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