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