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