Linux 4.19.133
[linux/fpc-iii.git] / drivers / md / bcache / super.c
blob68ebc2759c2ef618c22c3137d65aa9fdb40f5866
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.
6 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
7 * Copyright 2012 Google, Inc.
8 */
10 #include "bcache.h"
11 #include "btree.h"
12 #include "debug.h"
13 #include "extents.h"
14 #include "request.h"
15 #include "writeback.h"
17 #include <linux/blkdev.h>
18 #include <linux/buffer_head.h>
19 #include <linux/debugfs.h>
20 #include <linux/genhd.h>
21 #include <linux/idr.h>
22 #include <linux/kthread.h>
23 #include <linux/module.h>
24 #include <linux/random.h>
25 #include <linux/reboot.h>
26 #include <linux/sysfs.h>
28 MODULE_LICENSE("GPL");
29 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
31 static const char bcache_magic[] = {
32 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
33 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
36 static const char invalid_uuid[] = {
37 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
38 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
41 static struct kobject *bcache_kobj;
42 struct mutex bch_register_lock;
43 LIST_HEAD(bch_cache_sets);
44 static LIST_HEAD(uncached_devices);
46 static int bcache_major;
47 static DEFINE_IDA(bcache_device_idx);
48 static wait_queue_head_t unregister_wait;
49 struct workqueue_struct *bcache_wq;
50 struct workqueue_struct *bch_journal_wq;
52 #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
53 /* limitation of partitions number on single bcache device */
54 #define BCACHE_MINORS 128
55 /* limitation of bcache devices number on single system */
56 #define BCACHE_DEVICE_IDX_MAX ((1U << MINORBITS)/BCACHE_MINORS)
58 /* Superblock */
60 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
61 struct page **res)
63 const char *err;
64 struct cache_sb *s;
65 struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
66 unsigned int i;
68 if (!bh)
69 return "IO error";
71 s = (struct cache_sb *) bh->b_data;
73 sb->offset = le64_to_cpu(s->offset);
74 sb->version = le64_to_cpu(s->version);
76 memcpy(sb->magic, s->magic, 16);
77 memcpy(sb->uuid, s->uuid, 16);
78 memcpy(sb->set_uuid, s->set_uuid, 16);
79 memcpy(sb->label, s->label, SB_LABEL_SIZE);
81 sb->flags = le64_to_cpu(s->flags);
82 sb->seq = le64_to_cpu(s->seq);
83 sb->last_mount = le32_to_cpu(s->last_mount);
84 sb->first_bucket = le16_to_cpu(s->first_bucket);
85 sb->keys = le16_to_cpu(s->keys);
87 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
88 sb->d[i] = le64_to_cpu(s->d[i]);
90 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
91 sb->version, sb->flags, sb->seq, sb->keys);
93 err = "Not a bcache superblock";
94 if (sb->offset != SB_SECTOR)
95 goto err;
97 if (memcmp(sb->magic, bcache_magic, 16))
98 goto err;
100 err = "Too many journal buckets";
101 if (sb->keys > SB_JOURNAL_BUCKETS)
102 goto err;
104 err = "Bad checksum";
105 if (s->csum != csum_set(s))
106 goto err;
108 err = "Bad UUID";
109 if (bch_is_zero(sb->uuid, 16))
110 goto err;
112 sb->block_size = le16_to_cpu(s->block_size);
114 err = "Superblock block size smaller than device block size";
115 if (sb->block_size << 9 < bdev_logical_block_size(bdev))
116 goto err;
118 switch (sb->version) {
119 case BCACHE_SB_VERSION_BDEV:
120 sb->data_offset = BDEV_DATA_START_DEFAULT;
121 break;
122 case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
123 sb->data_offset = le64_to_cpu(s->data_offset);
125 err = "Bad data offset";
126 if (sb->data_offset < BDEV_DATA_START_DEFAULT)
127 goto err;
129 break;
130 case BCACHE_SB_VERSION_CDEV:
131 case BCACHE_SB_VERSION_CDEV_WITH_UUID:
132 sb->nbuckets = le64_to_cpu(s->nbuckets);
133 sb->bucket_size = le16_to_cpu(s->bucket_size);
135 sb->nr_in_set = le16_to_cpu(s->nr_in_set);
136 sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
138 err = "Too many buckets";
139 if (sb->nbuckets > LONG_MAX)
140 goto err;
142 err = "Not enough buckets";
143 if (sb->nbuckets < 1 << 7)
144 goto err;
146 err = "Bad block/bucket size";
147 if (!is_power_of_2(sb->block_size) ||
148 sb->block_size > PAGE_SECTORS ||
149 !is_power_of_2(sb->bucket_size) ||
150 sb->bucket_size < PAGE_SECTORS)
151 goto err;
153 err = "Invalid superblock: device too small";
154 if (get_capacity(bdev->bd_disk) <
155 sb->bucket_size * sb->nbuckets)
156 goto err;
158 err = "Bad UUID";
159 if (bch_is_zero(sb->set_uuid, 16))
160 goto err;
162 err = "Bad cache device number in set";
163 if (!sb->nr_in_set ||
164 sb->nr_in_set <= sb->nr_this_dev ||
165 sb->nr_in_set > MAX_CACHES_PER_SET)
166 goto err;
168 err = "Journal buckets not sequential";
169 for (i = 0; i < sb->keys; i++)
170 if (sb->d[i] != sb->first_bucket + i)
171 goto err;
173 err = "Too many journal buckets";
174 if (sb->first_bucket + sb->keys > sb->nbuckets)
175 goto err;
177 err = "Invalid superblock: first bucket comes before end of super";
178 if (sb->first_bucket * sb->bucket_size < 16)
179 goto err;
181 break;
182 default:
183 err = "Unsupported superblock version";
184 goto err;
187 sb->last_mount = (u32)ktime_get_real_seconds();
188 err = NULL;
190 get_page(bh->b_page);
191 *res = bh->b_page;
192 err:
193 put_bh(bh);
194 return err;
197 static void write_bdev_super_endio(struct bio *bio)
199 struct cached_dev *dc = bio->bi_private;
200 /* XXX: error checking */
202 closure_put(&dc->sb_write);
205 static void __write_super(struct cache_sb *sb, struct bio *bio)
207 struct cache_sb *out = page_address(bio_first_page_all(bio));
208 unsigned int i;
210 bio->bi_iter.bi_sector = SB_SECTOR;
211 bio->bi_iter.bi_size = SB_SIZE;
212 bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC|REQ_META);
213 bch_bio_map(bio, NULL);
215 out->offset = cpu_to_le64(sb->offset);
216 out->version = cpu_to_le64(sb->version);
218 memcpy(out->uuid, sb->uuid, 16);
219 memcpy(out->set_uuid, sb->set_uuid, 16);
220 memcpy(out->label, sb->label, SB_LABEL_SIZE);
222 out->flags = cpu_to_le64(sb->flags);
223 out->seq = cpu_to_le64(sb->seq);
225 out->last_mount = cpu_to_le32(sb->last_mount);
226 out->first_bucket = cpu_to_le16(sb->first_bucket);
227 out->keys = cpu_to_le16(sb->keys);
229 for (i = 0; i < sb->keys; i++)
230 out->d[i] = cpu_to_le64(sb->d[i]);
232 out->csum = csum_set(out);
234 pr_debug("ver %llu, flags %llu, seq %llu",
235 sb->version, sb->flags, sb->seq);
237 submit_bio(bio);
240 static void bch_write_bdev_super_unlock(struct closure *cl)
242 struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
244 up(&dc->sb_write_mutex);
247 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
249 struct closure *cl = &dc->sb_write;
250 struct bio *bio = &dc->sb_bio;
252 down(&dc->sb_write_mutex);
253 closure_init(cl, parent);
255 bio_reset(bio);
256 bio_set_dev(bio, dc->bdev);
257 bio->bi_end_io = write_bdev_super_endio;
258 bio->bi_private = dc;
260 closure_get(cl);
261 /* I/O request sent to backing device */
262 __write_super(&dc->sb, bio);
264 closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
267 static void write_super_endio(struct bio *bio)
269 struct cache *ca = bio->bi_private;
271 /* is_read = 0 */
272 bch_count_io_errors(ca, bio->bi_status, 0,
273 "writing superblock");
274 closure_put(&ca->set->sb_write);
277 static void bcache_write_super_unlock(struct closure *cl)
279 struct cache_set *c = container_of(cl, struct cache_set, sb_write);
281 up(&c->sb_write_mutex);
284 void bcache_write_super(struct cache_set *c)
286 struct closure *cl = &c->sb_write;
287 struct cache *ca;
288 unsigned int i;
290 down(&c->sb_write_mutex);
291 closure_init(cl, &c->cl);
293 c->sb.seq++;
295 for_each_cache(ca, c, i) {
296 struct bio *bio = &ca->sb_bio;
298 ca->sb.version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
299 ca->sb.seq = c->sb.seq;
300 ca->sb.last_mount = c->sb.last_mount;
302 SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
304 bio_reset(bio);
305 bio_set_dev(bio, ca->bdev);
306 bio->bi_end_io = write_super_endio;
307 bio->bi_private = ca;
309 closure_get(cl);
310 __write_super(&ca->sb, bio);
313 closure_return_with_destructor(cl, bcache_write_super_unlock);
316 /* UUID io */
318 static void uuid_endio(struct bio *bio)
320 struct closure *cl = bio->bi_private;
321 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
323 cache_set_err_on(bio->bi_status, c, "accessing uuids");
324 bch_bbio_free(bio, c);
325 closure_put(cl);
328 static void uuid_io_unlock(struct closure *cl)
330 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
332 up(&c->uuid_write_mutex);
335 static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
336 struct bkey *k, struct closure *parent)
338 struct closure *cl = &c->uuid_write;
339 struct uuid_entry *u;
340 unsigned int i;
341 char buf[80];
343 BUG_ON(!parent);
344 down(&c->uuid_write_mutex);
345 closure_init(cl, parent);
347 for (i = 0; i < KEY_PTRS(k); i++) {
348 struct bio *bio = bch_bbio_alloc(c);
350 bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
351 bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
353 bio->bi_end_io = uuid_endio;
354 bio->bi_private = cl;
355 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
356 bch_bio_map(bio, c->uuids);
358 bch_submit_bbio(bio, c, k, i);
360 if (op != REQ_OP_WRITE)
361 break;
364 bch_extent_to_text(buf, sizeof(buf), k);
365 pr_debug("%s UUIDs at %s", op == REQ_OP_WRITE ? "wrote" : "read", buf);
367 for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
368 if (!bch_is_zero(u->uuid, 16))
369 pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
370 u - c->uuids, u->uuid, u->label,
371 u->first_reg, u->last_reg, u->invalidated);
373 closure_return_with_destructor(cl, uuid_io_unlock);
376 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
378 struct bkey *k = &j->uuid_bucket;
380 if (__bch_btree_ptr_invalid(c, k))
381 return "bad uuid pointer";
383 bkey_copy(&c->uuid_bucket, k);
384 uuid_io(c, REQ_OP_READ, 0, k, cl);
386 if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
387 struct uuid_entry_v0 *u0 = (void *) c->uuids;
388 struct uuid_entry *u1 = (void *) c->uuids;
389 int i;
391 closure_sync(cl);
394 * Since the new uuid entry is bigger than the old, we have to
395 * convert starting at the highest memory address and work down
396 * in order to do it in place
399 for (i = c->nr_uuids - 1;
400 i >= 0;
401 --i) {
402 memcpy(u1[i].uuid, u0[i].uuid, 16);
403 memcpy(u1[i].label, u0[i].label, 32);
405 u1[i].first_reg = u0[i].first_reg;
406 u1[i].last_reg = u0[i].last_reg;
407 u1[i].invalidated = u0[i].invalidated;
409 u1[i].flags = 0;
410 u1[i].sectors = 0;
414 return NULL;
417 static int __uuid_write(struct cache_set *c)
419 BKEY_PADDED(key) k;
420 struct closure cl;
421 struct cache *ca;
423 closure_init_stack(&cl);
424 lockdep_assert_held(&bch_register_lock);
426 if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
427 return 1;
429 SET_KEY_SIZE(&k.key, c->sb.bucket_size);
430 uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
431 closure_sync(&cl);
433 /* Only one bucket used for uuid write */
434 ca = PTR_CACHE(c, &k.key, 0);
435 atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
437 bkey_copy(&c->uuid_bucket, &k.key);
438 bkey_put(c, &k.key);
439 return 0;
442 int bch_uuid_write(struct cache_set *c)
444 int ret = __uuid_write(c);
446 if (!ret)
447 bch_journal_meta(c, NULL);
449 return ret;
452 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
454 struct uuid_entry *u;
456 for (u = c->uuids;
457 u < c->uuids + c->nr_uuids; u++)
458 if (!memcmp(u->uuid, uuid, 16))
459 return u;
461 return NULL;
464 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
466 static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
468 return uuid_find(c, zero_uuid);
472 * Bucket priorities/gens:
474 * For each bucket, we store on disk its
475 * 8 bit gen
476 * 16 bit priority
478 * See alloc.c for an explanation of the gen. The priority is used to implement
479 * lru (and in the future other) cache replacement policies; for most purposes
480 * it's just an opaque integer.
482 * The gens and the priorities don't have a whole lot to do with each other, and
483 * it's actually the gens that must be written out at specific times - it's no
484 * big deal if the priorities don't get written, if we lose them we just reuse
485 * buckets in suboptimal order.
487 * On disk they're stored in a packed array, and in as many buckets are required
488 * to fit them all. The buckets we use to store them form a list; the journal
489 * header points to the first bucket, the first bucket points to the second
490 * bucket, et cetera.
492 * This code is used by the allocation code; periodically (whenever it runs out
493 * of buckets to allocate from) the allocation code will invalidate some
494 * buckets, but it can't use those buckets until their new gens are safely on
495 * disk.
498 static void prio_endio(struct bio *bio)
500 struct cache *ca = bio->bi_private;
502 cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
503 bch_bbio_free(bio, ca->set);
504 closure_put(&ca->prio);
507 static void prio_io(struct cache *ca, uint64_t bucket, int op,
508 unsigned long op_flags)
510 struct closure *cl = &ca->prio;
511 struct bio *bio = bch_bbio_alloc(ca->set);
513 closure_init_stack(cl);
515 bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
516 bio_set_dev(bio, ca->bdev);
517 bio->bi_iter.bi_size = bucket_bytes(ca);
519 bio->bi_end_io = prio_endio;
520 bio->bi_private = ca;
521 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
522 bch_bio_map(bio, ca->disk_buckets);
524 closure_bio_submit(ca->set, bio, &ca->prio);
525 closure_sync(cl);
528 int bch_prio_write(struct cache *ca, bool wait)
530 int i;
531 struct bucket *b;
532 struct closure cl;
534 pr_debug("free_prio=%zu, free_none=%zu, free_inc=%zu",
535 fifo_used(&ca->free[RESERVE_PRIO]),
536 fifo_used(&ca->free[RESERVE_NONE]),
537 fifo_used(&ca->free_inc));
540 * Pre-check if there are enough free buckets. In the non-blocking
541 * scenario it's better to fail early rather than starting to allocate
542 * buckets and do a cleanup later in case of failure.
544 if (!wait) {
545 size_t avail = fifo_used(&ca->free[RESERVE_PRIO]) +
546 fifo_used(&ca->free[RESERVE_NONE]);
547 if (prio_buckets(ca) > avail)
548 return -ENOMEM;
551 closure_init_stack(&cl);
553 lockdep_assert_held(&ca->set->bucket_lock);
555 ca->disk_buckets->seq++;
557 atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
558 &ca->meta_sectors_written);
560 for (i = prio_buckets(ca) - 1; i >= 0; --i) {
561 long bucket;
562 struct prio_set *p = ca->disk_buckets;
563 struct bucket_disk *d = p->data;
564 struct bucket_disk *end = d + prios_per_bucket(ca);
566 for (b = ca->buckets + i * prios_per_bucket(ca);
567 b < ca->buckets + ca->sb.nbuckets && d < end;
568 b++, d++) {
569 d->prio = cpu_to_le16(b->prio);
570 d->gen = b->gen;
573 p->next_bucket = ca->prio_buckets[i + 1];
574 p->magic = pset_magic(&ca->sb);
575 p->csum = bch_crc64(&p->magic, bucket_bytes(ca) - 8);
577 bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
578 BUG_ON(bucket == -1);
580 mutex_unlock(&ca->set->bucket_lock);
581 prio_io(ca, bucket, REQ_OP_WRITE, 0);
582 mutex_lock(&ca->set->bucket_lock);
584 ca->prio_buckets[i] = bucket;
585 atomic_dec_bug(&ca->buckets[bucket].pin);
588 mutex_unlock(&ca->set->bucket_lock);
590 bch_journal_meta(ca->set, &cl);
591 closure_sync(&cl);
593 mutex_lock(&ca->set->bucket_lock);
596 * Don't want the old priorities to get garbage collected until after we
597 * finish writing the new ones, and they're journalled
599 for (i = 0; i < prio_buckets(ca); i++) {
600 if (ca->prio_last_buckets[i])
601 __bch_bucket_free(ca,
602 &ca->buckets[ca->prio_last_buckets[i]]);
604 ca->prio_last_buckets[i] = ca->prio_buckets[i];
606 return 0;
609 static void prio_read(struct cache *ca, uint64_t bucket)
611 struct prio_set *p = ca->disk_buckets;
612 struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
613 struct bucket *b;
614 unsigned int bucket_nr = 0;
616 for (b = ca->buckets;
617 b < ca->buckets + ca->sb.nbuckets;
618 b++, d++) {
619 if (d == end) {
620 ca->prio_buckets[bucket_nr] = bucket;
621 ca->prio_last_buckets[bucket_nr] = bucket;
622 bucket_nr++;
624 prio_io(ca, bucket, REQ_OP_READ, 0);
626 if (p->csum !=
627 bch_crc64(&p->magic, bucket_bytes(ca) - 8))
628 pr_warn("bad csum reading priorities");
630 if (p->magic != pset_magic(&ca->sb))
631 pr_warn("bad magic reading priorities");
633 bucket = p->next_bucket;
634 d = p->data;
637 b->prio = le16_to_cpu(d->prio);
638 b->gen = b->last_gc = d->gen;
642 /* Bcache device */
644 static int open_dev(struct block_device *b, fmode_t mode)
646 struct bcache_device *d = b->bd_disk->private_data;
648 if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
649 return -ENXIO;
651 closure_get(&d->cl);
652 return 0;
655 static void release_dev(struct gendisk *b, fmode_t mode)
657 struct bcache_device *d = b->private_data;
659 closure_put(&d->cl);
662 static int ioctl_dev(struct block_device *b, fmode_t mode,
663 unsigned int cmd, unsigned long arg)
665 struct bcache_device *d = b->bd_disk->private_data;
667 return d->ioctl(d, mode, cmd, arg);
670 static const struct block_device_operations bcache_ops = {
671 .open = open_dev,
672 .release = release_dev,
673 .ioctl = ioctl_dev,
674 .owner = THIS_MODULE,
677 void bcache_device_stop(struct bcache_device *d)
679 if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
680 closure_queue(&d->cl);
683 static void bcache_device_unlink(struct bcache_device *d)
685 lockdep_assert_held(&bch_register_lock);
687 if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
688 unsigned int i;
689 struct cache *ca;
691 sysfs_remove_link(&d->c->kobj, d->name);
692 sysfs_remove_link(&d->kobj, "cache");
694 for_each_cache(ca, d->c, i)
695 bd_unlink_disk_holder(ca->bdev, d->disk);
699 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
700 const char *name)
702 unsigned int i;
703 struct cache *ca;
705 for_each_cache(ca, d->c, i)
706 bd_link_disk_holder(ca->bdev, d->disk);
708 snprintf(d->name, BCACHEDEVNAME_SIZE,
709 "%s%u", name, d->id);
711 WARN(sysfs_create_link(&d->kobj, &c->kobj, "cache") ||
712 sysfs_create_link(&c->kobj, &d->kobj, d->name),
713 "Couldn't create device <-> cache set symlinks");
715 clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
718 static void bcache_device_detach(struct bcache_device *d)
720 lockdep_assert_held(&bch_register_lock);
722 atomic_dec(&d->c->attached_dev_nr);
724 if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
725 struct uuid_entry *u = d->c->uuids + d->id;
727 SET_UUID_FLASH_ONLY(u, 0);
728 memcpy(u->uuid, invalid_uuid, 16);
729 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
730 bch_uuid_write(d->c);
733 bcache_device_unlink(d);
735 d->c->devices[d->id] = NULL;
736 closure_put(&d->c->caching);
737 d->c = NULL;
740 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
741 unsigned int id)
743 d->id = id;
744 d->c = c;
745 c->devices[id] = d;
747 if (id >= c->devices_max_used)
748 c->devices_max_used = id + 1;
750 closure_get(&c->caching);
753 static inline int first_minor_to_idx(int first_minor)
755 return (first_minor/BCACHE_MINORS);
758 static inline int idx_to_first_minor(int idx)
760 return (idx * BCACHE_MINORS);
763 static void bcache_device_free(struct bcache_device *d)
765 struct gendisk *disk = d->disk;
767 lockdep_assert_held(&bch_register_lock);
769 if (disk)
770 pr_info("%s stopped", disk->disk_name);
771 else
772 pr_err("bcache device (NULL gendisk) stopped");
774 if (d->c)
775 bcache_device_detach(d);
777 if (disk) {
778 bool disk_added = (disk->flags & GENHD_FL_UP) != 0;
780 if (disk_added)
781 del_gendisk(disk);
783 if (disk->queue)
784 blk_cleanup_queue(disk->queue);
786 ida_simple_remove(&bcache_device_idx,
787 first_minor_to_idx(disk->first_minor));
788 if (disk_added)
789 put_disk(disk);
792 bioset_exit(&d->bio_split);
793 kvfree(d->full_dirty_stripes);
794 kvfree(d->stripe_sectors_dirty);
796 closure_debug_destroy(&d->cl);
799 static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
800 sector_t sectors)
802 struct request_queue *q;
803 const size_t max_stripes = min_t(size_t, INT_MAX,
804 SIZE_MAX / sizeof(atomic_t));
805 size_t n;
806 int idx;
808 if (!d->stripe_size)
809 d->stripe_size = 1 << 31;
811 d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
813 if (!d->nr_stripes || d->nr_stripes > max_stripes) {
814 pr_err("nr_stripes too large or invalid: %u (start sector beyond end of disk?)",
815 (unsigned int)d->nr_stripes);
816 return -ENOMEM;
819 n = d->nr_stripes * sizeof(atomic_t);
820 d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
821 if (!d->stripe_sectors_dirty)
822 return -ENOMEM;
824 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
825 d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
826 if (!d->full_dirty_stripes)
827 return -ENOMEM;
829 idx = ida_simple_get(&bcache_device_idx, 0,
830 BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
831 if (idx < 0)
832 return idx;
834 if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
835 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
836 goto err;
838 d->disk = alloc_disk(BCACHE_MINORS);
839 if (!d->disk)
840 goto err;
842 set_capacity(d->disk, sectors);
843 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
845 d->disk->major = bcache_major;
846 d->disk->first_minor = idx_to_first_minor(idx);
847 d->disk->fops = &bcache_ops;
848 d->disk->private_data = d;
850 q = blk_alloc_queue(GFP_KERNEL);
851 if (!q)
852 return -ENOMEM;
854 blk_queue_make_request(q, NULL);
855 d->disk->queue = q;
856 q->queuedata = d;
857 q->backing_dev_info->congested_data = d;
858 q->limits.max_hw_sectors = UINT_MAX;
859 q->limits.max_sectors = UINT_MAX;
860 q->limits.max_segment_size = UINT_MAX;
861 q->limits.max_segments = BIO_MAX_PAGES;
862 blk_queue_max_discard_sectors(q, UINT_MAX);
863 q->limits.discard_granularity = 512;
864 q->limits.io_min = block_size;
865 q->limits.logical_block_size = block_size;
866 q->limits.physical_block_size = block_size;
867 blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
868 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
869 blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
871 blk_queue_write_cache(q, true, true);
873 return 0;
875 err:
876 ida_simple_remove(&bcache_device_idx, idx);
877 return -ENOMEM;
881 /* Cached device */
883 static void calc_cached_dev_sectors(struct cache_set *c)
885 uint64_t sectors = 0;
886 struct cached_dev *dc;
888 list_for_each_entry(dc, &c->cached_devs, list)
889 sectors += bdev_sectors(dc->bdev);
891 c->cached_dev_sectors = sectors;
894 #define BACKING_DEV_OFFLINE_TIMEOUT 5
895 static int cached_dev_status_update(void *arg)
897 struct cached_dev *dc = arg;
898 struct request_queue *q;
901 * If this delayed worker is stopping outside, directly quit here.
902 * dc->io_disable might be set via sysfs interface, so check it
903 * here too.
905 while (!kthread_should_stop() && !dc->io_disable) {
906 q = bdev_get_queue(dc->bdev);
907 if (blk_queue_dying(q))
908 dc->offline_seconds++;
909 else
910 dc->offline_seconds = 0;
912 if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
913 pr_err("%s: device offline for %d seconds",
914 dc->backing_dev_name,
915 BACKING_DEV_OFFLINE_TIMEOUT);
916 pr_err("%s: disable I/O request due to backing "
917 "device offline", dc->disk.name);
918 dc->io_disable = true;
919 /* let others know earlier that io_disable is true */
920 smp_mb();
921 bcache_device_stop(&dc->disk);
922 break;
924 schedule_timeout_interruptible(HZ);
927 wait_for_kthread_stop();
928 return 0;
932 void bch_cached_dev_run(struct cached_dev *dc)
934 struct bcache_device *d = &dc->disk;
935 char buf[SB_LABEL_SIZE + 1];
936 char *env[] = {
937 "DRIVER=bcache",
938 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
939 NULL,
940 NULL,
943 memcpy(buf, dc->sb.label, SB_LABEL_SIZE);
944 buf[SB_LABEL_SIZE] = '\0';
945 env[2] = kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf);
947 if (atomic_xchg(&dc->running, 1)) {
948 kfree(env[1]);
949 kfree(env[2]);
950 return;
953 if (!d->c &&
954 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
955 struct closure cl;
957 closure_init_stack(&cl);
959 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
960 bch_write_bdev_super(dc, &cl);
961 closure_sync(&cl);
964 add_disk(d->disk);
965 bd_link_disk_holder(dc->bdev, dc->disk.disk);
967 * won't show up in the uevent file, use udevadm monitor -e instead
968 * only class / kset properties are persistent
970 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
971 kfree(env[1]);
972 kfree(env[2]);
974 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
975 sysfs_create_link(&disk_to_dev(d->disk)->kobj, &d->kobj, "bcache"))
976 pr_debug("error creating sysfs link");
978 dc->status_update_thread = kthread_run(cached_dev_status_update,
979 dc, "bcache_status_update");
980 if (IS_ERR(dc->status_update_thread)) {
981 pr_warn("failed to create bcache_status_update kthread, "
982 "continue to run without monitoring backing "
983 "device status");
988 * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
989 * work dc->writeback_rate_update is running. Wait until the routine
990 * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
991 * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
992 * seconds, give up waiting here and continue to cancel it too.
994 static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
996 int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
998 do {
999 if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
1000 &dc->disk.flags))
1001 break;
1002 time_out--;
1003 schedule_timeout_interruptible(1);
1004 } while (time_out > 0);
1006 if (time_out == 0)
1007 pr_warn("give up waiting for dc->writeback_write_update to quit");
1009 cancel_delayed_work_sync(&dc->writeback_rate_update);
1012 static void cached_dev_detach_finish(struct work_struct *w)
1014 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
1015 struct closure cl;
1017 closure_init_stack(&cl);
1019 BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
1020 BUG_ON(refcount_read(&dc->count));
1022 mutex_lock(&bch_register_lock);
1024 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1025 cancel_writeback_rate_update_dwork(dc);
1027 if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
1028 kthread_stop(dc->writeback_thread);
1029 dc->writeback_thread = NULL;
1032 memset(&dc->sb.set_uuid, 0, 16);
1033 SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
1035 bch_write_bdev_super(dc, &cl);
1036 closure_sync(&cl);
1038 calc_cached_dev_sectors(dc->disk.c);
1039 bcache_device_detach(&dc->disk);
1040 list_move(&dc->list, &uncached_devices);
1042 clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
1043 clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
1045 mutex_unlock(&bch_register_lock);
1047 pr_info("Caching disabled for %s", dc->backing_dev_name);
1049 /* Drop ref we took in cached_dev_detach() */
1050 closure_put(&dc->disk.cl);
1053 void bch_cached_dev_detach(struct cached_dev *dc)
1055 lockdep_assert_held(&bch_register_lock);
1057 if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1058 return;
1060 if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
1061 return;
1064 * Block the device from being closed and freed until we're finished
1065 * detaching
1067 closure_get(&dc->disk.cl);
1069 bch_writeback_queue(dc);
1071 cached_dev_put(dc);
1074 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
1075 uint8_t *set_uuid)
1077 uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
1078 struct uuid_entry *u;
1079 struct cached_dev *exist_dc, *t;
1081 if ((set_uuid && memcmp(set_uuid, c->sb.set_uuid, 16)) ||
1082 (!set_uuid && memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16)))
1083 return -ENOENT;
1085 if (dc->disk.c) {
1086 pr_err("Can't attach %s: already attached",
1087 dc->backing_dev_name);
1088 return -EINVAL;
1091 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
1092 pr_err("Can't attach %s: shutting down",
1093 dc->backing_dev_name);
1094 return -EINVAL;
1097 if (dc->sb.block_size < c->sb.block_size) {
1098 /* Will die */
1099 pr_err("Couldn't attach %s: block size less than set's block size",
1100 dc->backing_dev_name);
1101 return -EINVAL;
1104 /* Check whether already attached */
1105 list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
1106 if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
1107 pr_err("Tried to attach %s but duplicate UUID already attached",
1108 dc->backing_dev_name);
1110 return -EINVAL;
1114 u = uuid_find(c, dc->sb.uuid);
1116 if (u &&
1117 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1118 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1119 memcpy(u->uuid, invalid_uuid, 16);
1120 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1121 u = NULL;
1124 if (!u) {
1125 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1126 pr_err("Couldn't find uuid for %s in set",
1127 dc->backing_dev_name);
1128 return -ENOENT;
1131 u = uuid_find_empty(c);
1132 if (!u) {
1133 pr_err("Not caching %s, no room for UUID",
1134 dc->backing_dev_name);
1135 return -EINVAL;
1140 * Deadlocks since we're called via sysfs...
1141 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1144 if (bch_is_zero(u->uuid, 16)) {
1145 struct closure cl;
1147 closure_init_stack(&cl);
1149 memcpy(u->uuid, dc->sb.uuid, 16);
1150 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1151 u->first_reg = u->last_reg = rtime;
1152 bch_uuid_write(c);
1154 memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1155 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1157 bch_write_bdev_super(dc, &cl);
1158 closure_sync(&cl);
1159 } else {
1160 u->last_reg = rtime;
1161 bch_uuid_write(c);
1164 bcache_device_attach(&dc->disk, c, u - c->uuids);
1165 list_move(&dc->list, &c->cached_devs);
1166 calc_cached_dev_sectors(c);
1169 * dc->c must be set before dc->count != 0 - paired with the mb in
1170 * cached_dev_get()
1172 smp_wmb();
1173 refcount_set(&dc->count, 1);
1175 /* Block writeback thread, but spawn it */
1176 down_write(&dc->writeback_lock);
1177 if (bch_cached_dev_writeback_start(dc)) {
1178 up_write(&dc->writeback_lock);
1179 return -ENOMEM;
1182 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1183 atomic_set(&dc->has_dirty, 1);
1184 bch_writeback_queue(dc);
1187 bch_sectors_dirty_init(&dc->disk);
1189 bch_cached_dev_run(dc);
1190 bcache_device_link(&dc->disk, c, "bdev");
1191 atomic_inc(&c->attached_dev_nr);
1193 /* Allow the writeback thread to proceed */
1194 up_write(&dc->writeback_lock);
1196 pr_info("Caching %s as %s on set %pU",
1197 dc->backing_dev_name,
1198 dc->disk.disk->disk_name,
1199 dc->disk.c->sb.set_uuid);
1200 return 0;
1203 void bch_cached_dev_release(struct kobject *kobj)
1205 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1206 disk.kobj);
1207 kfree(dc);
1208 module_put(THIS_MODULE);
1211 static void cached_dev_free(struct closure *cl)
1213 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1215 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1216 cancel_writeback_rate_update_dwork(dc);
1218 if (!IS_ERR_OR_NULL(dc->writeback_thread))
1219 kthread_stop(dc->writeback_thread);
1220 if (!IS_ERR_OR_NULL(dc->status_update_thread))
1221 kthread_stop(dc->status_update_thread);
1223 mutex_lock(&bch_register_lock);
1225 if (atomic_read(&dc->running))
1226 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1227 bcache_device_free(&dc->disk);
1228 list_del(&dc->list);
1230 mutex_unlock(&bch_register_lock);
1232 if (dc->sb_bio.bi_inline_vecs[0].bv_page)
1233 put_page(bio_first_page_all(&dc->sb_bio));
1235 if (!IS_ERR_OR_NULL(dc->bdev))
1236 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1238 wake_up(&unregister_wait);
1240 kobject_put(&dc->disk.kobj);
1243 static void cached_dev_flush(struct closure *cl)
1245 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1246 struct bcache_device *d = &dc->disk;
1248 mutex_lock(&bch_register_lock);
1249 bcache_device_unlink(d);
1250 mutex_unlock(&bch_register_lock);
1252 bch_cache_accounting_destroy(&dc->accounting);
1253 kobject_del(&d->kobj);
1255 continue_at(cl, cached_dev_free, system_wq);
1258 static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1260 int ret;
1261 struct io *io;
1262 struct request_queue *q = bdev_get_queue(dc->bdev);
1264 __module_get(THIS_MODULE);
1265 INIT_LIST_HEAD(&dc->list);
1266 closure_init(&dc->disk.cl, NULL);
1267 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1268 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1269 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1270 sema_init(&dc->sb_write_mutex, 1);
1271 INIT_LIST_HEAD(&dc->io_lru);
1272 spin_lock_init(&dc->io_lock);
1273 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1275 dc->sequential_cutoff = 4 << 20;
1277 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1278 list_add(&io->lru, &dc->io_lru);
1279 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1282 dc->disk.stripe_size = q->limits.io_opt >> 9;
1284 if (dc->disk.stripe_size)
1285 dc->partial_stripes_expensive =
1286 q->limits.raid_partial_stripes_expensive;
1288 ret = bcache_device_init(&dc->disk, block_size,
1289 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1290 if (ret)
1291 return ret;
1293 dc->disk.disk->queue->backing_dev_info->ra_pages =
1294 max(dc->disk.disk->queue->backing_dev_info->ra_pages,
1295 q->backing_dev_info->ra_pages);
1297 atomic_set(&dc->io_errors, 0);
1298 dc->io_disable = false;
1299 dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
1300 /* default to auto */
1301 dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
1303 bch_cached_dev_request_init(dc);
1304 bch_cached_dev_writeback_init(dc);
1305 return 0;
1308 /* Cached device - bcache superblock */
1310 static void register_bdev(struct cache_sb *sb, struct page *sb_page,
1311 struct block_device *bdev,
1312 struct cached_dev *dc)
1314 const char *err = "cannot allocate memory";
1315 struct cache_set *c;
1317 bdevname(bdev, dc->backing_dev_name);
1318 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1319 dc->bdev = bdev;
1320 dc->bdev->bd_holder = dc;
1322 bio_init(&dc->sb_bio, dc->sb_bio.bi_inline_vecs, 1);
1323 bio_first_bvec_all(&dc->sb_bio)->bv_page = sb_page;
1324 get_page(sb_page);
1327 if (cached_dev_init(dc, sb->block_size << 9))
1328 goto err;
1330 err = "error creating kobject";
1331 if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1332 "bcache"))
1333 goto err;
1334 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1335 goto err;
1337 pr_info("registered backing device %s", dc->backing_dev_name);
1339 list_add(&dc->list, &uncached_devices);
1340 /* attach to a matched cache set if it exists */
1341 list_for_each_entry(c, &bch_cache_sets, list)
1342 bch_cached_dev_attach(dc, c, NULL);
1344 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1345 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE)
1346 bch_cached_dev_run(dc);
1348 return;
1349 err:
1350 pr_notice("error %s: %s", dc->backing_dev_name, err);
1351 bcache_device_stop(&dc->disk);
1354 /* Flash only volumes */
1356 void bch_flash_dev_release(struct kobject *kobj)
1358 struct bcache_device *d = container_of(kobj, struct bcache_device,
1359 kobj);
1360 kfree(d);
1363 static void flash_dev_free(struct closure *cl)
1365 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1367 mutex_lock(&bch_register_lock);
1368 atomic_long_sub(bcache_dev_sectors_dirty(d),
1369 &d->c->flash_dev_dirty_sectors);
1370 bcache_device_free(d);
1371 mutex_unlock(&bch_register_lock);
1372 kobject_put(&d->kobj);
1375 static void flash_dev_flush(struct closure *cl)
1377 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1379 mutex_lock(&bch_register_lock);
1380 bcache_device_unlink(d);
1381 mutex_unlock(&bch_register_lock);
1382 kobject_del(&d->kobj);
1383 continue_at(cl, flash_dev_free, system_wq);
1386 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1388 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1389 GFP_KERNEL);
1390 if (!d)
1391 return -ENOMEM;
1393 closure_init(&d->cl, NULL);
1394 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1396 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1398 if (bcache_device_init(d, block_bytes(c), u->sectors))
1399 goto err;
1401 bcache_device_attach(d, c, u - c->uuids);
1402 bch_sectors_dirty_init(d);
1403 bch_flash_dev_request_init(d);
1404 add_disk(d->disk);
1406 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1407 goto err;
1409 bcache_device_link(d, c, "volume");
1411 return 0;
1412 err:
1413 kobject_put(&d->kobj);
1414 return -ENOMEM;
1417 static int flash_devs_run(struct cache_set *c)
1419 int ret = 0;
1420 struct uuid_entry *u;
1422 for (u = c->uuids;
1423 u < c->uuids + c->nr_uuids && !ret;
1424 u++)
1425 if (UUID_FLASH_ONLY(u))
1426 ret = flash_dev_run(c, u);
1428 return ret;
1431 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1433 struct uuid_entry *u;
1435 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1436 return -EINTR;
1438 if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1439 return -EPERM;
1441 u = uuid_find_empty(c);
1442 if (!u) {
1443 pr_err("Can't create volume, no room for UUID");
1444 return -EINVAL;
1447 get_random_bytes(u->uuid, 16);
1448 memset(u->label, 0, 32);
1449 u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1451 SET_UUID_FLASH_ONLY(u, 1);
1452 u->sectors = size >> 9;
1454 bch_uuid_write(c);
1456 return flash_dev_run(c, u);
1459 bool bch_cached_dev_error(struct cached_dev *dc)
1461 if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1462 return false;
1464 dc->io_disable = true;
1465 /* make others know io_disable is true earlier */
1466 smp_mb();
1468 pr_err("stop %s: too many IO errors on backing device %s\n",
1469 dc->disk.disk->disk_name, dc->backing_dev_name);
1471 bcache_device_stop(&dc->disk);
1472 return true;
1475 /* Cache set */
1477 __printf(2, 3)
1478 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1480 va_list args;
1482 if (c->on_error != ON_ERROR_PANIC &&
1483 test_bit(CACHE_SET_STOPPING, &c->flags))
1484 return false;
1486 if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1487 pr_info("CACHE_SET_IO_DISABLE already set");
1490 * XXX: we can be called from atomic context
1491 * acquire_console_sem();
1494 pr_err("bcache: error on %pU: ", c->sb.set_uuid);
1496 va_start(args, fmt);
1497 vprintk(fmt, args);
1498 va_end(args);
1500 pr_err(", disabling caching\n");
1502 if (c->on_error == ON_ERROR_PANIC)
1503 panic("panic forced after error\n");
1505 bch_cache_set_unregister(c);
1506 return true;
1509 void bch_cache_set_release(struct kobject *kobj)
1511 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1513 kfree(c);
1514 module_put(THIS_MODULE);
1517 static void cache_set_free(struct closure *cl)
1519 struct cache_set *c = container_of(cl, struct cache_set, cl);
1520 struct cache *ca;
1521 unsigned int i;
1523 debugfs_remove(c->debug);
1525 bch_open_buckets_free(c);
1526 bch_btree_cache_free(c);
1527 bch_journal_free(c);
1529 mutex_lock(&bch_register_lock);
1530 for_each_cache(ca, c, i)
1531 if (ca) {
1532 ca->set = NULL;
1533 c->cache[ca->sb.nr_this_dev] = NULL;
1534 kobject_put(&ca->kobj);
1537 bch_bset_sort_state_free(&c->sort);
1538 free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1540 if (c->moving_gc_wq)
1541 destroy_workqueue(c->moving_gc_wq);
1542 bioset_exit(&c->bio_split);
1543 mempool_exit(&c->fill_iter);
1544 mempool_exit(&c->bio_meta);
1545 mempool_exit(&c->search);
1546 kfree(c->devices);
1548 list_del(&c->list);
1549 mutex_unlock(&bch_register_lock);
1551 pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1552 wake_up(&unregister_wait);
1554 closure_debug_destroy(&c->cl);
1555 kobject_put(&c->kobj);
1558 static void cache_set_flush(struct closure *cl)
1560 struct cache_set *c = container_of(cl, struct cache_set, caching);
1561 struct cache *ca;
1562 struct btree *b;
1563 unsigned int i;
1565 bch_cache_accounting_destroy(&c->accounting);
1567 kobject_put(&c->internal);
1568 kobject_del(&c->kobj);
1570 if (!IS_ERR_OR_NULL(c->gc_thread))
1571 kthread_stop(c->gc_thread);
1573 if (!IS_ERR_OR_NULL(c->root))
1574 list_add(&c->root->list, &c->btree_cache);
1576 /* Should skip this if we're unregistering because of an error */
1577 list_for_each_entry(b, &c->btree_cache, list) {
1578 mutex_lock(&b->write_lock);
1579 if (btree_node_dirty(b))
1580 __bch_btree_node_write(b, NULL);
1581 mutex_unlock(&b->write_lock);
1584 for_each_cache(ca, c, i)
1585 if (ca->alloc_thread)
1586 kthread_stop(ca->alloc_thread);
1588 if (c->journal.cur) {
1589 cancel_delayed_work_sync(&c->journal.work);
1590 /* flush last journal entry if needed */
1591 c->journal.work.work.func(&c->journal.work.work);
1594 closure_return(cl);
1598 * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1599 * cache set is unregistering due to too many I/O errors. In this condition,
1600 * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1601 * value and whether the broken cache has dirty data:
1603 * dc->stop_when_cache_set_failed dc->has_dirty stop bcache device
1604 * BCH_CACHED_STOP_AUTO 0 NO
1605 * BCH_CACHED_STOP_AUTO 1 YES
1606 * BCH_CACHED_DEV_STOP_ALWAYS 0 YES
1607 * BCH_CACHED_DEV_STOP_ALWAYS 1 YES
1609 * The expected behavior is, if stop_when_cache_set_failed is configured to
1610 * "auto" via sysfs interface, the bcache device will not be stopped if the
1611 * backing device is clean on the broken cache device.
1613 static void conditional_stop_bcache_device(struct cache_set *c,
1614 struct bcache_device *d,
1615 struct cached_dev *dc)
1617 if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1618 pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.",
1619 d->disk->disk_name, c->sb.set_uuid);
1620 bcache_device_stop(d);
1621 } else if (atomic_read(&dc->has_dirty)) {
1623 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1624 * and dc->has_dirty == 1
1626 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.",
1627 d->disk->disk_name);
1629 * There might be a small time gap that cache set is
1630 * released but bcache device is not. Inside this time
1631 * gap, regular I/O requests will directly go into
1632 * backing device as no cache set attached to. This
1633 * behavior may also introduce potential inconsistence
1634 * data in writeback mode while cache is dirty.
1635 * Therefore before calling bcache_device_stop() due
1636 * to a broken cache device, dc->io_disable should be
1637 * explicitly set to true.
1639 dc->io_disable = true;
1640 /* make others know io_disable is true earlier */
1641 smp_mb();
1642 bcache_device_stop(d);
1643 } else {
1645 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1646 * and dc->has_dirty == 0
1648 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.",
1649 d->disk->disk_name);
1653 static void __cache_set_unregister(struct closure *cl)
1655 struct cache_set *c = container_of(cl, struct cache_set, caching);
1656 struct cached_dev *dc;
1657 struct bcache_device *d;
1658 size_t i;
1660 mutex_lock(&bch_register_lock);
1662 for (i = 0; i < c->devices_max_used; i++) {
1663 d = c->devices[i];
1664 if (!d)
1665 continue;
1667 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1668 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1669 dc = container_of(d, struct cached_dev, disk);
1670 bch_cached_dev_detach(dc);
1671 if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1672 conditional_stop_bcache_device(c, d, dc);
1673 } else {
1674 bcache_device_stop(d);
1678 mutex_unlock(&bch_register_lock);
1680 continue_at(cl, cache_set_flush, system_wq);
1683 void bch_cache_set_stop(struct cache_set *c)
1685 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1686 closure_queue(&c->caching);
1689 void bch_cache_set_unregister(struct cache_set *c)
1691 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1692 bch_cache_set_stop(c);
1695 #define alloc_bucket_pages(gfp, c) \
1696 ((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1698 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1700 int iter_size;
1701 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1703 if (!c)
1704 return NULL;
1706 __module_get(THIS_MODULE);
1707 closure_init(&c->cl, NULL);
1708 set_closure_fn(&c->cl, cache_set_free, system_wq);
1710 closure_init(&c->caching, &c->cl);
1711 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1713 /* Maybe create continue_at_noreturn() and use it here? */
1714 closure_set_stopped(&c->cl);
1715 closure_put(&c->cl);
1717 kobject_init(&c->kobj, &bch_cache_set_ktype);
1718 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1720 bch_cache_accounting_init(&c->accounting, &c->cl);
1722 memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1723 c->sb.block_size = sb->block_size;
1724 c->sb.bucket_size = sb->bucket_size;
1725 c->sb.nr_in_set = sb->nr_in_set;
1726 c->sb.last_mount = sb->last_mount;
1727 c->bucket_bits = ilog2(sb->bucket_size);
1728 c->block_bits = ilog2(sb->block_size);
1729 c->nr_uuids = bucket_bytes(c) / sizeof(struct uuid_entry);
1730 c->devices_max_used = 0;
1731 atomic_set(&c->attached_dev_nr, 0);
1732 c->btree_pages = bucket_pages(c);
1733 if (c->btree_pages > BTREE_MAX_PAGES)
1734 c->btree_pages = max_t(int, c->btree_pages / 4,
1735 BTREE_MAX_PAGES);
1737 sema_init(&c->sb_write_mutex, 1);
1738 mutex_init(&c->bucket_lock);
1739 init_waitqueue_head(&c->btree_cache_wait);
1740 init_waitqueue_head(&c->bucket_wait);
1741 init_waitqueue_head(&c->gc_wait);
1742 sema_init(&c->uuid_write_mutex, 1);
1744 spin_lock_init(&c->btree_gc_time.lock);
1745 spin_lock_init(&c->btree_split_time.lock);
1746 spin_lock_init(&c->btree_read_time.lock);
1748 bch_moving_init_cache_set(c);
1750 INIT_LIST_HEAD(&c->list);
1751 INIT_LIST_HEAD(&c->cached_devs);
1752 INIT_LIST_HEAD(&c->btree_cache);
1753 INIT_LIST_HEAD(&c->btree_cache_freeable);
1754 INIT_LIST_HEAD(&c->btree_cache_freed);
1755 INIT_LIST_HEAD(&c->data_buckets);
1757 iter_size = (sb->bucket_size / sb->block_size + 1) *
1758 sizeof(struct btree_iter_set);
1760 if (!(c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL)) ||
1761 mempool_init_slab_pool(&c->search, 32, bch_search_cache) ||
1762 mempool_init_kmalloc_pool(&c->bio_meta, 2,
1763 sizeof(struct bbio) + sizeof(struct bio_vec) *
1764 bucket_pages(c)) ||
1765 mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
1766 bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1767 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER) ||
1768 !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1769 !(c->moving_gc_wq = alloc_workqueue("bcache_gc",
1770 WQ_MEM_RECLAIM, 0)) ||
1771 bch_journal_alloc(c) ||
1772 bch_btree_cache_alloc(c) ||
1773 bch_open_buckets_alloc(c) ||
1774 bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1775 goto err;
1777 c->congested_read_threshold_us = 2000;
1778 c->congested_write_threshold_us = 20000;
1779 c->error_limit = DEFAULT_IO_ERROR_LIMIT;
1780 WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1782 return c;
1783 err:
1784 bch_cache_set_unregister(c);
1785 return NULL;
1788 static int run_cache_set(struct cache_set *c)
1790 const char *err = "cannot allocate memory";
1791 struct cached_dev *dc, *t;
1792 struct cache *ca;
1793 struct closure cl;
1794 unsigned int i;
1795 LIST_HEAD(journal);
1796 struct journal_replay *l;
1798 closure_init_stack(&cl);
1800 for_each_cache(ca, c, i)
1801 c->nbuckets += ca->sb.nbuckets;
1802 set_gc_sectors(c);
1804 if (CACHE_SYNC(&c->sb)) {
1805 struct bkey *k;
1806 struct jset *j;
1808 err = "cannot allocate memory for journal";
1809 if (bch_journal_read(c, &journal))
1810 goto err;
1812 pr_debug("btree_journal_read() done");
1814 err = "no journal entries found";
1815 if (list_empty(&journal))
1816 goto err;
1818 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1820 err = "IO error reading priorities";
1821 for_each_cache(ca, c, i)
1822 prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1825 * If prio_read() fails it'll call cache_set_error and we'll
1826 * tear everything down right away, but if we perhaps checked
1827 * sooner we could avoid journal replay.
1830 k = &j->btree_root;
1832 err = "bad btree root";
1833 if (__bch_btree_ptr_invalid(c, k))
1834 goto err;
1836 err = "error reading btree root";
1837 c->root = bch_btree_node_get(c, NULL, k,
1838 j->btree_level,
1839 true, NULL);
1840 if (IS_ERR_OR_NULL(c->root))
1841 goto err;
1843 list_del_init(&c->root->list);
1844 rw_unlock(true, c->root);
1846 err = uuid_read(c, j, &cl);
1847 if (err)
1848 goto err;
1850 err = "error in recovery";
1851 if (bch_btree_check(c))
1852 goto err;
1854 bch_journal_mark(c, &journal);
1855 bch_initial_gc_finish(c);
1856 pr_debug("btree_check() done");
1859 * bcache_journal_next() can't happen sooner, or
1860 * btree_gc_finish() will give spurious errors about last_gc >
1861 * gc_gen - this is a hack but oh well.
1863 bch_journal_next(&c->journal);
1865 err = "error starting allocator thread";
1866 for_each_cache(ca, c, i)
1867 if (bch_cache_allocator_start(ca))
1868 goto err;
1871 * First place it's safe to allocate: btree_check() and
1872 * btree_gc_finish() have to run before we have buckets to
1873 * allocate, and bch_bucket_alloc_set() might cause a journal
1874 * entry to be written so bcache_journal_next() has to be called
1875 * first.
1877 * If the uuids were in the old format we have to rewrite them
1878 * before the next journal entry is written:
1880 if (j->version < BCACHE_JSET_VERSION_UUID)
1881 __uuid_write(c);
1883 err = "bcache: replay journal failed";
1884 if (bch_journal_replay(c, &journal))
1885 goto err;
1886 } else {
1887 pr_notice("invalidating existing data");
1889 for_each_cache(ca, c, i) {
1890 unsigned int j;
1892 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1893 2, SB_JOURNAL_BUCKETS);
1895 for (j = 0; j < ca->sb.keys; j++)
1896 ca->sb.d[j] = ca->sb.first_bucket + j;
1899 bch_initial_gc_finish(c);
1901 err = "error starting allocator thread";
1902 for_each_cache(ca, c, i)
1903 if (bch_cache_allocator_start(ca))
1904 goto err;
1906 mutex_lock(&c->bucket_lock);
1907 for_each_cache(ca, c, i)
1908 bch_prio_write(ca, true);
1909 mutex_unlock(&c->bucket_lock);
1911 err = "cannot allocate new UUID bucket";
1912 if (__uuid_write(c))
1913 goto err;
1915 err = "cannot allocate new btree root";
1916 c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
1917 if (IS_ERR_OR_NULL(c->root))
1918 goto err;
1920 mutex_lock(&c->root->write_lock);
1921 bkey_copy_key(&c->root->key, &MAX_KEY);
1922 bch_btree_node_write(c->root, &cl);
1923 mutex_unlock(&c->root->write_lock);
1925 bch_btree_set_root(c->root);
1926 rw_unlock(true, c->root);
1929 * We don't want to write the first journal entry until
1930 * everything is set up - fortunately journal entries won't be
1931 * written until the SET_CACHE_SYNC() here:
1933 SET_CACHE_SYNC(&c->sb, true);
1935 bch_journal_next(&c->journal);
1936 bch_journal_meta(c, &cl);
1939 err = "error starting gc thread";
1940 if (bch_gc_thread_start(c))
1941 goto err;
1943 closure_sync(&cl);
1944 c->sb.last_mount = (u32)ktime_get_real_seconds();
1945 bcache_write_super(c);
1947 list_for_each_entry_safe(dc, t, &uncached_devices, list)
1948 bch_cached_dev_attach(dc, c, NULL);
1950 flash_devs_run(c);
1952 set_bit(CACHE_SET_RUNNING, &c->flags);
1953 return 0;
1954 err:
1955 while (!list_empty(&journal)) {
1956 l = list_first_entry(&journal, struct journal_replay, list);
1957 list_del(&l->list);
1958 kfree(l);
1961 closure_sync(&cl);
1962 /* XXX: test this, it's broken */
1963 bch_cache_set_error(c, "%s", err);
1965 return -EIO;
1968 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
1970 return ca->sb.block_size == c->sb.block_size &&
1971 ca->sb.bucket_size == c->sb.bucket_size &&
1972 ca->sb.nr_in_set == c->sb.nr_in_set;
1975 static const char *register_cache_set(struct cache *ca)
1977 char buf[12];
1978 const char *err = "cannot allocate memory";
1979 struct cache_set *c;
1981 list_for_each_entry(c, &bch_cache_sets, list)
1982 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
1983 if (c->cache[ca->sb.nr_this_dev])
1984 return "duplicate cache set member";
1986 if (!can_attach_cache(ca, c))
1987 return "cache sb does not match set";
1989 if (!CACHE_SYNC(&ca->sb))
1990 SET_CACHE_SYNC(&c->sb, false);
1992 goto found;
1995 c = bch_cache_set_alloc(&ca->sb);
1996 if (!c)
1997 return err;
1999 err = "error creating kobject";
2000 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
2001 kobject_add(&c->internal, &c->kobj, "internal"))
2002 goto err;
2004 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2005 goto err;
2007 bch_debug_init_cache_set(c);
2009 list_add(&c->list, &bch_cache_sets);
2010 found:
2011 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2012 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2013 sysfs_create_link(&c->kobj, &ca->kobj, buf))
2014 goto err;
2016 if (ca->sb.seq > c->sb.seq) {
2017 c->sb.version = ca->sb.version;
2018 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
2019 c->sb.flags = ca->sb.flags;
2020 c->sb.seq = ca->sb.seq;
2021 pr_debug("set version = %llu", c->sb.version);
2024 kobject_get(&ca->kobj);
2025 ca->set = c;
2026 ca->set->cache[ca->sb.nr_this_dev] = ca;
2027 c->cache_by_alloc[c->caches_loaded++] = ca;
2029 if (c->caches_loaded == c->sb.nr_in_set) {
2030 err = "failed to run cache set";
2031 if (run_cache_set(c) < 0)
2032 goto err;
2035 return NULL;
2036 err:
2037 bch_cache_set_unregister(c);
2038 return err;
2041 /* Cache device */
2043 void bch_cache_release(struct kobject *kobj)
2045 struct cache *ca = container_of(kobj, struct cache, kobj);
2046 unsigned int i;
2048 if (ca->set) {
2049 BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
2050 ca->set->cache[ca->sb.nr_this_dev] = NULL;
2053 free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
2054 kfree(ca->prio_buckets);
2055 vfree(ca->buckets);
2057 free_heap(&ca->heap);
2058 free_fifo(&ca->free_inc);
2060 for (i = 0; i < RESERVE_NR; i++)
2061 free_fifo(&ca->free[i]);
2063 if (ca->sb_bio.bi_inline_vecs[0].bv_page)
2064 put_page(bio_first_page_all(&ca->sb_bio));
2066 if (!IS_ERR_OR_NULL(ca->bdev))
2067 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2069 kfree(ca);
2070 module_put(THIS_MODULE);
2073 static int cache_alloc(struct cache *ca)
2075 size_t free;
2076 size_t btree_buckets;
2077 struct bucket *b;
2079 __module_get(THIS_MODULE);
2080 kobject_init(&ca->kobj, &bch_cache_ktype);
2082 bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2085 * when ca->sb.njournal_buckets is not zero, journal exists,
2086 * and in bch_journal_replay(), tree node may split,
2087 * so bucket of RESERVE_BTREE type is needed,
2088 * the worst situation is all journal buckets are valid journal,
2089 * and all the keys need to replay,
2090 * so the number of RESERVE_BTREE type buckets should be as much
2091 * as journal buckets
2093 btree_buckets = ca->sb.njournal_buckets ?: 8;
2094 free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
2096 if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets, GFP_KERNEL) ||
2097 !init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca), GFP_KERNEL) ||
2098 !init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL) ||
2099 !init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL) ||
2100 !init_fifo(&ca->free_inc, free << 2, GFP_KERNEL) ||
2101 !init_heap(&ca->heap, free << 3, GFP_KERNEL) ||
2102 !(ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2103 ca->sb.nbuckets))) ||
2104 !(ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
2105 prio_buckets(ca), 2),
2106 GFP_KERNEL)) ||
2107 !(ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca)))
2108 return -ENOMEM;
2110 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2112 for_each_bucket(b, ca)
2113 atomic_set(&b->pin, 0);
2115 return 0;
2118 static int register_cache(struct cache_sb *sb, struct page *sb_page,
2119 struct block_device *bdev, struct cache *ca)
2121 const char *err = NULL; /* must be set for any error case */
2122 int ret = 0;
2124 bdevname(bdev, ca->cache_dev_name);
2125 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2126 ca->bdev = bdev;
2127 ca->bdev->bd_holder = ca;
2129 bio_init(&ca->sb_bio, ca->sb_bio.bi_inline_vecs, 1);
2130 bio_first_bvec_all(&ca->sb_bio)->bv_page = sb_page;
2131 get_page(sb_page);
2133 if (blk_queue_discard(bdev_get_queue(bdev)))
2134 ca->discard = CACHE_DISCARD(&ca->sb);
2136 ret = cache_alloc(ca);
2137 if (ret != 0) {
2138 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2139 if (ret == -ENOMEM)
2140 err = "cache_alloc(): -ENOMEM";
2141 else
2142 err = "cache_alloc(): unknown error";
2143 goto err;
2146 if (kobject_add(&ca->kobj,
2147 &part_to_dev(bdev->bd_part)->kobj,
2148 "bcache")) {
2149 err = "error calling kobject_add";
2150 ret = -ENOMEM;
2151 goto out;
2154 mutex_lock(&bch_register_lock);
2155 err = register_cache_set(ca);
2156 mutex_unlock(&bch_register_lock);
2158 if (err) {
2159 ret = -ENODEV;
2160 goto out;
2163 pr_info("registered cache device %s", ca->cache_dev_name);
2165 out:
2166 kobject_put(&ca->kobj);
2168 err:
2169 if (err)
2170 pr_notice("error %s: %s", ca->cache_dev_name, err);
2172 return ret;
2175 /* Global interfaces/init */
2177 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2178 const char *buffer, size_t size);
2180 kobj_attribute_write(register, register_bcache);
2181 kobj_attribute_write(register_quiet, register_bcache);
2183 static bool bch_is_open_backing(struct block_device *bdev)
2185 struct cache_set *c, *tc;
2186 struct cached_dev *dc, *t;
2188 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2189 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2190 if (dc->bdev == bdev)
2191 return true;
2192 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2193 if (dc->bdev == bdev)
2194 return true;
2195 return false;
2198 static bool bch_is_open_cache(struct block_device *bdev)
2200 struct cache_set *c, *tc;
2201 struct cache *ca;
2202 unsigned int i;
2204 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2205 for_each_cache(ca, c, i)
2206 if (ca->bdev == bdev)
2207 return true;
2208 return false;
2211 static bool bch_is_open(struct block_device *bdev)
2213 return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2216 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2217 const char *buffer, size_t size)
2219 ssize_t ret = size;
2220 const char *err = "cannot allocate memory";
2221 char *path = NULL;
2222 struct cache_sb *sb = NULL;
2223 struct block_device *bdev = NULL;
2224 struct page *sb_page = NULL;
2226 if (!try_module_get(THIS_MODULE))
2227 return -EBUSY;
2229 path = kstrndup(buffer, size, GFP_KERNEL);
2230 if (!path)
2231 goto err;
2233 sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2234 if (!sb)
2235 goto err;
2237 err = "failed to open device";
2238 bdev = blkdev_get_by_path(strim(path),
2239 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2240 sb);
2241 if (IS_ERR(bdev)) {
2242 if (bdev == ERR_PTR(-EBUSY)) {
2243 bdev = lookup_bdev(strim(path));
2244 mutex_lock(&bch_register_lock);
2245 if (!IS_ERR(bdev) && bch_is_open(bdev))
2246 err = "device already registered";
2247 else
2248 err = "device busy";
2249 mutex_unlock(&bch_register_lock);
2250 if (!IS_ERR(bdev))
2251 bdput(bdev);
2252 if (attr == &ksysfs_register_quiet)
2253 goto out;
2255 goto err;
2258 err = "failed to set blocksize";
2259 if (set_blocksize(bdev, 4096))
2260 goto err_close;
2262 err = read_super(sb, bdev, &sb_page);
2263 if (err)
2264 goto err_close;
2266 err = "failed to register device";
2267 if (SB_IS_BDEV(sb)) {
2268 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2270 if (!dc)
2271 goto err_close;
2273 mutex_lock(&bch_register_lock);
2274 register_bdev(sb, sb_page, bdev, dc);
2275 mutex_unlock(&bch_register_lock);
2276 } else {
2277 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2279 if (!ca)
2280 goto err_close;
2282 if (register_cache(sb, sb_page, bdev, ca) != 0)
2283 goto err;
2285 out:
2286 if (sb_page)
2287 put_page(sb_page);
2288 kfree(sb);
2289 kfree(path);
2290 module_put(THIS_MODULE);
2291 return ret;
2293 err_close:
2294 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2295 err:
2296 pr_info("error %s: %s", path, err);
2297 ret = -EINVAL;
2298 goto out;
2301 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2303 if (code == SYS_DOWN ||
2304 code == SYS_HALT ||
2305 code == SYS_POWER_OFF) {
2306 DEFINE_WAIT(wait);
2307 unsigned long start = jiffies;
2308 bool stopped = false;
2310 struct cache_set *c, *tc;
2311 struct cached_dev *dc, *tdc;
2313 mutex_lock(&bch_register_lock);
2315 if (list_empty(&bch_cache_sets) &&
2316 list_empty(&uncached_devices))
2317 goto out;
2319 pr_info("Stopping all devices:");
2321 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2322 bch_cache_set_stop(c);
2324 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2325 bcache_device_stop(&dc->disk);
2327 /* What's a condition variable? */
2328 while (1) {
2329 long timeout = start + 2 * HZ - jiffies;
2331 stopped = list_empty(&bch_cache_sets) &&
2332 list_empty(&uncached_devices);
2334 if (timeout < 0 || stopped)
2335 break;
2337 prepare_to_wait(&unregister_wait, &wait,
2338 TASK_UNINTERRUPTIBLE);
2340 mutex_unlock(&bch_register_lock);
2341 schedule_timeout(timeout);
2342 mutex_lock(&bch_register_lock);
2345 finish_wait(&unregister_wait, &wait);
2347 if (stopped)
2348 pr_info("All devices stopped");
2349 else
2350 pr_notice("Timeout waiting for devices to be closed");
2351 out:
2352 mutex_unlock(&bch_register_lock);
2355 return NOTIFY_DONE;
2358 static struct notifier_block reboot = {
2359 .notifier_call = bcache_reboot,
2360 .priority = INT_MAX, /* before any real devices */
2363 static void bcache_exit(void)
2365 bch_debug_exit();
2366 bch_request_exit();
2367 if (bcache_kobj)
2368 kobject_put(bcache_kobj);
2369 if (bcache_wq)
2370 destroy_workqueue(bcache_wq);
2371 if (bch_journal_wq)
2372 destroy_workqueue(bch_journal_wq);
2374 if (bcache_major)
2375 unregister_blkdev(bcache_major, "bcache");
2376 unregister_reboot_notifier(&reboot);
2377 mutex_destroy(&bch_register_lock);
2380 static int __init bcache_init(void)
2382 static const struct attribute *files[] = {
2383 &ksysfs_register.attr,
2384 &ksysfs_register_quiet.attr,
2385 NULL
2388 mutex_init(&bch_register_lock);
2389 init_waitqueue_head(&unregister_wait);
2390 register_reboot_notifier(&reboot);
2392 bcache_major = register_blkdev(0, "bcache");
2393 if (bcache_major < 0) {
2394 unregister_reboot_notifier(&reboot);
2395 mutex_destroy(&bch_register_lock);
2396 return bcache_major;
2399 bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2400 if (!bcache_wq)
2401 goto err;
2403 bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
2404 if (!bch_journal_wq)
2405 goto err;
2407 bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2408 if (!bcache_kobj)
2409 goto err;
2411 if (bch_request_init() ||
2412 sysfs_create_files(bcache_kobj, files))
2413 goto err;
2415 bch_debug_init(bcache_kobj);
2416 closure_debug_init();
2418 return 0;
2419 err:
2420 bcache_exit();
2421 return -ENOMEM;
2424 module_exit(bcache_exit);
2425 module_init(bcache_init);