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