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