blob: efdf6ce0443ea9694194a06de368f57b34940ce1 [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// 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
David Brazdil0f672f62019-12-10 10:32:29 +000028unsigned int bch_cutoff_writeback;
29unsigned int bch_cutoff_writeback_sync;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000030
31static const char bcache_magic[] = {
32 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
33 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
34};
35
36static const char invalid_uuid[] = {
37 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
38 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
39};
40
41static struct kobject *bcache_kobj;
42struct mutex bch_register_lock;
David Brazdil0f672f62019-12-10 10:32:29 +000043bool bcache_is_reboot;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000044LIST_HEAD(bch_cache_sets);
45static LIST_HEAD(uncached_devices);
46
47static int bcache_major;
48static DEFINE_IDA(bcache_device_idx);
49static wait_queue_head_t unregister_wait;
50struct workqueue_struct *bcache_wq;
Olivier Deprez0e641232021-09-23 10:07:05 +020051struct workqueue_struct *bch_flush_wq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000052struct workqueue_struct *bch_journal_wq;
53
David Brazdil0f672f62019-12-10 10:32:29 +000054
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000055#define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
56/* limitation of partitions number on single bcache device */
57#define BCACHE_MINORS 128
58/* limitation of bcache devices number on single system */
59#define BCACHE_DEVICE_IDX_MAX ((1U << MINORBITS)/BCACHE_MINORS)
60
61/* Superblock */
62
63static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
64 struct page **res)
65{
66 const char *err;
67 struct cache_sb *s;
68 struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
69 unsigned int i;
70
71 if (!bh)
72 return "IO error";
73
74 s = (struct cache_sb *) bh->b_data;
75
76 sb->offset = le64_to_cpu(s->offset);
77 sb->version = le64_to_cpu(s->version);
78
79 memcpy(sb->magic, s->magic, 16);
80 memcpy(sb->uuid, s->uuid, 16);
81 memcpy(sb->set_uuid, s->set_uuid, 16);
82 memcpy(sb->label, s->label, SB_LABEL_SIZE);
83
84 sb->flags = le64_to_cpu(s->flags);
85 sb->seq = le64_to_cpu(s->seq);
86 sb->last_mount = le32_to_cpu(s->last_mount);
87 sb->first_bucket = le16_to_cpu(s->first_bucket);
88 sb->keys = le16_to_cpu(s->keys);
89
90 for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
91 sb->d[i] = le64_to_cpu(s->d[i]);
92
93 pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
94 sb->version, sb->flags, sb->seq, sb->keys);
95
96 err = "Not a bcache superblock";
97 if (sb->offset != SB_SECTOR)
98 goto err;
99
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;
195err:
196 put_bh(bh);
197 return err;
198}
199
200static void write_bdev_super_endio(struct bio *bio)
201{
202 struct cached_dev *dc = bio->bi_private;
David Brazdil0f672f62019-12-10 10:32:29 +0000203
204 if (bio->bi_status)
205 bch_count_backing_io_errors(dc, bio);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000206
207 closure_put(&dc->sb_write);
208}
209
210static void __write_super(struct cache_sb *sb, struct bio *bio)
211{
212 struct cache_sb *out = page_address(bio_first_page_all(bio));
213 unsigned int i;
214
215 bio->bi_iter.bi_sector = SB_SECTOR;
216 bio->bi_iter.bi_size = SB_SIZE;
217 bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC|REQ_META);
218 bch_bio_map(bio, NULL);
219
220 out->offset = cpu_to_le64(sb->offset);
221 out->version = cpu_to_le64(sb->version);
222
223 memcpy(out->uuid, sb->uuid, 16);
224 memcpy(out->set_uuid, sb->set_uuid, 16);
225 memcpy(out->label, sb->label, SB_LABEL_SIZE);
226
227 out->flags = cpu_to_le64(sb->flags);
228 out->seq = cpu_to_le64(sb->seq);
229
230 out->last_mount = cpu_to_le32(sb->last_mount);
231 out->first_bucket = cpu_to_le16(sb->first_bucket);
232 out->keys = cpu_to_le16(sb->keys);
233
234 for (i = 0; i < sb->keys; i++)
235 out->d[i] = cpu_to_le64(sb->d[i]);
236
237 out->csum = csum_set(out);
238
239 pr_debug("ver %llu, flags %llu, seq %llu",
240 sb->version, sb->flags, sb->seq);
241
242 submit_bio(bio);
243}
244
245static 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
252void 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
272static 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
282static 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
289void 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
323static 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
333static 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
340static 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
381static 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
422static int __uuid_write(struct cache_set *c)
423{
424 BKEY_PADDED(key) k;
425 struct closure cl;
David Brazdil0f672f62019-12-10 10:32:29 +0000426 struct cache *ca;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000427
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
David Brazdil0f672f62019-12-10 10:32:29 +0000438 /* 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
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000442 bkey_copy(&c->uuid_bucket, &k.key);
443 bkey_put(c, &k.key);
444 return 0;
445}
446
447int 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
457static 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
469static 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
503static 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
512static 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
Olivier Deprez0e641232021-09-23 10:07:05 +0200533int bch_prio_write(struct cache *ca, bool wait)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000534{
535 int i;
536 struct bucket *b;
537 struct closure cl;
538
Olivier Deprez0e641232021-09-23 10:07:05 +0200539 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
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000556 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
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000565 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
Olivier Deprez0e641232021-09-23 10:07:05 +0200582 bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000583 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 }
Olivier Deprez0e641232021-09-23 10:07:05 +0200611 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000612}
613
614static 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
649static 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
660static 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
667static 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
675static 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
682void bcache_device_stop(struct bcache_device *d)
683{
684 if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
David Brazdil0f672f62019-12-10 10:32:29 +0000685 /*
686 * closure_fn set to
687 * - cached device: cached_dev_flush()
688 * - flash dev: flash_dev_flush()
689 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000690 closure_queue(&d->cl);
691}
692
693static 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
709static 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;
David Brazdil0f672f62019-12-10 10:32:29 +0000714 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000715
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
David Brazdil0f672f62019-12-10 10:32:29 +0000722 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");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000729
730 clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
731}
732
733static 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
755static 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
768static inline int first_minor_to_idx(int first_minor)
769{
770 return (first_minor/BCACHE_MINORS);
771}
772
773static inline int idx_to_first_minor(int idx)
774{
775 return (idx * BCACHE_MINORS);
776}
777
778static void bcache_device_free(struct bcache_device *d)
779{
Olivier Deprez0e641232021-09-23 10:07:05 +0200780 struct gendisk *disk = d->disk;
781
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000782 lockdep_assert_held(&bch_register_lock);
783
Olivier Deprez0e641232021-09-23 10:07:05 +0200784 if (disk)
785 pr_info("%s stopped", disk->disk_name);
786 else
787 pr_err("bcache device (NULL gendisk) stopped");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000788
789 if (d->c)
790 bcache_device_detach(d);
Olivier Deprez0e641232021-09-23 10:07:05 +0200791
792 if (disk) {
793 bool disk_added = (disk->flags & GENHD_FL_UP) != 0;
794
795 if (disk_added)
796 del_gendisk(disk);
797
798 if (disk->queue)
799 blk_cleanup_queue(disk->queue);
800
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000801 ida_simple_remove(&bcache_device_idx,
Olivier Deprez0e641232021-09-23 10:07:05 +0200802 first_minor_to_idx(disk->first_minor));
803 if (disk_added)
804 put_disk(disk);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000805 }
806
807 bioset_exit(&d->bio_split);
808 kvfree(d->full_dirty_stripes);
809 kvfree(d->stripe_sectors_dirty);
810
811 closure_debug_destroy(&d->cl);
812}
813
814static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
815 sector_t sectors)
816{
817 struct request_queue *q;
818 const size_t max_stripes = min_t(size_t, INT_MAX,
819 SIZE_MAX / sizeof(atomic_t));
Olivier Deprez0e641232021-09-23 10:07:05 +0200820 uint64_t n;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000821 int idx;
822
823 if (!d->stripe_size)
824 d->stripe_size = 1 << 31;
825
Olivier Deprez0e641232021-09-23 10:07:05 +0200826 n = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
827 if (!n || n > max_stripes) {
828 pr_err("nr_stripes too large or invalid: %llu (start sector beyond end of disk?)\n",
829 n);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000830 return -ENOMEM;
831 }
Olivier Deprez0e641232021-09-23 10:07:05 +0200832 d->nr_stripes = n;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000833
834 n = d->nr_stripes * sizeof(atomic_t);
835 d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
836 if (!d->stripe_sectors_dirty)
837 return -ENOMEM;
838
839 n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
840 d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
841 if (!d->full_dirty_stripes)
Olivier Deprez0e641232021-09-23 10:07:05 +0200842 goto out_free_stripe_sectors_dirty;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000843
844 idx = ida_simple_get(&bcache_device_idx, 0,
845 BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
846 if (idx < 0)
Olivier Deprez0e641232021-09-23 10:07:05 +0200847 goto out_free_full_dirty_stripes;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000848
849 if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
850 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
Olivier Deprez0e641232021-09-23 10:07:05 +0200851 goto out_ida_remove;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000852
853 d->disk = alloc_disk(BCACHE_MINORS);
854 if (!d->disk)
Olivier Deprez0e641232021-09-23 10:07:05 +0200855 goto out_bioset_exit;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000856
857 set_capacity(d->disk, sectors);
858 snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
859
860 d->disk->major = bcache_major;
861 d->disk->first_minor = idx_to_first_minor(idx);
862 d->disk->fops = &bcache_ops;
863 d->disk->private_data = d;
864
865 q = blk_alloc_queue(GFP_KERNEL);
866 if (!q)
867 return -ENOMEM;
868
869 blk_queue_make_request(q, NULL);
870 d->disk->queue = q;
871 q->queuedata = d;
872 q->backing_dev_info->congested_data = d;
873 q->limits.max_hw_sectors = UINT_MAX;
874 q->limits.max_sectors = UINT_MAX;
875 q->limits.max_segment_size = UINT_MAX;
876 q->limits.max_segments = BIO_MAX_PAGES;
877 blk_queue_max_discard_sectors(q, UINT_MAX);
878 q->limits.discard_granularity = 512;
879 q->limits.io_min = block_size;
880 q->limits.logical_block_size = block_size;
881 q->limits.physical_block_size = block_size;
882 blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
883 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
884 blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
885
886 blk_queue_write_cache(q, true, true);
887
888 return 0;
889
Olivier Deprez0e641232021-09-23 10:07:05 +0200890out_bioset_exit:
891 bioset_exit(&d->bio_split);
892out_ida_remove:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000893 ida_simple_remove(&bcache_device_idx, idx);
Olivier Deprez0e641232021-09-23 10:07:05 +0200894out_free_full_dirty_stripes:
895 kvfree(d->full_dirty_stripes);
896out_free_stripe_sectors_dirty:
897 kvfree(d->stripe_sectors_dirty);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000898 return -ENOMEM;
899
900}
901
902/* Cached device */
903
904static void calc_cached_dev_sectors(struct cache_set *c)
905{
906 uint64_t sectors = 0;
907 struct cached_dev *dc;
908
909 list_for_each_entry(dc, &c->cached_devs, list)
910 sectors += bdev_sectors(dc->bdev);
911
912 c->cached_dev_sectors = sectors;
913}
914
915#define BACKING_DEV_OFFLINE_TIMEOUT 5
916static int cached_dev_status_update(void *arg)
917{
918 struct cached_dev *dc = arg;
919 struct request_queue *q;
920
921 /*
922 * If this delayed worker is stopping outside, directly quit here.
923 * dc->io_disable might be set via sysfs interface, so check it
924 * here too.
925 */
926 while (!kthread_should_stop() && !dc->io_disable) {
927 q = bdev_get_queue(dc->bdev);
928 if (blk_queue_dying(q))
929 dc->offline_seconds++;
930 else
931 dc->offline_seconds = 0;
932
933 if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
934 pr_err("%s: device offline for %d seconds",
935 dc->backing_dev_name,
936 BACKING_DEV_OFFLINE_TIMEOUT);
937 pr_err("%s: disable I/O request due to backing "
938 "device offline", dc->disk.name);
939 dc->io_disable = true;
940 /* let others know earlier that io_disable is true */
941 smp_mb();
942 bcache_device_stop(&dc->disk);
943 break;
944 }
945 schedule_timeout_interruptible(HZ);
946 }
947
948 wait_for_kthread_stop();
949 return 0;
950}
951
952
David Brazdil0f672f62019-12-10 10:32:29 +0000953int bch_cached_dev_run(struct cached_dev *dc)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000954{
955 struct bcache_device *d = &dc->disk;
David Brazdil0f672f62019-12-10 10:32:29 +0000956 char *buf = kmemdup_nul(dc->sb.label, SB_LABEL_SIZE, GFP_KERNEL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000957 char *env[] = {
958 "DRIVER=bcache",
959 kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
David Brazdil0f672f62019-12-10 10:32:29 +0000960 kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf ? : ""),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000961 NULL,
962 };
963
David Brazdil0f672f62019-12-10 10:32:29 +0000964 if (dc->io_disable) {
965 pr_err("I/O disabled on cached dev %s",
966 dc->backing_dev_name);
967 kfree(env[1]);
968 kfree(env[2]);
969 kfree(buf);
970 return -EIO;
971 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000972
973 if (atomic_xchg(&dc->running, 1)) {
974 kfree(env[1]);
975 kfree(env[2]);
David Brazdil0f672f62019-12-10 10:32:29 +0000976 kfree(buf);
977 pr_info("cached dev %s is running already",
978 dc->backing_dev_name);
979 return -EBUSY;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000980 }
981
982 if (!d->c &&
983 BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
984 struct closure cl;
985
986 closure_init_stack(&cl);
987
988 SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
989 bch_write_bdev_super(dc, &cl);
990 closure_sync(&cl);
991 }
992
993 add_disk(d->disk);
994 bd_link_disk_holder(dc->bdev, dc->disk.disk);
995 /*
996 * won't show up in the uevent file, use udevadm monitor -e instead
997 * only class / kset properties are persistent
998 */
999 kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
1000 kfree(env[1]);
1001 kfree(env[2]);
David Brazdil0f672f62019-12-10 10:32:29 +00001002 kfree(buf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001003
1004 if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
David Brazdil0f672f62019-12-10 10:32:29 +00001005 sysfs_create_link(&disk_to_dev(d->disk)->kobj,
1006 &d->kobj, "bcache")) {
1007 pr_err("Couldn't create bcache dev <-> disk sysfs symlinks");
1008 return -ENOMEM;
1009 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001010
1011 dc->status_update_thread = kthread_run(cached_dev_status_update,
1012 dc, "bcache_status_update");
1013 if (IS_ERR(dc->status_update_thread)) {
1014 pr_warn("failed to create bcache_status_update kthread, "
1015 "continue to run without monitoring backing "
1016 "device status");
1017 }
David Brazdil0f672f62019-12-10 10:32:29 +00001018
1019 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001020}
1021
1022/*
1023 * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
1024 * work dc->writeback_rate_update is running. Wait until the routine
1025 * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
1026 * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
1027 * seconds, give up waiting here and continue to cancel it too.
1028 */
1029static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
1030{
1031 int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
1032
1033 do {
1034 if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
1035 &dc->disk.flags))
1036 break;
1037 time_out--;
1038 schedule_timeout_interruptible(1);
1039 } while (time_out > 0);
1040
1041 if (time_out == 0)
1042 pr_warn("give up waiting for dc->writeback_write_update to quit");
1043
1044 cancel_delayed_work_sync(&dc->writeback_rate_update);
1045}
1046
1047static void cached_dev_detach_finish(struct work_struct *w)
1048{
1049 struct cached_dev *dc = container_of(w, struct cached_dev, detach);
1050 struct closure cl;
1051
1052 closure_init_stack(&cl);
1053
1054 BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
1055 BUG_ON(refcount_read(&dc->count));
1056
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001057
1058 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1059 cancel_writeback_rate_update_dwork(dc);
1060
1061 if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
1062 kthread_stop(dc->writeback_thread);
1063 dc->writeback_thread = NULL;
1064 }
1065
1066 memset(&dc->sb.set_uuid, 0, 16);
1067 SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
1068
1069 bch_write_bdev_super(dc, &cl);
1070 closure_sync(&cl);
1071
David Brazdil0f672f62019-12-10 10:32:29 +00001072 mutex_lock(&bch_register_lock);
1073
1074 calc_cached_dev_sectors(dc->disk.c);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001075 bcache_device_detach(&dc->disk);
1076 list_move(&dc->list, &uncached_devices);
1077
1078 clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
1079 clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
1080
1081 mutex_unlock(&bch_register_lock);
1082
1083 pr_info("Caching disabled for %s", dc->backing_dev_name);
1084
1085 /* Drop ref we took in cached_dev_detach() */
1086 closure_put(&dc->disk.cl);
1087}
1088
1089void bch_cached_dev_detach(struct cached_dev *dc)
1090{
1091 lockdep_assert_held(&bch_register_lock);
1092
1093 if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1094 return;
1095
1096 if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
1097 return;
1098
1099 /*
1100 * Block the device from being closed and freed until we're finished
1101 * detaching
1102 */
1103 closure_get(&dc->disk.cl);
1104
1105 bch_writeback_queue(dc);
1106
1107 cached_dev_put(dc);
1108}
1109
1110int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
1111 uint8_t *set_uuid)
1112{
1113 uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
1114 struct uuid_entry *u;
1115 struct cached_dev *exist_dc, *t;
David Brazdil0f672f62019-12-10 10:32:29 +00001116 int ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001117
1118 if ((set_uuid && memcmp(set_uuid, c->sb.set_uuid, 16)) ||
1119 (!set_uuid && memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16)))
1120 return -ENOENT;
1121
1122 if (dc->disk.c) {
1123 pr_err("Can't attach %s: already attached",
1124 dc->backing_dev_name);
1125 return -EINVAL;
1126 }
1127
1128 if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
1129 pr_err("Can't attach %s: shutting down",
1130 dc->backing_dev_name);
1131 return -EINVAL;
1132 }
1133
1134 if (dc->sb.block_size < c->sb.block_size) {
1135 /* Will die */
1136 pr_err("Couldn't attach %s: block size less than set's block size",
1137 dc->backing_dev_name);
1138 return -EINVAL;
1139 }
1140
1141 /* Check whether already attached */
1142 list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
1143 if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
1144 pr_err("Tried to attach %s but duplicate UUID already attached",
1145 dc->backing_dev_name);
1146
1147 return -EINVAL;
1148 }
1149 }
1150
1151 u = uuid_find(c, dc->sb.uuid);
1152
1153 if (u &&
1154 (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1155 BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1156 memcpy(u->uuid, invalid_uuid, 16);
1157 u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1158 u = NULL;
1159 }
1160
1161 if (!u) {
1162 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1163 pr_err("Couldn't find uuid for %s in set",
1164 dc->backing_dev_name);
1165 return -ENOENT;
1166 }
1167
1168 u = uuid_find_empty(c);
1169 if (!u) {
1170 pr_err("Not caching %s, no room for UUID",
1171 dc->backing_dev_name);
1172 return -EINVAL;
1173 }
1174 }
1175
1176 /*
1177 * Deadlocks since we're called via sysfs...
1178 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1179 */
1180
1181 if (bch_is_zero(u->uuid, 16)) {
1182 struct closure cl;
1183
1184 closure_init_stack(&cl);
1185
1186 memcpy(u->uuid, dc->sb.uuid, 16);
1187 memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1188 u->first_reg = u->last_reg = rtime;
1189 bch_uuid_write(c);
1190
1191 memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1192 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1193
1194 bch_write_bdev_super(dc, &cl);
1195 closure_sync(&cl);
1196 } else {
1197 u->last_reg = rtime;
1198 bch_uuid_write(c);
1199 }
1200
1201 bcache_device_attach(&dc->disk, c, u - c->uuids);
1202 list_move(&dc->list, &c->cached_devs);
1203 calc_cached_dev_sectors(c);
1204
1205 /*
1206 * dc->c must be set before dc->count != 0 - paired with the mb in
1207 * cached_dev_get()
1208 */
1209 smp_wmb();
1210 refcount_set(&dc->count, 1);
1211
1212 /* Block writeback thread, but spawn it */
1213 down_write(&dc->writeback_lock);
1214 if (bch_cached_dev_writeback_start(dc)) {
1215 up_write(&dc->writeback_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001216 pr_err("Couldn't start writeback facilities for %s",
1217 dc->disk.disk->disk_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001218 return -ENOMEM;
1219 }
1220
1221 if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1222 atomic_set(&dc->has_dirty, 1);
1223 bch_writeback_queue(dc);
1224 }
1225
1226 bch_sectors_dirty_init(&dc->disk);
1227
David Brazdil0f672f62019-12-10 10:32:29 +00001228 ret = bch_cached_dev_run(dc);
1229 if (ret && (ret != -EBUSY)) {
1230 up_write(&dc->writeback_lock);
1231 /*
1232 * bch_register_lock is held, bcache_device_stop() is not
1233 * able to be directly called. The kthread and kworker
1234 * created previously in bch_cached_dev_writeback_start()
1235 * have to be stopped manually here.
1236 */
1237 kthread_stop(dc->writeback_thread);
1238 cancel_writeback_rate_update_dwork(dc);
1239 pr_err("Couldn't run cached device %s",
1240 dc->backing_dev_name);
1241 return ret;
1242 }
1243
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001244 bcache_device_link(&dc->disk, c, "bdev");
1245 atomic_inc(&c->attached_dev_nr);
1246
1247 /* Allow the writeback thread to proceed */
1248 up_write(&dc->writeback_lock);
1249
1250 pr_info("Caching %s as %s on set %pU",
1251 dc->backing_dev_name,
1252 dc->disk.disk->disk_name,
1253 dc->disk.c->sb.set_uuid);
1254 return 0;
1255}
1256
David Brazdil0f672f62019-12-10 10:32:29 +00001257/* when dc->disk.kobj released */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001258void bch_cached_dev_release(struct kobject *kobj)
1259{
1260 struct cached_dev *dc = container_of(kobj, struct cached_dev,
1261 disk.kobj);
1262 kfree(dc);
1263 module_put(THIS_MODULE);
1264}
1265
1266static void cached_dev_free(struct closure *cl)
1267{
1268 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1269
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001270 if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
1271 cancel_writeback_rate_update_dwork(dc);
1272
1273 if (!IS_ERR_OR_NULL(dc->writeback_thread))
1274 kthread_stop(dc->writeback_thread);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001275 if (!IS_ERR_OR_NULL(dc->status_update_thread))
1276 kthread_stop(dc->status_update_thread);
1277
David Brazdil0f672f62019-12-10 10:32:29 +00001278 mutex_lock(&bch_register_lock);
1279
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001280 if (atomic_read(&dc->running))
1281 bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1282 bcache_device_free(&dc->disk);
1283 list_del(&dc->list);
1284
1285 mutex_unlock(&bch_register_lock);
1286
Olivier Deprez0e641232021-09-23 10:07:05 +02001287 if (dc->sb_bio.bi_inline_vecs[0].bv_page)
1288 put_page(bio_first_page_all(&dc->sb_bio));
1289
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001290 if (!IS_ERR_OR_NULL(dc->bdev))
1291 blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1292
1293 wake_up(&unregister_wait);
1294
1295 kobject_put(&dc->disk.kobj);
1296}
1297
1298static void cached_dev_flush(struct closure *cl)
1299{
1300 struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1301 struct bcache_device *d = &dc->disk;
1302
1303 mutex_lock(&bch_register_lock);
1304 bcache_device_unlink(d);
1305 mutex_unlock(&bch_register_lock);
1306
1307 bch_cache_accounting_destroy(&dc->accounting);
1308 kobject_del(&d->kobj);
1309
1310 continue_at(cl, cached_dev_free, system_wq);
1311}
1312
1313static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1314{
1315 int ret;
1316 struct io *io;
1317 struct request_queue *q = bdev_get_queue(dc->bdev);
1318
1319 __module_get(THIS_MODULE);
1320 INIT_LIST_HEAD(&dc->list);
1321 closure_init(&dc->disk.cl, NULL);
1322 set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1323 kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1324 INIT_WORK(&dc->detach, cached_dev_detach_finish);
1325 sema_init(&dc->sb_write_mutex, 1);
1326 INIT_LIST_HEAD(&dc->io_lru);
1327 spin_lock_init(&dc->io_lock);
1328 bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1329
1330 dc->sequential_cutoff = 4 << 20;
1331
1332 for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1333 list_add(&io->lru, &dc->io_lru);
1334 hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1335 }
1336
1337 dc->disk.stripe_size = q->limits.io_opt >> 9;
1338
1339 if (dc->disk.stripe_size)
1340 dc->partial_stripes_expensive =
1341 q->limits.raid_partial_stripes_expensive;
1342
1343 ret = bcache_device_init(&dc->disk, block_size,
1344 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1345 if (ret)
1346 return ret;
1347
1348 dc->disk.disk->queue->backing_dev_info->ra_pages =
1349 max(dc->disk.disk->queue->backing_dev_info->ra_pages,
1350 q->backing_dev_info->ra_pages);
1351
1352 atomic_set(&dc->io_errors, 0);
1353 dc->io_disable = false;
1354 dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
1355 /* default to auto */
1356 dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
1357
1358 bch_cached_dev_request_init(dc);
1359 bch_cached_dev_writeback_init(dc);
1360 return 0;
1361}
1362
1363/* Cached device - bcache superblock */
1364
David Brazdil0f672f62019-12-10 10:32:29 +00001365static int register_bdev(struct cache_sb *sb, struct page *sb_page,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001366 struct block_device *bdev,
1367 struct cached_dev *dc)
1368{
1369 const char *err = "cannot allocate memory";
1370 struct cache_set *c;
David Brazdil0f672f62019-12-10 10:32:29 +00001371 int ret = -ENOMEM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001372
1373 bdevname(bdev, dc->backing_dev_name);
1374 memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1375 dc->bdev = bdev;
1376 dc->bdev->bd_holder = dc;
1377
1378 bio_init(&dc->sb_bio, dc->sb_bio.bi_inline_vecs, 1);
1379 bio_first_bvec_all(&dc->sb_bio)->bv_page = sb_page;
1380 get_page(sb_page);
1381
1382
1383 if (cached_dev_init(dc, sb->block_size << 9))
1384 goto err;
1385
1386 err = "error creating kobject";
1387 if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1388 "bcache"))
1389 goto err;
1390 if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1391 goto err;
1392
1393 pr_info("registered backing device %s", dc->backing_dev_name);
1394
1395 list_add(&dc->list, &uncached_devices);
1396 /* attach to a matched cache set if it exists */
1397 list_for_each_entry(c, &bch_cache_sets, list)
1398 bch_cached_dev_attach(dc, c, NULL);
1399
1400 if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
David Brazdil0f672f62019-12-10 10:32:29 +00001401 BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
1402 err = "failed to run cached device";
1403 ret = bch_cached_dev_run(dc);
1404 if (ret)
1405 goto err;
1406 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001407
David Brazdil0f672f62019-12-10 10:32:29 +00001408 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001409err:
1410 pr_notice("error %s: %s", dc->backing_dev_name, err);
1411 bcache_device_stop(&dc->disk);
David Brazdil0f672f62019-12-10 10:32:29 +00001412 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001413}
1414
1415/* Flash only volumes */
1416
David Brazdil0f672f62019-12-10 10:32:29 +00001417/* When d->kobj released */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001418void bch_flash_dev_release(struct kobject *kobj)
1419{
1420 struct bcache_device *d = container_of(kobj, struct bcache_device,
1421 kobj);
1422 kfree(d);
1423}
1424
1425static void flash_dev_free(struct closure *cl)
1426{
1427 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1428
1429 mutex_lock(&bch_register_lock);
1430 atomic_long_sub(bcache_dev_sectors_dirty(d),
1431 &d->c->flash_dev_dirty_sectors);
1432 bcache_device_free(d);
1433 mutex_unlock(&bch_register_lock);
1434 kobject_put(&d->kobj);
1435}
1436
1437static void flash_dev_flush(struct closure *cl)
1438{
1439 struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1440
1441 mutex_lock(&bch_register_lock);
1442 bcache_device_unlink(d);
1443 mutex_unlock(&bch_register_lock);
1444 kobject_del(&d->kobj);
1445 continue_at(cl, flash_dev_free, system_wq);
1446}
1447
1448static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1449{
1450 struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1451 GFP_KERNEL);
1452 if (!d)
1453 return -ENOMEM;
1454
1455 closure_init(&d->cl, NULL);
1456 set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1457
1458 kobject_init(&d->kobj, &bch_flash_dev_ktype);
1459
1460 if (bcache_device_init(d, block_bytes(c), u->sectors))
1461 goto err;
1462
1463 bcache_device_attach(d, c, u - c->uuids);
1464 bch_sectors_dirty_init(d);
1465 bch_flash_dev_request_init(d);
1466 add_disk(d->disk);
1467
1468 if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1469 goto err;
1470
1471 bcache_device_link(d, c, "volume");
1472
1473 return 0;
1474err:
1475 kobject_put(&d->kobj);
1476 return -ENOMEM;
1477}
1478
1479static int flash_devs_run(struct cache_set *c)
1480{
1481 int ret = 0;
1482 struct uuid_entry *u;
1483
1484 for (u = c->uuids;
1485 u < c->uuids + c->nr_uuids && !ret;
1486 u++)
1487 if (UUID_FLASH_ONLY(u))
1488 ret = flash_dev_run(c, u);
1489
1490 return ret;
1491}
1492
1493int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1494{
1495 struct uuid_entry *u;
1496
1497 if (test_bit(CACHE_SET_STOPPING, &c->flags))
1498 return -EINTR;
1499
1500 if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1501 return -EPERM;
1502
1503 u = uuid_find_empty(c);
1504 if (!u) {
1505 pr_err("Can't create volume, no room for UUID");
1506 return -EINVAL;
1507 }
1508
1509 get_random_bytes(u->uuid, 16);
1510 memset(u->label, 0, 32);
1511 u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1512
1513 SET_UUID_FLASH_ONLY(u, 1);
1514 u->sectors = size >> 9;
1515
1516 bch_uuid_write(c);
1517
1518 return flash_dev_run(c, u);
1519}
1520
1521bool bch_cached_dev_error(struct cached_dev *dc)
1522{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001523 if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1524 return false;
1525
1526 dc->io_disable = true;
1527 /* make others know io_disable is true earlier */
1528 smp_mb();
1529
1530 pr_err("stop %s: too many IO errors on backing device %s\n",
1531 dc->disk.disk->disk_name, dc->backing_dev_name);
1532
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001533 bcache_device_stop(&dc->disk);
1534 return true;
1535}
1536
1537/* Cache set */
1538
1539__printf(2, 3)
1540bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1541{
1542 va_list args;
1543
1544 if (c->on_error != ON_ERROR_PANIC &&
1545 test_bit(CACHE_SET_STOPPING, &c->flags))
1546 return false;
1547
1548 if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
1549 pr_info("CACHE_SET_IO_DISABLE already set");
1550
1551 /*
1552 * XXX: we can be called from atomic context
1553 * acquire_console_sem();
1554 */
1555
1556 pr_err("bcache: error on %pU: ", c->sb.set_uuid);
1557
1558 va_start(args, fmt);
1559 vprintk(fmt, args);
1560 va_end(args);
1561
1562 pr_err(", disabling caching\n");
1563
1564 if (c->on_error == ON_ERROR_PANIC)
1565 panic("panic forced after error\n");
1566
1567 bch_cache_set_unregister(c);
1568 return true;
1569}
1570
David Brazdil0f672f62019-12-10 10:32:29 +00001571/* When c->kobj released */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001572void bch_cache_set_release(struct kobject *kobj)
1573{
1574 struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1575
1576 kfree(c);
1577 module_put(THIS_MODULE);
1578}
1579
1580static void cache_set_free(struct closure *cl)
1581{
1582 struct cache_set *c = container_of(cl, struct cache_set, cl);
1583 struct cache *ca;
1584 unsigned int i;
1585
David Brazdil0f672f62019-12-10 10:32:29 +00001586 debugfs_remove(c->debug);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001587
1588 bch_open_buckets_free(c);
1589 bch_btree_cache_free(c);
1590 bch_journal_free(c);
1591
David Brazdil0f672f62019-12-10 10:32:29 +00001592 mutex_lock(&bch_register_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001593 for_each_cache(ca, c, i)
1594 if (ca) {
1595 ca->set = NULL;
1596 c->cache[ca->sb.nr_this_dev] = NULL;
1597 kobject_put(&ca->kobj);
1598 }
1599
1600 bch_bset_sort_state_free(&c->sort);
1601 free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1602
1603 if (c->moving_gc_wq)
1604 destroy_workqueue(c->moving_gc_wq);
1605 bioset_exit(&c->bio_split);
1606 mempool_exit(&c->fill_iter);
1607 mempool_exit(&c->bio_meta);
1608 mempool_exit(&c->search);
1609 kfree(c->devices);
1610
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001611 list_del(&c->list);
1612 mutex_unlock(&bch_register_lock);
1613
1614 pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1615 wake_up(&unregister_wait);
1616
1617 closure_debug_destroy(&c->cl);
1618 kobject_put(&c->kobj);
1619}
1620
1621static void cache_set_flush(struct closure *cl)
1622{
1623 struct cache_set *c = container_of(cl, struct cache_set, caching);
1624 struct cache *ca;
1625 struct btree *b;
1626 unsigned int i;
1627
1628 bch_cache_accounting_destroy(&c->accounting);
1629
1630 kobject_put(&c->internal);
1631 kobject_del(&c->kobj);
1632
David Brazdil0f672f62019-12-10 10:32:29 +00001633 if (!IS_ERR_OR_NULL(c->gc_thread))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001634 kthread_stop(c->gc_thread);
1635
1636 if (!IS_ERR_OR_NULL(c->root))
1637 list_add(&c->root->list, &c->btree_cache);
1638
David Brazdil0f672f62019-12-10 10:32:29 +00001639 /*
1640 * Avoid flushing cached nodes if cache set is retiring
1641 * due to too many I/O errors detected.
1642 */
1643 if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1644 list_for_each_entry(b, &c->btree_cache, list) {
1645 mutex_lock(&b->write_lock);
1646 if (btree_node_dirty(b))
1647 __bch_btree_node_write(b, NULL);
1648 mutex_unlock(&b->write_lock);
1649 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001650
1651 for_each_cache(ca, c, i)
1652 if (ca->alloc_thread)
1653 kthread_stop(ca->alloc_thread);
1654
1655 if (c->journal.cur) {
1656 cancel_delayed_work_sync(&c->journal.work);
1657 /* flush last journal entry if needed */
1658 c->journal.work.work.func(&c->journal.work.work);
1659 }
1660
1661 closure_return(cl);
1662}
1663
1664/*
1665 * This function is only called when CACHE_SET_IO_DISABLE is set, which means
1666 * cache set is unregistering due to too many I/O errors. In this condition,
1667 * the bcache device might be stopped, it depends on stop_when_cache_set_failed
1668 * value and whether the broken cache has dirty data:
1669 *
1670 * dc->stop_when_cache_set_failed dc->has_dirty stop bcache device
1671 * BCH_CACHED_STOP_AUTO 0 NO
1672 * BCH_CACHED_STOP_AUTO 1 YES
1673 * BCH_CACHED_DEV_STOP_ALWAYS 0 YES
1674 * BCH_CACHED_DEV_STOP_ALWAYS 1 YES
1675 *
1676 * The expected behavior is, if stop_when_cache_set_failed is configured to
1677 * "auto" via sysfs interface, the bcache device will not be stopped if the
1678 * backing device is clean on the broken cache device.
1679 */
1680static void conditional_stop_bcache_device(struct cache_set *c,
1681 struct bcache_device *d,
1682 struct cached_dev *dc)
1683{
1684 if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
1685 pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.",
1686 d->disk->disk_name, c->sb.set_uuid);
1687 bcache_device_stop(d);
1688 } else if (atomic_read(&dc->has_dirty)) {
1689 /*
1690 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1691 * and dc->has_dirty == 1
1692 */
1693 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.",
1694 d->disk->disk_name);
David Brazdil0f672f62019-12-10 10:32:29 +00001695 /*
1696 * There might be a small time gap that cache set is
1697 * released but bcache device is not. Inside this time
1698 * gap, regular I/O requests will directly go into
1699 * backing device as no cache set attached to. This
1700 * behavior may also introduce potential inconsistence
1701 * data in writeback mode while cache is dirty.
1702 * Therefore before calling bcache_device_stop() due
1703 * to a broken cache device, dc->io_disable should be
1704 * explicitly set to true.
1705 */
1706 dc->io_disable = true;
1707 /* make others know io_disable is true earlier */
1708 smp_mb();
1709 bcache_device_stop(d);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001710 } else {
1711 /*
1712 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
1713 * and dc->has_dirty == 0
1714 */
1715 pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.",
1716 d->disk->disk_name);
1717 }
1718}
1719
1720static void __cache_set_unregister(struct closure *cl)
1721{
1722 struct cache_set *c = container_of(cl, struct cache_set, caching);
1723 struct cached_dev *dc;
1724 struct bcache_device *d;
1725 size_t i;
1726
1727 mutex_lock(&bch_register_lock);
1728
1729 for (i = 0; i < c->devices_max_used; i++) {
1730 d = c->devices[i];
1731 if (!d)
1732 continue;
1733
1734 if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
1735 test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
1736 dc = container_of(d, struct cached_dev, disk);
1737 bch_cached_dev_detach(dc);
1738 if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
1739 conditional_stop_bcache_device(c, d, dc);
1740 } else {
1741 bcache_device_stop(d);
1742 }
1743 }
1744
1745 mutex_unlock(&bch_register_lock);
1746
1747 continue_at(cl, cache_set_flush, system_wq);
1748}
1749
1750void bch_cache_set_stop(struct cache_set *c)
1751{
1752 if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
David Brazdil0f672f62019-12-10 10:32:29 +00001753 /* closure_fn set to __cache_set_unregister() */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001754 closure_queue(&c->caching);
1755}
1756
1757void bch_cache_set_unregister(struct cache_set *c)
1758{
1759 set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1760 bch_cache_set_stop(c);
1761}
1762
1763#define alloc_bucket_pages(gfp, c) \
Olivier Deprez0e641232021-09-23 10:07:05 +02001764 ((void *) __get_free_pages(__GFP_ZERO|__GFP_COMP|gfp, ilog2(bucket_pages(c))))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001765
1766struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1767{
1768 int iter_size;
1769 struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1770
1771 if (!c)
1772 return NULL;
1773
1774 __module_get(THIS_MODULE);
1775 closure_init(&c->cl, NULL);
1776 set_closure_fn(&c->cl, cache_set_free, system_wq);
1777
1778 closure_init(&c->caching, &c->cl);
1779 set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1780
1781 /* Maybe create continue_at_noreturn() and use it here? */
1782 closure_set_stopped(&c->cl);
1783 closure_put(&c->cl);
1784
1785 kobject_init(&c->kobj, &bch_cache_set_ktype);
1786 kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1787
1788 bch_cache_accounting_init(&c->accounting, &c->cl);
1789
1790 memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1791 c->sb.block_size = sb->block_size;
1792 c->sb.bucket_size = sb->bucket_size;
1793 c->sb.nr_in_set = sb->nr_in_set;
1794 c->sb.last_mount = sb->last_mount;
1795 c->bucket_bits = ilog2(sb->bucket_size);
1796 c->block_bits = ilog2(sb->block_size);
1797 c->nr_uuids = bucket_bytes(c) / sizeof(struct uuid_entry);
1798 c->devices_max_used = 0;
1799 atomic_set(&c->attached_dev_nr, 0);
1800 c->btree_pages = bucket_pages(c);
1801 if (c->btree_pages > BTREE_MAX_PAGES)
1802 c->btree_pages = max_t(int, c->btree_pages / 4,
1803 BTREE_MAX_PAGES);
1804
1805 sema_init(&c->sb_write_mutex, 1);
1806 mutex_init(&c->bucket_lock);
1807 init_waitqueue_head(&c->btree_cache_wait);
Olivier Deprez0e641232021-09-23 10:07:05 +02001808 spin_lock_init(&c->btree_cannibalize_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001809 init_waitqueue_head(&c->bucket_wait);
1810 init_waitqueue_head(&c->gc_wait);
1811 sema_init(&c->uuid_write_mutex, 1);
1812
1813 spin_lock_init(&c->btree_gc_time.lock);
1814 spin_lock_init(&c->btree_split_time.lock);
1815 spin_lock_init(&c->btree_read_time.lock);
1816
1817 bch_moving_init_cache_set(c);
1818
1819 INIT_LIST_HEAD(&c->list);
1820 INIT_LIST_HEAD(&c->cached_devs);
1821 INIT_LIST_HEAD(&c->btree_cache);
1822 INIT_LIST_HEAD(&c->btree_cache_freeable);
1823 INIT_LIST_HEAD(&c->btree_cache_freed);
1824 INIT_LIST_HEAD(&c->data_buckets);
1825
1826 iter_size = (sb->bucket_size / sb->block_size + 1) *
1827 sizeof(struct btree_iter_set);
1828
1829 if (!(c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL)) ||
1830 mempool_init_slab_pool(&c->search, 32, bch_search_cache) ||
1831 mempool_init_kmalloc_pool(&c->bio_meta, 2,
1832 sizeof(struct bbio) + sizeof(struct bio_vec) *
1833 bucket_pages(c)) ||
1834 mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
1835 bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1836 BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER) ||
1837 !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1838 !(c->moving_gc_wq = alloc_workqueue("bcache_gc",
1839 WQ_MEM_RECLAIM, 0)) ||
1840 bch_journal_alloc(c) ||
1841 bch_btree_cache_alloc(c) ||
1842 bch_open_buckets_alloc(c) ||
1843 bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1844 goto err;
1845
1846 c->congested_read_threshold_us = 2000;
1847 c->congested_write_threshold_us = 20000;
1848 c->error_limit = DEFAULT_IO_ERROR_LIMIT;
1849 WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1850
1851 return c;
1852err:
1853 bch_cache_set_unregister(c);
1854 return NULL;
1855}
1856
David Brazdil0f672f62019-12-10 10:32:29 +00001857static int run_cache_set(struct cache_set *c)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001858{
1859 const char *err = "cannot allocate memory";
1860 struct cached_dev *dc, *t;
1861 struct cache *ca;
1862 struct closure cl;
1863 unsigned int i;
David Brazdil0f672f62019-12-10 10:32:29 +00001864 LIST_HEAD(journal);
1865 struct journal_replay *l;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001866
1867 closure_init_stack(&cl);
1868
1869 for_each_cache(ca, c, i)
1870 c->nbuckets += ca->sb.nbuckets;
1871 set_gc_sectors(c);
1872
1873 if (CACHE_SYNC(&c->sb)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001874 struct bkey *k;
1875 struct jset *j;
1876
1877 err = "cannot allocate memory for journal";
1878 if (bch_journal_read(c, &journal))
1879 goto err;
1880
1881 pr_debug("btree_journal_read() done");
1882
1883 err = "no journal entries found";
1884 if (list_empty(&journal))
1885 goto err;
1886
1887 j = &list_entry(journal.prev, struct journal_replay, list)->j;
1888
1889 err = "IO error reading priorities";
1890 for_each_cache(ca, c, i)
1891 prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1892
1893 /*
1894 * If prio_read() fails it'll call cache_set_error and we'll
1895 * tear everything down right away, but if we perhaps checked
1896 * sooner we could avoid journal replay.
1897 */
1898
1899 k = &j->btree_root;
1900
1901 err = "bad btree root";
1902 if (__bch_btree_ptr_invalid(c, k))
1903 goto err;
1904
1905 err = "error reading btree root";
1906 c->root = bch_btree_node_get(c, NULL, k,
1907 j->btree_level,
1908 true, NULL);
1909 if (IS_ERR_OR_NULL(c->root))
1910 goto err;
1911
1912 list_del_init(&c->root->list);
1913 rw_unlock(true, c->root);
1914
1915 err = uuid_read(c, j, &cl);
1916 if (err)
1917 goto err;
1918
1919 err = "error in recovery";
1920 if (bch_btree_check(c))
1921 goto err;
1922
David Brazdil0f672f62019-12-10 10:32:29 +00001923 /*
1924 * bch_btree_check() may occupy too much system memory which
1925 * has negative effects to user space application (e.g. data
1926 * base) performance. Shrink the mca cache memory proactively
1927 * here to avoid competing memory with user space workloads..
1928 */
1929 if (!c->shrinker_disabled) {
1930 struct shrink_control sc;
1931
1932 sc.gfp_mask = GFP_KERNEL;
1933 sc.nr_to_scan = c->btree_cache_used * c->btree_pages;
1934 /* first run to clear b->accessed tag */
1935 c->shrink.scan_objects(&c->shrink, &sc);
1936 /* second run to reap non-accessed nodes */
1937 c->shrink.scan_objects(&c->shrink, &sc);
1938 }
1939
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001940 bch_journal_mark(c, &journal);
1941 bch_initial_gc_finish(c);
1942 pr_debug("btree_check() done");
1943
1944 /*
1945 * bcache_journal_next() can't happen sooner, or
1946 * btree_gc_finish() will give spurious errors about last_gc >
1947 * gc_gen - this is a hack but oh well.
1948 */
1949 bch_journal_next(&c->journal);
1950
1951 err = "error starting allocator thread";
1952 for_each_cache(ca, c, i)
1953 if (bch_cache_allocator_start(ca))
1954 goto err;
1955
1956 /*
1957 * First place it's safe to allocate: btree_check() and
1958 * btree_gc_finish() have to run before we have buckets to
1959 * allocate, and bch_bucket_alloc_set() might cause a journal
1960 * entry to be written so bcache_journal_next() has to be called
1961 * first.
1962 *
1963 * If the uuids were in the old format we have to rewrite them
1964 * before the next journal entry is written:
1965 */
1966 if (j->version < BCACHE_JSET_VERSION_UUID)
1967 __uuid_write(c);
1968
David Brazdil0f672f62019-12-10 10:32:29 +00001969 err = "bcache: replay journal failed";
1970 if (bch_journal_replay(c, &journal))
1971 goto err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001972 } else {
1973 pr_notice("invalidating existing data");
1974
1975 for_each_cache(ca, c, i) {
1976 unsigned int j;
1977
1978 ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1979 2, SB_JOURNAL_BUCKETS);
1980
1981 for (j = 0; j < ca->sb.keys; j++)
1982 ca->sb.d[j] = ca->sb.first_bucket + j;
1983 }
1984
1985 bch_initial_gc_finish(c);
1986
1987 err = "error starting allocator thread";
1988 for_each_cache(ca, c, i)
1989 if (bch_cache_allocator_start(ca))
1990 goto err;
1991
1992 mutex_lock(&c->bucket_lock);
1993 for_each_cache(ca, c, i)
Olivier Deprez0e641232021-09-23 10:07:05 +02001994 bch_prio_write(ca, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001995 mutex_unlock(&c->bucket_lock);
1996
1997 err = "cannot allocate new UUID bucket";
1998 if (__uuid_write(c))
1999 goto err;
2000
2001 err = "cannot allocate new btree root";
2002 c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
2003 if (IS_ERR_OR_NULL(c->root))
2004 goto err;
2005
2006 mutex_lock(&c->root->write_lock);
2007 bkey_copy_key(&c->root->key, &MAX_KEY);
2008 bch_btree_node_write(c->root, &cl);
2009 mutex_unlock(&c->root->write_lock);
2010
2011 bch_btree_set_root(c->root);
2012 rw_unlock(true, c->root);
2013
2014 /*
2015 * We don't want to write the first journal entry until
2016 * everything is set up - fortunately journal entries won't be
2017 * written until the SET_CACHE_SYNC() here:
2018 */
2019 SET_CACHE_SYNC(&c->sb, true);
2020
2021 bch_journal_next(&c->journal);
2022 bch_journal_meta(c, &cl);
2023 }
2024
2025 err = "error starting gc thread";
2026 if (bch_gc_thread_start(c))
2027 goto err;
2028
2029 closure_sync(&cl);
2030 c->sb.last_mount = (u32)ktime_get_real_seconds();
2031 bcache_write_super(c);
2032
2033 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2034 bch_cached_dev_attach(dc, c, NULL);
2035
2036 flash_devs_run(c);
2037
2038 set_bit(CACHE_SET_RUNNING, &c->flags);
David Brazdil0f672f62019-12-10 10:32:29 +00002039 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002040err:
David Brazdil0f672f62019-12-10 10:32:29 +00002041 while (!list_empty(&journal)) {
2042 l = list_first_entry(&journal, struct journal_replay, list);
2043 list_del(&l->list);
2044 kfree(l);
2045 }
2046
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002047 closure_sync(&cl);
David Brazdil0f672f62019-12-10 10:32:29 +00002048
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002049 bch_cache_set_error(c, "%s", err);
David Brazdil0f672f62019-12-10 10:32:29 +00002050
2051 return -EIO;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002052}
2053
2054static bool can_attach_cache(struct cache *ca, struct cache_set *c)
2055{
2056 return ca->sb.block_size == c->sb.block_size &&
2057 ca->sb.bucket_size == c->sb.bucket_size &&
2058 ca->sb.nr_in_set == c->sb.nr_in_set;
2059}
2060
2061static const char *register_cache_set(struct cache *ca)
2062{
2063 char buf[12];
2064 const char *err = "cannot allocate memory";
2065 struct cache_set *c;
2066
2067 list_for_each_entry(c, &bch_cache_sets, list)
2068 if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
2069 if (c->cache[ca->sb.nr_this_dev])
2070 return "duplicate cache set member";
2071
2072 if (!can_attach_cache(ca, c))
2073 return "cache sb does not match set";
2074
2075 if (!CACHE_SYNC(&ca->sb))
2076 SET_CACHE_SYNC(&c->sb, false);
2077
2078 goto found;
2079 }
2080
2081 c = bch_cache_set_alloc(&ca->sb);
2082 if (!c)
2083 return err;
2084
2085 err = "error creating kobject";
2086 if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
2087 kobject_add(&c->internal, &c->kobj, "internal"))
2088 goto err;
2089
2090 if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2091 goto err;
2092
2093 bch_debug_init_cache_set(c);
2094
2095 list_add(&c->list, &bch_cache_sets);
2096found:
2097 sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2098 if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2099 sysfs_create_link(&c->kobj, &ca->kobj, buf))
2100 goto err;
2101
Olivier Deprez0e641232021-09-23 10:07:05 +02002102 /*
2103 * A special case is both ca->sb.seq and c->sb.seq are 0,
2104 * such condition happens on a new created cache device whose
2105 * super block is never flushed yet. In this case c->sb.version
2106 * and other members should be updated too, otherwise we will
2107 * have a mistaken super block version in cache set.
2108 */
2109 if (ca->sb.seq > c->sb.seq || c->sb.seq == 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002110 c->sb.version = ca->sb.version;
2111 memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
2112 c->sb.flags = ca->sb.flags;
2113 c->sb.seq = ca->sb.seq;
2114 pr_debug("set version = %llu", c->sb.version);
2115 }
2116
2117 kobject_get(&ca->kobj);
2118 ca->set = c;
2119 ca->set->cache[ca->sb.nr_this_dev] = ca;
2120 c->cache_by_alloc[c->caches_loaded++] = ca;
2121
David Brazdil0f672f62019-12-10 10:32:29 +00002122 if (c->caches_loaded == c->sb.nr_in_set) {
2123 err = "failed to run cache set";
2124 if (run_cache_set(c) < 0)
2125 goto err;
2126 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002127
2128 return NULL;
2129err:
2130 bch_cache_set_unregister(c);
2131 return err;
2132}
2133
2134/* Cache device */
2135
David Brazdil0f672f62019-12-10 10:32:29 +00002136/* When ca->kobj released */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002137void bch_cache_release(struct kobject *kobj)
2138{
2139 struct cache *ca = container_of(kobj, struct cache, kobj);
2140 unsigned int i;
2141
2142 if (ca->set) {
2143 BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
2144 ca->set->cache[ca->sb.nr_this_dev] = NULL;
2145 }
2146
2147 free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
2148 kfree(ca->prio_buckets);
2149 vfree(ca->buckets);
2150
2151 free_heap(&ca->heap);
2152 free_fifo(&ca->free_inc);
2153
2154 for (i = 0; i < RESERVE_NR; i++)
2155 free_fifo(&ca->free[i]);
2156
2157 if (ca->sb_bio.bi_inline_vecs[0].bv_page)
2158 put_page(bio_first_page_all(&ca->sb_bio));
2159
2160 if (!IS_ERR_OR_NULL(ca->bdev))
2161 blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2162
2163 kfree(ca);
2164 module_put(THIS_MODULE);
2165}
2166
2167static int cache_alloc(struct cache *ca)
2168{
2169 size_t free;
2170 size_t btree_buckets;
2171 struct bucket *b;
David Brazdil0f672f62019-12-10 10:32:29 +00002172 int ret = -ENOMEM;
2173 const char *err = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002174
2175 __module_get(THIS_MODULE);
2176 kobject_init(&ca->kobj, &bch_cache_ktype);
2177
2178 bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2179
2180 /*
2181 * when ca->sb.njournal_buckets is not zero, journal exists,
2182 * and in bch_journal_replay(), tree node may split,
2183 * so bucket of RESERVE_BTREE type is needed,
2184 * the worst situation is all journal buckets are valid journal,
2185 * and all the keys need to replay,
2186 * so the number of RESERVE_BTREE type buckets should be as much
2187 * as journal buckets
2188 */
2189 btree_buckets = ca->sb.njournal_buckets ?: 8;
2190 free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
David Brazdil0f672f62019-12-10 10:32:29 +00002191 if (!free) {
2192 ret = -EPERM;
2193 err = "ca->sb.nbuckets is too small";
2194 goto err_free;
2195 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002196
David Brazdil0f672f62019-12-10 10:32:29 +00002197 if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
2198 GFP_KERNEL)) {
2199 err = "ca->free[RESERVE_BTREE] alloc failed";
2200 goto err_btree_alloc;
2201 }
2202
2203 if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
2204 GFP_KERNEL)) {
2205 err = "ca->free[RESERVE_PRIO] alloc failed";
2206 goto err_prio_alloc;
2207 }
2208
2209 if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
2210 err = "ca->free[RESERVE_MOVINGGC] alloc failed";
2211 goto err_movinggc_alloc;
2212 }
2213
2214 if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
2215 err = "ca->free[RESERVE_NONE] alloc failed";
2216 goto err_none_alloc;
2217 }
2218
2219 if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
2220 err = "ca->free_inc alloc failed";
2221 goto err_free_inc_alloc;
2222 }
2223
2224 if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
2225 err = "ca->heap alloc failed";
2226 goto err_heap_alloc;
2227 }
2228
2229 ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2230 ca->sb.nbuckets));
2231 if (!ca->buckets) {
2232 err = "ca->buckets alloc failed";
2233 goto err_buckets_alloc;
2234 }
2235
2236 ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
2237 prio_buckets(ca), 2),
2238 GFP_KERNEL);
2239 if (!ca->prio_buckets) {
2240 err = "ca->prio_buckets alloc failed";
2241 goto err_prio_buckets_alloc;
2242 }
2243
2244 ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca);
2245 if (!ca->disk_buckets) {
2246 err = "ca->disk_buckets alloc failed";
2247 goto err_disk_buckets_alloc;
2248 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002249
2250 ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2251
2252 for_each_bucket(b, ca)
2253 atomic_set(&b->pin, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002254 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002255
2256err_disk_buckets_alloc:
2257 kfree(ca->prio_buckets);
2258err_prio_buckets_alloc:
2259 vfree(ca->buckets);
2260err_buckets_alloc:
2261 free_heap(&ca->heap);
2262err_heap_alloc:
2263 free_fifo(&ca->free_inc);
2264err_free_inc_alloc:
2265 free_fifo(&ca->free[RESERVE_NONE]);
2266err_none_alloc:
2267 free_fifo(&ca->free[RESERVE_MOVINGGC]);
2268err_movinggc_alloc:
2269 free_fifo(&ca->free[RESERVE_PRIO]);
2270err_prio_alloc:
2271 free_fifo(&ca->free[RESERVE_BTREE]);
2272err_btree_alloc:
2273err_free:
2274 module_put(THIS_MODULE);
2275 if (err)
2276 pr_notice("error %s: %s", ca->cache_dev_name, err);
2277 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002278}
2279
2280static int register_cache(struct cache_sb *sb, struct page *sb_page,
2281 struct block_device *bdev, struct cache *ca)
2282{
2283 const char *err = NULL; /* must be set for any error case */
2284 int ret = 0;
2285
2286 bdevname(bdev, ca->cache_dev_name);
2287 memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2288 ca->bdev = bdev;
2289 ca->bdev->bd_holder = ca;
2290
2291 bio_init(&ca->sb_bio, ca->sb_bio.bi_inline_vecs, 1);
2292 bio_first_bvec_all(&ca->sb_bio)->bv_page = sb_page;
2293 get_page(sb_page);
2294
2295 if (blk_queue_discard(bdev_get_queue(bdev)))
2296 ca->discard = CACHE_DISCARD(&ca->sb);
2297
2298 ret = cache_alloc(ca);
2299 if (ret != 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00002300 /*
2301 * If we failed here, it means ca->kobj is not initialized yet,
2302 * kobject_put() won't be called and there is no chance to
2303 * call blkdev_put() to bdev in bch_cache_release(). So we
2304 * explicitly call blkdev_put() here.
2305 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002306 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2307 if (ret == -ENOMEM)
2308 err = "cache_alloc(): -ENOMEM";
David Brazdil0f672f62019-12-10 10:32:29 +00002309 else if (ret == -EPERM)
2310 err = "cache_alloc(): cache device is too small";
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002311 else
2312 err = "cache_alloc(): unknown error";
2313 goto err;
2314 }
2315
2316 if (kobject_add(&ca->kobj,
2317 &part_to_dev(bdev->bd_part)->kobj,
2318 "bcache")) {
2319 err = "error calling kobject_add";
2320 ret = -ENOMEM;
2321 goto out;
2322 }
2323
2324 mutex_lock(&bch_register_lock);
2325 err = register_cache_set(ca);
2326 mutex_unlock(&bch_register_lock);
2327
2328 if (err) {
2329 ret = -ENODEV;
2330 goto out;
2331 }
2332
2333 pr_info("registered cache device %s", ca->cache_dev_name);
2334
2335out:
2336 kobject_put(&ca->kobj);
2337
2338err:
2339 if (err)
2340 pr_notice("error %s: %s", ca->cache_dev_name, err);
2341
2342 return ret;
2343}
2344
2345/* Global interfaces/init */
2346
2347static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2348 const char *buffer, size_t size);
David Brazdil0f672f62019-12-10 10:32:29 +00002349static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2350 struct kobj_attribute *attr,
2351 const char *buffer, size_t size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002352
2353kobj_attribute_write(register, register_bcache);
2354kobj_attribute_write(register_quiet, register_bcache);
David Brazdil0f672f62019-12-10 10:32:29 +00002355kobj_attribute_write(pendings_cleanup, bch_pending_bdevs_cleanup);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002356
2357static bool bch_is_open_backing(struct block_device *bdev)
2358{
2359 struct cache_set *c, *tc;
2360 struct cached_dev *dc, *t;
2361
2362 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2363 list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2364 if (dc->bdev == bdev)
2365 return true;
2366 list_for_each_entry_safe(dc, t, &uncached_devices, list)
2367 if (dc->bdev == bdev)
2368 return true;
2369 return false;
2370}
2371
2372static bool bch_is_open_cache(struct block_device *bdev)
2373{
2374 struct cache_set *c, *tc;
2375 struct cache *ca;
2376 unsigned int i;
2377
2378 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2379 for_each_cache(ca, c, i)
2380 if (ca->bdev == bdev)
2381 return true;
2382 return false;
2383}
2384
2385static bool bch_is_open(struct block_device *bdev)
2386{
2387 return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2388}
2389
2390static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2391 const char *buffer, size_t size)
2392{
Olivier Deprez0e641232021-09-23 10:07:05 +02002393 const char *err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002394 char *path = NULL;
Olivier Deprez0e641232021-09-23 10:07:05 +02002395 struct cache_sb *sb;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002396 struct block_device *bdev = NULL;
Olivier Deprez0e641232021-09-23 10:07:05 +02002397 struct page *sb_page;
2398 ssize_t ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002399
Olivier Deprez0e641232021-09-23 10:07:05 +02002400 ret = -EBUSY;
2401 err = "failed to reference bcache module";
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002402 if (!try_module_get(THIS_MODULE))
Olivier Deprez0e641232021-09-23 10:07:05 +02002403 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002404
David Brazdil0f672f62019-12-10 10:32:29 +00002405 /* For latest state of bcache_is_reboot */
2406 smp_mb();
Olivier Deprez0e641232021-09-23 10:07:05 +02002407 err = "bcache is in reboot";
David Brazdil0f672f62019-12-10 10:32:29 +00002408 if (bcache_is_reboot)
Olivier Deprez0e641232021-09-23 10:07:05 +02002409 goto out_module_put;
David Brazdil0f672f62019-12-10 10:32:29 +00002410
Olivier Deprez0e641232021-09-23 10:07:05 +02002411 ret = -ENOMEM;
2412 err = "cannot allocate memory";
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002413 path = kstrndup(buffer, size, GFP_KERNEL);
2414 if (!path)
Olivier Deprez0e641232021-09-23 10:07:05 +02002415 goto out_module_put;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002416
2417 sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2418 if (!sb)
Olivier Deprez0e641232021-09-23 10:07:05 +02002419 goto out_free_path;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002420
Olivier Deprez0e641232021-09-23 10:07:05 +02002421 ret = -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002422 err = "failed to open device";
2423 bdev = blkdev_get_by_path(strim(path),
2424 FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2425 sb);
2426 if (IS_ERR(bdev)) {
2427 if (bdev == ERR_PTR(-EBUSY)) {
2428 bdev = lookup_bdev(strim(path));
2429 mutex_lock(&bch_register_lock);
2430 if (!IS_ERR(bdev) && bch_is_open(bdev))
2431 err = "device already registered";
2432 else
2433 err = "device busy";
2434 mutex_unlock(&bch_register_lock);
2435 if (!IS_ERR(bdev))
2436 bdput(bdev);
2437 if (attr == &ksysfs_register_quiet)
Olivier Deprez0e641232021-09-23 10:07:05 +02002438 goto done;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002439 }
Olivier Deprez0e641232021-09-23 10:07:05 +02002440 goto out_free_sb;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002441 }
2442
2443 err = "failed to set blocksize";
2444 if (set_blocksize(bdev, 4096))
Olivier Deprez0e641232021-09-23 10:07:05 +02002445 goto out_blkdev_put;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002446
2447 err = read_super(sb, bdev, &sb_page);
2448 if (err)
Olivier Deprez0e641232021-09-23 10:07:05 +02002449 goto out_blkdev_put;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002450
2451 err = "failed to register device";
2452 if (SB_IS_BDEV(sb)) {
2453 struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
2454
2455 if (!dc)
Olivier Deprez0e641232021-09-23 10:07:05 +02002456 goto out_put_sb_page;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002457
2458 mutex_lock(&bch_register_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00002459 ret = register_bdev(sb, sb_page, bdev, dc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002460 mutex_unlock(&bch_register_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00002461 /* blkdev_put() will be called in cached_dev_free() */
Olivier Deprez0e641232021-09-23 10:07:05 +02002462 if (ret < 0) {
2463 bdev = NULL;
2464 goto out_put_sb_page;
2465 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002466 } else {
2467 struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2468
2469 if (!ca)
Olivier Deprez0e641232021-09-23 10:07:05 +02002470 goto out_put_sb_page;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002471
David Brazdil0f672f62019-12-10 10:32:29 +00002472 /* blkdev_put() will be called in bch_cache_release() */
Olivier Deprez0e641232021-09-23 10:07:05 +02002473 if (register_cache(sb, sb_page, bdev, ca) != 0) {
2474 bdev = NULL;
2475 goto out_put_sb_page;
2476 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002477 }
Olivier Deprez0e641232021-09-23 10:07:05 +02002478
2479 put_page(sb_page);
2480done:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002481 kfree(sb);
2482 kfree(path);
2483 module_put(THIS_MODULE);
Olivier Deprez0e641232021-09-23 10:07:05 +02002484 return size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002485
Olivier Deprez0e641232021-09-23 10:07:05 +02002486out_put_sb_page:
2487 put_page(sb_page);
2488out_blkdev_put:
2489 if (bdev)
2490 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2491out_free_sb:
2492 kfree(sb);
2493out_free_path:
2494 kfree(path);
2495 path = NULL;
2496out_module_put:
2497 module_put(THIS_MODULE);
2498out:
2499 pr_info("error %s: %s", path?path:"", err);
2500 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002501}
2502
David Brazdil0f672f62019-12-10 10:32:29 +00002503
2504struct pdev {
2505 struct list_head list;
2506 struct cached_dev *dc;
2507};
2508
2509static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
2510 struct kobj_attribute *attr,
2511 const char *buffer,
2512 size_t size)
2513{
2514 LIST_HEAD(pending_devs);
2515 ssize_t ret = size;
2516 struct cached_dev *dc, *tdc;
2517 struct pdev *pdev, *tpdev;
2518 struct cache_set *c, *tc;
2519
2520 mutex_lock(&bch_register_lock);
2521 list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
2522 pdev = kmalloc(sizeof(struct pdev), GFP_KERNEL);
2523 if (!pdev)
2524 break;
2525 pdev->dc = dc;
2526 list_add(&pdev->list, &pending_devs);
2527 }
2528
2529 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2530 list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
2531 char *pdev_set_uuid = pdev->dc->sb.set_uuid;
2532 char *set_uuid = c->sb.uuid;
2533
2534 if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
2535 list_del(&pdev->list);
2536 kfree(pdev);
2537 break;
2538 }
2539 }
2540 }
2541 mutex_unlock(&bch_register_lock);
2542
2543 list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
2544 pr_info("delete pdev %p", pdev);
2545 list_del(&pdev->list);
2546 bcache_device_stop(&pdev->dc->disk);
2547 kfree(pdev);
2548 }
2549
2550 return ret;
2551}
2552
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002553static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2554{
David Brazdil0f672f62019-12-10 10:32:29 +00002555 if (bcache_is_reboot)
2556 return NOTIFY_DONE;
2557
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002558 if (code == SYS_DOWN ||
2559 code == SYS_HALT ||
2560 code == SYS_POWER_OFF) {
2561 DEFINE_WAIT(wait);
2562 unsigned long start = jiffies;
2563 bool stopped = false;
2564
2565 struct cache_set *c, *tc;
2566 struct cached_dev *dc, *tdc;
2567
2568 mutex_lock(&bch_register_lock);
2569
David Brazdil0f672f62019-12-10 10:32:29 +00002570 if (bcache_is_reboot)
2571 goto out;
2572
2573 /* New registration is rejected since now */
2574 bcache_is_reboot = true;
2575 /*
2576 * Make registering caller (if there is) on other CPU
2577 * core know bcache_is_reboot set to true earlier
2578 */
2579 smp_mb();
2580
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002581 if (list_empty(&bch_cache_sets) &&
2582 list_empty(&uncached_devices))
2583 goto out;
2584
David Brazdil0f672f62019-12-10 10:32:29 +00002585 mutex_unlock(&bch_register_lock);
2586
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002587 pr_info("Stopping all devices:");
2588
David Brazdil0f672f62019-12-10 10:32:29 +00002589 /*
2590 * The reason bch_register_lock is not held to call
2591 * bch_cache_set_stop() and bcache_device_stop() is to
2592 * avoid potential deadlock during reboot, because cache
2593 * set or bcache device stopping process will acqurie
2594 * bch_register_lock too.
2595 *
2596 * We are safe here because bcache_is_reboot sets to
2597 * true already, register_bcache() will reject new
2598 * registration now. bcache_is_reboot also makes sure
2599 * bcache_reboot() won't be re-entered on by other thread,
2600 * so there is no race in following list iteration by
2601 * list_for_each_entry_safe().
2602 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002603 list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2604 bch_cache_set_stop(c);
2605
2606 list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2607 bcache_device_stop(&dc->disk);
2608
David Brazdil0f672f62019-12-10 10:32:29 +00002609
2610 /*
2611 * Give an early chance for other kthreads and
2612 * kworkers to stop themselves
2613 */
2614 schedule();
2615
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002616 /* What's a condition variable? */
2617 while (1) {
David Brazdil0f672f62019-12-10 10:32:29 +00002618 long timeout = start + 10 * HZ - jiffies;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002619
David Brazdil0f672f62019-12-10 10:32:29 +00002620 mutex_lock(&bch_register_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002621 stopped = list_empty(&bch_cache_sets) &&
2622 list_empty(&uncached_devices);
2623
2624 if (timeout < 0 || stopped)
2625 break;
2626
2627 prepare_to_wait(&unregister_wait, &wait,
2628 TASK_UNINTERRUPTIBLE);
2629
2630 mutex_unlock(&bch_register_lock);
2631 schedule_timeout(timeout);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002632 }
2633
2634 finish_wait(&unregister_wait, &wait);
2635
2636 if (stopped)
2637 pr_info("All devices stopped");
2638 else
2639 pr_notice("Timeout waiting for devices to be closed");
2640out:
2641 mutex_unlock(&bch_register_lock);
2642 }
2643
2644 return NOTIFY_DONE;
2645}
2646
2647static struct notifier_block reboot = {
2648 .notifier_call = bcache_reboot,
2649 .priority = INT_MAX, /* before any real devices */
2650};
2651
2652static void bcache_exit(void)
2653{
2654 bch_debug_exit();
2655 bch_request_exit();
2656 if (bcache_kobj)
2657 kobject_put(bcache_kobj);
2658 if (bcache_wq)
2659 destroy_workqueue(bcache_wq);
2660 if (bch_journal_wq)
2661 destroy_workqueue(bch_journal_wq);
Olivier Deprez0e641232021-09-23 10:07:05 +02002662 if (bch_flush_wq)
2663 destroy_workqueue(bch_flush_wq);
2664 bch_btree_exit();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002665
2666 if (bcache_major)
2667 unregister_blkdev(bcache_major, "bcache");
2668 unregister_reboot_notifier(&reboot);
2669 mutex_destroy(&bch_register_lock);
2670}
2671
David Brazdil0f672f62019-12-10 10:32:29 +00002672/* Check and fixup module parameters */
2673static void check_module_parameters(void)
2674{
2675 if (bch_cutoff_writeback_sync == 0)
2676 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
2677 else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
2678 pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u",
2679 bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
2680 bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
2681 }
2682
2683 if (bch_cutoff_writeback == 0)
2684 bch_cutoff_writeback = CUTOFF_WRITEBACK;
2685 else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
2686 pr_warn("set bch_cutoff_writeback (%u) to max value %u",
2687 bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
2688 bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
2689 }
2690
2691 if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
2692 pr_warn("set bch_cutoff_writeback (%u) to %u",
2693 bch_cutoff_writeback, bch_cutoff_writeback_sync);
2694 bch_cutoff_writeback = bch_cutoff_writeback_sync;
2695 }
2696}
2697
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002698static int __init bcache_init(void)
2699{
2700 static const struct attribute *files[] = {
2701 &ksysfs_register.attr,
2702 &ksysfs_register_quiet.attr,
David Brazdil0f672f62019-12-10 10:32:29 +00002703 &ksysfs_pendings_cleanup.attr,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002704 NULL
2705 };
2706
David Brazdil0f672f62019-12-10 10:32:29 +00002707 check_module_parameters();
2708
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002709 mutex_init(&bch_register_lock);
2710 init_waitqueue_head(&unregister_wait);
2711 register_reboot_notifier(&reboot);
2712
2713 bcache_major = register_blkdev(0, "bcache");
2714 if (bcache_major < 0) {
2715 unregister_reboot_notifier(&reboot);
2716 mutex_destroy(&bch_register_lock);
2717 return bcache_major;
2718 }
2719
Olivier Deprez0e641232021-09-23 10:07:05 +02002720 if (bch_btree_init())
2721 goto err;
2722
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002723 bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
2724 if (!bcache_wq)
2725 goto err;
2726
Olivier Deprez0e641232021-09-23 10:07:05 +02002727 /*
2728 * Let's not make this `WQ_MEM_RECLAIM` for the following reasons:
2729 *
2730 * 1. It used `system_wq` before which also does no memory reclaim.
2731 * 2. With `WQ_MEM_RECLAIM` desktop stalls, increased boot times, and
2732 * reduced throughput can be observed.
2733 *
2734 * We still want to user our own queue to not congest the `system_wq`.
2735 */
2736 bch_flush_wq = alloc_workqueue("bch_flush", 0, 0);
2737 if (!bch_flush_wq)
2738 goto err;
2739
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002740 bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
2741 if (!bch_journal_wq)
2742 goto err;
2743
2744 bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
2745 if (!bcache_kobj)
2746 goto err;
2747
2748 if (bch_request_init() ||
2749 sysfs_create_files(bcache_kobj, files))
2750 goto err;
2751
David Brazdil0f672f62019-12-10 10:32:29 +00002752 bch_debug_init();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002753 closure_debug_init();
2754
David Brazdil0f672f62019-12-10 10:32:29 +00002755 bcache_is_reboot = false;
2756
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002757 return 0;
2758err:
2759 bcache_exit();
2760 return -ENOMEM;
2761}
2762
David Brazdil0f672f62019-12-10 10:32:29 +00002763/*
2764 * Module hooks
2765 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002766module_exit(bcache_exit);
2767module_init(bcache_init);
David Brazdil0f672f62019-12-10 10:32:29 +00002768
2769module_param(bch_cutoff_writeback, uint, 0);
2770MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
2771
2772module_param(bch_cutoff_writeback_sync, uint, 0);
2773MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
2774
2775MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
2776MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
2777MODULE_LICENSE("GPL");