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