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