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