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