mm: reorder code blocks in gup.c
[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>
13
174cd4b1 14#include <linux/sched/signal.h>
2667f50e 15#include <linux/rwsem.h>
f30c59e9 16#include <linux/hugetlb.h>
9a4e9f3b
AK
17#include <linux/migrate.h>
18#include <linux/mm_inline.h>
19#include <linux/sched/mm.h>
1027e443 20
33a709b2 21#include <asm/mmu_context.h>
2667f50e 22#include <asm/pgtable.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
fc1d8e7c
JH
32typedef int (*set_dirty_func_t)(struct page *page);
33
34static void __put_user_pages_dirty(struct page **pages,
35 unsigned long npages,
36 set_dirty_func_t sdf)
37{
38 unsigned long index;
39
40 for (index = 0; index < npages; index++) {
41 struct page *page = compound_head(pages[index]);
42
43 /*
44 * Checking PageDirty at this point may race with
45 * clear_page_dirty_for_io(), but that's OK. Two key cases:
46 *
47 * 1) This code sees the page as already dirty, so it skips
48 * the call to sdf(). That could happen because
49 * clear_page_dirty_for_io() called page_mkclean(),
50 * followed by set_page_dirty(). However, now the page is
51 * going to get written back, which meets the original
52 * intention of setting it dirty, so all is well:
53 * clear_page_dirty_for_io() goes on to call
54 * TestClearPageDirty(), and write the page back.
55 *
56 * 2) This code sees the page as clean, so it calls sdf().
57 * The page stays dirty, despite being written back, so it
58 * gets written back again in the next writeback cycle.
59 * This is harmless.
60 */
61 if (!PageDirty(page))
62 sdf(page);
63
64 put_user_page(page);
65 }
66}
67
68/**
69 * put_user_pages_dirty() - release and dirty an array of gup-pinned pages
70 * @pages: array of pages to be marked dirty and released.
71 * @npages: number of pages in the @pages array.
72 *
73 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
74 * variants called on that page.
75 *
76 * For each page in the @pages array, make that page (or its head page, if a
77 * compound page) dirty, if it was previously listed as clean. Then, release
78 * the page using put_user_page().
79 *
80 * Please see the put_user_page() documentation for details.
81 *
82 * set_page_dirty(), which does not lock the page, is used here.
83 * Therefore, it is the caller's responsibility to ensure that this is
84 * safe. If not, then put_user_pages_dirty_lock() should be called instead.
85 *
86 */
87void put_user_pages_dirty(struct page **pages, unsigned long npages)
88{
89 __put_user_pages_dirty(pages, npages, set_page_dirty);
90}
91EXPORT_SYMBOL(put_user_pages_dirty);
92
93/**
94 * put_user_pages_dirty_lock() - release and dirty an array of gup-pinned pages
95 * @pages: array of pages to be marked dirty and released.
96 * @npages: number of pages in the @pages array.
97 *
98 * For each page in the @pages array, make that page (or its head page, if a
99 * compound page) dirty, if it was previously listed as clean. Then, release
100 * the page using put_user_page().
101 *
102 * Please see the put_user_page() documentation for details.
103 *
104 * This is just like put_user_pages_dirty(), except that it invokes
105 * set_page_dirty_lock(), instead of set_page_dirty().
106 *
107 */
108void put_user_pages_dirty_lock(struct page **pages, unsigned long npages)
109{
110 __put_user_pages_dirty(pages, npages, set_page_dirty_lock);
111}
112EXPORT_SYMBOL(put_user_pages_dirty_lock);
113
114/**
115 * put_user_pages() - release an array of gup-pinned pages.
116 * @pages: array of pages to be marked dirty and released.
117 * @npages: number of pages in the @pages array.
118 *
119 * For each page in the @pages array, release the page using put_user_page().
120 *
121 * Please see the put_user_page() documentation for details.
122 */
123void put_user_pages(struct page **pages, unsigned long npages)
124{
125 unsigned long index;
126
127 /*
128 * TODO: this can be optimized for huge pages: if a series of pages is
129 * physically contiguous and part of the same compound page, then a
130 * single operation to the head page should suffice.
131 */
132 for (index = 0; index < npages; index++)
133 put_user_page(pages[index]);
134}
135EXPORT_SYMBOL(put_user_pages);
136
69e68b4f
KS
137static struct page *no_page_table(struct vm_area_struct *vma,
138 unsigned int flags)
4bbd4c77 139{
69e68b4f
KS
140 /*
141 * When core dumping an enormous anonymous area that nobody
142 * has touched so far, we don't want to allocate unnecessary pages or
143 * page tables. Return error instead of NULL to skip handle_mm_fault,
144 * then get_dump_page() will return NULL to leave a hole in the dump.
145 * But we can only make this optimization where a hole would surely
146 * be zero-filled if handle_mm_fault() actually did handle it.
147 */
148 if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault))
149 return ERR_PTR(-EFAULT);
150 return NULL;
151}
4bbd4c77 152
1027e443
KS
153static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
154 pte_t *pte, unsigned int flags)
155{
156 /* No page to get reference */
157 if (flags & FOLL_GET)
158 return -EFAULT;
159
160 if (flags & FOLL_TOUCH) {
161 pte_t entry = *pte;
162
163 if (flags & FOLL_WRITE)
164 entry = pte_mkdirty(entry);
165 entry = pte_mkyoung(entry);
166
167 if (!pte_same(*pte, entry)) {
168 set_pte_at(vma->vm_mm, address, pte, entry);
169 update_mmu_cache(vma, address, pte);
170 }
171 }
172
173 /* Proper page table entry exists, but no corresponding struct page */
174 return -EEXIST;
175}
176
19be0eaf
LT
177/*
178 * FOLL_FORCE can write to even unwritable pte's, but only
179 * after we've gone through a COW cycle and they are dirty.
180 */
181static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
182{
f6f37321 183 return pte_write(pte) ||
19be0eaf
LT
184 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
185}
186
69e68b4f 187static struct page *follow_page_pte(struct vm_area_struct *vma,
df06b37f
KB
188 unsigned long address, pmd_t *pmd, unsigned int flags,
189 struct dev_pagemap **pgmap)
69e68b4f
KS
190{
191 struct mm_struct *mm = vma->vm_mm;
192 struct page *page;
193 spinlock_t *ptl;
194 pte_t *ptep, pte;
4bbd4c77 195
69e68b4f 196retry:
4bbd4c77 197 if (unlikely(pmd_bad(*pmd)))
69e68b4f 198 return no_page_table(vma, flags);
4bbd4c77
KS
199
200 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
4bbd4c77
KS
201 pte = *ptep;
202 if (!pte_present(pte)) {
203 swp_entry_t entry;
204 /*
205 * KSM's break_ksm() relies upon recognizing a ksm page
206 * even while it is being migrated, so for that case we
207 * need migration_entry_wait().
208 */
209 if (likely(!(flags & FOLL_MIGRATION)))
210 goto no_page;
0661a336 211 if (pte_none(pte))
4bbd4c77
KS
212 goto no_page;
213 entry = pte_to_swp_entry(pte);
214 if (!is_migration_entry(entry))
215 goto no_page;
216 pte_unmap_unlock(ptep, ptl);
217 migration_entry_wait(mm, pmd, address);
69e68b4f 218 goto retry;
4bbd4c77 219 }
8a0516ed 220 if ((flags & FOLL_NUMA) && pte_protnone(pte))
4bbd4c77 221 goto no_page;
19be0eaf 222 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
69e68b4f
KS
223 pte_unmap_unlock(ptep, ptl);
224 return NULL;
225 }
4bbd4c77
KS
226
227 page = vm_normal_page(vma, address, pte);
3565fce3
DW
228 if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
229 /*
230 * Only return device mapping pages in the FOLL_GET case since
231 * they are only valid while holding the pgmap reference.
232 */
df06b37f
KB
233 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
234 if (*pgmap)
3565fce3
DW
235 page = pte_page(pte);
236 else
237 goto no_page;
238 } else if (unlikely(!page)) {
1027e443
KS
239 if (flags & FOLL_DUMP) {
240 /* Avoid special (like zero) pages in core dumps */
241 page = ERR_PTR(-EFAULT);
242 goto out;
243 }
244
245 if (is_zero_pfn(pte_pfn(pte))) {
246 page = pte_page(pte);
247 } else {
248 int ret;
249
250 ret = follow_pfn_pte(vma, address, ptep, flags);
251 page = ERR_PTR(ret);
252 goto out;
253 }
4bbd4c77
KS
254 }
255
6742d293
KS
256 if (flags & FOLL_SPLIT && PageTransCompound(page)) {
257 int ret;
258 get_page(page);
259 pte_unmap_unlock(ptep, ptl);
260 lock_page(page);
261 ret = split_huge_page(page);
262 unlock_page(page);
263 put_page(page);
264 if (ret)
265 return ERR_PTR(ret);
266 goto retry;
267 }
268
8fde12ca
LT
269 if (flags & FOLL_GET) {
270 if (unlikely(!try_get_page(page))) {
271 page = ERR_PTR(-ENOMEM);
272 goto out;
273 }
274 }
4bbd4c77
KS
275 if (flags & FOLL_TOUCH) {
276 if ((flags & FOLL_WRITE) &&
277 !pte_dirty(pte) && !PageDirty(page))
278 set_page_dirty(page);
279 /*
280 * pte_mkyoung() would be more correct here, but atomic care
281 * is needed to avoid losing the dirty bit: it is easier to use
282 * mark_page_accessed().
283 */
284 mark_page_accessed(page);
285 }
de60f5f1 286 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
e90309c9
KS
287 /* Do not mlock pte-mapped THP */
288 if (PageTransCompound(page))
289 goto out;
290
4bbd4c77
KS
291 /*
292 * The preliminary mapping check is mainly to avoid the
293 * pointless overhead of lock_page on the ZERO_PAGE
294 * which might bounce very badly if there is contention.
295 *
296 * If the page is already locked, we don't need to
297 * handle it now - vmscan will handle it later if and
298 * when it attempts to reclaim the page.
299 */
300 if (page->mapping && trylock_page(page)) {
301 lru_add_drain(); /* push cached pages to LRU */
302 /*
303 * Because we lock page here, and migration is
304 * blocked by the pte's page reference, and we
305 * know the page is still mapped, we don't even
306 * need to check for file-cache page truncation.
307 */
308 mlock_vma_page(page);
309 unlock_page(page);
310 }
311 }
1027e443 312out:
4bbd4c77 313 pte_unmap_unlock(ptep, ptl);
4bbd4c77 314 return page;
4bbd4c77
KS
315no_page:
316 pte_unmap_unlock(ptep, ptl);
317 if (!pte_none(pte))
69e68b4f
KS
318 return NULL;
319 return no_page_table(vma, flags);
320}
321
080dbb61
AK
322static struct page *follow_pmd_mask(struct vm_area_struct *vma,
323 unsigned long address, pud_t *pudp,
df06b37f
KB
324 unsigned int flags,
325 struct follow_page_context *ctx)
69e68b4f 326{
68827280 327 pmd_t *pmd, pmdval;
69e68b4f
KS
328 spinlock_t *ptl;
329 struct page *page;
330 struct mm_struct *mm = vma->vm_mm;
331
080dbb61 332 pmd = pmd_offset(pudp, address);
68827280
HY
333 /*
334 * The READ_ONCE() will stabilize the pmdval in a register or
335 * on the stack so that it will stop changing under the code.
336 */
337 pmdval = READ_ONCE(*pmd);
338 if (pmd_none(pmdval))
69e68b4f 339 return no_page_table(vma, flags);
68827280 340 if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) {
e66f17ff
NH
341 page = follow_huge_pmd(mm, address, pmd, flags);
342 if (page)
343 return page;
344 return no_page_table(vma, flags);
69e68b4f 345 }
68827280 346 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
4dc71451 347 page = follow_huge_pd(vma, address,
68827280 348 __hugepd(pmd_val(pmdval)), flags,
4dc71451
AK
349 PMD_SHIFT);
350 if (page)
351 return page;
352 return no_page_table(vma, flags);
353 }
84c3fc4e 354retry:
68827280 355 if (!pmd_present(pmdval)) {
84c3fc4e
ZY
356 if (likely(!(flags & FOLL_MIGRATION)))
357 return no_page_table(vma, flags);
358 VM_BUG_ON(thp_migration_supported() &&
68827280
HY
359 !is_pmd_migration_entry(pmdval));
360 if (is_pmd_migration_entry(pmdval))
84c3fc4e 361 pmd_migration_entry_wait(mm, pmd);
68827280
HY
362 pmdval = READ_ONCE(*pmd);
363 /*
364 * MADV_DONTNEED may convert the pmd to null because
365 * mmap_sem is held in read mode
366 */
367 if (pmd_none(pmdval))
368 return no_page_table(vma, flags);
84c3fc4e
ZY
369 goto retry;
370 }
68827280 371 if (pmd_devmap(pmdval)) {
3565fce3 372 ptl = pmd_lock(mm, pmd);
df06b37f 373 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
3565fce3
DW
374 spin_unlock(ptl);
375 if (page)
376 return page;
377 }
68827280 378 if (likely(!pmd_trans_huge(pmdval)))
df06b37f 379 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
6742d293 380
68827280 381 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
db08f203
AK
382 return no_page_table(vma, flags);
383
84c3fc4e 384retry_locked:
6742d293 385 ptl = pmd_lock(mm, pmd);
68827280
HY
386 if (unlikely(pmd_none(*pmd))) {
387 spin_unlock(ptl);
388 return no_page_table(vma, flags);
389 }
84c3fc4e
ZY
390 if (unlikely(!pmd_present(*pmd))) {
391 spin_unlock(ptl);
392 if (likely(!(flags & FOLL_MIGRATION)))
393 return no_page_table(vma, flags);
394 pmd_migration_entry_wait(mm, pmd);
395 goto retry_locked;
396 }
6742d293
KS
397 if (unlikely(!pmd_trans_huge(*pmd))) {
398 spin_unlock(ptl);
df06b37f 399 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
6742d293 400 }
6742d293
KS
401 if (flags & FOLL_SPLIT) {
402 int ret;
403 page = pmd_page(*pmd);
404 if (is_huge_zero_page(page)) {
405 spin_unlock(ptl);
406 ret = 0;
78ddc534 407 split_huge_pmd(vma, pmd, address);
337d9abf
NH
408 if (pmd_trans_unstable(pmd))
409 ret = -EBUSY;
6742d293 410 } else {
8fde12ca
LT
411 if (unlikely(!try_get_page(page))) {
412 spin_unlock(ptl);
413 return ERR_PTR(-ENOMEM);
414 }
69e68b4f 415 spin_unlock(ptl);
6742d293
KS
416 lock_page(page);
417 ret = split_huge_page(page);
418 unlock_page(page);
419 put_page(page);
baa355fd
KS
420 if (pmd_none(*pmd))
421 return no_page_table(vma, flags);
6742d293
KS
422 }
423
424 return ret ? ERR_PTR(ret) :
df06b37f 425 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
69e68b4f 426 }
6742d293
KS
427 page = follow_trans_huge_pmd(vma, address, pmd, flags);
428 spin_unlock(ptl);
df06b37f 429 ctx->page_mask = HPAGE_PMD_NR - 1;
6742d293 430 return page;
4bbd4c77
KS
431}
432
080dbb61
AK
433static struct page *follow_pud_mask(struct vm_area_struct *vma,
434 unsigned long address, p4d_t *p4dp,
df06b37f
KB
435 unsigned int flags,
436 struct follow_page_context *ctx)
080dbb61
AK
437{
438 pud_t *pud;
439 spinlock_t *ptl;
440 struct page *page;
441 struct mm_struct *mm = vma->vm_mm;
442
443 pud = pud_offset(p4dp, address);
444 if (pud_none(*pud))
445 return no_page_table(vma, flags);
446 if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
447 page = follow_huge_pud(mm, address, pud, flags);
448 if (page)
449 return page;
450 return no_page_table(vma, flags);
451 }
4dc71451
AK
452 if (is_hugepd(__hugepd(pud_val(*pud)))) {
453 page = follow_huge_pd(vma, address,
454 __hugepd(pud_val(*pud)), flags,
455 PUD_SHIFT);
456 if (page)
457 return page;
458 return no_page_table(vma, flags);
459 }
080dbb61
AK
460 if (pud_devmap(*pud)) {
461 ptl = pud_lock(mm, pud);
df06b37f 462 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
080dbb61
AK
463 spin_unlock(ptl);
464 if (page)
465 return page;
466 }
467 if (unlikely(pud_bad(*pud)))
468 return no_page_table(vma, flags);
469
df06b37f 470 return follow_pmd_mask(vma, address, pud, flags, ctx);
080dbb61
AK
471}
472
080dbb61
AK
473static struct page *follow_p4d_mask(struct vm_area_struct *vma,
474 unsigned long address, pgd_t *pgdp,
df06b37f
KB
475 unsigned int flags,
476 struct follow_page_context *ctx)
080dbb61
AK
477{
478 p4d_t *p4d;
4dc71451 479 struct page *page;
080dbb61
AK
480
481 p4d = p4d_offset(pgdp, address);
482 if (p4d_none(*p4d))
483 return no_page_table(vma, flags);
484 BUILD_BUG_ON(p4d_huge(*p4d));
485 if (unlikely(p4d_bad(*p4d)))
486 return no_page_table(vma, flags);
487
4dc71451
AK
488 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
489 page = follow_huge_pd(vma, address,
490 __hugepd(p4d_val(*p4d)), flags,
491 P4D_SHIFT);
492 if (page)
493 return page;
494 return no_page_table(vma, flags);
495 }
df06b37f 496 return follow_pud_mask(vma, address, p4d, flags, ctx);
080dbb61
AK
497}
498
499/**
500 * follow_page_mask - look up a page descriptor from a user-virtual address
501 * @vma: vm_area_struct mapping @address
502 * @address: virtual address to look up
503 * @flags: flags modifying lookup behaviour
78179556
MR
504 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
505 * pointer to output page_mask
080dbb61
AK
506 *
507 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
508 *
78179556
MR
509 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
510 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
511 *
512 * On output, the @ctx->page_mask is set according to the size of the page.
513 *
514 * Return: the mapped (struct page *), %NULL if no mapping exists, or
080dbb61
AK
515 * an error pointer if there is a mapping to something not represented
516 * by a page descriptor (see also vm_normal_page()).
517 */
a7030aea 518static struct page *follow_page_mask(struct vm_area_struct *vma,
080dbb61 519 unsigned long address, unsigned int flags,
df06b37f 520 struct follow_page_context *ctx)
080dbb61
AK
521{
522 pgd_t *pgd;
523 struct page *page;
524 struct mm_struct *mm = vma->vm_mm;
525
df06b37f 526 ctx->page_mask = 0;
080dbb61
AK
527
528 /* make this handle hugepd */
529 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
530 if (!IS_ERR(page)) {
531 BUG_ON(flags & FOLL_GET);
532 return page;
533 }
534
535 pgd = pgd_offset(mm, address);
536
537 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
538 return no_page_table(vma, flags);
539
faaa5b62
AK
540 if (pgd_huge(*pgd)) {
541 page = follow_huge_pgd(mm, address, pgd, flags);
542 if (page)
543 return page;
544 return no_page_table(vma, flags);
545 }
4dc71451
AK
546 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
547 page = follow_huge_pd(vma, address,
548 __hugepd(pgd_val(*pgd)), flags,
549 PGDIR_SHIFT);
550 if (page)
551 return page;
552 return no_page_table(vma, flags);
553 }
faaa5b62 554
df06b37f
KB
555 return follow_p4d_mask(vma, address, pgd, flags, ctx);
556}
557
558struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
559 unsigned int foll_flags)
560{
561 struct follow_page_context ctx = { NULL };
562 struct page *page;
563
564 page = follow_page_mask(vma, address, foll_flags, &ctx);
565 if (ctx.pgmap)
566 put_dev_pagemap(ctx.pgmap);
567 return page;
080dbb61
AK
568}
569
f2b495ca
KS
570static int get_gate_page(struct mm_struct *mm, unsigned long address,
571 unsigned int gup_flags, struct vm_area_struct **vma,
572 struct page **page)
573{
574 pgd_t *pgd;
c2febafc 575 p4d_t *p4d;
f2b495ca
KS
576 pud_t *pud;
577 pmd_t *pmd;
578 pte_t *pte;
579 int ret = -EFAULT;
580
581 /* user gate pages are read-only */
582 if (gup_flags & FOLL_WRITE)
583 return -EFAULT;
584 if (address > TASK_SIZE)
585 pgd = pgd_offset_k(address);
586 else
587 pgd = pgd_offset_gate(mm, address);
588 BUG_ON(pgd_none(*pgd));
c2febafc
KS
589 p4d = p4d_offset(pgd, address);
590 BUG_ON(p4d_none(*p4d));
591 pud = pud_offset(p4d, address);
f2b495ca
KS
592 BUG_ON(pud_none(*pud));
593 pmd = pmd_offset(pud, address);
84c3fc4e 594 if (!pmd_present(*pmd))
f2b495ca
KS
595 return -EFAULT;
596 VM_BUG_ON(pmd_trans_huge(*pmd));
597 pte = pte_offset_map(pmd, address);
598 if (pte_none(*pte))
599 goto unmap;
600 *vma = get_gate_vma(mm);
601 if (!page)
602 goto out;
603 *page = vm_normal_page(*vma, address, *pte);
604 if (!*page) {
605 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
606 goto unmap;
607 *page = pte_page(*pte);
df6ad698
JG
608
609 /*
610 * This should never happen (a device public page in the gate
611 * area).
612 */
613 if (is_device_public_page(*page))
614 goto unmap;
f2b495ca 615 }
8fde12ca
LT
616 if (unlikely(!try_get_page(*page))) {
617 ret = -ENOMEM;
618 goto unmap;
619 }
f2b495ca
KS
620out:
621 ret = 0;
622unmap:
623 pte_unmap(pte);
624 return ret;
625}
626
9a95f3cf
PC
627/*
628 * mmap_sem must be held on entry. If @nonblocking != NULL and
629 * *@flags does not include FOLL_NOWAIT, the mmap_sem may be released.
630 * If it is, *@nonblocking will be set to 0 and -EBUSY returned.
631 */
16744483
KS
632static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
633 unsigned long address, unsigned int *flags, int *nonblocking)
634{
16744483 635 unsigned int fault_flags = 0;
2b740303 636 vm_fault_t ret;
16744483 637
de60f5f1
EM
638 /* mlock all present pages, but do not fault in new pages */
639 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
640 return -ENOENT;
16744483
KS
641 if (*flags & FOLL_WRITE)
642 fault_flags |= FAULT_FLAG_WRITE;
1b2ee126
DH
643 if (*flags & FOLL_REMOTE)
644 fault_flags |= FAULT_FLAG_REMOTE;
16744483
KS
645 if (nonblocking)
646 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
647 if (*flags & FOLL_NOWAIT)
648 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
234b239b
ALC
649 if (*flags & FOLL_TRIED) {
650 VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
651 fault_flags |= FAULT_FLAG_TRIED;
652 }
16744483 653
dcddffd4 654 ret = handle_mm_fault(vma, address, fault_flags);
16744483 655 if (ret & VM_FAULT_ERROR) {
9a291a7c
JM
656 int err = vm_fault_to_errno(ret, *flags);
657
658 if (err)
659 return err;
16744483
KS
660 BUG();
661 }
662
663 if (tsk) {
664 if (ret & VM_FAULT_MAJOR)
665 tsk->maj_flt++;
666 else
667 tsk->min_flt++;
668 }
669
670 if (ret & VM_FAULT_RETRY) {
96312e61 671 if (nonblocking && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
16744483
KS
672 *nonblocking = 0;
673 return -EBUSY;
674 }
675
676 /*
677 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
678 * necessary, even if maybe_mkwrite decided not to set pte_write. We
679 * can thus safely do subsequent page lookups as if they were reads.
680 * But only do so when looping for pte_write is futile: in some cases
681 * userspace may also be wanting to write to the gotten user page,
682 * which a read fault here might prevent (a readonly page might get
683 * reCOWed by userspace write).
684 */
685 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
2923117b 686 *flags |= FOLL_COW;
16744483
KS
687 return 0;
688}
689
fa5bb209
KS
690static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
691{
692 vm_flags_t vm_flags = vma->vm_flags;
1b2ee126
DH
693 int write = (gup_flags & FOLL_WRITE);
694 int foreign = (gup_flags & FOLL_REMOTE);
fa5bb209
KS
695
696 if (vm_flags & (VM_IO | VM_PFNMAP))
697 return -EFAULT;
698
7f7ccc2c
WT
699 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
700 return -EFAULT;
701
1b2ee126 702 if (write) {
fa5bb209
KS
703 if (!(vm_flags & VM_WRITE)) {
704 if (!(gup_flags & FOLL_FORCE))
705 return -EFAULT;
706 /*
707 * We used to let the write,force case do COW in a
708 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
709 * set a breakpoint in a read-only mapping of an
710 * executable, without corrupting the file (yet only
711 * when that file had been opened for writing!).
712 * Anon pages in shared mappings are surprising: now
713 * just reject it.
714 */
46435364 715 if (!is_cow_mapping(vm_flags))
fa5bb209 716 return -EFAULT;
fa5bb209
KS
717 }
718 } else if (!(vm_flags & VM_READ)) {
719 if (!(gup_flags & FOLL_FORCE))
720 return -EFAULT;
721 /*
722 * Is there actually any vma we can reach here which does not
723 * have VM_MAYREAD set?
724 */
725 if (!(vm_flags & VM_MAYREAD))
726 return -EFAULT;
727 }
d61172b4
DH
728 /*
729 * gups are always data accesses, not instruction
730 * fetches, so execute=false here
731 */
732 if (!arch_vma_access_permitted(vma, write, false, foreign))
33a709b2 733 return -EFAULT;
fa5bb209
KS
734 return 0;
735}
736
4bbd4c77
KS
737/**
738 * __get_user_pages() - pin user pages in memory
739 * @tsk: task_struct of target task
740 * @mm: mm_struct of target mm
741 * @start: starting user address
742 * @nr_pages: number of pages from start to pin
743 * @gup_flags: flags modifying pin behaviour
744 * @pages: array that receives pointers to the pages pinned.
745 * Should be at least nr_pages long. Or NULL, if caller
746 * only intends to ensure the pages are faulted in.
747 * @vmas: array of pointers to vmas corresponding to each page.
748 * Or NULL if the caller does not require them.
749 * @nonblocking: whether waiting for disk IO or mmap_sem contention
750 *
751 * Returns number of pages pinned. This may be fewer than the number
752 * requested. If nr_pages is 0 or negative, returns 0. If no pages
753 * were pinned, returns -errno. Each page returned must be released
754 * with a put_page() call when it is finished with. vmas will only
755 * remain valid while mmap_sem is held.
756 *
9a95f3cf 757 * Must be called with mmap_sem held. It may be released. See below.
4bbd4c77
KS
758 *
759 * __get_user_pages walks a process's page tables and takes a reference to
760 * each struct page that each user address corresponds to at a given
761 * instant. That is, it takes the page that would be accessed if a user
762 * thread accesses the given user virtual address at that instant.
763 *
764 * This does not guarantee that the page exists in the user mappings when
765 * __get_user_pages returns, and there may even be a completely different
766 * page there in some cases (eg. if mmapped pagecache has been invalidated
767 * and subsequently re faulted). However it does guarantee that the page
768 * won't be freed completely. And mostly callers simply care that the page
769 * contains data that was valid *at some point in time*. Typically, an IO
770 * or similar operation cannot guarantee anything stronger anyway because
771 * locks can't be held over the syscall boundary.
772 *
773 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
774 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
775 * appropriate) must be called after the page is finished with, and
776 * before put_page is called.
777 *
778 * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
779 * or mmap_sem contention, and if waiting is needed to pin all pages,
9a95f3cf
PC
780 * *@nonblocking will be set to 0. Further, if @gup_flags does not
781 * include FOLL_NOWAIT, the mmap_sem will be released via up_read() in
782 * this case.
783 *
784 * A caller using such a combination of @nonblocking and @gup_flags
785 * must therefore hold the mmap_sem for reading only, and recognize
786 * when it's been released. Otherwise, it must be held for either
787 * reading or writing and will not be released.
4bbd4c77
KS
788 *
789 * In most cases, get_user_pages or get_user_pages_fast should be used
790 * instead of __get_user_pages. __get_user_pages should be used only if
791 * you need some special @gup_flags.
792 */
0d731759 793static long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
4bbd4c77
KS
794 unsigned long start, unsigned long nr_pages,
795 unsigned int gup_flags, struct page **pages,
796 struct vm_area_struct **vmas, int *nonblocking)
797{
df06b37f 798 long ret = 0, i = 0;
fa5bb209 799 struct vm_area_struct *vma = NULL;
df06b37f 800 struct follow_page_context ctx = { NULL };
4bbd4c77
KS
801
802 if (!nr_pages)
803 return 0;
804
805 VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
806
807 /*
808 * If FOLL_FORCE is set then do not force a full fault as the hinting
809 * fault information is unrelated to the reference behaviour of a task
810 * using the address space
811 */
812 if (!(gup_flags & FOLL_FORCE))
813 gup_flags |= FOLL_NUMA;
814
4bbd4c77 815 do {
fa5bb209
KS
816 struct page *page;
817 unsigned int foll_flags = gup_flags;
818 unsigned int page_increm;
819
820 /* first iteration or cross vma bound */
821 if (!vma || start >= vma->vm_end) {
822 vma = find_extend_vma(mm, start);
823 if (!vma && in_gate_area(mm, start)) {
fa5bb209
KS
824 ret = get_gate_page(mm, start & PAGE_MASK,
825 gup_flags, &vma,
826 pages ? &pages[i] : NULL);
827 if (ret)
08be37b7 828 goto out;
df06b37f 829 ctx.page_mask = 0;
fa5bb209
KS
830 goto next_page;
831 }
4bbd4c77 832
df06b37f
KB
833 if (!vma || check_vma_flags(vma, gup_flags)) {
834 ret = -EFAULT;
835 goto out;
836 }
fa5bb209
KS
837 if (is_vm_hugetlb_page(vma)) {
838 i = follow_hugetlb_page(mm, vma, pages, vmas,
839 &start, &nr_pages, i,
87ffc118 840 gup_flags, nonblocking);
fa5bb209 841 continue;
4bbd4c77 842 }
fa5bb209
KS
843 }
844retry:
845 /*
846 * If we have a pending SIGKILL, don't keep faulting pages and
847 * potentially allocating memory.
848 */
fa45f116 849 if (fatal_signal_pending(current)) {
df06b37f
KB
850 ret = -ERESTARTSYS;
851 goto out;
852 }
fa5bb209 853 cond_resched();
df06b37f
KB
854
855 page = follow_page_mask(vma, start, foll_flags, &ctx);
fa5bb209 856 if (!page) {
fa5bb209
KS
857 ret = faultin_page(tsk, vma, start, &foll_flags,
858 nonblocking);
859 switch (ret) {
860 case 0:
861 goto retry;
df06b37f
KB
862 case -EBUSY:
863 ret = 0;
864 /* FALLTHRU */
fa5bb209
KS
865 case -EFAULT:
866 case -ENOMEM:
867 case -EHWPOISON:
df06b37f 868 goto out;
fa5bb209
KS
869 case -ENOENT:
870 goto next_page;
4bbd4c77 871 }
fa5bb209 872 BUG();
1027e443
KS
873 } else if (PTR_ERR(page) == -EEXIST) {
874 /*
875 * Proper page table entry exists, but no corresponding
876 * struct page.
877 */
878 goto next_page;
879 } else if (IS_ERR(page)) {
df06b37f
KB
880 ret = PTR_ERR(page);
881 goto out;
1027e443 882 }
fa5bb209
KS
883 if (pages) {
884 pages[i] = page;
885 flush_anon_page(vma, page, start);
886 flush_dcache_page(page);
df06b37f 887 ctx.page_mask = 0;
4bbd4c77 888 }
4bbd4c77 889next_page:
fa5bb209
KS
890 if (vmas) {
891 vmas[i] = vma;
df06b37f 892 ctx.page_mask = 0;
fa5bb209 893 }
df06b37f 894 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
fa5bb209
KS
895 if (page_increm > nr_pages)
896 page_increm = nr_pages;
897 i += page_increm;
898 start += page_increm * PAGE_SIZE;
899 nr_pages -= page_increm;
4bbd4c77 900 } while (nr_pages);
df06b37f
KB
901out:
902 if (ctx.pgmap)
903 put_dev_pagemap(ctx.pgmap);
904 return i ? i : ret;
4bbd4c77 905}
4bbd4c77 906
771ab430
TK
907static bool vma_permits_fault(struct vm_area_struct *vma,
908 unsigned int fault_flags)
d4925e00 909{
1b2ee126
DH
910 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
911 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
33a709b2 912 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
d4925e00
DH
913
914 if (!(vm_flags & vma->vm_flags))
915 return false;
916
33a709b2
DH
917 /*
918 * The architecture might have a hardware protection
1b2ee126 919 * mechanism other than read/write that can deny access.
d61172b4
DH
920 *
921 * gup always represents data access, not instruction
922 * fetches, so execute=false here:
33a709b2 923 */
d61172b4 924 if (!arch_vma_access_permitted(vma, write, false, foreign))
33a709b2
DH
925 return false;
926
d4925e00
DH
927 return true;
928}
929
4bbd4c77
KS
930/*
931 * fixup_user_fault() - manually resolve a user page fault
932 * @tsk: the task_struct to use for page fault accounting, or
933 * NULL if faults are not to be recorded.
934 * @mm: mm_struct of target mm
935 * @address: user address
936 * @fault_flags:flags to pass down to handle_mm_fault()
4a9e1cda
DD
937 * @unlocked: did we unlock the mmap_sem while retrying, maybe NULL if caller
938 * does not allow retry
4bbd4c77
KS
939 *
940 * This is meant to be called in the specific scenario where for locking reasons
941 * we try to access user memory in atomic context (within a pagefault_disable()
942 * section), this returns -EFAULT, and we want to resolve the user fault before
943 * trying again.
944 *
945 * Typically this is meant to be used by the futex code.
946 *
947 * The main difference with get_user_pages() is that this function will
948 * unconditionally call handle_mm_fault() which will in turn perform all the
949 * necessary SW fixup of the dirty and young bits in the PTE, while
4a9e1cda 950 * get_user_pages() only guarantees to update these in the struct page.
4bbd4c77
KS
951 *
952 * This is important for some architectures where those bits also gate the
953 * access permission to the page because they are maintained in software. On
954 * such architectures, gup() will not be enough to make a subsequent access
955 * succeed.
956 *
4a9e1cda
DD
957 * This function will not return with an unlocked mmap_sem. So it has not the
958 * same semantics wrt the @mm->mmap_sem as does filemap_fault().
4bbd4c77
KS
959 */
960int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
4a9e1cda
DD
961 unsigned long address, unsigned int fault_flags,
962 bool *unlocked)
4bbd4c77
KS
963{
964 struct vm_area_struct *vma;
2b740303 965 vm_fault_t ret, major = 0;
4a9e1cda
DD
966
967 if (unlocked)
968 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
4bbd4c77 969
4a9e1cda 970retry:
4bbd4c77
KS
971 vma = find_extend_vma(mm, address);
972 if (!vma || address < vma->vm_start)
973 return -EFAULT;
974
d4925e00 975 if (!vma_permits_fault(vma, fault_flags))
4bbd4c77
KS
976 return -EFAULT;
977
dcddffd4 978 ret = handle_mm_fault(vma, address, fault_flags);
4a9e1cda 979 major |= ret & VM_FAULT_MAJOR;
4bbd4c77 980 if (ret & VM_FAULT_ERROR) {
9a291a7c
JM
981 int err = vm_fault_to_errno(ret, 0);
982
983 if (err)
984 return err;
4bbd4c77
KS
985 BUG();
986 }
4a9e1cda
DD
987
988 if (ret & VM_FAULT_RETRY) {
989 down_read(&mm->mmap_sem);
990 if (!(fault_flags & FAULT_FLAG_TRIED)) {
991 *unlocked = true;
992 fault_flags &= ~FAULT_FLAG_ALLOW_RETRY;
993 fault_flags |= FAULT_FLAG_TRIED;
994 goto retry;
995 }
996 }
997
4bbd4c77 998 if (tsk) {
4a9e1cda 999 if (major)
4bbd4c77
KS
1000 tsk->maj_flt++;
1001 else
1002 tsk->min_flt++;
1003 }
1004 return 0;
1005}
add6a0cd 1006EXPORT_SYMBOL_GPL(fixup_user_fault);
4bbd4c77 1007
f0818f47
AA
1008static __always_inline long __get_user_pages_locked(struct task_struct *tsk,
1009 struct mm_struct *mm,
1010 unsigned long start,
1011 unsigned long nr_pages,
f0818f47
AA
1012 struct page **pages,
1013 struct vm_area_struct **vmas,
e716712f 1014 int *locked,
0fd71a56 1015 unsigned int flags)
f0818f47 1016{
f0818f47
AA
1017 long ret, pages_done;
1018 bool lock_dropped;
1019
1020 if (locked) {
1021 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1022 BUG_ON(vmas);
1023 /* check caller initialized locked */
1024 BUG_ON(*locked != 1);
1025 }
1026
1027 if (pages)
1028 flags |= FOLL_GET;
f0818f47
AA
1029
1030 pages_done = 0;
1031 lock_dropped = false;
1032 for (;;) {
1033 ret = __get_user_pages(tsk, mm, start, nr_pages, flags, pages,
1034 vmas, locked);
1035 if (!locked)
1036 /* VM_FAULT_RETRY couldn't trigger, bypass */
1037 return ret;
1038
1039 /* VM_FAULT_RETRY cannot return errors */
1040 if (!*locked) {
1041 BUG_ON(ret < 0);
1042 BUG_ON(ret >= nr_pages);
1043 }
1044
f0818f47
AA
1045 if (ret > 0) {
1046 nr_pages -= ret;
1047 pages_done += ret;
1048 if (!nr_pages)
1049 break;
1050 }
1051 if (*locked) {
96312e61
AA
1052 /*
1053 * VM_FAULT_RETRY didn't trigger or it was a
1054 * FOLL_NOWAIT.
1055 */
f0818f47
AA
1056 if (!pages_done)
1057 pages_done = ret;
1058 break;
1059 }
df17277b
MR
1060 /*
1061 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1062 * For the prefault case (!pages) we only update counts.
1063 */
1064 if (likely(pages))
1065 pages += ret;
f0818f47
AA
1066 start += ret << PAGE_SHIFT;
1067
1068 /*
1069 * Repeat on the address that fired VM_FAULT_RETRY
1070 * without FAULT_FLAG_ALLOW_RETRY but with
1071 * FAULT_FLAG_TRIED.
1072 */
1073 *locked = 1;
1074 lock_dropped = true;
1075 down_read(&mm->mmap_sem);
1076 ret = __get_user_pages(tsk, mm, start, 1, flags | FOLL_TRIED,
1077 pages, NULL, NULL);
1078 if (ret != 1) {
1079 BUG_ON(ret > 1);
1080 if (!pages_done)
1081 pages_done = ret;
1082 break;
1083 }
1084 nr_pages--;
1085 pages_done++;
1086 if (!nr_pages)
1087 break;
df17277b
MR
1088 if (likely(pages))
1089 pages++;
f0818f47
AA
1090 start += PAGE_SIZE;
1091 }
e716712f 1092 if (lock_dropped && *locked) {
f0818f47
AA
1093 /*
1094 * We must let the caller know we temporarily dropped the lock
1095 * and so the critical section protected by it was lost.
1096 */
1097 up_read(&mm->mmap_sem);
1098 *locked = 0;
1099 }
1100 return pages_done;
1101}
1102
4bbd4c77 1103/*
1e987790 1104 * get_user_pages_remote() - pin user pages in memory
4bbd4c77
KS
1105 * @tsk: the task_struct to use for page fault accounting, or
1106 * NULL if faults are not to be recorded.
1107 * @mm: mm_struct of target mm
1108 * @start: starting user address
1109 * @nr_pages: number of pages from start to pin
9beae1ea 1110 * @gup_flags: flags modifying lookup behaviour
4bbd4c77
KS
1111 * @pages: array that receives pointers to the pages pinned.
1112 * Should be at least nr_pages long. Or NULL, if caller
1113 * only intends to ensure the pages are faulted in.
1114 * @vmas: array of pointers to vmas corresponding to each page.
1115 * Or NULL if the caller does not require them.
5b56d49f
LS
1116 * @locked: pointer to lock flag indicating whether lock is held and
1117 * subsequently whether VM_FAULT_RETRY functionality can be
1118 * utilised. Lock must initially be held.
4bbd4c77
KS
1119 *
1120 * Returns number of pages pinned. This may be fewer than the number
1121 * requested. If nr_pages is 0 or negative, returns 0. If no pages
1122 * were pinned, returns -errno. Each page returned must be released
1123 * with a put_page() call when it is finished with. vmas will only
1124 * remain valid while mmap_sem is held.
1125 *
1126 * Must be called with mmap_sem held for read or write.
1127 *
1128 * get_user_pages walks a process's page tables and takes a reference to
1129 * each struct page that each user address corresponds to at a given
1130 * instant. That is, it takes the page that would be accessed if a user
1131 * thread accesses the given user virtual address at that instant.
1132 *
1133 * This does not guarantee that the page exists in the user mappings when
1134 * get_user_pages returns, and there may even be a completely different
1135 * page there in some cases (eg. if mmapped pagecache has been invalidated
1136 * and subsequently re faulted). However it does guarantee that the page
1137 * won't be freed completely. And mostly callers simply care that the page
1138 * contains data that was valid *at some point in time*. Typically, an IO
1139 * or similar operation cannot guarantee anything stronger anyway because
1140 * locks can't be held over the syscall boundary.
1141 *
9beae1ea
LS
1142 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1143 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1144 * be called after the page is finished with, and before put_page is called.
4bbd4c77
KS
1145 *
1146 * get_user_pages is typically used for fewer-copy IO operations, to get a
1147 * handle on the memory by some means other than accesses via the user virtual
1148 * addresses. The pages may be submitted for DMA to devices or accessed via
1149 * their kernel linear mapping (via the kmap APIs). Care should be taken to
1150 * use the correct cache flushing APIs.
1151 *
1152 * See also get_user_pages_fast, for performance critical applications.
f0818f47
AA
1153 *
1154 * get_user_pages should be phased out in favor of
1155 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1156 * should use get_user_pages because it cannot pass
1157 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
4bbd4c77 1158 */
1e987790
DH
1159long get_user_pages_remote(struct task_struct *tsk, struct mm_struct *mm,
1160 unsigned long start, unsigned long nr_pages,
9beae1ea 1161 unsigned int gup_flags, struct page **pages,
5b56d49f 1162 struct vm_area_struct **vmas, int *locked)
4bbd4c77 1163{
932f4a63
IW
1164 /*
1165 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1166 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1167 * vmas. As there are no users of this flag in this call we simply
1168 * disallow this option for now.
1169 */
1170 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1171 return -EINVAL;
1172
859110d7 1173 return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
e716712f 1174 locked,
9beae1ea 1175 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1e987790
DH
1176}
1177EXPORT_SYMBOL(get_user_pages_remote);
1178
d3649f68
CH
1179/**
1180 * populate_vma_page_range() - populate a range of pages in the vma.
1181 * @vma: target vma
1182 * @start: start address
1183 * @end: end address
1184 * @nonblocking:
1185 *
1186 * This takes care of mlocking the pages too if VM_LOCKED is set.
1187 *
1188 * return 0 on success, negative error code on error.
1189 *
1190 * vma->vm_mm->mmap_sem must be held.
1191 *
1192 * If @nonblocking is NULL, it may be held for read or write and will
1193 * be unperturbed.
1194 *
1195 * If @nonblocking is non-NULL, it must held for read only and may be
1196 * released. If it's released, *@nonblocking will be set to 0.
1197 */
1198long populate_vma_page_range(struct vm_area_struct *vma,
1199 unsigned long start, unsigned long end, int *nonblocking)
1200{
1201 struct mm_struct *mm = vma->vm_mm;
1202 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1203 int gup_flags;
1204
1205 VM_BUG_ON(start & ~PAGE_MASK);
1206 VM_BUG_ON(end & ~PAGE_MASK);
1207 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1208 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1209 VM_BUG_ON_MM(!rwsem_is_locked(&mm->mmap_sem), mm);
1210
1211 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1212 if (vma->vm_flags & VM_LOCKONFAULT)
1213 gup_flags &= ~FOLL_POPULATE;
1214 /*
1215 * We want to touch writable mappings with a write fault in order
1216 * to break COW, except for shared mappings because these don't COW
1217 * and we would not want to dirty them for nothing.
1218 */
1219 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1220 gup_flags |= FOLL_WRITE;
1221
1222 /*
1223 * We want mlock to succeed for regions that have any permissions
1224 * other than PROT_NONE.
1225 */
1226 if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
1227 gup_flags |= FOLL_FORCE;
1228
1229 /*
1230 * We made sure addr is within a VMA, so the following will
1231 * not result in a stack expansion that recurses back here.
1232 */
1233 return __get_user_pages(current, mm, start, nr_pages, gup_flags,
1234 NULL, NULL, nonblocking);
1235}
1236
1237/*
1238 * __mm_populate - populate and/or mlock pages within a range of address space.
1239 *
1240 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1241 * flags. VMAs must be already marked with the desired vm_flags, and
1242 * mmap_sem must not be held.
1243 */
1244int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1245{
1246 struct mm_struct *mm = current->mm;
1247 unsigned long end, nstart, nend;
1248 struct vm_area_struct *vma = NULL;
1249 int locked = 0;
1250 long ret = 0;
1251
1252 end = start + len;
1253
1254 for (nstart = start; nstart < end; nstart = nend) {
1255 /*
1256 * We want to fault in pages for [nstart; end) address range.
1257 * Find first corresponding VMA.
1258 */
1259 if (!locked) {
1260 locked = 1;
1261 down_read(&mm->mmap_sem);
1262 vma = find_vma(mm, nstart);
1263 } else if (nstart >= vma->vm_end)
1264 vma = vma->vm_next;
1265 if (!vma || vma->vm_start >= end)
1266 break;
1267 /*
1268 * Set [nstart; nend) to intersection of desired address
1269 * range with the first VMA. Also, skip undesirable VMA types.
1270 */
1271 nend = min(end, vma->vm_end);
1272 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1273 continue;
1274 if (nstart < vma->vm_start)
1275 nstart = vma->vm_start;
1276 /*
1277 * Now fault in a range of pages. populate_vma_page_range()
1278 * double checks the vma flags, so that it won't mlock pages
1279 * if the vma was already munlocked.
1280 */
1281 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1282 if (ret < 0) {
1283 if (ignore_errors) {
1284 ret = 0;
1285 continue; /* continue at next VMA */
1286 }
1287 break;
1288 }
1289 nend = nstart + ret * PAGE_SIZE;
1290 ret = 0;
1291 }
1292 if (locked)
1293 up_read(&mm->mmap_sem);
1294 return ret; /* 0 or negative error code */
1295}
1296
1297/**
1298 * get_dump_page() - pin user page in memory while writing it to core dump
1299 * @addr: user address
1300 *
1301 * Returns struct page pointer of user page pinned for dump,
1302 * to be freed afterwards by put_page().
1303 *
1304 * Returns NULL on any kind of failure - a hole must then be inserted into
1305 * the corefile, to preserve alignment with its headers; and also returns
1306 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1307 * allowing a hole to be left in the corefile to save diskspace.
1308 *
1309 * Called without mmap_sem, but after all other threads have been killed.
1310 */
1311#ifdef CONFIG_ELF_CORE
1312struct page *get_dump_page(unsigned long addr)
1313{
1314 struct vm_area_struct *vma;
1315 struct page *page;
1316
1317 if (__get_user_pages(current, current->mm, addr, 1,
1318 FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
1319 NULL) < 1)
1320 return NULL;
1321 flush_cache_page(vma, addr, page_to_pfn(page));
1322 return page;
1323}
1324#endif /* CONFIG_ELF_CORE */
1325
9a4e9f3b 1326#if defined(CONFIG_FS_DAX) || defined (CONFIG_CMA)
9a4e9f3b
AK
1327static bool check_dax_vmas(struct vm_area_struct **vmas, long nr_pages)
1328{
1329 long i;
1330 struct vm_area_struct *vma_prev = NULL;
1331
1332 for (i = 0; i < nr_pages; i++) {
1333 struct vm_area_struct *vma = vmas[i];
1334
1335 if (vma == vma_prev)
1336 continue;
1337
1338 vma_prev = vma;
1339
1340 if (vma_is_fsdax(vma))
1341 return true;
1342 }
1343 return false;
1344}
9a4e9f3b
AK
1345
1346#ifdef CONFIG_CMA
1347static struct page *new_non_cma_page(struct page *page, unsigned long private)
1348{
1349 /*
1350 * We want to make sure we allocate the new page from the same node
1351 * as the source page.
1352 */
1353 int nid = page_to_nid(page);
1354 /*
1355 * Trying to allocate a page for migration. Ignore allocation
1356 * failure warnings. We don't force __GFP_THISNODE here because
1357 * this node here is the node where we have CMA reservation and
1358 * in some case these nodes will have really less non movable
1359 * allocation memory.
1360 */
1361 gfp_t gfp_mask = GFP_USER | __GFP_NOWARN;
1362
1363 if (PageHighMem(page))
1364 gfp_mask |= __GFP_HIGHMEM;
1365
1366#ifdef CONFIG_HUGETLB_PAGE
1367 if (PageHuge(page)) {
1368 struct hstate *h = page_hstate(page);
1369 /*
1370 * We don't want to dequeue from the pool because pool pages will
1371 * mostly be from the CMA region.
1372 */
1373 return alloc_migrate_huge_page(h, gfp_mask, nid, NULL);
1374 }
1375#endif
1376 if (PageTransHuge(page)) {
1377 struct page *thp;
1378 /*
1379 * ignore allocation failure warnings
1380 */
1381 gfp_t thp_gfpmask = GFP_TRANSHUGE | __GFP_NOWARN;
1382
1383 /*
1384 * Remove the movable mask so that we don't allocate from
1385 * CMA area again.
1386 */
1387 thp_gfpmask &= ~__GFP_MOVABLE;
1388 thp = __alloc_pages_node(nid, thp_gfpmask, HPAGE_PMD_ORDER);
1389 if (!thp)
1390 return NULL;
1391 prep_transhuge_page(thp);
1392 return thp;
1393 }
1394
1395 return __alloc_pages_node(nid, gfp_mask, 0);
1396}
1397
932f4a63
IW
1398static long check_and_migrate_cma_pages(struct task_struct *tsk,
1399 struct mm_struct *mm,
1400 unsigned long start,
1401 unsigned long nr_pages,
9a4e9f3b 1402 struct page **pages,
932f4a63
IW
1403 struct vm_area_struct **vmas,
1404 unsigned int gup_flags)
9a4e9f3b
AK
1405{
1406 long i;
1407 bool drain_allow = true;
1408 bool migrate_allow = true;
1409 LIST_HEAD(cma_page_list);
1410
1411check_again:
1412 for (i = 0; i < nr_pages; i++) {
1413 /*
1414 * If we get a page from the CMA zone, since we are going to
1415 * be pinning these entries, we might as well move them out
1416 * of the CMA zone if possible.
1417 */
1418 if (is_migrate_cma_page(pages[i])) {
1419
1420 struct page *head = compound_head(pages[i]);
1421
1422 if (PageHuge(head)) {
1423 isolate_huge_page(head, &cma_page_list);
1424 } else {
1425 if (!PageLRU(head) && drain_allow) {
1426 lru_add_drain_all();
1427 drain_allow = false;
1428 }
1429
1430 if (!isolate_lru_page(head)) {
1431 list_add_tail(&head->lru, &cma_page_list);
1432 mod_node_page_state(page_pgdat(head),
1433 NR_ISOLATED_ANON +
1434 page_is_file_cache(head),
1435 hpage_nr_pages(head));
1436 }
1437 }
1438 }
1439 }
1440
1441 if (!list_empty(&cma_page_list)) {
1442 /*
1443 * drop the above get_user_pages reference.
1444 */
1445 for (i = 0; i < nr_pages; i++)
1446 put_page(pages[i]);
1447
1448 if (migrate_pages(&cma_page_list, new_non_cma_page,
1449 NULL, 0, MIGRATE_SYNC, MR_CONTIG_RANGE)) {
1450 /*
1451 * some of the pages failed migration. Do get_user_pages
1452 * without migration.
1453 */
1454 migrate_allow = false;
1455
1456 if (!list_empty(&cma_page_list))
1457 putback_movable_pages(&cma_page_list);
1458 }
1459 /*
932f4a63
IW
1460 * We did migrate all the pages, Try to get the page references
1461 * again migrating any new CMA pages which we failed to isolate
1462 * earlier.
9a4e9f3b 1463 */
932f4a63
IW
1464 nr_pages = __get_user_pages_locked(tsk, mm, start, nr_pages,
1465 pages, vmas, NULL,
1466 gup_flags);
1467
9a4e9f3b
AK
1468 if ((nr_pages > 0) && migrate_allow) {
1469 drain_allow = true;
1470 goto check_again;
1471 }
1472 }
1473
1474 return nr_pages;
1475}
1476#else
932f4a63
IW
1477static long check_and_migrate_cma_pages(struct task_struct *tsk,
1478 struct mm_struct *mm,
1479 unsigned long start,
1480 unsigned long nr_pages,
1481 struct page **pages,
1482 struct vm_area_struct **vmas,
1483 unsigned int gup_flags)
9a4e9f3b
AK
1484{
1485 return nr_pages;
1486}
1487#endif
1488
2bb6d283 1489/*
932f4a63
IW
1490 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1491 * allows us to process the FOLL_LONGTERM flag.
2bb6d283 1492 */
932f4a63
IW
1493static long __gup_longterm_locked(struct task_struct *tsk,
1494 struct mm_struct *mm,
1495 unsigned long start,
1496 unsigned long nr_pages,
1497 struct page **pages,
1498 struct vm_area_struct **vmas,
1499 unsigned int gup_flags)
2bb6d283 1500{
932f4a63
IW
1501 struct vm_area_struct **vmas_tmp = vmas;
1502 unsigned long flags = 0;
2bb6d283
DW
1503 long rc, i;
1504
932f4a63
IW
1505 if (gup_flags & FOLL_LONGTERM) {
1506 if (!pages)
1507 return -EINVAL;
1508
1509 if (!vmas_tmp) {
1510 vmas_tmp = kcalloc(nr_pages,
1511 sizeof(struct vm_area_struct *),
1512 GFP_KERNEL);
1513 if (!vmas_tmp)
1514 return -ENOMEM;
1515 }
1516 flags = memalloc_nocma_save();
2bb6d283
DW
1517 }
1518
932f4a63
IW
1519 rc = __get_user_pages_locked(tsk, mm, start, nr_pages, pages,
1520 vmas_tmp, NULL, gup_flags);
2bb6d283 1521
932f4a63
IW
1522 if (gup_flags & FOLL_LONGTERM) {
1523 memalloc_nocma_restore(flags);
1524 if (rc < 0)
1525 goto out;
1526
1527 if (check_dax_vmas(vmas_tmp, rc)) {
1528 for (i = 0; i < rc; i++)
1529 put_page(pages[i]);
1530 rc = -EOPNOTSUPP;
1531 goto out;
1532 }
1533
1534 rc = check_and_migrate_cma_pages(tsk, mm, start, rc, pages,
1535 vmas_tmp, gup_flags);
9a4e9f3b 1536 }
2bb6d283 1537
2bb6d283 1538out:
932f4a63
IW
1539 if (vmas_tmp != vmas)
1540 kfree(vmas_tmp);
2bb6d283
DW
1541 return rc;
1542}
932f4a63
IW
1543#else /* !CONFIG_FS_DAX && !CONFIG_CMA */
1544static __always_inline long __gup_longterm_locked(struct task_struct *tsk,
1545 struct mm_struct *mm,
1546 unsigned long start,
1547 unsigned long nr_pages,
1548 struct page **pages,
1549 struct vm_area_struct **vmas,
1550 unsigned int flags)
1551{
1552 return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
1553 NULL, flags);
1554}
1555#endif /* CONFIG_FS_DAX || CONFIG_CMA */
1556
1557/*
1558 * This is the same as get_user_pages_remote(), just with a
1559 * less-flexible calling convention where we assume that the task
1560 * and mm being operated on are the current task's and don't allow
1561 * passing of a locked parameter. We also obviously don't pass
1562 * FOLL_REMOTE in here.
1563 */
1564long get_user_pages(unsigned long start, unsigned long nr_pages,
1565 unsigned int gup_flags, struct page **pages,
1566 struct vm_area_struct **vmas)
1567{
1568 return __gup_longterm_locked(current, current->mm, start, nr_pages,
1569 pages, vmas, gup_flags | FOLL_TOUCH);
1570}
1571EXPORT_SYMBOL(get_user_pages);
2bb6d283 1572
d3649f68
CH
1573/*
1574 * We can leverage the VM_FAULT_RETRY functionality in the page fault
1575 * paths better by using either get_user_pages_locked() or
1576 * get_user_pages_unlocked().
acc3c8d1 1577 *
d3649f68 1578 * get_user_pages_locked() is suitable to replace the form:
acc3c8d1 1579 *
d3649f68
CH
1580 * down_read(&mm->mmap_sem);
1581 * do_something()
1582 * get_user_pages(tsk, mm, ..., pages, NULL);
1583 * up_read(&mm->mmap_sem);
acc3c8d1 1584 *
d3649f68 1585 * to:
acc3c8d1 1586 *
d3649f68
CH
1587 * int locked = 1;
1588 * down_read(&mm->mmap_sem);
1589 * do_something()
1590 * get_user_pages_locked(tsk, mm, ..., pages, &locked);
1591 * if (locked)
1592 * up_read(&mm->mmap_sem);
acc3c8d1 1593 */
d3649f68
CH
1594long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1595 unsigned int gup_flags, struct page **pages,
1596 int *locked)
acc3c8d1 1597{
acc3c8d1 1598 /*
d3649f68
CH
1599 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1600 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1601 * vmas. As there are no users of this flag in this call we simply
1602 * disallow this option for now.
acc3c8d1 1603 */
d3649f68
CH
1604 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1605 return -EINVAL;
acc3c8d1 1606
d3649f68
CH
1607 return __get_user_pages_locked(current, current->mm, start, nr_pages,
1608 pages, NULL, locked,
1609 gup_flags | FOLL_TOUCH);
acc3c8d1 1610}
d3649f68 1611EXPORT_SYMBOL(get_user_pages_locked);
acc3c8d1
KS
1612
1613/*
d3649f68 1614 * get_user_pages_unlocked() is suitable to replace the form:
acc3c8d1 1615 *
d3649f68
CH
1616 * down_read(&mm->mmap_sem);
1617 * get_user_pages(tsk, mm, ..., pages, NULL);
1618 * up_read(&mm->mmap_sem);
1619 *
1620 * with:
1621 *
1622 * get_user_pages_unlocked(tsk, mm, ..., pages);
1623 *
1624 * It is functionally equivalent to get_user_pages_fast so
1625 * get_user_pages_fast should be used instead if specific gup_flags
1626 * (e.g. FOLL_FORCE) are not required.
acc3c8d1 1627 */
d3649f68
CH
1628long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
1629 struct page **pages, unsigned int gup_flags)
acc3c8d1
KS
1630{
1631 struct mm_struct *mm = current->mm;
d3649f68
CH
1632 int locked = 1;
1633 long ret;
acc3c8d1 1634
d3649f68
CH
1635 /*
1636 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1637 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1638 * vmas. As there are no users of this flag in this call we simply
1639 * disallow this option for now.
1640 */
1641 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1642 return -EINVAL;
acc3c8d1 1643
d3649f68
CH
1644 down_read(&mm->mmap_sem);
1645 ret = __get_user_pages_locked(current, mm, start, nr_pages, pages, NULL,
1646 &locked, gup_flags | FOLL_TOUCH);
acc3c8d1
KS
1647 if (locked)
1648 up_read(&mm->mmap_sem);
d3649f68 1649 return ret;
4bbd4c77 1650}
d3649f68 1651EXPORT_SYMBOL(get_user_pages_unlocked);
2667f50e
SC
1652
1653/*
67a929e0 1654 * Fast GUP
2667f50e
SC
1655 *
1656 * get_user_pages_fast attempts to pin user pages by walking the page
1657 * tables directly and avoids taking locks. Thus the walker needs to be
1658 * protected from page table pages being freed from under it, and should
1659 * block any THP splits.
1660 *
1661 * One way to achieve this is to have the walker disable interrupts, and
1662 * rely on IPIs from the TLB flushing code blocking before the page table
1663 * pages are freed. This is unsuitable for architectures that do not need
1664 * to broadcast an IPI when invalidating TLBs.
1665 *
1666 * Another way to achieve this is to batch up page table containing pages
1667 * belonging to more than one mm_user, then rcu_sched a callback to free those
1668 * pages. Disabling interrupts will allow the fast_gup walker to both block
1669 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
1670 * (which is a relatively rare event). The code below adopts this strategy.
1671 *
1672 * Before activating this code, please be aware that the following assumptions
1673 * are currently made:
1674 *
e585513b
KS
1675 * *) Either HAVE_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
1676 * free pages containing page tables or TLB flushing requires IPI broadcast.
2667f50e 1677 *
2667f50e
SC
1678 * *) ptes can be read atomically by the architecture.
1679 *
1680 * *) access_ok is sufficient to validate userspace address ranges.
1681 *
1682 * The last two assumptions can be relaxed by the addition of helper functions.
1683 *
1684 * This code is based heavily on the PowerPC implementation by Nick Piggin.
1685 */
67a929e0 1686#ifdef CONFIG_HAVE_FAST_GUP
39656e83
CH
1687#ifdef CONFIG_GUP_GET_PTE_LOW_HIGH
1688/*
1689 * WARNING: only to be used in the get_user_pages_fast() implementation.
1690 *
1691 * With get_user_pages_fast(), we walk down the pagetables without taking any
1692 * locks. For this we would like to load the pointers atomically, but sometimes
1693 * that is not possible (e.g. without expensive cmpxchg8b on x86_32 PAE). What
1694 * we do have is the guarantee that a PTE will only either go from not present
1695 * to present, or present to not present or both -- it will not switch to a
1696 * completely different present page without a TLB flush in between; something
1697 * that we are blocking by holding interrupts off.
1698 *
1699 * Setting ptes from not present to present goes:
1700 *
1701 * ptep->pte_high = h;
1702 * smp_wmb();
1703 * ptep->pte_low = l;
1704 *
1705 * And present to not present goes:
1706 *
1707 * ptep->pte_low = 0;
1708 * smp_wmb();
1709 * ptep->pte_high = 0;
1710 *
1711 * We must ensure here that the load of pte_low sees 'l' IFF pte_high sees 'h'.
1712 * We load pte_high *after* loading pte_low, which ensures we don't see an older
1713 * value of pte_high. *Then* we recheck pte_low, which ensures that we haven't
1714 * picked up a changed pte high. We might have gotten rubbish values from
1715 * pte_low and pte_high, but we are guaranteed that pte_low will not have the
1716 * present bit set *unless* it is 'l'. Because get_user_pages_fast() only
1717 * operates on present ptes we're safe.
1718 */
1719static inline pte_t gup_get_pte(pte_t *ptep)
1720{
1721 pte_t pte;
2667f50e 1722
39656e83
CH
1723 do {
1724 pte.pte_low = ptep->pte_low;
1725 smp_rmb();
1726 pte.pte_high = ptep->pte_high;
1727 smp_rmb();
1728 } while (unlikely(pte.pte_low != ptep->pte_low));
1729
1730 return pte;
1731}
1732#else /* CONFIG_GUP_GET_PTE_LOW_HIGH */
0005d20b 1733/*
39656e83 1734 * We require that the PTE can be read atomically.
0005d20b
KS
1735 */
1736static inline pte_t gup_get_pte(pte_t *ptep)
1737{
1738 return READ_ONCE(*ptep);
1739}
39656e83 1740#endif /* CONFIG_GUP_GET_PTE_LOW_HIGH */
0005d20b 1741
b59f65fa
KS
1742static void undo_dev_pagemap(int *nr, int nr_start, struct page **pages)
1743{
1744 while ((*nr) - nr_start) {
1745 struct page *page = pages[--(*nr)];
1746
1747 ClearPageReferenced(page);
1748 put_page(page);
1749 }
1750}
1751
8fde12ca
LT
1752/*
1753 * Return the compund head page with ref appropriately incremented,
1754 * or NULL if that failed.
1755 */
1756static inline struct page *try_get_compound_head(struct page *page, int refs)
1757{
1758 struct page *head = compound_head(page);
1759 if (WARN_ON_ONCE(page_ref_count(head) < 0))
1760 return NULL;
1761 if (unlikely(!page_cache_add_speculative(head, refs)))
1762 return NULL;
1763 return head;
1764}
1765
3010a5ea 1766#ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2667f50e 1767static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
b798bec4 1768 unsigned int flags, struct page **pages, int *nr)
2667f50e 1769{
b59f65fa
KS
1770 struct dev_pagemap *pgmap = NULL;
1771 int nr_start = *nr, ret = 0;
2667f50e 1772 pte_t *ptep, *ptem;
2667f50e
SC
1773
1774 ptem = ptep = pte_offset_map(&pmd, addr);
1775 do {
0005d20b 1776 pte_t pte = gup_get_pte(ptep);
7aef4172 1777 struct page *head, *page;
2667f50e
SC
1778
1779 /*
1780 * Similar to the PMD case below, NUMA hinting must take slow
8a0516ed 1781 * path using the pte_protnone check.
2667f50e 1782 */
e7884f8e
KS
1783 if (pte_protnone(pte))
1784 goto pte_unmap;
1785
b798bec4 1786 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
e7884f8e
KS
1787 goto pte_unmap;
1788
b59f65fa 1789 if (pte_devmap(pte)) {
7af75561
IW
1790 if (unlikely(flags & FOLL_LONGTERM))
1791 goto pte_unmap;
1792
b59f65fa
KS
1793 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
1794 if (unlikely(!pgmap)) {
1795 undo_dev_pagemap(nr, nr_start, pages);
1796 goto pte_unmap;
1797 }
1798 } else if (pte_special(pte))
2667f50e
SC
1799 goto pte_unmap;
1800
1801 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
1802 page = pte_page(pte);
1803
8fde12ca
LT
1804 head = try_get_compound_head(page, 1);
1805 if (!head)
2667f50e
SC
1806 goto pte_unmap;
1807
1808 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
7aef4172 1809 put_page(head);
2667f50e
SC
1810 goto pte_unmap;
1811 }
1812
7aef4172 1813 VM_BUG_ON_PAGE(compound_head(page) != head, page);
e9348053
KS
1814
1815 SetPageReferenced(page);
2667f50e
SC
1816 pages[*nr] = page;
1817 (*nr)++;
1818
1819 } while (ptep++, addr += PAGE_SIZE, addr != end);
1820
1821 ret = 1;
1822
1823pte_unmap:
832d7aa0
CH
1824 if (pgmap)
1825 put_dev_pagemap(pgmap);
2667f50e
SC
1826 pte_unmap(ptem);
1827 return ret;
1828}
1829#else
1830
1831/*
1832 * If we can't determine whether or not a pte is special, then fail immediately
1833 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
1834 * to be special.
1835 *
1836 * For a futex to be placed on a THP tail page, get_futex_key requires a
1837 * __get_user_pages_fast implementation that can pin pages. Thus it's still
1838 * useful to have gup_huge_pmd even if we can't operate on ptes.
1839 */
1840static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
b798bec4 1841 unsigned int flags, struct page **pages, int *nr)
2667f50e
SC
1842{
1843 return 0;
1844}
3010a5ea 1845#endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2667f50e 1846
09180ca4 1847#if defined(__HAVE_ARCH_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
b59f65fa
KS
1848static int __gup_device_huge(unsigned long pfn, unsigned long addr,
1849 unsigned long end, struct page **pages, int *nr)
1850{
1851 int nr_start = *nr;
1852 struct dev_pagemap *pgmap = NULL;
1853
1854 do {
1855 struct page *page = pfn_to_page(pfn);
1856
1857 pgmap = get_dev_pagemap(pfn, pgmap);
1858 if (unlikely(!pgmap)) {
1859 undo_dev_pagemap(nr, nr_start, pages);
1860 return 0;
1861 }
1862 SetPageReferenced(page);
1863 pages[*nr] = page;
1864 get_page(page);
b59f65fa
KS
1865 (*nr)++;
1866 pfn++;
1867 } while (addr += PAGE_SIZE, addr != end);
832d7aa0
CH
1868
1869 if (pgmap)
1870 put_dev_pagemap(pgmap);
b59f65fa
KS
1871 return 1;
1872}
1873
a9b6de77 1874static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
b59f65fa
KS
1875 unsigned long end, struct page **pages, int *nr)
1876{
1877 unsigned long fault_pfn;
a9b6de77
DW
1878 int nr_start = *nr;
1879
1880 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
1881 if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1882 return 0;
b59f65fa 1883
a9b6de77
DW
1884 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1885 undo_dev_pagemap(nr, nr_start, pages);
1886 return 0;
1887 }
1888 return 1;
b59f65fa
KS
1889}
1890
a9b6de77 1891static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
b59f65fa
KS
1892 unsigned long end, struct page **pages, int *nr)
1893{
1894 unsigned long fault_pfn;
a9b6de77
DW
1895 int nr_start = *nr;
1896
1897 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
1898 if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1899 return 0;
b59f65fa 1900
a9b6de77
DW
1901 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1902 undo_dev_pagemap(nr, nr_start, pages);
1903 return 0;
1904 }
1905 return 1;
b59f65fa
KS
1906}
1907#else
a9b6de77 1908static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
b59f65fa
KS
1909 unsigned long end, struct page **pages, int *nr)
1910{
1911 BUILD_BUG();
1912 return 0;
1913}
1914
a9b6de77 1915static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
b59f65fa
KS
1916 unsigned long end, struct page **pages, int *nr)
1917{
1918 BUILD_BUG();
1919 return 0;
1920}
1921#endif
1922
2667f50e 1923static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
b798bec4 1924 unsigned long end, unsigned int flags, struct page **pages, int *nr)
2667f50e 1925{
ddc58f27 1926 struct page *head, *page;
2667f50e
SC
1927 int refs;
1928
b798bec4 1929 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2667f50e
SC
1930 return 0;
1931
7af75561
IW
1932 if (pmd_devmap(orig)) {
1933 if (unlikely(flags & FOLL_LONGTERM))
1934 return 0;
a9b6de77 1935 return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
7af75561 1936 }
b59f65fa 1937
2667f50e 1938 refs = 0;
d63206ee 1939 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2667f50e 1940 do {
2667f50e
SC
1941 pages[*nr] = page;
1942 (*nr)++;
1943 page++;
1944 refs++;
1945 } while (addr += PAGE_SIZE, addr != end);
1946
8fde12ca
LT
1947 head = try_get_compound_head(pmd_page(orig), refs);
1948 if (!head) {
2667f50e
SC
1949 *nr -= refs;
1950 return 0;
1951 }
1952
1953 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1954 *nr -= refs;
1955 while (refs--)
1956 put_page(head);
1957 return 0;
1958 }
1959
e9348053 1960 SetPageReferenced(head);
2667f50e
SC
1961 return 1;
1962}
1963
1964static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
b798bec4 1965 unsigned long end, unsigned int flags, struct page **pages, int *nr)
2667f50e 1966{
ddc58f27 1967 struct page *head, *page;
2667f50e
SC
1968 int refs;
1969
b798bec4 1970 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2667f50e
SC
1971 return 0;
1972
7af75561
IW
1973 if (pud_devmap(orig)) {
1974 if (unlikely(flags & FOLL_LONGTERM))
1975 return 0;
a9b6de77 1976 return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
7af75561 1977 }
b59f65fa 1978
2667f50e 1979 refs = 0;
d63206ee 1980 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2667f50e 1981 do {
2667f50e
SC
1982 pages[*nr] = page;
1983 (*nr)++;
1984 page++;
1985 refs++;
1986 } while (addr += PAGE_SIZE, addr != end);
1987
8fde12ca
LT
1988 head = try_get_compound_head(pud_page(orig), refs);
1989 if (!head) {
2667f50e
SC
1990 *nr -= refs;
1991 return 0;
1992 }
1993
1994 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1995 *nr -= refs;
1996 while (refs--)
1997 put_page(head);
1998 return 0;
1999 }
2000
e9348053 2001 SetPageReferenced(head);
2667f50e
SC
2002 return 1;
2003}
2004
f30c59e9 2005static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
b798bec4 2006 unsigned long end, unsigned int flags,
f30c59e9
AK
2007 struct page **pages, int *nr)
2008{
2009 int refs;
ddc58f27 2010 struct page *head, *page;
f30c59e9 2011
b798bec4 2012 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
f30c59e9
AK
2013 return 0;
2014
b59f65fa 2015 BUILD_BUG_ON(pgd_devmap(orig));
f30c59e9 2016 refs = 0;
d63206ee 2017 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
f30c59e9 2018 do {
f30c59e9
AK
2019 pages[*nr] = page;
2020 (*nr)++;
2021 page++;
2022 refs++;
2023 } while (addr += PAGE_SIZE, addr != end);
2024
8fde12ca
LT
2025 head = try_get_compound_head(pgd_page(orig), refs);
2026 if (!head) {
f30c59e9
AK
2027 *nr -= refs;
2028 return 0;
2029 }
2030
2031 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2032 *nr -= refs;
2033 while (refs--)
2034 put_page(head);
2035 return 0;
2036 }
2037
e9348053 2038 SetPageReferenced(head);
f30c59e9
AK
2039 return 1;
2040}
2041
2667f50e 2042static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
b798bec4 2043 unsigned int flags, struct page **pages, int *nr)
2667f50e
SC
2044{
2045 unsigned long next;
2046 pmd_t *pmdp;
2047
2048 pmdp = pmd_offset(&pud, addr);
2049 do {
38c5ce93 2050 pmd_t pmd = READ_ONCE(*pmdp);
2667f50e
SC
2051
2052 next = pmd_addr_end(addr, end);
84c3fc4e 2053 if (!pmd_present(pmd))
2667f50e
SC
2054 return 0;
2055
414fd080
YZ
2056 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2057 pmd_devmap(pmd))) {
2667f50e
SC
2058 /*
2059 * NUMA hinting faults need to be handled in the GUP
2060 * slowpath for accounting purposes and so that they
2061 * can be serialised against THP migration.
2062 */
8a0516ed 2063 if (pmd_protnone(pmd))
2667f50e
SC
2064 return 0;
2065
b798bec4 2066 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2667f50e
SC
2067 pages, nr))
2068 return 0;
2069
f30c59e9
AK
2070 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2071 /*
2072 * architecture have different format for hugetlbfs
2073 * pmd format and THP pmd format
2074 */
2075 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
b798bec4 2076 PMD_SHIFT, next, flags, pages, nr))
f30c59e9 2077 return 0;
b798bec4 2078 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2923117b 2079 return 0;
2667f50e
SC
2080 } while (pmdp++, addr = next, addr != end);
2081
2082 return 1;
2083}
2084
c2febafc 2085static int gup_pud_range(p4d_t p4d, unsigned long addr, unsigned long end,
b798bec4 2086 unsigned int flags, struct page **pages, int *nr)
2667f50e
SC
2087{
2088 unsigned long next;
2089 pud_t *pudp;
2090
c2febafc 2091 pudp = pud_offset(&p4d, addr);
2667f50e 2092 do {
e37c6982 2093 pud_t pud = READ_ONCE(*pudp);
2667f50e
SC
2094
2095 next = pud_addr_end(addr, end);
2096 if (pud_none(pud))
2097 return 0;
f30c59e9 2098 if (unlikely(pud_huge(pud))) {
b798bec4 2099 if (!gup_huge_pud(pud, pudp, addr, next, flags,
f30c59e9
AK
2100 pages, nr))
2101 return 0;
2102 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2103 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
b798bec4 2104 PUD_SHIFT, next, flags, pages, nr))
2667f50e 2105 return 0;
b798bec4 2106 } else if (!gup_pmd_range(pud, addr, next, flags, pages, nr))
2667f50e
SC
2107 return 0;
2108 } while (pudp++, addr = next, addr != end);
2109
2110 return 1;
2111}
2112
c2febafc 2113static int gup_p4d_range(pgd_t pgd, unsigned long addr, unsigned long end,
b798bec4 2114 unsigned int flags, struct page **pages, int *nr)
c2febafc
KS
2115{
2116 unsigned long next;
2117 p4d_t *p4dp;
2118
2119 p4dp = p4d_offset(&pgd, addr);
2120 do {
2121 p4d_t p4d = READ_ONCE(*p4dp);
2122
2123 next = p4d_addr_end(addr, end);
2124 if (p4d_none(p4d))
2125 return 0;
2126 BUILD_BUG_ON(p4d_huge(p4d));
2127 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2128 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
b798bec4 2129 P4D_SHIFT, next, flags, pages, nr))
c2febafc 2130 return 0;
b798bec4 2131 } else if (!gup_pud_range(p4d, addr, next, flags, pages, nr))
c2febafc
KS
2132 return 0;
2133 } while (p4dp++, addr = next, addr != end);
2134
2135 return 1;
2136}
2137
5b65c467 2138static void gup_pgd_range(unsigned long addr, unsigned long end,
b798bec4 2139 unsigned int flags, struct page **pages, int *nr)
5b65c467
KS
2140{
2141 unsigned long next;
2142 pgd_t *pgdp;
2143
2144 pgdp = pgd_offset(current->mm, addr);
2145 do {
2146 pgd_t pgd = READ_ONCE(*pgdp);
2147
2148 next = pgd_addr_end(addr, end);
2149 if (pgd_none(pgd))
2150 return;
2151 if (unlikely(pgd_huge(pgd))) {
b798bec4 2152 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
5b65c467
KS
2153 pages, nr))
2154 return;
2155 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2156 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
b798bec4 2157 PGDIR_SHIFT, next, flags, pages, nr))
5b65c467 2158 return;
b798bec4 2159 } else if (!gup_p4d_range(pgd, addr, next, flags, pages, nr))
5b65c467
KS
2160 return;
2161 } while (pgdp++, addr = next, addr != end);
2162}
2163
2164#ifndef gup_fast_permitted
2165/*
2166 * Check if it's allowed to use __get_user_pages_fast() for the range, or
2167 * we need to fall back to the slow version:
2168 */
26f4c328 2169static bool gup_fast_permitted(unsigned long start, unsigned long end)
5b65c467 2170{
26f4c328 2171 return true;
5b65c467
KS
2172}
2173#endif
2174
2667f50e
SC
2175/*
2176 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
d0811078
MT
2177 * the regular GUP.
2178 * Note a difference with get_user_pages_fast: this always returns the
2179 * number of pages pinned, 0 if no pages were pinned.
2667f50e
SC
2180 */
2181int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
2182 struct page **pages)
2183{
d4faa402 2184 unsigned long len, end;
5b65c467 2185 unsigned long flags;
2667f50e
SC
2186 int nr = 0;
2187
f455c854 2188 start = untagged_addr(start) & PAGE_MASK;
2667f50e
SC
2189 len = (unsigned long) nr_pages << PAGE_SHIFT;
2190 end = start + len;
2191
26f4c328
CH
2192 if (end <= start)
2193 return 0;
96d4f267 2194 if (unlikely(!access_ok((void __user *)start, len)))
2667f50e
SC
2195 return 0;
2196
2197 /*
2198 * Disable interrupts. We use the nested form as we can already have
2199 * interrupts disabled by get_futex_key.
2200 *
2201 * With interrupts disabled, we block page table pages from being
2ebe8228
FW
2202 * freed from under us. See struct mmu_table_batch comments in
2203 * include/asm-generic/tlb.h for more details.
2667f50e
SC
2204 *
2205 * We do not adopt an rcu_read_lock(.) here as we also want to
2206 * block IPIs that come from THPs splitting.
2207 */
2208
26f4c328 2209 if (gup_fast_permitted(start, end)) {
5b65c467 2210 local_irq_save(flags);
b798bec4 2211 gup_pgd_range(start, end, write ? FOLL_WRITE : 0, pages, &nr);
5b65c467
KS
2212 local_irq_restore(flags);
2213 }
2667f50e
SC
2214
2215 return nr;
2216}
2217
7af75561
IW
2218static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2219 unsigned int gup_flags, struct page **pages)
2220{
2221 int ret;
2222
2223 /*
2224 * FIXME: FOLL_LONGTERM does not work with
2225 * get_user_pages_unlocked() (see comments in that function)
2226 */
2227 if (gup_flags & FOLL_LONGTERM) {
2228 down_read(&current->mm->mmap_sem);
2229 ret = __gup_longterm_locked(current, current->mm,
2230 start, nr_pages,
2231 pages, NULL, gup_flags);
2232 up_read(&current->mm->mmap_sem);
2233 } else {
2234 ret = get_user_pages_unlocked(start, nr_pages,
2235 pages, gup_flags);
2236 }
2237
2238 return ret;
2239}
2240
2667f50e
SC
2241/**
2242 * get_user_pages_fast() - pin user pages in memory
2243 * @start: starting user address
2244 * @nr_pages: number of pages from start to pin
73b0140b 2245 * @gup_flags: flags modifying pin behaviour
2667f50e
SC
2246 * @pages: array that receives pointers to the pages pinned.
2247 * Should be at least nr_pages long.
2248 *
2249 * Attempt to pin user pages in memory without taking mm->mmap_sem.
2250 * If not successful, it will fall back to taking the lock and
2251 * calling get_user_pages().
2252 *
2253 * Returns number of pages pinned. This may be fewer than the number
2254 * requested. If nr_pages is 0 or negative, returns 0. If no pages
2255 * were pinned, returns -errno.
2256 */
73b0140b
IW
2257int get_user_pages_fast(unsigned long start, int nr_pages,
2258 unsigned int gup_flags, struct page **pages)
2667f50e 2259{
5b65c467 2260 unsigned long addr, len, end;
73e10a61 2261 int nr = 0, ret = 0;
2667f50e 2262
f455c854 2263 start = untagged_addr(start) & PAGE_MASK;
5b65c467
KS
2264 addr = start;
2265 len = (unsigned long) nr_pages << PAGE_SHIFT;
2266 end = start + len;
2267
26f4c328 2268 if (end <= start)
c61611f7 2269 return 0;
96d4f267 2270 if (unlikely(!access_ok((void __user *)start, len)))
c61611f7 2271 return -EFAULT;
73e10a61 2272
26f4c328 2273 if (gup_fast_permitted(start, end)) {
5b65c467 2274 local_irq_disable();
73b0140b 2275 gup_pgd_range(addr, end, gup_flags, pages, &nr);
5b65c467 2276 local_irq_enable();
73e10a61
KS
2277 ret = nr;
2278 }
2667f50e
SC
2279
2280 if (nr < nr_pages) {
2281 /* Try to get the remaining pages with get_user_pages */
2282 start += nr << PAGE_SHIFT;
2283 pages += nr;
2284
7af75561
IW
2285 ret = __gup_longterm_unlocked(start, nr_pages - nr,
2286 gup_flags, pages);
2667f50e
SC
2287
2288 /* Have to be a bit careful with return values */
2289 if (nr > 0) {
2290 if (ret < 0)
2291 ret = nr;
2292 else
2293 ret += nr;
2294 }
2295 }
2296
2297 return ret;
2298}
2299
e585513b 2300#endif /* CONFIG_HAVE_GENERIC_GUP */