OSDN Git Service

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