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