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