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