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