2 * Interface for controlling IO bandwidth on a request queue
4 * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/blkdev.h>
10 #include <linux/bio.h>
11 #include <linux/blktrace_api.h>
12 #include <linux/blk-cgroup.h>
15 /* Max dispatch from a group in 1 round */
16 static int throtl_grp_quantum = 8;
18 /* Total max dispatch from all groups in one round */
19 static int throtl_quantum = 32;
21 /* Throttling is performed over 100ms slice and after that slice is renewed */
22 #define DFL_THROTL_SLICE (HZ / 10)
23 #define MAX_THROTL_SLICE (HZ)
25 static struct blkcg_policy blkcg_policy_throtl;
27 /* A workqueue to queue throttle related work */
28 static struct workqueue_struct *kthrotld_workqueue;
31 * To implement hierarchical throttling, throtl_grps form a tree and bios
32 * are dispatched upwards level by level until they reach the top and get
33 * issued. When dispatching bios from the children and local group at each
34 * level, if the bios are dispatched into a single bio_list, there's a risk
35 * of a local or child group which can queue many bios at once filling up
36 * the list starving others.
38 * To avoid such starvation, dispatched bios are queued separately
39 * according to where they came from. When they are again dispatched to
40 * the parent, they're popped in round-robin order so that no single source
41 * hogs the dispatch window.
43 * throtl_qnode is used to keep the queued bios separated by their sources.
44 * Bios are queued to throtl_qnode which in turn is queued to
45 * throtl_service_queue and then dispatched in round-robin order.
47 * It's also used to track the reference counts on blkg's. A qnode always
48 * belongs to a throtl_grp and gets queued on itself or the parent, so
49 * incrementing the reference of the associated throtl_grp when a qnode is
50 * queued and decrementing when dequeued is enough to keep the whole blkg
51 * tree pinned while bios are in flight.
54 struct list_head node; /* service_queue->queued[] */
55 struct bio_list bios; /* queued bios */
56 struct throtl_grp *tg; /* tg this qnode belongs to */
59 struct throtl_service_queue {
60 struct throtl_service_queue *parent_sq; /* the parent service_queue */
63 * Bios queued directly to this service_queue or dispatched from
64 * children throtl_grp's.
66 struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
67 unsigned int nr_queued[2]; /* number of queued bios */
70 * RB tree of active children throtl_grp's, which are sorted by
73 struct rb_root pending_tree; /* RB tree of active tgs */
74 struct rb_node *first_pending; /* first node in the tree */
75 unsigned int nr_pending; /* # queued in the tree */
76 unsigned long first_pending_disptime; /* disptime of the first tg */
77 struct timer_list pending_timer; /* fires on first_pending_disptime */
81 THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
82 THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
85 #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
94 /* must be the first member */
95 struct blkg_policy_data pd;
97 /* active throtl group service_queue member */
98 struct rb_node rb_node;
100 /* throtl_data this group belongs to */
101 struct throtl_data *td;
103 /* this group's service queue */
104 struct throtl_service_queue service_queue;
107 * qnode_on_self is used when bios are directly queued to this
108 * throtl_grp so that local bios compete fairly with bios
109 * dispatched from children. qnode_on_parent is used when bios are
110 * dispatched from this throtl_grp into its parent and will compete
111 * with the sibling qnode_on_parents and the parent's
114 struct throtl_qnode qnode_on_self[2];
115 struct throtl_qnode qnode_on_parent[2];
118 * Dispatch time in jiffies. This is the estimated time when group
119 * will unthrottle and is ready to dispatch more bio. It is used as
120 * key to sort active groups in service tree.
122 unsigned long disptime;
126 /* are there any throtl rules between this group and td? */
129 /* internally used bytes per second rate limits */
130 uint64_t bps[2][LIMIT_CNT];
131 /* user configured bps limits */
132 uint64_t bps_conf[2][LIMIT_CNT];
134 /* internally used IOPS limits */
135 unsigned int iops[2][LIMIT_CNT];
136 /* user configured IOPS limits */
137 unsigned int iops_conf[2][LIMIT_CNT];
139 /* Number of bytes disptached in current slice */
140 uint64_t bytes_disp[2];
141 /* Number of bio's dispatched in current slice */
142 unsigned int io_disp[2];
144 unsigned long last_low_overflow_time[2];
146 uint64_t last_bytes_disp[2];
147 unsigned int last_io_disp[2];
149 unsigned long last_check_time;
151 /* When did we start a new slice */
152 unsigned long slice_start[2];
153 unsigned long slice_end[2];
158 /* service tree for active throtl groups */
159 struct throtl_service_queue service_queue;
161 struct request_queue *queue;
163 /* Total Number of queued bios on READ and WRITE lists */
164 unsigned int nr_queued[2];
166 unsigned int throtl_slice;
168 /* Work for dispatching throttled bios */
169 struct work_struct dispatch_work;
170 unsigned int limit_index;
171 bool limit_valid[LIMIT_CNT];
173 unsigned long low_upgrade_time;
174 unsigned long low_downgrade_time;
177 static void throtl_pending_timer_fn(unsigned long arg);
179 static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
181 return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
184 static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
186 return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
189 static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
191 return pd_to_blkg(&tg->pd);
195 * sq_to_tg - return the throl_grp the specified service queue belongs to
196 * @sq: the throtl_service_queue of interest
198 * Return the throtl_grp @sq belongs to. If @sq is the top-level one
199 * embedded in throtl_data, %NULL is returned.
201 static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
203 if (sq && sq->parent_sq)
204 return container_of(sq, struct throtl_grp, service_queue);
210 * sq_to_td - return throtl_data the specified service queue belongs to
211 * @sq: the throtl_service_queue of interest
213 * A service_queue can be embedded in either a throtl_grp or throtl_data.
214 * Determine the associated throtl_data accordingly and return it.
216 static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
218 struct throtl_grp *tg = sq_to_tg(sq);
223 return container_of(sq, struct throtl_data, service_queue);
226 static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
228 struct blkcg_gq *blkg = tg_to_blkg(tg);
231 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
233 ret = tg->bps[rw][tg->td->limit_index];
234 if (ret == 0 && tg->td->limit_index == LIMIT_LOW)
235 return tg->bps[rw][LIMIT_MAX];
239 static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
241 struct blkcg_gq *blkg = tg_to_blkg(tg);
244 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
246 ret = tg->iops[rw][tg->td->limit_index];
247 if (ret == 0 && tg->td->limit_index == LIMIT_LOW)
248 return tg->iops[rw][LIMIT_MAX];
253 * throtl_log - log debug message via blktrace
254 * @sq: the service_queue being reported
255 * @fmt: printf format string
258 * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
259 * throtl_grp; otherwise, just "throtl".
261 #define throtl_log(sq, fmt, args...) do { \
262 struct throtl_grp *__tg = sq_to_tg((sq)); \
263 struct throtl_data *__td = sq_to_td((sq)); \
266 if (likely(!blk_trace_note_message_enabled(__td->queue))) \
271 blkg_path(tg_to_blkg(__tg), __pbuf, sizeof(__pbuf)); \
272 blk_add_trace_msg(__td->queue, "throtl %s " fmt, __pbuf, ##args); \
274 blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
278 static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
280 INIT_LIST_HEAD(&qn->node);
281 bio_list_init(&qn->bios);
286 * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
287 * @bio: bio being added
288 * @qn: qnode to add bio to
289 * @queued: the service_queue->queued[] list @qn belongs to
291 * Add @bio to @qn and put @qn on @queued if it's not already on.
292 * @qn->tg's reference count is bumped when @qn is activated. See the
293 * comment on top of throtl_qnode definition for details.
295 static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
296 struct list_head *queued)
298 bio_list_add(&qn->bios, bio);
299 if (list_empty(&qn->node)) {
300 list_add_tail(&qn->node, queued);
301 blkg_get(tg_to_blkg(qn->tg));
306 * throtl_peek_queued - peek the first bio on a qnode list
307 * @queued: the qnode list to peek
309 static struct bio *throtl_peek_queued(struct list_head *queued)
311 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
314 if (list_empty(queued))
317 bio = bio_list_peek(&qn->bios);
323 * throtl_pop_queued - pop the first bio form a qnode list
324 * @queued: the qnode list to pop a bio from
325 * @tg_to_put: optional out argument for throtl_grp to put
327 * Pop the first bio from the qnode list @queued. After popping, the first
328 * qnode is removed from @queued if empty or moved to the end of @queued so
329 * that the popping order is round-robin.
331 * When the first qnode is removed, its associated throtl_grp should be put
332 * too. If @tg_to_put is NULL, this function automatically puts it;
333 * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
334 * responsible for putting it.
336 static struct bio *throtl_pop_queued(struct list_head *queued,
337 struct throtl_grp **tg_to_put)
339 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
342 if (list_empty(queued))
345 bio = bio_list_pop(&qn->bios);
348 if (bio_list_empty(&qn->bios)) {
349 list_del_init(&qn->node);
353 blkg_put(tg_to_blkg(qn->tg));
355 list_move_tail(&qn->node, queued);
361 /* init a service_queue, assumes the caller zeroed it */
362 static void throtl_service_queue_init(struct throtl_service_queue *sq)
364 INIT_LIST_HEAD(&sq->queued[0]);
365 INIT_LIST_HEAD(&sq->queued[1]);
366 sq->pending_tree = RB_ROOT;
367 setup_timer(&sq->pending_timer, throtl_pending_timer_fn,
371 static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
373 struct throtl_grp *tg;
376 tg = kzalloc_node(sizeof(*tg), gfp, node);
380 throtl_service_queue_init(&tg->service_queue);
382 for (rw = READ; rw <= WRITE; rw++) {
383 throtl_qnode_init(&tg->qnode_on_self[rw], tg);
384 throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
387 RB_CLEAR_NODE(&tg->rb_node);
388 tg->bps[READ][LIMIT_MAX] = U64_MAX;
389 tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
390 tg->iops[READ][LIMIT_MAX] = UINT_MAX;
391 tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
392 tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
393 tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
394 tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
395 tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
396 /* LIMIT_LOW will have default value 0 */
401 static void throtl_pd_init(struct blkg_policy_data *pd)
403 struct throtl_grp *tg = pd_to_tg(pd);
404 struct blkcg_gq *blkg = tg_to_blkg(tg);
405 struct throtl_data *td = blkg->q->td;
406 struct throtl_service_queue *sq = &tg->service_queue;
409 * If on the default hierarchy, we switch to properly hierarchical
410 * behavior where limits on a given throtl_grp are applied to the
411 * whole subtree rather than just the group itself. e.g. If 16M
412 * read_bps limit is set on the root group, the whole system can't
413 * exceed 16M for the device.
415 * If not on the default hierarchy, the broken flat hierarchy
416 * behavior is retained where all throtl_grps are treated as if
417 * they're all separate root groups right below throtl_data.
418 * Limits of a group don't interact with limits of other groups
419 * regardless of the position of the group in the hierarchy.
421 sq->parent_sq = &td->service_queue;
422 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
423 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
428 * Set has_rules[] if @tg or any of its parents have limits configured.
429 * This doesn't require walking up to the top of the hierarchy as the
430 * parent's has_rules[] is guaranteed to be correct.
432 static void tg_update_has_rules(struct throtl_grp *tg)
434 struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
435 struct throtl_data *td = tg->td;
438 for (rw = READ; rw <= WRITE; rw++)
439 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
440 (td->limit_valid[td->limit_index] &&
441 (tg_bps_limit(tg, rw) != U64_MAX ||
442 tg_iops_limit(tg, rw) != UINT_MAX));
445 static void throtl_pd_online(struct blkg_policy_data *pd)
448 * We don't want new groups to escape the limits of its ancestors.
449 * Update has_rules[] after a new group is brought online.
451 tg_update_has_rules(pd_to_tg(pd));
454 static void blk_throtl_update_limit_valid(struct throtl_data *td)
456 struct cgroup_subsys_state *pos_css;
457 struct blkcg_gq *blkg;
458 bool low_valid = false;
461 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
462 struct throtl_grp *tg = blkg_to_tg(blkg);
464 if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
465 tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
470 td->limit_valid[LIMIT_LOW] = low_valid;
473 static void throtl_upgrade_state(struct throtl_data *td);
474 static void throtl_pd_offline(struct blkg_policy_data *pd)
476 struct throtl_grp *tg = pd_to_tg(pd);
478 tg->bps[READ][LIMIT_LOW] = 0;
479 tg->bps[WRITE][LIMIT_LOW] = 0;
480 tg->iops[READ][LIMIT_LOW] = 0;
481 tg->iops[WRITE][LIMIT_LOW] = 0;
483 blk_throtl_update_limit_valid(tg->td);
485 if (!tg->td->limit_valid[tg->td->limit_index])
486 throtl_upgrade_state(tg->td);
489 static void throtl_pd_free(struct blkg_policy_data *pd)
491 struct throtl_grp *tg = pd_to_tg(pd);
493 del_timer_sync(&tg->service_queue.pending_timer);
497 static struct throtl_grp *
498 throtl_rb_first(struct throtl_service_queue *parent_sq)
500 /* Service tree is empty */
501 if (!parent_sq->nr_pending)
504 if (!parent_sq->first_pending)
505 parent_sq->first_pending = rb_first(&parent_sq->pending_tree);
507 if (parent_sq->first_pending)
508 return rb_entry_tg(parent_sq->first_pending);
513 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
519 static void throtl_rb_erase(struct rb_node *n,
520 struct throtl_service_queue *parent_sq)
522 if (parent_sq->first_pending == n)
523 parent_sq->first_pending = NULL;
524 rb_erase_init(n, &parent_sq->pending_tree);
525 --parent_sq->nr_pending;
528 static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
530 struct throtl_grp *tg;
532 tg = throtl_rb_first(parent_sq);
536 parent_sq->first_pending_disptime = tg->disptime;
539 static void tg_service_queue_add(struct throtl_grp *tg)
541 struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
542 struct rb_node **node = &parent_sq->pending_tree.rb_node;
543 struct rb_node *parent = NULL;
544 struct throtl_grp *__tg;
545 unsigned long key = tg->disptime;
548 while (*node != NULL) {
550 __tg = rb_entry_tg(parent);
552 if (time_before(key, __tg->disptime))
553 node = &parent->rb_left;
555 node = &parent->rb_right;
561 parent_sq->first_pending = &tg->rb_node;
563 rb_link_node(&tg->rb_node, parent, node);
564 rb_insert_color(&tg->rb_node, &parent_sq->pending_tree);
567 static void __throtl_enqueue_tg(struct throtl_grp *tg)
569 tg_service_queue_add(tg);
570 tg->flags |= THROTL_TG_PENDING;
571 tg->service_queue.parent_sq->nr_pending++;
574 static void throtl_enqueue_tg(struct throtl_grp *tg)
576 if (!(tg->flags & THROTL_TG_PENDING))
577 __throtl_enqueue_tg(tg);
580 static void __throtl_dequeue_tg(struct throtl_grp *tg)
582 throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
583 tg->flags &= ~THROTL_TG_PENDING;
586 static void throtl_dequeue_tg(struct throtl_grp *tg)
588 if (tg->flags & THROTL_TG_PENDING)
589 __throtl_dequeue_tg(tg);
592 /* Call with queue lock held */
593 static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
594 unsigned long expires)
596 unsigned long max_expire = jiffies + 8 * sq_to_tg(sq)->td->throtl_slice;
599 * Since we are adjusting the throttle limit dynamically, the sleep
600 * time calculated according to previous limit might be invalid. It's
601 * possible the cgroup sleep time is very long and no other cgroups
602 * have IO running so notify the limit changes. Make sure the cgroup
603 * doesn't sleep too long to avoid the missed notification.
605 if (time_after(expires, max_expire))
606 expires = max_expire;
607 mod_timer(&sq->pending_timer, expires);
608 throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
609 expires - jiffies, jiffies);
613 * throtl_schedule_next_dispatch - schedule the next dispatch cycle
614 * @sq: the service_queue to schedule dispatch for
615 * @force: force scheduling
617 * Arm @sq->pending_timer so that the next dispatch cycle starts on the
618 * dispatch time of the first pending child. Returns %true if either timer
619 * is armed or there's no pending child left. %false if the current
620 * dispatch window is still open and the caller should continue
623 * If @force is %true, the dispatch timer is always scheduled and this
624 * function is guaranteed to return %true. This is to be used when the
625 * caller can't dispatch itself and needs to invoke pending_timer
626 * unconditionally. Note that forced scheduling is likely to induce short
627 * delay before dispatch starts even if @sq->first_pending_disptime is not
628 * in the future and thus shouldn't be used in hot paths.
630 static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
633 /* any pending children left? */
637 update_min_dispatch_time(sq);
639 /* is the next dispatch time in the future? */
640 if (force || time_after(sq->first_pending_disptime, jiffies)) {
641 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
645 /* tell the caller to continue dispatching */
649 static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
650 bool rw, unsigned long start)
652 tg->bytes_disp[rw] = 0;
656 * Previous slice has expired. We must have trimmed it after last
657 * bio dispatch. That means since start of last slice, we never used
658 * that bandwidth. Do try to make use of that bandwidth while giving
661 if (time_after_eq(start, tg->slice_start[rw]))
662 tg->slice_start[rw] = start;
664 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
665 throtl_log(&tg->service_queue,
666 "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
667 rw == READ ? 'R' : 'W', tg->slice_start[rw],
668 tg->slice_end[rw], jiffies);
671 static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
673 tg->bytes_disp[rw] = 0;
675 tg->slice_start[rw] = jiffies;
676 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
677 throtl_log(&tg->service_queue,
678 "[%c] new slice start=%lu end=%lu jiffies=%lu",
679 rw == READ ? 'R' : 'W', tg->slice_start[rw],
680 tg->slice_end[rw], jiffies);
683 static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
684 unsigned long jiffy_end)
686 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
689 static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
690 unsigned long jiffy_end)
692 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
693 throtl_log(&tg->service_queue,
694 "[%c] extend slice start=%lu end=%lu jiffies=%lu",
695 rw == READ ? 'R' : 'W', tg->slice_start[rw],
696 tg->slice_end[rw], jiffies);
699 /* Determine if previously allocated or extended slice is complete or not */
700 static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
702 if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
708 /* Trim the used slices and adjust slice start accordingly */
709 static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
711 unsigned long nr_slices, time_elapsed, io_trim;
714 BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
717 * If bps are unlimited (-1), then time slice don't get
718 * renewed. Don't try to trim the slice if slice is used. A new
719 * slice will start when appropriate.
721 if (throtl_slice_used(tg, rw))
725 * A bio has been dispatched. Also adjust slice_end. It might happen
726 * that initially cgroup limit was very low resulting in high
727 * slice_end, but later limit was bumped up and bio was dispached
728 * sooner, then we need to reduce slice_end. A high bogus slice_end
729 * is bad because it does not allow new slice to start.
732 throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
734 time_elapsed = jiffies - tg->slice_start[rw];
736 nr_slices = time_elapsed / tg->td->throtl_slice;
740 tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
744 io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
747 if (!bytes_trim && !io_trim)
750 if (tg->bytes_disp[rw] >= bytes_trim)
751 tg->bytes_disp[rw] -= bytes_trim;
753 tg->bytes_disp[rw] = 0;
755 if (tg->io_disp[rw] >= io_trim)
756 tg->io_disp[rw] -= io_trim;
760 tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
762 throtl_log(&tg->service_queue,
763 "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
764 rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
765 tg->slice_start[rw], tg->slice_end[rw], jiffies);
768 static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
771 bool rw = bio_data_dir(bio);
772 unsigned int io_allowed;
773 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
776 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
778 /* Slice has just started. Consider one slice interval */
780 jiffy_elapsed_rnd = tg->td->throtl_slice;
782 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
785 * jiffy_elapsed_rnd should not be a big value as minimum iops can be
786 * 1 then at max jiffy elapsed should be equivalent of 1 second as we
787 * will allow dispatch after 1 second and after that slice should
791 tmp = (u64)tg_iops_limit(tg, rw) * jiffy_elapsed_rnd;
795 io_allowed = UINT_MAX;
799 if (tg->io_disp[rw] + 1 <= io_allowed) {
805 /* Calc approx time to dispatch */
806 jiffy_wait = ((tg->io_disp[rw] + 1) * HZ) / tg_iops_limit(tg, rw) + 1;
808 if (jiffy_wait > jiffy_elapsed)
809 jiffy_wait = jiffy_wait - jiffy_elapsed;
818 static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
821 bool rw = bio_data_dir(bio);
822 u64 bytes_allowed, extra_bytes, tmp;
823 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
825 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
827 /* Slice has just started. Consider one slice interval */
829 jiffy_elapsed_rnd = tg->td->throtl_slice;
831 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
833 tmp = tg_bps_limit(tg, rw) * jiffy_elapsed_rnd;
837 if (tg->bytes_disp[rw] + bio->bi_iter.bi_size <= bytes_allowed) {
843 /* Calc approx time to dispatch */
844 extra_bytes = tg->bytes_disp[rw] + bio->bi_iter.bi_size - bytes_allowed;
845 jiffy_wait = div64_u64(extra_bytes * HZ, tg_bps_limit(tg, rw));
851 * This wait time is without taking into consideration the rounding
852 * up we did. Add that time also.
854 jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
861 * Returns whether one can dispatch a bio or not. Also returns approx number
862 * of jiffies to wait before this bio is with-in IO rate and can be dispatched
864 static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
867 bool rw = bio_data_dir(bio);
868 unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
871 * Currently whole state machine of group depends on first bio
872 * queued in the group bio list. So one should not be calling
873 * this function with a different bio if there are other bios
876 BUG_ON(tg->service_queue.nr_queued[rw] &&
877 bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
879 /* If tg->bps = -1, then BW is unlimited */
880 if (tg_bps_limit(tg, rw) == U64_MAX &&
881 tg_iops_limit(tg, rw) == UINT_MAX) {
888 * If previous slice expired, start a new one otherwise renew/extend
889 * existing slice to make sure it is at least throtl_slice interval
890 * long since now. New slice is started only for empty throttle group.
891 * If there is queued bio, that means there should be an active
892 * slice and it should be extended instead.
894 if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
895 throtl_start_new_slice(tg, rw);
897 if (time_before(tg->slice_end[rw],
898 jiffies + tg->td->throtl_slice))
899 throtl_extend_slice(tg, rw,
900 jiffies + tg->td->throtl_slice);
903 if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
904 tg_with_in_iops_limit(tg, bio, &iops_wait)) {
910 max_wait = max(bps_wait, iops_wait);
915 if (time_before(tg->slice_end[rw], jiffies + max_wait))
916 throtl_extend_slice(tg, rw, jiffies + max_wait);
921 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
923 bool rw = bio_data_dir(bio);
925 /* Charge the bio to the group */
926 tg->bytes_disp[rw] += bio->bi_iter.bi_size;
928 tg->last_bytes_disp[rw] += bio->bi_iter.bi_size;
929 tg->last_io_disp[rw]++;
932 * BIO_THROTTLED is used to prevent the same bio to be throttled
933 * more than once as a throttled bio will go through blk-throtl the
934 * second time when it eventually gets issued. Set it when a bio
935 * is being charged to a tg.
937 if (!bio_flagged(bio, BIO_THROTTLED))
938 bio_set_flag(bio, BIO_THROTTLED);
942 * throtl_add_bio_tg - add a bio to the specified throtl_grp
945 * @tg: the target throtl_grp
947 * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
948 * tg->qnode_on_self[] is used.
950 static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
951 struct throtl_grp *tg)
953 struct throtl_service_queue *sq = &tg->service_queue;
954 bool rw = bio_data_dir(bio);
957 qn = &tg->qnode_on_self[rw];
960 * If @tg doesn't currently have any bios queued in the same
961 * direction, queueing @bio can change when @tg should be
962 * dispatched. Mark that @tg was empty. This is automatically
963 * cleaered on the next tg_update_disptime().
965 if (!sq->nr_queued[rw])
966 tg->flags |= THROTL_TG_WAS_EMPTY;
968 throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
971 throtl_enqueue_tg(tg);
974 static void tg_update_disptime(struct throtl_grp *tg)
976 struct throtl_service_queue *sq = &tg->service_queue;
977 unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
980 bio = throtl_peek_queued(&sq->queued[READ]);
982 tg_may_dispatch(tg, bio, &read_wait);
984 bio = throtl_peek_queued(&sq->queued[WRITE]);
986 tg_may_dispatch(tg, bio, &write_wait);
988 min_wait = min(read_wait, write_wait);
989 disptime = jiffies + min_wait;
991 /* Update dispatch time */
992 throtl_dequeue_tg(tg);
993 tg->disptime = disptime;
994 throtl_enqueue_tg(tg);
996 /* see throtl_add_bio_tg() */
997 tg->flags &= ~THROTL_TG_WAS_EMPTY;
1000 static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
1001 struct throtl_grp *parent_tg, bool rw)
1003 if (throtl_slice_used(parent_tg, rw)) {
1004 throtl_start_new_slice_with_credit(parent_tg, rw,
1005 child_tg->slice_start[rw]);
1010 static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
1012 struct throtl_service_queue *sq = &tg->service_queue;
1013 struct throtl_service_queue *parent_sq = sq->parent_sq;
1014 struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
1015 struct throtl_grp *tg_to_put = NULL;
1019 * @bio is being transferred from @tg to @parent_sq. Popping a bio
1020 * from @tg may put its reference and @parent_sq might end up
1021 * getting released prematurely. Remember the tg to put and put it
1022 * after @bio is transferred to @parent_sq.
1024 bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
1025 sq->nr_queued[rw]--;
1027 throtl_charge_bio(tg, bio);
1030 * If our parent is another tg, we just need to transfer @bio to
1031 * the parent using throtl_add_bio_tg(). If our parent is
1032 * @td->service_queue, @bio is ready to be issued. Put it on its
1033 * bio_lists[] and decrease total number queued. The caller is
1034 * responsible for issuing these bios.
1037 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
1038 start_parent_slice_with_credit(tg, parent_tg, rw);
1040 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1041 &parent_sq->queued[rw]);
1042 BUG_ON(tg->td->nr_queued[rw] <= 0);
1043 tg->td->nr_queued[rw]--;
1046 throtl_trim_slice(tg, rw);
1049 blkg_put(tg_to_blkg(tg_to_put));
1052 static int throtl_dispatch_tg(struct throtl_grp *tg)
1054 struct throtl_service_queue *sq = &tg->service_queue;
1055 unsigned int nr_reads = 0, nr_writes = 0;
1056 unsigned int max_nr_reads = throtl_grp_quantum*3/4;
1057 unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
1060 /* Try to dispatch 75% READS and 25% WRITES */
1062 while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
1063 tg_may_dispatch(tg, bio, NULL)) {
1065 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1068 if (nr_reads >= max_nr_reads)
1072 while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
1073 tg_may_dispatch(tg, bio, NULL)) {
1075 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1078 if (nr_writes >= max_nr_writes)
1082 return nr_reads + nr_writes;
1085 static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
1087 unsigned int nr_disp = 0;
1090 struct throtl_grp *tg = throtl_rb_first(parent_sq);
1091 struct throtl_service_queue *sq = &tg->service_queue;
1096 if (time_before(jiffies, tg->disptime))
1099 throtl_dequeue_tg(tg);
1101 nr_disp += throtl_dispatch_tg(tg);
1103 if (sq->nr_queued[0] || sq->nr_queued[1])
1104 tg_update_disptime(tg);
1106 if (nr_disp >= throtl_quantum)
1113 static bool throtl_can_upgrade(struct throtl_data *td,
1114 struct throtl_grp *this_tg);
1116 * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1117 * @arg: the throtl_service_queue being serviced
1119 * This timer is armed when a child throtl_grp with active bio's become
1120 * pending and queued on the service_queue's pending_tree and expires when
1121 * the first child throtl_grp should be dispatched. This function
1122 * dispatches bio's from the children throtl_grps to the parent
1125 * If the parent's parent is another throtl_grp, dispatching is propagated
1126 * by either arming its pending_timer or repeating dispatch directly. If
1127 * the top-level service_tree is reached, throtl_data->dispatch_work is
1128 * kicked so that the ready bio's are issued.
1130 static void throtl_pending_timer_fn(unsigned long arg)
1132 struct throtl_service_queue *sq = (void *)arg;
1133 struct throtl_grp *tg = sq_to_tg(sq);
1134 struct throtl_data *td = sq_to_td(sq);
1135 struct request_queue *q = td->queue;
1136 struct throtl_service_queue *parent_sq;
1140 spin_lock_irq(q->queue_lock);
1141 if (throtl_can_upgrade(td, NULL))
1142 throtl_upgrade_state(td);
1145 parent_sq = sq->parent_sq;
1149 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
1150 sq->nr_queued[READ] + sq->nr_queued[WRITE],
1151 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1153 ret = throtl_select_dispatch(sq);
1155 throtl_log(sq, "bios disp=%u", ret);
1159 if (throtl_schedule_next_dispatch(sq, false))
1162 /* this dispatch windows is still open, relax and repeat */
1163 spin_unlock_irq(q->queue_lock);
1165 spin_lock_irq(q->queue_lock);
1172 /* @parent_sq is another throl_grp, propagate dispatch */
1173 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1174 tg_update_disptime(tg);
1175 if (!throtl_schedule_next_dispatch(parent_sq, false)) {
1176 /* window is already open, repeat dispatching */
1183 /* reached the top-level, queue issueing */
1184 queue_work(kthrotld_workqueue, &td->dispatch_work);
1187 spin_unlock_irq(q->queue_lock);
1191 * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1192 * @work: work item being executed
1194 * This function is queued for execution when bio's reach the bio_lists[]
1195 * of throtl_data->service_queue. Those bio's are ready and issued by this
1198 static void blk_throtl_dispatch_work_fn(struct work_struct *work)
1200 struct throtl_data *td = container_of(work, struct throtl_data,
1202 struct throtl_service_queue *td_sq = &td->service_queue;
1203 struct request_queue *q = td->queue;
1204 struct bio_list bio_list_on_stack;
1206 struct blk_plug plug;
1209 bio_list_init(&bio_list_on_stack);
1211 spin_lock_irq(q->queue_lock);
1212 for (rw = READ; rw <= WRITE; rw++)
1213 while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
1214 bio_list_add(&bio_list_on_stack, bio);
1215 spin_unlock_irq(q->queue_lock);
1217 if (!bio_list_empty(&bio_list_on_stack)) {
1218 blk_start_plug(&plug);
1219 while((bio = bio_list_pop(&bio_list_on_stack)))
1220 generic_make_request(bio);
1221 blk_finish_plug(&plug);
1225 static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1228 struct throtl_grp *tg = pd_to_tg(pd);
1229 u64 v = *(u64 *)((void *)tg + off);
1233 return __blkg_prfill_u64(sf, pd, v);
1236 static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1239 struct throtl_grp *tg = pd_to_tg(pd);
1240 unsigned int v = *(unsigned int *)((void *)tg + off);
1244 return __blkg_prfill_u64(sf, pd, v);
1247 static int tg_print_conf_u64(struct seq_file *sf, void *v)
1249 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1250 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1254 static int tg_print_conf_uint(struct seq_file *sf, void *v)
1256 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1257 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1261 static void tg_conf_updated(struct throtl_grp *tg)
1263 struct throtl_service_queue *sq = &tg->service_queue;
1264 struct cgroup_subsys_state *pos_css;
1265 struct blkcg_gq *blkg;
1267 throtl_log(&tg->service_queue,
1268 "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
1269 tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1270 tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
1273 * Update has_rules[] flags for the updated tg's subtree. A tg is
1274 * considered to have rules if either the tg itself or any of its
1275 * ancestors has rules. This identifies groups without any
1276 * restrictions in the whole hierarchy and allows them to bypass
1279 blkg_for_each_descendant_pre(blkg, pos_css, tg_to_blkg(tg))
1280 tg_update_has_rules(blkg_to_tg(blkg));
1283 * We're already holding queue_lock and know @tg is valid. Let's
1284 * apply the new config directly.
1286 * Restart the slices for both READ and WRITES. It might happen
1287 * that a group's limit are dropped suddenly and we don't want to
1288 * account recently dispatched IO with new low rate.
1290 throtl_start_new_slice(tg, 0);
1291 throtl_start_new_slice(tg, 1);
1293 if (tg->flags & THROTL_TG_PENDING) {
1294 tg_update_disptime(tg);
1295 throtl_schedule_next_dispatch(sq->parent_sq, true);
1299 static ssize_t tg_set_conf(struct kernfs_open_file *of,
1300 char *buf, size_t nbytes, loff_t off, bool is_u64)
1302 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1303 struct blkg_conf_ctx ctx;
1304 struct throtl_grp *tg;
1308 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1313 if (sscanf(ctx.body, "%llu", &v) != 1)
1318 tg = blkg_to_tg(ctx.blkg);
1321 *(u64 *)((void *)tg + of_cft(of)->private) = v;
1323 *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
1325 tg_conf_updated(tg);
1328 blkg_conf_finish(&ctx);
1329 return ret ?: nbytes;
1332 static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1333 char *buf, size_t nbytes, loff_t off)
1335 return tg_set_conf(of, buf, nbytes, off, true);
1338 static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1339 char *buf, size_t nbytes, loff_t off)
1341 return tg_set_conf(of, buf, nbytes, off, false);
1344 static struct cftype throtl_legacy_files[] = {
1346 .name = "throttle.read_bps_device",
1347 .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
1348 .seq_show = tg_print_conf_u64,
1349 .write = tg_set_conf_u64,
1352 .name = "throttle.write_bps_device",
1353 .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
1354 .seq_show = tg_print_conf_u64,
1355 .write = tg_set_conf_u64,
1358 .name = "throttle.read_iops_device",
1359 .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
1360 .seq_show = tg_print_conf_uint,
1361 .write = tg_set_conf_uint,
1364 .name = "throttle.write_iops_device",
1365 .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
1366 .seq_show = tg_print_conf_uint,
1367 .write = tg_set_conf_uint,
1370 .name = "throttle.io_service_bytes",
1371 .private = (unsigned long)&blkcg_policy_throtl,
1372 .seq_show = blkg_print_stat_bytes,
1375 .name = "throttle.io_serviced",
1376 .private = (unsigned long)&blkcg_policy_throtl,
1377 .seq_show = blkg_print_stat_ios,
1382 static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
1385 struct throtl_grp *tg = pd_to_tg(pd);
1386 const char *dname = blkg_dev_name(pd->blkg);
1387 char bufs[4][21] = { "max", "max", "max", "max" };
1389 unsigned int iops_dft;
1394 if (off == LIMIT_LOW) {
1399 iops_dft = UINT_MAX;
1402 if (tg->bps_conf[READ][off] == bps_dft &&
1403 tg->bps_conf[WRITE][off] == bps_dft &&
1404 tg->iops_conf[READ][off] == iops_dft &&
1405 tg->iops_conf[WRITE][off] == iops_dft)
1408 if (tg->bps_conf[READ][off] != bps_dft)
1409 snprintf(bufs[0], sizeof(bufs[0]), "%llu",
1410 tg->bps_conf[READ][off]);
1411 if (tg->bps_conf[WRITE][off] != bps_dft)
1412 snprintf(bufs[1], sizeof(bufs[1]), "%llu",
1413 tg->bps_conf[WRITE][off]);
1414 if (tg->iops_conf[READ][off] != iops_dft)
1415 snprintf(bufs[2], sizeof(bufs[2]), "%u",
1416 tg->iops_conf[READ][off]);
1417 if (tg->iops_conf[WRITE][off] != iops_dft)
1418 snprintf(bufs[3], sizeof(bufs[3]), "%u",
1419 tg->iops_conf[WRITE][off]);
1421 seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s\n",
1422 dname, bufs[0], bufs[1], bufs[2], bufs[3]);
1426 static int tg_print_limit(struct seq_file *sf, void *v)
1428 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
1429 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1433 static ssize_t tg_set_limit(struct kernfs_open_file *of,
1434 char *buf, size_t nbytes, loff_t off)
1436 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1437 struct blkg_conf_ctx ctx;
1438 struct throtl_grp *tg;
1441 int index = of_cft(of)->private;
1443 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1447 tg = blkg_to_tg(ctx.blkg);
1449 v[0] = tg->bps_conf[READ][index];
1450 v[1] = tg->bps_conf[WRITE][index];
1451 v[2] = tg->iops_conf[READ][index];
1452 v[3] = tg->iops_conf[WRITE][index];
1455 char tok[27]; /* wiops=18446744073709551616 */
1460 if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
1469 if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
1477 if (!strcmp(tok, "rbps"))
1479 else if (!strcmp(tok, "wbps"))
1481 else if (!strcmp(tok, "riops"))
1482 v[2] = min_t(u64, val, UINT_MAX);
1483 else if (!strcmp(tok, "wiops"))
1484 v[3] = min_t(u64, val, UINT_MAX);
1489 tg->bps_conf[READ][index] = v[0];
1490 tg->bps_conf[WRITE][index] = v[1];
1491 tg->iops_conf[READ][index] = v[2];
1492 tg->iops_conf[WRITE][index] = v[3];
1494 if (index == LIMIT_MAX) {
1495 tg->bps[READ][index] = v[0];
1496 tg->bps[WRITE][index] = v[1];
1497 tg->iops[READ][index] = v[2];
1498 tg->iops[WRITE][index] = v[3];
1500 tg->bps[READ][LIMIT_LOW] = min(tg->bps_conf[READ][LIMIT_LOW],
1501 tg->bps_conf[READ][LIMIT_MAX]);
1502 tg->bps[WRITE][LIMIT_LOW] = min(tg->bps_conf[WRITE][LIMIT_LOW],
1503 tg->bps_conf[WRITE][LIMIT_MAX]);
1504 tg->iops[READ][LIMIT_LOW] = min(tg->iops_conf[READ][LIMIT_LOW],
1505 tg->iops_conf[READ][LIMIT_MAX]);
1506 tg->iops[WRITE][LIMIT_LOW] = min(tg->iops_conf[WRITE][LIMIT_LOW],
1507 tg->iops_conf[WRITE][LIMIT_MAX]);
1509 if (index == LIMIT_LOW) {
1510 blk_throtl_update_limit_valid(tg->td);
1511 if (tg->td->limit_valid[LIMIT_LOW])
1512 tg->td->limit_index = LIMIT_LOW;
1514 tg_conf_updated(tg);
1517 blkg_conf_finish(&ctx);
1518 return ret ?: nbytes;
1521 static struct cftype throtl_files[] = {
1522 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1525 .flags = CFTYPE_NOT_ON_ROOT,
1526 .seq_show = tg_print_limit,
1527 .write = tg_set_limit,
1528 .private = LIMIT_LOW,
1533 .flags = CFTYPE_NOT_ON_ROOT,
1534 .seq_show = tg_print_limit,
1535 .write = tg_set_limit,
1536 .private = LIMIT_MAX,
1541 static void throtl_shutdown_wq(struct request_queue *q)
1543 struct throtl_data *td = q->td;
1545 cancel_work_sync(&td->dispatch_work);
1548 static struct blkcg_policy blkcg_policy_throtl = {
1549 .dfl_cftypes = throtl_files,
1550 .legacy_cftypes = throtl_legacy_files,
1552 .pd_alloc_fn = throtl_pd_alloc,
1553 .pd_init_fn = throtl_pd_init,
1554 .pd_online_fn = throtl_pd_online,
1555 .pd_offline_fn = throtl_pd_offline,
1556 .pd_free_fn = throtl_pd_free,
1559 static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
1561 unsigned long rtime = jiffies, wtime = jiffies;
1563 if (tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW])
1564 rtime = tg->last_low_overflow_time[READ];
1565 if (tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
1566 wtime = tg->last_low_overflow_time[WRITE];
1567 return min(rtime, wtime);
1570 /* tg should not be an intermediate node */
1571 static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
1573 struct throtl_service_queue *parent_sq;
1574 struct throtl_grp *parent = tg;
1575 unsigned long ret = __tg_last_low_overflow_time(tg);
1578 parent_sq = parent->service_queue.parent_sq;
1579 parent = sq_to_tg(parent_sq);
1584 * The parent doesn't have low limit, it always reaches low
1585 * limit. Its overflow time is useless for children
1587 if (!parent->bps[READ][LIMIT_LOW] &&
1588 !parent->iops[READ][LIMIT_LOW] &&
1589 !parent->bps[WRITE][LIMIT_LOW] &&
1590 !parent->iops[WRITE][LIMIT_LOW])
1592 if (time_after(__tg_last_low_overflow_time(parent), ret))
1593 ret = __tg_last_low_overflow_time(parent);
1598 static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
1600 struct throtl_service_queue *sq = &tg->service_queue;
1601 bool read_limit, write_limit;
1604 * if cgroup reaches low limit (if low limit is 0, the cgroup always
1605 * reaches), it's ok to upgrade to next limit
1607 read_limit = tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW];
1608 write_limit = tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW];
1609 if (!read_limit && !write_limit)
1611 if (read_limit && sq->nr_queued[READ] &&
1612 (!write_limit || sq->nr_queued[WRITE]))
1614 if (write_limit && sq->nr_queued[WRITE] &&
1615 (!read_limit || sq->nr_queued[READ]))
1620 static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
1623 if (throtl_tg_can_upgrade(tg))
1625 tg = sq_to_tg(tg->service_queue.parent_sq);
1626 if (!tg || !tg_to_blkg(tg)->parent)
1632 static bool throtl_can_upgrade(struct throtl_data *td,
1633 struct throtl_grp *this_tg)
1635 struct cgroup_subsys_state *pos_css;
1636 struct blkcg_gq *blkg;
1638 if (td->limit_index != LIMIT_LOW)
1641 if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
1645 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1646 struct throtl_grp *tg = blkg_to_tg(blkg);
1650 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1652 if (!throtl_hierarchy_can_upgrade(tg)) {
1661 static void throtl_upgrade_state(struct throtl_data *td)
1663 struct cgroup_subsys_state *pos_css;
1664 struct blkcg_gq *blkg;
1666 td->limit_index = LIMIT_MAX;
1667 td->low_upgrade_time = jiffies;
1669 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1670 struct throtl_grp *tg = blkg_to_tg(blkg);
1671 struct throtl_service_queue *sq = &tg->service_queue;
1673 tg->disptime = jiffies - 1;
1674 throtl_select_dispatch(sq);
1675 throtl_schedule_next_dispatch(sq, false);
1678 throtl_select_dispatch(&td->service_queue);
1679 throtl_schedule_next_dispatch(&td->service_queue, false);
1680 queue_work(kthrotld_workqueue, &td->dispatch_work);
1683 static void throtl_downgrade_state(struct throtl_data *td, int new)
1685 td->limit_index = new;
1686 td->low_downgrade_time = jiffies;
1689 static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
1691 struct throtl_data *td = tg->td;
1692 unsigned long now = jiffies;
1695 * If cgroup is below low limit, consider downgrade and throttle other
1698 if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
1699 time_after_eq(now, tg_last_low_overflow_time(tg) +
1705 static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
1708 if (!throtl_tg_can_downgrade(tg))
1710 tg = sq_to_tg(tg->service_queue.parent_sq);
1711 if (!tg || !tg_to_blkg(tg)->parent)
1717 static void throtl_downgrade_check(struct throtl_grp *tg)
1721 unsigned long elapsed_time;
1722 unsigned long now = jiffies;
1724 if (tg->td->limit_index != LIMIT_MAX ||
1725 !tg->td->limit_valid[LIMIT_LOW])
1727 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1729 if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1732 elapsed_time = now - tg->last_check_time;
1733 tg->last_check_time = now;
1735 if (time_before(now, tg_last_low_overflow_time(tg) +
1736 tg->td->throtl_slice))
1739 if (tg->bps[READ][LIMIT_LOW]) {
1740 bps = tg->last_bytes_disp[READ] * HZ;
1741 do_div(bps, elapsed_time);
1742 if (bps >= tg->bps[READ][LIMIT_LOW])
1743 tg->last_low_overflow_time[READ] = now;
1746 if (tg->bps[WRITE][LIMIT_LOW]) {
1747 bps = tg->last_bytes_disp[WRITE] * HZ;
1748 do_div(bps, elapsed_time);
1749 if (bps >= tg->bps[WRITE][LIMIT_LOW])
1750 tg->last_low_overflow_time[WRITE] = now;
1753 if (tg->iops[READ][LIMIT_LOW]) {
1754 iops = tg->last_io_disp[READ] * HZ / elapsed_time;
1755 if (iops >= tg->iops[READ][LIMIT_LOW])
1756 tg->last_low_overflow_time[READ] = now;
1759 if (tg->iops[WRITE][LIMIT_LOW]) {
1760 iops = tg->last_io_disp[WRITE] * HZ / elapsed_time;
1761 if (iops >= tg->iops[WRITE][LIMIT_LOW])
1762 tg->last_low_overflow_time[WRITE] = now;
1766 * If cgroup is below low limit, consider downgrade and throttle other
1769 if (throtl_hierarchy_can_downgrade(tg))
1770 throtl_downgrade_state(tg->td, LIMIT_LOW);
1772 tg->last_bytes_disp[READ] = 0;
1773 tg->last_bytes_disp[WRITE] = 0;
1774 tg->last_io_disp[READ] = 0;
1775 tg->last_io_disp[WRITE] = 0;
1778 bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
1781 struct throtl_qnode *qn = NULL;
1782 struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
1783 struct throtl_service_queue *sq;
1784 bool rw = bio_data_dir(bio);
1785 bool throttled = false;
1787 WARN_ON_ONCE(!rcu_read_lock_held());
1789 /* see throtl_charge_bio() */
1790 if (bio_flagged(bio, BIO_THROTTLED) || !tg->has_rules[rw])
1793 spin_lock_irq(q->queue_lock);
1795 if (unlikely(blk_queue_bypass(q)))
1798 sq = &tg->service_queue;
1802 if (tg->last_low_overflow_time[rw] == 0)
1803 tg->last_low_overflow_time[rw] = jiffies;
1804 throtl_downgrade_check(tg);
1805 /* throtl is FIFO - if bios are already queued, should queue */
1806 if (sq->nr_queued[rw])
1809 /* if above limits, break to queue */
1810 if (!tg_may_dispatch(tg, bio, NULL)) {
1811 tg->last_low_overflow_time[rw] = jiffies;
1812 if (throtl_can_upgrade(tg->td, tg)) {
1813 throtl_upgrade_state(tg->td);
1819 /* within limits, let's charge and dispatch directly */
1820 throtl_charge_bio(tg, bio);
1823 * We need to trim slice even when bios are not being queued
1824 * otherwise it might happen that a bio is not queued for
1825 * a long time and slice keeps on extending and trim is not
1826 * called for a long time. Now if limits are reduced suddenly
1827 * we take into account all the IO dispatched so far at new
1828 * low rate and * newly queued IO gets a really long dispatch
1831 * So keep on trimming slice even if bio is not queued.
1833 throtl_trim_slice(tg, rw);
1836 * @bio passed through this layer without being throttled.
1837 * Climb up the ladder. If we''re already at the top, it
1838 * can be executed directly.
1840 qn = &tg->qnode_on_parent[rw];
1847 /* out-of-limit, queue to @tg */
1848 throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
1849 rw == READ ? 'R' : 'W',
1850 tg->bytes_disp[rw], bio->bi_iter.bi_size,
1851 tg_bps_limit(tg, rw),
1852 tg->io_disp[rw], tg_iops_limit(tg, rw),
1853 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1855 tg->last_low_overflow_time[rw] = jiffies;
1857 bio_associate_current(bio);
1858 tg->td->nr_queued[rw]++;
1859 throtl_add_bio_tg(bio, qn, tg);
1863 * Update @tg's dispatch time and force schedule dispatch if @tg
1864 * was empty before @bio. The forced scheduling isn't likely to
1865 * cause undue delay as @bio is likely to be dispatched directly if
1866 * its @tg's disptime is not in the future.
1868 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1869 tg_update_disptime(tg);
1870 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
1874 spin_unlock_irq(q->queue_lock);
1877 * As multiple blk-throtls may stack in the same issue path, we
1878 * don't want bios to leave with the flag set. Clear the flag if
1882 bio_clear_flag(bio, BIO_THROTTLED);
1887 * Dispatch all bios from all children tg's queued on @parent_sq. On
1888 * return, @parent_sq is guaranteed to not have any active children tg's
1889 * and all bios from previously active tg's are on @parent_sq->bio_lists[].
1891 static void tg_drain_bios(struct throtl_service_queue *parent_sq)
1893 struct throtl_grp *tg;
1895 while ((tg = throtl_rb_first(parent_sq))) {
1896 struct throtl_service_queue *sq = &tg->service_queue;
1899 throtl_dequeue_tg(tg);
1901 while ((bio = throtl_peek_queued(&sq->queued[READ])))
1902 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1903 while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
1904 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1909 * blk_throtl_drain - drain throttled bios
1910 * @q: request_queue to drain throttled bios for
1912 * Dispatch all currently throttled bios on @q through ->make_request_fn().
1914 void blk_throtl_drain(struct request_queue *q)
1915 __releases(q->queue_lock) __acquires(q->queue_lock)
1917 struct throtl_data *td = q->td;
1918 struct blkcg_gq *blkg;
1919 struct cgroup_subsys_state *pos_css;
1923 queue_lockdep_assert_held(q);
1927 * Drain each tg while doing post-order walk on the blkg tree, so
1928 * that all bios are propagated to td->service_queue. It'd be
1929 * better to walk service_queue tree directly but blkg walk is
1932 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
1933 tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
1935 /* finally, transfer bios from top-level tg's into the td */
1936 tg_drain_bios(&td->service_queue);
1939 spin_unlock_irq(q->queue_lock);
1941 /* all bios now should be in td->service_queue, issue them */
1942 for (rw = READ; rw <= WRITE; rw++)
1943 while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
1945 generic_make_request(bio);
1947 spin_lock_irq(q->queue_lock);
1950 int blk_throtl_init(struct request_queue *q)
1952 struct throtl_data *td;
1955 td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
1959 INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
1960 throtl_service_queue_init(&td->service_queue);
1964 td->throtl_slice = DFL_THROTL_SLICE;
1966 td->limit_valid[LIMIT_MAX] = true;
1967 td->limit_index = LIMIT_MAX;
1968 td->low_upgrade_time = jiffies;
1969 td->low_downgrade_time = jiffies;
1970 /* activate policy */
1971 ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
1977 void blk_throtl_exit(struct request_queue *q)
1980 throtl_shutdown_wq(q);
1981 blkcg_deactivate_policy(q, &blkcg_policy_throtl);
1985 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1986 ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
1990 return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
1993 ssize_t blk_throtl_sample_time_store(struct request_queue *q,
1994 const char *page, size_t count)
2001 if (kstrtoul(page, 10, &v))
2003 t = msecs_to_jiffies(v);
2004 if (t == 0 || t > MAX_THROTL_SLICE)
2006 q->td->throtl_slice = t;
2011 static int __init throtl_init(void)
2013 kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2014 if (!kthrotld_workqueue)
2015 panic("Failed to create kthrotld\n");
2017 return blkcg_policy_register(&blkcg_policy_throtl);
2020 module_init(throtl_init);