Merge git://git.infradead.org/~dwmw2/rbtree-2.6
[safe/jmp/linux-2.6] / block / as-iosched.c
1 /*
2  *  Anticipatory & deadline i/o scheduler.
3  *
4  *  Copyright (C) 2002 Jens Axboe <axboe@suse.de>
5  *                     Nick Piggin <nickpiggin@yahoo.com.au>
6  *
7  */
8 #include <linux/kernel.h>
9 #include <linux/fs.h>
10 #include <linux/blkdev.h>
11 #include <linux/elevator.h>
12 #include <linux/bio.h>
13 #include <linux/config.h>
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/init.h>
17 #include <linux/compiler.h>
18 #include <linux/hash.h>
19 #include <linux/rbtree.h>
20 #include <linux/interrupt.h>
21
22 #define REQ_SYNC        1
23 #define REQ_ASYNC       0
24
25 /*
26  * See Documentation/block/as-iosched.txt
27  */
28
29 /*
30  * max time before a read is submitted.
31  */
32 #define default_read_expire (HZ / 8)
33
34 /*
35  * ditto for writes, these limits are not hard, even
36  * if the disk is capable of satisfying them.
37  */
38 #define default_write_expire (HZ / 4)
39
40 /*
41  * read_batch_expire describes how long we will allow a stream of reads to
42  * persist before looking to see whether it is time to switch over to writes.
43  */
44 #define default_read_batch_expire (HZ / 2)
45
46 /*
47  * write_batch_expire describes how long we want a stream of writes to run for.
48  * This is not a hard limit, but a target we set for the auto-tuning thingy.
49  * See, the problem is: we can send a lot of writes to disk cache / TCQ in
50  * a short amount of time...
51  */
52 #define default_write_batch_expire (HZ / 8)
53
54 /*
55  * max time we may wait to anticipate a read (default around 6ms)
56  */
57 #define default_antic_expire ((HZ / 150) ? HZ / 150 : 1)
58
59 /*
60  * Keep track of up to 20ms thinktimes. We can go as big as we like here,
61  * however huge values tend to interfere and not decay fast enough. A program
62  * might be in a non-io phase of operation. Waiting on user input for example,
63  * or doing a lengthy computation. A small penalty can be justified there, and
64  * will still catch out those processes that constantly have large thinktimes.
65  */
66 #define MAX_THINKTIME (HZ/50UL)
67
68 /* Bits in as_io_context.state */
69 enum as_io_states {
70         AS_TASK_RUNNING=0,      /* Process has not exited */
71         AS_TASK_IOSTARTED,      /* Process has started some IO */
72         AS_TASK_IORUNNING,      /* Process has completed some IO */
73 };
74
75 enum anticipation_status {
76         ANTIC_OFF=0,            /* Not anticipating (normal operation)  */
77         ANTIC_WAIT_REQ,         /* The last read has not yet completed  */
78         ANTIC_WAIT_NEXT,        /* Currently anticipating a request vs
79                                    last read (which has completed) */
80         ANTIC_FINISHED,         /* Anticipating but have found a candidate
81                                  * or timed out */
82 };
83
84 struct as_data {
85         /*
86          * run time data
87          */
88
89         struct request_queue *q;        /* the "owner" queue */
90
91         /*
92          * requests (as_rq s) are present on both sort_list and fifo_list
93          */
94         struct rb_root sort_list[2];
95         struct list_head fifo_list[2];
96
97         struct as_rq *next_arq[2];      /* next in sort order */
98         sector_t last_sector[2];        /* last REQ_SYNC & REQ_ASYNC sectors */
99         struct list_head *hash;         /* request hash */
100
101         unsigned long exit_prob;        /* probability a task will exit while
102                                            being waited on */
103         unsigned long exit_no_coop;     /* probablility an exited task will
104                                            not be part of a later cooperating
105                                            request */
106         unsigned long new_ttime_total;  /* mean thinktime on new proc */
107         unsigned long new_ttime_mean;
108         u64 new_seek_total;             /* mean seek on new proc */
109         sector_t new_seek_mean;
110
111         unsigned long current_batch_expires;
112         unsigned long last_check_fifo[2];
113         int changed_batch;              /* 1: waiting for old batch to end */
114         int new_batch;                  /* 1: waiting on first read complete */
115         int batch_data_dir;             /* current batch REQ_SYNC / REQ_ASYNC */
116         int write_batch_count;          /* max # of reqs in a write batch */
117         int current_write_count;        /* how many requests left this batch */
118         int write_batch_idled;          /* has the write batch gone idle? */
119         mempool_t *arq_pool;
120
121         enum anticipation_status antic_status;
122         unsigned long antic_start;      /* jiffies: when it started */
123         struct timer_list antic_timer;  /* anticipatory scheduling timer */
124         struct work_struct antic_work;  /* Deferred unplugging */
125         struct io_context *io_context;  /* Identify the expected process */
126         int ioc_finished; /* IO associated with io_context is finished */
127         int nr_dispatched;
128
129         /*
130          * settings that change how the i/o scheduler behaves
131          */
132         unsigned long fifo_expire[2];
133         unsigned long batch_expire[2];
134         unsigned long antic_expire;
135 };
136
137 #define list_entry_fifo(ptr)    list_entry((ptr), struct as_rq, fifo)
138
139 /*
140  * per-request data.
141  */
142 enum arq_state {
143         AS_RQ_NEW=0,            /* New - not referenced and not on any lists */
144         AS_RQ_QUEUED,           /* In the request queue. It belongs to the
145                                    scheduler */
146         AS_RQ_DISPATCHED,       /* On the dispatch list. It belongs to the
147                                    driver now */
148         AS_RQ_PRESCHED,         /* Debug poisoning for requests being used */
149         AS_RQ_REMOVED,
150         AS_RQ_MERGED,
151         AS_RQ_POSTSCHED,        /* when they shouldn't be */
152 };
153
154 struct as_rq {
155         /*
156          * rbtree index, key is the starting offset
157          */
158         struct rb_node rb_node;
159         sector_t rb_key;
160
161         struct request *request;
162
163         struct io_context *io_context;  /* The submitting task */
164
165         /*
166          * request hash, key is the ending offset (for back merge lookup)
167          */
168         struct list_head hash;
169         unsigned int on_hash;
170
171         /*
172          * expire fifo
173          */
174         struct list_head fifo;
175         unsigned long expires;
176
177         unsigned int is_sync;
178         enum arq_state state;
179 };
180
181 #define RQ_DATA(rq)     ((struct as_rq *) (rq)->elevator_private)
182
183 static kmem_cache_t *arq_pool;
184
185 static atomic_t ioc_count = ATOMIC_INIT(0);
186 static struct completion *ioc_gone;
187
188 static void as_move_to_dispatch(struct as_data *ad, struct as_rq *arq);
189 static void as_antic_stop(struct as_data *ad);
190
191 /*
192  * IO Context helper functions
193  */
194
195 /* Called to deallocate the as_io_context */
196 static void free_as_io_context(struct as_io_context *aic)
197 {
198         kfree(aic);
199         if (atomic_dec_and_test(&ioc_count) && ioc_gone)
200                 complete(ioc_gone);
201 }
202
203 static void as_trim(struct io_context *ioc)
204 {
205         if (ioc->aic)
206                 free_as_io_context(ioc->aic);
207         ioc->aic = NULL;
208 }
209
210 /* Called when the task exits */
211 static void exit_as_io_context(struct as_io_context *aic)
212 {
213         WARN_ON(!test_bit(AS_TASK_RUNNING, &aic->state));
214         clear_bit(AS_TASK_RUNNING, &aic->state);
215 }
216
217 static struct as_io_context *alloc_as_io_context(void)
218 {
219         struct as_io_context *ret;
220
221         ret = kmalloc(sizeof(*ret), GFP_ATOMIC);
222         if (ret) {
223                 ret->dtor = free_as_io_context;
224                 ret->exit = exit_as_io_context;
225                 ret->state = 1 << AS_TASK_RUNNING;
226                 atomic_set(&ret->nr_queued, 0);
227                 atomic_set(&ret->nr_dispatched, 0);
228                 spin_lock_init(&ret->lock);
229                 ret->ttime_total = 0;
230                 ret->ttime_samples = 0;
231                 ret->ttime_mean = 0;
232                 ret->seek_total = 0;
233                 ret->seek_samples = 0;
234                 ret->seek_mean = 0;
235                 atomic_inc(&ioc_count);
236         }
237
238         return ret;
239 }
240
241 /*
242  * If the current task has no AS IO context then create one and initialise it.
243  * Then take a ref on the task's io context and return it.
244  */
245 static struct io_context *as_get_io_context(void)
246 {
247         struct io_context *ioc = get_io_context(GFP_ATOMIC);
248         if (ioc && !ioc->aic) {
249                 ioc->aic = alloc_as_io_context();
250                 if (!ioc->aic) {
251                         put_io_context(ioc);
252                         ioc = NULL;
253                 }
254         }
255         return ioc;
256 }
257
258 static void as_put_io_context(struct as_rq *arq)
259 {
260         struct as_io_context *aic;
261
262         if (unlikely(!arq->io_context))
263                 return;
264
265         aic = arq->io_context->aic;
266
267         if (arq->is_sync == REQ_SYNC && aic) {
268                 spin_lock(&aic->lock);
269                 set_bit(AS_TASK_IORUNNING, &aic->state);
270                 aic->last_end_request = jiffies;
271                 spin_unlock(&aic->lock);
272         }
273
274         put_io_context(arq->io_context);
275 }
276
277 /*
278  * the back merge hash support functions
279  */
280 static const int as_hash_shift = 6;
281 #define AS_HASH_BLOCK(sec)      ((sec) >> 3)
282 #define AS_HASH_FN(sec)         (hash_long(AS_HASH_BLOCK((sec)), as_hash_shift))
283 #define AS_HASH_ENTRIES         (1 << as_hash_shift)
284 #define rq_hash_key(rq)         ((rq)->sector + (rq)->nr_sectors)
285 #define list_entry_hash(ptr)    list_entry((ptr), struct as_rq, hash)
286
287 static inline void __as_del_arq_hash(struct as_rq *arq)
288 {
289         arq->on_hash = 0;
290         list_del_init(&arq->hash);
291 }
292
293 static inline void as_del_arq_hash(struct as_rq *arq)
294 {
295         if (arq->on_hash)
296                 __as_del_arq_hash(arq);
297 }
298
299 static void as_add_arq_hash(struct as_data *ad, struct as_rq *arq)
300 {
301         struct request *rq = arq->request;
302
303         BUG_ON(arq->on_hash);
304
305         arq->on_hash = 1;
306         list_add(&arq->hash, &ad->hash[AS_HASH_FN(rq_hash_key(rq))]);
307 }
308
309 /*
310  * move hot entry to front of chain
311  */
312 static inline void as_hot_arq_hash(struct as_data *ad, struct as_rq *arq)
313 {
314         struct request *rq = arq->request;
315         struct list_head *head = &ad->hash[AS_HASH_FN(rq_hash_key(rq))];
316
317         if (!arq->on_hash) {
318                 WARN_ON(1);
319                 return;
320         }
321
322         if (arq->hash.prev != head) {
323                 list_del(&arq->hash);
324                 list_add(&arq->hash, head);
325         }
326 }
327
328 static struct request *as_find_arq_hash(struct as_data *ad, sector_t offset)
329 {
330         struct list_head *hash_list = &ad->hash[AS_HASH_FN(offset)];
331         struct list_head *entry, *next = hash_list->next;
332
333         while ((entry = next) != hash_list) {
334                 struct as_rq *arq = list_entry_hash(entry);
335                 struct request *__rq = arq->request;
336
337                 next = entry->next;
338
339                 BUG_ON(!arq->on_hash);
340
341                 if (!rq_mergeable(__rq)) {
342                         as_del_arq_hash(arq);
343                         continue;
344                 }
345
346                 if (rq_hash_key(__rq) == offset)
347                         return __rq;
348         }
349
350         return NULL;
351 }
352
353 /*
354  * rb tree support functions
355  */
356 #define RB_EMPTY(root)  ((root)->rb_node == NULL)
357 #define ON_RB(node)     (rb_parent(node) != node)
358 #define RB_CLEAR(node)  (rb_set_parent(node, node))
359 #define rb_entry_arq(node)      rb_entry((node), struct as_rq, rb_node)
360 #define ARQ_RB_ROOT(ad, arq)    (&(ad)->sort_list[(arq)->is_sync])
361 #define rq_rb_key(rq)           (rq)->sector
362
363 /*
364  * as_find_first_arq finds the first (lowest sector numbered) request
365  * for the specified data_dir. Used to sweep back to the start of the disk
366  * (1-way elevator) after we process the last (highest sector) request.
367  */
368 static struct as_rq *as_find_first_arq(struct as_data *ad, int data_dir)
369 {
370         struct rb_node *n = ad->sort_list[data_dir].rb_node;
371
372         if (n == NULL)
373                 return NULL;
374
375         for (;;) {
376                 if (n->rb_left == NULL)
377                         return rb_entry_arq(n);
378
379                 n = n->rb_left;
380         }
381 }
382
383 /*
384  * Add the request to the rb tree if it is unique.  If there is an alias (an
385  * existing request against the same sector), which can happen when using
386  * direct IO, then return the alias.
387  */
388 static struct as_rq *__as_add_arq_rb(struct as_data *ad, struct as_rq *arq)
389 {
390         struct rb_node **p = &ARQ_RB_ROOT(ad, arq)->rb_node;
391         struct rb_node *parent = NULL;
392         struct as_rq *__arq;
393         struct request *rq = arq->request;
394
395         arq->rb_key = rq_rb_key(rq);
396
397         while (*p) {
398                 parent = *p;
399                 __arq = rb_entry_arq(parent);
400
401                 if (arq->rb_key < __arq->rb_key)
402                         p = &(*p)->rb_left;
403                 else if (arq->rb_key > __arq->rb_key)
404                         p = &(*p)->rb_right;
405                 else
406                         return __arq;
407         }
408
409         rb_link_node(&arq->rb_node, parent, p);
410         rb_insert_color(&arq->rb_node, ARQ_RB_ROOT(ad, arq));
411
412         return NULL;
413 }
414
415 static void as_add_arq_rb(struct as_data *ad, struct as_rq *arq)
416 {
417         struct as_rq *alias;
418
419         while ((unlikely(alias = __as_add_arq_rb(ad, arq)))) {
420                 as_move_to_dispatch(ad, alias);
421                 as_antic_stop(ad);
422         }
423 }
424
425 static inline void as_del_arq_rb(struct as_data *ad, struct as_rq *arq)
426 {
427         if (!ON_RB(&arq->rb_node)) {
428                 WARN_ON(1);
429                 return;
430         }
431
432         rb_erase(&arq->rb_node, ARQ_RB_ROOT(ad, arq));
433         RB_CLEAR(&arq->rb_node);
434 }
435
436 static struct request *
437 as_find_arq_rb(struct as_data *ad, sector_t sector, int data_dir)
438 {
439         struct rb_node *n = ad->sort_list[data_dir].rb_node;
440         struct as_rq *arq;
441
442         while (n) {
443                 arq = rb_entry_arq(n);
444
445                 if (sector < arq->rb_key)
446                         n = n->rb_left;
447                 else if (sector > arq->rb_key)
448                         n = n->rb_right;
449                 else
450                         return arq->request;
451         }
452
453         return NULL;
454 }
455
456 /*
457  * IO Scheduler proper
458  */
459
460 #define MAXBACK (1024 * 1024)   /*
461                                  * Maximum distance the disk will go backward
462                                  * for a request.
463                                  */
464
465 #define BACK_PENALTY    2
466
467 /*
468  * as_choose_req selects the preferred one of two requests of the same data_dir
469  * ignoring time - eg. timeouts, which is the job of as_dispatch_request
470  */
471 static struct as_rq *
472 as_choose_req(struct as_data *ad, struct as_rq *arq1, struct as_rq *arq2)
473 {
474         int data_dir;
475         sector_t last, s1, s2, d1, d2;
476         int r1_wrap=0, r2_wrap=0;       /* requests are behind the disk head */
477         const sector_t maxback = MAXBACK;
478
479         if (arq1 == NULL || arq1 == arq2)
480                 return arq2;
481         if (arq2 == NULL)
482                 return arq1;
483
484         data_dir = arq1->is_sync;
485
486         last = ad->last_sector[data_dir];
487         s1 = arq1->request->sector;
488         s2 = arq2->request->sector;
489
490         BUG_ON(data_dir != arq2->is_sync);
491
492         /*
493          * Strict one way elevator _except_ in the case where we allow
494          * short backward seeks which are biased as twice the cost of a
495          * similar forward seek.
496          */
497         if (s1 >= last)
498                 d1 = s1 - last;
499         else if (s1+maxback >= last)
500                 d1 = (last - s1)*BACK_PENALTY;
501         else {
502                 r1_wrap = 1;
503                 d1 = 0; /* shut up, gcc */
504         }
505
506         if (s2 >= last)
507                 d2 = s2 - last;
508         else if (s2+maxback >= last)
509                 d2 = (last - s2)*BACK_PENALTY;
510         else {
511                 r2_wrap = 1;
512                 d2 = 0;
513         }
514
515         /* Found required data */
516         if (!r1_wrap && r2_wrap)
517                 return arq1;
518         else if (!r2_wrap && r1_wrap)
519                 return arq2;
520         else if (r1_wrap && r2_wrap) {
521                 /* both behind the head */
522                 if (s1 <= s2)
523                         return arq1;
524                 else
525                         return arq2;
526         }
527
528         /* Both requests in front of the head */
529         if (d1 < d2)
530                 return arq1;
531         else if (d2 < d1)
532                 return arq2;
533         else {
534                 if (s1 >= s2)
535                         return arq1;
536                 else
537                         return arq2;
538         }
539 }
540
541 /*
542  * as_find_next_arq finds the next request after @prev in elevator order.
543  * this with as_choose_req form the basis for how the scheduler chooses
544  * what request to process next. Anticipation works on top of this.
545  */
546 static struct as_rq *as_find_next_arq(struct as_data *ad, struct as_rq *last)
547 {
548         const int data_dir = last->is_sync;
549         struct as_rq *ret;
550         struct rb_node *rbnext = rb_next(&last->rb_node);
551         struct rb_node *rbprev = rb_prev(&last->rb_node);
552         struct as_rq *arq_next, *arq_prev;
553
554         BUG_ON(!ON_RB(&last->rb_node));
555
556         if (rbprev)
557                 arq_prev = rb_entry_arq(rbprev);
558         else
559                 arq_prev = NULL;
560
561         if (rbnext)
562                 arq_next = rb_entry_arq(rbnext);
563         else {
564                 arq_next = as_find_first_arq(ad, data_dir);
565                 if (arq_next == last)
566                         arq_next = NULL;
567         }
568
569         ret = as_choose_req(ad, arq_next, arq_prev);
570
571         return ret;
572 }
573
574 /*
575  * anticipatory scheduling functions follow
576  */
577
578 /*
579  * as_antic_expired tells us when we have anticipated too long.
580  * The funny "absolute difference" math on the elapsed time is to handle
581  * jiffy wraps, and disks which have been idle for 0x80000000 jiffies.
582  */
583 static int as_antic_expired(struct as_data *ad)
584 {
585         long delta_jif;
586
587         delta_jif = jiffies - ad->antic_start;
588         if (unlikely(delta_jif < 0))
589                 delta_jif = -delta_jif;
590         if (delta_jif < ad->antic_expire)
591                 return 0;
592
593         return 1;
594 }
595
596 /*
597  * as_antic_waitnext starts anticipating that a nice request will soon be
598  * submitted. See also as_antic_waitreq
599  */
600 static void as_antic_waitnext(struct as_data *ad)
601 {
602         unsigned long timeout;
603
604         BUG_ON(ad->antic_status != ANTIC_OFF
605                         && ad->antic_status != ANTIC_WAIT_REQ);
606
607         timeout = ad->antic_start + ad->antic_expire;
608
609         mod_timer(&ad->antic_timer, timeout);
610
611         ad->antic_status = ANTIC_WAIT_NEXT;
612 }
613
614 /*
615  * as_antic_waitreq starts anticipating. We don't start timing the anticipation
616  * until the request that we're anticipating on has finished. This means we
617  * are timing from when the candidate process wakes up hopefully.
618  */
619 static void as_antic_waitreq(struct as_data *ad)
620 {
621         BUG_ON(ad->antic_status == ANTIC_FINISHED);
622         if (ad->antic_status == ANTIC_OFF) {
623                 if (!ad->io_context || ad->ioc_finished)
624                         as_antic_waitnext(ad);
625                 else
626                         ad->antic_status = ANTIC_WAIT_REQ;
627         }
628 }
629
630 /*
631  * This is called directly by the functions in this file to stop anticipation.
632  * We kill the timer and schedule a call to the request_fn asap.
633  */
634 static void as_antic_stop(struct as_data *ad)
635 {
636         int status = ad->antic_status;
637
638         if (status == ANTIC_WAIT_REQ || status == ANTIC_WAIT_NEXT) {
639                 if (status == ANTIC_WAIT_NEXT)
640                         del_timer(&ad->antic_timer);
641                 ad->antic_status = ANTIC_FINISHED;
642                 /* see as_work_handler */
643                 kblockd_schedule_work(&ad->antic_work);
644         }
645 }
646
647 /*
648  * as_antic_timeout is the timer function set by as_antic_waitnext.
649  */
650 static void as_antic_timeout(unsigned long data)
651 {
652         struct request_queue *q = (struct request_queue *)data;
653         struct as_data *ad = q->elevator->elevator_data;
654         unsigned long flags;
655
656         spin_lock_irqsave(q->queue_lock, flags);
657         if (ad->antic_status == ANTIC_WAIT_REQ
658                         || ad->antic_status == ANTIC_WAIT_NEXT) {
659                 struct as_io_context *aic = ad->io_context->aic;
660
661                 ad->antic_status = ANTIC_FINISHED;
662                 kblockd_schedule_work(&ad->antic_work);
663
664                 if (aic->ttime_samples == 0) {
665                         /* process anticipated on has exited or timed out*/
666                         ad->exit_prob = (7*ad->exit_prob + 256)/8;
667                 }
668                 if (!test_bit(AS_TASK_RUNNING, &aic->state)) {
669                         /* process not "saved" by a cooperating request */
670                         ad->exit_no_coop = (7*ad->exit_no_coop + 256)/8;
671                 }
672         }
673         spin_unlock_irqrestore(q->queue_lock, flags);
674 }
675
676 static void as_update_thinktime(struct as_data *ad, struct as_io_context *aic,
677                                 unsigned long ttime)
678 {
679         /* fixed point: 1.0 == 1<<8 */
680         if (aic->ttime_samples == 0) {
681                 ad->new_ttime_total = (7*ad->new_ttime_total + 256*ttime) / 8;
682                 ad->new_ttime_mean = ad->new_ttime_total / 256;
683
684                 ad->exit_prob = (7*ad->exit_prob)/8;
685         }
686         aic->ttime_samples = (7*aic->ttime_samples + 256) / 8;
687         aic->ttime_total = (7*aic->ttime_total + 256*ttime) / 8;
688         aic->ttime_mean = (aic->ttime_total + 128) / aic->ttime_samples;
689 }
690
691 static void as_update_seekdist(struct as_data *ad, struct as_io_context *aic,
692                                 sector_t sdist)
693 {
694         u64 total;
695
696         if (aic->seek_samples == 0) {
697                 ad->new_seek_total = (7*ad->new_seek_total + 256*(u64)sdist)/8;
698                 ad->new_seek_mean = ad->new_seek_total / 256;
699         }
700
701         /*
702          * Don't allow the seek distance to get too large from the
703          * odd fragment, pagein, etc
704          */
705         if (aic->seek_samples <= 60) /* second&third seek */
706                 sdist = min(sdist, (aic->seek_mean * 4) + 2*1024*1024);
707         else
708                 sdist = min(sdist, (aic->seek_mean * 4) + 2*1024*64);
709
710         aic->seek_samples = (7*aic->seek_samples + 256) / 8;
711         aic->seek_total = (7*aic->seek_total + (u64)256*sdist) / 8;
712         total = aic->seek_total + (aic->seek_samples/2);
713         do_div(total, aic->seek_samples);
714         aic->seek_mean = (sector_t)total;
715 }
716
717 /*
718  * as_update_iohist keeps a decaying histogram of IO thinktimes, and
719  * updates @aic->ttime_mean based on that. It is called when a new
720  * request is queued.
721  */
722 static void as_update_iohist(struct as_data *ad, struct as_io_context *aic,
723                                 struct request *rq)
724 {
725         struct as_rq *arq = RQ_DATA(rq);
726         int data_dir = arq->is_sync;
727         unsigned long thinktime = 0;
728         sector_t seek_dist;
729
730         if (aic == NULL)
731                 return;
732
733         if (data_dir == REQ_SYNC) {
734                 unsigned long in_flight = atomic_read(&aic->nr_queued)
735                                         + atomic_read(&aic->nr_dispatched);
736                 spin_lock(&aic->lock);
737                 if (test_bit(AS_TASK_IORUNNING, &aic->state) ||
738                         test_bit(AS_TASK_IOSTARTED, &aic->state)) {
739                         /* Calculate read -> read thinktime */
740                         if (test_bit(AS_TASK_IORUNNING, &aic->state)
741                                                         && in_flight == 0) {
742                                 thinktime = jiffies - aic->last_end_request;
743                                 thinktime = min(thinktime, MAX_THINKTIME-1);
744                         }
745                         as_update_thinktime(ad, aic, thinktime);
746
747                         /* Calculate read -> read seek distance */
748                         if (aic->last_request_pos < rq->sector)
749                                 seek_dist = rq->sector - aic->last_request_pos;
750                         else
751                                 seek_dist = aic->last_request_pos - rq->sector;
752                         as_update_seekdist(ad, aic, seek_dist);
753                 }
754                 aic->last_request_pos = rq->sector + rq->nr_sectors;
755                 set_bit(AS_TASK_IOSTARTED, &aic->state);
756                 spin_unlock(&aic->lock);
757         }
758 }
759
760 /*
761  * as_close_req decides if one request is considered "close" to the
762  * previous one issued.
763  */
764 static int as_close_req(struct as_data *ad, struct as_io_context *aic,
765                                 struct as_rq *arq)
766 {
767         unsigned long delay;    /* milliseconds */
768         sector_t last = ad->last_sector[ad->batch_data_dir];
769         sector_t next = arq->request->sector;
770         sector_t delta; /* acceptable close offset (in sectors) */
771         sector_t s;
772
773         if (ad->antic_status == ANTIC_OFF || !ad->ioc_finished)
774                 delay = 0;
775         else
776                 delay = ((jiffies - ad->antic_start) * 1000) / HZ;
777
778         if (delay == 0)
779                 delta = 8192;
780         else if (delay <= 20 && delay <= ad->antic_expire)
781                 delta = 8192 << delay;
782         else
783                 return 1;
784
785         if ((last <= next + (delta>>1)) && (next <= last + delta))
786                 return 1;
787
788         if (last < next)
789                 s = next - last;
790         else
791                 s = last - next;
792
793         if (aic->seek_samples == 0) {
794                 /*
795                  * Process has just started IO. Use past statistics to
796                  * gauge success possibility
797                  */
798                 if (ad->new_seek_mean > s) {
799                         /* this request is better than what we're expecting */
800                         return 1;
801                 }
802
803         } else {
804                 if (aic->seek_mean > s) {
805                         /* this request is better than what we're expecting */
806                         return 1;
807                 }
808         }
809
810         return 0;
811 }
812
813 /*
814  * as_can_break_anticipation returns true if we have been anticipating this
815  * request.
816  *
817  * It also returns true if the process against which we are anticipating
818  * submits a write - that's presumably an fsync, O_SYNC write, etc. We want to
819  * dispatch it ASAP, because we know that application will not be submitting
820  * any new reads.
821  *
822  * If the task which has submitted the request has exited, break anticipation.
823  *
824  * If this task has queued some other IO, do not enter enticipation.
825  */
826 static int as_can_break_anticipation(struct as_data *ad, struct as_rq *arq)
827 {
828         struct io_context *ioc;
829         struct as_io_context *aic;
830
831         ioc = ad->io_context;
832         BUG_ON(!ioc);
833
834         if (arq && ioc == arq->io_context) {
835                 /* request from same process */
836                 return 1;
837         }
838
839         if (ad->ioc_finished && as_antic_expired(ad)) {
840                 /*
841                  * In this situation status should really be FINISHED,
842                  * however the timer hasn't had the chance to run yet.
843                  */
844                 return 1;
845         }
846
847         aic = ioc->aic;
848         if (!aic)
849                 return 0;
850
851         if (atomic_read(&aic->nr_queued) > 0) {
852                 /* process has more requests queued */
853                 return 1;
854         }
855
856         if (atomic_read(&aic->nr_dispatched) > 0) {
857                 /* process has more requests dispatched */
858                 return 1;
859         }
860
861         if (arq && arq->is_sync == REQ_SYNC && as_close_req(ad, aic, arq)) {
862                 /*
863                  * Found a close request that is not one of ours.
864                  *
865                  * This makes close requests from another process update
866                  * our IO history. Is generally useful when there are
867                  * two or more cooperating processes working in the same
868                  * area.
869                  */
870                 if (!test_bit(AS_TASK_RUNNING, &aic->state)) {
871                         if (aic->ttime_samples == 0)
872                                 ad->exit_prob = (7*ad->exit_prob + 256)/8;
873
874                         ad->exit_no_coop = (7*ad->exit_no_coop)/8;
875                 }
876
877                 as_update_iohist(ad, aic, arq->request);
878                 return 1;
879         }
880
881         if (!test_bit(AS_TASK_RUNNING, &aic->state)) {
882                 /* process anticipated on has exited */
883                 if (aic->ttime_samples == 0)
884                         ad->exit_prob = (7*ad->exit_prob + 256)/8;
885
886                 if (ad->exit_no_coop > 128)
887                         return 1;
888         }
889
890         if (aic->ttime_samples == 0) {
891                 if (ad->new_ttime_mean > ad->antic_expire)
892                         return 1;
893                 if (ad->exit_prob * ad->exit_no_coop > 128*256)
894                         return 1;
895         } else if (aic->ttime_mean > ad->antic_expire) {
896                 /* the process thinks too much between requests */
897                 return 1;
898         }
899
900         return 0;
901 }
902
903 /*
904  * as_can_anticipate indicates weather we should either run arq
905  * or keep anticipating a better request.
906  */
907 static int as_can_anticipate(struct as_data *ad, struct as_rq *arq)
908 {
909         if (!ad->io_context)
910                 /*
911                  * Last request submitted was a write
912                  */
913                 return 0;
914
915         if (ad->antic_status == ANTIC_FINISHED)
916                 /*
917                  * Don't restart if we have just finished. Run the next request
918                  */
919                 return 0;
920
921         if (as_can_break_anticipation(ad, arq))
922                 /*
923                  * This request is a good candidate. Don't keep anticipating,
924                  * run it.
925                  */
926                 return 0;
927
928         /*
929          * OK from here, we haven't finished, and don't have a decent request!
930          * Status is either ANTIC_OFF so start waiting,
931          * ANTIC_WAIT_REQ so continue waiting for request to finish
932          * or ANTIC_WAIT_NEXT so continue waiting for an acceptable request.
933          */
934
935         return 1;
936 }
937
938 /*
939  * as_update_arq must be called whenever a request (arq) is added to
940  * the sort_list. This function keeps caches up to date, and checks if the
941  * request might be one we are "anticipating"
942  */
943 static void as_update_arq(struct as_data *ad, struct as_rq *arq)
944 {
945         const int data_dir = arq->is_sync;
946
947         /* keep the next_arq cache up to date */
948         ad->next_arq[data_dir] = as_choose_req(ad, arq, ad->next_arq[data_dir]);
949
950         /*
951          * have we been anticipating this request?
952          * or does it come from the same process as the one we are anticipating
953          * for?
954          */
955         if (ad->antic_status == ANTIC_WAIT_REQ
956                         || ad->antic_status == ANTIC_WAIT_NEXT) {
957                 if (as_can_break_anticipation(ad, arq))
958                         as_antic_stop(ad);
959         }
960 }
961
962 /*
963  * Gathers timings and resizes the write batch automatically
964  */
965 static void update_write_batch(struct as_data *ad)
966 {
967         unsigned long batch = ad->batch_expire[REQ_ASYNC];
968         long write_time;
969
970         write_time = (jiffies - ad->current_batch_expires) + batch;
971         if (write_time < 0)
972                 write_time = 0;
973
974         if (write_time > batch && !ad->write_batch_idled) {
975                 if (write_time > batch * 3)
976                         ad->write_batch_count /= 2;
977                 else
978                         ad->write_batch_count--;
979         } else if (write_time < batch && ad->current_write_count == 0) {
980                 if (batch > write_time * 3)
981                         ad->write_batch_count *= 2;
982                 else
983                         ad->write_batch_count++;
984         }
985
986         if (ad->write_batch_count < 1)
987                 ad->write_batch_count = 1;
988 }
989
990 /*
991  * as_completed_request is to be called when a request has completed and
992  * returned something to the requesting process, be it an error or data.
993  */
994 static void as_completed_request(request_queue_t *q, struct request *rq)
995 {
996         struct as_data *ad = q->elevator->elevator_data;
997         struct as_rq *arq = RQ_DATA(rq);
998
999         WARN_ON(!list_empty(&rq->queuelist));
1000
1001         if (arq->state != AS_RQ_REMOVED) {
1002                 printk("arq->state %d\n", arq->state);
1003                 WARN_ON(1);
1004                 goto out;
1005         }
1006
1007         if (ad->changed_batch && ad->nr_dispatched == 1) {
1008                 kblockd_schedule_work(&ad->antic_work);
1009                 ad->changed_batch = 0;
1010
1011                 if (ad->batch_data_dir == REQ_SYNC)
1012                         ad->new_batch = 1;
1013         }
1014         WARN_ON(ad->nr_dispatched == 0);
1015         ad->nr_dispatched--;
1016
1017         /*
1018          * Start counting the batch from when a request of that direction is
1019          * actually serviced. This should help devices with big TCQ windows
1020          * and writeback caches
1021          */
1022         if (ad->new_batch && ad->batch_data_dir == arq->is_sync) {
1023                 update_write_batch(ad);
1024                 ad->current_batch_expires = jiffies +
1025                                 ad->batch_expire[REQ_SYNC];
1026                 ad->new_batch = 0;
1027         }
1028
1029         if (ad->io_context == arq->io_context && ad->io_context) {
1030                 ad->antic_start = jiffies;
1031                 ad->ioc_finished = 1;
1032                 if (ad->antic_status == ANTIC_WAIT_REQ) {
1033                         /*
1034                          * We were waiting on this request, now anticipate
1035                          * the next one
1036                          */
1037                         as_antic_waitnext(ad);
1038                 }
1039         }
1040
1041         as_put_io_context(arq);
1042 out:
1043         arq->state = AS_RQ_POSTSCHED;
1044 }
1045
1046 /*
1047  * as_remove_queued_request removes a request from the pre dispatch queue
1048  * without updating refcounts. It is expected the caller will drop the
1049  * reference unless it replaces the request at somepart of the elevator
1050  * (ie. the dispatch queue)
1051  */
1052 static void as_remove_queued_request(request_queue_t *q, struct request *rq)
1053 {
1054         struct as_rq *arq = RQ_DATA(rq);
1055         const int data_dir = arq->is_sync;
1056         struct as_data *ad = q->elevator->elevator_data;
1057
1058         WARN_ON(arq->state != AS_RQ_QUEUED);
1059
1060         if (arq->io_context && arq->io_context->aic) {
1061                 BUG_ON(!atomic_read(&arq->io_context->aic->nr_queued));
1062                 atomic_dec(&arq->io_context->aic->nr_queued);
1063         }
1064
1065         /*
1066          * Update the "next_arq" cache if we are about to remove its
1067          * entry
1068          */
1069         if (ad->next_arq[data_dir] == arq)
1070                 ad->next_arq[data_dir] = as_find_next_arq(ad, arq);
1071
1072         list_del_init(&arq->fifo);
1073         as_del_arq_hash(arq);
1074         as_del_arq_rb(ad, arq);
1075 }
1076
1077 /*
1078  * as_fifo_expired returns 0 if there are no expired reads on the fifo,
1079  * 1 otherwise.  It is ratelimited so that we only perform the check once per
1080  * `fifo_expire' interval.  Otherwise a large number of expired requests
1081  * would create a hopeless seekstorm.
1082  *
1083  * See as_antic_expired comment.
1084  */
1085 static int as_fifo_expired(struct as_data *ad, int adir)
1086 {
1087         struct as_rq *arq;
1088         long delta_jif;
1089
1090         delta_jif = jiffies - ad->last_check_fifo[adir];
1091         if (unlikely(delta_jif < 0))
1092                 delta_jif = -delta_jif;
1093         if (delta_jif < ad->fifo_expire[adir])
1094                 return 0;
1095
1096         ad->last_check_fifo[adir] = jiffies;
1097
1098         if (list_empty(&ad->fifo_list[adir]))
1099                 return 0;
1100
1101         arq = list_entry_fifo(ad->fifo_list[adir].next);
1102
1103         return time_after(jiffies, arq->expires);
1104 }
1105
1106 /*
1107  * as_batch_expired returns true if the current batch has expired. A batch
1108  * is a set of reads or a set of writes.
1109  */
1110 static inline int as_batch_expired(struct as_data *ad)
1111 {
1112         if (ad->changed_batch || ad->new_batch)
1113                 return 0;
1114
1115         if (ad->batch_data_dir == REQ_SYNC)
1116                 /* TODO! add a check so a complete fifo gets written? */
1117                 return time_after(jiffies, ad->current_batch_expires);
1118
1119         return time_after(jiffies, ad->current_batch_expires)
1120                 || ad->current_write_count == 0;
1121 }
1122
1123 /*
1124  * move an entry to dispatch queue
1125  */
1126 static void as_move_to_dispatch(struct as_data *ad, struct as_rq *arq)
1127 {
1128         struct request *rq = arq->request;
1129         const int data_dir = arq->is_sync;
1130
1131         BUG_ON(!ON_RB(&arq->rb_node));
1132
1133         as_antic_stop(ad);
1134         ad->antic_status = ANTIC_OFF;
1135
1136         /*
1137          * This has to be set in order to be correctly updated by
1138          * as_find_next_arq
1139          */
1140         ad->last_sector[data_dir] = rq->sector + rq->nr_sectors;
1141
1142         if (data_dir == REQ_SYNC) {
1143                 /* In case we have to anticipate after this */
1144                 copy_io_context(&ad->io_context, &arq->io_context);
1145         } else {
1146                 if (ad->io_context) {
1147                         put_io_context(ad->io_context);
1148                         ad->io_context = NULL;
1149                 }
1150
1151                 if (ad->current_write_count != 0)
1152                         ad->current_write_count--;
1153         }
1154         ad->ioc_finished = 0;
1155
1156         ad->next_arq[data_dir] = as_find_next_arq(ad, arq);
1157
1158         /*
1159          * take it off the sort and fifo list, add to dispatch queue
1160          */
1161         as_remove_queued_request(ad->q, rq);
1162         WARN_ON(arq->state != AS_RQ_QUEUED);
1163
1164         elv_dispatch_sort(ad->q, rq);
1165
1166         arq->state = AS_RQ_DISPATCHED;
1167         if (arq->io_context && arq->io_context->aic)
1168                 atomic_inc(&arq->io_context->aic->nr_dispatched);
1169         ad->nr_dispatched++;
1170 }
1171
1172 /*
1173  * as_dispatch_request selects the best request according to
1174  * read/write expire, batch expire, etc, and moves it to the dispatch
1175  * queue. Returns 1 if a request was found, 0 otherwise.
1176  */
1177 static int as_dispatch_request(request_queue_t *q, int force)
1178 {
1179         struct as_data *ad = q->elevator->elevator_data;
1180         struct as_rq *arq;
1181         const int reads = !list_empty(&ad->fifo_list[REQ_SYNC]);
1182         const int writes = !list_empty(&ad->fifo_list[REQ_ASYNC]);
1183
1184         if (unlikely(force)) {
1185                 /*
1186                  * Forced dispatch, accounting is useless.  Reset
1187                  * accounting states and dump fifo_lists.  Note that
1188                  * batch_data_dir is reset to REQ_SYNC to avoid
1189                  * screwing write batch accounting as write batch
1190                  * accounting occurs on W->R transition.
1191                  */
1192                 int dispatched = 0;
1193
1194                 ad->batch_data_dir = REQ_SYNC;
1195                 ad->changed_batch = 0;
1196                 ad->new_batch = 0;
1197
1198                 while (ad->next_arq[REQ_SYNC]) {
1199                         as_move_to_dispatch(ad, ad->next_arq[REQ_SYNC]);
1200                         dispatched++;
1201                 }
1202                 ad->last_check_fifo[REQ_SYNC] = jiffies;
1203
1204                 while (ad->next_arq[REQ_ASYNC]) {
1205                         as_move_to_dispatch(ad, ad->next_arq[REQ_ASYNC]);
1206                         dispatched++;
1207                 }
1208                 ad->last_check_fifo[REQ_ASYNC] = jiffies;
1209
1210                 return dispatched;
1211         }
1212
1213         /* Signal that the write batch was uncontended, so we can't time it */
1214         if (ad->batch_data_dir == REQ_ASYNC && !reads) {
1215                 if (ad->current_write_count == 0 || !writes)
1216                         ad->write_batch_idled = 1;
1217         }
1218
1219         if (!(reads || writes)
1220                 || ad->antic_status == ANTIC_WAIT_REQ
1221                 || ad->antic_status == ANTIC_WAIT_NEXT
1222                 || ad->changed_batch)
1223                 return 0;
1224
1225         if (!(reads && writes && as_batch_expired(ad))) {
1226                 /*
1227                  * batch is still running or no reads or no writes
1228                  */
1229                 arq = ad->next_arq[ad->batch_data_dir];
1230
1231                 if (ad->batch_data_dir == REQ_SYNC && ad->antic_expire) {
1232                         if (as_fifo_expired(ad, REQ_SYNC))
1233                                 goto fifo_expired;
1234
1235                         if (as_can_anticipate(ad, arq)) {
1236                                 as_antic_waitreq(ad);
1237                                 return 0;
1238                         }
1239                 }
1240
1241                 if (arq) {
1242                         /* we have a "next request" */
1243                         if (reads && !writes)
1244                                 ad->current_batch_expires =
1245                                         jiffies + ad->batch_expire[REQ_SYNC];
1246                         goto dispatch_request;
1247                 }
1248         }
1249
1250         /*
1251          * at this point we are not running a batch. select the appropriate
1252          * data direction (read / write)
1253          */
1254
1255         if (reads) {
1256                 BUG_ON(RB_EMPTY(&ad->sort_list[REQ_SYNC]));
1257
1258                 if (writes && ad->batch_data_dir == REQ_SYNC)
1259                         /*
1260                          * Last batch was a read, switch to writes
1261                          */
1262                         goto dispatch_writes;
1263
1264                 if (ad->batch_data_dir == REQ_ASYNC) {
1265                         WARN_ON(ad->new_batch);
1266                         ad->changed_batch = 1;
1267                 }
1268                 ad->batch_data_dir = REQ_SYNC;
1269                 arq = list_entry_fifo(ad->fifo_list[ad->batch_data_dir].next);
1270                 ad->last_check_fifo[ad->batch_data_dir] = jiffies;
1271                 goto dispatch_request;
1272         }
1273
1274         /*
1275          * the last batch was a read
1276          */
1277
1278         if (writes) {
1279 dispatch_writes:
1280                 BUG_ON(RB_EMPTY(&ad->sort_list[REQ_ASYNC]));
1281
1282                 if (ad->batch_data_dir == REQ_SYNC) {
1283                         ad->changed_batch = 1;
1284
1285                         /*
1286                          * new_batch might be 1 when the queue runs out of
1287                          * reads. A subsequent submission of a write might
1288                          * cause a change of batch before the read is finished.
1289                          */
1290                         ad->new_batch = 0;
1291                 }
1292                 ad->batch_data_dir = REQ_ASYNC;
1293                 ad->current_write_count = ad->write_batch_count;
1294                 ad->write_batch_idled = 0;
1295                 arq = ad->next_arq[ad->batch_data_dir];
1296                 goto dispatch_request;
1297         }
1298
1299         BUG();
1300         return 0;
1301
1302 dispatch_request:
1303         /*
1304          * If a request has expired, service it.
1305          */
1306
1307         if (as_fifo_expired(ad, ad->batch_data_dir)) {
1308 fifo_expired:
1309                 arq = list_entry_fifo(ad->fifo_list[ad->batch_data_dir].next);
1310                 BUG_ON(arq == NULL);
1311         }
1312
1313         if (ad->changed_batch) {
1314                 WARN_ON(ad->new_batch);
1315
1316                 if (ad->nr_dispatched)
1317                         return 0;
1318
1319                 if (ad->batch_data_dir == REQ_ASYNC)
1320                         ad->current_batch_expires = jiffies +
1321                                         ad->batch_expire[REQ_ASYNC];
1322                 else
1323                         ad->new_batch = 1;
1324
1325                 ad->changed_batch = 0;
1326         }
1327
1328         /*
1329          * arq is the selected appropriate request.
1330          */
1331         as_move_to_dispatch(ad, arq);
1332
1333         return 1;
1334 }
1335
1336 /*
1337  * add arq to rbtree and fifo
1338  */
1339 static void as_add_request(request_queue_t *q, struct request *rq)
1340 {
1341         struct as_data *ad = q->elevator->elevator_data;
1342         struct as_rq *arq = RQ_DATA(rq);
1343         int data_dir;
1344
1345         arq->state = AS_RQ_NEW;
1346
1347         if (rq_data_dir(arq->request) == READ
1348                         || current->flags&PF_SYNCWRITE)
1349                 arq->is_sync = 1;
1350         else
1351                 arq->is_sync = 0;
1352         data_dir = arq->is_sync;
1353
1354         arq->io_context = as_get_io_context();
1355
1356         if (arq->io_context) {
1357                 as_update_iohist(ad, arq->io_context->aic, arq->request);
1358                 atomic_inc(&arq->io_context->aic->nr_queued);
1359         }
1360
1361         as_add_arq_rb(ad, arq);
1362         if (rq_mergeable(arq->request))
1363                 as_add_arq_hash(ad, arq);
1364
1365         /*
1366          * set expire time (only used for reads) and add to fifo list
1367          */
1368         arq->expires = jiffies + ad->fifo_expire[data_dir];
1369         list_add_tail(&arq->fifo, &ad->fifo_list[data_dir]);
1370
1371         as_update_arq(ad, arq); /* keep state machine up to date */
1372         arq->state = AS_RQ_QUEUED;
1373 }
1374
1375 static void as_activate_request(request_queue_t *q, struct request *rq)
1376 {
1377         struct as_rq *arq = RQ_DATA(rq);
1378
1379         WARN_ON(arq->state != AS_RQ_DISPATCHED);
1380         arq->state = AS_RQ_REMOVED;
1381         if (arq->io_context && arq->io_context->aic)
1382                 atomic_dec(&arq->io_context->aic->nr_dispatched);
1383 }
1384
1385 static void as_deactivate_request(request_queue_t *q, struct request *rq)
1386 {
1387         struct as_rq *arq = RQ_DATA(rq);
1388
1389         WARN_ON(arq->state != AS_RQ_REMOVED);
1390         arq->state = AS_RQ_DISPATCHED;
1391         if (arq->io_context && arq->io_context->aic)
1392                 atomic_inc(&arq->io_context->aic->nr_dispatched);
1393 }
1394
1395 /*
1396  * as_queue_empty tells us if there are requests left in the device. It may
1397  * not be the case that a driver can get the next request even if the queue
1398  * is not empty - it is used in the block layer to check for plugging and
1399  * merging opportunities
1400  */
1401 static int as_queue_empty(request_queue_t *q)
1402 {
1403         struct as_data *ad = q->elevator->elevator_data;
1404
1405         return list_empty(&ad->fifo_list[REQ_ASYNC])
1406                 && list_empty(&ad->fifo_list[REQ_SYNC]);
1407 }
1408
1409 static struct request *as_former_request(request_queue_t *q,
1410                                         struct request *rq)
1411 {
1412         struct as_rq *arq = RQ_DATA(rq);
1413         struct rb_node *rbprev = rb_prev(&arq->rb_node);
1414         struct request *ret = NULL;
1415
1416         if (rbprev)
1417                 ret = rb_entry_arq(rbprev)->request;
1418
1419         return ret;
1420 }
1421
1422 static struct request *as_latter_request(request_queue_t *q,
1423                                         struct request *rq)
1424 {
1425         struct as_rq *arq = RQ_DATA(rq);
1426         struct rb_node *rbnext = rb_next(&arq->rb_node);
1427         struct request *ret = NULL;
1428
1429         if (rbnext)
1430                 ret = rb_entry_arq(rbnext)->request;
1431
1432         return ret;
1433 }
1434
1435 static int
1436 as_merge(request_queue_t *q, struct request **req, struct bio *bio)
1437 {
1438         struct as_data *ad = q->elevator->elevator_data;
1439         sector_t rb_key = bio->bi_sector + bio_sectors(bio);
1440         struct request *__rq;
1441         int ret;
1442
1443         /*
1444          * see if the merge hash can satisfy a back merge
1445          */
1446         __rq = as_find_arq_hash(ad, bio->bi_sector);
1447         if (__rq) {
1448                 BUG_ON(__rq->sector + __rq->nr_sectors != bio->bi_sector);
1449
1450                 if (elv_rq_merge_ok(__rq, bio)) {
1451                         ret = ELEVATOR_BACK_MERGE;
1452                         goto out;
1453                 }
1454         }
1455
1456         /*
1457          * check for front merge
1458          */
1459         __rq = as_find_arq_rb(ad, rb_key, bio_data_dir(bio));
1460         if (__rq) {
1461                 BUG_ON(rb_key != rq_rb_key(__rq));
1462
1463                 if (elv_rq_merge_ok(__rq, bio)) {
1464                         ret = ELEVATOR_FRONT_MERGE;
1465                         goto out;
1466                 }
1467         }
1468
1469         return ELEVATOR_NO_MERGE;
1470 out:
1471         if (ret) {
1472                 if (rq_mergeable(__rq))
1473                         as_hot_arq_hash(ad, RQ_DATA(__rq));
1474         }
1475         *req = __rq;
1476         return ret;
1477 }
1478
1479 static void as_merged_request(request_queue_t *q, struct request *req)
1480 {
1481         struct as_data *ad = q->elevator->elevator_data;
1482         struct as_rq *arq = RQ_DATA(req);
1483
1484         /*
1485          * hash always needs to be repositioned, key is end sector
1486          */
1487         as_del_arq_hash(arq);
1488         as_add_arq_hash(ad, arq);
1489
1490         /*
1491          * if the merge was a front merge, we need to reposition request
1492          */
1493         if (rq_rb_key(req) != arq->rb_key) {
1494                 as_del_arq_rb(ad, arq);
1495                 as_add_arq_rb(ad, arq);
1496                 /*
1497                  * Note! At this stage of this and the next function, our next
1498                  * request may not be optimal - eg the request may have "grown"
1499                  * behind the disk head. We currently don't bother adjusting.
1500                  */
1501         }
1502 }
1503
1504 static void as_merged_requests(request_queue_t *q, struct request *req,
1505                                 struct request *next)
1506 {
1507         struct as_data *ad = q->elevator->elevator_data;
1508         struct as_rq *arq = RQ_DATA(req);
1509         struct as_rq *anext = RQ_DATA(next);
1510
1511         BUG_ON(!arq);
1512         BUG_ON(!anext);
1513
1514         /*
1515          * reposition arq (this is the merged request) in hash, and in rbtree
1516          * in case of a front merge
1517          */
1518         as_del_arq_hash(arq);
1519         as_add_arq_hash(ad, arq);
1520
1521         if (rq_rb_key(req) != arq->rb_key) {
1522                 as_del_arq_rb(ad, arq);
1523                 as_add_arq_rb(ad, arq);
1524         }
1525
1526         /*
1527          * if anext expires before arq, assign its expire time to arq
1528          * and move into anext position (anext will be deleted) in fifo
1529          */
1530         if (!list_empty(&arq->fifo) && !list_empty(&anext->fifo)) {
1531                 if (time_before(anext->expires, arq->expires)) {
1532                         list_move(&arq->fifo, &anext->fifo);
1533                         arq->expires = anext->expires;
1534                         /*
1535                          * Don't copy here but swap, because when anext is
1536                          * removed below, it must contain the unused context
1537                          */
1538                         swap_io_context(&arq->io_context, &anext->io_context);
1539                 }
1540         }
1541
1542         /*
1543          * kill knowledge of next, this one is a goner
1544          */
1545         as_remove_queued_request(q, next);
1546         as_put_io_context(anext);
1547
1548         anext->state = AS_RQ_MERGED;
1549 }
1550
1551 /*
1552  * This is executed in a "deferred" process context, by kblockd. It calls the
1553  * driver's request_fn so the driver can submit that request.
1554  *
1555  * IMPORTANT! This guy will reenter the elevator, so set up all queue global
1556  * state before calling, and don't rely on any state over calls.
1557  *
1558  * FIXME! dispatch queue is not a queue at all!
1559  */
1560 static void as_work_handler(void *data)
1561 {
1562         struct request_queue *q = data;
1563         unsigned long flags;
1564
1565         spin_lock_irqsave(q->queue_lock, flags);
1566         if (!as_queue_empty(q))
1567                 q->request_fn(q);
1568         spin_unlock_irqrestore(q->queue_lock, flags);
1569 }
1570
1571 static void as_put_request(request_queue_t *q, struct request *rq)
1572 {
1573         struct as_data *ad = q->elevator->elevator_data;
1574         struct as_rq *arq = RQ_DATA(rq);
1575
1576         if (!arq) {
1577                 WARN_ON(1);
1578                 return;
1579         }
1580
1581         if (unlikely(arq->state != AS_RQ_POSTSCHED &&
1582                      arq->state != AS_RQ_PRESCHED &&
1583                      arq->state != AS_RQ_MERGED)) {
1584                 printk("arq->state %d\n", arq->state);
1585                 WARN_ON(1);
1586         }
1587
1588         mempool_free(arq, ad->arq_pool);
1589         rq->elevator_private = NULL;
1590 }
1591
1592 static int as_set_request(request_queue_t *q, struct request *rq,
1593                           struct bio *bio, gfp_t gfp_mask)
1594 {
1595         struct as_data *ad = q->elevator->elevator_data;
1596         struct as_rq *arq = mempool_alloc(ad->arq_pool, gfp_mask);
1597
1598         if (arq) {
1599                 memset(arq, 0, sizeof(*arq));
1600                 RB_CLEAR(&arq->rb_node);
1601                 arq->request = rq;
1602                 arq->state = AS_RQ_PRESCHED;
1603                 arq->io_context = NULL;
1604                 INIT_LIST_HEAD(&arq->hash);
1605                 arq->on_hash = 0;
1606                 INIT_LIST_HEAD(&arq->fifo);
1607                 rq->elevator_private = arq;
1608                 return 0;
1609         }
1610
1611         return 1;
1612 }
1613
1614 static int as_may_queue(request_queue_t *q, int rw, struct bio *bio)
1615 {
1616         int ret = ELV_MQUEUE_MAY;
1617         struct as_data *ad = q->elevator->elevator_data;
1618         struct io_context *ioc;
1619         if (ad->antic_status == ANTIC_WAIT_REQ ||
1620                         ad->antic_status == ANTIC_WAIT_NEXT) {
1621                 ioc = as_get_io_context();
1622                 if (ad->io_context == ioc)
1623                         ret = ELV_MQUEUE_MUST;
1624                 put_io_context(ioc);
1625         }
1626
1627         return ret;
1628 }
1629
1630 static void as_exit_queue(elevator_t *e)
1631 {
1632         struct as_data *ad = e->elevator_data;
1633
1634         del_timer_sync(&ad->antic_timer);
1635         kblockd_flush();
1636
1637         BUG_ON(!list_empty(&ad->fifo_list[REQ_SYNC]));
1638         BUG_ON(!list_empty(&ad->fifo_list[REQ_ASYNC]));
1639
1640         mempool_destroy(ad->arq_pool);
1641         put_io_context(ad->io_context);
1642         kfree(ad->hash);
1643         kfree(ad);
1644 }
1645
1646 /*
1647  * initialize elevator private data (as_data), and alloc a arq for
1648  * each request on the free lists
1649  */
1650 static void *as_init_queue(request_queue_t *q, elevator_t *e)
1651 {
1652         struct as_data *ad;
1653         int i;
1654
1655         if (!arq_pool)
1656                 return NULL;
1657
1658         ad = kmalloc_node(sizeof(*ad), GFP_KERNEL, q->node);
1659         if (!ad)
1660                 return NULL;
1661         memset(ad, 0, sizeof(*ad));
1662
1663         ad->q = q; /* Identify what queue the data belongs to */
1664
1665         ad->hash = kmalloc_node(sizeof(struct list_head)*AS_HASH_ENTRIES,
1666                                 GFP_KERNEL, q->node);
1667         if (!ad->hash) {
1668                 kfree(ad);
1669                 return NULL;
1670         }
1671
1672         ad->arq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
1673                                 mempool_free_slab, arq_pool, q->node);
1674         if (!ad->arq_pool) {
1675                 kfree(ad->hash);
1676                 kfree(ad);
1677                 return NULL;
1678         }
1679
1680         /* anticipatory scheduling helpers */
1681         ad->antic_timer.function = as_antic_timeout;
1682         ad->antic_timer.data = (unsigned long)q;
1683         init_timer(&ad->antic_timer);
1684         INIT_WORK(&ad->antic_work, as_work_handler, q);
1685
1686         for (i = 0; i < AS_HASH_ENTRIES; i++)
1687                 INIT_LIST_HEAD(&ad->hash[i]);
1688
1689         INIT_LIST_HEAD(&ad->fifo_list[REQ_SYNC]);
1690         INIT_LIST_HEAD(&ad->fifo_list[REQ_ASYNC]);
1691         ad->sort_list[REQ_SYNC] = RB_ROOT;
1692         ad->sort_list[REQ_ASYNC] = RB_ROOT;
1693         ad->fifo_expire[REQ_SYNC] = default_read_expire;
1694         ad->fifo_expire[REQ_ASYNC] = default_write_expire;
1695         ad->antic_expire = default_antic_expire;
1696         ad->batch_expire[REQ_SYNC] = default_read_batch_expire;
1697         ad->batch_expire[REQ_ASYNC] = default_write_batch_expire;
1698
1699         ad->current_batch_expires = jiffies + ad->batch_expire[REQ_SYNC];
1700         ad->write_batch_count = ad->batch_expire[REQ_ASYNC] / 10;
1701         if (ad->write_batch_count < 2)
1702                 ad->write_batch_count = 2;
1703
1704         return ad;
1705 }
1706
1707 /*
1708  * sysfs parts below
1709  */
1710
1711 static ssize_t
1712 as_var_show(unsigned int var, char *page)
1713 {
1714         return sprintf(page, "%d\n", var);
1715 }
1716
1717 static ssize_t
1718 as_var_store(unsigned long *var, const char *page, size_t count)
1719 {
1720         char *p = (char *) page;
1721
1722         *var = simple_strtoul(p, &p, 10);
1723         return count;
1724 }
1725
1726 static ssize_t est_time_show(elevator_t *e, char *page)
1727 {
1728         struct as_data *ad = e->elevator_data;
1729         int pos = 0;
1730
1731         pos += sprintf(page+pos, "%lu %% exit probability\n",
1732                                 100*ad->exit_prob/256);
1733         pos += sprintf(page+pos, "%lu %% probability of exiting without a "
1734                                 "cooperating process submitting IO\n",
1735                                 100*ad->exit_no_coop/256);
1736         pos += sprintf(page+pos, "%lu ms new thinktime\n", ad->new_ttime_mean);
1737         pos += sprintf(page+pos, "%llu sectors new seek distance\n",
1738                                 (unsigned long long)ad->new_seek_mean);
1739
1740         return pos;
1741 }
1742
1743 #define SHOW_FUNCTION(__FUNC, __VAR)                            \
1744 static ssize_t __FUNC(elevator_t *e, char *page)                \
1745 {                                                               \
1746         struct as_data *ad = e->elevator_data;                  \
1747         return as_var_show(jiffies_to_msecs((__VAR)), (page));  \
1748 }
1749 SHOW_FUNCTION(as_read_expire_show, ad->fifo_expire[REQ_SYNC]);
1750 SHOW_FUNCTION(as_write_expire_show, ad->fifo_expire[REQ_ASYNC]);
1751 SHOW_FUNCTION(as_antic_expire_show, ad->antic_expire);
1752 SHOW_FUNCTION(as_read_batch_expire_show, ad->batch_expire[REQ_SYNC]);
1753 SHOW_FUNCTION(as_write_batch_expire_show, ad->batch_expire[REQ_ASYNC]);
1754 #undef SHOW_FUNCTION
1755
1756 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX)                         \
1757 static ssize_t __FUNC(elevator_t *e, const char *page, size_t count)    \
1758 {                                                                       \
1759         struct as_data *ad = e->elevator_data;                          \
1760         int ret = as_var_store(__PTR, (page), count);                   \
1761         if (*(__PTR) < (MIN))                                           \
1762                 *(__PTR) = (MIN);                                       \
1763         else if (*(__PTR) > (MAX))                                      \
1764                 *(__PTR) = (MAX);                                       \
1765         *(__PTR) = msecs_to_jiffies(*(__PTR));                          \
1766         return ret;                                                     \
1767 }
1768 STORE_FUNCTION(as_read_expire_store, &ad->fifo_expire[REQ_SYNC], 0, INT_MAX);
1769 STORE_FUNCTION(as_write_expire_store, &ad->fifo_expire[REQ_ASYNC], 0, INT_MAX);
1770 STORE_FUNCTION(as_antic_expire_store, &ad->antic_expire, 0, INT_MAX);
1771 STORE_FUNCTION(as_read_batch_expire_store,
1772                         &ad->batch_expire[REQ_SYNC], 0, INT_MAX);
1773 STORE_FUNCTION(as_write_batch_expire_store,
1774                         &ad->batch_expire[REQ_ASYNC], 0, INT_MAX);
1775 #undef STORE_FUNCTION
1776
1777 #define AS_ATTR(name) \
1778         __ATTR(name, S_IRUGO|S_IWUSR, as_##name##_show, as_##name##_store)
1779
1780 static struct elv_fs_entry as_attrs[] = {
1781         __ATTR_RO(est_time),
1782         AS_ATTR(read_expire),
1783         AS_ATTR(write_expire),
1784         AS_ATTR(antic_expire),
1785         AS_ATTR(read_batch_expire),
1786         AS_ATTR(write_batch_expire),
1787         __ATTR_NULL
1788 };
1789
1790 static struct elevator_type iosched_as = {
1791         .ops = {
1792                 .elevator_merge_fn =            as_merge,
1793                 .elevator_merged_fn =           as_merged_request,
1794                 .elevator_merge_req_fn =        as_merged_requests,
1795                 .elevator_dispatch_fn =         as_dispatch_request,
1796                 .elevator_add_req_fn =          as_add_request,
1797                 .elevator_activate_req_fn =     as_activate_request,
1798                 .elevator_deactivate_req_fn =   as_deactivate_request,
1799                 .elevator_queue_empty_fn =      as_queue_empty,
1800                 .elevator_completed_req_fn =    as_completed_request,
1801                 .elevator_former_req_fn =       as_former_request,
1802                 .elevator_latter_req_fn =       as_latter_request,
1803                 .elevator_set_req_fn =          as_set_request,
1804                 .elevator_put_req_fn =          as_put_request,
1805                 .elevator_may_queue_fn =        as_may_queue,
1806                 .elevator_init_fn =             as_init_queue,
1807                 .elevator_exit_fn =             as_exit_queue,
1808                 .trim =                         as_trim,
1809         },
1810
1811         .elevator_attrs = as_attrs,
1812         .elevator_name = "anticipatory",
1813         .elevator_owner = THIS_MODULE,
1814 };
1815
1816 static int __init as_init(void)
1817 {
1818         int ret;
1819
1820         arq_pool = kmem_cache_create("as_arq", sizeof(struct as_rq),
1821                                      0, 0, NULL, NULL);
1822         if (!arq_pool)
1823                 return -ENOMEM;
1824
1825         ret = elv_register(&iosched_as);
1826         if (!ret) {
1827                 /*
1828                  * don't allow AS to get unregistered, since we would have
1829                  * to browse all tasks in the system and release their
1830                  * as_io_context first
1831                  */
1832                 __module_get(THIS_MODULE);
1833                 return 0;
1834         }
1835
1836         kmem_cache_destroy(arq_pool);
1837         return ret;
1838 }
1839
1840 static void __exit as_exit(void)
1841 {
1842         DECLARE_COMPLETION(all_gone);
1843         elv_unregister(&iosched_as);
1844         ioc_gone = &all_gone;
1845         /* ioc_gone's update must be visible before reading ioc_count */
1846         smp_wmb();
1847         if (atomic_read(&ioc_count))
1848                 wait_for_completion(ioc_gone);
1849         synchronize_rcu();
1850         kmem_cache_destroy(arq_pool);
1851 }
1852
1853 module_init(as_init);
1854 module_exit(as_exit);
1855
1856 MODULE_AUTHOR("Nick Piggin");
1857 MODULE_LICENSE("GPL");
1858 MODULE_DESCRIPTION("anticipatory IO scheduler");