1 // SPDX-License-Identifier: GPL-2.0
3 * background writeback - scan btree for dirty data and write it to the backing
6 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
7 * Copyright 2012 Google, Inc.
13 #include "writeback.h"
15 #include <linux/delay.h>
16 #include <linux/kthread.h>
17 #include <linux/sched/clock.h>
18 #include <trace/events/bcache.h>
21 static uint64_t __calc_target_rate(struct cached_dev *dc)
23 struct cache_set *c = dc->disk.c;
26 * This is the size of the cache, minus the amount used for
29 uint64_t cache_sectors = c->nbuckets * c->sb.bucket_size -
30 atomic_long_read(&c->flash_dev_dirty_sectors);
33 * Unfortunately there is no control of global dirty data. If the
34 * user states that they want 10% dirty data in the cache, and has,
35 * e.g., 5 backing volumes of equal size, we try and ensure each
36 * backing volume uses about 2% of the cache for dirty data.
39 div64_u64(bdev_sectors(dc->bdev) << WRITEBACK_SHARE_SHIFT,
40 c->cached_dev_sectors);
42 uint64_t cache_dirty_target =
43 div_u64(cache_sectors * dc->writeback_percent, 100);
45 /* Ensure each backing dev gets at least one dirty share */
49 return (cache_dirty_target * bdev_share) >> WRITEBACK_SHARE_SHIFT;
52 static void __update_writeback_rate(struct cached_dev *dc)
56 * Figures out the amount that should be written per second.
58 * First, the error (number of sectors that are dirty beyond our
59 * target) is calculated. The error is accumulated (numerically
62 * Then, the proportional value and integral value are scaled
63 * based on configured values. These are stored as inverses to
64 * avoid fixed point math and to make configuration easy-- e.g.
65 * the default value of 40 for writeback_rate_p_term_inverse
66 * attempts to write at a rate that would retire all the dirty
67 * blocks in 40 seconds.
69 * The writeback_rate_i_inverse value of 10000 means that 1/10000th
70 * of the error is accumulated in the integral term per second.
71 * This acts as a slow, long-term average that is not subject to
72 * variations in usage like the p term.
74 int64_t target = __calc_target_rate(dc);
75 int64_t dirty = bcache_dev_sectors_dirty(&dc->disk);
76 int64_t error = dirty - target;
77 int64_t proportional_scaled =
78 div_s64(error, dc->writeback_rate_p_term_inverse);
79 int64_t integral_scaled;
82 if ((error < 0 && dc->writeback_rate_integral > 0) ||
83 (error > 0 && time_before64(local_clock(),
84 dc->writeback_rate.next + NSEC_PER_MSEC))) {
86 * Only decrease the integral term if it's more than
87 * zero. Only increase the integral term if the device
88 * is keeping up. (Don't wind up the integral
89 * ineffectively in either case).
91 * It's necessary to scale this by
92 * writeback_rate_update_seconds to keep the integral
93 * term dimensioned properly.
95 dc->writeback_rate_integral += error *
96 dc->writeback_rate_update_seconds;
99 integral_scaled = div_s64(dc->writeback_rate_integral,
100 dc->writeback_rate_i_term_inverse);
102 new_rate = clamp_t(int32_t, (proportional_scaled + integral_scaled),
103 dc->writeback_rate_minimum, NSEC_PER_SEC);
105 dc->writeback_rate_proportional = proportional_scaled;
106 dc->writeback_rate_integral_scaled = integral_scaled;
107 dc->writeback_rate_change = new_rate -
108 atomic_long_read(&dc->writeback_rate.rate);
109 atomic_long_set(&dc->writeback_rate.rate, new_rate);
110 dc->writeback_rate_target = target;
113 static bool set_at_max_writeback_rate(struct cache_set *c,
114 struct cached_dev *dc)
117 * Idle_counter is increased everytime when update_writeback_rate() is
118 * called. If all backing devices attached to the same cache set have
119 * identical dc->writeback_rate_update_seconds values, it is about 6
120 * rounds of update_writeback_rate() on each backing device before
121 * c->at_max_writeback_rate is set to 1, and then max wrteback rate set
122 * to each dc->writeback_rate.rate.
123 * In order to avoid extra locking cost for counting exact dirty cached
124 * devices number, c->attached_dev_nr is used to calculate the idle
125 * throushold. It might be bigger if not all cached device are in write-
126 * back mode, but it still works well with limited extra rounds of
127 * update_writeback_rate().
129 if (atomic_inc_return(&c->idle_counter) <
130 atomic_read(&c->attached_dev_nr) * 6)
133 if (atomic_read(&c->at_max_writeback_rate) != 1)
134 atomic_set(&c->at_max_writeback_rate, 1);
136 atomic_long_set(&dc->writeback_rate.rate, INT_MAX);
138 /* keep writeback_rate_target as existing value */
139 dc->writeback_rate_proportional = 0;
140 dc->writeback_rate_integral_scaled = 0;
141 dc->writeback_rate_change = 0;
144 * Check c->idle_counter and c->at_max_writeback_rate agagain in case
145 * new I/O arrives during before set_at_max_writeback_rate() returns.
146 * Then the writeback rate is set to 1, and its new value should be
147 * decided via __update_writeback_rate().
149 if ((atomic_read(&c->idle_counter) <
150 atomic_read(&c->attached_dev_nr) * 6) ||
151 !atomic_read(&c->at_max_writeback_rate))
157 static void update_writeback_rate(struct work_struct *work)
159 struct cached_dev *dc = container_of(to_delayed_work(work),
161 writeback_rate_update);
162 struct cache_set *c = dc->disk.c;
165 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
166 * cancel_delayed_work_sync().
168 set_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
169 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
173 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
176 if (!test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) ||
177 test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
178 clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
179 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
184 if (atomic_read(&dc->has_dirty) && dc->writeback_percent) {
186 * If the whole cache set is idle, set_at_max_writeback_rate()
187 * will set writeback rate to a max number. Then it is
188 * unncessary to update writeback rate for an idle cache set
189 * in maximum writeback rate number(s).
191 if (!set_at_max_writeback_rate(c, dc)) {
192 down_read(&dc->writeback_lock);
193 __update_writeback_rate(dc);
194 up_read(&dc->writeback_lock);
200 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
203 if (test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) &&
204 !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
205 schedule_delayed_work(&dc->writeback_rate_update,
206 dc->writeback_rate_update_seconds * HZ);
210 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
211 * cancel_delayed_work_sync().
213 clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
214 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
218 static unsigned int writeback_delay(struct cached_dev *dc,
219 unsigned int sectors)
221 if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
222 !dc->writeback_percent)
225 return bch_next_delay(&dc->writeback_rate, sectors);
230 struct cached_dev *dc;
235 static void dirty_init(struct keybuf_key *w)
237 struct dirty_io *io = w->private;
238 struct bio *bio = &io->bio;
240 bio_init(bio, bio->bi_inline_vecs,
241 DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS));
242 if (!io->dc->writeback_percent)
243 bio_set_prio(bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
245 bio->bi_iter.bi_size = KEY_SIZE(&w->key) << 9;
247 bch_bio_map(bio, NULL);
250 static void dirty_io_destructor(struct closure *cl)
252 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
257 static void write_dirty_finish(struct closure *cl)
259 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
260 struct keybuf_key *w = io->bio.bi_private;
261 struct cached_dev *dc = io->dc;
263 bio_free_pages(&io->bio);
265 /* This is kind of a dumb way of signalling errors. */
266 if (KEY_DIRTY(&w->key)) {
271 bch_keylist_init(&keys);
273 bkey_copy(keys.top, &w->key);
274 SET_KEY_DIRTY(keys.top, false);
275 bch_keylist_push(&keys);
277 for (i = 0; i < KEY_PTRS(&w->key); i++)
278 atomic_inc(&PTR_BUCKET(dc->disk.c, &w->key, i)->pin);
280 ret = bch_btree_insert(dc->disk.c, &keys, NULL, &w->key);
283 trace_bcache_writeback_collision(&w->key);
286 ? &dc->disk.c->writeback_keys_failed
287 : &dc->disk.c->writeback_keys_done);
290 bch_keybuf_del(&dc->writeback_keys, w);
293 closure_return_with_destructor(cl, dirty_io_destructor);
296 static void dirty_endio(struct bio *bio)
298 struct keybuf_key *w = bio->bi_private;
299 struct dirty_io *io = w->private;
301 if (bio->bi_status) {
302 SET_KEY_DIRTY(&w->key, false);
303 bch_count_backing_io_errors(io->dc, bio);
306 closure_put(&io->cl);
309 static void write_dirty(struct closure *cl)
311 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
312 struct keybuf_key *w = io->bio.bi_private;
313 struct cached_dev *dc = io->dc;
315 uint16_t next_sequence;
317 if (atomic_read(&dc->writeback_sequence_next) != io->sequence) {
318 /* Not our turn to write; wait for a write to complete */
319 closure_wait(&dc->writeback_ordering_wait, cl);
321 if (atomic_read(&dc->writeback_sequence_next) == io->sequence) {
323 * Edge case-- it happened in indeterminate order
324 * relative to when we were added to wait list..
326 closure_wake_up(&dc->writeback_ordering_wait);
329 continue_at(cl, write_dirty, io->dc->writeback_write_wq);
333 next_sequence = io->sequence + 1;
336 * IO errors are signalled using the dirty bit on the key.
337 * If we failed to read, we should not attempt to write to the
338 * backing device. Instead, immediately go to write_dirty_finish
341 if (KEY_DIRTY(&w->key)) {
343 bio_set_op_attrs(&io->bio, REQ_OP_WRITE, 0);
344 io->bio.bi_iter.bi_sector = KEY_START(&w->key);
345 bio_set_dev(&io->bio, io->dc->bdev);
346 io->bio.bi_end_io = dirty_endio;
348 /* I/O request sent to backing device */
349 closure_bio_submit(io->dc->disk.c, &io->bio, cl);
352 atomic_set(&dc->writeback_sequence_next, next_sequence);
353 closure_wake_up(&dc->writeback_ordering_wait);
355 continue_at(cl, write_dirty_finish, io->dc->writeback_write_wq);
358 static void read_dirty_endio(struct bio *bio)
360 struct keybuf_key *w = bio->bi_private;
361 struct dirty_io *io = w->private;
364 bch_count_io_errors(PTR_CACHE(io->dc->disk.c, &w->key, 0),
366 "reading dirty data from cache");
371 static void read_dirty_submit(struct closure *cl)
373 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
375 closure_bio_submit(io->dc->disk.c, &io->bio, cl);
377 continue_at(cl, write_dirty, io->dc->writeback_write_wq);
380 static void read_dirty(struct cached_dev *dc)
382 unsigned int delay = 0;
383 struct keybuf_key *next, *keys[MAX_WRITEBACKS_IN_PASS], *w;
388 uint16_t sequence = 0;
390 BUG_ON(!llist_empty(&dc->writeback_ordering_wait.list));
391 atomic_set(&dc->writeback_sequence_next, sequence);
392 closure_init_stack(&cl);
395 * XXX: if we error, background writeback just spins. Should use some
399 next = bch_keybuf_next(&dc->writeback_keys);
401 while (!kthread_should_stop() &&
402 !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
408 BUG_ON(ptr_stale(dc->disk.c, &next->key, 0));
411 * Don't combine too many operations, even if they
414 if (nk >= MAX_WRITEBACKS_IN_PASS)
418 * If the current operation is very large, don't
419 * further combine operations.
421 if (size >= MAX_WRITESIZE_IN_PASS)
425 * Operations are only eligible to be combined
426 * if they are contiguous.
428 * TODO: add a heuristic willing to fire a
429 * certain amount of non-contiguous IO per pass,
430 * so that we can benefit from backing device
433 if ((nk != 0) && bkey_cmp(&keys[nk-1]->key,
434 &START_KEY(&next->key)))
437 size += KEY_SIZE(&next->key);
439 } while ((next = bch_keybuf_next(&dc->writeback_keys)));
441 /* Now we have gathered a set of 1..5 keys to write back. */
442 for (i = 0; i < nk; i++) {
445 io = kzalloc(sizeof(struct dirty_io) +
446 sizeof(struct bio_vec) *
447 DIV_ROUND_UP(KEY_SIZE(&w->key),
455 io->sequence = sequence++;
458 bio_set_op_attrs(&io->bio, REQ_OP_READ, 0);
459 io->bio.bi_iter.bi_sector = PTR_OFFSET(&w->key, 0);
460 bio_set_dev(&io->bio,
461 PTR_CACHE(dc->disk.c, &w->key, 0)->bdev);
462 io->bio.bi_end_io = read_dirty_endio;
464 if (bch_bio_alloc_pages(&io->bio, GFP_KERNEL))
467 trace_bcache_writeback(&w->key);
469 down(&dc->in_flight);
472 * We've acquired a semaphore for the maximum
473 * simultaneous number of writebacks; from here
474 * everything happens asynchronously.
476 closure_call(&io->cl, read_dirty_submit, NULL, &cl);
479 delay = writeback_delay(dc, size);
481 while (!kthread_should_stop() &&
482 !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
484 schedule_timeout_interruptible(delay);
485 delay = writeback_delay(dc, 0);
493 bch_keybuf_del(&dc->writeback_keys, w);
497 * Wait for outstanding writeback IOs to finish (and keybuf slots to be
498 * freed) before refilling again
503 /* Scan for dirty data */
505 void bcache_dev_sectors_dirty_add(struct cache_set *c, unsigned int inode,
506 uint64_t offset, int nr_sectors)
508 struct bcache_device *d = c->devices[inode];
509 unsigned int stripe_offset, sectors_dirty;
515 stripe = offset_to_stripe(d, offset);
519 if (UUID_FLASH_ONLY(&c->uuids[inode]))
520 atomic_long_add(nr_sectors, &c->flash_dev_dirty_sectors);
522 stripe_offset = offset & (d->stripe_size - 1);
525 int s = min_t(unsigned int, abs(nr_sectors),
526 d->stripe_size - stripe_offset);
531 if (stripe >= d->nr_stripes)
534 sectors_dirty = atomic_add_return(s,
535 d->stripe_sectors_dirty + stripe);
536 if (sectors_dirty == d->stripe_size)
537 set_bit(stripe, d->full_dirty_stripes);
539 clear_bit(stripe, d->full_dirty_stripes);
547 static bool dirty_pred(struct keybuf *buf, struct bkey *k)
549 struct cached_dev *dc = container_of(buf,
553 BUG_ON(KEY_INODE(k) != dc->disk.id);
558 static void refill_full_stripes(struct cached_dev *dc)
560 struct keybuf *buf = &dc->writeback_keys;
561 unsigned int start_stripe, next_stripe;
563 bool wrapped = false;
565 stripe = offset_to_stripe(&dc->disk, KEY_OFFSET(&buf->last_scanned));
569 start_stripe = stripe;
572 stripe = find_next_bit(dc->disk.full_dirty_stripes,
573 dc->disk.nr_stripes, stripe);
575 if (stripe == dc->disk.nr_stripes)
578 next_stripe = find_next_zero_bit(dc->disk.full_dirty_stripes,
579 dc->disk.nr_stripes, stripe);
581 buf->last_scanned = KEY(dc->disk.id,
582 stripe * dc->disk.stripe_size, 0);
584 bch_refill_keybuf(dc->disk.c, buf,
586 next_stripe * dc->disk.stripe_size, 0),
589 if (array_freelist_empty(&buf->freelist))
592 stripe = next_stripe;
594 if (wrapped && stripe > start_stripe)
597 if (stripe == dc->disk.nr_stripes) {
605 * Returns true if we scanned the entire disk
607 static bool refill_dirty(struct cached_dev *dc)
609 struct keybuf *buf = &dc->writeback_keys;
610 struct bkey start = KEY(dc->disk.id, 0, 0);
611 struct bkey end = KEY(dc->disk.id, MAX_KEY_OFFSET, 0);
612 struct bkey start_pos;
615 * make sure keybuf pos is inside the range for this disk - at bringup
616 * we might not be attached yet so this disk's inode nr isn't
619 if (bkey_cmp(&buf->last_scanned, &start) < 0 ||
620 bkey_cmp(&buf->last_scanned, &end) > 0)
621 buf->last_scanned = start;
623 if (dc->partial_stripes_expensive) {
624 refill_full_stripes(dc);
625 if (array_freelist_empty(&buf->freelist))
629 start_pos = buf->last_scanned;
630 bch_refill_keybuf(dc->disk.c, buf, &end, dirty_pred);
632 if (bkey_cmp(&buf->last_scanned, &end) < 0)
636 * If we get to the end start scanning again from the beginning, and
637 * only scan up to where we initially started scanning from:
639 buf->last_scanned = start;
640 bch_refill_keybuf(dc->disk.c, buf, &start_pos, dirty_pred);
642 return bkey_cmp(&buf->last_scanned, &start_pos) >= 0;
645 static int bch_writeback_thread(void *arg)
647 struct cached_dev *dc = arg;
648 struct cache_set *c = dc->disk.c;
649 bool searched_full_index;
651 bch_ratelimit_reset(&dc->writeback_rate);
653 while (!kthread_should_stop() &&
654 !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
655 down_write(&dc->writeback_lock);
656 set_current_state(TASK_INTERRUPTIBLE);
658 * If the bache device is detaching, skip here and continue
659 * to perform writeback. Otherwise, if no dirty data on cache,
660 * or there is dirty data on cache but writeback is disabled,
661 * the writeback thread should sleep here and wait for others
664 if (!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) &&
665 (!atomic_read(&dc->has_dirty) || !dc->writeback_running)) {
666 up_write(&dc->writeback_lock);
668 if (kthread_should_stop() ||
669 test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
670 set_current_state(TASK_RUNNING);
677 set_current_state(TASK_RUNNING);
679 searched_full_index = refill_dirty(dc);
681 if (searched_full_index &&
682 RB_EMPTY_ROOT(&dc->writeback_keys.keys)) {
683 atomic_set(&dc->has_dirty, 0);
684 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
685 bch_write_bdev_super(dc, NULL);
687 * If bcache device is detaching via sysfs interface,
688 * writeback thread should stop after there is no dirty
689 * data on cache. BCACHE_DEV_DETACHING flag is set in
690 * bch_cached_dev_detach().
692 if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags)) {
693 up_write(&dc->writeback_lock);
698 up_write(&dc->writeback_lock);
702 if (searched_full_index) {
703 unsigned int delay = dc->writeback_delay * HZ;
706 !kthread_should_stop() &&
707 !test_bit(CACHE_SET_IO_DISABLE, &c->flags) &&
708 !test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
709 delay = schedule_timeout_interruptible(delay);
711 bch_ratelimit_reset(&dc->writeback_rate);
715 if (dc->writeback_write_wq) {
716 flush_workqueue(dc->writeback_write_wq);
717 destroy_workqueue(dc->writeback_write_wq);
720 wait_for_kthread_stop();
726 #define INIT_KEYS_EACH_TIME 500000
727 #define INIT_KEYS_SLEEP_MS 100
729 struct sectors_dirty_init {
736 static int sectors_dirty_init_fn(struct btree_op *_op, struct btree *b,
739 struct sectors_dirty_init *op = container_of(_op,
740 struct sectors_dirty_init, op);
741 if (KEY_INODE(k) > op->inode)
745 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
746 KEY_START(k), KEY_SIZE(k));
749 if (atomic_read(&b->c->search_inflight) &&
750 !(op->count % INIT_KEYS_EACH_TIME)) {
751 bkey_copy_key(&op->start, k);
758 void bch_sectors_dirty_init(struct bcache_device *d)
760 struct sectors_dirty_init op;
763 bch_btree_op_init(&op.op, -1);
766 op.start = KEY(op.inode, 0, 0);
769 ret = bch_btree_map_keys(&op.op, d->c, &op.start,
770 sectors_dirty_init_fn, 0);
772 schedule_timeout_interruptible(
773 msecs_to_jiffies(INIT_KEYS_SLEEP_MS));
775 pr_warn("sectors dirty init failed, ret=%d!", ret);
778 } while (ret == -EAGAIN);
781 void bch_cached_dev_writeback_init(struct cached_dev *dc)
783 sema_init(&dc->in_flight, 64);
784 init_rwsem(&dc->writeback_lock);
785 bch_keybuf_init(&dc->writeback_keys);
787 dc->writeback_metadata = true;
788 dc->writeback_running = false;
789 dc->writeback_percent = 10;
790 dc->writeback_delay = 30;
791 atomic_long_set(&dc->writeback_rate.rate, 1024);
792 dc->writeback_rate_minimum = 8;
794 dc->writeback_rate_update_seconds = WRITEBACK_RATE_UPDATE_SECS_DEFAULT;
795 dc->writeback_rate_p_term_inverse = 40;
796 dc->writeback_rate_i_term_inverse = 10000;
798 WARN_ON(test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
799 INIT_DELAYED_WORK(&dc->writeback_rate_update, update_writeback_rate);
802 int bch_cached_dev_writeback_start(struct cached_dev *dc)
804 dc->writeback_write_wq = alloc_workqueue("bcache_writeback_wq",
806 if (!dc->writeback_write_wq)
810 dc->writeback_thread = kthread_create(bch_writeback_thread, dc,
812 if (IS_ERR(dc->writeback_thread)) {
814 destroy_workqueue(dc->writeback_write_wq);
815 return PTR_ERR(dc->writeback_thread);
817 dc->writeback_running = true;
819 WARN_ON(test_and_set_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
820 schedule_delayed_work(&dc->writeback_rate_update,
821 dc->writeback_rate_update_seconds * HZ);
823 bch_writeback_queue(dc);