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