2 * Anticipatory & deadline i/o scheduler.
4 * Copyright (C) 2002 Jens Axboe <axboe@suse.de>
5 * Nick Piggin <nickpiggin@yahoo.com.au>
8 #include <linux/kernel.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>
24 * See Documentation/block/as-iosched.txt
28 * max time before a read is submitted.
30 #define default_read_expire (HZ / 8)
33 * ditto for writes, these limits are not hard, even
34 * if the disk is capable of satisfying them.
36 #define default_write_expire (HZ / 4)
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.
42 #define default_read_batch_expire (HZ / 2)
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...
50 #define default_write_batch_expire (HZ / 8)
53 * max time we may wait to anticipate a read (default around 6ms)
55 #define default_antic_expire ((HZ / 150) ? HZ / 150 : 1)
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.
64 #define MAX_THINKTIME (HZ/50UL)
66 /* Bits in as_io_context.state */
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 */
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
87 struct request_queue *q; /* the "owner" queue */
90 * requests (as_rq s) are present on both sort_list and fifo_list
92 struct rb_root sort_list[2];
93 struct list_head fifo_list[2];
95 struct as_rq *next_arq[2]; /* next in sort order */
96 sector_t last_sector[2]; /* last REQ_SYNC & REQ_ASYNC sectors */
98 unsigned long exit_prob; /* probability a task will exit while
100 unsigned long exit_no_coop; /* probablility an exited task will
101 not be part of a later cooperating
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;
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? */
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 */
127 * settings that change how the i/o scheduler behaves
129 unsigned long fifo_expire[2];
130 unsigned long batch_expire[2];
131 unsigned long antic_expire;
134 #define list_entry_fifo(ptr) list_entry((ptr), struct as_rq, fifo)
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
143 AS_RQ_DISPATCHED, /* On the dispatch list. It belongs to the
145 AS_RQ_PRESCHED, /* Debug poisoning for requests being used */
148 AS_RQ_POSTSCHED, /* when they shouldn't be */
153 * rbtree index, key is the starting offset
155 struct rb_node rb_node;
158 struct request *request;
160 struct io_context *io_context; /* The submitting task */
165 struct list_head fifo;
166 unsigned long expires;
168 unsigned int is_sync;
169 enum arq_state state;
172 #define RQ_DATA(rq) ((struct as_rq *) (rq)->elevator_private)
174 static kmem_cache_t *arq_pool;
176 static atomic_t ioc_count = ATOMIC_INIT(0);
177 static struct completion *ioc_gone;
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);
183 * IO Context helper functions
186 /* Called to deallocate the as_io_context */
187 static void free_as_io_context(struct as_io_context *aic)
190 if (atomic_dec_and_test(&ioc_count) && ioc_gone)
194 static void as_trim(struct io_context *ioc)
197 free_as_io_context(ioc->aic);
201 /* Called when the task exits */
202 static void exit_as_io_context(struct as_io_context *aic)
204 WARN_ON(!test_bit(AS_TASK_RUNNING, &aic->state));
205 clear_bit(AS_TASK_RUNNING, &aic->state);
208 static struct as_io_context *alloc_as_io_context(void)
210 struct as_io_context *ret;
212 ret = kmalloc(sizeof(*ret), GFP_ATOMIC);
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;
224 ret->seek_samples = 0;
226 atomic_inc(&ioc_count);
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.
236 static struct io_context *as_get_io_context(void)
238 struct io_context *ioc = get_io_context(GFP_ATOMIC);
239 if (ioc && !ioc->aic) {
240 ioc->aic = alloc_as_io_context();
249 static void as_put_io_context(struct as_rq *arq)
251 struct as_io_context *aic;
253 if (unlikely(!arq->io_context))
256 aic = arq->io_context->aic;
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);
265 put_io_context(arq->io_context);
269 * rb tree support functions
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
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.
280 static struct as_rq *as_find_first_arq(struct as_data *ad, int data_dir)
282 struct rb_node *n = ad->sort_list[data_dir].rb_node;
288 if (n->rb_left == NULL)
289 return rb_entry_arq(n);
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.
300 static struct as_rq *__as_add_arq_rb(struct as_data *ad, struct as_rq *arq)
302 struct rb_node **p = &ARQ_RB_ROOT(ad, arq)->rb_node;
303 struct rb_node *parent = NULL;
305 struct request *rq = arq->request;
307 arq->rb_key = rq_rb_key(rq);
311 __arq = rb_entry_arq(parent);
313 if (arq->rb_key < __arq->rb_key)
315 else if (arq->rb_key > __arq->rb_key)
321 rb_link_node(&arq->rb_node, parent, p);
322 rb_insert_color(&arq->rb_node, ARQ_RB_ROOT(ad, arq));
327 static void as_add_arq_rb(struct as_data *ad, struct as_rq *arq)
331 while ((unlikely(alias = __as_add_arq_rb(ad, arq)))) {
332 as_move_to_dispatch(ad, alias);
337 static inline void as_del_arq_rb(struct as_data *ad, struct as_rq *arq)
339 if (RB_EMPTY_NODE(&arq->rb_node)) {
344 rb_erase(&arq->rb_node, ARQ_RB_ROOT(ad, arq));
345 RB_CLEAR_NODE(&arq->rb_node);
348 static struct request *
349 as_find_arq_rb(struct as_data *ad, sector_t sector, int data_dir)
351 struct rb_node *n = ad->sort_list[data_dir].rb_node;
355 arq = rb_entry_arq(n);
357 if (sector < arq->rb_key)
359 else if (sector > arq->rb_key)
369 * IO Scheduler proper
372 #define MAXBACK (1024 * 1024) /*
373 * Maximum distance the disk will go backward
377 #define BACK_PENALTY 2
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
383 static struct as_rq *
384 as_choose_req(struct as_data *ad, struct as_rq *arq1, struct as_rq *arq2)
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;
391 if (arq1 == NULL || arq1 == arq2)
396 data_dir = arq1->is_sync;
398 last = ad->last_sector[data_dir];
399 s1 = arq1->request->sector;
400 s2 = arq2->request->sector;
402 BUG_ON(data_dir != arq2->is_sync);
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.
411 else if (s1+maxback >= last)
412 d1 = (last - s1)*BACK_PENALTY;
415 d1 = 0; /* shut up, gcc */
420 else if (s2+maxback >= last)
421 d2 = (last - s2)*BACK_PENALTY;
427 /* Found required data */
428 if (!r1_wrap && r2_wrap)
430 else if (!r2_wrap && r1_wrap)
432 else if (r1_wrap && r2_wrap) {
433 /* both behind the head */
440 /* Both requests in front of the head */
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.
458 static struct as_rq *as_find_next_arq(struct as_data *ad, struct as_rq *last)
460 const int data_dir = last->is_sync;
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;
466 BUG_ON(!RB_EMPTY_NODE(&last->rb_node));
469 arq_prev = rb_entry_arq(rbprev);
474 arq_next = rb_entry_arq(rbnext);
476 arq_next = as_find_first_arq(ad, data_dir);
477 if (arq_next == last)
481 ret = as_choose_req(ad, arq_next, arq_prev);
487 * anticipatory scheduling functions follow
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.
495 static int as_antic_expired(struct as_data *ad)
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)
509 * as_antic_waitnext starts anticipating that a nice request will soon be
510 * submitted. See also as_antic_waitreq
512 static void as_antic_waitnext(struct as_data *ad)
514 unsigned long timeout;
516 BUG_ON(ad->antic_status != ANTIC_OFF
517 && ad->antic_status != ANTIC_WAIT_REQ);
519 timeout = ad->antic_start + ad->antic_expire;
521 mod_timer(&ad->antic_timer, timeout);
523 ad->antic_status = ANTIC_WAIT_NEXT;
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.
531 static void as_antic_waitreq(struct as_data *ad)
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);
538 ad->antic_status = ANTIC_WAIT_REQ;
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.
546 static void as_antic_stop(struct as_data *ad)
548 int status = ad->antic_status;
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);
560 * as_antic_timeout is the timer function set by as_antic_waitnext.
562 static void as_antic_timeout(unsigned long data)
564 struct request_queue *q = (struct request_queue *)data;
565 struct as_data *ad = q->elevator->elevator_data;
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;
573 ad->antic_status = ANTIC_FINISHED;
574 kblockd_schedule_work(&ad->antic_work);
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;
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;
585 spin_unlock_irqrestore(q->queue_lock, flags);
588 static void as_update_thinktime(struct as_data *ad, struct as_io_context *aic,
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;
596 ad->exit_prob = (7*ad->exit_prob)/8;
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;
603 static void as_update_seekdist(struct as_data *ad, struct as_io_context *aic,
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;
614 * Don't allow the seek distance to get too large from the
615 * odd fragment, pagein, etc
617 if (aic->seek_samples <= 60) /* second&third seek */
618 sdist = min(sdist, (aic->seek_mean * 4) + 2*1024*1024);
620 sdist = min(sdist, (aic->seek_mean * 4) + 2*1024*64);
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;
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
634 static void as_update_iohist(struct as_data *ad, struct as_io_context *aic,
637 struct as_rq *arq = RQ_DATA(rq);
638 int data_dir = arq->is_sync;
639 unsigned long thinktime = 0;
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)
654 thinktime = jiffies - aic->last_end_request;
655 thinktime = min(thinktime, MAX_THINKTIME-1);
657 as_update_thinktime(ad, aic, thinktime);
659 /* Calculate read -> read seek distance */
660 if (aic->last_request_pos < rq->sector)
661 seek_dist = rq->sector - aic->last_request_pos;
663 seek_dist = aic->last_request_pos - rq->sector;
664 as_update_seekdist(ad, aic, seek_dist);
666 aic->last_request_pos = rq->sector + rq->nr_sectors;
667 set_bit(AS_TASK_IOSTARTED, &aic->state);
668 spin_unlock(&aic->lock);
673 * as_close_req decides if one request is considered "close" to the
674 * previous one issued.
676 static int as_close_req(struct as_data *ad, struct as_io_context *aic,
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) */
685 if (ad->antic_status == ANTIC_OFF || !ad->ioc_finished)
688 delay = ((jiffies - ad->antic_start) * 1000) / HZ;
692 else if (delay <= 20 && delay <= ad->antic_expire)
693 delta = 8192 << delay;
697 if ((last <= next + (delta>>1)) && (next <= last + delta))
705 if (aic->seek_samples == 0) {
707 * Process has just started IO. Use past statistics to
708 * gauge success possibility
710 if (ad->new_seek_mean > s) {
711 /* this request is better than what we're expecting */
716 if (aic->seek_mean > s) {
717 /* this request is better than what we're expecting */
726 * as_can_break_anticipation returns true if we have been anticipating this
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
734 * If the task which has submitted the request has exited, break anticipation.
736 * If this task has queued some other IO, do not enter enticipation.
738 static int as_can_break_anticipation(struct as_data *ad, struct as_rq *arq)
740 struct io_context *ioc;
741 struct as_io_context *aic;
743 ioc = ad->io_context;
746 if (arq && ioc == arq->io_context) {
747 /* request from same process */
751 if (ad->ioc_finished && as_antic_expired(ad)) {
753 * In this situation status should really be FINISHED,
754 * however the timer hasn't had the chance to run yet.
763 if (atomic_read(&aic->nr_queued) > 0) {
764 /* process has more requests queued */
768 if (atomic_read(&aic->nr_dispatched) > 0) {
769 /* process has more requests dispatched */
773 if (arq && arq->is_sync == REQ_SYNC && as_close_req(ad, aic, arq)) {
775 * Found a close request that is not one of ours.
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
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;
786 ad->exit_no_coop = (7*ad->exit_no_coop)/8;
789 as_update_iohist(ad, aic, arq->request);
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;
798 if (ad->exit_no_coop > 128)
802 if (aic->ttime_samples == 0) {
803 if (ad->new_ttime_mean > ad->antic_expire)
805 if (ad->exit_prob * ad->exit_no_coop > 128*256)
807 } else if (aic->ttime_mean > ad->antic_expire) {
808 /* the process thinks too much between requests */
816 * as_can_anticipate indicates whether we should either run arq
817 * or keep anticipating a better request.
819 static int as_can_anticipate(struct as_data *ad, struct as_rq *arq)
823 * Last request submitted was a write
827 if (ad->antic_status == ANTIC_FINISHED)
829 * Don't restart if we have just finished. Run the next request
833 if (as_can_break_anticipation(ad, arq))
835 * This request is a good candidate. Don't keep anticipating,
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.
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"
855 static void as_update_arq(struct as_data *ad, struct as_rq *arq)
857 const int data_dir = arq->is_sync;
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]);
863 * have we been anticipating this request?
864 * or does it come from the same process as the one we are anticipating
867 if (ad->antic_status == ANTIC_WAIT_REQ
868 || ad->antic_status == ANTIC_WAIT_NEXT) {
869 if (as_can_break_anticipation(ad, arq))
875 * Gathers timings and resizes the write batch automatically
877 static void update_write_batch(struct as_data *ad)
879 unsigned long batch = ad->batch_expire[REQ_ASYNC];
882 write_time = (jiffies - ad->current_batch_expires) + batch;
886 if (write_time > batch && !ad->write_batch_idled) {
887 if (write_time > batch * 3)
888 ad->write_batch_count /= 2;
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;
895 ad->write_batch_count++;
898 if (ad->write_batch_count < 1)
899 ad->write_batch_count = 1;
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.
906 static void as_completed_request(request_queue_t *q, struct request *rq)
908 struct as_data *ad = q->elevator->elevator_data;
909 struct as_rq *arq = RQ_DATA(rq);
911 WARN_ON(!list_empty(&rq->queuelist));
913 if (arq->state != AS_RQ_REMOVED) {
914 printk("arq->state %d\n", arq->state);
919 if (ad->changed_batch && ad->nr_dispatched == 1) {
920 kblockd_schedule_work(&ad->antic_work);
921 ad->changed_batch = 0;
923 if (ad->batch_data_dir == REQ_SYNC)
926 WARN_ON(ad->nr_dispatched == 0);
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
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];
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) {
946 * We were waiting on this request, now anticipate
949 as_antic_waitnext(ad);
953 as_put_io_context(arq);
955 arq->state = AS_RQ_POSTSCHED;
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)
964 static void as_remove_queued_request(request_queue_t *q, struct request *rq)
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;
970 WARN_ON(arq->state != AS_RQ_QUEUED);
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);
978 * Update the "next_arq" cache if we are about to remove its
981 if (ad->next_arq[data_dir] == arq)
982 ad->next_arq[data_dir] = as_find_next_arq(ad, arq);
984 list_del_init(&arq->fifo);
985 as_del_arq_rb(ad, arq);
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.
994 * See as_antic_expired comment.
996 static int as_fifo_expired(struct as_data *ad, int adir)
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])
1007 ad->last_check_fifo[adir] = jiffies;
1009 if (list_empty(&ad->fifo_list[adir]))
1012 arq = list_entry_fifo(ad->fifo_list[adir].next);
1014 return time_after(jiffies, arq->expires);
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.
1021 static inline int as_batch_expired(struct as_data *ad)
1023 if (ad->changed_batch || ad->new_batch)
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);
1030 return time_after(jiffies, ad->current_batch_expires)
1031 || ad->current_write_count == 0;
1035 * move an entry to dispatch queue
1037 static void as_move_to_dispatch(struct as_data *ad, struct as_rq *arq)
1039 struct request *rq = arq->request;
1040 const int data_dir = arq->is_sync;
1042 BUG_ON(RB_EMPTY_NODE(&arq->rb_node));
1045 ad->antic_status = ANTIC_OFF;
1048 * This has to be set in order to be correctly updated by
1051 ad->last_sector[data_dir] = rq->sector + rq->nr_sectors;
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);
1057 if (ad->io_context) {
1058 put_io_context(ad->io_context);
1059 ad->io_context = NULL;
1062 if (ad->current_write_count != 0)
1063 ad->current_write_count--;
1065 ad->ioc_finished = 0;
1067 ad->next_arq[data_dir] = as_find_next_arq(ad, arq);
1070 * take it off the sort and fifo list, add to dispatch queue
1072 as_remove_queued_request(ad->q, rq);
1073 WARN_ON(arq->state != AS_RQ_QUEUED);
1075 elv_dispatch_sort(ad->q, rq);
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++;
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.
1088 static int as_dispatch_request(request_queue_t *q, int force)
1090 struct as_data *ad = q->elevator->elevator_data;
1092 const int reads = !list_empty(&ad->fifo_list[REQ_SYNC]);
1093 const int writes = !list_empty(&ad->fifo_list[REQ_ASYNC]);
1095 if (unlikely(force)) {
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.
1105 ad->batch_data_dir = REQ_SYNC;
1106 ad->changed_batch = 0;
1109 while (ad->next_arq[REQ_SYNC]) {
1110 as_move_to_dispatch(ad, ad->next_arq[REQ_SYNC]);
1113 ad->last_check_fifo[REQ_SYNC] = jiffies;
1115 while (ad->next_arq[REQ_ASYNC]) {
1116 as_move_to_dispatch(ad, ad->next_arq[REQ_ASYNC]);
1119 ad->last_check_fifo[REQ_ASYNC] = jiffies;
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;
1130 if (!(reads || writes)
1131 || ad->antic_status == ANTIC_WAIT_REQ
1132 || ad->antic_status == ANTIC_WAIT_NEXT
1133 || ad->changed_batch)
1136 if (!(reads && writes && as_batch_expired(ad))) {
1138 * batch is still running or no reads or no writes
1140 arq = ad->next_arq[ad->batch_data_dir];
1142 if (ad->batch_data_dir == REQ_SYNC && ad->antic_expire) {
1143 if (as_fifo_expired(ad, REQ_SYNC))
1146 if (as_can_anticipate(ad, arq)) {
1147 as_antic_waitreq(ad);
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;
1162 * at this point we are not running a batch. select the appropriate
1163 * data direction (read / write)
1167 BUG_ON(RB_EMPTY_ROOT(&ad->sort_list[REQ_SYNC]));
1169 if (writes && ad->batch_data_dir == REQ_SYNC)
1171 * Last batch was a read, switch to writes
1173 goto dispatch_writes;
1175 if (ad->batch_data_dir == REQ_ASYNC) {
1176 WARN_ON(ad->new_batch);
1177 ad->changed_batch = 1;
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;
1186 * the last batch was a read
1191 BUG_ON(RB_EMPTY_ROOT(&ad->sort_list[REQ_ASYNC]));
1193 if (ad->batch_data_dir == REQ_SYNC) {
1194 ad->changed_batch = 1;
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.
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;
1215 * If a request has expired, service it.
1218 if (as_fifo_expired(ad, ad->batch_data_dir)) {
1220 arq = list_entry_fifo(ad->fifo_list[ad->batch_data_dir].next);
1221 BUG_ON(arq == NULL);
1224 if (ad->changed_batch) {
1225 WARN_ON(ad->new_batch);
1227 if (ad->nr_dispatched)
1230 if (ad->batch_data_dir == REQ_ASYNC)
1231 ad->current_batch_expires = jiffies +
1232 ad->batch_expire[REQ_ASYNC];
1236 ad->changed_batch = 0;
1240 * arq is the selected appropriate request.
1242 as_move_to_dispatch(ad, arq);
1248 * add arq to rbtree and fifo
1250 static void as_add_request(request_queue_t *q, struct request *rq)
1252 struct as_data *ad = q->elevator->elevator_data;
1253 struct as_rq *arq = RQ_DATA(rq);
1256 arq->state = AS_RQ_NEW;
1258 if (rq_data_dir(arq->request) == READ
1259 || (arq->request->cmd_flags & REQ_RW_SYNC))
1263 data_dir = arq->is_sync;
1265 arq->io_context = as_get_io_context();
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);
1272 as_add_arq_rb(ad, arq);
1275 * set expire time (only used for reads) and add to fifo list
1277 arq->expires = jiffies + ad->fifo_expire[data_dir];
1278 list_add_tail(&arq->fifo, &ad->fifo_list[data_dir]);
1280 as_update_arq(ad, arq); /* keep state machine up to date */
1281 arq->state = AS_RQ_QUEUED;
1284 static void as_activate_request(request_queue_t *q, struct request *rq)
1286 struct as_rq *arq = RQ_DATA(rq);
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);
1294 static void as_deactivate_request(request_queue_t *q, struct request *rq)
1296 struct as_rq *arq = RQ_DATA(rq);
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);
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
1310 static int as_queue_empty(request_queue_t *q)
1312 struct as_data *ad = q->elevator->elevator_data;
1314 return list_empty(&ad->fifo_list[REQ_ASYNC])
1315 && list_empty(&ad->fifo_list[REQ_SYNC]);
1318 static struct request *as_former_request(request_queue_t *q,
1321 struct as_rq *arq = RQ_DATA(rq);
1322 struct rb_node *rbprev = rb_prev(&arq->rb_node);
1323 struct request *ret = NULL;
1326 ret = rb_entry_arq(rbprev)->request;
1331 static struct request *as_latter_request(request_queue_t *q,
1334 struct as_rq *arq = RQ_DATA(rq);
1335 struct rb_node *rbnext = rb_next(&arq->rb_node);
1336 struct request *ret = NULL;
1339 ret = rb_entry_arq(rbnext)->request;
1345 as_merge(request_queue_t *q, struct request **req, struct bio *bio)
1347 struct as_data *ad = q->elevator->elevator_data;
1348 sector_t rb_key = bio->bi_sector + bio_sectors(bio);
1349 struct request *__rq;
1352 * check for front merge
1354 __rq = as_find_arq_rb(ad, rb_key, bio_data_dir(bio));
1355 if (__rq && elv_rq_merge_ok(__rq, bio)) {
1357 return ELEVATOR_FRONT_MERGE;
1360 return ELEVATOR_NO_MERGE;
1363 static void as_merged_request(request_queue_t *q, struct request *req)
1365 struct as_data *ad = q->elevator->elevator_data;
1366 struct as_rq *arq = RQ_DATA(req);
1369 * if the merge was a front merge, we need to reposition request
1371 if (rq_rb_key(req) != arq->rb_key) {
1372 as_del_arq_rb(ad, arq);
1373 as_add_arq_rb(ad, arq);
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.
1382 static void as_merged_requests(request_queue_t *q, struct request *req,
1383 struct request *next)
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);
1392 if (rq_rb_key(req) != arq->rb_key) {
1393 as_del_arq_rb(ad, arq);
1394 as_add_arq_rb(ad, arq);
1398 * if anext expires before arq, assign its expire time to arq
1399 * and move into anext position (anext will be deleted) in fifo
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;
1406 * Don't copy here but swap, because when anext is
1407 * removed below, it must contain the unused context
1409 swap_io_context(&arq->io_context, &anext->io_context);
1414 * kill knowledge of next, this one is a goner
1416 as_remove_queued_request(q, next);
1417 as_put_io_context(anext);
1419 anext->state = AS_RQ_MERGED;
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.
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.
1429 * FIXME! dispatch queue is not a queue at all!
1431 static void as_work_handler(void *data)
1433 struct request_queue *q = data;
1434 unsigned long flags;
1436 spin_lock_irqsave(q->queue_lock, flags);
1437 if (!as_queue_empty(q))
1439 spin_unlock_irqrestore(q->queue_lock, flags);
1442 static void as_put_request(request_queue_t *q, struct request *rq)
1444 struct as_data *ad = q->elevator->elevator_data;
1445 struct as_rq *arq = RQ_DATA(rq);
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);
1459 mempool_free(arq, ad->arq_pool);
1460 rq->elevator_private = NULL;
1463 static int as_set_request(request_queue_t *q, struct request *rq,
1464 struct bio *bio, gfp_t gfp_mask)
1466 struct as_data *ad = q->elevator->elevator_data;
1467 struct as_rq *arq = mempool_alloc(ad->arq_pool, gfp_mask);
1470 memset(arq, 0, sizeof(*arq));
1471 RB_CLEAR_NODE(&arq->rb_node);
1473 arq->state = AS_RQ_PRESCHED;
1474 arq->io_context = NULL;
1475 INIT_LIST_HEAD(&arq->fifo);
1476 rq->elevator_private = arq;
1483 static int as_may_queue(request_queue_t *q, int rw, struct bio *bio)
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);
1499 static void as_exit_queue(elevator_t *e)
1501 struct as_data *ad = e->elevator_data;
1503 del_timer_sync(&ad->antic_timer);
1506 BUG_ON(!list_empty(&ad->fifo_list[REQ_SYNC]));
1507 BUG_ON(!list_empty(&ad->fifo_list[REQ_ASYNC]));
1509 mempool_destroy(ad->arq_pool);
1510 put_io_context(ad->io_context);
1515 * initialize elevator private data (as_data), and alloc a arq for
1516 * each request on the free lists
1518 static void *as_init_queue(request_queue_t *q, elevator_t *e)
1525 ad = kmalloc_node(sizeof(*ad), GFP_KERNEL, q->node);
1528 memset(ad, 0, sizeof(*ad));
1530 ad->q = q; /* Identify what queue the data belongs to */
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) {
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);
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;
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;
1568 as_var_show(unsigned int var, char *page)
1570 return sprintf(page, "%d\n", var);
1574 as_var_store(unsigned long *var, const char *page, size_t count)
1576 char *p = (char *) page;
1578 *var = simple_strtoul(p, &p, 10);
1582 static ssize_t est_time_show(elevator_t *e, char *page)
1584 struct as_data *ad = e->elevator_data;
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);
1599 #define SHOW_FUNCTION(__FUNC, __VAR) \
1600 static ssize_t __FUNC(elevator_t *e, char *page) \
1602 struct as_data *ad = e->elevator_data; \
1603 return as_var_show(jiffies_to_msecs((__VAR)), (page)); \
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
1612 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
1613 static ssize_t __FUNC(elevator_t *e, const char *page, size_t count) \
1615 struct as_data *ad = e->elevator_data; \
1616 int ret = as_var_store(__PTR, (page), count); \
1617 if (*(__PTR) < (MIN)) \
1619 else if (*(__PTR) > (MAX)) \
1621 *(__PTR) = msecs_to_jiffies(*(__PTR)); \
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
1633 #define AS_ATTR(name) \
1634 __ATTR(name, S_IRUGO|S_IWUSR, as_##name##_show, as_##name##_store)
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),
1646 static struct elevator_type iosched_as = {
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,
1667 .elevator_attrs = as_attrs,
1668 .elevator_name = "anticipatory",
1669 .elevator_owner = THIS_MODULE,
1672 static int __init as_init(void)
1676 arq_pool = kmem_cache_create("as_arq", sizeof(struct as_rq),
1681 ret = elv_register(&iosched_as);
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
1688 __module_get(THIS_MODULE);
1692 kmem_cache_destroy(arq_pool);
1696 static void __exit as_exit(void)
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 */
1703 if (atomic_read(&ioc_count))
1704 wait_for_completion(ioc_gone);
1706 kmem_cache_destroy(arq_pool);
1709 module_init(as_init);
1710 module_exit(as_exit);
1712 MODULE_AUTHOR("Nick Piggin");
1713 MODULE_LICENSE("GPL");
1714 MODULE_DESCRIPTION("anticipatory IO scheduler");