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/coredump.h> 47 #include <linux/sched/numa_balancing.h> 48 #include <linux/sched/task.h> 49 #include <linux/hugetlb.h> 50 #include <linux/mman.h> 51 #include <linux/swap.h> 52 #include <linux/highmem.h> 53 #include <linux/pagemap.h> 54 #include <linux/memremap.h> 55 #include <linux/ksm.h> 56 #include <linux/rmap.h> 57 #include <linux/export.h> 58 #include <linux/delayacct.h> 59 #include <linux/init.h> 60 #include <linux/pfn_t.h> 61 #include <linux/writeback.h> 62 #include <linux/memcontrol.h> 63 #include <linux/mmu_notifier.h> 64 #include <linux/swapops.h> 65 #include <linux/elf.h> 66 #include <linux/gfp.h> 67 #include <linux/migrate.h> 68 #include <linux/string.h> 69 #include <linux/debugfs.h> 70 #include <linux/userfaultfd_k.h> 71 #include <linux/dax.h> 72 #include <linux/oom.h> 73 #include <linux/numa.h> 74 #include <linux/perf_event.h> 75 #include <linux/ptrace.h> 76 #include <linux/vmalloc.h> 77 #include <linux/sched/sysctl.h> 78 79 #include <trace/events/kmem.h> 80 81 #include <asm/io.h> 82 #include <asm/mmu_context.h> 83 #include <asm/pgalloc.h> 84 #include <linux/uaccess.h> 85 #include <asm/tlb.h> 86 #include <asm/tlbflush.h> 87 88 #include "pgalloc-track.h" 89 #include "internal.h" 90 #include "swap.h" 91 92 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST) 93 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid. 94 #endif 95 96 #ifndef CONFIG_NUMA 97 unsigned long max_mapnr; 98 EXPORT_SYMBOL(max_mapnr); 99 100 struct page *mem_map; 101 EXPORT_SYMBOL(mem_map); 102 #endif 103 104 static vm_fault_t do_fault(struct vm_fault *vmf); 105 106 /* 107 * A number of key systems in x86 including ioremap() rely on the assumption 108 * that high_memory defines the upper bound on direct map memory, then end 109 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and 110 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL 111 * and ZONE_HIGHMEM. 112 */ 113 void *high_memory; 114 EXPORT_SYMBOL(high_memory); 115 116 /* 117 * Randomize the address space (stacks, mmaps, brk, etc.). 118 * 119 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization, 120 * as ancient (libc5 based) binaries can segfault. ) 121 */ 122 int randomize_va_space __read_mostly = 123 #ifdef CONFIG_COMPAT_BRK 124 1; 125 #else 126 2; 127 #endif 128 129 #ifndef arch_wants_old_prefaulted_pte 130 static inline bool arch_wants_old_prefaulted_pte(void) 131 { 132 /* 133 * Transitioning a PTE from 'old' to 'young' can be expensive on 134 * some architectures, even if it's performed in hardware. By 135 * default, "false" means prefaulted entries will be 'young'. 136 */ 137 return false; 138 } 139 #endif 140 141 static int __init disable_randmaps(char *s) 142 { 143 randomize_va_space = 0; 144 return 1; 145 } 146 __setup("norandmaps", disable_randmaps); 147 148 unsigned long zero_pfn __read_mostly; 149 EXPORT_SYMBOL(zero_pfn); 150 151 unsigned long highest_memmap_pfn __read_mostly; 152 153 /* 154 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init() 155 */ 156 static int __init init_zero_pfn(void) 157 { 158 zero_pfn = page_to_pfn(ZERO_PAGE(0)); 159 return 0; 160 } 161 early_initcall(init_zero_pfn); 162 163 void mm_trace_rss_stat(struct mm_struct *mm, int member, long count) 164 { 165 trace_rss_stat(mm, member, count); 166 } 167 168 #if defined(SPLIT_RSS_COUNTING) 169 170 void sync_mm_rss(struct mm_struct *mm) 171 { 172 int i; 173 174 for (i = 0; i < NR_MM_COUNTERS; i++) { 175 if (current->rss_stat.count[i]) { 176 add_mm_counter(mm, i, current->rss_stat.count[i]); 177 current->rss_stat.count[i] = 0; 178 } 179 } 180 current->rss_stat.events = 0; 181 } 182 183 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val) 184 { 185 struct task_struct *task = current; 186 187 if (likely(task->mm == mm)) 188 task->rss_stat.count[member] += val; 189 else 190 add_mm_counter(mm, member, val); 191 } 192 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1) 193 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1) 194 195 /* sync counter once per 64 page faults */ 196 #define TASK_RSS_EVENTS_THRESH (64) 197 static void check_sync_rss_stat(struct task_struct *task) 198 { 199 if (unlikely(task != current)) 200 return; 201 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH)) 202 sync_mm_rss(task->mm); 203 } 204 #else /* SPLIT_RSS_COUNTING */ 205 206 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member) 207 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member) 208 209 static void check_sync_rss_stat(struct task_struct *task) 210 { 211 } 212 213 #endif /* SPLIT_RSS_COUNTING */ 214 215 /* 216 * Note: this doesn't free the actual pages themselves. That 217 * has been handled earlier when unmapping all the memory regions. 218 */ 219 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd, 220 unsigned long addr) 221 { 222 pgtable_t token = pmd_pgtable(*pmd); 223 pmd_clear(pmd); 224 pte_free_tlb(tlb, token, addr); 225 mm_dec_nr_ptes(tlb->mm); 226 } 227 228 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud, 229 unsigned long addr, unsigned long end, 230 unsigned long floor, unsigned long ceiling) 231 { 232 pmd_t *pmd; 233 unsigned long next; 234 unsigned long start; 235 236 start = addr; 237 pmd = pmd_offset(pud, addr); 238 do { 239 next = pmd_addr_end(addr, end); 240 if (pmd_none_or_clear_bad(pmd)) 241 continue; 242 free_pte_range(tlb, pmd, addr); 243 } while (pmd++, addr = next, addr != end); 244 245 start &= PUD_MASK; 246 if (start < floor) 247 return; 248 if (ceiling) { 249 ceiling &= PUD_MASK; 250 if (!ceiling) 251 return; 252 } 253 if (end - 1 > ceiling - 1) 254 return; 255 256 pmd = pmd_offset(pud, start); 257 pud_clear(pud); 258 pmd_free_tlb(tlb, pmd, start); 259 mm_dec_nr_pmds(tlb->mm); 260 } 261 262 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d, 263 unsigned long addr, unsigned long end, 264 unsigned long floor, unsigned long ceiling) 265 { 266 pud_t *pud; 267 unsigned long next; 268 unsigned long start; 269 270 start = addr; 271 pud = pud_offset(p4d, addr); 272 do { 273 next = pud_addr_end(addr, end); 274 if (pud_none_or_clear_bad(pud)) 275 continue; 276 free_pmd_range(tlb, pud, addr, next, floor, ceiling); 277 } while (pud++, addr = next, addr != end); 278 279 start &= P4D_MASK; 280 if (start < floor) 281 return; 282 if (ceiling) { 283 ceiling &= P4D_MASK; 284 if (!ceiling) 285 return; 286 } 287 if (end - 1 > ceiling - 1) 288 return; 289 290 pud = pud_offset(p4d, start); 291 p4d_clear(p4d); 292 pud_free_tlb(tlb, pud, start); 293 mm_dec_nr_puds(tlb->mm); 294 } 295 296 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd, 297 unsigned long addr, unsigned long end, 298 unsigned long floor, unsigned long ceiling) 299 { 300 p4d_t *p4d; 301 unsigned long next; 302 unsigned long start; 303 304 start = addr; 305 p4d = p4d_offset(pgd, addr); 306 do { 307 next = p4d_addr_end(addr, end); 308 if (p4d_none_or_clear_bad(p4d)) 309 continue; 310 free_pud_range(tlb, p4d, addr, next, floor, ceiling); 311 } while (p4d++, addr = next, addr != end); 312 313 start &= PGDIR_MASK; 314 if (start < floor) 315 return; 316 if (ceiling) { 317 ceiling &= PGDIR_MASK; 318 if (!ceiling) 319 return; 320 } 321 if (end - 1 > ceiling - 1) 322 return; 323 324 p4d = p4d_offset(pgd, start); 325 pgd_clear(pgd); 326 p4d_free_tlb(tlb, p4d, start); 327 } 328 329 /* 330 * This function frees user-level page tables of a process. 331 */ 332 void free_pgd_range(struct mmu_gather *tlb, 333 unsigned long addr, unsigned long end, 334 unsigned long floor, unsigned long ceiling) 335 { 336 pgd_t *pgd; 337 unsigned long next; 338 339 /* 340 * The next few lines have given us lots of grief... 341 * 342 * Why are we testing PMD* at this top level? Because often 343 * there will be no work to do at all, and we'd prefer not to 344 * go all the way down to the bottom just to discover that. 345 * 346 * Why all these "- 1"s? Because 0 represents both the bottom 347 * of the address space and the top of it (using -1 for the 348 * top wouldn't help much: the masks would do the wrong thing). 349 * The rule is that addr 0 and floor 0 refer to the bottom of 350 * the address space, but end 0 and ceiling 0 refer to the top 351 * Comparisons need to use "end - 1" and "ceiling - 1" (though 352 * that end 0 case should be mythical). 353 * 354 * Wherever addr is brought up or ceiling brought down, we must 355 * be careful to reject "the opposite 0" before it confuses the 356 * subsequent tests. But what about where end is brought down 357 * by PMD_SIZE below? no, end can't go down to 0 there. 358 * 359 * Whereas we round start (addr) and ceiling down, by different 360 * masks at different levels, in order to test whether a table 361 * now has no other vmas using it, so can be freed, we don't 362 * bother to round floor or end up - the tests don't need that. 363 */ 364 365 addr &= PMD_MASK; 366 if (addr < floor) { 367 addr += PMD_SIZE; 368 if (!addr) 369 return; 370 } 371 if (ceiling) { 372 ceiling &= PMD_MASK; 373 if (!ceiling) 374 return; 375 } 376 if (end - 1 > ceiling - 1) 377 end -= PMD_SIZE; 378 if (addr > end - 1) 379 return; 380 /* 381 * We add page table cache pages with PAGE_SIZE, 382 * (see pte_free_tlb()), flush the tlb if we need 383 */ 384 tlb_change_page_size(tlb, PAGE_SIZE); 385 pgd = pgd_offset(tlb->mm, addr); 386 do { 387 next = pgd_addr_end(addr, end); 388 if (pgd_none_or_clear_bad(pgd)) 389 continue; 390 free_p4d_range(tlb, pgd, addr, next, floor, ceiling); 391 } while (pgd++, addr = next, addr != end); 392 } 393 394 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma, 395 unsigned long floor, unsigned long ceiling) 396 { 397 while (vma) { 398 struct vm_area_struct *next = vma->vm_next; 399 unsigned long addr = vma->vm_start; 400 401 /* 402 * Hide vma from rmap and truncate_pagecache before freeing 403 * pgtables 404 */ 405 unlink_anon_vmas(vma); 406 unlink_file_vma(vma); 407 408 if (is_vm_hugetlb_page(vma)) { 409 hugetlb_free_pgd_range(tlb, addr, vma->vm_end, 410 floor, next ? next->vm_start : ceiling); 411 } else { 412 /* 413 * Optimization: gather nearby vmas into one call down 414 */ 415 while (next && next->vm_start <= vma->vm_end + PMD_SIZE 416 && !is_vm_hugetlb_page(next)) { 417 vma = next; 418 next = vma->vm_next; 419 unlink_anon_vmas(vma); 420 unlink_file_vma(vma); 421 } 422 free_pgd_range(tlb, addr, vma->vm_end, 423 floor, next ? next->vm_start : ceiling); 424 } 425 vma = next; 426 } 427 } 428 429 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte) 430 { 431 spinlock_t *ptl = pmd_lock(mm, pmd); 432 433 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ 434 mm_inc_nr_ptes(mm); 435 /* 436 * Ensure all pte setup (eg. pte page lock and page clearing) are 437 * visible before the pte is made visible to other CPUs by being 438 * put into page tables. 439 * 440 * The other side of the story is the pointer chasing in the page 441 * table walking code (when walking the page table without locking; 442 * ie. most of the time). Fortunately, these data accesses consist 443 * of a chain of data-dependent loads, meaning most CPUs (alpha 444 * being the notable exception) will already guarantee loads are 445 * seen in-order. See the alpha page table accessors for the 446 * smp_rmb() barriers in page table walking code. 447 */ 448 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */ 449 pmd_populate(mm, pmd, *pte); 450 *pte = NULL; 451 } 452 spin_unlock(ptl); 453 } 454 455 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd) 456 { 457 pgtable_t new = pte_alloc_one(mm); 458 if (!new) 459 return -ENOMEM; 460 461 pmd_install(mm, pmd, &new); 462 if (new) 463 pte_free(mm, new); 464 return 0; 465 } 466 467 int __pte_alloc_kernel(pmd_t *pmd) 468 { 469 pte_t *new = pte_alloc_one_kernel(&init_mm); 470 if (!new) 471 return -ENOMEM; 472 473 spin_lock(&init_mm.page_table_lock); 474 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ 475 smp_wmb(); /* See comment in pmd_install() */ 476 pmd_populate_kernel(&init_mm, pmd, new); 477 new = NULL; 478 } 479 spin_unlock(&init_mm.page_table_lock); 480 if (new) 481 pte_free_kernel(&init_mm, new); 482 return 0; 483 } 484 485 static inline void init_rss_vec(int *rss) 486 { 487 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS); 488 } 489 490 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss) 491 { 492 int i; 493 494 if (current->mm == mm) 495 sync_mm_rss(mm); 496 for (i = 0; i < NR_MM_COUNTERS; i++) 497 if (rss[i]) 498 add_mm_counter(mm, i, rss[i]); 499 } 500 501 /* 502 * This function is called to print an error when a bad pte 503 * is found. For example, we might have a PFN-mapped pte in 504 * a region that doesn't allow it. 505 * 506 * The calling function must still handle the error. 507 */ 508 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr, 509 pte_t pte, struct page *page) 510 { 511 pgd_t *pgd = pgd_offset(vma->vm_mm, addr); 512 p4d_t *p4d = p4d_offset(pgd, addr); 513 pud_t *pud = pud_offset(p4d, addr); 514 pmd_t *pmd = pmd_offset(pud, addr); 515 struct address_space *mapping; 516 pgoff_t index; 517 static unsigned long resume; 518 static unsigned long nr_shown; 519 static unsigned long nr_unshown; 520 521 /* 522 * Allow a burst of 60 reports, then keep quiet for that minute; 523 * or allow a steady drip of one report per second. 524 */ 525 if (nr_shown == 60) { 526 if (time_before(jiffies, resume)) { 527 nr_unshown++; 528 return; 529 } 530 if (nr_unshown) { 531 pr_alert("BUG: Bad page map: %lu messages suppressed\n", 532 nr_unshown); 533 nr_unshown = 0; 534 } 535 nr_shown = 0; 536 } 537 if (nr_shown++ == 0) 538 resume = jiffies + 60 * HZ; 539 540 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL; 541 index = linear_page_index(vma, addr); 542 543 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n", 544 current->comm, 545 (long long)pte_val(pte), (long long)pmd_val(*pmd)); 546 if (page) 547 dump_page(page, "bad pte"); 548 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n", 549 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index); 550 pr_alert("file:%pD fault:%ps mmap:%ps read_folio:%ps\n", 551 vma->vm_file, 552 vma->vm_ops ? vma->vm_ops->fault : NULL, 553 vma->vm_file ? vma->vm_file->f_op->mmap : NULL, 554 mapping ? mapping->a_ops->read_folio : NULL); 555 dump_stack(); 556 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 557 } 558 559 /* 560 * vm_normal_page -- This function gets the "struct page" associated with a pte. 561 * 562 * "Special" mappings do not wish to be associated with a "struct page" (either 563 * it doesn't exist, or it exists but they don't want to touch it). In this 564 * case, NULL is returned here. "Normal" mappings do have a struct page. 565 * 566 * There are 2 broad cases. Firstly, an architecture may define a pte_special() 567 * pte bit, in which case this function is trivial. Secondly, an architecture 568 * may not have a spare pte bit, which requires a more complicated scheme, 569 * described below. 570 * 571 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a 572 * special mapping (even if there are underlying and valid "struct pages"). 573 * COWed pages of a VM_PFNMAP are always normal. 574 * 575 * The way we recognize COWed pages within VM_PFNMAP mappings is through the 576 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit 577 * set, and the vm_pgoff will point to the first PFN mapped: thus every special 578 * mapping will always honor the rule 579 * 580 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT) 581 * 582 * And for normal mappings this is false. 583 * 584 * This restricts such mappings to be a linear translation from virtual address 585 * to pfn. To get around this restriction, we allow arbitrary mappings so long 586 * as the vma is not a COW mapping; in that case, we know that all ptes are 587 * special (because none can have been COWed). 588 * 589 * 590 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP. 591 * 592 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct 593 * page" backing, however the difference is that _all_ pages with a struct 594 * page (that is, those where pfn_valid is true) are refcounted and considered 595 * normal pages by the VM. The disadvantage is that pages are refcounted 596 * (which can be slower and simply not an option for some PFNMAP users). The 597 * advantage is that we don't have to follow the strict linearity rule of 598 * PFNMAP mappings in order to support COWable mappings. 599 * 600 */ 601 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, 602 pte_t pte) 603 { 604 unsigned long pfn = pte_pfn(pte); 605 606 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) { 607 if (likely(!pte_special(pte))) 608 goto check_pfn; 609 if (vma->vm_ops && vma->vm_ops->find_special_page) 610 return vma->vm_ops->find_special_page(vma, addr); 611 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP)) 612 return NULL; 613 if (is_zero_pfn(pfn)) 614 return NULL; 615 if (pte_devmap(pte)) 616 /* 617 * NOTE: New users of ZONE_DEVICE will not set pte_devmap() 618 * and will have refcounts incremented on their struct pages 619 * when they are inserted into PTEs, thus they are safe to 620 * return here. Legacy ZONE_DEVICE pages that set pte_devmap() 621 * do not have refcounts. Example of legacy ZONE_DEVICE is 622 * MEMORY_DEVICE_FS_DAX type in pmem or virtio_fs drivers. 623 */ 624 return NULL; 625 626 print_bad_pte(vma, addr, pte, NULL); 627 return NULL; 628 } 629 630 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */ 631 632 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) { 633 if (vma->vm_flags & VM_MIXEDMAP) { 634 if (!pfn_valid(pfn)) 635 return NULL; 636 goto out; 637 } else { 638 unsigned long off; 639 off = (addr - vma->vm_start) >> PAGE_SHIFT; 640 if (pfn == vma->vm_pgoff + off) 641 return NULL; 642 if (!is_cow_mapping(vma->vm_flags)) 643 return NULL; 644 } 645 } 646 647 if (is_zero_pfn(pfn)) 648 return NULL; 649 650 check_pfn: 651 if (unlikely(pfn > highest_memmap_pfn)) { 652 print_bad_pte(vma, addr, pte, NULL); 653 return NULL; 654 } 655 656 /* 657 * NOTE! We still have PageReserved() pages in the page tables. 658 * eg. VDSO mappings can cause them to exist. 659 */ 660 out: 661 return pfn_to_page(pfn); 662 } 663 664 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 665 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr, 666 pmd_t pmd) 667 { 668 unsigned long pfn = pmd_pfn(pmd); 669 670 /* 671 * There is no pmd_special() but there may be special pmds, e.g. 672 * in a direct-access (dax) mapping, so let's just replicate the 673 * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here. 674 */ 675 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) { 676 if (vma->vm_flags & VM_MIXEDMAP) { 677 if (!pfn_valid(pfn)) 678 return NULL; 679 goto out; 680 } else { 681 unsigned long off; 682 off = (addr - vma->vm_start) >> PAGE_SHIFT; 683 if (pfn == vma->vm_pgoff + off) 684 return NULL; 685 if (!is_cow_mapping(vma->vm_flags)) 686 return NULL; 687 } 688 } 689 690 if (pmd_devmap(pmd)) 691 return NULL; 692 if (is_huge_zero_pmd(pmd)) 693 return NULL; 694 if (unlikely(pfn > highest_memmap_pfn)) 695 return NULL; 696 697 /* 698 * NOTE! We still have PageReserved() pages in the page tables. 699 * eg. VDSO mappings can cause them to exist. 700 */ 701 out: 702 return pfn_to_page(pfn); 703 } 704 #endif 705 706 static void restore_exclusive_pte(struct vm_area_struct *vma, 707 struct page *page, unsigned long address, 708 pte_t *ptep) 709 { 710 pte_t pte; 711 swp_entry_t entry; 712 713 pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot))); 714 if (pte_swp_soft_dirty(*ptep)) 715 pte = pte_mksoft_dirty(pte); 716 717 entry = pte_to_swp_entry(*ptep); 718 if (pte_swp_uffd_wp(*ptep)) 719 pte = pte_mkuffd_wp(pte); 720 else if (is_writable_device_exclusive_entry(entry)) 721 pte = maybe_mkwrite(pte_mkdirty(pte), vma); 722 723 VM_BUG_ON(pte_write(pte) && !(PageAnon(page) && PageAnonExclusive(page))); 724 725 /* 726 * No need to take a page reference as one was already 727 * created when the swap entry was made. 728 */ 729 if (PageAnon(page)) 730 page_add_anon_rmap(page, vma, address, RMAP_NONE); 731 else 732 /* 733 * Currently device exclusive access only supports anonymous 734 * memory so the entry shouldn't point to a filebacked page. 735 */ 736 WARN_ON_ONCE(1); 737 738 set_pte_at(vma->vm_mm, address, ptep, pte); 739 740 /* 741 * No need to invalidate - it was non-present before. However 742 * secondary CPUs may have mappings that need invalidating. 743 */ 744 update_mmu_cache(vma, address, ptep); 745 } 746 747 /* 748 * Tries to restore an exclusive pte if the page lock can be acquired without 749 * sleeping. 750 */ 751 static int 752 try_restore_exclusive_pte(pte_t *src_pte, struct vm_area_struct *vma, 753 unsigned long addr) 754 { 755 swp_entry_t entry = pte_to_swp_entry(*src_pte); 756 struct page *page = pfn_swap_entry_to_page(entry); 757 758 if (trylock_page(page)) { 759 restore_exclusive_pte(vma, page, addr, src_pte); 760 unlock_page(page); 761 return 0; 762 } 763 764 return -EBUSY; 765 } 766 767 /* 768 * copy one vm_area from one task to the other. Assumes the page tables 769 * already present in the new task to be cleared in the whole range 770 * covered by this vma. 771 */ 772 773 static unsigned long 774 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm, 775 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma, 776 struct vm_area_struct *src_vma, unsigned long addr, int *rss) 777 { 778 unsigned long vm_flags = dst_vma->vm_flags; 779 pte_t pte = *src_pte; 780 struct page *page; 781 swp_entry_t entry = pte_to_swp_entry(pte); 782 783 if (likely(!non_swap_entry(entry))) { 784 if (swap_duplicate(entry) < 0) 785 return -EIO; 786 787 /* make sure dst_mm is on swapoff's mmlist. */ 788 if (unlikely(list_empty(&dst_mm->mmlist))) { 789 spin_lock(&mmlist_lock); 790 if (list_empty(&dst_mm->mmlist)) 791 list_add(&dst_mm->mmlist, 792 &src_mm->mmlist); 793 spin_unlock(&mmlist_lock); 794 } 795 /* Mark the swap entry as shared. */ 796 if (pte_swp_exclusive(*src_pte)) { 797 pte = pte_swp_clear_exclusive(*src_pte); 798 set_pte_at(src_mm, addr, src_pte, pte); 799 } 800 rss[MM_SWAPENTS]++; 801 } else if (is_migration_entry(entry)) { 802 page = pfn_swap_entry_to_page(entry); 803 804 rss[mm_counter(page)]++; 805 806 if (!is_readable_migration_entry(entry) && 807 is_cow_mapping(vm_flags)) { 808 /* 809 * COW mappings require pages in both parent and child 810 * to be set to read. A previously exclusive entry is 811 * now shared. 812 */ 813 entry = make_readable_migration_entry( 814 swp_offset(entry)); 815 pte = swp_entry_to_pte(entry); 816 if (pte_swp_soft_dirty(*src_pte)) 817 pte = pte_swp_mksoft_dirty(pte); 818 if (pte_swp_uffd_wp(*src_pte)) 819 pte = pte_swp_mkuffd_wp(pte); 820 set_pte_at(src_mm, addr, src_pte, pte); 821 } 822 } else if (is_device_private_entry(entry)) { 823 page = pfn_swap_entry_to_page(entry); 824 825 /* 826 * Update rss count even for unaddressable pages, as 827 * they should treated just like normal pages in this 828 * respect. 829 * 830 * We will likely want to have some new rss counters 831 * for unaddressable pages, at some point. But for now 832 * keep things as they are. 833 */ 834 get_page(page); 835 rss[mm_counter(page)]++; 836 /* Cannot fail as these pages cannot get pinned. */ 837 BUG_ON(page_try_dup_anon_rmap(page, false, src_vma)); 838 839 /* 840 * We do not preserve soft-dirty information, because so 841 * far, checkpoint/restore is the only feature that 842 * requires that. And checkpoint/restore does not work 843 * when a device driver is involved (you cannot easily 844 * save and restore device driver state). 845 */ 846 if (is_writable_device_private_entry(entry) && 847 is_cow_mapping(vm_flags)) { 848 entry = make_readable_device_private_entry( 849 swp_offset(entry)); 850 pte = swp_entry_to_pte(entry); 851 if (pte_swp_uffd_wp(*src_pte)) 852 pte = pte_swp_mkuffd_wp(pte); 853 set_pte_at(src_mm, addr, src_pte, pte); 854 } 855 } else if (is_device_exclusive_entry(entry)) { 856 /* 857 * Make device exclusive entries present by restoring the 858 * original entry then copying as for a present pte. Device 859 * exclusive entries currently only support private writable 860 * (ie. COW) mappings. 861 */ 862 VM_BUG_ON(!is_cow_mapping(src_vma->vm_flags)); 863 if (try_restore_exclusive_pte(src_pte, src_vma, addr)) 864 return -EBUSY; 865 return -ENOENT; 866 } else if (is_pte_marker_entry(entry)) { 867 /* 868 * We're copying the pgtable should only because dst_vma has 869 * uffd-wp enabled, do sanity check. 870 */ 871 WARN_ON_ONCE(!userfaultfd_wp(dst_vma)); 872 set_pte_at(dst_mm, addr, dst_pte, pte); 873 return 0; 874 } 875 if (!userfaultfd_wp(dst_vma)) 876 pte = pte_swp_clear_uffd_wp(pte); 877 set_pte_at(dst_mm, addr, dst_pte, pte); 878 return 0; 879 } 880 881 /* 882 * Copy a present and normal page. 883 * 884 * NOTE! The usual case is that this isn't required; 885 * instead, the caller can just increase the page refcount 886 * and re-use the pte the traditional way. 887 * 888 * And if we need a pre-allocated page but don't yet have 889 * one, return a negative error to let the preallocation 890 * code know so that it can do so outside the page table 891 * lock. 892 */ 893 static inline int 894 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 895 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss, 896 struct page **prealloc, struct page *page) 897 { 898 struct page *new_page; 899 pte_t pte; 900 901 new_page = *prealloc; 902 if (!new_page) 903 return -EAGAIN; 904 905 /* 906 * We have a prealloc page, all good! Take it 907 * over and copy the page & arm it. 908 */ 909 *prealloc = NULL; 910 copy_user_highpage(new_page, page, addr, src_vma); 911 __SetPageUptodate(new_page); 912 page_add_new_anon_rmap(new_page, dst_vma, addr); 913 lru_cache_add_inactive_or_unevictable(new_page, dst_vma); 914 rss[mm_counter(new_page)]++; 915 916 /* All done, just insert the new page copy in the child */ 917 pte = mk_pte(new_page, dst_vma->vm_page_prot); 918 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma); 919 if (userfaultfd_pte_wp(dst_vma, *src_pte)) 920 /* Uffd-wp needs to be delivered to dest pte as well */ 921 pte = pte_wrprotect(pte_mkuffd_wp(pte)); 922 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte); 923 return 0; 924 } 925 926 /* 927 * Copy one pte. Returns 0 if succeeded, or -EAGAIN if one preallocated page 928 * is required to copy this pte. 929 */ 930 static inline int 931 copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 932 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss, 933 struct page **prealloc) 934 { 935 struct mm_struct *src_mm = src_vma->vm_mm; 936 unsigned long vm_flags = src_vma->vm_flags; 937 pte_t pte = *src_pte; 938 struct page *page; 939 940 page = vm_normal_page(src_vma, addr, pte); 941 if (page && PageAnon(page)) { 942 /* 943 * If this page may have been pinned by the parent process, 944 * copy the page immediately for the child so that we'll always 945 * guarantee the pinned page won't be randomly replaced in the 946 * future. 947 */ 948 get_page(page); 949 if (unlikely(page_try_dup_anon_rmap(page, false, src_vma))) { 950 /* Page maybe pinned, we have to copy. */ 951 put_page(page); 952 return copy_present_page(dst_vma, src_vma, dst_pte, src_pte, 953 addr, rss, prealloc, page); 954 } 955 rss[mm_counter(page)]++; 956 } else if (page) { 957 get_page(page); 958 page_dup_file_rmap(page, false); 959 rss[mm_counter(page)]++; 960 } 961 962 /* 963 * If it's a COW mapping, write protect it both 964 * in the parent and the child 965 */ 966 if (is_cow_mapping(vm_flags) && pte_write(pte)) { 967 ptep_set_wrprotect(src_mm, addr, src_pte); 968 pte = pte_wrprotect(pte); 969 } 970 VM_BUG_ON(page && PageAnon(page) && PageAnonExclusive(page)); 971 972 /* 973 * If it's a shared mapping, mark it clean in 974 * the child 975 */ 976 if (vm_flags & VM_SHARED) 977 pte = pte_mkclean(pte); 978 pte = pte_mkold(pte); 979 980 if (!userfaultfd_wp(dst_vma)) 981 pte = pte_clear_uffd_wp(pte); 982 983 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte); 984 return 0; 985 } 986 987 static inline struct page * 988 page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma, 989 unsigned long addr) 990 { 991 struct page *new_page; 992 993 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr); 994 if (!new_page) 995 return NULL; 996 997 if (mem_cgroup_charge(page_folio(new_page), src_mm, GFP_KERNEL)) { 998 put_page(new_page); 999 return NULL; 1000 } 1001 cgroup_throttle_swaprate(new_page, GFP_KERNEL); 1002 1003 return new_page; 1004 } 1005 1006 static int 1007 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1008 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr, 1009 unsigned long end) 1010 { 1011 struct mm_struct *dst_mm = dst_vma->vm_mm; 1012 struct mm_struct *src_mm = src_vma->vm_mm; 1013 pte_t *orig_src_pte, *orig_dst_pte; 1014 pte_t *src_pte, *dst_pte; 1015 spinlock_t *src_ptl, *dst_ptl; 1016 int progress, ret = 0; 1017 int rss[NR_MM_COUNTERS]; 1018 swp_entry_t entry = (swp_entry_t){0}; 1019 struct page *prealloc = NULL; 1020 1021 again: 1022 progress = 0; 1023 init_rss_vec(rss); 1024 1025 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl); 1026 if (!dst_pte) { 1027 ret = -ENOMEM; 1028 goto out; 1029 } 1030 src_pte = pte_offset_map(src_pmd, addr); 1031 src_ptl = pte_lockptr(src_mm, src_pmd); 1032 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1033 orig_src_pte = src_pte; 1034 orig_dst_pte = dst_pte; 1035 arch_enter_lazy_mmu_mode(); 1036 1037 do { 1038 /* 1039 * We are holding two locks at this point - either of them 1040 * could generate latencies in another task on another CPU. 1041 */ 1042 if (progress >= 32) { 1043 progress = 0; 1044 if (need_resched() || 1045 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl)) 1046 break; 1047 } 1048 if (pte_none(*src_pte)) { 1049 progress++; 1050 continue; 1051 } 1052 if (unlikely(!pte_present(*src_pte))) { 1053 ret = copy_nonpresent_pte(dst_mm, src_mm, 1054 dst_pte, src_pte, 1055 dst_vma, src_vma, 1056 addr, rss); 1057 if (ret == -EIO) { 1058 entry = pte_to_swp_entry(*src_pte); 1059 break; 1060 } else if (ret == -EBUSY) { 1061 break; 1062 } else if (!ret) { 1063 progress += 8; 1064 continue; 1065 } 1066 1067 /* 1068 * Device exclusive entry restored, continue by copying 1069 * the now present pte. 1070 */ 1071 WARN_ON_ONCE(ret != -ENOENT); 1072 } 1073 /* copy_present_pte() will clear `*prealloc' if consumed */ 1074 ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte, 1075 addr, rss, &prealloc); 1076 /* 1077 * If we need a pre-allocated page for this pte, drop the 1078 * locks, allocate, and try again. 1079 */ 1080 if (unlikely(ret == -EAGAIN)) 1081 break; 1082 if (unlikely(prealloc)) { 1083 /* 1084 * pre-alloc page cannot be reused by next time so as 1085 * to strictly follow mempolicy (e.g., alloc_page_vma() 1086 * will allocate page according to address). This 1087 * could only happen if one pinned pte changed. 1088 */ 1089 put_page(prealloc); 1090 prealloc = NULL; 1091 } 1092 progress += 8; 1093 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end); 1094 1095 arch_leave_lazy_mmu_mode(); 1096 spin_unlock(src_ptl); 1097 pte_unmap(orig_src_pte); 1098 add_mm_rss_vec(dst_mm, rss); 1099 pte_unmap_unlock(orig_dst_pte, dst_ptl); 1100 cond_resched(); 1101 1102 if (ret == -EIO) { 1103 VM_WARN_ON_ONCE(!entry.val); 1104 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) { 1105 ret = -ENOMEM; 1106 goto out; 1107 } 1108 entry.val = 0; 1109 } else if (ret == -EBUSY) { 1110 goto out; 1111 } else if (ret == -EAGAIN) { 1112 prealloc = page_copy_prealloc(src_mm, src_vma, addr); 1113 if (!prealloc) 1114 return -ENOMEM; 1115 } else if (ret) { 1116 VM_WARN_ON_ONCE(1); 1117 } 1118 1119 /* We've captured and resolved the error. Reset, try again. */ 1120 ret = 0; 1121 1122 if (addr != end) 1123 goto again; 1124 out: 1125 if (unlikely(prealloc)) 1126 put_page(prealloc); 1127 return ret; 1128 } 1129 1130 static inline int 1131 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1132 pud_t *dst_pud, pud_t *src_pud, unsigned long addr, 1133 unsigned long end) 1134 { 1135 struct mm_struct *dst_mm = dst_vma->vm_mm; 1136 struct mm_struct *src_mm = src_vma->vm_mm; 1137 pmd_t *src_pmd, *dst_pmd; 1138 unsigned long next; 1139 1140 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr); 1141 if (!dst_pmd) 1142 return -ENOMEM; 1143 src_pmd = pmd_offset(src_pud, addr); 1144 do { 1145 next = pmd_addr_end(addr, end); 1146 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd) 1147 || pmd_devmap(*src_pmd)) { 1148 int err; 1149 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma); 1150 err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd, 1151 addr, dst_vma, src_vma); 1152 if (err == -ENOMEM) 1153 return -ENOMEM; 1154 if (!err) 1155 continue; 1156 /* fall through */ 1157 } 1158 if (pmd_none_or_clear_bad(src_pmd)) 1159 continue; 1160 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd, 1161 addr, next)) 1162 return -ENOMEM; 1163 } while (dst_pmd++, src_pmd++, addr = next, addr != end); 1164 return 0; 1165 } 1166 1167 static inline int 1168 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1169 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr, 1170 unsigned long end) 1171 { 1172 struct mm_struct *dst_mm = dst_vma->vm_mm; 1173 struct mm_struct *src_mm = src_vma->vm_mm; 1174 pud_t *src_pud, *dst_pud; 1175 unsigned long next; 1176 1177 dst_pud = pud_alloc(dst_mm, dst_p4d, addr); 1178 if (!dst_pud) 1179 return -ENOMEM; 1180 src_pud = pud_offset(src_p4d, addr); 1181 do { 1182 next = pud_addr_end(addr, end); 1183 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) { 1184 int err; 1185 1186 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma); 1187 err = copy_huge_pud(dst_mm, src_mm, 1188 dst_pud, src_pud, addr, src_vma); 1189 if (err == -ENOMEM) 1190 return -ENOMEM; 1191 if (!err) 1192 continue; 1193 /* fall through */ 1194 } 1195 if (pud_none_or_clear_bad(src_pud)) 1196 continue; 1197 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud, 1198 addr, next)) 1199 return -ENOMEM; 1200 } while (dst_pud++, src_pud++, addr = next, addr != end); 1201 return 0; 1202 } 1203 1204 static inline int 1205 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1206 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr, 1207 unsigned long end) 1208 { 1209 struct mm_struct *dst_mm = dst_vma->vm_mm; 1210 p4d_t *src_p4d, *dst_p4d; 1211 unsigned long next; 1212 1213 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr); 1214 if (!dst_p4d) 1215 return -ENOMEM; 1216 src_p4d = p4d_offset(src_pgd, addr); 1217 do { 1218 next = p4d_addr_end(addr, end); 1219 if (p4d_none_or_clear_bad(src_p4d)) 1220 continue; 1221 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d, 1222 addr, next)) 1223 return -ENOMEM; 1224 } while (dst_p4d++, src_p4d++, addr = next, addr != end); 1225 return 0; 1226 } 1227 1228 /* 1229 * Return true if the vma needs to copy the pgtable during this fork(). Return 1230 * false when we can speed up fork() by allowing lazy page faults later until 1231 * when the child accesses the memory range. 1232 */ 1233 static bool 1234 vma_needs_copy(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma) 1235 { 1236 /* 1237 * Always copy pgtables when dst_vma has uffd-wp enabled even if it's 1238 * file-backed (e.g. shmem). Because when uffd-wp is enabled, pgtable 1239 * contains uffd-wp protection information, that's something we can't 1240 * retrieve from page cache, and skip copying will lose those info. 1241 */ 1242 if (userfaultfd_wp(dst_vma)) 1243 return true; 1244 1245 if (src_vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP)) 1246 return true; 1247 1248 if (src_vma->anon_vma) 1249 return true; 1250 1251 /* 1252 * Don't copy ptes where a page fault will fill them correctly. Fork 1253 * becomes much lighter when there are big shared or private readonly 1254 * mappings. The tradeoff is that copy_page_range is more efficient 1255 * than faulting. 1256 */ 1257 return false; 1258 } 1259 1260 int 1261 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma) 1262 { 1263 pgd_t *src_pgd, *dst_pgd; 1264 unsigned long next; 1265 unsigned long addr = src_vma->vm_start; 1266 unsigned long end = src_vma->vm_end; 1267 struct mm_struct *dst_mm = dst_vma->vm_mm; 1268 struct mm_struct *src_mm = src_vma->vm_mm; 1269 struct mmu_notifier_range range; 1270 bool is_cow; 1271 int ret; 1272 1273 if (!vma_needs_copy(dst_vma, src_vma)) 1274 return 0; 1275 1276 if (is_vm_hugetlb_page(src_vma)) 1277 return copy_hugetlb_page_range(dst_mm, src_mm, dst_vma, src_vma); 1278 1279 if (unlikely(src_vma->vm_flags & VM_PFNMAP)) { 1280 /* 1281 * We do not free on error cases below as remove_vma 1282 * gets called on error from higher level routine 1283 */ 1284 ret = track_pfn_copy(src_vma); 1285 if (ret) 1286 return ret; 1287 } 1288 1289 /* 1290 * We need to invalidate the secondary MMU mappings only when 1291 * there could be a permission downgrade on the ptes of the 1292 * parent mm. And a permission downgrade will only happen if 1293 * is_cow_mapping() returns true. 1294 */ 1295 is_cow = is_cow_mapping(src_vma->vm_flags); 1296 1297 if (is_cow) { 1298 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE, 1299 0, src_vma, src_mm, addr, end); 1300 mmu_notifier_invalidate_range_start(&range); 1301 /* 1302 * Disabling preemption is not needed for the write side, as 1303 * the read side doesn't spin, but goes to the mmap_lock. 1304 * 1305 * Use the raw variant of the seqcount_t write API to avoid 1306 * lockdep complaining about preemptibility. 1307 */ 1308 mmap_assert_write_locked(src_mm); 1309 raw_write_seqcount_begin(&src_mm->write_protect_seq); 1310 } 1311 1312 ret = 0; 1313 dst_pgd = pgd_offset(dst_mm, addr); 1314 src_pgd = pgd_offset(src_mm, addr); 1315 do { 1316 next = pgd_addr_end(addr, end); 1317 if (pgd_none_or_clear_bad(src_pgd)) 1318 continue; 1319 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd, 1320 addr, next))) { 1321 ret = -ENOMEM; 1322 break; 1323 } 1324 } while (dst_pgd++, src_pgd++, addr = next, addr != end); 1325 1326 if (is_cow) { 1327 raw_write_seqcount_end(&src_mm->write_protect_seq); 1328 mmu_notifier_invalidate_range_end(&range); 1329 } 1330 return ret; 1331 } 1332 1333 /* 1334 * Parameter block passed down to zap_pte_range in exceptional cases. 1335 */ 1336 struct zap_details { 1337 struct folio *single_folio; /* Locked folio to be unmapped */ 1338 bool even_cows; /* Zap COWed private pages too? */ 1339 zap_flags_t zap_flags; /* Extra flags for zapping */ 1340 }; 1341 1342 /* Whether we should zap all COWed (private) pages too */ 1343 static inline bool should_zap_cows(struct zap_details *details) 1344 { 1345 /* By default, zap all pages */ 1346 if (!details) 1347 return true; 1348 1349 /* Or, we zap COWed pages only if the caller wants to */ 1350 return details->even_cows; 1351 } 1352 1353 /* Decides whether we should zap this page with the page pointer specified */ 1354 static inline bool should_zap_page(struct zap_details *details, struct page *page) 1355 { 1356 /* If we can make a decision without *page.. */ 1357 if (should_zap_cows(details)) 1358 return true; 1359 1360 /* E.g. the caller passes NULL for the case of a zero page */ 1361 if (!page) 1362 return true; 1363 1364 /* Otherwise we should only zap non-anon pages */ 1365 return !PageAnon(page); 1366 } 1367 1368 static inline bool zap_drop_file_uffd_wp(struct zap_details *details) 1369 { 1370 if (!details) 1371 return false; 1372 1373 return details->zap_flags & ZAP_FLAG_DROP_MARKER; 1374 } 1375 1376 /* 1377 * This function makes sure that we'll replace the none pte with an uffd-wp 1378 * swap special pte marker when necessary. Must be with the pgtable lock held. 1379 */ 1380 static inline void 1381 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma, 1382 unsigned long addr, pte_t *pte, 1383 struct zap_details *details, pte_t pteval) 1384 { 1385 if (zap_drop_file_uffd_wp(details)) 1386 return; 1387 1388 pte_install_uffd_wp_if_needed(vma, addr, pte, pteval); 1389 } 1390 1391 static unsigned long zap_pte_range(struct mmu_gather *tlb, 1392 struct vm_area_struct *vma, pmd_t *pmd, 1393 unsigned long addr, unsigned long end, 1394 struct zap_details *details) 1395 { 1396 struct mm_struct *mm = tlb->mm; 1397 int force_flush = 0; 1398 int rss[NR_MM_COUNTERS]; 1399 spinlock_t *ptl; 1400 pte_t *start_pte; 1401 pte_t *pte; 1402 swp_entry_t entry; 1403 1404 tlb_change_page_size(tlb, PAGE_SIZE); 1405 again: 1406 init_rss_vec(rss); 1407 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl); 1408 pte = start_pte; 1409 flush_tlb_batched_pending(mm); 1410 arch_enter_lazy_mmu_mode(); 1411 do { 1412 pte_t ptent = *pte; 1413 struct page *page; 1414 1415 if (pte_none(ptent)) 1416 continue; 1417 1418 if (need_resched()) 1419 break; 1420 1421 if (pte_present(ptent)) { 1422 page = vm_normal_page(vma, addr, ptent); 1423 if (unlikely(!should_zap_page(details, page))) 1424 continue; 1425 ptent = ptep_get_and_clear_full(mm, addr, pte, 1426 tlb->fullmm); 1427 tlb_remove_tlb_entry(tlb, pte, addr); 1428 zap_install_uffd_wp_if_needed(vma, addr, pte, details, 1429 ptent); 1430 if (unlikely(!page)) 1431 continue; 1432 1433 if (!PageAnon(page)) { 1434 if (pte_dirty(ptent)) { 1435 force_flush = 1; 1436 set_page_dirty(page); 1437 } 1438 if (pte_young(ptent) && 1439 likely(!(vma->vm_flags & VM_SEQ_READ))) 1440 mark_page_accessed(page); 1441 } 1442 rss[mm_counter(page)]--; 1443 page_remove_rmap(page, vma, false); 1444 if (unlikely(page_mapcount(page) < 0)) 1445 print_bad_pte(vma, addr, ptent, page); 1446 if (unlikely(__tlb_remove_page(tlb, page))) { 1447 force_flush = 1; 1448 addr += PAGE_SIZE; 1449 break; 1450 } 1451 continue; 1452 } 1453 1454 entry = pte_to_swp_entry(ptent); 1455 if (is_device_private_entry(entry) || 1456 is_device_exclusive_entry(entry)) { 1457 page = pfn_swap_entry_to_page(entry); 1458 if (unlikely(!should_zap_page(details, page))) 1459 continue; 1460 /* 1461 * Both device private/exclusive mappings should only 1462 * work with anonymous page so far, so we don't need to 1463 * consider uffd-wp bit when zap. For more information, 1464 * see zap_install_uffd_wp_if_needed(). 1465 */ 1466 WARN_ON_ONCE(!vma_is_anonymous(vma)); 1467 rss[mm_counter(page)]--; 1468 if (is_device_private_entry(entry)) 1469 page_remove_rmap(page, vma, false); 1470 put_page(page); 1471 } else if (!non_swap_entry(entry)) { 1472 /* Genuine swap entry, hence a private anon page */ 1473 if (!should_zap_cows(details)) 1474 continue; 1475 rss[MM_SWAPENTS]--; 1476 if (unlikely(!free_swap_and_cache(entry))) 1477 print_bad_pte(vma, addr, ptent, NULL); 1478 } else if (is_migration_entry(entry)) { 1479 page = pfn_swap_entry_to_page(entry); 1480 if (!should_zap_page(details, page)) 1481 continue; 1482 rss[mm_counter(page)]--; 1483 } else if (pte_marker_entry_uffd_wp(entry)) { 1484 /* Only drop the uffd-wp marker if explicitly requested */ 1485 if (!zap_drop_file_uffd_wp(details)) 1486 continue; 1487 } else if (is_hwpoison_entry(entry) || 1488 is_swapin_error_entry(entry)) { 1489 if (!should_zap_cows(details)) 1490 continue; 1491 } else { 1492 /* We should have covered all the swap entry types */ 1493 WARN_ON_ONCE(1); 1494 } 1495 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm); 1496 zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent); 1497 } while (pte++, addr += PAGE_SIZE, addr != end); 1498 1499 add_mm_rss_vec(mm, rss); 1500 arch_leave_lazy_mmu_mode(); 1501 1502 /* Do the actual TLB flush before dropping ptl */ 1503 if (force_flush) 1504 tlb_flush_mmu_tlbonly(tlb); 1505 pte_unmap_unlock(start_pte, ptl); 1506 1507 /* 1508 * If we forced a TLB flush (either due to running out of 1509 * batch buffers or because we needed to flush dirty TLB 1510 * entries before releasing the ptl), free the batched 1511 * memory too. Restart if we didn't do everything. 1512 */ 1513 if (force_flush) { 1514 force_flush = 0; 1515 tlb_flush_mmu(tlb); 1516 } 1517 1518 if (addr != end) { 1519 cond_resched(); 1520 goto again; 1521 } 1522 1523 return addr; 1524 } 1525 1526 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, 1527 struct vm_area_struct *vma, pud_t *pud, 1528 unsigned long addr, unsigned long end, 1529 struct zap_details *details) 1530 { 1531 pmd_t *pmd; 1532 unsigned long next; 1533 1534 pmd = pmd_offset(pud, addr); 1535 do { 1536 next = pmd_addr_end(addr, end); 1537 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) { 1538 if (next - addr != HPAGE_PMD_SIZE) 1539 __split_huge_pmd(vma, pmd, addr, false, NULL); 1540 else if (zap_huge_pmd(tlb, vma, pmd, addr)) 1541 goto next; 1542 /* fall through */ 1543 } else if (details && details->single_folio && 1544 folio_test_pmd_mappable(details->single_folio) && 1545 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) { 1546 spinlock_t *ptl = pmd_lock(tlb->mm, pmd); 1547 /* 1548 * Take and drop THP pmd lock so that we cannot return 1549 * prematurely, while zap_huge_pmd() has cleared *pmd, 1550 * but not yet decremented compound_mapcount(). 1551 */ 1552 spin_unlock(ptl); 1553 } 1554 1555 /* 1556 * Here there can be other concurrent MADV_DONTNEED or 1557 * trans huge page faults running, and if the pmd is 1558 * none or trans huge it can change under us. This is 1559 * because MADV_DONTNEED holds the mmap_lock in read 1560 * mode. 1561 */ 1562 if (pmd_none_or_trans_huge_or_clear_bad(pmd)) 1563 goto next; 1564 next = zap_pte_range(tlb, vma, pmd, addr, next, details); 1565 next: 1566 cond_resched(); 1567 } while (pmd++, addr = next, addr != end); 1568 1569 return addr; 1570 } 1571 1572 static inline unsigned long zap_pud_range(struct mmu_gather *tlb, 1573 struct vm_area_struct *vma, p4d_t *p4d, 1574 unsigned long addr, unsigned long end, 1575 struct zap_details *details) 1576 { 1577 pud_t *pud; 1578 unsigned long next; 1579 1580 pud = pud_offset(p4d, addr); 1581 do { 1582 next = pud_addr_end(addr, end); 1583 if (pud_trans_huge(*pud) || pud_devmap(*pud)) { 1584 if (next - addr != HPAGE_PUD_SIZE) { 1585 mmap_assert_locked(tlb->mm); 1586 split_huge_pud(vma, pud, addr); 1587 } else if (zap_huge_pud(tlb, vma, pud, addr)) 1588 goto next; 1589 /* fall through */ 1590 } 1591 if (pud_none_or_clear_bad(pud)) 1592 continue; 1593 next = zap_pmd_range(tlb, vma, pud, addr, next, details); 1594 next: 1595 cond_resched(); 1596 } while (pud++, addr = next, addr != end); 1597 1598 return addr; 1599 } 1600 1601 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb, 1602 struct vm_area_struct *vma, pgd_t *pgd, 1603 unsigned long addr, unsigned long end, 1604 struct zap_details *details) 1605 { 1606 p4d_t *p4d; 1607 unsigned long next; 1608 1609 p4d = p4d_offset(pgd, addr); 1610 do { 1611 next = p4d_addr_end(addr, end); 1612 if (p4d_none_or_clear_bad(p4d)) 1613 continue; 1614 next = zap_pud_range(tlb, vma, p4d, addr, next, details); 1615 } while (p4d++, addr = next, addr != end); 1616 1617 return addr; 1618 } 1619 1620 void unmap_page_range(struct mmu_gather *tlb, 1621 struct vm_area_struct *vma, 1622 unsigned long addr, unsigned long end, 1623 struct zap_details *details) 1624 { 1625 pgd_t *pgd; 1626 unsigned long next; 1627 1628 BUG_ON(addr >= end); 1629 tlb_start_vma(tlb, vma); 1630 pgd = pgd_offset(vma->vm_mm, addr); 1631 do { 1632 next = pgd_addr_end(addr, end); 1633 if (pgd_none_or_clear_bad(pgd)) 1634 continue; 1635 next = zap_p4d_range(tlb, vma, pgd, addr, next, details); 1636 } while (pgd++, addr = next, addr != end); 1637 tlb_end_vma(tlb, vma); 1638 } 1639 1640 1641 static void unmap_single_vma(struct mmu_gather *tlb, 1642 struct vm_area_struct *vma, unsigned long start_addr, 1643 unsigned long end_addr, 1644 struct zap_details *details) 1645 { 1646 unsigned long start = max(vma->vm_start, start_addr); 1647 unsigned long end; 1648 1649 if (start >= vma->vm_end) 1650 return; 1651 end = min(vma->vm_end, end_addr); 1652 if (end <= vma->vm_start) 1653 return; 1654 1655 if (vma->vm_file) 1656 uprobe_munmap(vma, start, end); 1657 1658 if (unlikely(vma->vm_flags & VM_PFNMAP)) 1659 untrack_pfn(vma, 0, 0); 1660 1661 if (start != end) { 1662 if (unlikely(is_vm_hugetlb_page(vma))) { 1663 /* 1664 * It is undesirable to test vma->vm_file as it 1665 * should be non-null for valid hugetlb area. 1666 * However, vm_file will be NULL in the error 1667 * cleanup path of mmap_region. When 1668 * hugetlbfs ->mmap method fails, 1669 * mmap_region() nullifies vma->vm_file 1670 * before calling this function to clean up. 1671 * Since no pte has actually been setup, it is 1672 * safe to do nothing in this case. 1673 */ 1674 if (vma->vm_file) { 1675 zap_flags_t zap_flags = details ? 1676 details->zap_flags : 0; 1677 i_mmap_lock_write(vma->vm_file->f_mapping); 1678 __unmap_hugepage_range_final(tlb, vma, start, end, 1679 NULL, zap_flags); 1680 i_mmap_unlock_write(vma->vm_file->f_mapping); 1681 } 1682 } else 1683 unmap_page_range(tlb, vma, start, end, details); 1684 } 1685 } 1686 1687 /** 1688 * unmap_vmas - unmap a range of memory covered by a list of vma's 1689 * @tlb: address of the caller's struct mmu_gather 1690 * @vma: the starting vma 1691 * @start_addr: virtual address at which to start unmapping 1692 * @end_addr: virtual address at which to end unmapping 1693 * 1694 * Unmap all pages in the vma list. 1695 * 1696 * Only addresses between `start' and `end' will be unmapped. 1697 * 1698 * The VMA list must be sorted in ascending virtual address order. 1699 * 1700 * unmap_vmas() assumes that the caller will flush the whole unmapped address 1701 * range after unmap_vmas() returns. So the only responsibility here is to 1702 * ensure that any thus-far unmapped pages are flushed before unmap_vmas() 1703 * drops the lock and schedules. 1704 */ 1705 void unmap_vmas(struct mmu_gather *tlb, 1706 struct vm_area_struct *vma, unsigned long start_addr, 1707 unsigned long end_addr) 1708 { 1709 struct mmu_notifier_range range; 1710 struct zap_details details = { 1711 .zap_flags = ZAP_FLAG_DROP_MARKER, 1712 /* Careful - we need to zap private pages too! */ 1713 .even_cows = true, 1714 }; 1715 1716 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm, 1717 start_addr, end_addr); 1718 mmu_notifier_invalidate_range_start(&range); 1719 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next) 1720 unmap_single_vma(tlb, vma, start_addr, end_addr, &details); 1721 mmu_notifier_invalidate_range_end(&range); 1722 } 1723 1724 /** 1725 * zap_page_range - remove user pages in a given range 1726 * @vma: vm_area_struct holding the applicable pages 1727 * @start: starting address of pages to zap 1728 * @size: number of bytes to zap 1729 * 1730 * Caller must protect the VMA list 1731 */ 1732 void zap_page_range(struct vm_area_struct *vma, unsigned long start, 1733 unsigned long size) 1734 { 1735 struct mmu_notifier_range range; 1736 struct mmu_gather tlb; 1737 1738 lru_add_drain(); 1739 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm, 1740 start, start + size); 1741 tlb_gather_mmu(&tlb, vma->vm_mm); 1742 update_hiwater_rss(vma->vm_mm); 1743 mmu_notifier_invalidate_range_start(&range); 1744 for ( ; vma && vma->vm_start < range.end; vma = vma->vm_next) 1745 unmap_single_vma(&tlb, vma, start, range.end, NULL); 1746 mmu_notifier_invalidate_range_end(&range); 1747 tlb_finish_mmu(&tlb); 1748 } 1749 1750 /** 1751 * zap_page_range_single - remove user pages in a given range 1752 * @vma: vm_area_struct holding the applicable pages 1753 * @address: starting address of pages to zap 1754 * @size: number of bytes to zap 1755 * @details: details of shared cache invalidation 1756 * 1757 * The range must fit into one VMA. 1758 */ 1759 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address, 1760 unsigned long size, struct zap_details *details) 1761 { 1762 struct mmu_notifier_range range; 1763 struct mmu_gather tlb; 1764 1765 lru_add_drain(); 1766 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm, 1767 address, address + size); 1768 tlb_gather_mmu(&tlb, vma->vm_mm); 1769 update_hiwater_rss(vma->vm_mm); 1770 mmu_notifier_invalidate_range_start(&range); 1771 unmap_single_vma(&tlb, vma, address, range.end, details); 1772 mmu_notifier_invalidate_range_end(&range); 1773 tlb_finish_mmu(&tlb); 1774 } 1775 1776 /** 1777 * zap_vma_ptes - remove ptes mapping the vma 1778 * @vma: vm_area_struct holding ptes to be zapped 1779 * @address: starting address of pages to zap 1780 * @size: number of bytes to zap 1781 * 1782 * This function only unmaps ptes assigned to VM_PFNMAP vmas. 1783 * 1784 * The entire address range must be fully contained within the vma. 1785 * 1786 */ 1787 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, 1788 unsigned long size) 1789 { 1790 if (!range_in_vma(vma, address, address + size) || 1791 !(vma->vm_flags & VM_PFNMAP)) 1792 return; 1793 1794 zap_page_range_single(vma, address, size, NULL); 1795 } 1796 EXPORT_SYMBOL_GPL(zap_vma_ptes); 1797 1798 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr) 1799 { 1800 pgd_t *pgd; 1801 p4d_t *p4d; 1802 pud_t *pud; 1803 pmd_t *pmd; 1804 1805 pgd = pgd_offset(mm, addr); 1806 p4d = p4d_alloc(mm, pgd, addr); 1807 if (!p4d) 1808 return NULL; 1809 pud = pud_alloc(mm, p4d, addr); 1810 if (!pud) 1811 return NULL; 1812 pmd = pmd_alloc(mm, pud, addr); 1813 if (!pmd) 1814 return NULL; 1815 1816 VM_BUG_ON(pmd_trans_huge(*pmd)); 1817 return pmd; 1818 } 1819 1820 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr, 1821 spinlock_t **ptl) 1822 { 1823 pmd_t *pmd = walk_to_pmd(mm, addr); 1824 1825 if (!pmd) 1826 return NULL; 1827 return pte_alloc_map_lock(mm, pmd, addr, ptl); 1828 } 1829 1830 static int validate_page_before_insert(struct page *page) 1831 { 1832 if (PageAnon(page) || PageSlab(page) || page_has_type(page)) 1833 return -EINVAL; 1834 flush_dcache_page(page); 1835 return 0; 1836 } 1837 1838 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte, 1839 unsigned long addr, struct page *page, pgprot_t prot) 1840 { 1841 if (!pte_none(*pte)) 1842 return -EBUSY; 1843 /* Ok, finally just insert the thing.. */ 1844 get_page(page); 1845 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page)); 1846 page_add_file_rmap(page, vma, false); 1847 set_pte_at(vma->vm_mm, addr, pte, mk_pte(page, prot)); 1848 return 0; 1849 } 1850 1851 /* 1852 * This is the old fallback for page remapping. 1853 * 1854 * For historical reasons, it only allows reserved pages. Only 1855 * old drivers should use this, and they needed to mark their 1856 * pages reserved for the old functions anyway. 1857 */ 1858 static int insert_page(struct vm_area_struct *vma, unsigned long addr, 1859 struct page *page, pgprot_t prot) 1860 { 1861 int retval; 1862 pte_t *pte; 1863 spinlock_t *ptl; 1864 1865 retval = validate_page_before_insert(page); 1866 if (retval) 1867 goto out; 1868 retval = -ENOMEM; 1869 pte = get_locked_pte(vma->vm_mm, addr, &ptl); 1870 if (!pte) 1871 goto out; 1872 retval = insert_page_into_pte_locked(vma, pte, addr, page, prot); 1873 pte_unmap_unlock(pte, ptl); 1874 out: 1875 return retval; 1876 } 1877 1878 #ifdef pte_index 1879 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte, 1880 unsigned long addr, struct page *page, pgprot_t prot) 1881 { 1882 int err; 1883 1884 if (!page_count(page)) 1885 return -EINVAL; 1886 err = validate_page_before_insert(page); 1887 if (err) 1888 return err; 1889 return insert_page_into_pte_locked(vma, pte, addr, page, prot); 1890 } 1891 1892 /* insert_pages() amortizes the cost of spinlock operations 1893 * when inserting pages in a loop. Arch *must* define pte_index. 1894 */ 1895 static int insert_pages(struct vm_area_struct *vma, unsigned long addr, 1896 struct page **pages, unsigned long *num, pgprot_t prot) 1897 { 1898 pmd_t *pmd = NULL; 1899 pte_t *start_pte, *pte; 1900 spinlock_t *pte_lock; 1901 struct mm_struct *const mm = vma->vm_mm; 1902 unsigned long curr_page_idx = 0; 1903 unsigned long remaining_pages_total = *num; 1904 unsigned long pages_to_write_in_pmd; 1905 int ret; 1906 more: 1907 ret = -EFAULT; 1908 pmd = walk_to_pmd(mm, addr); 1909 if (!pmd) 1910 goto out; 1911 1912 pages_to_write_in_pmd = min_t(unsigned long, 1913 remaining_pages_total, PTRS_PER_PTE - pte_index(addr)); 1914 1915 /* Allocate the PTE if necessary; takes PMD lock once only. */ 1916 ret = -ENOMEM; 1917 if (pte_alloc(mm, pmd)) 1918 goto out; 1919 1920 while (pages_to_write_in_pmd) { 1921 int pte_idx = 0; 1922 const int batch_size = min_t(int, pages_to_write_in_pmd, 8); 1923 1924 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock); 1925 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) { 1926 int err = insert_page_in_batch_locked(vma, pte, 1927 addr, pages[curr_page_idx], prot); 1928 if (unlikely(err)) { 1929 pte_unmap_unlock(start_pte, pte_lock); 1930 ret = err; 1931 remaining_pages_total -= pte_idx; 1932 goto out; 1933 } 1934 addr += PAGE_SIZE; 1935 ++curr_page_idx; 1936 } 1937 pte_unmap_unlock(start_pte, pte_lock); 1938 pages_to_write_in_pmd -= batch_size; 1939 remaining_pages_total -= batch_size; 1940 } 1941 if (remaining_pages_total) 1942 goto more; 1943 ret = 0; 1944 out: 1945 *num = remaining_pages_total; 1946 return ret; 1947 } 1948 #endif /* ifdef pte_index */ 1949 1950 /** 1951 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock. 1952 * @vma: user vma to map to 1953 * @addr: target start user address of these pages 1954 * @pages: source kernel pages 1955 * @num: in: number of pages to map. out: number of pages that were *not* 1956 * mapped. (0 means all pages were successfully mapped). 1957 * 1958 * Preferred over vm_insert_page() when inserting multiple pages. 1959 * 1960 * In case of error, we may have mapped a subset of the provided 1961 * pages. It is the caller's responsibility to account for this case. 1962 * 1963 * The same restrictions apply as in vm_insert_page(). 1964 */ 1965 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr, 1966 struct page **pages, unsigned long *num) 1967 { 1968 #ifdef pte_index 1969 const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1; 1970 1971 if (addr < vma->vm_start || end_addr >= vma->vm_end) 1972 return -EFAULT; 1973 if (!(vma->vm_flags & VM_MIXEDMAP)) { 1974 BUG_ON(mmap_read_trylock(vma->vm_mm)); 1975 BUG_ON(vma->vm_flags & VM_PFNMAP); 1976 vma->vm_flags |= VM_MIXEDMAP; 1977 } 1978 /* Defer page refcount checking till we're about to map that page. */ 1979 return insert_pages(vma, addr, pages, num, vma->vm_page_prot); 1980 #else 1981 unsigned long idx = 0, pgcount = *num; 1982 int err = -EINVAL; 1983 1984 for (; idx < pgcount; ++idx) { 1985 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]); 1986 if (err) 1987 break; 1988 } 1989 *num = pgcount - idx; 1990 return err; 1991 #endif /* ifdef pte_index */ 1992 } 1993 EXPORT_SYMBOL(vm_insert_pages); 1994 1995 /** 1996 * vm_insert_page - insert single page into user vma 1997 * @vma: user vma to map to 1998 * @addr: target user address of this page 1999 * @page: source kernel page 2000 * 2001 * This allows drivers to insert individual pages they've allocated 2002 * into a user vma. 2003 * 2004 * The page has to be a nice clean _individual_ kernel allocation. 2005 * If you allocate a compound page, you need to have marked it as 2006 * such (__GFP_COMP), or manually just split the page up yourself 2007 * (see split_page()). 2008 * 2009 * NOTE! Traditionally this was done with "remap_pfn_range()" which 2010 * took an arbitrary page protection parameter. This doesn't allow 2011 * that. Your vma protection will have to be set up correctly, which 2012 * means that if you want a shared writable mapping, you'd better 2013 * ask for a shared writable mapping! 2014 * 2015 * The page does not need to be reserved. 2016 * 2017 * Usually this function is called from f_op->mmap() handler 2018 * under mm->mmap_lock write-lock, so it can change vma->vm_flags. 2019 * Caller must set VM_MIXEDMAP on vma if it wants to call this 2020 * function from other places, for example from page-fault handler. 2021 * 2022 * Return: %0 on success, negative error code otherwise. 2023 */ 2024 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr, 2025 struct page *page) 2026 { 2027 if (addr < vma->vm_start || addr >= vma->vm_end) 2028 return -EFAULT; 2029 if (!page_count(page)) 2030 return -EINVAL; 2031 if (!(vma->vm_flags & VM_MIXEDMAP)) { 2032 BUG_ON(mmap_read_trylock(vma->vm_mm)); 2033 BUG_ON(vma->vm_flags & VM_PFNMAP); 2034 vma->vm_flags |= VM_MIXEDMAP; 2035 } 2036 return insert_page(vma, addr, page, vma->vm_page_prot); 2037 } 2038 EXPORT_SYMBOL(vm_insert_page); 2039 2040 /* 2041 * __vm_map_pages - maps range of kernel pages into user vma 2042 * @vma: user vma to map to 2043 * @pages: pointer to array of source kernel pages 2044 * @num: number of pages in page array 2045 * @offset: user's requested vm_pgoff 2046 * 2047 * This allows drivers to map range of kernel pages into a user vma. 2048 * 2049 * Return: 0 on success and error code otherwise. 2050 */ 2051 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages, 2052 unsigned long num, unsigned long offset) 2053 { 2054 unsigned long count = vma_pages(vma); 2055 unsigned long uaddr = vma->vm_start; 2056 int ret, i; 2057 2058 /* Fail if the user requested offset is beyond the end of the object */ 2059 if (offset >= num) 2060 return -ENXIO; 2061 2062 /* Fail if the user requested size exceeds available object size */ 2063 if (count > num - offset) 2064 return -ENXIO; 2065 2066 for (i = 0; i < count; i++) { 2067 ret = vm_insert_page(vma, uaddr, pages[offset + i]); 2068 if (ret < 0) 2069 return ret; 2070 uaddr += PAGE_SIZE; 2071 } 2072 2073 return 0; 2074 } 2075 2076 /** 2077 * vm_map_pages - maps range of kernel pages starts with non zero offset 2078 * @vma: user vma to map to 2079 * @pages: pointer to array of source kernel pages 2080 * @num: number of pages in page array 2081 * 2082 * Maps an object consisting of @num pages, catering for the user's 2083 * requested vm_pgoff 2084 * 2085 * If we fail to insert any page into the vma, the function will return 2086 * immediately leaving any previously inserted pages present. Callers 2087 * from the mmap handler may immediately return the error as their caller 2088 * will destroy the vma, removing any successfully inserted pages. Other 2089 * callers should make their own arrangements for calling unmap_region(). 2090 * 2091 * Context: Process context. Called by mmap handlers. 2092 * Return: 0 on success and error code otherwise. 2093 */ 2094 int vm_map_pages(struct vm_area_struct *vma, struct page **pages, 2095 unsigned long num) 2096 { 2097 return __vm_map_pages(vma, pages, num, vma->vm_pgoff); 2098 } 2099 EXPORT_SYMBOL(vm_map_pages); 2100 2101 /** 2102 * vm_map_pages_zero - map range of kernel pages starts with zero offset 2103 * @vma: user vma to map to 2104 * @pages: pointer to array of source kernel pages 2105 * @num: number of pages in page array 2106 * 2107 * Similar to vm_map_pages(), except that it explicitly sets the offset 2108 * to 0. This function is intended for the drivers that did not consider 2109 * vm_pgoff. 2110 * 2111 * Context: Process context. Called by mmap handlers. 2112 * Return: 0 on success and error code otherwise. 2113 */ 2114 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages, 2115 unsigned long num) 2116 { 2117 return __vm_map_pages(vma, pages, num, 0); 2118 } 2119 EXPORT_SYMBOL(vm_map_pages_zero); 2120 2121 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr, 2122 pfn_t pfn, pgprot_t prot, bool mkwrite) 2123 { 2124 struct mm_struct *mm = vma->vm_mm; 2125 pte_t *pte, entry; 2126 spinlock_t *ptl; 2127 2128 pte = get_locked_pte(mm, addr, &ptl); 2129 if (!pte) 2130 return VM_FAULT_OOM; 2131 if (!pte_none(*pte)) { 2132 if (mkwrite) { 2133 /* 2134 * For read faults on private mappings the PFN passed 2135 * in may not match the PFN we have mapped if the 2136 * mapped PFN is a writeable COW page. In the mkwrite 2137 * case we are creating a writable PTE for a shared 2138 * mapping and we expect the PFNs to match. If they 2139 * don't match, we are likely racing with block 2140 * allocation and mapping invalidation so just skip the 2141 * update. 2142 */ 2143 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) { 2144 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte))); 2145 goto out_unlock; 2146 } 2147 entry = pte_mkyoung(*pte); 2148 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 2149 if (ptep_set_access_flags(vma, addr, pte, entry, 1)) 2150 update_mmu_cache(vma, addr, pte); 2151 } 2152 goto out_unlock; 2153 } 2154 2155 /* Ok, finally just insert the thing.. */ 2156 if (pfn_t_devmap(pfn)) 2157 entry = pte_mkdevmap(pfn_t_pte(pfn, prot)); 2158 else 2159 entry = pte_mkspecial(pfn_t_pte(pfn, prot)); 2160 2161 if (mkwrite) { 2162 entry = pte_mkyoung(entry); 2163 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 2164 } 2165 2166 set_pte_at(mm, addr, pte, entry); 2167 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */ 2168 2169 out_unlock: 2170 pte_unmap_unlock(pte, ptl); 2171 return VM_FAULT_NOPAGE; 2172 } 2173 2174 /** 2175 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot 2176 * @vma: user vma to map to 2177 * @addr: target user address of this page 2178 * @pfn: source kernel pfn 2179 * @pgprot: pgprot flags for the inserted page 2180 * 2181 * This is exactly like vmf_insert_pfn(), except that it allows drivers 2182 * to override pgprot on a per-page basis. 2183 * 2184 * This only makes sense for IO mappings, and it makes no sense for 2185 * COW mappings. In general, using multiple vmas is preferable; 2186 * vmf_insert_pfn_prot should only be used if using multiple VMAs is 2187 * impractical. 2188 * 2189 * See vmf_insert_mixed_prot() for a discussion of the implication of using 2190 * a value of @pgprot different from that of @vma->vm_page_prot. 2191 * 2192 * Context: Process context. May allocate using %GFP_KERNEL. 2193 * Return: vm_fault_t value. 2194 */ 2195 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr, 2196 unsigned long pfn, pgprot_t pgprot) 2197 { 2198 /* 2199 * Technically, architectures with pte_special can avoid all these 2200 * restrictions (same for remap_pfn_range). However we would like 2201 * consistency in testing and feature parity among all, so we should 2202 * try to keep these invariants in place for everybody. 2203 */ 2204 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); 2205 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == 2206 (VM_PFNMAP|VM_MIXEDMAP)); 2207 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags)); 2208 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn)); 2209 2210 if (addr < vma->vm_start || addr >= vma->vm_end) 2211 return VM_FAULT_SIGBUS; 2212 2213 if (!pfn_modify_allowed(pfn, pgprot)) 2214 return VM_FAULT_SIGBUS; 2215 2216 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV)); 2217 2218 return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot, 2219 false); 2220 } 2221 EXPORT_SYMBOL(vmf_insert_pfn_prot); 2222 2223 /** 2224 * vmf_insert_pfn - insert single pfn into user vma 2225 * @vma: user vma to map to 2226 * @addr: target user address of this page 2227 * @pfn: source kernel pfn 2228 * 2229 * Similar to vm_insert_page, this allows drivers to insert individual pages 2230 * they've allocated into a user vma. Same comments apply. 2231 * 2232 * This function should only be called from a vm_ops->fault handler, and 2233 * in that case the handler should return the result of this function. 2234 * 2235 * vma cannot be a COW mapping. 2236 * 2237 * As this is called only for pages that do not currently exist, we 2238 * do not need to flush old virtual caches or the TLB. 2239 * 2240 * Context: Process context. May allocate using %GFP_KERNEL. 2241 * Return: vm_fault_t value. 2242 */ 2243 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr, 2244 unsigned long pfn) 2245 { 2246 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot); 2247 } 2248 EXPORT_SYMBOL(vmf_insert_pfn); 2249 2250 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn) 2251 { 2252 /* these checks mirror the abort conditions in vm_normal_page */ 2253 if (vma->vm_flags & VM_MIXEDMAP) 2254 return true; 2255 if (pfn_t_devmap(pfn)) 2256 return true; 2257 if (pfn_t_special(pfn)) 2258 return true; 2259 if (is_zero_pfn(pfn_t_to_pfn(pfn))) 2260 return true; 2261 return false; 2262 } 2263 2264 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma, 2265 unsigned long addr, pfn_t pfn, pgprot_t pgprot, 2266 bool mkwrite) 2267 { 2268 int err; 2269 2270 BUG_ON(!vm_mixed_ok(vma, pfn)); 2271 2272 if (addr < vma->vm_start || addr >= vma->vm_end) 2273 return VM_FAULT_SIGBUS; 2274 2275 track_pfn_insert(vma, &pgprot, pfn); 2276 2277 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot)) 2278 return VM_FAULT_SIGBUS; 2279 2280 /* 2281 * If we don't have pte special, then we have to use the pfn_valid() 2282 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must* 2283 * refcount the page if pfn_valid is true (hence insert_page rather 2284 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP 2285 * without pte special, it would there be refcounted as a normal page. 2286 */ 2287 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) && 2288 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) { 2289 struct page *page; 2290 2291 /* 2292 * At this point we are committed to insert_page() 2293 * regardless of whether the caller specified flags that 2294 * result in pfn_t_has_page() == false. 2295 */ 2296 page = pfn_to_page(pfn_t_to_pfn(pfn)); 2297 err = insert_page(vma, addr, page, pgprot); 2298 } else { 2299 return insert_pfn(vma, addr, pfn, pgprot, mkwrite); 2300 } 2301 2302 if (err == -ENOMEM) 2303 return VM_FAULT_OOM; 2304 if (err < 0 && err != -EBUSY) 2305 return VM_FAULT_SIGBUS; 2306 2307 return VM_FAULT_NOPAGE; 2308 } 2309 2310 /** 2311 * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot 2312 * @vma: user vma to map to 2313 * @addr: target user address of this page 2314 * @pfn: source kernel pfn 2315 * @pgprot: pgprot flags for the inserted page 2316 * 2317 * This is exactly like vmf_insert_mixed(), except that it allows drivers 2318 * to override pgprot on a per-page basis. 2319 * 2320 * Typically this function should be used by drivers to set caching- and 2321 * encryption bits different than those of @vma->vm_page_prot, because 2322 * the caching- or encryption mode may not be known at mmap() time. 2323 * This is ok as long as @vma->vm_page_prot is not used by the core vm 2324 * to set caching and encryption bits for those vmas (except for COW pages). 2325 * This is ensured by core vm only modifying these page table entries using 2326 * functions that don't touch caching- or encryption bits, using pte_modify() 2327 * if needed. (See for example mprotect()). 2328 * Also when new page-table entries are created, this is only done using the 2329 * fault() callback, and never using the value of vma->vm_page_prot, 2330 * except for page-table entries that point to anonymous pages as the result 2331 * of COW. 2332 * 2333 * Context: Process context. May allocate using %GFP_KERNEL. 2334 * Return: vm_fault_t value. 2335 */ 2336 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr, 2337 pfn_t pfn, pgprot_t pgprot) 2338 { 2339 return __vm_insert_mixed(vma, addr, pfn, pgprot, false); 2340 } 2341 EXPORT_SYMBOL(vmf_insert_mixed_prot); 2342 2343 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr, 2344 pfn_t pfn) 2345 { 2346 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false); 2347 } 2348 EXPORT_SYMBOL(vmf_insert_mixed); 2349 2350 /* 2351 * If the insertion of PTE failed because someone else already added a 2352 * different entry in the mean time, we treat that as success as we assume 2353 * the same entry was actually inserted. 2354 */ 2355 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma, 2356 unsigned long addr, pfn_t pfn) 2357 { 2358 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true); 2359 } 2360 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite); 2361 2362 /* 2363 * maps a range of physical memory into the requested pages. the old 2364 * mappings are removed. any references to nonexistent pages results 2365 * in null mappings (currently treated as "copy-on-access") 2366 */ 2367 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd, 2368 unsigned long addr, unsigned long end, 2369 unsigned long pfn, pgprot_t prot) 2370 { 2371 pte_t *pte, *mapped_pte; 2372 spinlock_t *ptl; 2373 int err = 0; 2374 2375 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl); 2376 if (!pte) 2377 return -ENOMEM; 2378 arch_enter_lazy_mmu_mode(); 2379 do { 2380 BUG_ON(!pte_none(*pte)); 2381 if (!pfn_modify_allowed(pfn, prot)) { 2382 err = -EACCES; 2383 break; 2384 } 2385 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot))); 2386 pfn++; 2387 } while (pte++, addr += PAGE_SIZE, addr != end); 2388 arch_leave_lazy_mmu_mode(); 2389 pte_unmap_unlock(mapped_pte, ptl); 2390 return err; 2391 } 2392 2393 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud, 2394 unsigned long addr, unsigned long end, 2395 unsigned long pfn, pgprot_t prot) 2396 { 2397 pmd_t *pmd; 2398 unsigned long next; 2399 int err; 2400 2401 pfn -= addr >> PAGE_SHIFT; 2402 pmd = pmd_alloc(mm, pud, addr); 2403 if (!pmd) 2404 return -ENOMEM; 2405 VM_BUG_ON(pmd_trans_huge(*pmd)); 2406 do { 2407 next = pmd_addr_end(addr, end); 2408 err = remap_pte_range(mm, pmd, addr, next, 2409 pfn + (addr >> PAGE_SHIFT), prot); 2410 if (err) 2411 return err; 2412 } while (pmd++, addr = next, addr != end); 2413 return 0; 2414 } 2415 2416 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d, 2417 unsigned long addr, unsigned long end, 2418 unsigned long pfn, pgprot_t prot) 2419 { 2420 pud_t *pud; 2421 unsigned long next; 2422 int err; 2423 2424 pfn -= addr >> PAGE_SHIFT; 2425 pud = pud_alloc(mm, p4d, addr); 2426 if (!pud) 2427 return -ENOMEM; 2428 do { 2429 next = pud_addr_end(addr, end); 2430 err = remap_pmd_range(mm, pud, addr, next, 2431 pfn + (addr >> PAGE_SHIFT), prot); 2432 if (err) 2433 return err; 2434 } while (pud++, addr = next, addr != end); 2435 return 0; 2436 } 2437 2438 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd, 2439 unsigned long addr, unsigned long end, 2440 unsigned long pfn, pgprot_t prot) 2441 { 2442 p4d_t *p4d; 2443 unsigned long next; 2444 int err; 2445 2446 pfn -= addr >> PAGE_SHIFT; 2447 p4d = p4d_alloc(mm, pgd, addr); 2448 if (!p4d) 2449 return -ENOMEM; 2450 do { 2451 next = p4d_addr_end(addr, end); 2452 err = remap_pud_range(mm, p4d, addr, next, 2453 pfn + (addr >> PAGE_SHIFT), prot); 2454 if (err) 2455 return err; 2456 } while (p4d++, addr = next, addr != end); 2457 return 0; 2458 } 2459 2460 /* 2461 * Variant of remap_pfn_range that does not call track_pfn_remap. The caller 2462 * must have pre-validated the caching bits of the pgprot_t. 2463 */ 2464 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr, 2465 unsigned long pfn, unsigned long size, pgprot_t prot) 2466 { 2467 pgd_t *pgd; 2468 unsigned long next; 2469 unsigned long end = addr + PAGE_ALIGN(size); 2470 struct mm_struct *mm = vma->vm_mm; 2471 int err; 2472 2473 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr))) 2474 return -EINVAL; 2475 2476 /* 2477 * Physically remapped pages are special. Tell the 2478 * rest of the world about it: 2479 * VM_IO tells people not to look at these pages 2480 * (accesses can have side effects). 2481 * VM_PFNMAP tells the core MM that the base pages are just 2482 * raw PFN mappings, and do not have a "struct page" associated 2483 * with them. 2484 * VM_DONTEXPAND 2485 * Disable vma merging and expanding with mremap(). 2486 * VM_DONTDUMP 2487 * Omit vma from core dump, even when VM_IO turned off. 2488 * 2489 * There's a horrible special case to handle copy-on-write 2490 * behaviour that some programs depend on. We mark the "original" 2491 * un-COW'ed pages by matching them up with "vma->vm_pgoff". 2492 * See vm_normal_page() for details. 2493 */ 2494 if (is_cow_mapping(vma->vm_flags)) { 2495 if (addr != vma->vm_start || end != vma->vm_end) 2496 return -EINVAL; 2497 vma->vm_pgoff = pfn; 2498 } 2499 2500 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP; 2501 2502 BUG_ON(addr >= end); 2503 pfn -= addr >> PAGE_SHIFT; 2504 pgd = pgd_offset(mm, addr); 2505 flush_cache_range(vma, addr, end); 2506 do { 2507 next = pgd_addr_end(addr, end); 2508 err = remap_p4d_range(mm, pgd, addr, next, 2509 pfn + (addr >> PAGE_SHIFT), prot); 2510 if (err) 2511 return err; 2512 } while (pgd++, addr = next, addr != end); 2513 2514 return 0; 2515 } 2516 2517 /** 2518 * remap_pfn_range - remap kernel memory to userspace 2519 * @vma: user vma to map to 2520 * @addr: target page aligned user address to start at 2521 * @pfn: page frame number of kernel physical memory address 2522 * @size: size of mapping area 2523 * @prot: page protection flags for this mapping 2524 * 2525 * Note: this is only safe if the mm semaphore is held when called. 2526 * 2527 * Return: %0 on success, negative error code otherwise. 2528 */ 2529 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, 2530 unsigned long pfn, unsigned long size, pgprot_t prot) 2531 { 2532 int err; 2533 2534 err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size)); 2535 if (err) 2536 return -EINVAL; 2537 2538 err = remap_pfn_range_notrack(vma, addr, pfn, size, prot); 2539 if (err) 2540 untrack_pfn(vma, pfn, PAGE_ALIGN(size)); 2541 return err; 2542 } 2543 EXPORT_SYMBOL(remap_pfn_range); 2544 2545 /** 2546 * vm_iomap_memory - remap memory to userspace 2547 * @vma: user vma to map to 2548 * @start: start of the physical memory to be mapped 2549 * @len: size of area 2550 * 2551 * This is a simplified io_remap_pfn_range() for common driver use. The 2552 * driver just needs to give us the physical memory range to be mapped, 2553 * we'll figure out the rest from the vma information. 2554 * 2555 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get 2556 * whatever write-combining details or similar. 2557 * 2558 * Return: %0 on success, negative error code otherwise. 2559 */ 2560 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len) 2561 { 2562 unsigned long vm_len, pfn, pages; 2563 2564 /* Check that the physical memory area passed in looks valid */ 2565 if (start + len < start) 2566 return -EINVAL; 2567 /* 2568 * You *really* shouldn't map things that aren't page-aligned, 2569 * but we've historically allowed it because IO memory might 2570 * just have smaller alignment. 2571 */ 2572 len += start & ~PAGE_MASK; 2573 pfn = start >> PAGE_SHIFT; 2574 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT; 2575 if (pfn + pages < pfn) 2576 return -EINVAL; 2577 2578 /* We start the mapping 'vm_pgoff' pages into the area */ 2579 if (vma->vm_pgoff > pages) 2580 return -EINVAL; 2581 pfn += vma->vm_pgoff; 2582 pages -= vma->vm_pgoff; 2583 2584 /* Can we fit all of the mapping? */ 2585 vm_len = vma->vm_end - vma->vm_start; 2586 if (vm_len >> PAGE_SHIFT > pages) 2587 return -EINVAL; 2588 2589 /* Ok, let it rip */ 2590 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot); 2591 } 2592 EXPORT_SYMBOL(vm_iomap_memory); 2593 2594 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd, 2595 unsigned long addr, unsigned long end, 2596 pte_fn_t fn, void *data, bool create, 2597 pgtbl_mod_mask *mask) 2598 { 2599 pte_t *pte, *mapped_pte; 2600 int err = 0; 2601 spinlock_t *ptl; 2602 2603 if (create) { 2604 mapped_pte = pte = (mm == &init_mm) ? 2605 pte_alloc_kernel_track(pmd, addr, mask) : 2606 pte_alloc_map_lock(mm, pmd, addr, &ptl); 2607 if (!pte) 2608 return -ENOMEM; 2609 } else { 2610 mapped_pte = pte = (mm == &init_mm) ? 2611 pte_offset_kernel(pmd, addr) : 2612 pte_offset_map_lock(mm, pmd, addr, &ptl); 2613 } 2614 2615 BUG_ON(pmd_huge(*pmd)); 2616 2617 arch_enter_lazy_mmu_mode(); 2618 2619 if (fn) { 2620 do { 2621 if (create || !pte_none(*pte)) { 2622 err = fn(pte++, addr, data); 2623 if (err) 2624 break; 2625 } 2626 } while (addr += PAGE_SIZE, addr != end); 2627 } 2628 *mask |= PGTBL_PTE_MODIFIED; 2629 2630 arch_leave_lazy_mmu_mode(); 2631 2632 if (mm != &init_mm) 2633 pte_unmap_unlock(mapped_pte, ptl); 2634 return err; 2635 } 2636 2637 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud, 2638 unsigned long addr, unsigned long end, 2639 pte_fn_t fn, void *data, bool create, 2640 pgtbl_mod_mask *mask) 2641 { 2642 pmd_t *pmd; 2643 unsigned long next; 2644 int err = 0; 2645 2646 BUG_ON(pud_huge(*pud)); 2647 2648 if (create) { 2649 pmd = pmd_alloc_track(mm, pud, addr, mask); 2650 if (!pmd) 2651 return -ENOMEM; 2652 } else { 2653 pmd = pmd_offset(pud, addr); 2654 } 2655 do { 2656 next = pmd_addr_end(addr, end); 2657 if (pmd_none(*pmd) && !create) 2658 continue; 2659 if (WARN_ON_ONCE(pmd_leaf(*pmd))) 2660 return -EINVAL; 2661 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) { 2662 if (!create) 2663 continue; 2664 pmd_clear_bad(pmd); 2665 } 2666 err = apply_to_pte_range(mm, pmd, addr, next, 2667 fn, data, create, mask); 2668 if (err) 2669 break; 2670 } while (pmd++, addr = next, addr != end); 2671 2672 return err; 2673 } 2674 2675 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d, 2676 unsigned long addr, unsigned long end, 2677 pte_fn_t fn, void *data, bool create, 2678 pgtbl_mod_mask *mask) 2679 { 2680 pud_t *pud; 2681 unsigned long next; 2682 int err = 0; 2683 2684 if (create) { 2685 pud = pud_alloc_track(mm, p4d, addr, mask); 2686 if (!pud) 2687 return -ENOMEM; 2688 } else { 2689 pud = pud_offset(p4d, addr); 2690 } 2691 do { 2692 next = pud_addr_end(addr, end); 2693 if (pud_none(*pud) && !create) 2694 continue; 2695 if (WARN_ON_ONCE(pud_leaf(*pud))) 2696 return -EINVAL; 2697 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) { 2698 if (!create) 2699 continue; 2700 pud_clear_bad(pud); 2701 } 2702 err = apply_to_pmd_range(mm, pud, addr, next, 2703 fn, data, create, mask); 2704 if (err) 2705 break; 2706 } while (pud++, addr = next, addr != end); 2707 2708 return err; 2709 } 2710 2711 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd, 2712 unsigned long addr, unsigned long end, 2713 pte_fn_t fn, void *data, bool create, 2714 pgtbl_mod_mask *mask) 2715 { 2716 p4d_t *p4d; 2717 unsigned long next; 2718 int err = 0; 2719 2720 if (create) { 2721 p4d = p4d_alloc_track(mm, pgd, addr, mask); 2722 if (!p4d) 2723 return -ENOMEM; 2724 } else { 2725 p4d = p4d_offset(pgd, addr); 2726 } 2727 do { 2728 next = p4d_addr_end(addr, end); 2729 if (p4d_none(*p4d) && !create) 2730 continue; 2731 if (WARN_ON_ONCE(p4d_leaf(*p4d))) 2732 return -EINVAL; 2733 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) { 2734 if (!create) 2735 continue; 2736 p4d_clear_bad(p4d); 2737 } 2738 err = apply_to_pud_range(mm, p4d, addr, next, 2739 fn, data, create, mask); 2740 if (err) 2741 break; 2742 } while (p4d++, addr = next, addr != end); 2743 2744 return err; 2745 } 2746 2747 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr, 2748 unsigned long size, pte_fn_t fn, 2749 void *data, bool create) 2750 { 2751 pgd_t *pgd; 2752 unsigned long start = addr, next; 2753 unsigned long end = addr + size; 2754 pgtbl_mod_mask mask = 0; 2755 int err = 0; 2756 2757 if (WARN_ON(addr >= end)) 2758 return -EINVAL; 2759 2760 pgd = pgd_offset(mm, addr); 2761 do { 2762 next = pgd_addr_end(addr, end); 2763 if (pgd_none(*pgd) && !create) 2764 continue; 2765 if (WARN_ON_ONCE(pgd_leaf(*pgd))) 2766 return -EINVAL; 2767 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) { 2768 if (!create) 2769 continue; 2770 pgd_clear_bad(pgd); 2771 } 2772 err = apply_to_p4d_range(mm, pgd, addr, next, 2773 fn, data, create, &mask); 2774 if (err) 2775 break; 2776 } while (pgd++, addr = next, addr != end); 2777 2778 if (mask & ARCH_PAGE_TABLE_SYNC_MASK) 2779 arch_sync_kernel_mappings(start, start + size); 2780 2781 return err; 2782 } 2783 2784 /* 2785 * Scan a region of virtual memory, filling in page tables as necessary 2786 * and calling a provided function on each leaf page table. 2787 */ 2788 int apply_to_page_range(struct mm_struct *mm, unsigned long addr, 2789 unsigned long size, pte_fn_t fn, void *data) 2790 { 2791 return __apply_to_page_range(mm, addr, size, fn, data, true); 2792 } 2793 EXPORT_SYMBOL_GPL(apply_to_page_range); 2794 2795 /* 2796 * Scan a region of virtual memory, calling a provided function on 2797 * each leaf page table where it exists. 2798 * 2799 * Unlike apply_to_page_range, this does _not_ fill in page tables 2800 * where they are absent. 2801 */ 2802 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr, 2803 unsigned long size, pte_fn_t fn, void *data) 2804 { 2805 return __apply_to_page_range(mm, addr, size, fn, data, false); 2806 } 2807 EXPORT_SYMBOL_GPL(apply_to_existing_page_range); 2808 2809 /* 2810 * handle_pte_fault chooses page fault handler according to an entry which was 2811 * read non-atomically. Before making any commitment, on those architectures 2812 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched 2813 * parts, do_swap_page must check under lock before unmapping the pte and 2814 * proceeding (but do_wp_page is only called after already making such a check; 2815 * and do_anonymous_page can safely check later on). 2816 */ 2817 static inline int pte_unmap_same(struct vm_fault *vmf) 2818 { 2819 int same = 1; 2820 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION) 2821 if (sizeof(pte_t) > sizeof(unsigned long)) { 2822 spinlock_t *ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd); 2823 spin_lock(ptl); 2824 same = pte_same(*vmf->pte, vmf->orig_pte); 2825 spin_unlock(ptl); 2826 } 2827 #endif 2828 pte_unmap(vmf->pte); 2829 vmf->pte = NULL; 2830 return same; 2831 } 2832 2833 static inline bool __wp_page_copy_user(struct page *dst, struct page *src, 2834 struct vm_fault *vmf) 2835 { 2836 bool ret; 2837 void *kaddr; 2838 void __user *uaddr; 2839 bool locked = false; 2840 struct vm_area_struct *vma = vmf->vma; 2841 struct mm_struct *mm = vma->vm_mm; 2842 unsigned long addr = vmf->address; 2843 2844 if (likely(src)) { 2845 copy_user_highpage(dst, src, addr, vma); 2846 return true; 2847 } 2848 2849 /* 2850 * If the source page was a PFN mapping, we don't have 2851 * a "struct page" for it. We do a best-effort copy by 2852 * just copying from the original user address. If that 2853 * fails, we just zero-fill it. Live with it. 2854 */ 2855 kaddr = kmap_atomic(dst); 2856 uaddr = (void __user *)(addr & PAGE_MASK); 2857 2858 /* 2859 * On architectures with software "accessed" bits, we would 2860 * take a double page fault, so mark it accessed here. 2861 */ 2862 if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) { 2863 pte_t entry; 2864 2865 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl); 2866 locked = true; 2867 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) { 2868 /* 2869 * Other thread has already handled the fault 2870 * and update local tlb only 2871 */ 2872 update_mmu_tlb(vma, addr, vmf->pte); 2873 ret = false; 2874 goto pte_unlock; 2875 } 2876 2877 entry = pte_mkyoung(vmf->orig_pte); 2878 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0)) 2879 update_mmu_cache(vma, addr, vmf->pte); 2880 } 2881 2882 /* 2883 * This really shouldn't fail, because the page is there 2884 * in the page tables. But it might just be unreadable, 2885 * in which case we just give up and fill the result with 2886 * zeroes. 2887 */ 2888 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) { 2889 if (locked) 2890 goto warn; 2891 2892 /* Re-validate under PTL if the page is still mapped */ 2893 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl); 2894 locked = true; 2895 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) { 2896 /* The PTE changed under us, update local tlb */ 2897 update_mmu_tlb(vma, addr, vmf->pte); 2898 ret = false; 2899 goto pte_unlock; 2900 } 2901 2902 /* 2903 * The same page can be mapped back since last copy attempt. 2904 * Try to copy again under PTL. 2905 */ 2906 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) { 2907 /* 2908 * Give a warn in case there can be some obscure 2909 * use-case 2910 */ 2911 warn: 2912 WARN_ON_ONCE(1); 2913 clear_page(kaddr); 2914 } 2915 } 2916 2917 ret = true; 2918 2919 pte_unlock: 2920 if (locked) 2921 pte_unmap_unlock(vmf->pte, vmf->ptl); 2922 kunmap_atomic(kaddr); 2923 flush_dcache_page(dst); 2924 2925 return ret; 2926 } 2927 2928 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma) 2929 { 2930 struct file *vm_file = vma->vm_file; 2931 2932 if (vm_file) 2933 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO; 2934 2935 /* 2936 * Special mappings (e.g. VDSO) do not have any file so fake 2937 * a default GFP_KERNEL for them. 2938 */ 2939 return GFP_KERNEL; 2940 } 2941 2942 /* 2943 * Notify the address space that the page is about to become writable so that 2944 * it can prohibit this or wait for the page to get into an appropriate state. 2945 * 2946 * We do this without the lock held, so that it can sleep if it needs to. 2947 */ 2948 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf) 2949 { 2950 vm_fault_t ret; 2951 struct page *page = vmf->page; 2952 unsigned int old_flags = vmf->flags; 2953 2954 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; 2955 2956 if (vmf->vma->vm_file && 2957 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host)) 2958 return VM_FAULT_SIGBUS; 2959 2960 ret = vmf->vma->vm_ops->page_mkwrite(vmf); 2961 /* Restore original flags so that caller is not surprised */ 2962 vmf->flags = old_flags; 2963 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) 2964 return ret; 2965 if (unlikely(!(ret & VM_FAULT_LOCKED))) { 2966 lock_page(page); 2967 if (!page->mapping) { 2968 unlock_page(page); 2969 return 0; /* retry */ 2970 } 2971 ret |= VM_FAULT_LOCKED; 2972 } else 2973 VM_BUG_ON_PAGE(!PageLocked(page), page); 2974 return ret; 2975 } 2976 2977 /* 2978 * Handle dirtying of a page in shared file mapping on a write fault. 2979 * 2980 * The function expects the page to be locked and unlocks it. 2981 */ 2982 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf) 2983 { 2984 struct vm_area_struct *vma = vmf->vma; 2985 struct address_space *mapping; 2986 struct page *page = vmf->page; 2987 bool dirtied; 2988 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite; 2989 2990 dirtied = set_page_dirty(page); 2991 VM_BUG_ON_PAGE(PageAnon(page), page); 2992 /* 2993 * Take a local copy of the address_space - page.mapping may be zeroed 2994 * by truncate after unlock_page(). The address_space itself remains 2995 * pinned by vma->vm_file's reference. We rely on unlock_page()'s 2996 * release semantics to prevent the compiler from undoing this copying. 2997 */ 2998 mapping = page_rmapping(page); 2999 unlock_page(page); 3000 3001 if (!page_mkwrite) 3002 file_update_time(vma->vm_file); 3003 3004 /* 3005 * Throttle page dirtying rate down to writeback speed. 3006 * 3007 * mapping may be NULL here because some device drivers do not 3008 * set page.mapping but still dirty their pages 3009 * 3010 * Drop the mmap_lock before waiting on IO, if we can. The file 3011 * is pinning the mapping, as per above. 3012 */ 3013 if ((dirtied || page_mkwrite) && mapping) { 3014 struct file *fpin; 3015 3016 fpin = maybe_unlock_mmap_for_io(vmf, NULL); 3017 balance_dirty_pages_ratelimited(mapping); 3018 if (fpin) { 3019 fput(fpin); 3020 return VM_FAULT_COMPLETED; 3021 } 3022 } 3023 3024 return 0; 3025 } 3026 3027 /* 3028 * Handle write page faults for pages that can be reused in the current vma 3029 * 3030 * This can happen either due to the mapping being with the VM_SHARED flag, 3031 * or due to us being the last reference standing to the page. In either 3032 * case, all we need to do here is to mark the page as writable and update 3033 * any related book-keeping. 3034 */ 3035 static inline void wp_page_reuse(struct vm_fault *vmf) 3036 __releases(vmf->ptl) 3037 { 3038 struct vm_area_struct *vma = vmf->vma; 3039 struct page *page = vmf->page; 3040 pte_t entry; 3041 3042 VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE)); 3043 VM_BUG_ON(page && PageAnon(page) && !PageAnonExclusive(page)); 3044 3045 /* 3046 * Clear the pages cpupid information as the existing 3047 * information potentially belongs to a now completely 3048 * unrelated process. 3049 */ 3050 if (page) 3051 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1); 3052 3053 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte)); 3054 entry = pte_mkyoung(vmf->orig_pte); 3055 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 3056 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1)) 3057 update_mmu_cache(vma, vmf->address, vmf->pte); 3058 pte_unmap_unlock(vmf->pte, vmf->ptl); 3059 count_vm_event(PGREUSE); 3060 } 3061 3062 /* 3063 * Handle the case of a page which we actually need to copy to a new page, 3064 * either due to COW or unsharing. 3065 * 3066 * Called with mmap_lock locked and the old page referenced, but 3067 * without the ptl held. 3068 * 3069 * High level logic flow: 3070 * 3071 * - Allocate a page, copy the content of the old page to the new one. 3072 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc. 3073 * - Take the PTL. If the pte changed, bail out and release the allocated page 3074 * - If the pte is still the way we remember it, update the page table and all 3075 * relevant references. This includes dropping the reference the page-table 3076 * held to the old page, as well as updating the rmap. 3077 * - In any case, unlock the PTL and drop the reference we took to the old page. 3078 */ 3079 static vm_fault_t wp_page_copy(struct vm_fault *vmf) 3080 { 3081 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 3082 struct vm_area_struct *vma = vmf->vma; 3083 struct mm_struct *mm = vma->vm_mm; 3084 struct page *old_page = vmf->page; 3085 struct page *new_page = NULL; 3086 pte_t entry; 3087 int page_copied = 0; 3088 struct mmu_notifier_range range; 3089 3090 delayacct_wpcopy_start(); 3091 3092 if (unlikely(anon_vma_prepare(vma))) 3093 goto oom; 3094 3095 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) { 3096 new_page = alloc_zeroed_user_highpage_movable(vma, 3097 vmf->address); 3098 if (!new_page) 3099 goto oom; 3100 } else { 3101 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, 3102 vmf->address); 3103 if (!new_page) 3104 goto oom; 3105 3106 if (!__wp_page_copy_user(new_page, old_page, vmf)) { 3107 /* 3108 * COW failed, if the fault was solved by other, 3109 * it's fine. If not, userspace would re-fault on 3110 * the same address and we will handle the fault 3111 * from the second attempt. 3112 */ 3113 put_page(new_page); 3114 if (old_page) 3115 put_page(old_page); 3116 3117 delayacct_wpcopy_end(); 3118 return 0; 3119 } 3120 } 3121 3122 if (mem_cgroup_charge(page_folio(new_page), mm, GFP_KERNEL)) 3123 goto oom_free_new; 3124 cgroup_throttle_swaprate(new_page, GFP_KERNEL); 3125 3126 __SetPageUptodate(new_page); 3127 3128 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, 3129 vmf->address & PAGE_MASK, 3130 (vmf->address & PAGE_MASK) + PAGE_SIZE); 3131 mmu_notifier_invalidate_range_start(&range); 3132 3133 /* 3134 * Re-check the pte - we dropped the lock 3135 */ 3136 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl); 3137 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) { 3138 if (old_page) { 3139 if (!PageAnon(old_page)) { 3140 dec_mm_counter_fast(mm, 3141 mm_counter_file(old_page)); 3142 inc_mm_counter_fast(mm, MM_ANONPAGES); 3143 } 3144 } else { 3145 inc_mm_counter_fast(mm, MM_ANONPAGES); 3146 } 3147 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte)); 3148 entry = mk_pte(new_page, vma->vm_page_prot); 3149 entry = pte_sw_mkyoung(entry); 3150 if (unlikely(unshare)) { 3151 if (pte_soft_dirty(vmf->orig_pte)) 3152 entry = pte_mksoft_dirty(entry); 3153 if (pte_uffd_wp(vmf->orig_pte)) 3154 entry = pte_mkuffd_wp(entry); 3155 } else { 3156 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 3157 } 3158 3159 /* 3160 * Clear the pte entry and flush it first, before updating the 3161 * pte with the new entry, to keep TLBs on different CPUs in 3162 * sync. This code used to set the new PTE then flush TLBs, but 3163 * that left a window where the new PTE could be loaded into 3164 * some TLBs while the old PTE remains in others. 3165 */ 3166 ptep_clear_flush_notify(vma, vmf->address, vmf->pte); 3167 page_add_new_anon_rmap(new_page, vma, vmf->address); 3168 lru_cache_add_inactive_or_unevictable(new_page, vma); 3169 /* 3170 * We call the notify macro here because, when using secondary 3171 * mmu page tables (such as kvm shadow page tables), we want the 3172 * new page to be mapped directly into the secondary page table. 3173 */ 3174 BUG_ON(unshare && pte_write(entry)); 3175 set_pte_at_notify(mm, vmf->address, vmf->pte, entry); 3176 update_mmu_cache(vma, vmf->address, vmf->pte); 3177 if (old_page) { 3178 /* 3179 * Only after switching the pte to the new page may 3180 * we remove the mapcount here. Otherwise another 3181 * process may come and find the rmap count decremented 3182 * before the pte is switched to the new page, and 3183 * "reuse" the old page writing into it while our pte 3184 * here still points into it and can be read by other 3185 * threads. 3186 * 3187 * The critical issue is to order this 3188 * page_remove_rmap with the ptp_clear_flush above. 3189 * Those stores are ordered by (if nothing else,) 3190 * the barrier present in the atomic_add_negative 3191 * in page_remove_rmap. 3192 * 3193 * Then the TLB flush in ptep_clear_flush ensures that 3194 * no process can access the old page before the 3195 * decremented mapcount is visible. And the old page 3196 * cannot be reused until after the decremented 3197 * mapcount is visible. So transitively, TLBs to 3198 * old page will be flushed before it can be reused. 3199 */ 3200 page_remove_rmap(old_page, vma, false); 3201 } 3202 3203 /* Free the old page.. */ 3204 new_page = old_page; 3205 page_copied = 1; 3206 } else { 3207 update_mmu_tlb(vma, vmf->address, vmf->pte); 3208 } 3209 3210 if (new_page) 3211 put_page(new_page); 3212 3213 pte_unmap_unlock(vmf->pte, vmf->ptl); 3214 /* 3215 * No need to double call mmu_notifier->invalidate_range() callback as 3216 * the above ptep_clear_flush_notify() did already call it. 3217 */ 3218 mmu_notifier_invalidate_range_only_end(&range); 3219 if (old_page) { 3220 if (page_copied) 3221 free_swap_cache(old_page); 3222 put_page(old_page); 3223 } 3224 3225 delayacct_wpcopy_end(); 3226 return (page_copied && !unshare) ? VM_FAULT_WRITE : 0; 3227 oom_free_new: 3228 put_page(new_page); 3229 oom: 3230 if (old_page) 3231 put_page(old_page); 3232 3233 delayacct_wpcopy_end(); 3234 return VM_FAULT_OOM; 3235 } 3236 3237 /** 3238 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE 3239 * writeable once the page is prepared 3240 * 3241 * @vmf: structure describing the fault 3242 * 3243 * This function handles all that is needed to finish a write page fault in a 3244 * shared mapping due to PTE being read-only once the mapped page is prepared. 3245 * It handles locking of PTE and modifying it. 3246 * 3247 * The function expects the page to be locked or other protection against 3248 * concurrent faults / writeback (such as DAX radix tree locks). 3249 * 3250 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before 3251 * we acquired PTE lock. 3252 */ 3253 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf) 3254 { 3255 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED)); 3256 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address, 3257 &vmf->ptl); 3258 /* 3259 * We might have raced with another page fault while we released the 3260 * pte_offset_map_lock. 3261 */ 3262 if (!pte_same(*vmf->pte, vmf->orig_pte)) { 3263 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte); 3264 pte_unmap_unlock(vmf->pte, vmf->ptl); 3265 return VM_FAULT_NOPAGE; 3266 } 3267 wp_page_reuse(vmf); 3268 return 0; 3269 } 3270 3271 /* 3272 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED 3273 * mapping 3274 */ 3275 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf) 3276 { 3277 struct vm_area_struct *vma = vmf->vma; 3278 3279 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) { 3280 vm_fault_t ret; 3281 3282 pte_unmap_unlock(vmf->pte, vmf->ptl); 3283 vmf->flags |= FAULT_FLAG_MKWRITE; 3284 ret = vma->vm_ops->pfn_mkwrite(vmf); 3285 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)) 3286 return ret; 3287 return finish_mkwrite_fault(vmf); 3288 } 3289 wp_page_reuse(vmf); 3290 return VM_FAULT_WRITE; 3291 } 3292 3293 static vm_fault_t wp_page_shared(struct vm_fault *vmf) 3294 __releases(vmf->ptl) 3295 { 3296 struct vm_area_struct *vma = vmf->vma; 3297 vm_fault_t ret = VM_FAULT_WRITE; 3298 3299 get_page(vmf->page); 3300 3301 if (vma->vm_ops && vma->vm_ops->page_mkwrite) { 3302 vm_fault_t tmp; 3303 3304 pte_unmap_unlock(vmf->pte, vmf->ptl); 3305 tmp = do_page_mkwrite(vmf); 3306 if (unlikely(!tmp || (tmp & 3307 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { 3308 put_page(vmf->page); 3309 return tmp; 3310 } 3311 tmp = finish_mkwrite_fault(vmf); 3312 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { 3313 unlock_page(vmf->page); 3314 put_page(vmf->page); 3315 return tmp; 3316 } 3317 } else { 3318 wp_page_reuse(vmf); 3319 lock_page(vmf->page); 3320 } 3321 ret |= fault_dirty_shared_page(vmf); 3322 put_page(vmf->page); 3323 3324 return ret; 3325 } 3326 3327 /* 3328 * This routine handles present pages, when 3329 * * users try to write to a shared page (FAULT_FLAG_WRITE) 3330 * * GUP wants to take a R/O pin on a possibly shared anonymous page 3331 * (FAULT_FLAG_UNSHARE) 3332 * 3333 * It is done by copying the page to a new address and decrementing the 3334 * shared-page counter for the old page. 3335 * 3336 * Note that this routine assumes that the protection checks have been 3337 * done by the caller (the low-level page fault routine in most cases). 3338 * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've 3339 * done any necessary COW. 3340 * 3341 * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even 3342 * though the page will change only once the write actually happens. This 3343 * avoids a few races, and potentially makes it more efficient. 3344 * 3345 * We enter with non-exclusive mmap_lock (to exclude vma changes, 3346 * but allow concurrent faults), with pte both mapped and locked. 3347 * We return with mmap_lock still held, but pte unmapped and unlocked. 3348 */ 3349 static vm_fault_t do_wp_page(struct vm_fault *vmf) 3350 __releases(vmf->ptl) 3351 { 3352 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 3353 struct vm_area_struct *vma = vmf->vma; 3354 3355 VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE)); 3356 VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE)); 3357 3358 if (likely(!unshare)) { 3359 if (userfaultfd_pte_wp(vma, *vmf->pte)) { 3360 pte_unmap_unlock(vmf->pte, vmf->ptl); 3361 return handle_userfault(vmf, VM_UFFD_WP); 3362 } 3363 3364 /* 3365 * Userfaultfd write-protect can defer flushes. Ensure the TLB 3366 * is flushed in this case before copying. 3367 */ 3368 if (unlikely(userfaultfd_wp(vmf->vma) && 3369 mm_tlb_flush_pending(vmf->vma->vm_mm))) 3370 flush_tlb_page(vmf->vma, vmf->address); 3371 } 3372 3373 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte); 3374 if (!vmf->page) { 3375 if (unlikely(unshare)) { 3376 /* No anonymous page -> nothing to do. */ 3377 pte_unmap_unlock(vmf->pte, vmf->ptl); 3378 return 0; 3379 } 3380 3381 /* 3382 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a 3383 * VM_PFNMAP VMA. 3384 * 3385 * We should not cow pages in a shared writeable mapping. 3386 * Just mark the pages writable and/or call ops->pfn_mkwrite. 3387 */ 3388 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) == 3389 (VM_WRITE|VM_SHARED)) 3390 return wp_pfn_shared(vmf); 3391 3392 pte_unmap_unlock(vmf->pte, vmf->ptl); 3393 return wp_page_copy(vmf); 3394 } 3395 3396 /* 3397 * Take out anonymous pages first, anonymous shared vmas are 3398 * not dirty accountable. 3399 */ 3400 if (PageAnon(vmf->page)) { 3401 struct page *page = vmf->page; 3402 3403 /* 3404 * If the page is exclusive to this process we must reuse the 3405 * page without further checks. 3406 */ 3407 if (PageAnonExclusive(page)) 3408 goto reuse; 3409 3410 /* 3411 * We have to verify under page lock: these early checks are 3412 * just an optimization to avoid locking the page and freeing 3413 * the swapcache if there is little hope that we can reuse. 3414 * 3415 * PageKsm() doesn't necessarily raise the page refcount. 3416 */ 3417 if (PageKsm(page) || page_count(page) > 3) 3418 goto copy; 3419 if (!PageLRU(page)) 3420 /* 3421 * Note: We cannot easily detect+handle references from 3422 * remote LRU pagevecs or references to PageLRU() pages. 3423 */ 3424 lru_add_drain(); 3425 if (page_count(page) > 1 + PageSwapCache(page)) 3426 goto copy; 3427 if (!trylock_page(page)) 3428 goto copy; 3429 if (PageSwapCache(page)) 3430 try_to_free_swap(page); 3431 if (PageKsm(page) || page_count(page) != 1) { 3432 unlock_page(page); 3433 goto copy; 3434 } 3435 /* 3436 * Ok, we've got the only page reference from our mapping 3437 * and the page is locked, it's dark out, and we're wearing 3438 * sunglasses. Hit it. 3439 */ 3440 page_move_anon_rmap(page, vma); 3441 unlock_page(page); 3442 reuse: 3443 if (unlikely(unshare)) { 3444 pte_unmap_unlock(vmf->pte, vmf->ptl); 3445 return 0; 3446 } 3447 wp_page_reuse(vmf); 3448 return VM_FAULT_WRITE; 3449 } else if (unshare) { 3450 /* No anonymous page -> nothing to do. */ 3451 pte_unmap_unlock(vmf->pte, vmf->ptl); 3452 return 0; 3453 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) == 3454 (VM_WRITE|VM_SHARED))) { 3455 return wp_page_shared(vmf); 3456 } 3457 copy: 3458 /* 3459 * Ok, we need to copy. Oh, well.. 3460 */ 3461 get_page(vmf->page); 3462 3463 pte_unmap_unlock(vmf->pte, vmf->ptl); 3464 #ifdef CONFIG_KSM 3465 if (PageKsm(vmf->page)) 3466 count_vm_event(COW_KSM); 3467 #endif 3468 return wp_page_copy(vmf); 3469 } 3470 3471 static void unmap_mapping_range_vma(struct vm_area_struct *vma, 3472 unsigned long start_addr, unsigned long end_addr, 3473 struct zap_details *details) 3474 { 3475 zap_page_range_single(vma, start_addr, end_addr - start_addr, details); 3476 } 3477 3478 static inline void unmap_mapping_range_tree(struct rb_root_cached *root, 3479 pgoff_t first_index, 3480 pgoff_t last_index, 3481 struct zap_details *details) 3482 { 3483 struct vm_area_struct *vma; 3484 pgoff_t vba, vea, zba, zea; 3485 3486 vma_interval_tree_foreach(vma, root, first_index, last_index) { 3487 vba = vma->vm_pgoff; 3488 vea = vba + vma_pages(vma) - 1; 3489 zba = max(first_index, vba); 3490 zea = min(last_index, vea); 3491 3492 unmap_mapping_range_vma(vma, 3493 ((zba - vba) << PAGE_SHIFT) + vma->vm_start, 3494 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start, 3495 details); 3496 } 3497 } 3498 3499 /** 3500 * unmap_mapping_folio() - Unmap single folio from processes. 3501 * @folio: The locked folio to be unmapped. 3502 * 3503 * Unmap this folio from any userspace process which still has it mmaped. 3504 * Typically, for efficiency, the range of nearby pages has already been 3505 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once 3506 * truncation or invalidation holds the lock on a folio, it may find that 3507 * the page has been remapped again: and then uses unmap_mapping_folio() 3508 * to unmap it finally. 3509 */ 3510 void unmap_mapping_folio(struct folio *folio) 3511 { 3512 struct address_space *mapping = folio->mapping; 3513 struct zap_details details = { }; 3514 pgoff_t first_index; 3515 pgoff_t last_index; 3516 3517 VM_BUG_ON(!folio_test_locked(folio)); 3518 3519 first_index = folio->index; 3520 last_index = folio->index + folio_nr_pages(folio) - 1; 3521 3522 details.even_cows = false; 3523 details.single_folio = folio; 3524 details.zap_flags = ZAP_FLAG_DROP_MARKER; 3525 3526 i_mmap_lock_read(mapping); 3527 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root))) 3528 unmap_mapping_range_tree(&mapping->i_mmap, first_index, 3529 last_index, &details); 3530 i_mmap_unlock_read(mapping); 3531 } 3532 3533 /** 3534 * unmap_mapping_pages() - Unmap pages from processes. 3535 * @mapping: The address space containing pages to be unmapped. 3536 * @start: Index of first page to be unmapped. 3537 * @nr: Number of pages to be unmapped. 0 to unmap to end of file. 3538 * @even_cows: Whether to unmap even private COWed pages. 3539 * 3540 * Unmap the pages in this address space from any userspace process which 3541 * has them mmaped. Generally, you want to remove COWed pages as well when 3542 * a file is being truncated, but not when invalidating pages from the page 3543 * cache. 3544 */ 3545 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start, 3546 pgoff_t nr, bool even_cows) 3547 { 3548 struct zap_details details = { }; 3549 pgoff_t first_index = start; 3550 pgoff_t last_index = start + nr - 1; 3551 3552 details.even_cows = even_cows; 3553 if (last_index < first_index) 3554 last_index = ULONG_MAX; 3555 3556 i_mmap_lock_read(mapping); 3557 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root))) 3558 unmap_mapping_range_tree(&mapping->i_mmap, first_index, 3559 last_index, &details); 3560 i_mmap_unlock_read(mapping); 3561 } 3562 EXPORT_SYMBOL_GPL(unmap_mapping_pages); 3563 3564 /** 3565 * unmap_mapping_range - unmap the portion of all mmaps in the specified 3566 * address_space corresponding to the specified byte range in the underlying 3567 * file. 3568 * 3569 * @mapping: the address space containing mmaps to be unmapped. 3570 * @holebegin: byte in first page to unmap, relative to the start of 3571 * the underlying file. This will be rounded down to a PAGE_SIZE 3572 * boundary. Note that this is different from truncate_pagecache(), which 3573 * must keep the partial page. In contrast, we must get rid of 3574 * partial pages. 3575 * @holelen: size of prospective hole in bytes. This will be rounded 3576 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the 3577 * end of the file. 3578 * @even_cows: 1 when truncating a file, unmap even private COWed pages; 3579 * but 0 when invalidating pagecache, don't throw away private data. 3580 */ 3581 void unmap_mapping_range(struct address_space *mapping, 3582 loff_t const holebegin, loff_t const holelen, int even_cows) 3583 { 3584 pgoff_t hba = holebegin >> PAGE_SHIFT; 3585 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; 3586 3587 /* Check for overflow. */ 3588 if (sizeof(holelen) > sizeof(hlen)) { 3589 long long holeend = 3590 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; 3591 if (holeend & ~(long long)ULONG_MAX) 3592 hlen = ULONG_MAX - hba + 1; 3593 } 3594 3595 unmap_mapping_pages(mapping, hba, hlen, even_cows); 3596 } 3597 EXPORT_SYMBOL(unmap_mapping_range); 3598 3599 /* 3600 * Restore a potential device exclusive pte to a working pte entry 3601 */ 3602 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf) 3603 { 3604 struct page *page = vmf->page; 3605 struct vm_area_struct *vma = vmf->vma; 3606 struct mmu_notifier_range range; 3607 3608 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) 3609 return VM_FAULT_RETRY; 3610 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma, 3611 vma->vm_mm, vmf->address & PAGE_MASK, 3612 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL); 3613 mmu_notifier_invalidate_range_start(&range); 3614 3615 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 3616 &vmf->ptl); 3617 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) 3618 restore_exclusive_pte(vma, page, vmf->address, vmf->pte); 3619 3620 pte_unmap_unlock(vmf->pte, vmf->ptl); 3621 unlock_page(page); 3622 3623 mmu_notifier_invalidate_range_end(&range); 3624 return 0; 3625 } 3626 3627 static inline bool should_try_to_free_swap(struct page *page, 3628 struct vm_area_struct *vma, 3629 unsigned int fault_flags) 3630 { 3631 if (!PageSwapCache(page)) 3632 return false; 3633 if (mem_cgroup_swap_full(page) || (vma->vm_flags & VM_LOCKED) || 3634 PageMlocked(page)) 3635 return true; 3636 /* 3637 * If we want to map a page that's in the swapcache writable, we 3638 * have to detect via the refcount if we're really the exclusive 3639 * user. Try freeing the swapcache to get rid of the swapcache 3640 * reference only in case it's likely that we'll be the exlusive user. 3641 */ 3642 return (fault_flags & FAULT_FLAG_WRITE) && !PageKsm(page) && 3643 page_count(page) == 2; 3644 } 3645 3646 static vm_fault_t pte_marker_clear(struct vm_fault *vmf) 3647 { 3648 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, 3649 vmf->address, &vmf->ptl); 3650 /* 3651 * Be careful so that we will only recover a special uffd-wp pte into a 3652 * none pte. Otherwise it means the pte could have changed, so retry. 3653 */ 3654 if (is_pte_marker(*vmf->pte)) 3655 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte); 3656 pte_unmap_unlock(vmf->pte, vmf->ptl); 3657 return 0; 3658 } 3659 3660 /* 3661 * This is actually a page-missing access, but with uffd-wp special pte 3662 * installed. It means this pte was wr-protected before being unmapped. 3663 */ 3664 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf) 3665 { 3666 /* 3667 * Just in case there're leftover special ptes even after the region 3668 * got unregistered - we can simply clear them. We can also do that 3669 * proactively when e.g. when we do UFFDIO_UNREGISTER upon some uffd-wp 3670 * ranges, but it should be more efficient to be done lazily here. 3671 */ 3672 if (unlikely(!userfaultfd_wp(vmf->vma) || vma_is_anonymous(vmf->vma))) 3673 return pte_marker_clear(vmf); 3674 3675 /* do_fault() can handle pte markers too like none pte */ 3676 return do_fault(vmf); 3677 } 3678 3679 static vm_fault_t handle_pte_marker(struct vm_fault *vmf) 3680 { 3681 swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte); 3682 unsigned long marker = pte_marker_get(entry); 3683 3684 /* 3685 * PTE markers should always be with file-backed memories, and the 3686 * marker should never be empty. If anything weird happened, the best 3687 * thing to do is to kill the process along with its mm. 3688 */ 3689 if (WARN_ON_ONCE(vma_is_anonymous(vmf->vma) || !marker)) 3690 return VM_FAULT_SIGBUS; 3691 3692 if (pte_marker_entry_uffd_wp(entry)) 3693 return pte_marker_handle_uffd_wp(vmf); 3694 3695 /* This is an unknown pte marker */ 3696 return VM_FAULT_SIGBUS; 3697 } 3698 3699 /* 3700 * We enter with non-exclusive mmap_lock (to exclude vma changes, 3701 * but allow concurrent faults), and pte mapped but not yet locked. 3702 * We return with pte unmapped and unlocked. 3703 * 3704 * We return with the mmap_lock locked or unlocked in the same cases 3705 * as does filemap_fault(). 3706 */ 3707 vm_fault_t do_swap_page(struct vm_fault *vmf) 3708 { 3709 struct vm_area_struct *vma = vmf->vma; 3710 struct page *page = NULL, *swapcache; 3711 struct swap_info_struct *si = NULL; 3712 rmap_t rmap_flags = RMAP_NONE; 3713 bool exclusive = false; 3714 swp_entry_t entry; 3715 pte_t pte; 3716 int locked; 3717 vm_fault_t ret = 0; 3718 void *shadow = NULL; 3719 3720 if (!pte_unmap_same(vmf)) 3721 goto out; 3722 3723 entry = pte_to_swp_entry(vmf->orig_pte); 3724 if (unlikely(non_swap_entry(entry))) { 3725 if (is_migration_entry(entry)) { 3726 migration_entry_wait(vma->vm_mm, vmf->pmd, 3727 vmf->address); 3728 } else if (is_device_exclusive_entry(entry)) { 3729 vmf->page = pfn_swap_entry_to_page(entry); 3730 ret = remove_device_exclusive_entry(vmf); 3731 } else if (is_device_private_entry(entry)) { 3732 vmf->page = pfn_swap_entry_to_page(entry); 3733 ret = vmf->page->pgmap->ops->migrate_to_ram(vmf); 3734 } else if (is_hwpoison_entry(entry)) { 3735 ret = VM_FAULT_HWPOISON; 3736 } else if (is_swapin_error_entry(entry)) { 3737 ret = VM_FAULT_SIGBUS; 3738 } else if (is_pte_marker_entry(entry)) { 3739 ret = handle_pte_marker(vmf); 3740 } else { 3741 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL); 3742 ret = VM_FAULT_SIGBUS; 3743 } 3744 goto out; 3745 } 3746 3747 /* Prevent swapoff from happening to us. */ 3748 si = get_swap_device(entry); 3749 if (unlikely(!si)) 3750 goto out; 3751 3752 page = lookup_swap_cache(entry, vma, vmf->address); 3753 swapcache = page; 3754 3755 if (!page) { 3756 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) && 3757 __swap_count(entry) == 1) { 3758 /* skip swapcache */ 3759 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, 3760 vmf->address); 3761 if (page) { 3762 __SetPageLocked(page); 3763 __SetPageSwapBacked(page); 3764 3765 if (mem_cgroup_swapin_charge_page(page, 3766 vma->vm_mm, GFP_KERNEL, entry)) { 3767 ret = VM_FAULT_OOM; 3768 goto out_page; 3769 } 3770 mem_cgroup_swapin_uncharge_swap(entry); 3771 3772 shadow = get_shadow_from_swap_cache(entry); 3773 if (shadow) 3774 workingset_refault(page_folio(page), 3775 shadow); 3776 3777 lru_cache_add(page); 3778 3779 /* To provide entry to swap_readpage() */ 3780 set_page_private(page, entry.val); 3781 swap_readpage(page, true, NULL); 3782 set_page_private(page, 0); 3783 } 3784 } else { 3785 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, 3786 vmf); 3787 swapcache = page; 3788 } 3789 3790 if (!page) { 3791 /* 3792 * Back out if somebody else faulted in this pte 3793 * while we released the pte lock. 3794 */ 3795 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 3796 vmf->address, &vmf->ptl); 3797 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) 3798 ret = VM_FAULT_OOM; 3799 goto unlock; 3800 } 3801 3802 /* Had to read the page from swap area: Major fault */ 3803 ret = VM_FAULT_MAJOR; 3804 count_vm_event(PGMAJFAULT); 3805 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT); 3806 } else if (PageHWPoison(page)) { 3807 /* 3808 * hwpoisoned dirty swapcache pages are kept for killing 3809 * owner processes (which may be unknown at hwpoison time) 3810 */ 3811 ret = VM_FAULT_HWPOISON; 3812 goto out_release; 3813 } 3814 3815 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags); 3816 3817 if (!locked) { 3818 ret |= VM_FAULT_RETRY; 3819 goto out_release; 3820 } 3821 3822 if (swapcache) { 3823 /* 3824 * Make sure try_to_free_swap or swapoff did not release the 3825 * swapcache from under us. The page pin, and pte_same test 3826 * below, are not enough to exclude that. Even if it is still 3827 * swapcache, we need to check that the page's swap has not 3828 * changed. 3829 */ 3830 if (unlikely(!PageSwapCache(page) || 3831 page_private(page) != entry.val)) 3832 goto out_page; 3833 3834 /* 3835 * KSM sometimes has to copy on read faults, for example, if 3836 * page->index of !PageKSM() pages would be nonlinear inside the 3837 * anon VMA -- PageKSM() is lost on actual swapout. 3838 */ 3839 page = ksm_might_need_to_copy(page, vma, vmf->address); 3840 if (unlikely(!page)) { 3841 ret = VM_FAULT_OOM; 3842 page = swapcache; 3843 goto out_page; 3844 } 3845 3846 /* 3847 * If we want to map a page that's in the swapcache writable, we 3848 * have to detect via the refcount if we're really the exclusive 3849 * owner. Try removing the extra reference from the local LRU 3850 * pagevecs if required. 3851 */ 3852 if ((vmf->flags & FAULT_FLAG_WRITE) && page == swapcache && 3853 !PageKsm(page) && !PageLRU(page)) 3854 lru_add_drain(); 3855 } 3856 3857 cgroup_throttle_swaprate(page, GFP_KERNEL); 3858 3859 /* 3860 * Back out if somebody else already faulted in this pte. 3861 */ 3862 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 3863 &vmf->ptl); 3864 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) 3865 goto out_nomap; 3866 3867 if (unlikely(!PageUptodate(page))) { 3868 ret = VM_FAULT_SIGBUS; 3869 goto out_nomap; 3870 } 3871 3872 /* 3873 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte 3874 * must never point at an anonymous page in the swapcache that is 3875 * PG_anon_exclusive. Sanity check that this holds and especially, that 3876 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity 3877 * check after taking the PT lock and making sure that nobody 3878 * concurrently faulted in this page and set PG_anon_exclusive. 3879 */ 3880 BUG_ON(!PageAnon(page) && PageMappedToDisk(page)); 3881 BUG_ON(PageAnon(page) && PageAnonExclusive(page)); 3882 3883 /* 3884 * Check under PT lock (to protect against concurrent fork() sharing 3885 * the swap entry concurrently) for certainly exclusive pages. 3886 */ 3887 if (!PageKsm(page)) { 3888 /* 3889 * Note that pte_swp_exclusive() == false for architectures 3890 * without __HAVE_ARCH_PTE_SWP_EXCLUSIVE. 3891 */ 3892 exclusive = pte_swp_exclusive(vmf->orig_pte); 3893 if (page != swapcache) { 3894 /* 3895 * We have a fresh page that is not exposed to the 3896 * swapcache -> certainly exclusive. 3897 */ 3898 exclusive = true; 3899 } else if (exclusive && PageWriteback(page) && 3900 data_race(si->flags & SWP_STABLE_WRITES)) { 3901 /* 3902 * This is tricky: not all swap backends support 3903 * concurrent page modifications while under writeback. 3904 * 3905 * So if we stumble over such a page in the swapcache 3906 * we must not set the page exclusive, otherwise we can 3907 * map it writable without further checks and modify it 3908 * while still under writeback. 3909 * 3910 * For these problematic swap backends, simply drop the 3911 * exclusive marker: this is perfectly fine as we start 3912 * writeback only if we fully unmapped the page and 3913 * there are no unexpected references on the page after 3914 * unmapping succeeded. After fully unmapped, no 3915 * further GUP references (FOLL_GET and FOLL_PIN) can 3916 * appear, so dropping the exclusive marker and mapping 3917 * it only R/O is fine. 3918 */ 3919 exclusive = false; 3920 } 3921 } 3922 3923 /* 3924 * Remove the swap entry and conditionally try to free up the swapcache. 3925 * We're already holding a reference on the page but haven't mapped it 3926 * yet. 3927 */ 3928 swap_free(entry); 3929 if (should_try_to_free_swap(page, vma, vmf->flags)) 3930 try_to_free_swap(page); 3931 3932 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES); 3933 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS); 3934 pte = mk_pte(page, vma->vm_page_prot); 3935 3936 /* 3937 * Same logic as in do_wp_page(); however, optimize for pages that are 3938 * certainly not shared either because we just allocated them without 3939 * exposing them to the swapcache or because the swap entry indicates 3940 * exclusivity. 3941 */ 3942 if (!PageKsm(page) && (exclusive || page_count(page) == 1)) { 3943 if (vmf->flags & FAULT_FLAG_WRITE) { 3944 pte = maybe_mkwrite(pte_mkdirty(pte), vma); 3945 vmf->flags &= ~FAULT_FLAG_WRITE; 3946 ret |= VM_FAULT_WRITE; 3947 } 3948 rmap_flags |= RMAP_EXCLUSIVE; 3949 } 3950 flush_icache_page(vma, page); 3951 if (pte_swp_soft_dirty(vmf->orig_pte)) 3952 pte = pte_mksoft_dirty(pte); 3953 if (pte_swp_uffd_wp(vmf->orig_pte)) { 3954 pte = pte_mkuffd_wp(pte); 3955 pte = pte_wrprotect(pte); 3956 } 3957 vmf->orig_pte = pte; 3958 3959 /* ksm created a completely new copy */ 3960 if (unlikely(page != swapcache && swapcache)) { 3961 page_add_new_anon_rmap(page, vma, vmf->address); 3962 lru_cache_add_inactive_or_unevictable(page, vma); 3963 } else { 3964 page_add_anon_rmap(page, vma, vmf->address, rmap_flags); 3965 } 3966 3967 VM_BUG_ON(!PageAnon(page) || (pte_write(pte) && !PageAnonExclusive(page))); 3968 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte); 3969 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte); 3970 3971 unlock_page(page); 3972 if (page != swapcache && swapcache) { 3973 /* 3974 * Hold the lock to avoid the swap entry to be reused 3975 * until we take the PT lock for the pte_same() check 3976 * (to avoid false positives from pte_same). For 3977 * further safety release the lock after the swap_free 3978 * so that the swap count won't change under a 3979 * parallel locked swapcache. 3980 */ 3981 unlock_page(swapcache); 3982 put_page(swapcache); 3983 } 3984 3985 if (vmf->flags & FAULT_FLAG_WRITE) { 3986 ret |= do_wp_page(vmf); 3987 if (ret & VM_FAULT_ERROR) 3988 ret &= VM_FAULT_ERROR; 3989 goto out; 3990 } 3991 3992 /* No need to invalidate - it was non-present before */ 3993 update_mmu_cache(vma, vmf->address, vmf->pte); 3994 unlock: 3995 pte_unmap_unlock(vmf->pte, vmf->ptl); 3996 out: 3997 if (si) 3998 put_swap_device(si); 3999 return ret; 4000 out_nomap: 4001 pte_unmap_unlock(vmf->pte, vmf->ptl); 4002 out_page: 4003 unlock_page(page); 4004 out_release: 4005 put_page(page); 4006 if (page != swapcache && swapcache) { 4007 unlock_page(swapcache); 4008 put_page(swapcache); 4009 } 4010 if (si) 4011 put_swap_device(si); 4012 return ret; 4013 } 4014 4015 /* 4016 * We enter with non-exclusive mmap_lock (to exclude vma changes, 4017 * but allow concurrent faults), and pte mapped but not yet locked. 4018 * We return with mmap_lock still held, but pte unmapped and unlocked. 4019 */ 4020 static vm_fault_t do_anonymous_page(struct vm_fault *vmf) 4021 { 4022 struct vm_area_struct *vma = vmf->vma; 4023 struct page *page; 4024 vm_fault_t ret = 0; 4025 pte_t entry; 4026 4027 /* File mapping without ->vm_ops ? */ 4028 if (vma->vm_flags & VM_SHARED) 4029 return VM_FAULT_SIGBUS; 4030 4031 /* 4032 * Use pte_alloc() instead of pte_alloc_map(). We can't run 4033 * pte_offset_map() on pmds where a huge pmd might be created 4034 * from a different thread. 4035 * 4036 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when 4037 * parallel threads are excluded by other means. 4038 * 4039 * Here we only have mmap_read_lock(mm). 4040 */ 4041 if (pte_alloc(vma->vm_mm, vmf->pmd)) 4042 return VM_FAULT_OOM; 4043 4044 /* See comment in handle_pte_fault() */ 4045 if (unlikely(pmd_trans_unstable(vmf->pmd))) 4046 return 0; 4047 4048 /* Use the zero-page for reads */ 4049 if (!(vmf->flags & FAULT_FLAG_WRITE) && 4050 !mm_forbids_zeropage(vma->vm_mm)) { 4051 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address), 4052 vma->vm_page_prot)); 4053 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4054 vmf->address, &vmf->ptl); 4055 if (!pte_none(*vmf->pte)) { 4056 update_mmu_tlb(vma, vmf->address, vmf->pte); 4057 goto unlock; 4058 } 4059 ret = check_stable_address_space(vma->vm_mm); 4060 if (ret) 4061 goto unlock; 4062 /* Deliver the page fault to userland, check inside PT lock */ 4063 if (userfaultfd_missing(vma)) { 4064 pte_unmap_unlock(vmf->pte, vmf->ptl); 4065 return handle_userfault(vmf, VM_UFFD_MISSING); 4066 } 4067 goto setpte; 4068 } 4069 4070 /* Allocate our own private page. */ 4071 if (unlikely(anon_vma_prepare(vma))) 4072 goto oom; 4073 page = alloc_zeroed_user_highpage_movable(vma, vmf->address); 4074 if (!page) 4075 goto oom; 4076 4077 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL)) 4078 goto oom_free_page; 4079 cgroup_throttle_swaprate(page, GFP_KERNEL); 4080 4081 /* 4082 * The memory barrier inside __SetPageUptodate makes sure that 4083 * preceding stores to the page contents become visible before 4084 * the set_pte_at() write. 4085 */ 4086 __SetPageUptodate(page); 4087 4088 entry = mk_pte(page, vma->vm_page_prot); 4089 entry = pte_sw_mkyoung(entry); 4090 if (vma->vm_flags & VM_WRITE) 4091 entry = pte_mkwrite(pte_mkdirty(entry)); 4092 4093 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, 4094 &vmf->ptl); 4095 if (!pte_none(*vmf->pte)) { 4096 update_mmu_cache(vma, vmf->address, vmf->pte); 4097 goto release; 4098 } 4099 4100 ret = check_stable_address_space(vma->vm_mm); 4101 if (ret) 4102 goto release; 4103 4104 /* Deliver the page fault to userland, check inside PT lock */ 4105 if (userfaultfd_missing(vma)) { 4106 pte_unmap_unlock(vmf->pte, vmf->ptl); 4107 put_page(page); 4108 return handle_userfault(vmf, VM_UFFD_MISSING); 4109 } 4110 4111 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES); 4112 page_add_new_anon_rmap(page, vma, vmf->address); 4113 lru_cache_add_inactive_or_unevictable(page, vma); 4114 setpte: 4115 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry); 4116 4117 /* No need to invalidate - it was non-present before */ 4118 update_mmu_cache(vma, vmf->address, vmf->pte); 4119 unlock: 4120 pte_unmap_unlock(vmf->pte, vmf->ptl); 4121 return ret; 4122 release: 4123 put_page(page); 4124 goto unlock; 4125 oom_free_page: 4126 put_page(page); 4127 oom: 4128 return VM_FAULT_OOM; 4129 } 4130 4131 /* 4132 * The mmap_lock must have been held on entry, and may have been 4133 * released depending on flags and vma->vm_ops->fault() return value. 4134 * See filemap_fault() and __lock_page_retry(). 4135 */ 4136 static vm_fault_t __do_fault(struct vm_fault *vmf) 4137 { 4138 struct vm_area_struct *vma = vmf->vma; 4139 vm_fault_t ret; 4140 4141 /* 4142 * Preallocate pte before we take page_lock because this might lead to 4143 * deadlocks for memcg reclaim which waits for pages under writeback: 4144 * lock_page(A) 4145 * SetPageWriteback(A) 4146 * unlock_page(A) 4147 * lock_page(B) 4148 * lock_page(B) 4149 * pte_alloc_one 4150 * shrink_page_list 4151 * wait_on_page_writeback(A) 4152 * SetPageWriteback(B) 4153 * unlock_page(B) 4154 * # flush A, B to clear the writeback 4155 */ 4156 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) { 4157 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm); 4158 if (!vmf->prealloc_pte) 4159 return VM_FAULT_OOM; 4160 } 4161 4162 ret = vma->vm_ops->fault(vmf); 4163 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY | 4164 VM_FAULT_DONE_COW))) 4165 return ret; 4166 4167 if (unlikely(PageHWPoison(vmf->page))) { 4168 struct page *page = vmf->page; 4169 vm_fault_t poisonret = VM_FAULT_HWPOISON; 4170 if (ret & VM_FAULT_LOCKED) { 4171 if (page_mapped(page)) 4172 unmap_mapping_pages(page_mapping(page), 4173 page->index, 1, false); 4174 /* Retry if a clean page was removed from the cache. */ 4175 if (invalidate_inode_page(page)) 4176 poisonret = VM_FAULT_NOPAGE; 4177 unlock_page(page); 4178 } 4179 put_page(page); 4180 vmf->page = NULL; 4181 return poisonret; 4182 } 4183 4184 if (unlikely(!(ret & VM_FAULT_LOCKED))) 4185 lock_page(vmf->page); 4186 else 4187 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page); 4188 4189 return ret; 4190 } 4191 4192 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4193 static void deposit_prealloc_pte(struct vm_fault *vmf) 4194 { 4195 struct vm_area_struct *vma = vmf->vma; 4196 4197 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte); 4198 /* 4199 * We are going to consume the prealloc table, 4200 * count that as nr_ptes. 4201 */ 4202 mm_inc_nr_ptes(vma->vm_mm); 4203 vmf->prealloc_pte = NULL; 4204 } 4205 4206 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page) 4207 { 4208 struct vm_area_struct *vma = vmf->vma; 4209 bool write = vmf->flags & FAULT_FLAG_WRITE; 4210 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 4211 pmd_t entry; 4212 int i; 4213 vm_fault_t ret = VM_FAULT_FALLBACK; 4214 4215 if (!transhuge_vma_suitable(vma, haddr)) 4216 return ret; 4217 4218 page = compound_head(page); 4219 if (compound_order(page) != HPAGE_PMD_ORDER) 4220 return ret; 4221 4222 /* 4223 * Just backoff if any subpage of a THP is corrupted otherwise 4224 * the corrupted page may mapped by PMD silently to escape the 4225 * check. This kind of THP just can be PTE mapped. Access to 4226 * the corrupted subpage should trigger SIGBUS as expected. 4227 */ 4228 if (unlikely(PageHasHWPoisoned(page))) 4229 return ret; 4230 4231 /* 4232 * Archs like ppc64 need additional space to store information 4233 * related to pte entry. Use the preallocated table for that. 4234 */ 4235 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) { 4236 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm); 4237 if (!vmf->prealloc_pte) 4238 return VM_FAULT_OOM; 4239 } 4240 4241 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 4242 if (unlikely(!pmd_none(*vmf->pmd))) 4243 goto out; 4244 4245 for (i = 0; i < HPAGE_PMD_NR; i++) 4246 flush_icache_page(vma, page + i); 4247 4248 entry = mk_huge_pmd(page, vma->vm_page_prot); 4249 if (write) 4250 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 4251 4252 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR); 4253 page_add_file_rmap(page, vma, true); 4254 4255 /* 4256 * deposit and withdraw with pmd lock held 4257 */ 4258 if (arch_needs_pgtable_deposit()) 4259 deposit_prealloc_pte(vmf); 4260 4261 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry); 4262 4263 update_mmu_cache_pmd(vma, haddr, vmf->pmd); 4264 4265 /* fault is handled */ 4266 ret = 0; 4267 count_vm_event(THP_FILE_MAPPED); 4268 out: 4269 spin_unlock(vmf->ptl); 4270 return ret; 4271 } 4272 #else 4273 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page) 4274 { 4275 return VM_FAULT_FALLBACK; 4276 } 4277 #endif 4278 4279 void do_set_pte(struct vm_fault *vmf, struct page *page, unsigned long addr) 4280 { 4281 struct vm_area_struct *vma = vmf->vma; 4282 bool uffd_wp = pte_marker_uffd_wp(vmf->orig_pte); 4283 bool write = vmf->flags & FAULT_FLAG_WRITE; 4284 bool prefault = vmf->address != addr; 4285 pte_t entry; 4286 4287 flush_icache_page(vma, page); 4288 entry = mk_pte(page, vma->vm_page_prot); 4289 4290 if (prefault && arch_wants_old_prefaulted_pte()) 4291 entry = pte_mkold(entry); 4292 else 4293 entry = pte_sw_mkyoung(entry); 4294 4295 if (write) 4296 entry = maybe_mkwrite(pte_mkdirty(entry), vma); 4297 if (unlikely(uffd_wp)) 4298 entry = pte_mkuffd_wp(pte_wrprotect(entry)); 4299 /* copy-on-write page */ 4300 if (write && !(vma->vm_flags & VM_SHARED)) { 4301 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES); 4302 page_add_new_anon_rmap(page, vma, addr); 4303 lru_cache_add_inactive_or_unevictable(page, vma); 4304 } else { 4305 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page)); 4306 page_add_file_rmap(page, vma, false); 4307 } 4308 set_pte_at(vma->vm_mm, addr, vmf->pte, entry); 4309 } 4310 4311 static bool vmf_pte_changed(struct vm_fault *vmf) 4312 { 4313 if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID) 4314 return !pte_same(*vmf->pte, vmf->orig_pte); 4315 4316 return !pte_none(*vmf->pte); 4317 } 4318 4319 /** 4320 * finish_fault - finish page fault once we have prepared the page to fault 4321 * 4322 * @vmf: structure describing the fault 4323 * 4324 * This function handles all that is needed to finish a page fault once the 4325 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for 4326 * given page, adds reverse page mapping, handles memcg charges and LRU 4327 * addition. 4328 * 4329 * The function expects the page to be locked and on success it consumes a 4330 * reference of a page being mapped (for the PTE which maps it). 4331 * 4332 * Return: %0 on success, %VM_FAULT_ code in case of error. 4333 */ 4334 vm_fault_t finish_fault(struct vm_fault *vmf) 4335 { 4336 struct vm_area_struct *vma = vmf->vma; 4337 struct page *page; 4338 vm_fault_t ret; 4339 4340 /* Did we COW the page? */ 4341 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) 4342 page = vmf->cow_page; 4343 else 4344 page = vmf->page; 4345 4346 /* 4347 * check even for read faults because we might have lost our CoWed 4348 * page 4349 */ 4350 if (!(vma->vm_flags & VM_SHARED)) { 4351 ret = check_stable_address_space(vma->vm_mm); 4352 if (ret) 4353 return ret; 4354 } 4355 4356 if (pmd_none(*vmf->pmd)) { 4357 if (PageTransCompound(page)) { 4358 ret = do_set_pmd(vmf, page); 4359 if (ret != VM_FAULT_FALLBACK) 4360 return ret; 4361 } 4362 4363 if (vmf->prealloc_pte) 4364 pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte); 4365 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) 4366 return VM_FAULT_OOM; 4367 } 4368 4369 /* 4370 * See comment in handle_pte_fault() for how this scenario happens, we 4371 * need to return NOPAGE so that we drop this page. 4372 */ 4373 if (pmd_devmap_trans_unstable(vmf->pmd)) 4374 return VM_FAULT_NOPAGE; 4375 4376 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, 4377 vmf->address, &vmf->ptl); 4378 4379 /* Re-check under ptl */ 4380 if (likely(!vmf_pte_changed(vmf))) { 4381 do_set_pte(vmf, page, vmf->address); 4382 4383 /* no need to invalidate: a not-present page won't be cached */ 4384 update_mmu_cache(vma, vmf->address, vmf->pte); 4385 4386 ret = 0; 4387 } else { 4388 update_mmu_tlb(vma, vmf->address, vmf->pte); 4389 ret = VM_FAULT_NOPAGE; 4390 } 4391 4392 pte_unmap_unlock(vmf->pte, vmf->ptl); 4393 return ret; 4394 } 4395 4396 static unsigned long fault_around_bytes __read_mostly = 4397 rounddown_pow_of_two(65536); 4398 4399 #ifdef CONFIG_DEBUG_FS 4400 static int fault_around_bytes_get(void *data, u64 *val) 4401 { 4402 *val = fault_around_bytes; 4403 return 0; 4404 } 4405 4406 /* 4407 * fault_around_bytes must be rounded down to the nearest page order as it's 4408 * what do_fault_around() expects to see. 4409 */ 4410 static int fault_around_bytes_set(void *data, u64 val) 4411 { 4412 if (val / PAGE_SIZE > PTRS_PER_PTE) 4413 return -EINVAL; 4414 if (val > PAGE_SIZE) 4415 fault_around_bytes = rounddown_pow_of_two(val); 4416 else 4417 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */ 4418 return 0; 4419 } 4420 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops, 4421 fault_around_bytes_get, fault_around_bytes_set, "%llu\n"); 4422 4423 static int __init fault_around_debugfs(void) 4424 { 4425 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL, 4426 &fault_around_bytes_fops); 4427 return 0; 4428 } 4429 late_initcall(fault_around_debugfs); 4430 #endif 4431 4432 /* 4433 * do_fault_around() tries to map few pages around the fault address. The hope 4434 * is that the pages will be needed soon and this will lower the number of 4435 * faults to handle. 4436 * 4437 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's 4438 * not ready to be mapped: not up-to-date, locked, etc. 4439 * 4440 * This function doesn't cross the VMA boundaries, in order to call map_pages() 4441 * only once. 4442 * 4443 * fault_around_bytes defines how many bytes we'll try to map. 4444 * do_fault_around() expects it to be set to a power of two less than or equal 4445 * to PTRS_PER_PTE. 4446 * 4447 * The virtual address of the area that we map is naturally aligned to 4448 * fault_around_bytes rounded down to the machine page size 4449 * (and therefore to page order). This way it's easier to guarantee 4450 * that we don't cross page table boundaries. 4451 */ 4452 static vm_fault_t do_fault_around(struct vm_fault *vmf) 4453 { 4454 unsigned long address = vmf->address, nr_pages, mask; 4455 pgoff_t start_pgoff = vmf->pgoff; 4456 pgoff_t end_pgoff; 4457 int off; 4458 4459 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT; 4460 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK; 4461 4462 address = max(address & mask, vmf->vma->vm_start); 4463 off = ((vmf->address - address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1); 4464 start_pgoff -= off; 4465 4466 /* 4467 * end_pgoff is either the end of the page table, the end of 4468 * the vma or nr_pages from start_pgoff, depending what is nearest. 4469 */ 4470 end_pgoff = start_pgoff - 4471 ((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) + 4472 PTRS_PER_PTE - 1; 4473 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1, 4474 start_pgoff + nr_pages - 1); 4475 4476 if (pmd_none(*vmf->pmd)) { 4477 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm); 4478 if (!vmf->prealloc_pte) 4479 return VM_FAULT_OOM; 4480 } 4481 4482 return vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff); 4483 } 4484 4485 /* Return true if we should do read fault-around, false otherwise */ 4486 static inline bool should_fault_around(struct vm_fault *vmf) 4487 { 4488 /* No ->map_pages? No way to fault around... */ 4489 if (!vmf->vma->vm_ops->map_pages) 4490 return false; 4491 4492 if (uffd_disable_fault_around(vmf->vma)) 4493 return false; 4494 4495 return fault_around_bytes >> PAGE_SHIFT > 1; 4496 } 4497 4498 static vm_fault_t do_read_fault(struct vm_fault *vmf) 4499 { 4500 vm_fault_t ret = 0; 4501 4502 /* 4503 * Let's call ->map_pages() first and use ->fault() as fallback 4504 * if page by the offset is not ready to be mapped (cold cache or 4505 * something). 4506 */ 4507 if (should_fault_around(vmf)) { 4508 ret = do_fault_around(vmf); 4509 if (ret) 4510 return ret; 4511 } 4512 4513 ret = __do_fault(vmf); 4514 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4515 return ret; 4516 4517 ret |= finish_fault(vmf); 4518 unlock_page(vmf->page); 4519 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4520 put_page(vmf->page); 4521 return ret; 4522 } 4523 4524 static vm_fault_t do_cow_fault(struct vm_fault *vmf) 4525 { 4526 struct vm_area_struct *vma = vmf->vma; 4527 vm_fault_t ret; 4528 4529 if (unlikely(anon_vma_prepare(vma))) 4530 return VM_FAULT_OOM; 4531 4532 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address); 4533 if (!vmf->cow_page) 4534 return VM_FAULT_OOM; 4535 4536 if (mem_cgroup_charge(page_folio(vmf->cow_page), vma->vm_mm, 4537 GFP_KERNEL)) { 4538 put_page(vmf->cow_page); 4539 return VM_FAULT_OOM; 4540 } 4541 cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL); 4542 4543 ret = __do_fault(vmf); 4544 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4545 goto uncharge_out; 4546 if (ret & VM_FAULT_DONE_COW) 4547 return ret; 4548 4549 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma); 4550 __SetPageUptodate(vmf->cow_page); 4551 4552 ret |= finish_fault(vmf); 4553 unlock_page(vmf->page); 4554 put_page(vmf->page); 4555 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4556 goto uncharge_out; 4557 return ret; 4558 uncharge_out: 4559 put_page(vmf->cow_page); 4560 return ret; 4561 } 4562 4563 static vm_fault_t do_shared_fault(struct vm_fault *vmf) 4564 { 4565 struct vm_area_struct *vma = vmf->vma; 4566 vm_fault_t ret, tmp; 4567 4568 ret = __do_fault(vmf); 4569 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) 4570 return ret; 4571 4572 /* 4573 * Check if the backing address space wants to know that the page is 4574 * about to become writable 4575 */ 4576 if (vma->vm_ops->page_mkwrite) { 4577 unlock_page(vmf->page); 4578 tmp = do_page_mkwrite(vmf); 4579 if (unlikely(!tmp || 4580 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { 4581 put_page(vmf->page); 4582 return tmp; 4583 } 4584 } 4585 4586 ret |= finish_fault(vmf); 4587 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | 4588 VM_FAULT_RETRY))) { 4589 unlock_page(vmf->page); 4590 put_page(vmf->page); 4591 return ret; 4592 } 4593 4594 ret |= fault_dirty_shared_page(vmf); 4595 return ret; 4596 } 4597 4598 /* 4599 * We enter with non-exclusive mmap_lock (to exclude vma changes, 4600 * but allow concurrent faults). 4601 * The mmap_lock may have been released depending on flags and our 4602 * return value. See filemap_fault() and __folio_lock_or_retry(). 4603 * If mmap_lock is released, vma may become invalid (for example 4604 * by other thread calling munmap()). 4605 */ 4606 static vm_fault_t do_fault(struct vm_fault *vmf) 4607 { 4608 struct vm_area_struct *vma = vmf->vma; 4609 struct mm_struct *vm_mm = vma->vm_mm; 4610 vm_fault_t ret; 4611 4612 /* 4613 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND 4614 */ 4615 if (!vma->vm_ops->fault) { 4616 /* 4617 * If we find a migration pmd entry or a none pmd entry, which 4618 * should never happen, return SIGBUS 4619 */ 4620 if (unlikely(!pmd_present(*vmf->pmd))) 4621 ret = VM_FAULT_SIGBUS; 4622 else { 4623 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, 4624 vmf->pmd, 4625 vmf->address, 4626 &vmf->ptl); 4627 /* 4628 * Make sure this is not a temporary clearing of pte 4629 * by holding ptl and checking again. A R/M/W update 4630 * of pte involves: take ptl, clearing the pte so that 4631 * we don't have concurrent modification by hardware 4632 * followed by an update. 4633 */ 4634 if (unlikely(pte_none(*vmf->pte))) 4635 ret = VM_FAULT_SIGBUS; 4636 else 4637 ret = VM_FAULT_NOPAGE; 4638 4639 pte_unmap_unlock(vmf->pte, vmf->ptl); 4640 } 4641 } else if (!(vmf->flags & FAULT_FLAG_WRITE)) 4642 ret = do_read_fault(vmf); 4643 else if (!(vma->vm_flags & VM_SHARED)) 4644 ret = do_cow_fault(vmf); 4645 else 4646 ret = do_shared_fault(vmf); 4647 4648 /* preallocated pagetable is unused: free it */ 4649 if (vmf->prealloc_pte) { 4650 pte_free(vm_mm, vmf->prealloc_pte); 4651 vmf->prealloc_pte = NULL; 4652 } 4653 return ret; 4654 } 4655 4656 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma, 4657 unsigned long addr, int page_nid, int *flags) 4658 { 4659 get_page(page); 4660 4661 count_vm_numa_event(NUMA_HINT_FAULTS); 4662 if (page_nid == numa_node_id()) { 4663 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL); 4664 *flags |= TNF_FAULT_LOCAL; 4665 } 4666 4667 return mpol_misplaced(page, vma, addr); 4668 } 4669 4670 static vm_fault_t do_numa_page(struct vm_fault *vmf) 4671 { 4672 struct vm_area_struct *vma = vmf->vma; 4673 struct page *page = NULL; 4674 int page_nid = NUMA_NO_NODE; 4675 int last_cpupid; 4676 int target_nid; 4677 pte_t pte, old_pte; 4678 bool was_writable = pte_savedwrite(vmf->orig_pte); 4679 int flags = 0; 4680 4681 /* 4682 * The "pte" at this point cannot be used safely without 4683 * validation through pte_unmap_same(). It's of NUMA type but 4684 * the pfn may be screwed if the read is non atomic. 4685 */ 4686 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd); 4687 spin_lock(vmf->ptl); 4688 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) { 4689 pte_unmap_unlock(vmf->pte, vmf->ptl); 4690 goto out; 4691 } 4692 4693 /* Get the normal PTE */ 4694 old_pte = ptep_get(vmf->pte); 4695 pte = pte_modify(old_pte, vma->vm_page_prot); 4696 4697 page = vm_normal_page(vma, vmf->address, pte); 4698 if (!page || is_zone_device_page(page)) 4699 goto out_map; 4700 4701 /* TODO: handle PTE-mapped THP */ 4702 if (PageCompound(page)) 4703 goto out_map; 4704 4705 /* 4706 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as 4707 * much anyway since they can be in shared cache state. This misses 4708 * the case where a mapping is writable but the process never writes 4709 * to it but pte_write gets cleared during protection updates and 4710 * pte_dirty has unpredictable behaviour between PTE scan updates, 4711 * background writeback, dirty balancing and application behaviour. 4712 */ 4713 if (!was_writable) 4714 flags |= TNF_NO_GROUP; 4715 4716 /* 4717 * Flag if the page is shared between multiple address spaces. This 4718 * is later used when determining whether to group tasks together 4719 */ 4720 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED)) 4721 flags |= TNF_SHARED; 4722 4723 page_nid = page_to_nid(page); 4724 /* 4725 * For memory tiering mode, cpupid of slow memory page is used 4726 * to record page access time. So use default value. 4727 */ 4728 if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 4729 !node_is_toptier(page_nid)) 4730 last_cpupid = (-1 & LAST_CPUPID_MASK); 4731 else 4732 last_cpupid = page_cpupid_last(page); 4733 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid, 4734 &flags); 4735 if (target_nid == NUMA_NO_NODE) { 4736 put_page(page); 4737 goto out_map; 4738 } 4739 pte_unmap_unlock(vmf->pte, vmf->ptl); 4740 4741 /* Migrate to the requested node */ 4742 if (migrate_misplaced_page(page, vma, target_nid)) { 4743 page_nid = target_nid; 4744 flags |= TNF_MIGRATED; 4745 } else { 4746 flags |= TNF_MIGRATE_FAIL; 4747 vmf->pte = pte_offset_map(vmf->pmd, vmf->address); 4748 spin_lock(vmf->ptl); 4749 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) { 4750 pte_unmap_unlock(vmf->pte, vmf->ptl); 4751 goto out; 4752 } 4753 goto out_map; 4754 } 4755 4756 out: 4757 if (page_nid != NUMA_NO_NODE) 4758 task_numa_fault(last_cpupid, page_nid, 1, flags); 4759 return 0; 4760 out_map: 4761 /* 4762 * Make it present again, depending on how arch implements 4763 * non-accessible ptes, some can allow access by kernel mode. 4764 */ 4765 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte); 4766 pte = pte_modify(old_pte, vma->vm_page_prot); 4767 pte = pte_mkyoung(pte); 4768 if (was_writable) 4769 pte = pte_mkwrite(pte); 4770 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte); 4771 update_mmu_cache(vma, vmf->address, vmf->pte); 4772 pte_unmap_unlock(vmf->pte, vmf->ptl); 4773 goto out; 4774 } 4775 4776 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf) 4777 { 4778 if (vma_is_anonymous(vmf->vma)) 4779 return do_huge_pmd_anonymous_page(vmf); 4780 if (vmf->vma->vm_ops->huge_fault) 4781 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD); 4782 return VM_FAULT_FALLBACK; 4783 } 4784 4785 /* `inline' is required to avoid gcc 4.1.2 build error */ 4786 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf) 4787 { 4788 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 4789 4790 if (vma_is_anonymous(vmf->vma)) { 4791 if (likely(!unshare) && 4792 userfaultfd_huge_pmd_wp(vmf->vma, vmf->orig_pmd)) 4793 return handle_userfault(vmf, VM_UFFD_WP); 4794 return do_huge_pmd_wp_page(vmf); 4795 } 4796 if (vmf->vma->vm_ops->huge_fault) { 4797 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD); 4798 4799 if (!(ret & VM_FAULT_FALLBACK)) 4800 return ret; 4801 } 4802 4803 /* COW or write-notify handled on pte level: split pmd. */ 4804 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL); 4805 4806 return VM_FAULT_FALLBACK; 4807 } 4808 4809 static vm_fault_t create_huge_pud(struct vm_fault *vmf) 4810 { 4811 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \ 4812 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) 4813 /* No support for anonymous transparent PUD pages yet */ 4814 if (vma_is_anonymous(vmf->vma)) 4815 return VM_FAULT_FALLBACK; 4816 if (vmf->vma->vm_ops->huge_fault) 4817 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD); 4818 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 4819 return VM_FAULT_FALLBACK; 4820 } 4821 4822 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud) 4823 { 4824 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \ 4825 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) 4826 /* No support for anonymous transparent PUD pages yet */ 4827 if (vma_is_anonymous(vmf->vma)) 4828 goto split; 4829 if (vmf->vma->vm_ops->huge_fault) { 4830 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD); 4831 4832 if (!(ret & VM_FAULT_FALLBACK)) 4833 return ret; 4834 } 4835 split: 4836 /* COW or write-notify not handled on PUD level: split pud.*/ 4837 __split_huge_pud(vmf->vma, vmf->pud, vmf->address); 4838 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 4839 return VM_FAULT_FALLBACK; 4840 } 4841 4842 /* 4843 * These routines also need to handle stuff like marking pages dirty 4844 * and/or accessed for architectures that don't do it in hardware (most 4845 * RISC architectures). The early dirtying is also good on the i386. 4846 * 4847 * There is also a hook called "update_mmu_cache()" that architectures 4848 * with external mmu caches can use to update those (ie the Sparc or 4849 * PowerPC hashed page tables that act as extended TLBs). 4850 * 4851 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow 4852 * concurrent faults). 4853 * 4854 * The mmap_lock may have been released depending on flags and our return value. 4855 * See filemap_fault() and __folio_lock_or_retry(). 4856 */ 4857 static vm_fault_t handle_pte_fault(struct vm_fault *vmf) 4858 { 4859 pte_t entry; 4860 4861 if (unlikely(pmd_none(*vmf->pmd))) { 4862 /* 4863 * Leave __pte_alloc() until later: because vm_ops->fault may 4864 * want to allocate huge page, and if we expose page table 4865 * for an instant, it will be difficult to retract from 4866 * concurrent faults and from rmap lookups. 4867 */ 4868 vmf->pte = NULL; 4869 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID; 4870 } else { 4871 /* 4872 * If a huge pmd materialized under us just retry later. Use 4873 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead 4874 * of pmd_trans_huge() to ensure the pmd didn't become 4875 * pmd_trans_huge under us and then back to pmd_none, as a 4876 * result of MADV_DONTNEED running immediately after a huge pmd 4877 * fault in a different thread of this mm, in turn leading to a 4878 * misleading pmd_trans_huge() retval. All we have to ensure is 4879 * that it is a regular pmd that we can walk with 4880 * pte_offset_map() and we can do that through an atomic read 4881 * in C, which is what pmd_trans_unstable() provides. 4882 */ 4883 if (pmd_devmap_trans_unstable(vmf->pmd)) 4884 return 0; 4885 /* 4886 * A regular pmd is established and it can't morph into a huge 4887 * pmd from under us anymore at this point because we hold the 4888 * mmap_lock read mode and khugepaged takes it in write mode. 4889 * So now it's safe to run pte_offset_map(). 4890 */ 4891 vmf->pte = pte_offset_map(vmf->pmd, vmf->address); 4892 vmf->orig_pte = *vmf->pte; 4893 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID; 4894 4895 /* 4896 * some architectures can have larger ptes than wordsize, 4897 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and 4898 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic 4899 * accesses. The code below just needs a consistent view 4900 * for the ifs and we later double check anyway with the 4901 * ptl lock held. So here a barrier will do. 4902 */ 4903 barrier(); 4904 if (pte_none(vmf->orig_pte)) { 4905 pte_unmap(vmf->pte); 4906 vmf->pte = NULL; 4907 } 4908 } 4909 4910 if (!vmf->pte) { 4911 if (vma_is_anonymous(vmf->vma)) 4912 return do_anonymous_page(vmf); 4913 else 4914 return do_fault(vmf); 4915 } 4916 4917 if (!pte_present(vmf->orig_pte)) 4918 return do_swap_page(vmf); 4919 4920 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma)) 4921 return do_numa_page(vmf); 4922 4923 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd); 4924 spin_lock(vmf->ptl); 4925 entry = vmf->orig_pte; 4926 if (unlikely(!pte_same(*vmf->pte, entry))) { 4927 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte); 4928 goto unlock; 4929 } 4930 if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) { 4931 if (!pte_write(entry)) 4932 return do_wp_page(vmf); 4933 else if (likely(vmf->flags & FAULT_FLAG_WRITE)) 4934 entry = pte_mkdirty(entry); 4935 } 4936 entry = pte_mkyoung(entry); 4937 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry, 4938 vmf->flags & FAULT_FLAG_WRITE)) { 4939 update_mmu_cache(vmf->vma, vmf->address, vmf->pte); 4940 } else { 4941 /* Skip spurious TLB flush for retried page fault */ 4942 if (vmf->flags & FAULT_FLAG_TRIED) 4943 goto unlock; 4944 /* 4945 * This is needed only for protection faults but the arch code 4946 * is not yet telling us if this is a protection fault or not. 4947 * This still avoids useless tlb flushes for .text page faults 4948 * with threads. 4949 */ 4950 if (vmf->flags & FAULT_FLAG_WRITE) 4951 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address); 4952 } 4953 unlock: 4954 pte_unmap_unlock(vmf->pte, vmf->ptl); 4955 return 0; 4956 } 4957 4958 /* 4959 * By the time we get here, we already hold the mm semaphore 4960 * 4961 * The mmap_lock may have been released depending on flags and our 4962 * return value. See filemap_fault() and __folio_lock_or_retry(). 4963 */ 4964 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma, 4965 unsigned long address, unsigned int flags) 4966 { 4967 struct vm_fault vmf = { 4968 .vma = vma, 4969 .address = address & PAGE_MASK, 4970 .real_address = address, 4971 .flags = flags, 4972 .pgoff = linear_page_index(vma, address), 4973 .gfp_mask = __get_fault_gfp_mask(vma), 4974 }; 4975 struct mm_struct *mm = vma->vm_mm; 4976 unsigned long vm_flags = vma->vm_flags; 4977 pgd_t *pgd; 4978 p4d_t *p4d; 4979 vm_fault_t ret; 4980 4981 pgd = pgd_offset(mm, address); 4982 p4d = p4d_alloc(mm, pgd, address); 4983 if (!p4d) 4984 return VM_FAULT_OOM; 4985 4986 vmf.pud = pud_alloc(mm, p4d, address); 4987 if (!vmf.pud) 4988 return VM_FAULT_OOM; 4989 retry_pud: 4990 if (pud_none(*vmf.pud) && 4991 hugepage_vma_check(vma, vm_flags, false, true, true)) { 4992 ret = create_huge_pud(&vmf); 4993 if (!(ret & VM_FAULT_FALLBACK)) 4994 return ret; 4995 } else { 4996 pud_t orig_pud = *vmf.pud; 4997 4998 barrier(); 4999 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) { 5000 5001 /* 5002 * TODO once we support anonymous PUDs: NUMA case and 5003 * FAULT_FLAG_UNSHARE handling. 5004 */ 5005 if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) { 5006 ret = wp_huge_pud(&vmf, orig_pud); 5007 if (!(ret & VM_FAULT_FALLBACK)) 5008 return ret; 5009 } else { 5010 huge_pud_set_accessed(&vmf, orig_pud); 5011 return 0; 5012 } 5013 } 5014 } 5015 5016 vmf.pmd = pmd_alloc(mm, vmf.pud, address); 5017 if (!vmf.pmd) 5018 return VM_FAULT_OOM; 5019 5020 /* Huge pud page fault raced with pmd_alloc? */ 5021 if (pud_trans_unstable(vmf.pud)) 5022 goto retry_pud; 5023 5024 if (pmd_none(*vmf.pmd) && 5025 hugepage_vma_check(vma, vm_flags, false, true, true)) { 5026 ret = create_huge_pmd(&vmf); 5027 if (!(ret & VM_FAULT_FALLBACK)) 5028 return ret; 5029 } else { 5030 vmf.orig_pmd = *vmf.pmd; 5031 5032 barrier(); 5033 if (unlikely(is_swap_pmd(vmf.orig_pmd))) { 5034 VM_BUG_ON(thp_migration_supported() && 5035 !is_pmd_migration_entry(vmf.orig_pmd)); 5036 if (is_pmd_migration_entry(vmf.orig_pmd)) 5037 pmd_migration_entry_wait(mm, vmf.pmd); 5038 return 0; 5039 } 5040 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) { 5041 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma)) 5042 return do_huge_pmd_numa_page(&vmf); 5043 5044 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) && 5045 !pmd_write(vmf.orig_pmd)) { 5046 ret = wp_huge_pmd(&vmf); 5047 if (!(ret & VM_FAULT_FALLBACK)) 5048 return ret; 5049 } else { 5050 huge_pmd_set_accessed(&vmf); 5051 return 0; 5052 } 5053 } 5054 } 5055 5056 return handle_pte_fault(&vmf); 5057 } 5058 5059 /** 5060 * mm_account_fault - Do page fault accounting 5061 * 5062 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting 5063 * of perf event counters, but we'll still do the per-task accounting to 5064 * the task who triggered this page fault. 5065 * @address: the faulted address. 5066 * @flags: the fault flags. 5067 * @ret: the fault retcode. 5068 * 5069 * This will take care of most of the page fault accounting. Meanwhile, it 5070 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter 5071 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should 5072 * still be in per-arch page fault handlers at the entry of page fault. 5073 */ 5074 static inline void mm_account_fault(struct pt_regs *regs, 5075 unsigned long address, unsigned int flags, 5076 vm_fault_t ret) 5077 { 5078 bool major; 5079 5080 /* 5081 * We don't do accounting for some specific faults: 5082 * 5083 * - Unsuccessful faults (e.g. when the address wasn't valid). That 5084 * includes arch_vma_access_permitted() failing before reaching here. 5085 * So this is not a "this many hardware page faults" counter. We 5086 * should use the hw profiling for that. 5087 * 5088 * - Incomplete faults (VM_FAULT_RETRY). They will only be counted 5089 * once they're completed. 5090 */ 5091 if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY)) 5092 return; 5093 5094 /* 5095 * We define the fault as a major fault when the final successful fault 5096 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't 5097 * handle it immediately previously). 5098 */ 5099 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED); 5100 5101 if (major) 5102 current->maj_flt++; 5103 else 5104 current->min_flt++; 5105 5106 /* 5107 * If the fault is done for GUP, regs will be NULL. We only do the 5108 * accounting for the per thread fault counters who triggered the 5109 * fault, and we skip the perf event updates. 5110 */ 5111 if (!regs) 5112 return; 5113 5114 if (major) 5115 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address); 5116 else 5117 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address); 5118 } 5119 5120 /* 5121 * By the time we get here, we already hold the mm semaphore 5122 * 5123 * The mmap_lock may have been released depending on flags and our 5124 * return value. See filemap_fault() and __folio_lock_or_retry(). 5125 */ 5126 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address, 5127 unsigned int flags, struct pt_regs *regs) 5128 { 5129 vm_fault_t ret; 5130 5131 __set_current_state(TASK_RUNNING); 5132 5133 count_vm_event(PGFAULT); 5134 count_memcg_event_mm(vma->vm_mm, PGFAULT); 5135 5136 /* do counter updates before entering really critical section. */ 5137 check_sync_rss_stat(current); 5138 5139 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE, 5140 flags & FAULT_FLAG_INSTRUCTION, 5141 flags & FAULT_FLAG_REMOTE)) 5142 return VM_FAULT_SIGSEGV; 5143 5144 /* 5145 * Enable the memcg OOM handling for faults triggered in user 5146 * space. Kernel faults are handled more gracefully. 5147 */ 5148 if (flags & FAULT_FLAG_USER) 5149 mem_cgroup_enter_user_fault(); 5150 5151 if (unlikely(is_vm_hugetlb_page(vma))) 5152 ret = hugetlb_fault(vma->vm_mm, vma, address, flags); 5153 else 5154 ret = __handle_mm_fault(vma, address, flags); 5155 5156 if (flags & FAULT_FLAG_USER) { 5157 mem_cgroup_exit_user_fault(); 5158 /* 5159 * The task may have entered a memcg OOM situation but 5160 * if the allocation error was handled gracefully (no 5161 * VM_FAULT_OOM), there is no need to kill anything. 5162 * Just clean up the OOM state peacefully. 5163 */ 5164 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM)) 5165 mem_cgroup_oom_synchronize(false); 5166 } 5167 5168 mm_account_fault(regs, address, flags, ret); 5169 5170 return ret; 5171 } 5172 EXPORT_SYMBOL_GPL(handle_mm_fault); 5173 5174 #ifndef __PAGETABLE_P4D_FOLDED 5175 /* 5176 * Allocate p4d page table. 5177 * We've already handled the fast-path in-line. 5178 */ 5179 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) 5180 { 5181 p4d_t *new = p4d_alloc_one(mm, address); 5182 if (!new) 5183 return -ENOMEM; 5184 5185 spin_lock(&mm->page_table_lock); 5186 if (pgd_present(*pgd)) { /* Another has populated it */ 5187 p4d_free(mm, new); 5188 } else { 5189 smp_wmb(); /* See comment in pmd_install() */ 5190 pgd_populate(mm, pgd, new); 5191 } 5192 spin_unlock(&mm->page_table_lock); 5193 return 0; 5194 } 5195 #endif /* __PAGETABLE_P4D_FOLDED */ 5196 5197 #ifndef __PAGETABLE_PUD_FOLDED 5198 /* 5199 * Allocate page upper directory. 5200 * We've already handled the fast-path in-line. 5201 */ 5202 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address) 5203 { 5204 pud_t *new = pud_alloc_one(mm, address); 5205 if (!new) 5206 return -ENOMEM; 5207 5208 spin_lock(&mm->page_table_lock); 5209 if (!p4d_present(*p4d)) { 5210 mm_inc_nr_puds(mm); 5211 smp_wmb(); /* See comment in pmd_install() */ 5212 p4d_populate(mm, p4d, new); 5213 } else /* Another has populated it */ 5214 pud_free(mm, new); 5215 spin_unlock(&mm->page_table_lock); 5216 return 0; 5217 } 5218 #endif /* __PAGETABLE_PUD_FOLDED */ 5219 5220 #ifndef __PAGETABLE_PMD_FOLDED 5221 /* 5222 * Allocate page middle directory. 5223 * We've already handled the fast-path in-line. 5224 */ 5225 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) 5226 { 5227 spinlock_t *ptl; 5228 pmd_t *new = pmd_alloc_one(mm, address); 5229 if (!new) 5230 return -ENOMEM; 5231 5232 ptl = pud_lock(mm, pud); 5233 if (!pud_present(*pud)) { 5234 mm_inc_nr_pmds(mm); 5235 smp_wmb(); /* See comment in pmd_install() */ 5236 pud_populate(mm, pud, new); 5237 } else { /* Another has populated it */ 5238 pmd_free(mm, new); 5239 } 5240 spin_unlock(ptl); 5241 return 0; 5242 } 5243 #endif /* __PAGETABLE_PMD_FOLDED */ 5244 5245 /** 5246 * follow_pte - look up PTE at a user virtual address 5247 * @mm: the mm_struct of the target address space 5248 * @address: user virtual address 5249 * @ptepp: location to store found PTE 5250 * @ptlp: location to store the lock for the PTE 5251 * 5252 * On a successful return, the pointer to the PTE is stored in @ptepp; 5253 * the corresponding lock is taken and its location is stored in @ptlp. 5254 * The contents of the PTE are only stable until @ptlp is released; 5255 * any further use, if any, must be protected against invalidation 5256 * with MMU notifiers. 5257 * 5258 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore 5259 * should be taken for read. 5260 * 5261 * KVM uses this function. While it is arguably less bad than ``follow_pfn``, 5262 * it is not a good general-purpose API. 5263 * 5264 * Return: zero on success, -ve otherwise. 5265 */ 5266 int follow_pte(struct mm_struct *mm, unsigned long address, 5267 pte_t **ptepp, spinlock_t **ptlp) 5268 { 5269 pgd_t *pgd; 5270 p4d_t *p4d; 5271 pud_t *pud; 5272 pmd_t *pmd; 5273 pte_t *ptep; 5274 5275 pgd = pgd_offset(mm, address); 5276 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) 5277 goto out; 5278 5279 p4d = p4d_offset(pgd, address); 5280 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d))) 5281 goto out; 5282 5283 pud = pud_offset(p4d, address); 5284 if (pud_none(*pud) || unlikely(pud_bad(*pud))) 5285 goto out; 5286 5287 pmd = pmd_offset(pud, address); 5288 VM_BUG_ON(pmd_trans_huge(*pmd)); 5289 5290 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd))) 5291 goto out; 5292 5293 ptep = pte_offset_map_lock(mm, pmd, address, ptlp); 5294 if (!pte_present(*ptep)) 5295 goto unlock; 5296 *ptepp = ptep; 5297 return 0; 5298 unlock: 5299 pte_unmap_unlock(ptep, *ptlp); 5300 out: 5301 return -EINVAL; 5302 } 5303 EXPORT_SYMBOL_GPL(follow_pte); 5304 5305 /** 5306 * follow_pfn - look up PFN at a user virtual address 5307 * @vma: memory mapping 5308 * @address: user virtual address 5309 * @pfn: location to store found PFN 5310 * 5311 * Only IO mappings and raw PFN mappings are allowed. 5312 * 5313 * This function does not allow the caller to read the permissions 5314 * of the PTE. Do not use it. 5315 * 5316 * Return: zero and the pfn at @pfn on success, -ve otherwise. 5317 */ 5318 int follow_pfn(struct vm_area_struct *vma, unsigned long address, 5319 unsigned long *pfn) 5320 { 5321 int ret = -EINVAL; 5322 spinlock_t *ptl; 5323 pte_t *ptep; 5324 5325 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 5326 return ret; 5327 5328 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl); 5329 if (ret) 5330 return ret; 5331 *pfn = pte_pfn(*ptep); 5332 pte_unmap_unlock(ptep, ptl); 5333 return 0; 5334 } 5335 EXPORT_SYMBOL(follow_pfn); 5336 5337 #ifdef CONFIG_HAVE_IOREMAP_PROT 5338 int follow_phys(struct vm_area_struct *vma, 5339 unsigned long address, unsigned int flags, 5340 unsigned long *prot, resource_size_t *phys) 5341 { 5342 int ret = -EINVAL; 5343 pte_t *ptep, pte; 5344 spinlock_t *ptl; 5345 5346 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 5347 goto out; 5348 5349 if (follow_pte(vma->vm_mm, address, &ptep, &ptl)) 5350 goto out; 5351 pte = *ptep; 5352 5353 if ((flags & FOLL_WRITE) && !pte_write(pte)) 5354 goto unlock; 5355 5356 *prot = pgprot_val(pte_pgprot(pte)); 5357 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; 5358 5359 ret = 0; 5360 unlock: 5361 pte_unmap_unlock(ptep, ptl); 5362 out: 5363 return ret; 5364 } 5365 5366 /** 5367 * generic_access_phys - generic implementation for iomem mmap access 5368 * @vma: the vma to access 5369 * @addr: userspace address, not relative offset within @vma 5370 * @buf: buffer to read/write 5371 * @len: length of transfer 5372 * @write: set to FOLL_WRITE when writing, otherwise reading 5373 * 5374 * This is a generic implementation for &vm_operations_struct.access for an 5375 * iomem mapping. This callback is used by access_process_vm() when the @vma is 5376 * not page based. 5377 */ 5378 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, 5379 void *buf, int len, int write) 5380 { 5381 resource_size_t phys_addr; 5382 unsigned long prot = 0; 5383 void __iomem *maddr; 5384 pte_t *ptep, pte; 5385 spinlock_t *ptl; 5386 int offset = offset_in_page(addr); 5387 int ret = -EINVAL; 5388 5389 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) 5390 return -EINVAL; 5391 5392 retry: 5393 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl)) 5394 return -EINVAL; 5395 pte = *ptep; 5396 pte_unmap_unlock(ptep, ptl); 5397 5398 prot = pgprot_val(pte_pgprot(pte)); 5399 phys_addr = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; 5400 5401 if ((write & FOLL_WRITE) && !pte_write(pte)) 5402 return -EINVAL; 5403 5404 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot); 5405 if (!maddr) 5406 return -ENOMEM; 5407 5408 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl)) 5409 goto out_unmap; 5410 5411 if (!pte_same(pte, *ptep)) { 5412 pte_unmap_unlock(ptep, ptl); 5413 iounmap(maddr); 5414 5415 goto retry; 5416 } 5417 5418 if (write) 5419 memcpy_toio(maddr + offset, buf, len); 5420 else 5421 memcpy_fromio(buf, maddr + offset, len); 5422 ret = len; 5423 pte_unmap_unlock(ptep, ptl); 5424 out_unmap: 5425 iounmap(maddr); 5426 5427 return ret; 5428 } 5429 EXPORT_SYMBOL_GPL(generic_access_phys); 5430 #endif 5431 5432 /* 5433 * Access another process' address space as given in mm. 5434 */ 5435 int __access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf, 5436 int len, unsigned int gup_flags) 5437 { 5438 struct vm_area_struct *vma; 5439 void *old_buf = buf; 5440 int write = gup_flags & FOLL_WRITE; 5441 5442 if (mmap_read_lock_killable(mm)) 5443 return 0; 5444 5445 /* ignore errors, just check how much was successfully transferred */ 5446 while (len) { 5447 int bytes, ret, offset; 5448 void *maddr; 5449 struct page *page = NULL; 5450 5451 ret = get_user_pages_remote(mm, addr, 1, 5452 gup_flags, &page, &vma, NULL); 5453 if (ret <= 0) { 5454 #ifndef CONFIG_HAVE_IOREMAP_PROT 5455 break; 5456 #else 5457 /* 5458 * Check if this is a VM_IO | VM_PFNMAP VMA, which 5459 * we can access using slightly different code. 5460 */ 5461 vma = vma_lookup(mm, addr); 5462 if (!vma) 5463 break; 5464 if (vma->vm_ops && vma->vm_ops->access) 5465 ret = vma->vm_ops->access(vma, addr, buf, 5466 len, write); 5467 if (ret <= 0) 5468 break; 5469 bytes = ret; 5470 #endif 5471 } else { 5472 bytes = len; 5473 offset = addr & (PAGE_SIZE-1); 5474 if (bytes > PAGE_SIZE-offset) 5475 bytes = PAGE_SIZE-offset; 5476 5477 maddr = kmap(page); 5478 if (write) { 5479 copy_to_user_page(vma, page, addr, 5480 maddr + offset, buf, bytes); 5481 set_page_dirty_lock(page); 5482 } else { 5483 copy_from_user_page(vma, page, addr, 5484 buf, maddr + offset, bytes); 5485 } 5486 kunmap(page); 5487 put_page(page); 5488 } 5489 len -= bytes; 5490 buf += bytes; 5491 addr += bytes; 5492 } 5493 mmap_read_unlock(mm); 5494 5495 return buf - old_buf; 5496 } 5497 5498 /** 5499 * access_remote_vm - access another process' address space 5500 * @mm: the mm_struct of the target address space 5501 * @addr: start address to access 5502 * @buf: source or destination buffer 5503 * @len: number of bytes to transfer 5504 * @gup_flags: flags modifying lookup behaviour 5505 * 5506 * The caller must hold a reference on @mm. 5507 * 5508 * Return: number of bytes copied from source to destination. 5509 */ 5510 int access_remote_vm(struct mm_struct *mm, unsigned long addr, 5511 void *buf, int len, unsigned int gup_flags) 5512 { 5513 return __access_remote_vm(mm, addr, buf, len, gup_flags); 5514 } 5515 5516 /* 5517 * Access another process' address space. 5518 * Source/target buffer must be kernel space, 5519 * Do not walk the page table directly, use get_user_pages 5520 */ 5521 int access_process_vm(struct task_struct *tsk, unsigned long addr, 5522 void *buf, int len, unsigned int gup_flags) 5523 { 5524 struct mm_struct *mm; 5525 int ret; 5526 5527 mm = get_task_mm(tsk); 5528 if (!mm) 5529 return 0; 5530 5531 ret = __access_remote_vm(mm, addr, buf, len, gup_flags); 5532 5533 mmput(mm); 5534 5535 return ret; 5536 } 5537 EXPORT_SYMBOL_GPL(access_process_vm); 5538 5539 /* 5540 * Print the name of a VMA. 5541 */ 5542 void print_vma_addr(char *prefix, unsigned long ip) 5543 { 5544 struct mm_struct *mm = current->mm; 5545 struct vm_area_struct *vma; 5546 5547 /* 5548 * we might be running from an atomic context so we cannot sleep 5549 */ 5550 if (!mmap_read_trylock(mm)) 5551 return; 5552 5553 vma = find_vma(mm, ip); 5554 if (vma && vma->vm_file) { 5555 struct file *f = vma->vm_file; 5556 char *buf = (char *)__get_free_page(GFP_NOWAIT); 5557 if (buf) { 5558 char *p; 5559 5560 p = file_path(f, buf, PAGE_SIZE); 5561 if (IS_ERR(p)) 5562 p = "?"; 5563 printk("%s%s[%lx+%lx]", prefix, kbasename(p), 5564 vma->vm_start, 5565 vma->vm_end - vma->vm_start); 5566 free_page((unsigned long)buf); 5567 } 5568 } 5569 mmap_read_unlock(mm); 5570 } 5571 5572 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP) 5573 void __might_fault(const char *file, int line) 5574 { 5575 if (pagefault_disabled()) 5576 return; 5577 __might_sleep(file, line); 5578 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP) 5579 if (current->mm) 5580 might_lock_read(¤t->mm->mmap_lock); 5581 #endif 5582 } 5583 EXPORT_SYMBOL(__might_fault); 5584 #endif 5585 5586 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) 5587 /* 5588 * Process all subpages of the specified huge page with the specified 5589 * operation. The target subpage will be processed last to keep its 5590 * cache lines hot. 5591 */ 5592 static inline void process_huge_page( 5593 unsigned long addr_hint, unsigned int pages_per_huge_page, 5594 void (*process_subpage)(unsigned long addr, int idx, void *arg), 5595 void *arg) 5596 { 5597 int i, n, base, l; 5598 unsigned long addr = addr_hint & 5599 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1); 5600 5601 /* Process target subpage last to keep its cache lines hot */ 5602 might_sleep(); 5603 n = (addr_hint - addr) / PAGE_SIZE; 5604 if (2 * n <= pages_per_huge_page) { 5605 /* If target subpage in first half of huge page */ 5606 base = 0; 5607 l = n; 5608 /* Process subpages at the end of huge page */ 5609 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) { 5610 cond_resched(); 5611 process_subpage(addr + i * PAGE_SIZE, i, arg); 5612 } 5613 } else { 5614 /* If target subpage in second half of huge page */ 5615 base = pages_per_huge_page - 2 * (pages_per_huge_page - n); 5616 l = pages_per_huge_page - n; 5617 /* Process subpages at the begin of huge page */ 5618 for (i = 0; i < base; i++) { 5619 cond_resched(); 5620 process_subpage(addr + i * PAGE_SIZE, i, arg); 5621 } 5622 } 5623 /* 5624 * Process remaining subpages in left-right-left-right pattern 5625 * towards the target subpage 5626 */ 5627 for (i = 0; i < l; i++) { 5628 int left_idx = base + i; 5629 int right_idx = base + 2 * l - 1 - i; 5630 5631 cond_resched(); 5632 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg); 5633 cond_resched(); 5634 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg); 5635 } 5636 } 5637 5638 static void clear_gigantic_page(struct page *page, 5639 unsigned long addr, 5640 unsigned int pages_per_huge_page) 5641 { 5642 int i; 5643 struct page *p = page; 5644 5645 might_sleep(); 5646 for (i = 0; i < pages_per_huge_page; 5647 i++, p = mem_map_next(p, page, i)) { 5648 cond_resched(); 5649 clear_user_highpage(p, addr + i * PAGE_SIZE); 5650 } 5651 } 5652 5653 static void clear_subpage(unsigned long addr, int idx, void *arg) 5654 { 5655 struct page *page = arg; 5656 5657 clear_user_highpage(page + idx, addr); 5658 } 5659 5660 void clear_huge_page(struct page *page, 5661 unsigned long addr_hint, unsigned int pages_per_huge_page) 5662 { 5663 unsigned long addr = addr_hint & 5664 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1); 5665 5666 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { 5667 clear_gigantic_page(page, addr, pages_per_huge_page); 5668 return; 5669 } 5670 5671 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page); 5672 } 5673 5674 static void copy_user_gigantic_page(struct page *dst, struct page *src, 5675 unsigned long addr, 5676 struct vm_area_struct *vma, 5677 unsigned int pages_per_huge_page) 5678 { 5679 int i; 5680 struct page *dst_base = dst; 5681 struct page *src_base = src; 5682 5683 for (i = 0; i < pages_per_huge_page; ) { 5684 cond_resched(); 5685 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma); 5686 5687 i++; 5688 dst = mem_map_next(dst, dst_base, i); 5689 src = mem_map_next(src, src_base, i); 5690 } 5691 } 5692 5693 struct copy_subpage_arg { 5694 struct page *dst; 5695 struct page *src; 5696 struct vm_area_struct *vma; 5697 }; 5698 5699 static void copy_subpage(unsigned long addr, int idx, void *arg) 5700 { 5701 struct copy_subpage_arg *copy_arg = arg; 5702 5703 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx, 5704 addr, copy_arg->vma); 5705 } 5706 5707 void copy_user_huge_page(struct page *dst, struct page *src, 5708 unsigned long addr_hint, struct vm_area_struct *vma, 5709 unsigned int pages_per_huge_page) 5710 { 5711 unsigned long addr = addr_hint & 5712 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1); 5713 struct copy_subpage_arg arg = { 5714 .dst = dst, 5715 .src = src, 5716 .vma = vma, 5717 }; 5718 5719 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { 5720 copy_user_gigantic_page(dst, src, addr, vma, 5721 pages_per_huge_page); 5722 return; 5723 } 5724 5725 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg); 5726 } 5727 5728 long copy_huge_page_from_user(struct page *dst_page, 5729 const void __user *usr_src, 5730 unsigned int pages_per_huge_page, 5731 bool allow_pagefault) 5732 { 5733 void *page_kaddr; 5734 unsigned long i, rc = 0; 5735 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE; 5736 struct page *subpage = dst_page; 5737 5738 for (i = 0; i < pages_per_huge_page; 5739 i++, subpage = mem_map_next(subpage, dst_page, i)) { 5740 if (allow_pagefault) 5741 page_kaddr = kmap(subpage); 5742 else 5743 page_kaddr = kmap_atomic(subpage); 5744 rc = copy_from_user(page_kaddr, 5745 usr_src + i * PAGE_SIZE, PAGE_SIZE); 5746 if (allow_pagefault) 5747 kunmap(subpage); 5748 else 5749 kunmap_atomic(page_kaddr); 5750 5751 ret_val -= (PAGE_SIZE - rc); 5752 if (rc) 5753 break; 5754 5755 flush_dcache_page(subpage); 5756 5757 cond_resched(); 5758 } 5759 return ret_val; 5760 } 5761 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */ 5762 5763 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS 5764 5765 static struct kmem_cache *page_ptl_cachep; 5766 5767 void __init ptlock_cache_init(void) 5768 { 5769 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0, 5770 SLAB_PANIC, NULL); 5771 } 5772 5773 bool ptlock_alloc(struct page *page) 5774 { 5775 spinlock_t *ptl; 5776 5777 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL); 5778 if (!ptl) 5779 return false; 5780 page->ptl = ptl; 5781 return true; 5782 } 5783 5784 void ptlock_free(struct page *page) 5785 { 5786 kmem_cache_free(page_ptl_cachep, page->ptl); 5787 } 5788 #endif 5789