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