OSDN Git Service

bcache: use a separate data structure for the on-disk super block
[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 page **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 = bh->b_page;
195 err:
196         put_bh(bh);
197         return err;
198 }
199
200 static void write_bdev_super_endio(struct bio *bio)
201 {
202         struct cached_dev *dc = bio->bi_private;
203
204         if (bio->bi_status)
205                 bch_count_backing_io_errors(dc, bio);
206
207         closure_put(&dc->sb_write);
208 }
209
210 static void __write_super(struct cache_sb *sb, struct bio *bio)
211 {
212         struct cache_sb_disk *out = page_address(bio_first_page_all(bio));
213         unsigned int i;
214
215         bio->bi_iter.bi_sector  = SB_SECTOR;
216         bio->bi_iter.bi_size    = SB_SIZE;
217         bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC|REQ_META);
218         bch_bio_map(bio, NULL);
219
220         out->offset             = cpu_to_le64(sb->offset);
221         out->version            = cpu_to_le64(sb->version);
222
223         memcpy(out->uuid,       sb->uuid, 16);
224         memcpy(out->set_uuid,   sb->set_uuid, 16);
225         memcpy(out->label,      sb->label, SB_LABEL_SIZE);
226
227         out->flags              = cpu_to_le64(sb->flags);
228         out->seq                = cpu_to_le64(sb->seq);
229
230         out->last_mount         = cpu_to_le32(sb->last_mount);
231         out->first_bucket       = cpu_to_le16(sb->first_bucket);
232         out->keys               = cpu_to_le16(sb->keys);
233
234         for (i = 0; i < sb->keys; i++)
235                 out->d[i] = cpu_to_le64(sb->d[i]);
236
237         out->csum = csum_set(out);
238
239         pr_debug("ver %llu, flags %llu, seq %llu",
240                  sb->version, sb->flags, sb->seq);
241
242         submit_bio(bio);
243 }
244
245 static void bch_write_bdev_super_unlock(struct closure *cl)
246 {
247         struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
248
249         up(&dc->sb_write_mutex);
250 }
251
252 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
253 {
254         struct closure *cl = &dc->sb_write;
255         struct bio *bio = &dc->sb_bio;
256
257         down(&dc->sb_write_mutex);
258         closure_init(cl, parent);
259
260         bio_reset(bio);
261         bio_set_dev(bio, dc->bdev);
262         bio->bi_end_io  = write_bdev_super_endio;
263         bio->bi_private = dc;
264
265         closure_get(cl);
266         /* I/O request sent to backing device */
267         __write_super(&dc->sb, bio);
268
269         closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
270 }
271
272 static void write_super_endio(struct bio *bio)
273 {
274         struct cache *ca = bio->bi_private;
275
276         /* is_read = 0 */
277         bch_count_io_errors(ca, bio->bi_status, 0,
278                             "writing superblock");
279         closure_put(&ca->set->sb_write);
280 }
281
282 static void bcache_write_super_unlock(struct closure *cl)
283 {
284         struct cache_set *c = container_of(cl, struct cache_set, sb_write);
285
286         up(&c->sb_write_mutex);
287 }
288
289 void bcache_write_super(struct cache_set *c)
290 {
291         struct closure *cl = &c->sb_write;
292         struct cache *ca;
293         unsigned int i;
294
295         down(&c->sb_write_mutex);
296         closure_init(cl, &c->cl);
297
298         c->sb.seq++;
299
300         for_each_cache(ca, c, i) {
301                 struct bio *bio = &ca->sb_bio;
302
303                 ca->sb.version          = BCACHE_SB_VERSION_CDEV_WITH_UUID;
304                 ca->sb.seq              = c->sb.seq;
305                 ca->sb.last_mount       = c->sb.last_mount;
306
307                 SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
308
309                 bio_reset(bio);
310                 bio_set_dev(bio, ca->bdev);
311                 bio->bi_end_io  = write_super_endio;
312                 bio->bi_private = ca;
313
314                 closure_get(cl);
315                 __write_super(&ca->sb, bio);
316         }
317
318         closure_return_with_destructor(cl, bcache_write_super_unlock);
319 }
320
321 /* UUID io */
322
323 static void uuid_endio(struct bio *bio)
324 {
325         struct closure *cl = bio->bi_private;
326         struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
327
328         cache_set_err_on(bio->bi_status, c, "accessing uuids");
329         bch_bbio_free(bio, c);
330         closure_put(cl);
331 }
332
333 static void uuid_io_unlock(struct closure *cl)
334 {
335         struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
336
337         up(&c->uuid_write_mutex);
338 }
339
340 static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
341                     struct bkey *k, struct closure *parent)
342 {
343         struct closure *cl = &c->uuid_write;
344         struct uuid_entry *u;
345         unsigned int i;
346         char buf[80];
347
348         BUG_ON(!parent);
349         down(&c->uuid_write_mutex);
350         closure_init(cl, parent);
351
352         for (i = 0; i < KEY_PTRS(k); i++) {
353                 struct bio *bio = bch_bbio_alloc(c);
354
355                 bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
356                 bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
357
358                 bio->bi_end_io  = uuid_endio;
359                 bio->bi_private = cl;
360                 bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
361                 bch_bio_map(bio, c->uuids);
362
363                 bch_submit_bbio(bio, c, k, i);
364
365                 if (op != REQ_OP_WRITE)
366                         break;
367         }
368
369         bch_extent_to_text(buf, sizeof(buf), k);
370         pr_debug("%s UUIDs at %s", op == REQ_OP_WRITE ? "wrote" : "read", buf);
371
372         for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
373                 if (!bch_is_zero(u->uuid, 16))
374                         pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
375                                  u - c->uuids, u->uuid, u->label,
376                                  u->first_reg, u->last_reg, u->invalidated);
377
378         closure_return_with_destructor(cl, uuid_io_unlock);
379 }
380
381 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
382 {
383         struct bkey *k = &j->uuid_bucket;
384
385         if (__bch_btree_ptr_invalid(c, k))
386                 return "bad uuid pointer";
387
388         bkey_copy(&c->uuid_bucket, k);
389         uuid_io(c, REQ_OP_READ, 0, k, cl);
390
391         if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
392                 struct uuid_entry_v0    *u0 = (void *) c->uuids;
393                 struct uuid_entry       *u1 = (void *) c->uuids;
394                 int i;
395
396                 closure_sync(cl);
397
398                 /*
399                  * Since the new uuid entry is bigger than the old, we have to
400                  * convert starting at the highest memory address and work down
401                  * in order to do it in place
402                  */
403
404                 for (i = c->nr_uuids - 1;
405                      i >= 0;
406                      --i) {
407                         memcpy(u1[i].uuid,      u0[i].uuid, 16);
408                         memcpy(u1[i].label,     u0[i].label, 32);
409
410                         u1[i].first_reg         = u0[i].first_reg;
411                         u1[i].last_reg          = u0[i].last_reg;
412                         u1[i].invalidated       = u0[i].invalidated;
413
414                         u1[i].flags     = 0;
415                         u1[i].sectors   = 0;
416                 }
417         }
418
419         return NULL;
420 }
421
422 static int __uuid_write(struct cache_set *c)
423 {
424         BKEY_PADDED(key) k;
425         struct closure cl;
426         struct cache *ca;
427
428         closure_init_stack(&cl);
429         lockdep_assert_held(&bch_register_lock);
430
431         if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
432                 return 1;
433
434         SET_KEY_SIZE(&k.key, c->sb.bucket_size);
435         uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
436         closure_sync(&cl);
437
438         /* Only one bucket used for uuid write */
439         ca = PTR_CACHE(c, &k.key, 0);
440         atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
441
442         bkey_copy(&c->uuid_bucket, &k.key);
443         bkey_put(c, &k.key);
444         return 0;
445 }
446
447 int bch_uuid_write(struct cache_set *c)
448 {
449         int ret = __uuid_write(c);
450
451         if (!ret)
452                 bch_journal_meta(c, NULL);
453
454         return ret;
455 }
456
457 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
458 {
459         struct uuid_entry *u;
460
461         for (u = c->uuids;
462              u < c->uuids + c->nr_uuids; u++)
463                 if (!memcmp(u->uuid, uuid, 16))
464                         return u;
465
466         return NULL;
467 }
468
469 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
470 {
471         static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
472
473         return uuid_find(c, zero_uuid);
474 }
475
476 /*
477  * Bucket priorities/gens:
478  *
479  * For each bucket, we store on disk its
480  *   8 bit gen
481  *  16 bit priority
482  *
483  * See alloc.c for an explanation of the gen. The priority is used to implement
484  * lru (and in the future other) cache replacement policies; for most purposes
485  * it's just an opaque integer.
486  *
487  * The gens and the priorities don't have a whole lot to do with each other, and
488  * it's actually the gens that must be written out at specific times - it's no
489  * big deal if the priorities don't get written, if we lose them we just reuse
490  * buckets in suboptimal order.
491  *
492  * On disk they're stored in a packed array, and in as many buckets are required
493  * to fit them all. The buckets we use to store them form a list; the journal
494  * header points to the first bucket, the first bucket points to the second
495  * bucket, et cetera.
496  *
497  * This code is used by the allocation code; periodically (whenever it runs out
498  * of buckets to allocate from) the allocation code will invalidate some
499  * buckets, but it can't use those buckets until their new gens are safely on
500  * disk.
501  */
502
503 static void prio_endio(struct bio *bio)
504 {
505         struct cache *ca = bio->bi_private;
506
507         cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
508         bch_bbio_free(bio, ca->set);
509         closure_put(&ca->prio);
510 }
511
512 static void prio_io(struct cache *ca, uint64_t bucket, int op,
513                     unsigned long op_flags)
514 {
515         struct closure *cl = &ca->prio;
516         struct bio *bio = bch_bbio_alloc(ca->set);
517
518         closure_init_stack(cl);
519
520         bio->bi_iter.bi_sector  = bucket * ca->sb.bucket_size;
521         bio_set_dev(bio, ca->bdev);
522         bio->bi_iter.bi_size    = bucket_bytes(ca);
523
524         bio->bi_end_io  = prio_endio;
525         bio->bi_private = ca;
526         bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
527         bch_bio_map(bio, ca->disk_buckets);
528
529         closure_bio_submit(ca->set, bio, &ca->prio);
530         closure_sync(cl);
531 }
532
533 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_bio.bi_inline_vecs[0].bv_page)
1279                 put_page(bio_first_page_all(&dc->sb_bio));
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 page *sb_page,
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
1369         bio_init(&dc->sb_bio, dc->sb_bio.bi_inline_vecs, 1);
1370         bio_first_bvec_all(&dc->sb_bio)->bv_page = sb_page;
1371         get_page(sb_page);
1372
1373
1374         if (cached_dev_init(dc, sb->block_size << 9))
1375                 goto err;
1376
1377         err = "error creating kobject";
1378         if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1379                         "bcache"))
1380                 goto err;
1381         if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1382                 goto err;
1383
1384         pr_info("registered backing device %s", dc->backing_dev_name);
1385
1386         list_add(&dc->list, &uncached_devices);
1387         /* attach to a matched cache set if it exists */
1388         list_for_each_entry(c, &bch_cache_sets, list)
1389                 bch_cached_dev_attach(dc, c, NULL);
1390
1391         if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1392             BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
1393                 err = "failed to run cached device";
1394                 ret = bch_cached_dev_run(dc);
1395                 if (ret)
1396                         goto err;
1397         }
1398
1399         return 0;
1400 err:
1401         pr_notice("error %s: %s", dc->backing_dev_name, err);
1402         bcache_device_stop(&dc->disk);
1403         return ret;
1404 }
1405
1406 /* Flash only volumes */
1407
1408 /* When d->kobj released */
1409 void bch_flash_dev_release(struct kobject *kobj)
1410 {
1411         struct bcache_device *d = container_of(kobj, struct bcache_device,
1412                                                kobj);
1413         kfree(d);
1414 }
1415
1416 static void flash_dev_free(struct closure *cl)
1417 {
1418         struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1419
1420         mutex_lock(&bch_register_lock);
1421         atomic_long_sub(bcache_dev_sectors_dirty(d),
1422                         &d->c->flash_dev_dirty_sectors);
1423         bcache_device_free(d);
1424         mutex_unlock(&bch_register_lock);
1425         kobject_put(&d->kobj);
1426 }
1427
1428 static void flash_dev_flush(struct closure *cl)
1429 {
1430         struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1431
1432         mutex_lock(&bch_register_lock);
1433         bcache_device_unlink(d);
1434         mutex_unlock(&bch_register_lock);
1435         kobject_del(&d->kobj);
1436         continue_at(cl, flash_dev_free, system_wq);
1437 }
1438
1439 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1440 {
1441         struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1442                                           GFP_KERNEL);
1443         if (!d)
1444                 return -ENOMEM;
1445
1446         closure_init(&d->cl, NULL);
1447         set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1448
1449         kobject_init(&d->kobj, &bch_flash_dev_ktype);
1450
1451         if (bcache_device_init(d, block_bytes(c), u->sectors))
1452                 goto err;
1453
1454         bcache_device_attach(d, c, u - c->uuids);
1455         bch_sectors_dirty_init(d);
1456         bch_flash_dev_request_init(d);
1457         add_disk(d->disk);
1458
1459         if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1460                 goto err;
1461
1462         bcache_device_link(d, c, "volume");
1463
1464         return 0;
1465 err:
1466         kobject_put(&d->kobj);
1467         return -ENOMEM;
1468 }
1469
1470 static int flash_devs_run(struct cache_set *c)
1471 {
1472         int ret = 0;
1473         struct uuid_entry *u;
1474
1475         for (u = c->uuids;
1476              u < c->uuids + c->nr_uuids && !ret;
1477              u++)
1478                 if (UUID_FLASH_ONLY(u))
1479                         ret = flash_dev_run(c, u);
1480
1481         return ret;
1482 }
1483
1484 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1485 {
1486         struct uuid_entry *u;
1487
1488         if (test_bit(CACHE_SET_STOPPING, &c->flags))
1489                 return -EINTR;
1490
1491         if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1492                 return -EPERM;
1493
1494         u = uuid_find_empty(c);
1495         if (!u) {
1496                 pr_err("Can't create volume, no room for UUID");
1497                 return -EINVAL;
1498         }
1499
1500         get_random_bytes(u->uuid, 16);
1501         memset(u->label, 0, 32);
1502         u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1503
1504         SET_UUID_FLASH_ONLY(u, 1);
1505         u->sectors = size >> 9;
1506
1507         bch_uuid_write(c);
1508
1509         return flash_dev_run(c, u);
1510 }
1511
1512 bool bch_cached_dev_error(struct cached_dev *dc)
1513 {
1514         if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1515                 return false;
1516
1517         dc->io_disable = true;
1518         /* make others know io_disable is true earlier */
1519         smp_mb();
1520
1521         pr_err("stop %s: too many IO errors on backing device %s\n",
1522                 dc->disk.disk->disk_name, dc->backing_dev_name);
1523
1524         bcache_device_stop(&dc->disk);
1525         return true;
1526 }
1527
1528 /* Cache set */
1529
1530 __printf(2, 3)
1531 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1532 {
1533         va_list args;
1534
1535         if (c->on_error != ON_ERROR_PANIC &&
1536             test_bit(CACHE_SET_STOPPING, &c->flags))
1537                 return false;
1538
1539         if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1540                 pr_info("CACHE_SET_IO_DISABLE already set");
1541
1542         /*
1543          * XXX: we can be called from atomic context
1544          * acquire_console_sem();
1545          */
1546
1547         pr_err("bcache: error on %pU: ", c->sb.set_uuid);
1548
1549         va_start(args, fmt);
1550         vprintk(fmt, args);
1551         va_end(args);
1552
1553         pr_err(", disabling caching\n");
1554
1555         if (c->on_error == ON_ERROR_PANIC)
1556                 panic("panic forced after error\n");
1557
1558         bch_cache_set_unregister(c);
1559         return true;
1560 }
1561
1562 /* When c->kobj released */
1563 void bch_cache_set_release(struct kobject *kobj)
1564 {
1565         struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1566
1567         kfree(c);
1568         module_put(THIS_MODULE);
1569 }
1570
1571 static void cache_set_free(struct closure *cl)
1572 {
1573         struct cache_set *c = container_of(cl, struct cache_set, cl);
1574         struct cache *ca;
1575         unsigned int i;
1576
1577         debugfs_remove(c->debug);
1578
1579         bch_open_buckets_free(c);
1580         bch_btree_cache_free(c);
1581         bch_journal_free(c);
1582
1583         mutex_lock(&bch_register_lock);
1584         for_each_cache(ca, c, i)
1585                 if (ca) {
1586                         ca->set = NULL;
1587                         c->cache[ca->sb.nr_this_dev] = NULL;
1588                         kobject_put(&ca->kobj);
1589                 }
1590
1591         bch_bset_sort_state_free(&c->sort);
1592         free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1593
1594         if (c->moving_gc_wq)
1595                 destroy_workqueue(c->moving_gc_wq);
1596         bioset_exit(&c->bio_split);
1597         mempool_exit(&c->fill_iter);
1598         mempool_exit(&c->bio_meta);
1599         mempool_exit(&c->search);
1600         kfree(c->devices);
1601
1602         list_del(&c->list);
1603         mutex_unlock(&bch_register_lock);
1604
1605         pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1606         wake_up(&unregister_wait);
1607
1608         closure_debug_destroy(&c->cl);
1609         kobject_put(&c->kobj);
1610 }
1611
1612 static void cache_set_flush(struct closure *cl)
1613 {
1614         struct cache_set *c = container_of(cl, struct cache_set, caching);
1615         struct cache *ca;
1616         struct btree *b;
1617         unsigned int i;
1618
1619         bch_cache_accounting_destroy(&c->accounting);
1620
1621         kobject_put(&c->internal);
1622         kobject_del(&c->kobj);
1623
1624         if (!IS_ERR_OR_NULL(c->gc_thread))
1625                 kthread_stop(c->gc_thread);
1626
1627         if (!IS_ERR_OR_NULL(c->root))
1628                 list_add(&c->root->list, &c->btree_cache);
1629
1630         /*
1631          * Avoid flushing cached nodes if cache set is retiring
1632          * due to too many I/O errors detected.
1633          */
1634         if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1635                 list_for_each_entry(b, &c->btree_cache, list) {
1636                         mutex_lock(&b->write_lock);
1637                         if (btree_node_dirty(b))
1638                                 __bch_btree_node_write(b, NULL);
1639                         mutex_unlock(&b->write_lock);
1640                 }
1641
1642         for_each_cache(ca, c, i)
1643                 if (ca->alloc_thread)
1644                         kthread_stop(ca->alloc_thread);
1645
1646         if (c->journal.cur) {
1647                 cancel_delayed_work_sync(&c->journal.work);
1648                 /* flush last journal entry if needed */
1649                 c->journal.work.work.func(&c->journal.work.work);
1650         }
1651
1652         closure_return(cl);
1653 }
1654
1655 /*
1656  * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1657  * cache set is unregistering due to too many I/O errors. In this condition,
1658  * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1659  * value and whether the broken cache has dirty data:
1660  *
1661  * dc->stop_when_cache_set_failed    dc->has_dirty   stop bcache device
1662  *  BCH_CACHED_STOP_AUTO               0               NO
1663  *  BCH_CACHED_STOP_AUTO               1               YES
1664  *  BCH_CACHED_DEV_STOP_ALWAYS         0               YES
1665  *  BCH_CACHED_DEV_STOP_ALWAYS         1               YES
1666  *
1667  * The expected behavior is, if stop_when_cache_set_failed is configured to
1668  * "auto" via sysfs interface, the bcache device will not be stopped if the
1669  * backing device is clean on the broken cache device.
1670  */
1671 static void conditional_stop_bcache_device(struct cache_set *c,
1672                                            struct bcache_device *d,
1673                                            struct cached_dev *dc)
1674 {
1675         if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1676                 pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.",
1677                         d->disk->disk_name, c->sb.set_uuid);
1678                 bcache_device_stop(d);
1679         } else if (atomic_read(&dc->has_dirty)) {
1680                 /*
1681                  * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1682                  * and dc->has_dirty == 1
1683                  */
1684                 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.",
1685                         d->disk->disk_name);
1686                 /*
1687                  * There might be a small time gap that cache set is
1688                  * released but bcache device is not. Inside this time
1689                  * gap, regular I/O requests will directly go into
1690                  * backing device as no cache set attached to. This
1691                  * behavior may also introduce potential inconsistence
1692                  * data in writeback mode while cache is dirty.
1693                  * Therefore before calling bcache_device_stop() due
1694                  * to a broken cache device, dc->io_disable should be
1695                  * explicitly set to true.
1696                  */
1697                 dc->io_disable = true;
1698                 /* make others know io_disable is true earlier */
1699                 smp_mb();
1700                 bcache_device_stop(d);
1701         } else {
1702                 /*
1703                  * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1704                  * and dc->has_dirty == 0
1705                  */
1706                 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.",
1707                         d->disk->disk_name);
1708         }
1709 }
1710
1711 static void __cache_set_unregister(struct closure *cl)
1712 {
1713         struct cache_set *c = container_of(cl, struct cache_set, caching);
1714         struct cached_dev *dc;
1715         struct bcache_device *d;
1716         size_t i;
1717
1718         mutex_lock(&bch_register_lock);
1719
1720         for (i = 0; i < c->devices_max_used; i++) {
1721                 d = c->devices[i];
1722                 if (!d)
1723                         continue;
1724
1725                 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1726                     test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1727                         dc = container_of(d, struct cached_dev, disk);
1728                         bch_cached_dev_detach(dc);
1729                         if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1730                                 conditional_stop_bcache_device(c, d, dc);
1731                 } else {
1732                         bcache_device_stop(d);
1733                 }
1734         }
1735
1736         mutex_unlock(&bch_register_lock);
1737
1738         continue_at(cl, cache_set_flush, system_wq);
1739 }
1740
1741 void bch_cache_set_stop(struct cache_set *c)
1742 {
1743         if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1744                 /* closure_fn set to __cache_set_unregister() */
1745                 closure_queue(&c->caching);
1746 }
1747
1748 void bch_cache_set_unregister(struct cache_set *c)
1749 {
1750         set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1751         bch_cache_set_stop(c);
1752 }
1753
1754 #define alloc_bucket_pages(gfp, c)                      \
1755         ((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1756
1757 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1758 {
1759         int iter_size;
1760         struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1761
1762         if (!c)
1763                 return NULL;
1764
1765         __module_get(THIS_MODULE);
1766         closure_init(&c->cl, NULL);
1767         set_closure_fn(&c->cl, cache_set_free, system_wq);
1768
1769         closure_init(&c->caching, &c->cl);
1770         set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1771
1772         /* Maybe create continue_at_noreturn() and use it here? */
1773         closure_set_stopped(&c->cl);
1774         closure_put(&c->cl);
1775
1776         kobject_init(&c->kobj, &bch_cache_set_ktype);
1777         kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1778
1779         bch_cache_accounting_init(&c->accounting, &c->cl);
1780
1781         memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1782         c->sb.block_size        = sb->block_size;
1783         c->sb.bucket_size       = sb->bucket_size;
1784         c->sb.nr_in_set         = sb->nr_in_set;
1785         c->sb.last_mount        = sb->last_mount;
1786         c->bucket_bits          = ilog2(sb->bucket_size);
1787         c->block_bits           = ilog2(sb->block_size);
1788         c->nr_uuids             = bucket_bytes(c) / sizeof(struct uuid_entry);
1789         c->devices_max_used     = 0;
1790         atomic_set(&c->attached_dev_nr, 0);
1791         c->btree_pages          = bucket_pages(c);
1792         if (c->btree_pages > BTREE_MAX_PAGES)
1793                 c->btree_pages = max_t(int, c->btree_pages / 4,
1794                                        BTREE_MAX_PAGES);
1795
1796         sema_init(&c->sb_write_mutex, 1);
1797         mutex_init(&c->bucket_lock);
1798         init_waitqueue_head(&c->btree_cache_wait);
1799         spin_lock_init(&c->btree_cannibalize_lock);
1800         init_waitqueue_head(&c->bucket_wait);
1801         init_waitqueue_head(&c->gc_wait);
1802         sema_init(&c->uuid_write_mutex, 1);
1803
1804         spin_lock_init(&c->btree_gc_time.lock);
1805         spin_lock_init(&c->btree_split_time.lock);
1806         spin_lock_init(&c->btree_read_time.lock);
1807
1808         bch_moving_init_cache_set(c);
1809
1810         INIT_LIST_HEAD(&c->list);
1811         INIT_LIST_HEAD(&c->cached_devs);
1812         INIT_LIST_HEAD(&c->btree_cache);
1813         INIT_LIST_HEAD(&c->btree_cache_freeable);
1814         INIT_LIST_HEAD(&c->btree_cache_freed);
1815         INIT_LIST_HEAD(&c->data_buckets);
1816
1817         iter_size = (sb->bucket_size / sb->block_size + 1) *
1818                 sizeof(struct btree_iter_set);
1819
1820         if (!(c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL)) ||
1821             mempool_init_slab_pool(&c->search, 32, bch_search_cache) ||
1822             mempool_init_kmalloc_pool(&c->bio_meta, 2,
1823                                 sizeof(struct bbio) + sizeof(struct bio_vec) *
1824                                 bucket_pages(c)) ||
1825             mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
1826             bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1827                         BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER) ||
1828             !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1829             !(c->moving_gc_wq = alloc_workqueue("bcache_gc",
1830                                                 WQ_MEM_RECLAIM, 0)) ||
1831             bch_journal_alloc(c) ||
1832             bch_btree_cache_alloc(c) ||
1833             bch_open_buckets_alloc(c) ||
1834             bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1835                 goto err;
1836
1837         c->congested_read_threshold_us  = 2000;
1838         c->congested_write_threshold_us = 20000;
1839         c->error_limit  = DEFAULT_IO_ERROR_LIMIT;
1840         c->idle_max_writeback_rate_enabled = 1;
1841         WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1842
1843         return c;
1844 err:
1845         bch_cache_set_unregister(c);
1846         return NULL;
1847 }
1848
1849 static int run_cache_set(struct cache_set *c)
1850 {
1851         const char *err = "cannot allocate memory";
1852         struct cached_dev *dc, *t;
1853         struct cache *ca;
1854         struct closure cl;
1855         unsigned int i;
1856         LIST_HEAD(journal);
1857         struct journal_replay *l;
1858
1859         closure_init_stack(&cl);
1860
1861         for_each_cache(ca, c, i)
1862                 c->nbuckets += ca->sb.nbuckets;
1863         set_gc_sectors(c);
1864
1865         if (CACHE_SYNC(&c->sb)) {
1866                 struct bkey *k;
1867                 struct jset *j;
1868
1869                 err = "cannot allocate memory for journal";
1870                 if (bch_journal_read(c, &journal))
1871                         goto err;
1872
1873                 pr_debug("btree_journal_read() done");
1874
1875                 err = "no journal entries found";
1876                 if (list_empty(&journal))
1877                         goto err;
1878
1879                 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1880
1881                 err = "IO error reading priorities";
1882                 for_each_cache(ca, c, i)
1883                         prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1884
1885                 /*
1886                  * If prio_read() fails it'll call cache_set_error and we'll
1887                  * tear everything down right away, but if we perhaps checked
1888                  * sooner we could avoid journal replay.
1889                  */
1890
1891                 k = &j->btree_root;
1892
1893                 err = "bad btree root";
1894                 if (__bch_btree_ptr_invalid(c, k))
1895                         goto err;
1896
1897                 err = "error reading btree root";
1898                 c->root = bch_btree_node_get(c, NULL, k,
1899                                              j->btree_level,
1900                                              true, NULL);
1901                 if (IS_ERR_OR_NULL(c->root))
1902                         goto err;
1903
1904                 list_del_init(&c->root->list);
1905                 rw_unlock(true, c->root);
1906
1907                 err = uuid_read(c, j, &cl);
1908                 if (err)
1909                         goto err;
1910
1911                 err = "error in recovery";
1912                 if (bch_btree_check(c))
1913                         goto err;
1914
1915                 /*
1916                  * bch_btree_check() may occupy too much system memory which
1917                  * has negative effects to user space application (e.g. data
1918                  * base) performance. Shrink the mca cache memory proactively
1919                  * here to avoid competing memory with user space workloads..
1920                  */
1921                 if (!c->shrinker_disabled) {
1922                         struct shrink_control sc;
1923
1924                         sc.gfp_mask = GFP_KERNEL;
1925                         sc.nr_to_scan = c->btree_cache_used * c->btree_pages;
1926                         /* first run to clear b->accessed tag */
1927                         c->shrink.scan_objects(&c->shrink, &sc);
1928                         /* second run to reap non-accessed nodes */
1929                         c->shrink.scan_objects(&c->shrink, &sc);
1930                 }
1931
1932                 bch_journal_mark(c, &journal);
1933                 bch_initial_gc_finish(c);
1934                 pr_debug("btree_check() done");
1935
1936                 /*
1937                  * bcache_journal_next() can't happen sooner, or
1938                  * btree_gc_finish() will give spurious errors about last_gc >
1939                  * gc_gen - this is a hack but oh well.
1940                  */
1941                 bch_journal_next(&c->journal);
1942
1943                 err = "error starting allocator thread";
1944                 for_each_cache(ca, c, i)
1945                         if (bch_cache_allocator_start(ca))
1946                                 goto err;
1947
1948                 /*
1949                  * First place it's safe to allocate: btree_check() and
1950                  * btree_gc_finish() have to run before we have buckets to
1951                  * allocate, and bch_bucket_alloc_set() might cause a journal
1952                  * entry to be written so bcache_journal_next() has to be called
1953                  * first.
1954                  *
1955                  * If the uuids were in the old format we have to rewrite them
1956                  * before the next journal entry is written:
1957                  */
1958                 if (j->version < BCACHE_JSET_VERSION_UUID)
1959                         __uuid_write(c);
1960
1961                 err = "bcache: replay journal failed";
1962                 if (bch_journal_replay(c, &journal))
1963                         goto err;
1964         } else {
1965                 pr_notice("invalidating existing data");
1966
1967                 for_each_cache(ca, c, i) {
1968                         unsigned int j;
1969
1970                         ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1971                                               2, SB_JOURNAL_BUCKETS);
1972
1973                         for (j = 0; j < ca->sb.keys; j++)
1974                                 ca->sb.d[j] = ca->sb.first_bucket + j;
1975                 }
1976
1977                 bch_initial_gc_finish(c);
1978
1979                 err = "error starting allocator thread";
1980                 for_each_cache(ca, c, i)
1981                         if (bch_cache_allocator_start(ca))
1982                                 goto err;
1983
1984                 mutex_lock(&c->bucket_lock);
1985                 for_each_cache(ca, c, i)
1986                         bch_prio_write(ca, true);
1987                 mutex_unlock(&c->bucket_lock);
1988
1989                 err = "cannot allocate new UUID bucket";
1990                 if (__uuid_write(c))
1991                         goto err;
1992
1993                 err = "cannot allocate new btree root";
1994                 c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
1995                 if (IS_ERR_OR_NULL(c->root))
1996                         goto err;
1997
1998                 mutex_lock(&c->root->write_lock);
1999                 bkey_copy_key(&c->root->key, &MAX_KEY);
2000                 bch_btree_node_write(c->root, &cl);
2001                 mutex_unlock(&c->root->write_lock);
2002
2003                 bch_btree_set_root(c->root);
2004                 rw_unlock(true, c->root);
2005
2006                 /*
2007                  * We don't want to write the first journal entry until
2008                  * everything is set up - fortunately journal entries won't be
2009                  * written until the SET_CACHE_SYNC() here:
2010                  */
2011                 SET_CACHE_SYNC(&c->sb, true);
2012
2013                 bch_journal_next(&c->journal);
2014                 bch_journal_meta(c, &cl);
2015         }
2016
2017         err = "error starting gc thread";
2018         if (bch_gc_thread_start(c))
2019                 goto err;
2020
2021         closure_sync(&cl);
2022         c->sb.last_mount = (u32)ktime_get_real_seconds();
2023         bcache_write_super(c);
2024
2025         list_for_each_entry_safe(dc, t, &uncached_devices, list)
2026                 bch_cached_dev_attach(dc, c, NULL);
2027
2028         flash_devs_run(c);
2029
2030         set_bit(CACHE_SET_RUNNING, &c->flags);
2031         return 0;
2032 err:
2033         while (!list_empty(&journal)) {
2034                 l = list_first_entry(&journal, struct journal_replay, list);
2035                 list_del(&l->list);
2036                 kfree(l);
2037         }
2038
2039         closure_sync(&cl);
2040
2041         bch_cache_set_error(c, "%s", err);
2042
2043         return -EIO;
2044 }
2045
2046 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
2047 {
2048         return ca->sb.block_size        == c->sb.block_size &&
2049                 ca->sb.bucket_size      == c->sb.bucket_size &&
2050                 ca->sb.nr_in_set        == c->sb.nr_in_set;
2051 }
2052
2053 static const char *register_cache_set(struct cache *ca)
2054 {
2055         char buf[12];
2056         const char *err = "cannot allocate memory";
2057         struct cache_set *c;
2058
2059         list_for_each_entry(c, &bch_cache_sets, list)
2060                 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
2061                         if (c->cache[ca->sb.nr_this_dev])
2062                                 return "duplicate cache set member";
2063
2064                         if (!can_attach_cache(ca, c))
2065                                 return "cache sb does not match set";
2066
2067                         if (!CACHE_SYNC(&ca->sb))
2068                                 SET_CACHE_SYNC(&c->sb, false);
2069
2070                         goto found;
2071                 }
2072
2073         c = bch_cache_set_alloc(&ca->sb);
2074         if (!c)
2075                 return err;
2076
2077         err = "error creating kobject";
2078         if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
2079             kobject_add(&c->internal, &c->kobj, "internal"))
2080                 goto err;
2081
2082         if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2083                 goto err;
2084
2085         bch_debug_init_cache_set(c);
2086
2087         list_add(&c->list, &bch_cache_sets);
2088 found:
2089         sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2090         if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2091             sysfs_create_link(&c->kobj, &ca->kobj, buf))
2092                 goto err;
2093
2094         if (ca->sb.seq > c->sb.seq) {
2095                 c->sb.version           = ca->sb.version;
2096                 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
2097                 c->sb.flags             = ca->sb.flags;
2098                 c->sb.seq               = ca->sb.seq;
2099                 pr_debug("set version = %llu", c->sb.version);
2100         }
2101
2102         kobject_get(&ca->kobj);
2103         ca->set = c;
2104         ca->set->cache[ca->sb.nr_this_dev] = ca;
2105         c->cache_by_alloc[c->caches_loaded++] = ca;
2106
2107         if (c->caches_loaded == c->sb.nr_in_set) {
2108                 err = "failed to run cache set";
2109                 if (run_cache_set(c) < 0)
2110                         goto err;
2111         }
2112
2113         return NULL;
2114 err:
2115         bch_cache_set_unregister(c);
2116         return err;
2117 }
2118
2119 /* Cache device */
2120
2121 /* When ca->kobj released */
2122 void bch_cache_release(struct kobject *kobj)
2123 {
2124         struct cache *ca = container_of(kobj, struct cache, kobj);
2125         unsigned int i;
2126
2127         if (ca->set) {
2128                 BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
2129                 ca->set->cache[ca->sb.nr_this_dev] = NULL;
2130         }
2131
2132         free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
2133         kfree(ca->prio_buckets);
2134         vfree(ca->buckets);
2135
2136         free_heap(&ca->heap);
2137         free_fifo(&ca->free_inc);
2138
2139         for (i = 0; i < RESERVE_NR; i++)
2140                 free_fifo(&ca->free[i]);
2141
2142         if (ca->sb_bio.bi_inline_vecs[0].bv_page)
2143                 put_page(bio_first_page_all(&ca->sb_bio));
2144
2145         if (!IS_ERR_OR_NULL(ca->bdev))
2146                 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2147
2148         kfree(ca);
2149         module_put(THIS_MODULE);
2150 }
2151
2152 static int cache_alloc(struct cache *ca)
2153 {
2154         size_t free;
2155         size_t btree_buckets;
2156         struct bucket *b;
2157         int ret = -ENOMEM;
2158         const char *err = NULL;
2159
2160         __module_get(THIS_MODULE);
2161         kobject_init(&ca->kobj, &bch_cache_ktype);
2162
2163         bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2164
2165         /*
2166          * when ca->sb.njournal_buckets is not zero, journal exists,
2167          * and in bch_journal_replay(), tree node may split,
2168          * so bucket of RESERVE_BTREE type is needed,
2169          * the worst situation is all journal buckets are valid journal,
2170          * and all the keys need to replay,
2171          * so the number of  RESERVE_BTREE type buckets should be as much
2172          * as journal buckets
2173          */
2174         btree_buckets = ca->sb.njournal_buckets ?: 8;
2175         free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
2176         if (!free) {
2177                 ret = -EPERM;
2178                 err = "ca->sb.nbuckets is too small";
2179                 goto err_free;
2180         }
2181
2182         if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
2183                                                 GFP_KERNEL)) {
2184                 err = "ca->free[RESERVE_BTREE] alloc failed";
2185                 goto err_btree_alloc;
2186         }
2187
2188         if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
2189                                                         GFP_KERNEL)) {
2190                 err = "ca->free[RESERVE_PRIO] alloc failed";
2191                 goto err_prio_alloc;
2192         }
2193
2194         if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
2195                 err = "ca->free[RESERVE_MOVINGGC] alloc failed";
2196                 goto err_movinggc_alloc;
2197         }
2198
2199         if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
2200                 err = "ca->free[RESERVE_NONE] alloc failed";
2201                 goto err_none_alloc;
2202         }
2203
2204         if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
2205                 err = "ca->free_inc alloc failed";
2206                 goto err_free_inc_alloc;
2207         }
2208
2209         if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
2210                 err = "ca->heap alloc failed";
2211                 goto err_heap_alloc;
2212         }
2213
2214         ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2215                               ca->sb.nbuckets));
2216         if (!ca->buckets) {
2217                 err = "ca->buckets alloc failed";
2218                 goto err_buckets_alloc;
2219         }
2220
2221         ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
2222                                    prio_buckets(ca), 2),
2223                                    GFP_KERNEL);
2224         if (!ca->prio_buckets) {
2225                 err = "ca->prio_buckets alloc failed";
2226                 goto err_prio_buckets_alloc;
2227         }
2228
2229         ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca);
2230         if (!ca->disk_buckets) {
2231                 err = "ca->disk_buckets alloc failed";
2232                 goto err_disk_buckets_alloc;
2233         }
2234
2235         ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2236
2237         for_each_bucket(b, ca)
2238                 atomic_set(&b->pin, 0);
2239         return 0;
2240
2241 err_disk_buckets_alloc:
2242         kfree(ca->prio_buckets);
2243 err_prio_buckets_alloc:
2244         vfree(ca->buckets);
2245 err_buckets_alloc:
2246         free_heap(&ca->heap);
2247 err_heap_alloc:
2248         free_fifo(&ca->free_inc);
2249 err_free_inc_alloc:
2250         free_fifo(&ca->free[RESERVE_NONE]);
2251 err_none_alloc:
2252         free_fifo(&ca->free[RESERVE_MOVINGGC]);
2253 err_movinggc_alloc:
2254         free_fifo(&ca->free[RESERVE_PRIO]);
2255 err_prio_alloc:
2256         free_fifo(&ca->free[RESERVE_BTREE]);
2257 err_btree_alloc:
2258 err_free:
2259         module_put(THIS_MODULE);
2260         if (err)
2261                 pr_notice("error %s: %s", ca->cache_dev_name, err);
2262         return ret;
2263 }
2264
2265 static int register_cache(struct cache_sb *sb, struct page *sb_page,
2266                                 struct block_device *bdev, struct cache *ca)
2267 {
2268         const char *err = NULL; /* must be set for any error case */
2269         int ret = 0;
2270
2271         bdevname(bdev, ca->cache_dev_name);
2272         memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2273         ca->bdev = bdev;
2274         ca->bdev->bd_holder = ca;
2275
2276         bio_init(&ca->sb_bio, ca->sb_bio.bi_inline_vecs, 1);
2277         bio_first_bvec_all(&ca->sb_bio)->bv_page = sb_page;
2278         get_page(sb_page);
2279
2280         if (blk_queue_discard(bdev_get_queue(bdev)))
2281                 ca->discard = CACHE_DISCARD(&ca->sb);
2282
2283         ret = cache_alloc(ca);
2284         if (ret != 0) {
2285                 /*
2286                  * If we failed here, it means ca->kobj is not initialized yet,
2287                  * kobject_put() won't be called and there is no chance to
2288                  * call blkdev_put() to bdev in bch_cache_release(). So we
2289                  * explicitly call blkdev_put() here.
2290                  */
2291                 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2292                 if (ret == -ENOMEM)
2293                         err = "cache_alloc(): -ENOMEM";
2294                 else if (ret == -EPERM)
2295                         err = "cache_alloc(): cache device is too small";
2296                 else
2297                         err = "cache_alloc(): unknown error";
2298                 goto err;
2299         }
2300
2301         if (kobject_add(&ca->kobj,
2302                         &part_to_dev(bdev->bd_part)->kobj,
2303                         "bcache")) {
2304                 err = "error calling kobject_add";
2305                 ret = -ENOMEM;
2306                 goto out;
2307         }
2308
2309         mutex_lock(&bch_register_lock);
2310         err = register_cache_set(ca);
2311         mutex_unlock(&bch_register_lock);
2312
2313         if (err) {
2314                 ret = -ENODEV;
2315                 goto out;
2316         }
2317
2318         pr_info("registered cache device %s", ca->cache_dev_name);
2319
2320 out:
2321         kobject_put(&ca->kobj);
2322
2323 err:
2324         if (err)
2325                 pr_notice("error %s: %s", ca->cache_dev_name, err);
2326
2327         return ret;
2328 }
2329
2330 /* Global interfaces/init */
2331
2332 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2333                                const char *buffer, size_t size);
2334 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2335                                          struct kobj_attribute *attr,
2336                                          const char *buffer, size_t size);
2337
2338 kobj_attribute_write(register,          register_bcache);
2339 kobj_attribute_write(register_quiet,    register_bcache);
2340 kobj_attribute_write(pendings_cleanup,  bch_pending_bdevs_cleanup);
2341
2342 static bool bch_is_open_backing(struct block_device *bdev)
2343 {
2344         struct cache_set *c, *tc;
2345         struct cached_dev *dc, *t;
2346
2347         list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2348                 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2349                         if (dc->bdev == bdev)
2350                                 return true;
2351         list_for_each_entry_safe(dc, t, &uncached_devices, list)
2352                 if (dc->bdev == bdev)
2353                         return true;
2354         return false;
2355 }
2356
2357 static bool bch_is_open_cache(struct block_device *bdev)
2358 {
2359         struct cache_set *c, *tc;
2360         struct cache *ca;
2361         unsigned int i;
2362
2363         list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2364                 for_each_cache(ca, c, i)
2365                         if (ca->bdev == bdev)
2366                                 return true;
2367         return false;
2368 }
2369
2370 static bool bch_is_open(struct block_device *bdev)
2371 {
2372         return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2373 }
2374
2375 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2376                                const char *buffer, size_t size)
2377 {
2378         ssize_t ret = -EINVAL;
2379         const char *err = "cannot allocate memory";
2380         char *path = NULL;
2381         struct cache_sb *sb = NULL;
2382         struct block_device *bdev = NULL;
2383         struct page *sb_page = NULL;
2384
2385         if (!try_module_get(THIS_MODULE))
2386                 return -EBUSY;
2387
2388         /* For latest state of bcache_is_reboot */
2389         smp_mb();
2390         if (bcache_is_reboot)
2391                 return -EBUSY;
2392
2393         path = kstrndup(buffer, size, GFP_KERNEL);
2394         if (!path)
2395                 goto err;
2396
2397         sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2398         if (!sb)
2399                 goto err;
2400
2401         err = "failed to open device";
2402         bdev = blkdev_get_by_path(strim(path),
2403                                   FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2404                                   sb);
2405         if (IS_ERR(bdev)) {
2406                 if (bdev == ERR_PTR(-EBUSY)) {
2407                         bdev = lookup_bdev(strim(path));
2408                         mutex_lock(&bch_register_lock);
2409                         if (!IS_ERR(bdev) && bch_is_open(bdev))
2410                                 err = "device already registered";
2411                         else
2412                                 err = "device busy";
2413                         mutex_unlock(&bch_register_lock);
2414                         if (!IS_ERR(bdev))
2415                                 bdput(bdev);
2416                         if (attr == &ksysfs_register_quiet)
2417                                 goto quiet_out;
2418                 }
2419                 goto err;
2420         }
2421
2422         err = "failed to set blocksize";
2423         if (set_blocksize(bdev, 4096))
2424                 goto err_close;
2425
2426         err = read_super(sb, bdev, &sb_page);
2427         if (err)
2428                 goto err_close;
2429
2430         err = "failed to register device";
2431         if (SB_IS_BDEV(sb)) {
2432                 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2433
2434                 if (!dc)
2435                         goto err_close;
2436
2437                 mutex_lock(&bch_register_lock);
2438                 ret = register_bdev(sb, sb_page, bdev, dc);
2439                 mutex_unlock(&bch_register_lock);
2440                 /* blkdev_put() will be called in cached_dev_free() */
2441                 if (ret < 0)
2442                         goto err;
2443         } else {
2444                 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2445
2446                 if (!ca)
2447                         goto err_close;
2448
2449                 /* blkdev_put() will be called in bch_cache_release() */
2450                 if (register_cache(sb, sb_page, bdev, ca) != 0)
2451                         goto err;
2452         }
2453 quiet_out:
2454         ret = size;
2455 out:
2456         if (sb_page)
2457                 put_page(sb_page);
2458         kfree(sb);
2459         kfree(path);
2460         module_put(THIS_MODULE);
2461         return ret;
2462
2463 err_close:
2464         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2465 err:
2466         pr_info("error %s: %s", path, err);
2467         goto out;
2468 }
2469
2470
2471 struct pdev {
2472         struct list_head list;
2473         struct cached_dev *dc;
2474 };
2475
2476 static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2477                                          struct kobj_attribute *attr,
2478                                          const char *buffer,
2479                                          size_t size)
2480 {
2481         LIST_HEAD(pending_devs);
2482         ssize_t ret = size;
2483         struct cached_dev *dc, *tdc;
2484         struct pdev *pdev, *tpdev;
2485         struct cache_set *c, *tc;
2486
2487         mutex_lock(&bch_register_lock);
2488         list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
2489                 pdev = kmalloc(sizeof(struct pdev), GFP_KERNEL);
2490                 if (!pdev)
2491                         break;
2492                 pdev->dc = dc;
2493                 list_add(&pdev->list, &pending_devs);
2494         }
2495
2496         list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2497                 list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
2498                         char *pdev_set_uuid = pdev->dc->sb.set_uuid;
2499                         char *set_uuid = c->sb.uuid;
2500
2501                         if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
2502                                 list_del(&pdev->list);
2503                                 kfree(pdev);
2504                                 break;
2505                         }
2506                 }
2507         }
2508         mutex_unlock(&bch_register_lock);
2509
2510         list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2511                 pr_info("delete pdev %p", pdev);
2512                 list_del(&pdev->list);
2513                 bcache_device_stop(&pdev->dc->disk);
2514                 kfree(pdev);
2515         }
2516
2517         return ret;
2518 }
2519
2520 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2521 {
2522         if (bcache_is_reboot)
2523                 return NOTIFY_DONE;
2524
2525         if (code == SYS_DOWN ||
2526             code == SYS_HALT ||
2527             code == SYS_POWER_OFF) {
2528                 DEFINE_WAIT(wait);
2529                 unsigned long start = jiffies;
2530                 bool stopped = false;
2531
2532                 struct cache_set *c, *tc;
2533                 struct cached_dev *dc, *tdc;
2534
2535                 mutex_lock(&bch_register_lock);
2536
2537                 if (bcache_is_reboot)
2538                         goto out;
2539
2540                 /* New registration is rejected since now */
2541                 bcache_is_reboot = true;
2542                 /*
2543                  * Make registering caller (if there is) on other CPU
2544                  * core know bcache_is_reboot set to true earlier
2545                  */
2546                 smp_mb();
2547
2548                 if (list_empty(&bch_cache_sets) &&
2549                     list_empty(&uncached_devices))
2550                         goto out;
2551
2552                 mutex_unlock(&bch_register_lock);
2553
2554                 pr_info("Stopping all devices:");
2555
2556                 /*
2557                  * The reason bch_register_lock is not held to call
2558                  * bch_cache_set_stop() and bcache_device_stop() is to
2559                  * avoid potential deadlock during reboot, because cache
2560                  * set or bcache device stopping process will acqurie
2561                  * bch_register_lock too.
2562                  *
2563                  * We are safe here because bcache_is_reboot sets to
2564                  * true already, register_bcache() will reject new
2565                  * registration now. bcache_is_reboot also makes sure
2566                  * bcache_reboot() won't be re-entered on by other thread,
2567                  * so there is no race in following list iteration by
2568                  * list_for_each_entry_safe().
2569                  */
2570                 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2571                         bch_cache_set_stop(c);
2572
2573                 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2574                         bcache_device_stop(&dc->disk);
2575
2576
2577                 /*
2578                  * Give an early chance for other kthreads and
2579                  * kworkers to stop themselves
2580                  */
2581                 schedule();
2582
2583                 /* What's a condition variable? */
2584                 while (1) {
2585                         long timeout = start + 10 * HZ - jiffies;
2586
2587                         mutex_lock(&bch_register_lock);
2588                         stopped = list_empty(&bch_cache_sets) &&
2589                                 list_empty(&uncached_devices);
2590
2591                         if (timeout < 0 || stopped)
2592                                 break;
2593
2594                         prepare_to_wait(&unregister_wait, &wait,
2595                                         TASK_UNINTERRUPTIBLE);
2596
2597                         mutex_unlock(&bch_register_lock);
2598                         schedule_timeout(timeout);
2599                 }
2600
2601                 finish_wait(&unregister_wait, &wait);
2602
2603                 if (stopped)
2604                         pr_info("All devices stopped");
2605                 else
2606                         pr_notice("Timeout waiting for devices to be closed");
2607 out:
2608                 mutex_unlock(&bch_register_lock);
2609         }
2610
2611         return NOTIFY_DONE;
2612 }
2613
2614 static struct notifier_block reboot = {
2615         .notifier_call  = bcache_reboot,
2616         .priority       = INT_MAX, /* before any real devices */
2617 };
2618
2619 static void bcache_exit(void)
2620 {
2621         bch_debug_exit();
2622         bch_request_exit();
2623         if (bcache_kobj)
2624                 kobject_put(bcache_kobj);
2625         if (bcache_wq)
2626                 destroy_workqueue(bcache_wq);
2627         if (bch_journal_wq)
2628                 destroy_workqueue(bch_journal_wq);
2629
2630         if (bcache_major)
2631                 unregister_blkdev(bcache_major, "bcache");
2632         unregister_reboot_notifier(&reboot);
2633         mutex_destroy(&bch_register_lock);
2634 }
2635
2636 /* Check and fixup module parameters */
2637 static void check_module_parameters(void)
2638 {
2639         if (bch_cutoff_writeback_sync == 0)
2640                 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
2641         else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
2642                 pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u",
2643                         bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
2644                 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
2645         }
2646
2647         if (bch_cutoff_writeback == 0)
2648                 bch_cutoff_writeback = CUTOFF_WRITEBACK;
2649         else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
2650                 pr_warn("set bch_cutoff_writeback (%u) to max value %u",
2651                         bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
2652                 bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
2653         }
2654
2655         if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
2656                 pr_warn("set bch_cutoff_writeback (%u) to %u",
2657                         bch_cutoff_writeback, bch_cutoff_writeback_sync);
2658                 bch_cutoff_writeback = bch_cutoff_writeback_sync;
2659         }
2660 }
2661
2662 static int __init bcache_init(void)
2663 {
2664         static const struct attribute *files[] = {
2665                 &ksysfs_register.attr,
2666                 &ksysfs_register_quiet.attr,
2667                 &ksysfs_pendings_cleanup.attr,
2668                 NULL
2669         };
2670
2671         check_module_parameters();
2672
2673         mutex_init(&bch_register_lock);
2674         init_waitqueue_head(&unregister_wait);
2675         register_reboot_notifier(&reboot);
2676
2677         bcache_major = register_blkdev(0, "bcache");
2678         if (bcache_major < 0) {
2679                 unregister_reboot_notifier(&reboot);
2680                 mutex_destroy(&bch_register_lock);
2681                 return bcache_major;
2682         }
2683
2684         bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2685         if (!bcache_wq)
2686                 goto err;
2687
2688         bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
2689         if (!bch_journal_wq)
2690                 goto err;
2691
2692         bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2693         if (!bcache_kobj)
2694                 goto err;
2695
2696         if (bch_request_init() ||
2697             sysfs_create_files(bcache_kobj, files))
2698                 goto err;
2699
2700         bch_debug_init();
2701         closure_debug_init();
2702
2703         bcache_is_reboot = false;
2704
2705         return 0;
2706 err:
2707         bcache_exit();
2708         return -ENOMEM;
2709 }
2710
2711 /*
2712  * Module hooks
2713  */
2714 module_exit(bcache_exit);
2715 module_init(bcache_init);
2716
2717 module_param(bch_cutoff_writeback, uint, 0);
2718 MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
2719
2720 module_param(bch_cutoff_writeback_sync, uint, 0);
2721 MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
2722
2723 MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
2724 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
2725 MODULE_LICENSE("GPL");