xref: /linux/mm/gup.c (revision 3e7819886281e077e82006fe4804b0d6b0f5643b)
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 #include <linux/shmem_fs.h>
22 
23 #include <asm/mmu_context.h>
24 #include <asm/tlbflush.h>
25 
26 #include "internal.h"
27 
28 struct follow_page_context {
29 	struct dev_pagemap *pgmap;
30 	unsigned int page_mask;
31 };
32 
33 static inline void sanity_check_pinned_pages(struct page **pages,
34 					     unsigned long npages)
35 {
36 	if (!IS_ENABLED(CONFIG_DEBUG_VM))
37 		return;
38 
39 	/*
40 	 * We only pin anonymous pages if they are exclusive. Once pinned, we
41 	 * can no longer turn them possibly shared and PageAnonExclusive() will
42 	 * stick around until the page is freed.
43 	 *
44 	 * We'd like to verify that our pinned anonymous pages are still mapped
45 	 * exclusively. The issue with anon THP is that we don't know how
46 	 * they are/were mapped when pinning them. However, for anon
47 	 * THP we can assume that either the given page (PTE-mapped THP) or
48 	 * the head page (PMD-mapped THP) should be PageAnonExclusive(). If
49 	 * neither is the case, there is certainly something wrong.
50 	 */
51 	for (; npages; npages--, pages++) {
52 		struct page *page = *pages;
53 		struct folio *folio = page_folio(page);
54 
55 		if (is_zero_page(page) ||
56 		    !folio_test_anon(folio))
57 			continue;
58 		if (!folio_test_large(folio) || folio_test_hugetlb(folio))
59 			VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page), page);
60 		else
61 			/* Either a PTE-mapped or a PMD-mapped THP. */
62 			VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page) &&
63 				       !PageAnonExclusive(page), page);
64 	}
65 }
66 
67 /*
68  * Return the folio with ref appropriately incremented,
69  * or NULL if that failed.
70  */
71 static inline struct folio *try_get_folio(struct page *page, int refs)
72 {
73 	struct folio *folio;
74 
75 retry:
76 	folio = page_folio(page);
77 	if (WARN_ON_ONCE(folio_ref_count(folio) < 0))
78 		return NULL;
79 	if (unlikely(!folio_ref_try_add(folio, refs)))
80 		return NULL;
81 
82 	/*
83 	 * At this point we have a stable reference to the folio; but it
84 	 * could be that between calling page_folio() and the refcount
85 	 * increment, the folio was split, in which case we'd end up
86 	 * holding a reference on a folio that has nothing to do with the page
87 	 * we were given anymore.
88 	 * So now that the folio is stable, recheck that the page still
89 	 * belongs to this folio.
90 	 */
91 	if (unlikely(page_folio(page) != folio)) {
92 		if (!put_devmap_managed_folio_refs(folio, refs))
93 			folio_put_refs(folio, refs);
94 		goto retry;
95 	}
96 
97 	return folio;
98 }
99 
100 static void gup_put_folio(struct folio *folio, int refs, unsigned int flags)
101 {
102 	if (flags & FOLL_PIN) {
103 		if (is_zero_folio(folio))
104 			return;
105 		node_stat_mod_folio(folio, NR_FOLL_PIN_RELEASED, refs);
106 		if (folio_test_large(folio))
107 			atomic_sub(refs, &folio->_pincount);
108 		else
109 			refs *= GUP_PIN_COUNTING_BIAS;
110 	}
111 
112 	if (!put_devmap_managed_folio_refs(folio, refs))
113 		folio_put_refs(folio, refs);
114 }
115 
116 /**
117  * try_grab_folio() - add a folio's refcount by a flag-dependent amount
118  * @folio:    pointer to folio to be grabbed
119  * @refs:     the value to (effectively) add to the folio's refcount
120  * @flags:    gup flags: these are the FOLL_* flag values
121  *
122  * This might not do anything at all, depending on the flags argument.
123  *
124  * "grab" names in this file mean, "look at flags to decide whether to use
125  * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
126  *
127  * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
128  * time.
129  *
130  * Return: 0 for success, or if no action was required (if neither FOLL_PIN
131  * nor FOLL_GET was set, nothing is done). A negative error code for failure:
132  *
133  *   -ENOMEM		FOLL_GET or FOLL_PIN was set, but the folio could not
134  *			be grabbed.
135  *
136  * It is called when we have a stable reference for the folio, typically in
137  * GUP slow path.
138  */
139 int __must_check try_grab_folio(struct folio *folio, int refs,
140 				unsigned int flags)
141 {
142 	if (WARN_ON_ONCE(folio_ref_count(folio) <= 0))
143 		return -ENOMEM;
144 
145 	if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(&folio->page)))
146 		return -EREMOTEIO;
147 
148 	if (flags & FOLL_GET)
149 		folio_ref_add(folio, refs);
150 	else if (flags & FOLL_PIN) {
151 		/*
152 		 * Don't take a pin on the zero page - it's not going anywhere
153 		 * and it is used in a *lot* of places.
154 		 */
155 		if (is_zero_folio(folio))
156 			return 0;
157 
158 		/*
159 		 * Increment the normal page refcount field at least once,
160 		 * so that the page really is pinned.
161 		 */
162 		if (folio_test_large(folio)) {
163 			folio_ref_add(folio, refs);
164 			atomic_add(refs, &folio->_pincount);
165 		} else {
166 			folio_ref_add(folio, refs * GUP_PIN_COUNTING_BIAS);
167 		}
168 
169 		node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
170 	}
171 
172 	return 0;
173 }
174 
175 /**
176  * unpin_user_page() - release a dma-pinned page
177  * @page:            pointer to page to be released
178  *
179  * Pages that were pinned via pin_user_pages*() must be released via either
180  * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
181  * that such pages can be separately tracked and uniquely handled. In
182  * particular, interactions with RDMA and filesystems need special handling.
183  */
184 void unpin_user_page(struct page *page)
185 {
186 	sanity_check_pinned_pages(&page, 1);
187 	gup_put_folio(page_folio(page), 1, FOLL_PIN);
188 }
189 EXPORT_SYMBOL(unpin_user_page);
190 
191 /**
192  * folio_add_pin - Try to get an additional pin on a pinned folio
193  * @folio: The folio to be pinned
194  *
195  * Get an additional pin on a folio we already have a pin on.  Makes no change
196  * if the folio is a zero_page.
197  */
198 void folio_add_pin(struct folio *folio)
199 {
200 	if (is_zero_folio(folio))
201 		return;
202 
203 	/*
204 	 * Similar to try_grab_folio(): be sure to *also* increment the normal
205 	 * page refcount field at least once, so that the page really is
206 	 * pinned.
207 	 */
208 	if (folio_test_large(folio)) {
209 		WARN_ON_ONCE(atomic_read(&folio->_pincount) < 1);
210 		folio_ref_inc(folio);
211 		atomic_inc(&folio->_pincount);
212 	} else {
213 		WARN_ON_ONCE(folio_ref_count(folio) < GUP_PIN_COUNTING_BIAS);
214 		folio_ref_add(folio, GUP_PIN_COUNTING_BIAS);
215 	}
216 }
217 
218 static inline struct folio *gup_folio_range_next(struct page *start,
219 		unsigned long npages, unsigned long i, unsigned int *ntails)
220 {
221 	struct page *next = nth_page(start, i);
222 	struct folio *folio = page_folio(next);
223 	unsigned int nr = 1;
224 
225 	if (folio_test_large(folio))
226 		nr = min_t(unsigned int, npages - i,
227 			   folio_nr_pages(folio) - folio_page_idx(folio, next));
228 
229 	*ntails = nr;
230 	return folio;
231 }
232 
233 static inline struct folio *gup_folio_next(struct page **list,
234 		unsigned long npages, unsigned long i, unsigned int *ntails)
235 {
236 	struct folio *folio = page_folio(list[i]);
237 	unsigned int nr;
238 
239 	for (nr = i + 1; nr < npages; nr++) {
240 		if (page_folio(list[nr]) != folio)
241 			break;
242 	}
243 
244 	*ntails = nr - i;
245 	return folio;
246 }
247 
248 /**
249  * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
250  * @pages:  array of pages to be maybe marked dirty, and definitely released.
251  * @npages: number of pages in the @pages array.
252  * @make_dirty: whether to mark the pages dirty
253  *
254  * "gup-pinned page" refers to a page that has had one of the get_user_pages()
255  * variants called on that page.
256  *
257  * For each page in the @pages array, make that page (or its head page, if a
258  * compound page) dirty, if @make_dirty is true, and if the page was previously
259  * listed as clean. In any case, releases all pages using unpin_user_page(),
260  * possibly via unpin_user_pages(), for the non-dirty case.
261  *
262  * Please see the unpin_user_page() documentation for details.
263  *
264  * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
265  * required, then the caller should a) verify that this is really correct,
266  * because _lock() is usually required, and b) hand code it:
267  * set_page_dirty_lock(), unpin_user_page().
268  *
269  */
270 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
271 				 bool make_dirty)
272 {
273 	unsigned long i;
274 	struct folio *folio;
275 	unsigned int nr;
276 
277 	if (!make_dirty) {
278 		unpin_user_pages(pages, npages);
279 		return;
280 	}
281 
282 	sanity_check_pinned_pages(pages, npages);
283 	for (i = 0; i < npages; i += nr) {
284 		folio = gup_folio_next(pages, npages, i, &nr);
285 		/*
286 		 * Checking PageDirty at this point may race with
287 		 * clear_page_dirty_for_io(), but that's OK. Two key
288 		 * cases:
289 		 *
290 		 * 1) This code sees the page as already dirty, so it
291 		 * skips the call to set_page_dirty(). That could happen
292 		 * because clear_page_dirty_for_io() called
293 		 * page_mkclean(), followed by set_page_dirty().
294 		 * However, now the page is going to get written back,
295 		 * which meets the original intention of setting it
296 		 * dirty, so all is well: clear_page_dirty_for_io() goes
297 		 * on to call TestClearPageDirty(), and write the page
298 		 * back.
299 		 *
300 		 * 2) This code sees the page as clean, so it calls
301 		 * set_page_dirty(). The page stays dirty, despite being
302 		 * written back, so it gets written back again in the
303 		 * next writeback cycle. This is harmless.
304 		 */
305 		if (!folio_test_dirty(folio)) {
306 			folio_lock(folio);
307 			folio_mark_dirty(folio);
308 			folio_unlock(folio);
309 		}
310 		gup_put_folio(folio, nr, FOLL_PIN);
311 	}
312 }
313 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
314 
315 /**
316  * unpin_user_page_range_dirty_lock() - release and optionally dirty
317  * gup-pinned page range
318  *
319  * @page:  the starting page of a range maybe marked dirty, and definitely released.
320  * @npages: number of consecutive pages to release.
321  * @make_dirty: whether to mark the pages dirty
322  *
323  * "gup-pinned page range" refers to a range of pages that has had one of the
324  * pin_user_pages() variants called on that page.
325  *
326  * For the page ranges defined by [page .. page+npages], make that range (or
327  * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
328  * page range was previously listed as clean.
329  *
330  * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
331  * required, then the caller should a) verify that this is really correct,
332  * because _lock() is usually required, and b) hand code it:
333  * set_page_dirty_lock(), unpin_user_page().
334  *
335  */
336 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
337 				      bool make_dirty)
338 {
339 	unsigned long i;
340 	struct folio *folio;
341 	unsigned int nr;
342 
343 	for (i = 0; i < npages; i += nr) {
344 		folio = gup_folio_range_next(page, npages, i, &nr);
345 		if (make_dirty && !folio_test_dirty(folio)) {
346 			folio_lock(folio);
347 			folio_mark_dirty(folio);
348 			folio_unlock(folio);
349 		}
350 		gup_put_folio(folio, nr, FOLL_PIN);
351 	}
352 }
353 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
354 
355 static void gup_fast_unpin_user_pages(struct page **pages, unsigned long npages)
356 {
357 	unsigned long i;
358 	struct folio *folio;
359 	unsigned int nr;
360 
361 	/*
362 	 * Don't perform any sanity checks because we might have raced with
363 	 * fork() and some anonymous pages might now actually be shared --
364 	 * which is why we're unpinning after all.
365 	 */
366 	for (i = 0; i < npages; i += nr) {
367 		folio = gup_folio_next(pages, npages, i, &nr);
368 		gup_put_folio(folio, nr, FOLL_PIN);
369 	}
370 }
371 
372 /**
373  * unpin_user_pages() - release an array of gup-pinned pages.
374  * @pages:  array of pages to be marked dirty and released.
375  * @npages: number of pages in the @pages array.
376  *
377  * For each page in the @pages array, release the page using unpin_user_page().
378  *
379  * Please see the unpin_user_page() documentation for details.
380  */
381 void unpin_user_pages(struct page **pages, unsigned long npages)
382 {
383 	unsigned long i;
384 	struct folio *folio;
385 	unsigned int nr;
386 
387 	/*
388 	 * If this WARN_ON() fires, then the system *might* be leaking pages (by
389 	 * leaving them pinned), but probably not. More likely, gup/pup returned
390 	 * a hard -ERRNO error to the caller, who erroneously passed it here.
391 	 */
392 	if (WARN_ON(IS_ERR_VALUE(npages)))
393 		return;
394 
395 	sanity_check_pinned_pages(pages, npages);
396 	for (i = 0; i < npages; i += nr) {
397 		folio = gup_folio_next(pages, npages, i, &nr);
398 		gup_put_folio(folio, nr, FOLL_PIN);
399 	}
400 }
401 EXPORT_SYMBOL(unpin_user_pages);
402 
403 /*
404  * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
405  * lifecycle.  Avoid setting the bit unless necessary, or it might cause write
406  * cache bouncing on large SMP machines for concurrent pinned gups.
407  */
408 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
409 {
410 	if (!test_bit(MMF_HAS_PINNED, mm_flags))
411 		set_bit(MMF_HAS_PINNED, mm_flags);
412 }
413 
414 #ifdef CONFIG_MMU
415 
416 #if defined(CONFIG_ARCH_HAS_HUGEPD) || defined(CONFIG_HAVE_GUP_FAST)
417 static int record_subpages(struct page *page, unsigned long sz,
418 			   unsigned long addr, unsigned long end,
419 			   struct page **pages)
420 {
421 	struct page *start_page;
422 	int nr;
423 
424 	start_page = nth_page(page, (addr & (sz - 1)) >> PAGE_SHIFT);
425 	for (nr = 0; addr != end; nr++, addr += PAGE_SIZE)
426 		pages[nr] = nth_page(start_page, nr);
427 
428 	return nr;
429 }
430 
431 /**
432  * try_grab_folio_fast() - Attempt to get or pin a folio in fast path.
433  * @page:  pointer to page to be grabbed
434  * @refs:  the value to (effectively) add to the folio's refcount
435  * @flags: gup flags: these are the FOLL_* flag values.
436  *
437  * "grab" names in this file mean, "look at flags to decide whether to use
438  * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
439  *
440  * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
441  * same time. (That's true throughout the get_user_pages*() and
442  * pin_user_pages*() APIs.) Cases:
443  *
444  *    FOLL_GET: folio's refcount will be incremented by @refs.
445  *
446  *    FOLL_PIN on large folios: folio's refcount will be incremented by
447  *    @refs, and its pincount will be incremented by @refs.
448  *
449  *    FOLL_PIN on single-page folios: folio's refcount will be incremented by
450  *    @refs * GUP_PIN_COUNTING_BIAS.
451  *
452  * Return: The folio containing @page (with refcount appropriately
453  * incremented) for success, or NULL upon failure. If neither FOLL_GET
454  * nor FOLL_PIN was set, that's considered failure, and furthermore,
455  * a likely bug in the caller, so a warning is also emitted.
456  *
457  * It uses add ref unless zero to elevate the folio refcount and must be called
458  * in fast path only.
459  */
460 static struct folio *try_grab_folio_fast(struct page *page, int refs,
461 					 unsigned int flags)
462 {
463 	struct folio *folio;
464 
465 	/* Raise warn if it is not called in fast GUP */
466 	VM_WARN_ON_ONCE(!irqs_disabled());
467 
468 	if (WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == 0))
469 		return NULL;
470 
471 	if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)))
472 		return NULL;
473 
474 	if (flags & FOLL_GET)
475 		return try_get_folio(page, refs);
476 
477 	/* FOLL_PIN is set */
478 
479 	/*
480 	 * Don't take a pin on the zero page - it's not going anywhere
481 	 * and it is used in a *lot* of places.
482 	 */
483 	if (is_zero_page(page))
484 		return page_folio(page);
485 
486 	folio = try_get_folio(page, refs);
487 	if (!folio)
488 		return NULL;
489 
490 	/*
491 	 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
492 	 * right zone, so fail and let the caller fall back to the slow
493 	 * path.
494 	 */
495 	if (unlikely((flags & FOLL_LONGTERM) &&
496 		     !folio_is_longterm_pinnable(folio))) {
497 		if (!put_devmap_managed_folio_refs(folio, refs))
498 			folio_put_refs(folio, refs);
499 		return NULL;
500 	}
501 
502 	/*
503 	 * When pinning a large folio, use an exact count to track it.
504 	 *
505 	 * However, be sure to *also* increment the normal folio
506 	 * refcount field at least once, so that the folio really
507 	 * is pinned.  That's why the refcount from the earlier
508 	 * try_get_folio() is left intact.
509 	 */
510 	if (folio_test_large(folio))
511 		atomic_add(refs, &folio->_pincount);
512 	else
513 		folio_ref_add(folio,
514 				refs * (GUP_PIN_COUNTING_BIAS - 1));
515 	/*
516 	 * Adjust the pincount before re-checking the PTE for changes.
517 	 * This is essentially a smp_mb() and is paired with a memory
518 	 * barrier in folio_try_share_anon_rmap_*().
519 	 */
520 	smp_mb__after_atomic();
521 
522 	node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
523 
524 	return folio;
525 }
526 #endif	/* CONFIG_ARCH_HAS_HUGEPD || CONFIG_HAVE_GUP_FAST */
527 
528 #ifdef CONFIG_ARCH_HAS_HUGEPD
529 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
530 				      unsigned long sz)
531 {
532 	unsigned long __boundary = (addr + sz) & ~(sz-1);
533 	return (__boundary - 1 < end - 1) ? __boundary : end;
534 }
535 
536 /*
537  * Returns 1 if succeeded, 0 if failed, -EMLINK if unshare needed.
538  *
539  * NOTE: for the same entry, gup-fast and gup-slow can return different
540  * results (0 v.s. -EMLINK) depending on whether vma is available.  This is
541  * the expected behavior, where we simply want gup-fast to fallback to
542  * gup-slow to take the vma reference first.
543  */
544 static int gup_hugepte(struct vm_area_struct *vma, pte_t *ptep, unsigned long sz,
545 		       unsigned long addr, unsigned long end, unsigned int flags,
546 		       struct page **pages, int *nr, bool fast)
547 {
548 	unsigned long pte_end;
549 	struct page *page;
550 	struct folio *folio;
551 	pte_t pte;
552 	int refs;
553 
554 	pte_end = (addr + sz) & ~(sz-1);
555 	if (pte_end < end)
556 		end = pte_end;
557 
558 	pte = huge_ptep_get(ptep);
559 
560 	if (!pte_access_permitted(pte, flags & FOLL_WRITE))
561 		return 0;
562 
563 	/* hugepages are never "special" */
564 	VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
565 
566 	page = pte_page(pte);
567 	refs = record_subpages(page, sz, addr, end, pages + *nr);
568 
569 	if (fast) {
570 		folio = try_grab_folio_fast(page, refs, flags);
571 		if (!folio)
572 			return 0;
573 	} else {
574 		folio = page_folio(page);
575 		if (try_grab_folio(folio, refs, flags))
576 			return 0;
577 	}
578 
579 	if (unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
580 		gup_put_folio(folio, refs, flags);
581 		return 0;
582 	}
583 
584 	if (!pte_write(pte) && gup_must_unshare(vma, flags, &folio->page)) {
585 		gup_put_folio(folio, refs, flags);
586 		return -EMLINK;
587 	}
588 
589 	*nr += refs;
590 	folio_set_referenced(folio);
591 	return 1;
592 }
593 
594 /*
595  * NOTE: currently GUP for a hugepd is only possible on hugetlbfs file
596  * systems on Power, which does not have issue with folio writeback against
597  * GUP updates.  When hugepd will be extended to support non-hugetlbfs or
598  * even anonymous memory, we need to do extra check as what we do with most
599  * of the other folios. See writable_file_mapping_allowed() and
600  * gup_fast_folio_allowed() for more information.
601  */
602 static int gup_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
603 		      unsigned long addr, unsigned int pdshift,
604 		      unsigned long end, unsigned int flags,
605 		      struct page **pages, int *nr, bool fast)
606 {
607 	pte_t *ptep;
608 	unsigned long sz = 1UL << hugepd_shift(hugepd);
609 	unsigned long next;
610 	int ret;
611 
612 	ptep = hugepte_offset(hugepd, addr, pdshift);
613 	do {
614 		next = hugepte_addr_end(addr, end, sz);
615 		ret = gup_hugepte(vma, ptep, sz, addr, end, flags, pages, nr,
616 				  fast);
617 		if (ret != 1)
618 			return ret;
619 	} while (ptep++, addr = next, addr != end);
620 
621 	return 1;
622 }
623 
624 static struct page *follow_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
625 				  unsigned long addr, unsigned int pdshift,
626 				  unsigned int flags,
627 				  struct follow_page_context *ctx)
628 {
629 	struct page *page;
630 	struct hstate *h;
631 	spinlock_t *ptl;
632 	int nr = 0, ret;
633 	pte_t *ptep;
634 
635 	/* Only hugetlb supports hugepd */
636 	if (WARN_ON_ONCE(!is_vm_hugetlb_page(vma)))
637 		return ERR_PTR(-EFAULT);
638 
639 	h = hstate_vma(vma);
640 	ptep = hugepte_offset(hugepd, addr, pdshift);
641 	ptl = huge_pte_lock(h, vma->vm_mm, ptep);
642 	ret = gup_hugepd(vma, hugepd, addr, pdshift, addr + PAGE_SIZE,
643 			 flags, &page, &nr, false);
644 	spin_unlock(ptl);
645 
646 	if (ret == 1) {
647 		/* GUP succeeded */
648 		WARN_ON_ONCE(nr != 1);
649 		ctx->page_mask = (1U << huge_page_order(h)) - 1;
650 		return page;
651 	}
652 
653 	/* ret can be either 0 (translates to NULL) or negative */
654 	return ERR_PTR(ret);
655 }
656 #else /* CONFIG_ARCH_HAS_HUGEPD */
657 static inline int gup_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
658 			     unsigned long addr, unsigned int pdshift,
659 			     unsigned long end, unsigned int flags,
660 			     struct page **pages, int *nr, bool fast)
661 {
662 	return 0;
663 }
664 
665 static struct page *follow_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
666 				  unsigned long addr, unsigned int pdshift,
667 				  unsigned int flags,
668 				  struct follow_page_context *ctx)
669 {
670 	return NULL;
671 }
672 #endif /* CONFIG_ARCH_HAS_HUGEPD */
673 
674 
675 static struct page *no_page_table(struct vm_area_struct *vma,
676 				  unsigned int flags, unsigned long address)
677 {
678 	if (!(flags & FOLL_DUMP))
679 		return NULL;
680 
681 	/*
682 	 * When core dumping, we don't want to allocate unnecessary pages or
683 	 * page tables.  Return error instead of NULL to skip handle_mm_fault,
684 	 * then get_dump_page() will return NULL to leave a hole in the dump.
685 	 * But we can only make this optimization where a hole would surely
686 	 * be zero-filled if handle_mm_fault() actually did handle it.
687 	 */
688 	if (is_vm_hugetlb_page(vma)) {
689 		struct hstate *h = hstate_vma(vma);
690 
691 		if (!hugetlbfs_pagecache_present(h, vma, address))
692 			return ERR_PTR(-EFAULT);
693 	} else if ((vma_is_anonymous(vma) || !vma->vm_ops->fault)) {
694 		return ERR_PTR(-EFAULT);
695 	}
696 
697 	return NULL;
698 }
699 
700 #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES
701 static struct page *follow_huge_pud(struct vm_area_struct *vma,
702 				    unsigned long addr, pud_t *pudp,
703 				    int flags, struct follow_page_context *ctx)
704 {
705 	struct mm_struct *mm = vma->vm_mm;
706 	struct page *page;
707 	pud_t pud = *pudp;
708 	unsigned long pfn = pud_pfn(pud);
709 	int ret;
710 
711 	assert_spin_locked(pud_lockptr(mm, pudp));
712 
713 	if ((flags & FOLL_WRITE) && !pud_write(pud))
714 		return NULL;
715 
716 	if (!pud_present(pud))
717 		return NULL;
718 
719 	pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
720 
721 	if (IS_ENABLED(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) &&
722 	    pud_devmap(pud)) {
723 		/*
724 		 * device mapped pages can only be returned if the caller
725 		 * will manage the page reference count.
726 		 *
727 		 * At least one of FOLL_GET | FOLL_PIN must be set, so
728 		 * assert that here:
729 		 */
730 		if (!(flags & (FOLL_GET | FOLL_PIN)))
731 			return ERR_PTR(-EEXIST);
732 
733 		if (flags & FOLL_TOUCH)
734 			touch_pud(vma, addr, pudp, flags & FOLL_WRITE);
735 
736 		ctx->pgmap = get_dev_pagemap(pfn, ctx->pgmap);
737 		if (!ctx->pgmap)
738 			return ERR_PTR(-EFAULT);
739 	}
740 
741 	page = pfn_to_page(pfn);
742 
743 	if (!pud_devmap(pud) && !pud_write(pud) &&
744 	    gup_must_unshare(vma, flags, page))
745 		return ERR_PTR(-EMLINK);
746 
747 	ret = try_grab_folio(page_folio(page), 1, flags);
748 	if (ret)
749 		page = ERR_PTR(ret);
750 	else
751 		ctx->page_mask = HPAGE_PUD_NR - 1;
752 
753 	return page;
754 }
755 
756 /* FOLL_FORCE can write to even unwritable PMDs in COW mappings. */
757 static inline bool can_follow_write_pmd(pmd_t pmd, struct page *page,
758 					struct vm_area_struct *vma,
759 					unsigned int flags)
760 {
761 	/* If the pmd is writable, we can write to the page. */
762 	if (pmd_write(pmd))
763 		return true;
764 
765 	/* Maybe FOLL_FORCE is set to override it? */
766 	if (!(flags & FOLL_FORCE))
767 		return false;
768 
769 	/* But FOLL_FORCE has no effect on shared mappings */
770 	if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
771 		return false;
772 
773 	/* ... or read-only private ones */
774 	if (!(vma->vm_flags & VM_MAYWRITE))
775 		return false;
776 
777 	/* ... or already writable ones that just need to take a write fault */
778 	if (vma->vm_flags & VM_WRITE)
779 		return false;
780 
781 	/*
782 	 * See can_change_pte_writable(): we broke COW and could map the page
783 	 * writable if we have an exclusive anonymous page ...
784 	 */
785 	if (!page || !PageAnon(page) || !PageAnonExclusive(page))
786 		return false;
787 
788 	/* ... and a write-fault isn't required for other reasons. */
789 	if (vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd))
790 		return false;
791 	return !userfaultfd_huge_pmd_wp(vma, pmd);
792 }
793 
794 static struct page *follow_huge_pmd(struct vm_area_struct *vma,
795 				    unsigned long addr, pmd_t *pmd,
796 				    unsigned int flags,
797 				    struct follow_page_context *ctx)
798 {
799 	struct mm_struct *mm = vma->vm_mm;
800 	pmd_t pmdval = *pmd;
801 	struct page *page;
802 	int ret;
803 
804 	assert_spin_locked(pmd_lockptr(mm, pmd));
805 
806 	page = pmd_page(pmdval);
807 	if ((flags & FOLL_WRITE) &&
808 	    !can_follow_write_pmd(pmdval, page, vma, flags))
809 		return NULL;
810 
811 	/* Avoid dumping huge zero page */
812 	if ((flags & FOLL_DUMP) && is_huge_zero_pmd(pmdval))
813 		return ERR_PTR(-EFAULT);
814 
815 	if (pmd_protnone(*pmd) && !gup_can_follow_protnone(vma, flags))
816 		return NULL;
817 
818 	if (!pmd_write(pmdval) && gup_must_unshare(vma, flags, page))
819 		return ERR_PTR(-EMLINK);
820 
821 	VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
822 			!PageAnonExclusive(page), page);
823 
824 	ret = try_grab_folio(page_folio(page), 1, flags);
825 	if (ret)
826 		return ERR_PTR(ret);
827 
828 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
829 	if (pmd_trans_huge(pmdval) && (flags & FOLL_TOUCH))
830 		touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
831 #endif	/* CONFIG_TRANSPARENT_HUGEPAGE */
832 
833 	page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
834 	ctx->page_mask = HPAGE_PMD_NR - 1;
835 
836 	return page;
837 }
838 
839 #else  /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */
840 static struct page *follow_huge_pud(struct vm_area_struct *vma,
841 				    unsigned long addr, pud_t *pudp,
842 				    int flags, struct follow_page_context *ctx)
843 {
844 	return NULL;
845 }
846 
847 static struct page *follow_huge_pmd(struct vm_area_struct *vma,
848 				    unsigned long addr, pmd_t *pmd,
849 				    unsigned int flags,
850 				    struct follow_page_context *ctx)
851 {
852 	return NULL;
853 }
854 #endif	/* CONFIG_PGTABLE_HAS_HUGE_LEAVES */
855 
856 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
857 		pte_t *pte, unsigned int flags)
858 {
859 	if (flags & FOLL_TOUCH) {
860 		pte_t orig_entry = ptep_get(pte);
861 		pte_t entry = orig_entry;
862 
863 		if (flags & FOLL_WRITE)
864 			entry = pte_mkdirty(entry);
865 		entry = pte_mkyoung(entry);
866 
867 		if (!pte_same(orig_entry, entry)) {
868 			set_pte_at(vma->vm_mm, address, pte, entry);
869 			update_mmu_cache(vma, address, pte);
870 		}
871 	}
872 
873 	/* Proper page table entry exists, but no corresponding struct page */
874 	return -EEXIST;
875 }
876 
877 /* FOLL_FORCE can write to even unwritable PTEs in COW mappings. */
878 static inline bool can_follow_write_pte(pte_t pte, struct page *page,
879 					struct vm_area_struct *vma,
880 					unsigned int flags)
881 {
882 	/* If the pte is writable, we can write to the page. */
883 	if (pte_write(pte))
884 		return true;
885 
886 	/* Maybe FOLL_FORCE is set to override it? */
887 	if (!(flags & FOLL_FORCE))
888 		return false;
889 
890 	/* But FOLL_FORCE has no effect on shared mappings */
891 	if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
892 		return false;
893 
894 	/* ... or read-only private ones */
895 	if (!(vma->vm_flags & VM_MAYWRITE))
896 		return false;
897 
898 	/* ... or already writable ones that just need to take a write fault */
899 	if (vma->vm_flags & VM_WRITE)
900 		return false;
901 
902 	/*
903 	 * See can_change_pte_writable(): we broke COW and could map the page
904 	 * writable if we have an exclusive anonymous page ...
905 	 */
906 	if (!page || !PageAnon(page) || !PageAnonExclusive(page))
907 		return false;
908 
909 	/* ... and a write-fault isn't required for other reasons. */
910 	if (vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte))
911 		return false;
912 	return !userfaultfd_pte_wp(vma, pte);
913 }
914 
915 static struct page *follow_page_pte(struct vm_area_struct *vma,
916 		unsigned long address, pmd_t *pmd, unsigned int flags,
917 		struct dev_pagemap **pgmap)
918 {
919 	struct mm_struct *mm = vma->vm_mm;
920 	struct page *page;
921 	spinlock_t *ptl;
922 	pte_t *ptep, pte;
923 	int ret;
924 
925 	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
926 	if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
927 			 (FOLL_PIN | FOLL_GET)))
928 		return ERR_PTR(-EINVAL);
929 
930 	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
931 	if (!ptep)
932 		return no_page_table(vma, flags, address);
933 	pte = ptep_get(ptep);
934 	if (!pte_present(pte))
935 		goto no_page;
936 	if (pte_protnone(pte) && !gup_can_follow_protnone(vma, flags))
937 		goto no_page;
938 
939 	page = vm_normal_page(vma, address, pte);
940 
941 	/*
942 	 * We only care about anon pages in can_follow_write_pte() and don't
943 	 * have to worry about pte_devmap() because they are never anon.
944 	 */
945 	if ((flags & FOLL_WRITE) &&
946 	    !can_follow_write_pte(pte, page, vma, flags)) {
947 		page = NULL;
948 		goto out;
949 	}
950 
951 	if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
952 		/*
953 		 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
954 		 * case since they are only valid while holding the pgmap
955 		 * reference.
956 		 */
957 		*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
958 		if (*pgmap)
959 			page = pte_page(pte);
960 		else
961 			goto no_page;
962 	} else if (unlikely(!page)) {
963 		if (flags & FOLL_DUMP) {
964 			/* Avoid special (like zero) pages in core dumps */
965 			page = ERR_PTR(-EFAULT);
966 			goto out;
967 		}
968 
969 		if (is_zero_pfn(pte_pfn(pte))) {
970 			page = pte_page(pte);
971 		} else {
972 			ret = follow_pfn_pte(vma, address, ptep, flags);
973 			page = ERR_PTR(ret);
974 			goto out;
975 		}
976 	}
977 
978 	if (!pte_write(pte) && gup_must_unshare(vma, flags, page)) {
979 		page = ERR_PTR(-EMLINK);
980 		goto out;
981 	}
982 
983 	VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
984 		       !PageAnonExclusive(page), page);
985 
986 	/* try_grab_folio() does nothing unless FOLL_GET or FOLL_PIN is set. */
987 	ret = try_grab_folio(page_folio(page), 1, flags);
988 	if (unlikely(ret)) {
989 		page = ERR_PTR(ret);
990 		goto out;
991 	}
992 
993 	/*
994 	 * We need to make the page accessible if and only if we are going
995 	 * to access its content (the FOLL_PIN case).  Please see
996 	 * Documentation/core-api/pin_user_pages.rst for details.
997 	 */
998 	if (flags & FOLL_PIN) {
999 		ret = arch_make_page_accessible(page);
1000 		if (ret) {
1001 			unpin_user_page(page);
1002 			page = ERR_PTR(ret);
1003 			goto out;
1004 		}
1005 	}
1006 	if (flags & FOLL_TOUCH) {
1007 		if ((flags & FOLL_WRITE) &&
1008 		    !pte_dirty(pte) && !PageDirty(page))
1009 			set_page_dirty(page);
1010 		/*
1011 		 * pte_mkyoung() would be more correct here, but atomic care
1012 		 * is needed to avoid losing the dirty bit: it is easier to use
1013 		 * mark_page_accessed().
1014 		 */
1015 		mark_page_accessed(page);
1016 	}
1017 out:
1018 	pte_unmap_unlock(ptep, ptl);
1019 	return page;
1020 no_page:
1021 	pte_unmap_unlock(ptep, ptl);
1022 	if (!pte_none(pte))
1023 		return NULL;
1024 	return no_page_table(vma, flags, address);
1025 }
1026 
1027 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
1028 				    unsigned long address, pud_t *pudp,
1029 				    unsigned int flags,
1030 				    struct follow_page_context *ctx)
1031 {
1032 	pmd_t *pmd, pmdval;
1033 	spinlock_t *ptl;
1034 	struct page *page;
1035 	struct mm_struct *mm = vma->vm_mm;
1036 
1037 	pmd = pmd_offset(pudp, address);
1038 	pmdval = pmdp_get_lockless(pmd);
1039 	if (pmd_none(pmdval))
1040 		return no_page_table(vma, flags, address);
1041 	if (!pmd_present(pmdval))
1042 		return no_page_table(vma, flags, address);
1043 	if (unlikely(is_hugepd(__hugepd(pmd_val(pmdval)))))
1044 		return follow_hugepd(vma, __hugepd(pmd_val(pmdval)),
1045 				     address, PMD_SHIFT, flags, ctx);
1046 	if (pmd_devmap(pmdval)) {
1047 		ptl = pmd_lock(mm, pmd);
1048 		page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
1049 		spin_unlock(ptl);
1050 		if (page)
1051 			return page;
1052 		return no_page_table(vma, flags, address);
1053 	}
1054 	if (likely(!pmd_leaf(pmdval)))
1055 		return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
1056 
1057 	if (pmd_protnone(pmdval) && !gup_can_follow_protnone(vma, flags))
1058 		return no_page_table(vma, flags, address);
1059 
1060 	ptl = pmd_lock(mm, pmd);
1061 	pmdval = *pmd;
1062 	if (unlikely(!pmd_present(pmdval))) {
1063 		spin_unlock(ptl);
1064 		return no_page_table(vma, flags, address);
1065 	}
1066 	if (unlikely(!pmd_leaf(pmdval))) {
1067 		spin_unlock(ptl);
1068 		return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
1069 	}
1070 	if (pmd_trans_huge(pmdval) && (flags & FOLL_SPLIT_PMD)) {
1071 		spin_unlock(ptl);
1072 		split_huge_pmd(vma, pmd, address);
1073 		/* If pmd was left empty, stuff a page table in there quickly */
1074 		return pte_alloc(mm, pmd) ? ERR_PTR(-ENOMEM) :
1075 			follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
1076 	}
1077 	page = follow_huge_pmd(vma, address, pmd, flags, ctx);
1078 	spin_unlock(ptl);
1079 	return page;
1080 }
1081 
1082 static struct page *follow_pud_mask(struct vm_area_struct *vma,
1083 				    unsigned long address, p4d_t *p4dp,
1084 				    unsigned int flags,
1085 				    struct follow_page_context *ctx)
1086 {
1087 	pud_t *pudp, pud;
1088 	spinlock_t *ptl;
1089 	struct page *page;
1090 	struct mm_struct *mm = vma->vm_mm;
1091 
1092 	pudp = pud_offset(p4dp, address);
1093 	pud = READ_ONCE(*pudp);
1094 	if (!pud_present(pud))
1095 		return no_page_table(vma, flags, address);
1096 	if (unlikely(is_hugepd(__hugepd(pud_val(pud)))))
1097 		return follow_hugepd(vma, __hugepd(pud_val(pud)),
1098 				     address, PUD_SHIFT, flags, ctx);
1099 	if (pud_leaf(pud)) {
1100 		ptl = pud_lock(mm, pudp);
1101 		page = follow_huge_pud(vma, address, pudp, flags, ctx);
1102 		spin_unlock(ptl);
1103 		if (page)
1104 			return page;
1105 		return no_page_table(vma, flags, address);
1106 	}
1107 	if (unlikely(pud_bad(pud)))
1108 		return no_page_table(vma, flags, address);
1109 
1110 	return follow_pmd_mask(vma, address, pudp, flags, ctx);
1111 }
1112 
1113 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
1114 				    unsigned long address, pgd_t *pgdp,
1115 				    unsigned int flags,
1116 				    struct follow_page_context *ctx)
1117 {
1118 	p4d_t *p4dp, p4d;
1119 
1120 	p4dp = p4d_offset(pgdp, address);
1121 	p4d = READ_ONCE(*p4dp);
1122 	BUILD_BUG_ON(p4d_leaf(p4d));
1123 
1124 	if (unlikely(is_hugepd(__hugepd(p4d_val(p4d)))))
1125 		return follow_hugepd(vma, __hugepd(p4d_val(p4d)),
1126 				     address, P4D_SHIFT, flags, ctx);
1127 
1128 	if (!p4d_present(p4d) || p4d_bad(p4d))
1129 		return no_page_table(vma, flags, address);
1130 
1131 	return follow_pud_mask(vma, address, p4dp, flags, ctx);
1132 }
1133 
1134 /**
1135  * follow_page_mask - look up a page descriptor from a user-virtual address
1136  * @vma: vm_area_struct mapping @address
1137  * @address: virtual address to look up
1138  * @flags: flags modifying lookup behaviour
1139  * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
1140  *       pointer to output page_mask
1141  *
1142  * @flags can have FOLL_ flags set, defined in <linux/mm.h>
1143  *
1144  * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
1145  * the device's dev_pagemap metadata to avoid repeating expensive lookups.
1146  *
1147  * When getting an anonymous page and the caller has to trigger unsharing
1148  * of a shared anonymous page first, -EMLINK is returned. The caller should
1149  * trigger a fault with FAULT_FLAG_UNSHARE set. Note that unsharing is only
1150  * relevant with FOLL_PIN and !FOLL_WRITE.
1151  *
1152  * On output, the @ctx->page_mask is set according to the size of the page.
1153  *
1154  * Return: the mapped (struct page *), %NULL if no mapping exists, or
1155  * an error pointer if there is a mapping to something not represented
1156  * by a page descriptor (see also vm_normal_page()).
1157  */
1158 static struct page *follow_page_mask(struct vm_area_struct *vma,
1159 			      unsigned long address, unsigned int flags,
1160 			      struct follow_page_context *ctx)
1161 {
1162 	pgd_t *pgd;
1163 	struct mm_struct *mm = vma->vm_mm;
1164 	struct page *page;
1165 
1166 	vma_pgtable_walk_begin(vma);
1167 
1168 	ctx->page_mask = 0;
1169 	pgd = pgd_offset(mm, address);
1170 
1171 	if (unlikely(is_hugepd(__hugepd(pgd_val(*pgd)))))
1172 		page = follow_hugepd(vma, __hugepd(pgd_val(*pgd)),
1173 				     address, PGDIR_SHIFT, flags, ctx);
1174 	else if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
1175 		page = no_page_table(vma, flags, address);
1176 	else
1177 		page = follow_p4d_mask(vma, address, pgd, flags, ctx);
1178 
1179 	vma_pgtable_walk_end(vma);
1180 
1181 	return page;
1182 }
1183 
1184 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
1185 			 unsigned int foll_flags)
1186 {
1187 	struct follow_page_context ctx = { NULL };
1188 	struct page *page;
1189 
1190 	if (vma_is_secretmem(vma))
1191 		return NULL;
1192 
1193 	if (WARN_ON_ONCE(foll_flags & FOLL_PIN))
1194 		return NULL;
1195 
1196 	/*
1197 	 * We never set FOLL_HONOR_NUMA_FAULT because callers don't expect
1198 	 * to fail on PROT_NONE-mapped pages.
1199 	 */
1200 	page = follow_page_mask(vma, address, foll_flags, &ctx);
1201 	if (ctx.pgmap)
1202 		put_dev_pagemap(ctx.pgmap);
1203 	return page;
1204 }
1205 
1206 static int get_gate_page(struct mm_struct *mm, unsigned long address,
1207 		unsigned int gup_flags, struct vm_area_struct **vma,
1208 		struct page **page)
1209 {
1210 	pgd_t *pgd;
1211 	p4d_t *p4d;
1212 	pud_t *pud;
1213 	pmd_t *pmd;
1214 	pte_t *pte;
1215 	pte_t entry;
1216 	int ret = -EFAULT;
1217 
1218 	/* user gate pages are read-only */
1219 	if (gup_flags & FOLL_WRITE)
1220 		return -EFAULT;
1221 	if (address > TASK_SIZE)
1222 		pgd = pgd_offset_k(address);
1223 	else
1224 		pgd = pgd_offset_gate(mm, address);
1225 	if (pgd_none(*pgd))
1226 		return -EFAULT;
1227 	p4d = p4d_offset(pgd, address);
1228 	if (p4d_none(*p4d))
1229 		return -EFAULT;
1230 	pud = pud_offset(p4d, address);
1231 	if (pud_none(*pud))
1232 		return -EFAULT;
1233 	pmd = pmd_offset(pud, address);
1234 	if (!pmd_present(*pmd))
1235 		return -EFAULT;
1236 	pte = pte_offset_map(pmd, address);
1237 	if (!pte)
1238 		return -EFAULT;
1239 	entry = ptep_get(pte);
1240 	if (pte_none(entry))
1241 		goto unmap;
1242 	*vma = get_gate_vma(mm);
1243 	if (!page)
1244 		goto out;
1245 	*page = vm_normal_page(*vma, address, entry);
1246 	if (!*page) {
1247 		if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(entry)))
1248 			goto unmap;
1249 		*page = pte_page(entry);
1250 	}
1251 	ret = try_grab_folio(page_folio(*page), 1, gup_flags);
1252 	if (unlikely(ret))
1253 		goto unmap;
1254 out:
1255 	ret = 0;
1256 unmap:
1257 	pte_unmap(pte);
1258 	return ret;
1259 }
1260 
1261 /*
1262  * mmap_lock must be held on entry.  If @flags has FOLL_UNLOCKABLE but not
1263  * FOLL_NOWAIT, the mmap_lock may be released.  If it is, *@locked will be set
1264  * to 0 and -EBUSY returned.
1265  */
1266 static int faultin_page(struct vm_area_struct *vma,
1267 		unsigned long address, unsigned int *flags, bool unshare,
1268 		int *locked)
1269 {
1270 	unsigned int fault_flags = 0;
1271 	vm_fault_t ret;
1272 
1273 	if (*flags & FOLL_NOFAULT)
1274 		return -EFAULT;
1275 	if (*flags & FOLL_WRITE)
1276 		fault_flags |= FAULT_FLAG_WRITE;
1277 	if (*flags & FOLL_REMOTE)
1278 		fault_flags |= FAULT_FLAG_REMOTE;
1279 	if (*flags & FOLL_UNLOCKABLE) {
1280 		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1281 		/*
1282 		 * FAULT_FLAG_INTERRUPTIBLE is opt-in. GUP callers must set
1283 		 * FOLL_INTERRUPTIBLE to enable FAULT_FLAG_INTERRUPTIBLE.
1284 		 * That's because some callers may not be prepared to
1285 		 * handle early exits caused by non-fatal signals.
1286 		 */
1287 		if (*flags & FOLL_INTERRUPTIBLE)
1288 			fault_flags |= FAULT_FLAG_INTERRUPTIBLE;
1289 	}
1290 	if (*flags & FOLL_NOWAIT)
1291 		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
1292 	if (*flags & FOLL_TRIED) {
1293 		/*
1294 		 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
1295 		 * can co-exist
1296 		 */
1297 		fault_flags |= FAULT_FLAG_TRIED;
1298 	}
1299 	if (unshare) {
1300 		fault_flags |= FAULT_FLAG_UNSHARE;
1301 		/* FAULT_FLAG_WRITE and FAULT_FLAG_UNSHARE are incompatible */
1302 		VM_BUG_ON(fault_flags & FAULT_FLAG_WRITE);
1303 	}
1304 
1305 	ret = handle_mm_fault(vma, address, fault_flags, NULL);
1306 
1307 	if (ret & VM_FAULT_COMPLETED) {
1308 		/*
1309 		 * With FAULT_FLAG_RETRY_NOWAIT we'll never release the
1310 		 * mmap lock in the page fault handler. Sanity check this.
1311 		 */
1312 		WARN_ON_ONCE(fault_flags & FAULT_FLAG_RETRY_NOWAIT);
1313 		*locked = 0;
1314 
1315 		/*
1316 		 * We should do the same as VM_FAULT_RETRY, but let's not
1317 		 * return -EBUSY since that's not reflecting the reality of
1318 		 * what has happened - we've just fully completed a page
1319 		 * fault, with the mmap lock released.  Use -EAGAIN to show
1320 		 * that we want to take the mmap lock _again_.
1321 		 */
1322 		return -EAGAIN;
1323 	}
1324 
1325 	if (ret & VM_FAULT_ERROR) {
1326 		int err = vm_fault_to_errno(ret, *flags);
1327 
1328 		if (err)
1329 			return err;
1330 		BUG();
1331 	}
1332 
1333 	if (ret & VM_FAULT_RETRY) {
1334 		if (!(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
1335 			*locked = 0;
1336 		return -EBUSY;
1337 	}
1338 
1339 	return 0;
1340 }
1341 
1342 /*
1343  * Writing to file-backed mappings which require folio dirty tracking using GUP
1344  * is a fundamentally broken operation, as kernel write access to GUP mappings
1345  * do not adhere to the semantics expected by a file system.
1346  *
1347  * Consider the following scenario:-
1348  *
1349  * 1. A folio is written to via GUP which write-faults the memory, notifying
1350  *    the file system and dirtying the folio.
1351  * 2. Later, writeback is triggered, resulting in the folio being cleaned and
1352  *    the PTE being marked read-only.
1353  * 3. The GUP caller writes to the folio, as it is mapped read/write via the
1354  *    direct mapping.
1355  * 4. The GUP caller, now done with the page, unpins it and sets it dirty
1356  *    (though it does not have to).
1357  *
1358  * This results in both data being written to a folio without writenotify, and
1359  * the folio being dirtied unexpectedly (if the caller decides to do so).
1360  */
1361 static bool writable_file_mapping_allowed(struct vm_area_struct *vma,
1362 					  unsigned long gup_flags)
1363 {
1364 	/*
1365 	 * If we aren't pinning then no problematic write can occur. A long term
1366 	 * pin is the most egregious case so this is the case we disallow.
1367 	 */
1368 	if ((gup_flags & (FOLL_PIN | FOLL_LONGTERM)) !=
1369 	    (FOLL_PIN | FOLL_LONGTERM))
1370 		return true;
1371 
1372 	/*
1373 	 * If the VMA does not require dirty tracking then no problematic write
1374 	 * can occur either.
1375 	 */
1376 	return !vma_needs_dirty_tracking(vma);
1377 }
1378 
1379 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
1380 {
1381 	vm_flags_t vm_flags = vma->vm_flags;
1382 	int write = (gup_flags & FOLL_WRITE);
1383 	int foreign = (gup_flags & FOLL_REMOTE);
1384 	bool vma_anon = vma_is_anonymous(vma);
1385 
1386 	if (vm_flags & (VM_IO | VM_PFNMAP))
1387 		return -EFAULT;
1388 
1389 	if ((gup_flags & FOLL_ANON) && !vma_anon)
1390 		return -EFAULT;
1391 
1392 	if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
1393 		return -EOPNOTSUPP;
1394 
1395 	if (vma_is_secretmem(vma))
1396 		return -EFAULT;
1397 
1398 	if (write) {
1399 		if (!vma_anon &&
1400 		    !writable_file_mapping_allowed(vma, gup_flags))
1401 			return -EFAULT;
1402 
1403 		if (!(vm_flags & VM_WRITE) || (vm_flags & VM_SHADOW_STACK)) {
1404 			if (!(gup_flags & FOLL_FORCE))
1405 				return -EFAULT;
1406 			/* hugetlb does not support FOLL_FORCE|FOLL_WRITE. */
1407 			if (is_vm_hugetlb_page(vma))
1408 				return -EFAULT;
1409 			/*
1410 			 * We used to let the write,force case do COW in a
1411 			 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
1412 			 * set a breakpoint in a read-only mapping of an
1413 			 * executable, without corrupting the file (yet only
1414 			 * when that file had been opened for writing!).
1415 			 * Anon pages in shared mappings are surprising: now
1416 			 * just reject it.
1417 			 */
1418 			if (!is_cow_mapping(vm_flags))
1419 				return -EFAULT;
1420 		}
1421 	} else if (!(vm_flags & VM_READ)) {
1422 		if (!(gup_flags & FOLL_FORCE))
1423 			return -EFAULT;
1424 		/*
1425 		 * Is there actually any vma we can reach here which does not
1426 		 * have VM_MAYREAD set?
1427 		 */
1428 		if (!(vm_flags & VM_MAYREAD))
1429 			return -EFAULT;
1430 	}
1431 	/*
1432 	 * gups are always data accesses, not instruction
1433 	 * fetches, so execute=false here
1434 	 */
1435 	if (!arch_vma_access_permitted(vma, write, false, foreign))
1436 		return -EFAULT;
1437 	return 0;
1438 }
1439 
1440 /*
1441  * This is "vma_lookup()", but with a warning if we would have
1442  * historically expanded the stack in the GUP code.
1443  */
1444 static struct vm_area_struct *gup_vma_lookup(struct mm_struct *mm,
1445 	 unsigned long addr)
1446 {
1447 #ifdef CONFIG_STACK_GROWSUP
1448 	return vma_lookup(mm, addr);
1449 #else
1450 	static volatile unsigned long next_warn;
1451 	struct vm_area_struct *vma;
1452 	unsigned long now, next;
1453 
1454 	vma = find_vma(mm, addr);
1455 	if (!vma || (addr >= vma->vm_start))
1456 		return vma;
1457 
1458 	/* Only warn for half-way relevant accesses */
1459 	if (!(vma->vm_flags & VM_GROWSDOWN))
1460 		return NULL;
1461 	if (vma->vm_start - addr > 65536)
1462 		return NULL;
1463 
1464 	/* Let's not warn more than once an hour.. */
1465 	now = jiffies; next = next_warn;
1466 	if (next && time_before(now, next))
1467 		return NULL;
1468 	next_warn = now + 60*60*HZ;
1469 
1470 	/* Let people know things may have changed. */
1471 	pr_warn("GUP no longer grows the stack in %s (%d): %lx-%lx (%lx)\n",
1472 		current->comm, task_pid_nr(current),
1473 		vma->vm_start, vma->vm_end, addr);
1474 	dump_stack();
1475 	return NULL;
1476 #endif
1477 }
1478 
1479 /**
1480  * __get_user_pages() - pin user pages in memory
1481  * @mm:		mm_struct of target mm
1482  * @start:	starting user address
1483  * @nr_pages:	number of pages from start to pin
1484  * @gup_flags:	flags modifying pin behaviour
1485  * @pages:	array that receives pointers to the pages pinned.
1486  *		Should be at least nr_pages long. Or NULL, if caller
1487  *		only intends to ensure the pages are faulted in.
1488  * @locked:     whether we're still with the mmap_lock held
1489  *
1490  * Returns either number of pages pinned (which may be less than the
1491  * number requested), or an error. Details about the return value:
1492  *
1493  * -- If nr_pages is 0, returns 0.
1494  * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1495  * -- If nr_pages is >0, and some pages were pinned, returns the number of
1496  *    pages pinned. Again, this may be less than nr_pages.
1497  * -- 0 return value is possible when the fault would need to be retried.
1498  *
1499  * The caller is responsible for releasing returned @pages, via put_page().
1500  *
1501  * Must be called with mmap_lock held.  It may be released.  See below.
1502  *
1503  * __get_user_pages walks a process's page tables and takes a reference to
1504  * each struct page that each user address corresponds to at a given
1505  * instant. That is, it takes the page that would be accessed if a user
1506  * thread accesses the given user virtual address at that instant.
1507  *
1508  * This does not guarantee that the page exists in the user mappings when
1509  * __get_user_pages returns, and there may even be a completely different
1510  * page there in some cases (eg. if mmapped pagecache has been invalidated
1511  * and subsequently re-faulted). However it does guarantee that the page
1512  * won't be freed completely. And mostly callers simply care that the page
1513  * contains data that was valid *at some point in time*. Typically, an IO
1514  * or similar operation cannot guarantee anything stronger anyway because
1515  * locks can't be held over the syscall boundary.
1516  *
1517  * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1518  * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1519  * appropriate) must be called after the page is finished with, and
1520  * before put_page is called.
1521  *
1522  * If FOLL_UNLOCKABLE is set without FOLL_NOWAIT then the mmap_lock may
1523  * be released. If this happens *@locked will be set to 0 on return.
1524  *
1525  * A caller using such a combination of @gup_flags must therefore hold the
1526  * mmap_lock for reading only, and recognize when it's been released. Otherwise,
1527  * it must be held for either reading or writing and will not be released.
1528  *
1529  * In most cases, get_user_pages or get_user_pages_fast should be used
1530  * instead of __get_user_pages. __get_user_pages should be used only if
1531  * you need some special @gup_flags.
1532  */
1533 static long __get_user_pages(struct mm_struct *mm,
1534 		unsigned long start, unsigned long nr_pages,
1535 		unsigned int gup_flags, struct page **pages,
1536 		int *locked)
1537 {
1538 	long ret = 0, i = 0;
1539 	struct vm_area_struct *vma = NULL;
1540 	struct follow_page_context ctx = { NULL };
1541 
1542 	if (!nr_pages)
1543 		return 0;
1544 
1545 	start = untagged_addr_remote(mm, start);
1546 
1547 	VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1548 
1549 	do {
1550 		struct page *page;
1551 		unsigned int foll_flags = gup_flags;
1552 		unsigned int page_increm;
1553 
1554 		/* first iteration or cross vma bound */
1555 		if (!vma || start >= vma->vm_end) {
1556 			/*
1557 			 * MADV_POPULATE_(READ|WRITE) wants to handle VMA
1558 			 * lookups+error reporting differently.
1559 			 */
1560 			if (gup_flags & FOLL_MADV_POPULATE) {
1561 				vma = vma_lookup(mm, start);
1562 				if (!vma) {
1563 					ret = -ENOMEM;
1564 					goto out;
1565 				}
1566 				if (check_vma_flags(vma, gup_flags)) {
1567 					ret = -EINVAL;
1568 					goto out;
1569 				}
1570 				goto retry;
1571 			}
1572 			vma = gup_vma_lookup(mm, start);
1573 			if (!vma && in_gate_area(mm, start)) {
1574 				ret = get_gate_page(mm, start & PAGE_MASK,
1575 						gup_flags, &vma,
1576 						pages ? &page : NULL);
1577 				if (ret)
1578 					goto out;
1579 				ctx.page_mask = 0;
1580 				goto next_page;
1581 			}
1582 
1583 			if (!vma) {
1584 				ret = -EFAULT;
1585 				goto out;
1586 			}
1587 			ret = check_vma_flags(vma, gup_flags);
1588 			if (ret)
1589 				goto out;
1590 		}
1591 retry:
1592 		/*
1593 		 * If we have a pending SIGKILL, don't keep faulting pages and
1594 		 * potentially allocating memory.
1595 		 */
1596 		if (fatal_signal_pending(current)) {
1597 			ret = -EINTR;
1598 			goto out;
1599 		}
1600 		cond_resched();
1601 
1602 		page = follow_page_mask(vma, start, foll_flags, &ctx);
1603 		if (!page || PTR_ERR(page) == -EMLINK) {
1604 			ret = faultin_page(vma, start, &foll_flags,
1605 					   PTR_ERR(page) == -EMLINK, locked);
1606 			switch (ret) {
1607 			case 0:
1608 				goto retry;
1609 			case -EBUSY:
1610 			case -EAGAIN:
1611 				ret = 0;
1612 				fallthrough;
1613 			case -EFAULT:
1614 			case -ENOMEM:
1615 			case -EHWPOISON:
1616 				goto out;
1617 			}
1618 			BUG();
1619 		} else if (PTR_ERR(page) == -EEXIST) {
1620 			/*
1621 			 * Proper page table entry exists, but no corresponding
1622 			 * struct page. If the caller expects **pages to be
1623 			 * filled in, bail out now, because that can't be done
1624 			 * for this page.
1625 			 */
1626 			if (pages) {
1627 				ret = PTR_ERR(page);
1628 				goto out;
1629 			}
1630 		} else if (IS_ERR(page)) {
1631 			ret = PTR_ERR(page);
1632 			goto out;
1633 		}
1634 next_page:
1635 		page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1636 		if (page_increm > nr_pages)
1637 			page_increm = nr_pages;
1638 
1639 		if (pages) {
1640 			struct page *subpage;
1641 			unsigned int j;
1642 
1643 			/*
1644 			 * This must be a large folio (and doesn't need to
1645 			 * be the whole folio; it can be part of it), do
1646 			 * the refcount work for all the subpages too.
1647 			 *
1648 			 * NOTE: here the page may not be the head page
1649 			 * e.g. when start addr is not thp-size aligned.
1650 			 * try_grab_folio() should have taken care of tail
1651 			 * pages.
1652 			 */
1653 			if (page_increm > 1) {
1654 				struct folio *folio = page_folio(page);
1655 
1656 				/*
1657 				 * Since we already hold refcount on the
1658 				 * large folio, this should never fail.
1659 				 */
1660 				if (try_grab_folio(folio, page_increm - 1,
1661 						   foll_flags)) {
1662 					/*
1663 					 * Release the 1st page ref if the
1664 					 * folio is problematic, fail hard.
1665 					 */
1666 					gup_put_folio(folio, 1,
1667 						      foll_flags);
1668 					ret = -EFAULT;
1669 					goto out;
1670 				}
1671 			}
1672 
1673 			for (j = 0; j < page_increm; j++) {
1674 				subpage = nth_page(page, j);
1675 				pages[i + j] = subpage;
1676 				flush_anon_page(vma, subpage, start + j * PAGE_SIZE);
1677 				flush_dcache_page(subpage);
1678 			}
1679 		}
1680 
1681 		i += page_increm;
1682 		start += page_increm * PAGE_SIZE;
1683 		nr_pages -= page_increm;
1684 	} while (nr_pages);
1685 out:
1686 	if (ctx.pgmap)
1687 		put_dev_pagemap(ctx.pgmap);
1688 	return i ? i : ret;
1689 }
1690 
1691 static bool vma_permits_fault(struct vm_area_struct *vma,
1692 			      unsigned int fault_flags)
1693 {
1694 	bool write   = !!(fault_flags & FAULT_FLAG_WRITE);
1695 	bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1696 	vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1697 
1698 	if (!(vm_flags & vma->vm_flags))
1699 		return false;
1700 
1701 	/*
1702 	 * The architecture might have a hardware protection
1703 	 * mechanism other than read/write that can deny access.
1704 	 *
1705 	 * gup always represents data access, not instruction
1706 	 * fetches, so execute=false here:
1707 	 */
1708 	if (!arch_vma_access_permitted(vma, write, false, foreign))
1709 		return false;
1710 
1711 	return true;
1712 }
1713 
1714 /**
1715  * fixup_user_fault() - manually resolve a user page fault
1716  * @mm:		mm_struct of target mm
1717  * @address:	user address
1718  * @fault_flags:flags to pass down to handle_mm_fault()
1719  * @unlocked:	did we unlock the mmap_lock while retrying, maybe NULL if caller
1720  *		does not allow retry. If NULL, the caller must guarantee
1721  *		that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1722  *
1723  * This is meant to be called in the specific scenario where for locking reasons
1724  * we try to access user memory in atomic context (within a pagefault_disable()
1725  * section), this returns -EFAULT, and we want to resolve the user fault before
1726  * trying again.
1727  *
1728  * Typically this is meant to be used by the futex code.
1729  *
1730  * The main difference with get_user_pages() is that this function will
1731  * unconditionally call handle_mm_fault() which will in turn perform all the
1732  * necessary SW fixup of the dirty and young bits in the PTE, while
1733  * get_user_pages() only guarantees to update these in the struct page.
1734  *
1735  * This is important for some architectures where those bits also gate the
1736  * access permission to the page because they are maintained in software.  On
1737  * such architectures, gup() will not be enough to make a subsequent access
1738  * succeed.
1739  *
1740  * This function will not return with an unlocked mmap_lock. So it has not the
1741  * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1742  */
1743 int fixup_user_fault(struct mm_struct *mm,
1744 		     unsigned long address, unsigned int fault_flags,
1745 		     bool *unlocked)
1746 {
1747 	struct vm_area_struct *vma;
1748 	vm_fault_t ret;
1749 
1750 	address = untagged_addr_remote(mm, address);
1751 
1752 	if (unlocked)
1753 		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1754 
1755 retry:
1756 	vma = gup_vma_lookup(mm, address);
1757 	if (!vma)
1758 		return -EFAULT;
1759 
1760 	if (!vma_permits_fault(vma, fault_flags))
1761 		return -EFAULT;
1762 
1763 	if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1764 	    fatal_signal_pending(current))
1765 		return -EINTR;
1766 
1767 	ret = handle_mm_fault(vma, address, fault_flags, NULL);
1768 
1769 	if (ret & VM_FAULT_COMPLETED) {
1770 		/*
1771 		 * NOTE: it's a pity that we need to retake the lock here
1772 		 * to pair with the unlock() in the callers. Ideally we
1773 		 * could tell the callers so they do not need to unlock.
1774 		 */
1775 		mmap_read_lock(mm);
1776 		*unlocked = true;
1777 		return 0;
1778 	}
1779 
1780 	if (ret & VM_FAULT_ERROR) {
1781 		int err = vm_fault_to_errno(ret, 0);
1782 
1783 		if (err)
1784 			return err;
1785 		BUG();
1786 	}
1787 
1788 	if (ret & VM_FAULT_RETRY) {
1789 		mmap_read_lock(mm);
1790 		*unlocked = true;
1791 		fault_flags |= FAULT_FLAG_TRIED;
1792 		goto retry;
1793 	}
1794 
1795 	return 0;
1796 }
1797 EXPORT_SYMBOL_GPL(fixup_user_fault);
1798 
1799 /*
1800  * GUP always responds to fatal signals.  When FOLL_INTERRUPTIBLE is
1801  * specified, it'll also respond to generic signals.  The caller of GUP
1802  * that has FOLL_INTERRUPTIBLE should take care of the GUP interruption.
1803  */
1804 static bool gup_signal_pending(unsigned int flags)
1805 {
1806 	if (fatal_signal_pending(current))
1807 		return true;
1808 
1809 	if (!(flags & FOLL_INTERRUPTIBLE))
1810 		return false;
1811 
1812 	return signal_pending(current);
1813 }
1814 
1815 /*
1816  * Locking: (*locked == 1) means that the mmap_lock has already been acquired by
1817  * the caller. This function may drop the mmap_lock. If it does so, then it will
1818  * set (*locked = 0).
1819  *
1820  * (*locked == 0) means that the caller expects this function to acquire and
1821  * drop the mmap_lock. Therefore, the value of *locked will still be zero when
1822  * the function returns, even though it may have changed temporarily during
1823  * function execution.
1824  *
1825  * Please note that this function, unlike __get_user_pages(), will not return 0
1826  * for nr_pages > 0, unless FOLL_NOWAIT is used.
1827  */
1828 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1829 						unsigned long start,
1830 						unsigned long nr_pages,
1831 						struct page **pages,
1832 						int *locked,
1833 						unsigned int flags)
1834 {
1835 	long ret, pages_done;
1836 	bool must_unlock = false;
1837 
1838 	if (!nr_pages)
1839 		return 0;
1840 
1841 	/*
1842 	 * The internal caller expects GUP to manage the lock internally and the
1843 	 * lock must be released when this returns.
1844 	 */
1845 	if (!*locked) {
1846 		if (mmap_read_lock_killable(mm))
1847 			return -EAGAIN;
1848 		must_unlock = true;
1849 		*locked = 1;
1850 	}
1851 	else
1852 		mmap_assert_locked(mm);
1853 
1854 	if (flags & FOLL_PIN)
1855 		mm_set_has_pinned_flag(&mm->flags);
1856 
1857 	/*
1858 	 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1859 	 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1860 	 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1861 	 * for FOLL_GET, not for the newer FOLL_PIN.
1862 	 *
1863 	 * FOLL_PIN always expects pages to be non-null, but no need to assert
1864 	 * that here, as any failures will be obvious enough.
1865 	 */
1866 	if (pages && !(flags & FOLL_PIN))
1867 		flags |= FOLL_GET;
1868 
1869 	pages_done = 0;
1870 	for (;;) {
1871 		ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1872 				       locked);
1873 		if (!(flags & FOLL_UNLOCKABLE)) {
1874 			/* VM_FAULT_RETRY couldn't trigger, bypass */
1875 			pages_done = ret;
1876 			break;
1877 		}
1878 
1879 		/* VM_FAULT_RETRY or VM_FAULT_COMPLETED cannot return errors */
1880 		if (!*locked) {
1881 			BUG_ON(ret < 0);
1882 			BUG_ON(ret >= nr_pages);
1883 		}
1884 
1885 		if (ret > 0) {
1886 			nr_pages -= ret;
1887 			pages_done += ret;
1888 			if (!nr_pages)
1889 				break;
1890 		}
1891 		if (*locked) {
1892 			/*
1893 			 * VM_FAULT_RETRY didn't trigger or it was a
1894 			 * FOLL_NOWAIT.
1895 			 */
1896 			if (!pages_done)
1897 				pages_done = ret;
1898 			break;
1899 		}
1900 		/*
1901 		 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1902 		 * For the prefault case (!pages) we only update counts.
1903 		 */
1904 		if (likely(pages))
1905 			pages += ret;
1906 		start += ret << PAGE_SHIFT;
1907 
1908 		/* The lock was temporarily dropped, so we must unlock later */
1909 		must_unlock = true;
1910 
1911 retry:
1912 		/*
1913 		 * Repeat on the address that fired VM_FAULT_RETRY
1914 		 * with both FAULT_FLAG_ALLOW_RETRY and
1915 		 * FAULT_FLAG_TRIED.  Note that GUP can be interrupted
1916 		 * by fatal signals of even common signals, depending on
1917 		 * the caller's request. So we need to check it before we
1918 		 * start trying again otherwise it can loop forever.
1919 		 */
1920 		if (gup_signal_pending(flags)) {
1921 			if (!pages_done)
1922 				pages_done = -EINTR;
1923 			break;
1924 		}
1925 
1926 		ret = mmap_read_lock_killable(mm);
1927 		if (ret) {
1928 			BUG_ON(ret > 0);
1929 			if (!pages_done)
1930 				pages_done = ret;
1931 			break;
1932 		}
1933 
1934 		*locked = 1;
1935 		ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1936 				       pages, locked);
1937 		if (!*locked) {
1938 			/* Continue to retry until we succeeded */
1939 			BUG_ON(ret != 0);
1940 			goto retry;
1941 		}
1942 		if (ret != 1) {
1943 			BUG_ON(ret > 1);
1944 			if (!pages_done)
1945 				pages_done = ret;
1946 			break;
1947 		}
1948 		nr_pages--;
1949 		pages_done++;
1950 		if (!nr_pages)
1951 			break;
1952 		if (likely(pages))
1953 			pages++;
1954 		start += PAGE_SIZE;
1955 	}
1956 	if (must_unlock && *locked) {
1957 		/*
1958 		 * We either temporarily dropped the lock, or the caller
1959 		 * requested that we both acquire and drop the lock. Either way,
1960 		 * we must now unlock, and notify the caller of that state.
1961 		 */
1962 		mmap_read_unlock(mm);
1963 		*locked = 0;
1964 	}
1965 
1966 	/*
1967 	 * Failing to pin anything implies something has gone wrong (except when
1968 	 * FOLL_NOWAIT is specified).
1969 	 */
1970 	if (WARN_ON_ONCE(pages_done == 0 && !(flags & FOLL_NOWAIT)))
1971 		return -EFAULT;
1972 
1973 	return pages_done;
1974 }
1975 
1976 /**
1977  * populate_vma_page_range() -  populate a range of pages in the vma.
1978  * @vma:   target vma
1979  * @start: start address
1980  * @end:   end address
1981  * @locked: whether the mmap_lock is still held
1982  *
1983  * This takes care of mlocking the pages too if VM_LOCKED is set.
1984  *
1985  * Return either number of pages pinned in the vma, or a negative error
1986  * code on error.
1987  *
1988  * vma->vm_mm->mmap_lock must be held.
1989  *
1990  * If @locked is NULL, it may be held for read or write and will
1991  * be unperturbed.
1992  *
1993  * If @locked is non-NULL, it must held for read only and may be
1994  * released.  If it's released, *@locked will be set to 0.
1995  */
1996 long populate_vma_page_range(struct vm_area_struct *vma,
1997 		unsigned long start, unsigned long end, int *locked)
1998 {
1999 	struct mm_struct *mm = vma->vm_mm;
2000 	unsigned long nr_pages = (end - start) / PAGE_SIZE;
2001 	int local_locked = 1;
2002 	int gup_flags;
2003 	long ret;
2004 
2005 	VM_BUG_ON(!PAGE_ALIGNED(start));
2006 	VM_BUG_ON(!PAGE_ALIGNED(end));
2007 	VM_BUG_ON_VMA(start < vma->vm_start, vma);
2008 	VM_BUG_ON_VMA(end   > vma->vm_end, vma);
2009 	mmap_assert_locked(mm);
2010 
2011 	/*
2012 	 * Rightly or wrongly, the VM_LOCKONFAULT case has never used
2013 	 * faultin_page() to break COW, so it has no work to do here.
2014 	 */
2015 	if (vma->vm_flags & VM_LOCKONFAULT)
2016 		return nr_pages;
2017 
2018 	/* ... similarly, we've never faulted in PROT_NONE pages */
2019 	if (!vma_is_accessible(vma))
2020 		return -EFAULT;
2021 
2022 	gup_flags = FOLL_TOUCH;
2023 	/*
2024 	 * We want to touch writable mappings with a write fault in order
2025 	 * to break COW, except for shared mappings because these don't COW
2026 	 * and we would not want to dirty them for nothing.
2027 	 *
2028 	 * Otherwise, do a read fault, and use FOLL_FORCE in case it's not
2029 	 * readable (ie write-only or executable).
2030 	 */
2031 	if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
2032 		gup_flags |= FOLL_WRITE;
2033 	else
2034 		gup_flags |= FOLL_FORCE;
2035 
2036 	if (locked)
2037 		gup_flags |= FOLL_UNLOCKABLE;
2038 
2039 	/*
2040 	 * We made sure addr is within a VMA, so the following will
2041 	 * not result in a stack expansion that recurses back here.
2042 	 */
2043 	ret = __get_user_pages(mm, start, nr_pages, gup_flags,
2044 			       NULL, locked ? locked : &local_locked);
2045 	lru_add_drain();
2046 	return ret;
2047 }
2048 
2049 /*
2050  * faultin_page_range() - populate (prefault) page tables inside the
2051  *			  given range readable/writable
2052  *
2053  * This takes care of mlocking the pages, too, if VM_LOCKED is set.
2054  *
2055  * @mm: the mm to populate page tables in
2056  * @start: start address
2057  * @end: end address
2058  * @write: whether to prefault readable or writable
2059  * @locked: whether the mmap_lock is still held
2060  *
2061  * Returns either number of processed pages in the MM, or a negative error
2062  * code on error (see __get_user_pages()). Note that this function reports
2063  * errors related to VMAs, such as incompatible mappings, as expected by
2064  * MADV_POPULATE_(READ|WRITE).
2065  *
2066  * The range must be page-aligned.
2067  *
2068  * mm->mmap_lock must be held. If it's released, *@locked will be set to 0.
2069  */
2070 long faultin_page_range(struct mm_struct *mm, unsigned long start,
2071 			unsigned long end, bool write, int *locked)
2072 {
2073 	unsigned long nr_pages = (end - start) / PAGE_SIZE;
2074 	int gup_flags;
2075 	long ret;
2076 
2077 	VM_BUG_ON(!PAGE_ALIGNED(start));
2078 	VM_BUG_ON(!PAGE_ALIGNED(end));
2079 	mmap_assert_locked(mm);
2080 
2081 	/*
2082 	 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
2083 	 *	       the page dirty with FOLL_WRITE -- which doesn't make a
2084 	 *	       difference with !FOLL_FORCE, because the page is writable
2085 	 *	       in the page table.
2086 	 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
2087 	 *		  a poisoned page.
2088 	 * !FOLL_FORCE: Require proper access permissions.
2089 	 */
2090 	gup_flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_UNLOCKABLE |
2091 		    FOLL_MADV_POPULATE;
2092 	if (write)
2093 		gup_flags |= FOLL_WRITE;
2094 
2095 	ret = __get_user_pages_locked(mm, start, nr_pages, NULL, locked,
2096 				      gup_flags);
2097 	lru_add_drain();
2098 	return ret;
2099 }
2100 
2101 /*
2102  * __mm_populate - populate and/or mlock pages within a range of address space.
2103  *
2104  * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
2105  * flags. VMAs must be already marked with the desired vm_flags, and
2106  * mmap_lock must not be held.
2107  */
2108 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
2109 {
2110 	struct mm_struct *mm = current->mm;
2111 	unsigned long end, nstart, nend;
2112 	struct vm_area_struct *vma = NULL;
2113 	int locked = 0;
2114 	long ret = 0;
2115 
2116 	end = start + len;
2117 
2118 	for (nstart = start; nstart < end; nstart = nend) {
2119 		/*
2120 		 * We want to fault in pages for [nstart; end) address range.
2121 		 * Find first corresponding VMA.
2122 		 */
2123 		if (!locked) {
2124 			locked = 1;
2125 			mmap_read_lock(mm);
2126 			vma = find_vma_intersection(mm, nstart, end);
2127 		} else if (nstart >= vma->vm_end)
2128 			vma = find_vma_intersection(mm, vma->vm_end, end);
2129 
2130 		if (!vma)
2131 			break;
2132 		/*
2133 		 * Set [nstart; nend) to intersection of desired address
2134 		 * range with the first VMA. Also, skip undesirable VMA types.
2135 		 */
2136 		nend = min(end, vma->vm_end);
2137 		if (vma->vm_flags & (VM_IO | VM_PFNMAP))
2138 			continue;
2139 		if (nstart < vma->vm_start)
2140 			nstart = vma->vm_start;
2141 		/*
2142 		 * Now fault in a range of pages. populate_vma_page_range()
2143 		 * double checks the vma flags, so that it won't mlock pages
2144 		 * if the vma was already munlocked.
2145 		 */
2146 		ret = populate_vma_page_range(vma, nstart, nend, &locked);
2147 		if (ret < 0) {
2148 			if (ignore_errors) {
2149 				ret = 0;
2150 				continue;	/* continue at next VMA */
2151 			}
2152 			break;
2153 		}
2154 		nend = nstart + ret * PAGE_SIZE;
2155 		ret = 0;
2156 	}
2157 	if (locked)
2158 		mmap_read_unlock(mm);
2159 	return ret;	/* 0 or negative error code */
2160 }
2161 #else /* CONFIG_MMU */
2162 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
2163 		unsigned long nr_pages, struct page **pages,
2164 		int *locked, unsigned int foll_flags)
2165 {
2166 	struct vm_area_struct *vma;
2167 	bool must_unlock = false;
2168 	unsigned long vm_flags;
2169 	long i;
2170 
2171 	if (!nr_pages)
2172 		return 0;
2173 
2174 	/*
2175 	 * The internal caller expects GUP to manage the lock internally and the
2176 	 * lock must be released when this returns.
2177 	 */
2178 	if (!*locked) {
2179 		if (mmap_read_lock_killable(mm))
2180 			return -EAGAIN;
2181 		must_unlock = true;
2182 		*locked = 1;
2183 	}
2184 
2185 	/* calculate required read or write permissions.
2186 	 * If FOLL_FORCE is set, we only require the "MAY" flags.
2187 	 */
2188 	vm_flags  = (foll_flags & FOLL_WRITE) ?
2189 			(VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
2190 	vm_flags &= (foll_flags & FOLL_FORCE) ?
2191 			(VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
2192 
2193 	for (i = 0; i < nr_pages; i++) {
2194 		vma = find_vma(mm, start);
2195 		if (!vma)
2196 			break;
2197 
2198 		/* protect what we can, including chardevs */
2199 		if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
2200 		    !(vm_flags & vma->vm_flags))
2201 			break;
2202 
2203 		if (pages) {
2204 			pages[i] = virt_to_page((void *)start);
2205 			if (pages[i])
2206 				get_page(pages[i]);
2207 		}
2208 
2209 		start = (start + PAGE_SIZE) & PAGE_MASK;
2210 	}
2211 
2212 	if (must_unlock && *locked) {
2213 		mmap_read_unlock(mm);
2214 		*locked = 0;
2215 	}
2216 
2217 	return i ? : -EFAULT;
2218 }
2219 #endif /* !CONFIG_MMU */
2220 
2221 /**
2222  * fault_in_writeable - fault in userspace address range for writing
2223  * @uaddr: start of address range
2224  * @size: size of address range
2225  *
2226  * Returns the number of bytes not faulted in (like copy_to_user() and
2227  * copy_from_user()).
2228  */
2229 size_t fault_in_writeable(char __user *uaddr, size_t size)
2230 {
2231 	char __user *start = uaddr, *end;
2232 
2233 	if (unlikely(size == 0))
2234 		return 0;
2235 	if (!user_write_access_begin(uaddr, size))
2236 		return size;
2237 	if (!PAGE_ALIGNED(uaddr)) {
2238 		unsafe_put_user(0, uaddr, out);
2239 		uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
2240 	}
2241 	end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
2242 	if (unlikely(end < start))
2243 		end = NULL;
2244 	while (uaddr != end) {
2245 		unsafe_put_user(0, uaddr, out);
2246 		uaddr += PAGE_SIZE;
2247 	}
2248 
2249 out:
2250 	user_write_access_end();
2251 	if (size > uaddr - start)
2252 		return size - (uaddr - start);
2253 	return 0;
2254 }
2255 EXPORT_SYMBOL(fault_in_writeable);
2256 
2257 /**
2258  * fault_in_subpage_writeable - fault in an address range for writing
2259  * @uaddr: start of address range
2260  * @size: size of address range
2261  *
2262  * Fault in a user address range for writing while checking for permissions at
2263  * sub-page granularity (e.g. arm64 MTE). This function should be used when
2264  * the caller cannot guarantee forward progress of a copy_to_user() loop.
2265  *
2266  * Returns the number of bytes not faulted in (like copy_to_user() and
2267  * copy_from_user()).
2268  */
2269 size_t fault_in_subpage_writeable(char __user *uaddr, size_t size)
2270 {
2271 	size_t faulted_in;
2272 
2273 	/*
2274 	 * Attempt faulting in at page granularity first for page table
2275 	 * permission checking. The arch-specific probe_subpage_writeable()
2276 	 * functions may not check for this.
2277 	 */
2278 	faulted_in = size - fault_in_writeable(uaddr, size);
2279 	if (faulted_in)
2280 		faulted_in -= probe_subpage_writeable(uaddr, faulted_in);
2281 
2282 	return size - faulted_in;
2283 }
2284 EXPORT_SYMBOL(fault_in_subpage_writeable);
2285 
2286 /*
2287  * fault_in_safe_writeable - fault in an address range for writing
2288  * @uaddr: start of address range
2289  * @size: length of address range
2290  *
2291  * Faults in an address range for writing.  This is primarily useful when we
2292  * already know that some or all of the pages in the address range aren't in
2293  * memory.
2294  *
2295  * Unlike fault_in_writeable(), this function is non-destructive.
2296  *
2297  * Note that we don't pin or otherwise hold the pages referenced that we fault
2298  * in.  There's no guarantee that they'll stay in memory for any duration of
2299  * time.
2300  *
2301  * Returns the number of bytes not faulted in, like copy_to_user() and
2302  * copy_from_user().
2303  */
2304 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
2305 {
2306 	unsigned long start = (unsigned long)uaddr, end;
2307 	struct mm_struct *mm = current->mm;
2308 	bool unlocked = false;
2309 
2310 	if (unlikely(size == 0))
2311 		return 0;
2312 	end = PAGE_ALIGN(start + size);
2313 	if (end < start)
2314 		end = 0;
2315 
2316 	mmap_read_lock(mm);
2317 	do {
2318 		if (fixup_user_fault(mm, start, FAULT_FLAG_WRITE, &unlocked))
2319 			break;
2320 		start = (start + PAGE_SIZE) & PAGE_MASK;
2321 	} while (start != end);
2322 	mmap_read_unlock(mm);
2323 
2324 	if (size > (unsigned long)uaddr - start)
2325 		return size - ((unsigned long)uaddr - start);
2326 	return 0;
2327 }
2328 EXPORT_SYMBOL(fault_in_safe_writeable);
2329 
2330 /**
2331  * fault_in_readable - fault in userspace address range for reading
2332  * @uaddr: start of user address range
2333  * @size: size of user address range
2334  *
2335  * Returns the number of bytes not faulted in (like copy_to_user() and
2336  * copy_from_user()).
2337  */
2338 size_t fault_in_readable(const char __user *uaddr, size_t size)
2339 {
2340 	const char __user *start = uaddr, *end;
2341 	volatile char c;
2342 
2343 	if (unlikely(size == 0))
2344 		return 0;
2345 	if (!user_read_access_begin(uaddr, size))
2346 		return size;
2347 	if (!PAGE_ALIGNED(uaddr)) {
2348 		unsafe_get_user(c, uaddr, out);
2349 		uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
2350 	}
2351 	end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
2352 	if (unlikely(end < start))
2353 		end = NULL;
2354 	while (uaddr != end) {
2355 		unsafe_get_user(c, uaddr, out);
2356 		uaddr += PAGE_SIZE;
2357 	}
2358 
2359 out:
2360 	user_read_access_end();
2361 	(void)c;
2362 	if (size > uaddr - start)
2363 		return size - (uaddr - start);
2364 	return 0;
2365 }
2366 EXPORT_SYMBOL(fault_in_readable);
2367 
2368 /**
2369  * get_dump_page() - pin user page in memory while writing it to core dump
2370  * @addr: user address
2371  *
2372  * Returns struct page pointer of user page pinned for dump,
2373  * to be freed afterwards by put_page().
2374  *
2375  * Returns NULL on any kind of failure - a hole must then be inserted into
2376  * the corefile, to preserve alignment with its headers; and also returns
2377  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
2378  * allowing a hole to be left in the corefile to save disk space.
2379  *
2380  * Called without mmap_lock (takes and releases the mmap_lock by itself).
2381  */
2382 #ifdef CONFIG_ELF_CORE
2383 struct page *get_dump_page(unsigned long addr)
2384 {
2385 	struct page *page;
2386 	int locked = 0;
2387 	int ret;
2388 
2389 	ret = __get_user_pages_locked(current->mm, addr, 1, &page, &locked,
2390 				      FOLL_FORCE | FOLL_DUMP | FOLL_GET);
2391 	return (ret == 1) ? page : NULL;
2392 }
2393 #endif /* CONFIG_ELF_CORE */
2394 
2395 #ifdef CONFIG_MIGRATION
2396 /*
2397  * Returns the number of collected pages. Return value is always >= 0.
2398  */
2399 static unsigned long collect_longterm_unpinnable_pages(
2400 					struct list_head *movable_page_list,
2401 					unsigned long nr_pages,
2402 					struct page **pages)
2403 {
2404 	unsigned long i, collected = 0;
2405 	struct folio *prev_folio = NULL;
2406 	bool drain_allow = true;
2407 
2408 	for (i = 0; i < nr_pages; i++) {
2409 		struct folio *folio = page_folio(pages[i]);
2410 
2411 		if (folio == prev_folio)
2412 			continue;
2413 		prev_folio = folio;
2414 
2415 		if (folio_is_longterm_pinnable(folio))
2416 			continue;
2417 
2418 		collected++;
2419 
2420 		if (folio_is_device_coherent(folio))
2421 			continue;
2422 
2423 		if (folio_test_hugetlb(folio)) {
2424 			isolate_hugetlb(folio, movable_page_list);
2425 			continue;
2426 		}
2427 
2428 		if (!folio_test_lru(folio) && drain_allow) {
2429 			lru_add_drain_all();
2430 			drain_allow = false;
2431 		}
2432 
2433 		if (!folio_isolate_lru(folio))
2434 			continue;
2435 
2436 		list_add_tail(&folio->lru, movable_page_list);
2437 		node_stat_mod_folio(folio,
2438 				    NR_ISOLATED_ANON + folio_is_file_lru(folio),
2439 				    folio_nr_pages(folio));
2440 	}
2441 
2442 	return collected;
2443 }
2444 
2445 /*
2446  * Unpins all pages and migrates device coherent pages and movable_page_list.
2447  * Returns -EAGAIN if all pages were successfully migrated or -errno for failure
2448  * (or partial success).
2449  */
2450 static int migrate_longterm_unpinnable_pages(
2451 					struct list_head *movable_page_list,
2452 					unsigned long nr_pages,
2453 					struct page **pages)
2454 {
2455 	int ret;
2456 	unsigned long i;
2457 
2458 	for (i = 0; i < nr_pages; i++) {
2459 		struct folio *folio = page_folio(pages[i]);
2460 
2461 		if (folio_is_device_coherent(folio)) {
2462 			/*
2463 			 * Migration will fail if the page is pinned, so convert
2464 			 * the pin on the source page to a normal reference.
2465 			 */
2466 			pages[i] = NULL;
2467 			folio_get(folio);
2468 			gup_put_folio(folio, 1, FOLL_PIN);
2469 
2470 			if (migrate_device_coherent_page(&folio->page)) {
2471 				ret = -EBUSY;
2472 				goto err;
2473 			}
2474 
2475 			continue;
2476 		}
2477 
2478 		/*
2479 		 * We can't migrate pages with unexpected references, so drop
2480 		 * the reference obtained by __get_user_pages_locked().
2481 		 * Migrating pages have been added to movable_page_list after
2482 		 * calling folio_isolate_lru() which takes a reference so the
2483 		 * page won't be freed if it's migrating.
2484 		 */
2485 		unpin_user_page(pages[i]);
2486 		pages[i] = NULL;
2487 	}
2488 
2489 	if (!list_empty(movable_page_list)) {
2490 		struct migration_target_control mtc = {
2491 			.nid = NUMA_NO_NODE,
2492 			.gfp_mask = GFP_USER | __GFP_NOWARN,
2493 			.reason = MR_LONGTERM_PIN,
2494 		};
2495 
2496 		if (migrate_pages(movable_page_list, alloc_migration_target,
2497 				  NULL, (unsigned long)&mtc, MIGRATE_SYNC,
2498 				  MR_LONGTERM_PIN, NULL)) {
2499 			ret = -ENOMEM;
2500 			goto err;
2501 		}
2502 	}
2503 
2504 	putback_movable_pages(movable_page_list);
2505 
2506 	return -EAGAIN;
2507 
2508 err:
2509 	for (i = 0; i < nr_pages; i++)
2510 		if (pages[i])
2511 			unpin_user_page(pages[i]);
2512 	putback_movable_pages(movable_page_list);
2513 
2514 	return ret;
2515 }
2516 
2517 /*
2518  * Check whether all pages are *allowed* to be pinned. Rather confusingly, all
2519  * pages in the range are required to be pinned via FOLL_PIN, before calling
2520  * this routine.
2521  *
2522  * If any pages in the range are not allowed to be pinned, then this routine
2523  * will migrate those pages away, unpin all the pages in the range and return
2524  * -EAGAIN. The caller should re-pin the entire range with FOLL_PIN and then
2525  * call this routine again.
2526  *
2527  * If an error other than -EAGAIN occurs, this indicates a migration failure.
2528  * The caller should give up, and propagate the error back up the call stack.
2529  *
2530  * If everything is OK and all pages in the range are allowed to be pinned, then
2531  * this routine leaves all pages pinned and returns zero for success.
2532  */
2533 static long check_and_migrate_movable_pages(unsigned long nr_pages,
2534 					    struct page **pages)
2535 {
2536 	unsigned long collected;
2537 	LIST_HEAD(movable_page_list);
2538 
2539 	collected = collect_longterm_unpinnable_pages(&movable_page_list,
2540 						nr_pages, pages);
2541 	if (!collected)
2542 		return 0;
2543 
2544 	return migrate_longterm_unpinnable_pages(&movable_page_list, nr_pages,
2545 						pages);
2546 }
2547 #else
2548 static long check_and_migrate_movable_pages(unsigned long nr_pages,
2549 					    struct page **pages)
2550 {
2551 	return 0;
2552 }
2553 #endif /* CONFIG_MIGRATION */
2554 
2555 /*
2556  * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
2557  * allows us to process the FOLL_LONGTERM flag.
2558  */
2559 static long __gup_longterm_locked(struct mm_struct *mm,
2560 				  unsigned long start,
2561 				  unsigned long nr_pages,
2562 				  struct page **pages,
2563 				  int *locked,
2564 				  unsigned int gup_flags)
2565 {
2566 	unsigned int flags;
2567 	long rc, nr_pinned_pages;
2568 
2569 	if (!(gup_flags & FOLL_LONGTERM))
2570 		return __get_user_pages_locked(mm, start, nr_pages, pages,
2571 					       locked, gup_flags);
2572 
2573 	flags = memalloc_pin_save();
2574 	do {
2575 		nr_pinned_pages = __get_user_pages_locked(mm, start, nr_pages,
2576 							  pages, locked,
2577 							  gup_flags);
2578 		if (nr_pinned_pages <= 0) {
2579 			rc = nr_pinned_pages;
2580 			break;
2581 		}
2582 
2583 		/* FOLL_LONGTERM implies FOLL_PIN */
2584 		rc = check_and_migrate_movable_pages(nr_pinned_pages, pages);
2585 	} while (rc == -EAGAIN);
2586 	memalloc_pin_restore(flags);
2587 	return rc ? rc : nr_pinned_pages;
2588 }
2589 
2590 /*
2591  * Check that the given flags are valid for the exported gup/pup interface, and
2592  * update them with the required flags that the caller must have set.
2593  */
2594 static bool is_valid_gup_args(struct page **pages, int *locked,
2595 			      unsigned int *gup_flags_p, unsigned int to_set)
2596 {
2597 	unsigned int gup_flags = *gup_flags_p;
2598 
2599 	/*
2600 	 * These flags not allowed to be specified externally to the gup
2601 	 * interfaces:
2602 	 * - FOLL_TOUCH/FOLL_PIN/FOLL_TRIED/FOLL_FAST_ONLY are internal only
2603 	 * - FOLL_REMOTE is internal only and used on follow_page()
2604 	 * - FOLL_UNLOCKABLE is internal only and used if locked is !NULL
2605 	 */
2606 	if (WARN_ON_ONCE(gup_flags & INTERNAL_GUP_FLAGS))
2607 		return false;
2608 
2609 	gup_flags |= to_set;
2610 	if (locked) {
2611 		/* At the external interface locked must be set */
2612 		if (WARN_ON_ONCE(*locked != 1))
2613 			return false;
2614 
2615 		gup_flags |= FOLL_UNLOCKABLE;
2616 	}
2617 
2618 	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
2619 	if (WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) ==
2620 			 (FOLL_PIN | FOLL_GET)))
2621 		return false;
2622 
2623 	/* LONGTERM can only be specified when pinning */
2624 	if (WARN_ON_ONCE(!(gup_flags & FOLL_PIN) && (gup_flags & FOLL_LONGTERM)))
2625 		return false;
2626 
2627 	/* Pages input must be given if using GET/PIN */
2628 	if (WARN_ON_ONCE((gup_flags & (FOLL_GET | FOLL_PIN)) && !pages))
2629 		return false;
2630 
2631 	/* We want to allow the pgmap to be hot-unplugged at all times */
2632 	if (WARN_ON_ONCE((gup_flags & FOLL_LONGTERM) &&
2633 			 (gup_flags & FOLL_PCI_P2PDMA)))
2634 		return false;
2635 
2636 	*gup_flags_p = gup_flags;
2637 	return true;
2638 }
2639 
2640 #ifdef CONFIG_MMU
2641 /**
2642  * get_user_pages_remote() - pin user pages in memory
2643  * @mm:		mm_struct of target mm
2644  * @start:	starting user address
2645  * @nr_pages:	number of pages from start to pin
2646  * @gup_flags:	flags modifying lookup behaviour
2647  * @pages:	array that receives pointers to the pages pinned.
2648  *		Should be at least nr_pages long. Or NULL, if caller
2649  *		only intends to ensure the pages are faulted in.
2650  * @locked:	pointer to lock flag indicating whether lock is held and
2651  *		subsequently whether VM_FAULT_RETRY functionality can be
2652  *		utilised. Lock must initially be held.
2653  *
2654  * Returns either number of pages pinned (which may be less than the
2655  * number requested), or an error. Details about the return value:
2656  *
2657  * -- If nr_pages is 0, returns 0.
2658  * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2659  * -- If nr_pages is >0, and some pages were pinned, returns the number of
2660  *    pages pinned. Again, this may be less than nr_pages.
2661  *
2662  * The caller is responsible for releasing returned @pages, via put_page().
2663  *
2664  * Must be called with mmap_lock held for read or write.
2665  *
2666  * get_user_pages_remote walks a process's page tables and takes a reference
2667  * to each struct page that each user address corresponds to at a given
2668  * instant. That is, it takes the page that would be accessed if a user
2669  * thread accesses the given user virtual address at that instant.
2670  *
2671  * This does not guarantee that the page exists in the user mappings when
2672  * get_user_pages_remote returns, and there may even be a completely different
2673  * page there in some cases (eg. if mmapped pagecache has been invalidated
2674  * and subsequently re-faulted). However it does guarantee that the page
2675  * won't be freed completely. And mostly callers simply care that the page
2676  * contains data that was valid *at some point in time*. Typically, an IO
2677  * or similar operation cannot guarantee anything stronger anyway because
2678  * locks can't be held over the syscall boundary.
2679  *
2680  * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2681  * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2682  * be called after the page is finished with, and before put_page is called.
2683  *
2684  * get_user_pages_remote is typically used for fewer-copy IO operations,
2685  * to get a handle on the memory by some means other than accesses
2686  * via the user virtual addresses. The pages may be submitted for
2687  * DMA to devices or accessed via their kernel linear mapping (via the
2688  * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2689  *
2690  * See also get_user_pages_fast, for performance critical applications.
2691  *
2692  * get_user_pages_remote should be phased out in favor of
2693  * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2694  * should use get_user_pages_remote because it cannot pass
2695  * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2696  */
2697 long get_user_pages_remote(struct mm_struct *mm,
2698 		unsigned long start, unsigned long nr_pages,
2699 		unsigned int gup_flags, struct page **pages,
2700 		int *locked)
2701 {
2702 	int local_locked = 1;
2703 
2704 	if (!is_valid_gup_args(pages, locked, &gup_flags,
2705 			       FOLL_TOUCH | FOLL_REMOTE))
2706 		return -EINVAL;
2707 
2708 	return __get_user_pages_locked(mm, start, nr_pages, pages,
2709 				       locked ? locked : &local_locked,
2710 				       gup_flags);
2711 }
2712 EXPORT_SYMBOL(get_user_pages_remote);
2713 
2714 #else /* CONFIG_MMU */
2715 long get_user_pages_remote(struct mm_struct *mm,
2716 			   unsigned long start, unsigned long nr_pages,
2717 			   unsigned int gup_flags, struct page **pages,
2718 			   int *locked)
2719 {
2720 	return 0;
2721 }
2722 #endif /* !CONFIG_MMU */
2723 
2724 /**
2725  * get_user_pages() - pin user pages in memory
2726  * @start:      starting user address
2727  * @nr_pages:   number of pages from start to pin
2728  * @gup_flags:  flags modifying lookup behaviour
2729  * @pages:      array that receives pointers to the pages pinned.
2730  *              Should be at least nr_pages long. Or NULL, if caller
2731  *              only intends to ensure the pages are faulted in.
2732  *
2733  * This is the same as get_user_pages_remote(), just with a less-flexible
2734  * calling convention where we assume that the mm being operated on belongs to
2735  * the current task, and doesn't allow passing of a locked parameter.  We also
2736  * obviously don't pass FOLL_REMOTE in here.
2737  */
2738 long get_user_pages(unsigned long start, unsigned long nr_pages,
2739 		    unsigned int gup_flags, struct page **pages)
2740 {
2741 	int locked = 1;
2742 
2743 	if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_TOUCH))
2744 		return -EINVAL;
2745 
2746 	return __get_user_pages_locked(current->mm, start, nr_pages, pages,
2747 				       &locked, gup_flags);
2748 }
2749 EXPORT_SYMBOL(get_user_pages);
2750 
2751 /*
2752  * get_user_pages_unlocked() is suitable to replace the form:
2753  *
2754  *      mmap_read_lock(mm);
2755  *      get_user_pages(mm, ..., pages, NULL);
2756  *      mmap_read_unlock(mm);
2757  *
2758  *  with:
2759  *
2760  *      get_user_pages_unlocked(mm, ..., pages);
2761  *
2762  * It is functionally equivalent to get_user_pages_fast so
2763  * get_user_pages_fast should be used instead if specific gup_flags
2764  * (e.g. FOLL_FORCE) are not required.
2765  */
2766 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2767 			     struct page **pages, unsigned int gup_flags)
2768 {
2769 	int locked = 0;
2770 
2771 	if (!is_valid_gup_args(pages, NULL, &gup_flags,
2772 			       FOLL_TOUCH | FOLL_UNLOCKABLE))
2773 		return -EINVAL;
2774 
2775 	return __get_user_pages_locked(current->mm, start, nr_pages, pages,
2776 				       &locked, gup_flags);
2777 }
2778 EXPORT_SYMBOL(get_user_pages_unlocked);
2779 
2780 /*
2781  * GUP-fast
2782  *
2783  * get_user_pages_fast attempts to pin user pages by walking the page
2784  * tables directly and avoids taking locks. Thus the walker needs to be
2785  * protected from page table pages being freed from under it, and should
2786  * block any THP splits.
2787  *
2788  * One way to achieve this is to have the walker disable interrupts, and
2789  * rely on IPIs from the TLB flushing code blocking before the page table
2790  * pages are freed. This is unsuitable for architectures that do not need
2791  * to broadcast an IPI when invalidating TLBs.
2792  *
2793  * Another way to achieve this is to batch up page table containing pages
2794  * belonging to more than one mm_user, then rcu_sched a callback to free those
2795  * pages. Disabling interrupts will allow the gup_fast() walker to both block
2796  * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2797  * (which is a relatively rare event). The code below adopts this strategy.
2798  *
2799  * Before activating this code, please be aware that the following assumptions
2800  * are currently made:
2801  *
2802  *  *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2803  *  free pages containing page tables or TLB flushing requires IPI broadcast.
2804  *
2805  *  *) ptes can be read atomically by the architecture.
2806  *
2807  *  *) access_ok is sufficient to validate userspace address ranges.
2808  *
2809  * The last two assumptions can be relaxed by the addition of helper functions.
2810  *
2811  * This code is based heavily on the PowerPC implementation by Nick Piggin.
2812  */
2813 #ifdef CONFIG_HAVE_GUP_FAST
2814 /*
2815  * Used in the GUP-fast path to determine whether GUP is permitted to work on
2816  * a specific folio.
2817  *
2818  * This call assumes the caller has pinned the folio, that the lowest page table
2819  * level still points to this folio, and that interrupts have been disabled.
2820  *
2821  * GUP-fast must reject all secretmem folios.
2822  *
2823  * Writing to pinned file-backed dirty tracked folios is inherently problematic
2824  * (see comment describing the writable_file_mapping_allowed() function). We
2825  * therefore try to avoid the most egregious case of a long-term mapping doing
2826  * so.
2827  *
2828  * This function cannot be as thorough as that one as the VMA is not available
2829  * in the fast path, so instead we whitelist known good cases and if in doubt,
2830  * fall back to the slow path.
2831  */
2832 static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)
2833 {
2834 	bool reject_file_backed = false;
2835 	struct address_space *mapping;
2836 	bool check_secretmem = false;
2837 	unsigned long mapping_flags;
2838 
2839 	/*
2840 	 * If we aren't pinning then no problematic write can occur. A long term
2841 	 * pin is the most egregious case so this is the one we disallow.
2842 	 */
2843 	if ((flags & (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)) ==
2844 	    (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE))
2845 		reject_file_backed = true;
2846 
2847 	/* We hold a folio reference, so we can safely access folio fields. */
2848 
2849 	/* secretmem folios are always order-0 folios. */
2850 	if (IS_ENABLED(CONFIG_SECRETMEM) && !folio_test_large(folio))
2851 		check_secretmem = true;
2852 
2853 	if (!reject_file_backed && !check_secretmem)
2854 		return true;
2855 
2856 	if (WARN_ON_ONCE(folio_test_slab(folio)))
2857 		return false;
2858 
2859 	/* hugetlb neither requires dirty-tracking nor can be secretmem. */
2860 	if (folio_test_hugetlb(folio))
2861 		return true;
2862 
2863 	/*
2864 	 * GUP-fast disables IRQs. When IRQS are disabled, RCU grace periods
2865 	 * cannot proceed, which means no actions performed under RCU can
2866 	 * proceed either.
2867 	 *
2868 	 * inodes and thus their mappings are freed under RCU, which means the
2869 	 * mapping cannot be freed beneath us and thus we can safely dereference
2870 	 * it.
2871 	 */
2872 	lockdep_assert_irqs_disabled();
2873 
2874 	/*
2875 	 * However, there may be operations which _alter_ the mapping, so ensure
2876 	 * we read it once and only once.
2877 	 */
2878 	mapping = READ_ONCE(folio->mapping);
2879 
2880 	/*
2881 	 * The mapping may have been truncated, in any case we cannot determine
2882 	 * if this mapping is safe - fall back to slow path to determine how to
2883 	 * proceed.
2884 	 */
2885 	if (!mapping)
2886 		return false;
2887 
2888 	/* Anonymous folios pose no problem. */
2889 	mapping_flags = (unsigned long)mapping & PAGE_MAPPING_FLAGS;
2890 	if (mapping_flags)
2891 		return mapping_flags & PAGE_MAPPING_ANON;
2892 
2893 	/*
2894 	 * At this point, we know the mapping is non-null and points to an
2895 	 * address_space object.
2896 	 */
2897 	if (check_secretmem && secretmem_mapping(mapping))
2898 		return false;
2899 	/* The only remaining allowed file system is shmem. */
2900 	return !reject_file_backed || shmem_mapping(mapping);
2901 }
2902 
2903 static void __maybe_unused gup_fast_undo_dev_pagemap(int *nr, int nr_start,
2904 		unsigned int flags, struct page **pages)
2905 {
2906 	while ((*nr) - nr_start) {
2907 		struct folio *folio = page_folio(pages[--(*nr)]);
2908 
2909 		folio_clear_referenced(folio);
2910 		gup_put_folio(folio, 1, flags);
2911 	}
2912 }
2913 
2914 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2915 /*
2916  * GUP-fast relies on pte change detection to avoid concurrent pgtable
2917  * operations.
2918  *
2919  * To pin the page, GUP-fast needs to do below in order:
2920  * (1) pin the page (by prefetching pte), then (2) check pte not changed.
2921  *
2922  * For the rest of pgtable operations where pgtable updates can be racy
2923  * with GUP-fast, we need to do (1) clear pte, then (2) check whether page
2924  * is pinned.
2925  *
2926  * Above will work for all pte-level operations, including THP split.
2927  *
2928  * For THP collapse, it's a bit more complicated because GUP-fast may be
2929  * walking a pgtable page that is being freed (pte is still valid but pmd
2930  * can be cleared already).  To avoid race in such condition, we need to
2931  * also check pmd here to make sure pmd doesn't change (corresponds to
2932  * pmdp_collapse_flush() in the THP collapse code path).
2933  */
2934 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
2935 		unsigned long end, unsigned int flags, struct page **pages,
2936 		int *nr)
2937 {
2938 	struct dev_pagemap *pgmap = NULL;
2939 	int nr_start = *nr, ret = 0;
2940 	pte_t *ptep, *ptem;
2941 
2942 	ptem = ptep = pte_offset_map(&pmd, addr);
2943 	if (!ptep)
2944 		return 0;
2945 	do {
2946 		pte_t pte = ptep_get_lockless(ptep);
2947 		struct page *page;
2948 		struct folio *folio;
2949 
2950 		/*
2951 		 * Always fallback to ordinary GUP on PROT_NONE-mapped pages:
2952 		 * pte_access_permitted() better should reject these pages
2953 		 * either way: otherwise, GUP-fast might succeed in
2954 		 * cases where ordinary GUP would fail due to VMA access
2955 		 * permissions.
2956 		 */
2957 		if (pte_protnone(pte))
2958 			goto pte_unmap;
2959 
2960 		if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2961 			goto pte_unmap;
2962 
2963 		if (pte_devmap(pte)) {
2964 			if (unlikely(flags & FOLL_LONGTERM))
2965 				goto pte_unmap;
2966 
2967 			pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2968 			if (unlikely(!pgmap)) {
2969 				gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
2970 				goto pte_unmap;
2971 			}
2972 		} else if (pte_special(pte))
2973 			goto pte_unmap;
2974 
2975 		VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2976 		page = pte_page(pte);
2977 
2978 		folio = try_grab_folio_fast(page, 1, flags);
2979 		if (!folio)
2980 			goto pte_unmap;
2981 
2982 		if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) ||
2983 		    unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
2984 			gup_put_folio(folio, 1, flags);
2985 			goto pte_unmap;
2986 		}
2987 
2988 		if (!gup_fast_folio_allowed(folio, flags)) {
2989 			gup_put_folio(folio, 1, flags);
2990 			goto pte_unmap;
2991 		}
2992 
2993 		if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) {
2994 			gup_put_folio(folio, 1, flags);
2995 			goto pte_unmap;
2996 		}
2997 
2998 		/*
2999 		 * We need to make the page accessible if and only if we are
3000 		 * going to access its content (the FOLL_PIN case).  Please
3001 		 * see Documentation/core-api/pin_user_pages.rst for
3002 		 * details.
3003 		 */
3004 		if (flags & FOLL_PIN) {
3005 			ret = arch_make_page_accessible(page);
3006 			if (ret) {
3007 				gup_put_folio(folio, 1, flags);
3008 				goto pte_unmap;
3009 			}
3010 		}
3011 		folio_set_referenced(folio);
3012 		pages[*nr] = page;
3013 		(*nr)++;
3014 	} while (ptep++, addr += PAGE_SIZE, addr != end);
3015 
3016 	ret = 1;
3017 
3018 pte_unmap:
3019 	if (pgmap)
3020 		put_dev_pagemap(pgmap);
3021 	pte_unmap(ptem);
3022 	return ret;
3023 }
3024 #else
3025 
3026 /*
3027  * If we can't determine whether or not a pte is special, then fail immediately
3028  * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
3029  * to be special.
3030  *
3031  * For a futex to be placed on a THP tail page, get_futex_key requires a
3032  * get_user_pages_fast_only implementation that can pin pages. Thus it's still
3033  * useful to have gup_fast_pmd_leaf even if we can't operate on ptes.
3034  */
3035 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
3036 		unsigned long end, unsigned int flags, struct page **pages,
3037 		int *nr)
3038 {
3039 	return 0;
3040 }
3041 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
3042 
3043 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
3044 static int gup_fast_devmap_leaf(unsigned long pfn, unsigned long addr,
3045 	unsigned long end, unsigned int flags, struct page **pages, int *nr)
3046 {
3047 	int nr_start = *nr;
3048 	struct dev_pagemap *pgmap = NULL;
3049 
3050 	do {
3051 		struct folio *folio;
3052 		struct page *page = pfn_to_page(pfn);
3053 
3054 		pgmap = get_dev_pagemap(pfn, pgmap);
3055 		if (unlikely(!pgmap)) {
3056 			gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3057 			break;
3058 		}
3059 
3060 		if (!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)) {
3061 			gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3062 			break;
3063 		}
3064 
3065 		folio = try_grab_folio_fast(page, 1, flags);
3066 		if (!folio) {
3067 			gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3068 			break;
3069 		}
3070 		folio_set_referenced(folio);
3071 		pages[*nr] = page;
3072 		(*nr)++;
3073 		pfn++;
3074 	} while (addr += PAGE_SIZE, addr != end);
3075 
3076 	put_dev_pagemap(pgmap);
3077 	return addr == end;
3078 }
3079 
3080 static int gup_fast_devmap_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
3081 		unsigned long end, unsigned int flags, struct page **pages,
3082 		int *nr)
3083 {
3084 	unsigned long fault_pfn;
3085 	int nr_start = *nr;
3086 
3087 	fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
3088 	if (!gup_fast_devmap_leaf(fault_pfn, addr, end, flags, pages, nr))
3089 		return 0;
3090 
3091 	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
3092 		gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3093 		return 0;
3094 	}
3095 	return 1;
3096 }
3097 
3098 static int gup_fast_devmap_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr,
3099 		unsigned long end, unsigned int flags, struct page **pages,
3100 		int *nr)
3101 {
3102 	unsigned long fault_pfn;
3103 	int nr_start = *nr;
3104 
3105 	fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
3106 	if (!gup_fast_devmap_leaf(fault_pfn, addr, end, flags, pages, nr))
3107 		return 0;
3108 
3109 	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
3110 		gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3111 		return 0;
3112 	}
3113 	return 1;
3114 }
3115 #else
3116 static int gup_fast_devmap_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
3117 		unsigned long end, unsigned int flags, struct page **pages,
3118 		int *nr)
3119 {
3120 	BUILD_BUG();
3121 	return 0;
3122 }
3123 
3124 static int gup_fast_devmap_pud_leaf(pud_t pud, pud_t *pudp, unsigned long addr,
3125 		unsigned long end, unsigned int flags, struct page **pages,
3126 		int *nr)
3127 {
3128 	BUILD_BUG();
3129 	return 0;
3130 }
3131 #endif
3132 
3133 static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
3134 		unsigned long end, unsigned int flags, struct page **pages,
3135 		int *nr)
3136 {
3137 	struct page *page;
3138 	struct folio *folio;
3139 	int refs;
3140 
3141 	if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
3142 		return 0;
3143 
3144 	if (pmd_devmap(orig)) {
3145 		if (unlikely(flags & FOLL_LONGTERM))
3146 			return 0;
3147 		return gup_fast_devmap_pmd_leaf(orig, pmdp, addr, end, flags,
3148 					        pages, nr);
3149 	}
3150 
3151 	page = pmd_page(orig);
3152 	refs = record_subpages(page, PMD_SIZE, addr, end, pages + *nr);
3153 
3154 	folio = try_grab_folio_fast(page, refs, flags);
3155 	if (!folio)
3156 		return 0;
3157 
3158 	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
3159 		gup_put_folio(folio, refs, flags);
3160 		return 0;
3161 	}
3162 
3163 	if (!gup_fast_folio_allowed(folio, flags)) {
3164 		gup_put_folio(folio, refs, flags);
3165 		return 0;
3166 	}
3167 	if (!pmd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
3168 		gup_put_folio(folio, refs, flags);
3169 		return 0;
3170 	}
3171 
3172 	*nr += refs;
3173 	folio_set_referenced(folio);
3174 	return 1;
3175 }
3176 
3177 static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr,
3178 		unsigned long end, unsigned int flags, struct page **pages,
3179 		int *nr)
3180 {
3181 	struct page *page;
3182 	struct folio *folio;
3183 	int refs;
3184 
3185 	if (!pud_access_permitted(orig, flags & FOLL_WRITE))
3186 		return 0;
3187 
3188 	if (pud_devmap(orig)) {
3189 		if (unlikely(flags & FOLL_LONGTERM))
3190 			return 0;
3191 		return gup_fast_devmap_pud_leaf(orig, pudp, addr, end, flags,
3192 					        pages, nr);
3193 	}
3194 
3195 	page = pud_page(orig);
3196 	refs = record_subpages(page, PUD_SIZE, addr, end, pages + *nr);
3197 
3198 	folio = try_grab_folio_fast(page, refs, flags);
3199 	if (!folio)
3200 		return 0;
3201 
3202 	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
3203 		gup_put_folio(folio, refs, flags);
3204 		return 0;
3205 	}
3206 
3207 	if (!gup_fast_folio_allowed(folio, flags)) {
3208 		gup_put_folio(folio, refs, flags);
3209 		return 0;
3210 	}
3211 
3212 	if (!pud_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
3213 		gup_put_folio(folio, refs, flags);
3214 		return 0;
3215 	}
3216 
3217 	*nr += refs;
3218 	folio_set_referenced(folio);
3219 	return 1;
3220 }
3221 
3222 static int gup_fast_pgd_leaf(pgd_t orig, pgd_t *pgdp, unsigned long addr,
3223 		unsigned long end, unsigned int flags, struct page **pages,
3224 		int *nr)
3225 {
3226 	int refs;
3227 	struct page *page;
3228 	struct folio *folio;
3229 
3230 	if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
3231 		return 0;
3232 
3233 	BUILD_BUG_ON(pgd_devmap(orig));
3234 
3235 	page = pgd_page(orig);
3236 	refs = record_subpages(page, PGDIR_SIZE, addr, end, pages + *nr);
3237 
3238 	folio = try_grab_folio_fast(page, refs, flags);
3239 	if (!folio)
3240 		return 0;
3241 
3242 	if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
3243 		gup_put_folio(folio, refs, flags);
3244 		return 0;
3245 	}
3246 
3247 	if (!pgd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
3248 		gup_put_folio(folio, refs, flags);
3249 		return 0;
3250 	}
3251 
3252 	if (!gup_fast_folio_allowed(folio, flags)) {
3253 		gup_put_folio(folio, refs, flags);
3254 		return 0;
3255 	}
3256 
3257 	*nr += refs;
3258 	folio_set_referenced(folio);
3259 	return 1;
3260 }
3261 
3262 static int gup_fast_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr,
3263 		unsigned long end, unsigned int flags, struct page **pages,
3264 		int *nr)
3265 {
3266 	unsigned long next;
3267 	pmd_t *pmdp;
3268 
3269 	pmdp = pmd_offset_lockless(pudp, pud, addr);
3270 	do {
3271 		pmd_t pmd = pmdp_get_lockless(pmdp);
3272 
3273 		next = pmd_addr_end(addr, end);
3274 		if (!pmd_present(pmd))
3275 			return 0;
3276 
3277 		if (unlikely(pmd_leaf(pmd))) {
3278 			/* See gup_fast_pte_range() */
3279 			if (pmd_protnone(pmd))
3280 				return 0;
3281 
3282 			if (!gup_fast_pmd_leaf(pmd, pmdp, addr, next, flags,
3283 				pages, nr))
3284 				return 0;
3285 
3286 		} else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
3287 			/*
3288 			 * architecture have different format for hugetlbfs
3289 			 * pmd format and THP pmd format
3290 			 */
3291 			if (gup_hugepd(NULL, __hugepd(pmd_val(pmd)), addr,
3292 				       PMD_SHIFT, next, flags, pages, nr,
3293 				       true) != 1)
3294 				return 0;
3295 		} else if (!gup_fast_pte_range(pmd, pmdp, addr, next, flags,
3296 					       pages, nr))
3297 			return 0;
3298 	} while (pmdp++, addr = next, addr != end);
3299 
3300 	return 1;
3301 }
3302 
3303 static int gup_fast_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr,
3304 		unsigned long end, unsigned int flags, struct page **pages,
3305 		int *nr)
3306 {
3307 	unsigned long next;
3308 	pud_t *pudp;
3309 
3310 	pudp = pud_offset_lockless(p4dp, p4d, addr);
3311 	do {
3312 		pud_t pud = READ_ONCE(*pudp);
3313 
3314 		next = pud_addr_end(addr, end);
3315 		if (unlikely(!pud_present(pud)))
3316 			return 0;
3317 		if (unlikely(pud_leaf(pud))) {
3318 			if (!gup_fast_pud_leaf(pud, pudp, addr, next, flags,
3319 					       pages, nr))
3320 				return 0;
3321 		} else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
3322 			if (gup_hugepd(NULL, __hugepd(pud_val(pud)), addr,
3323 				       PUD_SHIFT, next, flags, pages, nr,
3324 				       true) != 1)
3325 				return 0;
3326 		} else if (!gup_fast_pmd_range(pudp, pud, addr, next, flags,
3327 					       pages, nr))
3328 			return 0;
3329 	} while (pudp++, addr = next, addr != end);
3330 
3331 	return 1;
3332 }
3333 
3334 static int gup_fast_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr,
3335 		unsigned long end, unsigned int flags, struct page **pages,
3336 		int *nr)
3337 {
3338 	unsigned long next;
3339 	p4d_t *p4dp;
3340 
3341 	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
3342 	do {
3343 		p4d_t p4d = READ_ONCE(*p4dp);
3344 
3345 		next = p4d_addr_end(addr, end);
3346 		if (!p4d_present(p4d))
3347 			return 0;
3348 		BUILD_BUG_ON(p4d_leaf(p4d));
3349 		if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
3350 			if (gup_hugepd(NULL, __hugepd(p4d_val(p4d)), addr,
3351 				       P4D_SHIFT, next, flags, pages, nr,
3352 				       true) != 1)
3353 				return 0;
3354 		} else if (!gup_fast_pud_range(p4dp, p4d, addr, next, flags,
3355 					       pages, nr))
3356 			return 0;
3357 	} while (p4dp++, addr = next, addr != end);
3358 
3359 	return 1;
3360 }
3361 
3362 static void gup_fast_pgd_range(unsigned long addr, unsigned long end,
3363 		unsigned int flags, struct page **pages, int *nr)
3364 {
3365 	unsigned long next;
3366 	pgd_t *pgdp;
3367 
3368 	pgdp = pgd_offset(current->mm, addr);
3369 	do {
3370 		pgd_t pgd = READ_ONCE(*pgdp);
3371 
3372 		next = pgd_addr_end(addr, end);
3373 		if (pgd_none(pgd))
3374 			return;
3375 		if (unlikely(pgd_leaf(pgd))) {
3376 			if (!gup_fast_pgd_leaf(pgd, pgdp, addr, next, flags,
3377 					       pages, nr))
3378 				return;
3379 		} else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
3380 			if (gup_hugepd(NULL, __hugepd(pgd_val(pgd)), addr,
3381 				       PGDIR_SHIFT, next, flags, pages, nr,
3382 				       true) != 1)
3383 				return;
3384 		} else if (!gup_fast_p4d_range(pgdp, pgd, addr, next, flags,
3385 					       pages, nr))
3386 			return;
3387 	} while (pgdp++, addr = next, addr != end);
3388 }
3389 #else
3390 static inline void gup_fast_pgd_range(unsigned long addr, unsigned long end,
3391 		unsigned int flags, struct page **pages, int *nr)
3392 {
3393 }
3394 #endif /* CONFIG_HAVE_GUP_FAST */
3395 
3396 #ifndef gup_fast_permitted
3397 /*
3398  * Check if it's allowed to use get_user_pages_fast_only() for the range, or
3399  * we need to fall back to the slow version:
3400  */
3401 static bool gup_fast_permitted(unsigned long start, unsigned long end)
3402 {
3403 	return true;
3404 }
3405 #endif
3406 
3407 static unsigned long gup_fast(unsigned long start, unsigned long end,
3408 		unsigned int gup_flags, struct page **pages)
3409 {
3410 	unsigned long flags;
3411 	int nr_pinned = 0;
3412 	unsigned seq;
3413 
3414 	if (!IS_ENABLED(CONFIG_HAVE_GUP_FAST) ||
3415 	    !gup_fast_permitted(start, end))
3416 		return 0;
3417 
3418 	if (gup_flags & FOLL_PIN) {
3419 		seq = raw_read_seqcount(&current->mm->write_protect_seq);
3420 		if (seq & 1)
3421 			return 0;
3422 	}
3423 
3424 	/*
3425 	 * Disable interrupts. The nested form is used, in order to allow full,
3426 	 * general purpose use of this routine.
3427 	 *
3428 	 * With interrupts disabled, we block page table pages from being freed
3429 	 * from under us. See struct mmu_table_batch comments in
3430 	 * include/asm-generic/tlb.h for more details.
3431 	 *
3432 	 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
3433 	 * that come from THPs splitting.
3434 	 */
3435 	local_irq_save(flags);
3436 	gup_fast_pgd_range(start, end, gup_flags, pages, &nr_pinned);
3437 	local_irq_restore(flags);
3438 
3439 	/*
3440 	 * When pinning pages for DMA there could be a concurrent write protect
3441 	 * from fork() via copy_page_range(), in this case always fail GUP-fast.
3442 	 */
3443 	if (gup_flags & FOLL_PIN) {
3444 		if (read_seqcount_retry(&current->mm->write_protect_seq, seq)) {
3445 			gup_fast_unpin_user_pages(pages, nr_pinned);
3446 			return 0;
3447 		} else {
3448 			sanity_check_pinned_pages(pages, nr_pinned);
3449 		}
3450 	}
3451 	return nr_pinned;
3452 }
3453 
3454 static int gup_fast_fallback(unsigned long start, unsigned long nr_pages,
3455 		unsigned int gup_flags, struct page **pages)
3456 {
3457 	unsigned long len, end;
3458 	unsigned long nr_pinned;
3459 	int locked = 0;
3460 	int ret;
3461 
3462 	if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
3463 				       FOLL_FORCE | FOLL_PIN | FOLL_GET |
3464 				       FOLL_FAST_ONLY | FOLL_NOFAULT |
3465 				       FOLL_PCI_P2PDMA | FOLL_HONOR_NUMA_FAULT)))
3466 		return -EINVAL;
3467 
3468 	if (gup_flags & FOLL_PIN)
3469 		mm_set_has_pinned_flag(&current->mm->flags);
3470 
3471 	if (!(gup_flags & FOLL_FAST_ONLY))
3472 		might_lock_read(&current->mm->mmap_lock);
3473 
3474 	start = untagged_addr(start) & PAGE_MASK;
3475 	len = nr_pages << PAGE_SHIFT;
3476 	if (check_add_overflow(start, len, &end))
3477 		return -EOVERFLOW;
3478 	if (end > TASK_SIZE_MAX)
3479 		return -EFAULT;
3480 	if (unlikely(!access_ok((void __user *)start, len)))
3481 		return -EFAULT;
3482 
3483 	nr_pinned = gup_fast(start, end, gup_flags, pages);
3484 	if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
3485 		return nr_pinned;
3486 
3487 	/* Slow path: try to get the remaining pages with get_user_pages */
3488 	start += nr_pinned << PAGE_SHIFT;
3489 	pages += nr_pinned;
3490 	ret = __gup_longterm_locked(current->mm, start, nr_pages - nr_pinned,
3491 				    pages, &locked,
3492 				    gup_flags | FOLL_TOUCH | FOLL_UNLOCKABLE);
3493 	if (ret < 0) {
3494 		/*
3495 		 * The caller has to unpin the pages we already pinned so
3496 		 * returning -errno is not an option
3497 		 */
3498 		if (nr_pinned)
3499 			return nr_pinned;
3500 		return ret;
3501 	}
3502 	return ret + nr_pinned;
3503 }
3504 
3505 /**
3506  * get_user_pages_fast_only() - pin user pages in memory
3507  * @start:      starting user address
3508  * @nr_pages:   number of pages from start to pin
3509  * @gup_flags:  flags modifying pin behaviour
3510  * @pages:      array that receives pointers to the pages pinned.
3511  *              Should be at least nr_pages long.
3512  *
3513  * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
3514  * the regular GUP.
3515  *
3516  * If the architecture does not support this function, simply return with no
3517  * pages pinned.
3518  *
3519  * Careful, careful! COW breaking can go either way, so a non-write
3520  * access can get ambiguous page results. If you call this function without
3521  * 'write' set, you'd better be sure that you're ok with that ambiguity.
3522  */
3523 int get_user_pages_fast_only(unsigned long start, int nr_pages,
3524 			     unsigned int gup_flags, struct page **pages)
3525 {
3526 	/*
3527 	 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
3528 	 * because gup fast is always a "pin with a +1 page refcount" request.
3529 	 *
3530 	 * FOLL_FAST_ONLY is required in order to match the API description of
3531 	 * this routine: no fall back to regular ("slow") GUP.
3532 	 */
3533 	if (!is_valid_gup_args(pages, NULL, &gup_flags,
3534 			       FOLL_GET | FOLL_FAST_ONLY))
3535 		return -EINVAL;
3536 
3537 	return gup_fast_fallback(start, nr_pages, gup_flags, pages);
3538 }
3539 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
3540 
3541 /**
3542  * get_user_pages_fast() - pin user pages in memory
3543  * @start:      starting user address
3544  * @nr_pages:   number of pages from start to pin
3545  * @gup_flags:  flags modifying pin behaviour
3546  * @pages:      array that receives pointers to the pages pinned.
3547  *              Should be at least nr_pages long.
3548  *
3549  * Attempt to pin user pages in memory without taking mm->mmap_lock.
3550  * If not successful, it will fall back to taking the lock and
3551  * calling get_user_pages().
3552  *
3553  * Returns number of pages pinned. This may be fewer than the number requested.
3554  * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
3555  * -errno.
3556  */
3557 int get_user_pages_fast(unsigned long start, int nr_pages,
3558 			unsigned int gup_flags, struct page **pages)
3559 {
3560 	/*
3561 	 * The caller may or may not have explicitly set FOLL_GET; either way is
3562 	 * OK. However, internally (within mm/gup.c), gup fast variants must set
3563 	 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
3564 	 * request.
3565 	 */
3566 	if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_GET))
3567 		return -EINVAL;
3568 	return gup_fast_fallback(start, nr_pages, gup_flags, pages);
3569 }
3570 EXPORT_SYMBOL_GPL(get_user_pages_fast);
3571 
3572 /**
3573  * pin_user_pages_fast() - pin user pages in memory without taking locks
3574  *
3575  * @start:      starting user address
3576  * @nr_pages:   number of pages from start to pin
3577  * @gup_flags:  flags modifying pin behaviour
3578  * @pages:      array that receives pointers to the pages pinned.
3579  *              Should be at least nr_pages long.
3580  *
3581  * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
3582  * get_user_pages_fast() for documentation on the function arguments, because
3583  * the arguments here are identical.
3584  *
3585  * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3586  * see Documentation/core-api/pin_user_pages.rst for further details.
3587  *
3588  * Note that if a zero_page is amongst the returned pages, it will not have
3589  * pins in it and unpin_user_page() will not remove pins from it.
3590  */
3591 int pin_user_pages_fast(unsigned long start, int nr_pages,
3592 			unsigned int gup_flags, struct page **pages)
3593 {
3594 	if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
3595 		return -EINVAL;
3596 	return gup_fast_fallback(start, nr_pages, gup_flags, pages);
3597 }
3598 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
3599 
3600 /**
3601  * pin_user_pages_remote() - pin pages of a remote process
3602  *
3603  * @mm:		mm_struct of target mm
3604  * @start:	starting user address
3605  * @nr_pages:	number of pages from start to pin
3606  * @gup_flags:	flags modifying lookup behaviour
3607  * @pages:	array that receives pointers to the pages pinned.
3608  *		Should be at least nr_pages long.
3609  * @locked:	pointer to lock flag indicating whether lock is held and
3610  *		subsequently whether VM_FAULT_RETRY functionality can be
3611  *		utilised. Lock must initially be held.
3612  *
3613  * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3614  * get_user_pages_remote() for documentation on the function arguments, because
3615  * the arguments here are identical.
3616  *
3617  * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3618  * see Documentation/core-api/pin_user_pages.rst for details.
3619  *
3620  * Note that if a zero_page is amongst the returned pages, it will not have
3621  * pins in it and unpin_user_page*() will not remove pins from it.
3622  */
3623 long pin_user_pages_remote(struct mm_struct *mm,
3624 			   unsigned long start, unsigned long nr_pages,
3625 			   unsigned int gup_flags, struct page **pages,
3626 			   int *locked)
3627 {
3628 	int local_locked = 1;
3629 
3630 	if (!is_valid_gup_args(pages, locked, &gup_flags,
3631 			       FOLL_PIN | FOLL_TOUCH | FOLL_REMOTE))
3632 		return 0;
3633 	return __gup_longterm_locked(mm, start, nr_pages, pages,
3634 				     locked ? locked : &local_locked,
3635 				     gup_flags);
3636 }
3637 EXPORT_SYMBOL(pin_user_pages_remote);
3638 
3639 /**
3640  * pin_user_pages() - pin user pages in memory for use by other devices
3641  *
3642  * @start:	starting user address
3643  * @nr_pages:	number of pages from start to pin
3644  * @gup_flags:	flags modifying lookup behaviour
3645  * @pages:	array that receives pointers to the pages pinned.
3646  *		Should be at least nr_pages long.
3647  *
3648  * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3649  * FOLL_PIN is set.
3650  *
3651  * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3652  * see Documentation/core-api/pin_user_pages.rst for details.
3653  *
3654  * Note that if a zero_page is amongst the returned pages, it will not have
3655  * pins in it and unpin_user_page*() will not remove pins from it.
3656  */
3657 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3658 		    unsigned int gup_flags, struct page **pages)
3659 {
3660 	int locked = 1;
3661 
3662 	if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
3663 		return 0;
3664 	return __gup_longterm_locked(current->mm, start, nr_pages,
3665 				     pages, &locked, gup_flags);
3666 }
3667 EXPORT_SYMBOL(pin_user_pages);
3668 
3669 /*
3670  * pin_user_pages_unlocked() is the FOLL_PIN variant of
3671  * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3672  * FOLL_PIN and rejects FOLL_GET.
3673  *
3674  * Note that if a zero_page is amongst the returned pages, it will not have
3675  * pins in it and unpin_user_page*() will not remove pins from it.
3676  */
3677 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3678 			     struct page **pages, unsigned int gup_flags)
3679 {
3680 	int locked = 0;
3681 
3682 	if (!is_valid_gup_args(pages, NULL, &gup_flags,
3683 			       FOLL_PIN | FOLL_TOUCH | FOLL_UNLOCKABLE))
3684 		return 0;
3685 
3686 	return __gup_longterm_locked(current->mm, start, nr_pages, pages,
3687 				     &locked, gup_flags);
3688 }
3689 EXPORT_SYMBOL(pin_user_pages_unlocked);
3690