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