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