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