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