OSDN Git Service

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