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