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