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