blk-throttle: Make dispatch stats per cpu
[linux-flexiantxendom0-3.2.10.git] / block / blk-throttle.c
1 /*
2  * Interface for controlling IO bandwidth on a request queue
3  *
4  * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
5  */
6
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/blkdev.h>
10 #include <linux/bio.h>
11 #include <linux/blktrace_api.h>
12 #include "blk-cgroup.h"
13
14 /* Max dispatch from a group in 1 round */
15 static int throtl_grp_quantum = 8;
16
17 /* Total max dispatch from all groups in one round */
18 static int throtl_quantum = 32;
19
20 /* Throttling is performed over 100ms slice and after that slice is renewed */
21 static unsigned long throtl_slice = HZ/10;      /* 100 ms */
22
23 /* A workqueue to queue throttle related work */
24 static struct workqueue_struct *kthrotld_workqueue;
25 static void throtl_schedule_delayed_work(struct throtl_data *td,
26                                 unsigned long delay);
27
28 struct throtl_rb_root {
29         struct rb_root rb;
30         struct rb_node *left;
31         unsigned int count;
32         unsigned long min_disptime;
33 };
34
35 #define THROTL_RB_ROOT  (struct throtl_rb_root) { .rb = RB_ROOT, .left = NULL, \
36                         .count = 0, .min_disptime = 0}
37
38 #define rb_entry_tg(node)       rb_entry((node), struct throtl_grp, rb_node)
39
40 struct throtl_grp {
41         /* List of throtl groups on the request queue*/
42         struct hlist_node tg_node;
43
44         /* active throtl group service_tree member */
45         struct rb_node rb_node;
46
47         /*
48          * Dispatch time in jiffies. This is the estimated time when group
49          * will unthrottle and is ready to dispatch more bio. It is used as
50          * key to sort active groups in service tree.
51          */
52         unsigned long disptime;
53
54         struct blkio_group blkg;
55         atomic_t ref;
56         unsigned int flags;
57
58         /* Two lists for READ and WRITE */
59         struct bio_list bio_lists[2];
60
61         /* Number of queued bios on READ and WRITE lists */
62         unsigned int nr_queued[2];
63
64         /* bytes per second rate limits */
65         uint64_t bps[2];
66
67         /* IOPS limits */
68         unsigned int iops[2];
69
70         /* Number of bytes disptached in current slice */
71         uint64_t bytes_disp[2];
72         /* Number of bio's dispatched in current slice */
73         unsigned int io_disp[2];
74
75         /* When did we start a new slice */
76         unsigned long slice_start[2];
77         unsigned long slice_end[2];
78
79         /* Some throttle limits got updated for the group */
80         int limits_changed;
81
82         struct rcu_head rcu_head;
83 };
84
85 struct throtl_data
86 {
87         /* List of throtl groups */
88         struct hlist_head tg_list;
89
90         /* service tree for active throtl groups */
91         struct throtl_rb_root tg_service_tree;
92
93         struct throtl_grp *root_tg;
94         struct request_queue *queue;
95
96         /* Total Number of queued bios on READ and WRITE lists */
97         unsigned int nr_queued[2];
98
99         /*
100          * number of total undestroyed groups
101          */
102         unsigned int nr_undestroyed_grps;
103
104         /* Work for dispatching throttled bios */
105         struct delayed_work throtl_work;
106
107         int limits_changed;
108 };
109
110 enum tg_state_flags {
111         THROTL_TG_FLAG_on_rr = 0,       /* on round-robin busy list */
112 };
113
114 #define THROTL_TG_FNS(name)                                             \
115 static inline void throtl_mark_tg_##name(struct throtl_grp *tg)         \
116 {                                                                       \
117         (tg)->flags |= (1 << THROTL_TG_FLAG_##name);                    \
118 }                                                                       \
119 static inline void throtl_clear_tg_##name(struct throtl_grp *tg)        \
120 {                                                                       \
121         (tg)->flags &= ~(1 << THROTL_TG_FLAG_##name);                   \
122 }                                                                       \
123 static inline int throtl_tg_##name(const struct throtl_grp *tg)         \
124 {                                                                       \
125         return ((tg)->flags & (1 << THROTL_TG_FLAG_##name)) != 0;       \
126 }
127
128 THROTL_TG_FNS(on_rr);
129
130 #define throtl_log_tg(td, tg, fmt, args...)                             \
131         blk_add_trace_msg((td)->queue, "throtl %s " fmt,                \
132                                 blkg_path(&(tg)->blkg), ##args);        \
133
134 #define throtl_log(td, fmt, args...)    \
135         blk_add_trace_msg((td)->queue, "throtl " fmt, ##args)
136
137 static inline struct throtl_grp *tg_of_blkg(struct blkio_group *blkg)
138 {
139         if (blkg)
140                 return container_of(blkg, struct throtl_grp, blkg);
141
142         return NULL;
143 }
144
145 static inline int total_nr_queued(struct throtl_data *td)
146 {
147         return (td->nr_queued[0] + td->nr_queued[1]);
148 }
149
150 static inline struct throtl_grp *throtl_ref_get_tg(struct throtl_grp *tg)
151 {
152         atomic_inc(&tg->ref);
153         return tg;
154 }
155
156 static void throtl_free_tg(struct rcu_head *head)
157 {
158         struct throtl_grp *tg;
159
160         tg = container_of(head, struct throtl_grp, rcu_head);
161         free_percpu(tg->blkg.stats_cpu);
162         kfree(tg);
163 }
164
165 static void throtl_put_tg(struct throtl_grp *tg)
166 {
167         BUG_ON(atomic_read(&tg->ref) <= 0);
168         if (!atomic_dec_and_test(&tg->ref))
169                 return;
170
171         /*
172          * A group is freed in rcu manner. But having an rcu lock does not
173          * mean that one can access all the fields of blkg and assume these
174          * are valid. For example, don't try to follow throtl_data and
175          * request queue links.
176          *
177          * Having a reference to blkg under an rcu allows acess to only
178          * values local to groups like group stats and group rate limits
179          */
180         call_rcu(&tg->rcu_head, throtl_free_tg);
181 }
182
183 static void throtl_init_group(struct throtl_grp *tg)
184 {
185         INIT_HLIST_NODE(&tg->tg_node);
186         RB_CLEAR_NODE(&tg->rb_node);
187         bio_list_init(&tg->bio_lists[0]);
188         bio_list_init(&tg->bio_lists[1]);
189         tg->limits_changed = false;
190
191         /* Practically unlimited BW */
192         tg->bps[0] = tg->bps[1] = -1;
193         tg->iops[0] = tg->iops[1] = -1;
194
195         /*
196          * Take the initial reference that will be released on destroy
197          * This can be thought of a joint reference by cgroup and
198          * request queue which will be dropped by either request queue
199          * exit or cgroup deletion path depending on who is exiting first.
200          */
201         atomic_set(&tg->ref, 1);
202 }
203
204 /* Should be called with rcu read lock held (needed for blkcg) */
205 static void
206 throtl_add_group_to_td_list(struct throtl_data *td, struct throtl_grp *tg)
207 {
208         hlist_add_head(&tg->tg_node, &td->tg_list);
209         td->nr_undestroyed_grps++;
210 }
211
212 static void
213 __throtl_tg_fill_dev_details(struct throtl_data *td, struct throtl_grp *tg)
214 {
215         struct backing_dev_info *bdi = &td->queue->backing_dev_info;
216         unsigned int major, minor;
217
218         if (!tg || tg->blkg.dev)
219                 return;
220
221         /*
222          * Fill in device details for a group which might not have been
223          * filled at group creation time as queue was being instantiated
224          * and driver had not attached a device yet
225          */
226         if (bdi->dev && dev_name(bdi->dev)) {
227                 sscanf(dev_name(bdi->dev), "%u:%u", &major, &minor);
228                 tg->blkg.dev = MKDEV(major, minor);
229         }
230 }
231
232 static void throtl_init_add_tg_lists(struct throtl_data *td,
233                         struct throtl_grp *tg, struct blkio_cgroup *blkcg)
234 {
235         __throtl_tg_fill_dev_details(td, tg);
236
237         /* Add group onto cgroup list */
238         blkiocg_add_blkio_group(blkcg, &tg->blkg, (void *)td,
239                                 tg->blkg.dev, BLKIO_POLICY_THROTL);
240
241         tg->bps[READ] = blkcg_get_read_bps(blkcg, tg->blkg.dev);
242         tg->bps[WRITE] = blkcg_get_write_bps(blkcg, tg->blkg.dev);
243         tg->iops[READ] = blkcg_get_read_iops(blkcg, tg->blkg.dev);
244         tg->iops[WRITE] = blkcg_get_write_iops(blkcg, tg->blkg.dev);
245
246         throtl_add_group_to_td_list(td, tg);
247 }
248
249 /* Should be called without queue lock and outside of rcu period */
250 static struct throtl_grp *throtl_alloc_tg(struct throtl_data *td)
251 {
252         struct throtl_grp *tg = NULL;
253         int ret;
254
255         tg = kzalloc_node(sizeof(*tg), GFP_ATOMIC, td->queue->node);
256         if (!tg)
257                 return NULL;
258
259         ret = blkio_alloc_blkg_stats(&tg->blkg);
260
261         if (ret) {
262                 kfree(tg);
263                 return NULL;
264         }
265
266         throtl_init_group(tg);
267         return tg;
268 }
269
270 static struct
271 throtl_grp *throtl_find_tg(struct throtl_data *td, struct blkio_cgroup *blkcg)
272 {
273         struct throtl_grp *tg = NULL;
274         void *key = td;
275
276         /*
277          * This is the common case when there are no blkio cgroups.
278          * Avoid lookup in this case
279          */
280         if (blkcg == &blkio_root_cgroup)
281                 tg = td->root_tg;
282         else
283                 tg = tg_of_blkg(blkiocg_lookup_group(blkcg, key));
284
285         __throtl_tg_fill_dev_details(td, tg);
286         return tg;
287 }
288
289 /*
290  * This function returns with queue lock unlocked in case of error, like
291  * request queue is no more
292  */
293 static struct throtl_grp * throtl_get_tg(struct throtl_data *td)
294 {
295         struct throtl_grp *tg = NULL, *__tg = NULL;
296         struct blkio_cgroup *blkcg;
297         struct request_queue *q = td->queue;
298
299         rcu_read_lock();
300         blkcg = task_blkio_cgroup(current);
301         tg = throtl_find_tg(td, blkcg);
302         if (tg) {
303                 rcu_read_unlock();
304                 return tg;
305         }
306
307         /*
308          * Need to allocate a group. Allocation of group also needs allocation
309          * of per cpu stats which in-turn takes a mutex() and can block. Hence
310          * we need to drop rcu lock and queue_lock before we call alloc
311          *
312          * Take the request queue reference to make sure queue does not
313          * go away once we return from allocation.
314          */
315         blk_get_queue(q);
316         rcu_read_unlock();
317         spin_unlock_irq(q->queue_lock);
318
319         tg = throtl_alloc_tg(td);
320         /*
321          * We might have slept in group allocation. Make sure queue is not
322          * dead
323          */
324         if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
325                 blk_put_queue(q);
326                 if (tg)
327                         kfree(tg);
328
329                 return ERR_PTR(-ENODEV);
330         }
331         blk_put_queue(q);
332
333         /* Group allocated and queue is still alive. take the lock */
334         spin_lock_irq(q->queue_lock);
335
336         /*
337          * Initialize the new group. After sleeping, read the blkcg again.
338          */
339         rcu_read_lock();
340         blkcg = task_blkio_cgroup(current);
341
342         /*
343          * If some other thread already allocated the group while we were
344          * not holding queue lock, free up the group
345          */
346         __tg = throtl_find_tg(td, blkcg);
347
348         if (__tg) {
349                 kfree(tg);
350                 rcu_read_unlock();
351                 return __tg;
352         }
353
354         /* Group allocation failed. Account the IO to root group */
355         if (!tg) {
356                 tg = td->root_tg;
357                 return tg;
358         }
359
360         throtl_init_add_tg_lists(td, tg, blkcg);
361         rcu_read_unlock();
362         return tg;
363 }
364
365 static struct throtl_grp *throtl_rb_first(struct throtl_rb_root *root)
366 {
367         /* Service tree is empty */
368         if (!root->count)
369                 return NULL;
370
371         if (!root->left)
372                 root->left = rb_first(&root->rb);
373
374         if (root->left)
375                 return rb_entry_tg(root->left);
376
377         return NULL;
378 }
379
380 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
381 {
382         rb_erase(n, root);
383         RB_CLEAR_NODE(n);
384 }
385
386 static void throtl_rb_erase(struct rb_node *n, struct throtl_rb_root *root)
387 {
388         if (root->left == n)
389                 root->left = NULL;
390         rb_erase_init(n, &root->rb);
391         --root->count;
392 }
393
394 static void update_min_dispatch_time(struct throtl_rb_root *st)
395 {
396         struct throtl_grp *tg;
397
398         tg = throtl_rb_first(st);
399         if (!tg)
400                 return;
401
402         st->min_disptime = tg->disptime;
403 }
404
405 static void
406 tg_service_tree_add(struct throtl_rb_root *st, struct throtl_grp *tg)
407 {
408         struct rb_node **node = &st->rb.rb_node;
409         struct rb_node *parent = NULL;
410         struct throtl_grp *__tg;
411         unsigned long key = tg->disptime;
412         int left = 1;
413
414         while (*node != NULL) {
415                 parent = *node;
416                 __tg = rb_entry_tg(parent);
417
418                 if (time_before(key, __tg->disptime))
419                         node = &parent->rb_left;
420                 else {
421                         node = &parent->rb_right;
422                         left = 0;
423                 }
424         }
425
426         if (left)
427                 st->left = &tg->rb_node;
428
429         rb_link_node(&tg->rb_node, parent, node);
430         rb_insert_color(&tg->rb_node, &st->rb);
431 }
432
433 static void __throtl_enqueue_tg(struct throtl_data *td, struct throtl_grp *tg)
434 {
435         struct throtl_rb_root *st = &td->tg_service_tree;
436
437         tg_service_tree_add(st, tg);
438         throtl_mark_tg_on_rr(tg);
439         st->count++;
440 }
441
442 static void throtl_enqueue_tg(struct throtl_data *td, struct throtl_grp *tg)
443 {
444         if (!throtl_tg_on_rr(tg))
445                 __throtl_enqueue_tg(td, tg);
446 }
447
448 static void __throtl_dequeue_tg(struct throtl_data *td, struct throtl_grp *tg)
449 {
450         throtl_rb_erase(&tg->rb_node, &td->tg_service_tree);
451         throtl_clear_tg_on_rr(tg);
452 }
453
454 static void throtl_dequeue_tg(struct throtl_data *td, struct throtl_grp *tg)
455 {
456         if (throtl_tg_on_rr(tg))
457                 __throtl_dequeue_tg(td, tg);
458 }
459
460 static void throtl_schedule_next_dispatch(struct throtl_data *td)
461 {
462         struct throtl_rb_root *st = &td->tg_service_tree;
463
464         /*
465          * If there are more bios pending, schedule more work.
466          */
467         if (!total_nr_queued(td))
468                 return;
469
470         BUG_ON(!st->count);
471
472         update_min_dispatch_time(st);
473
474         if (time_before_eq(st->min_disptime, jiffies))
475                 throtl_schedule_delayed_work(td, 0);
476         else
477                 throtl_schedule_delayed_work(td, (st->min_disptime - jiffies));
478 }
479
480 static inline void
481 throtl_start_new_slice(struct throtl_data *td, struct throtl_grp *tg, bool rw)
482 {
483         tg->bytes_disp[rw] = 0;
484         tg->io_disp[rw] = 0;
485         tg->slice_start[rw] = jiffies;
486         tg->slice_end[rw] = jiffies + throtl_slice;
487         throtl_log_tg(td, tg, "[%c] new slice start=%lu end=%lu jiffies=%lu",
488                         rw == READ ? 'R' : 'W', tg->slice_start[rw],
489                         tg->slice_end[rw], jiffies);
490 }
491
492 static inline void throtl_set_slice_end(struct throtl_data *td,
493                 struct throtl_grp *tg, bool rw, unsigned long jiffy_end)
494 {
495         tg->slice_end[rw] = roundup(jiffy_end, throtl_slice);
496 }
497
498 static inline void throtl_extend_slice(struct throtl_data *td,
499                 struct throtl_grp *tg, bool rw, unsigned long jiffy_end)
500 {
501         tg->slice_end[rw] = roundup(jiffy_end, throtl_slice);
502         throtl_log_tg(td, tg, "[%c] extend slice start=%lu end=%lu jiffies=%lu",
503                         rw == READ ? 'R' : 'W', tg->slice_start[rw],
504                         tg->slice_end[rw], jiffies);
505 }
506
507 /* Determine if previously allocated or extended slice is complete or not */
508 static bool
509 throtl_slice_used(struct throtl_data *td, struct throtl_grp *tg, bool rw)
510 {
511         if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
512                 return 0;
513
514         return 1;
515 }
516
517 /* Trim the used slices and adjust slice start accordingly */
518 static inline void
519 throtl_trim_slice(struct throtl_data *td, struct throtl_grp *tg, bool rw)
520 {
521         unsigned long nr_slices, time_elapsed, io_trim;
522         u64 bytes_trim, tmp;
523
524         BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
525
526         /*
527          * If bps are unlimited (-1), then time slice don't get
528          * renewed. Don't try to trim the slice if slice is used. A new
529          * slice will start when appropriate.
530          */
531         if (throtl_slice_used(td, tg, rw))
532                 return;
533
534         /*
535          * A bio has been dispatched. Also adjust slice_end. It might happen
536          * that initially cgroup limit was very low resulting in high
537          * slice_end, but later limit was bumped up and bio was dispached
538          * sooner, then we need to reduce slice_end. A high bogus slice_end
539          * is bad because it does not allow new slice to start.
540          */
541
542         throtl_set_slice_end(td, tg, rw, jiffies + throtl_slice);
543
544         time_elapsed = jiffies - tg->slice_start[rw];
545
546         nr_slices = time_elapsed / throtl_slice;
547
548         if (!nr_slices)
549                 return;
550         tmp = tg->bps[rw] * throtl_slice * nr_slices;
551         do_div(tmp, HZ);
552         bytes_trim = tmp;
553
554         io_trim = (tg->iops[rw] * throtl_slice * nr_slices)/HZ;
555
556         if (!bytes_trim && !io_trim)
557                 return;
558
559         if (tg->bytes_disp[rw] >= bytes_trim)
560                 tg->bytes_disp[rw] -= bytes_trim;
561         else
562                 tg->bytes_disp[rw] = 0;
563
564         if (tg->io_disp[rw] >= io_trim)
565                 tg->io_disp[rw] -= io_trim;
566         else
567                 tg->io_disp[rw] = 0;
568
569         tg->slice_start[rw] += nr_slices * throtl_slice;
570
571         throtl_log_tg(td, tg, "[%c] trim slice nr=%lu bytes=%llu io=%lu"
572                         " start=%lu end=%lu jiffies=%lu",
573                         rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
574                         tg->slice_start[rw], tg->slice_end[rw], jiffies);
575 }
576
577 static bool tg_with_in_iops_limit(struct throtl_data *td, struct throtl_grp *tg,
578                 struct bio *bio, unsigned long *wait)
579 {
580         bool rw = bio_data_dir(bio);
581         unsigned int io_allowed;
582         unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
583         u64 tmp;
584
585         jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
586
587         /* Slice has just started. Consider one slice interval */
588         if (!jiffy_elapsed)
589                 jiffy_elapsed_rnd = throtl_slice;
590
591         jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, throtl_slice);
592
593         /*
594          * jiffy_elapsed_rnd should not be a big value as minimum iops can be
595          * 1 then at max jiffy elapsed should be equivalent of 1 second as we
596          * will allow dispatch after 1 second and after that slice should
597          * have been trimmed.
598          */
599
600         tmp = (u64)tg->iops[rw] * jiffy_elapsed_rnd;
601         do_div(tmp, HZ);
602
603         if (tmp > UINT_MAX)
604                 io_allowed = UINT_MAX;
605         else
606                 io_allowed = tmp;
607
608         if (tg->io_disp[rw] + 1 <= io_allowed) {
609                 if (wait)
610                         *wait = 0;
611                 return 1;
612         }
613
614         /* Calc approx time to dispatch */
615         jiffy_wait = ((tg->io_disp[rw] + 1) * HZ)/tg->iops[rw] + 1;
616
617         if (jiffy_wait > jiffy_elapsed)
618                 jiffy_wait = jiffy_wait - jiffy_elapsed;
619         else
620                 jiffy_wait = 1;
621
622         if (wait)
623                 *wait = jiffy_wait;
624         return 0;
625 }
626
627 static bool tg_with_in_bps_limit(struct throtl_data *td, struct throtl_grp *tg,
628                 struct bio *bio, unsigned long *wait)
629 {
630         bool rw = bio_data_dir(bio);
631         u64 bytes_allowed, extra_bytes, tmp;
632         unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
633
634         jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
635
636         /* Slice has just started. Consider one slice interval */
637         if (!jiffy_elapsed)
638                 jiffy_elapsed_rnd = throtl_slice;
639
640         jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, throtl_slice);
641
642         tmp = tg->bps[rw] * jiffy_elapsed_rnd;
643         do_div(tmp, HZ);
644         bytes_allowed = tmp;
645
646         if (tg->bytes_disp[rw] + bio->bi_size <= bytes_allowed) {
647                 if (wait)
648                         *wait = 0;
649                 return 1;
650         }
651
652         /* Calc approx time to dispatch */
653         extra_bytes = tg->bytes_disp[rw] + bio->bi_size - bytes_allowed;
654         jiffy_wait = div64_u64(extra_bytes * HZ, tg->bps[rw]);
655
656         if (!jiffy_wait)
657                 jiffy_wait = 1;
658
659         /*
660          * This wait time is without taking into consideration the rounding
661          * up we did. Add that time also.
662          */
663         jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
664         if (wait)
665                 *wait = jiffy_wait;
666         return 0;
667 }
668
669 /*
670  * Returns whether one can dispatch a bio or not. Also returns approx number
671  * of jiffies to wait before this bio is with-in IO rate and can be dispatched
672  */
673 static bool tg_may_dispatch(struct throtl_data *td, struct throtl_grp *tg,
674                                 struct bio *bio, unsigned long *wait)
675 {
676         bool rw = bio_data_dir(bio);
677         unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
678
679         /*
680          * Currently whole state machine of group depends on first bio
681          * queued in the group bio list. So one should not be calling
682          * this function with a different bio if there are other bios
683          * queued.
684          */
685         BUG_ON(tg->nr_queued[rw] && bio != bio_list_peek(&tg->bio_lists[rw]));
686
687         /* If tg->bps = -1, then BW is unlimited */
688         if (tg->bps[rw] == -1 && tg->iops[rw] == -1) {
689                 if (wait)
690                         *wait = 0;
691                 return 1;
692         }
693
694         /*
695          * If previous slice expired, start a new one otherwise renew/extend
696          * existing slice to make sure it is at least throtl_slice interval
697          * long since now.
698          */
699         if (throtl_slice_used(td, tg, rw))
700                 throtl_start_new_slice(td, tg, rw);
701         else {
702                 if (time_before(tg->slice_end[rw], jiffies + throtl_slice))
703                         throtl_extend_slice(td, tg, rw, jiffies + throtl_slice);
704         }
705
706         if (tg_with_in_bps_limit(td, tg, bio, &bps_wait)
707             && tg_with_in_iops_limit(td, tg, bio, &iops_wait)) {
708                 if (wait)
709                         *wait = 0;
710                 return 1;
711         }
712
713         max_wait = max(bps_wait, iops_wait);
714
715         if (wait)
716                 *wait = max_wait;
717
718         if (time_before(tg->slice_end[rw], jiffies + max_wait))
719                 throtl_extend_slice(td, tg, rw, jiffies + max_wait);
720
721         return 0;
722 }
723
724 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
725 {
726         bool rw = bio_data_dir(bio);
727         bool sync = bio->bi_rw & REQ_SYNC;
728
729         /* Charge the bio to the group */
730         tg->bytes_disp[rw] += bio->bi_size;
731         tg->io_disp[rw]++;
732
733         /*
734          * TODO: This will take blkg->stats_lock. Figure out a way
735          * to avoid this cost.
736          */
737         blkiocg_update_dispatch_stats(&tg->blkg, bio->bi_size, rw, sync);
738 }
739
740 static void throtl_add_bio_tg(struct throtl_data *td, struct throtl_grp *tg,
741                         struct bio *bio)
742 {
743         bool rw = bio_data_dir(bio);
744
745         bio_list_add(&tg->bio_lists[rw], bio);
746         /* Take a bio reference on tg */
747         throtl_ref_get_tg(tg);
748         tg->nr_queued[rw]++;
749         td->nr_queued[rw]++;
750         throtl_enqueue_tg(td, tg);
751 }
752
753 static void tg_update_disptime(struct throtl_data *td, struct throtl_grp *tg)
754 {
755         unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
756         struct bio *bio;
757
758         if ((bio = bio_list_peek(&tg->bio_lists[READ])))
759                 tg_may_dispatch(td, tg, bio, &read_wait);
760
761         if ((bio = bio_list_peek(&tg->bio_lists[WRITE])))
762                 tg_may_dispatch(td, tg, bio, &write_wait);
763
764         min_wait = min(read_wait, write_wait);
765         disptime = jiffies + min_wait;
766
767         /* Update dispatch time */
768         throtl_dequeue_tg(td, tg);
769         tg->disptime = disptime;
770         throtl_enqueue_tg(td, tg);
771 }
772
773 static void tg_dispatch_one_bio(struct throtl_data *td, struct throtl_grp *tg,
774                                 bool rw, struct bio_list *bl)
775 {
776         struct bio *bio;
777
778         bio = bio_list_pop(&tg->bio_lists[rw]);
779         tg->nr_queued[rw]--;
780         /* Drop bio reference on tg */
781         throtl_put_tg(tg);
782
783         BUG_ON(td->nr_queued[rw] <= 0);
784         td->nr_queued[rw]--;
785
786         throtl_charge_bio(tg, bio);
787         bio_list_add(bl, bio);
788         bio->bi_rw |= REQ_THROTTLED;
789
790         throtl_trim_slice(td, tg, rw);
791 }
792
793 static int throtl_dispatch_tg(struct throtl_data *td, struct throtl_grp *tg,
794                                 struct bio_list *bl)
795 {
796         unsigned int nr_reads = 0, nr_writes = 0;
797         unsigned int max_nr_reads = throtl_grp_quantum*3/4;
798         unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
799         struct bio *bio;
800
801         /* Try to dispatch 75% READS and 25% WRITES */
802
803         while ((bio = bio_list_peek(&tg->bio_lists[READ]))
804                 && tg_may_dispatch(td, tg, bio, NULL)) {
805
806                 tg_dispatch_one_bio(td, tg, bio_data_dir(bio), bl);
807                 nr_reads++;
808
809                 if (nr_reads >= max_nr_reads)
810                         break;
811         }
812
813         while ((bio = bio_list_peek(&tg->bio_lists[WRITE]))
814                 && tg_may_dispatch(td, tg, bio, NULL)) {
815
816                 tg_dispatch_one_bio(td, tg, bio_data_dir(bio), bl);
817                 nr_writes++;
818
819                 if (nr_writes >= max_nr_writes)
820                         break;
821         }
822
823         return nr_reads + nr_writes;
824 }
825
826 static int throtl_select_dispatch(struct throtl_data *td, struct bio_list *bl)
827 {
828         unsigned int nr_disp = 0;
829         struct throtl_grp *tg;
830         struct throtl_rb_root *st = &td->tg_service_tree;
831
832         while (1) {
833                 tg = throtl_rb_first(st);
834
835                 if (!tg)
836                         break;
837
838                 if (time_before(jiffies, tg->disptime))
839                         break;
840
841                 throtl_dequeue_tg(td, tg);
842
843                 nr_disp += throtl_dispatch_tg(td, tg, bl);
844
845                 if (tg->nr_queued[0] || tg->nr_queued[1]) {
846                         tg_update_disptime(td, tg);
847                         throtl_enqueue_tg(td, tg);
848                 }
849
850                 if (nr_disp >= throtl_quantum)
851                         break;
852         }
853
854         return nr_disp;
855 }
856
857 static void throtl_process_limit_change(struct throtl_data *td)
858 {
859         struct throtl_grp *tg;
860         struct hlist_node *pos, *n;
861
862         if (!td->limits_changed)
863                 return;
864
865         xchg(&td->limits_changed, false);
866
867         throtl_log(td, "limits changed");
868
869         hlist_for_each_entry_safe(tg, pos, n, &td->tg_list, tg_node) {
870                 if (!tg->limits_changed)
871                         continue;
872
873                 if (!xchg(&tg->limits_changed, false))
874                         continue;
875
876                 throtl_log_tg(td, tg, "limit change rbps=%llu wbps=%llu"
877                         " riops=%u wiops=%u", tg->bps[READ], tg->bps[WRITE],
878                         tg->iops[READ], tg->iops[WRITE]);
879
880                 /*
881                  * Restart the slices for both READ and WRITES. It
882                  * might happen that a group's limit are dropped
883                  * suddenly and we don't want to account recently
884                  * dispatched IO with new low rate
885                  */
886                 throtl_start_new_slice(td, tg, 0);
887                 throtl_start_new_slice(td, tg, 1);
888
889                 if (throtl_tg_on_rr(tg))
890                         tg_update_disptime(td, tg);
891         }
892 }
893
894 /* Dispatch throttled bios. Should be called without queue lock held. */
895 static int throtl_dispatch(struct request_queue *q)
896 {
897         struct throtl_data *td = q->td;
898         unsigned int nr_disp = 0;
899         struct bio_list bio_list_on_stack;
900         struct bio *bio;
901         struct blk_plug plug;
902
903         spin_lock_irq(q->queue_lock);
904
905         throtl_process_limit_change(td);
906
907         if (!total_nr_queued(td))
908                 goto out;
909
910         bio_list_init(&bio_list_on_stack);
911
912         throtl_log(td, "dispatch nr_queued=%lu read=%u write=%u",
913                         total_nr_queued(td), td->nr_queued[READ],
914                         td->nr_queued[WRITE]);
915
916         nr_disp = throtl_select_dispatch(td, &bio_list_on_stack);
917
918         if (nr_disp)
919                 throtl_log(td, "bios disp=%u", nr_disp);
920
921         throtl_schedule_next_dispatch(td);
922 out:
923         spin_unlock_irq(q->queue_lock);
924
925         /*
926          * If we dispatched some requests, unplug the queue to make sure
927          * immediate dispatch
928          */
929         if (nr_disp) {
930                 blk_start_plug(&plug);
931                 while((bio = bio_list_pop(&bio_list_on_stack)))
932                         generic_make_request(bio);
933                 blk_finish_plug(&plug);
934         }
935         return nr_disp;
936 }
937
938 void blk_throtl_work(struct work_struct *work)
939 {
940         struct throtl_data *td = container_of(work, struct throtl_data,
941                                         throtl_work.work);
942         struct request_queue *q = td->queue;
943
944         throtl_dispatch(q);
945 }
946
947 /* Call with queue lock held */
948 static void
949 throtl_schedule_delayed_work(struct throtl_data *td, unsigned long delay)
950 {
951
952         struct delayed_work *dwork = &td->throtl_work;
953
954         /* schedule work if limits changed even if no bio is queued */
955         if (total_nr_queued(td) > 0 || td->limits_changed) {
956                 /*
957                  * We might have a work scheduled to be executed in future.
958                  * Cancel that and schedule a new one.
959                  */
960                 __cancel_delayed_work(dwork);
961                 queue_delayed_work(kthrotld_workqueue, dwork, delay);
962                 throtl_log(td, "schedule work. delay=%lu jiffies=%lu",
963                                 delay, jiffies);
964         }
965 }
966
967 static void
968 throtl_destroy_tg(struct throtl_data *td, struct throtl_grp *tg)
969 {
970         /* Something wrong if we are trying to remove same group twice */
971         BUG_ON(hlist_unhashed(&tg->tg_node));
972
973         hlist_del_init(&tg->tg_node);
974
975         /*
976          * Put the reference taken at the time of creation so that when all
977          * queues are gone, group can be destroyed.
978          */
979         throtl_put_tg(tg);
980         td->nr_undestroyed_grps--;
981 }
982
983 static void throtl_release_tgs(struct throtl_data *td)
984 {
985         struct hlist_node *pos, *n;
986         struct throtl_grp *tg;
987
988         hlist_for_each_entry_safe(tg, pos, n, &td->tg_list, tg_node) {
989                 /*
990                  * If cgroup removal path got to blk_group first and removed
991                  * it from cgroup list, then it will take care of destroying
992                  * cfqg also.
993                  */
994                 if (!blkiocg_del_blkio_group(&tg->blkg))
995                         throtl_destroy_tg(td, tg);
996         }
997 }
998
999 static void throtl_td_free(struct throtl_data *td)
1000 {
1001         kfree(td);
1002 }
1003
1004 /*
1005  * Blk cgroup controller notification saying that blkio_group object is being
1006  * delinked as associated cgroup object is going away. That also means that
1007  * no new IO will come in this group. So get rid of this group as soon as
1008  * any pending IO in the group is finished.
1009  *
1010  * This function is called under rcu_read_lock(). key is the rcu protected
1011  * pointer. That means "key" is a valid throtl_data pointer as long as we are
1012  * rcu read lock.
1013  *
1014  * "key" was fetched from blkio_group under blkio_cgroup->lock. That means
1015  * it should not be NULL as even if queue was going away, cgroup deltion
1016  * path got to it first.
1017  */
1018 void throtl_unlink_blkio_group(void *key, struct blkio_group *blkg)
1019 {
1020         unsigned long flags;
1021         struct throtl_data *td = key;
1022
1023         spin_lock_irqsave(td->queue->queue_lock, flags);
1024         throtl_destroy_tg(td, tg_of_blkg(blkg));
1025         spin_unlock_irqrestore(td->queue->queue_lock, flags);
1026 }
1027
1028 static void throtl_update_blkio_group_common(struct throtl_data *td,
1029                                 struct throtl_grp *tg)
1030 {
1031         xchg(&tg->limits_changed, true);
1032         xchg(&td->limits_changed, true);
1033         /* Schedule a work now to process the limit change */
1034         throtl_schedule_delayed_work(td, 0);
1035 }
1036
1037 /*
1038  * For all update functions, key should be a valid pointer because these
1039  * update functions are called under blkcg_lock, that means, blkg is
1040  * valid and in turn key is valid. queue exit path can not race because
1041  * of blkcg_lock
1042  *
1043  * Can not take queue lock in update functions as queue lock under blkcg_lock
1044  * is not allowed. Under other paths we take blkcg_lock under queue_lock.
1045  */
1046 static void throtl_update_blkio_group_read_bps(void *key,
1047                                 struct blkio_group *blkg, u64 read_bps)
1048 {
1049         struct throtl_data *td = key;
1050         struct throtl_grp *tg = tg_of_blkg(blkg);
1051
1052         tg->bps[READ] = read_bps;
1053         throtl_update_blkio_group_common(td, tg);
1054 }
1055
1056 static void throtl_update_blkio_group_write_bps(void *key,
1057                                 struct blkio_group *blkg, u64 write_bps)
1058 {
1059         struct throtl_data *td = key;
1060         struct throtl_grp *tg = tg_of_blkg(blkg);
1061
1062         tg->bps[WRITE] = write_bps;
1063         throtl_update_blkio_group_common(td, tg);
1064 }
1065
1066 static void throtl_update_blkio_group_read_iops(void *key,
1067                         struct blkio_group *blkg, unsigned int read_iops)
1068 {
1069         struct throtl_data *td = key;
1070         struct throtl_grp *tg = tg_of_blkg(blkg);
1071
1072         tg->iops[READ] = read_iops;
1073         throtl_update_blkio_group_common(td, tg);
1074 }
1075
1076 static void throtl_update_blkio_group_write_iops(void *key,
1077                         struct blkio_group *blkg, unsigned int write_iops)
1078 {
1079         struct throtl_data *td = key;
1080         struct throtl_grp *tg = tg_of_blkg(blkg);
1081
1082         tg->iops[WRITE] = write_iops;
1083         throtl_update_blkio_group_common(td, tg);
1084 }
1085
1086 static void throtl_shutdown_wq(struct request_queue *q)
1087 {
1088         struct throtl_data *td = q->td;
1089
1090         cancel_delayed_work_sync(&td->throtl_work);
1091 }
1092
1093 static struct blkio_policy_type blkio_policy_throtl = {
1094         .ops = {
1095                 .blkio_unlink_group_fn = throtl_unlink_blkio_group,
1096                 .blkio_update_group_read_bps_fn =
1097                                         throtl_update_blkio_group_read_bps,
1098                 .blkio_update_group_write_bps_fn =
1099                                         throtl_update_blkio_group_write_bps,
1100                 .blkio_update_group_read_iops_fn =
1101                                         throtl_update_blkio_group_read_iops,
1102                 .blkio_update_group_write_iops_fn =
1103                                         throtl_update_blkio_group_write_iops,
1104         },
1105         .plid = BLKIO_POLICY_THROTL,
1106 };
1107
1108 int blk_throtl_bio(struct request_queue *q, struct bio **biop)
1109 {
1110         struct throtl_data *td = q->td;
1111         struct throtl_grp *tg;
1112         struct bio *bio = *biop;
1113         bool rw = bio_data_dir(bio), update_disptime = true;
1114
1115         if (bio->bi_rw & REQ_THROTTLED) {
1116                 bio->bi_rw &= ~REQ_THROTTLED;
1117                 return 0;
1118         }
1119
1120         spin_lock_irq(q->queue_lock);
1121         tg = throtl_get_tg(td);
1122
1123         if (IS_ERR(tg)) {
1124                 if (PTR_ERR(tg) == -ENODEV) {
1125                         /*
1126                          * Queue is gone. No queue lock held here.
1127                          */
1128                         return -ENODEV;
1129                 }
1130         }
1131
1132         if (tg->nr_queued[rw]) {
1133                 /*
1134                  * There is already another bio queued in same dir. No
1135                  * need to update dispatch time.
1136                  */
1137                 update_disptime = false;
1138                 goto queue_bio;
1139
1140         }
1141
1142         /* Bio is with-in rate limit of group */
1143         if (tg_may_dispatch(td, tg, bio, NULL)) {
1144                 throtl_charge_bio(tg, bio);
1145
1146                 /*
1147                  * We need to trim slice even when bios are not being queued
1148                  * otherwise it might happen that a bio is not queued for
1149                  * a long time and slice keeps on extending and trim is not
1150                  * called for a long time. Now if limits are reduced suddenly
1151                  * we take into account all the IO dispatched so far at new
1152                  * low rate and * newly queued IO gets a really long dispatch
1153                  * time.
1154                  *
1155                  * So keep on trimming slice even if bio is not queued.
1156                  */
1157                 throtl_trim_slice(td, tg, rw);
1158                 goto out;
1159         }
1160
1161 queue_bio:
1162         throtl_log_tg(td, tg, "[%c] bio. bdisp=%u sz=%u bps=%llu"
1163                         " iodisp=%u iops=%u queued=%d/%d",
1164                         rw == READ ? 'R' : 'W',
1165                         tg->bytes_disp[rw], bio->bi_size, tg->bps[rw],
1166                         tg->io_disp[rw], tg->iops[rw],
1167                         tg->nr_queued[READ], tg->nr_queued[WRITE]);
1168
1169         throtl_add_bio_tg(q->td, tg, bio);
1170         *biop = NULL;
1171
1172         if (update_disptime) {
1173                 tg_update_disptime(td, tg);
1174                 throtl_schedule_next_dispatch(td);
1175         }
1176
1177 out:
1178         spin_unlock_irq(q->queue_lock);
1179         return 0;
1180 }
1181
1182 int blk_throtl_init(struct request_queue *q)
1183 {
1184         struct throtl_data *td;
1185         struct throtl_grp *tg;
1186
1187         td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
1188         if (!td)
1189                 return -ENOMEM;
1190
1191         INIT_HLIST_HEAD(&td->tg_list);
1192         td->tg_service_tree = THROTL_RB_ROOT;
1193         td->limits_changed = false;
1194         INIT_DELAYED_WORK(&td->throtl_work, blk_throtl_work);
1195
1196         /* alloc and Init root group. */
1197         td->queue = q;
1198         tg = throtl_alloc_tg(td);
1199
1200         if (!tg) {
1201                 kfree(td);
1202                 return -ENOMEM;
1203         }
1204
1205         td->root_tg = tg;
1206
1207         rcu_read_lock();
1208         throtl_init_add_tg_lists(td, tg, &blkio_root_cgroup);
1209         rcu_read_unlock();
1210
1211         /* Attach throtl data to request queue */
1212         q->td = td;
1213         return 0;
1214 }
1215
1216 void blk_throtl_exit(struct request_queue *q)
1217 {
1218         struct throtl_data *td = q->td;
1219         bool wait = false;
1220
1221         BUG_ON(!td);
1222
1223         throtl_shutdown_wq(q);
1224
1225         spin_lock_irq(q->queue_lock);
1226         throtl_release_tgs(td);
1227
1228         /* If there are other groups */
1229         if (td->nr_undestroyed_grps > 0)
1230                 wait = true;
1231
1232         spin_unlock_irq(q->queue_lock);
1233
1234         /*
1235          * Wait for tg->blkg->key accessors to exit their grace periods.
1236          * Do this wait only if there are other undestroyed groups out
1237          * there (other than root group). This can happen if cgroup deletion
1238          * path claimed the responsibility of cleaning up a group before
1239          * queue cleanup code get to the group.
1240          *
1241          * Do not call synchronize_rcu() unconditionally as there are drivers
1242          * which create/delete request queue hundreds of times during scan/boot
1243          * and synchronize_rcu() can take significant time and slow down boot.
1244          */
1245         if (wait)
1246                 synchronize_rcu();
1247
1248         /*
1249          * Just being safe to make sure after previous flush if some body did
1250          * update limits through cgroup and another work got queued, cancel
1251          * it.
1252          */
1253         throtl_shutdown_wq(q);
1254         throtl_td_free(td);
1255 }
1256
1257 static int __init throtl_init(void)
1258 {
1259         kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
1260         if (!kthrotld_workqueue)
1261                 panic("Failed to create kthrotld\n");
1262
1263         blkio_policy_register(&blkio_policy_throtl);
1264         return 0;
1265 }
1266
1267 module_init(throtl_init);