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