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