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