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