linux/mm/filemap.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 *      linux/mm/filemap.c
   4 *
   5 * Copyright (C) 1994-1999  Linus Torvalds
   6 */
   7
   8/*
   9 * This file handles the generic file mmap semantics used by
  10 * most "normal" filesystems (but you don't /have/ to use this:
  11 * the NFS filesystem used to do this differently, for example)
  12 */
  13#include <linux/export.h>
  14#include <linux/compiler.h>
  15#include <linux/dax.h>
  16#include <linux/fs.h>
  17#include <linux/sched/signal.h>
  18#include <linux/uaccess.h>
  19#include <linux/capability.h>
  20#include <linux/kernel_stat.h>
  21#include <linux/gfp.h>
  22#include <linux/mm.h>
  23#include <linux/swap.h>
  24#include <linux/mman.h>
  25#include <linux/pagemap.h>
  26#include <linux/file.h>
  27#include <linux/uio.h>
  28#include <linux/error-injection.h>
  29#include <linux/hash.h>
  30#include <linux/writeback.h>
  31#include <linux/backing-dev.h>
  32#include <linux/pagevec.h>
  33#include <linux/blkdev.h>
  34#include <linux/security.h>
  35#include <linux/cpuset.h>
  36#include <linux/hugetlb.h>
  37#include <linux/memcontrol.h>
  38#include <linux/cleancache.h>
  39#include <linux/shmem_fs.h>
  40#include <linux/rmap.h>
  41#include <linux/delayacct.h>
  42#include <linux/psi.h>
  43#include "internal.h"
  44
  45#define CREATE_TRACE_POINTS
  46#include <trace/events/filemap.h>
  47
  48/*
  49 * FIXME: remove all knowledge of the buffer layer from the core VM
  50 */
  51#include <linux/buffer_head.h> /* for try_to_free_buffers */
  52
  53#include <asm/mman.h>
  54
  55/*
  56 * Shared mappings implemented 30.11.1994. It's not fully working yet,
  57 * though.
  58 *
  59 * Shared mappings now work. 15.8.1995  Bruno.
  60 *
  61 * finished 'unifying' the page and buffer cache and SMP-threaded the
  62 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
  63 *
  64 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
  65 */
  66
  67/*
  68 * Lock ordering:
  69 *
  70 *  ->i_mmap_rwsem              (truncate_pagecache)
  71 *    ->private_lock            (__free_pte->__set_page_dirty_buffers)
  72 *      ->swap_lock             (exclusive_swap_page, others)
  73 *        ->i_pages lock
  74 *
  75 *  ->i_mutex
  76 *    ->i_mmap_rwsem            (truncate->unmap_mapping_range)
  77 *
  78 *  ->mmap_sem
  79 *    ->i_mmap_rwsem
  80 *      ->page_table_lock or pte_lock   (various, mainly in memory.c)
  81 *        ->i_pages lock        (arch-dependent flush_dcache_mmap_lock)
  82 *
  83 *  ->mmap_sem
  84 *    ->lock_page               (access_process_vm)
  85 *
  86 *  ->i_mutex                   (generic_perform_write)
  87 *    ->mmap_sem                (fault_in_pages_readable->do_page_fault)
  88 *
  89 *  bdi->wb.list_lock
  90 *    sb_lock                   (fs/fs-writeback.c)
  91 *    ->i_pages lock            (__sync_single_inode)
  92 *
  93 *  ->i_mmap_rwsem
  94 *    ->anon_vma.lock           (vma_adjust)
  95 *
  96 *  ->anon_vma.lock
  97 *    ->page_table_lock or pte_lock     (anon_vma_prepare and various)
  98 *
  99 *  ->page_table_lock or pte_lock
 100 *    ->swap_lock               (try_to_unmap_one)
 101 *    ->private_lock            (try_to_unmap_one)
 102 *    ->i_pages lock            (try_to_unmap_one)
 103 *    ->pgdat->lru_lock         (follow_page->mark_page_accessed)
 104 *    ->pgdat->lru_lock         (check_pte_range->isolate_lru_page)
 105 *    ->private_lock            (page_remove_rmap->set_page_dirty)
 106 *    ->i_pages lock            (page_remove_rmap->set_page_dirty)
 107 *    bdi.wb->list_lock         (page_remove_rmap->set_page_dirty)
 108 *    ->inode->i_lock           (page_remove_rmap->set_page_dirty)
 109 *    ->memcg->move_lock        (page_remove_rmap->lock_page_memcg)
 110 *    bdi.wb->list_lock         (zap_pte_range->set_page_dirty)
 111 *    ->inode->i_lock           (zap_pte_range->set_page_dirty)
 112 *    ->private_lock            (zap_pte_range->__set_page_dirty_buffers)
 113 *
 114 * ->i_mmap_rwsem
 115 *   ->tasklist_lock            (memory_failure, collect_procs_ao)
 116 */
 117
 118static void page_cache_delete(struct address_space *mapping,
 119                                   struct page *page, void *shadow)
 120{
 121        XA_STATE(xas, &mapping->i_pages, page->index);
 122        unsigned int nr = 1;
 123
 124        mapping_set_update(&xas, mapping);
 125
 126        /* hugetlb pages are represented by a single entry in the xarray */
 127        if (!PageHuge(page)) {
 128                xas_set_order(&xas, page->index, compound_order(page));
 129                nr = 1U << compound_order(page);
 130        }
 131
 132        VM_BUG_ON_PAGE(!PageLocked(page), page);
 133        VM_BUG_ON_PAGE(PageTail(page), page);
 134        VM_BUG_ON_PAGE(nr != 1 && shadow, page);
 135
 136        xas_store(&xas, shadow);
 137        xas_init_marks(&xas);
 138
 139        page->mapping = NULL;
 140        /* Leave page->index set: truncation lookup relies upon it */
 141
 142        if (shadow) {
 143                mapping->nrexceptional += nr;
 144                /*
 145                 * Make sure the nrexceptional update is committed before
 146                 * the nrpages update so that final truncate racing
 147                 * with reclaim does not see both counters 0 at the
 148                 * same time and miss a shadow entry.
 149                 */
 150                smp_wmb();
 151        }
 152        mapping->nrpages -= nr;
 153}
 154
 155static void unaccount_page_cache_page(struct address_space *mapping,
 156                                      struct page *page)
 157{
 158        int nr;
 159
 160        /*
 161         * if we're uptodate, flush out into the cleancache, otherwise
 162         * invalidate any existing cleancache entries.  We can't leave
 163         * stale data around in the cleancache once our page is gone
 164         */
 165        if (PageUptodate(page) && PageMappedToDisk(page))
 166                cleancache_put_page(page);
 167        else
 168                cleancache_invalidate_page(mapping, page);
 169
 170        VM_BUG_ON_PAGE(PageTail(page), page);
 171        VM_BUG_ON_PAGE(page_mapped(page), page);
 172        if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
 173                int mapcount;
 174
 175                pr_alert("BUG: Bad page cache in process %s  pfn:%05lx\n",
 176                         current->comm, page_to_pfn(page));
 177                dump_page(page, "still mapped when deleted");
 178                dump_stack();
 179                add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
 180
 181                mapcount = page_mapcount(page);
 182                if (mapping_exiting(mapping) &&
 183                    page_count(page) >= mapcount + 2) {
 184                        /*
 185                         * All vmas have already been torn down, so it's
 186                         * a good bet that actually the page is unmapped,
 187                         * and we'd prefer not to leak it: if we're wrong,
 188                         * some other bad page check should catch it later.
 189                         */
 190                        page_mapcount_reset(page);
 191                        page_ref_sub(page, mapcount);
 192                }
 193        }
 194
 195        /* hugetlb pages do not participate in page cache accounting. */
 196        if (PageHuge(page))
 197                return;
 198
 199        nr = hpage_nr_pages(page);
 200
 201        __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
 202        if (PageSwapBacked(page)) {
 203                __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
 204                if (PageTransHuge(page))
 205                        __dec_node_page_state(page, NR_SHMEM_THPS);
 206        } else {
 207                VM_BUG_ON_PAGE(PageTransHuge(page), page);
 208        }
 209
 210        /*
 211         * At this point page must be either written or cleaned by
 212         * truncate.  Dirty page here signals a bug and loss of
 213         * unwritten data.
 214         *
 215         * This fixes dirty accounting after removing the page entirely
 216         * but leaves PageDirty set: it has no effect for truncated
 217         * page and anyway will be cleared before returning page into
 218         * buddy allocator.
 219         */
 220        if (WARN_ON_ONCE(PageDirty(page)))
 221                account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
 222}
 223
 224/*
 225 * Delete a page from the page cache and free it. Caller has to make
 226 * sure the page is locked and that nobody else uses it - or that usage
 227 * is safe.  The caller must hold the i_pages lock.
 228 */
 229void __delete_from_page_cache(struct page *page, void *shadow)
 230{
 231        struct address_space *mapping = page->mapping;
 232
 233        trace_mm_filemap_delete_from_page_cache(page);
 234
 235        unaccount_page_cache_page(mapping, page);
 236        page_cache_delete(mapping, page, shadow);
 237}
 238
 239static void page_cache_free_page(struct address_space *mapping,
 240                                struct page *page)
 241{
 242        void (*freepage)(struct page *);
 243
 244        freepage = mapping->a_ops->freepage;
 245        if (freepage)
 246                freepage(page);
 247
 248        if (PageTransHuge(page) && !PageHuge(page)) {
 249                page_ref_sub(page, HPAGE_PMD_NR);
 250                VM_BUG_ON_PAGE(page_count(page) <= 0, page);
 251        } else {
 252                put_page(page);
 253        }
 254}
 255
 256/**
 257 * delete_from_page_cache - delete page from page cache
 258 * @page: the page which the kernel is trying to remove from page cache
 259 *
 260 * This must be called only on pages that have been verified to be in the page
 261 * cache and locked.  It will never put the page into the free list, the caller
 262 * has a reference on the page.
 263 */
 264void delete_from_page_cache(struct page *page)
 265{
 266        struct address_space *mapping = page_mapping(page);
 267        unsigned long flags;
 268
 269        BUG_ON(!PageLocked(page));
 270        xa_lock_irqsave(&mapping->i_pages, flags);
 271        __delete_from_page_cache(page, NULL);
 272        xa_unlock_irqrestore(&mapping->i_pages, flags);
 273
 274        page_cache_free_page(mapping, page);
 275}
 276EXPORT_SYMBOL(delete_from_page_cache);
 277
 278/*
 279 * page_cache_delete_batch - delete several pages from page cache
 280 * @mapping: the mapping to which pages belong
 281 * @pvec: pagevec with pages to delete
 282 *
 283 * The function walks over mapping->i_pages and removes pages passed in @pvec
 284 * from the mapping. The function expects @pvec to be sorted by page index.
 285 * It tolerates holes in @pvec (mapping entries at those indices are not
 286 * modified). The function expects only THP head pages to be present in the
 287 * @pvec and takes care to delete all corresponding tail pages from the
 288 * mapping as well.
 289 *
 290 * The function expects the i_pages lock to be held.
 291 */
 292static void page_cache_delete_batch(struct address_space *mapping,
 293                             struct pagevec *pvec)
 294{
 295        XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
 296        int total_pages = 0;
 297        int i = 0, tail_pages = 0;
 298        struct page *page;
 299
 300        mapping_set_update(&xas, mapping);
 301        xas_for_each(&xas, page, ULONG_MAX) {
 302                if (i >= pagevec_count(pvec) && !tail_pages)
 303                        break;
 304                if (xa_is_value(page))
 305                        continue;
 306                if (!tail_pages) {
 307                        /*
 308                         * Some page got inserted in our range? Skip it. We
 309                         * have our pages locked so they are protected from
 310                         * being removed.
 311                         */
 312                        if (page != pvec->pages[i]) {
 313                                VM_BUG_ON_PAGE(page->index >
 314                                                pvec->pages[i]->index, page);
 315                                continue;
 316                        }
 317                        WARN_ON_ONCE(!PageLocked(page));
 318                        if (PageTransHuge(page) && !PageHuge(page))
 319                                tail_pages = HPAGE_PMD_NR - 1;
 320                        page->mapping = NULL;
 321                        /*
 322                         * Leave page->index set: truncation lookup relies
 323                         * upon it
 324                         */
 325                        i++;
 326                } else {
 327                        VM_BUG_ON_PAGE(page->index + HPAGE_PMD_NR - tail_pages
 328                                        != pvec->pages[i]->index, page);
 329                        tail_pages--;
 330                }
 331                xas_store(&xas, NULL);
 332                total_pages++;
 333        }
 334        mapping->nrpages -= total_pages;
 335}
 336
 337void delete_from_page_cache_batch(struct address_space *mapping,
 338                                  struct pagevec *pvec)
 339{
 340        int i;
 341        unsigned long flags;
 342
 343        if (!pagevec_count(pvec))
 344                return;
 345
 346        xa_lock_irqsave(&mapping->i_pages, flags);
 347        for (i = 0; i < pagevec_count(pvec); i++) {
 348                trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
 349
 350                unaccount_page_cache_page(mapping, pvec->pages[i]);
 351        }
 352        page_cache_delete_batch(mapping, pvec);
 353        xa_unlock_irqrestore(&mapping->i_pages, flags);
 354
 355        for (i = 0; i < pagevec_count(pvec); i++)
 356                page_cache_free_page(mapping, pvec->pages[i]);
 357}
 358
 359int filemap_check_errors(struct address_space *mapping)
 360{
 361        int ret = 0;
 362        /* Check for outstanding write errors */
 363        if (test_bit(AS_ENOSPC, &mapping->flags) &&
 364            test_and_clear_bit(AS_ENOSPC, &mapping->flags))
 365                ret = -ENOSPC;
 366        if (test_bit(AS_EIO, &mapping->flags) &&
 367            test_and_clear_bit(AS_EIO, &mapping->flags))
 368                ret = -EIO;
 369        return ret;
 370}
 371EXPORT_SYMBOL(filemap_check_errors);
 372
 373static int filemap_check_and_keep_errors(struct address_space *mapping)
 374{
 375        /* Check for outstanding write errors */
 376        if (test_bit(AS_EIO, &mapping->flags))
 377                return -EIO;
 378        if (test_bit(AS_ENOSPC, &mapping->flags))
 379                return -ENOSPC;
 380        return 0;
 381}
 382
 383/**
 384 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
 385 * @mapping:    address space structure to write
 386 * @start:      offset in bytes where the range starts
 387 * @end:        offset in bytes where the range ends (inclusive)
 388 * @sync_mode:  enable synchronous operation
 389 *
 390 * Start writeback against all of a mapping's dirty pages that lie
 391 * within the byte offsets <start, end> inclusive.
 392 *
 393 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
 394 * opposed to a regular memory cleansing writeback.  The difference between
 395 * these two operations is that if a dirty page/buffer is encountered, it must
 396 * be waited upon, and not just skipped over.
 397 *
 398 * Return: %0 on success, negative error code otherwise.
 399 */
 400int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
 401                                loff_t end, int sync_mode)
 402{
 403        int ret;
 404        struct writeback_control wbc = {
 405                .sync_mode = sync_mode,
 406                .nr_to_write = LONG_MAX,
 407                .range_start = start,
 408                .range_end = end,
 409        };
 410
 411        if (!mapping_cap_writeback_dirty(mapping))
 412                return 0;
 413
 414        wbc_attach_fdatawrite_inode(&wbc, mapping->host);
 415        ret = do_writepages(mapping, &wbc);
 416        wbc_detach_inode(&wbc);
 417        return ret;
 418}
 419
 420static inline int __filemap_fdatawrite(struct address_space *mapping,
 421        int sync_mode)
 422{
 423        return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
 424}
 425
 426int filemap_fdatawrite(struct address_space *mapping)
 427{
 428        return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
 429}
 430EXPORT_SYMBOL(filemap_fdatawrite);
 431
 432int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
 433                                loff_t end)
 434{
 435        return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
 436}
 437EXPORT_SYMBOL(filemap_fdatawrite_range);
 438
 439/**
 440 * filemap_flush - mostly a non-blocking flush
 441 * @mapping:    target address_space
 442 *
 443 * This is a mostly non-blocking flush.  Not suitable for data-integrity
 444 * purposes - I/O may not be started against all dirty pages.
 445 *
 446 * Return: %0 on success, negative error code otherwise.
 447 */
 448int filemap_flush(struct address_space *mapping)
 449{
 450        return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
 451}
 452EXPORT_SYMBOL(filemap_flush);
 453
 454/**
 455 * filemap_range_has_page - check if a page exists in range.
 456 * @mapping:           address space within which to check
 457 * @start_byte:        offset in bytes where the range starts
 458 * @end_byte:          offset in bytes where the range ends (inclusive)
 459 *
 460 * Find at least one page in the range supplied, usually used to check if
 461 * direct writing in this range will trigger a writeback.
 462 *
 463 * Return: %true if at least one page exists in the specified range,
 464 * %false otherwise.
 465 */
 466bool filemap_range_has_page(struct address_space *mapping,
 467                           loff_t start_byte, loff_t end_byte)
 468{
 469        struct page *page;
 470        XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
 471        pgoff_t max = end_byte >> PAGE_SHIFT;
 472
 473        if (end_byte < start_byte)
 474                return false;
 475
 476        rcu_read_lock();
 477        for (;;) {
 478                page = xas_find(&xas, max);
 479                if (xas_retry(&xas, page))
 480                        continue;
 481                /* Shadow entries don't count */
 482                if (xa_is_value(page))
 483                        continue;
 484                /*
 485                 * We don't need to try to pin this page; we're about to
 486                 * release the RCU lock anyway.  It is enough to know that
 487                 * there was a page here recently.
 488                 */
 489                break;
 490        }
 491        rcu_read_unlock();
 492
 493        return page != NULL;
 494}
 495EXPORT_SYMBOL(filemap_range_has_page);
 496
 497static void __filemap_fdatawait_range(struct address_space *mapping,
 498                                     loff_t start_byte, loff_t end_byte)
 499{
 500        pgoff_t index = start_byte >> PAGE_SHIFT;
 501        pgoff_t end = end_byte >> PAGE_SHIFT;
 502        struct pagevec pvec;
 503        int nr_pages;
 504
 505        if (end_byte < start_byte)
 506                return;
 507
 508        pagevec_init(&pvec);
 509        while (index <= end) {
 510                unsigned i;
 511
 512                nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
 513                                end, PAGECACHE_TAG_WRITEBACK);
 514                if (!nr_pages)
 515                        break;
 516
 517                for (i = 0; i < nr_pages; i++) {
 518                        struct page *page = pvec.pages[i];
 519
 520                        wait_on_page_writeback(page);
 521                        ClearPageError(page);
 522                }
 523                pagevec_release(&pvec);
 524                cond_resched();
 525        }
 526}
 527
 528/**
 529 * filemap_fdatawait_range - wait for writeback to complete
 530 * @mapping:            address space structure to wait for
 531 * @start_byte:         offset in bytes where the range starts
 532 * @end_byte:           offset in bytes where the range ends (inclusive)
 533 *
 534 * Walk the list of under-writeback pages of the given address space
 535 * in the given range and wait for all of them.  Check error status of
 536 * the address space and return it.
 537 *
 538 * Since the error status of the address space is cleared by this function,
 539 * callers are responsible for checking the return value and handling and/or
 540 * reporting the error.
 541 *
 542 * Return: error status of the address space.
 543 */
 544int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
 545                            loff_t end_byte)
 546{
 547        __filemap_fdatawait_range(mapping, start_byte, end_byte);
 548        return filemap_check_errors(mapping);
 549}
 550EXPORT_SYMBOL(filemap_fdatawait_range);
 551
 552/**
 553 * file_fdatawait_range - wait for writeback to complete
 554 * @file:               file pointing to address space structure to wait for
 555 * @start_byte:         offset in bytes where the range starts
 556 * @end_byte:           offset in bytes where the range ends (inclusive)
 557 *
 558 * Walk the list of under-writeback pages of the address space that file
 559 * refers to, in the given range and wait for all of them.  Check error
 560 * status of the address space vs. the file->f_wb_err cursor and return it.
 561 *
 562 * Since the error status of the file is advanced by this function,
 563 * callers are responsible for checking the return value and handling and/or
 564 * reporting the error.
 565 *
 566 * Return: error status of the address space vs. the file->f_wb_err cursor.
 567 */
 568int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
 569{
 570        struct address_space *mapping = file->f_mapping;
 571
 572        __filemap_fdatawait_range(mapping, start_byte, end_byte);
 573        return file_check_and_advance_wb_err(file);
 574}
 575EXPORT_SYMBOL(file_fdatawait_range);
 576
 577/**
 578 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
 579 * @mapping: address space structure to wait for
 580 *
 581 * Walk the list of under-writeback pages of the given address space
 582 * and wait for all of them.  Unlike filemap_fdatawait(), this function
 583 * does not clear error status of the address space.
 584 *
 585 * Use this function if callers don't handle errors themselves.  Expected
 586 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
 587 * fsfreeze(8)
 588 *
 589 * Return: error status of the address space.
 590 */
 591int filemap_fdatawait_keep_errors(struct address_space *mapping)
 592{
 593        __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
 594        return filemap_check_and_keep_errors(mapping);
 595}
 596EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
 597
 598static bool mapping_needs_writeback(struct address_space *mapping)
 599{
 600        return (!dax_mapping(mapping) && mapping->nrpages) ||
 601            (dax_mapping(mapping) && mapping->nrexceptional);
 602}
 603
 604int filemap_write_and_wait(struct address_space *mapping)
 605{
 606        int err = 0;
 607
 608        if (mapping_needs_writeback(mapping)) {
 609                err = filemap_fdatawrite(mapping);
 610                /*
 611                 * Even if the above returned error, the pages may be
 612                 * written partially (e.g. -ENOSPC), so we wait for it.
 613                 * But the -EIO is special case, it may indicate the worst
 614                 * thing (e.g. bug) happened, so we avoid waiting for it.
 615                 */
 616                if (err != -EIO) {
 617                        int err2 = filemap_fdatawait(mapping);
 618                        if (!err)
 619                                err = err2;
 620                } else {
 621                        /* Clear any previously stored errors */
 622                        filemap_check_errors(mapping);
 623                }
 624        } else {
 625                err = filemap_check_errors(mapping);
 626        }
 627        return err;
 628}
 629EXPORT_SYMBOL(filemap_write_and_wait);
 630
 631/**
 632 * filemap_write_and_wait_range - write out & wait on a file range
 633 * @mapping:    the address_space for the pages
 634 * @lstart:     offset in bytes where the range starts
 635 * @lend:       offset in bytes where the range ends (inclusive)
 636 *
 637 * Write out and wait upon file offsets lstart->lend, inclusive.
 638 *
 639 * Note that @lend is inclusive (describes the last byte to be written) so
 640 * that this function can be used to write to the very end-of-file (end = -1).
 641 *
 642 * Return: error status of the address space.
 643 */
 644int filemap_write_and_wait_range(struct address_space *mapping,
 645                                 loff_t lstart, loff_t lend)
 646{
 647        int err = 0;
 648
 649        if (mapping_needs_writeback(mapping)) {
 650                err = __filemap_fdatawrite_range(mapping, lstart, lend,
 651                                                 WB_SYNC_ALL);
 652                /* See comment of filemap_write_and_wait() */
 653                if (err != -EIO) {
 654                        int err2 = filemap_fdatawait_range(mapping,
 655                                                lstart, lend);
 656                        if (!err)
 657                                err = err2;
 658                } else {
 659                        /* Clear any previously stored errors */
 660                        filemap_check_errors(mapping);
 661                }
 662        } else {
 663                err = filemap_check_errors(mapping);
 664        }
 665        return err;
 666}
 667EXPORT_SYMBOL(filemap_write_and_wait_range);
 668
 669void __filemap_set_wb_err(struct address_space *mapping, int err)
 670{
 671        errseq_t eseq = errseq_set(&mapping->wb_err, err);
 672
 673        trace_filemap_set_wb_err(mapping, eseq);
 674}
 675EXPORT_SYMBOL(__filemap_set_wb_err);
 676
 677/**
 678 * file_check_and_advance_wb_err - report wb error (if any) that was previously
 679 *                                 and advance wb_err to current one
 680 * @file: struct file on which the error is being reported
 681 *
 682 * When userland calls fsync (or something like nfsd does the equivalent), we
 683 * want to report any writeback errors that occurred since the last fsync (or
 684 * since the file was opened if there haven't been any).
 685 *
 686 * Grab the wb_err from the mapping. If it matches what we have in the file,
 687 * then just quickly return 0. The file is all caught up.
 688 *
 689 * If it doesn't match, then take the mapping value, set the "seen" flag in
 690 * it and try to swap it into place. If it works, or another task beat us
 691 * to it with the new value, then update the f_wb_err and return the error
 692 * portion. The error at this point must be reported via proper channels
 693 * (a'la fsync, or NFS COMMIT operation, etc.).
 694 *
 695 * While we handle mapping->wb_err with atomic operations, the f_wb_err
 696 * value is protected by the f_lock since we must ensure that it reflects
 697 * the latest value swapped in for this file descriptor.
 698 *
 699 * Return: %0 on success, negative error code otherwise.
 700 */
 701int file_check_and_advance_wb_err(struct file *file)
 702{
 703        int err = 0;
 704        errseq_t old = READ_ONCE(file->f_wb_err);
 705        struct address_space *mapping = file->f_mapping;
 706
 707        /* Locklessly handle the common case where nothing has changed */
 708        if (errseq_check(&mapping->wb_err, old)) {
 709                /* Something changed, must use slow path */
 710                spin_lock(&file->f_lock);
 711                old = file->f_wb_err;
 712                err = errseq_check_and_advance(&mapping->wb_err,
 713                                                &file->f_wb_err);
 714                trace_file_check_and_advance_wb_err(file, old);
 715                spin_unlock(&file->f_lock);
 716        }
 717
 718        /*
 719         * We're mostly using this function as a drop in replacement for
 720         * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
 721         * that the legacy code would have had on these flags.
 722         */
 723        clear_bit(AS_EIO, &mapping->flags);
 724        clear_bit(AS_ENOSPC, &mapping->flags);
 725        return err;
 726}
 727EXPORT_SYMBOL(file_check_and_advance_wb_err);
 728
 729/**
 730 * file_write_and_wait_range - write out & wait on a file range
 731 * @file:       file pointing to address_space with pages
 732 * @lstart:     offset in bytes where the range starts
 733 * @lend:       offset in bytes where the range ends (inclusive)
 734 *
 735 * Write out and wait upon file offsets lstart->lend, inclusive.
 736 *
 737 * Note that @lend is inclusive (describes the last byte to be written) so
 738 * that this function can be used to write to the very end-of-file (end = -1).
 739 *
 740 * After writing out and waiting on the data, we check and advance the
 741 * f_wb_err cursor to the latest value, and return any errors detected there.
 742 *
 743 * Return: %0 on success, negative error code otherwise.
 744 */
 745int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
 746{
 747        int err = 0, err2;
 748        struct address_space *mapping = file->f_mapping;
 749
 750        if (mapping_needs_writeback(mapping)) {
 751                err = __filemap_fdatawrite_range(mapping, lstart, lend,
 752                                                 WB_SYNC_ALL);
 753                /* See comment of filemap_write_and_wait() */
 754                if (err != -EIO)
 755                        __filemap_fdatawait_range(mapping, lstart, lend);
 756        }
 757        err2 = file_check_and_advance_wb_err(file);
 758        if (!err)
 759                err = err2;
 760        return err;
 761}
 762EXPORT_SYMBOL(file_write_and_wait_range);
 763
 764/**
 765 * replace_page_cache_page - replace a pagecache page with a new one
 766 * @old:        page to be replaced
 767 * @new:        page to replace with
 768 * @gfp_mask:   allocation mode
 769 *
 770 * This function replaces a page in the pagecache with a new one.  On
 771 * success it acquires the pagecache reference for the new page and
 772 * drops it for the old page.  Both the old and new pages must be
 773 * locked.  This function does not add the new page to the LRU, the
 774 * caller must do that.
 775 *
 776 * The remove + add is atomic.  This function cannot fail.
 777 *
 778 * Return: %0
 779 */
 780int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
 781{
 782        struct address_space *mapping = old->mapping;
 783        void (*freepage)(struct page *) = mapping->a_ops->freepage;
 784        pgoff_t offset = old->index;
 785        XA_STATE(xas, &mapping->i_pages, offset);
 786        unsigned long flags;
 787
 788        VM_BUG_ON_PAGE(!PageLocked(old), old);
 789        VM_BUG_ON_PAGE(!PageLocked(new), new);
 790        VM_BUG_ON_PAGE(new->mapping, new);
 791
 792        get_page(new);
 793        new->mapping = mapping;
 794        new->index = offset;
 795
 796        xas_lock_irqsave(&xas, flags);
 797        xas_store(&xas, new);
 798
 799        old->mapping = NULL;
 800        /* hugetlb pages do not participate in page cache accounting. */
 801        if (!PageHuge(old))
 802                __dec_node_page_state(new, NR_FILE_PAGES);
 803        if (!PageHuge(new))
 804                __inc_node_page_state(new, NR_FILE_PAGES);
 805        if (PageSwapBacked(old))
 806                __dec_node_page_state(new, NR_SHMEM);
 807        if (PageSwapBacked(new))
 808                __inc_node_page_state(new, NR_SHMEM);
 809        xas_unlock_irqrestore(&xas, flags);
 810        mem_cgroup_migrate(old, new);
 811        if (freepage)
 812                freepage(old);
 813        put_page(old);
 814
 815        return 0;
 816}
 817EXPORT_SYMBOL_GPL(replace_page_cache_page);
 818
 819static int __add_to_page_cache_locked(struct page *page,
 820                                      struct address_space *mapping,
 821                                      pgoff_t offset, gfp_t gfp_mask,
 822                                      void **shadowp)
 823{
 824        XA_STATE(xas, &mapping->i_pages, offset);
 825        int huge = PageHuge(page);
 826        struct mem_cgroup *memcg;
 827        int error;
 828        void *old;
 829
 830        VM_BUG_ON_PAGE(!PageLocked(page), page);
 831        VM_BUG_ON_PAGE(PageSwapBacked(page), page);
 832        mapping_set_update(&xas, mapping);
 833
 834        if (!huge) {
 835                error = mem_cgroup_try_charge(page, current->mm,
 836                                              gfp_mask, &memcg, false);
 837                if (error)
 838                        return error;
 839        }
 840
 841        get_page(page);
 842        page->mapping = mapping;
 843        page->index = offset;
 844
 845        do {
 846                xas_lock_irq(&xas);
 847                old = xas_load(&xas);
 848                if (old && !xa_is_value(old))
 849                        xas_set_err(&xas, -EEXIST);
 850                xas_store(&xas, page);
 851                if (xas_error(&xas))
 852                        goto unlock;
 853
 854                if (xa_is_value(old)) {
 855                        mapping->nrexceptional--;
 856                        if (shadowp)
 857                                *shadowp = old;
 858                }
 859                mapping->nrpages++;
 860
 861                /* hugetlb pages do not participate in page cache accounting */
 862                if (!huge)
 863                        __inc_node_page_state(page, NR_FILE_PAGES);
 864unlock:
 865                xas_unlock_irq(&xas);
 866        } while (xas_nomem(&xas, gfp_mask & GFP_RECLAIM_MASK));
 867
 868        if (xas_error(&xas))
 869                goto error;
 870
 871        if (!huge)
 872                mem_cgroup_commit_charge(page, memcg, false, false);
 873        trace_mm_filemap_add_to_page_cache(page);
 874        return 0;
 875error:
 876        page->mapping = NULL;
 877        /* Leave page->index set: truncation relies upon it */
 878        if (!huge)
 879                mem_cgroup_cancel_charge(page, memcg, false);
 880        put_page(page);
 881        return xas_error(&xas);
 882}
 883ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
 884
 885/**
 886 * add_to_page_cache_locked - add a locked page to the pagecache
 887 * @page:       page to add
 888 * @mapping:    the page's address_space
 889 * @offset:     page index
 890 * @gfp_mask:   page allocation mode
 891 *
 892 * This function is used to add a page to the pagecache. It must be locked.
 893 * This function does not add the page to the LRU.  The caller must do that.
 894 *
 895 * Return: %0 on success, negative error code otherwise.
 896 */
 897int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
 898                pgoff_t offset, gfp_t gfp_mask)
 899{
 900        return __add_to_page_cache_locked(page, mapping, offset,
 901                                          gfp_mask, NULL);
 902}
 903EXPORT_SYMBOL(add_to_page_cache_locked);
 904
 905int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
 906                                pgoff_t offset, gfp_t gfp_mask)
 907{
 908        void *shadow = NULL;
 909        int ret;
 910
 911        __SetPageLocked(page);
 912        ret = __add_to_page_cache_locked(page, mapping, offset,
 913                                         gfp_mask, &shadow);
 914        if (unlikely(ret))
 915                __ClearPageLocked(page);
 916        else {
 917                /*
 918                 * The page might have been evicted from cache only
 919                 * recently, in which case it should be activated like
 920                 * any other repeatedly accessed page.
 921                 * The exception is pages getting rewritten; evicting other
 922                 * data from the working set, only to cache data that will
 923                 * get overwritten with something else, is a waste of memory.
 924                 */
 925                WARN_ON_ONCE(PageActive(page));
 926                if (!(gfp_mask & __GFP_WRITE) && shadow)
 927                        workingset_refault(page, shadow);
 928                lru_cache_add(page);
 929        }
 930        return ret;
 931}
 932EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
 933
 934#ifdef CONFIG_NUMA
 935struct page *__page_cache_alloc(gfp_t gfp)
 936{
 937        int n;
 938        struct page *page;
 939
 940        if (cpuset_do_page_mem_spread()) {
 941                unsigned int cpuset_mems_cookie;
 942                do {
 943                        cpuset_mems_cookie = read_mems_allowed_begin();
 944                        n = cpuset_mem_spread_node();
 945                        page = __alloc_pages_node(n, gfp, 0);
 946                } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
 947
 948                return page;
 949        }
 950        return alloc_pages(gfp, 0);
 951}
 952EXPORT_SYMBOL(__page_cache_alloc);
 953#endif
 954
 955/*
 956 * In order to wait for pages to become available there must be
 957 * waitqueues associated with pages. By using a hash table of
 958 * waitqueues where the bucket discipline is to maintain all
 959 * waiters on the same queue and wake all when any of the pages
 960 * become available, and for the woken contexts to check to be
 961 * sure the appropriate page became available, this saves space
 962 * at a cost of "thundering herd" phenomena during rare hash
 963 * collisions.
 964 */
 965#define PAGE_WAIT_TABLE_BITS 8
 966#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
 967static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
 968
 969static wait_queue_head_t *page_waitqueue(struct page *page)
 970{
 971        return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
 972}
 973
 974void __init pagecache_init(void)
 975{
 976        int i;
 977
 978        for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
 979                init_waitqueue_head(&page_wait_table[i]);
 980
 981        page_writeback_init();
 982}
 983
 984/* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
 985struct wait_page_key {
 986        struct page *page;
 987        int bit_nr;
 988        int page_match;
 989};
 990
 991struct wait_page_queue {
 992        struct page *page;
 993        int bit_nr;
 994        wait_queue_entry_t wait;
 995};
 996
 997static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
 998{
 999        struct wait_page_key *key = arg;
1000        struct wait_page_queue *wait_page
1001                = container_of(wait, struct wait_page_queue, wait);
1002
1003        if (wait_page->page != key->page)
1004               return 0;
1005        key->page_match = 1;
1006
1007        if (wait_page->bit_nr != key->bit_nr)
1008                return 0;
1009
1010        /*
1011         * Stop walking if it's locked.
1012         * Is this safe if put_and_wait_on_page_locked() is in use?
1013         * Yes: the waker must hold a reference to this page, and if PG_locked
1014         * has now already been set by another task, that task must also hold
1015         * a reference to the *same usage* of this page; so there is no need
1016         * to walk on to wake even the put_and_wait_on_page_locked() callers.
1017         */
1018        if (test_bit(key->bit_nr, &key->page->flags))
1019                return -1;
1020
1021        return autoremove_wake_function(wait, mode, sync, key);
1022}
1023
1024static void wake_up_page_bit(struct page *page, int bit_nr)
1025{
1026        wait_queue_head_t *q = page_waitqueue(page);
1027        struct wait_page_key key;
1028        unsigned long flags;
1029        wait_queue_entry_t bookmark;
1030
1031        key.page = page;
1032        key.bit_nr = bit_nr;
1033        key.page_match = 0;
1034
1035        bookmark.flags = 0;
1036        bookmark.private = NULL;
1037        bookmark.func = NULL;
1038        INIT_LIST_HEAD(&bookmark.entry);
1039
1040        spin_lock_irqsave(&q->lock, flags);
1041        __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1042
1043        while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1044                /*
1045                 * Take a breather from holding the lock,
1046                 * allow pages that finish wake up asynchronously
1047                 * to acquire the lock and remove themselves
1048                 * from wait queue
1049                 */
1050                spin_unlock_irqrestore(&q->lock, flags);
1051                cpu_relax();
1052                spin_lock_irqsave(&q->lock, flags);
1053                __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1054        }
1055
1056        /*
1057         * It is possible for other pages to have collided on the waitqueue
1058         * hash, so in that case check for a page match. That prevents a long-
1059         * term waiter
1060         *
1061         * It is still possible to miss a case here, when we woke page waiters
1062         * and removed them from the waitqueue, but there are still other
1063         * page waiters.
1064         */
1065        if (!waitqueue_active(q) || !key.page_match) {
1066                ClearPageWaiters(page);
1067                /*
1068                 * It's possible to miss clearing Waiters here, when we woke
1069                 * our page waiters, but the hashed waitqueue has waiters for
1070                 * other pages on it.
1071                 *
1072                 * That's okay, it's a rare case. The next waker will clear it.
1073                 */
1074        }
1075        spin_unlock_irqrestore(&q->lock, flags);
1076}
1077
1078static void wake_up_page(struct page *page, int bit)
1079{
1080        if (!PageWaiters(page))
1081                return;
1082        wake_up_page_bit(page, bit);
1083}
1084
1085/*
1086 * A choice of three behaviors for wait_on_page_bit_common():
1087 */
1088enum behavior {
1089        EXCLUSIVE,      /* Hold ref to page and take the bit when woken, like
1090                         * __lock_page() waiting on then setting PG_locked.
1091                         */
1092        SHARED,         /* Hold ref to page and check the bit when woken, like
1093                         * wait_on_page_writeback() waiting on PG_writeback.
1094                         */
1095        DROP,           /* Drop ref to page before wait, no check when woken,
1096                         * like put_and_wait_on_page_locked() on PG_locked.
1097                         */
1098};
1099
1100static inline int wait_on_page_bit_common(wait_queue_head_t *q,
1101        struct page *page, int bit_nr, int state, enum behavior behavior)
1102{
1103        struct wait_page_queue wait_page;
1104        wait_queue_entry_t *wait = &wait_page.wait;
1105        bool bit_is_set;
1106        bool thrashing = false;
1107        bool delayacct = false;
1108        unsigned long pflags;
1109        int ret = 0;
1110
1111        if (bit_nr == PG_locked &&
1112            !PageUptodate(page) && PageWorkingset(page)) {
1113                if (!PageSwapBacked(page)) {
1114                        delayacct_thrashing_start();
1115                        delayacct = true;
1116                }
1117                psi_memstall_enter(&pflags);
1118                thrashing = true;
1119        }
1120
1121        init_wait(wait);
1122        wait->flags = behavior == EXCLUSIVE ? WQ_FLAG_EXCLUSIVE : 0;
1123        wait->func = wake_page_function;
1124        wait_page.page = page;
1125        wait_page.bit_nr = bit_nr;
1126
1127        for (;;) {
1128                spin_lock_irq(&q->lock);
1129
1130                if (likely(list_empty(&wait->entry))) {
1131                        __add_wait_queue_entry_tail(q, wait);
1132                        SetPageWaiters(page);
1133                }
1134
1135                set_current_state(state);
1136
1137                spin_unlock_irq(&q->lock);
1138
1139                bit_is_set = test_bit(bit_nr, &page->flags);
1140                if (behavior == DROP)
1141                        put_page(page);
1142
1143                if (likely(bit_is_set))
1144                        io_schedule();
1145
1146                if (behavior == EXCLUSIVE) {
1147                        if (!test_and_set_bit_lock(bit_nr, &page->flags))
1148                                break;
1149                } else if (behavior == SHARED) {
1150                        if (!test_bit(bit_nr, &page->flags))
1151                                break;
1152                }
1153
1154                if (signal_pending_state(state, current)) {
1155                        ret = -EINTR;
1156                        break;
1157                }
1158
1159                if (behavior == DROP) {
1160                        /*
1161                         * We can no longer safely access page->flags:
1162                         * even if CONFIG_MEMORY_HOTREMOVE is not enabled,
1163                         * there is a risk of waiting forever on a page reused
1164                         * for something that keeps it locked indefinitely.
1165                         * But best check for -EINTR above before breaking.
1166                         */
1167                        break;
1168                }
1169        }
1170
1171        finish_wait(q, wait);
1172
1173        if (thrashing) {
1174                if (delayacct)
1175                        delayacct_thrashing_end();
1176                psi_memstall_leave(&pflags);
1177        }
1178
1179        /*
1180         * A signal could leave PageWaiters set. Clearing it here if
1181         * !waitqueue_active would be possible (by open-coding finish_wait),
1182         * but still fail to catch it in the case of wait hash collision. We
1183         * already can fail to clear wait hash collision cases, so don't
1184         * bother with signals either.
1185         */
1186
1187        return ret;
1188}
1189
1190void wait_on_page_bit(struct page *page, int bit_nr)
1191{
1192        wait_queue_head_t *q = page_waitqueue(page);
1193        wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1194}
1195EXPORT_SYMBOL(wait_on_page_bit);
1196
1197int wait_on_page_bit_killable(struct page *page, int bit_nr)
1198{
1199        wait_queue_head_t *q = page_waitqueue(page);
1200        return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
1201}
1202EXPORT_SYMBOL(wait_on_page_bit_killable);
1203
1204/**
1205 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1206 * @page: The page to wait for.
1207 *
1208 * The caller should hold a reference on @page.  They expect the page to
1209 * become unlocked relatively soon, but do not wish to hold up migration
1210 * (for example) by holding the reference while waiting for the page to
1211 * come unlocked.  After this function returns, the caller should not
1212 * dereference @page.
1213 */
1214void put_and_wait_on_page_locked(struct page *page)
1215{
1216        wait_queue_head_t *q;
1217
1218        page = compound_head(page);
1219        q = page_waitqueue(page);
1220        wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1221}
1222
1223/**
1224 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1225 * @page: Page defining the wait queue of interest
1226 * @waiter: Waiter to add to the queue
1227 *
1228 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1229 */
1230void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1231{
1232        wait_queue_head_t *q = page_waitqueue(page);
1233        unsigned long flags;
1234
1235        spin_lock_irqsave(&q->lock, flags);
1236        __add_wait_queue_entry_tail(q, waiter);
1237        SetPageWaiters(page);
1238        spin_unlock_irqrestore(&q->lock, flags);
1239}
1240EXPORT_SYMBOL_GPL(add_page_wait_queue);
1241
1242#ifndef clear_bit_unlock_is_negative_byte
1243
1244/*
1245 * PG_waiters is the high bit in the same byte as PG_lock.
1246 *
1247 * On x86 (and on many other architectures), we can clear PG_lock and
1248 * test the sign bit at the same time. But if the architecture does
1249 * not support that special operation, we just do this all by hand
1250 * instead.
1251 *
1252 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1253 * being cleared, but a memory barrier should be unneccssary since it is
1254 * in the same byte as PG_locked.
1255 */
1256static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1257{
1258        clear_bit_unlock(nr, mem);
1259        /* smp_mb__after_atomic(); */
1260        return test_bit(PG_waiters, mem);
1261}
1262
1263#endif
1264
1265/**
1266 * unlock_page - unlock a locked page
1267 * @page: the page
1268 *
1269 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1270 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1271 * mechanism between PageLocked pages and PageWriteback pages is shared.
1272 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1273 *
1274 * Note that this depends on PG_waiters being the sign bit in the byte
1275 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1276 * clear the PG_locked bit and test PG_waiters at the same time fairly
1277 * portably (architectures that do LL/SC can test any bit, while x86 can
1278 * test the sign bit).
1279 */
1280void unlock_page(struct page *page)
1281{
1282        BUILD_BUG_ON(PG_waiters != 7);
1283        page = compound_head(page);
1284        VM_BUG_ON_PAGE(!PageLocked(page), page);
1285        if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1286                wake_up_page_bit(page, PG_locked);
1287}
1288EXPORT_SYMBOL(unlock_page);
1289
1290/**
1291 * end_page_writeback - end writeback against a page
1292 * @page: the page
1293 */
1294void end_page_writeback(struct page *page)
1295{
1296        /*
1297         * TestClearPageReclaim could be used here but it is an atomic
1298         * operation and overkill in this particular case. Failing to
1299         * shuffle a page marked for immediate reclaim is too mild to
1300         * justify taking an atomic operation penalty at the end of
1301         * ever page writeback.
1302         */
1303        if (PageReclaim(page)) {
1304                ClearPageReclaim(page);
1305                rotate_reclaimable_page(page);
1306        }
1307
1308        if (!test_clear_page_writeback(page))
1309                BUG();
1310
1311        smp_mb__after_atomic();
1312        wake_up_page(page, PG_writeback);
1313}
1314EXPORT_SYMBOL(end_page_writeback);
1315
1316/*
1317 * After completing I/O on a page, call this routine to update the page
1318 * flags appropriately
1319 */
1320void page_endio(struct page *page, bool is_write, int err)
1321{
1322        if (!is_write) {
1323                if (!err) {
1324                        SetPageUptodate(page);
1325                } else {
1326                        ClearPageUptodate(page);
1327                        SetPageError(page);
1328                }
1329                unlock_page(page);
1330        } else {
1331                if (err) {
1332                        struct address_space *mapping;
1333
1334                        SetPageError(page);
1335                        mapping = page_mapping(page);
1336                        if (mapping)
1337                                mapping_set_error(mapping, err);
1338                }
1339                end_page_writeback(page);
1340        }
1341}
1342EXPORT_SYMBOL_GPL(page_endio);
1343
1344/**
1345 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1346 * @__page: the page to lock
1347 */
1348void __lock_page(struct page *__page)
1349{
1350        struct page *page = compound_head(__page);
1351        wait_queue_head_t *q = page_waitqueue(page);
1352        wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1353                                EXCLUSIVE);
1354}
1355EXPORT_SYMBOL(__lock_page);
1356
1357int __lock_page_killable(struct page *__page)
1358{
1359        struct page *page = compound_head(__page);
1360        wait_queue_head_t *q = page_waitqueue(page);
1361        return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1362                                        EXCLUSIVE);
1363}
1364EXPORT_SYMBOL_GPL(__lock_page_killable);
1365
1366/*
1367 * Return values:
1368 * 1 - page is locked; mmap_sem is still held.
1369 * 0 - page is not locked.
1370 *     mmap_sem has been released (up_read()), unless flags had both
1371 *     FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1372 *     which case mmap_sem is still held.
1373 *
1374 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1375 * with the page locked and the mmap_sem unperturbed.
1376 */
1377int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1378                         unsigned int flags)
1379{
1380        if (flags & FAULT_FLAG_ALLOW_RETRY) {
1381                /*
1382                 * CAUTION! In this case, mmap_sem is not released
1383                 * even though return 0.
1384                 */
1385                if (flags & FAULT_FLAG_RETRY_NOWAIT)
1386                        return 0;
1387
1388                up_read(&mm->mmap_sem);
1389                if (flags & FAULT_FLAG_KILLABLE)
1390                        wait_on_page_locked_killable(page);
1391                else
1392                        wait_on_page_locked(page);
1393                return 0;
1394        } else {
1395                if (flags & FAULT_FLAG_KILLABLE) {
1396                        int ret;
1397
1398                        ret = __lock_page_killable(page);
1399                        if (ret) {
1400                                up_read(&mm->mmap_sem);
1401                                return 0;
1402                        }
1403                } else
1404                        __lock_page(page);
1405                return 1;
1406        }
1407}
1408
1409/**
1410 * page_cache_next_miss() - Find the next gap in the page cache.
1411 * @mapping: Mapping.
1412 * @index: Index.
1413 * @max_scan: Maximum range to search.
1414 *
1415 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1416 * gap with the lowest index.
1417 *
1418 * This function may be called under the rcu_read_lock.  However, this will
1419 * not atomically search a snapshot of the cache at a single point in time.
1420 * For example, if a gap is created at index 5, then subsequently a gap is
1421 * created at index 10, page_cache_next_miss covering both indices may
1422 * return 10 if called under the rcu_read_lock.
1423 *
1424 * Return: The index of the gap if found, otherwise an index outside the
1425 * range specified (in which case 'return - index >= max_scan' will be true).
1426 * In the rare case of index wrap-around, 0 will be returned.
1427 */
1428pgoff_t page_cache_next_miss(struct address_space *mapping,
1429                             pgoff_t index, unsigned long max_scan)
1430{
1431        XA_STATE(xas, &mapping->i_pages, index);
1432
1433        while (max_scan--) {
1434                void *entry = xas_next(&xas);
1435                if (!entry || xa_is_value(entry))
1436                        break;
1437                if (xas.xa_index == 0)
1438                        break;
1439        }
1440
1441        return xas.xa_index;
1442}
1443EXPORT_SYMBOL(page_cache_next_miss);
1444
1445/**
1446 * page_cache_prev_miss() - Find the previous gap in the page cache.
1447 * @mapping: Mapping.
1448 * @index: Index.
1449 * @max_scan: Maximum range to search.
1450 *
1451 * Search the range [max(index - max_scan + 1, 0), index] for the
1452 * gap with the highest index.
1453 *
1454 * This function may be called under the rcu_read_lock.  However, this will
1455 * not atomically search a snapshot of the cache at a single point in time.
1456 * For example, if a gap is created at index 10, then subsequently a gap is
1457 * created at index 5, page_cache_prev_miss() covering both indices may
1458 * return 5 if called under the rcu_read_lock.
1459 *
1460 * Return: The index of the gap if found, otherwise an index outside the
1461 * range specified (in which case 'index - return >= max_scan' will be true).
1462 * In the rare case of wrap-around, ULONG_MAX will be returned.
1463 */
1464pgoff_t page_cache_prev_miss(struct address_space *mapping,
1465                             pgoff_t index, unsigned long max_scan)
1466{
1467        XA_STATE(xas, &mapping->i_pages, index);
1468
1469        while (max_scan--) {
1470                void *entry = xas_prev(&xas);
1471                if (!entry || xa_is_value(entry))
1472                        break;
1473                if (xas.xa_index == ULONG_MAX)
1474                        break;
1475        }
1476
1477        return xas.xa_index;
1478}
1479EXPORT_SYMBOL(page_cache_prev_miss);
1480
1481/**
1482 * find_get_entry - find and get a page cache entry
1483 * @mapping: the address_space to search
1484 * @offset: the page cache index
1485 *
1486 * Looks up the page cache slot at @mapping & @offset.  If there is a
1487 * page cache page, it is returned with an increased refcount.
1488 *
1489 * If the slot holds a shadow entry of a previously evicted page, or a
1490 * swap entry from shmem/tmpfs, it is returned.
1491 *
1492 * Return: the found page or shadow entry, %NULL if nothing is found.
1493 */
1494struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1495{
1496        XA_STATE(xas, &mapping->i_pages, offset);
1497        struct page *head, *page;
1498
1499        rcu_read_lock();
1500repeat:
1501        xas_reset(&xas);
1502        page = xas_load(&xas);
1503        if (xas_retry(&xas, page))
1504                goto repeat;
1505        /*
1506         * A shadow entry of a recently evicted page, or a swap entry from
1507         * shmem/tmpfs.  Return it without attempting to raise page count.
1508         */
1509        if (!page || xa_is_value(page))
1510                goto out;
1511
1512        head = compound_head(page);
1513        if (!page_cache_get_speculative(head))
1514                goto repeat;
1515
1516        /* The page was split under us? */
1517        if (compound_head(page) != head) {
1518                put_page(head);
1519                goto repeat;
1520        }
1521
1522        /*
1523         * Has the page moved?
1524         * This is part of the lockless pagecache protocol. See
1525         * include/linux/pagemap.h for details.
1526         */
1527        if (unlikely(page != xas_reload(&xas))) {
1528                put_page(head);
1529                goto repeat;
1530        }
1531out:
1532        rcu_read_unlock();
1533
1534        return page;
1535}
1536EXPORT_SYMBOL(find_get_entry);
1537
1538/**
1539 * find_lock_entry - locate, pin and lock a page cache entry
1540 * @mapping: the address_space to search
1541 * @offset: the page cache index
1542 *
1543 * Looks up the page cache slot at @mapping & @offset.  If there is a
1544 * page cache page, it is returned locked and with an increased
1545 * refcount.
1546 *
1547 * If the slot holds a shadow entry of a previously evicted page, or a
1548 * swap entry from shmem/tmpfs, it is returned.
1549 *
1550 * find_lock_entry() may sleep.
1551 *
1552 * Return: the found page or shadow entry, %NULL if nothing is found.
1553 */
1554struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1555{
1556        struct page *page;
1557
1558repeat:
1559        page = find_get_entry(mapping, offset);
1560        if (page && !xa_is_value(page)) {
1561                lock_page(page);
1562                /* Has the page been truncated? */
1563                if (unlikely(page_mapping(page) != mapping)) {
1564                        unlock_page(page);
1565                        put_page(page);
1566                        goto repeat;
1567                }
1568                VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1569        }
1570        return page;
1571}
1572EXPORT_SYMBOL(find_lock_entry);
1573
1574/**
1575 * pagecache_get_page - find and get a page reference
1576 * @mapping: the address_space to search
1577 * @offset: the page index
1578 * @fgp_flags: PCG flags
1579 * @gfp_mask: gfp mask to use for the page cache data page allocation
1580 *
1581 * Looks up the page cache slot at @mapping & @offset.
1582 *
1583 * PCG flags modify how the page is returned.
1584 *
1585 * @fgp_flags can be:
1586 *
1587 * - FGP_ACCESSED: the page will be marked accessed
1588 * - FGP_LOCK: Page is return locked
1589 * - FGP_CREAT: If page is not present then a new page is allocated using
1590 *   @gfp_mask and added to the page cache and the VM's LRU
1591 *   list. The page is returned locked and with an increased
1592 *   refcount.
1593 * - FGP_FOR_MMAP: Similar to FGP_CREAT, only we want to allow the caller to do
1594 *   its own locking dance if the page is already in cache, or unlock the page
1595 *   before returning if we had to add the page to pagecache.
1596 *
1597 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1598 * if the GFP flags specified for FGP_CREAT are atomic.
1599 *
1600 * If there is a page cache page, it is returned with an increased refcount.
1601 *
1602 * Return: the found page or %NULL otherwise.
1603 */
1604struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1605        int fgp_flags, gfp_t gfp_mask)
1606{
1607        struct page *page;
1608
1609repeat:
1610        page = find_get_entry(mapping, offset);
1611        if (xa_is_value(page))
1612                page = NULL;
1613        if (!page)
1614                goto no_page;
1615
1616        if (fgp_flags & FGP_LOCK) {
1617                if (fgp_flags & FGP_NOWAIT) {
1618                        if (!trylock_page(page)) {
1619                                put_page(page);
1620                                return NULL;
1621                        }
1622                } else {
1623                        lock_page(page);
1624                }
1625
1626                /* Has the page been truncated? */
1627                if (unlikely(page->mapping != mapping)) {
1628                        unlock_page(page);
1629                        put_page(page);
1630                        goto repeat;
1631                }
1632                VM_BUG_ON_PAGE(page->index != offset, page);
1633        }
1634
1635        if (fgp_flags & FGP_ACCESSED)
1636                mark_page_accessed(page);
1637
1638no_page:
1639        if (!page && (fgp_flags & FGP_CREAT)) {
1640                int err;
1641                if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1642                        gfp_mask |= __GFP_WRITE;
1643                if (fgp_flags & FGP_NOFS)
1644                        gfp_mask &= ~__GFP_FS;
1645
1646                page = __page_cache_alloc(gfp_mask);
1647                if (!page)
1648                        return NULL;
1649
1650                if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1651                        fgp_flags |= FGP_LOCK;
1652
1653                /* Init accessed so avoid atomic mark_page_accessed later */
1654                if (fgp_flags & FGP_ACCESSED)
1655                        __SetPageReferenced(page);
1656
1657                err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1658                if (unlikely(err)) {
1659                        put_page(page);
1660                        page = NULL;
1661                        if (err == -EEXIST)
1662                                goto repeat;
1663                }
1664
1665                /*
1666                 * add_to_page_cache_lru locks the page, and for mmap we expect
1667                 * an unlocked page.
1668                 */
1669                if (page && (fgp_flags & FGP_FOR_MMAP))
1670                        unlock_page(page);
1671        }
1672
1673        return page;
1674}
1675EXPORT_SYMBOL(pagecache_get_page);
1676
1677/**
1678 * find_get_entries - gang pagecache lookup
1679 * @mapping:    The address_space to search
1680 * @start:      The starting page cache index
1681 * @nr_entries: The maximum number of entries
1682 * @entries:    Where the resulting entries are placed
1683 * @indices:    The cache indices corresponding to the entries in @entries
1684 *
1685 * find_get_entries() will search for and return a group of up to
1686 * @nr_entries entries in the mapping.  The entries are placed at
1687 * @entries.  find_get_entries() takes a reference against any actual
1688 * pages it returns.
1689 *
1690 * The search returns a group of mapping-contiguous page cache entries
1691 * with ascending indexes.  There may be holes in the indices due to
1692 * not-present pages.
1693 *
1694 * Any shadow entries of evicted pages, or swap entries from
1695 * shmem/tmpfs, are included in the returned array.
1696 *
1697 * Return: the number of pages and shadow entries which were found.
1698 */
1699unsigned find_get_entries(struct address_space *mapping,
1700                          pgoff_t start, unsigned int nr_entries,
1701                          struct page **entries, pgoff_t *indices)
1702{
1703        XA_STATE(xas, &mapping->i_pages, start);
1704        struct page *page;
1705        unsigned int ret = 0;
1706
1707        if (!nr_entries)
1708                return 0;
1709
1710        rcu_read_lock();
1711        xas_for_each(&xas, page, ULONG_MAX) {
1712                struct page *head;
1713                if (xas_retry(&xas, page))
1714                        continue;
1715                /*
1716                 * A shadow entry of a recently evicted page, a swap
1717                 * entry from shmem/tmpfs or a DAX entry.  Return it
1718                 * without attempting to raise page count.
1719                 */
1720                if (xa_is_value(page))
1721                        goto export;
1722
1723                head = compound_head(page);
1724                if (!page_cache_get_speculative(head))
1725                        goto retry;
1726
1727                /* The page was split under us? */
1728                if (compound_head(page) != head)
1729                        goto put_page;
1730
1731                /* Has the page moved? */
1732                if (unlikely(page != xas_reload(&xas)))
1733                        goto put_page;
1734
1735export:
1736                indices[ret] = xas.xa_index;
1737                entries[ret] = page;
1738                if (++ret == nr_entries)
1739                        break;
1740                continue;
1741put_page:
1742                put_page(head);
1743retry:
1744                xas_reset(&xas);
1745        }
1746        rcu_read_unlock();
1747        return ret;
1748}
1749
1750/**
1751 * find_get_pages_range - gang pagecache lookup
1752 * @mapping:    The address_space to search
1753 * @start:      The starting page index
1754 * @end:        The final page index (inclusive)
1755 * @nr_pages:   The maximum number of pages
1756 * @pages:      Where the resulting pages are placed
1757 *
1758 * find_get_pages_range() will search for and return a group of up to @nr_pages
1759 * pages in the mapping starting at index @start and up to index @end
1760 * (inclusive).  The pages are placed at @pages.  find_get_pages_range() takes
1761 * a reference against the returned pages.
1762 *
1763 * The search returns a group of mapping-contiguous pages with ascending
1764 * indexes.  There may be holes in the indices due to not-present pages.
1765 * We also update @start to index the next page for the traversal.
1766 *
1767 * Return: the number of pages which were found. If this number is
1768 * smaller than @nr_pages, the end of specified range has been
1769 * reached.
1770 */
1771unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1772                              pgoff_t end, unsigned int nr_pages,
1773                              struct page **pages)
1774{
1775        XA_STATE(xas, &mapping->i_pages, *start);
1776        struct page *page;
1777        unsigned ret = 0;
1778
1779        if (unlikely(!nr_pages))
1780                return 0;
1781
1782        rcu_read_lock();
1783        xas_for_each(&xas, page, end) {
1784                struct page *head;
1785                if (xas_retry(&xas, page))
1786                        continue;
1787                /* Skip over shadow, swap and DAX entries */
1788                if (xa_is_value(page))
1789                        continue;
1790
1791                head = compound_head(page);
1792                if (!page_cache_get_speculative(head))
1793                        goto retry;
1794
1795                /* The page was split under us? */
1796                if (compound_head(page) != head)
1797                        goto put_page;
1798
1799                /* Has the page moved? */
1800                if (unlikely(page != xas_reload(&xas)))
1801                        goto put_page;
1802
1803                pages[ret] = page;
1804                if (++ret == nr_pages) {
1805                        *start = xas.xa_index + 1;
1806                        goto out;
1807                }
1808                continue;
1809put_page:
1810                put_page(head);
1811retry:
1812                xas_reset(&xas);
1813        }
1814
1815        /*
1816         * We come here when there is no page beyond @end. We take care to not
1817         * overflow the index @start as it confuses some of the callers. This
1818         * breaks the iteration when there is a page at index -1 but that is
1819         * already broken anyway.
1820         */
1821        if (end == (pgoff_t)-1)
1822                *start = (pgoff_t)-1;
1823        else
1824                *start = end + 1;
1825out:
1826        rcu_read_unlock();
1827
1828        return ret;
1829}
1830
1831/**
1832 * find_get_pages_contig - gang contiguous pagecache lookup
1833 * @mapping:    The address_space to search
1834 * @index:      The starting page index
1835 * @nr_pages:   The maximum number of pages
1836 * @pages:      Where the resulting pages are placed
1837 *
1838 * find_get_pages_contig() works exactly like find_get_pages(), except
1839 * that the returned number of pages are guaranteed to be contiguous.
1840 *
1841 * Return: the number of pages which were found.
1842 */
1843unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1844                               unsigned int nr_pages, struct page **pages)
1845{
1846        XA_STATE(xas, &mapping->i_pages, index);
1847        struct page *page;
1848        unsigned int ret = 0;
1849
1850        if (unlikely(!nr_pages))
1851                return 0;
1852
1853        rcu_read_lock();
1854        for (page = xas_load(&xas); page; page = xas_next(&xas)) {
1855                struct page *head;
1856                if (xas_retry(&xas, page))
1857                        continue;
1858                /*
1859                 * If the entry has been swapped out, we can stop looking.
1860                 * No current caller is looking for DAX entries.
1861                 */
1862                if (xa_is_value(page))
1863                        break;
1864
1865                head = compound_head(page);
1866                if (!page_cache_get_speculative(head))
1867                        goto retry;
1868
1869                /* The page was split under us? */
1870                if (compound_head(page) != head)
1871                        goto put_page;
1872
1873                /* Has the page moved? */
1874                if (unlikely(page != xas_reload(&xas)))
1875                        goto put_page;
1876
1877                pages[ret] = page;
1878                if (++ret == nr_pages)
1879                        break;
1880                continue;
1881put_page:
1882                put_page(head);
1883retry:
1884                xas_reset(&xas);
1885        }
1886        rcu_read_unlock();
1887        return ret;
1888}
1889EXPORT_SYMBOL(find_get_pages_contig);
1890
1891/**
1892 * find_get_pages_range_tag - find and return pages in given range matching @tag
1893 * @mapping:    the address_space to search
1894 * @index:      the starting page index
1895 * @end:        The final page index (inclusive)
1896 * @tag:        the tag index
1897 * @nr_pages:   the maximum number of pages
1898 * @pages:      where the resulting pages are placed
1899 *
1900 * Like find_get_pages, except we only return pages which are tagged with
1901 * @tag.   We update @index to index the next page for the traversal.
1902 *
1903 * Return: the number of pages which were found.
1904 */
1905unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
1906                        pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
1907                        struct page **pages)
1908{
1909        XA_STATE(xas, &mapping->i_pages, *index);
1910        struct page *page;
1911        unsigned ret = 0;
1912
1913        if (unlikely(!nr_pages))
1914                return 0;
1915
1916        rcu_read_lock();
1917        xas_for_each_marked(&xas, page, end, tag) {
1918                struct page *head;
1919                if (xas_retry(&xas, page))
1920                        continue;
1921                /*
1922                 * Shadow entries should never be tagged, but this iteration
1923                 * is lockless so there is a window for page reclaim to evict
1924                 * a page we saw tagged.  Skip over it.
1925                 */
1926                if (xa_is_value(page))
1927                        continue;
1928
1929                head = compound_head(page);
1930                if (!page_cache_get_speculative(head))
1931                        goto retry;
1932
1933                /* The page was split under us? */
1934                if (compound_head(page) != head)
1935                        goto put_page;
1936
1937                /* Has the page moved? */
1938                if (unlikely(page != xas_reload(&xas)))
1939                        goto put_page;
1940
1941                pages[ret] = page;
1942                if (++ret == nr_pages) {
1943                        *index = xas.xa_index + 1;
1944                        goto out;
1945                }
1946                continue;
1947put_page:
1948                put_page(head);
1949retry:
1950                xas_reset(&xas);
1951        }
1952
1953        /*
1954         * We come here when we got to @end. We take care to not overflow the
1955         * index @index as it confuses some of the callers. This breaks the
1956         * iteration when there is a page at index -1 but that is already
1957         * broken anyway.
1958         */
1959        if (end == (pgoff_t)-1)
1960                *index = (pgoff_t)-1;
1961        else
1962                *index = end + 1;
1963out:
1964        rcu_read_unlock();
1965
1966        return ret;
1967}
1968EXPORT_SYMBOL(find_get_pages_range_tag);
1969
1970/*
1971 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1972 * a _large_ part of the i/o request. Imagine the worst scenario:
1973 *
1974 *      ---R__________________________________________B__________
1975 *         ^ reading here                             ^ bad block(assume 4k)
1976 *
1977 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1978 * => failing the whole request => read(R) => read(R+1) =>
1979 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1980 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1981 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1982 *
1983 * It is going insane. Fix it by quickly scaling down the readahead size.
1984 */
1985static void shrink_readahead_size_eio(struct file *filp,
1986                                        struct file_ra_state *ra)
1987{
1988        ra->ra_pages /= 4;
1989}
1990
1991/**
1992 * generic_file_buffered_read - generic file read routine
1993 * @iocb:       the iocb to read
1994 * @iter:       data destination
1995 * @written:    already copied
1996 *
1997 * This is a generic file read routine, and uses the
1998 * mapping->a_ops->readpage() function for the actual low-level stuff.
1999 *
2000 * This is really ugly. But the goto's actually try to clarify some
2001 * of the logic when it comes to error handling etc.
2002 *
2003 * Return:
2004 * * total number of bytes copied, including those the were already @written
2005 * * negative error code if nothing was copied
2006 */
2007static ssize_t generic_file_buffered_read(struct kiocb *iocb,
2008                struct iov_iter *iter, ssize_t written)
2009{
2010        struct file *filp = iocb->ki_filp;
2011        struct address_space *mapping = filp->f_mapping;
2012        struct inode *inode = mapping->host;
2013        struct file_ra_state *ra = &filp->f_ra;
2014        loff_t *ppos = &iocb->ki_pos;
2015        pgoff_t index;
2016        pgoff_t last_index;
2017        pgoff_t prev_index;
2018        unsigned long offset;      /* offset into pagecache page */
2019        unsigned int prev_offset;
2020        int error = 0;
2021
2022        if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
2023                return 0;
2024        iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2025
2026        index = *ppos >> PAGE_SHIFT;
2027        prev_index = ra->prev_pos >> PAGE_SHIFT;
2028        prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2029        last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2030        offset = *ppos & ~PAGE_MASK;
2031
2032        for (;;) {
2033                struct page *page;
2034                pgoff_t end_index;
2035                loff_t isize;
2036                unsigned long nr, ret;
2037
2038                cond_resched();
2039find_page:
2040                if (fatal_signal_pending(current)) {
2041                        error = -EINTR;
2042                        goto out;
2043                }
2044
2045                page = find_get_page(mapping, index);
2046                if (!page) {
2047                        if (iocb->ki_flags & IOCB_NOWAIT)
2048                                goto would_block;
2049                        page_cache_sync_readahead(mapping,
2050                                        ra, filp,
2051                                        index, last_index - index);
2052                        page = find_get_page(mapping, index);
2053                        if (unlikely(page == NULL))
2054                                goto no_cached_page;
2055                }
2056                if (PageReadahead(page)) {
2057                        page_cache_async_readahead(mapping,
2058                                        ra, filp, page,
2059                                        index, last_index - index);
2060                }
2061                if (!PageUptodate(page)) {
2062                        if (iocb->ki_flags & IOCB_NOWAIT) {
2063                                put_page(page);
2064                                goto would_block;
2065                        }
2066
2067                        /*
2068                         * See comment in do_read_cache_page on why
2069                         * wait_on_page_locked is used to avoid unnecessarily
2070                         * serialisations and why it's safe.
2071                         */
2072                        error = wait_on_page_locked_killable(page);
2073                        if (unlikely(error))
2074                                goto readpage_error;
2075                        if (PageUptodate(page))
2076                                goto page_ok;
2077
2078                        if (inode->i_blkbits == PAGE_SHIFT ||
2079                                        !mapping->a_ops->is_partially_uptodate)
2080                                goto page_not_up_to_date;
2081                        /* pipes can't handle partially uptodate pages */
2082                        if (unlikely(iov_iter_is_pipe(iter)))
2083                                goto page_not_up_to_date;
2084                        if (!trylock_page(page))
2085                                goto page_not_up_to_date;
2086                        /* Did it get truncated before we got the lock? */
2087                        if (!page->mapping)
2088                                goto page_not_up_to_date_locked;
2089                        if (!mapping->a_ops->is_partially_uptodate(page,
2090                                                        offset, iter->count))
2091                                goto page_not_up_to_date_locked;
2092                        unlock_page(page);
2093                }
2094page_ok:
2095                /*
2096                 * i_size must be checked after we know the page is Uptodate.
2097                 *
2098                 * Checking i_size after the check allows us to calculate
2099                 * the correct value for "nr", which means the zero-filled
2100                 * part of the page is not copied back to userspace (unless
2101                 * another truncate extends the file - this is desired though).
2102                 */
2103
2104                isize = i_size_read(inode);
2105                end_index = (isize - 1) >> PAGE_SHIFT;
2106                if (unlikely(!isize || index > end_index)) {
2107                        put_page(page);
2108                        goto out;
2109                }
2110
2111                /* nr is the maximum number of bytes to copy from this page */
2112                nr = PAGE_SIZE;
2113                if (index == end_index) {
2114                        nr = ((isize - 1) & ~PAGE_MASK) + 1;
2115                        if (nr <= offset) {
2116                                put_page(page);
2117                                goto out;
2118                        }
2119                }
2120                nr = nr - offset;
2121
2122                /* If users can be writing to this page using arbitrary
2123                 * virtual addresses, take care about potential aliasing
2124                 * before reading the page on the kernel side.
2125                 */
2126                if (mapping_writably_mapped(mapping))
2127                        flush_dcache_page(page);
2128
2129                /*
2130                 * When a sequential read accesses a page several times,
2131                 * only mark it as accessed the first time.
2132                 */
2133                if (prev_index != index || offset != prev_offset)
2134                        mark_page_accessed(page);
2135                prev_index = index;
2136
2137                /*
2138                 * Ok, we have the page, and it's up-to-date, so
2139                 * now we can copy it to user space...
2140                 */
2141
2142                ret = copy_page_to_iter(page, offset, nr, iter);
2143                offset += ret;
2144                index += offset >> PAGE_SHIFT;
2145                offset &= ~PAGE_MASK;
2146                prev_offset = offset;
2147
2148                put_page(page);
2149                written += ret;
2150                if (!iov_iter_count(iter))
2151                        goto out;
2152                if (ret < nr) {
2153                        error = -EFAULT;
2154                        goto out;
2155                }
2156                continue;
2157
2158page_not_up_to_date:
2159                /* Get exclusive access to the page ... */
2160                error = lock_page_killable(page);
2161                if (unlikely(error))
2162                        goto readpage_error;
2163
2164page_not_up_to_date_locked:
2165                /* Did it get truncated before we got the lock? */
2166                if (!page->mapping) {
2167                        unlock_page(page);
2168                        put_page(page);
2169                        continue;
2170                }
2171
2172                /* Did somebody else fill it already? */
2173                if (PageUptodate(page)) {
2174                        unlock_page(page);
2175                        goto page_ok;
2176                }
2177
2178readpage:
2179                /*
2180                 * A previous I/O error may have been due to temporary
2181                 * failures, eg. multipath errors.
2182                 * PG_error will be set again if readpage fails.
2183                 */
2184                ClearPageError(page);
2185                /* Start the actual read. The read will unlock the page. */
2186                error = mapping->a_ops->readpage(filp, page);
2187
2188                if (unlikely(error)) {
2189                        if (error == AOP_TRUNCATED_PAGE) {
2190                                put_page(page);
2191                                error = 0;
2192                                goto find_page;
2193                        }
2194                        goto readpage_error;
2195                }
2196
2197                if (!PageUptodate(page)) {
2198                        error = lock_page_killable(page);
2199                        if (unlikely(error))
2200                                goto readpage_error;
2201                        if (!PageUptodate(page)) {
2202                                if (page->mapping == NULL) {
2203                                        /*
2204                                         * invalidate_mapping_pages got it
2205                                         */
2206                                        unlock_page(page);
2207                                        put_page(page);
2208                                        goto find_page;
2209                                }
2210                                unlock_page(page);
2211                                shrink_readahead_size_eio(filp, ra);
2212                                error = -EIO;
2213                                goto readpage_error;
2214                        }
2215                        unlock_page(page);
2216                }
2217
2218                goto page_ok;
2219
2220readpage_error:
2221                /* UHHUH! A synchronous read error occurred. Report it */
2222                put_page(page);
2223                goto out;
2224
2225no_cached_page:
2226                /*
2227                 * Ok, it wasn't cached, so we need to create a new
2228                 * page..
2229                 */
2230                page = page_cache_alloc(mapping);
2231                if (!page) {
2232                        error = -ENOMEM;
2233                        goto out;
2234                }
2235                error = add_to_page_cache_lru(page, mapping, index,
2236                                mapping_gfp_constraint(mapping, GFP_KERNEL));
2237                if (error) {
2238                        put_page(page);
2239                        if (error == -EEXIST) {
2240                                error = 0;
2241                                goto find_page;
2242                        }
2243                        goto out;
2244                }
2245                goto readpage;
2246        }
2247
2248would_block:
2249        error = -EAGAIN;
2250out:
2251        ra->prev_pos = prev_index;
2252        ra->prev_pos <<= PAGE_SHIFT;
2253        ra->prev_pos |= prev_offset;
2254
2255        *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2256        file_accessed(filp);
2257        return written ? written : error;
2258}
2259
2260/**
2261 * generic_file_read_iter - generic filesystem read routine
2262 * @iocb:       kernel I/O control block
2263 * @iter:       destination for the data read
2264 *
2265 * This is the "read_iter()" routine for all filesystems
2266 * that can use the page cache directly.
2267 * Return:
2268 * * number of bytes copied, even for partial reads
2269 * * negative error code if nothing was read
2270 */
2271ssize_t
2272generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2273{
2274        size_t count = iov_iter_count(iter);
2275        ssize_t retval = 0;
2276
2277        if (!count)
2278                goto out; /* skip atime */
2279
2280        if (iocb->ki_flags & IOCB_DIRECT) {
2281                struct file *file = iocb->ki_filp;
2282                struct address_space *mapping = file->f_mapping;
2283                struct inode *inode = mapping->host;
2284                loff_t size;
2285
2286                size = i_size_read(inode);
2287                if (iocb->ki_flags & IOCB_NOWAIT) {
2288                        if (filemap_range_has_page(mapping, iocb->ki_pos,
2289                                                   iocb->ki_pos + count - 1))
2290                                return -EAGAIN;
2291                } else {
2292                        retval = filemap_write_and_wait_range(mapping,
2293                                                iocb->ki_pos,
2294                                                iocb->ki_pos + count - 1);
2295                        if (retval < 0)
2296                                goto out;
2297                }
2298
2299                file_accessed(file);
2300
2301                retval = mapping->a_ops->direct_IO(iocb, iter);
2302                if (retval >= 0) {
2303                        iocb->ki_pos += retval;
2304                        count -= retval;
2305                }
2306                iov_iter_revert(iter, count - iov_iter_count(iter));
2307
2308                /*
2309                 * Btrfs can have a short DIO read if we encounter
2310                 * compressed extents, so if there was an error, or if
2311                 * we've already read everything we wanted to, or if
2312                 * there was a short read because we hit EOF, go ahead
2313                 * and return.  Otherwise fallthrough to buffered io for
2314                 * the rest of the read.  Buffered reads will not work for
2315                 * DAX files, so don't bother trying.
2316                 */
2317                if (retval < 0 || !count || iocb->ki_pos >= size ||
2318                    IS_DAX(inode))
2319                        goto out;
2320        }
2321
2322        retval = generic_file_buffered_read(iocb, iter, retval);
2323out:
2324        return retval;
2325}
2326EXPORT_SYMBOL(generic_file_read_iter);
2327
2328#ifdef CONFIG_MMU
2329#define MMAP_LOTSAMISS  (100)
2330static struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
2331                                             struct file *fpin)
2332{
2333        int flags = vmf->flags;
2334
2335        if (fpin)
2336                return fpin;
2337
2338        /*
2339         * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
2340         * anything, so we only pin the file and drop the mmap_sem if only
2341         * FAULT_FLAG_ALLOW_RETRY is set.
2342         */
2343        if ((flags & (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT)) ==
2344            FAULT_FLAG_ALLOW_RETRY) {
2345                fpin = get_file(vmf->vma->vm_file);
2346                up_read(&vmf->vma->vm_mm->mmap_sem);
2347        }
2348        return fpin;
2349}
2350
2351/*
2352 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_sem
2353 * @vmf - the vm_fault for this fault.
2354 * @page - the page to lock.
2355 * @fpin - the pointer to the file we may pin (or is already pinned).
2356 *
2357 * This works similar to lock_page_or_retry in that it can drop the mmap_sem.
2358 * It differs in that it actually returns the page locked if it returns 1 and 0
2359 * if it couldn't lock the page.  If we did have to drop the mmap_sem then fpin
2360 * will point to the pinned file and needs to be fput()'ed at a later point.
2361 */
2362static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2363                                     struct file **fpin)
2364{
2365        if (trylock_page(page))
2366                return 1;
2367
2368        /*
2369         * NOTE! This will make us return with VM_FAULT_RETRY, but with
2370         * the mmap_sem still held. That's how FAULT_FLAG_RETRY_NOWAIT
2371         * is supposed to work. We have way too many special cases..
2372         */
2373        if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2374                return 0;
2375
2376        *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2377        if (vmf->flags & FAULT_FLAG_KILLABLE) {
2378                if (__lock_page_killable(page)) {
2379                        /*
2380                         * We didn't have the right flags to drop the mmap_sem,
2381                         * but all fault_handlers only check for fatal signals
2382                         * if we return VM_FAULT_RETRY, so we need to drop the
2383                         * mmap_sem here and return 0 if we don't have a fpin.
2384                         */
2385                        if (*fpin == NULL)
2386                                up_read(&vmf->vma->vm_mm->mmap_sem);
2387                        return 0;
2388                }
2389        } else
2390                __lock_page(page);
2391        return 1;
2392}
2393
2394
2395/*
2396 * Synchronous readahead happens when we don't even find a page in the page
2397 * cache at all.  We don't want to perform IO under the mmap sem, so if we have
2398 * to drop the mmap sem we return the file that was pinned in order for us to do
2399 * that.  If we didn't pin a file then we return NULL.  The file that is
2400 * returned needs to be fput()'ed when we're done with it.
2401 */
2402static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2403{
2404        struct file *file = vmf->vma->vm_file;
2405        struct file_ra_state *ra = &file->f_ra;
2406        struct address_space *mapping = file->f_mapping;
2407        struct file *fpin = NULL;
2408        pgoff_t offset = vmf->pgoff;
2409
2410        /* If we don't want any read-ahead, don't bother */
2411        if (vmf->vma->vm_flags & VM_RAND_READ)
2412                return fpin;
2413        if (!ra->ra_pages)
2414                return fpin;
2415
2416        if (vmf->vma->vm_flags & VM_SEQ_READ) {
2417                fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2418                page_cache_sync_readahead(mapping, ra, file, offset,
2419                                          ra->ra_pages);
2420                return fpin;
2421        }
2422
2423        /* Avoid banging the cache line if not needed */
2424        if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2425                ra->mmap_miss++;
2426
2427        /*
2428         * Do we miss much more than hit in this file? If so,
2429         * stop bothering with read-ahead. It will only hurt.
2430         */
2431        if (ra->mmap_miss > MMAP_LOTSAMISS)
2432                return fpin;
2433
2434        /*
2435         * mmap read-around
2436         */
2437        fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2438        ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2439        ra->size = ra->ra_pages;
2440        ra->async_size = ra->ra_pages / 4;
2441        ra_submit(ra, mapping, file);
2442        return fpin;
2443}
2444
2445/*
2446 * Asynchronous readahead happens when we find the page and PG_readahead,
2447 * so we want to possibly extend the readahead further.  We return the file that
2448 * was pinned if we have to drop the mmap_sem in order to do IO.
2449 */
2450static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2451                                            struct page *page)
2452{
2453        struct file *file = vmf->vma->vm_file;
2454        struct file_ra_state *ra = &file->f_ra;
2455        struct address_space *mapping = file->f_mapping;
2456        struct file *fpin = NULL;
2457        pgoff_t offset = vmf->pgoff;
2458
2459        /* If we don't want any read-ahead, don't bother */
2460        if (vmf->vma->vm_flags & VM_RAND_READ)
2461                return fpin;
2462        if (ra->mmap_miss > 0)
2463                ra->mmap_miss--;
2464        if (PageReadahead(page)) {
2465                fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2466                page_cache_async_readahead(mapping, ra, file,
2467                                           page, offset, ra->ra_pages);
2468        }
2469        return fpin;
2470}
2471
2472/**
2473 * filemap_fault - read in file data for page fault handling
2474 * @vmf:        struct vm_fault containing details of the fault
2475 *
2476 * filemap_fault() is invoked via the vma operations vector for a
2477 * mapped memory region to read in file data during a page fault.
2478 *
2479 * The goto's are kind of ugly, but this streamlines the normal case of having
2480 * it in the page cache, and handles the special cases reasonably without
2481 * having a lot of duplicated code.
2482 *
2483 * vma->vm_mm->mmap_sem must be held on entry.
2484 *
2485 * If our return value has VM_FAULT_RETRY set, it's because
2486 * lock_page_or_retry() returned 0.
2487 * The mmap_sem has usually been released in this case.
2488 * See __lock_page_or_retry() for the exception.
2489 *
2490 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2491 * has not been released.
2492 *
2493 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2494 *
2495 * Return: bitwise-OR of %VM_FAULT_ codes.
2496 */
2497vm_fault_t filemap_fault(struct vm_fault *vmf)
2498{
2499        int error;
2500        struct file *file = vmf->vma->vm_file;
2501        struct file *fpin = NULL;
2502        struct address_space *mapping = file->f_mapping;
2503        struct file_ra_state *ra = &file->f_ra;
2504        struct inode *inode = mapping->host;
2505        pgoff_t offset = vmf->pgoff;
2506        pgoff_t max_off;
2507        struct page *page;
2508        vm_fault_t ret = 0;
2509
2510        max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2511        if (unlikely(offset >= max_off))
2512                return VM_FAULT_SIGBUS;
2513
2514        /*
2515         * Do we have something in the page cache already?
2516         */
2517        page = find_get_page(mapping, offset);
2518        if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2519                /*
2520                 * We found the page, so try async readahead before
2521                 * waiting for the lock.
2522                 */
2523                fpin = do_async_mmap_readahead(vmf, page);
2524        } else if (!page) {
2525                /* No page in the page cache at all */
2526                count_vm_event(PGMAJFAULT);
2527                count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2528                ret = VM_FAULT_MAJOR;
2529                fpin = do_sync_mmap_readahead(vmf);
2530retry_find:
2531                page = pagecache_get_page(mapping, offset,
2532                                          FGP_CREAT|FGP_FOR_MMAP,
2533                                          vmf->gfp_mask);
2534                if (!page) {
2535                        if (fpin)
2536                                goto out_retry;
2537                        return vmf_error(-ENOMEM);
2538                }
2539        }
2540
2541        if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2542                goto out_retry;
2543
2544        /* Did it get truncated? */
2545        if (unlikely(page->mapping != mapping)) {
2546                unlock_page(page);
2547                put_page(page);
2548                goto retry_find;
2549        }
2550        VM_BUG_ON_PAGE(page->index != offset, page);
2551
2552        /*
2553         * We have a locked page in the page cache, now we need to check
2554         * that it's up-to-date. If not, it is going to be due to an error.
2555         */
2556        if (unlikely(!PageUptodate(page)))
2557                goto page_not_uptodate;
2558
2559        /*
2560         * We've made it this far and we had to drop our mmap_sem, now is the
2561         * time to return to the upper layer and have it re-find the vma and
2562         * redo the fault.
2563         */
2564        if (fpin) {
2565                unlock_page(page);
2566                goto out_retry;
2567        }
2568
2569        /*
2570         * Found the page and have a reference on it.
2571         * We must recheck i_size under page lock.
2572         */
2573        max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2574        if (unlikely(offset >= max_off)) {
2575                unlock_page(page);
2576                put_page(page);
2577                return VM_FAULT_SIGBUS;
2578        }
2579
2580        vmf->page = page;
2581        return ret | VM_FAULT_LOCKED;
2582
2583page_not_uptodate:
2584        /*
2585         * Umm, take care of errors if the page isn't up-to-date.
2586         * Try to re-read it _once_. We do this synchronously,
2587         * because there really aren't any performance issues here
2588         * and we need to check for errors.
2589         */
2590        ClearPageError(page);
2591        fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2592        error = mapping->a_ops->readpage(file, page);
2593        if (!error) {
2594                wait_on_page_locked(page);
2595                if (!PageUptodate(page))
2596                        error = -EIO;
2597        }
2598        if (fpin)
2599                goto out_retry;
2600        put_page(page);
2601
2602        if (!error || error == AOP_TRUNCATED_PAGE)
2603                goto retry_find;
2604
2605        /* Things didn't work out. Return zero to tell the mm layer so. */
2606        shrink_readahead_size_eio(file, ra);
2607        return VM_FAULT_SIGBUS;
2608
2609out_retry:
2610        /*
2611         * We dropped the mmap_sem, we need to return to the fault handler to
2612         * re-find the vma and come back and find our hopefully still populated
2613         * page.
2614         */
2615        if (page)
2616                put_page(page);
2617        if (fpin)
2618                fput(fpin);
2619        return ret | VM_FAULT_RETRY;
2620}
2621EXPORT_SYMBOL(filemap_fault);
2622
2623void filemap_map_pages(struct vm_fault *vmf,
2624                pgoff_t start_pgoff, pgoff_t end_pgoff)
2625{
2626        struct file *file = vmf->vma->vm_file;
2627        struct address_space *mapping = file->f_mapping;
2628        pgoff_t last_pgoff = start_pgoff;
2629        unsigned long max_idx;
2630        XA_STATE(xas, &mapping->i_pages, start_pgoff);
2631        struct page *head, *page;
2632
2633        rcu_read_lock();
2634        xas_for_each(&xas, page, end_pgoff) {
2635                if (xas_retry(&xas, page))
2636                        continue;
2637                if (xa_is_value(page))
2638                        goto next;
2639
2640                head = compound_head(page);
2641
2642                /*
2643                 * Check for a locked page first, as a speculative
2644                 * reference may adversely influence page migration.
2645                 */
2646                if (PageLocked(head))
2647                        goto next;
2648                if (!page_cache_get_speculative(head))
2649                        goto next;
2650
2651                /* The page was split under us? */
2652                if (compound_head(page) != head)
2653                        goto skip;
2654
2655                /* Has the page moved? */
2656                if (unlikely(page != xas_reload(&xas)))
2657                        goto skip;
2658
2659                if (!PageUptodate(page) ||
2660                                PageReadahead(page) ||
2661                                PageHWPoison(page))
2662                        goto skip;
2663                if (!trylock_page(page))
2664                        goto skip;
2665
2666                if (page->mapping != mapping || !PageUptodate(page))
2667                        goto unlock;
2668
2669                max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2670                if (page->index >= max_idx)
2671                        goto unlock;
2672
2673                if (file->f_ra.mmap_miss > 0)
2674                        file->f_ra.mmap_miss--;
2675
2676                vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
2677                if (vmf->pte)
2678                        vmf->pte += xas.xa_index - last_pgoff;
2679                last_pgoff = xas.xa_index;
2680                if (alloc_set_pte(vmf, NULL, page))
2681                        goto unlock;
2682                unlock_page(page);
2683                goto next;
2684unlock:
2685                unlock_page(page);
2686skip:
2687                put_page(page);
2688next:
2689                /* Huge page is mapped? No need to proceed. */
2690                if (pmd_trans_huge(*vmf->pmd))
2691                        break;
2692        }
2693        rcu_read_unlock();
2694}
2695EXPORT_SYMBOL(filemap_map_pages);
2696
2697vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2698{
2699        struct page *page = vmf->page;
2700        struct inode *inode = file_inode(vmf->vma->vm_file);
2701        vm_fault_t ret = VM_FAULT_LOCKED;
2702
2703        sb_start_pagefault(inode->i_sb);
2704        file_update_time(vmf->vma->vm_file);
2705        lock_page(page);
2706        if (page->mapping != inode->i_mapping) {
2707                unlock_page(page);
2708                ret = VM_FAULT_NOPAGE;
2709                goto out;
2710        }
2711        /*
2712         * We mark the page dirty already here so that when freeze is in
2713         * progress, we are guaranteed that writeback during freezing will
2714         * see the dirty page and writeprotect it again.
2715         */
2716        set_page_dirty(page);
2717        wait_for_stable_page(page);
2718out:
2719        sb_end_pagefault(inode->i_sb);
2720        return ret;
2721}
2722
2723const struct vm_operations_struct generic_file_vm_ops = {
2724        .fault          = filemap_fault,
2725        .map_pages      = filemap_map_pages,
2726        .page_mkwrite   = filemap_page_mkwrite,
2727};
2728
2729/* This is used for a general mmap of a disk file */
2730
2731int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2732{
2733        struct address_space *mapping = file->f_mapping;
2734
2735        if (!mapping->a_ops->readpage)
2736                return -ENOEXEC;
2737        file_accessed(file);
2738        vma->vm_ops = &generic_file_vm_ops;
2739        return 0;
2740}
2741
2742/*
2743 * This is for filesystems which do not implement ->writepage.
2744 */
2745int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2746{
2747        if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2748                return -EINVAL;
2749        return generic_file_mmap(file, vma);
2750}
2751#else
2752vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2753{
2754        return VM_FAULT_SIGBUS;
2755}
2756int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2757{
2758        return -ENOSYS;
2759}
2760int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2761{
2762        return -ENOSYS;
2763}
2764#endif /* CONFIG_MMU */
2765
2766EXPORT_SYMBOL(filemap_page_mkwrite);
2767EXPORT_SYMBOL(generic_file_mmap);
2768EXPORT_SYMBOL(generic_file_readonly_mmap);
2769
2770static struct page *wait_on_page_read(struct page *page)
2771{
2772        if (!IS_ERR(page)) {
2773                wait_on_page_locked(page);
2774                if (!PageUptodate(page)) {
2775                        put_page(page);
2776                        page = ERR_PTR(-EIO);
2777                }
2778        }
2779        return page;
2780}
2781
2782static struct page *do_read_cache_page(struct address_space *mapping,
2783                                pgoff_t index,
2784                                int (*filler)(void *, struct page *),
2785                                void *data,
2786                                gfp_t gfp)
2787{
2788        struct page *page;
2789        int err;
2790repeat:
2791        page = find_get_page(mapping, index);
2792        if (!page) {
2793                page = __page_cache_alloc(gfp);
2794                if (!page)
2795                        return ERR_PTR(-ENOMEM);
2796                err = add_to_page_cache_lru(page, mapping, index, gfp);
2797                if (unlikely(err)) {
2798                        put_page(page);
2799                        if (err == -EEXIST)
2800                                goto repeat;
2801                        /* Presumably ENOMEM for xarray node */
2802                        return ERR_PTR(err);
2803                }
2804
2805filler:
2806                err = filler(data, page);
2807                if (err < 0) {
2808                        put_page(page);
2809                        return ERR_PTR(err);
2810                }
2811
2812                page = wait_on_page_read(page);
2813                if (IS_ERR(page))
2814                        return page;
2815                goto out;
2816        }
2817        if (PageUptodate(page))
2818                goto out;
2819
2820        /*
2821         * Page is not up to date and may be locked due one of the following
2822         * case a: Page is being filled and the page lock is held
2823         * case b: Read/write error clearing the page uptodate status
2824         * case c: Truncation in progress (page locked)
2825         * case d: Reclaim in progress
2826         *
2827         * Case a, the page will be up to date when the page is unlocked.
2828         *    There is no need to serialise on the page lock here as the page
2829         *    is pinned so the lock gives no additional protection. Even if the
2830         *    the page is truncated, the data is still valid if PageUptodate as
2831         *    it's a race vs truncate race.
2832         * Case b, the page will not be up to date
2833         * Case c, the page may be truncated but in itself, the data may still
2834         *    be valid after IO completes as it's a read vs truncate race. The
2835         *    operation must restart if the page is not uptodate on unlock but
2836         *    otherwise serialising on page lock to stabilise the mapping gives
2837         *    no additional guarantees to the caller as the page lock is
2838         *    released before return.
2839         * Case d, similar to truncation. If reclaim holds the page lock, it
2840         *    will be a race with remove_mapping that determines if the mapping
2841         *    is valid on unlock but otherwise the data is valid and there is
2842         *    no need to serialise with page lock.
2843         *
2844         * As the page lock gives no additional guarantee, we optimistically
2845         * wait on the page to be unlocked and check if it's up to date and
2846         * use the page if it is. Otherwise, the page lock is required to
2847         * distinguish between the different cases. The motivation is that we
2848         * avoid spurious serialisations and wakeups when multiple processes
2849         * wait on the same page for IO to complete.
2850         */
2851        wait_on_page_locked(page);
2852        if (PageUptodate(page))
2853                goto out;
2854
2855        /* Distinguish between all the cases under the safety of the lock */
2856        lock_page(page);
2857
2858        /* Case c or d, restart the operation */
2859        if (!page->mapping) {
2860                unlock_page(page);
2861                put_page(page);
2862                goto repeat;
2863        }
2864
2865        /* Someone else locked and filled the page in a very small window */
2866        if (PageUptodate(page)) {
2867                unlock_page(page);
2868                goto out;
2869        }
2870        goto filler;
2871
2872out:
2873        mark_page_accessed(page);
2874        return page;
2875}
2876
2877/**
2878 * read_cache_page - read into page cache, fill it if needed
2879 * @mapping:    the page's address_space
2880 * @index:      the page index
2881 * @filler:     function to perform the read
2882 * @data:       first arg to filler(data, page) function, often left as NULL
2883 *
2884 * Read into the page cache. If a page already exists, and PageUptodate() is
2885 * not set, try to fill the page and wait for it to become unlocked.
2886 *
2887 * If the page does not get brought uptodate, return -EIO.
2888 *
2889 * Return: up to date page on success, ERR_PTR() on failure.
2890 */
2891struct page *read_cache_page(struct address_space *mapping,
2892                                pgoff_t index,
2893                                int (*filler)(void *, struct page *),
2894                                void *data)
2895{
2896        return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2897}
2898EXPORT_SYMBOL(read_cache_page);
2899
2900/**
2901 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2902 * @mapping:    the page's address_space
2903 * @index:      the page index
2904 * @gfp:        the page allocator flags to use if allocating
2905 *
2906 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2907 * any new page allocations done using the specified allocation flags.
2908 *
2909 * If the page does not get brought uptodate, return -EIO.
2910 *
2911 * Return: up to date page on success, ERR_PTR() on failure.
2912 */
2913struct page *read_cache_page_gfp(struct address_space *mapping,
2914                                pgoff_t index,
2915                                gfp_t gfp)
2916{
2917        filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2918
2919        return do_read_cache_page(mapping, index, filler, NULL, gfp);
2920}
2921EXPORT_SYMBOL(read_cache_page_gfp);
2922
2923/*
2924 * Don't operate on ranges the page cache doesn't support, and don't exceed the
2925 * LFS limits.  If pos is under the limit it becomes a short access.  If it
2926 * exceeds the limit we return -EFBIG.
2927 */
2928static int generic_access_check_limits(struct file *file, loff_t pos,
2929                                       loff_t *count)
2930{
2931        struct inode *inode = file->f_mapping->host;
2932        loff_t max_size = inode->i_sb->s_maxbytes;
2933
2934        if (!(file->f_flags & O_LARGEFILE))
2935                max_size = MAX_NON_LFS;
2936
2937        if (unlikely(pos >= max_size))
2938                return -EFBIG;
2939        *count = min(*count, max_size - pos);
2940        return 0;
2941}
2942
2943static int generic_write_check_limits(struct file *file, loff_t pos,
2944                                      loff_t *count)
2945{
2946        loff_t limit = rlimit(RLIMIT_FSIZE);
2947
2948        if (limit != RLIM_INFINITY) {
2949                if (pos >= limit) {
2950                        send_sig(SIGXFSZ, current, 0);
2951                        return -EFBIG;
2952                }
2953                *count = min(*count, limit - pos);
2954        }
2955
2956        return generic_access_check_limits(file, pos, count);
2957}
2958
2959/*
2960 * Performs necessary checks before doing a write
2961 *
2962 * Can adjust writing position or amount of bytes to write.
2963 * Returns appropriate error code that caller should return or
2964 * zero in case that write should be allowed.
2965 */
2966inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2967{
2968        struct file *file = iocb->ki_filp;
2969        struct inode *inode = file->f_mapping->host;
2970        loff_t count;
2971        int ret;
2972
2973        if (!iov_iter_count(from))
2974                return 0;
2975
2976        /* FIXME: this is for backwards compatibility with 2.4 */
2977        if (iocb->ki_flags & IOCB_APPEND)
2978                iocb->ki_pos = i_size_read(inode);
2979
2980        if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2981                return -EINVAL;
2982
2983        count = iov_iter_count(from);
2984        ret = generic_write_check_limits(file, iocb->ki_pos, &count);
2985        if (ret)
2986                return ret;
2987
2988        iov_iter_truncate(from, count);
2989        return iov_iter_count(from);
2990}
2991EXPORT_SYMBOL(generic_write_checks);
2992
2993/*
2994 * Performs necessary checks before doing a clone.
2995 *
2996 * Can adjust amount of bytes to clone.
2997 * Returns appropriate error code that caller should return or
2998 * zero in case the clone should be allowed.
2999 */
3000int generic_remap_checks(struct file *file_in, loff_t pos_in,
3001                         struct file *file_out, loff_t pos_out,
3002                         loff_t *req_count, unsigned int remap_flags)
3003{
3004        struct inode *inode_in = file_in->f_mapping->host;
3005        struct inode *inode_out = file_out->f_mapping->host;
3006        uint64_t count = *req_count;
3007        uint64_t bcount;
3008        loff_t size_in, size_out;
3009        loff_t bs = inode_out->i_sb->s_blocksize;
3010        int ret;
3011
3012        /* The start of both ranges must be aligned to an fs block. */
3013        if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_out, bs))
3014                return -EINVAL;
3015
3016        /* Ensure offsets don't wrap. */
3017        if (pos_in + count < pos_in || pos_out + count < pos_out)
3018                return -EINVAL;
3019
3020        size_in = i_size_read(inode_in);
3021        size_out = i_size_read(inode_out);
3022
3023        /* Dedupe requires both ranges to be within EOF. */
3024        if ((remap_flags & REMAP_FILE_DEDUP) &&
3025            (pos_in >= size_in || pos_in + count > size_in ||
3026             pos_out >= size_out || pos_out + count > size_out))
3027                return -EINVAL;
3028
3029        /* Ensure the infile range is within the infile. */
3030        if (pos_in >= size_in)
3031                return -EINVAL;
3032        count = min(count, size_in - (uint64_t)pos_in);
3033
3034        ret = generic_access_check_limits(file_in, pos_in, &count);
3035        if (ret)
3036                return ret;
3037
3038        ret = generic_write_check_limits(file_out, pos_out, &count);
3039        if (ret)
3040                return ret;
3041
3042        /*
3043         * If the user wanted us to link to the infile's EOF, round up to the
3044         * next block boundary for this check.
3045         *
3046         * Otherwise, make sure the count is also block-aligned, having
3047         * already confirmed the starting offsets' block alignment.
3048         */
3049        if (pos_in + count == size_in) {
3050                bcount = ALIGN(size_in, bs) - pos_in;
3051        } else {
3052                if (!IS_ALIGNED(count, bs))
3053                        count = ALIGN_DOWN(count, bs);
3054                bcount = count;
3055        }
3056
3057        /* Don't allow overlapped cloning within the same file. */
3058        if (inode_in == inode_out &&
3059            pos_out + bcount > pos_in &&
3060            pos_out < pos_in + bcount)
3061                return -EINVAL;
3062
3063        /*
3064         * We shortened the request but the caller can't deal with that, so
3065         * bounce the request back to userspace.
3066         */
3067        if (*req_count != count && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
3068                return -EINVAL;
3069
3070        *req_count = count;
3071        return 0;
3072}
3073
3074int pagecache_write_begin(struct file *file, struct address_space *mapping,
3075                                loff_t pos, unsigned len, unsigned flags,
3076                                struct page **pagep, void **fsdata)
3077{
3078        const struct address_space_operations *aops = mapping->a_ops;
3079
3080        return aops->write_begin(file, mapping, pos, len, flags,
3081                                                        pagep, fsdata);
3082}
3083EXPORT_SYMBOL(pagecache_write_begin);
3084
3085int pagecache_write_end(struct file *file, struct address_space *mapping,
3086                                loff_t pos, unsigned len, unsigned copied,
3087                                struct page *page, void *fsdata)
3088{
3089        const struct address_space_operations *aops = mapping->a_ops;
3090
3091        return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3092}
3093EXPORT_SYMBOL(pagecache_write_end);
3094
3095ssize_t
3096generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3097{
3098        struct file     *file = iocb->ki_filp;
3099        struct address_space *mapping = file->f_mapping;
3100        struct inode    *inode = mapping->host;
3101        loff_t          pos = iocb->ki_pos;
3102        ssize_t         written;
3103        size_t          write_len;
3104        pgoff_t         end;
3105
3106        write_len = iov_iter_count(from);
3107        end = (pos + write_len - 1) >> PAGE_SHIFT;
3108
3109        if (iocb->ki_flags & IOCB_NOWAIT) {
3110                /* If there are pages to writeback, return */
3111                if (filemap_range_has_page(inode->i_mapping, pos,
3112                                           pos + write_len - 1))
3113                        return -EAGAIN;
3114        } else {
3115                written = filemap_write_and_wait_range(mapping, pos,
3116                                                        pos + write_len - 1);
3117                if (written)
3118                        goto out;
3119        }
3120
3121        /*
3122         * After a write we want buffered reads to be sure to go to disk to get
3123         * the new data.  We invalidate clean cached page from the region we're
3124         * about to write.  We do this *before* the write so that we can return
3125         * without clobbering -EIOCBQUEUED from ->direct_IO().
3126         */
3127        written = invalidate_inode_pages2_range(mapping,
3128                                        pos >> PAGE_SHIFT, end);
3129        /*
3130         * If a page can not be invalidated, return 0 to fall back
3131         * to buffered write.
3132         */
3133        if (written) {
3134                if (written == -EBUSY)
3135                        return 0;
3136                goto out;
3137        }
3138
3139        written = mapping->a_ops->direct_IO(iocb, from);
3140
3141        /*
3142         * Finally, try again to invalidate clean pages which might have been
3143         * cached by non-direct readahead, or faulted in by get_user_pages()
3144         * if the source of the write was an mmap'ed region of the file
3145         * we're writing.  Either one is a pretty crazy thing to do,
3146         * so we don't support it 100%.  If this invalidation
3147         * fails, tough, the write still worked...
3148         *
3149         * Most of the time we do not need this since dio_complete() will do
3150         * the invalidation for us. However there are some file systems that
3151         * do not end up with dio_complete() being called, so let's not break
3152         * them by removing it completely
3153         */
3154        if (mapping->nrpages)
3155                invalidate_inode_pages2_range(mapping,
3156                                        pos >> PAGE_SHIFT, end);
3157
3158        if (written > 0) {
3159                pos += written;
3160                write_len -= written;
3161                if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3162                        i_size_write(inode, pos);
3163                        mark_inode_dirty(inode);
3164                }
3165                iocb->ki_pos = pos;
3166        }
3167        iov_iter_revert(from, write_len - iov_iter_count(from));
3168out:
3169        return written;
3170}
3171EXPORT_SYMBOL(generic_file_direct_write);
3172
3173/*
3174 * Find or create a page at the given pagecache position. Return the locked
3175 * page. This function is specifically for buffered writes.
3176 */
3177struct page *grab_cache_page_write_begin(struct address_space *mapping,
3178                                        pgoff_t index, unsigned flags)
3179{
3180        struct page *page;
3181        int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3182
3183        if (flags & AOP_FLAG_NOFS)
3184                fgp_flags |= FGP_NOFS;
3185
3186        page = pagecache_get_page(mapping, index, fgp_flags,
3187                        mapping_gfp_mask(mapping));
3188        if (page)
3189                wait_for_stable_page(page);
3190
3191        return page;
3192}
3193EXPORT_SYMBOL(grab_cache_page_write_begin);
3194
3195ssize_t generic_perform_write(struct file *file,
3196                                struct iov_iter *i, loff_t pos)
3197{
3198        struct address_space *mapping = file->f_mapping;
3199        const struct address_space_operations *a_ops = mapping->a_ops;
3200        long status = 0;
3201        ssize_t written = 0;
3202        unsigned int flags = 0;
3203
3204        do {
3205                struct page *page;
3206                unsigned long offset;   /* Offset into pagecache page */
3207                unsigned long bytes;    /* Bytes to write to page */
3208                size_t copied;          /* Bytes copied from user */
3209                void *fsdata;
3210
3211                offset = (pos & (PAGE_SIZE - 1));
3212                bytes = min_t(unsigned long, PAGE_SIZE - offset,
3213                                                iov_iter_count(i));
3214
3215again:
3216                /*
3217                 * Bring in the user page that we will copy from _first_.
3218                 * Otherwise there's a nasty deadlock on copying from the
3219                 * same page as we're writing to, without it being marked
3220                 * up-to-date.
3221                 *
3222                 * Not only is this an optimisation, but it is also required
3223                 * to check that the address is actually valid, when atomic
3224                 * usercopies are used, below.
3225                 */
3226                if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3227                        status = -EFAULT;
3228                        break;
3229                }
3230
3231                if (fatal_signal_pending(current)) {
3232                        status = -EINTR;
3233                        break;
3234                }
3235
3236                status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3237                                                &page, &fsdata);
3238                if (unlikely(status < 0))
3239                        break;
3240
3241                if (mapping_writably_mapped(mapping))
3242                        flush_dcache_page(page);
3243
3244                copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3245                flush_dcache_page(page);
3246
3247                status = a_ops->write_end(file, mapping, pos, bytes, copied,
3248                                                page, fsdata);
3249                if (unlikely(status < 0))
3250                        break;
3251                copied = status;
3252
3253                cond_resched();
3254
3255                iov_iter_advance(i, copied);
3256                if (unlikely(copied == 0)) {
3257                        /*
3258                         * If we were unable to copy any data at all, we must
3259                         * fall back to a single segment length write.
3260                         *
3261                         * If we didn't fallback here, we could livelock
3262                         * because not all segments in the iov can be copied at
3263                         * once without a pagefault.
3264                         */
3265                        bytes = min_t(unsigned long, PAGE_SIZE - offset,
3266                                                iov_iter_single_seg_count(i));
3267                        goto again;
3268                }
3269                pos += copied;
3270                written += copied;
3271
3272                balance_dirty_pages_ratelimited(mapping);
3273        } while (iov_iter_count(i));
3274
3275        return written ? written : status;
3276}
3277EXPORT_SYMBOL(generic_perform_write);
3278
3279/**
3280 * __generic_file_write_iter - write data to a file
3281 * @iocb:       IO state structure (file, offset, etc.)
3282 * @from:       iov_iter with data to write
3283 *
3284 * This function does all the work needed for actually writing data to a
3285 * file. It does all basic checks, removes SUID from the file, updates
3286 * modification times and calls proper subroutines depending on whether we
3287 * do direct IO or a standard buffered write.
3288 *
3289 * It expects i_mutex to be grabbed unless we work on a block device or similar
3290 * object which does not need locking at all.
3291 *
3292 * This function does *not* take care of syncing data in case of O_SYNC write.
3293 * A caller has to handle it. This is mainly due to the fact that we want to
3294 * avoid syncing under i_mutex.
3295 *
3296 * Return:
3297 * * number of bytes written, even for truncated writes
3298 * * negative error code if no data has been written at all
3299 */
3300ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3301{
3302        struct file *file = iocb->ki_filp;
3303        struct address_space * mapping = file->f_mapping;
3304        struct inode    *inode = mapping->host;
3305        ssize_t         written = 0;
3306        ssize_t         err;
3307        ssize_t         status;
3308
3309        /* We can write back this queue in page reclaim */
3310        current->backing_dev_info = inode_to_bdi(inode);
3311        err = file_remove_privs(file);
3312        if (err)
3313                goto out;
3314
3315        err = file_update_time(file);
3316        if (err)
3317                goto out;
3318
3319        if (iocb->ki_flags & IOCB_DIRECT) {
3320                loff_t pos, endbyte;
3321
3322                written = generic_file_direct_write(iocb, from);
3323                /*
3324                 * If the write stopped short of completing, fall back to
3325                 * buffered writes.  Some filesystems do this for writes to
3326                 * holes, for example.  For DAX files, a buffered write will
3327                 * not succeed (even if it did, DAX does not handle dirty
3328                 * page-cache pages correctly).
3329                 */
3330                if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3331                        goto out;
3332
3333                status = generic_perform_write(file, from, pos = iocb->ki_pos);
3334                /*
3335                 * If generic_perform_write() returned a synchronous error
3336                 * then we want to return the number of bytes which were
3337                 * direct-written, or the error code if that was zero.  Note
3338                 * that this differs from normal direct-io semantics, which
3339                 * will return -EFOO even if some bytes were written.
3340                 */
3341                if (unlikely(status < 0)) {
3342                        err = status;
3343                        goto out;
3344                }
3345                /*
3346                 * We need to ensure that the page cache pages are written to
3347                 * disk and invalidated to preserve the expected O_DIRECT
3348                 * semantics.
3349                 */
3350                endbyte = pos + status - 1;
3351                err = filemap_write_and_wait_range(mapping, pos, endbyte);
3352                if (err == 0) {
3353                        iocb->ki_pos = endbyte + 1;
3354                        written += status;
3355                        invalidate_mapping_pages(mapping,
3356                                                 pos >> PAGE_SHIFT,
3357                                                 endbyte >> PAGE_SHIFT);
3358                } else {
3359                        /*
3360                         * We don't know how much we wrote, so just return
3361                         * the number of bytes which were direct-written
3362                         */
3363                }
3364        } else {
3365                written = generic_perform_write(file, from, iocb->ki_pos);
3366                if (likely(written > 0))
3367                        iocb->ki_pos += written;
3368        }
3369out:
3370        current->backing_dev_info = NULL;
3371        return written ? written : err;
3372}
3373EXPORT_SYMBOL(__generic_file_write_iter);
3374
3375/**
3376 * generic_file_write_iter - write data to a file
3377 * @iocb:       IO state structure
3378 * @from:       iov_iter with data to write
3379 *
3380 * This is a wrapper around __generic_file_write_iter() to be used by most
3381 * filesystems. It takes care of syncing the file in case of O_SYNC file
3382 * and acquires i_mutex as needed.
3383 * Return:
3384 * * negative error code if no data has been written at all of
3385 *   vfs_fsync_range() failed for a synchronous write
3386 * * number of bytes written, even for truncated writes
3387 */
3388ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3389{
3390        struct file *file = iocb->ki_filp;
3391        struct inode *inode = file->f_mapping->host;
3392        ssize_t ret;
3393
3394        inode_lock(inode);
3395        ret = generic_write_checks(iocb, from);
3396        if (ret > 0)
3397                ret = __generic_file_write_iter(iocb, from);
3398        inode_unlock(inode);
3399
3400        if (ret > 0)
3401                ret = generic_write_sync(iocb, ret);
3402        return ret;
3403}
3404EXPORT_SYMBOL(generic_file_write_iter);
3405
3406/**
3407 * try_to_release_page() - release old fs-specific metadata on a page
3408 *
3409 * @page: the page which the kernel is trying to free
3410 * @gfp_mask: memory allocation flags (and I/O mode)
3411 *
3412 * The address_space is to try to release any data against the page
3413 * (presumably at page->private).
3414 *
3415 * This may also be called if PG_fscache is set on a page, indicating that the
3416 * page is known to the local caching routines.
3417 *
3418 * The @gfp_mask argument specifies whether I/O may be performed to release
3419 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3420 *
3421 * Return: %1 if the release was successful, otherwise return zero.
3422 */
3423int try_to_release_page(struct page *page, gfp_t gfp_mask)
3424{
3425        struct address_space * const mapping = page->mapping;
3426
3427        BUG_ON(!PageLocked(page));
3428        if (PageWriteback(page))
3429                return 0;
3430
3431        if (mapping && mapping->a_ops->releasepage)
3432                return mapping->a_ops->releasepage(page, gfp_mask);
3433        return try_to_free_buffers(page);
3434}
3435
3436EXPORT_SYMBOL(try_to_release_page);
3437