]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - block/blk-throttle.c
blk-throttle: make bandwidth change smooth
[mirror_ubuntu-artful-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
d61fcfa4
SL
21/* Throttling is performed over a slice and after that slice is renewed */
22#define DFL_THROTL_SLICE_HD (HZ / 10)
23#define DFL_THROTL_SLICE_SSD (HZ / 50)
297e3d85 24#define MAX_THROTL_SLICE (HZ)
e43473b7 25
3c798398 26static struct blkcg_policy blkcg_policy_throtl;
0381411e 27
450adcbe
VG
28/* A workqueue to queue throttle related work */
29static struct workqueue_struct *kthrotld_workqueue;
450adcbe 30
c5cc2070
TH
31/*
32 * To implement hierarchical throttling, throtl_grps form a tree and bios
33 * are dispatched upwards level by level until they reach the top and get
34 * issued. When dispatching bios from the children and local group at each
35 * level, if the bios are dispatched into a single bio_list, there's a risk
36 * of a local or child group which can queue many bios at once filling up
37 * the list starving others.
38 *
39 * To avoid such starvation, dispatched bios are queued separately
40 * according to where they came from. When they are again dispatched to
41 * the parent, they're popped in round-robin order so that no single source
42 * hogs the dispatch window.
43 *
44 * throtl_qnode is used to keep the queued bios separated by their sources.
45 * Bios are queued to throtl_qnode which in turn is queued to
46 * throtl_service_queue and then dispatched in round-robin order.
47 *
48 * It's also used to track the reference counts on blkg's. A qnode always
49 * belongs to a throtl_grp and gets queued on itself or the parent, so
50 * incrementing the reference of the associated throtl_grp when a qnode is
51 * queued and decrementing when dequeued is enough to keep the whole blkg
52 * tree pinned while bios are in flight.
53 */
54struct throtl_qnode {
55 struct list_head node; /* service_queue->queued[] */
56 struct bio_list bios; /* queued bios */
57 struct throtl_grp *tg; /* tg this qnode belongs to */
58};
59
c9e0332e 60struct throtl_service_queue {
77216b04
TH
61 struct throtl_service_queue *parent_sq; /* the parent service_queue */
62
73f0d49a
TH
63 /*
64 * Bios queued directly to this service_queue or dispatched from
65 * children throtl_grp's.
66 */
c5cc2070 67 struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
73f0d49a
TH
68 unsigned int nr_queued[2]; /* number of queued bios */
69
70 /*
71 * RB tree of active children throtl_grp's, which are sorted by
72 * their ->disptime.
73 */
c9e0332e
TH
74 struct rb_root pending_tree; /* RB tree of active tgs */
75 struct rb_node *first_pending; /* first node in the tree */
76 unsigned int nr_pending; /* # queued in the tree */
77 unsigned long first_pending_disptime; /* disptime of the first tg */
69df0ab0 78 struct timer_list pending_timer; /* fires on first_pending_disptime */
e43473b7
VG
79};
80
5b2c16aa
TH
81enum tg_state_flags {
82 THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
0e9f4164 83 THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
5b2c16aa
TH
84};
85
e43473b7
VG
86#define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
87
9f626e37 88enum {
cd5ab1b0 89 LIMIT_LOW,
9f626e37
SL
90 LIMIT_MAX,
91 LIMIT_CNT,
92};
93
e43473b7 94struct throtl_grp {
f95a04af
TH
95 /* must be the first member */
96 struct blkg_policy_data pd;
97
c9e0332e 98 /* active throtl group service_queue member */
e43473b7
VG
99 struct rb_node rb_node;
100
0f3457f6
TH
101 /* throtl_data this group belongs to */
102 struct throtl_data *td;
103
49a2f1e3
TH
104 /* this group's service queue */
105 struct throtl_service_queue service_queue;
106
c5cc2070
TH
107 /*
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
113 * qnode_on_self.
114 */
115 struct throtl_qnode qnode_on_self[2];
116 struct throtl_qnode qnode_on_parent[2];
117
e43473b7
VG
118 /*
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.
122 */
123 unsigned long disptime;
124
e43473b7
VG
125 unsigned int flags;
126
693e751e
TH
127 /* are there any throtl rules between this group and td? */
128 bool has_rules[2];
129
cd5ab1b0 130 /* internally used bytes per second rate limits */
9f626e37 131 uint64_t bps[2][LIMIT_CNT];
cd5ab1b0
SL
132 /* user configured bps limits */
133 uint64_t bps_conf[2][LIMIT_CNT];
e43473b7 134
cd5ab1b0 135 /* internally used IOPS limits */
9f626e37 136 unsigned int iops[2][LIMIT_CNT];
cd5ab1b0
SL
137 /* user configured IOPS limits */
138 unsigned int iops_conf[2][LIMIT_CNT];
8e89d13f 139
e43473b7
VG
140 /* Number of bytes disptached in current slice */
141 uint64_t bytes_disp[2];
8e89d13f
VG
142 /* Number of bio's dispatched in current slice */
143 unsigned int io_disp[2];
e43473b7 144
3f0abd80
SL
145 unsigned long last_low_overflow_time[2];
146
147 uint64_t last_bytes_disp[2];
148 unsigned int last_io_disp[2];
149
150 unsigned long last_check_time;
151
aec24246
SL
152 unsigned long last_dispatch_time[2];
153
e43473b7
VG
154 /* When did we start a new slice */
155 unsigned long slice_start[2];
156 unsigned long slice_end[2];
157};
158
159struct throtl_data
160{
e43473b7 161 /* service tree for active throtl groups */
c9e0332e 162 struct throtl_service_queue service_queue;
e43473b7 163
e43473b7
VG
164 struct request_queue *queue;
165
166 /* Total Number of queued bios on READ and WRITE lists */
167 unsigned int nr_queued[2];
168
297e3d85
SL
169 unsigned int throtl_slice;
170
e43473b7 171 /* Work for dispatching throttled bios */
69df0ab0 172 struct work_struct dispatch_work;
9f626e37
SL
173 unsigned int limit_index;
174 bool limit_valid[LIMIT_CNT];
3f0abd80
SL
175
176 unsigned long low_upgrade_time;
177 unsigned long low_downgrade_time;
7394e31f
SL
178
179 unsigned int scale;
e43473b7
VG
180};
181
69df0ab0
TH
182static void throtl_pending_timer_fn(unsigned long arg);
183
f95a04af
TH
184static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
185{
186 return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
187}
188
3c798398 189static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
0381411e 190{
f95a04af 191 return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
0381411e
TH
192}
193
3c798398 194static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
0381411e 195{
f95a04af 196 return pd_to_blkg(&tg->pd);
0381411e
TH
197}
198
fda6f272
TH
199/**
200 * sq_to_tg - return the throl_grp the specified service queue belongs to
201 * @sq: the throtl_service_queue of interest
202 *
203 * Return the throtl_grp @sq belongs to. If @sq is the top-level one
204 * embedded in throtl_data, %NULL is returned.
205 */
206static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
207{
208 if (sq && sq->parent_sq)
209 return container_of(sq, struct throtl_grp, service_queue);
210 else
211 return NULL;
212}
213
214/**
215 * sq_to_td - return throtl_data the specified service queue belongs to
216 * @sq: the throtl_service_queue of interest
217 *
b43daedc 218 * A service_queue can be embedded in either a throtl_grp or throtl_data.
fda6f272
TH
219 * Determine the associated throtl_data accordingly and return it.
220 */
221static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
222{
223 struct throtl_grp *tg = sq_to_tg(sq);
224
225 if (tg)
226 return tg->td;
227 else
228 return container_of(sq, struct throtl_data, service_queue);
229}
230
7394e31f
SL
231/*
232 * cgroup's limit in LIMIT_MAX is scaled if low limit is set. This scale is to
233 * make the IO dispatch more smooth.
234 * Scale up: linearly scale up according to lapsed time since upgrade. For
235 * every throtl_slice, the limit scales up 1/2 .low limit till the
236 * limit hits .max limit
237 * Scale down: exponentially scale down if a cgroup doesn't hit its .low limit
238 */
239static uint64_t throtl_adjusted_limit(uint64_t low, struct throtl_data *td)
240{
241 /* arbitrary value to avoid too big scale */
242 if (td->scale < 4096 && time_after_eq(jiffies,
243 td->low_upgrade_time + td->scale * td->throtl_slice))
244 td->scale = (jiffies - td->low_upgrade_time) / td->throtl_slice;
245
246 return low + (low >> 1) * td->scale;
247}
248
9f626e37
SL
249static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
250{
b22c417c 251 struct blkcg_gq *blkg = tg_to_blkg(tg);
7394e31f 252 struct throtl_data *td;
b22c417c
SL
253 uint64_t ret;
254
255 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
256 return U64_MAX;
7394e31f
SL
257
258 td = tg->td;
259 ret = tg->bps[rw][td->limit_index];
260 if (ret == 0 && td->limit_index == LIMIT_LOW)
b22c417c 261 return tg->bps[rw][LIMIT_MAX];
7394e31f
SL
262
263 if (td->limit_index == LIMIT_MAX && tg->bps[rw][LIMIT_LOW] &&
264 tg->bps[rw][LIMIT_LOW] != tg->bps[rw][LIMIT_MAX]) {
265 uint64_t adjusted;
266
267 adjusted = throtl_adjusted_limit(tg->bps[rw][LIMIT_LOW], td);
268 ret = min(tg->bps[rw][LIMIT_MAX], adjusted);
269 }
b22c417c 270 return ret;
9f626e37
SL
271}
272
273static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
274{
b22c417c 275 struct blkcg_gq *blkg = tg_to_blkg(tg);
7394e31f 276 struct throtl_data *td;
b22c417c
SL
277 unsigned int ret;
278
279 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
280 return UINT_MAX;
7394e31f
SL
281 td = tg->td;
282 ret = tg->iops[rw][td->limit_index];
b22c417c
SL
283 if (ret == 0 && tg->td->limit_index == LIMIT_LOW)
284 return tg->iops[rw][LIMIT_MAX];
7394e31f
SL
285
286 if (td->limit_index == LIMIT_MAX && tg->iops[rw][LIMIT_LOW] &&
287 tg->iops[rw][LIMIT_LOW] != tg->iops[rw][LIMIT_MAX]) {
288 uint64_t adjusted;
289
290 adjusted = throtl_adjusted_limit(tg->iops[rw][LIMIT_LOW], td);
291 if (adjusted > UINT_MAX)
292 adjusted = UINT_MAX;
293 ret = min_t(unsigned int, tg->iops[rw][LIMIT_MAX], adjusted);
294 }
b22c417c 295 return ret;
9f626e37
SL
296}
297
fda6f272
TH
298/**
299 * throtl_log - log debug message via blktrace
300 * @sq: the service_queue being reported
301 * @fmt: printf format string
302 * @args: printf args
303 *
304 * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
305 * throtl_grp; otherwise, just "throtl".
fda6f272
TH
306 */
307#define throtl_log(sq, fmt, args...) do { \
308 struct throtl_grp *__tg = sq_to_tg((sq)); \
309 struct throtl_data *__td = sq_to_td((sq)); \
310 \
311 (void)__td; \
59fa0224
SL
312 if (likely(!blk_trace_note_message_enabled(__td->queue))) \
313 break; \
fda6f272
TH
314 if ((__tg)) { \
315 char __pbuf[128]; \
54e7ed12 316 \
fda6f272
TH
317 blkg_path(tg_to_blkg(__tg), __pbuf, sizeof(__pbuf)); \
318 blk_add_trace_msg(__td->queue, "throtl %s " fmt, __pbuf, ##args); \
319 } else { \
320 blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
321 } \
54e7ed12 322} while (0)
e43473b7 323
c5cc2070
TH
324static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
325{
326 INIT_LIST_HEAD(&qn->node);
327 bio_list_init(&qn->bios);
328 qn->tg = tg;
329}
330
331/**
332 * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
333 * @bio: bio being added
334 * @qn: qnode to add bio to
335 * @queued: the service_queue->queued[] list @qn belongs to
336 *
337 * Add @bio to @qn and put @qn on @queued if it's not already on.
338 * @qn->tg's reference count is bumped when @qn is activated. See the
339 * comment on top of throtl_qnode definition for details.
340 */
341static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
342 struct list_head *queued)
343{
344 bio_list_add(&qn->bios, bio);
345 if (list_empty(&qn->node)) {
346 list_add_tail(&qn->node, queued);
347 blkg_get(tg_to_blkg(qn->tg));
348 }
349}
350
351/**
352 * throtl_peek_queued - peek the first bio on a qnode list
353 * @queued: the qnode list to peek
354 */
355static struct bio *throtl_peek_queued(struct list_head *queued)
356{
357 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
358 struct bio *bio;
359
360 if (list_empty(queued))
361 return NULL;
362
363 bio = bio_list_peek(&qn->bios);
364 WARN_ON_ONCE(!bio);
365 return bio;
366}
367
368/**
369 * throtl_pop_queued - pop the first bio form a qnode list
370 * @queued: the qnode list to pop a bio from
371 * @tg_to_put: optional out argument for throtl_grp to put
372 *
373 * Pop the first bio from the qnode list @queued. After popping, the first
374 * qnode is removed from @queued if empty or moved to the end of @queued so
375 * that the popping order is round-robin.
376 *
377 * When the first qnode is removed, its associated throtl_grp should be put
378 * too. If @tg_to_put is NULL, this function automatically puts it;
379 * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
380 * responsible for putting it.
381 */
382static struct bio *throtl_pop_queued(struct list_head *queued,
383 struct throtl_grp **tg_to_put)
384{
385 struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
386 struct bio *bio;
387
388 if (list_empty(queued))
389 return NULL;
390
391 bio = bio_list_pop(&qn->bios);
392 WARN_ON_ONCE(!bio);
393
394 if (bio_list_empty(&qn->bios)) {
395 list_del_init(&qn->node);
396 if (tg_to_put)
397 *tg_to_put = qn->tg;
398 else
399 blkg_put(tg_to_blkg(qn->tg));
400 } else {
401 list_move_tail(&qn->node, queued);
402 }
403
404 return bio;
405}
406
49a2f1e3 407/* init a service_queue, assumes the caller zeroed it */
b2ce2643 408static void throtl_service_queue_init(struct throtl_service_queue *sq)
49a2f1e3 409{
c5cc2070
TH
410 INIT_LIST_HEAD(&sq->queued[0]);
411 INIT_LIST_HEAD(&sq->queued[1]);
49a2f1e3 412 sq->pending_tree = RB_ROOT;
69df0ab0
TH
413 setup_timer(&sq->pending_timer, throtl_pending_timer_fn,
414 (unsigned long)sq);
415}
416
001bea73
TH
417static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
418{
4fb72036 419 struct throtl_grp *tg;
24bdb8ef 420 int rw;
4fb72036
TH
421
422 tg = kzalloc_node(sizeof(*tg), gfp, node);
423 if (!tg)
77ea7338 424 return NULL;
4fb72036 425
b2ce2643
TH
426 throtl_service_queue_init(&tg->service_queue);
427
428 for (rw = READ; rw <= WRITE; rw++) {
429 throtl_qnode_init(&tg->qnode_on_self[rw], tg);
430 throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
431 }
432
433 RB_CLEAR_NODE(&tg->rb_node);
9f626e37
SL
434 tg->bps[READ][LIMIT_MAX] = U64_MAX;
435 tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
436 tg->iops[READ][LIMIT_MAX] = UINT_MAX;
437 tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
cd5ab1b0
SL
438 tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
439 tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
440 tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
441 tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
442 /* LIMIT_LOW will have default value 0 */
b2ce2643 443
4fb72036 444 return &tg->pd;
001bea73
TH
445}
446
a9520cd6 447static void throtl_pd_init(struct blkg_policy_data *pd)
a29a171e 448{
a9520cd6
TH
449 struct throtl_grp *tg = pd_to_tg(pd);
450 struct blkcg_gq *blkg = tg_to_blkg(tg);
77216b04 451 struct throtl_data *td = blkg->q->td;
b2ce2643 452 struct throtl_service_queue *sq = &tg->service_queue;
cd1604fa 453
9138125b 454 /*
aa6ec29b 455 * If on the default hierarchy, we switch to properly hierarchical
9138125b
TH
456 * behavior where limits on a given throtl_grp are applied to the
457 * whole subtree rather than just the group itself. e.g. If 16M
458 * read_bps limit is set on the root group, the whole system can't
459 * exceed 16M for the device.
460 *
aa6ec29b 461 * If not on the default hierarchy, the broken flat hierarchy
9138125b
TH
462 * behavior is retained where all throtl_grps are treated as if
463 * they're all separate root groups right below throtl_data.
464 * Limits of a group don't interact with limits of other groups
465 * regardless of the position of the group in the hierarchy.
466 */
b2ce2643 467 sq->parent_sq = &td->service_queue;
9e10a130 468 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
b2ce2643 469 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
77216b04 470 tg->td = td;
8a3d2615
TH
471}
472
693e751e
TH
473/*
474 * Set has_rules[] if @tg or any of its parents have limits configured.
475 * This doesn't require walking up to the top of the hierarchy as the
476 * parent's has_rules[] is guaranteed to be correct.
477 */
478static void tg_update_has_rules(struct throtl_grp *tg)
479{
480 struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
9f626e37 481 struct throtl_data *td = tg->td;
693e751e
TH
482 int rw;
483
484 for (rw = READ; rw <= WRITE; rw++)
485 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
9f626e37
SL
486 (td->limit_valid[td->limit_index] &&
487 (tg_bps_limit(tg, rw) != U64_MAX ||
488 tg_iops_limit(tg, rw) != UINT_MAX));
693e751e
TH
489}
490
a9520cd6 491static void throtl_pd_online(struct blkg_policy_data *pd)
693e751e 492{
aec24246 493 struct throtl_grp *tg = pd_to_tg(pd);
693e751e
TH
494 /*
495 * We don't want new groups to escape the limits of its ancestors.
496 * Update has_rules[] after a new group is brought online.
497 */
aec24246
SL
498 tg_update_has_rules(tg);
499 tg->last_dispatch_time[READ] = jiffies;
500 tg->last_dispatch_time[WRITE] = jiffies;
693e751e
TH
501}
502
cd5ab1b0
SL
503static void blk_throtl_update_limit_valid(struct throtl_data *td)
504{
505 struct cgroup_subsys_state *pos_css;
506 struct blkcg_gq *blkg;
507 bool low_valid = false;
508
509 rcu_read_lock();
510 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
511 struct throtl_grp *tg = blkg_to_tg(blkg);
512
513 if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
514 tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
515 low_valid = true;
516 }
517 rcu_read_unlock();
518
519 td->limit_valid[LIMIT_LOW] = low_valid;
520}
521
c79892c5 522static void throtl_upgrade_state(struct throtl_data *td);
cd5ab1b0
SL
523static void throtl_pd_offline(struct blkg_policy_data *pd)
524{
525 struct throtl_grp *tg = pd_to_tg(pd);
526
527 tg->bps[READ][LIMIT_LOW] = 0;
528 tg->bps[WRITE][LIMIT_LOW] = 0;
529 tg->iops[READ][LIMIT_LOW] = 0;
530 tg->iops[WRITE][LIMIT_LOW] = 0;
531
532 blk_throtl_update_limit_valid(tg->td);
533
c79892c5
SL
534 if (!tg->td->limit_valid[tg->td->limit_index])
535 throtl_upgrade_state(tg->td);
cd5ab1b0
SL
536}
537
001bea73
TH
538static void throtl_pd_free(struct blkg_policy_data *pd)
539{
4fb72036
TH
540 struct throtl_grp *tg = pd_to_tg(pd);
541
b2ce2643 542 del_timer_sync(&tg->service_queue.pending_timer);
4fb72036 543 kfree(tg);
001bea73
TH
544}
545
0049af73
TH
546static struct throtl_grp *
547throtl_rb_first(struct throtl_service_queue *parent_sq)
e43473b7
VG
548{
549 /* Service tree is empty */
0049af73 550 if (!parent_sq->nr_pending)
e43473b7
VG
551 return NULL;
552
0049af73
TH
553 if (!parent_sq->first_pending)
554 parent_sq->first_pending = rb_first(&parent_sq->pending_tree);
e43473b7 555
0049af73
TH
556 if (parent_sq->first_pending)
557 return rb_entry_tg(parent_sq->first_pending);
e43473b7
VG
558
559 return NULL;
560}
561
562static void rb_erase_init(struct rb_node *n, struct rb_root *root)
563{
564 rb_erase(n, root);
565 RB_CLEAR_NODE(n);
566}
567
0049af73
TH
568static void throtl_rb_erase(struct rb_node *n,
569 struct throtl_service_queue *parent_sq)
e43473b7 570{
0049af73
TH
571 if (parent_sq->first_pending == n)
572 parent_sq->first_pending = NULL;
573 rb_erase_init(n, &parent_sq->pending_tree);
574 --parent_sq->nr_pending;
e43473b7
VG
575}
576
0049af73 577static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
e43473b7
VG
578{
579 struct throtl_grp *tg;
580
0049af73 581 tg = throtl_rb_first(parent_sq);
e43473b7
VG
582 if (!tg)
583 return;
584
0049af73 585 parent_sq->first_pending_disptime = tg->disptime;
e43473b7
VG
586}
587
77216b04 588static void tg_service_queue_add(struct throtl_grp *tg)
e43473b7 589{
77216b04 590 struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
0049af73 591 struct rb_node **node = &parent_sq->pending_tree.rb_node;
e43473b7
VG
592 struct rb_node *parent = NULL;
593 struct throtl_grp *__tg;
594 unsigned long key = tg->disptime;
595 int left = 1;
596
597 while (*node != NULL) {
598 parent = *node;
599 __tg = rb_entry_tg(parent);
600
601 if (time_before(key, __tg->disptime))
602 node = &parent->rb_left;
603 else {
604 node = &parent->rb_right;
605 left = 0;
606 }
607 }
608
609 if (left)
0049af73 610 parent_sq->first_pending = &tg->rb_node;
e43473b7
VG
611
612 rb_link_node(&tg->rb_node, parent, node);
0049af73 613 rb_insert_color(&tg->rb_node, &parent_sq->pending_tree);
e43473b7
VG
614}
615
77216b04 616static void __throtl_enqueue_tg(struct throtl_grp *tg)
e43473b7 617{
77216b04 618 tg_service_queue_add(tg);
5b2c16aa 619 tg->flags |= THROTL_TG_PENDING;
77216b04 620 tg->service_queue.parent_sq->nr_pending++;
e43473b7
VG
621}
622
77216b04 623static void throtl_enqueue_tg(struct throtl_grp *tg)
e43473b7 624{
5b2c16aa 625 if (!(tg->flags & THROTL_TG_PENDING))
77216b04 626 __throtl_enqueue_tg(tg);
e43473b7
VG
627}
628
77216b04 629static void __throtl_dequeue_tg(struct throtl_grp *tg)
e43473b7 630{
77216b04 631 throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
5b2c16aa 632 tg->flags &= ~THROTL_TG_PENDING;
e43473b7
VG
633}
634
77216b04 635static void throtl_dequeue_tg(struct throtl_grp *tg)
e43473b7 636{
5b2c16aa 637 if (tg->flags & THROTL_TG_PENDING)
77216b04 638 __throtl_dequeue_tg(tg);
e43473b7
VG
639}
640
a9131a27 641/* Call with queue lock held */
69df0ab0
TH
642static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
643 unsigned long expires)
a9131a27 644{
297e3d85 645 unsigned long max_expire = jiffies + 8 * sq_to_tg(sq)->td->throtl_slice;
06cceedc
SL
646
647 /*
648 * Since we are adjusting the throttle limit dynamically, the sleep
649 * time calculated according to previous limit might be invalid. It's
650 * possible the cgroup sleep time is very long and no other cgroups
651 * have IO running so notify the limit changes. Make sure the cgroup
652 * doesn't sleep too long to avoid the missed notification.
653 */
654 if (time_after(expires, max_expire))
655 expires = max_expire;
69df0ab0
TH
656 mod_timer(&sq->pending_timer, expires);
657 throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
658 expires - jiffies, jiffies);
a9131a27
TH
659}
660
7f52f98c
TH
661/**
662 * throtl_schedule_next_dispatch - schedule the next dispatch cycle
663 * @sq: the service_queue to schedule dispatch for
664 * @force: force scheduling
665 *
666 * Arm @sq->pending_timer so that the next dispatch cycle starts on the
667 * dispatch time of the first pending child. Returns %true if either timer
668 * is armed or there's no pending child left. %false if the current
669 * dispatch window is still open and the caller should continue
670 * dispatching.
671 *
672 * If @force is %true, the dispatch timer is always scheduled and this
673 * function is guaranteed to return %true. This is to be used when the
674 * caller can't dispatch itself and needs to invoke pending_timer
675 * unconditionally. Note that forced scheduling is likely to induce short
676 * delay before dispatch starts even if @sq->first_pending_disptime is not
677 * in the future and thus shouldn't be used in hot paths.
678 */
679static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
680 bool force)
e43473b7 681{
6a525600 682 /* any pending children left? */
c9e0332e 683 if (!sq->nr_pending)
7f52f98c 684 return true;
e43473b7 685
c9e0332e 686 update_min_dispatch_time(sq);
e43473b7 687
69df0ab0 688 /* is the next dispatch time in the future? */
7f52f98c 689 if (force || time_after(sq->first_pending_disptime, jiffies)) {
69df0ab0 690 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
7f52f98c 691 return true;
69df0ab0
TH
692 }
693
7f52f98c
TH
694 /* tell the caller to continue dispatching */
695 return false;
e43473b7
VG
696}
697
32ee5bc4
VG
698static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
699 bool rw, unsigned long start)
700{
701 tg->bytes_disp[rw] = 0;
702 tg->io_disp[rw] = 0;
703
704 /*
705 * Previous slice has expired. We must have trimmed it after last
706 * bio dispatch. That means since start of last slice, we never used
707 * that bandwidth. Do try to make use of that bandwidth while giving
708 * credit.
709 */
710 if (time_after_eq(start, tg->slice_start[rw]))
711 tg->slice_start[rw] = start;
712
297e3d85 713 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
32ee5bc4
VG
714 throtl_log(&tg->service_queue,
715 "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
716 rw == READ ? 'R' : 'W', tg->slice_start[rw],
717 tg->slice_end[rw], jiffies);
718}
719
0f3457f6 720static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
e43473b7
VG
721{
722 tg->bytes_disp[rw] = 0;
8e89d13f 723 tg->io_disp[rw] = 0;
e43473b7 724 tg->slice_start[rw] = jiffies;
297e3d85 725 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
fda6f272
TH
726 throtl_log(&tg->service_queue,
727 "[%c] new slice start=%lu end=%lu jiffies=%lu",
728 rw == READ ? 'R' : 'W', tg->slice_start[rw],
729 tg->slice_end[rw], jiffies);
e43473b7
VG
730}
731
0f3457f6
TH
732static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
733 unsigned long jiffy_end)
d1ae8ffd 734{
297e3d85 735 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
d1ae8ffd
VG
736}
737
0f3457f6
TH
738static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
739 unsigned long jiffy_end)
e43473b7 740{
297e3d85 741 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
fda6f272
TH
742 throtl_log(&tg->service_queue,
743 "[%c] extend slice start=%lu end=%lu jiffies=%lu",
744 rw == READ ? 'R' : 'W', tg->slice_start[rw],
745 tg->slice_end[rw], jiffies);
e43473b7
VG
746}
747
748/* Determine if previously allocated or extended slice is complete or not */
0f3457f6 749static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
e43473b7
VG
750{
751 if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
5cf8c227 752 return false;
e43473b7
VG
753
754 return 1;
755}
756
757/* Trim the used slices and adjust slice start accordingly */
0f3457f6 758static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
e43473b7 759{
3aad5d3e
VG
760 unsigned long nr_slices, time_elapsed, io_trim;
761 u64 bytes_trim, tmp;
e43473b7
VG
762
763 BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
764
765 /*
766 * If bps are unlimited (-1), then time slice don't get
767 * renewed. Don't try to trim the slice if slice is used. A new
768 * slice will start when appropriate.
769 */
0f3457f6 770 if (throtl_slice_used(tg, rw))
e43473b7
VG
771 return;
772
d1ae8ffd
VG
773 /*
774 * A bio has been dispatched. Also adjust slice_end. It might happen
775 * that initially cgroup limit was very low resulting in high
776 * slice_end, but later limit was bumped up and bio was dispached
777 * sooner, then we need to reduce slice_end. A high bogus slice_end
778 * is bad because it does not allow new slice to start.
779 */
780
297e3d85 781 throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
d1ae8ffd 782
e43473b7
VG
783 time_elapsed = jiffies - tg->slice_start[rw];
784
297e3d85 785 nr_slices = time_elapsed / tg->td->throtl_slice;
e43473b7
VG
786
787 if (!nr_slices)
788 return;
297e3d85 789 tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
3aad5d3e
VG
790 do_div(tmp, HZ);
791 bytes_trim = tmp;
e43473b7 792
297e3d85
SL
793 io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
794 HZ;
e43473b7 795
8e89d13f 796 if (!bytes_trim && !io_trim)
e43473b7
VG
797 return;
798
799 if (tg->bytes_disp[rw] >= bytes_trim)
800 tg->bytes_disp[rw] -= bytes_trim;
801 else
802 tg->bytes_disp[rw] = 0;
803
8e89d13f
VG
804 if (tg->io_disp[rw] >= io_trim)
805 tg->io_disp[rw] -= io_trim;
806 else
807 tg->io_disp[rw] = 0;
808
297e3d85 809 tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
e43473b7 810
fda6f272
TH
811 throtl_log(&tg->service_queue,
812 "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
813 rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
814 tg->slice_start[rw], tg->slice_end[rw], jiffies);
e43473b7
VG
815}
816
0f3457f6
TH
817static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
818 unsigned long *wait)
e43473b7
VG
819{
820 bool rw = bio_data_dir(bio);
8e89d13f 821 unsigned int io_allowed;
e43473b7 822 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
c49c06e4 823 u64 tmp;
e43473b7 824
8e89d13f 825 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
e43473b7 826
8e89d13f
VG
827 /* Slice has just started. Consider one slice interval */
828 if (!jiffy_elapsed)
297e3d85 829 jiffy_elapsed_rnd = tg->td->throtl_slice;
8e89d13f 830
297e3d85 831 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
8e89d13f 832
c49c06e4
VG
833 /*
834 * jiffy_elapsed_rnd should not be a big value as minimum iops can be
835 * 1 then at max jiffy elapsed should be equivalent of 1 second as we
836 * will allow dispatch after 1 second and after that slice should
837 * have been trimmed.
838 */
839
9f626e37 840 tmp = (u64)tg_iops_limit(tg, rw) * jiffy_elapsed_rnd;
c49c06e4
VG
841 do_div(tmp, HZ);
842
843 if (tmp > UINT_MAX)
844 io_allowed = UINT_MAX;
845 else
846 io_allowed = tmp;
8e89d13f
VG
847
848 if (tg->io_disp[rw] + 1 <= io_allowed) {
e43473b7
VG
849 if (wait)
850 *wait = 0;
5cf8c227 851 return true;
e43473b7
VG
852 }
853
8e89d13f 854 /* Calc approx time to dispatch */
9f626e37 855 jiffy_wait = ((tg->io_disp[rw] + 1) * HZ) / tg_iops_limit(tg, rw) + 1;
8e89d13f
VG
856
857 if (jiffy_wait > jiffy_elapsed)
858 jiffy_wait = jiffy_wait - jiffy_elapsed;
859 else
860 jiffy_wait = 1;
861
862 if (wait)
863 *wait = jiffy_wait;
864 return 0;
865}
866
0f3457f6
TH
867static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
868 unsigned long *wait)
8e89d13f
VG
869{
870 bool rw = bio_data_dir(bio);
3aad5d3e 871 u64 bytes_allowed, extra_bytes, tmp;
8e89d13f 872 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
e43473b7
VG
873
874 jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
875
876 /* Slice has just started. Consider one slice interval */
877 if (!jiffy_elapsed)
297e3d85 878 jiffy_elapsed_rnd = tg->td->throtl_slice;
e43473b7 879
297e3d85 880 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
e43473b7 881
9f626e37 882 tmp = tg_bps_limit(tg, rw) * jiffy_elapsed_rnd;
5e901a2b 883 do_div(tmp, HZ);
3aad5d3e 884 bytes_allowed = tmp;
e43473b7 885
4f024f37 886 if (tg->bytes_disp[rw] + bio->bi_iter.bi_size <= bytes_allowed) {
e43473b7
VG
887 if (wait)
888 *wait = 0;
5cf8c227 889 return true;
e43473b7
VG
890 }
891
892 /* Calc approx time to dispatch */
4f024f37 893 extra_bytes = tg->bytes_disp[rw] + bio->bi_iter.bi_size - bytes_allowed;
9f626e37 894 jiffy_wait = div64_u64(extra_bytes * HZ, tg_bps_limit(tg, rw));
e43473b7
VG
895
896 if (!jiffy_wait)
897 jiffy_wait = 1;
898
899 /*
900 * This wait time is without taking into consideration the rounding
901 * up we did. Add that time also.
902 */
903 jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
e43473b7
VG
904 if (wait)
905 *wait = jiffy_wait;
8e89d13f
VG
906 return 0;
907}
908
909/*
910 * Returns whether one can dispatch a bio or not. Also returns approx number
911 * of jiffies to wait before this bio is with-in IO rate and can be dispatched
912 */
0f3457f6
TH
913static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
914 unsigned long *wait)
8e89d13f
VG
915{
916 bool rw = bio_data_dir(bio);
917 unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
918
919 /*
920 * Currently whole state machine of group depends on first bio
921 * queued in the group bio list. So one should not be calling
922 * this function with a different bio if there are other bios
923 * queued.
924 */
73f0d49a 925 BUG_ON(tg->service_queue.nr_queued[rw] &&
c5cc2070 926 bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
e43473b7 927
8e89d13f 928 /* If tg->bps = -1, then BW is unlimited */
9f626e37
SL
929 if (tg_bps_limit(tg, rw) == U64_MAX &&
930 tg_iops_limit(tg, rw) == UINT_MAX) {
8e89d13f
VG
931 if (wait)
932 *wait = 0;
5cf8c227 933 return true;
8e89d13f
VG
934 }
935
936 /*
937 * If previous slice expired, start a new one otherwise renew/extend
938 * existing slice to make sure it is at least throtl_slice interval
164c80ed
VG
939 * long since now. New slice is started only for empty throttle group.
940 * If there is queued bio, that means there should be an active
941 * slice and it should be extended instead.
8e89d13f 942 */
164c80ed 943 if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
0f3457f6 944 throtl_start_new_slice(tg, rw);
8e89d13f 945 else {
297e3d85
SL
946 if (time_before(tg->slice_end[rw],
947 jiffies + tg->td->throtl_slice))
948 throtl_extend_slice(tg, rw,
949 jiffies + tg->td->throtl_slice);
8e89d13f
VG
950 }
951
0f3457f6
TH
952 if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
953 tg_with_in_iops_limit(tg, bio, &iops_wait)) {
8e89d13f
VG
954 if (wait)
955 *wait = 0;
956 return 1;
957 }
958
959 max_wait = max(bps_wait, iops_wait);
960
961 if (wait)
962 *wait = max_wait;
963
964 if (time_before(tg->slice_end[rw], jiffies + max_wait))
0f3457f6 965 throtl_extend_slice(tg, rw, jiffies + max_wait);
e43473b7
VG
966
967 return 0;
968}
969
970static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
971{
972 bool rw = bio_data_dir(bio);
e43473b7
VG
973
974 /* Charge the bio to the group */
4f024f37 975 tg->bytes_disp[rw] += bio->bi_iter.bi_size;
8e89d13f 976 tg->io_disp[rw]++;
3f0abd80
SL
977 tg->last_bytes_disp[rw] += bio->bi_iter.bi_size;
978 tg->last_io_disp[rw]++;
e43473b7 979
2a0f61e6 980 /*
8d2bbd4c 981 * BIO_THROTTLED is used to prevent the same bio to be throttled
2a0f61e6
TH
982 * more than once as a throttled bio will go through blk-throtl the
983 * second time when it eventually gets issued. Set it when a bio
984 * is being charged to a tg.
2a0f61e6 985 */
8d2bbd4c
CH
986 if (!bio_flagged(bio, BIO_THROTTLED))
987 bio_set_flag(bio, BIO_THROTTLED);
e43473b7
VG
988}
989
c5cc2070
TH
990/**
991 * throtl_add_bio_tg - add a bio to the specified throtl_grp
992 * @bio: bio to add
993 * @qn: qnode to use
994 * @tg: the target throtl_grp
995 *
996 * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
997 * tg->qnode_on_self[] is used.
998 */
999static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
1000 struct throtl_grp *tg)
e43473b7 1001{
73f0d49a 1002 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
1003 bool rw = bio_data_dir(bio);
1004
c5cc2070
TH
1005 if (!qn)
1006 qn = &tg->qnode_on_self[rw];
1007
0e9f4164
TH
1008 /*
1009 * If @tg doesn't currently have any bios queued in the same
1010 * direction, queueing @bio can change when @tg should be
1011 * dispatched. Mark that @tg was empty. This is automatically
1012 * cleaered on the next tg_update_disptime().
1013 */
1014 if (!sq->nr_queued[rw])
1015 tg->flags |= THROTL_TG_WAS_EMPTY;
1016
c5cc2070
TH
1017 throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
1018
73f0d49a 1019 sq->nr_queued[rw]++;
77216b04 1020 throtl_enqueue_tg(tg);
e43473b7
VG
1021}
1022
77216b04 1023static void tg_update_disptime(struct throtl_grp *tg)
e43473b7 1024{
73f0d49a 1025 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
1026 unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
1027 struct bio *bio;
1028
d609af3a
ME
1029 bio = throtl_peek_queued(&sq->queued[READ]);
1030 if (bio)
0f3457f6 1031 tg_may_dispatch(tg, bio, &read_wait);
e43473b7 1032
d609af3a
ME
1033 bio = throtl_peek_queued(&sq->queued[WRITE]);
1034 if (bio)
0f3457f6 1035 tg_may_dispatch(tg, bio, &write_wait);
e43473b7
VG
1036
1037 min_wait = min(read_wait, write_wait);
1038 disptime = jiffies + min_wait;
1039
e43473b7 1040 /* Update dispatch time */
77216b04 1041 throtl_dequeue_tg(tg);
e43473b7 1042 tg->disptime = disptime;
77216b04 1043 throtl_enqueue_tg(tg);
0e9f4164
TH
1044
1045 /* see throtl_add_bio_tg() */
1046 tg->flags &= ~THROTL_TG_WAS_EMPTY;
e43473b7
VG
1047}
1048
32ee5bc4
VG
1049static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
1050 struct throtl_grp *parent_tg, bool rw)
1051{
1052 if (throtl_slice_used(parent_tg, rw)) {
1053 throtl_start_new_slice_with_credit(parent_tg, rw,
1054 child_tg->slice_start[rw]);
1055 }
1056
1057}
1058
77216b04 1059static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
e43473b7 1060{
73f0d49a 1061 struct throtl_service_queue *sq = &tg->service_queue;
6bc9c2b4
TH
1062 struct throtl_service_queue *parent_sq = sq->parent_sq;
1063 struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
c5cc2070 1064 struct throtl_grp *tg_to_put = NULL;
e43473b7
VG
1065 struct bio *bio;
1066
c5cc2070
TH
1067 /*
1068 * @bio is being transferred from @tg to @parent_sq. Popping a bio
1069 * from @tg may put its reference and @parent_sq might end up
1070 * getting released prematurely. Remember the tg to put and put it
1071 * after @bio is transferred to @parent_sq.
1072 */
1073 bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
73f0d49a 1074 sq->nr_queued[rw]--;
e43473b7
VG
1075
1076 throtl_charge_bio(tg, bio);
6bc9c2b4
TH
1077
1078 /*
1079 * If our parent is another tg, we just need to transfer @bio to
1080 * the parent using throtl_add_bio_tg(). If our parent is
1081 * @td->service_queue, @bio is ready to be issued. Put it on its
1082 * bio_lists[] and decrease total number queued. The caller is
1083 * responsible for issuing these bios.
1084 */
1085 if (parent_tg) {
c5cc2070 1086 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
32ee5bc4 1087 start_parent_slice_with_credit(tg, parent_tg, rw);
6bc9c2b4 1088 } else {
c5cc2070
TH
1089 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1090 &parent_sq->queued[rw]);
6bc9c2b4
TH
1091 BUG_ON(tg->td->nr_queued[rw] <= 0);
1092 tg->td->nr_queued[rw]--;
1093 }
e43473b7 1094
0f3457f6 1095 throtl_trim_slice(tg, rw);
6bc9c2b4 1096
c5cc2070
TH
1097 if (tg_to_put)
1098 blkg_put(tg_to_blkg(tg_to_put));
e43473b7
VG
1099}
1100
77216b04 1101static int throtl_dispatch_tg(struct throtl_grp *tg)
e43473b7 1102{
73f0d49a 1103 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
1104 unsigned int nr_reads = 0, nr_writes = 0;
1105 unsigned int max_nr_reads = throtl_grp_quantum*3/4;
c2f6805d 1106 unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
e43473b7
VG
1107 struct bio *bio;
1108
1109 /* Try to dispatch 75% READS and 25% WRITES */
1110
c5cc2070 1111 while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
0f3457f6 1112 tg_may_dispatch(tg, bio, NULL)) {
e43473b7 1113
77216b04 1114 tg_dispatch_one_bio(tg, bio_data_dir(bio));
e43473b7
VG
1115 nr_reads++;
1116
1117 if (nr_reads >= max_nr_reads)
1118 break;
1119 }
1120
c5cc2070 1121 while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
0f3457f6 1122 tg_may_dispatch(tg, bio, NULL)) {
e43473b7 1123
77216b04 1124 tg_dispatch_one_bio(tg, bio_data_dir(bio));
e43473b7
VG
1125 nr_writes++;
1126
1127 if (nr_writes >= max_nr_writes)
1128 break;
1129 }
1130
1131 return nr_reads + nr_writes;
1132}
1133
651930bc 1134static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
e43473b7
VG
1135{
1136 unsigned int nr_disp = 0;
e43473b7
VG
1137
1138 while (1) {
73f0d49a
TH
1139 struct throtl_grp *tg = throtl_rb_first(parent_sq);
1140 struct throtl_service_queue *sq = &tg->service_queue;
e43473b7
VG
1141
1142 if (!tg)
1143 break;
1144
1145 if (time_before(jiffies, tg->disptime))
1146 break;
1147
77216b04 1148 throtl_dequeue_tg(tg);
e43473b7 1149
77216b04 1150 nr_disp += throtl_dispatch_tg(tg);
e43473b7 1151
73f0d49a 1152 if (sq->nr_queued[0] || sq->nr_queued[1])
77216b04 1153 tg_update_disptime(tg);
e43473b7
VG
1154
1155 if (nr_disp >= throtl_quantum)
1156 break;
1157 }
1158
1159 return nr_disp;
1160}
1161
c79892c5
SL
1162static bool throtl_can_upgrade(struct throtl_data *td,
1163 struct throtl_grp *this_tg);
6e1a5704
TH
1164/**
1165 * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1166 * @arg: the throtl_service_queue being serviced
1167 *
1168 * This timer is armed when a child throtl_grp with active bio's become
1169 * pending and queued on the service_queue's pending_tree and expires when
1170 * the first child throtl_grp should be dispatched. This function
2e48a530
TH
1171 * dispatches bio's from the children throtl_grps to the parent
1172 * service_queue.
1173 *
1174 * If the parent's parent is another throtl_grp, dispatching is propagated
1175 * by either arming its pending_timer or repeating dispatch directly. If
1176 * the top-level service_tree is reached, throtl_data->dispatch_work is
1177 * kicked so that the ready bio's are issued.
6e1a5704 1178 */
69df0ab0
TH
1179static void throtl_pending_timer_fn(unsigned long arg)
1180{
1181 struct throtl_service_queue *sq = (void *)arg;
2e48a530 1182 struct throtl_grp *tg = sq_to_tg(sq);
69df0ab0 1183 struct throtl_data *td = sq_to_td(sq);
cb76199c 1184 struct request_queue *q = td->queue;
2e48a530
TH
1185 struct throtl_service_queue *parent_sq;
1186 bool dispatched;
6e1a5704 1187 int ret;
e43473b7
VG
1188
1189 spin_lock_irq(q->queue_lock);
c79892c5
SL
1190 if (throtl_can_upgrade(td, NULL))
1191 throtl_upgrade_state(td);
1192
2e48a530
TH
1193again:
1194 parent_sq = sq->parent_sq;
1195 dispatched = false;
e43473b7 1196
7f52f98c
TH
1197 while (true) {
1198 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
2e48a530
TH
1199 sq->nr_queued[READ] + sq->nr_queued[WRITE],
1200 sq->nr_queued[READ], sq->nr_queued[WRITE]);
7f52f98c
TH
1201
1202 ret = throtl_select_dispatch(sq);
1203 if (ret) {
7f52f98c
TH
1204 throtl_log(sq, "bios disp=%u", ret);
1205 dispatched = true;
1206 }
e43473b7 1207
7f52f98c
TH
1208 if (throtl_schedule_next_dispatch(sq, false))
1209 break;
e43473b7 1210
7f52f98c
TH
1211 /* this dispatch windows is still open, relax and repeat */
1212 spin_unlock_irq(q->queue_lock);
1213 cpu_relax();
1214 spin_lock_irq(q->queue_lock);
651930bc 1215 }
e43473b7 1216
2e48a530
TH
1217 if (!dispatched)
1218 goto out_unlock;
6e1a5704 1219
2e48a530
TH
1220 if (parent_sq) {
1221 /* @parent_sq is another throl_grp, propagate dispatch */
1222 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1223 tg_update_disptime(tg);
1224 if (!throtl_schedule_next_dispatch(parent_sq, false)) {
1225 /* window is already open, repeat dispatching */
1226 sq = parent_sq;
1227 tg = sq_to_tg(sq);
1228 goto again;
1229 }
1230 }
1231 } else {
1232 /* reached the top-level, queue issueing */
1233 queue_work(kthrotld_workqueue, &td->dispatch_work);
1234 }
1235out_unlock:
e43473b7 1236 spin_unlock_irq(q->queue_lock);
6e1a5704 1237}
e43473b7 1238
6e1a5704
TH
1239/**
1240 * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1241 * @work: work item being executed
1242 *
1243 * This function is queued for execution when bio's reach the bio_lists[]
1244 * of throtl_data->service_queue. Those bio's are ready and issued by this
1245 * function.
1246 */
8876e140 1247static void blk_throtl_dispatch_work_fn(struct work_struct *work)
6e1a5704
TH
1248{
1249 struct throtl_data *td = container_of(work, struct throtl_data,
1250 dispatch_work);
1251 struct throtl_service_queue *td_sq = &td->service_queue;
1252 struct request_queue *q = td->queue;
1253 struct bio_list bio_list_on_stack;
1254 struct bio *bio;
1255 struct blk_plug plug;
1256 int rw;
1257
1258 bio_list_init(&bio_list_on_stack);
1259
1260 spin_lock_irq(q->queue_lock);
c5cc2070
TH
1261 for (rw = READ; rw <= WRITE; rw++)
1262 while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
1263 bio_list_add(&bio_list_on_stack, bio);
6e1a5704
TH
1264 spin_unlock_irq(q->queue_lock);
1265
1266 if (!bio_list_empty(&bio_list_on_stack)) {
69d60eb9 1267 blk_start_plug(&plug);
e43473b7
VG
1268 while((bio = bio_list_pop(&bio_list_on_stack)))
1269 generic_make_request(bio);
69d60eb9 1270 blk_finish_plug(&plug);
e43473b7 1271 }
e43473b7
VG
1272}
1273
f95a04af
TH
1274static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1275 int off)
60c2bc2d 1276{
f95a04af
TH
1277 struct throtl_grp *tg = pd_to_tg(pd);
1278 u64 v = *(u64 *)((void *)tg + off);
60c2bc2d 1279
2ab5492d 1280 if (v == U64_MAX)
60c2bc2d 1281 return 0;
f95a04af 1282 return __blkg_prfill_u64(sf, pd, v);
60c2bc2d
TH
1283}
1284
f95a04af
TH
1285static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1286 int off)
e43473b7 1287{
f95a04af
TH
1288 struct throtl_grp *tg = pd_to_tg(pd);
1289 unsigned int v = *(unsigned int *)((void *)tg + off);
fe071437 1290
2ab5492d 1291 if (v == UINT_MAX)
af133ceb 1292 return 0;
f95a04af 1293 return __blkg_prfill_u64(sf, pd, v);
e43473b7
VG
1294}
1295
2da8ca82 1296static int tg_print_conf_u64(struct seq_file *sf, void *v)
8e89d13f 1297{
2da8ca82
TH
1298 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1299 &blkcg_policy_throtl, seq_cft(sf)->private, false);
af133ceb 1300 return 0;
8e89d13f
VG
1301}
1302
2da8ca82 1303static int tg_print_conf_uint(struct seq_file *sf, void *v)
8e89d13f 1304{
2da8ca82
TH
1305 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1306 &blkcg_policy_throtl, seq_cft(sf)->private, false);
af133ceb 1307 return 0;
60c2bc2d
TH
1308}
1309
69948b07 1310static void tg_conf_updated(struct throtl_grp *tg)
60c2bc2d 1311{
69948b07 1312 struct throtl_service_queue *sq = &tg->service_queue;
492eb21b 1313 struct cgroup_subsys_state *pos_css;
69948b07 1314 struct blkcg_gq *blkg;
af133ceb 1315
fda6f272
TH
1316 throtl_log(&tg->service_queue,
1317 "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
9f626e37
SL
1318 tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1319 tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
632b4493 1320
693e751e
TH
1321 /*
1322 * Update has_rules[] flags for the updated tg's subtree. A tg is
1323 * considered to have rules if either the tg itself or any of its
1324 * ancestors has rules. This identifies groups without any
1325 * restrictions in the whole hierarchy and allows them to bypass
1326 * blk-throttle.
1327 */
69948b07 1328 blkg_for_each_descendant_pre(blkg, pos_css, tg_to_blkg(tg))
693e751e
TH
1329 tg_update_has_rules(blkg_to_tg(blkg));
1330
632b4493
TH
1331 /*
1332 * We're already holding queue_lock and know @tg is valid. Let's
1333 * apply the new config directly.
1334 *
1335 * Restart the slices for both READ and WRITES. It might happen
1336 * that a group's limit are dropped suddenly and we don't want to
1337 * account recently dispatched IO with new low rate.
1338 */
0f3457f6
TH
1339 throtl_start_new_slice(tg, 0);
1340 throtl_start_new_slice(tg, 1);
632b4493 1341
5b2c16aa 1342 if (tg->flags & THROTL_TG_PENDING) {
77216b04 1343 tg_update_disptime(tg);
7f52f98c 1344 throtl_schedule_next_dispatch(sq->parent_sq, true);
632b4493 1345 }
69948b07
TH
1346}
1347
1348static ssize_t tg_set_conf(struct kernfs_open_file *of,
1349 char *buf, size_t nbytes, loff_t off, bool is_u64)
1350{
1351 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1352 struct blkg_conf_ctx ctx;
1353 struct throtl_grp *tg;
1354 int ret;
1355 u64 v;
1356
1357 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1358 if (ret)
1359 return ret;
1360
1361 ret = -EINVAL;
1362 if (sscanf(ctx.body, "%llu", &v) != 1)
1363 goto out_finish;
1364 if (!v)
2ab5492d 1365 v = U64_MAX;
69948b07
TH
1366
1367 tg = blkg_to_tg(ctx.blkg);
1368
1369 if (is_u64)
1370 *(u64 *)((void *)tg + of_cft(of)->private) = v;
1371 else
1372 *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
60c2bc2d 1373
69948b07 1374 tg_conf_updated(tg);
36aa9e5f
TH
1375 ret = 0;
1376out_finish:
60c2bc2d 1377 blkg_conf_finish(&ctx);
36aa9e5f 1378 return ret ?: nbytes;
8e89d13f
VG
1379}
1380
451af504
TH
1381static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1382 char *buf, size_t nbytes, loff_t off)
60c2bc2d 1383{
451af504 1384 return tg_set_conf(of, buf, nbytes, off, true);
60c2bc2d
TH
1385}
1386
451af504
TH
1387static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1388 char *buf, size_t nbytes, loff_t off)
60c2bc2d 1389{
451af504 1390 return tg_set_conf(of, buf, nbytes, off, false);
60c2bc2d
TH
1391}
1392
880f50e2 1393static struct cftype throtl_legacy_files[] = {
60c2bc2d
TH
1394 {
1395 .name = "throttle.read_bps_device",
9f626e37 1396 .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
2da8ca82 1397 .seq_show = tg_print_conf_u64,
451af504 1398 .write = tg_set_conf_u64,
60c2bc2d
TH
1399 },
1400 {
1401 .name = "throttle.write_bps_device",
9f626e37 1402 .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
2da8ca82 1403 .seq_show = tg_print_conf_u64,
451af504 1404 .write = tg_set_conf_u64,
60c2bc2d
TH
1405 },
1406 {
1407 .name = "throttle.read_iops_device",
9f626e37 1408 .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
2da8ca82 1409 .seq_show = tg_print_conf_uint,
451af504 1410 .write = tg_set_conf_uint,
60c2bc2d
TH
1411 },
1412 {
1413 .name = "throttle.write_iops_device",
9f626e37 1414 .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
2da8ca82 1415 .seq_show = tg_print_conf_uint,
451af504 1416 .write = tg_set_conf_uint,
60c2bc2d
TH
1417 },
1418 {
1419 .name = "throttle.io_service_bytes",
77ea7338
TH
1420 .private = (unsigned long)&blkcg_policy_throtl,
1421 .seq_show = blkg_print_stat_bytes,
60c2bc2d
TH
1422 },
1423 {
1424 .name = "throttle.io_serviced",
77ea7338
TH
1425 .private = (unsigned long)&blkcg_policy_throtl,
1426 .seq_show = blkg_print_stat_ios,
60c2bc2d
TH
1427 },
1428 { } /* terminate */
1429};
1430
cd5ab1b0 1431static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
2ee867dc
TH
1432 int off)
1433{
1434 struct throtl_grp *tg = pd_to_tg(pd);
1435 const char *dname = blkg_dev_name(pd->blkg);
1436 char bufs[4][21] = { "max", "max", "max", "max" };
cd5ab1b0
SL
1437 u64 bps_dft;
1438 unsigned int iops_dft;
2ee867dc
TH
1439
1440 if (!dname)
1441 return 0;
9f626e37 1442
cd5ab1b0
SL
1443 if (off == LIMIT_LOW) {
1444 bps_dft = 0;
1445 iops_dft = 0;
1446 } else {
1447 bps_dft = U64_MAX;
1448 iops_dft = UINT_MAX;
1449 }
1450
1451 if (tg->bps_conf[READ][off] == bps_dft &&
1452 tg->bps_conf[WRITE][off] == bps_dft &&
1453 tg->iops_conf[READ][off] == iops_dft &&
1454 tg->iops_conf[WRITE][off] == iops_dft)
2ee867dc
TH
1455 return 0;
1456
cd5ab1b0 1457 if (tg->bps_conf[READ][off] != bps_dft)
9f626e37 1458 snprintf(bufs[0], sizeof(bufs[0]), "%llu",
cd5ab1b0
SL
1459 tg->bps_conf[READ][off]);
1460 if (tg->bps_conf[WRITE][off] != bps_dft)
9f626e37 1461 snprintf(bufs[1], sizeof(bufs[1]), "%llu",
cd5ab1b0
SL
1462 tg->bps_conf[WRITE][off]);
1463 if (tg->iops_conf[READ][off] != iops_dft)
9f626e37 1464 snprintf(bufs[2], sizeof(bufs[2]), "%u",
cd5ab1b0
SL
1465 tg->iops_conf[READ][off]);
1466 if (tg->iops_conf[WRITE][off] != iops_dft)
9f626e37 1467 snprintf(bufs[3], sizeof(bufs[3]), "%u",
cd5ab1b0 1468 tg->iops_conf[WRITE][off]);
2ee867dc
TH
1469
1470 seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s\n",
1471 dname, bufs[0], bufs[1], bufs[2], bufs[3]);
1472 return 0;
1473}
1474
cd5ab1b0 1475static int tg_print_limit(struct seq_file *sf, void *v)
2ee867dc 1476{
cd5ab1b0 1477 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
2ee867dc
TH
1478 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1479 return 0;
1480}
1481
cd5ab1b0 1482static ssize_t tg_set_limit(struct kernfs_open_file *of,
2ee867dc
TH
1483 char *buf, size_t nbytes, loff_t off)
1484{
1485 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1486 struct blkg_conf_ctx ctx;
1487 struct throtl_grp *tg;
1488 u64 v[4];
1489 int ret;
cd5ab1b0 1490 int index = of_cft(of)->private;
2ee867dc
TH
1491
1492 ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1493 if (ret)
1494 return ret;
1495
1496 tg = blkg_to_tg(ctx.blkg);
1497
cd5ab1b0
SL
1498 v[0] = tg->bps_conf[READ][index];
1499 v[1] = tg->bps_conf[WRITE][index];
1500 v[2] = tg->iops_conf[READ][index];
1501 v[3] = tg->iops_conf[WRITE][index];
2ee867dc
TH
1502
1503 while (true) {
1504 char tok[27]; /* wiops=18446744073709551616 */
1505 char *p;
2ab5492d 1506 u64 val = U64_MAX;
2ee867dc
TH
1507 int len;
1508
1509 if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
1510 break;
1511 if (tok[0] == '\0')
1512 break;
1513 ctx.body += len;
1514
1515 ret = -EINVAL;
1516 p = tok;
1517 strsep(&p, "=");
1518 if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
1519 goto out_finish;
1520
1521 ret = -ERANGE;
1522 if (!val)
1523 goto out_finish;
1524
1525 ret = -EINVAL;
1526 if (!strcmp(tok, "rbps"))
1527 v[0] = val;
1528 else if (!strcmp(tok, "wbps"))
1529 v[1] = val;
1530 else if (!strcmp(tok, "riops"))
1531 v[2] = min_t(u64, val, UINT_MAX);
1532 else if (!strcmp(tok, "wiops"))
1533 v[3] = min_t(u64, val, UINT_MAX);
1534 else
1535 goto out_finish;
1536 }
1537
cd5ab1b0
SL
1538 tg->bps_conf[READ][index] = v[0];
1539 tg->bps_conf[WRITE][index] = v[1];
1540 tg->iops_conf[READ][index] = v[2];
1541 tg->iops_conf[WRITE][index] = v[3];
2ee867dc 1542
cd5ab1b0
SL
1543 if (index == LIMIT_MAX) {
1544 tg->bps[READ][index] = v[0];
1545 tg->bps[WRITE][index] = v[1];
1546 tg->iops[READ][index] = v[2];
1547 tg->iops[WRITE][index] = v[3];
1548 }
1549 tg->bps[READ][LIMIT_LOW] = min(tg->bps_conf[READ][LIMIT_LOW],
1550 tg->bps_conf[READ][LIMIT_MAX]);
1551 tg->bps[WRITE][LIMIT_LOW] = min(tg->bps_conf[WRITE][LIMIT_LOW],
1552 tg->bps_conf[WRITE][LIMIT_MAX]);
1553 tg->iops[READ][LIMIT_LOW] = min(tg->iops_conf[READ][LIMIT_LOW],
1554 tg->iops_conf[READ][LIMIT_MAX]);
1555 tg->iops[WRITE][LIMIT_LOW] = min(tg->iops_conf[WRITE][LIMIT_LOW],
1556 tg->iops_conf[WRITE][LIMIT_MAX]);
1557
1558 if (index == LIMIT_LOW) {
1559 blk_throtl_update_limit_valid(tg->td);
1560 if (tg->td->limit_valid[LIMIT_LOW])
1561 tg->td->limit_index = LIMIT_LOW;
1562 }
2ee867dc
TH
1563 tg_conf_updated(tg);
1564 ret = 0;
1565out_finish:
1566 blkg_conf_finish(&ctx);
1567 return ret ?: nbytes;
1568}
1569
1570static struct cftype throtl_files[] = {
cd5ab1b0
SL
1571#ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1572 {
1573 .name = "low",
1574 .flags = CFTYPE_NOT_ON_ROOT,
1575 .seq_show = tg_print_limit,
1576 .write = tg_set_limit,
1577 .private = LIMIT_LOW,
1578 },
1579#endif
2ee867dc
TH
1580 {
1581 .name = "max",
1582 .flags = CFTYPE_NOT_ON_ROOT,
cd5ab1b0
SL
1583 .seq_show = tg_print_limit,
1584 .write = tg_set_limit,
1585 .private = LIMIT_MAX,
2ee867dc
TH
1586 },
1587 { } /* terminate */
1588};
1589
da527770 1590static void throtl_shutdown_wq(struct request_queue *q)
e43473b7
VG
1591{
1592 struct throtl_data *td = q->td;
1593
69df0ab0 1594 cancel_work_sync(&td->dispatch_work);
e43473b7
VG
1595}
1596
3c798398 1597static struct blkcg_policy blkcg_policy_throtl = {
2ee867dc 1598 .dfl_cftypes = throtl_files,
880f50e2 1599 .legacy_cftypes = throtl_legacy_files,
f9fcc2d3 1600
001bea73 1601 .pd_alloc_fn = throtl_pd_alloc,
f9fcc2d3 1602 .pd_init_fn = throtl_pd_init,
693e751e 1603 .pd_online_fn = throtl_pd_online,
cd5ab1b0 1604 .pd_offline_fn = throtl_pd_offline,
001bea73 1605 .pd_free_fn = throtl_pd_free,
e43473b7
VG
1606};
1607
3f0abd80
SL
1608static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
1609{
1610 unsigned long rtime = jiffies, wtime = jiffies;
1611
1612 if (tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW])
1613 rtime = tg->last_low_overflow_time[READ];
1614 if (tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
1615 wtime = tg->last_low_overflow_time[WRITE];
1616 return min(rtime, wtime);
1617}
1618
1619/* tg should not be an intermediate node */
1620static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
1621{
1622 struct throtl_service_queue *parent_sq;
1623 struct throtl_grp *parent = tg;
1624 unsigned long ret = __tg_last_low_overflow_time(tg);
1625
1626 while (true) {
1627 parent_sq = parent->service_queue.parent_sq;
1628 parent = sq_to_tg(parent_sq);
1629 if (!parent)
1630 break;
1631
1632 /*
1633 * The parent doesn't have low limit, it always reaches low
1634 * limit. Its overflow time is useless for children
1635 */
1636 if (!parent->bps[READ][LIMIT_LOW] &&
1637 !parent->iops[READ][LIMIT_LOW] &&
1638 !parent->bps[WRITE][LIMIT_LOW] &&
1639 !parent->iops[WRITE][LIMIT_LOW])
1640 continue;
1641 if (time_after(__tg_last_low_overflow_time(parent), ret))
1642 ret = __tg_last_low_overflow_time(parent);
1643 }
1644 return ret;
1645}
1646
c79892c5
SL
1647static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
1648{
1649 struct throtl_service_queue *sq = &tg->service_queue;
1650 bool read_limit, write_limit;
1651
1652 /*
1653 * if cgroup reaches low limit (if low limit is 0, the cgroup always
1654 * reaches), it's ok to upgrade to next limit
1655 */
1656 read_limit = tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW];
1657 write_limit = tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW];
1658 if (!read_limit && !write_limit)
1659 return true;
1660 if (read_limit && sq->nr_queued[READ] &&
1661 (!write_limit || sq->nr_queued[WRITE]))
1662 return true;
1663 if (write_limit && sq->nr_queued[WRITE] &&
1664 (!read_limit || sq->nr_queued[READ]))
1665 return true;
aec24246
SL
1666
1667 if (time_after_eq(jiffies,
1668 tg->last_dispatch_time[READ] + tg->td->throtl_slice) &&
1669 time_after_eq(jiffies,
1670 tg->last_dispatch_time[WRITE] + tg->td->throtl_slice))
1671 return true;
c79892c5
SL
1672 return false;
1673}
1674
1675static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
1676{
1677 while (true) {
1678 if (throtl_tg_can_upgrade(tg))
1679 return true;
1680 tg = sq_to_tg(tg->service_queue.parent_sq);
1681 if (!tg || !tg_to_blkg(tg)->parent)
1682 return false;
1683 }
1684 return false;
1685}
1686
1687static bool throtl_can_upgrade(struct throtl_data *td,
1688 struct throtl_grp *this_tg)
1689{
1690 struct cgroup_subsys_state *pos_css;
1691 struct blkcg_gq *blkg;
1692
1693 if (td->limit_index != LIMIT_LOW)
1694 return false;
1695
297e3d85 1696 if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
3f0abd80
SL
1697 return false;
1698
c79892c5
SL
1699 rcu_read_lock();
1700 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1701 struct throtl_grp *tg = blkg_to_tg(blkg);
1702
1703 if (tg == this_tg)
1704 continue;
1705 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1706 continue;
1707 if (!throtl_hierarchy_can_upgrade(tg)) {
1708 rcu_read_unlock();
1709 return false;
1710 }
1711 }
1712 rcu_read_unlock();
1713 return true;
1714}
1715
1716static void throtl_upgrade_state(struct throtl_data *td)
1717{
1718 struct cgroup_subsys_state *pos_css;
1719 struct blkcg_gq *blkg;
1720
1721 td->limit_index = LIMIT_MAX;
3f0abd80 1722 td->low_upgrade_time = jiffies;
7394e31f 1723 td->scale = 0;
c79892c5
SL
1724 rcu_read_lock();
1725 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1726 struct throtl_grp *tg = blkg_to_tg(blkg);
1727 struct throtl_service_queue *sq = &tg->service_queue;
1728
1729 tg->disptime = jiffies - 1;
1730 throtl_select_dispatch(sq);
1731 throtl_schedule_next_dispatch(sq, false);
1732 }
1733 rcu_read_unlock();
1734 throtl_select_dispatch(&td->service_queue);
1735 throtl_schedule_next_dispatch(&td->service_queue, false);
1736 queue_work(kthrotld_workqueue, &td->dispatch_work);
1737}
1738
3f0abd80
SL
1739static void throtl_downgrade_state(struct throtl_data *td, int new)
1740{
7394e31f
SL
1741 td->scale /= 2;
1742
1743 if (td->scale) {
1744 td->low_upgrade_time = jiffies - td->scale * td->throtl_slice;
1745 return;
1746 }
1747
3f0abd80
SL
1748 td->limit_index = new;
1749 td->low_downgrade_time = jiffies;
1750}
1751
1752static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
1753{
1754 struct throtl_data *td = tg->td;
1755 unsigned long now = jiffies;
1756
aec24246
SL
1757 if (time_after_eq(now, tg->last_dispatch_time[READ] +
1758 td->throtl_slice) &&
1759 time_after_eq(now, tg->last_dispatch_time[WRITE] +
1760 td->throtl_slice))
1761 return false;
3f0abd80
SL
1762 /*
1763 * If cgroup is below low limit, consider downgrade and throttle other
1764 * cgroups
1765 */
297e3d85
SL
1766 if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
1767 time_after_eq(now, tg_last_low_overflow_time(tg) +
1768 td->throtl_slice))
3f0abd80
SL
1769 return true;
1770 return false;
1771}
1772
1773static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
1774{
1775 while (true) {
1776 if (!throtl_tg_can_downgrade(tg))
1777 return false;
1778 tg = sq_to_tg(tg->service_queue.parent_sq);
1779 if (!tg || !tg_to_blkg(tg)->parent)
1780 break;
1781 }
1782 return true;
1783}
1784
1785static void throtl_downgrade_check(struct throtl_grp *tg)
1786{
1787 uint64_t bps;
1788 unsigned int iops;
1789 unsigned long elapsed_time;
1790 unsigned long now = jiffies;
1791
1792 if (tg->td->limit_index != LIMIT_MAX ||
1793 !tg->td->limit_valid[LIMIT_LOW])
1794 return;
1795 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1796 return;
297e3d85 1797 if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
3f0abd80
SL
1798 return;
1799
1800 elapsed_time = now - tg->last_check_time;
1801 tg->last_check_time = now;
1802
297e3d85
SL
1803 if (time_before(now, tg_last_low_overflow_time(tg) +
1804 tg->td->throtl_slice))
3f0abd80
SL
1805 return;
1806
1807 if (tg->bps[READ][LIMIT_LOW]) {
1808 bps = tg->last_bytes_disp[READ] * HZ;
1809 do_div(bps, elapsed_time);
1810 if (bps >= tg->bps[READ][LIMIT_LOW])
1811 tg->last_low_overflow_time[READ] = now;
1812 }
1813
1814 if (tg->bps[WRITE][LIMIT_LOW]) {
1815 bps = tg->last_bytes_disp[WRITE] * HZ;
1816 do_div(bps, elapsed_time);
1817 if (bps >= tg->bps[WRITE][LIMIT_LOW])
1818 tg->last_low_overflow_time[WRITE] = now;
1819 }
1820
1821 if (tg->iops[READ][LIMIT_LOW]) {
1822 iops = tg->last_io_disp[READ] * HZ / elapsed_time;
1823 if (iops >= tg->iops[READ][LIMIT_LOW])
1824 tg->last_low_overflow_time[READ] = now;
1825 }
1826
1827 if (tg->iops[WRITE][LIMIT_LOW]) {
1828 iops = tg->last_io_disp[WRITE] * HZ / elapsed_time;
1829 if (iops >= tg->iops[WRITE][LIMIT_LOW])
1830 tg->last_low_overflow_time[WRITE] = now;
1831 }
1832
1833 /*
1834 * If cgroup is below low limit, consider downgrade and throttle other
1835 * cgroups
1836 */
1837 if (throtl_hierarchy_can_downgrade(tg))
1838 throtl_downgrade_state(tg->td, LIMIT_LOW);
1839
1840 tg->last_bytes_disp[READ] = 0;
1841 tg->last_bytes_disp[WRITE] = 0;
1842 tg->last_io_disp[READ] = 0;
1843 tg->last_io_disp[WRITE] = 0;
1844}
1845
ae118896
TH
1846bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
1847 struct bio *bio)
e43473b7 1848{
c5cc2070 1849 struct throtl_qnode *qn = NULL;
ae118896 1850 struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
73f0d49a 1851 struct throtl_service_queue *sq;
0e9f4164 1852 bool rw = bio_data_dir(bio);
bc16a4f9 1853 bool throttled = false;
e43473b7 1854
ae118896
TH
1855 WARN_ON_ONCE(!rcu_read_lock_held());
1856
2a0f61e6 1857 /* see throtl_charge_bio() */
8d2bbd4c 1858 if (bio_flagged(bio, BIO_THROTTLED) || !tg->has_rules[rw])
bc16a4f9 1859 goto out;
e43473b7
VG
1860
1861 spin_lock_irq(q->queue_lock);
c9589f03
TH
1862
1863 if (unlikely(blk_queue_bypass(q)))
bc16a4f9 1864 goto out_unlock;
f469a7b4 1865
73f0d49a
TH
1866 sq = &tg->service_queue;
1867
c79892c5 1868again:
9e660acf 1869 while (true) {
aec24246 1870 tg->last_dispatch_time[rw] = jiffies;
3f0abd80
SL
1871 if (tg->last_low_overflow_time[rw] == 0)
1872 tg->last_low_overflow_time[rw] = jiffies;
1873 throtl_downgrade_check(tg);
9e660acf
TH
1874 /* throtl is FIFO - if bios are already queued, should queue */
1875 if (sq->nr_queued[rw])
1876 break;
de701c74 1877
9e660acf 1878 /* if above limits, break to queue */
c79892c5 1879 if (!tg_may_dispatch(tg, bio, NULL)) {
3f0abd80 1880 tg->last_low_overflow_time[rw] = jiffies;
c79892c5
SL
1881 if (throtl_can_upgrade(tg->td, tg)) {
1882 throtl_upgrade_state(tg->td);
1883 goto again;
1884 }
9e660acf 1885 break;
c79892c5 1886 }
9e660acf
TH
1887
1888 /* within limits, let's charge and dispatch directly */
e43473b7 1889 throtl_charge_bio(tg, bio);
04521db0
VG
1890
1891 /*
1892 * We need to trim slice even when bios are not being queued
1893 * otherwise it might happen that a bio is not queued for
1894 * a long time and slice keeps on extending and trim is not
1895 * called for a long time. Now if limits are reduced suddenly
1896 * we take into account all the IO dispatched so far at new
1897 * low rate and * newly queued IO gets a really long dispatch
1898 * time.
1899 *
1900 * So keep on trimming slice even if bio is not queued.
1901 */
0f3457f6 1902 throtl_trim_slice(tg, rw);
9e660acf
TH
1903
1904 /*
1905 * @bio passed through this layer without being throttled.
1906 * Climb up the ladder. If we''re already at the top, it
1907 * can be executed directly.
1908 */
c5cc2070 1909 qn = &tg->qnode_on_parent[rw];
9e660acf
TH
1910 sq = sq->parent_sq;
1911 tg = sq_to_tg(sq);
1912 if (!tg)
1913 goto out_unlock;
e43473b7
VG
1914 }
1915
9e660acf 1916 /* out-of-limit, queue to @tg */
fda6f272
TH
1917 throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
1918 rw == READ ? 'R' : 'W',
9f626e37
SL
1919 tg->bytes_disp[rw], bio->bi_iter.bi_size,
1920 tg_bps_limit(tg, rw),
1921 tg->io_disp[rw], tg_iops_limit(tg, rw),
fda6f272 1922 sq->nr_queued[READ], sq->nr_queued[WRITE]);
e43473b7 1923
3f0abd80
SL
1924 tg->last_low_overflow_time[rw] = jiffies;
1925
671058fb 1926 bio_associate_current(bio);
6bc9c2b4 1927 tg->td->nr_queued[rw]++;
c5cc2070 1928 throtl_add_bio_tg(bio, qn, tg);
bc16a4f9 1929 throttled = true;
e43473b7 1930
7f52f98c
TH
1931 /*
1932 * Update @tg's dispatch time and force schedule dispatch if @tg
1933 * was empty before @bio. The forced scheduling isn't likely to
1934 * cause undue delay as @bio is likely to be dispatched directly if
1935 * its @tg's disptime is not in the future.
1936 */
0e9f4164 1937 if (tg->flags & THROTL_TG_WAS_EMPTY) {
77216b04 1938 tg_update_disptime(tg);
7f52f98c 1939 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
e43473b7
VG
1940 }
1941
bc16a4f9 1942out_unlock:
e43473b7 1943 spin_unlock_irq(q->queue_lock);
bc16a4f9 1944out:
2a0f61e6
TH
1945 /*
1946 * As multiple blk-throtls may stack in the same issue path, we
1947 * don't want bios to leave with the flag set. Clear the flag if
1948 * being issued.
1949 */
1950 if (!throttled)
8d2bbd4c 1951 bio_clear_flag(bio, BIO_THROTTLED);
bc16a4f9 1952 return throttled;
e43473b7
VG
1953}
1954
2a12f0dc
TH
1955/*
1956 * Dispatch all bios from all children tg's queued on @parent_sq. On
1957 * return, @parent_sq is guaranteed to not have any active children tg's
1958 * and all bios from previously active tg's are on @parent_sq->bio_lists[].
1959 */
1960static void tg_drain_bios(struct throtl_service_queue *parent_sq)
1961{
1962 struct throtl_grp *tg;
1963
1964 while ((tg = throtl_rb_first(parent_sq))) {
1965 struct throtl_service_queue *sq = &tg->service_queue;
1966 struct bio *bio;
1967
1968 throtl_dequeue_tg(tg);
1969
c5cc2070 1970 while ((bio = throtl_peek_queued(&sq->queued[READ])))
2a12f0dc 1971 tg_dispatch_one_bio(tg, bio_data_dir(bio));
c5cc2070 1972 while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
2a12f0dc
TH
1973 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1974 }
1975}
1976
c9a929dd
TH
1977/**
1978 * blk_throtl_drain - drain throttled bios
1979 * @q: request_queue to drain throttled bios for
1980 *
1981 * Dispatch all currently throttled bios on @q through ->make_request_fn().
1982 */
1983void blk_throtl_drain(struct request_queue *q)
1984 __releases(q->queue_lock) __acquires(q->queue_lock)
1985{
1986 struct throtl_data *td = q->td;
2a12f0dc 1987 struct blkcg_gq *blkg;
492eb21b 1988 struct cgroup_subsys_state *pos_css;
c9a929dd 1989 struct bio *bio;
651930bc 1990 int rw;
c9a929dd 1991
8bcb6c7d 1992 queue_lockdep_assert_held(q);
2a12f0dc 1993 rcu_read_lock();
c9a929dd 1994
2a12f0dc
TH
1995 /*
1996 * Drain each tg while doing post-order walk on the blkg tree, so
1997 * that all bios are propagated to td->service_queue. It'd be
1998 * better to walk service_queue tree directly but blkg walk is
1999 * easier.
2000 */
492eb21b 2001 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
2a12f0dc 2002 tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
73f0d49a 2003
2a12f0dc
TH
2004 /* finally, transfer bios from top-level tg's into the td */
2005 tg_drain_bios(&td->service_queue);
2006
2007 rcu_read_unlock();
c9a929dd
TH
2008 spin_unlock_irq(q->queue_lock);
2009
2a12f0dc 2010 /* all bios now should be in td->service_queue, issue them */
651930bc 2011 for (rw = READ; rw <= WRITE; rw++)
c5cc2070
TH
2012 while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
2013 NULL)))
651930bc 2014 generic_make_request(bio);
c9a929dd
TH
2015
2016 spin_lock_irq(q->queue_lock);
2017}
2018
e43473b7
VG
2019int blk_throtl_init(struct request_queue *q)
2020{
2021 struct throtl_data *td;
a2b1693b 2022 int ret;
e43473b7
VG
2023
2024 td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
2025 if (!td)
2026 return -ENOMEM;
2027
69df0ab0 2028 INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
b2ce2643 2029 throtl_service_queue_init(&td->service_queue);
e43473b7 2030
cd1604fa 2031 q->td = td;
29b12589 2032 td->queue = q;
02977e4a 2033
9f626e37 2034 td->limit_valid[LIMIT_MAX] = true;
cd5ab1b0 2035 td->limit_index = LIMIT_MAX;
3f0abd80
SL
2036 td->low_upgrade_time = jiffies;
2037 td->low_downgrade_time = jiffies;
a2b1693b 2038 /* activate policy */
3c798398 2039 ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
a2b1693b 2040 if (ret)
f51b802c 2041 kfree(td);
a2b1693b 2042 return ret;
e43473b7
VG
2043}
2044
2045void blk_throtl_exit(struct request_queue *q)
2046{
c875f4d0 2047 BUG_ON(!q->td);
da527770 2048 throtl_shutdown_wq(q);
3c798398 2049 blkcg_deactivate_policy(q, &blkcg_policy_throtl);
c9a929dd 2050 kfree(q->td);
e43473b7
VG
2051}
2052
d61fcfa4
SL
2053void blk_throtl_register_queue(struct request_queue *q)
2054{
2055 struct throtl_data *td;
2056
2057 td = q->td;
2058 BUG_ON(!td);
2059
2060 if (blk_queue_nonrot(q))
2061 td->throtl_slice = DFL_THROTL_SLICE_SSD;
2062 else
2063 td->throtl_slice = DFL_THROTL_SLICE_HD;
2064#ifndef CONFIG_BLK_DEV_THROTTLING_LOW
2065 /* if no low limit, use previous default */
2066 td->throtl_slice = DFL_THROTL_SLICE_HD;
2067#endif
2068}
2069
297e3d85
SL
2070#ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2071ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
2072{
2073 if (!q->td)
2074 return -EINVAL;
2075 return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
2076}
2077
2078ssize_t blk_throtl_sample_time_store(struct request_queue *q,
2079 const char *page, size_t count)
2080{
2081 unsigned long v;
2082 unsigned long t;
2083
2084 if (!q->td)
2085 return -EINVAL;
2086 if (kstrtoul(page, 10, &v))
2087 return -EINVAL;
2088 t = msecs_to_jiffies(v);
2089 if (t == 0 || t > MAX_THROTL_SLICE)
2090 return -EINVAL;
2091 q->td->throtl_slice = t;
2092 return count;
2093}
2094#endif
2095
e43473b7
VG
2096static int __init throtl_init(void)
2097{
450adcbe
VG
2098 kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2099 if (!kthrotld_workqueue)
2100 panic("Failed to create kthrotld\n");
2101
3c798398 2102 return blkcg_policy_register(&blkcg_policy_throtl);
e43473b7
VG
2103}
2104
2105module_init(throtl_init);