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"
17 #include <linux/blkdev.h>
18 #include <linux/buffer_head.h>
19 #include <linux/debugfs.h>
20 #include <linux/genhd.h>
21 #include <linux/idr.h>
22 #include <linux/kthread.h>
23 #include <linux/module.h>
24 #include <linux/random.h>
25 #include <linux/reboot.h>
26 #include <linux/sysfs.h>
28 unsigned int bch_cutoff_writeback;
29 unsigned int bch_cutoff_writeback_sync;
31 static const char bcache_magic[] = {
32 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
33 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
36 static const char invalid_uuid[] = {
37 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
38 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
41 static struct kobject *bcache_kobj;
42 struct mutex bch_register_lock;
43 bool bcache_is_reboot;
44 LIST_HEAD(bch_cache_sets);
45 static LIST_HEAD(uncached_devices);
47 static int bcache_major;
48 static DEFINE_IDA(bcache_device_idx);
49 static wait_queue_head_t unregister_wait;
50 struct workqueue_struct *bcache_wq;
51 struct workqueue_struct *bch_journal_wq;
54 #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
55 /* limitation of partitions number on single bcache device */
56 #define BCACHE_MINORS 128
57 /* limitation of bcache devices number on single system */
58 #define BCACHE_DEVICE_IDX_MAX ((1U << MINORBITS)/BCACHE_MINORS)
62 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
67 struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
73 s = (struct cache_sb *) bh->b_data;
75 sb->offset = le64_to_cpu(s->offset);
76 sb->version = le64_to_cpu(s->version);
78 memcpy(sb->magic, s->magic, 16);
79 memcpy(sb->uuid, s->uuid, 16);
80 memcpy(sb->set_uuid, s->set_uuid, 16);
81 memcpy(sb->label, s->label, SB_LABEL_SIZE);
83 sb->flags = le64_to_cpu(s->flags);
84 sb->seq = le64_to_cpu(s->seq);
85 sb->last_mount = le32_to_cpu(s->last_mount);
86 sb->first_bucket = le16_to_cpu(s->first_bucket);
87 sb->keys = le16_to_cpu(s->keys);
89 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
90 sb->d[i] = le64_to_cpu(s->d[i]);
92 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
93 sb->version, sb->flags, sb->seq, sb->keys);
95 err = "Not a bcache superblock (bad offset)";
96 if (sb->offset != SB_SECTOR)
99 err = "Not a bcache superblock (bad magic)";
100 if (memcmp(sb->magic, bcache_magic, 16))
103 err = "Too many journal buckets";
104 if (sb->keys > SB_JOURNAL_BUCKETS)
107 err = "Bad checksum";
108 if (s->csum != csum_set(s))
112 if (bch_is_zero(sb->uuid, 16))
115 sb->block_size = le16_to_cpu(s->block_size);
117 err = "Superblock block size smaller than device block size";
118 if (sb->block_size << 9 < bdev_logical_block_size(bdev))
121 switch (sb->version) {
122 case BCACHE_SB_VERSION_BDEV:
123 sb->data_offset = BDEV_DATA_START_DEFAULT;
125 case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
126 sb->data_offset = le64_to_cpu(s->data_offset);
128 err = "Bad data offset";
129 if (sb->data_offset < BDEV_DATA_START_DEFAULT)
133 case BCACHE_SB_VERSION_CDEV:
134 case BCACHE_SB_VERSION_CDEV_WITH_UUID:
135 sb->nbuckets = le64_to_cpu(s->nbuckets);
136 sb->bucket_size = le16_to_cpu(s->bucket_size);
138 sb->nr_in_set = le16_to_cpu(s->nr_in_set);
139 sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
141 err = "Too many buckets";
142 if (sb->nbuckets > LONG_MAX)
145 err = "Not enough buckets";
146 if (sb->nbuckets < 1 << 7)
149 err = "Bad block/bucket size";
150 if (!is_power_of_2(sb->block_size) ||
151 sb->block_size > PAGE_SECTORS ||
152 !is_power_of_2(sb->bucket_size) ||
153 sb->bucket_size < PAGE_SECTORS)
156 err = "Invalid superblock: device too small";
157 if (get_capacity(bdev->bd_disk) <
158 sb->bucket_size * sb->nbuckets)
162 if (bch_is_zero(sb->set_uuid, 16))
165 err = "Bad cache device number in set";
166 if (!sb->nr_in_set ||
167 sb->nr_in_set <= sb->nr_this_dev ||
168 sb->nr_in_set > MAX_CACHES_PER_SET)
171 err = "Journal buckets not sequential";
172 for (i = 0; i < sb->keys; i++)
173 if (sb->d[i] != sb->first_bucket + i)
176 err = "Too many journal buckets";
177 if (sb->first_bucket + sb->keys > sb->nbuckets)
180 err = "Invalid superblock: first bucket comes before end of super";
181 if (sb->first_bucket * sb->bucket_size < 16)
186 err = "Unsupported superblock version";
190 sb->last_mount = (u32)ktime_get_real_seconds();
193 get_page(bh->b_page);
200 static void write_bdev_super_endio(struct bio *bio)
202 struct cached_dev *dc = bio->bi_private;
205 bch_count_backing_io_errors(dc, bio);
207 closure_put(&dc->sb_write);
210 static void __write_super(struct cache_sb *sb, struct bio *bio)
212 struct cache_sb *out = page_address(bio_first_page_all(bio));
215 bio->bi_iter.bi_sector = SB_SECTOR;
216 bio->bi_iter.bi_size = SB_SIZE;
217 bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC|REQ_META);
218 bch_bio_map(bio, NULL);
220 out->offset = cpu_to_le64(sb->offset);
221 out->version = cpu_to_le64(sb->version);
223 memcpy(out->uuid, sb->uuid, 16);
224 memcpy(out->set_uuid, sb->set_uuid, 16);
225 memcpy(out->label, sb->label, SB_LABEL_SIZE);
227 out->flags = cpu_to_le64(sb->flags);
228 out->seq = cpu_to_le64(sb->seq);
230 out->last_mount = cpu_to_le32(sb->last_mount);
231 out->first_bucket = cpu_to_le16(sb->first_bucket);
232 out->keys = cpu_to_le16(sb->keys);
234 for (i = 0; i < sb->keys; i++)
235 out->d[i] = cpu_to_le64(sb->d[i]);
237 out->csum = csum_set(out);
239 pr_debug("ver %llu, flags %llu, seq %llu",
240 sb->version, sb->flags, sb->seq);
245 static void bch_write_bdev_super_unlock(struct closure *cl)
247 struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
249 up(&dc->sb_write_mutex);
252 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
254 struct closure *cl = &dc->sb_write;
255 struct bio *bio = &dc->sb_bio;
257 down(&dc->sb_write_mutex);
258 closure_init(cl, parent);
261 bio_set_dev(bio, dc->bdev);
262 bio->bi_end_io = write_bdev_super_endio;
263 bio->bi_private = dc;
266 /* I/O request sent to backing device */
267 __write_super(&dc->sb, bio);
269 closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
272 static void write_super_endio(struct bio *bio)
274 struct cache *ca = bio->bi_private;
277 bch_count_io_errors(ca, bio->bi_status, 0,
278 "writing superblock");
279 closure_put(&ca->set->sb_write);
282 static void bcache_write_super_unlock(struct closure *cl)
284 struct cache_set *c = container_of(cl, struct cache_set, sb_write);
286 up(&c->sb_write_mutex);
289 void bcache_write_super(struct cache_set *c)
291 struct closure *cl = &c->sb_write;
295 down(&c->sb_write_mutex);
296 closure_init(cl, &c->cl);
300 for_each_cache(ca, c, i) {
301 struct bio *bio = &ca->sb_bio;
303 ca->sb.version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
304 ca->sb.seq = c->sb.seq;
305 ca->sb.last_mount = c->sb.last_mount;
307 SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
310 bio_set_dev(bio, ca->bdev);
311 bio->bi_end_io = write_super_endio;
312 bio->bi_private = ca;
315 __write_super(&ca->sb, bio);
318 closure_return_with_destructor(cl, bcache_write_super_unlock);
323 static void uuid_endio(struct bio *bio)
325 struct closure *cl = bio->bi_private;
326 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
328 cache_set_err_on(bio->bi_status, c, "accessing uuids");
329 bch_bbio_free(bio, c);
333 static void uuid_io_unlock(struct closure *cl)
335 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
337 up(&c->uuid_write_mutex);
340 static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
341 struct bkey *k, struct closure *parent)
343 struct closure *cl = &c->uuid_write;
344 struct uuid_entry *u;
349 down(&c->uuid_write_mutex);
350 closure_init(cl, parent);
352 for (i = 0; i < KEY_PTRS(k); i++) {
353 struct bio *bio = bch_bbio_alloc(c);
355 bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
356 bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
358 bio->bi_end_io = uuid_endio;
359 bio->bi_private = cl;
360 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
361 bch_bio_map(bio, c->uuids);
363 bch_submit_bbio(bio, c, k, i);
365 if (op != REQ_OP_WRITE)
369 bch_extent_to_text(buf, sizeof(buf), k);
370 pr_debug("%s UUIDs at %s", op == REQ_OP_WRITE ? "wrote" : "read", buf);
372 for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
373 if (!bch_is_zero(u->uuid, 16))
374 pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
375 u - c->uuids, u->uuid, u->label,
376 u->first_reg, u->last_reg, u->invalidated);
378 closure_return_with_destructor(cl, uuid_io_unlock);
381 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
383 struct bkey *k = &j->uuid_bucket;
385 if (__bch_btree_ptr_invalid(c, k))
386 return "bad uuid pointer";
388 bkey_copy(&c->uuid_bucket, k);
389 uuid_io(c, REQ_OP_READ, 0, k, cl);
391 if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
392 struct uuid_entry_v0 *u0 = (void *) c->uuids;
393 struct uuid_entry *u1 = (void *) c->uuids;
399 * Since the new uuid entry is bigger than the old, we have to
400 * convert starting at the highest memory address and work down
401 * in order to do it in place
404 for (i = c->nr_uuids - 1;
407 memcpy(u1[i].uuid, u0[i].uuid, 16);
408 memcpy(u1[i].label, u0[i].label, 32);
410 u1[i].first_reg = u0[i].first_reg;
411 u1[i].last_reg = u0[i].last_reg;
412 u1[i].invalidated = u0[i].invalidated;
422 static int __uuid_write(struct cache_set *c)
428 closure_init_stack(&cl);
429 lockdep_assert_held(&bch_register_lock);
431 if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
434 SET_KEY_SIZE(&k.key, c->sb.bucket_size);
435 uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
438 /* Only one bucket used for uuid write */
439 ca = PTR_CACHE(c, &k.key, 0);
440 atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
442 bkey_copy(&c->uuid_bucket, &k.key);
447 int bch_uuid_write(struct cache_set *c)
449 int ret = __uuid_write(c);
452 bch_journal_meta(c, NULL);
457 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
459 struct uuid_entry *u;
462 u < c->uuids + c->nr_uuids; u++)
463 if (!memcmp(u->uuid, uuid, 16))
469 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
471 static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
473 return uuid_find(c, zero_uuid);
477 * Bucket priorities/gens:
479 * For each bucket, we store on disk its
483 * See alloc.c for an explanation of the gen. The priority is used to implement
484 * lru (and in the future other) cache replacement policies; for most purposes
485 * it's just an opaque integer.
487 * The gens and the priorities don't have a whole lot to do with each other, and
488 * it's actually the gens that must be written out at specific times - it's no
489 * big deal if the priorities don't get written, if we lose them we just reuse
490 * buckets in suboptimal order.
492 * On disk they're stored in a packed array, and in as many buckets are required
493 * to fit them all. The buckets we use to store them form a list; the journal
494 * header points to the first bucket, the first bucket points to the second
497 * This code is used by the allocation code; periodically (whenever it runs out
498 * of buckets to allocate from) the allocation code will invalidate some
499 * buckets, but it can't use those buckets until their new gens are safely on
503 static void prio_endio(struct bio *bio)
505 struct cache *ca = bio->bi_private;
507 cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
508 bch_bbio_free(bio, ca->set);
509 closure_put(&ca->prio);
512 static void prio_io(struct cache *ca, uint64_t bucket, int op,
513 unsigned long op_flags)
515 struct closure *cl = &ca->prio;
516 struct bio *bio = bch_bbio_alloc(ca->set);
518 closure_init_stack(cl);
520 bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
521 bio_set_dev(bio, ca->bdev);
522 bio->bi_iter.bi_size = bucket_bytes(ca);
524 bio->bi_end_io = prio_endio;
525 bio->bi_private = ca;
526 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
527 bch_bio_map(bio, ca->disk_buckets);
529 closure_bio_submit(ca->set, bio, &ca->prio);
533 int bch_prio_write(struct cache *ca, bool wait)
539 pr_debug("free_prio=%zu, free_none=%zu, free_inc=%zu",
540 fifo_used(&ca->free[RESERVE_PRIO]),
541 fifo_used(&ca->free[RESERVE_NONE]),
542 fifo_used(&ca->free_inc));
545 * Pre-check if there are enough free buckets. In the non-blocking
546 * scenario it's better to fail early rather than starting to allocate
547 * buckets and do a cleanup later in case of failure.
550 size_t avail = fifo_used(&ca->free[RESERVE_PRIO]) +
551 fifo_used(&ca->free[RESERVE_NONE]);
552 if (prio_buckets(ca) > avail)
556 closure_init_stack(&cl);
558 lockdep_assert_held(&ca->set->bucket_lock);
560 ca->disk_buckets->seq++;
562 atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
563 &ca->meta_sectors_written);
565 for (i = prio_buckets(ca) - 1; i >= 0; --i) {
567 struct prio_set *p = ca->disk_buckets;
568 struct bucket_disk *d = p->data;
569 struct bucket_disk *end = d + prios_per_bucket(ca);
571 for (b = ca->buckets + i * prios_per_bucket(ca);
572 b < ca->buckets + ca->sb.nbuckets && d < end;
574 d->prio = cpu_to_le16(b->prio);
578 p->next_bucket = ca->prio_buckets[i + 1];
579 p->magic = pset_magic(&ca->sb);
580 p->csum = bch_crc64(&p->magic, bucket_bytes(ca) - 8);
582 bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
583 BUG_ON(bucket == -1);
585 mutex_unlock(&ca->set->bucket_lock);
586 prio_io(ca, bucket, REQ_OP_WRITE, 0);
587 mutex_lock(&ca->set->bucket_lock);
589 ca->prio_buckets[i] = bucket;
590 atomic_dec_bug(&ca->buckets[bucket].pin);
593 mutex_unlock(&ca->set->bucket_lock);
595 bch_journal_meta(ca->set, &cl);
598 mutex_lock(&ca->set->bucket_lock);
601 * Don't want the old priorities to get garbage collected until after we
602 * finish writing the new ones, and they're journalled
604 for (i = 0; i < prio_buckets(ca); i++) {
605 if (ca->prio_last_buckets[i])
606 __bch_bucket_free(ca,
607 &ca->buckets[ca->prio_last_buckets[i]]);
609 ca->prio_last_buckets[i] = ca->prio_buckets[i];
614 static void prio_read(struct cache *ca, uint64_t bucket)
616 struct prio_set *p = ca->disk_buckets;
617 struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
619 unsigned int bucket_nr = 0;
621 for (b = ca->buckets;
622 b < ca->buckets + ca->sb.nbuckets;
625 ca->prio_buckets[bucket_nr] = bucket;
626 ca->prio_last_buckets[bucket_nr] = bucket;
629 prio_io(ca, bucket, REQ_OP_READ, 0);
632 bch_crc64(&p->magic, bucket_bytes(ca) - 8))
633 pr_warn("bad csum reading priorities");
635 if (p->magic != pset_magic(&ca->sb))
636 pr_warn("bad magic reading priorities");
638 bucket = p->next_bucket;
642 b->prio = le16_to_cpu(d->prio);
643 b->gen = b->last_gc = d->gen;
649 static int open_dev(struct block_device *b, fmode_t mode)
651 struct bcache_device *d = b->bd_disk->private_data;
653 if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
660 static void release_dev(struct gendisk *b, fmode_t mode)
662 struct bcache_device *d = b->private_data;
667 static int ioctl_dev(struct block_device *b, fmode_t mode,
668 unsigned int cmd, unsigned long arg)
670 struct bcache_device *d = b->bd_disk->private_data;
672 return d->ioctl(d, mode, cmd, arg);
675 static const struct block_device_operations bcache_ops = {
677 .release = release_dev,
679 .owner = THIS_MODULE,
682 void bcache_device_stop(struct bcache_device *d)
684 if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
687 * - cached device: cached_dev_flush()
688 * - flash dev: flash_dev_flush()
690 closure_queue(&d->cl);
693 static void bcache_device_unlink(struct bcache_device *d)
695 lockdep_assert_held(&bch_register_lock);
697 if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
701 sysfs_remove_link(&d->c->kobj, d->name);
702 sysfs_remove_link(&d->kobj, "cache");
704 for_each_cache(ca, d->c, i)
705 bd_unlink_disk_holder(ca->bdev, d->disk);
709 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
716 for_each_cache(ca, d->c, i)
717 bd_link_disk_holder(ca->bdev, d->disk);
719 snprintf(d->name, BCACHEDEVNAME_SIZE,
720 "%s%u", name, d->id);
722 ret = sysfs_create_link(&d->kobj, &c->kobj, "cache");
724 pr_err("Couldn't create device -> cache set symlink");
726 ret = sysfs_create_link(&c->kobj, &d->kobj, d->name);
728 pr_err("Couldn't create cache set -> device symlink");
730 clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
733 static void bcache_device_detach(struct bcache_device *d)
735 lockdep_assert_held(&bch_register_lock);
737 atomic_dec(&d->c->attached_dev_nr);
739 if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
740 struct uuid_entry *u = d->c->uuids + d->id;
742 SET_UUID_FLASH_ONLY(u, 0);
743 memcpy(u->uuid, invalid_uuid, 16);
744 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
745 bch_uuid_write(d->c);
748 bcache_device_unlink(d);
750 d->c->devices[d->id] = NULL;
751 closure_put(&d->c->caching);
755 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
762 if (id >= c->devices_max_used)
763 c->devices_max_used = id + 1;
765 closure_get(&c->caching);
768 static inline int first_minor_to_idx(int first_minor)
770 return (first_minor/BCACHE_MINORS);
773 static inline int idx_to_first_minor(int idx)
775 return (idx * BCACHE_MINORS);
778 static void bcache_device_free(struct bcache_device *d)
780 struct gendisk *disk = d->disk;
782 lockdep_assert_held(&bch_register_lock);
785 pr_info("%s stopped", disk->disk_name);
787 pr_err("bcache device (NULL gendisk) stopped");
790 bcache_device_detach(d);
793 if (disk->flags & GENHD_FL_UP)
797 blk_cleanup_queue(disk->queue);
799 ida_simple_remove(&bcache_device_idx,
800 first_minor_to_idx(disk->first_minor));
804 bioset_exit(&d->bio_split);
805 kvfree(d->full_dirty_stripes);
806 kvfree(d->stripe_sectors_dirty);
808 closure_debug_destroy(&d->cl);
811 static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
814 struct request_queue *q;
815 const size_t max_stripes = min_t(size_t, INT_MAX,
816 SIZE_MAX / sizeof(atomic_t));
821 d->stripe_size = 1 << 31;
823 d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
825 if (!d->nr_stripes || d->nr_stripes > max_stripes) {
826 pr_err("nr_stripes too large or invalid: %u (start sector beyond end of disk?)",
827 (unsigned int)d->nr_stripes);
831 n = d->nr_stripes * sizeof(atomic_t);
832 d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
833 if (!d->stripe_sectors_dirty)
836 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
837 d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
838 if (!d->full_dirty_stripes)
841 idx = ida_simple_get(&bcache_device_idx, 0,
842 BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
846 if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
847 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
850 d->disk = alloc_disk(BCACHE_MINORS);
854 set_capacity(d->disk, sectors);
855 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
857 d->disk->major = bcache_major;
858 d->disk->first_minor = idx_to_first_minor(idx);
859 d->disk->fops = &bcache_ops;
860 d->disk->private_data = d;
862 q = blk_alloc_queue(GFP_KERNEL);
866 blk_queue_make_request(q, NULL);
869 q->backing_dev_info->congested_data = d;
870 q->limits.max_hw_sectors = UINT_MAX;
871 q->limits.max_sectors = UINT_MAX;
872 q->limits.max_segment_size = UINT_MAX;
873 q->limits.max_segments = BIO_MAX_PAGES;
874 blk_queue_max_discard_sectors(q, UINT_MAX);
875 q->limits.discard_granularity = 512;
876 q->limits.io_min = block_size;
877 q->limits.logical_block_size = block_size;
878 q->limits.physical_block_size = block_size;
879 blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
880 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
881 blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
883 blk_queue_write_cache(q, true, true);
888 ida_simple_remove(&bcache_device_idx, idx);
895 static void calc_cached_dev_sectors(struct cache_set *c)
897 uint64_t sectors = 0;
898 struct cached_dev *dc;
900 list_for_each_entry(dc, &c->cached_devs, list)
901 sectors += bdev_sectors(dc->bdev);
903 c->cached_dev_sectors = sectors;
906 #define BACKING_DEV_OFFLINE_TIMEOUT 5
907 static int cached_dev_status_update(void *arg)
909 struct cached_dev *dc = arg;
910 struct request_queue *q;
913 * If this delayed worker is stopping outside, directly quit here.
914 * dc->io_disable might be set via sysfs interface, so check it
917 while (!kthread_should_stop() && !dc->io_disable) {
918 q = bdev_get_queue(dc->bdev);
919 if (blk_queue_dying(q))
920 dc->offline_seconds++;
922 dc->offline_seconds = 0;
924 if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
925 pr_err("%s: device offline for %d seconds",
926 dc->backing_dev_name,
927 BACKING_DEV_OFFLINE_TIMEOUT);
928 pr_err("%s: disable I/O request due to backing "
929 "device offline", dc->disk.name);
930 dc->io_disable = true;
931 /* let others know earlier that io_disable is true */
933 bcache_device_stop(&dc->disk);
936 schedule_timeout_interruptible(HZ);
939 wait_for_kthread_stop();
944 int bch_cached_dev_run(struct cached_dev *dc)
946 struct bcache_device *d = &dc->disk;
947 char *buf = kmemdup_nul(dc->sb.label, SB_LABEL_SIZE, GFP_KERNEL);
950 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
951 kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf ? : ""),
955 if (dc->io_disable) {
956 pr_err("I/O disabled on cached dev %s",
957 dc->backing_dev_name);
964 if (atomic_xchg(&dc->running, 1)) {
968 pr_info("cached dev %s is running already",
969 dc->backing_dev_name);
974 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
977 closure_init_stack(&cl);
979 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
980 bch_write_bdev_super(dc, &cl);
985 bd_link_disk_holder(dc->bdev, dc->disk.disk);
987 * won't show up in the uevent file, use udevadm monitor -e instead
988 * only class / kset properties are persistent
990 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
995 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
996 sysfs_create_link(&disk_to_dev(d->disk)->kobj,
997 &d->kobj, "bcache")) {
998 pr_err("Couldn't create bcache dev <-> disk sysfs symlinks");
1002 dc->status_update_thread = kthread_run(cached_dev_status_update,
1003 dc, "bcache_status_update");
1004 if (IS_ERR(dc->status_update_thread)) {
1005 pr_warn("failed to create bcache_status_update kthread, "
1006 "continue to run without monitoring backing "
1014 * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
1015 * work dc->writeback_rate_update is running. Wait until the routine
1016 * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
1017 * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
1018 * seconds, give up waiting here and continue to cancel it too.
1020 static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
1022 int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
1025 if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
1029 schedule_timeout_interruptible(1);
1030 } while (time_out > 0);
1033 pr_warn("give up waiting for dc->writeback_write_update to quit");
1035 cancel_delayed_work_sync(&dc->writeback_rate_update);
1038 static void cached_dev_detach_finish(struct work_struct *w)
1040 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
1043 closure_init_stack(&cl);
1045 BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
1046 BUG_ON(refcount_read(&dc->count));
1049 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1050 cancel_writeback_rate_update_dwork(dc);
1052 if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
1053 kthread_stop(dc->writeback_thread);
1054 dc->writeback_thread = NULL;
1057 memset(&dc->sb.set_uuid, 0, 16);
1058 SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
1060 bch_write_bdev_super(dc, &cl);
1063 mutex_lock(&bch_register_lock);
1065 calc_cached_dev_sectors(dc->disk.c);
1066 bcache_device_detach(&dc->disk);
1067 list_move(&dc->list, &uncached_devices);
1069 clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
1070 clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
1072 mutex_unlock(&bch_register_lock);
1074 pr_info("Caching disabled for %s", dc->backing_dev_name);
1076 /* Drop ref we took in cached_dev_detach() */
1077 closure_put(&dc->disk.cl);
1080 void bch_cached_dev_detach(struct cached_dev *dc)
1082 lockdep_assert_held(&bch_register_lock);
1084 if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1087 if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
1091 * Block the device from being closed and freed until we're finished
1094 closure_get(&dc->disk.cl);
1096 bch_writeback_queue(dc);
1101 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
1104 uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
1105 struct uuid_entry *u;
1106 struct cached_dev *exist_dc, *t;
1109 if ((set_uuid && memcmp(set_uuid, c->sb.set_uuid, 16)) ||
1110 (!set_uuid && memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16)))
1114 pr_err("Can't attach %s: already attached",
1115 dc->backing_dev_name);
1119 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
1120 pr_err("Can't attach %s: shutting down",
1121 dc->backing_dev_name);
1125 if (dc->sb.block_size < c->sb.block_size) {
1127 pr_err("Couldn't attach %s: block size less than set's block size",
1128 dc->backing_dev_name);
1132 /* Check whether already attached */
1133 list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
1134 if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
1135 pr_err("Tried to attach %s but duplicate UUID already attached",
1136 dc->backing_dev_name);
1142 u = uuid_find(c, dc->sb.uuid);
1145 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1146 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1147 memcpy(u->uuid, invalid_uuid, 16);
1148 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1153 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1154 pr_err("Couldn't find uuid for %s in set",
1155 dc->backing_dev_name);
1159 u = uuid_find_empty(c);
1161 pr_err("Not caching %s, no room for UUID",
1162 dc->backing_dev_name);
1168 * Deadlocks since we're called via sysfs...
1169 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1172 if (bch_is_zero(u->uuid, 16)) {
1175 closure_init_stack(&cl);
1177 memcpy(u->uuid, dc->sb.uuid, 16);
1178 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1179 u->first_reg = u->last_reg = rtime;
1182 memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1183 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1185 bch_write_bdev_super(dc, &cl);
1188 u->last_reg = rtime;
1192 bcache_device_attach(&dc->disk, c, u - c->uuids);
1193 list_move(&dc->list, &c->cached_devs);
1194 calc_cached_dev_sectors(c);
1197 * dc->c must be set before dc->count != 0 - paired with the mb in
1201 refcount_set(&dc->count, 1);
1203 /* Block writeback thread, but spawn it */
1204 down_write(&dc->writeback_lock);
1205 if (bch_cached_dev_writeback_start(dc)) {
1206 up_write(&dc->writeback_lock);
1207 pr_err("Couldn't start writeback facilities for %s",
1208 dc->disk.disk->disk_name);
1212 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1213 atomic_set(&dc->has_dirty, 1);
1214 bch_writeback_queue(dc);
1217 bch_sectors_dirty_init(&dc->disk);
1219 ret = bch_cached_dev_run(dc);
1220 if (ret && (ret != -EBUSY)) {
1221 up_write(&dc->writeback_lock);
1223 * bch_register_lock is held, bcache_device_stop() is not
1224 * able to be directly called. The kthread and kworker
1225 * created previously in bch_cached_dev_writeback_start()
1226 * have to be stopped manually here.
1228 kthread_stop(dc->writeback_thread);
1229 cancel_writeback_rate_update_dwork(dc);
1230 pr_err("Couldn't run cached device %s",
1231 dc->backing_dev_name);
1235 bcache_device_link(&dc->disk, c, "bdev");
1236 atomic_inc(&c->attached_dev_nr);
1238 /* Allow the writeback thread to proceed */
1239 up_write(&dc->writeback_lock);
1241 pr_info("Caching %s as %s on set %pU",
1242 dc->backing_dev_name,
1243 dc->disk.disk->disk_name,
1244 dc->disk.c->sb.set_uuid);
1248 /* when dc->disk.kobj released */
1249 void bch_cached_dev_release(struct kobject *kobj)
1251 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1254 module_put(THIS_MODULE);
1257 static void cached_dev_free(struct closure *cl)
1259 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1261 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1262 cancel_writeback_rate_update_dwork(dc);
1264 if (!IS_ERR_OR_NULL(dc->writeback_thread))
1265 kthread_stop(dc->writeback_thread);
1266 if (!IS_ERR_OR_NULL(dc->status_update_thread))
1267 kthread_stop(dc->status_update_thread);
1269 mutex_lock(&bch_register_lock);
1271 if (atomic_read(&dc->running))
1272 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1273 bcache_device_free(&dc->disk);
1274 list_del(&dc->list);
1276 mutex_unlock(&bch_register_lock);
1278 if (!IS_ERR_OR_NULL(dc->bdev))
1279 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1281 wake_up(&unregister_wait);
1283 kobject_put(&dc->disk.kobj);
1286 static void cached_dev_flush(struct closure *cl)
1288 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1289 struct bcache_device *d = &dc->disk;
1291 mutex_lock(&bch_register_lock);
1292 bcache_device_unlink(d);
1293 mutex_unlock(&bch_register_lock);
1295 bch_cache_accounting_destroy(&dc->accounting);
1296 kobject_del(&d->kobj);
1298 continue_at(cl, cached_dev_free, system_wq);
1301 static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1305 struct request_queue *q = bdev_get_queue(dc->bdev);
1307 __module_get(THIS_MODULE);
1308 INIT_LIST_HEAD(&dc->list);
1309 closure_init(&dc->disk.cl, NULL);
1310 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1311 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1312 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1313 sema_init(&dc->sb_write_mutex, 1);
1314 INIT_LIST_HEAD(&dc->io_lru);
1315 spin_lock_init(&dc->io_lock);
1316 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1318 dc->sequential_cutoff = 4 << 20;
1320 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1321 list_add(&io->lru, &dc->io_lru);
1322 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1325 dc->disk.stripe_size = q->limits.io_opt >> 9;
1327 if (dc->disk.stripe_size)
1328 dc->partial_stripes_expensive =
1329 q->limits.raid_partial_stripes_expensive;
1331 ret = bcache_device_init(&dc->disk, block_size,
1332 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1336 dc->disk.disk->queue->backing_dev_info->ra_pages =
1337 max(dc->disk.disk->queue->backing_dev_info->ra_pages,
1338 q->backing_dev_info->ra_pages);
1340 atomic_set(&dc->io_errors, 0);
1341 dc->io_disable = false;
1342 dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
1343 /* default to auto */
1344 dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
1346 bch_cached_dev_request_init(dc);
1347 bch_cached_dev_writeback_init(dc);
1351 /* Cached device - bcache superblock */
1353 static int register_bdev(struct cache_sb *sb, struct page *sb_page,
1354 struct block_device *bdev,
1355 struct cached_dev *dc)
1357 const char *err = "cannot allocate memory";
1358 struct cache_set *c;
1361 bdevname(bdev, dc->backing_dev_name);
1362 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1364 dc->bdev->bd_holder = dc;
1366 bio_init(&dc->sb_bio, dc->sb_bio.bi_inline_vecs, 1);
1367 bio_first_bvec_all(&dc->sb_bio)->bv_page = sb_page;
1371 if (cached_dev_init(dc, sb->block_size << 9))
1374 err = "error creating kobject";
1375 if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1378 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1381 pr_info("registered backing device %s", dc->backing_dev_name);
1383 list_add(&dc->list, &uncached_devices);
1384 /* attach to a matched cache set if it exists */
1385 list_for_each_entry(c, &bch_cache_sets, list)
1386 bch_cached_dev_attach(dc, c, NULL);
1388 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1389 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
1390 err = "failed to run cached device";
1391 ret = bch_cached_dev_run(dc);
1398 pr_notice("error %s: %s", dc->backing_dev_name, err);
1399 bcache_device_stop(&dc->disk);
1403 /* Flash only volumes */
1405 /* When d->kobj released */
1406 void bch_flash_dev_release(struct kobject *kobj)
1408 struct bcache_device *d = container_of(kobj, struct bcache_device,
1413 static void flash_dev_free(struct closure *cl)
1415 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1417 mutex_lock(&bch_register_lock);
1418 atomic_long_sub(bcache_dev_sectors_dirty(d),
1419 &d->c->flash_dev_dirty_sectors);
1420 bcache_device_free(d);
1421 mutex_unlock(&bch_register_lock);
1422 kobject_put(&d->kobj);
1425 static void flash_dev_flush(struct closure *cl)
1427 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1429 mutex_lock(&bch_register_lock);
1430 bcache_device_unlink(d);
1431 mutex_unlock(&bch_register_lock);
1432 kobject_del(&d->kobj);
1433 continue_at(cl, flash_dev_free, system_wq);
1436 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1438 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1443 closure_init(&d->cl, NULL);
1444 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1446 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1448 if (bcache_device_init(d, block_bytes(c), u->sectors))
1451 bcache_device_attach(d, c, u - c->uuids);
1452 bch_sectors_dirty_init(d);
1453 bch_flash_dev_request_init(d);
1456 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1459 bcache_device_link(d, c, "volume");
1463 kobject_put(&d->kobj);
1467 static int flash_devs_run(struct cache_set *c)
1470 struct uuid_entry *u;
1473 u < c->uuids + c->nr_uuids && !ret;
1475 if (UUID_FLASH_ONLY(u))
1476 ret = flash_dev_run(c, u);
1481 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1483 struct uuid_entry *u;
1485 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1488 if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1491 u = uuid_find_empty(c);
1493 pr_err("Can't create volume, no room for UUID");
1497 get_random_bytes(u->uuid, 16);
1498 memset(u->label, 0, 32);
1499 u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1501 SET_UUID_FLASH_ONLY(u, 1);
1502 u->sectors = size >> 9;
1506 return flash_dev_run(c, u);
1509 bool bch_cached_dev_error(struct cached_dev *dc)
1511 if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1514 dc->io_disable = true;
1515 /* make others know io_disable is true earlier */
1518 pr_err("stop %s: too many IO errors on backing device %s\n",
1519 dc->disk.disk->disk_name, dc->backing_dev_name);
1521 bcache_device_stop(&dc->disk);
1528 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1532 if (c->on_error != ON_ERROR_PANIC &&
1533 test_bit(CACHE_SET_STOPPING, &c->flags))
1536 if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1537 pr_info("CACHE_SET_IO_DISABLE already set");
1540 * XXX: we can be called from atomic context
1541 * acquire_console_sem();
1544 pr_err("bcache: error on %pU: ", c->sb.set_uuid);
1546 va_start(args, fmt);
1550 pr_err(", disabling caching\n");
1552 if (c->on_error == ON_ERROR_PANIC)
1553 panic("panic forced after error\n");
1555 bch_cache_set_unregister(c);
1559 /* When c->kobj released */
1560 void bch_cache_set_release(struct kobject *kobj)
1562 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1565 module_put(THIS_MODULE);
1568 static void cache_set_free(struct closure *cl)
1570 struct cache_set *c = container_of(cl, struct cache_set, cl);
1574 debugfs_remove(c->debug);
1576 bch_open_buckets_free(c);
1577 bch_btree_cache_free(c);
1578 bch_journal_free(c);
1580 mutex_lock(&bch_register_lock);
1581 for_each_cache(ca, c, i)
1584 c->cache[ca->sb.nr_this_dev] = NULL;
1585 kobject_put(&ca->kobj);
1588 bch_bset_sort_state_free(&c->sort);
1589 free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1591 if (c->moving_gc_wq)
1592 destroy_workqueue(c->moving_gc_wq);
1593 bioset_exit(&c->bio_split);
1594 mempool_exit(&c->fill_iter);
1595 mempool_exit(&c->bio_meta);
1596 mempool_exit(&c->search);
1600 mutex_unlock(&bch_register_lock);
1602 pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1603 wake_up(&unregister_wait);
1605 closure_debug_destroy(&c->cl);
1606 kobject_put(&c->kobj);
1609 static void cache_set_flush(struct closure *cl)
1611 struct cache_set *c = container_of(cl, struct cache_set, caching);
1616 bch_cache_accounting_destroy(&c->accounting);
1618 kobject_put(&c->internal);
1619 kobject_del(&c->kobj);
1621 if (!IS_ERR_OR_NULL(c->gc_thread))
1622 kthread_stop(c->gc_thread);
1624 if (!IS_ERR_OR_NULL(c->root))
1625 list_add(&c->root->list, &c->btree_cache);
1628 * Avoid flushing cached nodes if cache set is retiring
1629 * due to too many I/O errors detected.
1631 if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1632 list_for_each_entry(b, &c->btree_cache, list) {
1633 mutex_lock(&b->write_lock);
1634 if (btree_node_dirty(b))
1635 __bch_btree_node_write(b, NULL);
1636 mutex_unlock(&b->write_lock);
1639 for_each_cache(ca, c, i)
1640 if (ca->alloc_thread)
1641 kthread_stop(ca->alloc_thread);
1643 if (c->journal.cur) {
1644 cancel_delayed_work_sync(&c->journal.work);
1645 /* flush last journal entry if needed */
1646 c->journal.work.work.func(&c->journal.work.work);
1653 * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1654 * cache set is unregistering due to too many I/O errors. In this condition,
1655 * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1656 * value and whether the broken cache has dirty data:
1658 * dc->stop_when_cache_set_failed dc->has_dirty stop bcache device
1659 * BCH_CACHED_STOP_AUTO 0 NO
1660 * BCH_CACHED_STOP_AUTO 1 YES
1661 * BCH_CACHED_DEV_STOP_ALWAYS 0 YES
1662 * BCH_CACHED_DEV_STOP_ALWAYS 1 YES
1664 * The expected behavior is, if stop_when_cache_set_failed is configured to
1665 * "auto" via sysfs interface, the bcache device will not be stopped if the
1666 * backing device is clean on the broken cache device.
1668 static void conditional_stop_bcache_device(struct cache_set *c,
1669 struct bcache_device *d,
1670 struct cached_dev *dc)
1672 if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1673 pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.",
1674 d->disk->disk_name, c->sb.set_uuid);
1675 bcache_device_stop(d);
1676 } else if (atomic_read(&dc->has_dirty)) {
1678 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1679 * and dc->has_dirty == 1
1681 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.",
1682 d->disk->disk_name);
1684 * There might be a small time gap that cache set is
1685 * released but bcache device is not. Inside this time
1686 * gap, regular I/O requests will directly go into
1687 * backing device as no cache set attached to. This
1688 * behavior may also introduce potential inconsistence
1689 * data in writeback mode while cache is dirty.
1690 * Therefore before calling bcache_device_stop() due
1691 * to a broken cache device, dc->io_disable should be
1692 * explicitly set to true.
1694 dc->io_disable = true;
1695 /* make others know io_disable is true earlier */
1697 bcache_device_stop(d);
1700 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1701 * and dc->has_dirty == 0
1703 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.",
1704 d->disk->disk_name);
1708 static void __cache_set_unregister(struct closure *cl)
1710 struct cache_set *c = container_of(cl, struct cache_set, caching);
1711 struct cached_dev *dc;
1712 struct bcache_device *d;
1715 mutex_lock(&bch_register_lock);
1717 for (i = 0; i < c->devices_max_used; i++) {
1722 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1723 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1724 dc = container_of(d, struct cached_dev, disk);
1725 bch_cached_dev_detach(dc);
1726 if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1727 conditional_stop_bcache_device(c, d, dc);
1729 bcache_device_stop(d);
1733 mutex_unlock(&bch_register_lock);
1735 continue_at(cl, cache_set_flush, system_wq);
1738 void bch_cache_set_stop(struct cache_set *c)
1740 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1741 /* closure_fn set to __cache_set_unregister() */
1742 closure_queue(&c->caching);
1745 void bch_cache_set_unregister(struct cache_set *c)
1747 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1748 bch_cache_set_stop(c);
1751 #define alloc_bucket_pages(gfp, c) \
1752 ((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1754 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1757 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1762 __module_get(THIS_MODULE);
1763 closure_init(&c->cl, NULL);
1764 set_closure_fn(&c->cl, cache_set_free, system_wq);
1766 closure_init(&c->caching, &c->cl);
1767 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1769 /* Maybe create continue_at_noreturn() and use it here? */
1770 closure_set_stopped(&c->cl);
1771 closure_put(&c->cl);
1773 kobject_init(&c->kobj, &bch_cache_set_ktype);
1774 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1776 bch_cache_accounting_init(&c->accounting, &c->cl);
1778 memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1779 c->sb.block_size = sb->block_size;
1780 c->sb.bucket_size = sb->bucket_size;
1781 c->sb.nr_in_set = sb->nr_in_set;
1782 c->sb.last_mount = sb->last_mount;
1783 c->bucket_bits = ilog2(sb->bucket_size);
1784 c->block_bits = ilog2(sb->block_size);
1785 c->nr_uuids = bucket_bytes(c) / sizeof(struct uuid_entry);
1786 c->devices_max_used = 0;
1787 atomic_set(&c->attached_dev_nr, 0);
1788 c->btree_pages = bucket_pages(c);
1789 if (c->btree_pages > BTREE_MAX_PAGES)
1790 c->btree_pages = max_t(int, c->btree_pages / 4,
1793 sema_init(&c->sb_write_mutex, 1);
1794 mutex_init(&c->bucket_lock);
1795 init_waitqueue_head(&c->btree_cache_wait);
1796 spin_lock_init(&c->btree_cannibalize_lock);
1797 init_waitqueue_head(&c->bucket_wait);
1798 init_waitqueue_head(&c->gc_wait);
1799 sema_init(&c->uuid_write_mutex, 1);
1801 spin_lock_init(&c->btree_gc_time.lock);
1802 spin_lock_init(&c->btree_split_time.lock);
1803 spin_lock_init(&c->btree_read_time.lock);
1805 bch_moving_init_cache_set(c);
1807 INIT_LIST_HEAD(&c->list);
1808 INIT_LIST_HEAD(&c->cached_devs);
1809 INIT_LIST_HEAD(&c->btree_cache);
1810 INIT_LIST_HEAD(&c->btree_cache_freeable);
1811 INIT_LIST_HEAD(&c->btree_cache_freed);
1812 INIT_LIST_HEAD(&c->data_buckets);
1814 iter_size = (sb->bucket_size / sb->block_size + 1) *
1815 sizeof(struct btree_iter_set);
1817 if (!(c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL)) ||
1818 mempool_init_slab_pool(&c->search, 32, bch_search_cache) ||
1819 mempool_init_kmalloc_pool(&c->bio_meta, 2,
1820 sizeof(struct bbio) + sizeof(struct bio_vec) *
1822 mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
1823 bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1824 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER) ||
1825 !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1826 !(c->moving_gc_wq = alloc_workqueue("bcache_gc",
1827 WQ_MEM_RECLAIM, 0)) ||
1828 bch_journal_alloc(c) ||
1829 bch_btree_cache_alloc(c) ||
1830 bch_open_buckets_alloc(c) ||
1831 bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1834 c->congested_read_threshold_us = 2000;
1835 c->congested_write_threshold_us = 20000;
1836 c->error_limit = DEFAULT_IO_ERROR_LIMIT;
1837 c->idle_max_writeback_rate_enabled = 1;
1838 WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1842 bch_cache_set_unregister(c);
1846 static int run_cache_set(struct cache_set *c)
1848 const char *err = "cannot allocate memory";
1849 struct cached_dev *dc, *t;
1854 struct journal_replay *l;
1856 closure_init_stack(&cl);
1858 for_each_cache(ca, c, i)
1859 c->nbuckets += ca->sb.nbuckets;
1862 if (CACHE_SYNC(&c->sb)) {
1866 err = "cannot allocate memory for journal";
1867 if (bch_journal_read(c, &journal))
1870 pr_debug("btree_journal_read() done");
1872 err = "no journal entries found";
1873 if (list_empty(&journal))
1876 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1878 err = "IO error reading priorities";
1879 for_each_cache(ca, c, i)
1880 prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1883 * If prio_read() fails it'll call cache_set_error and we'll
1884 * tear everything down right away, but if we perhaps checked
1885 * sooner we could avoid journal replay.
1890 err = "bad btree root";
1891 if (__bch_btree_ptr_invalid(c, k))
1894 err = "error reading btree root";
1895 c->root = bch_btree_node_get(c, NULL, k,
1898 if (IS_ERR_OR_NULL(c->root))
1901 list_del_init(&c->root->list);
1902 rw_unlock(true, c->root);
1904 err = uuid_read(c, j, &cl);
1908 err = "error in recovery";
1909 if (bch_btree_check(c))
1913 * bch_btree_check() may occupy too much system memory which
1914 * has negative effects to user space application (e.g. data
1915 * base) performance. Shrink the mca cache memory proactively
1916 * here to avoid competing memory with user space workloads..
1918 if (!c->shrinker_disabled) {
1919 struct shrink_control sc;
1921 sc.gfp_mask = GFP_KERNEL;
1922 sc.nr_to_scan = c->btree_cache_used * c->btree_pages;
1923 /* first run to clear b->accessed tag */
1924 c->shrink.scan_objects(&c->shrink, &sc);
1925 /* second run to reap non-accessed nodes */
1926 c->shrink.scan_objects(&c->shrink, &sc);
1929 bch_journal_mark(c, &journal);
1930 bch_initial_gc_finish(c);
1931 pr_debug("btree_check() done");
1934 * bcache_journal_next() can't happen sooner, or
1935 * btree_gc_finish() will give spurious errors about last_gc >
1936 * gc_gen - this is a hack but oh well.
1938 bch_journal_next(&c->journal);
1940 err = "error starting allocator thread";
1941 for_each_cache(ca, c, i)
1942 if (bch_cache_allocator_start(ca))
1946 * First place it's safe to allocate: btree_check() and
1947 * btree_gc_finish() have to run before we have buckets to
1948 * allocate, and bch_bucket_alloc_set() might cause a journal
1949 * entry to be written so bcache_journal_next() has to be called
1952 * If the uuids were in the old format we have to rewrite them
1953 * before the next journal entry is written:
1955 if (j->version < BCACHE_JSET_VERSION_UUID)
1958 err = "bcache: replay journal failed";
1959 if (bch_journal_replay(c, &journal))
1962 pr_notice("invalidating existing data");
1964 for_each_cache(ca, c, i) {
1967 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1968 2, SB_JOURNAL_BUCKETS);
1970 for (j = 0; j < ca->sb.keys; j++)
1971 ca->sb.d[j] = ca->sb.first_bucket + j;
1974 bch_initial_gc_finish(c);
1976 err = "error starting allocator thread";
1977 for_each_cache(ca, c, i)
1978 if (bch_cache_allocator_start(ca))
1981 mutex_lock(&c->bucket_lock);
1982 for_each_cache(ca, c, i)
1983 bch_prio_write(ca, true);
1984 mutex_unlock(&c->bucket_lock);
1986 err = "cannot allocate new UUID bucket";
1987 if (__uuid_write(c))
1990 err = "cannot allocate new btree root";
1991 c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
1992 if (IS_ERR_OR_NULL(c->root))
1995 mutex_lock(&c->root->write_lock);
1996 bkey_copy_key(&c->root->key, &MAX_KEY);
1997 bch_btree_node_write(c->root, &cl);
1998 mutex_unlock(&c->root->write_lock);
2000 bch_btree_set_root(c->root);
2001 rw_unlock(true, c->root);
2004 * We don't want to write the first journal entry until
2005 * everything is set up - fortunately journal entries won't be
2006 * written until the SET_CACHE_SYNC() here:
2008 SET_CACHE_SYNC(&c->sb, true);
2010 bch_journal_next(&c->journal);
2011 bch_journal_meta(c, &cl);
2014 err = "error starting gc thread";
2015 if (bch_gc_thread_start(c))
2019 c->sb.last_mount = (u32)ktime_get_real_seconds();
2020 bcache_write_super(c);
2022 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2023 bch_cached_dev_attach(dc, c, NULL);
2027 set_bit(CACHE_SET_RUNNING, &c->flags);
2030 while (!list_empty(&journal)) {
2031 l = list_first_entry(&journal, struct journal_replay, list);
2038 bch_cache_set_error(c, "%s", err);
2043 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
2045 return ca->sb.block_size == c->sb.block_size &&
2046 ca->sb.bucket_size == c->sb.bucket_size &&
2047 ca->sb.nr_in_set == c->sb.nr_in_set;
2050 static const char *register_cache_set(struct cache *ca)
2053 const char *err = "cannot allocate memory";
2054 struct cache_set *c;
2056 list_for_each_entry(c, &bch_cache_sets, list)
2057 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
2058 if (c->cache[ca->sb.nr_this_dev])
2059 return "duplicate cache set member";
2061 if (!can_attach_cache(ca, c))
2062 return "cache sb does not match set";
2064 if (!CACHE_SYNC(&ca->sb))
2065 SET_CACHE_SYNC(&c->sb, false);
2070 c = bch_cache_set_alloc(&ca->sb);
2074 err = "error creating kobject";
2075 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
2076 kobject_add(&c->internal, &c->kobj, "internal"))
2079 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2082 bch_debug_init_cache_set(c);
2084 list_add(&c->list, &bch_cache_sets);
2086 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2087 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2088 sysfs_create_link(&c->kobj, &ca->kobj, buf))
2091 if (ca->sb.seq > c->sb.seq) {
2092 c->sb.version = ca->sb.version;
2093 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
2094 c->sb.flags = ca->sb.flags;
2095 c->sb.seq = ca->sb.seq;
2096 pr_debug("set version = %llu", c->sb.version);
2099 kobject_get(&ca->kobj);
2101 ca->set->cache[ca->sb.nr_this_dev] = ca;
2102 c->cache_by_alloc[c->caches_loaded++] = ca;
2104 if (c->caches_loaded == c->sb.nr_in_set) {
2105 err = "failed to run cache set";
2106 if (run_cache_set(c) < 0)
2112 bch_cache_set_unregister(c);
2118 /* When ca->kobj released */
2119 void bch_cache_release(struct kobject *kobj)
2121 struct cache *ca = container_of(kobj, struct cache, kobj);
2125 BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
2126 ca->set->cache[ca->sb.nr_this_dev] = NULL;
2129 free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
2130 kfree(ca->prio_buckets);
2133 free_heap(&ca->heap);
2134 free_fifo(&ca->free_inc);
2136 for (i = 0; i < RESERVE_NR; i++)
2137 free_fifo(&ca->free[i]);
2139 if (ca->sb_bio.bi_inline_vecs[0].bv_page)
2140 put_page(bio_first_page_all(&ca->sb_bio));
2142 if (!IS_ERR_OR_NULL(ca->bdev))
2143 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2146 module_put(THIS_MODULE);
2149 static int cache_alloc(struct cache *ca)
2152 size_t btree_buckets;
2155 const char *err = NULL;
2157 __module_get(THIS_MODULE);
2158 kobject_init(&ca->kobj, &bch_cache_ktype);
2160 bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2163 * when ca->sb.njournal_buckets is not zero, journal exists,
2164 * and in bch_journal_replay(), tree node may split,
2165 * so bucket of RESERVE_BTREE type is needed,
2166 * the worst situation is all journal buckets are valid journal,
2167 * and all the keys need to replay,
2168 * so the number of RESERVE_BTREE type buckets should be as much
2169 * as journal buckets
2171 btree_buckets = ca->sb.njournal_buckets ?: 8;
2172 free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
2175 err = "ca->sb.nbuckets is too small";
2179 if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
2181 err = "ca->free[RESERVE_BTREE] alloc failed";
2182 goto err_btree_alloc;
2185 if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
2187 err = "ca->free[RESERVE_PRIO] alloc failed";
2188 goto err_prio_alloc;
2191 if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
2192 err = "ca->free[RESERVE_MOVINGGC] alloc failed";
2193 goto err_movinggc_alloc;
2196 if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
2197 err = "ca->free[RESERVE_NONE] alloc failed";
2198 goto err_none_alloc;
2201 if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
2202 err = "ca->free_inc alloc failed";
2203 goto err_free_inc_alloc;
2206 if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
2207 err = "ca->heap alloc failed";
2208 goto err_heap_alloc;
2211 ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2214 err = "ca->buckets alloc failed";
2215 goto err_buckets_alloc;
2218 ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
2219 prio_buckets(ca), 2),
2221 if (!ca->prio_buckets) {
2222 err = "ca->prio_buckets alloc failed";
2223 goto err_prio_buckets_alloc;
2226 ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca);
2227 if (!ca->disk_buckets) {
2228 err = "ca->disk_buckets alloc failed";
2229 goto err_disk_buckets_alloc;
2232 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2234 for_each_bucket(b, ca)
2235 atomic_set(&b->pin, 0);
2238 err_disk_buckets_alloc:
2239 kfree(ca->prio_buckets);
2240 err_prio_buckets_alloc:
2243 free_heap(&ca->heap);
2245 free_fifo(&ca->free_inc);
2247 free_fifo(&ca->free[RESERVE_NONE]);
2249 free_fifo(&ca->free[RESERVE_MOVINGGC]);
2251 free_fifo(&ca->free[RESERVE_PRIO]);
2253 free_fifo(&ca->free[RESERVE_BTREE]);
2256 module_put(THIS_MODULE);
2258 pr_notice("error %s: %s", ca->cache_dev_name, err);
2262 static int register_cache(struct cache_sb *sb, struct page *sb_page,
2263 struct block_device *bdev, struct cache *ca)
2265 const char *err = NULL; /* must be set for any error case */
2268 bdevname(bdev, ca->cache_dev_name);
2269 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2271 ca->bdev->bd_holder = ca;
2273 bio_init(&ca->sb_bio, ca->sb_bio.bi_inline_vecs, 1);
2274 bio_first_bvec_all(&ca->sb_bio)->bv_page = sb_page;
2277 if (blk_queue_discard(bdev_get_queue(bdev)))
2278 ca->discard = CACHE_DISCARD(&ca->sb);
2280 ret = cache_alloc(ca);
2283 * If we failed here, it means ca->kobj is not initialized yet,
2284 * kobject_put() won't be called and there is no chance to
2285 * call blkdev_put() to bdev in bch_cache_release(). So we
2286 * explicitly call blkdev_put() here.
2288 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2290 err = "cache_alloc(): -ENOMEM";
2291 else if (ret == -EPERM)
2292 err = "cache_alloc(): cache device is too small";
2294 err = "cache_alloc(): unknown error";
2298 if (kobject_add(&ca->kobj,
2299 &part_to_dev(bdev->bd_part)->kobj,
2301 err = "error calling kobject_add";
2306 mutex_lock(&bch_register_lock);
2307 err = register_cache_set(ca);
2308 mutex_unlock(&bch_register_lock);
2315 pr_info("registered cache device %s", ca->cache_dev_name);
2318 kobject_put(&ca->kobj);
2322 pr_notice("error %s: %s", ca->cache_dev_name, err);
2327 /* Global interfaces/init */
2329 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2330 const char *buffer, size_t size);
2331 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2332 struct kobj_attribute *attr,
2333 const char *buffer, size_t size);
2335 kobj_attribute_write(register, register_bcache);
2336 kobj_attribute_write(register_quiet, register_bcache);
2337 kobj_attribute_write(pendings_cleanup, bch_pending_bdevs_cleanup);
2339 static bool bch_is_open_backing(struct block_device *bdev)
2341 struct cache_set *c, *tc;
2342 struct cached_dev *dc, *t;
2344 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2345 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2346 if (dc->bdev == bdev)
2348 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2349 if (dc->bdev == bdev)
2354 static bool bch_is_open_cache(struct block_device *bdev)
2356 struct cache_set *c, *tc;
2360 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2361 for_each_cache(ca, c, i)
2362 if (ca->bdev == bdev)
2367 static bool bch_is_open(struct block_device *bdev)
2369 return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2372 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2373 const char *buffer, size_t size)
2375 ssize_t ret = -EINVAL;
2376 const char *err = "cannot allocate memory";
2378 struct cache_sb *sb = NULL;
2379 struct block_device *bdev = NULL;
2380 struct page *sb_page = NULL;
2382 if (!try_module_get(THIS_MODULE))
2385 /* For latest state of bcache_is_reboot */
2387 if (bcache_is_reboot)
2390 path = kstrndup(buffer, size, GFP_KERNEL);
2394 sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2398 err = "failed to open device";
2399 bdev = blkdev_get_by_path(strim(path),
2400 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2403 if (bdev == ERR_PTR(-EBUSY)) {
2404 bdev = lookup_bdev(strim(path));
2405 mutex_lock(&bch_register_lock);
2406 if (!IS_ERR(bdev) && bch_is_open(bdev))
2407 err = "device already registered";
2409 err = "device busy";
2410 mutex_unlock(&bch_register_lock);
2413 if (attr == &ksysfs_register_quiet)
2419 err = "failed to set blocksize";
2420 if (set_blocksize(bdev, 4096))
2423 err = read_super(sb, bdev, &sb_page);
2427 err = "failed to register device";
2428 if (SB_IS_BDEV(sb)) {
2429 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2434 mutex_lock(&bch_register_lock);
2435 ret = register_bdev(sb, sb_page, bdev, dc);
2436 mutex_unlock(&bch_register_lock);
2437 /* blkdev_put() will be called in cached_dev_free() */
2441 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2446 /* blkdev_put() will be called in bch_cache_release() */
2447 if (register_cache(sb, sb_page, bdev, ca) != 0)
2457 module_put(THIS_MODULE);
2461 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2463 pr_info("error %s: %s", path, err);
2469 struct list_head list;
2470 struct cached_dev *dc;
2473 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2474 struct kobj_attribute *attr,
2478 LIST_HEAD(pending_devs);
2480 struct cached_dev *dc, *tdc;
2481 struct pdev *pdev, *tpdev;
2482 struct cache_set *c, *tc;
2484 mutex_lock(&bch_register_lock);
2485 list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
2486 pdev = kmalloc(sizeof(struct pdev), GFP_KERNEL);
2490 list_add(&pdev->list, &pending_devs);
2493 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2494 list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
2495 char *pdev_set_uuid = pdev->dc->sb.set_uuid;
2496 char *set_uuid = c->sb.uuid;
2498 if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
2499 list_del(&pdev->list);
2505 mutex_unlock(&bch_register_lock);
2507 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2508 pr_info("delete pdev %p", pdev);
2509 list_del(&pdev->list);
2510 bcache_device_stop(&pdev->dc->disk);
2517 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2519 if (bcache_is_reboot)
2522 if (code == SYS_DOWN ||
2524 code == SYS_POWER_OFF) {
2526 unsigned long start = jiffies;
2527 bool stopped = false;
2529 struct cache_set *c, *tc;
2530 struct cached_dev *dc, *tdc;
2532 mutex_lock(&bch_register_lock);
2534 if (bcache_is_reboot)
2537 /* New registration is rejected since now */
2538 bcache_is_reboot = true;
2540 * Make registering caller (if there is) on other CPU
2541 * core know bcache_is_reboot set to true earlier
2545 if (list_empty(&bch_cache_sets) &&
2546 list_empty(&uncached_devices))
2549 mutex_unlock(&bch_register_lock);
2551 pr_info("Stopping all devices:");
2554 * The reason bch_register_lock is not held to call
2555 * bch_cache_set_stop() and bcache_device_stop() is to
2556 * avoid potential deadlock during reboot, because cache
2557 * set or bcache device stopping process will acqurie
2558 * bch_register_lock too.
2560 * We are safe here because bcache_is_reboot sets to
2561 * true already, register_bcache() will reject new
2562 * registration now. bcache_is_reboot also makes sure
2563 * bcache_reboot() won't be re-entered on by other thread,
2564 * so there is no race in following list iteration by
2565 * list_for_each_entry_safe().
2567 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2568 bch_cache_set_stop(c);
2570 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2571 bcache_device_stop(&dc->disk);
2575 * Give an early chance for other kthreads and
2576 * kworkers to stop themselves
2580 /* What's a condition variable? */
2582 long timeout = start + 10 * HZ - jiffies;
2584 mutex_lock(&bch_register_lock);
2585 stopped = list_empty(&bch_cache_sets) &&
2586 list_empty(&uncached_devices);
2588 if (timeout < 0 || stopped)
2591 prepare_to_wait(&unregister_wait, &wait,
2592 TASK_UNINTERRUPTIBLE);
2594 mutex_unlock(&bch_register_lock);
2595 schedule_timeout(timeout);
2598 finish_wait(&unregister_wait, &wait);
2601 pr_info("All devices stopped");
2603 pr_notice("Timeout waiting for devices to be closed");
2605 mutex_unlock(&bch_register_lock);
2611 static struct notifier_block reboot = {
2612 .notifier_call = bcache_reboot,
2613 .priority = INT_MAX, /* before any real devices */
2616 static void bcache_exit(void)
2621 kobject_put(bcache_kobj);
2623 destroy_workqueue(bcache_wq);
2625 destroy_workqueue(bch_journal_wq);
2628 unregister_blkdev(bcache_major, "bcache");
2629 unregister_reboot_notifier(&reboot);
2630 mutex_destroy(&bch_register_lock);
2633 /* Check and fixup module parameters */
2634 static void check_module_parameters(void)
2636 if (bch_cutoff_writeback_sync == 0)
2637 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
2638 else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
2639 pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u",
2640 bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
2641 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
2644 if (bch_cutoff_writeback == 0)
2645 bch_cutoff_writeback = CUTOFF_WRITEBACK;
2646 else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
2647 pr_warn("set bch_cutoff_writeback (%u) to max value %u",
2648 bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
2649 bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
2652 if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
2653 pr_warn("set bch_cutoff_writeback (%u) to %u",
2654 bch_cutoff_writeback, bch_cutoff_writeback_sync);
2655 bch_cutoff_writeback = bch_cutoff_writeback_sync;
2659 static int __init bcache_init(void)
2661 static const struct attribute *files[] = {
2662 &ksysfs_register.attr,
2663 &ksysfs_register_quiet.attr,
2664 &ksysfs_pendings_cleanup.attr,
2668 check_module_parameters();
2670 mutex_init(&bch_register_lock);
2671 init_waitqueue_head(&unregister_wait);
2672 register_reboot_notifier(&reboot);
2674 bcache_major = register_blkdev(0, "bcache");
2675 if (bcache_major < 0) {
2676 unregister_reboot_notifier(&reboot);
2677 mutex_destroy(&bch_register_lock);
2678 return bcache_major;
2681 bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2685 bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
2686 if (!bch_journal_wq)
2689 bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2693 if (bch_request_init() ||
2694 sysfs_create_files(bcache_kobj, files))
2698 closure_debug_init();
2700 bcache_is_reboot = false;
2711 module_exit(bcache_exit);
2712 module_init(bcache_init);
2714 module_param(bch_cutoff_writeback, uint, 0);
2715 MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
2717 module_param(bch_cutoff_writeback_sync, uint, 0);
2718 MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
2720 MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
2721 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
2722 MODULE_LICENSE("GPL");