blk-throttle: remove THROTL_TG_HAS_IOPS_LIMIT
[linux-2.6-microblaze.git] / block / blk-throttle.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Interface for controlling IO bandwidth on a request queue
4  *
5  * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
6  */
7
8 #include <linux/module.h>
9 #include <linux/slab.h>
10 #include <linux/blkdev.h>
11 #include <linux/bio.h>
12 #include <linux/blktrace_api.h>
13 #include "blk.h"
14 #include "blk-cgroup-rwstat.h"
15 #include "blk-stat.h"
16 #include "blk-throttle.h"
17
18 /* Max dispatch from a group in 1 round */
19 #define THROTL_GRP_QUANTUM 8
20
21 /* Total max dispatch from all groups in one round */
22 #define THROTL_QUANTUM 32
23
24 /* Throttling is performed over a slice and after that slice is renewed */
25 #define DFL_THROTL_SLICE_HD (HZ / 10)
26 #define DFL_THROTL_SLICE_SSD (HZ / 50)
27 #define MAX_THROTL_SLICE (HZ)
28 #define MAX_IDLE_TIME (5L * 1000 * 1000) /* 5 s */
29 #define MIN_THROTL_BPS (320 * 1024)
30 #define MIN_THROTL_IOPS (10)
31 #define DFL_LATENCY_TARGET (-1L)
32 #define DFL_IDLE_THRESHOLD (0)
33 #define DFL_HD_BASELINE_LATENCY (4000L) /* 4ms */
34 #define LATENCY_FILTERED_SSD (0)
35 /*
36  * For HD, very small latency comes from sequential IO. Such IO is helpless to
37  * help determine if its IO is impacted by others, hence we ignore the IO
38  */
39 #define LATENCY_FILTERED_HD (1000L) /* 1ms */
40
41 /* A workqueue to queue throttle related work */
42 static struct workqueue_struct *kthrotld_workqueue;
43
44 #define rb_entry_tg(node)       rb_entry((node), struct throtl_grp, rb_node)
45
46 /* We measure latency for request size from <= 4k to >= 1M */
47 #define LATENCY_BUCKET_SIZE 9
48
49 struct latency_bucket {
50         unsigned long total_latency; /* ns / 1024 */
51         int samples;
52 };
53
54 struct avg_latency_bucket {
55         unsigned long latency; /* ns / 1024 */
56         bool valid;
57 };
58
59 struct throtl_data
60 {
61         /* service tree for active throtl groups */
62         struct throtl_service_queue service_queue;
63
64         struct request_queue *queue;
65
66         /* Total Number of queued bios on READ and WRITE lists */
67         unsigned int nr_queued[2];
68
69         unsigned int throtl_slice;
70
71         /* Work for dispatching throttled bios */
72         struct work_struct dispatch_work;
73         unsigned int limit_index;
74         bool limit_valid[LIMIT_CNT];
75
76         unsigned long low_upgrade_time;
77         unsigned long low_downgrade_time;
78
79         unsigned int scale;
80
81         struct latency_bucket tmp_buckets[2][LATENCY_BUCKET_SIZE];
82         struct avg_latency_bucket avg_buckets[2][LATENCY_BUCKET_SIZE];
83         struct latency_bucket __percpu *latency_buckets[2];
84         unsigned long last_calculate_time;
85         unsigned long filtered_latency;
86
87         bool track_bio_latency;
88 };
89
90 static void throtl_pending_timer_fn(struct timer_list *t);
91
92 static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
93 {
94         return pd_to_blkg(&tg->pd);
95 }
96
97 /**
98  * sq_to_tg - return the throl_grp the specified service queue belongs to
99  * @sq: the throtl_service_queue of interest
100  *
101  * Return the throtl_grp @sq belongs to.  If @sq is the top-level one
102  * embedded in throtl_data, %NULL is returned.
103  */
104 static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
105 {
106         if (sq && sq->parent_sq)
107                 return container_of(sq, struct throtl_grp, service_queue);
108         else
109                 return NULL;
110 }
111
112 /**
113  * sq_to_td - return throtl_data the specified service queue belongs to
114  * @sq: the throtl_service_queue of interest
115  *
116  * A service_queue can be embedded in either a throtl_grp or throtl_data.
117  * Determine the associated throtl_data accordingly and return it.
118  */
119 static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
120 {
121         struct throtl_grp *tg = sq_to_tg(sq);
122
123         if (tg)
124                 return tg->td;
125         else
126                 return container_of(sq, struct throtl_data, service_queue);
127 }
128
129 /*
130  * cgroup's limit in LIMIT_MAX is scaled if low limit is set. This scale is to
131  * make the IO dispatch more smooth.
132  * Scale up: linearly scale up according to lapsed time since upgrade. For
133  *           every throtl_slice, the limit scales up 1/2 .low limit till the
134  *           limit hits .max limit
135  * Scale down: exponentially scale down if a cgroup doesn't hit its .low limit
136  */
137 static uint64_t throtl_adjusted_limit(uint64_t low, struct throtl_data *td)
138 {
139         /* arbitrary value to avoid too big scale */
140         if (td->scale < 4096 && time_after_eq(jiffies,
141             td->low_upgrade_time + td->scale * td->throtl_slice))
142                 td->scale = (jiffies - td->low_upgrade_time) / td->throtl_slice;
143
144         return low + (low >> 1) * td->scale;
145 }
146
147 static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
148 {
149         struct blkcg_gq *blkg = tg_to_blkg(tg);
150         struct throtl_data *td;
151         uint64_t ret;
152
153         if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
154                 return U64_MAX;
155
156         td = tg->td;
157         ret = tg->bps[rw][td->limit_index];
158         if (ret == 0 && td->limit_index == LIMIT_LOW) {
159                 /* intermediate node or iops isn't 0 */
160                 if (!list_empty(&blkg->blkcg->css.children) ||
161                     tg->iops[rw][td->limit_index])
162                         return U64_MAX;
163                 else
164                         return MIN_THROTL_BPS;
165         }
166
167         if (td->limit_index == LIMIT_MAX && tg->bps[rw][LIMIT_LOW] &&
168             tg->bps[rw][LIMIT_LOW] != tg->bps[rw][LIMIT_MAX]) {
169                 uint64_t adjusted;
170
171                 adjusted = throtl_adjusted_limit(tg->bps[rw][LIMIT_LOW], td);
172                 ret = min(tg->bps[rw][LIMIT_MAX], adjusted);
173         }
174         return ret;
175 }
176
177 static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
178 {
179         struct blkcg_gq *blkg = tg_to_blkg(tg);
180         struct throtl_data *td;
181         unsigned int ret;
182
183         if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
184                 return UINT_MAX;
185
186         td = tg->td;
187         ret = tg->iops[rw][td->limit_index];
188         if (ret == 0 && tg->td->limit_index == LIMIT_LOW) {
189                 /* intermediate node or bps isn't 0 */
190                 if (!list_empty(&blkg->blkcg->css.children) ||
191                     tg->bps[rw][td->limit_index])
192                         return UINT_MAX;
193                 else
194                         return MIN_THROTL_IOPS;
195         }
196
197         if (td->limit_index == LIMIT_MAX && tg->iops[rw][LIMIT_LOW] &&
198             tg->iops[rw][LIMIT_LOW] != tg->iops[rw][LIMIT_MAX]) {
199                 uint64_t adjusted;
200
201                 adjusted = throtl_adjusted_limit(tg->iops[rw][LIMIT_LOW], td);
202                 if (adjusted > UINT_MAX)
203                         adjusted = UINT_MAX;
204                 ret = min_t(unsigned int, tg->iops[rw][LIMIT_MAX], adjusted);
205         }
206         return ret;
207 }
208
209 #define request_bucket_index(sectors) \
210         clamp_t(int, order_base_2(sectors) - 3, 0, LATENCY_BUCKET_SIZE - 1)
211
212 /**
213  * throtl_log - log debug message via blktrace
214  * @sq: the service_queue being reported
215  * @fmt: printf format string
216  * @args: printf args
217  *
218  * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
219  * throtl_grp; otherwise, just "throtl".
220  */
221 #define throtl_log(sq, fmt, args...)    do {                            \
222         struct throtl_grp *__tg = sq_to_tg((sq));                       \
223         struct throtl_data *__td = sq_to_td((sq));                      \
224                                                                         \
225         (void)__td;                                                     \
226         if (likely(!blk_trace_note_message_enabled(__td->queue)))       \
227                 break;                                                  \
228         if ((__tg)) {                                                   \
229                 blk_add_cgroup_trace_msg(__td->queue,                   \
230                         &tg_to_blkg(__tg)->blkcg->css, "throtl " fmt, ##args);\
231         } else {                                                        \
232                 blk_add_trace_msg(__td->queue, "throtl " fmt, ##args);  \
233         }                                                               \
234 } while (0)
235
236 static inline unsigned int throtl_bio_data_size(struct bio *bio)
237 {
238         /* assume it's one sector */
239         if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
240                 return 512;
241         return bio->bi_iter.bi_size;
242 }
243
244 static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
245 {
246         INIT_LIST_HEAD(&qn->node);
247         bio_list_init(&qn->bios);
248         qn->tg = tg;
249 }
250
251 /**
252  * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
253  * @bio: bio being added
254  * @qn: qnode to add bio to
255  * @queued: the service_queue->queued[] list @qn belongs to
256  *
257  * Add @bio to @qn and put @qn on @queued if it's not already on.
258  * @qn->tg's reference count is bumped when @qn is activated.  See the
259  * comment on top of throtl_qnode definition for details.
260  */
261 static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
262                                  struct list_head *queued)
263 {
264         bio_list_add(&qn->bios, bio);
265         if (list_empty(&qn->node)) {
266                 list_add_tail(&qn->node, queued);
267                 blkg_get(tg_to_blkg(qn->tg));
268         }
269 }
270
271 /**
272  * throtl_peek_queued - peek the first bio on a qnode list
273  * @queued: the qnode list to peek
274  */
275 static struct bio *throtl_peek_queued(struct list_head *queued)
276 {
277         struct throtl_qnode *qn;
278         struct bio *bio;
279
280         if (list_empty(queued))
281                 return NULL;
282
283         qn = list_first_entry(queued, struct throtl_qnode, node);
284         bio = bio_list_peek(&qn->bios);
285         WARN_ON_ONCE(!bio);
286         return bio;
287 }
288
289 /**
290  * throtl_pop_queued - pop the first bio form a qnode list
291  * @queued: the qnode list to pop a bio from
292  * @tg_to_put: optional out argument for throtl_grp to put
293  *
294  * Pop the first bio from the qnode list @queued.  After popping, the first
295  * qnode is removed from @queued if empty or moved to the end of @queued so
296  * that the popping order is round-robin.
297  *
298  * When the first qnode is removed, its associated throtl_grp should be put
299  * too.  If @tg_to_put is NULL, this function automatically puts it;
300  * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
301  * responsible for putting it.
302  */
303 static struct bio *throtl_pop_queued(struct list_head *queued,
304                                      struct throtl_grp **tg_to_put)
305 {
306         struct throtl_qnode *qn;
307         struct bio *bio;
308
309         if (list_empty(queued))
310                 return NULL;
311
312         qn = list_first_entry(queued, struct throtl_qnode, node);
313         bio = bio_list_pop(&qn->bios);
314         WARN_ON_ONCE(!bio);
315
316         if (bio_list_empty(&qn->bios)) {
317                 list_del_init(&qn->node);
318                 if (tg_to_put)
319                         *tg_to_put = qn->tg;
320                 else
321                         blkg_put(tg_to_blkg(qn->tg));
322         } else {
323                 list_move_tail(&qn->node, queued);
324         }
325
326         return bio;
327 }
328
329 /* init a service_queue, assumes the caller zeroed it */
330 static void throtl_service_queue_init(struct throtl_service_queue *sq)
331 {
332         INIT_LIST_HEAD(&sq->queued[READ]);
333         INIT_LIST_HEAD(&sq->queued[WRITE]);
334         sq->pending_tree = RB_ROOT_CACHED;
335         timer_setup(&sq->pending_timer, throtl_pending_timer_fn, 0);
336 }
337
338 static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp,
339                                                 struct request_queue *q,
340                                                 struct blkcg *blkcg)
341 {
342         struct throtl_grp *tg;
343         int rw;
344
345         tg = kzalloc_node(sizeof(*tg), gfp, q->node);
346         if (!tg)
347                 return NULL;
348
349         if (blkg_rwstat_init(&tg->stat_bytes, gfp))
350                 goto err_free_tg;
351
352         if (blkg_rwstat_init(&tg->stat_ios, gfp))
353                 goto err_exit_stat_bytes;
354
355         throtl_service_queue_init(&tg->service_queue);
356
357         for (rw = READ; rw <= WRITE; rw++) {
358                 throtl_qnode_init(&tg->qnode_on_self[rw], tg);
359                 throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
360         }
361
362         RB_CLEAR_NODE(&tg->rb_node);
363         tg->bps[READ][LIMIT_MAX] = U64_MAX;
364         tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
365         tg->iops[READ][LIMIT_MAX] = UINT_MAX;
366         tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
367         tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
368         tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
369         tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
370         tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
371         /* LIMIT_LOW will have default value 0 */
372
373         tg->latency_target = DFL_LATENCY_TARGET;
374         tg->latency_target_conf = DFL_LATENCY_TARGET;
375         tg->idletime_threshold = DFL_IDLE_THRESHOLD;
376         tg->idletime_threshold_conf = DFL_IDLE_THRESHOLD;
377
378         return &tg->pd;
379
380 err_exit_stat_bytes:
381         blkg_rwstat_exit(&tg->stat_bytes);
382 err_free_tg:
383         kfree(tg);
384         return NULL;
385 }
386
387 static void throtl_pd_init(struct blkg_policy_data *pd)
388 {
389         struct throtl_grp *tg = pd_to_tg(pd);
390         struct blkcg_gq *blkg = tg_to_blkg(tg);
391         struct throtl_data *td = blkg->q->td;
392         struct throtl_service_queue *sq = &tg->service_queue;
393
394         /*
395          * If on the default hierarchy, we switch to properly hierarchical
396          * behavior where limits on a given throtl_grp are applied to the
397          * whole subtree rather than just the group itself.  e.g. If 16M
398          * read_bps limit is set on the root group, the whole system can't
399          * exceed 16M for the device.
400          *
401          * If not on the default hierarchy, the broken flat hierarchy
402          * behavior is retained where all throtl_grps are treated as if
403          * they're all separate root groups right below throtl_data.
404          * Limits of a group don't interact with limits of other groups
405          * regardless of the position of the group in the hierarchy.
406          */
407         sq->parent_sq = &td->service_queue;
408         if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
409                 sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
410         tg->td = td;
411 }
412
413 /*
414  * Set has_rules[] if @tg or any of its parents have limits configured.
415  * This doesn't require walking up to the top of the hierarchy as the
416  * parent's has_rules[] is guaranteed to be correct.
417  */
418 static void tg_update_has_rules(struct throtl_grp *tg)
419 {
420         struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
421         struct throtl_data *td = tg->td;
422         int rw;
423
424         for (rw = READ; rw <= WRITE; rw++)
425                 tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
426                         (td->limit_valid[td->limit_index] &&
427                          (tg_bps_limit(tg, rw) != U64_MAX ||
428                           tg_iops_limit(tg, rw) != UINT_MAX));
429 }
430
431 static void throtl_pd_online(struct blkg_policy_data *pd)
432 {
433         struct throtl_grp *tg = pd_to_tg(pd);
434         /*
435          * We don't want new groups to escape the limits of its ancestors.
436          * Update has_rules[] after a new group is brought online.
437          */
438         tg_update_has_rules(tg);
439 }
440
441 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
442 static void blk_throtl_update_limit_valid(struct throtl_data *td)
443 {
444         struct cgroup_subsys_state *pos_css;
445         struct blkcg_gq *blkg;
446         bool low_valid = false;
447
448         rcu_read_lock();
449         blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
450                 struct throtl_grp *tg = blkg_to_tg(blkg);
451
452                 if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
453                     tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) {
454                         low_valid = true;
455                         break;
456                 }
457         }
458         rcu_read_unlock();
459
460         td->limit_valid[LIMIT_LOW] = low_valid;
461 }
462 #else
463 static inline void blk_throtl_update_limit_valid(struct throtl_data *td)
464 {
465 }
466 #endif
467
468 static void throtl_upgrade_state(struct throtl_data *td);
469 static void throtl_pd_offline(struct blkg_policy_data *pd)
470 {
471         struct throtl_grp *tg = pd_to_tg(pd);
472
473         tg->bps[READ][LIMIT_LOW] = 0;
474         tg->bps[WRITE][LIMIT_LOW] = 0;
475         tg->iops[READ][LIMIT_LOW] = 0;
476         tg->iops[WRITE][LIMIT_LOW] = 0;
477
478         blk_throtl_update_limit_valid(tg->td);
479
480         if (!tg->td->limit_valid[tg->td->limit_index])
481                 throtl_upgrade_state(tg->td);
482 }
483
484 static void throtl_pd_free(struct blkg_policy_data *pd)
485 {
486         struct throtl_grp *tg = pd_to_tg(pd);
487
488         del_timer_sync(&tg->service_queue.pending_timer);
489         blkg_rwstat_exit(&tg->stat_bytes);
490         blkg_rwstat_exit(&tg->stat_ios);
491         kfree(tg);
492 }
493
494 static struct throtl_grp *
495 throtl_rb_first(struct throtl_service_queue *parent_sq)
496 {
497         struct rb_node *n;
498
499         n = rb_first_cached(&parent_sq->pending_tree);
500         WARN_ON_ONCE(!n);
501         if (!n)
502                 return NULL;
503         return rb_entry_tg(n);
504 }
505
506 static void throtl_rb_erase(struct rb_node *n,
507                             struct throtl_service_queue *parent_sq)
508 {
509         rb_erase_cached(n, &parent_sq->pending_tree);
510         RB_CLEAR_NODE(n);
511 }
512
513 static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
514 {
515         struct throtl_grp *tg;
516
517         tg = throtl_rb_first(parent_sq);
518         if (!tg)
519                 return;
520
521         parent_sq->first_pending_disptime = tg->disptime;
522 }
523
524 static void tg_service_queue_add(struct throtl_grp *tg)
525 {
526         struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
527         struct rb_node **node = &parent_sq->pending_tree.rb_root.rb_node;
528         struct rb_node *parent = NULL;
529         struct throtl_grp *__tg;
530         unsigned long key = tg->disptime;
531         bool leftmost = true;
532
533         while (*node != NULL) {
534                 parent = *node;
535                 __tg = rb_entry_tg(parent);
536
537                 if (time_before(key, __tg->disptime))
538                         node = &parent->rb_left;
539                 else {
540                         node = &parent->rb_right;
541                         leftmost = false;
542                 }
543         }
544
545         rb_link_node(&tg->rb_node, parent, node);
546         rb_insert_color_cached(&tg->rb_node, &parent_sq->pending_tree,
547                                leftmost);
548 }
549
550 static void throtl_enqueue_tg(struct throtl_grp *tg)
551 {
552         if (!(tg->flags & THROTL_TG_PENDING)) {
553                 tg_service_queue_add(tg);
554                 tg->flags |= THROTL_TG_PENDING;
555                 tg->service_queue.parent_sq->nr_pending++;
556         }
557 }
558
559 static void throtl_dequeue_tg(struct throtl_grp *tg)
560 {
561         if (tg->flags & THROTL_TG_PENDING) {
562                 struct throtl_service_queue *parent_sq =
563                         tg->service_queue.parent_sq;
564
565                 throtl_rb_erase(&tg->rb_node, parent_sq);
566                 --parent_sq->nr_pending;
567                 tg->flags &= ~THROTL_TG_PENDING;
568         }
569 }
570
571 /* Call with queue lock held */
572 static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
573                                           unsigned long expires)
574 {
575         unsigned long max_expire = jiffies + 8 * sq_to_td(sq)->throtl_slice;
576
577         /*
578          * Since we are adjusting the throttle limit dynamically, the sleep
579          * time calculated according to previous limit might be invalid. It's
580          * possible the cgroup sleep time is very long and no other cgroups
581          * have IO running so notify the limit changes. Make sure the cgroup
582          * doesn't sleep too long to avoid the missed notification.
583          */
584         if (time_after(expires, max_expire))
585                 expires = max_expire;
586         mod_timer(&sq->pending_timer, expires);
587         throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
588                    expires - jiffies, jiffies);
589 }
590
591 /**
592  * throtl_schedule_next_dispatch - schedule the next dispatch cycle
593  * @sq: the service_queue to schedule dispatch for
594  * @force: force scheduling
595  *
596  * Arm @sq->pending_timer so that the next dispatch cycle starts on the
597  * dispatch time of the first pending child.  Returns %true if either timer
598  * is armed or there's no pending child left.  %false if the current
599  * dispatch window is still open and the caller should continue
600  * dispatching.
601  *
602  * If @force is %true, the dispatch timer is always scheduled and this
603  * function is guaranteed to return %true.  This is to be used when the
604  * caller can't dispatch itself and needs to invoke pending_timer
605  * unconditionally.  Note that forced scheduling is likely to induce short
606  * delay before dispatch starts even if @sq->first_pending_disptime is not
607  * in the future and thus shouldn't be used in hot paths.
608  */
609 static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
610                                           bool force)
611 {
612         /* any pending children left? */
613         if (!sq->nr_pending)
614                 return true;
615
616         update_min_dispatch_time(sq);
617
618         /* is the next dispatch time in the future? */
619         if (force || time_after(sq->first_pending_disptime, jiffies)) {
620                 throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
621                 return true;
622         }
623
624         /* tell the caller to continue dispatching */
625         return false;
626 }
627
628 static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
629                 bool rw, unsigned long start)
630 {
631         tg->bytes_disp[rw] = 0;
632         tg->io_disp[rw] = 0;
633         tg->carryover_bytes[rw] = 0;
634         tg->carryover_ios[rw] = 0;
635
636         /*
637          * Previous slice has expired. We must have trimmed it after last
638          * bio dispatch. That means since start of last slice, we never used
639          * that bandwidth. Do try to make use of that bandwidth while giving
640          * credit.
641          */
642         if (time_after_eq(start, tg->slice_start[rw]))
643                 tg->slice_start[rw] = start;
644
645         tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
646         throtl_log(&tg->service_queue,
647                    "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
648                    rw == READ ? 'R' : 'W', tg->slice_start[rw],
649                    tg->slice_end[rw], jiffies);
650 }
651
652 static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw,
653                                           bool clear_carryover)
654 {
655         tg->bytes_disp[rw] = 0;
656         tg->io_disp[rw] = 0;
657         tg->slice_start[rw] = jiffies;
658         tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
659         if (clear_carryover) {
660                 tg->carryover_bytes[rw] = 0;
661                 tg->carryover_ios[rw] = 0;
662         }
663
664         throtl_log(&tg->service_queue,
665                    "[%c] new slice start=%lu end=%lu jiffies=%lu",
666                    rw == READ ? 'R' : 'W', tg->slice_start[rw],
667                    tg->slice_end[rw], jiffies);
668 }
669
670 static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
671                                         unsigned long jiffy_end)
672 {
673         tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
674 }
675
676 static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
677                                        unsigned long jiffy_end)
678 {
679         throtl_set_slice_end(tg, rw, jiffy_end);
680         throtl_log(&tg->service_queue,
681                    "[%c] extend slice start=%lu end=%lu jiffies=%lu",
682                    rw == READ ? 'R' : 'W', tg->slice_start[rw],
683                    tg->slice_end[rw], jiffies);
684 }
685
686 /* Determine if previously allocated or extended slice is complete or not */
687 static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
688 {
689         if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
690                 return false;
691
692         return true;
693 }
694
695 /* Trim the used slices and adjust slice start accordingly */
696 static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
697 {
698         unsigned long nr_slices, time_elapsed, io_trim;
699         u64 bytes_trim, tmp;
700
701         BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
702
703         /*
704          * If bps are unlimited (-1), then time slice don't get
705          * renewed. Don't try to trim the slice if slice is used. A new
706          * slice will start when appropriate.
707          */
708         if (throtl_slice_used(tg, rw))
709                 return;
710
711         /*
712          * A bio has been dispatched. Also adjust slice_end. It might happen
713          * that initially cgroup limit was very low resulting in high
714          * slice_end, but later limit was bumped up and bio was dispatched
715          * sooner, then we need to reduce slice_end. A high bogus slice_end
716          * is bad because it does not allow new slice to start.
717          */
718
719         throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
720
721         time_elapsed = jiffies - tg->slice_start[rw];
722
723         nr_slices = time_elapsed / tg->td->throtl_slice;
724
725         if (!nr_slices)
726                 return;
727         tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
728         do_div(tmp, HZ);
729         bytes_trim = tmp;
730
731         io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
732                 HZ;
733
734         if (!bytes_trim && !io_trim)
735                 return;
736
737         if (tg->bytes_disp[rw] >= bytes_trim)
738                 tg->bytes_disp[rw] -= bytes_trim;
739         else
740                 tg->bytes_disp[rw] = 0;
741
742         if (tg->io_disp[rw] >= io_trim)
743                 tg->io_disp[rw] -= io_trim;
744         else
745                 tg->io_disp[rw] = 0;
746
747         tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
748
749         throtl_log(&tg->service_queue,
750                    "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
751                    rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
752                    tg->slice_start[rw], tg->slice_end[rw], jiffies);
753 }
754
755 static unsigned int calculate_io_allowed(u32 iops_limit,
756                                          unsigned long jiffy_elapsed)
757 {
758         unsigned int io_allowed;
759         u64 tmp;
760
761         /*
762          * jiffy_elapsed should not be a big value as minimum iops can be
763          * 1 then at max jiffy elapsed should be equivalent of 1 second as we
764          * will allow dispatch after 1 second and after that slice should
765          * have been trimmed.
766          */
767
768         tmp = (u64)iops_limit * jiffy_elapsed;
769         do_div(tmp, HZ);
770
771         if (tmp > UINT_MAX)
772                 io_allowed = UINT_MAX;
773         else
774                 io_allowed = tmp;
775
776         return io_allowed;
777 }
778
779 static u64 calculate_bytes_allowed(u64 bps_limit, unsigned long jiffy_elapsed)
780 {
781         return mul_u64_u64_div_u64(bps_limit, (u64)jiffy_elapsed, (u64)HZ);
782 }
783
784 static void __tg_update_carryover(struct throtl_grp *tg, bool rw)
785 {
786         unsigned long jiffy_elapsed = jiffies - tg->slice_start[rw];
787         u64 bps_limit = tg_bps_limit(tg, rw);
788         u32 iops_limit = tg_iops_limit(tg, rw);
789
790         /*
791          * If config is updated while bios are still throttled, calculate and
792          * accumulate how many bytes/ios are waited across changes. And
793          * carryover_bytes/ios will be used to calculate new wait time under new
794          * configuration.
795          */
796         if (bps_limit != U64_MAX)
797                 tg->carryover_bytes[rw] +=
798                         calculate_bytes_allowed(bps_limit, jiffy_elapsed) -
799                         tg->bytes_disp[rw];
800         if (iops_limit != UINT_MAX)
801                 tg->carryover_ios[rw] +=
802                         calculate_io_allowed(iops_limit, jiffy_elapsed) -
803                         tg->io_disp[rw];
804 }
805
806 static void tg_update_carryover(struct throtl_grp *tg)
807 {
808         if (tg->service_queue.nr_queued[READ])
809                 __tg_update_carryover(tg, READ);
810         if (tg->service_queue.nr_queued[WRITE])
811                 __tg_update_carryover(tg, WRITE);
812
813         /* see comments in struct throtl_grp for meaning of these fields. */
814         throtl_log(&tg->service_queue, "%s: %llu %llu %u %u\n", __func__,
815                    tg->carryover_bytes[READ], tg->carryover_bytes[WRITE],
816                    tg->carryover_ios[READ], tg->carryover_ios[WRITE]);
817 }
818
819 static bool tg_within_iops_limit(struct throtl_grp *tg, struct bio *bio,
820                                  u32 iops_limit, unsigned long *wait)
821 {
822         bool rw = bio_data_dir(bio);
823         unsigned int io_allowed;
824         unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
825
826         if (iops_limit == UINT_MAX) {
827                 if (wait)
828                         *wait = 0;
829                 return true;
830         }
831
832         jiffy_elapsed = jiffies - tg->slice_start[rw];
833
834         /* Round up to the next throttle slice, wait time must be nonzero */
835         jiffy_elapsed_rnd = roundup(jiffy_elapsed + 1, tg->td->throtl_slice);
836         io_allowed = calculate_io_allowed(iops_limit, jiffy_elapsed_rnd) +
837                      tg->carryover_ios[rw];
838         if (tg->io_disp[rw] + 1 <= io_allowed) {
839                 if (wait)
840                         *wait = 0;
841                 return true;
842         }
843
844         /* Calc approx time to dispatch */
845         jiffy_wait = jiffy_elapsed_rnd - jiffy_elapsed;
846
847         if (wait)
848                 *wait = jiffy_wait;
849         return false;
850 }
851
852 static bool tg_within_bps_limit(struct throtl_grp *tg, struct bio *bio,
853                                 u64 bps_limit, unsigned long *wait)
854 {
855         bool rw = bio_data_dir(bio);
856         u64 bytes_allowed, extra_bytes;
857         unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
858         unsigned int bio_size = throtl_bio_data_size(bio);
859
860         /* no need to throttle if this bio's bytes have been accounted */
861         if (bps_limit == U64_MAX || bio_flagged(bio, BIO_BPS_THROTTLED)) {
862                 if (wait)
863                         *wait = 0;
864                 return true;
865         }
866
867         jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
868
869         /* Slice has just started. Consider one slice interval */
870         if (!jiffy_elapsed)
871                 jiffy_elapsed_rnd = tg->td->throtl_slice;
872
873         jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
874         bytes_allowed = calculate_bytes_allowed(bps_limit, jiffy_elapsed_rnd) +
875                         tg->carryover_bytes[rw];
876         if (tg->bytes_disp[rw] + bio_size <= bytes_allowed) {
877                 if (wait)
878                         *wait = 0;
879                 return true;
880         }
881
882         /* Calc approx time to dispatch */
883         extra_bytes = tg->bytes_disp[rw] + bio_size - bytes_allowed;
884         jiffy_wait = div64_u64(extra_bytes * HZ, bps_limit);
885
886         if (!jiffy_wait)
887                 jiffy_wait = 1;
888
889         /*
890          * This wait time is without taking into consideration the rounding
891          * up we did. Add that time also.
892          */
893         jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
894         if (wait)
895                 *wait = jiffy_wait;
896         return false;
897 }
898
899 /*
900  * Returns whether one can dispatch a bio or not. Also returns approx number
901  * of jiffies to wait before this bio is with-in IO rate and can be dispatched
902  */
903 static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
904                             unsigned long *wait)
905 {
906         bool rw = bio_data_dir(bio);
907         unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
908         u64 bps_limit = tg_bps_limit(tg, rw);
909         u32 iops_limit = tg_iops_limit(tg, rw);
910
911         /*
912          * Currently whole state machine of group depends on first bio
913          * queued in the group bio list. So one should not be calling
914          * this function with a different bio if there are other bios
915          * queued.
916          */
917         BUG_ON(tg->service_queue.nr_queued[rw] &&
918                bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
919
920         /* If tg->bps = -1, then BW is unlimited */
921         if ((bps_limit == U64_MAX && iops_limit == UINT_MAX) ||
922             tg->flags & THROTL_TG_CANCELING) {
923                 if (wait)
924                         *wait = 0;
925                 return true;
926         }
927
928         /*
929          * If previous slice expired, start a new one otherwise renew/extend
930          * existing slice to make sure it is at least throtl_slice interval
931          * long since now. New slice is started only for empty throttle group.
932          * If there is queued bio, that means there should be an active
933          * slice and it should be extended instead.
934          */
935         if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
936                 throtl_start_new_slice(tg, rw, true);
937         else {
938                 if (time_before(tg->slice_end[rw],
939                     jiffies + tg->td->throtl_slice))
940                         throtl_extend_slice(tg, rw,
941                                 jiffies + tg->td->throtl_slice);
942         }
943
944         if (tg_within_bps_limit(tg, bio, bps_limit, &bps_wait) &&
945             tg_within_iops_limit(tg, bio, iops_limit, &iops_wait)) {
946                 if (wait)
947                         *wait = 0;
948                 return true;
949         }
950
951         max_wait = max(bps_wait, iops_wait);
952
953         if (wait)
954                 *wait = max_wait;
955
956         if (time_before(tg->slice_end[rw], jiffies + max_wait))
957                 throtl_extend_slice(tg, rw, jiffies + max_wait);
958
959         return false;
960 }
961
962 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
963 {
964         bool rw = bio_data_dir(bio);
965         unsigned int bio_size = throtl_bio_data_size(bio);
966
967         /* Charge the bio to the group */
968         if (!bio_flagged(bio, BIO_BPS_THROTTLED)) {
969                 tg->bytes_disp[rw] += bio_size;
970                 tg->last_bytes_disp[rw] += bio_size;
971         }
972
973         tg->io_disp[rw]++;
974         tg->last_io_disp[rw]++;
975 }
976
977 /**
978  * throtl_add_bio_tg - add a bio to the specified throtl_grp
979  * @bio: bio to add
980  * @qn: qnode to use
981  * @tg: the target throtl_grp
982  *
983  * Add @bio to @tg's service_queue using @qn.  If @qn is not specified,
984  * tg->qnode_on_self[] is used.
985  */
986 static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
987                               struct throtl_grp *tg)
988 {
989         struct throtl_service_queue *sq = &tg->service_queue;
990         bool rw = bio_data_dir(bio);
991
992         if (!qn)
993                 qn = &tg->qnode_on_self[rw];
994
995         /*
996          * If @tg doesn't currently have any bios queued in the same
997          * direction, queueing @bio can change when @tg should be
998          * dispatched.  Mark that @tg was empty.  This is automatically
999          * cleared on the next tg_update_disptime().
1000          */
1001         if (!sq->nr_queued[rw])
1002                 tg->flags |= THROTL_TG_WAS_EMPTY;
1003
1004         throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
1005
1006         sq->nr_queued[rw]++;
1007         throtl_enqueue_tg(tg);
1008 }
1009
1010 static void tg_update_disptime(struct throtl_grp *tg)
1011 {
1012         struct throtl_service_queue *sq = &tg->service_queue;
1013         unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
1014         struct bio *bio;
1015
1016         bio = throtl_peek_queued(&sq->queued[READ]);
1017         if (bio)
1018                 tg_may_dispatch(tg, bio, &read_wait);
1019
1020         bio = throtl_peek_queued(&sq->queued[WRITE]);
1021         if (bio)
1022                 tg_may_dispatch(tg, bio, &write_wait);
1023
1024         min_wait = min(read_wait, write_wait);
1025         disptime = jiffies + min_wait;
1026
1027         /* Update dispatch time */
1028         throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
1029         tg->disptime = disptime;
1030         tg_service_queue_add(tg);
1031
1032         /* see throtl_add_bio_tg() */
1033         tg->flags &= ~THROTL_TG_WAS_EMPTY;
1034 }
1035
1036 static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
1037                                         struct throtl_grp *parent_tg, bool rw)
1038 {
1039         if (throtl_slice_used(parent_tg, rw)) {
1040                 throtl_start_new_slice_with_credit(parent_tg, rw,
1041                                 child_tg->slice_start[rw]);
1042         }
1043
1044 }
1045
1046 static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
1047 {
1048         struct throtl_service_queue *sq = &tg->service_queue;
1049         struct throtl_service_queue *parent_sq = sq->parent_sq;
1050         struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
1051         struct throtl_grp *tg_to_put = NULL;
1052         struct bio *bio;
1053
1054         /*
1055          * @bio is being transferred from @tg to @parent_sq.  Popping a bio
1056          * from @tg may put its reference and @parent_sq might end up
1057          * getting released prematurely.  Remember the tg to put and put it
1058          * after @bio is transferred to @parent_sq.
1059          */
1060         bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
1061         sq->nr_queued[rw]--;
1062
1063         throtl_charge_bio(tg, bio);
1064         bio_set_flag(bio, BIO_BPS_THROTTLED);
1065
1066         /*
1067          * If our parent is another tg, we just need to transfer @bio to
1068          * the parent using throtl_add_bio_tg().  If our parent is
1069          * @td->service_queue, @bio is ready to be issued.  Put it on its
1070          * bio_lists[] and decrease total number queued.  The caller is
1071          * responsible for issuing these bios.
1072          */
1073         if (parent_tg) {
1074                 throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
1075                 start_parent_slice_with_credit(tg, parent_tg, rw);
1076         } else {
1077                 throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1078                                      &parent_sq->queued[rw]);
1079                 BUG_ON(tg->td->nr_queued[rw] <= 0);
1080                 tg->td->nr_queued[rw]--;
1081         }
1082
1083         throtl_trim_slice(tg, rw);
1084
1085         if (tg_to_put)
1086                 blkg_put(tg_to_blkg(tg_to_put));
1087 }
1088
1089 static int throtl_dispatch_tg(struct throtl_grp *tg)
1090 {
1091         struct throtl_service_queue *sq = &tg->service_queue;
1092         unsigned int nr_reads = 0, nr_writes = 0;
1093         unsigned int max_nr_reads = THROTL_GRP_QUANTUM * 3 / 4;
1094         unsigned int max_nr_writes = THROTL_GRP_QUANTUM - max_nr_reads;
1095         struct bio *bio;
1096
1097         /* Try to dispatch 75% READS and 25% WRITES */
1098
1099         while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
1100                tg_may_dispatch(tg, bio, NULL)) {
1101
1102                 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1103                 nr_reads++;
1104
1105                 if (nr_reads >= max_nr_reads)
1106                         break;
1107         }
1108
1109         while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
1110                tg_may_dispatch(tg, bio, NULL)) {
1111
1112                 tg_dispatch_one_bio(tg, bio_data_dir(bio));
1113                 nr_writes++;
1114
1115                 if (nr_writes >= max_nr_writes)
1116                         break;
1117         }
1118
1119         return nr_reads + nr_writes;
1120 }
1121
1122 static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
1123 {
1124         unsigned int nr_disp = 0;
1125
1126         while (1) {
1127                 struct throtl_grp *tg;
1128                 struct throtl_service_queue *sq;
1129
1130                 if (!parent_sq->nr_pending)
1131                         break;
1132
1133                 tg = throtl_rb_first(parent_sq);
1134                 if (!tg)
1135                         break;
1136
1137                 if (time_before(jiffies, tg->disptime))
1138                         break;
1139
1140                 nr_disp += throtl_dispatch_tg(tg);
1141
1142                 sq = &tg->service_queue;
1143                 if (sq->nr_queued[READ] || sq->nr_queued[WRITE])
1144                         tg_update_disptime(tg);
1145                 else
1146                         throtl_dequeue_tg(tg);
1147
1148                 if (nr_disp >= THROTL_QUANTUM)
1149                         break;
1150         }
1151
1152         return nr_disp;
1153 }
1154
1155 static bool throtl_can_upgrade(struct throtl_data *td,
1156         struct throtl_grp *this_tg);
1157 /**
1158  * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1159  * @t: the pending_timer member of the throtl_service_queue being serviced
1160  *
1161  * This timer is armed when a child throtl_grp with active bio's become
1162  * pending and queued on the service_queue's pending_tree and expires when
1163  * the first child throtl_grp should be dispatched.  This function
1164  * dispatches bio's from the children throtl_grps to the parent
1165  * service_queue.
1166  *
1167  * If the parent's parent is another throtl_grp, dispatching is propagated
1168  * by either arming its pending_timer or repeating dispatch directly.  If
1169  * the top-level service_tree is reached, throtl_data->dispatch_work is
1170  * kicked so that the ready bio's are issued.
1171  */
1172 static void throtl_pending_timer_fn(struct timer_list *t)
1173 {
1174         struct throtl_service_queue *sq = from_timer(sq, t, pending_timer);
1175         struct throtl_grp *tg = sq_to_tg(sq);
1176         struct throtl_data *td = sq_to_td(sq);
1177         struct throtl_service_queue *parent_sq;
1178         struct request_queue *q;
1179         bool dispatched;
1180         int ret;
1181
1182         /* throtl_data may be gone, so figure out request queue by blkg */
1183         if (tg)
1184                 q = tg->pd.blkg->q;
1185         else
1186                 q = td->queue;
1187
1188         spin_lock_irq(&q->queue_lock);
1189
1190         if (!q->root_blkg)
1191                 goto out_unlock;
1192
1193         if (throtl_can_upgrade(td, NULL))
1194                 throtl_upgrade_state(td);
1195
1196 again:
1197         parent_sq = sq->parent_sq;
1198         dispatched = false;
1199
1200         while (true) {
1201                 throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
1202                            sq->nr_queued[READ] + sq->nr_queued[WRITE],
1203                            sq->nr_queued[READ], sq->nr_queued[WRITE]);
1204
1205                 ret = throtl_select_dispatch(sq);
1206                 if (ret) {
1207                         throtl_log(sq, "bios disp=%u", ret);
1208                         dispatched = true;
1209                 }
1210
1211                 if (throtl_schedule_next_dispatch(sq, false))
1212                         break;
1213
1214                 /* this dispatch windows is still open, relax and repeat */
1215                 spin_unlock_irq(&q->queue_lock);
1216                 cpu_relax();
1217                 spin_lock_irq(&q->queue_lock);
1218         }
1219
1220         if (!dispatched)
1221                 goto out_unlock;
1222
1223         if (parent_sq) {
1224                 /* @parent_sq is another throl_grp, propagate dispatch */
1225                 if (tg->flags & THROTL_TG_WAS_EMPTY) {
1226                         tg_update_disptime(tg);
1227                         if (!throtl_schedule_next_dispatch(parent_sq, false)) {
1228                                 /* window is already open, repeat dispatching */
1229                                 sq = parent_sq;
1230                                 tg = sq_to_tg(sq);
1231                                 goto again;
1232                         }
1233                 }
1234         } else {
1235                 /* reached the top-level, queue issuing */
1236                 queue_work(kthrotld_workqueue, &td->dispatch_work);
1237         }
1238 out_unlock:
1239         spin_unlock_irq(&q->queue_lock);
1240 }
1241
1242 /**
1243  * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1244  * @work: work item being executed
1245  *
1246  * This function is queued for execution when bios reach the bio_lists[]
1247  * of throtl_data->service_queue.  Those bios are ready and issued by this
1248  * function.
1249  */
1250 static void blk_throtl_dispatch_work_fn(struct work_struct *work)
1251 {
1252         struct throtl_data *td = container_of(work, struct throtl_data,
1253                                               dispatch_work);
1254         struct throtl_service_queue *td_sq = &td->service_queue;
1255         struct request_queue *q = td->queue;
1256         struct bio_list bio_list_on_stack;
1257         struct bio *bio;
1258         struct blk_plug plug;
1259         int rw;
1260
1261         bio_list_init(&bio_list_on_stack);
1262
1263         spin_lock_irq(&q->queue_lock);
1264         for (rw = READ; rw <= WRITE; rw++)
1265                 while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
1266                         bio_list_add(&bio_list_on_stack, bio);
1267         spin_unlock_irq(&q->queue_lock);
1268
1269         if (!bio_list_empty(&bio_list_on_stack)) {
1270                 blk_start_plug(&plug);
1271                 while ((bio = bio_list_pop(&bio_list_on_stack)))
1272                         submit_bio_noacct_nocheck(bio);
1273                 blk_finish_plug(&plug);
1274         }
1275 }
1276
1277 static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1278                               int off)
1279 {
1280         struct throtl_grp *tg = pd_to_tg(pd);
1281         u64 v = *(u64 *)((void *)tg + off);
1282
1283         if (v == U64_MAX)
1284                 return 0;
1285         return __blkg_prfill_u64(sf, pd, v);
1286 }
1287
1288 static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1289                                int off)
1290 {
1291         struct throtl_grp *tg = pd_to_tg(pd);
1292         unsigned int v = *(unsigned int *)((void *)tg + off);
1293
1294         if (v == UINT_MAX)
1295                 return 0;
1296         return __blkg_prfill_u64(sf, pd, v);
1297 }
1298
1299 static int tg_print_conf_u64(struct seq_file *sf, void *v)
1300 {
1301         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1302                           &blkcg_policy_throtl, seq_cft(sf)->private, false);
1303         return 0;
1304 }
1305
1306 static int tg_print_conf_uint(struct seq_file *sf, void *v)
1307 {
1308         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1309                           &blkcg_policy_throtl, seq_cft(sf)->private, false);
1310         return 0;
1311 }
1312
1313 static void tg_conf_updated(struct throtl_grp *tg, bool global)
1314 {
1315         struct throtl_service_queue *sq = &tg->service_queue;
1316         struct cgroup_subsys_state *pos_css;
1317         struct blkcg_gq *blkg;
1318
1319         throtl_log(&tg->service_queue,
1320                    "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
1321                    tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1322                    tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
1323
1324         /*
1325          * Update has_rules[] flags for the updated tg's subtree.  A tg is
1326          * considered to have rules if either the tg itself or any of its
1327          * ancestors has rules.  This identifies groups without any
1328          * restrictions in the whole hierarchy and allows them to bypass
1329          * blk-throttle.
1330          */
1331         blkg_for_each_descendant_pre(blkg, pos_css,
1332                         global ? tg->td->queue->root_blkg : tg_to_blkg(tg)) {
1333                 struct throtl_grp *this_tg = blkg_to_tg(blkg);
1334                 struct throtl_grp *parent_tg;
1335
1336                 tg_update_has_rules(this_tg);
1337                 /* ignore root/second level */
1338                 if (!cgroup_subsys_on_dfl(io_cgrp_subsys) || !blkg->parent ||
1339                     !blkg->parent->parent)
1340                         continue;
1341                 parent_tg = blkg_to_tg(blkg->parent);
1342                 /*
1343                  * make sure all children has lower idle time threshold and
1344                  * higher latency target
1345                  */
1346                 this_tg->idletime_threshold = min(this_tg->idletime_threshold,
1347                                 parent_tg->idletime_threshold);
1348                 this_tg->latency_target = max(this_tg->latency_target,
1349                                 parent_tg->latency_target);
1350         }
1351
1352         /*
1353          * We're already holding queue_lock and know @tg is valid.  Let's
1354          * apply the new config directly.
1355          *
1356          * Restart the slices for both READ and WRITES. It might happen
1357          * that a group's limit are dropped suddenly and we don't want to
1358          * account recently dispatched IO with new low rate.
1359          */
1360         throtl_start_new_slice(tg, READ, false);
1361         throtl_start_new_slice(tg, WRITE, false);
1362
1363         if (tg->flags & THROTL_TG_PENDING) {
1364                 tg_update_disptime(tg);
1365                 throtl_schedule_next_dispatch(sq->parent_sq, true);
1366         }
1367 }
1368
1369 static ssize_t tg_set_conf(struct kernfs_open_file *of,
1370                            char *buf, size_t nbytes, loff_t off, bool is_u64)
1371 {
1372         struct blkcg *blkcg = css_to_blkcg(of_css(of));
1373         struct blkg_conf_ctx ctx;
1374         struct throtl_grp *tg;
1375         int ret;
1376         u64 v;
1377
1378         ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1379         if (ret)
1380                 return ret;
1381
1382         ret = -EINVAL;
1383         if (sscanf(ctx.body, "%llu", &v) != 1)
1384                 goto out_finish;
1385         if (!v)
1386                 v = U64_MAX;
1387
1388         tg = blkg_to_tg(ctx.blkg);
1389         tg_update_carryover(tg);
1390
1391         if (is_u64)
1392                 *(u64 *)((void *)tg + of_cft(of)->private) = v;
1393         else
1394                 *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
1395
1396         tg_conf_updated(tg, false);
1397         ret = 0;
1398 out_finish:
1399         blkg_conf_finish(&ctx);
1400         return ret ?: nbytes;
1401 }
1402
1403 static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1404                                char *buf, size_t nbytes, loff_t off)
1405 {
1406         return tg_set_conf(of, buf, nbytes, off, true);
1407 }
1408
1409 static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1410                                 char *buf, size_t nbytes, loff_t off)
1411 {
1412         return tg_set_conf(of, buf, nbytes, off, false);
1413 }
1414
1415 static int tg_print_rwstat(struct seq_file *sf, void *v)
1416 {
1417         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1418                           blkg_prfill_rwstat, &blkcg_policy_throtl,
1419                           seq_cft(sf)->private, true);
1420         return 0;
1421 }
1422
1423 static u64 tg_prfill_rwstat_recursive(struct seq_file *sf,
1424                                       struct blkg_policy_data *pd, int off)
1425 {
1426         struct blkg_rwstat_sample sum;
1427
1428         blkg_rwstat_recursive_sum(pd_to_blkg(pd), &blkcg_policy_throtl, off,
1429                                   &sum);
1430         return __blkg_prfill_rwstat(sf, pd, &sum);
1431 }
1432
1433 static int tg_print_rwstat_recursive(struct seq_file *sf, void *v)
1434 {
1435         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1436                           tg_prfill_rwstat_recursive, &blkcg_policy_throtl,
1437                           seq_cft(sf)->private, true);
1438         return 0;
1439 }
1440
1441 static struct cftype throtl_legacy_files[] = {
1442         {
1443                 .name = "throttle.read_bps_device",
1444                 .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
1445                 .seq_show = tg_print_conf_u64,
1446                 .write = tg_set_conf_u64,
1447         },
1448         {
1449                 .name = "throttle.write_bps_device",
1450                 .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
1451                 .seq_show = tg_print_conf_u64,
1452                 .write = tg_set_conf_u64,
1453         },
1454         {
1455                 .name = "throttle.read_iops_device",
1456                 .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
1457                 .seq_show = tg_print_conf_uint,
1458                 .write = tg_set_conf_uint,
1459         },
1460         {
1461                 .name = "throttle.write_iops_device",
1462                 .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
1463                 .seq_show = tg_print_conf_uint,
1464                 .write = tg_set_conf_uint,
1465         },
1466         {
1467                 .name = "throttle.io_service_bytes",
1468                 .private = offsetof(struct throtl_grp, stat_bytes),
1469                 .seq_show = tg_print_rwstat,
1470         },
1471         {
1472                 .name = "throttle.io_service_bytes_recursive",
1473                 .private = offsetof(struct throtl_grp, stat_bytes),
1474                 .seq_show = tg_print_rwstat_recursive,
1475         },
1476         {
1477                 .name = "throttle.io_serviced",
1478                 .private = offsetof(struct throtl_grp, stat_ios),
1479                 .seq_show = tg_print_rwstat,
1480         },
1481         {
1482                 .name = "throttle.io_serviced_recursive",
1483                 .private = offsetof(struct throtl_grp, stat_ios),
1484                 .seq_show = tg_print_rwstat_recursive,
1485         },
1486         { }     /* terminate */
1487 };
1488
1489 static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
1490                          int off)
1491 {
1492         struct throtl_grp *tg = pd_to_tg(pd);
1493         const char *dname = blkg_dev_name(pd->blkg);
1494         char bufs[4][21] = { "max", "max", "max", "max" };
1495         u64 bps_dft;
1496         unsigned int iops_dft;
1497         char idle_time[26] = "";
1498         char latency_time[26] = "";
1499
1500         if (!dname)
1501                 return 0;
1502
1503         if (off == LIMIT_LOW) {
1504                 bps_dft = 0;
1505                 iops_dft = 0;
1506         } else {
1507                 bps_dft = U64_MAX;
1508                 iops_dft = UINT_MAX;
1509         }
1510
1511         if (tg->bps_conf[READ][off] == bps_dft &&
1512             tg->bps_conf[WRITE][off] == bps_dft &&
1513             tg->iops_conf[READ][off] == iops_dft &&
1514             tg->iops_conf[WRITE][off] == iops_dft &&
1515             (off != LIMIT_LOW ||
1516              (tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD &&
1517               tg->latency_target_conf == DFL_LATENCY_TARGET)))
1518                 return 0;
1519
1520         if (tg->bps_conf[READ][off] != U64_MAX)
1521                 snprintf(bufs[0], sizeof(bufs[0]), "%llu",
1522                         tg->bps_conf[READ][off]);
1523         if (tg->bps_conf[WRITE][off] != U64_MAX)
1524                 snprintf(bufs[1], sizeof(bufs[1]), "%llu",
1525                         tg->bps_conf[WRITE][off]);
1526         if (tg->iops_conf[READ][off] != UINT_MAX)
1527                 snprintf(bufs[2], sizeof(bufs[2]), "%u",
1528                         tg->iops_conf[READ][off]);
1529         if (tg->iops_conf[WRITE][off] != UINT_MAX)
1530                 snprintf(bufs[3], sizeof(bufs[3]), "%u",
1531                         tg->iops_conf[WRITE][off]);
1532         if (off == LIMIT_LOW) {
1533                 if (tg->idletime_threshold_conf == ULONG_MAX)
1534                         strcpy(idle_time, " idle=max");
1535                 else
1536                         snprintf(idle_time, sizeof(idle_time), " idle=%lu",
1537                                 tg->idletime_threshold_conf);
1538
1539                 if (tg->latency_target_conf == ULONG_MAX)
1540                         strcpy(latency_time, " latency=max");
1541                 else
1542                         snprintf(latency_time, sizeof(latency_time),
1543                                 " latency=%lu", tg->latency_target_conf);
1544         }
1545
1546         seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s%s%s\n",
1547                    dname, bufs[0], bufs[1], bufs[2], bufs[3], idle_time,
1548                    latency_time);
1549         return 0;
1550 }
1551
1552 static int tg_print_limit(struct seq_file *sf, void *v)
1553 {
1554         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
1555                           &blkcg_policy_throtl, seq_cft(sf)->private, false);
1556         return 0;
1557 }
1558
1559 static ssize_t tg_set_limit(struct kernfs_open_file *of,
1560                           char *buf, size_t nbytes, loff_t off)
1561 {
1562         struct blkcg *blkcg = css_to_blkcg(of_css(of));
1563         struct blkg_conf_ctx ctx;
1564         struct throtl_grp *tg;
1565         u64 v[4];
1566         unsigned long idle_time;
1567         unsigned long latency_time;
1568         int ret;
1569         int index = of_cft(of)->private;
1570
1571         ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1572         if (ret)
1573                 return ret;
1574
1575         tg = blkg_to_tg(ctx.blkg);
1576         tg_update_carryover(tg);
1577
1578         v[0] = tg->bps_conf[READ][index];
1579         v[1] = tg->bps_conf[WRITE][index];
1580         v[2] = tg->iops_conf[READ][index];
1581         v[3] = tg->iops_conf[WRITE][index];
1582
1583         idle_time = tg->idletime_threshold_conf;
1584         latency_time = tg->latency_target_conf;
1585         while (true) {
1586                 char tok[27];   /* wiops=18446744073709551616 */
1587                 char *p;
1588                 u64 val = U64_MAX;
1589                 int len;
1590
1591                 if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
1592                         break;
1593                 if (tok[0] == '\0')
1594                         break;
1595                 ctx.body += len;
1596
1597                 ret = -EINVAL;
1598                 p = tok;
1599                 strsep(&p, "=");
1600                 if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
1601                         goto out_finish;
1602
1603                 ret = -ERANGE;
1604                 if (!val)
1605                         goto out_finish;
1606
1607                 ret = -EINVAL;
1608                 if (!strcmp(tok, "rbps") && val > 1)
1609                         v[0] = val;
1610                 else if (!strcmp(tok, "wbps") && val > 1)
1611                         v[1] = val;
1612                 else if (!strcmp(tok, "riops") && val > 1)
1613                         v[2] = min_t(u64, val, UINT_MAX);
1614                 else if (!strcmp(tok, "wiops") && val > 1)
1615                         v[3] = min_t(u64, val, UINT_MAX);
1616                 else if (off == LIMIT_LOW && !strcmp(tok, "idle"))
1617                         idle_time = val;
1618                 else if (off == LIMIT_LOW && !strcmp(tok, "latency"))
1619                         latency_time = val;
1620                 else
1621                         goto out_finish;
1622         }
1623
1624         tg->bps_conf[READ][index] = v[0];
1625         tg->bps_conf[WRITE][index] = v[1];
1626         tg->iops_conf[READ][index] = v[2];
1627         tg->iops_conf[WRITE][index] = v[3];
1628
1629         if (index == LIMIT_MAX) {
1630                 tg->bps[READ][index] = v[0];
1631                 tg->bps[WRITE][index] = v[1];
1632                 tg->iops[READ][index] = v[2];
1633                 tg->iops[WRITE][index] = v[3];
1634         }
1635         tg->bps[READ][LIMIT_LOW] = min(tg->bps_conf[READ][LIMIT_LOW],
1636                 tg->bps_conf[READ][LIMIT_MAX]);
1637         tg->bps[WRITE][LIMIT_LOW] = min(tg->bps_conf[WRITE][LIMIT_LOW],
1638                 tg->bps_conf[WRITE][LIMIT_MAX]);
1639         tg->iops[READ][LIMIT_LOW] = min(tg->iops_conf[READ][LIMIT_LOW],
1640                 tg->iops_conf[READ][LIMIT_MAX]);
1641         tg->iops[WRITE][LIMIT_LOW] = min(tg->iops_conf[WRITE][LIMIT_LOW],
1642                 tg->iops_conf[WRITE][LIMIT_MAX]);
1643         tg->idletime_threshold_conf = idle_time;
1644         tg->latency_target_conf = latency_time;
1645
1646         /* force user to configure all settings for low limit  */
1647         if (!(tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW] ||
1648               tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) ||
1649             tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD ||
1650             tg->latency_target_conf == DFL_LATENCY_TARGET) {
1651                 tg->bps[READ][LIMIT_LOW] = 0;
1652                 tg->bps[WRITE][LIMIT_LOW] = 0;
1653                 tg->iops[READ][LIMIT_LOW] = 0;
1654                 tg->iops[WRITE][LIMIT_LOW] = 0;
1655                 tg->idletime_threshold = DFL_IDLE_THRESHOLD;
1656                 tg->latency_target = DFL_LATENCY_TARGET;
1657         } else if (index == LIMIT_LOW) {
1658                 tg->idletime_threshold = tg->idletime_threshold_conf;
1659                 tg->latency_target = tg->latency_target_conf;
1660         }
1661
1662         blk_throtl_update_limit_valid(tg->td);
1663         if (tg->td->limit_valid[LIMIT_LOW]) {
1664                 if (index == LIMIT_LOW)
1665                         tg->td->limit_index = LIMIT_LOW;
1666         } else
1667                 tg->td->limit_index = LIMIT_MAX;
1668         tg_conf_updated(tg, index == LIMIT_LOW &&
1669                 tg->td->limit_valid[LIMIT_LOW]);
1670         ret = 0;
1671 out_finish:
1672         blkg_conf_finish(&ctx);
1673         return ret ?: nbytes;
1674 }
1675
1676 static struct cftype throtl_files[] = {
1677 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1678         {
1679                 .name = "low",
1680                 .flags = CFTYPE_NOT_ON_ROOT,
1681                 .seq_show = tg_print_limit,
1682                 .write = tg_set_limit,
1683                 .private = LIMIT_LOW,
1684         },
1685 #endif
1686         {
1687                 .name = "max",
1688                 .flags = CFTYPE_NOT_ON_ROOT,
1689                 .seq_show = tg_print_limit,
1690                 .write = tg_set_limit,
1691                 .private = LIMIT_MAX,
1692         },
1693         { }     /* terminate */
1694 };
1695
1696 static void throtl_shutdown_wq(struct request_queue *q)
1697 {
1698         struct throtl_data *td = q->td;
1699
1700         cancel_work_sync(&td->dispatch_work);
1701 }
1702
1703 struct blkcg_policy blkcg_policy_throtl = {
1704         .dfl_cftypes            = throtl_files,
1705         .legacy_cftypes         = throtl_legacy_files,
1706
1707         .pd_alloc_fn            = throtl_pd_alloc,
1708         .pd_init_fn             = throtl_pd_init,
1709         .pd_online_fn           = throtl_pd_online,
1710         .pd_offline_fn          = throtl_pd_offline,
1711         .pd_free_fn             = throtl_pd_free,
1712 };
1713
1714 void blk_throtl_cancel_bios(struct request_queue *q)
1715 {
1716         struct cgroup_subsys_state *pos_css;
1717         struct blkcg_gq *blkg;
1718
1719         spin_lock_irq(&q->queue_lock);
1720         /*
1721          * queue_lock is held, rcu lock is not needed here technically.
1722          * However, rcu lock is still held to emphasize that following
1723          * path need RCU protection and to prevent warning from lockdep.
1724          */
1725         rcu_read_lock();
1726         blkg_for_each_descendant_post(blkg, pos_css, q->root_blkg) {
1727                 struct throtl_grp *tg = blkg_to_tg(blkg);
1728                 struct throtl_service_queue *sq = &tg->service_queue;
1729
1730                 /*
1731                  * Set the flag to make sure throtl_pending_timer_fn() won't
1732                  * stop until all throttled bios are dispatched.
1733                  */
1734                 blkg_to_tg(blkg)->flags |= THROTL_TG_CANCELING;
1735                 /*
1736                  * Update disptime after setting the above flag to make sure
1737                  * throtl_select_dispatch() won't exit without dispatching.
1738                  */
1739                 tg_update_disptime(tg);
1740
1741                 throtl_schedule_pending_timer(sq, jiffies + 1);
1742         }
1743         rcu_read_unlock();
1744         spin_unlock_irq(&q->queue_lock);
1745 }
1746
1747 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1748 static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
1749 {
1750         unsigned long rtime = jiffies, wtime = jiffies;
1751
1752         if (tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW])
1753                 rtime = tg->last_low_overflow_time[READ];
1754         if (tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
1755                 wtime = tg->last_low_overflow_time[WRITE];
1756         return min(rtime, wtime);
1757 }
1758
1759 /* tg should not be an intermediate node */
1760 static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
1761 {
1762         struct throtl_service_queue *parent_sq;
1763         struct throtl_grp *parent = tg;
1764         unsigned long ret = __tg_last_low_overflow_time(tg);
1765
1766         while (true) {
1767                 parent_sq = parent->service_queue.parent_sq;
1768                 parent = sq_to_tg(parent_sq);
1769                 if (!parent)
1770                         break;
1771
1772                 /*
1773                  * The parent doesn't have low limit, it always reaches low
1774                  * limit. Its overflow time is useless for children
1775                  */
1776                 if (!parent->bps[READ][LIMIT_LOW] &&
1777                     !parent->iops[READ][LIMIT_LOW] &&
1778                     !parent->bps[WRITE][LIMIT_LOW] &&
1779                     !parent->iops[WRITE][LIMIT_LOW])
1780                         continue;
1781                 if (time_after(__tg_last_low_overflow_time(parent), ret))
1782                         ret = __tg_last_low_overflow_time(parent);
1783         }
1784         return ret;
1785 }
1786
1787 static bool throtl_tg_is_idle(struct throtl_grp *tg)
1788 {
1789         /*
1790          * cgroup is idle if:
1791          * - single idle is too long, longer than a fixed value (in case user
1792          *   configure a too big threshold) or 4 times of idletime threshold
1793          * - average think time is more than threshold
1794          * - IO latency is largely below threshold
1795          */
1796         unsigned long time;
1797         bool ret;
1798
1799         time = min_t(unsigned long, MAX_IDLE_TIME, 4 * tg->idletime_threshold);
1800         ret = tg->latency_target == DFL_LATENCY_TARGET ||
1801               tg->idletime_threshold == DFL_IDLE_THRESHOLD ||
1802               (ktime_get_ns() >> 10) - tg->last_finish_time > time ||
1803               tg->avg_idletime > tg->idletime_threshold ||
1804               (tg->latency_target && tg->bio_cnt &&
1805                 tg->bad_bio_cnt * 5 < tg->bio_cnt);
1806         throtl_log(&tg->service_queue,
1807                 "avg_idle=%ld, idle_threshold=%ld, bad_bio=%d, total_bio=%d, is_idle=%d, scale=%d",
1808                 tg->avg_idletime, tg->idletime_threshold, tg->bad_bio_cnt,
1809                 tg->bio_cnt, ret, tg->td->scale);
1810         return ret;
1811 }
1812
1813 static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
1814 {
1815         struct throtl_service_queue *sq = &tg->service_queue;
1816         bool read_limit, write_limit;
1817
1818         /*
1819          * if cgroup reaches low limit (if low limit is 0, the cgroup always
1820          * reaches), it's ok to upgrade to next limit
1821          */
1822         read_limit = tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW];
1823         write_limit = tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW];
1824         if (!read_limit && !write_limit)
1825                 return true;
1826         if (read_limit && sq->nr_queued[READ] &&
1827             (!write_limit || sq->nr_queued[WRITE]))
1828                 return true;
1829         if (write_limit && sq->nr_queued[WRITE] &&
1830             (!read_limit || sq->nr_queued[READ]))
1831                 return true;
1832
1833         if (time_after_eq(jiffies,
1834                 tg_last_low_overflow_time(tg) + tg->td->throtl_slice) &&
1835             throtl_tg_is_idle(tg))
1836                 return true;
1837         return false;
1838 }
1839
1840 static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
1841 {
1842         while (true) {
1843                 if (throtl_tg_can_upgrade(tg))
1844                         return true;
1845                 tg = sq_to_tg(tg->service_queue.parent_sq);
1846                 if (!tg || !tg_to_blkg(tg)->parent)
1847                         return false;
1848         }
1849         return false;
1850 }
1851
1852 static bool throtl_can_upgrade(struct throtl_data *td,
1853         struct throtl_grp *this_tg)
1854 {
1855         struct cgroup_subsys_state *pos_css;
1856         struct blkcg_gq *blkg;
1857
1858         if (td->limit_index != LIMIT_LOW)
1859                 return false;
1860
1861         if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
1862                 return false;
1863
1864         rcu_read_lock();
1865         blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1866                 struct throtl_grp *tg = blkg_to_tg(blkg);
1867
1868                 if (tg == this_tg)
1869                         continue;
1870                 if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1871                         continue;
1872                 if (!throtl_hierarchy_can_upgrade(tg)) {
1873                         rcu_read_unlock();
1874                         return false;
1875                 }
1876         }
1877         rcu_read_unlock();
1878         return true;
1879 }
1880
1881 static void throtl_upgrade_check(struct throtl_grp *tg)
1882 {
1883         unsigned long now = jiffies;
1884
1885         if (tg->td->limit_index != LIMIT_LOW)
1886                 return;
1887
1888         if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1889                 return;
1890
1891         tg->last_check_time = now;
1892
1893         if (!time_after_eq(now,
1894              __tg_last_low_overflow_time(tg) + tg->td->throtl_slice))
1895                 return;
1896
1897         if (throtl_can_upgrade(tg->td, NULL))
1898                 throtl_upgrade_state(tg->td);
1899 }
1900
1901 static void throtl_upgrade_state(struct throtl_data *td)
1902 {
1903         struct cgroup_subsys_state *pos_css;
1904         struct blkcg_gq *blkg;
1905
1906         throtl_log(&td->service_queue, "upgrade to max");
1907         td->limit_index = LIMIT_MAX;
1908         td->low_upgrade_time = jiffies;
1909         td->scale = 0;
1910         rcu_read_lock();
1911         blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1912                 struct throtl_grp *tg = blkg_to_tg(blkg);
1913                 struct throtl_service_queue *sq = &tg->service_queue;
1914
1915                 tg->disptime = jiffies - 1;
1916                 throtl_select_dispatch(sq);
1917                 throtl_schedule_next_dispatch(sq, true);
1918         }
1919         rcu_read_unlock();
1920         throtl_select_dispatch(&td->service_queue);
1921         throtl_schedule_next_dispatch(&td->service_queue, true);
1922         queue_work(kthrotld_workqueue, &td->dispatch_work);
1923 }
1924
1925 static void throtl_downgrade_state(struct throtl_data *td)
1926 {
1927         td->scale /= 2;
1928
1929         throtl_log(&td->service_queue, "downgrade, scale %d", td->scale);
1930         if (td->scale) {
1931                 td->low_upgrade_time = jiffies - td->scale * td->throtl_slice;
1932                 return;
1933         }
1934
1935         td->limit_index = LIMIT_LOW;
1936         td->low_downgrade_time = jiffies;
1937 }
1938
1939 static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
1940 {
1941         struct throtl_data *td = tg->td;
1942         unsigned long now = jiffies;
1943
1944         /*
1945          * If cgroup is below low limit, consider downgrade and throttle other
1946          * cgroups
1947          */
1948         if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
1949             time_after_eq(now, tg_last_low_overflow_time(tg) +
1950                                         td->throtl_slice) &&
1951             (!throtl_tg_is_idle(tg) ||
1952              !list_empty(&tg_to_blkg(tg)->blkcg->css.children)))
1953                 return true;
1954         return false;
1955 }
1956
1957 static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
1958 {
1959         while (true) {
1960                 if (!throtl_tg_can_downgrade(tg))
1961                         return false;
1962                 tg = sq_to_tg(tg->service_queue.parent_sq);
1963                 if (!tg || !tg_to_blkg(tg)->parent)
1964                         break;
1965         }
1966         return true;
1967 }
1968
1969 static void throtl_downgrade_check(struct throtl_grp *tg)
1970 {
1971         uint64_t bps;
1972         unsigned int iops;
1973         unsigned long elapsed_time;
1974         unsigned long now = jiffies;
1975
1976         if (tg->td->limit_index != LIMIT_MAX ||
1977             !tg->td->limit_valid[LIMIT_LOW])
1978                 return;
1979         if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1980                 return;
1981         if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1982                 return;
1983
1984         elapsed_time = now - tg->last_check_time;
1985         tg->last_check_time = now;
1986
1987         if (time_before(now, tg_last_low_overflow_time(tg) +
1988                         tg->td->throtl_slice))
1989                 return;
1990
1991         if (tg->bps[READ][LIMIT_LOW]) {
1992                 bps = tg->last_bytes_disp[READ] * HZ;
1993                 do_div(bps, elapsed_time);
1994                 if (bps >= tg->bps[READ][LIMIT_LOW])
1995                         tg->last_low_overflow_time[READ] = now;
1996         }
1997
1998         if (tg->bps[WRITE][LIMIT_LOW]) {
1999                 bps = tg->last_bytes_disp[WRITE] * HZ;
2000                 do_div(bps, elapsed_time);
2001                 if (bps >= tg->bps[WRITE][LIMIT_LOW])
2002                         tg->last_low_overflow_time[WRITE] = now;
2003         }
2004
2005         if (tg->iops[READ][LIMIT_LOW]) {
2006                 iops = tg->last_io_disp[READ] * HZ / elapsed_time;
2007                 if (iops >= tg->iops[READ][LIMIT_LOW])
2008                         tg->last_low_overflow_time[READ] = now;
2009         }
2010
2011         if (tg->iops[WRITE][LIMIT_LOW]) {
2012                 iops = tg->last_io_disp[WRITE] * HZ / elapsed_time;
2013                 if (iops >= tg->iops[WRITE][LIMIT_LOW])
2014                         tg->last_low_overflow_time[WRITE] = now;
2015         }
2016
2017         /*
2018          * If cgroup is below low limit, consider downgrade and throttle other
2019          * cgroups
2020          */
2021         if (throtl_hierarchy_can_downgrade(tg))
2022                 throtl_downgrade_state(tg->td);
2023
2024         tg->last_bytes_disp[READ] = 0;
2025         tg->last_bytes_disp[WRITE] = 0;
2026         tg->last_io_disp[READ] = 0;
2027         tg->last_io_disp[WRITE] = 0;
2028 }
2029
2030 static void blk_throtl_update_idletime(struct throtl_grp *tg)
2031 {
2032         unsigned long now;
2033         unsigned long last_finish_time = tg->last_finish_time;
2034
2035         if (last_finish_time == 0)
2036                 return;
2037
2038         now = ktime_get_ns() >> 10;
2039         if (now <= last_finish_time ||
2040             last_finish_time == tg->checked_last_finish_time)
2041                 return;
2042
2043         tg->avg_idletime = (tg->avg_idletime * 7 + now - last_finish_time) >> 3;
2044         tg->checked_last_finish_time = last_finish_time;
2045 }
2046
2047 static void throtl_update_latency_buckets(struct throtl_data *td)
2048 {
2049         struct avg_latency_bucket avg_latency[2][LATENCY_BUCKET_SIZE];
2050         int i, cpu, rw;
2051         unsigned long last_latency[2] = { 0 };
2052         unsigned long latency[2];
2053
2054         if (!blk_queue_nonrot(td->queue) || !td->limit_valid[LIMIT_LOW])
2055                 return;
2056         if (time_before(jiffies, td->last_calculate_time + HZ))
2057                 return;
2058         td->last_calculate_time = jiffies;
2059
2060         memset(avg_latency, 0, sizeof(avg_latency));
2061         for (rw = READ; rw <= WRITE; rw++) {
2062                 for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2063                         struct latency_bucket *tmp = &td->tmp_buckets[rw][i];
2064
2065                         for_each_possible_cpu(cpu) {
2066                                 struct latency_bucket *bucket;
2067
2068                                 /* this isn't race free, but ok in practice */
2069                                 bucket = per_cpu_ptr(td->latency_buckets[rw],
2070                                         cpu);
2071                                 tmp->total_latency += bucket[i].total_latency;
2072                                 tmp->samples += bucket[i].samples;
2073                                 bucket[i].total_latency = 0;
2074                                 bucket[i].samples = 0;
2075                         }
2076
2077                         if (tmp->samples >= 32) {
2078                                 int samples = tmp->samples;
2079
2080                                 latency[rw] = tmp->total_latency;
2081
2082                                 tmp->total_latency = 0;
2083                                 tmp->samples = 0;
2084                                 latency[rw] /= samples;
2085                                 if (latency[rw] == 0)
2086                                         continue;
2087                                 avg_latency[rw][i].latency = latency[rw];
2088                         }
2089                 }
2090         }
2091
2092         for (rw = READ; rw <= WRITE; rw++) {
2093                 for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2094                         if (!avg_latency[rw][i].latency) {
2095                                 if (td->avg_buckets[rw][i].latency < last_latency[rw])
2096                                         td->avg_buckets[rw][i].latency =
2097                                                 last_latency[rw];
2098                                 continue;
2099                         }
2100
2101                         if (!td->avg_buckets[rw][i].valid)
2102                                 latency[rw] = avg_latency[rw][i].latency;
2103                         else
2104                                 latency[rw] = (td->avg_buckets[rw][i].latency * 7 +
2105                                         avg_latency[rw][i].latency) >> 3;
2106
2107                         td->avg_buckets[rw][i].latency = max(latency[rw],
2108                                 last_latency[rw]);
2109                         td->avg_buckets[rw][i].valid = true;
2110                         last_latency[rw] = td->avg_buckets[rw][i].latency;
2111                 }
2112         }
2113
2114         for (i = 0; i < LATENCY_BUCKET_SIZE; i++)
2115                 throtl_log(&td->service_queue,
2116                         "Latency bucket %d: read latency=%ld, read valid=%d, "
2117                         "write latency=%ld, write valid=%d", i,
2118                         td->avg_buckets[READ][i].latency,
2119                         td->avg_buckets[READ][i].valid,
2120                         td->avg_buckets[WRITE][i].latency,
2121                         td->avg_buckets[WRITE][i].valid);
2122 }
2123 #else
2124 static inline void throtl_update_latency_buckets(struct throtl_data *td)
2125 {
2126 }
2127
2128 static void blk_throtl_update_idletime(struct throtl_grp *tg)
2129 {
2130 }
2131
2132 static void throtl_downgrade_check(struct throtl_grp *tg)
2133 {
2134 }
2135
2136 static void throtl_upgrade_check(struct throtl_grp *tg)
2137 {
2138 }
2139
2140 static bool throtl_can_upgrade(struct throtl_data *td,
2141         struct throtl_grp *this_tg)
2142 {
2143         return false;
2144 }
2145
2146 static void throtl_upgrade_state(struct throtl_data *td)
2147 {
2148 }
2149 #endif
2150
2151 bool __blk_throtl_bio(struct bio *bio)
2152 {
2153         struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2154         struct blkcg_gq *blkg = bio->bi_blkg;
2155         struct throtl_qnode *qn = NULL;
2156         struct throtl_grp *tg = blkg_to_tg(blkg);
2157         struct throtl_service_queue *sq;
2158         bool rw = bio_data_dir(bio);
2159         bool throttled = false;
2160         struct throtl_data *td = tg->td;
2161
2162         rcu_read_lock();
2163
2164         if (!cgroup_subsys_on_dfl(io_cgrp_subsys)) {
2165                 blkg_rwstat_add(&tg->stat_bytes, bio->bi_opf,
2166                                 bio->bi_iter.bi_size);
2167                 blkg_rwstat_add(&tg->stat_ios, bio->bi_opf, 1);
2168         }
2169
2170         spin_lock_irq(&q->queue_lock);
2171
2172         throtl_update_latency_buckets(td);
2173
2174         blk_throtl_update_idletime(tg);
2175
2176         sq = &tg->service_queue;
2177
2178 again:
2179         while (true) {
2180                 if (tg->last_low_overflow_time[rw] == 0)
2181                         tg->last_low_overflow_time[rw] = jiffies;
2182                 throtl_downgrade_check(tg);
2183                 throtl_upgrade_check(tg);
2184                 /* throtl is FIFO - if bios are already queued, should queue */
2185                 if (sq->nr_queued[rw])
2186                         break;
2187
2188                 /* if above limits, break to queue */
2189                 if (!tg_may_dispatch(tg, bio, NULL)) {
2190                         tg->last_low_overflow_time[rw] = jiffies;
2191                         if (throtl_can_upgrade(td, tg)) {
2192                                 throtl_upgrade_state(td);
2193                                 goto again;
2194                         }
2195                         break;
2196                 }
2197
2198                 /* within limits, let's charge and dispatch directly */
2199                 throtl_charge_bio(tg, bio);
2200
2201                 /*
2202                  * We need to trim slice even when bios are not being queued
2203                  * otherwise it might happen that a bio is not queued for
2204                  * a long time and slice keeps on extending and trim is not
2205                  * called for a long time. Now if limits are reduced suddenly
2206                  * we take into account all the IO dispatched so far at new
2207                  * low rate and * newly queued IO gets a really long dispatch
2208                  * time.
2209                  *
2210                  * So keep on trimming slice even if bio is not queued.
2211                  */
2212                 throtl_trim_slice(tg, rw);
2213
2214                 /*
2215                  * @bio passed through this layer without being throttled.
2216                  * Climb up the ladder.  If we're already at the top, it
2217                  * can be executed directly.
2218                  */
2219                 qn = &tg->qnode_on_parent[rw];
2220                 sq = sq->parent_sq;
2221                 tg = sq_to_tg(sq);
2222                 if (!tg) {
2223                         bio_set_flag(bio, BIO_BPS_THROTTLED);
2224                         goto out_unlock;
2225                 }
2226         }
2227
2228         /* out-of-limit, queue to @tg */
2229         throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
2230                    rw == READ ? 'R' : 'W',
2231                    tg->bytes_disp[rw], bio->bi_iter.bi_size,
2232                    tg_bps_limit(tg, rw),
2233                    tg->io_disp[rw], tg_iops_limit(tg, rw),
2234                    sq->nr_queued[READ], sq->nr_queued[WRITE]);
2235
2236         tg->last_low_overflow_time[rw] = jiffies;
2237
2238         td->nr_queued[rw]++;
2239         throtl_add_bio_tg(bio, qn, tg);
2240         throttled = true;
2241
2242         /*
2243          * Update @tg's dispatch time and force schedule dispatch if @tg
2244          * was empty before @bio.  The forced scheduling isn't likely to
2245          * cause undue delay as @bio is likely to be dispatched directly if
2246          * its @tg's disptime is not in the future.
2247          */
2248         if (tg->flags & THROTL_TG_WAS_EMPTY) {
2249                 tg_update_disptime(tg);
2250                 throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
2251         }
2252
2253 out_unlock:
2254 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2255         if (throttled || !td->track_bio_latency)
2256                 bio->bi_issue.value |= BIO_ISSUE_THROTL_SKIP_LATENCY;
2257 #endif
2258         spin_unlock_irq(&q->queue_lock);
2259
2260         rcu_read_unlock();
2261         return throttled;
2262 }
2263
2264 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2265 static void throtl_track_latency(struct throtl_data *td, sector_t size,
2266                                  enum req_op op, unsigned long time)
2267 {
2268         const bool rw = op_is_write(op);
2269         struct latency_bucket *latency;
2270         int index;
2271
2272         if (!td || td->limit_index != LIMIT_LOW ||
2273             !(op == REQ_OP_READ || op == REQ_OP_WRITE) ||
2274             !blk_queue_nonrot(td->queue))
2275                 return;
2276
2277         index = request_bucket_index(size);
2278
2279         latency = get_cpu_ptr(td->latency_buckets[rw]);
2280         latency[index].total_latency += time;
2281         latency[index].samples++;
2282         put_cpu_ptr(td->latency_buckets[rw]);
2283 }
2284
2285 void blk_throtl_stat_add(struct request *rq, u64 time_ns)
2286 {
2287         struct request_queue *q = rq->q;
2288         struct throtl_data *td = q->td;
2289
2290         throtl_track_latency(td, blk_rq_stats_sectors(rq), req_op(rq),
2291                              time_ns >> 10);
2292 }
2293
2294 void blk_throtl_bio_endio(struct bio *bio)
2295 {
2296         struct blkcg_gq *blkg;
2297         struct throtl_grp *tg;
2298         u64 finish_time_ns;
2299         unsigned long finish_time;
2300         unsigned long start_time;
2301         unsigned long lat;
2302         int rw = bio_data_dir(bio);
2303
2304         blkg = bio->bi_blkg;
2305         if (!blkg)
2306                 return;
2307         tg = blkg_to_tg(blkg);
2308         if (!tg->td->limit_valid[LIMIT_LOW])
2309                 return;
2310
2311         finish_time_ns = ktime_get_ns();
2312         tg->last_finish_time = finish_time_ns >> 10;
2313
2314         start_time = bio_issue_time(&bio->bi_issue) >> 10;
2315         finish_time = __bio_issue_time(finish_time_ns) >> 10;
2316         if (!start_time || finish_time <= start_time)
2317                 return;
2318
2319         lat = finish_time - start_time;
2320         /* this is only for bio based driver */
2321         if (!(bio->bi_issue.value & BIO_ISSUE_THROTL_SKIP_LATENCY))
2322                 throtl_track_latency(tg->td, bio_issue_size(&bio->bi_issue),
2323                                      bio_op(bio), lat);
2324
2325         if (tg->latency_target && lat >= tg->td->filtered_latency) {
2326                 int bucket;
2327                 unsigned int threshold;
2328
2329                 bucket = request_bucket_index(bio_issue_size(&bio->bi_issue));
2330                 threshold = tg->td->avg_buckets[rw][bucket].latency +
2331                         tg->latency_target;
2332                 if (lat > threshold)
2333                         tg->bad_bio_cnt++;
2334                 /*
2335                  * Not race free, could get wrong count, which means cgroups
2336                  * will be throttled
2337                  */
2338                 tg->bio_cnt++;
2339         }
2340
2341         if (time_after(jiffies, tg->bio_cnt_reset_time) || tg->bio_cnt > 1024) {
2342                 tg->bio_cnt_reset_time = tg->td->throtl_slice + jiffies;
2343                 tg->bio_cnt /= 2;
2344                 tg->bad_bio_cnt /= 2;
2345         }
2346 }
2347 #endif
2348
2349 int blk_throtl_init(struct request_queue *q)
2350 {
2351         struct throtl_data *td;
2352         int ret;
2353
2354         td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
2355         if (!td)
2356                 return -ENOMEM;
2357         td->latency_buckets[READ] = __alloc_percpu(sizeof(struct latency_bucket) *
2358                 LATENCY_BUCKET_SIZE, __alignof__(u64));
2359         if (!td->latency_buckets[READ]) {
2360                 kfree(td);
2361                 return -ENOMEM;
2362         }
2363         td->latency_buckets[WRITE] = __alloc_percpu(sizeof(struct latency_bucket) *
2364                 LATENCY_BUCKET_SIZE, __alignof__(u64));
2365         if (!td->latency_buckets[WRITE]) {
2366                 free_percpu(td->latency_buckets[READ]);
2367                 kfree(td);
2368                 return -ENOMEM;
2369         }
2370
2371         INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
2372         throtl_service_queue_init(&td->service_queue);
2373
2374         q->td = td;
2375         td->queue = q;
2376
2377         td->limit_valid[LIMIT_MAX] = true;
2378         td->limit_index = LIMIT_MAX;
2379         td->low_upgrade_time = jiffies;
2380         td->low_downgrade_time = jiffies;
2381
2382         /* activate policy */
2383         ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
2384         if (ret) {
2385                 free_percpu(td->latency_buckets[READ]);
2386                 free_percpu(td->latency_buckets[WRITE]);
2387                 kfree(td);
2388         }
2389         return ret;
2390 }
2391
2392 void blk_throtl_exit(struct request_queue *q)
2393 {
2394         BUG_ON(!q->td);
2395         del_timer_sync(&q->td->service_queue.pending_timer);
2396         throtl_shutdown_wq(q);
2397         blkcg_deactivate_policy(q, &blkcg_policy_throtl);
2398         free_percpu(q->td->latency_buckets[READ]);
2399         free_percpu(q->td->latency_buckets[WRITE]);
2400         kfree(q->td);
2401 }
2402
2403 void blk_throtl_register_queue(struct request_queue *q)
2404 {
2405         struct throtl_data *td;
2406         int i;
2407
2408         td = q->td;
2409         BUG_ON(!td);
2410
2411         if (blk_queue_nonrot(q)) {
2412                 td->throtl_slice = DFL_THROTL_SLICE_SSD;
2413                 td->filtered_latency = LATENCY_FILTERED_SSD;
2414         } else {
2415                 td->throtl_slice = DFL_THROTL_SLICE_HD;
2416                 td->filtered_latency = LATENCY_FILTERED_HD;
2417                 for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2418                         td->avg_buckets[READ][i].latency = DFL_HD_BASELINE_LATENCY;
2419                         td->avg_buckets[WRITE][i].latency = DFL_HD_BASELINE_LATENCY;
2420                 }
2421         }
2422 #ifndef CONFIG_BLK_DEV_THROTTLING_LOW
2423         /* if no low limit, use previous default */
2424         td->throtl_slice = DFL_THROTL_SLICE_HD;
2425 #endif
2426
2427         td->track_bio_latency = !queue_is_mq(q);
2428         if (!td->track_bio_latency)
2429                 blk_stat_enable_accounting(q);
2430 }
2431
2432 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2433 ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
2434 {
2435         if (!q->td)
2436                 return -EINVAL;
2437         return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
2438 }
2439
2440 ssize_t blk_throtl_sample_time_store(struct request_queue *q,
2441         const char *page, size_t count)
2442 {
2443         unsigned long v;
2444         unsigned long t;
2445
2446         if (!q->td)
2447                 return -EINVAL;
2448         if (kstrtoul(page, 10, &v))
2449                 return -EINVAL;
2450         t = msecs_to_jiffies(v);
2451         if (t == 0 || t > MAX_THROTL_SLICE)
2452                 return -EINVAL;
2453         q->td->throtl_slice = t;
2454         return count;
2455 }
2456 #endif
2457
2458 static int __init throtl_init(void)
2459 {
2460         kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2461         if (!kthrotld_workqueue)
2462                 panic("Failed to create kthrotld\n");
2463
2464         return blkcg_policy_register(&blkcg_policy_throtl);
2465 }
2466
2467 module_init(throtl_init);