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