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