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