bcache: Better full stripe scanning
[GitHub/exynos8895/android_kernel_samsung_universal8895.git] / drivers / md / bcache / super.c
1 /*
2 * bcache setup/teardown code, and some metadata io - read a superblock and
3 * figure out what to do with it.
4 *
5 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6 * Copyright 2012 Google, Inc.
7 */
8
9 #include "bcache.h"
10 #include "btree.h"
11 #include "debug.h"
12 #include "request.h"
13 #include "writeback.h"
14
15 #include <linux/blkdev.h>
16 #include <linux/buffer_head.h>
17 #include <linux/debugfs.h>
18 #include <linux/genhd.h>
19 #include <linux/kthread.h>
20 #include <linux/module.h>
21 #include <linux/random.h>
22 #include <linux/reboot.h>
23 #include <linux/sysfs.h>
24
25 MODULE_LICENSE("GPL");
26 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
27
28 static const char bcache_magic[] = {
29 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
30 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
31 };
32
33 static const char invalid_uuid[] = {
34 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
35 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
36 };
37
38 /* Default is -1; we skip past it for struct cached_dev's cache mode */
39 const char * const bch_cache_modes[] = {
40 "default",
41 "writethrough",
42 "writeback",
43 "writearound",
44 "none",
45 NULL
46 };
47
48 static struct kobject *bcache_kobj;
49 struct mutex bch_register_lock;
50 LIST_HEAD(bch_cache_sets);
51 static LIST_HEAD(uncached_devices);
52
53 static int bcache_major, bcache_minor;
54 static wait_queue_head_t unregister_wait;
55 struct workqueue_struct *bcache_wq;
56
57 #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
58
59 static void bio_split_pool_free(struct bio_split_pool *p)
60 {
61 if (p->bio_split_hook)
62 mempool_destroy(p->bio_split_hook);
63
64 if (p->bio_split)
65 bioset_free(p->bio_split);
66 }
67
68 static int bio_split_pool_init(struct bio_split_pool *p)
69 {
70 p->bio_split = bioset_create(4, 0);
71 if (!p->bio_split)
72 return -ENOMEM;
73
74 p->bio_split_hook = mempool_create_kmalloc_pool(4,
75 sizeof(struct bio_split_hook));
76 if (!p->bio_split_hook)
77 return -ENOMEM;
78
79 return 0;
80 }
81
82 /* Superblock */
83
84 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
85 struct page **res)
86 {
87 const char *err;
88 struct cache_sb *s;
89 struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
90 unsigned i;
91
92 if (!bh)
93 return "IO error";
94
95 s = (struct cache_sb *) bh->b_data;
96
97 sb->offset = le64_to_cpu(s->offset);
98 sb->version = le64_to_cpu(s->version);
99
100 memcpy(sb->magic, s->magic, 16);
101 memcpy(sb->uuid, s->uuid, 16);
102 memcpy(sb->set_uuid, s->set_uuid, 16);
103 memcpy(sb->label, s->label, SB_LABEL_SIZE);
104
105 sb->flags = le64_to_cpu(s->flags);
106 sb->seq = le64_to_cpu(s->seq);
107 sb->last_mount = le32_to_cpu(s->last_mount);
108 sb->first_bucket = le16_to_cpu(s->first_bucket);
109 sb->keys = le16_to_cpu(s->keys);
110
111 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
112 sb->d[i] = le64_to_cpu(s->d[i]);
113
114 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
115 sb->version, sb->flags, sb->seq, sb->keys);
116
117 err = "Not a bcache superblock";
118 if (sb->offset != SB_SECTOR)
119 goto err;
120
121 if (memcmp(sb->magic, bcache_magic, 16))
122 goto err;
123
124 err = "Too many journal buckets";
125 if (sb->keys > SB_JOURNAL_BUCKETS)
126 goto err;
127
128 err = "Bad checksum";
129 if (s->csum != csum_set(s))
130 goto err;
131
132 err = "Bad UUID";
133 if (bch_is_zero(sb->uuid, 16))
134 goto err;
135
136 sb->block_size = le16_to_cpu(s->block_size);
137
138 err = "Superblock block size smaller than device block size";
139 if (sb->block_size << 9 < bdev_logical_block_size(bdev))
140 goto err;
141
142 switch (sb->version) {
143 case BCACHE_SB_VERSION_BDEV:
144 sb->data_offset = BDEV_DATA_START_DEFAULT;
145 break;
146 case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
147 sb->data_offset = le64_to_cpu(s->data_offset);
148
149 err = "Bad data offset";
150 if (sb->data_offset < BDEV_DATA_START_DEFAULT)
151 goto err;
152
153 break;
154 case BCACHE_SB_VERSION_CDEV:
155 case BCACHE_SB_VERSION_CDEV_WITH_UUID:
156 sb->nbuckets = le64_to_cpu(s->nbuckets);
157 sb->block_size = le16_to_cpu(s->block_size);
158 sb->bucket_size = le16_to_cpu(s->bucket_size);
159
160 sb->nr_in_set = le16_to_cpu(s->nr_in_set);
161 sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
162
163 err = "Too many buckets";
164 if (sb->nbuckets > LONG_MAX)
165 goto err;
166
167 err = "Not enough buckets";
168 if (sb->nbuckets < 1 << 7)
169 goto err;
170
171 err = "Bad block/bucket size";
172 if (!is_power_of_2(sb->block_size) ||
173 sb->block_size > PAGE_SECTORS ||
174 !is_power_of_2(sb->bucket_size) ||
175 sb->bucket_size < PAGE_SECTORS)
176 goto err;
177
178 err = "Invalid superblock: device too small";
179 if (get_capacity(bdev->bd_disk) < sb->bucket_size * sb->nbuckets)
180 goto err;
181
182 err = "Bad UUID";
183 if (bch_is_zero(sb->set_uuid, 16))
184 goto err;
185
186 err = "Bad cache device number in set";
187 if (!sb->nr_in_set ||
188 sb->nr_in_set <= sb->nr_this_dev ||
189 sb->nr_in_set > MAX_CACHES_PER_SET)
190 goto err;
191
192 err = "Journal buckets not sequential";
193 for (i = 0; i < sb->keys; i++)
194 if (sb->d[i] != sb->first_bucket + i)
195 goto err;
196
197 err = "Too many journal buckets";
198 if (sb->first_bucket + sb->keys > sb->nbuckets)
199 goto err;
200
201 err = "Invalid superblock: first bucket comes before end of super";
202 if (sb->first_bucket * sb->bucket_size < 16)
203 goto err;
204
205 break;
206 default:
207 err = "Unsupported superblock version";
208 goto err;
209 }
210
211 sb->last_mount = get_seconds();
212 err = NULL;
213
214 get_page(bh->b_page);
215 *res = bh->b_page;
216 err:
217 put_bh(bh);
218 return err;
219 }
220
221 static void write_bdev_super_endio(struct bio *bio, int error)
222 {
223 struct cached_dev *dc = bio->bi_private;
224 /* XXX: error checking */
225
226 closure_put(&dc->sb_write.cl);
227 }
228
229 static void __write_super(struct cache_sb *sb, struct bio *bio)
230 {
231 struct cache_sb *out = page_address(bio->bi_io_vec[0].bv_page);
232 unsigned i;
233
234 bio->bi_sector = SB_SECTOR;
235 bio->bi_rw = REQ_SYNC|REQ_META;
236 bio->bi_size = SB_SIZE;
237 bch_bio_map(bio, NULL);
238
239 out->offset = cpu_to_le64(sb->offset);
240 out->version = cpu_to_le64(sb->version);
241
242 memcpy(out->uuid, sb->uuid, 16);
243 memcpy(out->set_uuid, sb->set_uuid, 16);
244 memcpy(out->label, sb->label, SB_LABEL_SIZE);
245
246 out->flags = cpu_to_le64(sb->flags);
247 out->seq = cpu_to_le64(sb->seq);
248
249 out->last_mount = cpu_to_le32(sb->last_mount);
250 out->first_bucket = cpu_to_le16(sb->first_bucket);
251 out->keys = cpu_to_le16(sb->keys);
252
253 for (i = 0; i < sb->keys; i++)
254 out->d[i] = cpu_to_le64(sb->d[i]);
255
256 out->csum = csum_set(out);
257
258 pr_debug("ver %llu, flags %llu, seq %llu",
259 sb->version, sb->flags, sb->seq);
260
261 submit_bio(REQ_WRITE, bio);
262 }
263
264 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
265 {
266 struct closure *cl = &dc->sb_write.cl;
267 struct bio *bio = &dc->sb_bio;
268
269 closure_lock(&dc->sb_write, parent);
270
271 bio_reset(bio);
272 bio->bi_bdev = dc->bdev;
273 bio->bi_end_io = write_bdev_super_endio;
274 bio->bi_private = dc;
275
276 closure_get(cl);
277 __write_super(&dc->sb, bio);
278
279 closure_return(cl);
280 }
281
282 static void write_super_endio(struct bio *bio, int error)
283 {
284 struct cache *ca = bio->bi_private;
285
286 bch_count_io_errors(ca, error, "writing superblock");
287 closure_put(&ca->set->sb_write.cl);
288 }
289
290 void bcache_write_super(struct cache_set *c)
291 {
292 struct closure *cl = &c->sb_write.cl;
293 struct cache *ca;
294 unsigned i;
295
296 closure_lock(&c->sb_write, &c->cl);
297
298 c->sb.seq++;
299
300 for_each_cache(ca, c, i) {
301 struct bio *bio = &ca->sb_bio;
302
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;
306
307 SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
308
309 bio_reset(bio);
310 bio->bi_bdev = ca->bdev;
311 bio->bi_end_io = write_super_endio;
312 bio->bi_private = ca;
313
314 closure_get(cl);
315 __write_super(&ca->sb, bio);
316 }
317
318 closure_return(cl);
319 }
320
321 /* UUID io */
322
323 static void uuid_endio(struct bio *bio, int error)
324 {
325 struct closure *cl = bio->bi_private;
326 struct cache_set *c = container_of(cl, struct cache_set, uuid_write.cl);
327
328 cache_set_err_on(error, c, "accessing uuids");
329 bch_bbio_free(bio, c);
330 closure_put(cl);
331 }
332
333 static void uuid_io(struct cache_set *c, unsigned long rw,
334 struct bkey *k, struct closure *parent)
335 {
336 struct closure *cl = &c->uuid_write.cl;
337 struct uuid_entry *u;
338 unsigned i;
339 char buf[80];
340
341 BUG_ON(!parent);
342 closure_lock(&c->uuid_write, parent);
343
344 for (i = 0; i < KEY_PTRS(k); i++) {
345 struct bio *bio = bch_bbio_alloc(c);
346
347 bio->bi_rw = REQ_SYNC|REQ_META|rw;
348 bio->bi_size = KEY_SIZE(k) << 9;
349
350 bio->bi_end_io = uuid_endio;
351 bio->bi_private = cl;
352 bch_bio_map(bio, c->uuids);
353
354 bch_submit_bbio(bio, c, k, i);
355
356 if (!(rw & WRITE))
357 break;
358 }
359
360 bch_bkey_to_text(buf, sizeof(buf), k);
361 pr_debug("%s UUIDs at %s", rw & REQ_WRITE ? "wrote" : "read", buf);
362
363 for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
364 if (!bch_is_zero(u->uuid, 16))
365 pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
366 u - c->uuids, u->uuid, u->label,
367 u->first_reg, u->last_reg, u->invalidated);
368
369 closure_return(cl);
370 }
371
372 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
373 {
374 struct bkey *k = &j->uuid_bucket;
375
376 if (bch_btree_ptr_invalid(c, k))
377 return "bad uuid pointer";
378
379 bkey_copy(&c->uuid_bucket, k);
380 uuid_io(c, READ_SYNC, k, cl);
381
382 if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
383 struct uuid_entry_v0 *u0 = (void *) c->uuids;
384 struct uuid_entry *u1 = (void *) c->uuids;
385 int i;
386
387 closure_sync(cl);
388
389 /*
390 * Since the new uuid entry is bigger than the old, we have to
391 * convert starting at the highest memory address and work down
392 * in order to do it in place
393 */
394
395 for (i = c->nr_uuids - 1;
396 i >= 0;
397 --i) {
398 memcpy(u1[i].uuid, u0[i].uuid, 16);
399 memcpy(u1[i].label, u0[i].label, 32);
400
401 u1[i].first_reg = u0[i].first_reg;
402 u1[i].last_reg = u0[i].last_reg;
403 u1[i].invalidated = u0[i].invalidated;
404
405 u1[i].flags = 0;
406 u1[i].sectors = 0;
407 }
408 }
409
410 return NULL;
411 }
412
413 static int __uuid_write(struct cache_set *c)
414 {
415 BKEY_PADDED(key) k;
416 struct closure cl;
417 closure_init_stack(&cl);
418
419 lockdep_assert_held(&bch_register_lock);
420
421 if (bch_bucket_alloc_set(c, WATERMARK_METADATA, &k.key, 1, true))
422 return 1;
423
424 SET_KEY_SIZE(&k.key, c->sb.bucket_size);
425 uuid_io(c, REQ_WRITE, &k.key, &cl);
426 closure_sync(&cl);
427
428 bkey_copy(&c->uuid_bucket, &k.key);
429 bkey_put(c, &k.key);
430 return 0;
431 }
432
433 int bch_uuid_write(struct cache_set *c)
434 {
435 int ret = __uuid_write(c);
436
437 if (!ret)
438 bch_journal_meta(c, NULL);
439
440 return ret;
441 }
442
443 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
444 {
445 struct uuid_entry *u;
446
447 for (u = c->uuids;
448 u < c->uuids + c->nr_uuids; u++)
449 if (!memcmp(u->uuid, uuid, 16))
450 return u;
451
452 return NULL;
453 }
454
455 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
456 {
457 static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
458 return uuid_find(c, zero_uuid);
459 }
460
461 /*
462 * Bucket priorities/gens:
463 *
464 * For each bucket, we store on disk its
465 * 8 bit gen
466 * 16 bit priority
467 *
468 * See alloc.c for an explanation of the gen. The priority is used to implement
469 * lru (and in the future other) cache replacement policies; for most purposes
470 * it's just an opaque integer.
471 *
472 * The gens and the priorities don't have a whole lot to do with each other, and
473 * it's actually the gens that must be written out at specific times - it's no
474 * big deal if the priorities don't get written, if we lose them we just reuse
475 * buckets in suboptimal order.
476 *
477 * On disk they're stored in a packed array, and in as many buckets are required
478 * to fit them all. The buckets we use to store them form a list; the journal
479 * header points to the first bucket, the first bucket points to the second
480 * bucket, et cetera.
481 *
482 * This code is used by the allocation code; periodically (whenever it runs out
483 * of buckets to allocate from) the allocation code will invalidate some
484 * buckets, but it can't use those buckets until their new gens are safely on
485 * disk.
486 */
487
488 static void prio_endio(struct bio *bio, int error)
489 {
490 struct cache *ca = bio->bi_private;
491
492 cache_set_err_on(error, ca->set, "accessing priorities");
493 bch_bbio_free(bio, ca->set);
494 closure_put(&ca->prio);
495 }
496
497 static void prio_io(struct cache *ca, uint64_t bucket, unsigned long rw)
498 {
499 struct closure *cl = &ca->prio;
500 struct bio *bio = bch_bbio_alloc(ca->set);
501
502 closure_init_stack(cl);
503
504 bio->bi_sector = bucket * ca->sb.bucket_size;
505 bio->bi_bdev = ca->bdev;
506 bio->bi_rw = REQ_SYNC|REQ_META|rw;
507 bio->bi_size = bucket_bytes(ca);
508
509 bio->bi_end_io = prio_endio;
510 bio->bi_private = ca;
511 bch_bio_map(bio, ca->disk_buckets);
512
513 closure_bio_submit(bio, &ca->prio, ca);
514 closure_sync(cl);
515 }
516
517 #define buckets_free(c) "free %zu, free_inc %zu, unused %zu", \
518 fifo_used(&c->free), fifo_used(&c->free_inc), fifo_used(&c->unused)
519
520 void bch_prio_write(struct cache *ca)
521 {
522 int i;
523 struct bucket *b;
524 struct closure cl;
525
526 closure_init_stack(&cl);
527
528 lockdep_assert_held(&ca->set->bucket_lock);
529
530 for (b = ca->buckets;
531 b < ca->buckets + ca->sb.nbuckets; b++)
532 b->disk_gen = b->gen;
533
534 ca->disk_buckets->seq++;
535
536 atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
537 &ca->meta_sectors_written);
538
539 pr_debug("free %zu, free_inc %zu, unused %zu", fifo_used(&ca->free),
540 fifo_used(&ca->free_inc), fifo_used(&ca->unused));
541
542 for (i = prio_buckets(ca) - 1; i >= 0; --i) {
543 long bucket;
544 struct prio_set *p = ca->disk_buckets;
545 struct bucket_disk *d = p->data;
546 struct bucket_disk *end = d + prios_per_bucket(ca);
547
548 for (b = ca->buckets + i * prios_per_bucket(ca);
549 b < ca->buckets + ca->sb.nbuckets && d < end;
550 b++, d++) {
551 d->prio = cpu_to_le16(b->prio);
552 d->gen = b->gen;
553 }
554
555 p->next_bucket = ca->prio_buckets[i + 1];
556 p->magic = pset_magic(&ca->sb);
557 p->csum = bch_crc64(&p->magic, bucket_bytes(ca) - 8);
558
559 bucket = bch_bucket_alloc(ca, WATERMARK_PRIO, true);
560 BUG_ON(bucket == -1);
561
562 mutex_unlock(&ca->set->bucket_lock);
563 prio_io(ca, bucket, REQ_WRITE);
564 mutex_lock(&ca->set->bucket_lock);
565
566 ca->prio_buckets[i] = bucket;
567 atomic_dec_bug(&ca->buckets[bucket].pin);
568 }
569
570 mutex_unlock(&ca->set->bucket_lock);
571
572 bch_journal_meta(ca->set, &cl);
573 closure_sync(&cl);
574
575 mutex_lock(&ca->set->bucket_lock);
576
577 ca->need_save_prio = 0;
578
579 /*
580 * Don't want the old priorities to get garbage collected until after we
581 * finish writing the new ones, and they're journalled
582 */
583 for (i = 0; i < prio_buckets(ca); i++)
584 ca->prio_last_buckets[i] = ca->prio_buckets[i];
585 }
586
587 static void prio_read(struct cache *ca, uint64_t bucket)
588 {
589 struct prio_set *p = ca->disk_buckets;
590 struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
591 struct bucket *b;
592 unsigned bucket_nr = 0;
593
594 for (b = ca->buckets;
595 b < ca->buckets + ca->sb.nbuckets;
596 b++, d++) {
597 if (d == end) {
598 ca->prio_buckets[bucket_nr] = bucket;
599 ca->prio_last_buckets[bucket_nr] = bucket;
600 bucket_nr++;
601
602 prio_io(ca, bucket, READ_SYNC);
603
604 if (p->csum != bch_crc64(&p->magic, bucket_bytes(ca) - 8))
605 pr_warn("bad csum reading priorities");
606
607 if (p->magic != pset_magic(&ca->sb))
608 pr_warn("bad magic reading priorities");
609
610 bucket = p->next_bucket;
611 d = p->data;
612 }
613
614 b->prio = le16_to_cpu(d->prio);
615 b->gen = b->disk_gen = b->last_gc = b->gc_gen = d->gen;
616 }
617 }
618
619 /* Bcache device */
620
621 static int open_dev(struct block_device *b, fmode_t mode)
622 {
623 struct bcache_device *d = b->bd_disk->private_data;
624 if (atomic_read(&d->closing))
625 return -ENXIO;
626
627 closure_get(&d->cl);
628 return 0;
629 }
630
631 static void release_dev(struct gendisk *b, fmode_t mode)
632 {
633 struct bcache_device *d = b->private_data;
634 closure_put(&d->cl);
635 }
636
637 static int ioctl_dev(struct block_device *b, fmode_t mode,
638 unsigned int cmd, unsigned long arg)
639 {
640 struct bcache_device *d = b->bd_disk->private_data;
641 return d->ioctl(d, mode, cmd, arg);
642 }
643
644 static const struct block_device_operations bcache_ops = {
645 .open = open_dev,
646 .release = release_dev,
647 .ioctl = ioctl_dev,
648 .owner = THIS_MODULE,
649 };
650
651 void bcache_device_stop(struct bcache_device *d)
652 {
653 if (!atomic_xchg(&d->closing, 1))
654 closure_queue(&d->cl);
655 }
656
657 static void bcache_device_unlink(struct bcache_device *d)
658 {
659 unsigned i;
660 struct cache *ca;
661
662 sysfs_remove_link(&d->c->kobj, d->name);
663 sysfs_remove_link(&d->kobj, "cache");
664
665 for_each_cache(ca, d->c, i)
666 bd_unlink_disk_holder(ca->bdev, d->disk);
667 }
668
669 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
670 const char *name)
671 {
672 unsigned i;
673 struct cache *ca;
674
675 for_each_cache(ca, d->c, i)
676 bd_link_disk_holder(ca->bdev, d->disk);
677
678 snprintf(d->name, BCACHEDEVNAME_SIZE,
679 "%s%u", name, d->id);
680
681 WARN(sysfs_create_link(&d->kobj, &c->kobj, "cache") ||
682 sysfs_create_link(&c->kobj, &d->kobj, d->name),
683 "Couldn't create device <-> cache set symlinks");
684 }
685
686 static void bcache_device_detach(struct bcache_device *d)
687 {
688 lockdep_assert_held(&bch_register_lock);
689
690 if (atomic_read(&d->detaching)) {
691 struct uuid_entry *u = d->c->uuids + d->id;
692
693 SET_UUID_FLASH_ONLY(u, 0);
694 memcpy(u->uuid, invalid_uuid, 16);
695 u->invalidated = cpu_to_le32(get_seconds());
696 bch_uuid_write(d->c);
697
698 atomic_set(&d->detaching, 0);
699 }
700
701 if (!d->flush_done)
702 bcache_device_unlink(d);
703
704 d->c->devices[d->id] = NULL;
705 closure_put(&d->c->caching);
706 d->c = NULL;
707 }
708
709 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
710 unsigned id)
711 {
712 BUG_ON(test_bit(CACHE_SET_STOPPING, &c->flags));
713
714 d->id = id;
715 d->c = c;
716 c->devices[id] = d;
717
718 closure_get(&c->caching);
719 }
720
721 static void bcache_device_free(struct bcache_device *d)
722 {
723 lockdep_assert_held(&bch_register_lock);
724
725 pr_info("%s stopped", d->disk->disk_name);
726
727 if (d->c)
728 bcache_device_detach(d);
729 if (d->disk && d->disk->flags & GENHD_FL_UP)
730 del_gendisk(d->disk);
731 if (d->disk && d->disk->queue)
732 blk_cleanup_queue(d->disk->queue);
733 if (d->disk)
734 put_disk(d->disk);
735
736 bio_split_pool_free(&d->bio_split_hook);
737 if (d->unaligned_bvec)
738 mempool_destroy(d->unaligned_bvec);
739 if (d->bio_split)
740 bioset_free(d->bio_split);
741 if (is_vmalloc_addr(d->full_dirty_stripes))
742 vfree(d->full_dirty_stripes);
743 else
744 kfree(d->full_dirty_stripes);
745 if (is_vmalloc_addr(d->stripe_sectors_dirty))
746 vfree(d->stripe_sectors_dirty);
747 else
748 kfree(d->stripe_sectors_dirty);
749
750 closure_debug_destroy(&d->cl);
751 }
752
753 static int bcache_device_init(struct bcache_device *d, unsigned block_size,
754 sector_t sectors)
755 {
756 struct request_queue *q;
757 size_t n;
758
759 if (!d->stripe_size)
760 d->stripe_size = 1 << 31;
761
762 d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
763
764 if (!d->nr_stripes ||
765 d->nr_stripes > INT_MAX ||
766 d->nr_stripes > SIZE_MAX / sizeof(atomic_t)) {
767 pr_err("nr_stripes too large");
768 return -ENOMEM;
769 }
770
771 n = d->nr_stripes * sizeof(atomic_t);
772 d->stripe_sectors_dirty = n < PAGE_SIZE << 6
773 ? kzalloc(n, GFP_KERNEL)
774 : vzalloc(n);
775 if (!d->stripe_sectors_dirty)
776 return -ENOMEM;
777
778 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
779 d->full_dirty_stripes = n < PAGE_SIZE << 6
780 ? kzalloc(n, GFP_KERNEL)
781 : vzalloc(n);
782 if (!d->full_dirty_stripes)
783 return -ENOMEM;
784
785 if (!(d->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
786 !(d->unaligned_bvec = mempool_create_kmalloc_pool(1,
787 sizeof(struct bio_vec) * BIO_MAX_PAGES)) ||
788 bio_split_pool_init(&d->bio_split_hook) ||
789 !(d->disk = alloc_disk(1)) ||
790 !(q = blk_alloc_queue(GFP_KERNEL)))
791 return -ENOMEM;
792
793 set_capacity(d->disk, sectors);
794 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", bcache_minor);
795
796 d->disk->major = bcache_major;
797 d->disk->first_minor = bcache_minor++;
798 d->disk->fops = &bcache_ops;
799 d->disk->private_data = d;
800
801 blk_queue_make_request(q, NULL);
802 d->disk->queue = q;
803 q->queuedata = d;
804 q->backing_dev_info.congested_data = d;
805 q->limits.max_hw_sectors = UINT_MAX;
806 q->limits.max_sectors = UINT_MAX;
807 q->limits.max_segment_size = UINT_MAX;
808 q->limits.max_segments = BIO_MAX_PAGES;
809 q->limits.max_discard_sectors = UINT_MAX;
810 q->limits.io_min = block_size;
811 q->limits.logical_block_size = block_size;
812 q->limits.physical_block_size = block_size;
813 set_bit(QUEUE_FLAG_NONROT, &d->disk->queue->queue_flags);
814 set_bit(QUEUE_FLAG_DISCARD, &d->disk->queue->queue_flags);
815
816 blk_queue_flush(q, REQ_FLUSH|REQ_FUA);
817
818 return 0;
819 }
820
821 /* Cached device */
822
823 static void calc_cached_dev_sectors(struct cache_set *c)
824 {
825 uint64_t sectors = 0;
826 struct cached_dev *dc;
827
828 list_for_each_entry(dc, &c->cached_devs, list)
829 sectors += bdev_sectors(dc->bdev);
830
831 c->cached_dev_sectors = sectors;
832 }
833
834 void bch_cached_dev_run(struct cached_dev *dc)
835 {
836 struct bcache_device *d = &dc->disk;
837 char buf[SB_LABEL_SIZE + 1];
838 char *env[] = {
839 "DRIVER=bcache",
840 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
841 NULL,
842 NULL,
843 };
844
845 memcpy(buf, dc->sb.label, SB_LABEL_SIZE);
846 buf[SB_LABEL_SIZE] = '\0';
847 env[2] = kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf);
848
849 if (atomic_xchg(&dc->running, 1))
850 return;
851
852 if (!d->c &&
853 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
854 struct closure cl;
855 closure_init_stack(&cl);
856
857 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
858 bch_write_bdev_super(dc, &cl);
859 closure_sync(&cl);
860 }
861
862 add_disk(d->disk);
863 bd_link_disk_holder(dc->bdev, dc->disk.disk);
864 /* won't show up in the uevent file, use udevadm monitor -e instead
865 * only class / kset properties are persistent */
866 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
867 kfree(env[1]);
868 kfree(env[2]);
869
870 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
871 sysfs_create_link(&disk_to_dev(d->disk)->kobj, &d->kobj, "bcache"))
872 pr_debug("error creating sysfs link");
873 }
874
875 static void cached_dev_detach_finish(struct work_struct *w)
876 {
877 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
878 char buf[BDEVNAME_SIZE];
879 struct closure cl;
880 closure_init_stack(&cl);
881
882 BUG_ON(!atomic_read(&dc->disk.detaching));
883 BUG_ON(atomic_read(&dc->count));
884
885 mutex_lock(&bch_register_lock);
886
887 memset(&dc->sb.set_uuid, 0, 16);
888 SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
889
890 bch_write_bdev_super(dc, &cl);
891 closure_sync(&cl);
892
893 bcache_device_detach(&dc->disk);
894 list_move(&dc->list, &uncached_devices);
895
896 mutex_unlock(&bch_register_lock);
897
898 pr_info("Caching disabled for %s", bdevname(dc->bdev, buf));
899
900 /* Drop ref we took in cached_dev_detach() */
901 closure_put(&dc->disk.cl);
902 }
903
904 void bch_cached_dev_detach(struct cached_dev *dc)
905 {
906 lockdep_assert_held(&bch_register_lock);
907
908 if (atomic_read(&dc->disk.closing))
909 return;
910
911 if (atomic_xchg(&dc->disk.detaching, 1))
912 return;
913
914 /*
915 * Block the device from being closed and freed until we're finished
916 * detaching
917 */
918 closure_get(&dc->disk.cl);
919
920 bch_writeback_queue(dc);
921 cached_dev_put(dc);
922 }
923
924 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c)
925 {
926 uint32_t rtime = cpu_to_le32(get_seconds());
927 struct uuid_entry *u;
928 char buf[BDEVNAME_SIZE];
929
930 bdevname(dc->bdev, buf);
931
932 if (memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16))
933 return -ENOENT;
934
935 if (dc->disk.c) {
936 pr_err("Can't attach %s: already attached", buf);
937 return -EINVAL;
938 }
939
940 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
941 pr_err("Can't attach %s: shutting down", buf);
942 return -EINVAL;
943 }
944
945 if (dc->sb.block_size < c->sb.block_size) {
946 /* Will die */
947 pr_err("Couldn't attach %s: block size less than set's block size",
948 buf);
949 return -EINVAL;
950 }
951
952 u = uuid_find(c, dc->sb.uuid);
953
954 if (u &&
955 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
956 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
957 memcpy(u->uuid, invalid_uuid, 16);
958 u->invalidated = cpu_to_le32(get_seconds());
959 u = NULL;
960 }
961
962 if (!u) {
963 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
964 pr_err("Couldn't find uuid for %s in set", buf);
965 return -ENOENT;
966 }
967
968 u = uuid_find_empty(c);
969 if (!u) {
970 pr_err("Not caching %s, no room for UUID", buf);
971 return -EINVAL;
972 }
973 }
974
975 /* Deadlocks since we're called via sysfs...
976 sysfs_remove_file(&dc->kobj, &sysfs_attach);
977 */
978
979 if (bch_is_zero(u->uuid, 16)) {
980 struct closure cl;
981 closure_init_stack(&cl);
982
983 memcpy(u->uuid, dc->sb.uuid, 16);
984 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
985 u->first_reg = u->last_reg = rtime;
986 bch_uuid_write(c);
987
988 memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
989 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
990
991 bch_write_bdev_super(dc, &cl);
992 closure_sync(&cl);
993 } else {
994 u->last_reg = rtime;
995 bch_uuid_write(c);
996 }
997
998 bcache_device_attach(&dc->disk, c, u - c->uuids);
999 list_move(&dc->list, &c->cached_devs);
1000 calc_cached_dev_sectors(c);
1001
1002 smp_wmb();
1003 /*
1004 * dc->c must be set before dc->count != 0 - paired with the mb in
1005 * cached_dev_get()
1006 */
1007 atomic_set(&dc->count, 1);
1008
1009 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1010 bch_sectors_dirty_init(dc);
1011 atomic_set(&dc->has_dirty, 1);
1012 atomic_inc(&dc->count);
1013 bch_writeback_queue(dc);
1014 }
1015
1016 bch_cached_dev_run(dc);
1017 bcache_device_link(&dc->disk, c, "bdev");
1018
1019 pr_info("Caching %s as %s on set %pU",
1020 bdevname(dc->bdev, buf), dc->disk.disk->disk_name,
1021 dc->disk.c->sb.set_uuid);
1022 return 0;
1023 }
1024
1025 void bch_cached_dev_release(struct kobject *kobj)
1026 {
1027 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1028 disk.kobj);
1029 kfree(dc);
1030 module_put(THIS_MODULE);
1031 }
1032
1033 static void cached_dev_free(struct closure *cl)
1034 {
1035 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1036
1037 cancel_delayed_work_sync(&dc->writeback_rate_update);
1038 kthread_stop(dc->writeback_thread);
1039
1040 mutex_lock(&bch_register_lock);
1041
1042 if (atomic_read(&dc->running))
1043 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1044 bcache_device_free(&dc->disk);
1045 list_del(&dc->list);
1046
1047 mutex_unlock(&bch_register_lock);
1048
1049 if (!IS_ERR_OR_NULL(dc->bdev)) {
1050 if (dc->bdev->bd_disk)
1051 blk_sync_queue(bdev_get_queue(dc->bdev));
1052
1053 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1054 }
1055
1056 wake_up(&unregister_wait);
1057
1058 kobject_put(&dc->disk.kobj);
1059 }
1060
1061 static void cached_dev_flush(struct closure *cl)
1062 {
1063 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1064 struct bcache_device *d = &dc->disk;
1065
1066 mutex_lock(&bch_register_lock);
1067 d->flush_done = 1;
1068
1069 if (d->c)
1070 bcache_device_unlink(d);
1071
1072 mutex_unlock(&bch_register_lock);
1073
1074 bch_cache_accounting_destroy(&dc->accounting);
1075 kobject_del(&d->kobj);
1076
1077 continue_at(cl, cached_dev_free, system_wq);
1078 }
1079
1080 static int cached_dev_init(struct cached_dev *dc, unsigned block_size)
1081 {
1082 int ret;
1083 struct io *io;
1084 struct request_queue *q = bdev_get_queue(dc->bdev);
1085
1086 __module_get(THIS_MODULE);
1087 INIT_LIST_HEAD(&dc->list);
1088 closure_init(&dc->disk.cl, NULL);
1089 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1090 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1091 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1092 closure_init_unlocked(&dc->sb_write);
1093 INIT_LIST_HEAD(&dc->io_lru);
1094 spin_lock_init(&dc->io_lock);
1095 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1096
1097 dc->sequential_cutoff = 4 << 20;
1098
1099 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1100 list_add(&io->lru, &dc->io_lru);
1101 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1102 }
1103
1104 ret = bcache_device_init(&dc->disk, block_size,
1105 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1106 if (ret)
1107 return ret;
1108
1109 set_capacity(dc->disk.disk,
1110 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1111
1112 dc->disk.disk->queue->backing_dev_info.ra_pages =
1113 max(dc->disk.disk->queue->backing_dev_info.ra_pages,
1114 q->backing_dev_info.ra_pages);
1115
1116 bch_cached_dev_request_init(dc);
1117 bch_cached_dev_writeback_init(dc);
1118 return 0;
1119 }
1120
1121 /* Cached device - bcache superblock */
1122
1123 static void register_bdev(struct cache_sb *sb, struct page *sb_page,
1124 struct block_device *bdev,
1125 struct cached_dev *dc)
1126 {
1127 char name[BDEVNAME_SIZE];
1128 const char *err = "cannot allocate memory";
1129 struct cache_set *c;
1130
1131 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1132 dc->bdev = bdev;
1133 dc->bdev->bd_holder = dc;
1134
1135 bio_init(&dc->sb_bio);
1136 dc->sb_bio.bi_max_vecs = 1;
1137 dc->sb_bio.bi_io_vec = dc->sb_bio.bi_inline_vecs;
1138 dc->sb_bio.bi_io_vec[0].bv_page = sb_page;
1139 get_page(sb_page);
1140
1141 if (cached_dev_init(dc, sb->block_size << 9))
1142 goto err;
1143
1144 err = "error creating kobject";
1145 if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1146 "bcache"))
1147 goto err;
1148 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1149 goto err;
1150
1151 pr_info("registered backing device %s", bdevname(bdev, name));
1152
1153 list_add(&dc->list, &uncached_devices);
1154 list_for_each_entry(c, &bch_cache_sets, list)
1155 bch_cached_dev_attach(dc, c);
1156
1157 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1158 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE)
1159 bch_cached_dev_run(dc);
1160
1161 return;
1162 err:
1163 pr_notice("error opening %s: %s", bdevname(bdev, name), err);
1164 bcache_device_stop(&dc->disk);
1165 }
1166
1167 /* Flash only volumes */
1168
1169 void bch_flash_dev_release(struct kobject *kobj)
1170 {
1171 struct bcache_device *d = container_of(kobj, struct bcache_device,
1172 kobj);
1173 kfree(d);
1174 }
1175
1176 static void flash_dev_free(struct closure *cl)
1177 {
1178 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1179 bcache_device_free(d);
1180 kobject_put(&d->kobj);
1181 }
1182
1183 static void flash_dev_flush(struct closure *cl)
1184 {
1185 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1186
1187 bcache_device_unlink(d);
1188 kobject_del(&d->kobj);
1189 continue_at(cl, flash_dev_free, system_wq);
1190 }
1191
1192 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1193 {
1194 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1195 GFP_KERNEL);
1196 if (!d)
1197 return -ENOMEM;
1198
1199 closure_init(&d->cl, NULL);
1200 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1201
1202 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1203
1204 if (bcache_device_init(d, block_bytes(c), u->sectors))
1205 goto err;
1206
1207 bcache_device_attach(d, c, u - c->uuids);
1208 bch_flash_dev_request_init(d);
1209 add_disk(d->disk);
1210
1211 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1212 goto err;
1213
1214 bcache_device_link(d, c, "volume");
1215
1216 return 0;
1217 err:
1218 kobject_put(&d->kobj);
1219 return -ENOMEM;
1220 }
1221
1222 static int flash_devs_run(struct cache_set *c)
1223 {
1224 int ret = 0;
1225 struct uuid_entry *u;
1226
1227 for (u = c->uuids;
1228 u < c->uuids + c->nr_uuids && !ret;
1229 u++)
1230 if (UUID_FLASH_ONLY(u))
1231 ret = flash_dev_run(c, u);
1232
1233 return ret;
1234 }
1235
1236 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1237 {
1238 struct uuid_entry *u;
1239
1240 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1241 return -EINTR;
1242
1243 u = uuid_find_empty(c);
1244 if (!u) {
1245 pr_err("Can't create volume, no room for UUID");
1246 return -EINVAL;
1247 }
1248
1249 get_random_bytes(u->uuid, 16);
1250 memset(u->label, 0, 32);
1251 u->first_reg = u->last_reg = cpu_to_le32(get_seconds());
1252
1253 SET_UUID_FLASH_ONLY(u, 1);
1254 u->sectors = size >> 9;
1255
1256 bch_uuid_write(c);
1257
1258 return flash_dev_run(c, u);
1259 }
1260
1261 /* Cache set */
1262
1263 __printf(2, 3)
1264 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1265 {
1266 va_list args;
1267
1268 if (c->on_error != ON_ERROR_PANIC &&
1269 test_bit(CACHE_SET_STOPPING, &c->flags))
1270 return false;
1271
1272 /* XXX: we can be called from atomic context
1273 acquire_console_sem();
1274 */
1275
1276 printk(KERN_ERR "bcache: error on %pU: ", c->sb.set_uuid);
1277
1278 va_start(args, fmt);
1279 vprintk(fmt, args);
1280 va_end(args);
1281
1282 printk(", disabling caching\n");
1283
1284 if (c->on_error == ON_ERROR_PANIC)
1285 panic("panic forced after error\n");
1286
1287 bch_cache_set_unregister(c);
1288 return true;
1289 }
1290
1291 void bch_cache_set_release(struct kobject *kobj)
1292 {
1293 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1294 kfree(c);
1295 module_put(THIS_MODULE);
1296 }
1297
1298 static void cache_set_free(struct closure *cl)
1299 {
1300 struct cache_set *c = container_of(cl, struct cache_set, cl);
1301 struct cache *ca;
1302 unsigned i;
1303
1304 if (!IS_ERR_OR_NULL(c->debug))
1305 debugfs_remove(c->debug);
1306
1307 bch_open_buckets_free(c);
1308 bch_btree_cache_free(c);
1309 bch_journal_free(c);
1310
1311 for_each_cache(ca, c, i)
1312 if (ca)
1313 kobject_put(&ca->kobj);
1314
1315 free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1316 free_pages((unsigned long) c->sort, ilog2(bucket_pages(c)));
1317
1318 if (c->bio_split)
1319 bioset_free(c->bio_split);
1320 if (c->fill_iter)
1321 mempool_destroy(c->fill_iter);
1322 if (c->bio_meta)
1323 mempool_destroy(c->bio_meta);
1324 if (c->search)
1325 mempool_destroy(c->search);
1326 kfree(c->devices);
1327
1328 mutex_lock(&bch_register_lock);
1329 list_del(&c->list);
1330 mutex_unlock(&bch_register_lock);
1331
1332 pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1333 wake_up(&unregister_wait);
1334
1335 closure_debug_destroy(&c->cl);
1336 kobject_put(&c->kobj);
1337 }
1338
1339 static void cache_set_flush(struct closure *cl)
1340 {
1341 struct cache_set *c = container_of(cl, struct cache_set, caching);
1342 struct cache *ca;
1343 struct btree *b;
1344 unsigned i;
1345
1346 bch_cache_accounting_destroy(&c->accounting);
1347
1348 kobject_put(&c->internal);
1349 kobject_del(&c->kobj);
1350
1351 if (c->gc_thread)
1352 kthread_stop(c->gc_thread);
1353
1354 if (!IS_ERR_OR_NULL(c->root))
1355 list_add(&c->root->list, &c->btree_cache);
1356
1357 /* Should skip this if we're unregistering because of an error */
1358 list_for_each_entry(b, &c->btree_cache, list)
1359 if (btree_node_dirty(b))
1360 bch_btree_node_write(b, NULL);
1361
1362 for_each_cache(ca, c, i)
1363 if (ca->alloc_thread)
1364 kthread_stop(ca->alloc_thread);
1365
1366 closure_return(cl);
1367 }
1368
1369 static void __cache_set_unregister(struct closure *cl)
1370 {
1371 struct cache_set *c = container_of(cl, struct cache_set, caching);
1372 struct cached_dev *dc;
1373 size_t i;
1374
1375 mutex_lock(&bch_register_lock);
1376
1377 for (i = 0; i < c->nr_uuids; i++)
1378 if (c->devices[i]) {
1379 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1380 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1381 dc = container_of(c->devices[i],
1382 struct cached_dev, disk);
1383 bch_cached_dev_detach(dc);
1384 } else {
1385 bcache_device_stop(c->devices[i]);
1386 }
1387 }
1388
1389 mutex_unlock(&bch_register_lock);
1390
1391 continue_at(cl, cache_set_flush, system_wq);
1392 }
1393
1394 void bch_cache_set_stop(struct cache_set *c)
1395 {
1396 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1397 closure_queue(&c->caching);
1398 }
1399
1400 void bch_cache_set_unregister(struct cache_set *c)
1401 {
1402 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1403 bch_cache_set_stop(c);
1404 }
1405
1406 #define alloc_bucket_pages(gfp, c) \
1407 ((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1408
1409 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1410 {
1411 int iter_size;
1412 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1413 if (!c)
1414 return NULL;
1415
1416 __module_get(THIS_MODULE);
1417 closure_init(&c->cl, NULL);
1418 set_closure_fn(&c->cl, cache_set_free, system_wq);
1419
1420 closure_init(&c->caching, &c->cl);
1421 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1422
1423 /* Maybe create continue_at_noreturn() and use it here? */
1424 closure_set_stopped(&c->cl);
1425 closure_put(&c->cl);
1426
1427 kobject_init(&c->kobj, &bch_cache_set_ktype);
1428 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1429
1430 bch_cache_accounting_init(&c->accounting, &c->cl);
1431
1432 memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1433 c->sb.block_size = sb->block_size;
1434 c->sb.bucket_size = sb->bucket_size;
1435 c->sb.nr_in_set = sb->nr_in_set;
1436 c->sb.last_mount = sb->last_mount;
1437 c->bucket_bits = ilog2(sb->bucket_size);
1438 c->block_bits = ilog2(sb->block_size);
1439 c->nr_uuids = bucket_bytes(c) / sizeof(struct uuid_entry);
1440
1441 c->btree_pages = c->sb.bucket_size / PAGE_SECTORS;
1442 if (c->btree_pages > BTREE_MAX_PAGES)
1443 c->btree_pages = max_t(int, c->btree_pages / 4,
1444 BTREE_MAX_PAGES);
1445
1446 c->sort_crit_factor = int_sqrt(c->btree_pages);
1447
1448 closure_init_unlocked(&c->sb_write);
1449 mutex_init(&c->bucket_lock);
1450 init_waitqueue_head(&c->try_wait);
1451 init_waitqueue_head(&c->bucket_wait);
1452 closure_init_unlocked(&c->uuid_write);
1453 mutex_init(&c->sort_lock);
1454
1455 spin_lock_init(&c->sort_time.lock);
1456 spin_lock_init(&c->btree_gc_time.lock);
1457 spin_lock_init(&c->btree_split_time.lock);
1458 spin_lock_init(&c->btree_read_time.lock);
1459 spin_lock_init(&c->try_harder_time.lock);
1460
1461 bch_moving_init_cache_set(c);
1462
1463 INIT_LIST_HEAD(&c->list);
1464 INIT_LIST_HEAD(&c->cached_devs);
1465 INIT_LIST_HEAD(&c->btree_cache);
1466 INIT_LIST_HEAD(&c->btree_cache_freeable);
1467 INIT_LIST_HEAD(&c->btree_cache_freed);
1468 INIT_LIST_HEAD(&c->data_buckets);
1469
1470 c->search = mempool_create_slab_pool(32, bch_search_cache);
1471 if (!c->search)
1472 goto err;
1473
1474 iter_size = (sb->bucket_size / sb->block_size + 1) *
1475 sizeof(struct btree_iter_set);
1476
1477 if (!(c->devices = kzalloc(c->nr_uuids * sizeof(void *), GFP_KERNEL)) ||
1478 !(c->bio_meta = mempool_create_kmalloc_pool(2,
1479 sizeof(struct bbio) + sizeof(struct bio_vec) *
1480 bucket_pages(c))) ||
1481 !(c->fill_iter = mempool_create_kmalloc_pool(1, iter_size)) ||
1482 !(c->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
1483 !(c->sort = alloc_bucket_pages(GFP_KERNEL, c)) ||
1484 !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1485 bch_journal_alloc(c) ||
1486 bch_btree_cache_alloc(c) ||
1487 bch_open_buckets_alloc(c))
1488 goto err;
1489
1490 c->congested_read_threshold_us = 2000;
1491 c->congested_write_threshold_us = 20000;
1492 c->error_limit = 8 << IO_ERROR_SHIFT;
1493
1494 return c;
1495 err:
1496 bch_cache_set_unregister(c);
1497 return NULL;
1498 }
1499
1500 static void run_cache_set(struct cache_set *c)
1501 {
1502 const char *err = "cannot allocate memory";
1503 struct cached_dev *dc, *t;
1504 struct cache *ca;
1505 struct closure cl;
1506 unsigned i;
1507
1508 closure_init_stack(&cl);
1509
1510 for_each_cache(ca, c, i)
1511 c->nbuckets += ca->sb.nbuckets;
1512
1513 if (CACHE_SYNC(&c->sb)) {
1514 LIST_HEAD(journal);
1515 struct bkey *k;
1516 struct jset *j;
1517
1518 err = "cannot allocate memory for journal";
1519 if (bch_journal_read(c, &journal))
1520 goto err;
1521
1522 pr_debug("btree_journal_read() done");
1523
1524 err = "no journal entries found";
1525 if (list_empty(&journal))
1526 goto err;
1527
1528 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1529
1530 err = "IO error reading priorities";
1531 for_each_cache(ca, c, i)
1532 prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1533
1534 /*
1535 * If prio_read() fails it'll call cache_set_error and we'll
1536 * tear everything down right away, but if we perhaps checked
1537 * sooner we could avoid journal replay.
1538 */
1539
1540 k = &j->btree_root;
1541
1542 err = "bad btree root";
1543 if (bch_btree_ptr_invalid(c, k))
1544 goto err;
1545
1546 err = "error reading btree root";
1547 c->root = bch_btree_node_get(c, k, j->btree_level, true);
1548 if (IS_ERR_OR_NULL(c->root))
1549 goto err;
1550
1551 list_del_init(&c->root->list);
1552 rw_unlock(true, c->root);
1553
1554 err = uuid_read(c, j, &cl);
1555 if (err)
1556 goto err;
1557
1558 err = "error in recovery";
1559 if (bch_btree_check(c))
1560 goto err;
1561
1562 bch_journal_mark(c, &journal);
1563 bch_btree_gc_finish(c);
1564 pr_debug("btree_check() done");
1565
1566 /*
1567 * bcache_journal_next() can't happen sooner, or
1568 * btree_gc_finish() will give spurious errors about last_gc >
1569 * gc_gen - this is a hack but oh well.
1570 */
1571 bch_journal_next(&c->journal);
1572
1573 err = "error starting allocator thread";
1574 for_each_cache(ca, c, i)
1575 if (bch_cache_allocator_start(ca))
1576 goto err;
1577
1578 /*
1579 * First place it's safe to allocate: btree_check() and
1580 * btree_gc_finish() have to run before we have buckets to
1581 * allocate, and bch_bucket_alloc_set() might cause a journal
1582 * entry to be written so bcache_journal_next() has to be called
1583 * first.
1584 *
1585 * If the uuids were in the old format we have to rewrite them
1586 * before the next journal entry is written:
1587 */
1588 if (j->version < BCACHE_JSET_VERSION_UUID)
1589 __uuid_write(c);
1590
1591 bch_journal_replay(c, &journal);
1592 } else {
1593 pr_notice("invalidating existing data");
1594
1595 for_each_cache(ca, c, i) {
1596 unsigned j;
1597
1598 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1599 2, SB_JOURNAL_BUCKETS);
1600
1601 for (j = 0; j < ca->sb.keys; j++)
1602 ca->sb.d[j] = ca->sb.first_bucket + j;
1603 }
1604
1605 bch_btree_gc_finish(c);
1606
1607 err = "error starting allocator thread";
1608 for_each_cache(ca, c, i)
1609 if (bch_cache_allocator_start(ca))
1610 goto err;
1611
1612 mutex_lock(&c->bucket_lock);
1613 for_each_cache(ca, c, i)
1614 bch_prio_write(ca);
1615 mutex_unlock(&c->bucket_lock);
1616
1617 err = "cannot allocate new UUID bucket";
1618 if (__uuid_write(c))
1619 goto err;
1620
1621 err = "cannot allocate new btree root";
1622 c->root = bch_btree_node_alloc(c, 0, true);
1623 if (IS_ERR_OR_NULL(c->root))
1624 goto err;
1625
1626 bkey_copy_key(&c->root->key, &MAX_KEY);
1627 bch_btree_node_write(c->root, &cl);
1628
1629 bch_btree_set_root(c->root);
1630 rw_unlock(true, c->root);
1631
1632 /*
1633 * We don't want to write the first journal entry until
1634 * everything is set up - fortunately journal entries won't be
1635 * written until the SET_CACHE_SYNC() here:
1636 */
1637 SET_CACHE_SYNC(&c->sb, true);
1638
1639 bch_journal_next(&c->journal);
1640 bch_journal_meta(c, &cl);
1641 }
1642
1643 err = "error starting gc thread";
1644 if (bch_gc_thread_start(c))
1645 goto err;
1646
1647 closure_sync(&cl);
1648 c->sb.last_mount = get_seconds();
1649 bcache_write_super(c);
1650
1651 list_for_each_entry_safe(dc, t, &uncached_devices, list)
1652 bch_cached_dev_attach(dc, c);
1653
1654 flash_devs_run(c);
1655
1656 return;
1657 err:
1658 closure_sync(&cl);
1659 /* XXX: test this, it's broken */
1660 bch_cache_set_error(c, err);
1661 }
1662
1663 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
1664 {
1665 return ca->sb.block_size == c->sb.block_size &&
1666 ca->sb.bucket_size == c->sb.block_size &&
1667 ca->sb.nr_in_set == c->sb.nr_in_set;
1668 }
1669
1670 static const char *register_cache_set(struct cache *ca)
1671 {
1672 char buf[12];
1673 const char *err = "cannot allocate memory";
1674 struct cache_set *c;
1675
1676 list_for_each_entry(c, &bch_cache_sets, list)
1677 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
1678 if (c->cache[ca->sb.nr_this_dev])
1679 return "duplicate cache set member";
1680
1681 if (!can_attach_cache(ca, c))
1682 return "cache sb does not match set";
1683
1684 if (!CACHE_SYNC(&ca->sb))
1685 SET_CACHE_SYNC(&c->sb, false);
1686
1687 goto found;
1688 }
1689
1690 c = bch_cache_set_alloc(&ca->sb);
1691 if (!c)
1692 return err;
1693
1694 err = "error creating kobject";
1695 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
1696 kobject_add(&c->internal, &c->kobj, "internal"))
1697 goto err;
1698
1699 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
1700 goto err;
1701
1702 bch_debug_init_cache_set(c);
1703
1704 list_add(&c->list, &bch_cache_sets);
1705 found:
1706 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
1707 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
1708 sysfs_create_link(&c->kobj, &ca->kobj, buf))
1709 goto err;
1710
1711 if (ca->sb.seq > c->sb.seq) {
1712 c->sb.version = ca->sb.version;
1713 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
1714 c->sb.flags = ca->sb.flags;
1715 c->sb.seq = ca->sb.seq;
1716 pr_debug("set version = %llu", c->sb.version);
1717 }
1718
1719 ca->set = c;
1720 ca->set->cache[ca->sb.nr_this_dev] = ca;
1721 c->cache_by_alloc[c->caches_loaded++] = ca;
1722
1723 if (c->caches_loaded == c->sb.nr_in_set)
1724 run_cache_set(c);
1725
1726 return NULL;
1727 err:
1728 bch_cache_set_unregister(c);
1729 return err;
1730 }
1731
1732 /* Cache device */
1733
1734 void bch_cache_release(struct kobject *kobj)
1735 {
1736 struct cache *ca = container_of(kobj, struct cache, kobj);
1737
1738 if (ca->set)
1739 ca->set->cache[ca->sb.nr_this_dev] = NULL;
1740
1741 bio_split_pool_free(&ca->bio_split_hook);
1742
1743 free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
1744 kfree(ca->prio_buckets);
1745 vfree(ca->buckets);
1746
1747 free_heap(&ca->heap);
1748 free_fifo(&ca->unused);
1749 free_fifo(&ca->free_inc);
1750 free_fifo(&ca->free);
1751
1752 if (ca->sb_bio.bi_inline_vecs[0].bv_page)
1753 put_page(ca->sb_bio.bi_io_vec[0].bv_page);
1754
1755 if (!IS_ERR_OR_NULL(ca->bdev)) {
1756 blk_sync_queue(bdev_get_queue(ca->bdev));
1757 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1758 }
1759
1760 kfree(ca);
1761 module_put(THIS_MODULE);
1762 }
1763
1764 static int cache_alloc(struct cache_sb *sb, struct cache *ca)
1765 {
1766 size_t free;
1767 struct bucket *b;
1768
1769 __module_get(THIS_MODULE);
1770 kobject_init(&ca->kobj, &bch_cache_ktype);
1771
1772 bio_init(&ca->journal.bio);
1773 ca->journal.bio.bi_max_vecs = 8;
1774 ca->journal.bio.bi_io_vec = ca->journal.bio.bi_inline_vecs;
1775
1776 free = roundup_pow_of_two(ca->sb.nbuckets) >> 9;
1777 free = max_t(size_t, free, (prio_buckets(ca) + 8) * 2);
1778
1779 if (!init_fifo(&ca->free, free, GFP_KERNEL) ||
1780 !init_fifo(&ca->free_inc, free << 2, GFP_KERNEL) ||
1781 !init_fifo(&ca->unused, free << 2, GFP_KERNEL) ||
1782 !init_heap(&ca->heap, free << 3, GFP_KERNEL) ||
1783 !(ca->buckets = vzalloc(sizeof(struct bucket) *
1784 ca->sb.nbuckets)) ||
1785 !(ca->prio_buckets = kzalloc(sizeof(uint64_t) * prio_buckets(ca) *
1786 2, GFP_KERNEL)) ||
1787 !(ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca)) ||
1788 bio_split_pool_init(&ca->bio_split_hook))
1789 return -ENOMEM;
1790
1791 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
1792
1793 for_each_bucket(b, ca)
1794 atomic_set(&b->pin, 0);
1795
1796 if (bch_cache_allocator_init(ca))
1797 goto err;
1798
1799 return 0;
1800 err:
1801 kobject_put(&ca->kobj);
1802 return -ENOMEM;
1803 }
1804
1805 static void register_cache(struct cache_sb *sb, struct page *sb_page,
1806 struct block_device *bdev, struct cache *ca)
1807 {
1808 char name[BDEVNAME_SIZE];
1809 const char *err = "cannot allocate memory";
1810
1811 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
1812 ca->bdev = bdev;
1813 ca->bdev->bd_holder = ca;
1814
1815 bio_init(&ca->sb_bio);
1816 ca->sb_bio.bi_max_vecs = 1;
1817 ca->sb_bio.bi_io_vec = ca->sb_bio.bi_inline_vecs;
1818 ca->sb_bio.bi_io_vec[0].bv_page = sb_page;
1819 get_page(sb_page);
1820
1821 if (blk_queue_discard(bdev_get_queue(ca->bdev)))
1822 ca->discard = CACHE_DISCARD(&ca->sb);
1823
1824 if (cache_alloc(sb, ca) != 0)
1825 goto err;
1826
1827 err = "error creating kobject";
1828 if (kobject_add(&ca->kobj, &part_to_dev(bdev->bd_part)->kobj, "bcache"))
1829 goto err;
1830
1831 err = register_cache_set(ca);
1832 if (err)
1833 goto err;
1834
1835 pr_info("registered cache device %s", bdevname(bdev, name));
1836 return;
1837 err:
1838 pr_notice("error opening %s: %s", bdevname(bdev, name), err);
1839 kobject_put(&ca->kobj);
1840 }
1841
1842 /* Global interfaces/init */
1843
1844 static ssize_t register_bcache(struct kobject *, struct kobj_attribute *,
1845 const char *, size_t);
1846
1847 kobj_attribute_write(register, register_bcache);
1848 kobj_attribute_write(register_quiet, register_bcache);
1849
1850 static bool bch_is_open_backing(struct block_device *bdev) {
1851 struct cache_set *c, *tc;
1852 struct cached_dev *dc, *t;
1853
1854 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
1855 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
1856 if (dc->bdev == bdev)
1857 return true;
1858 list_for_each_entry_safe(dc, t, &uncached_devices, list)
1859 if (dc->bdev == bdev)
1860 return true;
1861 return false;
1862 }
1863
1864 static bool bch_is_open_cache(struct block_device *bdev) {
1865 struct cache_set *c, *tc;
1866 struct cache *ca;
1867 unsigned i;
1868
1869 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
1870 for_each_cache(ca, c, i)
1871 if (ca->bdev == bdev)
1872 return true;
1873 return false;
1874 }
1875
1876 static bool bch_is_open(struct block_device *bdev) {
1877 return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
1878 }
1879
1880 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
1881 const char *buffer, size_t size)
1882 {
1883 ssize_t ret = size;
1884 const char *err = "cannot allocate memory";
1885 char *path = NULL;
1886 struct cache_sb *sb = NULL;
1887 struct block_device *bdev = NULL;
1888 struct page *sb_page = NULL;
1889
1890 if (!try_module_get(THIS_MODULE))
1891 return -EBUSY;
1892
1893 mutex_lock(&bch_register_lock);
1894
1895 if (!(path = kstrndup(buffer, size, GFP_KERNEL)) ||
1896 !(sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL)))
1897 goto err;
1898
1899 err = "failed to open device";
1900 bdev = blkdev_get_by_path(strim(path),
1901 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
1902 sb);
1903 if (IS_ERR(bdev)) {
1904 if (bdev == ERR_PTR(-EBUSY)) {
1905 bdev = lookup_bdev(strim(path));
1906 if (!IS_ERR(bdev) && bch_is_open(bdev))
1907 err = "device already registered";
1908 else
1909 err = "device busy";
1910 }
1911 goto err;
1912 }
1913
1914 err = "failed to set blocksize";
1915 if (set_blocksize(bdev, 4096))
1916 goto err_close;
1917
1918 err = read_super(sb, bdev, &sb_page);
1919 if (err)
1920 goto err_close;
1921
1922 if (SB_IS_BDEV(sb)) {
1923 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
1924 if (!dc)
1925 goto err_close;
1926
1927 register_bdev(sb, sb_page, bdev, dc);
1928 } else {
1929 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1930 if (!ca)
1931 goto err_close;
1932
1933 register_cache(sb, sb_page, bdev, ca);
1934 }
1935 out:
1936 if (sb_page)
1937 put_page(sb_page);
1938 kfree(sb);
1939 kfree(path);
1940 mutex_unlock(&bch_register_lock);
1941 module_put(THIS_MODULE);
1942 return ret;
1943
1944 err_close:
1945 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1946 err:
1947 if (attr != &ksysfs_register_quiet)
1948 pr_info("error opening %s: %s", path, err);
1949 ret = -EINVAL;
1950 goto out;
1951 }
1952
1953 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
1954 {
1955 if (code == SYS_DOWN ||
1956 code == SYS_HALT ||
1957 code == SYS_POWER_OFF) {
1958 DEFINE_WAIT(wait);
1959 unsigned long start = jiffies;
1960 bool stopped = false;
1961
1962 struct cache_set *c, *tc;
1963 struct cached_dev *dc, *tdc;
1964
1965 mutex_lock(&bch_register_lock);
1966
1967 if (list_empty(&bch_cache_sets) &&
1968 list_empty(&uncached_devices))
1969 goto out;
1970
1971 pr_info("Stopping all devices:");
1972
1973 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
1974 bch_cache_set_stop(c);
1975
1976 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
1977 bcache_device_stop(&dc->disk);
1978
1979 /* What's a condition variable? */
1980 while (1) {
1981 long timeout = start + 2 * HZ - jiffies;
1982
1983 stopped = list_empty(&bch_cache_sets) &&
1984 list_empty(&uncached_devices);
1985
1986 if (timeout < 0 || stopped)
1987 break;
1988
1989 prepare_to_wait(&unregister_wait, &wait,
1990 TASK_UNINTERRUPTIBLE);
1991
1992 mutex_unlock(&bch_register_lock);
1993 schedule_timeout(timeout);
1994 mutex_lock(&bch_register_lock);
1995 }
1996
1997 finish_wait(&unregister_wait, &wait);
1998
1999 if (stopped)
2000 pr_info("All devices stopped");
2001 else
2002 pr_notice("Timeout waiting for devices to be closed");
2003 out:
2004 mutex_unlock(&bch_register_lock);
2005 }
2006
2007 return NOTIFY_DONE;
2008 }
2009
2010 static struct notifier_block reboot = {
2011 .notifier_call = bcache_reboot,
2012 .priority = INT_MAX, /* before any real devices */
2013 };
2014
2015 static void bcache_exit(void)
2016 {
2017 bch_debug_exit();
2018 bch_request_exit();
2019 bch_btree_exit();
2020 if (bcache_kobj)
2021 kobject_put(bcache_kobj);
2022 if (bcache_wq)
2023 destroy_workqueue(bcache_wq);
2024 unregister_blkdev(bcache_major, "bcache");
2025 unregister_reboot_notifier(&reboot);
2026 }
2027
2028 static int __init bcache_init(void)
2029 {
2030 static const struct attribute *files[] = {
2031 &ksysfs_register.attr,
2032 &ksysfs_register_quiet.attr,
2033 NULL
2034 };
2035
2036 mutex_init(&bch_register_lock);
2037 init_waitqueue_head(&unregister_wait);
2038 register_reboot_notifier(&reboot);
2039 closure_debug_init();
2040
2041 bcache_major = register_blkdev(0, "bcache");
2042 if (bcache_major < 0)
2043 return bcache_major;
2044
2045 if (!(bcache_wq = create_workqueue("bcache")) ||
2046 !(bcache_kobj = kobject_create_and_add("bcache", fs_kobj)) ||
2047 sysfs_create_files(bcache_kobj, files) ||
2048 bch_btree_init() ||
2049 bch_request_init() ||
2050 bch_debug_init(bcache_kobj))
2051 goto err;
2052
2053 return 0;
2054 err:
2055 bcache_exit();
2056 return -ENOMEM;
2057 }
2058
2059 module_exit(bcache_exit);
2060 module_init(bcache_init);