2 * bcache setup/teardown code, and some metadata io - read a superblock and
3 * figure out what to do with it.
5 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6 * Copyright 2012 Google, Inc.
14 #include "writeback.h"
16 #include <linux/blkdev.h>
17 #include <linux/buffer_head.h>
18 #include <linux/debugfs.h>
19 #include <linux/genhd.h>
20 #include <linux/idr.h>
21 #include <linux/kthread.h>
22 #include <linux/module.h>
23 #include <linux/random.h>
24 #include <linux/reboot.h>
25 #include <linux/sysfs.h>
27 MODULE_LICENSE("GPL");
28 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
30 static const char bcache_magic[] = {
31 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
32 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
35 static const char invalid_uuid[] = {
36 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
37 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
40 /* Default is -1; we skip past it for struct cached_dev's cache mode */
41 const char * const bch_cache_modes[] = {
50 static struct kobject *bcache_kobj;
51 struct mutex bch_register_lock;
52 LIST_HEAD(bch_cache_sets);
53 static LIST_HEAD(uncached_devices);
55 static int bcache_major;
56 static DEFINE_IDA(bcache_minor);
57 static wait_queue_head_t unregister_wait;
58 struct workqueue_struct *bcache_wq;
60 #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
62 static void bio_split_pool_free(struct bio_split_pool *p)
64 if (p->bio_split_hook)
65 mempool_destroy(p->bio_split_hook);
68 bioset_free(p->bio_split);
71 static int bio_split_pool_init(struct bio_split_pool *p)
73 p->bio_split = bioset_create(4, 0);
77 p->bio_split_hook = mempool_create_kmalloc_pool(4,
78 sizeof(struct bio_split_hook));
79 if (!p->bio_split_hook)
87 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
92 struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
98 s = (struct cache_sb *) bh->b_data;
100 sb->offset = le64_to_cpu(s->offset);
101 sb->version = le64_to_cpu(s->version);
103 memcpy(sb->magic, s->magic, 16);
104 memcpy(sb->uuid, s->uuid, 16);
105 memcpy(sb->set_uuid, s->set_uuid, 16);
106 memcpy(sb->label, s->label, SB_LABEL_SIZE);
108 sb->flags = le64_to_cpu(s->flags);
109 sb->seq = le64_to_cpu(s->seq);
110 sb->last_mount = le32_to_cpu(s->last_mount);
111 sb->first_bucket = le16_to_cpu(s->first_bucket);
112 sb->keys = le16_to_cpu(s->keys);
114 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
115 sb->d[i] = le64_to_cpu(s->d[i]);
117 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
118 sb->version, sb->flags, sb->seq, sb->keys);
120 err = "Not a bcache superblock";
121 if (sb->offset != SB_SECTOR)
124 if (memcmp(sb->magic, bcache_magic, 16))
127 err = "Too many journal buckets";
128 if (sb->keys > SB_JOURNAL_BUCKETS)
131 err = "Bad checksum";
132 if (s->csum != csum_set(s))
136 if (bch_is_zero(sb->uuid, 16))
139 sb->block_size = le16_to_cpu(s->block_size);
141 err = "Superblock block size smaller than device block size";
142 if (sb->block_size << 9 < bdev_logical_block_size(bdev))
145 switch (sb->version) {
146 case BCACHE_SB_VERSION_BDEV:
147 sb->data_offset = BDEV_DATA_START_DEFAULT;
149 case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
150 sb->data_offset = le64_to_cpu(s->data_offset);
152 err = "Bad data offset";
153 if (sb->data_offset < BDEV_DATA_START_DEFAULT)
157 case BCACHE_SB_VERSION_CDEV:
158 case BCACHE_SB_VERSION_CDEV_WITH_UUID:
159 sb->nbuckets = le64_to_cpu(s->nbuckets);
160 sb->block_size = le16_to_cpu(s->block_size);
161 sb->bucket_size = le16_to_cpu(s->bucket_size);
163 sb->nr_in_set = le16_to_cpu(s->nr_in_set);
164 sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
166 err = "Too many buckets";
167 if (sb->nbuckets > LONG_MAX)
170 err = "Not enough buckets";
171 if (sb->nbuckets < 1 << 7)
174 err = "Bad block/bucket size";
175 if (!is_power_of_2(sb->block_size) ||
176 sb->block_size > PAGE_SECTORS ||
177 !is_power_of_2(sb->bucket_size) ||
178 sb->bucket_size < PAGE_SECTORS)
181 err = "Invalid superblock: device too small";
182 if (get_capacity(bdev->bd_disk) < sb->bucket_size * sb->nbuckets)
186 if (bch_is_zero(sb->set_uuid, 16))
189 err = "Bad cache device number in set";
190 if (!sb->nr_in_set ||
191 sb->nr_in_set <= sb->nr_this_dev ||
192 sb->nr_in_set > MAX_CACHES_PER_SET)
195 err = "Journal buckets not sequential";
196 for (i = 0; i < sb->keys; i++)
197 if (sb->d[i] != sb->first_bucket + i)
200 err = "Too many journal buckets";
201 if (sb->first_bucket + sb->keys > sb->nbuckets)
204 err = "Invalid superblock: first bucket comes before end of super";
205 if (sb->first_bucket * sb->bucket_size < 16)
210 err = "Unsupported superblock version";
214 sb->last_mount = get_seconds();
217 get_page(bh->b_page);
224 static void write_bdev_super_endio(struct bio *bio, int error)
226 struct cached_dev *dc = bio->bi_private;
227 /* XXX: error checking */
229 closure_put(&dc->sb_write);
232 static void __write_super(struct cache_sb *sb, struct bio *bio)
234 struct cache_sb *out = page_address(bio->bi_io_vec[0].bv_page);
237 bio->bi_iter.bi_sector = SB_SECTOR;
238 bio->bi_rw = REQ_SYNC|REQ_META;
239 bio->bi_iter.bi_size = SB_SIZE;
240 bch_bio_map(bio, NULL);
242 out->offset = cpu_to_le64(sb->offset);
243 out->version = cpu_to_le64(sb->version);
245 memcpy(out->uuid, sb->uuid, 16);
246 memcpy(out->set_uuid, sb->set_uuid, 16);
247 memcpy(out->label, sb->label, SB_LABEL_SIZE);
249 out->flags = cpu_to_le64(sb->flags);
250 out->seq = cpu_to_le64(sb->seq);
252 out->last_mount = cpu_to_le32(sb->last_mount);
253 out->first_bucket = cpu_to_le16(sb->first_bucket);
254 out->keys = cpu_to_le16(sb->keys);
256 for (i = 0; i < sb->keys; i++)
257 out->d[i] = cpu_to_le64(sb->d[i]);
259 out->csum = csum_set(out);
261 pr_debug("ver %llu, flags %llu, seq %llu",
262 sb->version, sb->flags, sb->seq);
264 submit_bio(REQ_WRITE, bio);
267 static void bch_write_bdev_super_unlock(struct closure *cl)
269 struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
271 up(&dc->sb_write_mutex);
274 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
276 struct closure *cl = &dc->sb_write;
277 struct bio *bio = &dc->sb_bio;
279 down(&dc->sb_write_mutex);
280 closure_init(cl, parent);
283 bio->bi_bdev = dc->bdev;
284 bio->bi_end_io = write_bdev_super_endio;
285 bio->bi_private = dc;
288 __write_super(&dc->sb, bio);
290 closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
293 static void write_super_endio(struct bio *bio, int error)
295 struct cache *ca = bio->bi_private;
297 bch_count_io_errors(ca, error, "writing superblock");
298 closure_put(&ca->set->sb_write);
301 static void bcache_write_super_unlock(struct closure *cl)
303 struct cache_set *c = container_of(cl, struct cache_set, sb_write);
305 up(&c->sb_write_mutex);
308 void bcache_write_super(struct cache_set *c)
310 struct closure *cl = &c->sb_write;
314 down(&c->sb_write_mutex);
315 closure_init(cl, &c->cl);
319 for_each_cache(ca, c, i) {
320 struct bio *bio = &ca->sb_bio;
322 ca->sb.version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
323 ca->sb.seq = c->sb.seq;
324 ca->sb.last_mount = c->sb.last_mount;
326 SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
329 bio->bi_bdev = ca->bdev;
330 bio->bi_end_io = write_super_endio;
331 bio->bi_private = ca;
334 __write_super(&ca->sb, bio);
337 closure_return_with_destructor(cl, bcache_write_super_unlock);
342 static void uuid_endio(struct bio *bio, int error)
344 struct closure *cl = bio->bi_private;
345 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
347 cache_set_err_on(error, c, "accessing uuids");
348 bch_bbio_free(bio, c);
352 static void uuid_io_unlock(struct closure *cl)
354 struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
356 up(&c->uuid_write_mutex);
359 static void uuid_io(struct cache_set *c, unsigned long rw,
360 struct bkey *k, struct closure *parent)
362 struct closure *cl = &c->uuid_write;
363 struct uuid_entry *u;
368 down(&c->uuid_write_mutex);
369 closure_init(cl, parent);
371 for (i = 0; i < KEY_PTRS(k); i++) {
372 struct bio *bio = bch_bbio_alloc(c);
374 bio->bi_rw = REQ_SYNC|REQ_META|rw;
375 bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
377 bio->bi_end_io = uuid_endio;
378 bio->bi_private = cl;
379 bch_bio_map(bio, c->uuids);
381 bch_submit_bbio(bio, c, k, i);
387 bch_extent_to_text(buf, sizeof(buf), k);
388 pr_debug("%s UUIDs at %s", rw & REQ_WRITE ? "wrote" : "read", buf);
390 for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
391 if (!bch_is_zero(u->uuid, 16))
392 pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
393 u - c->uuids, u->uuid, u->label,
394 u->first_reg, u->last_reg, u->invalidated);
396 closure_return_with_destructor(cl, uuid_io_unlock);
399 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
401 struct bkey *k = &j->uuid_bucket;
403 if (__bch_btree_ptr_invalid(c, k))
404 return "bad uuid pointer";
406 bkey_copy(&c->uuid_bucket, k);
407 uuid_io(c, READ_SYNC, k, cl);
409 if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
410 struct uuid_entry_v0 *u0 = (void *) c->uuids;
411 struct uuid_entry *u1 = (void *) c->uuids;
417 * Since the new uuid entry is bigger than the old, we have to
418 * convert starting at the highest memory address and work down
419 * in order to do it in place
422 for (i = c->nr_uuids - 1;
425 memcpy(u1[i].uuid, u0[i].uuid, 16);
426 memcpy(u1[i].label, u0[i].label, 32);
428 u1[i].first_reg = u0[i].first_reg;
429 u1[i].last_reg = u0[i].last_reg;
430 u1[i].invalidated = u0[i].invalidated;
440 static int __uuid_write(struct cache_set *c)
444 closure_init_stack(&cl);
446 lockdep_assert_held(&bch_register_lock);
448 if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
451 SET_KEY_SIZE(&k.key, c->sb.bucket_size);
452 uuid_io(c, REQ_WRITE, &k.key, &cl);
455 bkey_copy(&c->uuid_bucket, &k.key);
460 int bch_uuid_write(struct cache_set *c)
462 int ret = __uuid_write(c);
465 bch_journal_meta(c, NULL);
470 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
472 struct uuid_entry *u;
475 u < c->uuids + c->nr_uuids; u++)
476 if (!memcmp(u->uuid, uuid, 16))
482 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
484 static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
485 return uuid_find(c, zero_uuid);
489 * Bucket priorities/gens:
491 * For each bucket, we store on disk its
495 * See alloc.c for an explanation of the gen. The priority is used to implement
496 * lru (and in the future other) cache replacement policies; for most purposes
497 * it's just an opaque integer.
499 * The gens and the priorities don't have a whole lot to do with each other, and
500 * it's actually the gens that must be written out at specific times - it's no
501 * big deal if the priorities don't get written, if we lose them we just reuse
502 * buckets in suboptimal order.
504 * On disk they're stored in a packed array, and in as many buckets are required
505 * to fit them all. The buckets we use to store them form a list; the journal
506 * header points to the first bucket, the first bucket points to the second
509 * This code is used by the allocation code; periodically (whenever it runs out
510 * of buckets to allocate from) the allocation code will invalidate some
511 * buckets, but it can't use those buckets until their new gens are safely on
515 static void prio_endio(struct bio *bio, int error)
517 struct cache *ca = bio->bi_private;
519 cache_set_err_on(error, ca->set, "accessing priorities");
520 bch_bbio_free(bio, ca->set);
521 closure_put(&ca->prio);
524 static void prio_io(struct cache *ca, uint64_t bucket, unsigned long rw)
526 struct closure *cl = &ca->prio;
527 struct bio *bio = bch_bbio_alloc(ca->set);
529 closure_init_stack(cl);
531 bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
532 bio->bi_bdev = ca->bdev;
533 bio->bi_rw = REQ_SYNC|REQ_META|rw;
534 bio->bi_iter.bi_size = bucket_bytes(ca);
536 bio->bi_end_io = prio_endio;
537 bio->bi_private = ca;
538 bch_bio_map(bio, ca->disk_buckets);
540 closure_bio_submit(bio, &ca->prio, ca);
544 #define buckets_free(c) "free %zu, free_inc %zu, unused %zu", \
545 fifo_used(&c->free), fifo_used(&c->free_inc), fifo_used(&c->unused)
547 void bch_prio_write(struct cache *ca)
553 closure_init_stack(&cl);
555 lockdep_assert_held(&ca->set->bucket_lock);
557 for (b = ca->buckets;
558 b < ca->buckets + ca->sb.nbuckets; b++)
559 b->disk_gen = b->gen;
561 ca->disk_buckets->seq++;
563 atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
564 &ca->meta_sectors_written);
566 //pr_debug("free %zu, free_inc %zu, unused %zu", fifo_used(&ca->free),
567 // fifo_used(&ca->free_inc), fifo_used(&ca->unused));
569 for (i = prio_buckets(ca) - 1; i >= 0; --i) {
571 struct prio_set *p = ca->disk_buckets;
572 struct bucket_disk *d = p->data;
573 struct bucket_disk *end = d + prios_per_bucket(ca);
575 for (b = ca->buckets + i * prios_per_bucket(ca);
576 b < ca->buckets + ca->sb.nbuckets && d < end;
578 d->prio = cpu_to_le16(b->prio);
582 p->next_bucket = ca->prio_buckets[i + 1];
583 p->magic = pset_magic(&ca->sb);
584 p->csum = bch_crc64(&p->magic, bucket_bytes(ca) - 8);
586 bucket = bch_bucket_alloc(ca, RESERVE_PRIO, true);
587 BUG_ON(bucket == -1);
589 mutex_unlock(&ca->set->bucket_lock);
590 prio_io(ca, bucket, REQ_WRITE);
591 mutex_lock(&ca->set->bucket_lock);
593 ca->prio_buckets[i] = bucket;
594 atomic_dec_bug(&ca->buckets[bucket].pin);
597 mutex_unlock(&ca->set->bucket_lock);
599 bch_journal_meta(ca->set, &cl);
602 mutex_lock(&ca->set->bucket_lock);
604 ca->need_save_prio = 0;
607 * Don't want the old priorities to get garbage collected until after we
608 * finish writing the new ones, and they're journalled
610 for (i = 0; i < prio_buckets(ca); i++)
611 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 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, READ_SYNC);
631 if (p->csum != bch_crc64(&p->magic, bucket_bytes(ca) - 8))
632 pr_warn("bad csum reading priorities");
634 if (p->magic != pset_magic(&ca->sb))
635 pr_warn("bad magic reading priorities");
637 bucket = p->next_bucket;
641 b->prio = le16_to_cpu(d->prio);
642 b->gen = b->disk_gen = b->last_gc = b->gc_gen = d->gen;
648 static int open_dev(struct block_device *b, fmode_t mode)
650 struct bcache_device *d = b->bd_disk->private_data;
651 if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
658 static void release_dev(struct gendisk *b, fmode_t mode)
660 struct bcache_device *d = b->private_data;
664 static int ioctl_dev(struct block_device *b, fmode_t mode,
665 unsigned int cmd, unsigned long arg)
667 struct bcache_device *d = b->bd_disk->private_data;
668 return d->ioctl(d, mode, cmd, arg);
671 static const struct block_device_operations bcache_ops = {
673 .release = release_dev,
675 .owner = THIS_MODULE,
678 void bcache_device_stop(struct bcache_device *d)
680 if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
681 closure_queue(&d->cl);
684 static void bcache_device_unlink(struct bcache_device *d)
686 lockdep_assert_held(&bch_register_lock);
688 if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
692 sysfs_remove_link(&d->c->kobj, d->name);
693 sysfs_remove_link(&d->kobj, "cache");
695 for_each_cache(ca, d->c, i)
696 bd_unlink_disk_holder(ca->bdev, d->disk);
700 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
706 for_each_cache(ca, d->c, i)
707 bd_link_disk_holder(ca->bdev, d->disk);
709 snprintf(d->name, BCACHEDEVNAME_SIZE,
710 "%s%u", name, d->id);
712 WARN(sysfs_create_link(&d->kobj, &c->kobj, "cache") ||
713 sysfs_create_link(&c->kobj, &d->kobj, d->name),
714 "Couldn't create device <-> cache set symlinks");
717 static void bcache_device_detach(struct bcache_device *d)
719 lockdep_assert_held(&bch_register_lock);
721 if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
722 struct uuid_entry *u = d->c->uuids + d->id;
724 SET_UUID_FLASH_ONLY(u, 0);
725 memcpy(u->uuid, invalid_uuid, 16);
726 u->invalidated = cpu_to_le32(get_seconds());
727 bch_uuid_write(d->c);
730 bcache_device_unlink(d);
732 d->c->devices[d->id] = NULL;
733 closure_put(&d->c->caching);
737 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
740 BUG_ON(test_bit(CACHE_SET_STOPPING, &c->flags));
746 closure_get(&c->caching);
749 static void bcache_device_free(struct bcache_device *d)
751 lockdep_assert_held(&bch_register_lock);
753 pr_info("%s stopped", d->disk->disk_name);
756 bcache_device_detach(d);
757 if (d->disk && d->disk->flags & GENHD_FL_UP)
758 del_gendisk(d->disk);
759 if (d->disk && d->disk->queue)
760 blk_cleanup_queue(d->disk->queue);
762 ida_simple_remove(&bcache_minor, d->disk->first_minor);
766 bio_split_pool_free(&d->bio_split_hook);
768 bioset_free(d->bio_split);
769 if (is_vmalloc_addr(d->full_dirty_stripes))
770 vfree(d->full_dirty_stripes);
772 kfree(d->full_dirty_stripes);
773 if (is_vmalloc_addr(d->stripe_sectors_dirty))
774 vfree(d->stripe_sectors_dirty);
776 kfree(d->stripe_sectors_dirty);
778 closure_debug_destroy(&d->cl);
781 static int bcache_device_init(struct bcache_device *d, unsigned block_size,
784 struct request_queue *q;
789 d->stripe_size = 1 << 31;
791 d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
793 if (!d->nr_stripes ||
794 d->nr_stripes > INT_MAX ||
795 d->nr_stripes > SIZE_MAX / sizeof(atomic_t)) {
796 pr_err("nr_stripes too large");
800 n = d->nr_stripes * sizeof(atomic_t);
801 d->stripe_sectors_dirty = n < PAGE_SIZE << 6
802 ? kzalloc(n, GFP_KERNEL)
804 if (!d->stripe_sectors_dirty)
807 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
808 d->full_dirty_stripes = n < PAGE_SIZE << 6
809 ? kzalloc(n, GFP_KERNEL)
811 if (!d->full_dirty_stripes)
814 minor = ida_simple_get(&bcache_minor, 0, MINORMASK + 1, GFP_KERNEL);
818 if (!(d->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
819 bio_split_pool_init(&d->bio_split_hook) ||
820 !(d->disk = alloc_disk(1))) {
821 ida_simple_remove(&bcache_minor, minor);
825 set_capacity(d->disk, sectors);
826 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", minor);
828 d->disk->major = bcache_major;
829 d->disk->first_minor = minor;
830 d->disk->fops = &bcache_ops;
831 d->disk->private_data = d;
833 q = blk_alloc_queue(GFP_KERNEL);
837 blk_queue_make_request(q, NULL);
840 q->backing_dev_info.congested_data = d;
841 q->limits.max_hw_sectors = UINT_MAX;
842 q->limits.max_sectors = UINT_MAX;
843 q->limits.max_segment_size = UINT_MAX;
844 q->limits.max_segments = BIO_MAX_PAGES;
845 q->limits.max_discard_sectors = UINT_MAX;
846 q->limits.discard_granularity = 512;
847 q->limits.io_min = block_size;
848 q->limits.logical_block_size = block_size;
849 q->limits.physical_block_size = block_size;
850 set_bit(QUEUE_FLAG_NONROT, &d->disk->queue->queue_flags);
851 set_bit(QUEUE_FLAG_DISCARD, &d->disk->queue->queue_flags);
853 blk_queue_flush(q, REQ_FLUSH|REQ_FUA);
860 static void calc_cached_dev_sectors(struct cache_set *c)
862 uint64_t sectors = 0;
863 struct cached_dev *dc;
865 list_for_each_entry(dc, &c->cached_devs, list)
866 sectors += bdev_sectors(dc->bdev);
868 c->cached_dev_sectors = sectors;
871 void bch_cached_dev_run(struct cached_dev *dc)
873 struct bcache_device *d = &dc->disk;
874 char buf[SB_LABEL_SIZE + 1];
877 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
882 memcpy(buf, dc->sb.label, SB_LABEL_SIZE);
883 buf[SB_LABEL_SIZE] = '\0';
884 env[2] = kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf);
886 if (atomic_xchg(&dc->running, 1))
890 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
892 closure_init_stack(&cl);
894 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
895 bch_write_bdev_super(dc, &cl);
900 bd_link_disk_holder(dc->bdev, dc->disk.disk);
901 /* won't show up in the uevent file, use udevadm monitor -e instead
902 * only class / kset properties are persistent */
903 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
907 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
908 sysfs_create_link(&disk_to_dev(d->disk)->kobj, &d->kobj, "bcache"))
909 pr_debug("error creating sysfs link");
912 static void cached_dev_detach_finish(struct work_struct *w)
914 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
915 char buf[BDEVNAME_SIZE];
917 closure_init_stack(&cl);
919 BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
920 BUG_ON(atomic_read(&dc->count));
922 mutex_lock(&bch_register_lock);
924 memset(&dc->sb.set_uuid, 0, 16);
925 SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
927 bch_write_bdev_super(dc, &cl);
930 bcache_device_detach(&dc->disk);
931 list_move(&dc->list, &uncached_devices);
933 clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
935 mutex_unlock(&bch_register_lock);
937 pr_info("Caching disabled for %s", bdevname(dc->bdev, buf));
939 /* Drop ref we took in cached_dev_detach() */
940 closure_put(&dc->disk.cl);
943 void bch_cached_dev_detach(struct cached_dev *dc)
945 lockdep_assert_held(&bch_register_lock);
947 if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
950 if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
954 * Block the device from being closed and freed until we're finished
957 closure_get(&dc->disk.cl);
959 bch_writeback_queue(dc);
963 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c)
965 uint32_t rtime = cpu_to_le32(get_seconds());
966 struct uuid_entry *u;
967 char buf[BDEVNAME_SIZE];
969 bdevname(dc->bdev, buf);
971 if (memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16))
975 pr_err("Can't attach %s: already attached", buf);
979 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
980 pr_err("Can't attach %s: shutting down", buf);
984 if (dc->sb.block_size < c->sb.block_size) {
986 pr_err("Couldn't attach %s: block size less than set's block size",
991 u = uuid_find(c, dc->sb.uuid);
994 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
995 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
996 memcpy(u->uuid, invalid_uuid, 16);
997 u->invalidated = cpu_to_le32(get_seconds());
1002 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1003 pr_err("Couldn't find uuid for %s in set", buf);
1007 u = uuid_find_empty(c);
1009 pr_err("Not caching %s, no room for UUID", buf);
1014 /* Deadlocks since we're called via sysfs...
1015 sysfs_remove_file(&dc->kobj, &sysfs_attach);
1018 if (bch_is_zero(u->uuid, 16)) {
1020 closure_init_stack(&cl);
1022 memcpy(u->uuid, dc->sb.uuid, 16);
1023 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1024 u->first_reg = u->last_reg = rtime;
1027 memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1028 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1030 bch_write_bdev_super(dc, &cl);
1033 u->last_reg = rtime;
1037 bcache_device_attach(&dc->disk, c, u - c->uuids);
1038 list_move(&dc->list, &c->cached_devs);
1039 calc_cached_dev_sectors(c);
1043 * dc->c must be set before dc->count != 0 - paired with the mb in
1046 atomic_set(&dc->count, 1);
1048 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1049 bch_sectors_dirty_init(dc);
1050 atomic_set(&dc->has_dirty, 1);
1051 atomic_inc(&dc->count);
1052 bch_writeback_queue(dc);
1055 bch_cached_dev_run(dc);
1056 bcache_device_link(&dc->disk, c, "bdev");
1058 pr_info("Caching %s as %s on set %pU",
1059 bdevname(dc->bdev, buf), dc->disk.disk->disk_name,
1060 dc->disk.c->sb.set_uuid);
1064 void bch_cached_dev_release(struct kobject *kobj)
1066 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1069 module_put(THIS_MODULE);
1072 static void cached_dev_free(struct closure *cl)
1074 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1076 cancel_delayed_work_sync(&dc->writeback_rate_update);
1077 kthread_stop(dc->writeback_thread);
1079 mutex_lock(&bch_register_lock);
1081 if (atomic_read(&dc->running))
1082 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1083 bcache_device_free(&dc->disk);
1084 list_del(&dc->list);
1086 mutex_unlock(&bch_register_lock);
1088 if (!IS_ERR_OR_NULL(dc->bdev)) {
1089 if (dc->bdev->bd_disk)
1090 blk_sync_queue(bdev_get_queue(dc->bdev));
1092 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1095 wake_up(&unregister_wait);
1097 kobject_put(&dc->disk.kobj);
1100 static void cached_dev_flush(struct closure *cl)
1102 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1103 struct bcache_device *d = &dc->disk;
1105 mutex_lock(&bch_register_lock);
1106 bcache_device_unlink(d);
1107 mutex_unlock(&bch_register_lock);
1109 bch_cache_accounting_destroy(&dc->accounting);
1110 kobject_del(&d->kobj);
1112 continue_at(cl, cached_dev_free, system_wq);
1115 static int cached_dev_init(struct cached_dev *dc, unsigned block_size)
1119 struct request_queue *q = bdev_get_queue(dc->bdev);
1121 __module_get(THIS_MODULE);
1122 INIT_LIST_HEAD(&dc->list);
1123 closure_init(&dc->disk.cl, NULL);
1124 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1125 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1126 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1127 sema_init(&dc->sb_write_mutex, 1);
1128 INIT_LIST_HEAD(&dc->io_lru);
1129 spin_lock_init(&dc->io_lock);
1130 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1132 dc->sequential_cutoff = 4 << 20;
1134 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1135 list_add(&io->lru, &dc->io_lru);
1136 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1139 dc->disk.stripe_size = q->limits.io_opt >> 9;
1141 if (dc->disk.stripe_size)
1142 dc->partial_stripes_expensive =
1143 q->limits.raid_partial_stripes_expensive;
1145 ret = bcache_device_init(&dc->disk, block_size,
1146 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1150 set_capacity(dc->disk.disk,
1151 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1153 dc->disk.disk->queue->backing_dev_info.ra_pages =
1154 max(dc->disk.disk->queue->backing_dev_info.ra_pages,
1155 q->backing_dev_info.ra_pages);
1157 bch_cached_dev_request_init(dc);
1158 bch_cached_dev_writeback_init(dc);
1162 /* Cached device - bcache superblock */
1164 static void register_bdev(struct cache_sb *sb, struct page *sb_page,
1165 struct block_device *bdev,
1166 struct cached_dev *dc)
1168 char name[BDEVNAME_SIZE];
1169 const char *err = "cannot allocate memory";
1170 struct cache_set *c;
1172 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1174 dc->bdev->bd_holder = dc;
1176 bio_init(&dc->sb_bio);
1177 dc->sb_bio.bi_max_vecs = 1;
1178 dc->sb_bio.bi_io_vec = dc->sb_bio.bi_inline_vecs;
1179 dc->sb_bio.bi_io_vec[0].bv_page = sb_page;
1182 if (cached_dev_init(dc, sb->block_size << 9))
1185 err = "error creating kobject";
1186 if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1189 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1192 pr_info("registered backing device %s", bdevname(bdev, name));
1194 list_add(&dc->list, &uncached_devices);
1195 list_for_each_entry(c, &bch_cache_sets, list)
1196 bch_cached_dev_attach(dc, c);
1198 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1199 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE)
1200 bch_cached_dev_run(dc);
1204 pr_notice("error opening %s: %s", bdevname(bdev, name), err);
1205 bcache_device_stop(&dc->disk);
1208 /* Flash only volumes */
1210 void bch_flash_dev_release(struct kobject *kobj)
1212 struct bcache_device *d = container_of(kobj, struct bcache_device,
1217 static void flash_dev_free(struct closure *cl)
1219 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1220 bcache_device_free(d);
1221 kobject_put(&d->kobj);
1224 static void flash_dev_flush(struct closure *cl)
1226 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1228 bcache_device_unlink(d);
1229 kobject_del(&d->kobj);
1230 continue_at(cl, flash_dev_free, system_wq);
1233 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1235 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1240 closure_init(&d->cl, NULL);
1241 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1243 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1245 if (bcache_device_init(d, block_bytes(c), u->sectors))
1248 bcache_device_attach(d, c, u - c->uuids);
1249 bch_flash_dev_request_init(d);
1252 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1255 bcache_device_link(d, c, "volume");
1259 kobject_put(&d->kobj);
1263 static int flash_devs_run(struct cache_set *c)
1266 struct uuid_entry *u;
1269 u < c->uuids + c->nr_uuids && !ret;
1271 if (UUID_FLASH_ONLY(u))
1272 ret = flash_dev_run(c, u);
1277 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1279 struct uuid_entry *u;
1281 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1284 u = uuid_find_empty(c);
1286 pr_err("Can't create volume, no room for UUID");
1290 get_random_bytes(u->uuid, 16);
1291 memset(u->label, 0, 32);
1292 u->first_reg = u->last_reg = cpu_to_le32(get_seconds());
1294 SET_UUID_FLASH_ONLY(u, 1);
1295 u->sectors = size >> 9;
1299 return flash_dev_run(c, u);
1305 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1309 if (c->on_error != ON_ERROR_PANIC &&
1310 test_bit(CACHE_SET_STOPPING, &c->flags))
1313 /* XXX: we can be called from atomic context
1314 acquire_console_sem();
1317 printk(KERN_ERR "bcache: error on %pU: ", c->sb.set_uuid);
1319 va_start(args, fmt);
1323 printk(", disabling caching\n");
1325 if (c->on_error == ON_ERROR_PANIC)
1326 panic("panic forced after error\n");
1328 bch_cache_set_unregister(c);
1332 void bch_cache_set_release(struct kobject *kobj)
1334 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1336 module_put(THIS_MODULE);
1339 static void cache_set_free(struct closure *cl)
1341 struct cache_set *c = container_of(cl, struct cache_set, cl);
1345 if (!IS_ERR_OR_NULL(c->debug))
1346 debugfs_remove(c->debug);
1348 bch_open_buckets_free(c);
1349 bch_btree_cache_free(c);
1350 bch_journal_free(c);
1352 for_each_cache(ca, c, i)
1354 kobject_put(&ca->kobj);
1356 bch_bset_sort_state_free(&c->sort);
1357 free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1359 if (c->moving_gc_wq)
1360 destroy_workqueue(c->moving_gc_wq);
1362 bioset_free(c->bio_split);
1364 mempool_destroy(c->fill_iter);
1366 mempool_destroy(c->bio_meta);
1368 mempool_destroy(c->search);
1371 mutex_lock(&bch_register_lock);
1373 mutex_unlock(&bch_register_lock);
1375 pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1376 wake_up(&unregister_wait);
1378 closure_debug_destroy(&c->cl);
1379 kobject_put(&c->kobj);
1382 static void cache_set_flush(struct closure *cl)
1384 struct cache_set *c = container_of(cl, struct cache_set, caching);
1389 bch_cache_accounting_destroy(&c->accounting);
1391 kobject_put(&c->internal);
1392 kobject_del(&c->kobj);
1395 kthread_stop(c->gc_thread);
1397 if (!IS_ERR_OR_NULL(c->root))
1398 list_add(&c->root->list, &c->btree_cache);
1400 /* Should skip this if we're unregistering because of an error */
1401 list_for_each_entry(b, &c->btree_cache, list) {
1402 mutex_lock(&b->write_lock);
1403 if (btree_node_dirty(b))
1404 __bch_btree_node_write(b, NULL);
1405 mutex_unlock(&b->write_lock);
1408 for_each_cache(ca, c, i)
1409 if (ca->alloc_thread)
1410 kthread_stop(ca->alloc_thread);
1412 cancel_delayed_work_sync(&c->journal.work);
1413 /* flush last journal entry if needed */
1414 c->journal.work.work.func(&c->journal.work.work);
1419 static void __cache_set_unregister(struct closure *cl)
1421 struct cache_set *c = container_of(cl, struct cache_set, caching);
1422 struct cached_dev *dc;
1425 mutex_lock(&bch_register_lock);
1427 for (i = 0; i < c->nr_uuids; i++)
1428 if (c->devices[i]) {
1429 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1430 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1431 dc = container_of(c->devices[i],
1432 struct cached_dev, disk);
1433 bch_cached_dev_detach(dc);
1435 bcache_device_stop(c->devices[i]);
1439 mutex_unlock(&bch_register_lock);
1441 continue_at(cl, cache_set_flush, system_wq);
1444 void bch_cache_set_stop(struct cache_set *c)
1446 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1447 closure_queue(&c->caching);
1450 void bch_cache_set_unregister(struct cache_set *c)
1452 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1453 bch_cache_set_stop(c);
1456 #define alloc_bucket_pages(gfp, c) \
1457 ((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1459 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1462 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1466 __module_get(THIS_MODULE);
1467 closure_init(&c->cl, NULL);
1468 set_closure_fn(&c->cl, cache_set_free, system_wq);
1470 closure_init(&c->caching, &c->cl);
1471 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1473 /* Maybe create continue_at_noreturn() and use it here? */
1474 closure_set_stopped(&c->cl);
1475 closure_put(&c->cl);
1477 kobject_init(&c->kobj, &bch_cache_set_ktype);
1478 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1480 bch_cache_accounting_init(&c->accounting, &c->cl);
1482 memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1483 c->sb.block_size = sb->block_size;
1484 c->sb.bucket_size = sb->bucket_size;
1485 c->sb.nr_in_set = sb->nr_in_set;
1486 c->sb.last_mount = sb->last_mount;
1487 c->bucket_bits = ilog2(sb->bucket_size);
1488 c->block_bits = ilog2(sb->block_size);
1489 c->nr_uuids = bucket_bytes(c) / sizeof(struct uuid_entry);
1491 c->btree_pages = bucket_pages(c);
1492 if (c->btree_pages > BTREE_MAX_PAGES)
1493 c->btree_pages = max_t(int, c->btree_pages / 4,
1496 sema_init(&c->sb_write_mutex, 1);
1497 mutex_init(&c->bucket_lock);
1498 init_waitqueue_head(&c->try_wait);
1499 init_waitqueue_head(&c->bucket_wait);
1500 sema_init(&c->uuid_write_mutex, 1);
1502 spin_lock_init(&c->btree_gc_time.lock);
1503 spin_lock_init(&c->btree_split_time.lock);
1504 spin_lock_init(&c->btree_read_time.lock);
1505 spin_lock_init(&c->try_harder_time.lock);
1507 bch_moving_init_cache_set(c);
1509 INIT_LIST_HEAD(&c->list);
1510 INIT_LIST_HEAD(&c->cached_devs);
1511 INIT_LIST_HEAD(&c->btree_cache);
1512 INIT_LIST_HEAD(&c->btree_cache_freeable);
1513 INIT_LIST_HEAD(&c->btree_cache_freed);
1514 INIT_LIST_HEAD(&c->data_buckets);
1516 c->search = mempool_create_slab_pool(32, bch_search_cache);
1520 iter_size = (sb->bucket_size / sb->block_size + 1) *
1521 sizeof(struct btree_iter_set);
1523 if (!(c->devices = kzalloc(c->nr_uuids * sizeof(void *), GFP_KERNEL)) ||
1524 !(c->bio_meta = mempool_create_kmalloc_pool(2,
1525 sizeof(struct bbio) + sizeof(struct bio_vec) *
1526 bucket_pages(c))) ||
1527 !(c->fill_iter = mempool_create_kmalloc_pool(1, iter_size)) ||
1528 !(c->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
1529 !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1530 !(c->moving_gc_wq = create_workqueue("bcache_gc")) ||
1531 bch_journal_alloc(c) ||
1532 bch_btree_cache_alloc(c) ||
1533 bch_open_buckets_alloc(c) ||
1534 bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1537 c->congested_read_threshold_us = 2000;
1538 c->congested_write_threshold_us = 20000;
1539 c->error_limit = 8 << IO_ERROR_SHIFT;
1543 bch_cache_set_unregister(c);
1547 static void run_cache_set(struct cache_set *c)
1549 const char *err = "cannot allocate memory";
1550 struct cached_dev *dc, *t;
1555 closure_init_stack(&cl);
1557 for_each_cache(ca, c, i)
1558 c->nbuckets += ca->sb.nbuckets;
1560 if (CACHE_SYNC(&c->sb)) {
1565 err = "cannot allocate memory for journal";
1566 if (bch_journal_read(c, &journal))
1569 pr_debug("btree_journal_read() done");
1571 err = "no journal entries found";
1572 if (list_empty(&journal))
1575 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1577 err = "IO error reading priorities";
1578 for_each_cache(ca, c, i)
1579 prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1582 * If prio_read() fails it'll call cache_set_error and we'll
1583 * tear everything down right away, but if we perhaps checked
1584 * sooner we could avoid journal replay.
1589 err = "bad btree root";
1590 if (__bch_btree_ptr_invalid(c, k))
1593 err = "error reading btree root";
1594 c->root = bch_btree_node_get(c, k, j->btree_level, true);
1595 if (IS_ERR_OR_NULL(c->root))
1598 list_del_init(&c->root->list);
1599 rw_unlock(true, c->root);
1601 err = uuid_read(c, j, &cl);
1605 err = "error in recovery";
1606 if (bch_btree_check(c))
1609 bch_journal_mark(c, &journal);
1610 bch_btree_gc_finish(c);
1611 pr_debug("btree_check() done");
1614 * bcache_journal_next() can't happen sooner, or
1615 * btree_gc_finish() will give spurious errors about last_gc >
1616 * gc_gen - this is a hack but oh well.
1618 bch_journal_next(&c->journal);
1620 err = "error starting allocator thread";
1621 for_each_cache(ca, c, i)
1622 if (bch_cache_allocator_start(ca))
1626 * First place it's safe to allocate: btree_check() and
1627 * btree_gc_finish() have to run before we have buckets to
1628 * allocate, and bch_bucket_alloc_set() might cause a journal
1629 * entry to be written so bcache_journal_next() has to be called
1632 * If the uuids were in the old format we have to rewrite them
1633 * before the next journal entry is written:
1635 if (j->version < BCACHE_JSET_VERSION_UUID)
1638 bch_journal_replay(c, &journal);
1640 pr_notice("invalidating existing data");
1642 for_each_cache(ca, c, i) {
1645 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1646 2, SB_JOURNAL_BUCKETS);
1648 for (j = 0; j < ca->sb.keys; j++)
1649 ca->sb.d[j] = ca->sb.first_bucket + j;
1652 bch_btree_gc_finish(c);
1654 err = "error starting allocator thread";
1655 for_each_cache(ca, c, i)
1656 if (bch_cache_allocator_start(ca))
1659 mutex_lock(&c->bucket_lock);
1660 for_each_cache(ca, c, i)
1662 mutex_unlock(&c->bucket_lock);
1664 err = "cannot allocate new UUID bucket";
1665 if (__uuid_write(c))
1668 err = "cannot allocate new btree root";
1669 c->root = bch_btree_node_alloc(c, 0, true);
1670 if (IS_ERR_OR_NULL(c->root))
1673 mutex_lock(&c->root->write_lock);
1674 bkey_copy_key(&c->root->key, &MAX_KEY);
1675 bch_btree_node_write(c->root, &cl);
1676 mutex_unlock(&c->root->write_lock);
1678 bch_btree_set_root(c->root);
1679 rw_unlock(true, c->root);
1682 * We don't want to write the first journal entry until
1683 * everything is set up - fortunately journal entries won't be
1684 * written until the SET_CACHE_SYNC() here:
1686 SET_CACHE_SYNC(&c->sb, true);
1688 bch_journal_next(&c->journal);
1689 bch_journal_meta(c, &cl);
1692 err = "error starting gc thread";
1693 if (bch_gc_thread_start(c))
1697 c->sb.last_mount = get_seconds();
1698 bcache_write_super(c);
1700 list_for_each_entry_safe(dc, t, &uncached_devices, list)
1701 bch_cached_dev_attach(dc, c);
1708 /* XXX: test this, it's broken */
1709 bch_cache_set_error(c, "%s", err);
1712 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
1714 return ca->sb.block_size == c->sb.block_size &&
1715 ca->sb.bucket_size == c->sb.bucket_size &&
1716 ca->sb.nr_in_set == c->sb.nr_in_set;
1719 static const char *register_cache_set(struct cache *ca)
1722 const char *err = "cannot allocate memory";
1723 struct cache_set *c;
1725 list_for_each_entry(c, &bch_cache_sets, list)
1726 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
1727 if (c->cache[ca->sb.nr_this_dev])
1728 return "duplicate cache set member";
1730 if (!can_attach_cache(ca, c))
1731 return "cache sb does not match set";
1733 if (!CACHE_SYNC(&ca->sb))
1734 SET_CACHE_SYNC(&c->sb, false);
1739 c = bch_cache_set_alloc(&ca->sb);
1743 err = "error creating kobject";
1744 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
1745 kobject_add(&c->internal, &c->kobj, "internal"))
1748 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
1751 bch_debug_init_cache_set(c);
1753 list_add(&c->list, &bch_cache_sets);
1755 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
1756 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
1757 sysfs_create_link(&c->kobj, &ca->kobj, buf))
1760 if (ca->sb.seq > c->sb.seq) {
1761 c->sb.version = ca->sb.version;
1762 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
1763 c->sb.flags = ca->sb.flags;
1764 c->sb.seq = ca->sb.seq;
1765 pr_debug("set version = %llu", c->sb.version);
1769 ca->set->cache[ca->sb.nr_this_dev] = ca;
1770 c->cache_by_alloc[c->caches_loaded++] = ca;
1772 if (c->caches_loaded == c->sb.nr_in_set)
1777 bch_cache_set_unregister(c);
1783 void bch_cache_release(struct kobject *kobj)
1785 struct cache *ca = container_of(kobj, struct cache, kobj);
1789 ca->set->cache[ca->sb.nr_this_dev] = NULL;
1791 bio_split_pool_free(&ca->bio_split_hook);
1793 free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
1794 kfree(ca->prio_buckets);
1797 free_heap(&ca->heap);
1798 free_fifo(&ca->unused);
1799 free_fifo(&ca->free_inc);
1801 for (i = 0; i < RESERVE_NR; i++)
1802 free_fifo(&ca->free[i]);
1804 if (ca->sb_bio.bi_inline_vecs[0].bv_page)
1805 put_page(ca->sb_bio.bi_io_vec[0].bv_page);
1807 if (!IS_ERR_OR_NULL(ca->bdev)) {
1808 blk_sync_queue(bdev_get_queue(ca->bdev));
1809 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1813 module_put(THIS_MODULE);
1816 static int cache_alloc(struct cache_sb *sb, struct cache *ca)
1821 __module_get(THIS_MODULE);
1822 kobject_init(&ca->kobj, &bch_cache_ktype);
1824 bio_init(&ca->journal.bio);
1825 ca->journal.bio.bi_max_vecs = 8;
1826 ca->journal.bio.bi_io_vec = ca->journal.bio.bi_inline_vecs;
1828 free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
1830 if (!init_fifo(&ca->free[RESERVE_BTREE], 8, GFP_KERNEL) ||
1831 !init_fifo(&ca->free[RESERVE_PRIO], prio_buckets(ca), GFP_KERNEL) ||
1832 !init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL) ||
1833 !init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL) ||
1834 !init_fifo(&ca->free_inc, free << 2, GFP_KERNEL) ||
1835 !init_fifo(&ca->unused, free << 2, GFP_KERNEL) ||
1836 !init_heap(&ca->heap, free << 3, GFP_KERNEL) ||
1837 !(ca->buckets = vzalloc(sizeof(struct bucket) *
1838 ca->sb.nbuckets)) ||
1839 !(ca->prio_buckets = kzalloc(sizeof(uint64_t) * prio_buckets(ca) *
1841 !(ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca)) ||
1842 bio_split_pool_init(&ca->bio_split_hook))
1845 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
1847 for_each_bucket(b, ca)
1848 atomic_set(&b->pin, 0);
1850 if (bch_cache_allocator_init(ca))
1855 kobject_put(&ca->kobj);
1859 static void register_cache(struct cache_sb *sb, struct page *sb_page,
1860 struct block_device *bdev, struct cache *ca)
1862 char name[BDEVNAME_SIZE];
1863 const char *err = "cannot allocate memory";
1865 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
1867 ca->bdev->bd_holder = ca;
1869 bio_init(&ca->sb_bio);
1870 ca->sb_bio.bi_max_vecs = 1;
1871 ca->sb_bio.bi_io_vec = ca->sb_bio.bi_inline_vecs;
1872 ca->sb_bio.bi_io_vec[0].bv_page = sb_page;
1875 if (blk_queue_discard(bdev_get_queue(ca->bdev)))
1876 ca->discard = CACHE_DISCARD(&ca->sb);
1878 if (cache_alloc(sb, ca) != 0)
1881 err = "error creating kobject";
1882 if (kobject_add(&ca->kobj, &part_to_dev(bdev->bd_part)->kobj, "bcache"))
1885 mutex_lock(&bch_register_lock);
1886 err = register_cache_set(ca);
1887 mutex_unlock(&bch_register_lock);
1892 pr_info("registered cache device %s", bdevname(bdev, name));
1895 pr_notice("error opening %s: %s", bdevname(bdev, name), err);
1896 kobject_put(&ca->kobj);
1899 /* Global interfaces/init */
1901 static ssize_t register_bcache(struct kobject *, struct kobj_attribute *,
1902 const char *, size_t);
1904 kobj_attribute_write(register, register_bcache);
1905 kobj_attribute_write(register_quiet, register_bcache);
1907 static bool bch_is_open_backing(struct block_device *bdev) {
1908 struct cache_set *c, *tc;
1909 struct cached_dev *dc, *t;
1911 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
1912 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
1913 if (dc->bdev == bdev)
1915 list_for_each_entry_safe(dc, t, &uncached_devices, list)
1916 if (dc->bdev == bdev)
1921 static bool bch_is_open_cache(struct block_device *bdev) {
1922 struct cache_set *c, *tc;
1926 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
1927 for_each_cache(ca, c, i)
1928 if (ca->bdev == bdev)
1933 static bool bch_is_open(struct block_device *bdev) {
1934 return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
1937 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
1938 const char *buffer, size_t size)
1941 const char *err = "cannot allocate memory";
1943 struct cache_sb *sb = NULL;
1944 struct block_device *bdev = NULL;
1945 struct page *sb_page = NULL;
1947 if (!try_module_get(THIS_MODULE))
1950 if (!(path = kstrndup(buffer, size, GFP_KERNEL)) ||
1951 !(sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL)))
1954 err = "failed to open device";
1955 bdev = blkdev_get_by_path(strim(path),
1956 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
1959 if (bdev == ERR_PTR(-EBUSY)) {
1960 bdev = lookup_bdev(strim(path));
1961 if (!IS_ERR(bdev) && bch_is_open(bdev))
1962 err = "device already registered";
1964 err = "device busy";
1969 err = "failed to set blocksize";
1970 if (set_blocksize(bdev, 4096))
1973 err = read_super(sb, bdev, &sb_page);
1977 if (SB_IS_BDEV(sb)) {
1978 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
1982 mutex_lock(&bch_register_lock);
1983 register_bdev(sb, sb_page, bdev, dc);
1984 mutex_unlock(&bch_register_lock);
1986 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1990 register_cache(sb, sb_page, bdev, ca);
1997 module_put(THIS_MODULE);
2001 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2003 if (attr != &ksysfs_register_quiet)
2004 pr_info("error opening %s: %s", path, err);
2009 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2011 if (code == SYS_DOWN ||
2013 code == SYS_POWER_OFF) {
2015 unsigned long start = jiffies;
2016 bool stopped = false;
2018 struct cache_set *c, *tc;
2019 struct cached_dev *dc, *tdc;
2021 mutex_lock(&bch_register_lock);
2023 if (list_empty(&bch_cache_sets) &&
2024 list_empty(&uncached_devices))
2027 pr_info("Stopping all devices:");
2029 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2030 bch_cache_set_stop(c);
2032 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2033 bcache_device_stop(&dc->disk);
2035 /* What's a condition variable? */
2037 long timeout = start + 2 * HZ - jiffies;
2039 stopped = list_empty(&bch_cache_sets) &&
2040 list_empty(&uncached_devices);
2042 if (timeout < 0 || stopped)
2045 prepare_to_wait(&unregister_wait, &wait,
2046 TASK_UNINTERRUPTIBLE);
2048 mutex_unlock(&bch_register_lock);
2049 schedule_timeout(timeout);
2050 mutex_lock(&bch_register_lock);
2053 finish_wait(&unregister_wait, &wait);
2056 pr_info("All devices stopped");
2058 pr_notice("Timeout waiting for devices to be closed");
2060 mutex_unlock(&bch_register_lock);
2066 static struct notifier_block reboot = {
2067 .notifier_call = bcache_reboot,
2068 .priority = INT_MAX, /* before any real devices */
2071 static void bcache_exit(void)
2076 kobject_put(bcache_kobj);
2078 destroy_workqueue(bcache_wq);
2080 unregister_blkdev(bcache_major, "bcache");
2081 unregister_reboot_notifier(&reboot);
2084 static int __init bcache_init(void)
2086 static const struct attribute *files[] = {
2087 &ksysfs_register.attr,
2088 &ksysfs_register_quiet.attr,
2092 mutex_init(&bch_register_lock);
2093 init_waitqueue_head(&unregister_wait);
2094 register_reboot_notifier(&reboot);
2095 closure_debug_init();
2097 bcache_major = register_blkdev(0, "bcache");
2098 if (bcache_major < 0)
2099 return bcache_major;
2101 if (!(bcache_wq = create_workqueue("bcache")) ||
2102 !(bcache_kobj = kobject_create_and_add("bcache", fs_kobj)) ||
2103 sysfs_create_files(bcache_kobj, files) ||
2104 bch_request_init() ||
2105 bch_debug_init(bcache_kobj))
2114 module_exit(bcache_exit);
2115 module_init(bcache_init);