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