2 * buffered writeback throttling. loosely based on CoDel. We can't drop
3 * packets for IO scheduling, so the logic is something like this:
5 * - Monitor latencies in a defined window of time.
6 * - If the minimum latency in the above window exceeds some target, increment
7 * scaling step and scale down queue depth by a factor of 2x. The monitoring
8 * window is then shrunk to 100 / sqrt(scaling step + 1).
9 * - For any window where we don't have solid data on what the latencies
10 * look like, retain status quo.
11 * - If latencies look good, decrement scaling step.
12 * - If we're only doing writes, allow the scaling step to go negative. This
13 * will temporarily boost write performance, snapping back to a stable
14 * scaling step of 0 if reads show up or the heavy writers finish. Unlike
15 * positive scaling steps where we shrink the monitoring window, a negative
16 * scaling step retains the default step==0 window size.
18 * Copyright (C) 2016 Jens Axboe
21 #include <linux/kernel.h>
22 #include <linux/blk_types.h>
23 #include <linux/slab.h>
24 #include <linux/backing-dev.h>
25 #include <linux/swap.h>
29 #define CREATE_TRACE_POINTS
30 #include <trace/events/wbt.h>
32 static inline void wbt_clear_state(struct request
*rq
)
37 static inline enum wbt_flags
wbt_flags(struct request
*rq
)
42 static inline bool wbt_is_tracked(struct request
*rq
)
44 return rq
->wbt_flags
& WBT_TRACKED
;
47 static inline bool wbt_is_read(struct request
*rq
)
49 return rq
->wbt_flags
& WBT_READ
;
54 * Default setting, we'll scale up (to 75% of QD max) or down (min 1)
55 * from here depending on device stats
62 RWB_WINDOW_NSEC
= 100 * 1000 * 1000ULL,
65 * Disregard stats, if we don't meet this minimum
67 RWB_MIN_WRITE_SAMPLES
= 3,
70 * If we have this number of consecutive windows with not enough
71 * information to scale up or down, scale up.
76 static inline bool rwb_enabled(struct rq_wb
*rwb
)
78 return rwb
&& rwb
->wb_normal
!= 0;
82 * Increment 'v', if 'v' is below 'below'. Returns true if we succeeded,
83 * false if 'v' + 1 would be bigger than 'below'.
85 static bool atomic_inc_below(atomic_t
*v
, int below
)
87 int cur
= atomic_read(v
);
94 old
= atomic_cmpxchg(v
, cur
, cur
+ 1);
103 static void wb_timestamp(struct rq_wb
*rwb
, unsigned long *var
)
105 if (rwb_enabled(rwb
)) {
106 const unsigned long cur
= jiffies
;
114 * If a task was rate throttled in balance_dirty_pages() within the last
115 * second or so, use that to indicate a higher cleaning rate.
117 static bool wb_recent_wait(struct rq_wb
*rwb
)
119 struct bdi_writeback
*wb
= &rwb
->queue
->backing_dev_info
->wb
;
121 return time_before(jiffies
, wb
->dirty_sleep
+ HZ
);
124 static inline struct rq_wait
*get_rq_wait(struct rq_wb
*rwb
,
125 enum wbt_flags wb_acct
)
127 if (wb_acct
& WBT_KSWAPD
)
128 return &rwb
->rq_wait
[WBT_RWQ_KSWAPD
];
129 else if (wb_acct
& WBT_DISCARD
)
130 return &rwb
->rq_wait
[WBT_RWQ_DISCARD
];
132 return &rwb
->rq_wait
[WBT_RWQ_BG
];
135 static void rwb_wake_all(struct rq_wb
*rwb
)
139 for (i
= 0; i
< WBT_NUM_RWQ
; i
++) {
140 struct rq_wait
*rqw
= &rwb
->rq_wait
[i
];
142 if (waitqueue_active(&rqw
->wait
))
143 wake_up_all(&rqw
->wait
);
147 void __wbt_done(struct rq_wb
*rwb
, enum wbt_flags wb_acct
)
152 if (!(wb_acct
& WBT_TRACKED
))
155 rqw
= get_rq_wait(rwb
, wb_acct
);
156 inflight
= atomic_dec_return(&rqw
->inflight
);
159 * wbt got disabled with IO in flight. Wake up any potential
160 * waiters, we don't have to do more than that.
162 if (unlikely(!rwb_enabled(rwb
))) {
168 * For discards, our limit is always the background. For writes, if
169 * the device does write back caching, drop further down before we
172 if (wb_acct
& WBT_DISCARD
)
173 limit
= rwb
->wb_background
;
174 else if (rwb
->wc
&& !wb_recent_wait(rwb
))
177 limit
= rwb
->wb_normal
;
180 * Don't wake anyone up if we are above the normal limit.
182 if (inflight
&& inflight
>= limit
)
185 if (waitqueue_active(&rqw
->wait
)) {
186 int diff
= limit
- inflight
;
188 if (!inflight
|| diff
>= rwb
->wb_background
/ 2)
189 wake_up_all(&rqw
->wait
);
194 * Called on completion of a request. Note that it's also called when
195 * a request is merged, when the request gets freed.
197 void wbt_done(struct rq_wb
*rwb
, struct request
*rq
)
202 if (!wbt_is_tracked(rq
)) {
203 if (rwb
->sync_cookie
== rq
) {
205 rwb
->sync_cookie
= NULL
;
209 wb_timestamp(rwb
, &rwb
->last_comp
);
211 WARN_ON_ONCE(rq
== rwb
->sync_cookie
);
212 __wbt_done(rwb
, wbt_flags(rq
));
218 * Return true, if we can't increase the depth further by scaling
220 static bool calc_wb_limits(struct rq_wb
*rwb
)
225 if (!rwb
->min_lat_nsec
) {
226 rwb
->wb_max
= rwb
->wb_normal
= rwb
->wb_background
= 0;
231 * For QD=1 devices, this is a special case. It's important for those
232 * to have one request ready when one completes, so force a depth of
233 * 2 for those devices. On the backend, it'll be a depth of 1 anyway,
234 * since the device can't have more than that in flight. If we're
235 * scaling down, then keep a setting of 1/1/1.
237 if (rwb
->queue_depth
== 1) {
238 if (rwb
->scale_step
> 0)
239 rwb
->wb_max
= rwb
->wb_normal
= 1;
241 rwb
->wb_max
= rwb
->wb_normal
= 2;
244 rwb
->wb_background
= 1;
247 * scale_step == 0 is our default state. If we have suffered
248 * latency spikes, step will be > 0, and we shrink the
249 * allowed write depths. If step is < 0, we're only doing
250 * writes, and we allow a temporarily higher depth to
251 * increase performance.
253 depth
= min_t(unsigned int, RWB_DEF_DEPTH
, rwb
->queue_depth
);
254 if (rwb
->scale_step
> 0)
255 depth
= 1 + ((depth
- 1) >> min(31, rwb
->scale_step
));
256 else if (rwb
->scale_step
< 0) {
257 unsigned int maxd
= 3 * rwb
->queue_depth
/ 4;
259 depth
= 1 + ((depth
- 1) << -rwb
->scale_step
);
267 * Set our max/normal/bg queue depths based on how far
268 * we have scaled down (->scale_step).
271 rwb
->wb_normal
= (rwb
->wb_max
+ 1) / 2;
272 rwb
->wb_background
= (rwb
->wb_max
+ 3) / 4;
278 static inline bool stat_sample_valid(struct blk_rq_stat
*stat
)
281 * We need at least one read sample, and a minimum of
282 * RWB_MIN_WRITE_SAMPLES. We require some write samples to know
283 * that it's writes impacting us, and not just some sole read on
284 * a device that is in a lower power state.
286 return (stat
[READ
].nr_samples
>= 1 &&
287 stat
[WRITE
].nr_samples
>= RWB_MIN_WRITE_SAMPLES
);
290 static u64
rwb_sync_issue_lat(struct rq_wb
*rwb
)
292 u64 now
, issue
= READ_ONCE(rwb
->sync_issue
);
294 if (!issue
|| !rwb
->sync_cookie
)
297 now
= ktime_to_ns(ktime_get());
308 static int latency_exceeded(struct rq_wb
*rwb
, struct blk_rq_stat
*stat
)
310 struct backing_dev_info
*bdi
= rwb
->queue
->backing_dev_info
;
314 * If our stored sync issue exceeds the window size, or it
315 * exceeds our min target AND we haven't logged any entries,
316 * flag the latency as exceeded. wbt works off completion latencies,
317 * but for a flooded device, a single sync IO can take a long time
318 * to complete after being issued. If this time exceeds our
319 * monitoring window AND we didn't see any other completions in that
320 * window, then count that sync IO as a violation of the latency.
322 thislat
= rwb_sync_issue_lat(rwb
);
323 if (thislat
> rwb
->cur_win_nsec
||
324 (thislat
> rwb
->min_lat_nsec
&& !stat
[READ
].nr_samples
)) {
325 trace_wbt_lat(bdi
, thislat
);
330 * No read/write mix, if stat isn't valid
332 if (!stat_sample_valid(stat
)) {
334 * If we had writes in this stat window and the window is
335 * current, we're only doing writes. If a task recently
336 * waited or still has writes in flights, consider us doing
337 * just writes as well.
339 if (stat
[WRITE
].nr_samples
|| wb_recent_wait(rwb
) ||
341 return LAT_UNKNOWN_WRITES
;
346 * If the 'min' latency exceeds our target, step down.
348 if (stat
[READ
].min
> rwb
->min_lat_nsec
) {
349 trace_wbt_lat(bdi
, stat
[READ
].min
);
350 trace_wbt_stat(bdi
, stat
);
355 trace_wbt_stat(bdi
, stat
);
360 static void rwb_trace_step(struct rq_wb
*rwb
, const char *msg
)
362 struct backing_dev_info
*bdi
= rwb
->queue
->backing_dev_info
;
364 trace_wbt_step(bdi
, msg
, rwb
->scale_step
, rwb
->cur_win_nsec
,
365 rwb
->wb_background
, rwb
->wb_normal
, rwb
->wb_max
);
368 static void scale_up(struct rq_wb
*rwb
)
371 * Hit max in previous round, stop here
377 rwb
->unknown_cnt
= 0;
379 rwb
->scaled_max
= calc_wb_limits(rwb
);
383 rwb_trace_step(rwb
, "step up");
387 * Scale rwb down. If 'hard_throttle' is set, do it quicker, since we
388 * had a latency violation.
390 static void scale_down(struct rq_wb
*rwb
, bool hard_throttle
)
393 * Stop scaling down when we've hit the limit. This also prevents
394 * ->scale_step from going to crazy values, if the device can't
397 if (rwb
->wb_max
== 1)
400 if (rwb
->scale_step
< 0 && hard_throttle
)
405 rwb
->scaled_max
= false;
406 rwb
->unknown_cnt
= 0;
408 rwb_trace_step(rwb
, "step down");
411 static void rwb_arm_timer(struct rq_wb
*rwb
)
413 if (rwb
->scale_step
> 0) {
415 * We should speed this up, using some variant of a fast
416 * integer inverse square root calculation. Since we only do
417 * this for every window expiration, it's not a huge deal,
420 rwb
->cur_win_nsec
= div_u64(rwb
->win_nsec
<< 4,
421 int_sqrt((rwb
->scale_step
+ 1) << 8));
424 * For step < 0, we don't want to increase/decrease the
427 rwb
->cur_win_nsec
= rwb
->win_nsec
;
430 blk_stat_activate_nsecs(rwb
->cb
, rwb
->cur_win_nsec
);
433 static void wb_timer_fn(struct blk_stat_callback
*cb
)
435 struct rq_wb
*rwb
= cb
->data
;
436 unsigned int inflight
= wbt_inflight(rwb
);
439 status
= latency_exceeded(rwb
, cb
->stat
);
441 trace_wbt_timer(rwb
->queue
->backing_dev_info
, status
, rwb
->scale_step
,
445 * If we exceeded the latency target, step down. If we did not,
446 * step one level up. If we don't know enough to say either exceeded
447 * or ok, then don't do anything.
451 scale_down(rwb
, true);
456 case LAT_UNKNOWN_WRITES
:
458 * We started a the center step, but don't have a valid
459 * read/write sample, but we do have writes going on.
460 * Allow step to go negative, to increase write perf.
465 if (++rwb
->unknown_cnt
< RWB_UNKNOWN_BUMP
)
468 * We get here when previously scaled reduced depth, and we
469 * currently don't have a valid read/write sample. For that
470 * case, slowly return to center state (step == 0).
472 if (rwb
->scale_step
> 0)
474 else if (rwb
->scale_step
< 0)
475 scale_down(rwb
, false);
482 * Re-arm timer, if we have IO in flight
484 if (rwb
->scale_step
|| inflight
)
488 void wbt_update_limits(struct rq_wb
*rwb
)
491 rwb
->scaled_max
= false;
497 static bool close_io(struct rq_wb
*rwb
)
499 const unsigned long now
= jiffies
;
501 return time_before(now
, rwb
->last_issue
+ HZ
/ 10) ||
502 time_before(now
, rwb
->last_comp
+ HZ
/ 10);
505 #define REQ_HIPRIO (REQ_SYNC | REQ_META | REQ_PRIO)
507 static inline unsigned int get_limit(struct rq_wb
*rwb
, unsigned long rw
)
511 if ((rw
& REQ_OP_MASK
) == REQ_OP_DISCARD
)
512 return rwb
->wb_background
;
515 * At this point we know it's a buffered write. If this is
516 * kswapd trying to free memory, or REQ_SYNC is set, then
517 * it's WB_SYNC_ALL writeback, and we'll use the max limit for
518 * that. If the write is marked as a background write, then use
519 * the idle limit, or go to normal if we haven't had competing
522 if ((rw
& REQ_HIPRIO
) || wb_recent_wait(rwb
) || current_is_kswapd())
524 else if ((rw
& REQ_BACKGROUND
) || close_io(rwb
)) {
526 * If less than 100ms since we completed unrelated IO,
527 * limit us to half the depth for background writeback.
529 limit
= rwb
->wb_background
;
531 limit
= rwb
->wb_normal
;
536 static inline bool may_queue(struct rq_wb
*rwb
, struct rq_wait
*rqw
,
537 wait_queue_entry_t
*wait
, unsigned long rw
)
540 * inc it here even if disabled, since we'll dec it at completion.
541 * this only happens if the task was sleeping in __wbt_wait(),
542 * and someone turned it off at the same time.
544 if (!rwb_enabled(rwb
)) {
545 atomic_inc(&rqw
->inflight
);
550 * If the waitqueue is already active and we are not the next
551 * in line to be woken up, wait for our turn.
553 if (waitqueue_active(&rqw
->wait
) &&
554 rqw
->wait
.head
.next
!= &wait
->entry
)
557 return atomic_inc_below(&rqw
->inflight
, get_limit(rwb
, rw
));
561 * Block if we will exceed our limit, or if we are currently waiting for
562 * the timer to kick off queuing again.
564 static void __wbt_wait(struct rq_wb
*rwb
, enum wbt_flags wb_acct
,
565 unsigned long rw
, spinlock_t
*lock
)
569 struct rq_wait
*rqw
= get_rq_wait(rwb
, wb_acct
);
572 if (may_queue(rwb
, rqw
, &wait
, rw
))
576 prepare_to_wait_exclusive(&rqw
->wait
, &wait
,
577 TASK_UNINTERRUPTIBLE
);
579 if (may_queue(rwb
, rqw
, &wait
, rw
))
583 spin_unlock_irq(lock
);
590 finish_wait(&rqw
->wait
, &wait
);
593 static inline bool wbt_should_throttle(struct rq_wb
*rwb
, struct bio
*bio
)
595 switch (bio_op(bio
)) {
598 * Don't throttle WRITE_ODIRECT
600 if ((bio
->bi_opf
& (REQ_SYNC
| REQ_IDLE
)) ==
601 (REQ_SYNC
| REQ_IDLE
))
612 * Returns true if the IO request should be accounted, false if not.
613 * May sleep, if we have exceeded the writeback limits. Caller can pass
614 * in an irq held spinlock, if it holds one when calling this function.
615 * If we do sleep, we'll release and re-grab it.
617 enum wbt_flags
wbt_wait(struct rq_wb
*rwb
, struct bio
*bio
, spinlock_t
*lock
)
619 enum wbt_flags ret
= 0;
621 if (!rwb_enabled(rwb
))
624 if (bio_op(bio
) == REQ_OP_READ
)
627 if (!wbt_should_throttle(rwb
, bio
)) {
629 wb_timestamp(rwb
, &rwb
->last_issue
);
633 if (current_is_kswapd())
635 if (bio_op(bio
) == REQ_OP_DISCARD
)
638 __wbt_wait(rwb
, ret
, bio
->bi_opf
, lock
);
640 if (!blk_stat_is_active(rwb
->cb
))
643 return ret
| WBT_TRACKED
;
646 void wbt_issue(struct rq_wb
*rwb
, struct request
*rq
)
648 if (!rwb_enabled(rwb
))
652 * Track sync issue, in case it takes a long time to complete. Allows us
653 * to react quicker, if a sync IO takes a long time to complete. Note
654 * that this is just a hint. The request can go away when it completes,
655 * so it's important we never dereference it. We only use the address to
656 * compare with, which is why we store the sync_issue time locally.
658 if (wbt_is_read(rq
) && !rwb
->sync_issue
) {
659 rwb
->sync_cookie
= rq
;
660 rwb
->sync_issue
= rq
->io_start_time_ns
;
664 void wbt_requeue(struct rq_wb
*rwb
, struct request
*rq
)
666 if (!rwb_enabled(rwb
))
668 if (rq
== rwb
->sync_cookie
) {
670 rwb
->sync_cookie
= NULL
;
674 void wbt_set_queue_depth(struct rq_wb
*rwb
, unsigned int depth
)
677 rwb
->queue_depth
= depth
;
678 wbt_update_limits(rwb
);
682 void wbt_set_write_cache(struct rq_wb
*rwb
, bool write_cache_on
)
685 rwb
->wc
= write_cache_on
;
689 * Disable wbt, if enabled by default.
691 void wbt_disable_default(struct request_queue
*q
)
693 struct rq_wb
*rwb
= q
->rq_wb
;
695 if (rwb
&& rwb
->enable_state
== WBT_STATE_ON_DEFAULT
)
698 EXPORT_SYMBOL_GPL(wbt_disable_default
);
701 * Enable wbt if defaults are configured that way
703 void wbt_enable_default(struct request_queue
*q
)
705 /* Throttling already enabled? */
709 /* Queue not registered? Maybe shutting down... */
710 if (!test_bit(QUEUE_FLAG_REGISTERED
, &q
->queue_flags
))
713 if ((q
->mq_ops
&& IS_ENABLED(CONFIG_BLK_WBT_MQ
)) ||
714 (q
->request_fn
&& IS_ENABLED(CONFIG_BLK_WBT_SQ
)))
717 EXPORT_SYMBOL_GPL(wbt_enable_default
);
719 u64
wbt_default_latency_nsec(struct request_queue
*q
)
722 * We default to 2msec for non-rotational storage, and 75msec
723 * for rotational storage.
725 if (blk_queue_nonrot(q
))
731 static int wbt_data_dir(const struct request
*rq
)
733 const int op
= req_op(rq
);
735 if (op
== REQ_OP_READ
)
737 else if (op_is_write(op
))
744 int wbt_init(struct request_queue
*q
)
749 rwb
= kzalloc(sizeof(*rwb
), GFP_KERNEL
);
753 rwb
->cb
= blk_stat_alloc_callback(wb_timer_fn
, wbt_data_dir
, 2, rwb
);
759 for (i
= 0; i
< WBT_NUM_RWQ
; i
++) {
760 atomic_set(&rwb
->rq_wait
[i
].inflight
, 0);
761 init_waitqueue_head(&rwb
->rq_wait
[i
].wait
);
764 rwb
->last_comp
= rwb
->last_issue
= jiffies
;
766 rwb
->win_nsec
= RWB_WINDOW_NSEC
;
767 rwb
->enable_state
= WBT_STATE_ON_DEFAULT
;
768 wbt_update_limits(rwb
);
771 * Assign rwb and add the stats callback.
774 blk_stat_add_callback(q
, rwb
->cb
);
776 rwb
->min_lat_nsec
= wbt_default_latency_nsec(q
);
778 wbt_set_queue_depth(rwb
, blk_queue_depth(q
));
779 wbt_set_write_cache(rwb
, test_bit(QUEUE_FLAG_WC
, &q
->queue_flags
));
784 void wbt_exit(struct request_queue
*q
)
786 struct rq_wb
*rwb
= q
->rq_wb
;
789 blk_stat_remove_callback(q
, rwb
->cb
);
790 blk_stat_free_callback(rwb
->cb
);