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