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