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>
20 static void update_gc_after_writeback(struct cache_set *c)
22 if (c->gc_after_writeback != (BCH_ENABLE_AUTO_GC) ||
23 c->gc_stats.in_use < BCH_AUTO_GC_DIRTY_THRESHOLD)
26 c->gc_after_writeback |= BCH_DO_AUTO_GC;
30 static uint64_t __calc_target_rate(struct cached_dev *dc)
32 struct cache_set *c = dc->disk.c;
35 * This is the size of the cache, minus the amount used for
38 uint64_t cache_sectors = c->nbuckets * c->cache->sb.bucket_size -
39 atomic_long_read(&c->flash_dev_dirty_sectors);
42 * Unfortunately there is no control of global dirty data. If the
43 * user states that they want 10% dirty data in the cache, and has,
44 * e.g., 5 backing volumes of equal size, we try and ensure each
45 * backing volume uses about 2% of the cache for dirty data.
48 div64_u64(bdev_sectors(dc->bdev) << WRITEBACK_SHARE_SHIFT,
49 c->cached_dev_sectors);
51 uint64_t cache_dirty_target =
52 div_u64(cache_sectors * dc->writeback_percent, 100);
54 /* Ensure each backing dev gets at least one dirty share */
58 return (cache_dirty_target * bdev_share) >> WRITEBACK_SHARE_SHIFT;
61 static void __update_writeback_rate(struct cached_dev *dc)
65 * Figures out the amount that should be written per second.
67 * First, the error (number of sectors that are dirty beyond our
68 * target) is calculated. The error is accumulated (numerically
71 * Then, the proportional value and integral value are scaled
72 * based on configured values. These are stored as inverses to
73 * avoid fixed point math and to make configuration easy-- e.g.
74 * the default value of 40 for writeback_rate_p_term_inverse
75 * attempts to write at a rate that would retire all the dirty
76 * blocks in 40 seconds.
78 * The writeback_rate_i_inverse value of 10000 means that 1/10000th
79 * of the error is accumulated in the integral term per second.
80 * This acts as a slow, long-term average that is not subject to
81 * variations in usage like the p term.
83 int64_t target = __calc_target_rate(dc);
84 int64_t dirty = bcache_dev_sectors_dirty(&dc->disk);
85 int64_t error = dirty - target;
86 int64_t proportional_scaled =
87 div_s64(error, dc->writeback_rate_p_term_inverse);
88 int64_t integral_scaled;
91 if ((error < 0 && dc->writeback_rate_integral > 0) ||
92 (error > 0 && time_before64(local_clock(),
93 dc->writeback_rate.next + NSEC_PER_MSEC))) {
95 * Only decrease the integral term if it's more than
96 * zero. Only increase the integral term if the device
97 * is keeping up. (Don't wind up the integral
98 * ineffectively in either case).
100 * It's necessary to scale this by
101 * writeback_rate_update_seconds to keep the integral
102 * term dimensioned properly.
104 dc->writeback_rate_integral += error *
105 dc->writeback_rate_update_seconds;
108 integral_scaled = div_s64(dc->writeback_rate_integral,
109 dc->writeback_rate_i_term_inverse);
111 new_rate = clamp_t(int32_t, (proportional_scaled + integral_scaled),
112 dc->writeback_rate_minimum, NSEC_PER_SEC);
114 dc->writeback_rate_proportional = proportional_scaled;
115 dc->writeback_rate_integral_scaled = integral_scaled;
116 dc->writeback_rate_change = new_rate -
117 atomic_long_read(&dc->writeback_rate.rate);
118 atomic_long_set(&dc->writeback_rate.rate, new_rate);
119 dc->writeback_rate_target = target;
122 static bool idle_counter_exceeded(struct cache_set *c)
127 * If c->idle_counter is overflow (idel for really long time),
128 * reset as 0 and not set maximum rate this time for code
131 counter = atomic_inc_return(&c->idle_counter);
133 atomic_set(&c->idle_counter, 0);
137 dev_nr = atomic_read(&c->attached_dev_nr);
142 * c->idle_counter is increased by writeback thread of all
143 * attached backing devices, in order to represent a rough
144 * time period, counter should be divided by dev_nr.
145 * Otherwise the idle time cannot be larger with more backing
147 * The following calculation equals to checking
148 * (counter / dev_nr) < (dev_nr * 6)
150 if (counter < (dev_nr * dev_nr * 6))
157 * Idle_counter is increased every time when update_writeback_rate() is
158 * called. If all backing devices attached to the same cache set have
159 * identical dc->writeback_rate_update_seconds values, it is about 6
160 * rounds of update_writeback_rate() on each backing device before
161 * c->at_max_writeback_rate is set to 1, and then max wrteback rate set
162 * to each dc->writeback_rate.rate.
163 * In order to avoid extra locking cost for counting exact dirty cached
164 * devices number, c->attached_dev_nr is used to calculate the idle
165 * throushold. It might be bigger if not all cached device are in write-
166 * back mode, but it still works well with limited extra rounds of
167 * update_writeback_rate().
169 static bool set_at_max_writeback_rate(struct cache_set *c,
170 struct cached_dev *dc)
172 /* Don't sst max writeback rate if it is disabled */
173 if (!c->idle_max_writeback_rate_enabled)
176 /* Don't set max writeback rate if gc is running */
177 if (!c->gc_mark_valid)
180 if (!idle_counter_exceeded(c))
183 if (atomic_read(&c->at_max_writeback_rate) != 1)
184 atomic_set(&c->at_max_writeback_rate, 1);
186 atomic_long_set(&dc->writeback_rate.rate, INT_MAX);
188 /* keep writeback_rate_target as existing value */
189 dc->writeback_rate_proportional = 0;
190 dc->writeback_rate_integral_scaled = 0;
191 dc->writeback_rate_change = 0;
194 * In case new I/O arrives during before
195 * set_at_max_writeback_rate() returns.
197 if (!idle_counter_exceeded(c) ||
198 !atomic_read(&c->at_max_writeback_rate))
204 static void update_writeback_rate(struct work_struct *work)
206 struct cached_dev *dc = container_of(to_delayed_work(work),
208 writeback_rate_update);
209 struct cache_set *c = dc->disk.c;
212 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
213 * cancel_delayed_work_sync().
215 set_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
216 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
217 smp_mb__after_atomic();
220 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
223 if (!test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) ||
224 test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
225 clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
226 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
227 smp_mb__after_atomic();
231 if (atomic_read(&dc->has_dirty) && dc->writeback_percent) {
233 * If the whole cache set is idle, set_at_max_writeback_rate()
234 * will set writeback rate to a max number. Then it is
235 * unncessary to update writeback rate for an idle cache set
236 * in maximum writeback rate number(s).
238 if (!set_at_max_writeback_rate(c, dc)) {
239 down_read(&dc->writeback_lock);
240 __update_writeback_rate(dc);
241 update_gc_after_writeback(c);
242 up_read(&dc->writeback_lock);
248 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
251 if (test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) &&
252 !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
253 schedule_delayed_work(&dc->writeback_rate_update,
254 dc->writeback_rate_update_seconds * HZ);
258 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
259 * cancel_delayed_work_sync().
261 clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
262 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
263 smp_mb__after_atomic();
266 static unsigned int writeback_delay(struct cached_dev *dc,
267 unsigned int sectors)
269 if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
270 !dc->writeback_percent)
273 return bch_next_delay(&dc->writeback_rate, sectors);
278 struct cached_dev *dc;
283 static void dirty_init(struct keybuf_key *w)
285 struct dirty_io *io = w->private;
286 struct bio *bio = &io->bio;
288 bio_init(bio, bio->bi_inline_vecs,
289 DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS));
290 if (!io->dc->writeback_percent)
291 bio_set_prio(bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
293 bio->bi_iter.bi_size = KEY_SIZE(&w->key) << 9;
295 bch_bio_map(bio, NULL);
298 static void dirty_io_destructor(struct closure *cl)
300 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
305 static void write_dirty_finish(struct closure *cl)
307 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
308 struct keybuf_key *w = io->bio.bi_private;
309 struct cached_dev *dc = io->dc;
311 bio_free_pages(&io->bio);
313 /* This is kind of a dumb way of signalling errors. */
314 if (KEY_DIRTY(&w->key)) {
319 bch_keylist_init(&keys);
321 bkey_copy(keys.top, &w->key);
322 SET_KEY_DIRTY(keys.top, false);
323 bch_keylist_push(&keys);
325 for (i = 0; i < KEY_PTRS(&w->key); i++)
326 atomic_inc(&PTR_BUCKET(dc->disk.c, &w->key, i)->pin);
328 ret = bch_btree_insert(dc->disk.c, &keys, NULL, &w->key);
331 trace_bcache_writeback_collision(&w->key);
334 ? &dc->disk.c->writeback_keys_failed
335 : &dc->disk.c->writeback_keys_done);
338 bch_keybuf_del(&dc->writeback_keys, w);
341 closure_return_with_destructor(cl, dirty_io_destructor);
344 static void dirty_endio(struct bio *bio)
346 struct keybuf_key *w = bio->bi_private;
347 struct dirty_io *io = w->private;
349 if (bio->bi_status) {
350 SET_KEY_DIRTY(&w->key, false);
351 bch_count_backing_io_errors(io->dc, bio);
354 closure_put(&io->cl);
357 static void write_dirty(struct closure *cl)
359 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
360 struct keybuf_key *w = io->bio.bi_private;
361 struct cached_dev *dc = io->dc;
363 uint16_t next_sequence;
365 if (atomic_read(&dc->writeback_sequence_next) != io->sequence) {
366 /* Not our turn to write; wait for a write to complete */
367 closure_wait(&dc->writeback_ordering_wait, cl);
369 if (atomic_read(&dc->writeback_sequence_next) == io->sequence) {
371 * Edge case-- it happened in indeterminate order
372 * relative to when we were added to wait list..
374 closure_wake_up(&dc->writeback_ordering_wait);
377 continue_at(cl, write_dirty, io->dc->writeback_write_wq);
381 next_sequence = io->sequence + 1;
384 * IO errors are signalled using the dirty bit on the key.
385 * If we failed to read, we should not attempt to write to the
386 * backing device. Instead, immediately go to write_dirty_finish
389 if (KEY_DIRTY(&w->key)) {
391 bio_set_op_attrs(&io->bio, REQ_OP_WRITE, 0);
392 io->bio.bi_iter.bi_sector = KEY_START(&w->key);
393 bio_set_dev(&io->bio, io->dc->bdev);
394 io->bio.bi_end_io = dirty_endio;
396 /* I/O request sent to backing device */
397 closure_bio_submit(io->dc->disk.c, &io->bio, cl);
400 atomic_set(&dc->writeback_sequence_next, next_sequence);
401 closure_wake_up(&dc->writeback_ordering_wait);
403 continue_at(cl, write_dirty_finish, io->dc->writeback_write_wq);
406 static void read_dirty_endio(struct bio *bio)
408 struct keybuf_key *w = bio->bi_private;
409 struct dirty_io *io = w->private;
412 bch_count_io_errors(PTR_CACHE(io->dc->disk.c, &w->key, 0),
414 "reading dirty data from cache");
419 static void read_dirty_submit(struct closure *cl)
421 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
423 closure_bio_submit(io->dc->disk.c, &io->bio, cl);
425 continue_at(cl, write_dirty, io->dc->writeback_write_wq);
428 static void read_dirty(struct cached_dev *dc)
430 unsigned int delay = 0;
431 struct keybuf_key *next, *keys[MAX_WRITEBACKS_IN_PASS], *w;
436 uint16_t sequence = 0;
438 BUG_ON(!llist_empty(&dc->writeback_ordering_wait.list));
439 atomic_set(&dc->writeback_sequence_next, sequence);
440 closure_init_stack(&cl);
443 * XXX: if we error, background writeback just spins. Should use some
447 next = bch_keybuf_next(&dc->writeback_keys);
449 while (!kthread_should_stop() &&
450 !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
456 BUG_ON(ptr_stale(dc->disk.c, &next->key, 0));
459 * Don't combine too many operations, even if they
462 if (nk >= MAX_WRITEBACKS_IN_PASS)
466 * If the current operation is very large, don't
467 * further combine operations.
469 if (size >= MAX_WRITESIZE_IN_PASS)
473 * Operations are only eligible to be combined
474 * if they are contiguous.
476 * TODO: add a heuristic willing to fire a
477 * certain amount of non-contiguous IO per pass,
478 * so that we can benefit from backing device
481 if ((nk != 0) && bkey_cmp(&keys[nk-1]->key,
482 &START_KEY(&next->key)))
485 size += KEY_SIZE(&next->key);
487 } while ((next = bch_keybuf_next(&dc->writeback_keys)));
489 /* Now we have gathered a set of 1..5 keys to write back. */
490 for (i = 0; i < nk; i++) {
493 io = kzalloc(struct_size(io, bio.bi_inline_vecs,
494 DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS)),
501 io->sequence = sequence++;
504 bio_set_op_attrs(&io->bio, REQ_OP_READ, 0);
505 io->bio.bi_iter.bi_sector = PTR_OFFSET(&w->key, 0);
506 bio_set_dev(&io->bio,
507 PTR_CACHE(dc->disk.c, &w->key, 0)->bdev);
508 io->bio.bi_end_io = read_dirty_endio;
510 if (bch_bio_alloc_pages(&io->bio, GFP_KERNEL))
513 trace_bcache_writeback(&w->key);
515 down(&dc->in_flight);
518 * We've acquired a semaphore for the maximum
519 * simultaneous number of writebacks; from here
520 * everything happens asynchronously.
522 closure_call(&io->cl, read_dirty_submit, NULL, &cl);
525 delay = writeback_delay(dc, size);
527 while (!kthread_should_stop() &&
528 !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
530 schedule_timeout_interruptible(delay);
531 delay = writeback_delay(dc, 0);
539 bch_keybuf_del(&dc->writeback_keys, w);
543 * Wait for outstanding writeback IOs to finish (and keybuf slots to be
544 * freed) before refilling again
549 /* Scan for dirty data */
551 void bcache_dev_sectors_dirty_add(struct cache_set *c, unsigned int inode,
552 uint64_t offset, int nr_sectors)
554 struct bcache_device *d = c->devices[inode];
555 unsigned int stripe_offset, sectors_dirty;
561 stripe = offset_to_stripe(d, offset);
565 if (UUID_FLASH_ONLY(&c->uuids[inode]))
566 atomic_long_add(nr_sectors, &c->flash_dev_dirty_sectors);
568 stripe_offset = offset & (d->stripe_size - 1);
571 int s = min_t(unsigned int, abs(nr_sectors),
572 d->stripe_size - stripe_offset);
577 if (stripe >= d->nr_stripes)
580 sectors_dirty = atomic_add_return(s,
581 d->stripe_sectors_dirty + stripe);
582 if (sectors_dirty == d->stripe_size)
583 set_bit(stripe, d->full_dirty_stripes);
585 clear_bit(stripe, d->full_dirty_stripes);
593 static bool dirty_pred(struct keybuf *buf, struct bkey *k)
595 struct cached_dev *dc = container_of(buf,
599 BUG_ON(KEY_INODE(k) != dc->disk.id);
604 static void refill_full_stripes(struct cached_dev *dc)
606 struct keybuf *buf = &dc->writeback_keys;
607 unsigned int start_stripe, next_stripe;
609 bool wrapped = false;
611 stripe = offset_to_stripe(&dc->disk, KEY_OFFSET(&buf->last_scanned));
615 start_stripe = stripe;
618 stripe = find_next_bit(dc->disk.full_dirty_stripes,
619 dc->disk.nr_stripes, stripe);
621 if (stripe == dc->disk.nr_stripes)
624 next_stripe = find_next_zero_bit(dc->disk.full_dirty_stripes,
625 dc->disk.nr_stripes, stripe);
627 buf->last_scanned = KEY(dc->disk.id,
628 stripe * dc->disk.stripe_size, 0);
630 bch_refill_keybuf(dc->disk.c, buf,
632 next_stripe * dc->disk.stripe_size, 0),
635 if (array_freelist_empty(&buf->freelist))
638 stripe = next_stripe;
640 if (wrapped && stripe > start_stripe)
643 if (stripe == dc->disk.nr_stripes) {
651 * Returns true if we scanned the entire disk
653 static bool refill_dirty(struct cached_dev *dc)
655 struct keybuf *buf = &dc->writeback_keys;
656 struct bkey start = KEY(dc->disk.id, 0, 0);
657 struct bkey end = KEY(dc->disk.id, MAX_KEY_OFFSET, 0);
658 struct bkey start_pos;
661 * make sure keybuf pos is inside the range for this disk - at bringup
662 * we might not be attached yet so this disk's inode nr isn't
665 if (bkey_cmp(&buf->last_scanned, &start) < 0 ||
666 bkey_cmp(&buf->last_scanned, &end) > 0)
667 buf->last_scanned = start;
669 if (dc->partial_stripes_expensive) {
670 refill_full_stripes(dc);
671 if (array_freelist_empty(&buf->freelist))
675 start_pos = buf->last_scanned;
676 bch_refill_keybuf(dc->disk.c, buf, &end, dirty_pred);
678 if (bkey_cmp(&buf->last_scanned, &end) < 0)
682 * If we get to the end start scanning again from the beginning, and
683 * only scan up to where we initially started scanning from:
685 buf->last_scanned = start;
686 bch_refill_keybuf(dc->disk.c, buf, &start_pos, dirty_pred);
688 return bkey_cmp(&buf->last_scanned, &start_pos) >= 0;
691 static int bch_writeback_thread(void *arg)
693 struct cached_dev *dc = arg;
694 struct cache_set *c = dc->disk.c;
695 bool searched_full_index;
697 bch_ratelimit_reset(&dc->writeback_rate);
699 while (!kthread_should_stop() &&
700 !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
701 down_write(&dc->writeback_lock);
702 set_current_state(TASK_INTERRUPTIBLE);
704 * If the bache device is detaching, skip here and continue
705 * to perform writeback. Otherwise, if no dirty data on cache,
706 * or there is dirty data on cache but writeback is disabled,
707 * the writeback thread should sleep here and wait for others
710 if (!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) &&
711 (!atomic_read(&dc->has_dirty) || !dc->writeback_running)) {
712 up_write(&dc->writeback_lock);
714 if (kthread_should_stop() ||
715 test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
716 set_current_state(TASK_RUNNING);
723 set_current_state(TASK_RUNNING);
725 searched_full_index = refill_dirty(dc);
727 if (searched_full_index &&
728 RB_EMPTY_ROOT(&dc->writeback_keys.keys)) {
729 atomic_set(&dc->has_dirty, 0);
730 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
731 bch_write_bdev_super(dc, NULL);
733 * If bcache device is detaching via sysfs interface,
734 * writeback thread should stop after there is no dirty
735 * data on cache. BCACHE_DEV_DETACHING flag is set in
736 * bch_cached_dev_detach().
738 if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags)) {
739 up_write(&dc->writeback_lock);
744 * When dirty data rate is high (e.g. 50%+), there might
745 * be heavy buckets fragmentation after writeback
746 * finished, which hurts following write performance.
747 * If users really care about write performance they
748 * may set BCH_ENABLE_AUTO_GC via sysfs, then when
749 * BCH_DO_AUTO_GC is set, garbage collection thread
750 * will be wake up here. After moving gc, the shrunk
751 * btree and discarded free buckets SSD space may be
752 * helpful for following write requests.
754 if (c->gc_after_writeback ==
755 (BCH_ENABLE_AUTO_GC|BCH_DO_AUTO_GC)) {
756 c->gc_after_writeback &= ~BCH_DO_AUTO_GC;
761 up_write(&dc->writeback_lock);
765 if (searched_full_index) {
766 unsigned int delay = dc->writeback_delay * HZ;
769 !kthread_should_stop() &&
770 !test_bit(CACHE_SET_IO_DISABLE, &c->flags) &&
771 !test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
772 delay = schedule_timeout_interruptible(delay);
774 bch_ratelimit_reset(&dc->writeback_rate);
778 if (dc->writeback_write_wq) {
779 flush_workqueue(dc->writeback_write_wq);
780 destroy_workqueue(dc->writeback_write_wq);
783 wait_for_kthread_stop();
789 #define INIT_KEYS_EACH_TIME 500000
791 struct sectors_dirty_init {
797 static int sectors_dirty_init_fn(struct btree_op *_op, struct btree *b,
800 struct sectors_dirty_init *op = container_of(_op,
801 struct sectors_dirty_init, op);
802 if (KEY_INODE(k) > op->inode)
806 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
807 KEY_START(k), KEY_SIZE(k));
810 if (!(op->count % INIT_KEYS_EACH_TIME))
816 static int bch_root_node_dirty_init(struct cache_set *c,
817 struct bcache_device *d,
820 struct sectors_dirty_init op;
823 bch_btree_op_init(&op.op, -1);
827 ret = bcache_btree(map_keys_recurse,
831 &KEY(op.inode, 0, 0),
832 sectors_dirty_init_fn,
835 pr_warn("sectors dirty init failed, ret=%d!\n", ret);
840 static int bch_dirty_init_thread(void *arg)
842 struct dirty_init_thrd_info *info = arg;
843 struct bch_dirty_init_state *state = info->state;
844 struct cache_set *c = state->c;
845 struct btree_iter iter;
847 int cur_idx, prev_idx, skip_nr;
850 cur_idx = prev_idx = 0;
852 bch_btree_iter_init(&c->root->keys, &iter, NULL);
853 k = bch_btree_iter_next_filter(&iter, &c->root->keys, bch_ptr_bad);
859 spin_lock(&state->idx_lock);
860 cur_idx = state->key_idx;
862 spin_unlock(&state->idx_lock);
864 skip_nr = cur_idx - prev_idx;
867 k = bch_btree_iter_next_filter(&iter,
873 atomic_set(&state->enough, 1);
874 /* Update state->enough earlier */
875 smp_mb__after_atomic();
882 if (bch_root_node_dirty_init(c, state->d, p) < 0)
891 /* In order to wake up state->wait in time */
892 smp_mb__before_atomic();
893 if (atomic_dec_and_test(&state->started))
894 wake_up(&state->wait);
899 static int bch_btre_dirty_init_thread_nr(void)
901 int n = num_online_cpus()/2;
905 else if (n > BCH_DIRTY_INIT_THRD_MAX)
906 n = BCH_DIRTY_INIT_THRD_MAX;
911 void bch_sectors_dirty_init(struct bcache_device *d)
914 struct bkey *k = NULL;
915 struct btree_iter iter;
916 struct sectors_dirty_init op;
917 struct cache_set *c = d->c;
918 struct bch_dirty_init_state state;
920 /* Just count root keys if no leaf node */
921 rw_lock(0, c->root, c->root->level);
922 if (c->root->level == 0) {
923 bch_btree_op_init(&op.op, -1);
927 for_each_key_filter(&c->root->keys,
928 k, &iter, bch_ptr_invalid)
929 sectors_dirty_init_fn(&op.op, c->root, k);
931 rw_unlock(0, c->root);
935 memset(&state, 0, sizeof(struct bch_dirty_init_state));
938 state.total_threads = bch_btre_dirty_init_thread_nr();
940 spin_lock_init(&state.idx_lock);
941 atomic_set(&state.started, 0);
942 atomic_set(&state.enough, 0);
943 init_waitqueue_head(&state.wait);
945 for (i = 0; i < state.total_threads; i++) {
946 /* Fetch latest state.enough earlier */
947 smp_mb__before_atomic();
948 if (atomic_read(&state.enough))
951 state.infos[i].state = &state;
952 state.infos[i].thread =
953 kthread_run(bch_dirty_init_thread, &state.infos[i],
954 "bch_dirtcnt[%d]", i);
955 if (IS_ERR(state.infos[i].thread)) {
956 pr_err("fails to run thread bch_dirty_init[%d]\n", i);
957 for (--i; i >= 0; i--)
958 kthread_stop(state.infos[i].thread);
961 atomic_inc(&state.started);
965 /* Must wait for all threads to stop. */
966 wait_event(state.wait, atomic_read(&state.started) == 0);
967 rw_unlock(0, c->root);
970 void bch_cached_dev_writeback_init(struct cached_dev *dc)
972 sema_init(&dc->in_flight, 64);
973 init_rwsem(&dc->writeback_lock);
974 bch_keybuf_init(&dc->writeback_keys);
976 dc->writeback_metadata = true;
977 dc->writeback_running = false;
978 dc->writeback_percent = 10;
979 dc->writeback_delay = 30;
980 atomic_long_set(&dc->writeback_rate.rate, 1024);
981 dc->writeback_rate_minimum = 8;
983 dc->writeback_rate_update_seconds = WRITEBACK_RATE_UPDATE_SECS_DEFAULT;
984 dc->writeback_rate_p_term_inverse = 40;
985 dc->writeback_rate_i_term_inverse = 10000;
987 WARN_ON(test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
988 INIT_DELAYED_WORK(&dc->writeback_rate_update, update_writeback_rate);
991 int bch_cached_dev_writeback_start(struct cached_dev *dc)
993 dc->writeback_write_wq = alloc_workqueue("bcache_writeback_wq",
995 if (!dc->writeback_write_wq)
999 dc->writeback_thread = kthread_create(bch_writeback_thread, dc,
1000 "bcache_writeback");
1001 if (IS_ERR(dc->writeback_thread)) {
1003 destroy_workqueue(dc->writeback_write_wq);
1004 return PTR_ERR(dc->writeback_thread);
1006 dc->writeback_running = true;
1008 WARN_ON(test_and_set_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
1009 schedule_delayed_work(&dc->writeback_rate_update,
1010 dc->writeback_rate_update_seconds * HZ);
1012 bch_writeback_queue(dc);