]> rtime.felk.cvut.cz Git - hercules2020/nv-tegra/linux-4.4.git/blob - mm/gup.c
pcie: host: tegra: fix bus data memory permissions
[hercules2020/nv-tegra/linux-4.4.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/pagemap.h>
8 #include <linux/rmap.h>
9 #include <linux/swap.h>
10 #include <linux/swapops.h>
11 #include <linux/dma-contiguous.h>
12
13 #include <linux/sched.h>
14 #include <linux/rwsem.h>
15 #include <linux/hugetlb.h>
16 #include <linux/migrate.h>
17
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 #define FOLL_CMA 0x10000000
40
41 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
42                 pte_t *pte, unsigned int flags)
43 {
44         /* No page to get reference */
45         if (flags & FOLL_GET)
46                 return -EFAULT;
47
48         if (flags & FOLL_TOUCH) {
49                 pte_t entry = *pte;
50
51                 if (flags & FOLL_WRITE)
52                         entry = pte_mkdirty(entry);
53                 entry = pte_mkyoung(entry);
54
55                 if (!pte_same(*pte, entry)) {
56                         set_pte_at(vma->vm_mm, address, pte, entry);
57                         update_mmu_cache(vma, address, pte);
58                 }
59         }
60
61         /* Proper page table entry exists, but no corresponding struct page */
62         return -EEXIST;
63 }
64
65 /*
66  * FOLL_FORCE can write to even unwritable pte's, but only
67  * after we've gone through a COW cycle and they are dirty.
68  */
69 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
70 {
71         return pte_write(pte) ||
72                 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
73 }
74
75 static struct page *follow_page_pte(struct vm_area_struct *vma,
76                 unsigned long address, pmd_t *pmd, unsigned int flags)
77 {
78         struct mm_struct *mm = vma->vm_mm;
79         struct page *page;
80         spinlock_t *ptl;
81         pte_t *ptep, pte;
82         bool replace_page = false;
83
84 retry:
85         if (unlikely(pmd_bad(*pmd)))
86                 return no_page_table(vma, flags);
87
88         ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
89         pte = *ptep;
90         if (!pte_present(pte)) {
91                 swp_entry_t entry;
92                 /*
93                  * KSM's break_ksm() relies upon recognizing a ksm page
94                  * even while it is being migrated, so for that case we
95                  * need migration_entry_wait().
96                  */
97                 if (likely(!(flags & FOLL_MIGRATION)))
98                         goto no_page;
99                 if (pte_none(pte))
100                         goto no_page;
101                 entry = pte_to_swp_entry(pte);
102                 if (!is_migration_entry(entry))
103                         goto no_page;
104                 pte_unmap_unlock(ptep, ptl);
105                 migration_entry_wait(mm, pmd, address);
106                 goto retry;
107         }
108         if ((flags & FOLL_NUMA) && pte_protnone(pte))
109                 goto no_page;
110         if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
111                 pte_unmap_unlock(ptep, ptl);
112                 return NULL;
113         }
114
115         page = vm_normal_page(vma, address, pte);
116         if (unlikely(!page)) {
117                 if (flags & FOLL_DUMP) {
118                         /* Avoid special (like zero) pages in core dumps */
119                         page = ERR_PTR(-EFAULT);
120                         goto out;
121                 }
122
123                 if (is_zero_pfn(pte_pfn(pte))) {
124                         page = pte_page(pte);
125                 } else {
126                         int ret;
127
128                         ret = follow_pfn_pte(vma, address, ptep, flags);
129                         page = ERR_PTR(ret);
130                         goto out;
131                 }
132         }
133
134         if ((flags & FOLL_CMA) && (flags & FOLL_GET) &&
135                 dma_contiguous_should_replace_page(page))
136                 /*
137                  * Don't get ref on page.
138                  * Let __get_user_pages replace the CMA page with non-CMA.
139                  */
140                 replace_page = true;
141         else if (flags & FOLL_GET)
142                 get_page_foll(page);
143
144         if (flags & FOLL_TOUCH) {
145                 if ((flags & FOLL_WRITE) &&
146                     !pte_dirty(pte) && !PageDirty(page))
147                         set_page_dirty(page);
148                 /*
149                  * pte_mkyoung() would be more correct here, but atomic care
150                  * is needed to avoid losing the dirty bit: it is easier to use
151                  * mark_page_accessed().
152                  */
153                 mark_page_accessed(page);
154         }
155         if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
156                 /*
157                  * The preliminary mapping check is mainly to avoid the
158                  * pointless overhead of lock_page on the ZERO_PAGE
159                  * which might bounce very badly if there is contention.
160                  *
161                  * If the page is already locked, we don't need to
162                  * handle it now - vmscan will handle it later if and
163                  * when it attempts to reclaim the page.
164                  */
165                 if (page->mapping && trylock_page(page)) {
166                         lru_add_drain();  /* push cached pages to LRU */
167                         /*
168                          * Because we lock page here, and migration is
169                          * blocked by the pte's page reference, and we
170                          * know the page is still mapped, we don't even
171                          * need to check for file-cache page truncation.
172                          */
173                         mlock_vma_page(page);
174                         unlock_page(page);
175                 }
176         }
177 out:
178         pte_unmap_unlock(ptep, ptl);
179         if (replace_page && !IS_ERR(page))
180                 return (struct page *)((ulong)page + 1);
181         return page;
182 no_page:
183         pte_unmap_unlock(ptep, ptl);
184         if (!pte_none(pte))
185                 return NULL;
186         return no_page_table(vma, flags);
187 }
188
189 /**
190  * follow_page_mask - look up a page descriptor from a user-virtual address
191  * @vma: vm_area_struct mapping @address
192  * @address: virtual address to look up
193  * @flags: flags modifying lookup behaviour
194  * @page_mask: on output, *page_mask is set according to the size of the page
195  *
196  * @flags can have FOLL_ flags set, defined in <linux/mm.h>
197  *
198  * Returns the mapped (struct page *), %NULL if no mapping exists, or
199  * an error pointer if there is a mapping to something not represented
200  * by a page descriptor (see also vm_normal_page()).
201  */
202 struct page *follow_page_mask(struct vm_area_struct *vma,
203                               unsigned long address, unsigned int flags,
204                               unsigned int *page_mask)
205 {
206         pgd_t *pgd;
207         pud_t *pud;
208         pmd_t *pmd;
209         spinlock_t *ptl;
210         struct page *page;
211         struct mm_struct *mm = vma->vm_mm;
212
213         *page_mask = 0;
214
215         page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
216         if (!IS_ERR(page)) {
217                 BUG_ON(flags & FOLL_GET);
218                 return page;
219         }
220
221         pgd = pgd_offset(mm, address);
222         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
223                 return no_page_table(vma, flags);
224
225         pud = pud_offset(pgd, address);
226         if (pud_none(*pud))
227                 return no_page_table(vma, flags);
228         if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
229                 page = follow_huge_pud(mm, address, pud, flags);
230                 if (page)
231                         return page;
232                 return no_page_table(vma, flags);
233         }
234         if (unlikely(pud_bad(*pud)))
235                 return no_page_table(vma, flags);
236
237         pmd = pmd_offset(pud, address);
238         if (pmd_none(*pmd))
239                 return no_page_table(vma, flags);
240         if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) {
241                 page = follow_huge_pmd(mm, address, pmd, flags);
242                 if (page)
243                         return page;
244                 return no_page_table(vma, flags);
245         }
246         if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
247                 return no_page_table(vma, flags);
248         if (pmd_trans_huge(*pmd)) {
249                 if (flags & FOLL_SPLIT) {
250                         split_huge_page_pmd(vma, address, pmd);
251                         return follow_page_pte(vma, address, pmd, flags);
252                 }
253                 ptl = pmd_lock(mm, pmd);
254                 if (likely(pmd_trans_huge(*pmd))) {
255                         if (unlikely(pmd_trans_splitting(*pmd))) {
256                                 spin_unlock(ptl);
257                                 wait_split_huge_page(vma->anon_vma, pmd);
258                         } else {
259                                 page = follow_trans_huge_pmd(vma, address,
260                                                              pmd, flags);
261                                 spin_unlock(ptl);
262                                 *page_mask = HPAGE_PMD_NR - 1;
263                                 return page;
264                         }
265                 } else
266                         spin_unlock(ptl);
267         }
268         return follow_page_pte(vma, address, pmd, flags);
269 }
270
271 static int get_gate_page(struct mm_struct *mm, unsigned long address,
272                 unsigned int gup_flags, struct vm_area_struct **vma,
273                 struct page **page)
274 {
275         pgd_t *pgd;
276         pud_t *pud;
277         pmd_t *pmd;
278         pte_t *pte;
279         int ret = -EFAULT;
280
281         /* user gate pages are read-only */
282         if (gup_flags & FOLL_WRITE)
283                 return -EFAULT;
284         if (address > TASK_SIZE)
285                 pgd = pgd_offset_k(address);
286         else
287                 pgd = pgd_offset_gate(mm, address);
288         BUG_ON(pgd_none(*pgd));
289         pud = pud_offset(pgd, address);
290         BUG_ON(pud_none(*pud));
291         pmd = pmd_offset(pud, address);
292         if (pmd_none(*pmd))
293                 return -EFAULT;
294         VM_BUG_ON(pmd_trans_huge(*pmd));
295         pte = pte_offset_map(pmd, address);
296         if (pte_none(*pte))
297                 goto unmap;
298         *vma = get_gate_vma(mm);
299         if (!page)
300                 goto out;
301         *page = vm_normal_page(*vma, address, *pte);
302         if (!*page) {
303                 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
304                         goto unmap;
305                 *page = pte_page(*pte);
306         }
307         get_page(*page);
308 out:
309         ret = 0;
310 unmap:
311         pte_unmap(pte);
312         return ret;
313 }
314
315 /*
316  * mmap_sem must be held on entry.  If @nonblocking != NULL and
317  * *@flags does not include FOLL_NOWAIT, the mmap_sem may be released.
318  * If it is, *@nonblocking will be set to 0 and -EBUSY returned.
319  */
320 static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
321                 unsigned long address, unsigned int *flags, int *nonblocking)
322 {
323         struct mm_struct *mm = vma->vm_mm;
324         unsigned int fault_flags = 0;
325         int ret;
326
327         if (*flags & FOLL_DURABLE)
328                 fault_flags |= FAULT_FLAG_NO_CMA;
329
330         /* mlock all present pages, but do not fault in new pages */
331         if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
332                 return -ENOENT;
333         /* For mm_populate(), just skip the stack guard page. */
334         if ((*flags & FOLL_POPULATE) &&
335                         (stack_guard_page_start(vma, address) ||
336                          stack_guard_page_end(vma, address + PAGE_SIZE)))
337                 return -ENOENT;
338         if (*flags & FOLL_WRITE)
339                 fault_flags |= FAULT_FLAG_WRITE;
340         if (nonblocking)
341                 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
342         if (*flags & FOLL_NOWAIT)
343                 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
344         if (*flags & FOLL_TRIED) {
345                 VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
346                 fault_flags |= FAULT_FLAG_TRIED;
347         }
348
349         ret = handle_mm_fault(mm, vma, address, fault_flags);
350         if (ret & VM_FAULT_ERROR) {
351                 if (ret & VM_FAULT_OOM)
352                         return -ENOMEM;
353                 if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
354                         return *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT;
355                 if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
356                         return -EFAULT;
357                 BUG();
358         }
359
360         if (tsk) {
361                 if (ret & VM_FAULT_MAJOR)
362                         tsk->maj_flt++;
363                 else
364                         tsk->min_flt++;
365         }
366
367         if (ret & VM_FAULT_RETRY) {
368                 if (nonblocking)
369                         *nonblocking = 0;
370                 return -EBUSY;
371         }
372
373         /*
374          * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
375          * necessary, even if maybe_mkwrite decided not to set pte_write. We
376          * can thus safely do subsequent page lookups as if they were reads.
377          * But only do so when looping for pte_write is futile: in some cases
378          * userspace may also be wanting to write to the gotten user page,
379          * which a read fault here might prevent (a readonly page might get
380          * reCOWed by userspace write).
381          */
382         if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
383                 *flags |= FOLL_COW;
384         return 0;
385 }
386
387 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
388 {
389         vm_flags_t vm_flags = vma->vm_flags;
390
391         if (vm_flags & (VM_IO | VM_PFNMAP))
392                 return -EFAULT;
393
394         if (gup_flags & FOLL_WRITE) {
395                 if (!(vm_flags & VM_WRITE)) {
396                         if (!(gup_flags & FOLL_FORCE))
397                                 return -EFAULT;
398                         /*
399                          * We used to let the write,force case do COW in a
400                          * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
401                          * set a breakpoint in a read-only mapping of an
402                          * executable, without corrupting the file (yet only
403                          * when that file had been opened for writing!).
404                          * Anon pages in shared mappings are surprising: now
405                          * just reject it.
406                          */
407                         if (!is_cow_mapping(vm_flags)) {
408                                 WARN_ON_ONCE(vm_flags & VM_MAYWRITE);
409                                 return -EFAULT;
410                         }
411                 }
412         } else if (!(vm_flags & VM_READ)) {
413                 if (!(gup_flags & FOLL_FORCE))
414                         return -EFAULT;
415                 /*
416                  * Is there actually any vma we can reach here which does not
417                  * have VM_MAYREAD set?
418                  */
419                 if (!(vm_flags & VM_MAYREAD))
420                         return -EFAULT;
421         }
422         return 0;
423 }
424
425 /**
426  * replace_cma_page() - migrate page out of CMA page blocks
427  * @page:       source page to be migrated
428  *
429  * Returns either the old page (if migration was not possible) or the pointer
430  * to the newly allocated page (with additional reference taken).
431  *
432  * get_user_pages() might take a reference to a page for a long period of time,
433  * what prevent such page from migration. This is fatal to the preffered usage
434  * pattern of CMA pageblocks. This function replaces the given user page with
435  * a new one allocated from NON-MOVABLE pageblock, so locking CMA page can be
436  * avoided.
437  */
438 static inline struct page *migrate_replace_cma_page(struct page *page)
439 {
440         struct page *newpage = alloc_page(GFP_HIGHUSER);
441
442         if (!newpage)
443                 goto out;
444
445         /*
446          * Take additional reference to the new page to ensure it won't get
447          * freed after migration procedure end.
448          */
449         get_page_foll(newpage);
450
451         if (migrate_replace_page(page, newpage) == 0) {
452                 put_page(newpage);
453                 return newpage;
454         }
455
456         put_page(newpage);
457         __free_page(newpage);
458 out:
459         /*
460          * Migration errors in case of get_user_pages() might not
461          * be fatal to CMA itself, so better don't fail here.
462          */
463         return page;
464 }
465
466 /**
467  * __get_user_pages() - pin user pages in memory
468  * @tsk:        task_struct of target task
469  * @mm:         mm_struct of target mm
470  * @start:      starting user address
471  * @nr_pages:   number of pages from start to pin
472  * @gup_flags:  flags modifying pin behaviour
473  * @pages:      array that receives pointers to the pages pinned.
474  *              Should be at least nr_pages long. Or NULL, if caller
475  *              only intends to ensure the pages are faulted in.
476  * @vmas:       array of pointers to vmas corresponding to each page.
477  *              Or NULL if the caller does not require them.
478  * @nonblocking: whether waiting for disk IO or mmap_sem contention
479  *
480  * Returns number of pages pinned. This may be fewer than the number
481  * requested. If nr_pages is 0 or negative, returns 0. If no pages
482  * were pinned, returns -errno. Each page returned must be released
483  * with a put_page() call when it is finished with. vmas will only
484  * remain valid while mmap_sem is held.
485  *
486  * Must be called with mmap_sem held.  It may be released.  See below.
487  *
488  * __get_user_pages walks a process's page tables and takes a reference to
489  * each struct page that each user address corresponds to at a given
490  * instant. That is, it takes the page that would be accessed if a user
491  * thread accesses the given user virtual address at that instant.
492  *
493  * This does not guarantee that the page exists in the user mappings when
494  * __get_user_pages returns, and there may even be a completely different
495  * page there in some cases (eg. if mmapped pagecache has been invalidated
496  * and subsequently re faulted). However it does guarantee that the page
497  * won't be freed completely. And mostly callers simply care that the page
498  * contains data that was valid *at some point in time*. Typically, an IO
499  * or similar operation cannot guarantee anything stronger anyway because
500  * locks can't be held over the syscall boundary.
501  *
502  * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
503  * the page is written to, set_page_dirty (or set_page_dirty_lock, as
504  * appropriate) must be called after the page is finished with, and
505  * before put_page is called.
506  *
507  * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
508  * or mmap_sem contention, and if waiting is needed to pin all pages,
509  * *@nonblocking will be set to 0.  Further, if @gup_flags does not
510  * include FOLL_NOWAIT, the mmap_sem will be released via up_read() in
511  * this case.
512  *
513  * A caller using such a combination of @nonblocking and @gup_flags
514  * must therefore hold the mmap_sem for reading only, and recognize
515  * when it's been released.  Otherwise, it must be held for either
516  * reading or writing and will not be released.
517  *
518  * In most cases, get_user_pages or get_user_pages_fast should be used
519  * instead of __get_user_pages. __get_user_pages should be used only if
520  * you need some special @gup_flags.
521  */
522 long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
523                 unsigned long start, unsigned long nr_pages,
524                 unsigned int gup_flags, struct page **pages,
525                 struct vm_area_struct **vmas, int *nonblocking)
526 {
527         long i = 0;
528         unsigned int page_mask;
529         struct vm_area_struct *vma = NULL;
530
531         if (!nr_pages)
532                 return 0;
533
534         VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
535
536         /*
537          * If FOLL_FORCE is set then do not force a full fault as the hinting
538          * fault information is unrelated to the reference behaviour of a task
539          * using the address space
540          */
541         if (!(gup_flags & FOLL_FORCE))
542                 gup_flags |= FOLL_NUMA;
543
544         do {
545                 struct page *page;
546                 unsigned int foll_flags = gup_flags;
547                 unsigned int page_increm;
548                 static DEFINE_MUTEX(s_follow_page_lock);
549
550                 /* first iteration or cross vma bound */
551                 if (!vma || start >= vma->vm_end) {
552                         vma = find_extend_vma(mm, start);
553                         if (!vma && in_gate_area(mm, start)) {
554                                 int ret;
555                                 ret = get_gate_page(mm, start & PAGE_MASK,
556                                                 gup_flags, &vma,
557                                                 pages ? &pages[i] : NULL);
558                                 if (ret)
559                                         return i ? : ret;
560                                 page_mask = 0;
561                                 goto next_page;
562                         }
563
564                         if (!vma || check_vma_flags(vma, gup_flags))
565                                 return i ? : -EFAULT;
566                         if (is_vm_hugetlb_page(vma)) {
567                                 i = follow_hugetlb_page(mm, vma, pages, vmas,
568                                                 &start, &nr_pages, i,
569                                                 gup_flags);
570                                 continue;
571                         }
572                 }
573 retry:
574                 /*
575                  * If we have a pending SIGKILL, don't keep faulting pages and
576                  * potentially allocating memory.
577                  */
578                 if (unlikely(fatal_signal_pending(current)))
579                         return i ? i : -ERESTARTSYS;
580                 cond_resched();
581                 page = follow_page_mask(vma, start,
582                                 foll_flags | FOLL_CMA, &page_mask);
583                 if (!page) {
584                         int ret;
585                         ret = faultin_page(tsk, vma, start, &foll_flags,
586                                         nonblocking);
587                         switch (ret) {
588                         case 0:
589                                 goto retry;
590                         case -EFAULT:
591                         case -ENOMEM:
592                         case -EHWPOISON:
593                                 return i ? i : ret;
594                         case -EBUSY:
595                                 return i;
596                         case -ENOENT:
597                                 goto next_page;
598                         }
599                         BUG();
600                 } else if (PTR_ERR(page) == -EEXIST) {
601                         /*
602                          * Proper page table entry exists, but no corresponding
603                          * struct page.
604                          */
605                         goto next_page;
606                 } else if (IS_ERR(page)) {
607                         return i ? i : PTR_ERR(page);
608                 }
609
610                 /* Page would have lsb set when CMA page need replacement. */
611                 if (((ulong)page & 0x1) == 0x1) {
612                         struct page *old_page;
613                         unsigned int fault_flags = 0;
614
615                         mutex_lock(&s_follow_page_lock);
616                         page = (struct page *)((ulong)page & ~0x1);
617                         old_page = page;
618                         wait_on_page_locked_timeout(page);
619                         page = migrate_replace_cma_page(page);
620                         /* migration might be successful. vma mapping
621                          * might have changed if there had been a write
622                          * fault from other accesses before migration
623                          * code locked the page. Follow the page again
624                          * to get the latest mapping. If migration was
625                          * successful, follow again would get
626                          * non-CMA page. If there had been a write
627                          * page fault, follow page and CMA page
628                          * replacement(if necessary) would restart with
629                          * new page.
630                          */
631                         if (page == old_page)
632                                 wait_on_page_locked_timeout(page);
633                         if (foll_flags & FOLL_WRITE) {
634                                 /* page would be marked as old during
635                                  * migration. To make it young, call
636                                  * handle_mm_fault.
637                                  * This to avoid the sanity check
638                                  * failures in the calling code, which
639                                  * check for pte write permission
640                                  * bits.
641                                  */
642                                 fault_flags |= FAULT_FLAG_WRITE;
643                                 handle_mm_fault(mm, vma,
644                                         start, fault_flags);
645                         }
646                         foll_flags = gup_flags;
647                         mutex_unlock(&s_follow_page_lock);
648                         goto retry;
649                 }
650
651                 BUG_ON(dma_contiguous_should_replace_page(page) &&
652                         (foll_flags & FOLL_GET));
653
654                 if (pages) {
655                         pages[i] = page;
656                         flush_anon_page(vma, page, start);
657                         flush_dcache_page(page);
658                         page_mask = 0;
659                 }
660 next_page:
661                 if (vmas) {
662                         vmas[i] = vma;
663                         page_mask = 0;
664                 }
665                 page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
666                 if (page_increm > nr_pages)
667                         page_increm = nr_pages;
668                 i += page_increm;
669                 start += page_increm * PAGE_SIZE;
670                 nr_pages -= page_increm;
671         } while (nr_pages);
672         return i;
673 }
674 EXPORT_SYMBOL(__get_user_pages);
675
676 /*
677  * fixup_user_fault() - manually resolve a user page fault
678  * @tsk:        the task_struct to use for page fault accounting, or
679  *              NULL if faults are not to be recorded.
680  * @mm:         mm_struct of target mm
681  * @address:    user address
682  * @fault_flags:flags to pass down to handle_mm_fault()
683  *
684  * This is meant to be called in the specific scenario where for locking reasons
685  * we try to access user memory in atomic context (within a pagefault_disable()
686  * section), this returns -EFAULT, and we want to resolve the user fault before
687  * trying again.
688  *
689  * Typically this is meant to be used by the futex code.
690  *
691  * The main difference with get_user_pages() is that this function will
692  * unconditionally call handle_mm_fault() which will in turn perform all the
693  * necessary SW fixup of the dirty and young bits in the PTE, while
694  * handle_mm_fault() only guarantees to update these in the struct page.
695  *
696  * This is important for some architectures where those bits also gate the
697  * access permission to the page because they are maintained in software.  On
698  * such architectures, gup() will not be enough to make a subsequent access
699  * succeed.
700  *
701  * This has the same semantics wrt the @mm->mmap_sem as does filemap_fault().
702  */
703 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
704                      unsigned long address, unsigned int fault_flags)
705 {
706         struct vm_area_struct *vma;
707         vm_flags_t vm_flags;
708         int ret;
709
710         vma = find_extend_vma(mm, address);
711         if (!vma || address < vma->vm_start)
712                 return -EFAULT;
713
714         vm_flags = (fault_flags & FAULT_FLAG_WRITE) ? VM_WRITE : VM_READ;
715         if (!(vm_flags & vma->vm_flags))
716                 return -EFAULT;
717
718         ret = handle_mm_fault(mm, vma, address, fault_flags);
719         if (ret & VM_FAULT_ERROR) {
720                 if (ret & VM_FAULT_OOM)
721                         return -ENOMEM;
722                 if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
723                         return -EHWPOISON;
724                 if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
725                         return -EFAULT;
726                 BUG();
727         }
728         if (tsk) {
729                 if (ret & VM_FAULT_MAJOR)
730                         tsk->maj_flt++;
731                 else
732                         tsk->min_flt++;
733         }
734         return 0;
735 }
736
737 static __always_inline long __get_user_pages_locked(struct task_struct *tsk,
738                                                 struct mm_struct *mm,
739                                                 unsigned long start,
740                                                 unsigned long nr_pages,
741                                                 int write, int force,
742                                                 struct page **pages,
743                                                 struct vm_area_struct **vmas,
744                                                 int *locked, bool notify_drop,
745                                                 unsigned int flags)
746 {
747         long ret, pages_done;
748         bool lock_dropped;
749
750         if (locked) {
751                 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
752                 BUG_ON(vmas);
753                 /* check caller initialized locked */
754                 BUG_ON(*locked != 1);
755         }
756
757         if (pages)
758                 flags |= FOLL_GET;
759         if (write)
760                 flags |= FOLL_WRITE;
761         if (force)
762                 flags |= FOLL_FORCE;
763
764         pages_done = 0;
765         lock_dropped = false;
766         for (;;) {
767                 ret = __get_user_pages(tsk, mm, start, nr_pages, flags, pages,
768                                        vmas, locked);
769                 if (!locked)
770                         /* VM_FAULT_RETRY couldn't trigger, bypass */
771                         return ret;
772
773                 /* VM_FAULT_RETRY cannot return errors */
774                 if (!*locked) {
775                         BUG_ON(ret < 0);
776                         BUG_ON(ret >= nr_pages);
777                 }
778
779                 if (!pages)
780                         /* If it's a prefault don't insist harder */
781                         return ret;
782
783                 if (ret > 0) {
784                         nr_pages -= ret;
785                         pages_done += ret;
786                         if (!nr_pages)
787                                 break;
788                 }
789                 if (*locked) {
790                         /* VM_FAULT_RETRY didn't trigger */
791                         if (!pages_done)
792                                 pages_done = ret;
793                         break;
794                 }
795                 /* VM_FAULT_RETRY triggered, so seek to the faulting offset */
796                 pages += ret;
797                 start += ret << PAGE_SHIFT;
798
799                 /*
800                  * Repeat on the address that fired VM_FAULT_RETRY
801                  * without FAULT_FLAG_ALLOW_RETRY but with
802                  * FAULT_FLAG_TRIED.
803                  */
804                 *locked = 1;
805                 lock_dropped = true;
806                 down_read(&mm->mmap_sem);
807                 ret = __get_user_pages(tsk, mm, start, 1, flags | FOLL_TRIED,
808                                        pages, NULL, NULL);
809                 if (ret != 1) {
810                         BUG_ON(ret > 1);
811                         if (!pages_done)
812                                 pages_done = ret;
813                         break;
814                 }
815                 nr_pages--;
816                 pages_done++;
817                 if (!nr_pages)
818                         break;
819                 pages++;
820                 start += PAGE_SIZE;
821         }
822         if (notify_drop && lock_dropped && *locked) {
823                 /*
824                  * We must let the caller know we temporarily dropped the lock
825                  * and so the critical section protected by it was lost.
826                  */
827                 up_read(&mm->mmap_sem);
828                 *locked = 0;
829         }
830         return pages_done;
831 }
832
833 /*
834  * We can leverage the VM_FAULT_RETRY functionality in the page fault
835  * paths better by using either get_user_pages_locked() or
836  * get_user_pages_unlocked().
837  *
838  * get_user_pages_locked() is suitable to replace the form:
839  *
840  *      down_read(&mm->mmap_sem);
841  *      do_something()
842  *      get_user_pages(tsk, mm, ..., pages, NULL);
843  *      up_read(&mm->mmap_sem);
844  *
845  *  to:
846  *
847  *      int locked = 1;
848  *      down_read(&mm->mmap_sem);
849  *      do_something()
850  *      get_user_pages_locked(tsk, mm, ..., pages, &locked);
851  *      if (locked)
852  *          up_read(&mm->mmap_sem);
853  */
854 long get_user_pages_locked(struct task_struct *tsk, struct mm_struct *mm,
855                            unsigned long start, unsigned long nr_pages,
856                            int write, int force, struct page **pages,
857                            int *locked)
858 {
859         return __get_user_pages_locked(tsk, mm, start, nr_pages, write, force,
860                                        pages, NULL, locked, true, FOLL_TOUCH);
861 }
862 EXPORT_SYMBOL(get_user_pages_locked);
863
864 /*
865  * Same as get_user_pages_unlocked(...., FOLL_TOUCH) but it allows to
866  * pass additional gup_flags as last parameter (like FOLL_HWPOISON).
867  *
868  * NOTE: here FOLL_TOUCH is not set implicitly and must be set by the
869  * caller if required (just like with __get_user_pages). "FOLL_GET",
870  * "FOLL_WRITE" and "FOLL_FORCE" are set implicitly as needed
871  * according to the parameters "pages", "write", "force"
872  * respectively.
873  */
874 __always_inline long __get_user_pages_unlocked(struct task_struct *tsk, struct mm_struct *mm,
875                                                unsigned long start, unsigned long nr_pages,
876                                                int write, int force, struct page **pages,
877                                                unsigned int gup_flags)
878 {
879         long ret;
880         int locked = 1;
881         down_read(&mm->mmap_sem);
882         ret = __get_user_pages_locked(tsk, mm, start, nr_pages, write, force,
883                                       pages, NULL, &locked, false, gup_flags);
884         if (locked)
885                 up_read(&mm->mmap_sem);
886         return ret;
887 }
888 EXPORT_SYMBOL(__get_user_pages_unlocked);
889
890 /*
891  * get_user_pages_unlocked() is suitable to replace the form:
892  *
893  *      down_read(&mm->mmap_sem);
894  *      get_user_pages(tsk, mm, ..., pages, NULL);
895  *      up_read(&mm->mmap_sem);
896  *
897  *  with:
898  *
899  *      get_user_pages_unlocked(tsk, mm, ..., pages);
900  *
901  * It is functionally equivalent to get_user_pages_fast so
902  * get_user_pages_fast should be used instead, if the two parameters
903  * "tsk" and "mm" are respectively equal to current and current->mm,
904  * or if "force" shall be set to 1 (get_user_pages_fast misses the
905  * "force" parameter).
906  */
907 long get_user_pages_unlocked(struct task_struct *tsk, struct mm_struct *mm,
908                              unsigned long start, unsigned long nr_pages,
909                              int write, int force, struct page **pages)
910 {
911         return __get_user_pages_unlocked(tsk, mm, start, nr_pages, write,
912                                          force, pages, FOLL_TOUCH);
913 }
914 EXPORT_SYMBOL(get_user_pages_unlocked);
915
916 /*
917  * get_user_pages() - pin user pages in memory
918  * @tsk:        the task_struct to use for page fault accounting, or
919  *              NULL if faults are not to be recorded.
920  * @mm:         mm_struct of target mm
921  * @start:      starting user address
922  * @nr_pages:   number of pages from start to pin
923  * @write:      whether pages will be written to by the caller
924  * @force:      whether to force access even when user mapping is currently
925  *              protected (but never forces write access to shared mapping).
926  * @pages:      array that receives pointers to the pages pinned.
927  *              Should be at least nr_pages long. Or NULL, if caller
928  *              only intends to ensure the pages are faulted in.
929  * @vmas:       array of pointers to vmas corresponding to each page.
930  *              Or NULL if the caller does not require them.
931  *
932  * Returns number of pages pinned. This may be fewer than the number
933  * requested. If nr_pages is 0 or negative, returns 0. If no pages
934  * were pinned, returns -errno. Each page returned must be released
935  * with a put_page() call when it is finished with. vmas will only
936  * remain valid while mmap_sem is held.
937  *
938  * Must be called with mmap_sem held for read or write.
939  *
940  * get_user_pages walks a process's page tables and takes a reference to
941  * each struct page that each user address corresponds to at a given
942  * instant. That is, it takes the page that would be accessed if a user
943  * thread accesses the given user virtual address at that instant.
944  *
945  * This does not guarantee that the page exists in the user mappings when
946  * get_user_pages returns, and there may even be a completely different
947  * page there in some cases (eg. if mmapped pagecache has been invalidated
948  * and subsequently re faulted). However it does guarantee that the page
949  * won't be freed completely. And mostly callers simply care that the page
950  * contains data that was valid *at some point in time*. Typically, an IO
951  * or similar operation cannot guarantee anything stronger anyway because
952  * locks can't be held over the syscall boundary.
953  *
954  * If write=0, the page must not be written to. If the page is written to,
955  * set_page_dirty (or set_page_dirty_lock, as appropriate) must be called
956  * after the page is finished with, and before put_page is called.
957  *
958  * get_user_pages is typically used for fewer-copy IO operations, to get a
959  * handle on the memory by some means other than accesses via the user virtual
960  * addresses. The pages may be submitted for DMA to devices or accessed via
961  * their kernel linear mapping (via the kmap APIs). Care should be taken to
962  * use the correct cache flushing APIs.
963  *
964  * See also get_user_pages_fast, for performance critical applications.
965  *
966  * get_user_pages should be phased out in favor of
967  * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
968  * should use get_user_pages because it cannot pass
969  * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
970  */
971 long get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
972                 unsigned long start, unsigned long nr_pages, int write,
973                 int force, struct page **pages, struct vm_area_struct **vmas)
974 {
975         return __get_user_pages_locked(tsk, mm, start, nr_pages, write, force,
976                                        pages, vmas, NULL, false, FOLL_TOUCH);
977 }
978 EXPORT_SYMBOL(get_user_pages);
979
980 /**
981  * populate_vma_page_range() -  populate a range of pages in the vma.
982  * @vma:   target vma
983  * @start: start address
984  * @end:   end address
985  * @nonblocking:
986  *
987  * This takes care of mlocking the pages too if VM_LOCKED is set.
988  *
989  * return 0 on success, negative error code on error.
990  *
991  * vma->vm_mm->mmap_sem must be held.
992  *
993  * If @nonblocking is NULL, it may be held for read or write and will
994  * be unperturbed.
995  *
996  * If @nonblocking is non-NULL, it must held for read only and may be
997  * released.  If it's released, *@nonblocking will be set to 0.
998  */
999 long populate_vma_page_range(struct vm_area_struct *vma,
1000                 unsigned long start, unsigned long end, int *nonblocking)
1001 {
1002         struct mm_struct *mm = vma->vm_mm;
1003         unsigned long nr_pages = (end - start) / PAGE_SIZE;
1004         int gup_flags;
1005
1006         VM_BUG_ON(start & ~PAGE_MASK);
1007         VM_BUG_ON(end   & ~PAGE_MASK);
1008         VM_BUG_ON_VMA(start < vma->vm_start, vma);
1009         VM_BUG_ON_VMA(end   > vma->vm_end, vma);
1010         VM_BUG_ON_MM(!rwsem_is_locked(&mm->mmap_sem), mm);
1011
1012         gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1013         if (vma->vm_flags & VM_LOCKONFAULT)
1014                 gup_flags &= ~FOLL_POPULATE;
1015
1016         /*
1017          * We want to touch writable mappings with a write fault in order
1018          * to break COW, except for shared mappings because these don't COW
1019          * and we would not want to dirty them for nothing.
1020          */
1021         if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1022                 gup_flags |= FOLL_WRITE;
1023
1024         /*
1025          * We want mlock to succeed for regions that have any permissions
1026          * other than PROT_NONE.
1027          */
1028         if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
1029                 gup_flags |= FOLL_FORCE;
1030
1031         /*
1032          * We made sure addr is within a VMA, so the following will
1033          * not result in a stack expansion that recurses back here.
1034          */
1035         return __get_user_pages(current, mm, start, nr_pages, gup_flags,
1036                                 NULL, NULL, nonblocking);
1037 }
1038
1039 /*
1040  * __mm_populate - populate and/or mlock pages within a range of address space.
1041  *
1042  * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1043  * flags. VMAs must be already marked with the desired vm_flags, and
1044  * mmap_sem must not be held.
1045  */
1046 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1047 {
1048         struct mm_struct *mm = current->mm;
1049         unsigned long end, nstart, nend;
1050         struct vm_area_struct *vma = NULL;
1051         int locked = 0;
1052         long ret = 0;
1053
1054         VM_BUG_ON(start & ~PAGE_MASK);
1055         VM_BUG_ON(len != PAGE_ALIGN(len));
1056         end = start + len;
1057
1058         for (nstart = start; nstart < end; nstart = nend) {
1059                 /*
1060                  * We want to fault in pages for [nstart; end) address range.
1061                  * Find first corresponding VMA.
1062                  */
1063                 if (!locked) {
1064                         locked = 1;
1065                         down_read(&mm->mmap_sem);
1066                         vma = find_vma(mm, nstart);
1067                 } else if (nstart >= vma->vm_end)
1068                         vma = vma->vm_next;
1069                 if (!vma || vma->vm_start >= end)
1070                         break;
1071                 /*
1072                  * Set [nstart; nend) to intersection of desired address
1073                  * range with the first VMA. Also, skip undesirable VMA types.
1074                  */
1075                 nend = min(end, vma->vm_end);
1076                 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1077                         continue;
1078                 if (nstart < vma->vm_start)
1079                         nstart = vma->vm_start;
1080                 /*
1081                  * Now fault in a range of pages. populate_vma_page_range()
1082                  * double checks the vma flags, so that it won't mlock pages
1083                  * if the vma was already munlocked.
1084                  */
1085                 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1086                 if (ret < 0) {
1087                         if (ignore_errors) {
1088                                 ret = 0;
1089                                 continue;       /* continue at next VMA */
1090                         }
1091                         break;
1092                 }
1093                 nend = nstart + ret * PAGE_SIZE;
1094                 ret = 0;
1095         }
1096         if (locked)
1097                 up_read(&mm->mmap_sem);
1098         return ret;     /* 0 or negative error code */
1099 }
1100
1101 /**
1102  * get_dump_page() - pin user page in memory while writing it to core dump
1103  * @addr: user address
1104  *
1105  * Returns struct page pointer of user page pinned for dump,
1106  * to be freed afterwards by page_cache_release() or put_page().
1107  *
1108  * Returns NULL on any kind of failure - a hole must then be inserted into
1109  * the corefile, to preserve alignment with its headers; and also returns
1110  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1111  * allowing a hole to be left in the corefile to save diskspace.
1112  *
1113  * Called without mmap_sem, but after all other threads have been killed.
1114  */
1115 #ifdef CONFIG_ELF_CORE
1116 struct page *get_dump_page(unsigned long addr)
1117 {
1118         struct vm_area_struct *vma;
1119         struct page *page;
1120
1121         if (__get_user_pages(current, current->mm, addr, 1,
1122                              FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
1123                              NULL) < 1)
1124                 return NULL;
1125         flush_cache_page(vma, addr, page_to_pfn(page));
1126         return page;
1127 }
1128 #endif /* CONFIG_ELF_CORE */
1129
1130 /*
1131  * Generic RCU Fast GUP
1132  *
1133  * get_user_pages_fast attempts to pin user pages by walking the page
1134  * tables directly and avoids taking locks. Thus the walker needs to be
1135  * protected from page table pages being freed from under it, and should
1136  * block any THP splits.
1137  *
1138  * One way to achieve this is to have the walker disable interrupts, and
1139  * rely on IPIs from the TLB flushing code blocking before the page table
1140  * pages are freed. This is unsuitable for architectures that do not need
1141  * to broadcast an IPI when invalidating TLBs.
1142  *
1143  * Another way to achieve this is to batch up page table containing pages
1144  * belonging to more than one mm_user, then rcu_sched a callback to free those
1145  * pages. Disabling interrupts will allow the fast_gup walker to both block
1146  * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
1147  * (which is a relatively rare event). The code below adopts this strategy.
1148  *
1149  * Before activating this code, please be aware that the following assumptions
1150  * are currently made:
1151  *
1152  *  *) HAVE_RCU_TABLE_FREE is enabled, and tlb_remove_table is used to free
1153  *      pages containing page tables.
1154  *
1155  *  *) THP splits will broadcast an IPI, this can be achieved by overriding
1156  *      pmdp_splitting_flush.
1157  *
1158  *  *) ptes can be read atomically by the architecture.
1159  *
1160  *  *) access_ok is sufficient to validate userspace address ranges.
1161  *
1162  * The last two assumptions can be relaxed by the addition of helper functions.
1163  *
1164  * This code is based heavily on the PowerPC implementation by Nick Piggin.
1165  */
1166 #ifdef CONFIG_HAVE_GENERIC_RCU_GUP
1167
1168 #ifdef __HAVE_ARCH_PTE_SPECIAL
1169 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1170                          int write, struct page **pages, int *nr)
1171 {
1172         pte_t *ptep, *ptem;
1173         int ret = 0;
1174
1175         ptem = ptep = pte_offset_map(&pmd, addr);
1176         do {
1177                 /*
1178                  * In the line below we are assuming that the pte can be read
1179                  * atomically. If this is not the case for your architecture,
1180                  * please wrap this in a helper function!
1181                  *
1182                  * for an example see gup_get_pte in arch/x86/mm/gup.c
1183                  */
1184                 pte_t pte = READ_ONCE(*ptep);
1185                 struct page *page;
1186
1187                 /*
1188                  * Similar to the PMD case below, NUMA hinting must take slow
1189                  * path using the pte_protnone check.
1190                  */
1191                 if (!pte_present(pte) || pte_special(pte) ||
1192                         pte_protnone(pte) || (write && !pte_write(pte)))
1193                         goto pte_unmap;
1194
1195                 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
1196                 page = pte_page(pte);
1197
1198                 if (!page_cache_get_speculative(page))
1199                         goto pte_unmap;
1200
1201                 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
1202                         put_page(page);
1203                         goto pte_unmap;
1204                 }
1205
1206                 pages[*nr] = page;
1207                 (*nr)++;
1208
1209         } while (ptep++, addr += PAGE_SIZE, addr != end);
1210
1211         ret = 1;
1212
1213 pte_unmap:
1214         pte_unmap(ptem);
1215         return ret;
1216 }
1217 #else
1218
1219 /*
1220  * If we can't determine whether or not a pte is special, then fail immediately
1221  * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
1222  * to be special.
1223  *
1224  * For a futex to be placed on a THP tail page, get_futex_key requires a
1225  * __get_user_pages_fast implementation that can pin pages. Thus it's still
1226  * useful to have gup_huge_pmd even if we can't operate on ptes.
1227  */
1228 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1229                          int write, struct page **pages, int *nr)
1230 {
1231         return 0;
1232 }
1233 #endif /* __HAVE_ARCH_PTE_SPECIAL */
1234
1235 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1236                 unsigned long end, int write, struct page **pages, int *nr)
1237 {
1238         struct page *head, *page, *tail;
1239         int refs;
1240
1241         if (write && !pmd_write(orig))
1242                 return 0;
1243
1244         refs = 0;
1245         head = pmd_page(orig);
1246         page = head + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
1247         tail = page;
1248         do {
1249                 VM_BUG_ON_PAGE(compound_head(page) != head, page);
1250                 pages[*nr] = page;
1251                 (*nr)++;
1252                 page++;
1253                 refs++;
1254         } while (addr += PAGE_SIZE, addr != end);
1255
1256         if (!page_cache_add_speculative(head, refs)) {
1257                 *nr -= refs;
1258                 return 0;
1259         }
1260
1261         if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1262                 *nr -= refs;
1263                 while (refs--)
1264                         put_page(head);
1265                 return 0;
1266         }
1267
1268         /*
1269          * Any tail pages need their mapcount reference taken before we
1270          * return. (This allows the THP code to bump their ref count when
1271          * they are split into base pages).
1272          */
1273         while (refs--) {
1274                 if (PageTail(tail))
1275                         get_huge_page_tail(tail);
1276                 tail++;
1277         }
1278
1279         return 1;
1280 }
1281
1282 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
1283                 unsigned long end, int write, struct page **pages, int *nr)
1284 {
1285         struct page *head, *page, *tail;
1286         int refs;
1287
1288         if (write && !pud_write(orig))
1289                 return 0;
1290
1291         refs = 0;
1292         head = pud_page(orig);
1293         page = head + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
1294         tail = page;
1295         do {
1296                 VM_BUG_ON_PAGE(compound_head(page) != head, page);
1297                 pages[*nr] = page;
1298                 (*nr)++;
1299                 page++;
1300                 refs++;
1301         } while (addr += PAGE_SIZE, addr != end);
1302
1303         if (!page_cache_add_speculative(head, refs)) {
1304                 *nr -= refs;
1305                 return 0;
1306         }
1307
1308         if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1309                 *nr -= refs;
1310                 while (refs--)
1311                         put_page(head);
1312                 return 0;
1313         }
1314
1315         while (refs--) {
1316                 if (PageTail(tail))
1317                         get_huge_page_tail(tail);
1318                 tail++;
1319         }
1320
1321         return 1;
1322 }
1323
1324 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
1325                         unsigned long end, int write,
1326                         struct page **pages, int *nr)
1327 {
1328         int refs;
1329         struct page *head, *page, *tail;
1330
1331         if (write && !pgd_write(orig))
1332                 return 0;
1333
1334         refs = 0;
1335         head = pgd_page(orig);
1336         page = head + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
1337         tail = page;
1338         do {
1339                 VM_BUG_ON_PAGE(compound_head(page) != head, page);
1340                 pages[*nr] = page;
1341                 (*nr)++;
1342                 page++;
1343                 refs++;
1344         } while (addr += PAGE_SIZE, addr != end);
1345
1346         if (!page_cache_add_speculative(head, refs)) {
1347                 *nr -= refs;
1348                 return 0;
1349         }
1350
1351         if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
1352                 *nr -= refs;
1353                 while (refs--)
1354                         put_page(head);
1355                 return 0;
1356         }
1357
1358         while (refs--) {
1359                 if (PageTail(tail))
1360                         get_huge_page_tail(tail);
1361                 tail++;
1362         }
1363
1364         return 1;
1365 }
1366
1367 static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
1368                 int write, struct page **pages, int *nr)
1369 {
1370         unsigned long next;
1371         pmd_t *pmdp;
1372
1373         pmdp = pmd_offset(&pud, addr);
1374         do {
1375                 pmd_t pmd = READ_ONCE(*pmdp);
1376
1377                 next = pmd_addr_end(addr, end);
1378                 if (pmd_none(pmd) || pmd_trans_splitting(pmd))
1379                         return 0;
1380
1381                 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd))) {
1382                         /*
1383                          * NUMA hinting faults need to be handled in the GUP
1384                          * slowpath for accounting purposes and so that they
1385                          * can be serialised against THP migration.
1386                          */
1387                         if (pmd_protnone(pmd))
1388                                 return 0;
1389
1390                         if (!gup_huge_pmd(pmd, pmdp, addr, next, write,
1391                                 pages, nr))
1392                                 return 0;
1393
1394                 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
1395                         /*
1396                          * architecture have different format for hugetlbfs
1397                          * pmd format and THP pmd format
1398                          */
1399                         if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
1400                                          PMD_SHIFT, next, write, pages, nr))
1401                                 return 0;
1402                 } else if (!gup_pte_range(pmd, addr, next, write, pages, nr))
1403                                 return 0;
1404         } while (pmdp++, addr = next, addr != end);
1405
1406         return 1;
1407 }
1408
1409 static int gup_pud_range(pgd_t pgd, unsigned long addr, unsigned long end,
1410                          int write, struct page **pages, int *nr)
1411 {
1412         unsigned long next;
1413         pud_t *pudp;
1414
1415         pudp = pud_offset(&pgd, addr);
1416         do {
1417                 pud_t pud = READ_ONCE(*pudp);
1418
1419                 next = pud_addr_end(addr, end);
1420                 if (pud_none(pud))
1421                         return 0;
1422                 if (unlikely(pud_huge(pud))) {
1423                         if (!gup_huge_pud(pud, pudp, addr, next, write,
1424                                           pages, nr))
1425                                 return 0;
1426                 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
1427                         if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
1428                                          PUD_SHIFT, next, write, pages, nr))
1429                                 return 0;
1430                 } else if (!gup_pmd_range(pud, addr, next, write, pages, nr))
1431                         return 0;
1432         } while (pudp++, addr = next, addr != end);
1433
1434         return 1;
1435 }
1436
1437 /*
1438  * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
1439  * the regular GUP. It will only return non-negative values.
1440  */
1441 int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
1442                           struct page **pages)
1443 {
1444         struct mm_struct *mm = current->mm;
1445         unsigned long addr, len, end;
1446         unsigned long next, flags;
1447         pgd_t *pgdp;
1448         int nr = 0;
1449
1450         start &= PAGE_MASK;
1451         addr = start;
1452         len = (unsigned long) nr_pages << PAGE_SHIFT;
1453         end = start + len;
1454
1455         if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ,
1456                                         start, len)))
1457                 return 0;
1458
1459         /*
1460          * Disable interrupts.  We use the nested form as we can already have
1461          * interrupts disabled by get_futex_key.
1462          *
1463          * With interrupts disabled, we block page table pages from being
1464          * freed from under us. See mmu_gather_tlb in asm-generic/tlb.h
1465          * for more details.
1466          *
1467          * We do not adopt an rcu_read_lock(.) here as we also want to
1468          * block IPIs that come from THPs splitting.
1469          */
1470
1471         local_irq_save(flags);
1472         pgdp = pgd_offset(mm, addr);
1473         do {
1474                 pgd_t pgd = READ_ONCE(*pgdp);
1475
1476                 next = pgd_addr_end(addr, end);
1477                 if (pgd_none(pgd))
1478                         break;
1479                 if (unlikely(pgd_huge(pgd))) {
1480                         if (!gup_huge_pgd(pgd, pgdp, addr, next, write,
1481                                           pages, &nr))
1482                                 break;
1483                 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
1484                         if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
1485                                          PGDIR_SHIFT, next, write, pages, &nr))
1486                                 break;
1487                 } else if (!gup_pud_range(pgd, addr, next, write, pages, &nr))
1488                         break;
1489         } while (pgdp++, addr = next, addr != end);
1490         local_irq_restore(flags);
1491
1492         return nr;
1493 }
1494
1495 /**
1496  * get_user_pages_fast() - pin user pages in memory
1497  * @start:      starting user address
1498  * @nr_pages:   number of pages from start to pin
1499  * @write:      whether pages will be written to
1500  * @pages:      array that receives pointers to the pages pinned.
1501  *              Should be at least nr_pages long.
1502  *
1503  * Attempt to pin user pages in memory without taking mm->mmap_sem.
1504  * If not successful, it will fall back to taking the lock and
1505  * calling get_user_pages().
1506  *
1507  * Returns number of pages pinned. This may be fewer than the number
1508  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1509  * were pinned, returns -errno.
1510  */
1511 int get_user_pages_fast(unsigned long start, int nr_pages, int write,
1512                         struct page **pages)
1513 {
1514         struct mm_struct *mm = current->mm;
1515         int nr, ret;
1516
1517         start &= PAGE_MASK;
1518         nr = __get_user_pages_fast(start, nr_pages, write, pages);
1519         ret = nr;
1520
1521         if (nr < nr_pages) {
1522                 /* Try to get the remaining pages with get_user_pages */
1523                 start += nr << PAGE_SHIFT;
1524                 pages += nr;
1525
1526                 ret = get_user_pages_unlocked(current, mm, start,
1527                                               nr_pages - nr, write, 0, pages);
1528
1529                 /* Have to be a bit careful with return values */
1530                 if (nr > 0) {
1531                         if (ret < 0)
1532                                 ret = nr;
1533                         else
1534                                 ret += nr;
1535                 }
1536         }
1537
1538         return ret;
1539 }
1540
1541 #endif /* CONFIG_HAVE_GENERIC_RCU_GUP */