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