linux/fs/direct-io.c
<<
>>
Prefs
   1/*
   2 * fs/direct-io.c
   3 *
   4 * Copyright (C) 2002, Linus Torvalds.
   5 *
   6 * O_DIRECT
   7 *
   8 * 04Jul2002    Andrew Morton
   9 *              Initial version
  10 * 11Sep2002    janetinc@us.ibm.com
  11 *              added readv/writev support.
  12 * 29Oct2002    Andrew Morton
  13 *              rewrote bio_add_page() support.
  14 * 30Oct2002    pbadari@us.ibm.com
  15 *              added support for non-aligned IO.
  16 * 06Nov2002    pbadari@us.ibm.com
  17 *              added asynchronous IO support.
  18 * 21Jul2003    nathans@sgi.com
  19 *              added IO completion notifier.
  20 */
  21
  22#include <linux/kernel.h>
  23#include <linux/module.h>
  24#include <linux/types.h>
  25#include <linux/fs.h>
  26#include <linux/mm.h>
  27#include <linux/slab.h>
  28#include <linux/highmem.h>
  29#include <linux/pagemap.h>
  30#include <linux/task_io_accounting_ops.h>
  31#include <linux/bio.h>
  32#include <linux/wait.h>
  33#include <linux/err.h>
  34#include <linux/blkdev.h>
  35#include <linux/buffer_head.h>
  36#include <linux/rwsem.h>
  37#include <linux/uio.h>
  38#include <linux/atomic.h>
  39#include <linux/prefetch.h>
  40#include <linux/aio.h>
  41
  42/*
  43 * How many user pages to map in one call to get_user_pages().  This determines
  44 * the size of a structure in the slab cache
  45 */
  46#define DIO_PAGES       64
  47
  48/*
  49 * Flags for dio_complete()
  50 */
  51#define DIO_COMPLETE_ASYNC              0x01    /* This is async IO */
  52#define DIO_COMPLETE_INVALIDATE         0x02    /* Can invalidate pages */
  53
  54/*
  55 * This code generally works in units of "dio_blocks".  A dio_block is
  56 * somewhere between the hard sector size and the filesystem block size.  it
  57 * is determined on a per-invocation basis.   When talking to the filesystem
  58 * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
  59 * down by dio->blkfactor.  Similarly, fs-blocksize quantities are converted
  60 * to bio_block quantities by shifting left by blkfactor.
  61 *
  62 * If blkfactor is zero then the user's request was aligned to the filesystem's
  63 * blocksize.
  64 */
  65
  66/* dio_state only used in the submission path */
  67
  68struct dio_submit {
  69        struct bio *bio;                /* bio under assembly */
  70        unsigned blkbits;               /* doesn't change */
  71        unsigned blkfactor;             /* When we're using an alignment which
  72                                           is finer than the filesystem's soft
  73                                           blocksize, this specifies how much
  74                                           finer.  blkfactor=2 means 1/4-block
  75                                           alignment.  Does not change */
  76        unsigned start_zero_done;       /* flag: sub-blocksize zeroing has
  77                                           been performed at the start of a
  78                                           write */
  79        int pages_in_io;                /* approximate total IO pages */
  80        size_t  size;                   /* total request size (doesn't change)*/
  81        sector_t block_in_file;         /* Current offset into the underlying
  82                                           file in dio_block units. */
  83        unsigned blocks_available;      /* At block_in_file.  changes */
  84        int reap_counter;               /* rate limit reaping */
  85        sector_t final_block_in_request;/* doesn't change */
  86        unsigned first_block_in_page;   /* doesn't change, Used only once */
  87        int boundary;                   /* prev block is at a boundary */
  88        get_block_t *get_block;         /* block mapping function */
  89        dio_submit_t *submit_io;        /* IO submition function */
  90
  91        loff_t logical_offset_in_bio;   /* current first logical block in bio */
  92        sector_t final_block_in_bio;    /* current final block in bio + 1 */
  93        sector_t next_block_for_io;     /* next block to be put under IO,
  94                                           in dio_blocks units */
  95
  96        /*
  97         * Deferred addition of a page to the dio.  These variables are
  98         * private to dio_send_cur_page(), submit_page_section() and
  99         * dio_bio_add_page().
 100         */
 101        struct page *cur_page;          /* The page */
 102        unsigned cur_page_offset;       /* Offset into it, in bytes */
 103        unsigned cur_page_len;          /* Nr of bytes at cur_page_offset */
 104        sector_t cur_page_block;        /* Where it starts */
 105        loff_t cur_page_fs_offset;      /* Offset in file */
 106
 107        /*
 108         * Page fetching state. These variables belong to dio_refill_pages().
 109         */
 110        int curr_page;                  /* changes */
 111        int total_pages;                /* doesn't change */
 112        unsigned long curr_user_address;/* changes */
 113
 114        /*
 115         * Page queue.  These variables belong to dio_refill_pages() and
 116         * dio_get_page().
 117         */
 118        unsigned head;                  /* next page to process */
 119        unsigned tail;                  /* last valid page + 1 */
 120};
 121
 122/* dio_state communicated between submission path and end_io */
 123struct dio {
 124        int flags;                      /* doesn't change */
 125        int rw;
 126        struct inode *inode;
 127        loff_t i_size;                  /* i_size when submitted */
 128        dio_iodone_t *end_io;           /* IO completion function */
 129
 130        void *private;                  /* copy from map_bh.b_private */
 131
 132        /* BIO completion state */
 133        spinlock_t bio_lock;            /* protects BIO fields below */
 134        int page_errors;                /* errno from get_user_pages() */
 135        int is_async;                   /* is IO async ? */
 136        bool defer_completion;          /* defer AIO completion to workqueue? */
 137        int io_error;                   /* IO error in completion path */
 138        unsigned long refcount;         /* direct_io_worker() and bios */
 139        struct bio *bio_list;           /* singly linked via bi_private */
 140        struct task_struct *waiter;     /* waiting task (NULL if none) */
 141
 142        /* AIO related stuff */
 143        struct kiocb *iocb;             /* kiocb */
 144        ssize_t result;                 /* IO result */
 145
 146        /*
 147         * pages[] (and any fields placed after it) are not zeroed out at
 148         * allocation time.  Don't add new fields after pages[] unless you
 149         * wish that they not be zeroed.
 150         */
 151        union {
 152                struct page *pages[DIO_PAGES];  /* page buffer */
 153                struct work_struct complete_work;/* deferred AIO completion */
 154        };
 155} ____cacheline_aligned_in_smp;
 156
 157static struct kmem_cache *dio_cache __read_mostly;
 158
 159/*
 160 * How many pages are in the queue?
 161 */
 162static inline unsigned dio_pages_present(struct dio_submit *sdio)
 163{
 164        return sdio->tail - sdio->head;
 165}
 166
 167/*
 168 * Go grab and pin some userspace pages.   Typically we'll get 64 at a time.
 169 */
 170static inline int dio_refill_pages(struct dio *dio, struct dio_submit *sdio)
 171{
 172        int ret;
 173        int nr_pages;
 174
 175        nr_pages = min(sdio->total_pages - sdio->curr_page, DIO_PAGES);
 176        ret = get_user_pages_fast(
 177                sdio->curr_user_address,                /* Where from? */
 178                nr_pages,                       /* How many pages? */
 179                dio->rw == READ,                /* Write to memory? */
 180                &dio->pages[0]);                /* Put results here */
 181
 182        if (ret < 0 && sdio->blocks_available && (dio->rw & WRITE)) {
 183                struct page *page = ZERO_PAGE(0);
 184                /*
 185                 * A memory fault, but the filesystem has some outstanding
 186                 * mapped blocks.  We need to use those blocks up to avoid
 187                 * leaking stale data in the file.
 188                 */
 189                if (dio->page_errors == 0)
 190                        dio->page_errors = ret;
 191                page_cache_get(page);
 192                dio->pages[0] = page;
 193                sdio->head = 0;
 194                sdio->tail = 1;
 195                ret = 0;
 196                goto out;
 197        }
 198
 199        if (ret >= 0) {
 200                sdio->curr_user_address += ret * PAGE_SIZE;
 201                sdio->curr_page += ret;
 202                sdio->head = 0;
 203                sdio->tail = ret;
 204                ret = 0;
 205        }
 206out:
 207        return ret;     
 208}
 209
 210/*
 211 * Get another userspace page.  Returns an ERR_PTR on error.  Pages are
 212 * buffered inside the dio so that we can call get_user_pages() against a
 213 * decent number of pages, less frequently.  To provide nicer use of the
 214 * L1 cache.
 215 */
 216static inline struct page *dio_get_page(struct dio *dio,
 217                struct dio_submit *sdio)
 218{
 219        if (dio_pages_present(sdio) == 0) {
 220                int ret;
 221
 222                ret = dio_refill_pages(dio, sdio);
 223                if (ret)
 224                        return ERR_PTR(ret);
 225                BUG_ON(dio_pages_present(sdio) == 0);
 226        }
 227        return dio->pages[sdio->head++];
 228}
 229
 230static void dio_iodone_helper(struct dio *dio, loff_t offset,
 231                              ssize_t transferred, ssize_t ret, bool is_async)
 232{
 233        if (dio->end_io && dio->result) {
 234                dio->end_io(dio->iocb, offset, transferred,
 235                            dio->private, ret, is_async);
 236        } else {
 237                if (!(dio->flags & DIO_SKIP_DIO_COUNT))
 238                        inode_dio_end(dio->inode);
 239                if (is_async)
 240                        aio_complete(dio->iocb, ret, 0);
 241        }
 242}
 243
 244static void dio_iodone2_helper(struct dio *dio, loff_t offset,
 245                               ssize_t transferred, ssize_t ret, bool is_async)
 246{
 247        if (dio->end_io)
 248                dio->end_io(dio->iocb, offset, ret, dio->private, 0, 0);
 249
 250        if (!(dio->flags & DIO_SKIP_DIO_COUNT))
 251                inode_dio_end(dio->inode);
 252
 253        if (is_async) {
 254                if (dio->rw & WRITE) {
 255                        int err;
 256
 257                        err = generic_write_sync(dio->iocb->ki_filp, offset,
 258                                                 transferred);
 259                        if (err < 0 && ret > 0)
 260                                ret = err;
 261                }
 262
 263                aio_complete(dio->iocb, ret, 0);
 264        }
 265}
 266
 267/**
 268 * dio_complete() - called when all DIO BIO I/O has been completed
 269 * @offset: the byte offset in the file of the completed operation
 270 *
 271 * This drops i_dio_count, lets interested parties know that a DIO operation
 272 * has completed, and calculates the resulting return code for the operation.
 273 *
 274 * It lets the filesystem know if it registered an interest earlier via
 275 * get_block.  Pass the private field of the map buffer_head so that
 276 * filesystems can use it to hold additional state between get_block calls and
 277 * dio_complete.
 278 */
 279static ssize_t dio_complete(struct dio *dio, loff_t offset, ssize_t ret,
 280                unsigned int flags)
 281{
 282        ssize_t transferred = 0;
 283        int err;
 284        bool is_async = false;
 285
 286        /*
 287         * AIO submission can race with bio completion to get here while
 288         * expecting to have the last io completed by bio completion.
 289         * In that case -EIOCBQUEUED is in fact not an error we want
 290         * to preserve through this call.
 291         */
 292        if (ret == -EIOCBQUEUED)
 293                ret = 0;
 294
 295        if (dio->result) {
 296                transferred = dio->result;
 297
 298                /* Check for short read case */
 299                if ((dio->rw == READ) && ((offset + transferred) > dio->i_size))
 300                        transferred = dio->i_size - offset;
 301        }
 302
 303        if (ret == 0)
 304                ret = dio->page_errors;
 305        if (ret == 0)
 306                ret = dio->io_error;
 307        if (ret == 0)
 308                ret = transferred;
 309
 310        /*
 311         * Try again to invalidate clean pages which might have been cached by
 312         * non-direct readahead, or faulted in by get_user_pages() if the source
 313         * of the write was an mmap'ed region of the file we're writing.  Either
 314         * one is a pretty crazy thing to do, so we don't support it 100%.  If
 315         * this invalidation fails, tough, the write still worked...
 316         */
 317        if (flags & DIO_COMPLETE_INVALIDATE &&
 318            ret > 0 && dio->rw & WRITE &&
 319            dio->inode->i_mapping->nrpages) {
 320                err = invalidate_inode_pages2_range(dio->inode->i_mapping,
 321                                        offset >> PAGE_SHIFT,
 322                                        (offset + ret - 1) >> PAGE_SHIFT);
 323                WARN_ON_ONCE(err);
 324        }
 325
 326        /*
 327         * Red Hat only: we have to support two calling conventions for
 328         * dio_iodone_t functions:
 329         * 1) the original, where the routine will call aio_complete and
 330         * 2) the new calling convention, where that is done in the
 331         *    generic code.
 332         * Differentiate between the two cases using an inode flag that
 333         * gets populated for all in-tree file systems.
 334         */
 335        if (flags & DIO_COMPLETE_ASYNC)
 336                is_async = true;
 337        if (dio->inode->i_sb->s_type->fs_flags & FS_HAS_DIO_IODONE2)
 338                dio_iodone2_helper(dio, offset, transferred, ret, is_async);
 339        else
 340                dio_iodone_helper(dio, offset, transferred, ret, is_async);
 341
 342        kmem_cache_free(dio_cache, dio);
 343        return ret;
 344}
 345
 346static void dio_aio_complete_work(struct work_struct *work)
 347{
 348        struct dio *dio = container_of(work, struct dio, complete_work);
 349
 350        dio_complete(dio, dio->iocb->ki_pos, 0,
 351                     DIO_COMPLETE_ASYNC | DIO_COMPLETE_INVALIDATE);
 352}
 353
 354static int dio_bio_complete(struct dio *dio, struct bio *bio);
 355
 356/*
 357 * Asynchronous IO callback. 
 358 */
 359static void dio_bio_end_aio(struct bio *bio, int error)
 360{
 361        struct dio *dio = bio->bi_private;
 362        unsigned long remaining;
 363        unsigned long flags;
 364        bool defer_completion = false;
 365
 366        /* cleanup the bio */
 367        dio_bio_complete(dio, bio);
 368
 369        spin_lock_irqsave(&dio->bio_lock, flags);
 370        remaining = --dio->refcount;
 371        if (remaining == 1 && dio->waiter)
 372                wake_up_process(dio->waiter);
 373        spin_unlock_irqrestore(&dio->bio_lock, flags);
 374
 375        if (remaining == 0) {
 376                /*
 377                 * Defer completion when defer_completion is set or
 378                 * when the inode has pages mapped and this is AIO write.
 379                 * We need to invalidate those pages because there is a
 380                 * chance they contain stale data in the case buffered IO
 381                 * went in between AIO submission and completion into the
 382                 * same region.
 383                 */
 384                if (dio->result && (dio->inode->i_sb->s_type->fs_flags &
 385                                    FS_HAS_DIO_IODONE2)) {
 386                        defer_completion = dio->defer_completion ||
 387                                           (dio->rw & WRITE &&
 388                                            dio->inode->i_mapping->nrpages);
 389                }
 390                if (defer_completion) {
 391                        INIT_WORK(&dio->complete_work, dio_aio_complete_work);
 392                        queue_work(dio->inode->i_sb->s_dio_done_wq,
 393                                   &dio->complete_work);
 394                } else {
 395                        dio_complete(dio, dio->iocb->ki_pos, 0,
 396                                     DIO_COMPLETE_ASYNC);
 397                }
 398        }
 399}
 400
 401/*
 402 * The BIO completion handler simply queues the BIO up for the process-context
 403 * handler.
 404 *
 405 * During I/O bi_private points at the dio.  After I/O, bi_private is used to
 406 * implement a singly-linked list of completed BIOs, at dio->bio_list.
 407 */
 408static void dio_bio_end_io(struct bio *bio, int error)
 409{
 410        struct dio *dio = bio->bi_private;
 411        unsigned long flags;
 412
 413        spin_lock_irqsave(&dio->bio_lock, flags);
 414        bio->bi_private = dio->bio_list;
 415        dio->bio_list = bio;
 416        if (--dio->refcount == 1 && dio->waiter)
 417                wake_up_process(dio->waiter);
 418        spin_unlock_irqrestore(&dio->bio_lock, flags);
 419}
 420
 421/**
 422 * dio_end_io - handle the end io action for the given bio
 423 * @bio: The direct io bio thats being completed
 424 * @error: Error if there was one
 425 *
 426 * This is meant to be called by any filesystem that uses their own dio_submit_t
 427 * so that the DIO specific endio actions are dealt with after the filesystem
 428 * has done it's completion work.
 429 */
 430void dio_end_io(struct bio *bio, int error)
 431{
 432        struct dio *dio = bio->bi_private;
 433
 434        if (dio->is_async)
 435                dio_bio_end_aio(bio, error);
 436        else
 437                dio_bio_end_io(bio, error);
 438}
 439EXPORT_SYMBOL_GPL(dio_end_io);
 440
 441static inline void
 442dio_bio_alloc(struct dio *dio, struct dio_submit *sdio,
 443              struct block_device *bdev,
 444              sector_t first_sector, int nr_vecs)
 445{
 446        struct bio *bio;
 447
 448        /*
 449         * bio_alloc() is guaranteed to return a bio when called with
 450         * __GFP_WAIT and we request a valid number of vectors.
 451         */
 452        bio = bio_alloc(GFP_KERNEL, nr_vecs);
 453
 454        bio->bi_bdev = bdev;
 455        bio->bi_sector = first_sector;
 456        if (dio->is_async)
 457                bio->bi_end_io = dio_bio_end_aio;
 458        else
 459                bio->bi_end_io = dio_bio_end_io;
 460
 461        sdio->bio = bio;
 462        sdio->logical_offset_in_bio = sdio->cur_page_fs_offset;
 463}
 464
 465/*
 466 * In the AIO read case we speculatively dirty the pages before starting IO.
 467 * During IO completion, any of these pages which happen to have been written
 468 * back will be redirtied by bio_check_pages_dirty().
 469 *
 470 * bios hold a dio reference between submit_bio and ->end_io.
 471 */
 472static inline void dio_bio_submit(struct dio *dio, struct dio_submit *sdio)
 473{
 474        struct bio *bio = sdio->bio;
 475        unsigned long flags;
 476
 477        bio->bi_private = dio;
 478
 479        spin_lock_irqsave(&dio->bio_lock, flags);
 480        dio->refcount++;
 481        spin_unlock_irqrestore(&dio->bio_lock, flags);
 482
 483        if (dio->is_async && dio->rw == READ)
 484                bio_set_pages_dirty(bio);
 485
 486        if (sdio->submit_io)
 487                sdio->submit_io(dio->rw, bio, dio->inode,
 488                               sdio->logical_offset_in_bio);
 489        else
 490                submit_bio(dio->rw, bio);
 491
 492        sdio->bio = NULL;
 493        sdio->boundary = 0;
 494        sdio->logical_offset_in_bio = 0;
 495}
 496
 497/*
 498 * Release any resources in case of a failure
 499 */
 500static inline void dio_cleanup(struct dio *dio, struct dio_submit *sdio)
 501{
 502        while (dio_pages_present(sdio))
 503                page_cache_release(dio_get_page(dio, sdio));
 504}
 505
 506/*
 507 * Wait for the next BIO to complete.  Remove it and return it.  NULL is
 508 * returned once all BIOs have been completed.  This must only be called once
 509 * all bios have been issued so that dio->refcount can only decrease.  This
 510 * requires that that the caller hold a reference on the dio.
 511 */
 512static struct bio *dio_await_one(struct dio *dio)
 513{
 514        unsigned long flags;
 515        struct bio *bio = NULL;
 516
 517        spin_lock_irqsave(&dio->bio_lock, flags);
 518
 519        /*
 520         * Wait as long as the list is empty and there are bios in flight.  bio
 521         * completion drops the count, maybe adds to the list, and wakes while
 522         * holding the bio_lock so we don't need set_current_state()'s barrier
 523         * and can call it after testing our condition.
 524         */
 525        while (dio->refcount > 1 && dio->bio_list == NULL) {
 526                __set_current_state(TASK_UNINTERRUPTIBLE);
 527                dio->waiter = current;
 528                spin_unlock_irqrestore(&dio->bio_lock, flags);
 529                io_schedule();
 530                /* wake up sets us TASK_RUNNING */
 531                spin_lock_irqsave(&dio->bio_lock, flags);
 532                dio->waiter = NULL;
 533        }
 534        if (dio->bio_list) {
 535                bio = dio->bio_list;
 536                dio->bio_list = bio->bi_private;
 537        }
 538        spin_unlock_irqrestore(&dio->bio_lock, flags);
 539        return bio;
 540}
 541
 542/*
 543 * Process one completed BIO.  No locks are held.
 544 */
 545static int dio_bio_complete(struct dio *dio, struct bio *bio)
 546{
 547        const int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 548        struct bio_vec *bvec;
 549        unsigned i;
 550
 551        if (!uptodate)
 552                dio->io_error = -EIO;
 553
 554        if (dio->is_async && dio->rw == READ) {
 555                bio_check_pages_dirty(bio);     /* transfers ownership */
 556        } else {
 557                bio_for_each_segment_all(bvec, bio, i) {
 558                        struct page *page = bvec->bv_page;
 559
 560                        if (dio->rw == READ && !PageCompound(page))
 561                                set_page_dirty_lock(page);
 562                        page_cache_release(page);
 563                }
 564                bio_put(bio);
 565        }
 566        return uptodate ? 0 : -EIO;
 567}
 568
 569/*
 570 * Wait on and process all in-flight BIOs.  This must only be called once
 571 * all bios have been issued so that the refcount can only decrease.
 572 * This just waits for all bios to make it through dio_bio_complete.  IO
 573 * errors are propagated through dio->io_error and should be propagated via
 574 * dio_complete().
 575 */
 576static void dio_await_completion(struct dio *dio)
 577{
 578        struct bio *bio;
 579        do {
 580                bio = dio_await_one(dio);
 581                if (bio)
 582                        dio_bio_complete(dio, bio);
 583        } while (bio);
 584}
 585
 586/*
 587 * A really large O_DIRECT read or write can generate a lot of BIOs.  So
 588 * to keep the memory consumption sane we periodically reap any completed BIOs
 589 * during the BIO generation phase.
 590 *
 591 * This also helps to limit the peak amount of pinned userspace memory.
 592 */
 593static inline int dio_bio_reap(struct dio *dio, struct dio_submit *sdio)
 594{
 595        int ret = 0;
 596
 597        if (sdio->reap_counter++ >= 64) {
 598                while (dio->bio_list) {
 599                        unsigned long flags;
 600                        struct bio *bio;
 601                        int ret2;
 602
 603                        spin_lock_irqsave(&dio->bio_lock, flags);
 604                        bio = dio->bio_list;
 605                        dio->bio_list = bio->bi_private;
 606                        spin_unlock_irqrestore(&dio->bio_lock, flags);
 607                        ret2 = dio_bio_complete(dio, bio);
 608                        if (ret == 0)
 609                                ret = ret2;
 610                }
 611                sdio->reap_counter = 0;
 612        }
 613        return ret;
 614}
 615
 616/*
 617 * Create workqueue for deferred direct IO completions. We allocate the
 618 * workqueue when it's first needed. This avoids creating workqueue for
 619 * filesystems that don't need it and also allows us to create the workqueue
 620 * late enough so the we can include s_id in the name of the workqueue.
 621 */
 622static int sb_init_dio_done_wq(struct super_block *sb)
 623{
 624        struct workqueue_struct *wq = alloc_workqueue("dio/%s",
 625                                                      WQ_MEM_RECLAIM, 0,
 626                                                      sb->s_id);
 627        if (!wq)
 628                return -ENOMEM;
 629        /*
 630         * This has to be atomic as more DIOs can race to create the workqueue
 631         */
 632        cmpxchg(&sb->s_dio_done_wq, NULL, wq);
 633        /* Someone created workqueue before us? Free ours... */
 634        if (wq != sb->s_dio_done_wq)
 635                destroy_workqueue(wq);
 636        return 0;
 637}
 638
 639static int dio_set_defer_completion(struct dio *dio)
 640{
 641        struct super_block *sb = dio->inode->i_sb;
 642
 643        /*
 644         * If we get here, the file system had better understand the
 645         * new iodone calling convention.
 646         */
 647        WARN_ON(!(dio->inode->i_sb->s_type->fs_flags & FS_HAS_DIO_IODONE2));
 648        if (dio->defer_completion)
 649                return 0;
 650        dio->defer_completion = true;
 651        if (!sb->s_dio_done_wq)
 652                return sb_init_dio_done_wq(sb);
 653        return 0;
 654}
 655
 656/*
 657 * Call into the fs to map some more disk blocks.  We record the current number
 658 * of available blocks at sdio->blocks_available.  These are in units of the
 659 * fs blocksize, (1 << inode->i_blkbits).
 660 *
 661 * The fs is allowed to map lots of blocks at once.  If it wants to do that,
 662 * it uses the passed inode-relative block number as the file offset, as usual.
 663 *
 664 * get_block() is passed the number of i_blkbits-sized blocks which direct_io
 665 * has remaining to do.  The fs should not map more than this number of blocks.
 666 *
 667 * If the fs has mapped a lot of blocks, it should populate bh->b_size to
 668 * indicate how much contiguous disk space has been made available at
 669 * bh->b_blocknr.
 670 *
 671 * If *any* of the mapped blocks are new, then the fs must set buffer_new().
 672 * This isn't very efficient...
 673 *
 674 * In the case of filesystem holes: the fs may return an arbitrarily-large
 675 * hole by returning an appropriate value in b_size and by clearing
 676 * buffer_mapped().  However the direct-io code will only process holes one
 677 * block at a time - it will repeatedly call get_block() as it walks the hole.
 678 */
 679static int get_more_blocks(struct dio *dio, struct dio_submit *sdio,
 680                           struct buffer_head *map_bh)
 681{
 682        int ret;
 683        sector_t fs_startblk;   /* Into file, in filesystem-sized blocks */
 684        sector_t fs_endblk;     /* Into file, in filesystem-sized blocks */
 685        unsigned long fs_count; /* Number of filesystem-sized blocks */
 686        int create;
 687        unsigned int i_blkbits = sdio->blkbits + sdio->blkfactor;
 688
 689        /*
 690         * If there was a memory error and we've overwritten all the
 691         * mapped blocks then we can now return that memory error
 692         */
 693        ret = dio->page_errors;
 694        if (ret == 0) {
 695                BUG_ON(sdio->block_in_file >= sdio->final_block_in_request);
 696                fs_startblk = sdio->block_in_file >> sdio->blkfactor;
 697                fs_endblk = (sdio->final_block_in_request - 1) >>
 698                                        sdio->blkfactor;
 699                fs_count = fs_endblk - fs_startblk + 1;
 700
 701                map_bh->b_state = 0;
 702                map_bh->b_size = fs_count << i_blkbits;
 703
 704                /*
 705                 * For writes that could fill holes inside i_size on a
 706                 * DIO_SKIP_HOLES filesystem we forbid block creations: only
 707                 * overwrites are permitted. We will return early to the caller
 708                 * once we see an unmapped buffer head returned, and the caller
 709                 * will fall back to buffered I/O.
 710                 *
 711                 * Otherwise the decision is left to the get_blocks method,
 712                 * which may decide to handle it or also return an unmapped
 713                 * buffer head.
 714                 */
 715                create = dio->rw & WRITE;
 716                if (dio->flags & DIO_SKIP_HOLES) {
 717                        if (fs_startblk <= ((i_size_read(dio->inode) - 1) >>
 718                                                        i_blkbits))
 719                                create = 0;
 720                }
 721
 722                ret = (*sdio->get_block)(dio->inode, fs_startblk,
 723                                                map_bh, create);
 724
 725                /* Store for completion */
 726                dio->private = map_bh->b_private;
 727
 728                if (ret == 0 && buffer_defer_completion(map_bh))
 729                        ret = dio_set_defer_completion(dio);
 730        }
 731        return ret;
 732}
 733
 734/*
 735 * There is no bio.  Make one now.
 736 */
 737static inline int dio_new_bio(struct dio *dio, struct dio_submit *sdio,
 738                sector_t start_sector, struct buffer_head *map_bh)
 739{
 740        sector_t sector;
 741        int ret, nr_pages;
 742
 743        ret = dio_bio_reap(dio, sdio);
 744        if (ret)
 745                goto out;
 746        sector = start_sector << (sdio->blkbits - 9);
 747        nr_pages = min(sdio->pages_in_io, bio_get_nr_vecs(map_bh->b_bdev));
 748        nr_pages = min(nr_pages, BIO_MAX_PAGES);
 749        BUG_ON(nr_pages <= 0);
 750        dio_bio_alloc(dio, sdio, map_bh->b_bdev, sector, nr_pages);
 751        sdio->boundary = 0;
 752out:
 753        return ret;
 754}
 755
 756/*
 757 * Attempt to put the current chunk of 'cur_page' into the current BIO.  If
 758 * that was successful then update final_block_in_bio and take a ref against
 759 * the just-added page.
 760 *
 761 * Return zero on success.  Non-zero means the caller needs to start a new BIO.
 762 */
 763static inline int dio_bio_add_page(struct dio_submit *sdio)
 764{
 765        int ret;
 766
 767        ret = bio_add_page(sdio->bio, sdio->cur_page,
 768                        sdio->cur_page_len, sdio->cur_page_offset);
 769        if (ret == sdio->cur_page_len) {
 770                /*
 771                 * Decrement count only, if we are done with this page
 772                 */
 773                if ((sdio->cur_page_len + sdio->cur_page_offset) == PAGE_SIZE)
 774                        sdio->pages_in_io--;
 775                page_cache_get(sdio->cur_page);
 776                sdio->final_block_in_bio = sdio->cur_page_block +
 777                        (sdio->cur_page_len >> sdio->blkbits);
 778                ret = 0;
 779        } else {
 780                ret = 1;
 781        }
 782        return ret;
 783}
 784                
 785/*
 786 * Put cur_page under IO.  The section of cur_page which is described by
 787 * cur_page_offset,cur_page_len is put into a BIO.  The section of cur_page
 788 * starts on-disk at cur_page_block.
 789 *
 790 * We take a ref against the page here (on behalf of its presence in the bio).
 791 *
 792 * The caller of this function is responsible for removing cur_page from the
 793 * dio, and for dropping the refcount which came from that presence.
 794 */
 795static inline int dio_send_cur_page(struct dio *dio, struct dio_submit *sdio,
 796                struct buffer_head *map_bh)
 797{
 798        int ret = 0;
 799
 800        if (sdio->bio) {
 801                loff_t cur_offset = sdio->cur_page_fs_offset;
 802                loff_t bio_next_offset = sdio->logical_offset_in_bio +
 803                        sdio->bio->bi_size;
 804
 805                /*
 806                 * See whether this new request is contiguous with the old.
 807                 *
 808                 * Btrfs cannot handle having logically non-contiguous requests
 809                 * submitted.  For example if you have
 810                 *
 811                 * Logical:  [0-4095][HOLE][8192-12287]
 812                 * Physical: [0-4095]      [4096-8191]
 813                 *
 814                 * We cannot submit those pages together as one BIO.  So if our
 815                 * current logical offset in the file does not equal what would
 816                 * be the next logical offset in the bio, submit the bio we
 817                 * have.
 818                 */
 819                if (sdio->final_block_in_bio != sdio->cur_page_block ||
 820                    cur_offset != bio_next_offset)
 821                        dio_bio_submit(dio, sdio);
 822        }
 823
 824        if (sdio->bio == NULL) {
 825                ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
 826                if (ret)
 827                        goto out;
 828        }
 829
 830        if (dio_bio_add_page(sdio) != 0) {
 831                dio_bio_submit(dio, sdio);
 832                ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
 833                if (ret == 0) {
 834                        ret = dio_bio_add_page(sdio);
 835                        BUG_ON(ret != 0);
 836                }
 837        }
 838out:
 839        return ret;
 840}
 841
 842/*
 843 * An autonomous function to put a chunk of a page under deferred IO.
 844 *
 845 * The caller doesn't actually know (or care) whether this piece of page is in
 846 * a BIO, or is under IO or whatever.  We just take care of all possible 
 847 * situations here.  The separation between the logic of do_direct_IO() and
 848 * that of submit_page_section() is important for clarity.  Please don't break.
 849 *
 850 * The chunk of page starts on-disk at blocknr.
 851 *
 852 * We perform deferred IO, by recording the last-submitted page inside our
 853 * private part of the dio structure.  If possible, we just expand the IO
 854 * across that page here.
 855 *
 856 * If that doesn't work out then we put the old page into the bio and add this
 857 * page to the dio instead.
 858 */
 859static inline int
 860submit_page_section(struct dio *dio, struct dio_submit *sdio, struct page *page,
 861                    unsigned offset, unsigned len, sector_t blocknr,
 862                    struct buffer_head *map_bh)
 863{
 864        int ret = 0;
 865
 866        if (dio->rw & WRITE) {
 867                /*
 868                 * Read accounting is performed in submit_bio()
 869                 */
 870                task_io_account_write(len);
 871        }
 872
 873        /*
 874         * Can we just grow the current page's presence in the dio?
 875         */
 876        if (sdio->cur_page == page &&
 877            sdio->cur_page_offset + sdio->cur_page_len == offset &&
 878            sdio->cur_page_block +
 879            (sdio->cur_page_len >> sdio->blkbits) == blocknr) {
 880                sdio->cur_page_len += len;
 881                goto out;
 882        }
 883
 884        /*
 885         * If there's a deferred page already there then send it.
 886         */
 887        if (sdio->cur_page) {
 888                ret = dio_send_cur_page(dio, sdio, map_bh);
 889                page_cache_release(sdio->cur_page);
 890                sdio->cur_page = NULL;
 891                if (ret)
 892                        return ret;
 893        }
 894
 895        page_cache_get(page);           /* It is in dio */
 896        sdio->cur_page = page;
 897        sdio->cur_page_offset = offset;
 898        sdio->cur_page_len = len;
 899        sdio->cur_page_block = blocknr;
 900        sdio->cur_page_fs_offset = sdio->block_in_file << sdio->blkbits;
 901out:
 902        /*
 903         * If sdio->boundary then we want to schedule the IO now to
 904         * avoid metadata seeks.
 905         */
 906        if (sdio->boundary) {
 907                ret = dio_send_cur_page(dio, sdio, map_bh);
 908                dio_bio_submit(dio, sdio);
 909                page_cache_release(sdio->cur_page);
 910                sdio->cur_page = NULL;
 911        }
 912        return ret;
 913}
 914
 915/*
 916 * Clean any dirty buffers in the blockdev mapping which alias newly-created
 917 * file blocks.  Only called for S_ISREG files - blockdevs do not set
 918 * buffer_new
 919 */
 920static void clean_blockdev_aliases(struct dio *dio, struct buffer_head *map_bh)
 921{
 922        unsigned i;
 923        unsigned nblocks;
 924
 925        nblocks = map_bh->b_size >> dio->inode->i_blkbits;
 926
 927        for (i = 0; i < nblocks; i++) {
 928                unmap_underlying_metadata(map_bh->b_bdev,
 929                                          map_bh->b_blocknr + i);
 930        }
 931}
 932
 933/*
 934 * If we are not writing the entire block and get_block() allocated
 935 * the block for us, we need to fill-in the unused portion of the
 936 * block with zeros. This happens only if user-buffer, fileoffset or
 937 * io length is not filesystem block-size multiple.
 938 *
 939 * `end' is zero if we're doing the start of the IO, 1 at the end of the
 940 * IO.
 941 */
 942static inline void dio_zero_block(struct dio *dio, struct dio_submit *sdio,
 943                int end, struct buffer_head *map_bh)
 944{
 945        unsigned dio_blocks_per_fs_block;
 946        unsigned this_chunk_blocks;     /* In dio_blocks */
 947        unsigned this_chunk_bytes;
 948        struct page *page;
 949
 950        sdio->start_zero_done = 1;
 951        if (!sdio->blkfactor || !buffer_new(map_bh))
 952                return;
 953
 954        dio_blocks_per_fs_block = 1 << sdio->blkfactor;
 955        this_chunk_blocks = sdio->block_in_file & (dio_blocks_per_fs_block - 1);
 956
 957        if (!this_chunk_blocks)
 958                return;
 959
 960        /*
 961         * We need to zero out part of an fs block.  It is either at the
 962         * beginning or the end of the fs block.
 963         */
 964        if (end) 
 965                this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
 966
 967        this_chunk_bytes = this_chunk_blocks << sdio->blkbits;
 968
 969        page = ZERO_PAGE(0);
 970        if (submit_page_section(dio, sdio, page, 0, this_chunk_bytes,
 971                                sdio->next_block_for_io, map_bh))
 972                return;
 973
 974        sdio->next_block_for_io += this_chunk_blocks;
 975}
 976
 977/*
 978 * Walk the user pages, and the file, mapping blocks to disk and generating
 979 * a sequence of (page,offset,len,block) mappings.  These mappings are injected
 980 * into submit_page_section(), which takes care of the next stage of submission
 981 *
 982 * Direct IO against a blockdev is different from a file.  Because we can
 983 * happily perform page-sized but 512-byte aligned IOs.  It is important that
 984 * blockdev IO be able to have fine alignment and large sizes.
 985 *
 986 * So what we do is to permit the ->get_block function to populate bh.b_size
 987 * with the size of IO which is permitted at this offset and this i_blkbits.
 988 *
 989 * For best results, the blockdev should be set up with 512-byte i_blkbits and
 990 * it should set b_size to PAGE_SIZE or more inside get_block().  This gives
 991 * fine alignment but still allows this function to work in PAGE_SIZE units.
 992 */
 993static int do_direct_IO(struct dio *dio, struct dio_submit *sdio,
 994                        struct buffer_head *map_bh)
 995{
 996        const unsigned blkbits = sdio->blkbits;
 997        const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
 998        struct page *page;
 999        unsigned block_in_page;
1000        int ret = 0;
1001
1002        /* The I/O can start at any block offset within the first page */
1003        block_in_page = sdio->first_block_in_page;
1004
1005        while (sdio->block_in_file < sdio->final_block_in_request) {
1006                page = dio_get_page(dio, sdio);
1007                if (IS_ERR(page)) {
1008                        ret = PTR_ERR(page);
1009                        goto out;
1010                }
1011
1012                while (block_in_page < blocks_per_page) {
1013                        unsigned offset_in_page = block_in_page << blkbits;
1014                        unsigned this_chunk_bytes;      /* # of bytes mapped */
1015                        unsigned this_chunk_blocks;     /* # of blocks */
1016                        unsigned u;
1017
1018                        if (sdio->blocks_available == 0) {
1019                                /*
1020                                 * Need to go and map some more disk
1021                                 */
1022                                unsigned long blkmask;
1023                                unsigned long dio_remainder;
1024
1025                                ret = get_more_blocks(dio, sdio, map_bh);
1026                                if (ret) {
1027                                        page_cache_release(page);
1028                                        goto out;
1029                                }
1030                                if (!buffer_mapped(map_bh))
1031                                        goto do_holes;
1032
1033                                sdio->blocks_available =
1034                                                map_bh->b_size >> sdio->blkbits;
1035                                sdio->next_block_for_io =
1036                                        map_bh->b_blocknr << sdio->blkfactor;
1037                                if (buffer_new(map_bh))
1038                                        clean_blockdev_aliases(dio, map_bh);
1039
1040                                if (!sdio->blkfactor)
1041                                        goto do_holes;
1042
1043                                blkmask = (1 << sdio->blkfactor) - 1;
1044                                dio_remainder = (sdio->block_in_file & blkmask);
1045
1046                                /*
1047                                 * If we are at the start of IO and that IO
1048                                 * starts partway into a fs-block,
1049                                 * dio_remainder will be non-zero.  If the IO
1050                                 * is a read then we can simply advance the IO
1051                                 * cursor to the first block which is to be
1052                                 * read.  But if the IO is a write and the
1053                                 * block was newly allocated we cannot do that;
1054                                 * the start of the fs block must be zeroed out
1055                                 * on-disk
1056                                 */
1057                                if (!buffer_new(map_bh))
1058                                        sdio->next_block_for_io += dio_remainder;
1059                                sdio->blocks_available -= dio_remainder;
1060                        }
1061do_holes:
1062                        /* Handle holes */
1063                        if (!buffer_mapped(map_bh)) {
1064                                loff_t i_size_aligned;
1065
1066                                /* AKPM: eargh, -ENOTBLK is a hack */
1067                                if (dio->rw & WRITE) {
1068                                        page_cache_release(page);
1069                                        return -ENOTBLK;
1070                                }
1071
1072                                /*
1073                                 * Be sure to account for a partial block as the
1074                                 * last block in the file
1075                                 */
1076                                i_size_aligned = ALIGN(i_size_read(dio->inode),
1077                                                        1 << blkbits);
1078                                if (sdio->block_in_file >=
1079                                                i_size_aligned >> blkbits) {
1080                                        /* We hit eof */
1081                                        page_cache_release(page);
1082                                        goto out;
1083                                }
1084                                zero_user(page, block_in_page << blkbits,
1085                                                1 << blkbits);
1086                                sdio->block_in_file++;
1087                                block_in_page++;
1088                                goto next_block;
1089                        }
1090
1091                        /*
1092                         * If we're performing IO which has an alignment which
1093                         * is finer than the underlying fs, go check to see if
1094                         * we must zero out the start of this block.
1095                         */
1096                        if (unlikely(sdio->blkfactor && !sdio->start_zero_done))
1097                                dio_zero_block(dio, sdio, 0, map_bh);
1098
1099                        /*
1100                         * Work out, in this_chunk_blocks, how much disk we
1101                         * can add to this page
1102                         */
1103                        this_chunk_blocks = sdio->blocks_available;
1104                        u = (PAGE_SIZE - offset_in_page) >> blkbits;
1105                        if (this_chunk_blocks > u)
1106                                this_chunk_blocks = u;
1107                        u = sdio->final_block_in_request - sdio->block_in_file;
1108                        if (this_chunk_blocks > u)
1109                                this_chunk_blocks = u;
1110                        this_chunk_bytes = this_chunk_blocks << blkbits;
1111                        BUG_ON(this_chunk_bytes == 0);
1112
1113                        if (this_chunk_blocks == sdio->blocks_available)
1114                                sdio->boundary = buffer_boundary(map_bh);
1115                        ret = submit_page_section(dio, sdio, page,
1116                                                  offset_in_page,
1117                                                  this_chunk_bytes,
1118                                                  sdio->next_block_for_io,
1119                                                  map_bh);
1120                        if (ret) {
1121                                page_cache_release(page);
1122                                goto out;
1123                        }
1124                        sdio->next_block_for_io += this_chunk_blocks;
1125
1126                        sdio->block_in_file += this_chunk_blocks;
1127                        block_in_page += this_chunk_blocks;
1128                        sdio->blocks_available -= this_chunk_blocks;
1129next_block:
1130                        BUG_ON(sdio->block_in_file > sdio->final_block_in_request);
1131                        if (sdio->block_in_file == sdio->final_block_in_request)
1132                                break;
1133                }
1134
1135                /* Drop the ref which was taken in get_user_pages() */
1136                page_cache_release(page);
1137                block_in_page = 0;
1138        }
1139out:
1140        return ret;
1141}
1142
1143static inline int drop_refcount(struct dio *dio)
1144{
1145        int ret2;
1146        unsigned long flags;
1147
1148        /*
1149         * Sync will always be dropping the final ref and completing the
1150         * operation.  AIO can if it was a broken operation described above or
1151         * in fact if all the bios race to complete before we get here.  In
1152         * that case dio_complete() translates the EIOCBQUEUED into the proper
1153         * return code that the caller will hand to aio_complete().
1154         *
1155         * This is managed by the bio_lock instead of being an atomic_t so that
1156         * completion paths can drop their ref and use the remaining count to
1157         * decide to wake the submission path atomically.
1158         */
1159        spin_lock_irqsave(&dio->bio_lock, flags);
1160        ret2 = --dio->refcount;
1161        spin_unlock_irqrestore(&dio->bio_lock, flags);
1162        return ret2;
1163}
1164
1165/*
1166 * This is a library function for use by filesystem drivers.
1167 *
1168 * The locking rules are governed by the flags parameter:
1169 *  - if the flags value contains DIO_LOCKING we use a fancy locking
1170 *    scheme for dumb filesystems.
1171 *    For writes this function is called under i_mutex and returns with
1172 *    i_mutex held, for reads, i_mutex is not held on entry, but it is
1173 *    taken and dropped again before returning.
1174 *  - if the flags value does NOT contain DIO_LOCKING we don't use any
1175 *    internal locking but rather rely on the filesystem to synchronize
1176 *    direct I/O reads/writes versus each other and truncate.
1177 *
1178 * To help with locking against truncate we incremented the i_dio_count
1179 * counter before starting direct I/O, and decrement it once we are done.
1180 * Truncate can wait for it to reach zero to provide exclusion.  It is
1181 * expected that filesystem provide exclusion between new direct I/O
1182 * and truncates.  For DIO_LOCKING filesystems this is done by i_mutex,
1183 * but other filesystems need to take care of this on their own.
1184 *
1185 * NOTE: if you pass "sdio" to anything by pointer make sure that function
1186 * is always inlined. Otherwise gcc is unable to split the structure into
1187 * individual fields and will generate much worse code. This is important
1188 * for the whole file.
1189 */
1190static inline ssize_t
1191do_blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
1192        struct block_device *bdev, const struct iovec *iov, loff_t offset, 
1193        unsigned long nr_segs, get_block_t get_block, dio_iodone_t end_io,
1194        dio_submit_t submit_io, int flags)
1195{
1196        int seg;
1197        size_t size;
1198        unsigned long addr;
1199        unsigned i_blkbits = ACCESS_ONCE(inode->i_blkbits);
1200        unsigned blkbits = i_blkbits;
1201        unsigned blocksize_mask = (1 << blkbits) - 1;
1202        ssize_t retval = -EINVAL;
1203        loff_t end = offset;
1204        struct dio *dio;
1205        struct dio_submit sdio = { 0, };
1206        unsigned long user_addr;
1207        size_t bytes;
1208        struct buffer_head map_bh = { 0, };
1209        struct blk_plug plug;
1210
1211        if (rw & WRITE)
1212                rw = WRITE_ODIRECT;
1213
1214        /*
1215         * Avoid references to bdev if not absolutely needed to give
1216         * the early prefetch in the caller enough time.
1217         */
1218
1219        if (offset & blocksize_mask) {
1220                if (bdev)
1221                        blkbits = blksize_bits(bdev_logical_block_size(bdev));
1222                blocksize_mask = (1 << blkbits) - 1;
1223                if (offset & blocksize_mask)
1224                        goto out;
1225        }
1226
1227        /* Check the memory alignment.  Blocks cannot straddle pages */
1228        for (seg = 0; seg < nr_segs; seg++) {
1229                addr = (unsigned long)iov[seg].iov_base;
1230                size = iov[seg].iov_len;
1231                end += size;
1232                if (unlikely((addr & blocksize_mask) ||
1233                             (size & blocksize_mask))) {
1234                        if (bdev)
1235                                blkbits = blksize_bits(
1236                                         bdev_logical_block_size(bdev));
1237                        blocksize_mask = (1 << blkbits) - 1;
1238                        if ((addr & blocksize_mask) || (size & blocksize_mask))
1239                                goto out;
1240                }
1241        }
1242
1243        /* watch out for a 0 len io from a tricksy fs */
1244        if (rw == READ && end == offset)
1245                return 0;
1246
1247        dio = kmem_cache_alloc(dio_cache, GFP_KERNEL);
1248        retval = -ENOMEM;
1249        if (!dio)
1250                goto out;
1251        /*
1252         * Believe it or not, zeroing out the page array caused a .5%
1253         * performance regression in a database benchmark.  So, we take
1254         * care to only zero out what's needed.
1255         */
1256        memset(dio, 0, offsetof(struct dio, pages));
1257
1258        dio->flags = flags;
1259        if (dio->flags & DIO_LOCKING) {
1260                if (rw == READ) {
1261                        struct address_space *mapping =
1262                                        iocb->ki_filp->f_mapping;
1263
1264                        /* will be released by direct_io_worker */
1265                        mutex_lock(&inode->i_mutex);
1266
1267                        retval = filemap_write_and_wait_range(mapping, offset,
1268                                                              end - 1);
1269                        if (retval) {
1270                                mutex_unlock(&inode->i_mutex);
1271                                kmem_cache_free(dio_cache, dio);
1272                                goto out;
1273                        }
1274                }
1275        }
1276
1277        /* Once we sampled i_size check for reads beyond EOF */
1278        dio->i_size = i_size_read(inode);
1279        if (rw == READ && offset >= dio->i_size) {
1280                if (dio->flags & DIO_LOCKING)
1281                        mutex_unlock(&inode->i_mutex);
1282                kmem_cache_free(dio_cache, dio);
1283                retval = 0;
1284                goto out;
1285        }
1286
1287        /*
1288         * For file extending writes updating i_size before data writeouts
1289         * complete can expose uninitialized blocks in dumb filesystems.
1290         * In that case we need to wait for I/O completion even if asked
1291         * for an asynchronous write.
1292         */
1293        if (is_sync_kiocb(iocb))
1294                dio->is_async = false;
1295        else if (!(dio->flags & DIO_ASYNC_EXTEND) &&
1296            (rw & WRITE) && end > i_size_read(inode))
1297                dio->is_async = false;
1298        else
1299                dio->is_async = true;
1300
1301        dio->inode = inode;
1302        dio->rw = rw;
1303
1304        /*
1305         * For AIO O_(D)SYNC writes we need to defer completions to a workqueue
1306         * so that we can call ->fsync.
1307         */
1308        if ((dio->inode->i_sb->s_type->fs_flags & FS_HAS_DIO_IODONE2) &&
1309            dio->is_async && (rw & WRITE)) {
1310                retval = 0;
1311                if ((iocb->ki_filp->f_flags & O_DSYNC) ||
1312                    IS_SYNC(iocb->ki_filp->f_mapping->host))
1313                        retval = dio_set_defer_completion(dio);
1314                else if (!dio->inode->i_sb->s_dio_done_wq) {
1315                        /*
1316                         * In case of AIO write racing with buffered read we
1317                         * need to defer completion. We can't decide this now,
1318                         * however the workqueue needs to be initialized here.
1319                         */
1320                        retval = sb_init_dio_done_wq(dio->inode->i_sb);
1321                }
1322                if (retval) {
1323                        /*
1324                         * We grab i_mutex only for reads so we don't have
1325                         * to release it here
1326                         */
1327                        kmem_cache_free(dio_cache, dio);
1328                        goto out;
1329                }
1330        }
1331
1332        /*
1333         * Will be decremented at I/O completion time.
1334         */
1335        if (!(dio->flags & DIO_SKIP_DIO_COUNT))
1336                inode_dio_begin(inode);
1337
1338        retval = 0;
1339        sdio.blkbits = blkbits;
1340        sdio.blkfactor = i_blkbits - blkbits;
1341        sdio.block_in_file = offset >> blkbits;
1342
1343        sdio.get_block = get_block;
1344        dio->end_io = end_io;
1345        sdio.submit_io = submit_io;
1346        sdio.final_block_in_bio = -1;
1347        sdio.next_block_for_io = -1;
1348
1349        dio->iocb = iocb;
1350
1351        spin_lock_init(&dio->bio_lock);
1352        dio->refcount = 1;
1353
1354        /*
1355         * In case of non-aligned buffers, we may need 2 more
1356         * pages since we need to zero out first and last block.
1357         */
1358        if (unlikely(sdio.blkfactor))
1359                sdio.pages_in_io = 2;
1360
1361        for (seg = 0; seg < nr_segs; seg++) {
1362                user_addr = (unsigned long)iov[seg].iov_base;
1363                sdio.pages_in_io +=
1364                        ((user_addr + iov[seg].iov_len + PAGE_SIZE-1) /
1365                                PAGE_SIZE - user_addr / PAGE_SIZE);
1366        }
1367
1368        blk_start_plug(&plug);
1369
1370        for (seg = 0; seg < nr_segs; seg++) {
1371                user_addr = (unsigned long)iov[seg].iov_base;
1372                sdio.size += bytes = iov[seg].iov_len;
1373
1374                /* Index into the first page of the first block */
1375                sdio.first_block_in_page = (user_addr & ~PAGE_MASK) >> blkbits;
1376                sdio.final_block_in_request = sdio.block_in_file +
1377                                                (bytes >> blkbits);
1378                /* Page fetching state */
1379                sdio.head = 0;
1380                sdio.tail = 0;
1381                sdio.curr_page = 0;
1382
1383                sdio.total_pages = 0;
1384                if (user_addr & (PAGE_SIZE-1)) {
1385                        sdio.total_pages++;
1386                        bytes -= PAGE_SIZE - (user_addr & (PAGE_SIZE - 1));
1387                }
1388                sdio.total_pages += (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1389                sdio.curr_user_address = user_addr;
1390
1391                retval = do_direct_IO(dio, &sdio, &map_bh);
1392
1393                dio->result += iov[seg].iov_len -
1394                        ((sdio.final_block_in_request - sdio.block_in_file) <<
1395                                        blkbits);
1396
1397                if (retval) {
1398                        dio_cleanup(dio, &sdio);
1399                        break;
1400                }
1401        } /* end iovec loop */
1402
1403        if (retval == -ENOTBLK) {
1404                /*
1405                 * The remaining part of the request will be
1406                 * be handled by buffered I/O when we return
1407                 */
1408                retval = 0;
1409        }
1410        /*
1411         * There may be some unwritten disk at the end of a part-written
1412         * fs-block-sized block.  Go zero that now.
1413         */
1414        dio_zero_block(dio, &sdio, 1, &map_bh);
1415
1416        if (sdio.cur_page) {
1417                ssize_t ret2;
1418
1419                ret2 = dio_send_cur_page(dio, &sdio, &map_bh);
1420                if (retval == 0)
1421                        retval = ret2;
1422                page_cache_release(sdio.cur_page);
1423                sdio.cur_page = NULL;
1424        }
1425        if (sdio.bio)
1426                dio_bio_submit(dio, &sdio);
1427
1428        blk_finish_plug(&plug);
1429
1430        /*
1431         * It is possible that, we return short IO due to end of file.
1432         * In that case, we need to release all the pages we got hold on.
1433         */
1434        dio_cleanup(dio, &sdio);
1435
1436        /*
1437         * All block lookups have been performed. For READ requests
1438         * we can let i_mutex go now that its achieved its purpose
1439         * of protecting us from looking up uninitialized blocks.
1440         */
1441        if (rw == READ && (dio->flags & DIO_LOCKING))
1442                mutex_unlock(&dio->inode->i_mutex);
1443
1444        /*
1445         * The only time we want to leave bios in flight is when a successful
1446         * partial aio read or full aio write have been setup.  In that case
1447         * bio completion will call aio_complete.  The only time it's safe to
1448         * call aio_complete is when we return -EIOCBQUEUED, so we key on that.
1449         * This had *better* be the only place that raises -EIOCBQUEUED.
1450         */
1451        BUG_ON(retval == -EIOCBQUEUED);
1452        if (dio->is_async && retval == 0 && dio->result &&
1453            ((rw == READ) || (dio->result == sdio.size)))
1454                retval = -EIOCBQUEUED;
1455
1456        if (retval != -EIOCBQUEUED)
1457                dio_await_completion(dio);
1458
1459        if (drop_refcount(dio) == 0) {
1460                retval = dio_complete(dio, offset, retval,
1461                                      DIO_COMPLETE_INVALIDATE);
1462        } else
1463                BUG_ON(retval != -EIOCBQUEUED);
1464
1465out:
1466        return retval;
1467}
1468
1469ssize_t
1470__blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
1471        struct block_device *bdev, const struct iovec *iov, loff_t offset,
1472        unsigned long nr_segs, get_block_t get_block, dio_iodone_t end_io,
1473        dio_submit_t submit_io, int flags)
1474{
1475        /*
1476         * The block device state is needed in the end to finally
1477         * submit everything.  Since it's likely to be cache cold
1478         * prefetch it here as first thing to hide some of the
1479         * latency.
1480         *
1481         * Attempt to prefetch the pieces we likely need later.
1482         */
1483        prefetch(&bdev->bd_disk->part_tbl);
1484        prefetch(bdev->bd_queue);
1485        prefetch((char *)bdev->bd_queue + SMP_CACHE_BYTES);
1486
1487        return do_blockdev_direct_IO(rw, iocb, inode, bdev, iov, offset,
1488                                     nr_segs, get_block, end_io,
1489                                     submit_io, flags);
1490}
1491
1492EXPORT_SYMBOL(__blockdev_direct_IO);
1493
1494static __init int dio_init(void)
1495{
1496        dio_cache = KMEM_CACHE(dio, SLAB_PANIC);
1497        return 0;
1498}
1499module_init(dio_init)
1500