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