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