xref: /openbmc/linux/drivers/md/bcache/writeback.c (revision 2359ccdd)
1 // 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 
20 /* Rate limiting */
21 static uint64_t __calc_target_rate(struct cached_dev *dc)
22 {
23 	struct cache_set *c = dc->disk.c;
24 
25 	/*
26 	 * This is the size of the cache, minus the amount used for
27 	 * flash-only devices
28 	 */
29 	uint64_t cache_sectors = c->nbuckets * c->sb.bucket_size -
30 				bcache_flash_devs_sectors_dirty(c);
31 
32 	/*
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.
37 	 */
38 	uint32_t bdev_share =
39 		div64_u64(bdev_sectors(dc->bdev) << WRITEBACK_SHARE_SHIFT,
40 				c->cached_dev_sectors);
41 
42 	uint64_t cache_dirty_target =
43 		div_u64(cache_sectors * dc->writeback_percent, 100);
44 
45 	/* Ensure each backing dev gets at least one dirty share */
46 	if (bdev_share < 1)
47 		bdev_share = 1;
48 
49 	return (cache_dirty_target * bdev_share) >> WRITEBACK_SHARE_SHIFT;
50 }
51 
52 static void __update_writeback_rate(struct cached_dev *dc)
53 {
54 	/*
55 	 * PI controller:
56 	 * Figures out the amount that should be written per second.
57 	 *
58 	 * First, the error (number of sectors that are dirty beyond our
59 	 * target) is calculated.  The error is accumulated (numerically
60 	 * integrated).
61 	 *
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.
68 	 *
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.
73 	 */
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;
80 	uint32_t new_rate;
81 
82 	if ((error < 0 && dc->writeback_rate_integral > 0) ||
83 	    (error > 0 && time_before64(local_clock(),
84 			 dc->writeback_rate.next + NSEC_PER_MSEC))) {
85 		/*
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).
90 		 *
91 		 * It's necessary to scale this by
92 		 * writeback_rate_update_seconds to keep the integral
93 		 * term dimensioned properly.
94 		 */
95 		dc->writeback_rate_integral += error *
96 			dc->writeback_rate_update_seconds;
97 	}
98 
99 	integral_scaled = div_s64(dc->writeback_rate_integral,
100 			dc->writeback_rate_i_term_inverse);
101 
102 	new_rate = clamp_t(int32_t, (proportional_scaled + integral_scaled),
103 			dc->writeback_rate_minimum, NSEC_PER_SEC);
104 
105 	dc->writeback_rate_proportional = proportional_scaled;
106 	dc->writeback_rate_integral_scaled = integral_scaled;
107 	dc->writeback_rate_change = new_rate - dc->writeback_rate.rate;
108 	dc->writeback_rate.rate = new_rate;
109 	dc->writeback_rate_target = target;
110 }
111 
112 static void update_writeback_rate(struct work_struct *work)
113 {
114 	struct cached_dev *dc = container_of(to_delayed_work(work),
115 					     struct cached_dev,
116 					     writeback_rate_update);
117 	struct cache_set *c = dc->disk.c;
118 
119 	/*
120 	 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
121 	 * cancel_delayed_work_sync().
122 	 */
123 	set_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
124 	/* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
125 	smp_mb();
126 
127 	/*
128 	 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
129 	 * check it here too.
130 	 */
131 	if (!test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) ||
132 	    test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
133 		clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
134 		/* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
135 		smp_mb();
136 		return;
137 	}
138 
139 	down_read(&dc->writeback_lock);
140 
141 	if (atomic_read(&dc->has_dirty) &&
142 	    dc->writeback_percent)
143 		__update_writeback_rate(dc);
144 
145 	up_read(&dc->writeback_lock);
146 
147 	/*
148 	 * CACHE_SET_IO_DISABLE might be set via sysfs interface,
149 	 * check it here too.
150 	 */
151 	if (test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) &&
152 	    !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
153 		schedule_delayed_work(&dc->writeback_rate_update,
154 			      dc->writeback_rate_update_seconds * HZ);
155 	}
156 
157 	/*
158 	 * should check BCACHE_DEV_RATE_DW_RUNNING before calling
159 	 * cancel_delayed_work_sync().
160 	 */
161 	clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
162 	/* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
163 	smp_mb();
164 }
165 
166 static unsigned writeback_delay(struct cached_dev *dc, unsigned sectors)
167 {
168 	if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
169 	    !dc->writeback_percent)
170 		return 0;
171 
172 	return bch_next_delay(&dc->writeback_rate, sectors);
173 }
174 
175 struct dirty_io {
176 	struct closure		cl;
177 	struct cached_dev	*dc;
178 	uint16_t		sequence;
179 	struct bio		bio;
180 };
181 
182 static void dirty_init(struct keybuf_key *w)
183 {
184 	struct dirty_io *io = w->private;
185 	struct bio *bio = &io->bio;
186 
187 	bio_init(bio, bio->bi_inline_vecs,
188 		 DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS));
189 	if (!io->dc->writeback_percent)
190 		bio_set_prio(bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
191 
192 	bio->bi_iter.bi_size	= KEY_SIZE(&w->key) << 9;
193 	bio->bi_private		= w;
194 	bch_bio_map(bio, NULL);
195 }
196 
197 static void dirty_io_destructor(struct closure *cl)
198 {
199 	struct dirty_io *io = container_of(cl, struct dirty_io, cl);
200 	kfree(io);
201 }
202 
203 static void write_dirty_finish(struct closure *cl)
204 {
205 	struct dirty_io *io = container_of(cl, struct dirty_io, cl);
206 	struct keybuf_key *w = io->bio.bi_private;
207 	struct cached_dev *dc = io->dc;
208 
209 	bio_free_pages(&io->bio);
210 
211 	/* This is kind of a dumb way of signalling errors. */
212 	if (KEY_DIRTY(&w->key)) {
213 		int ret;
214 		unsigned i;
215 		struct keylist keys;
216 
217 		bch_keylist_init(&keys);
218 
219 		bkey_copy(keys.top, &w->key);
220 		SET_KEY_DIRTY(keys.top, false);
221 		bch_keylist_push(&keys);
222 
223 		for (i = 0; i < KEY_PTRS(&w->key); i++)
224 			atomic_inc(&PTR_BUCKET(dc->disk.c, &w->key, i)->pin);
225 
226 		ret = bch_btree_insert(dc->disk.c, &keys, NULL, &w->key);
227 
228 		if (ret)
229 			trace_bcache_writeback_collision(&w->key);
230 
231 		atomic_long_inc(ret
232 				? &dc->disk.c->writeback_keys_failed
233 				: &dc->disk.c->writeback_keys_done);
234 	}
235 
236 	bch_keybuf_del(&dc->writeback_keys, w);
237 	up(&dc->in_flight);
238 
239 	closure_return_with_destructor(cl, dirty_io_destructor);
240 }
241 
242 static void dirty_endio(struct bio *bio)
243 {
244 	struct keybuf_key *w = bio->bi_private;
245 	struct dirty_io *io = w->private;
246 
247 	if (bio->bi_status)
248 		SET_KEY_DIRTY(&w->key, false);
249 
250 	closure_put(&io->cl);
251 }
252 
253 static void write_dirty(struct closure *cl)
254 {
255 	struct dirty_io *io = container_of(cl, struct dirty_io, cl);
256 	struct keybuf_key *w = io->bio.bi_private;
257 	struct cached_dev *dc = io->dc;
258 
259 	uint16_t next_sequence;
260 
261 	if (atomic_read(&dc->writeback_sequence_next) != io->sequence) {
262 		/* Not our turn to write; wait for a write to complete */
263 		closure_wait(&dc->writeback_ordering_wait, cl);
264 
265 		if (atomic_read(&dc->writeback_sequence_next) == io->sequence) {
266 			/*
267 			 * Edge case-- it happened in indeterminate order
268 			 * relative to when we were added to wait list..
269 			 */
270 			closure_wake_up(&dc->writeback_ordering_wait);
271 		}
272 
273 		continue_at(cl, write_dirty, io->dc->writeback_write_wq);
274 		return;
275 	}
276 
277 	next_sequence = io->sequence + 1;
278 
279 	/*
280 	 * IO errors are signalled using the dirty bit on the key.
281 	 * If we failed to read, we should not attempt to write to the
282 	 * backing device.  Instead, immediately go to write_dirty_finish
283 	 * to clean up.
284 	 */
285 	if (KEY_DIRTY(&w->key)) {
286 		dirty_init(w);
287 		bio_set_op_attrs(&io->bio, REQ_OP_WRITE, 0);
288 		io->bio.bi_iter.bi_sector = KEY_START(&w->key);
289 		bio_set_dev(&io->bio, io->dc->bdev);
290 		io->bio.bi_end_io	= dirty_endio;
291 
292 		/* I/O request sent to backing device */
293 		closure_bio_submit(io->dc->disk.c, &io->bio, cl);
294 	}
295 
296 	atomic_set(&dc->writeback_sequence_next, next_sequence);
297 	closure_wake_up(&dc->writeback_ordering_wait);
298 
299 	continue_at(cl, write_dirty_finish, io->dc->writeback_write_wq);
300 }
301 
302 static void read_dirty_endio(struct bio *bio)
303 {
304 	struct keybuf_key *w = bio->bi_private;
305 	struct dirty_io *io = w->private;
306 
307 	/* is_read = 1 */
308 	bch_count_io_errors(PTR_CACHE(io->dc->disk.c, &w->key, 0),
309 			    bio->bi_status, 1,
310 			    "reading dirty data from cache");
311 
312 	dirty_endio(bio);
313 }
314 
315 static void read_dirty_submit(struct closure *cl)
316 {
317 	struct dirty_io *io = container_of(cl, struct dirty_io, cl);
318 
319 	closure_bio_submit(io->dc->disk.c, &io->bio, cl);
320 
321 	continue_at(cl, write_dirty, io->dc->writeback_write_wq);
322 }
323 
324 static void read_dirty(struct cached_dev *dc)
325 {
326 	unsigned delay = 0;
327 	struct keybuf_key *next, *keys[MAX_WRITEBACKS_IN_PASS], *w;
328 	size_t size;
329 	int nk, i;
330 	struct dirty_io *io;
331 	struct closure cl;
332 	uint16_t sequence = 0;
333 
334 	BUG_ON(!llist_empty(&dc->writeback_ordering_wait.list));
335 	atomic_set(&dc->writeback_sequence_next, sequence);
336 	closure_init_stack(&cl);
337 
338 	/*
339 	 * XXX: if we error, background writeback just spins. Should use some
340 	 * mempools.
341 	 */
342 
343 	next = bch_keybuf_next(&dc->writeback_keys);
344 
345 	while (!kthread_should_stop() &&
346 	       !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
347 	       next) {
348 		size = 0;
349 		nk = 0;
350 
351 		do {
352 			BUG_ON(ptr_stale(dc->disk.c, &next->key, 0));
353 
354 			/*
355 			 * Don't combine too many operations, even if they
356 			 * are all small.
357 			 */
358 			if (nk >= MAX_WRITEBACKS_IN_PASS)
359 				break;
360 
361 			/*
362 			 * If the current operation is very large, don't
363 			 * further combine operations.
364 			 */
365 			if (size >= MAX_WRITESIZE_IN_PASS)
366 				break;
367 
368 			/*
369 			 * Operations are only eligible to be combined
370 			 * if they are contiguous.
371 			 *
372 			 * TODO: add a heuristic willing to fire a
373 			 * certain amount of non-contiguous IO per pass,
374 			 * so that we can benefit from backing device
375 			 * command queueing.
376 			 */
377 			if ((nk != 0) && bkey_cmp(&keys[nk-1]->key,
378 						&START_KEY(&next->key)))
379 				break;
380 
381 			size += KEY_SIZE(&next->key);
382 			keys[nk++] = next;
383 		} while ((next = bch_keybuf_next(&dc->writeback_keys)));
384 
385 		/* Now we have gathered a set of 1..5 keys to write back. */
386 		for (i = 0; i < nk; i++) {
387 			w = keys[i];
388 
389 			io = kzalloc(sizeof(struct dirty_io) +
390 				     sizeof(struct bio_vec) *
391 				     DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS),
392 				     GFP_KERNEL);
393 			if (!io)
394 				goto err;
395 
396 			w->private	= io;
397 			io->dc		= dc;
398 			io->sequence    = sequence++;
399 
400 			dirty_init(w);
401 			bio_set_op_attrs(&io->bio, REQ_OP_READ, 0);
402 			io->bio.bi_iter.bi_sector = PTR_OFFSET(&w->key, 0);
403 			bio_set_dev(&io->bio,
404 				    PTR_CACHE(dc->disk.c, &w->key, 0)->bdev);
405 			io->bio.bi_end_io	= read_dirty_endio;
406 
407 			if (bch_bio_alloc_pages(&io->bio, GFP_KERNEL))
408 				goto err_free;
409 
410 			trace_bcache_writeback(&w->key);
411 
412 			down(&dc->in_flight);
413 
414 			/* We've acquired a semaphore for the maximum
415 			 * simultaneous number of writebacks; from here
416 			 * everything happens asynchronously.
417 			 */
418 			closure_call(&io->cl, read_dirty_submit, NULL, &cl);
419 		}
420 
421 		delay = writeback_delay(dc, size);
422 
423 		/* If the control system would wait for at least half a
424 		 * second, and there's been no reqs hitting the backing disk
425 		 * for awhile: use an alternate mode where we have at most
426 		 * one contiguous set of writebacks in flight at a time.  If
427 		 * someone wants to do IO it will be quick, as it will only
428 		 * have to contend with one operation in flight, and we'll
429 		 * be round-tripping data to the backing disk as quickly as
430 		 * it can accept it.
431 		 */
432 		if (delay >= HZ / 2) {
433 			/* 3 means at least 1.5 seconds, up to 7.5 if we
434 			 * have slowed way down.
435 			 */
436 			if (atomic_inc_return(&dc->backing_idle) >= 3) {
437 				/* Wait for current I/Os to finish */
438 				closure_sync(&cl);
439 				/* And immediately launch a new set. */
440 				delay = 0;
441 			}
442 		}
443 
444 		while (!kthread_should_stop() &&
445 		       !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
446 		       delay) {
447 			schedule_timeout_interruptible(delay);
448 			delay = writeback_delay(dc, 0);
449 		}
450 	}
451 
452 	if (0) {
453 err_free:
454 		kfree(w->private);
455 err:
456 		bch_keybuf_del(&dc->writeback_keys, w);
457 	}
458 
459 	/*
460 	 * Wait for outstanding writeback IOs to finish (and keybuf slots to be
461 	 * freed) before refilling again
462 	 */
463 	closure_sync(&cl);
464 }
465 
466 /* Scan for dirty data */
467 
468 void bcache_dev_sectors_dirty_add(struct cache_set *c, unsigned inode,
469 				  uint64_t offset, int nr_sectors)
470 {
471 	struct bcache_device *d = c->devices[inode];
472 	unsigned stripe_offset, stripe, sectors_dirty;
473 
474 	if (!d)
475 		return;
476 
477 	stripe = offset_to_stripe(d, offset);
478 	stripe_offset = offset & (d->stripe_size - 1);
479 
480 	while (nr_sectors) {
481 		int s = min_t(unsigned, abs(nr_sectors),
482 			      d->stripe_size - stripe_offset);
483 
484 		if (nr_sectors < 0)
485 			s = -s;
486 
487 		if (stripe >= d->nr_stripes)
488 			return;
489 
490 		sectors_dirty = atomic_add_return(s,
491 					d->stripe_sectors_dirty + stripe);
492 		if (sectors_dirty == d->stripe_size)
493 			set_bit(stripe, d->full_dirty_stripes);
494 		else
495 			clear_bit(stripe, d->full_dirty_stripes);
496 
497 		nr_sectors -= s;
498 		stripe_offset = 0;
499 		stripe++;
500 	}
501 }
502 
503 static bool dirty_pred(struct keybuf *buf, struct bkey *k)
504 {
505 	struct cached_dev *dc = container_of(buf, struct cached_dev, writeback_keys);
506 
507 	BUG_ON(KEY_INODE(k) != dc->disk.id);
508 
509 	return KEY_DIRTY(k);
510 }
511 
512 static void refill_full_stripes(struct cached_dev *dc)
513 {
514 	struct keybuf *buf = &dc->writeback_keys;
515 	unsigned start_stripe, stripe, next_stripe;
516 	bool wrapped = false;
517 
518 	stripe = offset_to_stripe(&dc->disk, KEY_OFFSET(&buf->last_scanned));
519 
520 	if (stripe >= dc->disk.nr_stripes)
521 		stripe = 0;
522 
523 	start_stripe = stripe;
524 
525 	while (1) {
526 		stripe = find_next_bit(dc->disk.full_dirty_stripes,
527 				       dc->disk.nr_stripes, stripe);
528 
529 		if (stripe == dc->disk.nr_stripes)
530 			goto next;
531 
532 		next_stripe = find_next_zero_bit(dc->disk.full_dirty_stripes,
533 						 dc->disk.nr_stripes, stripe);
534 
535 		buf->last_scanned = KEY(dc->disk.id,
536 					stripe * dc->disk.stripe_size, 0);
537 
538 		bch_refill_keybuf(dc->disk.c, buf,
539 				  &KEY(dc->disk.id,
540 				       next_stripe * dc->disk.stripe_size, 0),
541 				  dirty_pred);
542 
543 		if (array_freelist_empty(&buf->freelist))
544 			return;
545 
546 		stripe = next_stripe;
547 next:
548 		if (wrapped && stripe > start_stripe)
549 			return;
550 
551 		if (stripe == dc->disk.nr_stripes) {
552 			stripe = 0;
553 			wrapped = true;
554 		}
555 	}
556 }
557 
558 /*
559  * Returns true if we scanned the entire disk
560  */
561 static bool refill_dirty(struct cached_dev *dc)
562 {
563 	struct keybuf *buf = &dc->writeback_keys;
564 	struct bkey start = KEY(dc->disk.id, 0, 0);
565 	struct bkey end = KEY(dc->disk.id, MAX_KEY_OFFSET, 0);
566 	struct bkey start_pos;
567 
568 	/*
569 	 * make sure keybuf pos is inside the range for this disk - at bringup
570 	 * we might not be attached yet so this disk's inode nr isn't
571 	 * initialized then
572 	 */
573 	if (bkey_cmp(&buf->last_scanned, &start) < 0 ||
574 	    bkey_cmp(&buf->last_scanned, &end) > 0)
575 		buf->last_scanned = start;
576 
577 	if (dc->partial_stripes_expensive) {
578 		refill_full_stripes(dc);
579 		if (array_freelist_empty(&buf->freelist))
580 			return false;
581 	}
582 
583 	start_pos = buf->last_scanned;
584 	bch_refill_keybuf(dc->disk.c, buf, &end, dirty_pred);
585 
586 	if (bkey_cmp(&buf->last_scanned, &end) < 0)
587 		return false;
588 
589 	/*
590 	 * If we get to the end start scanning again from the beginning, and
591 	 * only scan up to where we initially started scanning from:
592 	 */
593 	buf->last_scanned = start;
594 	bch_refill_keybuf(dc->disk.c, buf, &start_pos, dirty_pred);
595 
596 	return bkey_cmp(&buf->last_scanned, &start_pos) >= 0;
597 }
598 
599 static int bch_writeback_thread(void *arg)
600 {
601 	struct cached_dev *dc = arg;
602 	struct cache_set *c = dc->disk.c;
603 	bool searched_full_index;
604 
605 	bch_ratelimit_reset(&dc->writeback_rate);
606 
607 	while (!kthread_should_stop() &&
608 	       !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
609 		down_write(&dc->writeback_lock);
610 		set_current_state(TASK_INTERRUPTIBLE);
611 		/*
612 		 * If the bache device is detaching, skip here and continue
613 		 * to perform writeback. Otherwise, if no dirty data on cache,
614 		 * or there is dirty data on cache but writeback is disabled,
615 		 * the writeback thread should sleep here and wait for others
616 		 * to wake up it.
617 		 */
618 		if (!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) &&
619 		    (!atomic_read(&dc->has_dirty) || !dc->writeback_running)) {
620 			up_write(&dc->writeback_lock);
621 
622 			if (kthread_should_stop() ||
623 			    test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
624 				set_current_state(TASK_RUNNING);
625 				break;
626 			}
627 
628 			schedule();
629 			continue;
630 		}
631 		set_current_state(TASK_RUNNING);
632 
633 		searched_full_index = refill_dirty(dc);
634 
635 		if (searched_full_index &&
636 		    RB_EMPTY_ROOT(&dc->writeback_keys.keys)) {
637 			atomic_set(&dc->has_dirty, 0);
638 			SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
639 			bch_write_bdev_super(dc, NULL);
640 			/*
641 			 * If bcache device is detaching via sysfs interface,
642 			 * writeback thread should stop after there is no dirty
643 			 * data on cache. BCACHE_DEV_DETACHING flag is set in
644 			 * bch_cached_dev_detach().
645 			 */
646 			if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
647 				break;
648 		}
649 
650 		up_write(&dc->writeback_lock);
651 
652 		read_dirty(dc);
653 
654 		if (searched_full_index) {
655 			unsigned delay = dc->writeback_delay * HZ;
656 
657 			while (delay &&
658 			       !kthread_should_stop() &&
659 			       !test_bit(CACHE_SET_IO_DISABLE, &c->flags) &&
660 			       !test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
661 				delay = schedule_timeout_interruptible(delay);
662 
663 			bch_ratelimit_reset(&dc->writeback_rate);
664 		}
665 	}
666 
667 	cached_dev_put(dc);
668 	wait_for_kthread_stop();
669 
670 	return 0;
671 }
672 
673 /* Init */
674 
675 struct sectors_dirty_init {
676 	struct btree_op	op;
677 	unsigned	inode;
678 };
679 
680 static int sectors_dirty_init_fn(struct btree_op *_op, struct btree *b,
681 				 struct bkey *k)
682 {
683 	struct sectors_dirty_init *op = container_of(_op,
684 						struct sectors_dirty_init, op);
685 	if (KEY_INODE(k) > op->inode)
686 		return MAP_DONE;
687 
688 	if (KEY_DIRTY(k))
689 		bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
690 					     KEY_START(k), KEY_SIZE(k));
691 
692 	return MAP_CONTINUE;
693 }
694 
695 void bch_sectors_dirty_init(struct bcache_device *d)
696 {
697 	struct sectors_dirty_init op;
698 
699 	bch_btree_op_init(&op.op, -1);
700 	op.inode = d->id;
701 
702 	bch_btree_map_keys(&op.op, d->c, &KEY(op.inode, 0, 0),
703 			   sectors_dirty_init_fn, 0);
704 }
705 
706 void bch_cached_dev_writeback_init(struct cached_dev *dc)
707 {
708 	sema_init(&dc->in_flight, 64);
709 	init_rwsem(&dc->writeback_lock);
710 	bch_keybuf_init(&dc->writeback_keys);
711 
712 	dc->writeback_metadata		= true;
713 	dc->writeback_running		= true;
714 	dc->writeback_percent		= 10;
715 	dc->writeback_delay		= 30;
716 	dc->writeback_rate.rate		= 1024;
717 	dc->writeback_rate_minimum	= 8;
718 
719 	dc->writeback_rate_update_seconds = WRITEBACK_RATE_UPDATE_SECS_DEFAULT;
720 	dc->writeback_rate_p_term_inverse = 40;
721 	dc->writeback_rate_i_term_inverse = 10000;
722 
723 	WARN_ON(test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
724 	INIT_DELAYED_WORK(&dc->writeback_rate_update, update_writeback_rate);
725 }
726 
727 int bch_cached_dev_writeback_start(struct cached_dev *dc)
728 {
729 	dc->writeback_write_wq = alloc_workqueue("bcache_writeback_wq",
730 						WQ_MEM_RECLAIM, 0);
731 	if (!dc->writeback_write_wq)
732 		return -ENOMEM;
733 
734 	cached_dev_get(dc);
735 	dc->writeback_thread = kthread_create(bch_writeback_thread, dc,
736 					      "bcache_writeback");
737 	if (IS_ERR(dc->writeback_thread)) {
738 		cached_dev_put(dc);
739 		return PTR_ERR(dc->writeback_thread);
740 	}
741 
742 	WARN_ON(test_and_set_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
743 	schedule_delayed_work(&dc->writeback_rate_update,
744 			      dc->writeback_rate_update_seconds * HZ);
745 
746 	bch_writeback_queue(dc);
747 
748 	return 0;
749 }
750