[Tux3] Tux3 kernel port - stupid semaphore tricks

Daniel Phillips phillips at phunq.net
Fri Sep 19 07:10:54 PDT 2008


Here is a slightly different style of handling a bio completion that
uses a semaphore instead of a wait queue:

static void read_endio(struct bio *bio, int err)
{
	struct semaphore *sem = bio->bi_private;
	bio_put(bio);
	up(sem);
}

static int junkfs_fill_super(struct super_block *sb, void *data, int silent)
{
	__DECLARE_SEMAPHORE_GENERIC(sem, 0);
	struct bio *bio;
	int i;
	u8 *buf;


	if (IS_ERR(bio = bio_alloc(GFP_KERNEL, 1)))
		return PTR_ERR(bio);

	if (!(buf = kmalloc(SB_SIZE, GFP_KERNEL))) {
		bio_put(bio);
		return -ENOMEM;
	};
	bio->bi_io_vec[bio->bi_vcnt] = (struct bio_vec){
		.bv_page = virt_to_page(buf),
		.bv_offset = offset_in_page(buf),
		.bv_len = SB_SIZE };
	bio->bi_bdev = sb->s_bdev;
	bio->bi_sector = 0;
	bio->bi_size = SB_SIZE;
	bio->bi_vcnt = 1;
	bio->bi_end_io = read_endio;
	bio->bi_private = &sem;
	submit_bio(READ, bio);
	down(&sem);
	printk("super = ");
	for(i = 0; i < 16; i++)
		printk(" %02X", buf[i]);
	printk("\n");
	kfree(buf);
	return 0;
}

Note that I simply ignore the error from the bio here, which is not
right.  We actually do need to put a pointer to something more than
just the semaphore in the bio private field.  I just thought I would
write it as above for fun.  Well the fun is done, and the error var
goes back in before anything like this goes to production.

Note how we lost the state flag that is needed for non-racy waiting
on a wait queue (wait_event).  The semaphore count takes the place
of the state flag, and the semaphore has its own wait list, plus fancy
code in "down" to wait on the semaphore state.  (Not at all like the
wait queue code, it's worth taking a look at.)

For a one-off task like this, any efficiency difference between the
wait_event style and the semaphore technqiue does not matter at all.
The semaphore style is shorter, with one less state variable to get
wrong.

Regards,

Daniel

_______________________________________________
Tux3 mailing list
Tux3 at tux3.org
http://tux3.org/cgi-bin/mailman/listinfo/tux3



More information about the Tux3 mailing list