ia64/linux-2.6.18-xen.hg

view block/ll_rw_blk.c @ 912:dd42cdb0ab89

[IA64] Build blktap2 driver by default in x86 builds.

add CONFIG_XEN_BLKDEV_TAP2=y to buildconfigs/linux-defconfig_xen_ia64.

Signed-off-by: Isaku Yamahata <yamahata@valinux.co.jp>
author Isaku Yamahata <yamahata@valinux.co.jp>
date Mon Jun 29 12:09:16 2009 +0900 (2009-06-29)
parents 7128fe32720e
children
line source
1 /*
2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
4 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au> - July2000
7 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
8 */
10 /*
11 * This handles all read/write requests to block devices
12 */
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/backing-dev.h>
16 #include <linux/bio.h>
17 #include <linux/blkdev.h>
18 #include <linux/highmem.h>
19 #include <linux/mm.h>
20 #include <linux/kernel_stat.h>
21 #include <linux/string.h>
22 #include <linux/init.h>
23 #include <linux/bootmem.h> /* for max_pfn/max_low_pfn */
24 #include <linux/completion.h>
25 #include <linux/slab.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28 #include <linux/interrupt.h>
29 #include <linux/cpu.h>
30 #include <linux/blktrace_api.h>
32 /*
33 * for max sense size
34 */
35 #include <scsi/scsi_cmnd.h>
37 static void blk_unplug_work(void *data);
38 static void blk_unplug_timeout(unsigned long data);
39 static void drive_stat_acct(struct request *rq, int nr_sectors, int new_io);
40 static void init_request_from_bio(struct request *req, struct bio *bio);
41 static int __make_request(request_queue_t *q, struct bio *bio);
43 /*
44 * For the allocated request tables
45 */
46 static kmem_cache_t *request_cachep;
48 /*
49 * For queue allocation
50 */
51 static kmem_cache_t *requestq_cachep;
53 /*
54 * For io context allocations
55 */
56 static kmem_cache_t *iocontext_cachep;
58 static wait_queue_head_t congestion_wqh[2] = {
59 __WAIT_QUEUE_HEAD_INITIALIZER(congestion_wqh[0]),
60 __WAIT_QUEUE_HEAD_INITIALIZER(congestion_wqh[1])
61 };
63 /*
64 * Controlling structure to kblockd
65 */
66 static struct workqueue_struct *kblockd_workqueue;
68 unsigned long blk_max_low_pfn, blk_max_pfn;
70 EXPORT_SYMBOL(blk_max_low_pfn);
71 EXPORT_SYMBOL(blk_max_pfn);
73 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
75 /* Amount of time in which a process may batch requests */
76 #define BLK_BATCH_TIME (HZ/50UL)
78 /* Number of requests a "batching" process may submit */
79 #define BLK_BATCH_REQ 32
81 /*
82 * Return the threshold (number of used requests) at which the queue is
83 * considered to be congested. It include a little hysteresis to keep the
84 * context switch rate down.
85 */
86 static inline int queue_congestion_on_threshold(struct request_queue *q)
87 {
88 return q->nr_congestion_on;
89 }
91 /*
92 * The threshold at which a queue is considered to be uncongested
93 */
94 static inline int queue_congestion_off_threshold(struct request_queue *q)
95 {
96 return q->nr_congestion_off;
97 }
99 static void blk_queue_congestion_threshold(struct request_queue *q)
100 {
101 int nr;
103 nr = q->nr_requests - (q->nr_requests / 8) + 1;
104 if (nr > q->nr_requests)
105 nr = q->nr_requests;
106 q->nr_congestion_on = nr;
108 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
109 if (nr < 1)
110 nr = 1;
111 q->nr_congestion_off = nr;
112 }
114 /*
115 * A queue has just exitted congestion. Note this in the global counter of
116 * congested queues, and wake up anyone who was waiting for requests to be
117 * put back.
118 */
119 static void clear_queue_congested(request_queue_t *q, int rw)
120 {
121 enum bdi_state bit;
122 wait_queue_head_t *wqh = &congestion_wqh[rw];
124 bit = (rw == WRITE) ? BDI_write_congested : BDI_read_congested;
125 clear_bit(bit, &q->backing_dev_info.state);
126 smp_mb__after_clear_bit();
127 if (waitqueue_active(wqh))
128 wake_up(wqh);
129 }
131 /*
132 * A queue has just entered congestion. Flag that in the queue's VM-visible
133 * state flags and increment the global gounter of congested queues.
134 */
135 static void set_queue_congested(request_queue_t *q, int rw)
136 {
137 enum bdi_state bit;
139 bit = (rw == WRITE) ? BDI_write_congested : BDI_read_congested;
140 set_bit(bit, &q->backing_dev_info.state);
141 }
143 /**
144 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
145 * @bdev: device
146 *
147 * Locates the passed device's request queue and returns the address of its
148 * backing_dev_info
149 *
150 * Will return NULL if the request queue cannot be located.
151 */
152 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
153 {
154 struct backing_dev_info *ret = NULL;
155 request_queue_t *q = bdev_get_queue(bdev);
157 if (q)
158 ret = &q->backing_dev_info;
159 return ret;
160 }
162 EXPORT_SYMBOL(blk_get_backing_dev_info);
164 void blk_queue_activity_fn(request_queue_t *q, activity_fn *fn, void *data)
165 {
166 q->activity_fn = fn;
167 q->activity_data = data;
168 }
170 EXPORT_SYMBOL(blk_queue_activity_fn);
172 /**
173 * blk_queue_prep_rq - set a prepare_request function for queue
174 * @q: queue
175 * @pfn: prepare_request function
176 *
177 * It's possible for a queue to register a prepare_request callback which
178 * is invoked before the request is handed to the request_fn. The goal of
179 * the function is to prepare a request for I/O, it can be used to build a
180 * cdb from the request data for instance.
181 *
182 */
183 void blk_queue_prep_rq(request_queue_t *q, prep_rq_fn *pfn)
184 {
185 q->prep_rq_fn = pfn;
186 }
188 EXPORT_SYMBOL(blk_queue_prep_rq);
190 /**
191 * blk_queue_merge_bvec - set a merge_bvec function for queue
192 * @q: queue
193 * @mbfn: merge_bvec_fn
194 *
195 * Usually queues have static limitations on the max sectors or segments that
196 * we can put in a request. Stacking drivers may have some settings that
197 * are dynamic, and thus we have to query the queue whether it is ok to
198 * add a new bio_vec to a bio at a given offset or not. If the block device
199 * has such limitations, it needs to register a merge_bvec_fn to control
200 * the size of bio's sent to it. Note that a block device *must* allow a
201 * single page to be added to an empty bio. The block device driver may want
202 * to use the bio_split() function to deal with these bio's. By default
203 * no merge_bvec_fn is defined for a queue, and only the fixed limits are
204 * honored.
205 */
206 void blk_queue_merge_bvec(request_queue_t *q, merge_bvec_fn *mbfn)
207 {
208 q->merge_bvec_fn = mbfn;
209 }
211 EXPORT_SYMBOL(blk_queue_merge_bvec);
213 void blk_queue_softirq_done(request_queue_t *q, softirq_done_fn *fn)
214 {
215 q->softirq_done_fn = fn;
216 }
218 EXPORT_SYMBOL(blk_queue_softirq_done);
220 /**
221 * blk_queue_make_request - define an alternate make_request function for a device
222 * @q: the request queue for the device to be affected
223 * @mfn: the alternate make_request function
224 *
225 * Description:
226 * The normal way for &struct bios to be passed to a device
227 * driver is for them to be collected into requests on a request
228 * queue, and then to allow the device driver to select requests
229 * off that queue when it is ready. This works well for many block
230 * devices. However some block devices (typically virtual devices
231 * such as md or lvm) do not benefit from the processing on the
232 * request queue, and are served best by having the requests passed
233 * directly to them. This can be achieved by providing a function
234 * to blk_queue_make_request().
235 *
236 * Caveat:
237 * The driver that does this *must* be able to deal appropriately
238 * with buffers in "highmemory". This can be accomplished by either calling
239 * __bio_kmap_atomic() to get a temporary kernel mapping, or by calling
240 * blk_queue_bounce() to create a buffer in normal memory.
241 **/
242 void blk_queue_make_request(request_queue_t * q, make_request_fn * mfn)
243 {
244 /*
245 * set defaults
246 */
247 q->nr_requests = BLKDEV_MAX_RQ;
248 blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
249 blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
250 q->make_request_fn = mfn;
251 q->backing_dev_info.ra_pages = (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
252 q->backing_dev_info.state = 0;
253 q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
254 blk_queue_max_sectors(q, SAFE_MAX_SECTORS);
255 blk_queue_hardsect_size(q, 512);
256 blk_queue_dma_alignment(q, 511);
257 blk_queue_congestion_threshold(q);
258 q->nr_batching = BLK_BATCH_REQ;
260 q->unplug_thresh = 4; /* hmm */
261 q->unplug_delay = (3 * HZ) / 1000; /* 3 milliseconds */
262 if (q->unplug_delay == 0)
263 q->unplug_delay = 1;
265 INIT_WORK(&q->unplug_work, blk_unplug_work, q);
267 q->unplug_timer.function = blk_unplug_timeout;
268 q->unplug_timer.data = (unsigned long)q;
270 /*
271 * by default assume old behaviour and bounce for any highmem page
272 */
273 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
275 blk_queue_activity_fn(q, NULL, NULL);
276 }
278 EXPORT_SYMBOL(blk_queue_make_request);
280 static inline void rq_init(request_queue_t *q, struct request *rq)
281 {
282 INIT_LIST_HEAD(&rq->queuelist);
283 INIT_LIST_HEAD(&rq->donelist);
285 rq->errors = 0;
286 rq->rq_status = RQ_ACTIVE;
287 rq->bio = rq->biotail = NULL;
288 rq->ioprio = 0;
289 rq->buffer = NULL;
290 rq->ref_count = 1;
291 rq->q = q;
292 rq->waiting = NULL;
293 rq->special = NULL;
294 rq->data_len = 0;
295 rq->data = NULL;
296 rq->nr_phys_segments = 0;
297 rq->sense = NULL;
298 rq->end_io = NULL;
299 rq->end_io_data = NULL;
300 rq->completion_data = NULL;
301 }
303 /**
304 * blk_queue_ordered - does this queue support ordered writes
305 * @q: the request queue
306 * @ordered: one of QUEUE_ORDERED_*
307 * @prepare_flush_fn: rq setup helper for cache flush ordered writes
308 *
309 * Description:
310 * For journalled file systems, doing ordered writes on a commit
311 * block instead of explicitly doing wait_on_buffer (which is bad
312 * for performance) can be a big win. Block drivers supporting this
313 * feature should call this function and indicate so.
314 *
315 **/
316 int blk_queue_ordered(request_queue_t *q, unsigned ordered,
317 prepare_flush_fn *prepare_flush_fn)
318 {
319 if (ordered & (QUEUE_ORDERED_PREFLUSH | QUEUE_ORDERED_POSTFLUSH) &&
320 prepare_flush_fn == NULL) {
321 printk(KERN_ERR "blk_queue_ordered: prepare_flush_fn required\n");
322 return -EINVAL;
323 }
325 if (ordered != QUEUE_ORDERED_NONE &&
326 ordered != QUEUE_ORDERED_DRAIN &&
327 ordered != QUEUE_ORDERED_DRAIN_FLUSH &&
328 ordered != QUEUE_ORDERED_DRAIN_FUA &&
329 ordered != QUEUE_ORDERED_TAG &&
330 ordered != QUEUE_ORDERED_TAG_FLUSH &&
331 ordered != QUEUE_ORDERED_TAG_FUA) {
332 printk(KERN_ERR "blk_queue_ordered: bad value %d\n", ordered);
333 return -EINVAL;
334 }
336 q->ordered = ordered;
337 q->next_ordered = ordered;
338 q->prepare_flush_fn = prepare_flush_fn;
340 return 0;
341 }
343 EXPORT_SYMBOL(blk_queue_ordered);
345 /**
346 * blk_queue_issue_flush_fn - set function for issuing a flush
347 * @q: the request queue
348 * @iff: the function to be called issuing the flush
349 *
350 * Description:
351 * If a driver supports issuing a flush command, the support is notified
352 * to the block layer by defining it through this call.
353 *
354 **/
355 void blk_queue_issue_flush_fn(request_queue_t *q, issue_flush_fn *iff)
356 {
357 q->issue_flush_fn = iff;
358 }
360 EXPORT_SYMBOL(blk_queue_issue_flush_fn);
362 /*
363 * Cache flushing for ordered writes handling
364 */
365 inline unsigned blk_ordered_cur_seq(request_queue_t *q)
366 {
367 if (!q->ordseq)
368 return 0;
369 return 1 << ffz(q->ordseq);
370 }
372 unsigned blk_ordered_req_seq(struct request *rq)
373 {
374 request_queue_t *q = rq->q;
376 BUG_ON(q->ordseq == 0);
378 if (rq == &q->pre_flush_rq)
379 return QUEUE_ORDSEQ_PREFLUSH;
380 if (rq == &q->bar_rq)
381 return QUEUE_ORDSEQ_BAR;
382 if (rq == &q->post_flush_rq)
383 return QUEUE_ORDSEQ_POSTFLUSH;
385 if ((rq->flags & REQ_ORDERED_COLOR) ==
386 (q->orig_bar_rq->flags & REQ_ORDERED_COLOR))
387 return QUEUE_ORDSEQ_DRAIN;
388 else
389 return QUEUE_ORDSEQ_DONE;
390 }
392 void blk_ordered_complete_seq(request_queue_t *q, unsigned seq, int error)
393 {
394 struct request *rq;
395 int uptodate;
397 if (error && !q->orderr)
398 q->orderr = error;
400 BUG_ON(q->ordseq & seq);
401 q->ordseq |= seq;
403 if (blk_ordered_cur_seq(q) != QUEUE_ORDSEQ_DONE)
404 return;
406 /*
407 * Okay, sequence complete.
408 */
409 rq = q->orig_bar_rq;
410 uptodate = q->orderr ? q->orderr : 1;
412 q->ordseq = 0;
414 end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
415 end_that_request_last(rq, uptodate);
416 }
418 static void pre_flush_end_io(struct request *rq, int error)
419 {
420 elv_completed_request(rq->q, rq);
421 blk_ordered_complete_seq(rq->q, QUEUE_ORDSEQ_PREFLUSH, error);
422 }
424 static void bar_end_io(struct request *rq, int error)
425 {
426 elv_completed_request(rq->q, rq);
427 blk_ordered_complete_seq(rq->q, QUEUE_ORDSEQ_BAR, error);
428 }
430 static void post_flush_end_io(struct request *rq, int error)
431 {
432 elv_completed_request(rq->q, rq);
433 blk_ordered_complete_seq(rq->q, QUEUE_ORDSEQ_POSTFLUSH, error);
434 }
436 static void queue_flush(request_queue_t *q, unsigned which)
437 {
438 struct request *rq;
439 rq_end_io_fn *end_io;
441 if (which == QUEUE_ORDERED_PREFLUSH) {
442 rq = &q->pre_flush_rq;
443 end_io = pre_flush_end_io;
444 } else {
445 rq = &q->post_flush_rq;
446 end_io = post_flush_end_io;
447 }
449 rq_init(q, rq);
450 rq->flags = REQ_HARDBARRIER;
451 rq->elevator_private = NULL;
452 rq->rq_disk = q->bar_rq.rq_disk;
453 rq->rl = NULL;
454 rq->end_io = end_io;
455 q->prepare_flush_fn(q, rq);
457 elv_insert(q, rq, ELEVATOR_INSERT_FRONT);
458 }
460 static inline struct request *start_ordered(request_queue_t *q,
461 struct request *rq)
462 {
463 q->bi_size = 0;
464 q->orderr = 0;
465 q->ordered = q->next_ordered;
466 q->ordseq |= QUEUE_ORDSEQ_STARTED;
468 /*
469 * Prep proxy barrier request.
470 */
471 blkdev_dequeue_request(rq);
472 q->orig_bar_rq = rq;
473 rq = &q->bar_rq;
474 rq_init(q, rq);
475 rq->flags = bio_data_dir(q->orig_bar_rq->bio);
476 rq->flags |= q->ordered & QUEUE_ORDERED_FUA ? REQ_FUA : 0;
477 rq->elevator_private = NULL;
478 rq->rl = NULL;
479 init_request_from_bio(rq, q->orig_bar_rq->bio);
480 rq->end_io = bar_end_io;
482 /*
483 * Queue ordered sequence. As we stack them at the head, we
484 * need to queue in reverse order. Note that we rely on that
485 * no fs request uses ELEVATOR_INSERT_FRONT and thus no fs
486 * request gets inbetween ordered sequence. If this request is
487 * an empty barrier, we don't need to do a postflush ever since
488 * there will be no data written between the pre and post flush.
489 * Hence a single flush will suffice.
490 */
491 if ((q->ordered & QUEUE_ORDERED_POSTFLUSH) && !blk_empty_barrier(rq))
492 queue_flush(q, QUEUE_ORDERED_POSTFLUSH);
493 else
494 q->ordseq |= QUEUE_ORDSEQ_POSTFLUSH;
496 elv_insert(q, rq, ELEVATOR_INSERT_FRONT);
498 if (q->ordered & QUEUE_ORDERED_PREFLUSH) {
499 queue_flush(q, QUEUE_ORDERED_PREFLUSH);
500 rq = &q->pre_flush_rq;
501 } else
502 q->ordseq |= QUEUE_ORDSEQ_PREFLUSH;
504 if ((q->ordered & QUEUE_ORDERED_TAG) || q->in_flight == 0)
505 q->ordseq |= QUEUE_ORDSEQ_DRAIN;
506 else
507 rq = NULL;
509 return rq;
510 }
512 int blk_do_ordered(request_queue_t *q, struct request **rqp)
513 {
514 struct request *rq = *rqp;
515 int is_barrier = blk_fs_request(rq) && blk_barrier_rq(rq);
517 if (!q->ordseq) {
518 if (!is_barrier)
519 return 1;
521 if (q->next_ordered != QUEUE_ORDERED_NONE) {
522 *rqp = start_ordered(q, rq);
523 return 1;
524 } else {
525 /*
526 * This can happen when the queue switches to
527 * ORDERED_NONE while this request is on it.
528 */
529 blkdev_dequeue_request(rq);
530 end_that_request_first(rq, -EOPNOTSUPP,
531 rq->hard_nr_sectors);
532 end_that_request_last(rq, -EOPNOTSUPP);
533 *rqp = NULL;
534 return 0;
535 }
536 }
538 /*
539 * Ordered sequence in progress
540 */
542 /* Special requests are not subject to ordering rules. */
543 if (!blk_fs_request(rq) &&
544 rq != &q->pre_flush_rq && rq != &q->post_flush_rq)
545 return 1;
547 if (q->ordered & QUEUE_ORDERED_TAG) {
548 /* Ordered by tag. Blocking the next barrier is enough. */
549 if (is_barrier && rq != &q->bar_rq)
550 *rqp = NULL;
551 } else {
552 /* Ordered by draining. Wait for turn. */
553 WARN_ON(blk_ordered_req_seq(rq) < blk_ordered_cur_seq(q));
554 if (blk_ordered_req_seq(rq) > blk_ordered_cur_seq(q))
555 *rqp = NULL;
556 }
558 return 1;
559 }
561 static int flush_dry_bio_endio(struct bio *bio, unsigned int bytes, int error)
562 {
563 request_queue_t *q = bio->bi_private;
564 struct bio_vec *bvec;
565 int i;
567 /*
568 * This is dry run, restore bio_sector and size. We'll finish
569 * this request again with the original bi_end_io after an
570 * error occurs or post flush is complete.
571 */
572 q->bi_size += bytes;
574 if (bio->bi_size)
575 return 1;
577 /* Rewind bvec's */
578 bio->bi_idx = 0;
579 bio_for_each_segment(bvec, bio, i) {
580 bvec->bv_len += bvec->bv_offset;
581 bvec->bv_offset = 0;
582 }
584 /* Reset bio */
585 set_bit(BIO_UPTODATE, &bio->bi_flags);
586 bio->bi_size = q->bi_size;
587 bio->bi_sector -= (q->bi_size >> 9);
588 q->bi_size = 0;
590 return 0;
591 }
593 static inline int ordered_bio_endio(struct request *rq, struct bio *bio,
594 unsigned int nbytes, int error)
595 {
596 request_queue_t *q = rq->q;
597 bio_end_io_t *endio;
598 void *private;
600 if (&q->bar_rq != rq)
601 return 0;
603 /*
604 * Okay, this is the barrier request in progress, dry finish it.
605 */
606 if (error && !q->orderr)
607 q->orderr = error;
609 endio = bio->bi_end_io;
610 private = bio->bi_private;
611 bio->bi_end_io = flush_dry_bio_endio;
612 bio->bi_private = q;
614 bio_endio(bio, nbytes, error);
616 bio->bi_end_io = endio;
617 bio->bi_private = private;
619 return 1;
620 }
622 /**
623 * blk_queue_bounce_limit - set bounce buffer limit for queue
624 * @q: the request queue for the device
625 * @dma_addr: bus address limit
626 *
627 * Description:
628 * Different hardware can have different requirements as to what pages
629 * it can do I/O directly to. A low level driver can call
630 * blk_queue_bounce_limit to have lower memory pages allocated as bounce
631 * buffers for doing I/O to pages residing above @page.
632 **/
633 void blk_queue_bounce_limit(request_queue_t *q, u64 dma_addr)
634 {
635 unsigned long bounce_pfn = dma_addr >> PAGE_SHIFT;
636 int dma = 0;
638 q->bounce_gfp = GFP_NOIO;
639 #if BITS_PER_LONG == 64
640 /* Assume anything <= 4GB can be handled by IOMMU.
641 Actually some IOMMUs can handle everything, but I don't
642 know of a way to test this here. */
643 if (bounce_pfn < (min_t(u64,0xffffffff,BLK_BOUNCE_HIGH) >> PAGE_SHIFT))
644 dma = 1;
645 q->bounce_pfn = max_low_pfn;
646 #else
647 if (bounce_pfn < blk_max_low_pfn)
648 dma = 1;
649 q->bounce_pfn = bounce_pfn;
650 #endif
651 if (dma) {
652 init_emergency_isa_pool();
653 q->bounce_gfp = GFP_NOIO | GFP_DMA;
654 q->bounce_pfn = bounce_pfn;
655 }
656 }
658 EXPORT_SYMBOL(blk_queue_bounce_limit);
660 /**
661 * blk_queue_max_sectors - set max sectors for a request for this queue
662 * @q: the request queue for the device
663 * @max_sectors: max sectors in the usual 512b unit
664 *
665 * Description:
666 * Enables a low level driver to set an upper limit on the size of
667 * received requests.
668 **/
669 void blk_queue_max_sectors(request_queue_t *q, unsigned int max_sectors)
670 {
671 if ((max_sectors << 9) < PAGE_CACHE_SIZE) {
672 max_sectors = 1 << (PAGE_CACHE_SHIFT - 9);
673 printk("%s: set to minimum %d\n", __FUNCTION__, max_sectors);
674 }
676 if (BLK_DEF_MAX_SECTORS > max_sectors)
677 q->max_hw_sectors = q->max_sectors = max_sectors;
678 else {
679 q->max_sectors = BLK_DEF_MAX_SECTORS;
680 q->max_hw_sectors = max_sectors;
681 }
682 }
684 EXPORT_SYMBOL(blk_queue_max_sectors);
686 /**
687 * blk_queue_max_phys_segments - set max phys segments for a request for this queue
688 * @q: the request queue for the device
689 * @max_segments: max number of segments
690 *
691 * Description:
692 * Enables a low level driver to set an upper limit on the number of
693 * physical data segments in a request. This would be the largest sized
694 * scatter list the driver could handle.
695 **/
696 void blk_queue_max_phys_segments(request_queue_t *q, unsigned short max_segments)
697 {
698 if (!max_segments) {
699 max_segments = 1;
700 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
701 }
703 q->max_phys_segments = max_segments;
704 }
706 EXPORT_SYMBOL(blk_queue_max_phys_segments);
708 /**
709 * blk_queue_max_hw_segments - set max hw segments for a request for this queue
710 * @q: the request queue for the device
711 * @max_segments: max number of segments
712 *
713 * Description:
714 * Enables a low level driver to set an upper limit on the number of
715 * hw data segments in a request. This would be the largest number of
716 * address/length pairs the host adapter can actually give as once
717 * to the device.
718 **/
719 void blk_queue_max_hw_segments(request_queue_t *q, unsigned short max_segments)
720 {
721 if (!max_segments) {
722 max_segments = 1;
723 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
724 }
726 q->max_hw_segments = max_segments;
727 }
729 EXPORT_SYMBOL(blk_queue_max_hw_segments);
731 /**
732 * blk_queue_max_segment_size - set max segment size for blk_rq_map_sg
733 * @q: the request queue for the device
734 * @max_size: max size of segment in bytes
735 *
736 * Description:
737 * Enables a low level driver to set an upper limit on the size of a
738 * coalesced segment
739 **/
740 void blk_queue_max_segment_size(request_queue_t *q, unsigned int max_size)
741 {
742 if (max_size < PAGE_CACHE_SIZE) {
743 max_size = PAGE_CACHE_SIZE;
744 printk("%s: set to minimum %d\n", __FUNCTION__, max_size);
745 }
747 q->max_segment_size = max_size;
748 }
750 EXPORT_SYMBOL(blk_queue_max_segment_size);
752 /**
753 * blk_queue_hardsect_size - set hardware sector size for the queue
754 * @q: the request queue for the device
755 * @size: the hardware sector size, in bytes
756 *
757 * Description:
758 * This should typically be set to the lowest possible sector size
759 * that the hardware can operate on (possible without reverting to
760 * even internal read-modify-write operations). Usually the default
761 * of 512 covers most hardware.
762 **/
763 void blk_queue_hardsect_size(request_queue_t *q, unsigned short size)
764 {
765 q->hardsect_size = size;
766 }
768 EXPORT_SYMBOL(blk_queue_hardsect_size);
770 /*
771 * Returns the minimum that is _not_ zero, unless both are zero.
772 */
773 #define min_not_zero(l, r) (l == 0) ? r : ((r == 0) ? l : min(l, r))
775 /**
776 * blk_queue_stack_limits - inherit underlying queue limits for stacked drivers
777 * @t: the stacking driver (top)
778 * @b: the underlying device (bottom)
779 **/
780 void blk_queue_stack_limits(request_queue_t *t, request_queue_t *b)
781 {
782 /* zero is "infinity" */
783 t->max_sectors = min_not_zero(t->max_sectors,b->max_sectors);
784 t->max_hw_sectors = min_not_zero(t->max_hw_sectors,b->max_hw_sectors);
786 t->max_phys_segments = min(t->max_phys_segments,b->max_phys_segments);
787 t->max_hw_segments = min(t->max_hw_segments,b->max_hw_segments);
788 t->max_segment_size = min(t->max_segment_size,b->max_segment_size);
789 t->hardsect_size = max(t->hardsect_size,b->hardsect_size);
790 if (!test_bit(QUEUE_FLAG_CLUSTER, &b->queue_flags))
791 clear_bit(QUEUE_FLAG_CLUSTER, &t->queue_flags);
792 }
794 EXPORT_SYMBOL(blk_queue_stack_limits);
796 /**
797 * blk_queue_segment_boundary - set boundary rules for segment merging
798 * @q: the request queue for the device
799 * @mask: the memory boundary mask
800 **/
801 void blk_queue_segment_boundary(request_queue_t *q, unsigned long mask)
802 {
803 if (mask < PAGE_CACHE_SIZE - 1) {
804 mask = PAGE_CACHE_SIZE - 1;
805 printk("%s: set to minimum %lx\n", __FUNCTION__, mask);
806 }
808 q->seg_boundary_mask = mask;
809 }
811 EXPORT_SYMBOL(blk_queue_segment_boundary);
813 /**
814 * blk_queue_dma_alignment - set dma length and memory alignment
815 * @q: the request queue for the device
816 * @mask: alignment mask
817 *
818 * description:
819 * set required memory and length aligment for direct dma transactions.
820 * this is used when buiding direct io requests for the queue.
821 *
822 **/
823 void blk_queue_dma_alignment(request_queue_t *q, int mask)
824 {
825 q->dma_alignment = mask;
826 }
828 EXPORT_SYMBOL(blk_queue_dma_alignment);
830 /**
831 * blk_queue_find_tag - find a request by its tag and queue
832 * @q: The request queue for the device
833 * @tag: The tag of the request
834 *
835 * Notes:
836 * Should be used when a device returns a tag and you want to match
837 * it with a request.
838 *
839 * no locks need be held.
840 **/
841 struct request *blk_queue_find_tag(request_queue_t *q, int tag)
842 {
843 struct blk_queue_tag *bqt = q->queue_tags;
845 if (unlikely(bqt == NULL || tag >= bqt->real_max_depth))
846 return NULL;
848 return bqt->tag_index[tag];
849 }
851 EXPORT_SYMBOL(blk_queue_find_tag);
853 /**
854 * __blk_queue_free_tags - release tag maintenance info
855 * @q: the request queue for the device
856 *
857 * Notes:
858 * blk_cleanup_queue() will take care of calling this function, if tagging
859 * has been used. So there's no need to call this directly.
860 **/
861 static void __blk_queue_free_tags(request_queue_t *q)
862 {
863 struct blk_queue_tag *bqt = q->queue_tags;
865 if (!bqt)
866 return;
868 if (atomic_dec_and_test(&bqt->refcnt)) {
869 BUG_ON(bqt->busy);
870 BUG_ON(!list_empty(&bqt->busy_list));
872 kfree(bqt->tag_index);
873 bqt->tag_index = NULL;
875 kfree(bqt->tag_map);
876 bqt->tag_map = NULL;
878 kfree(bqt);
879 }
881 q->queue_tags = NULL;
882 q->queue_flags &= ~(1 << QUEUE_FLAG_QUEUED);
883 }
885 /**
886 * blk_queue_free_tags - release tag maintenance info
887 * @q: the request queue for the device
888 *
889 * Notes:
890 * This is used to disabled tagged queuing to a device, yet leave
891 * queue in function.
892 **/
893 void blk_queue_free_tags(request_queue_t *q)
894 {
895 clear_bit(QUEUE_FLAG_QUEUED, &q->queue_flags);
896 }
898 EXPORT_SYMBOL(blk_queue_free_tags);
900 static int
901 init_tag_map(request_queue_t *q, struct blk_queue_tag *tags, int depth)
902 {
903 struct request **tag_index;
904 unsigned long *tag_map;
905 int nr_ulongs;
907 if (depth > q->nr_requests * 2) {
908 depth = q->nr_requests * 2;
909 printk(KERN_ERR "%s: adjusted depth to %d\n",
910 __FUNCTION__, depth);
911 }
913 tag_index = kzalloc(depth * sizeof(struct request *), GFP_ATOMIC);
914 if (!tag_index)
915 goto fail;
917 nr_ulongs = ALIGN(depth, BITS_PER_LONG) / BITS_PER_LONG;
918 tag_map = kzalloc(nr_ulongs * sizeof(unsigned long), GFP_ATOMIC);
919 if (!tag_map)
920 goto fail;
922 tags->real_max_depth = depth;
923 tags->max_depth = depth;
924 tags->tag_index = tag_index;
925 tags->tag_map = tag_map;
927 return 0;
928 fail:
929 kfree(tag_index);
930 return -ENOMEM;
931 }
933 /**
934 * blk_queue_init_tags - initialize the queue tag info
935 * @q: the request queue for the device
936 * @depth: the maximum queue depth supported
937 * @tags: the tag to use
938 **/
939 int blk_queue_init_tags(request_queue_t *q, int depth,
940 struct blk_queue_tag *tags)
941 {
942 int rc;
944 BUG_ON(tags && q->queue_tags && tags != q->queue_tags);
946 if (!tags && !q->queue_tags) {
947 tags = kmalloc(sizeof(struct blk_queue_tag), GFP_ATOMIC);
948 if (!tags)
949 goto fail;
951 if (init_tag_map(q, tags, depth))
952 goto fail;
954 INIT_LIST_HEAD(&tags->busy_list);
955 tags->busy = 0;
956 atomic_set(&tags->refcnt, 1);
957 } else if (q->queue_tags) {
958 if ((rc = blk_queue_resize_tags(q, depth)))
959 return rc;
960 set_bit(QUEUE_FLAG_QUEUED, &q->queue_flags);
961 return 0;
962 } else
963 atomic_inc(&tags->refcnt);
965 /*
966 * assign it, all done
967 */
968 q->queue_tags = tags;
969 q->queue_flags |= (1 << QUEUE_FLAG_QUEUED);
970 return 0;
971 fail:
972 kfree(tags);
973 return -ENOMEM;
974 }
976 EXPORT_SYMBOL(blk_queue_init_tags);
978 /**
979 * blk_queue_resize_tags - change the queueing depth
980 * @q: the request queue for the device
981 * @new_depth: the new max command queueing depth
982 *
983 * Notes:
984 * Must be called with the queue lock held.
985 **/
986 int blk_queue_resize_tags(request_queue_t *q, int new_depth)
987 {
988 struct blk_queue_tag *bqt = q->queue_tags;
989 struct request **tag_index;
990 unsigned long *tag_map;
991 int max_depth, nr_ulongs;
993 if (!bqt)
994 return -ENXIO;
996 /*
997 * if we already have large enough real_max_depth. just
998 * adjust max_depth. *NOTE* as requests with tag value
999 * between new_depth and real_max_depth can be in-flight, tag
1000 * map can not be shrunk blindly here.
1001 */
1002 if (new_depth <= bqt->real_max_depth) {
1003 bqt->max_depth = new_depth;
1004 return 0;
1007 /*
1008 * save the old state info, so we can copy it back
1009 */
1010 tag_index = bqt->tag_index;
1011 tag_map = bqt->tag_map;
1012 max_depth = bqt->real_max_depth;
1014 if (init_tag_map(q, bqt, new_depth))
1015 return -ENOMEM;
1017 memcpy(bqt->tag_index, tag_index, max_depth * sizeof(struct request *));
1018 nr_ulongs = ALIGN(max_depth, BITS_PER_LONG) / BITS_PER_LONG;
1019 memcpy(bqt->tag_map, tag_map, nr_ulongs * sizeof(unsigned long));
1021 kfree(tag_index);
1022 kfree(tag_map);
1023 return 0;
1026 EXPORT_SYMBOL(blk_queue_resize_tags);
1028 /**
1029 * blk_queue_end_tag - end tag operations for a request
1030 * @q: the request queue for the device
1031 * @rq: the request that has completed
1033 * Description:
1034 * Typically called when end_that_request_first() returns 0, meaning
1035 * all transfers have been done for a request. It's important to call
1036 * this function before end_that_request_last(), as that will put the
1037 * request back on the free list thus corrupting the internal tag list.
1039 * Notes:
1040 * queue lock must be held.
1041 **/
1042 void blk_queue_end_tag(request_queue_t *q, struct request *rq)
1044 struct blk_queue_tag *bqt = q->queue_tags;
1045 int tag = rq->tag;
1047 BUG_ON(tag == -1);
1049 if (unlikely(tag >= bqt->real_max_depth))
1050 /*
1051 * This can happen after tag depth has been reduced.
1052 * FIXME: how about a warning or info message here?
1053 */
1054 return;
1056 if (unlikely(!__test_and_clear_bit(tag, bqt->tag_map))) {
1057 printk(KERN_ERR "%s: attempt to clear non-busy tag (%d)\n",
1058 __FUNCTION__, tag);
1059 return;
1062 list_del_init(&rq->queuelist);
1063 rq->flags &= ~REQ_QUEUED;
1064 rq->tag = -1;
1066 if (unlikely(bqt->tag_index[tag] == NULL))
1067 printk(KERN_ERR "%s: tag %d is missing\n",
1068 __FUNCTION__, tag);
1070 bqt->tag_index[tag] = NULL;
1071 bqt->busy--;
1074 EXPORT_SYMBOL(blk_queue_end_tag);
1076 /**
1077 * blk_queue_start_tag - find a free tag and assign it
1078 * @q: the request queue for the device
1079 * @rq: the block request that needs tagging
1081 * Description:
1082 * This can either be used as a stand-alone helper, or possibly be
1083 * assigned as the queue &prep_rq_fn (in which case &struct request
1084 * automagically gets a tag assigned). Note that this function
1085 * assumes that any type of request can be queued! if this is not
1086 * true for your device, you must check the request type before
1087 * calling this function. The request will also be removed from
1088 * the request queue, so it's the drivers responsibility to readd
1089 * it if it should need to be restarted for some reason.
1091 * Notes:
1092 * queue lock must be held.
1093 **/
1094 int blk_queue_start_tag(request_queue_t *q, struct request *rq)
1096 struct blk_queue_tag *bqt = q->queue_tags;
1097 int tag;
1099 if (unlikely((rq->flags & REQ_QUEUED))) {
1100 printk(KERN_ERR
1101 "%s: request %p for device [%s] already tagged %d",
1102 __FUNCTION__, rq,
1103 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->tag);
1104 BUG();
1107 tag = find_first_zero_bit(bqt->tag_map, bqt->max_depth);
1108 if (tag >= bqt->max_depth)
1109 return 1;
1111 __set_bit(tag, bqt->tag_map);
1113 rq->flags |= REQ_QUEUED;
1114 rq->tag = tag;
1115 bqt->tag_index[tag] = rq;
1116 blkdev_dequeue_request(rq);
1117 list_add(&rq->queuelist, &bqt->busy_list);
1118 bqt->busy++;
1119 return 0;
1122 EXPORT_SYMBOL(blk_queue_start_tag);
1124 /**
1125 * blk_queue_invalidate_tags - invalidate all pending tags
1126 * @q: the request queue for the device
1128 * Description:
1129 * Hardware conditions may dictate a need to stop all pending requests.
1130 * In this case, we will safely clear the block side of the tag queue and
1131 * readd all requests to the request queue in the right order.
1133 * Notes:
1134 * queue lock must be held.
1135 **/
1136 void blk_queue_invalidate_tags(request_queue_t *q)
1138 struct blk_queue_tag *bqt = q->queue_tags;
1139 struct list_head *tmp, *n;
1140 struct request *rq;
1142 list_for_each_safe(tmp, n, &bqt->busy_list) {
1143 rq = list_entry_rq(tmp);
1145 if (rq->tag == -1) {
1146 printk(KERN_ERR
1147 "%s: bad tag found on list\n", __FUNCTION__);
1148 list_del_init(&rq->queuelist);
1149 rq->flags &= ~REQ_QUEUED;
1150 } else
1151 blk_queue_end_tag(q, rq);
1153 rq->flags &= ~REQ_STARTED;
1154 __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
1158 EXPORT_SYMBOL(blk_queue_invalidate_tags);
1160 static const char * const rq_flags[] = {
1161 "REQ_RW",
1162 "REQ_FAILFAST",
1163 "REQ_SORTED",
1164 "REQ_SOFTBARRIER",
1165 "REQ_HARDBARRIER",
1166 "REQ_FUA",
1167 "REQ_CMD",
1168 "REQ_NOMERGE",
1169 "REQ_STARTED",
1170 "REQ_DONTPREP",
1171 "REQ_QUEUED",
1172 "REQ_ELVPRIV",
1173 "REQ_PC",
1174 "REQ_BLOCK_PC",
1175 "REQ_SENSE",
1176 "REQ_FAILED",
1177 "REQ_QUIET",
1178 "REQ_SPECIAL",
1179 "REQ_DRIVE_CMD",
1180 "REQ_DRIVE_TASK",
1181 "REQ_DRIVE_TASKFILE",
1182 "REQ_PREEMPT",
1183 "REQ_PM_SUSPEND",
1184 "REQ_PM_RESUME",
1185 "REQ_PM_SHUTDOWN",
1186 "REQ_ORDERED_COLOR",
1187 };
1189 void blk_dump_rq_flags(struct request *rq, char *msg)
1191 int bit;
1193 printk("%s: dev %s: flags = ", msg,
1194 rq->rq_disk ? rq->rq_disk->disk_name : "?");
1195 bit = 0;
1196 do {
1197 if (rq->flags & (1 << bit))
1198 printk("%s ", rq_flags[bit]);
1199 bit++;
1200 } while (bit < __REQ_NR_BITS);
1202 printk("\nsector %llu, nr/cnr %lu/%u\n", (unsigned long long)rq->sector,
1203 rq->nr_sectors,
1204 rq->current_nr_sectors);
1205 printk("bio %p, biotail %p, buffer %p, data %p, len %u\n", rq->bio, rq->biotail, rq->buffer, rq->data, rq->data_len);
1207 if (rq->flags & (REQ_BLOCK_PC | REQ_PC)) {
1208 printk("cdb: ");
1209 for (bit = 0; bit < sizeof(rq->cmd); bit++)
1210 printk("%02x ", rq->cmd[bit]);
1211 printk("\n");
1215 EXPORT_SYMBOL(blk_dump_rq_flags);
1217 void blk_recount_segments(request_queue_t *q, struct bio *bio)
1219 struct bio_vec *bv, *bvprv = NULL;
1220 int i, nr_phys_segs, nr_hw_segs, seg_size, hw_seg_size, cluster;
1221 int high, highprv = 1;
1223 if (unlikely(!bio->bi_io_vec))
1224 return;
1226 cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
1227 hw_seg_size = seg_size = nr_phys_segs = nr_hw_segs = 0;
1228 bio_for_each_segment(bv, bio, i) {
1229 /*
1230 * the trick here is making sure that a high page is never
1231 * considered part of another segment, since that might
1232 * change with the bounce page.
1233 */
1234 high = page_to_pfn(bv->bv_page) >= q->bounce_pfn;
1235 if (high || highprv)
1236 goto new_hw_segment;
1237 if (cluster) {
1238 if (seg_size + bv->bv_len > q->max_segment_size)
1239 goto new_segment;
1240 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bv))
1241 goto new_segment;
1242 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bv))
1243 goto new_segment;
1244 if (BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len))
1245 goto new_hw_segment;
1247 seg_size += bv->bv_len;
1248 hw_seg_size += bv->bv_len;
1249 bvprv = bv;
1250 continue;
1252 new_segment:
1253 if (BIOVEC_VIRT_MERGEABLE(bvprv, bv) &&
1254 !BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len)) {
1255 hw_seg_size += bv->bv_len;
1256 } else {
1257 new_hw_segment:
1258 if (hw_seg_size > bio->bi_hw_front_size)
1259 bio->bi_hw_front_size = hw_seg_size;
1260 hw_seg_size = BIOVEC_VIRT_START_SIZE(bv) + bv->bv_len;
1261 nr_hw_segs++;
1264 nr_phys_segs++;
1265 bvprv = bv;
1266 seg_size = bv->bv_len;
1267 highprv = high;
1269 if (hw_seg_size > bio->bi_hw_back_size)
1270 bio->bi_hw_back_size = hw_seg_size;
1271 if (nr_hw_segs == 1 && hw_seg_size > bio->bi_hw_front_size)
1272 bio->bi_hw_front_size = hw_seg_size;
1273 bio->bi_phys_segments = nr_phys_segs;
1274 bio->bi_hw_segments = nr_hw_segs;
1275 bio->bi_flags |= (1 << BIO_SEG_VALID);
1279 static int blk_phys_contig_segment(request_queue_t *q, struct bio *bio,
1280 struct bio *nxt)
1282 if (!(q->queue_flags & (1 << QUEUE_FLAG_CLUSTER)))
1283 return 0;
1285 if (!BIOVEC_PHYS_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)))
1286 return 0;
1287 if (bio->bi_size + nxt->bi_size > q->max_segment_size)
1288 return 0;
1290 /*
1291 * bio and nxt are contigous in memory, check if the queue allows
1292 * these two to be merged into one
1293 */
1294 if (BIO_SEG_BOUNDARY(q, bio, nxt))
1295 return 1;
1297 return 0;
1300 static int blk_hw_contig_segment(request_queue_t *q, struct bio *bio,
1301 struct bio *nxt)
1303 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1304 blk_recount_segments(q, bio);
1305 if (unlikely(!bio_flagged(nxt, BIO_SEG_VALID)))
1306 blk_recount_segments(q, nxt);
1307 if (!BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)) ||
1308 BIOVEC_VIRT_OVERSIZE(bio->bi_hw_front_size + bio->bi_hw_back_size))
1309 return 0;
1310 if (bio->bi_size + nxt->bi_size > q->max_segment_size)
1311 return 0;
1313 return 1;
1316 /*
1317 * map a request to scatterlist, return number of sg entries setup. Caller
1318 * must make sure sg can hold rq->nr_phys_segments entries
1319 */
1320 int blk_rq_map_sg(request_queue_t *q, struct request *rq, struct scatterlist *sg)
1322 struct bio_vec *bvec, *bvprv;
1323 struct bio *bio;
1324 int nsegs, i, cluster;
1326 nsegs = 0;
1327 cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
1329 /*
1330 * for each bio in rq
1331 */
1332 bvprv = NULL;
1333 rq_for_each_bio(bio, rq) {
1334 /*
1335 * for each segment in bio
1336 */
1337 bio_for_each_segment(bvec, bio, i) {
1338 int nbytes = bvec->bv_len;
1340 if (bvprv && cluster) {
1341 if (sg[nsegs - 1].length + nbytes > q->max_segment_size)
1342 goto new_segment;
1344 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bvec))
1345 goto new_segment;
1346 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bvec))
1347 goto new_segment;
1349 sg[nsegs - 1].length += nbytes;
1350 } else {
1351 new_segment:
1352 memset(&sg[nsegs],0,sizeof(struct scatterlist));
1353 sg[nsegs].page = bvec->bv_page;
1354 sg[nsegs].length = nbytes;
1355 sg[nsegs].offset = bvec->bv_offset;
1357 nsegs++;
1359 bvprv = bvec;
1360 } /* segments in bio */
1361 } /* bios in rq */
1363 return nsegs;
1366 EXPORT_SYMBOL(blk_rq_map_sg);
1368 /*
1369 * the standard queue merge functions, can be overridden with device
1370 * specific ones if so desired
1371 */
1373 static inline int ll_new_mergeable(request_queue_t *q,
1374 struct request *req,
1375 struct bio *bio)
1377 int nr_phys_segs = bio_phys_segments(q, bio);
1379 if (req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
1380 req->flags |= REQ_NOMERGE;
1381 if (req == q->last_merge)
1382 q->last_merge = NULL;
1383 return 0;
1386 /*
1387 * A hw segment is just getting larger, bump just the phys
1388 * counter.
1389 */
1390 req->nr_phys_segments += nr_phys_segs;
1391 return 1;
1394 static inline int ll_new_hw_segment(request_queue_t *q,
1395 struct request *req,
1396 struct bio *bio)
1398 int nr_hw_segs = bio_hw_segments(q, bio);
1399 int nr_phys_segs = bio_phys_segments(q, bio);
1401 if (req->nr_hw_segments + nr_hw_segs > q->max_hw_segments
1402 || req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
1403 req->flags |= REQ_NOMERGE;
1404 if (req == q->last_merge)
1405 q->last_merge = NULL;
1406 return 0;
1409 /*
1410 * This will form the start of a new hw segment. Bump both
1411 * counters.
1412 */
1413 req->nr_hw_segments += nr_hw_segs;
1414 req->nr_phys_segments += nr_phys_segs;
1415 return 1;
1418 static int ll_back_merge_fn(request_queue_t *q, struct request *req,
1419 struct bio *bio)
1421 unsigned short max_sectors;
1422 int len;
1424 if (unlikely(blk_pc_request(req)))
1425 max_sectors = q->max_hw_sectors;
1426 else
1427 max_sectors = q->max_sectors;
1429 if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
1430 req->flags |= REQ_NOMERGE;
1431 if (req == q->last_merge)
1432 q->last_merge = NULL;
1433 return 0;
1435 if (unlikely(!bio_flagged(req->biotail, BIO_SEG_VALID)))
1436 blk_recount_segments(q, req->biotail);
1437 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1438 blk_recount_segments(q, bio);
1439 len = req->biotail->bi_hw_back_size + bio->bi_hw_front_size;
1440 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(req->biotail), __BVEC_START(bio)) &&
1441 !BIOVEC_VIRT_OVERSIZE(len)) {
1442 int mergeable = ll_new_mergeable(q, req, bio);
1444 if (mergeable) {
1445 if (req->nr_hw_segments == 1)
1446 req->bio->bi_hw_front_size = len;
1447 if (bio->bi_hw_segments == 1)
1448 bio->bi_hw_back_size = len;
1450 return mergeable;
1453 return ll_new_hw_segment(q, req, bio);
1456 static int ll_front_merge_fn(request_queue_t *q, struct request *req,
1457 struct bio *bio)
1459 unsigned short max_sectors;
1460 int len;
1462 if (unlikely(blk_pc_request(req)))
1463 max_sectors = q->max_hw_sectors;
1464 else
1465 max_sectors = q->max_sectors;
1468 if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
1469 req->flags |= REQ_NOMERGE;
1470 if (req == q->last_merge)
1471 q->last_merge = NULL;
1472 return 0;
1474 len = bio->bi_hw_back_size + req->bio->bi_hw_front_size;
1475 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1476 blk_recount_segments(q, bio);
1477 if (unlikely(!bio_flagged(req->bio, BIO_SEG_VALID)))
1478 blk_recount_segments(q, req->bio);
1479 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(req->bio)) &&
1480 !BIOVEC_VIRT_OVERSIZE(len)) {
1481 int mergeable = ll_new_mergeable(q, req, bio);
1483 if (mergeable) {
1484 if (bio->bi_hw_segments == 1)
1485 bio->bi_hw_front_size = len;
1486 if (req->nr_hw_segments == 1)
1487 req->biotail->bi_hw_back_size = len;
1489 return mergeable;
1492 return ll_new_hw_segment(q, req, bio);
1495 static int ll_merge_requests_fn(request_queue_t *q, struct request *req,
1496 struct request *next)
1498 int total_phys_segments;
1499 int total_hw_segments;
1501 /*
1502 * First check if the either of the requests are re-queued
1503 * requests. Can't merge them if they are.
1504 */
1505 if (req->special || next->special)
1506 return 0;
1508 /*
1509 * Will it become too large?
1510 */
1511 if ((req->nr_sectors + next->nr_sectors) > q->max_sectors)
1512 return 0;
1514 total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
1515 if (blk_phys_contig_segment(q, req->biotail, next->bio))
1516 total_phys_segments--;
1518 if (total_phys_segments > q->max_phys_segments)
1519 return 0;
1521 total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
1522 if (blk_hw_contig_segment(q, req->biotail, next->bio)) {
1523 int len = req->biotail->bi_hw_back_size + next->bio->bi_hw_front_size;
1524 /*
1525 * propagate the combined length to the end of the requests
1526 */
1527 if (req->nr_hw_segments == 1)
1528 req->bio->bi_hw_front_size = len;
1529 if (next->nr_hw_segments == 1)
1530 next->biotail->bi_hw_back_size = len;
1531 total_hw_segments--;
1534 if (total_hw_segments > q->max_hw_segments)
1535 return 0;
1537 /* Merge is OK... */
1538 req->nr_phys_segments = total_phys_segments;
1539 req->nr_hw_segments = total_hw_segments;
1540 return 1;
1543 /*
1544 * "plug" the device if there are no outstanding requests: this will
1545 * force the transfer to start only after we have put all the requests
1546 * on the list.
1548 * This is called with interrupts off and no requests on the queue and
1549 * with the queue lock held.
1550 */
1551 void blk_plug_device(request_queue_t *q)
1553 WARN_ON(!irqs_disabled());
1555 /*
1556 * don't plug a stopped queue, it must be paired with blk_start_queue()
1557 * which will restart the queueing
1558 */
1559 if (blk_queue_stopped(q))
1560 return;
1562 if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags)) {
1563 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
1564 blk_add_trace_generic(q, NULL, 0, BLK_TA_PLUG);
1568 EXPORT_SYMBOL(blk_plug_device);
1570 /*
1571 * remove the queue from the plugged list, if present. called with
1572 * queue lock held and interrupts disabled.
1573 */
1574 int blk_remove_plug(request_queue_t *q)
1576 WARN_ON(!irqs_disabled());
1578 if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
1579 return 0;
1581 del_timer(&q->unplug_timer);
1582 return 1;
1585 EXPORT_SYMBOL(blk_remove_plug);
1587 /*
1588 * remove the plug and let it rip..
1589 */
1590 void __generic_unplug_device(request_queue_t *q)
1592 if (unlikely(blk_queue_stopped(q)))
1593 return;
1595 if (!blk_remove_plug(q))
1596 return;
1598 q->request_fn(q);
1600 EXPORT_SYMBOL(__generic_unplug_device);
1602 /**
1603 * generic_unplug_device - fire a request queue
1604 * @q: The &request_queue_t in question
1606 * Description:
1607 * Linux uses plugging to build bigger requests queues before letting
1608 * the device have at them. If a queue is plugged, the I/O scheduler
1609 * is still adding and merging requests on the queue. Once the queue
1610 * gets unplugged, the request_fn defined for the queue is invoked and
1611 * transfers started.
1612 **/
1613 void generic_unplug_device(request_queue_t *q)
1615 spin_lock_irq(q->queue_lock);
1616 __generic_unplug_device(q);
1617 spin_unlock_irq(q->queue_lock);
1619 EXPORT_SYMBOL(generic_unplug_device);
1621 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
1622 struct page *page)
1624 request_queue_t *q = bdi->unplug_io_data;
1626 /*
1627 * devices don't necessarily have an ->unplug_fn defined
1628 */
1629 if (q->unplug_fn) {
1630 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
1631 q->rq.count[READ] + q->rq.count[WRITE]);
1633 q->unplug_fn(q);
1637 static void blk_unplug_work(void *data)
1639 request_queue_t *q = data;
1641 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
1642 q->rq.count[READ] + q->rq.count[WRITE]);
1644 q->unplug_fn(q);
1647 static void blk_unplug_timeout(unsigned long data)
1649 request_queue_t *q = (request_queue_t *)data;
1651 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_TIMER, NULL,
1652 q->rq.count[READ] + q->rq.count[WRITE]);
1654 kblockd_schedule_work(&q->unplug_work);
1657 /**
1658 * blk_start_queue - restart a previously stopped queue
1659 * @q: The &request_queue_t in question
1661 * Description:
1662 * blk_start_queue() will clear the stop flag on the queue, and call
1663 * the request_fn for the queue if it was in a stopped state when
1664 * entered. Also see blk_stop_queue(). Queue lock must be held.
1665 **/
1666 void blk_start_queue(request_queue_t *q)
1668 WARN_ON(!irqs_disabled());
1670 clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1672 /*
1673 * one level of recursion is ok and is much faster than kicking
1674 * the unplug handling
1675 */
1676 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
1677 q->request_fn(q);
1678 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
1679 } else {
1680 blk_plug_device(q);
1681 kblockd_schedule_work(&q->unplug_work);
1685 EXPORT_SYMBOL(blk_start_queue);
1687 /**
1688 * blk_stop_queue - stop a queue
1689 * @q: The &request_queue_t in question
1691 * Description:
1692 * The Linux block layer assumes that a block driver will consume all
1693 * entries on the request queue when the request_fn strategy is called.
1694 * Often this will not happen, because of hardware limitations (queue
1695 * depth settings). If a device driver gets a 'queue full' response,
1696 * or if it simply chooses not to queue more I/O at one point, it can
1697 * call this function to prevent the request_fn from being called until
1698 * the driver has signalled it's ready to go again. This happens by calling
1699 * blk_start_queue() to restart queue operations. Queue lock must be held.
1700 **/
1701 void blk_stop_queue(request_queue_t *q)
1703 blk_remove_plug(q);
1704 set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1706 EXPORT_SYMBOL(blk_stop_queue);
1708 /**
1709 * blk_sync_queue - cancel any pending callbacks on a queue
1710 * @q: the queue
1712 * Description:
1713 * The block layer may perform asynchronous callback activity
1714 * on a queue, such as calling the unplug function after a timeout.
1715 * A block device may call blk_sync_queue to ensure that any
1716 * such activity is cancelled, thus allowing it to release resources
1717 * the the callbacks might use. The caller must already have made sure
1718 * that its ->make_request_fn will not re-add plugging prior to calling
1719 * this function.
1721 */
1722 void blk_sync_queue(struct request_queue *q)
1724 del_timer_sync(&q->unplug_timer);
1725 kblockd_flush();
1727 EXPORT_SYMBOL(blk_sync_queue);
1729 /**
1730 * blk_run_queue - run a single device queue
1731 * @q: The queue to run
1732 */
1733 void blk_run_queue(struct request_queue *q)
1735 unsigned long flags;
1737 spin_lock_irqsave(q->queue_lock, flags);
1738 blk_remove_plug(q);
1740 /*
1741 * Only recurse once to avoid overrunning the stack, let the unplug
1742 * handling reinvoke the handler shortly if we already got there.
1743 */
1744 if (!elv_queue_empty(q)) {
1745 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
1746 q->request_fn(q);
1747 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
1748 } else {
1749 blk_plug_device(q);
1750 kblockd_schedule_work(&q->unplug_work);
1754 spin_unlock_irqrestore(q->queue_lock, flags);
1756 EXPORT_SYMBOL(blk_run_queue);
1758 /**
1759 * blk_cleanup_queue: - release a &request_queue_t when it is no longer needed
1760 * @kobj: the kobj belonging of the request queue to be released
1762 * Description:
1763 * blk_cleanup_queue is the pair to blk_init_queue() or
1764 * blk_queue_make_request(). It should be called when a request queue is
1765 * being released; typically when a block device is being de-registered.
1766 * Currently, its primary task it to free all the &struct request
1767 * structures that were allocated to the queue and the queue itself.
1769 * Caveat:
1770 * Hopefully the low level driver will have finished any
1771 * outstanding requests first...
1772 **/
1773 static void blk_release_queue(struct kobject *kobj)
1775 request_queue_t *q = container_of(kobj, struct request_queue, kobj);
1776 struct request_list *rl = &q->rq;
1778 blk_sync_queue(q);
1780 if (rl->rq_pool)
1781 mempool_destroy(rl->rq_pool);
1783 if (q->queue_tags)
1784 __blk_queue_free_tags(q);
1786 if (q->blk_trace)
1787 blk_trace_shutdown(q);
1789 kmem_cache_free(requestq_cachep, q);
1792 void blk_put_queue(request_queue_t *q)
1794 kobject_put(&q->kobj);
1796 EXPORT_SYMBOL(blk_put_queue);
1798 void blk_cleanup_queue(request_queue_t * q)
1800 mutex_lock(&q->sysfs_lock);
1801 set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
1802 mutex_unlock(&q->sysfs_lock);
1804 if (q->elevator)
1805 elevator_exit(q->elevator);
1807 blk_put_queue(q);
1810 EXPORT_SYMBOL(blk_cleanup_queue);
1812 static int blk_init_free_list(request_queue_t *q)
1814 struct request_list *rl = &q->rq;
1816 rl->count[READ] = rl->count[WRITE] = 0;
1817 rl->starved[READ] = rl->starved[WRITE] = 0;
1818 rl->elvpriv = 0;
1819 init_waitqueue_head(&rl->wait[READ]);
1820 init_waitqueue_head(&rl->wait[WRITE]);
1822 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
1823 mempool_free_slab, request_cachep, q->node);
1825 if (!rl->rq_pool)
1826 return -ENOMEM;
1828 return 0;
1831 request_queue_t *blk_alloc_queue(gfp_t gfp_mask)
1833 return blk_alloc_queue_node(gfp_mask, -1);
1835 EXPORT_SYMBOL(blk_alloc_queue);
1837 static struct kobj_type queue_ktype;
1839 request_queue_t *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
1841 request_queue_t *q;
1843 q = kmem_cache_alloc_node(requestq_cachep, gfp_mask, node_id);
1844 if (!q)
1845 return NULL;
1847 memset(q, 0, sizeof(*q));
1848 init_timer(&q->unplug_timer);
1850 snprintf(q->kobj.name, KOBJ_NAME_LEN, "%s", "queue");
1851 q->kobj.ktype = &queue_ktype;
1852 kobject_init(&q->kobj);
1854 q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
1855 q->backing_dev_info.unplug_io_data = q;
1857 mutex_init(&q->sysfs_lock);
1859 return q;
1861 EXPORT_SYMBOL(blk_alloc_queue_node);
1863 /**
1864 * blk_init_queue - prepare a request queue for use with a block device
1865 * @rfn: The function to be called to process requests that have been
1866 * placed on the queue.
1867 * @lock: Request queue spin lock
1869 * Description:
1870 * If a block device wishes to use the standard request handling procedures,
1871 * which sorts requests and coalesces adjacent requests, then it must
1872 * call blk_init_queue(). The function @rfn will be called when there
1873 * are requests on the queue that need to be processed. If the device
1874 * supports plugging, then @rfn may not be called immediately when requests
1875 * are available on the queue, but may be called at some time later instead.
1876 * Plugged queues are generally unplugged when a buffer belonging to one
1877 * of the requests on the queue is needed, or due to memory pressure.
1879 * @rfn is not required, or even expected, to remove all requests off the
1880 * queue, but only as many as it can handle at a time. If it does leave
1881 * requests on the queue, it is responsible for arranging that the requests
1882 * get dealt with eventually.
1884 * The queue spin lock must be held while manipulating the requests on the
1885 * request queue; this lock will be taken also from interrupt context, so irq
1886 * disabling is needed for it.
1888 * Function returns a pointer to the initialized request queue, or NULL if
1889 * it didn't succeed.
1891 * Note:
1892 * blk_init_queue() must be paired with a blk_cleanup_queue() call
1893 * when the block device is deactivated (such as at module unload).
1894 **/
1896 request_queue_t *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1898 return blk_init_queue_node(rfn, lock, -1);
1900 EXPORT_SYMBOL(blk_init_queue);
1902 request_queue_t *
1903 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
1905 request_queue_t *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
1907 if (!q)
1908 return NULL;
1910 q->node = node_id;
1911 if (blk_init_free_list(q)) {
1912 kmem_cache_free(requestq_cachep, q);
1913 return NULL;
1916 /*
1917 * if caller didn't supply a lock, they get per-queue locking with
1918 * our embedded lock
1919 */
1920 if (!lock) {
1921 spin_lock_init(&q->__queue_lock);
1922 lock = &q->__queue_lock;
1925 q->request_fn = rfn;
1926 q->back_merge_fn = ll_back_merge_fn;
1927 q->front_merge_fn = ll_front_merge_fn;
1928 q->merge_requests_fn = ll_merge_requests_fn;
1929 q->prep_rq_fn = NULL;
1930 q->unplug_fn = generic_unplug_device;
1931 q->queue_flags = (1 << QUEUE_FLAG_CLUSTER);
1932 q->queue_lock = lock;
1934 blk_queue_segment_boundary(q, 0xffffffff);
1936 blk_queue_make_request(q, __make_request);
1937 blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
1939 blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
1940 blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
1942 /*
1943 * all done
1944 */
1945 if (!elevator_init(q, NULL)) {
1946 blk_queue_congestion_threshold(q);
1947 return q;
1950 blk_put_queue(q);
1951 return NULL;
1953 EXPORT_SYMBOL(blk_init_queue_node);
1955 int blk_get_queue(request_queue_t *q)
1957 if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
1958 kobject_get(&q->kobj);
1959 return 0;
1962 return 1;
1965 EXPORT_SYMBOL(blk_get_queue);
1967 static inline void blk_free_request(request_queue_t *q, struct request *rq)
1969 if (rq->flags & REQ_ELVPRIV)
1970 elv_put_request(q, rq);
1971 mempool_free(rq, q->rq.rq_pool);
1974 static inline struct request *
1975 blk_alloc_request(request_queue_t *q, int rw, struct bio *bio,
1976 int priv, gfp_t gfp_mask)
1978 struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
1980 if (!rq)
1981 return NULL;
1983 /*
1984 * first three bits are identical in rq->flags and bio->bi_rw,
1985 * see bio.h and blkdev.h
1986 */
1987 rq->flags = rw;
1989 if (priv) {
1990 if (unlikely(elv_set_request(q, rq, bio, gfp_mask))) {
1991 mempool_free(rq, q->rq.rq_pool);
1992 return NULL;
1994 rq->flags |= REQ_ELVPRIV;
1997 return rq;
2000 /*
2001 * ioc_batching returns true if the ioc is a valid batching request and
2002 * should be given priority access to a request.
2003 */
2004 static inline int ioc_batching(request_queue_t *q, struct io_context *ioc)
2006 if (!ioc)
2007 return 0;
2009 /*
2010 * Make sure the process is able to allocate at least 1 request
2011 * even if the batch times out, otherwise we could theoretically
2012 * lose wakeups.
2013 */
2014 return ioc->nr_batch_requests == q->nr_batching ||
2015 (ioc->nr_batch_requests > 0
2016 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
2019 /*
2020 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
2021 * will cause the process to be a "batcher" on all queues in the system. This
2022 * is the behaviour we want though - once it gets a wakeup it should be given
2023 * a nice run.
2024 */
2025 static void ioc_set_batching(request_queue_t *q, struct io_context *ioc)
2027 if (!ioc || ioc_batching(q, ioc))
2028 return;
2030 ioc->nr_batch_requests = q->nr_batching;
2031 ioc->last_waited = jiffies;
2034 static void __freed_request(request_queue_t *q, int rw)
2036 struct request_list *rl = &q->rq;
2038 if (rl->count[rw] < queue_congestion_off_threshold(q))
2039 clear_queue_congested(q, rw);
2041 if (rl->count[rw] + 1 <= q->nr_requests) {
2042 if (waitqueue_active(&rl->wait[rw]))
2043 wake_up(&rl->wait[rw]);
2045 blk_clear_queue_full(q, rw);
2049 /*
2050 * A request has just been released. Account for it, update the full and
2051 * congestion status, wake up any waiters. Called under q->queue_lock.
2052 */
2053 static void freed_request(request_queue_t *q, int rw, int priv)
2055 struct request_list *rl = &q->rq;
2057 rl->count[rw]--;
2058 if (priv)
2059 rl->elvpriv--;
2061 __freed_request(q, rw);
2063 if (unlikely(rl->starved[rw ^ 1]))
2064 __freed_request(q, rw ^ 1);
2067 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
2068 /*
2069 * Get a free request, queue_lock must be held.
2070 * Returns NULL on failure, with queue_lock held.
2071 * Returns !NULL on success, with queue_lock *not held*.
2072 */
2073 static struct request *get_request(request_queue_t *q, int rw, struct bio *bio,
2074 gfp_t gfp_mask)
2076 struct request *rq = NULL;
2077 struct request_list *rl = &q->rq;
2078 struct io_context *ioc = NULL;
2079 int may_queue, priv;
2081 may_queue = elv_may_queue(q, rw, bio);
2082 if (may_queue == ELV_MQUEUE_NO)
2083 goto rq_starved;
2085 if (rl->count[rw]+1 >= queue_congestion_on_threshold(q)) {
2086 if (rl->count[rw]+1 >= q->nr_requests) {
2087 ioc = current_io_context(GFP_ATOMIC);
2088 /*
2089 * The queue will fill after this allocation, so set
2090 * it as full, and mark this process as "batching".
2091 * This process will be allowed to complete a batch of
2092 * requests, others will be blocked.
2093 */
2094 if (!blk_queue_full(q, rw)) {
2095 ioc_set_batching(q, ioc);
2096 blk_set_queue_full(q, rw);
2097 } else {
2098 if (may_queue != ELV_MQUEUE_MUST
2099 && !ioc_batching(q, ioc)) {
2100 /*
2101 * The queue is full and the allocating
2102 * process is not a "batcher", and not
2103 * exempted by the IO scheduler
2104 */
2105 goto out;
2109 set_queue_congested(q, rw);
2112 /*
2113 * Only allow batching queuers to allocate up to 50% over the defined
2114 * limit of requests, otherwise we could have thousands of requests
2115 * allocated with any setting of ->nr_requests
2116 */
2117 if (rl->count[rw] >= (3 * q->nr_requests / 2))
2118 goto out;
2120 rl->count[rw]++;
2121 rl->starved[rw] = 0;
2123 priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
2124 if (priv)
2125 rl->elvpriv++;
2127 spin_unlock_irq(q->queue_lock);
2129 rq = blk_alloc_request(q, rw, bio, priv, gfp_mask);
2130 if (unlikely(!rq)) {
2131 /*
2132 * Allocation failed presumably due to memory. Undo anything
2133 * we might have messed up.
2135 * Allocating task should really be put onto the front of the
2136 * wait queue, but this is pretty rare.
2137 */
2138 spin_lock_irq(q->queue_lock);
2139 freed_request(q, rw, priv);
2141 /*
2142 * in the very unlikely event that allocation failed and no
2143 * requests for this direction was pending, mark us starved
2144 * so that freeing of a request in the other direction will
2145 * notice us. another possible fix would be to split the
2146 * rq mempool into READ and WRITE
2147 */
2148 rq_starved:
2149 if (unlikely(rl->count[rw] == 0))
2150 rl->starved[rw] = 1;
2152 goto out;
2155 /*
2156 * ioc may be NULL here, and ioc_batching will be false. That's
2157 * OK, if the queue is under the request limit then requests need
2158 * not count toward the nr_batch_requests limit. There will always
2159 * be some limit enforced by BLK_BATCH_TIME.
2160 */
2161 if (ioc_batching(q, ioc))
2162 ioc->nr_batch_requests--;
2164 rq_init(q, rq);
2165 rq->rl = rl;
2167 blk_add_trace_generic(q, bio, rw, BLK_TA_GETRQ);
2168 out:
2169 return rq;
2172 /*
2173 * No available requests for this queue, unplug the device and wait for some
2174 * requests to become available.
2176 * Called with q->queue_lock held, and returns with it unlocked.
2177 */
2178 static struct request *get_request_wait(request_queue_t *q, int rw,
2179 struct bio *bio)
2181 struct request *rq;
2183 rq = get_request(q, rw, bio, GFP_NOIO);
2184 while (!rq) {
2185 DEFINE_WAIT(wait);
2186 struct request_list *rl = &q->rq;
2188 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
2189 TASK_UNINTERRUPTIBLE);
2191 rq = get_request(q, rw, bio, GFP_NOIO);
2193 if (!rq) {
2194 struct io_context *ioc;
2196 blk_add_trace_generic(q, bio, rw, BLK_TA_SLEEPRQ);
2198 __generic_unplug_device(q);
2199 spin_unlock_irq(q->queue_lock);
2200 io_schedule();
2202 /*
2203 * After sleeping, we become a "batching" process and
2204 * will be able to allocate at least one request, and
2205 * up to a big batch of them for a small period time.
2206 * See ioc_batching, ioc_set_batching
2207 */
2208 ioc = current_io_context(GFP_NOIO);
2209 ioc_set_batching(q, ioc);
2211 spin_lock_irq(q->queue_lock);
2213 finish_wait(&rl->wait[rw], &wait);
2216 return rq;
2219 struct request *blk_get_request(request_queue_t *q, int rw, gfp_t gfp_mask)
2221 struct request *rq;
2223 BUG_ON(rw != READ && rw != WRITE);
2225 spin_lock_irq(q->queue_lock);
2226 if (gfp_mask & __GFP_WAIT) {
2227 rq = get_request_wait(q, rw, NULL);
2228 } else {
2229 rq = get_request(q, rw, NULL, gfp_mask);
2230 if (!rq)
2231 spin_unlock_irq(q->queue_lock);
2233 /* q->queue_lock is unlocked at this point */
2235 return rq;
2237 EXPORT_SYMBOL(blk_get_request);
2239 /**
2240 * blk_requeue_request - put a request back on queue
2241 * @q: request queue where request should be inserted
2242 * @rq: request to be inserted
2244 * Description:
2245 * Drivers often keep queueing requests until the hardware cannot accept
2246 * more, when that condition happens we need to put the request back
2247 * on the queue. Must be called with queue lock held.
2248 */
2249 void blk_requeue_request(request_queue_t *q, struct request *rq)
2251 blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
2253 if (blk_rq_tagged(rq))
2254 blk_queue_end_tag(q, rq);
2256 elv_requeue_request(q, rq);
2259 EXPORT_SYMBOL(blk_requeue_request);
2261 /**
2262 * blk_insert_request - insert a special request in to a request queue
2263 * @q: request queue where request should be inserted
2264 * @rq: request to be inserted
2265 * @at_head: insert request at head or tail of queue
2266 * @data: private data
2268 * Description:
2269 * Many block devices need to execute commands asynchronously, so they don't
2270 * block the whole kernel from preemption during request execution. This is
2271 * accomplished normally by inserting aritficial requests tagged as
2272 * REQ_SPECIAL in to the corresponding request queue, and letting them be
2273 * scheduled for actual execution by the request queue.
2275 * We have the option of inserting the head or the tail of the queue.
2276 * Typically we use the tail for new ioctls and so forth. We use the head
2277 * of the queue for things like a QUEUE_FULL message from a device, or a
2278 * host that is unable to accept a particular command.
2279 */
2280 void blk_insert_request(request_queue_t *q, struct request *rq,
2281 int at_head, void *data)
2283 int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
2284 unsigned long flags;
2286 /*
2287 * tell I/O scheduler that this isn't a regular read/write (ie it
2288 * must not attempt merges on this) and that it acts as a soft
2289 * barrier
2290 */
2291 rq->flags |= REQ_SPECIAL | REQ_SOFTBARRIER;
2293 rq->special = data;
2295 spin_lock_irqsave(q->queue_lock, flags);
2297 /*
2298 * If command is tagged, release the tag
2299 */
2300 if (blk_rq_tagged(rq))
2301 blk_queue_end_tag(q, rq);
2303 drive_stat_acct(rq, rq->nr_sectors, 1);
2304 __elv_add_request(q, rq, where, 0);
2306 if (blk_queue_plugged(q))
2307 __generic_unplug_device(q);
2308 else
2309 q->request_fn(q);
2310 spin_unlock_irqrestore(q->queue_lock, flags);
2313 EXPORT_SYMBOL(blk_insert_request);
2315 /**
2316 * blk_rq_map_user - map user data to a request, for REQ_BLOCK_PC usage
2317 * @q: request queue where request should be inserted
2318 * @rq: request structure to fill
2319 * @ubuf: the user buffer
2320 * @len: length of user data
2322 * Description:
2323 * Data will be mapped directly for zero copy io, if possible. Otherwise
2324 * a kernel bounce buffer is used.
2326 * A matching blk_rq_unmap_user() must be issued at the end of io, while
2327 * still in process context.
2329 * Note: The mapped bio may need to be bounced through blk_queue_bounce()
2330 * before being submitted to the device, as pages mapped may be out of
2331 * reach. It's the callers responsibility to make sure this happens. The
2332 * original bio must be passed back in to blk_rq_unmap_user() for proper
2333 * unmapping.
2334 */
2335 int blk_rq_map_user(request_queue_t *q, struct request *rq, void __user *ubuf,
2336 unsigned int len)
2338 unsigned long uaddr;
2339 struct bio *bio;
2340 int reading;
2342 if (len > (q->max_hw_sectors << 9))
2343 return -EINVAL;
2344 if (!len || !ubuf)
2345 return -EINVAL;
2347 reading = rq_data_dir(rq) == READ;
2349 /*
2350 * if alignment requirement is satisfied, map in user pages for
2351 * direct dma. else, set up kernel bounce buffers
2352 */
2353 uaddr = (unsigned long) ubuf;
2354 if (!(uaddr & queue_dma_alignment(q)) && !(len & queue_dma_alignment(q)))
2355 bio = bio_map_user(q, NULL, uaddr, len, reading);
2356 else
2357 bio = bio_copy_user(q, uaddr, len, reading);
2359 if (!IS_ERR(bio)) {
2360 rq->bio = rq->biotail = bio;
2361 blk_rq_bio_prep(q, rq, bio);
2363 rq->buffer = rq->data = NULL;
2364 rq->data_len = len;
2365 return 0;
2368 /*
2369 * bio is the err-ptr
2370 */
2371 return PTR_ERR(bio);
2374 EXPORT_SYMBOL(blk_rq_map_user);
2376 /**
2377 * blk_rq_map_user_iov - map user data to a request, for REQ_BLOCK_PC usage
2378 * @q: request queue where request should be inserted
2379 * @rq: request to map data to
2380 * @iov: pointer to the iovec
2381 * @iov_count: number of elements in the iovec
2383 * Description:
2384 * Data will be mapped directly for zero copy io, if possible. Otherwise
2385 * a kernel bounce buffer is used.
2387 * A matching blk_rq_unmap_user() must be issued at the end of io, while
2388 * still in process context.
2390 * Note: The mapped bio may need to be bounced through blk_queue_bounce()
2391 * before being submitted to the device, as pages mapped may be out of
2392 * reach. It's the callers responsibility to make sure this happens. The
2393 * original bio must be passed back in to blk_rq_unmap_user() for proper
2394 * unmapping.
2395 */
2396 int blk_rq_map_user_iov(request_queue_t *q, struct request *rq,
2397 struct sg_iovec *iov, int iov_count)
2399 struct bio *bio;
2401 if (!iov || iov_count <= 0)
2402 return -EINVAL;
2404 /* we don't allow misaligned data like bio_map_user() does. If the
2405 * user is using sg, they're expected to know the alignment constraints
2406 * and respect them accordingly */
2407 bio = bio_map_user_iov(q, NULL, iov, iov_count, rq_data_dir(rq)== READ);
2408 if (IS_ERR(bio))
2409 return PTR_ERR(bio);
2411 rq->bio = rq->biotail = bio;
2412 blk_rq_bio_prep(q, rq, bio);
2413 rq->buffer = rq->data = NULL;
2414 rq->data_len = bio->bi_size;
2415 return 0;
2418 EXPORT_SYMBOL(blk_rq_map_user_iov);
2420 /**
2421 * blk_rq_unmap_user - unmap a request with user data
2422 * @bio: bio to be unmapped
2423 * @ulen: length of user buffer
2425 * Description:
2426 * Unmap a bio previously mapped by blk_rq_map_user().
2427 */
2428 int blk_rq_unmap_user(struct bio *bio, unsigned int ulen)
2430 int ret = 0;
2432 if (bio) {
2433 if (bio_flagged(bio, BIO_USER_MAPPED))
2434 bio_unmap_user(bio);
2435 else
2436 ret = bio_uncopy_user(bio);
2439 return 0;
2442 EXPORT_SYMBOL(blk_rq_unmap_user);
2444 /**
2445 * blk_rq_map_kern - map kernel data to a request, for REQ_BLOCK_PC usage
2446 * @q: request queue where request should be inserted
2447 * @rq: request to fill
2448 * @kbuf: the kernel buffer
2449 * @len: length of user data
2450 * @gfp_mask: memory allocation flags
2451 */
2452 int blk_rq_map_kern(request_queue_t *q, struct request *rq, void *kbuf,
2453 unsigned int len, gfp_t gfp_mask)
2455 struct bio *bio;
2457 if (len > (q->max_hw_sectors << 9))
2458 return -EINVAL;
2459 if (!len || !kbuf)
2460 return -EINVAL;
2462 bio = bio_map_kern(q, kbuf, len, gfp_mask);
2463 if (IS_ERR(bio))
2464 return PTR_ERR(bio);
2466 if (rq_data_dir(rq) == WRITE)
2467 bio->bi_rw |= (1 << BIO_RW);
2469 rq->bio = rq->biotail = bio;
2470 blk_rq_bio_prep(q, rq, bio);
2472 rq->buffer = rq->data = NULL;
2473 rq->data_len = len;
2474 return 0;
2477 EXPORT_SYMBOL(blk_rq_map_kern);
2479 /**
2480 * blk_execute_rq_nowait - insert a request into queue for execution
2481 * @q: queue to insert the request in
2482 * @bd_disk: matching gendisk
2483 * @rq: request to insert
2484 * @at_head: insert request at head or tail of queue
2485 * @done: I/O completion handler
2487 * Description:
2488 * Insert a fully prepared request at the back of the io scheduler queue
2489 * for execution. Don't wait for completion.
2490 */
2491 void blk_execute_rq_nowait(request_queue_t *q, struct gendisk *bd_disk,
2492 struct request *rq, int at_head,
2493 rq_end_io_fn *done)
2495 int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
2497 rq->rq_disk = bd_disk;
2498 rq->flags |= REQ_NOMERGE;
2499 rq->end_io = done;
2500 WARN_ON(irqs_disabled());
2501 spin_lock_irq(q->queue_lock);
2502 __elv_add_request(q, rq, where, 1);
2503 __generic_unplug_device(q);
2504 spin_unlock_irq(q->queue_lock);
2506 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
2508 /**
2509 * blk_execute_rq - insert a request into queue for execution
2510 * @q: queue to insert the request in
2511 * @bd_disk: matching gendisk
2512 * @rq: request to insert
2513 * @at_head: insert request at head or tail of queue
2515 * Description:
2516 * Insert a fully prepared request at the back of the io scheduler queue
2517 * for execution and wait for completion.
2518 */
2519 int blk_execute_rq(request_queue_t *q, struct gendisk *bd_disk,
2520 struct request *rq, int at_head)
2522 DECLARE_COMPLETION_ONSTACK(wait);
2523 char sense[SCSI_SENSE_BUFFERSIZE];
2524 int err = 0;
2526 /*
2527 * we need an extra reference to the request, so we can look at
2528 * it after io completion
2529 */
2530 rq->ref_count++;
2532 if (!rq->sense) {
2533 memset(sense, 0, sizeof(sense));
2534 rq->sense = sense;
2535 rq->sense_len = 0;
2538 rq->waiting = &wait;
2539 blk_execute_rq_nowait(q, bd_disk, rq, at_head, blk_end_sync_rq);
2540 wait_for_completion(&wait);
2541 rq->waiting = NULL;
2543 if (rq->errors)
2544 err = -EIO;
2546 return err;
2549 EXPORT_SYMBOL(blk_execute_rq);
2551 /**
2552 * blkdev_issue_flush - queue a flush
2553 * @bdev: blockdev to issue flush for
2554 * @error_sector: error sector
2556 * Description:
2557 * Issue a flush for the block device in question. Caller can supply
2558 * room for storing the error offset in case of a flush error, if they
2559 * wish to. Caller must run wait_for_completion() on its own.
2560 */
2561 int blkdev_issue_flush(struct block_device *bdev, sector_t *error_sector)
2563 request_queue_t *q;
2565 if (bdev->bd_disk == NULL)
2566 return -ENXIO;
2568 q = bdev_get_queue(bdev);
2569 if (!q)
2570 return -ENXIO;
2571 if (!q->issue_flush_fn)
2572 return -EOPNOTSUPP;
2574 return q->issue_flush_fn(q, bdev->bd_disk, error_sector);
2577 EXPORT_SYMBOL(blkdev_issue_flush);
2579 static void drive_stat_acct(struct request *rq, int nr_sectors, int new_io)
2581 int rw = rq_data_dir(rq);
2583 if (!blk_fs_request(rq) || !rq->rq_disk)
2584 return;
2586 if (!new_io) {
2587 __disk_stat_inc(rq->rq_disk, merges[rw]);
2588 } else {
2589 disk_round_stats(rq->rq_disk);
2590 rq->rq_disk->in_flight++;
2594 /*
2595 * add-request adds a request to the linked list.
2596 * queue lock is held and interrupts disabled, as we muck with the
2597 * request queue list.
2598 */
2599 static inline void add_request(request_queue_t * q, struct request * req)
2601 drive_stat_acct(req, req->nr_sectors, 1);
2603 if (q->activity_fn)
2604 q->activity_fn(q->activity_data, rq_data_dir(req));
2606 /*
2607 * elevator indicated where it wants this request to be
2608 * inserted at elevator_merge time
2609 */
2610 __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
2613 /*
2614 * disk_round_stats() - Round off the performance stats on a struct
2615 * disk_stats.
2617 * The average IO queue length and utilisation statistics are maintained
2618 * by observing the current state of the queue length and the amount of
2619 * time it has been in this state for.
2621 * Normally, that accounting is done on IO completion, but that can result
2622 * in more than a second's worth of IO being accounted for within any one
2623 * second, leading to >100% utilisation. To deal with that, we call this
2624 * function to do a round-off before returning the results when reading
2625 * /proc/diskstats. This accounts immediately for all queue usage up to
2626 * the current jiffies and restarts the counters again.
2627 */
2628 void disk_round_stats(struct gendisk *disk)
2630 unsigned long now = jiffies;
2632 if (now == disk->stamp)
2633 return;
2635 if (disk->in_flight) {
2636 __disk_stat_add(disk, time_in_queue,
2637 disk->in_flight * (now - disk->stamp));
2638 __disk_stat_add(disk, io_ticks, (now - disk->stamp));
2640 disk->stamp = now;
2643 EXPORT_SYMBOL_GPL(disk_round_stats);
2645 /*
2646 * queue lock must be held
2647 */
2648 void __blk_put_request(request_queue_t *q, struct request *req)
2650 struct request_list *rl = req->rl;
2652 if (unlikely(!q))
2653 return;
2654 if (unlikely(--req->ref_count))
2655 return;
2657 elv_completed_request(q, req);
2659 req->rq_status = RQ_INACTIVE;
2660 req->rl = NULL;
2662 /*
2663 * Request may not have originated from ll_rw_blk. if not,
2664 * it didn't come out of our reserved rq pools
2665 */
2666 if (rl) {
2667 int rw = rq_data_dir(req);
2668 int priv = req->flags & REQ_ELVPRIV;
2670 BUG_ON(!list_empty(&req->queuelist));
2672 blk_free_request(q, req);
2673 freed_request(q, rw, priv);
2677 EXPORT_SYMBOL_GPL(__blk_put_request);
2679 void blk_put_request(struct request *req)
2681 unsigned long flags;
2682 request_queue_t *q = req->q;
2684 /*
2685 * Gee, IDE calls in w/ NULL q. Fix IDE and remove the
2686 * following if (q) test.
2687 */
2688 if (q) {
2689 spin_lock_irqsave(q->queue_lock, flags);
2690 __blk_put_request(q, req);
2691 spin_unlock_irqrestore(q->queue_lock, flags);
2695 EXPORT_SYMBOL(blk_put_request);
2697 /**
2698 * blk_end_sync_rq - executes a completion event on a request
2699 * @rq: request to complete
2700 * @error: end io status of the request
2701 */
2702 void blk_end_sync_rq(struct request *rq, int error)
2704 struct completion *waiting = rq->waiting;
2706 rq->waiting = NULL;
2707 __blk_put_request(rq->q, rq);
2709 /*
2710 * complete last, if this is a stack request the process (and thus
2711 * the rq pointer) could be invalid right after this complete()
2712 */
2713 complete(waiting);
2715 EXPORT_SYMBOL(blk_end_sync_rq);
2717 /**
2718 * blk_congestion_wait - wait for a queue to become uncongested
2719 * @rw: READ or WRITE
2720 * @timeout: timeout in jiffies
2722 * Waits for up to @timeout jiffies for a queue (any queue) to exit congestion.
2723 * If no queues are congested then just wait for the next request to be
2724 * returned.
2725 */
2726 long blk_congestion_wait(int rw, long timeout)
2728 long ret;
2729 DEFINE_WAIT(wait);
2730 wait_queue_head_t *wqh = &congestion_wqh[rw];
2732 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
2733 ret = io_schedule_timeout(timeout);
2734 finish_wait(wqh, &wait);
2735 return ret;
2738 EXPORT_SYMBOL(blk_congestion_wait);
2740 /*
2741 * Has to be called with the request spinlock acquired
2742 */
2743 static int attempt_merge(request_queue_t *q, struct request *req,
2744 struct request *next)
2746 if (!rq_mergeable(req) || !rq_mergeable(next))
2747 return 0;
2749 /*
2750 * not contiguous
2751 */
2752 if (req->sector + req->nr_sectors != next->sector)
2753 return 0;
2755 if (rq_data_dir(req) != rq_data_dir(next)
2756 || req->rq_disk != next->rq_disk
2757 || next->waiting || next->special)
2758 return 0;
2760 /*
2761 * If we are allowed to merge, then append bio list
2762 * from next to rq and release next. merge_requests_fn
2763 * will have updated segment counts, update sector
2764 * counts here.
2765 */
2766 if (!q->merge_requests_fn(q, req, next))
2767 return 0;
2769 /*
2770 * At this point we have either done a back merge
2771 * or front merge. We need the smaller start_time of
2772 * the merged requests to be the current request
2773 * for accounting purposes.
2774 */
2775 if (time_after(req->start_time, next->start_time))
2776 req->start_time = next->start_time;
2778 req->biotail->bi_next = next->bio;
2779 req->biotail = next->biotail;
2781 req->nr_sectors = req->hard_nr_sectors += next->hard_nr_sectors;
2783 elv_merge_requests(q, req, next);
2785 if (req->rq_disk) {
2786 disk_round_stats(req->rq_disk);
2787 req->rq_disk->in_flight--;
2790 req->ioprio = ioprio_best(req->ioprio, next->ioprio);
2792 __blk_put_request(q, next);
2793 return 1;
2796 static inline int attempt_back_merge(request_queue_t *q, struct request *rq)
2798 struct request *next = elv_latter_request(q, rq);
2800 if (next)
2801 return attempt_merge(q, rq, next);
2803 return 0;
2806 static inline int attempt_front_merge(request_queue_t *q, struct request *rq)
2808 struct request *prev = elv_former_request(q, rq);
2810 if (prev)
2811 return attempt_merge(q, prev, rq);
2813 return 0;
2816 static void init_request_from_bio(struct request *req, struct bio *bio)
2818 req->flags |= REQ_CMD;
2820 /*
2821 * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
2822 */
2823 if (bio_rw_ahead(bio) || bio_failfast(bio))
2824 req->flags |= REQ_FAILFAST;
2826 /*
2827 * REQ_BARRIER implies no merging, but lets make it explicit
2828 */
2829 if (unlikely(bio_barrier(bio)))
2830 req->flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
2832 if (bio_sync(bio))
2833 req->flags |= REQ_RW_SYNC;
2835 req->errors = 0;
2836 req->hard_sector = req->sector = bio->bi_sector;
2837 req->hard_nr_sectors = req->nr_sectors = bio_sectors(bio);
2838 req->current_nr_sectors = req->hard_cur_sectors = bio_cur_sectors(bio);
2839 req->nr_phys_segments = bio_phys_segments(req->q, bio);
2840 req->nr_hw_segments = bio_hw_segments(req->q, bio);
2841 req->buffer = bio_data(bio); /* see ->buffer comment above */
2842 req->waiting = NULL;
2843 req->bio = req->biotail = bio;
2844 req->ioprio = bio_prio(bio);
2845 req->rq_disk = bio->bi_bdev->bd_disk;
2846 req->start_time = jiffies;
2849 static int __make_request(request_queue_t *q, struct bio *bio)
2851 struct request *req;
2852 int el_ret, rw, nr_sectors, cur_nr_sectors, barrier, err, sync;
2853 unsigned short prio;
2854 sector_t sector;
2856 sector = bio->bi_sector;
2857 nr_sectors = bio_sectors(bio);
2858 cur_nr_sectors = bio_cur_sectors(bio);
2859 prio = bio_prio(bio);
2861 rw = bio_data_dir(bio);
2862 sync = bio_sync(bio);
2864 /*
2865 * low level driver can indicate that it wants pages above a
2866 * certain limit bounced to low memory (ie for highmem, or even
2867 * ISA dma in theory)
2868 */
2869 blk_queue_bounce(q, &bio);
2871 spin_lock_prefetch(q->queue_lock);
2873 barrier = bio_barrier(bio);
2874 if (unlikely(barrier) && (q->next_ordered == QUEUE_ORDERED_NONE)) {
2875 err = -EOPNOTSUPP;
2876 goto end_io;
2879 spin_lock_irq(q->queue_lock);
2881 if (unlikely(barrier) || elv_queue_empty(q))
2882 goto get_rq;
2884 el_ret = elv_merge(q, &req, bio);
2885 switch (el_ret) {
2886 case ELEVATOR_BACK_MERGE:
2887 BUG_ON(!rq_mergeable(req));
2889 if (!q->back_merge_fn(q, req, bio))
2890 break;
2892 blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
2894 req->biotail->bi_next = bio;
2895 req->biotail = bio;
2896 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2897 req->ioprio = ioprio_best(req->ioprio, prio);
2898 drive_stat_acct(req, nr_sectors, 0);
2899 if (!attempt_back_merge(q, req))
2900 elv_merged_request(q, req);
2901 goto out;
2903 case ELEVATOR_FRONT_MERGE:
2904 BUG_ON(!rq_mergeable(req));
2906 if (!q->front_merge_fn(q, req, bio))
2907 break;
2909 blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
2911 bio->bi_next = req->bio;
2912 req->bio = bio;
2914 /*
2915 * may not be valid. if the low level driver said
2916 * it didn't need a bounce buffer then it better
2917 * not touch req->buffer either...
2918 */
2919 req->buffer = bio_data(bio);
2920 req->current_nr_sectors = cur_nr_sectors;
2921 req->hard_cur_sectors = cur_nr_sectors;
2922 req->sector = req->hard_sector = sector;
2923 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2924 req->ioprio = ioprio_best(req->ioprio, prio);
2925 drive_stat_acct(req, nr_sectors, 0);
2926 if (!attempt_front_merge(q, req))
2927 elv_merged_request(q, req);
2928 goto out;
2930 /* ELV_NO_MERGE: elevator says don't/can't merge. */
2931 default:
2935 get_rq:
2936 /*
2937 * Grab a free request. This is might sleep but can not fail.
2938 * Returns with the queue unlocked.
2939 */
2940 req = get_request_wait(q, rw, bio);
2942 /*
2943 * After dropping the lock and possibly sleeping here, our request
2944 * may now be mergeable after it had proven unmergeable (above).
2945 * We don't worry about that case for efficiency. It won't happen
2946 * often, and the elevators are able to handle it.
2947 */
2948 init_request_from_bio(req, bio);
2950 spin_lock_irq(q->queue_lock);
2951 if (elv_queue_empty(q))
2952 blk_plug_device(q);
2953 add_request(q, req);
2954 out:
2955 if (sync)
2956 __generic_unplug_device(q);
2958 spin_unlock_irq(q->queue_lock);
2959 return 0;
2961 end_io:
2962 bio_endio(bio, nr_sectors << 9, err);
2963 return 0;
2966 /*
2967 * If bio->bi_dev is a partition, remap the location
2968 */
2969 static inline void blk_partition_remap(struct bio *bio)
2971 struct block_device *bdev = bio->bi_bdev;
2973 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
2974 struct hd_struct *p = bdev->bd_part;
2975 const int rw = bio_data_dir(bio);
2977 p->sectors[rw] += bio_sectors(bio);
2978 p->ios[rw]++;
2980 bio->bi_sector += p->start_sect;
2981 bio->bi_bdev = bdev->bd_contains;
2985 static void handle_bad_sector(struct bio *bio)
2987 char b[BDEVNAME_SIZE];
2989 printk(KERN_INFO "attempt to access beyond end of device\n");
2990 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
2991 bdevname(bio->bi_bdev, b),
2992 bio->bi_rw,
2993 (unsigned long long)bio->bi_sector + bio_sectors(bio),
2994 (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
2996 set_bit(BIO_EOF, &bio->bi_flags);
2999 /**
3000 * generic_make_request: hand a buffer to its device driver for I/O
3001 * @bio: The bio describing the location in memory and on the device.
3003 * generic_make_request() is used to make I/O requests of block
3004 * devices. It is passed a &struct bio, which describes the I/O that needs
3005 * to be done.
3007 * generic_make_request() does not return any status. The
3008 * success/failure status of the request, along with notification of
3009 * completion, is delivered asynchronously through the bio->bi_end_io
3010 * function described (one day) else where.
3012 * The caller of generic_make_request must make sure that bi_io_vec
3013 * are set to describe the memory buffer, and that bi_dev and bi_sector are
3014 * set to describe the device address, and the
3015 * bi_end_io and optionally bi_private are set to describe how
3016 * completion notification should be signaled.
3018 * generic_make_request and the drivers it calls may use bi_next if this
3019 * bio happens to be merged with someone else, and may change bi_dev and
3020 * bi_sector for remaps as it sees fit. So the values of these fields
3021 * should NOT be depended on after the call to generic_make_request.
3022 */
3023 void generic_make_request(struct bio *bio)
3025 request_queue_t *q;
3026 sector_t maxsector;
3027 sector_t old_sector;
3028 int ret, nr_sectors = bio_sectors(bio);
3029 dev_t old_dev;
3031 might_sleep();
3032 /* Test device or partition size, when known. */
3033 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
3034 if (maxsector && nr_sectors) {
3035 sector_t sector = bio->bi_sector;
3037 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
3038 /*
3039 * This may well happen - the kernel calls bread()
3040 * without checking the size of the device, e.g., when
3041 * mounting a device.
3042 */
3043 handle_bad_sector(bio);
3044 goto end_io;
3048 /*
3049 * Resolve the mapping until finished. (drivers are
3050 * still free to implement/resolve their own stacking
3051 * by explicitly returning 0)
3053 * NOTE: we don't repeat the blk_size check for each new device.
3054 * Stacking drivers are expected to know what they are doing.
3055 */
3056 old_sector = -1;
3057 old_dev = 0;
3058 do {
3059 char b[BDEVNAME_SIZE];
3061 q = bdev_get_queue(bio->bi_bdev);
3062 if (!q) {
3063 printk(KERN_ERR
3064 "generic_make_request: Trying to access "
3065 "nonexistent block-device %s (%Lu)\n",
3066 bdevname(bio->bi_bdev, b),
3067 (long long) bio->bi_sector);
3068 end_io:
3069 bio_endio(bio, bio->bi_size, -EIO);
3070 break;
3073 if (unlikely(bio_sectors(bio) > q->max_hw_sectors)) {
3074 printk("bio too big device %s (%u > %u)\n",
3075 bdevname(bio->bi_bdev, b),
3076 bio_sectors(bio),
3077 q->max_hw_sectors);
3078 goto end_io;
3081 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
3082 goto end_io;
3084 /*
3085 * If this device has partitions, remap block n
3086 * of partition p to block n+start(p) of the disk.
3087 */
3088 blk_partition_remap(bio);
3090 if (old_sector != -1)
3091 blk_add_trace_remap(q, bio, old_dev, bio->bi_sector,
3092 old_sector);
3094 blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
3096 old_sector = bio->bi_sector;
3097 old_dev = bio->bi_bdev->bd_dev;
3099 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
3100 if (maxsector && nr_sectors) {
3101 sector_t sector = bio->bi_sector;
3103 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
3104 /*
3105 * This may well happen - partitions are not checked
3106 * to make sure they are within the size of the
3107 * whole device.
3108 */
3109 handle_bad_sector(bio);
3110 goto end_io;
3114 ret = q->make_request_fn(q, bio);
3115 } while (ret);
3118 EXPORT_SYMBOL(generic_make_request);
3120 /**
3121 * submit_bio: submit a bio to the block device layer for I/O
3122 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
3123 * @bio: The &struct bio which describes the I/O
3125 * submit_bio() is very similar in purpose to generic_make_request(), and
3126 * uses that function to do most of the work. Both are fairly rough
3127 * interfaces, @bio must be presetup and ready for I/O.
3129 */
3130 void submit_bio(int rw, struct bio *bio)
3132 int count = bio_sectors(bio);
3134 bio->bi_rw |= rw;
3136 if (!bio_empty_barrier(bio)) {
3137 BIO_BUG_ON(!bio->bi_size);
3138 BIO_BUG_ON(!bio->bi_io_vec);
3140 if (rw & WRITE)
3141 count_vm_events(PGPGOUT, count);
3142 else
3143 count_vm_events(PGPGIN, count);
3145 if (unlikely(block_dump)) {
3146 char b[BDEVNAME_SIZE];
3147 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
3148 current->comm, current->pid,
3149 (rw & WRITE) ? "WRITE" : "READ",
3150 (unsigned long long)bio->bi_sector,
3151 bdevname(bio->bi_bdev,b));
3155 generic_make_request(bio);
3158 EXPORT_SYMBOL(submit_bio);
3160 static void blk_recalc_rq_segments(struct request *rq)
3162 struct bio *bio, *prevbio = NULL;
3163 int nr_phys_segs, nr_hw_segs;
3164 unsigned int phys_size, hw_size;
3165 request_queue_t *q = rq->q;
3167 if (!rq->bio)
3168 return;
3170 phys_size = hw_size = nr_phys_segs = nr_hw_segs = 0;
3171 rq_for_each_bio(bio, rq) {
3172 /* Force bio hw/phys segs to be recalculated. */
3173 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
3175 nr_phys_segs += bio_phys_segments(q, bio);
3176 nr_hw_segs += bio_hw_segments(q, bio);
3177 if (prevbio) {
3178 int pseg = phys_size + prevbio->bi_size + bio->bi_size;
3179 int hseg = hw_size + prevbio->bi_size + bio->bi_size;
3181 if (blk_phys_contig_segment(q, prevbio, bio) &&
3182 pseg <= q->max_segment_size) {
3183 nr_phys_segs--;
3184 phys_size += prevbio->bi_size + bio->bi_size;
3185 } else
3186 phys_size = 0;
3188 if (blk_hw_contig_segment(q, prevbio, bio) &&
3189 hseg <= q->max_segment_size) {
3190 nr_hw_segs--;
3191 hw_size += prevbio->bi_size + bio->bi_size;
3192 } else
3193 hw_size = 0;
3195 prevbio = bio;
3198 rq->nr_phys_segments = nr_phys_segs;
3199 rq->nr_hw_segments = nr_hw_segs;
3202 static void blk_recalc_rq_sectors(struct request *rq, int nsect)
3204 if (blk_fs_request(rq)) {
3205 rq->hard_sector += nsect;
3206 rq->hard_nr_sectors -= nsect;
3208 /*
3209 * Move the I/O submission pointers ahead if required.
3210 */
3211 if ((rq->nr_sectors >= rq->hard_nr_sectors) &&
3212 (rq->sector <= rq->hard_sector)) {
3213 rq->sector = rq->hard_sector;
3214 rq->nr_sectors = rq->hard_nr_sectors;
3215 rq->hard_cur_sectors = bio_cur_sectors(rq->bio);
3216 rq->current_nr_sectors = rq->hard_cur_sectors;
3217 rq->buffer = bio_data(rq->bio);
3220 /*
3221 * if total number of sectors is less than the first segment
3222 * size, something has gone terribly wrong
3223 */
3224 if (rq->nr_sectors < rq->current_nr_sectors) {
3225 printk("blk: request botched\n");
3226 rq->nr_sectors = rq->current_nr_sectors;
3231 static int __end_that_request_first(struct request *req, int uptodate,
3232 int nr_bytes)
3234 int total_bytes, bio_nbytes, error, next_idx = 0;
3235 struct bio *bio;
3237 blk_add_trace_rq(req->q, req, BLK_TA_COMPLETE);
3239 /*
3240 * extend uptodate bool to allow < 0 value to be direct io error
3241 */
3242 error = 0;
3243 if (end_io_error(uptodate))
3244 error = !uptodate ? -EIO : uptodate;
3246 /*
3247 * for a REQ_BLOCK_PC request, we want to carry any eventual
3248 * sense key with us all the way through
3249 */
3250 if (!blk_pc_request(req))
3251 req->errors = 0;
3253 if (!uptodate) {
3254 if (blk_fs_request(req) && !(req->flags & REQ_QUIET))
3255 printk("end_request: I/O error, dev %s, sector %llu\n",
3256 req->rq_disk ? req->rq_disk->disk_name : "?",
3257 (unsigned long long)req->sector);
3260 if (blk_fs_request(req) && req->rq_disk) {
3261 const int rw = rq_data_dir(req);
3263 disk_stat_add(req->rq_disk, sectors[rw], nr_bytes >> 9);
3266 total_bytes = bio_nbytes = 0;
3267 while ((bio = req->bio) != NULL) {
3268 int nbytes;
3270 /* For an empty barrier request, the low level driver must
3271 * store a potential error location in ->sector. We pass
3272 * that back up in ->bi_sector
3273 */
3274 if (blk_empty_barrier(req))
3275 bio->bi_sector = req->sector;
3277 if (nr_bytes >= bio->bi_size) {
3278 req->bio = bio->bi_next;
3279 nbytes = bio->bi_size;
3280 if (!ordered_bio_endio(req, bio, nbytes, error))
3281 bio_endio(bio, nbytes, error);
3282 next_idx = 0;
3283 bio_nbytes = 0;
3284 } else {
3285 int idx = bio->bi_idx + next_idx;
3287 if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
3288 blk_dump_rq_flags(req, "__end_that");
3289 printk("%s: bio idx %d >= vcnt %d\n",
3290 __FUNCTION__,
3291 bio->bi_idx, bio->bi_vcnt);
3292 break;
3295 nbytes = bio_iovec_idx(bio, idx)->bv_len;
3296 BIO_BUG_ON(nbytes > bio->bi_size);
3298 /*
3299 * not a complete bvec done
3300 */
3301 if (unlikely(nbytes > nr_bytes)) {
3302 bio_nbytes += nr_bytes;
3303 total_bytes += nr_bytes;
3304 break;
3307 /*
3308 * advance to the next vector
3309 */
3310 next_idx++;
3311 bio_nbytes += nbytes;
3314 total_bytes += nbytes;
3315 nr_bytes -= nbytes;
3317 if ((bio = req->bio)) {
3318 /*
3319 * end more in this run, or just return 'not-done'
3320 */
3321 if (unlikely(nr_bytes <= 0))
3322 break;
3326 /*
3327 * completely done
3328 */
3329 if (!req->bio)
3330 return 0;
3332 /*
3333 * if the request wasn't completed, update state
3334 */
3335 if (bio_nbytes) {
3336 if (!ordered_bio_endio(req, bio, bio_nbytes, error))
3337 bio_endio(bio, bio_nbytes, error);
3338 bio->bi_idx += next_idx;
3339 bio_iovec(bio)->bv_offset += nr_bytes;
3340 bio_iovec(bio)->bv_len -= nr_bytes;
3343 blk_recalc_rq_sectors(req, total_bytes >> 9);
3344 blk_recalc_rq_segments(req);
3345 return 1;
3348 /**
3349 * end_that_request_first - end I/O on a request
3350 * @req: the request being processed
3351 * @uptodate: 1 for success, 0 for I/O error, < 0 for specific error
3352 * @nr_sectors: number of sectors to end I/O on
3354 * Description:
3355 * Ends I/O on a number of sectors attached to @req, and sets it up
3356 * for the next range of segments (if any) in the cluster.
3358 * Return:
3359 * 0 - we are done with this request, call end_that_request_last()
3360 * 1 - still buffers pending for this request
3361 **/
3362 int end_that_request_first(struct request *req, int uptodate, int nr_sectors)
3364 return __end_that_request_first(req, uptodate, nr_sectors << 9);
3367 EXPORT_SYMBOL(end_that_request_first);
3369 /**
3370 * end_that_request_chunk - end I/O on a request
3371 * @req: the request being processed
3372 * @uptodate: 1 for success, 0 for I/O error, < 0 for specific error
3373 * @nr_bytes: number of bytes to complete
3375 * Description:
3376 * Ends I/O on a number of bytes attached to @req, and sets it up
3377 * for the next range of segments (if any). Like end_that_request_first(),
3378 * but deals with bytes instead of sectors.
3380 * Return:
3381 * 0 - we are done with this request, call end_that_request_last()
3382 * 1 - still buffers pending for this request
3383 **/
3384 int end_that_request_chunk(struct request *req, int uptodate, int nr_bytes)
3386 return __end_that_request_first(req, uptodate, nr_bytes);
3389 EXPORT_SYMBOL(end_that_request_chunk);
3391 /*
3392 * splice the completion data to a local structure and hand off to
3393 * process_completion_queue() to complete the requests
3394 */
3395 static void blk_done_softirq(struct softirq_action *h)
3397 struct list_head *cpu_list, local_list;
3399 local_irq_disable();
3400 cpu_list = &__get_cpu_var(blk_cpu_done);
3401 list_replace_init(cpu_list, &local_list);
3402 local_irq_enable();
3404 while (!list_empty(&local_list)) {
3405 struct request *rq = list_entry(local_list.next, struct request, donelist);
3407 list_del_init(&rq->donelist);
3408 rq->q->softirq_done_fn(rq);
3412 #ifdef CONFIG_HOTPLUG_CPU
3414 static int blk_cpu_notify(struct notifier_block *self, unsigned long action,
3415 void *hcpu)
3417 /*
3418 * If a CPU goes away, splice its entries to the current CPU
3419 * and trigger a run of the softirq
3420 */
3421 if (action == CPU_DEAD) {
3422 int cpu = (unsigned long) hcpu;
3424 local_irq_disable();
3425 list_splice_init(&per_cpu(blk_cpu_done, cpu),
3426 &__get_cpu_var(blk_cpu_done));
3427 raise_softirq_irqoff(BLOCK_SOFTIRQ);
3428 local_irq_enable();
3431 return NOTIFY_OK;
3435 static struct notifier_block __devinitdata blk_cpu_notifier = {
3436 .notifier_call = blk_cpu_notify,
3437 };
3439 #endif /* CONFIG_HOTPLUG_CPU */
3441 /**
3442 * blk_complete_request - end I/O on a request
3443 * @req: the request being processed
3445 * Description:
3446 * Ends all I/O on a request. It does not handle partial completions,
3447 * unless the driver actually implements this in its completion callback
3448 * through requeueing. Theh actual completion happens out-of-order,
3449 * through a softirq handler. The user must have registered a completion
3450 * callback through blk_queue_softirq_done().
3451 **/
3453 void blk_complete_request(struct request *req)
3455 struct list_head *cpu_list;
3456 unsigned long flags;
3458 BUG_ON(!req->q->softirq_done_fn);
3460 local_irq_save(flags);
3462 cpu_list = &__get_cpu_var(blk_cpu_done);
3463 list_add_tail(&req->donelist, cpu_list);
3464 raise_softirq_irqoff(BLOCK_SOFTIRQ);
3466 local_irq_restore(flags);
3469 EXPORT_SYMBOL(blk_complete_request);
3471 /*
3472 * queue lock must be held
3473 */
3474 void end_that_request_last(struct request *req, int uptodate)
3476 struct gendisk *disk = req->rq_disk;
3477 int error;
3479 /*
3480 * extend uptodate bool to allow < 0 value to be direct io error
3481 */
3482 error = 0;
3483 if (end_io_error(uptodate))
3484 error = !uptodate ? -EIO : uptodate;
3486 if (unlikely(laptop_mode) && blk_fs_request(req))
3487 laptop_io_completion();
3489 /*
3490 * Account IO completion. bar_rq isn't accounted as a normal
3491 * IO on queueing nor completion. Accounting the containing
3492 * request is enough.
3493 */
3494 if (disk && blk_fs_request(req) && req != &req->q->bar_rq) {
3495 unsigned long duration = jiffies - req->start_time;
3496 const int rw = rq_data_dir(req);
3498 __disk_stat_inc(disk, ios[rw]);
3499 __disk_stat_add(disk, ticks[rw], duration);
3500 disk_round_stats(disk);
3501 disk->in_flight--;
3503 if (req->end_io)
3504 req->end_io(req, error);
3505 else
3506 __blk_put_request(req->q, req);
3509 EXPORT_SYMBOL(end_that_request_last);
3511 void end_request(struct request *req, int uptodate)
3513 if (!end_that_request_first(req, uptodate, req->hard_cur_sectors)) {
3514 add_disk_randomness(req->rq_disk);
3515 blkdev_dequeue_request(req);
3516 end_that_request_last(req, uptodate);
3520 EXPORT_SYMBOL(end_request);
3522 void blk_rq_bio_prep(request_queue_t *q, struct request *rq, struct bio *bio)
3524 /* first two bits are identical in rq->flags and bio->bi_rw */
3525 rq->flags |= (bio->bi_rw & 3);
3527 rq->nr_phys_segments = bio_phys_segments(q, bio);
3528 rq->nr_hw_segments = bio_hw_segments(q, bio);
3529 rq->current_nr_sectors = bio_cur_sectors(bio);
3530 rq->hard_cur_sectors = rq->current_nr_sectors;
3531 rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
3532 rq->buffer = bio_data(bio);
3534 rq->bio = rq->biotail = bio;
3537 EXPORT_SYMBOL(blk_rq_bio_prep);
3539 int kblockd_schedule_work(struct work_struct *work)
3541 return queue_work(kblockd_workqueue, work);
3544 EXPORT_SYMBOL(kblockd_schedule_work);
3546 void kblockd_flush(void)
3548 flush_workqueue(kblockd_workqueue);
3550 EXPORT_SYMBOL(kblockd_flush);
3552 int __init blk_dev_init(void)
3554 int i;
3556 kblockd_workqueue = create_workqueue("kblockd");
3557 if (!kblockd_workqueue)
3558 panic("Failed to create kblockd\n");
3560 request_cachep = kmem_cache_create("blkdev_requests",
3561 sizeof(struct request), 0, SLAB_PANIC, NULL, NULL);
3563 requestq_cachep = kmem_cache_create("blkdev_queue",
3564 sizeof(request_queue_t), 0, SLAB_PANIC, NULL, NULL);
3566 iocontext_cachep = kmem_cache_create("blkdev_ioc",
3567 sizeof(struct io_context), 0, SLAB_PANIC, NULL, NULL);
3569 for_each_possible_cpu(i)
3570 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
3572 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq, NULL);
3573 register_hotcpu_notifier(&blk_cpu_notifier);
3575 blk_max_low_pfn = max_low_pfn;
3576 blk_max_pfn = max_pfn;
3578 return 0;
3581 /*
3582 * IO Context helper functions
3583 */
3584 void put_io_context(struct io_context *ioc)
3586 if (ioc == NULL)
3587 return;
3589 BUG_ON(atomic_read(&ioc->refcount) == 0);
3591 if (atomic_dec_and_test(&ioc->refcount)) {
3592 struct cfq_io_context *cic;
3594 rcu_read_lock();
3595 if (ioc->aic && ioc->aic->dtor)
3596 ioc->aic->dtor(ioc->aic);
3597 if (ioc->cic_root.rb_node != NULL) {
3598 struct rb_node *n = rb_first(&ioc->cic_root);
3600 cic = rb_entry(n, struct cfq_io_context, rb_node);
3601 cic->dtor(ioc);
3603 rcu_read_unlock();
3605 kmem_cache_free(iocontext_cachep, ioc);
3608 EXPORT_SYMBOL(put_io_context);
3610 /* Called by the exitting task */
3611 void exit_io_context(void)
3613 unsigned long flags;
3614 struct io_context *ioc;
3615 struct cfq_io_context *cic;
3617 local_irq_save(flags);
3618 task_lock(current);
3619 ioc = current->io_context;
3620 current->io_context = NULL;
3621 ioc->task = NULL;
3622 task_unlock(current);
3623 local_irq_restore(flags);
3625 if (ioc->aic && ioc->aic->exit)
3626 ioc->aic->exit(ioc->aic);
3627 if (ioc->cic_root.rb_node != NULL) {
3628 cic = rb_entry(rb_first(&ioc->cic_root), struct cfq_io_context, rb_node);
3629 cic->exit(ioc);
3632 put_io_context(ioc);
3635 /*
3636 * If the current task has no IO context then create one and initialise it.
3637 * Otherwise, return its existing IO context.
3639 * This returned IO context doesn't have a specifically elevated refcount,
3640 * but since the current task itself holds a reference, the context can be
3641 * used in general code, so long as it stays within `current` context.
3642 */
3643 struct io_context *current_io_context(gfp_t gfp_flags)
3645 struct task_struct *tsk = current;
3646 struct io_context *ret;
3648 ret = tsk->io_context;
3649 if (likely(ret))
3650 return ret;
3652 ret = kmem_cache_alloc(iocontext_cachep, gfp_flags);
3653 if (ret) {
3654 atomic_set(&ret->refcount, 1);
3655 ret->task = current;
3656 ret->set_ioprio = NULL;
3657 ret->last_waited = jiffies; /* doesn't matter... */
3658 ret->nr_batch_requests = 0; /* because this is 0 */
3659 ret->aic = NULL;
3660 ret->cic_root.rb_node = NULL;
3661 /* make sure set_task_ioprio() sees the settings above */
3662 smp_wmb();
3663 tsk->io_context = ret;
3666 return ret;
3668 EXPORT_SYMBOL(current_io_context);
3670 /*
3671 * If the current task has no IO context then create one and initialise it.
3672 * If it does have a context, take a ref on it.
3674 * This is always called in the context of the task which submitted the I/O.
3675 */
3676 struct io_context *get_io_context(gfp_t gfp_flags)
3678 struct io_context *ret;
3679 ret = current_io_context(gfp_flags);
3680 if (likely(ret))
3681 atomic_inc(&ret->refcount);
3682 return ret;
3684 EXPORT_SYMBOL(get_io_context);
3686 void copy_io_context(struct io_context **pdst, struct io_context **psrc)
3688 struct io_context *src = *psrc;
3689 struct io_context *dst = *pdst;
3691 if (src) {
3692 BUG_ON(atomic_read(&src->refcount) == 0);
3693 atomic_inc(&src->refcount);
3694 put_io_context(dst);
3695 *pdst = src;
3698 EXPORT_SYMBOL(copy_io_context);
3700 void swap_io_context(struct io_context **ioc1, struct io_context **ioc2)
3702 struct io_context *temp;
3703 temp = *ioc1;
3704 *ioc1 = *ioc2;
3705 *ioc2 = temp;
3707 EXPORT_SYMBOL(swap_io_context);
3709 /*
3710 * sysfs parts below
3711 */
3712 struct queue_sysfs_entry {
3713 struct attribute attr;
3714 ssize_t (*show)(struct request_queue *, char *);
3715 ssize_t (*store)(struct request_queue *, const char *, size_t);
3716 };
3718 static ssize_t
3719 queue_var_show(unsigned int var, char *page)
3721 return sprintf(page, "%d\n", var);
3724 static ssize_t
3725 queue_var_store(unsigned long *var, const char *page, size_t count)
3727 char *p = (char *) page;
3729 *var = simple_strtoul(p, &p, 10);
3730 return count;
3733 static ssize_t queue_requests_show(struct request_queue *q, char *page)
3735 return queue_var_show(q->nr_requests, (page));
3738 static ssize_t
3739 queue_requests_store(struct request_queue *q, const char *page, size_t count)
3741 struct request_list *rl = &q->rq;
3742 unsigned long nr;
3743 int ret = queue_var_store(&nr, page, count);
3744 if (nr < BLKDEV_MIN_RQ)
3745 nr = BLKDEV_MIN_RQ;
3747 spin_lock_irq(q->queue_lock);
3748 q->nr_requests = nr;
3749 blk_queue_congestion_threshold(q);
3751 if (rl->count[READ] >= queue_congestion_on_threshold(q))
3752 set_queue_congested(q, READ);
3753 else if (rl->count[READ] < queue_congestion_off_threshold(q))
3754 clear_queue_congested(q, READ);
3756 if (rl->count[WRITE] >= queue_congestion_on_threshold(q))
3757 set_queue_congested(q, WRITE);
3758 else if (rl->count[WRITE] < queue_congestion_off_threshold(q))
3759 clear_queue_congested(q, WRITE);
3761 if (rl->count[READ] >= q->nr_requests) {
3762 blk_set_queue_full(q, READ);
3763 } else if (rl->count[READ]+1 <= q->nr_requests) {
3764 blk_clear_queue_full(q, READ);
3765 wake_up(&rl->wait[READ]);
3768 if (rl->count[WRITE] >= q->nr_requests) {
3769 blk_set_queue_full(q, WRITE);
3770 } else if (rl->count[WRITE]+1 <= q->nr_requests) {
3771 blk_clear_queue_full(q, WRITE);
3772 wake_up(&rl->wait[WRITE]);
3774 spin_unlock_irq(q->queue_lock);
3775 return ret;
3778 static ssize_t queue_ra_show(struct request_queue *q, char *page)
3780 int ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10);
3782 return queue_var_show(ra_kb, (page));
3785 static ssize_t
3786 queue_ra_store(struct request_queue *q, const char *page, size_t count)
3788 unsigned long ra_kb;
3789 ssize_t ret = queue_var_store(&ra_kb, page, count);
3791 spin_lock_irq(q->queue_lock);
3792 if (ra_kb > (q->max_sectors >> 1))
3793 ra_kb = (q->max_sectors >> 1);
3795 q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10);
3796 spin_unlock_irq(q->queue_lock);
3798 return ret;
3801 static ssize_t queue_max_sectors_show(struct request_queue *q, char *page)
3803 int max_sectors_kb = q->max_sectors >> 1;
3805 return queue_var_show(max_sectors_kb, (page));
3808 static ssize_t
3809 queue_max_sectors_store(struct request_queue *q, const char *page, size_t count)
3811 unsigned long max_sectors_kb,
3812 max_hw_sectors_kb = q->max_hw_sectors >> 1,
3813 page_kb = 1 << (PAGE_CACHE_SHIFT - 10);
3814 ssize_t ret = queue_var_store(&max_sectors_kb, page, count);
3815 int ra_kb;
3817 if (max_sectors_kb > max_hw_sectors_kb || max_sectors_kb < page_kb)
3818 return -EINVAL;
3819 /*
3820 * Take the queue lock to update the readahead and max_sectors
3821 * values synchronously:
3822 */
3823 spin_lock_irq(q->queue_lock);
3824 /*
3825 * Trim readahead window as well, if necessary:
3826 */
3827 ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10);
3828 if (ra_kb > max_sectors_kb)
3829 q->backing_dev_info.ra_pages =
3830 max_sectors_kb >> (PAGE_CACHE_SHIFT - 10);
3832 q->max_sectors = max_sectors_kb << 1;
3833 spin_unlock_irq(q->queue_lock);
3835 return ret;
3838 static ssize_t queue_max_hw_sectors_show(struct request_queue *q, char *page)
3840 int max_hw_sectors_kb = q->max_hw_sectors >> 1;
3842 return queue_var_show(max_hw_sectors_kb, (page));
3846 static struct queue_sysfs_entry queue_requests_entry = {
3847 .attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR },
3848 .show = queue_requests_show,
3849 .store = queue_requests_store,
3850 };
3852 static struct queue_sysfs_entry queue_ra_entry = {
3853 .attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR },
3854 .show = queue_ra_show,
3855 .store = queue_ra_store,
3856 };
3858 static struct queue_sysfs_entry queue_max_sectors_entry = {
3859 .attr = {.name = "max_sectors_kb", .mode = S_IRUGO | S_IWUSR },
3860 .show = queue_max_sectors_show,
3861 .store = queue_max_sectors_store,
3862 };
3864 static struct queue_sysfs_entry queue_max_hw_sectors_entry = {
3865 .attr = {.name = "max_hw_sectors_kb", .mode = S_IRUGO },
3866 .show = queue_max_hw_sectors_show,
3867 };
3869 static struct queue_sysfs_entry queue_iosched_entry = {
3870 .attr = {.name = "scheduler", .mode = S_IRUGO | S_IWUSR },
3871 .show = elv_iosched_show,
3872 .store = elv_iosched_store,
3873 };
3875 static struct attribute *default_attrs[] = {
3876 &queue_requests_entry.attr,
3877 &queue_ra_entry.attr,
3878 &queue_max_hw_sectors_entry.attr,
3879 &queue_max_sectors_entry.attr,
3880 &queue_iosched_entry.attr,
3881 NULL,
3882 };
3884 #define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr)
3886 static ssize_t
3887 queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3889 struct queue_sysfs_entry *entry = to_queue(attr);
3890 request_queue_t *q = container_of(kobj, struct request_queue, kobj);
3891 ssize_t res;
3893 if (!entry->show)
3894 return -EIO;
3895 mutex_lock(&q->sysfs_lock);
3896 if (test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)) {
3897 mutex_unlock(&q->sysfs_lock);
3898 return -ENOENT;
3900 res = entry->show(q, page);
3901 mutex_unlock(&q->sysfs_lock);
3902 return res;
3905 static ssize_t
3906 queue_attr_store(struct kobject *kobj, struct attribute *attr,
3907 const char *page, size_t length)
3909 struct queue_sysfs_entry *entry = to_queue(attr);
3910 request_queue_t *q = container_of(kobj, struct request_queue, kobj);
3912 ssize_t res;
3914 if (!entry->store)
3915 return -EIO;
3916 mutex_lock(&q->sysfs_lock);
3917 if (test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)) {
3918 mutex_unlock(&q->sysfs_lock);
3919 return -ENOENT;
3921 res = entry->store(q, page, length);
3922 mutex_unlock(&q->sysfs_lock);
3923 return res;
3926 static struct sysfs_ops queue_sysfs_ops = {
3927 .show = queue_attr_show,
3928 .store = queue_attr_store,
3929 };
3931 static struct kobj_type queue_ktype = {
3932 .sysfs_ops = &queue_sysfs_ops,
3933 .default_attrs = default_attrs,
3934 .release = blk_release_queue,
3935 };
3937 int blk_register_queue(struct gendisk *disk)
3939 int ret;
3941 request_queue_t *q = disk->queue;
3943 if (!q || !q->request_fn)
3944 return -ENXIO;
3946 q->kobj.parent = kobject_get(&disk->kobj);
3948 ret = kobject_add(&q->kobj);
3949 if (ret < 0)
3950 return ret;
3952 kobject_uevent(&q->kobj, KOBJ_ADD);
3954 ret = elv_register_queue(q);
3955 if (ret) {
3956 kobject_uevent(&q->kobj, KOBJ_REMOVE);
3957 kobject_del(&q->kobj);
3958 return ret;
3961 return 0;
3964 void blk_unregister_queue(struct gendisk *disk)
3966 request_queue_t *q = disk->queue;
3968 if (q && q->request_fn) {
3969 elv_unregister_queue(q);
3971 kobject_uevent(&q->kobj, KOBJ_REMOVE);
3972 kobject_del(&q->kobj);
3973 kobject_put(&disk->kobj);