Skip to contentSkip to conversation

[Bcache v13 00/16]

PATCH NAK Kent Overstreet 10 participants 87 messages May 10, 2012 – Jun 1, 2012 1 message not in the archive Page 2 of 2

Subsystems (17)
lore
Share & tools
lore
#69 lore raw

Re: [Bcache v13 14/16] bcache: Request, io and allocation code

In reply to Tejun Heo
Quoted 9 lines · Tejun Heo

Hello, Kent.

I followed the control from cached_dev_make_request() this time.

Quoted 2 lines · Kent Overstreet

+ * Since the gens and priorities are all stored contiguously on disk, we can
+ * batch this up: We fill up the free_inc list with freshly invalidated buckets,

What does "inc" in free_inc stand for?

Incoming:

drivers/md/bcache/bcache.h +19 -6
index b20c49b..8ce9758 100644
@@ -342,6 +342,25 @@ struct cache {
 	 */
 	atomic_t		prio_written;
 
+	/*
+	 * free: Buckets that are ready to be used
+	 *
+	 * free_inc: Incoming buckets - these are buckets that currently have
+	 * cached data in them, and we can't reuse them until after we write
+	 * their new gen to disk. After prio_write() finishes writing the new
+	 * gens/prios, they'll be moved to the free list (and possibly discarded
+	 * in the process)
+	 *
+	 * unused: GC found nothing pointing into these buckets (possibly
+	 * because all the data they contained was overwritten), so we only
+	 * need to discard them before they can be moved to the free list.
+	 */
+	DECLARE_FIFO(long, free);
+	DECLARE_FIFO(long, free_inc);
+	DECLARE_FIFO(long, unused);
+
+	size_t			fifo_last_bucket;
+
 	/* Allocation stuff: */
 	struct bucket		*buckets;
 
@@ -360,12 +379,6 @@ struct cache {
 	 */
 	unsigned		invalidate_needs_gc:1;
 
-	size_t			fifo_last_bucket;
-
-	DECLARE_FIFO(long, free);
-	DECLARE_FIFO(long, free_inc);
-	DECLARE_FIFO(long, unused);
-
 	bool			discard; /* Get rid of? */
 	struct list_head	discards;
 	struct page		*discard_page;
Quoted 17 lines
Quoted 7 lines
(quoted diff) +6 -0
+static void discard_finish(struct work_struct *w)
+{
+	struct discard *d = container_of(w, struct discard, work);
+	struct cache *c = d->c;
+	char buf[BDEVNAME_SIZE];
+	bool run = false;

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+	if (!test_bit(BIO_UPTODATE, &d->bio.bi_flags)) {
+		printk(KERN_NOTICE "bcache: discard error on %s, disabling\n",
+		       bdevname(c->bdev, buf));
+		d->c->discard = 0;
+	}
+
+	mutex_lock(&c->set->bucket_lock);
+	if (fifo_empty(&c->free) ||
+	    fifo_used(&c->free) == 8)

Oh, ugh. That isn't even right - at _least_ the second check should be fifo_used() >= 8, not ==. It should probably be deleted entirely and just always do the wakeup, but the allocation code is prone to spinning and burning 100% cpu if stuff like that is wrong - I'll have to test it carefully.

Quoted 3 lines

I'm getting scared of the number 8. What does this mean? Is it the new 666? Oh, now I think about it, it's 2^3 thus 2*2*2. It's 3 of 2s. I think I can see the connection now. Oh devil!

It's a reserve, for btree bucket allocation - enough buckets for a btree split to succeed and for garbage collection to get some work done.

I have code in my copying gc branch that gets rid of that magic number - copying gc requires another reserve, and there's yet another reserve for writing priorities - the new code consolidates all that.

Quoted 10 lines

Review

Quoted 8 lines
(quoted diff) +7 -0
+		run = true;
+
+	fifo_push(&c->free, d->bucket);
+
+	list_add(&d->list, &c->discards);
+
+	do_discard(c);

So, this chains discard issuing. Wouldn't some explanation be nice?

Yeah. Does this help?

drivers/md/bcache/bcache.h +7 -0
index 8ce9758..ccf4060 100644
@@ -380,6 +380,13 @@ struct cache {
 	unsigned		invalidate_needs_gc:1;
 
 	bool			discard; /* Get rid of? */
+
+	/*
+	 * We preallocate structs for issuing discards to buckets, and keep them
+	 * on this list when they're not in use; do_discard() issues discards
+	 * whenever there's work to do and is called by free_some_buckets() and
+	 * when a discard finishes.
+	 */
 	struct list_head	discards;
 	struct page		*discard_page;
 
Quoted 13 lines
Quoted 13 lines
(quoted diff) +12 -0
+	mutex_unlock(&c->set->bucket_lock);
+
+	if (run)
+		closure_wake_up(&c->set->bucket_wait);
+
+	closure_put(&c->set->cl);
+}
+
+static void discard_endio(struct bio *bio, int error)
+{
+	struct discard *d = container_of(bio, struct discard, bio);
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+	PREPARE_WORK(&d->work, discard_finish);
+	schedule_work(&d->work);
+}

Why is a work item used here? Why not closure? What's the difference? This pattern of bouncing completion processing to process context is also something common in bio sequencing. I keep thinking what we want is bio sequencer.

That's a good question, I hadn't quite thought about explaining closures from that angle.

The main thing about closures, and the thing that separates them from a lot of other existing constructs is they have a well defined lifetime. That's IMO kind of natural if you think of a closure as a refcount on steroids, and it's very useful - it's why the parent makes sense (and using that well is what made a lot of tricky refcounting and other issues go away).

The end result - the way I think about it, anyways - is that closures are more threadlike and work_structs make more sense in the context of state machines.

Anyways, from that angle it probably would make sense to use closures here - the discard has a well defined lifetime, and it holds a refcount on the cache_set while it exists (i.e. the cache_set would be the parent closure).

I thought about it a bit when I originally wrote that code, and IIRC I ended up not using closures just because it wasn't necessary and wouldn't have made the code any smaller - the discard itself doesn't need a refcount for anything.

But I've also been trying to get rid of bare closure_puts() wherever reasonably possible - the idea being that things are more consistent and harder to screw up if closure_put() is only ever called on something that code logically owns (e.g. how it's used in most of the endio functions). Switching it to use a closure instead of a work_struct would mean the closure_put() on the cache_set's closure would go away, it would instead be done by the final closure_return().

Quoted 6 lines
Quoted 6 lines
(quoted diff) +6 -0
+
+static void discard_work(struct work_struct *w)
+{
+	struct discard *d = container_of(w, struct discard, work);
+	submit_bio(0, &d->bio);
+}
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+
+static void do_discard(struct cache *c)
+{
+	struct request_queue *q = bdev_get_queue(c->bdev);
+	int s = q->limits.logical_block_size;
+

Prolly can use lockdep_assert_held().

Yeah, good idea.

Quoted 9 lines

Review

Quoted 5 lines
(quoted diff) +4 -0
+	while (c->discard &&
+	       !atomic_read(&c->set->closing) &&
+	       !list_empty(&c->discards) &&
+	       fifo_free(&c->free) >= 8) {

What's the magic 8? Is this 8 someway related to other 8s in this file? How is one supposed to know what they mean or the rationale behind it?

This one is making sure there'll be room to stick the bucket on the free list - the 8 is the maximum number of discards that could be in flight.

I'm fixing that now. Didn't realize how many bare 8s there were in this file that meant different things.

Quoted 45 lines
Quoted 35 lines
(quoted diff) +34 -0
+		struct discard *d = list_first_entry(&c->discards,
+						     struct discard, list);
+
+		d->bucket = pop_freed(c);
+		if (d->bucket == -1)
+			break;
+
+		list_del(&d->list);
+		closure_get(&c->set->cl);
+
+		bio_init(&d->bio);
+		memset(&d->bv, 0, sizeof(struct bio_vec));
+		bio_set_prio(&d->bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
+
+		d->bio.bi_sector	= bucket_to_sector(c->set, d->bucket);
+		d->bio.bi_bdev		= c->bdev;
+		d->bio.bi_rw		= REQ_WRITE|(1 << BIO_RW_DISCARD);
+		d->bio.bi_max_vecs	= 1;
+		d->bio.bi_io_vec	= d->bio.bi_inline_vecs;
+		d->bio.bi_end_io	= discard_endio;
+
+		if (bio_add_pc_page(q, &d->bio, c->discard_page, s, 0) < s) {
+			printk(KERN_DEBUG "bcache: bio_add_pc_page failed\n");
+			c->discard = 0;
+			fifo_push(&c->free, d->bucket);
+			list_add(&d->list, &c->discards);
+			break;
+		}
+
+		d->bio.bi_size = bucket_bytes(c);
+
+		schedule_work(&d->work);
+	}
+}

...

Quoted 9 lines
(quoted diff) +9 -0
+int alloc_discards(struct cache *ca)
+{
+	for (int i = 0; i < 8; i++) {
+		struct discard *d = kzalloc(sizeof(*d), GFP_KERNEL);
+		if (!d)
+			return -ENOMEM;
+
+		d->c = ca;
+		INIT_WORK(&d->work, discard_work);
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+		list_add(&d->list, &ca->discards);
+	}
+
+	return 0;
+}

Why maintain separate pool of discards? It it to throttle discard commands? And another evil number!

Yeah, it's just a mempool that also throttles. I don't particularly care for doing it that way, any suggestions? (Just fixed the magic number, at least).

Quoted 9 lines

Review

Quoted 7 lines
(quoted diff) +6 -0
+static bool can_invalidate_bucket(struct cache *c, struct bucket *b)
+{
+	return b->mark >= 0 &&
+		!atomic_read(&b->pin) &&
+		bucket_gc_gen(b) < 96U &&
+		bucket_disk_gen(b) < 64U;

Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

b->mark >= 0 is pretty terrible (and it's also something fixed in my copy gc branch, heh).

In this code if mark is >= 0 it means there's only clean cached data in this bucket (the values for btree data and dirty data are negative), and if it's positive it's also the number of sectors gc found in this bucket (so that invalidate_buckets_lru() can preferentially invalidate buckets with less data in them).

The latest code splits out mark and sectors_used.

The !atomic_read() should be fairly self explanatory. I'm going to get rid of the per bucket refcount eventually, right now it's just used when we allocate a bucket so we can ensure it's not garbage collected until we insert a pointer to it into the btree.

bucket_gc_gen(), bucket_disk_gen() are the differences between the bucket's gen and the oldest gen in the btree (gc gen), and the gen on disk - those checks ensure the gen doesn't wrap around.

This improve things?

drivers/md/bcache/alloc.c +10 -6
index c37f73f..eb44b1d 100644
@@ -74,11 +74,11 @@ uint8_t inc_gen(struct cache *c, struct bucket *b)
 	uint8_t ret = ++b->gen;
 
 	c->set->need_gc = max(c->set->need_gc, bucket_gc_gen(b));
-	BUG_ON(c->set->need_gc > 97);
+	WARN_ON_ONCE(c->set->need_gc > BUCKET_GC_GEN_MAX);
 
 	if (CACHE_SYNC(&c->set->sb)) {
 		c->need_save_prio = max(c->need_save_prio, bucket_disk_gen(b));
-		BUG_ON(c->need_save_prio > 96);
+		WARN_ON_ONCE(c->need_save_prio > BUCKET_DISK_GEN_MAX);
 	}
 
 	return ret;
@@ -263,6 +263,12 @@ int alloc_discards(struct cache *ca)
 
 /* Allocation */
 
+static inline bool can_inc_bucket_gen(struct bucket *b)
+{
+	return bucket_gc_gen(b) < BUCKET_GC_GEN_MAX &&
+		bucket_disk_gen(b) < BUCKET_DISK_GEN_MAX;
+}
+
 bool bucket_add_unused(struct cache *c, struct bucket *b)
 {
 	if (c->prio_alloc == prio_buckets(c) &&
@@ -271,8 +277,7 @@ bool bucket_add_unused(struct cache *c, struct bucket *b)
 
 	b->prio = 0;
 
-	if (bucket_gc_gen(b) < 96U &&
-	    bucket_disk_gen(b) < 64U &&
+	if (can_inc_bucket_gen(b) &&
 	    fifo_push(&c->unused, b - c->buckets)) {
 		atomic_inc(&b->pin);
 		return true;
@@ -285,8 +290,7 @@ static bool can_invalidate_bucket(struct cache *c, struct bucket *b)
 {
 	return b->mark >= 0 &&
 		!atomic_read(&b->pin) &&
-		bucket_gc_gen(b) < 96U &&
-		bucket_disk_gen(b) < 64U;
+		can_inc_bucket_gen(b);
 }
 
 static void invalidate_one_bucket(struct cache *c, struct bucket *b)
drivers/md/bcache/bcache.h +20 -2
index ccf4060..f505168 100644
@@ -821,8 +821,26 @@ static inline bool cached_dev_get(struct cached_dev *d)
 	return true;
 }
 
-#define bucket_gc_gen(b)	((uint8_t) ((b)->gen - (b)->last_gc))
-#define bucket_disk_gen(b)	((uint8_t) ((b)->gen - (b)->disk_gen))
+/*
+ * bucket_gc_gen() returns the difference between the bucket's current gen and
+ * the oldest gen of any pointer into that bucket in the btree (last_gc).
+ *
+ * bucket_disk_gen() returns the difference between the current gen and the gen
+ * on disk; they're both used to make sure gens don't wrap around.
+ */
+
+static inline uint8_t bucket_gc_gen(struct bucket *b)
+{
+	return b->gen - b->last_gc;
+}
+
+static inline uint8_t bucket_disk_gen(struct bucket *b)
+{
+	return b->gen - b->disk_gc;
+}
+
+#define BUCKET_GC_GEN_MAX	96U
+#define BUCKET_DISK_GEN_MAX	64U
 
 #define kobj_attribute_write(n, fn)					\
 	static struct kobj_attribute ksysfs_##n = __ATTR(n, S_IWUSR, NULL, fn)
Quoted 18 lines
Quoted 18 lines
(quoted diff) +17 -0
+static void invalidate_buckets_lru(struct cache *c)
+{
+	unsigned bucket_prio(struct bucket *b)
+	{
+		return ((unsigned) (b->prio - c->set->min_prio)) * b->mark;
+	}
+
+	bool bucket_max_cmp(struct bucket *l, struct bucket *r)
+	{
+		return bucket_prio(l) < bucket_prio(r);
+	}
+
+	bool bucket_min_cmp(struct bucket *l, struct bucket *r)
+	{
+		return bucket_prio(l) > bucket_prio(r);
+	}
+
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+	struct bucket *b;
+
+	c->heap.used = 0;
+
+	for_each_bucket(b, c) {

So, this iterates all buckets in the cache, right? Maybe it warrants cond_resched()?

This is probably on the order of ~1 ms but - it can't hurt, and I haven't actually measured it.

Quoted 43 lines
Quoted 43 lines
(quoted diff) +42 -0
+		if (!can_invalidate_bucket(c, b))
+			continue;
+
+		if (!b->mark) {
+			if (!bucket_add_unused(c, b))
+				return;
+		} else {
+			if (!heap_full(&c->heap))
+				heap_add(&c->heap, b, bucket_max_cmp);
+			else if (bucket_max_cmp(b, heap_peek(&c->heap))) {
+				c->heap.data[0] = b;
+				heap_sift(&c->heap, 0, bucket_max_cmp);
+			}
+		}
+	}
+
+	if (c->heap.used * 2 < c->heap.size)
+		bcache_queue_gc(c->set);
+
+	for (ssize_t i = c->heap.used / 2 - 1; i >= 0; --i)
+		heap_sift(&c->heap, i, bucket_min_cmp);
+
+	while (!fifo_full(&c->free_inc)) {
+		if (!heap_pop(&c->heap, b, bucket_min_cmp)) {
+			/* We don't want to be calling invalidate_buckets()
+			 * multiple times when it can't do anything
+			 */
+			c->invalidate_needs_gc = 1;
+			bcache_queue_gc(c->set);
+			return;
+		}
+
+		invalidate_one_bucket(c, b);
+	}
+}
+void free_some_buckets(struct cache *c)
+{
+	long r;
+
+	/*
+	 * XXX: do_discard(), prio_write() take refcounts on the cache set.  How
+	 * do we know that refcount is nonzero?
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+	 */
+
+	do_discard(c);
+
+	while (!fifo_full(&c->free) &&
+	       (fifo_used(&c->free) <= 8 ||

Ooh, devil!

I'm deleting that fifo_free() <= 8 check. The idea is that if we're under our reserve we'll skip the discard and just allocate the bucket immediately, but there's no real need for it and it's going to complicate things later.

Quoted 56 lines
Quoted 13 lines
(quoted diff) +12 -0
+		!c->discard) &&
+	       (r = pop_freed(c)) != -1)
+		fifo_push(&c->free, r);
+
+	while (c->prio_alloc != prio_buckets(c) &&
+	       fifo_pop(&c->free, r)) {
+		struct bucket *b = c->buckets + r;
+		c->prio_next[c->prio_alloc++] = r;
+
+		b->mark = GC_MARK_BTREE;
+		atomic_dec_bug(&b->pin);
+	}

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+	if (!CACHE_SYNC(&c->set->sb)) {
+		if (fifo_empty(&c->free_inc))
+			invalidate_buckets(c);
+		return;
+	}
+
+	/* XXX: tracepoint for when c->need_save_prio > 64 */
+
+	if (c->need_save_prio <= 64 &&

Ooh, devil * devil!

Quoted 17 lines
(quoted diff) +17 -0
+	    fifo_used(&c->unused) > c->unused.size / 2)
+		return;
+
+	if (atomic_read(&c->prio_written) > 0 &&
+	    (fifo_empty(&c->free_inc) ||
+	     c->need_save_prio > 64))
+		atomic_set(&c->prio_written, 0);
+
+	if (!can_save_prios(c))
+		return;
+
+	invalidate_buckets(c);
+
+	if (!fifo_empty(&c->free_inc) ||
+	    c->need_save_prio > 64)
+		prio_write(c);
+}

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+static long pop_bucket(struct cache *c, uint16_t priority, struct closure *cl)
+{
+	long r = -1;
+again:
+	free_some_buckets(c);
+
+	if ((priority == btree_prio ||
+	     fifo_used(&c->free) > 8) &&
+	    fifo_pop(&c->free, r)) {

This is unconventional and more difficult to read than

Quoted 5 lines
	if ((priority == btree_prio || fifo_used(&c->free) > 8) &&
	    fifo_pop(&c->free, r)) {

It harms readability by both being unnecessarily different and visually less distinguishible. Why do this?

I prefer extra linebreaks in complicated if statements as the indentation makes the way the parentheses group things clearer, but for this one I'm fine with your version.

This is again the btree reserve. I'm gonna see if I can pull the improved reserve code out of my copying gc branch (I haven't worked on it awhile and some of the code could use more testing).

Quoted 39 lines
Quoted 39 lines
(quoted diff) +38 -0
+		struct bucket *b = c->buckets + r;
+#ifdef CONFIG_BCACHE_EDEBUG
+		long i;
+		for (unsigned j = 0; j < prio_buckets(c); j++)
+			BUG_ON(c->prio_buckets[j] == (uint64_t) r);
+		for (unsigned j = 0; j < c->prio_alloc; j++)
+			BUG_ON(c->prio_next[j] == (uint64_t) r);
+
+		fifo_for_each(i, &c->free)
+			BUG_ON(i == r);
+		fifo_for_each(i, &c->free_inc)
+			BUG_ON(i == r);
+		fifo_for_each(i, &c->unused)
+			BUG_ON(i == r);
+#endif
+		BUG_ON(atomic_read(&b->pin) != 1);
+
+		b->prio = priority;
+		b->mark = priority == btree_prio
+			? GC_MARK_BTREE
+			: c->sb.bucket_size;
+		return r;
+	}
+
+	pr_debug("no free buckets, prio_written %i, blocked %i, "
+		 "free %zu, free_inc %zu, unused %zu",
+		 atomic_read(&c->prio_written),
+		 atomic_read(&c->set->prio_blocked), fifo_used(&c->free),
+		 fifo_used(&c->free_inc), fifo_used(&c->unused));
+
+	if (cl) {
+		if (closure_blocking(cl))
+			mutex_unlock(&c->set->bucket_lock);
+
+		closure_wait_event(&c->set->bucket_wait, cl,
+				   atomic_read(&c->prio_written) > 0 ||
+				   can_save_prios(c));
+
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+		if (closure_blocking(cl)) {
+			mutex_lock(&c->set->bucket_lock);
+			goto again;
+		}
+	}

How is this different from using @gfp_flags (for %__GFP_WAIT) or bool @may_block + -EAGAIN return?

It's not fundamentally different. The reason I originally added it was for the closure_wait_event() in get_bucket() - for cache lookups (i.e. handling a read, which at least starts out running under generic_make_request()) it's critical that the wait be asynchronous, but for insertions that code doesn't want to wait asynchronously (and drop locks). The closure_blocking() flag means that get_bucket() doesn't have to care, as long as it handles async sync will also work.

But I'm thinking it probably was a mistake and should be ripped out, in favor of some kind of explicit parameter like you suggest.

Quoted 45 lines
Quoted 44 lines
(quoted diff) +43 -0
+	return -1;
+}
+
+void unpop_bucket(struct cache_set *c, struct bkey *k)
+{
+	for (unsigned i = 0; i < KEY_PTRS(k); i++) {
+		struct bucket *b = PTR_BUCKET(c, k, i);
+
+		b->mark = 0;
+		bucket_add_unused(PTR_CACHE(c, k, i), b);
+	}
+}
+
+int __pop_bucket_set(struct cache_set *c, uint16_t prio,
+		     struct bkey *k, int n, struct closure *cl)
+{
+	lockdep_assert_held(&c->bucket_lock);
+	BUG_ON(!n || n > c->caches_loaded || n > 8);
+
+	k->header = KEY_HEADER(0, 0);
+
+	/* sort by free space/prio of oldest data in caches */
+
+	for (int i = 0; i < n; i++) {
+		struct cache *ca = c->cache_by_alloc[i];
+		long b = pop_bucket(ca, prio, cl);
+
+		if (b == -1)
+			goto err;
+
+		k->ptr[i] = PTR(ca->buckets[b].gen,
+				bucket_to_sector(c, b),
+				ca->sb.nr_this_dev);
+
+		SET_KEY_PTRS(k, i + 1);
+	}
+
+	return 0;
+err:
+	unpop_bucket(c, k);
+	__bkey_put(c, k);
+	return -1;
+}

...

Quoted 16 lines

Review

Quoted 11 lines
(quoted diff) +11 -0
+static void bio_invalidate(struct closure *cl)
+{
+	struct btree_op *op = container_of(cl, struct btree_op, cl);
+	struct search *s = container_of(op, struct search, op);
+	struct bio *bio = s->cache_bio;
+
+	pr_debug("invalidating %i sectors from %llu",
+		 bio_sectors(bio), (uint64_t) bio->bi_sector);
+
+	while (bio_sectors(bio)) {
+		unsigned len = min(bio_sectors(bio), 1U << 14);

New line missing. Again, I'm not gonna complain about this more but please follow the usual formatting. There are cases where deviating can be beneficial / tolerated but IMHO you're deviating way too often for no good reasons (well, they're not apparent to me anyway).

I'll argue about some of the newlines you consider extra but I won't argue about any missing newlines - fixed.

Quoted 16 lines
Quoted 15 lines
(quoted diff) +14 -0
+		if (keylist_realloc(&s->op.keys, 0, s->op.d->c))
+			goto out;
+
+		bio->bi_sector	+= len;
+		bio->bi_size	-= len << 9;
+
+		keylist_add(&s->op.keys,
+			    &KEY(s->op.d->id, bio->bi_sector, len));
+	}
+
+	s->bio_insert_done = true;
+out:
+	continue_at(cl, bcache_journal, bcache_wq);
+}

...

Quoted 9 lines

Review

Quoted 7 lines
(quoted diff) +7 -0
+static struct open_bucket *get_data_bucket(struct bkey *search,
+					   struct search *s)
+{
+	struct closure cl, *w = NULL;
+	struct cache_set *c = s->op.d->c;
+	struct open_bucket *l, *ret, *ret_task;
+

Unnecessary new line.

That one serves no purpose, fixed.

Quoted 3 lines

Review

Quoted 1 line
(quoted diff) +1 -0
+	BKEY_PADDED(key) alloc;

Why BKEY_PADDED()? What does it do? Can we not do this?

Just a bare struct bkey on the stack won't be big enough for any pointers.

I _suppose_ I could do something like:

struct bkey_padded alloc_pad;
struct bkey *alloc = &alloc_pad.key;

I like that marginally better. Any better ideas?

Quoted 12 lines
Quoted 12 lines
(quoted diff) +12 -0
+	struct bkey *k = NULL;
+
+	if (s->writeback) {
+		closure_init_stack(&cl);
+		w = &cl;
+	}
+again:
+	ret = ret_task = NULL;
+
+	spin_lock(&c->data_bucket_lock);
+	list_for_each_entry_reverse(l, &c->data_buckets, list)
+		if (!bkey_cmp(&l->key, search)) {
Quoted 8 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+			ret = l;
+			goto found;
+		} else if (l->last == s->task)
+			ret_task = l;

if () {
} else if () {
}

Wasn't aware of that convention when I wrote most of this code - fixed.

Quoted 5 lines

Also, it's better to always use braces in outer constructs if inner needs one.

And, it seems the bucket allocations follow the task. What's the benefit of doing so? Why isn't there any explanation?

drivers/md/bcache/request.c +22 -0
index 5e00e2b..16185ef 100644
@@ -322,6 +322,28 @@ static void put_data_bucket(struct open_bucket *b, struct cache_set *c,
 	spin_unlock(&c->data_bucket_lock);
 }
 
+/**
+ * get_data_bucket - pick out a bucket to write some data to, possibly
+ * allocating a new one.
+ *
+ * We keep multiple buckets open for writes, and try to segregate different
+ * write streams for better cache utilization: first we look for a bucket where
+ * the last write to it was sequential with the current write, and failing that
+ * we look for a bucket that was last used by the same task.
+ *
+ * The ideas is if you've got multiple tasks pulling data into the cache at the
+ * same time, you'll get better cache utilization if you try to segregate their
+ * data and preserve locality.
+ *
+ * For example, say you've starting Firefox at the same time you're copying a
+ * bunch of files. Firefox will likely end up being fairly hot and stay in the
+ * cache awhile, but the data you copied might not be; if you wrote all that
+ * data to the same buckets it'd get invalidated at the same time.
+ *
+ * Both of those tasks will be doing fairly random IO so we can't rely on
+ * detecting sequential IO to segregate their data, but going off of the task
+ * should be a sane heuristic.
+ */
 static struct open_bucket *get_data_bucket(struct bkey *search,
 					   struct search *s)
 {
Quoted 11 lines
Quoted 11 lines
(quoted diff) +10 -0
+
+	ret = ret_task ?: list_first_entry(&c->data_buckets,
+					   struct open_bucket, list);
+found:
+	if (!ret->sectors_free) {
+		if (!k) {
+			spin_unlock(&c->data_bucket_lock);
+			k = &alloc.key;
+
+			if (pop_bucket_set(c, initial_prio, k, 1, w))
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+				return NULL;
+
+			goto again;

So, this is "try-locked-first, on failure, unlock-alloc-retry" dancing. Constructs like this aren't too atypical but they still warrant short explanation. Please be nice to people trying to read your code.

drivers/md/bcache/request.c +10 -0
index 28f4ef4..20485b2 100644
@@ -357,6 +357,11 @@ static struct open_bucket *get_data_bucket(struct bkey *search,
 		closure_init_stack(&cl);
 		w = &cl;
 	}
+	/*
+	 * We might have to allocate a new bucket, which we can't do with a
+	 * spinlock held. So if we have to allocate, we drop the lock, allocate
+	 * and then retry.
+	 */
 again:
 	ret = ret_task = NULL;
 
@@ -393,6 +398,11 @@ found:
 			EBUG_ON(ptr_stale(c, &ret->key, i));
 	}
 
+	/*
+	 * If we had to allocate and then retry, we might discover that we raced
+	 * and no longer need to allocate. Therefore, if we allocated a bucket
+	 * but didn't use it, drop the refcount pop_bucket_set() took:
+	 */
 	if (k)
 		__bkey_put(c, k);
 
Quoted 17 lines
Quoted 17 lines
(quoted diff) +17 -0
+		}
+
+		bkey_copy(&ret->key, k);
+		k = NULL;
+
+		ret->sectors_free = c->sb.bucket_size;
+	} else
+		for (unsigned i = 0; i < KEY_PTRS(&ret->key); i++)
+			EBUG_ON(ptr_stale(c, &ret->key, i));
+
+	if (k)
+		__bkey_put(c, k);
+
+	if (w)
+		for (unsigned i = 0; i < KEY_PTRS(&ret->key); i++)
+			PTR_BUCKET(c, &ret->key, i)->mark = GC_MARK_DIRTY;
+
Quoted 8 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+	ret->last = s->task;
+	bkey_copy_key(&ret->key, search);
+
+	list_move_tail(&ret->list, &c->data_buckets);

This too. It's a rather common pattern and people would be able to just read through without thinking if it had one line comment saying something like /* @ret is hot now, put it at the head of queue */.

Done.

Quoted 11 lines
Quoted 3 lines
(quoted diff) +2 -0
+	return ret;
+}

...

Quoted 1 line

+static void bio_insert(struct closure *cl)

Too generic name. This and a lot of others. Note that there are issues other than direct compile time symbol collision - it makes the code difficult to grep for and stack traces difficult to decipher. I'm not gonna complain more about too generic names but please review the code and fix other instances too.

I'm pretty terrible at naming, so if at some point you could help me come up with names that are descriptive _to you_, it'd be a big help.

Quoted 5 lines

Another thing is that why this function and its friends take @cl when they always expect @cl contained inside search->op. Why not take @search instead? Using @cl is more dangerous and less readable. Why do it?

bio_insert() used to be the closure function, but after breaking out bio_insert_loop() that's no longer true - so yeah, it should've been changed.

I've also been trying to get rid of all of bio_insert()'s dependencies on struct search. Not quite done.

Quoted 16 lines
Quoted 15 lines
(quoted diff) +14 -0
+{
+	struct btree_op *op = container_of(cl, struct btree_op, cl);
+	struct search *s = container_of(op, struct search, op);
+	struct bio *bio = s->cache_bio;
+
+	if (!s->skip) {
+		bio->bi_end_io	= bio_insert_endio;
+		bio->bi_private = cl;
+		bio_get(bio);
+	}
+
+	keylist_init(&op->keys);
+	bio_insert_loop(cl);
+}

...

Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+static void __do_bio_hook(struct search *s)
+{
+	struct bio *bio = &s->bio.bio;
+	memcpy(bio, s->orig_bio, sizeof(struct bio));
+
+#ifdef CONFIG_DISKMON

Contamination.

Ugh, yep.

Quoted 15 lines
Quoted 15 lines
(quoted diff) +14 -0
+	bio->bi_flowid		= NULL;
+#endif
+	bio->bi_end_io		= request_endio;
+	bio->bi_private		= &s->cl;
+	bio->bi_destructor	= NULL;
+	atomic_set(&bio->bi_cnt, 3);
+}
+
+static struct search *do_bio_hook(struct bio *bio, struct bcache_device *d)
+{
+	struct bio_vec *bv;
+	struct search *s = mempool_alloc(d->c->search, GFP_NOIO);
+	memset(s, 0, offsetof(struct search, op.keys));
+
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+	__closure_init(&s->cl, NULL);
+	__closure_init(&s->op.cl, &s->cl);
+
+	s->op.d			= d;
+	s->op.lock		= -1;
+	s->task			= get_current();

Please use current instead of get_current().

Done.

Quoted 19 lines
Quoted 18 lines
(quoted diff) +17 -0
+	s->orig_bio		= bio;
+	s->write		= bio->bi_rw & REQ_WRITE;
+	s->op.flush_journal	= bio->bi_rw & REQ_FLUSH;
+	s->recoverable		= 1;
+	__do_bio_hook(s);
+
+	if (bio->bi_size != bio_segments(bio) * PAGE_SIZE) {
+		bv = mempool_alloc(d->unaligned_bvec, GFP_NOIO);
+		memcpy(bv, bio_iovec(bio),
+		       sizeof(struct bio_vec) * bio_segments(bio));
+
+		s->bio.bio.bi_io_vec	= bv;
+		s->unaligned_bvec	= 1;
+	}
+
+	return s;
+}

...

Quoted 12 lines

Review

Quoted 7 lines
(quoted diff) +7 -0
+static bool should_writeback(struct cached_dev *d, struct bio *bio)
+{
+	return !atomic_read(&d->disk.detaching) &&
+		cache_mode(d, bio) == CACHE_MODE_WRITEBACK &&
+		(d->disk.c->gc_stats.in_use < (bio->bi_rw & REQ_SYNC)
+		 ? CUTOFF_WRITEBACK_SYNC
+		 : CUTOFF_WRITEBACK);

The formatting of the CUTOFF_WRITEBACK* test is atrocious. It almost looks like it's trying to mislead the reader. For $DIETY's sake, use a local variable for the threshold value or split the condition into a few "if () return;" clauses.

I clearly have different tastes than you here (it parses easily to me), but the local variable for the threshold is a great idea - doing that.

Quoted 11 lines
Quoted 11 lines
(quoted diff) +10 -0
+}
+
+static void request_write_resubmit(struct closure *cl)
+{
+	struct btree_op *op = container_of(cl, struct btree_op, cl);
+	struct search *s = container_of(op, struct search, op);
+	struct bio *bio = &s->bio.bio;
+
+	closure_bio_submit(bio, &s->cl, op->d->c->bio_split);
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+	bio_insert(&s->op.cl);
+	continue_at(&s->cl, cached_dev_write_complete, NULL);
+}

I'm kinda turned off by closure here too. It doesn't really seem to simplify the actual painful points of async programming. The user still has to compose separate paths for sync and async paths. I keep thinking domain-specific sequencer would be much better.

Not really following your complaint. The resubmit path is required when allocating a bio split fails because we're running under generic_make_request() - it's ugly, but I'm not sure how you're going to make it any cleaner.

I need to rebase this code onto my block cleanup patch series, the patch to make generic_make_request() handle arbitrary sized bios makes this go away.

Quoted 18 lines
Quoted 18 lines
(quoted diff) +18 -0
+
+static void request_write(struct cached_dev *d, struct search *s)
+{
+	struct closure *cl = &s->cl;
+	struct bio *bio = &s->bio.bio;
+
+	check_should_skip(d, s);
+	down_read_non_owner(&d->writeback_lock);
+
+	if (bcache_in_writeback(d, bio->bi_sector, bio_sectors(bio))) {
+		s->skip		= false;
+		s->writeback	= true;
+	}
+
+	if (s->skip) {
+skip:		s->cache_bio = s->orig_bio;
+		bio_get(s->cache_bio);
+		trace_bcache_write_skip(s->orig_bio);
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+		if (bio->bi_rw & (1 << BIO_RW_DISCARD)) {

This isn't bcache's problem but it probably would be better to make block layer handle this in generic manner. blk_queue_discard() already indicates whether a queue supports discard or not. generic_make_request() can simply treat discards as no-op if unsupported.

Good idea (especially since a no-op is a valid implementation of trim).

Quoted 34 lines
Quoted 34 lines
(quoted diff) +33 -0
+			closure_get(cl);
+
+			if (blk_queue_discard(bdev_get_queue(d->bdev)))
+				generic_make_request(bio);
+			else
+				bio_endio(bio, 0);
+
+			goto out;
+		} else
+			goto submit;
+	}
+
+	if (should_writeback(d, s->orig_bio))
+		s->writeback = true;
+
+	if (!s->writeback) {
+		s->cache_bio = bbio_kmalloc(GFP_NOIO, bio->bi_max_vecs);
+		if (!s->cache_bio) {
+			s->skip = true;
+			goto skip;
+		}
+
+		__bio_clone(s->cache_bio, bio);
+		trace_bcache_writethrough(s->orig_bio);
+submit:
+		if (closure_bio_submit(bio, cl, s->op.d->c->bio_split))
+			continue_at(&s->op.cl,
+				    request_write_resubmit,
+				    bcache_wq);
+	} else {
+		s->cache_bio = bio;
+		trace_bcache_writeback(s->orig_bio);
+		bcache_writeback_add(d, bio_sectors(bio));
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+	}
+out:
+	bio_insert(&s->op.cl);
+	continue_at(cl, cached_dev_write_complete, NULL);
+}

I hate how gotos are being abused in this function. This ain't 80s and we don't build complex control flow using gotos.

It is a nasty piece of code (but 10x better than it used to be).

Quoted 7 lines

If common logic
is used in different parts of the control flow in a way that the usual control constructs don't really yield pretty code, factor out the common part into a function. Are you not doing that because you don't wanna put continue_at() inside another function which may obscure the closure control flow? If that's the case, I think it just shows how retarded wrapping return in macros is. :(

That is a major downside (that's one reason I liked your idea of returning an opaque cookie).

But making generic_make_request() handle arbitrary size bios is going to make a lot of the pain in this function go away (there'll only be a single continue_at() in request_write() after that) - with that and your discard idea the skip path boils down to almost nothing.

I'm just gonna rebase this code onto my block cleanup branch.

Quoted 11 lines

Review

Quoted 9 lines
(quoted diff) +8 -0
+static void cached_dev_make_request(struct request_queue *q, struct bio *bio)
+{
+	struct search *s;
+	struct bcache_device *d = bio->bi_bdev->bd_disk->private_data;
+	struct cached_dev *dc = container_of(d, struct cached_dev, disk);
+
+	bio->bi_bdev = dc->bdev;
+	bio->bi_sector += 16;
                         ^^^^
Quoted 6 lines

Please don't do this. Use of magic numbers seems pretty common throughout the code base. This is error-prone and cryptic. Use enums or macros (this is what macros are for, actually) to give them meaningful names. If applicable, explain why the specific number is chosen on constant definition. I assume this is the size of superblock but I can't ask cscope about it or grep for it.

Just added BDEV_DATA_START.

Quoted 15 lines

Review

Quoted 9 lines
(quoted diff) +8 -0
+
+	if (cached_dev_get(dc)) {
+		s = do_bio_hook(bio, d);
+		trace_bcache_request_start(&s->op, bio);
+
+		(!bio_has_data(bio)	? request_nodata :
+		 bio->bi_rw & REQ_WRITE ? request_write :
+					  request_read)(dc, s);

Don't do this. Among other things, it should be possible to search / grep for "FUNCTION_NAME(" and find all the direct invocations. Just use if/else. You're not gaining anything from doing things like the above while basically aggravating other developers trying to understand your code.

I don't buy the argument about finding direct invocations (tons of stuff is indirectly invoked today and i can't remember ever caring about direct invocations vs. calls via a pointer, and worse for grepping is all the set wrappers for things like merge_bvec_fn (it's inconsistent and what is this, C++?)

But I give up, changed it :P

#55 lore raw

Re: [Bcache v13 11/16] bcache: Core btree code

In reply to Tejun Heo
Quoted 7 lines · Tejun Heo

A couple more comments from this round of reading.

Review

Quoted 2 lines · Kent Overstreet
(quoted diff) +2 -0
+#define btree_prio		USHRT_MAX
+#define initial_prio		32768

Why are these in lower case?

No good reason. I'll change it.

Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+#define PTR_BUCKET(c, k, n)						\
+	(PTR_CACHE(c, k, n)->buckets + PTR_BUCKET_NR(c, k, n))

PTR_BUCKET(c, k, n)

Awesome. I don't know what type it takes or what each single character argument stands for.

Yeah, that should be an inline function, along with some others. Fixed - well, have to convert the rest of the code to the lowercase names:

Maybe ptr_bucket_idx() instead of ptr_bucket_nr()?

drivers/md/bcache/bcache.h +33 -7
index 1011a73..0617885 100644
@@ -717,15 +717,41 @@ PTR_FIELD(PTR_GEN,		0,  8)
 #define PTR(gen, offset, dev)						\
 	((((uint64_t) dev) << 51) | ((uint64_t) offset) << 8 | gen)
 
-#define sector_to_bucket(c, s)	((long) ((s) >> (c)->bucket_bits))
-#define bucket_to_sector(c, b)	(((sector_t) (b)) << (c)->bucket_bits)
-#define bucket_remainder(c, b)	((b) & ((c)->sb.bucket_size - 1))
+static inline size_t sector_to_bucket(struct cache_set *c, sector_t s)
+{
+	return s >> c->bucket_bits;
+}
+
+static inline sector_t bucket_to_sector(struct cache_set *c, size_t b)
+{
+	return ((sector_t) b) << c->bucket_bits;
+}
 
-#define PTR_CACHE(c, k, n)	((c)->cache[PTR_DEV(k, n)])
-#define PTR_BUCKET_NR(c, k, n)	sector_to_bucket(c, PTR_OFFSET(k, n))
+static inline sector_t bucket_remainder(struct cache_set *c, sector_t s)
+{
+	return s & (c->sb.bucket_size - 1);
+}
 
-#define PTR_BUCKET(c, k, n)						\
-	(PTR_CACHE(c, k, n)->buckets + PTR_BUCKET_NR(c, k, n))
+static inline struct cache *ptr_cache(struct cache_set *c,
+				      struct bkey *k,
+				      unsigned ptr)
+{
+	return c->cache[PTR_DEV(k, ptr)];
+}
+
+static inline size_t ptr_bucket_nr(struct cache_set *c,
+				   struct bkey *k,
+				   unsigned ptr)
+{
+	return sector_to_bucket(c, PTR_OFFSET(k, ptr));
+}
+
+static inline struct bucket *ptr_bucket(struct cache_set *c,
+					struct bkey *k,
+					unsigned ptr)
+{
+	return ptr_cache(c, k, ptr)->buckets + ptr_bucket_nr(c, k, ptr);
+}
 
 /* Btree key macros */
 
Quoted 10 lines

Review

Quoted 7 lines
(quoted diff) +6 -0
+static inline bool cached_dev_get(struct cached_dev *d)
+{
+	if (!atomic_inc_not_zero(&d->count))
+		return false;
+
+	smp_mb__after_atomic_inc();

What is this mb() paired with? Whenever using a mb, please specify what the mb is paired with.

super.c, cached_dev_attach():

	smp_wmb();
	/* d->c must be set before d->count != 0 */
	atomic_set(&d->count, 1);

I'm improving the comments.

Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+	return true;
+}

Thanks.

Signature · 1 line
tejun
#70 lore raw

Re: [Bcache v13 14/16] bcache: Request, io and allocation code

In reply to Kent Overstreet

Hey, Kent.

Quoted 18 lines · Kent Overstreet
Quoted 9 lines
Quoted 9 lines
(quoted diff) +9 -0
+int alloc_discards(struct cache *ca)
+{
+	for (int i = 0; i < 8; i++) {
+		struct discard *d = kzalloc(sizeof(*d), GFP_KERNEL);
+		if (!d)
+			return -ENOMEM;
+
+		d->c = ca;
+		INIT_WORK(&d->work, discard_work);
Quoted 8 lines

drivers/md/bcache/bcache.h static inline bool cached_dev_get(struct cached_dev *d) · line 840

Quoted 5 lines
drivers/md/bcache/bcache.h +5 -0
+		list_add(&d->list, &ca->discards);
+	}
+
+	return 0;
+}

Why maintain separate pool of discards? It it to throttle discard commands? And another evil number!

Quoted 3 lines

Yeah, it's just a mempool that also throttles. I don't particularly care for doing it that way, any suggestions? (Just fixed the magic number, at least).

I think the list is fine. I'm curious how the 8 was chosen tho and what are the implications of higher or lower number. If it's just a number you just liked and didn't cause any problem, that's fine too as long as it's explained as such.

Quoted 15 lines
Quoted 15 lines

Review

Quoted 9 lines
(quoted diff) +9 -0
+static long pop_bucket(struct cache *c, uint16_t priority, struct closure *cl)
+{
+	long r = -1;
+again:
+	free_some_buckets(c);
+
+	if ((priority == btree_prio ||
+	     fifo_used(&c->free) > 8) &&
+	    fifo_pop(&c->free, r)) {

This is unconventional and more difficult to read than

	if ((priority == btree_prio || fifo_used(&c->free) > 8) &&
	    fifo_pop(&c->free, r)) {
Quoted 6 lines
Quoted 2 lines

It harms readability by both being unnecessarily different and visually less distinguishible. Why do this?

I prefer extra linebreaks in complicated if statements as the indentation makes the way the parentheses group things clearer, but for this one I'm fine with your version.

Hmmm.... more on the subject of style conformance at the end.

Quoted 19 lines
Quoted 9 lines

Review

Quoted 7 lines
(quoted diff) +7 -0
+static struct open_bucket *get_data_bucket(struct bkey *search,
+					   struct search *s)
+{
+	struct closure cl, *w = NULL;
+	struct cache_set *c = s->op.d->c;
+	struct open_bucket *l, *ret, *ret_task;
+

Unnecessary new line.

That one serves no purpose, fixed.

Quoted 3 lines

Review

Quoted 1 line
(quoted diff) +1 -0
+	BKEY_PADDED(key) alloc;

Why BKEY_PADDED()? What does it do? Can we not do this?

Just a bare struct bkey on the stack won't be big enough for any pointers.

Quoted 6 lines

I _suppose_ I could do something like:

struct bkey_padded alloc_pad;
struct bkey *alloc = &alloc_pad.key;

I like that marginally better. Any better ideas?

Looks sane enough to me. Maybe just use padded_key.key directly?

Quoted 3 lines

+/**
+ * get_data_bucket - pick out a bucket to write some data to, possibly
+ * allocating a new one.

If you're gonna do /** comments, please also add arguments section. DocBook stuff may get unhappy.

Quoted 21 lines

+ * We keep multiple buckets open for writes, and try to segregate different
+ * write streams for better cache utilization: first we look for a bucket where
+ * the last write to it was sequential with the current write, and failing that
+ * we look for a bucket that was last used by the same task.
+ *
+ * The ideas is if you've got multiple tasks pulling data into the cache at the
+ * same time, you'll get better cache utilization if you try to segregate their
+ * data and preserve locality.
+ *
+ * For example, say you've starting Firefox at the same time you're copying a
+ * bunch of files. Firefox will likely end up being fairly hot and stay in the
+ * cache awhile, but the data you copied might not be; if you wrote all that
+ * data to the same buckets it'd get invalidated at the same time.
+ *
+ * Both of those tasks will be doing fairly random IO so we can't rely on
+ * detecting sequential IO to segregate their data, but going off of the task
+ * should be a sane heuristic.
+ */
static struct open_bucket *get_data_bucket(struct bkey *search,
struct search *s)
{

...

Quoted 10 lines
Quoted 7 lines
Quoted 1 line

+static void bio_insert(struct closure *cl)

Too generic name. This and a lot of others. Note that there are issues other than direct compile time symbol collision - it makes the code difficult to grep for and stack traces difficult to decipher. I'm not gonna complain more about too generic names but please review the code and fix other instances too.

I'm pretty terrible at naming, so if at some point you could help me come up with names that are descriptive _to you_, it'd be a big help.

The problem I'm having with names are two-fold.

* Name not descriptive enough. It doesn't have to be super verbose but something which people can look at and associate with its type and/or role would be great. e.g. instead of k, use key, d -> cdev, and so on.

* Generic names. bio_insert() belongs to block layer. Block layer may use it in the future and when one sees bio_insert(), it's natural for that person to assume that it's a block layer thing doing something with bio. As for better name, I'm not sure. Maybe just prefix it with bc_?

Note that this isn't a 100% strict rule. You can and people do get away with some generic names and many of them don't cause any problem over the lifetime of the code but it's just way too prevalent in this code. You can bend stuff only so much.

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
(quoted diff) +6 -0
+
+	if (cached_dev_get(dc)) {
+		s = do_bio_hook(bio, d);
+		trace_bcache_request_start(&s->op, bio);
+
+		(!bio_has_data(bio)	? request_nodata :
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		 bio->bi_rw & REQ_WRITE ? request_write :
+					  request_read)(dc, s);

Don't do this. Among other things, it should be possible to search / grep for "FUNCTION_NAME(" and find all the direct invocations. Just use if/else. You're not gaining anything from doing things like the above while basically aggravating other developers trying to understand your code.

Quoted 7 lines

I don't buy the argument about finding direct invocations (tons of stuff is indirectly invoked today and i can't remember ever caring about direct invocations vs. calls via a pointer, and worse for grepping is all the set wrappers for things like merge_bvec_fn (it's inconsistent and what is this, C++?)

But I give up, changed it :P

So, I don't know. I guess I might be too conservative but the followings are the points I want to make.

* These small style issues don't really matter one way or the other. They're mostly the matter or taste or preference after all. Most technical merits or shortcomings one perceives in this area tend to be highly subjective and marginal, and the overhead of being unusual tends to be way higher. So, my or your taste doesn't weight that much unless there actually are tangible technical merits which people can agree upon. I don't see that here (or in many other bcache oddities).

* These aren't hard and fast rules. There isn't one true fixed standard that everyone conforms to. There still are different styles and people adopt the ones they think are pretty. That's how it evolves, but it too is a problem of degree and you can bend only so far before people start complaining.

For example, here's a fictionalized process that I got irritated and felt generally hostile against the code base.

1. Reading code. Full of macros.

2. Reading macros. Single char arguments. Starting to get irritated.

3. Encountered closures. Still unsure what they mean. This one looks like a simple refcnt. Wonders what the hell is wrong with the usual refcnts. Maybe somehow this gets used differently somewhere else? Of course, no explanation.

4. While trying to follow the control flow, encounters a function with full of cryptic numbers with "different" formatting. No high level explanation or anything. Getting irritated.

5. Now in the lower half of the function, forgot how @d was being used. Pressed ctrl-s and then d to highlight the variable in the function. Ooh, pretty.

6. Saw the next function which seems static. Tries to look for the immediate caller by searching for FUNC_NAME( - hmmm... no match. Maybe it's called indirectly somehow. Looks for FUNC_NAME assignments / used as arguments. Find the function symbol buried in ?:.

7. kajga;wioegja;sdklbja; bkjhaw83ua;kdgjasl;dgjk aw;eig93ua;kgNACK NACK NACK NACK NACK

So, at least to me, you seem to be pushing unique style / concepts too far and I can't identify the technical merits of doing so. Code is to be read and worked together on by peer developers.

Thanks.

Signature · 1 line
tejun
maintainer
#74 lore raw

Re: [Bcache v13 14/16] bcache: Request, io and allocation code

In reply to Kent Overstreet

Hey, Kent.

Quoted 18 lines · Kent Overstreet
Quoted 9 lines
Quoted 9 lines
(quoted diff) +9 -0
+int alloc_discards(struct cache *ca)
+{
+	for (int i = 0; i < 8; i++) {
+		struct discard *d = kzalloc(sizeof(*d), GFP_KERNEL);
+		if (!d)
+			return -ENOMEM;
+
+		d->c = ca;
+		INIT_WORK(&d->work, discard_work);
Quoted 8 lines

drivers/md/bcache/bcache.h static inline bool cached_dev_get(struct cached_dev *d) · line 840

Quoted 5 lines
drivers/md/bcache/bcache.h +5 -0
+		list_add(&d->list, &ca->discards);
+	}
+
+	return 0;
+}

Why maintain separate pool of discards? It it to throttle discard commands? And another evil number!

Quoted 3 lines

Yeah, it's just a mempool that also throttles. I don't particularly care for doing it that way, any suggestions? (Just fixed the magic number, at least).

I think the list is fine. I'm curious how the 8 was chosen tho and what are the implications of higher or lower number. If it's just a number you just liked and didn't cause any problem, that's fine too as long as it's explained as such.

Quoted 15 lines
Quoted 15 lines

Review

Quoted 9 lines
(quoted diff) +9 -0
+static long pop_bucket(struct cache *c, uint16_t priority, struct closure *cl)
+{
+	long r = -1;
+again:
+	free_some_buckets(c);
+
+	if ((priority == btree_prio ||
+	     fifo_used(&c->free) > 8) &&
+	    fifo_pop(&c->free, r)) {

This is unconventional and more difficult to read than

	if ((priority == btree_prio || fifo_used(&c->free) > 8) &&
	    fifo_pop(&c->free, r)) {
Quoted 6 lines
Quoted 2 lines

It harms readability by both being unnecessarily different and visually less distinguishible. Why do this?

I prefer extra linebreaks in complicated if statements as the indentation makes the way the parentheses group things clearer, but for this one I'm fine with your version.

Hmmm.... more on the subject of style conformance at the end.

Quoted 19 lines
Quoted 9 lines

Review

Quoted 7 lines
(quoted diff) +7 -0
+static struct open_bucket *get_data_bucket(struct bkey *search,
+					   struct search *s)
+{
+	struct closure cl, *w = NULL;
+	struct cache_set *c = s->op.d->c;
+	struct open_bucket *l, *ret, *ret_task;
+

Unnecessary new line.

That one serves no purpose, fixed.

Quoted 3 lines

Review

Quoted 1 line
(quoted diff) +1 -0
+	BKEY_PADDED(key) alloc;

Why BKEY_PADDED()? What does it do? Can we not do this?

Just a bare struct bkey on the stack won't be big enough for any pointers.

Quoted 6 lines

I _suppose_ I could do something like:

struct bkey_padded alloc_pad;
struct bkey *alloc = &alloc_pad.key;

I like that marginally better. Any better ideas?

Looks sane enough to me. Maybe just use padded_key.key directly?

Quoted 3 lines

+/**
+ * get_data_bucket - pick out a bucket to write some data to, possibly
+ * allocating a new one.

If you're gonna do /** comments, please also add arguments section. DocBook stuff may get unhappy.

Quoted 21 lines

+ * We keep multiple buckets open for writes, and try to segregate different
+ * write streams for better cache utilization: first we look for a bucket where
+ * the last write to it was sequential with the current write, and failing that
+ * we look for a bucket that was last used by the same task.
+ *
+ * The ideas is if you've got multiple tasks pulling data into the cache at the
+ * same time, you'll get better cache utilization if you try to segregate their
+ * data and preserve locality.
+ *
+ * For example, say you've starting Firefox at the same time you're copying a
+ * bunch of files. Firefox will likely end up being fairly hot and stay in the
+ * cache awhile, but the data you copied might not be; if you wrote all that
+ * data to the same buckets it'd get invalidated at the same time.
+ *
+ * Both of those tasks will be doing fairly random IO so we can't rely on
+ * detecting sequential IO to segregate their data, but going off of the task
+ * should be a sane heuristic.
+ */
static struct open_bucket *get_data_bucket(struct bkey *search,
struct search *s)
{

...

Quoted 10 lines
Quoted 7 lines
Quoted 1 line

+static void bio_insert(struct closure *cl)

Too generic name. This and a lot of others. Note that there are issues other than direct compile time symbol collision - it makes the code difficult to grep for and stack traces difficult to decipher. I'm not gonna complain more about too generic names but please review the code and fix other instances too.

I'm pretty terrible at naming, so if at some point you could help me come up with names that are descriptive _to you_, it'd be a big help.

The problem I'm having with names are two-fold.

* Name not descriptive enough. It doesn't have to be super verbose but something which people can look at and associate with its type and/or role would be great. e.g. instead of k, use key, d -> cdev, and so on.

* Generic names. bio_insert() belongs to block layer. Block layer may use it in the future and when one sees bio_insert(), it's natural for that person to assume that it's a block layer thing doing something with bio. As for better name, I'm not sure. Maybe just prefix it with bc_?

Note that this isn't a 100% strict rule. You can and people do get away with some generic names and many of them don't cause any problem over the lifetime of the code but it's just way too prevalent in this code. You can bend stuff only so much.

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
(quoted diff) +6 -0
+
+	if (cached_dev_get(dc)) {
+		s = do_bio_hook(bio, d);
+		trace_bcache_request_start(&s->op, bio);
+
+		(!bio_has_data(bio)	? request_nodata :
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		 bio->bi_rw & REQ_WRITE ? request_write :
+					  request_read)(dc, s);

Don't do this. Among other things, it should be possible to search / grep for "FUNCTION_NAME(" and find all the direct invocations. Just use if/else. You're not gaining anything from doing things like the above while basically aggravating other developers trying to understand your code.

Quoted 7 lines

I don't buy the argument about finding direct invocations (tons of stuff is indirectly invoked today and i can't remember ever caring about direct invocations vs. calls via a pointer, and worse for grepping is all the set wrappers for things like merge_bvec_fn (it's inconsistent and what is this, C++?)

But I give up, changed it :P

So, I don't know. I guess I might be too conservative but the followings are the points I want to make.

* These small style issues don't really matter one way or the other. They're mostly the matter or taste or preference after all. Most technical merits or shortcomings one perceives in this area tend to be highly subjective and marginal, and the overhead of being unusual tends to be way higher. So, my or your taste doesn't weight that much unless there actually are tangible technical merits which people can agree upon. I don't see that here (or in many other bcache oddities).

* These aren't hard and fast rules. There isn't one true fixed standard that everyone conforms to. There still are different styles and people adopt the ones they think are pretty. That's how it evolves, but it too is a problem of degree and you can bend only so far before people start complaining.

For example, here's a fictionalized process that I got irritated and felt generally hostile against the code base.

1. Reading code. Full of macros.

2. Reading macros. Single char arguments. Starting to get irritated.

3. Encountered closures. Still unsure what they mean. This one looks like a simple refcnt. Wonders what the hell is wrong with the usual refcnts. Maybe somehow this gets used differently somewhere else? Of course, no explanation.

4. While trying to follow the control flow, encounters a function with full of cryptic numbers with "different" formatting. No high level explanation or anything. Getting irritated.

5. Now in the lower half of the function, forgot how @d was being used. Pressed ctrl-s and then d to highlight the variable in the function. Ooh, pretty.

6. Saw the next function which seems static. Tries to look for the immediate caller by searching for FUNC_NAME( - hmmm... no match. Maybe it's called indirectly somehow. Looks for FUNC_NAME assignments / used as arguments. Find the function symbol buried in ?:.

7. kajga;wioegja;sdklbja; bkjhaw83ua;kdgjasl;dgjk aw;eig93ua;kgNACK NACK NACK NACK NACK

So, at least to me, you seem to be pushing unique style / concepts too far and I can't identify the technical merits of doing so. Code is to be read and worked together on by peer developers.

Thanks.

Signature · 1 line
tejun
#71 lore raw

Re: [Bcache v13 14/16] bcache: Request, io and allocation code

In reply to Tejun Heo
Quoted 21 lines · Tejun Heo

Hey, Kent.

Quoted 18 lines · Kent Overstreet
Quoted 17 lines
Quoted 4 lines
(quoted diff) +4 -0
+int alloc_discards(struct cache *ca)
+{
+	for (int i = 0; i < 8; i++) {
+		struct discard *d = kzalloc(sizeof(*d), GFP_KERNEL);

Review

Quoted 10 lines
(quoted diff) +10 -0
+		if (!d)
+			return -ENOMEM;
+
+		d->c = ca;
+		INIT_WORK(&d->work, discard_work);
+		list_add(&d->list, &ca->discards);
+	}
+
+	return 0;
+}

Why maintain separate pool of discards? It it to throttle discard commands? And another evil number!

Quoted 8 lines
Quoted 3 lines

Yeah, it's just a mempool that also throttles. I don't particularly care for doing it that way, any suggestions? (Just fixed the magic number, at least).

I think the list is fine. I'm curious how the 8 was chosen tho and what are the implications of higher or lower number. If it's just a number you just liked and didn't cause any problem, that's fine too as long as it's explained as such.

Just that, it was pretty arbitrary. Might actually be worth testing with it set to 1-2 since it's an unqueued command in SATA, though.

Quoted 1 line

Looks sane enough to me. Maybe just use padded_key.key directly?

Well, that is the current situation with the stack allocated ones. I'll do something.

BKEY_PADDED() was originally for keys in other structs that needed padded, where the transparent union thing actually works. Are you against the macro in general or just for stack allocated keys?

Quoted 2 lines

If you're gonna do /** comments, please also add arguments section. DocBook stuff may get unhappy.

Whoops, will do.

Quoted 6 lines

The problem I'm having with names are two-fold.

* Name not descriptive enough. It doesn't have to be super verbose but something which people can look at and associate with its type and/or role would be great. e.g. instead of k, use key, d -> cdev, and so on.

Some of those I'm not sure would be improved by expanding them - k -> key mainly, key is still fairly generic but also k for a struct bkey is used all over the place and fairly consistently (if I find k used for anything else, I'll fix it).

I kind of dislike any-single-letter + dev, mainly because dev is used all over the place and can mean damn near anything. (There's struct device which is commonly referred to as dev, there's struct bdev, and I'm pretty sure I could come up with more in a minute or two).

I would like more descriptive/unique variable names for cache, cache_set, bcache_device and cached_dev, I'm just not coming up with anything that's reasonably terse and seems to me like an improvement.

(I'm not really against cdev, it's just that bcache_device should then be bdev by analogy and that's taken... argh).

Anyways, I'm not really attached to the current variable names like I am some of the style issues, I just can't come up with anything I like.

Quoted 5 lines

* Generic names. bio_insert() belongs to block layer. Block layer may use it in the future and when one sees bio_insert(), it's natural for that person to assume that it's a block layer thing doing something with bio. As for better name, I'm not sure. Maybe just prefix it with bc_?

Agreed on bio_insert() (there's a fair number of functions that I've been meaning to rename for similarish reasons - get_bucket() and pop_bucket() don't have anything to do with each other, for example).

I think the function names are easier to improve than variabe names, though. The main obstacle (for me) to renaming stuff is that when I do I want to come up with names that are patterned on the relationships in the code, and that'll take some work.

Quoted 4 lines

Note that this isn't a 100% strict rule. You can and people do get away with some generic names and many of them don't cause any problem over the lifetime of the code but it's just way too prevalent in this code. You can bend stuff only so much.

I'm really not arguing with you about the naming. It's just been neglected for way too long.

Quoted 26 lines

So, I don't know. I guess I might be too conservative but the followings are the points I want to make.

* These small style issues don't really matter one way or the other. They're mostly the matter or taste or preference after all. Most technical merits or shortcomings one perceives in this area tend to be highly subjective and marginal, and the overhead of being unusual tends to be way higher. So, my or your taste doesn't weight that much unless there actually are tangible technical merits which people can agree upon. I don't see that here (or in many other bcache oddities).

* These aren't hard and fast rules. There isn't one true fixed standard that everyone conforms to. There still are different styles and people adopt the ones they think are pretty. That's how it evolves, but it too is a problem of degree and you can bend only so far before people start complaining.

For example, here's a fictionalized process that I got irritated and felt generally hostile against the code base.

1. Reading code. Full of macros.

2. Reading macros. Single char arguments. Starting to get irritated.

Quoted 8 lines

3. Encountered closures. Still unsure what they mean. This one looks like a simple refcnt. Wonders what the hell is wrong with the usual refcnts. Maybe somehow this gets used differently somewhere else? Of course, no explanation.

4. While trying to follow the control flow, encounters a function with full of cryptic numbers with "different" formatting. No high level explanation or anything. Getting irritated.

Which function was that?

Quoted 10 lines

5. Now in the lower half of the function, forgot how @d was being used. Pressed ctrl-s and then d to highlight the variable in the function. Ooh, pretty.

6. Saw the next function which seems static. Tries to look for the immediate caller by searching for FUNC_NAME( - hmmm... no match. Maybe it's called indirectly somehow. Looks for FUNC_NAME assignments / used as arguments. Find the function symbol buried in ?:.

Quoted 6 lines

7. kajga;wioegja;sdklbja; bkjhaw83ua;kdgjasl;dgjk aw;eig93ua;kgNACK NACK NACK NACK NACK

So, at least to me, you seem to be pushing unique style / concepts too far and I can't identify the technical merits of doing so. Code is to be read and worked together on by peer developers.

Well, there are a lot of style issues I'm happy to give on.

I think also I haven't been explicit about it but I do try to differentiate between style issues that are of no consequence (whoever feels more strongly about those can decide, for all I care) and things that make the codebase harder to read and understand.

Hell, I've never pretended to be any good at writing code that's understandable by others. There's things I _am_ good at - writing fast code, writing complex asynchronous code that _reliably works_ - but understandable code? Hell no.

(And I know I said I'd be writing design level documentation... I haven't forgotten, it's just been busy).

Anyways, there's huge room for improvement in bcache in that respect and while it's not going to happen overnight I am trying to steadily chip away at it, and while I certainly understand your frustration in reading the code it's not wasted.

That said, it does bug me when things are rejected out of hand merely for being different and foreign.

Closures being the main example - I'd be more receptive to criticism if I'd seen a half decent solution before, or if you or anyone else was actually trying to come up with something better.

I'd really like to see what you come up with if you implement that bio sequencer you've been talking about, because either you'll come up with something better or you'll have a better understanding of the problems I was trying to solve.

But, the thing about pushing a single purpose solution is - you might as well tell the person who first invented the red-black tree to come back with a simpler, single purpose solution to whatever he was working on.

If you want to tell me my sorted data structure/asynchronous programming model is crap and should be done _better_, that's completely different. I know closures could be improved, anyways.

But the previous tools for writing this kind of asynchronous code _sucked_, and I can trivially do things that were near impossible before, and my code is considerably more flexible and easier to work with than it was before. So if you want to convince me there's a better way to do what I'm doing - there is a genuinely high bar there.

maintainer
#72 lore raw

Re: [Bcache v13 14/16] bcache: Request, io and allocation code

Hello, Kent.

Quoted 3 lines · Kent Overstreet

BKEY_PADDED() was originally for keys in other structs that needed padded, where the transparent union thing actually works. Are you against the macro in general or just for stack allocated keys?

Macro in general. If it needs an extra union / struct member deref, so be it. No need to be smart for things like this.

Quoted 9 lines

I would like more descriptive/unique variable names for cache, cache_set, bcache_device and cached_dev, I'm just not coming up with anything that's reasonably terse and seems to me like an improvement.

(I'm not really against cdev, it's just that bcache_device should then be bdev by analogy and that's taken... argh).

Anyways, I'm not really attached to the current variable names like I am some of the style issues, I just can't come up with anything I like.

Heh, yeah, naming isn't easy. In most cases, it just has to be something consistent which has some association tho.

Quoted 6 lines
Quoted 5 lines

* Generic names. bio_insert() belongs to block layer. Block layer may use it in the future and when one sees bio_insert(), it's natural for that person to assume that it's a block layer thing doing something with bio. As for better name, I'm not sure. Maybe just prefix it with bc_?

Quoted 8 lines

Agreed on bio_insert() (there's a fair number of functions that I've been meaning to rename for similarish reasons - get_bucket() and pop_bucket() don't have anything to do with each other, for example).

I think the function names are easier to improve than variabe names, though. The main obstacle (for me) to renaming stuff is that when I do I want to come up with names that are patterned on the relationships in the code, and that'll take some work.

It doesn't have to be perfect. Naming schemes like anything else tend to lose consistency over time anyway, so something good enough is usually good enough.

Quoted 19 lines
Quoted 19 lines

* These aren't hard and fast rules. There isn't one true fixed standard that everyone conforms to. There still are different styles and people adopt the ones they think are pretty. That's how it evolves, but it too is a problem of degree and you can bend only so far before people start complaining.

For example, here's a fictionalized process that I got irritated and felt generally hostile against the code base.

1. Reading code. Full of macros.

2. Reading macros. Single char arguments. Starting to get irritated.

3. Encountered closures. Still unsure what they mean. This one looks like a simple refcnt. Wonders what the hell is wrong with the usual refcnts. Maybe somehow this gets used differently somewhere else? Of course, no explanation.

Quoted 5 lines
Quoted 3 lines

4. While trying to follow the control flow, encounters a function with full of cryptic numbers with "different" formatting. No high level explanation or anything. Getting irritated.

Which function was that?

Heh, this was dramatized for maximum effect. I was thinking about the condition check functions / macros with hard-coded constants.

...

Quoted 9 lines

I think also I haven't been explicit about it but I do try to differentiate between style issues that are of no consequence (whoever feels more strongly about those can decide, for all I care) and things that make the codebase harder to read and understand.

Hell, I've never pretended to be any good at writing code that's understandable by others. There's things I _am_ good at - writing fast code, writing complex asynchronous code that _reliably works_ - but understandable code? Hell no.

I don't think your style is inferior or anything. It's just different from the one used in the kernel. I don't think it's anything difficult either. It's just a matter of habit.

...

Quoted 11 lines

That said, it does bug me when things are rejected out of hand merely for being different and foreign.

Closures being the main example - I'd be more receptive to criticism if I'd seen a half decent solution before, or if you or anyone else was actually trying to come up with something better.

I'd really like to see what you come up with if you implement that bio sequencer you've been talking about, because either you'll come up with something better or you'll have a better understanding of the problems I was trying to solve.

I still don't understand what's being made better by closure. At least the ones I've seen didn't seem to be justified, so if you have some examples which highlight the benefits of closure, please go ahead and explain them.

I'll write more about it later but here are some of my current thoughts.

* I personally think async (using something other than stack for execution state) programming inherently sucks, no matter how it's done. The programming language and even the processor we use assume that stack is used to track execution context after all. My opinion about async programming can essentially be summarized as "avoid it as much as possible".

* This itself may be too abstract but excess is often worse than lack, especially for abstraction and design. Problems caused by excess is much more difficult to rectify as the problems are intentional and systematic. That's the part I dislike the most about kobject and friends.

* I don't (yet anyway) believe that you have something drastically better in closure. You just have something very different and maybe a bit more convenient. Both async and refcnting are well known problems with established patterns.

In a sense, I think it's similar to the style argument although at a higher level. I don't think the amount of benefit justifies the amount of deviation.

So, at least to me, the bar for highly abstract refcnty async thingy is pretty high. It's a ugly problem and I'd prefer to leave it ugly and painful unless it can be drastically better.

Thanks.

Signature · 1 line
tejun
maintainer
#73 lore raw

Re: [Bcache v13 14/16] bcache: Request, io and allocation code

Hello, again, Kent.

Quoted 7 lines · Tejun Heo

I still don't understand what's being made better by closure. At least the ones I've seen didn't seem to be justified, so if you have some examples which highlight the benefits of closure, please go ahead and explain them.

I'll write more about it later but here are some of my current thoughts.

I'm gonna try my (personal, of course) reasoning on closure. It's gonna be long-winded and fairly abstract. The issue at hand is an abstract one and I don't know how to communicate it better. :(

My objection to closure is largely two-fold.

1. Excessive abstraction / mosaicing of functions.

Abstraction itself isn't a goal onto itself - it is a (pretty important) tool that we rely on to manage complexities. By the very nature, it's heavily dependent on what concepts one develops on the subjct and those concepts may grow substantially removed from the concrete requirements and functionality, and as they get further removed from the concrete, different people tend to arrive at conclusions vastly far apart. One man's paradise can easily be another's hell. Concepts clear to one mind can be completely ambiguous or disturbing to others.

It's a problem with no fast solution but IMHO trying to minimize the distance between the needed functionality (requirements) and the abstraction. You brought up RB tree earlier in the discussion and that's a great example. It provides a clear functionality of balanced search tree without much extra abstracting. Most software developers can agree on the need of searching an element based on a key value and RB tree implements that specific functionality. If one understands the need, the abstraction is fundamental and immediate and thus self-evident.

One effective way of reaching at a bad abstraction, I think, is overly generalizing limited local usage patterns. When one sees certain pattern repeated, it's tempting to overly generalize and make it some fundamental abstraction when the only things which actually exist are local usage patterns.

Such over-generalization often ends up bundling things which aren't fundamentally associated. After all, there aren't clear fundamental requirements such an abstraction is serving - it is a mosaic of incidental set of features which happen to be in use for the specific part of code. Generalized ambiguity can be very generous - combining A and B resulted in this awesome generic super construct, adding C on top would woule make it super-duper, right?

This harms both the local usage and the code base in general. Local code develops unnecessary (generic things tend to have lives of their own) distance between the actual requirements and the mechanism implementing them making it more difficult to understand, and the rest of code base gets something which seems generic but is ambiguos, difficult to understand and easy to misuse.

I personally think kobject is a good example of this. Its name seems to suggest it's something like the base type for kernel objects. Pretty ambiguous and ambitious. If you look at it, it's a combination of refcnting, elements for sysfs representation, weird looking type system mostly born out from sysfs usage and device driver model, userland notification mechanism and some more. It's ass-ugly but seems to fit device driver model okish. Unfortunately, as soon as it gets dragged out of device driver model, it isn't clear what different parts of the dang thing are supposed to do.

For some device-driver-model specific reason, a directory in sysfs hierarchy maps to a kobject (there are attr dirs which are exceptions tho). As soon as you start using sysfs outside device driver model, it becomes weird. An entity which wants to expose something via sysfs somehow has to use kobject which brings in its object lifetime management which may not fit the existing usage model.

Let's say there are entities A, B and C, where A and B follow mostly the same life-cycle rules and C is dependent on B, and A and C have something to expose via sysfs. So, A and C embed kobjects inside them. What about kobj life-cycle management then? Let's say A and C use kobj life-cycle management. Hmmm... C is dependent on B. How does that play out? What if some in-kernel entity represents two separate userland-visible entities? What happens then? Do people have to suppress / circumvent kobj lifecycle mechanism? Wouldn't that make the code unnecessarily difficult to understand - extra cruft tends to be very effective at confusing people?

The stupid thing is that sysfs doesn't need any of the kobject silliness. sysfs should have provided interface fundamental to its features which device driver model should have used to implement whatever specific abstraction necessary and keep that inside. The association between certain type of life cycle management and sysfs usage wasn't anything fundamental. It was a device driver model local thing and the mechanism too should have stayed local inside the device driver model.

At least for me, closure triggers all the alarms for bad generic abstraction. The patch description you wrote for closure starts with "asynchronous refcounty thingies" and it's quite apt. It's a combination of object life-cycle management, async execution, object hierarchy, event mechanism and even locking. It isn't anything fundamental. It's a kitchen sink with spoon, knife, chainsaw and toilet welded together.

2. Making async programming better, or glaze-coating turd.

As I wrote before, I personally think that async programming - using something other than stack for execution state - is inherently inferior. The programming languages we program in and the processors the resulting programs run on depend on stack for execution context after all. To my mind, async programming is inherently a turd.

That isn't to say we can do away with async programming completely. At times, turds are unavoidable and even essential (and the line between turds and !turds isn't clear to begin with). Process context can be expensive in terms of switching and/or memory overhead. It would be silly to keep ten thousand threads lying around listening to ten thousand idle clients which may or may not make another request. It could also be silly to switch to a process context just to relay completion notification to another process context (although block layer kinda does that for a different reason).

In block layer, the need for async programming rises mostly from the disconnection between issue and completion contexts. The issuing context may not wait for the completion and we end up with IOs without matching process contexts. The problem isn't too bad tho. We require and thus have process context on the issue path and the completion paths tend to be not too complex.

When we have to deal with async programming, I think the best approach is to identify why they're necessary, restrict their scopes to minimum and clearly contain them. For example, bounce to wq as soon as things start to get complex, don't try to be smart with process contexts while something complex is going on, and relinquish context judicially when not doing so results in noticeable performance / resource hit and hopefully where doing so doesn't complicate things too much (e.g. it's a clear retry boundary).

If you follow such patterns, there isn't too much need for fancy async mechanism to blur the pain. Properly identified and consolidated, sync / async boundaries shouldn't be too painful to manage and the kernel already provides ample mechanisms to support such patterns.

The problem with closure is that it's a mechanism to glaze-coat turd. By glaze-coating, it encourages littering turds around instead of consolidating and isolating them, so in that sense, I prefer async programming to remain painful and explicit. People tend to do bat-shit crazy stuff otherwise.

To conclude, I *hope* that bcache followed more usual async programming conventions, much like I hope it followed more usual coding style. These aren't cut-and-dry issues and there probably are aspects that I haven't considered or lost balance on. Please feel free to point them out.

Thanks.

Signature · 1 line
tejun