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