blkio: Dynamic cfq group creation based on cgroup tasks belongs to
[linux-2.6.git] / block / cfq-iosched.c
1 /*
2  *  CFQ, or complete fairness queueing, disk scheduler.
3  *
4  *  Based on ideas from a previously unfinished io
5  *  scheduler (round robin per-process disk scheduling) and Andrea Arcangeli.
6  *
7  *  Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
8  */
9 #include <linux/module.h>
10 #include <linux/blkdev.h>
11 #include <linux/elevator.h>
12 #include <linux/jiffies.h>
13 #include <linux/rbtree.h>
14 #include <linux/ioprio.h>
15 #include <linux/blktrace_api.h>
16 #include "blk-cgroup.h"
17
18 /*
19  * tunables
20  */
21 /* max queue in one round of service */
22 static const int cfq_quantum = 4;
23 static const int cfq_fifo_expire[2] = { HZ / 4, HZ / 8 };
24 /* maximum backwards seek, in KiB */
25 static const int cfq_back_max = 16 * 1024;
26 /* penalty of a backwards seek */
27 static const int cfq_back_penalty = 2;
28 static const int cfq_slice_sync = HZ / 10;
29 static int cfq_slice_async = HZ / 25;
30 static const int cfq_slice_async_rq = 2;
31 static int cfq_slice_idle = HZ / 125;
32 static const int cfq_target_latency = HZ * 3/10; /* 300 ms */
33 static const int cfq_hist_divisor = 4;
34
35 /*
36  * offset from end of service tree
37  */
38 #define CFQ_IDLE_DELAY          (HZ / 5)
39
40 /*
41  * below this threshold, we consider thinktime immediate
42  */
43 #define CFQ_MIN_TT              (2)
44
45 /*
46  * Allow merged cfqqs to perform this amount of seeky I/O before
47  * deciding to break the queues up again.
48  */
49 #define CFQQ_COOP_TOUT          (HZ)
50
51 #define CFQ_SLICE_SCALE         (5)
52 #define CFQ_HW_QUEUE_MIN        (5)
53 #define CFQ_SERVICE_SHIFT       12
54
55 #define RQ_CIC(rq)              \
56         ((struct cfq_io_context *) (rq)->elevator_private)
57 #define RQ_CFQQ(rq)             (struct cfq_queue *) ((rq)->elevator_private2)
58
59 static struct kmem_cache *cfq_pool;
60 static struct kmem_cache *cfq_ioc_pool;
61
62 static DEFINE_PER_CPU(unsigned long, cfq_ioc_count);
63 static struct completion *ioc_gone;
64 static DEFINE_SPINLOCK(ioc_gone_lock);
65
66 #define CFQ_PRIO_LISTS          IOPRIO_BE_NR
67 #define cfq_class_idle(cfqq)    ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
68 #define cfq_class_rt(cfqq)      ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
69
70 #define sample_valid(samples)   ((samples) > 80)
71 #define rb_entry_cfqg(node)     rb_entry((node), struct cfq_group, rb_node)
72
73 /*
74  * Most of our rbtree usage is for sorting with min extraction, so
75  * if we cache the leftmost node we don't have to walk down the tree
76  * to find it. Idea borrowed from Ingo Molnars CFS scheduler. We should
77  * move this into the elevator for the rq sorting as well.
78  */
79 struct cfq_rb_root {
80         struct rb_root rb;
81         struct rb_node *left;
82         unsigned count;
83         u64 min_vdisktime;
84         struct rb_node *active;
85         unsigned total_weight;
86 };
87 #define CFQ_RB_ROOT     (struct cfq_rb_root) { RB_ROOT, NULL, 0, 0, }
88
89 /*
90  * Per process-grouping structure
91  */
92 struct cfq_queue {
93         /* reference count */
94         atomic_t ref;
95         /* various state flags, see below */
96         unsigned int flags;
97         /* parent cfq_data */
98         struct cfq_data *cfqd;
99         /* service_tree member */
100         struct rb_node rb_node;
101         /* service_tree key */
102         unsigned long rb_key;
103         /* prio tree member */
104         struct rb_node p_node;
105         /* prio tree root we belong to, if any */
106         struct rb_root *p_root;
107         /* sorted list of pending requests */
108         struct rb_root sort_list;
109         /* if fifo isn't expired, next request to serve */
110         struct request *next_rq;
111         /* requests queued in sort_list */
112         int queued[2];
113         /* currently allocated requests */
114         int allocated[2];
115         /* fifo list of requests in sort_list */
116         struct list_head fifo;
117
118         /* time when queue got scheduled in to dispatch first request. */
119         unsigned long dispatch_start;
120         /* time when first request from queue completed and slice started. */
121         unsigned long slice_start;
122         unsigned long slice_end;
123         long slice_resid;
124         unsigned int slice_dispatch;
125
126         /* pending metadata requests */
127         int meta_pending;
128         /* number of requests that are on the dispatch list or inside driver */
129         int dispatched;
130
131         /* io prio of this group */
132         unsigned short ioprio, org_ioprio;
133         unsigned short ioprio_class, org_ioprio_class;
134
135         unsigned int seek_samples;
136         u64 seek_total;
137         sector_t seek_mean;
138         sector_t last_request_pos;
139         unsigned long seeky_start;
140
141         pid_t pid;
142
143         struct cfq_rb_root *service_tree;
144         struct cfq_queue *new_cfqq;
145         struct cfq_group *cfqg;
146 };
147
148 /*
149  * First index in the service_trees.
150  * IDLE is handled separately, so it has negative index
151  */
152 enum wl_prio_t {
153         BE_WORKLOAD = 0,
154         RT_WORKLOAD = 1,
155         IDLE_WORKLOAD = 2,
156 };
157
158 /*
159  * Second index in the service_trees.
160  */
161 enum wl_type_t {
162         ASYNC_WORKLOAD = 0,
163         SYNC_NOIDLE_WORKLOAD = 1,
164         SYNC_WORKLOAD = 2
165 };
166
167 /* This is per cgroup per device grouping structure */
168 struct cfq_group {
169         /* group service_tree member */
170         struct rb_node rb_node;
171
172         /* group service_tree key */
173         u64 vdisktime;
174         unsigned int weight;
175         bool on_st;
176
177         /* number of cfqq currently on this group */
178         int nr_cfqq;
179
180         /* Per group busy queus average. Useful for workload slice calc. */
181         unsigned int busy_queues_avg[2];
182         /*
183          * rr lists of queues with requests, onle rr for each priority class.
184          * Counts are embedded in the cfq_rb_root
185          */
186         struct cfq_rb_root service_trees[2][3];
187         struct cfq_rb_root service_tree_idle;
188
189         unsigned long saved_workload_slice;
190         enum wl_type_t saved_workload;
191         enum wl_prio_t saved_serving_prio;
192         struct blkio_group blkg;
193 #ifdef CONFIG_CFQ_GROUP_IOSCHED
194         struct hlist_node cfqd_node;
195 #endif
196 };
197
198 /*
199  * Per block device queue structure
200  */
201 struct cfq_data {
202         struct request_queue *queue;
203         /* Root service tree for cfq_groups */
204         struct cfq_rb_root grp_service_tree;
205         struct cfq_group root_group;
206         /* Number of active cfq groups on group service tree */
207         int nr_groups;
208
209         /*
210          * The priority currently being served
211          */
212         enum wl_prio_t serving_prio;
213         enum wl_type_t serving_type;
214         unsigned long workload_expires;
215         struct cfq_group *serving_group;
216         bool noidle_tree_requires_idle;
217
218         /*
219          * Each priority tree is sorted by next_request position.  These
220          * trees are used when determining if two or more queues are
221          * interleaving requests (see cfq_close_cooperator).
222          */
223         struct rb_root prio_trees[CFQ_PRIO_LISTS];
224
225         unsigned int busy_queues;
226
227         int rq_in_driver[2];
228         int sync_flight;
229
230         /*
231          * queue-depth detection
232          */
233         int rq_queued;
234         int hw_tag;
235         /*
236          * hw_tag can be
237          * -1 => indeterminate, (cfq will behave as if NCQ is present, to allow better detection)
238          *  1 => NCQ is present (hw_tag_est_depth is the estimated max depth)
239          *  0 => no NCQ
240          */
241         int hw_tag_est_depth;
242         unsigned int hw_tag_samples;
243
244         /*
245          * idle window management
246          */
247         struct timer_list idle_slice_timer;
248         struct work_struct unplug_work;
249
250         struct cfq_queue *active_queue;
251         struct cfq_io_context *active_cic;
252
253         /*
254          * async queue for each priority case
255          */
256         struct cfq_queue *async_cfqq[2][IOPRIO_BE_NR];
257         struct cfq_queue *async_idle_cfqq;
258
259         sector_t last_position;
260
261         /*
262          * tunables, see top of file
263          */
264         unsigned int cfq_quantum;
265         unsigned int cfq_fifo_expire[2];
266         unsigned int cfq_back_penalty;
267         unsigned int cfq_back_max;
268         unsigned int cfq_slice[2];
269         unsigned int cfq_slice_async_rq;
270         unsigned int cfq_slice_idle;
271         unsigned int cfq_latency;
272
273         struct list_head cic_list;
274
275         /*
276          * Fallback dummy cfqq for extreme OOM conditions
277          */
278         struct cfq_queue oom_cfqq;
279
280         unsigned long last_end_sync_rq;
281
282         /* List of cfq groups being managed on this device*/
283         struct hlist_head cfqg_list;
284 };
285
286 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd);
287
288 static struct cfq_rb_root *service_tree_for(struct cfq_group *cfqg,
289                                             enum wl_prio_t prio,
290                                             enum wl_type_t type,
291                                             struct cfq_data *cfqd)
292 {
293         if (!cfqg)
294                 return NULL;
295
296         if (prio == IDLE_WORKLOAD)
297                 return &cfqg->service_tree_idle;
298
299         return &cfqg->service_trees[prio][type];
300 }
301
302 enum cfqq_state_flags {
303         CFQ_CFQQ_FLAG_on_rr = 0,        /* on round-robin busy list */
304         CFQ_CFQQ_FLAG_wait_request,     /* waiting for a request */
305         CFQ_CFQQ_FLAG_must_dispatch,    /* must be allowed a dispatch */
306         CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
307         CFQ_CFQQ_FLAG_fifo_expire,      /* FIFO checked in this slice */
308         CFQ_CFQQ_FLAG_idle_window,      /* slice idling enabled */
309         CFQ_CFQQ_FLAG_prio_changed,     /* task priority has changed */
310         CFQ_CFQQ_FLAG_slice_new,        /* no requests dispatched in slice */
311         CFQ_CFQQ_FLAG_sync,             /* synchronous queue */
312         CFQ_CFQQ_FLAG_coop,             /* cfqq is shared */
313         CFQ_CFQQ_FLAG_deep,             /* sync cfqq experienced large depth */
314 };
315
316 #define CFQ_CFQQ_FNS(name)                                              \
317 static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq)         \
318 {                                                                       \
319         (cfqq)->flags |= (1 << CFQ_CFQQ_FLAG_##name);                   \
320 }                                                                       \
321 static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq)        \
322 {                                                                       \
323         (cfqq)->flags &= ~(1 << CFQ_CFQQ_FLAG_##name);                  \
324 }                                                                       \
325 static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq)         \
326 {                                                                       \
327         return ((cfqq)->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0;      \
328 }
329
330 CFQ_CFQQ_FNS(on_rr);
331 CFQ_CFQQ_FNS(wait_request);
332 CFQ_CFQQ_FNS(must_dispatch);
333 CFQ_CFQQ_FNS(must_alloc_slice);
334 CFQ_CFQQ_FNS(fifo_expire);
335 CFQ_CFQQ_FNS(idle_window);
336 CFQ_CFQQ_FNS(prio_changed);
337 CFQ_CFQQ_FNS(slice_new);
338 CFQ_CFQQ_FNS(sync);
339 CFQ_CFQQ_FNS(coop);
340 CFQ_CFQQ_FNS(deep);
341 #undef CFQ_CFQQ_FNS
342
343 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...)  \
344         blk_add_trace_msg((cfqd)->queue, "cfq%d " fmt, (cfqq)->pid, ##args)
345 #define cfq_log(cfqd, fmt, args...)     \
346         blk_add_trace_msg((cfqd)->queue, "cfq " fmt, ##args)
347
348 /* Traverses through cfq group service trees */
349 #define for_each_cfqg_st(cfqg, i, j, st) \
350         for (i = 0; i <= IDLE_WORKLOAD; i++) \
351                 for (j = 0, st = i < IDLE_WORKLOAD ? &cfqg->service_trees[i][j]\
352                         : &cfqg->service_tree_idle; \
353                         (i < IDLE_WORKLOAD && j <= SYNC_WORKLOAD) || \
354                         (i == IDLE_WORKLOAD && j == 0); \
355                         j++, st = i < IDLE_WORKLOAD ? \
356                         &cfqg->service_trees[i][j]: NULL) \
357
358
359 static inline enum wl_prio_t cfqq_prio(struct cfq_queue *cfqq)
360 {
361         if (cfq_class_idle(cfqq))
362                 return IDLE_WORKLOAD;
363         if (cfq_class_rt(cfqq))
364                 return RT_WORKLOAD;
365         return BE_WORKLOAD;
366 }
367
368
369 static enum wl_type_t cfqq_type(struct cfq_queue *cfqq)
370 {
371         if (!cfq_cfqq_sync(cfqq))
372                 return ASYNC_WORKLOAD;
373         if (!cfq_cfqq_idle_window(cfqq))
374                 return SYNC_NOIDLE_WORKLOAD;
375         return SYNC_WORKLOAD;
376 }
377
378 static inline int cfq_group_busy_queues_wl(enum wl_prio_t wl,
379                                         struct cfq_data *cfqd,
380                                         struct cfq_group *cfqg)
381 {
382         if (wl == IDLE_WORKLOAD)
383                 return cfqg->service_tree_idle.count;
384
385         return cfqg->service_trees[wl][ASYNC_WORKLOAD].count
386                 + cfqg->service_trees[wl][SYNC_NOIDLE_WORKLOAD].count
387                 + cfqg->service_trees[wl][SYNC_WORKLOAD].count;
388 }
389
390 static void cfq_dispatch_insert(struct request_queue *, struct request *);
391 static struct cfq_queue *cfq_get_queue(struct cfq_data *, bool,
392                                        struct io_context *, gfp_t);
393 static struct cfq_io_context *cfq_cic_lookup(struct cfq_data *,
394                                                 struct io_context *);
395
396 static inline int rq_in_driver(struct cfq_data *cfqd)
397 {
398         return cfqd->rq_in_driver[0] + cfqd->rq_in_driver[1];
399 }
400
401 static inline struct cfq_queue *cic_to_cfqq(struct cfq_io_context *cic,
402                                             bool is_sync)
403 {
404         return cic->cfqq[is_sync];
405 }
406
407 static inline void cic_set_cfqq(struct cfq_io_context *cic,
408                                 struct cfq_queue *cfqq, bool is_sync)
409 {
410         cic->cfqq[is_sync] = cfqq;
411 }
412
413 /*
414  * We regard a request as SYNC, if it's either a read or has the SYNC bit
415  * set (in which case it could also be direct WRITE).
416  */
417 static inline bool cfq_bio_sync(struct bio *bio)
418 {
419         return bio_data_dir(bio) == READ || bio_rw_flagged(bio, BIO_RW_SYNCIO);
420 }
421
422 /*
423  * scheduler run of queue, if there are requests pending and no one in the
424  * driver that will restart queueing
425  */
426 static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
427 {
428         if (cfqd->busy_queues) {
429                 cfq_log(cfqd, "schedule dispatch");
430                 kblockd_schedule_work(cfqd->queue, &cfqd->unplug_work);
431         }
432 }
433
434 static int cfq_queue_empty(struct request_queue *q)
435 {
436         struct cfq_data *cfqd = q->elevator->elevator_data;
437
438         return !cfqd->rq_queued;
439 }
440
441 /*
442  * Scale schedule slice based on io priority. Use the sync time slice only
443  * if a queue is marked sync and has sync io queued. A sync queue with async
444  * io only, should not get full sync slice length.
445  */
446 static inline int cfq_prio_slice(struct cfq_data *cfqd, bool sync,
447                                  unsigned short prio)
448 {
449         const int base_slice = cfqd->cfq_slice[sync];
450
451         WARN_ON(prio >= IOPRIO_BE_NR);
452
453         return base_slice + (base_slice/CFQ_SLICE_SCALE * (4 - prio));
454 }
455
456 static inline int
457 cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
458 {
459         return cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio);
460 }
461
462 static inline u64 cfq_scale_slice(unsigned long delta, struct cfq_group *cfqg)
463 {
464         u64 d = delta << CFQ_SERVICE_SHIFT;
465
466         d = d * BLKIO_WEIGHT_DEFAULT;
467         do_div(d, cfqg->weight);
468         return d;
469 }
470
471 static inline u64 max_vdisktime(u64 min_vdisktime, u64 vdisktime)
472 {
473         s64 delta = (s64)(vdisktime - min_vdisktime);
474         if (delta > 0)
475                 min_vdisktime = vdisktime;
476
477         return min_vdisktime;
478 }
479
480 static inline u64 min_vdisktime(u64 min_vdisktime, u64 vdisktime)
481 {
482         s64 delta = (s64)(vdisktime - min_vdisktime);
483         if (delta < 0)
484                 min_vdisktime = vdisktime;
485
486         return min_vdisktime;
487 }
488
489 static void update_min_vdisktime(struct cfq_rb_root *st)
490 {
491         u64 vdisktime = st->min_vdisktime;
492         struct cfq_group *cfqg;
493
494         if (st->active) {
495                 cfqg = rb_entry_cfqg(st->active);
496                 vdisktime = cfqg->vdisktime;
497         }
498
499         if (st->left) {
500                 cfqg = rb_entry_cfqg(st->left);
501                 vdisktime = min_vdisktime(vdisktime, cfqg->vdisktime);
502         }
503
504         st->min_vdisktime = max_vdisktime(st->min_vdisktime, vdisktime);
505 }
506
507 /*
508  * get averaged number of queues of RT/BE priority.
509  * average is updated, with a formula that gives more weight to higher numbers,
510  * to quickly follows sudden increases and decrease slowly
511  */
512
513 static inline unsigned cfq_group_get_avg_queues(struct cfq_data *cfqd,
514                                         struct cfq_group *cfqg, bool rt)
515 {
516         unsigned min_q, max_q;
517         unsigned mult  = cfq_hist_divisor - 1;
518         unsigned round = cfq_hist_divisor / 2;
519         unsigned busy = cfq_group_busy_queues_wl(rt, cfqd, cfqg);
520
521         min_q = min(cfqg->busy_queues_avg[rt], busy);
522         max_q = max(cfqg->busy_queues_avg[rt], busy);
523         cfqg->busy_queues_avg[rt] = (mult * max_q + min_q + round) /
524                 cfq_hist_divisor;
525         return cfqg->busy_queues_avg[rt];
526 }
527
528 static inline unsigned
529 cfq_group_slice(struct cfq_data *cfqd, struct cfq_group *cfqg)
530 {
531         struct cfq_rb_root *st = &cfqd->grp_service_tree;
532
533         return cfq_target_latency * cfqg->weight / st->total_weight;
534 }
535
536 static inline void
537 cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
538 {
539         unsigned slice = cfq_prio_to_slice(cfqd, cfqq);
540         if (cfqd->cfq_latency) {
541                 /*
542                  * interested queues (we consider only the ones with the same
543                  * priority class in the cfq group)
544                  */
545                 unsigned iq = cfq_group_get_avg_queues(cfqd, cfqq->cfqg,
546                                                 cfq_class_rt(cfqq));
547                 unsigned sync_slice = cfqd->cfq_slice[1];
548                 unsigned expect_latency = sync_slice * iq;
549                 unsigned group_slice = cfq_group_slice(cfqd, cfqq->cfqg);
550
551                 if (expect_latency > group_slice) {
552                         unsigned base_low_slice = 2 * cfqd->cfq_slice_idle;
553                         /* scale low_slice according to IO priority
554                          * and sync vs async */
555                         unsigned low_slice =
556                                 min(slice, base_low_slice * slice / sync_slice);
557                         /* the adapted slice value is scaled to fit all iqs
558                          * into the target latency */
559                         slice = max(slice * group_slice / expect_latency,
560                                     low_slice);
561                 }
562         }
563         cfqq->slice_start = jiffies;
564         cfqq->slice_end = jiffies + slice;
565         cfq_log_cfqq(cfqd, cfqq, "set_slice=%lu", cfqq->slice_end - jiffies);
566 }
567
568 /*
569  * We need to wrap this check in cfq_cfqq_slice_new(), since ->slice_end
570  * isn't valid until the first request from the dispatch is activated
571  * and the slice time set.
572  */
573 static inline bool cfq_slice_used(struct cfq_queue *cfqq)
574 {
575         if (cfq_cfqq_slice_new(cfqq))
576                 return 0;
577         if (time_before(jiffies, cfqq->slice_end))
578                 return 0;
579
580         return 1;
581 }
582
583 /*
584  * Lifted from AS - choose which of rq1 and rq2 that is best served now.
585  * We choose the request that is closest to the head right now. Distance
586  * behind the head is penalized and only allowed to a certain extent.
587  */
588 static struct request *
589 cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2, sector_t last)
590 {
591         sector_t s1, s2, d1 = 0, d2 = 0;
592         unsigned long back_max;
593 #define CFQ_RQ1_WRAP    0x01 /* request 1 wraps */
594 #define CFQ_RQ2_WRAP    0x02 /* request 2 wraps */
595         unsigned wrap = 0; /* bit mask: requests behind the disk head? */
596
597         if (rq1 == NULL || rq1 == rq2)
598                 return rq2;
599         if (rq2 == NULL)
600                 return rq1;
601
602         if (rq_is_sync(rq1) && !rq_is_sync(rq2))
603                 return rq1;
604         else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
605                 return rq2;
606         if (rq_is_meta(rq1) && !rq_is_meta(rq2))
607                 return rq1;
608         else if (rq_is_meta(rq2) && !rq_is_meta(rq1))
609                 return rq2;
610
611         s1 = blk_rq_pos(rq1);
612         s2 = blk_rq_pos(rq2);
613
614         /*
615          * by definition, 1KiB is 2 sectors
616          */
617         back_max = cfqd->cfq_back_max * 2;
618
619         /*
620          * Strict one way elevator _except_ in the case where we allow
621          * short backward seeks which are biased as twice the cost of a
622          * similar forward seek.
623          */
624         if (s1 >= last)
625                 d1 = s1 - last;
626         else if (s1 + back_max >= last)
627                 d1 = (last - s1) * cfqd->cfq_back_penalty;
628         else
629                 wrap |= CFQ_RQ1_WRAP;
630
631         if (s2 >= last)
632                 d2 = s2 - last;
633         else if (s2 + back_max >= last)
634                 d2 = (last - s2) * cfqd->cfq_back_penalty;
635         else
636                 wrap |= CFQ_RQ2_WRAP;
637
638         /* Found required data */
639
640         /*
641          * By doing switch() on the bit mask "wrap" we avoid having to
642          * check two variables for all permutations: --> faster!
643          */
644         switch (wrap) {
645         case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
646                 if (d1 < d2)
647                         return rq1;
648                 else if (d2 < d1)
649                         return rq2;
650                 else {
651                         if (s1 >= s2)
652                                 return rq1;
653                         else
654                                 return rq2;
655                 }
656
657         case CFQ_RQ2_WRAP:
658                 return rq1;
659         case CFQ_RQ1_WRAP:
660                 return rq2;
661         case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
662         default:
663                 /*
664                  * Since both rqs are wrapped,
665                  * start with the one that's further behind head
666                  * (--> only *one* back seek required),
667                  * since back seek takes more time than forward.
668                  */
669                 if (s1 <= s2)
670                         return rq1;
671                 else
672                         return rq2;
673         }
674 }
675
676 /*
677  * The below is leftmost cache rbtree addon
678  */
679 static struct cfq_queue *cfq_rb_first(struct cfq_rb_root *root)
680 {
681         /* Service tree is empty */
682         if (!root->count)
683                 return NULL;
684
685         if (!root->left)
686                 root->left = rb_first(&root->rb);
687
688         if (root->left)
689                 return rb_entry(root->left, struct cfq_queue, rb_node);
690
691         return NULL;
692 }
693
694 static struct cfq_group *cfq_rb_first_group(struct cfq_rb_root *root)
695 {
696         if (!root->left)
697                 root->left = rb_first(&root->rb);
698
699         if (root->left)
700                 return rb_entry_cfqg(root->left);
701
702         return NULL;
703 }
704
705 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
706 {
707         rb_erase(n, root);
708         RB_CLEAR_NODE(n);
709 }
710
711 static void cfq_rb_erase(struct rb_node *n, struct cfq_rb_root *root)
712 {
713         if (root->left == n)
714                 root->left = NULL;
715         rb_erase_init(n, &root->rb);
716         --root->count;
717 }
718
719 /*
720  * would be nice to take fifo expire time into account as well
721  */
722 static struct request *
723 cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
724                   struct request *last)
725 {
726         struct rb_node *rbnext = rb_next(&last->rb_node);
727         struct rb_node *rbprev = rb_prev(&last->rb_node);
728         struct request *next = NULL, *prev = NULL;
729
730         BUG_ON(RB_EMPTY_NODE(&last->rb_node));
731
732         if (rbprev)
733                 prev = rb_entry_rq(rbprev);
734
735         if (rbnext)
736                 next = rb_entry_rq(rbnext);
737         else {
738                 rbnext = rb_first(&cfqq->sort_list);
739                 if (rbnext && rbnext != &last->rb_node)
740                         next = rb_entry_rq(rbnext);
741         }
742
743         return cfq_choose_req(cfqd, next, prev, blk_rq_pos(last));
744 }
745
746 static unsigned long cfq_slice_offset(struct cfq_data *cfqd,
747                                       struct cfq_queue *cfqq)
748 {
749         /*
750          * just an approximation, should be ok.
751          */
752         return (cfqq->cfqg->nr_cfqq - 1) * (cfq_prio_slice(cfqd, 1, 0) -
753                        cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio));
754 }
755
756 static inline s64
757 cfqg_key(struct cfq_rb_root *st, struct cfq_group *cfqg)
758 {
759         return cfqg->vdisktime - st->min_vdisktime;
760 }
761
762 static void
763 __cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
764 {
765         struct rb_node **node = &st->rb.rb_node;
766         struct rb_node *parent = NULL;
767         struct cfq_group *__cfqg;
768         s64 key = cfqg_key(st, cfqg);
769         int left = 1;
770
771         while (*node != NULL) {
772                 parent = *node;
773                 __cfqg = rb_entry_cfqg(parent);
774
775                 if (key < cfqg_key(st, __cfqg))
776                         node = &parent->rb_left;
777                 else {
778                         node = &parent->rb_right;
779                         left = 0;
780                 }
781         }
782
783         if (left)
784                 st->left = &cfqg->rb_node;
785
786         rb_link_node(&cfqg->rb_node, parent, node);
787         rb_insert_color(&cfqg->rb_node, &st->rb);
788 }
789
790 static void
791 cfq_group_service_tree_add(struct cfq_data *cfqd, struct cfq_group *cfqg)
792 {
793         struct cfq_rb_root *st = &cfqd->grp_service_tree;
794         struct cfq_group *__cfqg;
795         struct rb_node *n;
796
797         cfqg->nr_cfqq++;
798         if (cfqg->on_st)
799                 return;
800
801         /*
802          * Currently put the group at the end. Later implement something
803          * so that groups get lesser vtime based on their weights, so that
804          * if group does not loose all if it was not continously backlogged.
805          */
806         n = rb_last(&st->rb);
807         if (n) {
808                 __cfqg = rb_entry_cfqg(n);
809                 cfqg->vdisktime = __cfqg->vdisktime + CFQ_IDLE_DELAY;
810         } else
811                 cfqg->vdisktime = st->min_vdisktime;
812
813         __cfq_group_service_tree_add(st, cfqg);
814         cfqg->on_st = true;
815         cfqd->nr_groups++;
816         st->total_weight += cfqg->weight;
817 }
818
819 static void
820 cfq_group_service_tree_del(struct cfq_data *cfqd, struct cfq_group *cfqg)
821 {
822         struct cfq_rb_root *st = &cfqd->grp_service_tree;
823
824         if (st->active == &cfqg->rb_node)
825                 st->active = NULL;
826
827         BUG_ON(cfqg->nr_cfqq < 1);
828         cfqg->nr_cfqq--;
829
830         /* If there are other cfq queues under this group, don't delete it */
831         if (cfqg->nr_cfqq)
832                 return;
833
834         cfqg->on_st = false;
835         cfqd->nr_groups--;
836         st->total_weight -= cfqg->weight;
837         if (!RB_EMPTY_NODE(&cfqg->rb_node))
838                 cfq_rb_erase(&cfqg->rb_node, st);
839         cfqg->saved_workload_slice = 0;
840 }
841
842 static inline unsigned int cfq_cfqq_slice_usage(struct cfq_queue *cfqq)
843 {
844         unsigned int slice_used, allocated_slice;
845
846         /*
847          * Queue got expired before even a single request completed or
848          * got expired immediately after first request completion.
849          */
850         if (!cfqq->slice_start || cfqq->slice_start == jiffies) {
851                 /*
852                  * Also charge the seek time incurred to the group, otherwise
853                  * if there are mutiple queues in the group, each can dispatch
854                  * a single request on seeky media and cause lots of seek time
855                  * and group will never know it.
856                  */
857                 slice_used = max_t(unsigned, (jiffies - cfqq->dispatch_start),
858                                         1);
859         } else {
860                 slice_used = jiffies - cfqq->slice_start;
861                 allocated_slice = cfqq->slice_end - cfqq->slice_start;
862                 if (slice_used > allocated_slice)
863                         slice_used = allocated_slice;
864         }
865
866         cfq_log_cfqq(cfqq->cfqd, cfqq, "sl_used=%u", slice_used);
867         return slice_used;
868 }
869
870 static void cfq_group_served(struct cfq_data *cfqd, struct cfq_group *cfqg,
871                                 struct cfq_queue *cfqq)
872 {
873         struct cfq_rb_root *st = &cfqd->grp_service_tree;
874         unsigned int used_sl;
875
876         used_sl = cfq_cfqq_slice_usage(cfqq);
877
878         /* Can't update vdisktime while group is on service tree */
879         cfq_rb_erase(&cfqg->rb_node, st);
880         cfqg->vdisktime += cfq_scale_slice(used_sl, cfqg);
881         __cfq_group_service_tree_add(st, cfqg);
882
883         /* This group is being expired. Save the context */
884         if (time_after(cfqd->workload_expires, jiffies)) {
885                 cfqg->saved_workload_slice = cfqd->workload_expires
886                                                 - jiffies;
887                 cfqg->saved_workload = cfqd->serving_type;
888                 cfqg->saved_serving_prio = cfqd->serving_prio;
889         } else
890                 cfqg->saved_workload_slice = 0;
891 }
892
893 #ifdef CONFIG_CFQ_GROUP_IOSCHED
894 static inline struct cfq_group *cfqg_of_blkg(struct blkio_group *blkg)
895 {
896         if (blkg)
897                 return container_of(blkg, struct cfq_group, blkg);
898         return NULL;
899 }
900
901 static struct cfq_group *
902 cfq_find_alloc_cfqg(struct cfq_data *cfqd, struct cgroup *cgroup, int create)
903 {
904         struct blkio_cgroup *blkcg = cgroup_to_blkio_cgroup(cgroup);
905         struct cfq_group *cfqg = NULL;
906         void *key = cfqd;
907         int i, j;
908         struct cfq_rb_root *st;
909
910         /* Do we need to take this reference */
911         if (!css_tryget(&blkcg->css))
912                 return NULL;;
913
914         cfqg = cfqg_of_blkg(blkiocg_lookup_group(blkcg, key));
915         if (cfqg || !create)
916                 goto done;
917
918         cfqg = kzalloc_node(sizeof(*cfqg), GFP_ATOMIC, cfqd->queue->node);
919         if (!cfqg)
920                 goto done;
921
922         cfqg->weight = blkcg->weight;
923         for_each_cfqg_st(cfqg, i, j, st)
924                 *st = CFQ_RB_ROOT;
925         RB_CLEAR_NODE(&cfqg->rb_node);
926
927         /* Add group onto cgroup list */
928         blkiocg_add_blkio_group(blkcg, &cfqg->blkg, (void *)cfqd);
929
930         /* Add group on cfqd list */
931         hlist_add_head(&cfqg->cfqd_node, &cfqd->cfqg_list);
932
933 done:
934         css_put(&blkcg->css);
935         return cfqg;
936 }
937
938 /*
939  * Search for the cfq group current task belongs to. If create = 1, then also
940  * create the cfq group if it does not exist. request_queue lock must be held.
941  */
942 static struct cfq_group *cfq_get_cfqg(struct cfq_data *cfqd, int create)
943 {
944         struct cgroup *cgroup;
945         struct cfq_group *cfqg = NULL;
946
947         rcu_read_lock();
948         cgroup = task_cgroup(current, blkio_subsys_id);
949         cfqg = cfq_find_alloc_cfqg(cfqd, cgroup, create);
950         if (!cfqg && create)
951                 cfqg = &cfqd->root_group;
952         rcu_read_unlock();
953         return cfqg;
954 }
955
956 static void cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg)
957 {
958         /* Currently, all async queues are mapped to root group */
959         if (!cfq_cfqq_sync(cfqq))
960                 cfqg = &cfqq->cfqd->root_group;
961
962         cfqq->cfqg = cfqg;
963 }
964 #else /* GROUP_IOSCHED */
965 static struct cfq_group *cfq_get_cfqg(struct cfq_data *cfqd, int create)
966 {
967         return &cfqd->root_group;
968 }
969 static inline void
970 cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg) {
971         cfqq->cfqg = cfqg;
972 }
973
974 #endif /* GROUP_IOSCHED */
975
976 /*
977  * The cfqd->service_trees holds all pending cfq_queue's that have
978  * requests waiting to be processed. It is sorted in the order that
979  * we will service the queues.
980  */
981 static void cfq_service_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq,
982                                  bool add_front)
983 {
984         struct rb_node **p, *parent;
985         struct cfq_queue *__cfqq;
986         unsigned long rb_key;
987         struct cfq_rb_root *service_tree;
988         int left;
989         int new_cfqq = 1;
990
991         service_tree = service_tree_for(cfqq->cfqg, cfqq_prio(cfqq),
992                                                 cfqq_type(cfqq), cfqd);
993         if (cfq_class_idle(cfqq)) {
994                 rb_key = CFQ_IDLE_DELAY;
995                 parent = rb_last(&service_tree->rb);
996                 if (parent && parent != &cfqq->rb_node) {
997                         __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
998                         rb_key += __cfqq->rb_key;
999                 } else
1000                         rb_key += jiffies;
1001         } else if (!add_front) {
1002                 /*
1003                  * Get our rb key offset. Subtract any residual slice
1004                  * value carried from last service. A negative resid
1005                  * count indicates slice overrun, and this should position
1006                  * the next service time further away in the tree.
1007                  */
1008                 rb_key = cfq_slice_offset(cfqd, cfqq) + jiffies;
1009                 rb_key -= cfqq->slice_resid;
1010                 cfqq->slice_resid = 0;
1011         } else {
1012                 rb_key = -HZ;
1013                 __cfqq = cfq_rb_first(service_tree);
1014                 rb_key += __cfqq ? __cfqq->rb_key : jiffies;
1015         }
1016
1017         if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
1018                 new_cfqq = 0;
1019                 /*
1020                  * same position, nothing more to do
1021                  */
1022                 if (rb_key == cfqq->rb_key &&
1023                     cfqq->service_tree == service_tree)
1024                         return;
1025
1026                 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
1027                 cfqq->service_tree = NULL;
1028         }
1029
1030         left = 1;
1031         parent = NULL;
1032         cfqq->service_tree = service_tree;
1033         p = &service_tree->rb.rb_node;
1034         while (*p) {
1035                 struct rb_node **n;
1036
1037                 parent = *p;
1038                 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
1039
1040                 /*
1041                  * sort by key, that represents service time.
1042                  */
1043                 if (time_before(rb_key, __cfqq->rb_key))
1044                         n = &(*p)->rb_left;
1045                 else {
1046                         n = &(*p)->rb_right;
1047                         left = 0;
1048                 }
1049
1050                 p = n;
1051         }
1052
1053         if (left)
1054                 service_tree->left = &cfqq->rb_node;
1055
1056         cfqq->rb_key = rb_key;
1057         rb_link_node(&cfqq->rb_node, parent, p);
1058         rb_insert_color(&cfqq->rb_node, &service_tree->rb);
1059         service_tree->count++;
1060         if (add_front || !new_cfqq)
1061                 return;
1062         cfq_group_service_tree_add(cfqd, cfqq->cfqg);
1063 }
1064
1065 static struct cfq_queue *
1066 cfq_prio_tree_lookup(struct cfq_data *cfqd, struct rb_root *root,
1067                      sector_t sector, struct rb_node **ret_parent,
1068                      struct rb_node ***rb_link)
1069 {
1070         struct rb_node **p, *parent;
1071         struct cfq_queue *cfqq = NULL;
1072
1073         parent = NULL;
1074         p = &root->rb_node;
1075         while (*p) {
1076                 struct rb_node **n;
1077
1078                 parent = *p;
1079                 cfqq = rb_entry(parent, struct cfq_queue, p_node);
1080
1081                 /*
1082                  * Sort strictly based on sector.  Smallest to the left,
1083                  * largest to the right.
1084                  */
1085                 if (sector > blk_rq_pos(cfqq->next_rq))
1086                         n = &(*p)->rb_right;
1087                 else if (sector < blk_rq_pos(cfqq->next_rq))
1088                         n = &(*p)->rb_left;
1089                 else
1090                         break;
1091                 p = n;
1092                 cfqq = NULL;
1093         }
1094
1095         *ret_parent = parent;
1096         if (rb_link)
1097                 *rb_link = p;
1098         return cfqq;
1099 }
1100
1101 static void cfq_prio_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1102 {
1103         struct rb_node **p, *parent;
1104         struct cfq_queue *__cfqq;
1105
1106         if (cfqq->p_root) {
1107                 rb_erase(&cfqq->p_node, cfqq->p_root);
1108                 cfqq->p_root = NULL;
1109         }
1110
1111         if (cfq_class_idle(cfqq))
1112                 return;
1113         if (!cfqq->next_rq)
1114                 return;
1115
1116         cfqq->p_root = &cfqd->prio_trees[cfqq->org_ioprio];
1117         __cfqq = cfq_prio_tree_lookup(cfqd, cfqq->p_root,
1118                                       blk_rq_pos(cfqq->next_rq), &parent, &p);
1119         if (!__cfqq) {
1120                 rb_link_node(&cfqq->p_node, parent, p);
1121                 rb_insert_color(&cfqq->p_node, cfqq->p_root);
1122         } else
1123                 cfqq->p_root = NULL;
1124 }
1125
1126 /*
1127  * Update cfqq's position in the service tree.
1128  */
1129 static void cfq_resort_rr_list(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1130 {
1131         /*
1132          * Resorting requires the cfqq to be on the RR list already.
1133          */
1134         if (cfq_cfqq_on_rr(cfqq)) {
1135                 cfq_service_tree_add(cfqd, cfqq, 0);
1136                 cfq_prio_tree_add(cfqd, cfqq);
1137         }
1138 }
1139
1140 /*
1141  * add to busy list of queues for service, trying to be fair in ordering
1142  * the pending list according to last request service
1143  */
1144 static void cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1145 {
1146         cfq_log_cfqq(cfqd, cfqq, "add_to_rr");
1147         BUG_ON(cfq_cfqq_on_rr(cfqq));
1148         cfq_mark_cfqq_on_rr(cfqq);
1149         cfqd->busy_queues++;
1150
1151         cfq_resort_rr_list(cfqd, cfqq);
1152 }
1153
1154 /*
1155  * Called when the cfqq no longer has requests pending, remove it from
1156  * the service tree.
1157  */
1158 static void cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1159 {
1160         cfq_log_cfqq(cfqd, cfqq, "del_from_rr");
1161         BUG_ON(!cfq_cfqq_on_rr(cfqq));
1162         cfq_clear_cfqq_on_rr(cfqq);
1163
1164         if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
1165                 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
1166                 cfqq->service_tree = NULL;
1167         }
1168         if (cfqq->p_root) {
1169                 rb_erase(&cfqq->p_node, cfqq->p_root);
1170                 cfqq->p_root = NULL;
1171         }
1172
1173         cfq_group_service_tree_del(cfqd, cfqq->cfqg);
1174         BUG_ON(!cfqd->busy_queues);
1175         cfqd->busy_queues--;
1176 }
1177
1178 /*
1179  * rb tree support functions
1180  */
1181 static void cfq_del_rq_rb(struct request *rq)
1182 {
1183         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1184         const int sync = rq_is_sync(rq);
1185
1186         BUG_ON(!cfqq->queued[sync]);
1187         cfqq->queued[sync]--;
1188
1189         elv_rb_del(&cfqq->sort_list, rq);
1190
1191         if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list)) {
1192                 /*
1193                  * Queue will be deleted from service tree when we actually
1194                  * expire it later. Right now just remove it from prio tree
1195                  * as it is empty.
1196                  */
1197                 if (cfqq->p_root) {
1198                         rb_erase(&cfqq->p_node, cfqq->p_root);
1199                         cfqq->p_root = NULL;
1200                 }
1201         }
1202 }
1203
1204 static void cfq_add_rq_rb(struct request *rq)
1205 {
1206         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1207         struct cfq_data *cfqd = cfqq->cfqd;
1208         struct request *__alias, *prev;
1209
1210         cfqq->queued[rq_is_sync(rq)]++;
1211
1212         /*
1213          * looks a little odd, but the first insert might return an alias.
1214          * if that happens, put the alias on the dispatch list
1215          */
1216         while ((__alias = elv_rb_add(&cfqq->sort_list, rq)) != NULL)
1217                 cfq_dispatch_insert(cfqd->queue, __alias);
1218
1219         if (!cfq_cfqq_on_rr(cfqq))
1220                 cfq_add_cfqq_rr(cfqd, cfqq);
1221
1222         /*
1223          * check if this request is a better next-serve candidate
1224          */
1225         prev = cfqq->next_rq;
1226         cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq, cfqd->last_position);
1227
1228         /*
1229          * adjust priority tree position, if ->next_rq changes
1230          */
1231         if (prev != cfqq->next_rq)
1232                 cfq_prio_tree_add(cfqd, cfqq);
1233
1234         BUG_ON(!cfqq->next_rq);
1235 }
1236
1237 static void cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
1238 {
1239         elv_rb_del(&cfqq->sort_list, rq);
1240         cfqq->queued[rq_is_sync(rq)]--;
1241         cfq_add_rq_rb(rq);
1242 }
1243
1244 static struct request *
1245 cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
1246 {
1247         struct task_struct *tsk = current;
1248         struct cfq_io_context *cic;
1249         struct cfq_queue *cfqq;
1250
1251         cic = cfq_cic_lookup(cfqd, tsk->io_context);
1252         if (!cic)
1253                 return NULL;
1254
1255         cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
1256         if (cfqq) {
1257                 sector_t sector = bio->bi_sector + bio_sectors(bio);
1258
1259                 return elv_rb_find(&cfqq->sort_list, sector);
1260         }
1261
1262         return NULL;
1263 }
1264
1265 static void cfq_activate_request(struct request_queue *q, struct request *rq)
1266 {
1267         struct cfq_data *cfqd = q->elevator->elevator_data;
1268
1269         cfqd->rq_in_driver[rq_is_sync(rq)]++;
1270         cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "activate rq, drv=%d",
1271                                                 rq_in_driver(cfqd));
1272
1273         cfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
1274 }
1275
1276 static void cfq_deactivate_request(struct request_queue *q, struct request *rq)
1277 {
1278         struct cfq_data *cfqd = q->elevator->elevator_data;
1279         const int sync = rq_is_sync(rq);
1280
1281         WARN_ON(!cfqd->rq_in_driver[sync]);
1282         cfqd->rq_in_driver[sync]--;
1283         cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "deactivate rq, drv=%d",
1284                                                 rq_in_driver(cfqd));
1285 }
1286
1287 static void cfq_remove_request(struct request *rq)
1288 {
1289         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1290
1291         if (cfqq->next_rq == rq)
1292                 cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
1293
1294         list_del_init(&rq->queuelist);
1295         cfq_del_rq_rb(rq);
1296
1297         cfqq->cfqd->rq_queued--;
1298         if (rq_is_meta(rq)) {
1299                 WARN_ON(!cfqq->meta_pending);
1300                 cfqq->meta_pending--;
1301         }
1302 }
1303
1304 static int cfq_merge(struct request_queue *q, struct request **req,
1305                      struct bio *bio)
1306 {
1307         struct cfq_data *cfqd = q->elevator->elevator_data;
1308         struct request *__rq;
1309
1310         __rq = cfq_find_rq_fmerge(cfqd, bio);
1311         if (__rq && elv_rq_merge_ok(__rq, bio)) {
1312                 *req = __rq;
1313                 return ELEVATOR_FRONT_MERGE;
1314         }
1315
1316         return ELEVATOR_NO_MERGE;
1317 }
1318
1319 static void cfq_merged_request(struct request_queue *q, struct request *req,
1320                                int type)
1321 {
1322         if (type == ELEVATOR_FRONT_MERGE) {
1323                 struct cfq_queue *cfqq = RQ_CFQQ(req);
1324
1325                 cfq_reposition_rq_rb(cfqq, req);
1326         }
1327 }
1328
1329 static void
1330 cfq_merged_requests(struct request_queue *q, struct request *rq,
1331                     struct request *next)
1332 {
1333         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1334         /*
1335          * reposition in fifo if next is older than rq
1336          */
1337         if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
1338             time_before(rq_fifo_time(next), rq_fifo_time(rq))) {
1339                 list_move(&rq->queuelist, &next->queuelist);
1340                 rq_set_fifo_time(rq, rq_fifo_time(next));
1341         }
1342
1343         if (cfqq->next_rq == next)
1344                 cfqq->next_rq = rq;
1345         cfq_remove_request(next);
1346 }
1347
1348 static int cfq_allow_merge(struct request_queue *q, struct request *rq,
1349                            struct bio *bio)
1350 {
1351         struct cfq_data *cfqd = q->elevator->elevator_data;
1352         struct cfq_io_context *cic;
1353         struct cfq_queue *cfqq;
1354
1355         /*
1356          * Disallow merge of a sync bio into an async request.
1357          */
1358         if (cfq_bio_sync(bio) && !rq_is_sync(rq))
1359                 return false;
1360
1361         /*
1362          * Lookup the cfqq that this bio will be queued with. Allow
1363          * merge only if rq is queued there.
1364          */
1365         cic = cfq_cic_lookup(cfqd, current->io_context);
1366         if (!cic)
1367                 return false;
1368
1369         cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
1370         return cfqq == RQ_CFQQ(rq);
1371 }
1372
1373 static void __cfq_set_active_queue(struct cfq_data *cfqd,
1374                                    struct cfq_queue *cfqq)
1375 {
1376         if (cfqq) {
1377                 cfq_log_cfqq(cfqd, cfqq, "set_active");
1378                 cfqq->slice_start = 0;
1379                 cfqq->dispatch_start = jiffies;
1380                 cfqq->slice_end = 0;
1381                 cfqq->slice_dispatch = 0;
1382
1383                 cfq_clear_cfqq_wait_request(cfqq);
1384                 cfq_clear_cfqq_must_dispatch(cfqq);
1385                 cfq_clear_cfqq_must_alloc_slice(cfqq);
1386                 cfq_clear_cfqq_fifo_expire(cfqq);
1387                 cfq_mark_cfqq_slice_new(cfqq);
1388
1389                 del_timer(&cfqd->idle_slice_timer);
1390         }
1391
1392         cfqd->active_queue = cfqq;
1393 }
1394
1395 /*
1396  * current cfqq expired its slice (or was too idle), select new one
1397  */
1398 static void
1399 __cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1400                     bool timed_out)
1401 {
1402         cfq_log_cfqq(cfqd, cfqq, "slice expired t=%d", timed_out);
1403
1404         if (cfq_cfqq_wait_request(cfqq))
1405                 del_timer(&cfqd->idle_slice_timer);
1406
1407         cfq_clear_cfqq_wait_request(cfqq);
1408
1409         /*
1410          * store what was left of this slice, if the queue idled/timed out
1411          */
1412         if (timed_out && !cfq_cfqq_slice_new(cfqq)) {
1413                 cfqq->slice_resid = cfqq->slice_end - jiffies;
1414                 cfq_log_cfqq(cfqd, cfqq, "resid=%ld", cfqq->slice_resid);
1415         }
1416
1417         cfq_group_served(cfqd, cfqq->cfqg, cfqq);
1418
1419         if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
1420                 cfq_del_cfqq_rr(cfqd, cfqq);
1421
1422         cfq_resort_rr_list(cfqd, cfqq);
1423
1424         if (cfqq == cfqd->active_queue)
1425                 cfqd->active_queue = NULL;
1426
1427         if (&cfqq->cfqg->rb_node == cfqd->grp_service_tree.active)
1428                 cfqd->grp_service_tree.active = NULL;
1429
1430         if (cfqd->active_cic) {
1431                 put_io_context(cfqd->active_cic->ioc);
1432                 cfqd->active_cic = NULL;
1433         }
1434 }
1435
1436 static inline void cfq_slice_expired(struct cfq_data *cfqd, bool timed_out)
1437 {
1438         struct cfq_queue *cfqq = cfqd->active_queue;
1439
1440         if (cfqq)
1441                 __cfq_slice_expired(cfqd, cfqq, timed_out);
1442 }
1443
1444 /*
1445  * Get next queue for service. Unless we have a queue preemption,
1446  * we'll simply select the first cfqq in the service tree.
1447  */
1448 static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
1449 {
1450         struct cfq_rb_root *service_tree =
1451                 service_tree_for(cfqd->serving_group, cfqd->serving_prio,
1452                                         cfqd->serving_type, cfqd);
1453
1454         if (!cfqd->rq_queued)
1455                 return NULL;
1456
1457         /* There is nothing to dispatch */
1458         if (!service_tree)
1459                 return NULL;
1460         if (RB_EMPTY_ROOT(&service_tree->rb))
1461                 return NULL;
1462         return cfq_rb_first(service_tree);
1463 }
1464
1465 static struct cfq_queue *cfq_get_next_queue_forced(struct cfq_data *cfqd)
1466 {
1467         struct cfq_group *cfqg;
1468         struct cfq_queue *cfqq;
1469         int i, j;
1470         struct cfq_rb_root *st;
1471
1472         if (!cfqd->rq_queued)
1473                 return NULL;
1474
1475         cfqg = cfq_get_next_cfqg(cfqd);
1476         if (!cfqg)
1477                 return NULL;
1478
1479         for_each_cfqg_st(cfqg, i, j, st)
1480                 if ((cfqq = cfq_rb_first(st)) != NULL)
1481                         return cfqq;
1482         return NULL;
1483 }
1484
1485 /*
1486  * Get and set a new active queue for service.
1487  */
1488 static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd,
1489                                               struct cfq_queue *cfqq)
1490 {
1491         if (!cfqq)
1492                 cfqq = cfq_get_next_queue(cfqd);
1493
1494         __cfq_set_active_queue(cfqd, cfqq);
1495         return cfqq;
1496 }
1497
1498 static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
1499                                           struct request *rq)
1500 {
1501         if (blk_rq_pos(rq) >= cfqd->last_position)
1502                 return blk_rq_pos(rq) - cfqd->last_position;
1503         else
1504                 return cfqd->last_position - blk_rq_pos(rq);
1505 }
1506
1507 #define CFQQ_SEEK_THR           8 * 1024
1508 #define CFQQ_SEEKY(cfqq)        ((cfqq)->seek_mean > CFQQ_SEEK_THR)
1509
1510 static inline int cfq_rq_close(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1511                                struct request *rq)
1512 {
1513         sector_t sdist = cfqq->seek_mean;
1514
1515         if (!sample_valid(cfqq->seek_samples))
1516                 sdist = CFQQ_SEEK_THR;
1517
1518         return cfq_dist_from_last(cfqd, rq) <= sdist;
1519 }
1520
1521 static struct cfq_queue *cfqq_close(struct cfq_data *cfqd,
1522                                     struct cfq_queue *cur_cfqq)
1523 {
1524         struct rb_root *root = &cfqd->prio_trees[cur_cfqq->org_ioprio];
1525         struct rb_node *parent, *node;
1526         struct cfq_queue *__cfqq;
1527         sector_t sector = cfqd->last_position;
1528
1529         if (RB_EMPTY_ROOT(root))
1530                 return NULL;
1531
1532         /*
1533          * First, if we find a request starting at the end of the last
1534          * request, choose it.
1535          */
1536         __cfqq = cfq_prio_tree_lookup(cfqd, root, sector, &parent, NULL);
1537         if (__cfqq)
1538                 return __cfqq;
1539
1540         /*
1541          * If the exact sector wasn't found, the parent of the NULL leaf
1542          * will contain the closest sector.
1543          */
1544         __cfqq = rb_entry(parent, struct cfq_queue, p_node);
1545         if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
1546                 return __cfqq;
1547
1548         if (blk_rq_pos(__cfqq->next_rq) < sector)
1549                 node = rb_next(&__cfqq->p_node);
1550         else
1551                 node = rb_prev(&__cfqq->p_node);
1552         if (!node)
1553                 return NULL;
1554
1555         __cfqq = rb_entry(node, struct cfq_queue, p_node);
1556         if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
1557                 return __cfqq;
1558
1559         return NULL;
1560 }
1561
1562 /*
1563  * cfqd - obvious
1564  * cur_cfqq - passed in so that we don't decide that the current queue is
1565  *            closely cooperating with itself.
1566  *
1567  * So, basically we're assuming that that cur_cfqq has dispatched at least
1568  * one request, and that cfqd->last_position reflects a position on the disk
1569  * associated with the I/O issued by cur_cfqq.  I'm not sure this is a valid
1570  * assumption.
1571  */
1572 static struct cfq_queue *cfq_close_cooperator(struct cfq_data *cfqd,
1573                                               struct cfq_queue *cur_cfqq)
1574 {
1575         struct cfq_queue *cfqq;
1576
1577         if (!cfq_cfqq_sync(cur_cfqq))
1578                 return NULL;
1579         if (CFQQ_SEEKY(cur_cfqq))
1580                 return NULL;
1581
1582         /*
1583          * We should notice if some of the queues are cooperating, eg
1584          * working closely on the same area of the disk. In that case,
1585          * we can group them together and don't waste time idling.
1586          */
1587         cfqq = cfqq_close(cfqd, cur_cfqq);
1588         if (!cfqq)
1589                 return NULL;
1590
1591         /*
1592          * It only makes sense to merge sync queues.
1593          */
1594         if (!cfq_cfqq_sync(cfqq))
1595                 return NULL;
1596         if (CFQQ_SEEKY(cfqq))
1597                 return NULL;
1598
1599         /*
1600          * Do not merge queues of different priority classes
1601          */
1602         if (cfq_class_rt(cfqq) != cfq_class_rt(cur_cfqq))
1603                 return NULL;
1604
1605         return cfqq;
1606 }
1607
1608 /*
1609  * Determine whether we should enforce idle window for this queue.
1610  */
1611
1612 static bool cfq_should_idle(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1613 {
1614         enum wl_prio_t prio = cfqq_prio(cfqq);
1615         struct cfq_rb_root *service_tree = cfqq->service_tree;
1616
1617         BUG_ON(!service_tree);
1618         BUG_ON(!service_tree->count);
1619
1620         /* We never do for idle class queues. */
1621         if (prio == IDLE_WORKLOAD)
1622                 return false;
1623
1624         /* We do for queues that were marked with idle window flag. */
1625         if (cfq_cfqq_idle_window(cfqq))
1626                 return true;
1627
1628         /*
1629          * Otherwise, we do only if they are the last ones
1630          * in their service tree.
1631          */
1632         return service_tree->count == 1;
1633 }
1634
1635 static void cfq_arm_slice_timer(struct cfq_data *cfqd)
1636 {
1637         struct cfq_queue *cfqq = cfqd->active_queue;
1638         struct cfq_io_context *cic;
1639         unsigned long sl;
1640
1641         /*
1642          * SSD device without seek penalty, disable idling. But only do so
1643          * for devices that support queuing, otherwise we still have a problem
1644          * with sync vs async workloads.
1645          */
1646         if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag)
1647                 return;
1648
1649         WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
1650         WARN_ON(cfq_cfqq_slice_new(cfqq));
1651
1652         /*
1653          * idle is disabled, either manually or by past process history
1654          */
1655         if (!cfqd->cfq_slice_idle || !cfq_should_idle(cfqd, cfqq))
1656                 return;
1657
1658         /*
1659          * still active requests from this queue, don't idle
1660          */
1661         if (cfqq->dispatched)
1662                 return;
1663
1664         /*
1665          * task has exited, don't wait
1666          */
1667         cic = cfqd->active_cic;
1668         if (!cic || !atomic_read(&cic->ioc->nr_tasks))
1669                 return;
1670
1671         /*
1672          * If our average think time is larger than the remaining time
1673          * slice, then don't idle. This avoids overrunning the allotted
1674          * time slice.
1675          */
1676         if (sample_valid(cic->ttime_samples) &&
1677             (cfqq->slice_end - jiffies < cic->ttime_mean))
1678                 return;
1679
1680         cfq_mark_cfqq_wait_request(cfqq);
1681
1682         sl = cfqd->cfq_slice_idle;
1683
1684         mod_timer(&cfqd->idle_slice_timer, jiffies + sl);
1685         cfq_log_cfqq(cfqd, cfqq, "arm_idle: %lu", sl);
1686 }
1687
1688 /*
1689  * Move request from internal lists to the request queue dispatch list.
1690  */
1691 static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
1692 {
1693         struct cfq_data *cfqd = q->elevator->elevator_data;
1694         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1695
1696         cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
1697
1698         cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
1699         cfq_remove_request(rq);
1700         cfqq->dispatched++;
1701         elv_dispatch_sort(q, rq);
1702
1703         if (cfq_cfqq_sync(cfqq))
1704                 cfqd->sync_flight++;
1705 }
1706
1707 /*
1708  * return expired entry, or NULL to just start from scratch in rbtree
1709  */
1710 static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
1711 {
1712         struct request *rq = NULL;
1713
1714         if (cfq_cfqq_fifo_expire(cfqq))
1715                 return NULL;
1716
1717         cfq_mark_cfqq_fifo_expire(cfqq);
1718
1719         if (list_empty(&cfqq->fifo))
1720                 return NULL;
1721
1722         rq = rq_entry_fifo(cfqq->fifo.next);
1723         if (time_before(jiffies, rq_fifo_time(rq)))
1724                 rq = NULL;
1725
1726         cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
1727         return rq;
1728 }
1729
1730 static inline int
1731 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1732 {
1733         const int base_rq = cfqd->cfq_slice_async_rq;
1734
1735         WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
1736
1737         return 2 * (base_rq + base_rq * (CFQ_PRIO_LISTS - 1 - cfqq->ioprio));
1738 }
1739
1740 /*
1741  * Must be called with the queue_lock held.
1742  */
1743 static int cfqq_process_refs(struct cfq_queue *cfqq)
1744 {
1745         int process_refs, io_refs;
1746
1747         io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
1748         process_refs = atomic_read(&cfqq->ref) - io_refs;
1749         BUG_ON(process_refs < 0);
1750         return process_refs;
1751 }
1752
1753 static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
1754 {
1755         int process_refs, new_process_refs;
1756         struct cfq_queue *__cfqq;
1757
1758         /* Avoid a circular list and skip interim queue merges */
1759         while ((__cfqq = new_cfqq->new_cfqq)) {
1760                 if (__cfqq == cfqq)
1761                         return;
1762                 new_cfqq = __cfqq;
1763         }
1764
1765         process_refs = cfqq_process_refs(cfqq);
1766         /*
1767          * If the process for the cfqq has gone away, there is no
1768          * sense in merging the queues.
1769          */
1770         if (process_refs == 0)
1771                 return;
1772
1773         /*
1774          * Merge in the direction of the lesser amount of work.
1775          */
1776         new_process_refs = cfqq_process_refs(new_cfqq);
1777         if (new_process_refs >= process_refs) {
1778                 cfqq->new_cfqq = new_cfqq;
1779                 atomic_add(process_refs, &new_cfqq->ref);
1780         } else {
1781                 new_cfqq->new_cfqq = cfqq;
1782                 atomic_add(new_process_refs, &cfqq->ref);
1783         }
1784 }
1785
1786 static enum wl_type_t cfq_choose_wl(struct cfq_data *cfqd,
1787                                 struct cfq_group *cfqg, enum wl_prio_t prio,
1788                                 bool prio_changed)
1789 {
1790         struct cfq_queue *queue;
1791         int i;
1792         bool key_valid = false;
1793         unsigned long lowest_key = 0;
1794         enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
1795
1796         if (prio_changed) {
1797                 /*
1798                  * When priorities switched, we prefer starting
1799                  * from SYNC_NOIDLE (first choice), or just SYNC
1800                  * over ASYNC
1801                  */
1802                 if (service_tree_for(cfqg, prio, cur_best, cfqd)->count)
1803                         return cur_best;
1804                 cur_best = SYNC_WORKLOAD;
1805                 if (service_tree_for(cfqg, prio, cur_best, cfqd)->count)
1806                         return cur_best;
1807
1808                 return ASYNC_WORKLOAD;
1809         }
1810
1811         for (i = 0; i < 3; ++i) {
1812                 /* otherwise, select the one with lowest rb_key */
1813                 queue = cfq_rb_first(service_tree_for(cfqg, prio, i, cfqd));
1814                 if (queue &&
1815                     (!key_valid || time_before(queue->rb_key, lowest_key))) {
1816                         lowest_key = queue->rb_key;
1817                         cur_best = i;
1818                         key_valid = true;
1819                 }
1820         }
1821
1822         return cur_best;
1823 }
1824
1825 static void choose_service_tree(struct cfq_data *cfqd, struct cfq_group *cfqg)
1826 {
1827         enum wl_prio_t previous_prio = cfqd->serving_prio;
1828         bool prio_changed;
1829         unsigned slice;
1830         unsigned count;
1831         struct cfq_rb_root *st;
1832         unsigned group_slice;
1833
1834         if (!cfqg) {
1835                 cfqd->serving_prio = IDLE_WORKLOAD;
1836                 cfqd->workload_expires = jiffies + 1;
1837                 return;
1838         }
1839
1840         /* Choose next priority. RT > BE > IDLE */
1841         if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
1842                 cfqd->serving_prio = RT_WORKLOAD;
1843         else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
1844                 cfqd->serving_prio = BE_WORKLOAD;
1845         else {
1846                 cfqd->serving_prio = IDLE_WORKLOAD;
1847                 cfqd->workload_expires = jiffies + 1;
1848                 return;
1849         }
1850
1851         /*
1852          * For RT and BE, we have to choose also the type
1853          * (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
1854          * expiration time
1855          */
1856         prio_changed = (cfqd->serving_prio != previous_prio);
1857         st = service_tree_for(cfqg, cfqd->serving_prio, cfqd->serving_type,
1858                                 cfqd);
1859         count = st->count;
1860
1861         /*
1862          * If priority didn't change, check workload expiration,
1863          * and that we still have other queues ready
1864          */
1865         if (!prio_changed && count &&
1866             !time_after(jiffies, cfqd->workload_expires))
1867                 return;
1868
1869         /* otherwise select new workload type */
1870         cfqd->serving_type =
1871                 cfq_choose_wl(cfqd, cfqg, cfqd->serving_prio, prio_changed);
1872         st = service_tree_for(cfqg, cfqd->serving_prio, cfqd->serving_type,
1873                                 cfqd);
1874         count = st->count;
1875
1876         /*
1877          * the workload slice is computed as a fraction of target latency
1878          * proportional to the number of queues in that workload, over
1879          * all the queues in the same priority class
1880          */
1881         group_slice = cfq_group_slice(cfqd, cfqg);
1882
1883         slice = group_slice * count /
1884                 max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_prio],
1885                       cfq_group_busy_queues_wl(cfqd->serving_prio, cfqd, cfqg));
1886
1887         if (cfqd->serving_type == ASYNC_WORKLOAD)
1888                 /* async workload slice is scaled down according to
1889                  * the sync/async slice ratio. */
1890                 slice = slice * cfqd->cfq_slice[0] / cfqd->cfq_slice[1];
1891         else
1892                 /* sync workload slice is at least 2 * cfq_slice_idle */
1893                 slice = max(slice, 2 * cfqd->cfq_slice_idle);
1894
1895         slice = max_t(unsigned, slice, CFQ_MIN_TT);
1896         cfqd->workload_expires = jiffies + slice;
1897         cfqd->noidle_tree_requires_idle = false;
1898 }
1899
1900 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
1901 {
1902         struct cfq_rb_root *st = &cfqd->grp_service_tree;
1903         struct cfq_group *cfqg;
1904
1905         if (RB_EMPTY_ROOT(&st->rb))
1906                 return NULL;
1907         cfqg = cfq_rb_first_group(st);
1908         st->active = &cfqg->rb_node;
1909         update_min_vdisktime(st);
1910         return cfqg;
1911 }
1912
1913 static void cfq_choose_cfqg(struct cfq_data *cfqd)
1914 {
1915         struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
1916
1917         cfqd->serving_group = cfqg;
1918
1919         /* Restore the workload type data */
1920         if (cfqg->saved_workload_slice) {
1921                 cfqd->workload_expires = jiffies + cfqg->saved_workload_slice;
1922                 cfqd->serving_type = cfqg->saved_workload;
1923                 cfqd->serving_prio = cfqg->saved_serving_prio;
1924         }
1925         choose_service_tree(cfqd, cfqg);
1926 }
1927
1928 /*
1929  * Select a queue for service. If we have a current active queue,
1930  * check whether to continue servicing it, or retrieve and set a new one.
1931  */
1932 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
1933 {
1934         struct cfq_queue *cfqq, *new_cfqq = NULL;
1935
1936         cfqq = cfqd->active_queue;
1937         if (!cfqq)
1938                 goto new_queue;
1939
1940         if (!cfqd->rq_queued)
1941                 return NULL;
1942         /*
1943          * The active queue has run out of time, expire it and select new.
1944          */
1945         if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq))
1946                 goto expire;
1947
1948         /*
1949          * The active queue has requests and isn't expired, allow it to
1950          * dispatch.
1951          */
1952         if (!RB_EMPTY_ROOT(&cfqq->sort_list))
1953                 goto keep_queue;
1954
1955         /*
1956          * If another queue has a request waiting within our mean seek
1957          * distance, let it run.  The expire code will check for close
1958          * cooperators and put the close queue at the front of the service
1959          * tree.  If possible, merge the expiring queue with the new cfqq.
1960          */
1961         new_cfqq = cfq_close_cooperator(cfqd, cfqq);
1962         if (new_cfqq) {
1963                 if (!cfqq->new_cfqq)
1964                         cfq_setup_merge(cfqq, new_cfqq);
1965                 goto expire;
1966         }
1967
1968         /*
1969          * No requests pending. If the active queue still has requests in
1970          * flight or is idling for a new request, allow either of these
1971          * conditions to happen (or time out) before selecting a new queue.
1972          */
1973         if (timer_pending(&cfqd->idle_slice_timer) ||
1974             (cfqq->dispatched && cfq_should_idle(cfqd, cfqq))) {
1975                 cfqq = NULL;
1976                 goto keep_queue;
1977         }
1978
1979 expire:
1980         cfq_slice_expired(cfqd, 0);
1981 new_queue:
1982         /*
1983          * Current queue expired. Check if we have to switch to a new
1984          * service tree
1985          */
1986         if (!new_cfqq)
1987                 cfq_choose_cfqg(cfqd);
1988
1989         cfqq = cfq_set_active_queue(cfqd, new_cfqq);
1990 keep_queue:
1991         return cfqq;
1992 }
1993
1994 static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
1995 {
1996         int dispatched = 0;
1997
1998         while (cfqq->next_rq) {
1999                 cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
2000                 dispatched++;
2001         }
2002
2003         BUG_ON(!list_empty(&cfqq->fifo));
2004
2005         /* By default cfqq is not expired if it is empty. Do it explicitly */
2006         __cfq_slice_expired(cfqq->cfqd, cfqq, 0);
2007         return dispatched;
2008 }
2009
2010 /*
2011  * Drain our current requests. Used for barriers and when switching
2012  * io schedulers on-the-fly.
2013  */
2014 static int cfq_forced_dispatch(struct cfq_data *cfqd)
2015 {
2016         struct cfq_queue *cfqq;
2017         int dispatched = 0;
2018
2019         while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL)
2020                 dispatched += __cfq_forced_dispatch_cfqq(cfqq);
2021
2022         cfq_slice_expired(cfqd, 0);
2023         BUG_ON(cfqd->busy_queues);
2024
2025         cfq_log(cfqd, "forced_dispatch=%d", dispatched);
2026         return dispatched;
2027 }
2028
2029 static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2030 {
2031         unsigned int max_dispatch;
2032
2033         /*
2034          * Drain async requests before we start sync IO
2035          */
2036         if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_driver[BLK_RW_ASYNC])
2037                 return false;
2038
2039         /*
2040          * If this is an async queue and we have sync IO in flight, let it wait
2041          */
2042         if (cfqd->sync_flight && !cfq_cfqq_sync(cfqq))
2043                 return false;
2044
2045         max_dispatch = cfqd->cfq_quantum;
2046         if (cfq_class_idle(cfqq))
2047                 max_dispatch = 1;
2048
2049         /*
2050          * Does this cfqq already have too much IO in flight?
2051          */
2052         if (cfqq->dispatched >= max_dispatch) {
2053                 /*
2054                  * idle queue must always only have a single IO in flight
2055                  */
2056                 if (cfq_class_idle(cfqq))
2057                         return false;
2058
2059                 /*
2060                  * We have other queues, don't allow more IO from this one
2061                  */
2062                 if (cfqd->busy_queues > 1)
2063                         return false;
2064
2065                 /*
2066                  * Sole queue user, no limit
2067                  */
2068                 max_dispatch = -1;
2069         }
2070
2071         /*
2072          * Async queues must wait a bit before being allowed dispatch.
2073          * We also ramp up the dispatch depth gradually for async IO,
2074          * based on the last sync IO we serviced
2075          */
2076         if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
2077                 unsigned long last_sync = jiffies - cfqd->last_end_sync_rq;
2078                 unsigned int depth;
2079
2080                 depth = last_sync / cfqd->cfq_slice[1];
2081                 if (!depth && !cfqq->dispatched)
2082                         depth = 1;
2083                 if (depth < max_dispatch)
2084                         max_dispatch = depth;
2085         }
2086
2087         /*
2088          * If we're below the current max, allow a dispatch
2089          */
2090         return cfqq->dispatched < max_dispatch;
2091 }
2092
2093 /*
2094  * Dispatch a request from cfqq, moving them to the request queue
2095  * dispatch list.
2096  */
2097 static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2098 {
2099         struct request *rq;
2100
2101         BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
2102
2103         if (!cfq_may_dispatch(cfqd, cfqq))
2104                 return false;
2105
2106         /*
2107          * follow expired path, else get first next available
2108          */
2109         rq = cfq_check_fifo(cfqq);
2110         if (!rq)
2111                 rq = cfqq->next_rq;
2112
2113         /*
2114          * insert request into driver dispatch list
2115          */
2116         cfq_dispatch_insert(cfqd->queue, rq);
2117
2118         if (!cfqd->active_cic) {
2119                 struct cfq_io_context *cic = RQ_CIC(rq);
2120
2121                 atomic_long_inc(&cic->ioc->refcount);
2122                 cfqd->active_cic = cic;
2123         }
2124
2125         return true;
2126 }
2127
2128 /*
2129  * Find the cfqq that we need to service and move a request from that to the
2130  * dispatch list
2131  */
2132 static int cfq_dispatch_requests(struct request_queue *q, int force)
2133 {
2134         struct cfq_data *cfqd = q->elevator->elevator_data;
2135         struct cfq_queue *cfqq;
2136
2137         if (!cfqd->busy_queues)
2138                 return 0;
2139
2140         if (unlikely(force))
2141                 return cfq_forced_dispatch(cfqd);
2142
2143         cfqq = cfq_select_queue(cfqd);
2144         if (!cfqq)
2145                 return 0;
2146
2147         /*
2148          * Dispatch a request from this cfqq, if it is allowed
2149          */
2150         if (!cfq_dispatch_request(cfqd, cfqq))
2151                 return 0;
2152
2153         cfqq->slice_dispatch++;
2154         cfq_clear_cfqq_must_dispatch(cfqq);
2155
2156         /*
2157          * expire an async queue immediately if it has used up its slice. idle
2158          * queue always expire after 1 dispatch round.
2159          */
2160         if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
2161             cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
2162             cfq_class_idle(cfqq))) {
2163                 cfqq->slice_end = jiffies + 1;
2164                 cfq_slice_expired(cfqd, 0);
2165         }
2166
2167         cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
2168         return 1;
2169 }
2170
2171 /*
2172  * task holds one reference to the queue, dropped when task exits. each rq
2173  * in-flight on this queue also holds a reference, dropped when rq is freed.
2174  *
2175  * queue lock must be held here.
2176  */
2177 static void cfq_put_queue(struct cfq_queue *cfqq)
2178 {
2179         struct cfq_data *cfqd = cfqq->cfqd;
2180
2181         BUG_ON(atomic_read(&cfqq->ref) <= 0);
2182
2183         if (!atomic_dec_and_test(&cfqq->ref))
2184                 return;
2185
2186         cfq_log_cfqq(cfqd, cfqq, "put_queue");
2187         BUG_ON(rb_first(&cfqq->sort_list));
2188         BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
2189
2190         if (unlikely(cfqd->active_queue == cfqq)) {
2191                 __cfq_slice_expired(cfqd, cfqq, 0);
2192                 cfq_schedule_dispatch(cfqd);
2193         }
2194
2195         BUG_ON(cfq_cfqq_on_rr(cfqq));
2196         kmem_cache_free(cfq_pool, cfqq);
2197 }
2198
2199 /*
2200  * Must always be called with the rcu_read_lock() held
2201  */
2202 static void
2203 __call_for_each_cic(struct io_context *ioc,
2204                     void (*func)(struct io_context *, struct cfq_io_context *))
2205 {
2206         struct cfq_io_context *cic;
2207         struct hlist_node *n;
2208
2209         hlist_for_each_entry_rcu(cic, n, &ioc->cic_list, cic_list)
2210                 func(ioc, cic);
2211 }
2212
2213 /*
2214  * Call func for each cic attached to this ioc.
2215  */
2216 static void
2217 call_for_each_cic(struct io_context *ioc,
2218                   void (*func)(struct io_context *, struct cfq_io_context *))
2219 {
2220         rcu_read_lock();
2221         __call_for_each_cic(ioc, func);
2222         rcu_read_unlock();
2223 }
2224
2225 static void cfq_cic_free_rcu(struct rcu_head *head)
2226 {
2227         struct cfq_io_context *cic;
2228
2229         cic = container_of(head, struct cfq_io_context, rcu_head);
2230
2231         kmem_cache_free(cfq_ioc_pool, cic);
2232         elv_ioc_count_dec(cfq_ioc_count);
2233
2234         if (ioc_gone) {
2235                 /*
2236                  * CFQ scheduler is exiting, grab exit lock and check
2237                  * the pending io context count. If it hits zero,
2238                  * complete ioc_gone and set it back to NULL
2239                  */
2240                 spin_lock(&ioc_gone_lock);
2241                 if (ioc_gone && !elv_ioc_count_read(cfq_ioc_count)) {
2242                         complete(ioc_gone);
2243                         ioc_gone = NULL;
2244                 }
2245                 spin_unlock(&ioc_gone_lock);
2246         }
2247 }
2248
2249 static void cfq_cic_free(struct cfq_io_context *cic)
2250 {
2251         call_rcu(&cic->rcu_head, cfq_cic_free_rcu);
2252 }
2253
2254 static void cic_free_func(struct io_context *ioc, struct cfq_io_context *cic)
2255 {
2256         unsigned long flags;
2257
2258         BUG_ON(!cic->dead_key);
2259
2260         spin_lock_irqsave(&ioc->lock, flags);
2261         radix_tree_delete(&ioc->radix_root, cic->dead_key);
2262         hlist_del_rcu(&cic->cic_list);
2263         spin_unlock_irqrestore(&ioc->lock, flags);
2264
2265         cfq_cic_free(cic);
2266 }
2267
2268 /*
2269  * Must be called with rcu_read_lock() held or preemption otherwise disabled.
2270  * Only two callers of this - ->dtor() which is called with the rcu_read_lock(),
2271  * and ->trim() which is called with the task lock held
2272  */
2273 static void cfq_free_io_context(struct io_context *ioc)
2274 {
2275         /*
2276          * ioc->refcount is zero here, or we are called from elv_unregister(),
2277          * so no more cic's are allowed to be linked into this ioc.  So it
2278          * should be ok to iterate over the known list, we will see all cic's
2279          * since no new ones are added.
2280          */
2281         __call_for_each_cic(ioc, cic_free_func);
2282 }
2283
2284 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2285 {
2286         struct cfq_queue *__cfqq, *next;
2287
2288         if (unlikely(cfqq == cfqd->active_queue)) {
2289                 __cfq_slice_expired(cfqd, cfqq, 0);
2290                 cfq_schedule_dispatch(cfqd);
2291         }
2292
2293         /*
2294          * If this queue was scheduled to merge with another queue, be
2295          * sure to drop the reference taken on that queue (and others in
2296          * the merge chain).  See cfq_setup_merge and cfq_merge_cfqqs.
2297          */
2298         __cfqq = cfqq->new_cfqq;
2299         while (__cfqq) {
2300                 if (__cfqq == cfqq) {
2301                         WARN(1, "cfqq->new_cfqq loop detected\n");
2302                         break;
2303                 }
2304                 next = __cfqq->new_cfqq;
2305                 cfq_put_queue(__cfqq);
2306                 __cfqq = next;
2307         }
2308
2309         cfq_put_queue(cfqq);
2310 }
2311
2312 static void __cfq_exit_single_io_context(struct cfq_data *cfqd,
2313                                          struct cfq_io_context *cic)
2314 {
2315         struct io_context *ioc = cic->ioc;
2316
2317         list_del_init(&cic->queue_list);
2318
2319         /*
2320          * Make sure key == NULL is seen for dead queues
2321          */
2322         smp_wmb();
2323         cic->dead_key = (unsigned long) cic->key;
2324         cic->key = NULL;
2325
2326         if (ioc->ioc_data == cic)
2327                 rcu_assign_pointer(ioc->ioc_data, NULL);
2328
2329         if (cic->cfqq[BLK_RW_ASYNC]) {
2330                 cfq_exit_cfqq(cfqd, cic->cfqq[BLK_RW_ASYNC]);
2331                 cic->cfqq[BLK_RW_ASYNC] = NULL;
2332         }
2333
2334         if (cic->cfqq[BLK_RW_SYNC]) {
2335                 cfq_exit_cfqq(cfqd, cic->cfqq[BLK_RW_SYNC]);
2336                 cic->cfqq[BLK_RW_SYNC] = NULL;
2337         }
2338 }
2339
2340 static void cfq_exit_single_io_context(struct io_context *ioc,
2341                                        struct cfq_io_context *cic)
2342 {
2343         struct cfq_data *cfqd = cic->key;
2344
2345         if (cfqd) {
2346                 struct request_queue *q = cfqd->queue;
2347                 unsigned long flags;
2348
2349                 spin_lock_irqsave(q->queue_lock, flags);
2350
2351                 /*
2352                  * Ensure we get a fresh copy of the ->key to prevent
2353                  * race between exiting task and queue
2354                  */
2355                 smp_read_barrier_depends();
2356                 if (cic->key)
2357                         __cfq_exit_single_io_context(cfqd, cic);
2358
2359                 spin_unlock_irqrestore(q->queue_lock, flags);
2360         }
2361 }
2362
2363 /*
2364  * The process that ioc belongs to has exited, we need to clean up
2365  * and put the internal structures we have that belongs to that process.
2366  */
2367 static void cfq_exit_io_context(struct io_context *ioc)
2368 {
2369         call_for_each_cic(ioc, cfq_exit_single_io_context);
2370 }
2371
2372 static struct cfq_io_context *
2373 cfq_alloc_io_context(struct cfq_data *cfqd, gfp_t gfp_mask)
2374 {
2375         struct cfq_io_context *cic;
2376
2377         cic = kmem_cache_alloc_node(cfq_ioc_pool, gfp_mask | __GFP_ZERO,
2378                                                         cfqd->queue->node);
2379         if (cic) {
2380                 cic->last_end_request = jiffies;
2381                 INIT_LIST_HEAD(&cic->queue_list);
2382                 INIT_HLIST_NODE(&cic->cic_list);
2383                 cic->dtor = cfq_free_io_context;
2384                 cic->exit = cfq_exit_io_context;
2385                 elv_ioc_count_inc(cfq_ioc_count);
2386         }
2387
2388         return cic;
2389 }
2390
2391 static void cfq_init_prio_data(struct cfq_queue *cfqq, struct io_context *ioc)
2392 {
2393         struct task_struct *tsk = current;
2394         int ioprio_class;
2395
2396         if (!cfq_cfqq_prio_changed(cfqq))
2397                 return;
2398
2399         ioprio_class = IOPRIO_PRIO_CLASS(ioc->ioprio);
2400         switch (ioprio_class) {
2401         default:
2402                 printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
2403         case IOPRIO_CLASS_NONE:
2404                 /*
2405                  * no prio set, inherit CPU scheduling settings
2406                  */
2407                 cfqq->ioprio = task_nice_ioprio(tsk);
2408                 cfqq->ioprio_class = task_nice_ioclass(tsk);
2409                 break;
2410         case IOPRIO_CLASS_RT:
2411                 cfqq->ioprio = task_ioprio(ioc);
2412                 cfqq->ioprio_class = IOPRIO_CLASS_RT;
2413                 break;
2414         case IOPRIO_CLASS_BE:
2415                 cfqq->ioprio = task_ioprio(ioc);
2416                 cfqq->ioprio_class = IOPRIO_CLASS_BE;
2417                 break;
2418         case IOPRIO_CLASS_IDLE:
2419                 cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
2420                 cfqq->ioprio = 7;
2421                 cfq_clear_cfqq_idle_window(cfqq);
2422                 break;
2423         }
2424
2425         /*
2426          * keep track of original prio settings in case we have to temporarily
2427          * elevate the priority of this queue
2428          */
2429         cfqq->org_ioprio = cfqq->ioprio;
2430         cfqq->org_ioprio_class = cfqq->ioprio_class;
2431         cfq_clear_cfqq_prio_changed(cfqq);
2432 }
2433
2434 static void changed_ioprio(struct io_context *ioc, struct cfq_io_context *cic)
2435 {
2436         struct cfq_data *cfqd = cic->key;
2437         struct cfq_queue *cfqq;
2438         unsigned long flags;
2439
2440         if (unlikely(!cfqd))
2441                 return;
2442
2443         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
2444
2445         cfqq = cic->cfqq[BLK_RW_ASYNC];
2446         if (cfqq) {
2447                 struct cfq_queue *new_cfqq;
2448                 new_cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic->ioc,
2449                                                 GFP_ATOMIC);
2450                 if (new_cfqq) {
2451                         cic->cfqq[BLK_RW_ASYNC] = new_cfqq;
2452                         cfq_put_queue(cfqq);
2453                 }
2454         }
2455
2456         cfqq = cic->cfqq[BLK_RW_SYNC];
2457         if (cfqq)
2458                 cfq_mark_cfqq_prio_changed(cfqq);
2459
2460         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
2461 }
2462
2463 static void cfq_ioc_set_ioprio(struct io_context *ioc)
2464 {
2465         call_for_each_cic(ioc, changed_ioprio);
2466         ioc->ioprio_changed = 0;
2467 }
2468
2469 static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2470                           pid_t pid, bool is_sync)
2471 {
2472         RB_CLEAR_NODE(&cfqq->rb_node);
2473         RB_CLEAR_NODE(&cfqq->p_node);
2474         INIT_LIST_HEAD(&cfqq->fifo);
2475
2476         atomic_set(&cfqq->ref, 0);
2477         cfqq->cfqd = cfqd;
2478
2479         cfq_mark_cfqq_prio_changed(cfqq);
2480
2481         if (is_sync) {
2482                 if (!cfq_class_idle(cfqq))
2483                         cfq_mark_cfqq_idle_window(cfqq);
2484                 cfq_mark_cfqq_sync(cfqq);
2485         }
2486         cfqq->pid = pid;
2487 }
2488
2489 static struct cfq_queue *
2490 cfq_find_alloc_queue(struct cfq_data *cfqd, bool is_sync,
2491                      struct io_context *ioc, gfp_t gfp_mask)
2492 {
2493         struct cfq_queue *cfqq, *new_cfqq = NULL;
2494         struct cfq_io_context *cic;
2495         struct cfq_group *cfqg;
2496
2497 retry:
2498         cfqg = cfq_get_cfqg(cfqd, 1);
2499         cic = cfq_cic_lookup(cfqd, ioc);
2500         /* cic always exists here */
2501         cfqq = cic_to_cfqq(cic, is_sync);
2502
2503         /*
2504          * Always try a new alloc if we fell back to the OOM cfqq
2505          * originally, since it should just be a temporary situation.
2506          */
2507         if (!cfqq || cfqq == &cfqd->oom_cfqq) {
2508                 cfqq = NULL;
2509                 if (new_cfqq) {
2510                         cfqq = new_cfqq;
2511                         new_cfqq = NULL;
2512                 } else if (gfp_mask & __GFP_WAIT) {
2513                         spin_unlock_irq(cfqd->queue->queue_lock);
2514                         new_cfqq = kmem_cache_alloc_node(cfq_pool,
2515                                         gfp_mask | __GFP_ZERO,
2516                                         cfqd->queue->node);
2517                         spin_lock_irq(cfqd->queue->queue_lock);
2518                         if (new_cfqq)
2519                                 goto retry;
2520                 } else {
2521                         cfqq = kmem_cache_alloc_node(cfq_pool,
2522                                         gfp_mask | __GFP_ZERO,
2523                                         cfqd->queue->node);
2524                 }
2525
2526                 if (cfqq) {
2527                         cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
2528                         cfq_init_prio_data(cfqq, ioc);
2529                         cfq_link_cfqq_cfqg(cfqq, cfqg);
2530                         cfq_log_cfqq(cfqd, cfqq, "alloced");
2531                 } else
2532                         cfqq = &cfqd->oom_cfqq;
2533         }
2534
2535         if (new_cfqq)
2536                 kmem_cache_free(cfq_pool, new_cfqq);
2537
2538         return cfqq;
2539 }
2540
2541 static struct cfq_queue **
2542 cfq_async_queue_prio(struct cfq_data *cfqd, int ioprio_class, int ioprio)
2543 {
2544         switch (ioprio_class) {
2545         case IOPRIO_CLASS_RT:
2546                 return &cfqd->async_cfqq[0][ioprio];
2547         case IOPRIO_CLASS_BE:
2548                 return &cfqd->async_cfqq[1][ioprio];
2549         case IOPRIO_CLASS_IDLE:
2550                 return &cfqd->async_idle_cfqq;
2551         default:
2552                 BUG();
2553         }
2554 }
2555
2556 static struct cfq_queue *
2557 cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct io_context *ioc,
2558               gfp_t gfp_mask)
2559 {
2560         const int ioprio = task_ioprio(ioc);
2561         const int ioprio_class = task_ioprio_class(ioc);
2562         struct cfq_queue **async_cfqq = NULL;
2563         struct cfq_queue *cfqq = NULL;
2564
2565         if (!is_sync) {
2566                 async_cfqq = cfq_async_queue_prio(cfqd, ioprio_class, ioprio);
2567                 cfqq = *async_cfqq;
2568         }
2569
2570         if (!cfqq)
2571                 cfqq = cfq_find_alloc_queue(cfqd, is_sync, ioc, gfp_mask);
2572
2573         /*
2574          * pin the queue now that it's allocated, scheduler exit will prune it
2575          */
2576         if (!is_sync && !(*async_cfqq)) {
2577                 atomic_inc(&cfqq->ref);
2578                 *async_cfqq = cfqq;
2579         }
2580
2581         atomic_inc(&cfqq->ref);
2582         return cfqq;
2583 }
2584
2585 /*
2586  * We drop cfq io contexts lazily, so we may find a dead one.
2587  */
2588 static void
2589 cfq_drop_dead_cic(struct cfq_data *cfqd, struct io_context *ioc,
2590                   struct cfq_io_context *cic)
2591 {
2592         unsigned long flags;
2593
2594         WARN_ON(!list_empty(&cic->queue_list));
2595
2596         spin_lock_irqsave(&ioc->lock, flags);
2597
2598         BUG_ON(ioc->ioc_data == cic);
2599
2600         radix_tree_delete(&ioc->radix_root, (unsigned long) cfqd);
2601         hlist_del_rcu(&cic->cic_list);
2602         spin_unlock_irqrestore(&ioc->lock, flags);
2603
2604         cfq_cic_free(cic);
2605 }
2606
2607 static struct cfq_io_context *
2608 cfq_cic_lookup(struct cfq_data *cfqd, struct io_context *ioc)
2609 {
2610         struct cfq_io_context *cic;
2611         unsigned long flags;
2612         void *k;
2613
2614         if (unlikely(!ioc))
2615                 return NULL;
2616
2617         rcu_read_lock();
2618
2619         /*
2620          * we maintain a last-hit cache, to avoid browsing over the tree
2621          */
2622         cic = rcu_dereference(ioc->ioc_data);
2623         if (cic && cic->key == cfqd) {
2624                 rcu_read_unlock();
2625                 return cic;
2626         }
2627
2628         do {
2629                 cic = radix_tree_lookup(&ioc->radix_root, (unsigned long) cfqd);
2630                 rcu_read_unlock();
2631                 if (!cic)
2632                         break;
2633                 /* ->key must be copied to avoid race with cfq_exit_queue() */
2634                 k = cic->key;
2635                 if (unlikely(!k)) {
2636                         cfq_drop_dead_cic(cfqd, ioc, cic);
2637                         rcu_read_lock();
2638                         continue;
2639                 }
2640
2641                 spin_lock_irqsave(&ioc->lock, flags);
2642                 rcu_assign_pointer(ioc->ioc_data, cic);
2643                 spin_unlock_irqrestore(&ioc->lock, flags);
2644                 break;
2645         } while (1);
2646
2647         return cic;
2648 }
2649
2650 /*
2651  * Add cic into ioc, using cfqd as the search key. This enables us to lookup
2652  * the process specific cfq io context when entered from the block layer.
2653  * Also adds the cic to a per-cfqd list, used when this queue is removed.
2654  */
2655 static int cfq_cic_link(struct cfq_data *cfqd, struct io_context *ioc,
2656                         struct cfq_io_context *cic, gfp_t gfp_mask)
2657 {
2658         unsigned long flags;
2659         int ret;
2660
2661         ret = radix_tree_preload(gfp_mask);
2662         if (!ret) {
2663                 cic->ioc = ioc;
2664                 cic->key = cfqd;
2665
2666                 spin_lock_irqsave(&ioc->lock, flags);
2667                 ret = radix_tree_insert(&ioc->radix_root,
2668                                                 (unsigned long) cfqd, cic);
2669                 if (!ret)
2670                         hlist_add_head_rcu(&cic->cic_list, &ioc->cic_list);
2671                 spin_unlock_irqrestore(&ioc->lock, flags);
2672
2673                 radix_tree_preload_end();
2674
2675                 if (!ret) {
2676                         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
2677                         list_add(&cic->queue_list, &cfqd->cic_list);
2678                         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
2679                 }
2680         }
2681
2682         if (ret)
2683                 printk(KERN_ERR "cfq: cic link failed!\n");
2684
2685         return ret;
2686 }
2687
2688 /*
2689  * Setup general io context and cfq io context. There can be several cfq
2690  * io contexts per general io context, if this process is doing io to more
2691  * than one device managed by cfq.
2692  */
2693 static struct cfq_io_context *
2694 cfq_get_io_context(struct cfq_data *cfqd, gfp_t gfp_mask)
2695 {
2696         struct io_context *ioc = NULL;
2697         struct cfq_io_context *cic;
2698
2699         might_sleep_if(gfp_mask & __GFP_WAIT);
2700
2701         ioc = get_io_context(gfp_mask, cfqd->queue->node);
2702         if (!ioc)
2703                 return NULL;
2704
2705         cic = cfq_cic_lookup(cfqd, ioc);
2706         if (cic)
2707                 goto out;
2708
2709         cic = cfq_alloc_io_context(cfqd, gfp_mask);
2710         if (cic == NULL)
2711                 goto err;
2712
2713         if (cfq_cic_link(cfqd, ioc, cic, gfp_mask))
2714                 goto err_free;
2715
2716 out:
2717         smp_read_barrier_depends();
2718         if (unlikely(ioc->ioprio_changed))
2719                 cfq_ioc_set_ioprio(ioc);
2720
2721         return cic;
2722 err_free:
2723         cfq_cic_free(cic);
2724 err:
2725         put_io_context(ioc);
2726         return NULL;
2727 }
2728
2729 static void
2730 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_io_context *cic)
2731 {
2732         unsigned long elapsed = jiffies - cic->last_end_request;
2733         unsigned long ttime = min(elapsed, 2UL * cfqd->cfq_slice_idle);
2734
2735         cic->ttime_samples = (7*cic->ttime_samples + 256) / 8;
2736         cic->ttime_total = (7*cic->ttime_total + 256*ttime) / 8;
2737         cic->ttime_mean = (cic->ttime_total + 128) / cic->ttime_samples;
2738 }
2739
2740 static void
2741 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2742                        struct request *rq)
2743 {
2744         sector_t sdist;
2745         u64 total;
2746
2747         if (!cfqq->last_request_pos)
2748                 sdist = 0;
2749         else if (cfqq->last_request_pos < blk_rq_pos(rq))
2750                 sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
2751         else
2752                 sdist = cfqq->last_request_pos - blk_rq_pos(rq);
2753
2754         /*
2755          * Don't allow the seek distance to get too large from the
2756          * odd fragment, pagein, etc
2757          */
2758         if (cfqq->seek_samples <= 60) /* second&third seek */
2759                 sdist = min(sdist, (cfqq->seek_mean * 4) + 2*1024*1024);
2760         else
2761                 sdist = min(sdist, (cfqq->seek_mean * 4) + 2*1024*64);
2762
2763         cfqq->seek_samples = (7*cfqq->seek_samples + 256) / 8;
2764         cfqq->seek_total = (7*cfqq->seek_total + (u64)256*sdist) / 8;
2765         total = cfqq->seek_total + (cfqq->seek_samples/2);
2766         do_div(total, cfqq->seek_samples);
2767         cfqq->seek_mean = (sector_t)total;
2768
2769         /*
2770          * If this cfqq is shared between multiple processes, check to
2771          * make sure that those processes are still issuing I/Os within
2772          * the mean seek distance.  If not, it may be time to break the
2773          * queues apart again.
2774          */
2775         if (cfq_cfqq_coop(cfqq)) {
2776                 if (CFQQ_SEEKY(cfqq) && !cfqq->seeky_start)
2777                         cfqq->seeky_start = jiffies;
2778                 else if (!CFQQ_SEEKY(cfqq))
2779                         cfqq->seeky_start = 0;
2780         }
2781 }
2782
2783 /*
2784  * Disable idle window if the process thinks too long or seeks so much that
2785  * it doesn't matter
2786  */
2787 static void
2788 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2789                        struct cfq_io_context *cic)
2790 {
2791         int old_idle, enable_idle;
2792
2793         /*
2794          * Don't idle for async or idle io prio class
2795          */
2796         if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
2797                 return;
2798
2799         enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
2800
2801         if (cfqq->queued[0] + cfqq->queued[1] >= 4)
2802                 cfq_mark_cfqq_deep(cfqq);
2803
2804         if (!atomic_read(&cic->ioc->nr_tasks) || !cfqd->cfq_slice_idle ||
2805             (!cfq_cfqq_deep(cfqq) && sample_valid(cfqq->seek_samples)
2806              && CFQQ_SEEKY(cfqq)))
2807                 enable_idle = 0;
2808         else if (sample_valid(cic->ttime_samples)) {
2809                 if (cic->ttime_mean > cfqd->cfq_slice_idle)
2810                         enable_idle = 0;
2811                 else
2812                         enable_idle = 1;
2813         }
2814
2815         if (old_idle != enable_idle) {
2816                 cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
2817                 if (enable_idle)
2818                         cfq_mark_cfqq_idle_window(cfqq);
2819                 else
2820                         cfq_clear_cfqq_idle_window(cfqq);
2821         }
2822 }
2823
2824 /*
2825  * Check if new_cfqq should preempt the currently active queue. Return 0 for
2826  * no or if we aren't sure, a 1 will cause a preempt.
2827  */
2828 static bool
2829 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
2830                    struct request *rq)
2831 {
2832         struct cfq_queue *cfqq;
2833
2834         cfqq = cfqd->active_queue;
2835         if (!cfqq)
2836                 return false;
2837
2838         if (cfq_slice_used(cfqq))
2839                 return true;
2840
2841         if (cfq_class_idle(new_cfqq))
2842                 return false;
2843
2844         if (cfq_class_idle(cfqq))
2845                 return true;
2846
2847         /* Allow preemption only if we are idling on sync-noidle tree */
2848         if (cfqd->serving_type == SYNC_NOIDLE_WORKLOAD &&
2849             cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
2850             new_cfqq->service_tree->count == 2 &&
2851             RB_EMPTY_ROOT(&cfqq->sort_list))
2852                 return true;
2853
2854         /*
2855          * if the new request is sync, but the currently running queue is
2856          * not, let the sync request have priority.
2857          */
2858         if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq))
2859                 return true;
2860
2861         /*
2862          * So both queues are sync. Let the new request get disk time if
2863          * it's a metadata request and the current queue is doing regular IO.
2864          */
2865         if (rq_is_meta(rq) && !cfqq->meta_pending)
2866                 return true;
2867
2868         /*
2869          * Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
2870          */
2871         if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
2872                 return true;
2873
2874         if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
2875                 return false;
2876
2877         /*
2878          * if this request is as-good as one we would expect from the
2879          * current cfqq, let it preempt
2880          */
2881         if (cfq_rq_close(cfqd, cfqq, rq))
2882                 return true;
2883
2884         return false;
2885 }
2886
2887 /*
2888  * cfqq preempts the active queue. if we allowed preempt with no slice left,
2889  * let it have half of its nominal slice.
2890  */
2891 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2892 {
2893         cfq_log_cfqq(cfqd, cfqq, "preempt");
2894         cfq_slice_expired(cfqd, 1);
2895
2896         /*
2897          * Put the new queue at the front of the of the current list,
2898          * so we know that it will be selected next.
2899          */
2900         BUG_ON(!cfq_cfqq_on_rr(cfqq));
2901
2902         cfq_service_tree_add(cfqd, cfqq, 1);
2903
2904         cfqq->slice_end = 0;
2905         cfq_mark_cfqq_slice_new(cfqq);
2906 }
2907
2908 /*
2909  * Called when a new fs request (rq) is added (to cfqq). Check if there's
2910  * something we should do about it
2911  */
2912 static void
2913 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2914                 struct request *rq)
2915 {
2916         struct cfq_io_context *cic = RQ_CIC(rq);
2917
2918         cfqd->rq_queued++;
2919         if (rq_is_meta(rq))
2920                 cfqq->meta_pending++;
2921
2922         cfq_update_io_thinktime(cfqd, cic);
2923         cfq_update_io_seektime(cfqd, cfqq, rq);
2924         cfq_update_idle_window(cfqd, cfqq, cic);
2925
2926         cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
2927
2928         if (cfqq == cfqd->active_queue) {
2929                 /*
2930                  * Remember that we saw a request from this process, but
2931                  * don't start queuing just yet. Otherwise we risk seeing lots
2932                  * of tiny requests, because we disrupt the normal plugging
2933                  * and merging. If the request is already larger than a single
2934                  * page, let it rip immediately. For that case we assume that
2935                  * merging is already done. Ditto for a busy system that
2936                  * has other work pending, don't risk delaying until the
2937                  * idle timer unplug to continue working.
2938                  */
2939                 if (cfq_cfqq_wait_request(cfqq)) {
2940                         if (blk_rq_bytes(rq) > PAGE_CACHE_SIZE ||
2941                             cfqd->busy_queues > 1) {
2942                                 del_timer(&cfqd->idle_slice_timer);
2943                                 __blk_run_queue(cfqd->queue);
2944                         } else
2945                                 cfq_mark_cfqq_must_dispatch(cfqq);
2946                 }
2947         } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
2948                 /*
2949                  * not the active queue - expire current slice if it is
2950                  * idle and has expired it's mean thinktime or this new queue
2951                  * has some old slice time left and is of higher priority or
2952                  * this new queue is RT and the current one is BE
2953                  */
2954                 cfq_preempt_queue(cfqd, cfqq);
2955                 __blk_run_queue(cfqd->queue);
2956         }
2957 }
2958
2959 static void cfq_insert_request(struct request_queue *q, struct request *rq)
2960 {
2961         struct cfq_data *cfqd = q->elevator->elevator_data;
2962         struct cfq_queue *cfqq = RQ_CFQQ(rq);
2963
2964         cfq_log_cfqq(cfqd, cfqq, "insert_request");
2965         cfq_init_prio_data(cfqq, RQ_CIC(rq)->ioc);
2966
2967         rq_set_fifo_time(rq, jiffies + cfqd->cfq_fifo_expire[rq_is_sync(rq)]);
2968         list_add_tail(&rq->queuelist, &cfqq->fifo);
2969         cfq_add_rq_rb(rq);
2970
2971         cfq_rq_enqueued(cfqd, cfqq, rq);
2972 }
2973
2974 /*
2975  * Update hw_tag based on peak queue depth over 50 samples under
2976  * sufficient load.
2977  */
2978 static void cfq_update_hw_tag(struct cfq_data *cfqd)
2979 {
2980         struct cfq_queue *cfqq = cfqd->active_queue;
2981
2982         if (rq_in_driver(cfqd) > cfqd->hw_tag_est_depth)
2983                 cfqd->hw_tag_est_depth = rq_in_driver(cfqd);
2984
2985         if (cfqd->hw_tag == 1)
2986                 return;
2987
2988         if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
2989             rq_in_driver(cfqd) <= CFQ_HW_QUEUE_MIN)
2990                 return;
2991
2992         /*
2993          * If active queue hasn't enough requests and can idle, cfq might not
2994          * dispatch sufficient requests to hardware. Don't zero hw_tag in this
2995          * case
2996          */
2997         if (cfqq && cfq_cfqq_idle_window(cfqq) &&
2998             cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
2999             CFQ_HW_QUEUE_MIN && rq_in_driver(cfqd) < CFQ_HW_QUEUE_MIN)
3000                 return;
3001
3002         if (cfqd->hw_tag_samples++ < 50)
3003                 return;
3004
3005         if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
3006                 cfqd->hw_tag = 1;
3007         else
3008                 cfqd->hw_tag = 0;
3009 }
3010
3011 static void cfq_completed_request(struct request_queue *q, struct request *rq)
3012 {
3013         struct cfq_queue *cfqq = RQ_CFQQ(rq);
3014         struct cfq_data *cfqd = cfqq->cfqd;
3015         const int sync = rq_is_sync(rq);
3016         unsigned long now;
3017
3018         now = jiffies;
3019         cfq_log_cfqq(cfqd, cfqq, "complete");
3020
3021         cfq_update_hw_tag(cfqd);
3022
3023         WARN_ON(!cfqd->rq_in_driver[sync]);
3024         WARN_ON(!cfqq->dispatched);
3025         cfqd->rq_in_driver[sync]--;
3026         cfqq->dispatched--;
3027
3028         if (cfq_cfqq_sync(cfqq))
3029                 cfqd->sync_flight--;
3030
3031         if (sync) {
3032                 RQ_CIC(rq)->last_end_request = now;
3033                 cfqd->last_end_sync_rq = now;
3034         }
3035
3036         /*
3037          * If this is the active queue, check if it needs to be expired,
3038          * or if we want to idle in case it has no pending requests.
3039          */
3040         if (cfqd->active_queue == cfqq) {
3041                 const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
3042
3043                 if (cfq_cfqq_slice_new(cfqq)) {
3044                         cfq_set_prio_slice(cfqd, cfqq);
3045                         cfq_clear_cfqq_slice_new(cfqq);
3046                 }
3047                 /*
3048                  * Idling is not enabled on:
3049                  * - expired queues
3050                  * - idle-priority queues
3051                  * - async queues
3052                  * - queues with still some requests queued
3053                  * - when there is a close cooperator
3054                  */
3055                 if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
3056                         cfq_slice_expired(cfqd, 1);
3057                 else if (sync && cfqq_empty &&
3058                          !cfq_close_cooperator(cfqd, cfqq)) {
3059                         cfqd->noidle_tree_requires_idle |= !rq_noidle(rq);
3060                         /*
3061                          * Idling is enabled for SYNC_WORKLOAD.
3062                          * SYNC_NOIDLE_WORKLOAD idles at the end of the tree
3063                          * only if we processed at least one !rq_noidle request
3064                          */
3065                         if (cfqd->serving_type == SYNC_WORKLOAD
3066                             || cfqd->noidle_tree_requires_idle)
3067                                 cfq_arm_slice_timer(cfqd);
3068                 }
3069         }
3070
3071         if (!rq_in_driver(cfqd))
3072                 cfq_schedule_dispatch(cfqd);
3073 }
3074
3075 /*
3076  * we temporarily boost lower priority queues if they are holding fs exclusive
3077  * resources. they are boosted to normal prio (CLASS_BE/4)
3078  */
3079 static void cfq_prio_boost(struct cfq_queue *cfqq)
3080 {
3081         if (has_fs_excl()) {
3082                 /*
3083                  * boost idle prio on transactions that would lock out other
3084                  * users of the filesystem
3085                  */
3086                 if (cfq_class_idle(cfqq))
3087                         cfqq->ioprio_class = IOPRIO_CLASS_BE;
3088                 if (cfqq->ioprio > IOPRIO_NORM)
3089                         cfqq->ioprio = IOPRIO_NORM;
3090         } else {
3091                 /*
3092                  * unboost the queue (if needed)
3093                  */
3094                 cfqq->ioprio_class = cfqq->org_ioprio_class;
3095                 cfqq->ioprio = cfqq->org_ioprio;
3096         }
3097 }
3098
3099 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
3100 {
3101         if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
3102                 cfq_mark_cfqq_must_alloc_slice(cfqq);
3103                 return ELV_MQUEUE_MUST;
3104         }
3105
3106         return ELV_MQUEUE_MAY;
3107 }
3108
3109 static int cfq_may_queue(struct request_queue *q, int rw)
3110 {
3111         struct cfq_data *cfqd = q->elevator->elevator_data;
3112         struct task_struct *tsk = current;
3113         struct cfq_io_context *cic;
3114         struct cfq_queue *cfqq;
3115
3116         /*
3117          * don't force setup of a queue from here, as a call to may_queue
3118          * does not necessarily imply that a request actually will be queued.
3119          * so just lookup a possibly existing queue, or return 'may queue'
3120          * if that fails
3121          */
3122         cic = cfq_cic_lookup(cfqd, tsk->io_context);
3123         if (!cic)
3124                 return ELV_MQUEUE_MAY;
3125
3126         cfqq = cic_to_cfqq(cic, rw_is_sync(rw));
3127         if (cfqq) {
3128                 cfq_init_prio_data(cfqq, cic->ioc);
3129                 cfq_prio_boost(cfqq);
3130
3131                 return __cfq_may_queue(cfqq);
3132         }
3133
3134         return ELV_MQUEUE_MAY;
3135 }
3136
3137 /*
3138  * queue lock held here
3139  */
3140 static void cfq_put_request(struct request *rq)
3141 {
3142         struct cfq_queue *cfqq = RQ_CFQQ(rq);
3143
3144         if (cfqq) {
3145                 const int rw = rq_data_dir(rq);
3146
3147                 BUG_ON(!cfqq->allocated[rw]);
3148                 cfqq->allocated[rw]--;
3149
3150                 put_io_context(RQ_CIC(rq)->ioc);
3151
3152                 rq->elevator_private = NULL;
3153                 rq->elevator_private2 = NULL;
3154
3155                 cfq_put_queue(cfqq);
3156         }
3157 }
3158
3159 static struct cfq_queue *
3160 cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_context *cic,
3161                 struct cfq_queue *cfqq)
3162 {
3163         cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
3164         cic_set_cfqq(cic, cfqq->new_cfqq, 1);
3165         cfq_mark_cfqq_coop(cfqq->new_cfqq);
3166         cfq_put_queue(cfqq);
3167         return cic_to_cfqq(cic, 1);
3168 }
3169
3170 static int should_split_cfqq(struct cfq_queue *cfqq)
3171 {
3172         if (cfqq->seeky_start &&
3173             time_after(jiffies, cfqq->seeky_start + CFQQ_COOP_TOUT))
3174                 return 1;
3175         return 0;
3176 }
3177
3178 /*
3179  * Returns NULL if a new cfqq should be allocated, or the old cfqq if this
3180  * was the last process referring to said cfqq.
3181  */
3182 static struct cfq_queue *
3183 split_cfqq(struct cfq_io_context *cic, struct cfq_queue *cfqq)
3184 {
3185         if (cfqq_process_refs(cfqq) == 1) {
3186                 cfqq->seeky_start = 0;
3187                 cfqq->pid = current->pid;
3188                 cfq_clear_cfqq_coop(cfqq);
3189                 return cfqq;
3190         }
3191
3192         cic_set_cfqq(cic, NULL, 1);
3193         cfq_put_queue(cfqq);
3194         return NULL;
3195 }
3196 /*
3197  * Allocate cfq data structures associated with this request.
3198  */
3199 static int
3200 cfq_set_request(struct request_queue *q, struct request *rq, gfp_t gfp_mask)
3201 {
3202         struct cfq_data *cfqd = q->elevator->elevator_data;
3203         struct cfq_io_context *cic;
3204         const int rw = rq_data_dir(rq);
3205         const bool is_sync = rq_is_sync(rq);
3206         struct cfq_queue *cfqq;
3207         unsigned long flags;
3208
3209         might_sleep_if(gfp_mask & __GFP_WAIT);
3210
3211         cic = cfq_get_io_context(cfqd, gfp_mask);
3212
3213         spin_lock_irqsave(q->queue_lock, flags);
3214
3215         if (!cic)
3216                 goto queue_fail;
3217
3218 new_queue:
3219         cfqq = cic_to_cfqq(cic, is_sync);
3220         if (!cfqq || cfqq == &cfqd->oom_cfqq) {
3221                 cfqq = cfq_get_queue(cfqd, is_sync, cic->ioc, gfp_mask);
3222                 cic_set_cfqq(cic, cfqq, is_sync);
3223         } else {
3224                 /*
3225                  * If the queue was seeky for too long, break it apart.
3226                  */
3227                 if (cfq_cfqq_coop(cfqq) && should_split_cfqq(cfqq)) {
3228                         cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
3229                         cfqq = split_cfqq(cic, cfqq);
3230                         if (!cfqq)
3231                                 goto new_queue;
3232                 }
3233
3234                 /*
3235                  * Check to see if this queue is scheduled to merge with
3236                  * another, closely cooperating queue.  The merging of
3237                  * queues happens here as it must be done in process context.
3238                  * The reference on new_cfqq was taken in merge_cfqqs.
3239                  */
3240                 if (cfqq->new_cfqq)
3241                         cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
3242         }
3243
3244         cfqq->allocated[rw]++;
3245         atomic_inc(&cfqq->ref);
3246
3247         spin_unlock_irqrestore(q->queue_lock, flags);
3248
3249         rq->elevator_private = cic;
3250         rq->elevator_private2 = cfqq;
3251         return 0;
3252
3253 queue_fail:
3254         if (cic)
3255                 put_io_context(cic->ioc);
3256
3257         cfq_schedule_dispatch(cfqd);
3258         spin_unlock_irqrestore(q->queue_lock, flags);
3259         cfq_log(cfqd, "set_request fail");
3260         return 1;
3261 }
3262
3263 static void cfq_kick_queue(struct work_struct *work)
3264 {
3265         struct cfq_data *cfqd =
3266                 container_of(work, struct cfq_data, unplug_work);
3267         struct request_queue *q = cfqd->queue;
3268
3269         spin_lock_irq(q->queue_lock);
3270         __blk_run_queue(cfqd->queue);
3271         spin_unlock_irq(q->queue_lock);
3272 }
3273
3274 /*
3275  * Timer running if the active_queue is currently idling inside its time slice
3276  */
3277 static void cfq_idle_slice_timer(unsigned long data)
3278 {
3279         struct cfq_data *cfqd = (struct cfq_data *) data;
3280         struct cfq_queue *cfqq;
3281         unsigned long flags;
3282         int timed_out = 1;
3283
3284         cfq_log(cfqd, "idle timer fired");
3285
3286         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
3287
3288         cfqq = cfqd->active_queue;
3289         if (cfqq) {
3290                 timed_out = 0;
3291
3292                 /*
3293                  * We saw a request before the queue expired, let it through
3294                  */
3295                 if (cfq_cfqq_must_dispatch(cfqq))
3296                         goto out_kick;
3297
3298                 /*
3299                  * expired
3300                  */
3301                 if (cfq_slice_used(cfqq))
3302                         goto expire;
3303
3304                 /*
3305                  * only expire and reinvoke request handler, if there are
3306                  * other queues with pending requests
3307                  */
3308                 if (!cfqd->busy_queues)
3309                         goto out_cont;
3310
3311                 /*
3312                  * not expired and it has a request pending, let it dispatch
3313                  */
3314                 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
3315                         goto out_kick;
3316
3317                 /*
3318                  * Queue depth flag is reset only when the idle didn't succeed
3319                  */
3320                 cfq_clear_cfqq_deep(cfqq);
3321         }
3322 expire:
3323         cfq_slice_expired(cfqd, timed_out);
3324 out_kick:
3325         cfq_schedule_dispatch(cfqd);
3326 out_cont:
3327         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
3328 }
3329
3330 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
3331 {
3332         del_timer_sync(&cfqd->idle_slice_timer);
3333         cancel_work_sync(&cfqd->unplug_work);
3334 }
3335
3336 static void cfq_put_async_queues(struct cfq_data *cfqd)
3337 {
3338         int i;
3339
3340         for (i = 0; i < IOPRIO_BE_NR; i++) {
3341                 if (cfqd->async_cfqq[0][i])
3342                         cfq_put_queue(cfqd->async_cfqq[0][i]);
3343                 if (cfqd->async_cfqq[1][i])
3344                         cfq_put_queue(cfqd->async_cfqq[1][i]);
3345         }
3346
3347         if (cfqd->async_idle_cfqq)
3348                 cfq_put_queue(cfqd->async_idle_cfqq);
3349 }
3350
3351 static void cfq_exit_queue(struct elevator_queue *e)
3352 {
3353         struct cfq_data *cfqd = e->elevator_data;
3354         struct request_queue *q = cfqd->queue;
3355
3356         cfq_shutdown_timer_wq(cfqd);
3357
3358         spin_lock_irq(q->queue_lock);
3359
3360         if (cfqd->active_queue)
3361                 __cfq_slice_expired(cfqd, cfqd->active_queue, 0);
3362
3363         while (!list_empty(&cfqd->cic_list)) {
3364                 struct cfq_io_context *cic = list_entry(cfqd->cic_list.next,
3365                                                         struct cfq_io_context,
3366                                                         queue_list);
3367
3368                 __cfq_exit_single_io_context(cfqd, cic);
3369         }
3370
3371         cfq_put_async_queues(cfqd);
3372
3373         spin_unlock_irq(q->queue_lock);
3374
3375         cfq_shutdown_timer_wq(cfqd);
3376
3377         kfree(cfqd);
3378 }
3379
3380 static void *cfq_init_queue(struct request_queue *q)
3381 {
3382         struct cfq_data *cfqd;
3383         int i, j;
3384         struct cfq_group *cfqg;
3385         struct cfq_rb_root *st;
3386
3387         cfqd = kmalloc_node(sizeof(*cfqd), GFP_KERNEL | __GFP_ZERO, q->node);
3388         if (!cfqd)
3389                 return NULL;
3390
3391         /* Init root service tree */
3392         cfqd->grp_service_tree = CFQ_RB_ROOT;
3393
3394         /* Init root group */
3395         cfqg = &cfqd->root_group;
3396         for_each_cfqg_st(cfqg, i, j, st)
3397                 *st = CFQ_RB_ROOT;
3398         RB_CLEAR_NODE(&cfqg->rb_node);
3399
3400         /* Give preference to root group over other groups */
3401         cfqg->weight = 2*BLKIO_WEIGHT_DEFAULT;
3402
3403 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3404         blkiocg_add_blkio_group(&blkio_root_cgroup, &cfqg->blkg, (void *)cfqd);
3405 #endif
3406         /*
3407          * Not strictly needed (since RB_ROOT just clears the node and we
3408          * zeroed cfqd on alloc), but better be safe in case someone decides
3409          * to add magic to the rb code
3410          */
3411         for (i = 0; i < CFQ_PRIO_LISTS; i++)
3412                 cfqd->prio_trees[i] = RB_ROOT;
3413
3414         /*
3415          * Our fallback cfqq if cfq_find_alloc_queue() runs into OOM issues.
3416          * Grab a permanent reference to it, so that the normal code flow
3417          * will not attempt to free it.
3418          */
3419         cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
3420         atomic_inc(&cfqd->oom_cfqq.ref);
3421         cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, &cfqd->root_group);
3422
3423         INIT_LIST_HEAD(&cfqd->cic_list);
3424
3425         cfqd->queue = q;
3426
3427         init_timer(&cfqd->idle_slice_timer);
3428         cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
3429         cfqd->idle_slice_timer.data = (unsigned long) cfqd;
3430
3431         INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
3432
3433         cfqd->cfq_quantum = cfq_quantum;
3434         cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
3435         cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
3436         cfqd->cfq_back_max = cfq_back_max;
3437         cfqd->cfq_back_penalty = cfq_back_penalty;
3438         cfqd->cfq_slice[0] = cfq_slice_async;
3439         cfqd->cfq_slice[1] = cfq_slice_sync;
3440         cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
3441         cfqd->cfq_slice_idle = cfq_slice_idle;
3442         cfqd->cfq_latency = 1;
3443         cfqd->hw_tag = -1;
3444         cfqd->last_end_sync_rq = jiffies;
3445         return cfqd;
3446 }
3447
3448 static void cfq_slab_kill(void)
3449 {
3450         /*
3451          * Caller already ensured that pending RCU callbacks are completed,
3452          * so we should have no busy allocations at this point.
3453          */
3454         if (cfq_pool)
3455                 kmem_cache_destroy(cfq_pool);
3456         if (cfq_ioc_pool)
3457                 kmem_cache_destroy(cfq_ioc_pool);
3458 }
3459
3460 static int __init cfq_slab_setup(void)
3461 {
3462         cfq_pool = KMEM_CACHE(cfq_queue, 0);
3463         if (!cfq_pool)
3464                 goto fail;
3465
3466         cfq_ioc_pool = KMEM_CACHE(cfq_io_context, 0);
3467         if (!cfq_ioc_pool)
3468                 goto fail;
3469
3470         return 0;
3471 fail:
3472         cfq_slab_kill();
3473         return -ENOMEM;
3474 }
3475
3476 /*
3477  * sysfs parts below -->
3478  */
3479 static ssize_t
3480 cfq_var_show(unsigned int var, char *page)
3481 {
3482         return sprintf(page, "%d\n", var);
3483 }
3484
3485 static ssize_t
3486 cfq_var_store(unsigned int *var, const char *page, size_t count)
3487 {
3488         char *p = (char *) page;
3489
3490         *var = simple_strtoul(p, &p, 10);
3491         return count;
3492 }
3493
3494 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV)                            \
3495 static ssize_t __FUNC(struct elevator_queue *e, char *page)             \
3496 {                                                                       \
3497         struct cfq_data *cfqd = e->elevator_data;                       \
3498         unsigned int __data = __VAR;                                    \
3499         if (__CONV)                                                     \
3500                 __data = jiffies_to_msecs(__data);                      \
3501         return cfq_var_show(__data, (page));                            \
3502 }
3503 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
3504 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
3505 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
3506 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
3507 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
3508 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
3509 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
3510 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
3511 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
3512 SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
3513 #undef SHOW_FUNCTION
3514
3515 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV)                 \
3516 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
3517 {                                                                       \
3518         struct cfq_data *cfqd = e->elevator_data;                       \
3519         unsigned int __data;                                            \
3520         int ret = cfq_var_store(&__data, (page), count);                \
3521         if (__data < (MIN))                                             \
3522                 __data = (MIN);                                         \
3523         else if (__data > (MAX))                                        \
3524                 __data = (MAX);                                         \
3525         if (__CONV)                                                     \
3526                 *(__PTR) = msecs_to_jiffies(__data);                    \
3527         else                                                            \
3528                 *(__PTR) = __data;                                      \
3529         return ret;                                                     \
3530 }
3531 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
3532 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
3533                 UINT_MAX, 1);
3534 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
3535                 UINT_MAX, 1);
3536 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
3537 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
3538                 UINT_MAX, 0);
3539 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
3540 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
3541 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
3542 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
3543                 UINT_MAX, 0);
3544 STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
3545 #undef STORE_FUNCTION
3546
3547 #define CFQ_ATTR(name) \
3548         __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
3549
3550 static struct elv_fs_entry cfq_attrs[] = {
3551         CFQ_ATTR(quantum),
3552         CFQ_ATTR(fifo_expire_sync),
3553         CFQ_ATTR(fifo_expire_async),
3554         CFQ_ATTR(back_seek_max),
3555         CFQ_ATTR(back_seek_penalty),
3556         CFQ_ATTR(slice_sync),
3557         CFQ_ATTR(slice_async),
3558         CFQ_ATTR(slice_async_rq),
3559         CFQ_ATTR(slice_idle),
3560         CFQ_ATTR(low_latency),
3561         __ATTR_NULL
3562 };
3563
3564 static struct elevator_type iosched_cfq = {
3565         .ops = {
3566                 .elevator_merge_fn =            cfq_merge,
3567                 .elevator_merged_fn =           cfq_merged_request,
3568                 .elevator_merge_req_fn =        cfq_merged_requests,
3569                 .elevator_allow_merge_fn =      cfq_allow_merge,
3570                 .elevator_dispatch_fn =         cfq_dispatch_requests,
3571                 .elevator_add_req_fn =          cfq_insert_request,
3572                 .elevator_activate_req_fn =     cfq_activate_request,
3573                 .elevator_deactivate_req_fn =   cfq_deactivate_request,
3574                 .elevator_queue_empty_fn =      cfq_queue_empty,
3575                 .elevator_completed_req_fn =    cfq_completed_request,
3576                 .elevator_former_req_fn =       elv_rb_former_request,
3577                 .elevator_latter_req_fn =       elv_rb_latter_request,
3578                 .elevator_set_req_fn =          cfq_set_request,
3579                 .elevator_put_req_fn =          cfq_put_request,
3580                 .elevator_may_queue_fn =        cfq_may_queue,
3581                 .elevator_init_fn =             cfq_init_queue,
3582                 .elevator_exit_fn =             cfq_exit_queue,
3583                 .trim =                         cfq_free_io_context,
3584         },
3585         .elevator_attrs =       cfq_attrs,
3586         .elevator_name =        "cfq",
3587         .elevator_owner =       THIS_MODULE,
3588 };
3589
3590 static int __init cfq_init(void)
3591 {
3592         /*
3593          * could be 0 on HZ < 1000 setups
3594          */
3595         if (!cfq_slice_async)
3596                 cfq_slice_async = 1;
3597         if (!cfq_slice_idle)
3598                 cfq_slice_idle = 1;
3599
3600         if (cfq_slab_setup())
3601                 return -ENOMEM;
3602
3603         elv_register(&iosched_cfq);
3604
3605         return 0;
3606 }
3607
3608 static void __exit cfq_exit(void)
3609 {
3610         DECLARE_COMPLETION_ONSTACK(all_gone);
3611         elv_unregister(&iosched_cfq);
3612         ioc_gone = &all_gone;
3613         /* ioc_gone's update must be visible before reading ioc_count */
3614         smp_wmb();
3615
3616         /*
3617          * this also protects us from entering cfq_slab_kill() with
3618          * pending RCU callbacks
3619          */
3620         if (elv_ioc_count_read(cfq_ioc_count))
3621                 wait_for_completion(&all_gone);
3622         cfq_slab_kill();
3623 }
3624
3625 module_init(cfq_init);
3626 module_exit(cfq_exit);
3627
3628 MODULE_AUTHOR("Jens Axboe");
3629 MODULE_LICENSE("GPL");
3630 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");