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