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