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