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