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