OSDN Git Service

Merge tag 'v4.4.210' into 10
[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_rb_root *st = cfqq->service_tree;
2989         struct cfq_io_cq *cic;
2990         u64 sl, group_idle = 0;
2991         u64 now = ktime_get_ns();
2992
2993         /*
2994          * SSD device without seek penalty, disable idling. But only do so
2995          * for devices that support queuing (and when group idle is 0),
2996          * otherwise we still have a problem with sync vs async workloads.
2997          */
2998         if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag &&
2999                 !get_group_idle(cfqd))
3000                 return;
3001
3002         WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
3003         WARN_ON(cfq_cfqq_slice_new(cfqq));
3004
3005         /*
3006          * idle is disabled, either manually or by past process history
3007          */
3008         if (!cfq_should_idle(cfqd, cfqq)) {
3009                 /* no queue idling. Check for group idling */
3010                 group_idle = get_group_idle(cfqd);
3011                 if (!group_idle)
3012                         return;
3013         }
3014
3015         /*
3016          * still active requests from this queue, don't idle
3017          */
3018         if (cfqq->dispatched)
3019                 return;
3020
3021         /*
3022          * task has exited, don't wait
3023          */
3024         cic = cfqd->active_cic;
3025         if (!cic || !atomic_read(&cic->icq.ioc->active_ref))
3026                 return;
3027
3028         /*
3029          * If our average think time is larger than the remaining time
3030          * slice, then don't idle. This avoids overrunning the allotted
3031          * time slice.
3032          */
3033         if (sample_valid(cic->ttime.ttime_samples) &&
3034             (cfqq->slice_end - now < cic->ttime.ttime_mean)) {
3035                 cfq_log_cfqq(cfqd, cfqq, "Not idling. think_time:%llu",
3036                              cic->ttime.ttime_mean);
3037                 return;
3038         }
3039
3040         /*
3041          * There are other queues in the group or this is the only group and
3042          * it has too big thinktime, don't do group idle.
3043          */
3044         if (group_idle &&
3045             (cfqq->cfqg->nr_cfqq > 1 ||
3046              cfq_io_thinktime_big(cfqd, &st->ttime, true)))
3047                 return;
3048
3049         cfq_mark_cfqq_wait_request(cfqq);
3050
3051         if (group_idle)
3052                 sl = group_idle;
3053         else
3054                 sl = cfqd->cfq_slice_idle;
3055
3056         hrtimer_start(&cfqd->idle_slice_timer, ns_to_ktime(sl),
3057                       HRTIMER_MODE_REL);
3058         cfqg_stats_set_start_idle_time(cfqq->cfqg);
3059         cfq_log_cfqq(cfqd, cfqq, "arm_idle: %llu group_idle: %d", sl,
3060                         group_idle ? 1 : 0);
3061 }
3062
3063 /*
3064  * Move request from internal lists to the request queue dispatch list.
3065  */
3066 static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
3067 {
3068         struct cfq_data *cfqd = q->elevator->elevator_data;
3069         struct cfq_queue *cfqq = RQ_CFQQ(rq);
3070
3071         cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
3072
3073         cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
3074         cfq_remove_request(rq);
3075         cfqq->dispatched++;
3076         (RQ_CFQG(rq))->dispatched++;
3077         elv_dispatch_sort(q, rq);
3078
3079         cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]++;
3080         cfqq->nr_sectors += blk_rq_sectors(rq);
3081 }
3082
3083 /*
3084  * return expired entry, or NULL to just start from scratch in rbtree
3085  */
3086 static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
3087 {
3088         struct request *rq = NULL;
3089
3090         if (cfq_cfqq_fifo_expire(cfqq))
3091                 return NULL;
3092
3093         cfq_mark_cfqq_fifo_expire(cfqq);
3094
3095         if (list_empty(&cfqq->fifo))
3096                 return NULL;
3097
3098         rq = rq_entry_fifo(cfqq->fifo.next);
3099         if (ktime_get_ns() < rq->fifo_time)
3100                 rq = NULL;
3101
3102         return rq;
3103 }
3104
3105 static inline int
3106 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3107 {
3108         const int base_rq = cfqd->cfq_slice_async_rq;
3109
3110         WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
3111
3112         return 2 * base_rq * (IOPRIO_BE_NR - cfqq->ioprio);
3113 }
3114
3115 /*
3116  * Must be called with the queue_lock held.
3117  */
3118 static int cfqq_process_refs(struct cfq_queue *cfqq)
3119 {
3120         int process_refs, io_refs;
3121
3122         io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
3123         process_refs = cfqq->ref - io_refs;
3124         BUG_ON(process_refs < 0);
3125         return process_refs;
3126 }
3127
3128 static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
3129 {
3130         int process_refs, new_process_refs;
3131         struct cfq_queue *__cfqq;
3132
3133         /*
3134          * If there are no process references on the new_cfqq, then it is
3135          * unsafe to follow the ->new_cfqq chain as other cfqq's in the
3136          * chain may have dropped their last reference (not just their
3137          * last process reference).
3138          */
3139         if (!cfqq_process_refs(new_cfqq))
3140                 return;
3141
3142         /* Avoid a circular list and skip interim queue merges */
3143         while ((__cfqq = new_cfqq->new_cfqq)) {
3144                 if (__cfqq == cfqq)
3145                         return;
3146                 new_cfqq = __cfqq;
3147         }
3148
3149         process_refs = cfqq_process_refs(cfqq);
3150         new_process_refs = cfqq_process_refs(new_cfqq);
3151         /*
3152          * If the process for the cfqq has gone away, there is no
3153          * sense in merging the queues.
3154          */
3155         if (process_refs == 0 || new_process_refs == 0)
3156                 return;
3157
3158         /*
3159          * Merge in the direction of the lesser amount of work.
3160          */
3161         if (new_process_refs >= process_refs) {
3162                 cfqq->new_cfqq = new_cfqq;
3163                 new_cfqq->ref += process_refs;
3164         } else {
3165                 new_cfqq->new_cfqq = cfqq;
3166                 cfqq->ref += new_process_refs;
3167         }
3168 }
3169
3170 static enum wl_type_t cfq_choose_wl_type(struct cfq_data *cfqd,
3171                         struct cfq_group *cfqg, enum wl_class_t wl_class)
3172 {
3173         struct cfq_queue *queue;
3174         int i;
3175         bool key_valid = false;
3176         u64 lowest_key = 0;
3177         enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
3178
3179         for (i = 0; i <= SYNC_WORKLOAD; ++i) {
3180                 /* select the one with lowest rb_key */
3181                 queue = cfq_rb_first(st_for(cfqg, wl_class, i));
3182                 if (queue &&
3183                     (!key_valid || queue->rb_key < lowest_key)) {
3184                         lowest_key = queue->rb_key;
3185                         cur_best = i;
3186                         key_valid = true;
3187                 }
3188         }
3189
3190         return cur_best;
3191 }
3192
3193 static void
3194 choose_wl_class_and_type(struct cfq_data *cfqd, struct cfq_group *cfqg)
3195 {
3196         u64 slice;
3197         unsigned count;
3198         struct cfq_rb_root *st;
3199         u64 group_slice;
3200         enum wl_class_t original_class = cfqd->serving_wl_class;
3201         u64 now = ktime_get_ns();
3202
3203         /* Choose next priority. RT > BE > IDLE */
3204         if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
3205                 cfqd->serving_wl_class = RT_WORKLOAD;
3206         else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
3207                 cfqd->serving_wl_class = BE_WORKLOAD;
3208         else {
3209                 cfqd->serving_wl_class = IDLE_WORKLOAD;
3210                 cfqd->workload_expires = now + jiffies_to_nsecs(1);
3211                 return;
3212         }
3213
3214         if (original_class != cfqd->serving_wl_class)
3215                 goto new_workload;
3216
3217         /*
3218          * For RT and BE, we have to choose also the type
3219          * (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
3220          * expiration time
3221          */
3222         st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3223         count = st->count;
3224
3225         /*
3226          * check workload expiration, and that we still have other queues ready
3227          */
3228         if (count && !(now > cfqd->workload_expires))
3229                 return;
3230
3231 new_workload:
3232         /* otherwise select new workload type */
3233         cfqd->serving_wl_type = cfq_choose_wl_type(cfqd, cfqg,
3234                                         cfqd->serving_wl_class);
3235         st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3236         count = st->count;
3237
3238         /*
3239          * the workload slice is computed as a fraction of target latency
3240          * proportional to the number of queues in that workload, over
3241          * all the queues in the same priority class
3242          */
3243         group_slice = cfq_group_slice(cfqd, cfqg);
3244
3245         slice = div_u64(group_slice * count,
3246                 max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_wl_class],
3247                       cfq_group_busy_queues_wl(cfqd->serving_wl_class, cfqd,
3248                                         cfqg)));
3249
3250         if (cfqd->serving_wl_type == ASYNC_WORKLOAD) {
3251                 u64 tmp;
3252
3253                 /*
3254                  * Async queues are currently system wide. Just taking
3255                  * proportion of queues with-in same group will lead to higher
3256                  * async ratio system wide as generally root group is going
3257                  * to have higher weight. A more accurate thing would be to
3258                  * calculate system wide asnc/sync ratio.
3259                  */
3260                 tmp = cfqd->cfq_target_latency *
3261                         cfqg_busy_async_queues(cfqd, cfqg);
3262                 tmp = div_u64(tmp, cfqd->busy_queues);
3263                 slice = min_t(u64, slice, tmp);
3264
3265                 /* async workload slice is scaled down according to
3266                  * the sync/async slice ratio. */
3267                 slice = div64_u64(slice*cfqd->cfq_slice[0], cfqd->cfq_slice[1]);
3268         } else
3269                 /* sync workload slice is at least 2 * cfq_slice_idle */
3270                 slice = max(slice, 2 * cfqd->cfq_slice_idle);
3271
3272         slice = max_t(u64, slice, CFQ_MIN_TT);
3273         cfq_log(cfqd, "workload slice:%llu", slice);
3274         cfqd->workload_expires = now + slice;
3275 }
3276
3277 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
3278 {
3279         struct cfq_rb_root *st = &cfqd->grp_service_tree;
3280         struct cfq_group *cfqg;
3281
3282         if (RB_EMPTY_ROOT(&st->rb))
3283                 return NULL;
3284         cfqg = cfq_rb_first_group(st);
3285         update_min_vdisktime(st);
3286         return cfqg;
3287 }
3288
3289 static void cfq_choose_cfqg(struct cfq_data *cfqd)
3290 {
3291         struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
3292         u64 now = ktime_get_ns();
3293
3294         cfqd->serving_group = cfqg;
3295
3296         /* Restore the workload type data */
3297         if (cfqg->saved_wl_slice) {
3298                 cfqd->workload_expires = now + cfqg->saved_wl_slice;
3299                 cfqd->serving_wl_type = cfqg->saved_wl_type;
3300                 cfqd->serving_wl_class = cfqg->saved_wl_class;
3301         } else
3302                 cfqd->workload_expires = now - 1;
3303
3304         choose_wl_class_and_type(cfqd, cfqg);
3305 }
3306
3307 /*
3308  * Select a queue for service. If we have a current active queue,
3309  * check whether to continue servicing it, or retrieve and set a new one.
3310  */
3311 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
3312 {
3313         struct cfq_queue *cfqq, *new_cfqq = NULL;
3314         u64 now = ktime_get_ns();
3315
3316         cfqq = cfqd->active_queue;
3317         if (!cfqq)
3318                 goto new_queue;
3319
3320         if (!cfqd->rq_queued)
3321                 return NULL;
3322
3323         /*
3324          * We were waiting for group to get backlogged. Expire the queue
3325          */
3326         if (cfq_cfqq_wait_busy(cfqq) && !RB_EMPTY_ROOT(&cfqq->sort_list))
3327                 goto expire;
3328
3329         /*
3330          * The active queue has run out of time, expire it and select new.
3331          */
3332         if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq)) {
3333                 /*
3334                  * If slice had not expired at the completion of last request
3335                  * we might not have turned on wait_busy flag. Don't expire
3336                  * the queue yet. Allow the group to get backlogged.
3337                  *
3338                  * The very fact that we have used the slice, that means we
3339                  * have been idling all along on this queue and it should be
3340                  * ok to wait for this request to complete.
3341                  */
3342                 if (cfqq->cfqg->nr_cfqq == 1 && RB_EMPTY_ROOT(&cfqq->sort_list)
3343                     && cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3344                         cfqq = NULL;
3345                         goto keep_queue;
3346                 } else
3347                         goto check_group_idle;
3348         }
3349
3350         /*
3351          * The active queue has requests and isn't expired, allow it to
3352          * dispatch.
3353          */
3354         if (!RB_EMPTY_ROOT(&cfqq->sort_list))
3355                 goto keep_queue;
3356
3357         /*
3358          * If another queue has a request waiting within our mean seek
3359          * distance, let it run.  The expire code will check for close
3360          * cooperators and put the close queue at the front of the service
3361          * tree.  If possible, merge the expiring queue with the new cfqq.
3362          */
3363         new_cfqq = cfq_close_cooperator(cfqd, cfqq);
3364         if (new_cfqq) {
3365                 if (!cfqq->new_cfqq)
3366                         cfq_setup_merge(cfqq, new_cfqq);
3367                 goto expire;
3368         }
3369
3370         /*
3371          * No requests pending. If the active queue still has requests in
3372          * flight or is idling for a new request, allow either of these
3373          * conditions to happen (or time out) before selecting a new queue.
3374          */
3375         if (hrtimer_active(&cfqd->idle_slice_timer)) {
3376                 cfqq = NULL;
3377                 goto keep_queue;
3378         }
3379
3380         /*
3381          * This is a deep seek queue, but the device is much faster than
3382          * the queue can deliver, don't idle
3383          **/
3384         if (CFQQ_SEEKY(cfqq) && cfq_cfqq_idle_window(cfqq) &&
3385             (cfq_cfqq_slice_new(cfqq) ||
3386             (cfqq->slice_end - now > now - cfqq->slice_start))) {
3387                 cfq_clear_cfqq_deep(cfqq);
3388                 cfq_clear_cfqq_idle_window(cfqq);
3389         }
3390
3391         if (cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3392                 cfqq = NULL;
3393                 goto keep_queue;
3394         }
3395
3396         /*
3397          * If group idle is enabled and there are requests dispatched from
3398          * this group, wait for requests to complete.
3399          */
3400 check_group_idle:
3401         if (get_group_idle(cfqd) && cfqq->cfqg->nr_cfqq == 1 &&
3402             cfqq->cfqg->dispatched &&
3403             !cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true)) {
3404                 cfqq = NULL;
3405                 goto keep_queue;
3406         }
3407
3408 expire:
3409         cfq_slice_expired(cfqd, 0);
3410 new_queue:
3411         /*
3412          * Current queue expired. Check if we have to switch to a new
3413          * service tree
3414          */
3415         if (!new_cfqq)
3416                 cfq_choose_cfqg(cfqd);
3417
3418         cfqq = cfq_set_active_queue(cfqd, new_cfqq);
3419 keep_queue:
3420         return cfqq;
3421 }
3422
3423 static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
3424 {
3425         int dispatched = 0;
3426
3427         while (cfqq->next_rq) {
3428                 cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
3429                 dispatched++;
3430         }
3431
3432         BUG_ON(!list_empty(&cfqq->fifo));
3433
3434         /* By default cfqq is not expired if it is empty. Do it explicitly */
3435         __cfq_slice_expired(cfqq->cfqd, cfqq, 0);
3436         return dispatched;
3437 }
3438
3439 /*
3440  * Drain our current requests. Used for barriers and when switching
3441  * io schedulers on-the-fly.
3442  */
3443 static int cfq_forced_dispatch(struct cfq_data *cfqd)
3444 {
3445         struct cfq_queue *cfqq;
3446         int dispatched = 0;
3447
3448         /* Expire the timeslice of the current active queue first */
3449         cfq_slice_expired(cfqd, 0);
3450         while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL) {
3451                 __cfq_set_active_queue(cfqd, cfqq);
3452                 dispatched += __cfq_forced_dispatch_cfqq(cfqq);
3453         }
3454
3455         BUG_ON(cfqd->busy_queues);
3456
3457         cfq_log(cfqd, "forced_dispatch=%d", dispatched);
3458         return dispatched;
3459 }
3460
3461 static inline bool cfq_slice_used_soon(struct cfq_data *cfqd,
3462         struct cfq_queue *cfqq)
3463 {
3464         u64 now = ktime_get_ns();
3465
3466         /* the queue hasn't finished any request, can't estimate */
3467         if (cfq_cfqq_slice_new(cfqq))
3468                 return true;
3469         if (now + cfqd->cfq_slice_idle * cfqq->dispatched > cfqq->slice_end)
3470                 return true;
3471
3472         return false;
3473 }
3474
3475 static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3476 {
3477         unsigned int max_dispatch;
3478
3479         if (cfq_cfqq_must_dispatch(cfqq))
3480                 return true;
3481
3482         /*
3483          * Drain async requests before we start sync IO
3484          */
3485         if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_flight[BLK_RW_ASYNC])
3486                 return false;
3487
3488         /*
3489          * If this is an async queue and we have sync IO in flight, let it wait
3490          */
3491         if (cfqd->rq_in_flight[BLK_RW_SYNC] && !cfq_cfqq_sync(cfqq))
3492                 return false;
3493
3494         max_dispatch = max_t(unsigned int, cfqd->cfq_quantum / 2, 1);
3495         if (cfq_class_idle(cfqq))
3496                 max_dispatch = 1;
3497
3498         /*
3499          * Does this cfqq already have too much IO in flight?
3500          */
3501         if (cfqq->dispatched >= max_dispatch) {
3502                 bool promote_sync = false;
3503                 /*
3504                  * idle queue must always only have a single IO in flight
3505                  */
3506                 if (cfq_class_idle(cfqq))
3507                         return false;
3508
3509                 /*
3510                  * If there is only one sync queue
3511                  * we can ignore async queue here and give the sync
3512                  * queue no dispatch limit. The reason is a sync queue can
3513                  * preempt async queue, limiting the sync queue doesn't make
3514                  * sense. This is useful for aiostress test.
3515                  */
3516                 if (cfq_cfqq_sync(cfqq) && cfqd->busy_sync_queues == 1)
3517                         promote_sync = true;
3518
3519                 /*
3520                  * We have other queues, don't allow more IO from this one
3521                  */
3522                 if (cfqd->busy_queues > 1 && cfq_slice_used_soon(cfqd, cfqq) &&
3523                                 !promote_sync)
3524                         return false;
3525
3526                 /*
3527                  * Sole queue user, no limit
3528                  */
3529                 if (cfqd->busy_queues == 1 || promote_sync)
3530                         max_dispatch = -1;
3531                 else
3532                         /*
3533                          * Normally we start throttling cfqq when cfq_quantum/2
3534                          * requests have been dispatched. But we can drive
3535                          * deeper queue depths at the beginning of slice
3536                          * subjected to upper limit of cfq_quantum.
3537                          * */
3538                         max_dispatch = cfqd->cfq_quantum;
3539         }
3540
3541         /*
3542          * Async queues must wait a bit before being allowed dispatch.
3543          * We also ramp up the dispatch depth gradually for async IO,
3544          * based on the last sync IO we serviced
3545          */
3546         if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
3547                 u64 last_sync = ktime_get_ns() - cfqd->last_delayed_sync;
3548                 unsigned int depth;
3549
3550                 depth = div64_u64(last_sync, cfqd->cfq_slice[1]);
3551                 if (!depth && !cfqq->dispatched)
3552                         depth = 1;
3553                 if (depth < max_dispatch)
3554                         max_dispatch = depth;
3555         }
3556
3557         /*
3558          * If we're below the current max, allow a dispatch
3559          */
3560         return cfqq->dispatched < max_dispatch;
3561 }
3562
3563 /*
3564  * Dispatch a request from cfqq, moving them to the request queue
3565  * dispatch list.
3566  */
3567 static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3568 {
3569         struct request *rq;
3570
3571         BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
3572
3573         rq = cfq_check_fifo(cfqq);
3574         if (rq)
3575                 cfq_mark_cfqq_must_dispatch(cfqq);
3576
3577         if (!cfq_may_dispatch(cfqd, cfqq))
3578                 return false;
3579
3580         /*
3581          * follow expired path, else get first next available
3582          */
3583         if (!rq)
3584                 rq = cfqq->next_rq;
3585         else
3586                 cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
3587
3588         /*
3589          * insert request into driver dispatch list
3590          */
3591         cfq_dispatch_insert(cfqd->queue, rq);
3592
3593         if (!cfqd->active_cic) {
3594                 struct cfq_io_cq *cic = RQ_CIC(rq);
3595
3596                 atomic_long_inc(&cic->icq.ioc->refcount);
3597                 cfqd->active_cic = cic;
3598         }
3599
3600         return true;
3601 }
3602
3603 /*
3604  * Find the cfqq that we need to service and move a request from that to the
3605  * dispatch list
3606  */
3607 static int cfq_dispatch_requests(struct request_queue *q, int force)
3608 {
3609         struct cfq_data *cfqd = q->elevator->elevator_data;
3610         struct cfq_queue *cfqq;
3611
3612         if (!cfqd->busy_queues)
3613                 return 0;
3614
3615         if (unlikely(force))
3616                 return cfq_forced_dispatch(cfqd);
3617
3618         cfqq = cfq_select_queue(cfqd);
3619         if (!cfqq)
3620                 return 0;
3621
3622         /*
3623          * Dispatch a request from this cfqq, if it is allowed
3624          */
3625         if (!cfq_dispatch_request(cfqd, cfqq))
3626                 return 0;
3627
3628         cfqq->slice_dispatch++;
3629         cfq_clear_cfqq_must_dispatch(cfqq);
3630
3631         /*
3632          * expire an async queue immediately if it has used up its slice. idle
3633          * queue always expire after 1 dispatch round.
3634          */
3635         if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
3636             cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
3637             cfq_class_idle(cfqq))) {
3638                 cfqq->slice_end = ktime_get_ns() + 1;
3639                 cfq_slice_expired(cfqd, 0);
3640         }
3641
3642         cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
3643         return 1;
3644 }
3645
3646 /*
3647  * task holds one reference to the queue, dropped when task exits. each rq
3648  * in-flight on this queue also holds a reference, dropped when rq is freed.
3649  *
3650  * Each cfq queue took a reference on the parent group. Drop it now.
3651  * queue lock must be held here.
3652  */
3653 static void cfq_put_queue(struct cfq_queue *cfqq)
3654 {
3655         struct cfq_data *cfqd = cfqq->cfqd;
3656         struct cfq_group *cfqg;
3657
3658         BUG_ON(cfqq->ref <= 0);
3659
3660         cfqq->ref--;
3661         if (cfqq->ref)
3662                 return;
3663
3664         cfq_log_cfqq(cfqd, cfqq, "put_queue");
3665         BUG_ON(rb_first(&cfqq->sort_list));
3666         BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
3667         cfqg = cfqq->cfqg;
3668
3669         if (unlikely(cfqd->active_queue == cfqq)) {
3670                 __cfq_slice_expired(cfqd, cfqq, 0);
3671                 cfq_schedule_dispatch(cfqd);
3672         }
3673
3674         BUG_ON(cfq_cfqq_on_rr(cfqq));
3675         kmem_cache_free(cfq_pool, cfqq);
3676         cfqg_put(cfqg);
3677 }
3678
3679 static void cfq_put_cooperator(struct cfq_queue *cfqq)
3680 {
3681         struct cfq_queue *__cfqq, *next;
3682
3683         /*
3684          * If this queue was scheduled to merge with another queue, be
3685          * sure to drop the reference taken on that queue (and others in
3686          * the merge chain).  See cfq_setup_merge and cfq_merge_cfqqs.
3687          */
3688         __cfqq = cfqq->new_cfqq;
3689         while (__cfqq) {
3690                 if (__cfqq == cfqq) {
3691                         WARN(1, "cfqq->new_cfqq loop detected\n");
3692                         break;
3693                 }
3694                 next = __cfqq->new_cfqq;
3695                 cfq_put_queue(__cfqq);
3696                 __cfqq = next;
3697         }
3698 }
3699
3700 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3701 {
3702         if (unlikely(cfqq == cfqd->active_queue)) {
3703                 __cfq_slice_expired(cfqd, cfqq, 0);
3704                 cfq_schedule_dispatch(cfqd);
3705         }
3706
3707         cfq_put_cooperator(cfqq);
3708
3709         cfq_put_queue(cfqq);
3710 }
3711
3712 static void cfq_init_icq(struct io_cq *icq)
3713 {
3714         struct cfq_io_cq *cic = icq_to_cic(icq);
3715
3716         cic->ttime.last_end_request = ktime_get_ns();
3717 }
3718
3719 static void cfq_exit_icq(struct io_cq *icq)
3720 {
3721         struct cfq_io_cq *cic = icq_to_cic(icq);
3722         struct cfq_data *cfqd = cic_to_cfqd(cic);
3723
3724         if (cic_to_cfqq(cic, false)) {
3725                 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, false));
3726                 cic_set_cfqq(cic, NULL, false);
3727         }
3728
3729         if (cic_to_cfqq(cic, true)) {
3730                 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, true));
3731                 cic_set_cfqq(cic, NULL, true);
3732         }
3733 }
3734
3735 static void cfq_init_prio_data(struct cfq_queue *cfqq, struct cfq_io_cq *cic)
3736 {
3737         struct task_struct *tsk = current;
3738         int ioprio_class;
3739
3740         if (!cfq_cfqq_prio_changed(cfqq))
3741                 return;
3742
3743         ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3744         switch (ioprio_class) {
3745         default:
3746                 printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
3747                 /* fall through */
3748         case IOPRIO_CLASS_NONE:
3749                 /*
3750                  * no prio set, inherit CPU scheduling settings
3751                  */
3752                 cfqq->ioprio = task_nice_ioprio(tsk);
3753                 cfqq->ioprio_class = task_nice_ioclass(tsk);
3754                 break;
3755         case IOPRIO_CLASS_RT:
3756                 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3757                 cfqq->ioprio_class = IOPRIO_CLASS_RT;
3758                 break;
3759         case IOPRIO_CLASS_BE:
3760                 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3761                 cfqq->ioprio_class = IOPRIO_CLASS_BE;
3762                 break;
3763         case IOPRIO_CLASS_IDLE:
3764                 cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
3765                 cfqq->ioprio = 7;
3766                 cfq_clear_cfqq_idle_window(cfqq);
3767                 break;
3768         }
3769
3770         /*
3771          * keep track of original prio settings in case we have to temporarily
3772          * elevate the priority of this queue
3773          */
3774         cfqq->org_ioprio = cfqq->ioprio;
3775         cfq_clear_cfqq_prio_changed(cfqq);
3776 }
3777
3778 static void check_ioprio_changed(struct cfq_io_cq *cic, struct bio *bio)
3779 {
3780         int ioprio = cic->icq.ioc->ioprio;
3781         struct cfq_data *cfqd = cic_to_cfqd(cic);
3782         struct cfq_queue *cfqq;
3783
3784         /*
3785          * Check whether ioprio has changed.  The condition may trigger
3786          * spuriously on a newly created cic but there's no harm.
3787          */
3788         if (unlikely(!cfqd) || likely(cic->ioprio == ioprio))
3789                 return;
3790
3791         cfqq = cic_to_cfqq(cic, false);
3792         if (cfqq) {
3793                 cfq_put_queue(cfqq);
3794                 cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic, bio);
3795                 cic_set_cfqq(cic, cfqq, false);
3796         }
3797
3798         cfqq = cic_to_cfqq(cic, true);
3799         if (cfqq)
3800                 cfq_mark_cfqq_prio_changed(cfqq);
3801
3802         cic->ioprio = ioprio;
3803 }
3804
3805 static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3806                           pid_t pid, bool is_sync)
3807 {
3808         RB_CLEAR_NODE(&cfqq->rb_node);
3809         RB_CLEAR_NODE(&cfqq->p_node);
3810         INIT_LIST_HEAD(&cfqq->fifo);
3811
3812         cfqq->ref = 0;
3813         cfqq->cfqd = cfqd;
3814
3815         cfq_mark_cfqq_prio_changed(cfqq);
3816
3817         if (is_sync) {
3818                 if (!cfq_class_idle(cfqq))
3819                         cfq_mark_cfqq_idle_window(cfqq);
3820                 cfq_mark_cfqq_sync(cfqq);
3821         }
3822         cfqq->pid = pid;
3823 }
3824
3825 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3826 static void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3827 {
3828         struct cfq_data *cfqd = cic_to_cfqd(cic);
3829         struct cfq_queue *cfqq;
3830         uint64_t serial_nr;
3831
3832         rcu_read_lock();
3833         serial_nr = bio_blkcg(bio)->css.serial_nr;
3834         rcu_read_unlock();
3835
3836         /*
3837          * Check whether blkcg has changed.  The condition may trigger
3838          * spuriously on a newly created cic but there's no harm.
3839          */
3840         if (unlikely(!cfqd) || likely(cic->blkcg_serial_nr == serial_nr))
3841                 return;
3842
3843         /*
3844          * Drop reference to queues.  New queues will be assigned in new
3845          * group upon arrival of fresh requests.
3846          */
3847         cfqq = cic_to_cfqq(cic, false);
3848         if (cfqq) {
3849                 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3850                 cic_set_cfqq(cic, NULL, false);
3851                 cfq_put_queue(cfqq);
3852         }
3853
3854         cfqq = cic_to_cfqq(cic, true);
3855         if (cfqq) {
3856                 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3857                 cic_set_cfqq(cic, NULL, true);
3858                 cfq_put_queue(cfqq);
3859         }
3860
3861         cic->blkcg_serial_nr = serial_nr;
3862 }
3863 #else
3864 static inline void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio) { }
3865 #endif  /* CONFIG_CFQ_GROUP_IOSCHED */
3866
3867 static struct cfq_queue **
3868 cfq_async_queue_prio(struct cfq_group *cfqg, int ioprio_class, int ioprio)
3869 {
3870         switch (ioprio_class) {
3871         case IOPRIO_CLASS_RT:
3872                 return &cfqg->async_cfqq[0][ioprio];
3873         case IOPRIO_CLASS_NONE:
3874                 ioprio = IOPRIO_NORM;
3875                 /* fall through */
3876         case IOPRIO_CLASS_BE:
3877                 return &cfqg->async_cfqq[1][ioprio];
3878         case IOPRIO_CLASS_IDLE:
3879                 return &cfqg->async_idle_cfqq;
3880         default:
3881                 BUG();
3882         }
3883 }
3884
3885 static struct cfq_queue *
3886 cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct cfq_io_cq *cic,
3887               struct bio *bio)
3888 {
3889         int ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3890         int ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3891         struct cfq_queue **async_cfqq = NULL;
3892         struct cfq_queue *cfqq;
3893         struct cfq_group *cfqg;
3894
3895         rcu_read_lock();
3896         cfqg = cfq_lookup_cfqg(cfqd, bio_blkcg(bio));
3897         if (!cfqg) {
3898                 cfqq = &cfqd->oom_cfqq;
3899                 goto out;
3900         }
3901
3902         if (!is_sync) {
3903                 if (!ioprio_valid(cic->ioprio)) {
3904                         struct task_struct *tsk = current;
3905                         ioprio = task_nice_ioprio(tsk);
3906                         ioprio_class = task_nice_ioclass(tsk);
3907                 }
3908                 async_cfqq = cfq_async_queue_prio(cfqg, ioprio_class, ioprio);
3909                 cfqq = *async_cfqq;
3910                 if (cfqq)
3911                         goto out;
3912         }
3913
3914         cfqq = kmem_cache_alloc_node(cfq_pool,
3915                                      GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
3916                                      cfqd->queue->node);
3917         if (!cfqq) {
3918                 cfqq = &cfqd->oom_cfqq;
3919                 goto out;
3920         }
3921
3922         /* cfq_init_cfqq() assumes cfqq->ioprio_class is initialized. */
3923         cfqq->ioprio_class = IOPRIO_CLASS_NONE;
3924         cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
3925         cfq_init_prio_data(cfqq, cic);
3926         cfq_link_cfqq_cfqg(cfqq, cfqg);
3927         cfq_log_cfqq(cfqd, cfqq, "alloced");
3928
3929         if (async_cfqq) {
3930                 /* a new async queue is created, pin and remember */
3931                 cfqq->ref++;
3932                 *async_cfqq = cfqq;
3933         }
3934 out:
3935         cfqq->ref++;
3936         rcu_read_unlock();
3937         return cfqq;
3938 }
3939
3940 static void
3941 __cfq_update_io_thinktime(struct cfq_ttime *ttime, u64 slice_idle)
3942 {
3943         u64 elapsed = ktime_get_ns() - ttime->last_end_request;
3944         elapsed = min(elapsed, 2UL * slice_idle);
3945
3946         ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
3947         ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed,  8);
3948         ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
3949                                      ttime->ttime_samples);
3950 }
3951
3952 static void
3953 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3954                         struct cfq_io_cq *cic)
3955 {
3956         if (cfq_cfqq_sync(cfqq)) {
3957                 __cfq_update_io_thinktime(&cic->ttime, cfqd->cfq_slice_idle);
3958                 __cfq_update_io_thinktime(&cfqq->service_tree->ttime,
3959                         cfqd->cfq_slice_idle);
3960         }
3961 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3962         __cfq_update_io_thinktime(&cfqq->cfqg->ttime, get_group_idle(cfqd));
3963 #endif
3964 }
3965
3966 static void
3967 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3968                        struct request *rq)
3969 {
3970         sector_t sdist = 0;
3971         sector_t n_sec = blk_rq_sectors(rq);
3972         if (cfqq->last_request_pos) {
3973                 if (cfqq->last_request_pos < blk_rq_pos(rq))
3974                         sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
3975                 else
3976                         sdist = cfqq->last_request_pos - blk_rq_pos(rq);
3977         }
3978
3979         cfqq->seek_history <<= 1;
3980         if (blk_queue_nonrot(cfqd->queue))
3981                 cfqq->seek_history |= (n_sec < CFQQ_SECT_THR_NONROT);
3982         else
3983                 cfqq->seek_history |= (sdist > CFQQ_SEEK_THR);
3984 }
3985
3986 /*
3987  * Disable idle window if the process thinks too long or seeks so much that
3988  * it doesn't matter
3989  */
3990 static void
3991 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3992                        struct cfq_io_cq *cic)
3993 {
3994         int old_idle, enable_idle;
3995
3996         /*
3997          * Don't idle for async or idle io prio class
3998          */
3999         if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
4000                 return;
4001
4002         enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
4003
4004         if (cfqq->queued[0] + cfqq->queued[1] >= 4)
4005                 cfq_mark_cfqq_deep(cfqq);
4006
4007         if (cfqq->next_rq && (cfqq->next_rq->cmd_flags & REQ_NOIDLE))
4008                 enable_idle = 0;
4009         else if (!atomic_read(&cic->icq.ioc->active_ref) ||
4010                  !cfqd->cfq_slice_idle ||
4011                  (!cfq_cfqq_deep(cfqq) && CFQQ_SEEKY(cfqq)))
4012                 enable_idle = 0;
4013         else if (sample_valid(cic->ttime.ttime_samples)) {
4014                 if (cic->ttime.ttime_mean > cfqd->cfq_slice_idle)
4015                         enable_idle = 0;
4016                 else
4017                         enable_idle = 1;
4018         }
4019
4020         if (old_idle != enable_idle) {
4021                 cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
4022                 if (enable_idle)
4023                         cfq_mark_cfqq_idle_window(cfqq);
4024                 else
4025                         cfq_clear_cfqq_idle_window(cfqq);
4026         }
4027 }
4028
4029 /*
4030  * Check if new_cfqq should preempt the currently active queue. Return 0 for
4031  * no or if we aren't sure, a 1 will cause a preempt.
4032  */
4033 static bool
4034 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
4035                    struct request *rq)
4036 {
4037         struct cfq_queue *cfqq;
4038
4039         cfqq = cfqd->active_queue;
4040         if (!cfqq)
4041                 return false;
4042
4043         if (cfq_class_idle(new_cfqq))
4044                 return false;
4045
4046         if (cfq_class_idle(cfqq))
4047                 return true;
4048
4049         /*
4050          * Don't allow a non-RT request to preempt an ongoing RT cfqq timeslice.
4051          */
4052         if (cfq_class_rt(cfqq) && !cfq_class_rt(new_cfqq))
4053                 return false;
4054
4055         /*
4056          * if the new request is sync, but the currently running queue is
4057          * not, let the sync request have priority.
4058          */
4059         if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq) && !cfq_cfqq_must_dispatch(cfqq))
4060                 return true;
4061
4062         /*
4063          * Treat ancestors of current cgroup the same way as current cgroup.
4064          * For anybody else we disallow preemption to guarantee service
4065          * fairness among cgroups.
4066          */
4067         if (!cfqg_is_descendant(cfqq->cfqg, new_cfqq->cfqg))
4068                 return false;
4069
4070         if (cfq_slice_used(cfqq))
4071                 return true;
4072
4073         /*
4074          * Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
4075          */
4076         if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
4077                 return true;
4078
4079         WARN_ON_ONCE(cfqq->ioprio_class != new_cfqq->ioprio_class);
4080         /* Allow preemption only if we are idling on sync-noidle tree */
4081         if (cfqd->serving_wl_type == SYNC_NOIDLE_WORKLOAD &&
4082             cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
4083             RB_EMPTY_ROOT(&cfqq->sort_list))
4084                 return true;
4085
4086         /*
4087          * So both queues are sync. Let the new request get disk time if
4088          * it's a metadata request and the current queue is doing regular IO.
4089          */
4090         if ((rq->cmd_flags & REQ_PRIO) && !cfqq->prio_pending)
4091                 return true;
4092
4093         /* An idle queue should not be idle now for some reason */
4094         if (RB_EMPTY_ROOT(&cfqq->sort_list) && !cfq_should_idle(cfqd, cfqq))
4095                 return true;
4096
4097         if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
4098                 return false;
4099
4100         /*
4101          * if this request is as-good as one we would expect from the
4102          * current cfqq, let it preempt
4103          */
4104         if (cfq_rq_close(cfqd, cfqq, rq))
4105                 return true;
4106
4107         return false;
4108 }
4109
4110 /*
4111  * cfqq preempts the active queue. if we allowed preempt with no slice left,
4112  * let it have half of its nominal slice.
4113  */
4114 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4115 {
4116         enum wl_type_t old_type = cfqq_type(cfqd->active_queue);
4117
4118         cfq_log_cfqq(cfqd, cfqq, "preempt");
4119         cfq_slice_expired(cfqd, 1);
4120
4121         /*
4122          * workload type is changed, don't save slice, otherwise preempt
4123          * doesn't happen
4124          */
4125         if (old_type != cfqq_type(cfqq))
4126                 cfqq->cfqg->saved_wl_slice = 0;
4127
4128         /*
4129          * Put the new queue at the front of the of the current list,
4130          * so we know that it will be selected next.
4131          */
4132         BUG_ON(!cfq_cfqq_on_rr(cfqq));
4133
4134         cfq_service_tree_add(cfqd, cfqq, 1);
4135
4136         cfqq->slice_end = 0;
4137         cfq_mark_cfqq_slice_new(cfqq);
4138 }
4139
4140 /*
4141  * Called when a new fs request (rq) is added (to cfqq). Check if there's
4142  * something we should do about it
4143  */
4144 static void
4145 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
4146                 struct request *rq)
4147 {
4148         struct cfq_io_cq *cic = RQ_CIC(rq);
4149
4150         cfqd->rq_queued++;
4151         if (rq->cmd_flags & REQ_PRIO)
4152                 cfqq->prio_pending++;
4153
4154         cfq_update_io_thinktime(cfqd, cfqq, cic);
4155         cfq_update_io_seektime(cfqd, cfqq, rq);
4156         cfq_update_idle_window(cfqd, cfqq, cic);
4157
4158         cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4159
4160         if (cfqq == cfqd->active_queue) {
4161                 /*
4162                  * Remember that we saw a request from this process, but
4163                  * don't start queuing just yet. Otherwise we risk seeing lots
4164                  * of tiny requests, because we disrupt the normal plugging
4165                  * and merging. If the request is already larger than a single
4166                  * page, let it rip immediately. For that case we assume that
4167                  * merging is already done. Ditto for a busy system that
4168                  * has other work pending, don't risk delaying until the
4169                  * idle timer unplug to continue working.
4170                  */
4171                 if (cfq_cfqq_wait_request(cfqq)) {
4172                         if (blk_rq_bytes(rq) > PAGE_CACHE_SIZE ||
4173                             cfqd->busy_queues > 1) {
4174                                 cfq_del_timer(cfqd, cfqq);
4175                                 cfq_clear_cfqq_wait_request(cfqq);
4176                                 __blk_run_queue(cfqd->queue);
4177                         } else {
4178                                 cfqg_stats_update_idle_time(cfqq->cfqg);
4179                                 cfq_mark_cfqq_must_dispatch(cfqq);
4180                         }
4181                 }
4182         } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
4183                 /*
4184                  * not the active queue - expire current slice if it is
4185                  * idle and has expired it's mean thinktime or this new queue
4186                  * has some old slice time left and is of higher priority or
4187                  * this new queue is RT and the current one is BE
4188                  */
4189                 cfq_preempt_queue(cfqd, cfqq);
4190                 __blk_run_queue(cfqd->queue);
4191         }
4192 }
4193
4194 static void cfq_insert_request(struct request_queue *q, struct request *rq)
4195 {
4196         struct cfq_data *cfqd = q->elevator->elevator_data;
4197         struct cfq_queue *cfqq = RQ_CFQQ(rq);
4198
4199         cfq_log_cfqq(cfqd, cfqq, "insert_request");
4200         cfq_init_prio_data(cfqq, RQ_CIC(rq));
4201
4202         rq->fifo_time = ktime_get_ns() + cfqd->cfq_fifo_expire[rq_is_sync(rq)];
4203         list_add_tail(&rq->queuelist, &cfqq->fifo);
4204         cfq_add_rq_rb(rq);
4205         cfqg_stats_update_io_add(RQ_CFQG(rq), cfqd->serving_group,
4206                                  rq->cmd_flags);
4207         cfq_rq_enqueued(cfqd, cfqq, rq);
4208 }
4209
4210 /*
4211  * Update hw_tag based on peak queue depth over 50 samples under
4212  * sufficient load.
4213  */
4214 static void cfq_update_hw_tag(struct cfq_data *cfqd)
4215 {
4216         struct cfq_queue *cfqq = cfqd->active_queue;
4217
4218         if (cfqd->rq_in_driver > cfqd->hw_tag_est_depth)
4219                 cfqd->hw_tag_est_depth = cfqd->rq_in_driver;
4220
4221         if (cfqd->hw_tag == 1)
4222                 return;
4223
4224         if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
4225             cfqd->rq_in_driver <= CFQ_HW_QUEUE_MIN)
4226                 return;
4227
4228         /*
4229          * If active queue hasn't enough requests and can idle, cfq might not
4230          * dispatch sufficient requests to hardware. Don't zero hw_tag in this
4231          * case
4232          */
4233         if (cfqq && cfq_cfqq_idle_window(cfqq) &&
4234             cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
4235             CFQ_HW_QUEUE_MIN && cfqd->rq_in_driver < CFQ_HW_QUEUE_MIN)
4236                 return;
4237
4238         if (cfqd->hw_tag_samples++ < 50)
4239                 return;
4240
4241         if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
4242                 cfqd->hw_tag = 1;
4243         else
4244                 cfqd->hw_tag = 0;
4245 }
4246
4247 static bool cfq_should_wait_busy(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4248 {
4249         struct cfq_io_cq *cic = cfqd->active_cic;
4250         u64 now = ktime_get_ns();
4251
4252         /* If the queue already has requests, don't wait */
4253         if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4254                 return false;
4255
4256         /* If there are other queues in the group, don't wait */
4257         if (cfqq->cfqg->nr_cfqq > 1)
4258                 return false;
4259
4260         /* the only queue in the group, but think time is big */
4261         if (cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true))
4262                 return false;
4263
4264         if (cfq_slice_used(cfqq))
4265                 return true;
4266
4267         /* if slice left is less than think time, wait busy */
4268         if (cic && sample_valid(cic->ttime.ttime_samples)
4269             && (cfqq->slice_end - now < cic->ttime.ttime_mean))
4270                 return true;
4271
4272         /*
4273          * If think times is less than a jiffy than ttime_mean=0 and above
4274          * will not be true. It might happen that slice has not expired yet
4275          * but will expire soon (4-5 ns) during select_queue(). To cover the
4276          * case where think time is less than a jiffy, mark the queue wait
4277          * busy if only 1 jiffy is left in the slice.
4278          */
4279         if (cfqq->slice_end - now <= jiffies_to_nsecs(1))
4280                 return true;
4281
4282         return false;
4283 }
4284
4285 static void cfq_completed_request(struct request_queue *q, struct request *rq)
4286 {
4287         struct cfq_queue *cfqq = RQ_CFQQ(rq);
4288         struct cfq_data *cfqd = cfqq->cfqd;
4289         const int sync = rq_is_sync(rq);
4290         u64 now = ktime_get_ns();
4291
4292         cfq_log_cfqq(cfqd, cfqq, "complete rqnoidle %d",
4293                      !!(rq->cmd_flags & REQ_NOIDLE));
4294
4295         cfq_update_hw_tag(cfqd);
4296
4297         WARN_ON(!cfqd->rq_in_driver);
4298         WARN_ON(!cfqq->dispatched);
4299         cfqd->rq_in_driver--;
4300         cfqq->dispatched--;
4301         (RQ_CFQG(rq))->dispatched--;
4302         cfqg_stats_update_completion(cfqq->cfqg, rq_start_time_ns(rq),
4303                                      rq_io_start_time_ns(rq), rq->cmd_flags);
4304
4305         cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]--;
4306
4307         if (sync) {
4308                 struct cfq_rb_root *st;
4309
4310                 RQ_CIC(rq)->ttime.last_end_request = now;
4311
4312                 if (cfq_cfqq_on_rr(cfqq))
4313                         st = cfqq->service_tree;
4314                 else
4315                         st = st_for(cfqq->cfqg, cfqq_class(cfqq),
4316                                         cfqq_type(cfqq));
4317
4318                 st->ttime.last_end_request = now;
4319                 /*
4320                  * We have to do this check in jiffies since start_time is in
4321                  * jiffies and it is not trivial to convert to ns. If
4322                  * cfq_fifo_expire[1] ever comes close to 1 jiffie, this test
4323                  * will become problematic but so far we are fine (the default
4324                  * is 128 ms).
4325                  */
4326                 if (!time_after(rq->start_time +
4327                                   nsecs_to_jiffies(cfqd->cfq_fifo_expire[1]),
4328                                 jiffies))
4329                         cfqd->last_delayed_sync = now;
4330         }
4331
4332 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4333         cfqq->cfqg->ttime.last_end_request = now;
4334 #endif
4335
4336         /*
4337          * If this is the active queue, check if it needs to be expired,
4338          * or if we want to idle in case it has no pending requests.
4339          */
4340         if (cfqd->active_queue == cfqq) {
4341                 const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
4342
4343                 if (cfq_cfqq_slice_new(cfqq)) {
4344                         cfq_set_prio_slice(cfqd, cfqq);
4345                         cfq_clear_cfqq_slice_new(cfqq);
4346                 }
4347
4348                 /*
4349                  * Should we wait for next request to come in before we expire
4350                  * the queue.
4351                  */
4352                 if (cfq_should_wait_busy(cfqd, cfqq)) {
4353                         u64 extend_sl = cfqd->cfq_slice_idle;
4354                         if (!cfqd->cfq_slice_idle)
4355                                 extend_sl = get_group_idle(cfqd);
4356                         cfqq->slice_end = now + extend_sl;
4357                         cfq_mark_cfqq_wait_busy(cfqq);
4358                         cfq_log_cfqq(cfqd, cfqq, "will busy wait");
4359                 }
4360
4361                 /*
4362                  * Idling is not enabled on:
4363                  * - expired queues
4364                  * - idle-priority queues
4365                  * - async queues
4366                  * - queues with still some requests queued
4367                  * - when there is a close cooperator
4368                  */
4369                 if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
4370                         cfq_slice_expired(cfqd, 1);
4371                 else if (sync && cfqq_empty &&
4372                          !cfq_close_cooperator(cfqd, cfqq)) {
4373                         cfq_arm_slice_timer(cfqd);
4374                 }
4375         }
4376
4377         if (!cfqd->rq_in_driver)
4378                 cfq_schedule_dispatch(cfqd);
4379 }
4380
4381 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
4382 {
4383         if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
4384                 cfq_mark_cfqq_must_alloc_slice(cfqq);
4385                 return ELV_MQUEUE_MUST;
4386         }
4387
4388         return ELV_MQUEUE_MAY;
4389 }
4390
4391 static int cfq_may_queue(struct request_queue *q, int rw)
4392 {
4393         struct cfq_data *cfqd = q->elevator->elevator_data;
4394         struct task_struct *tsk = current;
4395         struct cfq_io_cq *cic;
4396         struct cfq_queue *cfqq;
4397
4398         /*
4399          * don't force setup of a queue from here, as a call to may_queue
4400          * does not necessarily imply that a request actually will be queued.
4401          * so just lookup a possibly existing queue, or return 'may queue'
4402          * if that fails
4403          */
4404         cic = cfq_cic_lookup(cfqd, tsk->io_context);
4405         if (!cic)
4406                 return ELV_MQUEUE_MAY;
4407
4408         cfqq = cic_to_cfqq(cic, rw_is_sync(rw));
4409         if (cfqq) {
4410                 cfq_init_prio_data(cfqq, cic);
4411
4412                 return __cfq_may_queue(cfqq);
4413         }
4414
4415         return ELV_MQUEUE_MAY;
4416 }
4417
4418 /*
4419  * queue lock held here
4420  */
4421 static void cfq_put_request(struct request *rq)
4422 {
4423         struct cfq_queue *cfqq = RQ_CFQQ(rq);
4424
4425         if (cfqq) {
4426                 const int rw = rq_data_dir(rq);
4427
4428                 BUG_ON(!cfqq->allocated[rw]);
4429                 cfqq->allocated[rw]--;
4430
4431                 /* Put down rq reference on cfqg */
4432                 cfqg_put(RQ_CFQG(rq));
4433                 rq->elv.priv[0] = NULL;
4434                 rq->elv.priv[1] = NULL;
4435
4436                 cfq_put_queue(cfqq);
4437         }
4438 }
4439
4440 static struct cfq_queue *
4441 cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_cq *cic,
4442                 struct cfq_queue *cfqq)
4443 {
4444         cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
4445         cic_set_cfqq(cic, cfqq->new_cfqq, 1);
4446         cfq_mark_cfqq_coop(cfqq->new_cfqq);
4447         cfq_put_queue(cfqq);
4448         return cic_to_cfqq(cic, 1);
4449 }
4450
4451 /*
4452  * Returns NULL if a new cfqq should be allocated, or the old cfqq if this
4453  * was the last process referring to said cfqq.
4454  */
4455 static struct cfq_queue *
4456 split_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq)
4457 {
4458         if (cfqq_process_refs(cfqq) == 1) {
4459                 cfqq->pid = current->pid;
4460                 cfq_clear_cfqq_coop(cfqq);
4461                 cfq_clear_cfqq_split_coop(cfqq);
4462                 return cfqq;
4463         }
4464
4465         cic_set_cfqq(cic, NULL, 1);
4466
4467         cfq_put_cooperator(cfqq);
4468
4469         cfq_put_queue(cfqq);
4470         return NULL;
4471 }
4472 /*
4473  * Allocate cfq data structures associated with this request.
4474  */
4475 static int
4476 cfq_set_request(struct request_queue *q, struct request *rq, struct bio *bio,
4477                 gfp_t gfp_mask)
4478 {
4479         struct cfq_data *cfqd = q->elevator->elevator_data;
4480         struct cfq_io_cq *cic = icq_to_cic(rq->elv.icq);
4481         const int rw = rq_data_dir(rq);
4482         const bool is_sync = rq_is_sync(rq);
4483         struct cfq_queue *cfqq;
4484
4485         spin_lock_irq(q->queue_lock);
4486
4487         check_ioprio_changed(cic, bio);
4488         check_blkcg_changed(cic, bio);
4489 new_queue:
4490         cfqq = cic_to_cfqq(cic, is_sync);
4491         if (!cfqq || cfqq == &cfqd->oom_cfqq) {
4492                 if (cfqq)
4493                         cfq_put_queue(cfqq);
4494                 cfqq = cfq_get_queue(cfqd, is_sync, cic, bio);
4495                 cic_set_cfqq(cic, cfqq, is_sync);
4496         } else {
4497                 /*
4498                  * If the queue was seeky for too long, break it apart.
4499                  */
4500                 if (cfq_cfqq_coop(cfqq) && cfq_cfqq_split_coop(cfqq)) {
4501                         cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
4502                         cfqq = split_cfqq(cic, cfqq);
4503                         if (!cfqq)
4504                                 goto new_queue;
4505                 }
4506
4507                 /*
4508                  * Check to see if this queue is scheduled to merge with
4509                  * another, closely cooperating queue.  The merging of
4510                  * queues happens here as it must be done in process context.
4511                  * The reference on new_cfqq was taken in merge_cfqqs.
4512                  */
4513                 if (cfqq->new_cfqq)
4514                         cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
4515         }
4516
4517         cfqq->allocated[rw]++;
4518
4519         cfqq->ref++;
4520         cfqg_get(cfqq->cfqg);
4521         rq->elv.priv[0] = cfqq;
4522         rq->elv.priv[1] = cfqq->cfqg;
4523         spin_unlock_irq(q->queue_lock);
4524         return 0;
4525 }
4526
4527 static void cfq_kick_queue(struct work_struct *work)
4528 {
4529         struct cfq_data *cfqd =
4530                 container_of(work, struct cfq_data, unplug_work);
4531         struct request_queue *q = cfqd->queue;
4532
4533         spin_lock_irq(q->queue_lock);
4534         __blk_run_queue(cfqd->queue);
4535         spin_unlock_irq(q->queue_lock);
4536 }
4537
4538 /*
4539  * Timer running if the active_queue is currently idling inside its time slice
4540  */
4541 static enum hrtimer_restart cfq_idle_slice_timer(struct hrtimer *timer)
4542 {
4543         struct cfq_data *cfqd = container_of(timer, struct cfq_data,
4544                                              idle_slice_timer);
4545         struct cfq_queue *cfqq;
4546         unsigned long flags;
4547         int timed_out = 1;
4548
4549         cfq_log(cfqd, "idle timer fired");
4550
4551         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
4552
4553         cfqq = cfqd->active_queue;
4554         if (cfqq) {
4555                 timed_out = 0;
4556
4557                 /*
4558                  * We saw a request before the queue expired, let it through
4559                  */
4560                 if (cfq_cfqq_must_dispatch(cfqq))
4561                         goto out_kick;
4562
4563                 /*
4564                  * expired
4565                  */
4566                 if (cfq_slice_used(cfqq))
4567                         goto expire;
4568
4569                 /*
4570                  * only expire and reinvoke request handler, if there are
4571                  * other queues with pending requests
4572                  */
4573                 if (!cfqd->busy_queues)
4574                         goto out_cont;
4575
4576                 /*
4577                  * not expired and it has a request pending, let it dispatch
4578                  */
4579                 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4580                         goto out_kick;
4581
4582                 /*
4583                  * Queue depth flag is reset only when the idle didn't succeed
4584                  */
4585                 cfq_clear_cfqq_deep(cfqq);
4586         }
4587 expire:
4588         cfq_slice_expired(cfqd, timed_out);
4589 out_kick:
4590         cfq_schedule_dispatch(cfqd);
4591 out_cont:
4592         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
4593         return HRTIMER_NORESTART;
4594 }
4595
4596 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
4597 {
4598         hrtimer_cancel(&cfqd->idle_slice_timer);
4599         cancel_work_sync(&cfqd->unplug_work);
4600 }
4601
4602 static void cfq_exit_queue(struct elevator_queue *e)
4603 {
4604         struct cfq_data *cfqd = e->elevator_data;
4605         struct request_queue *q = cfqd->queue;
4606
4607         cfq_shutdown_timer_wq(cfqd);
4608
4609         spin_lock_irq(q->queue_lock);
4610
4611         if (cfqd->active_queue)
4612                 __cfq_slice_expired(cfqd, cfqd->active_queue, 0);
4613
4614         spin_unlock_irq(q->queue_lock);
4615
4616         cfq_shutdown_timer_wq(cfqd);
4617
4618 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4619         blkcg_deactivate_policy(q, &blkcg_policy_cfq);
4620 #else
4621         kfree(cfqd->root_group);
4622 #endif
4623         kfree(cfqd);
4624 }
4625
4626 static int cfq_init_queue(struct request_queue *q, struct elevator_type *e)
4627 {
4628         struct cfq_data *cfqd;
4629         struct blkcg_gq *blkg __maybe_unused;
4630         int i, ret;
4631         struct elevator_queue *eq;
4632
4633         eq = elevator_alloc(q, e);
4634         if (!eq)
4635                 return -ENOMEM;
4636
4637         cfqd = kzalloc_node(sizeof(*cfqd), GFP_KERNEL, q->node);
4638         if (!cfqd) {
4639                 kobject_put(&eq->kobj);
4640                 return -ENOMEM;
4641         }
4642         eq->elevator_data = cfqd;
4643
4644         cfqd->queue = q;
4645         spin_lock_irq(q->queue_lock);
4646         q->elevator = eq;
4647         spin_unlock_irq(q->queue_lock);
4648
4649         /* Init root service tree */
4650         cfqd->grp_service_tree = CFQ_RB_ROOT;
4651
4652         /* Init root group and prefer root group over other groups by default */
4653 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4654         ret = blkcg_activate_policy(q, &blkcg_policy_cfq);
4655         if (ret)
4656                 goto out_free;
4657
4658         cfqd->root_group = blkg_to_cfqg(q->root_blkg);
4659 #else
4660         ret = -ENOMEM;
4661         cfqd->root_group = kzalloc_node(sizeof(*cfqd->root_group),
4662                                         GFP_KERNEL, cfqd->queue->node);
4663         if (!cfqd->root_group)
4664                 goto out_free;
4665
4666         cfq_init_cfqg_base(cfqd->root_group);
4667         cfqd->root_group->weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4668         cfqd->root_group->leaf_weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4669 #endif
4670
4671         /*
4672          * Not strictly needed (since RB_ROOT just clears the node and we
4673          * zeroed cfqd on alloc), but better be safe in case someone decides
4674          * to add magic to the rb code
4675          */
4676         for (i = 0; i < CFQ_PRIO_LISTS; i++)
4677                 cfqd->prio_trees[i] = RB_ROOT;
4678
4679         /*
4680          * Our fallback cfqq if cfq_get_queue() runs into OOM issues.
4681          * Grab a permanent reference to it, so that the normal code flow
4682          * will not attempt to free it.  oom_cfqq is linked to root_group
4683          * but shouldn't hold a reference as it'll never be unlinked.  Lose
4684          * the reference from linking right away.
4685          */
4686         cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
4687         cfqd->oom_cfqq.ref++;
4688
4689         spin_lock_irq(q->queue_lock);
4690         cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, cfqd->root_group);
4691         cfqg_put(cfqd->root_group);
4692         spin_unlock_irq(q->queue_lock);
4693
4694         hrtimer_init(&cfqd->idle_slice_timer, CLOCK_MONOTONIC,
4695                      HRTIMER_MODE_REL);
4696         cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
4697
4698         INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
4699
4700         cfqd->cfq_quantum = cfq_quantum;
4701         cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
4702         cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
4703         cfqd->cfq_back_max = cfq_back_max;
4704         cfqd->cfq_back_penalty = cfq_back_penalty;
4705         cfqd->cfq_slice[0] = cfq_slice_async;
4706         cfqd->cfq_slice[1] = cfq_slice_sync;
4707         cfqd->cfq_target_latency = cfq_target_latency;
4708         cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
4709         cfqd->cfq_slice_idle = cfq_slice_idle;
4710         cfqd->cfq_group_idle = cfq_group_idle;
4711         cfqd->cfq_latency = 1;
4712         cfqd->hw_tag = -1;
4713         /*
4714          * we optimistically start assuming sync ops weren't delayed in last
4715          * second, in order to have larger depth for async operations.
4716          */
4717         cfqd->last_delayed_sync = ktime_get_ns() - NSEC_PER_SEC;
4718         return 0;
4719
4720 out_free:
4721         kfree(cfqd);
4722         kobject_put(&eq->kobj);
4723         return ret;
4724 }
4725
4726 static void cfq_registered_queue(struct request_queue *q)
4727 {
4728         struct elevator_queue *e = q->elevator;
4729         struct cfq_data *cfqd = e->elevator_data;
4730
4731         /*
4732          * Default to IOPS mode with no idling for SSDs
4733          */
4734         if (blk_queue_nonrot(q))
4735                 cfqd->cfq_slice_idle = 0;
4736 }
4737
4738 /*
4739  * sysfs parts below -->
4740  */
4741 static ssize_t
4742 cfq_var_show(unsigned int var, char *page)
4743 {
4744         return sprintf(page, "%u\n", var);
4745 }
4746
4747 static ssize_t
4748 cfq_var_store(unsigned int *var, const char *page, size_t count)
4749 {
4750         char *p = (char *) page;
4751
4752         *var = simple_strtoul(p, &p, 10);
4753         return count;
4754 }
4755
4756 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV)                            \
4757 static ssize_t __FUNC(struct elevator_queue *e, char *page)             \
4758 {                                                                       \
4759         struct cfq_data *cfqd = e->elevator_data;                       \
4760         u64 __data = __VAR;                                             \
4761         if (__CONV)                                                     \
4762                 __data = div_u64(__data, NSEC_PER_MSEC);                        \
4763         return cfq_var_show(__data, (page));                            \
4764 }
4765 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
4766 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
4767 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
4768 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
4769 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
4770 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
4771 SHOW_FUNCTION(cfq_group_idle_show, cfqd->cfq_group_idle, 1);
4772 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
4773 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
4774 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
4775 SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
4776 SHOW_FUNCTION(cfq_target_latency_show, cfqd->cfq_target_latency, 1);
4777 #undef SHOW_FUNCTION
4778
4779 #define USEC_SHOW_FUNCTION(__FUNC, __VAR)                               \
4780 static ssize_t __FUNC(struct elevator_queue *e, char *page)             \
4781 {                                                                       \
4782         struct cfq_data *cfqd = e->elevator_data;                       \
4783         u64 __data = __VAR;                                             \
4784         __data = div_u64(__data, NSEC_PER_USEC);                        \
4785         return cfq_var_show(__data, (page));                            \
4786 }
4787 USEC_SHOW_FUNCTION(cfq_slice_idle_us_show, cfqd->cfq_slice_idle);
4788 USEC_SHOW_FUNCTION(cfq_group_idle_us_show, cfqd->cfq_group_idle);
4789 USEC_SHOW_FUNCTION(cfq_slice_sync_us_show, cfqd->cfq_slice[1]);
4790 USEC_SHOW_FUNCTION(cfq_slice_async_us_show, cfqd->cfq_slice[0]);
4791 USEC_SHOW_FUNCTION(cfq_target_latency_us_show, cfqd->cfq_target_latency);
4792 #undef USEC_SHOW_FUNCTION
4793
4794 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV)                 \
4795 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4796 {                                                                       \
4797         struct cfq_data *cfqd = e->elevator_data;                       \
4798         unsigned int __data, __min = (MIN), __max = (MAX);              \
4799         int ret = cfq_var_store(&__data, (page), count);                \
4800         if (__data < __min)                                             \
4801                 __data = __min;                                         \
4802         else if (__data > __max)                                        \
4803                 __data = __max;                                         \
4804         if (__CONV)                                                     \
4805                 *(__PTR) = (u64)__data * NSEC_PER_MSEC;                 \
4806         else                                                            \
4807                 *(__PTR) = __data;                                      \
4808         return ret;                                                     \
4809 }
4810 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
4811 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
4812                 UINT_MAX, 1);
4813 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
4814                 UINT_MAX, 1);
4815 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
4816 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
4817                 UINT_MAX, 0);
4818 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
4819 STORE_FUNCTION(cfq_group_idle_store, &cfqd->cfq_group_idle, 0, UINT_MAX, 1);
4820 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
4821 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
4822 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
4823                 UINT_MAX, 0);
4824 STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
4825 STORE_FUNCTION(cfq_target_latency_store, &cfqd->cfq_target_latency, 1, UINT_MAX, 1);
4826 #undef STORE_FUNCTION
4827
4828 #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX)                    \
4829 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4830 {                                                                       \
4831         struct cfq_data *cfqd = e->elevator_data;                       \
4832         unsigned int __data, __min = (MIN), __max = (MAX);              \
4833         int ret = cfq_var_store(&__data, (page), count);                \
4834         if (__data < __min)                                             \
4835                 __data = __min;                                         \
4836         else if (__data > __max)                                        \
4837                 __data = __max;                                         \
4838         *(__PTR) = (u64)__data * NSEC_PER_USEC;                         \
4839         return ret;                                                     \
4840 }
4841 USEC_STORE_FUNCTION(cfq_slice_idle_us_store, &cfqd->cfq_slice_idle, 0, UINT_MAX);
4842 USEC_STORE_FUNCTION(cfq_group_idle_us_store, &cfqd->cfq_group_idle, 0, UINT_MAX);
4843 USEC_STORE_FUNCTION(cfq_slice_sync_us_store, &cfqd->cfq_slice[1], 1, UINT_MAX);
4844 USEC_STORE_FUNCTION(cfq_slice_async_us_store, &cfqd->cfq_slice[0], 1, UINT_MAX);
4845 USEC_STORE_FUNCTION(cfq_target_latency_us_store, &cfqd->cfq_target_latency, 1, UINT_MAX);
4846 #undef USEC_STORE_FUNCTION
4847
4848 #define CFQ_ATTR(name) \
4849         __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
4850
4851 static struct elv_fs_entry cfq_attrs[] = {
4852         CFQ_ATTR(quantum),
4853         CFQ_ATTR(fifo_expire_sync),
4854         CFQ_ATTR(fifo_expire_async),
4855         CFQ_ATTR(back_seek_max),
4856         CFQ_ATTR(back_seek_penalty),
4857         CFQ_ATTR(slice_sync),
4858         CFQ_ATTR(slice_sync_us),
4859         CFQ_ATTR(slice_async),
4860         CFQ_ATTR(slice_async_us),
4861         CFQ_ATTR(slice_async_rq),
4862         CFQ_ATTR(slice_idle),
4863         CFQ_ATTR(slice_idle_us),
4864         CFQ_ATTR(group_idle),
4865         CFQ_ATTR(group_idle_us),
4866         CFQ_ATTR(low_latency),
4867         CFQ_ATTR(target_latency),
4868         CFQ_ATTR(target_latency_us),
4869         __ATTR_NULL
4870 };
4871
4872 static struct elevator_type iosched_cfq = {
4873         .ops = {
4874                 .elevator_merge_fn =            cfq_merge,
4875                 .elevator_merged_fn =           cfq_merged_request,
4876                 .elevator_merge_req_fn =        cfq_merged_requests,
4877                 .elevator_allow_merge_fn =      cfq_allow_merge,
4878                 .elevator_bio_merged_fn =       cfq_bio_merged,
4879                 .elevator_dispatch_fn =         cfq_dispatch_requests,
4880                 .elevator_add_req_fn =          cfq_insert_request,
4881                 .elevator_activate_req_fn =     cfq_activate_request,
4882                 .elevator_deactivate_req_fn =   cfq_deactivate_request,
4883                 .elevator_completed_req_fn =    cfq_completed_request,
4884                 .elevator_former_req_fn =       elv_rb_former_request,
4885                 .elevator_latter_req_fn =       elv_rb_latter_request,
4886                 .elevator_init_icq_fn =         cfq_init_icq,
4887                 .elevator_exit_icq_fn =         cfq_exit_icq,
4888                 .elevator_set_req_fn =          cfq_set_request,
4889                 .elevator_put_req_fn =          cfq_put_request,
4890                 .elevator_may_queue_fn =        cfq_may_queue,
4891                 .elevator_init_fn =             cfq_init_queue,
4892                 .elevator_exit_fn =             cfq_exit_queue,
4893                 .elevator_registered_fn =       cfq_registered_queue,
4894         },
4895         .icq_size       =       sizeof(struct cfq_io_cq),
4896         .icq_align      =       __alignof__(struct cfq_io_cq),
4897         .elevator_attrs =       cfq_attrs,
4898         .elevator_name  =       "cfq",
4899         .elevator_owner =       THIS_MODULE,
4900 };
4901
4902 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4903 static struct blkcg_policy blkcg_policy_cfq = {
4904         .dfl_cftypes            = cfq_blkcg_files,
4905         .legacy_cftypes         = cfq_blkcg_legacy_files,
4906
4907         .cpd_alloc_fn           = cfq_cpd_alloc,
4908         .cpd_init_fn            = cfq_cpd_init,
4909         .cpd_free_fn            = cfq_cpd_free,
4910         .cpd_bind_fn            = cfq_cpd_bind,
4911
4912         .pd_alloc_fn            = cfq_pd_alloc,
4913         .pd_init_fn             = cfq_pd_init,
4914         .pd_offline_fn          = cfq_pd_offline,
4915         .pd_free_fn             = cfq_pd_free,
4916         .pd_reset_stats_fn      = cfq_pd_reset_stats,
4917 };
4918 #endif
4919
4920 static int __init cfq_init(void)
4921 {
4922         int ret;
4923
4924 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4925         ret = blkcg_policy_register(&blkcg_policy_cfq);
4926         if (ret)
4927                 return ret;
4928 #else
4929         cfq_group_idle = 0;
4930 #endif
4931
4932         ret = -ENOMEM;
4933         cfq_pool = KMEM_CACHE(cfq_queue, 0);
4934         if (!cfq_pool)
4935                 goto err_pol_unreg;
4936
4937         ret = elv_register(&iosched_cfq);
4938         if (ret)
4939                 goto err_free_pool;
4940
4941         return 0;
4942
4943 err_free_pool:
4944         kmem_cache_destroy(cfq_pool);
4945 err_pol_unreg:
4946 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4947         blkcg_policy_unregister(&blkcg_policy_cfq);
4948 #endif
4949         return ret;
4950 }
4951
4952 static void __exit cfq_exit(void)
4953 {
4954 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4955         blkcg_policy_unregister(&blkcg_policy_cfq);
4956 #endif
4957         elv_unregister(&iosched_cfq);
4958         kmem_cache_destroy(cfq_pool);
4959 }
4960
4961 module_init(cfq_init);
4962 module_exit(cfq_exit);
4963
4964 MODULE_AUTHOR("Jens Axboe");
4965 MODULE_LICENSE("GPL");
4966 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");