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