blob: 5767ff6c13e3388276b74b3bd16f281ed4b7ee53 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * background writeback - scan btree for dirty data and write it to the backing
4 * device
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 "writeback.h"
14
15#include <linux/delay.h>
16#include <linux/kthread.h>
17#include <linux/sched/clock.h>
18#include <trace/events/bcache.h>
19
20static void update_gc_after_writeback(struct cache_set *c)
21{
22 if (c->gc_after_writeback != (BCH_ENABLE_AUTO_GC) ||
23 c->gc_stats.in_use < BCH_AUTO_GC_DIRTY_THRESHOLD)
24 return;
25
26 c->gc_after_writeback |= BCH_DO_AUTO_GC;
27}
28
29/* Rate limiting */
30static uint64_t __calc_target_rate(struct cached_dev *dc)
31{
32 struct cache_set *c = dc->disk.c;
33
34 /*
35 * This is the size of the cache, minus the amount used for
36 * flash-only devices
37 */
38 uint64_t cache_sectors = c->nbuckets * c->sb.bucket_size -
39 atomic_long_read(&c->flash_dev_dirty_sectors);
40
41 /*
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.
46 */
47 uint32_t bdev_share =
48 div64_u64(bdev_sectors(dc->bdev) << WRITEBACK_SHARE_SHIFT,
49 c->cached_dev_sectors);
50
51 uint64_t cache_dirty_target =
52 div_u64(cache_sectors * dc->writeback_percent, 100);
53
54 /* Ensure each backing dev gets at least one dirty share */
55 if (bdev_share < 1)
56 bdev_share = 1;
57
58 return (cache_dirty_target * bdev_share) >> WRITEBACK_SHARE_SHIFT;
59}
60
61static void __update_writeback_rate(struct cached_dev *dc)
62{
63 /*
64 * PI controller:
65 * Figures out the amount that should be written per second.
66 *
67 * First, the error (number of sectors that are dirty beyond our
68 * target) is calculated. The error is accumulated (numerically
69 * integrated).
70 *
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.
77 *
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.
82 */
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;
89 uint32_t new_rate;
90
91 if ((error < 0 && dc->writeback_rate_integral > 0) ||
92 (error > 0 && time_before64(local_clock(),
93 dc->writeback_rate.next + NSEC_PER_MSEC))) {
94 /*
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).
99 *
100 * It's necessary to scale this by
101 * writeback_rate_update_seconds to keep the integral
102 * term dimensioned properly.
103 */
104 dc->writeback_rate_integral += error *
105 dc->writeback_rate_update_seconds;
106 }
107
108 integral_scaled = div_s64(dc->writeback_rate_integral,
109 dc->writeback_rate_i_term_inverse);
110
111 new_rate = clamp_t(int32_t, (proportional_scaled + integral_scaled),
112 dc->writeback_rate_minimum, NSEC_PER_SEC);
113
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;
120}
121
122static bool idle_counter_exceeded(struct cache_set *c)
123{
124 int counter, dev_nr;
125
126 /*
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
129 * simplicity.
130 */
131 counter = atomic_inc_return(&c->idle_counter);
132 if (counter <= 0) {
133 atomic_set(&c->idle_counter, 0);
134 return false;
135 }
136
137 dev_nr = atomic_read(&c->attached_dev_nr);
138 if (dev_nr == 0)
139 return false;
140
141 /*
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
146 * device attached.
147 * The following calculation equals to checking
148 * (counter / dev_nr) < (dev_nr * 6)
149 */
150 if (counter < (dev_nr * dev_nr * 6))
151 return false;
152
153 return true;
154}
155
156/*
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().
168 */
169static bool set_at_max_writeback_rate(struct cache_set *c,
170 struct cached_dev *dc)
171{
172 /* Don't set max writeback rate if gc is running */
173 if (!c->gc_mark_valid)
174 return false;
175
176 if (!idle_counter_exceeded(c))
177 return false;
178
179 if (atomic_read(&c->at_max_writeback_rate) != 1)
180 atomic_set(&c->at_max_writeback_rate, 1);
181
182 atomic_long_set(&dc->writeback_rate.rate, INT_MAX);
183
184 /* keep writeback_rate_target as existing value */
185 dc->writeback_rate_proportional = 0;
186 dc->writeback_rate_integral_scaled = 0;
187 dc->writeback_rate_change = 0;
188
189 /*
190 * In case new I/O arrives during before
191 * set_at_max_writeback_rate() returns.
192 */
193 if (!idle_counter_exceeded(c) ||
194 !atomic_read(&c->at_max_writeback_rate))
195 return false;
196
197 return true;
198}
199
200static void update_writeback_rate(struct work_struct *work)
201{
202 struct cached_dev *dc = container_of(to_delayed_work(work),
203 struct cached_dev,
204 writeback_rate_update);
205 struct cache_set *c = dc->disk.c;
206
207 /*
208 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
209 * cancel_delayed_work_sync().
210 */
211 set_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
212 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
213 smp_mb();
214
215 /*
216 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
217 * check it here too.
218 */
219 if (!test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) ||
220 test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
221 clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
222 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
223 smp_mb();
224 return;
225 }
226
227 if (atomic_read(&dc->has_dirty) && dc->writeback_percent) {
228 /*
229 * If the whole cache set is idle, set_at_max_writeback_rate()
230 * will set writeback rate to a max number. Then it is
231 * unncessary to update writeback rate for an idle cache set
232 * in maximum writeback rate number(s).
233 */
234 if (!set_at_max_writeback_rate(c, dc)) {
235 down_read(&dc->writeback_lock);
236 __update_writeback_rate(dc);
237 update_gc_after_writeback(c);
238 up_read(&dc->writeback_lock);
239 }
240 }
241
242
243 /*
244 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
245 * check it here too.
246 */
247 if (test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) &&
248 !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
249 schedule_delayed_work(&dc->writeback_rate_update,
250 dc->writeback_rate_update_seconds * HZ);
251 }
252
253 /*
254 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
255 * cancel_delayed_work_sync().
256 */
257 clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
258 /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
259 smp_mb();
260}
261
262static unsigned int writeback_delay(struct cached_dev *dc,
263 unsigned int sectors)
264{
265 if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
266 !dc->writeback_percent)
267 return 0;
268
269 return bch_next_delay(&dc->writeback_rate, sectors);
270}
271
272struct dirty_io {
273 struct closure cl;
274 struct cached_dev *dc;
275 uint16_t sequence;
276 struct bio bio;
277};
278
279static void dirty_init(struct keybuf_key *w)
280{
281 struct dirty_io *io = w->private;
282 struct bio *bio = &io->bio;
283
284 bio_init(bio, bio->bi_inline_vecs,
285 DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS));
286 if (!io->dc->writeback_percent)
287 bio_set_prio(bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
288
289 bio->bi_iter.bi_size = KEY_SIZE(&w->key) << 9;
290 bio->bi_private = w;
291 bch_bio_map(bio, NULL);
292}
293
294static void dirty_io_destructor(struct closure *cl)
295{
296 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
297
298 kfree(io);
299}
300
301static void write_dirty_finish(struct closure *cl)
302{
303 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
304 struct keybuf_key *w = io->bio.bi_private;
305 struct cached_dev *dc = io->dc;
306
307 bio_free_pages(&io->bio);
308
309 /* This is kind of a dumb way of signalling errors. */
310 if (KEY_DIRTY(&w->key)) {
311 int ret;
312 unsigned int i;
313 struct keylist keys;
314
315 bch_keylist_init(&keys);
316
317 bkey_copy(keys.top, &w->key);
318 SET_KEY_DIRTY(keys.top, false);
319 bch_keylist_push(&keys);
320
321 for (i = 0; i < KEY_PTRS(&w->key); i++)
322 atomic_inc(&PTR_BUCKET(dc->disk.c, &w->key, i)->pin);
323
324 ret = bch_btree_insert(dc->disk.c, &keys, NULL, &w->key);
325
326 if (ret)
327 trace_bcache_writeback_collision(&w->key);
328
329 atomic_long_inc(ret
330 ? &dc->disk.c->writeback_keys_failed
331 : &dc->disk.c->writeback_keys_done);
332 }
333
334 bch_keybuf_del(&dc->writeback_keys, w);
335 up(&dc->in_flight);
336
337 closure_return_with_destructor(cl, dirty_io_destructor);
338}
339
340static void dirty_endio(struct bio *bio)
341{
342 struct keybuf_key *w = bio->bi_private;
343 struct dirty_io *io = w->private;
344
345 if (bio->bi_status) {
346 SET_KEY_DIRTY(&w->key, false);
347 bch_count_backing_io_errors(io->dc, bio);
348 }
349
350 closure_put(&io->cl);
351}
352
353static void write_dirty(struct closure *cl)
354{
355 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
356 struct keybuf_key *w = io->bio.bi_private;
357 struct cached_dev *dc = io->dc;
358
359 uint16_t next_sequence;
360
361 if (atomic_read(&dc->writeback_sequence_next) != io->sequence) {
362 /* Not our turn to write; wait for a write to complete */
363 closure_wait(&dc->writeback_ordering_wait, cl);
364
365 if (atomic_read(&dc->writeback_sequence_next) == io->sequence) {
366 /*
367 * Edge case-- it happened in indeterminate order
368 * relative to when we were added to wait list..
369 */
370 closure_wake_up(&dc->writeback_ordering_wait);
371 }
372
373 continue_at(cl, write_dirty, io->dc->writeback_write_wq);
374 return;
375 }
376
377 next_sequence = io->sequence + 1;
378
379 /*
380 * IO errors are signalled using the dirty bit on the key.
381 * If we failed to read, we should not attempt to write to the
382 * backing device. Instead, immediately go to write_dirty_finish
383 * to clean up.
384 */
385 if (KEY_DIRTY(&w->key)) {
386 dirty_init(w);
387 bio_set_op_attrs(&io->bio, REQ_OP_WRITE, 0);
388 io->bio.bi_iter.bi_sector = KEY_START(&w->key);
389 bio_set_dev(&io->bio, io->dc->bdev);
390 io->bio.bi_end_io = dirty_endio;
391
392 /* I/O request sent to backing device */
393 closure_bio_submit(io->dc->disk.c, &io->bio, cl);
394 }
395
396 atomic_set(&dc->writeback_sequence_next, next_sequence);
397 closure_wake_up(&dc->writeback_ordering_wait);
398
399 continue_at(cl, write_dirty_finish, io->dc->writeback_write_wq);
400}
401
402static void read_dirty_endio(struct bio *bio)
403{
404 struct keybuf_key *w = bio->bi_private;
405 struct dirty_io *io = w->private;
406
407 /* is_read = 1 */
408 bch_count_io_errors(PTR_CACHE(io->dc->disk.c, &w->key, 0),
409 bio->bi_status, 1,
410 "reading dirty data from cache");
411
412 dirty_endio(bio);
413}
414
415static void read_dirty_submit(struct closure *cl)
416{
417 struct dirty_io *io = container_of(cl, struct dirty_io, cl);
418
419 closure_bio_submit(io->dc->disk.c, &io->bio, cl);
420
421 continue_at(cl, write_dirty, io->dc->writeback_write_wq);
422}
423
424static void read_dirty(struct cached_dev *dc)
425{
426 unsigned int delay = 0;
427 struct keybuf_key *next, *keys[MAX_WRITEBACKS_IN_PASS], *w;
428 size_t size;
429 int nk, i;
430 struct dirty_io *io;
431 struct closure cl;
432 uint16_t sequence = 0;
433
434 BUG_ON(!llist_empty(&dc->writeback_ordering_wait.list));
435 atomic_set(&dc->writeback_sequence_next, sequence);
436 closure_init_stack(&cl);
437
438 /*
439 * XXX: if we error, background writeback just spins. Should use some
440 * mempools.
441 */
442
443 next = bch_keybuf_next(&dc->writeback_keys);
444
445 while (!kthread_should_stop() &&
446 !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
447 next) {
448 size = 0;
449 nk = 0;
450
451 do {
452 BUG_ON(ptr_stale(dc->disk.c, &next->key, 0));
453
454 /*
455 * Don't combine too many operations, even if they
456 * are all small.
457 */
458 if (nk >= MAX_WRITEBACKS_IN_PASS)
459 break;
460
461 /*
462 * If the current operation is very large, don't
463 * further combine operations.
464 */
465 if (size >= MAX_WRITESIZE_IN_PASS)
466 break;
467
468 /*
469 * Operations are only eligible to be combined
470 * if they are contiguous.
471 *
472 * TODO: add a heuristic willing to fire a
473 * certain amount of non-contiguous IO per pass,
474 * so that we can benefit from backing device
475 * command queueing.
476 */
477 if ((nk != 0) && bkey_cmp(&keys[nk-1]->key,
478 &START_KEY(&next->key)))
479 break;
480
481 size += KEY_SIZE(&next->key);
482 keys[nk++] = next;
483 } while ((next = bch_keybuf_next(&dc->writeback_keys)));
484
485 /* Now we have gathered a set of 1..5 keys to write back. */
486 for (i = 0; i < nk; i++) {
487 w = keys[i];
488
489 io = kzalloc(sizeof(struct dirty_io) +
490 sizeof(struct bio_vec) *
491 DIV_ROUND_UP(KEY_SIZE(&w->key),
492 PAGE_SECTORS),
493 GFP_KERNEL);
494 if (!io)
495 goto err;
496
497 w->private = io;
498 io->dc = dc;
499 io->sequence = sequence++;
500
501 dirty_init(w);
502 bio_set_op_attrs(&io->bio, REQ_OP_READ, 0);
503 io->bio.bi_iter.bi_sector = PTR_OFFSET(&w->key, 0);
504 bio_set_dev(&io->bio,
505 PTR_CACHE(dc->disk.c, &w->key, 0)->bdev);
506 io->bio.bi_end_io = read_dirty_endio;
507
508 if (bch_bio_alloc_pages(&io->bio, GFP_KERNEL))
509 goto err_free;
510
511 trace_bcache_writeback(&w->key);
512
513 down(&dc->in_flight);
514
515 /*
516 * We've acquired a semaphore for the maximum
517 * simultaneous number of writebacks; from here
518 * everything happens asynchronously.
519 */
520 closure_call(&io->cl, read_dirty_submit, NULL, &cl);
521 }
522
523 delay = writeback_delay(dc, size);
524
525 while (!kthread_should_stop() &&
526 !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
527 delay) {
528 schedule_timeout_interruptible(delay);
529 delay = writeback_delay(dc, 0);
530 }
531 }
532
533 if (0) {
534err_free:
535 kfree(w->private);
536err:
537 bch_keybuf_del(&dc->writeback_keys, w);
538 }
539
540 /*
541 * Wait for outstanding writeback IOs to finish (and keybuf slots to be
542 * freed) before refilling again
543 */
544 closure_sync(&cl);
545}
546
547/* Scan for dirty data */
548
549void bcache_dev_sectors_dirty_add(struct cache_set *c, unsigned int inode,
550 uint64_t offset, int nr_sectors)
551{
552 struct bcache_device *d = c->devices[inode];
553 unsigned int stripe_offset, sectors_dirty;
554 int stripe;
555
556 if (!d)
557 return;
558
559 stripe = offset_to_stripe(d, offset);
560 if (stripe < 0)
561 return;
562
563 if (UUID_FLASH_ONLY(&c->uuids[inode]))
564 atomic_long_add(nr_sectors, &c->flash_dev_dirty_sectors);
565
566 stripe_offset = offset & (d->stripe_size - 1);
567
568 while (nr_sectors) {
569 int s = min_t(unsigned int, abs(nr_sectors),
570 d->stripe_size - stripe_offset);
571
572 if (nr_sectors < 0)
573 s = -s;
574
575 if (stripe >= d->nr_stripes)
576 return;
577
578 sectors_dirty = atomic_add_return(s,
579 d->stripe_sectors_dirty + stripe);
580 if (sectors_dirty == d->stripe_size)
581 set_bit(stripe, d->full_dirty_stripes);
582 else
583 clear_bit(stripe, d->full_dirty_stripes);
584
585 nr_sectors -= s;
586 stripe_offset = 0;
587 stripe++;
588 }
589}
590
591static bool dirty_pred(struct keybuf *buf, struct bkey *k)
592{
593 struct cached_dev *dc = container_of(buf,
594 struct cached_dev,
595 writeback_keys);
596
597 BUG_ON(KEY_INODE(k) != dc->disk.id);
598
599 return KEY_DIRTY(k);
600}
601
602static void refill_full_stripes(struct cached_dev *dc)
603{
604 struct keybuf *buf = &dc->writeback_keys;
605 unsigned int start_stripe, next_stripe;
606 int stripe;
607 bool wrapped = false;
608
609 stripe = offset_to_stripe(&dc->disk, KEY_OFFSET(&buf->last_scanned));
610 if (stripe < 0)
611 stripe = 0;
612
613 start_stripe = stripe;
614
615 while (1) {
616 stripe = find_next_bit(dc->disk.full_dirty_stripes,
617 dc->disk.nr_stripes, stripe);
618
619 if (stripe == dc->disk.nr_stripes)
620 goto next;
621
622 next_stripe = find_next_zero_bit(dc->disk.full_dirty_stripes,
623 dc->disk.nr_stripes, stripe);
624
625 buf->last_scanned = KEY(dc->disk.id,
626 stripe * dc->disk.stripe_size, 0);
627
628 bch_refill_keybuf(dc->disk.c, buf,
629 &KEY(dc->disk.id,
630 next_stripe * dc->disk.stripe_size, 0),
631 dirty_pred);
632
633 if (array_freelist_empty(&buf->freelist))
634 return;
635
636 stripe = next_stripe;
637next:
638 if (wrapped && stripe > start_stripe)
639 return;
640
641 if (stripe == dc->disk.nr_stripes) {
642 stripe = 0;
643 wrapped = true;
644 }
645 }
646}
647
648/*
649 * Returns true if we scanned the entire disk
650 */
651static bool refill_dirty(struct cached_dev *dc)
652{
653 struct keybuf *buf = &dc->writeback_keys;
654 struct bkey start = KEY(dc->disk.id, 0, 0);
655 struct bkey end = KEY(dc->disk.id, MAX_KEY_OFFSET, 0);
656 struct bkey start_pos;
657
658 /*
659 * make sure keybuf pos is inside the range for this disk - at bringup
660 * we might not be attached yet so this disk's inode nr isn't
661 * initialized then
662 */
663 if (bkey_cmp(&buf->last_scanned, &start) < 0 ||
664 bkey_cmp(&buf->last_scanned, &end) > 0)
665 buf->last_scanned = start;
666
667 if (dc->partial_stripes_expensive) {
668 refill_full_stripes(dc);
669 if (array_freelist_empty(&buf->freelist))
670 return false;
671 }
672
673 start_pos = buf->last_scanned;
674 bch_refill_keybuf(dc->disk.c, buf, &end, dirty_pred);
675
676 if (bkey_cmp(&buf->last_scanned, &end) < 0)
677 return false;
678
679 /*
680 * If we get to the end start scanning again from the beginning, and
681 * only scan up to where we initially started scanning from:
682 */
683 buf->last_scanned = start;
684 bch_refill_keybuf(dc->disk.c, buf, &start_pos, dirty_pred);
685
686 return bkey_cmp(&buf->last_scanned, &start_pos) >= 0;
687}
688
689static int bch_writeback_thread(void *arg)
690{
691 struct cached_dev *dc = arg;
692 struct cache_set *c = dc->disk.c;
693 bool searched_full_index;
694
695 bch_ratelimit_reset(&dc->writeback_rate);
696
697 while (!kthread_should_stop() &&
698 !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
699 down_write(&dc->writeback_lock);
700 set_current_state(TASK_INTERRUPTIBLE);
701 /*
702 * If the bache device is detaching, skip here and continue
703 * to perform writeback. Otherwise, if no dirty data on cache,
704 * or there is dirty data on cache but writeback is disabled,
705 * the writeback thread should sleep here and wait for others
706 * to wake up it.
707 */
708 if (!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) &&
709 (!atomic_read(&dc->has_dirty) || !dc->writeback_running)) {
710 up_write(&dc->writeback_lock);
711
712 if (kthread_should_stop() ||
713 test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
714 set_current_state(TASK_RUNNING);
715 break;
716 }
717
718 schedule();
719 continue;
720 }
721 set_current_state(TASK_RUNNING);
722
723 searched_full_index = refill_dirty(dc);
724
725 if (searched_full_index &&
726 RB_EMPTY_ROOT(&dc->writeback_keys.keys)) {
727 atomic_set(&dc->has_dirty, 0);
728 SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
729 bch_write_bdev_super(dc, NULL);
730 /*
731 * If bcache device is detaching via sysfs interface,
732 * writeback thread should stop after there is no dirty
733 * data on cache. BCACHE_DEV_DETACHING flag is set in
734 * bch_cached_dev_detach().
735 */
736 if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags)) {
737 up_write(&dc->writeback_lock);
738 break;
739 }
740
741 /*
742 * When dirty data rate is high (e.g. 50%+), there might
743 * be heavy buckets fragmentation after writeback
744 * finished, which hurts following write performance.
745 * If users really care about write performance they
746 * may set BCH_ENABLE_AUTO_GC via sysfs, then when
747 * BCH_DO_AUTO_GC is set, garbage collection thread
748 * will be wake up here. After moving gc, the shrunk
749 * btree and discarded free buckets SSD space may be
750 * helpful for following write requests.
751 */
752 if (c->gc_after_writeback ==
753 (BCH_ENABLE_AUTO_GC|BCH_DO_AUTO_GC)) {
754 c->gc_after_writeback &= ~BCH_DO_AUTO_GC;
755 force_wake_up_gc(c);
756 }
757 }
758
759 up_write(&dc->writeback_lock);
760
761 read_dirty(dc);
762
763 if (searched_full_index) {
764 unsigned int delay = dc->writeback_delay * HZ;
765
766 while (delay &&
767 !kthread_should_stop() &&
768 !test_bit(CACHE_SET_IO_DISABLE, &c->flags) &&
769 !test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
770 delay = schedule_timeout_interruptible(delay);
771
772 bch_ratelimit_reset(&dc->writeback_rate);
773 }
774 }
775
776 if (dc->writeback_write_wq) {
777 flush_workqueue(dc->writeback_write_wq);
778 destroy_workqueue(dc->writeback_write_wq);
779 }
780 cached_dev_put(dc);
781 wait_for_kthread_stop();
782
783 return 0;
784}
785
786/* Init */
787#define INIT_KEYS_EACH_TIME 500000
788#define INIT_KEYS_SLEEP_MS 100
789
790struct sectors_dirty_init {
791 struct btree_op op;
792 unsigned int inode;
793 size_t count;
794 struct bkey start;
795};
796
797static int sectors_dirty_init_fn(struct btree_op *_op, struct btree *b,
798 struct bkey *k)
799{
800 struct sectors_dirty_init *op = container_of(_op,
801 struct sectors_dirty_init, op);
802 if (KEY_INODE(k) > op->inode)
803 return MAP_DONE;
804
805 if (KEY_DIRTY(k))
806 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
807 KEY_START(k), KEY_SIZE(k));
808
809 op->count++;
810 if (atomic_read(&b->c->search_inflight) &&
811 !(op->count % INIT_KEYS_EACH_TIME)) {
812 bkey_copy_key(&op->start, k);
813 return -EAGAIN;
814 }
815
816 return MAP_CONTINUE;
817}
818
819void bch_sectors_dirty_init(struct bcache_device *d)
820{
821 struct sectors_dirty_init op;
822 int ret;
823
824 bch_btree_op_init(&op.op, -1);
825 op.inode = d->id;
826 op.count = 0;
827 op.start = KEY(op.inode, 0, 0);
828
829 do {
830 ret = bch_btree_map_keys(&op.op, d->c, &op.start,
831 sectors_dirty_init_fn, 0);
832 if (ret == -EAGAIN)
833 schedule_timeout_interruptible(
834 msecs_to_jiffies(INIT_KEYS_SLEEP_MS));
835 else if (ret < 0) {
836 pr_warn("sectors dirty init failed, ret=%d!", ret);
837 break;
838 }
839 } while (ret == -EAGAIN);
840}
841
842void bch_cached_dev_writeback_init(struct cached_dev *dc)
843{
844 sema_init(&dc->in_flight, 64);
845 init_rwsem(&dc->writeback_lock);
846 bch_keybuf_init(&dc->writeback_keys);
847
848 dc->writeback_metadata = true;
849 dc->writeback_running = false;
850 dc->writeback_percent = 10;
851 dc->writeback_delay = 30;
852 atomic_long_set(&dc->writeback_rate.rate, 1024);
853 dc->writeback_rate_minimum = 8;
854
855 dc->writeback_rate_update_seconds = WRITEBACK_RATE_UPDATE_SECS_DEFAULT;
856 dc->writeback_rate_p_term_inverse = 40;
857 dc->writeback_rate_i_term_inverse = 10000;
858
859 WARN_ON(test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
860 INIT_DELAYED_WORK(&dc->writeback_rate_update, update_writeback_rate);
861}
862
863int bch_cached_dev_writeback_start(struct cached_dev *dc)
864{
865 dc->writeback_write_wq = alloc_workqueue("bcache_writeback_wq",
866 WQ_MEM_RECLAIM, 0);
867 if (!dc->writeback_write_wq)
868 return -ENOMEM;
869
870 cached_dev_get(dc);
871 dc->writeback_thread = kthread_create(bch_writeback_thread, dc,
872 "bcache_writeback");
873 if (IS_ERR(dc->writeback_thread)) {
874 cached_dev_put(dc);
875 destroy_workqueue(dc->writeback_write_wq);
876 return PTR_ERR(dc->writeback_thread);
877 }
878 dc->writeback_running = true;
879
880 WARN_ON(test_and_set_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
881 schedule_delayed_work(&dc->writeback_rate_update,
882 dc->writeback_rate_update_seconds * HZ);
883
884 bch_writeback_queue(dc);
885
886 return 0;
887}