OSDN Git Service

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