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