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