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