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