xref: /openbmc/linux/drivers/md/bcache/super.c (revision da2ef666)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * bcache setup/teardown code, and some metadata io - read a superblock and
4  * figure out what to do with it.
5  *
6  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
7  * Copyright 2012 Google, Inc.
8  */
9 
10 #include "bcache.h"
11 #include "btree.h"
12 #include "debug.h"
13 #include "extents.h"
14 #include "request.h"
15 #include "writeback.h"
16 
17 #include <linux/blkdev.h>
18 #include <linux/buffer_head.h>
19 #include <linux/debugfs.h>
20 #include <linux/genhd.h>
21 #include <linux/idr.h>
22 #include <linux/kthread.h>
23 #include <linux/module.h>
24 #include <linux/random.h>
25 #include <linux/reboot.h>
26 #include <linux/sysfs.h>
27 
28 MODULE_LICENSE("GPL");
29 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
30 
31 static const char bcache_magic[] = {
32 	0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
33 	0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
34 };
35 
36 static const char invalid_uuid[] = {
37 	0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
38 	0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
39 };
40 
41 static struct kobject *bcache_kobj;
42 struct mutex bch_register_lock;
43 LIST_HEAD(bch_cache_sets);
44 static LIST_HEAD(uncached_devices);
45 
46 static int bcache_major;
47 static DEFINE_IDA(bcache_device_idx);
48 static wait_queue_head_t unregister_wait;
49 struct workqueue_struct *bcache_wq;
50 
51 #define BTREE_MAX_PAGES		(256 * 1024 / PAGE_SIZE)
52 /* limitation of partitions number on single bcache device */
53 #define BCACHE_MINORS		128
54 /* limitation of bcache devices number on single system */
55 #define BCACHE_DEVICE_IDX_MAX	((1U << MINORBITS)/BCACHE_MINORS)
56 
57 /* Superblock */
58 
59 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
60 			      struct page **res)
61 {
62 	const char *err;
63 	struct cache_sb *s;
64 	struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
65 	unsigned int i;
66 
67 	if (!bh)
68 		return "IO error";
69 
70 	s = (struct cache_sb *) bh->b_data;
71 
72 	sb->offset		= le64_to_cpu(s->offset);
73 	sb->version		= le64_to_cpu(s->version);
74 
75 	memcpy(sb->magic,	s->magic, 16);
76 	memcpy(sb->uuid,	s->uuid, 16);
77 	memcpy(sb->set_uuid,	s->set_uuid, 16);
78 	memcpy(sb->label,	s->label, SB_LABEL_SIZE);
79 
80 	sb->flags		= le64_to_cpu(s->flags);
81 	sb->seq			= le64_to_cpu(s->seq);
82 	sb->last_mount		= le32_to_cpu(s->last_mount);
83 	sb->first_bucket	= le16_to_cpu(s->first_bucket);
84 	sb->keys		= le16_to_cpu(s->keys);
85 
86 	for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
87 		sb->d[i] = le64_to_cpu(s->d[i]);
88 
89 	pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
90 		 sb->version, sb->flags, sb->seq, sb->keys);
91 
92 	err = "Not a bcache superblock";
93 	if (sb->offset != SB_SECTOR)
94 		goto err;
95 
96 	if (memcmp(sb->magic, bcache_magic, 16))
97 		goto err;
98 
99 	err = "Too many journal buckets";
100 	if (sb->keys > SB_JOURNAL_BUCKETS)
101 		goto err;
102 
103 	err = "Bad checksum";
104 	if (s->csum != csum_set(s))
105 		goto err;
106 
107 	err = "Bad UUID";
108 	if (bch_is_zero(sb->uuid, 16))
109 		goto err;
110 
111 	sb->block_size	= le16_to_cpu(s->block_size);
112 
113 	err = "Superblock block size smaller than device block size";
114 	if (sb->block_size << 9 < bdev_logical_block_size(bdev))
115 		goto err;
116 
117 	switch (sb->version) {
118 	case BCACHE_SB_VERSION_BDEV:
119 		sb->data_offset	= BDEV_DATA_START_DEFAULT;
120 		break;
121 	case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
122 		sb->data_offset	= le64_to_cpu(s->data_offset);
123 
124 		err = "Bad data offset";
125 		if (sb->data_offset < BDEV_DATA_START_DEFAULT)
126 			goto err;
127 
128 		break;
129 	case BCACHE_SB_VERSION_CDEV:
130 	case BCACHE_SB_VERSION_CDEV_WITH_UUID:
131 		sb->nbuckets	= le64_to_cpu(s->nbuckets);
132 		sb->bucket_size	= le16_to_cpu(s->bucket_size);
133 
134 		sb->nr_in_set	= le16_to_cpu(s->nr_in_set);
135 		sb->nr_this_dev	= le16_to_cpu(s->nr_this_dev);
136 
137 		err = "Too many buckets";
138 		if (sb->nbuckets > LONG_MAX)
139 			goto err;
140 
141 		err = "Not enough buckets";
142 		if (sb->nbuckets < 1 << 7)
143 			goto err;
144 
145 		err = "Bad block/bucket size";
146 		if (!is_power_of_2(sb->block_size) ||
147 		    sb->block_size > PAGE_SECTORS ||
148 		    !is_power_of_2(sb->bucket_size) ||
149 		    sb->bucket_size < PAGE_SECTORS)
150 			goto err;
151 
152 		err = "Invalid superblock: device too small";
153 		if (get_capacity(bdev->bd_disk) <
154 		    sb->bucket_size * sb->nbuckets)
155 			goto err;
156 
157 		err = "Bad UUID";
158 		if (bch_is_zero(sb->set_uuid, 16))
159 			goto err;
160 
161 		err = "Bad cache device number in set";
162 		if (!sb->nr_in_set ||
163 		    sb->nr_in_set <= sb->nr_this_dev ||
164 		    sb->nr_in_set > MAX_CACHES_PER_SET)
165 			goto err;
166 
167 		err = "Journal buckets not sequential";
168 		for (i = 0; i < sb->keys; i++)
169 			if (sb->d[i] != sb->first_bucket + i)
170 				goto err;
171 
172 		err = "Too many journal buckets";
173 		if (sb->first_bucket + sb->keys > sb->nbuckets)
174 			goto err;
175 
176 		err = "Invalid superblock: first bucket comes before end of super";
177 		if (sb->first_bucket * sb->bucket_size < 16)
178 			goto err;
179 
180 		break;
181 	default:
182 		err = "Unsupported superblock version";
183 		goto err;
184 	}
185 
186 	sb->last_mount = (u32)ktime_get_real_seconds();
187 	err = NULL;
188 
189 	get_page(bh->b_page);
190 	*res = bh->b_page;
191 err:
192 	put_bh(bh);
193 	return err;
194 }
195 
196 static void write_bdev_super_endio(struct bio *bio)
197 {
198 	struct cached_dev *dc = bio->bi_private;
199 	/* XXX: error checking */
200 
201 	closure_put(&dc->sb_write);
202 }
203 
204 static void __write_super(struct cache_sb *sb, struct bio *bio)
205 {
206 	struct cache_sb *out = page_address(bio_first_page_all(bio));
207 	unsigned int i;
208 
209 	bio->bi_iter.bi_sector	= SB_SECTOR;
210 	bio->bi_iter.bi_size	= SB_SIZE;
211 	bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC|REQ_META);
212 	bch_bio_map(bio, NULL);
213 
214 	out->offset		= cpu_to_le64(sb->offset);
215 	out->version		= cpu_to_le64(sb->version);
216 
217 	memcpy(out->uuid,	sb->uuid, 16);
218 	memcpy(out->set_uuid,	sb->set_uuid, 16);
219 	memcpy(out->label,	sb->label, SB_LABEL_SIZE);
220 
221 	out->flags		= cpu_to_le64(sb->flags);
222 	out->seq		= cpu_to_le64(sb->seq);
223 
224 	out->last_mount		= cpu_to_le32(sb->last_mount);
225 	out->first_bucket	= cpu_to_le16(sb->first_bucket);
226 	out->keys		= cpu_to_le16(sb->keys);
227 
228 	for (i = 0; i < sb->keys; i++)
229 		out->d[i] = cpu_to_le64(sb->d[i]);
230 
231 	out->csum = csum_set(out);
232 
233 	pr_debug("ver %llu, flags %llu, seq %llu",
234 		 sb->version, sb->flags, sb->seq);
235 
236 	submit_bio(bio);
237 }
238 
239 static void bch_write_bdev_super_unlock(struct closure *cl)
240 {
241 	struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
242 
243 	up(&dc->sb_write_mutex);
244 }
245 
246 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
247 {
248 	struct closure *cl = &dc->sb_write;
249 	struct bio *bio = &dc->sb_bio;
250 
251 	down(&dc->sb_write_mutex);
252 	closure_init(cl, parent);
253 
254 	bio_reset(bio);
255 	bio_set_dev(bio, dc->bdev);
256 	bio->bi_end_io	= write_bdev_super_endio;
257 	bio->bi_private = dc;
258 
259 	closure_get(cl);
260 	/* I/O request sent to backing device */
261 	__write_super(&dc->sb, bio);
262 
263 	closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
264 }
265 
266 static void write_super_endio(struct bio *bio)
267 {
268 	struct cache *ca = bio->bi_private;
269 
270 	/* is_read = 0 */
271 	bch_count_io_errors(ca, bio->bi_status, 0,
272 			    "writing superblock");
273 	closure_put(&ca->set->sb_write);
274 }
275 
276 static void bcache_write_super_unlock(struct closure *cl)
277 {
278 	struct cache_set *c = container_of(cl, struct cache_set, sb_write);
279 
280 	up(&c->sb_write_mutex);
281 }
282 
283 void bcache_write_super(struct cache_set *c)
284 {
285 	struct closure *cl = &c->sb_write;
286 	struct cache *ca;
287 	unsigned int i;
288 
289 	down(&c->sb_write_mutex);
290 	closure_init(cl, &c->cl);
291 
292 	c->sb.seq++;
293 
294 	for_each_cache(ca, c, i) {
295 		struct bio *bio = &ca->sb_bio;
296 
297 		ca->sb.version		= BCACHE_SB_VERSION_CDEV_WITH_UUID;
298 		ca->sb.seq		= c->sb.seq;
299 		ca->sb.last_mount	= c->sb.last_mount;
300 
301 		SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
302 
303 		bio_reset(bio);
304 		bio_set_dev(bio, ca->bdev);
305 		bio->bi_end_io	= write_super_endio;
306 		bio->bi_private = ca;
307 
308 		closure_get(cl);
309 		__write_super(&ca->sb, bio);
310 	}
311 
312 	closure_return_with_destructor(cl, bcache_write_super_unlock);
313 }
314 
315 /* UUID io */
316 
317 static void uuid_endio(struct bio *bio)
318 {
319 	struct closure *cl = bio->bi_private;
320 	struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
321 
322 	cache_set_err_on(bio->bi_status, c, "accessing uuids");
323 	bch_bbio_free(bio, c);
324 	closure_put(cl);
325 }
326 
327 static void uuid_io_unlock(struct closure *cl)
328 {
329 	struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
330 
331 	up(&c->uuid_write_mutex);
332 }
333 
334 static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
335 		    struct bkey *k, struct closure *parent)
336 {
337 	struct closure *cl = &c->uuid_write;
338 	struct uuid_entry *u;
339 	unsigned int i;
340 	char buf[80];
341 
342 	BUG_ON(!parent);
343 	down(&c->uuid_write_mutex);
344 	closure_init(cl, parent);
345 
346 	for (i = 0; i < KEY_PTRS(k); i++) {
347 		struct bio *bio = bch_bbio_alloc(c);
348 
349 		bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
350 		bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
351 
352 		bio->bi_end_io	= uuid_endio;
353 		bio->bi_private = cl;
354 		bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
355 		bch_bio_map(bio, c->uuids);
356 
357 		bch_submit_bbio(bio, c, k, i);
358 
359 		if (op != REQ_OP_WRITE)
360 			break;
361 	}
362 
363 	bch_extent_to_text(buf, sizeof(buf), k);
364 	pr_debug("%s UUIDs at %s", op == REQ_OP_WRITE ? "wrote" : "read", buf);
365 
366 	for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
367 		if (!bch_is_zero(u->uuid, 16))
368 			pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
369 				 u - c->uuids, u->uuid, u->label,
370 				 u->first_reg, u->last_reg, u->invalidated);
371 
372 	closure_return_with_destructor(cl, uuid_io_unlock);
373 }
374 
375 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
376 {
377 	struct bkey *k = &j->uuid_bucket;
378 
379 	if (__bch_btree_ptr_invalid(c, k))
380 		return "bad uuid pointer";
381 
382 	bkey_copy(&c->uuid_bucket, k);
383 	uuid_io(c, REQ_OP_READ, 0, k, cl);
384 
385 	if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
386 		struct uuid_entry_v0	*u0 = (void *) c->uuids;
387 		struct uuid_entry	*u1 = (void *) c->uuids;
388 		int i;
389 
390 		closure_sync(cl);
391 
392 		/*
393 		 * Since the new uuid entry is bigger than the old, we have to
394 		 * convert starting at the highest memory address and work down
395 		 * in order to do it in place
396 		 */
397 
398 		for (i = c->nr_uuids - 1;
399 		     i >= 0;
400 		     --i) {
401 			memcpy(u1[i].uuid,	u0[i].uuid, 16);
402 			memcpy(u1[i].label,	u0[i].label, 32);
403 
404 			u1[i].first_reg		= u0[i].first_reg;
405 			u1[i].last_reg		= u0[i].last_reg;
406 			u1[i].invalidated	= u0[i].invalidated;
407 
408 			u1[i].flags	= 0;
409 			u1[i].sectors	= 0;
410 		}
411 	}
412 
413 	return NULL;
414 }
415 
416 static int __uuid_write(struct cache_set *c)
417 {
418 	BKEY_PADDED(key) k;
419 	struct closure cl;
420 
421 	closure_init_stack(&cl);
422 	lockdep_assert_held(&bch_register_lock);
423 
424 	if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
425 		return 1;
426 
427 	SET_KEY_SIZE(&k.key, c->sb.bucket_size);
428 	uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
429 	closure_sync(&cl);
430 
431 	bkey_copy(&c->uuid_bucket, &k.key);
432 	bkey_put(c, &k.key);
433 	return 0;
434 }
435 
436 int bch_uuid_write(struct cache_set *c)
437 {
438 	int ret = __uuid_write(c);
439 
440 	if (!ret)
441 		bch_journal_meta(c, NULL);
442 
443 	return ret;
444 }
445 
446 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
447 {
448 	struct uuid_entry *u;
449 
450 	for (u = c->uuids;
451 	     u < c->uuids + c->nr_uuids; u++)
452 		if (!memcmp(u->uuid, uuid, 16))
453 			return u;
454 
455 	return NULL;
456 }
457 
458 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
459 {
460 	static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
461 
462 	return uuid_find(c, zero_uuid);
463 }
464 
465 /*
466  * Bucket priorities/gens:
467  *
468  * For each bucket, we store on disk its
469  *   8 bit gen
470  *  16 bit priority
471  *
472  * See alloc.c for an explanation of the gen. The priority is used to implement
473  * lru (and in the future other) cache replacement policies; for most purposes
474  * it's just an opaque integer.
475  *
476  * The gens and the priorities don't have a whole lot to do with each other, and
477  * it's actually the gens that must be written out at specific times - it's no
478  * big deal if the priorities don't get written, if we lose them we just reuse
479  * buckets in suboptimal order.
480  *
481  * On disk they're stored in a packed array, and in as many buckets are required
482  * to fit them all. The buckets we use to store them form a list; the journal
483  * header points to the first bucket, the first bucket points to the second
484  * bucket, et cetera.
485  *
486  * This code is used by the allocation code; periodically (whenever it runs out
487  * of buckets to allocate from) the allocation code will invalidate some
488  * buckets, but it can't use those buckets until their new gens are safely on
489  * disk.
490  */
491 
492 static void prio_endio(struct bio *bio)
493 {
494 	struct cache *ca = bio->bi_private;
495 
496 	cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
497 	bch_bbio_free(bio, ca->set);
498 	closure_put(&ca->prio);
499 }
500 
501 static void prio_io(struct cache *ca, uint64_t bucket, int op,
502 		    unsigned long op_flags)
503 {
504 	struct closure *cl = &ca->prio;
505 	struct bio *bio = bch_bbio_alloc(ca->set);
506 
507 	closure_init_stack(cl);
508 
509 	bio->bi_iter.bi_sector	= bucket * ca->sb.bucket_size;
510 	bio_set_dev(bio, ca->bdev);
511 	bio->bi_iter.bi_size	= bucket_bytes(ca);
512 
513 	bio->bi_end_io	= prio_endio;
514 	bio->bi_private = ca;
515 	bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
516 	bch_bio_map(bio, ca->disk_buckets);
517 
518 	closure_bio_submit(ca->set, bio, &ca->prio);
519 	closure_sync(cl);
520 }
521 
522 void bch_prio_write(struct cache *ca)
523 {
524 	int i;
525 	struct bucket *b;
526 	struct closure cl;
527 
528 	closure_init_stack(&cl);
529 
530 	lockdep_assert_held(&ca->set->bucket_lock);
531 
532 	ca->disk_buckets->seq++;
533 
534 	atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
535 			&ca->meta_sectors_written);
536 
537 	//pr_debug("free %zu, free_inc %zu, unused %zu", fifo_used(&ca->free),
538 	//	 fifo_used(&ca->free_inc), fifo_used(&ca->unused));
539 
540 	for (i = prio_buckets(ca) - 1; i >= 0; --i) {
541 		long bucket;
542 		struct prio_set *p = ca->disk_buckets;
543 		struct bucket_disk *d = p->data;
544 		struct bucket_disk *end = d + prios_per_bucket(ca);
545 
546 		for (b = ca->buckets + i * prios_per_bucket(ca);
547 		     b < ca->buckets + ca->sb.nbuckets && d < end;
548 		     b++, d++) {
549 			d->prio = cpu_to_le16(b->prio);
550 			d->gen = b->gen;
551 		}
552 
553 		p->next_bucket	= ca->prio_buckets[i + 1];
554 		p->magic	= pset_magic(&ca->sb);
555 		p->csum		= bch_crc64(&p->magic, bucket_bytes(ca) - 8);
556 
557 		bucket = bch_bucket_alloc(ca, RESERVE_PRIO, true);
558 		BUG_ON(bucket == -1);
559 
560 		mutex_unlock(&ca->set->bucket_lock);
561 		prio_io(ca, bucket, REQ_OP_WRITE, 0);
562 		mutex_lock(&ca->set->bucket_lock);
563 
564 		ca->prio_buckets[i] = bucket;
565 		atomic_dec_bug(&ca->buckets[bucket].pin);
566 	}
567 
568 	mutex_unlock(&ca->set->bucket_lock);
569 
570 	bch_journal_meta(ca->set, &cl);
571 	closure_sync(&cl);
572 
573 	mutex_lock(&ca->set->bucket_lock);
574 
575 	/*
576 	 * Don't want the old priorities to get garbage collected until after we
577 	 * finish writing the new ones, and they're journalled
578 	 */
579 	for (i = 0; i < prio_buckets(ca); i++) {
580 		if (ca->prio_last_buckets[i])
581 			__bch_bucket_free(ca,
582 				&ca->buckets[ca->prio_last_buckets[i]]);
583 
584 		ca->prio_last_buckets[i] = ca->prio_buckets[i];
585 	}
586 }
587 
588 static void prio_read(struct cache *ca, uint64_t bucket)
589 {
590 	struct prio_set *p = ca->disk_buckets;
591 	struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
592 	struct bucket *b;
593 	unsigned int bucket_nr = 0;
594 
595 	for (b = ca->buckets;
596 	     b < ca->buckets + ca->sb.nbuckets;
597 	     b++, d++) {
598 		if (d == end) {
599 			ca->prio_buckets[bucket_nr] = bucket;
600 			ca->prio_last_buckets[bucket_nr] = bucket;
601 			bucket_nr++;
602 
603 			prio_io(ca, bucket, REQ_OP_READ, 0);
604 
605 			if (p->csum !=
606 			    bch_crc64(&p->magic, bucket_bytes(ca) - 8))
607 				pr_warn("bad csum reading priorities");
608 
609 			if (p->magic != pset_magic(&ca->sb))
610 				pr_warn("bad magic reading priorities");
611 
612 			bucket = p->next_bucket;
613 			d = p->data;
614 		}
615 
616 		b->prio = le16_to_cpu(d->prio);
617 		b->gen = b->last_gc = d->gen;
618 	}
619 }
620 
621 /* Bcache device */
622 
623 static int open_dev(struct block_device *b, fmode_t mode)
624 {
625 	struct bcache_device *d = b->bd_disk->private_data;
626 
627 	if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
628 		return -ENXIO;
629 
630 	closure_get(&d->cl);
631 	return 0;
632 }
633 
634 static void release_dev(struct gendisk *b, fmode_t mode)
635 {
636 	struct bcache_device *d = b->private_data;
637 
638 	closure_put(&d->cl);
639 }
640 
641 static int ioctl_dev(struct block_device *b, fmode_t mode,
642 		     unsigned int cmd, unsigned long arg)
643 {
644 	struct bcache_device *d = b->bd_disk->private_data;
645 	struct cached_dev *dc = container_of(d, struct cached_dev, disk);
646 
647 	if (dc->io_disable)
648 		return -EIO;
649 
650 	return d->ioctl(d, mode, cmd, arg);
651 }
652 
653 static const struct block_device_operations bcache_ops = {
654 	.open		= open_dev,
655 	.release	= release_dev,
656 	.ioctl		= ioctl_dev,
657 	.owner		= THIS_MODULE,
658 };
659 
660 void bcache_device_stop(struct bcache_device *d)
661 {
662 	if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
663 		closure_queue(&d->cl);
664 }
665 
666 static void bcache_device_unlink(struct bcache_device *d)
667 {
668 	lockdep_assert_held(&bch_register_lock);
669 
670 	if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
671 		unsigned int i;
672 		struct cache *ca;
673 
674 		sysfs_remove_link(&d->c->kobj, d->name);
675 		sysfs_remove_link(&d->kobj, "cache");
676 
677 		for_each_cache(ca, d->c, i)
678 			bd_unlink_disk_holder(ca->bdev, d->disk);
679 	}
680 }
681 
682 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
683 			       const char *name)
684 {
685 	unsigned int i;
686 	struct cache *ca;
687 
688 	for_each_cache(ca, d->c, i)
689 		bd_link_disk_holder(ca->bdev, d->disk);
690 
691 	snprintf(d->name, BCACHEDEVNAME_SIZE,
692 		 "%s%u", name, d->id);
693 
694 	WARN(sysfs_create_link(&d->kobj, &c->kobj, "cache") ||
695 	     sysfs_create_link(&c->kobj, &d->kobj, d->name),
696 	     "Couldn't create device <-> cache set symlinks");
697 
698 	clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
699 }
700 
701 static void bcache_device_detach(struct bcache_device *d)
702 {
703 	lockdep_assert_held(&bch_register_lock);
704 
705 	atomic_dec(&d->c->attached_dev_nr);
706 
707 	if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
708 		struct uuid_entry *u = d->c->uuids + d->id;
709 
710 		SET_UUID_FLASH_ONLY(u, 0);
711 		memcpy(u->uuid, invalid_uuid, 16);
712 		u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
713 		bch_uuid_write(d->c);
714 	}
715 
716 	bcache_device_unlink(d);
717 
718 	d->c->devices[d->id] = NULL;
719 	closure_put(&d->c->caching);
720 	d->c = NULL;
721 }
722 
723 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
724 				 unsigned int id)
725 {
726 	d->id = id;
727 	d->c = c;
728 	c->devices[id] = d;
729 
730 	if (id >= c->devices_max_used)
731 		c->devices_max_used = id + 1;
732 
733 	closure_get(&c->caching);
734 }
735 
736 static inline int first_minor_to_idx(int first_minor)
737 {
738 	return (first_minor/BCACHE_MINORS);
739 }
740 
741 static inline int idx_to_first_minor(int idx)
742 {
743 	return (idx * BCACHE_MINORS);
744 }
745 
746 static void bcache_device_free(struct bcache_device *d)
747 {
748 	lockdep_assert_held(&bch_register_lock);
749 
750 	pr_info("%s stopped", d->disk->disk_name);
751 
752 	if (d->c)
753 		bcache_device_detach(d);
754 	if (d->disk && d->disk->flags & GENHD_FL_UP)
755 		del_gendisk(d->disk);
756 	if (d->disk && d->disk->queue)
757 		blk_cleanup_queue(d->disk->queue);
758 	if (d->disk) {
759 		ida_simple_remove(&bcache_device_idx,
760 				  first_minor_to_idx(d->disk->first_minor));
761 		put_disk(d->disk);
762 	}
763 
764 	bioset_exit(&d->bio_split);
765 	kvfree(d->full_dirty_stripes);
766 	kvfree(d->stripe_sectors_dirty);
767 
768 	closure_debug_destroy(&d->cl);
769 }
770 
771 static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
772 			      sector_t sectors)
773 {
774 	struct request_queue *q;
775 	const size_t max_stripes = min_t(size_t, INT_MAX,
776 					 SIZE_MAX / sizeof(atomic_t));
777 	size_t n;
778 	int idx;
779 
780 	if (!d->stripe_size)
781 		d->stripe_size = 1 << 31;
782 
783 	d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
784 
785 	if (!d->nr_stripes || d->nr_stripes > max_stripes) {
786 		pr_err("nr_stripes too large or invalid: %u (start sector beyond end of disk?)",
787 			(unsigned int)d->nr_stripes);
788 		return -ENOMEM;
789 	}
790 
791 	n = d->nr_stripes * sizeof(atomic_t);
792 	d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
793 	if (!d->stripe_sectors_dirty)
794 		return -ENOMEM;
795 
796 	n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
797 	d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
798 	if (!d->full_dirty_stripes)
799 		return -ENOMEM;
800 
801 	idx = ida_simple_get(&bcache_device_idx, 0,
802 				BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
803 	if (idx < 0)
804 		return idx;
805 
806 	if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
807 			BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
808 		goto err;
809 
810 	d->disk = alloc_disk(BCACHE_MINORS);
811 	if (!d->disk)
812 		goto err;
813 
814 	set_capacity(d->disk, sectors);
815 	snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
816 
817 	d->disk->major		= bcache_major;
818 	d->disk->first_minor	= idx_to_first_minor(idx);
819 	d->disk->fops		= &bcache_ops;
820 	d->disk->private_data	= d;
821 
822 	q = blk_alloc_queue(GFP_KERNEL);
823 	if (!q)
824 		return -ENOMEM;
825 
826 	blk_queue_make_request(q, NULL);
827 	d->disk->queue			= q;
828 	q->queuedata			= d;
829 	q->backing_dev_info->congested_data = d;
830 	q->limits.max_hw_sectors	= UINT_MAX;
831 	q->limits.max_sectors		= UINT_MAX;
832 	q->limits.max_segment_size	= UINT_MAX;
833 	q->limits.max_segments		= BIO_MAX_PAGES;
834 	blk_queue_max_discard_sectors(q, UINT_MAX);
835 	q->limits.discard_granularity	= 512;
836 	q->limits.io_min		= block_size;
837 	q->limits.logical_block_size	= block_size;
838 	q->limits.physical_block_size	= block_size;
839 	blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
840 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
841 	blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
842 
843 	blk_queue_write_cache(q, true, true);
844 
845 	return 0;
846 
847 err:
848 	ida_simple_remove(&bcache_device_idx, idx);
849 	return -ENOMEM;
850 
851 }
852 
853 /* Cached device */
854 
855 static void calc_cached_dev_sectors(struct cache_set *c)
856 {
857 	uint64_t sectors = 0;
858 	struct cached_dev *dc;
859 
860 	list_for_each_entry(dc, &c->cached_devs, list)
861 		sectors += bdev_sectors(dc->bdev);
862 
863 	c->cached_dev_sectors = sectors;
864 }
865 
866 #define BACKING_DEV_OFFLINE_TIMEOUT 5
867 static int cached_dev_status_update(void *arg)
868 {
869 	struct cached_dev *dc = arg;
870 	struct request_queue *q;
871 
872 	/*
873 	 * If this delayed worker is stopping outside, directly quit here.
874 	 * dc->io_disable might be set via sysfs interface, so check it
875 	 * here too.
876 	 */
877 	while (!kthread_should_stop() && !dc->io_disable) {
878 		q = bdev_get_queue(dc->bdev);
879 		if (blk_queue_dying(q))
880 			dc->offline_seconds++;
881 		else
882 			dc->offline_seconds = 0;
883 
884 		if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
885 			pr_err("%s: device offline for %d seconds",
886 			       dc->backing_dev_name,
887 			       BACKING_DEV_OFFLINE_TIMEOUT);
888 			pr_err("%s: disable I/O request due to backing "
889 			       "device offline", dc->disk.name);
890 			dc->io_disable = true;
891 			/* let others know earlier that io_disable is true */
892 			smp_mb();
893 			bcache_device_stop(&dc->disk);
894 			break;
895 		}
896 		schedule_timeout_interruptible(HZ);
897 	}
898 
899 	wait_for_kthread_stop();
900 	return 0;
901 }
902 
903 
904 void bch_cached_dev_run(struct cached_dev *dc)
905 {
906 	struct bcache_device *d = &dc->disk;
907 	char buf[SB_LABEL_SIZE + 1];
908 	char *env[] = {
909 		"DRIVER=bcache",
910 		kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
911 		NULL,
912 		NULL,
913 	};
914 
915 	memcpy(buf, dc->sb.label, SB_LABEL_SIZE);
916 	buf[SB_LABEL_SIZE] = '\0';
917 	env[2] = kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf);
918 
919 	if (atomic_xchg(&dc->running, 1)) {
920 		kfree(env[1]);
921 		kfree(env[2]);
922 		return;
923 	}
924 
925 	if (!d->c &&
926 	    BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
927 		struct closure cl;
928 
929 		closure_init_stack(&cl);
930 
931 		SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
932 		bch_write_bdev_super(dc, &cl);
933 		closure_sync(&cl);
934 	}
935 
936 	add_disk(d->disk);
937 	bd_link_disk_holder(dc->bdev, dc->disk.disk);
938 	/*
939 	 * won't show up in the uevent file, use udevadm monitor -e instead
940 	 * only class / kset properties are persistent
941 	 */
942 	kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
943 	kfree(env[1]);
944 	kfree(env[2]);
945 
946 	if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
947 	    sysfs_create_link(&disk_to_dev(d->disk)->kobj, &d->kobj, "bcache"))
948 		pr_debug("error creating sysfs link");
949 
950 	dc->status_update_thread = kthread_run(cached_dev_status_update,
951 					       dc, "bcache_status_update");
952 	if (IS_ERR(dc->status_update_thread)) {
953 		pr_warn("failed to create bcache_status_update kthread, "
954 			"continue to run without monitoring backing "
955 			"device status");
956 	}
957 }
958 
959 /*
960  * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
961  * work dc->writeback_rate_update is running. Wait until the routine
962  * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
963  * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
964  * seconds, give up waiting here and continue to cancel it too.
965  */
966 static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
967 {
968 	int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
969 
970 	do {
971 		if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
972 			      &dc->disk.flags))
973 			break;
974 		time_out--;
975 		schedule_timeout_interruptible(1);
976 	} while (time_out > 0);
977 
978 	if (time_out == 0)
979 		pr_warn("give up waiting for dc->writeback_write_update to quit");
980 
981 	cancel_delayed_work_sync(&dc->writeback_rate_update);
982 }
983 
984 static void cached_dev_detach_finish(struct work_struct *w)
985 {
986 	struct cached_dev *dc = container_of(w, struct cached_dev, detach);
987 	struct closure cl;
988 
989 	closure_init_stack(&cl);
990 
991 	BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
992 	BUG_ON(refcount_read(&dc->count));
993 
994 	mutex_lock(&bch_register_lock);
995 
996 	if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
997 		cancel_writeback_rate_update_dwork(dc);
998 
999 	if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
1000 		kthread_stop(dc->writeback_thread);
1001 		dc->writeback_thread = NULL;
1002 	}
1003 
1004 	memset(&dc->sb.set_uuid, 0, 16);
1005 	SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
1006 
1007 	bch_write_bdev_super(dc, &cl);
1008 	closure_sync(&cl);
1009 
1010 	bcache_device_detach(&dc->disk);
1011 	list_move(&dc->list, &uncached_devices);
1012 
1013 	clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
1014 	clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
1015 
1016 	mutex_unlock(&bch_register_lock);
1017 
1018 	pr_info("Caching disabled for %s", dc->backing_dev_name);
1019 
1020 	/* Drop ref we took in cached_dev_detach() */
1021 	closure_put(&dc->disk.cl);
1022 }
1023 
1024 void bch_cached_dev_detach(struct cached_dev *dc)
1025 {
1026 	lockdep_assert_held(&bch_register_lock);
1027 
1028 	if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1029 		return;
1030 
1031 	if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
1032 		return;
1033 
1034 	/*
1035 	 * Block the device from being closed and freed until we're finished
1036 	 * detaching
1037 	 */
1038 	closure_get(&dc->disk.cl);
1039 
1040 	bch_writeback_queue(dc);
1041 
1042 	cached_dev_put(dc);
1043 }
1044 
1045 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
1046 			  uint8_t *set_uuid)
1047 {
1048 	uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
1049 	struct uuid_entry *u;
1050 	struct cached_dev *exist_dc, *t;
1051 
1052 	if ((set_uuid && memcmp(set_uuid, c->sb.set_uuid, 16)) ||
1053 	    (!set_uuid && memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16)))
1054 		return -ENOENT;
1055 
1056 	if (dc->disk.c) {
1057 		pr_err("Can't attach %s: already attached",
1058 		       dc->backing_dev_name);
1059 		return -EINVAL;
1060 	}
1061 
1062 	if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
1063 		pr_err("Can't attach %s: shutting down",
1064 		       dc->backing_dev_name);
1065 		return -EINVAL;
1066 	}
1067 
1068 	if (dc->sb.block_size < c->sb.block_size) {
1069 		/* Will die */
1070 		pr_err("Couldn't attach %s: block size less than set's block size",
1071 		       dc->backing_dev_name);
1072 		return -EINVAL;
1073 	}
1074 
1075 	/* Check whether already attached */
1076 	list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
1077 		if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
1078 			pr_err("Tried to attach %s but duplicate UUID already attached",
1079 				dc->backing_dev_name);
1080 
1081 			return -EINVAL;
1082 		}
1083 	}
1084 
1085 	u = uuid_find(c, dc->sb.uuid);
1086 
1087 	if (u &&
1088 	    (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1089 	     BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1090 		memcpy(u->uuid, invalid_uuid, 16);
1091 		u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1092 		u = NULL;
1093 	}
1094 
1095 	if (!u) {
1096 		if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1097 			pr_err("Couldn't find uuid for %s in set",
1098 			       dc->backing_dev_name);
1099 			return -ENOENT;
1100 		}
1101 
1102 		u = uuid_find_empty(c);
1103 		if (!u) {
1104 			pr_err("Not caching %s, no room for UUID",
1105 			       dc->backing_dev_name);
1106 			return -EINVAL;
1107 		}
1108 	}
1109 
1110 	/*
1111 	 * Deadlocks since we're called via sysfs...
1112 	 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1113 	 */
1114 
1115 	if (bch_is_zero(u->uuid, 16)) {
1116 		struct closure cl;
1117 
1118 		closure_init_stack(&cl);
1119 
1120 		memcpy(u->uuid, dc->sb.uuid, 16);
1121 		memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1122 		u->first_reg = u->last_reg = rtime;
1123 		bch_uuid_write(c);
1124 
1125 		memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1126 		SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1127 
1128 		bch_write_bdev_super(dc, &cl);
1129 		closure_sync(&cl);
1130 	} else {
1131 		u->last_reg = rtime;
1132 		bch_uuid_write(c);
1133 	}
1134 
1135 	bcache_device_attach(&dc->disk, c, u - c->uuids);
1136 	list_move(&dc->list, &c->cached_devs);
1137 	calc_cached_dev_sectors(c);
1138 
1139 	/*
1140 	 * dc->c must be set before dc->count != 0 - paired with the mb in
1141 	 * cached_dev_get()
1142 	 */
1143 	smp_wmb();
1144 	refcount_set(&dc->count, 1);
1145 
1146 	/* Block writeback thread, but spawn it */
1147 	down_write(&dc->writeback_lock);
1148 	if (bch_cached_dev_writeback_start(dc)) {
1149 		up_write(&dc->writeback_lock);
1150 		return -ENOMEM;
1151 	}
1152 
1153 	if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1154 		bch_sectors_dirty_init(&dc->disk);
1155 		atomic_set(&dc->has_dirty, 1);
1156 		bch_writeback_queue(dc);
1157 	}
1158 
1159 	bch_cached_dev_run(dc);
1160 	bcache_device_link(&dc->disk, c, "bdev");
1161 	atomic_inc(&c->attached_dev_nr);
1162 
1163 	/* Allow the writeback thread to proceed */
1164 	up_write(&dc->writeback_lock);
1165 
1166 	pr_info("Caching %s as %s on set %pU",
1167 		dc->backing_dev_name,
1168 		dc->disk.disk->disk_name,
1169 		dc->disk.c->sb.set_uuid);
1170 	return 0;
1171 }
1172 
1173 void bch_cached_dev_release(struct kobject *kobj)
1174 {
1175 	struct cached_dev *dc = container_of(kobj, struct cached_dev,
1176 					     disk.kobj);
1177 	kfree(dc);
1178 	module_put(THIS_MODULE);
1179 }
1180 
1181 static void cached_dev_free(struct closure *cl)
1182 {
1183 	struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1184 
1185 	mutex_lock(&bch_register_lock);
1186 
1187 	if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1188 		cancel_writeback_rate_update_dwork(dc);
1189 
1190 	if (!IS_ERR_OR_NULL(dc->writeback_thread))
1191 		kthread_stop(dc->writeback_thread);
1192 	if (dc->writeback_write_wq)
1193 		destroy_workqueue(dc->writeback_write_wq);
1194 	if (!IS_ERR_OR_NULL(dc->status_update_thread))
1195 		kthread_stop(dc->status_update_thread);
1196 
1197 	if (atomic_read(&dc->running))
1198 		bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1199 	bcache_device_free(&dc->disk);
1200 	list_del(&dc->list);
1201 
1202 	mutex_unlock(&bch_register_lock);
1203 
1204 	if (!IS_ERR_OR_NULL(dc->bdev))
1205 		blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1206 
1207 	wake_up(&unregister_wait);
1208 
1209 	kobject_put(&dc->disk.kobj);
1210 }
1211 
1212 static void cached_dev_flush(struct closure *cl)
1213 {
1214 	struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1215 	struct bcache_device *d = &dc->disk;
1216 
1217 	mutex_lock(&bch_register_lock);
1218 	bcache_device_unlink(d);
1219 	mutex_unlock(&bch_register_lock);
1220 
1221 	bch_cache_accounting_destroy(&dc->accounting);
1222 	kobject_del(&d->kobj);
1223 
1224 	continue_at(cl, cached_dev_free, system_wq);
1225 }
1226 
1227 static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1228 {
1229 	int ret;
1230 	struct io *io;
1231 	struct request_queue *q = bdev_get_queue(dc->bdev);
1232 
1233 	__module_get(THIS_MODULE);
1234 	INIT_LIST_HEAD(&dc->list);
1235 	closure_init(&dc->disk.cl, NULL);
1236 	set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1237 	kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1238 	INIT_WORK(&dc->detach, cached_dev_detach_finish);
1239 	sema_init(&dc->sb_write_mutex, 1);
1240 	INIT_LIST_HEAD(&dc->io_lru);
1241 	spin_lock_init(&dc->io_lock);
1242 	bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1243 
1244 	dc->sequential_cutoff		= 4 << 20;
1245 
1246 	for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1247 		list_add(&io->lru, &dc->io_lru);
1248 		hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1249 	}
1250 
1251 	dc->disk.stripe_size = q->limits.io_opt >> 9;
1252 
1253 	if (dc->disk.stripe_size)
1254 		dc->partial_stripes_expensive =
1255 			q->limits.raid_partial_stripes_expensive;
1256 
1257 	ret = bcache_device_init(&dc->disk, block_size,
1258 			 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1259 	if (ret)
1260 		return ret;
1261 
1262 	dc->disk.disk->queue->backing_dev_info->ra_pages =
1263 		max(dc->disk.disk->queue->backing_dev_info->ra_pages,
1264 		    q->backing_dev_info->ra_pages);
1265 
1266 	atomic_set(&dc->io_errors, 0);
1267 	dc->io_disable = false;
1268 	dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
1269 	/* default to auto */
1270 	dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
1271 
1272 	bch_cached_dev_request_init(dc);
1273 	bch_cached_dev_writeback_init(dc);
1274 	return 0;
1275 }
1276 
1277 /* Cached device - bcache superblock */
1278 
1279 static void register_bdev(struct cache_sb *sb, struct page *sb_page,
1280 				 struct block_device *bdev,
1281 				 struct cached_dev *dc)
1282 {
1283 	const char *err = "cannot allocate memory";
1284 	struct cache_set *c;
1285 
1286 	bdevname(bdev, dc->backing_dev_name);
1287 	memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1288 	dc->bdev = bdev;
1289 	dc->bdev->bd_holder = dc;
1290 
1291 	bio_init(&dc->sb_bio, dc->sb_bio.bi_inline_vecs, 1);
1292 	bio_first_bvec_all(&dc->sb_bio)->bv_page = sb_page;
1293 	get_page(sb_page);
1294 
1295 
1296 	if (cached_dev_init(dc, sb->block_size << 9))
1297 		goto err;
1298 
1299 	err = "error creating kobject";
1300 	if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1301 			"bcache"))
1302 		goto err;
1303 	if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1304 		goto err;
1305 
1306 	pr_info("registered backing device %s", dc->backing_dev_name);
1307 
1308 	list_add(&dc->list, &uncached_devices);
1309 	/* attach to a matched cache set if it exists */
1310 	list_for_each_entry(c, &bch_cache_sets, list)
1311 		bch_cached_dev_attach(dc, c, NULL);
1312 
1313 	if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1314 	    BDEV_STATE(&dc->sb) == BDEV_STATE_STALE)
1315 		bch_cached_dev_run(dc);
1316 
1317 	return;
1318 err:
1319 	pr_notice("error %s: %s", dc->backing_dev_name, err);
1320 	bcache_device_stop(&dc->disk);
1321 }
1322 
1323 /* Flash only volumes */
1324 
1325 void bch_flash_dev_release(struct kobject *kobj)
1326 {
1327 	struct bcache_device *d = container_of(kobj, struct bcache_device,
1328 					       kobj);
1329 	kfree(d);
1330 }
1331 
1332 static void flash_dev_free(struct closure *cl)
1333 {
1334 	struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1335 
1336 	mutex_lock(&bch_register_lock);
1337 	atomic_long_sub(bcache_dev_sectors_dirty(d),
1338 			&d->c->flash_dev_dirty_sectors);
1339 	bcache_device_free(d);
1340 	mutex_unlock(&bch_register_lock);
1341 	kobject_put(&d->kobj);
1342 }
1343 
1344 static void flash_dev_flush(struct closure *cl)
1345 {
1346 	struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1347 
1348 	mutex_lock(&bch_register_lock);
1349 	bcache_device_unlink(d);
1350 	mutex_unlock(&bch_register_lock);
1351 	kobject_del(&d->kobj);
1352 	continue_at(cl, flash_dev_free, system_wq);
1353 }
1354 
1355 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1356 {
1357 	struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1358 					  GFP_KERNEL);
1359 	if (!d)
1360 		return -ENOMEM;
1361 
1362 	closure_init(&d->cl, NULL);
1363 	set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1364 
1365 	kobject_init(&d->kobj, &bch_flash_dev_ktype);
1366 
1367 	if (bcache_device_init(d, block_bytes(c), u->sectors))
1368 		goto err;
1369 
1370 	bcache_device_attach(d, c, u - c->uuids);
1371 	bch_sectors_dirty_init(d);
1372 	bch_flash_dev_request_init(d);
1373 	add_disk(d->disk);
1374 
1375 	if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1376 		goto err;
1377 
1378 	bcache_device_link(d, c, "volume");
1379 
1380 	return 0;
1381 err:
1382 	kobject_put(&d->kobj);
1383 	return -ENOMEM;
1384 }
1385 
1386 static int flash_devs_run(struct cache_set *c)
1387 {
1388 	int ret = 0;
1389 	struct uuid_entry *u;
1390 
1391 	for (u = c->uuids;
1392 	     u < c->uuids + c->nr_uuids && !ret;
1393 	     u++)
1394 		if (UUID_FLASH_ONLY(u))
1395 			ret = flash_dev_run(c, u);
1396 
1397 	return ret;
1398 }
1399 
1400 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1401 {
1402 	struct uuid_entry *u;
1403 
1404 	if (test_bit(CACHE_SET_STOPPING, &c->flags))
1405 		return -EINTR;
1406 
1407 	if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1408 		return -EPERM;
1409 
1410 	u = uuid_find_empty(c);
1411 	if (!u) {
1412 		pr_err("Can't create volume, no room for UUID");
1413 		return -EINVAL;
1414 	}
1415 
1416 	get_random_bytes(u->uuid, 16);
1417 	memset(u->label, 0, 32);
1418 	u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1419 
1420 	SET_UUID_FLASH_ONLY(u, 1);
1421 	u->sectors = size >> 9;
1422 
1423 	bch_uuid_write(c);
1424 
1425 	return flash_dev_run(c, u);
1426 }
1427 
1428 bool bch_cached_dev_error(struct cached_dev *dc)
1429 {
1430 	struct cache_set *c;
1431 
1432 	if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1433 		return false;
1434 
1435 	dc->io_disable = true;
1436 	/* make others know io_disable is true earlier */
1437 	smp_mb();
1438 
1439 	pr_err("stop %s: too many IO errors on backing device %s\n",
1440 		dc->disk.disk->disk_name, dc->backing_dev_name);
1441 
1442 	/*
1443 	 * If the cached device is still attached to a cache set,
1444 	 * even dc->io_disable is true and no more I/O requests
1445 	 * accepted, cache device internal I/O (writeback scan or
1446 	 * garbage collection) may still prevent bcache device from
1447 	 * being stopped. So here CACHE_SET_IO_DISABLE should be
1448 	 * set to c->flags too, to make the internal I/O to cache
1449 	 * device rejected and stopped immediately.
1450 	 * If c is NULL, that means the bcache device is not attached
1451 	 * to any cache set, then no CACHE_SET_IO_DISABLE bit to set.
1452 	 */
1453 	c = dc->disk.c;
1454 	if (c && test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1455 		pr_info("CACHE_SET_IO_DISABLE already set");
1456 
1457 	bcache_device_stop(&dc->disk);
1458 	return true;
1459 }
1460 
1461 /* Cache set */
1462 
1463 __printf(2, 3)
1464 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1465 {
1466 	va_list args;
1467 
1468 	if (c->on_error != ON_ERROR_PANIC &&
1469 	    test_bit(CACHE_SET_STOPPING, &c->flags))
1470 		return false;
1471 
1472 	if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1473 		pr_info("CACHE_SET_IO_DISABLE already set");
1474 
1475 	/*
1476 	 * XXX: we can be called from atomic context
1477 	 * acquire_console_sem();
1478 	 */
1479 
1480 	pr_err("bcache: error on %pU: ", c->sb.set_uuid);
1481 
1482 	va_start(args, fmt);
1483 	vprintk(fmt, args);
1484 	va_end(args);
1485 
1486 	pr_err(", disabling caching\n");
1487 
1488 	if (c->on_error == ON_ERROR_PANIC)
1489 		panic("panic forced after error\n");
1490 
1491 	bch_cache_set_unregister(c);
1492 	return true;
1493 }
1494 
1495 void bch_cache_set_release(struct kobject *kobj)
1496 {
1497 	struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1498 
1499 	kfree(c);
1500 	module_put(THIS_MODULE);
1501 }
1502 
1503 static void cache_set_free(struct closure *cl)
1504 {
1505 	struct cache_set *c = container_of(cl, struct cache_set, cl);
1506 	struct cache *ca;
1507 	unsigned int i;
1508 
1509 	if (!IS_ERR_OR_NULL(c->debug))
1510 		debugfs_remove(c->debug);
1511 
1512 	bch_open_buckets_free(c);
1513 	bch_btree_cache_free(c);
1514 	bch_journal_free(c);
1515 
1516 	for_each_cache(ca, c, i)
1517 		if (ca) {
1518 			ca->set = NULL;
1519 			c->cache[ca->sb.nr_this_dev] = NULL;
1520 			kobject_put(&ca->kobj);
1521 		}
1522 
1523 	bch_bset_sort_state_free(&c->sort);
1524 	free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1525 
1526 	if (c->moving_gc_wq)
1527 		destroy_workqueue(c->moving_gc_wq);
1528 	bioset_exit(&c->bio_split);
1529 	mempool_exit(&c->fill_iter);
1530 	mempool_exit(&c->bio_meta);
1531 	mempool_exit(&c->search);
1532 	kfree(c->devices);
1533 
1534 	mutex_lock(&bch_register_lock);
1535 	list_del(&c->list);
1536 	mutex_unlock(&bch_register_lock);
1537 
1538 	pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1539 	wake_up(&unregister_wait);
1540 
1541 	closure_debug_destroy(&c->cl);
1542 	kobject_put(&c->kobj);
1543 }
1544 
1545 static void cache_set_flush(struct closure *cl)
1546 {
1547 	struct cache_set *c = container_of(cl, struct cache_set, caching);
1548 	struct cache *ca;
1549 	struct btree *b;
1550 	unsigned int i;
1551 
1552 	bch_cache_accounting_destroy(&c->accounting);
1553 
1554 	kobject_put(&c->internal);
1555 	kobject_del(&c->kobj);
1556 
1557 	if (c->gc_thread)
1558 		kthread_stop(c->gc_thread);
1559 
1560 	if (!IS_ERR_OR_NULL(c->root))
1561 		list_add(&c->root->list, &c->btree_cache);
1562 
1563 	/* Should skip this if we're unregistering because of an error */
1564 	list_for_each_entry(b, &c->btree_cache, list) {
1565 		mutex_lock(&b->write_lock);
1566 		if (btree_node_dirty(b))
1567 			__bch_btree_node_write(b, NULL);
1568 		mutex_unlock(&b->write_lock);
1569 	}
1570 
1571 	for_each_cache(ca, c, i)
1572 		if (ca->alloc_thread)
1573 			kthread_stop(ca->alloc_thread);
1574 
1575 	if (c->journal.cur) {
1576 		cancel_delayed_work_sync(&c->journal.work);
1577 		/* flush last journal entry if needed */
1578 		c->journal.work.work.func(&c->journal.work.work);
1579 	}
1580 
1581 	closure_return(cl);
1582 }
1583 
1584 /*
1585  * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1586  * cache set is unregistering due to too many I/O errors. In this condition,
1587  * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1588  * value and whether the broken cache has dirty data:
1589  *
1590  * dc->stop_when_cache_set_failed    dc->has_dirty   stop bcache device
1591  *  BCH_CACHED_STOP_AUTO               0               NO
1592  *  BCH_CACHED_STOP_AUTO               1               YES
1593  *  BCH_CACHED_DEV_STOP_ALWAYS         0               YES
1594  *  BCH_CACHED_DEV_STOP_ALWAYS         1               YES
1595  *
1596  * The expected behavior is, if stop_when_cache_set_failed is configured to
1597  * "auto" via sysfs interface, the bcache device will not be stopped if the
1598  * backing device is clean on the broken cache device.
1599  */
1600 static void conditional_stop_bcache_device(struct cache_set *c,
1601 					   struct bcache_device *d,
1602 					   struct cached_dev *dc)
1603 {
1604 	if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1605 		pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.",
1606 			d->disk->disk_name, c->sb.set_uuid);
1607 		bcache_device_stop(d);
1608 	} else if (atomic_read(&dc->has_dirty)) {
1609 		/*
1610 		 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1611 		 * and dc->has_dirty == 1
1612 		 */
1613 		pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.",
1614 			d->disk->disk_name);
1615 			/*
1616 			 * There might be a small time gap that cache set is
1617 			 * released but bcache device is not. Inside this time
1618 			 * gap, regular I/O requests will directly go into
1619 			 * backing device as no cache set attached to. This
1620 			 * behavior may also introduce potential inconsistence
1621 			 * data in writeback mode while cache is dirty.
1622 			 * Therefore before calling bcache_device_stop() due
1623 			 * to a broken cache device, dc->io_disable should be
1624 			 * explicitly set to true.
1625 			 */
1626 			dc->io_disable = true;
1627 			/* make others know io_disable is true earlier */
1628 			smp_mb();
1629 			bcache_device_stop(d);
1630 	} else {
1631 		/*
1632 		 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1633 		 * and dc->has_dirty == 0
1634 		 */
1635 		pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.",
1636 			d->disk->disk_name);
1637 	}
1638 }
1639 
1640 static void __cache_set_unregister(struct closure *cl)
1641 {
1642 	struct cache_set *c = container_of(cl, struct cache_set, caching);
1643 	struct cached_dev *dc;
1644 	struct bcache_device *d;
1645 	size_t i;
1646 
1647 	mutex_lock(&bch_register_lock);
1648 
1649 	for (i = 0; i < c->devices_max_used; i++) {
1650 		d = c->devices[i];
1651 		if (!d)
1652 			continue;
1653 
1654 		if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1655 		    test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1656 			dc = container_of(d, struct cached_dev, disk);
1657 			bch_cached_dev_detach(dc);
1658 			if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1659 				conditional_stop_bcache_device(c, d, dc);
1660 		} else {
1661 			bcache_device_stop(d);
1662 		}
1663 	}
1664 
1665 	mutex_unlock(&bch_register_lock);
1666 
1667 	continue_at(cl, cache_set_flush, system_wq);
1668 }
1669 
1670 void bch_cache_set_stop(struct cache_set *c)
1671 {
1672 	if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1673 		closure_queue(&c->caching);
1674 }
1675 
1676 void bch_cache_set_unregister(struct cache_set *c)
1677 {
1678 	set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1679 	bch_cache_set_stop(c);
1680 }
1681 
1682 #define alloc_bucket_pages(gfp, c)			\
1683 	((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1684 
1685 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1686 {
1687 	int iter_size;
1688 	struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1689 
1690 	if (!c)
1691 		return NULL;
1692 
1693 	__module_get(THIS_MODULE);
1694 	closure_init(&c->cl, NULL);
1695 	set_closure_fn(&c->cl, cache_set_free, system_wq);
1696 
1697 	closure_init(&c->caching, &c->cl);
1698 	set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1699 
1700 	/* Maybe create continue_at_noreturn() and use it here? */
1701 	closure_set_stopped(&c->cl);
1702 	closure_put(&c->cl);
1703 
1704 	kobject_init(&c->kobj, &bch_cache_set_ktype);
1705 	kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1706 
1707 	bch_cache_accounting_init(&c->accounting, &c->cl);
1708 
1709 	memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1710 	c->sb.block_size	= sb->block_size;
1711 	c->sb.bucket_size	= sb->bucket_size;
1712 	c->sb.nr_in_set		= sb->nr_in_set;
1713 	c->sb.last_mount	= sb->last_mount;
1714 	c->bucket_bits		= ilog2(sb->bucket_size);
1715 	c->block_bits		= ilog2(sb->block_size);
1716 	c->nr_uuids		= bucket_bytes(c) / sizeof(struct uuid_entry);
1717 	c->devices_max_used	= 0;
1718 	atomic_set(&c->attached_dev_nr, 0);
1719 	c->btree_pages		= bucket_pages(c);
1720 	if (c->btree_pages > BTREE_MAX_PAGES)
1721 		c->btree_pages = max_t(int, c->btree_pages / 4,
1722 				       BTREE_MAX_PAGES);
1723 
1724 	sema_init(&c->sb_write_mutex, 1);
1725 	mutex_init(&c->bucket_lock);
1726 	init_waitqueue_head(&c->btree_cache_wait);
1727 	init_waitqueue_head(&c->bucket_wait);
1728 	init_waitqueue_head(&c->gc_wait);
1729 	sema_init(&c->uuid_write_mutex, 1);
1730 
1731 	spin_lock_init(&c->btree_gc_time.lock);
1732 	spin_lock_init(&c->btree_split_time.lock);
1733 	spin_lock_init(&c->btree_read_time.lock);
1734 
1735 	bch_moving_init_cache_set(c);
1736 
1737 	INIT_LIST_HEAD(&c->list);
1738 	INIT_LIST_HEAD(&c->cached_devs);
1739 	INIT_LIST_HEAD(&c->btree_cache);
1740 	INIT_LIST_HEAD(&c->btree_cache_freeable);
1741 	INIT_LIST_HEAD(&c->btree_cache_freed);
1742 	INIT_LIST_HEAD(&c->data_buckets);
1743 
1744 	iter_size = (sb->bucket_size / sb->block_size + 1) *
1745 		sizeof(struct btree_iter_set);
1746 
1747 	if (!(c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL)) ||
1748 	    mempool_init_slab_pool(&c->search, 32, bch_search_cache) ||
1749 	    mempool_init_kmalloc_pool(&c->bio_meta, 2,
1750 				sizeof(struct bbio) + sizeof(struct bio_vec) *
1751 				bucket_pages(c)) ||
1752 	    mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
1753 	    bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1754 			BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER) ||
1755 	    !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1756 	    !(c->moving_gc_wq = alloc_workqueue("bcache_gc",
1757 						WQ_MEM_RECLAIM, 0)) ||
1758 	    bch_journal_alloc(c) ||
1759 	    bch_btree_cache_alloc(c) ||
1760 	    bch_open_buckets_alloc(c) ||
1761 	    bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1762 		goto err;
1763 
1764 	c->congested_read_threshold_us	= 2000;
1765 	c->congested_write_threshold_us	= 20000;
1766 	c->error_limit	= DEFAULT_IO_ERROR_LIMIT;
1767 	WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1768 
1769 	return c;
1770 err:
1771 	bch_cache_set_unregister(c);
1772 	return NULL;
1773 }
1774 
1775 static void run_cache_set(struct cache_set *c)
1776 {
1777 	const char *err = "cannot allocate memory";
1778 	struct cached_dev *dc, *t;
1779 	struct cache *ca;
1780 	struct closure cl;
1781 	unsigned int i;
1782 
1783 	closure_init_stack(&cl);
1784 
1785 	for_each_cache(ca, c, i)
1786 		c->nbuckets += ca->sb.nbuckets;
1787 	set_gc_sectors(c);
1788 
1789 	if (CACHE_SYNC(&c->sb)) {
1790 		LIST_HEAD(journal);
1791 		struct bkey *k;
1792 		struct jset *j;
1793 
1794 		err = "cannot allocate memory for journal";
1795 		if (bch_journal_read(c, &journal))
1796 			goto err;
1797 
1798 		pr_debug("btree_journal_read() done");
1799 
1800 		err = "no journal entries found";
1801 		if (list_empty(&journal))
1802 			goto err;
1803 
1804 		j = &list_entry(journal.prev, struct journal_replay, list)->j;
1805 
1806 		err = "IO error reading priorities";
1807 		for_each_cache(ca, c, i)
1808 			prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1809 
1810 		/*
1811 		 * If prio_read() fails it'll call cache_set_error and we'll
1812 		 * tear everything down right away, but if we perhaps checked
1813 		 * sooner we could avoid journal replay.
1814 		 */
1815 
1816 		k = &j->btree_root;
1817 
1818 		err = "bad btree root";
1819 		if (__bch_btree_ptr_invalid(c, k))
1820 			goto err;
1821 
1822 		err = "error reading btree root";
1823 		c->root = bch_btree_node_get(c, NULL, k,
1824 					     j->btree_level,
1825 					     true, NULL);
1826 		if (IS_ERR_OR_NULL(c->root))
1827 			goto err;
1828 
1829 		list_del_init(&c->root->list);
1830 		rw_unlock(true, c->root);
1831 
1832 		err = uuid_read(c, j, &cl);
1833 		if (err)
1834 			goto err;
1835 
1836 		err = "error in recovery";
1837 		if (bch_btree_check(c))
1838 			goto err;
1839 
1840 		bch_journal_mark(c, &journal);
1841 		bch_initial_gc_finish(c);
1842 		pr_debug("btree_check() done");
1843 
1844 		/*
1845 		 * bcache_journal_next() can't happen sooner, or
1846 		 * btree_gc_finish() will give spurious errors about last_gc >
1847 		 * gc_gen - this is a hack but oh well.
1848 		 */
1849 		bch_journal_next(&c->journal);
1850 
1851 		err = "error starting allocator thread";
1852 		for_each_cache(ca, c, i)
1853 			if (bch_cache_allocator_start(ca))
1854 				goto err;
1855 
1856 		/*
1857 		 * First place it's safe to allocate: btree_check() and
1858 		 * btree_gc_finish() have to run before we have buckets to
1859 		 * allocate, and bch_bucket_alloc_set() might cause a journal
1860 		 * entry to be written so bcache_journal_next() has to be called
1861 		 * first.
1862 		 *
1863 		 * If the uuids were in the old format we have to rewrite them
1864 		 * before the next journal entry is written:
1865 		 */
1866 		if (j->version < BCACHE_JSET_VERSION_UUID)
1867 			__uuid_write(c);
1868 
1869 		bch_journal_replay(c, &journal);
1870 	} else {
1871 		pr_notice("invalidating existing data");
1872 
1873 		for_each_cache(ca, c, i) {
1874 			unsigned int j;
1875 
1876 			ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1877 					      2, SB_JOURNAL_BUCKETS);
1878 
1879 			for (j = 0; j < ca->sb.keys; j++)
1880 				ca->sb.d[j] = ca->sb.first_bucket + j;
1881 		}
1882 
1883 		bch_initial_gc_finish(c);
1884 
1885 		err = "error starting allocator thread";
1886 		for_each_cache(ca, c, i)
1887 			if (bch_cache_allocator_start(ca))
1888 				goto err;
1889 
1890 		mutex_lock(&c->bucket_lock);
1891 		for_each_cache(ca, c, i)
1892 			bch_prio_write(ca);
1893 		mutex_unlock(&c->bucket_lock);
1894 
1895 		err = "cannot allocate new UUID bucket";
1896 		if (__uuid_write(c))
1897 			goto err;
1898 
1899 		err = "cannot allocate new btree root";
1900 		c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
1901 		if (IS_ERR_OR_NULL(c->root))
1902 			goto err;
1903 
1904 		mutex_lock(&c->root->write_lock);
1905 		bkey_copy_key(&c->root->key, &MAX_KEY);
1906 		bch_btree_node_write(c->root, &cl);
1907 		mutex_unlock(&c->root->write_lock);
1908 
1909 		bch_btree_set_root(c->root);
1910 		rw_unlock(true, c->root);
1911 
1912 		/*
1913 		 * We don't want to write the first journal entry until
1914 		 * everything is set up - fortunately journal entries won't be
1915 		 * written until the SET_CACHE_SYNC() here:
1916 		 */
1917 		SET_CACHE_SYNC(&c->sb, true);
1918 
1919 		bch_journal_next(&c->journal);
1920 		bch_journal_meta(c, &cl);
1921 	}
1922 
1923 	err = "error starting gc thread";
1924 	if (bch_gc_thread_start(c))
1925 		goto err;
1926 
1927 	closure_sync(&cl);
1928 	c->sb.last_mount = (u32)ktime_get_real_seconds();
1929 	bcache_write_super(c);
1930 
1931 	list_for_each_entry_safe(dc, t, &uncached_devices, list)
1932 		bch_cached_dev_attach(dc, c, NULL);
1933 
1934 	flash_devs_run(c);
1935 
1936 	set_bit(CACHE_SET_RUNNING, &c->flags);
1937 	return;
1938 err:
1939 	closure_sync(&cl);
1940 	/* XXX: test this, it's broken */
1941 	bch_cache_set_error(c, "%s", err);
1942 }
1943 
1944 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
1945 {
1946 	return ca->sb.block_size	== c->sb.block_size &&
1947 		ca->sb.bucket_size	== c->sb.bucket_size &&
1948 		ca->sb.nr_in_set	== c->sb.nr_in_set;
1949 }
1950 
1951 static const char *register_cache_set(struct cache *ca)
1952 {
1953 	char buf[12];
1954 	const char *err = "cannot allocate memory";
1955 	struct cache_set *c;
1956 
1957 	list_for_each_entry(c, &bch_cache_sets, list)
1958 		if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
1959 			if (c->cache[ca->sb.nr_this_dev])
1960 				return "duplicate cache set member";
1961 
1962 			if (!can_attach_cache(ca, c))
1963 				return "cache sb does not match set";
1964 
1965 			if (!CACHE_SYNC(&ca->sb))
1966 				SET_CACHE_SYNC(&c->sb, false);
1967 
1968 			goto found;
1969 		}
1970 
1971 	c = bch_cache_set_alloc(&ca->sb);
1972 	if (!c)
1973 		return err;
1974 
1975 	err = "error creating kobject";
1976 	if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
1977 	    kobject_add(&c->internal, &c->kobj, "internal"))
1978 		goto err;
1979 
1980 	if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
1981 		goto err;
1982 
1983 	bch_debug_init_cache_set(c);
1984 
1985 	list_add(&c->list, &bch_cache_sets);
1986 found:
1987 	sprintf(buf, "cache%i", ca->sb.nr_this_dev);
1988 	if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
1989 	    sysfs_create_link(&c->kobj, &ca->kobj, buf))
1990 		goto err;
1991 
1992 	if (ca->sb.seq > c->sb.seq) {
1993 		c->sb.version		= ca->sb.version;
1994 		memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
1995 		c->sb.flags             = ca->sb.flags;
1996 		c->sb.seq		= ca->sb.seq;
1997 		pr_debug("set version = %llu", c->sb.version);
1998 	}
1999 
2000 	kobject_get(&ca->kobj);
2001 	ca->set = c;
2002 	ca->set->cache[ca->sb.nr_this_dev] = ca;
2003 	c->cache_by_alloc[c->caches_loaded++] = ca;
2004 
2005 	if (c->caches_loaded == c->sb.nr_in_set)
2006 		run_cache_set(c);
2007 
2008 	return NULL;
2009 err:
2010 	bch_cache_set_unregister(c);
2011 	return err;
2012 }
2013 
2014 /* Cache device */
2015 
2016 void bch_cache_release(struct kobject *kobj)
2017 {
2018 	struct cache *ca = container_of(kobj, struct cache, kobj);
2019 	unsigned int i;
2020 
2021 	if (ca->set) {
2022 		BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
2023 		ca->set->cache[ca->sb.nr_this_dev] = NULL;
2024 	}
2025 
2026 	free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
2027 	kfree(ca->prio_buckets);
2028 	vfree(ca->buckets);
2029 
2030 	free_heap(&ca->heap);
2031 	free_fifo(&ca->free_inc);
2032 
2033 	for (i = 0; i < RESERVE_NR; i++)
2034 		free_fifo(&ca->free[i]);
2035 
2036 	if (ca->sb_bio.bi_inline_vecs[0].bv_page)
2037 		put_page(bio_first_page_all(&ca->sb_bio));
2038 
2039 	if (!IS_ERR_OR_NULL(ca->bdev))
2040 		blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2041 
2042 	kfree(ca);
2043 	module_put(THIS_MODULE);
2044 }
2045 
2046 static int cache_alloc(struct cache *ca)
2047 {
2048 	size_t free;
2049 	size_t btree_buckets;
2050 	struct bucket *b;
2051 
2052 	__module_get(THIS_MODULE);
2053 	kobject_init(&ca->kobj, &bch_cache_ktype);
2054 
2055 	bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2056 
2057 	/*
2058 	 * when ca->sb.njournal_buckets is not zero, journal exists,
2059 	 * and in bch_journal_replay(), tree node may split,
2060 	 * so bucket of RESERVE_BTREE type is needed,
2061 	 * the worst situation is all journal buckets are valid journal,
2062 	 * and all the keys need to replay,
2063 	 * so the number of  RESERVE_BTREE type buckets should be as much
2064 	 * as journal buckets
2065 	 */
2066 	btree_buckets = ca->sb.njournal_buckets ?: 8;
2067 	free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
2068 
2069 	if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets, GFP_KERNEL) ||
2070 	    !init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca), GFP_KERNEL) ||
2071 	    !init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL) ||
2072 	    !init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL) ||
2073 	    !init_fifo(&ca->free_inc,	free << 2, GFP_KERNEL) ||
2074 	    !init_heap(&ca->heap,	free << 3, GFP_KERNEL) ||
2075 	    !(ca->buckets	= vzalloc(array_size(sizeof(struct bucket),
2076 						     ca->sb.nbuckets))) ||
2077 	    !(ca->prio_buckets	= kzalloc(array3_size(sizeof(uint64_t),
2078 						      prio_buckets(ca), 2),
2079 					  GFP_KERNEL)) ||
2080 	    !(ca->disk_buckets	= alloc_bucket_pages(GFP_KERNEL, ca)))
2081 		return -ENOMEM;
2082 
2083 	ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2084 
2085 	for_each_bucket(b, ca)
2086 		atomic_set(&b->pin, 0);
2087 
2088 	return 0;
2089 }
2090 
2091 static int register_cache(struct cache_sb *sb, struct page *sb_page,
2092 				struct block_device *bdev, struct cache *ca)
2093 {
2094 	const char *err = NULL; /* must be set for any error case */
2095 	int ret = 0;
2096 
2097 	bdevname(bdev, ca->cache_dev_name);
2098 	memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2099 	ca->bdev = bdev;
2100 	ca->bdev->bd_holder = ca;
2101 
2102 	bio_init(&ca->sb_bio, ca->sb_bio.bi_inline_vecs, 1);
2103 	bio_first_bvec_all(&ca->sb_bio)->bv_page = sb_page;
2104 	get_page(sb_page);
2105 
2106 	if (blk_queue_discard(bdev_get_queue(bdev)))
2107 		ca->discard = CACHE_DISCARD(&ca->sb);
2108 
2109 	ret = cache_alloc(ca);
2110 	if (ret != 0) {
2111 		blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2112 		if (ret == -ENOMEM)
2113 			err = "cache_alloc(): -ENOMEM";
2114 		else
2115 			err = "cache_alloc(): unknown error";
2116 		goto err;
2117 	}
2118 
2119 	if (kobject_add(&ca->kobj,
2120 			&part_to_dev(bdev->bd_part)->kobj,
2121 			"bcache")) {
2122 		err = "error calling kobject_add";
2123 		ret = -ENOMEM;
2124 		goto out;
2125 	}
2126 
2127 	mutex_lock(&bch_register_lock);
2128 	err = register_cache_set(ca);
2129 	mutex_unlock(&bch_register_lock);
2130 
2131 	if (err) {
2132 		ret = -ENODEV;
2133 		goto out;
2134 	}
2135 
2136 	pr_info("registered cache device %s", ca->cache_dev_name);
2137 
2138 out:
2139 	kobject_put(&ca->kobj);
2140 
2141 err:
2142 	if (err)
2143 		pr_notice("error %s: %s", ca->cache_dev_name, err);
2144 
2145 	return ret;
2146 }
2147 
2148 /* Global interfaces/init */
2149 
2150 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2151 			       const char *buffer, size_t size);
2152 
2153 kobj_attribute_write(register,		register_bcache);
2154 kobj_attribute_write(register_quiet,	register_bcache);
2155 
2156 static bool bch_is_open_backing(struct block_device *bdev)
2157 {
2158 	struct cache_set *c, *tc;
2159 	struct cached_dev *dc, *t;
2160 
2161 	list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2162 		list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2163 			if (dc->bdev == bdev)
2164 				return true;
2165 	list_for_each_entry_safe(dc, t, &uncached_devices, list)
2166 		if (dc->bdev == bdev)
2167 			return true;
2168 	return false;
2169 }
2170 
2171 static bool bch_is_open_cache(struct block_device *bdev)
2172 {
2173 	struct cache_set *c, *tc;
2174 	struct cache *ca;
2175 	unsigned int i;
2176 
2177 	list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2178 		for_each_cache(ca, c, i)
2179 			if (ca->bdev == bdev)
2180 				return true;
2181 	return false;
2182 }
2183 
2184 static bool bch_is_open(struct block_device *bdev)
2185 {
2186 	return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2187 }
2188 
2189 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2190 			       const char *buffer, size_t size)
2191 {
2192 	ssize_t ret = size;
2193 	const char *err = "cannot allocate memory";
2194 	char *path = NULL;
2195 	struct cache_sb *sb = NULL;
2196 	struct block_device *bdev = NULL;
2197 	struct page *sb_page = NULL;
2198 
2199 	if (!try_module_get(THIS_MODULE))
2200 		return -EBUSY;
2201 
2202 	path = kstrndup(buffer, size, GFP_KERNEL);
2203 	if (!path)
2204 		goto err;
2205 
2206 	sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2207 	if (!sb)
2208 		goto err;
2209 
2210 	err = "failed to open device";
2211 	bdev = blkdev_get_by_path(strim(path),
2212 				  FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2213 				  sb);
2214 	if (IS_ERR(bdev)) {
2215 		if (bdev == ERR_PTR(-EBUSY)) {
2216 			bdev = lookup_bdev(strim(path));
2217 			mutex_lock(&bch_register_lock);
2218 			if (!IS_ERR(bdev) && bch_is_open(bdev))
2219 				err = "device already registered";
2220 			else
2221 				err = "device busy";
2222 			mutex_unlock(&bch_register_lock);
2223 			if (!IS_ERR(bdev))
2224 				bdput(bdev);
2225 			if (attr == &ksysfs_register_quiet)
2226 				goto out;
2227 		}
2228 		goto err;
2229 	}
2230 
2231 	err = "failed to set blocksize";
2232 	if (set_blocksize(bdev, 4096))
2233 		goto err_close;
2234 
2235 	err = read_super(sb, bdev, &sb_page);
2236 	if (err)
2237 		goto err_close;
2238 
2239 	err = "failed to register device";
2240 	if (SB_IS_BDEV(sb)) {
2241 		struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2242 
2243 		if (!dc)
2244 			goto err_close;
2245 
2246 		mutex_lock(&bch_register_lock);
2247 		register_bdev(sb, sb_page, bdev, dc);
2248 		mutex_unlock(&bch_register_lock);
2249 	} else {
2250 		struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2251 
2252 		if (!ca)
2253 			goto err_close;
2254 
2255 		if (register_cache(sb, sb_page, bdev, ca) != 0)
2256 			goto err;
2257 	}
2258 out:
2259 	if (sb_page)
2260 		put_page(sb_page);
2261 	kfree(sb);
2262 	kfree(path);
2263 	module_put(THIS_MODULE);
2264 	return ret;
2265 
2266 err_close:
2267 	blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2268 err:
2269 	pr_info("error %s: %s", path, err);
2270 	ret = -EINVAL;
2271 	goto out;
2272 }
2273 
2274 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2275 {
2276 	if (code == SYS_DOWN ||
2277 	    code == SYS_HALT ||
2278 	    code == SYS_POWER_OFF) {
2279 		DEFINE_WAIT(wait);
2280 		unsigned long start = jiffies;
2281 		bool stopped = false;
2282 
2283 		struct cache_set *c, *tc;
2284 		struct cached_dev *dc, *tdc;
2285 
2286 		mutex_lock(&bch_register_lock);
2287 
2288 		if (list_empty(&bch_cache_sets) &&
2289 		    list_empty(&uncached_devices))
2290 			goto out;
2291 
2292 		pr_info("Stopping all devices:");
2293 
2294 		list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2295 			bch_cache_set_stop(c);
2296 
2297 		list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2298 			bcache_device_stop(&dc->disk);
2299 
2300 		/* What's a condition variable? */
2301 		while (1) {
2302 			long timeout = start + 2 * HZ - jiffies;
2303 
2304 			stopped = list_empty(&bch_cache_sets) &&
2305 				list_empty(&uncached_devices);
2306 
2307 			if (timeout < 0 || stopped)
2308 				break;
2309 
2310 			prepare_to_wait(&unregister_wait, &wait,
2311 					TASK_UNINTERRUPTIBLE);
2312 
2313 			mutex_unlock(&bch_register_lock);
2314 			schedule_timeout(timeout);
2315 			mutex_lock(&bch_register_lock);
2316 		}
2317 
2318 		finish_wait(&unregister_wait, &wait);
2319 
2320 		if (stopped)
2321 			pr_info("All devices stopped");
2322 		else
2323 			pr_notice("Timeout waiting for devices to be closed");
2324 out:
2325 		mutex_unlock(&bch_register_lock);
2326 	}
2327 
2328 	return NOTIFY_DONE;
2329 }
2330 
2331 static struct notifier_block reboot = {
2332 	.notifier_call	= bcache_reboot,
2333 	.priority	= INT_MAX, /* before any real devices */
2334 };
2335 
2336 static void bcache_exit(void)
2337 {
2338 	bch_debug_exit();
2339 	bch_request_exit();
2340 	if (bcache_kobj)
2341 		kobject_put(bcache_kobj);
2342 	if (bcache_wq)
2343 		destroy_workqueue(bcache_wq);
2344 	if (bcache_major)
2345 		unregister_blkdev(bcache_major, "bcache");
2346 	unregister_reboot_notifier(&reboot);
2347 	mutex_destroy(&bch_register_lock);
2348 }
2349 
2350 static int __init bcache_init(void)
2351 {
2352 	static const struct attribute *files[] = {
2353 		&ksysfs_register.attr,
2354 		&ksysfs_register_quiet.attr,
2355 		NULL
2356 	};
2357 
2358 	mutex_init(&bch_register_lock);
2359 	init_waitqueue_head(&unregister_wait);
2360 	register_reboot_notifier(&reboot);
2361 
2362 	bcache_major = register_blkdev(0, "bcache");
2363 	if (bcache_major < 0) {
2364 		unregister_reboot_notifier(&reboot);
2365 		mutex_destroy(&bch_register_lock);
2366 		return bcache_major;
2367 	}
2368 
2369 	bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2370 	if (!bcache_wq)
2371 		goto err;
2372 
2373 	bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2374 	if (!bcache_kobj)
2375 		goto err;
2376 
2377 	if (bch_request_init() ||
2378 	    sysfs_create_files(bcache_kobj, files))
2379 		goto err;
2380 
2381 	bch_debug_init(bcache_kobj);
2382 	closure_debug_init();
2383 
2384 	return 0;
2385 err:
2386 	bcache_exit();
2387 	return -ENOMEM;
2388 }
2389 
2390 module_exit(bcache_exit);
2391 module_init(bcache_init);
2392