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