OSDN Git Service

cfq-iosched: Adjust one function call together with a variable assignment
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / block / cfq-iosched.c
1 /*
2  *  CFQ, or complete fairness queueing, disk scheduler.
3  *
4  *  Based on ideas from a previously unfinished io
5  *  scheduler (round robin per-process disk scheduling) and Andrea Arcangeli.
6  *
7  *  Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
8  */
9 #include <linux/module.h>
10 #include <linux/slab.h>
11 #include <linux/blkdev.h>
12 #include <linux/elevator.h>
13 #include <linux/ktime.h>
14 #include <linux/rbtree.h>
15 #include <linux/ioprio.h>
16 #include <linux/blktrace_api.h>
17 #include <linux/blk-cgroup.h>
18 #include "blk.h"
19
20 /*
21  * tunables
22  */
23 /* max queue in one round of service */
24 static const int cfq_quantum = 8;
25 static const u64 cfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
26 /* maximum backwards seek, in KiB */
27 static const int cfq_back_max = 16 * 1024;
28 /* penalty of a backwards seek */
29 static const int cfq_back_penalty = 2;
30 static const u64 cfq_slice_sync = NSEC_PER_SEC / 10;
31 static u64 cfq_slice_async = NSEC_PER_SEC / 25;
32 static const int cfq_slice_async_rq = 2;
33 static u64 cfq_slice_idle = NSEC_PER_SEC / 125;
34 static u64 cfq_group_idle = NSEC_PER_SEC / 125;
35 static const u64 cfq_target_latency = (u64)NSEC_PER_SEC * 3/10; /* 300 ms */
36 static const int cfq_hist_divisor = 4;
37
38 /*
39  * offset from end of service tree
40  */
41 #define CFQ_IDLE_DELAY          (NSEC_PER_SEC / 5)
42
43 /*
44  * below this threshold, we consider thinktime immediate
45  */
46 #define CFQ_MIN_TT              (2 * NSEC_PER_SEC / HZ)
47
48 #define CFQ_SLICE_SCALE         (5)
49 #define CFQ_HW_QUEUE_MIN        (5)
50 #define CFQ_SERVICE_SHIFT       12
51
52 #define CFQQ_SEEK_THR           (sector_t)(8 * 100)
53 #define CFQQ_CLOSE_THR          (sector_t)(8 * 1024)
54 #define CFQQ_SECT_THR_NONROT    (sector_t)(2 * 32)
55 #define CFQQ_SEEKY(cfqq)        (hweight32(cfqq->seek_history) > 32/8)
56
57 #define RQ_CIC(rq)              icq_to_cic((rq)->elv.icq)
58 #define RQ_CFQQ(rq)             (struct cfq_queue *) ((rq)->elv.priv[0])
59 #define RQ_CFQG(rq)             (struct cfq_group *) ((rq)->elv.priv[1])
60
61 static struct kmem_cache *cfq_pool;
62
63 #define CFQ_PRIO_LISTS          IOPRIO_BE_NR
64 #define cfq_class_idle(cfqq)    ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
65 #define cfq_class_rt(cfqq)      ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
66
67 #define sample_valid(samples)   ((samples) > 80)
68 #define rb_entry_cfqg(node)     rb_entry((node), struct cfq_group, rb_node)
69
70 /* blkio-related constants */
71 #define CFQ_WEIGHT_LEGACY_MIN   10
72 #define CFQ_WEIGHT_LEGACY_DFL   500
73 #define CFQ_WEIGHT_LEGACY_MAX   1000
74
75 struct cfq_ttime {
76         u64 last_end_request;
77
78         u64 ttime_total;
79         u64 ttime_mean;
80         unsigned long ttime_samples;
81 };
82
83 /*
84  * Most of our rbtree usage is for sorting with min extraction, so
85  * if we cache the leftmost node we don't have to walk down the tree
86  * to find it. Idea borrowed from Ingo Molnars CFS scheduler. We should
87  * move this into the elevator for the rq sorting as well.
88  */
89 struct cfq_rb_root {
90         struct rb_root rb;
91         struct rb_node *left;
92         unsigned count;
93         u64 min_vdisktime;
94         struct cfq_ttime ttime;
95 };
96 #define CFQ_RB_ROOT     (struct cfq_rb_root) { .rb = RB_ROOT, \
97                         .ttime = {.last_end_request = ktime_get_ns(),},}
98
99 /*
100  * Per process-grouping structure
101  */
102 struct cfq_queue {
103         /* reference count */
104         int ref;
105         /* various state flags, see below */
106         unsigned int flags;
107         /* parent cfq_data */
108         struct cfq_data *cfqd;
109         /* service_tree member */
110         struct rb_node rb_node;
111         /* service_tree key */
112         u64 rb_key;
113         /* prio tree member */
114         struct rb_node p_node;
115         /* prio tree root we belong to, if any */
116         struct rb_root *p_root;
117         /* sorted list of pending requests */
118         struct rb_root sort_list;
119         /* if fifo isn't expired, next request to serve */
120         struct request *next_rq;
121         /* requests queued in sort_list */
122         int queued[2];
123         /* currently allocated requests */
124         int allocated[2];
125         /* fifo list of requests in sort_list */
126         struct list_head fifo;
127
128         /* time when queue got scheduled in to dispatch first request. */
129         u64 dispatch_start;
130         u64 allocated_slice;
131         u64 slice_dispatch;
132         /* time when first request from queue completed and slice started. */
133         u64 slice_start;
134         u64 slice_end;
135         s64 slice_resid;
136
137         /* pending priority requests */
138         int prio_pending;
139         /* number of requests that are on the dispatch list or inside driver */
140         int dispatched;
141
142         /* io prio of this group */
143         unsigned short ioprio, org_ioprio;
144         unsigned short ioprio_class;
145
146         pid_t pid;
147
148         u32 seek_history;
149         sector_t last_request_pos;
150
151         struct cfq_rb_root *service_tree;
152         struct cfq_queue *new_cfqq;
153         struct cfq_group *cfqg;
154         /* Number of sectors dispatched from queue in single dispatch round */
155         unsigned long nr_sectors;
156 };
157
158 /*
159  * First index in the service_trees.
160  * IDLE is handled separately, so it has negative index
161  */
162 enum wl_class_t {
163         BE_WORKLOAD = 0,
164         RT_WORKLOAD = 1,
165         IDLE_WORKLOAD = 2,
166         CFQ_PRIO_NR,
167 };
168
169 /*
170  * Second index in the service_trees.
171  */
172 enum wl_type_t {
173         ASYNC_WORKLOAD = 0,
174         SYNC_NOIDLE_WORKLOAD = 1,
175         SYNC_WORKLOAD = 2
176 };
177
178 struct cfqg_stats {
179 #ifdef CONFIG_CFQ_GROUP_IOSCHED
180         /* number of ios merged */
181         struct blkg_rwstat              merged;
182         /* total time spent on device in ns, may not be accurate w/ queueing */
183         struct blkg_rwstat              service_time;
184         /* total time spent waiting in scheduler queue in ns */
185         struct blkg_rwstat              wait_time;
186         /* number of IOs queued up */
187         struct blkg_rwstat              queued;
188         /* total disk time and nr sectors dispatched by this group */
189         struct blkg_stat                time;
190 #ifdef CONFIG_DEBUG_BLK_CGROUP
191         /* time not charged to this cgroup */
192         struct blkg_stat                unaccounted_time;
193         /* sum of number of ios queued across all samples */
194         struct blkg_stat                avg_queue_size_sum;
195         /* count of samples taken for average */
196         struct blkg_stat                avg_queue_size_samples;
197         /* how many times this group has been removed from service tree */
198         struct blkg_stat                dequeue;
199         /* total time spent waiting for it to be assigned a timeslice. */
200         struct blkg_stat                group_wait_time;
201         /* time spent idling for this blkcg_gq */
202         struct blkg_stat                idle_time;
203         /* total time with empty current active q with other requests queued */
204         struct blkg_stat                empty_time;
205         /* fields after this shouldn't be cleared on stat reset */
206         uint64_t                        start_group_wait_time;
207         uint64_t                        start_idle_time;
208         uint64_t                        start_empty_time;
209         uint16_t                        flags;
210 #endif  /* CONFIG_DEBUG_BLK_CGROUP */
211 #endif  /* CONFIG_CFQ_GROUP_IOSCHED */
212 };
213
214 /* Per-cgroup data */
215 struct cfq_group_data {
216         /* must be the first member */
217         struct blkcg_policy_data cpd;
218
219         unsigned int weight;
220         unsigned int leaf_weight;
221 };
222
223 /* This is per cgroup per device grouping structure */
224 struct cfq_group {
225         /* must be the first member */
226         struct blkg_policy_data pd;
227
228         /* group service_tree member */
229         struct rb_node rb_node;
230
231         /* group service_tree key */
232         u64 vdisktime;
233
234         /*
235          * The number of active cfqgs and sum of their weights under this
236          * cfqg.  This covers this cfqg's leaf_weight and all children's
237          * weights, but does not cover weights of further descendants.
238          *
239          * If a cfqg is on the service tree, it's active.  An active cfqg
240          * also activates its parent and contributes to the children_weight
241          * of the parent.
242          */
243         int nr_active;
244         unsigned int children_weight;
245
246         /*
247          * vfraction is the fraction of vdisktime that the tasks in this
248          * cfqg are entitled to.  This is determined by compounding the
249          * ratios walking up from this cfqg to the root.
250          *
251          * It is in fixed point w/ CFQ_SERVICE_SHIFT and the sum of all
252          * vfractions on a service tree is approximately 1.  The sum may
253          * deviate a bit due to rounding errors and fluctuations caused by
254          * cfqgs entering and leaving the service tree.
255          */
256         unsigned int vfraction;
257
258         /*
259          * There are two weights - (internal) weight is the weight of this
260          * cfqg against the sibling cfqgs.  leaf_weight is the wight of
261          * this cfqg against the child cfqgs.  For the root cfqg, both
262          * weights are kept in sync for backward compatibility.
263          */
264         unsigned int weight;
265         unsigned int new_weight;
266         unsigned int dev_weight;
267
268         unsigned int leaf_weight;
269         unsigned int new_leaf_weight;
270         unsigned int dev_leaf_weight;
271
272         /* number of cfqq currently on this group */
273         int nr_cfqq;
274
275         /*
276          * Per group busy queues average. Useful for workload slice calc. We
277          * create the array for each prio class but at run time it is used
278          * only for RT and BE class and slot for IDLE class remains unused.
279          * This is primarily done to avoid confusion and a gcc warning.
280          */
281         unsigned int busy_queues_avg[CFQ_PRIO_NR];
282         /*
283          * rr lists of queues with requests. We maintain service trees for
284          * RT and BE classes. These trees are subdivided in subclasses
285          * of SYNC, SYNC_NOIDLE and ASYNC based on workload type. For IDLE
286          * class there is no subclassification and all the cfq queues go on
287          * a single tree service_tree_idle.
288          * Counts are embedded in the cfq_rb_root
289          */
290         struct cfq_rb_root service_trees[2][3];
291         struct cfq_rb_root service_tree_idle;
292
293         u64 saved_wl_slice;
294         enum wl_type_t saved_wl_type;
295         enum wl_class_t saved_wl_class;
296
297         /* number of requests that are on the dispatch list or inside driver */
298         int dispatched;
299         struct cfq_ttime ttime;
300         struct cfqg_stats stats;        /* stats for this cfqg */
301
302         /* async queue for each priority case */
303         struct cfq_queue *async_cfqq[2][IOPRIO_BE_NR];
304         struct cfq_queue *async_idle_cfqq;
305
306 };
307
308 struct cfq_io_cq {
309         struct io_cq            icq;            /* must be the first member */
310         struct cfq_queue        *cfqq[2];
311         struct cfq_ttime        ttime;
312         int                     ioprio;         /* the current ioprio */
313 #ifdef CONFIG_CFQ_GROUP_IOSCHED
314         uint64_t                blkcg_serial_nr; /* the current blkcg serial */
315 #endif
316 };
317
318 /*
319  * Per block device queue structure
320  */
321 struct cfq_data {
322         struct request_queue *queue;
323         /* Root service tree for cfq_groups */
324         struct cfq_rb_root grp_service_tree;
325         struct cfq_group *root_group;
326
327         /*
328          * The priority currently being served
329          */
330         enum wl_class_t serving_wl_class;
331         enum wl_type_t serving_wl_type;
332         u64 workload_expires;
333         struct cfq_group *serving_group;
334
335         /*
336          * Each priority tree is sorted by next_request position.  These
337          * trees are used when determining if two or more queues are
338          * interleaving requests (see cfq_close_cooperator).
339          */
340         struct rb_root prio_trees[CFQ_PRIO_LISTS];
341
342         unsigned int busy_queues;
343         unsigned int busy_sync_queues;
344
345         int rq_in_driver;
346         int rq_in_flight[2];
347
348         /*
349          * queue-depth detection
350          */
351         int rq_queued;
352         int hw_tag;
353         /*
354          * hw_tag can be
355          * -1 => indeterminate, (cfq will behave as if NCQ is present, to allow better detection)
356          *  1 => NCQ is present (hw_tag_est_depth is the estimated max depth)
357          *  0 => no NCQ
358          */
359         int hw_tag_est_depth;
360         unsigned int hw_tag_samples;
361
362         /*
363          * idle window management
364          */
365         struct hrtimer idle_slice_timer;
366         struct work_struct unplug_work;
367
368         struct cfq_queue *active_queue;
369         struct cfq_io_cq *active_cic;
370
371         sector_t last_position;
372
373         /*
374          * tunables, see top of file
375          */
376         unsigned int cfq_quantum;
377         unsigned int cfq_back_penalty;
378         unsigned int cfq_back_max;
379         unsigned int cfq_slice_async_rq;
380         unsigned int cfq_latency;
381         u64 cfq_fifo_expire[2];
382         u64 cfq_slice[2];
383         u64 cfq_slice_idle;
384         u64 cfq_group_idle;
385         u64 cfq_target_latency;
386
387         /*
388          * Fallback dummy cfqq for extreme OOM conditions
389          */
390         struct cfq_queue oom_cfqq;
391
392         u64 last_delayed_sync;
393 };
394
395 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd);
396 static void cfq_put_queue(struct cfq_queue *cfqq);
397
398 static struct cfq_rb_root *st_for(struct cfq_group *cfqg,
399                                             enum wl_class_t class,
400                                             enum wl_type_t type)
401 {
402         if (!cfqg)
403                 return NULL;
404
405         if (class == IDLE_WORKLOAD)
406                 return &cfqg->service_tree_idle;
407
408         return &cfqg->service_trees[class][type];
409 }
410
411 enum cfqq_state_flags {
412         CFQ_CFQQ_FLAG_on_rr = 0,        /* on round-robin busy list */
413         CFQ_CFQQ_FLAG_wait_request,     /* waiting for a request */
414         CFQ_CFQQ_FLAG_must_dispatch,    /* must be allowed a dispatch */
415         CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
416         CFQ_CFQQ_FLAG_fifo_expire,      /* FIFO checked in this slice */
417         CFQ_CFQQ_FLAG_idle_window,      /* slice idling enabled */
418         CFQ_CFQQ_FLAG_prio_changed,     /* task priority has changed */
419         CFQ_CFQQ_FLAG_slice_new,        /* no requests dispatched in slice */
420         CFQ_CFQQ_FLAG_sync,             /* synchronous queue */
421         CFQ_CFQQ_FLAG_coop,             /* cfqq is shared */
422         CFQ_CFQQ_FLAG_split_coop,       /* shared cfqq will be splitted */
423         CFQ_CFQQ_FLAG_deep,             /* sync cfqq experienced large depth */
424         CFQ_CFQQ_FLAG_wait_busy,        /* Waiting for next request */
425 };
426
427 #define CFQ_CFQQ_FNS(name)                                              \
428 static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq)         \
429 {                                                                       \
430         (cfqq)->flags |= (1 << CFQ_CFQQ_FLAG_##name);                   \
431 }                                                                       \
432 static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq)        \
433 {                                                                       \
434         (cfqq)->flags &= ~(1 << CFQ_CFQQ_FLAG_##name);                  \
435 }                                                                       \
436 static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq)         \
437 {                                                                       \
438         return ((cfqq)->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0;      \
439 }
440
441 CFQ_CFQQ_FNS(on_rr);
442 CFQ_CFQQ_FNS(wait_request);
443 CFQ_CFQQ_FNS(must_dispatch);
444 CFQ_CFQQ_FNS(must_alloc_slice);
445 CFQ_CFQQ_FNS(fifo_expire);
446 CFQ_CFQQ_FNS(idle_window);
447 CFQ_CFQQ_FNS(prio_changed);
448 CFQ_CFQQ_FNS(slice_new);
449 CFQ_CFQQ_FNS(sync);
450 CFQ_CFQQ_FNS(coop);
451 CFQ_CFQQ_FNS(split_coop);
452 CFQ_CFQQ_FNS(deep);
453 CFQ_CFQQ_FNS(wait_busy);
454 #undef CFQ_CFQQ_FNS
455
456 #if defined(CONFIG_CFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
457
458 /* cfqg stats flags */
459 enum cfqg_stats_flags {
460         CFQG_stats_waiting = 0,
461         CFQG_stats_idling,
462         CFQG_stats_empty,
463 };
464
465 #define CFQG_FLAG_FNS(name)                                             \
466 static inline void cfqg_stats_mark_##name(struct cfqg_stats *stats)     \
467 {                                                                       \
468         stats->flags |= (1 << CFQG_stats_##name);                       \
469 }                                                                       \
470 static inline void cfqg_stats_clear_##name(struct cfqg_stats *stats)    \
471 {                                                                       \
472         stats->flags &= ~(1 << CFQG_stats_##name);                      \
473 }                                                                       \
474 static inline int cfqg_stats_##name(struct cfqg_stats *stats)           \
475 {                                                                       \
476         return (stats->flags & (1 << CFQG_stats_##name)) != 0;          \
477 }                                                                       \
478
479 CFQG_FLAG_FNS(waiting)
480 CFQG_FLAG_FNS(idling)
481 CFQG_FLAG_FNS(empty)
482 #undef CFQG_FLAG_FNS
483
484 /* This should be called with the queue_lock held. */
485 static void cfqg_stats_update_group_wait_time(struct cfqg_stats *stats)
486 {
487         unsigned long long now;
488
489         if (!cfqg_stats_waiting(stats))
490                 return;
491
492         now = sched_clock();
493         if (time_after64(now, stats->start_group_wait_time))
494                 blkg_stat_add(&stats->group_wait_time,
495                               now - stats->start_group_wait_time);
496         cfqg_stats_clear_waiting(stats);
497 }
498
499 /* This should be called with the queue_lock held. */
500 static void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg,
501                                                  struct cfq_group *curr_cfqg)
502 {
503         struct cfqg_stats *stats = &cfqg->stats;
504
505         if (cfqg_stats_waiting(stats))
506                 return;
507         if (cfqg == curr_cfqg)
508                 return;
509         stats->start_group_wait_time = sched_clock();
510         cfqg_stats_mark_waiting(stats);
511 }
512
513 /* This should be called with the queue_lock held. */
514 static void cfqg_stats_end_empty_time(struct cfqg_stats *stats)
515 {
516         unsigned long long now;
517
518         if (!cfqg_stats_empty(stats))
519                 return;
520
521         now = sched_clock();
522         if (time_after64(now, stats->start_empty_time))
523                 blkg_stat_add(&stats->empty_time,
524                               now - stats->start_empty_time);
525         cfqg_stats_clear_empty(stats);
526 }
527
528 static void cfqg_stats_update_dequeue(struct cfq_group *cfqg)
529 {
530         blkg_stat_add(&cfqg->stats.dequeue, 1);
531 }
532
533 static void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg)
534 {
535         struct cfqg_stats *stats = &cfqg->stats;
536
537         if (blkg_rwstat_total(&stats->queued))
538                 return;
539
540         /*
541          * group is already marked empty. This can happen if cfqq got new
542          * request in parent group and moved to this group while being added
543          * to service tree. Just ignore the event and move on.
544          */
545         if (cfqg_stats_empty(stats))
546                 return;
547
548         stats->start_empty_time = sched_clock();
549         cfqg_stats_mark_empty(stats);
550 }
551
552 static void cfqg_stats_update_idle_time(struct cfq_group *cfqg)
553 {
554         struct cfqg_stats *stats = &cfqg->stats;
555
556         if (cfqg_stats_idling(stats)) {
557                 unsigned long long now = sched_clock();
558
559                 if (time_after64(now, stats->start_idle_time))
560                         blkg_stat_add(&stats->idle_time,
561                                       now - stats->start_idle_time);
562                 cfqg_stats_clear_idling(stats);
563         }
564 }
565
566 static void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg)
567 {
568         struct cfqg_stats *stats = &cfqg->stats;
569
570         BUG_ON(cfqg_stats_idling(stats));
571
572         stats->start_idle_time = sched_clock();
573         cfqg_stats_mark_idling(stats);
574 }
575
576 static void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg)
577 {
578         struct cfqg_stats *stats = &cfqg->stats;
579
580         blkg_stat_add(&stats->avg_queue_size_sum,
581                       blkg_rwstat_total(&stats->queued));
582         blkg_stat_add(&stats->avg_queue_size_samples, 1);
583         cfqg_stats_update_group_wait_time(stats);
584 }
585
586 #else   /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
587
588 static inline void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg, struct cfq_group *curr_cfqg) { }
589 static inline void cfqg_stats_end_empty_time(struct cfqg_stats *stats) { }
590 static inline void cfqg_stats_update_dequeue(struct cfq_group *cfqg) { }
591 static inline void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg) { }
592 static inline void cfqg_stats_update_idle_time(struct cfq_group *cfqg) { }
593 static inline void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg) { }
594 static inline void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg) { }
595
596 #endif  /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
597
598 #ifdef CONFIG_CFQ_GROUP_IOSCHED
599
600 static inline struct cfq_group *pd_to_cfqg(struct blkg_policy_data *pd)
601 {
602         return pd ? container_of(pd, struct cfq_group, pd) : NULL;
603 }
604
605 static struct cfq_group_data
606 *cpd_to_cfqgd(struct blkcg_policy_data *cpd)
607 {
608         return cpd ? container_of(cpd, struct cfq_group_data, cpd) : NULL;
609 }
610
611 static inline struct blkcg_gq *cfqg_to_blkg(struct cfq_group *cfqg)
612 {
613         return pd_to_blkg(&cfqg->pd);
614 }
615
616 static struct blkcg_policy blkcg_policy_cfq;
617
618 static inline struct cfq_group *blkg_to_cfqg(struct blkcg_gq *blkg)
619 {
620         return pd_to_cfqg(blkg_to_pd(blkg, &blkcg_policy_cfq));
621 }
622
623 static struct cfq_group_data *blkcg_to_cfqgd(struct blkcg *blkcg)
624 {
625         return cpd_to_cfqgd(blkcg_to_cpd(blkcg, &blkcg_policy_cfq));
626 }
627
628 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg)
629 {
630         struct blkcg_gq *pblkg = cfqg_to_blkg(cfqg)->parent;
631
632         return pblkg ? blkg_to_cfqg(pblkg) : NULL;
633 }
634
635 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
636                                       struct cfq_group *ancestor)
637 {
638         return cgroup_is_descendant(cfqg_to_blkg(cfqg)->blkcg->css.cgroup,
639                                     cfqg_to_blkg(ancestor)->blkcg->css.cgroup);
640 }
641
642 static inline void cfqg_get(struct cfq_group *cfqg)
643 {
644         return blkg_get(cfqg_to_blkg(cfqg));
645 }
646
647 static inline void cfqg_put(struct cfq_group *cfqg)
648 {
649         return blkg_put(cfqg_to_blkg(cfqg));
650 }
651
652 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...)  do {                    \
653         char __pbuf[128];                                               \
654                                                                         \
655         blkg_path(cfqg_to_blkg((cfqq)->cfqg), __pbuf, sizeof(__pbuf));  \
656         blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c %s " fmt, (cfqq)->pid, \
657                         cfq_cfqq_sync((cfqq)) ? 'S' : 'A',              \
658                         cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
659                           __pbuf, ##args);                              \
660 } while (0)
661
662 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...)  do {                    \
663         char __pbuf[128];                                               \
664                                                                         \
665         blkg_path(cfqg_to_blkg(cfqg), __pbuf, sizeof(__pbuf));          \
666         blk_add_trace_msg((cfqd)->queue, "%s " fmt, __pbuf, ##args);    \
667 } while (0)
668
669 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
670                                             struct cfq_group *curr_cfqg, int rw)
671 {
672         blkg_rwstat_add(&cfqg->stats.queued, rw, 1);
673         cfqg_stats_end_empty_time(&cfqg->stats);
674         cfqg_stats_set_start_group_wait_time(cfqg, curr_cfqg);
675 }
676
677 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
678                         uint64_t time, unsigned long unaccounted_time)
679 {
680         blkg_stat_add(&cfqg->stats.time, time);
681 #ifdef CONFIG_DEBUG_BLK_CGROUP
682         blkg_stat_add(&cfqg->stats.unaccounted_time, unaccounted_time);
683 #endif
684 }
685
686 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg, int rw)
687 {
688         blkg_rwstat_add(&cfqg->stats.queued, rw, -1);
689 }
690
691 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg, int rw)
692 {
693         blkg_rwstat_add(&cfqg->stats.merged, rw, 1);
694 }
695
696 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
697                         uint64_t start_time, uint64_t io_start_time, int rw)
698 {
699         struct cfqg_stats *stats = &cfqg->stats;
700         unsigned long long now = sched_clock();
701
702         if (time_after64(now, io_start_time))
703                 blkg_rwstat_add(&stats->service_time, rw, now - io_start_time);
704         if (time_after64(io_start_time, start_time))
705                 blkg_rwstat_add(&stats->wait_time, rw,
706                                 io_start_time - start_time);
707 }
708
709 /* @stats = 0 */
710 static void cfqg_stats_reset(struct cfqg_stats *stats)
711 {
712         /* queued stats shouldn't be cleared */
713         blkg_rwstat_reset(&stats->merged);
714         blkg_rwstat_reset(&stats->service_time);
715         blkg_rwstat_reset(&stats->wait_time);
716         blkg_stat_reset(&stats->time);
717 #ifdef CONFIG_DEBUG_BLK_CGROUP
718         blkg_stat_reset(&stats->unaccounted_time);
719         blkg_stat_reset(&stats->avg_queue_size_sum);
720         blkg_stat_reset(&stats->avg_queue_size_samples);
721         blkg_stat_reset(&stats->dequeue);
722         blkg_stat_reset(&stats->group_wait_time);
723         blkg_stat_reset(&stats->idle_time);
724         blkg_stat_reset(&stats->empty_time);
725 #endif
726 }
727
728 /* @to += @from */
729 static void cfqg_stats_add_aux(struct cfqg_stats *to, struct cfqg_stats *from)
730 {
731         /* queued stats shouldn't be cleared */
732         blkg_rwstat_add_aux(&to->merged, &from->merged);
733         blkg_rwstat_add_aux(&to->service_time, &from->service_time);
734         blkg_rwstat_add_aux(&to->wait_time, &from->wait_time);
735         blkg_stat_add_aux(&from->time, &from->time);
736 #ifdef CONFIG_DEBUG_BLK_CGROUP
737         blkg_stat_add_aux(&to->unaccounted_time, &from->unaccounted_time);
738         blkg_stat_add_aux(&to->avg_queue_size_sum, &from->avg_queue_size_sum);
739         blkg_stat_add_aux(&to->avg_queue_size_samples, &from->avg_queue_size_samples);
740         blkg_stat_add_aux(&to->dequeue, &from->dequeue);
741         blkg_stat_add_aux(&to->group_wait_time, &from->group_wait_time);
742         blkg_stat_add_aux(&to->idle_time, &from->idle_time);
743         blkg_stat_add_aux(&to->empty_time, &from->empty_time);
744 #endif
745 }
746
747 /*
748  * Transfer @cfqg's stats to its parent's aux counts so that the ancestors'
749  * recursive stats can still account for the amount used by this cfqg after
750  * it's gone.
751  */
752 static void cfqg_stats_xfer_dead(struct cfq_group *cfqg)
753 {
754         struct cfq_group *parent = cfqg_parent(cfqg);
755
756         lockdep_assert_held(cfqg_to_blkg(cfqg)->q->queue_lock);
757
758         if (unlikely(!parent))
759                 return;
760
761         cfqg_stats_add_aux(&parent->stats, &cfqg->stats);
762         cfqg_stats_reset(&cfqg->stats);
763 }
764
765 #else   /* CONFIG_CFQ_GROUP_IOSCHED */
766
767 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg) { return NULL; }
768 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
769                                       struct cfq_group *ancestor)
770 {
771         return true;
772 }
773 static inline void cfqg_get(struct cfq_group *cfqg) { }
774 static inline void cfqg_put(struct cfq_group *cfqg) { }
775
776 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...)  \
777         blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c " fmt, (cfqq)->pid, \
778                         cfq_cfqq_sync((cfqq)) ? 'S' : 'A',              \
779                         cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
780                                 ##args)
781 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...)          do {} while (0)
782
783 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
784                         struct cfq_group *curr_cfqg, int rw) { }
785 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
786                         uint64_t time, unsigned long unaccounted_time) { }
787 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg, int rw) { }
788 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg, int rw) { }
789 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
790                         uint64_t start_time, uint64_t io_start_time, int rw) { }
791
792 #endif  /* CONFIG_CFQ_GROUP_IOSCHED */
793
794 #define cfq_log(cfqd, fmt, args...)     \
795         blk_add_trace_msg((cfqd)->queue, "cfq " fmt, ##args)
796
797 /* Traverses through cfq group service trees */
798 #define for_each_cfqg_st(cfqg, i, j, st) \
799         for (i = 0; i <= IDLE_WORKLOAD; i++) \
800                 for (j = 0, st = i < IDLE_WORKLOAD ? &cfqg->service_trees[i][j]\
801                         : &cfqg->service_tree_idle; \
802                         (i < IDLE_WORKLOAD && j <= SYNC_WORKLOAD) || \
803                         (i == IDLE_WORKLOAD && j == 0); \
804                         j++, st = i < IDLE_WORKLOAD ? \
805                         &cfqg->service_trees[i][j]: NULL) \
806
807 static inline bool cfq_io_thinktime_big(struct cfq_data *cfqd,
808         struct cfq_ttime *ttime, bool group_idle)
809 {
810         u64 slice;
811         if (!sample_valid(ttime->ttime_samples))
812                 return false;
813         if (group_idle)
814                 slice = cfqd->cfq_group_idle;
815         else
816                 slice = cfqd->cfq_slice_idle;
817         return ttime->ttime_mean > slice;
818 }
819
820 static inline bool iops_mode(struct cfq_data *cfqd)
821 {
822         /*
823          * If we are not idling on queues and it is a NCQ drive, parallel
824          * execution of requests is on and measuring time is not possible
825          * in most of the cases until and unless we drive shallower queue
826          * depths and that becomes a performance bottleneck. In such cases
827          * switch to start providing fairness in terms of number of IOs.
828          */
829         if (!cfqd->cfq_slice_idle && cfqd->hw_tag)
830                 return true;
831         else
832                 return false;
833 }
834
835 static inline enum wl_class_t cfqq_class(struct cfq_queue *cfqq)
836 {
837         if (cfq_class_idle(cfqq))
838                 return IDLE_WORKLOAD;
839         if (cfq_class_rt(cfqq))
840                 return RT_WORKLOAD;
841         return BE_WORKLOAD;
842 }
843
844
845 static enum wl_type_t cfqq_type(struct cfq_queue *cfqq)
846 {
847         if (!cfq_cfqq_sync(cfqq))
848                 return ASYNC_WORKLOAD;
849         if (!cfq_cfqq_idle_window(cfqq))
850                 return SYNC_NOIDLE_WORKLOAD;
851         return SYNC_WORKLOAD;
852 }
853
854 static inline int cfq_group_busy_queues_wl(enum wl_class_t wl_class,
855                                         struct cfq_data *cfqd,
856                                         struct cfq_group *cfqg)
857 {
858         if (wl_class == IDLE_WORKLOAD)
859                 return cfqg->service_tree_idle.count;
860
861         return cfqg->service_trees[wl_class][ASYNC_WORKLOAD].count +
862                 cfqg->service_trees[wl_class][SYNC_NOIDLE_WORKLOAD].count +
863                 cfqg->service_trees[wl_class][SYNC_WORKLOAD].count;
864 }
865
866 static inline int cfqg_busy_async_queues(struct cfq_data *cfqd,
867                                         struct cfq_group *cfqg)
868 {
869         return cfqg->service_trees[RT_WORKLOAD][ASYNC_WORKLOAD].count +
870                 cfqg->service_trees[BE_WORKLOAD][ASYNC_WORKLOAD].count;
871 }
872
873 static void cfq_dispatch_insert(struct request_queue *, struct request *);
874 static struct cfq_queue *cfq_get_queue(struct cfq_data *cfqd, bool is_sync,
875                                        struct cfq_io_cq *cic, struct bio *bio);
876
877 static inline struct cfq_io_cq *icq_to_cic(struct io_cq *icq)
878 {
879         /* cic->icq is the first member, %NULL will convert to %NULL */
880         return container_of(icq, struct cfq_io_cq, icq);
881 }
882
883 static inline struct cfq_io_cq *cfq_cic_lookup(struct cfq_data *cfqd,
884                                                struct io_context *ioc)
885 {
886         if (ioc)
887                 return icq_to_cic(ioc_lookup_icq(ioc, cfqd->queue));
888         return NULL;
889 }
890
891 static inline struct cfq_queue *cic_to_cfqq(struct cfq_io_cq *cic, bool is_sync)
892 {
893         return cic->cfqq[is_sync];
894 }
895
896 static inline void cic_set_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq,
897                                 bool is_sync)
898 {
899         cic->cfqq[is_sync] = cfqq;
900 }
901
902 static inline struct cfq_data *cic_to_cfqd(struct cfq_io_cq *cic)
903 {
904         return cic->icq.q->elevator->elevator_data;
905 }
906
907 /*
908  * We regard a request as SYNC, if it's either a read or has the SYNC bit
909  * set (in which case it could also be direct WRITE).
910  */
911 static inline bool cfq_bio_sync(struct bio *bio)
912 {
913         return bio_data_dir(bio) == READ || (bio->bi_rw & REQ_SYNC);
914 }
915
916 /*
917  * scheduler run of queue, if there are requests pending and no one in the
918  * driver that will restart queueing
919  */
920 static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
921 {
922         if (cfqd->busy_queues) {
923                 cfq_log(cfqd, "schedule dispatch");
924                 kblockd_schedule_work(&cfqd->unplug_work);
925         }
926 }
927
928 /*
929  * Scale schedule slice based on io priority. Use the sync time slice only
930  * if a queue is marked sync and has sync io queued. A sync queue with async
931  * io only, should not get full sync slice length.
932  */
933 static inline u64 cfq_prio_slice(struct cfq_data *cfqd, bool sync,
934                                  unsigned short prio)
935 {
936         u64 base_slice = cfqd->cfq_slice[sync];
937         u64 slice = div_u64(base_slice, CFQ_SLICE_SCALE);
938
939         WARN_ON(prio >= IOPRIO_BE_NR);
940
941         return base_slice + (slice * (4 - prio));
942 }
943
944 static inline u64
945 cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
946 {
947         return cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio);
948 }
949
950 /**
951  * cfqg_scale_charge - scale disk time charge according to cfqg weight
952  * @charge: disk time being charged
953  * @vfraction: vfraction of the cfqg, fixed point w/ CFQ_SERVICE_SHIFT
954  *
955  * Scale @charge according to @vfraction, which is in range (0, 1].  The
956  * scaling is inversely proportional.
957  *
958  * scaled = charge / vfraction
959  *
960  * The result is also in fixed point w/ CFQ_SERVICE_SHIFT.
961  */
962 static inline u64 cfqg_scale_charge(u64 charge,
963                                     unsigned int vfraction)
964 {
965         u64 c = charge << CFQ_SERVICE_SHIFT;    /* make it fixed point */
966
967         /* charge / vfraction */
968         c <<= CFQ_SERVICE_SHIFT;
969         return div_u64(c, vfraction);
970 }
971
972 static inline u64 max_vdisktime(u64 min_vdisktime, u64 vdisktime)
973 {
974         s64 delta = (s64)(vdisktime - min_vdisktime);
975         if (delta > 0)
976                 min_vdisktime = vdisktime;
977
978         return min_vdisktime;
979 }
980
981 static inline u64 min_vdisktime(u64 min_vdisktime, u64 vdisktime)
982 {
983         s64 delta = (s64)(vdisktime - min_vdisktime);
984         if (delta < 0)
985                 min_vdisktime = vdisktime;
986
987         return min_vdisktime;
988 }
989
990 static void update_min_vdisktime(struct cfq_rb_root *st)
991 {
992         struct cfq_group *cfqg;
993
994         if (st->left) {
995                 cfqg = rb_entry_cfqg(st->left);
996                 st->min_vdisktime = max_vdisktime(st->min_vdisktime,
997                                                   cfqg->vdisktime);
998         }
999 }
1000
1001 /*
1002  * get averaged number of queues of RT/BE priority.
1003  * average is updated, with a formula that gives more weight to higher numbers,
1004  * to quickly follows sudden increases and decrease slowly
1005  */
1006
1007 static inline unsigned cfq_group_get_avg_queues(struct cfq_data *cfqd,
1008                                         struct cfq_group *cfqg, bool rt)
1009 {
1010         unsigned min_q, max_q;
1011         unsigned mult  = cfq_hist_divisor - 1;
1012         unsigned round = cfq_hist_divisor / 2;
1013         unsigned busy = cfq_group_busy_queues_wl(rt, cfqd, cfqg);
1014
1015         min_q = min(cfqg->busy_queues_avg[rt], busy);
1016         max_q = max(cfqg->busy_queues_avg[rt], busy);
1017         cfqg->busy_queues_avg[rt] = (mult * max_q + min_q + round) /
1018                 cfq_hist_divisor;
1019         return cfqg->busy_queues_avg[rt];
1020 }
1021
1022 static inline u64
1023 cfq_group_slice(struct cfq_data *cfqd, struct cfq_group *cfqg)
1024 {
1025         return cfqd->cfq_target_latency * cfqg->vfraction >> CFQ_SERVICE_SHIFT;
1026 }
1027
1028 static inline u64
1029 cfq_scaled_cfqq_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1030 {
1031         u64 slice = cfq_prio_to_slice(cfqd, cfqq);
1032         if (cfqd->cfq_latency) {
1033                 /*
1034                  * interested queues (we consider only the ones with the same
1035                  * priority class in the cfq group)
1036                  */
1037                 unsigned iq = cfq_group_get_avg_queues(cfqd, cfqq->cfqg,
1038                                                 cfq_class_rt(cfqq));
1039                 u64 sync_slice = cfqd->cfq_slice[1];
1040                 u64 expect_latency = sync_slice * iq;
1041                 u64 group_slice = cfq_group_slice(cfqd, cfqq->cfqg);
1042
1043                 if (expect_latency > group_slice) {
1044                         u64 base_low_slice = 2 * cfqd->cfq_slice_idle;
1045                         u64 low_slice;
1046
1047                         /* scale low_slice according to IO priority
1048                          * and sync vs async */
1049                         low_slice = div64_u64(base_low_slice*slice, sync_slice);
1050                         low_slice = min(slice, low_slice);
1051                         /* the adapted slice value is scaled to fit all iqs
1052                          * into the target latency */
1053                         slice = div64_u64(slice*group_slice, expect_latency);
1054                         slice = max(slice, low_slice);
1055                 }
1056         }
1057         return slice;
1058 }
1059
1060 static inline void
1061 cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1062 {
1063         u64 slice = cfq_scaled_cfqq_slice(cfqd, cfqq);
1064         u64 now = ktime_get_ns();
1065
1066         cfqq->slice_start = now;
1067         cfqq->slice_end = now + slice;
1068         cfqq->allocated_slice = slice;
1069         cfq_log_cfqq(cfqd, cfqq, "set_slice=%llu", cfqq->slice_end - now);
1070 }
1071
1072 /*
1073  * We need to wrap this check in cfq_cfqq_slice_new(), since ->slice_end
1074  * isn't valid until the first request from the dispatch is activated
1075  * and the slice time set.
1076  */
1077 static inline bool cfq_slice_used(struct cfq_queue *cfqq)
1078 {
1079         if (cfq_cfqq_slice_new(cfqq))
1080                 return false;
1081         if (ktime_get_ns() < cfqq->slice_end)
1082                 return false;
1083
1084         return true;
1085 }
1086
1087 /*
1088  * Lifted from AS - choose which of rq1 and rq2 that is best served now.
1089  * We choose the request that is closest to the head right now. Distance
1090  * behind the head is penalized and only allowed to a certain extent.
1091  */
1092 static struct request *
1093 cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2, sector_t last)
1094 {
1095         sector_t s1, s2, d1 = 0, d2 = 0;
1096         unsigned long back_max;
1097 #define CFQ_RQ1_WRAP    0x01 /* request 1 wraps */
1098 #define CFQ_RQ2_WRAP    0x02 /* request 2 wraps */
1099         unsigned wrap = 0; /* bit mask: requests behind the disk head? */
1100
1101         if (rq1 == NULL || rq1 == rq2)
1102                 return rq2;
1103         if (rq2 == NULL)
1104                 return rq1;
1105
1106         if (rq_is_sync(rq1) != rq_is_sync(rq2))
1107                 return rq_is_sync(rq1) ? rq1 : rq2;
1108
1109         if ((rq1->cmd_flags ^ rq2->cmd_flags) & REQ_PRIO)
1110                 return rq1->cmd_flags & REQ_PRIO ? rq1 : rq2;
1111
1112         s1 = blk_rq_pos(rq1);
1113         s2 = blk_rq_pos(rq2);
1114
1115         /*
1116          * by definition, 1KiB is 2 sectors
1117          */
1118         back_max = cfqd->cfq_back_max * 2;
1119
1120         /*
1121          * Strict one way elevator _except_ in the case where we allow
1122          * short backward seeks which are biased as twice the cost of a
1123          * similar forward seek.
1124          */
1125         if (s1 >= last)
1126                 d1 = s1 - last;
1127         else if (s1 + back_max >= last)
1128                 d1 = (last - s1) * cfqd->cfq_back_penalty;
1129         else
1130                 wrap |= CFQ_RQ1_WRAP;
1131
1132         if (s2 >= last)
1133                 d2 = s2 - last;
1134         else if (s2 + back_max >= last)
1135                 d2 = (last - s2) * cfqd->cfq_back_penalty;
1136         else
1137                 wrap |= CFQ_RQ2_WRAP;
1138
1139         /* Found required data */
1140
1141         /*
1142          * By doing switch() on the bit mask "wrap" we avoid having to
1143          * check two variables for all permutations: --> faster!
1144          */
1145         switch (wrap) {
1146         case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
1147                 if (d1 < d2)
1148                         return rq1;
1149                 else if (d2 < d1)
1150                         return rq2;
1151                 else {
1152                         if (s1 >= s2)
1153                                 return rq1;
1154                         else
1155                                 return rq2;
1156                 }
1157
1158         case CFQ_RQ2_WRAP:
1159                 return rq1;
1160         case CFQ_RQ1_WRAP:
1161                 return rq2;
1162         case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
1163         default:
1164                 /*
1165                  * Since both rqs are wrapped,
1166                  * start with the one that's further behind head
1167                  * (--> only *one* back seek required),
1168                  * since back seek takes more time than forward.
1169                  */
1170                 if (s1 <= s2)
1171                         return rq1;
1172                 else
1173                         return rq2;
1174         }
1175 }
1176
1177 /*
1178  * The below is leftmost cache rbtree addon
1179  */
1180 static struct cfq_queue *cfq_rb_first(struct cfq_rb_root *root)
1181 {
1182         /* Service tree is empty */
1183         if (!root->count)
1184                 return NULL;
1185
1186         if (!root->left)
1187                 root->left = rb_first(&root->rb);
1188
1189         if (root->left)
1190                 return rb_entry(root->left, struct cfq_queue, rb_node);
1191
1192         return NULL;
1193 }
1194
1195 static struct cfq_group *cfq_rb_first_group(struct cfq_rb_root *root)
1196 {
1197         if (!root->left)
1198                 root->left = rb_first(&root->rb);
1199
1200         if (root->left)
1201                 return rb_entry_cfqg(root->left);
1202
1203         return NULL;
1204 }
1205
1206 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
1207 {
1208         rb_erase(n, root);
1209         RB_CLEAR_NODE(n);
1210 }
1211
1212 static void cfq_rb_erase(struct rb_node *n, struct cfq_rb_root *root)
1213 {
1214         if (root->left == n)
1215                 root->left = NULL;
1216         rb_erase_init(n, &root->rb);
1217         --root->count;
1218 }
1219
1220 /*
1221  * would be nice to take fifo expire time into account as well
1222  */
1223 static struct request *
1224 cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1225                   struct request *last)
1226 {
1227         struct rb_node *rbnext = rb_next(&last->rb_node);
1228         struct rb_node *rbprev = rb_prev(&last->rb_node);
1229         struct request *next = NULL, *prev = NULL;
1230
1231         BUG_ON(RB_EMPTY_NODE(&last->rb_node));
1232
1233         if (rbprev)
1234                 prev = rb_entry_rq(rbprev);
1235
1236         if (rbnext)
1237                 next = rb_entry_rq(rbnext);
1238         else {
1239                 rbnext = rb_first(&cfqq->sort_list);
1240                 if (rbnext && rbnext != &last->rb_node)
1241                         next = rb_entry_rq(rbnext);
1242         }
1243
1244         return cfq_choose_req(cfqd, next, prev, blk_rq_pos(last));
1245 }
1246
1247 static u64 cfq_slice_offset(struct cfq_data *cfqd,
1248                             struct cfq_queue *cfqq)
1249 {
1250         /*
1251          * just an approximation, should be ok.
1252          */
1253         return (cfqq->cfqg->nr_cfqq - 1) * (cfq_prio_slice(cfqd, 1, 0) -
1254                        cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio));
1255 }
1256
1257 static inline s64
1258 cfqg_key(struct cfq_rb_root *st, struct cfq_group *cfqg)
1259 {
1260         return cfqg->vdisktime - st->min_vdisktime;
1261 }
1262
1263 static void
1264 __cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1265 {
1266         struct rb_node **node = &st->rb.rb_node;
1267         struct rb_node *parent = NULL;
1268         struct cfq_group *__cfqg;
1269         s64 key = cfqg_key(st, cfqg);
1270         int left = 1;
1271
1272         while (*node != NULL) {
1273                 parent = *node;
1274                 __cfqg = rb_entry_cfqg(parent);
1275
1276                 if (key < cfqg_key(st, __cfqg))
1277                         node = &parent->rb_left;
1278                 else {
1279                         node = &parent->rb_right;
1280                         left = 0;
1281                 }
1282         }
1283
1284         if (left)
1285                 st->left = &cfqg->rb_node;
1286
1287         rb_link_node(&cfqg->rb_node, parent, node);
1288         rb_insert_color(&cfqg->rb_node, &st->rb);
1289 }
1290
1291 /*
1292  * This has to be called only on activation of cfqg
1293  */
1294 static void
1295 cfq_update_group_weight(struct cfq_group *cfqg)
1296 {
1297         if (cfqg->new_weight) {
1298                 cfqg->weight = cfqg->new_weight;
1299                 cfqg->new_weight = 0;
1300         }
1301 }
1302
1303 static void
1304 cfq_update_group_leaf_weight(struct cfq_group *cfqg)
1305 {
1306         BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1307
1308         if (cfqg->new_leaf_weight) {
1309                 cfqg->leaf_weight = cfqg->new_leaf_weight;
1310                 cfqg->new_leaf_weight = 0;
1311         }
1312 }
1313
1314 static void
1315 cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1316 {
1317         unsigned int vfr = 1 << CFQ_SERVICE_SHIFT;      /* start with 1 */
1318         struct cfq_group *pos = cfqg;
1319         struct cfq_group *parent;
1320         bool propagate;
1321
1322         /* add to the service tree */
1323         BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1324
1325         /*
1326          * Update leaf_weight.  We cannot update weight at this point
1327          * because cfqg might already have been activated and is
1328          * contributing its current weight to the parent's child_weight.
1329          */
1330         cfq_update_group_leaf_weight(cfqg);
1331         __cfq_group_service_tree_add(st, cfqg);
1332
1333         /*
1334          * Activate @cfqg and calculate the portion of vfraction @cfqg is
1335          * entitled to.  vfraction is calculated by walking the tree
1336          * towards the root calculating the fraction it has at each level.
1337          * The compounded ratio is how much vfraction @cfqg owns.
1338          *
1339          * Start with the proportion tasks in this cfqg has against active
1340          * children cfqgs - its leaf_weight against children_weight.
1341          */
1342         propagate = !pos->nr_active++;
1343         pos->children_weight += pos->leaf_weight;
1344         vfr = vfr * pos->leaf_weight / pos->children_weight;
1345
1346         /*
1347          * Compound ->weight walking up the tree.  Both activation and
1348          * vfraction calculation are done in the same loop.  Propagation
1349          * stops once an already activated node is met.  vfraction
1350          * calculation should always continue to the root.
1351          */
1352         while ((parent = cfqg_parent(pos))) {
1353                 if (propagate) {
1354                         cfq_update_group_weight(pos);
1355                         propagate = !parent->nr_active++;
1356                         parent->children_weight += pos->weight;
1357                 }
1358                 vfr = vfr * pos->weight / parent->children_weight;
1359                 pos = parent;
1360         }
1361
1362         cfqg->vfraction = max_t(unsigned, vfr, 1);
1363 }
1364
1365 static void
1366 cfq_group_notify_queue_add(struct cfq_data *cfqd, struct cfq_group *cfqg)
1367 {
1368         struct cfq_rb_root *st = &cfqd->grp_service_tree;
1369         struct cfq_group *__cfqg;
1370         struct rb_node *n;
1371
1372         cfqg->nr_cfqq++;
1373         if (!RB_EMPTY_NODE(&cfqg->rb_node))
1374                 return;
1375
1376         /*
1377          * Currently put the group at the end. Later implement something
1378          * so that groups get lesser vtime based on their weights, so that
1379          * if group does not loose all if it was not continuously backlogged.
1380          */
1381         n = rb_last(&st->rb);
1382         if (n) {
1383                 __cfqg = rb_entry_cfqg(n);
1384                 cfqg->vdisktime = __cfqg->vdisktime + CFQ_IDLE_DELAY;
1385         } else
1386                 cfqg->vdisktime = st->min_vdisktime;
1387         cfq_group_service_tree_add(st, cfqg);
1388 }
1389
1390 static void
1391 cfq_group_service_tree_del(struct cfq_rb_root *st, struct cfq_group *cfqg)
1392 {
1393         struct cfq_group *pos = cfqg;
1394         bool propagate;
1395
1396         /*
1397          * Undo activation from cfq_group_service_tree_add().  Deactivate
1398          * @cfqg and propagate deactivation upwards.
1399          */
1400         propagate = !--pos->nr_active;
1401         pos->children_weight -= pos->leaf_weight;
1402
1403         while (propagate) {
1404                 struct cfq_group *parent = cfqg_parent(pos);
1405
1406                 /* @pos has 0 nr_active at this point */
1407                 WARN_ON_ONCE(pos->children_weight);
1408                 pos->vfraction = 0;
1409
1410                 if (!parent)
1411                         break;
1412
1413                 propagate = !--parent->nr_active;
1414                 parent->children_weight -= pos->weight;
1415                 pos = parent;
1416         }
1417
1418         /* remove from the service tree */
1419         if (!RB_EMPTY_NODE(&cfqg->rb_node))
1420                 cfq_rb_erase(&cfqg->rb_node, st);
1421 }
1422
1423 static void
1424 cfq_group_notify_queue_del(struct cfq_data *cfqd, struct cfq_group *cfqg)
1425 {
1426         struct cfq_rb_root *st = &cfqd->grp_service_tree;
1427
1428         BUG_ON(cfqg->nr_cfqq < 1);
1429         cfqg->nr_cfqq--;
1430
1431         /* If there are other cfq queues under this group, don't delete it */
1432         if (cfqg->nr_cfqq)
1433                 return;
1434
1435         cfq_log_cfqg(cfqd, cfqg, "del_from_rr group");
1436         cfq_group_service_tree_del(st, cfqg);
1437         cfqg->saved_wl_slice = 0;
1438         cfqg_stats_update_dequeue(cfqg);
1439 }
1440
1441 static inline u64 cfq_cfqq_slice_usage(struct cfq_queue *cfqq,
1442                                        u64 *unaccounted_time)
1443 {
1444         u64 slice_used;
1445         u64 now = ktime_get_ns();
1446
1447         /*
1448          * Queue got expired before even a single request completed or
1449          * got expired immediately after first request completion.
1450          */
1451         if (!cfqq->slice_start || cfqq->slice_start == now) {
1452                 /*
1453                  * Also charge the seek time incurred to the group, otherwise
1454                  * if there are mutiple queues in the group, each can dispatch
1455                  * a single request on seeky media and cause lots of seek time
1456                  * and group will never know it.
1457                  */
1458                 slice_used = max_t(u64, (now - cfqq->dispatch_start),
1459                                         jiffies_to_nsecs(1));
1460         } else {
1461                 slice_used = now - cfqq->slice_start;
1462                 if (slice_used > cfqq->allocated_slice) {
1463                         *unaccounted_time = slice_used - cfqq->allocated_slice;
1464                         slice_used = cfqq->allocated_slice;
1465                 }
1466                 if (cfqq->slice_start > cfqq->dispatch_start)
1467                         *unaccounted_time += cfqq->slice_start -
1468                                         cfqq->dispatch_start;
1469         }
1470
1471         return slice_used;
1472 }
1473
1474 static void cfq_group_served(struct cfq_data *cfqd, struct cfq_group *cfqg,
1475                                 struct cfq_queue *cfqq)
1476 {
1477         struct cfq_rb_root *st = &cfqd->grp_service_tree;
1478         u64 used_sl, charge, unaccounted_sl = 0;
1479         int nr_sync = cfqg->nr_cfqq - cfqg_busy_async_queues(cfqd, cfqg)
1480                         - cfqg->service_tree_idle.count;
1481         unsigned int vfr;
1482         u64 now = ktime_get_ns();
1483
1484         BUG_ON(nr_sync < 0);
1485         used_sl = charge = cfq_cfqq_slice_usage(cfqq, &unaccounted_sl);
1486
1487         if (iops_mode(cfqd))
1488                 charge = cfqq->slice_dispatch;
1489         else if (!cfq_cfqq_sync(cfqq) && !nr_sync)
1490                 charge = cfqq->allocated_slice;
1491
1492         /*
1493          * Can't update vdisktime while on service tree and cfqg->vfraction
1494          * is valid only while on it.  Cache vfr, leave the service tree,
1495          * update vdisktime and go back on.  The re-addition to the tree
1496          * will also update the weights as necessary.
1497          */
1498         vfr = cfqg->vfraction;
1499         cfq_group_service_tree_del(st, cfqg);
1500         cfqg->vdisktime += cfqg_scale_charge(charge, vfr);
1501         cfq_group_service_tree_add(st, cfqg);
1502
1503         /* This group is being expired. Save the context */
1504         if (cfqd->workload_expires > now) {
1505                 cfqg->saved_wl_slice = cfqd->workload_expires - now;
1506                 cfqg->saved_wl_type = cfqd->serving_wl_type;
1507                 cfqg->saved_wl_class = cfqd->serving_wl_class;
1508         } else
1509                 cfqg->saved_wl_slice = 0;
1510
1511         cfq_log_cfqg(cfqd, cfqg, "served: vt=%llu min_vt=%llu", cfqg->vdisktime,
1512                                         st->min_vdisktime);
1513         cfq_log_cfqq(cfqq->cfqd, cfqq,
1514                      "sl_used=%llu disp=%llu charge=%llu iops=%u sect=%lu",
1515                      used_sl, cfqq->slice_dispatch, charge,
1516                      iops_mode(cfqd), cfqq->nr_sectors);
1517         cfqg_stats_update_timeslice_used(cfqg, used_sl, unaccounted_sl);
1518         cfqg_stats_set_start_empty_time(cfqg);
1519 }
1520
1521 /**
1522  * cfq_init_cfqg_base - initialize base part of a cfq_group
1523  * @cfqg: cfq_group to initialize
1524  *
1525  * Initialize the base part which is used whether %CONFIG_CFQ_GROUP_IOSCHED
1526  * is enabled or not.
1527  */
1528 static void cfq_init_cfqg_base(struct cfq_group *cfqg)
1529 {
1530         struct cfq_rb_root *st;
1531         int i, j;
1532
1533         for_each_cfqg_st(cfqg, i, j, st)
1534                 *st = CFQ_RB_ROOT;
1535         RB_CLEAR_NODE(&cfqg->rb_node);
1536
1537         cfqg->ttime.last_end_request = ktime_get_ns();
1538 }
1539
1540 #ifdef CONFIG_CFQ_GROUP_IOSCHED
1541 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1542                             bool on_dfl, bool reset_dev, bool is_leaf_weight);
1543
1544 static void cfqg_stats_exit(struct cfqg_stats *stats)
1545 {
1546         blkg_rwstat_exit(&stats->merged);
1547         blkg_rwstat_exit(&stats->service_time);
1548         blkg_rwstat_exit(&stats->wait_time);
1549         blkg_rwstat_exit(&stats->queued);
1550         blkg_stat_exit(&stats->time);
1551 #ifdef CONFIG_DEBUG_BLK_CGROUP
1552         blkg_stat_exit(&stats->unaccounted_time);
1553         blkg_stat_exit(&stats->avg_queue_size_sum);
1554         blkg_stat_exit(&stats->avg_queue_size_samples);
1555         blkg_stat_exit(&stats->dequeue);
1556         blkg_stat_exit(&stats->group_wait_time);
1557         blkg_stat_exit(&stats->idle_time);
1558         blkg_stat_exit(&stats->empty_time);
1559 #endif
1560 }
1561
1562 static int cfqg_stats_init(struct cfqg_stats *stats, gfp_t gfp)
1563 {
1564         if (blkg_rwstat_init(&stats->merged, gfp) ||
1565             blkg_rwstat_init(&stats->service_time, gfp) ||
1566             blkg_rwstat_init(&stats->wait_time, gfp) ||
1567             blkg_rwstat_init(&stats->queued, gfp) ||
1568             blkg_stat_init(&stats->time, gfp))
1569                 goto err;
1570
1571 #ifdef CONFIG_DEBUG_BLK_CGROUP
1572         if (blkg_stat_init(&stats->unaccounted_time, gfp) ||
1573             blkg_stat_init(&stats->avg_queue_size_sum, gfp) ||
1574             blkg_stat_init(&stats->avg_queue_size_samples, gfp) ||
1575             blkg_stat_init(&stats->dequeue, gfp) ||
1576             blkg_stat_init(&stats->group_wait_time, gfp) ||
1577             blkg_stat_init(&stats->idle_time, gfp) ||
1578             blkg_stat_init(&stats->empty_time, gfp))
1579                 goto err;
1580 #endif
1581         return 0;
1582 err:
1583         cfqg_stats_exit(stats);
1584         return -ENOMEM;
1585 }
1586
1587 static struct blkcg_policy_data *cfq_cpd_alloc(gfp_t gfp)
1588 {
1589         struct cfq_group_data *cgd;
1590
1591         cgd = kzalloc(sizeof(*cgd), gfp);
1592         if (!cgd)
1593                 return NULL;
1594         return &cgd->cpd;
1595 }
1596
1597 static void cfq_cpd_init(struct blkcg_policy_data *cpd)
1598 {
1599         struct cfq_group_data *cgd = cpd_to_cfqgd(cpd);
1600         unsigned int weight = cgroup_subsys_on_dfl(io_cgrp_subsys) ?
1601                               CGROUP_WEIGHT_DFL : CFQ_WEIGHT_LEGACY_DFL;
1602
1603         if (cpd_to_blkcg(cpd) == &blkcg_root)
1604                 weight *= 2;
1605
1606         cgd->weight = weight;
1607         cgd->leaf_weight = weight;
1608 }
1609
1610 static void cfq_cpd_free(struct blkcg_policy_data *cpd)
1611 {
1612         kfree(cpd_to_cfqgd(cpd));
1613 }
1614
1615 static void cfq_cpd_bind(struct blkcg_policy_data *cpd)
1616 {
1617         struct blkcg *blkcg = cpd_to_blkcg(cpd);
1618         bool on_dfl = cgroup_subsys_on_dfl(io_cgrp_subsys);
1619         unsigned int weight = on_dfl ? CGROUP_WEIGHT_DFL : CFQ_WEIGHT_LEGACY_DFL;
1620
1621         if (blkcg == &blkcg_root)
1622                 weight *= 2;
1623
1624         WARN_ON_ONCE(__cfq_set_weight(&blkcg->css, weight, on_dfl, true, false));
1625         WARN_ON_ONCE(__cfq_set_weight(&blkcg->css, weight, on_dfl, true, true));
1626 }
1627
1628 static struct blkg_policy_data *cfq_pd_alloc(gfp_t gfp, int node)
1629 {
1630         struct cfq_group *cfqg;
1631
1632         cfqg = kzalloc_node(sizeof(*cfqg), gfp, node);
1633         if (!cfqg)
1634                 return NULL;
1635
1636         cfq_init_cfqg_base(cfqg);
1637         if (cfqg_stats_init(&cfqg->stats, gfp)) {
1638                 kfree(cfqg);
1639                 return NULL;
1640         }
1641
1642         return &cfqg->pd;
1643 }
1644
1645 static void cfq_pd_init(struct blkg_policy_data *pd)
1646 {
1647         struct cfq_group *cfqg = pd_to_cfqg(pd);
1648         struct cfq_group_data *cgd = blkcg_to_cfqgd(pd->blkg->blkcg);
1649
1650         cfqg->weight = cgd->weight;
1651         cfqg->leaf_weight = cgd->leaf_weight;
1652 }
1653
1654 static void cfq_pd_offline(struct blkg_policy_data *pd)
1655 {
1656         struct cfq_group *cfqg = pd_to_cfqg(pd);
1657         int i;
1658
1659         for (i = 0; i < IOPRIO_BE_NR; i++) {
1660                 if (cfqg->async_cfqq[0][i])
1661                         cfq_put_queue(cfqg->async_cfqq[0][i]);
1662                 if (cfqg->async_cfqq[1][i])
1663                         cfq_put_queue(cfqg->async_cfqq[1][i]);
1664         }
1665
1666         if (cfqg->async_idle_cfqq)
1667                 cfq_put_queue(cfqg->async_idle_cfqq);
1668
1669         /*
1670          * @blkg is going offline and will be ignored by
1671          * blkg_[rw]stat_recursive_sum().  Transfer stats to the parent so
1672          * that they don't get lost.  If IOs complete after this point, the
1673          * stats for them will be lost.  Oh well...
1674          */
1675         cfqg_stats_xfer_dead(cfqg);
1676 }
1677
1678 static void cfq_pd_free(struct blkg_policy_data *pd)
1679 {
1680         struct cfq_group *cfqg = pd_to_cfqg(pd);
1681
1682         cfqg_stats_exit(&cfqg->stats);
1683         return kfree(cfqg);
1684 }
1685
1686 static void cfq_pd_reset_stats(struct blkg_policy_data *pd)
1687 {
1688         struct cfq_group *cfqg = pd_to_cfqg(pd);
1689
1690         cfqg_stats_reset(&cfqg->stats);
1691 }
1692
1693 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
1694                                          struct blkcg *blkcg)
1695 {
1696         struct blkcg_gq *blkg;
1697
1698         blkg = blkg_lookup(blkcg, cfqd->queue);
1699         if (likely(blkg))
1700                 return blkg_to_cfqg(blkg);
1701         return NULL;
1702 }
1703
1704 static void cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg)
1705 {
1706         cfqq->cfqg = cfqg;
1707         /* cfqq reference on cfqg */
1708         cfqg_get(cfqg);
1709 }
1710
1711 static u64 cfqg_prfill_weight_device(struct seq_file *sf,
1712                                      struct blkg_policy_data *pd, int off)
1713 {
1714         struct cfq_group *cfqg = pd_to_cfqg(pd);
1715
1716         if (!cfqg->dev_weight)
1717                 return 0;
1718         return __blkg_prfill_u64(sf, pd, cfqg->dev_weight);
1719 }
1720
1721 static int cfqg_print_weight_device(struct seq_file *sf, void *v)
1722 {
1723         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1724                           cfqg_prfill_weight_device, &blkcg_policy_cfq,
1725                           0, false);
1726         return 0;
1727 }
1728
1729 static u64 cfqg_prfill_leaf_weight_device(struct seq_file *sf,
1730                                           struct blkg_policy_data *pd, int off)
1731 {
1732         struct cfq_group *cfqg = pd_to_cfqg(pd);
1733
1734         if (!cfqg->dev_leaf_weight)
1735                 return 0;
1736         return __blkg_prfill_u64(sf, pd, cfqg->dev_leaf_weight);
1737 }
1738
1739 static int cfqg_print_leaf_weight_device(struct seq_file *sf, void *v)
1740 {
1741         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1742                           cfqg_prfill_leaf_weight_device, &blkcg_policy_cfq,
1743                           0, false);
1744         return 0;
1745 }
1746
1747 static int cfq_print_weight(struct seq_file *sf, void *v)
1748 {
1749         struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1750         struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
1751         unsigned int val = 0;
1752
1753         if (cgd)
1754                 val = cgd->weight;
1755
1756         seq_printf(sf, "%u\n", val);
1757         return 0;
1758 }
1759
1760 static int cfq_print_leaf_weight(struct seq_file *sf, void *v)
1761 {
1762         struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1763         struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
1764         unsigned int val = 0;
1765
1766         if (cgd)
1767                 val = cgd->leaf_weight;
1768
1769         seq_printf(sf, "%u\n", val);
1770         return 0;
1771 }
1772
1773 static ssize_t __cfqg_set_weight_device(struct kernfs_open_file *of,
1774                                         char *buf, size_t nbytes, loff_t off,
1775                                         bool on_dfl, bool is_leaf_weight)
1776 {
1777         unsigned int min = on_dfl ? CGROUP_WEIGHT_MIN : CFQ_WEIGHT_LEGACY_MIN;
1778         unsigned int max = on_dfl ? CGROUP_WEIGHT_MAX : CFQ_WEIGHT_LEGACY_MAX;
1779         struct blkcg *blkcg = css_to_blkcg(of_css(of));
1780         struct blkg_conf_ctx ctx;
1781         struct cfq_group *cfqg;
1782         struct cfq_group_data *cfqgd;
1783         int ret;
1784         u64 v;
1785
1786         ret = blkg_conf_prep(blkcg, &blkcg_policy_cfq, buf, &ctx);
1787         if (ret)
1788                 return ret;
1789
1790         if (sscanf(ctx.body, "%llu", &v) == 1) {
1791                 /* require "default" on dfl */
1792                 ret = -ERANGE;
1793                 if (!v && on_dfl)
1794                         goto out_finish;
1795         } else if (!strcmp(strim(ctx.body), "default")) {
1796                 v = 0;
1797         } else {
1798                 ret = -EINVAL;
1799                 goto out_finish;
1800         }
1801
1802         cfqg = blkg_to_cfqg(ctx.blkg);
1803         cfqgd = blkcg_to_cfqgd(blkcg);
1804
1805         ret = -ERANGE;
1806         if (!v || (v >= min && v <= max)) {
1807                 if (!is_leaf_weight) {
1808                         cfqg->dev_weight = v;
1809                         cfqg->new_weight = v ?: cfqgd->weight;
1810                 } else {
1811                         cfqg->dev_leaf_weight = v;
1812                         cfqg->new_leaf_weight = v ?: cfqgd->leaf_weight;
1813                 }
1814                 ret = 0;
1815         }
1816 out_finish:
1817         blkg_conf_finish(&ctx);
1818         return ret ?: nbytes;
1819 }
1820
1821 static ssize_t cfqg_set_weight_device(struct kernfs_open_file *of,
1822                                       char *buf, size_t nbytes, loff_t off)
1823 {
1824         return __cfqg_set_weight_device(of, buf, nbytes, off, false, false);
1825 }
1826
1827 static ssize_t cfqg_set_leaf_weight_device(struct kernfs_open_file *of,
1828                                            char *buf, size_t nbytes, loff_t off)
1829 {
1830         return __cfqg_set_weight_device(of, buf, nbytes, off, false, true);
1831 }
1832
1833 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1834                             bool on_dfl, bool reset_dev, bool is_leaf_weight)
1835 {
1836         unsigned int min = on_dfl ? CGROUP_WEIGHT_MIN : CFQ_WEIGHT_LEGACY_MIN;
1837         unsigned int max = on_dfl ? CGROUP_WEIGHT_MAX : CFQ_WEIGHT_LEGACY_MAX;
1838         struct blkcg *blkcg = css_to_blkcg(css);
1839         struct blkcg_gq *blkg;
1840         struct cfq_group_data *cfqgd;
1841         int ret = 0;
1842
1843         if (val < min || val > max)
1844                 return -ERANGE;
1845
1846         spin_lock_irq(&blkcg->lock);
1847         cfqgd = blkcg_to_cfqgd(blkcg);
1848         if (!cfqgd) {
1849                 ret = -EINVAL;
1850                 goto out;
1851         }
1852
1853         if (!is_leaf_weight)
1854                 cfqgd->weight = val;
1855         else
1856                 cfqgd->leaf_weight = val;
1857
1858         hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
1859                 struct cfq_group *cfqg = blkg_to_cfqg(blkg);
1860
1861                 if (!cfqg)
1862                         continue;
1863
1864                 if (!is_leaf_weight) {
1865                         if (reset_dev)
1866                                 cfqg->dev_weight = 0;
1867                         if (!cfqg->dev_weight)
1868                                 cfqg->new_weight = cfqgd->weight;
1869                 } else {
1870                         if (reset_dev)
1871                                 cfqg->dev_leaf_weight = 0;
1872                         if (!cfqg->dev_leaf_weight)
1873                                 cfqg->new_leaf_weight = cfqgd->leaf_weight;
1874                 }
1875         }
1876
1877 out:
1878         spin_unlock_irq(&blkcg->lock);
1879         return ret;
1880 }
1881
1882 static int cfq_set_weight(struct cgroup_subsys_state *css, struct cftype *cft,
1883                           u64 val)
1884 {
1885         return __cfq_set_weight(css, val, false, false, false);
1886 }
1887
1888 static int cfq_set_leaf_weight(struct cgroup_subsys_state *css,
1889                                struct cftype *cft, u64 val)
1890 {
1891         return __cfq_set_weight(css, val, false, false, true);
1892 }
1893
1894 static int cfqg_print_stat(struct seq_file *sf, void *v)
1895 {
1896         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_stat,
1897                           &blkcg_policy_cfq, seq_cft(sf)->private, false);
1898         return 0;
1899 }
1900
1901 static int cfqg_print_rwstat(struct seq_file *sf, void *v)
1902 {
1903         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat,
1904                           &blkcg_policy_cfq, seq_cft(sf)->private, true);
1905         return 0;
1906 }
1907
1908 static u64 cfqg_prfill_stat_recursive(struct seq_file *sf,
1909                                       struct blkg_policy_data *pd, int off)
1910 {
1911         u64 sum = blkg_stat_recursive_sum(pd_to_blkg(pd),
1912                                           &blkcg_policy_cfq, off);
1913         return __blkg_prfill_u64(sf, pd, sum);
1914 }
1915
1916 static u64 cfqg_prfill_rwstat_recursive(struct seq_file *sf,
1917                                         struct blkg_policy_data *pd, int off)
1918 {
1919         struct blkg_rwstat sum = blkg_rwstat_recursive_sum(pd_to_blkg(pd),
1920                                                         &blkcg_policy_cfq, off);
1921         return __blkg_prfill_rwstat(sf, pd, &sum);
1922 }
1923
1924 static int cfqg_print_stat_recursive(struct seq_file *sf, void *v)
1925 {
1926         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1927                           cfqg_prfill_stat_recursive, &blkcg_policy_cfq,
1928                           seq_cft(sf)->private, false);
1929         return 0;
1930 }
1931
1932 static int cfqg_print_rwstat_recursive(struct seq_file *sf, void *v)
1933 {
1934         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1935                           cfqg_prfill_rwstat_recursive, &blkcg_policy_cfq,
1936                           seq_cft(sf)->private, true);
1937         return 0;
1938 }
1939
1940 static u64 cfqg_prfill_sectors(struct seq_file *sf, struct blkg_policy_data *pd,
1941                                int off)
1942 {
1943         u64 sum = blkg_rwstat_total(&pd->blkg->stat_bytes);
1944
1945         return __blkg_prfill_u64(sf, pd, sum >> 9);
1946 }
1947
1948 static int cfqg_print_stat_sectors(struct seq_file *sf, void *v)
1949 {
1950         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1951                           cfqg_prfill_sectors, &blkcg_policy_cfq, 0, false);
1952         return 0;
1953 }
1954
1955 static u64 cfqg_prfill_sectors_recursive(struct seq_file *sf,
1956                                          struct blkg_policy_data *pd, int off)
1957 {
1958         struct blkg_rwstat tmp = blkg_rwstat_recursive_sum(pd->blkg, NULL,
1959                                         offsetof(struct blkcg_gq, stat_bytes));
1960         u64 sum = atomic64_read(&tmp.aux_cnt[BLKG_RWSTAT_READ]) +
1961                 atomic64_read(&tmp.aux_cnt[BLKG_RWSTAT_WRITE]);
1962
1963         return __blkg_prfill_u64(sf, pd, sum >> 9);
1964 }
1965
1966 static int cfqg_print_stat_sectors_recursive(struct seq_file *sf, void *v)
1967 {
1968         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1969                           cfqg_prfill_sectors_recursive, &blkcg_policy_cfq, 0,
1970                           false);
1971         return 0;
1972 }
1973
1974 #ifdef CONFIG_DEBUG_BLK_CGROUP
1975 static u64 cfqg_prfill_avg_queue_size(struct seq_file *sf,
1976                                       struct blkg_policy_data *pd, int off)
1977 {
1978         struct cfq_group *cfqg = pd_to_cfqg(pd);
1979         u64 samples = blkg_stat_read(&cfqg->stats.avg_queue_size_samples);
1980         u64 v = 0;
1981
1982         if (samples) {
1983                 v = blkg_stat_read(&cfqg->stats.avg_queue_size_sum);
1984                 v = div64_u64(v, samples);
1985         }
1986         __blkg_prfill_u64(sf, pd, v);
1987         return 0;
1988 }
1989
1990 /* print avg_queue_size */
1991 static int cfqg_print_avg_queue_size(struct seq_file *sf, void *v)
1992 {
1993         blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1994                           cfqg_prfill_avg_queue_size, &blkcg_policy_cfq,
1995                           0, false);
1996         return 0;
1997 }
1998 #endif  /* CONFIG_DEBUG_BLK_CGROUP */
1999
2000 static struct cftype cfq_blkcg_legacy_files[] = {
2001         /* on root, weight is mapped to leaf_weight */
2002         {
2003                 .name = "weight_device",
2004                 .flags = CFTYPE_ONLY_ON_ROOT,
2005                 .seq_show = cfqg_print_leaf_weight_device,
2006                 .write = cfqg_set_leaf_weight_device,
2007         },
2008         {
2009                 .name = "weight",
2010                 .flags = CFTYPE_ONLY_ON_ROOT,
2011                 .seq_show = cfq_print_leaf_weight,
2012                 .write_u64 = cfq_set_leaf_weight,
2013         },
2014
2015         /* no such mapping necessary for !roots */
2016         {
2017                 .name = "weight_device",
2018                 .flags = CFTYPE_NOT_ON_ROOT,
2019                 .seq_show = cfqg_print_weight_device,
2020                 .write = cfqg_set_weight_device,
2021         },
2022         {
2023                 .name = "weight",
2024                 .flags = CFTYPE_NOT_ON_ROOT,
2025                 .seq_show = cfq_print_weight,
2026                 .write_u64 = cfq_set_weight,
2027         },
2028
2029         {
2030                 .name = "leaf_weight_device",
2031                 .seq_show = cfqg_print_leaf_weight_device,
2032                 .write = cfqg_set_leaf_weight_device,
2033         },
2034         {
2035                 .name = "leaf_weight",
2036                 .seq_show = cfq_print_leaf_weight,
2037                 .write_u64 = cfq_set_leaf_weight,
2038         },
2039
2040         /* statistics, covers only the tasks in the cfqg */
2041         {
2042                 .name = "time",
2043                 .private = offsetof(struct cfq_group, stats.time),
2044                 .seq_show = cfqg_print_stat,
2045         },
2046         {
2047                 .name = "sectors",
2048                 .seq_show = cfqg_print_stat_sectors,
2049         },
2050         {
2051                 .name = "io_service_bytes",
2052                 .private = (unsigned long)&blkcg_policy_cfq,
2053                 .seq_show = blkg_print_stat_bytes,
2054         },
2055         {
2056                 .name = "io_serviced",
2057                 .private = (unsigned long)&blkcg_policy_cfq,
2058                 .seq_show = blkg_print_stat_ios,
2059         },
2060         {
2061                 .name = "io_service_time",
2062                 .private = offsetof(struct cfq_group, stats.service_time),
2063                 .seq_show = cfqg_print_rwstat,
2064         },
2065         {
2066                 .name = "io_wait_time",
2067                 .private = offsetof(struct cfq_group, stats.wait_time),
2068                 .seq_show = cfqg_print_rwstat,
2069         },
2070         {
2071                 .name = "io_merged",
2072                 .private = offsetof(struct cfq_group, stats.merged),
2073                 .seq_show = cfqg_print_rwstat,
2074         },
2075         {
2076                 .name = "io_queued",
2077                 .private = offsetof(struct cfq_group, stats.queued),
2078                 .seq_show = cfqg_print_rwstat,
2079         },
2080
2081         /* the same statictics which cover the cfqg and its descendants */
2082         {
2083                 .name = "time_recursive",
2084                 .private = offsetof(struct cfq_group, stats.time),
2085                 .seq_show = cfqg_print_stat_recursive,
2086         },
2087         {
2088                 .name = "sectors_recursive",
2089                 .seq_show = cfqg_print_stat_sectors_recursive,
2090         },
2091         {
2092                 .name = "io_service_bytes_recursive",
2093                 .private = (unsigned long)&blkcg_policy_cfq,
2094                 .seq_show = blkg_print_stat_bytes_recursive,
2095         },
2096         {
2097                 .name = "io_serviced_recursive",
2098                 .private = (unsigned long)&blkcg_policy_cfq,
2099                 .seq_show = blkg_print_stat_ios_recursive,
2100         },
2101         {
2102                 .name = "io_service_time_recursive",
2103                 .private = offsetof(struct cfq_group, stats.service_time),
2104                 .seq_show = cfqg_print_rwstat_recursive,
2105         },
2106         {
2107                 .name = "io_wait_time_recursive",
2108                 .private = offsetof(struct cfq_group, stats.wait_time),
2109                 .seq_show = cfqg_print_rwstat_recursive,
2110         },
2111         {
2112                 .name = "io_merged_recursive",
2113                 .private = offsetof(struct cfq_group, stats.merged),
2114                 .seq_show = cfqg_print_rwstat_recursive,
2115         },
2116         {
2117                 .name = "io_queued_recursive",
2118                 .private = offsetof(struct cfq_group, stats.queued),
2119                 .seq_show = cfqg_print_rwstat_recursive,
2120         },
2121 #ifdef CONFIG_DEBUG_BLK_CGROUP
2122         {
2123                 .name = "avg_queue_size",
2124                 .seq_show = cfqg_print_avg_queue_size,
2125         },
2126         {
2127                 .name = "group_wait_time",
2128                 .private = offsetof(struct cfq_group, stats.group_wait_time),
2129                 .seq_show = cfqg_print_stat,
2130         },
2131         {
2132                 .name = "idle_time",
2133                 .private = offsetof(struct cfq_group, stats.idle_time),
2134                 .seq_show = cfqg_print_stat,
2135         },
2136         {
2137                 .name = "empty_time",
2138                 .private = offsetof(struct cfq_group, stats.empty_time),
2139                 .seq_show = cfqg_print_stat,
2140         },
2141         {
2142                 .name = "dequeue",
2143                 .private = offsetof(struct cfq_group, stats.dequeue),
2144                 .seq_show = cfqg_print_stat,
2145         },
2146         {
2147                 .name = "unaccounted_time",
2148                 .private = offsetof(struct cfq_group, stats.unaccounted_time),
2149                 .seq_show = cfqg_print_stat,
2150         },
2151 #endif  /* CONFIG_DEBUG_BLK_CGROUP */
2152         { }     /* terminate */
2153 };
2154
2155 static int cfq_print_weight_on_dfl(struct seq_file *sf, void *v)
2156 {
2157         struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2158         struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
2159
2160         seq_printf(sf, "default %u\n", cgd->weight);
2161         blkcg_print_blkgs(sf, blkcg, cfqg_prfill_weight_device,
2162                           &blkcg_policy_cfq, 0, false);
2163         return 0;
2164 }
2165
2166 static ssize_t cfq_set_weight_on_dfl(struct kernfs_open_file *of,
2167                                      char *buf, size_t nbytes, loff_t off)
2168 {
2169         char *endp;
2170         int ret;
2171         u64 v;
2172
2173         buf = strim(buf);
2174
2175         /* "WEIGHT" or "default WEIGHT" sets the default weight */
2176         v = simple_strtoull(buf, &endp, 0);
2177         if (*endp == '\0' || sscanf(buf, "default %llu", &v) == 1) {
2178                 ret = __cfq_set_weight(of_css(of), v, true, false, false);
2179                 return ret ?: nbytes;
2180         }
2181
2182         /* "MAJ:MIN WEIGHT" */
2183         return __cfqg_set_weight_device(of, buf, nbytes, off, true, false);
2184 }
2185
2186 static struct cftype cfq_blkcg_files[] = {
2187         {
2188                 .name = "weight",
2189                 .flags = CFTYPE_NOT_ON_ROOT,
2190                 .seq_show = cfq_print_weight_on_dfl,
2191                 .write = cfq_set_weight_on_dfl,
2192         },
2193         { }     /* terminate */
2194 };
2195
2196 #else /* GROUP_IOSCHED */
2197 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
2198                                          struct blkcg *blkcg)
2199 {
2200         return cfqd->root_group;
2201 }
2202
2203 static inline void
2204 cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg) {
2205         cfqq->cfqg = cfqg;
2206 }
2207
2208 #endif /* GROUP_IOSCHED */
2209
2210 /*
2211  * The cfqd->service_trees holds all pending cfq_queue's that have
2212  * requests waiting to be processed. It is sorted in the order that
2213  * we will service the queues.
2214  */
2215 static void cfq_service_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2216                                  bool add_front)
2217 {
2218         struct rb_node **p, *parent;
2219         struct cfq_queue *__cfqq;
2220         u64 rb_key;
2221         struct cfq_rb_root *st;
2222         int left;
2223         int new_cfqq = 1;
2224         u64 now = ktime_get_ns();
2225
2226         st = st_for(cfqq->cfqg, cfqq_class(cfqq), cfqq_type(cfqq));
2227         if (cfq_class_idle(cfqq)) {
2228                 rb_key = CFQ_IDLE_DELAY;
2229                 parent = rb_last(&st->rb);
2230                 if (parent && parent != &cfqq->rb_node) {
2231                         __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2232                         rb_key += __cfqq->rb_key;
2233                 } else
2234                         rb_key += now;
2235         } else if (!add_front) {
2236                 /*
2237                  * Get our rb key offset. Subtract any residual slice
2238                  * value carried from last service. A negative resid
2239                  * count indicates slice overrun, and this should position
2240                  * the next service time further away in the tree.
2241                  */
2242                 rb_key = cfq_slice_offset(cfqd, cfqq) + now;
2243                 rb_key -= cfqq->slice_resid;
2244                 cfqq->slice_resid = 0;
2245         } else {
2246                 rb_key = -NSEC_PER_SEC;
2247                 __cfqq = cfq_rb_first(st);
2248                 rb_key += __cfqq ? __cfqq->rb_key : now;
2249         }
2250
2251         if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2252                 new_cfqq = 0;
2253                 /*
2254                  * same position, nothing more to do
2255                  */
2256                 if (rb_key == cfqq->rb_key && cfqq->service_tree == st)
2257                         return;
2258
2259                 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2260                 cfqq->service_tree = NULL;
2261         }
2262
2263         left = 1;
2264         parent = NULL;
2265         cfqq->service_tree = st;
2266         p = &st->rb.rb_node;
2267         while (*p) {
2268                 parent = *p;
2269                 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2270
2271                 /*
2272                  * sort by key, that represents service time.
2273                  */
2274                 if (rb_key < __cfqq->rb_key)
2275                         p = &parent->rb_left;
2276                 else {
2277                         p = &parent->rb_right;
2278                         left = 0;
2279                 }
2280         }
2281
2282         if (left)
2283                 st->left = &cfqq->rb_node;
2284
2285         cfqq->rb_key = rb_key;
2286         rb_link_node(&cfqq->rb_node, parent, p);
2287         rb_insert_color(&cfqq->rb_node, &st->rb);
2288         st->count++;
2289         if (add_front || !new_cfqq)
2290                 return;
2291         cfq_group_notify_queue_add(cfqd, cfqq->cfqg);
2292 }
2293
2294 static struct cfq_queue *
2295 cfq_prio_tree_lookup(struct cfq_data *cfqd, struct rb_root *root,
2296                      sector_t sector, struct rb_node **ret_parent,
2297                      struct rb_node ***rb_link)
2298 {
2299         struct rb_node **p, *parent;
2300         struct cfq_queue *cfqq = NULL;
2301
2302         parent = NULL;
2303         p = &root->rb_node;
2304         while (*p) {
2305                 struct rb_node **n;
2306
2307                 parent = *p;
2308                 cfqq = rb_entry(parent, struct cfq_queue, p_node);
2309
2310                 /*
2311                  * Sort strictly based on sector.  Smallest to the left,
2312                  * largest to the right.
2313                  */
2314                 if (sector > blk_rq_pos(cfqq->next_rq))
2315                         n = &(*p)->rb_right;
2316                 else if (sector < blk_rq_pos(cfqq->next_rq))
2317                         n = &(*p)->rb_left;
2318                 else
2319                         break;
2320                 p = n;
2321                 cfqq = NULL;
2322         }
2323
2324         *ret_parent = parent;
2325         if (rb_link)
2326                 *rb_link = p;
2327         return cfqq;
2328 }
2329
2330 static void cfq_prio_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2331 {
2332         struct rb_node **p, *parent;
2333         struct cfq_queue *__cfqq;
2334
2335         if (cfqq->p_root) {
2336                 rb_erase(&cfqq->p_node, cfqq->p_root);
2337                 cfqq->p_root = NULL;
2338         }
2339
2340         if (cfq_class_idle(cfqq))
2341                 return;
2342         if (!cfqq->next_rq)
2343                 return;
2344
2345         cfqq->p_root = &cfqd->prio_trees[cfqq->org_ioprio];
2346         __cfqq = cfq_prio_tree_lookup(cfqd, cfqq->p_root,
2347                                       blk_rq_pos(cfqq->next_rq), &parent, &p);
2348         if (!__cfqq) {
2349                 rb_link_node(&cfqq->p_node, parent, p);
2350                 rb_insert_color(&cfqq->p_node, cfqq->p_root);
2351         } else
2352                 cfqq->p_root = NULL;
2353 }
2354
2355 /*
2356  * Update cfqq's position in the service tree.
2357  */
2358 static void cfq_resort_rr_list(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2359 {
2360         /*
2361          * Resorting requires the cfqq to be on the RR list already.
2362          */
2363         if (cfq_cfqq_on_rr(cfqq)) {
2364                 cfq_service_tree_add(cfqd, cfqq, 0);
2365                 cfq_prio_tree_add(cfqd, cfqq);
2366         }
2367 }
2368
2369 /*
2370  * add to busy list of queues for service, trying to be fair in ordering
2371  * the pending list according to last request service
2372  */
2373 static void cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2374 {
2375         cfq_log_cfqq(cfqd, cfqq, "add_to_rr");
2376         BUG_ON(cfq_cfqq_on_rr(cfqq));
2377         cfq_mark_cfqq_on_rr(cfqq);
2378         cfqd->busy_queues++;
2379         if (cfq_cfqq_sync(cfqq))
2380                 cfqd->busy_sync_queues++;
2381
2382         cfq_resort_rr_list(cfqd, cfqq);
2383 }
2384
2385 /*
2386  * Called when the cfqq no longer has requests pending, remove it from
2387  * the service tree.
2388  */
2389 static void cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2390 {
2391         cfq_log_cfqq(cfqd, cfqq, "del_from_rr");
2392         BUG_ON(!cfq_cfqq_on_rr(cfqq));
2393         cfq_clear_cfqq_on_rr(cfqq);
2394
2395         if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2396                 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2397                 cfqq->service_tree = NULL;
2398         }
2399         if (cfqq->p_root) {
2400                 rb_erase(&cfqq->p_node, cfqq->p_root);
2401                 cfqq->p_root = NULL;
2402         }
2403
2404         cfq_group_notify_queue_del(cfqd, cfqq->cfqg);
2405         BUG_ON(!cfqd->busy_queues);
2406         cfqd->busy_queues--;
2407         if (cfq_cfqq_sync(cfqq))
2408                 cfqd->busy_sync_queues--;
2409 }
2410
2411 /*
2412  * rb tree support functions
2413  */
2414 static void cfq_del_rq_rb(struct request *rq)
2415 {
2416         struct cfq_queue *cfqq = RQ_CFQQ(rq);
2417         const int sync = rq_is_sync(rq);
2418
2419         BUG_ON(!cfqq->queued[sync]);
2420         cfqq->queued[sync]--;
2421
2422         elv_rb_del(&cfqq->sort_list, rq);
2423
2424         if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list)) {
2425                 /*
2426                  * Queue will be deleted from service tree when we actually
2427                  * expire it later. Right now just remove it from prio tree
2428                  * as it is empty.
2429                  */
2430                 if (cfqq->p_root) {
2431                         rb_erase(&cfqq->p_node, cfqq->p_root);
2432                         cfqq->p_root = NULL;
2433                 }
2434         }
2435 }
2436
2437 static void cfq_add_rq_rb(struct request *rq)
2438 {
2439         struct cfq_queue *cfqq = RQ_CFQQ(rq);
2440         struct cfq_data *cfqd = cfqq->cfqd;
2441         struct request *prev;
2442
2443         cfqq->queued[rq_is_sync(rq)]++;
2444
2445         elv_rb_add(&cfqq->sort_list, rq);
2446
2447         if (!cfq_cfqq_on_rr(cfqq))
2448                 cfq_add_cfqq_rr(cfqd, cfqq);
2449
2450         /*
2451          * check if this request is a better next-serve candidate
2452          */
2453         prev = cfqq->next_rq;
2454         cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq, cfqd->last_position);
2455
2456         /*
2457          * adjust priority tree position, if ->next_rq changes
2458          */
2459         if (prev != cfqq->next_rq)
2460                 cfq_prio_tree_add(cfqd, cfqq);
2461
2462         BUG_ON(!cfqq->next_rq);
2463 }
2464
2465 static void cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
2466 {
2467         elv_rb_del(&cfqq->sort_list, rq);
2468         cfqq->queued[rq_is_sync(rq)]--;
2469         cfqg_stats_update_io_remove(RQ_CFQG(rq), rq->cmd_flags);
2470         cfq_add_rq_rb(rq);
2471         cfqg_stats_update_io_add(RQ_CFQG(rq), cfqq->cfqd->serving_group,
2472                                  rq->cmd_flags);
2473 }
2474
2475 static struct request *
2476 cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
2477 {
2478         struct task_struct *tsk = current;
2479         struct cfq_io_cq *cic;
2480         struct cfq_queue *cfqq;
2481
2482         cic = cfq_cic_lookup(cfqd, tsk->io_context);
2483         if (!cic)
2484                 return NULL;
2485
2486         cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
2487         if (cfqq)
2488                 return elv_rb_find(&cfqq->sort_list, bio_end_sector(bio));
2489
2490         return NULL;
2491 }
2492
2493 static void cfq_activate_request(struct request_queue *q, struct request *rq)
2494 {
2495         struct cfq_data *cfqd = q->elevator->elevator_data;
2496
2497         cfqd->rq_in_driver++;
2498         cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "activate rq, drv=%d",
2499                                                 cfqd->rq_in_driver);
2500
2501         cfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2502 }
2503
2504 static void cfq_deactivate_request(struct request_queue *q, struct request *rq)
2505 {
2506         struct cfq_data *cfqd = q->elevator->elevator_data;
2507
2508         WARN_ON(!cfqd->rq_in_driver);
2509         cfqd->rq_in_driver--;
2510         cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "deactivate rq, drv=%d",
2511                                                 cfqd->rq_in_driver);
2512 }
2513
2514 static void cfq_remove_request(struct request *rq)
2515 {
2516         struct cfq_queue *cfqq = RQ_CFQQ(rq);
2517
2518         if (cfqq->next_rq == rq)
2519                 cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
2520
2521         list_del_init(&rq->queuelist);
2522         cfq_del_rq_rb(rq);
2523
2524         cfqq->cfqd->rq_queued--;
2525         cfqg_stats_update_io_remove(RQ_CFQG(rq), rq->cmd_flags);
2526         if (rq->cmd_flags & REQ_PRIO) {
2527                 WARN_ON(!cfqq->prio_pending);
2528                 cfqq->prio_pending--;
2529         }
2530 }
2531
2532 static int cfq_merge(struct request_queue *q, struct request **req,
2533                      struct bio *bio)
2534 {
2535         struct cfq_data *cfqd = q->elevator->elevator_data;
2536         struct request *__rq;
2537
2538         __rq = cfq_find_rq_fmerge(cfqd, bio);
2539         if (__rq && elv_rq_merge_ok(__rq, bio)) {
2540                 *req = __rq;
2541                 return ELEVATOR_FRONT_MERGE;
2542         }
2543
2544         return ELEVATOR_NO_MERGE;
2545 }
2546
2547 static void cfq_merged_request(struct request_queue *q, struct request *req,
2548                                int type)
2549 {
2550         if (type == ELEVATOR_FRONT_MERGE) {
2551                 struct cfq_queue *cfqq = RQ_CFQQ(req);
2552
2553                 cfq_reposition_rq_rb(cfqq, req);
2554         }
2555 }
2556
2557 static void cfq_bio_merged(struct request_queue *q, struct request *req,
2558                                 struct bio *bio)
2559 {
2560         cfqg_stats_update_io_merged(RQ_CFQG(req), bio->bi_rw);
2561 }
2562
2563 static void
2564 cfq_merged_requests(struct request_queue *q, struct request *rq,
2565                     struct request *next)
2566 {
2567         struct cfq_queue *cfqq = RQ_CFQQ(rq);
2568         struct cfq_data *cfqd = q->elevator->elevator_data;
2569
2570         /*
2571          * reposition in fifo if next is older than rq
2572          */
2573         if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
2574             next->fifo_time < rq->fifo_time &&
2575             cfqq == RQ_CFQQ(next)) {
2576                 list_move(&rq->queuelist, &next->queuelist);
2577                 rq->fifo_time = next->fifo_time;
2578         }
2579
2580         if (cfqq->next_rq == next)
2581                 cfqq->next_rq = rq;
2582         cfq_remove_request(next);
2583         cfqg_stats_update_io_merged(RQ_CFQG(rq), next->cmd_flags);
2584
2585         cfqq = RQ_CFQQ(next);
2586         /*
2587          * all requests of this queue are merged to other queues, delete it
2588          * from the service tree. If it's the active_queue,
2589          * cfq_dispatch_requests() will choose to expire it or do idle
2590          */
2591         if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list) &&
2592             cfqq != cfqd->active_queue)
2593                 cfq_del_cfqq_rr(cfqd, cfqq);
2594 }
2595
2596 static int cfq_allow_merge(struct request_queue *q, struct request *rq,
2597                            struct bio *bio)
2598 {
2599         struct cfq_data *cfqd = q->elevator->elevator_data;
2600         struct cfq_io_cq *cic;
2601         struct cfq_queue *cfqq;
2602
2603         /*
2604          * Disallow merge of a sync bio into an async request.
2605          */
2606         if (cfq_bio_sync(bio) && !rq_is_sync(rq))
2607                 return false;
2608
2609         /*
2610          * Lookup the cfqq that this bio will be queued with and allow
2611          * merge only if rq is queued there.
2612          */
2613         cic = cfq_cic_lookup(cfqd, current->io_context);
2614         if (!cic)
2615                 return false;
2616
2617         cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
2618         return cfqq == RQ_CFQQ(rq);
2619 }
2620
2621 static inline void cfq_del_timer(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2622 {
2623         hrtimer_try_to_cancel(&cfqd->idle_slice_timer);
2624         cfqg_stats_update_idle_time(cfqq->cfqg);
2625 }
2626
2627 static void __cfq_set_active_queue(struct cfq_data *cfqd,
2628                                    struct cfq_queue *cfqq)
2629 {
2630         if (cfqq) {
2631                 cfq_log_cfqq(cfqd, cfqq, "set_active wl_class:%d wl_type:%d",
2632                                 cfqd->serving_wl_class, cfqd->serving_wl_type);
2633                 cfqg_stats_update_avg_queue_size(cfqq->cfqg);
2634                 cfqq->slice_start = 0;
2635                 cfqq->dispatch_start = ktime_get_ns();
2636                 cfqq->allocated_slice = 0;
2637                 cfqq->slice_end = 0;
2638                 cfqq->slice_dispatch = 0;
2639                 cfqq->nr_sectors = 0;
2640
2641                 cfq_clear_cfqq_wait_request(cfqq);
2642                 cfq_clear_cfqq_must_dispatch(cfqq);
2643                 cfq_clear_cfqq_must_alloc_slice(cfqq);
2644                 cfq_clear_cfqq_fifo_expire(cfqq);
2645                 cfq_mark_cfqq_slice_new(cfqq);
2646
2647                 cfq_del_timer(cfqd, cfqq);
2648         }
2649
2650         cfqd->active_queue = cfqq;
2651 }
2652
2653 /*
2654  * current cfqq expired its slice (or was too idle), select new one
2655  */
2656 static void
2657 __cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2658                     bool timed_out)
2659 {
2660         cfq_log_cfqq(cfqd, cfqq, "slice expired t=%d", timed_out);
2661
2662         if (cfq_cfqq_wait_request(cfqq))
2663                 cfq_del_timer(cfqd, cfqq);
2664
2665         cfq_clear_cfqq_wait_request(cfqq);
2666         cfq_clear_cfqq_wait_busy(cfqq);
2667
2668         /*
2669          * If this cfqq is shared between multiple processes, check to
2670          * make sure that those processes are still issuing I/Os within
2671          * the mean seek distance.  If not, it may be time to break the
2672          * queues apart again.
2673          */
2674         if (cfq_cfqq_coop(cfqq) && CFQQ_SEEKY(cfqq))
2675                 cfq_mark_cfqq_split_coop(cfqq);
2676
2677         /*
2678          * store what was left of this slice, if the queue idled/timed out
2679          */
2680         if (timed_out) {
2681                 if (cfq_cfqq_slice_new(cfqq))
2682                         cfqq->slice_resid = cfq_scaled_cfqq_slice(cfqd, cfqq);
2683                 else
2684                         cfqq->slice_resid = cfqq->slice_end - ktime_get_ns();
2685                 cfq_log_cfqq(cfqd, cfqq, "resid=%lld", cfqq->slice_resid);
2686         }
2687
2688         cfq_group_served(cfqd, cfqq->cfqg, cfqq);
2689
2690         if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
2691                 cfq_del_cfqq_rr(cfqd, cfqq);
2692
2693         cfq_resort_rr_list(cfqd, cfqq);
2694
2695         if (cfqq == cfqd->active_queue)
2696                 cfqd->active_queue = NULL;
2697
2698         if (cfqd->active_cic) {
2699                 put_io_context(cfqd->active_cic->icq.ioc);
2700                 cfqd->active_cic = NULL;
2701         }
2702 }
2703
2704 static inline void cfq_slice_expired(struct cfq_data *cfqd, bool timed_out)
2705 {
2706         struct cfq_queue *cfqq = cfqd->active_queue;
2707
2708         if (cfqq)
2709                 __cfq_slice_expired(cfqd, cfqq, timed_out);
2710 }
2711
2712 /*
2713  * Get next queue for service. Unless we have a queue preemption,
2714  * we'll simply select the first cfqq in the service tree.
2715  */
2716 static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
2717 {
2718         struct cfq_rb_root *st = st_for(cfqd->serving_group,
2719                         cfqd->serving_wl_class, cfqd->serving_wl_type);
2720
2721         if (!cfqd->rq_queued)
2722                 return NULL;
2723
2724         /* There is nothing to dispatch */
2725         if (!st)
2726                 return NULL;
2727         if (RB_EMPTY_ROOT(&st->rb))
2728                 return NULL;
2729         return cfq_rb_first(st);
2730 }
2731
2732 static struct cfq_queue *cfq_get_next_queue_forced(struct cfq_data *cfqd)
2733 {
2734         struct cfq_group *cfqg;
2735         struct cfq_queue *cfqq;
2736         int i, j;
2737         struct cfq_rb_root *st;
2738
2739         if (!cfqd->rq_queued)
2740                 return NULL;
2741
2742         cfqg = cfq_get_next_cfqg(cfqd);
2743         if (!cfqg)
2744                 return NULL;
2745
2746         for_each_cfqg_st(cfqg, i, j, st) {
2747                 cfqq = cfq_rb_first(st);
2748                 if (cfqq)
2749                         return cfqq;
2750         }
2751         return NULL;
2752 }
2753
2754 /*
2755  * Get and set a new active queue for service.
2756  */
2757 static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd,
2758                                               struct cfq_queue *cfqq)
2759 {
2760         if (!cfqq)
2761                 cfqq = cfq_get_next_queue(cfqd);
2762
2763         __cfq_set_active_queue(cfqd, cfqq);
2764         return cfqq;
2765 }
2766
2767 static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
2768                                           struct request *rq)
2769 {
2770         if (blk_rq_pos(rq) >= cfqd->last_position)
2771                 return blk_rq_pos(rq) - cfqd->last_position;
2772         else
2773                 return cfqd->last_position - blk_rq_pos(rq);
2774 }
2775
2776 static inline int cfq_rq_close(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2777                                struct request *rq)
2778 {
2779         return cfq_dist_from_last(cfqd, rq) <= CFQQ_CLOSE_THR;
2780 }
2781
2782 static struct cfq_queue *cfqq_close(struct cfq_data *cfqd,
2783                                     struct cfq_queue *cur_cfqq)
2784 {
2785         struct rb_root *root = &cfqd->prio_trees[cur_cfqq->org_ioprio];
2786         struct rb_node *parent, *node;
2787         struct cfq_queue *__cfqq;
2788         sector_t sector = cfqd->last_position;
2789
2790         if (RB_EMPTY_ROOT(root))
2791                 return NULL;
2792
2793         /*
2794          * First, if we find a request starting at the end of the last
2795          * request, choose it.
2796          */
2797         __cfqq = cfq_prio_tree_lookup(cfqd, root, sector, &parent, NULL);
2798         if (__cfqq)
2799                 return __cfqq;
2800
2801         /*
2802          * If the exact sector wasn't found, the parent of the NULL leaf
2803          * will contain the closest sector.
2804          */
2805         __cfqq = rb_entry(parent, struct cfq_queue, p_node);
2806         if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2807                 return __cfqq;
2808
2809         if (blk_rq_pos(__cfqq->next_rq) < sector)
2810                 node = rb_next(&__cfqq->p_node);
2811         else
2812                 node = rb_prev(&__cfqq->p_node);
2813         if (!node)
2814                 return NULL;
2815
2816         __cfqq = rb_entry(node, struct cfq_queue, p_node);
2817         if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2818                 return __cfqq;
2819
2820         return NULL;
2821 }
2822
2823 /*
2824  * cfqd - obvious
2825  * cur_cfqq - passed in so that we don't decide that the current queue is
2826  *            closely cooperating with itself.
2827  *
2828  * So, basically we're assuming that that cur_cfqq has dispatched at least
2829  * one request, and that cfqd->last_position reflects a position on the disk
2830  * associated with the I/O issued by cur_cfqq.  I'm not sure this is a valid
2831  * assumption.
2832  */
2833 static struct cfq_queue *cfq_close_cooperator(struct cfq_data *cfqd,
2834                                               struct cfq_queue *cur_cfqq)
2835 {
2836         struct cfq_queue *cfqq;
2837
2838         if (cfq_class_idle(cur_cfqq))
2839                 return NULL;
2840         if (!cfq_cfqq_sync(cur_cfqq))
2841                 return NULL;
2842         if (CFQQ_SEEKY(cur_cfqq))
2843                 return NULL;
2844
2845         /*
2846          * Don't search priority tree if it's the only queue in the group.
2847          */
2848         if (cur_cfqq->cfqg->nr_cfqq == 1)
2849                 return NULL;
2850
2851         /*
2852          * We should notice if some of the queues are cooperating, eg
2853          * working closely on the same area of the disk. In that case,
2854          * we can group them together and don't waste time idling.
2855          */
2856         cfqq = cfqq_close(cfqd, cur_cfqq);
2857         if (!cfqq)
2858                 return NULL;
2859
2860         /* If new queue belongs to different cfq_group, don't choose it */
2861         if (cur_cfqq->cfqg != cfqq->cfqg)
2862                 return NULL;
2863
2864         /*
2865          * It only makes sense to merge sync queues.
2866          */
2867         if (!cfq_cfqq_sync(cfqq))
2868                 return NULL;
2869         if (CFQQ_SEEKY(cfqq))
2870                 return NULL;
2871
2872         /*
2873          * Do not merge queues of different priority classes
2874          */
2875         if (cfq_class_rt(cfqq) != cfq_class_rt(cur_cfqq))
2876                 return NULL;
2877
2878         return cfqq;
2879 }
2880
2881 /*
2882  * Determine whether we should enforce idle window for this queue.
2883  */
2884
2885 static bool cfq_should_idle(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2886 {
2887         enum wl_class_t wl_class = cfqq_class(cfqq);
2888         struct cfq_rb_root *st = cfqq->service_tree;
2889
2890         BUG_ON(!st);
2891         BUG_ON(!st->count);
2892
2893         if (!cfqd->cfq_slice_idle)
2894                 return false;
2895
2896         /* We never do for idle class queues. */
2897         if (wl_class == IDLE_WORKLOAD)
2898                 return false;
2899
2900         /* We do for queues that were marked with idle window flag. */
2901         if (cfq_cfqq_idle_window(cfqq) &&
2902            !(blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag))
2903                 return true;
2904
2905         /*
2906          * Otherwise, we do only if they are the last ones
2907          * in their service tree.
2908          */
2909         if (st->count == 1 && cfq_cfqq_sync(cfqq) &&
2910            !cfq_io_thinktime_big(cfqd, &st->ttime, false))
2911                 return true;
2912         cfq_log_cfqq(cfqd, cfqq, "Not idling. st->count:%d", st->count);
2913         return false;
2914 }
2915
2916 static void cfq_arm_slice_timer(struct cfq_data *cfqd)
2917 {
2918         struct cfq_queue *cfqq = cfqd->active_queue;
2919         struct cfq_io_cq *cic;
2920         u64 sl, group_idle = 0;
2921         u64 now = ktime_get_ns();
2922
2923         /*
2924          * SSD device without seek penalty, disable idling. But only do so
2925          * for devices that support queuing (and when group idle is 0),
2926          * otherwise we still have a problem with sync vs async workloads.
2927          */
2928         if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag &&
2929                 !cfqd->cfq_group_idle)
2930                 return;
2931
2932         WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
2933         WARN_ON(cfq_cfqq_slice_new(cfqq));
2934
2935         /*
2936          * idle is disabled, either manually or by past process history
2937          */
2938         if (!cfq_should_idle(cfqd, cfqq)) {
2939                 /* no queue idling. Check for group idling */
2940                 if (cfqd->cfq_group_idle)
2941                         group_idle = cfqd->cfq_group_idle;
2942                 else
2943                         return;
2944         }
2945
2946         /*
2947          * still active requests from this queue, don't idle
2948          */
2949         if (cfqq->dispatched)
2950                 return;
2951
2952         /*
2953          * task has exited, don't wait
2954          */
2955         cic = cfqd->active_cic;
2956         if (!cic || !atomic_read(&cic->icq.ioc->active_ref))
2957                 return;
2958
2959         /*
2960          * If our average think time is larger than the remaining time
2961          * slice, then don't idle. This avoids overrunning the allotted
2962          * time slice.
2963          */
2964         if (sample_valid(cic->ttime.ttime_samples) &&
2965             (cfqq->slice_end - now < cic->ttime.ttime_mean)) {
2966                 cfq_log_cfqq(cfqd, cfqq, "Not idling. think_time:%llu",
2967                              cic->ttime.ttime_mean);
2968                 return;
2969         }
2970
2971         /* There are other queues in the group, don't do group idle */
2972         if (group_idle && cfqq->cfqg->nr_cfqq > 1)
2973                 return;
2974
2975         cfq_mark_cfqq_wait_request(cfqq);
2976
2977         if (group_idle)
2978                 sl = cfqd->cfq_group_idle;
2979         else
2980                 sl = cfqd->cfq_slice_idle;
2981
2982         hrtimer_start(&cfqd->idle_slice_timer, ns_to_ktime(sl),
2983                       HRTIMER_MODE_REL);
2984         cfqg_stats_set_start_idle_time(cfqq->cfqg);
2985         cfq_log_cfqq(cfqd, cfqq, "arm_idle: %llu group_idle: %d", sl,
2986                         group_idle ? 1 : 0);
2987 }
2988
2989 /*
2990  * Move request from internal lists to the request queue dispatch list.
2991  */
2992 static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
2993 {
2994         struct cfq_data *cfqd = q->elevator->elevator_data;
2995         struct cfq_queue *cfqq = RQ_CFQQ(rq);
2996
2997         cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
2998
2999         cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
3000         cfq_remove_request(rq);
3001         cfqq->dispatched++;
3002         (RQ_CFQG(rq))->dispatched++;
3003         elv_dispatch_sort(q, rq);
3004
3005         cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]++;
3006         cfqq->nr_sectors += blk_rq_sectors(rq);
3007 }
3008
3009 /*
3010  * return expired entry, or NULL to just start from scratch in rbtree
3011  */
3012 static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
3013 {
3014         struct request *rq = NULL;
3015
3016         if (cfq_cfqq_fifo_expire(cfqq))
3017                 return NULL;
3018
3019         cfq_mark_cfqq_fifo_expire(cfqq);
3020
3021         if (list_empty(&cfqq->fifo))
3022                 return NULL;
3023
3024         rq = rq_entry_fifo(cfqq->fifo.next);
3025         if (ktime_get_ns() < rq->fifo_time)
3026                 rq = NULL;
3027
3028         return rq;
3029 }
3030
3031 static inline int
3032 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3033 {
3034         const int base_rq = cfqd->cfq_slice_async_rq;
3035
3036         WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
3037
3038         return 2 * base_rq * (IOPRIO_BE_NR - cfqq->ioprio);
3039 }
3040
3041 /*
3042  * Must be called with the queue_lock held.
3043  */
3044 static int cfqq_process_refs(struct cfq_queue *cfqq)
3045 {
3046         int process_refs, io_refs;
3047
3048         io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
3049         process_refs = cfqq->ref - io_refs;
3050         BUG_ON(process_refs < 0);
3051         return process_refs;
3052 }
3053
3054 static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
3055 {
3056         int process_refs, new_process_refs;
3057         struct cfq_queue *__cfqq;
3058
3059         /*
3060          * If there are no process references on the new_cfqq, then it is
3061          * unsafe to follow the ->new_cfqq chain as other cfqq's in the
3062          * chain may have dropped their last reference (not just their
3063          * last process reference).
3064          */
3065         if (!cfqq_process_refs(new_cfqq))
3066                 return;
3067
3068         /* Avoid a circular list and skip interim queue merges */
3069         while ((__cfqq = new_cfqq->new_cfqq)) {
3070                 if (__cfqq == cfqq)
3071                         return;
3072                 new_cfqq = __cfqq;
3073         }
3074
3075         process_refs = cfqq_process_refs(cfqq);
3076         new_process_refs = cfqq_process_refs(new_cfqq);
3077         /*
3078          * If the process for the cfqq has gone away, there is no
3079          * sense in merging the queues.
3080          */
3081         if (process_refs == 0 || new_process_refs == 0)
3082                 return;
3083
3084         /*
3085          * Merge in the direction of the lesser amount of work.
3086          */
3087         if (new_process_refs >= process_refs) {
3088                 cfqq->new_cfqq = new_cfqq;
3089                 new_cfqq->ref += process_refs;
3090         } else {
3091                 new_cfqq->new_cfqq = cfqq;
3092                 cfqq->ref += new_process_refs;
3093         }
3094 }
3095
3096 static enum wl_type_t cfq_choose_wl_type(struct cfq_data *cfqd,
3097                         struct cfq_group *cfqg, enum wl_class_t wl_class)
3098 {
3099         struct cfq_queue *queue;
3100         int i;
3101         bool key_valid = false;
3102         u64 lowest_key = 0;
3103         enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
3104
3105         for (i = 0; i <= SYNC_WORKLOAD; ++i) {
3106                 /* select the one with lowest rb_key */
3107                 queue = cfq_rb_first(st_for(cfqg, wl_class, i));
3108                 if (queue &&
3109                     (!key_valid || queue->rb_key < lowest_key)) {
3110                         lowest_key = queue->rb_key;
3111                         cur_best = i;
3112                         key_valid = true;
3113                 }
3114         }
3115
3116         return cur_best;
3117 }
3118
3119 static void
3120 choose_wl_class_and_type(struct cfq_data *cfqd, struct cfq_group *cfqg)
3121 {
3122         u64 slice;
3123         unsigned count;
3124         struct cfq_rb_root *st;
3125         u64 group_slice;
3126         enum wl_class_t original_class = cfqd->serving_wl_class;
3127         u64 now = ktime_get_ns();
3128
3129         /* Choose next priority. RT > BE > IDLE */
3130         if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
3131                 cfqd->serving_wl_class = RT_WORKLOAD;
3132         else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
3133                 cfqd->serving_wl_class = BE_WORKLOAD;
3134         else {
3135                 cfqd->serving_wl_class = IDLE_WORKLOAD;
3136                 cfqd->workload_expires = now + jiffies_to_nsecs(1);
3137                 return;
3138         }
3139
3140         if (original_class != cfqd->serving_wl_class)
3141                 goto new_workload;
3142
3143         /*
3144          * For RT and BE, we have to choose also the type
3145          * (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
3146          * expiration time
3147          */
3148         st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3149         count = st->count;
3150
3151         /*
3152          * check workload expiration, and that we still have other queues ready
3153          */
3154         if (count && !(now > cfqd->workload_expires))
3155                 return;
3156
3157 new_workload:
3158         /* otherwise select new workload type */
3159         cfqd->serving_wl_type = cfq_choose_wl_type(cfqd, cfqg,
3160                                         cfqd->serving_wl_class);
3161         st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3162         count = st->count;
3163
3164         /*
3165          * the workload slice is computed as a fraction of target latency
3166          * proportional to the number of queues in that workload, over
3167          * all the queues in the same priority class
3168          */
3169         group_slice = cfq_group_slice(cfqd, cfqg);
3170
3171         slice = div_u64(group_slice * count,
3172                 max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_wl_class],
3173                       cfq_group_busy_queues_wl(cfqd->serving_wl_class, cfqd,
3174                                         cfqg)));
3175
3176         if (cfqd->serving_wl_type == ASYNC_WORKLOAD) {
3177                 u64 tmp;
3178
3179                 /*
3180                  * Async queues are currently system wide. Just taking
3181                  * proportion of queues with-in same group will lead to higher
3182                  * async ratio system wide as generally root group is going
3183                  * to have higher weight. A more accurate thing would be to
3184                  * calculate system wide asnc/sync ratio.
3185                  */
3186                 tmp = cfqd->cfq_target_latency *
3187                         cfqg_busy_async_queues(cfqd, cfqg);
3188                 tmp = div_u64(tmp, cfqd->busy_queues);
3189                 slice = min_t(u64, slice, tmp);
3190
3191                 /* async workload slice is scaled down according to
3192                  * the sync/async slice ratio. */
3193                 slice = div64_u64(slice*cfqd->cfq_slice[0], cfqd->cfq_slice[1]);
3194         } else
3195                 /* sync workload slice is at least 2 * cfq_slice_idle */
3196                 slice = max(slice, 2 * cfqd->cfq_slice_idle);
3197
3198         slice = max_t(u64, slice, CFQ_MIN_TT);
3199         cfq_log(cfqd, "workload slice:%llu", slice);
3200         cfqd->workload_expires = now + slice;
3201 }
3202
3203 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
3204 {
3205         struct cfq_rb_root *st = &cfqd->grp_service_tree;
3206         struct cfq_group *cfqg;
3207
3208         if (RB_EMPTY_ROOT(&st->rb))
3209                 return NULL;
3210         cfqg = cfq_rb_first_group(st);
3211         update_min_vdisktime(st);
3212         return cfqg;
3213 }
3214
3215 static void cfq_choose_cfqg(struct cfq_data *cfqd)
3216 {
3217         struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
3218         u64 now = ktime_get_ns();
3219
3220         cfqd->serving_group = cfqg;
3221
3222         /* Restore the workload type data */
3223         if (cfqg->saved_wl_slice) {
3224                 cfqd->workload_expires = now + cfqg->saved_wl_slice;
3225                 cfqd->serving_wl_type = cfqg->saved_wl_type;
3226                 cfqd->serving_wl_class = cfqg->saved_wl_class;
3227         } else
3228                 cfqd->workload_expires = now - 1;
3229
3230         choose_wl_class_and_type(cfqd, cfqg);
3231 }
3232
3233 /*
3234  * Select a queue for service. If we have a current active queue,
3235  * check whether to continue servicing it, or retrieve and set a new one.
3236  */
3237 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
3238 {
3239         struct cfq_queue *cfqq, *new_cfqq = NULL;
3240         u64 now = ktime_get_ns();
3241
3242         cfqq = cfqd->active_queue;
3243         if (!cfqq)
3244                 goto new_queue;
3245
3246         if (!cfqd->rq_queued)
3247                 return NULL;
3248
3249         /*
3250          * We were waiting for group to get backlogged. Expire the queue
3251          */
3252         if (cfq_cfqq_wait_busy(cfqq) && !RB_EMPTY_ROOT(&cfqq->sort_list))
3253                 goto expire;
3254
3255         /*
3256          * The active queue has run out of time, expire it and select new.
3257          */
3258         if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq)) {
3259                 /*
3260                  * If slice had not expired at the completion of last request
3261                  * we might not have turned on wait_busy flag. Don't expire
3262                  * the queue yet. Allow the group to get backlogged.
3263                  *
3264                  * The very fact that we have used the slice, that means we
3265                  * have been idling all along on this queue and it should be
3266                  * ok to wait for this request to complete.
3267                  */
3268                 if (cfqq->cfqg->nr_cfqq == 1 && RB_EMPTY_ROOT(&cfqq->sort_list)
3269                     && cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3270                         cfqq = NULL;
3271                         goto keep_queue;
3272                 } else
3273                         goto check_group_idle;
3274         }
3275
3276         /*
3277          * The active queue has requests and isn't expired, allow it to
3278          * dispatch.
3279          */
3280         if (!RB_EMPTY_ROOT(&cfqq->sort_list))
3281                 goto keep_queue;
3282
3283         /*
3284          * If another queue has a request waiting within our mean seek
3285          * distance, let it run.  The expire code will check for close
3286          * cooperators and put the close queue at the front of the service
3287          * tree.  If possible, merge the expiring queue with the new cfqq.
3288          */
3289         new_cfqq = cfq_close_cooperator(cfqd, cfqq);
3290         if (new_cfqq) {
3291                 if (!cfqq->new_cfqq)
3292                         cfq_setup_merge(cfqq, new_cfqq);
3293                 goto expire;
3294         }
3295
3296         /*
3297          * No requests pending. If the active queue still has requests in
3298          * flight or is idling for a new request, allow either of these
3299          * conditions to happen (or time out) before selecting a new queue.
3300          */
3301         if (hrtimer_active(&cfqd->idle_slice_timer)) {
3302                 cfqq = NULL;
3303                 goto keep_queue;
3304         }
3305
3306         /*
3307          * This is a deep seek queue, but the device is much faster than
3308          * the queue can deliver, don't idle
3309          **/
3310         if (CFQQ_SEEKY(cfqq) && cfq_cfqq_idle_window(cfqq) &&
3311             (cfq_cfqq_slice_new(cfqq) ||
3312             (cfqq->slice_end - now > now - cfqq->slice_start))) {
3313                 cfq_clear_cfqq_deep(cfqq);
3314                 cfq_clear_cfqq_idle_window(cfqq);
3315         }
3316
3317         if (cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3318                 cfqq = NULL;
3319                 goto keep_queue;
3320         }
3321
3322         /*
3323          * If group idle is enabled and there are requests dispatched from
3324          * this group, wait for requests to complete.
3325          */
3326 check_group_idle:
3327         if (cfqd->cfq_group_idle && cfqq->cfqg->nr_cfqq == 1 &&
3328             cfqq->cfqg->dispatched &&
3329             !cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true)) {
3330                 cfqq = NULL;
3331                 goto keep_queue;
3332         }
3333
3334 expire:
3335         cfq_slice_expired(cfqd, 0);
3336 new_queue:
3337         /*
3338          * Current queue expired. Check if we have to switch to a new
3339          * service tree
3340          */
3341         if (!new_cfqq)
3342                 cfq_choose_cfqg(cfqd);
3343
3344         cfqq = cfq_set_active_queue(cfqd, new_cfqq);
3345 keep_queue:
3346         return cfqq;
3347 }
3348
3349 static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
3350 {
3351         int dispatched = 0;
3352
3353         while (cfqq->next_rq) {
3354                 cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
3355                 dispatched++;
3356         }
3357
3358         BUG_ON(!list_empty(&cfqq->fifo));
3359
3360         /* By default cfqq is not expired if it is empty. Do it explicitly */
3361         __cfq_slice_expired(cfqq->cfqd, cfqq, 0);
3362         return dispatched;
3363 }
3364
3365 /*
3366  * Drain our current requests. Used for barriers and when switching
3367  * io schedulers on-the-fly.
3368  */
3369 static int cfq_forced_dispatch(struct cfq_data *cfqd)
3370 {
3371         struct cfq_queue *cfqq;
3372         int dispatched = 0;
3373
3374         /* Expire the timeslice of the current active queue first */
3375         cfq_slice_expired(cfqd, 0);
3376         while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL) {
3377                 __cfq_set_active_queue(cfqd, cfqq);
3378                 dispatched += __cfq_forced_dispatch_cfqq(cfqq);
3379         }
3380
3381         BUG_ON(cfqd->busy_queues);
3382
3383         cfq_log(cfqd, "forced_dispatch=%d", dispatched);
3384         return dispatched;
3385 }
3386
3387 static inline bool cfq_slice_used_soon(struct cfq_data *cfqd,
3388         struct cfq_queue *cfqq)
3389 {
3390         u64 now = ktime_get_ns();
3391
3392         /* the queue hasn't finished any request, can't estimate */
3393         if (cfq_cfqq_slice_new(cfqq))
3394                 return true;
3395         if (now + cfqd->cfq_slice_idle * cfqq->dispatched > cfqq->slice_end)
3396                 return true;
3397
3398         return false;
3399 }
3400
3401 static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3402 {
3403         unsigned int max_dispatch;
3404
3405         if (cfq_cfqq_must_dispatch(cfqq))
3406                 return true;
3407
3408         /*
3409          * Drain async requests before we start sync IO
3410          */
3411         if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_flight[BLK_RW_ASYNC])
3412                 return false;
3413
3414         /*
3415          * If this is an async queue and we have sync IO in flight, let it wait
3416          */
3417         if (cfqd->rq_in_flight[BLK_RW_SYNC] && !cfq_cfqq_sync(cfqq))
3418                 return false;
3419
3420         max_dispatch = max_t(unsigned int, cfqd->cfq_quantum / 2, 1);
3421         if (cfq_class_idle(cfqq))
3422                 max_dispatch = 1;
3423
3424         /*
3425          * Does this cfqq already have too much IO in flight?
3426          */
3427         if (cfqq->dispatched >= max_dispatch) {
3428                 bool promote_sync = false;
3429                 /*
3430                  * idle queue must always only have a single IO in flight
3431                  */
3432                 if (cfq_class_idle(cfqq))
3433                         return false;
3434
3435                 /*
3436                  * If there is only one sync queue
3437                  * we can ignore async queue here and give the sync
3438                  * queue no dispatch limit. The reason is a sync queue can
3439                  * preempt async queue, limiting the sync queue doesn't make
3440                  * sense. This is useful for aiostress test.
3441                  */
3442                 if (cfq_cfqq_sync(cfqq) && cfqd->busy_sync_queues == 1)
3443                         promote_sync = true;
3444
3445                 /*
3446                  * We have other queues, don't allow more IO from this one
3447                  */
3448                 if (cfqd->busy_queues > 1 && cfq_slice_used_soon(cfqd, cfqq) &&
3449                                 !promote_sync)
3450                         return false;
3451
3452                 /*
3453                  * Sole queue user, no limit
3454                  */
3455                 if (cfqd->busy_queues == 1 || promote_sync)
3456                         max_dispatch = -1;
3457                 else
3458                         /*
3459                          * Normally we start throttling cfqq when cfq_quantum/2
3460                          * requests have been dispatched. But we can drive
3461                          * deeper queue depths at the beginning of slice
3462                          * subjected to upper limit of cfq_quantum.
3463                          * */
3464                         max_dispatch = cfqd->cfq_quantum;
3465         }
3466
3467         /*
3468          * Async queues must wait a bit before being allowed dispatch.
3469          * We also ramp up the dispatch depth gradually for async IO,
3470          * based on the last sync IO we serviced
3471          */
3472         if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
3473                 u64 last_sync = ktime_get_ns() - cfqd->last_delayed_sync;
3474                 unsigned int depth;
3475
3476                 depth = div64_u64(last_sync, cfqd->cfq_slice[1]);
3477                 if (!depth && !cfqq->dispatched)
3478                         depth = 1;
3479                 if (depth < max_dispatch)
3480                         max_dispatch = depth;
3481         }
3482
3483         /*
3484          * If we're below the current max, allow a dispatch
3485          */
3486         return cfqq->dispatched < max_dispatch;
3487 }
3488
3489 /*
3490  * Dispatch a request from cfqq, moving them to the request queue
3491  * dispatch list.
3492  */
3493 static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3494 {
3495         struct request *rq;
3496
3497         BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
3498
3499         rq = cfq_check_fifo(cfqq);
3500         if (rq)
3501                 cfq_mark_cfqq_must_dispatch(cfqq);
3502
3503         if (!cfq_may_dispatch(cfqd, cfqq))
3504                 return false;
3505
3506         /*
3507          * follow expired path, else get first next available
3508          */
3509         if (!rq)
3510                 rq = cfqq->next_rq;
3511         else
3512                 cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
3513
3514         /*
3515          * insert request into driver dispatch list
3516          */
3517         cfq_dispatch_insert(cfqd->queue, rq);
3518
3519         if (!cfqd->active_cic) {
3520                 struct cfq_io_cq *cic = RQ_CIC(rq);
3521
3522                 atomic_long_inc(&cic->icq.ioc->refcount);
3523                 cfqd->active_cic = cic;
3524         }
3525
3526         return true;
3527 }
3528
3529 /*
3530  * Find the cfqq that we need to service and move a request from that to the
3531  * dispatch list
3532  */
3533 static int cfq_dispatch_requests(struct request_queue *q, int force)
3534 {
3535         struct cfq_data *cfqd = q->elevator->elevator_data;
3536         struct cfq_queue *cfqq;
3537
3538         if (!cfqd->busy_queues)
3539                 return 0;
3540
3541         if (unlikely(force))
3542                 return cfq_forced_dispatch(cfqd);
3543
3544         cfqq = cfq_select_queue(cfqd);
3545         if (!cfqq)
3546                 return 0;
3547
3548         /*
3549          * Dispatch a request from this cfqq, if it is allowed
3550          */
3551         if (!cfq_dispatch_request(cfqd, cfqq))
3552                 return 0;
3553
3554         cfqq->slice_dispatch++;
3555         cfq_clear_cfqq_must_dispatch(cfqq);
3556
3557         /*
3558          * expire an async queue immediately if it has used up its slice. idle
3559          * queue always expire after 1 dispatch round.
3560          */
3561         if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
3562             cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
3563             cfq_class_idle(cfqq))) {
3564                 cfqq->slice_end = ktime_get_ns() + 1;
3565                 cfq_slice_expired(cfqd, 0);
3566         }
3567
3568         cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
3569         return 1;
3570 }
3571
3572 /*
3573  * task holds one reference to the queue, dropped when task exits. each rq
3574  * in-flight on this queue also holds a reference, dropped when rq is freed.
3575  *
3576  * Each cfq queue took a reference on the parent group. Drop it now.
3577  * queue lock must be held here.
3578  */
3579 static void cfq_put_queue(struct cfq_queue *cfqq)
3580 {
3581         struct cfq_data *cfqd = cfqq->cfqd;
3582         struct cfq_group *cfqg;
3583
3584         BUG_ON(cfqq->ref <= 0);
3585
3586         cfqq->ref--;
3587         if (cfqq->ref)
3588                 return;
3589
3590         cfq_log_cfqq(cfqd, cfqq, "put_queue");
3591         BUG_ON(rb_first(&cfqq->sort_list));
3592         BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
3593         cfqg = cfqq->cfqg;
3594
3595         if (unlikely(cfqd->active_queue == cfqq)) {
3596                 __cfq_slice_expired(cfqd, cfqq, 0);
3597                 cfq_schedule_dispatch(cfqd);
3598         }
3599
3600         BUG_ON(cfq_cfqq_on_rr(cfqq));
3601         kmem_cache_free(cfq_pool, cfqq);
3602         cfqg_put(cfqg);
3603 }
3604
3605 static void cfq_put_cooperator(struct cfq_queue *cfqq)
3606 {
3607         struct cfq_queue *__cfqq, *next;
3608
3609         /*
3610          * If this queue was scheduled to merge with another queue, be
3611          * sure to drop the reference taken on that queue (and others in
3612          * the merge chain).  See cfq_setup_merge and cfq_merge_cfqqs.
3613          */
3614         __cfqq = cfqq->new_cfqq;
3615         while (__cfqq) {
3616                 if (__cfqq == cfqq) {
3617                         WARN(1, "cfqq->new_cfqq loop detected\n");
3618                         break;
3619                 }
3620                 next = __cfqq->new_cfqq;
3621                 cfq_put_queue(__cfqq);
3622                 __cfqq = next;
3623         }
3624 }
3625
3626 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3627 {
3628         if (unlikely(cfqq == cfqd->active_queue)) {
3629                 __cfq_slice_expired(cfqd, cfqq, 0);
3630                 cfq_schedule_dispatch(cfqd);
3631         }
3632
3633         cfq_put_cooperator(cfqq);
3634
3635         cfq_put_queue(cfqq);
3636 }
3637
3638 static void cfq_init_icq(struct io_cq *icq)
3639 {
3640         struct cfq_io_cq *cic = icq_to_cic(icq);
3641
3642         cic->ttime.last_end_request = ktime_get_ns();
3643 }
3644
3645 static void cfq_exit_icq(struct io_cq *icq)
3646 {
3647         struct cfq_io_cq *cic = icq_to_cic(icq);
3648         struct cfq_data *cfqd = cic_to_cfqd(cic);
3649
3650         if (cic_to_cfqq(cic, false)) {
3651                 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, false));
3652                 cic_set_cfqq(cic, NULL, false);
3653         }
3654
3655         if (cic_to_cfqq(cic, true)) {
3656                 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, true));
3657                 cic_set_cfqq(cic, NULL, true);
3658         }
3659 }
3660
3661 static void cfq_init_prio_data(struct cfq_queue *cfqq, struct cfq_io_cq *cic)
3662 {
3663         struct task_struct *tsk = current;
3664         int ioprio_class;
3665
3666         if (!cfq_cfqq_prio_changed(cfqq))
3667                 return;
3668
3669         ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3670         switch (ioprio_class) {
3671         default:
3672                 printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
3673         case IOPRIO_CLASS_NONE:
3674                 /*
3675                  * no prio set, inherit CPU scheduling settings
3676                  */
3677                 cfqq->ioprio = task_nice_ioprio(tsk);
3678                 cfqq->ioprio_class = task_nice_ioclass(tsk);
3679                 break;
3680         case IOPRIO_CLASS_RT:
3681                 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3682                 cfqq->ioprio_class = IOPRIO_CLASS_RT;
3683                 break;
3684         case IOPRIO_CLASS_BE:
3685                 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3686                 cfqq->ioprio_class = IOPRIO_CLASS_BE;
3687                 break;
3688         case IOPRIO_CLASS_IDLE:
3689                 cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
3690                 cfqq->ioprio = 7;
3691                 cfq_clear_cfqq_idle_window(cfqq);
3692                 break;
3693         }
3694
3695         /*
3696          * keep track of original prio settings in case we have to temporarily
3697          * elevate the priority of this queue
3698          */
3699         cfqq->org_ioprio = cfqq->ioprio;
3700         cfq_clear_cfqq_prio_changed(cfqq);
3701 }
3702
3703 static void check_ioprio_changed(struct cfq_io_cq *cic, struct bio *bio)
3704 {
3705         int ioprio = cic->icq.ioc->ioprio;
3706         struct cfq_data *cfqd = cic_to_cfqd(cic);
3707         struct cfq_queue *cfqq;
3708
3709         /*
3710          * Check whether ioprio has changed.  The condition may trigger
3711          * spuriously on a newly created cic but there's no harm.
3712          */
3713         if (unlikely(!cfqd) || likely(cic->ioprio == ioprio))
3714                 return;
3715
3716         cfqq = cic_to_cfqq(cic, false);
3717         if (cfqq) {
3718                 cfq_put_queue(cfqq);
3719                 cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic, bio);
3720                 cic_set_cfqq(cic, cfqq, false);
3721         }
3722
3723         cfqq = cic_to_cfqq(cic, true);
3724         if (cfqq)
3725                 cfq_mark_cfqq_prio_changed(cfqq);
3726
3727         cic->ioprio = ioprio;
3728 }
3729
3730 static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3731                           pid_t pid, bool is_sync)
3732 {
3733         RB_CLEAR_NODE(&cfqq->rb_node);
3734         RB_CLEAR_NODE(&cfqq->p_node);
3735         INIT_LIST_HEAD(&cfqq->fifo);
3736
3737         cfqq->ref = 0;
3738         cfqq->cfqd = cfqd;
3739
3740         cfq_mark_cfqq_prio_changed(cfqq);
3741
3742         if (is_sync) {
3743                 if (!cfq_class_idle(cfqq))
3744                         cfq_mark_cfqq_idle_window(cfqq);
3745                 cfq_mark_cfqq_sync(cfqq);
3746         }
3747         cfqq->pid = pid;
3748 }
3749
3750 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3751 static void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3752 {
3753         struct cfq_data *cfqd = cic_to_cfqd(cic);
3754         struct cfq_queue *cfqq;
3755         uint64_t serial_nr;
3756
3757         rcu_read_lock();
3758         serial_nr = bio_blkcg(bio)->css.serial_nr;
3759         rcu_read_unlock();
3760
3761         /*
3762          * Check whether blkcg has changed.  The condition may trigger
3763          * spuriously on a newly created cic but there's no harm.
3764          */
3765         if (unlikely(!cfqd) || likely(cic->blkcg_serial_nr == serial_nr))
3766                 return;
3767
3768         /*
3769          * Drop reference to queues.  New queues will be assigned in new
3770          * group upon arrival of fresh requests.
3771          */
3772         cfqq = cic_to_cfqq(cic, false);
3773         if (cfqq) {
3774                 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3775                 cic_set_cfqq(cic, NULL, false);
3776                 cfq_put_queue(cfqq);
3777         }
3778
3779         cfqq = cic_to_cfqq(cic, true);
3780         if (cfqq) {
3781                 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3782                 cic_set_cfqq(cic, NULL, true);
3783                 cfq_put_queue(cfqq);
3784         }
3785
3786         cic->blkcg_serial_nr = serial_nr;
3787 }
3788 #else
3789 static inline void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio) { }
3790 #endif  /* CONFIG_CFQ_GROUP_IOSCHED */
3791
3792 static struct cfq_queue **
3793 cfq_async_queue_prio(struct cfq_group *cfqg, int ioprio_class, int ioprio)
3794 {
3795         switch (ioprio_class) {
3796         case IOPRIO_CLASS_RT:
3797                 return &cfqg->async_cfqq[0][ioprio];
3798         case IOPRIO_CLASS_NONE:
3799                 ioprio = IOPRIO_NORM;
3800                 /* fall through */
3801         case IOPRIO_CLASS_BE:
3802                 return &cfqg->async_cfqq[1][ioprio];
3803         case IOPRIO_CLASS_IDLE:
3804                 return &cfqg->async_idle_cfqq;
3805         default:
3806                 BUG();
3807         }
3808 }
3809
3810 static struct cfq_queue *
3811 cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct cfq_io_cq *cic,
3812               struct bio *bio)
3813 {
3814         int ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3815         int ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3816         struct cfq_queue **async_cfqq = NULL;
3817         struct cfq_queue *cfqq;
3818         struct cfq_group *cfqg;
3819
3820         rcu_read_lock();
3821         cfqg = cfq_lookup_cfqg(cfqd, bio_blkcg(bio));
3822         if (!cfqg) {
3823                 cfqq = &cfqd->oom_cfqq;
3824                 goto out;
3825         }
3826
3827         if (!is_sync) {
3828                 if (!ioprio_valid(cic->ioprio)) {
3829                         struct task_struct *tsk = current;
3830                         ioprio = task_nice_ioprio(tsk);
3831                         ioprio_class = task_nice_ioclass(tsk);
3832                 }
3833                 async_cfqq = cfq_async_queue_prio(cfqg, ioprio_class, ioprio);
3834                 cfqq = *async_cfqq;
3835                 if (cfqq)
3836                         goto out;
3837         }
3838
3839         cfqq = kmem_cache_alloc_node(cfq_pool,
3840                                      GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
3841                                      cfqd->queue->node);
3842         if (!cfqq) {
3843                 cfqq = &cfqd->oom_cfqq;
3844                 goto out;
3845         }
3846
3847         /* cfq_init_cfqq() assumes cfqq->ioprio_class is initialized. */
3848         cfqq->ioprio_class = IOPRIO_CLASS_NONE;
3849         cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
3850         cfq_init_prio_data(cfqq, cic);
3851         cfq_link_cfqq_cfqg(cfqq, cfqg);
3852         cfq_log_cfqq(cfqd, cfqq, "alloced");
3853
3854         if (async_cfqq) {
3855                 /* a new async queue is created, pin and remember */
3856                 cfqq->ref++;
3857                 *async_cfqq = cfqq;
3858         }
3859 out:
3860         cfqq->ref++;
3861         rcu_read_unlock();
3862         return cfqq;
3863 }
3864
3865 static void
3866 __cfq_update_io_thinktime(struct cfq_ttime *ttime, u64 slice_idle)
3867 {
3868         u64 elapsed = ktime_get_ns() - ttime->last_end_request;
3869         elapsed = min(elapsed, 2UL * slice_idle);
3870
3871         ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
3872         ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed,  8);
3873         ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
3874                                      ttime->ttime_samples);
3875 }
3876
3877 static void
3878 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3879                         struct cfq_io_cq *cic)
3880 {
3881         if (cfq_cfqq_sync(cfqq)) {
3882                 __cfq_update_io_thinktime(&cic->ttime, cfqd->cfq_slice_idle);
3883                 __cfq_update_io_thinktime(&cfqq->service_tree->ttime,
3884                         cfqd->cfq_slice_idle);
3885         }
3886 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3887         __cfq_update_io_thinktime(&cfqq->cfqg->ttime, cfqd->cfq_group_idle);
3888 #endif
3889 }
3890
3891 static void
3892 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3893                        struct request *rq)
3894 {
3895         sector_t sdist = 0;
3896         sector_t n_sec = blk_rq_sectors(rq);
3897         if (cfqq->last_request_pos) {
3898                 if (cfqq->last_request_pos < blk_rq_pos(rq))
3899                         sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
3900                 else
3901                         sdist = cfqq->last_request_pos - blk_rq_pos(rq);
3902         }
3903
3904         cfqq->seek_history <<= 1;
3905         if (blk_queue_nonrot(cfqd->queue))
3906                 cfqq->seek_history |= (n_sec < CFQQ_SECT_THR_NONROT);
3907         else
3908                 cfqq->seek_history |= (sdist > CFQQ_SEEK_THR);
3909 }
3910
3911 /*
3912  * Disable idle window if the process thinks too long or seeks so much that
3913  * it doesn't matter
3914  */
3915 static void
3916 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3917                        struct cfq_io_cq *cic)
3918 {
3919         int old_idle, enable_idle;
3920
3921         /*
3922          * Don't idle for async or idle io prio class
3923          */
3924         if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
3925                 return;
3926
3927         enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
3928
3929         if (cfqq->queued[0] + cfqq->queued[1] >= 4)
3930                 cfq_mark_cfqq_deep(cfqq);
3931
3932         if (cfqq->next_rq && (cfqq->next_rq->cmd_flags & REQ_NOIDLE))
3933                 enable_idle = 0;
3934         else if (!atomic_read(&cic->icq.ioc->active_ref) ||
3935                  !cfqd->cfq_slice_idle ||
3936                  (!cfq_cfqq_deep(cfqq) && CFQQ_SEEKY(cfqq)))
3937                 enable_idle = 0;
3938         else if (sample_valid(cic->ttime.ttime_samples)) {
3939                 if (cic->ttime.ttime_mean > cfqd->cfq_slice_idle)
3940                         enable_idle = 0;
3941                 else
3942                         enable_idle = 1;
3943         }
3944
3945         if (old_idle != enable_idle) {
3946                 cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
3947                 if (enable_idle)
3948                         cfq_mark_cfqq_idle_window(cfqq);
3949                 else
3950                         cfq_clear_cfqq_idle_window(cfqq);
3951         }
3952 }
3953
3954 /*
3955  * Check if new_cfqq should preempt the currently active queue. Return 0 for
3956  * no or if we aren't sure, a 1 will cause a preempt.
3957  */
3958 static bool
3959 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
3960                    struct request *rq)
3961 {
3962         struct cfq_queue *cfqq;
3963
3964         cfqq = cfqd->active_queue;
3965         if (!cfqq)
3966                 return false;
3967
3968         if (cfq_class_idle(new_cfqq))
3969                 return false;
3970
3971         if (cfq_class_idle(cfqq))
3972                 return true;
3973
3974         /*
3975          * Don't allow a non-RT request to preempt an ongoing RT cfqq timeslice.
3976          */
3977         if (cfq_class_rt(cfqq) && !cfq_class_rt(new_cfqq))
3978                 return false;
3979
3980         /*
3981          * if the new request is sync, but the currently running queue is
3982          * not, let the sync request have priority.
3983          */
3984         if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq) && !cfq_cfqq_must_dispatch(cfqq))
3985                 return true;
3986
3987         /*
3988          * Treat ancestors of current cgroup the same way as current cgroup.
3989          * For anybody else we disallow preemption to guarantee service
3990          * fairness among cgroups.
3991          */
3992         if (!cfqg_is_descendant(cfqq->cfqg, new_cfqq->cfqg))
3993                 return false;
3994
3995         if (cfq_slice_used(cfqq))
3996                 return true;
3997
3998         /*
3999          * Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
4000          */
4001         if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
4002                 return true;
4003
4004         WARN_ON_ONCE(cfqq->ioprio_class != new_cfqq->ioprio_class);
4005         /* Allow preemption only if we are idling on sync-noidle tree */
4006         if (cfqd->serving_wl_type == SYNC_NOIDLE_WORKLOAD &&
4007             cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
4008             RB_EMPTY_ROOT(&cfqq->sort_list))
4009                 return true;
4010
4011         /*
4012          * So both queues are sync. Let the new request get disk time if
4013          * it's a metadata request and the current queue is doing regular IO.
4014          */
4015         if ((rq->cmd_flags & REQ_PRIO) && !cfqq->prio_pending)
4016                 return true;
4017
4018         /* An idle queue should not be idle now for some reason */
4019         if (RB_EMPTY_ROOT(&cfqq->sort_list) && !cfq_should_idle(cfqd, cfqq))
4020                 return true;
4021
4022         if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
4023                 return false;
4024
4025         /*
4026          * if this request is as-good as one we would expect from the
4027          * current cfqq, let it preempt
4028          */
4029         if (cfq_rq_close(cfqd, cfqq, rq))
4030                 return true;
4031
4032         return false;
4033 }
4034
4035 /*
4036  * cfqq preempts the active queue. if we allowed preempt with no slice left,
4037  * let it have half of its nominal slice.
4038  */
4039 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4040 {
4041         enum wl_type_t old_type = cfqq_type(cfqd->active_queue);
4042
4043         cfq_log_cfqq(cfqd, cfqq, "preempt");
4044         cfq_slice_expired(cfqd, 1);
4045
4046         /*
4047          * workload type is changed, don't save slice, otherwise preempt
4048          * doesn't happen
4049          */
4050         if (old_type != cfqq_type(cfqq))
4051                 cfqq->cfqg->saved_wl_slice = 0;
4052
4053         /*
4054          * Put the new queue at the front of the of the current list,
4055          * so we know that it will be selected next.
4056          */
4057         BUG_ON(!cfq_cfqq_on_rr(cfqq));
4058
4059         cfq_service_tree_add(cfqd, cfqq, 1);
4060
4061         cfqq->slice_end = 0;
4062         cfq_mark_cfqq_slice_new(cfqq);
4063 }
4064
4065 /*
4066  * Called when a new fs request (rq) is added (to cfqq). Check if there's
4067  * something we should do about it
4068  */
4069 static void
4070 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
4071                 struct request *rq)
4072 {
4073         struct cfq_io_cq *cic = RQ_CIC(rq);
4074
4075         cfqd->rq_queued++;
4076         if (rq->cmd_flags & REQ_PRIO)
4077                 cfqq->prio_pending++;
4078
4079         cfq_update_io_thinktime(cfqd, cfqq, cic);
4080         cfq_update_io_seektime(cfqd, cfqq, rq);
4081         cfq_update_idle_window(cfqd, cfqq, cic);
4082
4083         cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4084
4085         if (cfqq == cfqd->active_queue) {
4086                 /*
4087                  * Remember that we saw a request from this process, but
4088                  * don't start queuing just yet. Otherwise we risk seeing lots
4089                  * of tiny requests, because we disrupt the normal plugging
4090                  * and merging. If the request is already larger than a single
4091                  * page, let it rip immediately. For that case we assume that
4092                  * merging is already done. Ditto for a busy system that
4093                  * has other work pending, don't risk delaying until the
4094                  * idle timer unplug to continue working.
4095                  */
4096                 if (cfq_cfqq_wait_request(cfqq)) {
4097                         if (blk_rq_bytes(rq) > PAGE_CACHE_SIZE ||
4098                             cfqd->busy_queues > 1) {
4099                                 cfq_del_timer(cfqd, cfqq);
4100                                 cfq_clear_cfqq_wait_request(cfqq);
4101                                 __blk_run_queue(cfqd->queue);
4102                         } else {
4103                                 cfqg_stats_update_idle_time(cfqq->cfqg);
4104                                 cfq_mark_cfqq_must_dispatch(cfqq);
4105                         }
4106                 }
4107         } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
4108                 /*
4109                  * not the active queue - expire current slice if it is
4110                  * idle and has expired it's mean thinktime or this new queue
4111                  * has some old slice time left and is of higher priority or
4112                  * this new queue is RT and the current one is BE
4113                  */
4114                 cfq_preempt_queue(cfqd, cfqq);
4115                 __blk_run_queue(cfqd->queue);
4116         }
4117 }
4118
4119 static void cfq_insert_request(struct request_queue *q, struct request *rq)
4120 {
4121         struct cfq_data *cfqd = q->elevator->elevator_data;
4122         struct cfq_queue *cfqq = RQ_CFQQ(rq);
4123
4124         cfq_log_cfqq(cfqd, cfqq, "insert_request");
4125         cfq_init_prio_data(cfqq, RQ_CIC(rq));
4126
4127         rq->fifo_time = ktime_get_ns() + cfqd->cfq_fifo_expire[rq_is_sync(rq)];
4128         list_add_tail(&rq->queuelist, &cfqq->fifo);
4129         cfq_add_rq_rb(rq);
4130         cfqg_stats_update_io_add(RQ_CFQG(rq), cfqd->serving_group,
4131                                  rq->cmd_flags);
4132         cfq_rq_enqueued(cfqd, cfqq, rq);
4133 }
4134
4135 /*
4136  * Update hw_tag based on peak queue depth over 50 samples under
4137  * sufficient load.
4138  */
4139 static void cfq_update_hw_tag(struct cfq_data *cfqd)
4140 {
4141         struct cfq_queue *cfqq = cfqd->active_queue;
4142
4143         if (cfqd->rq_in_driver > cfqd->hw_tag_est_depth)
4144                 cfqd->hw_tag_est_depth = cfqd->rq_in_driver;
4145
4146         if (cfqd->hw_tag == 1)
4147                 return;
4148
4149         if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
4150             cfqd->rq_in_driver <= CFQ_HW_QUEUE_MIN)
4151                 return;
4152
4153         /*
4154          * If active queue hasn't enough requests and can idle, cfq might not
4155          * dispatch sufficient requests to hardware. Don't zero hw_tag in this
4156          * case
4157          */
4158         if (cfqq && cfq_cfqq_idle_window(cfqq) &&
4159             cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
4160             CFQ_HW_QUEUE_MIN && cfqd->rq_in_driver < CFQ_HW_QUEUE_MIN)
4161                 return;
4162
4163         if (cfqd->hw_tag_samples++ < 50)
4164                 return;
4165
4166         if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
4167                 cfqd->hw_tag = 1;
4168         else
4169                 cfqd->hw_tag = 0;
4170 }
4171
4172 static bool cfq_should_wait_busy(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4173 {
4174         struct cfq_io_cq *cic = cfqd->active_cic;
4175         u64 now = ktime_get_ns();
4176
4177         /* If the queue already has requests, don't wait */
4178         if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4179                 return false;
4180
4181         /* If there are other queues in the group, don't wait */
4182         if (cfqq->cfqg->nr_cfqq > 1)
4183                 return false;
4184
4185         /* the only queue in the group, but think time is big */
4186         if (cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true))
4187                 return false;
4188
4189         if (cfq_slice_used(cfqq))
4190                 return true;
4191
4192         /* if slice left is less than think time, wait busy */
4193         if (cic && sample_valid(cic->ttime.ttime_samples)
4194             && (cfqq->slice_end - now < cic->ttime.ttime_mean))
4195                 return true;
4196
4197         /*
4198          * If think times is less than a jiffy than ttime_mean=0 and above
4199          * will not be true. It might happen that slice has not expired yet
4200          * but will expire soon (4-5 ns) during select_queue(). To cover the
4201          * case where think time is less than a jiffy, mark the queue wait
4202          * busy if only 1 jiffy is left in the slice.
4203          */
4204         if (cfqq->slice_end - now <= jiffies_to_nsecs(1))
4205                 return true;
4206
4207         return false;
4208 }
4209
4210 static void cfq_completed_request(struct request_queue *q, struct request *rq)
4211 {
4212         struct cfq_queue *cfqq = RQ_CFQQ(rq);
4213         struct cfq_data *cfqd = cfqq->cfqd;
4214         const int sync = rq_is_sync(rq);
4215         u64 now = ktime_get_ns();
4216
4217         cfq_log_cfqq(cfqd, cfqq, "complete rqnoidle %d",
4218                      !!(rq->cmd_flags & REQ_NOIDLE));
4219
4220         cfq_update_hw_tag(cfqd);
4221
4222         WARN_ON(!cfqd->rq_in_driver);
4223         WARN_ON(!cfqq->dispatched);
4224         cfqd->rq_in_driver--;
4225         cfqq->dispatched--;
4226         (RQ_CFQG(rq))->dispatched--;
4227         cfqg_stats_update_completion(cfqq->cfqg, rq_start_time_ns(rq),
4228                                      rq_io_start_time_ns(rq), rq->cmd_flags);
4229
4230         cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]--;
4231
4232         if (sync) {
4233                 struct cfq_rb_root *st;
4234
4235                 RQ_CIC(rq)->ttime.last_end_request = now;
4236
4237                 if (cfq_cfqq_on_rr(cfqq))
4238                         st = cfqq->service_tree;
4239                 else
4240                         st = st_for(cfqq->cfqg, cfqq_class(cfqq),
4241                                         cfqq_type(cfqq));
4242
4243                 st->ttime.last_end_request = now;
4244                 /*
4245                  * We have to do this check in jiffies since start_time is in
4246                  * jiffies and it is not trivial to convert to ns. If
4247                  * cfq_fifo_expire[1] ever comes close to 1 jiffie, this test
4248                  * will become problematic but so far we are fine (the default
4249                  * is 128 ms).
4250                  */
4251                 if (!time_after(rq->start_time +
4252                                   nsecs_to_jiffies(cfqd->cfq_fifo_expire[1]),
4253                                 jiffies))
4254                         cfqd->last_delayed_sync = now;
4255         }
4256
4257 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4258         cfqq->cfqg->ttime.last_end_request = now;
4259 #endif
4260
4261         /*
4262          * If this is the active queue, check if it needs to be expired,
4263          * or if we want to idle in case it has no pending requests.
4264          */
4265         if (cfqd->active_queue == cfqq) {
4266                 const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
4267
4268                 if (cfq_cfqq_slice_new(cfqq)) {
4269                         cfq_set_prio_slice(cfqd, cfqq);
4270                         cfq_clear_cfqq_slice_new(cfqq);
4271                 }
4272
4273                 /*
4274                  * Should we wait for next request to come in before we expire
4275                  * the queue.
4276                  */
4277                 if (cfq_should_wait_busy(cfqd, cfqq)) {
4278                         u64 extend_sl = cfqd->cfq_slice_idle;
4279                         if (!cfqd->cfq_slice_idle)
4280                                 extend_sl = cfqd->cfq_group_idle;
4281                         cfqq->slice_end = now + extend_sl;
4282                         cfq_mark_cfqq_wait_busy(cfqq);
4283                         cfq_log_cfqq(cfqd, cfqq, "will busy wait");
4284                 }
4285
4286                 /*
4287                  * Idling is not enabled on:
4288                  * - expired queues
4289                  * - idle-priority queues
4290                  * - async queues
4291                  * - queues with still some requests queued
4292                  * - when there is a close cooperator
4293                  */
4294                 if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
4295                         cfq_slice_expired(cfqd, 1);
4296                 else if (sync && cfqq_empty &&
4297                          !cfq_close_cooperator(cfqd, cfqq)) {
4298                         cfq_arm_slice_timer(cfqd);
4299                 }
4300         }
4301
4302         if (!cfqd->rq_in_driver)
4303                 cfq_schedule_dispatch(cfqd);
4304 }
4305
4306 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
4307 {
4308         if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
4309                 cfq_mark_cfqq_must_alloc_slice(cfqq);
4310                 return ELV_MQUEUE_MUST;
4311         }
4312
4313         return ELV_MQUEUE_MAY;
4314 }
4315
4316 static int cfq_may_queue(struct request_queue *q, int rw)
4317 {
4318         struct cfq_data *cfqd = q->elevator->elevator_data;
4319         struct task_struct *tsk = current;
4320         struct cfq_io_cq *cic;
4321         struct cfq_queue *cfqq;
4322
4323         /*
4324          * don't force setup of a queue from here, as a call to may_queue
4325          * does not necessarily imply that a request actually will be queued.
4326          * so just lookup a possibly existing queue, or return 'may queue'
4327          * if that fails
4328          */
4329         cic = cfq_cic_lookup(cfqd, tsk->io_context);
4330         if (!cic)
4331                 return ELV_MQUEUE_MAY;
4332
4333         cfqq = cic_to_cfqq(cic, rw_is_sync(rw));
4334         if (cfqq) {
4335                 cfq_init_prio_data(cfqq, cic);
4336
4337                 return __cfq_may_queue(cfqq);
4338         }
4339
4340         return ELV_MQUEUE_MAY;
4341 }
4342
4343 /*
4344  * queue lock held here
4345  */
4346 static void cfq_put_request(struct request *rq)
4347 {
4348         struct cfq_queue *cfqq = RQ_CFQQ(rq);
4349
4350         if (cfqq) {
4351                 const int rw = rq_data_dir(rq);
4352
4353                 BUG_ON(!cfqq->allocated[rw]);
4354                 cfqq->allocated[rw]--;
4355
4356                 /* Put down rq reference on cfqg */
4357                 cfqg_put(RQ_CFQG(rq));
4358                 rq->elv.priv[0] = NULL;
4359                 rq->elv.priv[1] = NULL;
4360
4361                 cfq_put_queue(cfqq);
4362         }
4363 }
4364
4365 static struct cfq_queue *
4366 cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_cq *cic,
4367                 struct cfq_queue *cfqq)
4368 {
4369         cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
4370         cic_set_cfqq(cic, cfqq->new_cfqq, 1);
4371         cfq_mark_cfqq_coop(cfqq->new_cfqq);
4372         cfq_put_queue(cfqq);
4373         return cic_to_cfqq(cic, 1);
4374 }
4375
4376 /*
4377  * Returns NULL if a new cfqq should be allocated, or the old cfqq if this
4378  * was the last process referring to said cfqq.
4379  */
4380 static struct cfq_queue *
4381 split_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq)
4382 {
4383         if (cfqq_process_refs(cfqq) == 1) {
4384                 cfqq->pid = current->pid;
4385                 cfq_clear_cfqq_coop(cfqq);
4386                 cfq_clear_cfqq_split_coop(cfqq);
4387                 return cfqq;
4388         }
4389
4390         cic_set_cfqq(cic, NULL, 1);
4391
4392         cfq_put_cooperator(cfqq);
4393
4394         cfq_put_queue(cfqq);
4395         return NULL;
4396 }
4397 /*
4398  * Allocate cfq data structures associated with this request.
4399  */
4400 static int
4401 cfq_set_request(struct request_queue *q, struct request *rq, struct bio *bio,
4402                 gfp_t gfp_mask)
4403 {
4404         struct cfq_data *cfqd = q->elevator->elevator_data;
4405         struct cfq_io_cq *cic = icq_to_cic(rq->elv.icq);
4406         const int rw = rq_data_dir(rq);
4407         const bool is_sync = rq_is_sync(rq);
4408         struct cfq_queue *cfqq;
4409
4410         spin_lock_irq(q->queue_lock);
4411
4412         check_ioprio_changed(cic, bio);
4413         check_blkcg_changed(cic, bio);
4414 new_queue:
4415         cfqq = cic_to_cfqq(cic, is_sync);
4416         if (!cfqq || cfqq == &cfqd->oom_cfqq) {
4417                 if (cfqq)
4418                         cfq_put_queue(cfqq);
4419                 cfqq = cfq_get_queue(cfqd, is_sync, cic, bio);
4420                 cic_set_cfqq(cic, cfqq, is_sync);
4421         } else {
4422                 /*
4423                  * If the queue was seeky for too long, break it apart.
4424                  */
4425                 if (cfq_cfqq_coop(cfqq) && cfq_cfqq_split_coop(cfqq)) {
4426                         cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
4427                         cfqq = split_cfqq(cic, cfqq);
4428                         if (!cfqq)
4429                                 goto new_queue;
4430                 }
4431
4432                 /*
4433                  * Check to see if this queue is scheduled to merge with
4434                  * another, closely cooperating queue.  The merging of
4435                  * queues happens here as it must be done in process context.
4436                  * The reference on new_cfqq was taken in merge_cfqqs.
4437                  */
4438                 if (cfqq->new_cfqq)
4439                         cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
4440         }
4441
4442         cfqq->allocated[rw]++;
4443
4444         cfqq->ref++;
4445         cfqg_get(cfqq->cfqg);
4446         rq->elv.priv[0] = cfqq;
4447         rq->elv.priv[1] = cfqq->cfqg;
4448         spin_unlock_irq(q->queue_lock);
4449         return 0;
4450 }
4451
4452 static void cfq_kick_queue(struct work_struct *work)
4453 {
4454         struct cfq_data *cfqd =
4455                 container_of(work, struct cfq_data, unplug_work);
4456         struct request_queue *q = cfqd->queue;
4457
4458         spin_lock_irq(q->queue_lock);
4459         __blk_run_queue(cfqd->queue);
4460         spin_unlock_irq(q->queue_lock);
4461 }
4462
4463 /*
4464  * Timer running if the active_queue is currently idling inside its time slice
4465  */
4466 static enum hrtimer_restart cfq_idle_slice_timer(struct hrtimer *timer)
4467 {
4468         struct cfq_data *cfqd = container_of(timer, struct cfq_data,
4469                                              idle_slice_timer);
4470         struct cfq_queue *cfqq;
4471         unsigned long flags;
4472         int timed_out = 1;
4473
4474         cfq_log(cfqd, "idle timer fired");
4475
4476         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
4477
4478         cfqq = cfqd->active_queue;
4479         if (cfqq) {
4480                 timed_out = 0;
4481
4482                 /*
4483                  * We saw a request before the queue expired, let it through
4484                  */
4485                 if (cfq_cfqq_must_dispatch(cfqq))
4486                         goto out_kick;
4487
4488                 /*
4489                  * expired
4490                  */
4491                 if (cfq_slice_used(cfqq))
4492                         goto expire;
4493
4494                 /*
4495                  * only expire and reinvoke request handler, if there are
4496                  * other queues with pending requests
4497                  */
4498                 if (!cfqd->busy_queues)
4499                         goto out_cont;
4500
4501                 /*
4502                  * not expired and it has a request pending, let it dispatch
4503                  */
4504                 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4505                         goto out_kick;
4506
4507                 /*
4508                  * Queue depth flag is reset only when the idle didn't succeed
4509                  */
4510                 cfq_clear_cfqq_deep(cfqq);
4511         }
4512 expire:
4513         cfq_slice_expired(cfqd, timed_out);
4514 out_kick:
4515         cfq_schedule_dispatch(cfqd);
4516 out_cont:
4517         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
4518         return HRTIMER_NORESTART;
4519 }
4520
4521 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
4522 {
4523         hrtimer_cancel(&cfqd->idle_slice_timer);
4524         cancel_work_sync(&cfqd->unplug_work);
4525 }
4526
4527 static void cfq_exit_queue(struct elevator_queue *e)
4528 {
4529         struct cfq_data *cfqd = e->elevator_data;
4530         struct request_queue *q = cfqd->queue;
4531
4532         cfq_shutdown_timer_wq(cfqd);
4533
4534         spin_lock_irq(q->queue_lock);
4535
4536         if (cfqd->active_queue)
4537                 __cfq_slice_expired(cfqd, cfqd->active_queue, 0);
4538
4539         spin_unlock_irq(q->queue_lock);
4540
4541         cfq_shutdown_timer_wq(cfqd);
4542
4543 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4544         blkcg_deactivate_policy(q, &blkcg_policy_cfq);
4545 #else
4546         kfree(cfqd->root_group);
4547 #endif
4548         kfree(cfqd);
4549 }
4550
4551 static int cfq_init_queue(struct request_queue *q, struct elevator_type *e)
4552 {
4553         struct cfq_data *cfqd;
4554         struct blkcg_gq *blkg __maybe_unused;
4555         int i, ret;
4556         struct elevator_queue *eq;
4557
4558         eq = elevator_alloc(q, e);
4559         if (!eq)
4560                 return -ENOMEM;
4561
4562         cfqd = kzalloc_node(sizeof(*cfqd), GFP_KERNEL, q->node);
4563         if (!cfqd) {
4564                 kobject_put(&eq->kobj);
4565                 return -ENOMEM;
4566         }
4567         eq->elevator_data = cfqd;
4568
4569         cfqd->queue = q;
4570         spin_lock_irq(q->queue_lock);
4571         q->elevator = eq;
4572         spin_unlock_irq(q->queue_lock);
4573
4574         /* Init root service tree */
4575         cfqd->grp_service_tree = CFQ_RB_ROOT;
4576
4577         /* Init root group and prefer root group over other groups by default */
4578 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4579         ret = blkcg_activate_policy(q, &blkcg_policy_cfq);
4580         if (ret)
4581                 goto out_free;
4582
4583         cfqd->root_group = blkg_to_cfqg(q->root_blkg);
4584 #else
4585         ret = -ENOMEM;
4586         cfqd->root_group = kzalloc_node(sizeof(*cfqd->root_group),
4587                                         GFP_KERNEL, cfqd->queue->node);
4588         if (!cfqd->root_group)
4589                 goto out_free;
4590
4591         cfq_init_cfqg_base(cfqd->root_group);
4592         cfqd->root_group->weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4593         cfqd->root_group->leaf_weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4594 #endif
4595
4596         /*
4597          * Not strictly needed (since RB_ROOT just clears the node and we
4598          * zeroed cfqd on alloc), but better be safe in case someone decides
4599          * to add magic to the rb code
4600          */
4601         for (i = 0; i < CFQ_PRIO_LISTS; i++)
4602                 cfqd->prio_trees[i] = RB_ROOT;
4603
4604         /*
4605          * Our fallback cfqq if cfq_get_queue() runs into OOM issues.
4606          * Grab a permanent reference to it, so that the normal code flow
4607          * will not attempt to free it.  oom_cfqq is linked to root_group
4608          * but shouldn't hold a reference as it'll never be unlinked.  Lose
4609          * the reference from linking right away.
4610          */
4611         cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
4612         cfqd->oom_cfqq.ref++;
4613
4614         spin_lock_irq(q->queue_lock);
4615         cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, cfqd->root_group);
4616         cfqg_put(cfqd->root_group);
4617         spin_unlock_irq(q->queue_lock);
4618
4619         hrtimer_init(&cfqd->idle_slice_timer, CLOCK_MONOTONIC,
4620                      HRTIMER_MODE_REL);
4621         cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
4622
4623         INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
4624
4625         cfqd->cfq_quantum = cfq_quantum;
4626         cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
4627         cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
4628         cfqd->cfq_back_max = cfq_back_max;
4629         cfqd->cfq_back_penalty = cfq_back_penalty;
4630         cfqd->cfq_slice[0] = cfq_slice_async;
4631         cfqd->cfq_slice[1] = cfq_slice_sync;
4632         cfqd->cfq_target_latency = cfq_target_latency;
4633         cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
4634         cfqd->cfq_slice_idle = cfq_slice_idle;
4635         cfqd->cfq_group_idle = cfq_group_idle;
4636         cfqd->cfq_latency = 1;
4637         cfqd->hw_tag = -1;
4638         /*
4639          * we optimistically start assuming sync ops weren't delayed in last
4640          * second, in order to have larger depth for async operations.
4641          */
4642         cfqd->last_delayed_sync = ktime_get_ns() - NSEC_PER_SEC;
4643         return 0;
4644
4645 out_free:
4646         kfree(cfqd);
4647         kobject_put(&eq->kobj);
4648         return ret;
4649 }
4650
4651 static void cfq_registered_queue(struct request_queue *q)
4652 {
4653         struct elevator_queue *e = q->elevator;
4654         struct cfq_data *cfqd = e->elevator_data;
4655
4656         /*
4657          * Default to IOPS mode with no idling for SSDs
4658          */
4659         if (blk_queue_nonrot(q))
4660                 cfqd->cfq_slice_idle = 0;
4661 }
4662
4663 /*
4664  * sysfs parts below -->
4665  */
4666 static ssize_t
4667 cfq_var_show(unsigned int var, char *page)
4668 {
4669         return sprintf(page, "%u\n", var);
4670 }
4671
4672 static ssize_t
4673 cfq_var_store(unsigned int *var, const char *page, size_t count)
4674 {
4675         char *p = (char *) page;
4676
4677         *var = simple_strtoul(p, &p, 10);
4678         return count;
4679 }
4680
4681 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV)                            \
4682 static ssize_t __FUNC(struct elevator_queue *e, char *page)             \
4683 {                                                                       \
4684         struct cfq_data *cfqd = e->elevator_data;                       \
4685         u64 __data = __VAR;                                             \
4686         if (__CONV)                                                     \
4687                 __data = div_u64(__data, NSEC_PER_MSEC);                        \
4688         return cfq_var_show(__data, (page));                            \
4689 }
4690 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
4691 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
4692 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
4693 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
4694 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
4695 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
4696 SHOW_FUNCTION(cfq_group_idle_show, cfqd->cfq_group_idle, 1);
4697 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
4698 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
4699 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
4700 SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
4701 SHOW_FUNCTION(cfq_target_latency_show, cfqd->cfq_target_latency, 1);
4702 #undef SHOW_FUNCTION
4703
4704 #define USEC_SHOW_FUNCTION(__FUNC, __VAR)                               \
4705 static ssize_t __FUNC(struct elevator_queue *e, char *page)             \
4706 {                                                                       \
4707         struct cfq_data *cfqd = e->elevator_data;                       \
4708         u64 __data = __VAR;                                             \
4709         __data = div_u64(__data, NSEC_PER_USEC);                        \
4710         return cfq_var_show(__data, (page));                            \
4711 }
4712 USEC_SHOW_FUNCTION(cfq_slice_idle_us_show, cfqd->cfq_slice_idle);
4713 USEC_SHOW_FUNCTION(cfq_group_idle_us_show, cfqd->cfq_group_idle);
4714 USEC_SHOW_FUNCTION(cfq_slice_sync_us_show, cfqd->cfq_slice[1]);
4715 USEC_SHOW_FUNCTION(cfq_slice_async_us_show, cfqd->cfq_slice[0]);
4716 USEC_SHOW_FUNCTION(cfq_target_latency_us_show, cfqd->cfq_target_latency);
4717 #undef USEC_SHOW_FUNCTION
4718
4719 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV)                 \
4720 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4721 {                                                                       \
4722         struct cfq_data *cfqd = e->elevator_data;                       \
4723         unsigned int __data;                                            \
4724         int ret = cfq_var_store(&__data, (page), count);                \
4725         if (__data < (MIN))                                             \
4726                 __data = (MIN);                                         \
4727         else if (__data > (MAX))                                        \
4728                 __data = (MAX);                                         \
4729         if (__CONV)                                                     \
4730                 *(__PTR) = (u64)__data * NSEC_PER_MSEC;                 \
4731         else                                                            \
4732                 *(__PTR) = __data;                                      \
4733         return ret;                                                     \
4734 }
4735 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
4736 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
4737                 UINT_MAX, 1);
4738 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
4739                 UINT_MAX, 1);
4740 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
4741 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
4742                 UINT_MAX, 0);
4743 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
4744 STORE_FUNCTION(cfq_group_idle_store, &cfqd->cfq_group_idle, 0, UINT_MAX, 1);
4745 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
4746 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
4747 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
4748                 UINT_MAX, 0);
4749 STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
4750 STORE_FUNCTION(cfq_target_latency_store, &cfqd->cfq_target_latency, 1, UINT_MAX, 1);
4751 #undef STORE_FUNCTION
4752
4753 #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX)                    \
4754 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4755 {                                                                       \
4756         struct cfq_data *cfqd = e->elevator_data;                       \
4757         unsigned int __data;                                            \
4758         int ret = cfq_var_store(&__data, (page), count);                \
4759         if (__data < (MIN))                                             \
4760                 __data = (MIN);                                         \
4761         else if (__data > (MAX))                                        \
4762                 __data = (MAX);                                         \
4763         *(__PTR) = (u64)__data * NSEC_PER_USEC;                         \
4764         return ret;                                                     \
4765 }
4766 USEC_STORE_FUNCTION(cfq_slice_idle_us_store, &cfqd->cfq_slice_idle, 0, UINT_MAX);
4767 USEC_STORE_FUNCTION(cfq_group_idle_us_store, &cfqd->cfq_group_idle, 0, UINT_MAX);
4768 USEC_STORE_FUNCTION(cfq_slice_sync_us_store, &cfqd->cfq_slice[1], 1, UINT_MAX);
4769 USEC_STORE_FUNCTION(cfq_slice_async_us_store, &cfqd->cfq_slice[0], 1, UINT_MAX);
4770 USEC_STORE_FUNCTION(cfq_target_latency_us_store, &cfqd->cfq_target_latency, 1, UINT_MAX);
4771 #undef USEC_STORE_FUNCTION
4772
4773 #define CFQ_ATTR(name) \
4774         __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
4775
4776 static struct elv_fs_entry cfq_attrs[] = {
4777         CFQ_ATTR(quantum),
4778         CFQ_ATTR(fifo_expire_sync),
4779         CFQ_ATTR(fifo_expire_async),
4780         CFQ_ATTR(back_seek_max),
4781         CFQ_ATTR(back_seek_penalty),
4782         CFQ_ATTR(slice_sync),
4783         CFQ_ATTR(slice_sync_us),
4784         CFQ_ATTR(slice_async),
4785         CFQ_ATTR(slice_async_us),
4786         CFQ_ATTR(slice_async_rq),
4787         CFQ_ATTR(slice_idle),
4788         CFQ_ATTR(slice_idle_us),
4789         CFQ_ATTR(group_idle),
4790         CFQ_ATTR(group_idle_us),
4791         CFQ_ATTR(low_latency),
4792         CFQ_ATTR(target_latency),
4793         CFQ_ATTR(target_latency_us),
4794         __ATTR_NULL
4795 };
4796
4797 static struct elevator_type iosched_cfq = {
4798         .ops = {
4799                 .elevator_merge_fn =            cfq_merge,
4800                 .elevator_merged_fn =           cfq_merged_request,
4801                 .elevator_merge_req_fn =        cfq_merged_requests,
4802                 .elevator_allow_merge_fn =      cfq_allow_merge,
4803                 .elevator_bio_merged_fn =       cfq_bio_merged,
4804                 .elevator_dispatch_fn =         cfq_dispatch_requests,
4805                 .elevator_add_req_fn =          cfq_insert_request,
4806                 .elevator_activate_req_fn =     cfq_activate_request,
4807                 .elevator_deactivate_req_fn =   cfq_deactivate_request,
4808                 .elevator_completed_req_fn =    cfq_completed_request,
4809                 .elevator_former_req_fn =       elv_rb_former_request,
4810                 .elevator_latter_req_fn =       elv_rb_latter_request,
4811                 .elevator_init_icq_fn =         cfq_init_icq,
4812                 .elevator_exit_icq_fn =         cfq_exit_icq,
4813                 .elevator_set_req_fn =          cfq_set_request,
4814                 .elevator_put_req_fn =          cfq_put_request,
4815                 .elevator_may_queue_fn =        cfq_may_queue,
4816                 .elevator_init_fn =             cfq_init_queue,
4817                 .elevator_exit_fn =             cfq_exit_queue,
4818                 .elevator_registered_fn =       cfq_registered_queue,
4819         },
4820         .icq_size       =       sizeof(struct cfq_io_cq),
4821         .icq_align      =       __alignof__(struct cfq_io_cq),
4822         .elevator_attrs =       cfq_attrs,
4823         .elevator_name  =       "cfq",
4824         .elevator_owner =       THIS_MODULE,
4825 };
4826
4827 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4828 static struct blkcg_policy blkcg_policy_cfq = {
4829         .dfl_cftypes            = cfq_blkcg_files,
4830         .legacy_cftypes         = cfq_blkcg_legacy_files,
4831
4832         .cpd_alloc_fn           = cfq_cpd_alloc,
4833         .cpd_init_fn            = cfq_cpd_init,
4834         .cpd_free_fn            = cfq_cpd_free,
4835         .cpd_bind_fn            = cfq_cpd_bind,
4836
4837         .pd_alloc_fn            = cfq_pd_alloc,
4838         .pd_init_fn             = cfq_pd_init,
4839         .pd_offline_fn          = cfq_pd_offline,
4840         .pd_free_fn             = cfq_pd_free,
4841         .pd_reset_stats_fn      = cfq_pd_reset_stats,
4842 };
4843 #endif
4844
4845 static int __init cfq_init(void)
4846 {
4847         int ret;
4848
4849 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4850         ret = blkcg_policy_register(&blkcg_policy_cfq);
4851         if (ret)
4852                 return ret;
4853 #else
4854         cfq_group_idle = 0;
4855 #endif
4856
4857         ret = -ENOMEM;
4858         cfq_pool = KMEM_CACHE(cfq_queue, 0);
4859         if (!cfq_pool)
4860                 goto err_pol_unreg;
4861
4862         ret = elv_register(&iosched_cfq);
4863         if (ret)
4864                 goto err_free_pool;
4865
4866         return 0;
4867
4868 err_free_pool:
4869         kmem_cache_destroy(cfq_pool);
4870 err_pol_unreg:
4871 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4872         blkcg_policy_unregister(&blkcg_policy_cfq);
4873 #endif
4874         return ret;
4875 }
4876
4877 static void __exit cfq_exit(void)
4878 {
4879 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4880         blkcg_policy_unregister(&blkcg_policy_cfq);
4881 #endif
4882         elv_unregister(&iosched_cfq);
4883         kmem_cache_destroy(cfq_pool);
4884 }
4885
4886 module_init(cfq_init);
4887 module_exit(cfq_exit);
4888
4889 MODULE_AUTHOR("Jens Axboe");
4890 MODULE_LICENSE("GPL");
4891 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");