GNU Linux-libre 4.14.290-gnu1
[releases.git] / mm / gup.c
1 #include <linux/kernel.h>
2 #include <linux/errno.h>
3 #include <linux/err.h>
4 #include <linux/spinlock.h>
5
6 #include <linux/mm.h>
7 #include <linux/memremap.h>
8 #include <linux/pagemap.h>
9 #include <linux/rmap.h>
10 #include <linux/swap.h>
11 #include <linux/swapops.h>
12
13 #include <linux/sched/signal.h>
14 #include <linux/rwsem.h>
15 #include <linux/hugetlb.h>
16
17 #include <asm/mmu_context.h>
18 #include <asm/pgtable.h>
19 #include <asm/tlbflush.h>
20
21 #include "internal.h"
22
23 static struct page *no_page_table(struct vm_area_struct *vma,
24                 unsigned int flags)
25 {
26         /*
27          * When core dumping an enormous anonymous area that nobody
28          * has touched so far, we don't want to allocate unnecessary pages or
29          * page tables.  Return error instead of NULL to skip handle_mm_fault,
30          * then get_dump_page() will return NULL to leave a hole in the dump.
31          * But we can only make this optimization where a hole would surely
32          * be zero-filled if handle_mm_fault() actually did handle it.
33          */
34         if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault))
35                 return ERR_PTR(-EFAULT);
36         return NULL;
37 }
38
39 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
40                 pte_t *pte, unsigned int flags)
41 {
42         /* No page to get reference */
43         if (flags & FOLL_GET)
44                 return -EFAULT;
45
46         if (flags & FOLL_TOUCH) {
47                 pte_t entry = *pte;
48
49                 if (flags & FOLL_WRITE)
50                         entry = pte_mkdirty(entry);
51                 entry = pte_mkyoung(entry);
52
53                 if (!pte_same(*pte, entry)) {
54                         set_pte_at(vma->vm_mm, address, pte, entry);
55                         update_mmu_cache(vma, address, pte);
56                 }
57         }
58
59         /* Proper page table entry exists, but no corresponding struct page */
60         return -EEXIST;
61 }
62
63 /*
64  * FOLL_FORCE or a forced COW break can write even to unwritable pte's,
65  * but only after we've gone through a COW cycle and they are dirty.
66  */
67 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
68 {
69         return pte_write(pte) || ((flags & FOLL_COW) && pte_dirty(pte));
70 }
71
72 /*
73  * A (separate) COW fault might break the page the other way and
74  * get_user_pages() would return the page from what is now the wrong
75  * VM. So we need to force a COW break at GUP time even for reads.
76  */
77 static inline bool should_force_cow_break(struct vm_area_struct *vma, unsigned int flags)
78 {
79         return is_cow_mapping(vma->vm_flags) && (flags & FOLL_GET);
80 }
81
82 static struct page *follow_page_pte(struct vm_area_struct *vma,
83                 unsigned long address, pmd_t *pmd, unsigned int flags)
84 {
85         struct mm_struct *mm = vma->vm_mm;
86         struct dev_pagemap *pgmap = NULL;
87         struct page *page;
88         spinlock_t *ptl;
89         pte_t *ptep, pte;
90
91 retry:
92         if (unlikely(pmd_bad(*pmd)))
93                 return no_page_table(vma, flags);
94
95         ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
96         pte = *ptep;
97         if (!pte_present(pte)) {
98                 swp_entry_t entry;
99                 /*
100                  * KSM's break_ksm() relies upon recognizing a ksm page
101                  * even while it is being migrated, so for that case we
102                  * need migration_entry_wait().
103                  */
104                 if (likely(!(flags & FOLL_MIGRATION)))
105                         goto no_page;
106                 if (pte_none(pte))
107                         goto no_page;
108                 entry = pte_to_swp_entry(pte);
109                 if (!is_migration_entry(entry))
110                         goto no_page;
111                 pte_unmap_unlock(ptep, ptl);
112                 migration_entry_wait(mm, pmd, address);
113                 goto retry;
114         }
115         if ((flags & FOLL_NUMA) && pte_protnone(pte))
116                 goto no_page;
117         if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
118                 pte_unmap_unlock(ptep, ptl);
119                 return NULL;
120         }
121
122         page = vm_normal_page(vma, address, pte);
123         if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
124                 /*
125                  * Only return device mapping pages in the FOLL_GET case since
126                  * they are only valid while holding the pgmap reference.
127                  */
128                 pgmap = get_dev_pagemap(pte_pfn(pte), NULL);
129                 if (pgmap)
130                         page = pte_page(pte);
131                 else
132                         goto no_page;
133         } else if (unlikely(!page)) {
134                 if (flags & FOLL_DUMP) {
135                         /* Avoid special (like zero) pages in core dumps */
136                         page = ERR_PTR(-EFAULT);
137                         goto out;
138                 }
139
140                 if (is_zero_pfn(pte_pfn(pte))) {
141                         page = pte_page(pte);
142                 } else {
143                         int ret;
144
145                         ret = follow_pfn_pte(vma, address, ptep, flags);
146                         page = ERR_PTR(ret);
147                         goto out;
148                 }
149         }
150
151         if (flags & FOLL_SPLIT && PageTransCompound(page)) {
152                 int ret;
153                 get_page(page);
154                 pte_unmap_unlock(ptep, ptl);
155                 lock_page(page);
156                 ret = split_huge_page(page);
157                 unlock_page(page);
158                 put_page(page);
159                 if (ret)
160                         return ERR_PTR(ret);
161                 goto retry;
162         }
163
164         if (flags & FOLL_GET) {
165                 if (unlikely(!try_get_page(page))) {
166                         page = ERR_PTR(-ENOMEM);
167                         goto out;
168                 }
169
170                 /* drop the pgmap reference now that we hold the page */
171                 if (pgmap) {
172                         put_dev_pagemap(pgmap);
173                         pgmap = NULL;
174                 }
175         }
176         if (flags & FOLL_TOUCH) {
177                 if ((flags & FOLL_WRITE) &&
178                     !pte_dirty(pte) && !PageDirty(page))
179                         set_page_dirty(page);
180                 /*
181                  * pte_mkyoung() would be more correct here, but atomic care
182                  * is needed to avoid losing the dirty bit: it is easier to use
183                  * mark_page_accessed().
184                  */
185                 mark_page_accessed(page);
186         }
187         if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
188                 /* Do not mlock pte-mapped THP */
189                 if (PageTransCompound(page))
190                         goto out;
191
192                 /*
193                  * The preliminary mapping check is mainly to avoid the
194                  * pointless overhead of lock_page on the ZERO_PAGE
195                  * which might bounce very badly if there is contention.
196                  *
197                  * If the page is already locked, we don't need to
198                  * handle it now - vmscan will handle it later if and
199                  * when it attempts to reclaim the page.
200                  */
201                 if (page->mapping && trylock_page(page)) {
202                         lru_add_drain();  /* push cached pages to LRU */
203                         /*
204                          * Because we lock page here, and migration is
205                          * blocked by the pte's page reference, and we
206                          * know the page is still mapped, we don't even
207                          * need to check for file-cache page truncation.
208                          */
209                         mlock_vma_page(page);
210                         unlock_page(page);
211                 }
212         }
213 out:
214         pte_unmap_unlock(ptep, ptl);
215         return page;
216 no_page:
217         pte_unmap_unlock(ptep, ptl);
218         if (!pte_none(pte))
219                 return NULL;
220         return no_page_table(vma, flags);
221 }
222
223 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
224                                     unsigned long address, pud_t *pudp,
225                                     unsigned int flags, unsigned int *page_mask)
226 {
227         pmd_t *pmd;
228         spinlock_t *ptl;
229         struct page *page;
230         struct mm_struct *mm = vma->vm_mm;
231
232         pmd = pmd_offset(pudp, address);
233         if (pmd_none(*pmd))
234                 return no_page_table(vma, flags);
235         if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) {
236                 page = follow_huge_pmd(mm, address, pmd, flags);
237                 if (page)
238                         return page;
239                 return no_page_table(vma, flags);
240         }
241         if (is_hugepd(__hugepd(pmd_val(*pmd)))) {
242                 page = follow_huge_pd(vma, address,
243                                       __hugepd(pmd_val(*pmd)), flags,
244                                       PMD_SHIFT);
245                 if (page)
246                         return page;
247                 return no_page_table(vma, flags);
248         }
249 retry:
250         if (!pmd_present(*pmd)) {
251                 if (likely(!(flags & FOLL_MIGRATION)))
252                         return no_page_table(vma, flags);
253                 VM_BUG_ON(thp_migration_supported() &&
254                                   !is_pmd_migration_entry(*pmd));
255                 if (is_pmd_migration_entry(*pmd))
256                         pmd_migration_entry_wait(mm, pmd);
257                 goto retry;
258         }
259         if (pmd_devmap(*pmd)) {
260                 ptl = pmd_lock(mm, pmd);
261                 page = follow_devmap_pmd(vma, address, pmd, flags);
262                 spin_unlock(ptl);
263                 if (page)
264                         return page;
265         }
266         if (likely(!pmd_trans_huge(*pmd)))
267                 return follow_page_pte(vma, address, pmd, flags);
268
269         if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
270                 return no_page_table(vma, flags);
271
272 retry_locked:
273         ptl = pmd_lock(mm, pmd);
274         if (unlikely(!pmd_present(*pmd))) {
275                 spin_unlock(ptl);
276                 if (likely(!(flags & FOLL_MIGRATION)))
277                         return no_page_table(vma, flags);
278                 pmd_migration_entry_wait(mm, pmd);
279                 goto retry_locked;
280         }
281         if (unlikely(!pmd_trans_huge(*pmd))) {
282                 spin_unlock(ptl);
283                 return follow_page_pte(vma, address, pmd, flags);
284         }
285         if (flags & FOLL_SPLIT) {
286                 int ret;
287                 page = pmd_page(*pmd);
288                 if (is_huge_zero_page(page)) {
289                         spin_unlock(ptl);
290                         ret = 0;
291                         split_huge_pmd(vma, pmd, address);
292                         if (pmd_trans_unstable(pmd))
293                                 ret = -EBUSY;
294                 } else {
295                         if (unlikely(!try_get_page(page))) {
296                                 spin_unlock(ptl);
297                                 return ERR_PTR(-ENOMEM);
298                         }
299                         spin_unlock(ptl);
300                         lock_page(page);
301                         ret = split_huge_page(page);
302                         unlock_page(page);
303                         put_page(page);
304                         if (pmd_none(*pmd))
305                                 return no_page_table(vma, flags);
306                 }
307
308                 return ret ? ERR_PTR(ret) :
309                         follow_page_pte(vma, address, pmd, flags);
310         }
311         page = follow_trans_huge_pmd(vma, address, pmd, flags);
312         spin_unlock(ptl);
313         *page_mask = HPAGE_PMD_NR - 1;
314         return page;
315 }
316
317
318 static struct page *follow_pud_mask(struct vm_area_struct *vma,
319                                     unsigned long address, p4d_t *p4dp,
320                                     unsigned int flags, unsigned int *page_mask)
321 {
322         pud_t *pud;
323         spinlock_t *ptl;
324         struct page *page;
325         struct mm_struct *mm = vma->vm_mm;
326
327         pud = pud_offset(p4dp, address);
328         if (pud_none(*pud))
329                 return no_page_table(vma, flags);
330         if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
331                 page = follow_huge_pud(mm, address, pud, flags);
332                 if (page)
333                         return page;
334                 return no_page_table(vma, flags);
335         }
336         if (is_hugepd(__hugepd(pud_val(*pud)))) {
337                 page = follow_huge_pd(vma, address,
338                                       __hugepd(pud_val(*pud)), flags,
339                                       PUD_SHIFT);
340                 if (page)
341                         return page;
342                 return no_page_table(vma, flags);
343         }
344         if (pud_devmap(*pud)) {
345                 ptl = pud_lock(mm, pud);
346                 page = follow_devmap_pud(vma, address, pud, flags);
347                 spin_unlock(ptl);
348                 if (page)
349                         return page;
350         }
351         if (unlikely(pud_bad(*pud)))
352                 return no_page_table(vma, flags);
353
354         return follow_pmd_mask(vma, address, pud, flags, page_mask);
355 }
356
357
358 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
359                                     unsigned long address, pgd_t *pgdp,
360                                     unsigned int flags, unsigned int *page_mask)
361 {
362         p4d_t *p4d;
363         struct page *page;
364
365         p4d = p4d_offset(pgdp, address);
366         if (p4d_none(*p4d))
367                 return no_page_table(vma, flags);
368         BUILD_BUG_ON(p4d_huge(*p4d));
369         if (unlikely(p4d_bad(*p4d)))
370                 return no_page_table(vma, flags);
371
372         if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
373                 page = follow_huge_pd(vma, address,
374                                       __hugepd(p4d_val(*p4d)), flags,
375                                       P4D_SHIFT);
376                 if (page)
377                         return page;
378                 return no_page_table(vma, flags);
379         }
380         return follow_pud_mask(vma, address, p4d, flags, page_mask);
381 }
382
383 /**
384  * follow_page_mask - look up a page descriptor from a user-virtual address
385  * @vma: vm_area_struct mapping @address
386  * @address: virtual address to look up
387  * @flags: flags modifying lookup behaviour
388  * @page_mask: on output, *page_mask is set according to the size of the page
389  *
390  * @flags can have FOLL_ flags set, defined in <linux/mm.h>
391  *
392  * Returns the mapped (struct page *), %NULL if no mapping exists, or
393  * an error pointer if there is a mapping to something not represented
394  * by a page descriptor (see also vm_normal_page()).
395  */
396 struct page *follow_page_mask(struct vm_area_struct *vma,
397                               unsigned long address, unsigned int flags,
398                               unsigned int *page_mask)
399 {
400         pgd_t *pgd;
401         struct page *page;
402         struct mm_struct *mm = vma->vm_mm;
403
404         *page_mask = 0;
405
406         /* make this handle hugepd */
407         page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
408         if (!IS_ERR(page)) {
409                 BUG_ON(flags & FOLL_GET);
410                 return page;
411         }
412
413         pgd = pgd_offset(mm, address);
414
415         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
416                 return no_page_table(vma, flags);
417
418         if (pgd_huge(*pgd)) {
419                 page = follow_huge_pgd(mm, address, pgd, flags);
420                 if (page)
421                         return page;
422                 return no_page_table(vma, flags);
423         }
424         if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
425                 page = follow_huge_pd(vma, address,
426                                       __hugepd(pgd_val(*pgd)), flags,
427                                       PGDIR_SHIFT);
428                 if (page)
429                         return page;
430                 return no_page_table(vma, flags);
431         }
432
433         return follow_p4d_mask(vma, address, pgd, flags, page_mask);
434 }
435
436 static int get_gate_page(struct mm_struct *mm, unsigned long address,
437                 unsigned int gup_flags, struct vm_area_struct **vma,
438                 struct page **page)
439 {
440         pgd_t *pgd;
441         p4d_t *p4d;
442         pud_t *pud;
443         pmd_t *pmd;
444         pte_t *pte;
445         int ret = -EFAULT;
446
447         /* user gate pages are read-only */
448         if (gup_flags & FOLL_WRITE)
449                 return -EFAULT;
450         if (address > TASK_SIZE)
451                 pgd = pgd_offset_k(address);
452         else
453                 pgd = pgd_offset_gate(mm, address);
454         if (pgd_none(*pgd))
455                 return -EFAULT;
456         p4d = p4d_offset(pgd, address);
457         if (p4d_none(*p4d))
458                 return -EFAULT;
459         pud = pud_offset(p4d, address);
460         if (pud_none(*pud))
461                 return -EFAULT;
462         pmd = pmd_offset(pud, address);
463         if (!pmd_present(*pmd))
464                 return -EFAULT;
465         VM_BUG_ON(pmd_trans_huge(*pmd));
466         pte = pte_offset_map(pmd, address);
467         if (pte_none(*pte))
468                 goto unmap;
469         *vma = get_gate_vma(mm);
470         if (!page)
471                 goto out;
472         *page = vm_normal_page(*vma, address, *pte);
473         if (!*page) {
474                 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
475                         goto unmap;
476                 *page = pte_page(*pte);
477
478                 /*
479                  * This should never happen (a device public page in the gate
480                  * area).
481                  */
482                 if (is_device_public_page(*page))
483                         goto unmap;
484         }
485         if (unlikely(!try_get_page(*page))) {
486                 ret = -ENOMEM;
487                 goto unmap;
488         }
489 out:
490         ret = 0;
491 unmap:
492         pte_unmap(pte);
493         return ret;
494 }
495
496 /*
497  * mmap_sem must be held on entry.  If @nonblocking != NULL and
498  * *@flags does not include FOLL_NOWAIT, the mmap_sem may be released.
499  * If it is, *@nonblocking will be set to 0 and -EBUSY returned.
500  */
501 static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
502                 unsigned long address, unsigned int *flags, int *nonblocking)
503 {
504         unsigned int fault_flags = 0;
505         int ret;
506
507         /* mlock all present pages, but do not fault in new pages */
508         if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
509                 return -ENOENT;
510         if (*flags & FOLL_WRITE)
511                 fault_flags |= FAULT_FLAG_WRITE;
512         if (*flags & FOLL_REMOTE)
513                 fault_flags |= FAULT_FLAG_REMOTE;
514         if (nonblocking)
515                 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
516         if (*flags & FOLL_NOWAIT)
517                 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
518         if (*flags & FOLL_TRIED) {
519                 VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
520                 fault_flags |= FAULT_FLAG_TRIED;
521         }
522
523         ret = handle_mm_fault(vma, address, fault_flags);
524         if (ret & VM_FAULT_ERROR) {
525                 int err = vm_fault_to_errno(ret, *flags);
526
527                 if (err)
528                         return err;
529                 BUG();
530         }
531
532         if (tsk) {
533                 if (ret & VM_FAULT_MAJOR)
534                         tsk->maj_flt++;
535                 else
536                         tsk->min_flt++;
537         }
538
539         if (ret & VM_FAULT_RETRY) {
540                 if (nonblocking)
541                         *nonblocking = 0;
542                 return -EBUSY;
543         }
544
545         /*
546          * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
547          * necessary, even if maybe_mkwrite decided not to set pte_write. We
548          * can thus safely do subsequent page lookups as if they were reads.
549          * But only do so when looping for pte_write is futile: in some cases
550          * userspace may also be wanting to write to the gotten user page,
551          * which a read fault here might prevent (a readonly page might get
552          * reCOWed by userspace write).
553          */
554         if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
555                 *flags |= FOLL_COW;
556         return 0;
557 }
558
559 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
560 {
561         vm_flags_t vm_flags = vma->vm_flags;
562         int write = (gup_flags & FOLL_WRITE);
563         int foreign = (gup_flags & FOLL_REMOTE);
564
565         if (vm_flags & (VM_IO | VM_PFNMAP))
566                 return -EFAULT;
567
568         if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
569                 return -EFAULT;
570
571         if (write) {
572                 if (!(vm_flags & VM_WRITE)) {
573                         if (!(gup_flags & FOLL_FORCE))
574                                 return -EFAULT;
575                         /*
576                          * We used to let the write,force case do COW in a
577                          * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
578                          * set a breakpoint in a read-only mapping of an
579                          * executable, without corrupting the file (yet only
580                          * when that file had been opened for writing!).
581                          * Anon pages in shared mappings are surprising: now
582                          * just reject it.
583                          */
584                         if (!is_cow_mapping(vm_flags))
585                                 return -EFAULT;
586                 }
587         } else if (!(vm_flags & VM_READ)) {
588                 if (!(gup_flags & FOLL_FORCE))
589                         return -EFAULT;
590                 /*
591                  * Is there actually any vma we can reach here which does not
592                  * have VM_MAYREAD set?
593                  */
594                 if (!(vm_flags & VM_MAYREAD))
595                         return -EFAULT;
596         }
597         /*
598          * gups are always data accesses, not instruction
599          * fetches, so execute=false here
600          */
601         if (!arch_vma_access_permitted(vma, write, false, foreign))
602                 return -EFAULT;
603         return 0;
604 }
605
606 /**
607  * __get_user_pages() - pin user pages in memory
608  * @tsk:        task_struct of target task
609  * @mm:         mm_struct of target mm
610  * @start:      starting user address
611  * @nr_pages:   number of pages from start to pin
612  * @gup_flags:  flags modifying pin behaviour
613  * @pages:      array that receives pointers to the pages pinned.
614  *              Should be at least nr_pages long. Or NULL, if caller
615  *              only intends to ensure the pages are faulted in.
616  * @vmas:       array of pointers to vmas corresponding to each page.
617  *              Or NULL if the caller does not require them.
618  * @nonblocking: whether waiting for disk IO or mmap_sem contention
619  *
620  * Returns number of pages pinned. This may be fewer than the number
621  * requested. If nr_pages is 0 or negative, returns 0. If no pages
622  * were pinned, returns -errno. Each page returned must be released
623  * with a put_page() call when it is finished with. vmas will only
624  * remain valid while mmap_sem is held.
625  *
626  * Must be called with mmap_sem held.  It may be released.  See below.
627  *
628  * __get_user_pages walks a process's page tables and takes a reference to
629  * each struct page that each user address corresponds to at a given
630  * instant. That is, it takes the page that would be accessed if a user
631  * thread accesses the given user virtual address at that instant.
632  *
633  * This does not guarantee that the page exists in the user mappings when
634  * __get_user_pages returns, and there may even be a completely different
635  * page there in some cases (eg. if mmapped pagecache has been invalidated
636  * and subsequently re faulted). However it does guarantee that the page
637  * won't be freed completely. And mostly callers simply care that the page
638  * contains data that was valid *at some point in time*. Typically, an IO
639  * or similar operation cannot guarantee anything stronger anyway because
640  * locks can't be held over the syscall boundary.
641  *
642  * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
643  * the page is written to, set_page_dirty (or set_page_dirty_lock, as
644  * appropriate) must be called after the page is finished with, and
645  * before put_page is called.
646  *
647  * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
648  * or mmap_sem contention, and if waiting is needed to pin all pages,
649  * *@nonblocking will be set to 0.  Further, if @gup_flags does not
650  * include FOLL_NOWAIT, the mmap_sem will be released via up_read() in
651  * this case.
652  *
653  * A caller using such a combination of @nonblocking and @gup_flags
654  * must therefore hold the mmap_sem for reading only, and recognize
655  * when it's been released.  Otherwise, it must be held for either
656  * reading or writing and will not be released.
657  *
658  * In most cases, get_user_pages or get_user_pages_fast should be used
659  * instead of __get_user_pages. __get_user_pages should be used only if
660  * you need some special @gup_flags.
661  */
662 static long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
663                 unsigned long start, unsigned long nr_pages,
664                 unsigned int gup_flags, struct page **pages,
665                 struct vm_area_struct **vmas, int *nonblocking)
666 {
667         long i = 0;
668         unsigned int page_mask;
669         struct vm_area_struct *vma = NULL;
670
671         if (!nr_pages)
672                 return 0;
673
674         VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
675
676         /*
677          * If FOLL_FORCE is set then do not force a full fault as the hinting
678          * fault information is unrelated to the reference behaviour of a task
679          * using the address space
680          */
681         if (!(gup_flags & FOLL_FORCE))
682                 gup_flags |= FOLL_NUMA;
683
684         do {
685                 struct page *page;
686                 unsigned int foll_flags = gup_flags;
687                 unsigned int page_increm;
688
689                 /* first iteration or cross vma bound */
690                 if (!vma || start >= vma->vm_end) {
691                         vma = find_extend_vma(mm, start);
692                         if (!vma && in_gate_area(mm, start)) {
693                                 int ret;
694                                 ret = get_gate_page(mm, start & PAGE_MASK,
695                                                 gup_flags, &vma,
696                                                 pages ? &pages[i] : NULL);
697                                 if (ret)
698                                         return i ? : ret;
699                                 page_mask = 0;
700                                 goto next_page;
701                         }
702
703                         if (!vma || check_vma_flags(vma, gup_flags))
704                                 return i ? : -EFAULT;
705                         if (is_vm_hugetlb_page(vma)) {
706                                 if (should_force_cow_break(vma, foll_flags))
707                                         foll_flags |= FOLL_WRITE;
708                                 i = follow_hugetlb_page(mm, vma, pages, vmas,
709                                                 &start, &nr_pages, i,
710                                                 foll_flags, nonblocking);
711                                 continue;
712                         }
713                 }
714
715                 if (should_force_cow_break(vma, foll_flags))
716                         foll_flags |= FOLL_WRITE;
717
718 retry:
719                 /*
720                  * If we have a pending SIGKILL, don't keep faulting pages and
721                  * potentially allocating memory.
722                  */
723                 if (unlikely(fatal_signal_pending(current)))
724                         return i ? i : -ERESTARTSYS;
725                 cond_resched();
726                 page = follow_page_mask(vma, start, foll_flags, &page_mask);
727                 if (!page) {
728                         int ret;
729                         ret = faultin_page(tsk, vma, start, &foll_flags,
730                                         nonblocking);
731                         switch (ret) {
732                         case 0:
733                                 goto retry;
734                         case -EFAULT:
735                         case -ENOMEM:
736                         case -EHWPOISON:
737                                 return i ? i : ret;
738                         case -EBUSY:
739                                 return i;
740                         case -ENOENT:
741                                 goto next_page;
742                         }
743                         BUG();
744                 } else if (PTR_ERR(page) == -EEXIST) {
745                         /*
746                          * Proper page table entry exists, but no corresponding
747                          * struct page.
748                          */
749                         goto next_page;
750                 } else if (IS_ERR(page)) {
751                         return i ? i : PTR_ERR(page);
752                 }
753                 if (pages) {
754                         pages[i] = page;
755                         flush_anon_page(vma, page, start);
756                         flush_dcache_page(page);
757                         page_mask = 0;
758                 }
759 next_page:
760                 if (vmas) {
761                         vmas[i] = vma;
762                         page_mask = 0;
763                 }
764                 page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
765                 if (page_increm > nr_pages)
766                         page_increm = nr_pages;
767                 i += page_increm;
768                 start += page_increm * PAGE_SIZE;
769                 nr_pages -= page_increm;
770         } while (nr_pages);
771         return i;
772 }
773
774 static bool vma_permits_fault(struct vm_area_struct *vma,
775                               unsigned int fault_flags)
776 {
777         bool write   = !!(fault_flags & FAULT_FLAG_WRITE);
778         bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
779         vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
780
781         if (!(vm_flags & vma->vm_flags))
782                 return false;
783
784         /*
785          * The architecture might have a hardware protection
786          * mechanism other than read/write that can deny access.
787          *
788          * gup always represents data access, not instruction
789          * fetches, so execute=false here:
790          */
791         if (!arch_vma_access_permitted(vma, write, false, foreign))
792                 return false;
793
794         return true;
795 }
796
797 /*
798  * fixup_user_fault() - manually resolve a user page fault
799  * @tsk:        the task_struct to use for page fault accounting, or
800  *              NULL if faults are not to be recorded.
801  * @mm:         mm_struct of target mm
802  * @address:    user address
803  * @fault_flags:flags to pass down to handle_mm_fault()
804  * @unlocked:   did we unlock the mmap_sem while retrying, maybe NULL if caller
805  *              does not allow retry
806  *
807  * This is meant to be called in the specific scenario where for locking reasons
808  * we try to access user memory in atomic context (within a pagefault_disable()
809  * section), this returns -EFAULT, and we want to resolve the user fault before
810  * trying again.
811  *
812  * Typically this is meant to be used by the futex code.
813  *
814  * The main difference with get_user_pages() is that this function will
815  * unconditionally call handle_mm_fault() which will in turn perform all the
816  * necessary SW fixup of the dirty and young bits in the PTE, while
817  * get_user_pages() only guarantees to update these in the struct page.
818  *
819  * This is important for some architectures where those bits also gate the
820  * access permission to the page because they are maintained in software.  On
821  * such architectures, gup() will not be enough to make a subsequent access
822  * succeed.
823  *
824  * This function will not return with an unlocked mmap_sem. So it has not the
825  * same semantics wrt the @mm->mmap_sem as does filemap_fault().
826  */
827 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
828                      unsigned long address, unsigned int fault_flags,
829                      bool *unlocked)
830 {
831         struct vm_area_struct *vma;
832         int ret, major = 0;
833
834         if (unlocked)
835                 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
836
837 retry:
838         vma = find_extend_vma(mm, address);
839         if (!vma || address < vma->vm_start)
840                 return -EFAULT;
841
842         if (!vma_permits_fault(vma, fault_flags))
843                 return -EFAULT;
844
845         ret = handle_mm_fault(vma, address, fault_flags);
846         major |= ret & VM_FAULT_MAJOR;
847         if (ret & VM_FAULT_ERROR) {
848                 int err = vm_fault_to_errno(ret, 0);
849
850                 if (err)
851                         return err;
852                 BUG();
853         }
854
855         if (ret & VM_FAULT_RETRY) {
856                 down_read(&mm->mmap_sem);
857                 if (!(fault_flags & FAULT_FLAG_TRIED)) {
858                         *unlocked = true;
859                         fault_flags &= ~FAULT_FLAG_ALLOW_RETRY;
860                         fault_flags |= FAULT_FLAG_TRIED;
861                         goto retry;
862                 }
863         }
864
865         if (tsk) {
866                 if (major)
867                         tsk->maj_flt++;
868                 else
869                         tsk->min_flt++;
870         }
871         return 0;
872 }
873 EXPORT_SYMBOL_GPL(fixup_user_fault);
874
875 static __always_inline long __get_user_pages_locked(struct task_struct *tsk,
876                                                 struct mm_struct *mm,
877                                                 unsigned long start,
878                                                 unsigned long nr_pages,
879                                                 struct page **pages,
880                                                 struct vm_area_struct **vmas,
881                                                 int *locked, bool notify_drop,
882                                                 unsigned int flags)
883 {
884         long ret, pages_done;
885         bool lock_dropped;
886
887         if (locked) {
888                 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
889                 BUG_ON(vmas);
890                 /* check caller initialized locked */
891                 BUG_ON(*locked != 1);
892         }
893
894         if (pages)
895                 flags |= FOLL_GET;
896
897         pages_done = 0;
898         lock_dropped = false;
899         for (;;) {
900                 ret = __get_user_pages(tsk, mm, start, nr_pages, flags, pages,
901                                        vmas, locked);
902                 if (!locked)
903                         /* VM_FAULT_RETRY couldn't trigger, bypass */
904                         return ret;
905
906                 /* VM_FAULT_RETRY cannot return errors */
907                 if (!*locked) {
908                         BUG_ON(ret < 0);
909                         BUG_ON(ret >= nr_pages);
910                 }
911
912                 if (!pages)
913                         /* If it's a prefault don't insist harder */
914                         return ret;
915
916                 if (ret > 0) {
917                         nr_pages -= ret;
918                         pages_done += ret;
919                         if (!nr_pages)
920                                 break;
921                 }
922                 if (*locked) {
923                         /* VM_FAULT_RETRY didn't trigger */
924                         if (!pages_done)
925                                 pages_done = ret;
926                         break;
927                 }
928                 /* VM_FAULT_RETRY triggered, so seek to the faulting offset */
929                 pages += ret;
930                 start += ret << PAGE_SHIFT;
931
932                 /*
933                  * Repeat on the address that fired VM_FAULT_RETRY
934                  * without FAULT_FLAG_ALLOW_RETRY but with
935                  * FAULT_FLAG_TRIED.
936                  */
937                 *locked = 1;
938                 lock_dropped = true;
939                 down_read(&mm->mmap_sem);
940                 ret = __get_user_pages(tsk, mm, start, 1, flags | FOLL_TRIED,
941                                        pages, NULL, NULL);
942                 if (ret != 1) {
943                         BUG_ON(ret > 1);
944                         if (!pages_done)
945                                 pages_done = ret;
946                         break;
947                 }
948                 nr_pages--;
949                 pages_done++;
950                 if (!nr_pages)
951                         break;
952                 pages++;
953                 start += PAGE_SIZE;
954         }
955         if (notify_drop && lock_dropped && *locked) {
956                 /*
957                  * We must let the caller know we temporarily dropped the lock
958                  * and so the critical section protected by it was lost.
959                  */
960                 up_read(&mm->mmap_sem);
961                 *locked = 0;
962         }
963         return pages_done;
964 }
965
966 /*
967  * We can leverage the VM_FAULT_RETRY functionality in the page fault
968  * paths better by using either get_user_pages_locked() or
969  * get_user_pages_unlocked().
970  *
971  * get_user_pages_locked() is suitable to replace the form:
972  *
973  *      down_read(&mm->mmap_sem);
974  *      do_something()
975  *      get_user_pages(tsk, mm, ..., pages, NULL);
976  *      up_read(&mm->mmap_sem);
977  *
978  *  to:
979  *
980  *      int locked = 1;
981  *      down_read(&mm->mmap_sem);
982  *      do_something()
983  *      get_user_pages_locked(tsk, mm, ..., pages, &locked);
984  *      if (locked)
985  *          up_read(&mm->mmap_sem);
986  */
987 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
988                            unsigned int gup_flags, struct page **pages,
989                            int *locked)
990 {
991         return __get_user_pages_locked(current, current->mm, start, nr_pages,
992                                        pages, NULL, locked, true,
993                                        gup_flags | FOLL_TOUCH);
994 }
995 EXPORT_SYMBOL(get_user_pages_locked);
996
997 /*
998  * Same as get_user_pages_unlocked(...., FOLL_TOUCH) but it allows for
999  * tsk, mm to be specified.
1000  *
1001  * NOTE: here FOLL_TOUCH is not set implicitly and must be set by the
1002  * caller if required (just like with __get_user_pages). "FOLL_GET"
1003  * is set implicitly if "pages" is non-NULL.
1004  */
1005 static __always_inline long __get_user_pages_unlocked(struct task_struct *tsk,
1006                 struct mm_struct *mm, unsigned long start,
1007                 unsigned long nr_pages, struct page **pages,
1008                 unsigned int gup_flags)
1009 {
1010         long ret;
1011         int locked = 1;
1012
1013         down_read(&mm->mmap_sem);
1014         ret = __get_user_pages_locked(tsk, mm, start, nr_pages, pages, NULL,
1015                                       &locked, false, gup_flags);
1016         if (locked)
1017                 up_read(&mm->mmap_sem);
1018         return ret;
1019 }
1020
1021 /*
1022  * get_user_pages_unlocked() is suitable to replace the form:
1023  *
1024  *      down_read(&mm->mmap_sem);
1025  *      get_user_pages(tsk, mm, ..., pages, NULL);
1026  *      up_read(&mm->mmap_sem);
1027  *
1028  *  with:
1029  *
1030  *      get_user_pages_unlocked(tsk, mm, ..., pages);
1031  *
1032  * It is functionally equivalent to get_user_pages_fast so
1033  * get_user_pages_fast should be used instead if specific gup_flags
1034  * (e.g. FOLL_FORCE) are not required.
1035  */
1036 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
1037                              struct page **pages, unsigned int gup_flags)
1038 {
1039         return __get_user_pages_unlocked(current, current->mm, start, nr_pages,
1040                                          pages, gup_flags | FOLL_TOUCH);
1041 }
1042 EXPORT_SYMBOL(get_user_pages_unlocked);
1043
1044 /*
1045  * get_user_pages_remote() - pin user pages in memory
1046  * @tsk:        the task_struct to use for page fault accounting, or
1047  *              NULL if faults are not to be recorded.
1048  * @mm:         mm_struct of target mm
1049  * @start:      starting user address
1050  * @nr_pages:   number of pages from start to pin
1051  * @gup_flags:  flags modifying lookup behaviour
1052  * @pages:      array that receives pointers to the pages pinned.
1053  *              Should be at least nr_pages long. Or NULL, if caller
1054  *              only intends to ensure the pages are faulted in.
1055  * @vmas:       array of pointers to vmas corresponding to each page.
1056  *              Or NULL if the caller does not require them.
1057  * @locked:     pointer to lock flag indicating whether lock is held and
1058  *              subsequently whether VM_FAULT_RETRY functionality can be
1059  *              utilised. Lock must initially be held.
1060  *
1061  * Returns number of pages pinned. This may be fewer than the number
1062  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1063  * were pinned, returns -errno. Each page returned must be released
1064  * with a put_page() call when it is finished with. vmas will only
1065  * remain valid while mmap_sem is held.
1066  *
1067  * Must be called with mmap_sem held for read or write.
1068  *
1069  * get_user_pages walks a process's page tables and takes a reference to
1070  * each struct page that each user address corresponds to at a given
1071  * instant. That is, it takes the page that would be accessed if a user
1072  * thread accesses the given user virtual address at that instant.
1073  *
1074  * This does not guarantee that the page exists in the user mappings when
1075  * get_user_pages returns, and there may even be a completely different
1076  * page there in some cases (eg. if mmapped pagecache has been invalidated
1077  * and subsequently re faulted). However it does guarantee that the page
1078  * won't be freed completely. And mostly callers simply care that the page
1079  * contains data that was valid *at some point in time*. Typically, an IO
1080  * or similar operation cannot guarantee anything stronger anyway because
1081  * locks can't be held over the syscall boundary.
1082  *
1083  * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1084  * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1085  * be called after the page is finished with, and before put_page is called.
1086  *
1087  * get_user_pages is typically used for fewer-copy IO operations, to get a
1088  * handle on the memory by some means other than accesses via the user virtual
1089  * addresses. The pages may be submitted for DMA to devices or accessed via
1090  * their kernel linear mapping (via the kmap APIs). Care should be taken to
1091  * use the correct cache flushing APIs.
1092  *
1093  * See also get_user_pages_fast, for performance critical applications.
1094  *
1095  * get_user_pages should be phased out in favor of
1096  * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1097  * should use get_user_pages because it cannot pass
1098  * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1099  */
1100 long get_user_pages_remote(struct task_struct *tsk, struct mm_struct *mm,
1101                 unsigned long start, unsigned long nr_pages,
1102                 unsigned int gup_flags, struct page **pages,
1103                 struct vm_area_struct **vmas, int *locked)
1104 {
1105         return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
1106                                        locked, true,
1107                                        gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1108 }
1109 EXPORT_SYMBOL(get_user_pages_remote);
1110
1111 /*
1112  * This is the same as get_user_pages_remote(), just with a
1113  * less-flexible calling convention where we assume that the task
1114  * and mm being operated on are the current task's and don't allow
1115  * passing of a locked parameter.  We also obviously don't pass
1116  * FOLL_REMOTE in here.
1117  */
1118 long get_user_pages(unsigned long start, unsigned long nr_pages,
1119                 unsigned int gup_flags, struct page **pages,
1120                 struct vm_area_struct **vmas)
1121 {
1122         return __get_user_pages_locked(current, current->mm, start, nr_pages,
1123                                        pages, vmas, NULL, false,
1124                                        gup_flags | FOLL_TOUCH);
1125 }
1126 EXPORT_SYMBOL(get_user_pages);
1127
1128 #ifdef CONFIG_FS_DAX
1129 /*
1130  * This is the same as get_user_pages() in that it assumes we are
1131  * operating on the current task's mm, but it goes further to validate
1132  * that the vmas associated with the address range are suitable for
1133  * longterm elevated page reference counts. For example, filesystem-dax
1134  * mappings are subject to the lifetime enforced by the filesystem and
1135  * we need guarantees that longterm users like RDMA and V4L2 only
1136  * establish mappings that have a kernel enforced revocation mechanism.
1137  *
1138  * "longterm" == userspace controlled elevated page count lifetime.
1139  * Contrast this to iov_iter_get_pages() usages which are transient.
1140  */
1141 long get_user_pages_longterm(unsigned long start, unsigned long nr_pages,
1142                 unsigned int gup_flags, struct page **pages,
1143                 struct vm_area_struct **vmas_arg)
1144 {
1145         struct vm_area_struct **vmas = vmas_arg;
1146         struct vm_area_struct *vma_prev = NULL;
1147         long rc, i;
1148
1149         if (!pages)
1150                 return -EINVAL;
1151
1152         if (!vmas) {
1153                 vmas = kcalloc(nr_pages, sizeof(struct vm_area_struct *),
1154                                GFP_KERNEL);
1155                 if (!vmas)
1156                         return -ENOMEM;
1157         }
1158
1159         rc = get_user_pages(start, nr_pages, gup_flags, pages, vmas);
1160
1161         for (i = 0; i < rc; i++) {
1162                 struct vm_area_struct *vma = vmas[i];
1163
1164                 if (vma == vma_prev)
1165                         continue;
1166
1167                 vma_prev = vma;
1168
1169                 if (vma_is_fsdax(vma))
1170                         break;
1171         }
1172
1173         /*
1174          * Either get_user_pages() failed, or the vma validation
1175          * succeeded, in either case we don't need to put_page() before
1176          * returning.
1177          */
1178         if (i >= rc)
1179                 goto out;
1180
1181         for (i = 0; i < rc; i++)
1182                 put_page(pages[i]);
1183         rc = -EOPNOTSUPP;
1184 out:
1185         if (vmas != vmas_arg)
1186                 kfree(vmas);
1187         return rc;
1188 }
1189 EXPORT_SYMBOL(get_user_pages_longterm);
1190 #endif /* CONFIG_FS_DAX */
1191
1192 /**
1193  * populate_vma_page_range() -  populate a range of pages in the vma.
1194  * @vma:   target vma
1195  * @start: start address
1196  * @end:   end address
1197  * @nonblocking:
1198  *
1199  * This takes care of mlocking the pages too if VM_LOCKED is set.
1200  *
1201  * return 0 on success, negative error code on error.
1202  *
1203  * vma->vm_mm->mmap_sem must be held.
1204  *
1205  * If @nonblocking is NULL, it may be held for read or write and will
1206  * be unperturbed.
1207  *
1208  * If @nonblocking is non-NULL, it must held for read only and may be
1209  * released.  If it's released, *@nonblocking will be set to 0.
1210  */
1211 long populate_vma_page_range(struct vm_area_struct *vma,
1212                 unsigned long start, unsigned long end, int *nonblocking)
1213 {
1214         struct mm_struct *mm = vma->vm_mm;
1215         unsigned long nr_pages = (end - start) / PAGE_SIZE;
1216         int gup_flags;
1217
1218         VM_BUG_ON(start & ~PAGE_MASK);
1219         VM_BUG_ON(end   & ~PAGE_MASK);
1220         VM_BUG_ON_VMA(start < vma->vm_start, vma);
1221         VM_BUG_ON_VMA(end   > vma->vm_end, vma);
1222         VM_BUG_ON_MM(!rwsem_is_locked(&mm->mmap_sem), mm);
1223
1224         gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1225         if (vma->vm_flags & VM_LOCKONFAULT)
1226                 gup_flags &= ~FOLL_POPULATE;
1227         /*
1228          * We want to touch writable mappings with a write fault in order
1229          * to break COW, except for shared mappings because these don't COW
1230          * and we would not want to dirty them for nothing.
1231          */
1232         if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1233                 gup_flags |= FOLL_WRITE;
1234
1235         /*
1236          * We want mlock to succeed for regions that have any permissions
1237          * other than PROT_NONE.
1238          */
1239         if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
1240                 gup_flags |= FOLL_FORCE;
1241
1242         /*
1243          * We made sure addr is within a VMA, so the following will
1244          * not result in a stack expansion that recurses back here.
1245          */
1246         return __get_user_pages(current, mm, start, nr_pages, gup_flags,
1247                                 NULL, NULL, nonblocking);
1248 }
1249
1250 /*
1251  * __mm_populate - populate and/or mlock pages within a range of address space.
1252  *
1253  * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1254  * flags. VMAs must be already marked with the desired vm_flags, and
1255  * mmap_sem must not be held.
1256  */
1257 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1258 {
1259         struct mm_struct *mm = current->mm;
1260         unsigned long end, nstart, nend;
1261         struct vm_area_struct *vma = NULL;
1262         int locked = 0;
1263         long ret = 0;
1264
1265         end = start + len;
1266
1267         for (nstart = start; nstart < end; nstart = nend) {
1268                 /*
1269                  * We want to fault in pages for [nstart; end) address range.
1270                  * Find first corresponding VMA.
1271                  */
1272                 if (!locked) {
1273                         locked = 1;
1274                         down_read(&mm->mmap_sem);
1275                         vma = find_vma(mm, nstart);
1276                 } else if (nstart >= vma->vm_end)
1277                         vma = vma->vm_next;
1278                 if (!vma || vma->vm_start >= end)
1279                         break;
1280                 /*
1281                  * Set [nstart; nend) to intersection of desired address
1282                  * range with the first VMA. Also, skip undesirable VMA types.
1283                  */
1284                 nend = min(end, vma->vm_end);
1285                 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1286                         continue;
1287                 if (nstart < vma->vm_start)
1288                         nstart = vma->vm_start;
1289                 /*
1290                  * Now fault in a range of pages. populate_vma_page_range()
1291                  * double checks the vma flags, so that it won't mlock pages
1292                  * if the vma was already munlocked.
1293                  */
1294                 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1295                 if (ret < 0) {
1296                         if (ignore_errors) {
1297                                 ret = 0;
1298                                 continue;       /* continue at next VMA */
1299                         }
1300                         break;
1301                 }
1302                 nend = nstart + ret * PAGE_SIZE;
1303                 ret = 0;
1304         }
1305         if (locked)
1306                 up_read(&mm->mmap_sem);
1307         return ret;     /* 0 or negative error code */
1308 }
1309
1310 /**
1311  * get_dump_page() - pin user page in memory while writing it to core dump
1312  * @addr: user address
1313  *
1314  * Returns struct page pointer of user page pinned for dump,
1315  * to be freed afterwards by put_page().
1316  *
1317  * Returns NULL on any kind of failure - a hole must then be inserted into
1318  * the corefile, to preserve alignment with its headers; and also returns
1319  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1320  * allowing a hole to be left in the corefile to save diskspace.
1321  *
1322  * Called without mmap_sem, but after all other threads have been killed.
1323  */
1324 #ifdef CONFIG_ELF_CORE
1325 struct page *get_dump_page(unsigned long addr)
1326 {
1327         struct vm_area_struct *vma;
1328         struct page *page;
1329
1330         if (__get_user_pages(current, current->mm, addr, 1,
1331                              FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
1332                              NULL) < 1)
1333                 return NULL;
1334         flush_cache_page(vma, addr, page_to_pfn(page));
1335         return page;
1336 }
1337 #endif /* CONFIG_ELF_CORE */
1338
1339 /*
1340  * Generic Fast GUP
1341  *
1342  * get_user_pages_fast attempts to pin user pages by walking the page
1343  * tables directly and avoids taking locks. Thus the walker needs to be
1344  * protected from page table pages being freed from under it, and should
1345  * block any THP splits.
1346  *
1347  * One way to achieve this is to have the walker disable interrupts, and
1348  * rely on IPIs from the TLB flushing code blocking before the page table
1349  * pages are freed. This is unsuitable for architectures that do not need
1350  * to broadcast an IPI when invalidating TLBs.
1351  *
1352  * Another way to achieve this is to batch up page table containing pages
1353  * belonging to more than one mm_user, then rcu_sched a callback to free those
1354  * pages. Disabling interrupts will allow the fast_gup walker to both block
1355  * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
1356  * (which is a relatively rare event). The code below adopts this strategy.
1357  *
1358  * Before activating this code, please be aware that the following assumptions
1359  * are currently made:
1360  *
1361  *  *) Either HAVE_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
1362  *  free pages containing page tables or TLB flushing requires IPI broadcast.
1363  *
1364  *  *) ptes can be read atomically by the architecture.
1365  *
1366  *  *) access_ok is sufficient to validate userspace address ranges.
1367  *
1368  * The last two assumptions can be relaxed by the addition of helper functions.
1369  *
1370  * This code is based heavily on the PowerPC implementation by Nick Piggin.
1371  */
1372 #ifdef CONFIG_HAVE_GENERIC_GUP
1373
1374 #ifndef gup_get_pte
1375 /*
1376  * We assume that the PTE can be read atomically. If this is not the case for
1377  * your architecture, please provide the helper.
1378  */
1379 static inline pte_t gup_get_pte(pte_t *ptep)
1380 {
1381         return READ_ONCE(*ptep);
1382 }
1383 #endif
1384
1385 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
1386                                             struct page **pages)
1387 {
1388         while ((*nr) - nr_start) {
1389                 struct page *page = pages[--(*nr)];
1390
1391                 ClearPageReferenced(page);
1392                 put_page(page);
1393         }
1394 }
1395
1396 /*
1397  * Return the compund head page with ref appropriately incremented,
1398  * or NULL if that failed.
1399  */
1400 static inline struct page *try_get_compound_head(struct page *page, int refs)
1401 {
1402         struct page *head = compound_head(page);
1403         if (WARN_ON_ONCE(page_ref_count(head) < 0))
1404                 return NULL;
1405         if (unlikely(!page_cache_add_speculative(head, refs)))
1406                 return NULL;
1407         return head;
1408 }
1409
1410 #ifdef __HAVE_ARCH_PTE_SPECIAL
1411 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1412                          int write, struct page **pages, int *nr)
1413 {
1414         struct dev_pagemap *pgmap = NULL;
1415         int nr_start = *nr, ret = 0;
1416         pte_t *ptep, *ptem;
1417
1418         ptem = ptep = pte_offset_map(&pmd, addr);
1419         do {
1420                 pte_t pte = gup_get_pte(ptep);
1421                 struct page *head, *page;
1422
1423                 /*
1424                  * Similar to the PMD case below, NUMA hinting must take slow
1425                  * path using the pte_protnone check.
1426                  */
1427                 if (pte_protnone(pte))
1428                         goto pte_unmap;
1429
1430                 if (!pte_access_permitted(pte, write))
1431                         goto pte_unmap;
1432
1433                 if (pte_devmap(pte)) {
1434                         pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
1435                         if (unlikely(!pgmap)) {
1436                                 undo_dev_pagemap(nr, nr_start, pages);
1437                                 goto pte_unmap;
1438                         }
1439                 } else if (pte_special(pte))
1440                         goto pte_unmap;
1441
1442                 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
1443                 page = pte_page(pte);
1444
1445                 head = try_get_compound_head(page, 1);
1446                 if (!head)
1447                         goto pte_unmap;
1448
1449                 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
1450                         put_page(head);
1451                         goto pte_unmap;
1452                 }
1453
1454                 VM_BUG_ON_PAGE(compound_head(page) != head, page);
1455
1456                 put_dev_pagemap(pgmap);
1457                 SetPageReferenced(page);
1458                 pages[*nr] = page;
1459                 (*nr)++;
1460
1461         } while (ptep++, addr += PAGE_SIZE, addr != end);
1462
1463         ret = 1;
1464
1465 pte_unmap:
1466         pte_unmap(ptem);
1467         return ret;
1468 }
1469 #else
1470
1471 /*
1472  * If we can't determine whether or not a pte is special, then fail immediately
1473  * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
1474  * to be special.
1475  *
1476  * For a futex to be placed on a THP tail page, get_futex_key requires a
1477  * __get_user_pages_fast implementation that can pin pages. Thus it's still
1478  * useful to have gup_huge_pmd even if we can't operate on ptes.
1479  */
1480 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1481                          int write, struct page **pages, int *nr)
1482 {
1483         return 0;
1484 }
1485 #endif /* __HAVE_ARCH_PTE_SPECIAL */
1486
1487 #if defined(__HAVE_ARCH_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1488 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
1489                 unsigned long end, struct page **pages, int *nr)
1490 {
1491         int nr_start = *nr;
1492         struct dev_pagemap *pgmap = NULL;
1493
1494         do {
1495                 struct page *page = pfn_to_page(pfn);
1496
1497                 pgmap = get_dev_pagemap(pfn, pgmap);
1498                 if (unlikely(!pgmap)) {
1499                         undo_dev_pagemap(nr, nr_start, pages);
1500                         return 0;
1501                 }
1502                 SetPageReferenced(page);
1503                 pages[*nr] = page;
1504                 get_page(page);
1505                 put_dev_pagemap(pgmap);
1506                 (*nr)++;
1507                 pfn++;
1508         } while (addr += PAGE_SIZE, addr != end);
1509         return 1;
1510 }
1511
1512 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1513                 unsigned long end, struct page **pages, int *nr)
1514 {
1515         unsigned long fault_pfn;
1516         int nr_start = *nr;
1517
1518         fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
1519         if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1520                 return 0;
1521
1522         if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1523                 undo_dev_pagemap(nr, nr_start, pages);
1524                 return 0;
1525         }
1526         return 1;
1527 }
1528
1529 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
1530                 unsigned long end, struct page **pages, int *nr)
1531 {
1532         unsigned long fault_pfn;
1533         int nr_start = *nr;
1534
1535         fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
1536         if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1537                 return 0;
1538
1539         if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1540                 undo_dev_pagemap(nr, nr_start, pages);
1541                 return 0;
1542         }
1543         return 1;
1544 }
1545 #else
1546 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1547                 unsigned long end, struct page **pages, int *nr)
1548 {
1549         BUILD_BUG();
1550         return 0;
1551 }
1552
1553 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
1554                 unsigned long end, struct page **pages, int *nr)
1555 {
1556         BUILD_BUG();
1557         return 0;
1558 }
1559 #endif
1560
1561 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1562                 unsigned long end, int write, struct page **pages, int *nr)
1563 {
1564         struct page *head, *page;
1565         int refs;
1566
1567         if (!pmd_access_permitted(orig, write))
1568                 return 0;
1569
1570         if (pmd_devmap(orig))
1571                 return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
1572
1573         refs = 0;
1574         page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
1575         do {
1576                 pages[*nr] = page;
1577                 (*nr)++;
1578                 page++;
1579                 refs++;
1580         } while (addr += PAGE_SIZE, addr != end);
1581
1582         head = try_get_compound_head(pmd_page(orig), refs);
1583         if (!head) {
1584                 *nr -= refs;
1585                 return 0;
1586         }
1587
1588         if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1589                 *nr -= refs;
1590                 while (refs--)
1591                         put_page(head);
1592                 return 0;
1593         }
1594
1595         SetPageReferenced(head);
1596         return 1;
1597 }
1598
1599 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
1600                 unsigned long end, int write, struct page **pages, int *nr)
1601 {
1602         struct page *head, *page;
1603         int refs;
1604
1605         if (!pud_access_permitted(orig, write))
1606                 return 0;
1607
1608         if (pud_devmap(orig))
1609                 return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
1610
1611         refs = 0;
1612         page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
1613         do {
1614                 pages[*nr] = page;
1615                 (*nr)++;
1616                 page++;
1617                 refs++;
1618         } while (addr += PAGE_SIZE, addr != end);
1619
1620         head = try_get_compound_head(pud_page(orig), refs);
1621         if (!head) {
1622                 *nr -= refs;
1623                 return 0;
1624         }
1625
1626         if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1627                 *nr -= refs;
1628                 while (refs--)
1629                         put_page(head);
1630                 return 0;
1631         }
1632
1633         SetPageReferenced(head);
1634         return 1;
1635 }
1636
1637 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
1638                         unsigned long end, int write,
1639                         struct page **pages, int *nr)
1640 {
1641         int refs;
1642         struct page *head, *page;
1643
1644         if (!pgd_access_permitted(orig, write))
1645                 return 0;
1646
1647         BUILD_BUG_ON(pgd_devmap(orig));
1648         refs = 0;
1649         page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
1650         do {
1651                 pages[*nr] = page;
1652                 (*nr)++;
1653                 page++;
1654                 refs++;
1655         } while (addr += PAGE_SIZE, addr != end);
1656
1657         head = try_get_compound_head(pgd_page(orig), refs);
1658         if (!head) {
1659                 *nr -= refs;
1660                 return 0;
1661         }
1662
1663         if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
1664                 *nr -= refs;
1665                 while (refs--)
1666                         put_page(head);
1667                 return 0;
1668         }
1669
1670         SetPageReferenced(head);
1671         return 1;
1672 }
1673
1674 static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
1675                 int write, struct page **pages, int *nr)
1676 {
1677         unsigned long next;
1678         pmd_t *pmdp;
1679
1680         pmdp = pmd_offset(&pud, addr);
1681         do {
1682                 pmd_t pmd = READ_ONCE(*pmdp);
1683
1684                 next = pmd_addr_end(addr, end);
1685                 if (!pmd_present(pmd))
1686                         return 0;
1687
1688                 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
1689                              pmd_devmap(pmd))) {
1690                         /*
1691                          * NUMA hinting faults need to be handled in the GUP
1692                          * slowpath for accounting purposes and so that they
1693                          * can be serialised against THP migration.
1694                          */
1695                         if (pmd_protnone(pmd))
1696                                 return 0;
1697
1698                         if (!gup_huge_pmd(pmd, pmdp, addr, next, write,
1699                                 pages, nr))
1700                                 return 0;
1701
1702                 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
1703                         /*
1704                          * architecture have different format for hugetlbfs
1705                          * pmd format and THP pmd format
1706                          */
1707                         if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
1708                                          PMD_SHIFT, next, write, pages, nr))
1709                                 return 0;
1710                 } else if (!gup_pte_range(pmd, addr, next, write, pages, nr))
1711                                 return 0;
1712         } while (pmdp++, addr = next, addr != end);
1713
1714         return 1;
1715 }
1716
1717 static int gup_pud_range(p4d_t p4d, unsigned long addr, unsigned long end,
1718                          int write, struct page **pages, int *nr)
1719 {
1720         unsigned long next;
1721         pud_t *pudp;
1722
1723         pudp = pud_offset(&p4d, addr);
1724         do {
1725                 pud_t pud = READ_ONCE(*pudp);
1726
1727                 next = pud_addr_end(addr, end);
1728                 if (pud_none(pud))
1729                         return 0;
1730                 if (unlikely(pud_huge(pud))) {
1731                         if (!gup_huge_pud(pud, pudp, addr, next, write,
1732                                           pages, nr))
1733                                 return 0;
1734                 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
1735                         if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
1736                                          PUD_SHIFT, next, write, pages, nr))
1737                                 return 0;
1738                 } else if (!gup_pmd_range(pud, addr, next, write, pages, nr))
1739                         return 0;
1740         } while (pudp++, addr = next, addr != end);
1741
1742         return 1;
1743 }
1744
1745 static int gup_p4d_range(pgd_t pgd, unsigned long addr, unsigned long end,
1746                          int write, struct page **pages, int *nr)
1747 {
1748         unsigned long next;
1749         p4d_t *p4dp;
1750
1751         p4dp = p4d_offset(&pgd, addr);
1752         do {
1753                 p4d_t p4d = READ_ONCE(*p4dp);
1754
1755                 next = p4d_addr_end(addr, end);
1756                 if (p4d_none(p4d))
1757                         return 0;
1758                 BUILD_BUG_ON(p4d_huge(p4d));
1759                 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
1760                         if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
1761                                          P4D_SHIFT, next, write, pages, nr))
1762                                 return 0;
1763                 } else if (!gup_pud_range(p4d, addr, next, write, pages, nr))
1764                         return 0;
1765         } while (p4dp++, addr = next, addr != end);
1766
1767         return 1;
1768 }
1769
1770 static void gup_pgd_range(unsigned long addr, unsigned long end,
1771                 int write, struct page **pages, int *nr)
1772 {
1773         unsigned long next;
1774         pgd_t *pgdp;
1775
1776         pgdp = pgd_offset(current->mm, addr);
1777         do {
1778                 pgd_t pgd = READ_ONCE(*pgdp);
1779
1780                 next = pgd_addr_end(addr, end);
1781                 if (pgd_none(pgd))
1782                         return;
1783                 if (unlikely(pgd_huge(pgd))) {
1784                         if (!gup_huge_pgd(pgd, pgdp, addr, next, write,
1785                                           pages, nr))
1786                                 return;
1787                 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
1788                         if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
1789                                          PGDIR_SHIFT, next, write, pages, nr))
1790                                 return;
1791                 } else if (!gup_p4d_range(pgd, addr, next, write, pages, nr))
1792                         return;
1793         } while (pgdp++, addr = next, addr != end);
1794 }
1795
1796 #ifndef gup_fast_permitted
1797 /*
1798  * Check if it's allowed to use __get_user_pages_fast() for the range, or
1799  * we need to fall back to the slow version:
1800  */
1801 bool gup_fast_permitted(unsigned long start, int nr_pages, int write)
1802 {
1803         unsigned long len, end;
1804
1805         len = (unsigned long) nr_pages << PAGE_SHIFT;
1806         end = start + len;
1807         return end >= start;
1808 }
1809 #endif
1810
1811 /*
1812  * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
1813  * the regular GUP. It will only return non-negative values.
1814  *
1815  * Careful, careful! COW breaking can go either way, so a non-write
1816  * access can get ambiguous page results. If you call this function without
1817  * 'write' set, you'd better be sure that you're ok with that ambiguity.
1818  */
1819 int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
1820                           struct page **pages)
1821 {
1822         unsigned long addr, len, end;
1823         unsigned long flags;
1824         int nr = 0;
1825
1826         start &= PAGE_MASK;
1827         addr = start;
1828         len = (unsigned long) nr_pages << PAGE_SHIFT;
1829         end = start + len;
1830
1831         if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ,
1832                                         (void __user *)start, len)))
1833                 return 0;
1834
1835         /*
1836          * Disable interrupts.  We use the nested form as we can already have
1837          * interrupts disabled by get_futex_key.
1838          *
1839          * With interrupts disabled, we block page table pages from being
1840          * freed from under us. See mmu_gather_tlb in asm-generic/tlb.h
1841          * for more details.
1842          *
1843          * We do not adopt an rcu_read_lock(.) here as we also want to
1844          * block IPIs that come from THPs splitting.
1845          *
1846          * NOTE! We allow read-only gup_fast() here, but you'd better be
1847          * careful about possible COW pages. You'll get _a_ COW page, but
1848          * not necessarily the one you intended to get depending on what
1849          * COW event happens after this. COW may break the page copy in a
1850          * random direction.
1851          */
1852
1853         if (gup_fast_permitted(start, nr_pages, write)) {
1854                 local_irq_save(flags);
1855                 gup_pgd_range(addr, end, write, pages, &nr);
1856                 local_irq_restore(flags);
1857         }
1858
1859         return nr;
1860 }
1861
1862 /**
1863  * get_user_pages_fast() - pin user pages in memory
1864  * @start:      starting user address
1865  * @nr_pages:   number of pages from start to pin
1866  * @write:      whether pages will be written to
1867  * @pages:      array that receives pointers to the pages pinned.
1868  *              Should be at least nr_pages long.
1869  *
1870  * Attempt to pin user pages in memory without taking mm->mmap_sem.
1871  * If not successful, it will fall back to taking the lock and
1872  * calling get_user_pages().
1873  *
1874  * Returns number of pages pinned. This may be fewer than the number
1875  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1876  * were pinned, returns -errno.
1877  */
1878 int get_user_pages_fast(unsigned long start, int nr_pages, int write,
1879                         struct page **pages)
1880 {
1881         unsigned long addr, len, end;
1882         int nr = 0, ret = 0;
1883
1884         start &= PAGE_MASK;
1885         addr = start;
1886         len = (unsigned long) nr_pages << PAGE_SHIFT;
1887         end = start + len;
1888
1889         if (nr_pages <= 0)
1890                 return 0;
1891
1892         if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ,
1893                                         (void __user *)start, len)))
1894                 return -EFAULT;
1895
1896         /*
1897          * The FAST_GUP case requires FOLL_WRITE even for pure reads,
1898          * because get_user_pages() may need to cause an early COW in
1899          * order to avoid confusing the normal COW routines. So only
1900          * targets that are already writable are safe to do by just
1901          * looking at the page tables.
1902          */
1903         if (gup_fast_permitted(start, nr_pages, write)) {
1904                 local_irq_disable();
1905                 gup_pgd_range(addr, end, 1, pages, &nr);
1906                 local_irq_enable();
1907                 ret = nr;
1908         }
1909
1910         if (nr < nr_pages) {
1911                 /* Try to get the remaining pages with get_user_pages */
1912                 start += nr << PAGE_SHIFT;
1913                 pages += nr;
1914
1915                 ret = get_user_pages_unlocked(start, nr_pages - nr, pages,
1916                                 write ? FOLL_WRITE : 0);
1917
1918                 /* Have to be a bit careful with return values */
1919                 if (nr > 0) {
1920                         if (ret < 0)
1921                                 ret = nr;
1922                         else
1923                                 ret += nr;
1924                 }
1925         }
1926
1927         return ret;
1928 }
1929
1930 #endif /* CONFIG_HAVE_GENERIC_GUP */