4 * Copyright (C) 2002, Linus Torvalds.
8 * 04Jul2002 akpm@zip.com.au
10 * 11Sep2002 janetinc@us.ibm.com
11 * added readv/writev support.
12 * 29Oct2002 akpm@zip.com.au
13 * rewrote bio_add_page() support.
14 * 30Oct2002 pbadari@us.ibm.com
15 * added support for non-aligned IO.
16 * 06Nov2002 pbadari@us.ibm.com
17 * added asynchronous IO support.
18 * 21Jul2003 nathans@sgi.com
19 * added IO completion notifier.
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/types.h>
27 #include <linux/slab.h>
28 #include <linux/highmem.h>
29 #include <linux/pagemap.h>
30 #include <linux/bio.h>
31 #include <linux/wait.h>
32 #include <linux/err.h>
33 #include <linux/blkdev.h>
34 #include <linux/buffer_head.h>
35 #include <linux/rwsem.h>
36 #include <linux/uio.h>
37 #include <asm/atomic.h>
40 * How many user pages to map in one call to get_user_pages(). This determines
41 * the size of a structure on the stack.
46 * This code generally works in units of "dio_blocks". A dio_block is
47 * somewhere between the hard sector size and the filesystem block size. it
48 * is determined on a per-invocation basis. When talking to the filesystem
49 * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
50 * down by dio->blkfactor. Similarly, fs-blocksize quantities are converted
51 * to bio_block quantities by shifting left by blkfactor.
53 * If blkfactor is zero then the user's request was aligned to the filesystem's
56 * needs_locking is set for regular files on direct-IO-naive filesystems. It
57 * determines whether we need to do the fancy locking which prevents direct-IO
58 * from being able to read uninitialised disk blocks.
62 /* BIO submission state */
63 struct bio *bio; /* bio under assembly */
66 int needs_locking; /* doesn't change */
67 unsigned blkbits; /* doesn't change */
68 unsigned blkfactor; /* When we're using an alignment which
69 is finer than the filesystem's soft
70 blocksize, this specifies how much
71 finer. blkfactor=2 means 1/4-block
72 alignment. Does not change */
73 unsigned start_zero_done; /* flag: sub-blocksize zeroing has
74 been performed at the start of a
76 int pages_in_io; /* approximate total IO pages */
77 size_t size; /* total request size (doesn't change)*/
78 sector_t block_in_file; /* Current offset into the underlying
79 file in dio_block units. */
80 unsigned blocks_available; /* At block_in_file. changes */
81 sector_t final_block_in_request;/* doesn't change */
82 unsigned first_block_in_page; /* doesn't change, Used only once */
83 int boundary; /* prev block is at a boundary */
84 int reap_counter; /* rate limit reaping */
85 get_blocks_t *get_blocks; /* block mapping function */
86 dio_iodone_t *end_io; /* IO completion function */
87 sector_t final_block_in_bio; /* current final block in bio + 1 */
88 sector_t next_block_for_io; /* next block to be put under IO,
89 in dio_blocks units */
90 struct buffer_head map_bh; /* last get_blocks() result */
93 * Deferred addition of a page to the dio. These variables are
94 * private to dio_send_cur_page(), submit_page_section() and
97 struct page *cur_page; /* The page */
98 unsigned cur_page_offset; /* Offset into it, in bytes */
99 unsigned cur_page_len; /* Nr of bytes at cur_page_offset */
100 sector_t cur_page_block; /* Where it starts */
103 * Page fetching state. These variables belong to dio_refill_pages().
105 int curr_page; /* changes */
106 int total_pages; /* doesn't change */
107 unsigned long curr_user_address;/* changes */
110 * Page queue. These variables belong to dio_refill_pages() and
113 struct page *pages[DIO_PAGES]; /* page buffer */
114 unsigned head; /* next page to process */
115 unsigned tail; /* last valid page + 1 */
116 int page_errors; /* errno from get_user_pages() */
118 /* BIO completion state */
119 spinlock_t bio_lock; /* protects BIO fields below */
120 int bio_count; /* nr bios to be completed */
121 int bios_in_flight; /* nr bios in flight */
122 struct bio *bio_list; /* singly linked via bi_private */
123 struct task_struct *waiter; /* waiting task (NULL if none) */
125 /* AIO related stuff */
126 struct kiocb *iocb; /* kiocb */
127 int is_async; /* is IO async ? */
128 ssize_t result; /* IO result */
132 * How many pages are in the queue?
134 static inline unsigned dio_pages_present(struct dio *dio)
136 return dio->tail - dio->head;
140 * Go grab and pin some userspace pages. Typically we'll get 64 at a time.
142 static int dio_refill_pages(struct dio *dio)
147 nr_pages = min(dio->total_pages - dio->curr_page, DIO_PAGES);
148 down_read(¤t->mm->mmap_sem);
149 ret = get_user_pages(
150 current, /* Task for fault acounting */
151 current->mm, /* whose pages? */
152 dio->curr_user_address, /* Where from? */
153 nr_pages, /* How many pages? */
154 dio->rw == READ, /* Write to memory? */
158 up_read(¤t->mm->mmap_sem);
160 if (ret < 0 && dio->blocks_available && (dio->rw == WRITE)) {
162 * A memory fault, but the filesystem has some outstanding
163 * mapped blocks. We need to use those blocks up to avoid
164 * leaking stale data in the file.
166 if (dio->page_errors == 0)
167 dio->page_errors = ret;
168 dio->pages[0] = ZERO_PAGE(dio->curr_user_address);
176 dio->curr_user_address += ret * PAGE_SIZE;
177 dio->curr_page += ret;
187 * Get another userspace page. Returns an ERR_PTR on error. Pages are
188 * buffered inside the dio so that we can call get_user_pages() against a
189 * decent number of pages, less frequently. To provide nicer use of the
192 static struct page *dio_get_page(struct dio *dio)
194 if (dio_pages_present(dio) == 0) {
197 ret = dio_refill_pages(dio);
200 BUG_ON(dio_pages_present(dio) == 0);
202 return dio->pages[dio->head++];
206 * Called when all DIO BIO I/O has been completed - let the filesystem
207 * know, if it registered an interest earlier via get_blocks. Pass the
208 * private field of the map buffer_head so that filesystems can use it
209 * to hold additional state between get_blocks calls and dio_complete.
211 static void dio_complete(struct dio *dio, loff_t offset, ssize_t bytes)
213 if (dio->end_io && dio->result)
214 dio->end_io(dio->inode, offset, bytes, dio->map_bh.b_private);
215 if (dio->needs_locking)
216 up_read(&dio->inode->i_alloc_sem);
220 * Called when a BIO has been processed. If the count goes to zero then IO is
221 * complete and we can signal this to the AIO layer.
223 static void finished_one_bio(struct dio *dio)
227 spin_lock_irqsave(&dio->bio_lock, flags);
228 if (dio->bio_count == 1) {
231 * Last reference to the dio is going away.
232 * Drop spinlock and complete the DIO.
234 spin_unlock_irqrestore(&dio->bio_lock, flags);
235 dio_complete(dio, dio->block_in_file << dio->blkbits,
237 /* Complete AIO later if falling back to buffered i/o */
238 if (dio->result == dio->size || dio->rw == READ) {
239 aio_complete(dio->iocb, dio->result, 0);
244 * Falling back to buffered
246 spin_lock_irqsave(&dio->bio_lock, flags);
249 wake_up_process(dio->waiter);
250 spin_unlock_irqrestore(&dio->bio_lock, flags);
256 spin_unlock_irqrestore(&dio->bio_lock, flags);
259 static int dio_bio_complete(struct dio *dio, struct bio *bio);
261 * Asynchronous IO callback.
263 static int dio_bio_end_aio(struct bio *bio, unsigned int bytes_done, int error)
265 struct dio *dio = bio->bi_private;
270 /* cleanup the bio */
271 dio_bio_complete(dio, bio);
276 * The BIO completion handler simply queues the BIO up for the process-context
279 * During I/O bi_private points at the dio. After I/O, bi_private is used to
280 * implement a singly-linked list of completed BIOs, at dio->bio_list.
282 static int dio_bio_end_io(struct bio *bio, unsigned int bytes_done, int error)
284 struct dio *dio = bio->bi_private;
290 spin_lock_irqsave(&dio->bio_lock, flags);
291 bio->bi_private = dio->bio_list;
293 dio->bios_in_flight--;
294 if (dio->waiter && dio->bios_in_flight == 0)
295 wake_up_process(dio->waiter);
296 spin_unlock_irqrestore(&dio->bio_lock, flags);
301 dio_bio_alloc(struct dio *dio, struct block_device *bdev,
302 sector_t first_sector, int nr_vecs)
306 bio = bio_alloc(GFP_KERNEL, nr_vecs);
311 bio->bi_sector = first_sector;
313 bio->bi_end_io = dio_bio_end_aio;
315 bio->bi_end_io = dio_bio_end_io;
322 * In the AIO read case we speculatively dirty the pages before starting IO.
323 * During IO completion, any of these pages which happen to have been written
324 * back will be redirtied by bio_check_pages_dirty().
326 static void dio_bio_submit(struct dio *dio)
328 struct bio *bio = dio->bio;
331 bio->bi_private = dio;
332 spin_lock_irqsave(&dio->bio_lock, flags);
334 dio->bios_in_flight++;
335 spin_unlock_irqrestore(&dio->bio_lock, flags);
336 if (dio->is_async && dio->rw == READ)
337 bio_set_pages_dirty(bio);
338 submit_bio(dio->rw, bio);
345 * Release any resources in case of a failure
347 static void dio_cleanup(struct dio *dio)
349 while (dio_pages_present(dio))
350 page_cache_release(dio_get_page(dio));
354 * Wait for the next BIO to complete. Remove it and return it.
356 static struct bio *dio_await_one(struct dio *dio)
361 spin_lock_irqsave(&dio->bio_lock, flags);
362 while (dio->bio_list == NULL) {
363 set_current_state(TASK_UNINTERRUPTIBLE);
364 if (dio->bio_list == NULL) {
365 dio->waiter = current;
366 spin_unlock_irqrestore(&dio->bio_lock, flags);
367 blk_run_address_space(dio->inode->i_mapping);
369 spin_lock_irqsave(&dio->bio_lock, flags);
372 set_current_state(TASK_RUNNING);
375 dio->bio_list = bio->bi_private;
376 spin_unlock_irqrestore(&dio->bio_lock, flags);
381 * Process one completed BIO. No locks are held.
383 static int dio_bio_complete(struct dio *dio, struct bio *bio)
385 const int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
386 struct bio_vec *bvec = bio->bi_io_vec;
392 if (dio->is_async && dio->rw == READ) {
393 bio_check_pages_dirty(bio); /* transfers ownership */
395 for (page_no = 0; page_no < bio->bi_vcnt; page_no++) {
396 struct page *page = bvec[page_no].bv_page;
398 if (dio->rw == READ && !PageCompound(page))
399 set_page_dirty_lock(page);
400 page_cache_release(page);
404 finished_one_bio(dio);
405 return uptodate ? 0 : -EIO;
409 * Wait on and process all in-flight BIOs.
411 static int dio_await_completion(struct dio *dio)
419 * The bio_lock is not held for the read of bio_count.
420 * This is ok since it is the dio_bio_complete() that changes
423 while (dio->bio_count) {
424 struct bio *bio = dio_await_one(dio);
427 ret2 = dio_bio_complete(dio, bio);
435 * A really large O_DIRECT read or write can generate a lot of BIOs. So
436 * to keep the memory consumption sane we periodically reap any completed BIOs
437 * during the BIO generation phase.
439 * This also helps to limit the peak amount of pinned userspace memory.
441 static int dio_bio_reap(struct dio *dio)
445 if (dio->reap_counter++ >= 64) {
446 while (dio->bio_list) {
451 spin_lock_irqsave(&dio->bio_lock, flags);
453 dio->bio_list = bio->bi_private;
454 spin_unlock_irqrestore(&dio->bio_lock, flags);
455 ret2 = dio_bio_complete(dio, bio);
459 dio->reap_counter = 0;
465 * Call into the fs to map some more disk blocks. We record the current number
466 * of available blocks at dio->blocks_available. These are in units of the
467 * fs blocksize, (1 << inode->i_blkbits).
469 * The fs is allowed to map lots of blocks at once. If it wants to do that,
470 * it uses the passed inode-relative block number as the file offset, as usual.
472 * get_blocks() is passed the number of i_blkbits-sized blocks which direct_io
473 * has remaining to do. The fs should not map more than this number of blocks.
475 * If the fs has mapped a lot of blocks, it should populate bh->b_size to
476 * indicate how much contiguous disk space has been made available at
479 * If *any* of the mapped blocks are new, then the fs must set buffer_new().
480 * This isn't very efficient...
482 * In the case of filesystem holes: the fs may return an arbitrarily-large
483 * hole by returning an appropriate value in b_size and by clearing
484 * buffer_mapped(). However the direct-io code will only process holes one
485 * block at a time - it will repeatedly call get_blocks() as it walks the hole.
487 static int get_more_blocks(struct dio *dio)
490 struct buffer_head *map_bh = &dio->map_bh;
491 sector_t fs_startblk; /* Into file, in filesystem-sized blocks */
492 unsigned long fs_count; /* Number of filesystem-sized blocks */
493 unsigned long dio_count;/* Number of dio_block-sized blocks */
494 unsigned long blkmask;
498 * If there was a memory error and we've overwritten all the
499 * mapped blocks then we can now return that memory error
501 ret = dio->page_errors;
505 BUG_ON(dio->block_in_file >= dio->final_block_in_request);
506 fs_startblk = dio->block_in_file >> dio->blkfactor;
507 dio_count = dio->final_block_in_request - dio->block_in_file;
508 fs_count = dio_count >> dio->blkfactor;
509 blkmask = (1 << dio->blkfactor) - 1;
510 if (dio_count & blkmask)
513 if (dio->needs_locking) {
514 if (dio->block_in_file >= (i_size_read(dio->inode) >>
519 * For writes inside i_size we forbid block creations: only
520 * overwrites are permitted. We fall back to buffered writes
521 * at a higher level for inside-i_size block-instantiating
524 ret = (*dio->get_blocks)(dio->inode, fs_startblk, fs_count,
525 map_bh, (dio->rw == WRITE) && beyond_eof);
531 * There is no bio. Make one now.
533 static int dio_new_bio(struct dio *dio, sector_t start_sector)
538 ret = dio_bio_reap(dio);
541 sector = start_sector << (dio->blkbits - 9);
542 nr_pages = min(dio->pages_in_io, bio_get_nr_vecs(dio->map_bh.b_bdev));
543 BUG_ON(nr_pages <= 0);
544 ret = dio_bio_alloc(dio, dio->map_bh.b_bdev, sector, nr_pages);
551 * Attempt to put the current chunk of 'cur_page' into the current BIO. If
552 * that was successful then update final_block_in_bio and take a ref against
553 * the just-added page.
555 * Return zero on success. Non-zero means the caller needs to start a new BIO.
557 static int dio_bio_add_page(struct dio *dio)
561 ret = bio_add_page(dio->bio, dio->cur_page,
562 dio->cur_page_len, dio->cur_page_offset);
563 if (ret == dio->cur_page_len) {
565 page_cache_get(dio->cur_page);
566 dio->final_block_in_bio = dio->cur_page_block +
567 (dio->cur_page_len >> dio->blkbits);
576 * Put cur_page under IO. The section of cur_page which is described by
577 * cur_page_offset,cur_page_len is put into a BIO. The section of cur_page
578 * starts on-disk at cur_page_block.
580 * We take a ref against the page here (on behalf of its presence in the bio).
582 * The caller of this function is responsible for removing cur_page from the
583 * dio, and for dropping the refcount which came from that presence.
585 static int dio_send_cur_page(struct dio *dio)
591 * See whether this new request is contiguous with the old
593 if (dio->final_block_in_bio != dio->cur_page_block)
596 * Submit now if the underlying fs is about to perform a
603 if (dio->bio == NULL) {
604 ret = dio_new_bio(dio, dio->cur_page_block);
609 if (dio_bio_add_page(dio) != 0) {
611 ret = dio_new_bio(dio, dio->cur_page_block);
613 ret = dio_bio_add_page(dio);
622 * An autonomous function to put a chunk of a page under deferred IO.
624 * The caller doesn't actually know (or care) whether this piece of page is in
625 * a BIO, or is under IO or whatever. We just take care of all possible
626 * situations here. The separation between the logic of do_direct_IO() and
627 * that of submit_page_section() is important for clarity. Please don't break.
629 * The chunk of page starts on-disk at blocknr.
631 * We perform deferred IO, by recording the last-submitted page inside our
632 * private part of the dio structure. If possible, we just expand the IO
633 * across that page here.
635 * If that doesn't work out then we put the old page into the bio and add this
636 * page to the dio instead.
639 submit_page_section(struct dio *dio, struct page *page,
640 unsigned offset, unsigned len, sector_t blocknr)
645 * Can we just grow the current page's presence in the dio?
647 if ( (dio->cur_page == page) &&
648 (dio->cur_page_offset + dio->cur_page_len == offset) &&
649 (dio->cur_page_block +
650 (dio->cur_page_len >> dio->blkbits) == blocknr)) {
651 dio->cur_page_len += len;
654 * If dio->boundary then we want to schedule the IO now to
655 * avoid metadata seeks.
658 ret = dio_send_cur_page(dio);
659 page_cache_release(dio->cur_page);
660 dio->cur_page = NULL;
666 * If there's a deferred page already there then send it.
669 ret = dio_send_cur_page(dio);
670 page_cache_release(dio->cur_page);
671 dio->cur_page = NULL;
676 page_cache_get(page); /* It is in dio */
677 dio->cur_page = page;
678 dio->cur_page_offset = offset;
679 dio->cur_page_len = len;
680 dio->cur_page_block = blocknr;
686 * Clean any dirty buffers in the blockdev mapping which alias newly-created
687 * file blocks. Only called for S_ISREG files - blockdevs do not set
690 static void clean_blockdev_aliases(struct dio *dio)
695 nblocks = dio->map_bh.b_size >> dio->inode->i_blkbits;
697 for (i = 0; i < nblocks; i++) {
698 unmap_underlying_metadata(dio->map_bh.b_bdev,
699 dio->map_bh.b_blocknr + i);
704 * If we are not writing the entire block and get_block() allocated
705 * the block for us, we need to fill-in the unused portion of the
706 * block with zeros. This happens only if user-buffer, fileoffset or
707 * io length is not filesystem block-size multiple.
709 * `end' is zero if we're doing the start of the IO, 1 at the end of the
712 static void dio_zero_block(struct dio *dio, int end)
714 unsigned dio_blocks_per_fs_block;
715 unsigned this_chunk_blocks; /* In dio_blocks */
716 unsigned this_chunk_bytes;
719 dio->start_zero_done = 1;
720 if (!dio->blkfactor || !buffer_new(&dio->map_bh))
723 dio_blocks_per_fs_block = 1 << dio->blkfactor;
724 this_chunk_blocks = dio->block_in_file & (dio_blocks_per_fs_block - 1);
726 if (!this_chunk_blocks)
730 * We need to zero out part of an fs block. It is either at the
731 * beginning or the end of the fs block.
734 this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
736 this_chunk_bytes = this_chunk_blocks << dio->blkbits;
738 page = ZERO_PAGE(dio->curr_user_address);
739 if (submit_page_section(dio, page, 0, this_chunk_bytes,
740 dio->next_block_for_io))
743 dio->next_block_for_io += this_chunk_blocks;
747 * Walk the user pages, and the file, mapping blocks to disk and generating
748 * a sequence of (page,offset,len,block) mappings. These mappings are injected
749 * into submit_page_section(), which takes care of the next stage of submission
751 * Direct IO against a blockdev is different from a file. Because we can
752 * happily perform page-sized but 512-byte aligned IOs. It is important that
753 * blockdev IO be able to have fine alignment and large sizes.
755 * So what we do is to permit the ->get_blocks function to populate bh.b_size
756 * with the size of IO which is permitted at this offset and this i_blkbits.
758 * For best results, the blockdev should be set up with 512-byte i_blkbits and
759 * it should set b_size to PAGE_SIZE or more inside get_blocks(). This gives
760 * fine alignment but still allows this function to work in PAGE_SIZE units.
762 static int do_direct_IO(struct dio *dio)
764 const unsigned blkbits = dio->blkbits;
765 const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
767 unsigned block_in_page;
768 struct buffer_head *map_bh = &dio->map_bh;
771 /* The I/O can start at any block offset within the first page */
772 block_in_page = dio->first_block_in_page;
774 while (dio->block_in_file < dio->final_block_in_request) {
775 page = dio_get_page(dio);
781 while (block_in_page < blocks_per_page) {
782 unsigned offset_in_page = block_in_page << blkbits;
783 unsigned this_chunk_bytes; /* # of bytes mapped */
784 unsigned this_chunk_blocks; /* # of blocks */
787 if (dio->blocks_available == 0) {
789 * Need to go and map some more disk
791 unsigned long blkmask;
792 unsigned long dio_remainder;
794 ret = get_more_blocks(dio);
796 page_cache_release(page);
799 if (!buffer_mapped(map_bh))
802 dio->blocks_available =
803 map_bh->b_size >> dio->blkbits;
804 dio->next_block_for_io =
805 map_bh->b_blocknr << dio->blkfactor;
806 if (buffer_new(map_bh))
807 clean_blockdev_aliases(dio);
812 blkmask = (1 << dio->blkfactor) - 1;
813 dio_remainder = (dio->block_in_file & blkmask);
816 * If we are at the start of IO and that IO
817 * starts partway into a fs-block,
818 * dio_remainder will be non-zero. If the IO
819 * is a read then we can simply advance the IO
820 * cursor to the first block which is to be
821 * read. But if the IO is a write and the
822 * block was newly allocated we cannot do that;
823 * the start of the fs block must be zeroed out
826 if (!buffer_new(map_bh))
827 dio->next_block_for_io += dio_remainder;
828 dio->blocks_available -= dio_remainder;
832 if (!buffer_mapped(map_bh)) {
835 /* AKPM: eargh, -ENOTBLK is a hack */
836 if (dio->rw == WRITE)
839 if (dio->block_in_file >=
840 i_size_read(dio->inode)>>blkbits) {
842 page_cache_release(page);
845 kaddr = kmap_atomic(page, KM_USER0);
846 memset(kaddr + (block_in_page << blkbits),
848 flush_dcache_page(page);
849 kunmap_atomic(kaddr, KM_USER0);
850 dio->block_in_file++;
856 * If we're performing IO which has an alignment which
857 * is finer than the underlying fs, go check to see if
858 * we must zero out the start of this block.
860 if (unlikely(dio->blkfactor && !dio->start_zero_done))
861 dio_zero_block(dio, 0);
864 * Work out, in this_chunk_blocks, how much disk we
865 * can add to this page
867 this_chunk_blocks = dio->blocks_available;
868 u = (PAGE_SIZE - offset_in_page) >> blkbits;
869 if (this_chunk_blocks > u)
870 this_chunk_blocks = u;
871 u = dio->final_block_in_request - dio->block_in_file;
872 if (this_chunk_blocks > u)
873 this_chunk_blocks = u;
874 this_chunk_bytes = this_chunk_blocks << blkbits;
875 BUG_ON(this_chunk_bytes == 0);
877 dio->boundary = buffer_boundary(map_bh);
878 ret = submit_page_section(dio, page, offset_in_page,
879 this_chunk_bytes, dio->next_block_for_io);
881 page_cache_release(page);
884 dio->next_block_for_io += this_chunk_blocks;
886 dio->block_in_file += this_chunk_blocks;
887 block_in_page += this_chunk_blocks;
888 dio->blocks_available -= this_chunk_blocks;
890 if (dio->block_in_file > dio->final_block_in_request)
892 if (dio->block_in_file == dio->final_block_in_request)
896 /* Drop the ref which was taken in get_user_pages() */
897 page_cache_release(page);
905 * Releases both i_sem and i_alloc_sem
908 direct_io_worker(int rw, struct kiocb *iocb, struct inode *inode,
909 const struct iovec *iov, loff_t offset, unsigned long nr_segs,
910 unsigned blkbits, get_blocks_t get_blocks, dio_iodone_t end_io,
913 unsigned long user_addr;
922 dio->blkbits = blkbits;
923 dio->blkfactor = inode->i_blkbits - blkbits;
924 dio->start_zero_done = 0;
926 dio->block_in_file = offset >> blkbits;
927 dio->blocks_available = 0;
928 dio->cur_page = NULL;
931 dio->reap_counter = 0;
932 dio->get_blocks = get_blocks;
933 dio->end_io = end_io;
934 dio->map_bh.b_private = NULL;
935 dio->final_block_in_bio = -1;
936 dio->next_block_for_io = -1;
938 dio->page_errors = 0;
943 * BIO completion state.
945 * ->bio_count starts out at one, and we decrement it to zero after all
946 * BIOs are submitted. This to avoid the situation where a really fast
947 * (or synchronous) device could take the count to zero while we're
948 * still submitting BIOs.
951 dio->bios_in_flight = 0;
952 spin_lock_init(&dio->bio_lock);
953 dio->bio_list = NULL;
956 dio->pages_in_io = 0;
957 for (seg = 0; seg < nr_segs; seg++)
958 dio->pages_in_io += (iov[seg].iov_len >> blkbits) + 2;
960 for (seg = 0; seg < nr_segs; seg++) {
961 user_addr = (unsigned long)iov[seg].iov_base;
962 dio->size += bytes = iov[seg].iov_len;
964 /* Index into the first page of the first block */
965 dio->first_block_in_page = (user_addr & ~PAGE_MASK) >> blkbits;
966 dio->final_block_in_request = dio->block_in_file +
968 /* Page fetching state */
973 dio->total_pages = 0;
974 if (user_addr & (PAGE_SIZE-1)) {
976 bytes -= PAGE_SIZE - (user_addr & (PAGE_SIZE - 1));
978 dio->total_pages += (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
979 dio->curr_user_address = user_addr;
981 ret = do_direct_IO(dio);
983 dio->result += iov[seg].iov_len -
984 ((dio->final_block_in_request - dio->block_in_file) <<
991 } /* end iovec loop */
993 if (ret == -ENOTBLK && rw == WRITE) {
995 * The remaining part of the request will be
996 * be handled by buffered I/O when we return
1001 * There may be some unwritten disk at the end of a part-written
1002 * fs-block-sized block. Go zero that now.
1004 dio_zero_block(dio, 1);
1006 if (dio->cur_page) {
1007 ret2 = dio_send_cur_page(dio);
1010 page_cache_release(dio->cur_page);
1011 dio->cur_page = NULL;
1014 dio_bio_submit(dio);
1017 * It is possible that, we return short IO due to end of file.
1018 * In that case, we need to release all the pages we got hold on.
1023 * All block lookups have been performed. For READ requests
1024 * we can let i_sem go now that its achieved its purpose
1025 * of protecting us from looking up uninitialized blocks.
1027 if ((rw == READ) && dio->needs_locking)
1028 up(&dio->inode->i_sem);
1031 * OK, all BIOs are submitted, so we can decrement bio_count to truly
1032 * reflect the number of to-be-processed BIOs.
1034 if (dio->is_async) {
1035 int should_wait = 0;
1037 if (dio->result < dio->size && rw == WRITE) {
1038 dio->waiter = current;
1043 finished_one_bio(dio); /* This can free the dio */
1044 blk_run_address_space(inode->i_mapping);
1046 unsigned long flags;
1048 * Wait for already issued I/O to drain out and
1049 * release its references to user-space pages
1050 * before returning to fallback on buffered I/O
1053 spin_lock_irqsave(&dio->bio_lock, flags);
1054 set_current_state(TASK_UNINTERRUPTIBLE);
1055 while (dio->bio_count) {
1056 spin_unlock_irqrestore(&dio->bio_lock, flags);
1058 spin_lock_irqsave(&dio->bio_lock, flags);
1059 set_current_state(TASK_UNINTERRUPTIBLE);
1061 spin_unlock_irqrestore(&dio->bio_lock, flags);
1062 set_current_state(TASK_RUNNING);
1066 ssize_t transferred = 0;
1068 finished_one_bio(dio);
1069 ret2 = dio_await_completion(dio);
1073 ret = dio->page_errors;
1075 loff_t i_size = i_size_read(inode);
1077 transferred = dio->result;
1079 * Adjust the return value if the read crossed a
1080 * non-block-aligned EOF.
1082 if (rw == READ && (offset + transferred > i_size))
1083 transferred = i_size - offset;
1085 dio_complete(dio, offset, transferred);
1089 /* We could have also come here on an AIO file extend */
1090 if (!is_sync_kiocb(iocb) && rw == WRITE &&
1091 ret >= 0 && dio->result == dio->size)
1093 * For AIO writes where we have completed the
1094 * i/o, we have to mark the the aio complete.
1096 aio_complete(iocb, ret, 0);
1103 * This is a library function for use by filesystem drivers.
1105 * For writes to S_ISREG files, we are called under i_sem and return with i_sem
1106 * held, even though it is internally dropped.
1108 * For writes to S_ISBLK files, i_sem is not held on entry; it is never taken.
1111 __blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
1112 struct block_device *bdev, const struct iovec *iov, loff_t offset,
1113 unsigned long nr_segs, get_blocks_t get_blocks, dio_iodone_t end_io,
1114 int needs_special_locking)
1119 unsigned blkbits = inode->i_blkbits;
1120 unsigned bdev_blkbits = 0;
1121 unsigned blocksize_mask = (1 << blkbits) - 1;
1122 ssize_t retval = -EINVAL;
1123 loff_t end = offset;
1128 bdev_blkbits = blksize_bits(bdev_hardsect_size(bdev));
1130 if (offset & blocksize_mask) {
1132 blkbits = bdev_blkbits;
1133 blocksize_mask = (1 << blkbits) - 1;
1134 if (offset & blocksize_mask)
1138 /* Check the memory alignment. Blocks cannot straddle pages */
1139 for (seg = 0; seg < nr_segs; seg++) {
1140 addr = (unsigned long)iov[seg].iov_base;
1141 size = iov[seg].iov_len;
1143 if ((addr & blocksize_mask) || (size & blocksize_mask)) {
1145 blkbits = bdev_blkbits;
1146 blocksize_mask = (1 << blkbits) - 1;
1147 if ((addr & blocksize_mask) || (size & blocksize_mask))
1152 dio = kmalloc(sizeof(*dio), GFP_KERNEL);
1158 * For regular files,
1159 * readers need to grab i_sem and i_alloc_sem
1160 * writers need to grab i_alloc_sem only (i_sem is already held)
1163 if (S_ISREG(inode->i_mode) && needs_special_locking) {
1166 struct address_space *mapping;
1168 mapping = iocb->ki_filp->f_mapping;
1169 down(&inode->i_sem);
1170 retval = filemap_write_and_wait(mapping);
1177 down_read(&inode->i_alloc_sem);
1179 dio->needs_locking = needs_locking;
1181 * For file extending writes updating i_size before data
1182 * writeouts complete can expose uninitialized blocks. So
1183 * even for AIO, we need to wait for i/o to complete before
1184 * returning in this case.
1186 dio->is_async = !is_sync_kiocb(iocb) && !((rw == WRITE) &&
1187 (end > i_size_read(inode)));
1189 retval = direct_io_worker(rw, iocb, inode, iov, offset,
1190 nr_segs, blkbits, get_blocks, end_io, dio);
1194 EXPORT_SYMBOL(__blockdev_direct_IO);