1 // SPDX-License-Identifier: GPL-2.0
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.
15 #include "writeback.h"
18 #include <linux/blkdev.h>
19 #include <linux/pagemap.h>
20 #include <linux/debugfs.h>
21 #include <linux/genhd.h>
22 #include <linux/idr.h>
23 #include <linux/kthread.h>
24 #include <linux/workqueue.h>
25 #include <linux/module.h>
26 #include <linux/random.h>
27 #include <linux/reboot.h>
28 #include <linux/sysfs.h>
30 unsigned int bch_cutoff_writeback;
31 unsigned int bch_cutoff_writeback_sync;
33 static const char bcache_magic[] = {
34 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
35 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
38 static const char invalid_uuid[] = {
39 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
40 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
43 static struct kobject *bcache_kobj;
44 struct mutex bch_register_lock;
45 bool bcache_is_reboot;
46 LIST_HEAD(bch_cache_sets);
47 static LIST_HEAD(uncached_devices);
49 static int bcache_major;
50 static DEFINE_IDA(bcache_device_idx);
51 static wait_queue_head_t unregister_wait;
52 struct workqueue_struct *bcache_wq;
53 struct workqueue_struct *bch_flush_wq;
54 struct workqueue_struct *bch_journal_wq;
57 #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
58 /* limitation of partitions number on single bcache device */
59 #define BCACHE_MINORS 128
60 /* limitation of bcache devices number on single system */
61 #define BCACHE_DEVICE_IDX_MAX ((1U << MINORBITS)/BCACHE_MINORS)
65 static unsigned int get_bucket_size(struct cache_sb *sb, struct cache_sb_disk *s)
67 unsigned int bucket_size = le16_to_cpu(s->bucket_size);
69 if (sb->version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES) {
70 if (bch_has_feature_large_bucket(sb)) {
71 unsigned int max, order;
73 max = sizeof(unsigned int) * BITS_PER_BYTE - 1;
74 order = le16_to_cpu(s->bucket_size);
76 * bcache tool will make sure the overflow won't
77 * happen, an error message here is enough.
80 pr_err("Bucket size (1 << %u) overflows\n",
82 bucket_size = 1 << order;
83 } else if (bch_has_feature_obso_large_bucket(sb)) {
85 le16_to_cpu(s->obso_bucket_size_hi) << 16;
92 static const char *read_super_common(struct cache_sb *sb, struct block_device *bdev,
93 struct cache_sb_disk *s)
98 sb->first_bucket= le16_to_cpu(s->first_bucket);
99 sb->nbuckets = le64_to_cpu(s->nbuckets);
100 sb->bucket_size = get_bucket_size(sb, s);
102 sb->nr_in_set = le16_to_cpu(s->nr_in_set);
103 sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
105 err = "Too many journal buckets";
106 if (sb->keys > SB_JOURNAL_BUCKETS)
109 err = "Too many buckets";
110 if (sb->nbuckets > LONG_MAX)
113 err = "Not enough buckets";
114 if (sb->nbuckets < 1 << 7)
117 err = "Bad block size (not power of 2)";
118 if (!is_power_of_2(sb->block_size))
121 err = "Bad block size (larger than page size)";
122 if (sb->block_size > PAGE_SECTORS)
125 err = "Bad bucket size (not power of 2)";
126 if (!is_power_of_2(sb->bucket_size))
129 err = "Bad bucket size (smaller than page size)";
130 if (sb->bucket_size < PAGE_SECTORS)
133 err = "Invalid superblock: device too small";
134 if (get_capacity(bdev->bd_disk) <
135 sb->bucket_size * sb->nbuckets)
139 if (bch_is_zero(sb->set_uuid, 16))
142 err = "Bad cache device number in set";
143 if (!sb->nr_in_set ||
144 sb->nr_in_set <= sb->nr_this_dev ||
145 sb->nr_in_set > MAX_CACHES_PER_SET)
148 err = "Journal buckets not sequential";
149 for (i = 0; i < sb->keys; i++)
150 if (sb->d[i] != sb->first_bucket + i)
153 err = "Too many journal buckets";
154 if (sb->first_bucket + sb->keys > sb->nbuckets)
157 err = "Invalid superblock: first bucket comes before end of super";
158 if (sb->first_bucket * sb->bucket_size < 16)
167 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
168 struct cache_sb_disk **res)
171 struct cache_sb_disk *s;
175 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
176 SB_OFFSET >> PAGE_SHIFT, GFP_KERNEL);
179 s = page_address(page) + offset_in_page(SB_OFFSET);
181 sb->offset = le64_to_cpu(s->offset);
182 sb->version = le64_to_cpu(s->version);
184 memcpy(sb->magic, s->magic, 16);
185 memcpy(sb->uuid, s->uuid, 16);
186 memcpy(sb->set_uuid, s->set_uuid, 16);
187 memcpy(sb->label, s->label, SB_LABEL_SIZE);
189 sb->flags = le64_to_cpu(s->flags);
190 sb->seq = le64_to_cpu(s->seq);
191 sb->last_mount = le32_to_cpu(s->last_mount);
192 sb->keys = le16_to_cpu(s->keys);
194 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
195 sb->d[i] = le64_to_cpu(s->d[i]);
197 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u\n",
198 sb->version, sb->flags, sb->seq, sb->keys);
200 err = "Not a bcache superblock (bad offset)";
201 if (sb->offset != SB_SECTOR)
204 err = "Not a bcache superblock (bad magic)";
205 if (memcmp(sb->magic, bcache_magic, 16))
208 err = "Bad checksum";
209 if (s->csum != csum_set(s))
213 if (bch_is_zero(sb->uuid, 16))
216 sb->block_size = le16_to_cpu(s->block_size);
218 err = "Superblock block size smaller than device block size";
219 if (sb->block_size << 9 < bdev_logical_block_size(bdev))
222 switch (sb->version) {
223 case BCACHE_SB_VERSION_BDEV:
224 sb->data_offset = BDEV_DATA_START_DEFAULT;
226 case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
227 case BCACHE_SB_VERSION_BDEV_WITH_FEATURES:
228 sb->data_offset = le64_to_cpu(s->data_offset);
230 err = "Bad data offset";
231 if (sb->data_offset < BDEV_DATA_START_DEFAULT)
235 case BCACHE_SB_VERSION_CDEV:
236 case BCACHE_SB_VERSION_CDEV_WITH_UUID:
237 err = read_super_common(sb, bdev, s);
241 case BCACHE_SB_VERSION_CDEV_WITH_FEATURES:
243 * Feature bits are needed in read_super_common(),
244 * convert them firstly.
246 sb->feature_compat = le64_to_cpu(s->feature_compat);
247 sb->feature_incompat = le64_to_cpu(s->feature_incompat);
248 sb->feature_ro_compat = le64_to_cpu(s->feature_ro_compat);
250 /* Check incompatible features */
251 err = "Unsupported compatible feature found";
252 if (bch_has_unknown_compat_features(sb))
255 err = "Unsupported read-only compatible feature found";
256 if (bch_has_unknown_ro_compat_features(sb))
259 err = "Unsupported incompatible feature found";
260 if (bch_has_unknown_incompat_features(sb))
263 err = read_super_common(sb, bdev, s);
268 err = "Unsupported superblock version";
272 sb->last_mount = (u32)ktime_get_real_seconds();
280 static void write_bdev_super_endio(struct bio *bio)
282 struct cached_dev *dc = bio->bi_private;
285 bch_count_backing_io_errors(dc, bio);
287 closure_put(&dc->sb_write);
290 static void __write_super(struct cache_sb *sb, struct cache_sb_disk *out,
295 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META;
296 bio->bi_iter.bi_sector = SB_SECTOR;
297 __bio_add_page(bio, virt_to_page(out), SB_SIZE,
298 offset_in_page(out));
300 out->offset = cpu_to_le64(sb->offset);
302 memcpy(out->uuid, sb->uuid, 16);
303 memcpy(out->set_uuid, sb->set_uuid, 16);
304 memcpy(out->label, sb->label, SB_LABEL_SIZE);
306 out->flags = cpu_to_le64(sb->flags);
307 out->seq = cpu_to_le64(sb->seq);
309 out->last_mount = cpu_to_le32(sb->last_mount);
310 out->first_bucket = cpu_to_le16(sb->first_bucket);
311 out->keys = cpu_to_le16(sb->keys);
313 for (i = 0; i < sb->keys; i++)
314 out->d[i] = cpu_to_le64(sb->d[i]);
316 if (sb->version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES) {
317 out->feature_compat = cpu_to_le64(sb->feature_compat);
318 out->feature_incompat = cpu_to_le64(sb->feature_incompat);
319 out->feature_ro_compat = cpu_to_le64(sb->feature_ro_compat);
322 out->version = cpu_to_le64(sb->version);
323 out->csum = csum_set(out);
325 pr_debug("ver %llu, flags %llu, seq %llu\n",
326 sb->version, sb->flags, sb->seq);
331 static void bch_write_bdev_super_unlock(struct closure *cl)
333 struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
335 up(&dc->sb_write_mutex);
338 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
340 struct closure *cl = &dc->sb_write;
341 struct bio *bio = &dc->sb_bio;
343 down(&dc->sb_write_mutex);
344 closure_init(cl, parent);
346 bio_init(bio, dc->sb_bv, 1);
347 bio_set_dev(bio, dc->bdev);
348 bio->bi_end_io = write_bdev_super_endio;
349 bio->bi_private = dc;
352 /* I/O request sent to backing device */
353 __write_super(&dc->sb, dc->sb_disk, bio);
355 closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
358 static void write_super_endio(struct bio *bio)
360 struct cache *ca = bio->bi_private;
363 bch_count_io_errors(ca, bio->bi_status, 0,
364 "writing superblock");
365 closure_put(&ca->set->sb_write);
368 static void bcache_write_super_unlock(struct closure *cl)
370 struct cache_set *c = container_of(cl, struct cache_set, sb_write);
372 up(&c->sb_write_mutex);
375 void bcache_write_super(struct cache_set *c)
377 struct closure *cl = &c->sb_write;
378 struct cache *ca = c->cache;
379 struct bio *bio = &ca->sb_bio;
380 unsigned int version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
382 down(&c->sb_write_mutex);
383 closure_init(cl, &c->cl);
387 if (ca->sb.version < version)
388 ca->sb.version = version;
390 bio_init(bio, ca->sb_bv, 1);
391 bio_set_dev(bio, ca->bdev);
392 bio->bi_end_io = write_super_endio;
393 bio->bi_private = ca;
396 __write_super(&ca->sb, ca->sb_disk, bio);
398 closure_return_with_destructor(cl, bcache_write_super_unlock);
403 static void uuid_endio(struct bio *bio)
405 struct closure *cl = bio->bi_private;
406 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
408 cache_set_err_on(bio->bi_status, c, "accessing uuids");
409 bch_bbio_free(bio, c);
413 static void uuid_io_unlock(struct closure *cl)
415 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
417 up(&c->uuid_write_mutex);
420 static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
421 struct bkey *k, struct closure *parent)
423 struct closure *cl = &c->uuid_write;
424 struct uuid_entry *u;
429 down(&c->uuid_write_mutex);
430 closure_init(cl, parent);
432 for (i = 0; i < KEY_PTRS(k); i++) {
433 struct bio *bio = bch_bbio_alloc(c);
435 bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
436 bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
438 bio->bi_end_io = uuid_endio;
439 bio->bi_private = cl;
440 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
441 bch_bio_map(bio, c->uuids);
443 bch_submit_bbio(bio, c, k, i);
445 if (op != REQ_OP_WRITE)
449 bch_extent_to_text(buf, sizeof(buf), k);
450 pr_debug("%s UUIDs at %s\n", op == REQ_OP_WRITE ? "wrote" : "read", buf);
452 for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
453 if (!bch_is_zero(u->uuid, 16))
454 pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u\n",
455 u - c->uuids, u->uuid, u->label,
456 u->first_reg, u->last_reg, u->invalidated);
458 closure_return_with_destructor(cl, uuid_io_unlock);
461 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
463 struct bkey *k = &j->uuid_bucket;
465 if (__bch_btree_ptr_invalid(c, k))
466 return "bad uuid pointer";
468 bkey_copy(&c->uuid_bucket, k);
469 uuid_io(c, REQ_OP_READ, 0, k, cl);
471 if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
472 struct uuid_entry_v0 *u0 = (void *) c->uuids;
473 struct uuid_entry *u1 = (void *) c->uuids;
479 * Since the new uuid entry is bigger than the old, we have to
480 * convert starting at the highest memory address and work down
481 * in order to do it in place
484 for (i = c->nr_uuids - 1;
487 memcpy(u1[i].uuid, u0[i].uuid, 16);
488 memcpy(u1[i].label, u0[i].label, 32);
490 u1[i].first_reg = u0[i].first_reg;
491 u1[i].last_reg = u0[i].last_reg;
492 u1[i].invalidated = u0[i].invalidated;
502 static int __uuid_write(struct cache_set *c)
506 struct cache *ca = c->cache;
509 closure_init_stack(&cl);
510 lockdep_assert_held(&bch_register_lock);
512 if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, true))
515 size = meta_bucket_pages(&ca->sb) * PAGE_SECTORS;
516 SET_KEY_SIZE(&k.key, size);
517 uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
520 /* Only one bucket used for uuid write */
521 atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
523 bkey_copy(&c->uuid_bucket, &k.key);
528 int bch_uuid_write(struct cache_set *c)
530 int ret = __uuid_write(c);
533 bch_journal_meta(c, NULL);
538 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
540 struct uuid_entry *u;
543 u < c->uuids + c->nr_uuids; u++)
544 if (!memcmp(u->uuid, uuid, 16))
550 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
552 static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
554 return uuid_find(c, zero_uuid);
558 * Bucket priorities/gens:
560 * For each bucket, we store on disk its
564 * See alloc.c for an explanation of the gen. The priority is used to implement
565 * lru (and in the future other) cache replacement policies; for most purposes
566 * it's just an opaque integer.
568 * The gens and the priorities don't have a whole lot to do with each other, and
569 * it's actually the gens that must be written out at specific times - it's no
570 * big deal if the priorities don't get written, if we lose them we just reuse
571 * buckets in suboptimal order.
573 * On disk they're stored in a packed array, and in as many buckets are required
574 * to fit them all. The buckets we use to store them form a list; the journal
575 * header points to the first bucket, the first bucket points to the second
578 * This code is used by the allocation code; periodically (whenever it runs out
579 * of buckets to allocate from) the allocation code will invalidate some
580 * buckets, but it can't use those buckets until their new gens are safely on
584 static void prio_endio(struct bio *bio)
586 struct cache *ca = bio->bi_private;
588 cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
589 bch_bbio_free(bio, ca->set);
590 closure_put(&ca->prio);
593 static void prio_io(struct cache *ca, uint64_t bucket, int op,
594 unsigned long op_flags)
596 struct closure *cl = &ca->prio;
597 struct bio *bio = bch_bbio_alloc(ca->set);
599 closure_init_stack(cl);
601 bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
602 bio_set_dev(bio, ca->bdev);
603 bio->bi_iter.bi_size = meta_bucket_bytes(&ca->sb);
605 bio->bi_end_io = prio_endio;
606 bio->bi_private = ca;
607 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
608 bch_bio_map(bio, ca->disk_buckets);
610 closure_bio_submit(ca->set, bio, &ca->prio);
614 int bch_prio_write(struct cache *ca, bool wait)
620 pr_debug("free_prio=%zu, free_none=%zu, free_inc=%zu\n",
621 fifo_used(&ca->free[RESERVE_PRIO]),
622 fifo_used(&ca->free[RESERVE_NONE]),
623 fifo_used(&ca->free_inc));
626 * Pre-check if there are enough free buckets. In the non-blocking
627 * scenario it's better to fail early rather than starting to allocate
628 * buckets and do a cleanup later in case of failure.
631 size_t avail = fifo_used(&ca->free[RESERVE_PRIO]) +
632 fifo_used(&ca->free[RESERVE_NONE]);
633 if (prio_buckets(ca) > avail)
637 closure_init_stack(&cl);
639 lockdep_assert_held(&ca->set->bucket_lock);
641 ca->disk_buckets->seq++;
643 atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
644 &ca->meta_sectors_written);
646 for (i = prio_buckets(ca) - 1; i >= 0; --i) {
648 struct prio_set *p = ca->disk_buckets;
649 struct bucket_disk *d = p->data;
650 struct bucket_disk *end = d + prios_per_bucket(ca);
652 for (b = ca->buckets + i * prios_per_bucket(ca);
653 b < ca->buckets + ca->sb.nbuckets && d < end;
655 d->prio = cpu_to_le16(b->prio);
659 p->next_bucket = ca->prio_buckets[i + 1];
660 p->magic = pset_magic(&ca->sb);
661 p->csum = bch_crc64(&p->magic, meta_bucket_bytes(&ca->sb) - 8);
663 bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
664 BUG_ON(bucket == -1);
666 mutex_unlock(&ca->set->bucket_lock);
667 prio_io(ca, bucket, REQ_OP_WRITE, 0);
668 mutex_lock(&ca->set->bucket_lock);
670 ca->prio_buckets[i] = bucket;
671 atomic_dec_bug(&ca->buckets[bucket].pin);
674 mutex_unlock(&ca->set->bucket_lock);
676 bch_journal_meta(ca->set, &cl);
679 mutex_lock(&ca->set->bucket_lock);
682 * Don't want the old priorities to get garbage collected until after we
683 * finish writing the new ones, and they're journalled
685 for (i = 0; i < prio_buckets(ca); i++) {
686 if (ca->prio_last_buckets[i])
687 __bch_bucket_free(ca,
688 &ca->buckets[ca->prio_last_buckets[i]]);
690 ca->prio_last_buckets[i] = ca->prio_buckets[i];
695 static int prio_read(struct cache *ca, uint64_t bucket)
697 struct prio_set *p = ca->disk_buckets;
698 struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
700 unsigned int bucket_nr = 0;
703 for (b = ca->buckets;
704 b < ca->buckets + ca->sb.nbuckets;
707 ca->prio_buckets[bucket_nr] = bucket;
708 ca->prio_last_buckets[bucket_nr] = bucket;
711 prio_io(ca, bucket, REQ_OP_READ, 0);
714 bch_crc64(&p->magic, meta_bucket_bytes(&ca->sb) - 8)) {
715 pr_warn("bad csum reading priorities\n");
719 if (p->magic != pset_magic(&ca->sb)) {
720 pr_warn("bad magic reading priorities\n");
724 bucket = p->next_bucket;
728 b->prio = le16_to_cpu(d->prio);
729 b->gen = b->last_gc = d->gen;
739 static int open_dev(struct block_device *b, fmode_t mode)
741 struct bcache_device *d = b->bd_disk->private_data;
743 if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
750 static void release_dev(struct gendisk *b, fmode_t mode)
752 struct bcache_device *d = b->private_data;
757 static int ioctl_dev(struct block_device *b, fmode_t mode,
758 unsigned int cmd, unsigned long arg)
760 struct bcache_device *d = b->bd_disk->private_data;
762 return d->ioctl(d, mode, cmd, arg);
765 static const struct block_device_operations bcache_cached_ops = {
766 .submit_bio = cached_dev_submit_bio,
768 .release = release_dev,
770 .owner = THIS_MODULE,
773 static const struct block_device_operations bcache_flash_ops = {
774 .submit_bio = flash_dev_submit_bio,
776 .release = release_dev,
778 .owner = THIS_MODULE,
781 void bcache_device_stop(struct bcache_device *d)
783 if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
786 * - cached device: cached_dev_flush()
787 * - flash dev: flash_dev_flush()
789 closure_queue(&d->cl);
792 static void bcache_device_unlink(struct bcache_device *d)
794 lockdep_assert_held(&bch_register_lock);
796 if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
797 struct cache *ca = d->c->cache;
799 sysfs_remove_link(&d->c->kobj, d->name);
800 sysfs_remove_link(&d->kobj, "cache");
802 bd_unlink_disk_holder(ca->bdev, d->disk);
806 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
809 struct cache *ca = c->cache;
812 bd_link_disk_holder(ca->bdev, d->disk);
814 snprintf(d->name, BCACHEDEVNAME_SIZE,
815 "%s%u", name, d->id);
817 ret = sysfs_create_link(&d->kobj, &c->kobj, "cache");
819 pr_err("Couldn't create device -> cache set symlink\n");
821 ret = sysfs_create_link(&c->kobj, &d->kobj, d->name);
823 pr_err("Couldn't create cache set -> device symlink\n");
825 clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
828 static void bcache_device_detach(struct bcache_device *d)
830 lockdep_assert_held(&bch_register_lock);
832 atomic_dec(&d->c->attached_dev_nr);
834 if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
835 struct uuid_entry *u = d->c->uuids + d->id;
837 SET_UUID_FLASH_ONLY(u, 0);
838 memcpy(u->uuid, invalid_uuid, 16);
839 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
840 bch_uuid_write(d->c);
843 bcache_device_unlink(d);
845 d->c->devices[d->id] = NULL;
846 closure_put(&d->c->caching);
850 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
857 if (id >= c->devices_max_used)
858 c->devices_max_used = id + 1;
860 closure_get(&c->caching);
863 static inline int first_minor_to_idx(int first_minor)
865 return (first_minor/BCACHE_MINORS);
868 static inline int idx_to_first_minor(int idx)
870 return (idx * BCACHE_MINORS);
873 static void bcache_device_free(struct bcache_device *d)
875 struct gendisk *disk = d->disk;
877 lockdep_assert_held(&bch_register_lock);
880 pr_info("%s stopped\n", disk->disk_name);
882 pr_err("bcache device (NULL gendisk) stopped\n");
885 bcache_device_detach(d);
888 blk_cleanup_disk(disk);
889 ida_simple_remove(&bcache_device_idx,
890 first_minor_to_idx(disk->first_minor));
893 bioset_exit(&d->bio_split);
894 kvfree(d->full_dirty_stripes);
895 kvfree(d->stripe_sectors_dirty);
897 closure_debug_destroy(&d->cl);
900 static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
901 sector_t sectors, struct block_device *cached_bdev,
902 const struct block_device_operations *ops)
904 struct request_queue *q;
905 const size_t max_stripes = min_t(size_t, INT_MAX,
906 SIZE_MAX / sizeof(atomic_t));
911 d->stripe_size = 1 << 31;
913 n = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
914 if (!n || n > max_stripes) {
915 pr_err("nr_stripes too large or invalid: %llu (start sector beyond end of disk?)\n",
921 n = d->nr_stripes * sizeof(atomic_t);
922 d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
923 if (!d->stripe_sectors_dirty)
926 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
927 d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
928 if (!d->full_dirty_stripes)
929 goto out_free_stripe_sectors_dirty;
931 idx = ida_simple_get(&bcache_device_idx, 0,
932 BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
934 goto out_free_full_dirty_stripes;
936 if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
937 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
940 d->disk = blk_alloc_disk(NUMA_NO_NODE);
942 goto out_bioset_exit;
944 set_capacity(d->disk, sectors);
945 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
947 d->disk->major = bcache_major;
948 d->disk->first_minor = idx_to_first_minor(idx);
949 d->disk->minors = BCACHE_MINORS;
951 d->disk->private_data = d;
954 q->limits.max_hw_sectors = UINT_MAX;
955 q->limits.max_sectors = UINT_MAX;
956 q->limits.max_segment_size = UINT_MAX;
957 q->limits.max_segments = BIO_MAX_VECS;
958 blk_queue_max_discard_sectors(q, UINT_MAX);
959 q->limits.discard_granularity = 512;
960 q->limits.io_min = block_size;
961 q->limits.logical_block_size = block_size;
962 q->limits.physical_block_size = block_size;
964 if (q->limits.logical_block_size > PAGE_SIZE && cached_bdev) {
966 * This should only happen with BCACHE_SB_VERSION_BDEV.
967 * Block/page size is checked for BCACHE_SB_VERSION_CDEV.
969 pr_info("%s: sb/logical block size (%u) greater than page size (%lu) falling back to device logical block size (%u)\n",
970 d->disk->disk_name, q->limits.logical_block_size,
971 PAGE_SIZE, bdev_logical_block_size(cached_bdev));
973 /* This also adjusts physical block size/min io size if needed */
974 blk_queue_logical_block_size(q, bdev_logical_block_size(cached_bdev));
977 blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
978 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
979 blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
981 blk_queue_write_cache(q, true, true);
986 bioset_exit(&d->bio_split);
988 ida_simple_remove(&bcache_device_idx, idx);
989 out_free_full_dirty_stripes:
990 kvfree(d->full_dirty_stripes);
991 out_free_stripe_sectors_dirty:
992 kvfree(d->stripe_sectors_dirty);
999 static void calc_cached_dev_sectors(struct cache_set *c)
1001 uint64_t sectors = 0;
1002 struct cached_dev *dc;
1004 list_for_each_entry(dc, &c->cached_devs, list)
1005 sectors += bdev_sectors(dc->bdev);
1007 c->cached_dev_sectors = sectors;
1010 #define BACKING_DEV_OFFLINE_TIMEOUT 5
1011 static int cached_dev_status_update(void *arg)
1013 struct cached_dev *dc = arg;
1014 struct request_queue *q;
1017 * If this delayed worker is stopping outside, directly quit here.
1018 * dc->io_disable might be set via sysfs interface, so check it
1021 while (!kthread_should_stop() && !dc->io_disable) {
1022 q = bdev_get_queue(dc->bdev);
1023 if (blk_queue_dying(q))
1024 dc->offline_seconds++;
1026 dc->offline_seconds = 0;
1028 if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
1029 pr_err("%pg: device offline for %d seconds\n",
1031 BACKING_DEV_OFFLINE_TIMEOUT);
1032 pr_err("%s: disable I/O request due to backing device offline\n",
1034 dc->io_disable = true;
1035 /* let others know earlier that io_disable is true */
1037 bcache_device_stop(&dc->disk);
1040 schedule_timeout_interruptible(HZ);
1043 wait_for_kthread_stop();
1048 int bch_cached_dev_run(struct cached_dev *dc)
1051 struct bcache_device *d = &dc->disk;
1052 char *buf = kmemdup_nul(dc->sb.label, SB_LABEL_SIZE, GFP_KERNEL);
1055 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
1056 kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf ? : ""),
1060 if (dc->io_disable) {
1061 pr_err("I/O disabled on cached dev %pg\n", dc->bdev);
1066 if (atomic_xchg(&dc->running, 1)) {
1067 pr_info("cached dev %pg is running already\n", dc->bdev);
1073 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
1076 closure_init_stack(&cl);
1078 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
1079 bch_write_bdev_super(dc, &cl);
1084 bd_link_disk_holder(dc->bdev, dc->disk.disk);
1086 * won't show up in the uevent file, use udevadm monitor -e instead
1087 * only class / kset properties are persistent
1089 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
1091 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
1092 sysfs_create_link(&disk_to_dev(d->disk)->kobj,
1093 &d->kobj, "bcache")) {
1094 pr_err("Couldn't create bcache dev <-> disk sysfs symlinks\n");
1099 dc->status_update_thread = kthread_run(cached_dev_status_update,
1100 dc, "bcache_status_update");
1101 if (IS_ERR(dc->status_update_thread)) {
1102 pr_warn("failed to create bcache_status_update kthread, continue to run without monitoring backing device status\n");
1113 * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
1114 * work dc->writeback_rate_update is running. Wait until the routine
1115 * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
1116 * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
1117 * seconds, give up waiting here and continue to cancel it too.
1119 static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
1121 int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
1124 if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
1128 schedule_timeout_interruptible(1);
1129 } while (time_out > 0);
1132 pr_warn("give up waiting for dc->writeback_write_update to quit\n");
1134 cancel_delayed_work_sync(&dc->writeback_rate_update);
1137 static void cached_dev_detach_finish(struct work_struct *w)
1139 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
1141 BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
1142 BUG_ON(refcount_read(&dc->count));
1145 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1146 cancel_writeback_rate_update_dwork(dc);
1148 if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
1149 kthread_stop(dc->writeback_thread);
1150 dc->writeback_thread = NULL;
1153 mutex_lock(&bch_register_lock);
1155 bcache_device_detach(&dc->disk);
1156 list_move(&dc->list, &uncached_devices);
1157 calc_cached_dev_sectors(dc->disk.c);
1159 clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
1160 clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
1162 mutex_unlock(&bch_register_lock);
1164 pr_info("Caching disabled for %pg\n", dc->bdev);
1166 /* Drop ref we took in cached_dev_detach() */
1167 closure_put(&dc->disk.cl);
1170 void bch_cached_dev_detach(struct cached_dev *dc)
1172 lockdep_assert_held(&bch_register_lock);
1174 if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1177 if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
1181 * Block the device from being closed and freed until we're finished
1184 closure_get(&dc->disk.cl);
1186 bch_writeback_queue(dc);
1191 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
1194 uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
1195 struct uuid_entry *u;
1196 struct cached_dev *exist_dc, *t;
1199 if ((set_uuid && memcmp(set_uuid, c->set_uuid, 16)) ||
1200 (!set_uuid && memcmp(dc->sb.set_uuid, c->set_uuid, 16)))
1204 pr_err("Can't attach %pg: already attached\n", dc->bdev);
1208 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
1209 pr_err("Can't attach %pg: shutting down\n", dc->bdev);
1213 if (dc->sb.block_size < c->cache->sb.block_size) {
1215 pr_err("Couldn't attach %pg: block size less than set's block size\n",
1220 /* Check whether already attached */
1221 list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
1222 if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
1223 pr_err("Tried to attach %pg but duplicate UUID already attached\n",
1230 u = uuid_find(c, dc->sb.uuid);
1233 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1234 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1235 memcpy(u->uuid, invalid_uuid, 16);
1236 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1241 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1242 pr_err("Couldn't find uuid for %pg in set\n", dc->bdev);
1246 u = uuid_find_empty(c);
1248 pr_err("Not caching %pg, no room for UUID\n", dc->bdev);
1254 * Deadlocks since we're called via sysfs...
1255 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1258 if (bch_is_zero(u->uuid, 16)) {
1261 closure_init_stack(&cl);
1263 memcpy(u->uuid, dc->sb.uuid, 16);
1264 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1265 u->first_reg = u->last_reg = rtime;
1268 memcpy(dc->sb.set_uuid, c->set_uuid, 16);
1269 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1271 bch_write_bdev_super(dc, &cl);
1274 u->last_reg = rtime;
1278 bcache_device_attach(&dc->disk, c, u - c->uuids);
1279 list_move(&dc->list, &c->cached_devs);
1280 calc_cached_dev_sectors(c);
1283 * dc->c must be set before dc->count != 0 - paired with the mb in
1287 refcount_set(&dc->count, 1);
1289 /* Block writeback thread, but spawn it */
1290 down_write(&dc->writeback_lock);
1291 if (bch_cached_dev_writeback_start(dc)) {
1292 up_write(&dc->writeback_lock);
1293 pr_err("Couldn't start writeback facilities for %s\n",
1294 dc->disk.disk->disk_name);
1298 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1299 atomic_set(&dc->has_dirty, 1);
1300 bch_writeback_queue(dc);
1303 bch_sectors_dirty_init(&dc->disk);
1305 ret = bch_cached_dev_run(dc);
1306 if (ret && (ret != -EBUSY)) {
1307 up_write(&dc->writeback_lock);
1309 * bch_register_lock is held, bcache_device_stop() is not
1310 * able to be directly called. The kthread and kworker
1311 * created previously in bch_cached_dev_writeback_start()
1312 * have to be stopped manually here.
1314 kthread_stop(dc->writeback_thread);
1315 cancel_writeback_rate_update_dwork(dc);
1316 pr_err("Couldn't run cached device %pg\n", dc->bdev);
1320 bcache_device_link(&dc->disk, c, "bdev");
1321 atomic_inc(&c->attached_dev_nr);
1323 if (bch_has_feature_obso_large_bucket(&(c->cache->sb))) {
1324 pr_err("The obsoleted large bucket layout is unsupported, set the bcache device into read-only\n");
1325 pr_err("Please update to the latest bcache-tools to create the cache device\n");
1326 set_disk_ro(dc->disk.disk, 1);
1329 /* Allow the writeback thread to proceed */
1330 up_write(&dc->writeback_lock);
1332 pr_info("Caching %pg as %s on set %pU\n",
1334 dc->disk.disk->disk_name,
1335 dc->disk.c->set_uuid);
1339 /* when dc->disk.kobj released */
1340 void bch_cached_dev_release(struct kobject *kobj)
1342 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1345 module_put(THIS_MODULE);
1348 static void cached_dev_free(struct closure *cl)
1350 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1352 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1353 cancel_writeback_rate_update_dwork(dc);
1355 if (!IS_ERR_OR_NULL(dc->writeback_thread))
1356 kthread_stop(dc->writeback_thread);
1357 if (!IS_ERR_OR_NULL(dc->status_update_thread))
1358 kthread_stop(dc->status_update_thread);
1360 mutex_lock(&bch_register_lock);
1362 if (atomic_read(&dc->running)) {
1363 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1364 del_gendisk(dc->disk.disk);
1366 bcache_device_free(&dc->disk);
1367 list_del(&dc->list);
1369 mutex_unlock(&bch_register_lock);
1372 put_page(virt_to_page(dc->sb_disk));
1374 if (!IS_ERR_OR_NULL(dc->bdev))
1375 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1377 wake_up(&unregister_wait);
1379 kobject_put(&dc->disk.kobj);
1382 static void cached_dev_flush(struct closure *cl)
1384 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1385 struct bcache_device *d = &dc->disk;
1387 mutex_lock(&bch_register_lock);
1388 bcache_device_unlink(d);
1389 mutex_unlock(&bch_register_lock);
1391 bch_cache_accounting_destroy(&dc->accounting);
1392 kobject_del(&d->kobj);
1394 continue_at(cl, cached_dev_free, system_wq);
1397 static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1401 struct request_queue *q = bdev_get_queue(dc->bdev);
1403 __module_get(THIS_MODULE);
1404 INIT_LIST_HEAD(&dc->list);
1405 closure_init(&dc->disk.cl, NULL);
1406 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1407 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1408 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1409 sema_init(&dc->sb_write_mutex, 1);
1410 INIT_LIST_HEAD(&dc->io_lru);
1411 spin_lock_init(&dc->io_lock);
1412 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1414 dc->sequential_cutoff = 4 << 20;
1416 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1417 list_add(&io->lru, &dc->io_lru);
1418 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1421 dc->disk.stripe_size = q->limits.io_opt >> 9;
1423 if (dc->disk.stripe_size)
1424 dc->partial_stripes_expensive =
1425 q->limits.raid_partial_stripes_expensive;
1427 ret = bcache_device_init(&dc->disk, block_size,
1428 bdev_nr_sectors(dc->bdev) - dc->sb.data_offset,
1429 dc->bdev, &bcache_cached_ops);
1433 blk_queue_io_opt(dc->disk.disk->queue,
1434 max(queue_io_opt(dc->disk.disk->queue), queue_io_opt(q)));
1436 atomic_set(&dc->io_errors, 0);
1437 dc->io_disable = false;
1438 dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
1439 /* default to auto */
1440 dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
1442 bch_cached_dev_request_init(dc);
1443 bch_cached_dev_writeback_init(dc);
1447 /* Cached device - bcache superblock */
1449 static int register_bdev(struct cache_sb *sb, struct cache_sb_disk *sb_disk,
1450 struct block_device *bdev,
1451 struct cached_dev *dc)
1453 const char *err = "cannot allocate memory";
1454 struct cache_set *c;
1457 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1459 dc->bdev->bd_holder = dc;
1460 dc->sb_disk = sb_disk;
1462 if (cached_dev_init(dc, sb->block_size << 9))
1465 err = "error creating kobject";
1466 if (kobject_add(&dc->disk.kobj, bdev_kobj(bdev), "bcache"))
1468 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1471 pr_info("registered backing device %pg\n", dc->bdev);
1473 list_add(&dc->list, &uncached_devices);
1474 /* attach to a matched cache set if it exists */
1475 list_for_each_entry(c, &bch_cache_sets, list)
1476 bch_cached_dev_attach(dc, c, NULL);
1478 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1479 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
1480 err = "failed to run cached device";
1481 ret = bch_cached_dev_run(dc);
1488 pr_notice("error %pg: %s\n", dc->bdev, err);
1489 bcache_device_stop(&dc->disk);
1493 /* Flash only volumes */
1495 /* When d->kobj released */
1496 void bch_flash_dev_release(struct kobject *kobj)
1498 struct bcache_device *d = container_of(kobj, struct bcache_device,
1503 static void flash_dev_free(struct closure *cl)
1505 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1507 mutex_lock(&bch_register_lock);
1508 atomic_long_sub(bcache_dev_sectors_dirty(d),
1509 &d->c->flash_dev_dirty_sectors);
1510 del_gendisk(d->disk);
1511 bcache_device_free(d);
1512 mutex_unlock(&bch_register_lock);
1513 kobject_put(&d->kobj);
1516 static void flash_dev_flush(struct closure *cl)
1518 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1520 mutex_lock(&bch_register_lock);
1521 bcache_device_unlink(d);
1522 mutex_unlock(&bch_register_lock);
1523 kobject_del(&d->kobj);
1524 continue_at(cl, flash_dev_free, system_wq);
1527 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1529 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1534 closure_init(&d->cl, NULL);
1535 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1537 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1539 if (bcache_device_init(d, block_bytes(c->cache), u->sectors,
1540 NULL, &bcache_flash_ops))
1543 bcache_device_attach(d, c, u - c->uuids);
1544 bch_sectors_dirty_init(d);
1545 bch_flash_dev_request_init(d);
1548 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1551 bcache_device_link(d, c, "volume");
1553 if (bch_has_feature_obso_large_bucket(&c->cache->sb)) {
1554 pr_err("The obsoleted large bucket layout is unsupported, set the bcache device into read-only\n");
1555 pr_err("Please update to the latest bcache-tools to create the cache device\n");
1556 set_disk_ro(d->disk, 1);
1561 kobject_put(&d->kobj);
1565 static int flash_devs_run(struct cache_set *c)
1568 struct uuid_entry *u;
1571 u < c->uuids + c->nr_uuids && !ret;
1573 if (UUID_FLASH_ONLY(u))
1574 ret = flash_dev_run(c, u);
1579 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1581 struct uuid_entry *u;
1583 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1586 if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1589 u = uuid_find_empty(c);
1591 pr_err("Can't create volume, no room for UUID\n");
1595 get_random_bytes(u->uuid, 16);
1596 memset(u->label, 0, 32);
1597 u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1599 SET_UUID_FLASH_ONLY(u, 1);
1600 u->sectors = size >> 9;
1604 return flash_dev_run(c, u);
1607 bool bch_cached_dev_error(struct cached_dev *dc)
1609 if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1612 dc->io_disable = true;
1613 /* make others know io_disable is true earlier */
1616 pr_err("stop %s: too many IO errors on backing device %pg\n",
1617 dc->disk.disk->disk_name, dc->bdev);
1619 bcache_device_stop(&dc->disk);
1626 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1628 struct va_format vaf;
1631 if (c->on_error != ON_ERROR_PANIC &&
1632 test_bit(CACHE_SET_STOPPING, &c->flags))
1635 if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1636 pr_info("CACHE_SET_IO_DISABLE already set\n");
1639 * XXX: we can be called from atomic context
1640 * acquire_console_sem();
1643 va_start(args, fmt);
1648 pr_err("error on %pU: %pV, disabling caching\n",
1653 if (c->on_error == ON_ERROR_PANIC)
1654 panic("panic forced after error\n");
1656 bch_cache_set_unregister(c);
1660 /* When c->kobj released */
1661 void bch_cache_set_release(struct kobject *kobj)
1663 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1666 module_put(THIS_MODULE);
1669 static void cache_set_free(struct closure *cl)
1671 struct cache_set *c = container_of(cl, struct cache_set, cl);
1674 debugfs_remove(c->debug);
1676 bch_open_buckets_free(c);
1677 bch_btree_cache_free(c);
1678 bch_journal_free(c);
1680 mutex_lock(&bch_register_lock);
1681 bch_bset_sort_state_free(&c->sort);
1682 free_pages((unsigned long) c->uuids, ilog2(meta_bucket_pages(&c->cache->sb)));
1688 kobject_put(&ca->kobj);
1692 if (c->moving_gc_wq)
1693 destroy_workqueue(c->moving_gc_wq);
1694 bioset_exit(&c->bio_split);
1695 mempool_exit(&c->fill_iter);
1696 mempool_exit(&c->bio_meta);
1697 mempool_exit(&c->search);
1701 mutex_unlock(&bch_register_lock);
1703 pr_info("Cache set %pU unregistered\n", c->set_uuid);
1704 wake_up(&unregister_wait);
1706 closure_debug_destroy(&c->cl);
1707 kobject_put(&c->kobj);
1710 static void cache_set_flush(struct closure *cl)
1712 struct cache_set *c = container_of(cl, struct cache_set, caching);
1713 struct cache *ca = c->cache;
1716 bch_cache_accounting_destroy(&c->accounting);
1718 kobject_put(&c->internal);
1719 kobject_del(&c->kobj);
1721 if (!IS_ERR_OR_NULL(c->gc_thread))
1722 kthread_stop(c->gc_thread);
1724 if (!IS_ERR_OR_NULL(c->root))
1725 list_add(&c->root->list, &c->btree_cache);
1728 * Avoid flushing cached nodes if cache set is retiring
1729 * due to too many I/O errors detected.
1731 if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1732 list_for_each_entry(b, &c->btree_cache, list) {
1733 mutex_lock(&b->write_lock);
1734 if (btree_node_dirty(b))
1735 __bch_btree_node_write(b, NULL);
1736 mutex_unlock(&b->write_lock);
1739 if (ca->alloc_thread)
1740 kthread_stop(ca->alloc_thread);
1742 if (c->journal.cur) {
1743 cancel_delayed_work_sync(&c->journal.work);
1744 /* flush last journal entry if needed */
1745 c->journal.work.work.func(&c->journal.work.work);
1752 * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1753 * cache set is unregistering due to too many I/O errors. In this condition,
1754 * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1755 * value and whether the broken cache has dirty data:
1757 * dc->stop_when_cache_set_failed dc->has_dirty stop bcache device
1758 * BCH_CACHED_STOP_AUTO 0 NO
1759 * BCH_CACHED_STOP_AUTO 1 YES
1760 * BCH_CACHED_DEV_STOP_ALWAYS 0 YES
1761 * BCH_CACHED_DEV_STOP_ALWAYS 1 YES
1763 * The expected behavior is, if stop_when_cache_set_failed is configured to
1764 * "auto" via sysfs interface, the bcache device will not be stopped if the
1765 * backing device is clean on the broken cache device.
1767 static void conditional_stop_bcache_device(struct cache_set *c,
1768 struct bcache_device *d,
1769 struct cached_dev *dc)
1771 if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1772 pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.\n",
1773 d->disk->disk_name, c->set_uuid);
1774 bcache_device_stop(d);
1775 } else if (atomic_read(&dc->has_dirty)) {
1777 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1778 * and dc->has_dirty == 1
1780 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.\n",
1781 d->disk->disk_name);
1783 * There might be a small time gap that cache set is
1784 * released but bcache device is not. Inside this time
1785 * gap, regular I/O requests will directly go into
1786 * backing device as no cache set attached to. This
1787 * behavior may also introduce potential inconsistence
1788 * data in writeback mode while cache is dirty.
1789 * Therefore before calling bcache_device_stop() due
1790 * to a broken cache device, dc->io_disable should be
1791 * explicitly set to true.
1793 dc->io_disable = true;
1794 /* make others know io_disable is true earlier */
1796 bcache_device_stop(d);
1799 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1800 * and dc->has_dirty == 0
1802 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.\n",
1803 d->disk->disk_name);
1807 static void __cache_set_unregister(struct closure *cl)
1809 struct cache_set *c = container_of(cl, struct cache_set, caching);
1810 struct cached_dev *dc;
1811 struct bcache_device *d;
1814 mutex_lock(&bch_register_lock);
1816 for (i = 0; i < c->devices_max_used; i++) {
1821 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1822 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1823 dc = container_of(d, struct cached_dev, disk);
1824 bch_cached_dev_detach(dc);
1825 if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1826 conditional_stop_bcache_device(c, d, dc);
1828 bcache_device_stop(d);
1832 mutex_unlock(&bch_register_lock);
1834 continue_at(cl, cache_set_flush, system_wq);
1837 void bch_cache_set_stop(struct cache_set *c)
1839 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1840 /* closure_fn set to __cache_set_unregister() */
1841 closure_queue(&c->caching);
1844 void bch_cache_set_unregister(struct cache_set *c)
1846 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1847 bch_cache_set_stop(c);
1850 #define alloc_meta_bucket_pages(gfp, sb) \
1851 ((void *) __get_free_pages(__GFP_ZERO|__GFP_COMP|gfp, ilog2(meta_bucket_pages(sb))))
1853 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1856 struct cache *ca = container_of(sb, struct cache, sb);
1857 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1862 __module_get(THIS_MODULE);
1863 closure_init(&c->cl, NULL);
1864 set_closure_fn(&c->cl, cache_set_free, system_wq);
1866 closure_init(&c->caching, &c->cl);
1867 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1869 /* Maybe create continue_at_noreturn() and use it here? */
1870 closure_set_stopped(&c->cl);
1871 closure_put(&c->cl);
1873 kobject_init(&c->kobj, &bch_cache_set_ktype);
1874 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1876 bch_cache_accounting_init(&c->accounting, &c->cl);
1878 memcpy(c->set_uuid, sb->set_uuid, 16);
1882 c->bucket_bits = ilog2(sb->bucket_size);
1883 c->block_bits = ilog2(sb->block_size);
1884 c->nr_uuids = meta_bucket_bytes(sb) / sizeof(struct uuid_entry);
1885 c->devices_max_used = 0;
1886 atomic_set(&c->attached_dev_nr, 0);
1887 c->btree_pages = meta_bucket_pages(sb);
1888 if (c->btree_pages > BTREE_MAX_PAGES)
1889 c->btree_pages = max_t(int, c->btree_pages / 4,
1892 sema_init(&c->sb_write_mutex, 1);
1893 mutex_init(&c->bucket_lock);
1894 init_waitqueue_head(&c->btree_cache_wait);
1895 spin_lock_init(&c->btree_cannibalize_lock);
1896 init_waitqueue_head(&c->bucket_wait);
1897 init_waitqueue_head(&c->gc_wait);
1898 sema_init(&c->uuid_write_mutex, 1);
1900 spin_lock_init(&c->btree_gc_time.lock);
1901 spin_lock_init(&c->btree_split_time.lock);
1902 spin_lock_init(&c->btree_read_time.lock);
1904 bch_moving_init_cache_set(c);
1906 INIT_LIST_HEAD(&c->list);
1907 INIT_LIST_HEAD(&c->cached_devs);
1908 INIT_LIST_HEAD(&c->btree_cache);
1909 INIT_LIST_HEAD(&c->btree_cache_freeable);
1910 INIT_LIST_HEAD(&c->btree_cache_freed);
1911 INIT_LIST_HEAD(&c->data_buckets);
1913 iter_size = ((meta_bucket_pages(sb) * PAGE_SECTORS) / sb->block_size + 1) *
1914 sizeof(struct btree_iter_set);
1916 c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL);
1920 if (mempool_init_slab_pool(&c->search, 32, bch_search_cache))
1923 if (mempool_init_kmalloc_pool(&c->bio_meta, 2,
1924 sizeof(struct bbio) +
1925 sizeof(struct bio_vec) * meta_bucket_pages(sb)))
1928 if (mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size))
1931 if (bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1932 BIOSET_NEED_RESCUER))
1935 c->uuids = alloc_meta_bucket_pages(GFP_KERNEL, sb);
1939 c->moving_gc_wq = alloc_workqueue("bcache_gc", WQ_MEM_RECLAIM, 0);
1940 if (!c->moving_gc_wq)
1943 if (bch_journal_alloc(c))
1946 if (bch_btree_cache_alloc(c))
1949 if (bch_open_buckets_alloc(c))
1952 if (bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1955 c->congested_read_threshold_us = 2000;
1956 c->congested_write_threshold_us = 20000;
1957 c->error_limit = DEFAULT_IO_ERROR_LIMIT;
1958 c->idle_max_writeback_rate_enabled = 1;
1959 WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1963 bch_cache_set_unregister(c);
1967 static int run_cache_set(struct cache_set *c)
1969 const char *err = "cannot allocate memory";
1970 struct cached_dev *dc, *t;
1971 struct cache *ca = c->cache;
1974 struct journal_replay *l;
1976 closure_init_stack(&cl);
1978 c->nbuckets = ca->sb.nbuckets;
1981 if (CACHE_SYNC(&c->cache->sb)) {
1985 err = "cannot allocate memory for journal";
1986 if (bch_journal_read(c, &journal))
1989 pr_debug("btree_journal_read() done\n");
1991 err = "no journal entries found";
1992 if (list_empty(&journal))
1995 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1997 err = "IO error reading priorities";
1998 if (prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]))
2002 * If prio_read() fails it'll call cache_set_error and we'll
2003 * tear everything down right away, but if we perhaps checked
2004 * sooner we could avoid journal replay.
2009 err = "bad btree root";
2010 if (__bch_btree_ptr_invalid(c, k))
2013 err = "error reading btree root";
2014 c->root = bch_btree_node_get(c, NULL, k,
2017 if (IS_ERR_OR_NULL(c->root))
2020 list_del_init(&c->root->list);
2021 rw_unlock(true, c->root);
2023 err = uuid_read(c, j, &cl);
2027 err = "error in recovery";
2028 if (bch_btree_check(c))
2031 bch_journal_mark(c, &journal);
2032 bch_initial_gc_finish(c);
2033 pr_debug("btree_check() done\n");
2036 * bcache_journal_next() can't happen sooner, or
2037 * btree_gc_finish() will give spurious errors about last_gc >
2038 * gc_gen - this is a hack but oh well.
2040 bch_journal_next(&c->journal);
2042 err = "error starting allocator thread";
2043 if (bch_cache_allocator_start(ca))
2047 * First place it's safe to allocate: btree_check() and
2048 * btree_gc_finish() have to run before we have buckets to
2049 * allocate, and bch_bucket_alloc_set() might cause a journal
2050 * entry to be written so bcache_journal_next() has to be called
2053 * If the uuids were in the old format we have to rewrite them
2054 * before the next journal entry is written:
2056 if (j->version < BCACHE_JSET_VERSION_UUID)
2059 err = "bcache: replay journal failed";
2060 if (bch_journal_replay(c, &journal))
2065 pr_notice("invalidating existing data\n");
2066 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
2067 2, SB_JOURNAL_BUCKETS);
2069 for (j = 0; j < ca->sb.keys; j++)
2070 ca->sb.d[j] = ca->sb.first_bucket + j;
2072 bch_initial_gc_finish(c);
2074 err = "error starting allocator thread";
2075 if (bch_cache_allocator_start(ca))
2078 mutex_lock(&c->bucket_lock);
2079 bch_prio_write(ca, true);
2080 mutex_unlock(&c->bucket_lock);
2082 err = "cannot allocate new UUID bucket";
2083 if (__uuid_write(c))
2086 err = "cannot allocate new btree root";
2087 c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
2088 if (IS_ERR_OR_NULL(c->root))
2091 mutex_lock(&c->root->write_lock);
2092 bkey_copy_key(&c->root->key, &MAX_KEY);
2093 bch_btree_node_write(c->root, &cl);
2094 mutex_unlock(&c->root->write_lock);
2096 bch_btree_set_root(c->root);
2097 rw_unlock(true, c->root);
2100 * We don't want to write the first journal entry until
2101 * everything is set up - fortunately journal entries won't be
2102 * written until the SET_CACHE_SYNC() here:
2104 SET_CACHE_SYNC(&c->cache->sb, true);
2106 bch_journal_next(&c->journal);
2107 bch_journal_meta(c, &cl);
2110 err = "error starting gc thread";
2111 if (bch_gc_thread_start(c))
2115 c->cache->sb.last_mount = (u32)ktime_get_real_seconds();
2116 bcache_write_super(c);
2118 if (bch_has_feature_obso_large_bucket(&c->cache->sb))
2119 pr_err("Detect obsoleted large bucket layout, all attached bcache device will be read-only\n");
2121 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2122 bch_cached_dev_attach(dc, c, NULL);
2126 set_bit(CACHE_SET_RUNNING, &c->flags);
2129 while (!list_empty(&journal)) {
2130 l = list_first_entry(&journal, struct journal_replay, list);
2137 bch_cache_set_error(c, "%s", err);
2142 static const char *register_cache_set(struct cache *ca)
2145 const char *err = "cannot allocate memory";
2146 struct cache_set *c;
2148 list_for_each_entry(c, &bch_cache_sets, list)
2149 if (!memcmp(c->set_uuid, ca->sb.set_uuid, 16)) {
2151 return "duplicate cache set member";
2156 c = bch_cache_set_alloc(&ca->sb);
2160 err = "error creating kobject";
2161 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->set_uuid) ||
2162 kobject_add(&c->internal, &c->kobj, "internal"))
2165 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2168 bch_debug_init_cache_set(c);
2170 list_add(&c->list, &bch_cache_sets);
2172 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2173 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2174 sysfs_create_link(&c->kobj, &ca->kobj, buf))
2177 kobject_get(&ca->kobj);
2179 ca->set->cache = ca;
2181 err = "failed to run cache set";
2182 if (run_cache_set(c) < 0)
2187 bch_cache_set_unregister(c);
2193 /* When ca->kobj released */
2194 void bch_cache_release(struct kobject *kobj)
2196 struct cache *ca = container_of(kobj, struct cache, kobj);
2200 BUG_ON(ca->set->cache != ca);
2201 ca->set->cache = NULL;
2204 free_pages((unsigned long) ca->disk_buckets, ilog2(meta_bucket_pages(&ca->sb)));
2205 kfree(ca->prio_buckets);
2208 free_heap(&ca->heap);
2209 free_fifo(&ca->free_inc);
2211 for (i = 0; i < RESERVE_NR; i++)
2212 free_fifo(&ca->free[i]);
2215 put_page(virt_to_page(ca->sb_disk));
2217 if (!IS_ERR_OR_NULL(ca->bdev))
2218 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2221 module_put(THIS_MODULE);
2224 static int cache_alloc(struct cache *ca)
2227 size_t btree_buckets;
2230 const char *err = NULL;
2232 __module_get(THIS_MODULE);
2233 kobject_init(&ca->kobj, &bch_cache_ktype);
2235 bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2238 * when ca->sb.njournal_buckets is not zero, journal exists,
2239 * and in bch_journal_replay(), tree node may split,
2240 * so bucket of RESERVE_BTREE type is needed,
2241 * the worst situation is all journal buckets are valid journal,
2242 * and all the keys need to replay,
2243 * so the number of RESERVE_BTREE type buckets should be as much
2244 * as journal buckets
2246 btree_buckets = ca->sb.njournal_buckets ?: 8;
2247 free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
2250 err = "ca->sb.nbuckets is too small";
2254 if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
2256 err = "ca->free[RESERVE_BTREE] alloc failed";
2257 goto err_btree_alloc;
2260 if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
2262 err = "ca->free[RESERVE_PRIO] alloc failed";
2263 goto err_prio_alloc;
2266 if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
2267 err = "ca->free[RESERVE_MOVINGGC] alloc failed";
2268 goto err_movinggc_alloc;
2271 if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
2272 err = "ca->free[RESERVE_NONE] alloc failed";
2273 goto err_none_alloc;
2276 if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
2277 err = "ca->free_inc alloc failed";
2278 goto err_free_inc_alloc;
2281 if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
2282 err = "ca->heap alloc failed";
2283 goto err_heap_alloc;
2286 ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2289 err = "ca->buckets alloc failed";
2290 goto err_buckets_alloc;
2293 ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
2294 prio_buckets(ca), 2),
2296 if (!ca->prio_buckets) {
2297 err = "ca->prio_buckets alloc failed";
2298 goto err_prio_buckets_alloc;
2301 ca->disk_buckets = alloc_meta_bucket_pages(GFP_KERNEL, &ca->sb);
2302 if (!ca->disk_buckets) {
2303 err = "ca->disk_buckets alloc failed";
2304 goto err_disk_buckets_alloc;
2307 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2309 for_each_bucket(b, ca)
2310 atomic_set(&b->pin, 0);
2313 err_disk_buckets_alloc:
2314 kfree(ca->prio_buckets);
2315 err_prio_buckets_alloc:
2318 free_heap(&ca->heap);
2320 free_fifo(&ca->free_inc);
2322 free_fifo(&ca->free[RESERVE_NONE]);
2324 free_fifo(&ca->free[RESERVE_MOVINGGC]);
2326 free_fifo(&ca->free[RESERVE_PRIO]);
2328 free_fifo(&ca->free[RESERVE_BTREE]);
2331 module_put(THIS_MODULE);
2333 pr_notice("error %pg: %s\n", ca->bdev, err);
2337 static int register_cache(struct cache_sb *sb, struct cache_sb_disk *sb_disk,
2338 struct block_device *bdev, struct cache *ca)
2340 const char *err = NULL; /* must be set for any error case */
2343 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2345 ca->bdev->bd_holder = ca;
2346 ca->sb_disk = sb_disk;
2348 if (blk_queue_discard(bdev_get_queue(bdev)))
2349 ca->discard = CACHE_DISCARD(&ca->sb);
2351 ret = cache_alloc(ca);
2354 * If we failed here, it means ca->kobj is not initialized yet,
2355 * kobject_put() won't be called and there is no chance to
2356 * call blkdev_put() to bdev in bch_cache_release(). So we
2357 * explicitly call blkdev_put() here.
2359 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2361 err = "cache_alloc(): -ENOMEM";
2362 else if (ret == -EPERM)
2363 err = "cache_alloc(): cache device is too small";
2365 err = "cache_alloc(): unknown error";
2369 if (kobject_add(&ca->kobj, bdev_kobj(bdev), "bcache")) {
2370 err = "error calling kobject_add";
2375 mutex_lock(&bch_register_lock);
2376 err = register_cache_set(ca);
2377 mutex_unlock(&bch_register_lock);
2384 pr_info("registered cache device %pg\n", ca->bdev);
2387 kobject_put(&ca->kobj);
2391 pr_notice("error %pg: %s\n", ca->bdev, err);
2396 /* Global interfaces/init */
2398 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2399 const char *buffer, size_t size);
2400 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2401 struct kobj_attribute *attr,
2402 const char *buffer, size_t size);
2404 kobj_attribute_write(register, register_bcache);
2405 kobj_attribute_write(register_quiet, register_bcache);
2406 kobj_attribute_write(pendings_cleanup, bch_pending_bdevs_cleanup);
2408 static bool bch_is_open_backing(dev_t dev)
2410 struct cache_set *c, *tc;
2411 struct cached_dev *dc, *t;
2413 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2414 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2415 if (dc->bdev->bd_dev == dev)
2417 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2418 if (dc->bdev->bd_dev == dev)
2423 static bool bch_is_open_cache(dev_t dev)
2425 struct cache_set *c, *tc;
2427 list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
2428 struct cache *ca = c->cache;
2430 if (ca->bdev->bd_dev == dev)
2437 static bool bch_is_open(dev_t dev)
2439 return bch_is_open_cache(dev) || bch_is_open_backing(dev);
2442 struct async_reg_args {
2443 struct delayed_work reg_work;
2445 struct cache_sb *sb;
2446 struct cache_sb_disk *sb_disk;
2447 struct block_device *bdev;
2450 static void register_bdev_worker(struct work_struct *work)
2453 struct async_reg_args *args =
2454 container_of(work, struct async_reg_args, reg_work.work);
2455 struct cached_dev *dc;
2457 dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2460 put_page(virt_to_page(args->sb_disk));
2461 blkdev_put(args->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2465 mutex_lock(&bch_register_lock);
2466 if (register_bdev(args->sb, args->sb_disk, args->bdev, dc) < 0)
2468 mutex_unlock(&bch_register_lock);
2472 pr_info("error %s: fail to register backing device\n",
2477 module_put(THIS_MODULE);
2480 static void register_cache_worker(struct work_struct *work)
2483 struct async_reg_args *args =
2484 container_of(work, struct async_reg_args, reg_work.work);
2487 ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2490 put_page(virt_to_page(args->sb_disk));
2491 blkdev_put(args->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2495 /* blkdev_put() will be called in bch_cache_release() */
2496 if (register_cache(args->sb, args->sb_disk, args->bdev, ca) != 0)
2501 pr_info("error %s: fail to register cache device\n",
2506 module_put(THIS_MODULE);
2509 static void register_device_async(struct async_reg_args *args)
2511 if (SB_IS_BDEV(args->sb))
2512 INIT_DELAYED_WORK(&args->reg_work, register_bdev_worker);
2514 INIT_DELAYED_WORK(&args->reg_work, register_cache_worker);
2516 /* 10 jiffies is enough for a delay */
2517 queue_delayed_work(system_wq, &args->reg_work, 10);
2520 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2521 const char *buffer, size_t size)
2525 struct cache_sb *sb;
2526 struct cache_sb_disk *sb_disk;
2527 struct block_device *bdev;
2529 bool async_registration = false;
2531 #ifdef CONFIG_BCACHE_ASYNC_REGISTRATION
2532 async_registration = true;
2536 err = "failed to reference bcache module";
2537 if (!try_module_get(THIS_MODULE))
2540 /* For latest state of bcache_is_reboot */
2542 err = "bcache is in reboot";
2543 if (bcache_is_reboot)
2544 goto out_module_put;
2547 err = "cannot allocate memory";
2548 path = kstrndup(buffer, size, GFP_KERNEL);
2550 goto out_module_put;
2552 sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2557 err = "failed to open device";
2558 bdev = blkdev_get_by_path(strim(path),
2559 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2562 if (bdev == ERR_PTR(-EBUSY)) {
2565 mutex_lock(&bch_register_lock);
2566 if (lookup_bdev(strim(path), &dev) == 0 &&
2568 err = "device already registered";
2570 err = "device busy";
2571 mutex_unlock(&bch_register_lock);
2572 if (attr == &ksysfs_register_quiet)
2578 err = "failed to set blocksize";
2579 if (set_blocksize(bdev, 4096))
2580 goto out_blkdev_put;
2582 err = read_super(sb, bdev, &sb_disk);
2584 goto out_blkdev_put;
2586 err = "failed to register device";
2588 if (async_registration) {
2589 /* register in asynchronous way */
2590 struct async_reg_args *args =
2591 kzalloc(sizeof(struct async_reg_args), GFP_KERNEL);
2595 err = "cannot allocate memory";
2596 goto out_put_sb_page;
2601 args->sb_disk = sb_disk;
2603 register_device_async(args);
2604 /* No wait and returns to user space */
2608 if (SB_IS_BDEV(sb)) {
2609 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2613 err = "cannot allocate memory";
2614 goto out_put_sb_page;
2617 mutex_lock(&bch_register_lock);
2618 ret = register_bdev(sb, sb_disk, bdev, dc);
2619 mutex_unlock(&bch_register_lock);
2620 /* blkdev_put() will be called in cached_dev_free() */
2624 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2628 err = "cannot allocate memory";
2629 goto out_put_sb_page;
2632 /* blkdev_put() will be called in bch_cache_release() */
2633 ret = register_cache(sb, sb_disk, bdev, ca);
2641 module_put(THIS_MODULE);
2646 put_page(virt_to_page(sb_disk));
2648 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2655 module_put(THIS_MODULE);
2657 pr_info("error %s: %s\n", path?path:"", err);
2663 struct list_head list;
2664 struct cached_dev *dc;
2667 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2668 struct kobj_attribute *attr,
2672 LIST_HEAD(pending_devs);
2674 struct cached_dev *dc, *tdc;
2675 struct pdev *pdev, *tpdev;
2676 struct cache_set *c, *tc;
2678 mutex_lock(&bch_register_lock);
2679 list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
2680 pdev = kmalloc(sizeof(struct pdev), GFP_KERNEL);
2684 list_add(&pdev->list, &pending_devs);
2687 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2688 char *pdev_set_uuid = pdev->dc->sb.set_uuid;
2689 list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
2690 char *set_uuid = c->set_uuid;
2692 if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
2693 list_del(&pdev->list);
2699 mutex_unlock(&bch_register_lock);
2701 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2702 pr_info("delete pdev %p\n", pdev);
2703 list_del(&pdev->list);
2704 bcache_device_stop(&pdev->dc->disk);
2711 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2713 if (bcache_is_reboot)
2716 if (code == SYS_DOWN ||
2718 code == SYS_POWER_OFF) {
2720 unsigned long start = jiffies;
2721 bool stopped = false;
2723 struct cache_set *c, *tc;
2724 struct cached_dev *dc, *tdc;
2726 mutex_lock(&bch_register_lock);
2728 if (bcache_is_reboot)
2731 /* New registration is rejected since now */
2732 bcache_is_reboot = true;
2734 * Make registering caller (if there is) on other CPU
2735 * core know bcache_is_reboot set to true earlier
2739 if (list_empty(&bch_cache_sets) &&
2740 list_empty(&uncached_devices))
2743 mutex_unlock(&bch_register_lock);
2745 pr_info("Stopping all devices:\n");
2748 * The reason bch_register_lock is not held to call
2749 * bch_cache_set_stop() and bcache_device_stop() is to
2750 * avoid potential deadlock during reboot, because cache
2751 * set or bcache device stopping process will acquire
2752 * bch_register_lock too.
2754 * We are safe here because bcache_is_reboot sets to
2755 * true already, register_bcache() will reject new
2756 * registration now. bcache_is_reboot also makes sure
2757 * bcache_reboot() won't be re-entered on by other thread,
2758 * so there is no race in following list iteration by
2759 * list_for_each_entry_safe().
2761 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2762 bch_cache_set_stop(c);
2764 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2765 bcache_device_stop(&dc->disk);
2769 * Give an early chance for other kthreads and
2770 * kworkers to stop themselves
2774 /* What's a condition variable? */
2776 long timeout = start + 10 * HZ - jiffies;
2778 mutex_lock(&bch_register_lock);
2779 stopped = list_empty(&bch_cache_sets) &&
2780 list_empty(&uncached_devices);
2782 if (timeout < 0 || stopped)
2785 prepare_to_wait(&unregister_wait, &wait,
2786 TASK_UNINTERRUPTIBLE);
2788 mutex_unlock(&bch_register_lock);
2789 schedule_timeout(timeout);
2792 finish_wait(&unregister_wait, &wait);
2795 pr_info("All devices stopped\n");
2797 pr_notice("Timeout waiting for devices to be closed\n");
2799 mutex_unlock(&bch_register_lock);
2805 static struct notifier_block reboot = {
2806 .notifier_call = bcache_reboot,
2807 .priority = INT_MAX, /* before any real devices */
2810 static void bcache_exit(void)
2815 kobject_put(bcache_kobj);
2817 destroy_workqueue(bcache_wq);
2819 destroy_workqueue(bch_journal_wq);
2821 destroy_workqueue(bch_flush_wq);
2825 unregister_blkdev(bcache_major, "bcache");
2826 unregister_reboot_notifier(&reboot);
2827 mutex_destroy(&bch_register_lock);
2830 /* Check and fixup module parameters */
2831 static void check_module_parameters(void)
2833 if (bch_cutoff_writeback_sync == 0)
2834 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
2835 else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
2836 pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u\n",
2837 bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
2838 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
2841 if (bch_cutoff_writeback == 0)
2842 bch_cutoff_writeback = CUTOFF_WRITEBACK;
2843 else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
2844 pr_warn("set bch_cutoff_writeback (%u) to max value %u\n",
2845 bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
2846 bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
2849 if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
2850 pr_warn("set bch_cutoff_writeback (%u) to %u\n",
2851 bch_cutoff_writeback, bch_cutoff_writeback_sync);
2852 bch_cutoff_writeback = bch_cutoff_writeback_sync;
2856 static int __init bcache_init(void)
2858 static const struct attribute *files[] = {
2859 &ksysfs_register.attr,
2860 &ksysfs_register_quiet.attr,
2861 &ksysfs_pendings_cleanup.attr,
2865 check_module_parameters();
2867 mutex_init(&bch_register_lock);
2868 init_waitqueue_head(&unregister_wait);
2869 register_reboot_notifier(&reboot);
2871 bcache_major = register_blkdev(0, "bcache");
2872 if (bcache_major < 0) {
2873 unregister_reboot_notifier(&reboot);
2874 mutex_destroy(&bch_register_lock);
2875 return bcache_major;
2878 if (bch_btree_init())
2881 bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2886 * Let's not make this `WQ_MEM_RECLAIM` for the following reasons:
2888 * 1. It used `system_wq` before which also does no memory reclaim.
2889 * 2. With `WQ_MEM_RECLAIM` desktop stalls, increased boot times, and
2890 * reduced throughput can be observed.
2892 * We still want to user our own queue to not congest the `system_wq`.
2894 bch_flush_wq = alloc_workqueue("bch_flush", 0, 0);
2898 bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
2899 if (!bch_journal_wq)
2902 bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2906 if (bch_request_init() ||
2907 sysfs_create_files(bcache_kobj, files))
2911 closure_debug_init();
2913 bcache_is_reboot = false;
2924 module_exit(bcache_exit);
2925 module_init(bcache_init);
2927 module_param(bch_cutoff_writeback, uint, 0);
2928 MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
2930 module_param(bch_cutoff_writeback_sync, uint, 0);
2931 MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
2933 MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
2934 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
2935 MODULE_LICENSE("GPL");