OSDN Git Service

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