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