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