]> bbs.cooldavid.org Git - net-next-2.6.git/blame - fs/direct-io.c
[XFS] Fix compiler warning and small code inconsistencies in compat
[net-next-2.6.git] / fs / direct-io.c
CommitLineData
1da177e4
LT
1/*
2 * fs/direct-io.c
3 *
4 * Copyright (C) 2002, Linus Torvalds.
5 *
6 * O_DIRECT
7 *
8 * 04Jul2002 akpm@zip.com.au
9 * Initial version
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.
20 */
21
22#include <linux/kernel.h>
23#include <linux/module.h>
24#include <linux/types.h>
25#include <linux/fs.h>
26#include <linux/mm.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>
38
39/*
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.
42 */
43#define DIO_PAGES 64
44
45/*
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.
52 *
53 * If blkfactor is zero then the user's request was aligned to the filesystem's
54 * blocksize.
55 *
56 * lock_type is DIO_LOCKING for regular files on direct-IO-naive filesystems.
57 * This determines whether we need to do the fancy locking which prevents
58 * direct-IO from being able to read uninitialised disk blocks. If its zero
1b1dcc1b 59 * (blockdev) this locking is not done, and if it is DIO_OWN_LOCKING i_mutex is
1da177e4
LT
60 * not held for the entire direct write (taken briefly, initially, during a
61 * direct read though, but its never held for the duration of a direct-IO).
62 */
63
64struct dio {
65 /* BIO submission state */
66 struct bio *bio; /* bio under assembly */
67 struct inode *inode;
68 int rw;
29504ff3 69 loff_t i_size; /* i_size when submitted */
1da177e4
LT
70 int lock_type; /* doesn't change */
71 unsigned blkbits; /* doesn't change */
72 unsigned blkfactor; /* When we're using an alignment which
73 is finer than the filesystem's soft
74 blocksize, this specifies how much
75 finer. blkfactor=2 means 1/4-block
76 alignment. Does not change */
77 unsigned start_zero_done; /* flag: sub-blocksize zeroing has
78 been performed at the start of a
79 write */
80 int pages_in_io; /* approximate total IO pages */
81 size_t size; /* total request size (doesn't change)*/
82 sector_t block_in_file; /* Current offset into the underlying
83 file in dio_block units. */
84 unsigned blocks_available; /* At block_in_file. changes */
85 sector_t final_block_in_request;/* doesn't change */
86 unsigned first_block_in_page; /* doesn't change, Used only once */
87 int boundary; /* prev block is at a boundary */
88 int reap_counter; /* rate limit reaping */
1d8fa7a2 89 get_block_t *get_block; /* block mapping function */
1da177e4
LT
90 dio_iodone_t *end_io; /* IO completion function */
91 sector_t final_block_in_bio; /* current final block in bio + 1 */
92 sector_t next_block_for_io; /* next block to be put under IO,
93 in dio_blocks units */
1d8fa7a2 94 struct buffer_head map_bh; /* last get_block() result */
1da177e4
LT
95
96 /*
97 * Deferred addition of a page to the dio. These variables are
98 * private to dio_send_cur_page(), submit_page_section() and
99 * dio_bio_add_page().
100 */
101 struct page *cur_page; /* The page */
102 unsigned cur_page_offset; /* Offset into it, in bytes */
103 unsigned cur_page_len; /* Nr of bytes at cur_page_offset */
104 sector_t cur_page_block; /* Where it starts */
105
106 /*
107 * Page fetching state. These variables belong to dio_refill_pages().
108 */
109 int curr_page; /* changes */
110 int total_pages; /* doesn't change */
111 unsigned long curr_user_address;/* changes */
112
113 /*
114 * Page queue. These variables belong to dio_refill_pages() and
115 * dio_get_page().
116 */
117 struct page *pages[DIO_PAGES]; /* page buffer */
118 unsigned head; /* next page to process */
119 unsigned tail; /* last valid page + 1 */
120 int page_errors; /* errno from get_user_pages() */
121
122 /* BIO completion state */
123 spinlock_t bio_lock; /* protects BIO fields below */
124 int bio_count; /* nr bios to be completed */
125 int bios_in_flight; /* nr bios in flight */
126 struct bio *bio_list; /* singly linked via bi_private */
127 struct task_struct *waiter; /* waiting task (NULL if none) */
128
129 /* AIO related stuff */
130 struct kiocb *iocb; /* kiocb */
131 int is_async; /* is IO async ? */
174e27c6 132 int io_error; /* IO error in completion path */
1da177e4
LT
133 ssize_t result; /* IO result */
134};
135
136/*
137 * How many pages are in the queue?
138 */
139static inline unsigned dio_pages_present(struct dio *dio)
140{
141 return dio->tail - dio->head;
142}
143
144/*
145 * Go grab and pin some userspace pages. Typically we'll get 64 at a time.
146 */
147static int dio_refill_pages(struct dio *dio)
148{
149 int ret;
150 int nr_pages;
151
152 nr_pages = min(dio->total_pages - dio->curr_page, DIO_PAGES);
153 down_read(&current->mm->mmap_sem);
154 ret = get_user_pages(
155 current, /* Task for fault acounting */
156 current->mm, /* whose pages? */
157 dio->curr_user_address, /* Where from? */
158 nr_pages, /* How many pages? */
159 dio->rw == READ, /* Write to memory? */
160 0, /* force (?) */
161 &dio->pages[0],
162 NULL); /* vmas */
163 up_read(&current->mm->mmap_sem);
164
165 if (ret < 0 && dio->blocks_available && (dio->rw == WRITE)) {
b5810039 166 struct page *page = ZERO_PAGE(dio->curr_user_address);
1da177e4
LT
167 /*
168 * A memory fault, but the filesystem has some outstanding
169 * mapped blocks. We need to use those blocks up to avoid
170 * leaking stale data in the file.
171 */
172 if (dio->page_errors == 0)
173 dio->page_errors = ret;
b5810039
NP
174 page_cache_get(page);
175 dio->pages[0] = page;
1da177e4
LT
176 dio->head = 0;
177 dio->tail = 1;
178 ret = 0;
179 goto out;
180 }
181
182 if (ret >= 0) {
183 dio->curr_user_address += ret * PAGE_SIZE;
184 dio->curr_page += ret;
185 dio->head = 0;
186 dio->tail = ret;
187 ret = 0;
188 }
189out:
190 return ret;
191}
192
193/*
194 * Get another userspace page. Returns an ERR_PTR on error. Pages are
195 * buffered inside the dio so that we can call get_user_pages() against a
196 * decent number of pages, less frequently. To provide nicer use of the
197 * L1 cache.
198 */
199static struct page *dio_get_page(struct dio *dio)
200{
201 if (dio_pages_present(dio) == 0) {
202 int ret;
203
204 ret = dio_refill_pages(dio);
205 if (ret)
206 return ERR_PTR(ret);
207 BUG_ON(dio_pages_present(dio) == 0);
208 }
209 return dio->pages[dio->head++];
210}
211
212/*
213 * Called when all DIO BIO I/O has been completed - let the filesystem
1d8fa7a2 214 * know, if it registered an interest earlier via get_block. Pass the
1da177e4 215 * private field of the map buffer_head so that filesystems can use it
1d8fa7a2 216 * to hold additional state between get_block calls and dio_complete.
1da177e4
LT
217 */
218static void dio_complete(struct dio *dio, loff_t offset, ssize_t bytes)
219{
220 if (dio->end_io && dio->result)
92198f7e 221 dio->end_io(dio->iocb, offset, bytes, dio->map_bh.b_private);
1da177e4
LT
222 if (dio->lock_type == DIO_LOCKING)
223 up_read(&dio->inode->i_alloc_sem);
224}
225
226/*
227 * Called when a BIO has been processed. If the count goes to zero then IO is
228 * complete and we can signal this to the AIO layer.
229 */
230static void finished_one_bio(struct dio *dio)
231{
232 unsigned long flags;
233
234 spin_lock_irqsave(&dio->bio_lock, flags);
235 if (dio->bio_count == 1) {
236 if (dio->is_async) {
29504ff3
DM
237 ssize_t transferred;
238 loff_t offset;
239
1da177e4
LT
240 /*
241 * Last reference to the dio is going away.
242 * Drop spinlock and complete the DIO.
243 */
244 spin_unlock_irqrestore(&dio->bio_lock, flags);
29504ff3
DM
245
246 /* Check for short read case */
247 transferred = dio->result;
248 offset = dio->iocb->ki_pos;
249
250 if ((dio->rw == READ) &&
251 ((offset + transferred) > dio->i_size))
252 transferred = dio->i_size - offset;
253
174e27c6
KC
254 /* check for error in completion path */
255 if (dio->io_error)
256 transferred = dio->io_error;
257
29504ff3
DM
258 dio_complete(dio, offset, transferred);
259
1da177e4
LT
260 /* Complete AIO later if falling back to buffered i/o */
261 if (dio->result == dio->size ||
262 ((dio->rw == READ) && dio->result)) {
29504ff3 263 aio_complete(dio->iocb, transferred, 0);
1da177e4
LT
264 kfree(dio);
265 return;
266 } else {
267 /*
268 * Falling back to buffered
269 */
270 spin_lock_irqsave(&dio->bio_lock, flags);
271 dio->bio_count--;
272 if (dio->waiter)
273 wake_up_process(dio->waiter);
274 spin_unlock_irqrestore(&dio->bio_lock, flags);
275 return;
276 }
277 }
278 }
279 dio->bio_count--;
280 spin_unlock_irqrestore(&dio->bio_lock, flags);
281}
282
283static int dio_bio_complete(struct dio *dio, struct bio *bio);
284/*
285 * Asynchronous IO callback.
286 */
287static int dio_bio_end_aio(struct bio *bio, unsigned int bytes_done, int error)
288{
289 struct dio *dio = bio->bi_private;
290
291 if (bio->bi_size)
292 return 1;
293
294 /* cleanup the bio */
295 dio_bio_complete(dio, bio);
296 return 0;
297}
298
299/*
300 * The BIO completion handler simply queues the BIO up for the process-context
301 * handler.
302 *
303 * During I/O bi_private points at the dio. After I/O, bi_private is used to
304 * implement a singly-linked list of completed BIOs, at dio->bio_list.
305 */
306static int dio_bio_end_io(struct bio *bio, unsigned int bytes_done, int error)
307{
308 struct dio *dio = bio->bi_private;
309 unsigned long flags;
310
311 if (bio->bi_size)
312 return 1;
313
314 spin_lock_irqsave(&dio->bio_lock, flags);
315 bio->bi_private = dio->bio_list;
316 dio->bio_list = bio;
317 dio->bios_in_flight--;
318 if (dio->waiter && dio->bios_in_flight == 0)
319 wake_up_process(dio->waiter);
320 spin_unlock_irqrestore(&dio->bio_lock, flags);
321 return 0;
322}
323
324static int
325dio_bio_alloc(struct dio *dio, struct block_device *bdev,
326 sector_t first_sector, int nr_vecs)
327{
328 struct bio *bio;
329
330 bio = bio_alloc(GFP_KERNEL, nr_vecs);
331 if (bio == NULL)
332 return -ENOMEM;
333
334 bio->bi_bdev = bdev;
335 bio->bi_sector = first_sector;
336 if (dio->is_async)
337 bio->bi_end_io = dio_bio_end_aio;
338 else
339 bio->bi_end_io = dio_bio_end_io;
340
341 dio->bio = bio;
342 return 0;
343}
344
345/*
346 * In the AIO read case we speculatively dirty the pages before starting IO.
347 * During IO completion, any of these pages which happen to have been written
348 * back will be redirtied by bio_check_pages_dirty().
349 */
350static void dio_bio_submit(struct dio *dio)
351{
352 struct bio *bio = dio->bio;
353 unsigned long flags;
354
355 bio->bi_private = dio;
356 spin_lock_irqsave(&dio->bio_lock, flags);
357 dio->bio_count++;
358 dio->bios_in_flight++;
359 spin_unlock_irqrestore(&dio->bio_lock, flags);
360 if (dio->is_async && dio->rw == READ)
361 bio_set_pages_dirty(bio);
362 submit_bio(dio->rw, bio);
363
364 dio->bio = NULL;
365 dio->boundary = 0;
366}
367
368/*
369 * Release any resources in case of a failure
370 */
371static void dio_cleanup(struct dio *dio)
372{
373 while (dio_pages_present(dio))
374 page_cache_release(dio_get_page(dio));
375}
376
377/*
378 * Wait for the next BIO to complete. Remove it and return it.
379 */
380static struct bio *dio_await_one(struct dio *dio)
381{
382 unsigned long flags;
383 struct bio *bio;
384
385 spin_lock_irqsave(&dio->bio_lock, flags);
386 while (dio->bio_list == NULL) {
387 set_current_state(TASK_UNINTERRUPTIBLE);
388 if (dio->bio_list == NULL) {
389 dio->waiter = current;
390 spin_unlock_irqrestore(&dio->bio_lock, flags);
391 blk_run_address_space(dio->inode->i_mapping);
392 io_schedule();
393 spin_lock_irqsave(&dio->bio_lock, flags);
394 dio->waiter = NULL;
395 }
396 set_current_state(TASK_RUNNING);
397 }
398 bio = dio->bio_list;
399 dio->bio_list = bio->bi_private;
400 spin_unlock_irqrestore(&dio->bio_lock, flags);
401 return bio;
402}
403
404/*
405 * Process one completed BIO. No locks are held.
406 */
407static int dio_bio_complete(struct dio *dio, struct bio *bio)
408{
409 const int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
410 struct bio_vec *bvec = bio->bi_io_vec;
411 int page_no;
412
413 if (!uptodate)
174e27c6 414 dio->io_error = -EIO;
1da177e4
LT
415
416 if (dio->is_async && dio->rw == READ) {
417 bio_check_pages_dirty(bio); /* transfers ownership */
418 } else {
419 for (page_no = 0; page_no < bio->bi_vcnt; page_no++) {
420 struct page *page = bvec[page_no].bv_page;
421
422 if (dio->rw == READ && !PageCompound(page))
423 set_page_dirty_lock(page);
424 page_cache_release(page);
425 }
426 bio_put(bio);
427 }
428 finished_one_bio(dio);
429 return uptodate ? 0 : -EIO;
430}
431
432/*
433 * Wait on and process all in-flight BIOs.
434 */
435static int dio_await_completion(struct dio *dio)
436{
437 int ret = 0;
438
439 if (dio->bio)
440 dio_bio_submit(dio);
441
442 /*
443 * The bio_lock is not held for the read of bio_count.
444 * This is ok since it is the dio_bio_complete() that changes
445 * bio_count.
446 */
447 while (dio->bio_count) {
448 struct bio *bio = dio_await_one(dio);
449 int ret2;
450
451 ret2 = dio_bio_complete(dio, bio);
452 if (ret == 0)
453 ret = ret2;
454 }
455 return ret;
456}
457
458/*
459 * A really large O_DIRECT read or write can generate a lot of BIOs. So
460 * to keep the memory consumption sane we periodically reap any completed BIOs
461 * during the BIO generation phase.
462 *
463 * This also helps to limit the peak amount of pinned userspace memory.
464 */
465static int dio_bio_reap(struct dio *dio)
466{
467 int ret = 0;
468
469 if (dio->reap_counter++ >= 64) {
470 while (dio->bio_list) {
471 unsigned long flags;
472 struct bio *bio;
473 int ret2;
474
475 spin_lock_irqsave(&dio->bio_lock, flags);
476 bio = dio->bio_list;
477 dio->bio_list = bio->bi_private;
478 spin_unlock_irqrestore(&dio->bio_lock, flags);
479 ret2 = dio_bio_complete(dio, bio);
480 if (ret == 0)
481 ret = ret2;
482 }
483 dio->reap_counter = 0;
484 }
485 return ret;
486}
487
488/*
489 * Call into the fs to map some more disk blocks. We record the current number
490 * of available blocks at dio->blocks_available. These are in units of the
491 * fs blocksize, (1 << inode->i_blkbits).
492 *
493 * The fs is allowed to map lots of blocks at once. If it wants to do that,
494 * it uses the passed inode-relative block number as the file offset, as usual.
495 *
1d8fa7a2 496 * get_block() is passed the number of i_blkbits-sized blocks which direct_io
1da177e4
LT
497 * has remaining to do. The fs should not map more than this number of blocks.
498 *
499 * If the fs has mapped a lot of blocks, it should populate bh->b_size to
500 * indicate how much contiguous disk space has been made available at
501 * bh->b_blocknr.
502 *
503 * If *any* of the mapped blocks are new, then the fs must set buffer_new().
504 * This isn't very efficient...
505 *
506 * In the case of filesystem holes: the fs may return an arbitrarily-large
507 * hole by returning an appropriate value in b_size and by clearing
508 * buffer_mapped(). However the direct-io code will only process holes one
1d8fa7a2 509 * block at a time - it will repeatedly call get_block() as it walks the hole.
1da177e4
LT
510 */
511static int get_more_blocks(struct dio *dio)
512{
513 int ret;
514 struct buffer_head *map_bh = &dio->map_bh;
515 sector_t fs_startblk; /* Into file, in filesystem-sized blocks */
516 unsigned long fs_count; /* Number of filesystem-sized blocks */
517 unsigned long dio_count;/* Number of dio_block-sized blocks */
518 unsigned long blkmask;
519 int create;
520
521 /*
522 * If there was a memory error and we've overwritten all the
523 * mapped blocks then we can now return that memory error
524 */
525 ret = dio->page_errors;
526 if (ret == 0) {
527 map_bh->b_state = 0;
528 map_bh->b_size = 0;
529 BUG_ON(dio->block_in_file >= dio->final_block_in_request);
530 fs_startblk = dio->block_in_file >> dio->blkfactor;
531 dio_count = dio->final_block_in_request - dio->block_in_file;
532 fs_count = dio_count >> dio->blkfactor;
533 blkmask = (1 << dio->blkfactor) - 1;
534 if (dio_count & blkmask)
535 fs_count++;
536
537 create = dio->rw == WRITE;
538 if (dio->lock_type == DIO_LOCKING) {
539 if (dio->block_in_file < (i_size_read(dio->inode) >>
540 dio->blkbits))
541 create = 0;
542 } else if (dio->lock_type == DIO_NO_LOCKING) {
543 create = 0;
544 }
545 /*
546 * For writes inside i_size we forbid block creations: only
547 * overwrites are permitted. We fall back to buffered writes
548 * at a higher level for inside-i_size block-instantiating
549 * writes.
550 */
1d8fa7a2
BP
551 map_bh->b_size = fs_count << dio->blkbits;
552 ret = (*dio->get_block)(dio->inode, fs_startblk,
1da177e4
LT
553 map_bh, create);
554 }
555 return ret;
556}
557
558/*
559 * There is no bio. Make one now.
560 */
561static int dio_new_bio(struct dio *dio, sector_t start_sector)
562{
563 sector_t sector;
564 int ret, nr_pages;
565
566 ret = dio_bio_reap(dio);
567 if (ret)
568 goto out;
569 sector = start_sector << (dio->blkbits - 9);
570 nr_pages = min(dio->pages_in_io, bio_get_nr_vecs(dio->map_bh.b_bdev));
571 BUG_ON(nr_pages <= 0);
572 ret = dio_bio_alloc(dio, dio->map_bh.b_bdev, sector, nr_pages);
573 dio->boundary = 0;
574out:
575 return ret;
576}
577
578/*
579 * Attempt to put the current chunk of 'cur_page' into the current BIO. If
580 * that was successful then update final_block_in_bio and take a ref against
581 * the just-added page.
582 *
583 * Return zero on success. Non-zero means the caller needs to start a new BIO.
584 */
585static int dio_bio_add_page(struct dio *dio)
586{
587 int ret;
588
589 ret = bio_add_page(dio->bio, dio->cur_page,
590 dio->cur_page_len, dio->cur_page_offset);
591 if (ret == dio->cur_page_len) {
592 /*
593 * Decrement count only, if we are done with this page
594 */
595 if ((dio->cur_page_len + dio->cur_page_offset) == PAGE_SIZE)
596 dio->pages_in_io--;
597 page_cache_get(dio->cur_page);
598 dio->final_block_in_bio = dio->cur_page_block +
599 (dio->cur_page_len >> dio->blkbits);
600 ret = 0;
601 } else {
602 ret = 1;
603 }
604 return ret;
605}
606
607/*
608 * Put cur_page under IO. The section of cur_page which is described by
609 * cur_page_offset,cur_page_len is put into a BIO. The section of cur_page
610 * starts on-disk at cur_page_block.
611 *
612 * We take a ref against the page here (on behalf of its presence in the bio).
613 *
614 * The caller of this function is responsible for removing cur_page from the
615 * dio, and for dropping the refcount which came from that presence.
616 */
617static int dio_send_cur_page(struct dio *dio)
618{
619 int ret = 0;
620
621 if (dio->bio) {
622 /*
623 * See whether this new request is contiguous with the old
624 */
625 if (dio->final_block_in_bio != dio->cur_page_block)
626 dio_bio_submit(dio);
627 /*
628 * Submit now if the underlying fs is about to perform a
629 * metadata read
630 */
631 if (dio->boundary)
632 dio_bio_submit(dio);
633 }
634
635 if (dio->bio == NULL) {
636 ret = dio_new_bio(dio, dio->cur_page_block);
637 if (ret)
638 goto out;
639 }
640
641 if (dio_bio_add_page(dio) != 0) {
642 dio_bio_submit(dio);
643 ret = dio_new_bio(dio, dio->cur_page_block);
644 if (ret == 0) {
645 ret = dio_bio_add_page(dio);
646 BUG_ON(ret != 0);
647 }
648 }
649out:
650 return ret;
651}
652
653/*
654 * An autonomous function to put a chunk of a page under deferred IO.
655 *
656 * The caller doesn't actually know (or care) whether this piece of page is in
657 * a BIO, or is under IO or whatever. We just take care of all possible
658 * situations here. The separation between the logic of do_direct_IO() and
659 * that of submit_page_section() is important for clarity. Please don't break.
660 *
661 * The chunk of page starts on-disk at blocknr.
662 *
663 * We perform deferred IO, by recording the last-submitted page inside our
664 * private part of the dio structure. If possible, we just expand the IO
665 * across that page here.
666 *
667 * If that doesn't work out then we put the old page into the bio and add this
668 * page to the dio instead.
669 */
670static int
671submit_page_section(struct dio *dio, struct page *page,
672 unsigned offset, unsigned len, sector_t blocknr)
673{
674 int ret = 0;
675
676 /*
677 * Can we just grow the current page's presence in the dio?
678 */
679 if ( (dio->cur_page == page) &&
680 (dio->cur_page_offset + dio->cur_page_len == offset) &&
681 (dio->cur_page_block +
682 (dio->cur_page_len >> dio->blkbits) == blocknr)) {
683 dio->cur_page_len += len;
684
685 /*
686 * If dio->boundary then we want to schedule the IO now to
687 * avoid metadata seeks.
688 */
689 if (dio->boundary) {
690 ret = dio_send_cur_page(dio);
691 page_cache_release(dio->cur_page);
692 dio->cur_page = NULL;
693 }
694 goto out;
695 }
696
697 /*
698 * If there's a deferred page already there then send it.
699 */
700 if (dio->cur_page) {
701 ret = dio_send_cur_page(dio);
702 page_cache_release(dio->cur_page);
703 dio->cur_page = NULL;
704 if (ret)
705 goto out;
706 }
707
708 page_cache_get(page); /* It is in dio */
709 dio->cur_page = page;
710 dio->cur_page_offset = offset;
711 dio->cur_page_len = len;
712 dio->cur_page_block = blocknr;
713out:
714 return ret;
715}
716
717/*
718 * Clean any dirty buffers in the blockdev mapping which alias newly-created
719 * file blocks. Only called for S_ISREG files - blockdevs do not set
720 * buffer_new
721 */
722static void clean_blockdev_aliases(struct dio *dio)
723{
724 unsigned i;
725 unsigned nblocks;
726
727 nblocks = dio->map_bh.b_size >> dio->inode->i_blkbits;
728
729 for (i = 0; i < nblocks; i++) {
730 unmap_underlying_metadata(dio->map_bh.b_bdev,
731 dio->map_bh.b_blocknr + i);
732 }
733}
734
735/*
736 * If we are not writing the entire block and get_block() allocated
737 * the block for us, we need to fill-in the unused portion of the
738 * block with zeros. This happens only if user-buffer, fileoffset or
739 * io length is not filesystem block-size multiple.
740 *
741 * `end' is zero if we're doing the start of the IO, 1 at the end of the
742 * IO.
743 */
744static void dio_zero_block(struct dio *dio, int end)
745{
746 unsigned dio_blocks_per_fs_block;
747 unsigned this_chunk_blocks; /* In dio_blocks */
748 unsigned this_chunk_bytes;
749 struct page *page;
750
751 dio->start_zero_done = 1;
752 if (!dio->blkfactor || !buffer_new(&dio->map_bh))
753 return;
754
755 dio_blocks_per_fs_block = 1 << dio->blkfactor;
756 this_chunk_blocks = dio->block_in_file & (dio_blocks_per_fs_block - 1);
757
758 if (!this_chunk_blocks)
759 return;
760
761 /*
762 * We need to zero out part of an fs block. It is either at the
763 * beginning or the end of the fs block.
764 */
765 if (end)
766 this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
767
768 this_chunk_bytes = this_chunk_blocks << dio->blkbits;
769
770 page = ZERO_PAGE(dio->curr_user_address);
771 if (submit_page_section(dio, page, 0, this_chunk_bytes,
772 dio->next_block_for_io))
773 return;
774
775 dio->next_block_for_io += this_chunk_blocks;
776}
777
778/*
779 * Walk the user pages, and the file, mapping blocks to disk and generating
780 * a sequence of (page,offset,len,block) mappings. These mappings are injected
781 * into submit_page_section(), which takes care of the next stage of submission
782 *
783 * Direct IO against a blockdev is different from a file. Because we can
784 * happily perform page-sized but 512-byte aligned IOs. It is important that
785 * blockdev IO be able to have fine alignment and large sizes.
786 *
1d8fa7a2 787 * So what we do is to permit the ->get_block function to populate bh.b_size
1da177e4
LT
788 * with the size of IO which is permitted at this offset and this i_blkbits.
789 *
790 * For best results, the blockdev should be set up with 512-byte i_blkbits and
1d8fa7a2 791 * it should set b_size to PAGE_SIZE or more inside get_block(). This gives
1da177e4
LT
792 * fine alignment but still allows this function to work in PAGE_SIZE units.
793 */
794static int do_direct_IO(struct dio *dio)
795{
796 const unsigned blkbits = dio->blkbits;
797 const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
798 struct page *page;
799 unsigned block_in_page;
800 struct buffer_head *map_bh = &dio->map_bh;
801 int ret = 0;
802
803 /* The I/O can start at any block offset within the first page */
804 block_in_page = dio->first_block_in_page;
805
806 while (dio->block_in_file < dio->final_block_in_request) {
807 page = dio_get_page(dio);
808 if (IS_ERR(page)) {
809 ret = PTR_ERR(page);
810 goto out;
811 }
812
813 while (block_in_page < blocks_per_page) {
814 unsigned offset_in_page = block_in_page << blkbits;
815 unsigned this_chunk_bytes; /* # of bytes mapped */
816 unsigned this_chunk_blocks; /* # of blocks */
817 unsigned u;
818
819 if (dio->blocks_available == 0) {
820 /*
821 * Need to go and map some more disk
822 */
823 unsigned long blkmask;
824 unsigned long dio_remainder;
825
826 ret = get_more_blocks(dio);
827 if (ret) {
828 page_cache_release(page);
829 goto out;
830 }
831 if (!buffer_mapped(map_bh))
832 goto do_holes;
833
834 dio->blocks_available =
835 map_bh->b_size >> dio->blkbits;
836 dio->next_block_for_io =
837 map_bh->b_blocknr << dio->blkfactor;
838 if (buffer_new(map_bh))
839 clean_blockdev_aliases(dio);
840
841 if (!dio->blkfactor)
842 goto do_holes;
843
844 blkmask = (1 << dio->blkfactor) - 1;
845 dio_remainder = (dio->block_in_file & blkmask);
846
847 /*
848 * If we are at the start of IO and that IO
849 * starts partway into a fs-block,
850 * dio_remainder will be non-zero. If the IO
851 * is a read then we can simply advance the IO
852 * cursor to the first block which is to be
853 * read. But if the IO is a write and the
854 * block was newly allocated we cannot do that;
855 * the start of the fs block must be zeroed out
856 * on-disk
857 */
858 if (!buffer_new(map_bh))
859 dio->next_block_for_io += dio_remainder;
860 dio->blocks_available -= dio_remainder;
861 }
862do_holes:
863 /* Handle holes */
864 if (!buffer_mapped(map_bh)) {
865 char *kaddr;
35dc8161 866 loff_t i_size_aligned;
1da177e4
LT
867
868 /* AKPM: eargh, -ENOTBLK is a hack */
869 if (dio->rw == WRITE) {
870 page_cache_release(page);
871 return -ENOTBLK;
872 }
873
35dc8161
JM
874 /*
875 * Be sure to account for a partial block as the
876 * last block in the file
877 */
878 i_size_aligned = ALIGN(i_size_read(dio->inode),
879 1 << blkbits);
1da177e4 880 if (dio->block_in_file >=
35dc8161 881 i_size_aligned >> blkbits) {
1da177e4
LT
882 /* We hit eof */
883 page_cache_release(page);
884 goto out;
885 }
886 kaddr = kmap_atomic(page, KM_USER0);
887 memset(kaddr + (block_in_page << blkbits),
888 0, 1 << blkbits);
889 flush_dcache_page(page);
890 kunmap_atomic(kaddr, KM_USER0);
891 dio->block_in_file++;
892 block_in_page++;
893 goto next_block;
894 }
895
896 /*
897 * If we're performing IO which has an alignment which
898 * is finer than the underlying fs, go check to see if
899 * we must zero out the start of this block.
900 */
901 if (unlikely(dio->blkfactor && !dio->start_zero_done))
902 dio_zero_block(dio, 0);
903
904 /*
905 * Work out, in this_chunk_blocks, how much disk we
906 * can add to this page
907 */
908 this_chunk_blocks = dio->blocks_available;
909 u = (PAGE_SIZE - offset_in_page) >> blkbits;
910 if (this_chunk_blocks > u)
911 this_chunk_blocks = u;
912 u = dio->final_block_in_request - dio->block_in_file;
913 if (this_chunk_blocks > u)
914 this_chunk_blocks = u;
915 this_chunk_bytes = this_chunk_blocks << blkbits;
916 BUG_ON(this_chunk_bytes == 0);
917
918 dio->boundary = buffer_boundary(map_bh);
919 ret = submit_page_section(dio, page, offset_in_page,
920 this_chunk_bytes, dio->next_block_for_io);
921 if (ret) {
922 page_cache_release(page);
923 goto out;
924 }
925 dio->next_block_for_io += this_chunk_blocks;
926
927 dio->block_in_file += this_chunk_blocks;
928 block_in_page += this_chunk_blocks;
929 dio->blocks_available -= this_chunk_blocks;
930next_block:
931 if (dio->block_in_file > dio->final_block_in_request)
932 BUG();
933 if (dio->block_in_file == dio->final_block_in_request)
934 break;
935 }
936
937 /* Drop the ref which was taken in get_user_pages() */
938 page_cache_release(page);
939 block_in_page = 0;
940 }
941out:
942 return ret;
943}
944
945/*
1b1dcc1b 946 * Releases both i_mutex and i_alloc_sem
1da177e4
LT
947 */
948static ssize_t
949direct_io_worker(int rw, struct kiocb *iocb, struct inode *inode,
950 const struct iovec *iov, loff_t offset, unsigned long nr_segs,
1d8fa7a2 951 unsigned blkbits, get_block_t get_block, dio_iodone_t end_io,
1da177e4
LT
952 struct dio *dio)
953{
954 unsigned long user_addr;
955 int seg;
956 ssize_t ret = 0;
957 ssize_t ret2;
958 size_t bytes;
959
960 dio->bio = NULL;
961 dio->inode = inode;
962 dio->rw = rw;
963 dio->blkbits = blkbits;
964 dio->blkfactor = inode->i_blkbits - blkbits;
965 dio->start_zero_done = 0;
966 dio->size = 0;
967 dio->block_in_file = offset >> blkbits;
968 dio->blocks_available = 0;
969 dio->cur_page = NULL;
970
971 dio->boundary = 0;
972 dio->reap_counter = 0;
1d8fa7a2 973 dio->get_block = get_block;
1da177e4
LT
974 dio->end_io = end_io;
975 dio->map_bh.b_private = NULL;
976 dio->final_block_in_bio = -1;
977 dio->next_block_for_io = -1;
978
979 dio->page_errors = 0;
174e27c6 980 dio->io_error = 0;
1da177e4
LT
981 dio->result = 0;
982 dio->iocb = iocb;
29504ff3 983 dio->i_size = i_size_read(inode);
1da177e4
LT
984
985 /*
986 * BIO completion state.
987 *
988 * ->bio_count starts out at one, and we decrement it to zero after all
989 * BIOs are submitted. This to avoid the situation where a really fast
990 * (or synchronous) device could take the count to zero while we're
991 * still submitting BIOs.
992 */
993 dio->bio_count = 1;
994 dio->bios_in_flight = 0;
995 spin_lock_init(&dio->bio_lock);
996 dio->bio_list = NULL;
997 dio->waiter = NULL;
998
999 /*
1000 * In case of non-aligned buffers, we may need 2 more
1001 * pages since we need to zero out first and last block.
1002 */
1003 if (unlikely(dio->blkfactor))
1004 dio->pages_in_io = 2;
1005 else
1006 dio->pages_in_io = 0;
1007
1008 for (seg = 0; seg < nr_segs; seg++) {
1009 user_addr = (unsigned long)iov[seg].iov_base;
1010 dio->pages_in_io +=
1011 ((user_addr+iov[seg].iov_len +PAGE_SIZE-1)/PAGE_SIZE
1012 - user_addr/PAGE_SIZE);
1013 }
1014
1015 for (seg = 0; seg < nr_segs; seg++) {
1016 user_addr = (unsigned long)iov[seg].iov_base;
1017 dio->size += bytes = iov[seg].iov_len;
1018
1019 /* Index into the first page of the first block */
1020 dio->first_block_in_page = (user_addr & ~PAGE_MASK) >> blkbits;
1021 dio->final_block_in_request = dio->block_in_file +
1022 (bytes >> blkbits);
1023 /* Page fetching state */
1024 dio->head = 0;
1025 dio->tail = 0;
1026 dio->curr_page = 0;
1027
1028 dio->total_pages = 0;
1029 if (user_addr & (PAGE_SIZE-1)) {
1030 dio->total_pages++;
1031 bytes -= PAGE_SIZE - (user_addr & (PAGE_SIZE - 1));
1032 }
1033 dio->total_pages += (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1034 dio->curr_user_address = user_addr;
1035
1036 ret = do_direct_IO(dio);
1037
1038 dio->result += iov[seg].iov_len -
1039 ((dio->final_block_in_request - dio->block_in_file) <<
1040 blkbits);
1041
1042 if (ret) {
1043 dio_cleanup(dio);
1044 break;
1045 }
1046 } /* end iovec loop */
1047
1048 if (ret == -ENOTBLK && rw == WRITE) {
1049 /*
1050 * The remaining part of the request will be
1051 * be handled by buffered I/O when we return
1052 */
1053 ret = 0;
1054 }
1055 /*
1056 * There may be some unwritten disk at the end of a part-written
1057 * fs-block-sized block. Go zero that now.
1058 */
1059 dio_zero_block(dio, 1);
1060
1061 if (dio->cur_page) {
1062 ret2 = dio_send_cur_page(dio);
1063 if (ret == 0)
1064 ret = ret2;
1065 page_cache_release(dio->cur_page);
1066 dio->cur_page = NULL;
1067 }
1068 if (dio->bio)
1069 dio_bio_submit(dio);
1070
1071 /*
1072 * It is possible that, we return short IO due to end of file.
1073 * In that case, we need to release all the pages we got hold on.
1074 */
1075 dio_cleanup(dio);
1076
1077 /*
1078 * All block lookups have been performed. For READ requests
1b1dcc1b 1079 * we can let i_mutex go now that its achieved its purpose
1da177e4
LT
1080 * of protecting us from looking up uninitialized blocks.
1081 */
1082 if ((rw == READ) && (dio->lock_type == DIO_LOCKING))
1b1dcc1b 1083 mutex_unlock(&dio->inode->i_mutex);
1da177e4
LT
1084
1085 /*
1086 * OK, all BIOs are submitted, so we can decrement bio_count to truly
1087 * reflect the number of to-be-processed BIOs.
1088 */
1089 if (dio->is_async) {
1090 int should_wait = 0;
1091
1092 if (dio->result < dio->size && rw == WRITE) {
1093 dio->waiter = current;
1094 should_wait = 1;
1095 }
1096 if (ret == 0)
1097 ret = dio->result;
1098 finished_one_bio(dio); /* This can free the dio */
1099 blk_run_address_space(inode->i_mapping);
1100 if (should_wait) {
1101 unsigned long flags;
1102 /*
1103 * Wait for already issued I/O to drain out and
1104 * release its references to user-space pages
1105 * before returning to fallback on buffered I/O
1106 */
1107
1108 spin_lock_irqsave(&dio->bio_lock, flags);
1109 set_current_state(TASK_UNINTERRUPTIBLE);
1110 while (dio->bio_count) {
1111 spin_unlock_irqrestore(&dio->bio_lock, flags);
1112 io_schedule();
1113 spin_lock_irqsave(&dio->bio_lock, flags);
1114 set_current_state(TASK_UNINTERRUPTIBLE);
1115 }
1116 spin_unlock_irqrestore(&dio->bio_lock, flags);
1117 set_current_state(TASK_RUNNING);
1118 kfree(dio);
1119 }
1120 } else {
1121 ssize_t transferred = 0;
1122
1123 finished_one_bio(dio);
1124 ret2 = dio_await_completion(dio);
1125 if (ret == 0)
1126 ret = ret2;
1127 if (ret == 0)
1128 ret = dio->page_errors;
1129 if (dio->result) {
1130 loff_t i_size = i_size_read(inode);
1131
1132 transferred = dio->result;
1133 /*
1134 * Adjust the return value if the read crossed a
1135 * non-block-aligned EOF.
1136 */
1137 if (rw == READ && (offset + transferred > i_size))
1138 transferred = i_size - offset;
1139 }
1140 dio_complete(dio, offset, transferred);
1141 if (ret == 0)
1142 ret = transferred;
1143
1144 /* We could have also come here on an AIO file extend */
1145 if (!is_sync_kiocb(iocb) && rw == WRITE &&
1146 ret >= 0 && dio->result == dio->size)
1147 /*
1148 * For AIO writes where we have completed the
1149 * i/o, we have to mark the the aio complete.
1150 */
1151 aio_complete(iocb, ret, 0);
1152 kfree(dio);
1153 }
1154 return ret;
1155}
1156
1157/*
1158 * This is a library function for use by filesystem drivers.
1159 * The locking rules are governed by the dio_lock_type parameter.
1160 *
1161 * DIO_NO_LOCKING (no locking, for raw block device access)
1b1dcc1b 1162 * For writes, i_mutex is not held on entry; it is never taken.
1da177e4
LT
1163 *
1164 * DIO_LOCKING (simple locking for regular files)
3fb962bd
NS
1165 * For writes we are called under i_mutex and return with i_mutex held, even
1166 * though it is internally dropped.
1b1dcc1b 1167 * For reads, i_mutex is not held on entry, but it is taken and dropped before
1da177e4
LT
1168 * returning.
1169 *
1170 * DIO_OWN_LOCKING (filesystem provides synchronisation and handling of
1171 * uninitialised data, allowing parallel direct readers and writers)
1b1dcc1b 1172 * For writes we are called without i_mutex, return without it, never touch it.
3fb962bd
NS
1173 * For reads we are called under i_mutex and return with i_mutex held, even
1174 * though it may be internally dropped.
1da177e4
LT
1175 *
1176 * Additional i_alloc_sem locking requirements described inline below.
1177 */
1178ssize_t
1179__blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
1180 struct block_device *bdev, const struct iovec *iov, loff_t offset,
1d8fa7a2 1181 unsigned long nr_segs, get_block_t get_block, dio_iodone_t end_io,
1da177e4
LT
1182 int dio_lock_type)
1183{
1184 int seg;
1185 size_t size;
1186 unsigned long addr;
1187 unsigned blkbits = inode->i_blkbits;
1188 unsigned bdev_blkbits = 0;
1189 unsigned blocksize_mask = (1 << blkbits) - 1;
1190 ssize_t retval = -EINVAL;
1191 loff_t end = offset;
1192 struct dio *dio;
3fb962bd
NS
1193 int release_i_mutex = 0;
1194 int acquire_i_mutex = 0;
1da177e4
LT
1195
1196 if (rw & WRITE)
1197 current->flags |= PF_SYNCWRITE;
1198
1199 if (bdev)
1200 bdev_blkbits = blksize_bits(bdev_hardsect_size(bdev));
1201
1202 if (offset & blocksize_mask) {
1203 if (bdev)
1204 blkbits = bdev_blkbits;
1205 blocksize_mask = (1 << blkbits) - 1;
1206 if (offset & blocksize_mask)
1207 goto out;
1208 }
1209
1210 /* Check the memory alignment. Blocks cannot straddle pages */
1211 for (seg = 0; seg < nr_segs; seg++) {
1212 addr = (unsigned long)iov[seg].iov_base;
1213 size = iov[seg].iov_len;
1214 end += size;
1215 if ((addr & blocksize_mask) || (size & blocksize_mask)) {
1216 if (bdev)
1217 blkbits = bdev_blkbits;
1218 blocksize_mask = (1 << blkbits) - 1;
1219 if ((addr & blocksize_mask) || (size & blocksize_mask))
1220 goto out;
1221 }
1222 }
1223
1224 dio = kmalloc(sizeof(*dio), GFP_KERNEL);
1225 retval = -ENOMEM;
1226 if (!dio)
1227 goto out;
1228
1229 /*
1230 * For block device access DIO_NO_LOCKING is used,
1231 * neither readers nor writers do any locking at all
1232 * For regular files using DIO_LOCKING,
1b1dcc1b
JS
1233 * readers need to grab i_mutex and i_alloc_sem
1234 * writers need to grab i_alloc_sem only (i_mutex is already held)
1da177e4
LT
1235 * For regular files using DIO_OWN_LOCKING,
1236 * neither readers nor writers take any locks here
1da177e4
LT
1237 */
1238 dio->lock_type = dio_lock_type;
1239 if (dio_lock_type != DIO_NO_LOCKING) {
1240 /* watch out for a 0 len io from a tricksy fs */
1241 if (rw == READ && end > offset) {
1242 struct address_space *mapping;
1243
1244 mapping = iocb->ki_filp->f_mapping;
1245 if (dio_lock_type != DIO_OWN_LOCKING) {
1b1dcc1b 1246 mutex_lock(&inode->i_mutex);
3fb962bd 1247 release_i_mutex = 1;
1da177e4
LT
1248 }
1249
1250 retval = filemap_write_and_wait_range(mapping, offset,
1251 end - 1);
1252 if (retval) {
1253 kfree(dio);
1254 goto out;
1255 }
1256
1257 if (dio_lock_type == DIO_OWN_LOCKING) {
1b1dcc1b 1258 mutex_unlock(&inode->i_mutex);
3fb962bd 1259 acquire_i_mutex = 1;
1da177e4
LT
1260 }
1261 }
1262
1263 if (dio_lock_type == DIO_LOCKING)
1264 down_read(&inode->i_alloc_sem);
1265 }
1266
1267 /*
1268 * For file extending writes updating i_size before data
1269 * writeouts complete can expose uninitialized blocks. So
1270 * even for AIO, we need to wait for i/o to complete before
1271 * returning in this case.
1272 */
1273 dio->is_async = !is_sync_kiocb(iocb) && !((rw == WRITE) &&
1274 (end > i_size_read(inode)));
1275
1276 retval = direct_io_worker(rw, iocb, inode, iov, offset,
1d8fa7a2 1277 nr_segs, blkbits, get_block, end_io, dio);
1da177e4
LT
1278
1279 if (rw == READ && dio_lock_type == DIO_LOCKING)
3fb962bd 1280 release_i_mutex = 0;
1da177e4
LT
1281
1282out:
3fb962bd 1283 if (release_i_mutex)
1b1dcc1b 1284 mutex_unlock(&inode->i_mutex);
3fb962bd
NS
1285 else if (acquire_i_mutex)
1286 mutex_lock(&inode->i_mutex);
1da177e4
LT
1287 if (rw & WRITE)
1288 current->flags &= ~PF_SYNCWRITE;
1289 return retval;
1290}
1291EXPORT_SYMBOL(__blockdev_direct_IO);