2 * linux/drivers/block/ll_rw_blk.c
4 * Copyright (C) 1991, 1992 Linus Torvalds
5 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
6 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
7 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
8 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au> - July2000
9 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
13 * This handles all read/write requests to block devices
15 #include <linux/config.h>
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/backing-dev.h>
19 #include <linux/bio.h>
20 #include <linux/blkdev.h>
21 #include <linux/highmem.h>
23 #include <linux/kernel_stat.h>
24 #include <linux/string.h>
25 #include <linux/init.h>
26 #include <linux/bootmem.h> /* for max_pfn/max_low_pfn */
27 #include <linux/completion.h>
28 #include <linux/slab.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
35 #include <scsi/scsi_cmnd.h>
37 static void blk_unplug_work(void *data);
38 static void blk_unplug_timeout(unsigned long data);
41 * For the allocated request tables
43 static kmem_cache_t *request_cachep;
46 * For queue allocation
48 static kmem_cache_t *requestq_cachep;
51 * For io context allocations
53 static kmem_cache_t *iocontext_cachep;
55 static wait_queue_head_t congestion_wqh[2] = {
56 __WAIT_QUEUE_HEAD_INITIALIZER(congestion_wqh[0]),
57 __WAIT_QUEUE_HEAD_INITIALIZER(congestion_wqh[1])
61 * Controlling structure to kblockd
63 static struct workqueue_struct *kblockd_workqueue;
65 unsigned long blk_max_low_pfn, blk_max_pfn;
67 EXPORT_SYMBOL(blk_max_low_pfn);
68 EXPORT_SYMBOL(blk_max_pfn);
70 /* Amount of time in which a process may batch requests */
71 #define BLK_BATCH_TIME (HZ/50UL)
73 /* Number of requests a "batching" process may submit */
74 #define BLK_BATCH_REQ 32
77 * Return the threshold (number of used requests) at which the queue is
78 * considered to be congested. It include a little hysteresis to keep the
79 * context switch rate down.
81 static inline int queue_congestion_on_threshold(struct request_queue *q)
83 return q->nr_congestion_on;
87 * The threshold at which a queue is considered to be uncongested
89 static inline int queue_congestion_off_threshold(struct request_queue *q)
91 return q->nr_congestion_off;
94 static void blk_queue_congestion_threshold(struct request_queue *q)
98 nr = q->nr_requests - (q->nr_requests / 8) + 1;
99 if (nr > q->nr_requests)
101 q->nr_congestion_on = nr;
103 nr = q->nr_requests - (q->nr_requests / 8) - 1;
106 q->nr_congestion_off = nr;
110 * A queue has just exitted congestion. Note this in the global counter of
111 * congested queues, and wake up anyone who was waiting for requests to be
114 static void clear_queue_congested(request_queue_t *q, int rw)
117 wait_queue_head_t *wqh = &congestion_wqh[rw];
119 bit = (rw == WRITE) ? BDI_write_congested : BDI_read_congested;
120 clear_bit(bit, &q->backing_dev_info.state);
121 smp_mb__after_clear_bit();
122 if (waitqueue_active(wqh))
127 * A queue has just entered congestion. Flag that in the queue's VM-visible
128 * state flags and increment the global gounter of congested queues.
130 static void set_queue_congested(request_queue_t *q, int rw)
134 bit = (rw == WRITE) ? BDI_write_congested : BDI_read_congested;
135 set_bit(bit, &q->backing_dev_info.state);
139 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
142 * Locates the passed device's request queue and returns the address of its
145 * Will return NULL if the request queue cannot be located.
147 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
149 struct backing_dev_info *ret = NULL;
150 request_queue_t *q = bdev_get_queue(bdev);
153 ret = &q->backing_dev_info;
157 void blk_queue_activity_fn(request_queue_t *q, activity_fn *fn, void *data)
160 q->activity_data = data;
163 EXPORT_SYMBOL(blk_queue_activity_fn);
166 * blk_queue_prep_rq - set a prepare_request function for queue
168 * @pfn: prepare_request function
170 * It's possible for a queue to register a prepare_request callback which
171 * is invoked before the request is handed to the request_fn. The goal of
172 * the function is to prepare a request for I/O, it can be used to build a
173 * cdb from the request data for instance.
176 void blk_queue_prep_rq(request_queue_t *q, prep_rq_fn *pfn)
181 EXPORT_SYMBOL(blk_queue_prep_rq);
184 * blk_queue_merge_bvec - set a merge_bvec function for queue
186 * @mbfn: merge_bvec_fn
188 * Usually queues have static limitations on the max sectors or segments that
189 * we can put in a request. Stacking drivers may have some settings that
190 * are dynamic, and thus we have to query the queue whether it is ok to
191 * add a new bio_vec to a bio at a given offset or not. If the block device
192 * has such limitations, it needs to register a merge_bvec_fn to control
193 * the size of bio's sent to it. Note that a block device *must* allow a
194 * single page to be added to an empty bio. The block device driver may want
195 * to use the bio_split() function to deal with these bio's. By default
196 * no merge_bvec_fn is defined for a queue, and only the fixed limits are
199 void blk_queue_merge_bvec(request_queue_t *q, merge_bvec_fn *mbfn)
201 q->merge_bvec_fn = mbfn;
204 EXPORT_SYMBOL(blk_queue_merge_bvec);
207 * blk_queue_make_request - define an alternate make_request function for a device
208 * @q: the request queue for the device to be affected
209 * @mfn: the alternate make_request function
212 * The normal way for &struct bios to be passed to a device
213 * driver is for them to be collected into requests on a request
214 * queue, and then to allow the device driver to select requests
215 * off that queue when it is ready. This works well for many block
216 * devices. However some block devices (typically virtual devices
217 * such as md or lvm) do not benefit from the processing on the
218 * request queue, and are served best by having the requests passed
219 * directly to them. This can be achieved by providing a function
220 * to blk_queue_make_request().
223 * The driver that does this *must* be able to deal appropriately
224 * with buffers in "highmemory". This can be accomplished by either calling
225 * __bio_kmap_atomic() to get a temporary kernel mapping, or by calling
226 * blk_queue_bounce() to create a buffer in normal memory.
228 void blk_queue_make_request(request_queue_t * q, make_request_fn * mfn)
233 q->nr_requests = BLKDEV_MAX_RQ;
234 q->max_phys_segments = MAX_PHYS_SEGMENTS;
235 q->max_hw_segments = MAX_HW_SEGMENTS;
236 q->make_request_fn = mfn;
237 q->backing_dev_info.ra_pages = (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
238 q->backing_dev_info.state = 0;
239 q->backing_dev_info.memory_backed = 0;
240 blk_queue_max_sectors(q, MAX_SECTORS);
241 blk_queue_hardsect_size(q, 512);
242 blk_queue_dma_alignment(q, 511);
243 blk_queue_congestion_threshold(q);
245 q->unplug_thresh = 4; /* hmm */
246 q->unplug_delay = (3 * HZ) / 1000; /* 3 milliseconds */
247 if (q->unplug_delay == 0)
250 INIT_WORK(&q->unplug_work, blk_unplug_work, q);
252 q->unplug_timer.function = blk_unplug_timeout;
253 q->unplug_timer.data = (unsigned long)q;
256 * by default assume old behaviour and bounce for any highmem page
258 blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
260 blk_queue_activity_fn(q, NULL, NULL);
263 EXPORT_SYMBOL(blk_queue_make_request);
266 * blk_queue_bounce_limit - set bounce buffer limit for queue
267 * @q: the request queue for the device
268 * @dma_addr: bus address limit
271 * Different hardware can have different requirements as to what pages
272 * it can do I/O directly to. A low level driver can call
273 * blk_queue_bounce_limit to have lower memory pages allocated as bounce
274 * buffers for doing I/O to pages residing above @page. By default
275 * the block layer sets this to the highest numbered "low" memory page.
277 void blk_queue_bounce_limit(request_queue_t *q, u64 dma_addr)
279 unsigned long bounce_pfn = dma_addr >> PAGE_SHIFT;
282 * set appropriate bounce gfp mask -- unfortunately we don't have a
283 * full 4GB zone, so we have to resort to low memory for any bounces.
284 * ISA has its own < 16MB zone.
286 if (bounce_pfn < blk_max_low_pfn) {
287 BUG_ON(dma_addr < BLK_BOUNCE_ISA);
288 init_emergency_isa_pool();
289 q->bounce_gfp = GFP_NOIO | GFP_DMA;
291 q->bounce_gfp = GFP_NOIO;
293 q->bounce_pfn = bounce_pfn;
296 EXPORT_SYMBOL(blk_queue_bounce_limit);
299 * blk_queue_max_sectors - set max sectors for a request for this queue
300 * @q: the request queue for the device
301 * @max_sectors: max sectors in the usual 512b unit
304 * Enables a low level driver to set an upper limit on the size of
307 void blk_queue_max_sectors(request_queue_t *q, unsigned short max_sectors)
309 if ((max_sectors << 9) < PAGE_CACHE_SIZE) {
310 max_sectors = 1 << (PAGE_CACHE_SHIFT - 9);
311 printk("%s: set to minimum %d\n", __FUNCTION__, max_sectors);
314 q->max_sectors = max_sectors;
317 EXPORT_SYMBOL(blk_queue_max_sectors);
320 * blk_queue_max_phys_segments - set max phys segments for a request for this queue
321 * @q: the request queue for the device
322 * @max_segments: max number of segments
325 * Enables a low level driver to set an upper limit on the number of
326 * physical data segments in a request. This would be the largest sized
327 * scatter list the driver could handle.
329 void blk_queue_max_phys_segments(request_queue_t *q, unsigned short max_segments)
333 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
336 q->max_phys_segments = max_segments;
339 EXPORT_SYMBOL(blk_queue_max_phys_segments);
342 * blk_queue_max_hw_segments - set max hw segments for a request for this queue
343 * @q: the request queue for the device
344 * @max_segments: max number of segments
347 * Enables a low level driver to set an upper limit on the number of
348 * hw data segments in a request. This would be the largest number of
349 * address/length pairs the host adapter can actually give as once
352 void blk_queue_max_hw_segments(request_queue_t *q, unsigned short max_segments)
356 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
359 q->max_hw_segments = max_segments;
362 EXPORT_SYMBOL(blk_queue_max_hw_segments);
365 * blk_queue_max_segment_size - set max segment size for blk_rq_map_sg
366 * @q: the request queue for the device
367 * @max_size: max size of segment in bytes
370 * Enables a low level driver to set an upper limit on the size of a
373 void blk_queue_max_segment_size(request_queue_t *q, unsigned int max_size)
375 if (max_size < PAGE_CACHE_SIZE) {
376 max_size = PAGE_CACHE_SIZE;
377 printk("%s: set to minimum %d\n", __FUNCTION__, max_size);
380 q->max_segment_size = max_size;
383 EXPORT_SYMBOL(blk_queue_max_segment_size);
386 * blk_queue_hardsect_size - set hardware sector size for the queue
387 * @q: the request queue for the device
388 * @size: the hardware sector size, in bytes
391 * This should typically be set to the lowest possible sector size
392 * that the hardware can operate on (possible without reverting to
393 * even internal read-modify-write operations). Usually the default
394 * of 512 covers most hardware.
396 void blk_queue_hardsect_size(request_queue_t *q, unsigned short size)
398 q->hardsect_size = size;
401 EXPORT_SYMBOL(blk_queue_hardsect_size);
404 * Returns the minimum that is _not_ zero, unless both are zero.
406 #define min_not_zero(l, r) (l == 0) ? r : ((r == 0) ? l : min(l, r))
409 * blk_queue_stack_limits - inherit underlying queue limits for stacked drivers
410 * @t: the stacking driver (top)
411 * @b: the underlying device (bottom)
413 void blk_queue_stack_limits(request_queue_t *t, request_queue_t *b)
415 /* zero is "infinity" */
416 t->max_sectors = min_not_zero(t->max_sectors,b->max_sectors);
418 t->max_phys_segments = min(t->max_phys_segments,b->max_phys_segments);
419 t->max_hw_segments = min(t->max_hw_segments,b->max_hw_segments);
420 t->max_segment_size = min(t->max_segment_size,b->max_segment_size);
421 t->hardsect_size = max(t->hardsect_size,b->hardsect_size);
424 EXPORT_SYMBOL(blk_queue_stack_limits);
427 * blk_queue_segment_boundary - set boundary rules for segment merging
428 * @q: the request queue for the device
429 * @mask: the memory boundary mask
431 void blk_queue_segment_boundary(request_queue_t *q, unsigned long mask)
433 if (mask < PAGE_CACHE_SIZE - 1) {
434 mask = PAGE_CACHE_SIZE - 1;
435 printk("%s: set to minimum %lx\n", __FUNCTION__, mask);
438 q->seg_boundary_mask = mask;
441 EXPORT_SYMBOL(blk_queue_segment_boundary);
444 * blk_queue_dma_alignment - set dma length and memory alignment
445 * @q: the request queue for the device
446 * @mask: alignment mask
449 * set required memory and length aligment for direct dma transactions.
450 * this is used when buiding direct io requests for the queue.
453 void blk_queue_dma_alignment(request_queue_t *q, int mask)
455 q->dma_alignment = mask;
458 EXPORT_SYMBOL(blk_queue_dma_alignment);
461 * blk_queue_find_tag - find a request by its tag and queue
463 * @q: The request queue for the device
464 * @tag: The tag of the request
467 * Should be used when a device returns a tag and you want to match
470 * no locks need be held.
472 struct request *blk_queue_find_tag(request_queue_t *q, int tag)
474 struct blk_queue_tag *bqt = q->queue_tags;
476 if (unlikely(bqt == NULL || tag >= bqt->real_max_depth))
479 return bqt->tag_index[tag];
482 EXPORT_SYMBOL(blk_queue_find_tag);
485 * blk_queue_free_tags - release tag maintenance info
486 * @q: the request queue for the device
489 * blk_cleanup_queue() will take care of calling this function, if tagging
490 * has been used. So there's usually no need to call this directly, unless
491 * tagging is just being disabled but the queue remains in function.
493 void blk_queue_free_tags(request_queue_t *q)
495 struct blk_queue_tag *bqt = q->queue_tags;
500 if (atomic_dec_and_test(&bqt->refcnt)) {
502 BUG_ON(!list_empty(&bqt->busy_list));
504 kfree(bqt->tag_index);
505 bqt->tag_index = NULL;
513 q->queue_tags = NULL;
514 q->queue_flags &= ~(1 << QUEUE_FLAG_QUEUED);
517 EXPORT_SYMBOL(blk_queue_free_tags);
520 init_tag_map(request_queue_t *q, struct blk_queue_tag *tags, int depth)
524 if (depth > q->nr_requests * 2) {
525 depth = q->nr_requests * 2;
526 printk(KERN_ERR "%s: adjusted depth to %d\n",
527 __FUNCTION__, depth);
530 tags->tag_index = kmalloc(depth * sizeof(struct request *), GFP_ATOMIC);
531 if (!tags->tag_index)
534 bits = (depth / BLK_TAGS_PER_LONG) + 1;
535 tags->tag_map = kmalloc(bits * sizeof(unsigned long), GFP_ATOMIC);
539 memset(tags->tag_index, 0, depth * sizeof(struct request *));
540 memset(tags->tag_map, 0, bits * sizeof(unsigned long));
541 tags->max_depth = depth;
542 tags->real_max_depth = bits * BITS_PER_LONG;
545 * set the upper bits if the depth isn't a multiple of the word size
547 for (i = depth; i < bits * BLK_TAGS_PER_LONG; i++)
548 __set_bit(i, tags->tag_map);
550 INIT_LIST_HEAD(&tags->busy_list);
552 atomic_set(&tags->refcnt, 1);
555 kfree(tags->tag_index);
560 * blk_queue_init_tags - initialize the queue tag info
561 * @q: the request queue for the device
562 * @depth: the maximum queue depth supported
564 int blk_queue_init_tags(request_queue_t *q, int depth,
565 struct blk_queue_tag *tags)
568 tags = kmalloc(sizeof(struct blk_queue_tag), GFP_ATOMIC);
572 if (init_tag_map(q, tags, depth))
575 atomic_inc(&tags->refcnt);
578 * assign it, all done
580 q->queue_tags = tags;
581 q->queue_flags |= (1 << QUEUE_FLAG_QUEUED);
588 EXPORT_SYMBOL(blk_queue_init_tags);
591 * blk_queue_resize_tags - change the queueing depth
592 * @q: the request queue for the device
593 * @new_depth: the new max command queueing depth
596 * Must be called with the queue lock held.
598 int blk_queue_resize_tags(request_queue_t *q, int new_depth)
600 struct blk_queue_tag *bqt = q->queue_tags;
601 struct request **tag_index;
602 unsigned long *tag_map;
609 * don't bother sizing down
611 if (new_depth <= bqt->real_max_depth) {
612 bqt->max_depth = new_depth;
617 * save the old state info, so we can copy it back
619 tag_index = bqt->tag_index;
620 tag_map = bqt->tag_map;
621 max_depth = bqt->real_max_depth;
623 if (init_tag_map(q, bqt, new_depth))
626 memcpy(bqt->tag_index, tag_index, max_depth * sizeof(struct request *));
627 bits = max_depth / BLK_TAGS_PER_LONG;
628 memcpy(bqt->tag_map, tag_map, bits * sizeof(unsigned long));
636 * blk_queue_end_tag - end tag operations for a request
637 * @q: the request queue for the device
638 * @rq: the request that has completed
641 * Typically called when end_that_request_first() returns 0, meaning
642 * all transfers have been done for a request. It's important to call
643 * this function before end_that_request_last(), as that will put the
644 * request back on the free list thus corrupting the internal tag list.
647 * queue lock must be held.
649 void blk_queue_end_tag(request_queue_t *q, struct request *rq)
651 struct blk_queue_tag *bqt = q->queue_tags;
656 if (unlikely(tag >= bqt->real_max_depth))
659 if (unlikely(!__test_and_clear_bit(tag, bqt->tag_map))) {
660 printk("attempt to clear non-busy tag (%d)\n", tag);
664 list_del_init(&rq->queuelist);
665 rq->flags &= ~REQ_QUEUED;
668 if (unlikely(bqt->tag_index[tag] == NULL))
669 printk("tag %d is missing\n", tag);
671 bqt->tag_index[tag] = NULL;
675 EXPORT_SYMBOL(blk_queue_end_tag);
678 * blk_queue_start_tag - find a free tag and assign it
679 * @q: the request queue for the device
680 * @rq: the block request that needs tagging
683 * This can either be used as a stand-alone helper, or possibly be
684 * assigned as the queue &prep_rq_fn (in which case &struct request
685 * automagically gets a tag assigned). Note that this function
686 * assumes that any type of request can be queued! if this is not
687 * true for your device, you must check the request type before
688 * calling this function. The request will also be removed from
689 * the request queue, so it's the drivers responsibility to readd
690 * it if it should need to be restarted for some reason.
693 * queue lock must be held.
695 int blk_queue_start_tag(request_queue_t *q, struct request *rq)
697 struct blk_queue_tag *bqt = q->queue_tags;
698 unsigned long *map = bqt->tag_map;
701 if (unlikely((rq->flags & REQ_QUEUED))) {
703 "request %p for device [%s] already tagged %d",
704 rq, rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->tag);
708 for (map = bqt->tag_map; *map == -1UL; map++) {
709 tag += BLK_TAGS_PER_LONG;
711 if (tag >= bqt->max_depth)
716 __set_bit(tag, bqt->tag_map);
718 rq->flags |= REQ_QUEUED;
720 bqt->tag_index[tag] = rq;
721 blkdev_dequeue_request(rq);
722 list_add(&rq->queuelist, &bqt->busy_list);
727 EXPORT_SYMBOL(blk_queue_start_tag);
730 * blk_queue_invalidate_tags - invalidate all pending tags
731 * @q: the request queue for the device
734 * Hardware conditions may dictate a need to stop all pending requests.
735 * In this case, we will safely clear the block side of the tag queue and
736 * readd all requests to the request queue in the right order.
739 * queue lock must be held.
741 void blk_queue_invalidate_tags(request_queue_t *q)
743 struct blk_queue_tag *bqt = q->queue_tags;
744 struct list_head *tmp, *n;
747 list_for_each_safe(tmp, n, &bqt->busy_list) {
748 rq = list_entry_rq(tmp);
751 printk("bad tag found on list\n");
752 list_del_init(&rq->queuelist);
753 rq->flags &= ~REQ_QUEUED;
755 blk_queue_end_tag(q, rq);
757 rq->flags &= ~REQ_STARTED;
758 __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
762 EXPORT_SYMBOL(blk_queue_invalidate_tags);
764 static char *rq_flags[] = {
782 "REQ_DRIVE_TASKFILE",
789 void blk_dump_rq_flags(struct request *rq, char *msg)
793 printk("%s: dev %s: flags = ", msg,
794 rq->rq_disk ? rq->rq_disk->disk_name : "?");
797 if (rq->flags & (1 << bit))
798 printk("%s ", rq_flags[bit]);
800 } while (bit < __REQ_NR_BITS);
802 printk("\nsector %llu, nr/cnr %lu/%u\n", (unsigned long long)rq->sector,
804 rq->current_nr_sectors);
805 printk("bio %p, biotail %p, buffer %p, data %p, len %u\n", rq->bio, rq->biotail, rq->buffer, rq->data, rq->data_len);
807 if (rq->flags & (REQ_BLOCK_PC | REQ_PC)) {
809 for (bit = 0; bit < sizeof(rq->cmd); bit++)
810 printk("%02x ", rq->cmd[bit]);
815 EXPORT_SYMBOL(blk_dump_rq_flags);
817 void blk_recount_segments(request_queue_t *q, struct bio *bio)
819 struct bio_vec *bv, *bvprv = NULL;
820 int i, nr_phys_segs, nr_hw_segs, seg_size, cluster;
821 int high, highprv = 1;
823 if (unlikely(!bio->bi_io_vec))
826 cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
827 seg_size = nr_phys_segs = nr_hw_segs = 0;
828 bio_for_each_segment(bv, bio, i) {
830 * the trick here is making sure that a high page is never
831 * considered part of another segment, since that might
832 * change with the bounce page.
834 high = page_to_pfn(bv->bv_page) >= q->bounce_pfn;
838 if (seg_size + bv->bv_len > q->max_segment_size)
840 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bv))
842 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bv))
845 seg_size += bv->bv_len;
850 if (!BIOVEC_VIRT_MERGEABLE(bvprv, bv))
856 seg_size = bv->bv_len;
860 bio->bi_phys_segments = nr_phys_segs;
861 bio->bi_hw_segments = nr_hw_segs;
862 bio->bi_flags |= (1 << BIO_SEG_VALID);
866 int blk_phys_contig_segment(request_queue_t *q, struct bio *bio,
869 if (!(q->queue_flags & (1 << QUEUE_FLAG_CLUSTER)))
872 if (!BIOVEC_PHYS_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)))
874 if (bio->bi_size + nxt->bi_size > q->max_segment_size)
878 * bio and nxt are contigous in memory, check if the queue allows
879 * these two to be merged into one
881 if (BIO_SEG_BOUNDARY(q, bio, nxt))
887 EXPORT_SYMBOL(blk_phys_contig_segment);
889 int blk_hw_contig_segment(request_queue_t *q, struct bio *bio,
892 if (!(q->queue_flags & (1 << QUEUE_FLAG_CLUSTER)))
895 if (!BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)))
897 if (bio->bi_size + nxt->bi_size > q->max_segment_size)
901 * bio and nxt are contigous in memory, check if the queue allows
902 * these two to be merged into one
904 if (BIO_SEG_BOUNDARY(q, bio, nxt))
910 EXPORT_SYMBOL(blk_hw_contig_segment);
913 * map a request to scatterlist, return number of sg entries setup. Caller
914 * must make sure sg can hold rq->nr_phys_segments entries
916 int blk_rq_map_sg(request_queue_t *q, struct request *rq, struct scatterlist *sg)
918 struct bio_vec *bvec, *bvprv;
920 int nsegs, i, cluster;
923 cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
929 rq_for_each_bio(bio, rq) {
931 * for each segment in bio
933 bio_for_each_segment(bvec, bio, i) {
934 int nbytes = bvec->bv_len;
936 if (bvprv && cluster) {
937 if (sg[nsegs - 1].length + nbytes > q->max_segment_size)
940 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bvec))
942 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bvec))
945 sg[nsegs - 1].length += nbytes;
948 memset(&sg[nsegs],0,sizeof(struct scatterlist));
949 sg[nsegs].page = bvec->bv_page;
950 sg[nsegs].length = nbytes;
951 sg[nsegs].offset = bvec->bv_offset;
956 } /* segments in bio */
962 EXPORT_SYMBOL(blk_rq_map_sg);
965 * the standard queue merge functions, can be overridden with device
966 * specific ones if so desired
969 static inline int ll_new_mergeable(request_queue_t *q,
973 int nr_phys_segs = bio_phys_segments(q, bio);
975 if (req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
976 req->flags |= REQ_NOMERGE;
977 q->last_merge = NULL;
982 * A hw segment is just getting larger, bump just the phys
985 req->nr_phys_segments += nr_phys_segs;
989 static inline int ll_new_hw_segment(request_queue_t *q,
993 int nr_hw_segs = bio_hw_segments(q, bio);
994 int nr_phys_segs = bio_phys_segments(q, bio);
996 if (req->nr_hw_segments + nr_hw_segs > q->max_hw_segments
997 || req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
998 req->flags |= REQ_NOMERGE;
999 q->last_merge = NULL;
1004 * This will form the start of a new hw segment. Bump both
1007 req->nr_hw_segments += nr_hw_segs;
1008 req->nr_phys_segments += nr_phys_segs;
1012 static int ll_back_merge_fn(request_queue_t *q, struct request *req,
1015 if (req->nr_sectors + bio_sectors(bio) > q->max_sectors) {
1016 req->flags |= REQ_NOMERGE;
1017 q->last_merge = NULL;
1021 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(req->biotail), __BVEC_START(bio)))
1022 return ll_new_mergeable(q, req, bio);
1024 return ll_new_hw_segment(q, req, bio);
1027 static int ll_front_merge_fn(request_queue_t *q, struct request *req,
1030 if (req->nr_sectors + bio_sectors(bio) > q->max_sectors) {
1031 req->flags |= REQ_NOMERGE;
1032 q->last_merge = NULL;
1036 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(req->bio)))
1037 return ll_new_mergeable(q, req, bio);
1039 return ll_new_hw_segment(q, req, bio);
1042 static int ll_merge_requests_fn(request_queue_t *q, struct request *req,
1043 struct request *next)
1045 int total_phys_segments = req->nr_phys_segments +next->nr_phys_segments;
1046 int total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
1049 * First check if the either of the requests are re-queued
1050 * requests. Can't merge them if they are.
1052 if (req->special || next->special)
1056 * Will it become to large?
1058 if ((req->nr_sectors + next->nr_sectors) > q->max_sectors)
1061 total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
1062 if (blk_phys_contig_segment(q, req->biotail, next->bio))
1063 total_phys_segments--;
1065 if (total_phys_segments > q->max_phys_segments)
1068 total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
1069 if (blk_hw_contig_segment(q, req->biotail, next->bio))
1070 total_hw_segments--;
1072 if (total_hw_segments > q->max_hw_segments)
1075 /* Merge is OK... */
1076 req->nr_phys_segments = total_phys_segments;
1077 req->nr_hw_segments = total_hw_segments;
1082 * "plug" the device if there are no outstanding requests: this will
1083 * force the transfer to start only after we have put all the requests
1086 * This is called with interrupts off and no requests on the queue and
1087 * with the queue lock held.
1089 void blk_plug_device(request_queue_t *q)
1091 WARN_ON(!irqs_disabled());
1094 * don't plug a stopped queue, it must be paired with blk_start_queue()
1095 * which will restart the queueing
1097 if (test_bit(QUEUE_FLAG_STOPPED, &q->queue_flags))
1100 if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
1101 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
1104 EXPORT_SYMBOL(blk_plug_device);
1107 * remove the queue from the plugged list, if present. called with
1108 * queue lock held and interrupts disabled.
1110 int blk_remove_plug(request_queue_t *q)
1112 WARN_ON(!irqs_disabled());
1114 if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
1117 del_timer(&q->unplug_timer);
1121 EXPORT_SYMBOL(blk_remove_plug);
1124 * remove the plug and let it rip..
1126 static inline void __generic_unplug_device(request_queue_t *q)
1128 if (test_bit(QUEUE_FLAG_STOPPED, &q->queue_flags))
1131 if (!blk_remove_plug(q))
1135 * was plugged, fire request_fn if queue has stuff to do
1137 if (elv_next_request(q))
1142 * generic_unplug_device - fire a request queue
1143 * @q: The &request_queue_t in question
1146 * Linux uses plugging to build bigger requests queues before letting
1147 * the device have at them. If a queue is plugged, the I/O scheduler
1148 * is still adding and merging requests on the queue. Once the queue
1149 * gets unplugged, the request_fn defined for the queue is invoked and
1150 * transfers started.
1152 void generic_unplug_device(request_queue_t *q)
1154 spin_lock_irq(q->queue_lock);
1155 __generic_unplug_device(q);
1156 spin_unlock_irq(q->queue_lock);
1158 EXPORT_SYMBOL(generic_unplug_device);
1160 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
1163 request_queue_t *q = bdi->unplug_io_data;
1166 * devices don't necessarily have an ->unplug_fn defined
1172 static void blk_unplug_work(void *data)
1174 request_queue_t *q = data;
1179 static void blk_unplug_timeout(unsigned long data)
1181 request_queue_t *q = (request_queue_t *)data;
1183 kblockd_schedule_work(&q->unplug_work);
1187 * blk_start_queue - restart a previously stopped queue
1188 * @q: The &request_queue_t in question
1191 * blk_start_queue() will clear the stop flag on the queue, and call
1192 * the request_fn for the queue if it was in a stopped state when
1193 * entered. Also see blk_stop_queue(). Queue lock must be held.
1195 void blk_start_queue(request_queue_t *q)
1197 clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1200 * one level of recursion is ok and is much faster than kicking
1201 * the unplug handling
1203 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
1205 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
1208 kblockd_schedule_work(&q->unplug_work);
1212 EXPORT_SYMBOL(blk_start_queue);
1215 * blk_stop_queue - stop a queue
1216 * @q: The &request_queue_t in question
1219 * The Linux block layer assumes that a block driver will consume all
1220 * entries on the request queue when the request_fn strategy is called.
1221 * Often this will not happen, because of hardware limitations (queue
1222 * depth settings). If a device driver gets a 'queue full' response,
1223 * or if it simply chooses not to queue more I/O at one point, it can
1224 * call this function to prevent the request_fn from being called until
1225 * the driver has signalled it's ready to go again. This happens by calling
1226 * blk_start_queue() to restart queue operations. Queue lock must be held.
1228 void blk_stop_queue(request_queue_t *q)
1231 set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1234 EXPORT_SYMBOL(blk_stop_queue);
1237 * blk_run_queue - run a single device queue
1238 * @q: The queue to run
1240 void blk_run_queue(struct request_queue *q)
1242 unsigned long flags;
1244 spin_lock_irqsave(q->queue_lock, flags);
1247 spin_unlock_irqrestore(q->queue_lock, flags);
1250 EXPORT_SYMBOL(blk_run_queue);
1253 * blk_cleanup_queue: - release a &request_queue_t when it is no longer needed
1254 * @q: the request queue to be released
1257 * blk_cleanup_queue is the pair to blk_init_queue() or
1258 * blk_queue_make_request(). It should be called when a request queue is
1259 * being released; typically when a block device is being de-registered.
1260 * Currently, its primary task it to free all the &struct request
1261 * structures that were allocated to the queue and the queue itself.
1264 * Hopefully the low level driver will have finished any
1265 * outstanding requests first...
1267 void blk_cleanup_queue(request_queue_t * q)
1269 struct request_list *rl = &q->rq;
1271 if (!atomic_dec_and_test(&q->refcnt))
1276 del_timer_sync(&q->unplug_timer);
1280 mempool_destroy(rl->rq_pool);
1282 if (blk_queue_tagged(q))
1283 blk_queue_free_tags(q);
1285 kmem_cache_free(requestq_cachep, q);
1288 EXPORT_SYMBOL(blk_cleanup_queue);
1290 static int blk_init_free_list(request_queue_t *q)
1292 struct request_list *rl = &q->rq;
1294 rl->count[READ] = rl->count[WRITE] = 0;
1295 init_waitqueue_head(&rl->wait[READ]);
1296 init_waitqueue_head(&rl->wait[WRITE]);
1298 rl->rq_pool = mempool_create(BLKDEV_MIN_RQ, mempool_alloc_slab, mempool_free_slab, request_cachep);
1306 static int __make_request(request_queue_t *, struct bio *);
1308 static elevator_t *chosen_elevator =
1309 #if defined(CONFIG_IOSCHED_AS)
1311 #elif defined(CONFIG_IOSCHED_DEADLINE)
1313 #elif defined(CONFIG_IOSCHED_CFQ)
1315 #elif defined(CONFIG_IOSCHED_NOOP)
1319 #error "You must have at least 1 I/O scheduler selected"
1322 #if defined(CONFIG_IOSCHED_AS) || defined(CONFIG_IOSCHED_DEADLINE) || defined (CONFIG_IOSCHED_NOOP)
1323 static int __init elevator_setup(char *str)
1325 #ifdef CONFIG_IOSCHED_DEADLINE
1326 if (!strcmp(str, "deadline"))
1327 chosen_elevator = &iosched_deadline;
1329 #ifdef CONFIG_IOSCHED_AS
1330 if (!strcmp(str, "as"))
1331 chosen_elevator = &iosched_as;
1333 #ifdef CONFIG_IOSCHED_CFQ
1334 if (!strcmp(str, "cfq"))
1335 chosen_elevator = &iosched_cfq;
1337 #ifdef CONFIG_IOSCHED_NOOP
1338 if (!strcmp(str, "noop"))
1339 chosen_elevator = &elevator_noop;
1344 __setup("elevator=", elevator_setup);
1345 #endif /* CONFIG_IOSCHED_AS || CONFIG_IOSCHED_DEADLINE || CONFIG_IOSCHED_NOOP */
1347 request_queue_t *blk_alloc_queue(int gfp_mask)
1349 request_queue_t *q = kmem_cache_alloc(requestq_cachep, gfp_mask);
1354 memset(q, 0, sizeof(*q));
1355 init_timer(&q->unplug_timer);
1356 atomic_set(&q->refcnt, 1);
1358 q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
1359 q->backing_dev_info.unplug_io_data = q;
1364 EXPORT_SYMBOL(blk_alloc_queue);
1367 * blk_init_queue - prepare a request queue for use with a block device
1368 * @rfn: The function to be called to process requests that have been
1369 * placed on the queue.
1370 * @lock: Request queue spin lock
1373 * If a block device wishes to use the standard request handling procedures,
1374 * which sorts requests and coalesces adjacent requests, then it must
1375 * call blk_init_queue(). The function @rfn will be called when there
1376 * are requests on the queue that need to be processed. If the device
1377 * supports plugging, then @rfn may not be called immediately when requests
1378 * are available on the queue, but may be called at some time later instead.
1379 * Plugged queues are generally unplugged when a buffer belonging to one
1380 * of the requests on the queue is needed, or due to memory pressure.
1382 * @rfn is not required, or even expected, to remove all requests off the
1383 * queue, but only as many as it can handle at a time. If it does leave
1384 * requests on the queue, it is responsible for arranging that the requests
1385 * get dealt with eventually.
1387 * The queue spin lock must be held while manipulating the requests on the
1390 * Function returns a pointer to the initialized request queue, or NULL if
1391 * it didn't succeed.
1394 * blk_init_queue() must be paired with a blk_cleanup_queue() call
1395 * when the block device is deactivated (such as at module unload).
1397 request_queue_t *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1402 q = blk_alloc_queue(GFP_KERNEL);
1406 if (blk_init_free_list(q))
1411 printk("Using %s io scheduler\n", chosen_elevator->elevator_name);
1414 if (elevator_init(q, chosen_elevator))
1417 q->request_fn = rfn;
1418 q->back_merge_fn = ll_back_merge_fn;
1419 q->front_merge_fn = ll_front_merge_fn;
1420 q->merge_requests_fn = ll_merge_requests_fn;
1421 q->prep_rq_fn = NULL;
1422 q->unplug_fn = generic_unplug_device;
1423 q->queue_flags = (1 << QUEUE_FLAG_CLUSTER);
1424 q->queue_lock = lock;
1426 blk_queue_segment_boundary(q, 0xffffffff);
1428 blk_queue_make_request(q, __make_request);
1429 blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
1431 blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
1432 blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
1436 blk_cleanup_queue(q);
1438 kmem_cache_free(requestq_cachep, q);
1442 EXPORT_SYMBOL(blk_init_queue);
1444 int blk_get_queue(request_queue_t *q)
1446 if (!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)) {
1447 atomic_inc(&q->refcnt);
1454 EXPORT_SYMBOL(blk_get_queue);
1456 static inline void blk_free_request(request_queue_t *q, struct request *rq)
1458 elv_put_request(q, rq);
1459 mempool_free(rq, q->rq.rq_pool);
1462 static inline struct request *blk_alloc_request(request_queue_t *q,int gfp_mask)
1464 struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
1469 if (!elv_set_request(q, rq, gfp_mask))
1472 mempool_free(rq, q->rq.rq_pool);
1477 * ioc_batching returns true if the ioc is a valid batching request and
1478 * should be given priority access to a request.
1480 static inline int ioc_batching(struct io_context *ioc)
1486 * Make sure the process is able to allocate at least 1 request
1487 * even if the batch times out, otherwise we could theoretically
1490 return ioc->nr_batch_requests == BLK_BATCH_REQ ||
1491 (ioc->nr_batch_requests > 0
1492 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
1496 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
1497 * will cause the process to be a "batcher" on all queues in the system. This
1498 * is the behaviour we want though - once it gets a wakeup it should be given
1501 void ioc_set_batching(struct io_context *ioc)
1503 if (!ioc || ioc_batching(ioc))
1506 ioc->nr_batch_requests = BLK_BATCH_REQ;
1507 ioc->last_waited = jiffies;
1511 * A request has just been released. Account for it, update the full and
1512 * congestion status, wake up any waiters. Called under q->queue_lock.
1514 static void freed_request(request_queue_t *q, int rw)
1516 struct request_list *rl = &q->rq;
1519 if (rl->count[rw] < queue_congestion_off_threshold(q))
1520 clear_queue_congested(q, rw);
1521 if (rl->count[rw]+1 <= q->nr_requests) {
1522 if (waitqueue_active(&rl->wait[rw]))
1523 wake_up(&rl->wait[rw]);
1524 if (!waitqueue_active(&rl->wait[rw]))
1525 blk_clear_queue_full(q, rw);
1529 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
1531 * Get a free request, queue_lock must not be held
1533 static struct request *get_request(request_queue_t *q, int rw, int gfp_mask)
1535 struct request *rq = NULL;
1536 struct request_list *rl = &q->rq;
1537 struct io_context *ioc = get_io_context(gfp_mask);
1539 spin_lock_irq(q->queue_lock);
1541 if (!elv_may_queue(q, rw))
1544 if (rl->count[rw]+1 >= q->nr_requests) {
1546 * The queue will fill after this allocation, so set it as
1547 * full, and mark this process as "batching". This process
1548 * will be allowed to complete a batch of requests, others
1551 if (!blk_queue_full(q, rw)) {
1552 ioc_set_batching(ioc);
1553 blk_set_queue_full(q, rw);
1558 * The queue is full and the allocating process is not a
1559 * "batcher", and not exempted by the IO scheduler
1561 if (blk_queue_full(q, rw) && !ioc_batching(ioc))
1565 if (rl->count[rw] >= queue_congestion_on_threshold(q))
1566 set_queue_congested(q, rw);
1567 spin_unlock_irq(q->queue_lock);
1569 rq = blk_alloc_request(q, gfp_mask);
1572 * Allocation failed presumably due to memory. Undo anything
1573 * we might have messed up.
1575 * Allocating task should really be put onto the front of the
1576 * wait queue, but this is pretty rare.
1578 spin_lock_irq(q->queue_lock);
1579 freed_request(q, rw);
1583 if (ioc_batching(ioc))
1584 ioc->nr_batch_requests--;
1586 INIT_LIST_HEAD(&rq->queuelist);
1589 * first three bits are identical in rq->flags and bio->bi_rw,
1590 * see bio.h and blkdev.h
1595 rq->rq_status = RQ_ACTIVE;
1596 rq->bio = rq->biotail = NULL;
1608 put_io_context(ioc);
1612 elv_set_congested(q);
1613 spin_unlock_irq(q->queue_lock);
1618 * No available requests for this queue, unplug the device and wait for some
1619 * requests to become available.
1621 static struct request *get_request_wait(request_queue_t *q, int rw)
1626 generic_unplug_device(q);
1628 struct request_list *rl = &q->rq;
1630 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
1631 TASK_UNINTERRUPTIBLE);
1633 rq = get_request(q, rw, GFP_NOIO);
1636 struct io_context *ioc;
1641 * After sleeping, we become a "batching" process and
1642 * will be able to allocate at least one request, and
1643 * up to a big batch of them for a small period time.
1644 * See ioc_batching, ioc_set_batching
1646 ioc = get_io_context(GFP_NOIO);
1647 ioc_set_batching(ioc);
1648 put_io_context(ioc);
1650 finish_wait(&rl->wait[rw], &wait);
1656 struct request *blk_get_request(request_queue_t *q, int rw, int gfp_mask)
1660 BUG_ON(rw != READ && rw != WRITE);
1662 if (gfp_mask & __GFP_WAIT)
1663 rq = get_request_wait(q, rw);
1665 rq = get_request(q, rw, gfp_mask);
1670 EXPORT_SYMBOL(blk_get_request);
1673 * blk_requeue_request - put a request back on queue
1674 * @q: request queue where request should be inserted
1675 * @rq: request to be inserted
1678 * Drivers often keep queueing requests until the hardware cannot accept
1679 * more, when that condition happens we need to put the request back
1680 * on the queue. Must be called with queue lock held.
1682 void blk_requeue_request(request_queue_t *q, struct request *rq)
1684 if (blk_rq_tagged(rq))
1685 blk_queue_end_tag(q, rq);
1687 elv_requeue_request(q, rq);
1690 EXPORT_SYMBOL(blk_requeue_request);
1693 * blk_insert_request - insert a special request in to a request queue
1694 * @q: request queue where request should be inserted
1695 * @rq: request to be inserted
1696 * @at_head: insert request at head or tail of queue
1697 * @data: private data
1698 * @reinsert: true if request it a reinsertion of previously processed one
1701 * Many block devices need to execute commands asynchronously, so they don't
1702 * block the whole kernel from preemption during request execution. This is
1703 * accomplished normally by inserting aritficial requests tagged as
1704 * REQ_SPECIAL in to the corresponding request queue, and letting them be
1705 * scheduled for actual execution by the request queue.
1707 * We have the option of inserting the head or the tail of the queue.
1708 * Typically we use the tail for new ioctls and so forth. We use the head
1709 * of the queue for things like a QUEUE_FULL message from a device, or a
1710 * host that is unable to accept a particular command.
1712 void blk_insert_request(request_queue_t *q, struct request *rq,
1713 int at_head, void *data, int reinsert)
1715 unsigned long flags;
1718 * tell I/O scheduler that this isn't a regular read/write (ie it
1719 * must not attempt merges on this) and that it acts as a soft
1722 rq->flags |= REQ_SPECIAL | REQ_SOFTBARRIER;
1726 spin_lock_irqsave(q->queue_lock, flags);
1729 * If command is tagged, release the tag
1732 blk_requeue_request(q, rq);
1734 int where = ELEVATOR_INSERT_BACK;
1737 where = ELEVATOR_INSERT_FRONT;
1739 if (blk_rq_tagged(rq))
1740 blk_queue_end_tag(q, rq);
1742 drive_stat_acct(rq, rq->nr_sectors, 1);
1743 __elv_add_request(q, rq, where, 0);
1745 if (blk_queue_plugged(q))
1746 __generic_unplug_device(q);
1749 spin_unlock_irqrestore(q->queue_lock, flags);
1752 EXPORT_SYMBOL(blk_insert_request);
1755 * blk_rq_map_user - map user data to a request, for REQ_BLOCK_PC usage
1756 * @q: request queue where request should be inserted
1757 * @rw: READ or WRITE data
1758 * @ubuf: the user buffer
1759 * @len: length of user data
1762 * Data will be mapped directly for zero copy io, if possible. Otherwise
1763 * a kernel bounce buffer is used.
1765 * A matching blk_rq_unmap_user() must be issued at the end of io, while
1766 * still in process context.
1768 struct request *blk_rq_map_user(request_queue_t *q, int rw, void __user *ubuf,
1771 struct request *rq = NULL;
1776 rq = blk_get_request(q, rw, __GFP_WAIT);
1778 return ERR_PTR(-ENOMEM);
1780 bio = bio_map_user(q, NULL, (unsigned long) ubuf, len, rw == READ);
1782 int bytes = (len + 511) & ~511;
1784 buf = kmalloc(bytes, q->bounce_gfp | GFP_USER);
1791 if (copy_from_user(buf, ubuf, len)) {
1796 memset(buf, 0, len);
1799 rq->bio = rq->biotail = bio;
1801 blk_rq_bio_prep(q, rq, bio);
1803 rq->buffer = rq->data = buf;
1810 bio_unmap_user(bio, 1);
1812 blk_put_request(rq);
1814 return ERR_PTR(ret);
1817 EXPORT_SYMBOL(blk_rq_map_user);
1820 * blk_rq_unmap_user - unmap a request with user data
1821 * @rq: request to be unmapped
1822 * @ubuf: user buffer
1823 * @ulen: length of user buffer
1826 * Unmap a request previously mapped by blk_rq_map_user().
1828 int blk_rq_unmap_user(struct request *rq, void __user *ubuf, struct bio *bio,
1831 const int read = rq_data_dir(rq) == READ;
1835 bio_unmap_user(bio, read);
1837 if (read && copy_to_user(ubuf, rq->buffer, ulen))
1842 blk_put_request(rq);
1846 EXPORT_SYMBOL(blk_rq_unmap_user);
1849 * blk_execute_rq - insert a request into queue for execution
1850 * @q: queue to insert the request in
1851 * @bd_disk: matching gendisk
1852 * @rq: request to insert
1855 * Insert a fully prepared request at the back of the io scheduler queue
1858 int blk_execute_rq(request_queue_t *q, struct gendisk *bd_disk,
1861 DECLARE_COMPLETION(wait);
1862 char sense[SCSI_SENSE_BUFFERSIZE];
1865 rq->rq_disk = bd_disk;
1868 * we need an extra reference to the request, so we can look at
1869 * it after io completion
1874 memset(sense, 0, sizeof(sense));
1879 rq->flags |= REQ_NOMERGE;
1880 rq->waiting = &wait;
1881 elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 1);
1882 generic_unplug_device(q);
1883 wait_for_completion(&wait);
1892 EXPORT_SYMBOL(blk_execute_rq);
1894 void drive_stat_acct(struct request *rq, int nr_sectors, int new_io)
1896 int rw = rq_data_dir(rq);
1898 if (!blk_fs_request(rq) || !rq->rq_disk)
1902 disk_stat_add(rq->rq_disk, read_sectors, nr_sectors);
1904 disk_stat_inc(rq->rq_disk, read_merges);
1905 } else if (rw == WRITE) {
1906 disk_stat_add(rq->rq_disk, write_sectors, nr_sectors);
1908 disk_stat_inc(rq->rq_disk, write_merges);
1911 disk_round_stats(rq->rq_disk);
1912 rq->rq_disk->in_flight++;
1917 * add-request adds a request to the linked list.
1918 * queue lock is held and interrupts disabled, as we muck with the
1919 * request queue list.
1921 static inline void add_request(request_queue_t * q, struct request * req)
1923 drive_stat_acct(req, req->nr_sectors, 1);
1926 q->activity_fn(q->activity_data, rq_data_dir(req));
1929 * elevator indicated where it wants this request to be
1930 * inserted at elevator_merge time
1932 __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
1936 * disk_round_stats() - Round off the performance stats on a struct
1939 * The average IO queue length and utilisation statistics are maintained
1940 * by observing the current state of the queue length and the amount of
1941 * time it has been in this state for.
1943 * Normally, that accounting is done on IO completion, but that can result
1944 * in more than a second's worth of IO being accounted for within any one
1945 * second, leading to >100% utilisation. To deal with that, we call this
1946 * function to do a round-off before returning the results when reading
1947 * /proc/diskstats. This accounts immediately for all queue usage up to
1948 * the current jiffies and restarts the counters again.
1950 void disk_round_stats(struct gendisk *disk)
1952 unsigned long now = jiffies;
1954 disk_stat_add(disk, time_in_queue,
1955 disk->in_flight * (now - disk->stamp));
1958 if (disk->in_flight)
1959 disk_stat_add(disk, io_ticks, (now - disk->stamp_idle));
1960 disk->stamp_idle = now;
1964 * queue lock must be held
1966 void __blk_put_request(request_queue_t *q, struct request *req)
1968 struct request_list *rl = req->rl;
1972 if (unlikely(--req->ref_count))
1975 req->rq_status = RQ_INACTIVE;
1980 * Request may not have originated from ll_rw_blk. if not,
1981 * it didn't come out of our reserved rq pools
1984 int rw = rq_data_dir(req);
1986 elv_completed_request(q, req);
1988 BUG_ON(!list_empty(&req->queuelist));
1990 blk_free_request(q, req);
1991 freed_request(q, rw);
1995 void blk_put_request(struct request *req)
1998 * if req->rl isn't set, this request didnt originate from the
1999 * block layer, so it's safe to just disregard it
2002 unsigned long flags;
2003 request_queue_t *q = req->q;
2005 spin_lock_irqsave(q->queue_lock, flags);
2006 __blk_put_request(q, req);
2007 spin_unlock_irqrestore(q->queue_lock, flags);
2011 EXPORT_SYMBOL(blk_put_request);
2014 * blk_congestion_wait - wait for a queue to become uncongested
2015 * @rw: READ or WRITE
2016 * @timeout: timeout in jiffies
2018 * Waits for up to @timeout jiffies for a queue (any queue) to exit congestion.
2019 * If no queues are congested then just wait for the next request to be
2022 long blk_congestion_wait(int rw, long timeout)
2026 wait_queue_head_t *wqh = &congestion_wqh[rw];
2028 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
2029 ret = io_schedule_timeout(timeout);
2030 finish_wait(wqh, &wait);
2034 EXPORT_SYMBOL(blk_congestion_wait);
2037 * Has to be called with the request spinlock acquired
2039 static int attempt_merge(request_queue_t *q, struct request *req,
2040 struct request *next)
2042 if (!rq_mergeable(req) || !rq_mergeable(next))
2048 if (req->sector + req->nr_sectors != next->sector)
2051 if (rq_data_dir(req) != rq_data_dir(next)
2052 || req->rq_disk != next->rq_disk
2053 || next->waiting || next->special)
2057 * If we are allowed to merge, then append bio list
2058 * from next to rq and release next. merge_requests_fn
2059 * will have updated segment counts, update sector
2062 if (!q->merge_requests_fn(q, req, next))
2066 * At this point we have either done a back merge
2067 * or front merge. We need the smaller start_time of
2068 * the merged requests to be the current request
2069 * for accounting purposes.
2071 if (time_after(req->start_time, next->start_time))
2072 req->start_time = next->start_time;
2074 req->biotail->bi_next = next->bio;
2075 req->biotail = next->biotail;
2077 req->nr_sectors = req->hard_nr_sectors += next->hard_nr_sectors;
2079 elv_merge_requests(q, req, next);
2082 disk_round_stats(req->rq_disk);
2083 req->rq_disk->in_flight--;
2086 __blk_put_request(q, next);
2090 static inline int attempt_back_merge(request_queue_t *q, struct request *rq)
2092 struct request *next = elv_latter_request(q, rq);
2095 return attempt_merge(q, rq, next);
2100 static inline int attempt_front_merge(request_queue_t *q, struct request *rq)
2102 struct request *prev = elv_former_request(q, rq);
2105 return attempt_merge(q, prev, rq);
2111 * blk_attempt_remerge - attempt to remerge active head with next request
2112 * @q: The &request_queue_t belonging to the device
2113 * @rq: The head request (usually)
2116 * For head-active devices, the queue can easily be unplugged so quickly
2117 * that proper merging is not done on the front request. This may hurt
2118 * performance greatly for some devices. The block layer cannot safely
2119 * do merging on that first request for these queues, but the driver can
2120 * call this function and make it happen any way. Only the driver knows
2121 * when it is safe to do so.
2123 void blk_attempt_remerge(request_queue_t *q, struct request *rq)
2125 unsigned long flags;
2127 spin_lock_irqsave(q->queue_lock, flags);
2128 attempt_back_merge(q, rq);
2129 spin_unlock_irqrestore(q->queue_lock, flags);
2132 EXPORT_SYMBOL(blk_attempt_remerge);
2135 * Non-locking blk_attempt_remerge variant.
2137 void __blk_attempt_remerge(request_queue_t *q, struct request *rq)
2139 attempt_back_merge(q, rq);
2142 EXPORT_SYMBOL(__blk_attempt_remerge);
2144 static int __make_request(request_queue_t *q, struct bio *bio)
2146 struct request *req, *freereq = NULL;
2147 int el_ret, rw, nr_sectors, cur_nr_sectors, barrier, ra;
2150 sector = bio->bi_sector;
2151 nr_sectors = bio_sectors(bio);
2152 cur_nr_sectors = bio_cur_sectors(bio);
2154 rw = bio_data_dir(bio);
2157 * low level driver can indicate that it wants pages above a
2158 * certain limit bounced to low memory (ie for highmem, or even
2159 * ISA dma in theory)
2161 blk_queue_bounce(q, &bio);
2163 spin_lock_prefetch(q->queue_lock);
2165 barrier = test_bit(BIO_RW_BARRIER, &bio->bi_rw);
2167 ra = bio->bi_rw & (1 << BIO_RW_AHEAD);
2170 spin_lock_irq(q->queue_lock);
2172 if (elv_queue_empty(q)) {
2179 el_ret = elv_merge(q, &req, bio);
2181 case ELEVATOR_BACK_MERGE:
2182 BUG_ON(!rq_mergeable(req));
2184 if (!q->back_merge_fn(q, req, bio))
2187 req->biotail->bi_next = bio;
2189 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2190 drive_stat_acct(req, nr_sectors, 0);
2191 if (!attempt_back_merge(q, req))
2192 elv_merged_request(q, req);
2195 case ELEVATOR_FRONT_MERGE:
2196 BUG_ON(!rq_mergeable(req));
2198 if (!q->front_merge_fn(q, req, bio))
2201 bio->bi_next = req->bio;
2202 req->cbio = req->bio = bio;
2203 req->nr_cbio_segments = bio_segments(bio);
2204 req->nr_cbio_sectors = bio_sectors(bio);
2207 * may not be valid. if the low level driver said
2208 * it didn't need a bounce buffer then it better
2209 * not touch req->buffer either...
2211 req->buffer = bio_data(bio);
2212 req->current_nr_sectors = cur_nr_sectors;
2213 req->hard_cur_sectors = cur_nr_sectors;
2214 req->sector = req->hard_sector = sector;
2215 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2216 drive_stat_acct(req, nr_sectors, 0);
2217 if (!attempt_front_merge(q, req))
2218 elv_merged_request(q, req);
2222 * elevator says don't/can't merge. get new request
2224 case ELEVATOR_NO_MERGE:
2228 printk("elevator returned crap (%d)\n", el_ret);
2233 * Grab a free request from the freelist - if that is empty, check
2234 * if we are doing read ahead and abort instead of blocking for
2242 spin_unlock_irq(q->queue_lock);
2243 if ((freereq = get_request(q, rw, GFP_ATOMIC)) == NULL) {
2250 freereq = get_request_wait(q, rw);
2255 req->flags |= REQ_CMD;
2258 * inherit FAILFAST from bio and don't stack up
2259 * retries for read ahead
2261 if (ra || test_bit(BIO_RW_FAILFAST, &bio->bi_rw))
2262 req->flags |= REQ_FAILFAST;
2265 * REQ_BARRIER implies no merging, but lets make it explicit
2268 req->flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
2271 req->hard_sector = req->sector = sector;
2272 req->hard_nr_sectors = req->nr_sectors = nr_sectors;
2273 req->current_nr_sectors = req->hard_cur_sectors = cur_nr_sectors;
2274 req->nr_phys_segments = bio_phys_segments(q, bio);
2275 req->nr_hw_segments = bio_hw_segments(q, bio);
2276 req->nr_cbio_segments = bio_segments(bio);
2277 req->nr_cbio_sectors = bio_sectors(bio);
2278 req->buffer = bio_data(bio); /* see ->buffer comment above */
2279 req->waiting = NULL;
2280 req->cbio = req->bio = req->biotail = bio;
2281 req->rq_disk = bio->bi_bdev->bd_disk;
2282 req->start_time = jiffies;
2284 add_request(q, req);
2287 __blk_put_request(q, freereq);
2289 if (blk_queue_plugged(q)) {
2290 int nrq = q->rq.count[READ] + q->rq.count[WRITE] - q->in_flight;
2292 if (nrq == q->unplug_thresh || bio_sync(bio))
2293 __generic_unplug_device(q);
2295 spin_unlock_irq(q->queue_lock);
2299 bio_endio(bio, nr_sectors << 9, -EWOULDBLOCK);
2304 * If bio->bi_dev is a partition, remap the location
2306 static inline void blk_partition_remap(struct bio *bio)
2308 struct block_device *bdev = bio->bi_bdev;
2310 if (bdev != bdev->bd_contains) {
2311 struct hd_struct *p = bdev->bd_part;
2313 switch (bio->bi_rw) {
2315 p->read_sectors += bio_sectors(bio);
2319 p->write_sectors += bio_sectors(bio);
2323 bio->bi_sector += p->start_sect;
2324 bio->bi_bdev = bdev->bd_contains;
2329 * generic_make_request: hand a buffer to its device driver for I/O
2330 * @bio: The bio describing the location in memory and on the device.
2332 * generic_make_request() is used to make I/O requests of block
2333 * devices. It is passed a &struct bio, which describes the I/O that needs
2336 * generic_make_request() does not return any status. The
2337 * success/failure status of the request, along with notification of
2338 * completion, is delivered asynchronously through the bio->bi_end_io
2339 * function described (one day) else where.
2341 * The caller of generic_make_request must make sure that bi_io_vec
2342 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2343 * set to describe the device address, and the
2344 * bi_end_io and optionally bi_private are set to describe how
2345 * completion notification should be signaled.
2347 * generic_make_request and the drivers it calls may use bi_next if this
2348 * bio happens to be merged with someone else, and may change bi_dev and
2349 * bi_sector for remaps as it sees fit. So the values of these fields
2350 * should NOT be depended on after the call to generic_make_request.
2352 void generic_make_request(struct bio *bio)
2356 int ret, nr_sectors = bio_sectors(bio);
2358 /* Test device or partition size, when known. */
2359 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
2361 sector_t sector = bio->bi_sector;
2363 if (maxsector < nr_sectors ||
2364 maxsector - nr_sectors < sector) {
2365 char b[BDEVNAME_SIZE];
2366 /* This may well happen - the kernel calls
2367 * bread() without checking the size of the
2368 * device, e.g., when mounting a device. */
2370 "attempt to access beyond end of device\n");
2371 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
2372 bdevname(bio->bi_bdev, b),
2374 (unsigned long long) sector + nr_sectors,
2375 (long long) maxsector);
2377 set_bit(BIO_EOF, &bio->bi_flags);
2383 * Resolve the mapping until finished. (drivers are
2384 * still free to implement/resolve their own stacking
2385 * by explicitly returning 0)
2387 * NOTE: we don't repeat the blk_size check for each new device.
2388 * Stacking drivers are expected to know what they are doing.
2391 char b[BDEVNAME_SIZE];
2393 q = bdev_get_queue(bio->bi_bdev);
2396 "generic_make_request: Trying to access "
2397 "nonexistent block-device %s (%Lu)\n",
2398 bdevname(bio->bi_bdev, b),
2399 (long long) bio->bi_sector);
2401 bio_endio(bio, bio->bi_size, -EIO);
2405 if (unlikely(bio_sectors(bio) > q->max_sectors)) {
2406 printk("bio too big device %s (%u > %u)\n",
2407 bdevname(bio->bi_bdev, b),
2413 if (test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))
2417 * If this device has partitions, remap block n
2418 * of partition p to block n+start(p) of the disk.
2420 blk_partition_remap(bio);
2422 ret = q->make_request_fn(q, bio);
2426 EXPORT_SYMBOL(generic_make_request);
2429 * submit_bio: submit a bio to the block device layer for I/O
2430 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2431 * @bio: The &struct bio which describes the I/O
2433 * submit_bio() is very similar in purpose to generic_make_request(), and
2434 * uses that function to do most of the work. Both are fairly rough
2435 * interfaces, @bio must be presetup and ready for I/O.
2438 void submit_bio(int rw, struct bio *bio)
2440 int count = bio_sectors(bio);
2442 BIO_BUG_ON(!bio->bi_size);
2443 BIO_BUG_ON(!bio->bi_io_vec);
2446 mod_page_state(pgpgout, count);
2448 mod_page_state(pgpgin, count);
2450 if (unlikely(block_dump)) {
2451 char b[BDEVNAME_SIZE];
2452 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
2453 current->comm, current->pid,
2454 (rw & WRITE) ? "WRITE" : "READ",
2455 (unsigned long long)bio->bi_sector,
2456 bdevname(bio->bi_bdev,b));
2459 generic_make_request(bio);
2462 EXPORT_SYMBOL(submit_bio);
2465 * blk_rq_next_segment
2466 * @rq: the request being processed
2469 * Points to the next segment in the request if the current segment
2470 * is complete. Leaves things unchanged if this segment is not over
2471 * or if no more segments are left in this request.
2473 * Meant to be used for bio traversal during I/O submission
2474 * Does not affect any I/O completions or update completion state
2475 * in the request, and does not modify any bio fields.
2477 * Decrementing rq->nr_sectors, rq->current_nr_sectors and
2478 * rq->nr_cbio_sectors as data is transferred is the caller's
2479 * responsibility and should be done before calling this routine.
2481 void blk_rq_next_segment(struct request *rq)
2483 if (rq->current_nr_sectors > 0)
2486 if (rq->nr_cbio_sectors > 0) {
2487 --rq->nr_cbio_segments;
2488 rq->current_nr_sectors = blk_rq_vec(rq)->bv_len >> 9;
2490 if ((rq->cbio = rq->cbio->bi_next)) {
2491 rq->nr_cbio_segments = bio_segments(rq->cbio);
2492 rq->nr_cbio_sectors = bio_sectors(rq->cbio);
2493 rq->current_nr_sectors = bio_cur_sectors(rq->cbio);
2497 /* remember the size of this segment before we start I/O */
2498 rq->hard_cur_sectors = rq->current_nr_sectors;
2502 * process_that_request_first - process partial request submission
2503 * @req: the request being processed
2504 * @nr_sectors: number of sectors I/O has been submitted on
2507 * May be used for processing bio's while submitting I/O without
2508 * signalling completion. Fails if more data is requested than is
2509 * available in the request in which case it doesn't advance any
2512 * Assumes a request is correctly set up. No sanity checks.
2515 * 0 - no more data left to submit (not processed)
2516 * 1 - data available to submit for this request (processed)
2518 int process_that_request_first(struct request *req, unsigned int nr_sectors)
2522 if (req->nr_sectors < nr_sectors)
2525 req->nr_sectors -= nr_sectors;
2526 req->sector += nr_sectors;
2527 while (nr_sectors) {
2528 nsect = min_t(unsigned, req->current_nr_sectors, nr_sectors);
2529 req->current_nr_sectors -= nsect;
2530 nr_sectors -= nsect;
2532 req->nr_cbio_sectors -= nsect;
2533 blk_rq_next_segment(req);
2539 EXPORT_SYMBOL(process_that_request_first);
2541 void blk_recalc_rq_segments(struct request *rq)
2544 int nr_phys_segs, nr_hw_segs;
2549 nr_phys_segs = nr_hw_segs = 0;
2550 rq_for_each_bio(bio, rq) {
2551 /* Force bio hw/phys segs to be recalculated. */
2552 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
2554 nr_phys_segs += bio_phys_segments(rq->q, bio);
2555 nr_hw_segs += bio_hw_segments(rq->q, bio);
2558 rq->nr_phys_segments = nr_phys_segs;
2559 rq->nr_hw_segments = nr_hw_segs;
2562 void blk_recalc_rq_sectors(struct request *rq, int nsect)
2564 if (blk_fs_request(rq)) {
2565 rq->hard_sector += nsect;
2566 rq->hard_nr_sectors -= nsect;
2569 * Move the I/O submission pointers ahead if required,
2570 * i.e. for drivers not aware of rq->cbio.
2572 if ((rq->nr_sectors >= rq->hard_nr_sectors) &&
2573 (rq->sector <= rq->hard_sector)) {
2574 rq->sector = rq->hard_sector;
2575 rq->nr_sectors = rq->hard_nr_sectors;
2576 rq->hard_cur_sectors = bio_cur_sectors(rq->bio);
2577 rq->current_nr_sectors = rq->hard_cur_sectors;
2578 rq->nr_cbio_segments = bio_segments(rq->bio);
2579 rq->nr_cbio_sectors = bio_sectors(rq->bio);
2580 rq->buffer = bio_data(rq->bio);
2586 * if total number of sectors is less than the first segment
2587 * size, something has gone terribly wrong
2589 if (rq->nr_sectors < rq->current_nr_sectors) {
2590 printk("blk: request botched\n");
2591 rq->nr_sectors = rq->current_nr_sectors;
2596 static int __end_that_request_first(struct request *req, int uptodate,
2599 int total_bytes, bio_nbytes, error = 0, next_idx = 0;
2603 * for a REQ_BLOCK_PC request, we want to carry any eventual
2604 * sense key with us all the way through
2606 if (!blk_pc_request(req))
2611 if (blk_fs_request(req) && !(req->flags & REQ_QUIET))
2612 printk("end_request: I/O error, dev %s, sector %llu\n",
2613 req->rq_disk ? req->rq_disk->disk_name : "?",
2614 (unsigned long long)req->sector);
2617 total_bytes = bio_nbytes = 0;
2618 while ((bio = req->bio)) {
2621 if (nr_bytes >= bio->bi_size) {
2622 req->bio = bio->bi_next;
2623 nbytes = bio->bi_size;
2624 bio_endio(bio, nbytes, error);
2628 int idx = bio->bi_idx + next_idx;
2630 if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
2631 blk_dump_rq_flags(req, "__end_that");
2632 printk("%s: bio idx %d >= vcnt %d\n",
2634 bio->bi_idx, bio->bi_vcnt);
2638 nbytes = bio_iovec_idx(bio, idx)->bv_len;
2639 BIO_BUG_ON(nbytes > bio->bi_size);
2642 * not a complete bvec done
2644 if (unlikely(nbytes > nr_bytes)) {
2645 bio_nbytes += nr_bytes;
2646 total_bytes += nr_bytes;
2651 * advance to the next vector
2654 bio_nbytes += nbytes;
2657 total_bytes += nbytes;
2660 if ((bio = req->bio)) {
2662 * end more in this run, or just return 'not-done'
2664 if (unlikely(nr_bytes <= 0))
2676 * if the request wasn't completed, update state
2679 bio_endio(bio, bio_nbytes, error);
2680 bio->bi_idx += next_idx;
2681 bio_iovec(bio)->bv_offset += nr_bytes;
2682 bio_iovec(bio)->bv_len -= nr_bytes;
2685 blk_recalc_rq_sectors(req, total_bytes >> 9);
2686 blk_recalc_rq_segments(req);
2691 * end_that_request_first - end I/O on a request
2692 * @req: the request being processed
2693 * @uptodate: 0 for I/O error
2694 * @nr_sectors: number of sectors to end I/O on
2697 * Ends I/O on a number of sectors attached to @req, and sets it up
2698 * for the next range of segments (if any) in the cluster.
2701 * 0 - we are done with this request, call end_that_request_last()
2702 * 1 - still buffers pending for this request
2704 int end_that_request_first(struct request *req, int uptodate, int nr_sectors)
2706 return __end_that_request_first(req, uptodate, nr_sectors << 9);
2709 EXPORT_SYMBOL(end_that_request_first);
2712 * end_that_request_chunk - end I/O on a request
2713 * @req: the request being processed
2714 * @uptodate: 0 for I/O error
2715 * @nr_bytes: number of bytes to complete
2718 * Ends I/O on a number of bytes attached to @req, and sets it up
2719 * for the next range of segments (if any). Like end_that_request_first(),
2720 * but deals with bytes instead of sectors.
2723 * 0 - we are done with this request, call end_that_request_last()
2724 * 1 - still buffers pending for this request
2726 int end_that_request_chunk(struct request *req, int uptodate, int nr_bytes)
2728 return __end_that_request_first(req, uptodate, nr_bytes);
2731 EXPORT_SYMBOL(end_that_request_chunk);
2734 * queue lock must be held
2736 void end_that_request_last(struct request *req)
2738 struct gendisk *disk = req->rq_disk;
2739 struct completion *waiting = req->waiting;
2741 if (unlikely(laptop_mode) && blk_fs_request(req))
2742 laptop_io_completion();
2744 if (disk && blk_fs_request(req)) {
2745 unsigned long duration = jiffies - req->start_time;
2746 switch (rq_data_dir(req)) {
2748 disk_stat_inc(disk, writes);
2749 disk_stat_add(disk, write_ticks, duration);
2752 disk_stat_inc(disk, reads);
2753 disk_stat_add(disk, read_ticks, duration);
2756 disk_round_stats(disk);
2759 __blk_put_request(req->q, req);
2760 /* Do this LAST! The structure may be freed immediately afterwards */
2765 EXPORT_SYMBOL(end_that_request_last);
2767 void end_request(struct request *req, int uptodate)
2769 if (!end_that_request_first(req, uptodate, req->hard_cur_sectors)) {
2770 add_disk_randomness(req->rq_disk);
2771 blkdev_dequeue_request(req);
2772 end_that_request_last(req);
2776 EXPORT_SYMBOL(end_request);
2778 void blk_rq_bio_prep(request_queue_t *q, struct request *rq, struct bio *bio)
2780 /* first three bits are identical in rq->flags and bio->bi_rw */
2781 rq->flags |= (bio->bi_rw & 7);
2783 rq->nr_phys_segments = bio_phys_segments(q, bio);
2784 rq->nr_hw_segments = bio_hw_segments(q, bio);
2785 rq->current_nr_sectors = bio_cur_sectors(bio);
2786 rq->hard_cur_sectors = rq->current_nr_sectors;
2787 rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
2788 rq->nr_cbio_segments = bio_segments(bio);
2789 rq->nr_cbio_sectors = bio_sectors(bio);
2790 rq->buffer = bio_data(bio);
2792 rq->cbio = rq->bio = rq->biotail = bio;
2795 EXPORT_SYMBOL(blk_rq_bio_prep);
2797 void blk_rq_prep_restart(struct request *rq)
2801 bio = rq->cbio = rq->bio;
2803 rq->nr_cbio_segments = bio_segments(bio);
2804 rq->nr_cbio_sectors = bio_sectors(bio);
2805 rq->hard_cur_sectors = bio_cur_sectors(bio);
2806 rq->buffer = bio_data(bio);
2808 rq->sector = rq->hard_sector;
2809 rq->nr_sectors = rq->hard_nr_sectors;
2810 rq->current_nr_sectors = rq->hard_cur_sectors;
2813 EXPORT_SYMBOL(blk_rq_prep_restart);
2815 int kblockd_schedule_work(struct work_struct *work)
2817 return queue_work(kblockd_workqueue, work);
2820 void kblockd_flush(void)
2822 flush_workqueue(kblockd_workqueue);
2825 int __init blk_dev_init(void)
2827 kblockd_workqueue = create_workqueue("kblockd");
2828 if (!kblockd_workqueue)
2829 panic("Failed to create kblockd\n");
2831 request_cachep = kmem_cache_create("blkdev_requests",
2832 sizeof(struct request), 0, SLAB_PANIC, NULL, NULL);
2834 requestq_cachep = kmem_cache_create("blkdev_queue",
2835 sizeof(request_queue_t), 0, SLAB_PANIC, NULL, NULL);
2837 iocontext_cachep = kmem_cache_create("blkdev_ioc",
2838 sizeof(struct io_context), 0, SLAB_PANIC, NULL, NULL);
2840 blk_max_low_pfn = max_low_pfn;
2841 blk_max_pfn = max_pfn;
2846 * IO Context helper functions
2848 void put_io_context(struct io_context *ioc)
2853 BUG_ON(atomic_read(&ioc->refcount) == 0);
2855 if (atomic_dec_and_test(&ioc->refcount)) {
2856 if (ioc->aic && ioc->aic->dtor)
2857 ioc->aic->dtor(ioc->aic);
2858 kmem_cache_free(iocontext_cachep, ioc);
2862 /* Called by the exitting task */
2863 void exit_io_context(void)
2865 unsigned long flags;
2866 struct io_context *ioc;
2868 local_irq_save(flags);
2869 ioc = current->io_context;
2871 if (ioc->aic && ioc->aic->exit)
2872 ioc->aic->exit(ioc->aic);
2873 put_io_context(ioc);
2874 current->io_context = NULL;
2877 local_irq_restore(flags);
2881 * If the current task has no IO context then create one and initialise it.
2882 * If it does have a context, take a ref on it.
2884 * This is always called in the context of the task which submitted the I/O.
2885 * But weird things happen, so we disable local interrupts to ensure exclusive
2886 * access to *current.
2888 struct io_context *get_io_context(int gfp_flags)
2890 struct task_struct *tsk = current;
2891 unsigned long flags;
2892 struct io_context *ret;
2894 local_irq_save(flags);
2895 ret = tsk->io_context;
2897 ret = kmem_cache_alloc(iocontext_cachep, GFP_ATOMIC);
2899 atomic_set(&ret->refcount, 1);
2900 ret->pid = tsk->pid;
2901 ret->last_waited = jiffies; /* doesn't matter... */
2902 ret->nr_batch_requests = 0; /* because this is 0 */
2904 tsk->io_context = ret;
2908 atomic_inc(&ret->refcount);
2909 local_irq_restore(flags);
2913 void copy_io_context(struct io_context **pdst, struct io_context **psrc)
2915 struct io_context *src = *psrc;
2916 struct io_context *dst = *pdst;
2919 BUG_ON(atomic_read(&src->refcount) == 0);
2920 atomic_inc(&src->refcount);
2921 put_io_context(dst);
2926 void swap_io_context(struct io_context **ioc1, struct io_context **ioc2)
2928 struct io_context *temp;
2938 struct queue_sysfs_entry {
2939 struct attribute attr;
2940 ssize_t (*show)(struct request_queue *, char *);
2941 ssize_t (*store)(struct request_queue *, const char *, size_t);
2945 queue_var_show(unsigned int var, char *page)
2947 return sprintf(page, "%d\n", var);
2951 queue_var_store(unsigned long *var, const char *page, size_t count)
2953 char *p = (char *) page;
2955 *var = simple_strtoul(p, &p, 10);
2959 static ssize_t queue_requests_show(struct request_queue *q, char *page)
2961 return queue_var_show(q->nr_requests, (page));
2965 queue_requests_store(struct request_queue *q, const char *page, size_t count)
2967 struct request_list *rl = &q->rq;
2969 int ret = queue_var_store(&q->nr_requests, page, count);
2970 if (q->nr_requests < BLKDEV_MIN_RQ)
2971 q->nr_requests = BLKDEV_MIN_RQ;
2972 blk_queue_congestion_threshold(q);
2974 if (rl->count[READ] >= queue_congestion_on_threshold(q))
2975 set_queue_congested(q, READ);
2976 else if (rl->count[READ] < queue_congestion_off_threshold(q))
2977 clear_queue_congested(q, READ);
2979 if (rl->count[WRITE] >= queue_congestion_on_threshold(q))
2980 set_queue_congested(q, WRITE);
2981 else if (rl->count[WRITE] < queue_congestion_off_threshold(q))
2982 clear_queue_congested(q, WRITE);
2984 if (rl->count[READ] >= q->nr_requests) {
2985 blk_set_queue_full(q, READ);
2986 } else if (rl->count[READ]+1 <= q->nr_requests) {
2987 blk_clear_queue_full(q, READ);
2988 wake_up(&rl->wait[READ]);
2991 if (rl->count[WRITE] >= q->nr_requests) {
2992 blk_set_queue_full(q, WRITE);
2993 } else if (rl->count[WRITE]+1 <= q->nr_requests) {
2994 blk_clear_queue_full(q, WRITE);
2995 wake_up(&rl->wait[WRITE]);
3000 static ssize_t queue_ra_show(struct request_queue *q, char *page)
3002 int ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10);
3004 return queue_var_show(ra_kb, (page));
3008 queue_ra_store(struct request_queue *q, const char *page, size_t count)
3010 unsigned long ra_kb;
3011 ssize_t ret = queue_var_store(&ra_kb, page, count);
3013 if (ra_kb > (q->max_sectors >> 1))
3014 ra_kb = (q->max_sectors >> 1);
3016 q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10);
3020 static struct queue_sysfs_entry queue_requests_entry = {
3021 .attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR },
3022 .show = queue_requests_show,
3023 .store = queue_requests_store,
3026 static struct queue_sysfs_entry queue_ra_entry = {
3027 .attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR },
3028 .show = queue_ra_show,
3029 .store = queue_ra_store,
3032 static struct attribute *default_attrs[] = {
3033 &queue_requests_entry.attr,
3034 &queue_ra_entry.attr,
3038 #define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr)
3041 queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3043 struct queue_sysfs_entry *entry = to_queue(attr);
3044 struct request_queue *q;
3046 q = container_of(kobj, struct request_queue, kobj);
3050 return entry->show(q, page);
3054 queue_attr_store(struct kobject *kobj, struct attribute *attr,
3055 const char *page, size_t length)
3057 struct queue_sysfs_entry *entry = to_queue(attr);
3058 struct request_queue *q;
3060 q = container_of(kobj, struct request_queue, kobj);
3064 return entry->store(q, page, length);
3067 static struct sysfs_ops queue_sysfs_ops = {
3068 .show = queue_attr_show,
3069 .store = queue_attr_store,
3072 struct kobj_type queue_ktype = {
3073 .sysfs_ops = &queue_sysfs_ops,
3074 .default_attrs = default_attrs,
3077 int blk_register_queue(struct gendisk *disk)
3081 request_queue_t *q = disk->queue;
3083 if (!q || !q->request_fn)
3086 q->kobj.parent = kobject_get(&disk->kobj);
3087 if (!q->kobj.parent)
3090 snprintf(q->kobj.name, KOBJ_NAME_LEN, "%s", "queue");
3091 q->kobj.ktype = &queue_ktype;
3093 ret = kobject_register(&q->kobj);
3097 ret = elv_register_queue(q);
3099 kobject_unregister(&q->kobj);
3106 void blk_unregister_queue(struct gendisk *disk)
3108 request_queue_t *q = disk->queue;
3110 if (q && q->request_fn) {
3111 elv_unregister_queue(q);
3113 kobject_unregister(&q->kobj);
3114 kobject_put(&disk->kobj);
3118 asmlinkage int sys_ioprio_set(int ioprio)
3120 if (ioprio < IOPRIO_IDLE || ioprio > IOPRIO_RT)
3122 if (ioprio == IOPRIO_RT && !capable(CAP_SYS_ADMIN))
3125 printk("%s: set ioprio %d\n", current->comm, ioprio);
3126 current->ioprio = ioprio;
3130 asmlinkage int sys_ioprio_get(void)
3132 return current->ioprio;