linux/mm/memory.c
<<
>>
Prefs
   1/*
   2 *  linux/mm/memory.c
   3 *
   4 *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
   5 */
   6
   7/*
   8 * demand-loading started 01.12.91 - seems it is high on the list of
   9 * things wanted, and it should be easy to implement. - Linus
  10 */
  11
  12/*
  13 * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
  14 * pages started 02.12.91, seems to work. - Linus.
  15 *
  16 * Tested sharing by executing about 30 /bin/sh: under the old kernel it
  17 * would have taken more than the 6M I have free, but it worked well as
  18 * far as I could see.
  19 *
  20 * Also corrected some "invalidate()"s - I wasn't doing enough of them.
  21 */
  22
  23/*
  24 * Real VM (paging to/from disk) started 18.12.91. Much more work and
  25 * thought has to go into this. Oh, well..
  26 * 19.12.91  -  works, somewhat. Sometimes I get faults, don't know why.
  27 *              Found it. Everything seems to work now.
  28 * 20.12.91  -  Ok, making the swap-device changeable like the root.
  29 */
  30
  31/*
  32 * 05.04.94  -  Multi-page memory management added for v1.1.
  33 *              Idea by Alex Bligh (alex@cconcepts.co.uk)
  34 *
  35 * 16.07.99  -  Support of BIGMEM added by Gerhard Wichert, Siemens AG
  36 *              (Gerhard.Wichert@pdb.siemens.de)
  37 *
  38 * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
  39 */
  40
  41#include <linux/kernel_stat.h>
  42#include <linux/mm.h>
  43#include <linux/sched/mm.h>
  44#include <linux/sched/coredump.h>
  45#include <linux/sched/numa_balancing.h>
  46#include <linux/sched/task.h>
  47#include <linux/hugetlb.h>
  48#include <linux/mman.h>
  49#include <linux/swap.h>
  50#include <linux/highmem.h>
  51#include <linux/pagemap.h>
  52#include <linux/memremap.h>
  53#include <linux/ksm.h>
  54#include <linux/rmap.h>
  55#include <linux/export.h>
  56#include <linux/delayacct.h>
  57#include <linux/init.h>
  58#include <linux/pfn_t.h>
  59#include <linux/writeback.h>
  60#include <linux/memcontrol.h>
  61#include <linux/mmu_notifier.h>
  62#include <linux/swapops.h>
  63#include <linux/elf.h>
  64#include <linux/gfp.h>
  65#include <linux/migrate.h>
  66#include <linux/string.h>
  67#include <linux/debugfs.h>
  68#include <linux/userfaultfd_k.h>
  69#include <linux/dax.h>
  70#include <linux/oom.h>
  71#include <linux/numa.h>
  72
  73#include <asm/io.h>
  74#include <asm/mmu_context.h>
  75#include <asm/pgalloc.h>
  76#include <linux/uaccess.h>
  77#include <asm/tlb.h>
  78#include <asm/tlbflush.h>
  79#include <asm/pgtable.h>
  80
  81#include "internal.h"
  82
  83#if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
  84#warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
  85#endif
  86
  87#ifndef CONFIG_NEED_MULTIPLE_NODES
  88/* use the per-pgdat data instead for discontigmem - mbligh */
  89unsigned long max_mapnr;
  90EXPORT_SYMBOL(max_mapnr);
  91
  92struct page *mem_map;
  93EXPORT_SYMBOL(mem_map);
  94#endif
  95
  96/*
  97 * A number of key systems in x86 including ioremap() rely on the assumption
  98 * that high_memory defines the upper bound on direct map memory, then end
  99 * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
 100 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
 101 * and ZONE_HIGHMEM.
 102 */
 103void *high_memory;
 104EXPORT_SYMBOL(high_memory);
 105
 106/*
 107 * Randomize the address space (stacks, mmaps, brk, etc.).
 108 *
 109 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
 110 *   as ancient (libc5 based) binaries can segfault. )
 111 */
 112int randomize_va_space __read_mostly =
 113#ifdef CONFIG_COMPAT_BRK
 114                                        1;
 115#else
 116                                        2;
 117#endif
 118
 119static int __init disable_randmaps(char *s)
 120{
 121        randomize_va_space = 0;
 122        return 1;
 123}
 124__setup("norandmaps", disable_randmaps);
 125
 126unsigned long zero_pfn __read_mostly;
 127EXPORT_SYMBOL(zero_pfn);
 128
 129unsigned long highest_memmap_pfn __read_mostly;
 130
 131/*
 132 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
 133 */
 134static int __init init_zero_pfn(void)
 135{
 136        zero_pfn = page_to_pfn(ZERO_PAGE(0));
 137        return 0;
 138}
 139core_initcall(init_zero_pfn);
 140
 141
 142#if defined(SPLIT_RSS_COUNTING)
 143
 144void sync_mm_rss(struct mm_struct *mm)
 145{
 146        int i;
 147
 148        for (i = 0; i < NR_MM_COUNTERS; i++) {
 149                if (current->rss_stat.count[i]) {
 150                        add_mm_counter(mm, i, current->rss_stat.count[i]);
 151                        current->rss_stat.count[i] = 0;
 152                }
 153        }
 154        current->rss_stat.events = 0;
 155}
 156
 157static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
 158{
 159        struct task_struct *task = current;
 160
 161        if (likely(task->mm == mm))
 162                task->rss_stat.count[member] += val;
 163        else
 164                add_mm_counter(mm, member, val);
 165}
 166#define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
 167#define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
 168
 169/* sync counter once per 64 page faults */
 170#define TASK_RSS_EVENTS_THRESH  (64)
 171static void check_sync_rss_stat(struct task_struct *task)
 172{
 173        if (unlikely(task != current))
 174                return;
 175        if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
 176                sync_mm_rss(task->mm);
 177}
 178#else /* SPLIT_RSS_COUNTING */
 179
 180#define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
 181#define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
 182
 183static void check_sync_rss_stat(struct task_struct *task)
 184{
 185}
 186
 187#endif /* SPLIT_RSS_COUNTING */
 188
 189/*
 190 * Note: this doesn't free the actual pages themselves. That
 191 * has been handled earlier when unmapping all the memory regions.
 192 */
 193static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
 194                           unsigned long addr)
 195{
 196        pgtable_t token = pmd_pgtable(*pmd);
 197        pmd_clear(pmd);
 198        pte_free_tlb(tlb, token, addr);
 199        mm_dec_nr_ptes(tlb->mm);
 200}
 201
 202static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
 203                                unsigned long addr, unsigned long end,
 204                                unsigned long floor, unsigned long ceiling)
 205{
 206        pmd_t *pmd;
 207        unsigned long next;
 208        unsigned long start;
 209
 210        start = addr;
 211        pmd = pmd_offset(pud, addr);
 212        do {
 213                next = pmd_addr_end(addr, end);
 214                if (pmd_none_or_clear_bad(pmd))
 215                        continue;
 216                free_pte_range(tlb, pmd, addr);
 217        } while (pmd++, addr = next, addr != end);
 218
 219        start &= PUD_MASK;
 220        if (start < floor)
 221                return;
 222        if (ceiling) {
 223                ceiling &= PUD_MASK;
 224                if (!ceiling)
 225                        return;
 226        }
 227        if (end - 1 > ceiling - 1)
 228                return;
 229
 230        pmd = pmd_offset(pud, start);
 231        pud_clear(pud);
 232        pmd_free_tlb(tlb, pmd, start);
 233        mm_dec_nr_pmds(tlb->mm);
 234}
 235
 236static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
 237                                unsigned long addr, unsigned long end,
 238                                unsigned long floor, unsigned long ceiling)
 239{
 240        pud_t *pud;
 241        unsigned long next;
 242        unsigned long start;
 243
 244        start = addr;
 245        pud = pud_offset(p4d, addr);
 246        do {
 247                next = pud_addr_end(addr, end);
 248                if (pud_none_or_clear_bad(pud))
 249                        continue;
 250                free_pmd_range(tlb, pud, addr, next, floor, ceiling);
 251        } while (pud++, addr = next, addr != end);
 252
 253        start &= P4D_MASK;
 254        if (start < floor)
 255                return;
 256        if (ceiling) {
 257                ceiling &= P4D_MASK;
 258                if (!ceiling)
 259                        return;
 260        }
 261        if (end - 1 > ceiling - 1)
 262                return;
 263
 264        pud = pud_offset(p4d, start);
 265        p4d_clear(p4d);
 266        pud_free_tlb(tlb, pud, start);
 267        mm_dec_nr_puds(tlb->mm);
 268}
 269
 270static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
 271                                unsigned long addr, unsigned long end,
 272                                unsigned long floor, unsigned long ceiling)
 273{
 274        p4d_t *p4d;
 275        unsigned long next;
 276        unsigned long start;
 277
 278        start = addr;
 279        p4d = p4d_offset(pgd, addr);
 280        do {
 281                next = p4d_addr_end(addr, end);
 282                if (p4d_none_or_clear_bad(p4d))
 283                        continue;
 284                free_pud_range(tlb, p4d, addr, next, floor, ceiling);
 285        } while (p4d++, addr = next, addr != end);
 286
 287        start &= PGDIR_MASK;
 288        if (start < floor)
 289                return;
 290        if (ceiling) {
 291                ceiling &= PGDIR_MASK;
 292                if (!ceiling)
 293                        return;
 294        }
 295        if (end - 1 > ceiling - 1)
 296                return;
 297
 298        p4d = p4d_offset(pgd, start);
 299        pgd_clear(pgd);
 300        p4d_free_tlb(tlb, p4d, start);
 301}
 302
 303/*
 304 * This function frees user-level page tables of a process.
 305 */
 306void free_pgd_range(struct mmu_gather *tlb,
 307                        unsigned long addr, unsigned long end,
 308                        unsigned long floor, unsigned long ceiling)
 309{
 310        pgd_t *pgd;
 311        unsigned long next;
 312
 313        /*
 314         * The next few lines have given us lots of grief...
 315         *
 316         * Why are we testing PMD* at this top level?  Because often
 317         * there will be no work to do at all, and we'd prefer not to
 318         * go all the way down to the bottom just to discover that.
 319         *
 320         * Why all these "- 1"s?  Because 0 represents both the bottom
 321         * of the address space and the top of it (using -1 for the
 322         * top wouldn't help much: the masks would do the wrong thing).
 323         * The rule is that addr 0 and floor 0 refer to the bottom of
 324         * the address space, but end 0 and ceiling 0 refer to the top
 325         * Comparisons need to use "end - 1" and "ceiling - 1" (though
 326         * that end 0 case should be mythical).
 327         *
 328         * Wherever addr is brought up or ceiling brought down, we must
 329         * be careful to reject "the opposite 0" before it confuses the
 330         * subsequent tests.  But what about where end is brought down
 331         * by PMD_SIZE below? no, end can't go down to 0 there.
 332         *
 333         * Whereas we round start (addr) and ceiling down, by different
 334         * masks at different levels, in order to test whether a table
 335         * now has no other vmas using it, so can be freed, we don't
 336         * bother to round floor or end up - the tests don't need that.
 337         */
 338
 339        addr &= PMD_MASK;
 340        if (addr < floor) {
 341                addr += PMD_SIZE;
 342                if (!addr)
 343                        return;
 344        }
 345        if (ceiling) {
 346                ceiling &= PMD_MASK;
 347                if (!ceiling)
 348                        return;
 349        }
 350        if (end - 1 > ceiling - 1)
 351                end -= PMD_SIZE;
 352        if (addr > end - 1)
 353                return;
 354        /*
 355         * We add page table cache pages with PAGE_SIZE,
 356         * (see pte_free_tlb()), flush the tlb if we need
 357         */
 358        tlb_change_page_size(tlb, PAGE_SIZE);
 359        pgd = pgd_offset(tlb->mm, addr);
 360        do {
 361                next = pgd_addr_end(addr, end);
 362                if (pgd_none_or_clear_bad(pgd))
 363                        continue;
 364                free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
 365        } while (pgd++, addr = next, addr != end);
 366}
 367
 368void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
 369                unsigned long floor, unsigned long ceiling)
 370{
 371        while (vma) {
 372                struct vm_area_struct *next = vma->vm_next;
 373                unsigned long addr = vma->vm_start;
 374
 375                /*
 376                 * Hide vma from rmap and truncate_pagecache before freeing
 377                 * pgtables
 378                 */
 379                unlink_anon_vmas(vma);
 380                unlink_file_vma(vma);
 381
 382                if (is_vm_hugetlb_page(vma)) {
 383                        hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
 384                                floor, next ? next->vm_start : ceiling);
 385                } else {
 386                        /*
 387                         * Optimization: gather nearby vmas into one call down
 388                         */
 389                        while (next && next->vm_start <= vma->vm_end + PMD_SIZE
 390                               && !is_vm_hugetlb_page(next)) {
 391                                vma = next;
 392                                next = vma->vm_next;
 393                                unlink_anon_vmas(vma);
 394                                unlink_file_vma(vma);
 395                        }
 396                        free_pgd_range(tlb, addr, vma->vm_end,
 397                                floor, next ? next->vm_start : ceiling);
 398                }
 399                vma = next;
 400        }
 401}
 402
 403int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
 404{
 405        spinlock_t *ptl;
 406        pgtable_t new = pte_alloc_one(mm);
 407        if (!new)
 408                return -ENOMEM;
 409
 410        /*
 411         * Ensure all pte setup (eg. pte page lock and page clearing) are
 412         * visible before the pte is made visible to other CPUs by being
 413         * put into page tables.
 414         *
 415         * The other side of the story is the pointer chasing in the page
 416         * table walking code (when walking the page table without locking;
 417         * ie. most of the time). Fortunately, these data accesses consist
 418         * of a chain of data-dependent loads, meaning most CPUs (alpha
 419         * being the notable exception) will already guarantee loads are
 420         * seen in-order. See the alpha page table accessors for the
 421         * smp_read_barrier_depends() barriers in page table walking code.
 422         */
 423        smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
 424
 425        ptl = pmd_lock(mm, pmd);
 426        if (likely(pmd_none(*pmd))) {   /* Has another populated it ? */
 427                mm_inc_nr_ptes(mm);
 428                pmd_populate(mm, pmd, new);
 429                new = NULL;
 430        }
 431        spin_unlock(ptl);
 432        if (new)
 433                pte_free(mm, new);
 434        return 0;
 435}
 436
 437int __pte_alloc_kernel(pmd_t *pmd)
 438{
 439        pte_t *new = pte_alloc_one_kernel(&init_mm);
 440        if (!new)
 441                return -ENOMEM;
 442
 443        smp_wmb(); /* See comment in __pte_alloc */
 444
 445        spin_lock(&init_mm.page_table_lock);
 446        if (likely(pmd_none(*pmd))) {   /* Has another populated it ? */
 447                pmd_populate_kernel(&init_mm, pmd, new);
 448                new = NULL;
 449        }
 450        spin_unlock(&init_mm.page_table_lock);
 451        if (new)
 452                pte_free_kernel(&init_mm, new);
 453        return 0;
 454}
 455
 456static inline void init_rss_vec(int *rss)
 457{
 458        memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
 459}
 460
 461static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
 462{
 463        int i;
 464
 465        if (current->mm == mm)
 466                sync_mm_rss(mm);
 467        for (i = 0; i < NR_MM_COUNTERS; i++)
 468                if (rss[i])
 469                        add_mm_counter(mm, i, rss[i]);
 470}
 471
 472/*
 473 * This function is called to print an error when a bad pte
 474 * is found. For example, we might have a PFN-mapped pte in
 475 * a region that doesn't allow it.
 476 *
 477 * The calling function must still handle the error.
 478 */
 479static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
 480                          pte_t pte, struct page *page)
 481{
 482        pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
 483        p4d_t *p4d = p4d_offset(pgd, addr);
 484        pud_t *pud = pud_offset(p4d, addr);
 485        pmd_t *pmd = pmd_offset(pud, addr);
 486        struct address_space *mapping;
 487        pgoff_t index;
 488        static unsigned long resume;
 489        static unsigned long nr_shown;
 490        static unsigned long nr_unshown;
 491
 492        /*
 493         * Allow a burst of 60 reports, then keep quiet for that minute;
 494         * or allow a steady drip of one report per second.
 495         */
 496        if (nr_shown == 60) {
 497                if (time_before(jiffies, resume)) {
 498                        nr_unshown++;
 499                        return;
 500                }
 501                if (nr_unshown) {
 502                        pr_alert("BUG: Bad page map: %lu messages suppressed\n",
 503                                 nr_unshown);
 504                        nr_unshown = 0;
 505                }
 506                nr_shown = 0;
 507        }
 508        if (nr_shown++ == 0)
 509                resume = jiffies + 60 * HZ;
 510
 511        mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
 512        index = linear_page_index(vma, addr);
 513
 514        pr_alert("BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
 515                 current->comm,
 516                 (long long)pte_val(pte), (long long)pmd_val(*pmd));
 517        if (page)
 518                dump_page(page, "bad pte");
 519        pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
 520                 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
 521        pr_alert("file:%pD fault:%ps mmap:%ps readpage:%ps\n",
 522                 vma->vm_file,
 523                 vma->vm_ops ? vma->vm_ops->fault : NULL,
 524                 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
 525                 mapping ? mapping->a_ops->readpage : NULL);
 526        dump_stack();
 527        add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
 528}
 529
 530/*
 531 * vm_normal_page -- This function gets the "struct page" associated with a pte.
 532 *
 533 * "Special" mappings do not wish to be associated with a "struct page" (either
 534 * it doesn't exist, or it exists but they don't want to touch it). In this
 535 * case, NULL is returned here. "Normal" mappings do have a struct page.
 536 *
 537 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
 538 * pte bit, in which case this function is trivial. Secondly, an architecture
 539 * may not have a spare pte bit, which requires a more complicated scheme,
 540 * described below.
 541 *
 542 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
 543 * special mapping (even if there are underlying and valid "struct pages").
 544 * COWed pages of a VM_PFNMAP are always normal.
 545 *
 546 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
 547 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
 548 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
 549 * mapping will always honor the rule
 550 *
 551 *      pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
 552 *
 553 * And for normal mappings this is false.
 554 *
 555 * This restricts such mappings to be a linear translation from virtual address
 556 * to pfn. To get around this restriction, we allow arbitrary mappings so long
 557 * as the vma is not a COW mapping; in that case, we know that all ptes are
 558 * special (because none can have been COWed).
 559 *
 560 *
 561 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
 562 *
 563 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
 564 * page" backing, however the difference is that _all_ pages with a struct
 565 * page (that is, those where pfn_valid is true) are refcounted and considered
 566 * normal pages by the VM. The disadvantage is that pages are refcounted
 567 * (which can be slower and simply not an option for some PFNMAP users). The
 568 * advantage is that we don't have to follow the strict linearity rule of
 569 * PFNMAP mappings in order to support COWable mappings.
 570 *
 571 */
 572struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
 573                            pte_t pte)
 574{
 575        unsigned long pfn = pte_pfn(pte);
 576
 577        if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
 578                if (likely(!pte_special(pte)))
 579                        goto check_pfn;
 580                if (vma->vm_ops && vma->vm_ops->find_special_page)
 581                        return vma->vm_ops->find_special_page(vma, addr);
 582                if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
 583                        return NULL;
 584                if (is_zero_pfn(pfn))
 585                        return NULL;
 586                if (pte_devmap(pte))
 587                        return NULL;
 588
 589                print_bad_pte(vma, addr, pte, NULL);
 590                return NULL;
 591        }
 592
 593        /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
 594
 595        if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
 596                if (vma->vm_flags & VM_MIXEDMAP) {
 597                        if (!pfn_valid(pfn))
 598                                return NULL;
 599                        goto out;
 600                } else {
 601                        unsigned long off;
 602                        off = (addr - vma->vm_start) >> PAGE_SHIFT;
 603                        if (pfn == vma->vm_pgoff + off)
 604                                return NULL;
 605                        if (!is_cow_mapping(vma->vm_flags))
 606                                return NULL;
 607                }
 608        }
 609
 610        if (is_zero_pfn(pfn))
 611                return NULL;
 612
 613check_pfn:
 614        if (unlikely(pfn > highest_memmap_pfn)) {
 615                print_bad_pte(vma, addr, pte, NULL);
 616                return NULL;
 617        }
 618
 619        /*
 620         * NOTE! We still have PageReserved() pages in the page tables.
 621         * eg. VDSO mappings can cause them to exist.
 622         */
 623out:
 624        return pfn_to_page(pfn);
 625}
 626
 627#ifdef CONFIG_TRANSPARENT_HUGEPAGE
 628struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
 629                                pmd_t pmd)
 630{
 631        unsigned long pfn = pmd_pfn(pmd);
 632
 633        /*
 634         * There is no pmd_special() but there may be special pmds, e.g.
 635         * in a direct-access (dax) mapping, so let's just replicate the
 636         * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
 637         */
 638        if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
 639                if (vma->vm_flags & VM_MIXEDMAP) {
 640                        if (!pfn_valid(pfn))
 641                                return NULL;
 642                        goto out;
 643                } else {
 644                        unsigned long off;
 645                        off = (addr - vma->vm_start) >> PAGE_SHIFT;
 646                        if (pfn == vma->vm_pgoff + off)
 647                                return NULL;
 648                        if (!is_cow_mapping(vma->vm_flags))
 649                                return NULL;
 650                }
 651        }
 652
 653        if (pmd_devmap(pmd))
 654                return NULL;
 655        if (is_zero_pfn(pfn))
 656                return NULL;
 657        if (unlikely(pfn > highest_memmap_pfn))
 658                return NULL;
 659
 660        /*
 661         * NOTE! We still have PageReserved() pages in the page tables.
 662         * eg. VDSO mappings can cause them to exist.
 663         */
 664out:
 665        return pfn_to_page(pfn);
 666}
 667#endif
 668
 669/*
 670 * copy one vm_area from one task to the other. Assumes the page tables
 671 * already present in the new task to be cleared in the whole range
 672 * covered by this vma.
 673 */
 674
 675static unsigned long
 676copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
 677                pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
 678                unsigned long addr, int *rss)
 679{
 680        unsigned long vm_flags = vma->vm_flags;
 681        pte_t pte = *src_pte;
 682        struct page *page;
 683        swp_entry_t entry = pte_to_swp_entry(pte);
 684
 685        if (likely(!non_swap_entry(entry))) {
 686                if (swap_duplicate(entry) < 0)
 687                        return entry.val;
 688
 689                /* make sure dst_mm is on swapoff's mmlist. */
 690                if (unlikely(list_empty(&dst_mm->mmlist))) {
 691                        spin_lock(&mmlist_lock);
 692                        if (list_empty(&dst_mm->mmlist))
 693                                list_add(&dst_mm->mmlist,
 694                                                &src_mm->mmlist);
 695                        spin_unlock(&mmlist_lock);
 696                }
 697                rss[MM_SWAPENTS]++;
 698        } else if (is_migration_entry(entry)) {
 699                page = migration_entry_to_page(entry);
 700
 701                rss[mm_counter(page)]++;
 702
 703                if (is_write_migration_entry(entry) &&
 704                                is_cow_mapping(vm_flags)) {
 705                        /*
 706                         * COW mappings require pages in both
 707                         * parent and child to be set to read.
 708                         */
 709                        make_migration_entry_read(&entry);
 710                        pte = swp_entry_to_pte(entry);
 711                        if (pte_swp_soft_dirty(*src_pte))
 712                                pte = pte_swp_mksoft_dirty(pte);
 713                        if (pte_swp_uffd_wp(*src_pte))
 714                                pte = pte_swp_mkuffd_wp(pte);
 715                        set_pte_at(src_mm, addr, src_pte, pte);
 716                }
 717        } else if (is_device_private_entry(entry)) {
 718                page = device_private_entry_to_page(entry);
 719
 720                /*
 721                 * Update rss count even for unaddressable pages, as
 722                 * they should treated just like normal pages in this
 723                 * respect.
 724                 *
 725                 * We will likely want to have some new rss counters
 726                 * for unaddressable pages, at some point. But for now
 727                 * keep things as they are.
 728                 */
 729                get_page(page);
 730                rss[mm_counter(page)]++;
 731                page_dup_rmap(page, false);
 732
 733                /*
 734                 * We do not preserve soft-dirty information, because so
 735                 * far, checkpoint/restore is the only feature that
 736                 * requires that. And checkpoint/restore does not work
 737                 * when a device driver is involved (you cannot easily
 738                 * save and restore device driver state).
 739                 */
 740                if (is_write_device_private_entry(entry) &&
 741                    is_cow_mapping(vm_flags)) {
 742                        make_device_private_entry_read(&entry);
 743                        pte = swp_entry_to_pte(entry);
 744                        if (pte_swp_uffd_wp(*src_pte))
 745                                pte = pte_swp_mkuffd_wp(pte);
 746                        set_pte_at(src_mm, addr, src_pte, pte);
 747                }
 748        }
 749        set_pte_at(dst_mm, addr, dst_pte, pte);
 750        return 0;
 751}
 752
 753/*
 754 * Copy a present and normal page if necessary.
 755 *
 756 * NOTE! The usual case is that this doesn't need to do
 757 * anything, and can just return a positive value. That
 758 * will let the caller know that it can just increase
 759 * the page refcount and re-use the pte the traditional
 760 * way.
 761 *
 762 * But _if_ we need to copy it because it needs to be
 763 * pinned in the parent (and the child should get its own
 764 * copy rather than just a reference to the same page),
 765 * we'll do that here and return zero to let the caller
 766 * know we're done.
 767 *
 768 * And if we need a pre-allocated page but don't yet have
 769 * one, return a negative error to let the preallocation
 770 * code know so that it can do so outside the page table
 771 * lock.
 772 */
 773static inline int
 774copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
 775                  pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
 776                  struct page **prealloc, pte_t pte, struct page *page)
 777{
 778        struct page *new_page;
 779
 780        /*
 781         * What we want to do is to check whether this page may
 782         * have been pinned by the parent process.  If so,
 783         * instead of wrprotect the pte on both sides, we copy
 784         * the page immediately so that we'll always guarantee
 785         * the pinned page won't be randomly replaced in the
 786         * future.
 787         *
 788         * The page pinning checks are just "has this mm ever
 789         * seen pinning", along with the (inexact) check of
 790         * the page count. That might give false positives for
 791         * for pinning, but it will work correctly.
 792         */
 793        if (likely(!page_needs_cow_for_dma(src_vma, page)))
 794                return 1;
 795
 796        new_page = *prealloc;
 797        if (!new_page)
 798                return -EAGAIN;
 799
 800        /*
 801         * We have a prealloc page, all good!  Take it
 802         * over and copy the page & arm it.
 803         */
 804        *prealloc = NULL;
 805        copy_user_highpage(new_page, page, addr, src_vma);
 806        __SetPageUptodate(new_page);
 807        page_add_new_anon_rmap(new_page, dst_vma, addr, false);
 808        lru_cache_add_inactive_or_unevictable(new_page, dst_vma);
 809        rss[mm_counter(new_page)]++;
 810
 811        /* All done, just insert the new page copy in the child */
 812        pte = mk_pte(new_page, dst_vma->vm_page_prot);
 813        pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
 814        set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
 815        return 0;
 816}
 817
 818/*
 819 * Copy one pte.  Returns 0 if succeeded, or -EAGAIN if one preallocated page
 820 * is required to copy this pte.
 821 */
 822static inline int
 823copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
 824                 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
 825                 struct page **prealloc)
 826{
 827        struct mm_struct *src_mm = src_vma->vm_mm;
 828        unsigned long vm_flags = src_vma->vm_flags;
 829        pte_t pte = *src_pte;
 830        struct page *page;
 831
 832        page = vm_normal_page(src_vma, addr, pte);
 833        if (page) {
 834                int retval;
 835
 836                retval = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
 837                                           addr, rss, prealloc, pte, page);
 838                if (retval <= 0)
 839                        return retval;
 840
 841                get_page(page);
 842                page_dup_rmap(page, false);
 843                rss[mm_counter(page)]++;
 844        }
 845
 846        /*
 847         * If it's a COW mapping, write protect it both
 848         * in the parent and the child
 849         */
 850        if (is_cow_mapping(vm_flags) && pte_write(pte)) {
 851                ptep_set_wrprotect(src_mm, addr, src_pte);
 852                pte = pte_wrprotect(pte);
 853        }
 854
 855        /*
 856         * If it's a shared mapping, mark it clean in
 857         * the child
 858         */
 859        if (vm_flags & VM_SHARED)
 860                pte = pte_mkclean(pte);
 861        pte = pte_mkold(pte);
 862
 863        /*
 864         * Make sure the _PAGE_UFFD_WP bit is cleared if the new VMA
 865         * does not have the VM_UFFD_WP, which means that the uffd
 866         * fork event is not enabled.
 867         */
 868        if (!(vm_flags & VM_UFFD_WP))
 869                pte = pte_clear_uffd_wp(pte);
 870
 871        set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
 872        return 0;
 873}
 874
 875static inline struct page *
 876page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma,
 877                   unsigned long addr)
 878{
 879        struct page *new_page;
 880
 881        new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr);
 882        if (!new_page)
 883                return NULL;
 884
 885        if (mem_cgroup_charge(new_page, src_mm, GFP_KERNEL)) {
 886                put_page(new_page);
 887                return NULL;
 888        }
 889        cgroup_throttle_swaprate(new_page, GFP_KERNEL);
 890
 891        return new_page;
 892}
 893
 894static int
 895copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
 896               pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
 897               unsigned long end)
 898{
 899        struct mm_struct *dst_mm = dst_vma->vm_mm;
 900        struct mm_struct *src_mm = src_vma->vm_mm;
 901        pte_t *orig_src_pte, *orig_dst_pte;
 902        pte_t *src_pte, *dst_pte;
 903        spinlock_t *src_ptl, *dst_ptl;
 904        int progress, ret = 0;
 905        int rss[NR_MM_COUNTERS];
 906        swp_entry_t entry = (swp_entry_t){0};
 907        struct page *prealloc = NULL;
 908
 909again:
 910        progress = 0;
 911        init_rss_vec(rss);
 912
 913        dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
 914        if (!dst_pte) {
 915                ret = -ENOMEM;
 916                goto out;
 917        }
 918        src_pte = pte_offset_map(src_pmd, addr);
 919        src_ptl = pte_lockptr(src_mm, src_pmd);
 920        spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
 921        orig_src_pte = src_pte;
 922        orig_dst_pte = dst_pte;
 923        arch_enter_lazy_mmu_mode();
 924
 925        do {
 926                /*
 927                 * We are holding two locks at this point - either of them
 928                 * could generate latencies in another task on another CPU.
 929                 */
 930                if (progress >= 32) {
 931                        progress = 0;
 932                        if (need_resched() ||
 933                            spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
 934                                break;
 935                }
 936                if (pte_none(*src_pte)) {
 937                        progress++;
 938                        continue;
 939                }
 940                if (unlikely(!pte_present(*src_pte))) {
 941                        entry.val = copy_nonpresent_pte(dst_mm, src_mm,
 942                                                        dst_pte, src_pte,
 943                                                        src_vma, addr, rss);
 944                        if (entry.val)
 945                                break;
 946                        progress += 8;
 947                        continue;
 948                }
 949                /* copy_present_pte() will clear `*prealloc' if consumed */
 950                ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte,
 951                                       addr, rss, &prealloc);
 952                /*
 953                 * If we need a pre-allocated page for this pte, drop the
 954                 * locks, allocate, and try again.
 955                 */
 956                if (unlikely(ret == -EAGAIN))
 957                        break;
 958                if (unlikely(prealloc)) {
 959                        /*
 960                         * pre-alloc page cannot be reused by next time so as
 961                         * to strictly follow mempolicy (e.g., alloc_page_vma()
 962                         * will allocate page according to address).  This
 963                         * could only happen if one pinned pte changed.
 964                         */
 965                        put_page(prealloc);
 966                        prealloc = NULL;
 967                }
 968                progress += 8;
 969        } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
 970
 971        arch_leave_lazy_mmu_mode();
 972        spin_unlock(src_ptl);
 973        pte_unmap(orig_src_pte);
 974        add_mm_rss_vec(dst_mm, rss);
 975        pte_unmap_unlock(orig_dst_pte, dst_ptl);
 976        cond_resched();
 977
 978        if (entry.val) {
 979                if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
 980                        ret = -ENOMEM;
 981                        goto out;
 982                }
 983                entry.val = 0;
 984        } else if (ret) {
 985                WARN_ON_ONCE(ret != -EAGAIN);
 986                prealloc = page_copy_prealloc(src_mm, src_vma, addr);
 987                if (!prealloc)
 988                        return -ENOMEM;
 989                /* We've captured and resolved the error. Reset, try again. */
 990                ret = 0;
 991        }
 992        if (addr != end)
 993                goto again;
 994out:
 995        if (unlikely(prealloc))
 996                put_page(prealloc);
 997        return ret;
 998}
 999
1000static inline int
1001copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1002               pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1003               unsigned long end)
1004{
1005        struct mm_struct *dst_mm = dst_vma->vm_mm;
1006        struct mm_struct *src_mm = src_vma->vm_mm;
1007        pmd_t *src_pmd, *dst_pmd;
1008        unsigned long next;
1009
1010        dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1011        if (!dst_pmd)
1012                return -ENOMEM;
1013        src_pmd = pmd_offset(src_pud, addr);
1014        do {
1015                next = pmd_addr_end(addr, end);
1016                if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1017                        || pmd_devmap(*src_pmd)) {
1018                        int err;
1019                        VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1020                        err = copy_huge_pmd(dst_mm, src_mm,
1021                                            dst_pmd, src_pmd, addr, src_vma);
1022                        if (err == -ENOMEM)
1023                                return -ENOMEM;
1024                        if (!err)
1025                                continue;
1026                        /* fall through */
1027                }
1028                if (pmd_none_or_clear_bad(src_pmd))
1029                        continue;
1030                if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1031                                   addr, next))
1032                        return -ENOMEM;
1033        } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1034        return 0;
1035}
1036
1037static inline int
1038copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1039               p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1040               unsigned long end)
1041{
1042        struct mm_struct *dst_mm = dst_vma->vm_mm;
1043        struct mm_struct *src_mm = src_vma->vm_mm;
1044        pud_t *src_pud, *dst_pud;
1045        unsigned long next;
1046
1047        dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1048        if (!dst_pud)
1049                return -ENOMEM;
1050        src_pud = pud_offset(src_p4d, addr);
1051        do {
1052                next = pud_addr_end(addr, end);
1053                if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1054                        int err;
1055
1056                        VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1057                        err = copy_huge_pud(dst_mm, src_mm,
1058                                            dst_pud, src_pud, addr, src_vma);
1059                        if (err == -ENOMEM)
1060                                return -ENOMEM;
1061                        if (!err)
1062                                continue;
1063                        /* fall through */
1064                }
1065                if (pud_none_or_clear_bad(src_pud))
1066                        continue;
1067                if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1068                                   addr, next))
1069                        return -ENOMEM;
1070        } while (dst_pud++, src_pud++, addr = next, addr != end);
1071        return 0;
1072}
1073
1074static inline int
1075copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1076               pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1077               unsigned long end)
1078{
1079        struct mm_struct __maybe_unused *dst_mm = dst_vma->vm_mm;
1080        p4d_t *src_p4d, *dst_p4d;
1081        unsigned long next;
1082
1083        dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1084        if (!dst_p4d)
1085                return -ENOMEM;
1086        src_p4d = p4d_offset(src_pgd, addr);
1087        do {
1088                next = p4d_addr_end(addr, end);
1089                if (p4d_none_or_clear_bad(src_p4d))
1090                        continue;
1091                if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1092                                   addr, next))
1093                        return -ENOMEM;
1094        } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1095        return 0;
1096}
1097
1098int
1099copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1100{
1101        pgd_t *src_pgd, *dst_pgd;
1102        unsigned long next;
1103        unsigned long addr = src_vma->vm_start;
1104        unsigned long end = src_vma->vm_end;
1105        struct mm_struct *dst_mm = dst_vma->vm_mm;
1106        struct mm_struct *src_mm = src_vma->vm_mm;
1107        struct mmu_notifier_range range;
1108        bool is_cow;
1109        int ret;
1110
1111        /*
1112         * Don't copy ptes where a page fault will fill them correctly.
1113         * Fork becomes much lighter when there are big shared or private
1114         * readonly mappings. The tradeoff is that copy_page_range is more
1115         * efficient than faulting.
1116         */
1117        if (!(src_vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1118            !src_vma->anon_vma)
1119                return 0;
1120
1121        if (is_vm_hugetlb_page(src_vma))
1122                return copy_hugetlb_page_range(dst_mm, src_mm, src_vma);
1123
1124        if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1125                /*
1126                 * We do not free on error cases below as remove_vma
1127                 * gets called on error from higher level routine
1128                 */
1129                ret = track_pfn_copy(src_vma);
1130                if (ret)
1131                        return ret;
1132        }
1133
1134        /*
1135         * We need to invalidate the secondary MMU mappings only when
1136         * there could be a permission downgrade on the ptes of the
1137         * parent mm. And a permission downgrade will only happen if
1138         * is_cow_mapping() returns true.
1139         */
1140        is_cow = is_cow_mapping(src_vma->vm_flags);
1141
1142        if (is_cow) {
1143                mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1144                                        0, src_vma, src_mm, addr, end);
1145                mmu_notifier_invalidate_range_start(&range);
1146                /*
1147                 * Disabling preemption is not needed for the write side, as
1148                 * the read side doesn't spin, but goes to the mmap_lock.
1149                 *
1150                 * Use the raw variant of the seqcount_t write API to avoid
1151                 * lockdep complaining about preemptibility.
1152                 */
1153                mmap_assert_write_locked(src_mm);
1154                raw_write_seqcount_begin(&src_mm->write_protect_seq);
1155        }
1156
1157        ret = 0;
1158        dst_pgd = pgd_offset(dst_mm, addr);
1159        src_pgd = pgd_offset(src_mm, addr);
1160        do {
1161                next = pgd_addr_end(addr, end);
1162                if (pgd_none_or_clear_bad(src_pgd))
1163                        continue;
1164                if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1165                                            addr, next))) {
1166                        ret = -ENOMEM;
1167                        break;
1168                }
1169        } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1170
1171        if (is_cow) {
1172                raw_write_seqcount_end(&src_mm->write_protect_seq);
1173                mmu_notifier_invalidate_range_end(&range);
1174        }
1175        return ret;
1176}
1177
1178static unsigned long zap_pte_range(struct mmu_gather *tlb,
1179                                struct vm_area_struct *vma, pmd_t *pmd,
1180                                unsigned long addr, unsigned long end,
1181                                struct zap_details *details)
1182{
1183        struct mm_struct *mm = tlb->mm;
1184        int force_flush = 0;
1185        int rss[NR_MM_COUNTERS];
1186        spinlock_t *ptl;
1187        pte_t *start_pte;
1188        pte_t *pte;
1189        swp_entry_t entry;
1190
1191        tlb_change_page_size(tlb, PAGE_SIZE);
1192again:
1193        init_rss_vec(rss);
1194        start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1195        pte = start_pte;
1196        flush_tlb_batched_pending(mm);
1197        arch_enter_lazy_mmu_mode();
1198        do {
1199                pte_t ptent = *pte;
1200                if (pte_none(ptent))
1201                        continue;
1202
1203                if (pte_present(ptent)) {
1204                        struct page *page;
1205
1206                        page = vm_normal_page(vma, addr, ptent);
1207                        if (unlikely(details) && page) {
1208                                /*
1209                                 * unmap_shared_mapping_pages() wants to
1210                                 * invalidate cache without truncating:
1211                                 * unmap shared but keep private pages.
1212                                 */
1213                                if (details->check_mapping &&
1214                                    details->check_mapping != page_rmapping(page))
1215                                        continue;
1216                        }
1217                        ptent = ptep_get_and_clear_full(mm, addr, pte,
1218                                                        tlb->fullmm);
1219                        tlb_remove_tlb_entry(tlb, pte, addr);
1220                        if (unlikely(!page))
1221                                continue;
1222
1223                        if (!PageAnon(page)) {
1224                                if (pte_dirty(ptent)) {
1225                                        force_flush = 1;
1226                                        set_page_dirty(page);
1227                                }
1228                                if (pte_young(ptent) &&
1229                                    likely(!(vma->vm_flags & VM_SEQ_READ)))
1230                                        mark_page_accessed(page);
1231                        }
1232                        rss[mm_counter(page)]--;
1233                        page_remove_rmap(page, false);
1234                        if (unlikely(page_mapcount(page) < 0))
1235                                print_bad_pte(vma, addr, ptent, page);
1236                        if (unlikely(__tlb_remove_page(tlb, page))) {
1237                                force_flush = 1;
1238                                addr += PAGE_SIZE;
1239                                break;
1240                        }
1241                        continue;
1242                }
1243
1244                entry = pte_to_swp_entry(ptent);
1245                if (non_swap_entry(entry) && is_device_private_entry(entry)) {
1246                        struct page *page = device_private_entry_to_page(entry);
1247
1248                        if (unlikely(details && details->check_mapping)) {
1249                                /*
1250                                 * unmap_shared_mapping_pages() wants to
1251                                 * invalidate cache without truncating:
1252                                 * unmap shared but keep private pages.
1253                                 */
1254                                if (details->check_mapping !=
1255                                    page_rmapping(page))
1256                                        continue;
1257                        }
1258
1259                        pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1260                        rss[mm_counter(page)]--;
1261                        page_remove_rmap(page, false);
1262                        put_page(page);
1263                        continue;
1264                }
1265
1266                /* If details->check_mapping, we leave swap entries. */
1267                if (unlikely(details))
1268                        continue;
1269
1270                entry = pte_to_swp_entry(ptent);
1271                if (!non_swap_entry(entry))
1272                        rss[MM_SWAPENTS]--;
1273                else if (is_migration_entry(entry)) {
1274                        struct page *page;
1275
1276                        page = migration_entry_to_page(entry);
1277                        rss[mm_counter(page)]--;
1278                }
1279                if (unlikely(!free_swap_and_cache(entry)))
1280                        print_bad_pte(vma, addr, ptent, NULL);
1281                pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1282        } while (pte++, addr += PAGE_SIZE, addr != end);
1283
1284        add_mm_rss_vec(mm, rss);
1285        arch_leave_lazy_mmu_mode();
1286
1287        /* Do the actual TLB flush before dropping ptl */
1288        if (force_flush)
1289                tlb_flush_mmu_tlbonly(tlb);
1290        pte_unmap_unlock(start_pte, ptl);
1291
1292        /*
1293         * If we forced a TLB flush (either due to running out of
1294         * batch buffers or because we needed to flush dirty TLB
1295         * entries before releasing the ptl), free the batched
1296         * memory too. Restart if we didn't do everything.
1297         */
1298        if (force_flush) {
1299                force_flush = 0;
1300                tlb_flush_mmu(tlb);
1301                if (addr != end)
1302                        goto again;
1303        }
1304
1305        return addr;
1306}
1307
1308static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1309                                struct vm_area_struct *vma, pud_t *pud,
1310                                unsigned long addr, unsigned long end,
1311                                struct zap_details *details)
1312{
1313        pmd_t *pmd;
1314        unsigned long next;
1315
1316        pmd = pmd_offset(pud, addr);
1317        do {
1318                next = pmd_addr_end(addr, end);
1319                if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1320                        if (next - addr != HPAGE_PMD_SIZE)
1321                                __split_huge_pmd(vma, pmd, addr, false, NULL);
1322                        else if (zap_huge_pmd(tlb, vma, pmd, addr))
1323                                goto next;
1324                        /* fall through */
1325                }
1326                /*
1327                 * Here there can be other concurrent MADV_DONTNEED or
1328                 * trans huge page faults running, and if the pmd is
1329                 * none or trans huge it can change under us. This is
1330                 * because MADV_DONTNEED holds the mmap_lock in read
1331                 * mode.
1332                 */
1333                if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1334                        goto next;
1335                next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1336next:
1337                cond_resched();
1338        } while (pmd++, addr = next, addr != end);
1339
1340        return addr;
1341}
1342
1343static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1344                                struct vm_area_struct *vma, p4d_t *p4d,
1345                                unsigned long addr, unsigned long end,
1346                                struct zap_details *details)
1347{
1348        pud_t *pud;
1349        unsigned long next;
1350
1351        pud = pud_offset(p4d, addr);
1352        do {
1353                next = pud_addr_end(addr, end);
1354                if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1355                        if (next - addr != HPAGE_PUD_SIZE) {
1356                                mmap_assert_locked(tlb->mm);
1357                                split_huge_pud(vma, pud, addr);
1358                        } else if (zap_huge_pud(tlb, vma, pud, addr))
1359                                goto next;
1360                        /* fall through */
1361                }
1362                if (pud_none_or_clear_bad(pud))
1363                        continue;
1364                next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1365next:
1366                cond_resched();
1367        } while (pud++, addr = next, addr != end);
1368
1369        return addr;
1370}
1371
1372static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1373                                struct vm_area_struct *vma, pgd_t *pgd,
1374                                unsigned long addr, unsigned long end,
1375                                struct zap_details *details)
1376{
1377        p4d_t *p4d;
1378        unsigned long next;
1379
1380        p4d = p4d_offset(pgd, addr);
1381        do {
1382                next = p4d_addr_end(addr, end);
1383                if (p4d_none_or_clear_bad(p4d))
1384                        continue;
1385                next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1386        } while (p4d++, addr = next, addr != end);
1387
1388        return addr;
1389}
1390
1391void unmap_page_range(struct mmu_gather *tlb,
1392                             struct vm_area_struct *vma,
1393                             unsigned long addr, unsigned long end,
1394                             struct zap_details *details)
1395{
1396        pgd_t *pgd;
1397        unsigned long next;
1398
1399        BUG_ON(addr >= end);
1400        tlb_start_vma(tlb, vma);
1401        pgd = pgd_offset(vma->vm_mm, addr);
1402        do {
1403                next = pgd_addr_end(addr, end);
1404                if (pgd_none_or_clear_bad(pgd))
1405                        continue;
1406                next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1407        } while (pgd++, addr = next, addr != end);
1408        tlb_end_vma(tlb, vma);
1409}
1410
1411
1412static void unmap_single_vma(struct mmu_gather *tlb,
1413                struct vm_area_struct *vma, unsigned long start_addr,
1414                unsigned long end_addr,
1415                struct zap_details *details)
1416{
1417        unsigned long start = max(vma->vm_start, start_addr);
1418        unsigned long end;
1419
1420        if (start >= vma->vm_end)
1421                return;
1422        end = min(vma->vm_end, end_addr);
1423        if (end <= vma->vm_start)
1424                return;
1425
1426        if (vma->vm_file)
1427                uprobe_munmap(vma, start, end);
1428
1429        if (unlikely(vma->vm_flags & VM_PFNMAP))
1430                untrack_pfn(vma, 0, 0);
1431
1432        if (start != end) {
1433                if (unlikely(is_vm_hugetlb_page(vma))) {
1434                        /*
1435                         * It is undesirable to test vma->vm_file as it
1436                         * should be non-null for valid hugetlb area.
1437                         * However, vm_file will be NULL in the error
1438                         * cleanup path of mmap_region. When
1439                         * hugetlbfs ->mmap method fails,
1440                         * mmap_region() nullifies vma->vm_file
1441                         * before calling this function to clean up.
1442                         * Since no pte has actually been setup, it is
1443                         * safe to do nothing in this case.
1444                         */
1445                        if (vma->vm_file) {
1446                                i_mmap_lock_write(vma->vm_file->f_mapping);
1447                                __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1448                                i_mmap_unlock_write(vma->vm_file->f_mapping);
1449                        }
1450                } else
1451                        unmap_page_range(tlb, vma, start, end, details);
1452        }
1453}
1454
1455/**
1456 * unmap_vmas - unmap a range of memory covered by a list of vma's
1457 * @tlb: address of the caller's struct mmu_gather
1458 * @vma: the starting vma
1459 * @start_addr: virtual address at which to start unmapping
1460 * @end_addr: virtual address at which to end unmapping
1461 *
1462 * Unmap all pages in the vma list.
1463 *
1464 * Only addresses between `start' and `end' will be unmapped.
1465 *
1466 * The VMA list must be sorted in ascending virtual address order.
1467 *
1468 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1469 * range after unmap_vmas() returns.  So the only responsibility here is to
1470 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1471 * drops the lock and schedules.
1472 */
1473void unmap_vmas(struct mmu_gather *tlb,
1474                struct vm_area_struct *vma, unsigned long start_addr,
1475                unsigned long end_addr)
1476{
1477        struct mmu_notifier_range range;
1478
1479        mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1480                                start_addr, end_addr);
1481        mmu_notifier_invalidate_range_start(&range);
1482        for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1483                unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1484        mmu_notifier_invalidate_range_end(&range);
1485}
1486
1487/**
1488 * zap_page_range - remove user pages in a given range
1489 * @vma: vm_area_struct holding the applicable pages
1490 * @start: starting address of pages to zap
1491 * @size: number of bytes to zap
1492 *
1493 * Caller must protect the VMA list
1494 */
1495void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1496                unsigned long size)
1497{
1498        struct mmu_notifier_range range;
1499        struct mmu_gather tlb;
1500
1501        lru_add_drain();
1502        mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1503                                start, start + size);
1504        tlb_gather_mmu(&tlb, vma->vm_mm, start, range.end);
1505        update_hiwater_rss(vma->vm_mm);
1506        mmu_notifier_invalidate_range_start(&range);
1507        for ( ; vma && vma->vm_start < range.end; vma = vma->vm_next)
1508                unmap_single_vma(&tlb, vma, start, range.end, NULL);
1509        mmu_notifier_invalidate_range_end(&range);
1510        tlb_finish_mmu(&tlb, start, range.end);
1511}
1512
1513/**
1514 * zap_page_range_single - remove user pages in a given range
1515 * @vma: vm_area_struct holding the applicable pages
1516 * @address: starting address of pages to zap
1517 * @size: number of bytes to zap
1518 * @details: details of shared cache invalidation
1519 *
1520 * The range must fit into one VMA.
1521 */
1522static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1523                unsigned long size, struct zap_details *details)
1524{
1525        struct mmu_notifier_range range;
1526        struct mmu_gather tlb;
1527
1528        lru_add_drain();
1529        mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1530                                address, address + size);
1531        tlb_gather_mmu(&tlb, vma->vm_mm, address, range.end);
1532        update_hiwater_rss(vma->vm_mm);
1533        mmu_notifier_invalidate_range_start(&range);
1534        unmap_single_vma(&tlb, vma, address, range.end, details);
1535        mmu_notifier_invalidate_range_end(&range);
1536        tlb_finish_mmu(&tlb, address, range.end);
1537}
1538
1539/**
1540 * zap_vma_ptes - remove ptes mapping the vma
1541 * @vma: vm_area_struct holding ptes to be zapped
1542 * @address: starting address of pages to zap
1543 * @size: number of bytes to zap
1544 *
1545 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1546 *
1547 * The entire address range must be fully contained within the vma.
1548 *
1549 */
1550void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1551                unsigned long size)
1552{
1553        if (address < vma->vm_start || address + size > vma->vm_end ||
1554                        !(vma->vm_flags & VM_PFNMAP))
1555                return;
1556
1557        zap_page_range_single(vma, address, size, NULL);
1558}
1559EXPORT_SYMBOL_GPL(zap_vma_ptes);
1560
1561pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1562                        spinlock_t **ptl)
1563{
1564        pgd_t *pgd;
1565        p4d_t *p4d;
1566        pud_t *pud;
1567        pmd_t *pmd;
1568
1569        pgd = pgd_offset(mm, addr);
1570        p4d = p4d_alloc(mm, pgd, addr);
1571        if (!p4d)
1572                return NULL;
1573        pud = pud_alloc(mm, p4d, addr);
1574        if (!pud)
1575                return NULL;
1576        pmd = pmd_alloc(mm, pud, addr);
1577        if (!pmd)
1578                return NULL;
1579
1580        VM_BUG_ON(pmd_trans_huge(*pmd));
1581        return pte_alloc_map_lock(mm, pmd, addr, ptl);
1582}
1583
1584/*
1585 * This is the old fallback for page remapping.
1586 *
1587 * For historical reasons, it only allows reserved pages. Only
1588 * old drivers should use this, and they needed to mark their
1589 * pages reserved for the old functions anyway.
1590 */
1591static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1592                        struct page *page, pgprot_t prot)
1593{
1594        struct mm_struct *mm = vma->vm_mm;
1595        int retval;
1596        pte_t *pte;
1597        spinlock_t *ptl;
1598
1599        retval = -EINVAL;
1600        if (PageAnon(page))
1601                goto out;
1602        retval = -ENOMEM;
1603        flush_dcache_page(page);
1604        pte = get_locked_pte(mm, addr, &ptl);
1605        if (!pte)
1606                goto out;
1607        retval = -EBUSY;
1608        if (!pte_none(*pte))
1609                goto out_unlock;
1610
1611        /* Ok, finally just insert the thing.. */
1612        get_page(page);
1613        inc_mm_counter_fast(mm, mm_counter_file(page));
1614        page_add_file_rmap(page, false);
1615        set_pte_at(mm, addr, pte, mk_pte(page, prot));
1616
1617        retval = 0;
1618        pte_unmap_unlock(pte, ptl);
1619        return retval;
1620out_unlock:
1621        pte_unmap_unlock(pte, ptl);
1622out:
1623        return retval;
1624}
1625
1626/**
1627 * vm_insert_page - insert single page into user vma
1628 * @vma: user vma to map to
1629 * @addr: target user address of this page
1630 * @page: source kernel page
1631 *
1632 * This allows drivers to insert individual pages they've allocated
1633 * into a user vma.
1634 *
1635 * The page has to be a nice clean _individual_ kernel allocation.
1636 * If you allocate a compound page, you need to have marked it as
1637 * such (__GFP_COMP), or manually just split the page up yourself
1638 * (see split_page()).
1639 *
1640 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1641 * took an arbitrary page protection parameter. This doesn't allow
1642 * that. Your vma protection will have to be set up correctly, which
1643 * means that if you want a shared writable mapping, you'd better
1644 * ask for a shared writable mapping!
1645 *
1646 * The page does not need to be reserved.
1647 *
1648 * Usually this function is called from f_op->mmap() handler
1649 * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
1650 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1651 * function from other places, for example from page-fault handler.
1652 *
1653 * Return: %0 on success, negative error code otherwise.
1654 */
1655int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1656                        struct page *page)
1657{
1658        if (addr < vma->vm_start || addr >= vma->vm_end)
1659                return -EFAULT;
1660        if (!page_count(page))
1661                return -EINVAL;
1662        if (!(vma->vm_flags & VM_MIXEDMAP)) {
1663                BUG_ON(mmap_read_trylock(vma->vm_mm));
1664                BUG_ON(vma->vm_flags & VM_PFNMAP);
1665                vma->vm_flags |= VM_MIXEDMAP;
1666        }
1667        return insert_page(vma, addr, page, vma->vm_page_prot);
1668}
1669EXPORT_SYMBOL(vm_insert_page);
1670
1671/*
1672 * __vm_map_pages - maps range of kernel pages into user vma
1673 * @vma: user vma to map to
1674 * @pages: pointer to array of source kernel pages
1675 * @num: number of pages in page array
1676 * @offset: user's requested vm_pgoff
1677 *
1678 * This allows drivers to map range of kernel pages into a user vma.
1679 *
1680 * Return: 0 on success and error code otherwise.
1681 */
1682static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1683                                unsigned long num, unsigned long offset)
1684{
1685        unsigned long count = vma_pages(vma);
1686        unsigned long uaddr = vma->vm_start;
1687        int ret, i;
1688
1689        /* Fail if the user requested offset is beyond the end of the object */
1690        if (offset > num)
1691                return -ENXIO;
1692
1693        /* Fail if the user requested size exceeds available object size */
1694        if (count > num - offset)
1695                return -ENXIO;
1696
1697        for (i = 0; i < count; i++) {
1698                ret = vm_insert_page(vma, uaddr, pages[offset + i]);
1699                if (ret < 0)
1700                        return ret;
1701                uaddr += PAGE_SIZE;
1702        }
1703
1704        return 0;
1705}
1706
1707/**
1708 * vm_map_pages - maps range of kernel pages starts with non zero offset
1709 * @vma: user vma to map to
1710 * @pages: pointer to array of source kernel pages
1711 * @num: number of pages in page array
1712 *
1713 * Maps an object consisting of @num pages, catering for the user's
1714 * requested vm_pgoff
1715 *
1716 * If we fail to insert any page into the vma, the function will return
1717 * immediately leaving any previously inserted pages present.  Callers
1718 * from the mmap handler may immediately return the error as their caller
1719 * will destroy the vma, removing any successfully inserted pages. Other
1720 * callers should make their own arrangements for calling unmap_region().
1721 *
1722 * Context: Process context. Called by mmap handlers.
1723 * Return: 0 on success and error code otherwise.
1724 */
1725int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1726                                unsigned long num)
1727{
1728        return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
1729}
1730EXPORT_SYMBOL(vm_map_pages);
1731
1732/**
1733 * vm_map_pages_zero - map range of kernel pages starts with zero offset
1734 * @vma: user vma to map to
1735 * @pages: pointer to array of source kernel pages
1736 * @num: number of pages in page array
1737 *
1738 * Similar to vm_map_pages(), except that it explicitly sets the offset
1739 * to 0. This function is intended for the drivers that did not consider
1740 * vm_pgoff.
1741 *
1742 * Context: Process context. Called by mmap handlers.
1743 * Return: 0 on success and error code otherwise.
1744 */
1745int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
1746                                unsigned long num)
1747{
1748        return __vm_map_pages(vma, pages, num, 0);
1749}
1750EXPORT_SYMBOL(vm_map_pages_zero);
1751
1752static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1753                        pfn_t pfn, pgprot_t prot, bool mkwrite)
1754{
1755        struct mm_struct *mm = vma->vm_mm;
1756        int retval;
1757        pte_t *pte, entry;
1758        spinlock_t *ptl;
1759
1760        retval = -ENOMEM;
1761        pte = get_locked_pte(mm, addr, &ptl);
1762        if (!pte)
1763                goto out;
1764        retval = -EBUSY;
1765        if (!pte_none(*pte)) {
1766                if (mkwrite) {
1767                        /*
1768                         * For read faults on private mappings the PFN passed
1769                         * in may not match the PFN we have mapped if the
1770                         * mapped PFN is a writeable COW page.  In the mkwrite
1771                         * case we are creating a writable PTE for a shared
1772                         * mapping and we expect the PFNs to match. If they
1773                         * don't match, we are likely racing with block
1774                         * allocation and mapping invalidation so just skip the
1775                         * update.
1776                         */
1777                        if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
1778                                WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
1779                                goto out_unlock;
1780                        }
1781                        entry = pte_mkyoung(*pte);
1782                        entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1783                        if (ptep_set_access_flags(vma, addr, pte, entry, 1))
1784                                update_mmu_cache(vma, addr, pte);
1785                }
1786                goto out_unlock;
1787        }
1788
1789        /* Ok, finally just insert the thing.. */
1790        if (pfn_t_devmap(pfn))
1791                entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1792        else
1793                entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1794
1795        if (mkwrite) {
1796                entry = pte_mkyoung(entry);
1797                entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1798        }
1799
1800        set_pte_at(mm, addr, pte, entry);
1801        update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1802
1803        retval = 0;
1804out_unlock:
1805        pte_unmap_unlock(pte, ptl);
1806out:
1807        return retval;
1808}
1809
1810/**
1811 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1812 * @vma: user vma to map to
1813 * @addr: target user address of this page
1814 * @pfn: source kernel pfn
1815 * @pgprot: pgprot flags for the inserted page
1816 *
1817 * This is exactly like vmf_insert_pfn(), except that it allows drivers to
1818 * to override pgprot on a per-page basis.
1819 *
1820 * This only makes sense for IO mappings, and it makes no sense for
1821 * COW mappings.  In general, using multiple vmas is preferable;
1822 * vmf_insert_pfn_prot should only be used if using multiple VMAs is
1823 * impractical.
1824 *
1825 * See vmf_insert_mixed_prot() for a discussion of the implication of using
1826 * a value of @pgprot different from that of @vma->vm_page_prot.
1827 *
1828 * Context: Process context.  May allocate using %GFP_KERNEL.
1829 * Return: vm_fault_t value.
1830 */
1831vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1832                        unsigned long pfn, pgprot_t pgprot)
1833{
1834        int err;
1835
1836        /*
1837         * Technically, architectures with pte_special can avoid all these
1838         * restrictions (same for remap_pfn_range).  However we would like
1839         * consistency in testing and feature parity among all, so we should
1840         * try to keep these invariants in place for everybody.
1841         */
1842        BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1843        BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1844                                                (VM_PFNMAP|VM_MIXEDMAP));
1845        BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1846        BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1847
1848        if (addr < vma->vm_start || addr >= vma->vm_end)
1849                return VM_FAULT_SIGBUS;
1850
1851        if (!pfn_modify_allowed(pfn, pgprot))
1852                return VM_FAULT_SIGBUS;
1853
1854        track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
1855
1856        err = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
1857                        false);
1858
1859        if (err == -ENOMEM)
1860                return VM_FAULT_OOM;
1861        if (err < 0 && err != -EBUSY)
1862                return VM_FAULT_SIGBUS;
1863
1864        return VM_FAULT_NOPAGE;
1865}
1866EXPORT_SYMBOL(vmf_insert_pfn_prot);
1867
1868/**
1869 * vmf_insert_pfn - insert single pfn into user vma
1870 * @vma: user vma to map to
1871 * @addr: target user address of this page
1872 * @pfn: source kernel pfn
1873 *
1874 * Similar to vm_insert_page, this allows drivers to insert individual pages
1875 * they've allocated into a user vma. Same comments apply.
1876 *
1877 * This function should only be called from a vm_ops->fault handler, and
1878 * in that case the handler should return the result of this function.
1879 *
1880 * vma cannot be a COW mapping.
1881 *
1882 * As this is called only for pages that do not currently exist, we
1883 * do not need to flush old virtual caches or the TLB.
1884 *
1885 * Context: Process context.  May allocate using %GFP_KERNEL.
1886 * Return: vm_fault_t value.
1887 */
1888vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1889                        unsigned long pfn)
1890{
1891        return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1892}
1893EXPORT_SYMBOL(vmf_insert_pfn);
1894
1895static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
1896{
1897        /* these checks mirror the abort conditions in vm_normal_page */
1898        if (vma->vm_flags & VM_MIXEDMAP)
1899                return true;
1900        if (pfn_t_devmap(pfn))
1901                return true;
1902        if (pfn_t_special(pfn))
1903                return true;
1904        if (is_zero_pfn(pfn_t_to_pfn(pfn)))
1905                return true;
1906        return false;
1907}
1908
1909static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
1910                unsigned long addr, pfn_t pfn, pgprot_t pgprot,
1911                bool mkwrite)
1912{
1913        int err;
1914
1915        BUG_ON(!vm_mixed_ok(vma, pfn));
1916
1917        if (addr < vma->vm_start || addr >= vma->vm_end)
1918                return VM_FAULT_SIGBUS;
1919
1920        track_pfn_insert(vma, &pgprot, pfn);
1921
1922        if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
1923                return VM_FAULT_SIGBUS;
1924
1925        /*
1926         * If we don't have pte special, then we have to use the pfn_valid()
1927         * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1928         * refcount the page if pfn_valid is true (hence insert_page rather
1929         * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
1930         * without pte special, it would there be refcounted as a normal page.
1931         */
1932        if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
1933            !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1934                struct page *page;
1935
1936                /*
1937                 * At this point we are committed to insert_page()
1938                 * regardless of whether the caller specified flags that
1939                 * result in pfn_t_has_page() == false.
1940                 */
1941                page = pfn_to_page(pfn_t_to_pfn(pfn));
1942                err = insert_page(vma, addr, page, pgprot);
1943        } else {
1944                err = insert_pfn(vma, addr, pfn, pgprot, mkwrite);
1945        }
1946
1947        if (err == -ENOMEM)
1948                return VM_FAULT_OOM;
1949        if (err < 0 && err != -EBUSY)
1950                return VM_FAULT_SIGBUS;
1951
1952        return VM_FAULT_NOPAGE;
1953}
1954
1955/**
1956 * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
1957 * @vma: user vma to map to
1958 * @addr: target user address of this page
1959 * @pfn: source kernel pfn
1960 * @pgprot: pgprot flags for the inserted page
1961 *
1962 * This is exactly like vmf_insert_mixed(), except that it allows drivers to
1963 * to override pgprot on a per-page basis.
1964 *
1965 * Typically this function should be used by drivers to set caching- and
1966 * encryption bits different than those of @vma->vm_page_prot, because
1967 * the caching- or encryption mode may not be known at mmap() time.
1968 * This is ok as long as @vma->vm_page_prot is not used by the core vm
1969 * to set caching and encryption bits for those vmas (except for COW pages).
1970 * This is ensured by core vm only modifying these page table entries using
1971 * functions that don't touch caching- or encryption bits, using pte_modify()
1972 * if needed. (See for example mprotect()).
1973 * Also when new page-table entries are created, this is only done using the
1974 * fault() callback, and never using the value of vma->vm_page_prot,
1975 * except for page-table entries that point to anonymous pages as the result
1976 * of COW.
1977 *
1978 * Context: Process context.  May allocate using %GFP_KERNEL.
1979 * Return: vm_fault_t value.
1980 */
1981vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
1982                                 pfn_t pfn, pgprot_t pgprot)
1983{
1984        return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
1985}
1986EXPORT_SYMBOL(vmf_insert_mixed_prot);
1987
1988vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1989                pfn_t pfn)
1990{
1991        return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
1992}
1993EXPORT_SYMBOL(vmf_insert_mixed);
1994
1995/*
1996 *  If the insertion of PTE failed because someone else already added a
1997 *  different entry in the mean time, we treat that as success as we assume
1998 *  the same entry was actually inserted.
1999 */
2000vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2001                unsigned long addr, pfn_t pfn)
2002{
2003        return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2004}
2005EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2006
2007/*
2008 * maps a range of physical memory into the requested pages. the old
2009 * mappings are removed. any references to nonexistent pages results
2010 * in null mappings (currently treated as "copy-on-access")
2011 */
2012static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2013                        unsigned long addr, unsigned long end,
2014                        unsigned long pfn, pgprot_t prot)
2015{
2016        pte_t *pte, *mapped_pte;
2017        spinlock_t *ptl;
2018        int err = 0;
2019
2020        mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2021        if (!pte)
2022                return -ENOMEM;
2023        arch_enter_lazy_mmu_mode();
2024        do {
2025                BUG_ON(!pte_none(*pte));
2026                if (!pfn_modify_allowed(pfn, prot)) {
2027                        err = -EACCES;
2028                        break;
2029                }
2030                set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2031                pfn++;
2032        } while (pte++, addr += PAGE_SIZE, addr != end);
2033        arch_leave_lazy_mmu_mode();
2034        pte_unmap_unlock(mapped_pte, ptl);
2035        return err;
2036}
2037
2038static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2039                        unsigned long addr, unsigned long end,
2040                        unsigned long pfn, pgprot_t prot)
2041{
2042        pmd_t *pmd;
2043        unsigned long next;
2044        int err;
2045
2046        pfn -= addr >> PAGE_SHIFT;
2047        pmd = pmd_alloc(mm, pud, addr);
2048        if (!pmd)
2049                return -ENOMEM;
2050        VM_BUG_ON(pmd_trans_huge(*pmd));
2051        do {
2052                next = pmd_addr_end(addr, end);
2053                err = remap_pte_range(mm, pmd, addr, next,
2054                                pfn + (addr >> PAGE_SHIFT), prot);
2055                if (err)
2056                        return err;
2057        } while (pmd++, addr = next, addr != end);
2058        return 0;
2059}
2060
2061static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2062                        unsigned long addr, unsigned long end,
2063                        unsigned long pfn, pgprot_t prot)
2064{
2065        pud_t *pud;
2066        unsigned long next;
2067        int err;
2068
2069        pfn -= addr >> PAGE_SHIFT;
2070        pud = pud_alloc(mm, p4d, addr);
2071        if (!pud)
2072                return -ENOMEM;
2073        do {
2074                next = pud_addr_end(addr, end);
2075                err = remap_pmd_range(mm, pud, addr, next,
2076                                pfn + (addr >> PAGE_SHIFT), prot);
2077                if (err)
2078                        return err;
2079        } while (pud++, addr = next, addr != end);
2080        return 0;
2081}
2082
2083static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2084                        unsigned long addr, unsigned long end,
2085                        unsigned long pfn, pgprot_t prot)
2086{
2087        p4d_t *p4d;
2088        unsigned long next;
2089        int err;
2090
2091        pfn -= addr >> PAGE_SHIFT;
2092        p4d = p4d_alloc(mm, pgd, addr);
2093        if (!p4d)
2094                return -ENOMEM;
2095        do {
2096                next = p4d_addr_end(addr, end);
2097                err = remap_pud_range(mm, p4d, addr, next,
2098                                pfn + (addr >> PAGE_SHIFT), prot);
2099                if (err)
2100                        return err;
2101        } while (p4d++, addr = next, addr != end);
2102        return 0;
2103}
2104
2105/**
2106 * remap_pfn_range - remap kernel memory to userspace
2107 * @vma: user vma to map to
2108 * @addr: target user address to start at
2109 * @pfn: physical address of kernel memory
2110 * @size: size of map area
2111 * @prot: page protection flags for this mapping
2112 *
2113 * Note: this is only safe if the mm semaphore is held when called.
2114 *
2115 * Return: %0 on success, negative error code otherwise.
2116 */
2117int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2118                    unsigned long pfn, unsigned long size, pgprot_t prot)
2119{
2120        pgd_t *pgd;
2121        unsigned long next;
2122        unsigned long end = addr + PAGE_ALIGN(size);
2123        struct mm_struct *mm = vma->vm_mm;
2124        unsigned long remap_pfn = pfn;
2125        int err;
2126
2127        /*
2128         * Physically remapped pages are special. Tell the
2129         * rest of the world about it:
2130         *   VM_IO tells people not to look at these pages
2131         *      (accesses can have side effects).
2132         *   VM_PFNMAP tells the core MM that the base pages are just
2133         *      raw PFN mappings, and do not have a "struct page" associated
2134         *      with them.
2135         *   VM_DONTEXPAND
2136         *      Disable vma merging and expanding with mremap().
2137         *   VM_DONTDUMP
2138         *      Omit vma from core dump, even when VM_IO turned off.
2139         *
2140         * There's a horrible special case to handle copy-on-write
2141         * behaviour that some programs depend on. We mark the "original"
2142         * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2143         * See vm_normal_page() for details.
2144         */
2145        if (is_cow_mapping(vma->vm_flags)) {
2146                if (addr != vma->vm_start || end != vma->vm_end)
2147                        return -EINVAL;
2148                vma->vm_pgoff = pfn;
2149        }
2150
2151        err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2152        if (err)
2153                return -EINVAL;
2154
2155        vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2156
2157        BUG_ON(addr >= end);
2158        pfn -= addr >> PAGE_SHIFT;
2159        pgd = pgd_offset(mm, addr);
2160        flush_cache_range(vma, addr, end);
2161        do {
2162                next = pgd_addr_end(addr, end);
2163                err = remap_p4d_range(mm, pgd, addr, next,
2164                                pfn + (addr >> PAGE_SHIFT), prot);
2165                if (err)
2166                        break;
2167        } while (pgd++, addr = next, addr != end);
2168
2169        if (err)
2170                untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2171
2172        return err;
2173}
2174EXPORT_SYMBOL(remap_pfn_range);
2175
2176/**
2177 * vm_iomap_memory - remap memory to userspace
2178 * @vma: user vma to map to
2179 * @start: start of area
2180 * @len: size of area
2181 *
2182 * This is a simplified io_remap_pfn_range() for common driver use. The
2183 * driver just needs to give us the physical memory range to be mapped,
2184 * we'll figure out the rest from the vma information.
2185 *
2186 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2187 * whatever write-combining details or similar.
2188 *
2189 * Return: %0 on success, negative error code otherwise.
2190 */
2191int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2192{
2193        unsigned long vm_len, pfn, pages;
2194
2195        /* Check that the physical memory area passed in looks valid */
2196        if (start + len < start)
2197                return -EINVAL;
2198        /*
2199         * You *really* shouldn't map things that aren't page-aligned,
2200         * but we've historically allowed it because IO memory might
2201         * just have smaller alignment.
2202         */
2203        len += start & ~PAGE_MASK;
2204        pfn = start >> PAGE_SHIFT;
2205        pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2206        if (pfn + pages < pfn)
2207                return -EINVAL;
2208
2209        /* We start the mapping 'vm_pgoff' pages into the area */
2210        if (vma->vm_pgoff > pages)
2211                return -EINVAL;
2212        pfn += vma->vm_pgoff;
2213        pages -= vma->vm_pgoff;
2214
2215        /* Can we fit all of the mapping? */
2216        vm_len = vma->vm_end - vma->vm_start;
2217        if (vm_len >> PAGE_SHIFT > pages)
2218                return -EINVAL;
2219
2220        /* Ok, let it rip */
2221        return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2222}
2223EXPORT_SYMBOL(vm_iomap_memory);
2224
2225static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2226                                     unsigned long addr, unsigned long end,
2227                                     pte_fn_t fn, void *data, bool create)
2228{
2229        pte_t *pte, *mapped_pte;
2230        int err = 0;
2231        spinlock_t *uninitialized_var(ptl);
2232
2233        if (create) {
2234                mapped_pte = pte = (mm == &init_mm) ?
2235                        pte_alloc_kernel(pmd, addr) :
2236                        pte_alloc_map_lock(mm, pmd, addr, &ptl);
2237                if (!pte)
2238                        return -ENOMEM;
2239        } else {
2240                mapped_pte = pte = (mm == &init_mm) ?
2241                        pte_offset_kernel(pmd, addr) :
2242                        pte_offset_map_lock(mm, pmd, addr, &ptl);
2243        }
2244
2245        BUG_ON(pmd_huge(*pmd));
2246
2247        arch_enter_lazy_mmu_mode();
2248
2249        if (fn) {
2250                do {
2251                        if (create || !pte_none(*pte)) {
2252                                err = fn(pte++, addr, data);
2253                                if (err)
2254                                        break;
2255                        }
2256                } while (addr += PAGE_SIZE, addr != end);
2257        }
2258
2259        arch_leave_lazy_mmu_mode();
2260
2261        if (mm != &init_mm)
2262                pte_unmap_unlock(mapped_pte, ptl);
2263        return err;
2264}
2265
2266static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2267                                     unsigned long addr, unsigned long end,
2268                                     pte_fn_t fn, void *data, bool create)
2269{
2270        pmd_t *pmd;
2271        unsigned long next;
2272        int err = 0;
2273
2274        BUG_ON(pud_huge(*pud));
2275
2276        if (create) {
2277                pmd = pmd_alloc(mm, pud, addr);
2278                if (!pmd)
2279                        return -ENOMEM;
2280        } else {
2281                pmd = pmd_offset(pud, addr);
2282        }
2283        do {
2284                next = pmd_addr_end(addr, end);
2285                if (create || !pmd_none_or_clear_bad(pmd)) {
2286                        err = apply_to_pte_range(mm, pmd, addr, next, fn, data,
2287                                                 create);
2288                        if (err)
2289                                break;
2290                }
2291        } while (pmd++, addr = next, addr != end);
2292        return err;
2293}
2294
2295static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2296                                     unsigned long addr, unsigned long end,
2297                                     pte_fn_t fn, void *data, bool create)
2298{
2299        pud_t *pud;
2300        unsigned long next;
2301        int err = 0;
2302
2303        if (create) {
2304                pud = pud_alloc(mm, p4d, addr);
2305                if (!pud)
2306                        return -ENOMEM;
2307        } else {
2308                pud = pud_offset(p4d, addr);
2309        }
2310        do {
2311                next = pud_addr_end(addr, end);
2312                if (create || !pud_none_or_clear_bad(pud)) {
2313                        err = apply_to_pmd_range(mm, pud, addr, next, fn, data,
2314                                                 create);
2315                        if (err)
2316                                break;
2317                }
2318        } while (pud++, addr = next, addr != end);
2319        return err;
2320}
2321
2322static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2323                                     unsigned long addr, unsigned long end,
2324                                     pte_fn_t fn, void *data, bool create)
2325{
2326        p4d_t *p4d;
2327        unsigned long next;
2328        int err = 0;
2329
2330        if (create) {
2331                p4d = p4d_alloc(mm, pgd, addr);
2332                if (!p4d)
2333                        return -ENOMEM;
2334        } else {
2335                p4d = p4d_offset(pgd, addr);
2336        }
2337        do {
2338                next = p4d_addr_end(addr, end);
2339                if (create || !p4d_none_or_clear_bad(p4d)) {
2340                        err = apply_to_pud_range(mm, p4d, addr, next, fn, data,
2341                                                 create);
2342                        if (err)
2343                                break;
2344                }
2345        } while (p4d++, addr = next, addr != end);
2346        return err;
2347}
2348
2349static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2350                                 unsigned long size, pte_fn_t fn,
2351                                 void *data, bool create)
2352{
2353        pgd_t *pgd;
2354        unsigned long next;
2355        unsigned long end = addr + size;
2356        int err = 0;
2357
2358        if (WARN_ON(addr >= end))
2359                return -EINVAL;
2360
2361        pgd = pgd_offset(mm, addr);
2362        do {
2363                next = pgd_addr_end(addr, end);
2364                if (!create && pgd_none_or_clear_bad(pgd))
2365                        continue;
2366                err = apply_to_p4d_range(mm, pgd, addr, next, fn, data, create);
2367                if (err)
2368                        break;
2369        } while (pgd++, addr = next, addr != end);
2370
2371        return err;
2372}
2373
2374/*
2375 * Scan a region of virtual memory, filling in page tables as necessary
2376 * and calling a provided function on each leaf page table.
2377 */
2378int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2379                        unsigned long size, pte_fn_t fn, void *data)
2380{
2381        return __apply_to_page_range(mm, addr, size, fn, data, true);
2382}
2383EXPORT_SYMBOL_GPL(apply_to_page_range);
2384
2385/*
2386 * Scan a region of virtual memory, calling a provided function on
2387 * each leaf page table where it exists.
2388 *
2389 * Unlike apply_to_page_range, this does _not_ fill in page tables
2390 * where they are absent.
2391 */
2392int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2393                                 unsigned long size, pte_fn_t fn, void *data)
2394{
2395        return __apply_to_page_range(mm, addr, size, fn, data, false);
2396}
2397EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2398
2399/*
2400 * handle_pte_fault chooses page fault handler according to an entry which was
2401 * read non-atomically.  Before making any commitment, on those architectures
2402 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2403 * parts, do_swap_page must check under lock before unmapping the pte and
2404 * proceeding (but do_wp_page is only called after already making such a check;
2405 * and do_anonymous_page can safely check later on).
2406 */
2407static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2408                                pte_t *page_table, pte_t orig_pte)
2409{
2410        int same = 1;
2411#if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2412        if (sizeof(pte_t) > sizeof(unsigned long)) {
2413                spinlock_t *ptl = pte_lockptr(mm, pmd);
2414                spin_lock(ptl);
2415                same = pte_same(*page_table, orig_pte);
2416                spin_unlock(ptl);
2417        }
2418#endif
2419        pte_unmap(page_table);
2420        return same;
2421}
2422
2423static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
2424{
2425        /*
2426         * If the source page was a PFN mapping, we don't have
2427         * a "struct page" for it. We do a best-effort copy by
2428         * just copying from the original user address. If that
2429         * fails, we just zero-fill it. Live with it.
2430         */
2431        if (unlikely(!src)) {
2432                void *kaddr = kmap_atomic(dst);
2433                void __user *uaddr = (void __user *)(va & PAGE_MASK);
2434
2435                /*
2436                 * This really shouldn't fail, because the page is there
2437                 * in the page tables. But it might just be unreadable,
2438                 * in which case we just give up and fill the result with
2439                 * zeroes.
2440                 */
2441                if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
2442                        clear_page(kaddr);
2443                kunmap_atomic(kaddr);
2444                flush_dcache_page(dst);
2445        } else
2446                copy_user_highpage(dst, src, va, vma);
2447}
2448
2449static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2450{
2451        struct file *vm_file = vma->vm_file;
2452
2453        if (vm_file)
2454                return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2455
2456        /*
2457         * Special mappings (e.g. VDSO) do not have any file so fake
2458         * a default GFP_KERNEL for them.
2459         */
2460        return GFP_KERNEL;
2461}
2462
2463/*
2464 * Notify the address space that the page is about to become writable so that
2465 * it can prohibit this or wait for the page to get into an appropriate state.
2466 *
2467 * We do this without the lock held, so that it can sleep if it needs to.
2468 */
2469static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2470{
2471        vm_fault_t ret;
2472        struct page *page = vmf->page;
2473        unsigned int old_flags = vmf->flags;
2474
2475        vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2476
2477        if (vmf->vma->vm_file &&
2478            IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2479                return VM_FAULT_SIGBUS;
2480
2481        ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2482        /* Restore original flags so that caller is not surprised */
2483        vmf->flags = old_flags;
2484        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2485                return ret;
2486        if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2487                lock_page(page);
2488                if (!page->mapping) {
2489                        unlock_page(page);
2490                        return 0; /* retry */
2491                }
2492                ret |= VM_FAULT_LOCKED;
2493        } else
2494                VM_BUG_ON_PAGE(!PageLocked(page), page);
2495        return ret;
2496}
2497
2498/*
2499 * Handle dirtying of a page in shared file mapping on a write fault.
2500 *
2501 * The function expects the page to be locked and unlocks it.
2502 */
2503static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
2504{
2505        struct vm_area_struct *vma = vmf->vma;
2506        struct address_space *mapping;
2507        struct page *page = vmf->page;
2508        bool dirtied;
2509        bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2510
2511        dirtied = set_page_dirty(page);
2512        VM_BUG_ON_PAGE(PageAnon(page), page);
2513        /*
2514         * Take a local copy of the address_space - page.mapping may be zeroed
2515         * by truncate after unlock_page().   The address_space itself remains
2516         * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
2517         * release semantics to prevent the compiler from undoing this copying.
2518         */
2519        mapping = page_rmapping(page);
2520        unlock_page(page);
2521
2522        if (!page_mkwrite)
2523                file_update_time(vma->vm_file);
2524
2525        /*
2526         * Throttle page dirtying rate down to writeback speed.
2527         *
2528         * mapping may be NULL here because some device drivers do not
2529         * set page.mapping but still dirty their pages
2530         *
2531         * Drop the mmap_lock before waiting on IO, if we can. The file
2532         * is pinning the mapping, as per above.
2533         */
2534        if ((dirtied || page_mkwrite) && mapping) {
2535                struct file *fpin;
2536
2537                fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2538                balance_dirty_pages_ratelimited(mapping);
2539                if (fpin) {
2540                        fput(fpin);
2541                        return VM_FAULT_RETRY;
2542                }
2543        }
2544
2545        return 0;
2546}
2547
2548/*
2549 * Handle write page faults for pages that can be reused in the current vma
2550 *
2551 * This can happen either due to the mapping being with the VM_SHARED flag,
2552 * or due to us being the last reference standing to the page. In either
2553 * case, all we need to do here is to mark the page as writable and update
2554 * any related book-keeping.
2555 */
2556static inline void wp_page_reuse(struct vm_fault *vmf)
2557        __releases(vmf->ptl)
2558{
2559        struct vm_area_struct *vma = vmf->vma;
2560        struct page *page = vmf->page;
2561        pte_t entry;
2562        /*
2563         * Clear the pages cpupid information as the existing
2564         * information potentially belongs to a now completely
2565         * unrelated process.
2566         */
2567        if (page)
2568                page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2569
2570        flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2571        entry = pte_mkyoung(vmf->orig_pte);
2572        entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2573        if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2574                update_mmu_cache(vma, vmf->address, vmf->pte);
2575        pte_unmap_unlock(vmf->pte, vmf->ptl);
2576}
2577
2578/*
2579 * Handle the case of a page which we actually need to copy to a new page.
2580 *
2581 * Called with mmap_lock locked and the old page referenced, but
2582 * without the ptl held.
2583 *
2584 * High level logic flow:
2585 *
2586 * - Allocate a page, copy the content of the old page to the new one.
2587 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2588 * - Take the PTL. If the pte changed, bail out and release the allocated page
2589 * - If the pte is still the way we remember it, update the page table and all
2590 *   relevant references. This includes dropping the reference the page-table
2591 *   held to the old page, as well as updating the rmap.
2592 * - In any case, unlock the PTL and drop the reference we took to the old page.
2593 */
2594static vm_fault_t wp_page_copy(struct vm_fault *vmf)
2595{
2596        struct vm_area_struct *vma = vmf->vma;
2597        struct mm_struct *mm = vma->vm_mm;
2598        struct page *old_page = vmf->page;
2599        struct page *new_page = NULL;
2600        pte_t entry;
2601        int page_copied = 0;
2602        struct mmu_notifier_range range;
2603
2604        if (unlikely(anon_vma_prepare(vma)))
2605                goto oom;
2606
2607        if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2608                new_page = alloc_zeroed_user_highpage_movable(vma,
2609                                                              vmf->address);
2610                if (!new_page)
2611                        goto oom;
2612        } else {
2613                new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2614                                vmf->address);
2615                if (!new_page)
2616                        goto oom;
2617                cow_user_page(new_page, old_page, vmf->address, vma);
2618        }
2619
2620        if (mem_cgroup_charge(new_page, mm, GFP_KERNEL))
2621                goto oom_free_new;
2622        cgroup_throttle_swaprate(new_page, GFP_KERNEL);
2623
2624        __SetPageUptodate(new_page);
2625
2626        mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
2627                                vmf->address & PAGE_MASK,
2628                                (vmf->address & PAGE_MASK) + PAGE_SIZE);
2629        mmu_notifier_invalidate_range_start(&range);
2630
2631        /*
2632         * Re-check the pte - we dropped the lock
2633         */
2634        vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2635        if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2636                if (old_page) {
2637                        if (!PageAnon(old_page)) {
2638                                dec_mm_counter_fast(mm,
2639                                                mm_counter_file(old_page));
2640                                inc_mm_counter_fast(mm, MM_ANONPAGES);
2641                        }
2642                } else {
2643                        inc_mm_counter_fast(mm, MM_ANONPAGES);
2644                }
2645                flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2646                entry = mk_pte(new_page, vma->vm_page_prot);
2647                entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2648                /*
2649                 * Clear the pte entry and flush it first, before updating the
2650                 * pte with the new entry. This will avoid a race condition
2651                 * seen in the presence of one thread doing SMC and another
2652                 * thread doing COW.
2653                 */
2654                ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
2655                page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2656                lru_cache_add_inactive_or_unevictable(new_page, vma);
2657                /*
2658                 * We call the notify macro here because, when using secondary
2659                 * mmu page tables (such as kvm shadow page tables), we want the
2660                 * new page to be mapped directly into the secondary page table.
2661                 */
2662                set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
2663                update_mmu_cache(vma, vmf->address, vmf->pte);
2664                if (old_page) {
2665                        /*
2666                         * Only after switching the pte to the new page may
2667                         * we remove the mapcount here. Otherwise another
2668                         * process may come and find the rmap count decremented
2669                         * before the pte is switched to the new page, and
2670                         * "reuse" the old page writing into it while our pte
2671                         * here still points into it and can be read by other
2672                         * threads.
2673                         *
2674                         * The critical issue is to order this
2675                         * page_remove_rmap with the ptp_clear_flush above.
2676                         * Those stores are ordered by (if nothing else,)
2677                         * the barrier present in the atomic_add_negative
2678                         * in page_remove_rmap.
2679                         *
2680                         * Then the TLB flush in ptep_clear_flush ensures that
2681                         * no process can access the old page before the
2682                         * decremented mapcount is visible. And the old page
2683                         * cannot be reused until after the decremented
2684                         * mapcount is visible. So transitively, TLBs to
2685                         * old page will be flushed before it can be reused.
2686                         */
2687                        page_remove_rmap(old_page, false);
2688                }
2689
2690                /* Free the old page.. */
2691                new_page = old_page;
2692                page_copied = 1;
2693        }
2694
2695        if (new_page)
2696                put_page(new_page);
2697
2698        pte_unmap_unlock(vmf->pte, vmf->ptl);
2699        /*
2700         * No need to double call mmu_notifier->invalidate_range() callback as
2701         * the above ptep_clear_flush_notify() did already call it.
2702         */
2703        mmu_notifier_invalidate_range_only_end(&range);
2704        if (old_page) {
2705                /*
2706                 * Don't let another task, with possibly unlocked vma,
2707                 * keep the mlocked page.
2708                 */
2709                if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2710                        lock_page(old_page);    /* LRU manipulation */
2711                        if (PageMlocked(old_page))
2712                                munlock_vma_page(old_page);
2713                        unlock_page(old_page);
2714                }
2715                put_page(old_page);
2716        }
2717        return page_copied ? VM_FAULT_WRITE : 0;
2718oom_free_new:
2719        put_page(new_page);
2720oom:
2721        if (old_page)
2722                put_page(old_page);
2723        return VM_FAULT_OOM;
2724}
2725
2726/**
2727 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
2728 *                        writeable once the page is prepared
2729 *
2730 * @vmf: structure describing the fault
2731 *
2732 * This function handles all that is needed to finish a write page fault in a
2733 * shared mapping due to PTE being read-only once the mapped page is prepared.
2734 * It handles locking of PTE and modifying it.
2735 *
2736 * The function expects the page to be locked or other protection against
2737 * concurrent faults / writeback (such as DAX radix tree locks).
2738 *
2739 * Return: %VM_FAULT_WRITE on success, %0 when PTE got changed before
2740 * we acquired PTE lock.
2741 */
2742vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
2743{
2744        WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
2745        vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
2746                                       &vmf->ptl);
2747        /*
2748         * We might have raced with another page fault while we released the
2749         * pte_offset_map_lock.
2750         */
2751        if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2752                pte_unmap_unlock(vmf->pte, vmf->ptl);
2753                return VM_FAULT_NOPAGE;
2754        }
2755        wp_page_reuse(vmf);
2756        return 0;
2757}
2758
2759/*
2760 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2761 * mapping
2762 */
2763static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
2764{
2765        struct vm_area_struct *vma = vmf->vma;
2766
2767        if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2768                vm_fault_t ret;
2769
2770                pte_unmap_unlock(vmf->pte, vmf->ptl);
2771                vmf->flags |= FAULT_FLAG_MKWRITE;
2772                ret = vma->vm_ops->pfn_mkwrite(vmf);
2773                if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
2774                        return ret;
2775                return finish_mkwrite_fault(vmf);
2776        }
2777        wp_page_reuse(vmf);
2778        return VM_FAULT_WRITE;
2779}
2780
2781static vm_fault_t wp_page_shared(struct vm_fault *vmf)
2782        __releases(vmf->ptl)
2783{
2784        struct vm_area_struct *vma = vmf->vma;
2785        vm_fault_t ret = VM_FAULT_WRITE;
2786
2787        get_page(vmf->page);
2788
2789        if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2790                vm_fault_t tmp;
2791
2792                pte_unmap_unlock(vmf->pte, vmf->ptl);
2793                tmp = do_page_mkwrite(vmf);
2794                if (unlikely(!tmp || (tmp &
2795                                      (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2796                        put_page(vmf->page);
2797                        return tmp;
2798                }
2799                tmp = finish_mkwrite_fault(vmf);
2800                if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2801                        unlock_page(vmf->page);
2802                        put_page(vmf->page);
2803                        return tmp;
2804                }
2805        } else {
2806                wp_page_reuse(vmf);
2807                lock_page(vmf->page);
2808        }
2809        ret |= fault_dirty_shared_page(vmf);
2810        put_page(vmf->page);
2811
2812        return ret;
2813}
2814
2815/*
2816 * This routine handles present pages, when users try to write
2817 * to a shared page. It is done by copying the page to a new address
2818 * and decrementing the shared-page counter for the old page.
2819 *
2820 * Note that this routine assumes that the protection checks have been
2821 * done by the caller (the low-level page fault routine in most cases).
2822 * Thus we can safely just mark it writable once we've done any necessary
2823 * COW.
2824 *
2825 * We also mark the page dirty at this point even though the page will
2826 * change only once the write actually happens. This avoids a few races,
2827 * and potentially makes it more efficient.
2828 *
2829 * We enter with non-exclusive mmap_lock (to exclude vma changes,
2830 * but allow concurrent faults), with pte both mapped and locked.
2831 * We return with mmap_lock still held, but pte unmapped and unlocked.
2832 */
2833static vm_fault_t do_wp_page(struct vm_fault *vmf)
2834        __releases(vmf->ptl)
2835{
2836        struct vm_area_struct *vma = vmf->vma;
2837
2838        if (userfaultfd_pte_wp(vma, *vmf->pte)) {
2839                pte_unmap_unlock(vmf->pte, vmf->ptl);
2840                return handle_userfault(vmf, VM_UFFD_WP);
2841        }
2842
2843        /*
2844         * Userfaultfd write-protect can defer flushes. Ensure the TLB
2845         * is flushed in this case before copying.
2846         */
2847        if (unlikely(userfaultfd_wp(vmf->vma) &&
2848                     mm_tlb_flush_pending(vmf->vma->vm_mm)))
2849                flush_tlb_page(vmf->vma, vmf->address);
2850
2851        vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2852        if (!vmf->page) {
2853                /*
2854                 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2855                 * VM_PFNMAP VMA.
2856                 *
2857                 * We should not cow pages in a shared writeable mapping.
2858                 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2859                 */
2860                if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2861                                     (VM_WRITE|VM_SHARED))
2862                        return wp_pfn_shared(vmf);
2863
2864                pte_unmap_unlock(vmf->pte, vmf->ptl);
2865                return wp_page_copy(vmf);
2866        }
2867
2868        /*
2869         * Take out anonymous pages first, anonymous shared vmas are
2870         * not dirty accountable.
2871         */
2872        if (PageAnon(vmf->page)) {
2873                int total_map_swapcount;
2874                if (PageKsm(vmf->page) && (PageSwapCache(vmf->page) ||
2875                                           page_count(vmf->page) != 1))
2876                        goto copy;
2877                if (!trylock_page(vmf->page)) {
2878                        get_page(vmf->page);
2879                        pte_unmap_unlock(vmf->pte, vmf->ptl);
2880                        lock_page(vmf->page);
2881                        vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
2882                                        vmf->address, &vmf->ptl);
2883                        if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2884                                unlock_page(vmf->page);
2885                                pte_unmap_unlock(vmf->pte, vmf->ptl);
2886                                put_page(vmf->page);
2887                                return 0;
2888                        }
2889                        put_page(vmf->page);
2890                }
2891                if (PageKsm(vmf->page)) {
2892                        bool reused = reuse_ksm_page(vmf->page, vmf->vma,
2893                                                     vmf->address);
2894                        unlock_page(vmf->page);
2895                        if (!reused)
2896                                goto copy;
2897                        wp_page_reuse(vmf);
2898                        return VM_FAULT_WRITE;
2899                }
2900                if (reuse_swap_page(vmf->page, &total_map_swapcount)) {
2901                        if (total_map_swapcount == 1) {
2902                                /*
2903                                 * The page is all ours. Move it to
2904                                 * our anon_vma so the rmap code will
2905                                 * not search our parent or siblings.
2906                                 * Protected against the rmap code by
2907                                 * the page lock.
2908                                 */
2909                                page_move_anon_rmap(vmf->page, vma);
2910                        }
2911                        unlock_page(vmf->page);
2912                        wp_page_reuse(vmf);
2913                        return VM_FAULT_WRITE;
2914                }
2915                unlock_page(vmf->page);
2916        } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2917                                        (VM_WRITE|VM_SHARED))) {
2918                return wp_page_shared(vmf);
2919        }
2920copy:
2921        /*
2922         * Ok, we need to copy. Oh, well..
2923         */
2924        get_page(vmf->page);
2925
2926        pte_unmap_unlock(vmf->pte, vmf->ptl);
2927        return wp_page_copy(vmf);
2928}
2929
2930static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2931                unsigned long start_addr, unsigned long end_addr,
2932                struct zap_details *details)
2933{
2934        zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2935}
2936
2937static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
2938                                            struct zap_details *details)
2939{
2940        struct vm_area_struct *vma;
2941        pgoff_t vba, vea, zba, zea;
2942
2943        vma_interval_tree_foreach(vma, root,
2944                        details->first_index, details->last_index) {
2945
2946                vba = vma->vm_pgoff;
2947                vea = vba + vma_pages(vma) - 1;
2948                zba = details->first_index;
2949                if (zba < vba)
2950                        zba = vba;
2951                zea = details->last_index;
2952                if (zea > vea)
2953                        zea = vea;
2954
2955                unmap_mapping_range_vma(vma,
2956                        ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2957                        ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2958                                details);
2959        }
2960}
2961
2962/**
2963 * unmap_mapping_pages() - Unmap pages from processes.
2964 * @mapping: The address space containing pages to be unmapped.
2965 * @start: Index of first page to be unmapped.
2966 * @nr: Number of pages to be unmapped.  0 to unmap to end of file.
2967 * @even_cows: Whether to unmap even private COWed pages.
2968 *
2969 * Unmap the pages in this address space from any userspace process which
2970 * has them mmaped.  Generally, you want to remove COWed pages as well when
2971 * a file is being truncated, but not when invalidating pages from the page
2972 * cache.
2973 */
2974void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
2975                pgoff_t nr, bool even_cows)
2976{
2977        struct zap_details details = { };
2978
2979        details.check_mapping = even_cows ? NULL : mapping;
2980        details.first_index = start;
2981        details.last_index = start + nr - 1;
2982        if (details.last_index < details.first_index)
2983                details.last_index = ULONG_MAX;
2984
2985        i_mmap_lock_write(mapping);
2986        if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
2987                unmap_mapping_range_tree(&mapping->i_mmap, &details);
2988        i_mmap_unlock_write(mapping);
2989}
2990
2991/**
2992 * unmap_mapping_range - unmap the portion of all mmaps in the specified
2993 * address_space corresponding to the specified byte range in the underlying
2994 * file.
2995 *
2996 * @mapping: the address space containing mmaps to be unmapped.
2997 * @holebegin: byte in first page to unmap, relative to the start of
2998 * the underlying file.  This will be rounded down to a PAGE_SIZE
2999 * boundary.  Note that this is different from truncate_pagecache(), which
3000 * must keep the partial page.  In contrast, we must get rid of
3001 * partial pages.
3002 * @holelen: size of prospective hole in bytes.  This will be rounded
3003 * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
3004 * end of the file.
3005 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3006 * but 0 when invalidating pagecache, don't throw away private data.
3007 */
3008void unmap_mapping_range(struct address_space *mapping,
3009                loff_t const holebegin, loff_t const holelen, int even_cows)
3010{
3011        pgoff_t hba = holebegin >> PAGE_SHIFT;
3012        pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3013
3014        /* Check for overflow. */
3015        if (sizeof(holelen) > sizeof(hlen)) {
3016                long long holeend =
3017                        (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3018                if (holeend & ~(long long)ULONG_MAX)
3019                        hlen = ULONG_MAX - hba + 1;
3020        }
3021
3022        unmap_mapping_pages(mapping, hba, hlen, even_cows);
3023}
3024EXPORT_SYMBOL(unmap_mapping_range);
3025
3026/*
3027 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3028 * but allow concurrent faults), and pte mapped but not yet locked.
3029 * We return with pte unmapped and unlocked.
3030 *
3031 * We return with the mmap_lock locked or unlocked in the same cases
3032 * as does filemap_fault().
3033 */
3034vm_fault_t do_swap_page(struct vm_fault *vmf)
3035{
3036        struct vm_area_struct *vma = vmf->vma;
3037        struct page *page = NULL, *swapcache;
3038        swp_entry_t entry;
3039        pte_t pte;
3040        int locked;
3041        int exclusive = 0;
3042        vm_fault_t ret = 0;
3043        void *shadow = NULL;
3044
3045        if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
3046                goto out;
3047
3048        entry = pte_to_swp_entry(vmf->orig_pte);
3049        if (unlikely(non_swap_entry(entry))) {
3050                if (is_migration_entry(entry)) {
3051                        migration_entry_wait(vma->vm_mm, vmf->pmd,
3052                                             vmf->address);
3053                } else if (is_device_private_entry(entry)) {
3054                        vmf->page = device_private_entry_to_page(entry);
3055                        ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3056                } else if (is_hwpoison_entry(entry)) {
3057                        ret = VM_FAULT_HWPOISON;
3058                } else {
3059                        print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3060                        ret = VM_FAULT_SIGBUS;
3061                }
3062                goto out;
3063        }
3064
3065
3066        delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3067        page = lookup_swap_cache(entry, vma, vmf->address);
3068        swapcache = page;
3069
3070        if (!page) {
3071                struct swap_info_struct *si = swp_swap_info(entry);
3072
3073                if (si->flags & SWP_SYNCHRONOUS_IO &&
3074                                __swap_count(entry) == 1) {
3075                        /* skip swapcache */
3076                        page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3077                                                        vmf->address);
3078                        if (page) {
3079                                __SetPageLocked(page);
3080                                __SetPageSwapBacked(page);
3081
3082                                if (mem_cgroup_swapin_charge_page(page,
3083                                        vma->vm_mm, GFP_KERNEL, entry)) {
3084                                        ret = VM_FAULT_OOM;
3085                                        goto out_page;
3086                                }
3087                                mem_cgroup_swapin_uncharge_swap(entry);
3088
3089                                shadow = get_shadow_from_swap_cache(entry);
3090                                if (shadow)
3091                                        workingset_refault(page, shadow);
3092
3093                                lru_cache_add(page);
3094
3095                                /* To provide entry to swap_readpage() */
3096                                set_page_private(page, entry.val);
3097                                swap_readpage(page, true);
3098                                set_page_private(page, 0);
3099                        }
3100                } else {
3101                        page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3102                                                vmf);
3103                        swapcache = page;
3104                }
3105
3106                if (!page) {
3107                        /*
3108                         * Back out if somebody else faulted in this pte
3109                         * while we released the pte lock.
3110                         */
3111                        vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3112                                        vmf->address, &vmf->ptl);
3113                        if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3114                                ret = VM_FAULT_OOM;
3115                        delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3116                        goto unlock;
3117                }
3118
3119                /* Had to read the page from swap area: Major fault */
3120                ret = VM_FAULT_MAJOR;
3121                count_vm_event(PGMAJFAULT);
3122                count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3123        } else if (PageHWPoison(page)) {
3124                /*
3125                 * hwpoisoned dirty swapcache pages are kept for killing
3126                 * owner processes (which may be unknown at hwpoison time)
3127                 */
3128                ret = VM_FAULT_HWPOISON;
3129                delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3130                goto out_release;
3131        }
3132
3133        locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3134
3135        delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3136        if (!locked) {
3137                ret |= VM_FAULT_RETRY;
3138                goto out_release;
3139        }
3140
3141        /*
3142         * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3143         * release the swapcache from under us.  The page pin, and pte_same
3144         * test below, are not enough to exclude that.  Even if it is still
3145         * swapcache, we need to check that the page's swap has not changed.
3146         */
3147        if (unlikely((!PageSwapCache(page) ||
3148                        page_private(page) != entry.val)) && swapcache)
3149                goto out_page;
3150
3151        page = ksm_might_need_to_copy(page, vma, vmf->address);
3152        if (unlikely(!page)) {
3153                ret = VM_FAULT_OOM;
3154                page = swapcache;
3155                goto out_page;
3156        }
3157
3158        cgroup_throttle_swaprate(page, GFP_KERNEL);
3159
3160        /*
3161         * Back out if somebody else already faulted in this pte.
3162         */
3163        vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3164                        &vmf->ptl);
3165        if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3166                goto out_nomap;
3167
3168        if (unlikely(!PageUptodate(page))) {
3169                ret = VM_FAULT_SIGBUS;
3170                goto out_nomap;
3171        }
3172
3173        /*
3174         * The page isn't present yet, go ahead with the fault.
3175         *
3176         * Be careful about the sequence of operations here.
3177         * To get its accounting right, reuse_swap_page() must be called
3178         * while the page is counted on swap but not yet in mapcount i.e.
3179         * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3180         * must be called after the swap_free(), or it will never succeed.
3181         */
3182
3183        inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3184        dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3185        pte = mk_pte(page, vma->vm_page_prot);
3186        if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3187                pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3188                vmf->flags &= ~FAULT_FLAG_WRITE;
3189                ret |= VM_FAULT_WRITE;
3190                exclusive = RMAP_EXCLUSIVE;
3191        }
3192        flush_icache_page(vma, page);
3193        if (pte_swp_soft_dirty(vmf->orig_pte))
3194                pte = pte_mksoft_dirty(pte);
3195        if (pte_swp_uffd_wp(vmf->orig_pte)) {
3196                pte = pte_mkuffd_wp(pte);
3197                pte = pte_wrprotect(pte);
3198        }
3199        set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3200        arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3201        vmf->orig_pte = pte;
3202
3203        /* ksm created a completely new copy */
3204        if (unlikely(page != swapcache && swapcache)) {
3205                page_add_new_anon_rmap(page, vma, vmf->address, false);
3206                lru_cache_add_inactive_or_unevictable(page, vma);
3207        } else {
3208                do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3209        }
3210
3211        swap_free(entry);
3212        if (mem_cgroup_swap_full(page) ||
3213            (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3214                try_to_free_swap(page);
3215        unlock_page(page);
3216        if (page != swapcache && swapcache) {
3217                /*
3218                 * Hold the lock to avoid the swap entry to be reused
3219                 * until we take the PT lock for the pte_same() check
3220                 * (to avoid false positives from pte_same). For
3221                 * further safety release the lock after the swap_free
3222                 * so that the swap count won't change under a
3223                 * parallel locked swapcache.
3224                 */
3225                unlock_page(swapcache);
3226                put_page(swapcache);
3227        }
3228
3229        if (vmf->flags & FAULT_FLAG_WRITE) {
3230                ret |= do_wp_page(vmf);
3231                if (ret & VM_FAULT_ERROR)
3232                        ret &= VM_FAULT_ERROR;
3233                goto out;
3234        }
3235
3236        /* No need to invalidate - it was non-present before */
3237        update_mmu_cache(vma, vmf->address, vmf->pte);
3238unlock:
3239        pte_unmap_unlock(vmf->pte, vmf->ptl);
3240out:
3241        return ret;
3242out_nomap:
3243        pte_unmap_unlock(vmf->pte, vmf->ptl);
3244out_page:
3245        unlock_page(page);
3246out_release:
3247        put_page(page);
3248        if (page != swapcache && swapcache) {
3249                unlock_page(swapcache);
3250                put_page(swapcache);
3251        }
3252        return ret;
3253}
3254
3255/*
3256 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3257 * but allow concurrent faults), and pte mapped but not yet locked.
3258 * We return with mmap_lock still held, but pte unmapped and unlocked.
3259 */
3260static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3261{
3262        struct vm_area_struct *vma = vmf->vma;
3263        struct page *page;
3264        vm_fault_t ret = 0;
3265        pte_t entry;
3266
3267        /* File mapping without ->vm_ops ? */
3268        if (vma->vm_flags & VM_SHARED)
3269                return VM_FAULT_SIGBUS;
3270
3271        /*
3272         * Use pte_alloc() instead of pte_alloc_map().  We can't run
3273         * pte_offset_map() on pmds where a huge pmd might be created
3274         * from a different thread.
3275         *
3276         * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
3277         * parallel threads are excluded by other means.
3278         *
3279         * Here we only have mmap_read_lock(mm).
3280         */
3281        if (pte_alloc(vma->vm_mm, vmf->pmd))
3282                return VM_FAULT_OOM;
3283
3284        /* See the comment in pte_alloc_one_map() */
3285        if (unlikely(pmd_trans_unstable(vmf->pmd)))
3286                return 0;
3287
3288        /* Use the zero-page for reads */
3289        if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3290                        !mm_forbids_zeropage(vma->vm_mm)) {
3291                entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3292                                                vma->vm_page_prot));
3293                vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3294                                vmf->address, &vmf->ptl);
3295                if (!pte_none(*vmf->pte))
3296                        goto unlock;
3297                ret = check_stable_address_space(vma->vm_mm);
3298                if (ret)
3299                        goto unlock;
3300                /* Deliver the page fault to userland, check inside PT lock */
3301                if (userfaultfd_missing(vma)) {
3302                        pte_unmap_unlock(vmf->pte, vmf->ptl);
3303                        return handle_userfault(vmf, VM_UFFD_MISSING);
3304                }
3305                goto setpte;
3306        }
3307
3308        /* Allocate our own private page. */
3309        if (unlikely(anon_vma_prepare(vma)))
3310                goto oom;
3311        page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3312        if (!page)
3313                goto oom;
3314
3315        if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
3316                goto oom_free_page;
3317        cgroup_throttle_swaprate(page, GFP_KERNEL);
3318
3319        /*
3320         * The memory barrier inside __SetPageUptodate makes sure that
3321         * preceeding stores to the page contents become visible before
3322         * the set_pte_at() write.
3323         */
3324        __SetPageUptodate(page);
3325
3326        entry = mk_pte(page, vma->vm_page_prot);
3327        if (vma->vm_flags & VM_WRITE)
3328                entry = pte_mkwrite(pte_mkdirty(entry));
3329
3330        vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3331                        &vmf->ptl);
3332        if (!pte_none(*vmf->pte))
3333                goto release;
3334
3335        ret = check_stable_address_space(vma->vm_mm);
3336        if (ret)
3337                goto release;
3338
3339        /* Deliver the page fault to userland, check inside PT lock */
3340        if (userfaultfd_missing(vma)) {
3341                pte_unmap_unlock(vmf->pte, vmf->ptl);
3342                put_page(page);
3343                return handle_userfault(vmf, VM_UFFD_MISSING);
3344        }
3345
3346        inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3347        page_add_new_anon_rmap(page, vma, vmf->address, false);
3348        lru_cache_add_inactive_or_unevictable(page, vma);
3349setpte:
3350        set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3351
3352        /* No need to invalidate - it was non-present before */
3353        update_mmu_cache(vma, vmf->address, vmf->pte);
3354unlock:
3355        pte_unmap_unlock(vmf->pte, vmf->ptl);
3356        return ret;
3357release:
3358        put_page(page);
3359        goto unlock;
3360oom_free_page:
3361        put_page(page);
3362oom:
3363        return VM_FAULT_OOM;
3364}
3365
3366/*
3367 * The mmap_lock must have been held on entry, and may have been
3368 * released depending on flags and vma->vm_ops->fault() return value.
3369 * See filemap_fault() and __lock_page_retry().
3370 */
3371static vm_fault_t __do_fault(struct vm_fault *vmf)
3372{
3373        struct vm_area_struct *vma = vmf->vma;
3374        vm_fault_t ret;
3375
3376        /*
3377         * Preallocate pte before we take page_lock because this might lead to
3378         * deadlocks for memcg reclaim which waits for pages under writeback:
3379         *                              lock_page(A)
3380         *                              SetPageWriteback(A)
3381         *                              unlock_page(A)
3382         * lock_page(B)
3383         *                              lock_page(B)
3384         * pte_alloc_pne
3385         *   shrink_page_list
3386         *     wait_on_page_writeback(A)
3387         *                              SetPageWriteback(B)
3388         *                              unlock_page(B)
3389         *                              # flush A, B to clear the writeback
3390         */
3391        if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3392                vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
3393                if (!vmf->prealloc_pte)
3394                        return VM_FAULT_OOM;
3395                smp_wmb(); /* See comment in __pte_alloc() */
3396        }
3397
3398        ret = vma->vm_ops->fault(vmf);
3399        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3400                            VM_FAULT_DONE_COW)))
3401                return ret;
3402
3403        if (unlikely(PageHWPoison(vmf->page))) {
3404                if (ret & VM_FAULT_LOCKED)
3405                        unlock_page(vmf->page);
3406                put_page(vmf->page);
3407                vmf->page = NULL;
3408                return VM_FAULT_HWPOISON;
3409        }
3410
3411        if (unlikely(!(ret & VM_FAULT_LOCKED)))
3412                lock_page(vmf->page);
3413        else
3414                VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3415
3416        return ret;
3417}
3418
3419/*
3420 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3421 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3422 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3423 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3424 */
3425static int pmd_devmap_trans_unstable(pmd_t *pmd)
3426{
3427        return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3428}
3429
3430static vm_fault_t pte_alloc_one_map(struct vm_fault *vmf)
3431{
3432        struct vm_area_struct *vma = vmf->vma;
3433
3434        if (!pmd_none(*vmf->pmd))
3435                goto map_pte;
3436        if (vmf->prealloc_pte) {
3437                vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3438                if (unlikely(!pmd_none(*vmf->pmd))) {
3439                        spin_unlock(vmf->ptl);
3440                        goto map_pte;
3441                }
3442
3443                mm_inc_nr_ptes(vma->vm_mm);
3444                pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3445                spin_unlock(vmf->ptl);
3446                vmf->prealloc_pte = NULL;
3447        } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) {
3448                return VM_FAULT_OOM;
3449        }
3450map_pte:
3451        /*
3452         * If a huge pmd materialized under us just retry later.  Use
3453         * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3454         * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3455         * under us and then back to pmd_none, as a result of MADV_DONTNEED
3456         * running immediately after a huge pmd fault in a different thread of
3457         * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3458         * All we have to ensure is that it is a regular pmd that we can walk
3459         * with pte_offset_map() and we can do that through an atomic read in
3460         * C, which is what pmd_trans_unstable() provides.
3461         */
3462        if (pmd_devmap_trans_unstable(vmf->pmd))
3463                return VM_FAULT_NOPAGE;
3464
3465        /*
3466         * At this point we know that our vmf->pmd points to a page of ptes
3467         * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3468         * for the duration of the fault.  If a racing MADV_DONTNEED runs and
3469         * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3470         * be valid and we will re-check to make sure the vmf->pte isn't
3471         * pte_none() under vmf->ptl protection when we return to
3472         * alloc_set_pte().
3473         */
3474        vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3475                        &vmf->ptl);
3476        return 0;
3477}
3478
3479#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3480static void deposit_prealloc_pte(struct vm_fault *vmf)
3481{
3482        struct vm_area_struct *vma = vmf->vma;
3483
3484        pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3485        /*
3486         * We are going to consume the prealloc table,
3487         * count that as nr_ptes.
3488         */
3489        mm_inc_nr_ptes(vma->vm_mm);
3490        vmf->prealloc_pte = NULL;
3491}
3492
3493static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3494{
3495        struct vm_area_struct *vma = vmf->vma;
3496        bool write = vmf->flags & FAULT_FLAG_WRITE;
3497        unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3498        pmd_t entry;
3499        int i;
3500        vm_fault_t ret = VM_FAULT_FALLBACK;
3501
3502        if (!transhuge_vma_suitable(vma, haddr))
3503                return ret;
3504
3505        page = compound_head(page);
3506        if (compound_order(page) != HPAGE_PMD_ORDER)
3507                return ret;
3508
3509        /*
3510         * Archs like ppc64 need additonal space to store information
3511         * related to pte entry. Use the preallocated table for that.
3512         */
3513        if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3514                vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3515                if (!vmf->prealloc_pte)
3516                        return VM_FAULT_OOM;
3517                smp_wmb(); /* See comment in __pte_alloc() */
3518        }
3519
3520        vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3521        if (unlikely(!pmd_none(*vmf->pmd)))
3522                goto out;
3523
3524        for (i = 0; i < HPAGE_PMD_NR; i++)
3525                flush_icache_page(vma, page + i);
3526
3527        entry = mk_huge_pmd(page, vma->vm_page_prot);
3528        if (write)
3529                entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3530
3531        add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
3532        page_add_file_rmap(page, true);
3533        /*
3534         * deposit and withdraw with pmd lock held
3535         */
3536        if (arch_needs_pgtable_deposit())
3537                deposit_prealloc_pte(vmf);
3538
3539        set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3540
3541        update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3542
3543        /* fault is handled */
3544        ret = 0;
3545        count_vm_event(THP_FILE_MAPPED);
3546out:
3547        spin_unlock(vmf->ptl);
3548        return ret;
3549}
3550#else
3551static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3552{
3553        BUILD_BUG();
3554        return 0;
3555}
3556#endif
3557
3558/**
3559 * alloc_set_pte - setup new PTE entry for given page and add reverse page
3560 * mapping. If needed, the fucntion allocates page table or use pre-allocated.
3561 *
3562 * @vmf: fault environment
3563 * @page: page to map
3564 *
3565 * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3566 * return.
3567 *
3568 * Target users are page handler itself and implementations of
3569 * vm_ops->map_pages.
3570 *
3571 * Return: %0 on success, %VM_FAULT_ code in case of error.
3572 */
3573vm_fault_t alloc_set_pte(struct vm_fault *vmf, struct page *page)
3574{
3575        struct vm_area_struct *vma = vmf->vma;
3576        bool write = vmf->flags & FAULT_FLAG_WRITE;
3577        pte_t entry;
3578        vm_fault_t ret;
3579
3580        if (pmd_none(*vmf->pmd) && PageTransCompound(page)) {
3581                ret = do_set_pmd(vmf, page);
3582                if (ret != VM_FAULT_FALLBACK)
3583                        return ret;
3584        }
3585
3586        if (!vmf->pte) {
3587                ret = pte_alloc_one_map(vmf);
3588                if (ret)
3589                        return ret;
3590        }
3591
3592        /* Re-check under ptl */
3593        if (unlikely(!pte_none(*vmf->pte)))
3594                return VM_FAULT_NOPAGE;
3595
3596        flush_icache_page(vma, page);
3597        entry = mk_pte(page, vma->vm_page_prot);
3598        if (write)
3599                entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3600        /* copy-on-write page */
3601        if (write && !(vma->vm_flags & VM_SHARED)) {
3602                inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3603                page_add_new_anon_rmap(page, vma, vmf->address, false);
3604                lru_cache_add_inactive_or_unevictable(page, vma);
3605        } else {
3606                inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3607                page_add_file_rmap(page, false);
3608        }
3609        set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3610
3611        /* no need to invalidate: a not-present page won't be cached */
3612        update_mmu_cache(vma, vmf->address, vmf->pte);
3613
3614        return 0;
3615}
3616
3617
3618/**
3619 * finish_fault - finish page fault once we have prepared the page to fault
3620 *
3621 * @vmf: structure describing the fault
3622 *
3623 * This function handles all that is needed to finish a page fault once the
3624 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
3625 * given page, adds reverse page mapping, handles memcg charges and LRU
3626 * addition.
3627 *
3628 * The function expects the page to be locked and on success it consumes a
3629 * reference of a page being mapped (for the PTE which maps it).
3630 *
3631 * Return: %0 on success, %VM_FAULT_ code in case of error.
3632 */
3633vm_fault_t finish_fault(struct vm_fault *vmf)
3634{
3635        struct page *page;
3636        vm_fault_t ret = 0;
3637
3638        /* Did we COW the page? */
3639        if ((vmf->flags & FAULT_FLAG_WRITE) &&
3640            !(vmf->vma->vm_flags & VM_SHARED))
3641                page = vmf->cow_page;
3642        else
3643                page = vmf->page;
3644
3645        /*
3646         * check even for read faults because we might have lost our CoWed
3647         * page
3648         */
3649        if (!(vmf->vma->vm_flags & VM_SHARED))
3650                ret = check_stable_address_space(vmf->vma->vm_mm);
3651        if (!ret)
3652                ret = alloc_set_pte(vmf, page);
3653        if (vmf->pte)
3654                pte_unmap_unlock(vmf->pte, vmf->ptl);
3655        return ret;
3656}
3657
3658static unsigned long fault_around_bytes __read_mostly =
3659        rounddown_pow_of_two(65536);
3660
3661#ifdef CONFIG_DEBUG_FS
3662static int fault_around_bytes_get(void *data, u64 *val)
3663{
3664        *val = fault_around_bytes;
3665        return 0;
3666}
3667
3668/*
3669 * fault_around_bytes must be rounded down to the nearest page order as it's
3670 * what do_fault_around() expects to see.
3671 */
3672static int fault_around_bytes_set(void *data, u64 val)
3673{
3674        if (val / PAGE_SIZE > PTRS_PER_PTE)
3675                return -EINVAL;
3676        if (val > PAGE_SIZE)
3677                fault_around_bytes = rounddown_pow_of_two(val);
3678        else
3679                fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3680        return 0;
3681}
3682DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3683                fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3684
3685static int __init fault_around_debugfs(void)
3686{
3687        debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3688                                   &fault_around_bytes_fops);
3689        return 0;
3690}
3691late_initcall(fault_around_debugfs);
3692#endif
3693
3694/*
3695 * do_fault_around() tries to map few pages around the fault address. The hope
3696 * is that the pages will be needed soon and this will lower the number of
3697 * faults to handle.
3698 *
3699 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3700 * not ready to be mapped: not up-to-date, locked, etc.
3701 *
3702 * This function is called with the page table lock taken. In the split ptlock
3703 * case the page table lock only protects only those entries which belong to
3704 * the page table corresponding to the fault address.
3705 *
3706 * This function doesn't cross the VMA boundaries, in order to call map_pages()
3707 * only once.
3708 *
3709 * fault_around_bytes defines how many bytes we'll try to map.
3710 * do_fault_around() expects it to be set to a power of two less than or equal
3711 * to PTRS_PER_PTE.
3712 *
3713 * The virtual address of the area that we map is naturally aligned to
3714 * fault_around_bytes rounded down to the machine page size
3715 * (and therefore to page order).  This way it's easier to guarantee
3716 * that we don't cross page table boundaries.
3717 */
3718static vm_fault_t do_fault_around(struct vm_fault *vmf)
3719{
3720        unsigned long address = vmf->address, nr_pages, mask;
3721        pgoff_t start_pgoff = vmf->pgoff;
3722        pgoff_t end_pgoff;
3723        int off;
3724        vm_fault_t ret = 0;
3725
3726        nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3727        mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3728
3729        vmf->address = max(address & mask, vmf->vma->vm_start);
3730        off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3731        start_pgoff -= off;
3732
3733        /*
3734         *  end_pgoff is either the end of the page table, the end of
3735         *  the vma or nr_pages from start_pgoff, depending what is nearest.
3736         */
3737        end_pgoff = start_pgoff -
3738                ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3739                PTRS_PER_PTE - 1;
3740        end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3741                        start_pgoff + nr_pages - 1);
3742
3743        if (pmd_none(*vmf->pmd)) {
3744                vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
3745                if (!vmf->prealloc_pte)
3746                        goto out;
3747                smp_wmb(); /* See comment in __pte_alloc() */
3748        }
3749
3750        vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
3751
3752        /* Huge page is mapped? Page fault is solved */
3753        if (pmd_trans_huge(*vmf->pmd)) {
3754                ret = VM_FAULT_NOPAGE;
3755                goto out;
3756        }
3757
3758        /* ->map_pages() haven't done anything useful. Cold page cache? */
3759        if (!vmf->pte)
3760                goto out;
3761
3762        /* check if the page fault is solved */
3763        vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3764        if (!pte_none(*vmf->pte))
3765                ret = VM_FAULT_NOPAGE;
3766        pte_unmap_unlock(vmf->pte, vmf->ptl);
3767out:
3768        vmf->address = address;
3769        vmf->pte = NULL;
3770        return ret;
3771}
3772
3773static vm_fault_t do_read_fault(struct vm_fault *vmf)
3774{
3775        struct vm_area_struct *vma = vmf->vma;
3776        vm_fault_t ret = 0;
3777
3778        /*
3779         * Let's call ->map_pages() first and use ->fault() as fallback
3780         * if page by the offset is not ready to be mapped (cold cache or
3781         * something).
3782         */
3783        if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3784                ret = do_fault_around(vmf);
3785                if (ret)
3786                        return ret;
3787        }
3788
3789        ret = __do_fault(vmf);
3790        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3791                return ret;
3792
3793        ret |= finish_fault(vmf);
3794        unlock_page(vmf->page);
3795        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3796                put_page(vmf->page);
3797        return ret;
3798}
3799
3800static vm_fault_t do_cow_fault(struct vm_fault *vmf)
3801{
3802        struct vm_area_struct *vma = vmf->vma;
3803        vm_fault_t ret;
3804
3805        if (unlikely(anon_vma_prepare(vma)))
3806                return VM_FAULT_OOM;
3807
3808        vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3809        if (!vmf->cow_page)
3810                return VM_FAULT_OOM;
3811
3812        if (mem_cgroup_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL)) {
3813                put_page(vmf->cow_page);
3814                return VM_FAULT_OOM;
3815        }
3816        cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
3817
3818        ret = __do_fault(vmf);
3819        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3820                goto uncharge_out;
3821        if (ret & VM_FAULT_DONE_COW)
3822                return ret;
3823
3824        copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3825        __SetPageUptodate(vmf->cow_page);
3826
3827        ret |= finish_fault(vmf);
3828        unlock_page(vmf->page);
3829        put_page(vmf->page);
3830        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3831                goto uncharge_out;
3832        return ret;
3833uncharge_out:
3834        put_page(vmf->cow_page);
3835        return ret;
3836}
3837
3838static vm_fault_t do_shared_fault(struct vm_fault *vmf)
3839{
3840        struct vm_area_struct *vma = vmf->vma;
3841        vm_fault_t ret, tmp;
3842
3843        ret = __do_fault(vmf);
3844        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3845                return ret;
3846
3847        /*
3848         * Check if the backing address space wants to know that the page is
3849         * about to become writable
3850         */
3851        if (vma->vm_ops->page_mkwrite) {
3852                unlock_page(vmf->page);
3853                tmp = do_page_mkwrite(vmf);
3854                if (unlikely(!tmp ||
3855                                (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3856                        put_page(vmf->page);
3857                        return tmp;
3858                }
3859        }
3860
3861        ret |= finish_fault(vmf);
3862        if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3863                                        VM_FAULT_RETRY))) {
3864                unlock_page(vmf->page);
3865                put_page(vmf->page);
3866                return ret;
3867        }
3868
3869        ret |= fault_dirty_shared_page(vmf);
3870        return ret;
3871}
3872
3873/*
3874 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3875 * but allow concurrent faults).
3876 * The mmap_lock may have been released depending on flags and our
3877 * return value.  See filemap_fault() and __lock_page_or_retry().
3878 * If mmap_lock is released, vma may become invalid (for example
3879 * by other thread calling munmap()).
3880 */
3881static vm_fault_t do_fault(struct vm_fault *vmf)
3882{
3883        struct vm_area_struct *vma = vmf->vma;
3884        struct mm_struct *vm_mm = vma->vm_mm;
3885        vm_fault_t ret;
3886
3887        /* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
3888        if (!vma->vm_ops->fault)
3889                ret = VM_FAULT_SIGBUS;
3890        else if (!(vmf->flags & FAULT_FLAG_WRITE))
3891                ret = do_read_fault(vmf);
3892        else if (!(vma->vm_flags & VM_SHARED))
3893                ret = do_cow_fault(vmf);
3894        else
3895                ret = do_shared_fault(vmf);
3896
3897        /* preallocated pagetable is unused: free it */
3898        if (vmf->prealloc_pte) {
3899                pte_free(vm_mm, vmf->prealloc_pte);
3900                vmf->prealloc_pte = NULL;
3901        }
3902        return ret;
3903}
3904
3905static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3906                                unsigned long addr, int page_nid,
3907                                int *flags)
3908{
3909        get_page(page);
3910
3911        count_vm_numa_event(NUMA_HINT_FAULTS);
3912        if (page_nid == numa_node_id()) {
3913                count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3914                *flags |= TNF_FAULT_LOCAL;
3915        }
3916
3917        return mpol_misplaced(page, vma, addr);
3918}
3919
3920static vm_fault_t do_numa_page(struct vm_fault *vmf)
3921{
3922        struct vm_area_struct *vma = vmf->vma;
3923        struct page *page = NULL;
3924        int page_nid = NUMA_NO_NODE;
3925        int last_cpupid;
3926        int target_nid;
3927        bool migrated = false;
3928        pte_t pte, old_pte;
3929        bool was_writable = pte_savedwrite(vmf->orig_pte);
3930        int flags = 0;
3931
3932        /*
3933         * The "pte" at this point cannot be used safely without
3934         * validation through pte_unmap_same(). It's of NUMA type but
3935         * the pfn may be screwed if the read is non atomic.
3936         */
3937        vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
3938        spin_lock(vmf->ptl);
3939        if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3940                pte_unmap_unlock(vmf->pte, vmf->ptl);
3941                goto out;
3942        }
3943
3944        /*
3945         * Make it present again, Depending on how arch implementes non
3946         * accessible ptes, some can allow access by kernel mode.
3947         */
3948        old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
3949        pte = pte_modify(old_pte, vma->vm_page_prot);
3950        pte = pte_mkyoung(pte);
3951        if (was_writable)
3952                pte = pte_mkwrite(pte);
3953        ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
3954        update_mmu_cache(vma, vmf->address, vmf->pte);
3955
3956        page = vm_normal_page(vma, vmf->address, pte);
3957        if (!page) {
3958                pte_unmap_unlock(vmf->pte, vmf->ptl);
3959                return 0;
3960        }
3961
3962        /* TODO: handle PTE-mapped THP */
3963        if (PageCompound(page)) {
3964                pte_unmap_unlock(vmf->pte, vmf->ptl);
3965                return 0;
3966        }
3967
3968        /*
3969         * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3970         * much anyway since they can be in shared cache state. This misses
3971         * the case where a mapping is writable but the process never writes
3972         * to it but pte_write gets cleared during protection updates and
3973         * pte_dirty has unpredictable behaviour between PTE scan updates,
3974         * background writeback, dirty balancing and application behaviour.
3975         */
3976        if (!pte_write(pte))
3977                flags |= TNF_NO_GROUP;
3978
3979        /*
3980         * Flag if the page is shared between multiple address spaces. This
3981         * is later used when determining whether to group tasks together
3982         */
3983        if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3984                flags |= TNF_SHARED;
3985
3986        last_cpupid = page_cpupid_last(page);
3987        page_nid = page_to_nid(page);
3988        target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
3989                        &flags);
3990        pte_unmap_unlock(vmf->pte, vmf->ptl);
3991        if (target_nid == NUMA_NO_NODE) {
3992                put_page(page);
3993                goto out;
3994        }
3995
3996        /* Migrate to the requested node */
3997        migrated = migrate_misplaced_page(page, vma, target_nid);
3998        if (migrated) {
3999                page_nid = target_nid;
4000                flags |= TNF_MIGRATED;
4001        } else
4002                flags |= TNF_MIGRATE_FAIL;
4003
4004out:
4005        if (page_nid != NUMA_NO_NODE)
4006                task_numa_fault(last_cpupid, page_nid, 1, flags);
4007        return 0;
4008}
4009
4010static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4011{
4012        if (vma_is_anonymous(vmf->vma))
4013                return do_huge_pmd_anonymous_page(vmf);
4014        if (vmf->vma->vm_ops->huge_fault)
4015                return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4016        return VM_FAULT_FALLBACK;
4017}
4018
4019/* `inline' is required to avoid gcc 4.1.2 build error */
4020static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
4021{
4022        if (vma_is_anonymous(vmf->vma)) {
4023                if (userfaultfd_huge_pmd_wp(vmf->vma, orig_pmd))
4024                        return handle_userfault(vmf, VM_UFFD_WP);
4025                return do_huge_pmd_wp_page(vmf, orig_pmd);
4026        }
4027        if (vmf->vma->vm_ops->huge_fault) {
4028                vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4029
4030                if (!(ret & VM_FAULT_FALLBACK))
4031                        return ret;
4032        }
4033
4034        /* COW or write-notify handled on pte level: split pmd. */
4035        __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4036
4037        return VM_FAULT_FALLBACK;
4038}
4039
4040static inline bool vma_is_accessible(struct vm_area_struct *vma)
4041{
4042        return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
4043}
4044
4045static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4046{
4047#if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&                     \
4048        defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4049        /* No support for anonymous transparent PUD pages yet */
4050        if (vma_is_anonymous(vmf->vma))
4051                goto split;
4052        if (vmf->vma->vm_ops->huge_fault) {
4053                vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4054
4055                if (!(ret & VM_FAULT_FALLBACK))
4056                        return ret;
4057        }
4058split:
4059        /* COW or write-notify not handled on PUD level: split pud.*/
4060        __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4061#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4062        return VM_FAULT_FALLBACK;
4063}
4064
4065static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4066{
4067#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4068        /* No support for anonymous transparent PUD pages yet */
4069        if (vma_is_anonymous(vmf->vma))
4070                return VM_FAULT_FALLBACK;
4071        if (vmf->vma->vm_ops->huge_fault)
4072                return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4073#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4074        return VM_FAULT_FALLBACK;
4075}
4076
4077/*
4078 * These routines also need to handle stuff like marking pages dirty
4079 * and/or accessed for architectures that don't do it in hardware (most
4080 * RISC architectures).  The early dirtying is also good on the i386.
4081 *
4082 * There is also a hook called "update_mmu_cache()" that architectures
4083 * with external mmu caches can use to update those (ie the Sparc or
4084 * PowerPC hashed page tables that act as extended TLBs).
4085 *
4086 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4087 * concurrent faults).
4088 *
4089 * The mmap_lock may have been released depending on flags and our return value.
4090 * See filemap_fault() and __lock_page_or_retry().
4091 */
4092static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4093{
4094        pte_t entry;
4095
4096        if (unlikely(pmd_none(*vmf->pmd))) {
4097                /*
4098                 * Leave __pte_alloc() until later: because vm_ops->fault may
4099                 * want to allocate huge page, and if we expose page table
4100                 * for an instant, it will be difficult to retract from
4101                 * concurrent faults and from rmap lookups.
4102                 */
4103                vmf->pte = NULL;
4104        } else {
4105                /* See comment in pte_alloc_one_map() */
4106                if (pmd_devmap_trans_unstable(vmf->pmd))
4107                        return 0;
4108                /*
4109                 * A regular pmd is established and it can't morph into a huge
4110                 * pmd from under us anymore at this point because we hold the
4111                 * mmap_lock read mode and khugepaged takes it in write mode.
4112                 * So now it's safe to run pte_offset_map().
4113                 */
4114                vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4115                vmf->orig_pte = *vmf->pte;
4116
4117                /*
4118                 * some architectures can have larger ptes than wordsize,
4119                 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4120                 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4121                 * accesses.  The code below just needs a consistent view
4122                 * for the ifs and we later double check anyway with the
4123                 * ptl lock held. So here a barrier will do.
4124                 */
4125                barrier();
4126                if (pte_none(vmf->orig_pte)) {
4127                        pte_unmap(vmf->pte);
4128                        vmf->pte = NULL;
4129                }
4130        }
4131
4132        if (!vmf->pte) {
4133                if (vma_is_anonymous(vmf->vma))
4134                        return do_anonymous_page(vmf);
4135                else
4136                        return do_fault(vmf);
4137        }
4138
4139        if (!pte_present(vmf->orig_pte))
4140                return do_swap_page(vmf);
4141
4142        if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4143                return do_numa_page(vmf);
4144
4145        vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4146        spin_lock(vmf->ptl);
4147        entry = vmf->orig_pte;
4148        if (unlikely(!pte_same(*vmf->pte, entry)))
4149                goto unlock;
4150        if (vmf->flags & FAULT_FLAG_WRITE) {
4151                if (!pte_write(entry))
4152                        return do_wp_page(vmf);
4153                entry = pte_mkdirty(entry);
4154        }
4155        entry = pte_mkyoung(entry);
4156        if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4157                                vmf->flags & FAULT_FLAG_WRITE)) {
4158                update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4159        } else {
4160                /* Skip spurious TLB flush for retried page fault */
4161                if (vmf->flags & FAULT_FLAG_TRIED)
4162                        goto unlock;
4163                /*
4164                 * This is needed only for protection faults but the arch code
4165                 * is not yet telling us if this is a protection fault or not.
4166                 * This still avoids useless tlb flushes for .text page faults
4167                 * with threads.
4168                 */
4169                if (vmf->flags & FAULT_FLAG_WRITE)
4170                        flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4171        }
4172unlock:
4173        pte_unmap_unlock(vmf->pte, vmf->ptl);
4174        return 0;
4175}
4176
4177/*
4178 * By the time we get here, we already hold the mm semaphore
4179 *
4180 * The mmap_lock may have been released depending on flags and our
4181 * return value.  See filemap_fault() and __lock_page_or_retry().
4182 */
4183static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4184                unsigned long address, unsigned int flags)
4185{
4186        struct vm_fault vmf = {
4187                .vma = vma,
4188                .address = address & PAGE_MASK,
4189                .flags = flags,
4190                .pgoff = linear_page_index(vma, address),
4191                .gfp_mask = __get_fault_gfp_mask(vma),
4192        };
4193        unsigned int dirty = flags & FAULT_FLAG_WRITE;
4194        struct mm_struct *mm = vma->vm_mm;
4195        pgd_t *pgd;
4196        p4d_t *p4d;
4197        vm_fault_t ret;
4198
4199        pgd = pgd_offset(mm, address);
4200        p4d = p4d_alloc(mm, pgd, address);
4201        if (!p4d)
4202                return VM_FAULT_OOM;
4203
4204        vmf.pud = pud_alloc(mm, p4d, address);
4205        if (!vmf.pud)
4206                return VM_FAULT_OOM;
4207retry_pud:
4208        if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4209                ret = create_huge_pud(&vmf);
4210                if (!(ret & VM_FAULT_FALLBACK))
4211                        return ret;
4212        } else {
4213                pud_t orig_pud = *vmf.pud;
4214
4215                barrier();
4216                if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4217
4218                        /* NUMA case for anonymous PUDs would go here */
4219
4220                        if (dirty && !pud_write(orig_pud)) {
4221                                ret = wp_huge_pud(&vmf, orig_pud);
4222                                if (!(ret & VM_FAULT_FALLBACK))
4223                                        return ret;
4224                        } else {
4225                                huge_pud_set_accessed(&vmf, orig_pud);
4226                                return 0;
4227                        }
4228                }
4229        }
4230
4231        vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4232        if (!vmf.pmd)
4233                return VM_FAULT_OOM;
4234
4235        /* Huge pud page fault raced with pmd_alloc? */
4236        if (pud_trans_unstable(vmf.pud))
4237                goto retry_pud;
4238
4239        if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4240                ret = create_huge_pmd(&vmf);
4241                if (!(ret & VM_FAULT_FALLBACK))
4242                        return ret;
4243        } else {
4244                pmd_t orig_pmd = *vmf.pmd;
4245
4246                barrier();
4247                if (unlikely(is_swap_pmd(orig_pmd))) {
4248                        VM_BUG_ON(thp_migration_supported() &&
4249                                          !is_pmd_migration_entry(orig_pmd));
4250                        if (is_pmd_migration_entry(orig_pmd))
4251                                pmd_migration_entry_wait(mm, vmf.pmd);
4252                        return 0;
4253                }
4254                if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4255                        if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4256                                return do_huge_pmd_numa_page(&vmf, orig_pmd);
4257
4258                        if (dirty && !pmd_write(orig_pmd)) {
4259                                ret = wp_huge_pmd(&vmf, orig_pmd);
4260                                if (!(ret & VM_FAULT_FALLBACK))
4261                                        return ret;
4262                        } else {
4263                                huge_pmd_set_accessed(&vmf, orig_pmd);
4264                                return 0;
4265                        }
4266                }
4267        }
4268
4269        return handle_pte_fault(&vmf);
4270}
4271
4272/*
4273 * By the time we get here, we already hold the mm semaphore
4274 *
4275 * The mmap_lock may have been released depending on flags and our
4276 * return value.  See filemap_fault() and __lock_page_or_retry().
4277 */
4278vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4279                unsigned int flags)
4280{
4281        vm_fault_t ret;
4282
4283        __set_current_state(TASK_RUNNING);
4284
4285        count_vm_event(PGFAULT);
4286        count_memcg_event_mm(vma->vm_mm, PGFAULT);
4287
4288        /* do counter updates before entering really critical section. */
4289        check_sync_rss_stat(current);
4290
4291        if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4292                                            flags & FAULT_FLAG_INSTRUCTION,
4293                                            flags & FAULT_FLAG_REMOTE))
4294                return VM_FAULT_SIGSEGV;
4295
4296        /*
4297         * Enable the memcg OOM handling for faults triggered in user
4298         * space.  Kernel faults are handled more gracefully.
4299         */
4300        if (flags & FAULT_FLAG_USER)
4301                mem_cgroup_enter_user_fault();
4302
4303        if (unlikely(is_vm_hugetlb_page(vma)))
4304                ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4305        else
4306                ret = __handle_mm_fault(vma, address, flags);
4307
4308        if (flags & FAULT_FLAG_USER) {
4309                mem_cgroup_exit_user_fault();
4310                /*
4311                 * The task may have entered a memcg OOM situation but
4312                 * if the allocation error was handled gracefully (no
4313                 * VM_FAULT_OOM), there is no need to kill anything.
4314                 * Just clean up the OOM state peacefully.
4315                 */
4316                if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4317                        mem_cgroup_oom_synchronize(false);
4318        }
4319
4320        return ret;
4321}
4322EXPORT_SYMBOL_GPL(handle_mm_fault);
4323
4324#ifndef __PAGETABLE_P4D_FOLDED
4325/*
4326 * Allocate p4d page table.
4327 * We've already handled the fast-path in-line.
4328 */
4329int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4330{
4331        p4d_t *new = p4d_alloc_one(mm, address);
4332        if (!new)
4333                return -ENOMEM;
4334
4335        smp_wmb(); /* See comment in __pte_alloc */
4336
4337        spin_lock(&mm->page_table_lock);
4338        if (pgd_present(*pgd))          /* Another has populated it */
4339                p4d_free(mm, new);
4340        else
4341                pgd_populate(mm, pgd, new);
4342        spin_unlock(&mm->page_table_lock);
4343        return 0;
4344}
4345#endif /* __PAGETABLE_P4D_FOLDED */
4346
4347#ifndef __PAGETABLE_PUD_FOLDED
4348/*
4349 * Allocate page upper directory.
4350 * We've already handled the fast-path in-line.
4351 */
4352int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4353{
4354        pud_t *new = pud_alloc_one(mm, address);
4355        if (!new)
4356                return -ENOMEM;
4357
4358        smp_wmb(); /* See comment in __pte_alloc */
4359
4360        spin_lock(&mm->page_table_lock);
4361#ifndef __ARCH_HAS_5LEVEL_HACK
4362        if (!p4d_present(*p4d)) {
4363                mm_inc_nr_puds(mm);
4364                p4d_populate(mm, p4d, new);
4365        } else  /* Another has populated it */
4366                pud_free(mm, new);
4367#else
4368        if (!pgd_present(*p4d)) {
4369                mm_inc_nr_puds(mm);
4370                pgd_populate(mm, p4d, new);
4371        } else  /* Another has populated it */
4372                pud_free(mm, new);
4373#endif /* __ARCH_HAS_5LEVEL_HACK */
4374        spin_unlock(&mm->page_table_lock);
4375        return 0;
4376}
4377#endif /* __PAGETABLE_PUD_FOLDED */
4378
4379#ifndef __PAGETABLE_PMD_FOLDED
4380/*
4381 * Allocate page middle directory.
4382 * We've already handled the fast-path in-line.
4383 */
4384int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4385{
4386        spinlock_t *ptl;
4387        pmd_t *new = pmd_alloc_one(mm, address);
4388        if (!new)
4389                return -ENOMEM;
4390
4391        smp_wmb(); /* See comment in __pte_alloc */
4392
4393        ptl = pud_lock(mm, pud);
4394#ifndef __ARCH_HAS_4LEVEL_HACK
4395        if (!pud_present(*pud)) {
4396                mm_inc_nr_pmds(mm);
4397                pud_populate(mm, pud, new);
4398        } else  /* Another has populated it */
4399                pmd_free(mm, new);
4400#else
4401        if (!pgd_present(*pud)) {
4402                mm_inc_nr_pmds(mm);
4403                pgd_populate(mm, pud, new);
4404        } else /* Another has populated it */
4405                pmd_free(mm, new);
4406#endif /* __ARCH_HAS_4LEVEL_HACK */
4407        spin_unlock(ptl);
4408        return 0;
4409}
4410#endif /* __PAGETABLE_PMD_FOLDED */
4411
4412static int __follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4413                            struct mmu_notifier_range *range,
4414                            pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4415{
4416        pgd_t *pgd;
4417        p4d_t *p4d;
4418        pud_t *pud;
4419        pmd_t *pmd;
4420        pte_t *ptep;
4421
4422        pgd = pgd_offset(mm, address);
4423        if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4424                goto out;
4425
4426        p4d = p4d_offset(pgd, address);
4427        if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4428                goto out;
4429
4430        pud = pud_offset(p4d, address);
4431        if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4432                goto out;
4433
4434        pmd = pmd_offset(pud, address);
4435        VM_BUG_ON(pmd_trans_huge(*pmd));
4436
4437        if (pmd_huge(*pmd)) {
4438                if (!pmdpp)
4439                        goto out;
4440
4441                if (range) {
4442                        mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0,
4443                                                NULL, mm, address & PMD_MASK,
4444                                                (address & PMD_MASK) + PMD_SIZE);
4445                        mmu_notifier_invalidate_range_start(range);
4446                }
4447                *ptlp = pmd_lock(mm, pmd);
4448                if (pmd_huge(*pmd)) {
4449                        *pmdpp = pmd;
4450                        return 0;
4451                }
4452                spin_unlock(*ptlp);
4453                if (range)
4454                        mmu_notifier_invalidate_range_end(range);
4455        }
4456
4457        if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4458                goto out;
4459
4460        if (range) {
4461                mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
4462                                        address & PAGE_MASK,
4463                                        (address & PAGE_MASK) + PAGE_SIZE);
4464                mmu_notifier_invalidate_range_start(range);
4465        }
4466        ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4467        if (!pte_present(*ptep))
4468                goto unlock;
4469        *ptepp = ptep;
4470        return 0;
4471unlock:
4472        pte_unmap_unlock(ptep, *ptlp);
4473        if (range)
4474                mmu_notifier_invalidate_range_end(range);
4475out:
4476        return -EINVAL;
4477}
4478
4479static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4480                             pte_t **ptepp, spinlock_t **ptlp)
4481{
4482        int res;
4483
4484        /* (void) is needed to make gcc happy */
4485        (void) __cond_lock(*ptlp,
4486                           !(res = __follow_pte_pmd(mm, address, NULL,
4487                                                    ptepp, NULL, ptlp)));
4488        return res;
4489}
4490
4491int follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4492                   struct mmu_notifier_range *range,
4493                   pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4494{
4495        int res;
4496
4497        /* (void) is needed to make gcc happy */
4498        (void) __cond_lock(*ptlp,
4499                           !(res = __follow_pte_pmd(mm, address, range,
4500                                                    ptepp, pmdpp, ptlp)));
4501        return res;
4502}
4503EXPORT_SYMBOL(follow_pte_pmd);
4504
4505/**
4506 * follow_pfn - look up PFN at a user virtual address
4507 * @vma: memory mapping
4508 * @address: user virtual address
4509 * @pfn: location to store found PFN
4510 *
4511 * Only IO mappings and raw PFN mappings are allowed.
4512 *
4513 * Return: zero and the pfn at @pfn on success, -ve otherwise.
4514 */
4515int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4516        unsigned long *pfn)
4517{
4518        int ret = -EINVAL;
4519        spinlock_t *ptl;
4520        pte_t *ptep;
4521
4522        if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4523                return ret;
4524
4525        ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4526        if (ret)
4527                return ret;
4528        *pfn = pte_pfn(*ptep);
4529        pte_unmap_unlock(ptep, ptl);
4530        return 0;
4531}
4532EXPORT_SYMBOL(follow_pfn);
4533
4534#ifdef CONFIG_HAVE_IOREMAP_PROT
4535int follow_phys(struct vm_area_struct *vma,
4536                unsigned long address, unsigned int flags,
4537                unsigned long *prot, resource_size_t *phys)
4538{
4539        int ret = -EINVAL;
4540        pte_t *ptep, pte;
4541        spinlock_t *ptl;
4542
4543        if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4544                goto out;
4545
4546        if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4547                goto out;
4548        pte = *ptep;
4549
4550        if ((flags & FOLL_WRITE) && !pte_write(pte))
4551                goto unlock;
4552
4553        *prot = pgprot_val(pte_pgprot(pte));
4554        *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4555
4556        ret = 0;
4557unlock:
4558        pte_unmap_unlock(ptep, ptl);
4559out:
4560        return ret;
4561}
4562
4563int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4564                        void *buf, int len, int write)
4565{
4566        resource_size_t phys_addr;
4567        unsigned long prot = 0;
4568        void __iomem *maddr;
4569        int offset = addr & (PAGE_SIZE-1);
4570
4571        if (follow_phys(vma, addr, write, &prot, &phys_addr))
4572                return -EINVAL;
4573
4574        maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4575        if (!maddr)
4576                return -ENOMEM;
4577
4578        if (write)
4579                memcpy_toio(maddr + offset, buf, len);
4580        else
4581                memcpy_fromio(buf, maddr + offset, len);
4582        iounmap(maddr);
4583
4584        return len;
4585}
4586EXPORT_SYMBOL_GPL(generic_access_phys);
4587#endif
4588
4589/*
4590 * Access another process' address space as given in mm.  If non-NULL, use the
4591 * given task for page fault accounting.
4592 */
4593int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4594                unsigned long addr, void *buf, int len, unsigned int gup_flags)
4595{
4596        struct vm_area_struct *vma;
4597        void *old_buf = buf;
4598        int write = gup_flags & FOLL_WRITE;
4599
4600        if (mmap_read_lock_killable(mm))
4601                return 0;
4602
4603        /* ignore errors, just check how much was successfully transferred */
4604        while (len) {
4605                int bytes, ret, offset;
4606                void *maddr;
4607                struct page *page = NULL;
4608
4609                ret = get_user_pages_remote(tsk, mm, addr, 1,
4610                                gup_flags, &page, &vma, NULL);
4611                if (ret <= 0) {
4612#ifndef CONFIG_HAVE_IOREMAP_PROT
4613                        break;
4614#else
4615                        /*
4616                         * Check if this is a VM_IO | VM_PFNMAP VMA, which
4617                         * we can access using slightly different code.
4618                         */
4619                        vma = vma_lookup(mm, addr);
4620                        if (!vma)
4621                                break;
4622                        if (vma->vm_ops && vma->vm_ops->access)
4623                                ret = vma->vm_ops->access(vma, addr, buf,
4624                                                          len, write);
4625                        if (ret <= 0)
4626                                break;
4627                        bytes = ret;
4628#endif
4629                } else {
4630                        bytes = len;
4631                        offset = addr & (PAGE_SIZE-1);
4632                        if (bytes > PAGE_SIZE-offset)
4633                                bytes = PAGE_SIZE-offset;
4634
4635                        maddr = kmap(page);
4636                        if (write) {
4637                                copy_to_user_page(vma, page, addr,
4638                                                  maddr + offset, buf, bytes);
4639                                set_page_dirty_lock(page);
4640                        } else {
4641                                copy_from_user_page(vma, page, addr,
4642                                                    buf, maddr + offset, bytes);
4643                        }
4644                        kunmap(page);
4645                        put_page(page);
4646                }
4647                len -= bytes;
4648                buf += bytes;
4649                addr += bytes;
4650        }
4651        mmap_read_unlock(mm);
4652
4653        return buf - old_buf;
4654}
4655
4656/**
4657 * access_remote_vm - access another process' address space
4658 * @mm:         the mm_struct of the target address space
4659 * @addr:       start address to access
4660 * @buf:        source or destination buffer
4661 * @len:        number of bytes to transfer
4662 * @gup_flags:  flags modifying lookup behaviour
4663 *
4664 * The caller must hold a reference on @mm.
4665 *
4666 * Return: number of bytes copied from source to destination.
4667 */
4668int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4669                void *buf, int len, unsigned int gup_flags)
4670{
4671        return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
4672}
4673
4674/*
4675 * Access another process' address space.
4676 * Source/target buffer must be kernel space,
4677 * Do not walk the page table directly, use get_user_pages
4678 */
4679int access_process_vm(struct task_struct *tsk, unsigned long addr,
4680                void *buf, int len, unsigned int gup_flags)
4681{
4682        struct mm_struct *mm;
4683        int ret;
4684
4685        mm = get_task_mm(tsk);
4686        if (!mm)
4687                return 0;
4688
4689        ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4690
4691        mmput(mm);
4692
4693        return ret;
4694}
4695EXPORT_SYMBOL_GPL(access_process_vm);
4696
4697/*
4698 * Print the name of a VMA.
4699 */
4700void print_vma_addr(char *prefix, unsigned long ip)
4701{
4702        struct mm_struct *mm = current->mm;
4703        struct vm_area_struct *vma;
4704
4705        /*
4706         * we might be running from an atomic context so we cannot sleep
4707         */
4708        if (!mmap_read_trylock(mm))
4709                return;
4710
4711        vma = find_vma(mm, ip);
4712        if (vma && vma->vm_file) {
4713                struct file *f = vma->vm_file;
4714                char *buf = (char *)__get_free_page(GFP_NOWAIT);
4715                if (buf) {
4716                        char *p;
4717
4718                        p = file_path(f, buf, PAGE_SIZE);
4719                        if (IS_ERR(p))
4720                                p = "?";
4721                        printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4722                                        vma->vm_start,
4723                                        vma->vm_end - vma->vm_start);
4724                        free_page((unsigned long)buf);
4725                }
4726        }
4727        mmap_read_unlock(mm);
4728}
4729
4730#if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4731void __might_fault(const char *file, int line)
4732{
4733        /*
4734         * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4735         * holding the mmap_lock, this is safe because kernel memory doesn't
4736         * get paged out, therefore we'll never actually fault, and the
4737         * below annotations will generate false positives.
4738         */
4739        if (uaccess_kernel())
4740                return;
4741        if (pagefault_disabled())
4742                return;
4743        __might_sleep(file, line, 0);
4744#if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4745        if (current->mm)
4746                might_lock_read(&current->mm->mmap_lock);
4747#endif
4748}
4749EXPORT_SYMBOL(__might_fault);
4750#endif
4751
4752#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4753/*
4754 * Process all subpages of the specified huge page with the specified
4755 * operation.  The target subpage will be processed last to keep its
4756 * cache lines hot.
4757 */
4758static inline void process_huge_page(
4759        unsigned long addr_hint, unsigned int pages_per_huge_page,
4760        void (*process_subpage)(unsigned long addr, int idx, void *arg),
4761        void *arg)
4762{
4763        int i, n, base, l;
4764        unsigned long addr = addr_hint &
4765                ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4766
4767        /* Process target subpage last to keep its cache lines hot */
4768        might_sleep();
4769        n = (addr_hint - addr) / PAGE_SIZE;
4770        if (2 * n <= pages_per_huge_page) {
4771                /* If target subpage in first half of huge page */
4772                base = 0;
4773                l = n;
4774                /* Process subpages at the end of huge page */
4775                for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
4776                        cond_resched();
4777                        process_subpage(addr + i * PAGE_SIZE, i, arg);
4778                }
4779        } else {
4780                /* If target subpage in second half of huge page */
4781                base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
4782                l = pages_per_huge_page - n;
4783                /* Process subpages at the begin of huge page */
4784                for (i = 0; i < base; i++) {
4785                        cond_resched();
4786                        process_subpage(addr + i * PAGE_SIZE, i, arg);
4787                }
4788        }
4789        /*
4790         * Process remaining subpages in left-right-left-right pattern
4791         * towards the target subpage
4792         */
4793        for (i = 0; i < l; i++) {
4794                int left_idx = base + i;
4795                int right_idx = base + 2 * l - 1 - i;
4796
4797                cond_resched();
4798                process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
4799                cond_resched();
4800                process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
4801        }
4802}
4803
4804static void clear_gigantic_page(struct page *page,
4805                                unsigned long addr,
4806                                unsigned int pages_per_huge_page)
4807{
4808        int i;
4809        struct page *p = page;
4810
4811        might_sleep();
4812        for (i = 0; i < pages_per_huge_page;
4813             i++, p = mem_map_next(p, page, i)) {
4814                cond_resched();
4815                clear_user_highpage(p, addr + i * PAGE_SIZE);
4816        }
4817}
4818
4819static void clear_subpage(unsigned long addr, int idx, void *arg)
4820{
4821        struct page *page = arg;
4822
4823        clear_user_highpage(page + idx, addr);
4824}
4825
4826void clear_huge_page(struct page *page,
4827                     unsigned long addr_hint, unsigned int pages_per_huge_page)
4828{
4829        unsigned long addr = addr_hint &
4830                ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4831
4832        if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4833                clear_gigantic_page(page, addr, pages_per_huge_page);
4834                return;
4835        }
4836
4837        process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
4838}
4839
4840static void copy_user_gigantic_page(struct page *dst, struct page *src,
4841                                    unsigned long addr,
4842                                    struct vm_area_struct *vma,
4843                                    unsigned int pages_per_huge_page)
4844{
4845        int i;
4846        struct page *dst_base = dst;
4847        struct page *src_base = src;
4848
4849        for (i = 0; i < pages_per_huge_page; ) {
4850                cond_resched();
4851                copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4852
4853                i++;
4854                dst = mem_map_next(dst, dst_base, i);
4855                src = mem_map_next(src, src_base, i);
4856        }
4857}
4858
4859struct copy_subpage_arg {
4860        struct page *dst;
4861        struct page *src;
4862        struct vm_area_struct *vma;
4863};
4864
4865static void copy_subpage(unsigned long addr, int idx, void *arg)
4866{
4867        struct copy_subpage_arg *copy_arg = arg;
4868
4869        copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
4870                           addr, copy_arg->vma);
4871}
4872
4873void copy_user_huge_page(struct page *dst, struct page *src,
4874                         unsigned long addr_hint, struct vm_area_struct *vma,
4875                         unsigned int pages_per_huge_page)
4876{
4877        unsigned long addr = addr_hint &
4878                ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4879        struct copy_subpage_arg arg = {
4880                .dst = dst,
4881                .src = src,
4882                .vma = vma,
4883        };
4884
4885        if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4886                copy_user_gigantic_page(dst, src, addr, vma,
4887                                        pages_per_huge_page);
4888                return;
4889        }
4890
4891        process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
4892}
4893
4894long copy_huge_page_from_user(struct page *dst_page,
4895                                const void __user *usr_src,
4896                                unsigned int pages_per_huge_page,
4897                                bool allow_pagefault)
4898{
4899        void *src = (void *)usr_src;
4900        void *page_kaddr;
4901        unsigned long i, rc = 0;
4902        unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
4903        struct page *subpage = dst_page;
4904
4905        for (i = 0; i < pages_per_huge_page;
4906             i++, subpage = mem_map_next(subpage, dst_page, i)) {
4907                if (allow_pagefault)
4908                        page_kaddr = kmap(subpage);
4909                else
4910                        page_kaddr = kmap_atomic(subpage);
4911                rc = copy_from_user(page_kaddr,
4912                                (const void __user *)(src + i * PAGE_SIZE),
4913                                PAGE_SIZE);
4914                if (allow_pagefault)
4915                        kunmap(subpage);
4916                else
4917                        kunmap_atomic(page_kaddr);
4918
4919                ret_val -= (PAGE_SIZE - rc);
4920                if (rc)
4921                        break;
4922
4923                cond_resched();
4924        }
4925        return ret_val;
4926}
4927#endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4928
4929#if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4930
4931static struct kmem_cache *page_ptl_cachep;
4932
4933void __init ptlock_cache_init(void)
4934{
4935        page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4936                        SLAB_PANIC, NULL);
4937}
4938
4939bool ptlock_alloc(struct page *page)
4940{
4941        spinlock_t *ptl;
4942
4943        ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
4944        if (!ptl)
4945                return false;
4946        page->ptl = ptl;
4947        return true;
4948}
4949
4950void ptlock_free(struct page *page)
4951{
4952        kmem_cache_free(page_ptl_cachep, page->ptl);
4953}
4954#endif
4955