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