1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * linux/mm/memory.c 4 * 5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 6 */ 7 8 /* 9 * demand-loading started 01.12.91 - seems it is high on the list of 10 * things wanted, and it should be easy to implement. - Linus 11 */ 12 13 /* 14 * Ok, demand-loading was easy, shared pages a little bit tricker. Shared 15 * pages started 02.12.91, seems to work. - Linus. 16 * 17 * Tested sharing by executing about 30 /bin/sh: under the old kernel it 18 * would have taken more than the 6M I have free, but it worked well as 19 * far as I could see. 20 * 21 * Also corrected some "invalidate()"s - I wasn't doing enough of them. 22 */ 23 24 /* 25 * Real VM (paging to/from disk) started 18.12.91. Much more work and 26 * thought has to go into this. Oh, well.. 27 * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why. 28 * Found it. Everything seems to work now. 29 * 20.12.91 - Ok, making the swap-device changeable like the root. 30 */ 31 32 /* 33 * 05.04.94 - Multi-page memory management added for v1.1. 34 * Idea by Alex Bligh (alex@cconcepts.co.uk) 35 * 36 * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG 37 * (Gerhard.Wichert@pdb.siemens.de) 38 * 39 * Aug/Sep 2004 Changed to four level page tables (Andi Kleen) 40 */ 41 42 #include <linux/kernel_stat.h> 43 #include <linux/mm.h> 44 #include <linux/mm_inline.h> 45 #include <linux/sched/mm.h> 46 #include <linux/sched/numa_balancing.h> 47 #include <linux/sched/task.h> 48 #include <linux/hugetlb.h> 49 #include <linux/mman.h> 50 #include <linux/swap.h> 51 #include <linux/highmem.h> 52 #include <linux/pagemap.h> 53 #include <linux/memremap.h> 54 #include <linux/kmsan.h> 55 #include <linux/ksm.h> 56 #include <linux/rmap.h> 57 #include <linux/export.h> 58 #include <linux/delayacct.h> 59 #include <linux/init.h> 60 #include <linux/writeback.h> 61 #include <linux/memcontrol.h> 62 #include <linux/mmu_notifier.h> 63 #include <linux/leafops.h> 64 #include <linux/elf.h> 65 #include <linux/gfp.h> 66 #include <linux/migrate.h> 67 #include <linux/string.h> 68 #include <linux/shmem_fs.h> 69 #include <linux/memory-tiers.h> 70 #include <linux/debugfs.h> 71 #include <linux/userfaultfd_k.h> 72 #include <linux/dax.h> 73 #include <linux/oom.h> 74 #include <linux/numa.h> 75 #include <linux/perf_event.h> 76 #include <linux/ptrace.h> 77 #include <linux/vmalloc.h> 78 #include <linux/sched/sysctl.h> 79 #include <linux/pgalloc.h> 80 #include <linux/uaccess.h> 81 82 #include <trace/events/kmem.h> 83 84 #include <asm/io.h> 85 #include <asm/mmu_context.h> 86 #include <asm/tlb.h> 87 #include <asm/tlbflush.h> 88 89 #include "pgalloc-track.h" 90 #include "internal.h" 91 #include "swap.h" 92 93 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST) 94 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid. 95 #endif 96 97 static vm_fault_t do_fault(struct vm_fault *vmf); 98 static vm_fault_t do_anonymous_page(struct vm_fault *vmf); 99 static bool vmf_pte_changed(struct vm_fault *vmf); 100 101 /* 102 * Return true if the original pte was a uffd-wp pte marker (so the pte was 103 * wr-protected). 104 */ 105 static __always_inline bool vmf_orig_pte_uffd_wp(struct vm_fault *vmf) 106 { 107 if (!userfaultfd_wp(vmf->vma)) 108 return false; 109 if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)) 110 return false; 111 112 return pte_is_uffd_wp_marker(vmf->orig_pte); 113 } 114 115 /* 116 * Randomize the address space (stacks, mmaps, brk, etc.). 117 * 118 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization, 119 * as ancient (libc5 based) binaries can segfault. ) 120 */ 121 int randomize_va_space __read_mostly = 122 #ifdef CONFIG_COMPAT_BRK 123 1; 124 #else 125 2; 126 #endif 127 128 static const struct ctl_table mmu_sysctl_table[] = { 129 { 130 .procname = "randomize_va_space", 131 .data = &randomize_va_space, 132 .maxlen = sizeof(int), 133 .mode = 0644, 134 .proc_handler = proc_dointvec, 135 }, 136 }; 137 138 static int __init init_mm_sysctl(void) 139 { 140 register_sysctl_init("kernel", mmu_sysctl_table); 141 return 0; 142 } 143 144 subsys_initcall(init_mm_sysctl); 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 highest_memmap_pfn __read_mostly; 166 167 void mm_trace_rss_stat(struct mm_struct *mm, int member) 168 { 169 trace_rss_stat(mm, member); 170 } 171 172 /* 173 * Note: this doesn't free the actual pages themselves. That 174 * has been handled earlier when unmapping all the memory regions. 175 */ 176 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd, 177 unsigned long addr) 178 { 179 pgtable_t token = pmd_pgtable(*pmd); 180 pmd_clear(pmd); 181 pte_free_tlb(tlb, token, addr); 182 mm_dec_nr_ptes(tlb->mm); 183 } 184 185 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud, 186 unsigned long addr, unsigned long end, 187 unsigned long floor, unsigned long ceiling) 188 { 189 pmd_t *pmd; 190 unsigned long next; 191 unsigned long start; 192 193 start = addr; 194 pmd = pmd_offset(pud, addr); 195 do { 196 next = pmd_addr_end(addr, end); 197 if (pmd_none_or_clear_bad(pmd)) 198 continue; 199 free_pte_range(tlb, pmd, addr); 200 } while (pmd++, addr = next, addr != end); 201 202 start &= PUD_MASK; 203 if (start < floor) 204 return; 205 if (ceiling) { 206 ceiling &= PUD_MASK; 207 if (!ceiling) 208 return; 209 } 210 if (end - 1 > ceiling - 1) 211 return; 212 213 pmd = pmd_offset(pud, start); 214 pud_clear(pud); 215 pmd_free_tlb(tlb, pmd, start); 216 mm_dec_nr_pmds(tlb->mm); 217 } 218 219 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d, 220 unsigned long addr, unsigned long end, 221 unsigned long floor, unsigned long ceiling) 222 { 223 pud_t *pud; 224 unsigned long next; 225 unsigned long start; 226 227 start = addr; 228 pud = pud_offset(p4d, addr); 229 do { 230 next = pud_addr_end(addr, end); 231 if (pud_none_or_clear_bad(pud)) 232 continue; 233 free_pmd_range(tlb, pud, addr, next, floor, ceiling); 234 } while (pud++, addr = next, addr != end); 235 236 start &= P4D_MASK; 237 if (start < floor) 238 return; 239 if (ceiling) { 240 ceiling &= P4D_MASK; 241 if (!ceiling) 242 return; 243 } 244 if (end - 1 > ceiling - 1) 245 return; 246 247 pud = pud_offset(p4d, start); 248 p4d_clear(p4d); 249 pud_free_tlb(tlb, pud, start); 250 mm_dec_nr_puds(tlb->mm); 251 } 252 253 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd, 254 unsigned long addr, unsigned long end, 255 unsigned long floor, unsigned long ceiling) 256 { 257 p4d_t *p4d; 258 unsigned long next; 259 unsigned long start; 260 261 start = addr; 262 p4d = p4d_offset(pgd, addr); 263 do { 264 next = p4d_addr_end(addr, end); 265 if (p4d_none_or_clear_bad(p4d)) 266 continue; 267 free_pud_range(tlb, p4d, addr, next, floor, ceiling); 268 } while (p4d++, addr = next, addr != end); 269 270 start &= PGDIR_MASK; 271 if (start < floor) 272 return; 273 if (ceiling) { 274 ceiling &= PGDIR_MASK; 275 if (!ceiling) 276 return; 277 } 278 if (end - 1 > ceiling - 1) 279 return; 280 281 p4d = p4d_offset(pgd, start); 282 pgd_clear(pgd); 283 p4d_free_tlb(tlb, p4d, start); 284 } 285 286 /** 287 * free_pgd_range - Unmap and free page tables in the range 288 * @tlb: the mmu_gather containing pending TLB flush info 289 * @addr: virtual address start 290 * @end: virtual address end 291 * @floor: lowest address boundary 292 * @ceiling: highest address boundary 293 * 294 * This function tears down all user-level page tables in the 295 * specified virtual address range [@addr..@end). It is part of 296 * the memory unmap flow. 297 */ 298 void free_pgd_range(struct mmu_gather *tlb, 299 unsigned long addr, unsigned long end, 300 unsigned long floor, unsigned long ceiling) 301 { 302 pgd_t *pgd; 303 unsigned long next; 304 305 /* 306 * The next few lines have given us lots of grief... 307 * 308 * Why are we testing PMD* at this top level? Because often 309 * there will be no work to do at all, and we'd prefer not to 310 * go all the way down to the bottom just to discover that. 311 * 312 * Why all these "- 1"s? Because 0 represents both the bottom 313 * of the address space and the top of it (using -1 for the 314 * top wouldn't help much: the masks would do the wrong thing). 315 * The rule is that addr 0 and floor 0 refer to the bottom of 316 * the address space, but end 0 and ceiling 0 refer to the top 317 * Comparisons need to use "end - 1" and "ceiling - 1" (though 318 * that end 0 case should be mythical). 319 * 320 * Wherever addr is brought up or ceiling brought down, we must 321 * be careful to reject "the opposite 0" before it confuses the 322 * subsequent tests. But what about where end is brought down 323 * by PMD_SIZE below? no, end can't go down to 0 there. 324 * 325 * Whereas we round start (addr) and ceiling down, by different 326 * masks at different levels, in order to test whether a table 327 * now has no other vmas using it, so can be freed, we don't 328 * bother to round floor or end up - the tests don't need that. 329 */ 330 331 addr &= PMD_MASK; 332 if (addr < floor) { 333 addr += PMD_SIZE; 334 if (!addr) 335 return; 336 } 337 if (ceiling) { 338 ceiling &= PMD_MASK; 339 if (!ceiling) 340 return; 341 } 342 if (end - 1 > ceiling - 1) 343 end -= PMD_SIZE; 344 if (addr > end - 1) 345 return; 346 /* 347 * We add page table cache pages with PAGE_SIZE, 348 * (see pte_free_tlb()), flush the tlb if we need 349 */ 350 tlb_change_page_size(tlb, PAGE_SIZE); 351 pgd = pgd_offset(tlb->mm, addr); 352 do { 353 next = pgd_addr_end(addr, end); 354 if (pgd_none_or_clear_bad(pgd)) 355 continue; 356 free_p4d_range(tlb, pgd, addr, next, floor, ceiling); 357 } while (pgd++, addr = next, addr != end); 358 } 359 360 /** 361 * free_pgtables() - Free a range of page tables 362 * @tlb: The mmu gather 363 * @unmap: The unmap_desc 364 * 365 * Note: pg_start and pg_end are provided to indicate the absolute range of the 366 * page tables that should be removed. This can differ from the vma mappings on 367 * some archs that may have mappings that need to be removed outside the vmas. 368 * Note that the prev->vm_end and next->vm_start are often used. 369 * 370 * The vma_end differs from the pg_end when a dup_mmap() failed and the tree has 371 * unrelated data to the mm_struct being torn down. 372 */ 373 void free_pgtables(struct mmu_gather *tlb, struct unmap_desc *unmap) 374 { 375 struct unlink_vma_file_batch vb; 376 struct ma_state *mas = unmap->mas; 377 struct vm_area_struct *vma = unmap->first; 378 379 /* 380 * Note: USER_PGTABLES_CEILING may be passed as the value of pg_end and 381 * may be 0. Underflow is expected in this case. Otherwise the 382 * pagetable end is exclusive. vma_end is exclusive. The last vma 383 * address should never be larger than the pagetable end. 384 */ 385 WARN_ON_ONCE(unmap->vma_end - 1 > unmap->pg_end - 1); 386 387 tlb_free_vmas(tlb); 388 389 do { 390 unsigned long addr = vma->vm_start; 391 struct vm_area_struct *next; 392 393 next = mas_find(mas, unmap->tree_end - 1); 394 395 /* 396 * Hide vma from rmap and truncate_pagecache before freeing 397 * pgtables 398 */ 399 if (unmap->mm_wr_locked) 400 vma_start_write(vma); 401 unlink_anon_vmas(vma); 402 403 unlink_file_vma_batch_init(&vb); 404 unlink_file_vma_batch_add(&vb, vma); 405 406 /* 407 * Optimization: gather nearby vmas into one call down 408 */ 409 while (next && next->vm_start <= vma->vm_end + PMD_SIZE) { 410 vma = next; 411 next = mas_find(mas, unmap->tree_end - 1); 412 if (unmap->mm_wr_locked) 413 vma_start_write(vma); 414 unlink_anon_vmas(vma); 415 unlink_file_vma_batch_add(&vb, vma); 416 } 417 unlink_file_vma_batch_final(&vb); 418 419 free_pgd_range(tlb, addr, vma->vm_end, unmap->pg_start, 420 next ? next->vm_start : unmap->pg_end); 421 vma = next; 422 } while (vma); 423 } 424 425 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte) 426 { 427 spinlock_t *ptl = pmd_lock(mm, pmd); 428 429 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ 430 mm_inc_nr_ptes(mm); 431 /* 432 * Ensure all pte setup (eg. pte page lock and page clearing) are 433 * visible before the pte is made visible to other CPUs by being 434 * put into page tables. 435 * 436 * The other side of the story is the pointer chasing in the page 437 * table walking code (when walking the page table without locking; 438 * ie. most of the time). Fortunately, these data accesses consist 439 * of a chain of data-dependent loads, meaning most CPUs (alpha 440 * being the notable exception) will already guarantee loads are 441 * seen in-order. See the alpha page table accessors for the 442 * smp_rmb() barriers in page table walking code. 443 */ 444 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */ 445 pmd_populate(mm, pmd, *pte); 446 *pte = NULL; 447 } 448 spin_unlock(ptl); 449 } 450 451 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd) 452 { 453 pgtable_t new = pte_alloc_one(mm); 454 if (!new) 455 return -ENOMEM; 456 457 pmd_install(mm, pmd, &new); 458 if (new) 459 pte_free(mm, new); 460 return 0; 461 } 462 463 int __pte_alloc_kernel(pmd_t *pmd) 464 { 465 pte_t *new = pte_alloc_one_kernel(&init_mm); 466 if (!new) 467 return -ENOMEM; 468 469 spin_lock(&init_mm.page_table_lock); 470 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ 471 smp_wmb(); /* See comment in pmd_install() */ 472 pmd_populate_kernel(&init_mm, pmd, new); 473 new = NULL; 474 } 475 spin_unlock(&init_mm.page_table_lock); 476 if (new) 477 pte_free_kernel(&init_mm, new); 478 return 0; 479 } 480 481 static inline void init_rss_vec(int *rss) 482 { 483 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS); 484 } 485 486 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss) 487 { 488 int i; 489 490 for (i = 0; i < NR_MM_COUNTERS; i++) 491 if (rss[i]) 492 add_mm_counter(mm, i, rss[i]); 493 } 494 495 /* Allow a burst of 60 bad page map reports per minute. */ 496 static DEFINE_RATELIMIT_STATE(bad_page_map_ratelimit, 60 * HZ, 60); 497 498 void ptval_bytes_to_hex_str(char *buf, size_t buf_size, const void *entry, size_t entry_size) 499 { 500 if (WARN_ON_ONCE(buf_size < entry_size * 2 + 1)) { 501 snprintf(buf, buf_size, "overflow"); 502 return; 503 } 504 505 switch (entry_size) { 506 case sizeof(u32): 507 snprintf(buf, buf_size, "%08x", *(const u32 *)entry); 508 break; 509 case sizeof(u64): 510 snprintf(buf, buf_size, "%016llx", *(const u64 *)entry); 511 break; 512 #if defined(__SIZEOF_INT128__) 513 case sizeof(u128): 514 snprintf(buf, buf_size, "%016llx%016llx", 515 (unsigned long long)(*(const u128 *)entry >> 64), 516 (unsigned long long)*(const u128 *)entry); 517 break; 518 #endif 519 default: 520 snprintf(buf, buf_size, "unsupported"); 521 break; 522 } 523 } 524 525 static void __print_bad_page_map_pgtable(struct mm_struct *mm, unsigned long addr) 526 { 527 char pgd_str[PTVAL_STR_MAX]; 528 char p4d_str[PTVAL_STR_MAX]; 529 char pud_str[PTVAL_STR_MAX]; 530 char pmd_str[PTVAL_STR_MAX]; 531 p4d_t p4d, *p4dp; 532 pud_t pud, *pudp; 533 pmd_t pmd, *pmdp; 534 pgd_t *pgdp; 535 536 /* 537 * Although this looks like a fully lockless pgtable walk, it is not: 538 * see locking requirements for print_bad_page_map(). 539 */ 540 pgdp = pgd_offset(mm, addr); 541 ptval_to_str(pgd_str, pgd_val(*pgdp)); 542 543 if (!pgd_present(*pgdp) || pgd_leaf(*pgdp)) { 544 pr_alert("pgd:%s\n", pgd_str); 545 return; 546 } 547 548 p4dp = p4d_offset(pgdp, addr); 549 p4d = p4dp_get(p4dp); 550 ptval_to_str(p4d_str, p4d_val(p4d)); 551 552 if (!p4d_present(p4d) || p4d_leaf(p4d)) { 553 pr_alert("pgd:%s p4d:%s\n", pgd_str, p4d_str); 554 return; 555 } 556 557 pudp = pud_offset(p4dp, addr); 558 pud = pudp_get(pudp); 559 ptval_to_str(pud_str, pud_val(pud)); 560 561 if (!pud_present(pud) || pud_leaf(pud)) { 562 pr_alert("pgd:%s p4d:%s pud:%s\n", pgd_str, p4d_str, pud_str); 563 return; 564 } 565 566 pmdp = pmd_offset(pudp, addr); 567 pmd = pmdp_get(pmdp); 568 ptval_to_str(pmd_str, pmd_val(pmd)); 569 570 /* 571 * Dumping the PTE would be nice, but it's tricky with CONFIG_HIGHPTE, 572 * because the table should already be mapped by the caller and 573 * doing another map would be bad. print_bad_page_map() should 574 * already take care of printing the PTE. 575 */ 576 pr_alert("pgd:%s p4d:%s pud:%s pmd:%s\n", pgd_str, p4d_str, pud_str, pmd_str); 577 } 578 579 /* 580 * This function is called to print an error when a bad page table entry (e.g., 581 * corrupted page table entry) is found. For example, we might have a 582 * PFN-mapped pte in a region that doesn't allow it. 583 * 584 * The calling function must still handle the error. 585 * 586 * This function must be called during a proper page table walk, as it will 587 * re-walk the page table to dump information: the caller MUST prevent page 588 * table teardown (by holding mmap, vma or rmap lock) and MUST hold the leaf 589 * page table lock. 590 */ 591 static void print_bad_page_map(struct vm_area_struct *vma, 592 unsigned long addr, const void *entry, size_t entry_size, 593 struct page *page, enum pgtable_level level) 594 { 595 struct address_space *mapping; 596 char entry_str[PTVAL_STR_MAX]; 597 pgoff_t index, anon_index; 598 599 if (!__ratelimit(&bad_page_map_ratelimit)) 600 return; 601 602 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL; 603 index = linear_page_index(vma, addr); 604 anon_index = __linear_anon_page_index(vma, addr); 605 606 ptval_bytes_to_hex_str(entry_str, sizeof(entry_str), entry, entry_size); 607 pr_alert("BUG: Bad page map in process %s %s:%s", current->comm, 608 pgtable_level_to_str(level), entry_str); 609 __print_bad_page_map_pgtable(vma->vm_mm, addr); 610 if (page) 611 dump_page(page, "bad page map"); 612 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px", 613 (void *)addr, vma->vm_flags, vma->anon_vma, mapping); 614 if (!vma_is_cow_mapping(vma) || index == anon_index) { 615 pr_cont(" index:%lx\n", index); 616 } else { 617 pr_cont(" index:%lx (file) %lx (anon)\n", index, anon_index); 618 } 619 620 pr_alert("file:%pD fault:%ps mmap:%ps mmap_prepare: %ps read_folio:%ps\n", 621 vma->vm_file, 622 vma->vm_ops ? vma->vm_ops->fault : NULL, 623 vma->vm_file ? vma->vm_file->f_op->mmap : NULL, 624 vma->vm_file ? vma->vm_file->f_op->mmap_prepare : NULL, 625 mapping ? mapping->a_ops->read_folio : NULL); 626 dump_stack(); 627 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 628 } 629 630 static inline bool pgtable_level_has_pxx_special(enum pgtable_level level) 631 { 632 switch (level) { 633 case PGTABLE_LEVEL_PTE: 634 return IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL); 635 case PGTABLE_LEVEL_PMD: 636 return IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP); 637 case PGTABLE_LEVEL_PUD: 638 return IS_ENABLED(CONFIG_ARCH_SUPPORTS_PUD_PFNMAP); 639 default: 640 return false; 641 } 642 } 643 644 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr, 645 pte_t pte, struct page *page) 646 { 647 auto entry = pte_val(pte); 648 649 print_bad_page_map(vma, addr, &entry, sizeof(entry), page, PGTABLE_LEVEL_PTE); 650 } 651 652 /** 653 * __vm_normal_page() - Get the "struct page" associated with a page table entry. 654 * @vma: The VMA mapping the page table entry. 655 * @addr: The address where the page table entry is mapped. 656 * @pfn: The PFN stored in the page table entry. 657 * @special: Whether the page table entry is marked "special". 658 * @entry: The page table entry value for error reporting purposes only. 659 * @entry_size: The size of @entry. 660 * @level: The page table level for error reporting purposes only. 661 * 662 * "Special" mappings do not wish to be associated with a "struct page" (either 663 * it doesn't exist, or it exists but they don't want to touch it). In this 664 * case, NULL is returned here. "Normal" mappings do have a struct page and 665 * are ordinarily refcounted. 666 * 667 * Page mappings of the shared zero folios are always considered "special", as 668 * they are not ordinarily refcounted: neither the refcount nor the mapcount 669 * of these folios is adjusted when mapping them into user page tables. 670 * Selected page table walkers (such as GUP) can still identify mappings of the 671 * shared zero folios and work with the underlying "struct page". 672 * 673 * There are 2 broad cases. Firstly, an architecture may define a "special" 674 * page table entry bit, such as pte_special(), in which case this function is 675 * trivial. Secondly, an architecture may not have a spare page table 676 * entry bit, which requires a more complicated scheme, described below. 677 * 678 * With CONFIG_FIND_NORMAL_PAGE, we might have the "special" bit set on 679 * page table entries that actually map "normal" pages: however, that page 680 * cannot be looked up through the PFN stored in the page table entry, but 681 * instead will be looked up through vm_ops->find_normal_page(). So far, this 682 * only applies to PTEs. 683 * 684 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a 685 * special mapping (even if there are underlying and valid "struct pages"). 686 * COWed pages of a VM_PFNMAP are always normal. 687 * 688 * The way we recognize COWed pages within VM_PFNMAP mappings is through the 689 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit 690 * set, and the vm_pgoff will point to the first PFN mapped: thus every special 691 * mapping will always honor the rule 692 * 693 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT) 694 * 695 * And for normal mappings this is false. 696 * 697 * This restricts such mappings to be a linear translation from virtual address 698 * to pfn. To get around this restriction, we allow arbitrary mappings so long 699 * as the vma is not a COW mapping; in that case, we know that all ptes are 700 * special (because none can have been COWed). 701 * 702 * 703 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP. 704 * 705 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct 706 * page" backing, however the difference is that _all_ pages with a struct 707 * page (that is, those where pfn_valid is true, except the shared zero 708 * folios) are refcounted and considered normal pages by the VM. 709 * 710 * The disadvantage is that pages are refcounted (which can be slower and 711 * simply not an option for some PFNMAP users). The advantage is that we 712 * don't have to follow the strict linearity rule of PFNMAP mappings in 713 * order to support COWable mappings. 714 * 715 * Return: Returns the "struct page" if this is a "normal" mapping. Returns 716 * NULL if this is a "special" mapping. 717 */ 718 static inline struct page *__vm_normal_page(struct vm_area_struct *vma, 719 unsigned long addr, unsigned long pfn, bool special, 720 const void *entry, size_t entry_size, enum pgtable_level level) 721 { 722 if (pgtable_level_has_pxx_special(level)) { 723 if (unlikely(special)) { 724 #ifdef CONFIG_FIND_NORMAL_PAGE 725 if (vma->vm_ops && vma->vm_ops->find_normal_page) 726 return vma->vm_ops->find_normal_page(vma, addr); 727 #endif /* CONFIG_FIND_NORMAL_PAGE */ 728 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP)) 729 return NULL; 730 if (is_zero_pfn(pfn) || is_huge_zero_pfn(pfn)) 731 return NULL; 732 733 print_bad_page_map(vma, addr, entry, entry_size, NULL, level); 734 return NULL; 735 } 736 /* 737 * With working pte_special()/pmd_special()..., any special page 738 * table mappings (incl. shared zero folios) are marked 739 * accordingly. 740 */ 741 } else { 742 if (unlikely(vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))) { 743 if (vma->vm_flags & VM_MIXEDMAP) { 744 /* If it has a "struct page", it's "normal". */ 745 if (!pfn_valid(pfn)) 746 return NULL; 747 } else { 748 const pgoff_t index = linear_page_index(vma, addr); 749 750 /* Only CoW'ed anon folios are "normal". */ 751 if (pfn == index) 752 return NULL; 753 if (!vma_is_cow_mapping(vma)) 754 return NULL; 755 } 756 } 757 758 if (is_zero_pfn(pfn) || is_huge_zero_pfn(pfn)) 759 return NULL; 760 } 761 762 if (unlikely(pfn > highest_memmap_pfn)) { 763 /* Corrupted page table entry. */ 764 print_bad_page_map(vma, addr, entry, entry_size, NULL, level); 765 return NULL; 766 } 767 /* 768 * NOTE! We still have PageReserved() pages in the page tables. 769 * For example, VDSO mappings can cause them to exist. 770 */ 771 VM_WARN_ON_ONCE(is_zero_pfn(pfn) || is_huge_zero_pfn(pfn)); 772 return pfn_to_page(pfn); 773 } 774 775 /** 776 * vm_normal_page() - Get the "struct page" associated with a PTE 777 * @vma: The VMA mapping the @pte. 778 * @addr: The address where the @pte is mapped. 779 * @pte: The PTE. 780 * 781 * Get the "struct page" associated with a PTE. See __vm_normal_page() 782 * for details on "normal" and "special" mappings. 783 * 784 * Return: Returns the "struct page" if this is a "normal" mapping. Returns 785 * NULL if this is a "special" mapping. 786 */ 787 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, 788 pte_t pte) 789 { 790 auto entry = pte_val(pte); 791 792 return __vm_normal_page(vma, addr, pte_pfn(pte), pte_special(pte), 793 &entry, sizeof(entry), PGTABLE_LEVEL_PTE); 794 } 795 796 /** 797 * vm_normal_folio() - Get the "struct folio" associated with a PTE 798 * @vma: The VMA mapping the @pte. 799 * @addr: The address where the @pte is mapped. 800 * @pte: The PTE. 801 * 802 * Get the "struct folio" associated with a PTE. See __vm_normal_page() 803 * for details on "normal" and "special" mappings. 804 * 805 * Return: Returns the "struct folio" if this is a "normal" mapping. Returns 806 * NULL if this is a "special" mapping. 807 */ 808 struct folio *vm_normal_folio(struct vm_area_struct *vma, unsigned long addr, 809 pte_t pte) 810 { 811 struct page *page = vm_normal_page(vma, addr, pte); 812 813 if (page) 814 return page_folio(page); 815 return NULL; 816 } 817 818 #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES 819 /** 820 * vm_normal_page_pmd() - Get the "struct page" associated with a PMD 821 * @vma: The VMA mapping the @pmd. 822 * @addr: The address where the @pmd is mapped. 823 * @pmd: The PMD. 824 * 825 * Get the "struct page" associated with a PTE. See __vm_normal_page() 826 * for details on "normal" and "special" mappings. 827 * 828 * Return: Returns the "struct page" if this is a "normal" mapping. Returns 829 * NULL if this is a "special" mapping. 830 */ 831 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr, 832 pmd_t pmd) 833 { 834 auto entry = pmd_val(pmd); 835 836 return __vm_normal_page(vma, addr, pmd_pfn(pmd), pmd_special(pmd), 837 &entry, sizeof(entry), PGTABLE_LEVEL_PMD); 838 } 839 840 /** 841 * vm_normal_folio_pmd() - Get the "struct folio" associated with a PMD 842 * @vma: The VMA mapping the @pmd. 843 * @addr: The address where the @pmd is mapped. 844 * @pmd: The PMD. 845 * 846 * Get the "struct folio" associated with a PTE. See __vm_normal_page() 847 * for details on "normal" and "special" mappings. 848 * 849 * Return: Returns the "struct folio" if this is a "normal" mapping. Returns 850 * NULL if this is a "special" mapping. 851 */ 852 struct folio *vm_normal_folio_pmd(struct vm_area_struct *vma, 853 unsigned long addr, pmd_t pmd) 854 { 855 struct page *page = vm_normal_page_pmd(vma, addr, pmd); 856 857 if (page) 858 return page_folio(page); 859 return NULL; 860 } 861 862 /** 863 * vm_normal_page_pud() - Get the "struct page" associated with a PUD 864 * @vma: The VMA mapping the @pud. 865 * @addr: The address where the @pud is mapped. 866 * @pud: The PUD. 867 * 868 * Get the "struct page" associated with a PUD. See __vm_normal_page() 869 * for details on "normal" and "special" mappings. 870 * 871 * Return: Returns the "struct page" if this is a "normal" mapping. Returns 872 * NULL if this is a "special" mapping. 873 */ 874 struct page *vm_normal_page_pud(struct vm_area_struct *vma, 875 unsigned long addr, pud_t pud) 876 { 877 auto entry = pud_val(pud); 878 879 return __vm_normal_page(vma, addr, pud_pfn(pud), pud_special(pud), 880 &entry, sizeof(entry), PGTABLE_LEVEL_PUD); 881 } 882 #endif 883 884 /** 885 * restore_exclusive_pte - Restore a device-exclusive entry 886 * @vma: VMA covering @address 887 * @folio: the mapped folio 888 * @page: the mapped folio page 889 * @address: the virtual address 890 * @ptep: pte pointer into the locked page table mapping the folio page 891 * @orig_pte: pte value at @ptep 892 * 893 * Restore a device-exclusive non-swap entry to an ordinary present pte. 894 * 895 * The folio and the page table must be locked, and MMU notifiers must have 896 * been called to invalidate any (exclusive) device mappings. 897 * 898 * Locking the folio makes sure that anybody who just converted the pte to 899 * a device-exclusive entry can map it into the device to make forward 900 * progress without others converting it back until the folio was unlocked. 901 * 902 * If the folio lock ever becomes an issue, we can stop relying on the folio 903 * lock; it might make some scenarios with heavy thrashing less likely to 904 * make forward progress, but these scenarios might not be valid use cases. 905 * 906 * Note that the folio lock does not protect against all cases of concurrent 907 * page table modifications (e.g., MADV_DONTNEED, mprotect), so device drivers 908 * must use MMU notifiers to sync against any concurrent changes. 909 */ 910 static void restore_exclusive_pte(struct vm_area_struct *vma, 911 struct folio *folio, struct page *page, unsigned long address, 912 pte_t *ptep, pte_t orig_pte) 913 { 914 pte_t pte; 915 916 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 917 918 pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot))); 919 if (pte_swp_soft_dirty(orig_pte)) 920 pte = pte_mksoft_dirty(pte); 921 922 if (pte_swp_uffd(orig_pte)) 923 pte = pte_mkuffd(pte); 924 925 /* See do_swap_page(): restore PAGE_NONE for RWP */ 926 if (pte_swp_uffd(orig_pte) && userfaultfd_rwp(vma)) 927 pte = pte_modify(pte, PAGE_NONE); 928 929 if ((vma->vm_flags & VM_WRITE) && 930 can_change_pte_writable(vma, address, pte)) { 931 if (folio_test_dirty(folio)) 932 pte = pte_mkdirty(pte); 933 pte = pte_mkwrite(pte, vma); 934 } 935 set_pte_at(vma->vm_mm, address, ptep, pte); 936 937 /* 938 * No need to invalidate - it was non-present before. However 939 * secondary CPUs may have mappings that need invalidating. 940 */ 941 update_mmu_cache(vma, address, ptep); 942 } 943 944 /* 945 * Tries to restore an exclusive pte if the page lock can be acquired without 946 * sleeping. 947 */ 948 static int try_restore_exclusive_pte(struct vm_area_struct *vma, 949 unsigned long addr, pte_t *ptep, pte_t orig_pte) 950 { 951 const softleaf_t entry = softleaf_from_pte(orig_pte); 952 struct page *page = softleaf_to_page(entry); 953 struct folio *folio = page_folio(page); 954 955 if (folio_trylock(folio)) { 956 restore_exclusive_pte(vma, folio, page, addr, ptep, orig_pte); 957 folio_unlock(folio); 958 return 0; 959 } 960 961 return -EBUSY; 962 } 963 964 /* 965 * copy one vm_area from one task to the other. Assumes the page tables 966 * already present in the new task to be cleared in the whole range 967 * covered by this vma. 968 */ 969 970 static unsigned long 971 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm, 972 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma, 973 struct vm_area_struct *src_vma, unsigned long addr, int *rss) 974 { 975 pte_t orig_pte = ptep_get(src_pte); 976 softleaf_t entry = softleaf_from_pte(orig_pte); 977 pte_t pte = orig_pte; 978 struct folio *folio; 979 struct page *page; 980 981 if (likely(softleaf_is_swap(entry))) { 982 if (swap_dup_entry_direct(entry) < 0) 983 return -EIO; 984 985 mm_prepare_for_swap_entries(dst_mm); 986 /* Mark the swap entry as shared. */ 987 if (pte_swp_exclusive(orig_pte)) { 988 pte = pte_swp_clear_exclusive(orig_pte); 989 set_pte_at(src_mm, addr, src_pte, pte); 990 } 991 rss[MM_SWAPENTS]++; 992 } else if (softleaf_is_migration(entry)) { 993 folio = softleaf_to_folio(entry); 994 995 rss[mm_counter(folio)]++; 996 997 if (!softleaf_is_migration_read(entry) && 998 vma_is_cow_mapping(dst_vma)) { 999 /* 1000 * COW mappings require pages in both parent and child 1001 * to be set to read. A previously exclusive entry is 1002 * now shared. 1003 */ 1004 entry = make_readable_migration_entry( 1005 swp_offset(entry)); 1006 pte = softleaf_to_pte(entry); 1007 if (pte_swp_soft_dirty(orig_pte)) 1008 pte = pte_swp_mksoft_dirty(pte); 1009 if (pte_swp_uffd(orig_pte)) 1010 pte = pte_swp_mkuffd(pte); 1011 set_pte_at(src_mm, addr, src_pte, pte); 1012 } 1013 } else if (softleaf_is_device_private(entry)) { 1014 page = softleaf_to_page(entry); 1015 folio = page_folio(page); 1016 1017 /* 1018 * Update rss count even for unaddressable pages, as 1019 * they should treated just like normal pages in this 1020 * respect. 1021 * 1022 * We will likely want to have some new rss counters 1023 * for unaddressable pages, at some point. But for now 1024 * keep things as they are. 1025 */ 1026 folio_get(folio); 1027 rss[mm_counter(folio)]++; 1028 /* Cannot fail as these pages cannot get pinned. */ 1029 folio_try_dup_anon_rmap_pte(folio, page, dst_vma, src_vma); 1030 1031 /* 1032 * We do not preserve soft-dirty information, because so 1033 * far, checkpoint/restore is the only feature that 1034 * requires that. And checkpoint/restore does not work 1035 * when a device driver is involved (you cannot easily 1036 * save and restore device driver state). 1037 */ 1038 if (softleaf_is_device_private_write(entry) && 1039 vma_is_cow_mapping(dst_vma)) { 1040 entry = make_readable_device_private_entry( 1041 swp_offset(entry)); 1042 pte = swp_entry_to_pte(entry); 1043 if (pte_swp_uffd(orig_pte)) 1044 pte = pte_swp_mkuffd(pte); 1045 set_pte_at(src_mm, addr, src_pte, pte); 1046 } 1047 } else if (softleaf_is_device_exclusive(entry)) { 1048 /* 1049 * Make device exclusive entries present by restoring the 1050 * original entry then copying as for a present pte. Device 1051 * exclusive entries currently only support private writable 1052 * (ie. COW) mappings. 1053 */ 1054 VM_BUG_ON(!vma_is_cow_mapping(src_vma)); 1055 if (try_restore_exclusive_pte(src_vma, addr, src_pte, orig_pte)) 1056 return -EBUSY; 1057 return -ENOENT; 1058 } else if (softleaf_is_marker(entry)) { 1059 pte_marker marker = copy_pte_marker(entry, dst_vma); 1060 1061 if (marker) 1062 set_pte_at(dst_mm, addr, dst_pte, 1063 make_pte_marker(marker)); 1064 return 0; 1065 } 1066 if (!userfaultfd_protected(dst_vma)) 1067 pte = pte_swp_clear_uffd(pte); 1068 set_pte_at(dst_mm, addr, dst_pte, pte); 1069 return 0; 1070 } 1071 1072 /* 1073 * Copy a present and normal page. 1074 * 1075 * NOTE! The usual case is that this isn't required; 1076 * instead, the caller can just increase the page refcount 1077 * and re-use the pte the traditional way. 1078 * 1079 * And if we need a pre-allocated page but don't yet have 1080 * one, return a negative error to let the preallocation 1081 * code know so that it can do so outside the page table 1082 * lock. 1083 */ 1084 static inline int 1085 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1086 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss, 1087 struct folio **prealloc, struct page *page) 1088 { 1089 struct folio *new_folio; 1090 pte_t pte; 1091 1092 new_folio = *prealloc; 1093 if (!new_folio) 1094 return -EAGAIN; 1095 1096 /* 1097 * We have a prealloc page, all good! Take it 1098 * over and copy the page & arm it. 1099 */ 1100 1101 if (copy_mc_user_highpage(&new_folio->page, page, addr, src_vma)) 1102 return -EHWPOISON; 1103 1104 *prealloc = NULL; 1105 __folio_mark_uptodate(new_folio); 1106 folio_add_new_anon_rmap(new_folio, dst_vma, addr, RMAP_EXCLUSIVE); 1107 folio_add_lru_vma(new_folio, dst_vma); 1108 rss[MM_ANONPAGES]++; 1109 1110 /* All done, just insert the new page copy in the child */ 1111 pte = folio_mk_pte(new_folio, dst_vma->vm_page_prot); 1112 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma); 1113 if (userfaultfd_protected(dst_vma) && pte_uffd(ptep_get(src_pte))) { 1114 /* The uffd bit needs to be delivered to the dest pte as well */ 1115 pte = pte_mkuffd(pte); 1116 /* Restore PAGE_NONE so the RWP marker keeps trapping */ 1117 if (userfaultfd_rwp(dst_vma)) 1118 pte = pte_modify(pte, PAGE_NONE); 1119 } 1120 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte); 1121 return 0; 1122 } 1123 1124 static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma, 1125 struct vm_area_struct *src_vma, pte_t *dst_pte, pte_t *src_pte, 1126 pte_t pte, unsigned long addr, int nr) 1127 { 1128 struct mm_struct *src_mm = src_vma->vm_mm; 1129 bool writable; 1130 1131 /* 1132 * Snapshot writability before the RWP-disarm rewrite below: when the 1133 * child is not RWP-armed, pte_modify(pte, dst_vma->vm_page_prot) can 1134 * silently drop _PAGE_RW from a resolved (no-marker) writable PTE, 1135 * so a later pte_write(pte) check would skip the COW wrprotect and 1136 * leave the parent writable over a folio shared with the child. 1137 */ 1138 writable = pte_write(pte); 1139 1140 /* 1141 * Child is not RWP-armed: restore accessible protection so the 1142 * inherited PAGE_NONE does not cost a fault on first read. Gate on 1143 * pte_uffd(pte) so unrelated PAGE_NONE markers (e.g. NUMA balancing) 1144 * are not normalised away. 1145 */ 1146 if (!userfaultfd_protected(dst_vma)) { 1147 if (userfaultfd_rwp(src_vma) && pte_uffd(pte)) 1148 pte = pte_modify(pte, dst_vma->vm_page_prot); 1149 pte = pte_clear_uffd(pte); 1150 } 1151 1152 /* If it's a COW mapping, write protect it both processes. */ 1153 if (vma_is_cow_mapping(src_vma) && writable) { 1154 wrprotect_ptes(src_mm, addr, src_pte, nr); 1155 pte = pte_wrprotect(pte); 1156 } 1157 1158 /* If it's a shared mapping, mark it clean in the child. */ 1159 if (src_vma->vm_flags & VM_SHARED) 1160 pte = pte_mkclean(pte); 1161 pte = pte_mkold(pte); 1162 1163 set_ptes(dst_vma->vm_mm, addr, dst_pte, pte, nr); 1164 } 1165 1166 /* 1167 * Copy one present PTE, trying to batch-process subsequent PTEs that map 1168 * consecutive pages of the same folio by copying them as well. 1169 * 1170 * Returns -EAGAIN if one preallocated page is required to copy the next PTE. 1171 * Otherwise, returns the number of copied PTEs (at least 1). 1172 */ 1173 static inline int 1174 copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1175 pte_t *dst_pte, pte_t *src_pte, pte_t pte, unsigned long addr, 1176 int max_nr, int *rss, struct folio **prealloc) 1177 { 1178 fpb_t flags = FPB_MERGE_WRITE; 1179 struct page *page; 1180 struct folio *folio; 1181 int err, nr; 1182 1183 page = vm_normal_page(src_vma, addr, pte); 1184 if (unlikely(!page)) 1185 goto copy_pte; 1186 1187 folio = page_folio(page); 1188 1189 /* 1190 * If we likely have to copy, just don't bother with batching. Make 1191 * sure that the common "small folio" case is as fast as possible 1192 * by keeping the batching logic separate. 1193 */ 1194 if (unlikely(!*prealloc && folio_test_large(folio) && max_nr != 1)) { 1195 if (!(src_vma->vm_flags & VM_SHARED)) 1196 flags |= FPB_RESPECT_DIRTY; 1197 if (vma_soft_dirty_enabled(src_vma)) 1198 flags |= FPB_RESPECT_SOFT_DIRTY; 1199 1200 nr = folio_pte_batch_flags(folio, src_vma, src_pte, &pte, max_nr, flags); 1201 folio_ref_add(folio, nr); 1202 if (folio_test_anon(folio)) { 1203 if (unlikely(folio_try_dup_anon_rmap_ptes(folio, page, 1204 nr, dst_vma, src_vma))) { 1205 folio_ref_sub(folio, nr); 1206 return -EAGAIN; 1207 } 1208 rss[MM_ANONPAGES] += nr; 1209 VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio); 1210 } else { 1211 folio_dup_file_rmap_ptes(folio, page, nr, dst_vma); 1212 rss[mm_counter_file(folio)] += nr; 1213 } 1214 __copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte, 1215 addr, nr); 1216 return nr; 1217 } 1218 1219 folio_get(folio); 1220 if (folio_test_anon(folio)) { 1221 /* 1222 * If this page may have been pinned by the parent process, 1223 * copy the page immediately for the child so that we'll always 1224 * guarantee the pinned page won't be randomly replaced in the 1225 * future. 1226 */ 1227 if (unlikely(folio_try_dup_anon_rmap_pte(folio, page, dst_vma, src_vma))) { 1228 /* Page may be pinned, we have to copy. */ 1229 folio_put(folio); 1230 err = copy_present_page(dst_vma, src_vma, dst_pte, src_pte, 1231 addr, rss, prealloc, page); 1232 return err ? err : 1; 1233 } 1234 rss[MM_ANONPAGES]++; 1235 VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio); 1236 } else { 1237 folio_dup_file_rmap_pte(folio, page, dst_vma); 1238 rss[mm_counter_file(folio)]++; 1239 } 1240 1241 copy_pte: 1242 __copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte, addr, 1); 1243 return 1; 1244 } 1245 1246 static inline struct folio *folio_prealloc(struct mm_struct *src_mm, 1247 struct vm_area_struct *vma, unsigned long addr, bool need_zero) 1248 { 1249 struct folio *new_folio; 1250 1251 if (need_zero) 1252 new_folio = vma_alloc_zeroed_movable_folio(vma, addr); 1253 else 1254 new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, addr); 1255 1256 if (!new_folio) 1257 return NULL; 1258 1259 if (mem_cgroup_charge(new_folio, src_mm, GFP_KERNEL)) { 1260 folio_put(new_folio); 1261 return NULL; 1262 } 1263 folio_throttle_swaprate(new_folio, GFP_KERNEL); 1264 1265 return new_folio; 1266 } 1267 1268 static int 1269 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1270 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr, 1271 unsigned long end) 1272 { 1273 struct mm_struct *dst_mm = dst_vma->vm_mm; 1274 struct mm_struct *src_mm = src_vma->vm_mm; 1275 pte_t *orig_src_pte, *orig_dst_pte; 1276 pte_t *src_pte, *dst_pte; 1277 pmd_t dummy_pmdval; 1278 pte_t ptent; 1279 spinlock_t *src_ptl, *dst_ptl; 1280 int progress, max_nr, ret = 0; 1281 int rss[NR_MM_COUNTERS]; 1282 softleaf_t entry = softleaf_mk_none(); 1283 struct folio *prealloc = NULL; 1284 int nr; 1285 1286 again: 1287 progress = 0; 1288 init_rss_vec(rss); 1289 1290 /* 1291 * copy_pmd_range()'s prior pmd_none_or_clear_bad(src_pmd), and the 1292 * error handling here, assume that exclusive mmap_lock on dst and src 1293 * protects anon from unexpected THP transitions; with shmem and file 1294 * protected by mmap_lock-less collapse skipping areas with anon_vma 1295 * (whereas vma_needs_copy() skips areas without anon_vma). A rework 1296 * can remove such assumptions later, but this is good enough for now. 1297 */ 1298 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl); 1299 if (!dst_pte) { 1300 ret = -ENOMEM; 1301 goto out; 1302 } 1303 1304 /* 1305 * We already hold the exclusive mmap_lock, the copy_pte_range() and 1306 * retract_page_tables() are using vma->anon_vma to be exclusive, so 1307 * the PTE page is stable, and there is no need to get pmdval and do 1308 * pmd_same() check. 1309 */ 1310 src_pte = pte_offset_map_rw_nolock(src_mm, src_pmd, addr, &dummy_pmdval, 1311 &src_ptl); 1312 if (!src_pte) { 1313 pte_unmap_unlock(dst_pte, dst_ptl); 1314 /* ret == 0 */ 1315 goto out; 1316 } 1317 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1318 orig_src_pte = src_pte; 1319 orig_dst_pte = dst_pte; 1320 lazy_mmu_mode_enable(); 1321 1322 do { 1323 nr = 1; 1324 1325 /* 1326 * We are holding two locks at this point - either of them 1327 * could generate latencies in another task on another CPU. 1328 */ 1329 if (progress >= 32) { 1330 progress = 0; 1331 if (need_resched() || 1332 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl)) 1333 break; 1334 } 1335 ptent = ptep_get(src_pte); 1336 if (pte_none(ptent)) { 1337 progress++; 1338 continue; 1339 } 1340 if (unlikely(!pte_present(ptent))) { 1341 ret = copy_nonpresent_pte(dst_mm, src_mm, 1342 dst_pte, src_pte, 1343 dst_vma, src_vma, 1344 addr, rss); 1345 if (ret == -EIO) { 1346 entry = softleaf_from_pte(ptep_get(src_pte)); 1347 break; 1348 } else if (ret == -EBUSY) { 1349 break; 1350 } else if (!ret) { 1351 progress += 8; 1352 continue; 1353 } 1354 ptent = ptep_get(src_pte); 1355 VM_WARN_ON_ONCE(!pte_present(ptent)); 1356 1357 /* 1358 * Device exclusive entry restored, continue by copying 1359 * the now present pte. 1360 */ 1361 WARN_ON_ONCE(ret != -ENOENT); 1362 } 1363 /* copy_present_ptes() will clear `*prealloc' if consumed */ 1364 max_nr = (end - addr) / PAGE_SIZE; 1365 ret = copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, 1366 ptent, addr, max_nr, rss, &prealloc); 1367 /* 1368 * If we need a pre-allocated page for this pte, drop the 1369 * locks, allocate, and try again. 1370 * If copy failed due to hwpoison in source page, break out. 1371 */ 1372 if (unlikely(ret == -EAGAIN || ret == -EHWPOISON)) 1373 break; 1374 if (unlikely(prealloc)) { 1375 /* 1376 * pre-alloc page cannot be reused by next time so as 1377 * to strictly follow mempolicy (e.g., alloc_page_vma() 1378 * will allocate page according to address). This 1379 * could only happen if one pinned pte changed. 1380 */ 1381 folio_put(prealloc); 1382 prealloc = NULL; 1383 } 1384 nr = ret; 1385 progress += 8 * nr; 1386 } while (dst_pte += nr, src_pte += nr, addr += PAGE_SIZE * nr, 1387 addr != end); 1388 1389 lazy_mmu_mode_disable(); 1390 pte_unmap_unlock(orig_src_pte, src_ptl); 1391 add_mm_rss_vec(dst_mm, rss); 1392 pte_unmap_unlock(orig_dst_pte, dst_ptl); 1393 cond_resched(); 1394 1395 if (ret == -EIO) { 1396 VM_WARN_ON_ONCE(!entry.val); 1397 if (swap_retry_table_alloc(entry, GFP_KERNEL) < 0) { 1398 ret = -ENOMEM; 1399 goto out; 1400 } 1401 entry.val = 0; 1402 } else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) { 1403 goto out; 1404 } else if (ret == -EAGAIN) { 1405 prealloc = folio_prealloc(src_mm, src_vma, addr, false); 1406 if (!prealloc) 1407 return -ENOMEM; 1408 } else if (ret < 0) { 1409 VM_WARN_ON_ONCE(1); 1410 } 1411 1412 /* We've captured and resolved the error. Reset, try again. */ 1413 ret = 0; 1414 1415 if (addr != end) 1416 goto again; 1417 out: 1418 if (unlikely(prealloc)) 1419 folio_put(prealloc); 1420 return ret; 1421 } 1422 1423 static inline int 1424 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1425 pud_t *dst_pud, pud_t *src_pud, unsigned long addr, 1426 unsigned long end) 1427 { 1428 struct mm_struct *dst_mm = dst_vma->vm_mm; 1429 struct mm_struct *src_mm = src_vma->vm_mm; 1430 pmd_t *src_pmd, *dst_pmd; 1431 unsigned long next; 1432 1433 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr); 1434 if (!dst_pmd) 1435 return -ENOMEM; 1436 src_pmd = pmd_offset(src_pud, addr); 1437 do { 1438 next = pmd_addr_end(addr, end); 1439 if (pmd_is_huge(*src_pmd)) { 1440 int err; 1441 1442 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma); 1443 err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd, 1444 addr, dst_vma, src_vma); 1445 if (err == -ENOMEM) 1446 return -ENOMEM; 1447 if (!err) 1448 continue; 1449 /* fall through */ 1450 } 1451 if (pmd_none_or_clear_bad(src_pmd)) 1452 continue; 1453 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd, 1454 addr, next)) 1455 return -ENOMEM; 1456 } while (dst_pmd++, src_pmd++, addr = next, addr != end); 1457 return 0; 1458 } 1459 1460 static inline int 1461 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1462 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr, 1463 unsigned long end) 1464 { 1465 struct mm_struct *dst_mm = dst_vma->vm_mm; 1466 struct mm_struct *src_mm = src_vma->vm_mm; 1467 pud_t *src_pud, *dst_pud; 1468 unsigned long next; 1469 1470 dst_pud = pud_alloc(dst_mm, dst_p4d, addr); 1471 if (!dst_pud) 1472 return -ENOMEM; 1473 src_pud = pud_offset(src_p4d, addr); 1474 do { 1475 next = pud_addr_end(addr, end); 1476 if (pud_trans_huge(*src_pud)) { 1477 int err; 1478 1479 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma); 1480 err = copy_huge_pud(dst_mm, src_mm, 1481 dst_pud, src_pud, addr, src_vma); 1482 if (err == -ENOMEM) 1483 return -ENOMEM; 1484 if (!err) 1485 continue; 1486 /* fall through */ 1487 } 1488 if (pud_none_or_clear_bad(src_pud)) 1489 continue; 1490 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud, 1491 addr, next)) 1492 return -ENOMEM; 1493 } while (dst_pud++, src_pud++, addr = next, addr != end); 1494 return 0; 1495 } 1496 1497 static inline int 1498 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1499 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr, 1500 unsigned long end) 1501 { 1502 struct mm_struct *dst_mm = dst_vma->vm_mm; 1503 p4d_t *src_p4d, *dst_p4d; 1504 unsigned long next; 1505 1506 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr); 1507 if (!dst_p4d) 1508 return -ENOMEM; 1509 src_p4d = p4d_offset(src_pgd, addr); 1510 do { 1511 next = p4d_addr_end(addr, end); 1512 if (p4d_none_or_clear_bad(src_p4d)) 1513 continue; 1514 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d, 1515 addr, next)) 1516 return -ENOMEM; 1517 } while (dst_p4d++, src_p4d++, addr = next, addr != end); 1518 return 0; 1519 } 1520 1521 /* 1522 * Return true if the vma needs to copy the pgtable during this fork(). Return 1523 * false when we can speed up fork() by allowing lazy page faults later until 1524 * when the child accesses the memory range. 1525 */ 1526 static bool 1527 vma_needs_copy(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma) 1528 { 1529 /* 1530 * We check against dst_vma as while sane VMA flags will have been 1531 * copied, VM_UFFD_WP may be set only on dst_vma. 1532 */ 1533 if (dst_vma->vm_flags & VM_COPY_ON_FORK) 1534 return true; 1535 /* 1536 * The presence of an anon_vma indicates an anonymous VMA has page 1537 * tables which naturally cannot be reconstituted on page fault. 1538 */ 1539 if (src_vma->anon_vma) 1540 return true; 1541 1542 /* 1543 * Don't copy ptes where a page fault will fill them correctly. Fork 1544 * becomes much lighter when there are big shared or private readonly 1545 * mappings. The tradeoff is that copy_page_range is more efficient 1546 * than faulting. 1547 */ 1548 return false; 1549 } 1550 1551 int 1552 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma) 1553 { 1554 pgd_t *src_pgd, *dst_pgd; 1555 unsigned long addr = src_vma->vm_start; 1556 unsigned long end = src_vma->vm_end; 1557 struct mm_struct *dst_mm = dst_vma->vm_mm; 1558 struct mm_struct *src_mm = src_vma->vm_mm; 1559 struct mmu_notifier_range range; 1560 unsigned long next; 1561 bool is_cow; 1562 int ret; 1563 1564 if (!vma_needs_copy(dst_vma, src_vma)) 1565 return 0; 1566 1567 if (is_vm_hugetlb_page(src_vma)) 1568 return copy_hugetlb_page_range(dst_mm, src_mm, dst_vma, src_vma); 1569 1570 /* 1571 * We need to invalidate the secondary MMU mappings only when 1572 * there could be a permission downgrade on the ptes of the 1573 * parent mm. And a permission downgrade will only happen if 1574 * vma_is_cow_mapping() returns true. 1575 */ 1576 is_cow = vma_is_cow_mapping(src_vma); 1577 1578 if (is_cow) { 1579 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE, 1580 0, src_mm, addr, end); 1581 mmu_notifier_invalidate_range_start(&range); 1582 /* 1583 * Disabling preemption is not needed for the write side, as 1584 * the read side doesn't spin, but goes to the mmap_lock. 1585 * 1586 * Use the raw variant of the seqcount_t write API to avoid 1587 * lockdep complaining about preemptibility. 1588 */ 1589 vma_assert_write_locked(src_vma); 1590 raw_write_seqcount_begin(&src_mm->write_protect_seq); 1591 } 1592 1593 ret = 0; 1594 dst_pgd = pgd_offset(dst_mm, addr); 1595 src_pgd = pgd_offset(src_mm, addr); 1596 do { 1597 next = pgd_addr_end(addr, end); 1598 if (pgd_none_or_clear_bad(src_pgd)) 1599 continue; 1600 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd, 1601 addr, next))) { 1602 ret = -ENOMEM; 1603 break; 1604 } 1605 } while (dst_pgd++, src_pgd++, addr = next, addr != end); 1606 1607 if (is_cow) { 1608 raw_write_seqcount_end(&src_mm->write_protect_seq); 1609 mmu_notifier_invalidate_range_end(&range); 1610 } 1611 return ret; 1612 } 1613 1614 /* Whether we should zap all COWed (private) pages too */ 1615 static inline bool should_zap_cows(struct zap_details *details) 1616 { 1617 /* By default, zap all pages */ 1618 if (!details) 1619 return true; 1620 1621 VM_WARN_ON_ONCE(details->skip_cows && details->reclaim_pt); 1622 1623 /* Or, we zap COWed pages only if the caller wants to */ 1624 return !details->skip_cows; 1625 } 1626 1627 /* Decides whether we should zap this folio with the folio pointer specified */ 1628 static inline bool should_zap_folio(struct zap_details *details, 1629 struct folio *folio) 1630 { 1631 /* If we can make a decision without *folio.. */ 1632 if (should_zap_cows(details)) 1633 return true; 1634 1635 /* Otherwise we should only zap non-anon folios */ 1636 return !folio_test_anon(folio); 1637 } 1638 1639 static inline bool zap_drop_markers(struct zap_details *details) 1640 { 1641 if (!details) 1642 return false; 1643 1644 return details->zap_flags & ZAP_FLAG_DROP_MARKER; 1645 } 1646 1647 /** 1648 * cond_install_uffd_wp_ptes - install uffd-wp markers after clearing PTEs 1649 * @vma: The VMA the pages are mapped into. 1650 * @addr: Address the first page of this batch is mapped at. 1651 * @ptep: Page table pointer for the first entry of this batch. 1652 * @pte: Old value of the entry pointed to by @ptep. 1653 * @nr_ptes: Number of entries to install. 1654 * 1655 * If the PTEs were write-protected by uffd-wp in any form, arm special PTEs 1656 * to replace none PTEs. NOTE! This should only be called when the PTEs are 1657 * already cleared so we will never accidentally replace something valuable. 1658 * Meanwhile none PTEs also mean we are not demoting the PTEs so a TLB flush is 1659 * not needed. E.g., when the PTEs were cleared, the caller should have taken 1660 * care of the TLB flush. 1661 * 1662 * Must be called with the page table lock held so that no thread will see the 1663 * none PTEs, and if they see them, they'll fault and serialize at the page table 1664 * lock. 1665 * 1666 * Returns true if uffd-wp PTEs were installed, false otherwise. 1667 */ 1668 bool cond_install_uffd_wp_ptes(struct vm_area_struct *vma, 1669 unsigned long addr, pte_t *ptep, pte_t pte, 1670 unsigned long nr_ptes) 1671 { 1672 bool arm_uffd_pte = false; 1673 1674 if (!uffd_supports_wp_marker()) 1675 return false; 1676 1677 /* The current status of the pte should be "cleared" before calling */ 1678 WARN_ON_ONCE(!pte_none(ptep_get(ptep))); 1679 1680 /* 1681 * NOTE: userfaultfd_wp_unpopulated() doesn't need this whole 1682 * thing, because when zapping either it means it's dropping the 1683 * page, or in TTU where the present pte will be quickly replaced 1684 * with a swap pte. There's no way of leaking the bit. 1685 */ 1686 if (vma_is_anonymous(vma) || !userfaultfd_wp(vma)) 1687 return false; 1688 1689 /* A uffd-wp wr-protected normal pte */ 1690 if (unlikely(pte_present(pte) && pte_uffd(pte))) 1691 arm_uffd_pte = true; 1692 1693 /* 1694 * A uffd-wp wr-protected swap pte. Note: this should even cover an 1695 * existing pte marker with uffd-wp bit set. 1696 */ 1697 if (unlikely(pte_swp_uffd_any(pte))) 1698 arm_uffd_pte = true; 1699 1700 if (likely(!arm_uffd_pte)) 1701 return false; 1702 1703 for (;;) { 1704 set_pte_at(vma->vm_mm, addr, ptep, 1705 make_pte_marker(PTE_MARKER_UFFD_WP)); 1706 if (--nr_ptes == 0) 1707 break; 1708 ptep++; 1709 addr += PAGE_SIZE; 1710 } 1711 1712 return true; 1713 } 1714 1715 /* 1716 * This function makes sure that we'll replace the none pte with an uffd-wp 1717 * swap special pte marker when necessary. Must be with the pgtable lock held. 1718 * 1719 * Returns true if uffd-wp ptes was installed, false otherwise. 1720 */ 1721 static inline bool 1722 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma, 1723 unsigned long addr, pte_t *pte, int nr, 1724 struct zap_details *details, pte_t pteval) 1725 { 1726 if (zap_drop_markers(details)) 1727 return false; 1728 1729 return cond_install_uffd_wp_ptes(vma, addr, pte, pteval, nr); 1730 } 1731 1732 static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb, 1733 struct vm_area_struct *vma, struct folio *folio, 1734 struct page *page, pte_t *pte, pte_t ptent, unsigned int nr, 1735 unsigned long addr, struct zap_details *details, int *rss, 1736 bool *force_flush, bool *force_break, bool *any_skipped) 1737 { 1738 struct mm_struct *mm = tlb->mm; 1739 bool delay_rmap = false; 1740 1741 if (!folio_test_anon(folio)) { 1742 ptent = get_and_clear_full_ptes(mm, addr, pte, nr, tlb->fullmm); 1743 if (pte_dirty(ptent)) { 1744 folio_mark_dirty(folio); 1745 if (tlb_delay_rmap(tlb)) { 1746 delay_rmap = true; 1747 *force_flush = true; 1748 } 1749 } 1750 if (pte_young(ptent) && likely(vma_has_recency(vma))) 1751 folio_mark_accessed(folio); 1752 rss[mm_counter(folio)] -= nr; 1753 } else { 1754 /* We don't need up-to-date accessed/dirty bits. */ 1755 clear_full_ptes(mm, addr, pte, nr, tlb->fullmm); 1756 rss[MM_ANONPAGES] -= nr; 1757 } 1758 /* Checking a single PTE in a batch is sufficient. */ 1759 arch_check_zapped_pte(vma, ptent); 1760 tlb_remove_tlb_entries(tlb, pte, nr, addr); 1761 if (unlikely(userfaultfd_pte_wp(vma, ptent))) 1762 *any_skipped = zap_install_uffd_wp_if_needed(vma, addr, pte, 1763 nr, details, ptent); 1764 1765 if (!delay_rmap) { 1766 folio_remove_rmap_ptes(folio, page, nr, vma); 1767 1768 if (unlikely(folio_mapcount(folio) < 0)) 1769 print_bad_pte(vma, addr, ptent, page); 1770 } 1771 if (unlikely(__tlb_remove_folio_pages(tlb, page, nr, delay_rmap))) { 1772 *force_flush = true; 1773 *force_break = true; 1774 } 1775 } 1776 1777 /* 1778 * Zap or skip at least one present PTE, trying to batch-process subsequent 1779 * PTEs that map consecutive pages of the same folio. 1780 * 1781 * Returns the number of processed (skipped or zapped) PTEs (at least 1). 1782 */ 1783 static inline int zap_present_ptes(struct mmu_gather *tlb, 1784 struct vm_area_struct *vma, pte_t *pte, pte_t ptent, 1785 unsigned int max_nr, unsigned long addr, 1786 struct zap_details *details, int *rss, bool *force_flush, 1787 bool *force_break, bool *any_skipped) 1788 { 1789 struct mm_struct *mm = tlb->mm; 1790 struct folio *folio; 1791 struct page *page; 1792 int nr; 1793 1794 page = vm_normal_page(vma, addr, ptent); 1795 if (!page) { 1796 /* We don't need up-to-date accessed/dirty bits. */ 1797 ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm); 1798 arch_check_zapped_pte(vma, ptent); 1799 tlb_remove_tlb_entry(tlb, pte, addr); 1800 if (userfaultfd_pte_wp(vma, ptent)) 1801 *any_skipped = zap_install_uffd_wp_if_needed(vma, addr, 1802 pte, 1, details, ptent); 1803 ksm_might_unmap_zero_page(mm, ptent); 1804 return 1; 1805 } 1806 1807 folio = page_folio(page); 1808 if (unlikely(!should_zap_folio(details, folio))) { 1809 *any_skipped = true; 1810 return 1; 1811 } 1812 1813 /* 1814 * Make sure that the common "small folio" case is as fast as possible 1815 * by keeping the batching logic separate. 1816 */ 1817 if (unlikely(folio_test_large(folio) && max_nr != 1)) { 1818 nr = folio_pte_batch(folio, pte, ptent, max_nr); 1819 zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, nr, 1820 addr, details, rss, force_flush, 1821 force_break, any_skipped); 1822 return nr; 1823 } 1824 zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, 1, addr, 1825 details, rss, force_flush, force_break, any_skipped); 1826 return 1; 1827 } 1828 1829 static inline int zap_nonpresent_ptes(struct mmu_gather *tlb, 1830 struct vm_area_struct *vma, pte_t *pte, pte_t ptent, 1831 unsigned int max_nr, unsigned long addr, 1832 struct zap_details *details, int *rss, bool *any_skipped) 1833 { 1834 softleaf_t entry; 1835 int nr = 1; 1836 1837 *any_skipped = true; 1838 entry = softleaf_from_pte(ptent); 1839 if (softleaf_is_device_private(entry) || 1840 softleaf_is_device_exclusive(entry)) { 1841 struct page *page = softleaf_to_page(entry); 1842 struct folio *folio = page_folio(page); 1843 1844 if (unlikely(!should_zap_folio(details, folio))) 1845 return 1; 1846 /* 1847 * Both device private/exclusive mappings should only 1848 * work with anonymous page so far, so we don't need to 1849 * consider uffd-wp bit when zap. For more information, 1850 * see zap_install_uffd_wp_if_needed(). 1851 */ 1852 WARN_ON_ONCE(!folio_test_anon(folio)); 1853 rss[mm_counter(folio)]--; 1854 folio_remove_rmap_pte(folio, page, vma); 1855 folio_put(folio); 1856 } else if (softleaf_is_swap(entry)) { 1857 /* Genuine swap entries, hence a private anon pages */ 1858 if (!should_zap_cows(details)) 1859 return 1; 1860 1861 nr = swap_pte_batch(pte, max_nr, ptent); 1862 rss[MM_SWAPENTS] -= nr; 1863 swap_put_entries_direct(entry, nr); 1864 } else if (softleaf_is_migration(entry)) { 1865 struct folio *folio = softleaf_to_folio(entry); 1866 1867 if (!should_zap_folio(details, folio)) 1868 return 1; 1869 rss[mm_counter(folio)]--; 1870 } else if (softleaf_is_uffd_wp_marker(entry)) { 1871 /* 1872 * For anon: always drop the marker; for file: only 1873 * drop the marker if explicitly requested. 1874 */ 1875 if (!vma_is_anonymous(vma) && !zap_drop_markers(details)) 1876 return 1; 1877 } else if (softleaf_is_guard_marker(entry)) { 1878 /* 1879 * Ordinary zapping should not remove guard PTE 1880 * markers. Only do so if we should remove PTE markers 1881 * in general. 1882 */ 1883 if (!zap_drop_markers(details)) 1884 return 1; 1885 } else if (softleaf_is_hwpoison(entry) || 1886 softleaf_is_poison_marker(entry)) { 1887 if (!should_zap_cows(details)) 1888 return 1; 1889 } else { 1890 /* We should have covered all the swap entry types */ 1891 pr_alert("unrecognized swap entry 0x%lx\n", entry.val); 1892 WARN_ON_ONCE(1); 1893 } 1894 clear_nonpresent_ptes(vma->vm_mm, addr, pte, nr); 1895 *any_skipped = zap_install_uffd_wp_if_needed(vma, addr, pte, nr, details, ptent); 1896 1897 return nr; 1898 } 1899 1900 static inline int do_zap_pte_range(struct mmu_gather *tlb, 1901 struct vm_area_struct *vma, pte_t *pte, 1902 unsigned long addr, unsigned long end, 1903 struct zap_details *details, int *rss, 1904 bool *force_flush, bool *force_break, 1905 bool *any_skipped) 1906 { 1907 pte_t ptent = ptep_get(pte); 1908 int max_nr = (end - addr) / PAGE_SIZE; 1909 int nr = 0; 1910 1911 /* Skip all consecutive none ptes */ 1912 if (pte_none(ptent)) { 1913 for (nr = 1; nr < max_nr; nr++) { 1914 ptent = ptep_get(pte + nr); 1915 if (!pte_none(ptent)) 1916 break; 1917 } 1918 max_nr -= nr; 1919 if (!max_nr) 1920 return nr; 1921 pte += nr; 1922 addr += nr * PAGE_SIZE; 1923 } 1924 1925 if (pte_present(ptent)) 1926 nr += zap_present_ptes(tlb, vma, pte, ptent, max_nr, addr, 1927 details, rss, force_flush, force_break, 1928 any_skipped); 1929 else 1930 nr += zap_nonpresent_ptes(tlb, vma, pte, ptent, max_nr, addr, 1931 details, rss, any_skipped); 1932 1933 return nr; 1934 } 1935 1936 static bool pte_table_reclaim_possible(unsigned long start, unsigned long end, 1937 struct zap_details *details) 1938 { 1939 if (!IS_ENABLED(CONFIG_PT_RECLAIM)) 1940 return false; 1941 /* Only zap if we are allowed to and cover the full page table. */ 1942 return details && details->reclaim_pt && (end - start >= PMD_SIZE); 1943 } 1944 1945 static bool zap_empty_pte_table(struct mm_struct *mm, pmd_t *pmd, 1946 spinlock_t *ptl, pmd_t *pmdval) 1947 { 1948 spinlock_t *pml = pmd_lockptr(mm, pmd); 1949 1950 if (ptl != pml && !spin_trylock(pml)) 1951 return false; 1952 1953 *pmdval = pmdp_get(pmd); 1954 pmd_clear(pmd); 1955 if (ptl != pml) 1956 spin_unlock(pml); 1957 return true; 1958 } 1959 1960 static bool zap_pte_table_if_empty(struct mm_struct *mm, pmd_t *pmd, 1961 unsigned long addr, pmd_t *pmdval) 1962 { 1963 spinlock_t *pml, *ptl = NULL; 1964 pte_t *start_pte, *pte; 1965 int i; 1966 1967 pml = pmd_lock(mm, pmd); 1968 start_pte = pte_offset_map_rw_nolock(mm, pmd, addr, pmdval, &ptl); 1969 if (!start_pte) 1970 goto out_ptl; 1971 if (ptl != pml) 1972 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1973 1974 for (i = 0, pte = start_pte; i < PTRS_PER_PTE; i++, pte++) { 1975 if (!pte_none(ptep_get(pte))) 1976 goto out_ptl; 1977 } 1978 pte_unmap(start_pte); 1979 1980 pmd_clear(pmd); 1981 1982 if (ptl != pml) 1983 spin_unlock(ptl); 1984 spin_unlock(pml); 1985 return true; 1986 out_ptl: 1987 if (start_pte) 1988 pte_unmap_unlock(start_pte, ptl); 1989 if (ptl != pml) 1990 spin_unlock(pml); 1991 return false; 1992 } 1993 1994 static unsigned long zap_pte_range(struct mmu_gather *tlb, 1995 struct vm_area_struct *vma, pmd_t *pmd, 1996 unsigned long addr, unsigned long end, 1997 struct zap_details *details) 1998 { 1999 bool can_reclaim_pt = pte_table_reclaim_possible(addr, end, details); 2000 bool force_flush = false, force_break = false; 2001 struct mm_struct *mm = tlb->mm; 2002 int rss[NR_MM_COUNTERS]; 2003 spinlock_t *ptl; 2004 pte_t *start_pte; 2005 pte_t *pte; 2006 pmd_t pmdval; 2007 unsigned long start = addr; 2008 bool direct_reclaim = true; 2009 int nr; 2010 2011 retry: 2012 tlb_change_page_size(tlb, PAGE_SIZE); 2013 init_rss_vec(rss); 2014 start_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl); 2015 if (!pte) 2016 return addr; 2017 2018 flush_tlb_batched_pending(mm); 2019 lazy_mmu_mode_enable(); 2020 do { 2021 bool any_skipped = false; 2022 2023 if (need_resched()) { 2024 direct_reclaim = false; 2025 break; 2026 } 2027 2028 nr = do_zap_pte_range(tlb, vma, pte, addr, end, details, rss, 2029 &force_flush, &force_break, &any_skipped); 2030 if (any_skipped) 2031 can_reclaim_pt = false; 2032 if (unlikely(force_break)) { 2033 addr += nr * PAGE_SIZE; 2034 direct_reclaim = false; 2035 break; 2036 } 2037 } while (pte += nr, addr += PAGE_SIZE * nr, addr != end); 2038 2039 /* 2040 * Fast path: try to hold the pmd lock and unmap the PTE page. 2041 * 2042 * If the pte lock was released midway (retry case), or if the attempt 2043 * to hold the pmd lock failed, then we need to recheck all pte entries 2044 * to ensure they are still none, thereby preventing the pte entries 2045 * from being repopulated by another thread. 2046 */ 2047 if (can_reclaim_pt && direct_reclaim && addr == end) 2048 direct_reclaim = zap_empty_pte_table(mm, pmd, ptl, &pmdval); 2049 2050 add_mm_rss_vec(mm, rss); 2051 lazy_mmu_mode_disable(); 2052 2053 /* Do the actual TLB flush before dropping ptl */ 2054 if (force_flush) { 2055 tlb_flush_mmu_tlbonly(tlb); 2056 tlb_flush_rmaps(tlb, vma); 2057 } 2058 pte_unmap_unlock(start_pte, ptl); 2059 2060 /* 2061 * If we forced a TLB flush (either due to running out of 2062 * batch buffers or because we needed to flush dirty TLB 2063 * entries before releasing the ptl), free the batched 2064 * memory too. Come back again if we didn't do everything. 2065 */ 2066 if (force_flush) 2067 tlb_flush_mmu(tlb); 2068 2069 if (addr != end) { 2070 cond_resched(); 2071 force_flush = false; 2072 force_break = false; 2073 goto retry; 2074 } 2075 2076 if (can_reclaim_pt) { 2077 if (direct_reclaim || zap_pte_table_if_empty(mm, pmd, start, &pmdval)) { 2078 pte_free_tlb(tlb, pmd_pgtable(pmdval), start); 2079 mm_dec_nr_ptes(mm); 2080 } 2081 } 2082 2083 return addr; 2084 } 2085 2086 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, 2087 struct vm_area_struct *vma, pud_t *pud, 2088 unsigned long addr, unsigned long end, 2089 struct zap_details *details) 2090 { 2091 pmd_t *pmd; 2092 unsigned long next; 2093 2094 pmd = pmd_offset(pud, addr); 2095 do { 2096 next = pmd_addr_end(addr, end); 2097 if (pmd_is_huge(*pmd)) { 2098 if (next - addr != HPAGE_PMD_SIZE) 2099 __split_huge_pmd(vma, pmd, addr, false); 2100 else if (zap_huge_pmd(tlb, vma, pmd, addr)) { 2101 addr = next; 2102 continue; 2103 } 2104 /* fall through */ 2105 } else if (details && details->single_folio && 2106 folio_test_pmd_mappable(details->single_folio) && 2107 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) { 2108 sync_with_folio_pmd_zap(tlb->mm, pmd); 2109 } 2110 if (pmd_none(*pmd)) { 2111 addr = next; 2112 continue; 2113 } 2114 addr = zap_pte_range(tlb, vma, pmd, addr, next, details); 2115 if (addr != next) 2116 pmd--; 2117 } while (pmd++, cond_resched(), addr != end); 2118 2119 return addr; 2120 } 2121 2122 static inline unsigned long zap_pud_range(struct mmu_gather *tlb, 2123 struct vm_area_struct *vma, p4d_t *p4d, 2124 unsigned long addr, unsigned long end, 2125 struct zap_details *details) 2126 { 2127 pud_t *pud; 2128 unsigned long next; 2129 2130 pud = pud_offset(p4d, addr); 2131 do { 2132 next = pud_addr_end(addr, end); 2133 if (pud_trans_huge(*pud)) { 2134 if (next - addr != HPAGE_PUD_SIZE) 2135 split_huge_pud(vma, pud, addr); 2136 else if (zap_huge_pud(tlb, vma, pud, addr)) 2137 goto next; 2138 /* fall through */ 2139 } 2140 if (pud_none_or_clear_bad(pud)) 2141 continue; 2142 next = zap_pmd_range(tlb, vma, pud, addr, next, details); 2143 next: 2144 cond_resched(); 2145 } while (pud++, addr = next, addr != end); 2146 2147 return addr; 2148 } 2149 2150 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb, 2151 struct vm_area_struct *vma, pgd_t *pgd, 2152 unsigned long addr, unsigned long end, 2153 struct zap_details *details) 2154 { 2155 p4d_t *p4d; 2156 unsigned long next; 2157 2158 p4d = p4d_offset(pgd, addr); 2159 do { 2160 next = p4d_addr_end(addr, end); 2161 if (p4d_none_or_clear_bad(p4d)) 2162 continue; 2163 next = zap_pud_range(tlb, vma, p4d, addr, next, details); 2164 } while (p4d++, addr = next, addr != end); 2165 2166 return addr; 2167 } 2168 2169 static void __zap_vma_range(struct mmu_gather *tlb, struct vm_area_struct *vma, 2170 unsigned long start, unsigned long end, 2171 struct zap_details *details) 2172 { 2173 const bool reaping = details && details->reaping; 2174 2175 VM_WARN_ON_ONCE(start >= end || !range_in_vma(vma, start, end)); 2176 2177 /* uprobe_munmap() might sleep, so skip it when reaping. */ 2178 if (vma->vm_file && !reaping) 2179 uprobe_munmap(vma, start, end); 2180 2181 if (unlikely(is_vm_hugetlb_page(vma))) { 2182 zap_flags_t zap_flags = details ? details->zap_flags : 0; 2183 2184 VM_WARN_ON_ONCE(reaping); 2185 /* 2186 * vm_file will be NULL when we fail early while instantiating 2187 * a new mapping. In this case, no pages were mapped yet and 2188 * there is nothing to do. 2189 */ 2190 if (!vma->vm_file) 2191 return; 2192 __unmap_hugepage_range(tlb, vma, start, end, NULL, zap_flags); 2193 } else { 2194 unsigned long next, addr = start; 2195 pgd_t *pgd; 2196 2197 tlb_start_vma(tlb, vma); 2198 pgd = pgd_offset(vma->vm_mm, addr); 2199 do { 2200 next = pgd_addr_end(addr, end); 2201 if (pgd_none_or_clear_bad(pgd)) 2202 continue; 2203 next = zap_p4d_range(tlb, vma, pgd, addr, next, details); 2204 } while (pgd++, addr = next, addr != end); 2205 tlb_end_vma(tlb, vma); 2206 } 2207 } 2208 2209 /** 2210 * zap_vma_for_reaping - zap all page table entries in the vma without blocking 2211 * @vma: The vma to zap. 2212 * 2213 * Zap all page table entries in the vma without blocking for use by the oom 2214 * killer. Hugetlb vmas are not supported. 2215 * 2216 * Returns: 0 on success, -EBUSY if we would have to block. 2217 */ 2218 int zap_vma_for_reaping(struct vm_area_struct *vma) 2219 { 2220 struct zap_details details = { 2221 .reaping = true, 2222 }; 2223 struct mmu_notifier_range range; 2224 struct mmu_gather tlb; 2225 2226 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 2227 vma->vm_start, vma->vm_end); 2228 tlb_gather_mmu(&tlb, vma->vm_mm); 2229 if (mmu_notifier_invalidate_range_start_nonblock(&range)) { 2230 tlb_finish_mmu(&tlb); 2231 return -EBUSY; 2232 } 2233 __zap_vma_range(&tlb, vma, range.start, range.end, &details); 2234 mmu_notifier_invalidate_range_end(&range); 2235 tlb_finish_mmu(&tlb); 2236 return 0; 2237 } 2238 2239 /** 2240 * unmap_vmas - unmap a range of memory covered by a list of vma's 2241 * @tlb: address of the caller's struct mmu_gather 2242 * @unmap: The unmap_desc 2243 * 2244 * Unmap all pages in the vma list. 2245 * 2246 * Only addresses between `start' and `end' will be unmapped. 2247 * 2248 * The VMA list must be sorted in ascending virtual address order. 2249 * 2250 * unmap_vmas() assumes that the caller will flush the whole unmapped address 2251 * range after unmap_vmas() returns. So the only responsibility here is to 2252 * ensure that any thus-far unmapped pages are flushed before unmap_vmas() 2253 * drops the lock and schedules. 2254 */ 2255 void unmap_vmas(struct mmu_gather *tlb, struct unmap_desc *unmap) 2256 { 2257 struct vm_area_struct *vma; 2258 struct mmu_notifier_range range; 2259 struct zap_details details = { 2260 .zap_flags = ZAP_FLAG_DROP_MARKER | ZAP_FLAG_UNMAP, 2261 }; 2262 2263 vma = unmap->first; 2264 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma->vm_mm, 2265 unmap->vma_start, unmap->vma_end); 2266 mmu_notifier_invalidate_range_start(&range); 2267 do { 2268 unsigned long start = max(vma->vm_start, unmap->vma_start); 2269 unsigned long end = min(vma->vm_end, unmap->vma_end); 2270 2271 hugetlb_zap_begin(vma, &start, &end); 2272 __zap_vma_range(tlb, vma, start, end, &details); 2273 hugetlb_zap_end(vma, &details); 2274 vma = mas_find(unmap->mas, unmap->tree_end - 1); 2275 } while (vma); 2276 mmu_notifier_invalidate_range_end(&range); 2277 } 2278 2279 /** 2280 * zap_vma_range_batched - zap page table entries in a vma range 2281 * @tlb: pointer to the caller's struct mmu_gather 2282 * @vma: the vma covering the range to zap 2283 * @address: starting address of the range to zap 2284 * @size: number of bytes to zap 2285 * @details: details specifying zapping behavior 2286 * 2287 * @tlb must not be NULL. The provided address range must be fully 2288 * contained within @vma. If @vma is for hugetlb, @tlb is flushed and 2289 * re-initialized by this function. 2290 * 2291 * If @details is NULL, this function will zap all page table entries. 2292 */ 2293 void zap_vma_range_batched(struct mmu_gather *tlb, 2294 struct vm_area_struct *vma, unsigned long address, 2295 unsigned long size, struct zap_details *details) 2296 { 2297 const unsigned long end = address + size; 2298 struct mmu_notifier_range range; 2299 2300 VM_WARN_ON_ONCE(!tlb || tlb->mm != vma->vm_mm); 2301 2302 if (unlikely(!size)) 2303 return; 2304 2305 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 2306 address, end); 2307 hugetlb_zap_begin(vma, &range.start, &range.end); 2308 update_hiwater_rss(vma->vm_mm); 2309 mmu_notifier_invalidate_range_start(&range); 2310 /* 2311 * unmap 'address-end' not 'range.start-range.end' as range 2312 * could have been expanded for hugetlb pmd sharing. 2313 */ 2314 __zap_vma_range(tlb, vma, address, end, details); 2315 mmu_notifier_invalidate_range_end(&range); 2316 if (is_vm_hugetlb_page(vma)) { 2317 /* 2318 * flush tlb and free resources before hugetlb_zap_end(), to 2319 * avoid concurrent page faults' allocation failure. 2320 */ 2321 tlb_finish_mmu(tlb); 2322 hugetlb_zap_end(vma, details); 2323 tlb_gather_mmu(tlb, vma->vm_mm); 2324 } 2325 } 2326 2327 /** 2328 * zap_vma_range - zap all page table entries in a vma range 2329 * @vma: the vma covering the range to zap 2330 * @address: starting address of the range to zap 2331 * @size: number of bytes to zap 2332 * 2333 * The provided address range must be fully contained within @vma. 2334 */ 2335 void zap_vma_range(struct vm_area_struct *vma, unsigned long address, 2336 unsigned long size) 2337 { 2338 struct mmu_gather tlb; 2339 2340 tlb_gather_mmu(&tlb, vma->vm_mm); 2341 zap_vma_range_batched(&tlb, vma, address, size, NULL); 2342 tlb_finish_mmu(&tlb); 2343 } 2344 2345 /** 2346 * zap_special_vma_range - zap all page table entries in a special vma range 2347 * @vma: the vma covering the range to zap 2348 * @address: starting address of the range to zap 2349 * @size: number of bytes to zap 2350 * 2351 * This function does nothing when the provided address range is not fully 2352 * contained in @vma, or when the @vma is not VM_PFNMAP or VM_MIXEDMAP. 2353 */ 2354 void zap_special_vma_range(struct vm_area_struct *vma, unsigned long address, 2355 unsigned long size) 2356 { 2357 if (!range_in_vma(vma, address, address + size) || 2358 !(vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))) 2359 return; 2360 2361 zap_vma_range(vma, address, size); 2362 } 2363 EXPORT_SYMBOL_GPL(zap_special_vma_range); 2364 2365 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr) 2366 { 2367 pgd_t *pgd; 2368 p4d_t *p4d; 2369 pud_t *pud; 2370 pmd_t *pmd; 2371 2372 pgd = pgd_offset(mm, addr); 2373 p4d = p4d_alloc(mm, pgd, addr); 2374 if (!p4d) 2375 return NULL; 2376 pud = pud_alloc(mm, p4d, addr); 2377 if (!pud) 2378 return NULL; 2379 pmd = pmd_alloc(mm, pud, addr); 2380 if (!pmd) 2381 return NULL; 2382 2383 VM_BUG_ON(pmd_trans_huge(*pmd)); 2384 return pmd; 2385 } 2386 2387 pte_t *get_locked_pte(struct mm_struct *mm, unsigned long addr, 2388 spinlock_t **ptl) 2389 { 2390 pmd_t *pmd = walk_to_pmd(mm, addr); 2391 2392 if (!pmd) 2393 return NULL; 2394 return pte_alloc_map_lock(mm, pmd, addr, ptl); 2395 } 2396 2397 static bool vm_mixed_zeropage_allowed(struct vm_area_struct *vma) 2398 { 2399 VM_WARN_ON_ONCE(vma->vm_flags & VM_PFNMAP); 2400 /* 2401 * Whoever wants to forbid the zeropage after some zeropages 2402 * might already have been mapped has to scan the page tables and 2403 * bail out on any zeropages. Zeropages in COW mappings can 2404 * be unshared using FAULT_FLAG_UNSHARE faults. 2405 */ 2406 if (mm_forbids_zeropage(vma->vm_mm)) 2407 return false; 2408 /* zeropages in COW mappings are common and unproblematic. */ 2409 if (vma_is_cow_mapping(vma)) 2410 return true; 2411 /* Mappings that do not allow for writable PTEs are unproblematic. */ 2412 if (!(vma->vm_flags & (VM_WRITE | VM_MAYWRITE))) 2413 return true; 2414 /* 2415 * Why not allow any VMA that has vm_ops->pfn_mkwrite? GUP could 2416 * find the shared zeropage and longterm-pin it, which would 2417 * be problematic as soon as the zeropage gets replaced by a different 2418 * page due to vma->vm_ops->pfn_mkwrite, because what's mapped would 2419 * now differ to what GUP looked up. FSDAX is incompatible to 2420 * FOLL_LONGTERM and VM_IO is incompatible to GUP completely (see 2421 * check_vma_flags). 2422 */ 2423 return vma->vm_ops && vma->vm_ops->pfn_mkwrite && 2424 (vma_is_fsdax(vma) || vma->vm_flags & VM_IO); 2425 } 2426 2427 static int validate_page_before_insert(struct vm_area_struct *vma, 2428 struct page *page) 2429 { 2430 struct folio *folio = page_folio(page); 2431 2432 if (!folio_ref_count(folio)) 2433 return -EINVAL; 2434 if (unlikely(is_zero_folio(folio))) { 2435 if (!vm_mixed_zeropage_allowed(vma)) 2436 return -EINVAL; 2437 return 0; 2438 } 2439 if (folio_test_anon(folio) || page_has_type(page)) 2440 return -EINVAL; 2441 flush_dcache_folio(folio); 2442 return 0; 2443 } 2444 2445 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte, 2446 unsigned long addr, struct page *page, 2447 pgprot_t prot, bool mkwrite) 2448 { 2449 struct folio *folio = page_folio(page); 2450 pte_t pteval = ptep_get(pte); 2451 2452 if (!pte_none(pteval)) { 2453 if (!mkwrite) 2454 return -EBUSY; 2455 2456 /* see insert_pfn(). */ 2457 if (pte_pfn(pteval) != page_to_pfn(page)) { 2458 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(pteval))); 2459 return -EFAULT; 2460 } 2461 pteval = maybe_mkwrite(pteval, vma); 2462 pteval = pte_mkyoung(pteval); 2463 if (ptep_set_access_flags(vma, addr, pte, pteval, 1)) 2464 update_mmu_cache(vma, addr, pte); 2465 return 0; 2466 } 2467 2468 /* Ok, finally just insert the thing.. */ 2469 pteval = mk_pte(page, prot); 2470 if (unlikely(is_zero_folio(folio))) { 2471 pteval = pte_mkspecial(pteval); 2472 } else { 2473 folio_get(folio); 2474 pteval = mk_pte(page, prot); 2475 if (mkwrite) { 2476 pteval = pte_mkyoung(pteval); 2477 pteval = maybe_mkwrite(pte_mkdirty(pteval), vma); 2478 } 2479 inc_mm_counter(vma->vm_mm, mm_counter_file(folio)); 2480 folio_add_file_rmap_pte(folio, page, vma); 2481 } 2482 set_pte_at(vma->vm_mm, addr, pte, pteval); 2483 return 0; 2484 } 2485 2486 static int insert_page(struct vm_area_struct *vma, unsigned long addr, 2487 struct page *page, pgprot_t prot, bool mkwrite) 2488 { 2489 int retval; 2490 pte_t *pte; 2491 spinlock_t *ptl; 2492 2493 retval = validate_page_before_insert(vma, page); 2494 if (retval) 2495 goto out; 2496 retval = -ENOMEM; 2497 pte = get_locked_pte(vma->vm_mm, addr, &ptl); 2498 if (!pte) 2499 goto out; 2500 retval = insert_page_into_pte_locked(vma, pte, addr, page, prot, 2501 mkwrite); 2502 pte_unmap_unlock(pte, ptl); 2503 out: 2504 return retval; 2505 } 2506 2507 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte, 2508 unsigned long addr, struct page *page, pgprot_t prot) 2509 { 2510 int err; 2511 2512 err = validate_page_before_insert(vma, page); 2513 if (err) 2514 return err; 2515 return insert_page_into_pte_locked(vma, pte, addr, page, prot, false); 2516 } 2517 2518 /* insert_pages() amortizes the cost of spinlock operations 2519 * when inserting pages in a loop. 2520 */ 2521 static int insert_pages(struct vm_area_struct *vma, unsigned long addr, 2522 struct page **pages, unsigned long *num, pgprot_t prot) 2523 { 2524 pmd_t *pmd = NULL; 2525 pte_t *start_pte, *pte; 2526 spinlock_t *pte_lock; 2527 struct mm_struct *const mm = vma->vm_mm; 2528 unsigned long curr_page_idx = 0; 2529 unsigned long remaining_pages_total = *num; 2530 unsigned long pages_to_write_in_pmd; 2531 int err = 0; 2532 more: 2533 pmd = walk_to_pmd(mm, addr); 2534 if (!pmd) { 2535 err = -ENOMEM; 2536 goto out; 2537 } 2538 2539 pages_to_write_in_pmd = min_t(unsigned long, 2540 remaining_pages_total, PTRS_PER_PTE - pte_index(addr)); 2541 2542 /* Allocate the PTE if necessary; takes PMD lock once only. */ 2543 if (pte_alloc(mm, pmd)) { 2544 err = -ENOMEM; 2545 goto out; 2546 } 2547 2548 while (pages_to_write_in_pmd) { 2549 int pte_idx = 0; 2550 const int batch_size = min_t(int, pages_to_write_in_pmd, 8); 2551 2552 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock); 2553 if (!start_pte) { 2554 err = -EFAULT; 2555 goto out; 2556 } 2557 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) { 2558 err = insert_page_in_batch_locked(vma, pte, addr, 2559 pages[curr_page_idx], prot); 2560 if (unlikely(err)) { 2561 pte_unmap_unlock(start_pte, pte_lock); 2562 remaining_pages_total -= pte_idx; 2563 goto out; 2564 } 2565 addr += PAGE_SIZE; 2566 ++curr_page_idx; 2567 } 2568 pte_unmap_unlock(start_pte, pte_lock); 2569 pages_to_write_in_pmd -= batch_size; 2570 remaining_pages_total -= batch_size; 2571 } 2572 if (remaining_pages_total) 2573 goto more; 2574 out: 2575 *num = remaining_pages_total; 2576 return err; 2577 } 2578 2579 /** 2580 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock. 2581 * @vma: user vma to map to 2582 * @addr: target start user address of these pages 2583 * @pages: source kernel pages 2584 * @num: in: number of pages to map. out: number of pages that were *not* 2585 * mapped. (0 means all pages were successfully mapped). 2586 * 2587 * Preferred over vm_insert_page() when inserting multiple pages. 2588 * 2589 * In case of error, we may have mapped a subset of the provided 2590 * pages. It is the caller's responsibility to account for this case. 2591 * 2592 * The same restrictions apply as in vm_insert_page(). 2593 */ 2594 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr, 2595 struct page **pages, unsigned long *num) 2596 { 2597 const unsigned long nr_pages = *num; 2598 const unsigned long end = addr + PAGE_SIZE * nr_pages; 2599 2600 if (!range_in_vma(vma, addr, end)) 2601 return -EFAULT; 2602 if (!(vma->vm_flags & VM_MIXEDMAP)) { 2603 VM_WARN_ON_ONCE(mmap_read_trylock(vma->vm_mm)); 2604 VM_WARN_ON_ONCE(vma->vm_flags & VM_PFNMAP); 2605 vm_flags_set(vma, VM_MIXEDMAP); 2606 } 2607 /* Defer page refcount checking till we're about to map that page. */ 2608 return insert_pages(vma, addr, pages, num, vma->vm_page_prot); 2609 } 2610 EXPORT_SYMBOL(vm_insert_pages); 2611 2612 int map_kernel_pages_prepare(struct vm_area_desc *desc) 2613 { 2614 const struct mmap_action *action = &desc->action; 2615 const unsigned long addr = action->map_kernel.start; 2616 unsigned long nr_pages, end; 2617 2618 if (!vma_desc_test(desc, VMA_MIXEDMAP_BIT)) { 2619 VM_WARN_ON_ONCE(mmap_read_trylock(desc->mm)); 2620 VM_WARN_ON_ONCE(vma_desc_test(desc, VMA_PFNMAP_BIT)); 2621 vma_desc_set_flags(desc, VMA_MIXEDMAP_BIT); 2622 } 2623 2624 nr_pages = action->map_kernel.nr_pages; 2625 end = addr + PAGE_SIZE * nr_pages; 2626 if (!range_in_vma_desc(desc, addr, end)) 2627 return -EFAULT; 2628 2629 return 0; 2630 } 2631 EXPORT_SYMBOL(map_kernel_pages_prepare); 2632 2633 int map_kernel_pages_complete(struct vm_area_struct *vma, 2634 struct mmap_action *action) 2635 { 2636 unsigned long nr_pages; 2637 2638 nr_pages = action->map_kernel.nr_pages; 2639 return insert_pages(vma, action->map_kernel.start, 2640 action->map_kernel.pages, 2641 &nr_pages, vma->vm_page_prot); 2642 } 2643 EXPORT_SYMBOL(map_kernel_pages_complete); 2644 2645 /** 2646 * vm_insert_page - insert single page into user vma 2647 * @vma: user vma to map to 2648 * @addr: target user address of this page 2649 * @page: source kernel page 2650 * 2651 * This allows drivers to insert individual pages they've allocated 2652 * into a user vma. The zeropage is supported in some VMAs, 2653 * see vm_mixed_zeropage_allowed(). 2654 * 2655 * The page has to be a nice clean _individual_ kernel allocation. 2656 * If you allocate a compound page, you need to have marked it as 2657 * such (__GFP_COMP), or manually just split the page up yourself 2658 * (see split_page()). 2659 * 2660 * NOTE! Traditionally this was done with "remap_pfn_range()" which 2661 * took an arbitrary page protection parameter. This doesn't allow 2662 * that. Your vma protection will have to be set up correctly, which 2663 * means that if you want a shared writable mapping, you'd better 2664 * ask for a shared writable mapping! 2665 * 2666 * The page does not need to be reserved. 2667 * 2668 * Usually this function is called from f_op->mmap() handler 2669 * under mm->mmap_lock write-lock, so it can change vma->vm_flags. 2670 * Caller must set VM_MIXEDMAP on vma if it wants to call this 2671 * function from other places, for example from page-fault handler. 2672 * 2673 * Return: %0 on success, negative error code otherwise. 2674 */ 2675 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr, 2676 struct page *page) 2677 { 2678 if (addr < vma->vm_start || addr >= vma->vm_end) 2679 return -EFAULT; 2680 if (!(vma->vm_flags & VM_MIXEDMAP)) { 2681 BUG_ON(mmap_read_trylock(vma->vm_mm)); 2682 BUG_ON(vma->vm_flags & VM_PFNMAP); 2683 vm_flags_set(vma, VM_MIXEDMAP); 2684 } 2685 return insert_page(vma, addr, page, vma->vm_page_prot, false); 2686 } 2687 EXPORT_SYMBOL(vm_insert_page); 2688 2689 /* 2690 * __vm_map_pages - maps range of kernel pages into user vma 2691 * @vma: user vma to map to 2692 * @pages: pointer to array of source kernel pages 2693 * @num: number of pages in page array 2694 * @offset: user's requested vm_pgoff 2695 * 2696 * This allows drivers to map range of kernel pages into a user vma. 2697 * The zeropage is supported in some VMAs, see 2698 * vm_mixed_zeropage_allowed(). 2699 * 2700 * Return: 0 on success and error code otherwise. 2701 */ 2702 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages, 2703 unsigned long num, unsigned long offset) 2704 { 2705 unsigned long count = vma_pages(vma); 2706 unsigned long uaddr = vma->vm_start; 2707 2708 /* Fail if the user requested offset is beyond the end of the object */ 2709 if (offset >= num) 2710 return -ENXIO; 2711 2712 /* Fail if the user requested size exceeds available object size */ 2713 if (count > num - offset) 2714 return -ENXIO; 2715 2716 return vm_insert_pages(vma, uaddr, pages + offset, &count); 2717 } 2718 2719 /** 2720 * vm_map_pages - maps range of kernel pages starts with non zero offset 2721 * @vma: user vma to map to 2722 * @pages: pointer to array of source kernel pages 2723 * @num: number of pages in page array 2724 * 2725 * Maps an object consisting of @num pages, catering for the user's 2726 * requested vm_pgoff 2727 * 2728 * If we fail to insert any page into the vma, the function will return 2729 * immediately leaving any previously inserted pages present. Callers 2730 * from the mmap handler may immediately return the error as their caller 2731 * will destroy the vma, removing any successfully inserted pages. Other 2732 * callers should make their own arrangements for calling unmap_region(). 2733 * 2734 * Context: Process context. Called by mmap handlers. 2735 * Return: 0 on success and error code otherwise. 2736 */ 2737 int vm_map_pages(struct vm_area_struct *vma, struct page **pages, 2738 unsigned long num) 2739 { 2740 return __vm_map_pages(vma, pages, num, vma_start_pgoff(vma)); 2741 } 2742 EXPORT_SYMBOL(vm_map_pages); 2743 2744 /** 2745 * vm_map_pages_zero - map range of kernel pages starts with zero offset 2746 * @vma: user vma to map to 2747 * @pages: pointer to array of source kernel pages 2748 * @num: number of pages in page array 2749 * 2750 * Similar to vm_map_pages(), except that it explicitly sets the offset 2751 * to 0. This function is intended for the drivers that did not consider 2752 * vm_pgoff. 2753 * 2754 * Context: Process context. Called by mmap handlers. 2755 * Return: 0 on success and error code otherwise. 2756 */ 2757 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages, 2758 unsigned long num) 2759 { 2760 return __vm_map_pages(vma, pages, num, 0); 2761 } 2762 EXPORT_SYMBOL(vm_map_pages_zero); 2763 2764 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr, 2765 unsigned long pfn, pgprot_t prot, bool mkwrite) 2766 { 2767 struct mm_struct *mm = vma->vm_mm; 2768 pte_t *pte, entry; 2769 spinlock_t *ptl; 2770 2771 pte = get_locked_pte(mm, addr, &ptl); 2772 if (!pte) 2773 return VM_FAULT_OOM; 2774 entry = ptep_get(pte); 2775 if (!pte_none(entry)) { 2776 if (mkwrite) { 2777 /* 2778 * For read faults on private mappings the PFN passed 2779 * in may not match the PFN we have mapped if the 2780 * mapped PFN is a writeable COW page. In the mkwrite 2781 * case we are creating a writable PTE for a shared 2782 * mapping and we expect the PFNs to match. If they 2783 * don't match, we are likely racing with block 2784 * allocation and mapping invalidation so just skip the 2785 * update. 2786 */ 2787 if (pte_pfn(entry) != pfn) { 2788 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(entry))); 2789 goto out_unlock; 2790 } 2791 entry = pte_mkyoung(entry); 2792 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 2793 if (ptep_set_access_flags(vma, addr, pte, entry, 1)) 2794 update_mmu_cache(vma, addr, pte); 2795 } 2796 goto out_unlock; 2797 } 2798 2799 /* Ok, finally just insert the thing.. */ 2800 entry = pte_mkspecial(pfn_pte(pfn, prot)); 2801 2802 if (mkwrite) { 2803 entry = pte_mkyoung(entry); 2804 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 2805 } 2806 2807 set_pte_at(mm, addr, pte, entry); 2808 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */ 2809 2810 out_unlock: 2811 pte_unmap_unlock(pte, ptl); 2812 return VM_FAULT_NOPAGE; 2813 } 2814 2815 /** 2816 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot 2817 * @vma: user vma to map to 2818 * @addr: target user address of this page 2819 * @pfn: source kernel pfn 2820 * @pgprot: pgprot flags for the inserted page 2821 * 2822 * This is exactly like vmf_insert_pfn(), except that it allows drivers 2823 * to override pgprot on a per-page basis. 2824 * 2825 * This only makes sense for IO mappings, and it makes no sense for 2826 * COW mappings. In general, using multiple vmas is preferable; 2827 * vmf_insert_pfn_prot should only be used if using multiple VMAs is 2828 * impractical. 2829 * 2830 * pgprot typically only differs from @vma->vm_page_prot when drivers set 2831 * caching- and encryption bits different than those of @vma->vm_page_prot, 2832 * because the caching- or encryption mode may not be known at mmap() time. 2833 * 2834 * This is ok as long as @vma->vm_page_prot is not used by the core vm 2835 * to set caching and encryption bits for those vmas (except for COW pages). 2836 * This is ensured by core vm only modifying these page table entries using 2837 * functions that don't touch caching- or encryption bits, using pte_modify() 2838 * if needed. (See for example mprotect()). 2839 * 2840 * Also when new page-table entries are created, this is only done using the 2841 * fault() callback, and never using the value of vma->vm_page_prot, 2842 * except for page-table entries that point to anonymous pages as the result 2843 * of COW. 2844 * 2845 * Context: Process context. May allocate using %GFP_KERNEL. 2846 * Return: vm_fault_t value. 2847 */ 2848 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr, 2849 unsigned long pfn, pgprot_t pgprot) 2850 { 2851 /* 2852 * Technically, architectures with pte_special can avoid all these 2853 * restrictions (same for remap_pfn_range). However we would like 2854 * consistency in testing and feature parity among all, so we should 2855 * try to keep these invariants in place for everybody. 2856 */ 2857 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); 2858 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == 2859 (VM_PFNMAP|VM_MIXEDMAP)); 2860 BUG_ON((vma->vm_flags & VM_PFNMAP) && vma_is_cow_mapping(vma)); 2861 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn)); 2862 2863 if (unlikely(is_zero_pfn(pfn))) 2864 return VM_FAULT_SIGBUS; 2865 2866 if (addr < vma->vm_start || addr >= vma->vm_end) 2867 return VM_FAULT_SIGBUS; 2868 2869 if (!pfn_modify_allowed(pfn, pgprot)) 2870 return VM_FAULT_SIGBUS; 2871 2872 pfnmap_setup_cachemode_pfn(pfn, &pgprot); 2873 2874 return insert_pfn(vma, addr, pfn, pgprot, false); 2875 } 2876 EXPORT_SYMBOL(vmf_insert_pfn_prot); 2877 2878 /** 2879 * vmf_insert_pfn - insert single pfn into user vma 2880 * @vma: user vma to map to 2881 * @addr: target user address of this page 2882 * @pfn: source kernel pfn 2883 * 2884 * Similar to vm_insert_page, this allows drivers to insert individual pages 2885 * they've allocated into a user vma. Same comments apply. 2886 * 2887 * This function should only be called from a vm_ops->fault handler, and 2888 * in that case the handler should return the result of this function. 2889 * 2890 * vma cannot be a COW mapping. 2891 * 2892 * As this is called only for pages that do not currently exist, we 2893 * do not need to flush old virtual caches or the TLB. 2894 * 2895 * Context: Process context. May allocate using %GFP_KERNEL. 2896 * Return: vm_fault_t value. 2897 */ 2898 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr, 2899 unsigned long pfn) 2900 { 2901 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot); 2902 } 2903 EXPORT_SYMBOL(vmf_insert_pfn); 2904 2905 static bool vm_mixed_ok(struct vm_area_struct *vma, unsigned long pfn, 2906 bool mkwrite) 2907 { 2908 if (unlikely(is_zero_pfn(pfn)) && 2909 (mkwrite || !vm_mixed_zeropage_allowed(vma))) 2910 return false; 2911 /* these checks mirror the abort conditions in vm_normal_page */ 2912 if (vma->vm_flags & VM_MIXEDMAP) 2913 return true; 2914 if (is_zero_pfn(pfn)) 2915 return true; 2916 return false; 2917 } 2918 2919 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma, 2920 unsigned long addr, unsigned long pfn, bool mkwrite) 2921 { 2922 pgprot_t pgprot = vma->vm_page_prot; 2923 int err; 2924 2925 if (!vm_mixed_ok(vma, pfn, mkwrite)) 2926 return VM_FAULT_SIGBUS; 2927 2928 if (addr < vma->vm_start || addr >= vma->vm_end) 2929 return VM_FAULT_SIGBUS; 2930 2931 pfnmap_setup_cachemode_pfn(pfn, &pgprot); 2932 2933 if (!pfn_modify_allowed(pfn, pgprot)) 2934 return VM_FAULT_SIGBUS; 2935 2936 /* 2937 * If we don't have pte special, then we have to use the pfn_valid() 2938 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must* 2939 * refcount the page if pfn_valid is true (hence insert_page rather 2940 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP 2941 * without pte special, it would there be refcounted as a normal page. 2942 */ 2943 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) && pfn_valid(pfn)) { 2944 struct page *page; 2945 2946 /* 2947 * At this point we are committed to insert_page() 2948 * regardless of whether the caller specified flags that 2949 * result in pfn_t_has_page() == false. 2950 */ 2951 page = pfn_to_page(pfn); 2952 err = insert_page(vma, addr, page, pgprot, mkwrite); 2953 } else { 2954 return insert_pfn(vma, addr, pfn, pgprot, mkwrite); 2955 } 2956 2957 if (err == -ENOMEM) 2958 return VM_FAULT_OOM; 2959 if (err < 0 && err != -EBUSY) 2960 return VM_FAULT_SIGBUS; 2961 2962 return VM_FAULT_NOPAGE; 2963 } 2964 2965 vm_fault_t vmf_insert_page_mkwrite(struct vm_fault *vmf, struct page *page, 2966 bool write) 2967 { 2968 pgprot_t pgprot = vmf->vma->vm_page_prot; 2969 unsigned long addr = vmf->address; 2970 int err; 2971 2972 if (addr < vmf->vma->vm_start || addr >= vmf->vma->vm_end) 2973 return VM_FAULT_SIGBUS; 2974 2975 err = insert_page(vmf->vma, addr, page, pgprot, write); 2976 if (err == -ENOMEM) 2977 return VM_FAULT_OOM; 2978 if (err < 0 && err != -EBUSY) 2979 return VM_FAULT_SIGBUS; 2980 2981 return VM_FAULT_NOPAGE; 2982 } 2983 EXPORT_SYMBOL_GPL(vmf_insert_page_mkwrite); 2984 2985 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr, 2986 unsigned long pfn) 2987 { 2988 return __vm_insert_mixed(vma, addr, pfn, false); 2989 } 2990 EXPORT_SYMBOL(vmf_insert_mixed); 2991 2992 /* 2993 * If the insertion of PTE failed because someone else already added a 2994 * different entry in the mean time, we treat that as success as we assume 2995 * the same entry was actually inserted. 2996 */ 2997 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma, 2998 unsigned long addr, unsigned long pfn) 2999 { 3000 return __vm_insert_mixed(vma, addr, pfn, true); 3001 } 3002 3003 /* 3004 * maps a range of physical memory into the requested pages. the old 3005 * mappings are removed. any references to nonexistent pages results 3006 * in null mappings (currently treated as "copy-on-access") 3007 */ 3008 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd, 3009 unsigned long addr, unsigned long end, 3010 unsigned long pfn, pgprot_t prot) 3011 { 3012 pte_t *pte, *mapped_pte; 3013 spinlock_t *ptl; 3014 int err = 0; 3015 3016 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl); 3017 if (!pte) 3018 return -ENOMEM; 3019 lazy_mmu_mode_enable(); 3020 do { 3021 BUG_ON(!pte_none(ptep_get(pte))); 3022 if (!pfn_modify_allowed(pfn, prot)) { 3023 err = -EACCES; 3024 break; 3025 } 3026 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot))); 3027 pfn++; 3028 } while (pte++, addr += PAGE_SIZE, addr != end); 3029 lazy_mmu_mode_disable(); 3030 pte_unmap_unlock(mapped_pte, ptl); 3031 return err; 3032 } 3033 3034 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud, 3035 unsigned long addr, unsigned long end, 3036 unsigned long pfn, pgprot_t prot) 3037 { 3038 pmd_t *pmd; 3039 unsigned long next; 3040 int err; 3041 3042 pfn -= addr >> PAGE_SHIFT; 3043 pmd = pmd_alloc(mm, pud, addr); 3044 if (!pmd) 3045 return -ENOMEM; 3046 VM_BUG_ON(pmd_trans_huge(*pmd)); 3047 do { 3048 next = pmd_addr_end(addr, end); 3049 err = remap_pte_range(mm, pmd, addr, next, 3050 pfn + (addr >> PAGE_SHIFT), prot); 3051 if (err) 3052 return err; 3053 } while (pmd++, addr = next, addr != end); 3054 return 0; 3055 } 3056 3057 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d, 3058 unsigned long addr, unsigned long end, 3059 unsigned long pfn, pgprot_t prot) 3060 { 3061 pud_t *pud; 3062 unsigned long next; 3063 int err; 3064 3065 pfn -= addr >> PAGE_SHIFT; 3066 pud = pud_alloc(mm, p4d, addr); 3067 if (!pud) 3068 return -ENOMEM; 3069 do { 3070 next = pud_addr_end(addr, end); 3071 err = remap_pmd_range(mm, pud, addr, next, 3072 pfn + (addr >> PAGE_SHIFT), prot); 3073 if (err) 3074 return err; 3075 } while (pud++, addr = next, addr != end); 3076 return 0; 3077 } 3078 3079 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd, 3080 unsigned long addr, unsigned long end, 3081 unsigned long pfn, pgprot_t prot) 3082 { 3083 p4d_t *p4d; 3084 unsigned long next; 3085 int err; 3086 3087 pfn -= addr >> PAGE_SHIFT; 3088 p4d = p4d_alloc(mm, pgd, addr); 3089 if (!p4d) 3090 return -ENOMEM; 3091 do { 3092 next = p4d_addr_end(addr, end); 3093 err = remap_pud_range(mm, p4d, addr, next, 3094 pfn + (addr >> PAGE_SHIFT), prot); 3095 if (err) 3096 return err; 3097 } while (p4d++, addr = next, addr != end); 3098 return 0; 3099 } 3100 3101 static int get_remap_pgoff(bool is_cow, unsigned long addr, 3102 unsigned long end, unsigned long vm_start, unsigned long vm_end, 3103 unsigned long pfn, pgoff_t *vm_pgoff_p) 3104 { 3105 /* 3106 * There's a horrible special case to handle copy-on-write 3107 * behaviour that some programs depend on. We mark the "original" 3108 * un-COW'ed pages by matching them up with "vma->vm_pgoff". 3109 * See vm_normal_page() for details. 3110 */ 3111 if (is_cow) { 3112 if (addr != vm_start || end != vm_end) 3113 return -EINVAL; 3114 *vm_pgoff_p = pfn; 3115 } 3116 3117 return 0; 3118 } 3119 3120 static int remap_pfn_range_internal(struct vm_area_struct *vma, unsigned long addr, 3121 unsigned long pfn, unsigned long size, pgprot_t prot) 3122 { 3123 pgd_t *pgd; 3124 unsigned long next; 3125 unsigned long end = addr + PAGE_ALIGN(size); 3126 struct mm_struct *mm = vma->vm_mm; 3127 int err; 3128 3129 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr))) 3130 return -EINVAL; 3131 3132 VM_WARN_ON_ONCE(!vma_test_all_mask(vma, VMA_REMAP_FLAGS)); 3133 3134 BUG_ON(addr >= end); 3135 pfn -= addr >> PAGE_SHIFT; 3136 pgd = pgd_offset(mm, addr); 3137 flush_cache_range(vma, addr, end); 3138 do { 3139 next = pgd_addr_end(addr, end); 3140 err = remap_p4d_range(mm, pgd, addr, next, 3141 pfn + (addr >> PAGE_SHIFT), prot); 3142 if (err) 3143 return err; 3144 } while (pgd++, addr = next, addr != end); 3145 3146 return 0; 3147 } 3148 3149 /* 3150 * Variant of remap_pfn_range that does not call track_pfn_remap. The caller 3151 * must have pre-validated the caching bits of the pgprot_t. 3152 */ 3153 static int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr, 3154 unsigned long pfn, unsigned long size, pgprot_t prot) 3155 { 3156 int error = remap_pfn_range_internal(vma, addr, pfn, size, prot); 3157 3158 if (!error) 3159 return 0; 3160 3161 /* 3162 * A partial pfn range mapping is dangerous: it does not 3163 * maintain page reference counts, and callers may free 3164 * pages due to the error. So zap it early. 3165 */ 3166 zap_vma_range(vma, addr, size); 3167 return error; 3168 } 3169 3170 #ifdef __HAVE_PFNMAP_TRACKING 3171 static inline struct pfnmap_track_ctx *pfnmap_track_ctx_alloc(unsigned long pfn, 3172 unsigned long size, pgprot_t *prot) 3173 { 3174 struct pfnmap_track_ctx *ctx; 3175 3176 if (pfnmap_track(pfn, size, prot)) 3177 return ERR_PTR(-EINVAL); 3178 3179 ctx = kmalloc_obj(*ctx); 3180 if (unlikely(!ctx)) { 3181 pfnmap_untrack(pfn, size); 3182 return ERR_PTR(-ENOMEM); 3183 } 3184 3185 ctx->pfn = pfn; 3186 ctx->size = size; 3187 kref_init(&ctx->kref); 3188 return ctx; 3189 } 3190 3191 void pfnmap_track_ctx_release(struct kref *ref) 3192 { 3193 struct pfnmap_track_ctx *ctx = container_of(ref, struct pfnmap_track_ctx, kref); 3194 3195 pfnmap_untrack(ctx->pfn, ctx->size); 3196 kfree(ctx); 3197 } 3198 3199 static int remap_pfn_range_track(struct vm_area_struct *vma, unsigned long addr, 3200 unsigned long pfn, unsigned long size, pgprot_t prot) 3201 { 3202 struct pfnmap_track_ctx *ctx = NULL; 3203 int err; 3204 3205 size = PAGE_ALIGN(size); 3206 3207 /* 3208 * If we cover the full VMA, we'll perform actual tracking, and 3209 * remember to untrack when the last reference to our tracking 3210 * context from a VMA goes away. We'll keep tracking the whole pfn 3211 * range even during VMA splits and partial unmapping. 3212 * 3213 * If we only cover parts of the VMA, we'll only setup the cachemode 3214 * in the pgprot for the pfn range. 3215 */ 3216 if (addr == vma->vm_start && addr + size == vma->vm_end) { 3217 if (vma->pfnmap_track_ctx) 3218 return -EINVAL; 3219 ctx = pfnmap_track_ctx_alloc(pfn, size, &prot); 3220 if (IS_ERR(ctx)) 3221 return PTR_ERR(ctx); 3222 } else if (pfnmap_setup_cachemode(pfn, size, &prot)) { 3223 return -EINVAL; 3224 } 3225 3226 err = remap_pfn_range_notrack(vma, addr, pfn, size, prot); 3227 if (ctx) { 3228 if (err) 3229 kref_put(&ctx->kref, pfnmap_track_ctx_release); 3230 else 3231 vma->pfnmap_track_ctx = ctx; 3232 } 3233 return err; 3234 } 3235 3236 static int do_remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, 3237 unsigned long pfn, unsigned long size, pgprot_t prot) 3238 { 3239 return remap_pfn_range_track(vma, addr, pfn, size, prot); 3240 } 3241 #else 3242 static int do_remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, 3243 unsigned long pfn, unsigned long size, pgprot_t prot) 3244 { 3245 return remap_pfn_range_notrack(vma, addr, pfn, size, prot); 3246 } 3247 #endif 3248 3249 int remap_pfn_range_prepare(struct vm_area_desc *desc) 3250 { 3251 const struct mmap_action *action = &desc->action; 3252 const unsigned long start = action->remap.start; 3253 const unsigned long end = start + action->remap.size; 3254 const unsigned long pfn = action->remap.start_pfn; 3255 const bool is_cow = vma_desc_is_cow_mapping(desc); 3256 int err; 3257 3258 if (!range_in_vma_desc(desc, start, end)) 3259 return -EFAULT; 3260 3261 err = get_remap_pgoff(is_cow, start, end, desc->start, desc->end, pfn, 3262 &desc->pgoff); 3263 if (err) 3264 return err; 3265 3266 vma_desc_set_flags_mask(desc, VMA_REMAP_FLAGS); 3267 return 0; 3268 } 3269 3270 static int remap_pfn_range_prepare_vma(struct vm_area_struct *vma, 3271 unsigned long addr, unsigned long pfn, 3272 unsigned long size) 3273 { 3274 const unsigned long end = addr + PAGE_ALIGN(size); 3275 const bool is_cow = vma_is_cow_mapping(vma); 3276 int err; 3277 3278 err = get_remap_pgoff(is_cow, addr, end, vma->vm_start, vma->vm_end, 3279 pfn, &vma->vm_pgoff); 3280 if (err) 3281 return err; 3282 3283 vma_set_flags_mask(vma, VMA_REMAP_FLAGS); 3284 return 0; 3285 } 3286 3287 /** 3288 * remap_pfn_range - remap kernel memory to userspace 3289 * @vma: user vma to map to 3290 * @addr: target page aligned user address to start at 3291 * @pfn: page frame number of kernel physical memory address 3292 * @size: size of mapping area 3293 * @prot: page protection flags for this mapping 3294 * 3295 * Note: this is only safe if the mm semaphore is held when called. 3296 * 3297 * Return: %0 on success, negative error code otherwise. 3298 */ 3299 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, 3300 unsigned long pfn, unsigned long size, pgprot_t prot) 3301 { 3302 int err; 3303 3304 err = remap_pfn_range_prepare_vma(vma, addr, pfn, size); 3305 if (err) 3306 return err; 3307 3308 return do_remap_pfn_range(vma, addr, pfn, size, prot); 3309 } 3310 EXPORT_SYMBOL(remap_pfn_range); 3311 3312 int remap_pfn_range_complete(struct vm_area_struct *vma, 3313 struct mmap_action *action) 3314 { 3315 const unsigned long start = action->remap.start; 3316 const unsigned long pfn = action->remap.start_pfn; 3317 const unsigned long size = action->remap.size; 3318 const pgprot_t prot = action->remap.pgprot; 3319 3320 return do_remap_pfn_range(vma, start, pfn, size, prot); 3321 } 3322 3323 static int __simple_ioremap_prep(unsigned long vm_len, pgoff_t vm_pgoff, 3324 phys_addr_t start_phys, unsigned long size, 3325 unsigned long *pfnp) 3326 { 3327 unsigned long pfn, pages; 3328 3329 /* Check that the physical memory area passed in looks valid */ 3330 if (start_phys + size < start_phys) 3331 return -EINVAL; 3332 /* 3333 * You *really* shouldn't map things that aren't page-aligned, 3334 * but we've historically allowed it because IO memory might 3335 * just have smaller alignment. 3336 */ 3337 size += start_phys & ~PAGE_MASK; 3338 pfn = start_phys >> PAGE_SHIFT; 3339 pages = (size + ~PAGE_MASK) >> PAGE_SHIFT; 3340 if (pfn + pages < pfn) 3341 return -EINVAL; 3342 3343 /* We start the mapping 'vm_pgoff' pages into the area */ 3344 if (vm_pgoff > pages) 3345 return -EINVAL; 3346 pfn += vm_pgoff; 3347 pages -= vm_pgoff; 3348 3349 /* Can we fit all of the mapping? */ 3350 if ((vm_len >> PAGE_SHIFT) > pages) 3351 return -EINVAL; 3352 3353 *pfnp = pfn; 3354 return 0; 3355 } 3356 3357 int simple_ioremap_prepare(struct vm_area_desc *desc) 3358 { 3359 struct mmap_action *action = &desc->action; 3360 const phys_addr_t start = action->simple_ioremap.start_phys_addr; 3361 const unsigned long size = action->simple_ioremap.size; 3362 unsigned long pfn; 3363 int err; 3364 3365 err = __simple_ioremap_prep(vma_desc_size(desc), desc->pgoff, 3366 start, size, &pfn); 3367 if (err) 3368 return err; 3369 3370 /* The I/O remap logic does the heavy lifting. */ 3371 mmap_action_ioremap_full(desc, pfn); 3372 return io_remap_pfn_range_prepare(desc); 3373 } 3374 3375 /** 3376 * vm_iomap_memory - remap memory to userspace 3377 * @vma: user vma to map to 3378 * @start: start of the physical memory to be mapped 3379 * @len: size of area 3380 * 3381 * This is a simplified io_remap_pfn_range() for common driver use. The 3382 * driver just needs to give us the physical memory range to be mapped, 3383 * we'll figure out the rest from the vma information. 3384 * 3385 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get 3386 * whatever write-combining details or similar. 3387 * 3388 * Return: %0 on success, negative error code otherwise. 3389 */ 3390 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len) 3391 { 3392 const unsigned long vm_start = vma->vm_start; 3393 const unsigned long vm_end = vma->vm_end; 3394 const unsigned long vm_len = vm_end - vm_start; 3395 unsigned long pfn; 3396 int err; 3397 3398 err = __simple_ioremap_prep(vm_len, vma_start_pgoff(vma), start, len, 3399 &pfn); 3400 if (err) 3401 return err; 3402 3403 /* Ok, let it rip */ 3404 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot); 3405 } 3406 EXPORT_SYMBOL(vm_iomap_memory); 3407 3408 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd, 3409 unsigned long addr, unsigned long end, 3410 pte_fn_t fn, void *data, bool create, 3411 pgtbl_mod_mask *mask) 3412 { 3413 pte_t *pte, *mapped_pte; 3414 int err = 0; 3415 spinlock_t *ptl; 3416 3417 if (create) { 3418 mapped_pte = pte = (mm == &init_mm) ? 3419 pte_alloc_kernel_track(pmd, addr, mask) : 3420 pte_alloc_map_lock(mm, pmd, addr, &ptl); 3421 if (!pte) 3422 return -ENOMEM; 3423 } else { 3424 mapped_pte = pte = (mm == &init_mm) ? 3425 pte_offset_kernel(pmd, addr) : 3426 pte_offset_map_lock(mm, pmd, addr, &ptl); 3427 if (!pte) 3428 return -EINVAL; 3429 } 3430 3431 lazy_mmu_mode_enable(); 3432 3433 if (fn) { 3434 do { 3435 if (create || !pte_none(ptep_get(pte))) { 3436 err = fn(pte, addr, data); 3437 if (err) 3438 break; 3439 } 3440 } while (pte++, addr += PAGE_SIZE, addr != end); 3441 } 3442 *mask |= PGTBL_PTE_MODIFIED; 3443 3444 lazy_mmu_mode_disable(); 3445 3446 if (mm != &init_mm) 3447 pte_unmap_unlock(mapped_pte, ptl); 3448 return err; 3449 } 3450 3451 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud, 3452 unsigned long addr, unsigned long end, 3453 pte_fn_t fn, void *data, bool create, 3454 pgtbl_mod_mask *mask) 3455 { 3456 pmd_t *pmd; 3457 unsigned long next; 3458 int err = 0; 3459 3460 BUG_ON(pud_leaf(*pud)); 3461 3462 if (create) { 3463 pmd = pmd_alloc_track(mm, pud, addr, mask); 3464 if (!pmd) 3465 return -ENOMEM; 3466 } else { 3467 pmd = pmd_offset(pud, addr); 3468 } 3469 do { 3470 next = pmd_addr_end(addr, end); 3471 if (pmd_none(*pmd) && !create) 3472 continue; 3473 if (WARN_ON_ONCE(pmd_leaf(*pmd))) 3474 return -EINVAL; 3475 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) { 3476 if (!create) 3477 continue; 3478 pmd_clear_bad(pmd); 3479 } 3480 err = apply_to_pte_range(mm, pmd, addr, next, 3481 fn, data, create, mask); 3482 if (err) 3483 break; 3484 } while (pmd++, addr = next, addr != end); 3485 3486 return err; 3487 } 3488 3489 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d, 3490 unsigned long addr, unsigned long end, 3491 pte_fn_t fn, void *data, bool create, 3492 pgtbl_mod_mask *mask) 3493 { 3494 pud_t *pud; 3495 unsigned long next; 3496 int err = 0; 3497 3498 if (create) { 3499 pud = pud_alloc_track(mm, p4d, addr, mask); 3500 if (!pud) 3501 return -ENOMEM; 3502 } else { 3503 pud = pud_offset(p4d, addr); 3504 } 3505 do { 3506 next = pud_addr_end(addr, end); 3507 if (pud_none(*pud) && !create) 3508 continue; 3509 if (WARN_ON_ONCE(pud_leaf(*pud))) 3510 return -EINVAL; 3511 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) { 3512 if (!create) 3513 continue; 3514 pud_clear_bad(pud); 3515 } 3516 err = apply_to_pmd_range(mm, pud, addr, next, 3517 fn, data, create, mask); 3518 if (err) 3519 break; 3520 } while (pud++, addr = next, addr != end); 3521 3522 return err; 3523 } 3524 3525 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd, 3526 unsigned long addr, unsigned long end, 3527 pte_fn_t fn, void *data, bool create, 3528 pgtbl_mod_mask *mask) 3529 { 3530 p4d_t *p4d; 3531 unsigned long next; 3532 int err = 0; 3533 3534 if (create) { 3535 p4d = p4d_alloc_track(mm, pgd, addr, mask); 3536 if (!p4d) 3537 return -ENOMEM; 3538 } else { 3539 p4d = p4d_offset(pgd, addr); 3540 } 3541 do { 3542 next = p4d_addr_end(addr, end); 3543 if (p4d_none(*p4d) && !create) 3544 continue; 3545 if (WARN_ON_ONCE(p4d_leaf(*p4d))) 3546 return -EINVAL; 3547 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) { 3548 if (!create) 3549 continue; 3550 p4d_clear_bad(p4d); 3551 } 3552 err = apply_to_pud_range(mm, p4d, addr, next, 3553 fn, data, create, mask); 3554 if (err) 3555 break; 3556 } while (p4d++, addr = next, addr != end); 3557 3558 return err; 3559 } 3560 3561 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr, 3562 unsigned long size, pte_fn_t fn, 3563 void *data, bool create) 3564 { 3565 pgd_t *pgd; 3566 unsigned long start = addr, next; 3567 unsigned long end = addr + size; 3568 pgtbl_mod_mask mask = 0; 3569 int err = 0; 3570 3571 if (WARN_ON(addr >= end)) 3572 return -EINVAL; 3573 3574 pgd = pgd_offset(mm, addr); 3575 do { 3576 next = pgd_addr_end(addr, end); 3577 if (pgd_none(*pgd) && !create) 3578 continue; 3579 if (WARN_ON_ONCE(pgd_leaf(*pgd))) { 3580 err = -EINVAL; 3581 break; 3582 } 3583 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) { 3584 if (!create) 3585 continue; 3586 pgd_clear_bad(pgd); 3587 } 3588 err = apply_to_p4d_range(mm, pgd, addr, next, 3589 fn, data, create, &mask); 3590 if (err) 3591 break; 3592 } while (pgd++, addr = next, addr != end); 3593 3594 if (mask & ARCH_PAGE_TABLE_SYNC_MASK) 3595 arch_sync_kernel_mappings(start, start + size); 3596 3597 return err; 3598 } 3599 3600 /* 3601 * Scan a region of virtual memory, filling in page tables as necessary 3602 * and calling a provided function on each leaf page table. 3603 */ 3604 int apply_to_page_range(struct mm_struct *mm, unsigned long addr, 3605 unsigned long size, pte_fn_t fn, void *data) 3606 { 3607 return __apply_to_page_range(mm, addr, size, fn, data, true); 3608 } 3609 EXPORT_SYMBOL_GPL(apply_to_page_range); 3610 3611 /* 3612 * Scan a region of virtual memory, calling a provided function on 3613 * each leaf page table where it exists. 3614 * 3615 * Unlike apply_to_page_range, this does _not_ fill in page tables 3616 * where they are absent. 3617 */ 3618 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr, 3619 unsigned long size, pte_fn_t fn, void *data) 3620 { 3621 return __apply_to_page_range(mm, addr, size, fn, data, false); 3622 } 3623 3624 /* 3625 * handle_pte_fault chooses page fault handler according to an entry which was 3626 * read non-atomically. Before making any commitment, on those architectures 3627 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched 3628 * parts, do_swap_page must check under lock before unmapping the pte and 3629 * proceeding (but do_wp_page is only called after already making such a check; 3630 * and do_anonymous_page can safely check later on). 3631 */ 3632 static inline int pte_unmap_same(struct vm_fault *vmf) 3633 { 3634 int same = 1; 3635 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION) 3636 if (sizeof(pte_t) > sizeof(unsigned long)) { 3637 spin_lock(vmf->ptl); 3638 same = pte_same(ptep_get(vmf->pte), vmf->orig_pte); 3639 spin_unlock(vmf->ptl); 3640 } 3641 #endif 3642 pte_unmap(vmf->pte); 3643 vmf->pte = NULL; 3644 return same; 3645 } 3646 3647 /* 3648 * Return: 3649 * 0: copied succeeded 3650 * -EHWPOISON: copy failed due to hwpoison in source page 3651 * -EAGAIN: copied failed (some other reason) 3652 */ 3653 static inline int __wp_page_copy_user(struct page *dst, struct page *src, 3654 struct vm_fault *vmf) 3655 { 3656 int ret; 3657 void *kaddr; 3658 void __user *uaddr; 3659 struct vm_area_struct *vma = vmf->vma; 3660 struct mm_struct *mm = vma->vm_mm; 3661 unsigned long addr = vmf->address; 3662 3663 if (likely(src)) { 3664 if (copy_mc_user_highpage(dst, src, addr, vma)) 3665 return -EHWPOISON; 3666 return 0; 3667 } 3668 3669 /* 3670 * If the source page was a PFN mapping, we don't have 3671 * a "struct page" for it. We do a best-effort copy by 3672 * just copying from the original user address. If that 3673 * fails, we just zero-fill it. Live with it. 3674 */ 3675 kaddr = kmap_local_page(dst); 3676 pagefault_disable(); 3677 uaddr = (void __user *)(addr & PAGE_MASK); 3678 3679 /* 3680 * On architectures with software "accessed" bits, we would 3681 * take a double page fault, so mark it accessed here. 3682 */ 3683 vmf->pte = NULL; 3684 if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) { 3685 pte_t entry; 3686 3687 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl); 3688 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 3689 /* 3690 * Other thread has already handled the fault 3691 * and update local tlb only 3692 */ 3693 if (vmf->pte) 3694 update_mmu_tlb(vma, addr, vmf->pte); 3695 ret = -EAGAIN; 3696 goto pte_unlock; 3697 } 3698 3699 entry = pte_mkyoung(vmf->orig_pte); 3700 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0)) 3701 update_mmu_cache_range(vmf, vma, addr, vmf->pte, 1); 3702 } 3703 3704 /* 3705 * This really shouldn't fail, because the page is there 3706 * in the page tables. But it might just be unreadable, 3707 * in which case we just give up and fill the result with 3708 * zeroes. 3709 */ 3710 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) { 3711 if (vmf->pte) 3712 goto warn; 3713 3714 /* Re-validate under PTL if the page is still mapped */ 3715 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl); 3716 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 3717 /* The PTE changed under us, update local tlb */ 3718 if (vmf->pte) 3719 update_mmu_tlb(vma, addr, vmf->pte); 3720 ret = -EAGAIN; 3721 goto pte_unlock; 3722 } 3723 3724 /* 3725 * The same page can be mapped back since last copy attempt. 3726 * Try to copy again under PTL. 3727 */ 3728 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) { 3729 /* 3730 * Give a warn in case there can be some obscure 3731 * use-case 3732 */ 3733 warn: 3734 WARN_ON_ONCE(1); 3735 clear_page(kaddr); 3736 } 3737 } 3738 3739 ret = 0; 3740 3741 pte_unlock: 3742 if (vmf->pte) 3743 pte_unmap_unlock(vmf->pte, vmf->ptl); 3744 pagefault_enable(); 3745 kunmap_local(kaddr); 3746 flush_dcache_page(dst); 3747 3748 return ret; 3749 } 3750 3751 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma) 3752 { 3753 struct file *vm_file = vma->vm_file; 3754 3755 if (vm_file) 3756 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO; 3757 3758 /* 3759 * Special mappings (e.g. VDSO) do not have any file so fake 3760 * a default GFP_KERNEL for them. 3761 */ 3762 return GFP_KERNEL; 3763 } 3764 3765 /* 3766 * Notify the address space that the page is about to become writable so that 3767 * it can prohibit this or wait for the page to get into an appropriate state. 3768 * 3769 * We do this without the lock held, so that it can sleep if it needs to. 3770 */ 3771 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf, struct folio *folio) 3772 { 3773 vm_fault_t ret; 3774 unsigned int old_flags = vmf->flags; 3775 3776 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; 3777 3778 if (vmf->vma->vm_file && 3779 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host)) 3780 return VM_FAULT_SIGBUS; 3781 3782 ret = vmf->vma->vm_ops->page_mkwrite(vmf); 3783 /* Restore original flags so that caller is not surprised */ 3784 vmf->flags = old_flags; 3785 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) 3786 return ret; 3787 if (unlikely(!(ret & VM_FAULT_LOCKED))) { 3788 folio_lock(folio); 3789 if (!folio->mapping) { 3790 folio_unlock(folio); 3791 return 0; /* retry */ 3792 } 3793 ret |= VM_FAULT_LOCKED; 3794 } else 3795 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 3796 return ret; 3797 } 3798 3799 /* 3800 * Handle dirtying of a page in shared file mapping on a write fault. 3801 * 3802 * The function expects the page to be locked and unlocks it. 3803 */ 3804 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf) 3805 { 3806 struct vm_area_struct *vma = vmf->vma; 3807 struct address_space *mapping; 3808 struct folio *folio = page_folio(vmf->page); 3809 bool dirtied; 3810 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite; 3811 3812 dirtied = folio_mark_dirty(folio); 3813 VM_BUG_ON_FOLIO(folio_test_anon(folio), folio); 3814 /* 3815 * Take a local copy of the address_space - folio.mapping may be zeroed 3816 * by truncate after folio_unlock(). The address_space itself remains 3817 * pinned by vma->vm_file's reference. We rely on folio_unlock()'s 3818 * release semantics to prevent the compiler from undoing this copying. 3819 */ 3820 mapping = folio_raw_mapping(folio); 3821 folio_unlock(folio); 3822 3823 if (!page_mkwrite) 3824 file_update_time(vma->vm_file); 3825 3826 /* 3827 * Throttle page dirtying rate down to writeback speed. 3828 * 3829 * mapping may be NULL here because some device drivers do not 3830 * set page.mapping but still dirty their pages 3831 * 3832 * Drop the mmap_lock before waiting on IO, if we can. The file 3833 * is pinning the mapping, as per above. 3834 */ 3835 if ((dirtied || page_mkwrite) && mapping) { 3836 struct file *fpin; 3837 3838 fpin = maybe_unlock_mmap_for_io(vmf, NULL); 3839 balance_dirty_pages_ratelimited(mapping); 3840 if (fpin) { 3841 fput(fpin); 3842 return VM_FAULT_COMPLETED; 3843 } 3844 } 3845 3846 return 0; 3847 } 3848 3849 /* 3850 * Handle write page faults for pages that can be reused in the current vma 3851 * 3852 * This can happen either due to the mapping being with the VM_SHARED flag, 3853 * or due to us being the last reference standing to the page. In either 3854 * case, all we need to do here is to mark the page as writable and update 3855 * any related book-keeping. 3856 */ 3857 static inline void wp_page_reuse(struct vm_fault *vmf, struct folio *folio) 3858 __releases(vmf->ptl) 3859 { 3860 struct vm_area_struct *vma = vmf->vma; 3861 pte_t entry; 3862 3863 VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE)); 3864 VM_WARN_ON(is_zero_pfn(pte_pfn(vmf->orig_pte))); 3865 3866 if (folio) { 3867 VM_BUG_ON(folio_test_anon(folio) && 3868 !PageAnonExclusive(vmf->page)); 3869 /* 3870 * Clear the folio's cpupid information as the existing 3871 * information potentially belongs to a now completely 3872 * unrelated process. 3873 */ 3874 folio_xchg_last_cpupid(folio, (1 << LAST_CPUPID_SHIFT) - 1); 3875 } 3876 3877 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte)); 3878 entry = pte_mkyoung(vmf->orig_pte); 3879 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 3880 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1)) 3881 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 3882 pte_unmap_unlock(vmf->pte, vmf->ptl); 3883 count_vm_event(PGREUSE); 3884 } 3885 3886 /* 3887 * We could add a bitflag somewhere, but for now, we know that all 3888 * vm_ops that have a ->map_pages have been audited and don't need 3889 * the mmap_lock to be held. 3890 */ 3891 static inline vm_fault_t vmf_can_call_fault(const struct vm_fault *vmf) 3892 { 3893 struct vm_area_struct *vma = vmf->vma; 3894 3895 if (vma->vm_ops->map_pages || !(vmf->flags & FAULT_FLAG_VMA_LOCK)) 3896 return 0; 3897 vma_end_read(vma); 3898 return VM_FAULT_RETRY; 3899 } 3900 3901 /** 3902 * __vmf_anon_prepare - Prepare to handle an anonymous fault. 3903 * @vmf: The vm_fault descriptor passed from the fault handler. 3904 * 3905 * When preparing to insert an anonymous page into a VMA from a 3906 * fault handler, call this function rather than anon_vma_prepare(). 3907 * If this vma does not already have an associated anon_vma and we are 3908 * only protected by the per-VMA lock, the caller must retry with the 3909 * mmap_lock held. __anon_vma_prepare() will look at adjacent VMAs to 3910 * determine if this VMA can share its anon_vma, and that's not safe to 3911 * do with only the per-VMA lock held for this VMA. 3912 * 3913 * Return: 0 if fault handling can proceed. Any other value should be 3914 * returned to the caller. 3915 */ 3916 vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf) 3917 { 3918 struct vm_area_struct *vma = vmf->vma; 3919 vm_fault_t ret = 0; 3920 3921 if (likely(vma->anon_vma)) 3922 return 0; 3923 if (vmf->flags & FAULT_FLAG_VMA_LOCK) { 3924 if (!mmap_read_trylock(vma->vm_mm)) 3925 return VM_FAULT_RETRY; 3926 } 3927 if (__anon_vma_prepare(vma)) 3928 ret = VM_FAULT_OOM; 3929 if (vmf->flags & FAULT_FLAG_VMA_LOCK) 3930 mmap_read_unlock(vma->vm_mm); 3931 return ret; 3932 } 3933 3934 /* 3935 * Handle the case of a page which we actually need to copy to a new page, 3936 * either due to COW or unsharing. 3937 * 3938 * Called with either the VMA lock or the mmap_lock held (see FAULT_FLAG_VMA_LOCK) 3939 * and the old page referenced, but without the ptl held. 3940 * 3941 * High level logic flow: 3942 * 3943 * - Allocate a page, copy the content of the old page to the new one. 3944 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc. 3945 * - Take the PTL. If the pte changed, bail out and release the allocated page 3946 * - If the pte is still the way we remember it, update the page table and all 3947 * relevant references. This includes dropping the reference the page-table 3948 * held to the old page, as well as updating the rmap. 3949 * - In any case, unlock the PTL and drop the reference we took to the old page. 3950 */ 3951 static vm_fault_t wp_page_copy(struct vm_fault *vmf) 3952 { 3953 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 3954 struct vm_area_struct *vma = vmf->vma; 3955 struct mm_struct *mm = vma->vm_mm; 3956 struct folio *old_folio = NULL; 3957 struct folio *new_folio = NULL; 3958 pte_t entry; 3959 int page_copied = 0; 3960 struct mmu_notifier_range range; 3961 vm_fault_t ret; 3962 bool pfn_is_zero; 3963 3964 delayacct_wpcopy_start(); 3965 3966 if (vmf->page) 3967 old_folio = page_folio(vmf->page); 3968 ret = vmf_anon_prepare(vmf); 3969 if (unlikely(ret)) 3970 goto out; 3971 3972 pfn_is_zero = is_zero_pfn(pte_pfn(vmf->orig_pte)); 3973 new_folio = folio_prealloc(mm, vma, vmf->address, pfn_is_zero); 3974 if (!new_folio) 3975 goto oom; 3976 3977 if (!pfn_is_zero) { 3978 int err; 3979 3980 err = __wp_page_copy_user(&new_folio->page, vmf->page, vmf); 3981 if (err) { 3982 /* 3983 * COW failed, if the fault was solved by other, 3984 * it's fine. If not, userspace would re-fault on 3985 * the same address and we will handle the fault 3986 * from the second attempt. 3987 * The -EHWPOISON case will not be retried. 3988 */ 3989 folio_put(new_folio); 3990 if (old_folio) 3991 folio_put(old_folio); 3992 3993 delayacct_wpcopy_end(); 3994 return err == -EHWPOISON ? VM_FAULT_HWPOISON : 0; 3995 } 3996 kmsan_copy_page_meta(&new_folio->page, vmf->page); 3997 } 3998 3999 __folio_mark_uptodate(new_folio); 4000 4001 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 4002 vmf->address & PAGE_MASK, 4003 (vmf->address & PAGE_MASK) + PAGE_SIZE); 4004 mmu_notifier_invalidate_range_start(&range); 4005 4006 /* 4007 * Re-check the pte - we dropped the lock 4008 */ 4009 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl); 4010 if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 4011 if (old_folio) { 4012 if (!folio_test_anon(old_folio)) { 4013 dec_mm_counter(mm, mm_counter_file(old_folio)); 4014 inc_mm_counter(mm, MM_ANONPAGES); 4015 } 4016 } else { 4017 ksm_might_unmap_zero_page(mm, vmf->orig_pte); 4018 inc_mm_counter(mm, MM_ANONPAGES); 4019 } 4020 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte)); 4021 entry = folio_mk_pte(new_folio, vma->vm_page_prot); 4022 entry = pte_sw_mkyoung(entry); 4023 if (unlikely(unshare)) { 4024 if (pte_soft_dirty(vmf->orig_pte)) 4025 entry = pte_mksoft_dirty(entry); 4026 if (pte_uffd(vmf->orig_pte)) 4027 entry = pte_mkuffd(entry); 4028 } else { 4029 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 4030 } 4031 4032 /* 4033 * Clear the pte entry and flush it first, before updating the 4034 * pte with the new entry, to keep TLBs on different CPUs in 4035 * sync. This code used to set the new PTE then flush TLBs, but 4036 * that left a window where the new PTE could be loaded into 4037 * some TLBs while the old PTE remains in others. 4038 */ 4039 ptep_clear_flush(vma, vmf->address, vmf->pte); 4040 folio_add_new_anon_rmap(new_folio, vma, vmf->address, RMAP_EXCLUSIVE); 4041 folio_add_lru_vma(new_folio, vma); 4042 BUG_ON(unshare && pte_write(entry)); 4043 set_pte_at(mm, vmf->address, vmf->pte, entry); 4044 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1); 4045 if (old_folio) { 4046 /* 4047 * Only after switching the pte to the new page may 4048 * we remove the mapcount here. Otherwise another 4049 * process may come and find the rmap count decremented 4050 * before the pte is switched to the new page, and 4051 * "reuse" the old page writing into it while our pte 4052 * here still points into it and can be read by other 4053 * threads. 4054 * 4055 * The critical issue is to order this 4056 * folio_remove_rmap_pte() with the ptp_clear_flush 4057 * above. Those stores are ordered by (if nothing else,) 4058 * the barrier present in the atomic_add_negative 4059 * in folio_remove_rmap_pte(); 4060 * 4061 * Then the TLB flush in ptep_clear_flush ensures that 4062 * no process can access the old page before the 4063 * decremented mapcount is visible. And the old page 4064 * cannot be reused until after the decremented 4065 * mapcount is visible. So transitively, TLBs to 4066 * old page will be flushed before it can be reused. 4067 */ 4068 folio_remove_rmap_pte(old_folio, vmf->page, vma); 4069 } 4070 4071 /* Free the old page.. */ 4072 new_folio = old_folio; 4073 page_copied = 1; 4074 pte_unmap_unlock(vmf->pte, vmf->ptl); 4075 } else if (vmf->pte) { 4076 update_mmu_tlb(vma, vmf->address, vmf->pte); 4077 pte_unmap_unlock(vmf->pte, vmf->ptl); 4078 } 4079 4080 mmu_notifier_invalidate_range_end(&range); 4081 4082 if (new_folio) 4083 folio_put(new_folio); 4084 if (old_folio) { 4085 if (page_copied) 4086 free_swap_cache(old_folio); 4087 folio_put(old_folio); 4088 } 4089 4090 delayacct_wpcopy_end(); 4091 return 0; 4092 oom: 4093 ret = VM_FAULT_OOM; 4094 out: 4095 if (old_folio) 4096 folio_put(old_folio); 4097 4098 delayacct_wpcopy_end(); 4099 return ret; 4100 } 4101 4102 /** 4103 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE 4104 * writeable once the page is prepared 4105 * 4106 * @vmf: structure describing the fault 4107 * @folio: the folio of vmf->page 4108 * 4109 * This function handles all that is needed to finish a write page fault in a 4110 * shared mapping due to PTE being read-only once the mapped page is prepared. 4111 * It handles locking of PTE and modifying it. 4112 * 4113 * The function expects the page to be locked or other protection against 4114 * concurrent faults / writeback (such as DAX radix tree locks). 4115 * 4116 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before 4117 * we acquired PTE lock. 4118 */ 4119 static vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf, struct folio *folio) 4120 { 4121 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED)); 4122 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address, 4123 &vmf->ptl); 4124 if (!vmf->pte) 4125 return VM_FAULT_NOPAGE; 4126 /* 4127 * We might have raced with another page fault while we released the 4128 * pte_offset_map_lock. 4129 */ 4130 if (!pte_same(ptep_get(vmf->pte), vmf->orig_pte)) { 4131 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte); 4132 pte_unmap_unlock(vmf->pte, vmf->ptl); 4133 return VM_FAULT_NOPAGE; 4134 } 4135 wp_page_reuse(vmf, folio); 4136 return 0; 4137 } 4138 4139 /* 4140 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED 4141 * mapping 4142 */ 4143 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf) 4144 { 4145 struct vm_area_struct *vma = vmf->vma; 4146 4147 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) { 4148 vm_fault_t ret; 4149 4150 pte_unmap_unlock(vmf->pte, vmf->ptl); 4151 ret = vmf_can_call_fault(vmf); 4152 if (ret) 4153 return ret; 4154 4155 vmf->flags |= FAULT_FLAG_MKWRITE; 4156 ret = vma->vm_ops->pfn_mkwrite(vmf); 4157 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)) 4158 return ret; 4159 return finish_mkwrite_fault(vmf, NULL); 4160 } 4161 wp_page_reuse(vmf, NULL); 4162 return 0; 4163 } 4164 4165 static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio) 4166 __releases(vmf->ptl) 4167 { 4168 struct vm_area_struct *vma = vmf->vma; 4169 vm_fault_t ret = 0; 4170 4171 folio_get(folio); 4172 4173 if (vma->vm_ops && vma->vm_ops->page_mkwrite) { 4174 vm_fault_t tmp; 4175 4176 pte_unmap_unlock(vmf->pte, vmf->ptl); 4177 tmp = vmf_can_call_fault(vmf); 4178 if (tmp) { 4179 folio_put(folio); 4180 return tmp; 4181 } 4182 4183 tmp = do_page_mkwrite(vmf, folio); 4184 if (unlikely(!tmp || (tmp & 4185 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { 4186 folio_put(folio); 4187 return tmp; 4188 } 4189 tmp = finish_mkwrite_fault(vmf, folio); 4190 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { 4191 folio_unlock(folio); 4192 folio_put(folio); 4193 return tmp; 4194 } 4195 } else { 4196 wp_page_reuse(vmf, folio); 4197 folio_lock(folio); 4198 } 4199 ret |= fault_dirty_shared_page(vmf); 4200 folio_put(folio); 4201 4202 return ret; 4203 } 4204 4205 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4206 static bool __wp_can_reuse_large_anon_folio(struct folio *folio, 4207 struct vm_area_struct *vma) 4208 { 4209 bool exclusive = false; 4210 4211 /* Let's just free up a large folio if only a single page is mapped. */ 4212 if (folio_large_mapcount(folio) <= 1) 4213 return false; 4214 4215 /* 4216 * The assumption for anonymous folios is that each page can only get 4217 * mapped once into each MM. The only exception are KSM folios, which 4218 * are always small. 4219 * 4220 * Each taken mapcount must be paired with exactly one taken reference, 4221 * whereby the refcount must be incremented before the mapcount when 4222 * mapping a page, and the refcount must be decremented after the 4223 * mapcount when unmapping a page. 4224 * 4225 * If all folio references are from mappings, and all mappings are in 4226 * the page tables of this MM, then this folio is exclusive to this MM. 4227 */ 4228 if (test_bit(FOLIO_MM_IDS_SHARED_BITNUM, &folio->_mm_ids)) 4229 return false; 4230 4231 VM_WARN_ON_ONCE(folio_test_ksm(folio)); 4232 4233 if (unlikely(folio_test_swapcache(folio))) { 4234 /* 4235 * Note: freeing up the swapcache will fail if some PTEs are 4236 * still swap entries. 4237 */ 4238 if (!folio_trylock(folio)) 4239 return false; 4240 folio_free_swap(folio); 4241 folio_unlock(folio); 4242 } 4243 4244 if (folio_large_mapcount(folio) != folio_ref_count(folio)) 4245 return false; 4246 4247 /* Stabilize the mapcount vs. refcount and recheck. */ 4248 folio_lock_large_mapcount(folio); 4249 VM_WARN_ON_ONCE_FOLIO(folio_large_mapcount(folio) > folio_ref_count(folio), folio); 4250 4251 if (test_bit(FOLIO_MM_IDS_SHARED_BITNUM, &folio->_mm_ids)) 4252 goto unlock; 4253 if (folio_large_mapcount(folio) != folio_ref_count(folio)) 4254 goto unlock; 4255 4256 VM_WARN_ON_ONCE_FOLIO(folio_large_mapcount(folio) > folio_nr_pages(folio), folio); 4257 VM_WARN_ON_ONCE_FOLIO(folio_entire_mapcount(folio), folio); 4258 VM_WARN_ON_ONCE(folio_mm_id(folio, 0) != vma->vm_mm->mm_id && 4259 folio_mm_id(folio, 1) != vma->vm_mm->mm_id); 4260 4261 /* 4262 * Do we need the folio lock? Likely not. If there would have been 4263 * references from page migration/swapout, we would have detected 4264 * an additional folio reference and never ended up here. 4265 */ 4266 exclusive = true; 4267 unlock: 4268 folio_unlock_large_mapcount(folio); 4269 return exclusive; 4270 } 4271 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */ 4272 static bool __wp_can_reuse_large_anon_folio(struct folio *folio, 4273 struct vm_area_struct *vma) 4274 { 4275 BUILD_BUG(); 4276 } 4277 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 4278 4279 static bool wp_can_reuse_anon_folio(struct folio *folio, 4280 struct vm_area_struct *vma) 4281 { 4282 const bool maybe_in_lru_cache = !folio_test_lru(folio); 4283 const bool in_swapcache = folio_test_swapcache(folio); 4284 4285 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && folio_test_large(folio)) 4286 return __wp_can_reuse_large_anon_folio(folio, vma); 4287 4288 /* 4289 * We have to verify under folio lock: these early checks are 4290 * just an optimization to avoid locking the folio and freeing 4291 * the swapcache if there is little hope that we can reuse. 4292 * 4293 * KSM doesn't necessarily raise the folio refcount. 4294 */ 4295 if (folio_test_ksm(folio) || 4296 folio_ref_count(folio) > 1 + maybe_in_lru_cache + in_swapcache) 4297 return false; 4298 if (maybe_in_lru_cache) 4299 /* 4300 * We cannot easily detect+handle references from 4301 * remote LRU caches or references to LRU folios. 4302 */ 4303 lru_add_drain(); 4304 if (folio_ref_count(folio) > 1 + in_swapcache) 4305 return false; 4306 if (!folio_trylock(folio)) 4307 return false; 4308 if (folio_test_swapcache(folio)) 4309 folio_free_swap(folio); 4310 if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) { 4311 folio_unlock(folio); 4312 return false; 4313 } 4314 /* 4315 * Ok, we've got the only folio reference from our mapping 4316 * and the folio is locked, it's dark out, and we're wearing 4317 * sunglasses. Hit it. 4318 */ 4319 folio_move_anon_rmap(folio, vma); 4320 folio_unlock(folio); 4321 return true; 4322 } 4323 4324 /* 4325 * This routine handles present pages, when 4326 * * users try to write to a shared page (FAULT_FLAG_WRITE) 4327 * * GUP wants to take a R/O pin on a possibly shared anonymous page 4328 * (FAULT_FLAG_UNSHARE) 4329 * 4330 * It is done by copying the page to a new address and decrementing the 4331 * shared-page counter for the old page. 4332 * 4333 * Note that this routine assumes that the protection checks have been 4334 * done by the caller (the low-level page fault routine in most cases). 4335 * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've 4336 * done any necessary COW. 4337 * 4338 * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even 4339 * though the page will change only once the write actually happens. This 4340 * avoids a few races, and potentially makes it more efficient. 4341 * 4342 * We enter with either the VMA lock or the mmap_lock held (see 4343 * FAULT_FLAG_VMA_LOCK) and pte both mapped and locked. We return with 4344 * the same lock still held, but pte unmapped and unlocked. 4345 */ 4346 static vm_fault_t do_wp_page(struct vm_fault *vmf) 4347 __releases(vmf->ptl) 4348 { 4349 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 4350 struct vm_area_struct *vma = vmf->vma; 4351 struct folio *folio = NULL; 4352 pte_t pte; 4353 4354 if (likely(!unshare)) { 4355 if (userfaultfd_pte_wp(vma, ptep_get(vmf->pte))) { 4356 if (!userfaultfd_wp_async(vma)) { 4357 pte_unmap_unlock(vmf->pte, vmf->ptl); 4358 return handle_userfault(vmf, VM_UFFD_WP); 4359 } 4360 4361 /* 4362 * Nothing needed (cache flush, TLB invalidations, 4363 * etc.) because we're only removing the uffd-wp bit, 4364 * which is completely invisible to the user. 4365 */ 4366 pte = pte_clear_uffd(ptep_get(vmf->pte)); 4367 4368 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte); 4369 /* 4370 * Update this to be prepared for following up CoW 4371 * handling 4372 */ 4373 vmf->orig_pte = pte; 4374 } 4375 4376 /* 4377 * Userfaultfd write-protect can defer flushes. Ensure the TLB 4378 * is flushed in this case before copying. 4379 */ 4380 if (unlikely(userfaultfd_wp(vmf->vma) && 4381 mm_tlb_flush_pending(vmf->vma->vm_mm))) 4382 flush_tlb_page(vmf->vma, vmf->address); 4383 } 4384 4385 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte); 4386 4387 if (vmf->page) 4388 folio = page_folio(vmf->page); 4389 4390 /* 4391 * Shared mapping: we are guaranteed to have VM_WRITE and 4392 * FAULT_FLAG_WRITE set at this point. 4393 */ 4394 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) { 4395 /* 4396 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a 4397 * VM_PFNMAP VMA. FS DAX also wants ops->pfn_mkwrite called. 4398 * 4399 * We should not cow pages in a shared writeable mapping. 4400 * Just mark the pages writable and/or call ops->pfn_mkwrite. 4401 */ 4402 if (!vmf->page || is_fsdax_page(vmf->page)) { 4403 vmf->page = NULL; 4404 return wp_pfn_shared(vmf); 4405 } 4406 return wp_page_shared(vmf, folio); 4407 } 4408 4409 /* 4410 * Private mapping: create an exclusive anonymous page copy if reuse 4411 * is impossible. We might miss VM_WRITE for FOLL_FORCE handling. 4412 * 4413 * If we encounter a page that is marked exclusive, we must reuse 4414 * the page without further checks. 4415 */ 4416 if (folio && folio_test_anon(folio) && 4417 (PageAnonExclusive(vmf->page) || wp_can_reuse_anon_folio(folio, vma))) { 4418 if (!PageAnonExclusive(vmf->page)) 4419 SetPageAnonExclusive(vmf->page); 4420 if (unlikely(unshare)) { 4421 pte_unmap_unlock(vmf->pte, vmf->ptl); 4422 return 0; 4423 } 4424 wp_page_reuse(vmf, folio); 4425 return 0; 4426 } 4427 /* 4428 * Ok, we need to copy. Oh, well.. 4429 */ 4430 if (folio) 4431 folio_get(folio); 4432 4433 pte_unmap_unlock(vmf->pte, vmf->ptl); 4434 #ifdef CONFIG_KSM 4435 if (folio && folio_test_ksm(folio)) 4436 count_vm_event(COW_KSM); 4437 #endif 4438 return wp_page_copy(vmf); 4439 } 4440 4441 static inline void unmap_mapping_range_tree(struct address_space *mapping, 4442 pgoff_t first_index, 4443 pgoff_t last_index, 4444 struct zap_details *details) 4445 { 4446 struct vm_area_struct *vma; 4447 struct mmu_gather tlb; 4448 4449 mapping_rmap_tree_foreach(vma, mapping, first_index, last_index) { 4450 const pgoff_t start_idx = max(first_index, vma_start_pgoff(vma)); 4451 const pgoff_t end_idx = min(last_index, vma_last_pgoff(vma)) + 1; 4452 const pgoff_t offset = start_idx - vma_start_pgoff(vma); 4453 const unsigned long offset_bytes = offset << PAGE_SHIFT; 4454 const unsigned long start = vma->vm_start + offset_bytes; 4455 const unsigned long size = (end_idx - start_idx) << PAGE_SHIFT; 4456 4457 tlb_gather_mmu(&tlb, vma->vm_mm); 4458 zap_vma_range_batched(&tlb, vma, start, size, details); 4459 tlb_finish_mmu(&tlb); 4460 } 4461 } 4462 4463 /** 4464 * unmap_mapping_folio() - Unmap single folio from processes. 4465 * @folio: The locked folio to be unmapped. 4466 * 4467 * Unmap this folio from any userspace process which still has it mmaped. 4468 * Typically, for efficiency, the range of nearby pages has already been 4469 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once 4470 * truncation or invalidation holds the lock on a folio, it may find that 4471 * the page has been remapped again: and then uses unmap_mapping_folio() 4472 * to unmap it finally. 4473 */ 4474 void unmap_mapping_folio(struct folio *folio) 4475 { 4476 struct address_space *mapping = folio->mapping; 4477 struct zap_details details = { }; 4478 pgoff_t first_index; 4479 pgoff_t last_index; 4480 4481 VM_BUG_ON(!folio_test_locked(folio)); 4482 4483 first_index = folio->index; 4484 last_index = folio_next_index(folio) - 1; 4485 4486 details.skip_cows = true; 4487 details.single_folio = folio; 4488 details.zap_flags = ZAP_FLAG_DROP_MARKER; 4489 4490 i_mmap_lock_read(mapping); 4491 if (unlikely(mapping_mapped(mapping))) 4492 unmap_mapping_range_tree(mapping, first_index, 4493 last_index, &details); 4494 i_mmap_unlock_read(mapping); 4495 } 4496 4497 /** 4498 * unmap_mapping_pages() - Unmap pages from processes. 4499 * @mapping: The address space containing pages to be unmapped. 4500 * @start: Index of first page to be unmapped. 4501 * @nr: Number of pages to be unmapped. 0 to unmap to end of file. 4502 * @even_cows: Whether to unmap even private COWed pages. 4503 * 4504 * Unmap the pages in this address space from any userspace process which 4505 * has them mmaped. Generally, you want to remove COWed pages as well when 4506 * a file is being truncated, but not when invalidating pages from the page 4507 * cache. 4508 */ 4509 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start, 4510 pgoff_t nr, bool even_cows) 4511 { 4512 struct zap_details details = { }; 4513 pgoff_t first_index = start; 4514 pgoff_t last_index = start + nr - 1; 4515 4516 details.skip_cows = !even_cows; 4517 if (last_index < first_index) 4518 last_index = ULONG_MAX; 4519 4520 i_mmap_lock_read(mapping); 4521 if (unlikely(mapping_mapped(mapping))) 4522 unmap_mapping_range_tree(mapping, first_index, 4523 last_index, &details); 4524 i_mmap_unlock_read(mapping); 4525 } 4526 EXPORT_SYMBOL_GPL(unmap_mapping_pages); 4527 4528 /** 4529 * unmap_mapping_range - unmap the portion of all mmaps in the specified 4530 * address_space corresponding to the specified byte range in the underlying 4531 * file. 4532 * 4533 * @mapping: the address space containing mmaps to be unmapped. 4534 * @holebegin: byte in first page to unmap, relative to the start of 4535 * the underlying file. This will be rounded down to a PAGE_SIZE 4536 * boundary. Note that this is different from truncate_pagecache(), which 4537 * must keep the partial page. In contrast, we must get rid of 4538 * partial pages. 4539 * @holelen: size of prospective hole in bytes. This will be rounded 4540 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the 4541 * end of the file. 4542 * @even_cows: 1 when truncating a file, unmap even private COWed pages; 4543 * but 0 when invalidating pagecache, don't throw away private data. 4544 */ 4545 void unmap_mapping_range(struct address_space *mapping, 4546 loff_t const holebegin, loff_t const holelen, int even_cows) 4547 { 4548 pgoff_t hba = (pgoff_t)(holebegin) >> PAGE_SHIFT; 4549 pgoff_t hlen = ((pgoff_t)(holelen) + PAGE_SIZE - 1) >> PAGE_SHIFT; 4550 4551 /* Check for overflow. */ 4552 if (sizeof(holelen) > sizeof(hlen)) { 4553 long long holeend = 4554 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; 4555 if (holeend & ~(long long)ULONG_MAX) 4556 hlen = ULONG_MAX - hba + 1; 4557 } 4558 4559 unmap_mapping_pages(mapping, hba, hlen, even_cows); 4560 } 4561 EXPORT_SYMBOL(unmap_mapping_range); 4562 4563 /* 4564 * Restore a potential device exclusive pte to a working pte entry 4565 */ 4566 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf) 4567 { 4568 struct folio *folio = page_folio(vmf->page); 4569 struct vm_area_struct *vma = vmf->vma; 4570 struct mmu_notifier_range range; 4571 vm_fault_t ret; 4572 4573 /* 4574 * We need a reference to lock the folio because we don't hold 4575 * the PTL so a racing thread can remove the device-exclusive 4576 * entry and unmap it. If the folio is free the entry must 4577 * have been removed already. If it happens to have already 4578 * been re-allocated after being freed all we do is lock and 4579 * unlock it. 4580 */ 4581 if (!folio_try_get(folio)) 4582 return 0; 4583 4584 ret = folio_lock_or_retry(folio, vmf); 4585 if (ret) { 4586 folio_put(folio); 4587 return ret; 4588 } 4589 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_CLEAR, 0, 4590 vma->vm_mm, vmf->address & PAGE_MASK, 4591 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL); 4592 mmu_notifier_invalidate_range_start(&range); 4593 4594 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 4595 &vmf->ptl); 4596 if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) 4597 restore_exclusive_pte(vma, folio, vmf->page, vmf->address, 4598 vmf->pte, vmf->orig_pte); 4599 4600 if (vmf->pte) 4601 pte_unmap_unlock(vmf->pte, vmf->ptl); 4602 folio_unlock(folio); 4603 folio_put(folio); 4604 4605 mmu_notifier_invalidate_range_end(&range); 4606 return 0; 4607 } 4608 4609 /* 4610 * Check if we should call folio_free_swap to free the swap cache. 4611 * folio_free_swap only frees the swap cache to release the slot if swap 4612 * count is zero, so we don't need to check the swap count here. 4613 */ 4614 static inline bool should_try_to_free_swap(struct swap_info_struct *si, 4615 struct folio *folio, 4616 struct vm_area_struct *vma, 4617 bool exclusive, 4618 unsigned int fault_flags) 4619 { 4620 if (!folio_test_swapcache(folio)) 4621 return false; 4622 /* 4623 * Always try to free swap cache for SWP_SYNCHRONOUS_IO devices. Swap 4624 * cache can help save some IO or memory overhead, but these devices 4625 * are fast, and meanwhile, swap cache pinning the slot deferring the 4626 * release of metadata or fragmentation is a more critical issue. 4627 */ 4628 if (data_race(si->flags & SWP_SYNCHRONOUS_IO)) 4629 return true; 4630 if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) || 4631 folio_test_mlocked(folio)) 4632 return true; 4633 4634 /* 4635 * Free the swapcache only if we are the exclusive user and 4636 * this is a write fault. 4637 */ 4638 return (fault_flags & FAULT_FLAG_WRITE) && exclusive; 4639 } 4640 4641 static vm_fault_t pte_marker_clear(struct vm_fault *vmf) 4642 { 4643 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, 4644 vmf->address, &vmf->ptl); 4645 if (!vmf->pte) 4646 return 0; 4647 /* 4648 * Be careful so that we will only recover a special uffd-wp pte into a 4649 * none pte. Otherwise it means the pte could have changed, so retry. 4650 * 4651 * This should also cover the case where e.g. the pte changed 4652 * quickly from a PTE_MARKER_UFFD_WP into PTE_MARKER_POISONED. 4653 * So pte_is_marker() check is not enough to safely drop the pte. 4654 */ 4655 if (pte_same(vmf->orig_pte, ptep_get(vmf->pte))) 4656 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte); 4657 pte_unmap_unlock(vmf->pte, vmf->ptl); 4658 return 0; 4659 } 4660 4661 static vm_fault_t do_pte_missing(struct vm_fault *vmf) 4662 { 4663 if (vma_is_anonymous(vmf->vma)) 4664 return do_anonymous_page(vmf); 4665 else 4666 return do_fault(vmf); 4667 } 4668 4669 /* 4670 * This is actually a page-missing access, but with uffd-wp special pte 4671 * installed. It means this pte was wr-protected before being unmapped. 4672 */ 4673 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf) 4674 { 4675 /* 4676 * Just in case there're leftover special ptes even after the region 4677 * got unregistered - we can simply clear them. 4678 */ 4679 if (unlikely(!userfaultfd_wp(vmf->vma))) 4680 return pte_marker_clear(vmf); 4681 4682 return do_pte_missing(vmf); 4683 } 4684 4685 static vm_fault_t handle_pte_marker(struct vm_fault *vmf) 4686 { 4687 const softleaf_t entry = softleaf_from_pte(vmf->orig_pte); 4688 const pte_marker marker = softleaf_to_marker(entry); 4689 4690 /* 4691 * PTE markers should never be empty. If anything weird happened, 4692 * the best thing to do is to kill the process along with its mm. 4693 */ 4694 if (WARN_ON_ONCE(!marker)) 4695 return VM_FAULT_SIGBUS; 4696 4697 /* Higher priority than uffd-wp when data corrupted */ 4698 if (marker & PTE_MARKER_POISONED) 4699 return VM_FAULT_HWPOISON; 4700 4701 /* Hitting a guard page is always a fatal condition. */ 4702 if (marker & PTE_MARKER_GUARD) 4703 return VM_FAULT_SIGSEGV; 4704 4705 if (softleaf_is_uffd_wp_marker(entry)) 4706 return pte_marker_handle_uffd_wp(vmf); 4707 4708 /* This is an unknown pte marker */ 4709 return VM_FAULT_SIGBUS; 4710 } 4711 4712 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4713 /* 4714 * Check if the PTEs within a range are contiguous swap entries. 4715 */ 4716 static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages) 4717 { 4718 unsigned long addr; 4719 int idx; 4720 pte_t pte; 4721 4722 addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE); 4723 idx = (vmf->address - addr) / PAGE_SIZE; 4724 pte = ptep_get(ptep); 4725 4726 if (!pte_same(pte, pte_move_swp_offset(vmf->orig_pte, -idx))) 4727 return false; 4728 /* 4729 * swap_read_folio() can't handle the case a large folio is hybridly 4730 * from different backends. And they are likely corner cases. Similar 4731 * things might be added once zswap support large folios. 4732 */ 4733 if (swap_pte_batch(ptep, nr_pages, pte) != nr_pages) 4734 return false; 4735 return true; 4736 } 4737 4738 static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset, 4739 unsigned long addr, 4740 unsigned long orders) 4741 { 4742 int order, nr; 4743 4744 order = highest_order(orders); 4745 4746 /* 4747 * To swap in a THP with nr pages, we require that its first swap_offset 4748 * is aligned with that number, as it was when the THP was swapped out. 4749 * This helps filter out most invalid entries. 4750 */ 4751 while (orders) { 4752 nr = 1 << order; 4753 if ((addr >> PAGE_SHIFT) % nr == swp_offset % nr) 4754 break; 4755 order = next_order(&orders, order); 4756 } 4757 4758 return orders; 4759 } 4760 4761 static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf) 4762 { 4763 struct vm_area_struct *vma = vmf->vma; 4764 unsigned long orders; 4765 unsigned long addr; 4766 softleaf_t entry; 4767 spinlock_t *ptl; 4768 pte_t *pte; 4769 int order; 4770 4771 /* 4772 * If uffd is active for the vma we need per-page fault fidelity to 4773 * maintain the uffd semantics. 4774 */ 4775 if (unlikely(userfaultfd_armed(vma))) 4776 return 0; 4777 4778 /* 4779 * A large swapped out folio could be partially or fully in zswap. We 4780 * lack handling for such cases, so fallback to swapping in order-0 4781 * folio. 4782 */ 4783 if (!zswap_never_enabled()) 4784 return 0; 4785 4786 entry = softleaf_from_pte(vmf->orig_pte); 4787 /* 4788 * Get a list of all the (large) orders below PMD_ORDER that are enabled 4789 * and suitable for swapping THP. 4790 */ 4791 orders = thp_vma_allowable_orders(vma, vma->vm_flags, TVA_PAGEFAULT, 4792 BIT(PMD_ORDER) - 1); 4793 orders = thp_vma_suitable_orders(vma, vmf->address, orders); 4794 orders = thp_swap_suitable_orders(swp_offset(entry), 4795 vmf->address, orders); 4796 4797 if (!orders) 4798 return 0; 4799 4800 pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, 4801 vmf->address & PMD_MASK, &ptl); 4802 if (unlikely(!pte)) 4803 return 0; 4804 4805 /* 4806 * For do_swap_page, find the highest order where the aligned range is 4807 * completely swap entries with contiguous swap offsets. 4808 */ 4809 order = highest_order(orders); 4810 while (orders) { 4811 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order); 4812 if (can_swapin_thp(vmf, pte + pte_index(addr), 1 << order)) 4813 break; 4814 order = next_order(&orders, order); 4815 } 4816 4817 pte_unmap_unlock(pte, ptl); 4818 4819 return orders; 4820 } 4821 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */ 4822 static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf) 4823 { 4824 return 0; 4825 } 4826 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 4827 4828 /* Sanity check that a folio is fully exclusive */ 4829 static void check_swap_exclusive(struct folio *folio, swp_entry_t entry, 4830 unsigned int nr_pages) 4831 { 4832 /* Called under PT locked and folio locked, the swap count is stable */ 4833 do { 4834 VM_WARN_ON_ONCE_FOLIO(__swap_count(entry) != 1, folio); 4835 entry.val++; 4836 } while (--nr_pages); 4837 } 4838 4839 /* 4840 * We enter with either the VMA lock or the mmap_lock held (see 4841 * FAULT_FLAG_VMA_LOCK), and pte mapped but not yet locked. 4842 * We return with pte unmapped and unlocked. 4843 * 4844 * When returning, the lock may have been released in the same cases 4845 * as done by filemap_fault(). 4846 */ 4847 vm_fault_t do_swap_page(struct vm_fault *vmf) 4848 { 4849 struct vm_area_struct *vma = vmf->vma; 4850 struct folio *swapcache = NULL, *folio; 4851 struct page *page; 4852 struct swap_info_struct *si = NULL; 4853 rmap_t rmap_flags = RMAP_NONE; 4854 bool exclusive = false; 4855 bool rwp_restore = false; 4856 softleaf_t entry; 4857 pte_t pte; 4858 vm_fault_t ret = 0; 4859 int nr_pages; 4860 unsigned long page_idx; 4861 unsigned long address; 4862 pte_t *ptep; 4863 4864 if (!pte_unmap_same(vmf)) 4865 goto out; 4866 4867 entry = softleaf_from_pte(vmf->orig_pte); 4868 if (unlikely(!softleaf_is_swap(entry))) { 4869 if (softleaf_is_migration(entry)) { 4870 migration_entry_wait(vma->vm_mm, vmf->pmd, 4871 vmf->address); 4872 } else if (softleaf_is_device_exclusive(entry)) { 4873 vmf->page = softleaf_to_page(entry); 4874 ret = remove_device_exclusive_entry(vmf); 4875 } else if (softleaf_is_device_private(entry)) { 4876 if (vmf->flags & FAULT_FLAG_VMA_LOCK) { 4877 /* 4878 * migrate_to_ram is not yet ready to operate 4879 * under VMA lock. 4880 */ 4881 vma_end_read(vma); 4882 ret = VM_FAULT_RETRY; 4883 goto out; 4884 } 4885 4886 vmf->page = softleaf_to_page(entry); 4887 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4888 vmf->address, &vmf->ptl); 4889 if (unlikely(!vmf->pte || 4890 !pte_same(ptep_get(vmf->pte), 4891 vmf->orig_pte))) 4892 goto unlock; 4893 4894 /* 4895 * Get a folio reference while we know the folio can't 4896 * be freed. 4897 */ 4898 folio = page_folio(vmf->page); 4899 if (folio_trylock(folio)) { 4900 struct dev_pagemap *pgmap; 4901 4902 folio_get(folio); 4903 pte_unmap_unlock(vmf->pte, vmf->ptl); 4904 pgmap = page_pgmap(vmf->page); 4905 ret = pgmap->ops->migrate_to_ram(vmf); 4906 /* migrate_to_ram() might have split the folio. */ 4907 folio = page_folio(vmf->page); 4908 folio_unlock(folio); 4909 folio_put(folio); 4910 } else { 4911 pte_unmap(vmf->pte); 4912 softleaf_entry_wait_on_locked(entry, vmf->ptl); 4913 } 4914 } else if (softleaf_is_hwpoison(entry)) { 4915 ret = VM_FAULT_HWPOISON; 4916 } else if (softleaf_is_marker(entry)) { 4917 ret = handle_pte_marker(vmf); 4918 } else { 4919 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL); 4920 ret = VM_FAULT_SIGBUS; 4921 } 4922 goto out; 4923 } 4924 4925 /* Prevent swapoff from happening to us, and reject a bad entry. */ 4926 si = get_swap_device(entry); 4927 if (IS_ERR_OR_NULL(si)) { 4928 if (IS_ERR(si)) 4929 ret = VM_FAULT_SIGBUS; 4930 goto out; 4931 } 4932 4933 folio = swap_cache_get_folio(entry); 4934 if (folio) 4935 swap_update_readahead(folio, vma, vmf->address); 4936 if (!folio) { 4937 /* Swapin bypasses readahead for SWP_SYNCHRONOUS_IO devices */ 4938 if (data_race(si->flags & SWP_SYNCHRONOUS_IO)) 4939 folio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE, 4940 thp_swapin_suitable_orders(vmf) | BIT(0), 4941 vmf, NULL, 0); 4942 else 4943 folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vmf); 4944 4945 if (IS_ERR_OR_NULL(folio)) { 4946 /* 4947 * Back out if somebody else faulted in this pte 4948 * while we released the pte lock. 4949 */ 4950 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4951 vmf->address, &vmf->ptl); 4952 if (likely(vmf->pte && 4953 pte_same(ptep_get(vmf->pte), vmf->orig_pte))) 4954 ret = VM_FAULT_OOM; 4955 folio = NULL; 4956 goto unlock; 4957 } 4958 4959 /* Had to read the page from swap area: Major fault */ 4960 ret = VM_FAULT_MAJOR; 4961 count_vm_event(PGMAJFAULT); 4962 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT); 4963 } 4964 4965 swapcache = folio; 4966 ret |= folio_lock_or_retry(folio, vmf); 4967 if (ret & VM_FAULT_RETRY) 4968 goto out_release; 4969 4970 page = folio_file_page(folio, swp_offset(entry)); 4971 /* 4972 * Make sure folio_free_swap() or swapoff did not release the 4973 * swapcache from under us. The page pin, and pte_same test 4974 * below, are not enough to exclude that. Even if it is still 4975 * swapcache, we need to check that the page's swap has not 4976 * changed. 4977 */ 4978 if (unlikely(!folio_matches_swap_entry(folio, entry))) 4979 goto out_page; 4980 4981 if (unlikely(PageHWPoison(page))) { 4982 /* 4983 * hwpoisoned dirty swapcache pages are kept for killing 4984 * owner processes (which may be unknown at hwpoison time) 4985 */ 4986 ret = VM_FAULT_HWPOISON; 4987 goto out_page; 4988 } 4989 4990 /* 4991 * KSM sometimes has to copy on read faults, for example, if 4992 * folio->index of non-ksm folios would be nonlinear inside the 4993 * anon VMA -- the ksm flag is lost on actual swapout. 4994 */ 4995 folio = ksm_might_need_to_copy(folio, vma, vmf->address); 4996 if (unlikely(!folio)) { 4997 ret = VM_FAULT_OOM; 4998 folio = swapcache; 4999 goto out_page; 5000 } else if (unlikely(folio == ERR_PTR(-EHWPOISON))) { 5001 ret = VM_FAULT_HWPOISON; 5002 folio = swapcache; 5003 goto out_page; 5004 } else if (folio != swapcache) 5005 page = folio_page(folio, 0); 5006 5007 folio_throttle_swaprate(folio, GFP_KERNEL); 5008 5009 /* 5010 * Back out if somebody else already faulted in this pte. 5011 */ 5012 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 5013 &vmf->ptl); 5014 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) 5015 goto out_nomap; 5016 5017 if (unlikely(!folio_test_uptodate(folio))) { 5018 ret = VM_FAULT_SIGBUS; 5019 goto out_nomap; 5020 } 5021 5022 nr_pages = 1; 5023 page_idx = 0; 5024 address = vmf->address; 5025 ptep = vmf->pte; 5026 if (folio_test_large(folio) && folio_test_swapcache(folio)) { 5027 int nr = folio_nr_pages(folio); 5028 unsigned long idx = folio_page_idx(folio, page); 5029 unsigned long folio_start = address - idx * PAGE_SIZE; 5030 unsigned long folio_end = folio_start + nr * PAGE_SIZE; 5031 pte_t *folio_ptep; 5032 pte_t folio_pte; 5033 5034 if (unlikely(folio_start < max(address & PMD_MASK, vma->vm_start))) 5035 goto check_folio; 5036 if (unlikely(folio_end > pmd_addr_end(address, vma->vm_end))) 5037 goto check_folio; 5038 5039 folio_ptep = vmf->pte - idx; 5040 folio_pte = ptep_get(folio_ptep); 5041 if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) || 5042 swap_pte_batch(folio_ptep, nr, folio_pte) != nr) 5043 goto check_folio; 5044 5045 page_idx = idx; 5046 address = folio_start; 5047 ptep = folio_ptep; 5048 nr_pages = nr; 5049 entry = folio->swap; 5050 page = &folio->page; 5051 } 5052 5053 check_folio: 5054 /* 5055 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte 5056 * must never point at an anonymous page in the swapcache that is 5057 * PG_anon_exclusive. Sanity check that this holds and especially, that 5058 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity 5059 * check after taking the PT lock and making sure that nobody 5060 * concurrently faulted in this page and set PG_anon_exclusive. 5061 */ 5062 BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio)); 5063 BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page)); 5064 5065 /* 5066 * If a large folio already belongs to anon mapping, then we 5067 * can just go on and map it partially. 5068 * If not, with the large swapin check above failing, the page table 5069 * have changed, so sub pages might got charged to the wrong cgroup, 5070 * or even should be shmem. So we have to free it and fallback. 5071 * Nothing should have touched it, both anon and shmem checks if a 5072 * large folio is fully appliable before use. 5073 * 5074 * This will be removed once we unify folio allocation in the swap cache 5075 * layer, where allocation of a folio stabilizes the swap entries. 5076 */ 5077 if (!folio_test_anon(folio) && folio_test_large(folio) && 5078 nr_pages != folio_nr_pages(folio)) { 5079 if (!WARN_ON_ONCE(folio_test_dirty(folio))) 5080 swap_cache_del_folio(folio); 5081 goto out_nomap; 5082 } 5083 5084 /* 5085 * Check under PT lock (to protect against concurrent fork() sharing 5086 * the swap entry concurrently) for certainly exclusive pages. 5087 */ 5088 if (!folio_test_ksm(folio)) { 5089 /* 5090 * The can_swapin_thp check above ensures all PTE have 5091 * same exclusiveness. Checking just one PTE is fine. 5092 */ 5093 exclusive = pte_swp_exclusive(vmf->orig_pte); 5094 if (exclusive) 5095 check_swap_exclusive(folio, entry, nr_pages); 5096 if (folio != swapcache) { 5097 /* 5098 * We have a fresh page that is not exposed to the 5099 * swapcache -> certainly exclusive. 5100 */ 5101 exclusive = true; 5102 } else if (exclusive && folio_test_writeback(folio) && 5103 data_race(si->flags & SWP_STABLE_WRITES)) { 5104 /* 5105 * This is tricky: not all swap backends support 5106 * concurrent page modifications while under writeback. 5107 * 5108 * So if we stumble over such a page in the swapcache 5109 * we must not set the page exclusive, otherwise we can 5110 * map it writable without further checks and modify it 5111 * while still under writeback. 5112 * 5113 * For these problematic swap backends, simply drop the 5114 * exclusive marker: this is perfectly fine as we start 5115 * writeback only if we fully unmapped the page and 5116 * there are no unexpected references on the page after 5117 * unmapping succeeded. After fully unmapped, no 5118 * further GUP references (FOLL_GET and FOLL_PIN) can 5119 * appear, so dropping the exclusive marker and mapping 5120 * it only R/O is fine. 5121 */ 5122 exclusive = false; 5123 } 5124 } 5125 5126 /* 5127 * Some architectures may have to restore extra metadata to the page 5128 * when reading from swap. This metadata may be indexed by swap entry 5129 * so this must be called before folio_put_swap(). 5130 */ 5131 arch_swap_restore(folio_swap(entry, folio), folio); 5132 5133 add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages); 5134 add_mm_counter(vma->vm_mm, MM_SWAPENTS, -nr_pages); 5135 pte = mk_pte(page, vma->vm_page_prot); 5136 if (pte_swp_soft_dirty(vmf->orig_pte)) 5137 pte = pte_mksoft_dirty(pte); 5138 if (pte_swp_uffd(vmf->orig_pte)) 5139 pte = pte_mkuffd(pte); 5140 5141 /* 5142 * A page reclaimed while RWP-protected carries the uffd bit on 5143 * its swap entry. Re-apply PAGE_NONE on swap-in so the first access 5144 * still traps as an RWP fault. pte_modify() preserves _PAGE_UFFD. 5145 */ 5146 if (pte_swp_uffd(vmf->orig_pte) && userfaultfd_rwp(vma)) { 5147 pte = pte_modify(pte, PAGE_NONE); 5148 rwp_restore = true; 5149 } 5150 5151 /* 5152 * Similar logic as in do_wp_page(); however, optimize for pages that 5153 * are certainly exclusive. 5154 * 5155 * Skip the write upgrade for an RWP-restored pte: it must stay 5156 * PROT_NONE so the access retries through the RWP fault path 5157 * (do_uffd_rwp()) rather than being made writable here. 5158 */ 5159 if (exclusive) { 5160 if (!rwp_restore && 5161 (vma->vm_flags & VM_WRITE) && !userfaultfd_pte_wp(vma, pte) && 5162 !pte_needs_soft_dirty_wp(vma, pte)) { 5163 pte = pte_mkwrite(pte, vma); 5164 if (vmf->flags & FAULT_FLAG_WRITE) 5165 pte = pte_mkdirty(pte); 5166 } 5167 rmap_flags |= RMAP_EXCLUSIVE; 5168 } 5169 folio_ref_add(folio, nr_pages - 1); 5170 flush_icache_pages(vma, page, nr_pages); 5171 vmf->orig_pte = pte_advance_pfn(pte, page_idx); 5172 5173 /* ksm created a completely new copy */ 5174 if (unlikely(folio != swapcache)) { 5175 folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE); 5176 folio_add_lru_vma(folio, vma); 5177 folio_put_swap(swapcache, NULL); 5178 } else if (!folio_test_anon(folio)) { 5179 /* 5180 * We currently only expect !anon folios that are fully 5181 * mappable. See the comment after can_swapin_thp above. 5182 */ 5183 VM_WARN_ON_ONCE_FOLIO(folio_nr_pages(folio) != nr_pages, folio); 5184 VM_WARN_ON_ONCE_FOLIO(folio_mapped(folio), folio); 5185 folio_add_new_anon_rmap(folio, vma, address, rmap_flags); 5186 folio_put_swap(folio, NULL); 5187 } else { 5188 VM_WARN_ON_ONCE(nr_pages != 1 && nr_pages != folio_nr_pages(folio)); 5189 folio_add_anon_rmap_ptes(folio, page, nr_pages, vma, address, 5190 rmap_flags); 5191 folio_put_swap(folio, nr_pages == 1 ? page : NULL); 5192 } 5193 5194 VM_BUG_ON(!folio_test_anon(folio) || 5195 (pte_write(pte) && !PageAnonExclusive(page))); 5196 set_ptes(vma->vm_mm, address, ptep, pte, nr_pages); 5197 arch_do_swap_page_nr(vma->vm_mm, vma, address, 5198 pte, pte, nr_pages); 5199 5200 /* 5201 * Remove the swap entry and conditionally try to free up the swapcache. 5202 * Do it after mapping, so raced page faults will likely see the folio 5203 * in swap cache and wait on the folio lock. 5204 */ 5205 if (should_try_to_free_swap(si, folio, vma, exclusive, vmf->flags)) 5206 folio_free_swap(folio); 5207 5208 folio_unlock(folio); 5209 if (unlikely(folio != swapcache)) { 5210 /* 5211 * Hold the lock to avoid the swap entry to be reused 5212 * until we take the PT lock for the pte_same() check 5213 * (to avoid false positives from pte_same). For 5214 * further safety release the lock after the folio_put_swap 5215 * so that the swap count won't change under a 5216 * parallel locked swapcache. 5217 */ 5218 folio_unlock(swapcache); 5219 folio_put(swapcache); 5220 } 5221 5222 /* 5223 * For an RWP-restored pte, leave it PROT_NONE and let the write 5224 * retry through the RWP fault path; do not COW it here, which would 5225 * drop the marker for a non-exclusive page. 5226 */ 5227 if ((vmf->flags & FAULT_FLAG_WRITE) && !pte_write(pte) && !rwp_restore) { 5228 ret |= do_wp_page(vmf); 5229 if (ret & VM_FAULT_ERROR) 5230 ret &= VM_FAULT_ERROR; 5231 goto out; 5232 } 5233 5234 /* No need to invalidate - it was non-present before */ 5235 update_mmu_cache_range(vmf, vma, address, ptep, nr_pages); 5236 unlock: 5237 if (vmf->pte) 5238 pte_unmap_unlock(vmf->pte, vmf->ptl); 5239 out: 5240 if (!IS_ERR_OR_NULL(si)) 5241 put_swap_device(si); 5242 return ret; 5243 out_nomap: 5244 if (vmf->pte) 5245 pte_unmap_unlock(vmf->pte, vmf->ptl); 5246 out_page: 5247 if (folio_test_swapcache(folio)) 5248 folio_free_swap(folio); 5249 folio_unlock(folio); 5250 out_release: 5251 folio_put(folio); 5252 if (folio != swapcache) { 5253 folio_unlock(swapcache); 5254 folio_put(swapcache); 5255 } 5256 if (si) 5257 put_swap_device(si); 5258 return ret; 5259 } 5260 5261 static bool pte_range_none(pte_t *pte, int nr_pages) 5262 { 5263 int i; 5264 5265 for (i = 0; i < nr_pages; i++) { 5266 if (!pte_none(ptep_get_lockless(pte + i))) 5267 return false; 5268 } 5269 5270 return true; 5271 } 5272 5273 static struct folio *alloc_anon_folio(struct vm_fault *vmf) 5274 { 5275 struct vm_area_struct *vma = vmf->vma; 5276 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5277 unsigned long orders; 5278 struct folio *folio; 5279 unsigned long addr; 5280 pte_t *pte; 5281 gfp_t gfp; 5282 int order; 5283 5284 /* 5285 * If uffd is active for the vma we need per-page fault fidelity to 5286 * maintain the uffd semantics. 5287 */ 5288 if (unlikely(userfaultfd_armed(vma))) 5289 goto fallback; 5290 5291 /* 5292 * Get a list of all the (large) orders below PMD_ORDER that are enabled 5293 * for this vma. Then filter out the orders that can't be allocated over 5294 * the faulting address and still be fully contained in the vma. 5295 */ 5296 orders = thp_vma_allowable_orders(vma, vma->vm_flags, TVA_PAGEFAULT, 5297 BIT(PMD_ORDER) - 1); 5298 orders = thp_vma_suitable_orders(vma, vmf->address, orders); 5299 5300 if (!orders) 5301 goto fallback; 5302 5303 pte = pte_offset_map(vmf->pmd, vmf->address & PMD_MASK); 5304 if (!pte) 5305 return ERR_PTR(-EAGAIN); 5306 5307 /* 5308 * Find the highest order where the aligned range is completely 5309 * pte_none(). Note that all remaining orders will be completely 5310 * pte_none(). 5311 */ 5312 order = highest_order(orders); 5313 while (orders) { 5314 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order); 5315 if (pte_range_none(pte + pte_index(addr), 1 << order)) 5316 break; 5317 order = next_order(&orders, order); 5318 } 5319 5320 pte_unmap(pte); 5321 5322 if (!orders) 5323 goto fallback; 5324 5325 /* Try allocating the highest of the remaining orders. */ 5326 gfp = vma_thp_gfp_mask(vma); 5327 while (orders) { 5328 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order); 5329 folio = vma_alloc_folio(gfp, order, vma, addr); 5330 if (!folio) 5331 goto next; 5332 if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) { 5333 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE); 5334 folio_put(folio); 5335 goto next; 5336 } 5337 if (order > 1 && folio_memcg_alloc_deferred(folio)) { 5338 folio_put(folio); 5339 goto fallback; 5340 } 5341 folio_throttle_swaprate(folio, gfp); 5342 /* 5343 * When a folio is not zeroed during allocation 5344 * (__GFP_ZERO not used) or user folios require special 5345 * handling, folio_zero_user() is used to make sure 5346 * that the page corresponding to the faulting address 5347 * will be hot in the cache after zeroing. 5348 */ 5349 if (user_alloc_needs_zeroing()) 5350 folio_zero_user(folio, vmf->address); 5351 return folio; 5352 next: 5353 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK); 5354 order = next_order(&orders, order); 5355 } 5356 5357 fallback: 5358 #endif 5359 return folio_prealloc(vma->vm_mm, vma, vmf->address, true); 5360 } 5361 5362 void map_anon_folio_pte_nopf(struct folio *folio, pte_t *pte, 5363 struct vm_area_struct *vma, unsigned long addr, 5364 bool uffd_wp) 5365 { 5366 const unsigned int nr_pages = folio_nr_pages(folio); 5367 pte_t entry = folio_mk_pte(folio, vma->vm_page_prot); 5368 5369 entry = pte_sw_mkyoung(entry); 5370 5371 if (vma->vm_flags & VM_WRITE) 5372 entry = pte_mkwrite(pte_mkdirty(entry), vma); 5373 if (uffd_wp) 5374 entry = pte_mkuffd(entry); 5375 5376 folio_ref_add(folio, nr_pages - 1); 5377 folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); 5378 folio_add_lru_vma(folio, vma); 5379 set_ptes(vma->vm_mm, addr, pte, entry, nr_pages); 5380 update_mmu_cache_range(NULL, vma, addr, pte, nr_pages); 5381 } 5382 5383 static void map_anon_folio_pte_pf(struct folio *folio, pte_t *pte, 5384 struct vm_area_struct *vma, unsigned long addr, bool uffd_wp) 5385 { 5386 const unsigned int order = folio_order(folio); 5387 5388 map_anon_folio_pte_nopf(folio, pte, vma, addr, uffd_wp); 5389 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1L << order); 5390 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_ALLOC); 5391 } 5392 5393 /* 5394 * We enter with either the VMA lock or the mmap_lock held (see 5395 * FAULT_FLAG_VMA_LOCK), and pte unmapped and unlocked. 5396 * We return with the lock still held, but pte unmapped and unlocked. 5397 * If VM_FAULT_RETRY is returned, the lock may have been released. 5398 */ 5399 static vm_fault_t do_anonymous_page(struct vm_fault *vmf) 5400 { 5401 struct vm_area_struct *vma = vmf->vma; 5402 unsigned long addr = vmf->address; 5403 struct folio *folio; 5404 vm_fault_t ret = 0; 5405 int nr_pages; 5406 pte_t entry; 5407 5408 /* File mapping without ->vm_ops ? */ 5409 if (vma->vm_flags & VM_SHARED) 5410 return VM_FAULT_SIGBUS; 5411 5412 /* 5413 * Use pte_alloc() instead of pte_alloc_map(), so that OOM can 5414 * be distinguished from a transient failure of pte_offset_map(). 5415 */ 5416 if (pte_alloc(vma->vm_mm, vmf->pmd)) 5417 return VM_FAULT_OOM; 5418 5419 /* Use the zero-page for reads */ 5420 if (!(vmf->flags & FAULT_FLAG_WRITE) && 5421 !mm_forbids_zeropage(vma->vm_mm)) { 5422 entry = pte_mkspecial(pfn_pte(zero_pfn(vmf->address), 5423 vma->vm_page_prot)); 5424 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 5425 vmf->address, &vmf->ptl); 5426 if (!vmf->pte) 5427 goto unlock; 5428 if (vmf_pte_changed(vmf)) { 5429 update_mmu_tlb(vma, vmf->address, vmf->pte); 5430 goto unlock; 5431 } 5432 ret = check_stable_address_space(vma->vm_mm); 5433 if (ret) 5434 goto unlock; 5435 /* Deliver the page fault to userland, check inside PT lock */ 5436 if (userfaultfd_missing(vma)) { 5437 pte_unmap_unlock(vmf->pte, vmf->ptl); 5438 return handle_userfault(vmf, VM_UFFD_MISSING); 5439 } 5440 if (vmf_orig_pte_uffd_wp(vmf)) 5441 entry = pte_mkuffd(entry); 5442 set_pte_at(vma->vm_mm, addr, vmf->pte, entry); 5443 5444 /* No need to invalidate - it was non-present before */ 5445 update_mmu_cache(vma, addr, vmf->pte); 5446 goto unlock; 5447 } 5448 5449 /* Allocate our own private page. */ 5450 ret = vmf_anon_prepare(vmf); 5451 if (ret) 5452 return ret; 5453 /* Returns NULL on OOM or ERR_PTR(-EAGAIN) if we must retry the fault */ 5454 folio = alloc_anon_folio(vmf); 5455 if (IS_ERR(folio)) 5456 return 0; 5457 if (!folio) 5458 goto oom; 5459 5460 nr_pages = folio_nr_pages(folio); 5461 addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE); 5462 5463 /* 5464 * The memory barrier inside __folio_mark_uptodate makes sure that 5465 * preceding stores to the page contents become visible before 5466 * the set_pte_at() write. 5467 */ 5468 __folio_mark_uptodate(folio); 5469 5470 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl); 5471 if (!vmf->pte) 5472 goto release; 5473 if (nr_pages == 1 && vmf_pte_changed(vmf)) { 5474 update_mmu_tlb(vma, addr, vmf->pte); 5475 goto release; 5476 } else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) { 5477 update_mmu_tlb_range(vma, addr, vmf->pte, nr_pages); 5478 goto release; 5479 } 5480 5481 ret = check_stable_address_space(vma->vm_mm); 5482 if (ret) 5483 goto release; 5484 5485 /* Deliver the page fault to userland, check inside PT lock */ 5486 if (userfaultfd_missing(vma)) { 5487 pte_unmap_unlock(vmf->pte, vmf->ptl); 5488 folio_put(folio); 5489 return handle_userfault(vmf, VM_UFFD_MISSING); 5490 } 5491 map_anon_folio_pte_pf(folio, vmf->pte, vma, addr, 5492 vmf_orig_pte_uffd_wp(vmf)); 5493 unlock: 5494 if (vmf->pte) 5495 pte_unmap_unlock(vmf->pte, vmf->ptl); 5496 return ret; 5497 release: 5498 folio_put(folio); 5499 goto unlock; 5500 oom: 5501 return VM_FAULT_OOM; 5502 } 5503 5504 /* 5505 * Either the VMA lock or the mmap_lock must have been held on entry 5506 * (see FAULT_FLAG_VMA_LOCK) and may have been released depending on 5507 * flags and vma->vm_ops->fault() return value. 5508 * See filemap_fault() and __folio_lock_or_retry(). 5509 */ 5510 static vm_fault_t __do_fault(struct vm_fault *vmf) 5511 { 5512 struct vm_area_struct *vma = vmf->vma; 5513 struct folio *folio; 5514 vm_fault_t ret; 5515 5516 /* 5517 * Preallocate pte before we take folio lock because this might lead to 5518 * deadlocks for memcg reclaim which waits for folios under writeback: 5519 * folio_lock(A) 5520 * folio_set_writeback(A) 5521 * folio_unlock(A) 5522 * folio_lock(B) 5523 * folio_lock(B) 5524 * pte_alloc_one 5525 * shrink_folio_list 5526 * folio_wait_writeback(A) 5527 * folio_set_writeback(B) 5528 * folio_unlock(B) 5529 * # flush A, B to clear the writeback 5530 */ 5531 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) { 5532 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm); 5533 if (!vmf->prealloc_pte) 5534 return VM_FAULT_OOM; 5535 } 5536 5537 ret = vma->vm_ops->fault(vmf); 5538 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY | 5539 VM_FAULT_DONE_COW))) 5540 return ret; 5541 5542 folio = page_folio(vmf->page); 5543 if (unlikely(PageHWPoison(vmf->page))) { 5544 vm_fault_t poisonret = VM_FAULT_HWPOISON; 5545 if (ret & VM_FAULT_LOCKED) { 5546 if (folio_mapped(folio)) 5547 unmap_mapping_folio(folio); 5548 /* Retry if a clean folio was removed from the cache. */ 5549 if (mapping_evict_folio(folio->mapping, folio)) 5550 poisonret = VM_FAULT_NOPAGE; 5551 folio_unlock(folio); 5552 } 5553 folio_put(folio); 5554 vmf->page = NULL; 5555 return poisonret; 5556 } 5557 5558 if (unlikely(!(ret & VM_FAULT_LOCKED))) 5559 folio_lock(folio); 5560 else 5561 VM_BUG_ON_PAGE(!folio_test_locked(folio), vmf->page); 5562 5563 return ret; 5564 } 5565 5566 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5567 static void deposit_prealloc_pte(struct vm_fault *vmf) 5568 { 5569 struct vm_area_struct *vma = vmf->vma; 5570 5571 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte); 5572 /* 5573 * We are going to consume the prealloc table, 5574 * count that as nr_ptes. 5575 */ 5576 mm_inc_nr_ptes(vma->vm_mm); 5577 vmf->prealloc_pte = NULL; 5578 } 5579 5580 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *page) 5581 { 5582 struct vm_area_struct *vma = vmf->vma; 5583 bool write = vmf->flags & FAULT_FLAG_WRITE; 5584 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 5585 pmd_t entry; 5586 vm_fault_t ret = VM_FAULT_FALLBACK; 5587 5588 /* 5589 * It is too late to allocate a small folio, we already have a large 5590 * folio in the pagecache: especially s390 KVM cannot tolerate any 5591 * PMD mappings, but PTE-mapped THP are fine. So let's simply refuse any 5592 * PMD mappings if THPs are disabled. As we already have a THP, 5593 * behave as if we are forcing a collapse. 5594 */ 5595 if (thp_disabled_by_hw() || vma_thp_disabled(vma, vma->vm_flags, 5596 /* forced_collapse=*/ true)) 5597 return ret; 5598 5599 if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER)) 5600 return ret; 5601 5602 if (!is_pmd_order(folio_order(folio))) 5603 return ret; 5604 page = &folio->page; 5605 5606 /* 5607 * Just backoff if any subpage of a THP is corrupted otherwise 5608 * the corrupted page may mapped by PMD silently to escape the 5609 * check. This kind of THP just can be PTE mapped. Access to 5610 * the corrupted subpage should trigger SIGBUS as expected. 5611 */ 5612 if (unlikely(folio_test_has_hwpoisoned(folio))) 5613 return ret; 5614 5615 /* 5616 * Archs like ppc64 need additional space to store information 5617 * related to pte entry. Use the preallocated table for that. 5618 */ 5619 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) { 5620 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm); 5621 if (!vmf->prealloc_pte) 5622 return VM_FAULT_OOM; 5623 } 5624 5625 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 5626 if (unlikely(!pmd_none(*vmf->pmd))) 5627 goto out; 5628 5629 flush_icache_pages(vma, page, HPAGE_PMD_NR); 5630 5631 entry = folio_mk_pmd(folio, vma->vm_page_prot); 5632 if (write) 5633 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 5634 5635 add_mm_counter(vma->vm_mm, mm_counter_file(folio), HPAGE_PMD_NR); 5636 folio_add_file_rmap_pmd(folio, page, vma); 5637 5638 /* 5639 * deposit and withdraw with pmd lock held 5640 */ 5641 if (arch_needs_pgtable_deposit()) 5642 deposit_prealloc_pte(vmf); 5643 5644 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry); 5645 5646 update_mmu_cache_pmd(vma, haddr, vmf->pmd); 5647 5648 /* fault is handled */ 5649 ret = 0; 5650 count_vm_event(THP_FILE_MAPPED); 5651 out: 5652 spin_unlock(vmf->ptl); 5653 return ret; 5654 } 5655 #else 5656 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *page) 5657 { 5658 return VM_FAULT_FALLBACK; 5659 } 5660 #endif 5661 5662 /** 5663 * set_pte_range - Set a range of PTEs to point to pages in a folio. 5664 * @vmf: Fault description. 5665 * @folio: The folio that contains @page. 5666 * @page: The first page to create a PTE for. 5667 * @nr: The number of PTEs to create. 5668 * @addr: The first address to create a PTE for. 5669 */ 5670 void set_pte_range(struct vm_fault *vmf, struct folio *folio, 5671 struct page *page, unsigned int nr, unsigned long addr) 5672 { 5673 struct vm_area_struct *vma = vmf->vma; 5674 bool write = vmf->flags & FAULT_FLAG_WRITE; 5675 bool prefault = !in_range(vmf->address, addr, nr * PAGE_SIZE); 5676 pte_t entry; 5677 5678 flush_icache_pages(vma, page, nr); 5679 entry = mk_pte(page, vma->vm_page_prot); 5680 5681 if (prefault && arch_wants_old_prefaulted_pte()) 5682 entry = pte_mkold(entry); 5683 else 5684 entry = pte_sw_mkyoung(entry); 5685 5686 if (write) 5687 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 5688 else if (pte_write(entry) && folio_test_dirty(folio)) 5689 entry = pte_mkdirty(entry); 5690 if (unlikely(vmf_orig_pte_uffd_wp(vmf))) 5691 entry = pte_mkuffd(entry); 5692 /* copy-on-write page */ 5693 if (write && !(vma->vm_flags & VM_SHARED)) { 5694 VM_BUG_ON_FOLIO(nr != 1, folio); 5695 folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); 5696 folio_add_lru_vma(folio, vma); 5697 } else { 5698 folio_add_file_rmap_ptes(folio, page, nr, vma); 5699 } 5700 set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr); 5701 5702 /* no need to invalidate: a not-present page won't be cached */ 5703 update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr); 5704 } 5705 5706 static bool vmf_pte_changed(struct vm_fault *vmf) 5707 { 5708 if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID) 5709 return !pte_same(ptep_get(vmf->pte), vmf->orig_pte); 5710 5711 return !pte_none(ptep_get(vmf->pte)); 5712 } 5713 5714 /** 5715 * finish_fault - finish page fault once we have prepared the page to fault 5716 * 5717 * @vmf: structure describing the fault 5718 * 5719 * This function handles all that is needed to finish a page fault once the 5720 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for 5721 * given page, adds reverse page mapping, handles memcg charges and LRU 5722 * addition. 5723 * 5724 * The function expects the page to be locked and on success it consumes a 5725 * reference of a page being mapped (for the PTE which maps it). 5726 * 5727 * Return: %0 on success, %VM_FAULT_ code in case of error. 5728 */ 5729 vm_fault_t finish_fault(struct vm_fault *vmf) 5730 { 5731 struct vm_area_struct *vma = vmf->vma; 5732 struct page *page; 5733 struct folio *folio; 5734 vm_fault_t ret; 5735 bool is_cow = (vmf->flags & FAULT_FLAG_WRITE) && 5736 !(vma->vm_flags & VM_SHARED); 5737 int type, nr_pages; 5738 unsigned long addr; 5739 bool needs_fallback = false; 5740 5741 fallback: 5742 addr = vmf->address; 5743 5744 /* Did we COW the page? */ 5745 if (is_cow) 5746 page = vmf->cow_page; 5747 else 5748 page = vmf->page; 5749 5750 folio = page_folio(page); 5751 /* 5752 * check even for read faults because we might have lost our CoWed 5753 * page 5754 */ 5755 if (!(vma->vm_flags & VM_SHARED)) { 5756 ret = check_stable_address_space(vma->vm_mm); 5757 if (ret) 5758 return ret; 5759 } 5760 5761 if (!needs_fallback && vma->vm_file) { 5762 struct address_space *mapping = vma->vm_file->f_mapping; 5763 pgoff_t file_end; 5764 5765 file_end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE); 5766 5767 /* 5768 * Do not allow to map with PTEs beyond i_size and with PMD 5769 * across i_size to preserve SIGBUS semantics. 5770 * 5771 * Make an exception for shmem/tmpfs that for long time 5772 * intentionally mapped with PMDs across i_size. 5773 */ 5774 needs_fallback = !shmem_mapping(mapping) && 5775 file_end < folio_next_index(folio); 5776 } 5777 5778 if (pmd_none(*vmf->pmd)) { 5779 if (!needs_fallback && folio_test_pmd_mappable(folio)) { 5780 ret = do_set_pmd(vmf, folio, page); 5781 if (ret != VM_FAULT_FALLBACK) 5782 return ret; 5783 } 5784 5785 if (vmf->prealloc_pte) 5786 pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte); 5787 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) 5788 return VM_FAULT_OOM; 5789 } 5790 5791 nr_pages = folio_nr_pages(folio); 5792 5793 /* Using per-page fault to maintain the uffd semantics */ 5794 if (unlikely(userfaultfd_armed(vma)) || unlikely(needs_fallback)) { 5795 nr_pages = 1; 5796 } else if (nr_pages > 1) { 5797 pgoff_t idx = folio_page_idx(folio, page); 5798 /* The page offset of vmf->address within the VMA. */ 5799 pgoff_t vma_off = vmf->pgoff - vma_start_pgoff(vmf->vma); 5800 /* The index of the entry in the pagetable for fault page. */ 5801 pgoff_t pte_off = pte_index(vmf->address); 5802 5803 /* 5804 * Fallback to per-page fault in case the folio size in page 5805 * cache beyond the VMA limits and PMD pagetable limits. 5806 */ 5807 if (unlikely(vma_off < idx || 5808 vma_off + (nr_pages - idx) > vma_pages(vma) || 5809 pte_off < idx || 5810 pte_off + (nr_pages - idx) > PTRS_PER_PTE)) { 5811 nr_pages = 1; 5812 } else { 5813 /* Now we can set mappings for the whole large folio. */ 5814 addr = vmf->address - idx * PAGE_SIZE; 5815 page = &folio->page; 5816 } 5817 } 5818 5819 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 5820 addr, &vmf->ptl); 5821 if (!vmf->pte) 5822 return VM_FAULT_NOPAGE; 5823 5824 /* Re-check under ptl */ 5825 if (nr_pages == 1 && unlikely(vmf_pte_changed(vmf))) { 5826 update_mmu_tlb(vma, addr, vmf->pte); 5827 ret = VM_FAULT_NOPAGE; 5828 goto unlock; 5829 } else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) { 5830 needs_fallback = true; 5831 pte_unmap_unlock(vmf->pte, vmf->ptl); 5832 goto fallback; 5833 } 5834 5835 folio_ref_add(folio, nr_pages - 1); 5836 set_pte_range(vmf, folio, page, nr_pages, addr); 5837 type = is_cow ? MM_ANONPAGES : mm_counter_file(folio); 5838 add_mm_counter(vma->vm_mm, type, nr_pages); 5839 ret = 0; 5840 5841 unlock: 5842 pte_unmap_unlock(vmf->pte, vmf->ptl); 5843 return ret; 5844 } 5845 5846 static unsigned long fault_around_pages __read_mostly = 5847 65536 >> PAGE_SHIFT; 5848 5849 #ifdef CONFIG_DEBUG_FS 5850 static int fault_around_bytes_get(void *data, u64 *val) 5851 { 5852 *val = fault_around_pages << PAGE_SHIFT; 5853 return 0; 5854 } 5855 5856 /* 5857 * fault_around_bytes must be rounded down to the nearest page order as it's 5858 * what do_fault_around() expects to see. 5859 */ 5860 static int fault_around_bytes_set(void *data, u64 val) 5861 { 5862 if (val / PAGE_SIZE > PTRS_PER_PTE) 5863 return -EINVAL; 5864 5865 /* 5866 * The minimum value is 1 page, however this results in no fault-around 5867 * at all. See should_fault_around(). 5868 */ 5869 val = max(val, PAGE_SIZE); 5870 fault_around_pages = rounddown_pow_of_two(val) >> PAGE_SHIFT; 5871 5872 return 0; 5873 } 5874 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops, 5875 fault_around_bytes_get, fault_around_bytes_set, "%llu\n"); 5876 5877 static int __init fault_around_debugfs(void) 5878 { 5879 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL, 5880 &fault_around_bytes_fops); 5881 return 0; 5882 } 5883 late_initcall(fault_around_debugfs); 5884 #endif 5885 5886 /* 5887 * do_fault_around() tries to map few pages around the fault address. The hope 5888 * is that the pages will be needed soon and this will lower the number of 5889 * faults to handle. 5890 * 5891 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's 5892 * not ready to be mapped: not up-to-date, locked, etc. 5893 * 5894 * This function doesn't cross VMA or page table boundaries, in order to call 5895 * map_pages() and acquire a PTE lock only once. 5896 * 5897 * fault_around_pages defines how many pages we'll try to map. 5898 * do_fault_around() expects it to be set to a power of two less than or equal 5899 * to PTRS_PER_PTE. 5900 * 5901 * The virtual address of the area that we map is naturally aligned to 5902 * fault_around_pages * PAGE_SIZE rounded down to the machine page size 5903 * (and therefore to page order). This way it's easier to guarantee 5904 * that we don't cross page table boundaries. 5905 */ 5906 static vm_fault_t do_fault_around(struct vm_fault *vmf) 5907 { 5908 pgoff_t nr_pages = READ_ONCE(fault_around_pages); 5909 pgoff_t pte_off = pte_index(vmf->address); 5910 /* The page offset of vmf->address within the VMA. */ 5911 pgoff_t vma_off = vmf->pgoff - vma_start_pgoff(vmf->vma); 5912 pgoff_t from_pte, to_pte; 5913 vm_fault_t ret; 5914 5915 /* The PTE offset of the start address, clamped to the VMA. */ 5916 from_pte = max(ALIGN_DOWN(pte_off, nr_pages), 5917 pte_off - min(pte_off, vma_off)); 5918 5919 /* The PTE offset of the end address, clamped to the VMA and PTE. */ 5920 to_pte = min3(from_pte + nr_pages, (pgoff_t)PTRS_PER_PTE, 5921 pte_off + vma_pages(vmf->vma) - vma_off) - 1; 5922 5923 if (pmd_none(*vmf->pmd)) { 5924 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm); 5925 if (!vmf->prealloc_pte) 5926 return VM_FAULT_OOM; 5927 } 5928 5929 rcu_read_lock(); 5930 ret = vmf->vma->vm_ops->map_pages(vmf, 5931 vmf->pgoff + from_pte - pte_off, 5932 vmf->pgoff + to_pte - pte_off); 5933 rcu_read_unlock(); 5934 5935 return ret; 5936 } 5937 5938 /* Return true if we should do read fault-around, false otherwise */ 5939 static inline bool should_fault_around(struct vm_fault *vmf) 5940 { 5941 /* No ->map_pages? No way to fault around... */ 5942 if (!vmf->vma->vm_ops->map_pages) 5943 return false; 5944 5945 if (uffd_disable_fault_around(vmf->vma)) 5946 return false; 5947 5948 /* A single page implies no faulting 'around' at all. */ 5949 return fault_around_pages > 1; 5950 } 5951 5952 static vm_fault_t do_read_fault(struct vm_fault *vmf) 5953 { 5954 vm_fault_t ret = 0; 5955 struct folio *folio; 5956 5957 /* 5958 * Let's call ->map_pages() first and use ->fault() as fallback 5959 * if page by the offset is not ready to be mapped (cold cache or 5960 * something). 5961 */ 5962 if (should_fault_around(vmf)) { 5963 ret = do_fault_around(vmf); 5964 if (ret) 5965 return ret; 5966 } 5967 5968 ret = vmf_can_call_fault(vmf); 5969 if (ret) 5970 return ret; 5971 5972 ret = __do_fault(vmf); 5973 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 5974 return ret; 5975 5976 ret |= finish_fault(vmf); 5977 folio = page_folio(vmf->page); 5978 folio_unlock(folio); 5979 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 5980 folio_put(folio); 5981 return ret; 5982 } 5983 5984 static vm_fault_t do_cow_fault(struct vm_fault *vmf) 5985 { 5986 struct vm_area_struct *vma = vmf->vma; 5987 struct folio *folio; 5988 vm_fault_t ret; 5989 5990 ret = vmf_can_call_fault(vmf); 5991 if (!ret) 5992 ret = vmf_anon_prepare(vmf); 5993 if (ret) 5994 return ret; 5995 5996 folio = folio_prealloc(vma->vm_mm, vma, vmf->address, false); 5997 if (!folio) 5998 return VM_FAULT_OOM; 5999 6000 vmf->cow_page = &folio->page; 6001 6002 ret = __do_fault(vmf); 6003 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 6004 goto uncharge_out; 6005 if (ret & VM_FAULT_DONE_COW) 6006 return ret; 6007 6008 if (copy_mc_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma)) { 6009 ret = VM_FAULT_HWPOISON; 6010 goto unlock; 6011 } 6012 __folio_mark_uptodate(folio); 6013 6014 ret |= finish_fault(vmf); 6015 unlock: 6016 unlock_page(vmf->page); 6017 put_page(vmf->page); 6018 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 6019 goto uncharge_out; 6020 return ret; 6021 uncharge_out: 6022 folio_put(folio); 6023 return ret; 6024 } 6025 6026 static vm_fault_t do_shared_fault(struct vm_fault *vmf) 6027 { 6028 struct vm_area_struct *vma = vmf->vma; 6029 vm_fault_t ret, tmp; 6030 struct folio *folio; 6031 6032 ret = vmf_can_call_fault(vmf); 6033 if (ret) 6034 return ret; 6035 6036 ret = __do_fault(vmf); 6037 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 6038 return ret; 6039 6040 folio = page_folio(vmf->page); 6041 6042 /* 6043 * Check if the backing address space wants to know that the page is 6044 * about to become writable 6045 */ 6046 if (vma->vm_ops->page_mkwrite) { 6047 folio_unlock(folio); 6048 tmp = do_page_mkwrite(vmf, folio); 6049 if (unlikely(!tmp || 6050 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { 6051 folio_put(folio); 6052 return tmp; 6053 } 6054 } 6055 6056 ret |= finish_fault(vmf); 6057 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | 6058 VM_FAULT_RETRY))) { 6059 folio_unlock(folio); 6060 folio_put(folio); 6061 return ret; 6062 } 6063 6064 ret |= fault_dirty_shared_page(vmf); 6065 return ret; 6066 } 6067 6068 /* 6069 * We enter with either the VMA lock or the mmap_lock held (see 6070 * FAULT_FLAG_VMA_LOCK). 6071 * The lock may have been released depending on flags and our 6072 * return value. See filemap_fault() and __folio_lock_or_retry(). 6073 * If the lock is released, vma may become invalid (for example 6074 * by other thread calling munmap()). 6075 */ 6076 static vm_fault_t do_fault(struct vm_fault *vmf) 6077 { 6078 struct vm_area_struct *vma = vmf->vma; 6079 struct mm_struct *vm_mm = vma->vm_mm; 6080 vm_fault_t ret; 6081 6082 /* 6083 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND 6084 */ 6085 if (!vma->vm_ops->fault) { 6086 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, 6087 vmf->address, &vmf->ptl); 6088 if (unlikely(!vmf->pte)) 6089 ret = VM_FAULT_SIGBUS; 6090 else { 6091 /* 6092 * Make sure this is not a temporary clearing of pte 6093 * by holding ptl and checking again. A R/M/W update 6094 * of pte involves: take ptl, clearing the pte so that 6095 * we don't have concurrent modification by hardware 6096 * followed by an update. 6097 */ 6098 if (unlikely(pte_none(ptep_get(vmf->pte)))) 6099 ret = VM_FAULT_SIGBUS; 6100 else 6101 ret = VM_FAULT_NOPAGE; 6102 6103 pte_unmap_unlock(vmf->pte, vmf->ptl); 6104 } 6105 } else if (!(vmf->flags & FAULT_FLAG_WRITE)) 6106 ret = do_read_fault(vmf); 6107 else if (!(vma->vm_flags & VM_SHARED)) 6108 ret = do_cow_fault(vmf); 6109 else 6110 ret = do_shared_fault(vmf); 6111 6112 /* preallocated pagetable is unused: free it */ 6113 if (vmf->prealloc_pte) { 6114 pte_free(vm_mm, vmf->prealloc_pte); 6115 vmf->prealloc_pte = NULL; 6116 } 6117 return ret; 6118 } 6119 6120 int numa_migrate_check(struct folio *folio, struct vm_fault *vmf, 6121 unsigned long addr, int *flags, 6122 bool writable, int *last_cpupid) 6123 { 6124 struct vm_area_struct *vma = vmf->vma; 6125 6126 /* 6127 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as 6128 * much anyway since they can be in shared cache state. This misses 6129 * the case where a mapping is writable but the process never writes 6130 * to it but pte_write gets cleared during protection updates and 6131 * pte_dirty has unpredictable behaviour between PTE scan updates, 6132 * background writeback, dirty balancing and application behaviour. 6133 */ 6134 if (!writable) 6135 *flags |= TNF_NO_GROUP; 6136 6137 /* 6138 * Flag if the folio is shared between multiple address spaces. This 6139 * is later used when determining whether to group tasks together 6140 */ 6141 if (folio_maybe_mapped_shared(folio) && (vma->vm_flags & VM_SHARED)) 6142 *flags |= TNF_SHARED; 6143 /* 6144 * For memory tiering mode, cpupid of slow memory page is used 6145 * to record page access time. So use default value. 6146 */ 6147 if (folio_use_access_time(folio)) 6148 *last_cpupid = (-1 & LAST_CPUPID_MASK); 6149 else 6150 *last_cpupid = folio_last_cpupid(folio); 6151 6152 /* Record the current PID accessing VMA */ 6153 vma_set_access_pid_bit(vma); 6154 6155 count_vm_numa_event(NUMA_HINT_FAULTS); 6156 #ifdef CONFIG_NUMA_BALANCING 6157 count_memcg_folio_events(folio, NUMA_HINT_FAULTS, 1); 6158 #endif 6159 if (folio_nid(folio) == numa_node_id()) { 6160 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL); 6161 *flags |= TNF_FAULT_LOCAL; 6162 } 6163 6164 return mpol_misplaced(folio, vmf, addr); 6165 } 6166 6167 static void numa_rebuild_single_mapping(struct vm_fault *vmf, struct vm_area_struct *vma, 6168 unsigned long fault_addr, pte_t *fault_pte, 6169 bool writable) 6170 { 6171 pte_t pte, old_pte; 6172 6173 old_pte = ptep_modify_prot_start(vma, fault_addr, fault_pte); 6174 pte = pte_modify(old_pte, vma->vm_page_prot); 6175 pte = pte_mkyoung(pte); 6176 if (writable) 6177 pte = pte_mkwrite(pte, vma); 6178 ptep_modify_prot_commit(vma, fault_addr, fault_pte, old_pte, pte); 6179 update_mmu_cache_range(vmf, vma, fault_addr, fault_pte, 1); 6180 } 6181 6182 static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_struct *vma, 6183 struct folio *folio, pte_t fault_pte, 6184 bool ignore_writable, bool pte_write_upgrade) 6185 { 6186 int nr = pte_pfn(fault_pte) - folio_pfn(folio); 6187 unsigned long start, end, addr = vmf->address; 6188 unsigned long addr_start = addr - (nr << PAGE_SHIFT); 6189 unsigned long pt_start = ALIGN_DOWN(addr, PMD_SIZE); 6190 pte_t *start_ptep; 6191 6192 /* Stay within the VMA and within the page table. */ 6193 start = max3(addr_start, pt_start, vma->vm_start); 6194 end = min3(addr_start + folio_size(folio), pt_start + PMD_SIZE, 6195 vma->vm_end); 6196 start_ptep = vmf->pte - ((addr - start) >> PAGE_SHIFT); 6197 6198 /* Restore all PTEs' mapping of the large folio */ 6199 for (addr = start; addr != end; start_ptep++, addr += PAGE_SIZE) { 6200 pte_t ptent = ptep_get(start_ptep); 6201 bool writable = false; 6202 6203 if (!pte_present(ptent) || !pte_protnone(ptent)) 6204 continue; 6205 6206 /* 6207 * RWP-armed PTEs are also protnone but carry _PAGE_UFFD as a 6208 * marker. Leave them alone -- rewriting to vm_page_prot would 6209 * stop the RWP trap. Gate on userfaultfd_rwp(vma) too: 6210 * NUMA balancing preserves _PAGE_UFFD on UFFD_WP-marked PTEs 6211 * when applying PROT_NONE, and those still need rebuilding. 6212 */ 6213 if (userfaultfd_rwp(vma) && pte_uffd(ptent)) 6214 continue; 6215 6216 if (pfn_folio(pte_pfn(ptent)) != folio) 6217 continue; 6218 6219 if (!ignore_writable) { 6220 ptent = pte_modify(ptent, vma->vm_page_prot); 6221 writable = pte_write(ptent); 6222 if (!writable && pte_write_upgrade && 6223 can_change_pte_writable(vma, addr, ptent)) 6224 writable = true; 6225 } 6226 6227 numa_rebuild_single_mapping(vmf, vma, addr, start_ptep, writable); 6228 } 6229 } 6230 6231 static vm_fault_t do_uffd_rwp(struct vm_fault *vmf) 6232 { 6233 pte_t pte; 6234 6235 if (!userfaultfd_rwp_async(vmf->vma)) { 6236 /* Sync mode: unmap PTE and deliver to userfaultfd handler */ 6237 pte_unmap(vmf->pte); 6238 return handle_userfault(vmf, VM_UFFD_RWP); 6239 } 6240 6241 spin_lock(vmf->ptl); 6242 if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 6243 pte_unmap_unlock(vmf->pte, vmf->ptl); 6244 return 0; 6245 } 6246 pte = pte_modify(vmf->orig_pte, vmf->vma->vm_page_prot); 6247 /* pte_modify() preserves _PAGE_UFFD; drop it on resolution */ 6248 pte = pte_clear_uffd(pte); 6249 pte = pte_mkyoung(pte); 6250 if (!pte_write(pte) && 6251 vma_wants_manual_pte_write_upgrade(vmf->vma) && 6252 can_change_pte_writable(vmf->vma, vmf->address, pte)) 6253 pte = pte_mkwrite(pte, vmf->vma); 6254 set_pte_at(vmf->vma->vm_mm, vmf->address, vmf->pte, pte); 6255 update_mmu_cache(vmf->vma, vmf->address, vmf->pte); 6256 pte_unmap_unlock(vmf->pte, vmf->ptl); 6257 return 0; 6258 } 6259 6260 static vm_fault_t do_numa_page(struct vm_fault *vmf) 6261 { 6262 struct vm_area_struct *vma = vmf->vma; 6263 struct folio *folio = NULL; 6264 int nid = NUMA_NO_NODE; 6265 bool writable = false, ignore_writable = false; 6266 bool pte_write_upgrade = vma_wants_manual_pte_write_upgrade(vma); 6267 int last_cpupid; 6268 int target_nid; 6269 pte_t pte, old_pte; 6270 int flags = 0, nr_pages; 6271 6272 /* 6273 * The pte cannot be used safely until we verify, while holding the page 6274 * table lock, that its contents have not changed during fault handling. 6275 */ 6276 spin_lock(vmf->ptl); 6277 /* Read the live PTE from the page tables: */ 6278 old_pte = ptep_get(vmf->pte); 6279 6280 if (unlikely(!pte_same(old_pte, vmf->orig_pte))) { 6281 pte_unmap_unlock(vmf->pte, vmf->ptl); 6282 return 0; 6283 } 6284 6285 pte = pte_modify(old_pte, vma->vm_page_prot); 6286 6287 /* 6288 * Detect now whether the PTE could be writable; this information 6289 * is only valid while holding the PT lock. 6290 */ 6291 writable = pte_write(pte); 6292 if (!writable && pte_write_upgrade && 6293 can_change_pte_writable(vma, vmf->address, pte)) 6294 writable = true; 6295 6296 folio = vm_normal_folio(vma, vmf->address, pte); 6297 if (!folio || folio_is_zone_device(folio)) 6298 goto out_map; 6299 6300 nid = folio_nid(folio); 6301 nr_pages = folio_nr_pages(folio); 6302 6303 target_nid = numa_migrate_check(folio, vmf, vmf->address, &flags, 6304 writable, &last_cpupid); 6305 if (target_nid == NUMA_NO_NODE) 6306 goto out_map; 6307 if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) { 6308 flags |= TNF_MIGRATE_FAIL; 6309 goto out_map; 6310 } 6311 /* The folio is isolated and isolation code holds a folio reference. */ 6312 pte_unmap_unlock(vmf->pte, vmf->ptl); 6313 writable = false; 6314 ignore_writable = true; 6315 6316 /* Migrate to the requested node */ 6317 if (!migrate_misplaced_folio(folio, target_nid)) { 6318 nid = target_nid; 6319 flags |= TNF_MIGRATED; 6320 task_numa_fault(last_cpupid, nid, nr_pages, flags); 6321 return 0; 6322 } 6323 6324 flags |= TNF_MIGRATE_FAIL; 6325 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 6326 vmf->address, &vmf->ptl); 6327 if (unlikely(!vmf->pte)) 6328 return 0; 6329 if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) { 6330 pte_unmap_unlock(vmf->pte, vmf->ptl); 6331 return 0; 6332 } 6333 out_map: 6334 /* 6335 * Make it present again, depending on how arch implements 6336 * non-accessible ptes, some can allow access by kernel mode. 6337 */ 6338 if (folio && folio_test_large(folio)) 6339 numa_rebuild_large_mapping(vmf, vma, folio, pte, ignore_writable, 6340 pte_write_upgrade); 6341 else 6342 numa_rebuild_single_mapping(vmf, vma, vmf->address, vmf->pte, 6343 writable); 6344 pte_unmap_unlock(vmf->pte, vmf->ptl); 6345 6346 if (nid != NUMA_NO_NODE) 6347 task_numa_fault(last_cpupid, nid, nr_pages, flags); 6348 return 0; 6349 } 6350 6351 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf) 6352 { 6353 struct vm_area_struct *vma = vmf->vma; 6354 if (vma_is_anonymous(vma)) 6355 return do_huge_pmd_anonymous_page(vmf); 6356 if (vma->vm_ops->huge_fault) 6357 return vma->vm_ops->huge_fault(vmf, PMD_ORDER); 6358 return VM_FAULT_FALLBACK; 6359 } 6360 6361 /* `inline' is required to avoid gcc 4.1.2 build error */ 6362 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf) 6363 { 6364 struct vm_area_struct *vma = vmf->vma; 6365 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 6366 vm_fault_t ret; 6367 6368 if (vma_is_anonymous(vma)) { 6369 if (likely(!unshare) && 6370 userfaultfd_huge_pmd_wp(vma, vmf->orig_pmd)) { 6371 if (userfaultfd_wp_async(vmf->vma)) 6372 goto split; 6373 return handle_userfault(vmf, VM_UFFD_WP); 6374 } 6375 return do_huge_pmd_wp_page(vmf); 6376 } 6377 6378 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) { 6379 if (vma->vm_ops->huge_fault) { 6380 ret = vma->vm_ops->huge_fault(vmf, PMD_ORDER); 6381 if (!(ret & VM_FAULT_FALLBACK)) 6382 return ret; 6383 } 6384 } 6385 6386 split: 6387 /* COW or write-notify handled on pte level: split pmd. */ 6388 __split_huge_pmd(vma, vmf->pmd, vmf->address, false); 6389 6390 return VM_FAULT_FALLBACK; 6391 } 6392 6393 static vm_fault_t create_huge_pud(struct vm_fault *vmf) 6394 { 6395 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \ 6396 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) 6397 struct vm_area_struct *vma = vmf->vma; 6398 /* No support for anonymous transparent PUD pages yet */ 6399 if (vma_is_anonymous(vma)) 6400 return VM_FAULT_FALLBACK; 6401 if (vma->vm_ops->huge_fault) 6402 return vma->vm_ops->huge_fault(vmf, PUD_ORDER); 6403 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 6404 return VM_FAULT_FALLBACK; 6405 } 6406 6407 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud) 6408 { 6409 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \ 6410 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) 6411 struct vm_area_struct *vma = vmf->vma; 6412 vm_fault_t ret; 6413 6414 /* No support for anonymous transparent PUD pages yet */ 6415 if (vma_is_anonymous(vma)) 6416 goto split; 6417 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) { 6418 if (vma->vm_ops->huge_fault) { 6419 ret = vma->vm_ops->huge_fault(vmf, PUD_ORDER); 6420 if (!(ret & VM_FAULT_FALLBACK)) 6421 return ret; 6422 } 6423 } 6424 split: 6425 /* COW or write-notify not handled on PUD level: split pud.*/ 6426 __split_huge_pud(vma, vmf->pud, vmf->address); 6427 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 6428 return VM_FAULT_FALLBACK; 6429 } 6430 6431 /* 6432 * The page faults may be spurious because of the racy access to the 6433 * page table. For example, a non-populated virtual page is accessed 6434 * on 2 CPUs simultaneously, thus the page faults are triggered on 6435 * both CPUs. However, it's possible that one CPU (say CPU A) cannot 6436 * find the reason for the page fault if the other CPU (say CPU B) has 6437 * changed the page table before the PTE is checked on CPU A. Most of 6438 * the time, the spurious page faults can be ignored safely. However, 6439 * if the page fault is for the write access, it's possible that a 6440 * stale read-only TLB entry exists in the local CPU and needs to be 6441 * flushed on some architectures. This is called the spurious page 6442 * fault fixing. 6443 * 6444 * Note: flush_tlb_fix_spurious_fault() is defined as flush_tlb_page() 6445 * by default and used as such on most architectures, while 6446 * flush_tlb_fix_spurious_fault_pmd() is defined as NOP by default and 6447 * used as such on most architectures. 6448 */ 6449 static void fix_spurious_fault(struct vm_fault *vmf, 6450 enum pgtable_level ptlevel) 6451 { 6452 /* Skip spurious TLB flush for retried page fault */ 6453 if (vmf->flags & FAULT_FLAG_TRIED) 6454 return; 6455 /* 6456 * This is needed only for protection faults but the arch code 6457 * is not yet telling us if this is a protection fault or not. 6458 * This still avoids useless tlb flushes for .text page faults 6459 * with threads. 6460 */ 6461 if (vmf->flags & FAULT_FLAG_WRITE) { 6462 if (ptlevel == PGTABLE_LEVEL_PTE) 6463 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address, 6464 vmf->pte); 6465 else 6466 flush_tlb_fix_spurious_fault_pmd(vmf->vma, vmf->address, 6467 vmf->pmd); 6468 } 6469 } 6470 /* 6471 * These routines also need to handle stuff like marking pages dirty 6472 * and/or accessed for architectures that don't do it in hardware (most 6473 * RISC architectures). The early dirtying is also good on the i386. 6474 * 6475 * There is also a hook called "update_mmu_cache()" that architectures 6476 * with external mmu caches can use to update those (ie the Sparc or 6477 * PowerPC hashed page tables that act as extended TLBs). 6478 * 6479 * On entry, we hold either the VMA lock or the mmap_lock 6480 * (see FAULT_FLAG_VMA_LOCK). 6481 * 6482 * The mmap_lock or VMA lock may have been released depending on flags 6483 * and our return value. 6484 * See filemap_fault() and __folio_lock_or_retry(). 6485 */ 6486 static vm_fault_t handle_pte_fault(struct vm_fault *vmf) 6487 { 6488 pte_t entry; 6489 6490 if (unlikely(pmd_none(*vmf->pmd))) { 6491 /* 6492 * Leave __pte_alloc() until later: because vm_ops->fault may 6493 * want to allocate huge page, and if we expose page table 6494 * for an instant, it will be difficult to retract from 6495 * concurrent faults and from rmap lookups. 6496 */ 6497 vmf->pte = NULL; 6498 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID; 6499 } else { 6500 pmd_t dummy_pmdval; 6501 6502 /* 6503 * A regular pmd is established and it can't morph into a huge 6504 * pmd by anon khugepaged, since that takes mmap_lock in write 6505 * mode; but shmem or file collapse to THP could still morph 6506 * it into a huge pmd: just retry later if so. 6507 * 6508 * Use the maywrite version to indicate that vmf->pte may be 6509 * modified, but since we will use pte_same() to detect the 6510 * change of the !pte_none() entry, there is no need to recheck 6511 * the pmdval. Here we choose to pass a dummy variable instead 6512 * of NULL, which helps new user think about why this place is 6513 * special. 6514 */ 6515 vmf->pte = pte_offset_map_rw_nolock(vmf->vma->vm_mm, vmf->pmd, 6516 vmf->address, &dummy_pmdval, 6517 &vmf->ptl); 6518 if (unlikely(!vmf->pte)) 6519 return 0; 6520 vmf->orig_pte = ptep_get_lockless(vmf->pte); 6521 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID; 6522 6523 if (pte_none(vmf->orig_pte)) { 6524 pte_unmap(vmf->pte); 6525 vmf->pte = NULL; 6526 } 6527 } 6528 6529 if (!vmf->pte) 6530 return do_pte_missing(vmf); 6531 6532 if (!pte_present(vmf->orig_pte)) 6533 return do_swap_page(vmf); 6534 6535 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma)) { 6536 /* 6537 * RWP-protected PTEs are protnone plus the uffd bit. On a 6538 * VM_UFFD_RWP VMA, a protnone PTE without the uffd bit is 6539 * NUMA hinting and must still fall through to do_numa_page(). 6540 */ 6541 if (userfaultfd_pte_rwp(vmf->vma, vmf->orig_pte)) 6542 return do_uffd_rwp(vmf); 6543 return do_numa_page(vmf); 6544 } 6545 6546 spin_lock(vmf->ptl); 6547 entry = vmf->orig_pte; 6548 if (unlikely(!pte_same(ptep_get(vmf->pte), entry))) { 6549 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte); 6550 goto unlock; 6551 } 6552 if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) { 6553 if (!pte_write(entry)) 6554 return do_wp_page(vmf); 6555 else if (likely(vmf->flags & FAULT_FLAG_WRITE)) 6556 entry = pte_mkdirty(entry); 6557 } 6558 entry = pte_mkyoung(entry); 6559 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry, 6560 vmf->flags & FAULT_FLAG_WRITE)) 6561 update_mmu_cache_range(vmf, vmf->vma, vmf->address, 6562 vmf->pte, 1); 6563 else 6564 fix_spurious_fault(vmf, PGTABLE_LEVEL_PTE); 6565 unlock: 6566 pte_unmap_unlock(vmf->pte, vmf->ptl); 6567 return 0; 6568 } 6569 6570 /* 6571 * On entry, we hold either the VMA lock or the mmap_lock 6572 * (see FAULT_FLAG_VMA_LOCK). If VM_FAULT_RETRY is set in 6573 * the result, the lock is not held on exit. See filemap_fault() 6574 * and __folio_lock_or_retry(). 6575 */ 6576 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma, 6577 unsigned long address, unsigned int flags) 6578 { 6579 struct vm_fault vmf = { 6580 .vma = vma, 6581 .address = address & PAGE_MASK, 6582 .real_address = address, 6583 .flags = flags, 6584 .pgoff = linear_page_index(vma, address), 6585 .gfp_mask = __get_fault_gfp_mask(vma), 6586 }; 6587 struct mm_struct *mm = vma->vm_mm; 6588 vm_flags_t vm_flags = vma->vm_flags; 6589 pgd_t *pgd; 6590 p4d_t *p4d; 6591 vm_fault_t ret; 6592 6593 pgd = pgd_offset(mm, address); 6594 p4d = p4d_alloc(mm, pgd, address); 6595 if (!p4d) 6596 return VM_FAULT_OOM; 6597 6598 vmf.pud = pud_alloc(mm, p4d, address); 6599 if (!vmf.pud) 6600 return VM_FAULT_OOM; 6601 retry_pud: 6602 if (pud_none(*vmf.pud) && 6603 thp_vma_allowable_order(vma, vm_flags, TVA_PAGEFAULT, PUD_ORDER)) { 6604 ret = create_huge_pud(&vmf); 6605 if (!(ret & VM_FAULT_FALLBACK)) 6606 return ret; 6607 } else { 6608 pud_t orig_pud = *vmf.pud; 6609 6610 barrier(); 6611 if (pud_trans_huge(orig_pud)) { 6612 6613 /* 6614 * TODO once we support anonymous PUDs: NUMA case and 6615 * FAULT_FLAG_UNSHARE handling. 6616 */ 6617 if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) { 6618 ret = wp_huge_pud(&vmf, orig_pud); 6619 if (!(ret & VM_FAULT_FALLBACK)) 6620 return ret; 6621 } else { 6622 huge_pud_set_accessed(&vmf, orig_pud); 6623 return 0; 6624 } 6625 } 6626 } 6627 6628 vmf.pmd = pmd_alloc(mm, vmf.pud, address); 6629 if (!vmf.pmd) 6630 return VM_FAULT_OOM; 6631 6632 /* Huge pud page fault raced with pmd_alloc? */ 6633 if (pud_trans_unstable(vmf.pud)) 6634 goto retry_pud; 6635 6636 if (pmd_none(*vmf.pmd) && 6637 thp_vma_allowable_order(vma, vm_flags, TVA_PAGEFAULT, PMD_ORDER)) { 6638 ret = create_huge_pmd(&vmf); 6639 if (ret & VM_FAULT_FALLBACK) 6640 goto fallback; 6641 else 6642 return ret; 6643 } 6644 6645 vmf.orig_pmd = pmdp_get_lockless(vmf.pmd); 6646 if (pmd_none(vmf.orig_pmd)) 6647 goto fallback; 6648 6649 if (unlikely(!pmd_present(vmf.orig_pmd))) { 6650 if (pmd_is_device_private_entry(vmf.orig_pmd)) 6651 return do_huge_pmd_device_private(&vmf); 6652 6653 if (pmd_is_migration_entry(vmf.orig_pmd)) 6654 pmd_migration_entry_wait(mm, vmf.pmd); 6655 return 0; 6656 } 6657 if (pmd_trans_huge(vmf.orig_pmd)) { 6658 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma)) { 6659 if (userfaultfd_huge_pmd_rwp(vma, vmf.orig_pmd)) 6660 return do_huge_pmd_uffd_rwp(&vmf); 6661 return do_huge_pmd_numa_page(&vmf); 6662 } 6663 6664 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) && 6665 !pmd_write(vmf.orig_pmd)) { 6666 ret = wp_huge_pmd(&vmf); 6667 if (!(ret & VM_FAULT_FALLBACK)) 6668 return ret; 6669 } else { 6670 vmf.ptl = pmd_lock(mm, vmf.pmd); 6671 if (!huge_pmd_set_accessed(&vmf)) 6672 fix_spurious_fault(&vmf, PGTABLE_LEVEL_PMD); 6673 spin_unlock(vmf.ptl); 6674 return 0; 6675 } 6676 } 6677 6678 fallback: 6679 return handle_pte_fault(&vmf); 6680 } 6681 6682 /** 6683 * mm_account_fault - Do page fault accounting 6684 * @mm: mm from which memcg should be extracted. It can be NULL. 6685 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting 6686 * of perf event counters, but we'll still do the per-task accounting to 6687 * the task who triggered this page fault. 6688 * @address: the faulted address. 6689 * @flags: the fault flags. 6690 * @ret: the fault retcode. 6691 * 6692 * This will take care of most of the page fault accounting. Meanwhile, it 6693 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter 6694 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should 6695 * still be in per-arch page fault handlers at the entry of page fault. 6696 */ 6697 static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs, 6698 unsigned long address, unsigned int flags, 6699 vm_fault_t ret) 6700 { 6701 bool major; 6702 6703 /* Incomplete faults will be accounted upon completion. */ 6704 if (ret & VM_FAULT_RETRY) 6705 return; 6706 6707 /* 6708 * To preserve the behavior of older kernels, PGFAULT counters record 6709 * both successful and failed faults, as opposed to perf counters, 6710 * which ignore failed cases. 6711 */ 6712 count_vm_event(PGFAULT); 6713 count_memcg_event_mm(mm, PGFAULT); 6714 6715 /* 6716 * Do not account for unsuccessful faults (e.g. when the address wasn't 6717 * valid). That includes arch_vma_access_permitted() failing before 6718 * reaching here. So this is not a "this many hardware page faults" 6719 * counter. We should use the hw profiling for that. 6720 */ 6721 if (ret & VM_FAULT_ERROR) 6722 return; 6723 6724 /* 6725 * We define the fault as a major fault when the final successful fault 6726 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't 6727 * handle it immediately previously). 6728 */ 6729 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED); 6730 6731 if (major) 6732 current->maj_flt++; 6733 else 6734 current->min_flt++; 6735 6736 /* 6737 * If the fault is done for GUP, regs will be NULL. We only do the 6738 * accounting for the per thread fault counters who triggered the 6739 * fault, and we skip the perf event updates. 6740 */ 6741 if (!regs) 6742 return; 6743 6744 if (major) 6745 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address); 6746 else 6747 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address); 6748 } 6749 6750 #ifdef CONFIG_LRU_GEN 6751 static void lru_gen_enter_fault(struct vm_area_struct *vma) 6752 { 6753 /* the LRU algorithm only applies to accesses with recency */ 6754 current->in_lru_fault = vma_has_recency(vma); 6755 } 6756 6757 static void lru_gen_exit_fault(void) 6758 { 6759 current->in_lru_fault = false; 6760 } 6761 #else 6762 static void lru_gen_enter_fault(struct vm_area_struct *vma) 6763 { 6764 } 6765 6766 static void lru_gen_exit_fault(void) 6767 { 6768 } 6769 #endif /* CONFIG_LRU_GEN */ 6770 6771 static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, 6772 unsigned int *flags) 6773 { 6774 if (unlikely(*flags & FAULT_FLAG_UNSHARE)) { 6775 if (WARN_ON_ONCE(*flags & FAULT_FLAG_WRITE)) 6776 return VM_FAULT_SIGSEGV; 6777 /* 6778 * FAULT_FLAG_UNSHARE only applies to COW mappings. Let's 6779 * just treat it like an ordinary read-fault otherwise. 6780 */ 6781 if (!vma_is_cow_mapping(vma)) 6782 *flags &= ~FAULT_FLAG_UNSHARE; 6783 } else if (*flags & FAULT_FLAG_WRITE) { 6784 /* Write faults on read-only mappings are impossible ... */ 6785 if (WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE))) 6786 return VM_FAULT_SIGSEGV; 6787 /* ... and FOLL_FORCE only applies to COW mappings. */ 6788 if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE) && 6789 !vma_is_cow_mapping(vma))) 6790 return VM_FAULT_SIGSEGV; 6791 } 6792 /* 6793 * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of 6794 * the assumption that lock is dropped on VM_FAULT_RETRY. 6795 */ 6796 if (WARN_ON_ONCE((*flags & 6797 (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) == 6798 (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT))) 6799 return VM_FAULT_SIGSEGV; 6800 6801 return 0; 6802 } 6803 6804 /* 6805 * By the time we get here, we already hold either the VMA lock or the 6806 * mmap_lock (see FAULT_FLAG_VMA_LOCK). 6807 * 6808 * The lock may have been released depending on flags and our 6809 * return value. See filemap_fault() and __folio_lock_or_retry(). 6810 */ 6811 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address, 6812 unsigned int flags, struct pt_regs *regs) 6813 { 6814 /* If the fault handler drops the mmap_lock, vma may be freed */ 6815 struct mm_struct *mm = vma->vm_mm; 6816 vm_fault_t ret; 6817 bool is_droppable; 6818 6819 __set_current_state(TASK_RUNNING); 6820 6821 ret = sanitize_fault_flags(vma, &flags); 6822 if (ret) 6823 goto out; 6824 6825 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE, 6826 flags & FAULT_FLAG_INSTRUCTION, 6827 flags & FAULT_FLAG_REMOTE)) { 6828 ret = VM_FAULT_SIGSEGV; 6829 goto out; 6830 } 6831 6832 is_droppable = !!(vma->vm_flags & VM_DROPPABLE); 6833 6834 /* 6835 * Enable the memcg OOM handling for faults triggered in user 6836 * space. Kernel faults are handled more gracefully. 6837 */ 6838 if (flags & FAULT_FLAG_USER) 6839 mem_cgroup_enter_user_fault(); 6840 6841 lru_gen_enter_fault(vma); 6842 6843 if (unlikely(is_vm_hugetlb_page(vma))) 6844 ret = hugetlb_fault(vma->vm_mm, vma, address, flags); 6845 else 6846 ret = __handle_mm_fault(vma, address, flags); 6847 6848 /* 6849 * Warning: It is no longer safe to dereference vma-> after this point, 6850 * because mmap_lock might have been dropped by __handle_mm_fault(), so 6851 * vma might be destroyed from underneath us. 6852 */ 6853 6854 lru_gen_exit_fault(); 6855 6856 /* If the mapping is droppable, then errors due to OOM aren't fatal. */ 6857 if (is_droppable) 6858 ret &= ~VM_FAULT_OOM; 6859 6860 if (flags & FAULT_FLAG_USER) { 6861 mem_cgroup_exit_user_fault(); 6862 /* 6863 * The task may have entered a memcg OOM situation but 6864 * if the allocation error was handled gracefully (no 6865 * VM_FAULT_OOM), there is no need to kill anything. 6866 * Just clean up the OOM state peacefully. 6867 */ 6868 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM)) 6869 mem_cgroup_oom_synchronize(false); 6870 } 6871 out: 6872 mm_account_fault(mm, regs, address, flags, ret); 6873 6874 return ret; 6875 } 6876 EXPORT_SYMBOL_GPL(handle_mm_fault); 6877 6878 #ifndef __PAGETABLE_P4D_FOLDED 6879 /* 6880 * Allocate p4d page table. 6881 * We've already handled the fast-path in-line. 6882 */ 6883 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) 6884 { 6885 p4d_t *new = p4d_alloc_one(mm, address); 6886 if (!new) 6887 return -ENOMEM; 6888 6889 spin_lock(&mm->page_table_lock); 6890 if (pgd_present(*pgd)) { /* Another has populated it */ 6891 p4d_free(mm, new); 6892 } else { 6893 smp_wmb(); /* See comment in pmd_install() */ 6894 pgd_populate(mm, pgd, new); 6895 } 6896 spin_unlock(&mm->page_table_lock); 6897 return 0; 6898 } 6899 #endif /* __PAGETABLE_P4D_FOLDED */ 6900 6901 #ifndef __PAGETABLE_PUD_FOLDED 6902 /* 6903 * Allocate page upper directory. 6904 * We've already handled the fast-path in-line. 6905 */ 6906 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address) 6907 { 6908 pud_t *new = pud_alloc_one(mm, address); 6909 if (!new) 6910 return -ENOMEM; 6911 6912 spin_lock(&mm->page_table_lock); 6913 if (!p4d_present(*p4d)) { 6914 mm_inc_nr_puds(mm); 6915 smp_wmb(); /* See comment in pmd_install() */ 6916 p4d_populate(mm, p4d, new); 6917 } else /* Another has populated it */ 6918 pud_free(mm, new); 6919 spin_unlock(&mm->page_table_lock); 6920 return 0; 6921 } 6922 #endif /* __PAGETABLE_PUD_FOLDED */ 6923 6924 #ifndef __PAGETABLE_PMD_FOLDED 6925 /* 6926 * Allocate page middle directory. 6927 * We've already handled the fast-path in-line. 6928 */ 6929 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) 6930 { 6931 spinlock_t *ptl; 6932 pmd_t *new = pmd_alloc_one(mm, address); 6933 if (!new) 6934 return -ENOMEM; 6935 6936 ptl = pud_lock(mm, pud); 6937 if (!pud_present(*pud)) { 6938 mm_inc_nr_pmds(mm); 6939 smp_wmb(); /* See comment in pmd_install() */ 6940 pud_populate(mm, pud, new); 6941 } else { /* Another has populated it */ 6942 pmd_free(mm, new); 6943 } 6944 spin_unlock(ptl); 6945 return 0; 6946 } 6947 #endif /* __PAGETABLE_PMD_FOLDED */ 6948 6949 static inline void pfnmap_args_setup(struct follow_pfnmap_args *args, 6950 spinlock_t *lock, pte_t *ptep, 6951 pgprot_t pgprot, unsigned long pfn_base, 6952 unsigned long addr_mask, bool writable, 6953 bool special) 6954 { 6955 args->lock = lock; 6956 args->ptep = ptep; 6957 args->pfn = pfn_base + ((args->address & ~addr_mask) >> PAGE_SHIFT); 6958 args->addr_mask = addr_mask; 6959 args->pgprot = pgprot; 6960 args->writable = writable; 6961 args->special = special; 6962 } 6963 6964 static inline void pfnmap_lockdep_assert(struct vm_area_struct *vma) 6965 { 6966 #ifdef CONFIG_LOCKDEP 6967 struct file *file = vma->vm_file; 6968 struct address_space *mapping = file ? file->f_mapping : NULL; 6969 6970 if (mapping) 6971 lockdep_assert(lockdep_is_held(&mapping->i_mmap_rwsem) || 6972 lockdep_is_held(&vma->vm_mm->mmap_lock)); 6973 else 6974 lockdep_assert(lockdep_is_held(&vma->vm_mm->mmap_lock)); 6975 #endif 6976 } 6977 6978 /** 6979 * follow_pfnmap_start() - Look up a pfn mapping at a user virtual address 6980 * @args: Pointer to struct @follow_pfnmap_args 6981 * 6982 * The caller needs to setup args->vma and args->address to point to the 6983 * virtual address as the target of such lookup. On a successful return, 6984 * the results will be put into other output fields. 6985 * 6986 * After the caller finished using the fields, the caller must invoke 6987 * another follow_pfnmap_end() to proper releases the locks and resources 6988 * of such look up request. 6989 * 6990 * During the start() and end() calls, the results in @args will be valid 6991 * as proper locks will be held. After the end() is called, all the fields 6992 * in @follow_pfnmap_args will be invalid to be further accessed. Further 6993 * use of such information after end() may require proper synchronizations 6994 * by the caller with page table updates, otherwise it can create a 6995 * security bug. 6996 * 6997 * If the PTE maps a refcounted page, callers are responsible to protect 6998 * against invalidation with MMU notifiers; otherwise access to the PFN at 6999 * a later point in time can trigger use-after-free. 7000 * 7001 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore 7002 * should be taken for read, and the mmap semaphore cannot be released 7003 * before the end() is invoked. 7004 * 7005 * This function must not be used to modify PTE content. 7006 * 7007 * Return: zero on success, negative otherwise. 7008 */ 7009 int follow_pfnmap_start(struct follow_pfnmap_args *args) 7010 { 7011 struct vm_area_struct *vma = args->vma; 7012 unsigned long address = args->address; 7013 struct mm_struct *mm = vma->vm_mm; 7014 spinlock_t *lock; 7015 pgd_t *pgdp; 7016 p4d_t *p4dp, p4d; 7017 pud_t *pudp, pud; 7018 pmd_t *pmdp, pmd; 7019 pte_t *ptep, pte; 7020 7021 pfnmap_lockdep_assert(vma); 7022 7023 if (unlikely(address < vma->vm_start || address >= vma->vm_end)) 7024 goto out; 7025 7026 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 7027 goto out; 7028 retry: 7029 pgdp = pgd_offset(mm, address); 7030 if (pgd_none(*pgdp) || unlikely(pgd_bad(*pgdp))) 7031 goto out; 7032 7033 p4dp = p4d_offset(pgdp, address); 7034 p4d = p4dp_get(p4dp); 7035 if (p4d_none(p4d) || unlikely(p4d_bad(p4d))) 7036 goto out; 7037 7038 pudp = pud_offset(p4dp, address); 7039 pud = pudp_get(pudp); 7040 if (!pud_present(pud)) 7041 goto out; 7042 if (pud_leaf(pud)) { 7043 lock = pud_lock(mm, pudp); 7044 pud = pudp_get(pudp); 7045 7046 if (unlikely(!pud_present(pud))) { 7047 spin_unlock(lock); 7048 goto out; 7049 } else if (unlikely(!pud_leaf(pud))) { 7050 spin_unlock(lock); 7051 goto retry; 7052 } 7053 pfnmap_args_setup(args, lock, NULL, pud_pgprot(pud), 7054 pud_pfn(pud), PUD_MASK, pud_write(pud), 7055 pud_special(pud)); 7056 return 0; 7057 } 7058 7059 pmdp = pmd_offset(pudp, address); 7060 pmd = pmdp_get_lockless(pmdp); 7061 if (!pmd_present(pmd)) 7062 goto out; 7063 if (pmd_leaf(pmd)) { 7064 lock = pmd_lock(mm, pmdp); 7065 pmd = pmdp_get(pmdp); 7066 7067 if (unlikely(!pmd_present(pmd))) { 7068 spin_unlock(lock); 7069 goto out; 7070 } else if (unlikely(!pmd_leaf(pmd))) { 7071 spin_unlock(lock); 7072 goto retry; 7073 } 7074 pfnmap_args_setup(args, lock, NULL, pmd_pgprot(pmd), 7075 pmd_pfn(pmd), PMD_MASK, pmd_write(pmd), 7076 pmd_special(pmd)); 7077 return 0; 7078 } 7079 7080 ptep = pte_offset_map_lock(mm, pmdp, address, &lock); 7081 if (!ptep) 7082 goto out; 7083 pte = ptep_get(ptep); 7084 if (!pte_present(pte)) 7085 goto unlock; 7086 pfnmap_args_setup(args, lock, ptep, pte_pgprot(pte), 7087 pte_pfn(pte), PAGE_MASK, pte_write(pte), 7088 pte_special(pte)); 7089 return 0; 7090 unlock: 7091 pte_unmap_unlock(ptep, lock); 7092 out: 7093 return -EINVAL; 7094 } 7095 EXPORT_SYMBOL_GPL(follow_pfnmap_start); 7096 7097 /** 7098 * follow_pfnmap_end(): End a follow_pfnmap_start() process 7099 * @args: Pointer to struct @follow_pfnmap_args 7100 * 7101 * Must be used in pair of follow_pfnmap_start(). See the start() function 7102 * above for more information. 7103 */ 7104 void follow_pfnmap_end(struct follow_pfnmap_args *args) 7105 { 7106 if (args->lock) 7107 spin_unlock(args->lock); 7108 if (args->ptep) 7109 pte_unmap(args->ptep); 7110 } 7111 EXPORT_SYMBOL_GPL(follow_pfnmap_end); 7112 7113 #ifdef CONFIG_HAVE_IOREMAP_PROT 7114 /** 7115 * generic_access_phys - generic implementation for iomem mmap access 7116 * @vma: the vma to access 7117 * @addr: userspace address, not relative offset within @vma 7118 * @buf: buffer to read/write 7119 * @len: length of transfer 7120 * @write: set to FOLL_WRITE when writing, otherwise reading 7121 * 7122 * This is a generic implementation for &vm_operations_struct.access for an 7123 * iomem mapping. This callback is used by access_process_vm() when the @vma is 7124 * not page based. 7125 */ 7126 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, 7127 void *buf, int len, int write) 7128 { 7129 resource_size_t phys_addr; 7130 pgprot_t prot = __pgprot(0); 7131 void __iomem *maddr; 7132 int offset = offset_in_page(addr); 7133 int ret = -EINVAL; 7134 bool writable; 7135 struct follow_pfnmap_args args = { .vma = vma, .address = addr }; 7136 7137 /* 7138 * Limit access to one page at a time, as that's what follow_pfnmap_start() 7139 * guarantees; expect the caller to retry to read larger ranges. 7140 */ 7141 len = min_t(int, len, PAGE_SIZE - offset); 7142 7143 retry: 7144 if (follow_pfnmap_start(&args)) 7145 return -EINVAL; 7146 prot = args.pgprot; 7147 phys_addr = (resource_size_t)args.pfn << PAGE_SHIFT; 7148 writable = args.writable; 7149 follow_pfnmap_end(&args); 7150 7151 if ((write & FOLL_WRITE) && !writable) 7152 return -EINVAL; 7153 7154 maddr = ioremap_prot(phys_addr, PAGE_SIZE, prot); 7155 if (!maddr) 7156 return -ENOMEM; 7157 7158 if (follow_pfnmap_start(&args)) 7159 goto out_unmap; 7160 7161 if ((pgprot_val(prot) != pgprot_val(args.pgprot)) || 7162 (phys_addr != ((resource_size_t)args.pfn << PAGE_SHIFT)) || 7163 (writable != args.writable)) { 7164 follow_pfnmap_end(&args); 7165 iounmap(maddr); 7166 goto retry; 7167 } 7168 7169 if (write) 7170 memcpy_toio(maddr + offset, buf, len); 7171 else 7172 memcpy_fromio(buf, maddr + offset, len); 7173 ret = len; 7174 follow_pfnmap_end(&args); 7175 out_unmap: 7176 iounmap(maddr); 7177 7178 return ret; 7179 } 7180 EXPORT_SYMBOL_GPL(generic_access_phys); 7181 #endif 7182 7183 /* 7184 * Access another process' address space as given in mm. 7185 */ 7186 static int __access_remote_vm(struct mm_struct *mm, unsigned long addr, 7187 void *buf, int len, unsigned int gup_flags) 7188 { 7189 void *old_buf = buf; 7190 int write = gup_flags & FOLL_WRITE; 7191 7192 if (mmap_read_lock_killable(mm)) 7193 return 0; 7194 7195 /* Untag the address before looking up the VMA */ 7196 addr = untagged_addr_remote(mm, addr); 7197 7198 /* Avoid triggering the temporary warning in __get_user_pages */ 7199 if (!vma_lookup(mm, addr) && !expand_stack(mm, addr)) 7200 return 0; 7201 7202 /* ignore errors, just check how much was successfully transferred */ 7203 while (len) { 7204 int bytes, offset; 7205 void *maddr; 7206 struct folio *folio; 7207 struct vm_area_struct *vma = NULL; 7208 struct page *page = get_user_page_vma_remote(mm, addr, 7209 gup_flags, &vma); 7210 7211 if (IS_ERR(page)) { 7212 /* We might need to expand the stack to access it */ 7213 vma = vma_lookup(mm, addr); 7214 if (!vma) { 7215 vma = expand_stack(mm, addr); 7216 7217 /* mmap_lock was dropped on failure */ 7218 if (!vma) 7219 return buf - old_buf; 7220 7221 /* Try again if stack expansion worked */ 7222 continue; 7223 } 7224 7225 /* 7226 * Check if this is a VM_IO | VM_PFNMAP VMA, which 7227 * we can access using slightly different code. 7228 */ 7229 bytes = 0; 7230 #ifdef CONFIG_HAVE_IOREMAP_PROT 7231 if (vma->vm_ops && vma->vm_ops->access) 7232 bytes = vma->vm_ops->access(vma, addr, buf, 7233 len, write); 7234 #endif 7235 if (bytes <= 0) 7236 break; 7237 } else { 7238 folio = page_folio(page); 7239 bytes = len; 7240 offset = addr & (PAGE_SIZE-1); 7241 if (bytes > PAGE_SIZE-offset) 7242 bytes = PAGE_SIZE-offset; 7243 7244 maddr = kmap_local_folio(folio, folio_page_idx(folio, page) * PAGE_SIZE); 7245 if (write) { 7246 copy_to_user_page(vma, page, addr, 7247 maddr + offset, buf, bytes); 7248 folio_mark_dirty_lock(folio); 7249 } else { 7250 copy_from_user_page(vma, page, addr, 7251 buf, maddr + offset, bytes); 7252 } 7253 folio_release_kmap(folio, maddr); 7254 } 7255 len -= bytes; 7256 buf += bytes; 7257 addr += bytes; 7258 } 7259 mmap_read_unlock(mm); 7260 7261 return buf - old_buf; 7262 } 7263 7264 /** 7265 * access_remote_vm - access another process' address space 7266 * @mm: the mm_struct of the target address space 7267 * @addr: start address to access 7268 * @buf: source or destination buffer 7269 * @len: number of bytes to transfer 7270 * @gup_flags: flags modifying lookup behaviour 7271 * 7272 * The caller must hold a reference on @mm. 7273 * 7274 * Return: number of bytes copied from source to destination. 7275 */ 7276 int access_remote_vm(struct mm_struct *mm, unsigned long addr, 7277 void *buf, int len, unsigned int gup_flags) 7278 { 7279 return __access_remote_vm(mm, addr, buf, len, gup_flags); 7280 } 7281 7282 /* 7283 * Access another process' address space. 7284 * Source/target buffer must be kernel space, 7285 * Do not walk the page table directly, use get_user_pages 7286 */ 7287 int access_process_vm(struct task_struct *tsk, unsigned long addr, 7288 void *buf, int len, unsigned int gup_flags) 7289 { 7290 struct mm_struct *mm; 7291 int ret; 7292 7293 mm = get_task_mm(tsk); 7294 if (!mm) 7295 return 0; 7296 7297 ret = __access_remote_vm(mm, addr, buf, len, gup_flags); 7298 7299 mmput(mm); 7300 7301 return ret; 7302 } 7303 EXPORT_SYMBOL_GPL(access_process_vm); 7304 7305 /* 7306 * Copy a string from another process's address space as given in mm. 7307 * If there is any error return -EFAULT. 7308 */ 7309 int __copy_remote_mm_str(struct mm_struct *mm, unsigned long addr, 7310 void *buf, int len, unsigned int gup_flags) 7311 { 7312 void *old_buf = buf; 7313 int err = 0; 7314 7315 *(char *)buf = '\0'; 7316 7317 if (mmap_read_lock_killable(mm)) 7318 return -EFAULT; 7319 7320 addr = untagged_addr_remote(mm, addr); 7321 7322 /* Avoid triggering the temporary warning in __get_user_pages */ 7323 if (!vma_lookup(mm, addr)) { 7324 err = -EFAULT; 7325 goto out; 7326 } 7327 7328 while (len) { 7329 int bytes, offset, retval; 7330 void *maddr; 7331 struct folio *folio; 7332 struct page *page; 7333 struct vm_area_struct *vma = NULL; 7334 7335 page = get_user_page_vma_remote(mm, addr, gup_flags, &vma); 7336 if (IS_ERR(page)) { 7337 /* 7338 * Treat as a total failure for now until we decide how 7339 * to handle the CONFIG_HAVE_IOREMAP_PROT case and 7340 * stack expansion. 7341 */ 7342 *(char *)buf = '\0'; 7343 err = -EFAULT; 7344 goto out; 7345 } 7346 7347 folio = page_folio(page); 7348 bytes = len; 7349 offset = addr & (PAGE_SIZE - 1); 7350 if (bytes > PAGE_SIZE - offset) 7351 bytes = PAGE_SIZE - offset; 7352 7353 maddr = kmap_local_folio(folio, folio_page_idx(folio, page) * PAGE_SIZE); 7354 retval = strscpy(buf, maddr + offset, bytes); 7355 if (retval >= 0) { 7356 /* Found the end of the string */ 7357 buf += retval; 7358 folio_release_kmap(folio, maddr); 7359 break; 7360 } 7361 7362 buf += bytes - 1; 7363 /* 7364 * Because strscpy always NUL terminates we need to 7365 * copy the last byte in the page if we are going to 7366 * load more pages 7367 */ 7368 if (bytes != len) { 7369 addr += bytes - 1; 7370 copy_from_user_page(vma, page, addr, buf, maddr + (PAGE_SIZE - 1), 1); 7371 buf += 1; 7372 addr += 1; 7373 } 7374 len -= bytes; 7375 7376 folio_release_kmap(folio, maddr); 7377 } 7378 7379 out: 7380 mmap_read_unlock(mm); 7381 if (err) 7382 return err; 7383 return buf - old_buf; 7384 } 7385 7386 /* 7387 * Print the name of a VMA. 7388 */ 7389 void print_vma_addr(char *prefix, unsigned long ip) 7390 { 7391 struct mm_struct *mm = current->mm; 7392 struct vm_area_struct *vma; 7393 7394 /* 7395 * we might be running from an atomic context so we cannot sleep 7396 */ 7397 if (!mmap_read_trylock(mm)) 7398 return; 7399 7400 vma = vma_lookup(mm, ip); 7401 if (vma && vma->vm_file) { 7402 struct file *f = vma->vm_file; 7403 ip -= vma->vm_start; 7404 ip += vma_start_pgoff(vma) << PAGE_SHIFT; 7405 printk("%s%pD[%lx,%lx+%lx]", prefix, f, ip, 7406 vma->vm_start, 7407 vma->vm_end - vma->vm_start); 7408 } 7409 mmap_read_unlock(mm); 7410 } 7411 7412 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP) 7413 void __might_fault(const char *file, int line) 7414 { 7415 if (pagefault_disabled()) 7416 return; 7417 __might_sleep(file, line); 7418 if (current->mm) 7419 might_lock_read(¤t->mm->mmap_lock); 7420 } 7421 EXPORT_SYMBOL(__might_fault); 7422 #endif 7423 7424 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) 7425 /* 7426 * Process all subpages of the specified huge page with the specified 7427 * operation. The target subpage will be processed last to keep its 7428 * cache lines hot. 7429 */ 7430 static inline int process_huge_page( 7431 unsigned long addr_hint, unsigned int nr_pages, 7432 int (*process_subpage)(unsigned long addr, int idx, void *arg), 7433 void *arg) 7434 { 7435 int i, n, base, l, ret; 7436 unsigned long addr = addr_hint & 7437 ~(((unsigned long)nr_pages << PAGE_SHIFT) - 1); 7438 7439 /* Process target subpage last to keep its cache lines hot */ 7440 might_sleep(); 7441 n = (addr_hint - addr) / PAGE_SIZE; 7442 if (2 * n <= nr_pages) { 7443 /* If target subpage in first half of huge page */ 7444 base = 0; 7445 l = n; 7446 /* Process subpages at the end of huge page */ 7447 for (i = nr_pages - 1; i >= 2 * n; i--) { 7448 cond_resched(); 7449 ret = process_subpage(addr + i * PAGE_SIZE, i, arg); 7450 if (ret) 7451 return ret; 7452 } 7453 } else { 7454 /* If target subpage in second half of huge page */ 7455 base = nr_pages - 2 * (nr_pages - n); 7456 l = nr_pages - n; 7457 /* Process subpages at the begin of huge page */ 7458 for (i = 0; i < base; i++) { 7459 cond_resched(); 7460 ret = process_subpage(addr + i * PAGE_SIZE, i, arg); 7461 if (ret) 7462 return ret; 7463 } 7464 } 7465 /* 7466 * Process remaining subpages in left-right-left-right pattern 7467 * towards the target subpage 7468 */ 7469 for (i = 0; i < l; i++) { 7470 int left_idx = base + i; 7471 int right_idx = base + 2 * l - 1 - i; 7472 7473 cond_resched(); 7474 ret = process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg); 7475 if (ret) 7476 return ret; 7477 cond_resched(); 7478 ret = process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg); 7479 if (ret) 7480 return ret; 7481 } 7482 return 0; 7483 } 7484 7485 static void clear_contig_highpages(struct page *page, unsigned long addr, 7486 unsigned int nr_pages) 7487 { 7488 unsigned int i, count; 7489 /* 7490 * When clearing we want to operate on the largest extent possible to 7491 * allow for architecture specific extent based optimizations. 7492 * 7493 * However, since clear_user_highpages() (and primitives clear_user_pages(), 7494 * clear_pages()), do not call cond_resched(), limit the unit size when 7495 * running under non-preemptible scheduling models. 7496 */ 7497 const unsigned int unit = preempt_model_preemptible() ? 7498 nr_pages : PROCESS_PAGES_NON_PREEMPT_BATCH; 7499 7500 might_sleep(); 7501 7502 for (i = 0; i < nr_pages; i += count) { 7503 cond_resched(); 7504 7505 count = min(unit, nr_pages - i); 7506 clear_user_highpages(page + i, addr + i * PAGE_SIZE, count); 7507 } 7508 } 7509 7510 /* 7511 * When zeroing a folio, we want to differentiate between pages in the 7512 * vicinity of the faulting address where we have spatial and temporal 7513 * locality, and those far away where we don't. 7514 * 7515 * Use a radius of 2 for determining the local neighbourhood. 7516 */ 7517 #define FOLIO_ZERO_LOCALITY_RADIUS 2 7518 7519 /** 7520 * folio_zero_user - Zero a folio which will be mapped to userspace. 7521 * @folio: The folio to zero. 7522 * @addr_hint: The address accessed by the user or the base address. 7523 */ 7524 void folio_zero_user(struct folio *folio, unsigned long addr_hint) 7525 { 7526 const unsigned long base_addr = ALIGN_DOWN(addr_hint, folio_size(folio)); 7527 const long fault_idx = (addr_hint - base_addr) / PAGE_SIZE; 7528 const struct range pg = DEFINE_RANGE(0, folio_nr_pages(folio) - 1); 7529 const long radius = FOLIO_ZERO_LOCALITY_RADIUS; 7530 struct range r[3]; 7531 int i; 7532 7533 /* 7534 * Faulting page and its immediate neighbourhood. Will be cleared at the 7535 * end to keep its cachelines hot. 7536 */ 7537 r[2] = DEFINE_RANGE(fault_idx - radius < (long)pg.start ? pg.start : fault_idx - radius, 7538 fault_idx + radius > (long)pg.end ? pg.end : fault_idx + radius); 7539 7540 7541 /* Region to the left of the fault */ 7542 r[1] = DEFINE_RANGE(pg.start, r[2].start - 1); 7543 7544 /* Region to the right of the fault: always valid for the common fault_idx=0 case. */ 7545 r[0] = DEFINE_RANGE(r[2].end + 1, pg.end); 7546 7547 for (i = 0; i < ARRAY_SIZE(r); i++) { 7548 const unsigned long addr = base_addr + r[i].start * PAGE_SIZE; 7549 const long nr_pages = (long)range_len(&r[i]); 7550 struct page *page = folio_page(folio, r[i].start); 7551 7552 if (nr_pages > 0) 7553 clear_contig_highpages(page, addr, nr_pages); 7554 } 7555 } 7556 7557 static int copy_user_gigantic_page(struct folio *dst, struct folio *src, 7558 unsigned long addr_hint, 7559 struct vm_area_struct *vma, 7560 unsigned int nr_pages) 7561 { 7562 unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(dst)); 7563 struct page *dst_page; 7564 struct page *src_page; 7565 int i; 7566 7567 for (i = 0; i < nr_pages; i++) { 7568 dst_page = folio_page(dst, i); 7569 src_page = folio_page(src, i); 7570 7571 cond_resched(); 7572 if (copy_mc_user_highpage(dst_page, src_page, 7573 addr + i*PAGE_SIZE, vma)) 7574 return -EHWPOISON; 7575 } 7576 return 0; 7577 } 7578 7579 struct copy_subpage_arg { 7580 struct folio *dst; 7581 struct folio *src; 7582 struct vm_area_struct *vma; 7583 }; 7584 7585 static int copy_subpage(unsigned long addr, int idx, void *arg) 7586 { 7587 struct copy_subpage_arg *copy_arg = arg; 7588 struct page *dst = folio_page(copy_arg->dst, idx); 7589 struct page *src = folio_page(copy_arg->src, idx); 7590 7591 if (copy_mc_user_highpage(dst, src, addr, copy_arg->vma)) 7592 return -EHWPOISON; 7593 return 0; 7594 } 7595 7596 int copy_user_large_folio(struct folio *dst, struct folio *src, 7597 unsigned long addr_hint, struct vm_area_struct *vma) 7598 { 7599 unsigned int nr_pages = folio_nr_pages(dst); 7600 struct copy_subpage_arg arg = { 7601 .dst = dst, 7602 .src = src, 7603 .vma = vma, 7604 }; 7605 7606 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) 7607 return copy_user_gigantic_page(dst, src, addr_hint, vma, nr_pages); 7608 7609 return process_huge_page(addr_hint, nr_pages, copy_subpage, &arg); 7610 } 7611 7612 long copy_folio_from_user(struct folio *dst_folio, 7613 const void __user *usr_src, 7614 bool allow_pagefault) 7615 { 7616 void *kaddr; 7617 unsigned long i, rc = 0; 7618 unsigned int nr_pages = folio_nr_pages(dst_folio); 7619 unsigned long ret_val = nr_pages * PAGE_SIZE; 7620 struct page *subpage; 7621 7622 for (i = 0; i < nr_pages; i++) { 7623 subpage = folio_page(dst_folio, i); 7624 kaddr = kmap_local_page(subpage); 7625 if (!allow_pagefault) 7626 pagefault_disable(); 7627 rc = copy_from_user(kaddr, usr_src + i * PAGE_SIZE, PAGE_SIZE); 7628 if (!allow_pagefault) 7629 pagefault_enable(); 7630 kunmap_local(kaddr); 7631 7632 ret_val -= (PAGE_SIZE - rc); 7633 if (rc) 7634 break; 7635 7636 flush_dcache_page(subpage); 7637 7638 cond_resched(); 7639 } 7640 return ret_val; 7641 } 7642 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */ 7643 7644 #if defined(CONFIG_SPLIT_PTE_PTLOCKS) && ALLOC_SPLIT_PTLOCKS 7645 7646 static struct kmem_cache *page_ptl_cachep; 7647 7648 void __init ptlock_cache_init(void) 7649 { 7650 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0, 7651 SLAB_PANIC, NULL); 7652 } 7653 7654 bool ptlock_alloc(struct ptdesc *ptdesc) 7655 { 7656 spinlock_t *ptl; 7657 7658 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL); 7659 if (!ptl) 7660 return false; 7661 ptdesc->ptl = ptl; 7662 return true; 7663 } 7664 7665 void ptlock_free(struct ptdesc *ptdesc) 7666 { 7667 if (ptdesc->ptl) 7668 kmem_cache_free(page_ptl_cachep, ptdesc->ptl); 7669 } 7670 #endif 7671 7672 void vma_pgtable_walk_begin(struct vm_area_struct *vma) 7673 { 7674 if (is_vm_hugetlb_page(vma)) 7675 hugetlb_vma_lock_read(vma); 7676 } 7677 7678 void vma_pgtable_walk_end(struct vm_area_struct *vma) 7679 { 7680 if (is_vm_hugetlb_page(vma)) 7681 hugetlb_vma_unlock_read(vma); 7682 } 7683