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