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