• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/err.h>
5 #include <linux/spinlock.h>
6 
7 #include <linux/mm.h>
8 #include <linux/memremap.h>
9 #include <linux/pagemap.h>
10 #include <linux/rmap.h>
11 #include <linux/swap.h>
12 #include <linux/swapops.h>
13 
14 #include <linux/sched/signal.h>
15 #include <linux/rwsem.h>
16 #include <linux/hugetlb.h>
17 #include <linux/migrate.h>
18 #include <linux/mm_inline.h>
19 #include <linux/sched/mm.h>
20 
21 #include <asm/mmu_context.h>
22 #include <asm/pgtable.h>
23 #include <asm/tlbflush.h>
24 
25 #include "internal.h"
26 
27 struct follow_page_context {
28 	struct dev_pagemap *pgmap;
29 	unsigned int page_mask;
30 };
31 
32 /**
33  * put_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
34  * @pages:  array of pages to be maybe marked dirty, and definitely released.
35  * @npages: number of pages in the @pages array.
36  * @make_dirty: whether to mark the pages dirty
37  *
38  * "gup-pinned page" refers to a page that has had one of the get_user_pages()
39  * variants called on that page.
40  *
41  * For each page in the @pages array, make that page (or its head page, if a
42  * compound page) dirty, if @make_dirty is true, and if the page was previously
43  * listed as clean. In any case, releases all pages using put_user_page(),
44  * possibly via put_user_pages(), for the non-dirty case.
45  *
46  * Please see the put_user_page() documentation for details.
47  *
48  * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
49  * required, then the caller should a) verify that this is really correct,
50  * because _lock() is usually required, and b) hand code it:
51  * set_page_dirty_lock(), put_user_page().
52  *
53  */
put_user_pages_dirty_lock(struct page ** pages,unsigned long npages,bool make_dirty)54 void put_user_pages_dirty_lock(struct page **pages, unsigned long npages,
55 			       bool make_dirty)
56 {
57 	unsigned long index;
58 
59 	/*
60 	 * TODO: this can be optimized for huge pages: if a series of pages is
61 	 * physically contiguous and part of the same compound page, then a
62 	 * single operation to the head page should suffice.
63 	 */
64 
65 	if (!make_dirty) {
66 		put_user_pages(pages, npages);
67 		return;
68 	}
69 
70 	for (index = 0; index < npages; index++) {
71 		struct page *page = compound_head(pages[index]);
72 		/*
73 		 * Checking PageDirty at this point may race with
74 		 * clear_page_dirty_for_io(), but that's OK. Two key
75 		 * cases:
76 		 *
77 		 * 1) This code sees the page as already dirty, so it
78 		 * skips the call to set_page_dirty(). That could happen
79 		 * because clear_page_dirty_for_io() called
80 		 * page_mkclean(), followed by set_page_dirty().
81 		 * However, now the page is going to get written back,
82 		 * which meets the original intention of setting it
83 		 * dirty, so all is well: clear_page_dirty_for_io() goes
84 		 * on to call TestClearPageDirty(), and write the page
85 		 * back.
86 		 *
87 		 * 2) This code sees the page as clean, so it calls
88 		 * set_page_dirty(). The page stays dirty, despite being
89 		 * written back, so it gets written back again in the
90 		 * next writeback cycle. This is harmless.
91 		 */
92 		if (!PageDirty(page))
93 			set_page_dirty_lock(page);
94 		put_user_page(page);
95 	}
96 }
97 EXPORT_SYMBOL(put_user_pages_dirty_lock);
98 
99 /**
100  * put_user_pages() - release an array of gup-pinned pages.
101  * @pages:  array of pages to be marked dirty and released.
102  * @npages: number of pages in the @pages array.
103  *
104  * For each page in the @pages array, release the page using put_user_page().
105  *
106  * Please see the put_user_page() documentation for details.
107  */
put_user_pages(struct page ** pages,unsigned long npages)108 void put_user_pages(struct page **pages, unsigned long npages)
109 {
110 	unsigned long index;
111 
112 	/*
113 	 * TODO: this can be optimized for huge pages: if a series of pages is
114 	 * physically contiguous and part of the same compound page, then a
115 	 * single operation to the head page should suffice.
116 	 */
117 	for (index = 0; index < npages; index++)
118 		put_user_page(pages[index]);
119 }
120 EXPORT_SYMBOL(put_user_pages);
121 
122 #ifdef CONFIG_MMU
no_page_table(struct vm_area_struct * vma,unsigned int flags)123 static struct page *no_page_table(struct vm_area_struct *vma,
124 		unsigned int flags)
125 {
126 	/*
127 	 * When core dumping an enormous anonymous area that nobody
128 	 * has touched so far, we don't want to allocate unnecessary pages or
129 	 * page tables.  Return error instead of NULL to skip handle_mm_fault,
130 	 * then get_dump_page() will return NULL to leave a hole in the dump.
131 	 * But we can only make this optimization where a hole would surely
132 	 * be zero-filled if handle_mm_fault() actually did handle it.
133 	 */
134 	if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault))
135 		return ERR_PTR(-EFAULT);
136 	return NULL;
137 }
138 
follow_pfn_pte(struct vm_area_struct * vma,unsigned long address,pte_t * pte,unsigned int flags)139 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
140 		pte_t *pte, unsigned int flags)
141 {
142 	/* No page to get reference */
143 	if (flags & FOLL_GET)
144 		return -EFAULT;
145 
146 	if (flags & FOLL_TOUCH) {
147 		pte_t entry = *pte;
148 
149 		if (flags & FOLL_WRITE)
150 			entry = pte_mkdirty(entry);
151 		entry = pte_mkyoung(entry);
152 
153 		if (!pte_same(*pte, entry)) {
154 			set_pte_at(vma->vm_mm, address, pte, entry);
155 			update_mmu_cache(vma, address, pte);
156 		}
157 	}
158 
159 	/* Proper page table entry exists, but no corresponding struct page */
160 	return -EEXIST;
161 }
162 
163 /*
164  * FOLL_FORCE or a forced COW break can write even to unwritable pte's,
165  * but only after we've gone through a COW cycle and they are dirty.
166  */
can_follow_write_pte(pte_t pte,unsigned int flags)167 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
168 {
169 	return pte_write(pte) || ((flags & FOLL_COW) && pte_dirty(pte));
170 }
171 
172 /*
173  * A (separate) COW fault might break the page the other way and
174  * get_user_pages() would return the page from what is now the wrong
175  * VM. So we need to force a COW break at GUP time even for reads.
176  */
should_force_cow_break(struct vm_area_struct * vma,unsigned int flags)177 static inline bool should_force_cow_break(struct vm_area_struct *vma, unsigned int flags)
178 {
179 	return is_cow_mapping(vma->vm_flags) && (flags & FOLL_GET);
180 }
181 
follow_page_pte(struct vm_area_struct * vma,unsigned long address,pmd_t * pmd,unsigned int flags,struct dev_pagemap ** pgmap)182 static struct page *follow_page_pte(struct vm_area_struct *vma,
183 		unsigned long address, pmd_t *pmd, unsigned int flags,
184 		struct dev_pagemap **pgmap)
185 {
186 	struct mm_struct *mm = vma->vm_mm;
187 	struct page *page;
188 	spinlock_t *ptl;
189 	pte_t *ptep, pte;
190 
191 	/*
192 	 * Considering PTE level hugetlb, like continuous-PTE hugetlb on
193 	 * ARM64 architecture.
194 	 */
195 	if (is_vm_hugetlb_page(vma)) {
196 		page = follow_huge_pmd_pte(vma, address, flags);
197 		if (page)
198 			return page;
199 		return no_page_table(vma, flags);
200 	}
201 
202 retry:
203 	if (unlikely(pmd_bad(*pmd)))
204 		return no_page_table(vma, flags);
205 
206 	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
207 	pte = *ptep;
208 	if (!pte_present(pte)) {
209 		swp_entry_t entry;
210 		/*
211 		 * KSM's break_ksm() relies upon recognizing a ksm page
212 		 * even while it is being migrated, so for that case we
213 		 * need migration_entry_wait().
214 		 */
215 		if (likely(!(flags & FOLL_MIGRATION)))
216 			goto no_page;
217 		if (pte_none(pte))
218 			goto no_page;
219 		entry = pte_to_swp_entry(pte);
220 		if (!is_migration_entry(entry))
221 			goto no_page;
222 		pte_unmap_unlock(ptep, ptl);
223 		migration_entry_wait(mm, pmd, address);
224 		goto retry;
225 	}
226 	if ((flags & FOLL_NUMA) && pte_protnone(pte))
227 		goto no_page;
228 	if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
229 		pte_unmap_unlock(ptep, ptl);
230 		return NULL;
231 	}
232 
233 	page = vm_normal_page(vma, address, pte);
234 	if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
235 		/*
236 		 * Only return device mapping pages in the FOLL_GET case since
237 		 * they are only valid while holding the pgmap reference.
238 		 */
239 		*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
240 		if (*pgmap)
241 			page = pte_page(pte);
242 		else
243 			goto no_page;
244 	} else if (unlikely(!page)) {
245 		if (flags & FOLL_DUMP) {
246 			/* Avoid special (like zero) pages in core dumps */
247 			page = ERR_PTR(-EFAULT);
248 			goto out;
249 		}
250 
251 		if (is_zero_pfn(pte_pfn(pte))) {
252 			page = pte_page(pte);
253 		} else {
254 			int ret;
255 
256 			ret = follow_pfn_pte(vma, address, ptep, flags);
257 			page = ERR_PTR(ret);
258 			goto out;
259 		}
260 	}
261 
262 	if (flags & FOLL_SPLIT && PageTransCompound(page)) {
263 		int ret;
264 		get_page(page);
265 		pte_unmap_unlock(ptep, ptl);
266 		lock_page(page);
267 		ret = split_huge_page(page);
268 		unlock_page(page);
269 		put_page(page);
270 		if (ret)
271 			return ERR_PTR(ret);
272 		goto retry;
273 	}
274 
275 	if (flags & FOLL_GET) {
276 		if (unlikely(!try_get_page(page))) {
277 			page = ERR_PTR(-ENOMEM);
278 			goto out;
279 		}
280 	}
281 	if (flags & FOLL_TOUCH) {
282 		if ((flags & FOLL_WRITE) &&
283 		    !pte_dirty(pte) && !PageDirty(page))
284 			set_page_dirty(page);
285 		/*
286 		 * pte_mkyoung() would be more correct here, but atomic care
287 		 * is needed to avoid losing the dirty bit: it is easier to use
288 		 * mark_page_accessed().
289 		 */
290 		mark_page_accessed(page);
291 	}
292 	if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
293 		/* Do not mlock pte-mapped THP */
294 		if (PageTransCompound(page))
295 			goto out;
296 
297 		/*
298 		 * The preliminary mapping check is mainly to avoid the
299 		 * pointless overhead of lock_page on the ZERO_PAGE
300 		 * which might bounce very badly if there is contention.
301 		 *
302 		 * If the page is already locked, we don't need to
303 		 * handle it now - vmscan will handle it later if and
304 		 * when it attempts to reclaim the page.
305 		 */
306 		if (page->mapping && trylock_page(page)) {
307 			lru_add_drain();  /* push cached pages to LRU */
308 			/*
309 			 * Because we lock page here, and migration is
310 			 * blocked by the pte's page reference, and we
311 			 * know the page is still mapped, we don't even
312 			 * need to check for file-cache page truncation.
313 			 */
314 			mlock_vma_page(page);
315 			unlock_page(page);
316 		}
317 	}
318 out:
319 	pte_unmap_unlock(ptep, ptl);
320 	return page;
321 no_page:
322 	pte_unmap_unlock(ptep, ptl);
323 	if (!pte_none(pte))
324 		return NULL;
325 	return no_page_table(vma, flags);
326 }
327 
follow_pmd_mask(struct vm_area_struct * vma,unsigned long address,pud_t * pudp,unsigned int flags,struct follow_page_context * ctx)328 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
329 				    unsigned long address, pud_t *pudp,
330 				    unsigned int flags,
331 				    struct follow_page_context *ctx)
332 {
333 	pmd_t *pmd, pmdval;
334 	spinlock_t *ptl;
335 	struct page *page;
336 	struct mm_struct *mm = vma->vm_mm;
337 
338 	pmd = pmd_offset(pudp, address);
339 	/*
340 	 * The READ_ONCE() will stabilize the pmdval in a register or
341 	 * on the stack so that it will stop changing under the code.
342 	 */
343 	pmdval = READ_ONCE(*pmd);
344 	if (pmd_none(pmdval))
345 		return no_page_table(vma, flags);
346 	if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) {
347 		page = follow_huge_pmd_pte(vma, address, flags);
348 		if (page)
349 			return page;
350 		return no_page_table(vma, flags);
351 	}
352 	if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
353 		page = follow_huge_pd(vma, address,
354 				      __hugepd(pmd_val(pmdval)), flags,
355 				      PMD_SHIFT);
356 		if (page)
357 			return page;
358 		return no_page_table(vma, flags);
359 	}
360 retry:
361 	if (!pmd_present(pmdval)) {
362 		if (likely(!(flags & FOLL_MIGRATION)))
363 			return no_page_table(vma, flags);
364 		VM_BUG_ON(thp_migration_supported() &&
365 				  !is_pmd_migration_entry(pmdval));
366 		if (is_pmd_migration_entry(pmdval))
367 			pmd_migration_entry_wait(mm, pmd);
368 		pmdval = READ_ONCE(*pmd);
369 		/*
370 		 * MADV_DONTNEED may convert the pmd to null because
371 		 * mmap_sem is held in read mode
372 		 */
373 		if (pmd_none(pmdval))
374 			return no_page_table(vma, flags);
375 		goto retry;
376 	}
377 	if (pmd_devmap(pmdval)) {
378 		ptl = pmd_lock(mm, pmd);
379 		page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
380 		spin_unlock(ptl);
381 		if (page)
382 			return page;
383 	}
384 	if (likely(!pmd_trans_huge(pmdval)))
385 		return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
386 
387 	if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
388 		return no_page_table(vma, flags);
389 
390 retry_locked:
391 	ptl = pmd_lock(mm, pmd);
392 	if (unlikely(pmd_none(*pmd))) {
393 		spin_unlock(ptl);
394 		return no_page_table(vma, flags);
395 	}
396 	if (unlikely(!pmd_present(*pmd))) {
397 		spin_unlock(ptl);
398 		if (likely(!(flags & FOLL_MIGRATION)))
399 			return no_page_table(vma, flags);
400 		pmd_migration_entry_wait(mm, pmd);
401 		goto retry_locked;
402 	}
403 	if (unlikely(!pmd_trans_huge(*pmd))) {
404 		spin_unlock(ptl);
405 		return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
406 	}
407 	if (flags & (FOLL_SPLIT | FOLL_SPLIT_PMD)) {
408 		int ret;
409 		page = pmd_page(*pmd);
410 		if (is_huge_zero_page(page)) {
411 			spin_unlock(ptl);
412 			ret = 0;
413 			split_huge_pmd(vma, pmd, address);
414 			if (pmd_trans_unstable(pmd))
415 				ret = -EBUSY;
416 		} else if (flags & FOLL_SPLIT) {
417 			if (unlikely(!try_get_page(page))) {
418 				spin_unlock(ptl);
419 				return ERR_PTR(-ENOMEM);
420 			}
421 			spin_unlock(ptl);
422 			lock_page(page);
423 			ret = split_huge_page(page);
424 			unlock_page(page);
425 			put_page(page);
426 			if (pmd_none(*pmd))
427 				return no_page_table(vma, flags);
428 		} else {  /* flags & FOLL_SPLIT_PMD */
429 			spin_unlock(ptl);
430 			split_huge_pmd(vma, pmd, address);
431 			ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
432 		}
433 
434 		return ret ? ERR_PTR(ret) :
435 			follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
436 	}
437 	page = follow_trans_huge_pmd(vma, address, pmd, flags);
438 	spin_unlock(ptl);
439 	ctx->page_mask = HPAGE_PMD_NR - 1;
440 	return page;
441 }
442 
follow_pud_mask(struct vm_area_struct * vma,unsigned long address,p4d_t * p4dp,unsigned int flags,struct follow_page_context * ctx)443 static struct page *follow_pud_mask(struct vm_area_struct *vma,
444 				    unsigned long address, p4d_t *p4dp,
445 				    unsigned int flags,
446 				    struct follow_page_context *ctx)
447 {
448 	pud_t *pud;
449 	spinlock_t *ptl;
450 	struct page *page;
451 	struct mm_struct *mm = vma->vm_mm;
452 
453 	pud = pud_offset(p4dp, address);
454 	if (pud_none(*pud))
455 		return no_page_table(vma, flags);
456 	if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
457 		page = follow_huge_pud(mm, address, pud, flags);
458 		if (page)
459 			return page;
460 		return no_page_table(vma, flags);
461 	}
462 	if (is_hugepd(__hugepd(pud_val(*pud)))) {
463 		page = follow_huge_pd(vma, address,
464 				      __hugepd(pud_val(*pud)), flags,
465 				      PUD_SHIFT);
466 		if (page)
467 			return page;
468 		return no_page_table(vma, flags);
469 	}
470 	if (pud_devmap(*pud)) {
471 		ptl = pud_lock(mm, pud);
472 		page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
473 		spin_unlock(ptl);
474 		if (page)
475 			return page;
476 	}
477 	if (unlikely(pud_bad(*pud)))
478 		return no_page_table(vma, flags);
479 
480 	return follow_pmd_mask(vma, address, pud, flags, ctx);
481 }
482 
follow_p4d_mask(struct vm_area_struct * vma,unsigned long address,pgd_t * pgdp,unsigned int flags,struct follow_page_context * ctx)483 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
484 				    unsigned long address, pgd_t *pgdp,
485 				    unsigned int flags,
486 				    struct follow_page_context *ctx)
487 {
488 	p4d_t *p4d;
489 	struct page *page;
490 
491 	p4d = p4d_offset(pgdp, address);
492 	if (p4d_none(*p4d))
493 		return no_page_table(vma, flags);
494 	BUILD_BUG_ON(p4d_huge(*p4d));
495 	if (unlikely(p4d_bad(*p4d)))
496 		return no_page_table(vma, flags);
497 
498 	if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
499 		page = follow_huge_pd(vma, address,
500 				      __hugepd(p4d_val(*p4d)), flags,
501 				      P4D_SHIFT);
502 		if (page)
503 			return page;
504 		return no_page_table(vma, flags);
505 	}
506 	return follow_pud_mask(vma, address, p4d, flags, ctx);
507 }
508 
509 /**
510  * follow_page_mask - look up a page descriptor from a user-virtual address
511  * @vma: vm_area_struct mapping @address
512  * @address: virtual address to look up
513  * @flags: flags modifying lookup behaviour
514  * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
515  *       pointer to output page_mask
516  *
517  * @flags can have FOLL_ flags set, defined in <linux/mm.h>
518  *
519  * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
520  * the device's dev_pagemap metadata to avoid repeating expensive lookups.
521  *
522  * On output, the @ctx->page_mask is set according to the size of the page.
523  *
524  * Return: the mapped (struct page *), %NULL if no mapping exists, or
525  * an error pointer if there is a mapping to something not represented
526  * by a page descriptor (see also vm_normal_page()).
527  */
follow_page_mask(struct vm_area_struct * vma,unsigned long address,unsigned int flags,struct follow_page_context * ctx)528 static struct page *follow_page_mask(struct vm_area_struct *vma,
529 			      unsigned long address, unsigned int flags,
530 			      struct follow_page_context *ctx)
531 {
532 	pgd_t *pgd;
533 	struct page *page;
534 	struct mm_struct *mm = vma->vm_mm;
535 
536 	ctx->page_mask = 0;
537 
538 	/* make this handle hugepd */
539 	page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
540 	if (!IS_ERR(page)) {
541 		BUG_ON(flags & FOLL_GET);
542 		return page;
543 	}
544 
545 	pgd = pgd_offset(mm, address);
546 
547 	if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
548 		return no_page_table(vma, flags);
549 
550 	if (pgd_huge(*pgd)) {
551 		page = follow_huge_pgd(mm, address, pgd, flags);
552 		if (page)
553 			return page;
554 		return no_page_table(vma, flags);
555 	}
556 	if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
557 		page = follow_huge_pd(vma, address,
558 				      __hugepd(pgd_val(*pgd)), flags,
559 				      PGDIR_SHIFT);
560 		if (page)
561 			return page;
562 		return no_page_table(vma, flags);
563 	}
564 
565 	return follow_p4d_mask(vma, address, pgd, flags, ctx);
566 }
567 
follow_page(struct vm_area_struct * vma,unsigned long address,unsigned int foll_flags)568 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
569 			 unsigned int foll_flags)
570 {
571 	struct follow_page_context ctx = { NULL };
572 	struct page *page;
573 
574 	page = follow_page_mask(vma, address, foll_flags, &ctx);
575 	if (ctx.pgmap)
576 		put_dev_pagemap(ctx.pgmap);
577 	return page;
578 }
579 
get_gate_page(struct mm_struct * mm,unsigned long address,unsigned int gup_flags,struct vm_area_struct ** vma,struct page ** page)580 static int get_gate_page(struct mm_struct *mm, unsigned long address,
581 		unsigned int gup_flags, struct vm_area_struct **vma,
582 		struct page **page)
583 {
584 	pgd_t *pgd;
585 	p4d_t *p4d;
586 	pud_t *pud;
587 	pmd_t *pmd;
588 	pte_t *pte;
589 	int ret = -EFAULT;
590 
591 	/* user gate pages are read-only */
592 	if (gup_flags & FOLL_WRITE)
593 		return -EFAULT;
594 	if (address > TASK_SIZE)
595 		pgd = pgd_offset_k(address);
596 	else
597 		pgd = pgd_offset_gate(mm, address);
598 	if (pgd_none(*pgd))
599 		return -EFAULT;
600 	p4d = p4d_offset(pgd, address);
601 	if (p4d_none(*p4d))
602 		return -EFAULT;
603 	pud = pud_offset(p4d, address);
604 	if (pud_none(*pud))
605 		return -EFAULT;
606 	pmd = pmd_offset(pud, address);
607 	if (!pmd_present(*pmd))
608 		return -EFAULT;
609 	VM_BUG_ON(pmd_trans_huge(*pmd));
610 	pte = pte_offset_map(pmd, address);
611 	if (pte_none(*pte))
612 		goto unmap;
613 	*vma = get_gate_vma(mm);
614 	if (!page)
615 		goto out;
616 	*page = vm_normal_page(*vma, address, *pte);
617 	if (!*page) {
618 		if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
619 			goto unmap;
620 		*page = pte_page(*pte);
621 	}
622 	if (unlikely(!try_get_page(*page))) {
623 		ret = -ENOMEM;
624 		goto unmap;
625 	}
626 out:
627 	ret = 0;
628 unmap:
629 	pte_unmap(pte);
630 	return ret;
631 }
632 
633 /*
634  * mmap_sem must be held on entry.  If @nonblocking != NULL and
635  * *@flags does not include FOLL_NOWAIT, the mmap_sem may be released.
636  * If it is, *@nonblocking will be set to 0 and -EBUSY returned.
637  */
faultin_page(struct task_struct * tsk,struct vm_area_struct * vma,unsigned long address,unsigned int * flags,int * nonblocking)638 static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
639 		unsigned long address, unsigned int *flags, int *nonblocking)
640 {
641 	unsigned int fault_flags = 0;
642 	vm_fault_t ret;
643 
644 	/* mlock all present pages, but do not fault in new pages */
645 	if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
646 		return -ENOENT;
647 	if (*flags & FOLL_WRITE)
648 		fault_flags |= FAULT_FLAG_WRITE;
649 	if (*flags & FOLL_REMOTE)
650 		fault_flags |= FAULT_FLAG_REMOTE;
651 	if (nonblocking)
652 		fault_flags |= FAULT_FLAG_ALLOW_RETRY;
653 	if (*flags & FOLL_NOWAIT)
654 		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
655 	if (*flags & FOLL_TRIED) {
656 		VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
657 		fault_flags |= FAULT_FLAG_TRIED;
658 	}
659 
660 	ret = handle_mm_fault(vma, address, fault_flags);
661 	if (ret & VM_FAULT_ERROR) {
662 		int err = vm_fault_to_errno(ret, *flags);
663 
664 		if (err)
665 			return err;
666 		BUG();
667 	}
668 
669 	if (tsk) {
670 		if (ret & VM_FAULT_MAJOR)
671 			tsk->maj_flt++;
672 		else
673 			tsk->min_flt++;
674 	}
675 
676 	if (ret & VM_FAULT_RETRY) {
677 		if (nonblocking && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
678 			*nonblocking = 0;
679 		return -EBUSY;
680 	}
681 
682 	/*
683 	 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
684 	 * necessary, even if maybe_mkwrite decided not to set pte_write. We
685 	 * can thus safely do subsequent page lookups as if they were reads.
686 	 * But only do so when looping for pte_write is futile: in some cases
687 	 * userspace may also be wanting to write to the gotten user page,
688 	 * which a read fault here might prevent (a readonly page might get
689 	 * reCOWed by userspace write).
690 	 */
691 	if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
692 		*flags |= FOLL_COW;
693 	return 0;
694 }
695 
check_vma_flags(struct vm_area_struct * vma,unsigned long gup_flags)696 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
697 {
698 	vm_flags_t vm_flags = vma->vm_flags;
699 	int write = (gup_flags & FOLL_WRITE);
700 	int foreign = (gup_flags & FOLL_REMOTE);
701 
702 	if (vm_flags & (VM_IO | VM_PFNMAP))
703 		return -EFAULT;
704 
705 	if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
706 		return -EFAULT;
707 
708 	if (write) {
709 		if (!(vm_flags & VM_WRITE)) {
710 			if (!(gup_flags & FOLL_FORCE))
711 				return -EFAULT;
712 			/*
713 			 * We used to let the write,force case do COW in a
714 			 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
715 			 * set a breakpoint in a read-only mapping of an
716 			 * executable, without corrupting the file (yet only
717 			 * when that file had been opened for writing!).
718 			 * Anon pages in shared mappings are surprising: now
719 			 * just reject it.
720 			 */
721 			if (!is_cow_mapping(vm_flags))
722 				return -EFAULT;
723 		}
724 	} else if (!(vm_flags & VM_READ)) {
725 		if (!(gup_flags & FOLL_FORCE))
726 			return -EFAULT;
727 		/*
728 		 * Is there actually any vma we can reach here which does not
729 		 * have VM_MAYREAD set?
730 		 */
731 		if (!(vm_flags & VM_MAYREAD))
732 			return -EFAULT;
733 	}
734 	/*
735 	 * gups are always data accesses, not instruction
736 	 * fetches, so execute=false here
737 	 */
738 	if (!arch_vma_access_permitted(vma, write, false, foreign))
739 		return -EFAULT;
740 	return 0;
741 }
742 
743 /**
744  * __get_user_pages() - pin user pages in memory
745  * @tsk:	task_struct of target task
746  * @mm:		mm_struct of target mm
747  * @start:	starting user address
748  * @nr_pages:	number of pages from start to pin
749  * @gup_flags:	flags modifying pin behaviour
750  * @pages:	array that receives pointers to the pages pinned.
751  *		Should be at least nr_pages long. Or NULL, if caller
752  *		only intends to ensure the pages are faulted in.
753  * @vmas:	array of pointers to vmas corresponding to each page.
754  *		Or NULL if the caller does not require them.
755  * @nonblocking: whether waiting for disk IO or mmap_sem contention
756  *
757  * Returns number of pages pinned. This may be fewer than the number
758  * requested. If nr_pages is 0 or negative, returns 0. If no pages
759  * were pinned, returns -errno. Each page returned must be released
760  * with a put_page() call when it is finished with. vmas will only
761  * remain valid while mmap_sem is held.
762  *
763  * Must be called with mmap_sem held.  It may be released.  See below.
764  *
765  * __get_user_pages walks a process's page tables and takes a reference to
766  * each struct page that each user address corresponds to at a given
767  * instant. That is, it takes the page that would be accessed if a user
768  * thread accesses the given user virtual address at that instant.
769  *
770  * This does not guarantee that the page exists in the user mappings when
771  * __get_user_pages returns, and there may even be a completely different
772  * page there in some cases (eg. if mmapped pagecache has been invalidated
773  * and subsequently re faulted). However it does guarantee that the page
774  * won't be freed completely. And mostly callers simply care that the page
775  * contains data that was valid *at some point in time*. Typically, an IO
776  * or similar operation cannot guarantee anything stronger anyway because
777  * locks can't be held over the syscall boundary.
778  *
779  * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
780  * the page is written to, set_page_dirty (or set_page_dirty_lock, as
781  * appropriate) must be called after the page is finished with, and
782  * before put_page is called.
783  *
784  * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
785  * or mmap_sem contention, and if waiting is needed to pin all pages,
786  * *@nonblocking will be set to 0.  Further, if @gup_flags does not
787  * include FOLL_NOWAIT, the mmap_sem will be released via up_read() in
788  * this case.
789  *
790  * A caller using such a combination of @nonblocking and @gup_flags
791  * must therefore hold the mmap_sem for reading only, and recognize
792  * when it's been released.  Otherwise, it must be held for either
793  * reading or writing and will not be released.
794  *
795  * In most cases, get_user_pages or get_user_pages_fast should be used
796  * instead of __get_user_pages. __get_user_pages should be used only if
797  * you need some special @gup_flags.
798  */
__get_user_pages(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,unsigned int gup_flags,struct page ** pages,struct vm_area_struct ** vmas,int * nonblocking)799 static long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
800 		unsigned long start, unsigned long nr_pages,
801 		unsigned int gup_flags, struct page **pages,
802 		struct vm_area_struct **vmas, int *nonblocking)
803 {
804 	long ret = 0, i = 0;
805 	struct vm_area_struct *vma = NULL;
806 	struct follow_page_context ctx = { NULL };
807 
808 	if (!nr_pages)
809 		return 0;
810 
811 	start = untagged_addr(start);
812 
813 	VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
814 
815 	/*
816 	 * If FOLL_FORCE is set then do not force a full fault as the hinting
817 	 * fault information is unrelated to the reference behaviour of a task
818 	 * using the address space
819 	 */
820 	if (!(gup_flags & FOLL_FORCE))
821 		gup_flags |= FOLL_NUMA;
822 
823 	do {
824 		struct page *page;
825 		unsigned int foll_flags = gup_flags;
826 		unsigned int page_increm;
827 
828 		/* first iteration or cross vma bound */
829 		if (!vma || start >= vma->vm_end) {
830 			vma = find_extend_vma(mm, start);
831 			if (!vma && in_gate_area(mm, start)) {
832 				ret = get_gate_page(mm, start & PAGE_MASK,
833 						gup_flags, &vma,
834 						pages ? &pages[i] : NULL);
835 				if (ret)
836 					goto out;
837 				ctx.page_mask = 0;
838 				goto next_page;
839 			}
840 
841 			if (!vma || check_vma_flags(vma, gup_flags)) {
842 				ret = -EFAULT;
843 				goto out;
844 			}
845 			if (is_vm_hugetlb_page(vma)) {
846 				if (should_force_cow_break(vma, foll_flags))
847 					foll_flags |= FOLL_WRITE;
848 				i = follow_hugetlb_page(mm, vma, pages, vmas,
849 						&start, &nr_pages, i,
850 						foll_flags, nonblocking);
851 				continue;
852 			}
853 		}
854 
855 		if (should_force_cow_break(vma, foll_flags))
856 			foll_flags |= FOLL_WRITE;
857 
858 retry:
859 		/*
860 		 * If we have a pending SIGKILL, don't keep faulting pages and
861 		 * potentially allocating memory.
862 		 */
863 		if (fatal_signal_pending(current)) {
864 			ret = -ERESTARTSYS;
865 			goto out;
866 		}
867 		cond_resched();
868 
869 		page = follow_page_mask(vma, start, foll_flags, &ctx);
870 		if (!page) {
871 			ret = faultin_page(tsk, vma, start, &foll_flags,
872 					nonblocking);
873 			switch (ret) {
874 			case 0:
875 				goto retry;
876 			case -EBUSY:
877 				ret = 0;
878 				/* FALLTHRU */
879 			case -EFAULT:
880 			case -ENOMEM:
881 			case -EHWPOISON:
882 				goto out;
883 			case -ENOENT:
884 				goto next_page;
885 			}
886 			BUG();
887 		} else if (PTR_ERR(page) == -EEXIST) {
888 			/*
889 			 * Proper page table entry exists, but no corresponding
890 			 * struct page.
891 			 */
892 			goto next_page;
893 		} else if (IS_ERR(page)) {
894 			ret = PTR_ERR(page);
895 			goto out;
896 		}
897 		if (pages) {
898 			pages[i] = page;
899 			flush_anon_page(vma, page, start);
900 			flush_dcache_page(page);
901 			ctx.page_mask = 0;
902 		}
903 next_page:
904 		if (vmas) {
905 			vmas[i] = vma;
906 			ctx.page_mask = 0;
907 		}
908 		page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
909 		if (page_increm > nr_pages)
910 			page_increm = nr_pages;
911 		i += page_increm;
912 		start += page_increm * PAGE_SIZE;
913 		nr_pages -= page_increm;
914 	} while (nr_pages);
915 out:
916 	if (ctx.pgmap)
917 		put_dev_pagemap(ctx.pgmap);
918 	return i ? i : ret;
919 }
920 
vma_permits_fault(struct vm_area_struct * vma,unsigned int fault_flags)921 static bool vma_permits_fault(struct vm_area_struct *vma,
922 			      unsigned int fault_flags)
923 {
924 	bool write   = !!(fault_flags & FAULT_FLAG_WRITE);
925 	bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
926 	vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
927 
928 	if (!(vm_flags & vma->vm_flags))
929 		return false;
930 
931 	/*
932 	 * The architecture might have a hardware protection
933 	 * mechanism other than read/write that can deny access.
934 	 *
935 	 * gup always represents data access, not instruction
936 	 * fetches, so execute=false here:
937 	 */
938 	if (!arch_vma_access_permitted(vma, write, false, foreign))
939 		return false;
940 
941 	return true;
942 }
943 
944 /*
945  * fixup_user_fault() - manually resolve a user page fault
946  * @tsk:	the task_struct to use for page fault accounting, or
947  *		NULL if faults are not to be recorded.
948  * @mm:		mm_struct of target mm
949  * @address:	user address
950  * @fault_flags:flags to pass down to handle_mm_fault()
951  * @unlocked:	did we unlock the mmap_sem while retrying, maybe NULL if caller
952  *		does not allow retry
953  *
954  * This is meant to be called in the specific scenario where for locking reasons
955  * we try to access user memory in atomic context (within a pagefault_disable()
956  * section), this returns -EFAULT, and we want to resolve the user fault before
957  * trying again.
958  *
959  * Typically this is meant to be used by the futex code.
960  *
961  * The main difference with get_user_pages() is that this function will
962  * unconditionally call handle_mm_fault() which will in turn perform all the
963  * necessary SW fixup of the dirty and young bits in the PTE, while
964  * get_user_pages() only guarantees to update these in the struct page.
965  *
966  * This is important for some architectures where those bits also gate the
967  * access permission to the page because they are maintained in software.  On
968  * such architectures, gup() will not be enough to make a subsequent access
969  * succeed.
970  *
971  * This function will not return with an unlocked mmap_sem. So it has not the
972  * same semantics wrt the @mm->mmap_sem as does filemap_fault().
973  */
fixup_user_fault(struct task_struct * tsk,struct mm_struct * mm,unsigned long address,unsigned int fault_flags,bool * unlocked)974 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
975 		     unsigned long address, unsigned int fault_flags,
976 		     bool *unlocked)
977 {
978 	struct vm_area_struct *vma;
979 	vm_fault_t ret, major = 0;
980 
981 	address = untagged_addr(address);
982 
983 	if (unlocked)
984 		fault_flags |= FAULT_FLAG_ALLOW_RETRY;
985 
986 retry:
987 	vma = find_extend_vma(mm, address);
988 	if (!vma || address < vma->vm_start)
989 		return -EFAULT;
990 
991 	if (!vma_permits_fault(vma, fault_flags))
992 		return -EFAULT;
993 
994 	ret = handle_mm_fault(vma, address, fault_flags);
995 	major |= ret & VM_FAULT_MAJOR;
996 	if (ret & VM_FAULT_ERROR) {
997 		int err = vm_fault_to_errno(ret, 0);
998 
999 		if (err)
1000 			return err;
1001 		BUG();
1002 	}
1003 
1004 	if (ret & VM_FAULT_RETRY) {
1005 		down_read(&mm->mmap_sem);
1006 		if (!(fault_flags & FAULT_FLAG_TRIED)) {
1007 			*unlocked = true;
1008 			fault_flags &= ~FAULT_FLAG_ALLOW_RETRY;
1009 			fault_flags |= FAULT_FLAG_TRIED;
1010 			goto retry;
1011 		}
1012 	}
1013 
1014 	if (tsk) {
1015 		if (major)
1016 			tsk->maj_flt++;
1017 		else
1018 			tsk->min_flt++;
1019 	}
1020 	return 0;
1021 }
1022 EXPORT_SYMBOL_GPL(fixup_user_fault);
1023 
__get_user_pages_locked(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,struct page ** pages,struct vm_area_struct ** vmas,int * locked,unsigned int flags)1024 static __always_inline long __get_user_pages_locked(struct task_struct *tsk,
1025 						struct mm_struct *mm,
1026 						unsigned long start,
1027 						unsigned long nr_pages,
1028 						struct page **pages,
1029 						struct vm_area_struct **vmas,
1030 						int *locked,
1031 						unsigned int flags)
1032 {
1033 	long ret, pages_done;
1034 	bool lock_dropped;
1035 
1036 	if (locked) {
1037 		/* if VM_FAULT_RETRY can be returned, vmas become invalid */
1038 		BUG_ON(vmas);
1039 		/* check caller initialized locked */
1040 		BUG_ON(*locked != 1);
1041 	}
1042 
1043 	if (pages)
1044 		flags |= FOLL_GET;
1045 
1046 	pages_done = 0;
1047 	lock_dropped = false;
1048 	for (;;) {
1049 		ret = __get_user_pages(tsk, mm, start, nr_pages, flags, pages,
1050 				       vmas, locked);
1051 		if (!locked)
1052 			/* VM_FAULT_RETRY couldn't trigger, bypass */
1053 			return ret;
1054 
1055 		/* VM_FAULT_RETRY cannot return errors */
1056 		if (!*locked) {
1057 			BUG_ON(ret < 0);
1058 			BUG_ON(ret >= nr_pages);
1059 		}
1060 
1061 		if (ret > 0) {
1062 			nr_pages -= ret;
1063 			pages_done += ret;
1064 			if (!nr_pages)
1065 				break;
1066 		}
1067 		if (*locked) {
1068 			/*
1069 			 * VM_FAULT_RETRY didn't trigger or it was a
1070 			 * FOLL_NOWAIT.
1071 			 */
1072 			if (!pages_done)
1073 				pages_done = ret;
1074 			break;
1075 		}
1076 		/*
1077 		 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1078 		 * For the prefault case (!pages) we only update counts.
1079 		 */
1080 		if (likely(pages))
1081 			pages += ret;
1082 		start += ret << PAGE_SHIFT;
1083 
1084 		/*
1085 		 * Repeat on the address that fired VM_FAULT_RETRY
1086 		 * without FAULT_FLAG_ALLOW_RETRY but with
1087 		 * FAULT_FLAG_TRIED.
1088 		 */
1089 		*locked = 1;
1090 		lock_dropped = true;
1091 		down_read(&mm->mmap_sem);
1092 		ret = __get_user_pages(tsk, mm, start, 1, flags | FOLL_TRIED,
1093 				       pages, NULL, NULL);
1094 		if (ret != 1) {
1095 			BUG_ON(ret > 1);
1096 			if (!pages_done)
1097 				pages_done = ret;
1098 			break;
1099 		}
1100 		nr_pages--;
1101 		pages_done++;
1102 		if (!nr_pages)
1103 			break;
1104 		if (likely(pages))
1105 			pages++;
1106 		start += PAGE_SIZE;
1107 	}
1108 	if (lock_dropped && *locked) {
1109 		/*
1110 		 * We must let the caller know we temporarily dropped the lock
1111 		 * and so the critical section protected by it was lost.
1112 		 */
1113 		up_read(&mm->mmap_sem);
1114 		*locked = 0;
1115 	}
1116 	return pages_done;
1117 }
1118 
1119 /*
1120  * get_user_pages_remote() - pin user pages in memory
1121  * @tsk:	the task_struct to use for page fault accounting, or
1122  *		NULL if faults are not to be recorded.
1123  * @mm:		mm_struct of target mm
1124  * @start:	starting user address
1125  * @nr_pages:	number of pages from start to pin
1126  * @gup_flags:	flags modifying lookup behaviour
1127  * @pages:	array that receives pointers to the pages pinned.
1128  *		Should be at least nr_pages long. Or NULL, if caller
1129  *		only intends to ensure the pages are faulted in.
1130  * @vmas:	array of pointers to vmas corresponding to each page.
1131  *		Or NULL if the caller does not require them.
1132  * @locked:	pointer to lock flag indicating whether lock is held and
1133  *		subsequently whether VM_FAULT_RETRY functionality can be
1134  *		utilised. Lock must initially be held.
1135  *
1136  * Returns number of pages pinned. This may be fewer than the number
1137  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1138  * were pinned, returns -errno. Each page returned must be released
1139  * with a put_page() call when it is finished with. vmas will only
1140  * remain valid while mmap_sem is held.
1141  *
1142  * Must be called with mmap_sem held for read or write.
1143  *
1144  * get_user_pages walks a process's page tables and takes a reference to
1145  * each struct page that each user address corresponds to at a given
1146  * instant. That is, it takes the page that would be accessed if a user
1147  * thread accesses the given user virtual address at that instant.
1148  *
1149  * This does not guarantee that the page exists in the user mappings when
1150  * get_user_pages returns, and there may even be a completely different
1151  * page there in some cases (eg. if mmapped pagecache has been invalidated
1152  * and subsequently re faulted). However it does guarantee that the page
1153  * won't be freed completely. And mostly callers simply care that the page
1154  * contains data that was valid *at some point in time*. Typically, an IO
1155  * or similar operation cannot guarantee anything stronger anyway because
1156  * locks can't be held over the syscall boundary.
1157  *
1158  * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1159  * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1160  * be called after the page is finished with, and before put_page is called.
1161  *
1162  * get_user_pages is typically used for fewer-copy IO operations, to get a
1163  * handle on the memory by some means other than accesses via the user virtual
1164  * addresses. The pages may be submitted for DMA to devices or accessed via
1165  * their kernel linear mapping (via the kmap APIs). Care should be taken to
1166  * use the correct cache flushing APIs.
1167  *
1168  * See also get_user_pages_fast, for performance critical applications.
1169  *
1170  * get_user_pages should be phased out in favor of
1171  * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1172  * should use get_user_pages because it cannot pass
1173  * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1174  */
get_user_pages_remote(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,unsigned int gup_flags,struct page ** pages,struct vm_area_struct ** vmas,int * locked)1175 long get_user_pages_remote(struct task_struct *tsk, struct mm_struct *mm,
1176 		unsigned long start, unsigned long nr_pages,
1177 		unsigned int gup_flags, struct page **pages,
1178 		struct vm_area_struct **vmas, int *locked)
1179 {
1180 	/*
1181 	 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1182 	 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1183 	 * vmas.  As there are no users of this flag in this call we simply
1184 	 * disallow this option for now.
1185 	 */
1186 	if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1187 		return -EINVAL;
1188 
1189 	return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
1190 				       locked,
1191 				       gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1192 }
1193 EXPORT_SYMBOL(get_user_pages_remote);
1194 
1195 /**
1196  * populate_vma_page_range() -  populate a range of pages in the vma.
1197  * @vma:   target vma
1198  * @start: start address
1199  * @end:   end address
1200  * @nonblocking:
1201  *
1202  * This takes care of mlocking the pages too if VM_LOCKED is set.
1203  *
1204  * return 0 on success, negative error code on error.
1205  *
1206  * vma->vm_mm->mmap_sem must be held.
1207  *
1208  * If @nonblocking is NULL, it may be held for read or write and will
1209  * be unperturbed.
1210  *
1211  * If @nonblocking is non-NULL, it must held for read only and may be
1212  * released.  If it's released, *@nonblocking will be set to 0.
1213  */
populate_vma_page_range(struct vm_area_struct * vma,unsigned long start,unsigned long end,int * nonblocking)1214 long populate_vma_page_range(struct vm_area_struct *vma,
1215 		unsigned long start, unsigned long end, int *nonblocking)
1216 {
1217 	struct mm_struct *mm = vma->vm_mm;
1218 	unsigned long nr_pages = (end - start) / PAGE_SIZE;
1219 	int gup_flags;
1220 
1221 	VM_BUG_ON(start & ~PAGE_MASK);
1222 	VM_BUG_ON(end   & ~PAGE_MASK);
1223 	VM_BUG_ON_VMA(start < vma->vm_start, vma);
1224 	VM_BUG_ON_VMA(end   > vma->vm_end, vma);
1225 	VM_BUG_ON_MM(!rwsem_is_locked(&mm->mmap_sem), mm);
1226 
1227 	gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1228 	if (vma->vm_flags & VM_LOCKONFAULT)
1229 		gup_flags &= ~FOLL_POPULATE;
1230 	/*
1231 	 * We want to touch writable mappings with a write fault in order
1232 	 * to break COW, except for shared mappings because these don't COW
1233 	 * and we would not want to dirty them for nothing.
1234 	 */
1235 	if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1236 		gup_flags |= FOLL_WRITE;
1237 
1238 	/*
1239 	 * We want mlock to succeed for regions that have any permissions
1240 	 * other than PROT_NONE.
1241 	 */
1242 	if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
1243 		gup_flags |= FOLL_FORCE;
1244 
1245 	/*
1246 	 * We made sure addr is within a VMA, so the following will
1247 	 * not result in a stack expansion that recurses back here.
1248 	 */
1249 	return __get_user_pages(current, mm, start, nr_pages, gup_flags,
1250 				NULL, NULL, nonblocking);
1251 }
1252 
1253 /*
1254  * __mm_populate - populate and/or mlock pages within a range of address space.
1255  *
1256  * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1257  * flags. VMAs must be already marked with the desired vm_flags, and
1258  * mmap_sem must not be held.
1259  */
__mm_populate(unsigned long start,unsigned long len,int ignore_errors)1260 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1261 {
1262 	struct mm_struct *mm = current->mm;
1263 	unsigned long end, nstart, nend;
1264 	struct vm_area_struct *vma = NULL;
1265 	int locked = 0;
1266 	long ret = 0;
1267 
1268 	end = start + len;
1269 
1270 	for (nstart = start; nstart < end; nstart = nend) {
1271 		/*
1272 		 * We want to fault in pages for [nstart; end) address range.
1273 		 * Find first corresponding VMA.
1274 		 */
1275 		if (!locked) {
1276 			locked = 1;
1277 			down_read(&mm->mmap_sem);
1278 			vma = find_vma(mm, nstart);
1279 		} else if (nstart >= vma->vm_end)
1280 			vma = vma->vm_next;
1281 		if (!vma || vma->vm_start >= end)
1282 			break;
1283 		/*
1284 		 * Set [nstart; nend) to intersection of desired address
1285 		 * range with the first VMA. Also, skip undesirable VMA types.
1286 		 */
1287 		nend = min(end, vma->vm_end);
1288 		if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1289 			continue;
1290 		if (nstart < vma->vm_start)
1291 			nstart = vma->vm_start;
1292 		/*
1293 		 * Now fault in a range of pages. populate_vma_page_range()
1294 		 * double checks the vma flags, so that it won't mlock pages
1295 		 * if the vma was already munlocked.
1296 		 */
1297 		ret = populate_vma_page_range(vma, nstart, nend, &locked);
1298 		if (ret < 0) {
1299 			if (ignore_errors) {
1300 				ret = 0;
1301 				continue;	/* continue at next VMA */
1302 			}
1303 			break;
1304 		}
1305 		nend = nstart + ret * PAGE_SIZE;
1306 		ret = 0;
1307 	}
1308 	if (locked)
1309 		up_read(&mm->mmap_sem);
1310 	return ret;	/* 0 or negative error code */
1311 }
1312 
1313 /**
1314  * get_dump_page() - pin user page in memory while writing it to core dump
1315  * @addr: user address
1316  *
1317  * Returns struct page pointer of user page pinned for dump,
1318  * to be freed afterwards by put_page().
1319  *
1320  * Returns NULL on any kind of failure - a hole must then be inserted into
1321  * the corefile, to preserve alignment with its headers; and also returns
1322  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1323  * allowing a hole to be left in the corefile to save diskspace.
1324  *
1325  * Called without mmap_sem, but after all other threads have been killed.
1326  */
1327 #ifdef CONFIG_ELF_CORE
get_dump_page(unsigned long addr)1328 struct page *get_dump_page(unsigned long addr)
1329 {
1330 	struct vm_area_struct *vma;
1331 	struct page *page;
1332 
1333 	if (__get_user_pages(current, current->mm, addr, 1,
1334 			     FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
1335 			     NULL) < 1)
1336 		return NULL;
1337 	flush_cache_page(vma, addr, page_to_pfn(page));
1338 	return page;
1339 }
1340 #endif /* CONFIG_ELF_CORE */
1341 #else /* CONFIG_MMU */
__get_user_pages_locked(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,struct page ** pages,struct vm_area_struct ** vmas,int * locked,unsigned int foll_flags)1342 static long __get_user_pages_locked(struct task_struct *tsk,
1343 		struct mm_struct *mm, unsigned long start,
1344 		unsigned long nr_pages, struct page **pages,
1345 		struct vm_area_struct **vmas, int *locked,
1346 		unsigned int foll_flags)
1347 {
1348 	struct vm_area_struct *vma;
1349 	unsigned long vm_flags;
1350 	int i;
1351 
1352 	/* calculate required read or write permissions.
1353 	 * If FOLL_FORCE is set, we only require the "MAY" flags.
1354 	 */
1355 	vm_flags  = (foll_flags & FOLL_WRITE) ?
1356 			(VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1357 	vm_flags &= (foll_flags & FOLL_FORCE) ?
1358 			(VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1359 
1360 	for (i = 0; i < nr_pages; i++) {
1361 		vma = find_vma(mm, start);
1362 		if (!vma)
1363 			goto finish_or_fault;
1364 
1365 		/* protect what we can, including chardevs */
1366 		if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1367 		    !(vm_flags & vma->vm_flags))
1368 			goto finish_or_fault;
1369 
1370 		if (pages) {
1371 			pages[i] = virt_to_page(start);
1372 			if (pages[i])
1373 				get_page(pages[i]);
1374 		}
1375 		if (vmas)
1376 			vmas[i] = vma;
1377 		start = (start + PAGE_SIZE) & PAGE_MASK;
1378 	}
1379 
1380 	return i;
1381 
1382 finish_or_fault:
1383 	return i ? : -EFAULT;
1384 }
1385 #endif /* !CONFIG_MMU */
1386 
1387 #if defined(CONFIG_FS_DAX) || defined (CONFIG_CMA)
check_dax_vmas(struct vm_area_struct ** vmas,long nr_pages)1388 static bool check_dax_vmas(struct vm_area_struct **vmas, long nr_pages)
1389 {
1390 	long i;
1391 	struct vm_area_struct *vma_prev = NULL;
1392 
1393 	for (i = 0; i < nr_pages; i++) {
1394 		struct vm_area_struct *vma = vmas[i];
1395 
1396 		if (vma == vma_prev)
1397 			continue;
1398 
1399 		vma_prev = vma;
1400 
1401 		if (vma_is_fsdax(vma))
1402 			return true;
1403 	}
1404 	return false;
1405 }
1406 
1407 #ifdef CONFIG_CMA
new_non_cma_page(struct page * page,unsigned long private)1408 static struct page *new_non_cma_page(struct page *page, unsigned long private)
1409 {
1410 	/*
1411 	 * We want to make sure we allocate the new page from the same node
1412 	 * as the source page.
1413 	 */
1414 	int nid = page_to_nid(page);
1415 	/*
1416 	 * Trying to allocate a page for migration. Ignore allocation
1417 	 * failure warnings. We don't force __GFP_THISNODE here because
1418 	 * this node here is the node where we have CMA reservation and
1419 	 * in some case these nodes will have really less non movable
1420 	 * allocation memory.
1421 	 */
1422 	gfp_t gfp_mask = GFP_USER | __GFP_NOWARN;
1423 
1424 	if (PageHighMem(page))
1425 		gfp_mask |= __GFP_HIGHMEM;
1426 
1427 #ifdef CONFIG_HUGETLB_PAGE
1428 	if (PageHuge(page)) {
1429 		struct hstate *h = page_hstate(page);
1430 		/*
1431 		 * We don't want to dequeue from the pool because pool pages will
1432 		 * mostly be from the CMA region.
1433 		 */
1434 		return alloc_migrate_huge_page(h, gfp_mask, nid, NULL);
1435 	}
1436 #endif
1437 	if (PageTransHuge(page)) {
1438 		struct page *thp;
1439 		/*
1440 		 * ignore allocation failure warnings
1441 		 */
1442 		gfp_t thp_gfpmask = GFP_TRANSHUGE | __GFP_NOWARN;
1443 
1444 		/*
1445 		 * Remove the movable mask so that we don't allocate from
1446 		 * CMA area again.
1447 		 */
1448 		thp_gfpmask &= ~__GFP_MOVABLE;
1449 		thp = __alloc_pages_node(nid, thp_gfpmask, HPAGE_PMD_ORDER);
1450 		if (!thp)
1451 			return NULL;
1452 		prep_transhuge_page(thp);
1453 		return thp;
1454 	}
1455 
1456 	return __alloc_pages_node(nid, gfp_mask, 0);
1457 }
1458 
check_and_migrate_cma_pages(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,struct page ** pages,struct vm_area_struct ** vmas,unsigned int gup_flags)1459 static long check_and_migrate_cma_pages(struct task_struct *tsk,
1460 					struct mm_struct *mm,
1461 					unsigned long start,
1462 					unsigned long nr_pages,
1463 					struct page **pages,
1464 					struct vm_area_struct **vmas,
1465 					unsigned int gup_flags)
1466 {
1467 	unsigned long i;
1468 	unsigned long step;
1469 	bool drain_allow = true;
1470 	bool migrate_allow = true;
1471 	LIST_HEAD(cma_page_list);
1472 
1473 check_again:
1474 	for (i = 0; i < nr_pages;) {
1475 
1476 		struct page *head = compound_head(pages[i]);
1477 
1478 		/*
1479 		 * gup may start from a tail page. Advance step by the left
1480 		 * part.
1481 		 */
1482 		step = compound_nr(head) - (pages[i] - head);
1483 		/*
1484 		 * If we get a page from the CMA zone, since we are going to
1485 		 * be pinning these entries, we might as well move them out
1486 		 * of the CMA zone if possible.
1487 		 */
1488 		if (is_migrate_cma_page(head)) {
1489 			if (PageHuge(head))
1490 				isolate_huge_page(head, &cma_page_list);
1491 			else {
1492 				if (!PageLRU(head) && drain_allow) {
1493 					lru_add_drain_all();
1494 					drain_allow = false;
1495 				}
1496 
1497 				if (!isolate_lru_page(head)) {
1498 					list_add_tail(&head->lru, &cma_page_list);
1499 					mod_node_page_state(page_pgdat(head),
1500 							    NR_ISOLATED_ANON +
1501 							    page_is_file_cache(head),
1502 							    hpage_nr_pages(head));
1503 				}
1504 			}
1505 		}
1506 
1507 		i += step;
1508 	}
1509 
1510 	if (!list_empty(&cma_page_list)) {
1511 		/*
1512 		 * drop the above get_user_pages reference.
1513 		 */
1514 		for (i = 0; i < nr_pages; i++)
1515 			put_page(pages[i]);
1516 
1517 		if (migrate_pages(&cma_page_list, new_non_cma_page,
1518 				  NULL, 0, MIGRATE_SYNC, MR_CONTIG_RANGE)) {
1519 			/*
1520 			 * some of the pages failed migration. Do get_user_pages
1521 			 * without migration.
1522 			 */
1523 			migrate_allow = false;
1524 
1525 			if (!list_empty(&cma_page_list))
1526 				putback_movable_pages(&cma_page_list);
1527 		}
1528 		/*
1529 		 * We did migrate all the pages, Try to get the page references
1530 		 * again migrating any new CMA pages which we failed to isolate
1531 		 * earlier.
1532 		 */
1533 		nr_pages = __get_user_pages_locked(tsk, mm, start, nr_pages,
1534 						   pages, vmas, NULL,
1535 						   gup_flags);
1536 
1537 		if ((nr_pages > 0) && migrate_allow) {
1538 			drain_allow = true;
1539 			goto check_again;
1540 		}
1541 	}
1542 
1543 	return nr_pages;
1544 }
1545 #else
check_and_migrate_cma_pages(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,struct page ** pages,struct vm_area_struct ** vmas,unsigned int gup_flags)1546 static long check_and_migrate_cma_pages(struct task_struct *tsk,
1547 					struct mm_struct *mm,
1548 					unsigned long start,
1549 					unsigned long nr_pages,
1550 					struct page **pages,
1551 					struct vm_area_struct **vmas,
1552 					unsigned int gup_flags)
1553 {
1554 	return nr_pages;
1555 }
1556 #endif /* CONFIG_CMA */
1557 
1558 /*
1559  * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1560  * allows us to process the FOLL_LONGTERM flag.
1561  */
__gup_longterm_locked(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,struct page ** pages,struct vm_area_struct ** vmas,unsigned int gup_flags)1562 static long __gup_longterm_locked(struct task_struct *tsk,
1563 				  struct mm_struct *mm,
1564 				  unsigned long start,
1565 				  unsigned long nr_pages,
1566 				  struct page **pages,
1567 				  struct vm_area_struct **vmas,
1568 				  unsigned int gup_flags)
1569 {
1570 	struct vm_area_struct **vmas_tmp = vmas;
1571 	unsigned long flags = 0;
1572 	long rc, i;
1573 
1574 	if (gup_flags & FOLL_LONGTERM) {
1575 		if (!pages)
1576 			return -EINVAL;
1577 
1578 		if (!vmas_tmp) {
1579 			vmas_tmp = kcalloc(nr_pages,
1580 					   sizeof(struct vm_area_struct *),
1581 					   GFP_KERNEL);
1582 			if (!vmas_tmp)
1583 				return -ENOMEM;
1584 		}
1585 		flags = memalloc_nocma_save();
1586 	}
1587 
1588 	rc = __get_user_pages_locked(tsk, mm, start, nr_pages, pages,
1589 				     vmas_tmp, NULL, gup_flags);
1590 
1591 	if (gup_flags & FOLL_LONGTERM) {
1592 		memalloc_nocma_restore(flags);
1593 		if (rc < 0)
1594 			goto out;
1595 
1596 		if (check_dax_vmas(vmas_tmp, rc)) {
1597 			for (i = 0; i < rc; i++)
1598 				put_page(pages[i]);
1599 			rc = -EOPNOTSUPP;
1600 			goto out;
1601 		}
1602 
1603 		rc = check_and_migrate_cma_pages(tsk, mm, start, rc, pages,
1604 						 vmas_tmp, gup_flags);
1605 	}
1606 
1607 out:
1608 	if (vmas_tmp != vmas)
1609 		kfree(vmas_tmp);
1610 	return rc;
1611 }
1612 #else /* !CONFIG_FS_DAX && !CONFIG_CMA */
__gup_longterm_locked(struct task_struct * tsk,struct mm_struct * mm,unsigned long start,unsigned long nr_pages,struct page ** pages,struct vm_area_struct ** vmas,unsigned int flags)1613 static __always_inline long __gup_longterm_locked(struct task_struct *tsk,
1614 						  struct mm_struct *mm,
1615 						  unsigned long start,
1616 						  unsigned long nr_pages,
1617 						  struct page **pages,
1618 						  struct vm_area_struct **vmas,
1619 						  unsigned int flags)
1620 {
1621 	return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
1622 				       NULL, flags);
1623 }
1624 #endif /* CONFIG_FS_DAX || CONFIG_CMA */
1625 
1626 /*
1627  * This is the same as get_user_pages_remote(), just with a
1628  * less-flexible calling convention where we assume that the task
1629  * and mm being operated on are the current task's and don't allow
1630  * passing of a locked parameter.  We also obviously don't pass
1631  * FOLL_REMOTE in here.
1632  */
get_user_pages(unsigned long start,unsigned long nr_pages,unsigned int gup_flags,struct page ** pages,struct vm_area_struct ** vmas)1633 long get_user_pages(unsigned long start, unsigned long nr_pages,
1634 		unsigned int gup_flags, struct page **pages,
1635 		struct vm_area_struct **vmas)
1636 {
1637 	return __gup_longterm_locked(current, current->mm, start, nr_pages,
1638 				     pages, vmas, gup_flags | FOLL_TOUCH);
1639 }
1640 EXPORT_SYMBOL(get_user_pages);
1641 
1642 /*
1643  * We can leverage the VM_FAULT_RETRY functionality in the page fault
1644  * paths better by using either get_user_pages_locked() or
1645  * get_user_pages_unlocked().
1646  *
1647  * get_user_pages_locked() is suitable to replace the form:
1648  *
1649  *      down_read(&mm->mmap_sem);
1650  *      do_something()
1651  *      get_user_pages(tsk, mm, ..., pages, NULL);
1652  *      up_read(&mm->mmap_sem);
1653  *
1654  *  to:
1655  *
1656  *      int locked = 1;
1657  *      down_read(&mm->mmap_sem);
1658  *      do_something()
1659  *      get_user_pages_locked(tsk, mm, ..., pages, &locked);
1660  *      if (locked)
1661  *          up_read(&mm->mmap_sem);
1662  */
get_user_pages_locked(unsigned long start,unsigned long nr_pages,unsigned int gup_flags,struct page ** pages,int * locked)1663 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1664 			   unsigned int gup_flags, struct page **pages,
1665 			   int *locked)
1666 {
1667 	/*
1668 	 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1669 	 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1670 	 * vmas.  As there are no users of this flag in this call we simply
1671 	 * disallow this option for now.
1672 	 */
1673 	if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1674 		return -EINVAL;
1675 
1676 	return __get_user_pages_locked(current, current->mm, start, nr_pages,
1677 				       pages, NULL, locked,
1678 				       gup_flags | FOLL_TOUCH);
1679 }
1680 EXPORT_SYMBOL(get_user_pages_locked);
1681 
1682 /*
1683  * get_user_pages_unlocked() is suitable to replace the form:
1684  *
1685  *      down_read(&mm->mmap_sem);
1686  *      get_user_pages(tsk, mm, ..., pages, NULL);
1687  *      up_read(&mm->mmap_sem);
1688  *
1689  *  with:
1690  *
1691  *      get_user_pages_unlocked(tsk, mm, ..., pages);
1692  *
1693  * It is functionally equivalent to get_user_pages_fast so
1694  * get_user_pages_fast should be used instead if specific gup_flags
1695  * (e.g. FOLL_FORCE) are not required.
1696  */
get_user_pages_unlocked(unsigned long start,unsigned long nr_pages,struct page ** pages,unsigned int gup_flags)1697 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
1698 			     struct page **pages, unsigned int gup_flags)
1699 {
1700 	struct mm_struct *mm = current->mm;
1701 	int locked = 1;
1702 	long ret;
1703 
1704 	/*
1705 	 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1706 	 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1707 	 * vmas.  As there are no users of this flag in this call we simply
1708 	 * disallow this option for now.
1709 	 */
1710 	if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1711 		return -EINVAL;
1712 
1713 	down_read(&mm->mmap_sem);
1714 	ret = __get_user_pages_locked(current, mm, start, nr_pages, pages, NULL,
1715 				      &locked, gup_flags | FOLL_TOUCH);
1716 	if (locked)
1717 		up_read(&mm->mmap_sem);
1718 	return ret;
1719 }
1720 EXPORT_SYMBOL(get_user_pages_unlocked);
1721 
1722 /*
1723  * Fast GUP
1724  *
1725  * get_user_pages_fast attempts to pin user pages by walking the page
1726  * tables directly and avoids taking locks. Thus the walker needs to be
1727  * protected from page table pages being freed from under it, and should
1728  * block any THP splits.
1729  *
1730  * One way to achieve this is to have the walker disable interrupts, and
1731  * rely on IPIs from the TLB flushing code blocking before the page table
1732  * pages are freed. This is unsuitable for architectures that do not need
1733  * to broadcast an IPI when invalidating TLBs.
1734  *
1735  * Another way to achieve this is to batch up page table containing pages
1736  * belonging to more than one mm_user, then rcu_sched a callback to free those
1737  * pages. Disabling interrupts will allow the fast_gup walker to both block
1738  * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
1739  * (which is a relatively rare event). The code below adopts this strategy.
1740  *
1741  * Before activating this code, please be aware that the following assumptions
1742  * are currently made:
1743  *
1744  *  *) Either HAVE_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
1745  *  free pages containing page tables or TLB flushing requires IPI broadcast.
1746  *
1747  *  *) ptes can be read atomically by the architecture.
1748  *
1749  *  *) access_ok is sufficient to validate userspace address ranges.
1750  *
1751  * The last two assumptions can be relaxed by the addition of helper functions.
1752  *
1753  * This code is based heavily on the PowerPC implementation by Nick Piggin.
1754  */
1755 #ifdef CONFIG_HAVE_FAST_GUP
1756 #ifdef CONFIG_GUP_GET_PTE_LOW_HIGH
1757 /*
1758  * WARNING: only to be used in the get_user_pages_fast() implementation.
1759  *
1760  * With get_user_pages_fast(), we walk down the pagetables without taking any
1761  * locks.  For this we would like to load the pointers atomically, but sometimes
1762  * that is not possible (e.g. without expensive cmpxchg8b on x86_32 PAE).  What
1763  * we do have is the guarantee that a PTE will only either go from not present
1764  * to present, or present to not present or both -- it will not switch to a
1765  * completely different present page without a TLB flush in between; something
1766  * that we are blocking by holding interrupts off.
1767  *
1768  * Setting ptes from not present to present goes:
1769  *
1770  *   ptep->pte_high = h;
1771  *   smp_wmb();
1772  *   ptep->pte_low = l;
1773  *
1774  * And present to not present goes:
1775  *
1776  *   ptep->pte_low = 0;
1777  *   smp_wmb();
1778  *   ptep->pte_high = 0;
1779  *
1780  * We must ensure here that the load of pte_low sees 'l' IFF pte_high sees 'h'.
1781  * We load pte_high *after* loading pte_low, which ensures we don't see an older
1782  * value of pte_high.  *Then* we recheck pte_low, which ensures that we haven't
1783  * picked up a changed pte high. We might have gotten rubbish values from
1784  * pte_low and pte_high, but we are guaranteed that pte_low will not have the
1785  * present bit set *unless* it is 'l'. Because get_user_pages_fast() only
1786  * operates on present ptes we're safe.
1787  */
gup_get_pte(pte_t * ptep)1788 static inline pte_t gup_get_pte(pte_t *ptep)
1789 {
1790 	pte_t pte;
1791 
1792 	do {
1793 		pte.pte_low = ptep->pte_low;
1794 		smp_rmb();
1795 		pte.pte_high = ptep->pte_high;
1796 		smp_rmb();
1797 	} while (unlikely(pte.pte_low != ptep->pte_low));
1798 
1799 	return pte;
1800 }
1801 #else /* CONFIG_GUP_GET_PTE_LOW_HIGH */
1802 /*
1803  * We require that the PTE can be read atomically.
1804  */
gup_get_pte(pte_t * ptep)1805 static inline pte_t gup_get_pte(pte_t *ptep)
1806 {
1807 	return READ_ONCE(*ptep);
1808 }
1809 #endif /* CONFIG_GUP_GET_PTE_LOW_HIGH */
1810 
undo_dev_pagemap(int * nr,int nr_start,struct page ** pages)1811 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
1812 					    struct page **pages)
1813 {
1814 	while ((*nr) - nr_start) {
1815 		struct page *page = pages[--(*nr)];
1816 
1817 		ClearPageReferenced(page);
1818 		put_page(page);
1819 	}
1820 }
1821 
1822 /*
1823  * Return the compund head page with ref appropriately incremented,
1824  * or NULL if that failed.
1825  */
try_get_compound_head(struct page * page,int refs)1826 static inline struct page *try_get_compound_head(struct page *page, int refs)
1827 {
1828 	struct page *head = compound_head(page);
1829 	if (WARN_ON_ONCE(page_ref_count(head) < 0))
1830 		return NULL;
1831 	if (unlikely(!page_cache_add_speculative(head, refs)))
1832 		return NULL;
1833 	return head;
1834 }
1835 
1836 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
gup_pte_range(pmd_t pmd,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)1837 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1838 			 unsigned int flags, struct page **pages, int *nr)
1839 {
1840 	struct dev_pagemap *pgmap = NULL;
1841 	int nr_start = *nr, ret = 0;
1842 	pte_t *ptep, *ptem;
1843 
1844 	ptem = ptep = pte_offset_map(&pmd, addr);
1845 	do {
1846 		pte_t pte = gup_get_pte(ptep);
1847 		struct page *head, *page;
1848 
1849 		/*
1850 		 * Similar to the PMD case below, NUMA hinting must take slow
1851 		 * path using the pte_protnone check.
1852 		 */
1853 		if (pte_protnone(pte))
1854 			goto pte_unmap;
1855 
1856 		if (!pte_access_permitted(pte, flags & FOLL_WRITE))
1857 			goto pte_unmap;
1858 
1859 		if (pte_devmap(pte)) {
1860 			if (unlikely(flags & FOLL_LONGTERM))
1861 				goto pte_unmap;
1862 
1863 			pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
1864 			if (unlikely(!pgmap)) {
1865 				undo_dev_pagemap(nr, nr_start, pages);
1866 				goto pte_unmap;
1867 			}
1868 		} else if (pte_special(pte))
1869 			goto pte_unmap;
1870 
1871 		VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
1872 		page = pte_page(pte);
1873 
1874 		head = try_get_compound_head(page, 1);
1875 		if (!head)
1876 			goto pte_unmap;
1877 
1878 		if (unlikely(pte_val(pte) != pte_val(*ptep))) {
1879 			put_page(head);
1880 			goto pte_unmap;
1881 		}
1882 
1883 		VM_BUG_ON_PAGE(compound_head(page) != head, page);
1884 
1885 		SetPageReferenced(page);
1886 		pages[*nr] = page;
1887 		(*nr)++;
1888 
1889 	} while (ptep++, addr += PAGE_SIZE, addr != end);
1890 
1891 	ret = 1;
1892 
1893 pte_unmap:
1894 	if (pgmap)
1895 		put_dev_pagemap(pgmap);
1896 	pte_unmap(ptem);
1897 	return ret;
1898 }
1899 #else
1900 
1901 /*
1902  * If we can't determine whether or not a pte is special, then fail immediately
1903  * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
1904  * to be special.
1905  *
1906  * For a futex to be placed on a THP tail page, get_futex_key requires a
1907  * __get_user_pages_fast implementation that can pin pages. Thus it's still
1908  * useful to have gup_huge_pmd even if we can't operate on ptes.
1909  */
gup_pte_range(pmd_t pmd,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)1910 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1911 			 unsigned int flags, struct page **pages, int *nr)
1912 {
1913 	return 0;
1914 }
1915 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
1916 
1917 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
__gup_device_huge(unsigned long pfn,unsigned long addr,unsigned long end,struct page ** pages,int * nr)1918 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
1919 		unsigned long end, struct page **pages, int *nr)
1920 {
1921 	int nr_start = *nr;
1922 	struct dev_pagemap *pgmap = NULL;
1923 
1924 	do {
1925 		struct page *page = pfn_to_page(pfn);
1926 
1927 		pgmap = get_dev_pagemap(pfn, pgmap);
1928 		if (unlikely(!pgmap)) {
1929 			undo_dev_pagemap(nr, nr_start, pages);
1930 			return 0;
1931 		}
1932 		SetPageReferenced(page);
1933 		pages[*nr] = page;
1934 		get_page(page);
1935 		(*nr)++;
1936 		pfn++;
1937 	} while (addr += PAGE_SIZE, addr != end);
1938 
1939 	if (pgmap)
1940 		put_dev_pagemap(pgmap);
1941 	return 1;
1942 }
1943 
__gup_device_huge_pmd(pmd_t orig,pmd_t * pmdp,unsigned long addr,unsigned long end,struct page ** pages,int * nr)1944 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1945 		unsigned long end, struct page **pages, int *nr)
1946 {
1947 	unsigned long fault_pfn;
1948 	int nr_start = *nr;
1949 
1950 	fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
1951 	if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1952 		return 0;
1953 
1954 	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1955 		undo_dev_pagemap(nr, nr_start, pages);
1956 		return 0;
1957 	}
1958 	return 1;
1959 }
1960 
__gup_device_huge_pud(pud_t orig,pud_t * pudp,unsigned long addr,unsigned long end,struct page ** pages,int * nr)1961 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
1962 		unsigned long end, struct page **pages, int *nr)
1963 {
1964 	unsigned long fault_pfn;
1965 	int nr_start = *nr;
1966 
1967 	fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
1968 	if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1969 		return 0;
1970 
1971 	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1972 		undo_dev_pagemap(nr, nr_start, pages);
1973 		return 0;
1974 	}
1975 	return 1;
1976 }
1977 #else
__gup_device_huge_pmd(pmd_t orig,pmd_t * pmdp,unsigned long addr,unsigned long end,struct page ** pages,int * nr)1978 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1979 		unsigned long end, struct page **pages, int *nr)
1980 {
1981 	BUILD_BUG();
1982 	return 0;
1983 }
1984 
__gup_device_huge_pud(pud_t pud,pud_t * pudp,unsigned long addr,unsigned long end,struct page ** pages,int * nr)1985 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
1986 		unsigned long end, struct page **pages, int *nr)
1987 {
1988 	BUILD_BUG();
1989 	return 0;
1990 }
1991 #endif
1992 
1993 #ifdef CONFIG_ARCH_HAS_HUGEPD
hugepte_addr_end(unsigned long addr,unsigned long end,unsigned long sz)1994 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
1995 				      unsigned long sz)
1996 {
1997 	unsigned long __boundary = (addr + sz) & ~(sz-1);
1998 	return (__boundary - 1 < end - 1) ? __boundary : end;
1999 }
2000 
gup_hugepte(pte_t * ptep,unsigned long sz,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2001 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2002 		       unsigned long end, unsigned int flags,
2003 		       struct page **pages, int *nr)
2004 {
2005 	unsigned long pte_end;
2006 	struct page *head, *page;
2007 	pte_t pte;
2008 	int refs;
2009 
2010 	pte_end = (addr + sz) & ~(sz-1);
2011 	if (pte_end < end)
2012 		end = pte_end;
2013 
2014 	pte = READ_ONCE(*ptep);
2015 
2016 	if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2017 		return 0;
2018 
2019 	/* hugepages are never "special" */
2020 	VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2021 
2022 	refs = 0;
2023 	head = pte_page(pte);
2024 
2025 	page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2026 	do {
2027 		VM_BUG_ON(compound_head(page) != head);
2028 		pages[*nr] = page;
2029 		(*nr)++;
2030 		page++;
2031 		refs++;
2032 	} while (addr += PAGE_SIZE, addr != end);
2033 
2034 	head = try_get_compound_head(head, refs);
2035 	if (!head) {
2036 		*nr -= refs;
2037 		return 0;
2038 	}
2039 
2040 	if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2041 		/* Could be optimized better */
2042 		*nr -= refs;
2043 		while (refs--)
2044 			put_page(head);
2045 		return 0;
2046 	}
2047 
2048 	SetPageReferenced(head);
2049 	return 1;
2050 }
2051 
gup_huge_pd(hugepd_t hugepd,unsigned long addr,unsigned int pdshift,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2052 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2053 		unsigned int pdshift, unsigned long end, unsigned int flags,
2054 		struct page **pages, int *nr)
2055 {
2056 	pte_t *ptep;
2057 	unsigned long sz = 1UL << hugepd_shift(hugepd);
2058 	unsigned long next;
2059 
2060 	ptep = hugepte_offset(hugepd, addr, pdshift);
2061 	do {
2062 		next = hugepte_addr_end(addr, end, sz);
2063 		if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2064 			return 0;
2065 	} while (ptep++, addr = next, addr != end);
2066 
2067 	return 1;
2068 }
2069 #else
gup_huge_pd(hugepd_t hugepd,unsigned long addr,unsigned int pdshift,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2070 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2071 		unsigned int pdshift, unsigned long end, unsigned int flags,
2072 		struct page **pages, int *nr)
2073 {
2074 	return 0;
2075 }
2076 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2077 
gup_huge_pmd(pmd_t orig,pmd_t * pmdp,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2078 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2079 			unsigned long end, unsigned int flags,
2080 			struct page **pages, int *nr)
2081 {
2082 	struct page *head, *page;
2083 	int refs;
2084 
2085 	if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2086 		return 0;
2087 
2088 	if (pmd_devmap(orig)) {
2089 		if (unlikely(flags & FOLL_LONGTERM))
2090 			return 0;
2091 		return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
2092 	}
2093 
2094 	refs = 0;
2095 	page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2096 	do {
2097 		pages[*nr] = page;
2098 		(*nr)++;
2099 		page++;
2100 		refs++;
2101 	} while (addr += PAGE_SIZE, addr != end);
2102 
2103 	head = try_get_compound_head(pmd_page(orig), refs);
2104 	if (!head) {
2105 		*nr -= refs;
2106 		return 0;
2107 	}
2108 
2109 	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2110 		*nr -= refs;
2111 		while (refs--)
2112 			put_page(head);
2113 		return 0;
2114 	}
2115 
2116 	SetPageReferenced(head);
2117 	return 1;
2118 }
2119 
gup_huge_pud(pud_t orig,pud_t * pudp,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2120 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2121 		unsigned long end, unsigned int flags, struct page **pages, int *nr)
2122 {
2123 	struct page *head, *page;
2124 	int refs;
2125 
2126 	if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2127 		return 0;
2128 
2129 	if (pud_devmap(orig)) {
2130 		if (unlikely(flags & FOLL_LONGTERM))
2131 			return 0;
2132 		return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
2133 	}
2134 
2135 	refs = 0;
2136 	page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2137 	do {
2138 		pages[*nr] = page;
2139 		(*nr)++;
2140 		page++;
2141 		refs++;
2142 	} while (addr += PAGE_SIZE, addr != end);
2143 
2144 	head = try_get_compound_head(pud_page(orig), refs);
2145 	if (!head) {
2146 		*nr -= refs;
2147 		return 0;
2148 	}
2149 
2150 	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2151 		*nr -= refs;
2152 		while (refs--)
2153 			put_page(head);
2154 		return 0;
2155 	}
2156 
2157 	SetPageReferenced(head);
2158 	return 1;
2159 }
2160 
gup_huge_pgd(pgd_t orig,pgd_t * pgdp,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2161 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2162 			unsigned long end, unsigned int flags,
2163 			struct page **pages, int *nr)
2164 {
2165 	int refs;
2166 	struct page *head, *page;
2167 
2168 	if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2169 		return 0;
2170 
2171 	BUILD_BUG_ON(pgd_devmap(orig));
2172 	refs = 0;
2173 	page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2174 	do {
2175 		pages[*nr] = page;
2176 		(*nr)++;
2177 		page++;
2178 		refs++;
2179 	} while (addr += PAGE_SIZE, addr != end);
2180 
2181 	head = try_get_compound_head(pgd_page(orig), refs);
2182 	if (!head) {
2183 		*nr -= refs;
2184 		return 0;
2185 	}
2186 
2187 	if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2188 		*nr -= refs;
2189 		while (refs--)
2190 			put_page(head);
2191 		return 0;
2192 	}
2193 
2194 	SetPageReferenced(head);
2195 	return 1;
2196 }
2197 
gup_pmd_range(pud_t * pudp,pud_t pud,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2198 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2199 		unsigned int flags, struct page **pages, int *nr)
2200 {
2201 	unsigned long next;
2202 	pmd_t *pmdp;
2203 
2204 	pmdp = pmd_offset_lockless(pudp, pud, addr);
2205 	do {
2206 		pmd_t pmd = READ_ONCE(*pmdp);
2207 
2208 		next = pmd_addr_end(addr, end);
2209 		if (!pmd_present(pmd))
2210 			return 0;
2211 
2212 		if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2213 			     pmd_devmap(pmd))) {
2214 			/*
2215 			 * NUMA hinting faults need to be handled in the GUP
2216 			 * slowpath for accounting purposes and so that they
2217 			 * can be serialised against THP migration.
2218 			 */
2219 			if (pmd_protnone(pmd))
2220 				return 0;
2221 
2222 			if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2223 				pages, nr))
2224 				return 0;
2225 
2226 		} else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2227 			/*
2228 			 * architecture have different format for hugetlbfs
2229 			 * pmd format and THP pmd format
2230 			 */
2231 			if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2232 					 PMD_SHIFT, next, flags, pages, nr))
2233 				return 0;
2234 		} else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2235 			return 0;
2236 	} while (pmdp++, addr = next, addr != end);
2237 
2238 	return 1;
2239 }
2240 
gup_pud_range(p4d_t * p4dp,p4d_t p4d,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2241 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2242 			 unsigned int flags, struct page **pages, int *nr)
2243 {
2244 	unsigned long next;
2245 	pud_t *pudp;
2246 
2247 	pudp = pud_offset_lockless(p4dp, p4d, addr);
2248 	do {
2249 		pud_t pud = READ_ONCE(*pudp);
2250 
2251 		next = pud_addr_end(addr, end);
2252 		if (pud_none(pud))
2253 			return 0;
2254 		if (unlikely(pud_huge(pud) || pud_devmap(pud))) {
2255 			if (!gup_huge_pud(pud, pudp, addr, next, flags,
2256 					  pages, nr))
2257 				return 0;
2258 		} else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2259 			if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2260 					 PUD_SHIFT, next, flags, pages, nr))
2261 				return 0;
2262 		} else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2263 			return 0;
2264 	} while (pudp++, addr = next, addr != end);
2265 
2266 	return 1;
2267 }
2268 
gup_p4d_range(pgd_t * pgdp,pgd_t pgd,unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2269 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2270 			 unsigned int flags, struct page **pages, int *nr)
2271 {
2272 	unsigned long next;
2273 	p4d_t *p4dp;
2274 
2275 	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2276 	do {
2277 		p4d_t p4d = READ_ONCE(*p4dp);
2278 
2279 		next = p4d_addr_end(addr, end);
2280 		if (p4d_none(p4d))
2281 			return 0;
2282 		BUILD_BUG_ON(p4d_huge(p4d));
2283 		if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2284 			if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2285 					 P4D_SHIFT, next, flags, pages, nr))
2286 				return 0;
2287 		} else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2288 			return 0;
2289 	} while (p4dp++, addr = next, addr != end);
2290 
2291 	return 1;
2292 }
2293 
gup_pgd_range(unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2294 static void gup_pgd_range(unsigned long addr, unsigned long end,
2295 		unsigned int flags, struct page **pages, int *nr)
2296 {
2297 	unsigned long next;
2298 	pgd_t *pgdp;
2299 
2300 	pgdp = pgd_offset(current->mm, addr);
2301 	do {
2302 		pgd_t pgd = READ_ONCE(*pgdp);
2303 
2304 		next = pgd_addr_end(addr, end);
2305 		if (pgd_none(pgd))
2306 			return;
2307 		if (unlikely(pgd_huge(pgd))) {
2308 			if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2309 					  pages, nr))
2310 				return;
2311 		} else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2312 			if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2313 					 PGDIR_SHIFT, next, flags, pages, nr))
2314 				return;
2315 		} else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2316 			return;
2317 	} while (pgdp++, addr = next, addr != end);
2318 }
2319 #else
gup_pgd_range(unsigned long addr,unsigned long end,unsigned int flags,struct page ** pages,int * nr)2320 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2321 		unsigned int flags, struct page **pages, int *nr)
2322 {
2323 }
2324 #endif /* CONFIG_HAVE_FAST_GUP */
2325 
2326 #ifndef gup_fast_permitted
2327 /*
2328  * Check if it's allowed to use __get_user_pages_fast() for the range, or
2329  * we need to fall back to the slow version:
2330  */
gup_fast_permitted(unsigned long start,unsigned long end)2331 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2332 {
2333 	return true;
2334 }
2335 #endif
2336 
2337 /*
2338  * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2339  * the regular GUP.
2340  * Note a difference with get_user_pages_fast: this always returns the
2341  * number of pages pinned, 0 if no pages were pinned.
2342  *
2343  * If the architecture does not support this function, simply return with no
2344  * pages pinned.
2345  *
2346  * Careful, careful! COW breaking can go either way, so a non-write
2347  * access can get ambiguous page results. If you call this function without
2348  * 'write' set, you'd better be sure that you're ok with that ambiguity.
2349  */
__get_user_pages_fast(unsigned long start,int nr_pages,int write,struct page ** pages)2350 int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
2351 			  struct page **pages)
2352 {
2353 	unsigned long len, end;
2354 	unsigned long flags;
2355 	int nr = 0;
2356 
2357 	start = untagged_addr(start) & PAGE_MASK;
2358 	len = (unsigned long) nr_pages << PAGE_SHIFT;
2359 	end = start + len;
2360 
2361 	if (end <= start)
2362 		return 0;
2363 	if (unlikely(!access_ok((void __user *)start, len)))
2364 		return 0;
2365 
2366 	/*
2367 	 * Disable interrupts.  We use the nested form as we can already have
2368 	 * interrupts disabled by get_futex_key.
2369 	 *
2370 	 * With interrupts disabled, we block page table pages from being
2371 	 * freed from under us. See struct mmu_table_batch comments in
2372 	 * include/asm-generic/tlb.h for more details.
2373 	 *
2374 	 * We do not adopt an rcu_read_lock(.) here as we also want to
2375 	 * block IPIs that come from THPs splitting.
2376 	 *
2377 	 * NOTE! We allow read-only gup_fast() here, but you'd better be
2378 	 * careful about possible COW pages. You'll get _a_ COW page, but
2379 	 * not necessarily the one you intended to get depending on what
2380 	 * COW event happens after this. COW may break the page copy in a
2381 	 * random direction.
2382 	 */
2383 
2384 	if (IS_ENABLED(CONFIG_HAVE_FAST_GUP) &&
2385 	    gup_fast_permitted(start, end)) {
2386 		local_irq_save(flags);
2387 		gup_pgd_range(start, end, write ? FOLL_WRITE : 0, pages, &nr);
2388 		local_irq_restore(flags);
2389 	}
2390 
2391 	return nr;
2392 }
2393 EXPORT_SYMBOL_GPL(__get_user_pages_fast);
2394 
__gup_longterm_unlocked(unsigned long start,int nr_pages,unsigned int gup_flags,struct page ** pages)2395 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2396 				   unsigned int gup_flags, struct page **pages)
2397 {
2398 	int ret;
2399 
2400 	/*
2401 	 * FIXME: FOLL_LONGTERM does not work with
2402 	 * get_user_pages_unlocked() (see comments in that function)
2403 	 */
2404 	if (gup_flags & FOLL_LONGTERM) {
2405 		down_read(&current->mm->mmap_sem);
2406 		ret = __gup_longterm_locked(current, current->mm,
2407 					    start, nr_pages,
2408 					    pages, NULL, gup_flags);
2409 		up_read(&current->mm->mmap_sem);
2410 	} else {
2411 		ret = get_user_pages_unlocked(start, nr_pages,
2412 					      pages, gup_flags);
2413 	}
2414 
2415 	return ret;
2416 }
2417 
2418 /**
2419  * get_user_pages_fast() - pin user pages in memory
2420  * @start:	starting user address
2421  * @nr_pages:	number of pages from start to pin
2422  * @gup_flags:	flags modifying pin behaviour
2423  * @pages:	array that receives pointers to the pages pinned.
2424  *		Should be at least nr_pages long.
2425  *
2426  * Attempt to pin user pages in memory without taking mm->mmap_sem.
2427  * If not successful, it will fall back to taking the lock and
2428  * calling get_user_pages().
2429  *
2430  * Returns number of pages pinned. This may be fewer than the number
2431  * requested. If nr_pages is 0 or negative, returns 0. If no pages
2432  * were pinned, returns -errno.
2433  */
get_user_pages_fast(unsigned long start,int nr_pages,unsigned int gup_flags,struct page ** pages)2434 int get_user_pages_fast(unsigned long start, int nr_pages,
2435 			unsigned int gup_flags, struct page **pages)
2436 {
2437 	unsigned long addr, len, end;
2438 	int nr = 0, ret = 0;
2439 
2440 	if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2441 				       FOLL_FORCE)))
2442 		return -EINVAL;
2443 
2444 	start = untagged_addr(start) & PAGE_MASK;
2445 	addr = start;
2446 	len = (unsigned long) nr_pages << PAGE_SHIFT;
2447 	end = start + len;
2448 
2449 	if (end <= start)
2450 		return 0;
2451 	if (unlikely(!access_ok((void __user *)start, len)))
2452 		return -EFAULT;
2453 
2454 	/*
2455 	 * The FAST_GUP case requires FOLL_WRITE even for pure reads,
2456 	 * because get_user_pages() may need to cause an early COW in
2457 	 * order to avoid confusing the normal COW routines. So only
2458 	 * targets that are already writable are safe to do by just
2459 	 * looking at the page tables.
2460 	 */
2461 	if (IS_ENABLED(CONFIG_HAVE_FAST_GUP) &&
2462 	    gup_fast_permitted(start, end)) {
2463 		local_irq_disable();
2464 		gup_pgd_range(addr, end, gup_flags | FOLL_WRITE, pages, &nr);
2465 		local_irq_enable();
2466 		ret = nr;
2467 	}
2468 
2469 	if (nr < nr_pages) {
2470 		/* Try to get the remaining pages with get_user_pages */
2471 		start += nr << PAGE_SHIFT;
2472 		pages += nr;
2473 
2474 		ret = __gup_longterm_unlocked(start, nr_pages - nr,
2475 					      gup_flags, pages);
2476 
2477 		/* Have to be a bit careful with return values */
2478 		if (nr > 0) {
2479 			if (ret < 0)
2480 				ret = nr;
2481 			else
2482 				ret += nr;
2483 		}
2484 	}
2485 
2486 	return ret;
2487 }
2488 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2489