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