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