1 // SPDX-License-Identifier: GPL-2.0-only 2 #include <linux/kernel.h> 3 #include <linux/errno.h> 4 #include <linux/err.h> 5 #include <linux/spinlock.h> 6 7 #include <linux/mm.h> 8 #include <linux/memfd.h> 9 #include <linux/memremap.h> 10 #include <linux/pagemap.h> 11 #include <linux/rmap.h> 12 #include <linux/swap.h> 13 #include <linux/swapops.h> 14 #include <linux/secretmem.h> 15 16 #include <linux/sched/signal.h> 17 #include <linux/rwsem.h> 18 #include <linux/hugetlb.h> 19 #include <linux/migrate.h> 20 #include <linux/mm_inline.h> 21 #include <linux/pagevec.h> 22 #include <linux/sched/mm.h> 23 #include <linux/shmem_fs.h> 24 25 #include <asm/mmu_context.h> 26 #include <asm/tlbflush.h> 27 28 #include "internal.h" 29 #include "swap.h" 30 31 struct follow_page_context { 32 struct dev_pagemap *pgmap; 33 unsigned int page_mask; 34 }; 35 36 static inline void sanity_check_pinned_pages(struct page **pages, 37 unsigned long npages) 38 { 39 if (!IS_ENABLED(CONFIG_DEBUG_VM)) 40 return; 41 42 /* 43 * We only pin anonymous pages if they are exclusive. Once pinned, we 44 * can no longer turn them possibly shared and PageAnonExclusive() will 45 * stick around until the page is freed. 46 * 47 * We'd like to verify that our pinned anonymous pages are still mapped 48 * exclusively. The issue with anon THP is that we don't know how 49 * they are/were mapped when pinning them. However, for anon 50 * THP we can assume that either the given page (PTE-mapped THP) or 51 * the head page (PMD-mapped THP) should be PageAnonExclusive(). If 52 * neither is the case, there is certainly something wrong. 53 */ 54 for (; npages; npages--, pages++) { 55 struct page *page = *pages; 56 struct folio *folio; 57 58 if (!page) 59 continue; 60 61 folio = page_folio(page); 62 63 if (is_zero_page(page) || 64 !folio_test_anon(folio)) 65 continue; 66 if (!folio_test_large(folio) || folio_test_hugetlb(folio)) 67 VM_WARN_ON_ONCE_FOLIO(!PageAnonExclusive(&folio->page), folio); 68 else 69 /* Either a PTE-mapped or a PMD-mapped THP. */ 70 VM_WARN_ON_ONCE_PAGE(!PageAnonExclusive(&folio->page) && 71 !PageAnonExclusive(page), page); 72 } 73 } 74 75 /* 76 * Return the folio with ref appropriately incremented, 77 * or NULL if that failed. 78 */ 79 static inline struct folio *try_get_folio(struct page *page, int refs) 80 { 81 struct folio *folio; 82 83 retry: 84 folio = page_folio(page); 85 if (WARN_ON_ONCE(folio_ref_count(folio) < 0)) 86 return NULL; 87 if (unlikely(!folio_ref_try_add(folio, refs))) 88 return NULL; 89 90 /* 91 * At this point we have a stable reference to the folio; but it 92 * could be that between calling page_folio() and the refcount 93 * increment, the folio was split, in which case we'd end up 94 * holding a reference on a folio that has nothing to do with the page 95 * we were given anymore. 96 * So now that the folio is stable, recheck that the page still 97 * belongs to this folio. 98 */ 99 if (unlikely(page_folio(page) != folio)) { 100 folio_put_refs(folio, refs); 101 goto retry; 102 } 103 104 return folio; 105 } 106 107 static void gup_put_folio(struct folio *folio, int refs, unsigned int flags) 108 { 109 if (flags & FOLL_PIN) { 110 if (is_zero_folio(folio)) 111 return; 112 node_stat_mod_folio(folio, NR_FOLL_PIN_RELEASED, refs); 113 if (folio_has_pincount(folio)) 114 atomic_sub(refs, &folio->_pincount); 115 else 116 refs *= GUP_PIN_COUNTING_BIAS; 117 } 118 119 folio_put_refs(folio, refs); 120 } 121 122 /** 123 * try_grab_folio() - add a folio's refcount by a flag-dependent amount 124 * @folio: pointer to folio to be grabbed 125 * @refs: the value to (effectively) add to the folio's refcount 126 * @flags: gup flags: these are the FOLL_* flag values 127 * 128 * This might not do anything at all, depending on the flags argument. 129 * 130 * "grab" names in this file mean, "look at flags to decide whether to use 131 * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount. 132 * 133 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same 134 * time. 135 * 136 * Return: 0 for success, or if no action was required (if neither FOLL_PIN 137 * nor FOLL_GET was set, nothing is done). A negative error code for failure: 138 * 139 * -ENOMEM FOLL_GET or FOLL_PIN was set, but the folio could not 140 * be grabbed. 141 * 142 * It is called when we have a stable reference for the folio, typically in 143 * GUP slow path. 144 */ 145 int __must_check try_grab_folio(struct folio *folio, int refs, 146 unsigned int flags) 147 { 148 if (WARN_ON_ONCE(folio_ref_count(folio) <= 0)) 149 return -ENOMEM; 150 151 if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(&folio->page))) 152 return -EREMOTEIO; 153 154 if (flags & FOLL_GET) 155 folio_ref_add(folio, refs); 156 else if (flags & FOLL_PIN) { 157 /* 158 * Don't take a pin on the zero page - it's not going anywhere 159 * and it is used in a *lot* of places. 160 */ 161 if (is_zero_folio(folio)) 162 return 0; 163 164 /* 165 * Increment the normal page refcount field at least once, 166 * so that the page really is pinned. 167 */ 168 if (folio_has_pincount(folio)) { 169 folio_ref_add(folio, refs); 170 atomic_add(refs, &folio->_pincount); 171 } else { 172 folio_ref_add(folio, refs * GUP_PIN_COUNTING_BIAS); 173 } 174 175 node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs); 176 } 177 178 return 0; 179 } 180 181 /** 182 * unpin_user_page() - release a dma-pinned page 183 * @page: pointer to page to be released 184 * 185 * Pages that were pinned via pin_user_pages*() must be released via either 186 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so 187 * that such pages can be separately tracked and uniquely handled. In 188 * particular, interactions with RDMA and filesystems need special handling. 189 */ 190 void unpin_user_page(struct page *page) 191 { 192 sanity_check_pinned_pages(&page, 1); 193 gup_put_folio(page_folio(page), 1, FOLL_PIN); 194 } 195 EXPORT_SYMBOL(unpin_user_page); 196 197 /** 198 * unpin_folio() - release a dma-pinned folio 199 * @folio: pointer to folio to be released 200 * 201 * Folios that were pinned via memfd_pin_folios() or other similar routines 202 * must be released either using unpin_folio() or unpin_folios(). 203 */ 204 void unpin_folio(struct folio *folio) 205 { 206 gup_put_folio(folio, 1, FOLL_PIN); 207 } 208 EXPORT_SYMBOL_GPL(unpin_folio); 209 210 /** 211 * folio_add_pin - Try to get an additional pin on a pinned folio 212 * @folio: The folio to be pinned 213 * 214 * Get an additional pin on a folio we already have a pin on. Makes no change 215 * if the folio is a zero_page. 216 */ 217 void folio_add_pin(struct folio *folio) 218 { 219 if (is_zero_folio(folio)) 220 return; 221 222 /* 223 * Similar to try_grab_folio(): be sure to *also* increment the normal 224 * page refcount field at least once, so that the page really is 225 * pinned. 226 */ 227 if (folio_has_pincount(folio)) { 228 WARN_ON_ONCE(atomic_read(&folio->_pincount) < 1); 229 folio_ref_inc(folio); 230 atomic_inc(&folio->_pincount); 231 } else { 232 WARN_ON_ONCE(folio_ref_count(folio) < GUP_PIN_COUNTING_BIAS); 233 folio_ref_add(folio, GUP_PIN_COUNTING_BIAS); 234 } 235 } 236 237 static inline struct folio *gup_folio_range_next(struct page *start, 238 unsigned long npages, unsigned long i, unsigned int *ntails) 239 { 240 struct page *next = nth_page(start, i); 241 struct folio *folio = page_folio(next); 242 unsigned int nr = 1; 243 244 if (folio_test_large(folio)) 245 nr = min_t(unsigned int, npages - i, 246 folio_nr_pages(folio) - folio_page_idx(folio, next)); 247 248 *ntails = nr; 249 return folio; 250 } 251 252 static inline struct folio *gup_folio_next(struct page **list, 253 unsigned long npages, unsigned long i, unsigned int *ntails) 254 { 255 struct folio *folio = page_folio(list[i]); 256 unsigned int nr; 257 258 for (nr = i + 1; nr < npages; nr++) { 259 if (page_folio(list[nr]) != folio) 260 break; 261 } 262 263 *ntails = nr - i; 264 return folio; 265 } 266 267 /** 268 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages 269 * @pages: array of pages to be maybe marked dirty, and definitely released. 270 * @npages: number of pages in the @pages array. 271 * @make_dirty: whether to mark the pages dirty 272 * 273 * "gup-pinned page" refers to a page that has had one of the get_user_pages() 274 * variants called on that page. 275 * 276 * For each page in the @pages array, make that page (or its head page, if a 277 * compound page) dirty, if @make_dirty is true, and if the page was previously 278 * listed as clean. In any case, releases all pages using unpin_user_page(), 279 * possibly via unpin_user_pages(), for the non-dirty case. 280 * 281 * Please see the unpin_user_page() documentation for details. 282 * 283 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is 284 * required, then the caller should a) verify that this is really correct, 285 * because _lock() is usually required, and b) hand code it: 286 * set_page_dirty_lock(), unpin_user_page(). 287 * 288 */ 289 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages, 290 bool make_dirty) 291 { 292 unsigned long i; 293 struct folio *folio; 294 unsigned int nr; 295 296 if (!make_dirty) { 297 unpin_user_pages(pages, npages); 298 return; 299 } 300 301 sanity_check_pinned_pages(pages, npages); 302 for (i = 0; i < npages; i += nr) { 303 folio = gup_folio_next(pages, npages, i, &nr); 304 /* 305 * Checking PageDirty at this point may race with 306 * clear_page_dirty_for_io(), but that's OK. Two key 307 * cases: 308 * 309 * 1) This code sees the page as already dirty, so it 310 * skips the call to set_page_dirty(). That could happen 311 * because clear_page_dirty_for_io() called 312 * folio_mkclean(), followed by set_page_dirty(). 313 * However, now the page is going to get written back, 314 * which meets the original intention of setting it 315 * dirty, so all is well: clear_page_dirty_for_io() goes 316 * on to call TestClearPageDirty(), and write the page 317 * back. 318 * 319 * 2) This code sees the page as clean, so it calls 320 * set_page_dirty(). The page stays dirty, despite being 321 * written back, so it gets written back again in the 322 * next writeback cycle. This is harmless. 323 */ 324 if (!folio_test_dirty(folio)) { 325 folio_lock(folio); 326 folio_mark_dirty(folio); 327 folio_unlock(folio); 328 } 329 gup_put_folio(folio, nr, FOLL_PIN); 330 } 331 } 332 EXPORT_SYMBOL(unpin_user_pages_dirty_lock); 333 334 /** 335 * unpin_user_page_range_dirty_lock() - release and optionally dirty 336 * gup-pinned page range 337 * 338 * @page: the starting page of a range maybe marked dirty, and definitely released. 339 * @npages: number of consecutive pages to release. 340 * @make_dirty: whether to mark the pages dirty 341 * 342 * "gup-pinned page range" refers to a range of pages that has had one of the 343 * pin_user_pages() variants called on that page. 344 * 345 * For the page ranges defined by [page .. page+npages], make that range (or 346 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the 347 * page range was previously listed as clean. 348 * 349 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is 350 * required, then the caller should a) verify that this is really correct, 351 * because _lock() is usually required, and b) hand code it: 352 * set_page_dirty_lock(), unpin_user_page(). 353 * 354 */ 355 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages, 356 bool make_dirty) 357 { 358 unsigned long i; 359 struct folio *folio; 360 unsigned int nr; 361 362 for (i = 0; i < npages; i += nr) { 363 folio = gup_folio_range_next(page, npages, i, &nr); 364 if (make_dirty && !folio_test_dirty(folio)) { 365 folio_lock(folio); 366 folio_mark_dirty(folio); 367 folio_unlock(folio); 368 } 369 gup_put_folio(folio, nr, FOLL_PIN); 370 } 371 } 372 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock); 373 374 static void gup_fast_unpin_user_pages(struct page **pages, unsigned long npages) 375 { 376 unsigned long i; 377 struct folio *folio; 378 unsigned int nr; 379 380 /* 381 * Don't perform any sanity checks because we might have raced with 382 * fork() and some anonymous pages might now actually be shared -- 383 * which is why we're unpinning after all. 384 */ 385 for (i = 0; i < npages; i += nr) { 386 folio = gup_folio_next(pages, npages, i, &nr); 387 gup_put_folio(folio, nr, FOLL_PIN); 388 } 389 } 390 391 /** 392 * unpin_user_pages() - release an array of gup-pinned pages. 393 * @pages: array of pages to be marked dirty and released. 394 * @npages: number of pages in the @pages array. 395 * 396 * For each page in the @pages array, release the page using unpin_user_page(). 397 * 398 * Please see the unpin_user_page() documentation for details. 399 */ 400 void unpin_user_pages(struct page **pages, unsigned long npages) 401 { 402 unsigned long i; 403 struct folio *folio; 404 unsigned int nr; 405 406 /* 407 * If this WARN_ON() fires, then the system *might* be leaking pages (by 408 * leaving them pinned), but probably not. More likely, gup/pup returned 409 * a hard -ERRNO error to the caller, who erroneously passed it here. 410 */ 411 if (WARN_ON(IS_ERR_VALUE(npages))) 412 return; 413 414 sanity_check_pinned_pages(pages, npages); 415 for (i = 0; i < npages; i += nr) { 416 if (!pages[i]) { 417 nr = 1; 418 continue; 419 } 420 folio = gup_folio_next(pages, npages, i, &nr); 421 gup_put_folio(folio, nr, FOLL_PIN); 422 } 423 } 424 EXPORT_SYMBOL(unpin_user_pages); 425 426 /** 427 * unpin_user_folio() - release pages of a folio 428 * @folio: pointer to folio to be released 429 * @npages: number of pages of same folio 430 * 431 * Release npages of the folio 432 */ 433 void unpin_user_folio(struct folio *folio, unsigned long npages) 434 { 435 gup_put_folio(folio, npages, FOLL_PIN); 436 } 437 EXPORT_SYMBOL(unpin_user_folio); 438 439 /** 440 * unpin_folios() - release an array of gup-pinned folios. 441 * @folios: array of folios to be marked dirty and released. 442 * @nfolios: number of folios in the @folios array. 443 * 444 * For each folio in the @folios array, release the folio using gup_put_folio. 445 * 446 * Please see the unpin_folio() documentation for details. 447 */ 448 void unpin_folios(struct folio **folios, unsigned long nfolios) 449 { 450 unsigned long i = 0, j; 451 452 /* 453 * If this WARN_ON() fires, then the system *might* be leaking folios 454 * (by leaving them pinned), but probably not. More likely, gup/pup 455 * returned a hard -ERRNO error to the caller, who erroneously passed 456 * it here. 457 */ 458 if (WARN_ON(IS_ERR_VALUE(nfolios))) 459 return; 460 461 while (i < nfolios) { 462 for (j = i + 1; j < nfolios; j++) 463 if (folios[i] != folios[j]) 464 break; 465 466 if (folios[i]) 467 gup_put_folio(folios[i], j - i, FOLL_PIN); 468 i = j; 469 } 470 } 471 EXPORT_SYMBOL_GPL(unpin_folios); 472 473 /* 474 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's 475 * lifecycle. Avoid setting the bit unless necessary, or it might cause write 476 * cache bouncing on large SMP machines for concurrent pinned gups. 477 */ 478 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags) 479 { 480 if (!test_bit(MMF_HAS_PINNED, mm_flags)) 481 set_bit(MMF_HAS_PINNED, mm_flags); 482 } 483 484 #ifdef CONFIG_MMU 485 486 #ifdef CONFIG_HAVE_GUP_FAST 487 static int record_subpages(struct page *page, unsigned long sz, 488 unsigned long addr, unsigned long end, 489 struct page **pages) 490 { 491 struct page *start_page; 492 int nr; 493 494 start_page = nth_page(page, (addr & (sz - 1)) >> PAGE_SHIFT); 495 for (nr = 0; addr != end; nr++, addr += PAGE_SIZE) 496 pages[nr] = nth_page(start_page, nr); 497 498 return nr; 499 } 500 501 /** 502 * try_grab_folio_fast() - Attempt to get or pin a folio in fast path. 503 * @page: pointer to page to be grabbed 504 * @refs: the value to (effectively) add to the folio's refcount 505 * @flags: gup flags: these are the FOLL_* flag values. 506 * 507 * "grab" names in this file mean, "look at flags to decide whether to use 508 * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount. 509 * 510 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the 511 * same time. (That's true throughout the get_user_pages*() and 512 * pin_user_pages*() APIs.) Cases: 513 * 514 * FOLL_GET: folio's refcount will be incremented by @refs. 515 * 516 * FOLL_PIN on large folios: folio's refcount will be incremented by 517 * @refs, and its pincount will be incremented by @refs. 518 * 519 * FOLL_PIN on single-page folios: folio's refcount will be incremented by 520 * @refs * GUP_PIN_COUNTING_BIAS. 521 * 522 * Return: The folio containing @page (with refcount appropriately 523 * incremented) for success, or NULL upon failure. If neither FOLL_GET 524 * nor FOLL_PIN was set, that's considered failure, and furthermore, 525 * a likely bug in the caller, so a warning is also emitted. 526 * 527 * It uses add ref unless zero to elevate the folio refcount and must be called 528 * in fast path only. 529 */ 530 static struct folio *try_grab_folio_fast(struct page *page, int refs, 531 unsigned int flags) 532 { 533 struct folio *folio; 534 535 /* Raise warn if it is not called in fast GUP */ 536 VM_WARN_ON_ONCE(!irqs_disabled()); 537 538 if (WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == 0)) 539 return NULL; 540 541 if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page))) 542 return NULL; 543 544 if (flags & FOLL_GET) 545 return try_get_folio(page, refs); 546 547 /* FOLL_PIN is set */ 548 549 /* 550 * Don't take a pin on the zero page - it's not going anywhere 551 * and it is used in a *lot* of places. 552 */ 553 if (is_zero_page(page)) 554 return page_folio(page); 555 556 folio = try_get_folio(page, refs); 557 if (!folio) 558 return NULL; 559 560 /* 561 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a 562 * right zone, so fail and let the caller fall back to the slow 563 * path. 564 */ 565 if (unlikely((flags & FOLL_LONGTERM) && 566 !folio_is_longterm_pinnable(folio))) { 567 folio_put_refs(folio, refs); 568 return NULL; 569 } 570 571 /* 572 * When pinning a large folio, use an exact count to track it. 573 * 574 * However, be sure to *also* increment the normal folio 575 * refcount field at least once, so that the folio really 576 * is pinned. That's why the refcount from the earlier 577 * try_get_folio() is left intact. 578 */ 579 if (folio_has_pincount(folio)) 580 atomic_add(refs, &folio->_pincount); 581 else 582 folio_ref_add(folio, 583 refs * (GUP_PIN_COUNTING_BIAS - 1)); 584 /* 585 * Adjust the pincount before re-checking the PTE for changes. 586 * This is essentially a smp_mb() and is paired with a memory 587 * barrier in folio_try_share_anon_rmap_*(). 588 */ 589 smp_mb__after_atomic(); 590 591 node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs); 592 593 return folio; 594 } 595 #endif /* CONFIG_HAVE_GUP_FAST */ 596 597 /* Common code for can_follow_write_* */ 598 static inline bool can_follow_write_common(struct page *page, 599 struct vm_area_struct *vma, unsigned int flags) 600 { 601 /* Maybe FOLL_FORCE is set to override it? */ 602 if (!(flags & FOLL_FORCE)) 603 return false; 604 605 /* But FOLL_FORCE has no effect on shared mappings */ 606 if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED)) 607 return false; 608 609 /* ... or read-only private ones */ 610 if (!(vma->vm_flags & VM_MAYWRITE)) 611 return false; 612 613 /* ... or already writable ones that just need to take a write fault */ 614 if (vma->vm_flags & VM_WRITE) 615 return false; 616 617 /* 618 * See can_change_pte_writable(): we broke COW and could map the page 619 * writable if we have an exclusive anonymous page ... 620 */ 621 return page && PageAnon(page) && PageAnonExclusive(page); 622 } 623 624 static struct page *no_page_table(struct vm_area_struct *vma, 625 unsigned int flags, unsigned long address) 626 { 627 if (!(flags & FOLL_DUMP)) 628 return NULL; 629 630 /* 631 * When core dumping, we don't want to allocate unnecessary pages or 632 * page tables. Return error instead of NULL to skip handle_mm_fault, 633 * then get_dump_page() will return NULL to leave a hole in the dump. 634 * But we can only make this optimization where a hole would surely 635 * be zero-filled if handle_mm_fault() actually did handle it. 636 */ 637 if (is_vm_hugetlb_page(vma)) { 638 struct hstate *h = hstate_vma(vma); 639 640 if (!hugetlbfs_pagecache_present(h, vma, address)) 641 return ERR_PTR(-EFAULT); 642 } else if ((vma_is_anonymous(vma) || !vma->vm_ops->fault)) { 643 return ERR_PTR(-EFAULT); 644 } 645 646 return NULL; 647 } 648 649 #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES 650 /* FOLL_FORCE can write to even unwritable PUDs in COW mappings. */ 651 static inline bool can_follow_write_pud(pud_t pud, struct page *page, 652 struct vm_area_struct *vma, 653 unsigned int flags) 654 { 655 /* If the pud is writable, we can write to the page. */ 656 if (pud_write(pud)) 657 return true; 658 659 return can_follow_write_common(page, vma, flags); 660 } 661 662 static struct page *follow_huge_pud(struct vm_area_struct *vma, 663 unsigned long addr, pud_t *pudp, 664 int flags, struct follow_page_context *ctx) 665 { 666 struct mm_struct *mm = vma->vm_mm; 667 struct page *page; 668 pud_t pud = *pudp; 669 unsigned long pfn = pud_pfn(pud); 670 int ret; 671 672 assert_spin_locked(pud_lockptr(mm, pudp)); 673 674 if (!pud_present(pud)) 675 return NULL; 676 677 if ((flags & FOLL_WRITE) && 678 !can_follow_write_pud(pud, pfn_to_page(pfn), vma, flags)) 679 return NULL; 680 681 pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT; 682 683 if (IS_ENABLED(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) && 684 pud_devmap(pud)) { 685 /* 686 * device mapped pages can only be returned if the caller 687 * will manage the page reference count. 688 * 689 * At least one of FOLL_GET | FOLL_PIN must be set, so 690 * assert that here: 691 */ 692 if (!(flags & (FOLL_GET | FOLL_PIN))) 693 return ERR_PTR(-EEXIST); 694 695 if (flags & FOLL_TOUCH) 696 touch_pud(vma, addr, pudp, flags & FOLL_WRITE); 697 698 ctx->pgmap = get_dev_pagemap(pfn, ctx->pgmap); 699 if (!ctx->pgmap) 700 return ERR_PTR(-EFAULT); 701 } 702 703 page = pfn_to_page(pfn); 704 705 if (!pud_devmap(pud) && !pud_write(pud) && 706 gup_must_unshare(vma, flags, page)) 707 return ERR_PTR(-EMLINK); 708 709 ret = try_grab_folio(page_folio(page), 1, flags); 710 if (ret) 711 page = ERR_PTR(ret); 712 else 713 ctx->page_mask = HPAGE_PUD_NR - 1; 714 715 return page; 716 } 717 718 /* FOLL_FORCE can write to even unwritable PMDs in COW mappings. */ 719 static inline bool can_follow_write_pmd(pmd_t pmd, struct page *page, 720 struct vm_area_struct *vma, 721 unsigned int flags) 722 { 723 /* If the pmd is writable, we can write to the page. */ 724 if (pmd_write(pmd)) 725 return true; 726 727 if (!can_follow_write_common(page, vma, flags)) 728 return false; 729 730 /* ... and a write-fault isn't required for other reasons. */ 731 if (pmd_needs_soft_dirty_wp(vma, pmd)) 732 return false; 733 return !userfaultfd_huge_pmd_wp(vma, pmd); 734 } 735 736 static struct page *follow_huge_pmd(struct vm_area_struct *vma, 737 unsigned long addr, pmd_t *pmd, 738 unsigned int flags, 739 struct follow_page_context *ctx) 740 { 741 struct mm_struct *mm = vma->vm_mm; 742 pmd_t pmdval = *pmd; 743 struct page *page; 744 int ret; 745 746 assert_spin_locked(pmd_lockptr(mm, pmd)); 747 748 page = pmd_page(pmdval); 749 if ((flags & FOLL_WRITE) && 750 !can_follow_write_pmd(pmdval, page, vma, flags)) 751 return NULL; 752 753 /* Avoid dumping huge zero page */ 754 if ((flags & FOLL_DUMP) && is_huge_zero_pmd(pmdval)) 755 return ERR_PTR(-EFAULT); 756 757 if (pmd_protnone(*pmd) && !gup_can_follow_protnone(vma, flags)) 758 return NULL; 759 760 if (!pmd_write(pmdval) && gup_must_unshare(vma, flags, page)) 761 return ERR_PTR(-EMLINK); 762 763 VM_WARN_ON_ONCE_PAGE((flags & FOLL_PIN) && PageAnon(page) && 764 !PageAnonExclusive(page), page); 765 766 ret = try_grab_folio(page_folio(page), 1, flags); 767 if (ret) 768 return ERR_PTR(ret); 769 770 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 771 if (pmd_trans_huge(pmdval) && (flags & FOLL_TOUCH)) 772 touch_pmd(vma, addr, pmd, flags & FOLL_WRITE); 773 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 774 775 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT; 776 ctx->page_mask = HPAGE_PMD_NR - 1; 777 778 return page; 779 } 780 781 #else /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */ 782 static struct page *follow_huge_pud(struct vm_area_struct *vma, 783 unsigned long addr, pud_t *pudp, 784 int flags, struct follow_page_context *ctx) 785 { 786 return NULL; 787 } 788 789 static struct page *follow_huge_pmd(struct vm_area_struct *vma, 790 unsigned long addr, pmd_t *pmd, 791 unsigned int flags, 792 struct follow_page_context *ctx) 793 { 794 return NULL; 795 } 796 #endif /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */ 797 798 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address, 799 pte_t *pte, unsigned int flags) 800 { 801 if (flags & FOLL_TOUCH) { 802 pte_t orig_entry = ptep_get(pte); 803 pte_t entry = orig_entry; 804 805 if (flags & FOLL_WRITE) 806 entry = pte_mkdirty(entry); 807 entry = pte_mkyoung(entry); 808 809 if (!pte_same(orig_entry, entry)) { 810 set_pte_at(vma->vm_mm, address, pte, entry); 811 update_mmu_cache(vma, address, pte); 812 } 813 } 814 815 /* Proper page table entry exists, but no corresponding struct page */ 816 return -EEXIST; 817 } 818 819 /* FOLL_FORCE can write to even unwritable PTEs in COW mappings. */ 820 static inline bool can_follow_write_pte(pte_t pte, struct page *page, 821 struct vm_area_struct *vma, 822 unsigned int flags) 823 { 824 /* If the pte is writable, we can write to the page. */ 825 if (pte_write(pte)) 826 return true; 827 828 if (!can_follow_write_common(page, vma, flags)) 829 return false; 830 831 /* ... and a write-fault isn't required for other reasons. */ 832 if (pte_needs_soft_dirty_wp(vma, pte)) 833 return false; 834 return !userfaultfd_pte_wp(vma, pte); 835 } 836 837 static struct page *follow_page_pte(struct vm_area_struct *vma, 838 unsigned long address, pmd_t *pmd, unsigned int flags, 839 struct dev_pagemap **pgmap) 840 { 841 struct mm_struct *mm = vma->vm_mm; 842 struct folio *folio; 843 struct page *page; 844 spinlock_t *ptl; 845 pte_t *ptep, pte; 846 int ret; 847 848 ptep = pte_offset_map_lock(mm, pmd, address, &ptl); 849 if (!ptep) 850 return no_page_table(vma, flags, address); 851 pte = ptep_get(ptep); 852 if (!pte_present(pte)) 853 goto no_page; 854 if (pte_protnone(pte) && !gup_can_follow_protnone(vma, flags)) 855 goto no_page; 856 857 page = vm_normal_page(vma, address, pte); 858 859 /* 860 * We only care about anon pages in can_follow_write_pte() and don't 861 * have to worry about pte_devmap() because they are never anon. 862 */ 863 if ((flags & FOLL_WRITE) && 864 !can_follow_write_pte(pte, page, vma, flags)) { 865 page = NULL; 866 goto out; 867 } 868 869 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) { 870 /* 871 * Only return device mapping pages in the FOLL_GET or FOLL_PIN 872 * case since they are only valid while holding the pgmap 873 * reference. 874 */ 875 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap); 876 if (*pgmap) 877 page = pte_page(pte); 878 else 879 goto no_page; 880 } else if (unlikely(!page)) { 881 if (flags & FOLL_DUMP) { 882 /* Avoid special (like zero) pages in core dumps */ 883 page = ERR_PTR(-EFAULT); 884 goto out; 885 } 886 887 if (is_zero_pfn(pte_pfn(pte))) { 888 page = pte_page(pte); 889 } else { 890 ret = follow_pfn_pte(vma, address, ptep, flags); 891 page = ERR_PTR(ret); 892 goto out; 893 } 894 } 895 folio = page_folio(page); 896 897 if (!pte_write(pte) && gup_must_unshare(vma, flags, page)) { 898 page = ERR_PTR(-EMLINK); 899 goto out; 900 } 901 902 VM_WARN_ON_ONCE_PAGE((flags & FOLL_PIN) && PageAnon(page) && 903 !PageAnonExclusive(page), page); 904 905 /* try_grab_folio() does nothing unless FOLL_GET or FOLL_PIN is set. */ 906 ret = try_grab_folio(folio, 1, flags); 907 if (unlikely(ret)) { 908 page = ERR_PTR(ret); 909 goto out; 910 } 911 912 /* 913 * We need to make the page accessible if and only if we are going 914 * to access its content (the FOLL_PIN case). Please see 915 * Documentation/core-api/pin_user_pages.rst for details. 916 */ 917 if (flags & FOLL_PIN) { 918 ret = arch_make_folio_accessible(folio); 919 if (ret) { 920 unpin_user_page(page); 921 page = ERR_PTR(ret); 922 goto out; 923 } 924 } 925 if (flags & FOLL_TOUCH) { 926 if ((flags & FOLL_WRITE) && 927 !pte_dirty(pte) && !folio_test_dirty(folio)) 928 folio_mark_dirty(folio); 929 /* 930 * pte_mkyoung() would be more correct here, but atomic care 931 * is needed to avoid losing the dirty bit: it is easier to use 932 * folio_mark_accessed(). 933 */ 934 folio_mark_accessed(folio); 935 } 936 out: 937 pte_unmap_unlock(ptep, ptl); 938 return page; 939 no_page: 940 pte_unmap_unlock(ptep, ptl); 941 if (!pte_none(pte)) 942 return NULL; 943 return no_page_table(vma, flags, address); 944 } 945 946 static struct page *follow_pmd_mask(struct vm_area_struct *vma, 947 unsigned long address, pud_t *pudp, 948 unsigned int flags, 949 struct follow_page_context *ctx) 950 { 951 pmd_t *pmd, pmdval; 952 spinlock_t *ptl; 953 struct page *page; 954 struct mm_struct *mm = vma->vm_mm; 955 956 pmd = pmd_offset(pudp, address); 957 pmdval = pmdp_get_lockless(pmd); 958 if (pmd_none(pmdval)) 959 return no_page_table(vma, flags, address); 960 if (!pmd_present(pmdval)) 961 return no_page_table(vma, flags, address); 962 if (pmd_devmap(pmdval)) { 963 ptl = pmd_lock(mm, pmd); 964 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap); 965 spin_unlock(ptl); 966 if (page) 967 return page; 968 return no_page_table(vma, flags, address); 969 } 970 if (likely(!pmd_leaf(pmdval))) 971 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); 972 973 if (pmd_protnone(pmdval) && !gup_can_follow_protnone(vma, flags)) 974 return no_page_table(vma, flags, address); 975 976 ptl = pmd_lock(mm, pmd); 977 pmdval = *pmd; 978 if (unlikely(!pmd_present(pmdval))) { 979 spin_unlock(ptl); 980 return no_page_table(vma, flags, address); 981 } 982 if (unlikely(!pmd_leaf(pmdval))) { 983 spin_unlock(ptl); 984 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); 985 } 986 if (pmd_trans_huge(pmdval) && (flags & FOLL_SPLIT_PMD)) { 987 spin_unlock(ptl); 988 split_huge_pmd(vma, pmd, address); 989 /* If pmd was left empty, stuff a page table in there quickly */ 990 return pte_alloc(mm, pmd) ? ERR_PTR(-ENOMEM) : 991 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); 992 } 993 page = follow_huge_pmd(vma, address, pmd, flags, ctx); 994 spin_unlock(ptl); 995 return page; 996 } 997 998 static struct page *follow_pud_mask(struct vm_area_struct *vma, 999 unsigned long address, p4d_t *p4dp, 1000 unsigned int flags, 1001 struct follow_page_context *ctx) 1002 { 1003 pud_t *pudp, pud; 1004 spinlock_t *ptl; 1005 struct page *page; 1006 struct mm_struct *mm = vma->vm_mm; 1007 1008 pudp = pud_offset(p4dp, address); 1009 pud = READ_ONCE(*pudp); 1010 if (!pud_present(pud)) 1011 return no_page_table(vma, flags, address); 1012 if (pud_leaf(pud)) { 1013 ptl = pud_lock(mm, pudp); 1014 page = follow_huge_pud(vma, address, pudp, flags, ctx); 1015 spin_unlock(ptl); 1016 if (page) 1017 return page; 1018 return no_page_table(vma, flags, address); 1019 } 1020 if (unlikely(pud_bad(pud))) 1021 return no_page_table(vma, flags, address); 1022 1023 return follow_pmd_mask(vma, address, pudp, flags, ctx); 1024 } 1025 1026 static struct page *follow_p4d_mask(struct vm_area_struct *vma, 1027 unsigned long address, pgd_t *pgdp, 1028 unsigned int flags, 1029 struct follow_page_context *ctx) 1030 { 1031 p4d_t *p4dp, p4d; 1032 1033 p4dp = p4d_offset(pgdp, address); 1034 p4d = READ_ONCE(*p4dp); 1035 BUILD_BUG_ON(p4d_leaf(p4d)); 1036 1037 if (!p4d_present(p4d) || p4d_bad(p4d)) 1038 return no_page_table(vma, flags, address); 1039 1040 return follow_pud_mask(vma, address, p4dp, flags, ctx); 1041 } 1042 1043 /** 1044 * follow_page_mask - look up a page descriptor from a user-virtual address 1045 * @vma: vm_area_struct mapping @address 1046 * @address: virtual address to look up 1047 * @flags: flags modifying lookup behaviour 1048 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a 1049 * pointer to output page_mask 1050 * 1051 * @flags can have FOLL_ flags set, defined in <linux/mm.h> 1052 * 1053 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches 1054 * the device's dev_pagemap metadata to avoid repeating expensive lookups. 1055 * 1056 * When getting an anonymous page and the caller has to trigger unsharing 1057 * of a shared anonymous page first, -EMLINK is returned. The caller should 1058 * trigger a fault with FAULT_FLAG_UNSHARE set. Note that unsharing is only 1059 * relevant with FOLL_PIN and !FOLL_WRITE. 1060 * 1061 * On output, the @ctx->page_mask is set according to the size of the page. 1062 * 1063 * Return: the mapped (struct page *), %NULL if no mapping exists, or 1064 * an error pointer if there is a mapping to something not represented 1065 * by a page descriptor (see also vm_normal_page()). 1066 */ 1067 static struct page *follow_page_mask(struct vm_area_struct *vma, 1068 unsigned long address, unsigned int flags, 1069 struct follow_page_context *ctx) 1070 { 1071 pgd_t *pgd; 1072 struct mm_struct *mm = vma->vm_mm; 1073 struct page *page; 1074 1075 vma_pgtable_walk_begin(vma); 1076 1077 ctx->page_mask = 0; 1078 pgd = pgd_offset(mm, address); 1079 1080 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) 1081 page = no_page_table(vma, flags, address); 1082 else 1083 page = follow_p4d_mask(vma, address, pgd, flags, ctx); 1084 1085 vma_pgtable_walk_end(vma); 1086 1087 return page; 1088 } 1089 1090 static int get_gate_page(struct mm_struct *mm, unsigned long address, 1091 unsigned int gup_flags, struct vm_area_struct **vma, 1092 struct page **page) 1093 { 1094 pgd_t *pgd; 1095 p4d_t *p4d; 1096 pud_t *pud; 1097 pmd_t *pmd; 1098 pte_t *pte; 1099 pte_t entry; 1100 int ret = -EFAULT; 1101 1102 /* user gate pages are read-only */ 1103 if (gup_flags & FOLL_WRITE) 1104 return -EFAULT; 1105 pgd = pgd_offset(mm, address); 1106 if (pgd_none(*pgd)) 1107 return -EFAULT; 1108 p4d = p4d_offset(pgd, address); 1109 if (p4d_none(*p4d)) 1110 return -EFAULT; 1111 pud = pud_offset(p4d, address); 1112 if (pud_none(*pud)) 1113 return -EFAULT; 1114 pmd = pmd_offset(pud, address); 1115 if (!pmd_present(*pmd)) 1116 return -EFAULT; 1117 pte = pte_offset_map(pmd, address); 1118 if (!pte) 1119 return -EFAULT; 1120 entry = ptep_get(pte); 1121 if (pte_none(entry)) 1122 goto unmap; 1123 *vma = get_gate_vma(mm); 1124 if (!page) 1125 goto out; 1126 *page = vm_normal_page(*vma, address, entry); 1127 if (!*page) { 1128 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(entry))) 1129 goto unmap; 1130 *page = pte_page(entry); 1131 } 1132 ret = try_grab_folio(page_folio(*page), 1, gup_flags); 1133 if (unlikely(ret)) 1134 goto unmap; 1135 out: 1136 ret = 0; 1137 unmap: 1138 pte_unmap(pte); 1139 return ret; 1140 } 1141 1142 /* 1143 * mmap_lock must be held on entry. If @flags has FOLL_UNLOCKABLE but not 1144 * FOLL_NOWAIT, the mmap_lock may be released. If it is, *@locked will be set 1145 * to 0 and -EBUSY returned. 1146 */ 1147 static int faultin_page(struct vm_area_struct *vma, 1148 unsigned long address, unsigned int flags, bool unshare, 1149 int *locked) 1150 { 1151 unsigned int fault_flags = 0; 1152 vm_fault_t ret; 1153 1154 if (flags & FOLL_NOFAULT) 1155 return -EFAULT; 1156 if (flags & FOLL_WRITE) 1157 fault_flags |= FAULT_FLAG_WRITE; 1158 if (flags & FOLL_REMOTE) 1159 fault_flags |= FAULT_FLAG_REMOTE; 1160 if (flags & FOLL_UNLOCKABLE) { 1161 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE; 1162 /* 1163 * FAULT_FLAG_INTERRUPTIBLE is opt-in. GUP callers must set 1164 * FOLL_INTERRUPTIBLE to enable FAULT_FLAG_INTERRUPTIBLE. 1165 * That's because some callers may not be prepared to 1166 * handle early exits caused by non-fatal signals. 1167 */ 1168 if (flags & FOLL_INTERRUPTIBLE) 1169 fault_flags |= FAULT_FLAG_INTERRUPTIBLE; 1170 } 1171 if (flags & FOLL_NOWAIT) 1172 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; 1173 if (flags & FOLL_TRIED) { 1174 /* 1175 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED 1176 * can co-exist 1177 */ 1178 fault_flags |= FAULT_FLAG_TRIED; 1179 } 1180 if (unshare) { 1181 fault_flags |= FAULT_FLAG_UNSHARE; 1182 /* FAULT_FLAG_WRITE and FAULT_FLAG_UNSHARE are incompatible */ 1183 VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_WRITE); 1184 } 1185 1186 ret = handle_mm_fault(vma, address, fault_flags, NULL); 1187 1188 if (ret & VM_FAULT_COMPLETED) { 1189 /* 1190 * With FAULT_FLAG_RETRY_NOWAIT we'll never release the 1191 * mmap lock in the page fault handler. Sanity check this. 1192 */ 1193 WARN_ON_ONCE(fault_flags & FAULT_FLAG_RETRY_NOWAIT); 1194 *locked = 0; 1195 1196 /* 1197 * We should do the same as VM_FAULT_RETRY, but let's not 1198 * return -EBUSY since that's not reflecting the reality of 1199 * what has happened - we've just fully completed a page 1200 * fault, with the mmap lock released. Use -EAGAIN to show 1201 * that we want to take the mmap lock _again_. 1202 */ 1203 return -EAGAIN; 1204 } 1205 1206 if (ret & VM_FAULT_ERROR) { 1207 int err = vm_fault_to_errno(ret, flags); 1208 1209 if (err) 1210 return err; 1211 BUG(); 1212 } 1213 1214 if (ret & VM_FAULT_RETRY) { 1215 if (!(fault_flags & FAULT_FLAG_RETRY_NOWAIT)) 1216 *locked = 0; 1217 return -EBUSY; 1218 } 1219 1220 return 0; 1221 } 1222 1223 /* 1224 * Writing to file-backed mappings which require folio dirty tracking using GUP 1225 * is a fundamentally broken operation, as kernel write access to GUP mappings 1226 * do not adhere to the semantics expected by a file system. 1227 * 1228 * Consider the following scenario:- 1229 * 1230 * 1. A folio is written to via GUP which write-faults the memory, notifying 1231 * the file system and dirtying the folio. 1232 * 2. Later, writeback is triggered, resulting in the folio being cleaned and 1233 * the PTE being marked read-only. 1234 * 3. The GUP caller writes to the folio, as it is mapped read/write via the 1235 * direct mapping. 1236 * 4. The GUP caller, now done with the page, unpins it and sets it dirty 1237 * (though it does not have to). 1238 * 1239 * This results in both data being written to a folio without writenotify, and 1240 * the folio being dirtied unexpectedly (if the caller decides to do so). 1241 */ 1242 static bool writable_file_mapping_allowed(struct vm_area_struct *vma, 1243 unsigned long gup_flags) 1244 { 1245 /* 1246 * If we aren't pinning then no problematic write can occur. A long term 1247 * pin is the most egregious case so this is the case we disallow. 1248 */ 1249 if ((gup_flags & (FOLL_PIN | FOLL_LONGTERM)) != 1250 (FOLL_PIN | FOLL_LONGTERM)) 1251 return true; 1252 1253 /* 1254 * If the VMA does not require dirty tracking then no problematic write 1255 * can occur either. 1256 */ 1257 return !vma_needs_dirty_tracking(vma); 1258 } 1259 1260 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags) 1261 { 1262 vm_flags_t vm_flags = vma->vm_flags; 1263 int write = (gup_flags & FOLL_WRITE); 1264 int foreign = (gup_flags & FOLL_REMOTE); 1265 bool vma_anon = vma_is_anonymous(vma); 1266 1267 if (vm_flags & (VM_IO | VM_PFNMAP)) 1268 return -EFAULT; 1269 1270 if ((gup_flags & FOLL_ANON) && !vma_anon) 1271 return -EFAULT; 1272 1273 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma)) 1274 return -EOPNOTSUPP; 1275 1276 if ((gup_flags & FOLL_SPLIT_PMD) && is_vm_hugetlb_page(vma)) 1277 return -EOPNOTSUPP; 1278 1279 if (vma_is_secretmem(vma)) 1280 return -EFAULT; 1281 1282 if (write) { 1283 if (!vma_anon && 1284 !writable_file_mapping_allowed(vma, gup_flags)) 1285 return -EFAULT; 1286 1287 if (!(vm_flags & VM_WRITE) || (vm_flags & VM_SHADOW_STACK)) { 1288 if (!(gup_flags & FOLL_FORCE)) 1289 return -EFAULT; 1290 /* 1291 * We used to let the write,force case do COW in a 1292 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could 1293 * set a breakpoint in a read-only mapping of an 1294 * executable, without corrupting the file (yet only 1295 * when that file had been opened for writing!). 1296 * Anon pages in shared mappings are surprising: now 1297 * just reject it. 1298 */ 1299 if (!is_cow_mapping(vm_flags)) 1300 return -EFAULT; 1301 } 1302 } else if (!(vm_flags & VM_READ)) { 1303 if (!(gup_flags & FOLL_FORCE)) 1304 return -EFAULT; 1305 /* 1306 * Is there actually any vma we can reach here which does not 1307 * have VM_MAYREAD set? 1308 */ 1309 if (!(vm_flags & VM_MAYREAD)) 1310 return -EFAULT; 1311 } 1312 /* 1313 * gups are always data accesses, not instruction 1314 * fetches, so execute=false here 1315 */ 1316 if (!arch_vma_access_permitted(vma, write, false, foreign)) 1317 return -EFAULT; 1318 return 0; 1319 } 1320 1321 /* 1322 * This is "vma_lookup()", but with a warning if we would have 1323 * historically expanded the stack in the GUP code. 1324 */ 1325 static struct vm_area_struct *gup_vma_lookup(struct mm_struct *mm, 1326 unsigned long addr) 1327 { 1328 #ifdef CONFIG_STACK_GROWSUP 1329 return vma_lookup(mm, addr); 1330 #else 1331 static volatile unsigned long next_warn; 1332 struct vm_area_struct *vma; 1333 unsigned long now, next; 1334 1335 vma = find_vma(mm, addr); 1336 if (!vma || (addr >= vma->vm_start)) 1337 return vma; 1338 1339 /* Only warn for half-way relevant accesses */ 1340 if (!(vma->vm_flags & VM_GROWSDOWN)) 1341 return NULL; 1342 if (vma->vm_start - addr > 65536) 1343 return NULL; 1344 1345 /* Let's not warn more than once an hour.. */ 1346 now = jiffies; next = next_warn; 1347 if (next && time_before(now, next)) 1348 return NULL; 1349 next_warn = now + 60*60*HZ; 1350 1351 /* Let people know things may have changed. */ 1352 pr_warn("GUP no longer grows the stack in %s (%d): %lx-%lx (%lx)\n", 1353 current->comm, task_pid_nr(current), 1354 vma->vm_start, vma->vm_end, addr); 1355 dump_stack(); 1356 return NULL; 1357 #endif 1358 } 1359 1360 /** 1361 * __get_user_pages() - pin user pages in memory 1362 * @mm: mm_struct of target mm 1363 * @start: starting user address 1364 * @nr_pages: number of pages from start to pin 1365 * @gup_flags: flags modifying pin behaviour 1366 * @pages: array that receives pointers to the pages pinned. 1367 * Should be at least nr_pages long. Or NULL, if caller 1368 * only intends to ensure the pages are faulted in. 1369 * @locked: whether we're still with the mmap_lock held 1370 * 1371 * Returns either number of pages pinned (which may be less than the 1372 * number requested), or an error. Details about the return value: 1373 * 1374 * -- If nr_pages is 0, returns 0. 1375 * -- If nr_pages is >0, but no pages were pinned, returns -errno. 1376 * -- If nr_pages is >0, and some pages were pinned, returns the number of 1377 * pages pinned. Again, this may be less than nr_pages. 1378 * -- 0 return value is possible when the fault would need to be retried. 1379 * 1380 * The caller is responsible for releasing returned @pages, via put_page(). 1381 * 1382 * Must be called with mmap_lock held. It may be released. See below. 1383 * 1384 * __get_user_pages walks a process's page tables and takes a reference to 1385 * each struct page that each user address corresponds to at a given 1386 * instant. That is, it takes the page that would be accessed if a user 1387 * thread accesses the given user virtual address at that instant. 1388 * 1389 * This does not guarantee that the page exists in the user mappings when 1390 * __get_user_pages returns, and there may even be a completely different 1391 * page there in some cases (eg. if mmapped pagecache has been invalidated 1392 * and subsequently re-faulted). However it does guarantee that the page 1393 * won't be freed completely. And mostly callers simply care that the page 1394 * contains data that was valid *at some point in time*. Typically, an IO 1395 * or similar operation cannot guarantee anything stronger anyway because 1396 * locks can't be held over the syscall boundary. 1397 * 1398 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If 1399 * the page is written to, set_page_dirty (or set_page_dirty_lock, as 1400 * appropriate) must be called after the page is finished with, and 1401 * before put_page is called. 1402 * 1403 * If FOLL_UNLOCKABLE is set without FOLL_NOWAIT then the mmap_lock may 1404 * be released. If this happens *@locked will be set to 0 on return. 1405 * 1406 * A caller using such a combination of @gup_flags must therefore hold the 1407 * mmap_lock for reading only, and recognize when it's been released. Otherwise, 1408 * it must be held for either reading or writing and will not be released. 1409 * 1410 * In most cases, get_user_pages or get_user_pages_fast should be used 1411 * instead of __get_user_pages. __get_user_pages should be used only if 1412 * you need some special @gup_flags. 1413 */ 1414 static long __get_user_pages(struct mm_struct *mm, 1415 unsigned long start, unsigned long nr_pages, 1416 unsigned int gup_flags, struct page **pages, 1417 int *locked) 1418 { 1419 long ret = 0, i = 0; 1420 struct vm_area_struct *vma = NULL; 1421 struct follow_page_context ctx = { NULL }; 1422 1423 if (!nr_pages) 1424 return 0; 1425 1426 start = untagged_addr_remote(mm, start); 1427 1428 VM_WARN_ON_ONCE(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN))); 1429 1430 /* FOLL_GET and FOLL_PIN are mutually exclusive. */ 1431 VM_WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) == 1432 (FOLL_PIN | FOLL_GET)); 1433 1434 do { 1435 struct page *page; 1436 unsigned int page_increm; 1437 1438 /* first iteration or cross vma bound */ 1439 if (!vma || start >= vma->vm_end) { 1440 /* 1441 * MADV_POPULATE_(READ|WRITE) wants to handle VMA 1442 * lookups+error reporting differently. 1443 */ 1444 if (gup_flags & FOLL_MADV_POPULATE) { 1445 vma = vma_lookup(mm, start); 1446 if (!vma) { 1447 ret = -ENOMEM; 1448 goto out; 1449 } 1450 if (check_vma_flags(vma, gup_flags)) { 1451 ret = -EINVAL; 1452 goto out; 1453 } 1454 goto retry; 1455 } 1456 vma = gup_vma_lookup(mm, start); 1457 if (!vma && in_gate_area(mm, start)) { 1458 ret = get_gate_page(mm, start & PAGE_MASK, 1459 gup_flags, &vma, 1460 pages ? &page : NULL); 1461 if (ret) 1462 goto out; 1463 ctx.page_mask = 0; 1464 goto next_page; 1465 } 1466 1467 if (!vma) { 1468 ret = -EFAULT; 1469 goto out; 1470 } 1471 ret = check_vma_flags(vma, gup_flags); 1472 if (ret) 1473 goto out; 1474 } 1475 retry: 1476 /* 1477 * If we have a pending SIGKILL, don't keep faulting pages and 1478 * potentially allocating memory. 1479 */ 1480 if (fatal_signal_pending(current)) { 1481 ret = -EINTR; 1482 goto out; 1483 } 1484 cond_resched(); 1485 1486 page = follow_page_mask(vma, start, gup_flags, &ctx); 1487 if (!page || PTR_ERR(page) == -EMLINK) { 1488 ret = faultin_page(vma, start, gup_flags, 1489 PTR_ERR(page) == -EMLINK, locked); 1490 switch (ret) { 1491 case 0: 1492 goto retry; 1493 case -EBUSY: 1494 case -EAGAIN: 1495 ret = 0; 1496 fallthrough; 1497 case -EFAULT: 1498 case -ENOMEM: 1499 case -EHWPOISON: 1500 goto out; 1501 } 1502 BUG(); 1503 } else if (PTR_ERR(page) == -EEXIST) { 1504 /* 1505 * Proper page table entry exists, but no corresponding 1506 * struct page. If the caller expects **pages to be 1507 * filled in, bail out now, because that can't be done 1508 * for this page. 1509 */ 1510 if (pages) { 1511 ret = PTR_ERR(page); 1512 goto out; 1513 } 1514 } else if (IS_ERR(page)) { 1515 ret = PTR_ERR(page); 1516 goto out; 1517 } 1518 next_page: 1519 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask); 1520 if (page_increm > nr_pages) 1521 page_increm = nr_pages; 1522 1523 if (pages) { 1524 struct page *subpage; 1525 unsigned int j; 1526 1527 /* 1528 * This must be a large folio (and doesn't need to 1529 * be the whole folio; it can be part of it), do 1530 * the refcount work for all the subpages too. 1531 * 1532 * NOTE: here the page may not be the head page 1533 * e.g. when start addr is not thp-size aligned. 1534 * try_grab_folio() should have taken care of tail 1535 * pages. 1536 */ 1537 if (page_increm > 1) { 1538 struct folio *folio = page_folio(page); 1539 1540 /* 1541 * Since we already hold refcount on the 1542 * large folio, this should never fail. 1543 */ 1544 if (try_grab_folio(folio, page_increm - 1, 1545 gup_flags)) { 1546 /* 1547 * Release the 1st page ref if the 1548 * folio is problematic, fail hard. 1549 */ 1550 gup_put_folio(folio, 1, gup_flags); 1551 ret = -EFAULT; 1552 goto out; 1553 } 1554 } 1555 1556 for (j = 0; j < page_increm; j++) { 1557 subpage = nth_page(page, j); 1558 pages[i + j] = subpage; 1559 flush_anon_page(vma, subpage, start + j * PAGE_SIZE); 1560 flush_dcache_page(subpage); 1561 } 1562 } 1563 1564 i += page_increm; 1565 start += page_increm * PAGE_SIZE; 1566 nr_pages -= page_increm; 1567 } while (nr_pages); 1568 out: 1569 if (ctx.pgmap) 1570 put_dev_pagemap(ctx.pgmap); 1571 return i ? i : ret; 1572 } 1573 1574 static bool vma_permits_fault(struct vm_area_struct *vma, 1575 unsigned int fault_flags) 1576 { 1577 bool write = !!(fault_flags & FAULT_FLAG_WRITE); 1578 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE); 1579 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ; 1580 1581 if (!(vm_flags & vma->vm_flags)) 1582 return false; 1583 1584 /* 1585 * The architecture might have a hardware protection 1586 * mechanism other than read/write that can deny access. 1587 * 1588 * gup always represents data access, not instruction 1589 * fetches, so execute=false here: 1590 */ 1591 if (!arch_vma_access_permitted(vma, write, false, foreign)) 1592 return false; 1593 1594 return true; 1595 } 1596 1597 /** 1598 * fixup_user_fault() - manually resolve a user page fault 1599 * @mm: mm_struct of target mm 1600 * @address: user address 1601 * @fault_flags:flags to pass down to handle_mm_fault() 1602 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller 1603 * does not allow retry. If NULL, the caller must guarantee 1604 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY. 1605 * 1606 * This is meant to be called in the specific scenario where for locking reasons 1607 * we try to access user memory in atomic context (within a pagefault_disable() 1608 * section), this returns -EFAULT, and we want to resolve the user fault before 1609 * trying again. 1610 * 1611 * Typically this is meant to be used by the futex code. 1612 * 1613 * The main difference with get_user_pages() is that this function will 1614 * unconditionally call handle_mm_fault() which will in turn perform all the 1615 * necessary SW fixup of the dirty and young bits in the PTE, while 1616 * get_user_pages() only guarantees to update these in the struct page. 1617 * 1618 * This is important for some architectures where those bits also gate the 1619 * access permission to the page because they are maintained in software. On 1620 * such architectures, gup() will not be enough to make a subsequent access 1621 * succeed. 1622 * 1623 * This function will not return with an unlocked mmap_lock. So it has not the 1624 * same semantics wrt the @mm->mmap_lock as does filemap_fault(). 1625 */ 1626 int fixup_user_fault(struct mm_struct *mm, 1627 unsigned long address, unsigned int fault_flags, 1628 bool *unlocked) 1629 { 1630 struct vm_area_struct *vma; 1631 vm_fault_t ret; 1632 1633 address = untagged_addr_remote(mm, address); 1634 1635 if (unlocked) 1636 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE; 1637 1638 retry: 1639 vma = gup_vma_lookup(mm, address); 1640 if (!vma) 1641 return -EFAULT; 1642 1643 if (!vma_permits_fault(vma, fault_flags)) 1644 return -EFAULT; 1645 1646 if ((fault_flags & FAULT_FLAG_KILLABLE) && 1647 fatal_signal_pending(current)) 1648 return -EINTR; 1649 1650 ret = handle_mm_fault(vma, address, fault_flags, NULL); 1651 1652 if (ret & VM_FAULT_COMPLETED) { 1653 /* 1654 * NOTE: it's a pity that we need to retake the lock here 1655 * to pair with the unlock() in the callers. Ideally we 1656 * could tell the callers so they do not need to unlock. 1657 */ 1658 mmap_read_lock(mm); 1659 *unlocked = true; 1660 return 0; 1661 } 1662 1663 if (ret & VM_FAULT_ERROR) { 1664 int err = vm_fault_to_errno(ret, 0); 1665 1666 if (err) 1667 return err; 1668 BUG(); 1669 } 1670 1671 if (ret & VM_FAULT_RETRY) { 1672 mmap_read_lock(mm); 1673 *unlocked = true; 1674 fault_flags |= FAULT_FLAG_TRIED; 1675 goto retry; 1676 } 1677 1678 return 0; 1679 } 1680 EXPORT_SYMBOL_GPL(fixup_user_fault); 1681 1682 /* 1683 * GUP always responds to fatal signals. When FOLL_INTERRUPTIBLE is 1684 * specified, it'll also respond to generic signals. The caller of GUP 1685 * that has FOLL_INTERRUPTIBLE should take care of the GUP interruption. 1686 */ 1687 static bool gup_signal_pending(unsigned int flags) 1688 { 1689 if (fatal_signal_pending(current)) 1690 return true; 1691 1692 if (!(flags & FOLL_INTERRUPTIBLE)) 1693 return false; 1694 1695 return signal_pending(current); 1696 } 1697 1698 /* 1699 * Locking: (*locked == 1) means that the mmap_lock has already been acquired by 1700 * the caller. This function may drop the mmap_lock. If it does so, then it will 1701 * set (*locked = 0). 1702 * 1703 * (*locked == 0) means that the caller expects this function to acquire and 1704 * drop the mmap_lock. Therefore, the value of *locked will still be zero when 1705 * the function returns, even though it may have changed temporarily during 1706 * function execution. 1707 * 1708 * Please note that this function, unlike __get_user_pages(), will not return 0 1709 * for nr_pages > 0, unless FOLL_NOWAIT is used. 1710 */ 1711 static __always_inline long __get_user_pages_locked(struct mm_struct *mm, 1712 unsigned long start, 1713 unsigned long nr_pages, 1714 struct page **pages, 1715 int *locked, 1716 unsigned int flags) 1717 { 1718 long ret, pages_done; 1719 bool must_unlock = false; 1720 1721 if (!nr_pages) 1722 return 0; 1723 1724 /* 1725 * The internal caller expects GUP to manage the lock internally and the 1726 * lock must be released when this returns. 1727 */ 1728 if (!*locked) { 1729 if (mmap_read_lock_killable(mm)) 1730 return -EAGAIN; 1731 must_unlock = true; 1732 *locked = 1; 1733 } 1734 else 1735 mmap_assert_locked(mm); 1736 1737 if (flags & FOLL_PIN) 1738 mm_set_has_pinned_flag(&mm->flags); 1739 1740 /* 1741 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior 1742 * is to set FOLL_GET if the caller wants pages[] filled in (but has 1743 * carelessly failed to specify FOLL_GET), so keep doing that, but only 1744 * for FOLL_GET, not for the newer FOLL_PIN. 1745 * 1746 * FOLL_PIN always expects pages to be non-null, but no need to assert 1747 * that here, as any failures will be obvious enough. 1748 */ 1749 if (pages && !(flags & FOLL_PIN)) 1750 flags |= FOLL_GET; 1751 1752 pages_done = 0; 1753 for (;;) { 1754 ret = __get_user_pages(mm, start, nr_pages, flags, pages, 1755 locked); 1756 if (!(flags & FOLL_UNLOCKABLE)) { 1757 /* VM_FAULT_RETRY couldn't trigger, bypass */ 1758 pages_done = ret; 1759 break; 1760 } 1761 1762 /* VM_FAULT_RETRY or VM_FAULT_COMPLETED cannot return errors */ 1763 VM_WARN_ON_ONCE(!*locked && (ret < 0 || ret >= nr_pages)); 1764 1765 if (ret > 0) { 1766 nr_pages -= ret; 1767 pages_done += ret; 1768 if (!nr_pages) 1769 break; 1770 } 1771 if (*locked) { 1772 /* 1773 * VM_FAULT_RETRY didn't trigger or it was a 1774 * FOLL_NOWAIT. 1775 */ 1776 if (!pages_done) 1777 pages_done = ret; 1778 break; 1779 } 1780 /* 1781 * VM_FAULT_RETRY triggered, so seek to the faulting offset. 1782 * For the prefault case (!pages) we only update counts. 1783 */ 1784 if (likely(pages)) 1785 pages += ret; 1786 start += ret << PAGE_SHIFT; 1787 1788 /* The lock was temporarily dropped, so we must unlock later */ 1789 must_unlock = true; 1790 1791 retry: 1792 /* 1793 * Repeat on the address that fired VM_FAULT_RETRY 1794 * with both FAULT_FLAG_ALLOW_RETRY and 1795 * FAULT_FLAG_TRIED. Note that GUP can be interrupted 1796 * by fatal signals of even common signals, depending on 1797 * the caller's request. So we need to check it before we 1798 * start trying again otherwise it can loop forever. 1799 */ 1800 if (gup_signal_pending(flags)) { 1801 if (!pages_done) 1802 pages_done = -EINTR; 1803 break; 1804 } 1805 1806 ret = mmap_read_lock_killable(mm); 1807 if (ret) { 1808 if (!pages_done) 1809 pages_done = ret; 1810 break; 1811 } 1812 1813 *locked = 1; 1814 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED, 1815 pages, locked); 1816 if (!*locked) { 1817 /* Continue to retry until we succeeded */ 1818 VM_WARN_ON_ONCE(ret != 0); 1819 goto retry; 1820 } 1821 if (ret != 1) { 1822 VM_WARN_ON_ONCE(ret > 1); 1823 if (!pages_done) 1824 pages_done = ret; 1825 break; 1826 } 1827 nr_pages--; 1828 pages_done++; 1829 if (!nr_pages) 1830 break; 1831 if (likely(pages)) 1832 pages++; 1833 start += PAGE_SIZE; 1834 } 1835 if (must_unlock && *locked) { 1836 /* 1837 * We either temporarily dropped the lock, or the caller 1838 * requested that we both acquire and drop the lock. Either way, 1839 * we must now unlock, and notify the caller of that state. 1840 */ 1841 mmap_read_unlock(mm); 1842 *locked = 0; 1843 } 1844 1845 /* 1846 * Failing to pin anything implies something has gone wrong (except when 1847 * FOLL_NOWAIT is specified). 1848 */ 1849 if (WARN_ON_ONCE(pages_done == 0 && !(flags & FOLL_NOWAIT))) 1850 return -EFAULT; 1851 1852 return pages_done; 1853 } 1854 1855 /** 1856 * populate_vma_page_range() - populate a range of pages in the vma. 1857 * @vma: target vma 1858 * @start: start address 1859 * @end: end address 1860 * @locked: whether the mmap_lock is still held 1861 * 1862 * This takes care of mlocking the pages too if VM_LOCKED is set. 1863 * 1864 * Return either number of pages pinned in the vma, or a negative error 1865 * code on error. 1866 * 1867 * vma->vm_mm->mmap_lock must be held. 1868 * 1869 * If @locked is NULL, it may be held for read or write and will 1870 * be unperturbed. 1871 * 1872 * If @locked is non-NULL, it must held for read only and may be 1873 * released. If it's released, *@locked will be set to 0. 1874 */ 1875 long populate_vma_page_range(struct vm_area_struct *vma, 1876 unsigned long start, unsigned long end, int *locked) 1877 { 1878 struct mm_struct *mm = vma->vm_mm; 1879 unsigned long nr_pages = (end - start) / PAGE_SIZE; 1880 int local_locked = 1; 1881 int gup_flags; 1882 long ret; 1883 1884 VM_WARN_ON_ONCE(!PAGE_ALIGNED(start)); 1885 VM_WARN_ON_ONCE(!PAGE_ALIGNED(end)); 1886 VM_WARN_ON_ONCE_VMA(start < vma->vm_start, vma); 1887 VM_WARN_ON_ONCE_VMA(end > vma->vm_end, vma); 1888 mmap_assert_locked(mm); 1889 1890 /* 1891 * Rightly or wrongly, the VM_LOCKONFAULT case has never used 1892 * faultin_page() to break COW, so it has no work to do here. 1893 */ 1894 if (vma->vm_flags & VM_LOCKONFAULT) 1895 return nr_pages; 1896 1897 /* ... similarly, we've never faulted in PROT_NONE pages */ 1898 if (!vma_is_accessible(vma)) 1899 return -EFAULT; 1900 1901 gup_flags = FOLL_TOUCH; 1902 /* 1903 * We want to touch writable mappings with a write fault in order 1904 * to break COW, except for shared mappings because these don't COW 1905 * and we would not want to dirty them for nothing. 1906 * 1907 * Otherwise, do a read fault, and use FOLL_FORCE in case it's not 1908 * readable (ie write-only or executable). 1909 */ 1910 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE) 1911 gup_flags |= FOLL_WRITE; 1912 else 1913 gup_flags |= FOLL_FORCE; 1914 1915 if (locked) 1916 gup_flags |= FOLL_UNLOCKABLE; 1917 1918 /* 1919 * We made sure addr is within a VMA, so the following will 1920 * not result in a stack expansion that recurses back here. 1921 */ 1922 ret = __get_user_pages(mm, start, nr_pages, gup_flags, 1923 NULL, locked ? locked : &local_locked); 1924 lru_add_drain(); 1925 return ret; 1926 } 1927 1928 /* 1929 * faultin_page_range() - populate (prefault) page tables inside the 1930 * given range readable/writable 1931 * 1932 * This takes care of mlocking the pages, too, if VM_LOCKED is set. 1933 * 1934 * @mm: the mm to populate page tables in 1935 * @start: start address 1936 * @end: end address 1937 * @write: whether to prefault readable or writable 1938 * @locked: whether the mmap_lock is still held 1939 * 1940 * Returns either number of processed pages in the MM, or a negative error 1941 * code on error (see __get_user_pages()). Note that this function reports 1942 * errors related to VMAs, such as incompatible mappings, as expected by 1943 * MADV_POPULATE_(READ|WRITE). 1944 * 1945 * The range must be page-aligned. 1946 * 1947 * mm->mmap_lock must be held. If it's released, *@locked will be set to 0. 1948 */ 1949 long faultin_page_range(struct mm_struct *mm, unsigned long start, 1950 unsigned long end, bool write, int *locked) 1951 { 1952 unsigned long nr_pages = (end - start) / PAGE_SIZE; 1953 int gup_flags; 1954 long ret; 1955 1956 VM_WARN_ON_ONCE(!PAGE_ALIGNED(start)); 1957 VM_WARN_ON_ONCE(!PAGE_ALIGNED(end)); 1958 mmap_assert_locked(mm); 1959 1960 /* 1961 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark 1962 * the page dirty with FOLL_WRITE -- which doesn't make a 1963 * difference with !FOLL_FORCE, because the page is writable 1964 * in the page table. 1965 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit 1966 * a poisoned page. 1967 * !FOLL_FORCE: Require proper access permissions. 1968 */ 1969 gup_flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_UNLOCKABLE | 1970 FOLL_MADV_POPULATE; 1971 if (write) 1972 gup_flags |= FOLL_WRITE; 1973 1974 ret = __get_user_pages_locked(mm, start, nr_pages, NULL, locked, 1975 gup_flags); 1976 lru_add_drain(); 1977 return ret; 1978 } 1979 1980 /* 1981 * __mm_populate - populate and/or mlock pages within a range of address space. 1982 * 1983 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap 1984 * flags. VMAs must be already marked with the desired vm_flags, and 1985 * mmap_lock must not be held. 1986 */ 1987 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors) 1988 { 1989 struct mm_struct *mm = current->mm; 1990 unsigned long end, nstart, nend; 1991 struct vm_area_struct *vma = NULL; 1992 int locked = 0; 1993 long ret = 0; 1994 1995 end = start + len; 1996 1997 for (nstart = start; nstart < end; nstart = nend) { 1998 /* 1999 * We want to fault in pages for [nstart; end) address range. 2000 * Find first corresponding VMA. 2001 */ 2002 if (!locked) { 2003 locked = 1; 2004 mmap_read_lock(mm); 2005 vma = find_vma_intersection(mm, nstart, end); 2006 } else if (nstart >= vma->vm_end) 2007 vma = find_vma_intersection(mm, vma->vm_end, end); 2008 2009 if (!vma) 2010 break; 2011 /* 2012 * Set [nstart; nend) to intersection of desired address 2013 * range with the first VMA. Also, skip undesirable VMA types. 2014 */ 2015 nend = min(end, vma->vm_end); 2016 if (vma->vm_flags & (VM_IO | VM_PFNMAP)) 2017 continue; 2018 if (nstart < vma->vm_start) 2019 nstart = vma->vm_start; 2020 /* 2021 * Now fault in a range of pages. populate_vma_page_range() 2022 * double checks the vma flags, so that it won't mlock pages 2023 * if the vma was already munlocked. 2024 */ 2025 ret = populate_vma_page_range(vma, nstart, nend, &locked); 2026 if (ret < 0) { 2027 if (ignore_errors) { 2028 ret = 0; 2029 continue; /* continue at next VMA */ 2030 } 2031 break; 2032 } 2033 nend = nstart + ret * PAGE_SIZE; 2034 ret = 0; 2035 } 2036 if (locked) 2037 mmap_read_unlock(mm); 2038 return ret; /* 0 or negative error code */ 2039 } 2040 #else /* CONFIG_MMU */ 2041 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start, 2042 unsigned long nr_pages, struct page **pages, 2043 int *locked, unsigned int foll_flags) 2044 { 2045 struct vm_area_struct *vma; 2046 bool must_unlock = false; 2047 unsigned long vm_flags; 2048 long i; 2049 2050 if (!nr_pages) 2051 return 0; 2052 2053 /* 2054 * The internal caller expects GUP to manage the lock internally and the 2055 * lock must be released when this returns. 2056 */ 2057 if (!*locked) { 2058 if (mmap_read_lock_killable(mm)) 2059 return -EAGAIN; 2060 must_unlock = true; 2061 *locked = 1; 2062 } 2063 2064 /* calculate required read or write permissions. 2065 * If FOLL_FORCE is set, we only require the "MAY" flags. 2066 */ 2067 vm_flags = (foll_flags & FOLL_WRITE) ? 2068 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD); 2069 vm_flags &= (foll_flags & FOLL_FORCE) ? 2070 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE); 2071 2072 for (i = 0; i < nr_pages; i++) { 2073 vma = find_vma(mm, start); 2074 if (!vma) 2075 break; 2076 2077 /* protect what we can, including chardevs */ 2078 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) || 2079 !(vm_flags & vma->vm_flags)) 2080 break; 2081 2082 if (pages) { 2083 pages[i] = virt_to_page((void *)start); 2084 if (pages[i]) 2085 get_page(pages[i]); 2086 } 2087 2088 start = (start + PAGE_SIZE) & PAGE_MASK; 2089 } 2090 2091 if (must_unlock && *locked) { 2092 mmap_read_unlock(mm); 2093 *locked = 0; 2094 } 2095 2096 return i ? : -EFAULT; 2097 } 2098 #endif /* !CONFIG_MMU */ 2099 2100 /** 2101 * fault_in_writeable - fault in userspace address range for writing 2102 * @uaddr: start of address range 2103 * @size: size of address range 2104 * 2105 * Returns the number of bytes not faulted in (like copy_to_user() and 2106 * copy_from_user()). 2107 */ 2108 size_t fault_in_writeable(char __user *uaddr, size_t size) 2109 { 2110 const unsigned long start = (unsigned long)uaddr; 2111 const unsigned long end = start + size; 2112 unsigned long cur; 2113 2114 if (unlikely(size == 0)) 2115 return 0; 2116 if (!user_write_access_begin(uaddr, size)) 2117 return size; 2118 2119 /* Stop once we overflow to 0. */ 2120 for (cur = start; cur && cur < end; cur = PAGE_ALIGN_DOWN(cur + PAGE_SIZE)) 2121 unsafe_put_user(0, (char __user *)cur, out); 2122 out: 2123 user_write_access_end(); 2124 if (size > cur - start) 2125 return size - (cur - start); 2126 return 0; 2127 } 2128 EXPORT_SYMBOL(fault_in_writeable); 2129 2130 /** 2131 * fault_in_subpage_writeable - fault in an address range for writing 2132 * @uaddr: start of address range 2133 * @size: size of address range 2134 * 2135 * Fault in a user address range for writing while checking for permissions at 2136 * sub-page granularity (e.g. arm64 MTE). This function should be used when 2137 * the caller cannot guarantee forward progress of a copy_to_user() loop. 2138 * 2139 * Returns the number of bytes not faulted in (like copy_to_user() and 2140 * copy_from_user()). 2141 */ 2142 size_t fault_in_subpage_writeable(char __user *uaddr, size_t size) 2143 { 2144 size_t faulted_in; 2145 2146 /* 2147 * Attempt faulting in at page granularity first for page table 2148 * permission checking. The arch-specific probe_subpage_writeable() 2149 * functions may not check for this. 2150 */ 2151 faulted_in = size - fault_in_writeable(uaddr, size); 2152 if (faulted_in) 2153 faulted_in -= probe_subpage_writeable(uaddr, faulted_in); 2154 2155 return size - faulted_in; 2156 } 2157 EXPORT_SYMBOL(fault_in_subpage_writeable); 2158 2159 /* 2160 * fault_in_safe_writeable - fault in an address range for writing 2161 * @uaddr: start of address range 2162 * @size: length of address range 2163 * 2164 * Faults in an address range for writing. This is primarily useful when we 2165 * already know that some or all of the pages in the address range aren't in 2166 * memory. 2167 * 2168 * Unlike fault_in_writeable(), this function is non-destructive. 2169 * 2170 * Note that we don't pin or otherwise hold the pages referenced that we fault 2171 * in. There's no guarantee that they'll stay in memory for any duration of 2172 * time. 2173 * 2174 * Returns the number of bytes not faulted in, like copy_to_user() and 2175 * copy_from_user(). 2176 */ 2177 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size) 2178 { 2179 const unsigned long start = (unsigned long)uaddr; 2180 const unsigned long end = start + size; 2181 unsigned long cur; 2182 struct mm_struct *mm = current->mm; 2183 bool unlocked = false; 2184 2185 if (unlikely(size == 0)) 2186 return 0; 2187 2188 mmap_read_lock(mm); 2189 /* Stop once we overflow to 0. */ 2190 for (cur = start; cur && cur < end; cur = PAGE_ALIGN_DOWN(cur + PAGE_SIZE)) 2191 if (fixup_user_fault(mm, cur, FAULT_FLAG_WRITE, &unlocked)) 2192 break; 2193 mmap_read_unlock(mm); 2194 2195 if (size > cur - start) 2196 return size - (cur - start); 2197 return 0; 2198 } 2199 EXPORT_SYMBOL(fault_in_safe_writeable); 2200 2201 /** 2202 * fault_in_readable - fault in userspace address range for reading 2203 * @uaddr: start of user address range 2204 * @size: size of user address range 2205 * 2206 * Returns the number of bytes not faulted in (like copy_to_user() and 2207 * copy_from_user()). 2208 */ 2209 size_t fault_in_readable(const char __user *uaddr, size_t size) 2210 { 2211 const unsigned long start = (unsigned long)uaddr; 2212 const unsigned long end = start + size; 2213 unsigned long cur; 2214 volatile char c; 2215 2216 if (unlikely(size == 0)) 2217 return 0; 2218 if (!user_read_access_begin(uaddr, size)) 2219 return size; 2220 2221 /* Stop once we overflow to 0. */ 2222 for (cur = start; cur && cur < end; cur = PAGE_ALIGN_DOWN(cur + PAGE_SIZE)) 2223 unsafe_get_user(c, (const char __user *)cur, out); 2224 out: 2225 user_read_access_end(); 2226 (void)c; 2227 if (size > cur - start) 2228 return size - (cur - start); 2229 return 0; 2230 } 2231 EXPORT_SYMBOL(fault_in_readable); 2232 2233 /** 2234 * get_dump_page() - pin user page in memory while writing it to core dump 2235 * @addr: user address 2236 * @locked: a pointer to an int denoting whether the mmap sem is held 2237 * 2238 * Returns struct page pointer of user page pinned for dump, 2239 * to be freed afterwards by put_page(). 2240 * 2241 * Returns NULL on any kind of failure - a hole must then be inserted into 2242 * the corefile, to preserve alignment with its headers; and also returns 2243 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found - 2244 * allowing a hole to be left in the corefile to save disk space. 2245 * 2246 * Called without mmap_lock (takes and releases the mmap_lock by itself). 2247 */ 2248 #ifdef CONFIG_ELF_CORE 2249 struct page *get_dump_page(unsigned long addr, int *locked) 2250 { 2251 struct page *page; 2252 int ret; 2253 2254 ret = __get_user_pages_locked(current->mm, addr, 1, &page, locked, 2255 FOLL_FORCE | FOLL_DUMP | FOLL_GET); 2256 return (ret == 1) ? page : NULL; 2257 } 2258 #endif /* CONFIG_ELF_CORE */ 2259 2260 #ifdef CONFIG_MIGRATION 2261 2262 /* 2263 * An array of either pages or folios ("pofs"). Although it may seem tempting to 2264 * avoid this complication, by simply interpreting a list of folios as a list of 2265 * pages, that approach won't work in the longer term, because eventually the 2266 * layouts of struct page and struct folio will become completely different. 2267 * Furthermore, this pof approach avoids excessive page_folio() calls. 2268 */ 2269 struct pages_or_folios { 2270 union { 2271 struct page **pages; 2272 struct folio **folios; 2273 void **entries; 2274 }; 2275 bool has_folios; 2276 long nr_entries; 2277 }; 2278 2279 static struct folio *pofs_get_folio(struct pages_or_folios *pofs, long i) 2280 { 2281 if (pofs->has_folios) 2282 return pofs->folios[i]; 2283 return page_folio(pofs->pages[i]); 2284 } 2285 2286 static void pofs_clear_entry(struct pages_or_folios *pofs, long i) 2287 { 2288 pofs->entries[i] = NULL; 2289 } 2290 2291 static void pofs_unpin(struct pages_or_folios *pofs) 2292 { 2293 if (pofs->has_folios) 2294 unpin_folios(pofs->folios, pofs->nr_entries); 2295 else 2296 unpin_user_pages(pofs->pages, pofs->nr_entries); 2297 } 2298 2299 static struct folio *pofs_next_folio(struct folio *folio, 2300 struct pages_or_folios *pofs, long *index_ptr) 2301 { 2302 long i = *index_ptr + 1; 2303 2304 if (!pofs->has_folios && folio_test_large(folio)) { 2305 const unsigned long start_pfn = folio_pfn(folio); 2306 const unsigned long end_pfn = start_pfn + folio_nr_pages(folio); 2307 2308 for (; i < pofs->nr_entries; i++) { 2309 unsigned long pfn = page_to_pfn(pofs->pages[i]); 2310 2311 /* Is this page part of this folio? */ 2312 if (pfn < start_pfn || pfn >= end_pfn) 2313 break; 2314 } 2315 } 2316 2317 if (unlikely(i == pofs->nr_entries)) 2318 return NULL; 2319 *index_ptr = i; 2320 2321 return pofs_get_folio(pofs, i); 2322 } 2323 2324 /* 2325 * Returns the number of collected folios. Return value is always >= 0. 2326 */ 2327 static unsigned long collect_longterm_unpinnable_folios( 2328 struct list_head *movable_folio_list, 2329 struct pages_or_folios *pofs) 2330 { 2331 unsigned long collected = 0; 2332 bool drain_allow = true; 2333 struct folio *folio; 2334 long i = 0; 2335 2336 for (folio = pofs_get_folio(pofs, i); folio; 2337 folio = pofs_next_folio(folio, pofs, &i)) { 2338 2339 if (folio_is_longterm_pinnable(folio)) 2340 continue; 2341 2342 collected++; 2343 2344 if (folio_is_device_coherent(folio)) 2345 continue; 2346 2347 if (folio_test_hugetlb(folio)) { 2348 folio_isolate_hugetlb(folio, movable_folio_list); 2349 continue; 2350 } 2351 2352 if (!folio_test_lru(folio) && drain_allow) { 2353 lru_add_drain_all(); 2354 drain_allow = false; 2355 } 2356 2357 if (!folio_isolate_lru(folio)) 2358 continue; 2359 2360 list_add_tail(&folio->lru, movable_folio_list); 2361 node_stat_mod_folio(folio, 2362 NR_ISOLATED_ANON + folio_is_file_lru(folio), 2363 folio_nr_pages(folio)); 2364 } 2365 2366 return collected; 2367 } 2368 2369 /* 2370 * Unpins all folios and migrates device coherent folios and movable_folio_list. 2371 * Returns -EAGAIN if all folios were successfully migrated or -errno for 2372 * failure (or partial success). 2373 */ 2374 static int 2375 migrate_longterm_unpinnable_folios(struct list_head *movable_folio_list, 2376 struct pages_or_folios *pofs) 2377 { 2378 int ret; 2379 unsigned long i; 2380 2381 for (i = 0; i < pofs->nr_entries; i++) { 2382 struct folio *folio = pofs_get_folio(pofs, i); 2383 2384 if (folio_is_device_coherent(folio)) { 2385 /* 2386 * Migration will fail if the folio is pinned, so 2387 * convert the pin on the source folio to a normal 2388 * reference. 2389 */ 2390 pofs_clear_entry(pofs, i); 2391 folio_get(folio); 2392 gup_put_folio(folio, 1, FOLL_PIN); 2393 2394 if (migrate_device_coherent_folio(folio)) { 2395 ret = -EBUSY; 2396 goto err; 2397 } 2398 2399 continue; 2400 } 2401 2402 /* 2403 * We can't migrate folios with unexpected references, so drop 2404 * the reference obtained by __get_user_pages_locked(). 2405 * Migrating folios have been added to movable_folio_list after 2406 * calling folio_isolate_lru() which takes a reference so the 2407 * folio won't be freed if it's migrating. 2408 */ 2409 unpin_folio(folio); 2410 pofs_clear_entry(pofs, i); 2411 } 2412 2413 if (!list_empty(movable_folio_list)) { 2414 struct migration_target_control mtc = { 2415 .nid = NUMA_NO_NODE, 2416 .gfp_mask = GFP_USER | __GFP_NOWARN, 2417 .reason = MR_LONGTERM_PIN, 2418 }; 2419 2420 if (migrate_pages(movable_folio_list, alloc_migration_target, 2421 NULL, (unsigned long)&mtc, MIGRATE_SYNC, 2422 MR_LONGTERM_PIN, NULL)) { 2423 ret = -ENOMEM; 2424 goto err; 2425 } 2426 } 2427 2428 putback_movable_pages(movable_folio_list); 2429 2430 return -EAGAIN; 2431 2432 err: 2433 pofs_unpin(pofs); 2434 putback_movable_pages(movable_folio_list); 2435 2436 return ret; 2437 } 2438 2439 static long 2440 check_and_migrate_movable_pages_or_folios(struct pages_or_folios *pofs) 2441 { 2442 LIST_HEAD(movable_folio_list); 2443 unsigned long collected; 2444 2445 collected = collect_longterm_unpinnable_folios(&movable_folio_list, 2446 pofs); 2447 if (!collected) 2448 return 0; 2449 2450 return migrate_longterm_unpinnable_folios(&movable_folio_list, pofs); 2451 } 2452 2453 /* 2454 * Check whether all folios are *allowed* to be pinned indefinitely (long term). 2455 * Rather confusingly, all folios in the range are required to be pinned via 2456 * FOLL_PIN, before calling this routine. 2457 * 2458 * Return values: 2459 * 2460 * 0: if everything is OK and all folios in the range are allowed to be pinned, 2461 * then this routine leaves all folios pinned and returns zero for success. 2462 * 2463 * -EAGAIN: if any folios in the range are not allowed to be pinned, then this 2464 * routine will migrate those folios away, unpin all the folios in the range. If 2465 * migration of the entire set of folios succeeds, then -EAGAIN is returned. The 2466 * caller should re-pin the entire range with FOLL_PIN and then call this 2467 * routine again. 2468 * 2469 * -ENOMEM, or any other -errno: if an error *other* than -EAGAIN occurs, this 2470 * indicates a migration failure. The caller should give up, and propagate the 2471 * error back up the call stack. The caller does not need to unpin any folios in 2472 * that case, because this routine will do the unpinning. 2473 */ 2474 static long check_and_migrate_movable_folios(unsigned long nr_folios, 2475 struct folio **folios) 2476 { 2477 struct pages_or_folios pofs = { 2478 .folios = folios, 2479 .has_folios = true, 2480 .nr_entries = nr_folios, 2481 }; 2482 2483 return check_and_migrate_movable_pages_or_folios(&pofs); 2484 } 2485 2486 /* 2487 * Return values and behavior are the same as those for 2488 * check_and_migrate_movable_folios(). 2489 */ 2490 static long check_and_migrate_movable_pages(unsigned long nr_pages, 2491 struct page **pages) 2492 { 2493 struct pages_or_folios pofs = { 2494 .pages = pages, 2495 .has_folios = false, 2496 .nr_entries = nr_pages, 2497 }; 2498 2499 return check_and_migrate_movable_pages_or_folios(&pofs); 2500 } 2501 #else 2502 static long check_and_migrate_movable_pages(unsigned long nr_pages, 2503 struct page **pages) 2504 { 2505 return 0; 2506 } 2507 2508 static long check_and_migrate_movable_folios(unsigned long nr_folios, 2509 struct folio **folios) 2510 { 2511 return 0; 2512 } 2513 #endif /* CONFIG_MIGRATION */ 2514 2515 /* 2516 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which 2517 * allows us to process the FOLL_LONGTERM flag. 2518 */ 2519 static long __gup_longterm_locked(struct mm_struct *mm, 2520 unsigned long start, 2521 unsigned long nr_pages, 2522 struct page **pages, 2523 int *locked, 2524 unsigned int gup_flags) 2525 { 2526 unsigned int flags; 2527 long rc, nr_pinned_pages; 2528 2529 if (!(gup_flags & FOLL_LONGTERM)) 2530 return __get_user_pages_locked(mm, start, nr_pages, pages, 2531 locked, gup_flags); 2532 2533 flags = memalloc_pin_save(); 2534 do { 2535 nr_pinned_pages = __get_user_pages_locked(mm, start, nr_pages, 2536 pages, locked, 2537 gup_flags); 2538 if (nr_pinned_pages <= 0) { 2539 rc = nr_pinned_pages; 2540 break; 2541 } 2542 2543 /* FOLL_LONGTERM implies FOLL_PIN */ 2544 rc = check_and_migrate_movable_pages(nr_pinned_pages, pages); 2545 } while (rc == -EAGAIN); 2546 memalloc_pin_restore(flags); 2547 return rc ? rc : nr_pinned_pages; 2548 } 2549 2550 /* 2551 * Check that the given flags are valid for the exported gup/pup interface, and 2552 * update them with the required flags that the caller must have set. 2553 */ 2554 static bool is_valid_gup_args(struct page **pages, int *locked, 2555 unsigned int *gup_flags_p, unsigned int to_set) 2556 { 2557 unsigned int gup_flags = *gup_flags_p; 2558 2559 /* 2560 * These flags not allowed to be specified externally to the gup 2561 * interfaces: 2562 * - FOLL_TOUCH/FOLL_PIN/FOLL_TRIED/FOLL_FAST_ONLY are internal only 2563 * - FOLL_REMOTE is internal only, set in (get|pin)_user_pages_remote() 2564 * - FOLL_UNLOCKABLE is internal only and used if locked is !NULL 2565 */ 2566 if (WARN_ON_ONCE(gup_flags & INTERNAL_GUP_FLAGS)) 2567 return false; 2568 2569 gup_flags |= to_set; 2570 if (locked) { 2571 /* At the external interface locked must be set */ 2572 if (WARN_ON_ONCE(*locked != 1)) 2573 return false; 2574 2575 gup_flags |= FOLL_UNLOCKABLE; 2576 } 2577 2578 /* FOLL_GET and FOLL_PIN are mutually exclusive. */ 2579 if (WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) == 2580 (FOLL_PIN | FOLL_GET))) 2581 return false; 2582 2583 /* LONGTERM can only be specified when pinning */ 2584 if (WARN_ON_ONCE(!(gup_flags & FOLL_PIN) && (gup_flags & FOLL_LONGTERM))) 2585 return false; 2586 2587 /* Pages input must be given if using GET/PIN */ 2588 if (WARN_ON_ONCE((gup_flags & (FOLL_GET | FOLL_PIN)) && !pages)) 2589 return false; 2590 2591 /* We want to allow the pgmap to be hot-unplugged at all times */ 2592 if (WARN_ON_ONCE((gup_flags & FOLL_LONGTERM) && 2593 (gup_flags & FOLL_PCI_P2PDMA))) 2594 return false; 2595 2596 *gup_flags_p = gup_flags; 2597 return true; 2598 } 2599 2600 #ifdef CONFIG_MMU 2601 /** 2602 * get_user_pages_remote() - pin user pages in memory 2603 * @mm: mm_struct of target mm 2604 * @start: starting user address 2605 * @nr_pages: number of pages from start to pin 2606 * @gup_flags: flags modifying lookup behaviour 2607 * @pages: array that receives pointers to the pages pinned. 2608 * Should be at least nr_pages long. Or NULL, if caller 2609 * only intends to ensure the pages are faulted in. 2610 * @locked: pointer to lock flag indicating whether lock is held and 2611 * subsequently whether VM_FAULT_RETRY functionality can be 2612 * utilised. Lock must initially be held. 2613 * 2614 * Returns either number of pages pinned (which may be less than the 2615 * number requested), or an error. Details about the return value: 2616 * 2617 * -- If nr_pages is 0, returns 0. 2618 * -- If nr_pages is >0, but no pages were pinned, returns -errno. 2619 * -- If nr_pages is >0, and some pages were pinned, returns the number of 2620 * pages pinned. Again, this may be less than nr_pages. 2621 * 2622 * The caller is responsible for releasing returned @pages, via put_page(). 2623 * 2624 * Must be called with mmap_lock held for read or write. 2625 * 2626 * get_user_pages_remote walks a process's page tables and takes a reference 2627 * to each struct page that each user address corresponds to at a given 2628 * instant. That is, it takes the page that would be accessed if a user 2629 * thread accesses the given user virtual address at that instant. 2630 * 2631 * This does not guarantee that the page exists in the user mappings when 2632 * get_user_pages_remote returns, and there may even be a completely different 2633 * page there in some cases (eg. if mmapped pagecache has been invalidated 2634 * and subsequently re-faulted). However it does guarantee that the page 2635 * won't be freed completely. And mostly callers simply care that the page 2636 * contains data that was valid *at some point in time*. Typically, an IO 2637 * or similar operation cannot guarantee anything stronger anyway because 2638 * locks can't be held over the syscall boundary. 2639 * 2640 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page 2641 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must 2642 * be called after the page is finished with, and before put_page is called. 2643 * 2644 * get_user_pages_remote is typically used for fewer-copy IO operations, 2645 * to get a handle on the memory by some means other than accesses 2646 * via the user virtual addresses. The pages may be submitted for 2647 * DMA to devices or accessed via their kernel linear mapping (via the 2648 * kmap APIs). Care should be taken to use the correct cache flushing APIs. 2649 * 2650 * See also get_user_pages_fast, for performance critical applications. 2651 * 2652 * get_user_pages_remote should be phased out in favor of 2653 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing 2654 * should use get_user_pages_remote because it cannot pass 2655 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault. 2656 */ 2657 long get_user_pages_remote(struct mm_struct *mm, 2658 unsigned long start, unsigned long nr_pages, 2659 unsigned int gup_flags, struct page **pages, 2660 int *locked) 2661 { 2662 int local_locked = 1; 2663 2664 if (!is_valid_gup_args(pages, locked, &gup_flags, 2665 FOLL_TOUCH | FOLL_REMOTE)) 2666 return -EINVAL; 2667 2668 return __get_user_pages_locked(mm, start, nr_pages, pages, 2669 locked ? locked : &local_locked, 2670 gup_flags); 2671 } 2672 EXPORT_SYMBOL(get_user_pages_remote); 2673 2674 #else /* CONFIG_MMU */ 2675 long get_user_pages_remote(struct mm_struct *mm, 2676 unsigned long start, unsigned long nr_pages, 2677 unsigned int gup_flags, struct page **pages, 2678 int *locked) 2679 { 2680 return 0; 2681 } 2682 #endif /* !CONFIG_MMU */ 2683 2684 /** 2685 * get_user_pages() - pin user pages in memory 2686 * @start: starting user address 2687 * @nr_pages: number of pages from start to pin 2688 * @gup_flags: flags modifying lookup behaviour 2689 * @pages: array that receives pointers to the pages pinned. 2690 * Should be at least nr_pages long. Or NULL, if caller 2691 * only intends to ensure the pages are faulted in. 2692 * 2693 * This is the same as get_user_pages_remote(), just with a less-flexible 2694 * calling convention where we assume that the mm being operated on belongs to 2695 * the current task, and doesn't allow passing of a locked parameter. We also 2696 * obviously don't pass FOLL_REMOTE in here. 2697 */ 2698 long get_user_pages(unsigned long start, unsigned long nr_pages, 2699 unsigned int gup_flags, struct page **pages) 2700 { 2701 int locked = 1; 2702 2703 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_TOUCH)) 2704 return -EINVAL; 2705 2706 return __get_user_pages_locked(current->mm, start, nr_pages, pages, 2707 &locked, gup_flags); 2708 } 2709 EXPORT_SYMBOL(get_user_pages); 2710 2711 /* 2712 * get_user_pages_unlocked() is suitable to replace the form: 2713 * 2714 * mmap_read_lock(mm); 2715 * get_user_pages(mm, ..., pages, NULL); 2716 * mmap_read_unlock(mm); 2717 * 2718 * with: 2719 * 2720 * get_user_pages_unlocked(mm, ..., pages); 2721 * 2722 * It is functionally equivalent to get_user_pages_fast so 2723 * get_user_pages_fast should be used instead if specific gup_flags 2724 * (e.g. FOLL_FORCE) are not required. 2725 */ 2726 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages, 2727 struct page **pages, unsigned int gup_flags) 2728 { 2729 int locked = 0; 2730 2731 if (!is_valid_gup_args(pages, NULL, &gup_flags, 2732 FOLL_TOUCH | FOLL_UNLOCKABLE)) 2733 return -EINVAL; 2734 2735 return __get_user_pages_locked(current->mm, start, nr_pages, pages, 2736 &locked, gup_flags); 2737 } 2738 EXPORT_SYMBOL(get_user_pages_unlocked); 2739 2740 /* 2741 * GUP-fast 2742 * 2743 * get_user_pages_fast attempts to pin user pages by walking the page 2744 * tables directly and avoids taking locks. Thus the walker needs to be 2745 * protected from page table pages being freed from under it, and should 2746 * block any THP splits. 2747 * 2748 * One way to achieve this is to have the walker disable interrupts, and 2749 * rely on IPIs from the TLB flushing code blocking before the page table 2750 * pages are freed. This is unsuitable for architectures that do not need 2751 * to broadcast an IPI when invalidating TLBs. 2752 * 2753 * Another way to achieve this is to batch up page table containing pages 2754 * belonging to more than one mm_user, then rcu_sched a callback to free those 2755 * pages. Disabling interrupts will allow the gup_fast() walker to both block 2756 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs 2757 * (which is a relatively rare event). The code below adopts this strategy. 2758 * 2759 * Before activating this code, please be aware that the following assumptions 2760 * are currently made: 2761 * 2762 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to 2763 * free pages containing page tables or TLB flushing requires IPI broadcast. 2764 * 2765 * *) ptes can be read atomically by the architecture. 2766 * 2767 * *) valid user addesses are below TASK_MAX_SIZE 2768 * 2769 * The last two assumptions can be relaxed by the addition of helper functions. 2770 * 2771 * This code is based heavily on the PowerPC implementation by Nick Piggin. 2772 */ 2773 #ifdef CONFIG_HAVE_GUP_FAST 2774 /* 2775 * Used in the GUP-fast path to determine whether GUP is permitted to work on 2776 * a specific folio. 2777 * 2778 * This call assumes the caller has pinned the folio, that the lowest page table 2779 * level still points to this folio, and that interrupts have been disabled. 2780 * 2781 * GUP-fast must reject all secretmem folios. 2782 * 2783 * Writing to pinned file-backed dirty tracked folios is inherently problematic 2784 * (see comment describing the writable_file_mapping_allowed() function). We 2785 * therefore try to avoid the most egregious case of a long-term mapping doing 2786 * so. 2787 * 2788 * This function cannot be as thorough as that one as the VMA is not available 2789 * in the fast path, so instead we whitelist known good cases and if in doubt, 2790 * fall back to the slow path. 2791 */ 2792 static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags) 2793 { 2794 bool reject_file_backed = false; 2795 struct address_space *mapping; 2796 bool check_secretmem = false; 2797 unsigned long mapping_flags; 2798 2799 /* 2800 * If we aren't pinning then no problematic write can occur. A long term 2801 * pin is the most egregious case so this is the one we disallow. 2802 */ 2803 if ((flags & (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)) == 2804 (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)) 2805 reject_file_backed = true; 2806 2807 /* We hold a folio reference, so we can safely access folio fields. */ 2808 2809 /* secretmem folios are always order-0 folios. */ 2810 if (IS_ENABLED(CONFIG_SECRETMEM) && !folio_test_large(folio)) 2811 check_secretmem = true; 2812 2813 if (!reject_file_backed && !check_secretmem) 2814 return true; 2815 2816 if (WARN_ON_ONCE(folio_test_slab(folio))) 2817 return false; 2818 2819 /* hugetlb neither requires dirty-tracking nor can be secretmem. */ 2820 if (folio_test_hugetlb(folio)) 2821 return true; 2822 2823 /* 2824 * GUP-fast disables IRQs. When IRQS are disabled, RCU grace periods 2825 * cannot proceed, which means no actions performed under RCU can 2826 * proceed either. 2827 * 2828 * inodes and thus their mappings are freed under RCU, which means the 2829 * mapping cannot be freed beneath us and thus we can safely dereference 2830 * it. 2831 */ 2832 lockdep_assert_irqs_disabled(); 2833 2834 /* 2835 * However, there may be operations which _alter_ the mapping, so ensure 2836 * we read it once and only once. 2837 */ 2838 mapping = READ_ONCE(folio->mapping); 2839 2840 /* 2841 * The mapping may have been truncated, in any case we cannot determine 2842 * if this mapping is safe - fall back to slow path to determine how to 2843 * proceed. 2844 */ 2845 if (!mapping) 2846 return false; 2847 2848 /* Anonymous folios pose no problem. */ 2849 mapping_flags = (unsigned long)mapping & PAGE_MAPPING_FLAGS; 2850 if (mapping_flags) 2851 return mapping_flags & PAGE_MAPPING_ANON; 2852 2853 /* 2854 * At this point, we know the mapping is non-null and points to an 2855 * address_space object. 2856 */ 2857 if (check_secretmem && secretmem_mapping(mapping)) 2858 return false; 2859 /* The only remaining allowed file system is shmem. */ 2860 return !reject_file_backed || shmem_mapping(mapping); 2861 } 2862 2863 static void __maybe_unused gup_fast_undo_dev_pagemap(int *nr, int nr_start, 2864 unsigned int flags, struct page **pages) 2865 { 2866 while ((*nr) - nr_start) { 2867 struct folio *folio = page_folio(pages[--(*nr)]); 2868 2869 folio_clear_referenced(folio); 2870 gup_put_folio(folio, 1, flags); 2871 } 2872 } 2873 2874 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL 2875 /* 2876 * GUP-fast relies on pte change detection to avoid concurrent pgtable 2877 * operations. 2878 * 2879 * To pin the page, GUP-fast needs to do below in order: 2880 * (1) pin the page (by prefetching pte), then (2) check pte not changed. 2881 * 2882 * For the rest of pgtable operations where pgtable updates can be racy 2883 * with GUP-fast, we need to do (1) clear pte, then (2) check whether page 2884 * is pinned. 2885 * 2886 * Above will work for all pte-level operations, including THP split. 2887 * 2888 * For THP collapse, it's a bit more complicated because GUP-fast may be 2889 * walking a pgtable page that is being freed (pte is still valid but pmd 2890 * can be cleared already). To avoid race in such condition, we need to 2891 * also check pmd here to make sure pmd doesn't change (corresponds to 2892 * pmdp_collapse_flush() in the THP collapse code path). 2893 */ 2894 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr, 2895 unsigned long end, unsigned int flags, struct page **pages, 2896 int *nr) 2897 { 2898 struct dev_pagemap *pgmap = NULL; 2899 int nr_start = *nr, ret = 0; 2900 pte_t *ptep, *ptem; 2901 2902 ptem = ptep = pte_offset_map(&pmd, addr); 2903 if (!ptep) 2904 return 0; 2905 do { 2906 pte_t pte = ptep_get_lockless(ptep); 2907 struct page *page; 2908 struct folio *folio; 2909 2910 /* 2911 * Always fallback to ordinary GUP on PROT_NONE-mapped pages: 2912 * pte_access_permitted() better should reject these pages 2913 * either way: otherwise, GUP-fast might succeed in 2914 * cases where ordinary GUP would fail due to VMA access 2915 * permissions. 2916 */ 2917 if (pte_protnone(pte)) 2918 goto pte_unmap; 2919 2920 if (!pte_access_permitted(pte, flags & FOLL_WRITE)) 2921 goto pte_unmap; 2922 2923 if (pte_devmap(pte)) { 2924 if (unlikely(flags & FOLL_LONGTERM)) 2925 goto pte_unmap; 2926 2927 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap); 2928 if (unlikely(!pgmap)) { 2929 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages); 2930 goto pte_unmap; 2931 } 2932 } else if (pte_special(pte)) 2933 goto pte_unmap; 2934 2935 /* If it's not marked as special it must have a valid memmap. */ 2936 VM_WARN_ON_ONCE(!pfn_valid(pte_pfn(pte))); 2937 page = pte_page(pte); 2938 2939 folio = try_grab_folio_fast(page, 1, flags); 2940 if (!folio) 2941 goto pte_unmap; 2942 2943 if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) || 2944 unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) { 2945 gup_put_folio(folio, 1, flags); 2946 goto pte_unmap; 2947 } 2948 2949 if (!gup_fast_folio_allowed(folio, flags)) { 2950 gup_put_folio(folio, 1, flags); 2951 goto pte_unmap; 2952 } 2953 2954 if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) { 2955 gup_put_folio(folio, 1, flags); 2956 goto pte_unmap; 2957 } 2958 2959 /* 2960 * We need to make the page accessible if and only if we are 2961 * going to access its content (the FOLL_PIN case). Please 2962 * see Documentation/core-api/pin_user_pages.rst for 2963 * details. 2964 */ 2965 if (flags & FOLL_PIN) { 2966 ret = arch_make_folio_accessible(folio); 2967 if (ret) { 2968 gup_put_folio(folio, 1, flags); 2969 goto pte_unmap; 2970 } 2971 } 2972 folio_set_referenced(folio); 2973 pages[*nr] = page; 2974 (*nr)++; 2975 } while (ptep++, addr += PAGE_SIZE, addr != end); 2976 2977 ret = 1; 2978 2979 pte_unmap: 2980 if (pgmap) 2981 put_dev_pagemap(pgmap); 2982 pte_unmap(ptem); 2983 return ret; 2984 } 2985 #else 2986 2987 /* 2988 * If we can't determine whether or not a pte is special, then fail immediately 2989 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not 2990 * to be special. 2991 * 2992 * For a futex to be placed on a THP tail page, get_futex_key requires a 2993 * get_user_pages_fast_only implementation that can pin pages. Thus it's still 2994 * useful to have gup_fast_pmd_leaf even if we can't operate on ptes. 2995 */ 2996 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr, 2997 unsigned long end, unsigned int flags, struct page **pages, 2998 int *nr) 2999 { 3000 return 0; 3001 } 3002 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */ 3003 3004 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE) 3005 static int gup_fast_devmap_leaf(unsigned long pfn, unsigned long addr, 3006 unsigned long end, unsigned int flags, struct page **pages, int *nr) 3007 { 3008 int nr_start = *nr; 3009 struct dev_pagemap *pgmap = NULL; 3010 3011 do { 3012 struct folio *folio; 3013 struct page *page = pfn_to_page(pfn); 3014 3015 pgmap = get_dev_pagemap(pfn, pgmap); 3016 if (unlikely(!pgmap)) { 3017 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages); 3018 break; 3019 } 3020 3021 folio = try_grab_folio_fast(page, 1, flags); 3022 if (!folio) { 3023 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages); 3024 break; 3025 } 3026 folio_set_referenced(folio); 3027 pages[*nr] = page; 3028 (*nr)++; 3029 pfn++; 3030 } while (addr += PAGE_SIZE, addr != end); 3031 3032 put_dev_pagemap(pgmap); 3033 return addr == end; 3034 } 3035 3036 static int gup_fast_devmap_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr, 3037 unsigned long end, unsigned int flags, struct page **pages, 3038 int *nr) 3039 { 3040 unsigned long fault_pfn; 3041 int nr_start = *nr; 3042 3043 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT); 3044 if (!gup_fast_devmap_leaf(fault_pfn, addr, end, flags, pages, nr)) 3045 return 0; 3046 3047 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) { 3048 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages); 3049 return 0; 3050 } 3051 return 1; 3052 } 3053 3054 static int gup_fast_devmap_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr, 3055 unsigned long end, unsigned int flags, struct page **pages, 3056 int *nr) 3057 { 3058 unsigned long fault_pfn; 3059 int nr_start = *nr; 3060 3061 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT); 3062 if (!gup_fast_devmap_leaf(fault_pfn, addr, end, flags, pages, nr)) 3063 return 0; 3064 3065 if (unlikely(pud_val(orig) != pud_val(*pudp))) { 3066 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages); 3067 return 0; 3068 } 3069 return 1; 3070 } 3071 #else 3072 static int gup_fast_devmap_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr, 3073 unsigned long end, unsigned int flags, struct page **pages, 3074 int *nr) 3075 { 3076 BUILD_BUG(); 3077 return 0; 3078 } 3079 3080 static int gup_fast_devmap_pud_leaf(pud_t pud, pud_t *pudp, unsigned long addr, 3081 unsigned long end, unsigned int flags, struct page **pages, 3082 int *nr) 3083 { 3084 BUILD_BUG(); 3085 return 0; 3086 } 3087 #endif 3088 3089 static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr, 3090 unsigned long end, unsigned int flags, struct page **pages, 3091 int *nr) 3092 { 3093 struct page *page; 3094 struct folio *folio; 3095 int refs; 3096 3097 if (!pmd_access_permitted(orig, flags & FOLL_WRITE)) 3098 return 0; 3099 3100 if (pmd_special(orig)) 3101 return 0; 3102 3103 if (pmd_devmap(orig)) { 3104 if (unlikely(flags & FOLL_LONGTERM)) 3105 return 0; 3106 return gup_fast_devmap_pmd_leaf(orig, pmdp, addr, end, flags, 3107 pages, nr); 3108 } 3109 3110 page = pmd_page(orig); 3111 refs = record_subpages(page, PMD_SIZE, addr, end, pages + *nr); 3112 3113 folio = try_grab_folio_fast(page, refs, flags); 3114 if (!folio) 3115 return 0; 3116 3117 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) { 3118 gup_put_folio(folio, refs, flags); 3119 return 0; 3120 } 3121 3122 if (!gup_fast_folio_allowed(folio, flags)) { 3123 gup_put_folio(folio, refs, flags); 3124 return 0; 3125 } 3126 if (!pmd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) { 3127 gup_put_folio(folio, refs, flags); 3128 return 0; 3129 } 3130 3131 *nr += refs; 3132 folio_set_referenced(folio); 3133 return 1; 3134 } 3135 3136 static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr, 3137 unsigned long end, unsigned int flags, struct page **pages, 3138 int *nr) 3139 { 3140 struct page *page; 3141 struct folio *folio; 3142 int refs; 3143 3144 if (!pud_access_permitted(orig, flags & FOLL_WRITE)) 3145 return 0; 3146 3147 if (pud_special(orig)) 3148 return 0; 3149 3150 if (pud_devmap(orig)) { 3151 if (unlikely(flags & FOLL_LONGTERM)) 3152 return 0; 3153 return gup_fast_devmap_pud_leaf(orig, pudp, addr, end, flags, 3154 pages, nr); 3155 } 3156 3157 page = pud_page(orig); 3158 refs = record_subpages(page, PUD_SIZE, addr, end, pages + *nr); 3159 3160 folio = try_grab_folio_fast(page, refs, flags); 3161 if (!folio) 3162 return 0; 3163 3164 if (unlikely(pud_val(orig) != pud_val(*pudp))) { 3165 gup_put_folio(folio, refs, flags); 3166 return 0; 3167 } 3168 3169 if (!gup_fast_folio_allowed(folio, flags)) { 3170 gup_put_folio(folio, refs, flags); 3171 return 0; 3172 } 3173 3174 if (!pud_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) { 3175 gup_put_folio(folio, refs, flags); 3176 return 0; 3177 } 3178 3179 *nr += refs; 3180 folio_set_referenced(folio); 3181 return 1; 3182 } 3183 3184 static int gup_fast_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, 3185 unsigned long end, unsigned int flags, struct page **pages, 3186 int *nr) 3187 { 3188 unsigned long next; 3189 pmd_t *pmdp; 3190 3191 pmdp = pmd_offset_lockless(pudp, pud, addr); 3192 do { 3193 pmd_t pmd = pmdp_get_lockless(pmdp); 3194 3195 next = pmd_addr_end(addr, end); 3196 if (!pmd_present(pmd)) 3197 return 0; 3198 3199 if (unlikely(pmd_leaf(pmd))) { 3200 /* See gup_fast_pte_range() */ 3201 if (pmd_protnone(pmd)) 3202 return 0; 3203 3204 if (!gup_fast_pmd_leaf(pmd, pmdp, addr, next, flags, 3205 pages, nr)) 3206 return 0; 3207 3208 } else if (!gup_fast_pte_range(pmd, pmdp, addr, next, flags, 3209 pages, nr)) 3210 return 0; 3211 } while (pmdp++, addr = next, addr != end); 3212 3213 return 1; 3214 } 3215 3216 static int gup_fast_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, 3217 unsigned long end, unsigned int flags, struct page **pages, 3218 int *nr) 3219 { 3220 unsigned long next; 3221 pud_t *pudp; 3222 3223 pudp = pud_offset_lockless(p4dp, p4d, addr); 3224 do { 3225 pud_t pud = READ_ONCE(*pudp); 3226 3227 next = pud_addr_end(addr, end); 3228 if (unlikely(!pud_present(pud))) 3229 return 0; 3230 if (unlikely(pud_leaf(pud))) { 3231 if (!gup_fast_pud_leaf(pud, pudp, addr, next, flags, 3232 pages, nr)) 3233 return 0; 3234 } else if (!gup_fast_pmd_range(pudp, pud, addr, next, flags, 3235 pages, nr)) 3236 return 0; 3237 } while (pudp++, addr = next, addr != end); 3238 3239 return 1; 3240 } 3241 3242 static int gup_fast_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, 3243 unsigned long end, unsigned int flags, struct page **pages, 3244 int *nr) 3245 { 3246 unsigned long next; 3247 p4d_t *p4dp; 3248 3249 p4dp = p4d_offset_lockless(pgdp, pgd, addr); 3250 do { 3251 p4d_t p4d = READ_ONCE(*p4dp); 3252 3253 next = p4d_addr_end(addr, end); 3254 if (!p4d_present(p4d)) 3255 return 0; 3256 BUILD_BUG_ON(p4d_leaf(p4d)); 3257 if (!gup_fast_pud_range(p4dp, p4d, addr, next, flags, 3258 pages, nr)) 3259 return 0; 3260 } while (p4dp++, addr = next, addr != end); 3261 3262 return 1; 3263 } 3264 3265 static void gup_fast_pgd_range(unsigned long addr, unsigned long end, 3266 unsigned int flags, struct page **pages, int *nr) 3267 { 3268 unsigned long next; 3269 pgd_t *pgdp; 3270 3271 pgdp = pgd_offset(current->mm, addr); 3272 do { 3273 pgd_t pgd = READ_ONCE(*pgdp); 3274 3275 next = pgd_addr_end(addr, end); 3276 if (pgd_none(pgd)) 3277 return; 3278 BUILD_BUG_ON(pgd_leaf(pgd)); 3279 if (!gup_fast_p4d_range(pgdp, pgd, addr, next, flags, 3280 pages, nr)) 3281 return; 3282 } while (pgdp++, addr = next, addr != end); 3283 } 3284 #else 3285 static inline void gup_fast_pgd_range(unsigned long addr, unsigned long end, 3286 unsigned int flags, struct page **pages, int *nr) 3287 { 3288 } 3289 #endif /* CONFIG_HAVE_GUP_FAST */ 3290 3291 #ifndef gup_fast_permitted 3292 /* 3293 * Check if it's allowed to use get_user_pages_fast_only() for the range, or 3294 * we need to fall back to the slow version: 3295 */ 3296 static bool gup_fast_permitted(unsigned long start, unsigned long end) 3297 { 3298 return true; 3299 } 3300 #endif 3301 3302 static unsigned long gup_fast(unsigned long start, unsigned long end, 3303 unsigned int gup_flags, struct page **pages) 3304 { 3305 unsigned long flags; 3306 int nr_pinned = 0; 3307 unsigned seq; 3308 3309 if (!IS_ENABLED(CONFIG_HAVE_GUP_FAST) || 3310 !gup_fast_permitted(start, end)) 3311 return 0; 3312 3313 if (gup_flags & FOLL_PIN) { 3314 if (!raw_seqcount_try_begin(¤t->mm->write_protect_seq, seq)) 3315 return 0; 3316 } 3317 3318 /* 3319 * Disable interrupts. The nested form is used, in order to allow full, 3320 * general purpose use of this routine. 3321 * 3322 * With interrupts disabled, we block page table pages from being freed 3323 * from under us. See struct mmu_table_batch comments in 3324 * include/asm-generic/tlb.h for more details. 3325 * 3326 * We do not adopt an rcu_read_lock() here as we also want to block IPIs 3327 * that come from callers of tlb_remove_table_sync_one(). 3328 */ 3329 local_irq_save(flags); 3330 gup_fast_pgd_range(start, end, gup_flags, pages, &nr_pinned); 3331 local_irq_restore(flags); 3332 3333 /* 3334 * When pinning pages for DMA there could be a concurrent write protect 3335 * from fork() via copy_page_range(), in this case always fail GUP-fast. 3336 */ 3337 if (gup_flags & FOLL_PIN) { 3338 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) { 3339 gup_fast_unpin_user_pages(pages, nr_pinned); 3340 return 0; 3341 } else { 3342 sanity_check_pinned_pages(pages, nr_pinned); 3343 } 3344 } 3345 return nr_pinned; 3346 } 3347 3348 static int gup_fast_fallback(unsigned long start, unsigned long nr_pages, 3349 unsigned int gup_flags, struct page **pages) 3350 { 3351 unsigned long len, end; 3352 unsigned long nr_pinned; 3353 int locked = 0; 3354 int ret; 3355 3356 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM | 3357 FOLL_FORCE | FOLL_PIN | FOLL_GET | 3358 FOLL_FAST_ONLY | FOLL_NOFAULT | 3359 FOLL_PCI_P2PDMA | FOLL_HONOR_NUMA_FAULT))) 3360 return -EINVAL; 3361 3362 if (gup_flags & FOLL_PIN) 3363 mm_set_has_pinned_flag(¤t->mm->flags); 3364 3365 if (!(gup_flags & FOLL_FAST_ONLY)) 3366 might_lock_read(¤t->mm->mmap_lock); 3367 3368 start = untagged_addr(start) & PAGE_MASK; 3369 len = nr_pages << PAGE_SHIFT; 3370 if (check_add_overflow(start, len, &end)) 3371 return -EOVERFLOW; 3372 if (end > TASK_SIZE_MAX) 3373 return -EFAULT; 3374 3375 nr_pinned = gup_fast(start, end, gup_flags, pages); 3376 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY) 3377 return nr_pinned; 3378 3379 /* Slow path: try to get the remaining pages with get_user_pages */ 3380 start += nr_pinned << PAGE_SHIFT; 3381 pages += nr_pinned; 3382 ret = __gup_longterm_locked(current->mm, start, nr_pages - nr_pinned, 3383 pages, &locked, 3384 gup_flags | FOLL_TOUCH | FOLL_UNLOCKABLE); 3385 if (ret < 0) { 3386 /* 3387 * The caller has to unpin the pages we already pinned so 3388 * returning -errno is not an option 3389 */ 3390 if (nr_pinned) 3391 return nr_pinned; 3392 return ret; 3393 } 3394 return ret + nr_pinned; 3395 } 3396 3397 /** 3398 * get_user_pages_fast_only() - pin user pages in memory 3399 * @start: starting user address 3400 * @nr_pages: number of pages from start to pin 3401 * @gup_flags: flags modifying pin behaviour 3402 * @pages: array that receives pointers to the pages pinned. 3403 * Should be at least nr_pages long. 3404 * 3405 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to 3406 * the regular GUP. 3407 * 3408 * If the architecture does not support this function, simply return with no 3409 * pages pinned. 3410 * 3411 * Careful, careful! COW breaking can go either way, so a non-write 3412 * access can get ambiguous page results. If you call this function without 3413 * 'write' set, you'd better be sure that you're ok with that ambiguity. 3414 */ 3415 int get_user_pages_fast_only(unsigned long start, int nr_pages, 3416 unsigned int gup_flags, struct page **pages) 3417 { 3418 /* 3419 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET, 3420 * because gup fast is always a "pin with a +1 page refcount" request. 3421 * 3422 * FOLL_FAST_ONLY is required in order to match the API description of 3423 * this routine: no fall back to regular ("slow") GUP. 3424 */ 3425 if (!is_valid_gup_args(pages, NULL, &gup_flags, 3426 FOLL_GET | FOLL_FAST_ONLY)) 3427 return -EINVAL; 3428 3429 return gup_fast_fallback(start, nr_pages, gup_flags, pages); 3430 } 3431 EXPORT_SYMBOL_GPL(get_user_pages_fast_only); 3432 3433 /** 3434 * get_user_pages_fast() - pin user pages in memory 3435 * @start: starting user address 3436 * @nr_pages: number of pages from start to pin 3437 * @gup_flags: flags modifying pin behaviour 3438 * @pages: array that receives pointers to the pages pinned. 3439 * Should be at least nr_pages long. 3440 * 3441 * Attempt to pin user pages in memory without taking mm->mmap_lock. 3442 * If not successful, it will fall back to taking the lock and 3443 * calling get_user_pages(). 3444 * 3445 * Returns number of pages pinned. This may be fewer than the number requested. 3446 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns 3447 * -errno. 3448 */ 3449 int get_user_pages_fast(unsigned long start, int nr_pages, 3450 unsigned int gup_flags, struct page **pages) 3451 { 3452 /* 3453 * The caller may or may not have explicitly set FOLL_GET; either way is 3454 * OK. However, internally (within mm/gup.c), gup fast variants must set 3455 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount" 3456 * request. 3457 */ 3458 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_GET)) 3459 return -EINVAL; 3460 return gup_fast_fallback(start, nr_pages, gup_flags, pages); 3461 } 3462 EXPORT_SYMBOL_GPL(get_user_pages_fast); 3463 3464 /** 3465 * pin_user_pages_fast() - pin user pages in memory without taking locks 3466 * 3467 * @start: starting user address 3468 * @nr_pages: number of pages from start to pin 3469 * @gup_flags: flags modifying pin behaviour 3470 * @pages: array that receives pointers to the pages pinned. 3471 * Should be at least nr_pages long. 3472 * 3473 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See 3474 * get_user_pages_fast() for documentation on the function arguments, because 3475 * the arguments here are identical. 3476 * 3477 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please 3478 * see Documentation/core-api/pin_user_pages.rst for further details. 3479 * 3480 * Note that if a zero_page is amongst the returned pages, it will not have 3481 * pins in it and unpin_user_page() will not remove pins from it. 3482 */ 3483 int pin_user_pages_fast(unsigned long start, int nr_pages, 3484 unsigned int gup_flags, struct page **pages) 3485 { 3486 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN)) 3487 return -EINVAL; 3488 return gup_fast_fallback(start, nr_pages, gup_flags, pages); 3489 } 3490 EXPORT_SYMBOL_GPL(pin_user_pages_fast); 3491 3492 /** 3493 * pin_user_pages_remote() - pin pages of a remote process 3494 * 3495 * @mm: mm_struct of target mm 3496 * @start: starting user address 3497 * @nr_pages: number of pages from start to pin 3498 * @gup_flags: flags modifying lookup behaviour 3499 * @pages: array that receives pointers to the pages pinned. 3500 * Should be at least nr_pages long. 3501 * @locked: pointer to lock flag indicating whether lock is held and 3502 * subsequently whether VM_FAULT_RETRY functionality can be 3503 * utilised. Lock must initially be held. 3504 * 3505 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See 3506 * get_user_pages_remote() for documentation on the function arguments, because 3507 * the arguments here are identical. 3508 * 3509 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please 3510 * see Documentation/core-api/pin_user_pages.rst for details. 3511 * 3512 * Note that if a zero_page is amongst the returned pages, it will not have 3513 * pins in it and unpin_user_page*() will not remove pins from it. 3514 */ 3515 long pin_user_pages_remote(struct mm_struct *mm, 3516 unsigned long start, unsigned long nr_pages, 3517 unsigned int gup_flags, struct page **pages, 3518 int *locked) 3519 { 3520 int local_locked = 1; 3521 3522 if (!is_valid_gup_args(pages, locked, &gup_flags, 3523 FOLL_PIN | FOLL_TOUCH | FOLL_REMOTE)) 3524 return 0; 3525 return __gup_longterm_locked(mm, start, nr_pages, pages, 3526 locked ? locked : &local_locked, 3527 gup_flags); 3528 } 3529 EXPORT_SYMBOL(pin_user_pages_remote); 3530 3531 /** 3532 * pin_user_pages() - pin user pages in memory for use by other devices 3533 * 3534 * @start: starting user address 3535 * @nr_pages: number of pages from start to pin 3536 * @gup_flags: flags modifying lookup behaviour 3537 * @pages: array that receives pointers to the pages pinned. 3538 * Should be at least nr_pages long. 3539 * 3540 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and 3541 * FOLL_PIN is set. 3542 * 3543 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please 3544 * see Documentation/core-api/pin_user_pages.rst for details. 3545 * 3546 * Note that if a zero_page is amongst the returned pages, it will not have 3547 * pins in it and unpin_user_page*() will not remove pins from it. 3548 */ 3549 long pin_user_pages(unsigned long start, unsigned long nr_pages, 3550 unsigned int gup_flags, struct page **pages) 3551 { 3552 int locked = 1; 3553 3554 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN)) 3555 return 0; 3556 return __gup_longterm_locked(current->mm, start, nr_pages, 3557 pages, &locked, gup_flags); 3558 } 3559 EXPORT_SYMBOL(pin_user_pages); 3560 3561 /* 3562 * pin_user_pages_unlocked() is the FOLL_PIN variant of 3563 * get_user_pages_unlocked(). Behavior is the same, except that this one sets 3564 * FOLL_PIN and rejects FOLL_GET. 3565 * 3566 * Note that if a zero_page is amongst the returned pages, it will not have 3567 * pins in it and unpin_user_page*() will not remove pins from it. 3568 */ 3569 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages, 3570 struct page **pages, unsigned int gup_flags) 3571 { 3572 int locked = 0; 3573 3574 if (!is_valid_gup_args(pages, NULL, &gup_flags, 3575 FOLL_PIN | FOLL_TOUCH | FOLL_UNLOCKABLE)) 3576 return 0; 3577 3578 return __gup_longterm_locked(current->mm, start, nr_pages, pages, 3579 &locked, gup_flags); 3580 } 3581 EXPORT_SYMBOL(pin_user_pages_unlocked); 3582 3583 /** 3584 * memfd_pin_folios() - pin folios associated with a memfd 3585 * @memfd: the memfd whose folios are to be pinned 3586 * @start: the first memfd offset 3587 * @end: the last memfd offset (inclusive) 3588 * @folios: array that receives pointers to the folios pinned 3589 * @max_folios: maximum number of entries in @folios 3590 * @offset: the offset into the first folio 3591 * 3592 * Attempt to pin folios associated with a memfd in the contiguous range 3593 * [start, end]. Given that a memfd is either backed by shmem or hugetlb, 3594 * the folios can either be found in the page cache or need to be allocated 3595 * if necessary. Once the folios are located, they are all pinned via 3596 * FOLL_PIN and @offset is populatedwith the offset into the first folio. 3597 * And, eventually, these pinned folios must be released either using 3598 * unpin_folios() or unpin_folio(). 3599 * 3600 * It must be noted that the folios may be pinned for an indefinite amount 3601 * of time. And, in most cases, the duration of time they may stay pinned 3602 * would be controlled by the userspace. This behavior is effectively the 3603 * same as using FOLL_LONGTERM with other GUP APIs. 3604 * 3605 * Returns number of folios pinned, which could be less than @max_folios 3606 * as it depends on the folio sizes that cover the range [start, end]. 3607 * If no folios were pinned, it returns -errno. 3608 */ 3609 long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end, 3610 struct folio **folios, unsigned int max_folios, 3611 pgoff_t *offset) 3612 { 3613 unsigned int flags, nr_folios, nr_found; 3614 unsigned int i, pgshift = PAGE_SHIFT; 3615 pgoff_t start_idx, end_idx; 3616 struct folio *folio = NULL; 3617 struct folio_batch fbatch; 3618 struct hstate *h; 3619 long ret = -EINVAL; 3620 3621 if (start < 0 || start > end || !max_folios) 3622 return -EINVAL; 3623 3624 if (!memfd) 3625 return -EINVAL; 3626 3627 if (!shmem_file(memfd) && !is_file_hugepages(memfd)) 3628 return -EINVAL; 3629 3630 if (end >= i_size_read(file_inode(memfd))) 3631 return -EINVAL; 3632 3633 if (is_file_hugepages(memfd)) { 3634 h = hstate_file(memfd); 3635 pgshift = huge_page_shift(h); 3636 } 3637 3638 flags = memalloc_pin_save(); 3639 do { 3640 nr_folios = 0; 3641 start_idx = start >> pgshift; 3642 end_idx = end >> pgshift; 3643 if (is_file_hugepages(memfd)) { 3644 start_idx <<= huge_page_order(h); 3645 end_idx <<= huge_page_order(h); 3646 } 3647 3648 folio_batch_init(&fbatch); 3649 while (start_idx <= end_idx && nr_folios < max_folios) { 3650 /* 3651 * In most cases, we should be able to find the folios 3652 * in the page cache. If we cannot find them for some 3653 * reason, we try to allocate them and add them to the 3654 * page cache. 3655 */ 3656 nr_found = filemap_get_folios_contig(memfd->f_mapping, 3657 &start_idx, 3658 end_idx, 3659 &fbatch); 3660 if (folio) { 3661 folio_put(folio); 3662 folio = NULL; 3663 } 3664 3665 for (i = 0; i < nr_found; i++) { 3666 folio = fbatch.folios[i]; 3667 3668 if (try_grab_folio(folio, 1, FOLL_PIN)) { 3669 folio_batch_release(&fbatch); 3670 ret = -EINVAL; 3671 goto err; 3672 } 3673 3674 if (nr_folios == 0) 3675 *offset = offset_in_folio(folio, start); 3676 3677 folios[nr_folios] = folio; 3678 if (++nr_folios == max_folios) 3679 break; 3680 } 3681 3682 folio = NULL; 3683 folio_batch_release(&fbatch); 3684 if (!nr_found) { 3685 folio = memfd_alloc_folio(memfd, start_idx); 3686 if (IS_ERR(folio)) { 3687 ret = PTR_ERR(folio); 3688 if (ret != -EEXIST) 3689 goto err; 3690 folio = NULL; 3691 } 3692 } 3693 } 3694 3695 ret = check_and_migrate_movable_folios(nr_folios, folios); 3696 } while (ret == -EAGAIN); 3697 3698 memalloc_pin_restore(flags); 3699 return ret ? ret : nr_folios; 3700 err: 3701 memalloc_pin_restore(flags); 3702 unpin_folios(folios, nr_folios); 3703 3704 return ret; 3705 } 3706 EXPORT_SYMBOL_GPL(memfd_pin_folios); 3707 3708 /** 3709 * folio_add_pins() - add pins to an already-pinned folio 3710 * @folio: the folio to add more pins to 3711 * @pins: number of pins to add 3712 * 3713 * Try to add more pins to an already-pinned folio. The semantics 3714 * of the pin (e.g., FOLL_WRITE) follow any existing pin and cannot 3715 * be changed. 3716 * 3717 * This function is helpful when having obtained a pin on a large folio 3718 * using memfd_pin_folios(), but wanting to logically unpin parts 3719 * (e.g., individual pages) of the folio later, for example, using 3720 * unpin_user_page_range_dirty_lock(). 3721 * 3722 * This is not the right interface to initially pin a folio. 3723 */ 3724 int folio_add_pins(struct folio *folio, unsigned int pins) 3725 { 3726 VM_WARN_ON_ONCE(!folio_maybe_dma_pinned(folio)); 3727 3728 return try_grab_folio(folio, pins, FOLL_PIN); 3729 } 3730 EXPORT_SYMBOL_GPL(folio_add_pins); 3731