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