1 // SPDX-License-Identifier: GPL-2.0
3 * Interface for controlling IO bandwidth on a request queue
5 * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
8 #include <linux/module.h>
9 #include <linux/slab.h>
10 #include <linux/blkdev.h>
11 #include <linux/bio.h>
12 #include <linux/blktrace_api.h>
14 #include "blk-cgroup-rwstat.h"
16 #include "blk-throttle.h"
18 /* Max dispatch from a group in 1 round */
19 #define THROTL_GRP_QUANTUM 8
21 /* Total max dispatch from all groups in one round */
22 #define THROTL_QUANTUM 32
24 /* Throttling is performed over a slice and after that slice is renewed */
25 #define DFL_THROTL_SLICE_HD (HZ / 10)
26 #define DFL_THROTL_SLICE_SSD (HZ / 50)
27 #define MAX_THROTL_SLICE (HZ)
28 #define MAX_IDLE_TIME (5L * 1000 * 1000) /* 5 s */
29 #define MIN_THROTL_BPS (320 * 1024)
30 #define MIN_THROTL_IOPS (10)
31 #define DFL_LATENCY_TARGET (-1L)
32 #define DFL_IDLE_THRESHOLD (0)
33 #define DFL_HD_BASELINE_LATENCY (4000L) /* 4ms */
34 #define LATENCY_FILTERED_SSD (0)
36 * For HD, very small latency comes from sequential IO. Such IO is helpless to
37 * help determine if its IO is impacted by others, hence we ignore the IO
39 #define LATENCY_FILTERED_HD (1000L) /* 1ms */
41 /* A workqueue to queue throttle related work */
42 static struct workqueue_struct *kthrotld_workqueue;
44 #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
46 /* We measure latency for request size from <= 4k to >= 1M */
47 #define LATENCY_BUCKET_SIZE 9
49 struct latency_bucket {
50 unsigned long total_latency; /* ns / 1024 */
54 struct avg_latency_bucket {
55 unsigned long latency; /* ns / 1024 */
61 /* service tree for active throtl groups */
62 struct throtl_service_queue service_queue;
64 struct request_queue *queue;
66 /* Total Number of queued bios on READ and WRITE lists */
67 unsigned int nr_queued[2];
69 unsigned int throtl_slice;
71 /* Work for dispatching throttled bios */
72 struct work_struct dispatch_work;
73 unsigned int limit_index;
74 bool limit_valid[LIMIT_CNT];
76 unsigned long low_upgrade_time;
77 unsigned long low_downgrade_time;
81 struct latency_bucket tmp_buckets[2][LATENCY_BUCKET_SIZE];
82 struct avg_latency_bucket avg_buckets[2][LATENCY_BUCKET_SIZE];
83 struct latency_bucket __percpu *latency_buckets[2];
84 unsigned long last_calculate_time;
85 unsigned long filtered_latency;
87 bool track_bio_latency;
90 static void throtl_pending_timer_fn(struct timer_list *t);
92 static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
94 return pd_to_blkg(&tg->pd);
98 * sq_to_tg - return the throl_grp the specified service queue belongs to
99 * @sq: the throtl_service_queue of interest
101 * Return the throtl_grp @sq belongs to. If @sq is the top-level one
102 * embedded in throtl_data, %NULL is returned.
104 static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
106 if (sq && sq->parent_sq)
107 return container_of(sq, struct throtl_grp, service_queue);
113 * sq_to_td - return throtl_data the specified service queue belongs to
114 * @sq: the throtl_service_queue of interest
116 * A service_queue can be embedded in either a throtl_grp or throtl_data.
117 * Determine the associated throtl_data accordingly and return it.
119 static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
121 struct throtl_grp *tg = sq_to_tg(sq);
126 return container_of(sq, struct throtl_data, service_queue);
130 * cgroup's limit in LIMIT_MAX is scaled if low limit is set. This scale is to
131 * make the IO dispatch more smooth.
132 * Scale up: linearly scale up according to lapsed time since upgrade. For
133 * every throtl_slice, the limit scales up 1/2 .low limit till the
134 * limit hits .max limit
135 * Scale down: exponentially scale down if a cgroup doesn't hit its .low limit
137 static uint64_t throtl_adjusted_limit(uint64_t low, struct throtl_data *td)
139 /* arbitrary value to avoid too big scale */
140 if (td->scale < 4096 && time_after_eq(jiffies,
141 td->low_upgrade_time + td->scale * td->throtl_slice))
142 td->scale = (jiffies - td->low_upgrade_time) / td->throtl_slice;
144 return low + (low >> 1) * td->scale;
147 static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
149 struct blkcg_gq *blkg = tg_to_blkg(tg);
150 struct throtl_data *td;
153 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
157 ret = tg->bps[rw][td->limit_index];
158 if (ret == 0 && td->limit_index == LIMIT_LOW) {
159 /* intermediate node or iops isn't 0 */
160 if (!list_empty(&blkg->blkcg->css.children) ||
161 tg->iops[rw][td->limit_index])
164 return MIN_THROTL_BPS;
167 if (td->limit_index == LIMIT_MAX && tg->bps[rw][LIMIT_LOW] &&
168 tg->bps[rw][LIMIT_LOW] != tg->bps[rw][LIMIT_MAX]) {
171 adjusted = throtl_adjusted_limit(tg->bps[rw][LIMIT_LOW], td);
172 ret = min(tg->bps[rw][LIMIT_MAX], adjusted);
177 static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
179 struct blkcg_gq *blkg = tg_to_blkg(tg);
180 struct throtl_data *td;
183 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
187 ret = tg->iops[rw][td->limit_index];
188 if (ret == 0 && tg->td->limit_index == LIMIT_LOW) {
189 /* intermediate node or bps isn't 0 */
190 if (!list_empty(&blkg->blkcg->css.children) ||
191 tg->bps[rw][td->limit_index])
194 return MIN_THROTL_IOPS;
197 if (td->limit_index == LIMIT_MAX && tg->iops[rw][LIMIT_LOW] &&
198 tg->iops[rw][LIMIT_LOW] != tg->iops[rw][LIMIT_MAX]) {
201 adjusted = throtl_adjusted_limit(tg->iops[rw][LIMIT_LOW], td);
202 if (adjusted > UINT_MAX)
204 ret = min_t(unsigned int, tg->iops[rw][LIMIT_MAX], adjusted);
209 #define request_bucket_index(sectors) \
210 clamp_t(int, order_base_2(sectors) - 3, 0, LATENCY_BUCKET_SIZE - 1)
213 * throtl_log - log debug message via blktrace
214 * @sq: the service_queue being reported
215 * @fmt: printf format string
218 * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
219 * throtl_grp; otherwise, just "throtl".
221 #define throtl_log(sq, fmt, args...) do { \
222 struct throtl_grp *__tg = sq_to_tg((sq)); \
223 struct throtl_data *__td = sq_to_td((sq)); \
226 if (likely(!blk_trace_note_message_enabled(__td->queue))) \
229 blk_add_cgroup_trace_msg(__td->queue, \
230 &tg_to_blkg(__tg)->blkcg->css, "throtl " fmt, ##args);\
232 blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
236 static inline unsigned int throtl_bio_data_size(struct bio *bio)
238 /* assume it's one sector */
239 if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
241 return bio->bi_iter.bi_size;
244 static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
246 INIT_LIST_HEAD(&qn->node);
247 bio_list_init(&qn->bios);
252 * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
253 * @bio: bio being added
254 * @qn: qnode to add bio to
255 * @queued: the service_queue->queued[] list @qn belongs to
257 * Add @bio to @qn and put @qn on @queued if it's not already on.
258 * @qn->tg's reference count is bumped when @qn is activated. See the
259 * comment on top of throtl_qnode definition for details.
261 static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
262 struct list_head *queued)
264 bio_list_add(&qn->bios, bio);
265 if (list_empty(&qn->node)) {
266 list_add_tail(&qn->node, queued);
267 blkg_get(tg_to_blkg(qn->tg));
272 * throtl_peek_queued - peek the first bio on a qnode list
273 * @queued: the qnode list to peek
275 static struct bio *throtl_peek_queued(struct list_head *queued)
277 struct throtl_qnode *qn;
280 if (list_empty(queued))
283 qn = list_first_entry(queued, struct throtl_qnode, node);
284 bio = bio_list_peek(&qn->bios);
290 * throtl_pop_queued - pop the first bio form a qnode list
291 * @queued: the qnode list to pop a bio from
292 * @tg_to_put: optional out argument for throtl_grp to put
294 * Pop the first bio from the qnode list @queued. After popping, the first
295 * qnode is removed from @queued if empty or moved to the end of @queued so
296 * that the popping order is round-robin.
298 * When the first qnode is removed, its associated throtl_grp should be put
299 * too. If @tg_to_put is NULL, this function automatically puts it;
300 * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
301 * responsible for putting it.
303 static struct bio *throtl_pop_queued(struct list_head *queued,
304 struct throtl_grp **tg_to_put)
306 struct throtl_qnode *qn;
309 if (list_empty(queued))
312 qn = list_first_entry(queued, struct throtl_qnode, node);
313 bio = bio_list_pop(&qn->bios);
316 if (bio_list_empty(&qn->bios)) {
317 list_del_init(&qn->node);
321 blkg_put(tg_to_blkg(qn->tg));
323 list_move_tail(&qn->node, queued);
329 /* init a service_queue, assumes the caller zeroed it */
330 static void throtl_service_queue_init(struct throtl_service_queue *sq)
332 INIT_LIST_HEAD(&sq->queued[READ]);
333 INIT_LIST_HEAD(&sq->queued[WRITE]);
334 sq->pending_tree = RB_ROOT_CACHED;
335 timer_setup(&sq->pending_timer, throtl_pending_timer_fn, 0);
338 static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp,
339 struct request_queue *q,
342 struct throtl_grp *tg;
345 tg = kzalloc_node(sizeof(*tg), gfp, q->node);
349 if (blkg_rwstat_init(&tg->stat_bytes, gfp))
352 if (blkg_rwstat_init(&tg->stat_ios, gfp))
353 goto err_exit_stat_bytes;
355 throtl_service_queue_init(&tg->service_queue);
357 for (rw = READ; rw <= WRITE; rw++) {
358 throtl_qnode_init(&tg->qnode_on_self[rw], tg);
359 throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
362 RB_CLEAR_NODE(&tg->rb_node);
363 tg->bps[READ][LIMIT_MAX] = U64_MAX;
364 tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
365 tg->iops[READ][LIMIT_MAX] = UINT_MAX;
366 tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
367 tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
368 tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
369 tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
370 tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
371 /* LIMIT_LOW will have default value 0 */
373 tg->latency_target = DFL_LATENCY_TARGET;
374 tg->latency_target_conf = DFL_LATENCY_TARGET;
375 tg->idletime_threshold = DFL_IDLE_THRESHOLD;
376 tg->idletime_threshold_conf = DFL_IDLE_THRESHOLD;
381 blkg_rwstat_exit(&tg->stat_bytes);
387 static void throtl_pd_init(struct blkg_policy_data *pd)
389 struct throtl_grp *tg = pd_to_tg(pd);
390 struct blkcg_gq *blkg = tg_to_blkg(tg);
391 struct throtl_data *td = blkg->q->td;
392 struct throtl_service_queue *sq = &tg->service_queue;
395 * If on the default hierarchy, we switch to properly hierarchical
396 * behavior where limits on a given throtl_grp are applied to the
397 * whole subtree rather than just the group itself. e.g. If 16M
398 * read_bps limit is set on the root group, the whole system can't
399 * exceed 16M for the device.
401 * If not on the default hierarchy, the broken flat hierarchy
402 * behavior is retained where all throtl_grps are treated as if
403 * they're all separate root groups right below throtl_data.
404 * Limits of a group don't interact with limits of other groups
405 * regardless of the position of the group in the hierarchy.
407 sq->parent_sq = &td->service_queue;
408 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
409 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
414 * Set has_rules[] if @tg or any of its parents have limits configured.
415 * This doesn't require walking up to the top of the hierarchy as the
416 * parent's has_rules[] is guaranteed to be correct.
418 static void tg_update_has_rules(struct throtl_grp *tg)
420 struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
421 struct throtl_data *td = tg->td;
424 for (rw = READ; rw <= WRITE; rw++)
425 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
426 (td->limit_valid[td->limit_index] &&
427 (tg_bps_limit(tg, rw) != U64_MAX ||
428 tg_iops_limit(tg, rw) != UINT_MAX));
431 static void throtl_pd_online(struct blkg_policy_data *pd)
433 struct throtl_grp *tg = pd_to_tg(pd);
435 * We don't want new groups to escape the limits of its ancestors.
436 * Update has_rules[] after a new group is brought online.
438 tg_update_has_rules(tg);
441 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
442 static void blk_throtl_update_limit_valid(struct throtl_data *td)
444 struct cgroup_subsys_state *pos_css;
445 struct blkcg_gq *blkg;
446 bool low_valid = false;
449 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
450 struct throtl_grp *tg = blkg_to_tg(blkg);
452 if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
453 tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) {
460 td->limit_valid[LIMIT_LOW] = low_valid;
463 static inline void blk_throtl_update_limit_valid(struct throtl_data *td)
468 static void throtl_upgrade_state(struct throtl_data *td);
469 static void throtl_pd_offline(struct blkg_policy_data *pd)
471 struct throtl_grp *tg = pd_to_tg(pd);
473 tg->bps[READ][LIMIT_LOW] = 0;
474 tg->bps[WRITE][LIMIT_LOW] = 0;
475 tg->iops[READ][LIMIT_LOW] = 0;
476 tg->iops[WRITE][LIMIT_LOW] = 0;
478 blk_throtl_update_limit_valid(tg->td);
480 if (!tg->td->limit_valid[tg->td->limit_index])
481 throtl_upgrade_state(tg->td);
484 static void throtl_pd_free(struct blkg_policy_data *pd)
486 struct throtl_grp *tg = pd_to_tg(pd);
488 del_timer_sync(&tg->service_queue.pending_timer);
489 blkg_rwstat_exit(&tg->stat_bytes);
490 blkg_rwstat_exit(&tg->stat_ios);
494 static struct throtl_grp *
495 throtl_rb_first(struct throtl_service_queue *parent_sq)
499 n = rb_first_cached(&parent_sq->pending_tree);
503 return rb_entry_tg(n);
506 static void throtl_rb_erase(struct rb_node *n,
507 struct throtl_service_queue *parent_sq)
509 rb_erase_cached(n, &parent_sq->pending_tree);
513 static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
515 struct throtl_grp *tg;
517 tg = throtl_rb_first(parent_sq);
521 parent_sq->first_pending_disptime = tg->disptime;
524 static void tg_service_queue_add(struct throtl_grp *tg)
526 struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
527 struct rb_node **node = &parent_sq->pending_tree.rb_root.rb_node;
528 struct rb_node *parent = NULL;
529 struct throtl_grp *__tg;
530 unsigned long key = tg->disptime;
531 bool leftmost = true;
533 while (*node != NULL) {
535 __tg = rb_entry_tg(parent);
537 if (time_before(key, __tg->disptime))
538 node = &parent->rb_left;
540 node = &parent->rb_right;
545 rb_link_node(&tg->rb_node, parent, node);
546 rb_insert_color_cached(&tg->rb_node, &parent_sq->pending_tree,
550 static void throtl_enqueue_tg(struct throtl_grp *tg)
552 if (!(tg->flags & THROTL_TG_PENDING)) {
553 tg_service_queue_add(tg);
554 tg->flags |= THROTL_TG_PENDING;
555 tg->service_queue.parent_sq->nr_pending++;
559 static void throtl_dequeue_tg(struct throtl_grp *tg)
561 if (tg->flags & THROTL_TG_PENDING) {
562 struct throtl_service_queue *parent_sq =
563 tg->service_queue.parent_sq;
565 throtl_rb_erase(&tg->rb_node, parent_sq);
566 --parent_sq->nr_pending;
567 tg->flags &= ~THROTL_TG_PENDING;
571 /* Call with queue lock held */
572 static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
573 unsigned long expires)
575 unsigned long max_expire = jiffies + 8 * sq_to_td(sq)->throtl_slice;
578 * Since we are adjusting the throttle limit dynamically, the sleep
579 * time calculated according to previous limit might be invalid. It's
580 * possible the cgroup sleep time is very long and no other cgroups
581 * have IO running so notify the limit changes. Make sure the cgroup
582 * doesn't sleep too long to avoid the missed notification.
584 if (time_after(expires, max_expire))
585 expires = max_expire;
586 mod_timer(&sq->pending_timer, expires);
587 throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
588 expires - jiffies, jiffies);
592 * throtl_schedule_next_dispatch - schedule the next dispatch cycle
593 * @sq: the service_queue to schedule dispatch for
594 * @force: force scheduling
596 * Arm @sq->pending_timer so that the next dispatch cycle starts on the
597 * dispatch time of the first pending child. Returns %true if either timer
598 * is armed or there's no pending child left. %false if the current
599 * dispatch window is still open and the caller should continue
602 * If @force is %true, the dispatch timer is always scheduled and this
603 * function is guaranteed to return %true. This is to be used when the
604 * caller can't dispatch itself and needs to invoke pending_timer
605 * unconditionally. Note that forced scheduling is likely to induce short
606 * delay before dispatch starts even if @sq->first_pending_disptime is not
607 * in the future and thus shouldn't be used in hot paths.
609 static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
612 /* any pending children left? */
616 update_min_dispatch_time(sq);
618 /* is the next dispatch time in the future? */
619 if (force || time_after(sq->first_pending_disptime, jiffies)) {
620 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
624 /* tell the caller to continue dispatching */
628 static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
629 bool rw, unsigned long start)
631 tg->bytes_disp[rw] = 0;
633 tg->carryover_bytes[rw] = 0;
634 tg->carryover_ios[rw] = 0;
637 * Previous slice has expired. We must have trimmed it after last
638 * bio dispatch. That means since start of last slice, we never used
639 * that bandwidth. Do try to make use of that bandwidth while giving
642 if (time_after_eq(start, tg->slice_start[rw]))
643 tg->slice_start[rw] = start;
645 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
646 throtl_log(&tg->service_queue,
647 "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
648 rw == READ ? 'R' : 'W', tg->slice_start[rw],
649 tg->slice_end[rw], jiffies);
652 static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw,
653 bool clear_carryover)
655 tg->bytes_disp[rw] = 0;
657 tg->slice_start[rw] = jiffies;
658 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
659 if (clear_carryover) {
660 tg->carryover_bytes[rw] = 0;
661 tg->carryover_ios[rw] = 0;
664 throtl_log(&tg->service_queue,
665 "[%c] new slice start=%lu end=%lu jiffies=%lu",
666 rw == READ ? 'R' : 'W', tg->slice_start[rw],
667 tg->slice_end[rw], jiffies);
670 static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
671 unsigned long jiffy_end)
673 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
676 static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
677 unsigned long jiffy_end)
679 throtl_set_slice_end(tg, rw, jiffy_end);
680 throtl_log(&tg->service_queue,
681 "[%c] extend slice start=%lu end=%lu jiffies=%lu",
682 rw == READ ? 'R' : 'W', tg->slice_start[rw],
683 tg->slice_end[rw], jiffies);
686 /* Determine if previously allocated or extended slice is complete or not */
687 static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
689 if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
695 /* Trim the used slices and adjust slice start accordingly */
696 static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
698 unsigned long nr_slices, time_elapsed, io_trim;
701 BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
704 * If bps are unlimited (-1), then time slice don't get
705 * renewed. Don't try to trim the slice if slice is used. A new
706 * slice will start when appropriate.
708 if (throtl_slice_used(tg, rw))
712 * A bio has been dispatched. Also adjust slice_end. It might happen
713 * that initially cgroup limit was very low resulting in high
714 * slice_end, but later limit was bumped up and bio was dispatched
715 * sooner, then we need to reduce slice_end. A high bogus slice_end
716 * is bad because it does not allow new slice to start.
719 throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
721 time_elapsed = jiffies - tg->slice_start[rw];
723 nr_slices = time_elapsed / tg->td->throtl_slice;
727 tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
731 io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
734 if (!bytes_trim && !io_trim)
737 if (tg->bytes_disp[rw] >= bytes_trim)
738 tg->bytes_disp[rw] -= bytes_trim;
740 tg->bytes_disp[rw] = 0;
742 if (tg->io_disp[rw] >= io_trim)
743 tg->io_disp[rw] -= io_trim;
747 tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
749 throtl_log(&tg->service_queue,
750 "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
751 rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
752 tg->slice_start[rw], tg->slice_end[rw], jiffies);
755 static unsigned int calculate_io_allowed(u32 iops_limit,
756 unsigned long jiffy_elapsed)
758 unsigned int io_allowed;
762 * jiffy_elapsed should not be a big value as minimum iops can be
763 * 1 then at max jiffy elapsed should be equivalent of 1 second as we
764 * will allow dispatch after 1 second and after that slice should
768 tmp = (u64)iops_limit * jiffy_elapsed;
772 io_allowed = UINT_MAX;
779 static u64 calculate_bytes_allowed(u64 bps_limit, unsigned long jiffy_elapsed)
781 return mul_u64_u64_div_u64(bps_limit, (u64)jiffy_elapsed, (u64)HZ);
784 static void __tg_update_carryover(struct throtl_grp *tg, bool rw)
786 unsigned long jiffy_elapsed = jiffies - tg->slice_start[rw];
787 u64 bps_limit = tg_bps_limit(tg, rw);
788 u32 iops_limit = tg_iops_limit(tg, rw);
791 * If config is updated while bios are still throttled, calculate and
792 * accumulate how many bytes/ios are waited across changes. And
793 * carryover_bytes/ios will be used to calculate new wait time under new
796 if (bps_limit != U64_MAX)
797 tg->carryover_bytes[rw] +=
798 calculate_bytes_allowed(bps_limit, jiffy_elapsed) -
800 if (iops_limit != UINT_MAX)
801 tg->carryover_ios[rw] +=
802 calculate_io_allowed(iops_limit, jiffy_elapsed) -
806 static void tg_update_carryover(struct throtl_grp *tg)
808 if (tg->service_queue.nr_queued[READ])
809 __tg_update_carryover(tg, READ);
810 if (tg->service_queue.nr_queued[WRITE])
811 __tg_update_carryover(tg, WRITE);
813 /* see comments in struct throtl_grp for meaning of these fields. */
814 throtl_log(&tg->service_queue, "%s: %llu %llu %u %u\n", __func__,
815 tg->carryover_bytes[READ], tg->carryover_bytes[WRITE],
816 tg->carryover_ios[READ], tg->carryover_ios[WRITE]);
819 static bool tg_within_iops_limit(struct throtl_grp *tg, struct bio *bio,
820 u32 iops_limit, unsigned long *wait)
822 bool rw = bio_data_dir(bio);
823 unsigned int io_allowed;
824 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
826 if (iops_limit == UINT_MAX) {
832 jiffy_elapsed = jiffies - tg->slice_start[rw];
834 /* Round up to the next throttle slice, wait time must be nonzero */
835 jiffy_elapsed_rnd = roundup(jiffy_elapsed + 1, tg->td->throtl_slice);
836 io_allowed = calculate_io_allowed(iops_limit, jiffy_elapsed_rnd) +
837 tg->carryover_ios[rw];
838 if (tg->io_disp[rw] + 1 <= io_allowed) {
844 /* Calc approx time to dispatch */
845 jiffy_wait = jiffy_elapsed_rnd - jiffy_elapsed;
852 static bool tg_within_bps_limit(struct throtl_grp *tg, struct bio *bio,
853 u64 bps_limit, unsigned long *wait)
855 bool rw = bio_data_dir(bio);
856 u64 bytes_allowed, extra_bytes;
857 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
858 unsigned int bio_size = throtl_bio_data_size(bio);
860 /* no need to throttle if this bio's bytes have been accounted */
861 if (bps_limit == U64_MAX || bio_flagged(bio, BIO_BPS_THROTTLED)) {
867 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
869 /* Slice has just started. Consider one slice interval */
871 jiffy_elapsed_rnd = tg->td->throtl_slice;
873 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
874 bytes_allowed = calculate_bytes_allowed(bps_limit, jiffy_elapsed_rnd) +
875 tg->carryover_bytes[rw];
876 if (tg->bytes_disp[rw] + bio_size <= bytes_allowed) {
882 /* Calc approx time to dispatch */
883 extra_bytes = tg->bytes_disp[rw] + bio_size - bytes_allowed;
884 jiffy_wait = div64_u64(extra_bytes * HZ, bps_limit);
890 * This wait time is without taking into consideration the rounding
891 * up we did. Add that time also.
893 jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
900 * Returns whether one can dispatch a bio or not. Also returns approx number
901 * of jiffies to wait before this bio is with-in IO rate and can be dispatched
903 static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
906 bool rw = bio_data_dir(bio);
907 unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
908 u64 bps_limit = tg_bps_limit(tg, rw);
909 u32 iops_limit = tg_iops_limit(tg, rw);
912 * Currently whole state machine of group depends on first bio
913 * queued in the group bio list. So one should not be calling
914 * this function with a different bio if there are other bios
917 BUG_ON(tg->service_queue.nr_queued[rw] &&
918 bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
920 /* If tg->bps = -1, then BW is unlimited */
921 if ((bps_limit == U64_MAX && iops_limit == UINT_MAX) ||
922 tg->flags & THROTL_TG_CANCELING) {
929 * If previous slice expired, start a new one otherwise renew/extend
930 * existing slice to make sure it is at least throtl_slice interval
931 * long since now. New slice is started only for empty throttle group.
932 * If there is queued bio, that means there should be an active
933 * slice and it should be extended instead.
935 if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
936 throtl_start_new_slice(tg, rw, true);
938 if (time_before(tg->slice_end[rw],
939 jiffies + tg->td->throtl_slice))
940 throtl_extend_slice(tg, rw,
941 jiffies + tg->td->throtl_slice);
944 if (tg_within_bps_limit(tg, bio, bps_limit, &bps_wait) &&
945 tg_within_iops_limit(tg, bio, iops_limit, &iops_wait)) {
951 max_wait = max(bps_wait, iops_wait);
956 if (time_before(tg->slice_end[rw], jiffies + max_wait))
957 throtl_extend_slice(tg, rw, jiffies + max_wait);
962 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
964 bool rw = bio_data_dir(bio);
965 unsigned int bio_size = throtl_bio_data_size(bio);
967 /* Charge the bio to the group */
968 if (!bio_flagged(bio, BIO_BPS_THROTTLED)) {
969 tg->bytes_disp[rw] += bio_size;
970 tg->last_bytes_disp[rw] += bio_size;
974 tg->last_io_disp[rw]++;
978 * throtl_add_bio_tg - add a bio to the specified throtl_grp
981 * @tg: the target throtl_grp
983 * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
984 * tg->qnode_on_self[] is used.
986 static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
987 struct throtl_grp *tg)
989 struct throtl_service_queue *sq = &tg->service_queue;
990 bool rw = bio_data_dir(bio);
993 qn = &tg->qnode_on_self[rw];
996 * If @tg doesn't currently have any bios queued in the same
997 * direction, queueing @bio can change when @tg should be
998 * dispatched. Mark that @tg was empty. This is automatically
999 * cleared on the next tg_update_disptime().
1001 if (!sq->nr_queued[rw])
1002 tg->flags |= THROTL_TG_WAS_EMPTY;
1004 throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
1006 sq->nr_queued[rw]++;
1007 throtl_enqueue_tg(tg);
1010 static void tg_update_disptime(struct throtl_grp *tg)
1012 struct throtl_service_queue *sq = &tg->service_queue;
1013 unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
1016 bio = throtl_peek_queued(&sq->queued[READ]);
1018 tg_may_dispatch(tg, bio, &read_wait);
1020 bio = throtl_peek_queued(&sq->queued[WRITE]);
1022 tg_may_dispatch(tg, bio, &write_wait);
1024 min_wait = min(read_wait, write_wait);
1025 disptime = jiffies + min_wait;
1027 /* Update dispatch time */
1028 throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
1029 tg->disptime = disptime;
1030 tg_service_queue_add(tg);
1032 /* see throtl_add_bio_tg() */
1033 tg->flags &= ~THROTL_TG_WAS_EMPTY;
1036 static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
1037 struct throtl_grp *parent_tg, bool rw)
1039 if (throtl_slice_used(parent_tg, rw)) {
1040 throtl_start_new_slice_with_credit(parent_tg, rw,
1041 child_tg->slice_start[rw]);
1046 static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
1048 struct throtl_service_queue *sq = &tg->service_queue;
1049 struct throtl_service_queue *parent_sq = sq->parent_sq;
1050 struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
1051 struct throtl_grp *tg_to_put = NULL;
1055 * @bio is being transferred from @tg to @parent_sq. Popping a bio
1056 * from @tg may put its reference and @parent_sq might end up
1057 * getting released prematurely. Remember the tg to put and put it
1058 * after @bio is transferred to @parent_sq.
1060 bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
1061 sq->nr_queued[rw]--;
1063 throtl_charge_bio(tg, bio);
1064 bio_set_flag(bio, BIO_BPS_THROTTLED);
1067 * If our parent is another tg, we just need to transfer @bio to
1068 * the parent using throtl_add_bio_tg(). If our parent is
1069 * @td->service_queue, @bio is ready to be issued. Put it on its
1070 * bio_lists[] and decrease total number queued. The caller is
1071 * responsible for issuing these bios.
1074 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
1075 start_parent_slice_with_credit(tg, parent_tg, rw);
1077 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1078 &parent_sq->queued[rw]);
1079 BUG_ON(tg->td->nr_queued[rw] <= 0);
1080 tg->td->nr_queued[rw]--;
1083 throtl_trim_slice(tg, rw);
1086 blkg_put(tg_to_blkg(tg_to_put));
1089 static int throtl_dispatch_tg(struct throtl_grp *tg)
1091 struct throtl_service_queue *sq = &tg->service_queue;
1092 unsigned int nr_reads = 0, nr_writes = 0;
1093 unsigned int max_nr_reads = THROTL_GRP_QUANTUM * 3 / 4;
1094 unsigned int max_nr_writes = THROTL_GRP_QUANTUM - max_nr_reads;
1097 /* Try to dispatch 75% READS and 25% WRITES */
1099 while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
1100 tg_may_dispatch(tg, bio, NULL)) {
1102 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1105 if (nr_reads >= max_nr_reads)
1109 while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
1110 tg_may_dispatch(tg, bio, NULL)) {
1112 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1115 if (nr_writes >= max_nr_writes)
1119 return nr_reads + nr_writes;
1122 static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
1124 unsigned int nr_disp = 0;
1127 struct throtl_grp *tg;
1128 struct throtl_service_queue *sq;
1130 if (!parent_sq->nr_pending)
1133 tg = throtl_rb_first(parent_sq);
1137 if (time_before(jiffies, tg->disptime))
1140 nr_disp += throtl_dispatch_tg(tg);
1142 sq = &tg->service_queue;
1143 if (sq->nr_queued[READ] || sq->nr_queued[WRITE])
1144 tg_update_disptime(tg);
1146 throtl_dequeue_tg(tg);
1148 if (nr_disp >= THROTL_QUANTUM)
1155 static bool throtl_can_upgrade(struct throtl_data *td,
1156 struct throtl_grp *this_tg);
1158 * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1159 * @t: the pending_timer member of the throtl_service_queue being serviced
1161 * This timer is armed when a child throtl_grp with active bio's become
1162 * pending and queued on the service_queue's pending_tree and expires when
1163 * the first child throtl_grp should be dispatched. This function
1164 * dispatches bio's from the children throtl_grps to the parent
1167 * If the parent's parent is another throtl_grp, dispatching is propagated
1168 * by either arming its pending_timer or repeating dispatch directly. If
1169 * the top-level service_tree is reached, throtl_data->dispatch_work is
1170 * kicked so that the ready bio's are issued.
1172 static void throtl_pending_timer_fn(struct timer_list *t)
1174 struct throtl_service_queue *sq = from_timer(sq, t, pending_timer);
1175 struct throtl_grp *tg = sq_to_tg(sq);
1176 struct throtl_data *td = sq_to_td(sq);
1177 struct throtl_service_queue *parent_sq;
1178 struct request_queue *q;
1182 /* throtl_data may be gone, so figure out request queue by blkg */
1188 spin_lock_irq(&q->queue_lock);
1193 if (throtl_can_upgrade(td, NULL))
1194 throtl_upgrade_state(td);
1197 parent_sq = sq->parent_sq;
1201 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
1202 sq->nr_queued[READ] + sq->nr_queued[WRITE],
1203 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1205 ret = throtl_select_dispatch(sq);
1207 throtl_log(sq, "bios disp=%u", ret);
1211 if (throtl_schedule_next_dispatch(sq, false))
1214 /* this dispatch windows is still open, relax and repeat */
1215 spin_unlock_irq(&q->queue_lock);
1217 spin_lock_irq(&q->queue_lock);
1224 /* @parent_sq is another throl_grp, propagate dispatch */
1225 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1226 tg_update_disptime(tg);
1227 if (!throtl_schedule_next_dispatch(parent_sq, false)) {
1228 /* window is already open, repeat dispatching */
1235 /* reached the top-level, queue issuing */
1236 queue_work(kthrotld_workqueue, &td->dispatch_work);
1239 spin_unlock_irq(&q->queue_lock);
1243 * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1244 * @work: work item being executed
1246 * This function is queued for execution when bios reach the bio_lists[]
1247 * of throtl_data->service_queue. Those bios are ready and issued by this
1250 static void blk_throtl_dispatch_work_fn(struct work_struct *work)
1252 struct throtl_data *td = container_of(work, struct throtl_data,
1254 struct throtl_service_queue *td_sq = &td->service_queue;
1255 struct request_queue *q = td->queue;
1256 struct bio_list bio_list_on_stack;
1258 struct blk_plug plug;
1261 bio_list_init(&bio_list_on_stack);
1263 spin_lock_irq(&q->queue_lock);
1264 for (rw = READ; rw <= WRITE; rw++)
1265 while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
1266 bio_list_add(&bio_list_on_stack, bio);
1267 spin_unlock_irq(&q->queue_lock);
1269 if (!bio_list_empty(&bio_list_on_stack)) {
1270 blk_start_plug(&plug);
1271 while ((bio = bio_list_pop(&bio_list_on_stack)))
1272 submit_bio_noacct_nocheck(bio);
1273 blk_finish_plug(&plug);
1277 static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1280 struct throtl_grp *tg = pd_to_tg(pd);
1281 u64 v = *(u64 *)((void *)tg + off);
1285 return __blkg_prfill_u64(sf, pd, v);
1288 static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1291 struct throtl_grp *tg = pd_to_tg(pd);
1292 unsigned int v = *(unsigned int *)((void *)tg + off);
1296 return __blkg_prfill_u64(sf, pd, v);
1299 static int tg_print_conf_u64(struct seq_file *sf, void *v)
1301 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1302 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1306 static int tg_print_conf_uint(struct seq_file *sf, void *v)
1308 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1309 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1313 static void tg_conf_updated(struct throtl_grp *tg, bool global)
1315 struct throtl_service_queue *sq = &tg->service_queue;
1316 struct cgroup_subsys_state *pos_css;
1317 struct blkcg_gq *blkg;
1319 throtl_log(&tg->service_queue,
1320 "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
1321 tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1322 tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
1325 * Update has_rules[] flags for the updated tg's subtree. A tg is
1326 * considered to have rules if either the tg itself or any of its
1327 * ancestors has rules. This identifies groups without any
1328 * restrictions in the whole hierarchy and allows them to bypass
1331 blkg_for_each_descendant_pre(blkg, pos_css,
1332 global ? tg->td->queue->root_blkg : tg_to_blkg(tg)) {
1333 struct throtl_grp *this_tg = blkg_to_tg(blkg);
1334 struct throtl_grp *parent_tg;
1336 tg_update_has_rules(this_tg);
1337 /* ignore root/second level */
1338 if (!cgroup_subsys_on_dfl(io_cgrp_subsys) || !blkg->parent ||
1339 !blkg->parent->parent)
1341 parent_tg = blkg_to_tg(blkg->parent);
1343 * make sure all children has lower idle time threshold and
1344 * higher latency target
1346 this_tg->idletime_threshold = min(this_tg->idletime_threshold,
1347 parent_tg->idletime_threshold);
1348 this_tg->latency_target = max(this_tg->latency_target,
1349 parent_tg->latency_target);
1353 * We're already holding queue_lock and know @tg is valid. Let's
1354 * apply the new config directly.
1356 * Restart the slices for both READ and WRITES. It might happen
1357 * that a group's limit are dropped suddenly and we don't want to
1358 * account recently dispatched IO with new low rate.
1360 throtl_start_new_slice(tg, READ, false);
1361 throtl_start_new_slice(tg, WRITE, false);
1363 if (tg->flags & THROTL_TG_PENDING) {
1364 tg_update_disptime(tg);
1365 throtl_schedule_next_dispatch(sq->parent_sq, true);
1369 static ssize_t tg_set_conf(struct kernfs_open_file *of,
1370 char *buf, size_t nbytes, loff_t off, bool is_u64)
1372 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1373 struct blkg_conf_ctx ctx;
1374 struct throtl_grp *tg;
1378 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1383 if (sscanf(ctx.body, "%llu", &v) != 1)
1388 tg = blkg_to_tg(ctx.blkg);
1389 tg_update_carryover(tg);
1392 *(u64 *)((void *)tg + of_cft(of)->private) = v;
1394 *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
1396 tg_conf_updated(tg, false);
1399 blkg_conf_finish(&ctx);
1400 return ret ?: nbytes;
1403 static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1404 char *buf, size_t nbytes, loff_t off)
1406 return tg_set_conf(of, buf, nbytes, off, true);
1409 static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1410 char *buf, size_t nbytes, loff_t off)
1412 return tg_set_conf(of, buf, nbytes, off, false);
1415 static int tg_print_rwstat(struct seq_file *sf, void *v)
1417 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1418 blkg_prfill_rwstat, &blkcg_policy_throtl,
1419 seq_cft(sf)->private, true);
1423 static u64 tg_prfill_rwstat_recursive(struct seq_file *sf,
1424 struct blkg_policy_data *pd, int off)
1426 struct blkg_rwstat_sample sum;
1428 blkg_rwstat_recursive_sum(pd_to_blkg(pd), &blkcg_policy_throtl, off,
1430 return __blkg_prfill_rwstat(sf, pd, &sum);
1433 static int tg_print_rwstat_recursive(struct seq_file *sf, void *v)
1435 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1436 tg_prfill_rwstat_recursive, &blkcg_policy_throtl,
1437 seq_cft(sf)->private, true);
1441 static struct cftype throtl_legacy_files[] = {
1443 .name = "throttle.read_bps_device",
1444 .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
1445 .seq_show = tg_print_conf_u64,
1446 .write = tg_set_conf_u64,
1449 .name = "throttle.write_bps_device",
1450 .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
1451 .seq_show = tg_print_conf_u64,
1452 .write = tg_set_conf_u64,
1455 .name = "throttle.read_iops_device",
1456 .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
1457 .seq_show = tg_print_conf_uint,
1458 .write = tg_set_conf_uint,
1461 .name = "throttle.write_iops_device",
1462 .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
1463 .seq_show = tg_print_conf_uint,
1464 .write = tg_set_conf_uint,
1467 .name = "throttle.io_service_bytes",
1468 .private = offsetof(struct throtl_grp, stat_bytes),
1469 .seq_show = tg_print_rwstat,
1472 .name = "throttle.io_service_bytes_recursive",
1473 .private = offsetof(struct throtl_grp, stat_bytes),
1474 .seq_show = tg_print_rwstat_recursive,
1477 .name = "throttle.io_serviced",
1478 .private = offsetof(struct throtl_grp, stat_ios),
1479 .seq_show = tg_print_rwstat,
1482 .name = "throttle.io_serviced_recursive",
1483 .private = offsetof(struct throtl_grp, stat_ios),
1484 .seq_show = tg_print_rwstat_recursive,
1489 static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
1492 struct throtl_grp *tg = pd_to_tg(pd);
1493 const char *dname = blkg_dev_name(pd->blkg);
1494 char bufs[4][21] = { "max", "max", "max", "max" };
1496 unsigned int iops_dft;
1497 char idle_time[26] = "";
1498 char latency_time[26] = "";
1503 if (off == LIMIT_LOW) {
1508 iops_dft = UINT_MAX;
1511 if (tg->bps_conf[READ][off] == bps_dft &&
1512 tg->bps_conf[WRITE][off] == bps_dft &&
1513 tg->iops_conf[READ][off] == iops_dft &&
1514 tg->iops_conf[WRITE][off] == iops_dft &&
1515 (off != LIMIT_LOW ||
1516 (tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD &&
1517 tg->latency_target_conf == DFL_LATENCY_TARGET)))
1520 if (tg->bps_conf[READ][off] != U64_MAX)
1521 snprintf(bufs[0], sizeof(bufs[0]), "%llu",
1522 tg->bps_conf[READ][off]);
1523 if (tg->bps_conf[WRITE][off] != U64_MAX)
1524 snprintf(bufs[1], sizeof(bufs[1]), "%llu",
1525 tg->bps_conf[WRITE][off]);
1526 if (tg->iops_conf[READ][off] != UINT_MAX)
1527 snprintf(bufs[2], sizeof(bufs[2]), "%u",
1528 tg->iops_conf[READ][off]);
1529 if (tg->iops_conf[WRITE][off] != UINT_MAX)
1530 snprintf(bufs[3], sizeof(bufs[3]), "%u",
1531 tg->iops_conf[WRITE][off]);
1532 if (off == LIMIT_LOW) {
1533 if (tg->idletime_threshold_conf == ULONG_MAX)
1534 strcpy(idle_time, " idle=max");
1536 snprintf(idle_time, sizeof(idle_time), " idle=%lu",
1537 tg->idletime_threshold_conf);
1539 if (tg->latency_target_conf == ULONG_MAX)
1540 strcpy(latency_time, " latency=max");
1542 snprintf(latency_time, sizeof(latency_time),
1543 " latency=%lu", tg->latency_target_conf);
1546 seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s%s%s\n",
1547 dname, bufs[0], bufs[1], bufs[2], bufs[3], idle_time,
1552 static int tg_print_limit(struct seq_file *sf, void *v)
1554 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
1555 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1559 static ssize_t tg_set_limit(struct kernfs_open_file *of,
1560 char *buf, size_t nbytes, loff_t off)
1562 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1563 struct blkg_conf_ctx ctx;
1564 struct throtl_grp *tg;
1566 unsigned long idle_time;
1567 unsigned long latency_time;
1569 int index = of_cft(of)->private;
1571 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1575 tg = blkg_to_tg(ctx.blkg);
1576 tg_update_carryover(tg);
1578 v[0] = tg->bps_conf[READ][index];
1579 v[1] = tg->bps_conf[WRITE][index];
1580 v[2] = tg->iops_conf[READ][index];
1581 v[3] = tg->iops_conf[WRITE][index];
1583 idle_time = tg->idletime_threshold_conf;
1584 latency_time = tg->latency_target_conf;
1586 char tok[27]; /* wiops=18446744073709551616 */
1591 if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
1600 if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
1608 if (!strcmp(tok, "rbps") && val > 1)
1610 else if (!strcmp(tok, "wbps") && val > 1)
1612 else if (!strcmp(tok, "riops") && val > 1)
1613 v[2] = min_t(u64, val, UINT_MAX);
1614 else if (!strcmp(tok, "wiops") && val > 1)
1615 v[3] = min_t(u64, val, UINT_MAX);
1616 else if (off == LIMIT_LOW && !strcmp(tok, "idle"))
1618 else if (off == LIMIT_LOW && !strcmp(tok, "latency"))
1624 tg->bps_conf[READ][index] = v[0];
1625 tg->bps_conf[WRITE][index] = v[1];
1626 tg->iops_conf[READ][index] = v[2];
1627 tg->iops_conf[WRITE][index] = v[3];
1629 if (index == LIMIT_MAX) {
1630 tg->bps[READ][index] = v[0];
1631 tg->bps[WRITE][index] = v[1];
1632 tg->iops[READ][index] = v[2];
1633 tg->iops[WRITE][index] = v[3];
1635 tg->bps[READ][LIMIT_LOW] = min(tg->bps_conf[READ][LIMIT_LOW],
1636 tg->bps_conf[READ][LIMIT_MAX]);
1637 tg->bps[WRITE][LIMIT_LOW] = min(tg->bps_conf[WRITE][LIMIT_LOW],
1638 tg->bps_conf[WRITE][LIMIT_MAX]);
1639 tg->iops[READ][LIMIT_LOW] = min(tg->iops_conf[READ][LIMIT_LOW],
1640 tg->iops_conf[READ][LIMIT_MAX]);
1641 tg->iops[WRITE][LIMIT_LOW] = min(tg->iops_conf[WRITE][LIMIT_LOW],
1642 tg->iops_conf[WRITE][LIMIT_MAX]);
1643 tg->idletime_threshold_conf = idle_time;
1644 tg->latency_target_conf = latency_time;
1646 /* force user to configure all settings for low limit */
1647 if (!(tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW] ||
1648 tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) ||
1649 tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD ||
1650 tg->latency_target_conf == DFL_LATENCY_TARGET) {
1651 tg->bps[READ][LIMIT_LOW] = 0;
1652 tg->bps[WRITE][LIMIT_LOW] = 0;
1653 tg->iops[READ][LIMIT_LOW] = 0;
1654 tg->iops[WRITE][LIMIT_LOW] = 0;
1655 tg->idletime_threshold = DFL_IDLE_THRESHOLD;
1656 tg->latency_target = DFL_LATENCY_TARGET;
1657 } else if (index == LIMIT_LOW) {
1658 tg->idletime_threshold = tg->idletime_threshold_conf;
1659 tg->latency_target = tg->latency_target_conf;
1662 blk_throtl_update_limit_valid(tg->td);
1663 if (tg->td->limit_valid[LIMIT_LOW]) {
1664 if (index == LIMIT_LOW)
1665 tg->td->limit_index = LIMIT_LOW;
1667 tg->td->limit_index = LIMIT_MAX;
1668 tg_conf_updated(tg, index == LIMIT_LOW &&
1669 tg->td->limit_valid[LIMIT_LOW]);
1672 blkg_conf_finish(&ctx);
1673 return ret ?: nbytes;
1676 static struct cftype throtl_files[] = {
1677 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1680 .flags = CFTYPE_NOT_ON_ROOT,
1681 .seq_show = tg_print_limit,
1682 .write = tg_set_limit,
1683 .private = LIMIT_LOW,
1688 .flags = CFTYPE_NOT_ON_ROOT,
1689 .seq_show = tg_print_limit,
1690 .write = tg_set_limit,
1691 .private = LIMIT_MAX,
1696 static void throtl_shutdown_wq(struct request_queue *q)
1698 struct throtl_data *td = q->td;
1700 cancel_work_sync(&td->dispatch_work);
1703 struct blkcg_policy blkcg_policy_throtl = {
1704 .dfl_cftypes = throtl_files,
1705 .legacy_cftypes = throtl_legacy_files,
1707 .pd_alloc_fn = throtl_pd_alloc,
1708 .pd_init_fn = throtl_pd_init,
1709 .pd_online_fn = throtl_pd_online,
1710 .pd_offline_fn = throtl_pd_offline,
1711 .pd_free_fn = throtl_pd_free,
1714 void blk_throtl_cancel_bios(struct request_queue *q)
1716 struct cgroup_subsys_state *pos_css;
1717 struct blkcg_gq *blkg;
1719 spin_lock_irq(&q->queue_lock);
1721 * queue_lock is held, rcu lock is not needed here technically.
1722 * However, rcu lock is still held to emphasize that following
1723 * path need RCU protection and to prevent warning from lockdep.
1726 blkg_for_each_descendant_post(blkg, pos_css, q->root_blkg) {
1727 struct throtl_grp *tg = blkg_to_tg(blkg);
1728 struct throtl_service_queue *sq = &tg->service_queue;
1731 * Set the flag to make sure throtl_pending_timer_fn() won't
1732 * stop until all throttled bios are dispatched.
1734 blkg_to_tg(blkg)->flags |= THROTL_TG_CANCELING;
1736 * Update disptime after setting the above flag to make sure
1737 * throtl_select_dispatch() won't exit without dispatching.
1739 tg_update_disptime(tg);
1741 throtl_schedule_pending_timer(sq, jiffies + 1);
1744 spin_unlock_irq(&q->queue_lock);
1747 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1748 static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
1750 unsigned long rtime = jiffies, wtime = jiffies;
1752 if (tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW])
1753 rtime = tg->last_low_overflow_time[READ];
1754 if (tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
1755 wtime = tg->last_low_overflow_time[WRITE];
1756 return min(rtime, wtime);
1759 /* tg should not be an intermediate node */
1760 static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
1762 struct throtl_service_queue *parent_sq;
1763 struct throtl_grp *parent = tg;
1764 unsigned long ret = __tg_last_low_overflow_time(tg);
1767 parent_sq = parent->service_queue.parent_sq;
1768 parent = sq_to_tg(parent_sq);
1773 * The parent doesn't have low limit, it always reaches low
1774 * limit. Its overflow time is useless for children
1776 if (!parent->bps[READ][LIMIT_LOW] &&
1777 !parent->iops[READ][LIMIT_LOW] &&
1778 !parent->bps[WRITE][LIMIT_LOW] &&
1779 !parent->iops[WRITE][LIMIT_LOW])
1781 if (time_after(__tg_last_low_overflow_time(parent), ret))
1782 ret = __tg_last_low_overflow_time(parent);
1787 static bool throtl_tg_is_idle(struct throtl_grp *tg)
1790 * cgroup is idle if:
1791 * - single idle is too long, longer than a fixed value (in case user
1792 * configure a too big threshold) or 4 times of idletime threshold
1793 * - average think time is more than threshold
1794 * - IO latency is largely below threshold
1799 time = min_t(unsigned long, MAX_IDLE_TIME, 4 * tg->idletime_threshold);
1800 ret = tg->latency_target == DFL_LATENCY_TARGET ||
1801 tg->idletime_threshold == DFL_IDLE_THRESHOLD ||
1802 (ktime_get_ns() >> 10) - tg->last_finish_time > time ||
1803 tg->avg_idletime > tg->idletime_threshold ||
1804 (tg->latency_target && tg->bio_cnt &&
1805 tg->bad_bio_cnt * 5 < tg->bio_cnt);
1806 throtl_log(&tg->service_queue,
1807 "avg_idle=%ld, idle_threshold=%ld, bad_bio=%d, total_bio=%d, is_idle=%d, scale=%d",
1808 tg->avg_idletime, tg->idletime_threshold, tg->bad_bio_cnt,
1809 tg->bio_cnt, ret, tg->td->scale);
1813 static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
1815 struct throtl_service_queue *sq = &tg->service_queue;
1816 bool read_limit, write_limit;
1819 * if cgroup reaches low limit (if low limit is 0, the cgroup always
1820 * reaches), it's ok to upgrade to next limit
1822 read_limit = tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW];
1823 write_limit = tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW];
1824 if (!read_limit && !write_limit)
1826 if (read_limit && sq->nr_queued[READ] &&
1827 (!write_limit || sq->nr_queued[WRITE]))
1829 if (write_limit && sq->nr_queued[WRITE] &&
1830 (!read_limit || sq->nr_queued[READ]))
1833 if (time_after_eq(jiffies,
1834 tg_last_low_overflow_time(tg) + tg->td->throtl_slice) &&
1835 throtl_tg_is_idle(tg))
1840 static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
1843 if (throtl_tg_can_upgrade(tg))
1845 tg = sq_to_tg(tg->service_queue.parent_sq);
1846 if (!tg || !tg_to_blkg(tg)->parent)
1852 static bool throtl_can_upgrade(struct throtl_data *td,
1853 struct throtl_grp *this_tg)
1855 struct cgroup_subsys_state *pos_css;
1856 struct blkcg_gq *blkg;
1858 if (td->limit_index != LIMIT_LOW)
1861 if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
1865 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1866 struct throtl_grp *tg = blkg_to_tg(blkg);
1870 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1872 if (!throtl_hierarchy_can_upgrade(tg)) {
1881 static void throtl_upgrade_check(struct throtl_grp *tg)
1883 unsigned long now = jiffies;
1885 if (tg->td->limit_index != LIMIT_LOW)
1888 if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1891 tg->last_check_time = now;
1893 if (!time_after_eq(now,
1894 __tg_last_low_overflow_time(tg) + tg->td->throtl_slice))
1897 if (throtl_can_upgrade(tg->td, NULL))
1898 throtl_upgrade_state(tg->td);
1901 static void throtl_upgrade_state(struct throtl_data *td)
1903 struct cgroup_subsys_state *pos_css;
1904 struct blkcg_gq *blkg;
1906 throtl_log(&td->service_queue, "upgrade to max");
1907 td->limit_index = LIMIT_MAX;
1908 td->low_upgrade_time = jiffies;
1911 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1912 struct throtl_grp *tg = blkg_to_tg(blkg);
1913 struct throtl_service_queue *sq = &tg->service_queue;
1915 tg->disptime = jiffies - 1;
1916 throtl_select_dispatch(sq);
1917 throtl_schedule_next_dispatch(sq, true);
1920 throtl_select_dispatch(&td->service_queue);
1921 throtl_schedule_next_dispatch(&td->service_queue, true);
1922 queue_work(kthrotld_workqueue, &td->dispatch_work);
1925 static void throtl_downgrade_state(struct throtl_data *td)
1929 throtl_log(&td->service_queue, "downgrade, scale %d", td->scale);
1931 td->low_upgrade_time = jiffies - td->scale * td->throtl_slice;
1935 td->limit_index = LIMIT_LOW;
1936 td->low_downgrade_time = jiffies;
1939 static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
1941 struct throtl_data *td = tg->td;
1942 unsigned long now = jiffies;
1945 * If cgroup is below low limit, consider downgrade and throttle other
1948 if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
1949 time_after_eq(now, tg_last_low_overflow_time(tg) +
1950 td->throtl_slice) &&
1951 (!throtl_tg_is_idle(tg) ||
1952 !list_empty(&tg_to_blkg(tg)->blkcg->css.children)))
1957 static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
1960 if (!throtl_tg_can_downgrade(tg))
1962 tg = sq_to_tg(tg->service_queue.parent_sq);
1963 if (!tg || !tg_to_blkg(tg)->parent)
1969 static void throtl_downgrade_check(struct throtl_grp *tg)
1973 unsigned long elapsed_time;
1974 unsigned long now = jiffies;
1976 if (tg->td->limit_index != LIMIT_MAX ||
1977 !tg->td->limit_valid[LIMIT_LOW])
1979 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1981 if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1984 elapsed_time = now - tg->last_check_time;
1985 tg->last_check_time = now;
1987 if (time_before(now, tg_last_low_overflow_time(tg) +
1988 tg->td->throtl_slice))
1991 if (tg->bps[READ][LIMIT_LOW]) {
1992 bps = tg->last_bytes_disp[READ] * HZ;
1993 do_div(bps, elapsed_time);
1994 if (bps >= tg->bps[READ][LIMIT_LOW])
1995 tg->last_low_overflow_time[READ] = now;
1998 if (tg->bps[WRITE][LIMIT_LOW]) {
1999 bps = tg->last_bytes_disp[WRITE] * HZ;
2000 do_div(bps, elapsed_time);
2001 if (bps >= tg->bps[WRITE][LIMIT_LOW])
2002 tg->last_low_overflow_time[WRITE] = now;
2005 if (tg->iops[READ][LIMIT_LOW]) {
2006 iops = tg->last_io_disp[READ] * HZ / elapsed_time;
2007 if (iops >= tg->iops[READ][LIMIT_LOW])
2008 tg->last_low_overflow_time[READ] = now;
2011 if (tg->iops[WRITE][LIMIT_LOW]) {
2012 iops = tg->last_io_disp[WRITE] * HZ / elapsed_time;
2013 if (iops >= tg->iops[WRITE][LIMIT_LOW])
2014 tg->last_low_overflow_time[WRITE] = now;
2018 * If cgroup is below low limit, consider downgrade and throttle other
2021 if (throtl_hierarchy_can_downgrade(tg))
2022 throtl_downgrade_state(tg->td);
2024 tg->last_bytes_disp[READ] = 0;
2025 tg->last_bytes_disp[WRITE] = 0;
2026 tg->last_io_disp[READ] = 0;
2027 tg->last_io_disp[WRITE] = 0;
2030 static void blk_throtl_update_idletime(struct throtl_grp *tg)
2033 unsigned long last_finish_time = tg->last_finish_time;
2035 if (last_finish_time == 0)
2038 now = ktime_get_ns() >> 10;
2039 if (now <= last_finish_time ||
2040 last_finish_time == tg->checked_last_finish_time)
2043 tg->avg_idletime = (tg->avg_idletime * 7 + now - last_finish_time) >> 3;
2044 tg->checked_last_finish_time = last_finish_time;
2047 static void throtl_update_latency_buckets(struct throtl_data *td)
2049 struct avg_latency_bucket avg_latency[2][LATENCY_BUCKET_SIZE];
2051 unsigned long last_latency[2] = { 0 };
2052 unsigned long latency[2];
2054 if (!blk_queue_nonrot(td->queue) || !td->limit_valid[LIMIT_LOW])
2056 if (time_before(jiffies, td->last_calculate_time + HZ))
2058 td->last_calculate_time = jiffies;
2060 memset(avg_latency, 0, sizeof(avg_latency));
2061 for (rw = READ; rw <= WRITE; rw++) {
2062 for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2063 struct latency_bucket *tmp = &td->tmp_buckets[rw][i];
2065 for_each_possible_cpu(cpu) {
2066 struct latency_bucket *bucket;
2068 /* this isn't race free, but ok in practice */
2069 bucket = per_cpu_ptr(td->latency_buckets[rw],
2071 tmp->total_latency += bucket[i].total_latency;
2072 tmp->samples += bucket[i].samples;
2073 bucket[i].total_latency = 0;
2074 bucket[i].samples = 0;
2077 if (tmp->samples >= 32) {
2078 int samples = tmp->samples;
2080 latency[rw] = tmp->total_latency;
2082 tmp->total_latency = 0;
2084 latency[rw] /= samples;
2085 if (latency[rw] == 0)
2087 avg_latency[rw][i].latency = latency[rw];
2092 for (rw = READ; rw <= WRITE; rw++) {
2093 for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2094 if (!avg_latency[rw][i].latency) {
2095 if (td->avg_buckets[rw][i].latency < last_latency[rw])
2096 td->avg_buckets[rw][i].latency =
2101 if (!td->avg_buckets[rw][i].valid)
2102 latency[rw] = avg_latency[rw][i].latency;
2104 latency[rw] = (td->avg_buckets[rw][i].latency * 7 +
2105 avg_latency[rw][i].latency) >> 3;
2107 td->avg_buckets[rw][i].latency = max(latency[rw],
2109 td->avg_buckets[rw][i].valid = true;
2110 last_latency[rw] = td->avg_buckets[rw][i].latency;
2114 for (i = 0; i < LATENCY_BUCKET_SIZE; i++)
2115 throtl_log(&td->service_queue,
2116 "Latency bucket %d: read latency=%ld, read valid=%d, "
2117 "write latency=%ld, write valid=%d", i,
2118 td->avg_buckets[READ][i].latency,
2119 td->avg_buckets[READ][i].valid,
2120 td->avg_buckets[WRITE][i].latency,
2121 td->avg_buckets[WRITE][i].valid);
2124 static inline void throtl_update_latency_buckets(struct throtl_data *td)
2128 static void blk_throtl_update_idletime(struct throtl_grp *tg)
2132 static void throtl_downgrade_check(struct throtl_grp *tg)
2136 static void throtl_upgrade_check(struct throtl_grp *tg)
2140 static bool throtl_can_upgrade(struct throtl_data *td,
2141 struct throtl_grp *this_tg)
2146 static void throtl_upgrade_state(struct throtl_data *td)
2151 bool __blk_throtl_bio(struct bio *bio)
2153 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2154 struct blkcg_gq *blkg = bio->bi_blkg;
2155 struct throtl_qnode *qn = NULL;
2156 struct throtl_grp *tg = blkg_to_tg(blkg);
2157 struct throtl_service_queue *sq;
2158 bool rw = bio_data_dir(bio);
2159 bool throttled = false;
2160 struct throtl_data *td = tg->td;
2164 if (!cgroup_subsys_on_dfl(io_cgrp_subsys)) {
2165 blkg_rwstat_add(&tg->stat_bytes, bio->bi_opf,
2166 bio->bi_iter.bi_size);
2167 blkg_rwstat_add(&tg->stat_ios, bio->bi_opf, 1);
2170 spin_lock_irq(&q->queue_lock);
2172 throtl_update_latency_buckets(td);
2174 blk_throtl_update_idletime(tg);
2176 sq = &tg->service_queue;
2180 if (tg->last_low_overflow_time[rw] == 0)
2181 tg->last_low_overflow_time[rw] = jiffies;
2182 throtl_downgrade_check(tg);
2183 throtl_upgrade_check(tg);
2184 /* throtl is FIFO - if bios are already queued, should queue */
2185 if (sq->nr_queued[rw])
2188 /* if above limits, break to queue */
2189 if (!tg_may_dispatch(tg, bio, NULL)) {
2190 tg->last_low_overflow_time[rw] = jiffies;
2191 if (throtl_can_upgrade(td, tg)) {
2192 throtl_upgrade_state(td);
2198 /* within limits, let's charge and dispatch directly */
2199 throtl_charge_bio(tg, bio);
2202 * We need to trim slice even when bios are not being queued
2203 * otherwise it might happen that a bio is not queued for
2204 * a long time and slice keeps on extending and trim is not
2205 * called for a long time. Now if limits are reduced suddenly
2206 * we take into account all the IO dispatched so far at new
2207 * low rate and * newly queued IO gets a really long dispatch
2210 * So keep on trimming slice even if bio is not queued.
2212 throtl_trim_slice(tg, rw);
2215 * @bio passed through this layer without being throttled.
2216 * Climb up the ladder. If we're already at the top, it
2217 * can be executed directly.
2219 qn = &tg->qnode_on_parent[rw];
2223 bio_set_flag(bio, BIO_BPS_THROTTLED);
2228 /* out-of-limit, queue to @tg */
2229 throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
2230 rw == READ ? 'R' : 'W',
2231 tg->bytes_disp[rw], bio->bi_iter.bi_size,
2232 tg_bps_limit(tg, rw),
2233 tg->io_disp[rw], tg_iops_limit(tg, rw),
2234 sq->nr_queued[READ], sq->nr_queued[WRITE]);
2236 tg->last_low_overflow_time[rw] = jiffies;
2238 td->nr_queued[rw]++;
2239 throtl_add_bio_tg(bio, qn, tg);
2243 * Update @tg's dispatch time and force schedule dispatch if @tg
2244 * was empty before @bio. The forced scheduling isn't likely to
2245 * cause undue delay as @bio is likely to be dispatched directly if
2246 * its @tg's disptime is not in the future.
2248 if (tg->flags & THROTL_TG_WAS_EMPTY) {
2249 tg_update_disptime(tg);
2250 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
2254 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2255 if (throttled || !td->track_bio_latency)
2256 bio->bi_issue.value |= BIO_ISSUE_THROTL_SKIP_LATENCY;
2258 spin_unlock_irq(&q->queue_lock);
2264 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2265 static void throtl_track_latency(struct throtl_data *td, sector_t size,
2266 enum req_op op, unsigned long time)
2268 const bool rw = op_is_write(op);
2269 struct latency_bucket *latency;
2272 if (!td || td->limit_index != LIMIT_LOW ||
2273 !(op == REQ_OP_READ || op == REQ_OP_WRITE) ||
2274 !blk_queue_nonrot(td->queue))
2277 index = request_bucket_index(size);
2279 latency = get_cpu_ptr(td->latency_buckets[rw]);
2280 latency[index].total_latency += time;
2281 latency[index].samples++;
2282 put_cpu_ptr(td->latency_buckets[rw]);
2285 void blk_throtl_stat_add(struct request *rq, u64 time_ns)
2287 struct request_queue *q = rq->q;
2288 struct throtl_data *td = q->td;
2290 throtl_track_latency(td, blk_rq_stats_sectors(rq), req_op(rq),
2294 void blk_throtl_bio_endio(struct bio *bio)
2296 struct blkcg_gq *blkg;
2297 struct throtl_grp *tg;
2299 unsigned long finish_time;
2300 unsigned long start_time;
2302 int rw = bio_data_dir(bio);
2304 blkg = bio->bi_blkg;
2307 tg = blkg_to_tg(blkg);
2308 if (!tg->td->limit_valid[LIMIT_LOW])
2311 finish_time_ns = ktime_get_ns();
2312 tg->last_finish_time = finish_time_ns >> 10;
2314 start_time = bio_issue_time(&bio->bi_issue) >> 10;
2315 finish_time = __bio_issue_time(finish_time_ns) >> 10;
2316 if (!start_time || finish_time <= start_time)
2319 lat = finish_time - start_time;
2320 /* this is only for bio based driver */
2321 if (!(bio->bi_issue.value & BIO_ISSUE_THROTL_SKIP_LATENCY))
2322 throtl_track_latency(tg->td, bio_issue_size(&bio->bi_issue),
2325 if (tg->latency_target && lat >= tg->td->filtered_latency) {
2327 unsigned int threshold;
2329 bucket = request_bucket_index(bio_issue_size(&bio->bi_issue));
2330 threshold = tg->td->avg_buckets[rw][bucket].latency +
2332 if (lat > threshold)
2335 * Not race free, could get wrong count, which means cgroups
2341 if (time_after(jiffies, tg->bio_cnt_reset_time) || tg->bio_cnt > 1024) {
2342 tg->bio_cnt_reset_time = tg->td->throtl_slice + jiffies;
2344 tg->bad_bio_cnt /= 2;
2349 int blk_throtl_init(struct request_queue *q)
2351 struct throtl_data *td;
2354 td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
2357 td->latency_buckets[READ] = __alloc_percpu(sizeof(struct latency_bucket) *
2358 LATENCY_BUCKET_SIZE, __alignof__(u64));
2359 if (!td->latency_buckets[READ]) {
2363 td->latency_buckets[WRITE] = __alloc_percpu(sizeof(struct latency_bucket) *
2364 LATENCY_BUCKET_SIZE, __alignof__(u64));
2365 if (!td->latency_buckets[WRITE]) {
2366 free_percpu(td->latency_buckets[READ]);
2371 INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
2372 throtl_service_queue_init(&td->service_queue);
2377 td->limit_valid[LIMIT_MAX] = true;
2378 td->limit_index = LIMIT_MAX;
2379 td->low_upgrade_time = jiffies;
2380 td->low_downgrade_time = jiffies;
2382 /* activate policy */
2383 ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
2385 free_percpu(td->latency_buckets[READ]);
2386 free_percpu(td->latency_buckets[WRITE]);
2392 void blk_throtl_exit(struct request_queue *q)
2395 del_timer_sync(&q->td->service_queue.pending_timer);
2396 throtl_shutdown_wq(q);
2397 blkcg_deactivate_policy(q, &blkcg_policy_throtl);
2398 free_percpu(q->td->latency_buckets[READ]);
2399 free_percpu(q->td->latency_buckets[WRITE]);
2403 void blk_throtl_register_queue(struct request_queue *q)
2405 struct throtl_data *td;
2411 if (blk_queue_nonrot(q)) {
2412 td->throtl_slice = DFL_THROTL_SLICE_SSD;
2413 td->filtered_latency = LATENCY_FILTERED_SSD;
2415 td->throtl_slice = DFL_THROTL_SLICE_HD;
2416 td->filtered_latency = LATENCY_FILTERED_HD;
2417 for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2418 td->avg_buckets[READ][i].latency = DFL_HD_BASELINE_LATENCY;
2419 td->avg_buckets[WRITE][i].latency = DFL_HD_BASELINE_LATENCY;
2422 #ifndef CONFIG_BLK_DEV_THROTTLING_LOW
2423 /* if no low limit, use previous default */
2424 td->throtl_slice = DFL_THROTL_SLICE_HD;
2427 td->track_bio_latency = !queue_is_mq(q);
2428 if (!td->track_bio_latency)
2429 blk_stat_enable_accounting(q);
2432 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2433 ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
2437 return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
2440 ssize_t blk_throtl_sample_time_store(struct request_queue *q,
2441 const char *page, size_t count)
2448 if (kstrtoul(page, 10, &v))
2450 t = msecs_to_jiffies(v);
2451 if (t == 0 || t > MAX_THROTL_SLICE)
2453 q->td->throtl_slice = t;
2458 static int __init throtl_init(void)
2460 kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2461 if (!kthrotld_workqueue)
2462 panic("Failed to create kthrotld\n");
2464 return blkcg_policy_register(&blkcg_policy_throtl);
2467 module_init(throtl_init);