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