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_atomic(dst); 2845 uaddr = (void __user *)(addr & PAGE_MASK); 2846 2847 /* 2848 * On architectures with software "accessed" bits, we would 2849 * take a double page fault, so mark it accessed here. 2850 */ 2851 vmf->pte = NULL; 2852 if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) { 2853 pte_t entry; 2854 2855 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl); 2856 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 2857 /* 2858 * Other thread has already handled the fault 2859 * and update local tlb only 2860 */ 2861 if (vmf->pte) 2862 update_mmu_tlb(vma, addr, vmf->pte); 2863 ret = -EAGAIN; 2864 goto pte_unlock; 2865 } 2866 2867 entry = pte_mkyoung(vmf->orig_pte); 2868 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0)) 2869 update_mmu_cache_range(vmf, vma, addr, vmf->pte, 1); 2870 } 2871 2872 /* 2873 * This really shouldn't fail, because the page is there 2874 * in the page tables. But it might just be unreadable, 2875 * in which case we just give up and fill the result with 2876 * zeroes. 2877 */ 2878 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) { 2879 if (vmf->pte) 2880 goto warn; 2881 2882 /* Re-validate under PTL if the page is still mapped */ 2883 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl); 2884 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 2885 /* The PTE changed under us, update local tlb */ 2886 if (vmf->pte) 2887 update_mmu_tlb(vma, addr, vmf->pte); 2888 ret = -EAGAIN; 2889 goto pte_unlock; 2890 } 2891 2892 /* 2893 * The same page can be mapped back since last copy attempt. 2894 * Try to copy again under PTL. 2895 */ 2896 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) { 2897 /* 2898 * Give a warn in case there can be some obscure 2899 * use-case 2900 */ 2901 warn: 2902 WARN_ON_ONCE(1); 2903 clear_page(kaddr); 2904 } 2905 } 2906 2907 ret = 0; 2908 2909 pte_unlock: 2910 if (vmf->pte) 2911 pte_unmap_unlock(vmf->pte, vmf->ptl); 2912 kunmap_atomic(kaddr); 2913 flush_dcache_page(dst); 2914 2915 return ret; 2916 } 2917 2918 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma) 2919 { 2920 struct file *vm_file = vma->vm_file; 2921 2922 if (vm_file) 2923 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO; 2924 2925 /* 2926 * Special mappings (e.g. VDSO) do not have any file so fake 2927 * a default GFP_KERNEL for them. 2928 */ 2929 return GFP_KERNEL; 2930 } 2931 2932 /* 2933 * Notify the address space that the page is about to become writable so that 2934 * it can prohibit this or wait for the page to get into an appropriate state. 2935 * 2936 * We do this without the lock held, so that it can sleep if it needs to. 2937 */ 2938 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf, struct folio *folio) 2939 { 2940 vm_fault_t ret; 2941 unsigned int old_flags = vmf->flags; 2942 2943 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; 2944 2945 if (vmf->vma->vm_file && 2946 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host)) 2947 return VM_FAULT_SIGBUS; 2948 2949 ret = vmf->vma->vm_ops->page_mkwrite(vmf); 2950 /* Restore original flags so that caller is not surprised */ 2951 vmf->flags = old_flags; 2952 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) 2953 return ret; 2954 if (unlikely(!(ret & VM_FAULT_LOCKED))) { 2955 folio_lock(folio); 2956 if (!folio->mapping) { 2957 folio_unlock(folio); 2958 return 0; /* retry */ 2959 } 2960 ret |= VM_FAULT_LOCKED; 2961 } else 2962 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 2963 return ret; 2964 } 2965 2966 /* 2967 * Handle dirtying of a page in shared file mapping on a write fault. 2968 * 2969 * The function expects the page to be locked and unlocks it. 2970 */ 2971 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf) 2972 { 2973 struct vm_area_struct *vma = vmf->vma; 2974 struct address_space *mapping; 2975 struct folio *folio = page_folio(vmf->page); 2976 bool dirtied; 2977 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite; 2978 2979 dirtied = folio_mark_dirty(folio); 2980 VM_BUG_ON_FOLIO(folio_test_anon(folio), folio); 2981 /* 2982 * Take a local copy of the address_space - folio.mapping may be zeroed 2983 * by truncate after folio_unlock(). The address_space itself remains 2984 * pinned by vma->vm_file's reference. We rely on folio_unlock()'s 2985 * release semantics to prevent the compiler from undoing this copying. 2986 */ 2987 mapping = folio_raw_mapping(folio); 2988 folio_unlock(folio); 2989 2990 if (!page_mkwrite) 2991 file_update_time(vma->vm_file); 2992 2993 /* 2994 * Throttle page dirtying rate down to writeback speed. 2995 * 2996 * mapping may be NULL here because some device drivers do not 2997 * set page.mapping but still dirty their pages 2998 * 2999 * Drop the mmap_lock before waiting on IO, if we can. The file 3000 * is pinning the mapping, as per above. 3001 */ 3002 if ((dirtied || page_mkwrite) && mapping) { 3003 struct file *fpin; 3004 3005 fpin = maybe_unlock_mmap_for_io(vmf, NULL); 3006 balance_dirty_pages_ratelimited(mapping); 3007 if (fpin) { 3008 fput(fpin); 3009 return VM_FAULT_COMPLETED; 3010 } 3011 } 3012 3013 return 0; 3014 } 3015 3016 /* 3017 * Handle write page faults for pages that can be reused in the current vma 3018 * 3019 * This can happen either due to the mapping being with the VM_SHARED flag, 3020 * or due to us being the last reference standing to the page. In either 3021 * case, all we need to do here is to mark the page as writable and update 3022 * any related book-keeping. 3023 */ 3024 static inline void wp_page_reuse(struct vm_fault *vmf, struct folio *folio) 3025 __releases(vmf->ptl) 3026 { 3027 struct vm_area_struct *vma = vmf->vma; 3028 pte_t entry; 3029 3030 VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE)); 3031 3032 if (folio) { 3033 VM_BUG_ON(folio_test_anon(folio) && 3034 !PageAnonExclusive(vmf->page)); 3035 /* 3036 * Clear the folio's cpupid information as the existing 3037 * information potentially belongs to a now completely 3038 * unrelated process. 3039 */ 3040 folio_xchg_last_cpupid(folio, (1 << LAST_CPUPID_SHIFT) - 1); 3041 } 3042 3043 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte)); 3044 entry = pte_mkyoung(vmf->orig_pte); 3045 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 3046 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1)) 3047 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 3048 pte_unmap_unlock(vmf->pte, vmf->ptl); 3049 count_vm_event(PGREUSE); 3050 } 3051 3052 /* 3053 * We could add a bitflag somewhere, but for now, we know that all 3054 * vm_ops that have a ->map_pages have been audited and don't need 3055 * the mmap_lock to be held. 3056 */ 3057 static inline vm_fault_t vmf_can_call_fault(const struct vm_fault *vmf) 3058 { 3059 struct vm_area_struct *vma = vmf->vma; 3060 3061 if (vma->vm_ops->map_pages || !(vmf->flags & FAULT_FLAG_VMA_LOCK)) 3062 return 0; 3063 vma_end_read(vma); 3064 return VM_FAULT_RETRY; 3065 } 3066 3067 static vm_fault_t vmf_anon_prepare(struct vm_fault *vmf) 3068 { 3069 struct vm_area_struct *vma = vmf->vma; 3070 3071 if (likely(vma->anon_vma)) 3072 return 0; 3073 if (vmf->flags & FAULT_FLAG_VMA_LOCK) { 3074 vma_end_read(vma); 3075 return VM_FAULT_RETRY; 3076 } 3077 if (__anon_vma_prepare(vma)) 3078 return VM_FAULT_OOM; 3079 return 0; 3080 } 3081 3082 /* 3083 * Handle the case of a page which we actually need to copy to a new page, 3084 * either due to COW or unsharing. 3085 * 3086 * Called with mmap_lock locked and the old page referenced, but 3087 * without the ptl held. 3088 * 3089 * High level logic flow: 3090 * 3091 * - Allocate a page, copy the content of the old page to the new one. 3092 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc. 3093 * - Take the PTL. If the pte changed, bail out and release the allocated page 3094 * - If the pte is still the way we remember it, update the page table and all 3095 * relevant references. This includes dropping the reference the page-table 3096 * held to the old page, as well as updating the rmap. 3097 * - In any case, unlock the PTL and drop the reference we took to the old page. 3098 */ 3099 static vm_fault_t wp_page_copy(struct vm_fault *vmf) 3100 { 3101 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 3102 struct vm_area_struct *vma = vmf->vma; 3103 struct mm_struct *mm = vma->vm_mm; 3104 struct folio *old_folio = NULL; 3105 struct folio *new_folio = NULL; 3106 pte_t entry; 3107 int page_copied = 0; 3108 struct mmu_notifier_range range; 3109 vm_fault_t ret; 3110 3111 delayacct_wpcopy_start(); 3112 3113 if (vmf->page) 3114 old_folio = page_folio(vmf->page); 3115 ret = vmf_anon_prepare(vmf); 3116 if (unlikely(ret)) 3117 goto out; 3118 3119 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) { 3120 new_folio = vma_alloc_zeroed_movable_folio(vma, vmf->address); 3121 if (!new_folio) 3122 goto oom; 3123 } else { 3124 int err; 3125 new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, 3126 vmf->address, false); 3127 if (!new_folio) 3128 goto oom; 3129 3130 err = __wp_page_copy_user(&new_folio->page, vmf->page, vmf); 3131 if (err) { 3132 /* 3133 * COW failed, if the fault was solved by other, 3134 * it's fine. If not, userspace would re-fault on 3135 * the same address and we will handle the fault 3136 * from the second attempt. 3137 * The -EHWPOISON case will not be retried. 3138 */ 3139 folio_put(new_folio); 3140 if (old_folio) 3141 folio_put(old_folio); 3142 3143 delayacct_wpcopy_end(); 3144 return err == -EHWPOISON ? VM_FAULT_HWPOISON : 0; 3145 } 3146 kmsan_copy_page_meta(&new_folio->page, vmf->page); 3147 } 3148 3149 if (mem_cgroup_charge(new_folio, mm, GFP_KERNEL)) 3150 goto oom_free_new; 3151 folio_throttle_swaprate(new_folio, GFP_KERNEL); 3152 3153 __folio_mark_uptodate(new_folio); 3154 3155 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 3156 vmf->address & PAGE_MASK, 3157 (vmf->address & PAGE_MASK) + PAGE_SIZE); 3158 mmu_notifier_invalidate_range_start(&range); 3159 3160 /* 3161 * Re-check the pte - we dropped the lock 3162 */ 3163 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl); 3164 if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 3165 if (old_folio) { 3166 if (!folio_test_anon(old_folio)) { 3167 dec_mm_counter(mm, mm_counter_file(&old_folio->page)); 3168 inc_mm_counter(mm, MM_ANONPAGES); 3169 } 3170 } else { 3171 ksm_might_unmap_zero_page(mm, vmf->orig_pte); 3172 inc_mm_counter(mm, MM_ANONPAGES); 3173 } 3174 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte)); 3175 entry = mk_pte(&new_folio->page, vma->vm_page_prot); 3176 entry = pte_sw_mkyoung(entry); 3177 if (unlikely(unshare)) { 3178 if (pte_soft_dirty(vmf->orig_pte)) 3179 entry = pte_mksoft_dirty(entry); 3180 if (pte_uffd_wp(vmf->orig_pte)) 3181 entry = pte_mkuffd_wp(entry); 3182 } else { 3183 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 3184 } 3185 3186 /* 3187 * Clear the pte entry and flush it first, before updating the 3188 * pte with the new entry, to keep TLBs on different CPUs in 3189 * sync. This code used to set the new PTE then flush TLBs, but 3190 * that left a window where the new PTE could be loaded into 3191 * some TLBs while the old PTE remains in others. 3192 */ 3193 ptep_clear_flush(vma, vmf->address, vmf->pte); 3194 folio_add_new_anon_rmap(new_folio, vma, vmf->address); 3195 folio_add_lru_vma(new_folio, vma); 3196 /* 3197 * We call the notify macro here because, when using secondary 3198 * mmu page tables (such as kvm shadow page tables), we want the 3199 * new page to be mapped directly into the secondary page table. 3200 */ 3201 BUG_ON(unshare && pte_write(entry)); 3202 set_pte_at_notify(mm, vmf->address, vmf->pte, entry); 3203 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 3204 if (old_folio) { 3205 /* 3206 * Only after switching the pte to the new page may 3207 * we remove the mapcount here. Otherwise another 3208 * process may come and find the rmap count decremented 3209 * before the pte is switched to the new page, and 3210 * "reuse" the old page writing into it while our pte 3211 * here still points into it and can be read by other 3212 * threads. 3213 * 3214 * The critical issue is to order this 3215 * page_remove_rmap with the ptp_clear_flush above. 3216 * Those stores are ordered by (if nothing else,) 3217 * the barrier present in the atomic_add_negative 3218 * in page_remove_rmap. 3219 * 3220 * Then the TLB flush in ptep_clear_flush ensures that 3221 * no process can access the old page before the 3222 * decremented mapcount is visible. And the old page 3223 * cannot be reused until after the decremented 3224 * mapcount is visible. So transitively, TLBs to 3225 * old page will be flushed before it can be reused. 3226 */ 3227 page_remove_rmap(vmf->page, vma, false); 3228 } 3229 3230 /* Free the old page.. */ 3231 new_folio = old_folio; 3232 page_copied = 1; 3233 pte_unmap_unlock(vmf->pte, vmf->ptl); 3234 } else if (vmf->pte) { 3235 update_mmu_tlb(vma, vmf->address, vmf->pte); 3236 pte_unmap_unlock(vmf->pte, vmf->ptl); 3237 } 3238 3239 mmu_notifier_invalidate_range_end(&range); 3240 3241 if (new_folio) 3242 folio_put(new_folio); 3243 if (old_folio) { 3244 if (page_copied) 3245 free_swap_cache(&old_folio->page); 3246 folio_put(old_folio); 3247 } 3248 3249 delayacct_wpcopy_end(); 3250 return 0; 3251 oom_free_new: 3252 folio_put(new_folio); 3253 oom: 3254 ret = VM_FAULT_OOM; 3255 out: 3256 if (old_folio) 3257 folio_put(old_folio); 3258 3259 delayacct_wpcopy_end(); 3260 return ret; 3261 } 3262 3263 /** 3264 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE 3265 * writeable once the page is prepared 3266 * 3267 * @vmf: structure describing the fault 3268 * @folio: the folio of vmf->page 3269 * 3270 * This function handles all that is needed to finish a write page fault in a 3271 * shared mapping due to PTE being read-only once the mapped page is prepared. 3272 * It handles locking of PTE and modifying it. 3273 * 3274 * The function expects the page to be locked or other protection against 3275 * concurrent faults / writeback (such as DAX radix tree locks). 3276 * 3277 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before 3278 * we acquired PTE lock. 3279 */ 3280 static vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf, struct folio *folio) 3281 { 3282 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED)); 3283 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address, 3284 &vmf->ptl); 3285 if (!vmf->pte) 3286 return VM_FAULT_NOPAGE; 3287 /* 3288 * We might have raced with another page fault while we released the 3289 * pte_offset_map_lock. 3290 */ 3291 if (!pte_same(ptep_get(vmf->pte), vmf->orig_pte)) { 3292 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte); 3293 pte_unmap_unlock(vmf->pte, vmf->ptl); 3294 return VM_FAULT_NOPAGE; 3295 } 3296 wp_page_reuse(vmf, folio); 3297 return 0; 3298 } 3299 3300 /* 3301 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED 3302 * mapping 3303 */ 3304 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf) 3305 { 3306 struct vm_area_struct *vma = vmf->vma; 3307 3308 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) { 3309 vm_fault_t ret; 3310 3311 pte_unmap_unlock(vmf->pte, vmf->ptl); 3312 ret = vmf_can_call_fault(vmf); 3313 if (ret) 3314 return ret; 3315 3316 vmf->flags |= FAULT_FLAG_MKWRITE; 3317 ret = vma->vm_ops->pfn_mkwrite(vmf); 3318 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)) 3319 return ret; 3320 return finish_mkwrite_fault(vmf, NULL); 3321 } 3322 wp_page_reuse(vmf, NULL); 3323 return 0; 3324 } 3325 3326 static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio) 3327 __releases(vmf->ptl) 3328 { 3329 struct vm_area_struct *vma = vmf->vma; 3330 vm_fault_t ret = 0; 3331 3332 folio_get(folio); 3333 3334 if (vma->vm_ops && vma->vm_ops->page_mkwrite) { 3335 vm_fault_t tmp; 3336 3337 pte_unmap_unlock(vmf->pte, vmf->ptl); 3338 tmp = vmf_can_call_fault(vmf); 3339 if (tmp) { 3340 folio_put(folio); 3341 return tmp; 3342 } 3343 3344 tmp = do_page_mkwrite(vmf, folio); 3345 if (unlikely(!tmp || (tmp & 3346 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { 3347 folio_put(folio); 3348 return tmp; 3349 } 3350 tmp = finish_mkwrite_fault(vmf, folio); 3351 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { 3352 folio_unlock(folio); 3353 folio_put(folio); 3354 return tmp; 3355 } 3356 } else { 3357 wp_page_reuse(vmf, folio); 3358 folio_lock(folio); 3359 } 3360 ret |= fault_dirty_shared_page(vmf); 3361 folio_put(folio); 3362 3363 return ret; 3364 } 3365 3366 static bool wp_can_reuse_anon_folio(struct folio *folio, 3367 struct vm_area_struct *vma) 3368 { 3369 /* 3370 * We have to verify under folio lock: these early checks are 3371 * just an optimization to avoid locking the folio and freeing 3372 * the swapcache if there is little hope that we can reuse. 3373 * 3374 * KSM doesn't necessarily raise the folio refcount. 3375 */ 3376 if (folio_test_ksm(folio) || folio_ref_count(folio) > 3) 3377 return false; 3378 if (!folio_test_lru(folio)) 3379 /* 3380 * We cannot easily detect+handle references from 3381 * remote LRU caches or references to LRU folios. 3382 */ 3383 lru_add_drain(); 3384 if (folio_ref_count(folio) > 1 + folio_test_swapcache(folio)) 3385 return false; 3386 if (!folio_trylock(folio)) 3387 return false; 3388 if (folio_test_swapcache(folio)) 3389 folio_free_swap(folio); 3390 if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) { 3391 folio_unlock(folio); 3392 return false; 3393 } 3394 /* 3395 * Ok, we've got the only folio reference from our mapping 3396 * and the folio is locked, it's dark out, and we're wearing 3397 * sunglasses. Hit it. 3398 */ 3399 folio_move_anon_rmap(folio, vma); 3400 folio_unlock(folio); 3401 return true; 3402 } 3403 3404 /* 3405 * This routine handles present pages, when 3406 * * users try to write to a shared page (FAULT_FLAG_WRITE) 3407 * * GUP wants to take a R/O pin on a possibly shared anonymous page 3408 * (FAULT_FLAG_UNSHARE) 3409 * 3410 * It is done by copying the page to a new address and decrementing the 3411 * shared-page counter for the old page. 3412 * 3413 * Note that this routine assumes that the protection checks have been 3414 * done by the caller (the low-level page fault routine in most cases). 3415 * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've 3416 * done any necessary COW. 3417 * 3418 * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even 3419 * though the page will change only once the write actually happens. This 3420 * avoids a few races, and potentially makes it more efficient. 3421 * 3422 * We enter with non-exclusive mmap_lock (to exclude vma changes, 3423 * but allow concurrent faults), with pte both mapped and locked. 3424 * We return with mmap_lock still held, but pte unmapped and unlocked. 3425 */ 3426 static vm_fault_t do_wp_page(struct vm_fault *vmf) 3427 __releases(vmf->ptl) 3428 { 3429 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 3430 struct vm_area_struct *vma = vmf->vma; 3431 struct folio *folio = NULL; 3432 pte_t pte; 3433 3434 if (likely(!unshare)) { 3435 if (userfaultfd_pte_wp(vma, ptep_get(vmf->pte))) { 3436 if (!userfaultfd_wp_async(vma)) { 3437 pte_unmap_unlock(vmf->pte, vmf->ptl); 3438 return handle_userfault(vmf, VM_UFFD_WP); 3439 } 3440 3441 /* 3442 * Nothing needed (cache flush, TLB invalidations, 3443 * etc.) because we're only removing the uffd-wp bit, 3444 * which is completely invisible to the user. 3445 */ 3446 pte = pte_clear_uffd_wp(ptep_get(vmf->pte)); 3447 3448 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte); 3449 /* 3450 * Update this to be prepared for following up CoW 3451 * handling 3452 */ 3453 vmf->orig_pte = pte; 3454 } 3455 3456 /* 3457 * Userfaultfd write-protect can defer flushes. Ensure the TLB 3458 * is flushed in this case before copying. 3459 */ 3460 if (unlikely(userfaultfd_wp(vmf->vma) && 3461 mm_tlb_flush_pending(vmf->vma->vm_mm))) 3462 flush_tlb_page(vmf->vma, vmf->address); 3463 } 3464 3465 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte); 3466 3467 if (vmf->page) 3468 folio = page_folio(vmf->page); 3469 3470 /* 3471 * Shared mapping: we are guaranteed to have VM_WRITE and 3472 * FAULT_FLAG_WRITE set at this point. 3473 */ 3474 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) { 3475 /* 3476 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a 3477 * VM_PFNMAP VMA. 3478 * 3479 * We should not cow pages in a shared writeable mapping. 3480 * Just mark the pages writable and/or call ops->pfn_mkwrite. 3481 */ 3482 if (!vmf->page) 3483 return wp_pfn_shared(vmf); 3484 return wp_page_shared(vmf, folio); 3485 } 3486 3487 /* 3488 * Private mapping: create an exclusive anonymous page copy if reuse 3489 * is impossible. We might miss VM_WRITE for FOLL_FORCE handling. 3490 * 3491 * If we encounter a page that is marked exclusive, we must reuse 3492 * the page without further checks. 3493 */ 3494 if (folio && folio_test_anon(folio) && 3495 (PageAnonExclusive(vmf->page) || wp_can_reuse_anon_folio(folio, vma))) { 3496 if (!PageAnonExclusive(vmf->page)) 3497 SetPageAnonExclusive(vmf->page); 3498 if (unlikely(unshare)) { 3499 pte_unmap_unlock(vmf->pte, vmf->ptl); 3500 return 0; 3501 } 3502 wp_page_reuse(vmf, folio); 3503 return 0; 3504 } 3505 /* 3506 * Ok, we need to copy. Oh, well.. 3507 */ 3508 if (folio) 3509 folio_get(folio); 3510 3511 pte_unmap_unlock(vmf->pte, vmf->ptl); 3512 #ifdef CONFIG_KSM 3513 if (folio && folio_test_ksm(folio)) 3514 count_vm_event(COW_KSM); 3515 #endif 3516 return wp_page_copy(vmf); 3517 } 3518 3519 static void unmap_mapping_range_vma(struct vm_area_struct *vma, 3520 unsigned long start_addr, unsigned long end_addr, 3521 struct zap_details *details) 3522 { 3523 zap_page_range_single(vma, start_addr, end_addr - start_addr, details); 3524 } 3525 3526 static inline void unmap_mapping_range_tree(struct rb_root_cached *root, 3527 pgoff_t first_index, 3528 pgoff_t last_index, 3529 struct zap_details *details) 3530 { 3531 struct vm_area_struct *vma; 3532 pgoff_t vba, vea, zba, zea; 3533 3534 vma_interval_tree_foreach(vma, root, first_index, last_index) { 3535 vba = vma->vm_pgoff; 3536 vea = vba + vma_pages(vma) - 1; 3537 zba = max(first_index, vba); 3538 zea = min(last_index, vea); 3539 3540 unmap_mapping_range_vma(vma, 3541 ((zba - vba) << PAGE_SHIFT) + vma->vm_start, 3542 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start, 3543 details); 3544 } 3545 } 3546 3547 /** 3548 * unmap_mapping_folio() - Unmap single folio from processes. 3549 * @folio: The locked folio to be unmapped. 3550 * 3551 * Unmap this folio from any userspace process which still has it mmaped. 3552 * Typically, for efficiency, the range of nearby pages has already been 3553 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once 3554 * truncation or invalidation holds the lock on a folio, it may find that 3555 * the page has been remapped again: and then uses unmap_mapping_folio() 3556 * to unmap it finally. 3557 */ 3558 void unmap_mapping_folio(struct folio *folio) 3559 { 3560 struct address_space *mapping = folio->mapping; 3561 struct zap_details details = { }; 3562 pgoff_t first_index; 3563 pgoff_t last_index; 3564 3565 VM_BUG_ON(!folio_test_locked(folio)); 3566 3567 first_index = folio->index; 3568 last_index = folio_next_index(folio) - 1; 3569 3570 details.even_cows = false; 3571 details.single_folio = folio; 3572 details.zap_flags = ZAP_FLAG_DROP_MARKER; 3573 3574 i_mmap_lock_read(mapping); 3575 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root))) 3576 unmap_mapping_range_tree(&mapping->i_mmap, first_index, 3577 last_index, &details); 3578 i_mmap_unlock_read(mapping); 3579 } 3580 3581 /** 3582 * unmap_mapping_pages() - Unmap pages from processes. 3583 * @mapping: The address space containing pages to be unmapped. 3584 * @start: Index of first page to be unmapped. 3585 * @nr: Number of pages to be unmapped. 0 to unmap to end of file. 3586 * @even_cows: Whether to unmap even private COWed pages. 3587 * 3588 * Unmap the pages in this address space from any userspace process which 3589 * has them mmaped. Generally, you want to remove COWed pages as well when 3590 * a file is being truncated, but not when invalidating pages from the page 3591 * cache. 3592 */ 3593 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start, 3594 pgoff_t nr, bool even_cows) 3595 { 3596 struct zap_details details = { }; 3597 pgoff_t first_index = start; 3598 pgoff_t last_index = start + nr - 1; 3599 3600 details.even_cows = even_cows; 3601 if (last_index < first_index) 3602 last_index = ULONG_MAX; 3603 3604 i_mmap_lock_read(mapping); 3605 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root))) 3606 unmap_mapping_range_tree(&mapping->i_mmap, first_index, 3607 last_index, &details); 3608 i_mmap_unlock_read(mapping); 3609 } 3610 EXPORT_SYMBOL_GPL(unmap_mapping_pages); 3611 3612 /** 3613 * unmap_mapping_range - unmap the portion of all mmaps in the specified 3614 * address_space corresponding to the specified byte range in the underlying 3615 * file. 3616 * 3617 * @mapping: the address space containing mmaps to be unmapped. 3618 * @holebegin: byte in first page to unmap, relative to the start of 3619 * the underlying file. This will be rounded down to a PAGE_SIZE 3620 * boundary. Note that this is different from truncate_pagecache(), which 3621 * must keep the partial page. In contrast, we must get rid of 3622 * partial pages. 3623 * @holelen: size of prospective hole in bytes. This will be rounded 3624 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the 3625 * end of the file. 3626 * @even_cows: 1 when truncating a file, unmap even private COWed pages; 3627 * but 0 when invalidating pagecache, don't throw away private data. 3628 */ 3629 void unmap_mapping_range(struct address_space *mapping, 3630 loff_t const holebegin, loff_t const holelen, int even_cows) 3631 { 3632 pgoff_t hba = holebegin >> PAGE_SHIFT; 3633 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; 3634 3635 /* Check for overflow. */ 3636 if (sizeof(holelen) > sizeof(hlen)) { 3637 long long holeend = 3638 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; 3639 if (holeend & ~(long long)ULONG_MAX) 3640 hlen = ULONG_MAX - hba + 1; 3641 } 3642 3643 unmap_mapping_pages(mapping, hba, hlen, even_cows); 3644 } 3645 EXPORT_SYMBOL(unmap_mapping_range); 3646 3647 /* 3648 * Restore a potential device exclusive pte to a working pte entry 3649 */ 3650 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf) 3651 { 3652 struct folio *folio = page_folio(vmf->page); 3653 struct vm_area_struct *vma = vmf->vma; 3654 struct mmu_notifier_range range; 3655 vm_fault_t ret; 3656 3657 /* 3658 * We need a reference to lock the folio because we don't hold 3659 * the PTL so a racing thread can remove the device-exclusive 3660 * entry and unmap it. If the folio is free the entry must 3661 * have been removed already. If it happens to have already 3662 * been re-allocated after being freed all we do is lock and 3663 * unlock it. 3664 */ 3665 if (!folio_try_get(folio)) 3666 return 0; 3667 3668 ret = folio_lock_or_retry(folio, vmf); 3669 if (ret) { 3670 folio_put(folio); 3671 return ret; 3672 } 3673 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, 3674 vma->vm_mm, vmf->address & PAGE_MASK, 3675 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL); 3676 mmu_notifier_invalidate_range_start(&range); 3677 3678 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 3679 &vmf->ptl); 3680 if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) 3681 restore_exclusive_pte(vma, vmf->page, vmf->address, vmf->pte); 3682 3683 if (vmf->pte) 3684 pte_unmap_unlock(vmf->pte, vmf->ptl); 3685 folio_unlock(folio); 3686 folio_put(folio); 3687 3688 mmu_notifier_invalidate_range_end(&range); 3689 return 0; 3690 } 3691 3692 static inline bool should_try_to_free_swap(struct folio *folio, 3693 struct vm_area_struct *vma, 3694 unsigned int fault_flags) 3695 { 3696 if (!folio_test_swapcache(folio)) 3697 return false; 3698 if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) || 3699 folio_test_mlocked(folio)) 3700 return true; 3701 /* 3702 * If we want to map a page that's in the swapcache writable, we 3703 * have to detect via the refcount if we're really the exclusive 3704 * user. Try freeing the swapcache to get rid of the swapcache 3705 * reference only in case it's likely that we'll be the exlusive user. 3706 */ 3707 return (fault_flags & FAULT_FLAG_WRITE) && !folio_test_ksm(folio) && 3708 folio_ref_count(folio) == 2; 3709 } 3710 3711 static vm_fault_t pte_marker_clear(struct vm_fault *vmf) 3712 { 3713 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, 3714 vmf->address, &vmf->ptl); 3715 if (!vmf->pte) 3716 return 0; 3717 /* 3718 * Be careful so that we will only recover a special uffd-wp pte into a 3719 * none pte. Otherwise it means the pte could have changed, so retry. 3720 * 3721 * This should also cover the case where e.g. the pte changed 3722 * quickly from a PTE_MARKER_UFFD_WP into PTE_MARKER_POISONED. 3723 * So is_pte_marker() check is not enough to safely drop the pte. 3724 */ 3725 if (pte_same(vmf->orig_pte, ptep_get(vmf->pte))) 3726 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte); 3727 pte_unmap_unlock(vmf->pte, vmf->ptl); 3728 return 0; 3729 } 3730 3731 static vm_fault_t do_pte_missing(struct vm_fault *vmf) 3732 { 3733 if (vma_is_anonymous(vmf->vma)) 3734 return do_anonymous_page(vmf); 3735 else 3736 return do_fault(vmf); 3737 } 3738 3739 /* 3740 * This is actually a page-missing access, but with uffd-wp special pte 3741 * installed. It means this pte was wr-protected before being unmapped. 3742 */ 3743 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf) 3744 { 3745 /* 3746 * Just in case there're leftover special ptes even after the region 3747 * got unregistered - we can simply clear them. 3748 */ 3749 if (unlikely(!userfaultfd_wp(vmf->vma))) 3750 return pte_marker_clear(vmf); 3751 3752 return do_pte_missing(vmf); 3753 } 3754 3755 static vm_fault_t handle_pte_marker(struct vm_fault *vmf) 3756 { 3757 swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte); 3758 unsigned long marker = pte_marker_get(entry); 3759 3760 /* 3761 * PTE markers should never be empty. If anything weird happened, 3762 * the best thing to do is to kill the process along with its mm. 3763 */ 3764 if (WARN_ON_ONCE(!marker)) 3765 return VM_FAULT_SIGBUS; 3766 3767 /* Higher priority than uffd-wp when data corrupted */ 3768 if (marker & PTE_MARKER_POISONED) 3769 return VM_FAULT_HWPOISON; 3770 3771 if (pte_marker_entry_uffd_wp(entry)) 3772 return pte_marker_handle_uffd_wp(vmf); 3773 3774 /* This is an unknown pte marker */ 3775 return VM_FAULT_SIGBUS; 3776 } 3777 3778 /* 3779 * We enter with non-exclusive mmap_lock (to exclude vma changes, 3780 * but allow concurrent faults), and pte mapped but not yet locked. 3781 * We return with pte unmapped and unlocked. 3782 * 3783 * We return with the mmap_lock locked or unlocked in the same cases 3784 * as does filemap_fault(). 3785 */ 3786 vm_fault_t do_swap_page(struct vm_fault *vmf) 3787 { 3788 struct vm_area_struct *vma = vmf->vma; 3789 struct folio *swapcache, *folio = NULL; 3790 struct page *page; 3791 struct swap_info_struct *si = NULL; 3792 rmap_t rmap_flags = RMAP_NONE; 3793 bool exclusive = false; 3794 swp_entry_t entry; 3795 pte_t pte; 3796 vm_fault_t ret = 0; 3797 void *shadow = NULL; 3798 3799 if (!pte_unmap_same(vmf)) 3800 goto out; 3801 3802 entry = pte_to_swp_entry(vmf->orig_pte); 3803 if (unlikely(non_swap_entry(entry))) { 3804 if (is_migration_entry(entry)) { 3805 migration_entry_wait(vma->vm_mm, vmf->pmd, 3806 vmf->address); 3807 } else if (is_device_exclusive_entry(entry)) { 3808 vmf->page = pfn_swap_entry_to_page(entry); 3809 ret = remove_device_exclusive_entry(vmf); 3810 } else if (is_device_private_entry(entry)) { 3811 if (vmf->flags & FAULT_FLAG_VMA_LOCK) { 3812 /* 3813 * migrate_to_ram is not yet ready to operate 3814 * under VMA lock. 3815 */ 3816 vma_end_read(vma); 3817 ret = VM_FAULT_RETRY; 3818 goto out; 3819 } 3820 3821 vmf->page = pfn_swap_entry_to_page(entry); 3822 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 3823 vmf->address, &vmf->ptl); 3824 if (unlikely(!vmf->pte || 3825 !pte_same(ptep_get(vmf->pte), 3826 vmf->orig_pte))) 3827 goto unlock; 3828 3829 /* 3830 * Get a page reference while we know the page can't be 3831 * freed. 3832 */ 3833 get_page(vmf->page); 3834 pte_unmap_unlock(vmf->pte, vmf->ptl); 3835 ret = vmf->page->pgmap->ops->migrate_to_ram(vmf); 3836 put_page(vmf->page); 3837 } else if (is_hwpoison_entry(entry)) { 3838 ret = VM_FAULT_HWPOISON; 3839 } else if (is_pte_marker_entry(entry)) { 3840 ret = handle_pte_marker(vmf); 3841 } else { 3842 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL); 3843 ret = VM_FAULT_SIGBUS; 3844 } 3845 goto out; 3846 } 3847 3848 /* Prevent swapoff from happening to us. */ 3849 si = get_swap_device(entry); 3850 if (unlikely(!si)) 3851 goto out; 3852 3853 folio = swap_cache_get_folio(entry, vma, vmf->address); 3854 if (folio) 3855 page = folio_file_page(folio, swp_offset(entry)); 3856 swapcache = folio; 3857 3858 if (!folio) { 3859 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) && 3860 __swap_count(entry) == 1) { 3861 /* skip swapcache */ 3862 folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, 3863 vma, vmf->address, false); 3864 page = &folio->page; 3865 if (folio) { 3866 __folio_set_locked(folio); 3867 __folio_set_swapbacked(folio); 3868 3869 if (mem_cgroup_swapin_charge_folio(folio, 3870 vma->vm_mm, GFP_KERNEL, 3871 entry)) { 3872 ret = VM_FAULT_OOM; 3873 goto out_page; 3874 } 3875 mem_cgroup_swapin_uncharge_swap(entry); 3876 3877 shadow = get_shadow_from_swap_cache(entry); 3878 if (shadow) 3879 workingset_refault(folio, shadow); 3880 3881 folio_add_lru(folio); 3882 3883 /* To provide entry to swap_readpage() */ 3884 folio->swap = entry; 3885 swap_readpage(page, true, NULL); 3886 folio->private = NULL; 3887 } 3888 } else { 3889 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, 3890 vmf); 3891 if (page) 3892 folio = page_folio(page); 3893 swapcache = folio; 3894 } 3895 3896 if (!folio) { 3897 /* 3898 * Back out if somebody else faulted in this pte 3899 * while we released the pte lock. 3900 */ 3901 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 3902 vmf->address, &vmf->ptl); 3903 if (likely(vmf->pte && 3904 pte_same(ptep_get(vmf->pte), vmf->orig_pte))) 3905 ret = VM_FAULT_OOM; 3906 goto unlock; 3907 } 3908 3909 /* Had to read the page from swap area: Major fault */ 3910 ret = VM_FAULT_MAJOR; 3911 count_vm_event(PGMAJFAULT); 3912 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT); 3913 } else if (PageHWPoison(page)) { 3914 /* 3915 * hwpoisoned dirty swapcache pages are kept for killing 3916 * owner processes (which may be unknown at hwpoison time) 3917 */ 3918 ret = VM_FAULT_HWPOISON; 3919 goto out_release; 3920 } 3921 3922 ret |= folio_lock_or_retry(folio, vmf); 3923 if (ret & VM_FAULT_RETRY) 3924 goto out_release; 3925 3926 if (swapcache) { 3927 /* 3928 * Make sure folio_free_swap() or swapoff did not release the 3929 * swapcache from under us. The page pin, and pte_same test 3930 * below, are not enough to exclude that. Even if it is still 3931 * swapcache, we need to check that the page's swap has not 3932 * changed. 3933 */ 3934 if (unlikely(!folio_test_swapcache(folio) || 3935 page_swap_entry(page).val != entry.val)) 3936 goto out_page; 3937 3938 /* 3939 * KSM sometimes has to copy on read faults, for example, if 3940 * page->index of !PageKSM() pages would be nonlinear inside the 3941 * anon VMA -- PageKSM() is lost on actual swapout. 3942 */ 3943 page = ksm_might_need_to_copy(page, vma, vmf->address); 3944 if (unlikely(!page)) { 3945 ret = VM_FAULT_OOM; 3946 goto out_page; 3947 } else if (unlikely(PTR_ERR(page) == -EHWPOISON)) { 3948 ret = VM_FAULT_HWPOISON; 3949 goto out_page; 3950 } 3951 folio = page_folio(page); 3952 3953 /* 3954 * If we want to map a page that's in the swapcache writable, we 3955 * have to detect via the refcount if we're really the exclusive 3956 * owner. Try removing the extra reference from the local LRU 3957 * caches if required. 3958 */ 3959 if ((vmf->flags & FAULT_FLAG_WRITE) && folio == swapcache && 3960 !folio_test_ksm(folio) && !folio_test_lru(folio)) 3961 lru_add_drain(); 3962 } 3963 3964 folio_throttle_swaprate(folio, GFP_KERNEL); 3965 3966 /* 3967 * Back out if somebody else already faulted in this pte. 3968 */ 3969 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 3970 &vmf->ptl); 3971 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) 3972 goto out_nomap; 3973 3974 if (unlikely(!folio_test_uptodate(folio))) { 3975 ret = VM_FAULT_SIGBUS; 3976 goto out_nomap; 3977 } 3978 3979 /* 3980 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte 3981 * must never point at an anonymous page in the swapcache that is 3982 * PG_anon_exclusive. Sanity check that this holds and especially, that 3983 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity 3984 * check after taking the PT lock and making sure that nobody 3985 * concurrently faulted in this page and set PG_anon_exclusive. 3986 */ 3987 BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio)); 3988 BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page)); 3989 3990 /* 3991 * Check under PT lock (to protect against concurrent fork() sharing 3992 * the swap entry concurrently) for certainly exclusive pages. 3993 */ 3994 if (!folio_test_ksm(folio)) { 3995 exclusive = pte_swp_exclusive(vmf->orig_pte); 3996 if (folio != swapcache) { 3997 /* 3998 * We have a fresh page that is not exposed to the 3999 * swapcache -> certainly exclusive. 4000 */ 4001 exclusive = true; 4002 } else if (exclusive && folio_test_writeback(folio) && 4003 data_race(si->flags & SWP_STABLE_WRITES)) { 4004 /* 4005 * This is tricky: not all swap backends support 4006 * concurrent page modifications while under writeback. 4007 * 4008 * So if we stumble over such a page in the swapcache 4009 * we must not set the page exclusive, otherwise we can 4010 * map it writable without further checks and modify it 4011 * while still under writeback. 4012 * 4013 * For these problematic swap backends, simply drop the 4014 * exclusive marker: this is perfectly fine as we start 4015 * writeback only if we fully unmapped the page and 4016 * there are no unexpected references on the page after 4017 * unmapping succeeded. After fully unmapped, no 4018 * further GUP references (FOLL_GET and FOLL_PIN) can 4019 * appear, so dropping the exclusive marker and mapping 4020 * it only R/O is fine. 4021 */ 4022 exclusive = false; 4023 } 4024 } 4025 4026 /* 4027 * Some architectures may have to restore extra metadata to the page 4028 * when reading from swap. This metadata may be indexed by swap entry 4029 * so this must be called before swap_free(). 4030 */ 4031 arch_swap_restore(entry, folio); 4032 4033 /* 4034 * Remove the swap entry and conditionally try to free up the swapcache. 4035 * We're already holding a reference on the page but haven't mapped it 4036 * yet. 4037 */ 4038 swap_free(entry); 4039 if (should_try_to_free_swap(folio, vma, vmf->flags)) 4040 folio_free_swap(folio); 4041 4042 inc_mm_counter(vma->vm_mm, MM_ANONPAGES); 4043 dec_mm_counter(vma->vm_mm, MM_SWAPENTS); 4044 pte = mk_pte(page, vma->vm_page_prot); 4045 4046 /* 4047 * Same logic as in do_wp_page(); however, optimize for pages that are 4048 * certainly not shared either because we just allocated them without 4049 * exposing them to the swapcache or because the swap entry indicates 4050 * exclusivity. 4051 */ 4052 if (!folio_test_ksm(folio) && 4053 (exclusive || folio_ref_count(folio) == 1)) { 4054 if (vmf->flags & FAULT_FLAG_WRITE) { 4055 pte = maybe_mkwrite(pte_mkdirty(pte), vma); 4056 vmf->flags &= ~FAULT_FLAG_WRITE; 4057 } 4058 rmap_flags |= RMAP_EXCLUSIVE; 4059 } 4060 flush_icache_page(vma, page); 4061 if (pte_swp_soft_dirty(vmf->orig_pte)) 4062 pte = pte_mksoft_dirty(pte); 4063 if (pte_swp_uffd_wp(vmf->orig_pte)) 4064 pte = pte_mkuffd_wp(pte); 4065 vmf->orig_pte = pte; 4066 4067 /* ksm created a completely new copy */ 4068 if (unlikely(folio != swapcache && swapcache)) { 4069 page_add_new_anon_rmap(page, vma, vmf->address); 4070 folio_add_lru_vma(folio, vma); 4071 } else { 4072 page_add_anon_rmap(page, vma, vmf->address, rmap_flags); 4073 } 4074 4075 VM_BUG_ON(!folio_test_anon(folio) || 4076 (pte_write(pte) && !PageAnonExclusive(page))); 4077 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte); 4078 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte); 4079 4080 folio_unlock(folio); 4081 if (folio != swapcache && swapcache) { 4082 /* 4083 * Hold the lock to avoid the swap entry to be reused 4084 * until we take the PT lock for the pte_same() check 4085 * (to avoid false positives from pte_same). For 4086 * further safety release the lock after the swap_free 4087 * so that the swap count won't change under a 4088 * parallel locked swapcache. 4089 */ 4090 folio_unlock(swapcache); 4091 folio_put(swapcache); 4092 } 4093 4094 if (vmf->flags & FAULT_FLAG_WRITE) { 4095 ret |= do_wp_page(vmf); 4096 if (ret & VM_FAULT_ERROR) 4097 ret &= VM_FAULT_ERROR; 4098 goto out; 4099 } 4100 4101 /* No need to invalidate - it was non-present before */ 4102 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 4103 unlock: 4104 if (vmf->pte) 4105 pte_unmap_unlock(vmf->pte, vmf->ptl); 4106 out: 4107 if (si) 4108 put_swap_device(si); 4109 return ret; 4110 out_nomap: 4111 if (vmf->pte) 4112 pte_unmap_unlock(vmf->pte, vmf->ptl); 4113 out_page: 4114 folio_unlock(folio); 4115 out_release: 4116 folio_put(folio); 4117 if (folio != swapcache && swapcache) { 4118 folio_unlock(swapcache); 4119 folio_put(swapcache); 4120 } 4121 if (si) 4122 put_swap_device(si); 4123 return ret; 4124 } 4125 4126 /* 4127 * We enter with non-exclusive mmap_lock (to exclude vma changes, 4128 * but allow concurrent faults), and pte mapped but not yet locked. 4129 * We return with mmap_lock still held, but pte unmapped and unlocked. 4130 */ 4131 static vm_fault_t do_anonymous_page(struct vm_fault *vmf) 4132 { 4133 bool uffd_wp = vmf_orig_pte_uffd_wp(vmf); 4134 struct vm_area_struct *vma = vmf->vma; 4135 struct folio *folio; 4136 vm_fault_t ret = 0; 4137 pte_t entry; 4138 4139 /* File mapping without ->vm_ops ? */ 4140 if (vma->vm_flags & VM_SHARED) 4141 return VM_FAULT_SIGBUS; 4142 4143 /* 4144 * Use pte_alloc() instead of pte_alloc_map(), so that OOM can 4145 * be distinguished from a transient failure of pte_offset_map(). 4146 */ 4147 if (pte_alloc(vma->vm_mm, vmf->pmd)) 4148 return VM_FAULT_OOM; 4149 4150 /* Use the zero-page for reads */ 4151 if (!(vmf->flags & FAULT_FLAG_WRITE) && 4152 !mm_forbids_zeropage(vma->vm_mm)) { 4153 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address), 4154 vma->vm_page_prot)); 4155 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4156 vmf->address, &vmf->ptl); 4157 if (!vmf->pte) 4158 goto unlock; 4159 if (vmf_pte_changed(vmf)) { 4160 update_mmu_tlb(vma, vmf->address, vmf->pte); 4161 goto unlock; 4162 } 4163 ret = check_stable_address_space(vma->vm_mm); 4164 if (ret) 4165 goto unlock; 4166 /* Deliver the page fault to userland, check inside PT lock */ 4167 if (userfaultfd_missing(vma)) { 4168 pte_unmap_unlock(vmf->pte, vmf->ptl); 4169 return handle_userfault(vmf, VM_UFFD_MISSING); 4170 } 4171 goto setpte; 4172 } 4173 4174 /* Allocate our own private page. */ 4175 if (unlikely(anon_vma_prepare(vma))) 4176 goto oom; 4177 folio = vma_alloc_zeroed_movable_folio(vma, vmf->address); 4178 if (!folio) 4179 goto oom; 4180 4181 if (mem_cgroup_charge(folio, vma->vm_mm, GFP_KERNEL)) 4182 goto oom_free_page; 4183 folio_throttle_swaprate(folio, GFP_KERNEL); 4184 4185 /* 4186 * The memory barrier inside __folio_mark_uptodate makes sure that 4187 * preceding stores to the page contents become visible before 4188 * the set_pte_at() write. 4189 */ 4190 __folio_mark_uptodate(folio); 4191 4192 entry = mk_pte(&folio->page, vma->vm_page_prot); 4193 entry = pte_sw_mkyoung(entry); 4194 if (vma->vm_flags & VM_WRITE) 4195 entry = pte_mkwrite(pte_mkdirty(entry), vma); 4196 4197 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 4198 &vmf->ptl); 4199 if (!vmf->pte) 4200 goto release; 4201 if (vmf_pte_changed(vmf)) { 4202 update_mmu_tlb(vma, vmf->address, vmf->pte); 4203 goto release; 4204 } 4205 4206 ret = check_stable_address_space(vma->vm_mm); 4207 if (ret) 4208 goto release; 4209 4210 /* Deliver the page fault to userland, check inside PT lock */ 4211 if (userfaultfd_missing(vma)) { 4212 pte_unmap_unlock(vmf->pte, vmf->ptl); 4213 folio_put(folio); 4214 return handle_userfault(vmf, VM_UFFD_MISSING); 4215 } 4216 4217 inc_mm_counter(vma->vm_mm, MM_ANONPAGES); 4218 folio_add_new_anon_rmap(folio, vma, vmf->address); 4219 folio_add_lru_vma(folio, vma); 4220 setpte: 4221 if (uffd_wp) 4222 entry = pte_mkuffd_wp(entry); 4223 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry); 4224 4225 /* No need to invalidate - it was non-present before */ 4226 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 4227 unlock: 4228 if (vmf->pte) 4229 pte_unmap_unlock(vmf->pte, vmf->ptl); 4230 return ret; 4231 release: 4232 folio_put(folio); 4233 goto unlock; 4234 oom_free_page: 4235 folio_put(folio); 4236 oom: 4237 return VM_FAULT_OOM; 4238 } 4239 4240 /* 4241 * The mmap_lock must have been held on entry, and may have been 4242 * released depending on flags and vma->vm_ops->fault() return value. 4243 * See filemap_fault() and __lock_page_retry(). 4244 */ 4245 static vm_fault_t __do_fault(struct vm_fault *vmf) 4246 { 4247 struct vm_area_struct *vma = vmf->vma; 4248 struct folio *folio; 4249 vm_fault_t ret; 4250 4251 /* 4252 * Preallocate pte before we take page_lock because this might lead to 4253 * deadlocks for memcg reclaim which waits for pages under writeback: 4254 * lock_page(A) 4255 * SetPageWriteback(A) 4256 * unlock_page(A) 4257 * lock_page(B) 4258 * lock_page(B) 4259 * pte_alloc_one 4260 * shrink_page_list 4261 * wait_on_page_writeback(A) 4262 * SetPageWriteback(B) 4263 * unlock_page(B) 4264 * # flush A, B to clear the writeback 4265 */ 4266 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) { 4267 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm); 4268 if (!vmf->prealloc_pte) 4269 return VM_FAULT_OOM; 4270 } 4271 4272 ret = vma->vm_ops->fault(vmf); 4273 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY | 4274 VM_FAULT_DONE_COW))) 4275 return ret; 4276 4277 folio = page_folio(vmf->page); 4278 if (unlikely(PageHWPoison(vmf->page))) { 4279 vm_fault_t poisonret = VM_FAULT_HWPOISON; 4280 if (ret & VM_FAULT_LOCKED) { 4281 if (page_mapped(vmf->page)) 4282 unmap_mapping_folio(folio); 4283 /* Retry if a clean folio was removed from the cache. */ 4284 if (mapping_evict_folio(folio->mapping, folio)) 4285 poisonret = VM_FAULT_NOPAGE; 4286 folio_unlock(folio); 4287 } 4288 folio_put(folio); 4289 vmf->page = NULL; 4290 return poisonret; 4291 } 4292 4293 if (unlikely(!(ret & VM_FAULT_LOCKED))) 4294 folio_lock(folio); 4295 else 4296 VM_BUG_ON_PAGE(!folio_test_locked(folio), vmf->page); 4297 4298 return ret; 4299 } 4300 4301 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4302 static void deposit_prealloc_pte(struct vm_fault *vmf) 4303 { 4304 struct vm_area_struct *vma = vmf->vma; 4305 4306 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte); 4307 /* 4308 * We are going to consume the prealloc table, 4309 * count that as nr_ptes. 4310 */ 4311 mm_inc_nr_ptes(vma->vm_mm); 4312 vmf->prealloc_pte = NULL; 4313 } 4314 4315 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page) 4316 { 4317 struct vm_area_struct *vma = vmf->vma; 4318 bool write = vmf->flags & FAULT_FLAG_WRITE; 4319 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 4320 pmd_t entry; 4321 vm_fault_t ret = VM_FAULT_FALLBACK; 4322 4323 if (!transhuge_vma_suitable(vma, haddr)) 4324 return ret; 4325 4326 page = compound_head(page); 4327 if (compound_order(page) != HPAGE_PMD_ORDER) 4328 return ret; 4329 4330 /* 4331 * Just backoff if any subpage of a THP is corrupted otherwise 4332 * the corrupted page may mapped by PMD silently to escape the 4333 * check. This kind of THP just can be PTE mapped. Access to 4334 * the corrupted subpage should trigger SIGBUS as expected. 4335 */ 4336 if (unlikely(PageHasHWPoisoned(page))) 4337 return ret; 4338 4339 /* 4340 * Archs like ppc64 need additional space to store information 4341 * related to pte entry. Use the preallocated table for that. 4342 */ 4343 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) { 4344 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm); 4345 if (!vmf->prealloc_pte) 4346 return VM_FAULT_OOM; 4347 } 4348 4349 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 4350 if (unlikely(!pmd_none(*vmf->pmd))) 4351 goto out; 4352 4353 flush_icache_pages(vma, page, HPAGE_PMD_NR); 4354 4355 entry = mk_huge_pmd(page, vma->vm_page_prot); 4356 if (write) 4357 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 4358 4359 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR); 4360 page_add_file_rmap(page, vma, true); 4361 4362 /* 4363 * deposit and withdraw with pmd lock held 4364 */ 4365 if (arch_needs_pgtable_deposit()) 4366 deposit_prealloc_pte(vmf); 4367 4368 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry); 4369 4370 update_mmu_cache_pmd(vma, haddr, vmf->pmd); 4371 4372 /* fault is handled */ 4373 ret = 0; 4374 count_vm_event(THP_FILE_MAPPED); 4375 out: 4376 spin_unlock(vmf->ptl); 4377 return ret; 4378 } 4379 #else 4380 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page) 4381 { 4382 return VM_FAULT_FALLBACK; 4383 } 4384 #endif 4385 4386 /** 4387 * set_pte_range - Set a range of PTEs to point to pages in a folio. 4388 * @vmf: Fault decription. 4389 * @folio: The folio that contains @page. 4390 * @page: The first page to create a PTE for. 4391 * @nr: The number of PTEs to create. 4392 * @addr: The first address to create a PTE for. 4393 */ 4394 void set_pte_range(struct vm_fault *vmf, struct folio *folio, 4395 struct page *page, unsigned int nr, unsigned long addr) 4396 { 4397 struct vm_area_struct *vma = vmf->vma; 4398 bool uffd_wp = vmf_orig_pte_uffd_wp(vmf); 4399 bool write = vmf->flags & FAULT_FLAG_WRITE; 4400 bool prefault = in_range(vmf->address, addr, nr * PAGE_SIZE); 4401 pte_t entry; 4402 4403 flush_icache_pages(vma, page, nr); 4404 entry = mk_pte(page, vma->vm_page_prot); 4405 4406 if (prefault && arch_wants_old_prefaulted_pte()) 4407 entry = pte_mkold(entry); 4408 else 4409 entry = pte_sw_mkyoung(entry); 4410 4411 if (write) 4412 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 4413 if (unlikely(uffd_wp)) 4414 entry = pte_mkuffd_wp(entry); 4415 /* copy-on-write page */ 4416 if (write && !(vma->vm_flags & VM_SHARED)) { 4417 add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr); 4418 VM_BUG_ON_FOLIO(nr != 1, folio); 4419 folio_add_new_anon_rmap(folio, vma, addr); 4420 folio_add_lru_vma(folio, vma); 4421 } else { 4422 add_mm_counter(vma->vm_mm, mm_counter_file(page), nr); 4423 folio_add_file_rmap_range(folio, page, nr, vma, false); 4424 } 4425 set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr); 4426 4427 /* no need to invalidate: a not-present page won't be cached */ 4428 update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr); 4429 } 4430 4431 static bool vmf_pte_changed(struct vm_fault *vmf) 4432 { 4433 if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID) 4434 return !pte_same(ptep_get(vmf->pte), vmf->orig_pte); 4435 4436 return !pte_none(ptep_get(vmf->pte)); 4437 } 4438 4439 /** 4440 * finish_fault - finish page fault once we have prepared the page to fault 4441 * 4442 * @vmf: structure describing the fault 4443 * 4444 * This function handles all that is needed to finish a page fault once the 4445 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for 4446 * given page, adds reverse page mapping, handles memcg charges and LRU 4447 * addition. 4448 * 4449 * The function expects the page to be locked and on success it consumes a 4450 * reference of a page being mapped (for the PTE which maps it). 4451 * 4452 * Return: %0 on success, %VM_FAULT_ code in case of error. 4453 */ 4454 vm_fault_t finish_fault(struct vm_fault *vmf) 4455 { 4456 struct vm_area_struct *vma = vmf->vma; 4457 struct page *page; 4458 vm_fault_t ret; 4459 4460 /* Did we COW the page? */ 4461 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) 4462 page = vmf->cow_page; 4463 else 4464 page = vmf->page; 4465 4466 /* 4467 * check even for read faults because we might have lost our CoWed 4468 * page 4469 */ 4470 if (!(vma->vm_flags & VM_SHARED)) { 4471 ret = check_stable_address_space(vma->vm_mm); 4472 if (ret) 4473 return ret; 4474 } 4475 4476 if (pmd_none(*vmf->pmd)) { 4477 if (PageTransCompound(page)) { 4478 ret = do_set_pmd(vmf, page); 4479 if (ret != VM_FAULT_FALLBACK) 4480 return ret; 4481 } 4482 4483 if (vmf->prealloc_pte) 4484 pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte); 4485 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) 4486 return VM_FAULT_OOM; 4487 } 4488 4489 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4490 vmf->address, &vmf->ptl); 4491 if (!vmf->pte) 4492 return VM_FAULT_NOPAGE; 4493 4494 /* Re-check under ptl */ 4495 if (likely(!vmf_pte_changed(vmf))) { 4496 struct folio *folio = page_folio(page); 4497 4498 set_pte_range(vmf, folio, page, 1, vmf->address); 4499 ret = 0; 4500 } else { 4501 update_mmu_tlb(vma, vmf->address, vmf->pte); 4502 ret = VM_FAULT_NOPAGE; 4503 } 4504 4505 pte_unmap_unlock(vmf->pte, vmf->ptl); 4506 return ret; 4507 } 4508 4509 static unsigned long fault_around_pages __read_mostly = 4510 65536 >> PAGE_SHIFT; 4511 4512 #ifdef CONFIG_DEBUG_FS 4513 static int fault_around_bytes_get(void *data, u64 *val) 4514 { 4515 *val = fault_around_pages << PAGE_SHIFT; 4516 return 0; 4517 } 4518 4519 /* 4520 * fault_around_bytes must be rounded down to the nearest page order as it's 4521 * what do_fault_around() expects to see. 4522 */ 4523 static int fault_around_bytes_set(void *data, u64 val) 4524 { 4525 if (val / PAGE_SIZE > PTRS_PER_PTE) 4526 return -EINVAL; 4527 4528 /* 4529 * The minimum value is 1 page, however this results in no fault-around 4530 * at all. See should_fault_around(). 4531 */ 4532 fault_around_pages = max(rounddown_pow_of_two(val) >> PAGE_SHIFT, 1UL); 4533 4534 return 0; 4535 } 4536 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops, 4537 fault_around_bytes_get, fault_around_bytes_set, "%llu\n"); 4538 4539 static int __init fault_around_debugfs(void) 4540 { 4541 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL, 4542 &fault_around_bytes_fops); 4543 return 0; 4544 } 4545 late_initcall(fault_around_debugfs); 4546 #endif 4547 4548 /* 4549 * do_fault_around() tries to map few pages around the fault address. The hope 4550 * is that the pages will be needed soon and this will lower the number of 4551 * faults to handle. 4552 * 4553 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's 4554 * not ready to be mapped: not up-to-date, locked, etc. 4555 * 4556 * This function doesn't cross VMA or page table boundaries, in order to call 4557 * map_pages() and acquire a PTE lock only once. 4558 * 4559 * fault_around_pages defines how many pages we'll try to map. 4560 * do_fault_around() expects it to be set to a power of two less than or equal 4561 * to PTRS_PER_PTE. 4562 * 4563 * The virtual address of the area that we map is naturally aligned to 4564 * fault_around_pages * PAGE_SIZE rounded down to the machine page size 4565 * (and therefore to page order). This way it's easier to guarantee 4566 * that we don't cross page table boundaries. 4567 */ 4568 static vm_fault_t do_fault_around(struct vm_fault *vmf) 4569 { 4570 pgoff_t nr_pages = READ_ONCE(fault_around_pages); 4571 pgoff_t pte_off = pte_index(vmf->address); 4572 /* The page offset of vmf->address within the VMA. */ 4573 pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff; 4574 pgoff_t from_pte, to_pte; 4575 vm_fault_t ret; 4576 4577 /* The PTE offset of the start address, clamped to the VMA. */ 4578 from_pte = max(ALIGN_DOWN(pte_off, nr_pages), 4579 pte_off - min(pte_off, vma_off)); 4580 4581 /* The PTE offset of the end address, clamped to the VMA and PTE. */ 4582 to_pte = min3(from_pte + nr_pages, (pgoff_t)PTRS_PER_PTE, 4583 pte_off + vma_pages(vmf->vma) - vma_off) - 1; 4584 4585 if (pmd_none(*vmf->pmd)) { 4586 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm); 4587 if (!vmf->prealloc_pte) 4588 return VM_FAULT_OOM; 4589 } 4590 4591 rcu_read_lock(); 4592 ret = vmf->vma->vm_ops->map_pages(vmf, 4593 vmf->pgoff + from_pte - pte_off, 4594 vmf->pgoff + to_pte - pte_off); 4595 rcu_read_unlock(); 4596 4597 return ret; 4598 } 4599 4600 /* Return true if we should do read fault-around, false otherwise */ 4601 static inline bool should_fault_around(struct vm_fault *vmf) 4602 { 4603 /* No ->map_pages? No way to fault around... */ 4604 if (!vmf->vma->vm_ops->map_pages) 4605 return false; 4606 4607 if (uffd_disable_fault_around(vmf->vma)) 4608 return false; 4609 4610 /* A single page implies no faulting 'around' at all. */ 4611 return fault_around_pages > 1; 4612 } 4613 4614 static vm_fault_t do_read_fault(struct vm_fault *vmf) 4615 { 4616 vm_fault_t ret = 0; 4617 struct folio *folio; 4618 4619 /* 4620 * Let's call ->map_pages() first and use ->fault() as fallback 4621 * if page by the offset is not ready to be mapped (cold cache or 4622 * something). 4623 */ 4624 if (should_fault_around(vmf)) { 4625 ret = do_fault_around(vmf); 4626 if (ret) 4627 return ret; 4628 } 4629 4630 ret = vmf_can_call_fault(vmf); 4631 if (ret) 4632 return ret; 4633 4634 ret = __do_fault(vmf); 4635 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4636 return ret; 4637 4638 ret |= finish_fault(vmf); 4639 folio = page_folio(vmf->page); 4640 folio_unlock(folio); 4641 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4642 folio_put(folio); 4643 return ret; 4644 } 4645 4646 static vm_fault_t do_cow_fault(struct vm_fault *vmf) 4647 { 4648 struct vm_area_struct *vma = vmf->vma; 4649 vm_fault_t ret; 4650 4651 ret = vmf_can_call_fault(vmf); 4652 if (!ret) 4653 ret = vmf_anon_prepare(vmf); 4654 if (ret) 4655 return ret; 4656 4657 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address); 4658 if (!vmf->cow_page) 4659 return VM_FAULT_OOM; 4660 4661 if (mem_cgroup_charge(page_folio(vmf->cow_page), vma->vm_mm, 4662 GFP_KERNEL)) { 4663 put_page(vmf->cow_page); 4664 return VM_FAULT_OOM; 4665 } 4666 folio_throttle_swaprate(page_folio(vmf->cow_page), GFP_KERNEL); 4667 4668 ret = __do_fault(vmf); 4669 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4670 goto uncharge_out; 4671 if (ret & VM_FAULT_DONE_COW) 4672 return ret; 4673 4674 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma); 4675 __SetPageUptodate(vmf->cow_page); 4676 4677 ret |= finish_fault(vmf); 4678 unlock_page(vmf->page); 4679 put_page(vmf->page); 4680 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4681 goto uncharge_out; 4682 return ret; 4683 uncharge_out: 4684 put_page(vmf->cow_page); 4685 return ret; 4686 } 4687 4688 static vm_fault_t do_shared_fault(struct vm_fault *vmf) 4689 { 4690 struct vm_area_struct *vma = vmf->vma; 4691 vm_fault_t ret, tmp; 4692 struct folio *folio; 4693 4694 ret = vmf_can_call_fault(vmf); 4695 if (ret) 4696 return ret; 4697 4698 ret = __do_fault(vmf); 4699 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4700 return ret; 4701 4702 folio = page_folio(vmf->page); 4703 4704 /* 4705 * Check if the backing address space wants to know that the page is 4706 * about to become writable 4707 */ 4708 if (vma->vm_ops->page_mkwrite) { 4709 folio_unlock(folio); 4710 tmp = do_page_mkwrite(vmf, folio); 4711 if (unlikely(!tmp || 4712 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { 4713 folio_put(folio); 4714 return tmp; 4715 } 4716 } 4717 4718 ret |= finish_fault(vmf); 4719 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | 4720 VM_FAULT_RETRY))) { 4721 folio_unlock(folio); 4722 folio_put(folio); 4723 return ret; 4724 } 4725 4726 ret |= fault_dirty_shared_page(vmf); 4727 return ret; 4728 } 4729 4730 /* 4731 * We enter with non-exclusive mmap_lock (to exclude vma changes, 4732 * but allow concurrent faults). 4733 * The mmap_lock may have been released depending on flags and our 4734 * return value. See filemap_fault() and __folio_lock_or_retry(). 4735 * If mmap_lock is released, vma may become invalid (for example 4736 * by other thread calling munmap()). 4737 */ 4738 static vm_fault_t do_fault(struct vm_fault *vmf) 4739 { 4740 struct vm_area_struct *vma = vmf->vma; 4741 struct mm_struct *vm_mm = vma->vm_mm; 4742 vm_fault_t ret; 4743 4744 /* 4745 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND 4746 */ 4747 if (!vma->vm_ops->fault) { 4748 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, 4749 vmf->address, &vmf->ptl); 4750 if (unlikely(!vmf->pte)) 4751 ret = VM_FAULT_SIGBUS; 4752 else { 4753 /* 4754 * Make sure this is not a temporary clearing of pte 4755 * by holding ptl and checking again. A R/M/W update 4756 * of pte involves: take ptl, clearing the pte so that 4757 * we don't have concurrent modification by hardware 4758 * followed by an update. 4759 */ 4760 if (unlikely(pte_none(ptep_get(vmf->pte)))) 4761 ret = VM_FAULT_SIGBUS; 4762 else 4763 ret = VM_FAULT_NOPAGE; 4764 4765 pte_unmap_unlock(vmf->pte, vmf->ptl); 4766 } 4767 } else if (!(vmf->flags & FAULT_FLAG_WRITE)) 4768 ret = do_read_fault(vmf); 4769 else if (!(vma->vm_flags & VM_SHARED)) 4770 ret = do_cow_fault(vmf); 4771 else 4772 ret = do_shared_fault(vmf); 4773 4774 /* preallocated pagetable is unused: free it */ 4775 if (vmf->prealloc_pte) { 4776 pte_free(vm_mm, vmf->prealloc_pte); 4777 vmf->prealloc_pte = NULL; 4778 } 4779 return ret; 4780 } 4781 4782 int numa_migrate_prep(struct folio *folio, struct vm_area_struct *vma, 4783 unsigned long addr, int page_nid, int *flags) 4784 { 4785 folio_get(folio); 4786 4787 /* Record the current PID acceesing VMA */ 4788 vma_set_access_pid_bit(vma); 4789 4790 count_vm_numa_event(NUMA_HINT_FAULTS); 4791 if (page_nid == numa_node_id()) { 4792 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL); 4793 *flags |= TNF_FAULT_LOCAL; 4794 } 4795 4796 return mpol_misplaced(folio, vma, addr); 4797 } 4798 4799 static vm_fault_t do_numa_page(struct vm_fault *vmf) 4800 { 4801 struct vm_area_struct *vma = vmf->vma; 4802 struct folio *folio = NULL; 4803 int nid = NUMA_NO_NODE; 4804 bool writable = false; 4805 int last_cpupid; 4806 int target_nid; 4807 pte_t pte, old_pte; 4808 int flags = 0; 4809 4810 /* 4811 * The "pte" at this point cannot be used safely without 4812 * validation through pte_unmap_same(). It's of NUMA type but 4813 * the pfn may be screwed if the read is non atomic. 4814 */ 4815 spin_lock(vmf->ptl); 4816 if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 4817 pte_unmap_unlock(vmf->pte, vmf->ptl); 4818 goto out; 4819 } 4820 4821 /* Get the normal PTE */ 4822 old_pte = ptep_get(vmf->pte); 4823 pte = pte_modify(old_pte, vma->vm_page_prot); 4824 4825 /* 4826 * Detect now whether the PTE could be writable; this information 4827 * is only valid while holding the PT lock. 4828 */ 4829 writable = pte_write(pte); 4830 if (!writable && vma_wants_manual_pte_write_upgrade(vma) && 4831 can_change_pte_writable(vma, vmf->address, pte)) 4832 writable = true; 4833 4834 folio = vm_normal_folio(vma, vmf->address, pte); 4835 if (!folio || folio_is_zone_device(folio)) 4836 goto out_map; 4837 4838 /* TODO: handle PTE-mapped THP */ 4839 if (folio_test_large(folio)) 4840 goto out_map; 4841 4842 /* 4843 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as 4844 * much anyway since they can be in shared cache state. This misses 4845 * the case where a mapping is writable but the process never writes 4846 * to it but pte_write gets cleared during protection updates and 4847 * pte_dirty has unpredictable behaviour between PTE scan updates, 4848 * background writeback, dirty balancing and application behaviour. 4849 */ 4850 if (!writable) 4851 flags |= TNF_NO_GROUP; 4852 4853 /* 4854 * Flag if the folio is shared between multiple address spaces. This 4855 * is later used when determining whether to group tasks together 4856 */ 4857 if (folio_estimated_sharers(folio) > 1 && (vma->vm_flags & VM_SHARED)) 4858 flags |= TNF_SHARED; 4859 4860 nid = folio_nid(folio); 4861 /* 4862 * For memory tiering mode, cpupid of slow memory page is used 4863 * to record page access time. So use default value. 4864 */ 4865 if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 4866 !node_is_toptier(nid)) 4867 last_cpupid = (-1 & LAST_CPUPID_MASK); 4868 else 4869 last_cpupid = folio_last_cpupid(folio); 4870 target_nid = numa_migrate_prep(folio, vma, vmf->address, nid, &flags); 4871 if (target_nid == NUMA_NO_NODE) { 4872 folio_put(folio); 4873 goto out_map; 4874 } 4875 pte_unmap_unlock(vmf->pte, vmf->ptl); 4876 writable = false; 4877 4878 /* Migrate to the requested node */ 4879 if (migrate_misplaced_folio(folio, vma, target_nid)) { 4880 nid = target_nid; 4881 flags |= TNF_MIGRATED; 4882 } else { 4883 flags |= TNF_MIGRATE_FAIL; 4884 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4885 vmf->address, &vmf->ptl); 4886 if (unlikely(!vmf->pte)) 4887 goto out; 4888 if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 4889 pte_unmap_unlock(vmf->pte, vmf->ptl); 4890 goto out; 4891 } 4892 goto out_map; 4893 } 4894 4895 out: 4896 if (nid != NUMA_NO_NODE) 4897 task_numa_fault(last_cpupid, nid, 1, flags); 4898 return 0; 4899 out_map: 4900 /* 4901 * Make it present again, depending on how arch implements 4902 * non-accessible ptes, some can allow access by kernel mode. 4903 */ 4904 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte); 4905 pte = pte_modify(old_pte, vma->vm_page_prot); 4906 pte = pte_mkyoung(pte); 4907 if (writable) 4908 pte = pte_mkwrite(pte, vma); 4909 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte); 4910 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 4911 pte_unmap_unlock(vmf->pte, vmf->ptl); 4912 goto out; 4913 } 4914 4915 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf) 4916 { 4917 struct vm_area_struct *vma = vmf->vma; 4918 if (vma_is_anonymous(vma)) 4919 return do_huge_pmd_anonymous_page(vmf); 4920 if (vma->vm_ops->huge_fault) 4921 return vma->vm_ops->huge_fault(vmf, PMD_ORDER); 4922 return VM_FAULT_FALLBACK; 4923 } 4924 4925 /* `inline' is required to avoid gcc 4.1.2 build error */ 4926 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf) 4927 { 4928 struct vm_area_struct *vma = vmf->vma; 4929 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 4930 vm_fault_t ret; 4931 4932 if (vma_is_anonymous(vma)) { 4933 if (likely(!unshare) && 4934 userfaultfd_huge_pmd_wp(vma, vmf->orig_pmd)) { 4935 if (userfaultfd_wp_async(vmf->vma)) 4936 goto split; 4937 return handle_userfault(vmf, VM_UFFD_WP); 4938 } 4939 return do_huge_pmd_wp_page(vmf); 4940 } 4941 4942 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) { 4943 if (vma->vm_ops->huge_fault) { 4944 ret = vma->vm_ops->huge_fault(vmf, PMD_ORDER); 4945 if (!(ret & VM_FAULT_FALLBACK)) 4946 return ret; 4947 } 4948 } 4949 4950 split: 4951 /* COW or write-notify handled on pte level: split pmd. */ 4952 __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL); 4953 4954 return VM_FAULT_FALLBACK; 4955 } 4956 4957 static vm_fault_t create_huge_pud(struct vm_fault *vmf) 4958 { 4959 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \ 4960 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) 4961 struct vm_area_struct *vma = vmf->vma; 4962 /* No support for anonymous transparent PUD pages yet */ 4963 if (vma_is_anonymous(vma)) 4964 return VM_FAULT_FALLBACK; 4965 if (vma->vm_ops->huge_fault) 4966 return vma->vm_ops->huge_fault(vmf, PUD_ORDER); 4967 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 4968 return VM_FAULT_FALLBACK; 4969 } 4970 4971 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud) 4972 { 4973 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \ 4974 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) 4975 struct vm_area_struct *vma = vmf->vma; 4976 vm_fault_t ret; 4977 4978 /* No support for anonymous transparent PUD pages yet */ 4979 if (vma_is_anonymous(vma)) 4980 goto split; 4981 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) { 4982 if (vma->vm_ops->huge_fault) { 4983 ret = vma->vm_ops->huge_fault(vmf, PUD_ORDER); 4984 if (!(ret & VM_FAULT_FALLBACK)) 4985 return ret; 4986 } 4987 } 4988 split: 4989 /* COW or write-notify not handled on PUD level: split pud.*/ 4990 __split_huge_pud(vma, vmf->pud, vmf->address); 4991 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 4992 return VM_FAULT_FALLBACK; 4993 } 4994 4995 /* 4996 * These routines also need to handle stuff like marking pages dirty 4997 * and/or accessed for architectures that don't do it in hardware (most 4998 * RISC architectures). The early dirtying is also good on the i386. 4999 * 5000 * There is also a hook called "update_mmu_cache()" that architectures 5001 * with external mmu caches can use to update those (ie the Sparc or 5002 * PowerPC hashed page tables that act as extended TLBs). 5003 * 5004 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow 5005 * concurrent faults). 5006 * 5007 * The mmap_lock may have been released depending on flags and our return value. 5008 * See filemap_fault() and __folio_lock_or_retry(). 5009 */ 5010 static vm_fault_t handle_pte_fault(struct vm_fault *vmf) 5011 { 5012 pte_t entry; 5013 5014 if (unlikely(pmd_none(*vmf->pmd))) { 5015 /* 5016 * Leave __pte_alloc() until later: because vm_ops->fault may 5017 * want to allocate huge page, and if we expose page table 5018 * for an instant, it will be difficult to retract from 5019 * concurrent faults and from rmap lookups. 5020 */ 5021 vmf->pte = NULL; 5022 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID; 5023 } else { 5024 /* 5025 * A regular pmd is established and it can't morph into a huge 5026 * pmd by anon khugepaged, since that takes mmap_lock in write 5027 * mode; but shmem or file collapse to THP could still morph 5028 * it into a huge pmd: just retry later if so. 5029 */ 5030 vmf->pte = pte_offset_map_nolock(vmf->vma->vm_mm, vmf->pmd, 5031 vmf->address, &vmf->ptl); 5032 if (unlikely(!vmf->pte)) 5033 return 0; 5034 vmf->orig_pte = ptep_get_lockless(vmf->pte); 5035 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID; 5036 5037 if (pte_none(vmf->orig_pte)) { 5038 pte_unmap(vmf->pte); 5039 vmf->pte = NULL; 5040 } 5041 } 5042 5043 if (!vmf->pte) 5044 return do_pte_missing(vmf); 5045 5046 if (!pte_present(vmf->orig_pte)) 5047 return do_swap_page(vmf); 5048 5049 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma)) 5050 return do_numa_page(vmf); 5051 5052 spin_lock(vmf->ptl); 5053 entry = vmf->orig_pte; 5054 if (unlikely(!pte_same(ptep_get(vmf->pte), entry))) { 5055 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte); 5056 goto unlock; 5057 } 5058 if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) { 5059 if (!pte_write(entry)) 5060 return do_wp_page(vmf); 5061 else if (likely(vmf->flags & FAULT_FLAG_WRITE)) 5062 entry = pte_mkdirty(entry); 5063 } 5064 entry = pte_mkyoung(entry); 5065 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry, 5066 vmf->flags & FAULT_FLAG_WRITE)) { 5067 update_mmu_cache_range(vmf, vmf->vma, vmf->address, 5068 vmf->pte, 1); 5069 } else { 5070 /* Skip spurious TLB flush for retried page fault */ 5071 if (vmf->flags & FAULT_FLAG_TRIED) 5072 goto unlock; 5073 /* 5074 * This is needed only for protection faults but the arch code 5075 * is not yet telling us if this is a protection fault or not. 5076 * This still avoids useless tlb flushes for .text page faults 5077 * with threads. 5078 */ 5079 if (vmf->flags & FAULT_FLAG_WRITE) 5080 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address, 5081 vmf->pte); 5082 } 5083 unlock: 5084 pte_unmap_unlock(vmf->pte, vmf->ptl); 5085 return 0; 5086 } 5087 5088 /* 5089 * On entry, we hold either the VMA lock or the mmap_lock 5090 * (FAULT_FLAG_VMA_LOCK tells you which). If VM_FAULT_RETRY is set in 5091 * the result, the mmap_lock is not held on exit. See filemap_fault() 5092 * and __folio_lock_or_retry(). 5093 */ 5094 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma, 5095 unsigned long address, unsigned int flags) 5096 { 5097 struct vm_fault vmf = { 5098 .vma = vma, 5099 .address = address & PAGE_MASK, 5100 .real_address = address, 5101 .flags = flags, 5102 .pgoff = linear_page_index(vma, address), 5103 .gfp_mask = __get_fault_gfp_mask(vma), 5104 }; 5105 struct mm_struct *mm = vma->vm_mm; 5106 unsigned long vm_flags = vma->vm_flags; 5107 pgd_t *pgd; 5108 p4d_t *p4d; 5109 vm_fault_t ret; 5110 5111 pgd = pgd_offset(mm, address); 5112 p4d = p4d_alloc(mm, pgd, address); 5113 if (!p4d) 5114 return VM_FAULT_OOM; 5115 5116 vmf.pud = pud_alloc(mm, p4d, address); 5117 if (!vmf.pud) 5118 return VM_FAULT_OOM; 5119 retry_pud: 5120 if (pud_none(*vmf.pud) && 5121 hugepage_vma_check(vma, vm_flags, false, true, true)) { 5122 ret = create_huge_pud(&vmf); 5123 if (!(ret & VM_FAULT_FALLBACK)) 5124 return ret; 5125 } else { 5126 pud_t orig_pud = *vmf.pud; 5127 5128 barrier(); 5129 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) { 5130 5131 /* 5132 * TODO once we support anonymous PUDs: NUMA case and 5133 * FAULT_FLAG_UNSHARE handling. 5134 */ 5135 if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) { 5136 ret = wp_huge_pud(&vmf, orig_pud); 5137 if (!(ret & VM_FAULT_FALLBACK)) 5138 return ret; 5139 } else { 5140 huge_pud_set_accessed(&vmf, orig_pud); 5141 return 0; 5142 } 5143 } 5144 } 5145 5146 vmf.pmd = pmd_alloc(mm, vmf.pud, address); 5147 if (!vmf.pmd) 5148 return VM_FAULT_OOM; 5149 5150 /* Huge pud page fault raced with pmd_alloc? */ 5151 if (pud_trans_unstable(vmf.pud)) 5152 goto retry_pud; 5153 5154 if (pmd_none(*vmf.pmd) && 5155 hugepage_vma_check(vma, vm_flags, false, true, true)) { 5156 ret = create_huge_pmd(&vmf); 5157 if (!(ret & VM_FAULT_FALLBACK)) 5158 return ret; 5159 } else { 5160 vmf.orig_pmd = pmdp_get_lockless(vmf.pmd); 5161 5162 if (unlikely(is_swap_pmd(vmf.orig_pmd))) { 5163 VM_BUG_ON(thp_migration_supported() && 5164 !is_pmd_migration_entry(vmf.orig_pmd)); 5165 if (is_pmd_migration_entry(vmf.orig_pmd)) 5166 pmd_migration_entry_wait(mm, vmf.pmd); 5167 return 0; 5168 } 5169 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) { 5170 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma)) 5171 return do_huge_pmd_numa_page(&vmf); 5172 5173 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) && 5174 !pmd_write(vmf.orig_pmd)) { 5175 ret = wp_huge_pmd(&vmf); 5176 if (!(ret & VM_FAULT_FALLBACK)) 5177 return ret; 5178 } else { 5179 huge_pmd_set_accessed(&vmf); 5180 return 0; 5181 } 5182 } 5183 } 5184 5185 return handle_pte_fault(&vmf); 5186 } 5187 5188 /** 5189 * mm_account_fault - Do page fault accounting 5190 * @mm: mm from which memcg should be extracted. It can be NULL. 5191 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting 5192 * of perf event counters, but we'll still do the per-task accounting to 5193 * the task who triggered this page fault. 5194 * @address: the faulted address. 5195 * @flags: the fault flags. 5196 * @ret: the fault retcode. 5197 * 5198 * This will take care of most of the page fault accounting. Meanwhile, it 5199 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter 5200 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should 5201 * still be in per-arch page fault handlers at the entry of page fault. 5202 */ 5203 static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs, 5204 unsigned long address, unsigned int flags, 5205 vm_fault_t ret) 5206 { 5207 bool major; 5208 5209 /* Incomplete faults will be accounted upon completion. */ 5210 if (ret & VM_FAULT_RETRY) 5211 return; 5212 5213 /* 5214 * To preserve the behavior of older kernels, PGFAULT counters record 5215 * both successful and failed faults, as opposed to perf counters, 5216 * which ignore failed cases. 5217 */ 5218 count_vm_event(PGFAULT); 5219 count_memcg_event_mm(mm, PGFAULT); 5220 5221 /* 5222 * Do not account for unsuccessful faults (e.g. when the address wasn't 5223 * valid). That includes arch_vma_access_permitted() failing before 5224 * reaching here. So this is not a "this many hardware page faults" 5225 * counter. We should use the hw profiling for that. 5226 */ 5227 if (ret & VM_FAULT_ERROR) 5228 return; 5229 5230 /* 5231 * We define the fault as a major fault when the final successful fault 5232 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't 5233 * handle it immediately previously). 5234 */ 5235 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED); 5236 5237 if (major) 5238 current->maj_flt++; 5239 else 5240 current->min_flt++; 5241 5242 /* 5243 * If the fault is done for GUP, regs will be NULL. We only do the 5244 * accounting for the per thread fault counters who triggered the 5245 * fault, and we skip the perf event updates. 5246 */ 5247 if (!regs) 5248 return; 5249 5250 if (major) 5251 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address); 5252 else 5253 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address); 5254 } 5255 5256 #ifdef CONFIG_LRU_GEN 5257 static void lru_gen_enter_fault(struct vm_area_struct *vma) 5258 { 5259 /* the LRU algorithm only applies to accesses with recency */ 5260 current->in_lru_fault = vma_has_recency(vma); 5261 } 5262 5263 static void lru_gen_exit_fault(void) 5264 { 5265 current->in_lru_fault = false; 5266 } 5267 #else 5268 static void lru_gen_enter_fault(struct vm_area_struct *vma) 5269 { 5270 } 5271 5272 static void lru_gen_exit_fault(void) 5273 { 5274 } 5275 #endif /* CONFIG_LRU_GEN */ 5276 5277 static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, 5278 unsigned int *flags) 5279 { 5280 if (unlikely(*flags & FAULT_FLAG_UNSHARE)) { 5281 if (WARN_ON_ONCE(*flags & FAULT_FLAG_WRITE)) 5282 return VM_FAULT_SIGSEGV; 5283 /* 5284 * FAULT_FLAG_UNSHARE only applies to COW mappings. Let's 5285 * just treat it like an ordinary read-fault otherwise. 5286 */ 5287 if (!is_cow_mapping(vma->vm_flags)) 5288 *flags &= ~FAULT_FLAG_UNSHARE; 5289 } else if (*flags & FAULT_FLAG_WRITE) { 5290 /* Write faults on read-only mappings are impossible ... */ 5291 if (WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE))) 5292 return VM_FAULT_SIGSEGV; 5293 /* ... and FOLL_FORCE only applies to COW mappings. */ 5294 if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE) && 5295 !is_cow_mapping(vma->vm_flags))) 5296 return VM_FAULT_SIGSEGV; 5297 } 5298 #ifdef CONFIG_PER_VMA_LOCK 5299 /* 5300 * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of 5301 * the assumption that lock is dropped on VM_FAULT_RETRY. 5302 */ 5303 if (WARN_ON_ONCE((*flags & 5304 (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) == 5305 (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT))) 5306 return VM_FAULT_SIGSEGV; 5307 #endif 5308 5309 return 0; 5310 } 5311 5312 /* 5313 * By the time we get here, we already hold the mm semaphore 5314 * 5315 * The mmap_lock may have been released depending on flags and our 5316 * return value. See filemap_fault() and __folio_lock_or_retry(). 5317 */ 5318 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address, 5319 unsigned int flags, struct pt_regs *regs) 5320 { 5321 /* If the fault handler drops the mmap_lock, vma may be freed */ 5322 struct mm_struct *mm = vma->vm_mm; 5323 vm_fault_t ret; 5324 5325 __set_current_state(TASK_RUNNING); 5326 5327 ret = sanitize_fault_flags(vma, &flags); 5328 if (ret) 5329 goto out; 5330 5331 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE, 5332 flags & FAULT_FLAG_INSTRUCTION, 5333 flags & FAULT_FLAG_REMOTE)) { 5334 ret = VM_FAULT_SIGSEGV; 5335 goto out; 5336 } 5337 5338 /* 5339 * Enable the memcg OOM handling for faults triggered in user 5340 * space. Kernel faults are handled more gracefully. 5341 */ 5342 if (flags & FAULT_FLAG_USER) 5343 mem_cgroup_enter_user_fault(); 5344 5345 lru_gen_enter_fault(vma); 5346 5347 if (unlikely(is_vm_hugetlb_page(vma))) 5348 ret = hugetlb_fault(vma->vm_mm, vma, address, flags); 5349 else 5350 ret = __handle_mm_fault(vma, address, flags); 5351 5352 lru_gen_exit_fault(); 5353 5354 if (flags & FAULT_FLAG_USER) { 5355 mem_cgroup_exit_user_fault(); 5356 /* 5357 * The task may have entered a memcg OOM situation but 5358 * if the allocation error was handled gracefully (no 5359 * VM_FAULT_OOM), there is no need to kill anything. 5360 * Just clean up the OOM state peacefully. 5361 */ 5362 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM)) 5363 mem_cgroup_oom_synchronize(false); 5364 } 5365 out: 5366 mm_account_fault(mm, regs, address, flags, ret); 5367 5368 return ret; 5369 } 5370 EXPORT_SYMBOL_GPL(handle_mm_fault); 5371 5372 #ifdef CONFIG_LOCK_MM_AND_FIND_VMA 5373 #include <linux/extable.h> 5374 5375 static inline bool get_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs) 5376 { 5377 if (likely(mmap_read_trylock(mm))) 5378 return true; 5379 5380 if (regs && !user_mode(regs)) { 5381 unsigned long ip = instruction_pointer(regs); 5382 if (!search_exception_tables(ip)) 5383 return false; 5384 } 5385 5386 return !mmap_read_lock_killable(mm); 5387 } 5388 5389 static inline bool mmap_upgrade_trylock(struct mm_struct *mm) 5390 { 5391 /* 5392 * We don't have this operation yet. 5393 * 5394 * It should be easy enough to do: it's basically a 5395 * atomic_long_try_cmpxchg_acquire() 5396 * from RWSEM_READER_BIAS -> RWSEM_WRITER_LOCKED, but 5397 * it also needs the proper lockdep magic etc. 5398 */ 5399 return false; 5400 } 5401 5402 static inline bool upgrade_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs) 5403 { 5404 mmap_read_unlock(mm); 5405 if (regs && !user_mode(regs)) { 5406 unsigned long ip = instruction_pointer(regs); 5407 if (!search_exception_tables(ip)) 5408 return false; 5409 } 5410 return !mmap_write_lock_killable(mm); 5411 } 5412 5413 /* 5414 * Helper for page fault handling. 5415 * 5416 * This is kind of equivalend to "mmap_read_lock()" followed 5417 * by "find_extend_vma()", except it's a lot more careful about 5418 * the locking (and will drop the lock on failure). 5419 * 5420 * For example, if we have a kernel bug that causes a page 5421 * fault, we don't want to just use mmap_read_lock() to get 5422 * the mm lock, because that would deadlock if the bug were 5423 * to happen while we're holding the mm lock for writing. 5424 * 5425 * So this checks the exception tables on kernel faults in 5426 * order to only do this all for instructions that are actually 5427 * expected to fault. 5428 * 5429 * We can also actually take the mm lock for writing if we 5430 * need to extend the vma, which helps the VM layer a lot. 5431 */ 5432 struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm, 5433 unsigned long addr, struct pt_regs *regs) 5434 { 5435 struct vm_area_struct *vma; 5436 5437 if (!get_mmap_lock_carefully(mm, regs)) 5438 return NULL; 5439 5440 vma = find_vma(mm, addr); 5441 if (likely(vma && (vma->vm_start <= addr))) 5442 return vma; 5443 5444 /* 5445 * Well, dang. We might still be successful, but only 5446 * if we can extend a vma to do so. 5447 */ 5448 if (!vma || !(vma->vm_flags & VM_GROWSDOWN)) { 5449 mmap_read_unlock(mm); 5450 return NULL; 5451 } 5452 5453 /* 5454 * We can try to upgrade the mmap lock atomically, 5455 * in which case we can continue to use the vma 5456 * we already looked up. 5457 * 5458 * Otherwise we'll have to drop the mmap lock and 5459 * re-take it, and also look up the vma again, 5460 * re-checking it. 5461 */ 5462 if (!mmap_upgrade_trylock(mm)) { 5463 if (!upgrade_mmap_lock_carefully(mm, regs)) 5464 return NULL; 5465 5466 vma = find_vma(mm, addr); 5467 if (!vma) 5468 goto fail; 5469 if (vma->vm_start <= addr) 5470 goto success; 5471 if (!(vma->vm_flags & VM_GROWSDOWN)) 5472 goto fail; 5473 } 5474 5475 if (expand_stack_locked(vma, addr)) 5476 goto fail; 5477 5478 success: 5479 mmap_write_downgrade(mm); 5480 return vma; 5481 5482 fail: 5483 mmap_write_unlock(mm); 5484 return NULL; 5485 } 5486 #endif 5487 5488 #ifdef CONFIG_PER_VMA_LOCK 5489 /* 5490 * Lookup and lock a VMA under RCU protection. Returned VMA is guaranteed to be 5491 * stable and not isolated. If the VMA is not found or is being modified the 5492 * function returns NULL. 5493 */ 5494 struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm, 5495 unsigned long address) 5496 { 5497 MA_STATE(mas, &mm->mm_mt, address, address); 5498 struct vm_area_struct *vma; 5499 5500 rcu_read_lock(); 5501 retry: 5502 vma = mas_walk(&mas); 5503 if (!vma) 5504 goto inval; 5505 5506 if (!vma_start_read(vma)) 5507 goto inval; 5508 5509 /* 5510 * find_mergeable_anon_vma uses adjacent vmas which are not locked. 5511 * This check must happen after vma_start_read(); otherwise, a 5512 * concurrent mremap() with MREMAP_DONTUNMAP could dissociate the VMA 5513 * from its anon_vma. 5514 */ 5515 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) 5516 goto inval_end_read; 5517 5518 /* Check since vm_start/vm_end might change before we lock the VMA */ 5519 if (unlikely(address < vma->vm_start || address >= vma->vm_end)) 5520 goto inval_end_read; 5521 5522 /* Check if the VMA got isolated after we found it */ 5523 if (vma->detached) { 5524 vma_end_read(vma); 5525 count_vm_vma_lock_event(VMA_LOCK_MISS); 5526 /* The area was replaced with another one */ 5527 goto retry; 5528 } 5529 5530 rcu_read_unlock(); 5531 return vma; 5532 5533 inval_end_read: 5534 vma_end_read(vma); 5535 inval: 5536 rcu_read_unlock(); 5537 count_vm_vma_lock_event(VMA_LOCK_ABORT); 5538 return NULL; 5539 } 5540 #endif /* CONFIG_PER_VMA_LOCK */ 5541 5542 #ifndef __PAGETABLE_P4D_FOLDED 5543 /* 5544 * Allocate p4d page table. 5545 * We've already handled the fast-path in-line. 5546 */ 5547 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) 5548 { 5549 p4d_t *new = p4d_alloc_one(mm, address); 5550 if (!new) 5551 return -ENOMEM; 5552 5553 spin_lock(&mm->page_table_lock); 5554 if (pgd_present(*pgd)) { /* Another has populated it */ 5555 p4d_free(mm, new); 5556 } else { 5557 smp_wmb(); /* See comment in pmd_install() */ 5558 pgd_populate(mm, pgd, new); 5559 } 5560 spin_unlock(&mm->page_table_lock); 5561 return 0; 5562 } 5563 #endif /* __PAGETABLE_P4D_FOLDED */ 5564 5565 #ifndef __PAGETABLE_PUD_FOLDED 5566 /* 5567 * Allocate page upper directory. 5568 * We've already handled the fast-path in-line. 5569 */ 5570 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address) 5571 { 5572 pud_t *new = pud_alloc_one(mm, address); 5573 if (!new) 5574 return -ENOMEM; 5575 5576 spin_lock(&mm->page_table_lock); 5577 if (!p4d_present(*p4d)) { 5578 mm_inc_nr_puds(mm); 5579 smp_wmb(); /* See comment in pmd_install() */ 5580 p4d_populate(mm, p4d, new); 5581 } else /* Another has populated it */ 5582 pud_free(mm, new); 5583 spin_unlock(&mm->page_table_lock); 5584 return 0; 5585 } 5586 #endif /* __PAGETABLE_PUD_FOLDED */ 5587 5588 #ifndef __PAGETABLE_PMD_FOLDED 5589 /* 5590 * Allocate page middle directory. 5591 * We've already handled the fast-path in-line. 5592 */ 5593 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) 5594 { 5595 spinlock_t *ptl; 5596 pmd_t *new = pmd_alloc_one(mm, address); 5597 if (!new) 5598 return -ENOMEM; 5599 5600 ptl = pud_lock(mm, pud); 5601 if (!pud_present(*pud)) { 5602 mm_inc_nr_pmds(mm); 5603 smp_wmb(); /* See comment in pmd_install() */ 5604 pud_populate(mm, pud, new); 5605 } else { /* Another has populated it */ 5606 pmd_free(mm, new); 5607 } 5608 spin_unlock(ptl); 5609 return 0; 5610 } 5611 #endif /* __PAGETABLE_PMD_FOLDED */ 5612 5613 /** 5614 * follow_pte - look up PTE at a user virtual address 5615 * @mm: the mm_struct of the target address space 5616 * @address: user virtual address 5617 * @ptepp: location to store found PTE 5618 * @ptlp: location to store the lock for the PTE 5619 * 5620 * On a successful return, the pointer to the PTE is stored in @ptepp; 5621 * the corresponding lock is taken and its location is stored in @ptlp. 5622 * The contents of the PTE are only stable until @ptlp is released; 5623 * any further use, if any, must be protected against invalidation 5624 * with MMU notifiers. 5625 * 5626 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore 5627 * should be taken for read. 5628 * 5629 * KVM uses this function. While it is arguably less bad than ``follow_pfn``, 5630 * it is not a good general-purpose API. 5631 * 5632 * Return: zero on success, -ve otherwise. 5633 */ 5634 int follow_pte(struct mm_struct *mm, unsigned long address, 5635 pte_t **ptepp, spinlock_t **ptlp) 5636 { 5637 pgd_t *pgd; 5638 p4d_t *p4d; 5639 pud_t *pud; 5640 pmd_t *pmd; 5641 pte_t *ptep; 5642 5643 pgd = pgd_offset(mm, address); 5644 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) 5645 goto out; 5646 5647 p4d = p4d_offset(pgd, address); 5648 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d))) 5649 goto out; 5650 5651 pud = pud_offset(p4d, address); 5652 if (pud_none(*pud) || unlikely(pud_bad(*pud))) 5653 goto out; 5654 5655 pmd = pmd_offset(pud, address); 5656 VM_BUG_ON(pmd_trans_huge(*pmd)); 5657 5658 ptep = pte_offset_map_lock(mm, pmd, address, ptlp); 5659 if (!ptep) 5660 goto out; 5661 if (!pte_present(ptep_get(ptep))) 5662 goto unlock; 5663 *ptepp = ptep; 5664 return 0; 5665 unlock: 5666 pte_unmap_unlock(ptep, *ptlp); 5667 out: 5668 return -EINVAL; 5669 } 5670 EXPORT_SYMBOL_GPL(follow_pte); 5671 5672 /** 5673 * follow_pfn - look up PFN at a user virtual address 5674 * @vma: memory mapping 5675 * @address: user virtual address 5676 * @pfn: location to store found PFN 5677 * 5678 * Only IO mappings and raw PFN mappings are allowed. 5679 * 5680 * This function does not allow the caller to read the permissions 5681 * of the PTE. Do not use it. 5682 * 5683 * Return: zero and the pfn at @pfn on success, -ve otherwise. 5684 */ 5685 int follow_pfn(struct vm_area_struct *vma, unsigned long address, 5686 unsigned long *pfn) 5687 { 5688 int ret = -EINVAL; 5689 spinlock_t *ptl; 5690 pte_t *ptep; 5691 5692 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 5693 return ret; 5694 5695 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl); 5696 if (ret) 5697 return ret; 5698 *pfn = pte_pfn(ptep_get(ptep)); 5699 pte_unmap_unlock(ptep, ptl); 5700 return 0; 5701 } 5702 EXPORT_SYMBOL(follow_pfn); 5703 5704 #ifdef CONFIG_HAVE_IOREMAP_PROT 5705 int follow_phys(struct vm_area_struct *vma, 5706 unsigned long address, unsigned int flags, 5707 unsigned long *prot, resource_size_t *phys) 5708 { 5709 int ret = -EINVAL; 5710 pte_t *ptep, pte; 5711 spinlock_t *ptl; 5712 5713 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 5714 goto out; 5715 5716 if (follow_pte(vma->vm_mm, address, &ptep, &ptl)) 5717 goto out; 5718 pte = ptep_get(ptep); 5719 5720 if ((flags & FOLL_WRITE) && !pte_write(pte)) 5721 goto unlock; 5722 5723 *prot = pgprot_val(pte_pgprot(pte)); 5724 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; 5725 5726 ret = 0; 5727 unlock: 5728 pte_unmap_unlock(ptep, ptl); 5729 out: 5730 return ret; 5731 } 5732 5733 /** 5734 * generic_access_phys - generic implementation for iomem mmap access 5735 * @vma: the vma to access 5736 * @addr: userspace address, not relative offset within @vma 5737 * @buf: buffer to read/write 5738 * @len: length of transfer 5739 * @write: set to FOLL_WRITE when writing, otherwise reading 5740 * 5741 * This is a generic implementation for &vm_operations_struct.access for an 5742 * iomem mapping. This callback is used by access_process_vm() when the @vma is 5743 * not page based. 5744 */ 5745 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, 5746 void *buf, int len, int write) 5747 { 5748 resource_size_t phys_addr; 5749 unsigned long prot = 0; 5750 void __iomem *maddr; 5751 pte_t *ptep, pte; 5752 spinlock_t *ptl; 5753 int offset = offset_in_page(addr); 5754 int ret = -EINVAL; 5755 5756 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 5757 return -EINVAL; 5758 5759 retry: 5760 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl)) 5761 return -EINVAL; 5762 pte = ptep_get(ptep); 5763 pte_unmap_unlock(ptep, ptl); 5764 5765 prot = pgprot_val(pte_pgprot(pte)); 5766 phys_addr = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; 5767 5768 if ((write & FOLL_WRITE) && !pte_write(pte)) 5769 return -EINVAL; 5770 5771 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot); 5772 if (!maddr) 5773 return -ENOMEM; 5774 5775 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl)) 5776 goto out_unmap; 5777 5778 if (!pte_same(pte, ptep_get(ptep))) { 5779 pte_unmap_unlock(ptep, ptl); 5780 iounmap(maddr); 5781 5782 goto retry; 5783 } 5784 5785 if (write) 5786 memcpy_toio(maddr + offset, buf, len); 5787 else 5788 memcpy_fromio(buf, maddr + offset, len); 5789 ret = len; 5790 pte_unmap_unlock(ptep, ptl); 5791 out_unmap: 5792 iounmap(maddr); 5793 5794 return ret; 5795 } 5796 EXPORT_SYMBOL_GPL(generic_access_phys); 5797 #endif 5798 5799 /* 5800 * Access another process' address space as given in mm. 5801 */ 5802 static int __access_remote_vm(struct mm_struct *mm, unsigned long addr, 5803 void *buf, int len, unsigned int gup_flags) 5804 { 5805 void *old_buf = buf; 5806 int write = gup_flags & FOLL_WRITE; 5807 5808 if (mmap_read_lock_killable(mm)) 5809 return 0; 5810 5811 /* Untag the address before looking up the VMA */ 5812 addr = untagged_addr_remote(mm, addr); 5813 5814 /* Avoid triggering the temporary warning in __get_user_pages */ 5815 if (!vma_lookup(mm, addr) && !expand_stack(mm, addr)) 5816 return 0; 5817 5818 /* ignore errors, just check how much was successfully transferred */ 5819 while (len) { 5820 int bytes, offset; 5821 void *maddr; 5822 struct vm_area_struct *vma = NULL; 5823 struct page *page = get_user_page_vma_remote(mm, addr, 5824 gup_flags, &vma); 5825 5826 if (IS_ERR(page)) { 5827 /* We might need to expand the stack to access it */ 5828 vma = vma_lookup(mm, addr); 5829 if (!vma) { 5830 vma = expand_stack(mm, addr); 5831 5832 /* mmap_lock was dropped on failure */ 5833 if (!vma) 5834 return buf - old_buf; 5835 5836 /* Try again if stack expansion worked */ 5837 continue; 5838 } 5839 5840 /* 5841 * Check if this is a VM_IO | VM_PFNMAP VMA, which 5842 * we can access using slightly different code. 5843 */ 5844 bytes = 0; 5845 #ifdef CONFIG_HAVE_IOREMAP_PROT 5846 if (vma->vm_ops && vma->vm_ops->access) 5847 bytes = vma->vm_ops->access(vma, addr, buf, 5848 len, write); 5849 #endif 5850 if (bytes <= 0) 5851 break; 5852 } else { 5853 bytes = len; 5854 offset = addr & (PAGE_SIZE-1); 5855 if (bytes > PAGE_SIZE-offset) 5856 bytes = PAGE_SIZE-offset; 5857 5858 maddr = kmap(page); 5859 if (write) { 5860 copy_to_user_page(vma, page, addr, 5861 maddr + offset, buf, bytes); 5862 set_page_dirty_lock(page); 5863 } else { 5864 copy_from_user_page(vma, page, addr, 5865 buf, maddr + offset, bytes); 5866 } 5867 kunmap(page); 5868 put_page(page); 5869 } 5870 len -= bytes; 5871 buf += bytes; 5872 addr += bytes; 5873 } 5874 mmap_read_unlock(mm); 5875 5876 return buf - old_buf; 5877 } 5878 5879 /** 5880 * access_remote_vm - access another process' address space 5881 * @mm: the mm_struct of the target address space 5882 * @addr: start address to access 5883 * @buf: source or destination buffer 5884 * @len: number of bytes to transfer 5885 * @gup_flags: flags modifying lookup behaviour 5886 * 5887 * The caller must hold a reference on @mm. 5888 * 5889 * Return: number of bytes copied from source to destination. 5890 */ 5891 int access_remote_vm(struct mm_struct *mm, unsigned long addr, 5892 void *buf, int len, unsigned int gup_flags) 5893 { 5894 return __access_remote_vm(mm, addr, buf, len, gup_flags); 5895 } 5896 5897 /* 5898 * Access another process' address space. 5899 * Source/target buffer must be kernel space, 5900 * Do not walk the page table directly, use get_user_pages 5901 */ 5902 int access_process_vm(struct task_struct *tsk, unsigned long addr, 5903 void *buf, int len, unsigned int gup_flags) 5904 { 5905 struct mm_struct *mm; 5906 int ret; 5907 5908 mm = get_task_mm(tsk); 5909 if (!mm) 5910 return 0; 5911 5912 ret = __access_remote_vm(mm, addr, buf, len, gup_flags); 5913 5914 mmput(mm); 5915 5916 return ret; 5917 } 5918 EXPORT_SYMBOL_GPL(access_process_vm); 5919 5920 /* 5921 * Print the name of a VMA. 5922 */ 5923 void print_vma_addr(char *prefix, unsigned long ip) 5924 { 5925 struct mm_struct *mm = current->mm; 5926 struct vm_area_struct *vma; 5927 5928 /* 5929 * we might be running from an atomic context so we cannot sleep 5930 */ 5931 if (!mmap_read_trylock(mm)) 5932 return; 5933 5934 vma = find_vma(mm, ip); 5935 if (vma && vma->vm_file) { 5936 struct file *f = vma->vm_file; 5937 char *buf = (char *)__get_free_page(GFP_NOWAIT); 5938 if (buf) { 5939 char *p; 5940 5941 p = file_path(f, buf, PAGE_SIZE); 5942 if (IS_ERR(p)) 5943 p = "?"; 5944 printk("%s%s[%lx+%lx]", prefix, kbasename(p), 5945 vma->vm_start, 5946 vma->vm_end - vma->vm_start); 5947 free_page((unsigned long)buf); 5948 } 5949 } 5950 mmap_read_unlock(mm); 5951 } 5952 5953 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP) 5954 void __might_fault(const char *file, int line) 5955 { 5956 if (pagefault_disabled()) 5957 return; 5958 __might_sleep(file, line); 5959 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP) 5960 if (current->mm) 5961 might_lock_read(¤t->mm->mmap_lock); 5962 #endif 5963 } 5964 EXPORT_SYMBOL(__might_fault); 5965 #endif 5966 5967 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) 5968 /* 5969 * Process all subpages of the specified huge page with the specified 5970 * operation. The target subpage will be processed last to keep its 5971 * cache lines hot. 5972 */ 5973 static inline int process_huge_page( 5974 unsigned long addr_hint, unsigned int pages_per_huge_page, 5975 int (*process_subpage)(unsigned long addr, int idx, void *arg), 5976 void *arg) 5977 { 5978 int i, n, base, l, ret; 5979 unsigned long addr = addr_hint & 5980 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1); 5981 5982 /* Process target subpage last to keep its cache lines hot */ 5983 might_sleep(); 5984 n = (addr_hint - addr) / PAGE_SIZE; 5985 if (2 * n <= pages_per_huge_page) { 5986 /* If target subpage in first half of huge page */ 5987 base = 0; 5988 l = n; 5989 /* Process subpages at the end of huge page */ 5990 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) { 5991 cond_resched(); 5992 ret = process_subpage(addr + i * PAGE_SIZE, i, arg); 5993 if (ret) 5994 return ret; 5995 } 5996 } else { 5997 /* If target subpage in second half of huge page */ 5998 base = pages_per_huge_page - 2 * (pages_per_huge_page - n); 5999 l = pages_per_huge_page - n; 6000 /* Process subpages at the begin of huge page */ 6001 for (i = 0; i < base; i++) { 6002 cond_resched(); 6003 ret = process_subpage(addr + i * PAGE_SIZE, i, arg); 6004 if (ret) 6005 return ret; 6006 } 6007 } 6008 /* 6009 * Process remaining subpages in left-right-left-right pattern 6010 * towards the target subpage 6011 */ 6012 for (i = 0; i < l; i++) { 6013 int left_idx = base + i; 6014 int right_idx = base + 2 * l - 1 - i; 6015 6016 cond_resched(); 6017 ret = process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg); 6018 if (ret) 6019 return ret; 6020 cond_resched(); 6021 ret = process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg); 6022 if (ret) 6023 return ret; 6024 } 6025 return 0; 6026 } 6027 6028 static void clear_gigantic_page(struct page *page, 6029 unsigned long addr, 6030 unsigned int pages_per_huge_page) 6031 { 6032 int i; 6033 struct page *p; 6034 6035 might_sleep(); 6036 for (i = 0; i < pages_per_huge_page; i++) { 6037 p = nth_page(page, i); 6038 cond_resched(); 6039 clear_user_highpage(p, addr + i * PAGE_SIZE); 6040 } 6041 } 6042 6043 static int clear_subpage(unsigned long addr, int idx, void *arg) 6044 { 6045 struct page *page = arg; 6046 6047 clear_user_highpage(page + idx, addr); 6048 return 0; 6049 } 6050 6051 void clear_huge_page(struct page *page, 6052 unsigned long addr_hint, unsigned int pages_per_huge_page) 6053 { 6054 unsigned long addr = addr_hint & 6055 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1); 6056 6057 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { 6058 clear_gigantic_page(page, addr, pages_per_huge_page); 6059 return; 6060 } 6061 6062 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page); 6063 } 6064 6065 static int copy_user_gigantic_page(struct folio *dst, struct folio *src, 6066 unsigned long addr, 6067 struct vm_area_struct *vma, 6068 unsigned int pages_per_huge_page) 6069 { 6070 int i; 6071 struct page *dst_page; 6072 struct page *src_page; 6073 6074 for (i = 0; i < pages_per_huge_page; i++) { 6075 dst_page = folio_page(dst, i); 6076 src_page = folio_page(src, i); 6077 6078 cond_resched(); 6079 if (copy_mc_user_highpage(dst_page, src_page, 6080 addr + i*PAGE_SIZE, vma)) { 6081 memory_failure_queue(page_to_pfn(src_page), 0); 6082 return -EHWPOISON; 6083 } 6084 } 6085 return 0; 6086 } 6087 6088 struct copy_subpage_arg { 6089 struct page *dst; 6090 struct page *src; 6091 struct vm_area_struct *vma; 6092 }; 6093 6094 static int copy_subpage(unsigned long addr, int idx, void *arg) 6095 { 6096 struct copy_subpage_arg *copy_arg = arg; 6097 6098 if (copy_mc_user_highpage(copy_arg->dst + idx, copy_arg->src + idx, 6099 addr, copy_arg->vma)) { 6100 memory_failure_queue(page_to_pfn(copy_arg->src + idx), 0); 6101 return -EHWPOISON; 6102 } 6103 return 0; 6104 } 6105 6106 int copy_user_large_folio(struct folio *dst, struct folio *src, 6107 unsigned long addr_hint, struct vm_area_struct *vma) 6108 { 6109 unsigned int pages_per_huge_page = folio_nr_pages(dst); 6110 unsigned long addr = addr_hint & 6111 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1); 6112 struct copy_subpage_arg arg = { 6113 .dst = &dst->page, 6114 .src = &src->page, 6115 .vma = vma, 6116 }; 6117 6118 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) 6119 return copy_user_gigantic_page(dst, src, addr, vma, 6120 pages_per_huge_page); 6121 6122 return process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg); 6123 } 6124 6125 long copy_folio_from_user(struct folio *dst_folio, 6126 const void __user *usr_src, 6127 bool allow_pagefault) 6128 { 6129 void *kaddr; 6130 unsigned long i, rc = 0; 6131 unsigned int nr_pages = folio_nr_pages(dst_folio); 6132 unsigned long ret_val = nr_pages * PAGE_SIZE; 6133 struct page *subpage; 6134 6135 for (i = 0; i < nr_pages; i++) { 6136 subpage = folio_page(dst_folio, i); 6137 kaddr = kmap_local_page(subpage); 6138 if (!allow_pagefault) 6139 pagefault_disable(); 6140 rc = copy_from_user(kaddr, usr_src + i * PAGE_SIZE, PAGE_SIZE); 6141 if (!allow_pagefault) 6142 pagefault_enable(); 6143 kunmap_local(kaddr); 6144 6145 ret_val -= (PAGE_SIZE - rc); 6146 if (rc) 6147 break; 6148 6149 flush_dcache_page(subpage); 6150 6151 cond_resched(); 6152 } 6153 return ret_val; 6154 } 6155 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */ 6156 6157 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS 6158 6159 static struct kmem_cache *page_ptl_cachep; 6160 6161 void __init ptlock_cache_init(void) 6162 { 6163 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0, 6164 SLAB_PANIC, NULL); 6165 } 6166 6167 bool ptlock_alloc(struct ptdesc *ptdesc) 6168 { 6169 spinlock_t *ptl; 6170 6171 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL); 6172 if (!ptl) 6173 return false; 6174 ptdesc->ptl = ptl; 6175 return true; 6176 } 6177 6178 void ptlock_free(struct ptdesc *ptdesc) 6179 { 6180 kmem_cache_free(page_ptl_cachep, ptdesc->ptl); 6181 } 6182 #endif 6183