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