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 static unsigned long throtl_slice = HZ/10; /* 100 ms */
24 static struct blkcg_policy blkcg_policy_throtl;
26 /* A workqueue to queue throttle related work */
27 static struct workqueue_struct *kthrotld_workqueue;
30 * To implement hierarchical throttling, throtl_grps form a tree and bios
31 * are dispatched upwards level by level until they reach the top and get
32 * issued. When dispatching bios from the children and local group at each
33 * level, if the bios are dispatched into a single bio_list, there's a risk
34 * of a local or child group which can queue many bios at once filling up
35 * the list starving others.
37 * To avoid such starvation, dispatched bios are queued separately
38 * according to where they came from. When they are again dispatched to
39 * the parent, they're popped in round-robin order so that no single source
40 * hogs the dispatch window.
42 * throtl_qnode is used to keep the queued bios separated by their sources.
43 * Bios are queued to throtl_qnode which in turn is queued to
44 * throtl_service_queue and then dispatched in round-robin order.
46 * It's also used to track the reference counts on blkg's. A qnode always
47 * belongs to a throtl_grp and gets queued on itself or the parent, so
48 * incrementing the reference of the associated throtl_grp when a qnode is
49 * queued and decrementing when dequeued is enough to keep the whole blkg
50 * tree pinned while bios are in flight.
53 struct list_head node; /* service_queue->queued[] */
54 struct bio_list bios; /* queued bios */
55 struct throtl_grp *tg; /* tg this qnode belongs to */
58 struct throtl_service_queue {
59 struct throtl_service_queue *parent_sq; /* the parent service_queue */
62 * Bios queued directly to this service_queue or dispatched from
63 * children throtl_grp's.
65 struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
66 unsigned int nr_queued[2]; /* number of queued bios */
69 * RB tree of active children throtl_grp's, which are sorted by
72 struct rb_root pending_tree; /* RB tree of active tgs */
73 struct rb_node *first_pending; /* first node in the tree */
74 unsigned int nr_pending; /* # queued in the tree */
75 unsigned long first_pending_disptime; /* disptime of the first tg */
76 struct timer_list pending_timer; /* fires on first_pending_disptime */
80 THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
81 THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
84 #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
86 /* Per-cpu group stats */
88 /* total bytes transferred */
89 struct blkg_rwstat service_bytes;
90 /* total IOs serviced, post merge */
91 struct blkg_rwstat serviced;
95 /* must be the first member */
96 struct blkg_policy_data pd;
98 /* active throtl group service_queue member */
99 struct rb_node rb_node;
101 /* throtl_data this group belongs to */
102 struct throtl_data *td;
104 /* this group's service queue */
105 struct throtl_service_queue service_queue;
108 * qnode_on_self is used when bios are directly queued to this
109 * throtl_grp so that local bios compete fairly with bios
110 * dispatched from children. qnode_on_parent is used when bios are
111 * dispatched from this throtl_grp into its parent and will compete
112 * with the sibling qnode_on_parents and the parent's
115 struct throtl_qnode qnode_on_self[2];
116 struct throtl_qnode qnode_on_parent[2];
119 * Dispatch time in jiffies. This is the estimated time when group
120 * will unthrottle and is ready to dispatch more bio. It is used as
121 * key to sort active groups in service tree.
123 unsigned long disptime;
127 /* are there any throtl rules between this group and td? */
130 /* bytes per second rate limits */
134 unsigned int iops[2];
136 /* Number of bytes disptached in current slice */
137 uint64_t bytes_disp[2];
138 /* Number of bio's dispatched in current slice */
139 unsigned int io_disp[2];
141 /* When did we start a new slice */
142 unsigned long slice_start[2];
143 unsigned long slice_end[2];
145 /* Per cpu stats pointer */
146 struct tg_stats_cpu __percpu *stats_cpu;
151 /* service tree for active throtl groups */
152 struct throtl_service_queue service_queue;
154 struct request_queue *queue;
156 /* Total Number of queued bios on READ and WRITE lists */
157 unsigned int nr_queued[2];
160 * number of total undestroyed groups
162 unsigned int nr_undestroyed_grps;
164 /* Work for dispatching throttled bios */
165 struct work_struct dispatch_work;
168 static void throtl_pending_timer_fn(unsigned long arg);
170 static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
172 return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
175 static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
177 return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
180 static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
182 return pd_to_blkg(&tg->pd);
186 * sq_to_tg - return the throl_grp the specified service queue belongs to
187 * @sq: the throtl_service_queue of interest
189 * Return the throtl_grp @sq belongs to. If @sq is the top-level one
190 * embedded in throtl_data, %NULL is returned.
192 static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
194 if (sq && sq->parent_sq)
195 return container_of(sq, struct throtl_grp, service_queue);
201 * sq_to_td - return throtl_data the specified service queue belongs to
202 * @sq: the throtl_service_queue of interest
204 * A service_queue can be embeded in either a throtl_grp or throtl_data.
205 * Determine the associated throtl_data accordingly and return it.
207 static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
209 struct throtl_grp *tg = sq_to_tg(sq);
214 return container_of(sq, struct throtl_data, service_queue);
218 * throtl_log - log debug message via blktrace
219 * @sq: the service_queue being reported
220 * @fmt: printf format string
223 * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
224 * throtl_grp; otherwise, just "throtl".
226 * TODO: this should be made a function and name formatting should happen
227 * after testing whether blktrace is enabled.
229 #define throtl_log(sq, fmt, args...) do { \
230 struct throtl_grp *__tg = sq_to_tg((sq)); \
231 struct throtl_data *__td = sq_to_td((sq)); \
237 blkg_path(tg_to_blkg(__tg), __pbuf, sizeof(__pbuf)); \
238 blk_add_trace_msg(__td->queue, "throtl %s " fmt, __pbuf, ##args); \
240 blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
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 = list_first_entry(queued, struct throtl_qnode, node);
280 if (list_empty(queued))
283 bio = bio_list_peek(&qn->bios);
289 * throtl_pop_queued - pop the first bio form a qnode list
290 * @queued: the qnode list to pop a bio from
291 * @tg_to_put: optional out argument for throtl_grp to put
293 * Pop the first bio from the qnode list @queued. After popping, the first
294 * qnode is removed from @queued if empty or moved to the end of @queued so
295 * that the popping order is round-robin.
297 * When the first qnode is removed, its associated throtl_grp should be put
298 * too. If @tg_to_put is NULL, this function automatically puts it;
299 * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
300 * responsible for putting it.
302 static struct bio *throtl_pop_queued(struct list_head *queued,
303 struct throtl_grp **tg_to_put)
305 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
308 if (list_empty(queued))
311 bio = bio_list_pop(&qn->bios);
314 if (bio_list_empty(&qn->bios)) {
315 list_del_init(&qn->node);
319 blkg_put(tg_to_blkg(qn->tg));
321 list_move_tail(&qn->node, queued);
327 /* init a service_queue, assumes the caller zeroed it */
328 static void throtl_service_queue_init(struct throtl_service_queue *sq)
330 INIT_LIST_HEAD(&sq->queued[0]);
331 INIT_LIST_HEAD(&sq->queued[1]);
332 sq->pending_tree = RB_ROOT;
333 setup_timer(&sq->pending_timer, throtl_pending_timer_fn,
337 static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
339 struct throtl_grp *tg;
342 tg = kzalloc_node(sizeof(*tg), gfp, node);
346 tg->stats_cpu = alloc_percpu_gfp(struct tg_stats_cpu, gfp);
347 if (!tg->stats_cpu) {
352 throtl_service_queue_init(&tg->service_queue);
354 for (rw = READ; rw <= WRITE; rw++) {
355 throtl_qnode_init(&tg->qnode_on_self[rw], tg);
356 throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
359 RB_CLEAR_NODE(&tg->rb_node);
363 tg->iops[WRITE] = -1;
365 for_each_possible_cpu(cpu) {
366 struct tg_stats_cpu *stats_cpu = per_cpu_ptr(tg->stats_cpu, cpu);
368 blkg_rwstat_init(&stats_cpu->service_bytes);
369 blkg_rwstat_init(&stats_cpu->serviced);
375 static void throtl_pd_init(struct blkg_policy_data *pd)
377 struct throtl_grp *tg = pd_to_tg(pd);
378 struct blkcg_gq *blkg = tg_to_blkg(tg);
379 struct throtl_data *td = blkg->q->td;
380 struct throtl_service_queue *sq = &tg->service_queue;
383 * If on the default hierarchy, we switch to properly hierarchical
384 * behavior where limits on a given throtl_grp are applied to the
385 * whole subtree rather than just the group itself. e.g. If 16M
386 * read_bps limit is set on the root group, the whole system can't
387 * exceed 16M for the device.
389 * If not on the default hierarchy, the broken flat hierarchy
390 * behavior is retained where all throtl_grps are treated as if
391 * they're all separate root groups right below throtl_data.
392 * Limits of a group don't interact with limits of other groups
393 * regardless of the position of the group in the hierarchy.
395 sq->parent_sq = &td->service_queue;
396 if (cgroup_on_dfl(blkg->blkcg->css.cgroup) && blkg->parent)
397 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
402 * Set has_rules[] if @tg or any of its parents have limits configured.
403 * This doesn't require walking up to the top of the hierarchy as the
404 * parent's has_rules[] is guaranteed to be correct.
406 static void tg_update_has_rules(struct throtl_grp *tg)
408 struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
411 for (rw = READ; rw <= WRITE; rw++)
412 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
413 (tg->bps[rw] != -1 || tg->iops[rw] != -1);
416 static void throtl_pd_online(struct blkg_policy_data *pd)
419 * We don't want new groups to escape the limits of its ancestors.
420 * Update has_rules[] after a new group is brought online.
422 tg_update_has_rules(pd_to_tg(pd));
425 static void throtl_pd_free(struct blkg_policy_data *pd)
427 struct throtl_grp *tg = pd_to_tg(pd);
429 del_timer_sync(&tg->service_queue.pending_timer);
430 free_percpu(tg->stats_cpu);
434 static void throtl_pd_reset_stats(struct blkg_policy_data *pd)
436 struct throtl_grp *tg = pd_to_tg(pd);
439 for_each_possible_cpu(cpu) {
440 struct tg_stats_cpu *sc = per_cpu_ptr(tg->stats_cpu, cpu);
442 blkg_rwstat_reset(&sc->service_bytes);
443 blkg_rwstat_reset(&sc->serviced);
447 static struct throtl_grp *
448 throtl_rb_first(struct throtl_service_queue *parent_sq)
450 /* Service tree is empty */
451 if (!parent_sq->nr_pending)
454 if (!parent_sq->first_pending)
455 parent_sq->first_pending = rb_first(&parent_sq->pending_tree);
457 if (parent_sq->first_pending)
458 return rb_entry_tg(parent_sq->first_pending);
463 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
469 static void throtl_rb_erase(struct rb_node *n,
470 struct throtl_service_queue *parent_sq)
472 if (parent_sq->first_pending == n)
473 parent_sq->first_pending = NULL;
474 rb_erase_init(n, &parent_sq->pending_tree);
475 --parent_sq->nr_pending;
478 static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
480 struct throtl_grp *tg;
482 tg = throtl_rb_first(parent_sq);
486 parent_sq->first_pending_disptime = tg->disptime;
489 static void tg_service_queue_add(struct throtl_grp *tg)
491 struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
492 struct rb_node **node = &parent_sq->pending_tree.rb_node;
493 struct rb_node *parent = NULL;
494 struct throtl_grp *__tg;
495 unsigned long key = tg->disptime;
498 while (*node != NULL) {
500 __tg = rb_entry_tg(parent);
502 if (time_before(key, __tg->disptime))
503 node = &parent->rb_left;
505 node = &parent->rb_right;
511 parent_sq->first_pending = &tg->rb_node;
513 rb_link_node(&tg->rb_node, parent, node);
514 rb_insert_color(&tg->rb_node, &parent_sq->pending_tree);
517 static void __throtl_enqueue_tg(struct throtl_grp *tg)
519 tg_service_queue_add(tg);
520 tg->flags |= THROTL_TG_PENDING;
521 tg->service_queue.parent_sq->nr_pending++;
524 static void throtl_enqueue_tg(struct throtl_grp *tg)
526 if (!(tg->flags & THROTL_TG_PENDING))
527 __throtl_enqueue_tg(tg);
530 static void __throtl_dequeue_tg(struct throtl_grp *tg)
532 throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
533 tg->flags &= ~THROTL_TG_PENDING;
536 static void throtl_dequeue_tg(struct throtl_grp *tg)
538 if (tg->flags & THROTL_TG_PENDING)
539 __throtl_dequeue_tg(tg);
542 /* Call with queue lock held */
543 static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
544 unsigned long expires)
546 mod_timer(&sq->pending_timer, expires);
547 throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
548 expires - jiffies, jiffies);
552 * throtl_schedule_next_dispatch - schedule the next dispatch cycle
553 * @sq: the service_queue to schedule dispatch for
554 * @force: force scheduling
556 * Arm @sq->pending_timer so that the next dispatch cycle starts on the
557 * dispatch time of the first pending child. Returns %true if either timer
558 * is armed or there's no pending child left. %false if the current
559 * dispatch window is still open and the caller should continue
562 * If @force is %true, the dispatch timer is always scheduled and this
563 * function is guaranteed to return %true. This is to be used when the
564 * caller can't dispatch itself and needs to invoke pending_timer
565 * unconditionally. Note that forced scheduling is likely to induce short
566 * delay before dispatch starts even if @sq->first_pending_disptime is not
567 * in the future and thus shouldn't be used in hot paths.
569 static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
572 /* any pending children left? */
576 update_min_dispatch_time(sq);
578 /* is the next dispatch time in the future? */
579 if (force || time_after(sq->first_pending_disptime, jiffies)) {
580 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
584 /* tell the caller to continue dispatching */
588 static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
589 bool rw, unsigned long start)
591 tg->bytes_disp[rw] = 0;
595 * Previous slice has expired. We must have trimmed it after last
596 * bio dispatch. That means since start of last slice, we never used
597 * that bandwidth. Do try to make use of that bandwidth while giving
600 if (time_after_eq(start, tg->slice_start[rw]))
601 tg->slice_start[rw] = start;
603 tg->slice_end[rw] = jiffies + throtl_slice;
604 throtl_log(&tg->service_queue,
605 "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
606 rw == READ ? 'R' : 'W', tg->slice_start[rw],
607 tg->slice_end[rw], jiffies);
610 static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
612 tg->bytes_disp[rw] = 0;
614 tg->slice_start[rw] = jiffies;
615 tg->slice_end[rw] = jiffies + throtl_slice;
616 throtl_log(&tg->service_queue,
617 "[%c] new slice start=%lu end=%lu jiffies=%lu",
618 rw == READ ? 'R' : 'W', tg->slice_start[rw],
619 tg->slice_end[rw], jiffies);
622 static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
623 unsigned long jiffy_end)
625 tg->slice_end[rw] = roundup(jiffy_end, throtl_slice);
628 static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
629 unsigned long jiffy_end)
631 tg->slice_end[rw] = roundup(jiffy_end, throtl_slice);
632 throtl_log(&tg->service_queue,
633 "[%c] extend slice start=%lu end=%lu jiffies=%lu",
634 rw == READ ? 'R' : 'W', tg->slice_start[rw],
635 tg->slice_end[rw], jiffies);
638 /* Determine if previously allocated or extended slice is complete or not */
639 static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
641 if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
647 /* Trim the used slices and adjust slice start accordingly */
648 static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
650 unsigned long nr_slices, time_elapsed, io_trim;
653 BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
656 * If bps are unlimited (-1), then time slice don't get
657 * renewed. Don't try to trim the slice if slice is used. A new
658 * slice will start when appropriate.
660 if (throtl_slice_used(tg, rw))
664 * A bio has been dispatched. Also adjust slice_end. It might happen
665 * that initially cgroup limit was very low resulting in high
666 * slice_end, but later limit was bumped up and bio was dispached
667 * sooner, then we need to reduce slice_end. A high bogus slice_end
668 * is bad because it does not allow new slice to start.
671 throtl_set_slice_end(tg, rw, jiffies + throtl_slice);
673 time_elapsed = jiffies - tg->slice_start[rw];
675 nr_slices = time_elapsed / throtl_slice;
679 tmp = tg->bps[rw] * throtl_slice * nr_slices;
683 io_trim = (tg->iops[rw] * throtl_slice * nr_slices)/HZ;
685 if (!bytes_trim && !io_trim)
688 if (tg->bytes_disp[rw] >= bytes_trim)
689 tg->bytes_disp[rw] -= bytes_trim;
691 tg->bytes_disp[rw] = 0;
693 if (tg->io_disp[rw] >= io_trim)
694 tg->io_disp[rw] -= io_trim;
698 tg->slice_start[rw] += nr_slices * throtl_slice;
700 throtl_log(&tg->service_queue,
701 "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
702 rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
703 tg->slice_start[rw], tg->slice_end[rw], jiffies);
706 static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
709 bool rw = bio_data_dir(bio);
710 unsigned int io_allowed;
711 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
714 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
716 /* Slice has just started. Consider one slice interval */
718 jiffy_elapsed_rnd = throtl_slice;
720 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, throtl_slice);
723 * jiffy_elapsed_rnd should not be a big value as minimum iops can be
724 * 1 then at max jiffy elapsed should be equivalent of 1 second as we
725 * will allow dispatch after 1 second and after that slice should
729 tmp = (u64)tg->iops[rw] * jiffy_elapsed_rnd;
733 io_allowed = UINT_MAX;
737 if (tg->io_disp[rw] + 1 <= io_allowed) {
743 /* Calc approx time to dispatch */
744 jiffy_wait = ((tg->io_disp[rw] + 1) * HZ)/tg->iops[rw] + 1;
746 if (jiffy_wait > jiffy_elapsed)
747 jiffy_wait = jiffy_wait - jiffy_elapsed;
756 static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
759 bool rw = bio_data_dir(bio);
760 u64 bytes_allowed, extra_bytes, tmp;
761 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
763 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
765 /* Slice has just started. Consider one slice interval */
767 jiffy_elapsed_rnd = throtl_slice;
769 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, throtl_slice);
771 tmp = tg->bps[rw] * jiffy_elapsed_rnd;
775 if (tg->bytes_disp[rw] + bio->bi_iter.bi_size <= bytes_allowed) {
781 /* Calc approx time to dispatch */
782 extra_bytes = tg->bytes_disp[rw] + bio->bi_iter.bi_size - bytes_allowed;
783 jiffy_wait = div64_u64(extra_bytes * HZ, tg->bps[rw]);
789 * This wait time is without taking into consideration the rounding
790 * up we did. Add that time also.
792 jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
799 * Returns whether one can dispatch a bio or not. Also returns approx number
800 * of jiffies to wait before this bio is with-in IO rate and can be dispatched
802 static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
805 bool rw = bio_data_dir(bio);
806 unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
809 * Currently whole state machine of group depends on first bio
810 * queued in the group bio list. So one should not be calling
811 * this function with a different bio if there are other bios
814 BUG_ON(tg->service_queue.nr_queued[rw] &&
815 bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
817 /* If tg->bps = -1, then BW is unlimited */
818 if (tg->bps[rw] == -1 && tg->iops[rw] == -1) {
825 * If previous slice expired, start a new one otherwise renew/extend
826 * existing slice to make sure it is at least throtl_slice interval
829 if (throtl_slice_used(tg, rw))
830 throtl_start_new_slice(tg, rw);
832 if (time_before(tg->slice_end[rw], jiffies + throtl_slice))
833 throtl_extend_slice(tg, rw, jiffies + throtl_slice);
836 if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
837 tg_with_in_iops_limit(tg, bio, &iops_wait)) {
843 max_wait = max(bps_wait, iops_wait);
848 if (time_before(tg->slice_end[rw], jiffies + max_wait))
849 throtl_extend_slice(tg, rw, jiffies + max_wait);
854 static void throtl_update_dispatch_stats(struct blkcg_gq *blkg, u64 bytes,
857 struct throtl_grp *tg = blkg_to_tg(blkg);
858 struct tg_stats_cpu *stats_cpu;
862 * Disabling interrupts to provide mutual exclusion between two
863 * writes on same cpu. It probably is not needed for 64bit. Not
864 * optimizing that case yet.
866 local_irq_save(flags);
868 stats_cpu = this_cpu_ptr(tg->stats_cpu);
870 blkg_rwstat_add(&stats_cpu->serviced, rw, 1);
871 blkg_rwstat_add(&stats_cpu->service_bytes, rw, bytes);
873 local_irq_restore(flags);
876 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
878 bool rw = bio_data_dir(bio);
880 /* Charge the bio to the group */
881 tg->bytes_disp[rw] += bio->bi_iter.bi_size;
885 * REQ_THROTTLED is used to prevent the same bio to be throttled
886 * more than once as a throttled bio will go through blk-throtl the
887 * second time when it eventually gets issued. Set it when a bio
888 * is being charged to a tg.
890 * Dispatch stats aren't recursive and each @bio should only be
891 * accounted by the @tg it was originally associated with. Let's
892 * update the stats when setting REQ_THROTTLED for the first time
893 * which is guaranteed to be for the @bio's original tg.
895 if (!(bio->bi_rw & REQ_THROTTLED)) {
896 bio->bi_rw |= REQ_THROTTLED;
897 throtl_update_dispatch_stats(tg_to_blkg(tg),
898 bio->bi_iter.bi_size, bio->bi_rw);
903 * throtl_add_bio_tg - add a bio to the specified throtl_grp
906 * @tg: the target throtl_grp
908 * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
909 * tg->qnode_on_self[] is used.
911 static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
912 struct throtl_grp *tg)
914 struct throtl_service_queue *sq = &tg->service_queue;
915 bool rw = bio_data_dir(bio);
918 qn = &tg->qnode_on_self[rw];
921 * If @tg doesn't currently have any bios queued in the same
922 * direction, queueing @bio can change when @tg should be
923 * dispatched. Mark that @tg was empty. This is automatically
924 * cleaered on the next tg_update_disptime().
926 if (!sq->nr_queued[rw])
927 tg->flags |= THROTL_TG_WAS_EMPTY;
929 throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
932 throtl_enqueue_tg(tg);
935 static void tg_update_disptime(struct throtl_grp *tg)
937 struct throtl_service_queue *sq = &tg->service_queue;
938 unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
941 if ((bio = throtl_peek_queued(&sq->queued[READ])))
942 tg_may_dispatch(tg, bio, &read_wait);
944 if ((bio = throtl_peek_queued(&sq->queued[WRITE])))
945 tg_may_dispatch(tg, bio, &write_wait);
947 min_wait = min(read_wait, write_wait);
948 disptime = jiffies + min_wait;
950 /* Update dispatch time */
951 throtl_dequeue_tg(tg);
952 tg->disptime = disptime;
953 throtl_enqueue_tg(tg);
955 /* see throtl_add_bio_tg() */
956 tg->flags &= ~THROTL_TG_WAS_EMPTY;
959 static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
960 struct throtl_grp *parent_tg, bool rw)
962 if (throtl_slice_used(parent_tg, rw)) {
963 throtl_start_new_slice_with_credit(parent_tg, rw,
964 child_tg->slice_start[rw]);
969 static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
971 struct throtl_service_queue *sq = &tg->service_queue;
972 struct throtl_service_queue *parent_sq = sq->parent_sq;
973 struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
974 struct throtl_grp *tg_to_put = NULL;
978 * @bio is being transferred from @tg to @parent_sq. Popping a bio
979 * from @tg may put its reference and @parent_sq might end up
980 * getting released prematurely. Remember the tg to put and put it
981 * after @bio is transferred to @parent_sq.
983 bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
986 throtl_charge_bio(tg, bio);
989 * If our parent is another tg, we just need to transfer @bio to
990 * the parent using throtl_add_bio_tg(). If our parent is
991 * @td->service_queue, @bio is ready to be issued. Put it on its
992 * bio_lists[] and decrease total number queued. The caller is
993 * responsible for issuing these bios.
996 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
997 start_parent_slice_with_credit(tg, parent_tg, rw);
999 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1000 &parent_sq->queued[rw]);
1001 BUG_ON(tg->td->nr_queued[rw] <= 0);
1002 tg->td->nr_queued[rw]--;
1005 throtl_trim_slice(tg, rw);
1008 blkg_put(tg_to_blkg(tg_to_put));
1011 static int throtl_dispatch_tg(struct throtl_grp *tg)
1013 struct throtl_service_queue *sq = &tg->service_queue;
1014 unsigned int nr_reads = 0, nr_writes = 0;
1015 unsigned int max_nr_reads = throtl_grp_quantum*3/4;
1016 unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
1019 /* Try to dispatch 75% READS and 25% WRITES */
1021 while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
1022 tg_may_dispatch(tg, bio, NULL)) {
1024 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1027 if (nr_reads >= max_nr_reads)
1031 while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
1032 tg_may_dispatch(tg, bio, NULL)) {
1034 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1037 if (nr_writes >= max_nr_writes)
1041 return nr_reads + nr_writes;
1044 static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
1046 unsigned int nr_disp = 0;
1049 struct throtl_grp *tg = throtl_rb_first(parent_sq);
1050 struct throtl_service_queue *sq = &tg->service_queue;
1055 if (time_before(jiffies, tg->disptime))
1058 throtl_dequeue_tg(tg);
1060 nr_disp += throtl_dispatch_tg(tg);
1062 if (sq->nr_queued[0] || sq->nr_queued[1])
1063 tg_update_disptime(tg);
1065 if (nr_disp >= throtl_quantum)
1073 * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1074 * @arg: the throtl_service_queue being serviced
1076 * This timer is armed when a child throtl_grp with active bio's become
1077 * pending and queued on the service_queue's pending_tree and expires when
1078 * the first child throtl_grp should be dispatched. This function
1079 * dispatches bio's from the children throtl_grps to the parent
1082 * If the parent's parent is another throtl_grp, dispatching is propagated
1083 * by either arming its pending_timer or repeating dispatch directly. If
1084 * the top-level service_tree is reached, throtl_data->dispatch_work is
1085 * kicked so that the ready bio's are issued.
1087 static void throtl_pending_timer_fn(unsigned long arg)
1089 struct throtl_service_queue *sq = (void *)arg;
1090 struct throtl_grp *tg = sq_to_tg(sq);
1091 struct throtl_data *td = sq_to_td(sq);
1092 struct request_queue *q = td->queue;
1093 struct throtl_service_queue *parent_sq;
1097 spin_lock_irq(q->queue_lock);
1099 parent_sq = sq->parent_sq;
1103 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
1104 sq->nr_queued[READ] + sq->nr_queued[WRITE],
1105 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1107 ret = throtl_select_dispatch(sq);
1109 throtl_log(sq, "bios disp=%u", ret);
1113 if (throtl_schedule_next_dispatch(sq, false))
1116 /* this dispatch windows is still open, relax and repeat */
1117 spin_unlock_irq(q->queue_lock);
1119 spin_lock_irq(q->queue_lock);
1126 /* @parent_sq is another throl_grp, propagate dispatch */
1127 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1128 tg_update_disptime(tg);
1129 if (!throtl_schedule_next_dispatch(parent_sq, false)) {
1130 /* window is already open, repeat dispatching */
1137 /* reached the top-level, queue issueing */
1138 queue_work(kthrotld_workqueue, &td->dispatch_work);
1141 spin_unlock_irq(q->queue_lock);
1145 * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1146 * @work: work item being executed
1148 * This function is queued for execution when bio's reach the bio_lists[]
1149 * of throtl_data->service_queue. Those bio's are ready and issued by this
1152 static void blk_throtl_dispatch_work_fn(struct work_struct *work)
1154 struct throtl_data *td = container_of(work, struct throtl_data,
1156 struct throtl_service_queue *td_sq = &td->service_queue;
1157 struct request_queue *q = td->queue;
1158 struct bio_list bio_list_on_stack;
1160 struct blk_plug plug;
1163 bio_list_init(&bio_list_on_stack);
1165 spin_lock_irq(q->queue_lock);
1166 for (rw = READ; rw <= WRITE; rw++)
1167 while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
1168 bio_list_add(&bio_list_on_stack, bio);
1169 spin_unlock_irq(q->queue_lock);
1171 if (!bio_list_empty(&bio_list_on_stack)) {
1172 blk_start_plug(&plug);
1173 while((bio = bio_list_pop(&bio_list_on_stack)))
1174 generic_make_request(bio);
1175 blk_finish_plug(&plug);
1179 static u64 tg_prfill_cpu_rwstat(struct seq_file *sf,
1180 struct blkg_policy_data *pd, int off)
1182 struct throtl_grp *tg = pd_to_tg(pd);
1183 struct blkg_rwstat rwstat = { }, tmp;
1186 for_each_possible_cpu(cpu) {
1187 struct tg_stats_cpu *sc = per_cpu_ptr(tg->stats_cpu, cpu);
1189 tmp = blkg_rwstat_read((void *)sc + off);
1190 for (i = 0; i < BLKG_RWSTAT_NR; i++)
1191 rwstat.cnt[i] += tmp.cnt[i];
1194 return __blkg_prfill_rwstat(sf, pd, &rwstat);
1197 static int tg_print_cpu_rwstat(struct seq_file *sf, void *v)
1199 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_cpu_rwstat,
1200 &blkcg_policy_throtl, seq_cft(sf)->private, true);
1204 static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1207 struct throtl_grp *tg = pd_to_tg(pd);
1208 u64 v = *(u64 *)((void *)tg + off);
1212 return __blkg_prfill_u64(sf, pd, v);
1215 static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1218 struct throtl_grp *tg = pd_to_tg(pd);
1219 unsigned int v = *(unsigned int *)((void *)tg + off);
1223 return __blkg_prfill_u64(sf, pd, v);
1226 static int tg_print_conf_u64(struct seq_file *sf, void *v)
1228 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1229 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1233 static int tg_print_conf_uint(struct seq_file *sf, void *v)
1235 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1236 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1240 static ssize_t tg_set_conf(struct kernfs_open_file *of,
1241 char *buf, size_t nbytes, loff_t off, bool is_u64)
1243 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1244 struct blkg_conf_ctx ctx;
1245 struct throtl_grp *tg;
1246 struct throtl_service_queue *sq;
1247 struct blkcg_gq *blkg;
1248 struct cgroup_subsys_state *pos_css;
1251 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1255 tg = blkg_to_tg(ctx.blkg);
1256 sq = &tg->service_queue;
1262 *(u64 *)((void *)tg + of_cft(of)->private) = ctx.v;
1264 *(unsigned int *)((void *)tg + of_cft(of)->private) = ctx.v;
1266 throtl_log(&tg->service_queue,
1267 "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
1268 tg->bps[READ], tg->bps[WRITE],
1269 tg->iops[READ], tg->iops[WRITE]);
1272 * Update has_rules[] flags for the updated tg's subtree. A tg is
1273 * considered to have rules if either the tg itself or any of its
1274 * ancestors has rules. This identifies groups without any
1275 * restrictions in the whole hierarchy and allows them to bypass
1278 blkg_for_each_descendant_pre(blkg, pos_css, ctx.blkg)
1279 tg_update_has_rules(blkg_to_tg(blkg));
1282 * We're already holding queue_lock and know @tg is valid. Let's
1283 * apply the new config directly.
1285 * Restart the slices for both READ and WRITES. It might happen
1286 * that a group's limit are dropped suddenly and we don't want to
1287 * account recently dispatched IO with new low rate.
1289 throtl_start_new_slice(tg, 0);
1290 throtl_start_new_slice(tg, 1);
1292 if (tg->flags & THROTL_TG_PENDING) {
1293 tg_update_disptime(tg);
1294 throtl_schedule_next_dispatch(sq->parent_sq, true);
1297 blkg_conf_finish(&ctx);
1301 static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1302 char *buf, size_t nbytes, loff_t off)
1304 return tg_set_conf(of, buf, nbytes, off, true);
1307 static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1308 char *buf, size_t nbytes, loff_t off)
1310 return tg_set_conf(of, buf, nbytes, off, false);
1313 static struct cftype throtl_files[] = {
1315 .name = "throttle.read_bps_device",
1316 .private = offsetof(struct throtl_grp, bps[READ]),
1317 .seq_show = tg_print_conf_u64,
1318 .write = tg_set_conf_u64,
1321 .name = "throttle.write_bps_device",
1322 .private = offsetof(struct throtl_grp, bps[WRITE]),
1323 .seq_show = tg_print_conf_u64,
1324 .write = tg_set_conf_u64,
1327 .name = "throttle.read_iops_device",
1328 .private = offsetof(struct throtl_grp, iops[READ]),
1329 .seq_show = tg_print_conf_uint,
1330 .write = tg_set_conf_uint,
1333 .name = "throttle.write_iops_device",
1334 .private = offsetof(struct throtl_grp, iops[WRITE]),
1335 .seq_show = tg_print_conf_uint,
1336 .write = tg_set_conf_uint,
1339 .name = "throttle.io_service_bytes",
1340 .private = offsetof(struct tg_stats_cpu, service_bytes),
1341 .seq_show = tg_print_cpu_rwstat,
1344 .name = "throttle.io_serviced",
1345 .private = offsetof(struct tg_stats_cpu, serviced),
1346 .seq_show = tg_print_cpu_rwstat,
1351 static void throtl_shutdown_wq(struct request_queue *q)
1353 struct throtl_data *td = q->td;
1355 cancel_work_sync(&td->dispatch_work);
1358 static struct blkcg_policy blkcg_policy_throtl = {
1359 .cftypes = throtl_files,
1361 .pd_alloc_fn = throtl_pd_alloc,
1362 .pd_init_fn = throtl_pd_init,
1363 .pd_online_fn = throtl_pd_online,
1364 .pd_free_fn = throtl_pd_free,
1365 .pd_reset_stats_fn = throtl_pd_reset_stats,
1368 bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
1371 struct throtl_qnode *qn = NULL;
1372 struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
1373 struct throtl_service_queue *sq;
1374 bool rw = bio_data_dir(bio);
1375 bool throttled = false;
1377 WARN_ON_ONCE(!rcu_read_lock_held());
1379 /* see throtl_charge_bio() */
1380 if ((bio->bi_rw & REQ_THROTTLED) || !tg->has_rules[rw])
1383 spin_lock_irq(q->queue_lock);
1385 if (unlikely(blk_queue_bypass(q)))
1388 sq = &tg->service_queue;
1391 /* throtl is FIFO - if bios are already queued, should queue */
1392 if (sq->nr_queued[rw])
1395 /* if above limits, break to queue */
1396 if (!tg_may_dispatch(tg, bio, NULL))
1399 /* within limits, let's charge and dispatch directly */
1400 throtl_charge_bio(tg, bio);
1403 * We need to trim slice even when bios are not being queued
1404 * otherwise it might happen that a bio is not queued for
1405 * a long time and slice keeps on extending and trim is not
1406 * called for a long time. Now if limits are reduced suddenly
1407 * we take into account all the IO dispatched so far at new
1408 * low rate and * newly queued IO gets a really long dispatch
1411 * So keep on trimming slice even if bio is not queued.
1413 throtl_trim_slice(tg, rw);
1416 * @bio passed through this layer without being throttled.
1417 * Climb up the ladder. If we''re already at the top, it
1418 * can be executed directly.
1420 qn = &tg->qnode_on_parent[rw];
1427 /* out-of-limit, queue to @tg */
1428 throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
1429 rw == READ ? 'R' : 'W',
1430 tg->bytes_disp[rw], bio->bi_iter.bi_size, tg->bps[rw],
1431 tg->io_disp[rw], tg->iops[rw],
1432 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1434 bio_associate_current(bio);
1435 tg->td->nr_queued[rw]++;
1436 throtl_add_bio_tg(bio, qn, tg);
1440 * Update @tg's dispatch time and force schedule dispatch if @tg
1441 * was empty before @bio. The forced scheduling isn't likely to
1442 * cause undue delay as @bio is likely to be dispatched directly if
1443 * its @tg's disptime is not in the future.
1445 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1446 tg_update_disptime(tg);
1447 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
1451 spin_unlock_irq(q->queue_lock);
1454 * As multiple blk-throtls may stack in the same issue path, we
1455 * don't want bios to leave with the flag set. Clear the flag if
1459 bio->bi_rw &= ~REQ_THROTTLED;
1464 * Dispatch all bios from all children tg's queued on @parent_sq. On
1465 * return, @parent_sq is guaranteed to not have any active children tg's
1466 * and all bios from previously active tg's are on @parent_sq->bio_lists[].
1468 static void tg_drain_bios(struct throtl_service_queue *parent_sq)
1470 struct throtl_grp *tg;
1472 while ((tg = throtl_rb_first(parent_sq))) {
1473 struct throtl_service_queue *sq = &tg->service_queue;
1476 throtl_dequeue_tg(tg);
1478 while ((bio = throtl_peek_queued(&sq->queued[READ])))
1479 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1480 while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
1481 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1486 * blk_throtl_drain - drain throttled bios
1487 * @q: request_queue to drain throttled bios for
1489 * Dispatch all currently throttled bios on @q through ->make_request_fn().
1491 void blk_throtl_drain(struct request_queue *q)
1492 __releases(q->queue_lock) __acquires(q->queue_lock)
1494 struct throtl_data *td = q->td;
1495 struct blkcg_gq *blkg;
1496 struct cgroup_subsys_state *pos_css;
1500 queue_lockdep_assert_held(q);
1504 * Drain each tg while doing post-order walk on the blkg tree, so
1505 * that all bios are propagated to td->service_queue. It'd be
1506 * better to walk service_queue tree directly but blkg walk is
1509 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
1510 tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
1512 /* finally, transfer bios from top-level tg's into the td */
1513 tg_drain_bios(&td->service_queue);
1516 spin_unlock_irq(q->queue_lock);
1518 /* all bios now should be in td->service_queue, issue them */
1519 for (rw = READ; rw <= WRITE; rw++)
1520 while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
1522 generic_make_request(bio);
1524 spin_lock_irq(q->queue_lock);
1527 int blk_throtl_init(struct request_queue *q)
1529 struct throtl_data *td;
1532 td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
1536 INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
1537 throtl_service_queue_init(&td->service_queue);
1542 /* activate policy */
1543 ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
1549 void blk_throtl_exit(struct request_queue *q)
1552 throtl_shutdown_wq(q);
1553 blkcg_deactivate_policy(q, &blkcg_policy_throtl);
1557 static int __init throtl_init(void)
1559 kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
1560 if (!kthrotld_workqueue)
1561 panic("Failed to create kthrotld\n");
1563 return blkcg_policy_register(&blkcg_policy_throtl);
1566 module_init(throtl_init);