]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - block/blk-throttle.c
blk-throttle: make throtl_slice tunable
[mirror_ubuntu-bionic-kernel.git] / block / blk-throttle.c
CommitLineData
e43473b7
VG
1/*
2 * Interface for controlling IO bandwidth on a request queue
3 *
4 * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
5 */
6
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>
eea8f41c 12#include <linux/blk-cgroup.h>
bc9fcbf9 13#include "blk.h"
e43473b7
VG
14
15/* Max dispatch from a group in 1 round */
16static int throtl_grp_quantum = 8;
17
18/* Total max dispatch from all groups in one round */
19static int throtl_quantum = 32;
20
21/* Throttling is performed over 100ms slice and after that slice is renewed */
297e3d85
SL
22#define DFL_THROTL_SLICE (HZ / 10)
23#define MAX_THROTL_SLICE (HZ)
e43473b7 24
3c798398 25static struct blkcg_policy blkcg_policy_throtl;
0381411e 26
450adcbe
VG
27/* A workqueue to queue throttle related work */
28static struct workqueue_struct *kthrotld_workqueue;
450adcbe 29
c5cc2070
TH
30/*
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.
37 *
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.
42 *
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.
46 *
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.
52 */
53struct throtl_qnode {
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 */
57};
58
c9e0332e 59struct throtl_service_queue {
77216b04
TH
60 struct throtl_service_queue *parent_sq; /* the parent service_queue */
61
73f0d49a
TH
62 /*
63 * Bios queued directly to this service_queue or dispatched from
64 * children throtl_grp's.
65 */
c5cc2070 66 struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
73f0d49a
TH
67 unsigned int nr_queued[2]; /* number of queued bios */
68
69 /*
70 * RB tree of active children throtl_grp's, which are sorted by
71 * their ->disptime.
72 */
c9e0332e
TH
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 */
69df0ab0 77 struct timer_list pending_timer; /* fires on first_pending_disptime */
e43473b7
VG
78};
79
5b2c16aa
TH
80enum tg_state_flags {
81 THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
0e9f4164 82 THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
5b2c16aa
TH
83};
84
e43473b7
VG
85#define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
86
9f626e37 87enum {
cd5ab1b0 88 LIMIT_LOW,
9f626e37
SL
89 LIMIT_MAX,
90 LIMIT_CNT,
91};
92
e43473b7 93struct throtl_grp {
f95a04af
TH
94 /* must be the first member */
95 struct blkg_policy_data pd;
96
c9e0332e 97 /* active throtl group service_queue member */
e43473b7
VG
98 struct rb_node rb_node;
99
0f3457f6
TH
100 /* throtl_data this group belongs to */
101 struct throtl_data *td;
102
49a2f1e3
TH
103 /* this group's service queue */
104 struct throtl_service_queue service_queue;
105
c5cc2070
TH
106 /*
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
112 * qnode_on_self.
113 */
114 struct throtl_qnode qnode_on_self[2];
115 struct throtl_qnode qnode_on_parent[2];
116
e43473b7
VG
117 /*
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.
121 */
122 unsigned long disptime;
123
e43473b7
VG
124 unsigned int flags;
125
693e751e
TH
126 /* are there any throtl rules between this group and td? */
127 bool has_rules[2];
128
cd5ab1b0 129 /* internally used bytes per second rate limits */
9f626e37 130 uint64_t bps[2][LIMIT_CNT];
cd5ab1b0
SL
131 /* user configured bps limits */
132 uint64_t bps_conf[2][LIMIT_CNT];
e43473b7 133
cd5ab1b0 134 /* internally used IOPS limits */
9f626e37 135 unsigned int iops[2][LIMIT_CNT];
cd5ab1b0
SL
136 /* user configured IOPS limits */
137 unsigned int iops_conf[2][LIMIT_CNT];
8e89d13f 138
e43473b7
VG
139 /* Number of bytes disptached in current slice */
140 uint64_t bytes_disp[2];
8e89d13f
VG
141 /* Number of bio's dispatched in current slice */
142 unsigned int io_disp[2];
e43473b7 143
3f0abd80
SL
144 unsigned long last_low_overflow_time[2];
145
146 uint64_t last_bytes_disp[2];
147 unsigned int last_io_disp[2];
148
149 unsigned long last_check_time;
150
e43473b7
VG
151 /* When did we start a new slice */
152 unsigned long slice_start[2];
153 unsigned long slice_end[2];
154};
155
156struct throtl_data
157{
e43473b7 158 /* service tree for active throtl groups */
c9e0332e 159 struct throtl_service_queue service_queue;
e43473b7 160
e43473b7
VG
161 struct request_queue *queue;
162
163 /* Total Number of queued bios on READ and WRITE lists */
164 unsigned int nr_queued[2];
165
297e3d85
SL
166 unsigned int throtl_slice;
167
e43473b7 168 /* Work for dispatching throttled bios */
69df0ab0 169 struct work_struct dispatch_work;
9f626e37
SL
170 unsigned int limit_index;
171 bool limit_valid[LIMIT_CNT];
3f0abd80
SL
172
173 unsigned long low_upgrade_time;
174 unsigned long low_downgrade_time;
e43473b7
VG
175};
176
69df0ab0
TH
177static void throtl_pending_timer_fn(unsigned long arg);
178
f95a04af
TH
179static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
180{
181 return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
182}
183
3c798398 184static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
0381411e 185{
f95a04af 186 return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
0381411e
TH
187}
188
3c798398 189static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
0381411e 190{
f95a04af 191 return pd_to_blkg(&tg->pd);
0381411e
TH
192}
193
fda6f272
TH
194/**
195 * sq_to_tg - return the throl_grp the specified service queue belongs to
196 * @sq: the throtl_service_queue of interest
197 *
198 * Return the throtl_grp @sq belongs to. If @sq is the top-level one
199 * embedded in throtl_data, %NULL is returned.
200 */
201static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
202{
203 if (sq && sq->parent_sq)
204 return container_of(sq, struct throtl_grp, service_queue);
205 else
206 return NULL;
207}
208
209/**
210 * sq_to_td - return throtl_data the specified service queue belongs to
211 * @sq: the throtl_service_queue of interest
212 *
b43daedc 213 * A service_queue can be embedded in either a throtl_grp or throtl_data.
fda6f272
TH
214 * Determine the associated throtl_data accordingly and return it.
215 */
216static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
217{
218 struct throtl_grp *tg = sq_to_tg(sq);
219
220 if (tg)
221 return tg->td;
222 else
223 return container_of(sq, struct throtl_data, service_queue);
224}
225
9f626e37
SL
226static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
227{
b22c417c
SL
228 struct blkcg_gq *blkg = tg_to_blkg(tg);
229 uint64_t ret;
230
231 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
232 return U64_MAX;
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];
236 return ret;
9f626e37
SL
237}
238
239static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
240{
b22c417c
SL
241 struct blkcg_gq *blkg = tg_to_blkg(tg);
242 unsigned int ret;
243
244 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
245 return UINT_MAX;
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];
249 return ret;
9f626e37
SL
250}
251
fda6f272
TH
252/**
253 * throtl_log - log debug message via blktrace
254 * @sq: the service_queue being reported
255 * @fmt: printf format string
256 * @args: printf args
257 *
258 * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
259 * throtl_grp; otherwise, just "throtl".
fda6f272
TH
260 */
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)); \
264 \
265 (void)__td; \
59fa0224
SL
266 if (likely(!blk_trace_note_message_enabled(__td->queue))) \
267 break; \
fda6f272
TH
268 if ((__tg)) { \
269 char __pbuf[128]; \
54e7ed12 270 \
fda6f272
TH
271 blkg_path(tg_to_blkg(__tg), __pbuf, sizeof(__pbuf)); \
272 blk_add_trace_msg(__td->queue, "throtl %s " fmt, __pbuf, ##args); \
273 } else { \
274 blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
275 } \
54e7ed12 276} while (0)
e43473b7 277
c5cc2070
TH
278static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
279{
280 INIT_LIST_HEAD(&qn->node);
281 bio_list_init(&qn->bios);
282 qn->tg = tg;
283}
284
285/**
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
290 *
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.
294 */
295static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
296 struct list_head *queued)
297{
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));
302 }
303}
304
305/**
306 * throtl_peek_queued - peek the first bio on a qnode list
307 * @queued: the qnode list to peek
308 */
309static struct bio *throtl_peek_queued(struct list_head *queued)
310{
311 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
312 struct bio *bio;
313
314 if (list_empty(queued))
315 return NULL;
316
317 bio = bio_list_peek(&qn->bios);
318 WARN_ON_ONCE(!bio);
319 return bio;
320}
321
322/**
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
326 *
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.
330 *
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.
335 */
336static struct bio *throtl_pop_queued(struct list_head *queued,
337 struct throtl_grp **tg_to_put)
338{
339 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
340 struct bio *bio;
341
342 if (list_empty(queued))
343 return NULL;
344
345 bio = bio_list_pop(&qn->bios);
346 WARN_ON_ONCE(!bio);
347
348 if (bio_list_empty(&qn->bios)) {
349 list_del_init(&qn->node);
350 if (tg_to_put)
351 *tg_to_put = qn->tg;
352 else
353 blkg_put(tg_to_blkg(qn->tg));
354 } else {
355 list_move_tail(&qn->node, queued);
356 }
357
358 return bio;
359}
360
49a2f1e3 361/* init a service_queue, assumes the caller zeroed it */
b2ce2643 362static void throtl_service_queue_init(struct throtl_service_queue *sq)
49a2f1e3 363{
c5cc2070
TH
364 INIT_LIST_HEAD(&sq->queued[0]);
365 INIT_LIST_HEAD(&sq->queued[1]);
49a2f1e3 366 sq->pending_tree = RB_ROOT;
69df0ab0
TH
367 setup_timer(&sq->pending_timer, throtl_pending_timer_fn,
368 (unsigned long)sq);
369}
370
001bea73
TH
371static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
372{
4fb72036 373 struct throtl_grp *tg;
24bdb8ef 374 int rw;
4fb72036
TH
375
376 tg = kzalloc_node(sizeof(*tg), gfp, node);
377 if (!tg)
77ea7338 378 return NULL;
4fb72036 379
b2ce2643
TH
380 throtl_service_queue_init(&tg->service_queue);
381
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);
385 }
386
387 RB_CLEAR_NODE(&tg->rb_node);
9f626e37
SL
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;
cd5ab1b0
SL
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 */
b2ce2643 397
4fb72036 398 return &tg->pd;
001bea73
TH
399}
400
a9520cd6 401static void throtl_pd_init(struct blkg_policy_data *pd)
a29a171e 402{
a9520cd6
TH
403 struct throtl_grp *tg = pd_to_tg(pd);
404 struct blkcg_gq *blkg = tg_to_blkg(tg);
77216b04 405 struct throtl_data *td = blkg->q->td;
b2ce2643 406 struct throtl_service_queue *sq = &tg->service_queue;
cd1604fa 407
9138125b 408 /*
aa6ec29b 409 * If on the default hierarchy, we switch to properly hierarchical
9138125b
TH
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.
414 *
aa6ec29b 415 * If not on the default hierarchy, the broken flat hierarchy
9138125b
TH
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.
420 */
b2ce2643 421 sq->parent_sq = &td->service_queue;
9e10a130 422 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
b2ce2643 423 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
77216b04 424 tg->td = td;
8a3d2615
TH
425}
426
693e751e
TH
427/*
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.
431 */
432static void tg_update_has_rules(struct throtl_grp *tg)
433{
434 struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
9f626e37 435 struct throtl_data *td = tg->td;
693e751e
TH
436 int rw;
437
438 for (rw = READ; rw <= WRITE; rw++)
439 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
9f626e37
SL
440 (td->limit_valid[td->limit_index] &&
441 (tg_bps_limit(tg, rw) != U64_MAX ||
442 tg_iops_limit(tg, rw) != UINT_MAX));
693e751e
TH
443}
444
a9520cd6 445static void throtl_pd_online(struct blkg_policy_data *pd)
693e751e
TH
446{
447 /*
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.
450 */
a9520cd6 451 tg_update_has_rules(pd_to_tg(pd));
693e751e
TH
452}
453
cd5ab1b0
SL
454static void blk_throtl_update_limit_valid(struct throtl_data *td)
455{
456 struct cgroup_subsys_state *pos_css;
457 struct blkcg_gq *blkg;
458 bool low_valid = false;
459
460 rcu_read_lock();
461 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
462 struct throtl_grp *tg = blkg_to_tg(blkg);
463
464 if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
465 tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
466 low_valid = true;
467 }
468 rcu_read_unlock();
469
470 td->limit_valid[LIMIT_LOW] = low_valid;
471}
472
c79892c5 473static void throtl_upgrade_state(struct throtl_data *td);
cd5ab1b0
SL
474static void throtl_pd_offline(struct blkg_policy_data *pd)
475{
476 struct throtl_grp *tg = pd_to_tg(pd);
477
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;
482
483 blk_throtl_update_limit_valid(tg->td);
484
c79892c5
SL
485 if (!tg->td->limit_valid[tg->td->limit_index])
486 throtl_upgrade_state(tg->td);
cd5ab1b0
SL
487}
488
001bea73
TH
489static void throtl_pd_free(struct blkg_policy_data *pd)
490{
4fb72036
TH
491 struct throtl_grp *tg = pd_to_tg(pd);
492
b2ce2643 493 del_timer_sync(&tg->service_queue.pending_timer);
4fb72036 494 kfree(tg);
001bea73
TH
495}
496
0049af73
TH
497static struct throtl_grp *
498throtl_rb_first(struct throtl_service_queue *parent_sq)
e43473b7
VG
499{
500 /* Service tree is empty */
0049af73 501 if (!parent_sq->nr_pending)
e43473b7
VG
502 return NULL;
503
0049af73
TH
504 if (!parent_sq->first_pending)
505 parent_sq->first_pending = rb_first(&parent_sq->pending_tree);
e43473b7 506
0049af73
TH
507 if (parent_sq->first_pending)
508 return rb_entry_tg(parent_sq->first_pending);
e43473b7
VG
509
510 return NULL;
511}
512
513static void rb_erase_init(struct rb_node *n, struct rb_root *root)
514{
515 rb_erase(n, root);
516 RB_CLEAR_NODE(n);
517}
518
0049af73
TH
519static void throtl_rb_erase(struct rb_node *n,
520 struct throtl_service_queue *parent_sq)
e43473b7 521{
0049af73
TH
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;
e43473b7
VG
526}
527
0049af73 528static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
e43473b7
VG
529{
530 struct throtl_grp *tg;
531
0049af73 532 tg = throtl_rb_first(parent_sq);
e43473b7
VG
533 if (!tg)
534 return;
535
0049af73 536 parent_sq->first_pending_disptime = tg->disptime;
e43473b7
VG
537}
538
77216b04 539static void tg_service_queue_add(struct throtl_grp *tg)
e43473b7 540{
77216b04 541 struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
0049af73 542 struct rb_node **node = &parent_sq->pending_tree.rb_node;
e43473b7
VG
543 struct rb_node *parent = NULL;
544 struct throtl_grp *__tg;
545 unsigned long key = tg->disptime;
546 int left = 1;
547
548 while (*node != NULL) {
549 parent = *node;
550 __tg = rb_entry_tg(parent);
551
552 if (time_before(key, __tg->disptime))
553 node = &parent->rb_left;
554 else {
555 node = &parent->rb_right;
556 left = 0;
557 }
558 }
559
560 if (left)
0049af73 561 parent_sq->first_pending = &tg->rb_node;
e43473b7
VG
562
563 rb_link_node(&tg->rb_node, parent, node);
0049af73 564 rb_insert_color(&tg->rb_node, &parent_sq->pending_tree);
e43473b7
VG
565}
566
77216b04 567static void __throtl_enqueue_tg(struct throtl_grp *tg)
e43473b7 568{
77216b04 569 tg_service_queue_add(tg);
5b2c16aa 570 tg->flags |= THROTL_TG_PENDING;
77216b04 571 tg->service_queue.parent_sq->nr_pending++;
e43473b7
VG
572}
573
77216b04 574static void throtl_enqueue_tg(struct throtl_grp *tg)
e43473b7 575{
5b2c16aa 576 if (!(tg->flags & THROTL_TG_PENDING))
77216b04 577 __throtl_enqueue_tg(tg);
e43473b7
VG
578}
579
77216b04 580static void __throtl_dequeue_tg(struct throtl_grp *tg)
e43473b7 581{
77216b04 582 throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
5b2c16aa 583 tg->flags &= ~THROTL_TG_PENDING;
e43473b7
VG
584}
585
77216b04 586static void throtl_dequeue_tg(struct throtl_grp *tg)
e43473b7 587{
5b2c16aa 588 if (tg->flags & THROTL_TG_PENDING)
77216b04 589 __throtl_dequeue_tg(tg);
e43473b7
VG
590}
591
a9131a27 592/* Call with queue lock held */
69df0ab0
TH
593static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
594 unsigned long expires)
a9131a27 595{
297e3d85 596 unsigned long max_expire = jiffies + 8 * sq_to_tg(sq)->td->throtl_slice;
06cceedc
SL
597
598 /*
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.
604 */
605 if (time_after(expires, max_expire))
606 expires = max_expire;
69df0ab0
TH
607 mod_timer(&sq->pending_timer, expires);
608 throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
609 expires - jiffies, jiffies);
a9131a27
TH
610}
611
7f52f98c
TH
612/**
613 * throtl_schedule_next_dispatch - schedule the next dispatch cycle
614 * @sq: the service_queue to schedule dispatch for
615 * @force: force scheduling
616 *
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
621 * dispatching.
622 *
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.
629 */
630static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
631 bool force)
e43473b7 632{
6a525600 633 /* any pending children left? */
c9e0332e 634 if (!sq->nr_pending)
7f52f98c 635 return true;
e43473b7 636
c9e0332e 637 update_min_dispatch_time(sq);
e43473b7 638
69df0ab0 639 /* is the next dispatch time in the future? */
7f52f98c 640 if (force || time_after(sq->first_pending_disptime, jiffies)) {
69df0ab0 641 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
7f52f98c 642 return true;
69df0ab0
TH
643 }
644
7f52f98c
TH
645 /* tell the caller to continue dispatching */
646 return false;
e43473b7
VG
647}
648
32ee5bc4
VG
649static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
650 bool rw, unsigned long start)
651{
652 tg->bytes_disp[rw] = 0;
653 tg->io_disp[rw] = 0;
654
655 /*
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
659 * credit.
660 */
661 if (time_after_eq(start, tg->slice_start[rw]))
662 tg->slice_start[rw] = start;
663
297e3d85 664 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
32ee5bc4
VG
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);
669}
670
0f3457f6 671static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
e43473b7
VG
672{
673 tg->bytes_disp[rw] = 0;
8e89d13f 674 tg->io_disp[rw] = 0;
e43473b7 675 tg->slice_start[rw] = jiffies;
297e3d85 676 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
fda6f272
TH
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);
e43473b7
VG
681}
682
0f3457f6
TH
683static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
684 unsigned long jiffy_end)
d1ae8ffd 685{
297e3d85 686 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
d1ae8ffd
VG
687}
688
0f3457f6
TH
689static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
690 unsigned long jiffy_end)
e43473b7 691{
297e3d85 692 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
fda6f272
TH
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);
e43473b7
VG
697}
698
699/* Determine if previously allocated or extended slice is complete or not */
0f3457f6 700static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
e43473b7
VG
701{
702 if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
5cf8c227 703 return false;
e43473b7
VG
704
705 return 1;
706}
707
708/* Trim the used slices and adjust slice start accordingly */
0f3457f6 709static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
e43473b7 710{
3aad5d3e
VG
711 unsigned long nr_slices, time_elapsed, io_trim;
712 u64 bytes_trim, tmp;
e43473b7
VG
713
714 BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
715
716 /*
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.
720 */
0f3457f6 721 if (throtl_slice_used(tg, rw))
e43473b7
VG
722 return;
723
d1ae8ffd
VG
724 /*
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.
730 */
731
297e3d85 732 throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
d1ae8ffd 733
e43473b7
VG
734 time_elapsed = jiffies - tg->slice_start[rw];
735
297e3d85 736 nr_slices = time_elapsed / tg->td->throtl_slice;
e43473b7
VG
737
738 if (!nr_slices)
739 return;
297e3d85 740 tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
3aad5d3e
VG
741 do_div(tmp, HZ);
742 bytes_trim = tmp;
e43473b7 743
297e3d85
SL
744 io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
745 HZ;
e43473b7 746
8e89d13f 747 if (!bytes_trim && !io_trim)
e43473b7
VG
748 return;
749
750 if (tg->bytes_disp[rw] >= bytes_trim)
751 tg->bytes_disp[rw] -= bytes_trim;
752 else
753 tg->bytes_disp[rw] = 0;
754
8e89d13f
VG
755 if (tg->io_disp[rw] >= io_trim)
756 tg->io_disp[rw] -= io_trim;
757 else
758 tg->io_disp[rw] = 0;
759
297e3d85 760 tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
e43473b7 761
fda6f272
TH
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);
e43473b7
VG
766}
767
0f3457f6
TH
768static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
769 unsigned long *wait)
e43473b7
VG
770{
771 bool rw = bio_data_dir(bio);
8e89d13f 772 unsigned int io_allowed;
e43473b7 773 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
c49c06e4 774 u64 tmp;
e43473b7 775
8e89d13f 776 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
e43473b7 777
8e89d13f
VG
778 /* Slice has just started. Consider one slice interval */
779 if (!jiffy_elapsed)
297e3d85 780 jiffy_elapsed_rnd = tg->td->throtl_slice;
8e89d13f 781
297e3d85 782 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
8e89d13f 783
c49c06e4
VG
784 /*
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
788 * have been trimmed.
789 */
790
9f626e37 791 tmp = (u64)tg_iops_limit(tg, rw) * jiffy_elapsed_rnd;
c49c06e4
VG
792 do_div(tmp, HZ);
793
794 if (tmp > UINT_MAX)
795 io_allowed = UINT_MAX;
796 else
797 io_allowed = tmp;
8e89d13f
VG
798
799 if (tg->io_disp[rw] + 1 <= io_allowed) {
e43473b7
VG
800 if (wait)
801 *wait = 0;
5cf8c227 802 return true;
e43473b7
VG
803 }
804
8e89d13f 805 /* Calc approx time to dispatch */
9f626e37 806 jiffy_wait = ((tg->io_disp[rw] + 1) * HZ) / tg_iops_limit(tg, rw) + 1;
8e89d13f
VG
807
808 if (jiffy_wait > jiffy_elapsed)
809 jiffy_wait = jiffy_wait - jiffy_elapsed;
810 else
811 jiffy_wait = 1;
812
813 if (wait)
814 *wait = jiffy_wait;
815 return 0;
816}
817
0f3457f6
TH
818static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
819 unsigned long *wait)
8e89d13f
VG
820{
821 bool rw = bio_data_dir(bio);
3aad5d3e 822 u64 bytes_allowed, extra_bytes, tmp;
8e89d13f 823 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
e43473b7
VG
824
825 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
826
827 /* Slice has just started. Consider one slice interval */
828 if (!jiffy_elapsed)
297e3d85 829 jiffy_elapsed_rnd = tg->td->throtl_slice;
e43473b7 830
297e3d85 831 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
e43473b7 832
9f626e37 833 tmp = tg_bps_limit(tg, rw) * jiffy_elapsed_rnd;
5e901a2b 834 do_div(tmp, HZ);
3aad5d3e 835 bytes_allowed = tmp;
e43473b7 836
4f024f37 837 if (tg->bytes_disp[rw] + bio->bi_iter.bi_size <= bytes_allowed) {
e43473b7
VG
838 if (wait)
839 *wait = 0;
5cf8c227 840 return true;
e43473b7
VG
841 }
842
843 /* Calc approx time to dispatch */
4f024f37 844 extra_bytes = tg->bytes_disp[rw] + bio->bi_iter.bi_size - bytes_allowed;
9f626e37 845 jiffy_wait = div64_u64(extra_bytes * HZ, tg_bps_limit(tg, rw));
e43473b7
VG
846
847 if (!jiffy_wait)
848 jiffy_wait = 1;
849
850 /*
851 * This wait time is without taking into consideration the rounding
852 * up we did. Add that time also.
853 */
854 jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
e43473b7
VG
855 if (wait)
856 *wait = jiffy_wait;
8e89d13f
VG
857 return 0;
858}
859
860/*
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
863 */
0f3457f6
TH
864static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
865 unsigned long *wait)
8e89d13f
VG
866{
867 bool rw = bio_data_dir(bio);
868 unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
869
870 /*
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
874 * queued.
875 */
73f0d49a 876 BUG_ON(tg->service_queue.nr_queued[rw] &&
c5cc2070 877 bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
e43473b7 878
8e89d13f 879 /* If tg->bps = -1, then BW is unlimited */
9f626e37
SL
880 if (tg_bps_limit(tg, rw) == U64_MAX &&
881 tg_iops_limit(tg, rw) == UINT_MAX) {
8e89d13f
VG
882 if (wait)
883 *wait = 0;
5cf8c227 884 return true;
8e89d13f
VG
885 }
886
887 /*
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
164c80ed
VG
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.
8e89d13f 893 */
164c80ed 894 if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
0f3457f6 895 throtl_start_new_slice(tg, rw);
8e89d13f 896 else {
297e3d85
SL
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);
8e89d13f
VG
901 }
902
0f3457f6
TH
903 if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
904 tg_with_in_iops_limit(tg, bio, &iops_wait)) {
8e89d13f
VG
905 if (wait)
906 *wait = 0;
907 return 1;
908 }
909
910 max_wait = max(bps_wait, iops_wait);
911
912 if (wait)
913 *wait = max_wait;
914
915 if (time_before(tg->slice_end[rw], jiffies + max_wait))
0f3457f6 916 throtl_extend_slice(tg, rw, jiffies + max_wait);
e43473b7
VG
917
918 return 0;
919}
920
921static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
922{
923 bool rw = bio_data_dir(bio);
e43473b7
VG
924
925 /* Charge the bio to the group */
4f024f37 926 tg->bytes_disp[rw] += bio->bi_iter.bi_size;
8e89d13f 927 tg->io_disp[rw]++;
3f0abd80
SL
928 tg->last_bytes_disp[rw] += bio->bi_iter.bi_size;
929 tg->last_io_disp[rw]++;
e43473b7 930
2a0f61e6 931 /*
8d2bbd4c 932 * BIO_THROTTLED is used to prevent the same bio to be throttled
2a0f61e6
TH
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.
2a0f61e6 936 */
8d2bbd4c
CH
937 if (!bio_flagged(bio, BIO_THROTTLED))
938 bio_set_flag(bio, BIO_THROTTLED);
e43473b7
VG
939}
940
c5cc2070
TH
941/**
942 * throtl_add_bio_tg - add a bio to the specified throtl_grp
943 * @bio: bio to add
944 * @qn: qnode to use
945 * @tg: the target throtl_grp
946 *
947 * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
948 * tg->qnode_on_self[] is used.
949 */
950static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
951 struct throtl_grp *tg)
e43473b7 952{
73f0d49a 953 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
954 bool rw = bio_data_dir(bio);
955
c5cc2070
TH
956 if (!qn)
957 qn = &tg->qnode_on_self[rw];
958
0e9f4164
TH
959 /*
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().
964 */
965 if (!sq->nr_queued[rw])
966 tg->flags |= THROTL_TG_WAS_EMPTY;
967
c5cc2070
TH
968 throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
969
73f0d49a 970 sq->nr_queued[rw]++;
77216b04 971 throtl_enqueue_tg(tg);
e43473b7
VG
972}
973
77216b04 974static void tg_update_disptime(struct throtl_grp *tg)
e43473b7 975{
73f0d49a 976 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
977 unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
978 struct bio *bio;
979
d609af3a
ME
980 bio = throtl_peek_queued(&sq->queued[READ]);
981 if (bio)
0f3457f6 982 tg_may_dispatch(tg, bio, &read_wait);
e43473b7 983
d609af3a
ME
984 bio = throtl_peek_queued(&sq->queued[WRITE]);
985 if (bio)
0f3457f6 986 tg_may_dispatch(tg, bio, &write_wait);
e43473b7
VG
987
988 min_wait = min(read_wait, write_wait);
989 disptime = jiffies + min_wait;
990
e43473b7 991 /* Update dispatch time */
77216b04 992 throtl_dequeue_tg(tg);
e43473b7 993 tg->disptime = disptime;
77216b04 994 throtl_enqueue_tg(tg);
0e9f4164
TH
995
996 /* see throtl_add_bio_tg() */
997 tg->flags &= ~THROTL_TG_WAS_EMPTY;
e43473b7
VG
998}
999
32ee5bc4
VG
1000static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
1001 struct throtl_grp *parent_tg, bool rw)
1002{
1003 if (throtl_slice_used(parent_tg, rw)) {
1004 throtl_start_new_slice_with_credit(parent_tg, rw,
1005 child_tg->slice_start[rw]);
1006 }
1007
1008}
1009
77216b04 1010static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
e43473b7 1011{
73f0d49a 1012 struct throtl_service_queue *sq = &tg->service_queue;
6bc9c2b4
TH
1013 struct throtl_service_queue *parent_sq = sq->parent_sq;
1014 struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
c5cc2070 1015 struct throtl_grp *tg_to_put = NULL;
e43473b7
VG
1016 struct bio *bio;
1017
c5cc2070
TH
1018 /*
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.
1023 */
1024 bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
73f0d49a 1025 sq->nr_queued[rw]--;
e43473b7
VG
1026
1027 throtl_charge_bio(tg, bio);
6bc9c2b4
TH
1028
1029 /*
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.
1035 */
1036 if (parent_tg) {
c5cc2070 1037 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
32ee5bc4 1038 start_parent_slice_with_credit(tg, parent_tg, rw);
6bc9c2b4 1039 } else {
c5cc2070
TH
1040 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1041 &parent_sq->queued[rw]);
6bc9c2b4
TH
1042 BUG_ON(tg->td->nr_queued[rw] <= 0);
1043 tg->td->nr_queued[rw]--;
1044 }
e43473b7 1045
0f3457f6 1046 throtl_trim_slice(tg, rw);
6bc9c2b4 1047
c5cc2070
TH
1048 if (tg_to_put)
1049 blkg_put(tg_to_blkg(tg_to_put));
e43473b7
VG
1050}
1051
77216b04 1052static int throtl_dispatch_tg(struct throtl_grp *tg)
e43473b7 1053{
73f0d49a 1054 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
1055 unsigned int nr_reads = 0, nr_writes = 0;
1056 unsigned int max_nr_reads = throtl_grp_quantum*3/4;
c2f6805d 1057 unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
e43473b7
VG
1058 struct bio *bio;
1059
1060 /* Try to dispatch 75% READS and 25% WRITES */
1061
c5cc2070 1062 while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
0f3457f6 1063 tg_may_dispatch(tg, bio, NULL)) {
e43473b7 1064
77216b04 1065 tg_dispatch_one_bio(tg, bio_data_dir(bio));
e43473b7
VG
1066 nr_reads++;
1067
1068 if (nr_reads >= max_nr_reads)
1069 break;
1070 }
1071
c5cc2070 1072 while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
0f3457f6 1073 tg_may_dispatch(tg, bio, NULL)) {
e43473b7 1074
77216b04 1075 tg_dispatch_one_bio(tg, bio_data_dir(bio));
e43473b7
VG
1076 nr_writes++;
1077
1078 if (nr_writes >= max_nr_writes)
1079 break;
1080 }
1081
1082 return nr_reads + nr_writes;
1083}
1084
651930bc 1085static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
e43473b7
VG
1086{
1087 unsigned int nr_disp = 0;
e43473b7
VG
1088
1089 while (1) {
73f0d49a
TH
1090 struct throtl_grp *tg = throtl_rb_first(parent_sq);
1091 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
1092
1093 if (!tg)
1094 break;
1095
1096 if (time_before(jiffies, tg->disptime))
1097 break;
1098
77216b04 1099 throtl_dequeue_tg(tg);
e43473b7 1100
77216b04 1101 nr_disp += throtl_dispatch_tg(tg);
e43473b7 1102
73f0d49a 1103 if (sq->nr_queued[0] || sq->nr_queued[1])
77216b04 1104 tg_update_disptime(tg);
e43473b7
VG
1105
1106 if (nr_disp >= throtl_quantum)
1107 break;
1108 }
1109
1110 return nr_disp;
1111}
1112
c79892c5
SL
1113static bool throtl_can_upgrade(struct throtl_data *td,
1114 struct throtl_grp *this_tg);
6e1a5704
TH
1115/**
1116 * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1117 * @arg: the throtl_service_queue being serviced
1118 *
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
2e48a530
TH
1122 * dispatches bio's from the children throtl_grps to the parent
1123 * service_queue.
1124 *
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.
6e1a5704 1129 */
69df0ab0
TH
1130static void throtl_pending_timer_fn(unsigned long arg)
1131{
1132 struct throtl_service_queue *sq = (void *)arg;
2e48a530 1133 struct throtl_grp *tg = sq_to_tg(sq);
69df0ab0 1134 struct throtl_data *td = sq_to_td(sq);
cb76199c 1135 struct request_queue *q = td->queue;
2e48a530
TH
1136 struct throtl_service_queue *parent_sq;
1137 bool dispatched;
6e1a5704 1138 int ret;
e43473b7
VG
1139
1140 spin_lock_irq(q->queue_lock);
c79892c5
SL
1141 if (throtl_can_upgrade(td, NULL))
1142 throtl_upgrade_state(td);
1143
2e48a530
TH
1144again:
1145 parent_sq = sq->parent_sq;
1146 dispatched = false;
e43473b7 1147
7f52f98c
TH
1148 while (true) {
1149 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
2e48a530
TH
1150 sq->nr_queued[READ] + sq->nr_queued[WRITE],
1151 sq->nr_queued[READ], sq->nr_queued[WRITE]);
7f52f98c
TH
1152
1153 ret = throtl_select_dispatch(sq);
1154 if (ret) {
7f52f98c
TH
1155 throtl_log(sq, "bios disp=%u", ret);
1156 dispatched = true;
1157 }
e43473b7 1158
7f52f98c
TH
1159 if (throtl_schedule_next_dispatch(sq, false))
1160 break;
e43473b7 1161
7f52f98c
TH
1162 /* this dispatch windows is still open, relax and repeat */
1163 spin_unlock_irq(q->queue_lock);
1164 cpu_relax();
1165 spin_lock_irq(q->queue_lock);
651930bc 1166 }
e43473b7 1167
2e48a530
TH
1168 if (!dispatched)
1169 goto out_unlock;
6e1a5704 1170
2e48a530
TH
1171 if (parent_sq) {
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 */
1177 sq = parent_sq;
1178 tg = sq_to_tg(sq);
1179 goto again;
1180 }
1181 }
1182 } else {
1183 /* reached the top-level, queue issueing */
1184 queue_work(kthrotld_workqueue, &td->dispatch_work);
1185 }
1186out_unlock:
e43473b7 1187 spin_unlock_irq(q->queue_lock);
6e1a5704 1188}
e43473b7 1189
6e1a5704
TH
1190/**
1191 * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1192 * @work: work item being executed
1193 *
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
1196 * function.
1197 */
8876e140 1198static void blk_throtl_dispatch_work_fn(struct work_struct *work)
6e1a5704
TH
1199{
1200 struct throtl_data *td = container_of(work, struct throtl_data,
1201 dispatch_work);
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;
1205 struct bio *bio;
1206 struct blk_plug plug;
1207 int rw;
1208
1209 bio_list_init(&bio_list_on_stack);
1210
1211 spin_lock_irq(q->queue_lock);
c5cc2070
TH
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);
6e1a5704
TH
1215 spin_unlock_irq(q->queue_lock);
1216
1217 if (!bio_list_empty(&bio_list_on_stack)) {
69d60eb9 1218 blk_start_plug(&plug);
e43473b7
VG
1219 while((bio = bio_list_pop(&bio_list_on_stack)))
1220 generic_make_request(bio);
69d60eb9 1221 blk_finish_plug(&plug);
e43473b7 1222 }
e43473b7
VG
1223}
1224
f95a04af
TH
1225static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1226 int off)
60c2bc2d 1227{
f95a04af
TH
1228 struct throtl_grp *tg = pd_to_tg(pd);
1229 u64 v = *(u64 *)((void *)tg + off);
60c2bc2d 1230
2ab5492d 1231 if (v == U64_MAX)
60c2bc2d 1232 return 0;
f95a04af 1233 return __blkg_prfill_u64(sf, pd, v);
60c2bc2d
TH
1234}
1235
f95a04af
TH
1236static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1237 int off)
e43473b7 1238{
f95a04af
TH
1239 struct throtl_grp *tg = pd_to_tg(pd);
1240 unsigned int v = *(unsigned int *)((void *)tg + off);
fe071437 1241
2ab5492d 1242 if (v == UINT_MAX)
af133ceb 1243 return 0;
f95a04af 1244 return __blkg_prfill_u64(sf, pd, v);
e43473b7
VG
1245}
1246
2da8ca82 1247static int tg_print_conf_u64(struct seq_file *sf, void *v)
8e89d13f 1248{
2da8ca82
TH
1249 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1250 &blkcg_policy_throtl, seq_cft(sf)->private, false);
af133ceb 1251 return 0;
8e89d13f
VG
1252}
1253
2da8ca82 1254static int tg_print_conf_uint(struct seq_file *sf, void *v)
8e89d13f 1255{
2da8ca82
TH
1256 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1257 &blkcg_policy_throtl, seq_cft(sf)->private, false);
af133ceb 1258 return 0;
60c2bc2d
TH
1259}
1260
69948b07 1261static void tg_conf_updated(struct throtl_grp *tg)
60c2bc2d 1262{
69948b07 1263 struct throtl_service_queue *sq = &tg->service_queue;
492eb21b 1264 struct cgroup_subsys_state *pos_css;
69948b07 1265 struct blkcg_gq *blkg;
af133ceb 1266
fda6f272
TH
1267 throtl_log(&tg->service_queue,
1268 "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
9f626e37
SL
1269 tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1270 tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
632b4493 1271
693e751e
TH
1272 /*
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
1277 * blk-throttle.
1278 */
69948b07 1279 blkg_for_each_descendant_pre(blkg, pos_css, tg_to_blkg(tg))
693e751e
TH
1280 tg_update_has_rules(blkg_to_tg(blkg));
1281
632b4493
TH
1282 /*
1283 * We're already holding queue_lock and know @tg is valid. Let's
1284 * apply the new config directly.
1285 *
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.
1289 */
0f3457f6
TH
1290 throtl_start_new_slice(tg, 0);
1291 throtl_start_new_slice(tg, 1);
632b4493 1292
5b2c16aa 1293 if (tg->flags & THROTL_TG_PENDING) {
77216b04 1294 tg_update_disptime(tg);
7f52f98c 1295 throtl_schedule_next_dispatch(sq->parent_sq, true);
632b4493 1296 }
69948b07
TH
1297}
1298
1299static ssize_t tg_set_conf(struct kernfs_open_file *of,
1300 char *buf, size_t nbytes, loff_t off, bool is_u64)
1301{
1302 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1303 struct blkg_conf_ctx ctx;
1304 struct throtl_grp *tg;
1305 int ret;
1306 u64 v;
1307
1308 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1309 if (ret)
1310 return ret;
1311
1312 ret = -EINVAL;
1313 if (sscanf(ctx.body, "%llu", &v) != 1)
1314 goto out_finish;
1315 if (!v)
2ab5492d 1316 v = U64_MAX;
69948b07
TH
1317
1318 tg = blkg_to_tg(ctx.blkg);
1319
1320 if (is_u64)
1321 *(u64 *)((void *)tg + of_cft(of)->private) = v;
1322 else
1323 *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
60c2bc2d 1324
69948b07 1325 tg_conf_updated(tg);
36aa9e5f
TH
1326 ret = 0;
1327out_finish:
60c2bc2d 1328 blkg_conf_finish(&ctx);
36aa9e5f 1329 return ret ?: nbytes;
8e89d13f
VG
1330}
1331
451af504
TH
1332static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1333 char *buf, size_t nbytes, loff_t off)
60c2bc2d 1334{
451af504 1335 return tg_set_conf(of, buf, nbytes, off, true);
60c2bc2d
TH
1336}
1337
451af504
TH
1338static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1339 char *buf, size_t nbytes, loff_t off)
60c2bc2d 1340{
451af504 1341 return tg_set_conf(of, buf, nbytes, off, false);
60c2bc2d
TH
1342}
1343
880f50e2 1344static struct cftype throtl_legacy_files[] = {
60c2bc2d
TH
1345 {
1346 .name = "throttle.read_bps_device",
9f626e37 1347 .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
2da8ca82 1348 .seq_show = tg_print_conf_u64,
451af504 1349 .write = tg_set_conf_u64,
60c2bc2d
TH
1350 },
1351 {
1352 .name = "throttle.write_bps_device",
9f626e37 1353 .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
2da8ca82 1354 .seq_show = tg_print_conf_u64,
451af504 1355 .write = tg_set_conf_u64,
60c2bc2d
TH
1356 },
1357 {
1358 .name = "throttle.read_iops_device",
9f626e37 1359 .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
2da8ca82 1360 .seq_show = tg_print_conf_uint,
451af504 1361 .write = tg_set_conf_uint,
60c2bc2d
TH
1362 },
1363 {
1364 .name = "throttle.write_iops_device",
9f626e37 1365 .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
2da8ca82 1366 .seq_show = tg_print_conf_uint,
451af504 1367 .write = tg_set_conf_uint,
60c2bc2d
TH
1368 },
1369 {
1370 .name = "throttle.io_service_bytes",
77ea7338
TH
1371 .private = (unsigned long)&blkcg_policy_throtl,
1372 .seq_show = blkg_print_stat_bytes,
60c2bc2d
TH
1373 },
1374 {
1375 .name = "throttle.io_serviced",
77ea7338
TH
1376 .private = (unsigned long)&blkcg_policy_throtl,
1377 .seq_show = blkg_print_stat_ios,
60c2bc2d
TH
1378 },
1379 { } /* terminate */
1380};
1381
cd5ab1b0 1382static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
2ee867dc
TH
1383 int off)
1384{
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" };
cd5ab1b0
SL
1388 u64 bps_dft;
1389 unsigned int iops_dft;
2ee867dc
TH
1390
1391 if (!dname)
1392 return 0;
9f626e37 1393
cd5ab1b0
SL
1394 if (off == LIMIT_LOW) {
1395 bps_dft = 0;
1396 iops_dft = 0;
1397 } else {
1398 bps_dft = U64_MAX;
1399 iops_dft = UINT_MAX;
1400 }
1401
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)
2ee867dc
TH
1406 return 0;
1407
cd5ab1b0 1408 if (tg->bps_conf[READ][off] != bps_dft)
9f626e37 1409 snprintf(bufs[0], sizeof(bufs[0]), "%llu",
cd5ab1b0
SL
1410 tg->bps_conf[READ][off]);
1411 if (tg->bps_conf[WRITE][off] != bps_dft)
9f626e37 1412 snprintf(bufs[1], sizeof(bufs[1]), "%llu",
cd5ab1b0
SL
1413 tg->bps_conf[WRITE][off]);
1414 if (tg->iops_conf[READ][off] != iops_dft)
9f626e37 1415 snprintf(bufs[2], sizeof(bufs[2]), "%u",
cd5ab1b0
SL
1416 tg->iops_conf[READ][off]);
1417 if (tg->iops_conf[WRITE][off] != iops_dft)
9f626e37 1418 snprintf(bufs[3], sizeof(bufs[3]), "%u",
cd5ab1b0 1419 tg->iops_conf[WRITE][off]);
2ee867dc
TH
1420
1421 seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s\n",
1422 dname, bufs[0], bufs[1], bufs[2], bufs[3]);
1423 return 0;
1424}
1425
cd5ab1b0 1426static int tg_print_limit(struct seq_file *sf, void *v)
2ee867dc 1427{
cd5ab1b0 1428 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
2ee867dc
TH
1429 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1430 return 0;
1431}
1432
cd5ab1b0 1433static ssize_t tg_set_limit(struct kernfs_open_file *of,
2ee867dc
TH
1434 char *buf, size_t nbytes, loff_t off)
1435{
1436 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1437 struct blkg_conf_ctx ctx;
1438 struct throtl_grp *tg;
1439 u64 v[4];
1440 int ret;
cd5ab1b0 1441 int index = of_cft(of)->private;
2ee867dc
TH
1442
1443 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1444 if (ret)
1445 return ret;
1446
1447 tg = blkg_to_tg(ctx.blkg);
1448
cd5ab1b0
SL
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];
2ee867dc
TH
1453
1454 while (true) {
1455 char tok[27]; /* wiops=18446744073709551616 */
1456 char *p;
2ab5492d 1457 u64 val = U64_MAX;
2ee867dc
TH
1458 int len;
1459
1460 if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
1461 break;
1462 if (tok[0] == '\0')
1463 break;
1464 ctx.body += len;
1465
1466 ret = -EINVAL;
1467 p = tok;
1468 strsep(&p, "=");
1469 if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
1470 goto out_finish;
1471
1472 ret = -ERANGE;
1473 if (!val)
1474 goto out_finish;
1475
1476 ret = -EINVAL;
1477 if (!strcmp(tok, "rbps"))
1478 v[0] = val;
1479 else if (!strcmp(tok, "wbps"))
1480 v[1] = val;
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);
1485 else
1486 goto out_finish;
1487 }
1488
cd5ab1b0
SL
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];
2ee867dc 1493
cd5ab1b0
SL
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];
1499 }
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]);
1508
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;
1513 }
2ee867dc
TH
1514 tg_conf_updated(tg);
1515 ret = 0;
1516out_finish:
1517 blkg_conf_finish(&ctx);
1518 return ret ?: nbytes;
1519}
1520
1521static struct cftype throtl_files[] = {
cd5ab1b0
SL
1522#ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1523 {
1524 .name = "low",
1525 .flags = CFTYPE_NOT_ON_ROOT,
1526 .seq_show = tg_print_limit,
1527 .write = tg_set_limit,
1528 .private = LIMIT_LOW,
1529 },
1530#endif
2ee867dc
TH
1531 {
1532 .name = "max",
1533 .flags = CFTYPE_NOT_ON_ROOT,
cd5ab1b0
SL
1534 .seq_show = tg_print_limit,
1535 .write = tg_set_limit,
1536 .private = LIMIT_MAX,
2ee867dc
TH
1537 },
1538 { } /* terminate */
1539};
1540
da527770 1541static void throtl_shutdown_wq(struct request_queue *q)
e43473b7
VG
1542{
1543 struct throtl_data *td = q->td;
1544
69df0ab0 1545 cancel_work_sync(&td->dispatch_work);
e43473b7
VG
1546}
1547
3c798398 1548static struct blkcg_policy blkcg_policy_throtl = {
2ee867dc 1549 .dfl_cftypes = throtl_files,
880f50e2 1550 .legacy_cftypes = throtl_legacy_files,
f9fcc2d3 1551
001bea73 1552 .pd_alloc_fn = throtl_pd_alloc,
f9fcc2d3 1553 .pd_init_fn = throtl_pd_init,
693e751e 1554 .pd_online_fn = throtl_pd_online,
cd5ab1b0 1555 .pd_offline_fn = throtl_pd_offline,
001bea73 1556 .pd_free_fn = throtl_pd_free,
e43473b7
VG
1557};
1558
3f0abd80
SL
1559static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
1560{
1561 unsigned long rtime = jiffies, wtime = jiffies;
1562
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);
1568}
1569
1570/* tg should not be an intermediate node */
1571static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
1572{
1573 struct throtl_service_queue *parent_sq;
1574 struct throtl_grp *parent = tg;
1575 unsigned long ret = __tg_last_low_overflow_time(tg);
1576
1577 while (true) {
1578 parent_sq = parent->service_queue.parent_sq;
1579 parent = sq_to_tg(parent_sq);
1580 if (!parent)
1581 break;
1582
1583 /*
1584 * The parent doesn't have low limit, it always reaches low
1585 * limit. Its overflow time is useless for children
1586 */
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])
1591 continue;
1592 if (time_after(__tg_last_low_overflow_time(parent), ret))
1593 ret = __tg_last_low_overflow_time(parent);
1594 }
1595 return ret;
1596}
1597
c79892c5
SL
1598static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
1599{
1600 struct throtl_service_queue *sq = &tg->service_queue;
1601 bool read_limit, write_limit;
1602
1603 /*
1604 * if cgroup reaches low limit (if low limit is 0, the cgroup always
1605 * reaches), it's ok to upgrade to next limit
1606 */
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)
1610 return true;
1611 if (read_limit && sq->nr_queued[READ] &&
1612 (!write_limit || sq->nr_queued[WRITE]))
1613 return true;
1614 if (write_limit && sq->nr_queued[WRITE] &&
1615 (!read_limit || sq->nr_queued[READ]))
1616 return true;
1617 return false;
1618}
1619
1620static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
1621{
1622 while (true) {
1623 if (throtl_tg_can_upgrade(tg))
1624 return true;
1625 tg = sq_to_tg(tg->service_queue.parent_sq);
1626 if (!tg || !tg_to_blkg(tg)->parent)
1627 return false;
1628 }
1629 return false;
1630}
1631
1632static bool throtl_can_upgrade(struct throtl_data *td,
1633 struct throtl_grp *this_tg)
1634{
1635 struct cgroup_subsys_state *pos_css;
1636 struct blkcg_gq *blkg;
1637
1638 if (td->limit_index != LIMIT_LOW)
1639 return false;
1640
297e3d85 1641 if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
3f0abd80
SL
1642 return false;
1643
c79892c5
SL
1644 rcu_read_lock();
1645 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1646 struct throtl_grp *tg = blkg_to_tg(blkg);
1647
1648 if (tg == this_tg)
1649 continue;
1650 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1651 continue;
1652 if (!throtl_hierarchy_can_upgrade(tg)) {
1653 rcu_read_unlock();
1654 return false;
1655 }
1656 }
1657 rcu_read_unlock();
1658 return true;
1659}
1660
1661static void throtl_upgrade_state(struct throtl_data *td)
1662{
1663 struct cgroup_subsys_state *pos_css;
1664 struct blkcg_gq *blkg;
1665
1666 td->limit_index = LIMIT_MAX;
3f0abd80 1667 td->low_upgrade_time = jiffies;
c79892c5
SL
1668 rcu_read_lock();
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;
1672
1673 tg->disptime = jiffies - 1;
1674 throtl_select_dispatch(sq);
1675 throtl_schedule_next_dispatch(sq, false);
1676 }
1677 rcu_read_unlock();
1678 throtl_select_dispatch(&td->service_queue);
1679 throtl_schedule_next_dispatch(&td->service_queue, false);
1680 queue_work(kthrotld_workqueue, &td->dispatch_work);
1681}
1682
3f0abd80
SL
1683static void throtl_downgrade_state(struct throtl_data *td, int new)
1684{
1685 td->limit_index = new;
1686 td->low_downgrade_time = jiffies;
1687}
1688
1689static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
1690{
1691 struct throtl_data *td = tg->td;
1692 unsigned long now = jiffies;
1693
1694 /*
1695 * If cgroup is below low limit, consider downgrade and throttle other
1696 * cgroups
1697 */
297e3d85
SL
1698 if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
1699 time_after_eq(now, tg_last_low_overflow_time(tg) +
1700 td->throtl_slice))
3f0abd80
SL
1701 return true;
1702 return false;
1703}
1704
1705static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
1706{
1707 while (true) {
1708 if (!throtl_tg_can_downgrade(tg))
1709 return false;
1710 tg = sq_to_tg(tg->service_queue.parent_sq);
1711 if (!tg || !tg_to_blkg(tg)->parent)
1712 break;
1713 }
1714 return true;
1715}
1716
1717static void throtl_downgrade_check(struct throtl_grp *tg)
1718{
1719 uint64_t bps;
1720 unsigned int iops;
1721 unsigned long elapsed_time;
1722 unsigned long now = jiffies;
1723
1724 if (tg->td->limit_index != LIMIT_MAX ||
1725 !tg->td->limit_valid[LIMIT_LOW])
1726 return;
1727 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1728 return;
297e3d85 1729 if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
3f0abd80
SL
1730 return;
1731
1732 elapsed_time = now - tg->last_check_time;
1733 tg->last_check_time = now;
1734
297e3d85
SL
1735 if (time_before(now, tg_last_low_overflow_time(tg) +
1736 tg->td->throtl_slice))
3f0abd80
SL
1737 return;
1738
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;
1744 }
1745
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;
1751 }
1752
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;
1757 }
1758
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;
1763 }
1764
1765 /*
1766 * If cgroup is below low limit, consider downgrade and throttle other
1767 * cgroups
1768 */
1769 if (throtl_hierarchy_can_downgrade(tg))
1770 throtl_downgrade_state(tg->td, LIMIT_LOW);
1771
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;
1776}
1777
ae118896
TH
1778bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
1779 struct bio *bio)
e43473b7 1780{
c5cc2070 1781 struct throtl_qnode *qn = NULL;
ae118896 1782 struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
73f0d49a 1783 struct throtl_service_queue *sq;
0e9f4164 1784 bool rw = bio_data_dir(bio);
bc16a4f9 1785 bool throttled = false;
e43473b7 1786
ae118896
TH
1787 WARN_ON_ONCE(!rcu_read_lock_held());
1788
2a0f61e6 1789 /* see throtl_charge_bio() */
8d2bbd4c 1790 if (bio_flagged(bio, BIO_THROTTLED) || !tg->has_rules[rw])
bc16a4f9 1791 goto out;
e43473b7
VG
1792
1793 spin_lock_irq(q->queue_lock);
c9589f03
TH
1794
1795 if (unlikely(blk_queue_bypass(q)))
bc16a4f9 1796 goto out_unlock;
f469a7b4 1797
73f0d49a
TH
1798 sq = &tg->service_queue;
1799
c79892c5 1800again:
9e660acf 1801 while (true) {
3f0abd80
SL
1802 if (tg->last_low_overflow_time[rw] == 0)
1803 tg->last_low_overflow_time[rw] = jiffies;
1804 throtl_downgrade_check(tg);
9e660acf
TH
1805 /* throtl is FIFO - if bios are already queued, should queue */
1806 if (sq->nr_queued[rw])
1807 break;
de701c74 1808
9e660acf 1809 /* if above limits, break to queue */
c79892c5 1810 if (!tg_may_dispatch(tg, bio, NULL)) {
3f0abd80 1811 tg->last_low_overflow_time[rw] = jiffies;
c79892c5
SL
1812 if (throtl_can_upgrade(tg->td, tg)) {
1813 throtl_upgrade_state(tg->td);
1814 goto again;
1815 }
9e660acf 1816 break;
c79892c5 1817 }
9e660acf
TH
1818
1819 /* within limits, let's charge and dispatch directly */
e43473b7 1820 throtl_charge_bio(tg, bio);
04521db0
VG
1821
1822 /*
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
1829 * time.
1830 *
1831 * So keep on trimming slice even if bio is not queued.
1832 */
0f3457f6 1833 throtl_trim_slice(tg, rw);
9e660acf
TH
1834
1835 /*
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.
1839 */
c5cc2070 1840 qn = &tg->qnode_on_parent[rw];
9e660acf
TH
1841 sq = sq->parent_sq;
1842 tg = sq_to_tg(sq);
1843 if (!tg)
1844 goto out_unlock;
e43473b7
VG
1845 }
1846
9e660acf 1847 /* out-of-limit, queue to @tg */
fda6f272
TH
1848 throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
1849 rw == READ ? 'R' : 'W',
9f626e37
SL
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),
fda6f272 1853 sq->nr_queued[READ], sq->nr_queued[WRITE]);
e43473b7 1854
3f0abd80
SL
1855 tg->last_low_overflow_time[rw] = jiffies;
1856
671058fb 1857 bio_associate_current(bio);
6bc9c2b4 1858 tg->td->nr_queued[rw]++;
c5cc2070 1859 throtl_add_bio_tg(bio, qn, tg);
bc16a4f9 1860 throttled = true;
e43473b7 1861
7f52f98c
TH
1862 /*
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.
1867 */
0e9f4164 1868 if (tg->flags & THROTL_TG_WAS_EMPTY) {
77216b04 1869 tg_update_disptime(tg);
7f52f98c 1870 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
e43473b7
VG
1871 }
1872
bc16a4f9 1873out_unlock:
e43473b7 1874 spin_unlock_irq(q->queue_lock);
bc16a4f9 1875out:
2a0f61e6
TH
1876 /*
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
1879 * being issued.
1880 */
1881 if (!throttled)
8d2bbd4c 1882 bio_clear_flag(bio, BIO_THROTTLED);
bc16a4f9 1883 return throttled;
e43473b7
VG
1884}
1885
2a12f0dc
TH
1886/*
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[].
1890 */
1891static void tg_drain_bios(struct throtl_service_queue *parent_sq)
1892{
1893 struct throtl_grp *tg;
1894
1895 while ((tg = throtl_rb_first(parent_sq))) {
1896 struct throtl_service_queue *sq = &tg->service_queue;
1897 struct bio *bio;
1898
1899 throtl_dequeue_tg(tg);
1900
c5cc2070 1901 while ((bio = throtl_peek_queued(&sq->queued[READ])))
2a12f0dc 1902 tg_dispatch_one_bio(tg, bio_data_dir(bio));
c5cc2070 1903 while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
2a12f0dc
TH
1904 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1905 }
1906}
1907
c9a929dd
TH
1908/**
1909 * blk_throtl_drain - drain throttled bios
1910 * @q: request_queue to drain throttled bios for
1911 *
1912 * Dispatch all currently throttled bios on @q through ->make_request_fn().
1913 */
1914void blk_throtl_drain(struct request_queue *q)
1915 __releases(q->queue_lock) __acquires(q->queue_lock)
1916{
1917 struct throtl_data *td = q->td;
2a12f0dc 1918 struct blkcg_gq *blkg;
492eb21b 1919 struct cgroup_subsys_state *pos_css;
c9a929dd 1920 struct bio *bio;
651930bc 1921 int rw;
c9a929dd 1922
8bcb6c7d 1923 queue_lockdep_assert_held(q);
2a12f0dc 1924 rcu_read_lock();
c9a929dd 1925
2a12f0dc
TH
1926 /*
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
1930 * easier.
1931 */
492eb21b 1932 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
2a12f0dc 1933 tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
73f0d49a 1934
2a12f0dc
TH
1935 /* finally, transfer bios from top-level tg's into the td */
1936 tg_drain_bios(&td->service_queue);
1937
1938 rcu_read_unlock();
c9a929dd
TH
1939 spin_unlock_irq(q->queue_lock);
1940
2a12f0dc 1941 /* all bios now should be in td->service_queue, issue them */
651930bc 1942 for (rw = READ; rw <= WRITE; rw++)
c5cc2070
TH
1943 while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
1944 NULL)))
651930bc 1945 generic_make_request(bio);
c9a929dd
TH
1946
1947 spin_lock_irq(q->queue_lock);
1948}
1949
e43473b7
VG
1950int blk_throtl_init(struct request_queue *q)
1951{
1952 struct throtl_data *td;
a2b1693b 1953 int ret;
e43473b7
VG
1954
1955 td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
1956 if (!td)
1957 return -ENOMEM;
1958
69df0ab0 1959 INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
b2ce2643 1960 throtl_service_queue_init(&td->service_queue);
e43473b7 1961
cd1604fa 1962 q->td = td;
29b12589 1963 td->queue = q;
297e3d85 1964 td->throtl_slice = DFL_THROTL_SLICE;
02977e4a 1965
9f626e37 1966 td->limit_valid[LIMIT_MAX] = true;
cd5ab1b0 1967 td->limit_index = LIMIT_MAX;
3f0abd80
SL
1968 td->low_upgrade_time = jiffies;
1969 td->low_downgrade_time = jiffies;
a2b1693b 1970 /* activate policy */
3c798398 1971 ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
a2b1693b 1972 if (ret)
f51b802c 1973 kfree(td);
a2b1693b 1974 return ret;
e43473b7
VG
1975}
1976
1977void blk_throtl_exit(struct request_queue *q)
1978{
c875f4d0 1979 BUG_ON(!q->td);
da527770 1980 throtl_shutdown_wq(q);
3c798398 1981 blkcg_deactivate_policy(q, &blkcg_policy_throtl);
c9a929dd 1982 kfree(q->td);
e43473b7
VG
1983}
1984
297e3d85
SL
1985#ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1986ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
1987{
1988 if (!q->td)
1989 return -EINVAL;
1990 return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
1991}
1992
1993ssize_t blk_throtl_sample_time_store(struct request_queue *q,
1994 const char *page, size_t count)
1995{
1996 unsigned long v;
1997 unsigned long t;
1998
1999 if (!q->td)
2000 return -EINVAL;
2001 if (kstrtoul(page, 10, &v))
2002 return -EINVAL;
2003 t = msecs_to_jiffies(v);
2004 if (t == 0 || t > MAX_THROTL_SLICE)
2005 return -EINVAL;
2006 q->td->throtl_slice = t;
2007 return count;
2008}
2009#endif
2010
e43473b7
VG
2011static int __init throtl_init(void)
2012{
450adcbe
VG
2013 kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2014 if (!kthrotld_workqueue)
2015 panic("Failed to create kthrotld\n");
2016
3c798398 2017 return blkcg_policy_register(&blkcg_policy_throtl);
e43473b7
VG
2018}
2019
2020module_init(throtl_init);