coredump: zap_threads: comments && use while_each_thread()
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / block / as-iosched.c
blob9735acb5b4f51544b831ecb07bd037f88d99090f
1 /*
2 * Anticipatory & deadline i/o scheduler.
4 * Copyright (C) 2002 Jens Axboe <axboe@kernel.dk>
5 * Nick Piggin <nickpiggin@yahoo.com.au>
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>
20 #define REQ_SYNC 1
21 #define REQ_ASYNC 0
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 */
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 */
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 */
82 struct as_data {
84 * run time data
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 request *next_rq[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
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;
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? */
117 enum anticipation_status antic_status;
118 unsigned long antic_start; /* jiffies: when it started */
119 struct timer_list antic_timer; /* anticipatory scheduling timer */
120 struct work_struct antic_work; /* Deferred unplugging */
121 struct io_context *io_context; /* Identify the expected process */
122 int ioc_finished; /* IO associated with io_context is finished */
123 int nr_dispatched;
126 * settings that change how the i/o scheduler behaves
128 unsigned long fifo_expire[2];
129 unsigned long batch_expire[2];
130 unsigned long antic_expire;
134 * per-request data.
136 enum arq_state {
137 AS_RQ_NEW=0, /* New - not referenced and not on any lists */
138 AS_RQ_QUEUED, /* In the request queue. It belongs to the
139 scheduler */
140 AS_RQ_DISPATCHED, /* On the dispatch list. It belongs to the
141 driver now */
142 AS_RQ_PRESCHED, /* Debug poisoning for requests being used */
143 AS_RQ_REMOVED,
144 AS_RQ_MERGED,
145 AS_RQ_POSTSCHED, /* when they shouldn't be */
148 #define RQ_IOC(rq) ((struct io_context *) (rq)->elevator_private)
149 #define RQ_STATE(rq) ((enum arq_state)(rq)->elevator_private2)
150 #define RQ_SET_STATE(rq, state) ((rq)->elevator_private2 = (void *) state)
152 static DEFINE_PER_CPU(unsigned long, ioc_count);
153 static struct completion *ioc_gone;
154 static DEFINE_SPINLOCK(ioc_gone_lock);
156 static void as_move_to_dispatch(struct as_data *ad, struct request *rq);
157 static void as_antic_stop(struct as_data *ad);
160 * IO Context helper functions
163 /* Called to deallocate the as_io_context */
164 static void free_as_io_context(struct as_io_context *aic)
166 kfree(aic);
167 elv_ioc_count_dec(ioc_count);
168 if (ioc_gone) {
170 * AS scheduler is exiting, grab exit lock and check
171 * the pending io context count. If it hits zero,
172 * complete ioc_gone and set it back to NULL.
174 spin_lock(&ioc_gone_lock);
175 if (ioc_gone && !elv_ioc_count_read(ioc_count)) {
176 complete(ioc_gone);
177 ioc_gone = NULL;
179 spin_unlock(&ioc_gone_lock);
183 static void as_trim(struct io_context *ioc)
185 spin_lock_irq(&ioc->lock);
186 if (ioc->aic)
187 free_as_io_context(ioc->aic);
188 ioc->aic = NULL;
189 spin_unlock_irq(&ioc->lock);
192 /* Called when the task exits */
193 static void exit_as_io_context(struct as_io_context *aic)
195 WARN_ON(!test_bit(AS_TASK_RUNNING, &aic->state));
196 clear_bit(AS_TASK_RUNNING, &aic->state);
199 static struct as_io_context *alloc_as_io_context(void)
201 struct as_io_context *ret;
203 ret = kmalloc(sizeof(*ret), GFP_ATOMIC);
204 if (ret) {
205 ret->dtor = free_as_io_context;
206 ret->exit = exit_as_io_context;
207 ret->state = 1 << AS_TASK_RUNNING;
208 atomic_set(&ret->nr_queued, 0);
209 atomic_set(&ret->nr_dispatched, 0);
210 spin_lock_init(&ret->lock);
211 ret->ttime_total = 0;
212 ret->ttime_samples = 0;
213 ret->ttime_mean = 0;
214 ret->seek_total = 0;
215 ret->seek_samples = 0;
216 ret->seek_mean = 0;
217 elv_ioc_count_inc(ioc_count);
220 return ret;
224 * If the current task has no AS IO context then create one and initialise it.
225 * Then take a ref on the task's io context and return it.
227 static struct io_context *as_get_io_context(int node)
229 struct io_context *ioc = get_io_context(GFP_ATOMIC, node);
230 if (ioc && !ioc->aic) {
231 ioc->aic = alloc_as_io_context();
232 if (!ioc->aic) {
233 put_io_context(ioc);
234 ioc = NULL;
237 return ioc;
240 static void as_put_io_context(struct request *rq)
242 struct as_io_context *aic;
244 if (unlikely(!RQ_IOC(rq)))
245 return;
247 aic = RQ_IOC(rq)->aic;
249 if (rq_is_sync(rq) && aic) {
250 unsigned long flags;
252 spin_lock_irqsave(&aic->lock, flags);
253 set_bit(AS_TASK_IORUNNING, &aic->state);
254 aic->last_end_request = jiffies;
255 spin_unlock_irqrestore(&aic->lock, flags);
258 put_io_context(RQ_IOC(rq));
262 * rb tree support functions
264 #define RQ_RB_ROOT(ad, rq) (&(ad)->sort_list[rq_is_sync((rq))])
266 static void as_add_rq_rb(struct as_data *ad, struct request *rq)
268 struct request *alias;
270 while ((unlikely(alias = elv_rb_add(RQ_RB_ROOT(ad, rq), rq)))) {
271 as_move_to_dispatch(ad, alias);
272 as_antic_stop(ad);
276 static inline void as_del_rq_rb(struct as_data *ad, struct request *rq)
278 elv_rb_del(RQ_RB_ROOT(ad, rq), rq);
282 * IO Scheduler proper
285 #define MAXBACK (1024 * 1024) /*
286 * Maximum distance the disk will go backward
287 * for a request.
290 #define BACK_PENALTY 2
293 * as_choose_req selects the preferred one of two requests of the same data_dir
294 * ignoring time - eg. timeouts, which is the job of as_dispatch_request
296 static struct request *
297 as_choose_req(struct as_data *ad, struct request *rq1, struct request *rq2)
299 int data_dir;
300 sector_t last, s1, s2, d1, d2;
301 int r1_wrap=0, r2_wrap=0; /* requests are behind the disk head */
302 const sector_t maxback = MAXBACK;
304 if (rq1 == NULL || rq1 == rq2)
305 return rq2;
306 if (rq2 == NULL)
307 return rq1;
309 data_dir = rq_is_sync(rq1);
311 last = ad->last_sector[data_dir];
312 s1 = rq1->sector;
313 s2 = rq2->sector;
315 BUG_ON(data_dir != rq_is_sync(rq2));
318 * Strict one way elevator _except_ in the case where we allow
319 * short backward seeks which are biased as twice the cost of a
320 * similar forward seek.
322 if (s1 >= last)
323 d1 = s1 - last;
324 else if (s1+maxback >= last)
325 d1 = (last - s1)*BACK_PENALTY;
326 else {
327 r1_wrap = 1;
328 d1 = 0; /* shut up, gcc */
331 if (s2 >= last)
332 d2 = s2 - last;
333 else if (s2+maxback >= last)
334 d2 = (last - s2)*BACK_PENALTY;
335 else {
336 r2_wrap = 1;
337 d2 = 0;
340 /* Found required data */
341 if (!r1_wrap && r2_wrap)
342 return rq1;
343 else if (!r2_wrap && r1_wrap)
344 return rq2;
345 else if (r1_wrap && r2_wrap) {
346 /* both behind the head */
347 if (s1 <= s2)
348 return rq1;
349 else
350 return rq2;
353 /* Both requests in front of the head */
354 if (d1 < d2)
355 return rq1;
356 else if (d2 < d1)
357 return rq2;
358 else {
359 if (s1 >= s2)
360 return rq1;
361 else
362 return rq2;
367 * as_find_next_rq finds the next request after @prev in elevator order.
368 * this with as_choose_req form the basis for how the scheduler chooses
369 * what request to process next. Anticipation works on top of this.
371 static struct request *
372 as_find_next_rq(struct as_data *ad, struct request *last)
374 struct rb_node *rbnext = rb_next(&last->rb_node);
375 struct rb_node *rbprev = rb_prev(&last->rb_node);
376 struct request *next = NULL, *prev = NULL;
378 BUG_ON(RB_EMPTY_NODE(&last->rb_node));
380 if (rbprev)
381 prev = rb_entry_rq(rbprev);
383 if (rbnext)
384 next = rb_entry_rq(rbnext);
385 else {
386 const int data_dir = rq_is_sync(last);
388 rbnext = rb_first(&ad->sort_list[data_dir]);
389 if (rbnext && rbnext != &last->rb_node)
390 next = rb_entry_rq(rbnext);
393 return as_choose_req(ad, next, prev);
397 * anticipatory scheduling functions follow
401 * as_antic_expired tells us when we have anticipated too long.
402 * The funny "absolute difference" math on the elapsed time is to handle
403 * jiffy wraps, and disks which have been idle for 0x80000000 jiffies.
405 static int as_antic_expired(struct as_data *ad)
407 long delta_jif;
409 delta_jif = jiffies - ad->antic_start;
410 if (unlikely(delta_jif < 0))
411 delta_jif = -delta_jif;
412 if (delta_jif < ad->antic_expire)
413 return 0;
415 return 1;
419 * as_antic_waitnext starts anticipating that a nice request will soon be
420 * submitted. See also as_antic_waitreq
422 static void as_antic_waitnext(struct as_data *ad)
424 unsigned long timeout;
426 BUG_ON(ad->antic_status != ANTIC_OFF
427 && ad->antic_status != ANTIC_WAIT_REQ);
429 timeout = ad->antic_start + ad->antic_expire;
431 mod_timer(&ad->antic_timer, timeout);
433 ad->antic_status = ANTIC_WAIT_NEXT;
437 * as_antic_waitreq starts anticipating. We don't start timing the anticipation
438 * until the request that we're anticipating on has finished. This means we
439 * are timing from when the candidate process wakes up hopefully.
441 static void as_antic_waitreq(struct as_data *ad)
443 BUG_ON(ad->antic_status == ANTIC_FINISHED);
444 if (ad->antic_status == ANTIC_OFF) {
445 if (!ad->io_context || ad->ioc_finished)
446 as_antic_waitnext(ad);
447 else
448 ad->antic_status = ANTIC_WAIT_REQ;
453 * This is called directly by the functions in this file to stop anticipation.
454 * We kill the timer and schedule a call to the request_fn asap.
456 static void as_antic_stop(struct as_data *ad)
458 int status = ad->antic_status;
460 if (status == ANTIC_WAIT_REQ || status == ANTIC_WAIT_NEXT) {
461 if (status == ANTIC_WAIT_NEXT)
462 del_timer(&ad->antic_timer);
463 ad->antic_status = ANTIC_FINISHED;
464 /* see as_work_handler */
465 kblockd_schedule_work(&ad->antic_work);
470 * as_antic_timeout is the timer function set by as_antic_waitnext.
472 static void as_antic_timeout(unsigned long data)
474 struct request_queue *q = (struct request_queue *)data;
475 struct as_data *ad = q->elevator->elevator_data;
476 unsigned long flags;
478 spin_lock_irqsave(q->queue_lock, flags);
479 if (ad->antic_status == ANTIC_WAIT_REQ
480 || ad->antic_status == ANTIC_WAIT_NEXT) {
481 struct as_io_context *aic;
482 spin_lock(&ad->io_context->lock);
483 aic = ad->io_context->aic;
485 ad->antic_status = ANTIC_FINISHED;
486 kblockd_schedule_work(&ad->antic_work);
488 if (aic->ttime_samples == 0) {
489 /* process anticipated on has exited or timed out*/
490 ad->exit_prob = (7*ad->exit_prob + 256)/8;
492 if (!test_bit(AS_TASK_RUNNING, &aic->state)) {
493 /* process not "saved" by a cooperating request */
494 ad->exit_no_coop = (7*ad->exit_no_coop + 256)/8;
496 spin_unlock(&ad->io_context->lock);
498 spin_unlock_irqrestore(q->queue_lock, flags);
501 static void as_update_thinktime(struct as_data *ad, struct as_io_context *aic,
502 unsigned long ttime)
504 /* fixed point: 1.0 == 1<<8 */
505 if (aic->ttime_samples == 0) {
506 ad->new_ttime_total = (7*ad->new_ttime_total + 256*ttime) / 8;
507 ad->new_ttime_mean = ad->new_ttime_total / 256;
509 ad->exit_prob = (7*ad->exit_prob)/8;
511 aic->ttime_samples = (7*aic->ttime_samples + 256) / 8;
512 aic->ttime_total = (7*aic->ttime_total + 256*ttime) / 8;
513 aic->ttime_mean = (aic->ttime_total + 128) / aic->ttime_samples;
516 static void as_update_seekdist(struct as_data *ad, struct as_io_context *aic,
517 sector_t sdist)
519 u64 total;
521 if (aic->seek_samples == 0) {
522 ad->new_seek_total = (7*ad->new_seek_total + 256*(u64)sdist)/8;
523 ad->new_seek_mean = ad->new_seek_total / 256;
527 * Don't allow the seek distance to get too large from the
528 * odd fragment, pagein, etc
530 if (aic->seek_samples <= 60) /* second&third seek */
531 sdist = min(sdist, (aic->seek_mean * 4) + 2*1024*1024);
532 else
533 sdist = min(sdist, (aic->seek_mean * 4) + 2*1024*64);
535 aic->seek_samples = (7*aic->seek_samples + 256) / 8;
536 aic->seek_total = (7*aic->seek_total + (u64)256*sdist) / 8;
537 total = aic->seek_total + (aic->seek_samples/2);
538 do_div(total, aic->seek_samples);
539 aic->seek_mean = (sector_t)total;
543 * as_update_iohist keeps a decaying histogram of IO thinktimes, and
544 * updates @aic->ttime_mean based on that. It is called when a new
545 * request is queued.
547 static void as_update_iohist(struct as_data *ad, struct as_io_context *aic,
548 struct request *rq)
550 int data_dir = rq_is_sync(rq);
551 unsigned long thinktime = 0;
552 sector_t seek_dist;
554 if (aic == NULL)
555 return;
557 if (data_dir == REQ_SYNC) {
558 unsigned long in_flight = atomic_read(&aic->nr_queued)
559 + atomic_read(&aic->nr_dispatched);
560 spin_lock(&aic->lock);
561 if (test_bit(AS_TASK_IORUNNING, &aic->state) ||
562 test_bit(AS_TASK_IOSTARTED, &aic->state)) {
563 /* Calculate read -> read thinktime */
564 if (test_bit(AS_TASK_IORUNNING, &aic->state)
565 && in_flight == 0) {
566 thinktime = jiffies - aic->last_end_request;
567 thinktime = min(thinktime, MAX_THINKTIME-1);
569 as_update_thinktime(ad, aic, thinktime);
571 /* Calculate read -> read seek distance */
572 if (aic->last_request_pos < rq->sector)
573 seek_dist = rq->sector - aic->last_request_pos;
574 else
575 seek_dist = aic->last_request_pos - rq->sector;
576 as_update_seekdist(ad, aic, seek_dist);
578 aic->last_request_pos = rq->sector + rq->nr_sectors;
579 set_bit(AS_TASK_IOSTARTED, &aic->state);
580 spin_unlock(&aic->lock);
585 * as_close_req decides if one request is considered "close" to the
586 * previous one issued.
588 static int as_close_req(struct as_data *ad, struct as_io_context *aic,
589 struct request *rq)
591 unsigned long delay; /* jiffies */
592 sector_t last = ad->last_sector[ad->batch_data_dir];
593 sector_t next = rq->sector;
594 sector_t delta; /* acceptable close offset (in sectors) */
595 sector_t s;
597 if (ad->antic_status == ANTIC_OFF || !ad->ioc_finished)
598 delay = 0;
599 else
600 delay = jiffies - ad->antic_start;
602 if (delay == 0)
603 delta = 8192;
604 else if (delay <= (20 * HZ / 1000) && delay <= ad->antic_expire)
605 delta = 8192 << delay;
606 else
607 return 1;
609 if ((last <= next + (delta>>1)) && (next <= last + delta))
610 return 1;
612 if (last < next)
613 s = next - last;
614 else
615 s = last - next;
617 if (aic->seek_samples == 0) {
619 * Process has just started IO. Use past statistics to
620 * gauge success possibility
622 if (ad->new_seek_mean > s) {
623 /* this request is better than what we're expecting */
624 return 1;
627 } else {
628 if (aic->seek_mean > s) {
629 /* this request is better than what we're expecting */
630 return 1;
634 return 0;
638 * as_can_break_anticipation returns true if we have been anticipating this
639 * request.
641 * It also returns true if the process against which we are anticipating
642 * submits a write - that's presumably an fsync, O_SYNC write, etc. We want to
643 * dispatch it ASAP, because we know that application will not be submitting
644 * any new reads.
646 * If the task which has submitted the request has exited, break anticipation.
648 * If this task has queued some other IO, do not enter enticipation.
650 static int as_can_break_anticipation(struct as_data *ad, struct request *rq)
652 struct io_context *ioc;
653 struct as_io_context *aic;
655 ioc = ad->io_context;
656 BUG_ON(!ioc);
657 spin_lock(&ioc->lock);
659 if (rq && ioc == RQ_IOC(rq)) {
660 /* request from same process */
661 spin_unlock(&ioc->lock);
662 return 1;
665 if (ad->ioc_finished && as_antic_expired(ad)) {
667 * In this situation status should really be FINISHED,
668 * however the timer hasn't had the chance to run yet.
670 spin_unlock(&ioc->lock);
671 return 1;
674 aic = ioc->aic;
675 if (!aic) {
676 spin_unlock(&ioc->lock);
677 return 0;
680 if (atomic_read(&aic->nr_queued) > 0) {
681 /* process has more requests queued */
682 spin_unlock(&ioc->lock);
683 return 1;
686 if (atomic_read(&aic->nr_dispatched) > 0) {
687 /* process has more requests dispatched */
688 spin_unlock(&ioc->lock);
689 return 1;
692 if (rq && rq_is_sync(rq) && as_close_req(ad, aic, rq)) {
694 * Found a close request that is not one of ours.
696 * This makes close requests from another process update
697 * our IO history. Is generally useful when there are
698 * two or more cooperating processes working in the same
699 * area.
701 if (!test_bit(AS_TASK_RUNNING, &aic->state)) {
702 if (aic->ttime_samples == 0)
703 ad->exit_prob = (7*ad->exit_prob + 256)/8;
705 ad->exit_no_coop = (7*ad->exit_no_coop)/8;
708 as_update_iohist(ad, aic, rq);
709 spin_unlock(&ioc->lock);
710 return 1;
713 if (!test_bit(AS_TASK_RUNNING, &aic->state)) {
714 /* process anticipated on has exited */
715 if (aic->ttime_samples == 0)
716 ad->exit_prob = (7*ad->exit_prob + 256)/8;
718 if (ad->exit_no_coop > 128) {
719 spin_unlock(&ioc->lock);
720 return 1;
724 if (aic->ttime_samples == 0) {
725 if (ad->new_ttime_mean > ad->antic_expire) {
726 spin_unlock(&ioc->lock);
727 return 1;
729 if (ad->exit_prob * ad->exit_no_coop > 128*256) {
730 spin_unlock(&ioc->lock);
731 return 1;
733 } else if (aic->ttime_mean > ad->antic_expire) {
734 /* the process thinks too much between requests */
735 spin_unlock(&ioc->lock);
736 return 1;
738 spin_unlock(&ioc->lock);
739 return 0;
743 * as_can_anticipate indicates whether we should either run rq
744 * or keep anticipating a better request.
746 static int as_can_anticipate(struct as_data *ad, struct request *rq)
748 if (!ad->io_context)
750 * Last request submitted was a write
752 return 0;
754 if (ad->antic_status == ANTIC_FINISHED)
756 * Don't restart if we have just finished. Run the next request
758 return 0;
760 if (as_can_break_anticipation(ad, rq))
762 * This request is a good candidate. Don't keep anticipating,
763 * run it.
765 return 0;
768 * OK from here, we haven't finished, and don't have a decent request!
769 * Status is either ANTIC_OFF so start waiting,
770 * ANTIC_WAIT_REQ so continue waiting for request to finish
771 * or ANTIC_WAIT_NEXT so continue waiting for an acceptable request.
774 return 1;
778 * as_update_rq must be called whenever a request (rq) is added to
779 * the sort_list. This function keeps caches up to date, and checks if the
780 * request might be one we are "anticipating"
782 static void as_update_rq(struct as_data *ad, struct request *rq)
784 const int data_dir = rq_is_sync(rq);
786 /* keep the next_rq cache up to date */
787 ad->next_rq[data_dir] = as_choose_req(ad, rq, ad->next_rq[data_dir]);
790 * have we been anticipating this request?
791 * or does it come from the same process as the one we are anticipating
792 * for?
794 if (ad->antic_status == ANTIC_WAIT_REQ
795 || ad->antic_status == ANTIC_WAIT_NEXT) {
796 if (as_can_break_anticipation(ad, rq))
797 as_antic_stop(ad);
802 * Gathers timings and resizes the write batch automatically
804 static void update_write_batch(struct as_data *ad)
806 unsigned long batch = ad->batch_expire[REQ_ASYNC];
807 long write_time;
809 write_time = (jiffies - ad->current_batch_expires) + batch;
810 if (write_time < 0)
811 write_time = 0;
813 if (write_time > batch && !ad->write_batch_idled) {
814 if (write_time > batch * 3)
815 ad->write_batch_count /= 2;
816 else
817 ad->write_batch_count--;
818 } else if (write_time < batch && ad->current_write_count == 0) {
819 if (batch > write_time * 3)
820 ad->write_batch_count *= 2;
821 else
822 ad->write_batch_count++;
825 if (ad->write_batch_count < 1)
826 ad->write_batch_count = 1;
830 * as_completed_request is to be called when a request has completed and
831 * returned something to the requesting process, be it an error or data.
833 static void as_completed_request(struct request_queue *q, struct request *rq)
835 struct as_data *ad = q->elevator->elevator_data;
837 WARN_ON(!list_empty(&rq->queuelist));
839 if (RQ_STATE(rq) != AS_RQ_REMOVED) {
840 printk("rq->state %d\n", RQ_STATE(rq));
841 WARN_ON(1);
842 goto out;
845 if (ad->changed_batch && ad->nr_dispatched == 1) {
846 ad->current_batch_expires = jiffies +
847 ad->batch_expire[ad->batch_data_dir];
848 kblockd_schedule_work(&ad->antic_work);
849 ad->changed_batch = 0;
851 if (ad->batch_data_dir == REQ_SYNC)
852 ad->new_batch = 1;
854 WARN_ON(ad->nr_dispatched == 0);
855 ad->nr_dispatched--;
858 * Start counting the batch from when a request of that direction is
859 * actually serviced. This should help devices with big TCQ windows
860 * and writeback caches
862 if (ad->new_batch && ad->batch_data_dir == rq_is_sync(rq)) {
863 update_write_batch(ad);
864 ad->current_batch_expires = jiffies +
865 ad->batch_expire[REQ_SYNC];
866 ad->new_batch = 0;
869 if (ad->io_context == RQ_IOC(rq) && ad->io_context) {
870 ad->antic_start = jiffies;
871 ad->ioc_finished = 1;
872 if (ad->antic_status == ANTIC_WAIT_REQ) {
874 * We were waiting on this request, now anticipate
875 * the next one
877 as_antic_waitnext(ad);
881 as_put_io_context(rq);
882 out:
883 RQ_SET_STATE(rq, AS_RQ_POSTSCHED);
887 * as_remove_queued_request removes a request from the pre dispatch queue
888 * without updating refcounts. It is expected the caller will drop the
889 * reference unless it replaces the request at somepart of the elevator
890 * (ie. the dispatch queue)
892 static void as_remove_queued_request(struct request_queue *q,
893 struct request *rq)
895 const int data_dir = rq_is_sync(rq);
896 struct as_data *ad = q->elevator->elevator_data;
897 struct io_context *ioc;
899 WARN_ON(RQ_STATE(rq) != AS_RQ_QUEUED);
901 ioc = RQ_IOC(rq);
902 if (ioc && ioc->aic) {
903 BUG_ON(!atomic_read(&ioc->aic->nr_queued));
904 atomic_dec(&ioc->aic->nr_queued);
908 * Update the "next_rq" cache if we are about to remove its
909 * entry
911 if (ad->next_rq[data_dir] == rq)
912 ad->next_rq[data_dir] = as_find_next_rq(ad, rq);
914 rq_fifo_clear(rq);
915 as_del_rq_rb(ad, rq);
919 * as_fifo_expired returns 0 if there are no expired requests on the fifo,
920 * 1 otherwise. It is ratelimited so that we only perform the check once per
921 * `fifo_expire' interval. Otherwise a large number of expired requests
922 * would create a hopeless seekstorm.
924 * See as_antic_expired comment.
926 static int as_fifo_expired(struct as_data *ad, int adir)
928 struct request *rq;
929 long delta_jif;
931 delta_jif = jiffies - ad->last_check_fifo[adir];
932 if (unlikely(delta_jif < 0))
933 delta_jif = -delta_jif;
934 if (delta_jif < ad->fifo_expire[adir])
935 return 0;
937 ad->last_check_fifo[adir] = jiffies;
939 if (list_empty(&ad->fifo_list[adir]))
940 return 0;
942 rq = rq_entry_fifo(ad->fifo_list[adir].next);
944 return time_after(jiffies, rq_fifo_time(rq));
948 * as_batch_expired returns true if the current batch has expired. A batch
949 * is a set of reads or a set of writes.
951 static inline int as_batch_expired(struct as_data *ad)
953 if (ad->changed_batch || ad->new_batch)
954 return 0;
956 if (ad->batch_data_dir == REQ_SYNC)
957 /* TODO! add a check so a complete fifo gets written? */
958 return time_after(jiffies, ad->current_batch_expires);
960 return time_after(jiffies, ad->current_batch_expires)
961 || ad->current_write_count == 0;
965 * move an entry to dispatch queue
967 static void as_move_to_dispatch(struct as_data *ad, struct request *rq)
969 const int data_dir = rq_is_sync(rq);
971 BUG_ON(RB_EMPTY_NODE(&rq->rb_node));
973 as_antic_stop(ad);
974 ad->antic_status = ANTIC_OFF;
977 * This has to be set in order to be correctly updated by
978 * as_find_next_rq
980 ad->last_sector[data_dir] = rq->sector + rq->nr_sectors;
982 if (data_dir == REQ_SYNC) {
983 struct io_context *ioc = RQ_IOC(rq);
984 /* In case we have to anticipate after this */
985 copy_io_context(&ad->io_context, &ioc);
986 } else {
987 if (ad->io_context) {
988 put_io_context(ad->io_context);
989 ad->io_context = NULL;
992 if (ad->current_write_count != 0)
993 ad->current_write_count--;
995 ad->ioc_finished = 0;
997 ad->next_rq[data_dir] = as_find_next_rq(ad, rq);
1000 * take it off the sort and fifo list, add to dispatch queue
1002 as_remove_queued_request(ad->q, rq);
1003 WARN_ON(RQ_STATE(rq) != AS_RQ_QUEUED);
1005 elv_dispatch_sort(ad->q, rq);
1007 RQ_SET_STATE(rq, AS_RQ_DISPATCHED);
1008 if (RQ_IOC(rq) && RQ_IOC(rq)->aic)
1009 atomic_inc(&RQ_IOC(rq)->aic->nr_dispatched);
1010 ad->nr_dispatched++;
1014 * as_dispatch_request selects the best request according to
1015 * read/write expire, batch expire, etc, and moves it to the dispatch
1016 * queue. Returns 1 if a request was found, 0 otherwise.
1018 static int as_dispatch_request(struct request_queue *q, int force)
1020 struct as_data *ad = q->elevator->elevator_data;
1021 const int reads = !list_empty(&ad->fifo_list[REQ_SYNC]);
1022 const int writes = !list_empty(&ad->fifo_list[REQ_ASYNC]);
1023 struct request *rq;
1025 if (unlikely(force)) {
1027 * Forced dispatch, accounting is useless. Reset
1028 * accounting states and dump fifo_lists. Note that
1029 * batch_data_dir is reset to REQ_SYNC to avoid
1030 * screwing write batch accounting as write batch
1031 * accounting occurs on W->R transition.
1033 int dispatched = 0;
1035 ad->batch_data_dir = REQ_SYNC;
1036 ad->changed_batch = 0;
1037 ad->new_batch = 0;
1039 while (ad->next_rq[REQ_SYNC]) {
1040 as_move_to_dispatch(ad, ad->next_rq[REQ_SYNC]);
1041 dispatched++;
1043 ad->last_check_fifo[REQ_SYNC] = jiffies;
1045 while (ad->next_rq[REQ_ASYNC]) {
1046 as_move_to_dispatch(ad, ad->next_rq[REQ_ASYNC]);
1047 dispatched++;
1049 ad->last_check_fifo[REQ_ASYNC] = jiffies;
1051 return dispatched;
1054 /* Signal that the write batch was uncontended, so we can't time it */
1055 if (ad->batch_data_dir == REQ_ASYNC && !reads) {
1056 if (ad->current_write_count == 0 || !writes)
1057 ad->write_batch_idled = 1;
1060 if (!(reads || writes)
1061 || ad->antic_status == ANTIC_WAIT_REQ
1062 || ad->antic_status == ANTIC_WAIT_NEXT
1063 || ad->changed_batch)
1064 return 0;
1066 if (!(reads && writes && as_batch_expired(ad))) {
1068 * batch is still running or no reads or no writes
1070 rq = ad->next_rq[ad->batch_data_dir];
1072 if (ad->batch_data_dir == REQ_SYNC && ad->antic_expire) {
1073 if (as_fifo_expired(ad, REQ_SYNC))
1074 goto fifo_expired;
1076 if (as_can_anticipate(ad, rq)) {
1077 as_antic_waitreq(ad);
1078 return 0;
1082 if (rq) {
1083 /* we have a "next request" */
1084 if (reads && !writes)
1085 ad->current_batch_expires =
1086 jiffies + ad->batch_expire[REQ_SYNC];
1087 goto dispatch_request;
1092 * at this point we are not running a batch. select the appropriate
1093 * data direction (read / write)
1096 if (reads) {
1097 BUG_ON(RB_EMPTY_ROOT(&ad->sort_list[REQ_SYNC]));
1099 if (writes && ad->batch_data_dir == REQ_SYNC)
1101 * Last batch was a read, switch to writes
1103 goto dispatch_writes;
1105 if (ad->batch_data_dir == REQ_ASYNC) {
1106 WARN_ON(ad->new_batch);
1107 ad->changed_batch = 1;
1109 ad->batch_data_dir = REQ_SYNC;
1110 rq = rq_entry_fifo(ad->fifo_list[REQ_SYNC].next);
1111 ad->last_check_fifo[ad->batch_data_dir] = jiffies;
1112 goto dispatch_request;
1116 * the last batch was a read
1119 if (writes) {
1120 dispatch_writes:
1121 BUG_ON(RB_EMPTY_ROOT(&ad->sort_list[REQ_ASYNC]));
1123 if (ad->batch_data_dir == REQ_SYNC) {
1124 ad->changed_batch = 1;
1127 * new_batch might be 1 when the queue runs out of
1128 * reads. A subsequent submission of a write might
1129 * cause a change of batch before the read is finished.
1131 ad->new_batch = 0;
1133 ad->batch_data_dir = REQ_ASYNC;
1134 ad->current_write_count = ad->write_batch_count;
1135 ad->write_batch_idled = 0;
1136 rq = rq_entry_fifo(ad->fifo_list[REQ_ASYNC].next);
1137 ad->last_check_fifo[REQ_ASYNC] = jiffies;
1138 goto dispatch_request;
1141 BUG();
1142 return 0;
1144 dispatch_request:
1146 * If a request has expired, service it.
1149 if (as_fifo_expired(ad, ad->batch_data_dir)) {
1150 fifo_expired:
1151 rq = rq_entry_fifo(ad->fifo_list[ad->batch_data_dir].next);
1154 if (ad->changed_batch) {
1155 WARN_ON(ad->new_batch);
1157 if (ad->nr_dispatched)
1158 return 0;
1160 if (ad->batch_data_dir == REQ_ASYNC)
1161 ad->current_batch_expires = jiffies +
1162 ad->batch_expire[REQ_ASYNC];
1163 else
1164 ad->new_batch = 1;
1166 ad->changed_batch = 0;
1170 * rq is the selected appropriate request.
1172 as_move_to_dispatch(ad, rq);
1174 return 1;
1178 * add rq to rbtree and fifo
1180 static void as_add_request(struct request_queue *q, struct request *rq)
1182 struct as_data *ad = q->elevator->elevator_data;
1183 int data_dir;
1185 RQ_SET_STATE(rq, AS_RQ_NEW);
1187 data_dir = rq_is_sync(rq);
1189 rq->elevator_private = as_get_io_context(q->node);
1191 if (RQ_IOC(rq)) {
1192 as_update_iohist(ad, RQ_IOC(rq)->aic, rq);
1193 atomic_inc(&RQ_IOC(rq)->aic->nr_queued);
1196 as_add_rq_rb(ad, rq);
1199 * set expire time and add to fifo list
1201 rq_set_fifo_time(rq, jiffies + ad->fifo_expire[data_dir]);
1202 list_add_tail(&rq->queuelist, &ad->fifo_list[data_dir]);
1204 as_update_rq(ad, rq); /* keep state machine up to date */
1205 RQ_SET_STATE(rq, AS_RQ_QUEUED);
1208 static void as_activate_request(struct request_queue *q, struct request *rq)
1210 WARN_ON(RQ_STATE(rq) != AS_RQ_DISPATCHED);
1211 RQ_SET_STATE(rq, AS_RQ_REMOVED);
1212 if (RQ_IOC(rq) && RQ_IOC(rq)->aic)
1213 atomic_dec(&RQ_IOC(rq)->aic->nr_dispatched);
1216 static void as_deactivate_request(struct request_queue *q, struct request *rq)
1218 WARN_ON(RQ_STATE(rq) != AS_RQ_REMOVED);
1219 RQ_SET_STATE(rq, AS_RQ_DISPATCHED);
1220 if (RQ_IOC(rq) && RQ_IOC(rq)->aic)
1221 atomic_inc(&RQ_IOC(rq)->aic->nr_dispatched);
1225 * as_queue_empty tells us if there are requests left in the device. It may
1226 * not be the case that a driver can get the next request even if the queue
1227 * is not empty - it is used in the block layer to check for plugging and
1228 * merging opportunities
1230 static int as_queue_empty(struct request_queue *q)
1232 struct as_data *ad = q->elevator->elevator_data;
1234 return list_empty(&ad->fifo_list[REQ_ASYNC])
1235 && list_empty(&ad->fifo_list[REQ_SYNC]);
1238 static int
1239 as_merge(struct request_queue *q, struct request **req, struct bio *bio)
1241 struct as_data *ad = q->elevator->elevator_data;
1242 sector_t rb_key = bio->bi_sector + bio_sectors(bio);
1243 struct request *__rq;
1246 * check for front merge
1248 __rq = elv_rb_find(&ad->sort_list[bio_data_dir(bio)], rb_key);
1249 if (__rq && elv_rq_merge_ok(__rq, bio)) {
1250 *req = __rq;
1251 return ELEVATOR_FRONT_MERGE;
1254 return ELEVATOR_NO_MERGE;
1257 static void as_merged_request(struct request_queue *q, struct request *req,
1258 int type)
1260 struct as_data *ad = q->elevator->elevator_data;
1263 * if the merge was a front merge, we need to reposition request
1265 if (type == ELEVATOR_FRONT_MERGE) {
1266 as_del_rq_rb(ad, req);
1267 as_add_rq_rb(ad, req);
1269 * Note! At this stage of this and the next function, our next
1270 * request may not be optimal - eg the request may have "grown"
1271 * behind the disk head. We currently don't bother adjusting.
1276 static void as_merged_requests(struct request_queue *q, struct request *req,
1277 struct request *next)
1280 * if next expires before rq, assign its expire time to arq
1281 * and move into next position (next will be deleted) in fifo
1283 if (!list_empty(&req->queuelist) && !list_empty(&next->queuelist)) {
1284 if (time_before(rq_fifo_time(next), rq_fifo_time(req))) {
1285 list_move(&req->queuelist, &next->queuelist);
1286 rq_set_fifo_time(req, rq_fifo_time(next));
1291 * kill knowledge of next, this one is a goner
1293 as_remove_queued_request(q, next);
1294 as_put_io_context(next);
1296 RQ_SET_STATE(next, AS_RQ_MERGED);
1300 * This is executed in a "deferred" process context, by kblockd. It calls the
1301 * driver's request_fn so the driver can submit that request.
1303 * IMPORTANT! This guy will reenter the elevator, so set up all queue global
1304 * state before calling, and don't rely on any state over calls.
1306 * FIXME! dispatch queue is not a queue at all!
1308 static void as_work_handler(struct work_struct *work)
1310 struct as_data *ad = container_of(work, struct as_data, antic_work);
1311 struct request_queue *q = ad->q;
1312 unsigned long flags;
1314 spin_lock_irqsave(q->queue_lock, flags);
1315 blk_start_queueing(q);
1316 spin_unlock_irqrestore(q->queue_lock, flags);
1319 static int as_may_queue(struct request_queue *q, int rw)
1321 int ret = ELV_MQUEUE_MAY;
1322 struct as_data *ad = q->elevator->elevator_data;
1323 struct io_context *ioc;
1324 if (ad->antic_status == ANTIC_WAIT_REQ ||
1325 ad->antic_status == ANTIC_WAIT_NEXT) {
1326 ioc = as_get_io_context(q->node);
1327 if (ad->io_context == ioc)
1328 ret = ELV_MQUEUE_MUST;
1329 put_io_context(ioc);
1332 return ret;
1335 static void as_exit_queue(elevator_t *e)
1337 struct as_data *ad = e->elevator_data;
1339 del_timer_sync(&ad->antic_timer);
1340 kblockd_flush_work(&ad->antic_work);
1342 BUG_ON(!list_empty(&ad->fifo_list[REQ_SYNC]));
1343 BUG_ON(!list_empty(&ad->fifo_list[REQ_ASYNC]));
1345 put_io_context(ad->io_context);
1346 kfree(ad);
1350 * initialize elevator private data (as_data).
1352 static void *as_init_queue(struct request_queue *q)
1354 struct as_data *ad;
1356 ad = kmalloc_node(sizeof(*ad), GFP_KERNEL | __GFP_ZERO, q->node);
1357 if (!ad)
1358 return NULL;
1360 ad->q = q; /* Identify what queue the data belongs to */
1362 /* anticipatory scheduling helpers */
1363 ad->antic_timer.function = as_antic_timeout;
1364 ad->antic_timer.data = (unsigned long)q;
1365 init_timer(&ad->antic_timer);
1366 INIT_WORK(&ad->antic_work, as_work_handler);
1368 INIT_LIST_HEAD(&ad->fifo_list[REQ_SYNC]);
1369 INIT_LIST_HEAD(&ad->fifo_list[REQ_ASYNC]);
1370 ad->sort_list[REQ_SYNC] = RB_ROOT;
1371 ad->sort_list[REQ_ASYNC] = RB_ROOT;
1372 ad->fifo_expire[REQ_SYNC] = default_read_expire;
1373 ad->fifo_expire[REQ_ASYNC] = default_write_expire;
1374 ad->antic_expire = default_antic_expire;
1375 ad->batch_expire[REQ_SYNC] = default_read_batch_expire;
1376 ad->batch_expire[REQ_ASYNC] = default_write_batch_expire;
1378 ad->current_batch_expires = jiffies + ad->batch_expire[REQ_SYNC];
1379 ad->write_batch_count = ad->batch_expire[REQ_ASYNC] / 10;
1380 if (ad->write_batch_count < 2)
1381 ad->write_batch_count = 2;
1383 return ad;
1387 * sysfs parts below
1390 static ssize_t
1391 as_var_show(unsigned int var, char *page)
1393 return sprintf(page, "%d\n", var);
1396 static ssize_t
1397 as_var_store(unsigned long *var, const char *page, size_t count)
1399 char *p = (char *) page;
1401 *var = simple_strtoul(p, &p, 10);
1402 return count;
1405 static ssize_t est_time_show(elevator_t *e, char *page)
1407 struct as_data *ad = e->elevator_data;
1408 int pos = 0;
1410 pos += sprintf(page+pos, "%lu %% exit probability\n",
1411 100*ad->exit_prob/256);
1412 pos += sprintf(page+pos, "%lu %% probability of exiting without a "
1413 "cooperating process submitting IO\n",
1414 100*ad->exit_no_coop/256);
1415 pos += sprintf(page+pos, "%lu ms new thinktime\n", ad->new_ttime_mean);
1416 pos += sprintf(page+pos, "%llu sectors new seek distance\n",
1417 (unsigned long long)ad->new_seek_mean);
1419 return pos;
1422 #define SHOW_FUNCTION(__FUNC, __VAR) \
1423 static ssize_t __FUNC(elevator_t *e, char *page) \
1425 struct as_data *ad = e->elevator_data; \
1426 return as_var_show(jiffies_to_msecs((__VAR)), (page)); \
1428 SHOW_FUNCTION(as_read_expire_show, ad->fifo_expire[REQ_SYNC]);
1429 SHOW_FUNCTION(as_write_expire_show, ad->fifo_expire[REQ_ASYNC]);
1430 SHOW_FUNCTION(as_antic_expire_show, ad->antic_expire);
1431 SHOW_FUNCTION(as_read_batch_expire_show, ad->batch_expire[REQ_SYNC]);
1432 SHOW_FUNCTION(as_write_batch_expire_show, ad->batch_expire[REQ_ASYNC]);
1433 #undef SHOW_FUNCTION
1435 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
1436 static ssize_t __FUNC(elevator_t *e, const char *page, size_t count) \
1438 struct as_data *ad = e->elevator_data; \
1439 int ret = as_var_store(__PTR, (page), count); \
1440 if (*(__PTR) < (MIN)) \
1441 *(__PTR) = (MIN); \
1442 else if (*(__PTR) > (MAX)) \
1443 *(__PTR) = (MAX); \
1444 *(__PTR) = msecs_to_jiffies(*(__PTR)); \
1445 return ret; \
1447 STORE_FUNCTION(as_read_expire_store, &ad->fifo_expire[REQ_SYNC], 0, INT_MAX);
1448 STORE_FUNCTION(as_write_expire_store, &ad->fifo_expire[REQ_ASYNC], 0, INT_MAX);
1449 STORE_FUNCTION(as_antic_expire_store, &ad->antic_expire, 0, INT_MAX);
1450 STORE_FUNCTION(as_read_batch_expire_store,
1451 &ad->batch_expire[REQ_SYNC], 0, INT_MAX);
1452 STORE_FUNCTION(as_write_batch_expire_store,
1453 &ad->batch_expire[REQ_ASYNC], 0, INT_MAX);
1454 #undef STORE_FUNCTION
1456 #define AS_ATTR(name) \
1457 __ATTR(name, S_IRUGO|S_IWUSR, as_##name##_show, as_##name##_store)
1459 static struct elv_fs_entry as_attrs[] = {
1460 __ATTR_RO(est_time),
1461 AS_ATTR(read_expire),
1462 AS_ATTR(write_expire),
1463 AS_ATTR(antic_expire),
1464 AS_ATTR(read_batch_expire),
1465 AS_ATTR(write_batch_expire),
1466 __ATTR_NULL
1469 static struct elevator_type iosched_as = {
1470 .ops = {
1471 .elevator_merge_fn = as_merge,
1472 .elevator_merged_fn = as_merged_request,
1473 .elevator_merge_req_fn = as_merged_requests,
1474 .elevator_dispatch_fn = as_dispatch_request,
1475 .elevator_add_req_fn = as_add_request,
1476 .elevator_activate_req_fn = as_activate_request,
1477 .elevator_deactivate_req_fn = as_deactivate_request,
1478 .elevator_queue_empty_fn = as_queue_empty,
1479 .elevator_completed_req_fn = as_completed_request,
1480 .elevator_former_req_fn = elv_rb_former_request,
1481 .elevator_latter_req_fn = elv_rb_latter_request,
1482 .elevator_may_queue_fn = as_may_queue,
1483 .elevator_init_fn = as_init_queue,
1484 .elevator_exit_fn = as_exit_queue,
1485 .trim = as_trim,
1488 .elevator_attrs = as_attrs,
1489 .elevator_name = "anticipatory",
1490 .elevator_owner = THIS_MODULE,
1493 static int __init as_init(void)
1495 elv_register(&iosched_as);
1497 return 0;
1500 static void __exit as_exit(void)
1502 DECLARE_COMPLETION_ONSTACK(all_gone);
1503 elv_unregister(&iosched_as);
1504 ioc_gone = &all_gone;
1505 /* ioc_gone's update must be visible before reading ioc_count */
1506 smp_wmb();
1507 if (elv_ioc_count_read(ioc_count))
1508 wait_for_completion(&all_gone);
1509 synchronize_rcu();
1512 module_init(as_init);
1513 module_exit(as_exit);
1515 MODULE_AUTHOR("Nick Piggin");
1516 MODULE_LICENSE("GPL");
1517 MODULE_DESCRIPTION("anticipatory IO scheduler");