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