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