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