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