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