]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - block/blk-throttle.c
blk-throttle: make bandwidth change smooth
[mirror_ubuntu-artful-kernel.git] / block / blk-throttle.c
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>
12 #include <linux/blk-cgroup.h>
13 #include "blk.h"
14
15 /* Max dispatch from a group in 1 round */
16 static int throtl_grp_quantum = 8;
17
18 /* Total max dispatch from all groups in one round */
19 static int throtl_quantum = 32;
20
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)
24 #define MAX_THROTL_SLICE (HZ)
25
26 static struct blkcg_policy blkcg_policy_throtl;
27
28 /* A workqueue to queue throttle related work */
29 static struct workqueue_struct *kthrotld_workqueue;
30
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 */
54 struct 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
60 struct throtl_service_queue {
61 struct throtl_service_queue *parent_sq; /* the parent service_queue */
62
63 /*
64 * Bios queued directly to this service_queue or dispatched from
65 * children throtl_grp's.
66 */
67 struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
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 */
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 */
78 struct timer_list pending_timer; /* fires on first_pending_disptime */
79 };
80
81 enum tg_state_flags {
82 THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
83 THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
84 };
85
86 #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
87
88 enum {
89 LIMIT_LOW,
90 LIMIT_MAX,
91 LIMIT_CNT,
92 };
93
94 struct throtl_grp {
95 /* must be the first member */
96 struct blkg_policy_data pd;
97
98 /* active throtl group service_queue member */
99 struct rb_node rb_node;
100
101 /* throtl_data this group belongs to */
102 struct throtl_data *td;
103
104 /* this group's service queue */
105 struct throtl_service_queue service_queue;
106
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
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
125 unsigned int flags;
126
127 /* are there any throtl rules between this group and td? */
128 bool has_rules[2];
129
130 /* internally used bytes per second rate limits */
131 uint64_t bps[2][LIMIT_CNT];
132 /* user configured bps limits */
133 uint64_t bps_conf[2][LIMIT_CNT];
134
135 /* internally used IOPS limits */
136 unsigned int iops[2][LIMIT_CNT];
137 /* user configured IOPS limits */
138 unsigned int iops_conf[2][LIMIT_CNT];
139
140 /* Number of bytes disptached in current slice */
141 uint64_t bytes_disp[2];
142 /* Number of bio's dispatched in current slice */
143 unsigned int io_disp[2];
144
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
152 unsigned long last_dispatch_time[2];
153
154 /* When did we start a new slice */
155 unsigned long slice_start[2];
156 unsigned long slice_end[2];
157 };
158
159 struct throtl_data
160 {
161 /* service tree for active throtl groups */
162 struct throtl_service_queue service_queue;
163
164 struct request_queue *queue;
165
166 /* Total Number of queued bios on READ and WRITE lists */
167 unsigned int nr_queued[2];
168
169 unsigned int throtl_slice;
170
171 /* Work for dispatching throttled bios */
172 struct work_struct dispatch_work;
173 unsigned int limit_index;
174 bool limit_valid[LIMIT_CNT];
175
176 unsigned long low_upgrade_time;
177 unsigned long low_downgrade_time;
178
179 unsigned int scale;
180 };
181
182 static void throtl_pending_timer_fn(unsigned long arg);
183
184 static 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
189 static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
190 {
191 return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
192 }
193
194 static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
195 {
196 return pd_to_blkg(&tg->pd);
197 }
198
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 */
206 static 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 *
218 * A service_queue can be embedded in either a throtl_grp or throtl_data.
219 * Determine the associated throtl_data accordingly and return it.
220 */
221 static 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
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 */
239 static 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
249 static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
250 {
251 struct blkcg_gq *blkg = tg_to_blkg(tg);
252 struct throtl_data *td;
253 uint64_t ret;
254
255 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
256 return U64_MAX;
257
258 td = tg->td;
259 ret = tg->bps[rw][td->limit_index];
260 if (ret == 0 && td->limit_index == LIMIT_LOW)
261 return tg->bps[rw][LIMIT_MAX];
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 }
270 return ret;
271 }
272
273 static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
274 {
275 struct blkcg_gq *blkg = tg_to_blkg(tg);
276 struct throtl_data *td;
277 unsigned int ret;
278
279 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
280 return UINT_MAX;
281 td = tg->td;
282 ret = tg->iops[rw][td->limit_index];
283 if (ret == 0 && tg->td->limit_index == LIMIT_LOW)
284 return tg->iops[rw][LIMIT_MAX];
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 }
295 return ret;
296 }
297
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".
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; \
312 if (likely(!blk_trace_note_message_enabled(__td->queue))) \
313 break; \
314 if ((__tg)) { \
315 char __pbuf[128]; \
316 \
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 } \
322 } while (0)
323
324 static 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 */
341 static 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 */
355 static 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 */
382 static 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
407 /* init a service_queue, assumes the caller zeroed it */
408 static void throtl_service_queue_init(struct throtl_service_queue *sq)
409 {
410 INIT_LIST_HEAD(&sq->queued[0]);
411 INIT_LIST_HEAD(&sq->queued[1]);
412 sq->pending_tree = RB_ROOT;
413 setup_timer(&sq->pending_timer, throtl_pending_timer_fn,
414 (unsigned long)sq);
415 }
416
417 static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
418 {
419 struct throtl_grp *tg;
420 int rw;
421
422 tg = kzalloc_node(sizeof(*tg), gfp, node);
423 if (!tg)
424 return NULL;
425
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);
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;
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 */
443
444 return &tg->pd;
445 }
446
447 static void throtl_pd_init(struct blkg_policy_data *pd)
448 {
449 struct throtl_grp *tg = pd_to_tg(pd);
450 struct blkcg_gq *blkg = tg_to_blkg(tg);
451 struct throtl_data *td = blkg->q->td;
452 struct throtl_service_queue *sq = &tg->service_queue;
453
454 /*
455 * If on the default hierarchy, we switch to properly hierarchical
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 *
461 * If not on the default hierarchy, the broken flat hierarchy
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 */
467 sq->parent_sq = &td->service_queue;
468 if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
469 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
470 tg->td = td;
471 }
472
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 */
478 static void tg_update_has_rules(struct throtl_grp *tg)
479 {
480 struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
481 struct throtl_data *td = tg->td;
482 int rw;
483
484 for (rw = READ; rw <= WRITE; rw++)
485 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
486 (td->limit_valid[td->limit_index] &&
487 (tg_bps_limit(tg, rw) != U64_MAX ||
488 tg_iops_limit(tg, rw) != UINT_MAX));
489 }
490
491 static void throtl_pd_online(struct blkg_policy_data *pd)
492 {
493 struct throtl_grp *tg = pd_to_tg(pd);
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 */
498 tg_update_has_rules(tg);
499 tg->last_dispatch_time[READ] = jiffies;
500 tg->last_dispatch_time[WRITE] = jiffies;
501 }
502
503 static 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
522 static void throtl_upgrade_state(struct throtl_data *td);
523 static 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
534 if (!tg->td->limit_valid[tg->td->limit_index])
535 throtl_upgrade_state(tg->td);
536 }
537
538 static void throtl_pd_free(struct blkg_policy_data *pd)
539 {
540 struct throtl_grp *tg = pd_to_tg(pd);
541
542 del_timer_sync(&tg->service_queue.pending_timer);
543 kfree(tg);
544 }
545
546 static struct throtl_grp *
547 throtl_rb_first(struct throtl_service_queue *parent_sq)
548 {
549 /* Service tree is empty */
550 if (!parent_sq->nr_pending)
551 return NULL;
552
553 if (!parent_sq->first_pending)
554 parent_sq->first_pending = rb_first(&parent_sq->pending_tree);
555
556 if (parent_sq->first_pending)
557 return rb_entry_tg(parent_sq->first_pending);
558
559 return NULL;
560 }
561
562 static 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
568 static void throtl_rb_erase(struct rb_node *n,
569 struct throtl_service_queue *parent_sq)
570 {
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;
575 }
576
577 static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
578 {
579 struct throtl_grp *tg;
580
581 tg = throtl_rb_first(parent_sq);
582 if (!tg)
583 return;
584
585 parent_sq->first_pending_disptime = tg->disptime;
586 }
587
588 static void tg_service_queue_add(struct throtl_grp *tg)
589 {
590 struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
591 struct rb_node **node = &parent_sq->pending_tree.rb_node;
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)
610 parent_sq->first_pending = &tg->rb_node;
611
612 rb_link_node(&tg->rb_node, parent, node);
613 rb_insert_color(&tg->rb_node, &parent_sq->pending_tree);
614 }
615
616 static void __throtl_enqueue_tg(struct throtl_grp *tg)
617 {
618 tg_service_queue_add(tg);
619 tg->flags |= THROTL_TG_PENDING;
620 tg->service_queue.parent_sq->nr_pending++;
621 }
622
623 static void throtl_enqueue_tg(struct throtl_grp *tg)
624 {
625 if (!(tg->flags & THROTL_TG_PENDING))
626 __throtl_enqueue_tg(tg);
627 }
628
629 static void __throtl_dequeue_tg(struct throtl_grp *tg)
630 {
631 throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
632 tg->flags &= ~THROTL_TG_PENDING;
633 }
634
635 static void throtl_dequeue_tg(struct throtl_grp *tg)
636 {
637 if (tg->flags & THROTL_TG_PENDING)
638 __throtl_dequeue_tg(tg);
639 }
640
641 /* Call with queue lock held */
642 static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
643 unsigned long expires)
644 {
645 unsigned long max_expire = jiffies + 8 * sq_to_tg(sq)->td->throtl_slice;
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;
656 mod_timer(&sq->pending_timer, expires);
657 throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
658 expires - jiffies, jiffies);
659 }
660
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 */
679 static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
680 bool force)
681 {
682 /* any pending children left? */
683 if (!sq->nr_pending)
684 return true;
685
686 update_min_dispatch_time(sq);
687
688 /* is the next dispatch time in the future? */
689 if (force || time_after(sq->first_pending_disptime, jiffies)) {
690 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
691 return true;
692 }
693
694 /* tell the caller to continue dispatching */
695 return false;
696 }
697
698 static 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
713 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
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
720 static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
721 {
722 tg->bytes_disp[rw] = 0;
723 tg->io_disp[rw] = 0;
724 tg->slice_start[rw] = jiffies;
725 tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
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);
730 }
731
732 static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
733 unsigned long jiffy_end)
734 {
735 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
736 }
737
738 static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
739 unsigned long jiffy_end)
740 {
741 tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
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);
746 }
747
748 /* Determine if previously allocated or extended slice is complete or not */
749 static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
750 {
751 if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
752 return false;
753
754 return 1;
755 }
756
757 /* Trim the used slices and adjust slice start accordingly */
758 static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
759 {
760 unsigned long nr_slices, time_elapsed, io_trim;
761 u64 bytes_trim, tmp;
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 */
770 if (throtl_slice_used(tg, rw))
771 return;
772
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
781 throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
782
783 time_elapsed = jiffies - tg->slice_start[rw];
784
785 nr_slices = time_elapsed / tg->td->throtl_slice;
786
787 if (!nr_slices)
788 return;
789 tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
790 do_div(tmp, HZ);
791 bytes_trim = tmp;
792
793 io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
794 HZ;
795
796 if (!bytes_trim && !io_trim)
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
804 if (tg->io_disp[rw] >= io_trim)
805 tg->io_disp[rw] -= io_trim;
806 else
807 tg->io_disp[rw] = 0;
808
809 tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
810
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);
815 }
816
817 static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
818 unsigned long *wait)
819 {
820 bool rw = bio_data_dir(bio);
821 unsigned int io_allowed;
822 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
823 u64 tmp;
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)
829 jiffy_elapsed_rnd = tg->td->throtl_slice;
830
831 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
832
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
840 tmp = (u64)tg_iops_limit(tg, rw) * jiffy_elapsed_rnd;
841 do_div(tmp, HZ);
842
843 if (tmp > UINT_MAX)
844 io_allowed = UINT_MAX;
845 else
846 io_allowed = tmp;
847
848 if (tg->io_disp[rw] + 1 <= io_allowed) {
849 if (wait)
850 *wait = 0;
851 return true;
852 }
853
854 /* Calc approx time to dispatch */
855 jiffy_wait = ((tg->io_disp[rw] + 1) * HZ) / tg_iops_limit(tg, rw) + 1;
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
867 static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
868 unsigned long *wait)
869 {
870 bool rw = bio_data_dir(bio);
871 u64 bytes_allowed, extra_bytes, tmp;
872 unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
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)
878 jiffy_elapsed_rnd = tg->td->throtl_slice;
879
880 jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
881
882 tmp = tg_bps_limit(tg, rw) * jiffy_elapsed_rnd;
883 do_div(tmp, HZ);
884 bytes_allowed = tmp;
885
886 if (tg->bytes_disp[rw] + bio->bi_iter.bi_size <= bytes_allowed) {
887 if (wait)
888 *wait = 0;
889 return true;
890 }
891
892 /* Calc approx time to dispatch */
893 extra_bytes = tg->bytes_disp[rw] + bio->bi_iter.bi_size - bytes_allowed;
894 jiffy_wait = div64_u64(extra_bytes * HZ, tg_bps_limit(tg, rw));
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);
904 if (wait)
905 *wait = jiffy_wait;
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 */
913 static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
914 unsigned long *wait)
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 */
925 BUG_ON(tg->service_queue.nr_queued[rw] &&
926 bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
927
928 /* If tg->bps = -1, then BW is unlimited */
929 if (tg_bps_limit(tg, rw) == U64_MAX &&
930 tg_iops_limit(tg, rw) == UINT_MAX) {
931 if (wait)
932 *wait = 0;
933 return true;
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
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.
942 */
943 if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
944 throtl_start_new_slice(tg, rw);
945 else {
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);
950 }
951
952 if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
953 tg_with_in_iops_limit(tg, bio, &iops_wait)) {
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))
965 throtl_extend_slice(tg, rw, jiffies + max_wait);
966
967 return 0;
968 }
969
970 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
971 {
972 bool rw = bio_data_dir(bio);
973
974 /* Charge the bio to the group */
975 tg->bytes_disp[rw] += bio->bi_iter.bi_size;
976 tg->io_disp[rw]++;
977 tg->last_bytes_disp[rw] += bio->bi_iter.bi_size;
978 tg->last_io_disp[rw]++;
979
980 /*
981 * BIO_THROTTLED is used to prevent the same bio to be throttled
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.
985 */
986 if (!bio_flagged(bio, BIO_THROTTLED))
987 bio_set_flag(bio, BIO_THROTTLED);
988 }
989
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 */
999 static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
1000 struct throtl_grp *tg)
1001 {
1002 struct throtl_service_queue *sq = &tg->service_queue;
1003 bool rw = bio_data_dir(bio);
1004
1005 if (!qn)
1006 qn = &tg->qnode_on_self[rw];
1007
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
1017 throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
1018
1019 sq->nr_queued[rw]++;
1020 throtl_enqueue_tg(tg);
1021 }
1022
1023 static void tg_update_disptime(struct throtl_grp *tg)
1024 {
1025 struct throtl_service_queue *sq = &tg->service_queue;
1026 unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
1027 struct bio *bio;
1028
1029 bio = throtl_peek_queued(&sq->queued[READ]);
1030 if (bio)
1031 tg_may_dispatch(tg, bio, &read_wait);
1032
1033 bio = throtl_peek_queued(&sq->queued[WRITE]);
1034 if (bio)
1035 tg_may_dispatch(tg, bio, &write_wait);
1036
1037 min_wait = min(read_wait, write_wait);
1038 disptime = jiffies + min_wait;
1039
1040 /* Update dispatch time */
1041 throtl_dequeue_tg(tg);
1042 tg->disptime = disptime;
1043 throtl_enqueue_tg(tg);
1044
1045 /* see throtl_add_bio_tg() */
1046 tg->flags &= ~THROTL_TG_WAS_EMPTY;
1047 }
1048
1049 static 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
1059 static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
1060 {
1061 struct throtl_service_queue *sq = &tg->service_queue;
1062 struct throtl_service_queue *parent_sq = sq->parent_sq;
1063 struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
1064 struct throtl_grp *tg_to_put = NULL;
1065 struct bio *bio;
1066
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);
1074 sq->nr_queued[rw]--;
1075
1076 throtl_charge_bio(tg, bio);
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) {
1086 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
1087 start_parent_slice_with_credit(tg, parent_tg, rw);
1088 } else {
1089 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1090 &parent_sq->queued[rw]);
1091 BUG_ON(tg->td->nr_queued[rw] <= 0);
1092 tg->td->nr_queued[rw]--;
1093 }
1094
1095 throtl_trim_slice(tg, rw);
1096
1097 if (tg_to_put)
1098 blkg_put(tg_to_blkg(tg_to_put));
1099 }
1100
1101 static int throtl_dispatch_tg(struct throtl_grp *tg)
1102 {
1103 struct throtl_service_queue *sq = &tg->service_queue;
1104 unsigned int nr_reads = 0, nr_writes = 0;
1105 unsigned int max_nr_reads = throtl_grp_quantum*3/4;
1106 unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
1107 struct bio *bio;
1108
1109 /* Try to dispatch 75% READS and 25% WRITES */
1110
1111 while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
1112 tg_may_dispatch(tg, bio, NULL)) {
1113
1114 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1115 nr_reads++;
1116
1117 if (nr_reads >= max_nr_reads)
1118 break;
1119 }
1120
1121 while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
1122 tg_may_dispatch(tg, bio, NULL)) {
1123
1124 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1125 nr_writes++;
1126
1127 if (nr_writes >= max_nr_writes)
1128 break;
1129 }
1130
1131 return nr_reads + nr_writes;
1132 }
1133
1134 static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
1135 {
1136 unsigned int nr_disp = 0;
1137
1138 while (1) {
1139 struct throtl_grp *tg = throtl_rb_first(parent_sq);
1140 struct throtl_service_queue *sq = &tg->service_queue;
1141
1142 if (!tg)
1143 break;
1144
1145 if (time_before(jiffies, tg->disptime))
1146 break;
1147
1148 throtl_dequeue_tg(tg);
1149
1150 nr_disp += throtl_dispatch_tg(tg);
1151
1152 if (sq->nr_queued[0] || sq->nr_queued[1])
1153 tg_update_disptime(tg);
1154
1155 if (nr_disp >= throtl_quantum)
1156 break;
1157 }
1158
1159 return nr_disp;
1160 }
1161
1162 static bool throtl_can_upgrade(struct throtl_data *td,
1163 struct throtl_grp *this_tg);
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
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.
1178 */
1179 static void throtl_pending_timer_fn(unsigned long arg)
1180 {
1181 struct throtl_service_queue *sq = (void *)arg;
1182 struct throtl_grp *tg = sq_to_tg(sq);
1183 struct throtl_data *td = sq_to_td(sq);
1184 struct request_queue *q = td->queue;
1185 struct throtl_service_queue *parent_sq;
1186 bool dispatched;
1187 int ret;
1188
1189 spin_lock_irq(q->queue_lock);
1190 if (throtl_can_upgrade(td, NULL))
1191 throtl_upgrade_state(td);
1192
1193 again:
1194 parent_sq = sq->parent_sq;
1195 dispatched = false;
1196
1197 while (true) {
1198 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
1199 sq->nr_queued[READ] + sq->nr_queued[WRITE],
1200 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1201
1202 ret = throtl_select_dispatch(sq);
1203 if (ret) {
1204 throtl_log(sq, "bios disp=%u", ret);
1205 dispatched = true;
1206 }
1207
1208 if (throtl_schedule_next_dispatch(sq, false))
1209 break;
1210
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);
1215 }
1216
1217 if (!dispatched)
1218 goto out_unlock;
1219
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 }
1235 out_unlock:
1236 spin_unlock_irq(q->queue_lock);
1237 }
1238
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 */
1247 static void blk_throtl_dispatch_work_fn(struct work_struct *work)
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);
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);
1264 spin_unlock_irq(q->queue_lock);
1265
1266 if (!bio_list_empty(&bio_list_on_stack)) {
1267 blk_start_plug(&plug);
1268 while((bio = bio_list_pop(&bio_list_on_stack)))
1269 generic_make_request(bio);
1270 blk_finish_plug(&plug);
1271 }
1272 }
1273
1274 static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1275 int off)
1276 {
1277 struct throtl_grp *tg = pd_to_tg(pd);
1278 u64 v = *(u64 *)((void *)tg + off);
1279
1280 if (v == U64_MAX)
1281 return 0;
1282 return __blkg_prfill_u64(sf, pd, v);
1283 }
1284
1285 static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1286 int off)
1287 {
1288 struct throtl_grp *tg = pd_to_tg(pd);
1289 unsigned int v = *(unsigned int *)((void *)tg + off);
1290
1291 if (v == UINT_MAX)
1292 return 0;
1293 return __blkg_prfill_u64(sf, pd, v);
1294 }
1295
1296 static int tg_print_conf_u64(struct seq_file *sf, void *v)
1297 {
1298 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1299 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1300 return 0;
1301 }
1302
1303 static int tg_print_conf_uint(struct seq_file *sf, void *v)
1304 {
1305 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1306 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1307 return 0;
1308 }
1309
1310 static void tg_conf_updated(struct throtl_grp *tg)
1311 {
1312 struct throtl_service_queue *sq = &tg->service_queue;
1313 struct cgroup_subsys_state *pos_css;
1314 struct blkcg_gq *blkg;
1315
1316 throtl_log(&tg->service_queue,
1317 "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
1318 tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1319 tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
1320
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 */
1328 blkg_for_each_descendant_pre(blkg, pos_css, tg_to_blkg(tg))
1329 tg_update_has_rules(blkg_to_tg(blkg));
1330
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 */
1339 throtl_start_new_slice(tg, 0);
1340 throtl_start_new_slice(tg, 1);
1341
1342 if (tg->flags & THROTL_TG_PENDING) {
1343 tg_update_disptime(tg);
1344 throtl_schedule_next_dispatch(sq->parent_sq, true);
1345 }
1346 }
1347
1348 static 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)
1365 v = U64_MAX;
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;
1373
1374 tg_conf_updated(tg);
1375 ret = 0;
1376 out_finish:
1377 blkg_conf_finish(&ctx);
1378 return ret ?: nbytes;
1379 }
1380
1381 static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1382 char *buf, size_t nbytes, loff_t off)
1383 {
1384 return tg_set_conf(of, buf, nbytes, off, true);
1385 }
1386
1387 static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1388 char *buf, size_t nbytes, loff_t off)
1389 {
1390 return tg_set_conf(of, buf, nbytes, off, false);
1391 }
1392
1393 static struct cftype throtl_legacy_files[] = {
1394 {
1395 .name = "throttle.read_bps_device",
1396 .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
1397 .seq_show = tg_print_conf_u64,
1398 .write = tg_set_conf_u64,
1399 },
1400 {
1401 .name = "throttle.write_bps_device",
1402 .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
1403 .seq_show = tg_print_conf_u64,
1404 .write = tg_set_conf_u64,
1405 },
1406 {
1407 .name = "throttle.read_iops_device",
1408 .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
1409 .seq_show = tg_print_conf_uint,
1410 .write = tg_set_conf_uint,
1411 },
1412 {
1413 .name = "throttle.write_iops_device",
1414 .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
1415 .seq_show = tg_print_conf_uint,
1416 .write = tg_set_conf_uint,
1417 },
1418 {
1419 .name = "throttle.io_service_bytes",
1420 .private = (unsigned long)&blkcg_policy_throtl,
1421 .seq_show = blkg_print_stat_bytes,
1422 },
1423 {
1424 .name = "throttle.io_serviced",
1425 .private = (unsigned long)&blkcg_policy_throtl,
1426 .seq_show = blkg_print_stat_ios,
1427 },
1428 { } /* terminate */
1429 };
1430
1431 static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
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" };
1437 u64 bps_dft;
1438 unsigned int iops_dft;
1439
1440 if (!dname)
1441 return 0;
1442
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)
1455 return 0;
1456
1457 if (tg->bps_conf[READ][off] != bps_dft)
1458 snprintf(bufs[0], sizeof(bufs[0]), "%llu",
1459 tg->bps_conf[READ][off]);
1460 if (tg->bps_conf[WRITE][off] != bps_dft)
1461 snprintf(bufs[1], sizeof(bufs[1]), "%llu",
1462 tg->bps_conf[WRITE][off]);
1463 if (tg->iops_conf[READ][off] != iops_dft)
1464 snprintf(bufs[2], sizeof(bufs[2]), "%u",
1465 tg->iops_conf[READ][off]);
1466 if (tg->iops_conf[WRITE][off] != iops_dft)
1467 snprintf(bufs[3], sizeof(bufs[3]), "%u",
1468 tg->iops_conf[WRITE][off]);
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
1475 static int tg_print_limit(struct seq_file *sf, void *v)
1476 {
1477 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
1478 &blkcg_policy_throtl, seq_cft(sf)->private, false);
1479 return 0;
1480 }
1481
1482 static ssize_t tg_set_limit(struct kernfs_open_file *of,
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;
1490 int index = of_cft(of)->private;
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
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];
1502
1503 while (true) {
1504 char tok[27]; /* wiops=18446744073709551616 */
1505 char *p;
1506 u64 val = U64_MAX;
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
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];
1542
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 }
1563 tg_conf_updated(tg);
1564 ret = 0;
1565 out_finish:
1566 blkg_conf_finish(&ctx);
1567 return ret ?: nbytes;
1568 }
1569
1570 static struct cftype throtl_files[] = {
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
1580 {
1581 .name = "max",
1582 .flags = CFTYPE_NOT_ON_ROOT,
1583 .seq_show = tg_print_limit,
1584 .write = tg_set_limit,
1585 .private = LIMIT_MAX,
1586 },
1587 { } /* terminate */
1588 };
1589
1590 static void throtl_shutdown_wq(struct request_queue *q)
1591 {
1592 struct throtl_data *td = q->td;
1593
1594 cancel_work_sync(&td->dispatch_work);
1595 }
1596
1597 static struct blkcg_policy blkcg_policy_throtl = {
1598 .dfl_cftypes = throtl_files,
1599 .legacy_cftypes = throtl_legacy_files,
1600
1601 .pd_alloc_fn = throtl_pd_alloc,
1602 .pd_init_fn = throtl_pd_init,
1603 .pd_online_fn = throtl_pd_online,
1604 .pd_offline_fn = throtl_pd_offline,
1605 .pd_free_fn = throtl_pd_free,
1606 };
1607
1608 static 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 */
1620 static 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
1647 static 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;
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;
1672 return false;
1673 }
1674
1675 static 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
1687 static 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
1696 if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
1697 return false;
1698
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
1716 static 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;
1722 td->low_upgrade_time = jiffies;
1723 td->scale = 0;
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
1739 static void throtl_downgrade_state(struct throtl_data *td, int new)
1740 {
1741 td->scale /= 2;
1742
1743 if (td->scale) {
1744 td->low_upgrade_time = jiffies - td->scale * td->throtl_slice;
1745 return;
1746 }
1747
1748 td->limit_index = new;
1749 td->low_downgrade_time = jiffies;
1750 }
1751
1752 static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
1753 {
1754 struct throtl_data *td = tg->td;
1755 unsigned long now = jiffies;
1756
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;
1762 /*
1763 * If cgroup is below low limit, consider downgrade and throttle other
1764 * cgroups
1765 */
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))
1769 return true;
1770 return false;
1771 }
1772
1773 static 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
1785 static 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;
1797 if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1798 return;
1799
1800 elapsed_time = now - tg->last_check_time;
1801 tg->last_check_time = now;
1802
1803 if (time_before(now, tg_last_low_overflow_time(tg) +
1804 tg->td->throtl_slice))
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
1846 bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
1847 struct bio *bio)
1848 {
1849 struct throtl_qnode *qn = NULL;
1850 struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
1851 struct throtl_service_queue *sq;
1852 bool rw = bio_data_dir(bio);
1853 bool throttled = false;
1854
1855 WARN_ON_ONCE(!rcu_read_lock_held());
1856
1857 /* see throtl_charge_bio() */
1858 if (bio_flagged(bio, BIO_THROTTLED) || !tg->has_rules[rw])
1859 goto out;
1860
1861 spin_lock_irq(q->queue_lock);
1862
1863 if (unlikely(blk_queue_bypass(q)))
1864 goto out_unlock;
1865
1866 sq = &tg->service_queue;
1867
1868 again:
1869 while (true) {
1870 tg->last_dispatch_time[rw] = jiffies;
1871 if (tg->last_low_overflow_time[rw] == 0)
1872 tg->last_low_overflow_time[rw] = jiffies;
1873 throtl_downgrade_check(tg);
1874 /* throtl is FIFO - if bios are already queued, should queue */
1875 if (sq->nr_queued[rw])
1876 break;
1877
1878 /* if above limits, break to queue */
1879 if (!tg_may_dispatch(tg, bio, NULL)) {
1880 tg->last_low_overflow_time[rw] = jiffies;
1881 if (throtl_can_upgrade(tg->td, tg)) {
1882 throtl_upgrade_state(tg->td);
1883 goto again;
1884 }
1885 break;
1886 }
1887
1888 /* within limits, let's charge and dispatch directly */
1889 throtl_charge_bio(tg, bio);
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 */
1902 throtl_trim_slice(tg, rw);
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 */
1909 qn = &tg->qnode_on_parent[rw];
1910 sq = sq->parent_sq;
1911 tg = sq_to_tg(sq);
1912 if (!tg)
1913 goto out_unlock;
1914 }
1915
1916 /* out-of-limit, queue to @tg */
1917 throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
1918 rw == READ ? 'R' : 'W',
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),
1922 sq->nr_queued[READ], sq->nr_queued[WRITE]);
1923
1924 tg->last_low_overflow_time[rw] = jiffies;
1925
1926 bio_associate_current(bio);
1927 tg->td->nr_queued[rw]++;
1928 throtl_add_bio_tg(bio, qn, tg);
1929 throttled = true;
1930
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 */
1937 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1938 tg_update_disptime(tg);
1939 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
1940 }
1941
1942 out_unlock:
1943 spin_unlock_irq(q->queue_lock);
1944 out:
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)
1951 bio_clear_flag(bio, BIO_THROTTLED);
1952 return throttled;
1953 }
1954
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 */
1960 static 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
1970 while ((bio = throtl_peek_queued(&sq->queued[READ])))
1971 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1972 while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
1973 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1974 }
1975 }
1976
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 */
1983 void blk_throtl_drain(struct request_queue *q)
1984 __releases(q->queue_lock) __acquires(q->queue_lock)
1985 {
1986 struct throtl_data *td = q->td;
1987 struct blkcg_gq *blkg;
1988 struct cgroup_subsys_state *pos_css;
1989 struct bio *bio;
1990 int rw;
1991
1992 queue_lockdep_assert_held(q);
1993 rcu_read_lock();
1994
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 */
2001 blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
2002 tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
2003
2004 /* finally, transfer bios from top-level tg's into the td */
2005 tg_drain_bios(&td->service_queue);
2006
2007 rcu_read_unlock();
2008 spin_unlock_irq(q->queue_lock);
2009
2010 /* all bios now should be in td->service_queue, issue them */
2011 for (rw = READ; rw <= WRITE; rw++)
2012 while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
2013 NULL)))
2014 generic_make_request(bio);
2015
2016 spin_lock_irq(q->queue_lock);
2017 }
2018
2019 int blk_throtl_init(struct request_queue *q)
2020 {
2021 struct throtl_data *td;
2022 int ret;
2023
2024 td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
2025 if (!td)
2026 return -ENOMEM;
2027
2028 INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
2029 throtl_service_queue_init(&td->service_queue);
2030
2031 q->td = td;
2032 td->queue = q;
2033
2034 td->limit_valid[LIMIT_MAX] = true;
2035 td->limit_index = LIMIT_MAX;
2036 td->low_upgrade_time = jiffies;
2037 td->low_downgrade_time = jiffies;
2038 /* activate policy */
2039 ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
2040 if (ret)
2041 kfree(td);
2042 return ret;
2043 }
2044
2045 void blk_throtl_exit(struct request_queue *q)
2046 {
2047 BUG_ON(!q->td);
2048 throtl_shutdown_wq(q);
2049 blkcg_deactivate_policy(q, &blkcg_policy_throtl);
2050 kfree(q->td);
2051 }
2052
2053 void 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
2070 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2071 ssize_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
2078 ssize_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
2096 static int __init throtl_init(void)
2097 {
2098 kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2099 if (!kthrotld_workqueue)
2100 panic("Failed to create kthrotld\n");
2101
2102 return blkcg_policy_register(&blkcg_policy_throtl);
2103 }
2104
2105 module_init(throtl_init);