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