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/debugfs.h>
20 #include <linux/genhd.h>
21 #include <linux/idr.h>
22 #include <linux/kthread.h>
23 #include <linux/workqueue.h>
24 #include <linux/module.h>
25 #include <linux/random.h>
26 #include <linux/reboot.h>
27 #include <linux/sysfs.h>
29 unsigned int bch_cutoff_writeback;
30 unsigned int bch_cutoff_writeback_sync;
32 static const char bcache_magic[] = {
33 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
34 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
37 static const char invalid_uuid[] = {
38 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
39 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
42 static struct kobject *bcache_kobj;
43 struct mutex bch_register_lock;
44 bool bcache_is_reboot;
45 LIST_HEAD(bch_cache_sets);
46 static LIST_HEAD(uncached_devices);
48 static int bcache_major;
49 static DEFINE_IDA(bcache_device_idx);
50 static wait_queue_head_t unregister_wait;
51 struct workqueue_struct *bcache_wq;
52 struct workqueue_struct *bch_journal_wq;
55 #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
56 /* limitation of partitions number on single bcache device */
57 #define BCACHE_MINORS 128
58 /* limitation of bcache devices number on single system */
59 #define BCACHE_DEVICE_IDX_MAX ((1U << MINORBITS)/BCACHE_MINORS)
63 static unsigned int get_bucket_size(struct cache_sb *sb, struct cache_sb_disk *s)
65 unsigned int bucket_size = le16_to_cpu(s->bucket_size);
67 if (sb->version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES &&
68 bch_has_feature_large_bucket(sb))
69 bucket_size |= le16_to_cpu(s->bucket_size_hi) << 16;
74 static const char *read_super_common(struct cache_sb *sb, struct block_device *bdev,
75 struct cache_sb_disk *s)
80 sb->first_bucket= le16_to_cpu(s->first_bucket);
81 sb->nbuckets = le64_to_cpu(s->nbuckets);
82 sb->bucket_size = get_bucket_size(sb, s);
84 sb->nr_in_set = le16_to_cpu(s->nr_in_set);
85 sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
87 err = "Too many journal buckets";
88 if (sb->keys > SB_JOURNAL_BUCKETS)
91 err = "Too many buckets";
92 if (sb->nbuckets > LONG_MAX)
95 err = "Not enough buckets";
96 if (sb->nbuckets < 1 << 7)
99 err = "Bad block size (not power of 2)";
100 if (!is_power_of_2(sb->block_size))
103 err = "Bad block size (larger than page size)";
104 if (sb->block_size > PAGE_SECTORS)
107 err = "Bad bucket size (not power of 2)";
108 if (!is_power_of_2(sb->bucket_size))
111 err = "Bad bucket size (smaller than page size)";
112 if (sb->bucket_size < PAGE_SECTORS)
115 err = "Invalid superblock: device too small";
116 if (get_capacity(bdev->bd_disk) <
117 sb->bucket_size * sb->nbuckets)
121 if (bch_is_zero(sb->set_uuid, 16))
124 err = "Bad cache device number in set";
125 if (!sb->nr_in_set ||
126 sb->nr_in_set <= sb->nr_this_dev ||
127 sb->nr_in_set > MAX_CACHES_PER_SET)
130 err = "Journal buckets not sequential";
131 for (i = 0; i < sb->keys; i++)
132 if (sb->d[i] != sb->first_bucket + i)
135 err = "Too many journal buckets";
136 if (sb->first_bucket + sb->keys > sb->nbuckets)
139 err = "Invalid superblock: first bucket comes before end of super";
140 if (sb->first_bucket * sb->bucket_size < 16)
149 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
150 struct cache_sb_disk **res)
153 struct cache_sb_disk *s;
157 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
158 SB_OFFSET >> PAGE_SHIFT, GFP_KERNEL);
161 s = page_address(page) + offset_in_page(SB_OFFSET);
163 sb->offset = le64_to_cpu(s->offset);
164 sb->version = le64_to_cpu(s->version);
166 memcpy(sb->magic, s->magic, 16);
167 memcpy(sb->uuid, s->uuid, 16);
168 memcpy(sb->set_uuid, s->set_uuid, 16);
169 memcpy(sb->label, s->label, SB_LABEL_SIZE);
171 sb->flags = le64_to_cpu(s->flags);
172 sb->seq = le64_to_cpu(s->seq);
173 sb->last_mount = le32_to_cpu(s->last_mount);
174 sb->keys = le16_to_cpu(s->keys);
176 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
177 sb->d[i] = le64_to_cpu(s->d[i]);
179 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u\n",
180 sb->version, sb->flags, sb->seq, sb->keys);
182 err = "Not a bcache superblock (bad offset)";
183 if (sb->offset != SB_SECTOR)
186 err = "Not a bcache superblock (bad magic)";
187 if (memcmp(sb->magic, bcache_magic, 16))
190 err = "Bad checksum";
191 if (s->csum != csum_set(s))
195 if (bch_is_zero(sb->uuid, 16))
198 sb->block_size = le16_to_cpu(s->block_size);
200 err = "Superblock block size smaller than device block size";
201 if (sb->block_size << 9 < bdev_logical_block_size(bdev))
204 switch (sb->version) {
205 case BCACHE_SB_VERSION_BDEV:
206 sb->data_offset = BDEV_DATA_START_DEFAULT;
208 case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
209 case BCACHE_SB_VERSION_BDEV_WITH_FEATURES:
210 sb->data_offset = le64_to_cpu(s->data_offset);
212 err = "Bad data offset";
213 if (sb->data_offset < BDEV_DATA_START_DEFAULT)
217 case BCACHE_SB_VERSION_CDEV:
218 case BCACHE_SB_VERSION_CDEV_WITH_UUID:
219 err = read_super_common(sb, bdev, s);
223 case BCACHE_SB_VERSION_CDEV_WITH_FEATURES:
225 * Feature bits are needed in read_super_common(),
226 * convert them firstly.
228 sb->feature_compat = le64_to_cpu(s->feature_compat);
229 sb->feature_incompat = le64_to_cpu(s->feature_incompat);
230 sb->feature_ro_compat = le64_to_cpu(s->feature_ro_compat);
231 err = read_super_common(sb, bdev, s);
236 err = "Unsupported superblock version";
240 sb->last_mount = (u32)ktime_get_real_seconds();
248 static void write_bdev_super_endio(struct bio *bio)
250 struct cached_dev *dc = bio->bi_private;
253 bch_count_backing_io_errors(dc, bio);
255 closure_put(&dc->sb_write);
258 static void __write_super(struct cache_sb *sb, struct cache_sb_disk *out,
263 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META;
264 bio->bi_iter.bi_sector = SB_SECTOR;
265 __bio_add_page(bio, virt_to_page(out), SB_SIZE,
266 offset_in_page(out));
268 out->offset = cpu_to_le64(sb->offset);
270 memcpy(out->uuid, sb->uuid, 16);
271 memcpy(out->set_uuid, sb->set_uuid, 16);
272 memcpy(out->label, sb->label, SB_LABEL_SIZE);
274 out->flags = cpu_to_le64(sb->flags);
275 out->seq = cpu_to_le64(sb->seq);
277 out->last_mount = cpu_to_le32(sb->last_mount);
278 out->first_bucket = cpu_to_le16(sb->first_bucket);
279 out->keys = cpu_to_le16(sb->keys);
281 for (i = 0; i < sb->keys; i++)
282 out->d[i] = cpu_to_le64(sb->d[i]);
284 if (sb->version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES) {
285 out->feature_compat = cpu_to_le64(sb->feature_compat);
286 out->feature_incompat = cpu_to_le64(sb->feature_incompat);
287 out->feature_ro_compat = cpu_to_le64(sb->feature_ro_compat);
290 out->version = cpu_to_le64(sb->version);
291 out->csum = csum_set(out);
293 pr_debug("ver %llu, flags %llu, seq %llu\n",
294 sb->version, sb->flags, sb->seq);
299 static void bch_write_bdev_super_unlock(struct closure *cl)
301 struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
303 up(&dc->sb_write_mutex);
306 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
308 struct closure *cl = &dc->sb_write;
309 struct bio *bio = &dc->sb_bio;
311 down(&dc->sb_write_mutex);
312 closure_init(cl, parent);
314 bio_init(bio, dc->sb_bv, 1);
315 bio_set_dev(bio, dc->bdev);
316 bio->bi_end_io = write_bdev_super_endio;
317 bio->bi_private = dc;
320 /* I/O request sent to backing device */
321 __write_super(&dc->sb, dc->sb_disk, bio);
323 closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
326 static void write_super_endio(struct bio *bio)
328 struct cache *ca = bio->bi_private;
331 bch_count_io_errors(ca, bio->bi_status, 0,
332 "writing superblock");
333 closure_put(&ca->set->sb_write);
336 static void bcache_write_super_unlock(struct closure *cl)
338 struct cache_set *c = container_of(cl, struct cache_set, sb_write);
340 up(&c->sb_write_mutex);
343 void bcache_write_super(struct cache_set *c)
345 struct closure *cl = &c->sb_write;
347 unsigned int i, version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
349 down(&c->sb_write_mutex);
350 closure_init(cl, &c->cl);
354 if (c->sb.version > version)
355 version = c->sb.version;
357 for_each_cache(ca, c, i) {
358 struct bio *bio = &ca->sb_bio;
360 ca->sb.version = version;
361 ca->sb.seq = c->sb.seq;
362 ca->sb.last_mount = c->sb.last_mount;
364 SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
366 bio_init(bio, ca->sb_bv, 1);
367 bio_set_dev(bio, ca->bdev);
368 bio->bi_end_io = write_super_endio;
369 bio->bi_private = ca;
372 __write_super(&ca->sb, ca->sb_disk, bio);
375 closure_return_with_destructor(cl, bcache_write_super_unlock);
380 static void uuid_endio(struct bio *bio)
382 struct closure *cl = bio->bi_private;
383 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
385 cache_set_err_on(bio->bi_status, c, "accessing uuids");
386 bch_bbio_free(bio, c);
390 static void uuid_io_unlock(struct closure *cl)
392 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
394 up(&c->uuid_write_mutex);
397 static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
398 struct bkey *k, struct closure *parent)
400 struct closure *cl = &c->uuid_write;
401 struct uuid_entry *u;
406 down(&c->uuid_write_mutex);
407 closure_init(cl, parent);
409 for (i = 0; i < KEY_PTRS(k); i++) {
410 struct bio *bio = bch_bbio_alloc(c);
412 bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
413 bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
415 bio->bi_end_io = uuid_endio;
416 bio->bi_private = cl;
417 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
418 bch_bio_map(bio, c->uuids);
420 bch_submit_bbio(bio, c, k, i);
422 if (op != REQ_OP_WRITE)
426 bch_extent_to_text(buf, sizeof(buf), k);
427 pr_debug("%s UUIDs at %s\n", op == REQ_OP_WRITE ? "wrote" : "read", buf);
429 for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
430 if (!bch_is_zero(u->uuid, 16))
431 pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u\n",
432 u - c->uuids, u->uuid, u->label,
433 u->first_reg, u->last_reg, u->invalidated);
435 closure_return_with_destructor(cl, uuid_io_unlock);
438 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
440 struct bkey *k = &j->uuid_bucket;
442 if (__bch_btree_ptr_invalid(c, k))
443 return "bad uuid pointer";
445 bkey_copy(&c->uuid_bucket, k);
446 uuid_io(c, REQ_OP_READ, 0, k, cl);
448 if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
449 struct uuid_entry_v0 *u0 = (void *) c->uuids;
450 struct uuid_entry *u1 = (void *) c->uuids;
456 * Since the new uuid entry is bigger than the old, we have to
457 * convert starting at the highest memory address and work down
458 * in order to do it in place
461 for (i = c->nr_uuids - 1;
464 memcpy(u1[i].uuid, u0[i].uuid, 16);
465 memcpy(u1[i].label, u0[i].label, 32);
467 u1[i].first_reg = u0[i].first_reg;
468 u1[i].last_reg = u0[i].last_reg;
469 u1[i].invalidated = u0[i].invalidated;
479 static int __uuid_write(struct cache_set *c)
486 closure_init_stack(&cl);
487 lockdep_assert_held(&bch_register_lock);
489 if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, true))
492 size = meta_bucket_pages(&c->sb) * PAGE_SECTORS;
493 SET_KEY_SIZE(&k.key, size);
494 uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
497 /* Only one bucket used for uuid write */
498 ca = PTR_CACHE(c, &k.key, 0);
499 atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
501 bkey_copy(&c->uuid_bucket, &k.key);
506 int bch_uuid_write(struct cache_set *c)
508 int ret = __uuid_write(c);
511 bch_journal_meta(c, NULL);
516 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
518 struct uuid_entry *u;
521 u < c->uuids + c->nr_uuids; u++)
522 if (!memcmp(u->uuid, uuid, 16))
528 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
530 static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
532 return uuid_find(c, zero_uuid);
536 * Bucket priorities/gens:
538 * For each bucket, we store on disk its
542 * See alloc.c for an explanation of the gen. The priority is used to implement
543 * lru (and in the future other) cache replacement policies; for most purposes
544 * it's just an opaque integer.
546 * The gens and the priorities don't have a whole lot to do with each other, and
547 * it's actually the gens that must be written out at specific times - it's no
548 * big deal if the priorities don't get written, if we lose them we just reuse
549 * buckets in suboptimal order.
551 * On disk they're stored in a packed array, and in as many buckets are required
552 * to fit them all. The buckets we use to store them form a list; the journal
553 * header points to the first bucket, the first bucket points to the second
556 * This code is used by the allocation code; periodically (whenever it runs out
557 * of buckets to allocate from) the allocation code will invalidate some
558 * buckets, but it can't use those buckets until their new gens are safely on
562 static void prio_endio(struct bio *bio)
564 struct cache *ca = bio->bi_private;
566 cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
567 bch_bbio_free(bio, ca->set);
568 closure_put(&ca->prio);
571 static void prio_io(struct cache *ca, uint64_t bucket, int op,
572 unsigned long op_flags)
574 struct closure *cl = &ca->prio;
575 struct bio *bio = bch_bbio_alloc(ca->set);
577 closure_init_stack(cl);
579 bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
580 bio_set_dev(bio, ca->bdev);
581 bio->bi_iter.bi_size = meta_bucket_bytes(&ca->sb);
583 bio->bi_end_io = prio_endio;
584 bio->bi_private = ca;
585 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
586 bch_bio_map(bio, ca->disk_buckets);
588 closure_bio_submit(ca->set, bio, &ca->prio);
592 int bch_prio_write(struct cache *ca, bool wait)
598 pr_debug("free_prio=%zu, free_none=%zu, free_inc=%zu\n",
599 fifo_used(&ca->free[RESERVE_PRIO]),
600 fifo_used(&ca->free[RESERVE_NONE]),
601 fifo_used(&ca->free_inc));
604 * Pre-check if there are enough free buckets. In the non-blocking
605 * scenario it's better to fail early rather than starting to allocate
606 * buckets and do a cleanup later in case of failure.
609 size_t avail = fifo_used(&ca->free[RESERVE_PRIO]) +
610 fifo_used(&ca->free[RESERVE_NONE]);
611 if (prio_buckets(ca) > avail)
615 closure_init_stack(&cl);
617 lockdep_assert_held(&ca->set->bucket_lock);
619 ca->disk_buckets->seq++;
621 atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
622 &ca->meta_sectors_written);
624 for (i = prio_buckets(ca) - 1; i >= 0; --i) {
626 struct prio_set *p = ca->disk_buckets;
627 struct bucket_disk *d = p->data;
628 struct bucket_disk *end = d + prios_per_bucket(ca);
630 for (b = ca->buckets + i * prios_per_bucket(ca);
631 b < ca->buckets + ca->sb.nbuckets && d < end;
633 d->prio = cpu_to_le16(b->prio);
637 p->next_bucket = ca->prio_buckets[i + 1];
638 p->magic = pset_magic(&ca->sb);
639 p->csum = bch_crc64(&p->magic, meta_bucket_bytes(&ca->sb) - 8);
641 bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
642 BUG_ON(bucket == -1);
644 mutex_unlock(&ca->set->bucket_lock);
645 prio_io(ca, bucket, REQ_OP_WRITE, 0);
646 mutex_lock(&ca->set->bucket_lock);
648 ca->prio_buckets[i] = bucket;
649 atomic_dec_bug(&ca->buckets[bucket].pin);
652 mutex_unlock(&ca->set->bucket_lock);
654 bch_journal_meta(ca->set, &cl);
657 mutex_lock(&ca->set->bucket_lock);
660 * Don't want the old priorities to get garbage collected until after we
661 * finish writing the new ones, and they're journalled
663 for (i = 0; i < prio_buckets(ca); i++) {
664 if (ca->prio_last_buckets[i])
665 __bch_bucket_free(ca,
666 &ca->buckets[ca->prio_last_buckets[i]]);
668 ca->prio_last_buckets[i] = ca->prio_buckets[i];
673 static int prio_read(struct cache *ca, uint64_t bucket)
675 struct prio_set *p = ca->disk_buckets;
676 struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
678 unsigned int bucket_nr = 0;
681 for (b = ca->buckets;
682 b < ca->buckets + ca->sb.nbuckets;
685 ca->prio_buckets[bucket_nr] = bucket;
686 ca->prio_last_buckets[bucket_nr] = bucket;
689 prio_io(ca, bucket, REQ_OP_READ, 0);
692 bch_crc64(&p->magic, meta_bucket_bytes(&ca->sb) - 8)) {
693 pr_warn("bad csum reading priorities\n");
697 if (p->magic != pset_magic(&ca->sb)) {
698 pr_warn("bad magic reading priorities\n");
702 bucket = p->next_bucket;
706 b->prio = le16_to_cpu(d->prio);
707 b->gen = b->last_gc = d->gen;
717 static int open_dev(struct block_device *b, fmode_t mode)
719 struct bcache_device *d = b->bd_disk->private_data;
721 if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
728 static void release_dev(struct gendisk *b, fmode_t mode)
730 struct bcache_device *d = b->private_data;
735 static int ioctl_dev(struct block_device *b, fmode_t mode,
736 unsigned int cmd, unsigned long arg)
738 struct bcache_device *d = b->bd_disk->private_data;
740 return d->ioctl(d, mode, cmd, arg);
743 static const struct block_device_operations bcache_cached_ops = {
744 .submit_bio = cached_dev_submit_bio,
746 .release = release_dev,
748 .owner = THIS_MODULE,
751 static const struct block_device_operations bcache_flash_ops = {
752 .submit_bio = flash_dev_submit_bio,
754 .release = release_dev,
756 .owner = THIS_MODULE,
759 void bcache_device_stop(struct bcache_device *d)
761 if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
764 * - cached device: cached_dev_flush()
765 * - flash dev: flash_dev_flush()
767 closure_queue(&d->cl);
770 static void bcache_device_unlink(struct bcache_device *d)
772 lockdep_assert_held(&bch_register_lock);
774 if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
778 sysfs_remove_link(&d->c->kobj, d->name);
779 sysfs_remove_link(&d->kobj, "cache");
781 for_each_cache(ca, d->c, i)
782 bd_unlink_disk_holder(ca->bdev, d->disk);
786 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
793 for_each_cache(ca, d->c, i)
794 bd_link_disk_holder(ca->bdev, d->disk);
796 snprintf(d->name, BCACHEDEVNAME_SIZE,
797 "%s%u", name, d->id);
799 ret = sysfs_create_link(&d->kobj, &c->kobj, "cache");
801 pr_err("Couldn't create device -> cache set symlink\n");
803 ret = sysfs_create_link(&c->kobj, &d->kobj, d->name);
805 pr_err("Couldn't create cache set -> device symlink\n");
807 clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
810 static void bcache_device_detach(struct bcache_device *d)
812 lockdep_assert_held(&bch_register_lock);
814 atomic_dec(&d->c->attached_dev_nr);
816 if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
817 struct uuid_entry *u = d->c->uuids + d->id;
819 SET_UUID_FLASH_ONLY(u, 0);
820 memcpy(u->uuid, invalid_uuid, 16);
821 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
822 bch_uuid_write(d->c);
825 bcache_device_unlink(d);
827 d->c->devices[d->id] = NULL;
828 closure_put(&d->c->caching);
832 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
839 if (id >= c->devices_max_used)
840 c->devices_max_used = id + 1;
842 closure_get(&c->caching);
845 static inline int first_minor_to_idx(int first_minor)
847 return (first_minor/BCACHE_MINORS);
850 static inline int idx_to_first_minor(int idx)
852 return (idx * BCACHE_MINORS);
855 static void bcache_device_free(struct bcache_device *d)
857 struct gendisk *disk = d->disk;
859 lockdep_assert_held(&bch_register_lock);
862 pr_info("%s stopped\n", disk->disk_name);
864 pr_err("bcache device (NULL gendisk) stopped\n");
867 bcache_device_detach(d);
870 bool disk_added = (disk->flags & GENHD_FL_UP) != 0;
876 blk_cleanup_queue(disk->queue);
878 ida_simple_remove(&bcache_device_idx,
879 first_minor_to_idx(disk->first_minor));
884 bioset_exit(&d->bio_split);
885 kvfree(d->full_dirty_stripes);
886 kvfree(d->stripe_sectors_dirty);
888 closure_debug_destroy(&d->cl);
891 static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
892 sector_t sectors, struct block_device *cached_bdev,
893 const struct block_device_operations *ops)
895 struct request_queue *q;
896 const size_t max_stripes = min_t(size_t, INT_MAX,
897 SIZE_MAX / sizeof(atomic_t));
902 d->stripe_size = 1 << 31;
904 n = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
905 if (!n || n > max_stripes) {
906 pr_err("nr_stripes too large or invalid: %llu (start sector beyond end of disk?)\n",
912 n = d->nr_stripes * sizeof(atomic_t);
913 d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
914 if (!d->stripe_sectors_dirty)
917 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
918 d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
919 if (!d->full_dirty_stripes)
922 idx = ida_simple_get(&bcache_device_idx, 0,
923 BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
927 if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
928 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
931 d->disk = alloc_disk(BCACHE_MINORS);
935 set_capacity(d->disk, sectors);
936 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
938 d->disk->major = bcache_major;
939 d->disk->first_minor = idx_to_first_minor(idx);
941 d->disk->private_data = d;
943 q = blk_alloc_queue(NUMA_NO_NODE);
948 q->limits.max_hw_sectors = UINT_MAX;
949 q->limits.max_sectors = UINT_MAX;
950 q->limits.max_segment_size = UINT_MAX;
951 q->limits.max_segments = BIO_MAX_PAGES;
952 blk_queue_max_discard_sectors(q, UINT_MAX);
953 q->limits.discard_granularity = 512;
954 q->limits.io_min = block_size;
955 q->limits.logical_block_size = block_size;
956 q->limits.physical_block_size = block_size;
958 if (q->limits.logical_block_size > PAGE_SIZE && cached_bdev) {
960 * This should only happen with BCACHE_SB_VERSION_BDEV.
961 * Block/page size is checked for BCACHE_SB_VERSION_CDEV.
963 pr_info("%s: sb/logical block size (%u) greater than page size (%lu) falling back to device logical block size (%u)\n",
964 d->disk->disk_name, q->limits.logical_block_size,
965 PAGE_SIZE, bdev_logical_block_size(cached_bdev));
967 /* This also adjusts physical block size/min io size if needed */
968 blk_queue_logical_block_size(q, bdev_logical_block_size(cached_bdev));
971 blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
972 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
973 blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
975 blk_queue_write_cache(q, true, true);
980 ida_simple_remove(&bcache_device_idx, idx);
987 static void calc_cached_dev_sectors(struct cache_set *c)
989 uint64_t sectors = 0;
990 struct cached_dev *dc;
992 list_for_each_entry(dc, &c->cached_devs, list)
993 sectors += bdev_sectors(dc->bdev);
995 c->cached_dev_sectors = sectors;
998 #define BACKING_DEV_OFFLINE_TIMEOUT 5
999 static int cached_dev_status_update(void *arg)
1001 struct cached_dev *dc = arg;
1002 struct request_queue *q;
1005 * If this delayed worker is stopping outside, directly quit here.
1006 * dc->io_disable might be set via sysfs interface, so check it
1009 while (!kthread_should_stop() && !dc->io_disable) {
1010 q = bdev_get_queue(dc->bdev);
1011 if (blk_queue_dying(q))
1012 dc->offline_seconds++;
1014 dc->offline_seconds = 0;
1016 if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
1017 pr_err("%s: device offline for %d seconds\n",
1018 dc->backing_dev_name,
1019 BACKING_DEV_OFFLINE_TIMEOUT);
1020 pr_err("%s: disable I/O request due to backing device offline\n",
1022 dc->io_disable = true;
1023 /* let others know earlier that io_disable is true */
1025 bcache_device_stop(&dc->disk);
1028 schedule_timeout_interruptible(HZ);
1031 wait_for_kthread_stop();
1036 int bch_cached_dev_run(struct cached_dev *dc)
1038 struct bcache_device *d = &dc->disk;
1039 char *buf = kmemdup_nul(dc->sb.label, SB_LABEL_SIZE, GFP_KERNEL);
1042 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
1043 kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf ? : ""),
1047 if (dc->io_disable) {
1048 pr_err("I/O disabled on cached dev %s\n",
1049 dc->backing_dev_name);
1056 if (atomic_xchg(&dc->running, 1)) {
1060 pr_info("cached dev %s is running already\n",
1061 dc->backing_dev_name);
1066 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
1069 closure_init_stack(&cl);
1071 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
1072 bch_write_bdev_super(dc, &cl);
1077 bd_link_disk_holder(dc->bdev, dc->disk.disk);
1079 * won't show up in the uevent file, use udevadm monitor -e instead
1080 * only class / kset properties are persistent
1082 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
1087 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
1088 sysfs_create_link(&disk_to_dev(d->disk)->kobj,
1089 &d->kobj, "bcache")) {
1090 pr_err("Couldn't create bcache dev <-> disk sysfs symlinks\n");
1094 dc->status_update_thread = kthread_run(cached_dev_status_update,
1095 dc, "bcache_status_update");
1096 if (IS_ERR(dc->status_update_thread)) {
1097 pr_warn("failed to create bcache_status_update kthread, continue to run without monitoring backing device status\n");
1104 * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
1105 * work dc->writeback_rate_update is running. Wait until the routine
1106 * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
1107 * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
1108 * seconds, give up waiting here and continue to cancel it too.
1110 static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
1112 int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
1115 if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
1119 schedule_timeout_interruptible(1);
1120 } while (time_out > 0);
1123 pr_warn("give up waiting for dc->writeback_write_update to quit\n");
1125 cancel_delayed_work_sync(&dc->writeback_rate_update);
1128 static void cached_dev_detach_finish(struct work_struct *w)
1130 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
1133 closure_init_stack(&cl);
1135 BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
1136 BUG_ON(refcount_read(&dc->count));
1139 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1140 cancel_writeback_rate_update_dwork(dc);
1142 if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
1143 kthread_stop(dc->writeback_thread);
1144 dc->writeback_thread = NULL;
1147 memset(&dc->sb.set_uuid, 0, 16);
1148 SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
1150 bch_write_bdev_super(dc, &cl);
1153 mutex_lock(&bch_register_lock);
1155 calc_cached_dev_sectors(dc->disk.c);
1156 bcache_device_detach(&dc->disk);
1157 list_move(&dc->list, &uncached_devices);
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 %s\n", dc->backing_dev_name);
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->sb.set_uuid, 16)) ||
1200 (!set_uuid && memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16)))
1204 pr_err("Can't attach %s: already attached\n",
1205 dc->backing_dev_name);
1209 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
1210 pr_err("Can't attach %s: shutting down\n",
1211 dc->backing_dev_name);
1215 if (dc->sb.block_size < c->sb.block_size) {
1217 pr_err("Couldn't attach %s: block size less than set's block size\n",
1218 dc->backing_dev_name);
1222 /* Check whether already attached */
1223 list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
1224 if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
1225 pr_err("Tried to attach %s but duplicate UUID already attached\n",
1226 dc->backing_dev_name);
1232 u = uuid_find(c, dc->sb.uuid);
1235 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1236 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1237 memcpy(u->uuid, invalid_uuid, 16);
1238 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1243 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1244 pr_err("Couldn't find uuid for %s in set\n",
1245 dc->backing_dev_name);
1249 u = uuid_find_empty(c);
1251 pr_err("Not caching %s, no room for UUID\n",
1252 dc->backing_dev_name);
1258 * Deadlocks since we're called via sysfs...
1259 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1262 if (bch_is_zero(u->uuid, 16)) {
1265 closure_init_stack(&cl);
1267 memcpy(u->uuid, dc->sb.uuid, 16);
1268 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1269 u->first_reg = u->last_reg = rtime;
1272 memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1273 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1275 bch_write_bdev_super(dc, &cl);
1278 u->last_reg = rtime;
1282 bcache_device_attach(&dc->disk, c, u - c->uuids);
1283 list_move(&dc->list, &c->cached_devs);
1284 calc_cached_dev_sectors(c);
1287 * dc->c must be set before dc->count != 0 - paired with the mb in
1291 refcount_set(&dc->count, 1);
1293 /* Block writeback thread, but spawn it */
1294 down_write(&dc->writeback_lock);
1295 if (bch_cached_dev_writeback_start(dc)) {
1296 up_write(&dc->writeback_lock);
1297 pr_err("Couldn't start writeback facilities for %s\n",
1298 dc->disk.disk->disk_name);
1302 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1303 atomic_set(&dc->has_dirty, 1);
1304 bch_writeback_queue(dc);
1307 bch_sectors_dirty_init(&dc->disk);
1309 ret = bch_cached_dev_run(dc);
1310 if (ret && (ret != -EBUSY)) {
1311 up_write(&dc->writeback_lock);
1313 * bch_register_lock is held, bcache_device_stop() is not
1314 * able to be directly called. The kthread and kworker
1315 * created previously in bch_cached_dev_writeback_start()
1316 * have to be stopped manually here.
1318 kthread_stop(dc->writeback_thread);
1319 cancel_writeback_rate_update_dwork(dc);
1320 pr_err("Couldn't run cached device %s\n",
1321 dc->backing_dev_name);
1325 bcache_device_link(&dc->disk, c, "bdev");
1326 atomic_inc(&c->attached_dev_nr);
1328 /* Allow the writeback thread to proceed */
1329 up_write(&dc->writeback_lock);
1331 pr_info("Caching %s as %s on set %pU\n",
1332 dc->backing_dev_name,
1333 dc->disk.disk->disk_name,
1334 dc->disk.c->sb.set_uuid);
1338 /* when dc->disk.kobj released */
1339 void bch_cached_dev_release(struct kobject *kobj)
1341 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1344 module_put(THIS_MODULE);
1347 static void cached_dev_free(struct closure *cl)
1349 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1351 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1352 cancel_writeback_rate_update_dwork(dc);
1354 if (!IS_ERR_OR_NULL(dc->writeback_thread))
1355 kthread_stop(dc->writeback_thread);
1356 if (!IS_ERR_OR_NULL(dc->status_update_thread))
1357 kthread_stop(dc->status_update_thread);
1359 mutex_lock(&bch_register_lock);
1361 if (atomic_read(&dc->running))
1362 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1363 bcache_device_free(&dc->disk);
1364 list_del(&dc->list);
1366 mutex_unlock(&bch_register_lock);
1369 put_page(virt_to_page(dc->sb_disk));
1371 if (!IS_ERR_OR_NULL(dc->bdev))
1372 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1374 wake_up(&unregister_wait);
1376 kobject_put(&dc->disk.kobj);
1379 static void cached_dev_flush(struct closure *cl)
1381 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1382 struct bcache_device *d = &dc->disk;
1384 mutex_lock(&bch_register_lock);
1385 bcache_device_unlink(d);
1386 mutex_unlock(&bch_register_lock);
1388 bch_cache_accounting_destroy(&dc->accounting);
1389 kobject_del(&d->kobj);
1391 continue_at(cl, cached_dev_free, system_wq);
1394 static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1398 struct request_queue *q = bdev_get_queue(dc->bdev);
1400 __module_get(THIS_MODULE);
1401 INIT_LIST_HEAD(&dc->list);
1402 closure_init(&dc->disk.cl, NULL);
1403 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1404 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1405 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1406 sema_init(&dc->sb_write_mutex, 1);
1407 INIT_LIST_HEAD(&dc->io_lru);
1408 spin_lock_init(&dc->io_lock);
1409 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1411 dc->sequential_cutoff = 4 << 20;
1413 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1414 list_add(&io->lru, &dc->io_lru);
1415 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1418 dc->disk.stripe_size = q->limits.io_opt >> 9;
1420 if (dc->disk.stripe_size)
1421 dc->partial_stripes_expensive =
1422 q->limits.raid_partial_stripes_expensive;
1424 ret = bcache_device_init(&dc->disk, block_size,
1425 dc->bdev->bd_part->nr_sects - dc->sb.data_offset,
1426 dc->bdev, &bcache_cached_ops);
1430 blk_queue_io_opt(dc->disk.disk->queue,
1431 max(queue_io_opt(dc->disk.disk->queue), queue_io_opt(q)));
1433 atomic_set(&dc->io_errors, 0);
1434 dc->io_disable = false;
1435 dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
1436 /* default to auto */
1437 dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
1439 bch_cached_dev_request_init(dc);
1440 bch_cached_dev_writeback_init(dc);
1444 /* Cached device - bcache superblock */
1446 static int register_bdev(struct cache_sb *sb, struct cache_sb_disk *sb_disk,
1447 struct block_device *bdev,
1448 struct cached_dev *dc)
1450 const char *err = "cannot allocate memory";
1451 struct cache_set *c;
1454 bdevname(bdev, dc->backing_dev_name);
1455 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1457 dc->bdev->bd_holder = dc;
1458 dc->sb_disk = sb_disk;
1460 if (cached_dev_init(dc, sb->block_size << 9))
1463 err = "error creating kobject";
1464 if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1467 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1470 pr_info("registered backing device %s\n", dc->backing_dev_name);
1472 list_add(&dc->list, &uncached_devices);
1473 /* attach to a matched cache set if it exists */
1474 list_for_each_entry(c, &bch_cache_sets, list)
1475 bch_cached_dev_attach(dc, c, NULL);
1477 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1478 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
1479 err = "failed to run cached device";
1480 ret = bch_cached_dev_run(dc);
1487 pr_notice("error %s: %s\n", dc->backing_dev_name, err);
1488 bcache_device_stop(&dc->disk);
1492 /* Flash only volumes */
1494 /* When d->kobj released */
1495 void bch_flash_dev_release(struct kobject *kobj)
1497 struct bcache_device *d = container_of(kobj, struct bcache_device,
1502 static void flash_dev_free(struct closure *cl)
1504 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1506 mutex_lock(&bch_register_lock);
1507 atomic_long_sub(bcache_dev_sectors_dirty(d),
1508 &d->c->flash_dev_dirty_sectors);
1509 bcache_device_free(d);
1510 mutex_unlock(&bch_register_lock);
1511 kobject_put(&d->kobj);
1514 static void flash_dev_flush(struct closure *cl)
1516 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1518 mutex_lock(&bch_register_lock);
1519 bcache_device_unlink(d);
1520 mutex_unlock(&bch_register_lock);
1521 kobject_del(&d->kobj);
1522 continue_at(cl, flash_dev_free, system_wq);
1525 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1527 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1532 closure_init(&d->cl, NULL);
1533 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1535 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1537 if (bcache_device_init(d, block_bytes(c), u->sectors,
1538 NULL, &bcache_flash_ops))
1541 bcache_device_attach(d, c, u - c->uuids);
1542 bch_sectors_dirty_init(d);
1543 bch_flash_dev_request_init(d);
1546 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1549 bcache_device_link(d, c, "volume");
1553 kobject_put(&d->kobj);
1557 static int flash_devs_run(struct cache_set *c)
1560 struct uuid_entry *u;
1563 u < c->uuids + c->nr_uuids && !ret;
1565 if (UUID_FLASH_ONLY(u))
1566 ret = flash_dev_run(c, u);
1571 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1573 struct uuid_entry *u;
1575 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1578 if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1581 u = uuid_find_empty(c);
1583 pr_err("Can't create volume, no room for UUID\n");
1587 get_random_bytes(u->uuid, 16);
1588 memset(u->label, 0, 32);
1589 u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1591 SET_UUID_FLASH_ONLY(u, 1);
1592 u->sectors = size >> 9;
1596 return flash_dev_run(c, u);
1599 bool bch_cached_dev_error(struct cached_dev *dc)
1601 if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1604 dc->io_disable = true;
1605 /* make others know io_disable is true earlier */
1608 pr_err("stop %s: too many IO errors on backing device %s\n",
1609 dc->disk.disk->disk_name, dc->backing_dev_name);
1611 bcache_device_stop(&dc->disk);
1618 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1620 struct va_format vaf;
1623 if (c->on_error != ON_ERROR_PANIC &&
1624 test_bit(CACHE_SET_STOPPING, &c->flags))
1627 if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1628 pr_info("CACHE_SET_IO_DISABLE already set\n");
1631 * XXX: we can be called from atomic context
1632 * acquire_console_sem();
1635 va_start(args, fmt);
1640 pr_err("error on %pU: %pV, disabling caching\n",
1641 c->sb.set_uuid, &vaf);
1645 if (c->on_error == ON_ERROR_PANIC)
1646 panic("panic forced after error\n");
1648 bch_cache_set_unregister(c);
1652 /* When c->kobj released */
1653 void bch_cache_set_release(struct kobject *kobj)
1655 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1658 module_put(THIS_MODULE);
1661 static void cache_set_free(struct closure *cl)
1663 struct cache_set *c = container_of(cl, struct cache_set, cl);
1667 debugfs_remove(c->debug);
1669 bch_open_buckets_free(c);
1670 bch_btree_cache_free(c);
1671 bch_journal_free(c);
1673 mutex_lock(&bch_register_lock);
1674 for_each_cache(ca, c, i)
1678 kobject_put(&ca->kobj);
1681 bch_bset_sort_state_free(&c->sort);
1682 free_pages((unsigned long) c->uuids, ilog2(meta_bucket_pages(&c->sb)));
1684 if (c->moving_gc_wq)
1685 destroy_workqueue(c->moving_gc_wq);
1686 bioset_exit(&c->bio_split);
1687 mempool_exit(&c->fill_iter);
1688 mempool_exit(&c->bio_meta);
1689 mempool_exit(&c->search);
1693 mutex_unlock(&bch_register_lock);
1695 pr_info("Cache set %pU unregistered\n", c->sb.set_uuid);
1696 wake_up(&unregister_wait);
1698 closure_debug_destroy(&c->cl);
1699 kobject_put(&c->kobj);
1702 static void cache_set_flush(struct closure *cl)
1704 struct cache_set *c = container_of(cl, struct cache_set, caching);
1709 bch_cache_accounting_destroy(&c->accounting);
1711 kobject_put(&c->internal);
1712 kobject_del(&c->kobj);
1714 if (!IS_ERR_OR_NULL(c->gc_thread))
1715 kthread_stop(c->gc_thread);
1717 if (!IS_ERR_OR_NULL(c->root))
1718 list_add(&c->root->list, &c->btree_cache);
1721 * Avoid flushing cached nodes if cache set is retiring
1722 * due to too many I/O errors detected.
1724 if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1725 list_for_each_entry(b, &c->btree_cache, list) {
1726 mutex_lock(&b->write_lock);
1727 if (btree_node_dirty(b))
1728 __bch_btree_node_write(b, NULL);
1729 mutex_unlock(&b->write_lock);
1732 for_each_cache(ca, c, i)
1733 if (ca->alloc_thread)
1734 kthread_stop(ca->alloc_thread);
1736 if (c->journal.cur) {
1737 cancel_delayed_work_sync(&c->journal.work);
1738 /* flush last journal entry if needed */
1739 c->journal.work.work.func(&c->journal.work.work);
1746 * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1747 * cache set is unregistering due to too many I/O errors. In this condition,
1748 * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1749 * value and whether the broken cache has dirty data:
1751 * dc->stop_when_cache_set_failed dc->has_dirty stop bcache device
1752 * BCH_CACHED_STOP_AUTO 0 NO
1753 * BCH_CACHED_STOP_AUTO 1 YES
1754 * BCH_CACHED_DEV_STOP_ALWAYS 0 YES
1755 * BCH_CACHED_DEV_STOP_ALWAYS 1 YES
1757 * The expected behavior is, if stop_when_cache_set_failed is configured to
1758 * "auto" via sysfs interface, the bcache device will not be stopped if the
1759 * backing device is clean on the broken cache device.
1761 static void conditional_stop_bcache_device(struct cache_set *c,
1762 struct bcache_device *d,
1763 struct cached_dev *dc)
1765 if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1766 pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.\n",
1767 d->disk->disk_name, c->sb.set_uuid);
1768 bcache_device_stop(d);
1769 } else if (atomic_read(&dc->has_dirty)) {
1771 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1772 * and dc->has_dirty == 1
1774 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.\n",
1775 d->disk->disk_name);
1777 * There might be a small time gap that cache set is
1778 * released but bcache device is not. Inside this time
1779 * gap, regular I/O requests will directly go into
1780 * backing device as no cache set attached to. This
1781 * behavior may also introduce potential inconsistence
1782 * data in writeback mode while cache is dirty.
1783 * Therefore before calling bcache_device_stop() due
1784 * to a broken cache device, dc->io_disable should be
1785 * explicitly set to true.
1787 dc->io_disable = true;
1788 /* make others know io_disable is true earlier */
1790 bcache_device_stop(d);
1793 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1794 * and dc->has_dirty == 0
1796 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.\n",
1797 d->disk->disk_name);
1801 static void __cache_set_unregister(struct closure *cl)
1803 struct cache_set *c = container_of(cl, struct cache_set, caching);
1804 struct cached_dev *dc;
1805 struct bcache_device *d;
1808 mutex_lock(&bch_register_lock);
1810 for (i = 0; i < c->devices_max_used; i++) {
1815 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1816 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1817 dc = container_of(d, struct cached_dev, disk);
1818 bch_cached_dev_detach(dc);
1819 if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1820 conditional_stop_bcache_device(c, d, dc);
1822 bcache_device_stop(d);
1826 mutex_unlock(&bch_register_lock);
1828 continue_at(cl, cache_set_flush, system_wq);
1831 void bch_cache_set_stop(struct cache_set *c)
1833 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1834 /* closure_fn set to __cache_set_unregister() */
1835 closure_queue(&c->caching);
1838 void bch_cache_set_unregister(struct cache_set *c)
1840 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1841 bch_cache_set_stop(c);
1844 #define alloc_bucket_pages(gfp, c) \
1845 ((void *) __get_free_pages(__GFP_ZERO|__GFP_COMP|gfp, ilog2(bucket_pages(c))))
1847 #define alloc_meta_bucket_pages(gfp, sb) \
1848 ((void *) __get_free_pages(__GFP_ZERO|__GFP_COMP|gfp, ilog2(meta_bucket_pages(sb))))
1850 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1853 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1858 __module_get(THIS_MODULE);
1859 closure_init(&c->cl, NULL);
1860 set_closure_fn(&c->cl, cache_set_free, system_wq);
1862 closure_init(&c->caching, &c->cl);
1863 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1865 /* Maybe create continue_at_noreturn() and use it here? */
1866 closure_set_stopped(&c->cl);
1867 closure_put(&c->cl);
1869 kobject_init(&c->kobj, &bch_cache_set_ktype);
1870 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1872 bch_cache_accounting_init(&c->accounting, &c->cl);
1874 memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1875 c->sb.block_size = sb->block_size;
1876 c->sb.bucket_size = sb->bucket_size;
1877 c->sb.nr_in_set = sb->nr_in_set;
1878 c->sb.last_mount = sb->last_mount;
1879 c->sb.version = sb->version;
1880 if (c->sb.version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES) {
1881 c->sb.feature_compat = sb->feature_compat;
1882 c->sb.feature_ro_compat = sb->feature_ro_compat;
1883 c->sb.feature_incompat = sb->feature_incompat;
1886 c->bucket_bits = ilog2(sb->bucket_size);
1887 c->block_bits = ilog2(sb->block_size);
1888 c->nr_uuids = meta_bucket_bytes(&c->sb) / sizeof(struct uuid_entry);
1889 c->devices_max_used = 0;
1890 atomic_set(&c->attached_dev_nr, 0);
1891 c->btree_pages = meta_bucket_pages(&c->sb);
1892 if (c->btree_pages > BTREE_MAX_PAGES)
1893 c->btree_pages = max_t(int, c->btree_pages / 4,
1896 sema_init(&c->sb_write_mutex, 1);
1897 mutex_init(&c->bucket_lock);
1898 init_waitqueue_head(&c->btree_cache_wait);
1899 spin_lock_init(&c->btree_cannibalize_lock);
1900 init_waitqueue_head(&c->bucket_wait);
1901 init_waitqueue_head(&c->gc_wait);
1902 sema_init(&c->uuid_write_mutex, 1);
1904 spin_lock_init(&c->btree_gc_time.lock);
1905 spin_lock_init(&c->btree_split_time.lock);
1906 spin_lock_init(&c->btree_read_time.lock);
1908 bch_moving_init_cache_set(c);
1910 INIT_LIST_HEAD(&c->list);
1911 INIT_LIST_HEAD(&c->cached_devs);
1912 INIT_LIST_HEAD(&c->btree_cache);
1913 INIT_LIST_HEAD(&c->btree_cache_freeable);
1914 INIT_LIST_HEAD(&c->btree_cache_freed);
1915 INIT_LIST_HEAD(&c->data_buckets);
1917 iter_size = ((meta_bucket_pages(sb) * PAGE_SECTORS) / sb->block_size + 1) *
1918 sizeof(struct btree_iter_set);
1920 c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL);
1924 if (mempool_init_slab_pool(&c->search, 32, bch_search_cache))
1927 if (mempool_init_kmalloc_pool(&c->bio_meta, 2,
1928 sizeof(struct bbio) +
1929 sizeof(struct bio_vec) * meta_bucket_pages(&c->sb)))
1932 if (mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size))
1935 if (bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1936 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
1939 c->uuids = alloc_meta_bucket_pages(GFP_KERNEL, &c->sb);
1943 c->moving_gc_wq = alloc_workqueue("bcache_gc", WQ_MEM_RECLAIM, 0);
1944 if (!c->moving_gc_wq)
1947 if (bch_journal_alloc(c))
1950 if (bch_btree_cache_alloc(c))
1953 if (bch_open_buckets_alloc(c))
1956 if (bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1959 c->congested_read_threshold_us = 2000;
1960 c->congested_write_threshold_us = 20000;
1961 c->error_limit = DEFAULT_IO_ERROR_LIMIT;
1962 c->idle_max_writeback_rate_enabled = 1;
1963 WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1967 bch_cache_set_unregister(c);
1971 static int run_cache_set(struct cache_set *c)
1973 const char *err = "cannot allocate memory";
1974 struct cached_dev *dc, *t;
1979 struct journal_replay *l;
1981 closure_init_stack(&cl);
1983 for_each_cache(ca, c, i)
1984 c->nbuckets += ca->sb.nbuckets;
1987 if (CACHE_SYNC(&c->sb)) {
1991 err = "cannot allocate memory for journal";
1992 if (bch_journal_read(c, &journal))
1995 pr_debug("btree_journal_read() done\n");
1997 err = "no journal entries found";
1998 if (list_empty(&journal))
2001 j = &list_entry(journal.prev, struct journal_replay, list)->j;
2003 err = "IO error reading priorities";
2004 for_each_cache(ca, c, i) {
2005 if (prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]))
2010 * If prio_read() fails it'll call cache_set_error and we'll
2011 * tear everything down right away, but if we perhaps checked
2012 * sooner we could avoid journal replay.
2017 err = "bad btree root";
2018 if (__bch_btree_ptr_invalid(c, k))
2021 err = "error reading btree root";
2022 c->root = bch_btree_node_get(c, NULL, k,
2025 if (IS_ERR_OR_NULL(c->root))
2028 list_del_init(&c->root->list);
2029 rw_unlock(true, c->root);
2031 err = uuid_read(c, j, &cl);
2035 err = "error in recovery";
2036 if (bch_btree_check(c))
2039 bch_journal_mark(c, &journal);
2040 bch_initial_gc_finish(c);
2041 pr_debug("btree_check() done\n");
2044 * bcache_journal_next() can't happen sooner, or
2045 * btree_gc_finish() will give spurious errors about last_gc >
2046 * gc_gen - this is a hack but oh well.
2048 bch_journal_next(&c->journal);
2050 err = "error starting allocator thread";
2051 for_each_cache(ca, c, i)
2052 if (bch_cache_allocator_start(ca))
2056 * First place it's safe to allocate: btree_check() and
2057 * btree_gc_finish() have to run before we have buckets to
2058 * allocate, and bch_bucket_alloc_set() might cause a journal
2059 * entry to be written so bcache_journal_next() has to be called
2062 * If the uuids were in the old format we have to rewrite them
2063 * before the next journal entry is written:
2065 if (j->version < BCACHE_JSET_VERSION_UUID)
2068 err = "bcache: replay journal failed";
2069 if (bch_journal_replay(c, &journal))
2072 pr_notice("invalidating existing data\n");
2074 for_each_cache(ca, c, i) {
2077 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
2078 2, SB_JOURNAL_BUCKETS);
2080 for (j = 0; j < ca->sb.keys; j++)
2081 ca->sb.d[j] = ca->sb.first_bucket + j;
2084 bch_initial_gc_finish(c);
2086 err = "error starting allocator thread";
2087 for_each_cache(ca, c, i)
2088 if (bch_cache_allocator_start(ca))
2091 mutex_lock(&c->bucket_lock);
2092 for_each_cache(ca, c, i)
2093 bch_prio_write(ca, true);
2094 mutex_unlock(&c->bucket_lock);
2096 err = "cannot allocate new UUID bucket";
2097 if (__uuid_write(c))
2100 err = "cannot allocate new btree root";
2101 c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
2102 if (IS_ERR_OR_NULL(c->root))
2105 mutex_lock(&c->root->write_lock);
2106 bkey_copy_key(&c->root->key, &MAX_KEY);
2107 bch_btree_node_write(c->root, &cl);
2108 mutex_unlock(&c->root->write_lock);
2110 bch_btree_set_root(c->root);
2111 rw_unlock(true, c->root);
2114 * We don't want to write the first journal entry until
2115 * everything is set up - fortunately journal entries won't be
2116 * written until the SET_CACHE_SYNC() here:
2118 SET_CACHE_SYNC(&c->sb, true);
2120 bch_journal_next(&c->journal);
2121 bch_journal_meta(c, &cl);
2124 err = "error starting gc thread";
2125 if (bch_gc_thread_start(c))
2129 c->sb.last_mount = (u32)ktime_get_real_seconds();
2130 bcache_write_super(c);
2132 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2133 bch_cached_dev_attach(dc, c, NULL);
2137 set_bit(CACHE_SET_RUNNING, &c->flags);
2140 while (!list_empty(&journal)) {
2141 l = list_first_entry(&journal, struct journal_replay, list);
2148 bch_cache_set_error(c, "%s", err);
2153 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
2155 return ca->sb.block_size == c->sb.block_size &&
2156 ca->sb.bucket_size == c->sb.bucket_size &&
2157 ca->sb.nr_in_set == c->sb.nr_in_set;
2160 static const char *register_cache_set(struct cache *ca)
2163 const char *err = "cannot allocate memory";
2164 struct cache_set *c;
2166 list_for_each_entry(c, &bch_cache_sets, list)
2167 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
2169 return "duplicate cache set member";
2171 if (!can_attach_cache(ca, c))
2172 return "cache sb does not match set";
2174 if (!CACHE_SYNC(&ca->sb))
2175 SET_CACHE_SYNC(&c->sb, false);
2180 c = bch_cache_set_alloc(&ca->sb);
2184 err = "error creating kobject";
2185 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
2186 kobject_add(&c->internal, &c->kobj, "internal"))
2189 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2192 bch_debug_init_cache_set(c);
2194 list_add(&c->list, &bch_cache_sets);
2196 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2197 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2198 sysfs_create_link(&c->kobj, &ca->kobj, buf))
2202 * A special case is both ca->sb.seq and c->sb.seq are 0,
2203 * such condition happens on a new created cache device whose
2204 * super block is never flushed yet. In this case c->sb.version
2205 * and other members should be updated too, otherwise we will
2206 * have a mistaken super block version in cache set.
2208 if (ca->sb.seq > c->sb.seq || c->sb.seq == 0) {
2209 c->sb.version = ca->sb.version;
2210 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
2211 c->sb.flags = ca->sb.flags;
2212 c->sb.seq = ca->sb.seq;
2213 pr_debug("set version = %llu\n", c->sb.version);
2216 kobject_get(&ca->kobj);
2218 ca->set->cache = ca;
2220 err = "failed to run cache set";
2221 if (run_cache_set(c) < 0)
2226 bch_cache_set_unregister(c);
2232 /* When ca->kobj released */
2233 void bch_cache_release(struct kobject *kobj)
2235 struct cache *ca = container_of(kobj, struct cache, kobj);
2239 BUG_ON(ca->set->cache != ca);
2240 ca->set->cache = NULL;
2243 free_pages((unsigned long) ca->disk_buckets, ilog2(meta_bucket_pages(&ca->sb)));
2244 kfree(ca->prio_buckets);
2247 free_heap(&ca->heap);
2248 free_fifo(&ca->free_inc);
2250 for (i = 0; i < RESERVE_NR; i++)
2251 free_fifo(&ca->free[i]);
2254 put_page(virt_to_page(ca->sb_disk));
2256 if (!IS_ERR_OR_NULL(ca->bdev))
2257 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2260 module_put(THIS_MODULE);
2263 static int cache_alloc(struct cache *ca)
2266 size_t btree_buckets;
2269 const char *err = NULL;
2271 __module_get(THIS_MODULE);
2272 kobject_init(&ca->kobj, &bch_cache_ktype);
2274 bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2277 * when ca->sb.njournal_buckets is not zero, journal exists,
2278 * and in bch_journal_replay(), tree node may split,
2279 * so bucket of RESERVE_BTREE type is needed,
2280 * the worst situation is all journal buckets are valid journal,
2281 * and all the keys need to replay,
2282 * so the number of RESERVE_BTREE type buckets should be as much
2283 * as journal buckets
2285 btree_buckets = ca->sb.njournal_buckets ?: 8;
2286 free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
2289 err = "ca->sb.nbuckets is too small";
2293 if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
2295 err = "ca->free[RESERVE_BTREE] alloc failed";
2296 goto err_btree_alloc;
2299 if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
2301 err = "ca->free[RESERVE_PRIO] alloc failed";
2302 goto err_prio_alloc;
2305 if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
2306 err = "ca->free[RESERVE_MOVINGGC] alloc failed";
2307 goto err_movinggc_alloc;
2310 if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
2311 err = "ca->free[RESERVE_NONE] alloc failed";
2312 goto err_none_alloc;
2315 if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
2316 err = "ca->free_inc alloc failed";
2317 goto err_free_inc_alloc;
2320 if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
2321 err = "ca->heap alloc failed";
2322 goto err_heap_alloc;
2325 ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2328 err = "ca->buckets alloc failed";
2329 goto err_buckets_alloc;
2332 ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
2333 prio_buckets(ca), 2),
2335 if (!ca->prio_buckets) {
2336 err = "ca->prio_buckets alloc failed";
2337 goto err_prio_buckets_alloc;
2340 ca->disk_buckets = alloc_meta_bucket_pages(GFP_KERNEL, &ca->sb);
2341 if (!ca->disk_buckets) {
2342 err = "ca->disk_buckets alloc failed";
2343 goto err_disk_buckets_alloc;
2346 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2348 for_each_bucket(b, ca)
2349 atomic_set(&b->pin, 0);
2352 err_disk_buckets_alloc:
2353 kfree(ca->prio_buckets);
2354 err_prio_buckets_alloc:
2357 free_heap(&ca->heap);
2359 free_fifo(&ca->free_inc);
2361 free_fifo(&ca->free[RESERVE_NONE]);
2363 free_fifo(&ca->free[RESERVE_MOVINGGC]);
2365 free_fifo(&ca->free[RESERVE_PRIO]);
2367 free_fifo(&ca->free[RESERVE_BTREE]);
2370 module_put(THIS_MODULE);
2372 pr_notice("error %s: %s\n", ca->cache_dev_name, err);
2376 static int register_cache(struct cache_sb *sb, struct cache_sb_disk *sb_disk,
2377 struct block_device *bdev, struct cache *ca)
2379 const char *err = NULL; /* must be set for any error case */
2382 bdevname(bdev, ca->cache_dev_name);
2383 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2385 ca->bdev->bd_holder = ca;
2386 ca->sb_disk = sb_disk;
2388 if (blk_queue_discard(bdev_get_queue(bdev)))
2389 ca->discard = CACHE_DISCARD(&ca->sb);
2391 ret = cache_alloc(ca);
2394 * If we failed here, it means ca->kobj is not initialized yet,
2395 * kobject_put() won't be called and there is no chance to
2396 * call blkdev_put() to bdev in bch_cache_release(). So we
2397 * explicitly call blkdev_put() here.
2399 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2401 err = "cache_alloc(): -ENOMEM";
2402 else if (ret == -EPERM)
2403 err = "cache_alloc(): cache device is too small";
2405 err = "cache_alloc(): unknown error";
2409 if (kobject_add(&ca->kobj,
2410 &part_to_dev(bdev->bd_part)->kobj,
2412 err = "error calling kobject_add";
2417 mutex_lock(&bch_register_lock);
2418 err = register_cache_set(ca);
2419 mutex_unlock(&bch_register_lock);
2426 pr_info("registered cache device %s\n", ca->cache_dev_name);
2429 kobject_put(&ca->kobj);
2433 pr_notice("error %s: %s\n", ca->cache_dev_name, err);
2438 /* Global interfaces/init */
2440 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2441 const char *buffer, size_t size);
2442 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2443 struct kobj_attribute *attr,
2444 const char *buffer, size_t size);
2446 kobj_attribute_write(register, register_bcache);
2447 kobj_attribute_write(register_quiet, register_bcache);
2448 kobj_attribute_write(pendings_cleanup, bch_pending_bdevs_cleanup);
2450 static bool bch_is_open_backing(struct block_device *bdev)
2452 struct cache_set *c, *tc;
2453 struct cached_dev *dc, *t;
2455 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2456 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2457 if (dc->bdev == bdev)
2459 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2460 if (dc->bdev == bdev)
2465 static bool bch_is_open_cache(struct block_device *bdev)
2467 struct cache_set *c, *tc;
2471 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2472 for_each_cache(ca, c, i)
2473 if (ca->bdev == bdev)
2478 static bool bch_is_open(struct block_device *bdev)
2480 return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2483 struct async_reg_args {
2484 struct delayed_work reg_work;
2486 struct cache_sb *sb;
2487 struct cache_sb_disk *sb_disk;
2488 struct block_device *bdev;
2491 static void register_bdev_worker(struct work_struct *work)
2494 struct async_reg_args *args =
2495 container_of(work, struct async_reg_args, reg_work.work);
2496 struct cached_dev *dc;
2498 dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2501 put_page(virt_to_page(args->sb_disk));
2502 blkdev_put(args->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2506 mutex_lock(&bch_register_lock);
2507 if (register_bdev(args->sb, args->sb_disk, args->bdev, dc) < 0)
2509 mutex_unlock(&bch_register_lock);
2513 pr_info("error %s: fail to register backing device\n",
2518 module_put(THIS_MODULE);
2521 static void register_cache_worker(struct work_struct *work)
2524 struct async_reg_args *args =
2525 container_of(work, struct async_reg_args, reg_work.work);
2528 ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2531 put_page(virt_to_page(args->sb_disk));
2532 blkdev_put(args->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2536 /* blkdev_put() will be called in bch_cache_release() */
2537 if (register_cache(args->sb, args->sb_disk, args->bdev, ca) != 0)
2542 pr_info("error %s: fail to register cache device\n",
2547 module_put(THIS_MODULE);
2550 static void register_device_aync(struct async_reg_args *args)
2552 if (SB_IS_BDEV(args->sb))
2553 INIT_DELAYED_WORK(&args->reg_work, register_bdev_worker);
2555 INIT_DELAYED_WORK(&args->reg_work, register_cache_worker);
2557 /* 10 jiffies is enough for a delay */
2558 queue_delayed_work(system_wq, &args->reg_work, 10);
2561 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2562 const char *buffer, size_t size)
2566 struct cache_sb *sb;
2567 struct cache_sb_disk *sb_disk;
2568 struct block_device *bdev;
2570 bool async_registration = false;
2572 #ifdef CONFIG_BCACHE_ASYNC_REGISTRATION
2573 async_registration = true;
2577 err = "failed to reference bcache module";
2578 if (!try_module_get(THIS_MODULE))
2581 /* For latest state of bcache_is_reboot */
2583 err = "bcache is in reboot";
2584 if (bcache_is_reboot)
2585 goto out_module_put;
2588 err = "cannot allocate memory";
2589 path = kstrndup(buffer, size, GFP_KERNEL);
2591 goto out_module_put;
2593 sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2598 err = "failed to open device";
2599 bdev = blkdev_get_by_path(strim(path),
2600 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2603 if (bdev == ERR_PTR(-EBUSY)) {
2604 bdev = lookup_bdev(strim(path));
2605 mutex_lock(&bch_register_lock);
2606 if (!IS_ERR(bdev) && bch_is_open(bdev))
2607 err = "device already registered";
2609 err = "device busy";
2610 mutex_unlock(&bch_register_lock);
2613 if (attr == &ksysfs_register_quiet)
2619 err = "failed to set blocksize";
2620 if (set_blocksize(bdev, 4096))
2621 goto out_blkdev_put;
2623 err = read_super(sb, bdev, &sb_disk);
2625 goto out_blkdev_put;
2627 err = "failed to register device";
2629 if (async_registration) {
2630 /* register in asynchronous way */
2631 struct async_reg_args *args =
2632 kzalloc(sizeof(struct async_reg_args), GFP_KERNEL);
2636 err = "cannot allocate memory";
2637 goto out_put_sb_page;
2642 args->sb_disk = sb_disk;
2644 register_device_aync(args);
2645 /* No wait and returns to user space */
2649 if (SB_IS_BDEV(sb)) {
2650 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2653 goto out_put_sb_page;
2655 mutex_lock(&bch_register_lock);
2656 ret = register_bdev(sb, sb_disk, bdev, dc);
2657 mutex_unlock(&bch_register_lock);
2658 /* blkdev_put() will be called in cached_dev_free() */
2662 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2665 goto out_put_sb_page;
2667 /* blkdev_put() will be called in bch_cache_release() */
2668 if (register_cache(sb, sb_disk, bdev, ca) != 0)
2675 module_put(THIS_MODULE);
2680 put_page(virt_to_page(sb_disk));
2682 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2689 module_put(THIS_MODULE);
2691 pr_info("error %s: %s\n", path?path:"", err);
2697 struct list_head list;
2698 struct cached_dev *dc;
2701 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2702 struct kobj_attribute *attr,
2706 LIST_HEAD(pending_devs);
2708 struct cached_dev *dc, *tdc;
2709 struct pdev *pdev, *tpdev;
2710 struct cache_set *c, *tc;
2712 mutex_lock(&bch_register_lock);
2713 list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
2714 pdev = kmalloc(sizeof(struct pdev), GFP_KERNEL);
2718 list_add(&pdev->list, &pending_devs);
2721 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2722 list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
2723 char *pdev_set_uuid = pdev->dc->sb.set_uuid;
2724 char *set_uuid = c->sb.uuid;
2726 if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
2727 list_del(&pdev->list);
2733 mutex_unlock(&bch_register_lock);
2735 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2736 pr_info("delete pdev %p\n", pdev);
2737 list_del(&pdev->list);
2738 bcache_device_stop(&pdev->dc->disk);
2745 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2747 if (bcache_is_reboot)
2750 if (code == SYS_DOWN ||
2752 code == SYS_POWER_OFF) {
2754 unsigned long start = jiffies;
2755 bool stopped = false;
2757 struct cache_set *c, *tc;
2758 struct cached_dev *dc, *tdc;
2760 mutex_lock(&bch_register_lock);
2762 if (bcache_is_reboot)
2765 /* New registration is rejected since now */
2766 bcache_is_reboot = true;
2768 * Make registering caller (if there is) on other CPU
2769 * core know bcache_is_reboot set to true earlier
2773 if (list_empty(&bch_cache_sets) &&
2774 list_empty(&uncached_devices))
2777 mutex_unlock(&bch_register_lock);
2779 pr_info("Stopping all devices:\n");
2782 * The reason bch_register_lock is not held to call
2783 * bch_cache_set_stop() and bcache_device_stop() is to
2784 * avoid potential deadlock during reboot, because cache
2785 * set or bcache device stopping process will acqurie
2786 * bch_register_lock too.
2788 * We are safe here because bcache_is_reboot sets to
2789 * true already, register_bcache() will reject new
2790 * registration now. bcache_is_reboot also makes sure
2791 * bcache_reboot() won't be re-entered on by other thread,
2792 * so there is no race in following list iteration by
2793 * list_for_each_entry_safe().
2795 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2796 bch_cache_set_stop(c);
2798 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2799 bcache_device_stop(&dc->disk);
2803 * Give an early chance for other kthreads and
2804 * kworkers to stop themselves
2808 /* What's a condition variable? */
2810 long timeout = start + 10 * HZ - jiffies;
2812 mutex_lock(&bch_register_lock);
2813 stopped = list_empty(&bch_cache_sets) &&
2814 list_empty(&uncached_devices);
2816 if (timeout < 0 || stopped)
2819 prepare_to_wait(&unregister_wait, &wait,
2820 TASK_UNINTERRUPTIBLE);
2822 mutex_unlock(&bch_register_lock);
2823 schedule_timeout(timeout);
2826 finish_wait(&unregister_wait, &wait);
2829 pr_info("All devices stopped\n");
2831 pr_notice("Timeout waiting for devices to be closed\n");
2833 mutex_unlock(&bch_register_lock);
2839 static struct notifier_block reboot = {
2840 .notifier_call = bcache_reboot,
2841 .priority = INT_MAX, /* before any real devices */
2844 static void bcache_exit(void)
2849 kobject_put(bcache_kobj);
2851 destroy_workqueue(bcache_wq);
2853 destroy_workqueue(bch_journal_wq);
2856 unregister_blkdev(bcache_major, "bcache");
2857 unregister_reboot_notifier(&reboot);
2858 mutex_destroy(&bch_register_lock);
2861 /* Check and fixup module parameters */
2862 static void check_module_parameters(void)
2864 if (bch_cutoff_writeback_sync == 0)
2865 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
2866 else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
2867 pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u\n",
2868 bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
2869 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
2872 if (bch_cutoff_writeback == 0)
2873 bch_cutoff_writeback = CUTOFF_WRITEBACK;
2874 else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
2875 pr_warn("set bch_cutoff_writeback (%u) to max value %u\n",
2876 bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
2877 bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
2880 if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
2881 pr_warn("set bch_cutoff_writeback (%u) to %u\n",
2882 bch_cutoff_writeback, bch_cutoff_writeback_sync);
2883 bch_cutoff_writeback = bch_cutoff_writeback_sync;
2887 static int __init bcache_init(void)
2889 static const struct attribute *files[] = {
2890 &ksysfs_register.attr,
2891 &ksysfs_register_quiet.attr,
2892 &ksysfs_pendings_cleanup.attr,
2896 check_module_parameters();
2898 mutex_init(&bch_register_lock);
2899 init_waitqueue_head(&unregister_wait);
2900 register_reboot_notifier(&reboot);
2902 bcache_major = register_blkdev(0, "bcache");
2903 if (bcache_major < 0) {
2904 unregister_reboot_notifier(&reboot);
2905 mutex_destroy(&bch_register_lock);
2906 return bcache_major;
2909 bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2913 bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
2914 if (!bch_journal_wq)
2917 bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2921 if (bch_request_init() ||
2922 sysfs_create_files(bcache_kobj, files))
2926 closure_debug_init();
2928 bcache_is_reboot = false;
2939 module_exit(bcache_exit);
2940 module_init(bcache_init);
2942 module_param(bch_cutoff_writeback, uint, 0);
2943 MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
2945 module_param(bch_cutoff_writeback_sync, uint, 0);
2946 MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
2948 MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
2949 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
2950 MODULE_LICENSE("GPL");