9d6f04103f01ae965959bb8b791373ffb633b020
[safe/jmp/linux-2.6] / block / cfq-iosched.c
1 /*
2  *  CFQ, or complete fairness queueing, disk scheduler.
3  *
4  *  Based on ideas from a previously unfinished io
5  *  scheduler (round robin per-process disk scheduling) and Andrea Arcangeli.
6  *
7  *  Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
8  */
9 #include <linux/module.h>
10 #include <linux/blkdev.h>
11 #include <linux/elevator.h>
12 #include <linux/hash.h>
13 #include <linux/rbtree.h>
14 #include <linux/ioprio.h>
15
16 /*
17  * tunables
18  */
19 static const int cfq_quantum = 4;               /* max queue in one round of service */
20 static const int cfq_fifo_expire[2] = { HZ / 4, HZ / 8 };
21 static const int cfq_back_max = 16 * 1024;      /* maximum backwards seek, in KiB */
22 static const int cfq_back_penalty = 2;          /* penalty of a backwards seek */
23
24 static const int cfq_slice_sync = HZ / 10;
25 static int cfq_slice_async = HZ / 25;
26 static const int cfq_slice_async_rq = 2;
27 static int cfq_slice_idle = HZ / 125;
28
29 #define CFQ_IDLE_GRACE          (HZ / 10)
30 #define CFQ_SLICE_SCALE         (5)
31
32 #define CFQ_KEY_ASYNC           (0)
33
34 /*
35  * for the hash of cfqq inside the cfqd
36  */
37 #define CFQ_QHASH_SHIFT         6
38 #define CFQ_QHASH_ENTRIES       (1 << CFQ_QHASH_SHIFT)
39 #define list_entry_qhash(entry) hlist_entry((entry), struct cfq_queue, cfq_hash)
40
41 #define list_entry_cfqq(ptr)    list_entry((ptr), struct cfq_queue, cfq_list)
42
43 #define RQ_CIC(rq)              ((struct cfq_io_context*)(rq)->elevator_private)
44 #define RQ_CFQQ(rq)             ((rq)->elevator_private2)
45
46 static struct kmem_cache *cfq_pool;
47 static struct kmem_cache *cfq_ioc_pool;
48
49 static DEFINE_PER_CPU(unsigned long, ioc_count);
50 static struct completion *ioc_gone;
51
52 #define CFQ_PRIO_LISTS          IOPRIO_BE_NR
53 #define cfq_class_idle(cfqq)    ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
54 #define cfq_class_rt(cfqq)      ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
55
56 #define ASYNC                   (0)
57 #define SYNC                    (1)
58
59 #define cfq_cfqq_sync(cfqq)     ((cfqq)->key != CFQ_KEY_ASYNC)
60
61 #define sample_valid(samples)   ((samples) > 80)
62
63 /*
64  * Per block device queue structure
65  */
66 struct cfq_data {
67         request_queue_t *queue;
68
69         /*
70          * rr list of queues with requests and the count of them
71          */
72         struct list_head rr_list[CFQ_PRIO_LISTS];
73         struct list_head cur_rr;
74         struct list_head idle_rr;
75         unsigned long cur_rr_tick;
76         unsigned int busy_queues;
77
78         /*
79          * cfqq lookup hash
80          */
81         struct hlist_head *cfq_hash;
82
83         int rq_in_driver;
84         int hw_tag;
85
86         /*
87          * idle window management
88          */
89         struct timer_list idle_slice_timer;
90         struct work_struct unplug_work;
91
92         struct cfq_queue *active_queue;
93         struct cfq_io_context *active_cic;
94         int cur_prio, cur_end_prio;
95         unsigned long prio_time;
96         unsigned int dispatch_slice;
97
98         struct timer_list idle_class_timer;
99
100         sector_t last_position;
101         unsigned long last_end_request;
102
103         /*
104          * tunables, see top of file
105          */
106         unsigned int cfq_quantum;
107         unsigned int cfq_fifo_expire[2];
108         unsigned int cfq_back_penalty;
109         unsigned int cfq_back_max;
110         unsigned int cfq_slice[2];
111         unsigned int cfq_slice_async_rq;
112         unsigned int cfq_slice_idle;
113
114         struct list_head cic_list;
115
116         sector_t new_seek_mean;
117         u64 new_seek_total;
118 };
119
120 /*
121  * Per process-grouping structure
122  */
123 struct cfq_queue {
124         /* reference count */
125         atomic_t ref;
126         /* parent cfq_data */
127         struct cfq_data *cfqd;
128         /* cfqq lookup hash */
129         struct hlist_node cfq_hash;
130         /* hash key */
131         unsigned int key;
132         /* member of the rr/busy/cur/idle cfqd list */
133         struct list_head cfq_list;
134         /* in what tick we were last serviced */
135         unsigned long rr_tick;
136         /* sorted list of pending requests */
137         struct rb_root sort_list;
138         /* if fifo isn't expired, next request to serve */
139         struct request *next_rq;
140         /* requests queued in sort_list */
141         int queued[2];
142         /* currently allocated requests */
143         int allocated[2];
144         /* pending metadata requests */
145         int meta_pending;
146         /* fifo list of requests in sort_list */
147         struct list_head fifo;
148
149         unsigned long slice_end;
150         unsigned long service_last;
151         unsigned long slice_start;
152         long slice_resid;
153
154         /* number of requests that are on the dispatch list or inside driver */
155         int dispatched;
156
157         /* io prio of this group */
158         unsigned short ioprio, org_ioprio;
159         unsigned short ioprio_class, org_ioprio_class;
160
161         /* various state flags, see below */
162         unsigned int flags;
163
164         sector_t last_request_pos;
165 };
166
167 enum cfqq_state_flags {
168         CFQ_CFQQ_FLAG_on_rr = 0,        /* on round-robin busy list */
169         CFQ_CFQQ_FLAG_wait_request,     /* waiting for a request */
170         CFQ_CFQQ_FLAG_must_alloc,       /* must be allowed rq alloc */
171         CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
172         CFQ_CFQQ_FLAG_must_dispatch,    /* must dispatch, even if expired */
173         CFQ_CFQQ_FLAG_fifo_expire,      /* FIFO checked in this slice */
174         CFQ_CFQQ_FLAG_idle_window,      /* slice idling enabled */
175         CFQ_CFQQ_FLAG_prio_changed,     /* task priority has changed */
176         CFQ_CFQQ_FLAG_queue_new,        /* queue never been serviced */
177         CFQ_CFQQ_FLAG_slice_new,        /* no requests dispatched in slice */
178 };
179
180 #define CFQ_CFQQ_FNS(name)                                              \
181 static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq)         \
182 {                                                                       \
183         cfqq->flags |= (1 << CFQ_CFQQ_FLAG_##name);                     \
184 }                                                                       \
185 static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq)        \
186 {                                                                       \
187         cfqq->flags &= ~(1 << CFQ_CFQQ_FLAG_##name);                    \
188 }                                                                       \
189 static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq)         \
190 {                                                                       \
191         return (cfqq->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0;        \
192 }
193
194 CFQ_CFQQ_FNS(on_rr);
195 CFQ_CFQQ_FNS(wait_request);
196 CFQ_CFQQ_FNS(must_alloc);
197 CFQ_CFQQ_FNS(must_alloc_slice);
198 CFQ_CFQQ_FNS(must_dispatch);
199 CFQ_CFQQ_FNS(fifo_expire);
200 CFQ_CFQQ_FNS(idle_window);
201 CFQ_CFQQ_FNS(prio_changed);
202 CFQ_CFQQ_FNS(queue_new);
203 CFQ_CFQQ_FNS(slice_new);
204 #undef CFQ_CFQQ_FNS
205
206 static struct cfq_queue *cfq_find_cfq_hash(struct cfq_data *, unsigned int, unsigned short);
207 static void cfq_dispatch_insert(request_queue_t *, struct request *);
208 static struct cfq_queue *cfq_get_queue(struct cfq_data *cfqd, unsigned int key, struct task_struct *tsk, gfp_t gfp_mask);
209
210 /*
211  * scheduler run of queue, if there are requests pending and no one in the
212  * driver that will restart queueing
213  */
214 static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
215 {
216         if (cfqd->busy_queues)
217                 kblockd_schedule_work(&cfqd->unplug_work);
218 }
219
220 static int cfq_queue_empty(request_queue_t *q)
221 {
222         struct cfq_data *cfqd = q->elevator->elevator_data;
223
224         return !cfqd->busy_queues;
225 }
226
227 static inline pid_t cfq_queue_pid(struct task_struct *task, int rw, int is_sync)
228 {
229         /*
230          * Use the per-process queue, for read requests and syncronous writes
231          */
232         if (!(rw & REQ_RW) || is_sync)
233                 return task->pid;
234
235         return CFQ_KEY_ASYNC;
236 }
237
238 /*
239  * Scale schedule slice based on io priority. Use the sync time slice only
240  * if a queue is marked sync and has sync io queued. A sync queue with async
241  * io only, should not get full sync slice length.
242  */
243 static inline int
244 cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
245 {
246         const int base_slice = cfqd->cfq_slice[cfq_cfqq_sync(cfqq)];
247
248         WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
249
250         return base_slice + (base_slice/CFQ_SLICE_SCALE * (4 - cfqq->ioprio));
251 }
252
253 static inline void
254 cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
255 {
256         cfqq->slice_end = cfq_prio_to_slice(cfqd, cfqq) + jiffies;
257         cfqq->slice_end += cfqq->slice_resid;
258
259         /*
260          * Don't carry over residual for more than one slice, we only want
261          * to slightly correct the fairness. Carrying over forever would
262          * easily introduce oscillations.
263          */
264         cfqq->slice_resid = 0;
265
266         cfqq->slice_start = jiffies;
267 }
268
269 /*
270  * We need to wrap this check in cfq_cfqq_slice_new(), since ->slice_end
271  * isn't valid until the first request from the dispatch is activated
272  * and the slice time set.
273  */
274 static inline int cfq_slice_used(struct cfq_queue *cfqq)
275 {
276         if (cfq_cfqq_slice_new(cfqq))
277                 return 0;
278         if (time_before(jiffies, cfqq->slice_end))
279                 return 0;
280
281         return 1;
282 }
283
284 /*
285  * Lifted from AS - choose which of rq1 and rq2 that is best served now.
286  * We choose the request that is closest to the head right now. Distance
287  * behind the head is penalized and only allowed to a certain extent.
288  */
289 static struct request *
290 cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2)
291 {
292         sector_t last, s1, s2, d1 = 0, d2 = 0;
293         unsigned long back_max;
294 #define CFQ_RQ1_WRAP    0x01 /* request 1 wraps */
295 #define CFQ_RQ2_WRAP    0x02 /* request 2 wraps */
296         unsigned wrap = 0; /* bit mask: requests behind the disk head? */
297
298         if (rq1 == NULL || rq1 == rq2)
299                 return rq2;
300         if (rq2 == NULL)
301                 return rq1;
302
303         if (rq_is_sync(rq1) && !rq_is_sync(rq2))
304                 return rq1;
305         else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
306                 return rq2;
307         if (rq_is_meta(rq1) && !rq_is_meta(rq2))
308                 return rq1;
309         else if (rq_is_meta(rq2) && !rq_is_meta(rq1))
310                 return rq2;
311
312         s1 = rq1->sector;
313         s2 = rq2->sector;
314
315         last = cfqd->last_position;
316
317         /*
318          * by definition, 1KiB is 2 sectors
319          */
320         back_max = cfqd->cfq_back_max * 2;
321
322         /*
323          * Strict one way elevator _except_ in the case where we allow
324          * short backward seeks which are biased as twice the cost of a
325          * similar forward seek.
326          */
327         if (s1 >= last)
328                 d1 = s1 - last;
329         else if (s1 + back_max >= last)
330                 d1 = (last - s1) * cfqd->cfq_back_penalty;
331         else
332                 wrap |= CFQ_RQ1_WRAP;
333
334         if (s2 >= last)
335                 d2 = s2 - last;
336         else if (s2 + back_max >= last)
337                 d2 = (last - s2) * cfqd->cfq_back_penalty;
338         else
339                 wrap |= CFQ_RQ2_WRAP;
340
341         /* Found required data */
342
343         /*
344          * By doing switch() on the bit mask "wrap" we avoid having to
345          * check two variables for all permutations: --> faster!
346          */
347         switch (wrap) {
348         case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
349                 if (d1 < d2)
350                         return rq1;
351                 else if (d2 < d1)
352                         return rq2;
353                 else {
354                         if (s1 >= s2)
355                                 return rq1;
356                         else
357                                 return rq2;
358                 }
359
360         case CFQ_RQ2_WRAP:
361                 return rq1;
362         case CFQ_RQ1_WRAP:
363                 return rq2;
364         case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
365         default:
366                 /*
367                  * Since both rqs are wrapped,
368                  * start with the one that's further behind head
369                  * (--> only *one* back seek required),
370                  * since back seek takes more time than forward.
371                  */
372                 if (s1 <= s2)
373                         return rq1;
374                 else
375                         return rq2;
376         }
377 }
378
379 /*
380  * would be nice to take fifo expire time into account as well
381  */
382 static struct request *
383 cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
384                   struct request *last)
385 {
386         struct rb_node *rbnext = rb_next(&last->rb_node);
387         struct rb_node *rbprev = rb_prev(&last->rb_node);
388         struct request *next = NULL, *prev = NULL;
389
390         BUG_ON(RB_EMPTY_NODE(&last->rb_node));
391
392         if (rbprev)
393                 prev = rb_entry_rq(rbprev);
394
395         if (rbnext)
396                 next = rb_entry_rq(rbnext);
397         else {
398                 rbnext = rb_first(&cfqq->sort_list);
399                 if (rbnext && rbnext != &last->rb_node)
400                         next = rb_entry_rq(rbnext);
401         }
402
403         return cfq_choose_req(cfqd, next, prev);
404 }
405
406 /*
407  * This function finds out where to insert a BE queue in the service hierarchy
408  */
409 static void cfq_resort_be_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq,
410                                 int preempted)
411 {
412         if (!cfq_cfqq_sync(cfqq))
413                 list_add_tail(&cfqq->cfq_list, &cfqd->rr_list[cfqq->ioprio]);
414         else {
415                 struct list_head *n = &cfqd->rr_list[cfqq->ioprio];
416
417                 /*
418                  * sort by last service, but don't cross a new or async
419                  * queue. we don't cross a new queue because it hasn't
420                  * been service before, and we don't cross an async
421                  * queue because it gets added to the end on expire.
422                  */
423                 while ((n = n->prev) != &cfqd->rr_list[cfqq->ioprio]) {
424                         struct cfq_queue *__c = list_entry_cfqq(n);
425
426                         if (!cfq_cfqq_sync(__c) || !__c->service_last)
427                                 break;
428                         if (time_before(__c->service_last, cfqq->service_last))
429                                 break;
430                 }
431                 list_add(&cfqq->cfq_list, n);
432         }
433 }
434
435 static void cfq_resort_rr_list(struct cfq_queue *cfqq, int preempted)
436 {
437         struct cfq_data *cfqd = cfqq->cfqd;
438         struct list_head *n;
439
440         /*
441          * Resorting requires the cfqq to be on the RR list already.
442          */
443         if (!cfq_cfqq_on_rr(cfqq))
444                 return;
445
446         list_del(&cfqq->cfq_list);
447
448         if (cfq_class_rt(cfqq)) {
449                 /*
450                  * At to the front of the current list, but behind other
451                  * RT queues.
452                  */
453                 n = &cfqd->cur_rr;
454                 while (n->next != &cfqd->cur_rr)
455                         if (!cfq_class_rt(cfqq))
456                                 break;
457
458                 list_add(&cfqq->cfq_list, n);
459         } else if (cfq_class_idle(cfqq)) {
460                 /*
461                  * IDLE goes to the tail of the idle list
462                  */
463                 list_add_tail(&cfqq->cfq_list, &cfqd->idle_rr);
464         } else {
465                 /*
466                  * So we get here, ergo the queue is a regular best-effort queue
467                  */
468                 cfq_resort_be_queue(cfqd, cfqq, preempted);
469         }
470 }
471
472 /*
473  * add to busy list of queues for service, trying to be fair in ordering
474  * the pending list according to last request service
475  */
476 static inline void
477 cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
478 {
479         BUG_ON(cfq_cfqq_on_rr(cfqq));
480         cfq_mark_cfqq_on_rr(cfqq);
481         cfqd->busy_queues++;
482
483         cfq_resort_rr_list(cfqq, 0);
484 }
485
486 static inline void
487 cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
488 {
489         BUG_ON(!cfq_cfqq_on_rr(cfqq));
490         cfq_clear_cfqq_on_rr(cfqq);
491         list_del_init(&cfqq->cfq_list);
492
493         BUG_ON(!cfqd->busy_queues);
494         cfqd->busy_queues--;
495 }
496
497 /*
498  * rb tree support functions
499  */
500 static inline void cfq_del_rq_rb(struct request *rq)
501 {
502         struct cfq_queue *cfqq = RQ_CFQQ(rq);
503         struct cfq_data *cfqd = cfqq->cfqd;
504         const int sync = rq_is_sync(rq);
505
506         BUG_ON(!cfqq->queued[sync]);
507         cfqq->queued[sync]--;
508
509         elv_rb_del(&cfqq->sort_list, rq);
510
511         if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
512                 cfq_del_cfqq_rr(cfqd, cfqq);
513 }
514
515 static void cfq_add_rq_rb(struct request *rq)
516 {
517         struct cfq_queue *cfqq = RQ_CFQQ(rq);
518         struct cfq_data *cfqd = cfqq->cfqd;
519         struct request *__alias;
520
521         cfqq->queued[rq_is_sync(rq)]++;
522
523         /*
524          * looks a little odd, but the first insert might return an alias.
525          * if that happens, put the alias on the dispatch list
526          */
527         while ((__alias = elv_rb_add(&cfqq->sort_list, rq)) != NULL)
528                 cfq_dispatch_insert(cfqd->queue, __alias);
529
530         if (!cfq_cfqq_on_rr(cfqq))
531                 cfq_add_cfqq_rr(cfqd, cfqq);
532
533         /*
534          * check if this request is a better next-serve candidate
535          */
536         cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq);
537         BUG_ON(!cfqq->next_rq);
538 }
539
540 static inline void
541 cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
542 {
543         elv_rb_del(&cfqq->sort_list, rq);
544         cfqq->queued[rq_is_sync(rq)]--;
545         cfq_add_rq_rb(rq);
546 }
547
548 static struct request *
549 cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
550 {
551         struct task_struct *tsk = current;
552         pid_t key = cfq_queue_pid(tsk, bio_data_dir(bio), bio_sync(bio));
553         struct cfq_queue *cfqq;
554
555         cfqq = cfq_find_cfq_hash(cfqd, key, tsk->ioprio);
556         if (cfqq) {
557                 sector_t sector = bio->bi_sector + bio_sectors(bio);
558
559                 return elv_rb_find(&cfqq->sort_list, sector);
560         }
561
562         return NULL;
563 }
564
565 static void cfq_activate_request(request_queue_t *q, struct request *rq)
566 {
567         struct cfq_data *cfqd = q->elevator->elevator_data;
568
569         cfqd->rq_in_driver++;
570
571         /*
572          * If the depth is larger 1, it really could be queueing. But lets
573          * make the mark a little higher - idling could still be good for
574          * low queueing, and a low queueing number could also just indicate
575          * a SCSI mid layer like behaviour where limit+1 is often seen.
576          */
577         if (!cfqd->hw_tag && cfqd->rq_in_driver > 4)
578                 cfqd->hw_tag = 1;
579
580         cfqd->last_position = rq->hard_sector + rq->hard_nr_sectors;
581 }
582
583 static void cfq_deactivate_request(request_queue_t *q, struct request *rq)
584 {
585         struct cfq_data *cfqd = q->elevator->elevator_data;
586
587         WARN_ON(!cfqd->rq_in_driver);
588         cfqd->rq_in_driver--;
589 }
590
591 static void cfq_remove_request(struct request *rq)
592 {
593         struct cfq_queue *cfqq = RQ_CFQQ(rq);
594
595         if (cfqq->next_rq == rq)
596                 cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
597
598         list_del_init(&rq->queuelist);
599         cfq_del_rq_rb(rq);
600
601         if (rq_is_meta(rq)) {
602                 WARN_ON(!cfqq->meta_pending);
603                 cfqq->meta_pending--;
604         }
605 }
606
607 static int
608 cfq_merge(request_queue_t *q, struct request **req, struct bio *bio)
609 {
610         struct cfq_data *cfqd = q->elevator->elevator_data;
611         struct request *__rq;
612
613         __rq = cfq_find_rq_fmerge(cfqd, bio);
614         if (__rq && elv_rq_merge_ok(__rq, bio)) {
615                 *req = __rq;
616                 return ELEVATOR_FRONT_MERGE;
617         }
618
619         return ELEVATOR_NO_MERGE;
620 }
621
622 static void cfq_merged_request(request_queue_t *q, struct request *req,
623                                int type)
624 {
625         if (type == ELEVATOR_FRONT_MERGE) {
626                 struct cfq_queue *cfqq = RQ_CFQQ(req);
627
628                 cfq_reposition_rq_rb(cfqq, req);
629         }
630 }
631
632 static void
633 cfq_merged_requests(request_queue_t *q, struct request *rq,
634                     struct request *next)
635 {
636         /*
637          * reposition in fifo if next is older than rq
638          */
639         if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
640             time_before(next->start_time, rq->start_time))
641                 list_move(&rq->queuelist, &next->queuelist);
642
643         cfq_remove_request(next);
644 }
645
646 static int cfq_allow_merge(request_queue_t *q, struct request *rq,
647                            struct bio *bio)
648 {
649         struct cfq_data *cfqd = q->elevator->elevator_data;
650         const int rw = bio_data_dir(bio);
651         struct cfq_queue *cfqq;
652         pid_t key;
653
654         /*
655          * Disallow merge of a sync bio into an async request.
656          */
657         if ((bio_data_dir(bio) == READ || bio_sync(bio)) && !rq_is_sync(rq))
658                 return 0;
659
660         /*
661          * Lookup the cfqq that this bio will be queued with. Allow
662          * merge only if rq is queued there.
663          */
664         key = cfq_queue_pid(current, rw, bio_sync(bio));
665         cfqq = cfq_find_cfq_hash(cfqd, key, current->ioprio);
666
667         if (cfqq == RQ_CFQQ(rq))
668                 return 1;
669
670         return 0;
671 }
672
673 static inline void
674 __cfq_set_active_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
675 {
676         if (cfqq) {
677                 /*
678                  * stop potential idle class queues waiting service
679                  */
680                 del_timer(&cfqd->idle_class_timer);
681
682                 cfqq->slice_end = 0;
683                 cfq_clear_cfqq_must_alloc_slice(cfqq);
684                 cfq_clear_cfqq_fifo_expire(cfqq);
685                 cfq_mark_cfqq_slice_new(cfqq);
686                 cfq_clear_cfqq_queue_new(cfqq);
687                 cfqq->rr_tick = cfqd->cur_rr_tick;
688         }
689
690         cfqd->active_queue = cfqq;
691 }
692
693 /*
694  * current cfqq expired its slice (or was too idle), select new one
695  */
696 static void
697 __cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
698                     int preempted, int timed_out)
699 {
700         if (cfq_cfqq_wait_request(cfqq))
701                 del_timer(&cfqd->idle_slice_timer);
702
703         cfq_clear_cfqq_must_dispatch(cfqq);
704         cfq_clear_cfqq_wait_request(cfqq);
705
706         /*
707          * store what was left of this slice, if the queue idled out
708          * or was preempted
709          */
710         if (timed_out && !cfq_cfqq_slice_new(cfqq))
711                 cfqq->slice_resid = cfqq->slice_end - jiffies;
712
713         cfq_resort_rr_list(cfqq, preempted);
714
715         if (cfqq == cfqd->active_queue)
716                 cfqd->active_queue = NULL;
717
718         if (cfqd->active_cic) {
719                 put_io_context(cfqd->active_cic->ioc);
720                 cfqd->active_cic = NULL;
721         }
722
723         cfqd->dispatch_slice = 0;
724 }
725
726 static inline void cfq_slice_expired(struct cfq_data *cfqd, int preempted,
727                                      int timed_out)
728 {
729         struct cfq_queue *cfqq = cfqd->active_queue;
730
731         if (cfqq)
732                 __cfq_slice_expired(cfqd, cfqq, preempted, timed_out);
733 }
734
735 /*
736  * 0
737  * 0,1
738  * 0,1,2
739  * 0,1,2,3
740  * 0,1,2,3,4
741  * 0,1,2,3,4,5
742  * 0,1,2,3,4,5,6
743  * 0,1,2,3,4,5,6,7
744  */
745 static int cfq_get_next_prio_level(struct cfq_data *cfqd)
746 {
747         int prio, wrap;
748
749         prio = -1;
750         wrap = 0;
751         do {
752                 int p;
753
754                 for (p = cfqd->cur_prio; p <= cfqd->cur_end_prio; p++) {
755                         if (!list_empty(&cfqd->rr_list[p])) {
756                                 prio = p;
757                                 break;
758                         }
759                 }
760
761                 if (prio != -1)
762                         break;
763                 cfqd->cur_prio = 0;
764                 if (++cfqd->cur_end_prio == CFQ_PRIO_LISTS) {
765                         cfqd->cur_end_prio = 0;
766                         if (wrap)
767                                 break;
768                         wrap = 1;
769                 }
770         } while (1);
771
772         if (unlikely(prio == -1))
773                 return -1;
774
775         BUG_ON(prio >= CFQ_PRIO_LISTS);
776
777         list_splice_init(&cfqd->rr_list[prio], &cfqd->cur_rr);
778
779         cfqd->cur_prio = prio + 1;
780         if (cfqd->cur_prio > cfqd->cur_end_prio) {
781                 cfqd->cur_end_prio = cfqd->cur_prio;
782                 cfqd->cur_prio = 0;
783         }
784         if (cfqd->cur_end_prio == CFQ_PRIO_LISTS) {
785                 cfqd->cur_prio = 0;
786                 cfqd->cur_end_prio = 0;
787         }
788
789         cfqd->cur_rr_tick++;
790         cfqd->prio_time = jiffies;
791         return prio;
792 }
793
794 static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
795                                           struct request *rq)
796 {
797         if (rq->sector >= cfqd->last_position)
798                 return rq->sector - cfqd->last_position;
799         else
800                 return cfqd->last_position - rq->sector;
801 }
802
803 static struct cfq_queue *cfq_get_best_queue(struct cfq_data *cfqd)
804 {
805         struct cfq_queue *cfqq = NULL, *__cfqq;
806         sector_t best = -1, first = -1, dist;
807
808         list_for_each_entry(__cfqq, &cfqd->cur_rr, cfq_list) {
809                 if (!__cfqq->next_rq || !cfq_cfqq_sync(__cfqq))
810                         continue;
811
812                 dist = cfq_dist_from_last(cfqd, __cfqq->next_rq);
813                 if (first == -1)
814                         first = dist;
815                 if (dist < best) {
816                         best = dist;
817                         cfqq = __cfqq;
818                 }
819         }
820
821         /*
822          * Only async queue(s) available, grab first entry. Do the same
823          * if the difference between the first and best isn't more than
824          * twice, to obey fairness.
825          */
826         if (!cfqq || (best && first != best && ((first / best) < 4)))
827                 cfqq = list_entry_cfqq(cfqd->cur_rr.next);
828
829         return cfqq;
830 }
831
832 static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
833 {
834         struct cfq_queue *cfqq = NULL;
835
836         if (!list_empty(&cfqd->cur_rr) || cfq_get_next_prio_level(cfqd) != -1) {
837                 /*
838                  * if current list is non-empty, grab first entry. if it is
839                  * empty, get next prio level and grab first entry then if any
840                  * are spliced
841                  */
842                 cfqq = cfq_get_best_queue(cfqd);
843         } else if (!list_empty(&cfqd->idle_rr)) {
844                 /*
845                  * if we have idle queues and no rt or be queues had pending
846                  * requests, either allow immediate service if the grace period
847                  * has passed or arm the idle grace timer
848                  */
849                 unsigned long end = cfqd->last_end_request + CFQ_IDLE_GRACE;
850
851                 if (time_after_eq(jiffies, end))
852                         cfqq = list_entry_cfqq(cfqd->idle_rr.next);
853                 else
854                         mod_timer(&cfqd->idle_class_timer, end);
855         }
856
857         return cfqq;
858 }
859
860 static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd)
861 {
862         struct cfq_queue *cfqq;
863
864         do {
865                 long prio;
866
867                 cfqq = cfq_get_next_queue(cfqd);
868                 if (!cfqq)
869                         break;
870
871                 prio = cfq_prio_to_slice(cfqd, cfqq);
872                 if (cfqq->slice_resid > -prio)
873                         break;
874
875                 cfqq->slice_resid += prio;
876                 list_del_init(&cfqq->cfq_list);
877                 list_add_tail(&cfqq->cfq_list, &cfqd->rr_list[cfqq->ioprio]);
878                 cfqq = NULL;
879         } while (1);
880
881         __cfq_set_active_queue(cfqd, cfqq);
882         return cfqq;
883 }
884
885 static inline int cfq_rq_close(struct cfq_data *cfqd, struct request *rq)
886 {
887         struct cfq_io_context *cic = cfqd->active_cic;
888
889         if (!sample_valid(cic->seek_samples))
890                 return 0;
891
892         return cfq_dist_from_last(cfqd, rq) <= cic->seek_mean;
893 }
894
895 static struct cfq_queue *__cfq_close_cooperator(struct cfq_data *cfqd,
896                                                 struct cfq_queue *cur_cfqq,
897                                                 struct list_head *list)
898 {
899         struct cfq_queue *cfqq;
900
901         list_for_each_entry(cfqq, list, cfq_list) {
902                 if (cfqq == cur_cfqq || !cfq_cfqq_sync(cfqq))
903                         continue;
904
905                 BUG_ON(!cfqq->next_rq);
906
907                 if (cfq_rq_close(cfqd, cfqq->next_rq))
908                         return cfqq;
909         }
910
911         return NULL;
912 }
913
914 static int cfq_close_cooperator(struct cfq_data *cfqd,
915                                 struct cfq_queue *cur_cfqq)
916 {
917         struct cfq_queue *cfqq;
918
919         if (!cfqd->busy_queues)
920                 return 0;
921
922         /*
923          * check cur_rr and same-prio rr_list for candidates
924          */
925         cfqq = __cfq_close_cooperator(cfqd, cur_cfqq, &cfqd->cur_rr);
926         if (cfqq)
927                 return 1;
928
929         cfqq = __cfq_close_cooperator(cfqd, cur_cfqq, &cfqd->rr_list[cur_cfqq->ioprio]);
930         if (cfqq && (cfqq->rr_tick == cfqd->cur_rr_tick))
931                 cfqq = NULL;
932
933         return cfqq != NULL;
934 }
935
936 #define CIC_SEEKY(cic) ((cic)->seek_mean > (8 * 1024))
937
938 static void cfq_arm_slice_timer(struct cfq_data *cfqd)
939 {
940         struct cfq_queue *cfqq = cfqd->active_queue;
941         struct cfq_io_context *cic;
942         unsigned long sl;
943
944         WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
945         WARN_ON(cfq_cfqq_slice_new(cfqq));
946
947         /*
948          * idle is disabled, either manually or by past process history
949          */
950         if (!cfqd->cfq_slice_idle || !cfq_cfqq_idle_window(cfqq))
951                 return;
952
953         /*
954          * task has exited, don't wait
955          */
956         cic = cfqd->active_cic;
957         if (!cic || !cic->ioc->task)
958                 return;
959
960         /*
961          * See if this prio level has a good candidate
962          */
963         if (cfq_close_cooperator(cfqd, cfqq) &&
964             (sample_valid(cic->ttime_samples) && cic->ttime_mean > 2))
965                 return;
966
967         cfq_mark_cfqq_must_dispatch(cfqq);
968         cfq_mark_cfqq_wait_request(cfqq);
969
970         /*
971          * we don't want to idle for seeks, but we do want to allow
972          * fair distribution of slice time for a process doing back-to-back
973          * seeks. so allow a little bit of time for him to submit a new rq
974          */
975         sl = cfqd->cfq_slice_idle;
976         if (sample_valid(cic->seek_samples) && CIC_SEEKY(cic))
977                 sl = min(sl, msecs_to_jiffies(2));
978
979         mod_timer(&cfqd->idle_slice_timer, jiffies + sl);
980 }
981
982 static void cfq_dispatch_insert(request_queue_t *q, struct request *rq)
983 {
984         struct cfq_queue *cfqq = RQ_CFQQ(rq);
985
986         cfq_remove_request(rq);
987         cfqq->dispatched++;
988         elv_dispatch_sort(q, rq);
989 }
990
991 /*
992  * return expired entry, or NULL to just start from scratch in rbtree
993  */
994 static inline struct request *cfq_check_fifo(struct cfq_queue *cfqq)
995 {
996         struct cfq_data *cfqd = cfqq->cfqd;
997         struct request *rq;
998         int fifo;
999
1000         if (cfq_cfqq_fifo_expire(cfqq))
1001                 return NULL;
1002
1003         cfq_mark_cfqq_fifo_expire(cfqq);
1004
1005         if (list_empty(&cfqq->fifo))
1006                 return NULL;
1007
1008         fifo = cfq_cfqq_sync(cfqq);
1009         rq = rq_entry_fifo(cfqq->fifo.next);
1010
1011         if (time_before(jiffies, rq->start_time + cfqd->cfq_fifo_expire[fifo]))
1012                 return NULL;
1013
1014         return rq;
1015 }
1016
1017 static inline int
1018 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1019 {
1020         const int base_rq = cfqd->cfq_slice_async_rq;
1021
1022         WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
1023
1024         return 2 * (base_rq + base_rq * (CFQ_PRIO_LISTS - 1 - cfqq->ioprio));
1025 }
1026
1027 /*
1028  * get next queue for service
1029  */
1030 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
1031 {
1032         struct cfq_queue *cfqq;
1033
1034         cfqq = cfqd->active_queue;
1035         if (!cfqq)
1036                 goto new_queue;
1037
1038         /*
1039          * The active queue has run out of time, expire it and select new.
1040          */
1041         if (cfq_slice_used(cfqq))
1042                 goto expire;
1043
1044         /*
1045          * The active queue has requests and isn't expired, allow it to
1046          * dispatch.
1047          */
1048         if (!RB_EMPTY_ROOT(&cfqq->sort_list))
1049                 goto keep_queue;
1050
1051         /*
1052          * No requests pending. If the active queue still has requests in
1053          * flight or is idling for a new request, allow either of these
1054          * conditions to happen (or time out) before selecting a new queue.
1055          */
1056         if (cfqq->dispatched || timer_pending(&cfqd->idle_slice_timer)) {
1057                 cfqq = NULL;
1058                 goto keep_queue;
1059         }
1060
1061 expire:
1062         cfq_slice_expired(cfqd, 0, 0);
1063 new_queue:
1064         cfqq = cfq_set_active_queue(cfqd);
1065 keep_queue:
1066         return cfqq;
1067 }
1068
1069 static int
1070 __cfq_dispatch_requests(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1071                         int max_dispatch)
1072 {
1073         int dispatched = 0;
1074
1075         BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
1076
1077         do {
1078                 struct request *rq;
1079
1080                 /*
1081                  * follow expired path, else get first next available
1082                  */
1083                 if ((rq = cfq_check_fifo(cfqq)) == NULL)
1084                         rq = cfqq->next_rq;
1085
1086                 /*
1087                  * finally, insert request into driver dispatch list
1088                  */
1089                 cfq_dispatch_insert(cfqd->queue, rq);
1090
1091                 cfqd->dispatch_slice++;
1092                 dispatched++;
1093
1094                 if (!cfqd->active_cic) {
1095                         atomic_inc(&RQ_CIC(rq)->ioc->refcount);
1096                         cfqd->active_cic = RQ_CIC(rq);
1097                 }
1098
1099                 if (RB_EMPTY_ROOT(&cfqq->sort_list))
1100                         break;
1101
1102         } while (dispatched < max_dispatch);
1103
1104         /*
1105          * expire an async queue immediately if it has used up its slice. idle
1106          * queue always expire after 1 dispatch round.
1107          */
1108         if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
1109             cfqd->dispatch_slice >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
1110             cfq_class_idle(cfqq))) {
1111                 cfqq->slice_end = jiffies + 1;
1112                 cfq_slice_expired(cfqd, 0, 0);
1113         }
1114
1115         return dispatched;
1116 }
1117
1118 static int
1119 cfq_forced_dispatch_cfqqs(struct list_head *list)
1120 {
1121         struct cfq_queue *cfqq, *next;
1122         int dispatched;
1123
1124         dispatched = 0;
1125         list_for_each_entry_safe(cfqq, next, list, cfq_list) {
1126                 while (cfqq->next_rq) {
1127                         cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
1128                         dispatched++;
1129                 }
1130                 BUG_ON(!list_empty(&cfqq->fifo));
1131         }
1132
1133         return dispatched;
1134 }
1135
1136 static int
1137 cfq_forced_dispatch(struct cfq_data *cfqd)
1138 {
1139         int i, dispatched = 0;
1140
1141         for (i = 0; i < CFQ_PRIO_LISTS; i++)
1142                 dispatched += cfq_forced_dispatch_cfqqs(&cfqd->rr_list[i]);
1143
1144         dispatched += cfq_forced_dispatch_cfqqs(&cfqd->cur_rr);
1145         dispatched += cfq_forced_dispatch_cfqqs(&cfqd->idle_rr);
1146
1147         cfq_slice_expired(cfqd, 0, 0);
1148
1149         BUG_ON(cfqd->busy_queues);
1150
1151         return dispatched;
1152 }
1153
1154 static int
1155 cfq_dispatch_requests(request_queue_t *q, int force)
1156 {
1157         struct cfq_data *cfqd = q->elevator->elevator_data;
1158         struct cfq_queue *cfqq;
1159         int dispatched;
1160
1161         if (!cfqd->busy_queues)
1162                 return 0;
1163
1164         if (unlikely(force))
1165                 return cfq_forced_dispatch(cfqd);
1166
1167         dispatched = 0;
1168         while ((cfqq = cfq_select_queue(cfqd)) != NULL) {
1169                 int max_dispatch;
1170
1171                 if (cfqd->busy_queues > 1) {
1172                         /*
1173                          * So we have dispatched before in this round, if the
1174                          * next queue has idling enabled (must be sync), don't
1175                          * allow it service until the previous have completed.
1176                          */
1177                         if (cfqd->rq_in_driver && cfq_cfqq_idle_window(cfqq) &&
1178                             dispatched)
1179                                 break;
1180                         if (cfqq->dispatched >= cfqd->cfq_quantum)
1181                                 break;
1182                 }
1183
1184                 cfq_clear_cfqq_must_dispatch(cfqq);
1185                 cfq_clear_cfqq_wait_request(cfqq);
1186                 del_timer(&cfqd->idle_slice_timer);
1187
1188                 max_dispatch = cfqd->cfq_quantum;
1189                 if (cfq_class_idle(cfqq))
1190                         max_dispatch = 1;
1191
1192                 dispatched += __cfq_dispatch_requests(cfqd, cfqq, max_dispatch);
1193         }
1194
1195         return dispatched;
1196 }
1197
1198 /*
1199  * task holds one reference to the queue, dropped when task exits. each rq
1200  * in-flight on this queue also holds a reference, dropped when rq is freed.
1201  *
1202  * queue lock must be held here.
1203  */
1204 static void cfq_put_queue(struct cfq_queue *cfqq)
1205 {
1206         struct cfq_data *cfqd = cfqq->cfqd;
1207
1208         BUG_ON(atomic_read(&cfqq->ref) <= 0);
1209
1210         if (!atomic_dec_and_test(&cfqq->ref))
1211                 return;
1212
1213         BUG_ON(rb_first(&cfqq->sort_list));
1214         BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
1215         BUG_ON(cfq_cfqq_on_rr(cfqq));
1216
1217         if (unlikely(cfqd->active_queue == cfqq)) {
1218                 __cfq_slice_expired(cfqd, cfqq, 0, 0);
1219                 cfq_schedule_dispatch(cfqd);
1220         }
1221
1222         /*
1223          * it's on the empty list and still hashed
1224          */
1225         list_del(&cfqq->cfq_list);
1226         hlist_del(&cfqq->cfq_hash);
1227         kmem_cache_free(cfq_pool, cfqq);
1228 }
1229
1230 static struct cfq_queue *
1231 __cfq_find_cfq_hash(struct cfq_data *cfqd, unsigned int key, unsigned int prio,
1232                     const int hashval)
1233 {
1234         struct hlist_head *hash_list = &cfqd->cfq_hash[hashval];
1235         struct hlist_node *entry;
1236         struct cfq_queue *__cfqq;
1237
1238         hlist_for_each_entry(__cfqq, entry, hash_list, cfq_hash) {
1239                 const unsigned short __p = IOPRIO_PRIO_VALUE(__cfqq->org_ioprio_class, __cfqq->org_ioprio);
1240
1241                 if (__cfqq->key == key && (__p == prio || !prio))
1242                         return __cfqq;
1243         }
1244
1245         return NULL;
1246 }
1247
1248 static struct cfq_queue *
1249 cfq_find_cfq_hash(struct cfq_data *cfqd, unsigned int key, unsigned short prio)
1250 {
1251         return __cfq_find_cfq_hash(cfqd, key, prio, hash_long(key, CFQ_QHASH_SHIFT));
1252 }
1253
1254 static void cfq_free_io_context(struct io_context *ioc)
1255 {
1256         struct cfq_io_context *__cic;
1257         struct rb_node *n;
1258         int freed = 0;
1259
1260         while ((n = rb_first(&ioc->cic_root)) != NULL) {
1261                 __cic = rb_entry(n, struct cfq_io_context, rb_node);
1262                 rb_erase(&__cic->rb_node, &ioc->cic_root);
1263                 kmem_cache_free(cfq_ioc_pool, __cic);
1264                 freed++;
1265         }
1266
1267         elv_ioc_count_mod(ioc_count, -freed);
1268
1269         if (ioc_gone && !elv_ioc_count_read(ioc_count))
1270                 complete(ioc_gone);
1271 }
1272
1273 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1274 {
1275         if (unlikely(cfqq == cfqd->active_queue)) {
1276                 __cfq_slice_expired(cfqd, cfqq, 0, 0);
1277                 cfq_schedule_dispatch(cfqd);
1278         }
1279
1280         cfq_put_queue(cfqq);
1281 }
1282
1283 static void __cfq_exit_single_io_context(struct cfq_data *cfqd,
1284                                          struct cfq_io_context *cic)
1285 {
1286         list_del_init(&cic->queue_list);
1287         smp_wmb();
1288         cic->key = NULL;
1289
1290         if (cic->cfqq[ASYNC]) {
1291                 cfq_exit_cfqq(cfqd, cic->cfqq[ASYNC]);
1292                 cic->cfqq[ASYNC] = NULL;
1293         }
1294
1295         if (cic->cfqq[SYNC]) {
1296                 cfq_exit_cfqq(cfqd, cic->cfqq[SYNC]);
1297                 cic->cfqq[SYNC] = NULL;
1298         }
1299 }
1300
1301
1302 /*
1303  * Called with interrupts disabled
1304  */
1305 static void cfq_exit_single_io_context(struct cfq_io_context *cic)
1306 {
1307         struct cfq_data *cfqd = cic->key;
1308
1309         if (cfqd) {
1310                 request_queue_t *q = cfqd->queue;
1311
1312                 spin_lock_irq(q->queue_lock);
1313                 __cfq_exit_single_io_context(cfqd, cic);
1314                 spin_unlock_irq(q->queue_lock);
1315         }
1316 }
1317
1318 static void cfq_exit_io_context(struct io_context *ioc)
1319 {
1320         struct cfq_io_context *__cic;
1321         struct rb_node *n;
1322
1323         /*
1324          * put the reference this task is holding to the various queues
1325          */
1326
1327         n = rb_first(&ioc->cic_root);
1328         while (n != NULL) {
1329                 __cic = rb_entry(n, struct cfq_io_context, rb_node);
1330
1331                 cfq_exit_single_io_context(__cic);
1332                 n = rb_next(n);
1333         }
1334 }
1335
1336 static struct cfq_io_context *
1337 cfq_alloc_io_context(struct cfq_data *cfqd, gfp_t gfp_mask)
1338 {
1339         struct cfq_io_context *cic;
1340
1341         cic = kmem_cache_alloc_node(cfq_ioc_pool, gfp_mask, cfqd->queue->node);
1342         if (cic) {
1343                 memset(cic, 0, sizeof(*cic));
1344                 cic->last_end_request = jiffies;
1345                 INIT_LIST_HEAD(&cic->queue_list);
1346                 cic->dtor = cfq_free_io_context;
1347                 cic->exit = cfq_exit_io_context;
1348                 elv_ioc_count_inc(ioc_count);
1349         }
1350
1351         return cic;
1352 }
1353
1354 static void cfq_init_prio_data(struct cfq_queue *cfqq)
1355 {
1356         struct task_struct *tsk = current;
1357         int ioprio_class;
1358
1359         if (!cfq_cfqq_prio_changed(cfqq))
1360                 return;
1361
1362         ioprio_class = IOPRIO_PRIO_CLASS(tsk->ioprio);
1363         switch (ioprio_class) {
1364                 default:
1365                         printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
1366                 case IOPRIO_CLASS_NONE:
1367                         /*
1368                          * no prio set, place us in the middle of the BE classes
1369                          */
1370                         cfqq->ioprio = task_nice_ioprio(tsk);
1371                         cfqq->ioprio_class = IOPRIO_CLASS_BE;
1372                         break;
1373                 case IOPRIO_CLASS_RT:
1374                         cfqq->ioprio = task_ioprio(tsk);
1375                         cfqq->ioprio_class = IOPRIO_CLASS_RT;
1376                         break;
1377                 case IOPRIO_CLASS_BE:
1378                         cfqq->ioprio = task_ioprio(tsk);
1379                         cfqq->ioprio_class = IOPRIO_CLASS_BE;
1380                         break;
1381                 case IOPRIO_CLASS_IDLE:
1382                         cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
1383                         cfqq->ioprio = 7;
1384                         cfq_clear_cfqq_idle_window(cfqq);
1385                         break;
1386         }
1387
1388         /*
1389          * keep track of original prio settings in case we have to temporarily
1390          * elevate the priority of this queue
1391          */
1392         cfqq->org_ioprio = cfqq->ioprio;
1393         cfqq->org_ioprio_class = cfqq->ioprio_class;
1394
1395         cfq_resort_rr_list(cfqq, 0);
1396         cfq_clear_cfqq_prio_changed(cfqq);
1397 }
1398
1399 static inline void changed_ioprio(struct cfq_io_context *cic)
1400 {
1401         struct cfq_data *cfqd = cic->key;
1402         struct cfq_queue *cfqq;
1403         unsigned long flags;
1404
1405         if (unlikely(!cfqd))
1406                 return;
1407
1408         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
1409
1410         cfqq = cic->cfqq[ASYNC];
1411         if (cfqq) {
1412                 struct cfq_queue *new_cfqq;
1413                 new_cfqq = cfq_get_queue(cfqd, CFQ_KEY_ASYNC, cic->ioc->task,
1414                                          GFP_ATOMIC);
1415                 if (new_cfqq) {
1416                         cic->cfqq[ASYNC] = new_cfqq;
1417                         cfq_put_queue(cfqq);
1418                 }
1419         }
1420
1421         cfqq = cic->cfqq[SYNC];
1422         if (cfqq)
1423                 cfq_mark_cfqq_prio_changed(cfqq);
1424
1425         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
1426 }
1427
1428 static void cfq_ioc_set_ioprio(struct io_context *ioc)
1429 {
1430         struct cfq_io_context *cic;
1431         struct rb_node *n;
1432
1433         ioc->ioprio_changed = 0;
1434
1435         n = rb_first(&ioc->cic_root);
1436         while (n != NULL) {
1437                 cic = rb_entry(n, struct cfq_io_context, rb_node);
1438
1439                 changed_ioprio(cic);
1440                 n = rb_next(n);
1441         }
1442 }
1443
1444 static struct cfq_queue *
1445 cfq_get_queue(struct cfq_data *cfqd, unsigned int key, struct task_struct *tsk,
1446               gfp_t gfp_mask)
1447 {
1448         const int hashval = hash_long(key, CFQ_QHASH_SHIFT);
1449         struct cfq_queue *cfqq, *new_cfqq = NULL;
1450         unsigned short ioprio;
1451
1452 retry:
1453         ioprio = tsk->ioprio;
1454         cfqq = __cfq_find_cfq_hash(cfqd, key, ioprio, hashval);
1455
1456         if (!cfqq) {
1457                 if (new_cfqq) {
1458                         cfqq = new_cfqq;
1459                         new_cfqq = NULL;
1460                 } else if (gfp_mask & __GFP_WAIT) {
1461                         /*
1462                          * Inform the allocator of the fact that we will
1463                          * just repeat this allocation if it fails, to allow
1464                          * the allocator to do whatever it needs to attempt to
1465                          * free memory.
1466                          */
1467                         spin_unlock_irq(cfqd->queue->queue_lock);
1468                         new_cfqq = kmem_cache_alloc_node(cfq_pool, gfp_mask|__GFP_NOFAIL, cfqd->queue->node);
1469                         spin_lock_irq(cfqd->queue->queue_lock);
1470                         goto retry;
1471                 } else {
1472                         cfqq = kmem_cache_alloc_node(cfq_pool, gfp_mask, cfqd->queue->node);
1473                         if (!cfqq)
1474                                 goto out;
1475                 }
1476
1477                 memset(cfqq, 0, sizeof(*cfqq));
1478
1479                 INIT_HLIST_NODE(&cfqq->cfq_hash);
1480                 INIT_LIST_HEAD(&cfqq->cfq_list);
1481                 INIT_LIST_HEAD(&cfqq->fifo);
1482
1483                 cfqq->key = key;
1484                 hlist_add_head(&cfqq->cfq_hash, &cfqd->cfq_hash[hashval]);
1485                 atomic_set(&cfqq->ref, 0);
1486                 cfqq->cfqd = cfqd;
1487
1488                 if (key != CFQ_KEY_ASYNC)
1489                         cfq_mark_cfqq_idle_window(cfqq);
1490
1491                 cfq_mark_cfqq_prio_changed(cfqq);
1492                 cfq_mark_cfqq_queue_new(cfqq);
1493                 cfq_init_prio_data(cfqq);
1494         }
1495
1496         if (new_cfqq)
1497                 kmem_cache_free(cfq_pool, new_cfqq);
1498
1499         atomic_inc(&cfqq->ref);
1500 out:
1501         WARN_ON((gfp_mask & __GFP_WAIT) && !cfqq);
1502         return cfqq;
1503 }
1504
1505 static void
1506 cfq_drop_dead_cic(struct io_context *ioc, struct cfq_io_context *cic)
1507 {
1508         WARN_ON(!list_empty(&cic->queue_list));
1509         rb_erase(&cic->rb_node, &ioc->cic_root);
1510         kmem_cache_free(cfq_ioc_pool, cic);
1511         elv_ioc_count_dec(ioc_count);
1512 }
1513
1514 static struct cfq_io_context *
1515 cfq_cic_rb_lookup(struct cfq_data *cfqd, struct io_context *ioc)
1516 {
1517         struct rb_node *n;
1518         struct cfq_io_context *cic;
1519         void *k, *key = cfqd;
1520
1521 restart:
1522         n = ioc->cic_root.rb_node;
1523         while (n) {
1524                 cic = rb_entry(n, struct cfq_io_context, rb_node);
1525                 /* ->key must be copied to avoid race with cfq_exit_queue() */
1526                 k = cic->key;
1527                 if (unlikely(!k)) {
1528                         cfq_drop_dead_cic(ioc, cic);
1529                         goto restart;
1530                 }
1531
1532                 if (key < k)
1533                         n = n->rb_left;
1534                 else if (key > k)
1535                         n = n->rb_right;
1536                 else
1537                         return cic;
1538         }
1539
1540         return NULL;
1541 }
1542
1543 static inline void
1544 cfq_cic_link(struct cfq_data *cfqd, struct io_context *ioc,
1545              struct cfq_io_context *cic)
1546 {
1547         struct rb_node **p;
1548         struct rb_node *parent;
1549         struct cfq_io_context *__cic;
1550         unsigned long flags;
1551         void *k;
1552
1553         cic->ioc = ioc;
1554         cic->key = cfqd;
1555
1556 restart:
1557         parent = NULL;
1558         p = &ioc->cic_root.rb_node;
1559         while (*p) {
1560                 parent = *p;
1561                 __cic = rb_entry(parent, struct cfq_io_context, rb_node);
1562                 /* ->key must be copied to avoid race with cfq_exit_queue() */
1563                 k = __cic->key;
1564                 if (unlikely(!k)) {
1565                         cfq_drop_dead_cic(ioc, __cic);
1566                         goto restart;
1567                 }
1568
1569                 if (cic->key < k)
1570                         p = &(*p)->rb_left;
1571                 else if (cic->key > k)
1572                         p = &(*p)->rb_right;
1573                 else
1574                         BUG();
1575         }
1576
1577         rb_link_node(&cic->rb_node, parent, p);
1578         rb_insert_color(&cic->rb_node, &ioc->cic_root);
1579
1580         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
1581         list_add(&cic->queue_list, &cfqd->cic_list);
1582         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
1583 }
1584
1585 /*
1586  * Setup general io context and cfq io context. There can be several cfq
1587  * io contexts per general io context, if this process is doing io to more
1588  * than one device managed by cfq.
1589  */
1590 static struct cfq_io_context *
1591 cfq_get_io_context(struct cfq_data *cfqd, gfp_t gfp_mask)
1592 {
1593         struct io_context *ioc = NULL;
1594         struct cfq_io_context *cic;
1595
1596         might_sleep_if(gfp_mask & __GFP_WAIT);
1597
1598         ioc = get_io_context(gfp_mask, cfqd->queue->node);
1599         if (!ioc)
1600                 return NULL;
1601
1602         cic = cfq_cic_rb_lookup(cfqd, ioc);
1603         if (cic)
1604                 goto out;
1605
1606         cic = cfq_alloc_io_context(cfqd, gfp_mask);
1607         if (cic == NULL)
1608                 goto err;
1609
1610         cfq_cic_link(cfqd, ioc, cic);
1611 out:
1612         smp_read_barrier_depends();
1613         if (unlikely(ioc->ioprio_changed))
1614                 cfq_ioc_set_ioprio(ioc);
1615
1616         return cic;
1617 err:
1618         put_io_context(ioc);
1619         return NULL;
1620 }
1621
1622 static void
1623 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_io_context *cic)
1624 {
1625         unsigned long elapsed = jiffies - cic->last_end_request;
1626         unsigned long ttime = min(elapsed, 2UL * cfqd->cfq_slice_idle);
1627
1628         cic->ttime_samples = (7*cic->ttime_samples + 256) / 8;
1629         cic->ttime_total = (7*cic->ttime_total + 256*ttime) / 8;
1630         cic->ttime_mean = (cic->ttime_total + 128) / cic->ttime_samples;
1631 }
1632
1633 static void
1634 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_io_context *cic,
1635                        struct request *rq)
1636 {
1637         sector_t sdist;
1638         u64 total;
1639
1640         if (cic->last_request_pos < rq->sector)
1641                 sdist = rq->sector - cic->last_request_pos;
1642         else
1643                 sdist = cic->last_request_pos - rq->sector;
1644
1645         if (!cic->seek_samples) {
1646                 cfqd->new_seek_total = (7*cic->seek_total + (u64)256*sdist) / 8;
1647                 cfqd->new_seek_mean = cfqd->new_seek_total / 256;
1648         }
1649
1650         /*
1651          * Don't allow the seek distance to get too large from the
1652          * odd fragment, pagein, etc
1653          */
1654         if (cic->seek_samples <= 60) /* second&third seek */
1655                 sdist = min(sdist, (cic->seek_mean * 4) + 2*1024*1024);
1656         else
1657                 sdist = min(sdist, (cic->seek_mean * 4) + 2*1024*64);
1658
1659         cic->seek_samples = (7*cic->seek_samples + 256) / 8;
1660         cic->seek_total = (7*cic->seek_total + (u64)256*sdist) / 8;
1661         total = cic->seek_total + (cic->seek_samples/2);
1662         do_div(total, cic->seek_samples);
1663         cic->seek_mean = (sector_t)total;
1664 }
1665
1666 /*
1667  * Disable idle window if the process thinks too long or seeks so much that
1668  * it doesn't matter
1669  */
1670 static void
1671 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1672                        struct cfq_io_context *cic)
1673 {
1674         int enable_idle = cfq_cfqq_idle_window(cfqq);
1675
1676         if (!cic->ioc->task || !cfqd->cfq_slice_idle ||
1677             (cfqd->hw_tag && CIC_SEEKY(cic)))
1678                 enable_idle = 0;
1679         else if (sample_valid(cic->ttime_samples)) {
1680                 if (cic->ttime_mean > cfqd->cfq_slice_idle)
1681                         enable_idle = 0;
1682                 else
1683                         enable_idle = 1;
1684         }
1685
1686         if (enable_idle)
1687                 cfq_mark_cfqq_idle_window(cfqq);
1688         else
1689                 cfq_clear_cfqq_idle_window(cfqq);
1690 }
1691
1692 /*
1693  * Check if new_cfqq should preempt the currently active queue. Return 0 for
1694  * no or if we aren't sure, a 1 will cause a preempt.
1695  */
1696 static int
1697 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
1698                    struct request *rq)
1699 {
1700         struct cfq_queue *cfqq;
1701
1702         cfqq = cfqd->active_queue;
1703         if (!cfqq)
1704                 return 0;
1705
1706         if (cfq_slice_used(cfqq))
1707                 return 1;
1708
1709         if (cfq_class_idle(new_cfqq))
1710                 return 0;
1711
1712         if (cfq_class_idle(cfqq))
1713                 return 1;
1714
1715         /*
1716          * if the new request is sync, but the currently running queue is
1717          * not, let the sync request have priority.
1718          */
1719         if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq))
1720                 return 1;
1721
1722         /*
1723          * So both queues are sync. Let the new request get disk time if
1724          * it's a metadata request and the current queue is doing regular IO.
1725          */
1726         if (rq_is_meta(rq) && !cfqq->meta_pending)
1727                 return 1;
1728
1729         if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
1730                 return 0;
1731
1732         /*
1733          * if this request is as-good as one we would expect from the
1734          * current cfqq, let it preempt
1735          */
1736         if (cfq_rq_close(cfqd, rq))
1737                 return 1;
1738
1739         return 0;
1740 }
1741
1742 /*
1743  * cfqq preempts the active queue. if we allowed preempt with no slice left,
1744  * let it have half of its nominal slice.
1745  */
1746 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1747 {
1748         cfq_slice_expired(cfqd, 1, 1);
1749
1750         /*
1751          * Put the new queue at the front of the of the current list,
1752          * so we know that it will be selected next.
1753          */
1754         BUG_ON(!cfq_cfqq_on_rr(cfqq));
1755         list_move(&cfqq->cfq_list, &cfqd->cur_rr);
1756
1757         cfqq->slice_end = 0;
1758         cfq_mark_cfqq_slice_new(cfqq);
1759 }
1760
1761 /*
1762  * Called when a new fs request (rq) is added (to cfqq). Check if there's
1763  * something we should do about it
1764  */
1765 static void
1766 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1767                 struct request *rq)
1768 {
1769         struct cfq_io_context *cic = RQ_CIC(rq);
1770
1771         if (rq_is_meta(rq))
1772                 cfqq->meta_pending++;
1773
1774         cfq_update_io_thinktime(cfqd, cic);
1775         cfq_update_io_seektime(cfqd, cic, rq);
1776         cfq_update_idle_window(cfqd, cfqq, cic);
1777
1778         cic->last_request_pos = rq->sector + rq->nr_sectors;
1779         cfqq->last_request_pos = cic->last_request_pos;
1780
1781         if (cfqq == cfqd->active_queue) {
1782                 /*
1783                  * if we are waiting for a request for this queue, let it rip
1784                  * immediately and flag that we must not expire this queue
1785                  * just now
1786                  */
1787                 if (cfq_cfqq_wait_request(cfqq)) {
1788                         cfq_mark_cfqq_must_dispatch(cfqq);
1789                         del_timer(&cfqd->idle_slice_timer);
1790                         blk_start_queueing(cfqd->queue);
1791                 }
1792         } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
1793                 /*
1794                  * not the active queue - expire current slice if it is
1795                  * idle and has expired it's mean thinktime or this new queue
1796                  * has some old slice time left and is of higher priority
1797                  */
1798                 cfq_preempt_queue(cfqd, cfqq);
1799                 cfq_mark_cfqq_must_dispatch(cfqq);
1800                 blk_start_queueing(cfqd->queue);
1801         }
1802 }
1803
1804 static void cfq_insert_request(request_queue_t *q, struct request *rq)
1805 {
1806         struct cfq_data *cfqd = q->elevator->elevator_data;
1807         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1808
1809         cfq_init_prio_data(cfqq);
1810
1811         cfq_add_rq_rb(rq);
1812
1813         list_add_tail(&rq->queuelist, &cfqq->fifo);
1814
1815         cfq_rq_enqueued(cfqd, cfqq, rq);
1816 }
1817
1818 static void cfq_completed_request(request_queue_t *q, struct request *rq)
1819 {
1820         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1821         struct cfq_data *cfqd = cfqq->cfqd;
1822         const int sync = rq_is_sync(rq);
1823         unsigned long now;
1824
1825         now = jiffies;
1826
1827         WARN_ON(!cfqd->rq_in_driver);
1828         WARN_ON(!cfqq->dispatched);
1829         cfqd->rq_in_driver--;
1830         cfqq->dispatched--;
1831         cfqq->service_last = now;
1832
1833         if (!cfq_class_idle(cfqq))
1834                 cfqd->last_end_request = now;
1835
1836         cfq_resort_rr_list(cfqq, 0);
1837
1838         if (sync)
1839                 RQ_CIC(rq)->last_end_request = now;
1840
1841         /*
1842          * If this is the active queue, check if it needs to be expired,
1843          * or if we want to idle in case it has no pending requests.
1844          */
1845         if (cfqd->active_queue == cfqq) {
1846                 if (cfq_cfqq_slice_new(cfqq)) {
1847                         cfq_set_prio_slice(cfqd, cfqq);
1848                         cfq_clear_cfqq_slice_new(cfqq);
1849                 }
1850                 if (cfq_slice_used(cfqq))
1851                         cfq_slice_expired(cfqd, 0, 1);
1852                 else if (sync && RB_EMPTY_ROOT(&cfqq->sort_list))
1853                         cfq_arm_slice_timer(cfqd);
1854         }
1855
1856         if (!cfqd->rq_in_driver)
1857                 cfq_schedule_dispatch(cfqd);
1858 }
1859
1860 /*
1861  * we temporarily boost lower priority queues if they are holding fs exclusive
1862  * resources. they are boosted to normal prio (CLASS_BE/4)
1863  */
1864 static void cfq_prio_boost(struct cfq_queue *cfqq)
1865 {
1866         const int ioprio_class = cfqq->ioprio_class;
1867         const int ioprio = cfqq->ioprio;
1868
1869         if (has_fs_excl()) {
1870                 /*
1871                  * boost idle prio on transactions that would lock out other
1872                  * users of the filesystem
1873                  */
1874                 if (cfq_class_idle(cfqq))
1875                         cfqq->ioprio_class = IOPRIO_CLASS_BE;
1876                 if (cfqq->ioprio > IOPRIO_NORM)
1877                         cfqq->ioprio = IOPRIO_NORM;
1878         } else {
1879                 /*
1880                  * check if we need to unboost the queue
1881                  */
1882                 if (cfqq->ioprio_class != cfqq->org_ioprio_class)
1883                         cfqq->ioprio_class = cfqq->org_ioprio_class;
1884                 if (cfqq->ioprio != cfqq->org_ioprio)
1885                         cfqq->ioprio = cfqq->org_ioprio;
1886         }
1887
1888         /*
1889          * refile between round-robin lists if we moved the priority class
1890          */
1891         if ((ioprio_class != cfqq->ioprio_class || ioprio != cfqq->ioprio))
1892                 cfq_resort_rr_list(cfqq, 0);
1893 }
1894
1895 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
1896 {
1897         if ((cfq_cfqq_wait_request(cfqq) || cfq_cfqq_must_alloc(cfqq)) &&
1898             !cfq_cfqq_must_alloc_slice(cfqq)) {
1899                 cfq_mark_cfqq_must_alloc_slice(cfqq);
1900                 return ELV_MQUEUE_MUST;
1901         }
1902
1903         return ELV_MQUEUE_MAY;
1904 }
1905
1906 static int cfq_may_queue(request_queue_t *q, int rw)
1907 {
1908         struct cfq_data *cfqd = q->elevator->elevator_data;
1909         struct task_struct *tsk = current;
1910         struct cfq_queue *cfqq;
1911         unsigned int key;
1912
1913         key = cfq_queue_pid(tsk, rw, rw & REQ_RW_SYNC);
1914
1915         /*
1916          * don't force setup of a queue from here, as a call to may_queue
1917          * does not necessarily imply that a request actually will be queued.
1918          * so just lookup a possibly existing queue, or return 'may queue'
1919          * if that fails
1920          */
1921         cfqq = cfq_find_cfq_hash(cfqd, key, tsk->ioprio);
1922         if (cfqq) {
1923                 cfq_init_prio_data(cfqq);
1924                 cfq_prio_boost(cfqq);
1925
1926                 return __cfq_may_queue(cfqq);
1927         }
1928
1929         return ELV_MQUEUE_MAY;
1930 }
1931
1932 /*
1933  * queue lock held here
1934  */
1935 static void cfq_put_request(struct request *rq)
1936 {
1937         struct cfq_queue *cfqq = RQ_CFQQ(rq);
1938
1939         if (cfqq) {
1940                 const int rw = rq_data_dir(rq);
1941
1942                 BUG_ON(!cfqq->allocated[rw]);
1943                 cfqq->allocated[rw]--;
1944
1945                 put_io_context(RQ_CIC(rq)->ioc);
1946
1947                 rq->elevator_private = NULL;
1948                 rq->elevator_private2 = NULL;
1949
1950                 cfq_put_queue(cfqq);
1951         }
1952 }
1953
1954 /*
1955  * Allocate cfq data structures associated with this request.
1956  */
1957 static int
1958 cfq_set_request(request_queue_t *q, struct request *rq, gfp_t gfp_mask)
1959 {
1960         struct cfq_data *cfqd = q->elevator->elevator_data;
1961         struct task_struct *tsk = current;
1962         struct cfq_io_context *cic;
1963         const int rw = rq_data_dir(rq);
1964         const int is_sync = rq_is_sync(rq);
1965         pid_t key = cfq_queue_pid(tsk, rw, is_sync);
1966         struct cfq_queue *cfqq;
1967         unsigned long flags;
1968
1969         might_sleep_if(gfp_mask & __GFP_WAIT);
1970
1971         cic = cfq_get_io_context(cfqd, gfp_mask);
1972
1973         spin_lock_irqsave(q->queue_lock, flags);
1974
1975         if (!cic)
1976                 goto queue_fail;
1977
1978         if (!cic->cfqq[is_sync]) {
1979                 cfqq = cfq_get_queue(cfqd, key, tsk, gfp_mask);
1980                 if (!cfqq)
1981                         goto queue_fail;
1982
1983                 cic->cfqq[is_sync] = cfqq;
1984         } else
1985                 cfqq = cic->cfqq[is_sync];
1986
1987         cfqq->allocated[rw]++;
1988         cfq_clear_cfqq_must_alloc(cfqq);
1989         atomic_inc(&cfqq->ref);
1990
1991         spin_unlock_irqrestore(q->queue_lock, flags);
1992
1993         rq->elevator_private = cic;
1994         rq->elevator_private2 = cfqq;
1995         return 0;
1996
1997 queue_fail:
1998         if (cic)
1999                 put_io_context(cic->ioc);
2000
2001         cfq_schedule_dispatch(cfqd);
2002         spin_unlock_irqrestore(q->queue_lock, flags);
2003         return 1;
2004 }
2005
2006 static void cfq_kick_queue(struct work_struct *work)
2007 {
2008         struct cfq_data *cfqd =
2009                 container_of(work, struct cfq_data, unplug_work);
2010         request_queue_t *q = cfqd->queue;
2011         unsigned long flags;
2012
2013         spin_lock_irqsave(q->queue_lock, flags);
2014         blk_start_queueing(q);
2015         spin_unlock_irqrestore(q->queue_lock, flags);
2016 }
2017
2018 /*
2019  * Timer running if the active_queue is currently idling inside its time slice
2020  */
2021 static void cfq_idle_slice_timer(unsigned long data)
2022 {
2023         struct cfq_data *cfqd = (struct cfq_data *) data;
2024         struct cfq_queue *cfqq;
2025         unsigned long flags;
2026         int timed_out = 1;
2027
2028         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
2029
2030         if ((cfqq = cfqd->active_queue) != NULL) {
2031                 timed_out = 0;
2032
2033                 /*
2034                  * expired
2035                  */
2036                 if (cfq_slice_used(cfqq))
2037                         goto expire;
2038
2039                 /*
2040                  * only expire and reinvoke request handler, if there are
2041                  * other queues with pending requests
2042                  */
2043                 if (!cfqd->busy_queues)
2044                         goto out_cont;
2045
2046                 /*
2047                  * not expired and it has a request pending, let it dispatch
2048                  */
2049                 if (!RB_EMPTY_ROOT(&cfqq->sort_list)) {
2050                         cfq_mark_cfqq_must_dispatch(cfqq);
2051                         goto out_kick;
2052                 }
2053         }
2054 expire:
2055         cfq_slice_expired(cfqd, 0, timed_out);
2056 out_kick:
2057         cfq_schedule_dispatch(cfqd);
2058 out_cont:
2059         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
2060 }
2061
2062 /*
2063  * Timer running if an idle class queue is waiting for service
2064  */
2065 static void cfq_idle_class_timer(unsigned long data)
2066 {
2067         struct cfq_data *cfqd = (struct cfq_data *) data;
2068         unsigned long flags, end;
2069
2070         spin_lock_irqsave(cfqd->queue->queue_lock, flags);
2071
2072         /*
2073          * race with a non-idle queue, reset timer
2074          */
2075         end = cfqd->last_end_request + CFQ_IDLE_GRACE;
2076         if (!time_after_eq(jiffies, end))
2077                 mod_timer(&cfqd->idle_class_timer, end);
2078         else
2079                 cfq_schedule_dispatch(cfqd);
2080
2081         spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
2082 }
2083
2084 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
2085 {
2086         del_timer_sync(&cfqd->idle_slice_timer);
2087         del_timer_sync(&cfqd->idle_class_timer);
2088         blk_sync_queue(cfqd->queue);
2089 }
2090
2091 static void cfq_exit_queue(elevator_t *e)
2092 {
2093         struct cfq_data *cfqd = e->elevator_data;
2094         request_queue_t *q = cfqd->queue;
2095
2096         cfq_shutdown_timer_wq(cfqd);
2097
2098         spin_lock_irq(q->queue_lock);
2099
2100         if (cfqd->active_queue)
2101                 __cfq_slice_expired(cfqd, cfqd->active_queue, 0, 0);
2102
2103         while (!list_empty(&cfqd->cic_list)) {
2104                 struct cfq_io_context *cic = list_entry(cfqd->cic_list.next,
2105                                                         struct cfq_io_context,
2106                                                         queue_list);
2107
2108                 __cfq_exit_single_io_context(cfqd, cic);
2109         }
2110
2111         spin_unlock_irq(q->queue_lock);
2112
2113         cfq_shutdown_timer_wq(cfqd);
2114
2115         kfree(cfqd->cfq_hash);
2116         kfree(cfqd);
2117 }
2118
2119 static void *cfq_init_queue(request_queue_t *q)
2120 {
2121         struct cfq_data *cfqd;
2122         int i;
2123
2124         cfqd = kmalloc_node(sizeof(*cfqd), GFP_KERNEL, q->node);
2125         if (!cfqd)
2126                 return NULL;
2127
2128         memset(cfqd, 0, sizeof(*cfqd));
2129
2130         for (i = 0; i < CFQ_PRIO_LISTS; i++)
2131                 INIT_LIST_HEAD(&cfqd->rr_list[i]);
2132
2133         INIT_LIST_HEAD(&cfqd->cur_rr);
2134         INIT_LIST_HEAD(&cfqd->idle_rr);
2135         INIT_LIST_HEAD(&cfqd->cic_list);
2136
2137         cfqd->cfq_hash = kmalloc_node(sizeof(struct hlist_head) * CFQ_QHASH_ENTRIES, GFP_KERNEL, q->node);
2138         if (!cfqd->cfq_hash)
2139                 goto out_free;
2140
2141         for (i = 0; i < CFQ_QHASH_ENTRIES; i++)
2142                 INIT_HLIST_HEAD(&cfqd->cfq_hash[i]);
2143
2144         cfqd->queue = q;
2145
2146         init_timer(&cfqd->idle_slice_timer);
2147         cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
2148         cfqd->idle_slice_timer.data = (unsigned long) cfqd;
2149
2150         init_timer(&cfqd->idle_class_timer);
2151         cfqd->idle_class_timer.function = cfq_idle_class_timer;
2152         cfqd->idle_class_timer.data = (unsigned long) cfqd;
2153
2154         INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
2155
2156         cfqd->cfq_quantum = cfq_quantum;
2157         cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
2158         cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
2159         cfqd->cfq_back_max = cfq_back_max;
2160         cfqd->cfq_back_penalty = cfq_back_penalty;
2161         cfqd->cfq_slice[0] = cfq_slice_async;
2162         cfqd->cfq_slice[1] = cfq_slice_sync;
2163         cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
2164         cfqd->cfq_slice_idle = cfq_slice_idle;
2165
2166         return cfqd;
2167 out_free:
2168         kfree(cfqd);
2169         return NULL;
2170 }
2171
2172 static void cfq_slab_kill(void)
2173 {
2174         if (cfq_pool)
2175                 kmem_cache_destroy(cfq_pool);
2176         if (cfq_ioc_pool)
2177                 kmem_cache_destroy(cfq_ioc_pool);
2178 }
2179
2180 static int __init cfq_slab_setup(void)
2181 {
2182         cfq_pool = kmem_cache_create("cfq_pool", sizeof(struct cfq_queue), 0, 0,
2183                                         NULL, NULL);
2184         if (!cfq_pool)
2185                 goto fail;
2186
2187         cfq_ioc_pool = kmem_cache_create("cfq_ioc_pool",
2188                         sizeof(struct cfq_io_context), 0, 0, NULL, NULL);
2189         if (!cfq_ioc_pool)
2190                 goto fail;
2191
2192         return 0;
2193 fail:
2194         cfq_slab_kill();
2195         return -ENOMEM;
2196 }
2197
2198 /*
2199  * sysfs parts below -->
2200  */
2201 static ssize_t
2202 cfq_var_show(unsigned int var, char *page)
2203 {
2204         return sprintf(page, "%d\n", var);
2205 }
2206
2207 static ssize_t
2208 cfq_var_store(unsigned int *var, const char *page, size_t count)
2209 {
2210         char *p = (char *) page;
2211
2212         *var = simple_strtoul(p, &p, 10);
2213         return count;
2214 }
2215
2216 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV)                            \
2217 static ssize_t __FUNC(elevator_t *e, char *page)                        \
2218 {                                                                       \
2219         struct cfq_data *cfqd = e->elevator_data;                       \
2220         unsigned int __data = __VAR;                                    \
2221         if (__CONV)                                                     \
2222                 __data = jiffies_to_msecs(__data);                      \
2223         return cfq_var_show(__data, (page));                            \
2224 }
2225 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
2226 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
2227 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
2228 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
2229 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
2230 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
2231 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
2232 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
2233 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
2234 #undef SHOW_FUNCTION
2235
2236 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV)                 \
2237 static ssize_t __FUNC(elevator_t *e, const char *page, size_t count)    \
2238 {                                                                       \
2239         struct cfq_data *cfqd = e->elevator_data;                       \
2240         unsigned int __data;                                            \
2241         int ret = cfq_var_store(&__data, (page), count);                \
2242         if (__data < (MIN))                                             \
2243                 __data = (MIN);                                         \
2244         else if (__data > (MAX))                                        \
2245                 __data = (MAX);                                         \
2246         if (__CONV)                                                     \
2247                 *(__PTR) = msecs_to_jiffies(__data);                    \
2248         else                                                            \
2249                 *(__PTR) = __data;                                      \
2250         return ret;                                                     \
2251 }
2252 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
2253 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1, UINT_MAX, 1);
2254 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1, UINT_MAX, 1);
2255 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
2256 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1, UINT_MAX, 0);
2257 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
2258 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
2259 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
2260 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1, UINT_MAX, 0);
2261 #undef STORE_FUNCTION
2262
2263 #define CFQ_ATTR(name) \
2264         __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
2265
2266 static struct elv_fs_entry cfq_attrs[] = {
2267         CFQ_ATTR(quantum),
2268         CFQ_ATTR(fifo_expire_sync),
2269         CFQ_ATTR(fifo_expire_async),
2270         CFQ_ATTR(back_seek_max),
2271         CFQ_ATTR(back_seek_penalty),
2272         CFQ_ATTR(slice_sync),
2273         CFQ_ATTR(slice_async),
2274         CFQ_ATTR(slice_async_rq),
2275         CFQ_ATTR(slice_idle),
2276         __ATTR_NULL
2277 };
2278
2279 static struct elevator_type iosched_cfq = {
2280         .ops = {
2281                 .elevator_merge_fn =            cfq_merge,
2282                 .elevator_merged_fn =           cfq_merged_request,
2283                 .elevator_merge_req_fn =        cfq_merged_requests,
2284                 .elevator_allow_merge_fn =      cfq_allow_merge,
2285                 .elevator_dispatch_fn =         cfq_dispatch_requests,
2286                 .elevator_add_req_fn =          cfq_insert_request,
2287                 .elevator_activate_req_fn =     cfq_activate_request,
2288                 .elevator_deactivate_req_fn =   cfq_deactivate_request,
2289                 .elevator_queue_empty_fn =      cfq_queue_empty,
2290                 .elevator_completed_req_fn =    cfq_completed_request,
2291                 .elevator_former_req_fn =       elv_rb_former_request,
2292                 .elevator_latter_req_fn =       elv_rb_latter_request,
2293                 .elevator_set_req_fn =          cfq_set_request,
2294                 .elevator_put_req_fn =          cfq_put_request,
2295                 .elevator_may_queue_fn =        cfq_may_queue,
2296                 .elevator_init_fn =             cfq_init_queue,
2297                 .elevator_exit_fn =             cfq_exit_queue,
2298                 .trim =                         cfq_free_io_context,
2299         },
2300         .elevator_attrs =       cfq_attrs,
2301         .elevator_name =        "cfq",
2302         .elevator_owner =       THIS_MODULE,
2303 };
2304
2305 static int __init cfq_init(void)
2306 {
2307         int ret;
2308
2309         /*
2310          * could be 0 on HZ < 1000 setups
2311          */
2312         if (!cfq_slice_async)
2313                 cfq_slice_async = 1;
2314         if (!cfq_slice_idle)
2315                 cfq_slice_idle = 1;
2316
2317         if (cfq_slab_setup())
2318                 return -ENOMEM;
2319
2320         ret = elv_register(&iosched_cfq);
2321         if (ret)
2322                 cfq_slab_kill();
2323
2324         return ret;
2325 }
2326
2327 static void __exit cfq_exit(void)
2328 {
2329         DECLARE_COMPLETION_ONSTACK(all_gone);
2330         elv_unregister(&iosched_cfq);
2331         ioc_gone = &all_gone;
2332         /* ioc_gone's update must be visible before reading ioc_count */
2333         smp_wmb();
2334         if (elv_ioc_count_read(ioc_count))
2335                 wait_for_completion(ioc_gone);
2336         synchronize_rcu();
2337         cfq_slab_kill();
2338 }
2339
2340 module_init(cfq_init);
2341 module_exit(cfq_exit);
2342
2343 MODULE_AUTHOR("Jens Axboe");
2344 MODULE_LICENSE("GPL");
2345 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");