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