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