gup.c 89.9 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/spinlock.h>

#include <linux/mm.h>
8
#include <linux/memremap.h>
9 10 11 12
#include <linux/pagemap.h>
#include <linux/rmap.h>
#include <linux/swap.h>
#include <linux/swapops.h>
13
#include <linux/secretmem.h>
14

15
#include <linux/sched/signal.h>
16
#include <linux/rwsem.h>
17
#include <linux/hugetlb.h>
18 19 20
#include <linux/migrate.h>
#include <linux/mm_inline.h>
#include <linux/sched/mm.h>
21

22
#include <asm/mmu_context.h>
23
#include <asm/tlbflush.h>
24

25 26
#include "internal.h"

27 28 29 30 31
struct follow_page_context {
	struct dev_pagemap *pgmap;
	unsigned int page_mask;
};

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
static inline void sanity_check_pinned_pages(struct page **pages,
					     unsigned long npages)
{
	if (!IS_ENABLED(CONFIG_DEBUG_VM))
		return;

	/*
	 * We only pin anonymous pages if they are exclusive. Once pinned, we
	 * can no longer turn them possibly shared and PageAnonExclusive() will
	 * stick around until the page is freed.
	 *
	 * We'd like to verify that our pinned anonymous pages are still mapped
	 * exclusively. The issue with anon THP is that we don't know how
	 * they are/were mapped when pinning them. However, for anon
	 * THP we can assume that either the given page (PTE-mapped THP) or
	 * the head page (PMD-mapped THP) should be PageAnonExclusive(). If
	 * neither is the case, there is certainly something wrong.
	 */
	for (; npages; npages--, pages++) {
		struct page *page = *pages;
		struct folio *folio = page_folio(page);

		if (!folio_test_anon(folio))
			continue;
		if (!folio_test_large(folio) || folio_test_hugetlb(folio))
			VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page), page);
		else
			/* Either a PTE-mapped or a PMD-mapped THP. */
			VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page) &&
				       !PageAnonExclusive(page), page);
	}
}

65
/*
66
 * Return the folio with ref appropriately incremented,
67
 * or NULL if that failed.
68
 */
69
static inline struct folio *try_get_folio(struct page *page, int refs)
70
{
71
	struct folio *folio;
72

73
retry:
74 75
	folio = page_folio(page);
	if (WARN_ON_ONCE(folio_ref_count(folio) < 0))
76
		return NULL;
77
	if (unlikely(!folio_ref_try_add_rcu(folio, refs)))
78
		return NULL;
79 80

	/*
81 82 83 84
	 * At this point we have a stable reference to the folio; but it
	 * could be that between calling page_folio() and the refcount
	 * increment, the folio was split, in which case we'd end up
	 * holding a reference on a folio that has nothing to do with the page
85
	 * we were given anymore.
86 87
	 * So now that the folio is stable, recheck that the page still
	 * belongs to this folio.
88
	 */
89
	if (unlikely(page_folio(page) != folio)) {
90 91
		if (!put_devmap_managed_page_refs(&folio->page, refs))
			folio_put_refs(folio, refs);
92
		goto retry;
93 94
	}

95
	return folio;
96 97
}

98
/**
99
 * try_grab_folio() - Attempt to get or pin a folio.
100
 * @page:  pointer to page to be grabbed
101
 * @refs:  the value to (effectively) add to the folio's refcount
102 103
 * @flags: gup flags: these are the FOLL_* flag values.
 *
John Hubbard's avatar
John Hubbard committed
104
 * "grab" names in this file mean, "look at flags to decide whether to use
105
 * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
John Hubbard's avatar
John Hubbard committed
106 107 108 109 110
 *
 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
 * same time. (That's true throughout the get_user_pages*() and
 * pin_user_pages*() APIs.) Cases:
 *
111
 *    FOLL_GET: folio's refcount will be incremented by @refs.
112
 *
113 114
 *    FOLL_PIN on large folios: folio's refcount will be incremented by
 *    @refs, and its compound_pincount will be incremented by @refs.
115
 *
116
 *    FOLL_PIN on single-page folios: folio's refcount will be incremented by
117
 *    @refs * GUP_PIN_COUNTING_BIAS.
John Hubbard's avatar
John Hubbard committed
118
 *
119 120 121 122
 * Return: The folio containing @page (with refcount appropriately
 * incremented) for success, or NULL upon failure. If neither FOLL_GET
 * nor FOLL_PIN was set, that's considered failure, and furthermore,
 * a likely bug in the caller, so a warning is also emitted.
John Hubbard's avatar
John Hubbard committed
123
 */
124
struct folio *try_grab_folio(struct page *page, int refs, unsigned int flags)
John Hubbard's avatar
John Hubbard committed
125 126
{
	if (flags & FOLL_GET)
127
		return try_get_folio(page, refs);
John Hubbard's avatar
John Hubbard committed
128
	else if (flags & FOLL_PIN) {
129 130
		struct folio *folio;

131
		/*
132 133 134
		 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
		 * right zone, so fail and let the caller fall back to the slow
		 * path.
135
		 */
136
		if (unlikely((flags & FOLL_LONGTERM) &&
137
			     !is_longterm_pinnable_page(page)))
138 139
			return NULL;

140 141 142 143
		/*
		 * CAUTION: Don't use compound_head() on the page before this
		 * point, the result won't be stable.
		 */
144 145
		folio = try_get_folio(page, refs);
		if (!folio)
146 147
			return NULL;

148
		/*
149
		 * When pinning a large folio, use an exact count to track it.
150
		 *
151 152
		 * However, be sure to *also* increment the normal folio
		 * refcount field at least once, so that the folio really
153
		 * is pinned.  That's why the refcount from the earlier
154
		 * try_get_folio() is left intact.
155
		 */
156 157
		if (folio_test_large(folio))
			atomic_add(refs, folio_pincount_ptr(folio));
158
		else
159 160
			folio_ref_add(folio,
					refs * (GUP_PIN_COUNTING_BIAS - 1));
161 162 163 164 165 166 167
		/*
		 * Adjust the pincount before re-checking the PTE for changes.
		 * This is essentially a smp_mb() and is paired with a memory
		 * barrier in page_try_share_anon_rmap().
		 */
		smp_mb__after_atomic();

168
		node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
169

170
		return folio;
John Hubbard's avatar
John Hubbard committed
171 172 173 174 175 176
	}

	WARN_ON_ONCE(1);
	return NULL;
}

177
static void gup_put_folio(struct folio *folio, int refs, unsigned int flags)
178 179
{
	if (flags & FOLL_PIN) {
180 181 182
		node_stat_mod_folio(folio, NR_FOLL_PIN_RELEASED, refs);
		if (folio_test_large(folio))
			atomic_sub(refs, folio_pincount_ptr(folio));
183 184 185 186
		else
			refs *= GUP_PIN_COUNTING_BIAS;
	}

187 188
	if (!put_devmap_managed_page_refs(&folio->page, refs))
		folio_put_refs(folio, refs);
189 190
}

John Hubbard's avatar
John Hubbard committed
191 192
/**
 * try_grab_page() - elevate a page's refcount by a flag-dependent amount
193 194
 * @page:    pointer to page to be grabbed
 * @flags:   gup flags: these are the FOLL_* flag values.
John Hubbard's avatar
John Hubbard committed
195 196 197 198 199 200 201
 *
 * This might not do anything at all, depending on the flags argument.
 *
 * "grab" names in this file mean, "look at flags to decide whether to use
 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
 *
 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
202
 * time. Cases: please see the try_grab_folio() documentation, with
203
 * "refs=1".
John Hubbard's avatar
John Hubbard committed
204 205 206 207 208 209 210
 *
 * Return: true for success, or if no action was required (if neither FOLL_PIN
 * nor FOLL_GET was set, nothing is done). False for failure: FOLL_GET or
 * FOLL_PIN was set, but the page could not be grabbed.
 */
bool __must_check try_grab_page(struct page *page, unsigned int flags)
{
211 212
	struct folio *folio = page_folio(page);

213
	WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == (FOLL_GET | FOLL_PIN));
214 215
	if (WARN_ON_ONCE(folio_ref_count(folio) <= 0))
		return false;
John Hubbard's avatar
John Hubbard committed
216

217
	if (flags & FOLL_GET)
218
		folio_ref_inc(folio);
219 220
	else if (flags & FOLL_PIN) {
		/*
221
		 * Similar to try_grab_folio(): be sure to *also*
222 223
		 * increment the normal page refcount field at least once,
		 * so that the page really is pinned.
224
		 */
225 226 227
		if (folio_test_large(folio)) {
			folio_ref_add(folio, 1);
			atomic_add(1, folio_pincount_ptr(folio));
228
		} else {
229
			folio_ref_add(folio, GUP_PIN_COUNTING_BIAS);
230
		}
231

232
		node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, 1);
233 234 235
	}

	return true;
John Hubbard's avatar
John Hubbard committed
236 237 238 239 240 241 242 243 244 245 246 247 248
}

/**
 * unpin_user_page() - release a dma-pinned page
 * @page:            pointer to page to be released
 *
 * Pages that were pinned via pin_user_pages*() must be released via either
 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
 * that such pages can be separately tracked and uniquely handled. In
 * particular, interactions with RDMA and filesystems need special handling.
 */
void unpin_user_page(struct page *page)
{
249
	sanity_check_pinned_pages(&page, 1);
250
	gup_put_folio(page_folio(page), 1, FOLL_PIN);
John Hubbard's avatar
John Hubbard committed
251 252 253
}
EXPORT_SYMBOL(unpin_user_page);

254
static inline struct folio *gup_folio_range_next(struct page *start,
255
		unsigned long npages, unsigned long i, unsigned int *ntails)
256
{
257 258
	struct page *next = nth_page(start, i);
	struct folio *folio = page_folio(next);
259 260
	unsigned int nr = 1;

261
	if (folio_test_large(folio))
262
		nr = min_t(unsigned int, npages - i,
263
			   folio_nr_pages(folio) - folio_page_idx(folio, next));
264 265

	*ntails = nr;
266
	return folio;
267 268
}

269
static inline struct folio *gup_folio_next(struct page **list,
270
		unsigned long npages, unsigned long i, unsigned int *ntails)
271
{
272
	struct folio *folio = page_folio(list[i]);
273 274 275
	unsigned int nr;

	for (nr = i + 1; nr < npages; nr++) {
276
		if (page_folio(list[nr]) != folio)
277 278 279 280
			break;
	}

	*ntails = nr - i;
281
	return folio;
282 283
}

284
/**
285
 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
286
 * @pages:  array of pages to be maybe marked dirty, and definitely released.
287
 * @npages: number of pages in the @pages array.
288
 * @make_dirty: whether to mark the pages dirty
289 290 291 292 293
 *
 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
 * variants called on that page.
 *
 * For each page in the @pages array, make that page (or its head page, if a
294
 * compound page) dirty, if @make_dirty is true, and if the page was previously
295 296
 * listed as clean. In any case, releases all pages using unpin_user_page(),
 * possibly via unpin_user_pages(), for the non-dirty case.
297
 *
298
 * Please see the unpin_user_page() documentation for details.
299
 *
300 301 302
 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
 * required, then the caller should a) verify that this is really correct,
 * because _lock() is usually required, and b) hand code it:
303
 * set_page_dirty_lock(), unpin_user_page().
304 305
 *
 */
306 307
void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
				 bool make_dirty)
308
{
309 310 311
	unsigned long i;
	struct folio *folio;
	unsigned int nr;
312 313

	if (!make_dirty) {
314
		unpin_user_pages(pages, npages);
315 316 317
		return;
	}

318
	sanity_check_pinned_pages(pages, npages);
319 320
	for (i = 0; i < npages; i += nr) {
		folio = gup_folio_next(pages, npages, i, &nr);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
		/*
		 * Checking PageDirty at this point may race with
		 * clear_page_dirty_for_io(), but that's OK. Two key
		 * cases:
		 *
		 * 1) This code sees the page as already dirty, so it
		 * skips the call to set_page_dirty(). That could happen
		 * because clear_page_dirty_for_io() called
		 * page_mkclean(), followed by set_page_dirty().
		 * However, now the page is going to get written back,
		 * which meets the original intention of setting it
		 * dirty, so all is well: clear_page_dirty_for_io() goes
		 * on to call TestClearPageDirty(), and write the page
		 * back.
		 *
		 * 2) This code sees the page as clean, so it calls
		 * set_page_dirty(). The page stays dirty, despite being
		 * written back, so it gets written back again in the
		 * next writeback cycle. This is harmless.
		 */
341 342 343 344 345 346
		if (!folio_test_dirty(folio)) {
			folio_lock(folio);
			folio_mark_dirty(folio);
			folio_unlock(folio);
		}
		gup_put_folio(folio, nr, FOLL_PIN);
347
	}
348
}
349
EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
/**
 * unpin_user_page_range_dirty_lock() - release and optionally dirty
 * gup-pinned page range
 *
 * @page:  the starting page of a range maybe marked dirty, and definitely released.
 * @npages: number of consecutive pages to release.
 * @make_dirty: whether to mark the pages dirty
 *
 * "gup-pinned page range" refers to a range of pages that has had one of the
 * pin_user_pages() variants called on that page.
 *
 * For the page ranges defined by [page .. page+npages], make that range (or
 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
 * page range was previously listed as clean.
 *
 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
 * required, then the caller should a) verify that this is really correct,
 * because _lock() is usually required, and b) hand code it:
 * set_page_dirty_lock(), unpin_user_page().
 *
 */
void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
				      bool make_dirty)
{
375 376 377 378 379 380 381 382 383 384 385 386
	unsigned long i;
	struct folio *folio;
	unsigned int nr;

	for (i = 0; i < npages; i += nr) {
		folio = gup_folio_range_next(page, npages, i, &nr);
		if (make_dirty && !folio_test_dirty(folio)) {
			folio_lock(folio);
			folio_mark_dirty(folio);
			folio_unlock(folio);
		}
		gup_put_folio(folio, nr, FOLL_PIN);
387 388 389 390
	}
}
EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
static void unpin_user_pages_lockless(struct page **pages, unsigned long npages)
{
	unsigned long i;
	struct folio *folio;
	unsigned int nr;

	/*
	 * Don't perform any sanity checks because we might have raced with
	 * fork() and some anonymous pages might now actually be shared --
	 * which is why we're unpinning after all.
	 */
	for (i = 0; i < npages; i += nr) {
		folio = gup_folio_next(pages, npages, i, &nr);
		gup_put_folio(folio, nr, FOLL_PIN);
	}
}

408
/**
409
 * unpin_user_pages() - release an array of gup-pinned pages.
410 411 412
 * @pages:  array of pages to be marked dirty and released.
 * @npages: number of pages in the @pages array.
 *
413
 * For each page in the @pages array, release the page using unpin_user_page().
414
 *
415
 * Please see the unpin_user_page() documentation for details.
416
 */
417
void unpin_user_pages(struct page **pages, unsigned long npages)
418
{
419 420 421
	unsigned long i;
	struct folio *folio;
	unsigned int nr;
422

423 424 425 426 427 428 429
	/*
	 * If this WARN_ON() fires, then the system *might* be leaking pages (by
	 * leaving them pinned), but probably not. More likely, gup/pup returned
	 * a hard -ERRNO error to the caller, who erroneously passed it here.
	 */
	if (WARN_ON(IS_ERR_VALUE(npages)))
		return;
430

431
	sanity_check_pinned_pages(pages, npages);
432 433 434
	for (i = 0; i < npages; i += nr) {
		folio = gup_folio_next(pages, npages, i, &nr);
		gup_put_folio(folio, nr, FOLL_PIN);
435
	}
436
}
437
EXPORT_SYMBOL(unpin_user_pages);
438

439 440 441 442 443 444 445 446 447 448 449
/*
 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
 * lifecycle.  Avoid setting the bit unless necessary, or it might cause write
 * cache bouncing on large SMP machines for concurrent pinned gups.
 */
static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
{
	if (!test_bit(MMF_HAS_PINNED, mm_flags))
		set_bit(MMF_HAS_PINNED, mm_flags);
}

450
#ifdef CONFIG_MMU
451 452
static struct page *no_page_table(struct vm_area_struct *vma,
		unsigned int flags)
453
{
454 455 456 457 458 459 460 461
	/*
	 * When core dumping an enormous anonymous area that nobody
	 * has touched so far, we don't want to allocate unnecessary pages or
	 * page tables.  Return error instead of NULL to skip handle_mm_fault,
	 * then get_dump_page() will return NULL to leave a hole in the dump.
	 * But we can only make this optimization where a hole would surely
	 * be zero-filled if handle_mm_fault() actually did handle it.
	 */
462 463
	if ((flags & FOLL_DUMP) &&
			(vma_is_anonymous(vma) || !vma->vm_ops->fault))
464 465 466
		return ERR_PTR(-EFAULT);
	return NULL;
}
467

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
		pte_t *pte, unsigned int flags)
{
	if (flags & FOLL_TOUCH) {
		pte_t entry = *pte;

		if (flags & FOLL_WRITE)
			entry = pte_mkdirty(entry);
		entry = pte_mkyoung(entry);

		if (!pte_same(*pte, entry)) {
			set_pte_at(vma->vm_mm, address, pte, entry);
			update_mmu_cache(vma, address, pte);
		}
	}

	/* Proper page table entry exists, but no corresponding struct page */
	return -EEXIST;
}

488 489 490 491
/* FOLL_FORCE can write to even unwritable PTEs in COW mappings. */
static inline bool can_follow_write_pte(pte_t pte, struct page *page,
					struct vm_area_struct *vma,
					unsigned int flags)
492
{
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
	/* If the pte is writable, we can write to the page. */
	if (pte_write(pte))
		return true;

	/* Maybe FOLL_FORCE is set to override it? */
	if (!(flags & FOLL_FORCE))
		return false;

	/* But FOLL_FORCE has no effect on shared mappings */
	if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
		return false;

	/* ... or read-only private ones */
	if (!(vma->vm_flags & VM_MAYWRITE))
		return false;

	/* ... or already writable ones that just need to take a write fault */
	if (vma->vm_flags & VM_WRITE)
		return false;

	/*
	 * See can_change_pte_writable(): we broke COW and could map the page
	 * writable if we have an exclusive anonymous page ...
	 */
	if (!page || !PageAnon(page) || !PageAnonExclusive(page))
		return false;

	/* ... and a write-fault isn't required for other reasons. */
	if (vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte))
		return false;
	return !userfaultfd_pte_wp(vma, pte);
524 525
}

526
static struct page *follow_page_pte(struct vm_area_struct *vma,
527 528
		unsigned long address, pmd_t *pmd, unsigned int flags,
		struct dev_pagemap **pgmap)
529 530 531 532 533
{
	struct mm_struct *mm = vma->vm_mm;
	struct page *page;
	spinlock_t *ptl;
	pte_t *ptep, pte;
534
	int ret;
535

536 537 538 539
	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
	if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
			 (FOLL_PIN | FOLL_GET)))
		return ERR_PTR(-EINVAL);
540
retry:
541
	if (unlikely(pmd_bad(*pmd)))
542
		return no_page_table(vma, flags);
543 544 545 546 547 548 549 550 551 552 553 554

	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
	pte = *ptep;
	if (!pte_present(pte)) {
		swp_entry_t entry;
		/*
		 * KSM's break_ksm() relies upon recognizing a ksm page
		 * even while it is being migrated, so for that case we
		 * need migration_entry_wait().
		 */
		if (likely(!(flags & FOLL_MIGRATION)))
			goto no_page;
555
		if (pte_none(pte))
556 557 558 559 560 561
			goto no_page;
		entry = pte_to_swp_entry(pte);
		if (!is_migration_entry(entry))
			goto no_page;
		pte_unmap_unlock(ptep, ptl);
		migration_entry_wait(mm, pmd, address);
562
		goto retry;
563
	}
564
	if (pte_protnone(pte) && !gup_can_follow_protnone(flags))
565 566 567
		goto no_page;

	page = vm_normal_page(vma, address, pte);
568 569 570 571 572 573 574 575 576 577 578

	/*
	 * We only care about anon pages in can_follow_write_pte() and don't
	 * have to worry about pte_devmap() because they are never anon.
	 */
	if ((flags & FOLL_WRITE) &&
	    !can_follow_write_pte(pte, page, vma, flags)) {
		page = NULL;
		goto out;
	}

John Hubbard's avatar
John Hubbard committed
579
	if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
580
		/*
John Hubbard's avatar
John Hubbard committed
581 582 583
		 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
		 * case since they are only valid while holding the pgmap
		 * reference.
584
		 */
585 586
		*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
		if (*pgmap)
587 588 589 590
			page = pte_page(pte);
		else
			goto no_page;
	} else if (unlikely(!page)) {
591 592 593 594 595 596 597 598 599 600 601 602 603
		if (flags & FOLL_DUMP) {
			/* Avoid special (like zero) pages in core dumps */
			page = ERR_PTR(-EFAULT);
			goto out;
		}

		if (is_zero_pfn(pte_pfn(pte))) {
			page = pte_page(pte);
		} else {
			ret = follow_pfn_pte(vma, address, ptep, flags);
			page = ERR_PTR(ret);
			goto out;
		}
604 605
	}

606
	if (!pte_write(pte) && gup_must_unshare(vma, flags, page)) {
607 608 609
		page = ERR_PTR(-EMLINK);
		goto out;
	}
610 611 612 613

	VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
		       !PageAnonExclusive(page), page);

John Hubbard's avatar
John Hubbard committed
614 615 616 617
	/* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
	if (unlikely(!try_grab_page(page, flags))) {
		page = ERR_PTR(-ENOMEM);
		goto out;
618
	}
619 620 621 622 623 624 625 626 627 628 629 630 631
	/*
	 * We need to make the page accessible if and only if we are going
	 * to access its content (the FOLL_PIN case).  Please see
	 * Documentation/core-api/pin_user_pages.rst for details.
	 */
	if (flags & FOLL_PIN) {
		ret = arch_make_page_accessible(page);
		if (ret) {
			unpin_user_page(page);
			page = ERR_PTR(ret);
			goto out;
		}
	}
632 633 634 635 636 637 638 639 640 641 642
	if (flags & FOLL_TOUCH) {
		if ((flags & FOLL_WRITE) &&
		    !pte_dirty(pte) && !PageDirty(page))
			set_page_dirty(page);
		/*
		 * pte_mkyoung() would be more correct here, but atomic care
		 * is needed to avoid losing the dirty bit: it is easier to use
		 * mark_page_accessed().
		 */
		mark_page_accessed(page);
	}
643
out:
644 645 646 647 648
	pte_unmap_unlock(ptep, ptl);
	return page;
no_page:
	pte_unmap_unlock(ptep, ptl);
	if (!pte_none(pte))
649 650 651 652
		return NULL;
	return no_page_table(vma, flags);
}

653 654
static struct page *follow_pmd_mask(struct vm_area_struct *vma,
				    unsigned long address, pud_t *pudp,
655 656
				    unsigned int flags,
				    struct follow_page_context *ctx)
657
{
658
	pmd_t *pmd, pmdval;
659 660 661 662
	spinlock_t *ptl;
	struct page *page;
	struct mm_struct *mm = vma->vm_mm;

663
	pmd = pmd_offset(pudp, address);
664 665 666 667 668 669
	/*
	 * The READ_ONCE() will stabilize the pmdval in a register or
	 * on the stack so that it will stop changing under the code.
	 */
	pmdval = READ_ONCE(*pmd);
	if (pmd_none(pmdval))
670
		return no_page_table(vma, flags);
671
retry:
672
	if (!pmd_present(pmdval)) {
673 674 675 676 677 678 679
		/*
		 * Should never reach here, if thp migration is not supported;
		 * Otherwise, it must be a thp migration entry.
		 */
		VM_BUG_ON(!thp_migration_supported() ||
				  !is_pmd_migration_entry(pmdval));

680 681
		if (likely(!(flags & FOLL_MIGRATION)))
			return no_page_table(vma, flags);
682 683

		pmd_migration_entry_wait(mm, pmd);
684 685 686
		pmdval = READ_ONCE(*pmd);
		/*
		 * MADV_DONTNEED may convert the pmd to null because
687
		 * mmap_lock is held in read mode
688 689 690
		 */
		if (pmd_none(pmdval))
			return no_page_table(vma, flags);
691 692
		goto retry;
	}
693
	if (pmd_devmap(pmdval)) {
694
		ptl = pmd_lock(mm, pmd);
695
		page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
696 697 698 699
		spin_unlock(ptl);
		if (page)
			return page;
	}
700
	if (likely(!pmd_trans_huge(pmdval)))
701
		return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
702

703
	if (pmd_protnone(pmdval) && !gup_can_follow_protnone(flags))
704 705
		return no_page_table(vma, flags);

706
retry_locked:
707
	ptl = pmd_lock(mm, pmd);
708 709 710 711
	if (unlikely(pmd_none(*pmd))) {
		spin_unlock(ptl);
		return no_page_table(vma, flags);
	}
712 713 714 715 716 717 718
	if (unlikely(!pmd_present(*pmd))) {
		spin_unlock(ptl);
		if (likely(!(flags & FOLL_MIGRATION)))
			return no_page_table(vma, flags);
		pmd_migration_entry_wait(mm, pmd);
		goto retry_locked;
	}
719 720
	if (unlikely(!pmd_trans_huge(*pmd))) {
		spin_unlock(ptl);
721
		return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
722
	}
Yang Shi's avatar
Yang Shi committed
723
	if (flags & FOLL_SPLIT_PMD) {
724 725 726 727 728
		int ret;
		page = pmd_page(*pmd);
		if (is_huge_zero_page(page)) {
			spin_unlock(ptl);
			ret = 0;
729
			split_huge_pmd(vma, pmd, address);
730 731
			if (pmd_trans_unstable(pmd))
				ret = -EBUSY;
Yang Shi's avatar
Yang Shi committed
732
		} else {
Song Liu's avatar
Song Liu committed
733 734 735
			spin_unlock(ptl);
			split_huge_pmd(vma, pmd, address);
			ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
736 737 738
		}

		return ret ? ERR_PTR(ret) :
739
			follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
740
	}
741 742
	page = follow_trans_huge_pmd(vma, address, pmd, flags);
	spin_unlock(ptl);
743
	ctx->page_mask = HPAGE_PMD_NR - 1;
744
	return page;
745 746
}

747 748
static struct page *follow_pud_mask(struct vm_area_struct *vma,
				    unsigned long address, p4d_t *p4dp,
749 750
				    unsigned int flags,
				    struct follow_page_context *ctx)
751 752 753 754 755 756 757 758 759 760 761
{
	pud_t *pud;
	spinlock_t *ptl;
	struct page *page;
	struct mm_struct *mm = vma->vm_mm;

	pud = pud_offset(p4dp, address);
	if (pud_none(*pud))
		return no_page_table(vma, flags);
	if (pud_devmap(*pud)) {
		ptl = pud_lock(mm, pud);
762
		page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
763 764 765 766 767 768 769
		spin_unlock(ptl);
		if (page)
			return page;
	}
	if (unlikely(pud_bad(*pud)))
		return no_page_table(vma, flags);

770
	return follow_pmd_mask(vma, address, pud, flags, ctx);
771 772 773 774
}

static struct page *follow_p4d_mask(struct vm_area_struct *vma,
				    unsigned long address, pgd_t *pgdp,
775 776
				    unsigned int flags,
				    struct follow_page_context *ctx)
777 778 779 780 781 782 783 784 785 786
{
	p4d_t *p4d;

	p4d = p4d_offset(pgdp, address);
	if (p4d_none(*p4d))
		return no_page_table(vma, flags);
	BUILD_BUG_ON(p4d_huge(*p4d));
	if (unlikely(p4d_bad(*p4d)))
		return no_page_table(vma, flags);

787
	return follow_pud_mask(vma, address, p4d, flags, ctx);
788 789 790 791 792 793 794
}

/**
 * follow_page_mask - look up a page descriptor from a user-virtual address
 * @vma: vm_area_struct mapping @address
 * @address: virtual address to look up
 * @flags: flags modifying lookup behaviour
795 796
 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
 *       pointer to output page_mask
797 798 799
 *
 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
 *
800 801 802
 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
 *
803 804 805 806 807
 * When getting an anonymous page and the caller has to trigger unsharing
 * of a shared anonymous page first, -EMLINK is returned. The caller should
 * trigger a fault with FAULT_FLAG_UNSHARE set. Note that unsharing is only
 * relevant with FOLL_PIN and !FOLL_WRITE.
 *
808 809 810
 * On output, the @ctx->page_mask is set according to the size of the page.
 *
 * Return: the mapped (struct page *), %NULL if no mapping exists, or
811 812 813
 * an error pointer if there is a mapping to something not represented
 * by a page descriptor (see also vm_normal_page()).
 */
814
static struct page *follow_page_mask(struct vm_area_struct *vma,
815
			      unsigned long address, unsigned int flags,
816
			      struct follow_page_context *ctx)
817 818 819 820 821
{
	pgd_t *pgd;
	struct page *page;
	struct mm_struct *mm = vma->vm_mm;

822
	ctx->page_mask = 0;
823

824 825 826 827 828 829 830 831 832 833 834 835
	/*
	 * Call hugetlb_follow_page_mask for hugetlb vmas as it will use
	 * special hugetlb page table walking code.  This eliminates the
	 * need to check for hugetlb entries in the general walking code.
	 *
	 * hugetlb_follow_page_mask is only for follow_page() handling here.
	 * Ordinary GUP uses follow_hugetlb_page for hugetlb processing.
	 */
	if (is_vm_hugetlb_page(vma)) {
		page = hugetlb_follow_page_mask(vma, address, flags);
		if (!page)
			page = no_page_table(vma, flags);
836 837 838 839 840 841 842 843
		return page;
	}

	pgd = pgd_offset(mm, address);

	if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
		return no_page_table(vma, flags);

844 845 846 847 848 849 850 851 852
	return follow_p4d_mask(vma, address, pgd, flags, ctx);
}

struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
			 unsigned int foll_flags)
{
	struct follow_page_context ctx = { NULL };
	struct page *page;

853 854 855
	if (vma_is_secretmem(vma))
		return NULL;

856 857 858
	if (foll_flags & FOLL_PIN)
		return NULL;

859 860 861 862
	page = follow_page_mask(vma, address, foll_flags, &ctx);
	if (ctx.pgmap)
		put_dev_pagemap(ctx.pgmap);
	return page;
863 864
}

865 866 867 868 869
static int get_gate_page(struct mm_struct *mm, unsigned long address,
		unsigned int gup_flags, struct vm_area_struct **vma,
		struct page **page)
{
	pgd_t *pgd;
870
	p4d_t *p4d;
871 872 873 874 875 876 877 878 879 880 881 882
	pud_t *pud;
	pmd_t *pmd;
	pte_t *pte;
	int ret = -EFAULT;

	/* user gate pages are read-only */
	if (gup_flags & FOLL_WRITE)
		return -EFAULT;
	if (address > TASK_SIZE)
		pgd = pgd_offset_k(address);
	else
		pgd = pgd_offset_gate(mm, address);
883 884
	if (pgd_none(*pgd))
		return -EFAULT;
885
	p4d = p4d_offset(pgd, address);
886 887
	if (p4d_none(*p4d))
		return -EFAULT;
888
	pud = pud_offset(p4d, address);
889 890
	if (pud_none(*pud))
		return -EFAULT;
891
	pmd = pmd_offset(pud, address);
892
	if (!pmd_present(*pmd))
893 894 895 896 897 898 899 900 901 902 903 904 905 906
		return -EFAULT;
	VM_BUG_ON(pmd_trans_huge(*pmd));
	pte = pte_offset_map(pmd, address);
	if (pte_none(*pte))
		goto unmap;
	*vma = get_gate_vma(mm);
	if (!page)
		goto out;
	*page = vm_normal_page(*vma, address, *pte);
	if (!*page) {
		if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
			goto unmap;
		*page = pte_page(*pte);
	}
907
	if (unlikely(!try_grab_page(*page, gup_flags))) {
908 909 910
		ret = -ENOMEM;
		goto unmap;
	}
911 912 913 914 915 916 917
out:
	ret = 0;
unmap:
	pte_unmap(pte);
	return ret;
}

918
/*
919 920
 * mmap_lock must be held on entry.  If @locked != NULL and *@flags
 * does not include FOLL_NOWAIT, the mmap_lock may be released.  If it
921
 * is, *@locked will be set to 0 and -EBUSY returned.
922
 */
923
static int faultin_page(struct vm_area_struct *vma,
924 925
		unsigned long address, unsigned int *flags, bool unshare,
		int *locked)
926 927
{
	unsigned int fault_flags = 0;
928
	vm_fault_t ret;
929

930 931
	if (*flags & FOLL_NOFAULT)
		return -EFAULT;
932 933
	if (*flags & FOLL_WRITE)
		fault_flags |= FAULT_FLAG_WRITE;
934 935
	if (*flags & FOLL_REMOTE)
		fault_flags |= FAULT_FLAG_REMOTE;
936
	if (locked)
937
		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
938 939
	if (*flags & FOLL_NOWAIT)
		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
940
	if (*flags & FOLL_TRIED) {
941 942 943 944
		/*
		 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
		 * can co-exist
		 */
945 946
		fault_flags |= FAULT_FLAG_TRIED;
	}
947 948 949 950 951
	if (unshare) {
		fault_flags |= FAULT_FLAG_UNSHARE;
		/* FAULT_FLAG_WRITE and FAULT_FLAG_UNSHARE are incompatible */
		VM_BUG_ON(fault_flags & FAULT_FLAG_WRITE);
	}
952

953
	ret = handle_mm_fault(vma, address, fault_flags, NULL);
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

	if (ret & VM_FAULT_COMPLETED) {
		/*
		 * With FAULT_FLAG_RETRY_NOWAIT we'll never release the
		 * mmap lock in the page fault handler. Sanity check this.
		 */
		WARN_ON_ONCE(fault_flags & FAULT_FLAG_RETRY_NOWAIT);
		if (locked)
			*locked = 0;
		/*
		 * We should do the same as VM_FAULT_RETRY, but let's not
		 * return -EBUSY since that's not reflecting the reality of
		 * what has happened - we've just fully completed a page
		 * fault, with the mmap lock released.  Use -EAGAIN to show
		 * that we want to take the mmap lock _again_.
		 */
		return -EAGAIN;
	}

973
	if (ret & VM_FAULT_ERROR) {
974 975 976 977
		int err = vm_fault_to_errno(ret, *flags);

		if (err)
			return err;
978 979 980 981
		BUG();
	}

	if (ret & VM_FAULT_RETRY) {
982 983
		if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
			*locked = 0;
984 985 986 987 988 989
		return -EBUSY;
	}

	return 0;
}

990 991 992
static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
{
	vm_flags_t vm_flags = vma->vm_flags;
993 994
	int write = (gup_flags & FOLL_WRITE);
	int foreign = (gup_flags & FOLL_REMOTE);
995 996 997 998

	if (vm_flags & (VM_IO | VM_PFNMAP))
		return -EFAULT;

999 1000 1001
	if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
		return -EFAULT;

1002 1003 1004
	if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
		return -EOPNOTSUPP;

1005 1006 1007
	if (vma_is_secretmem(vma))
		return -EFAULT;

1008
	if (write) {
1009 1010 1011
		if (!(vm_flags & VM_WRITE)) {
			if (!(gup_flags & FOLL_FORCE))
				return -EFAULT;
1012 1013 1014
			/* hugetlb does not support FOLL_FORCE|FOLL_WRITE. */
			if (is_vm_hugetlb_page(vma))
				return -EFAULT;
1015 1016 1017 1018 1019 1020 1021 1022 1023
			/*
			 * We used to let the write,force case do COW in a
			 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
			 * set a breakpoint in a read-only mapping of an
			 * executable, without corrupting the file (yet only
			 * when that file had been opened for writing!).
			 * Anon pages in shared mappings are surprising: now
			 * just reject it.
			 */
1024
			if (!is_cow_mapping(vm_flags))
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
				return -EFAULT;
		}
	} else if (!(vm_flags & VM_READ)) {
		if (!(gup_flags & FOLL_FORCE))
			return -EFAULT;
		/*
		 * Is there actually any vma we can reach here which does not
		 * have VM_MAYREAD set?
		 */
		if (!(vm_flags & VM_MAYREAD))
			return -EFAULT;
	}
1037 1038 1039 1040 1041
	/*
	 * gups are always data accesses, not instruction
	 * fetches, so execute=false here
	 */
	if (!arch_vma_access_permitted(vma, write, false, foreign))
1042
		return -EFAULT;
1043 1044 1045
	return 0;
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
/**
 * __get_user_pages() - pin user pages in memory
 * @mm:		mm_struct of target mm
 * @start:	starting user address
 * @nr_pages:	number of pages from start to pin
 * @gup_flags:	flags modifying pin behaviour
 * @pages:	array that receives pointers to the pages pinned.
 *		Should be at least nr_pages long. Or NULL, if caller
 *		only intends to ensure the pages are faulted in.
 * @vmas:	array of pointers to vmas corresponding to each page.
 *		Or NULL if the caller does not require them.
1057
 * @locked:     whether we're still with the mmap_lock held
1058
 *
1059 1060 1061 1062 1063 1064 1065
 * Returns either number of pages pinned (which may be less than the
 * number requested), or an error. Details about the return value:
 *
 * -- If nr_pages is 0, returns 0.
 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
 * -- If nr_pages is >0, and some pages were pinned, returns the number of
 *    pages pinned. Again, this may be less than nr_pages.
1066
 * -- 0 return value is possible when the fault would need to be retried.
1067 1068 1069
 *
 * The caller is responsible for releasing returned @pages, via put_page().
 *
1070
 * @vmas are valid only as long as mmap_lock is held.
1071
 *
1072
 * Must be called with mmap_lock held.  It may be released.  See below.
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
 *
 * __get_user_pages walks a process's page tables and takes a reference to
 * each struct page that each user address corresponds to at a given
 * instant. That is, it takes the page that would be accessed if a user
 * thread accesses the given user virtual address at that instant.
 *
 * This does not guarantee that the page exists in the user mappings when
 * __get_user_pages returns, and there may even be a completely different
 * page there in some cases (eg. if mmapped pagecache has been invalidated
 * and subsequently re faulted). However it does guarantee that the page
 * won't be freed completely. And mostly callers simply care that the page
 * contains data that was valid *at some point in time*. Typically, an IO
 * or similar operation cannot guarantee anything stronger anyway because
 * locks can't be held over the syscall boundary.
 *
 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
 * appropriate) must be called after the page is finished with, and
 * before put_page is called.
 *
1093
 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1094 1095
 * released by an up_read().  That can happen if @gup_flags does not
 * have FOLL_NOWAIT.
1096
 *
1097
 * A caller using such a combination of @locked and @gup_flags
1098
 * must therefore hold the mmap_lock for reading only, and recognize
1099 1100
 * when it's been released.  Otherwise, it must be held for either
 * reading or writing and will not be released.
1101 1102 1103 1104 1105
 *
 * In most cases, get_user_pages or get_user_pages_fast should be used
 * instead of __get_user_pages. __get_user_pages should be used only if
 * you need some special @gup_flags.
 */
1106
static long __get_user_pages(struct mm_struct *mm,
1107 1108
		unsigned long start, unsigned long nr_pages,
		unsigned int gup_flags, struct page **pages,
1109
		struct vm_area_struct **vmas, int *locked)
1110
{
1111
	long ret = 0, i = 0;
1112
	struct vm_area_struct *vma = NULL;
1113
	struct follow_page_context ctx = { NULL };
1114 1115 1116 1117

	if (!nr_pages)
		return 0;

1118 1119
	start = untagged_addr(start);

1120
	VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1121 1122

	do {
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
		struct page *page;
		unsigned int foll_flags = gup_flags;
		unsigned int page_increm;

		/* first iteration or cross vma bound */
		if (!vma || start >= vma->vm_end) {
			vma = find_extend_vma(mm, start);
			if (!vma && in_gate_area(mm, start)) {
				ret = get_gate_page(mm, start & PAGE_MASK,
						gup_flags, &vma,
						pages ? &pages[i] : NULL);
				if (ret)
1135
					goto out;
1136
				ctx.page_mask = 0;
1137 1138
				goto next_page;
			}
1139

1140
			if (!vma) {
1141 1142 1143
				ret = -EFAULT;
				goto out;
			}
1144 1145 1146 1147
			ret = check_vma_flags(vma, gup_flags);
			if (ret)
				goto out;

1148 1149 1150
			if (is_vm_hugetlb_page(vma)) {
				i = follow_hugetlb_page(mm, vma, pages, vmas,
						&start, &nr_pages, i,
1151
						gup_flags, locked);
1152 1153 1154
				if (locked && *locked == 0) {
					/*
					 * We've got a VM_FAULT_RETRY
1155
					 * and we've lost mmap_lock.
1156 1157 1158 1159 1160
					 * We must stop here.
					 */
					BUG_ON(gup_flags & FOLL_NOWAIT);
					goto out;
				}
1161
				continue;
1162
			}
1163 1164 1165 1166 1167 1168
		}
retry:
		/*
		 * If we have a pending SIGKILL, don't keep faulting pages and
		 * potentially allocating memory.
		 */
1169
		if (fatal_signal_pending(current)) {
1170
			ret = -EINTR;
1171 1172
			goto out;
		}
1173
		cond_resched();
1174 1175

		page = follow_page_mask(vma, start, foll_flags, &ctx);
1176 1177 1178
		if (!page || PTR_ERR(page) == -EMLINK) {
			ret = faultin_page(vma, start, &foll_flags,
					   PTR_ERR(page) == -EMLINK, locked);
1179 1180 1181
			switch (ret) {
			case 0:
				goto retry;
1182
			case -EBUSY:
1183
			case -EAGAIN:
1184
				ret = 0;
Joe Perches's avatar
Joe Perches committed
1185
				fallthrough;
1186 1187 1188
			case -EFAULT:
			case -ENOMEM:
			case -EHWPOISON:
1189
				goto out;
1190
			}
1191
			BUG();
1192 1193 1194
		} else if (PTR_ERR(page) == -EEXIST) {
			/*
			 * Proper page table entry exists, but no corresponding
1195 1196 1197
			 * struct page. If the caller expects **pages to be
			 * filled in, bail out now, because that can't be done
			 * for this page.
1198
			 */
1199 1200 1201 1202 1203
			if (pages) {
				ret = PTR_ERR(page);
				goto out;
			}

1204 1205
			goto next_page;
		} else if (IS_ERR(page)) {
1206 1207
			ret = PTR_ERR(page);
			goto out;
1208
		}
1209 1210 1211 1212
		if (pages) {
			pages[i] = page;
			flush_anon_page(vma, page, start);
			flush_dcache_page(page);
1213
			ctx.page_mask = 0;
1214 1215
		}
next_page:
1216 1217
		if (vmas) {
			vmas[i] = vma;
1218
			ctx.page_mask = 0;
1219
		}
1220
		page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1221 1222 1223 1224 1225
		if (page_increm > nr_pages)
			page_increm = nr_pages;
		i += page_increm;
		start += page_increm * PAGE_SIZE;
		nr_pages -= page_increm;
1226
	} while (nr_pages);
1227 1228 1229 1230
out:
	if (ctx.pgmap)
		put_dev_pagemap(ctx.pgmap);
	return i ? i : ret;
1231 1232
}

1233 1234
static bool vma_permits_fault(struct vm_area_struct *vma,
			      unsigned int fault_flags)
1235
{
1236 1237
	bool write   = !!(fault_flags & FAULT_FLAG_WRITE);
	bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1238
	vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1239 1240 1241 1242

	if (!(vm_flags & vma->vm_flags))
		return false;

1243 1244
	/*
	 * The architecture might have a hardware protection
1245
	 * mechanism other than read/write that can deny access.
1246 1247 1248
	 *
	 * gup always represents data access, not instruction
	 * fetches, so execute=false here:
1249
	 */
1250
	if (!arch_vma_access_permitted(vma, write, false, foreign))
1251 1252
		return false;

1253 1254 1255
	return true;
}

1256
/**
1257 1258 1259 1260
 * fixup_user_fault() - manually resolve a user page fault
 * @mm:		mm_struct of target mm
 * @address:	user address
 * @fault_flags:flags to pass down to handle_mm_fault()
1261
 * @unlocked:	did we unlock the mmap_lock while retrying, maybe NULL if caller
1262 1263
 *		does not allow retry. If NULL, the caller must guarantee
 *		that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
 *
 * This is meant to be called in the specific scenario where for locking reasons
 * we try to access user memory in atomic context (within a pagefault_disable()
 * section), this returns -EFAULT, and we want to resolve the user fault before
 * trying again.
 *
 * Typically this is meant to be used by the futex code.
 *
 * The main difference with get_user_pages() is that this function will
 * unconditionally call handle_mm_fault() which will in turn perform all the
 * necessary SW fixup of the dirty and young bits in the PTE, while
1275
 * get_user_pages() only guarantees to update these in the struct page.
1276 1277 1278 1279 1280 1281
 *
 * This is important for some architectures where those bits also gate the
 * access permission to the page because they are maintained in software.  On
 * such architectures, gup() will not be enough to make a subsequent access
 * succeed.
 *
1282 1283
 * This function will not return with an unlocked mmap_lock. So it has not the
 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1284
 */
1285
int fixup_user_fault(struct mm_struct *mm,
1286 1287
		     unsigned long address, unsigned int fault_flags,
		     bool *unlocked)
1288 1289
{
	struct vm_area_struct *vma;
1290
	vm_fault_t ret;
1291

1292 1293
	address = untagged_addr(address);

1294
	if (unlocked)
1295
		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1296

1297
retry:
1298 1299 1300 1301
	vma = find_extend_vma(mm, address);
	if (!vma || address < vma->vm_start)
		return -EFAULT;

1302
	if (!vma_permits_fault(vma, fault_flags))
1303 1304
		return -EFAULT;

1305 1306 1307 1308
	if ((fault_flags & FAULT_FLAG_KILLABLE) &&
	    fatal_signal_pending(current))
		return -EINTR;

1309
	ret = handle_mm_fault(vma, address, fault_flags, NULL);
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

	if (ret & VM_FAULT_COMPLETED) {
		/*
		 * NOTE: it's a pity that we need to retake the lock here
		 * to pair with the unlock() in the callers. Ideally we
		 * could tell the callers so they do not need to unlock.
		 */
		mmap_read_lock(mm);
		*unlocked = true;
		return 0;
	}

1322
	if (ret & VM_FAULT_ERROR) {
1323 1324 1325 1326
		int err = vm_fault_to_errno(ret, 0);

		if (err)
			return err;
1327 1328
		BUG();
	}
1329 1330

	if (ret & VM_FAULT_RETRY) {
1331
		mmap_read_lock(mm);
1332 1333 1334
		*unlocked = true;
		fault_flags |= FAULT_FLAG_TRIED;
		goto retry;
1335 1336
	}

1337 1338
	return 0;
}
1339
EXPORT_SYMBOL_GPL(fixup_user_fault);
1340

1341 1342 1343 1344
/*
 * Please note that this function, unlike __get_user_pages will not
 * return 0 for nr_pages > 0 without FOLL_NOWAIT
 */
1345
static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1346 1347 1348 1349
						unsigned long start,
						unsigned long nr_pages,
						struct page **pages,
						struct vm_area_struct **vmas,
1350
						int *locked,
1351
						unsigned int flags)
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
{
	long ret, pages_done;
	bool lock_dropped;

	if (locked) {
		/* if VM_FAULT_RETRY can be returned, vmas become invalid */
		BUG_ON(vmas);
		/* check caller initialized locked */
		BUG_ON(*locked != 1);
	}

1363 1364
	if (flags & FOLL_PIN)
		mm_set_has_pinned_flag(&mm->flags);
Peter Xu's avatar
Peter Xu committed
1365

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
	/*
	 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
	 * is to set FOLL_GET if the caller wants pages[] filled in (but has
	 * carelessly failed to specify FOLL_GET), so keep doing that, but only
	 * for FOLL_GET, not for the newer FOLL_PIN.
	 *
	 * FOLL_PIN always expects pages to be non-null, but no need to assert
	 * that here, as any failures will be obvious enough.
	 */
	if (pages && !(flags & FOLL_PIN))
1376 1377 1378 1379 1380
		flags |= FOLL_GET;

	pages_done = 0;
	lock_dropped = false;
	for (;;) {
1381
		ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1382 1383 1384 1385 1386
				       vmas, locked);
		if (!locked)
			/* VM_FAULT_RETRY couldn't trigger, bypass */
			return ret;

1387
		/* VM_FAULT_RETRY or VM_FAULT_COMPLETED cannot return errors */
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
		if (!*locked) {
			BUG_ON(ret < 0);
			BUG_ON(ret >= nr_pages);
		}

		if (ret > 0) {
			nr_pages -= ret;
			pages_done += ret;
			if (!nr_pages)
				break;
		}
		if (*locked) {
1400 1401 1402 1403
			/*
			 * VM_FAULT_RETRY didn't trigger or it was a
			 * FOLL_NOWAIT.
			 */
1404 1405 1406 1407
			if (!pages_done)
				pages_done = ret;
			break;
		}
1408 1409 1410 1411 1412 1413
		/*
		 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
		 * For the prefault case (!pages) we only update counts.
		 */
		if (likely(pages))
			pages += ret;
1414
		start += ret << PAGE_SHIFT;
1415
		lock_dropped = true;
1416

1417
retry:
1418 1419
		/*
		 * Repeat on the address that fired VM_FAULT_RETRY
1420 1421 1422 1423
		 * with both FAULT_FLAG_ALLOW_RETRY and
		 * FAULT_FLAG_TRIED.  Note that GUP can be interrupted
		 * by fatal signals, so we need to check it before we
		 * start trying again otherwise it can loop forever.
1424
		 */
1425

1426 1427 1428
		if (fatal_signal_pending(current)) {
			if (!pages_done)
				pages_done = -EINTR;
1429
			break;
1430
		}
1431

1432
		ret = mmap_read_lock_killable(mm);
1433 1434 1435 1436 1437 1438
		if (ret) {
			BUG_ON(ret > 0);
			if (!pages_done)
				pages_done = ret;
			break;
		}
1439

1440
		*locked = 1;
1441
		ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1442 1443 1444 1445 1446 1447
				       pages, NULL, locked);
		if (!*locked) {
			/* Continue to retry until we succeeded */
			BUG_ON(ret != 0);
			goto retry;
		}
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
		if (ret != 1) {
			BUG_ON(ret > 1);
			if (!pages_done)
				pages_done = ret;
			break;
		}
		nr_pages--;
		pages_done++;
		if (!nr_pages)
			break;
1458 1459
		if (likely(pages))
			pages++;
1460 1461
		start += PAGE_SIZE;
	}
1462
	if (lock_dropped && *locked) {
1463 1464 1465 1466
		/*
		 * We must let the caller know we temporarily dropped the lock
		 * and so the critical section protected by it was lost.
		 */
1467
		mmap_read_unlock(mm);
1468 1469 1470 1471 1472
		*locked = 0;
	}
	return pages_done;
}

1473 1474 1475 1476 1477
/**
 * populate_vma_page_range() -  populate a range of pages in the vma.
 * @vma:   target vma
 * @start: start address
 * @end:   end address
1478
 * @locked: whether the mmap_lock is still held
1479 1480 1481
 *
 * This takes care of mlocking the pages too if VM_LOCKED is set.
 *
1482 1483
 * Return either number of pages pinned in the vma, or a negative error
 * code on error.
1484
 *
1485
 * vma->vm_mm->mmap_lock must be held.
1486
 *
1487
 * If @locked is NULL, it may be held for read or write and will
1488 1489
 * be unperturbed.
 *
1490 1491
 * If @locked is non-NULL, it must held for read only and may be
 * released.  If it's released, *@locked will be set to 0.
1492 1493
 */
long populate_vma_page_range(struct vm_area_struct *vma,
1494
		unsigned long start, unsigned long end, int *locked)
1495 1496 1497 1498
{
	struct mm_struct *mm = vma->vm_mm;
	unsigned long nr_pages = (end - start) / PAGE_SIZE;
	int gup_flags;
1499
	long ret;
1500

1501 1502
	VM_BUG_ON(!PAGE_ALIGNED(start));
	VM_BUG_ON(!PAGE_ALIGNED(end));
1503 1504
	VM_BUG_ON_VMA(start < vma->vm_start, vma);
	VM_BUG_ON_VMA(end   > vma->vm_end, vma);
1505
	mmap_assert_locked(mm);
1506

1507 1508 1509 1510
	/*
	 * Rightly or wrongly, the VM_LOCKONFAULT case has never used
	 * faultin_page() to break COW, so it has no work to do here.
	 */
1511
	if (vma->vm_flags & VM_LOCKONFAULT)
1512 1513 1514
		return nr_pages;

	gup_flags = FOLL_TOUCH;
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
	/*
	 * We want to touch writable mappings with a write fault in order
	 * to break COW, except for shared mappings because these don't COW
	 * and we would not want to dirty them for nothing.
	 */
	if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
		gup_flags |= FOLL_WRITE;

	/*
	 * We want mlock to succeed for regions that have any permissions
	 * other than PROT_NONE.
	 */
1527
	if (vma_is_accessible(vma))
1528 1529 1530 1531 1532 1533
		gup_flags |= FOLL_FORCE;

	/*
	 * We made sure addr is within a VMA, so the following will
	 * not result in a stack expansion that recurses back here.
	 */
1534
	ret = __get_user_pages(mm, start, nr_pages, gup_flags,
1535
				NULL, NULL, locked);
1536 1537
	lru_add_drain();
	return ret;
1538 1539
}

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
/*
 * faultin_vma_page_range() - populate (prefault) page tables inside the
 *			      given VMA range readable/writable
 *
 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
 *
 * @vma: target vma
 * @start: start address
 * @end: end address
 * @write: whether to prefault readable or writable
 * @locked: whether the mmap_lock is still held
 *
 * Returns either number of processed pages in the vma, or a negative error
 * code on error (see __get_user_pages()).
 *
 * vma->vm_mm->mmap_lock must be held. The range must be page-aligned and
 * covered by the VMA.
 *
 * If @locked is NULL, it may be held for read or write and will be unperturbed.
 *
 * If @locked is non-NULL, it must held for read only and may be released.  If
 * it's released, *@locked will be set to 0.
 */
long faultin_vma_page_range(struct vm_area_struct *vma, unsigned long start,
			    unsigned long end, bool write, int *locked)
{
	struct mm_struct *mm = vma->vm_mm;
	unsigned long nr_pages = (end - start) / PAGE_SIZE;
	int gup_flags;
1569
	long ret;
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585

	VM_BUG_ON(!PAGE_ALIGNED(start));
	VM_BUG_ON(!PAGE_ALIGNED(end));
	VM_BUG_ON_VMA(start < vma->vm_start, vma);
	VM_BUG_ON_VMA(end > vma->vm_end, vma);
	mmap_assert_locked(mm);

	/*
	 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
	 *	       the page dirty with FOLL_WRITE -- which doesn't make a
	 *	       difference with !FOLL_FORCE, because the page is writable
	 *	       in the page table.
	 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
	 *		  a poisoned page.
	 * !FOLL_FORCE: Require proper access permissions.
	 */
1586
	gup_flags = FOLL_TOUCH | FOLL_HWPOISON;
1587 1588 1589 1590
	if (write)
		gup_flags |= FOLL_WRITE;

	/*
1591 1592
	 * We want to report -EINVAL instead of -EFAULT for any permission
	 * problems or incompatible mappings.
1593
	 */
1594 1595 1596
	if (check_vma_flags(vma, gup_flags))
		return -EINVAL;

1597
	ret = __get_user_pages(mm, start, nr_pages, gup_flags,
1598
				NULL, NULL, locked);
1599 1600
	lru_add_drain();
	return ret;
1601 1602
}

1603 1604 1605 1606 1607
/*
 * __mm_populate - populate and/or mlock pages within a range of address space.
 *
 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
 * flags. VMAs must be already marked with the desired vm_flags, and
1608
 * mmap_lock must not be held.
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
 */
int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
{
	struct mm_struct *mm = current->mm;
	unsigned long end, nstart, nend;
	struct vm_area_struct *vma = NULL;
	int locked = 0;
	long ret = 0;

	end = start + len;

	for (nstart = start; nstart < end; nstart = nend) {
		/*
		 * We want to fault in pages for [nstart; end) address range.
		 * Find first corresponding VMA.
		 */
		if (!locked) {
			locked = 1;
1627
			mmap_read_lock(mm);
1628
			vma = find_vma_intersection(mm, nstart, end);
1629
		} else if (nstart >= vma->vm_end)
1630 1631 1632
			vma = find_vma_intersection(mm, vma->vm_end, end);

		if (!vma)
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
			break;
		/*
		 * Set [nstart; nend) to intersection of desired address
		 * range with the first VMA. Also, skip undesirable VMA types.
		 */
		nend = min(end, vma->vm_end);
		if (vma->vm_flags & (VM_IO | VM_PFNMAP))
			continue;
		if (nstart < vma->vm_start)
			nstart = vma->vm_start;
		/*
		 * Now fault in a range of pages. populate_vma_page_range()
		 * double checks the vma flags, so that it won't mlock pages
		 * if the vma was already munlocked.
		 */
		ret = populate_vma_page_range(vma, nstart, nend, &locked);
		if (ret < 0) {
			if (ignore_errors) {
				ret = 0;
				continue;	/* continue at next VMA */
			}
			break;
		}
		nend = nstart + ret * PAGE_SIZE;
		ret = 0;
	}
	if (locked)
1660
		mmap_read_unlock(mm);
1661 1662
	return ret;	/* 0 or negative error code */
}
1663
#else /* CONFIG_MMU */
1664
static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1665 1666 1667 1668 1669 1670
		unsigned long nr_pages, struct page **pages,
		struct vm_area_struct **vmas, int *locked,
		unsigned int foll_flags)
{
	struct vm_area_struct *vma;
	unsigned long vm_flags;
1671
	long i;
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691

	/* calculate required read or write permissions.
	 * If FOLL_FORCE is set, we only require the "MAY" flags.
	 */
	vm_flags  = (foll_flags & FOLL_WRITE) ?
			(VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
	vm_flags &= (foll_flags & FOLL_FORCE) ?
			(VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);

	for (i = 0; i < nr_pages; i++) {
		vma = find_vma(mm, start);
		if (!vma)
			goto finish_or_fault;

		/* protect what we can, including chardevs */
		if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
		    !(vm_flags & vma->vm_flags))
			goto finish_or_fault;

		if (pages) {
1692
			pages[i] = virt_to_page((void *)start);
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
			if (pages[i])
				get_page(pages[i]);
		}
		if (vmas)
			vmas[i] = vma;
		start = (start + PAGE_SIZE) & PAGE_MASK;
	}

	return i;

finish_or_fault:
	return i ? : -EFAULT;
}
#endif /* !CONFIG_MMU */
1707

1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
/**
 * fault_in_writeable - fault in userspace address range for writing
 * @uaddr: start of address range
 * @size: size of address range
 *
 * Returns the number of bytes not faulted in (like copy_to_user() and
 * copy_from_user()).
 */
size_t fault_in_writeable(char __user *uaddr, size_t size)
{
	char __user *start = uaddr, *end;

	if (unlikely(size == 0))
		return 0;
1722 1723
	if (!user_write_access_begin(uaddr, size))
		return size;
1724
	if (!PAGE_ALIGNED(uaddr)) {
1725
		unsafe_put_user(0, uaddr, out);
1726 1727 1728 1729 1730 1731
		uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
	}
	end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
	if (unlikely(end < start))
		end = NULL;
	while (uaddr != end) {
1732
		unsafe_put_user(0, uaddr, out);
1733 1734 1735 1736
		uaddr += PAGE_SIZE;
	}

out:
1737
	user_write_access_end();
1738 1739 1740 1741 1742 1743
	if (size > uaddr - start)
		return size - (uaddr - start);
	return 0;
}
EXPORT_SYMBOL(fault_in_writeable);

1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
/**
 * fault_in_subpage_writeable - fault in an address range for writing
 * @uaddr: start of address range
 * @size: size of address range
 *
 * Fault in a user address range for writing while checking for permissions at
 * sub-page granularity (e.g. arm64 MTE). This function should be used when
 * the caller cannot guarantee forward progress of a copy_to_user() loop.
 *
 * Returns the number of bytes not faulted in (like copy_to_user() and
 * copy_from_user()).
 */
size_t fault_in_subpage_writeable(char __user *uaddr, size_t size)
{
	size_t faulted_in;

	/*
	 * Attempt faulting in at page granularity first for page table
	 * permission checking. The arch-specific probe_subpage_writeable()
	 * functions may not check for this.
	 */
	faulted_in = size - fault_in_writeable(uaddr, size);
	if (faulted_in)
		faulted_in -= probe_subpage_writeable(uaddr, faulted_in);

	return size - faulted_in;
}
EXPORT_SYMBOL(fault_in_subpage_writeable);

1773 1774 1775 1776 1777
/*
 * fault_in_safe_writeable - fault in an address range for writing
 * @uaddr: start of address range
 * @size: length of address range
 *
1778 1779 1780
 * Faults in an address range for writing.  This is primarily useful when we
 * already know that some or all of the pages in the address range aren't in
 * memory.
1781
 *
1782
 * Unlike fault_in_writeable(), this function is non-destructive.
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
 *
 * Note that we don't pin or otherwise hold the pages referenced that we fault
 * in.  There's no guarantee that they'll stay in memory for any duration of
 * time.
 *
 * Returns the number of bytes not faulted in, like copy_to_user() and
 * copy_from_user().
 */
size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
{
1793
	unsigned long start = (unsigned long)uaddr, end;
1794
	struct mm_struct *mm = current->mm;
1795
	bool unlocked = false;
1796

1797 1798
	if (unlikely(size == 0))
		return 0;
1799
	end = PAGE_ALIGN(start + size);
1800
	if (end < start)
1801 1802
		end = 0;

1803 1804 1805
	mmap_read_lock(mm);
	do {
		if (fixup_user_fault(mm, start, FAULT_FLAG_WRITE, &unlocked))
1806
			break;
1807 1808 1809 1810 1811 1812 1813
		start = (start + PAGE_SIZE) & PAGE_MASK;
	} while (start != end);
	mmap_read_unlock(mm);

	if (size > (unsigned long)uaddr - start)
		return size - ((unsigned long)uaddr - start);
	return 0;
1814 1815 1816
}
EXPORT_SYMBOL(fault_in_safe_writeable);

1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
/**
 * fault_in_readable - fault in userspace address range for reading
 * @uaddr: start of user address range
 * @size: size of user address range
 *
 * Returns the number of bytes not faulted in (like copy_to_user() and
 * copy_from_user()).
 */
size_t fault_in_readable(const char __user *uaddr, size_t size)
{
	const char __user *start = uaddr, *end;
	volatile char c;

	if (unlikely(size == 0))
		return 0;
1832 1833
	if (!user_read_access_begin(uaddr, size))
		return size;
1834
	if (!PAGE_ALIGNED(uaddr)) {
1835
		unsafe_get_user(c, uaddr, out);
1836 1837 1838 1839 1840 1841
		uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
	}
	end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
	if (unlikely(end < start))
		end = NULL;
	while (uaddr != end) {
1842
		unsafe_get_user(c, uaddr, out);
1843 1844 1845 1846
		uaddr += PAGE_SIZE;
	}

out:
1847
	user_read_access_end();
1848 1849 1850 1851 1852 1853 1854
	(void)c;
	if (size > uaddr - start)
		return size - (uaddr - start);
	return 0;
}
EXPORT_SYMBOL(fault_in_readable);

1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
/**
 * get_dump_page() - pin user page in memory while writing it to core dump
 * @addr: user address
 *
 * Returns struct page pointer of user page pinned for dump,
 * to be freed afterwards by put_page().
 *
 * Returns NULL on any kind of failure - a hole must then be inserted into
 * the corefile, to preserve alignment with its headers; and also returns
 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
Ingo Molnar's avatar
Ingo Molnar committed
1865
 * allowing a hole to be left in the corefile to save disk space.
1866
 *
1867
 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1868 1869 1870 1871
 */
#ifdef CONFIG_ELF_CORE
struct page *get_dump_page(unsigned long addr)
{
1872
	struct mm_struct *mm = current->mm;
1873
	struct page *page;
1874 1875
	int locked = 1;
	int ret;
1876

1877
	if (mmap_read_lock_killable(mm))
1878
		return NULL;
1879 1880 1881 1882 1883
	ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
				      FOLL_FORCE | FOLL_DUMP | FOLL_GET);
	if (locked)
		mmap_read_unlock(mm);
	return (ret == 1) ? page : NULL;
1884 1885 1886
}
#endif /* CONFIG_ELF_CORE */

1887
#ifdef CONFIG_MIGRATION
1888
/*
1889
 * Returns the number of collected pages. Return value is always >= 0.
1890
 */
1891 1892 1893 1894
static unsigned long collect_longterm_unpinnable_pages(
					struct list_head *movable_page_list,
					unsigned long nr_pages,
					struct page **pages)
1895
{
1896
	unsigned long i, collected = 0;
1897
	struct folio *prev_folio = NULL;
1898
	bool drain_allow = true;
1899

1900
	for (i = 0; i < nr_pages; i++) {
1901
		struct folio *folio = page_folio(pages[i]);
1902

1903
		if (folio == prev_folio)
1904
			continue;
1905
		prev_folio = folio;
1906

1907 1908
		if (folio_is_longterm_pinnable(folio))
			continue;
1909

1910
		collected++;
1911

1912
		if (folio_is_device_coherent(folio))
1913 1914
			continue;

1915
		if (folio_test_hugetlb(folio)) {
1916
			isolate_hugetlb(&folio->page, movable_page_list);
1917 1918
			continue;
		}
1919

1920
		if (!folio_test_lru(folio) && drain_allow) {
1921 1922 1923 1924
			lru_add_drain_all();
			drain_allow = false;
		}

1925
		if (!folio_isolate_lru(folio))
1926
			continue;
1927 1928

		list_add_tail(&folio->lru, movable_page_list);
1929 1930 1931
		node_stat_mod_folio(folio,
				    NR_ISOLATED_ANON + folio_is_file_lru(folio),
				    folio_nr_pages(folio));
1932 1933
	}

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
	return collected;
}

/*
 * Unpins all pages and migrates device coherent pages and movable_page_list.
 * Returns -EAGAIN if all pages were successfully migrated or -errno for failure
 * (or partial success).
 */
static int migrate_longterm_unpinnable_pages(
					struct list_head *movable_page_list,
					unsigned long nr_pages,
					struct page **pages)
{
	int ret;
	unsigned long i;
1949

1950
	for (i = 0; i < nr_pages; i++) {
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
		struct folio *folio = page_folio(pages[i]);

		if (folio_is_device_coherent(folio)) {
			/*
			 * Migration will fail if the page is pinned, so convert
			 * the pin on the source page to a normal reference.
			 */
			pages[i] = NULL;
			folio_get(folio);
			gup_put_folio(folio, 1, FOLL_PIN);

			if (migrate_device_coherent_page(&folio->page)) {
				ret = -EBUSY;
				goto err;
			}

1967
			continue;
1968
		}
1969

1970 1971 1972 1973 1974 1975 1976
		/*
		 * We can't migrate pages with unexpected references, so drop
		 * the reference obtained by __get_user_pages_locked().
		 * Migrating pages have been added to movable_page_list after
		 * calling folio_isolate_lru() which takes a reference so the
		 * page won't be freed if it's migrating.
		 */
1977
		unpin_user_page(pages[i]);
1978
		pages[i] = NULL;
1979
	}
1980

1981
	if (!list_empty(movable_page_list)) {
1982 1983 1984 1985 1986
		struct migration_target_control mtc = {
			.nid = NUMA_NO_NODE,
			.gfp_mask = GFP_USER | __GFP_NOWARN,
		};

1987 1988 1989
		if (migrate_pages(movable_page_list, alloc_migration_target,
				  NULL, (unsigned long)&mtc, MIGRATE_SYNC,
				  MR_LONGTERM_PIN, NULL)) {
1990
			ret = -ENOMEM;
1991 1992
			goto err;
		}
1993 1994
	}

1995 1996 1997 1998 1999 2000 2001 2002 2003
	putback_movable_pages(movable_page_list);

	return -EAGAIN;

err:
	for (i = 0; i < nr_pages; i++)
		if (pages[i])
			unpin_user_page(pages[i]);
	putback_movable_pages(movable_page_list);
2004

2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
	return ret;
}

/*
 * Check whether all pages are *allowed* to be pinned. Rather confusingly, all
 * pages in the range are required to be pinned via FOLL_PIN, before calling
 * this routine.
 *
 * If any pages in the range are not allowed to be pinned, then this routine
 * will migrate those pages away, unpin all the pages in the range and return
 * -EAGAIN. The caller should re-pin the entire range with FOLL_PIN and then
 * call this routine again.
 *
 * If an error other than -EAGAIN occurs, this indicates a migration failure.
 * The caller should give up, and propagate the error back up the call stack.
 *
 * If everything is OK and all pages in the range are allowed to be pinned, then
 * this routine leaves all pages pinned and returns zero for success.
 */
static long check_and_migrate_movable_pages(unsigned long nr_pages,
					    struct page **pages)
{
	unsigned long collected;
	LIST_HEAD(movable_page_list);

	collected = collect_longterm_unpinnable_pages(&movable_page_list,
						nr_pages, pages);
	if (!collected)
		return 0;

	return migrate_longterm_unpinnable_pages(&movable_page_list, nr_pages,
						pages);
2037 2038
}
#else
2039
static long check_and_migrate_movable_pages(unsigned long nr_pages,
2040
					    struct page **pages)
2041
{
2042
	return 0;
2043
}
2044
#endif /* CONFIG_MIGRATION */
2045

2046
/*
2047 2048
 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
 * allows us to process the FOLL_LONGTERM flag.
2049
 */
2050
static long __gup_longterm_locked(struct mm_struct *mm,
2051 2052 2053 2054
				  unsigned long start,
				  unsigned long nr_pages,
				  struct page **pages,
				  struct vm_area_struct **vmas,
2055
				  int *locked,
2056
				  unsigned int gup_flags)
2057
{
2058
	bool must_unlock = false;
2059
	unsigned int flags;
2060
	long rc, nr_pinned_pages;
2061

2062 2063 2064
	if (locked && WARN_ON_ONCE(!*locked))
		return -EINVAL;

2065 2066
	if (!(gup_flags & FOLL_LONGTERM))
		return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
2067
					       locked, gup_flags);
2068 2069 2070 2071 2072 2073 2074 2075 2076

	/*
	 * If we get to this point then FOLL_LONGTERM is set, and FOLL_LONGTERM
	 * implies FOLL_PIN (although the reverse is not true). Therefore it is
	 * correct to unconditionally call check_and_migrate_movable_pages()
	 * which assumes pages have been pinned via FOLL_PIN.
	 *
	 * Enforce the above reasoning by asserting that FOLL_PIN is set.
	 */
2077 2078
	if (WARN_ON(!(gup_flags & FOLL_PIN)))
		return -EINVAL;
2079 2080
	flags = memalloc_pin_save();
	do {
2081 2082 2083 2084 2085
		if (locked && !*locked) {
			mmap_read_lock(mm);
			must_unlock = true;
			*locked = 1;
		}
2086
		nr_pinned_pages = __get_user_pages_locked(mm, start, nr_pages,
2087
							  pages, vmas, locked,
2088 2089 2090
							  gup_flags);
		if (nr_pinned_pages <= 0) {
			rc = nr_pinned_pages;
2091
			break;
2092
		}
2093
		rc = check_and_migrate_movable_pages(nr_pinned_pages, pages);
2094
	} while (rc == -EAGAIN);
2095
	memalloc_pin_restore(flags);
2096

2097 2098 2099 2100
	if (locked && *locked && must_unlock) {
		mmap_read_unlock(mm);
		*locked = 0;
	}
2101
	return rc ? rc : nr_pinned_pages;
2102
}
2103

2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
static bool is_valid_gup_flags(unsigned int gup_flags)
{
	/*
	 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
	 * never directly by the caller, so enforce that with an assertion:
	 */
	if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
		return false;
	/*
	 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
	 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
	 * FOLL_PIN.
	 */
	if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
		return false;

	return true;
}

2123
#ifdef CONFIG_MMU
2124
/**
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
 * get_user_pages_remote() - pin user pages in memory
 * @mm:		mm_struct of target mm
 * @start:	starting user address
 * @nr_pages:	number of pages from start to pin
 * @gup_flags:	flags modifying lookup behaviour
 * @pages:	array that receives pointers to the pages pinned.
 *		Should be at least nr_pages long. Or NULL, if caller
 *		only intends to ensure the pages are faulted in.
 * @vmas:	array of pointers to vmas corresponding to each page.
 *		Or NULL if the caller does not require them.
 * @locked:	pointer to lock flag indicating whether lock is held and
 *		subsequently whether VM_FAULT_RETRY functionality can be
 *		utilised. Lock must initially be held.
 *
 * Returns either number of pages pinned (which may be less than the
 * number requested), or an error. Details about the return value:
 *
 * -- If nr_pages is 0, returns 0.
 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
 * -- If nr_pages is >0, and some pages were pinned, returns the number of
 *    pages pinned. Again, this may be less than nr_pages.
 *
 * The caller is responsible for releasing returned @pages, via put_page().
 *
2149
 * @vmas are valid only as long as mmap_lock is held.
2150
 *
2151
 * Must be called with mmap_lock held for read or write.
2152
 *
2153 2154
 * get_user_pages_remote walks a process's page tables and takes a reference
 * to each struct page that each user address corresponds to at a given
2155 2156 2157 2158
 * instant. That is, it takes the page that would be accessed if a user
 * thread accesses the given user virtual address at that instant.
 *
 * This does not guarantee that the page exists in the user mappings when
2159
 * get_user_pages_remote returns, and there may even be a completely different
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
 * page there in some cases (eg. if mmapped pagecache has been invalidated
 * and subsequently re faulted). However it does guarantee that the page
 * won't be freed completely. And mostly callers simply care that the page
 * contains data that was valid *at some point in time*. Typically, an IO
 * or similar operation cannot guarantee anything stronger anyway because
 * locks can't be held over the syscall boundary.
 *
 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
 * be called after the page is finished with, and before put_page is called.
 *
2171 2172 2173 2174 2175
 * get_user_pages_remote is typically used for fewer-copy IO operations,
 * to get a handle on the memory by some means other than accesses
 * via the user virtual addresses. The pages may be submitted for
 * DMA to devices or accessed via their kernel linear mapping (via the
 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2176 2177 2178
 *
 * See also get_user_pages_fast, for performance critical applications.
 *
2179
 * get_user_pages_remote should be phased out in favor of
2180
 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2181
 * should use get_user_pages_remote because it cannot pass
2182 2183
 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
 */
2184
long get_user_pages_remote(struct mm_struct *mm,
2185 2186 2187 2188
		unsigned long start, unsigned long nr_pages,
		unsigned int gup_flags, struct page **pages,
		struct vm_area_struct **vmas, int *locked)
{
2189
	if (!is_valid_gup_flags(gup_flags))
2190 2191
		return -EINVAL;

2192 2193
	return __gup_longterm_locked(mm, start, nr_pages, pages, vmas, locked,
				     gup_flags | FOLL_TOUCH | FOLL_REMOTE);
2194 2195 2196
}
EXPORT_SYMBOL(get_user_pages_remote);

2197
#else /* CONFIG_MMU */
2198
long get_user_pages_remote(struct mm_struct *mm,
2199 2200 2201 2202 2203 2204 2205 2206
			   unsigned long start, unsigned long nr_pages,
			   unsigned int gup_flags, struct page **pages,
			   struct vm_area_struct **vmas, int *locked)
{
	return 0;
}
#endif /* !CONFIG_MMU */

2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
/**
 * get_user_pages() - pin user pages in memory
 * @start:      starting user address
 * @nr_pages:   number of pages from start to pin
 * @gup_flags:  flags modifying lookup behaviour
 * @pages:      array that receives pointers to the pages pinned.
 *              Should be at least nr_pages long. Or NULL, if caller
 *              only intends to ensure the pages are faulted in.
 * @vmas:       array of pointers to vmas corresponding to each page.
 *              Or NULL if the caller does not require them.
 *
2218 2219 2220 2221
 * This is the same as get_user_pages_remote(), just with a less-flexible
 * calling convention where we assume that the mm being operated on belongs to
 * the current task, and doesn't allow passing of a locked parameter.  We also
 * obviously don't pass FOLL_REMOTE in here.
2222 2223 2224 2225 2226
 */
long get_user_pages(unsigned long start, unsigned long nr_pages,
		unsigned int gup_flags, struct page **pages,
		struct vm_area_struct **vmas)
{
2227
	if (!is_valid_gup_flags(gup_flags))
2228 2229
		return -EINVAL;

2230
	return __gup_longterm_locked(current->mm, start, nr_pages,
2231
				     pages, vmas, NULL, gup_flags | FOLL_TOUCH);
2232 2233
}
EXPORT_SYMBOL(get_user_pages);
2234

2235
/*
2236
 * get_user_pages_unlocked() is suitable to replace the form:
2237
 *
2238
 *      mmap_read_lock(mm);
2239
 *      get_user_pages(mm, ..., pages, NULL);
2240
 *      mmap_read_unlock(mm);
2241 2242 2243
 *
 *  with:
 *
2244
 *      get_user_pages_unlocked(mm, ..., pages);
2245 2246 2247 2248
 *
 * It is functionally equivalent to get_user_pages_fast so
 * get_user_pages_fast should be used instead if specific gup_flags
 * (e.g. FOLL_FORCE) are not required.
2249
 */
2250 2251
long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
			     struct page **pages, unsigned int gup_flags)
2252 2253
{
	struct mm_struct *mm = current->mm;
2254 2255
	int locked = 1;
	long ret;
2256

2257
	mmap_read_lock(mm);
2258 2259
	ret = __gup_longterm_locked(mm, start, nr_pages, pages, NULL, &locked,
				    gup_flags | FOLL_TOUCH);
2260
	if (locked)
2261
		mmap_read_unlock(mm);
2262
	return ret;
2263
}
2264
EXPORT_SYMBOL(get_user_pages_unlocked);
2265 2266

/*
2267
 * Fast GUP
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
 *
 * get_user_pages_fast attempts to pin user pages by walking the page
 * tables directly and avoids taking locks. Thus the walker needs to be
 * protected from page table pages being freed from under it, and should
 * block any THP splits.
 *
 * One way to achieve this is to have the walker disable interrupts, and
 * rely on IPIs from the TLB flushing code blocking before the page table
 * pages are freed. This is unsuitable for architectures that do not need
 * to broadcast an IPI when invalidating TLBs.
 *
 * Another way to achieve this is to batch up page table containing pages
 * belonging to more than one mm_user, then rcu_sched a callback to free those
 * pages. Disabling interrupts will allow the fast_gup walker to both block
 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
 * (which is a relatively rare event). The code below adopts this strategy.
 *
 * Before activating this code, please be aware that the following assumptions
 * are currently made:
 *
2288
 *  *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2289
 *  free pages containing page tables or TLB flushing requires IPI broadcast.
2290 2291 2292 2293 2294 2295 2296 2297 2298
 *
 *  *) ptes can be read atomically by the architecture.
 *
 *  *) access_ok is sufficient to validate userspace address ranges.
 *
 * The last two assumptions can be relaxed by the addition of helper functions.
 *
 * This code is based heavily on the PowerPC implementation by Nick Piggin.
 */
2299
#ifdef CONFIG_HAVE_FAST_GUP
John Hubbard's avatar
John Hubbard committed
2300

2301
static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2302
					    unsigned int flags,
2303
					    struct page **pages)
2304 2305 2306 2307 2308
{
	while ((*nr) - nr_start) {
		struct page *page = pages[--(*nr)];

		ClearPageReferenced(page);
John Hubbard's avatar
John Hubbard committed
2309 2310 2311 2312
		if (flags & FOLL_PIN)
			unpin_user_page(page);
		else
			put_page(page);
2313 2314 2315
	}
}

2316
#ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
/*
 * Fast-gup relies on pte change detection to avoid concurrent pgtable
 * operations.
 *
 * To pin the page, fast-gup needs to do below in order:
 * (1) pin the page (by prefetching pte), then (2) check pte not changed.
 *
 * For the rest of pgtable operations where pgtable updates can be racy
 * with fast-gup, we need to do (1) clear pte, then (2) check whether page
 * is pinned.
 *
 * Above will work for all pte-level operations, including THP split.
 *
 * For THP collapse, it's a bit more complicated because fast-gup may be
 * walking a pgtable page that is being freed (pte is still valid but pmd
 * can be cleared already).  To avoid race in such condition, we need to
 * also check pmd here to make sure pmd doesn't change (corresponds to
 * pmdp_collapse_flush() in the THP collapse code path).
 */
static int gup_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
			 unsigned long end, unsigned int flags,
			 struct page **pages, int *nr)
2339
{
2340 2341
	struct dev_pagemap *pgmap = NULL;
	int nr_start = *nr, ret = 0;
2342 2343 2344 2345
	pte_t *ptep, *ptem;

	ptem = ptep = pte_offset_map(&pmd, addr);
	do {
2346
		pte_t pte = ptep_get_lockless(ptep);
2347 2348
		struct page *page;
		struct folio *folio;
2349

2350
		if (pte_protnone(pte) && !gup_can_follow_protnone(flags))
2351 2352
			goto pte_unmap;

2353
		if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2354 2355
			goto pte_unmap;

2356
		if (pte_devmap(pte)) {
2357 2358 2359
			if (unlikely(flags & FOLL_LONGTERM))
				goto pte_unmap;

2360 2361
			pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
			if (unlikely(!pgmap)) {
2362
				undo_dev_pagemap(nr, nr_start, flags, pages);
2363 2364 2365
				goto pte_unmap;
			}
		} else if (pte_special(pte))
2366 2367 2368 2369 2370
			goto pte_unmap;

		VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
		page = pte_page(pte);

2371 2372
		folio = try_grab_folio(page, 1, flags);
		if (!folio)
2373 2374
			goto pte_unmap;

2375
		if (unlikely(page_is_secretmem(page))) {
2376
			gup_put_folio(folio, 1, flags);
2377 2378 2379
			goto pte_unmap;
		}

2380 2381
		if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) ||
		    unlikely(pte_val(pte) != pte_val(*ptep))) {
2382
			gup_put_folio(folio, 1, flags);
2383 2384 2385
			goto pte_unmap;
		}

2386
		if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) {
2387 2388 2389 2390
			gup_put_folio(folio, 1, flags);
			goto pte_unmap;
		}

2391 2392 2393 2394 2395 2396 2397 2398 2399
		/*
		 * We need to make the page accessible if and only if we are
		 * going to access its content (the FOLL_PIN case).  Please
		 * see Documentation/core-api/pin_user_pages.rst for
		 * details.
		 */
		if (flags & FOLL_PIN) {
			ret = arch_make_page_accessible(page);
			if (ret) {
2400
				gup_put_folio(folio, 1, flags);
2401 2402 2403
				goto pte_unmap;
			}
		}
2404
		folio_set_referenced(folio);
2405 2406 2407 2408 2409 2410 2411
		pages[*nr] = page;
		(*nr)++;
	} while (ptep++, addr += PAGE_SIZE, addr != end);

	ret = 1;

pte_unmap:
2412 2413
	if (pgmap)
		put_dev_pagemap(pgmap);
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
	pte_unmap(ptem);
	return ret;
}
#else

/*
 * If we can't determine whether or not a pte is special, then fail immediately
 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
 * to be special.
 *
 * For a futex to be placed on a THP tail page, get_futex_key requires a
2425
 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2426 2427
 * useful to have gup_huge_pmd even if we can't operate on ptes.
 */
2428 2429 2430
static int gup_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
			 unsigned long end, unsigned int flags,
			 struct page **pages, int *nr)
2431 2432 2433
{
	return 0;
}
2434
#endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2435

2436
#if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2437
static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2438 2439
			     unsigned long end, unsigned int flags,
			     struct page **pages, int *nr)
2440 2441 2442 2443 2444 2445 2446 2447 2448
{
	int nr_start = *nr;
	struct dev_pagemap *pgmap = NULL;

	do {
		struct page *page = pfn_to_page(pfn);

		pgmap = get_dev_pagemap(pfn, pgmap);
		if (unlikely(!pgmap)) {
2449
			undo_dev_pagemap(nr, nr_start, flags, pages);
2450
			break;
2451 2452 2453
		}
		SetPageReferenced(page);
		pages[*nr] = page;
John Hubbard's avatar
John Hubbard committed
2454 2455
		if (unlikely(!try_grab_page(page, flags))) {
			undo_dev_pagemap(nr, nr_start, flags, pages);
2456
			break;
John Hubbard's avatar
John Hubbard committed
2457
		}
2458 2459 2460
		(*nr)++;
		pfn++;
	} while (addr += PAGE_SIZE, addr != end);
2461

2462
	put_dev_pagemap(pgmap);
2463
	return addr == end;
2464 2465
}

2466
static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2467 2468
				 unsigned long end, unsigned int flags,
				 struct page **pages, int *nr)
2469 2470
{
	unsigned long fault_pfn;
2471 2472 2473
	int nr_start = *nr;

	fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2474
	if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2475
		return 0;
2476

2477
	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2478
		undo_dev_pagemap(nr, nr_start, flags, pages);
2479 2480 2481
		return 0;
	}
	return 1;
2482 2483
}

2484
static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2485 2486
				 unsigned long end, unsigned int flags,
				 struct page **pages, int *nr)
2487 2488
{
	unsigned long fault_pfn;
2489 2490 2491
	int nr_start = *nr;

	fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2492
	if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2493
		return 0;
2494

2495
	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2496
		undo_dev_pagemap(nr, nr_start, flags, pages);
2497 2498 2499
		return 0;
	}
	return 1;
2500 2501
}
#else
2502
static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2503 2504
				 unsigned long end, unsigned int flags,
				 struct page **pages, int *nr)
2505 2506 2507 2508 2509
{
	BUILD_BUG();
	return 0;
}

2510
static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2511 2512
				 unsigned long end, unsigned int flags,
				 struct page **pages, int *nr)
2513 2514 2515 2516 2517 2518
{
	BUILD_BUG();
	return 0;
}
#endif

2519 2520 2521 2522 2523
static int record_subpages(struct page *page, unsigned long addr,
			   unsigned long end, struct page **pages)
{
	int nr;

2524 2525
	for (nr = 0; addr != end; nr++, addr += PAGE_SIZE)
		pages[nr] = nth_page(page, nr);
2526 2527 2528 2529

	return nr;
}

2530 2531 2532 2533 2534 2535 2536 2537 2538
#ifdef CONFIG_ARCH_HAS_HUGEPD
static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
				      unsigned long sz)
{
	unsigned long __boundary = (addr + sz) & ~(sz-1);
	return (__boundary - 1 < end - 1) ? __boundary : end;
}

static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2539 2540
		       unsigned long end, unsigned int flags,
		       struct page **pages, int *nr)
2541 2542
{
	unsigned long pte_end;
2543 2544
	struct page *page;
	struct folio *folio;
2545 2546 2547 2548 2549 2550 2551
	pte_t pte;
	int refs;

	pte_end = (addr + sz) & ~(sz-1);
	if (pte_end < end)
		end = pte_end;

2552
	pte = huge_ptep_get(ptep);
2553

2554
	if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2555 2556 2557 2558 2559
		return 0;

	/* hugepages are never "special" */
	VM_BUG_ON(!pfn_valid(pte_pfn(pte)));

2560
	page = nth_page(pte_page(pte), (addr & (sz - 1)) >> PAGE_SHIFT);
2561
	refs = record_subpages(page, addr, end, pages + *nr);
2562

2563 2564
	folio = try_grab_folio(page, refs, flags);
	if (!folio)
2565 2566 2567
		return 0;

	if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2568
		gup_put_folio(folio, refs, flags);
2569 2570 2571
		return 0;
	}

2572
	if (!pte_write(pte) && gup_must_unshare(NULL, flags, &folio->page)) {
2573 2574 2575 2576
		gup_put_folio(folio, refs, flags);
		return 0;
	}

2577
	*nr += refs;
2578
	folio_set_referenced(folio);
2579 2580 2581 2582
	return 1;
}

static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2583
		unsigned int pdshift, unsigned long end, unsigned int flags,
2584 2585 2586 2587 2588 2589 2590 2591 2592
		struct page **pages, int *nr)
{
	pte_t *ptep;
	unsigned long sz = 1UL << hugepd_shift(hugepd);
	unsigned long next;

	ptep = hugepte_offset(hugepd, addr, pdshift);
	do {
		next = hugepte_addr_end(addr, end, sz);
2593
		if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2594 2595 2596 2597 2598 2599 2600
			return 0;
	} while (ptep++, addr = next, addr != end);

	return 1;
}
#else
static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2601
		unsigned int pdshift, unsigned long end, unsigned int flags,
2602 2603 2604 2605 2606 2607
		struct page **pages, int *nr)
{
	return 0;
}
#endif /* CONFIG_ARCH_HAS_HUGEPD */

2608
static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2609 2610
			unsigned long end, unsigned int flags,
			struct page **pages, int *nr)
2611
{
2612 2613
	struct page *page;
	struct folio *folio;
2614 2615
	int refs;

2616
	if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2617 2618
		return 0;

2619 2620 2621
	if (pmd_devmap(orig)) {
		if (unlikely(flags & FOLL_LONGTERM))
			return 0;
2622 2623
		return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
					     pages, nr);
2624
	}
2625

2626
	page = nth_page(pmd_page(orig), (addr & ~PMD_MASK) >> PAGE_SHIFT);
2627
	refs = record_subpages(page, addr, end, pages + *nr);
2628

2629 2630
	folio = try_grab_folio(page, refs, flags);
	if (!folio)
2631 2632 2633
		return 0;

	if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2634
		gup_put_folio(folio, refs, flags);
2635 2636 2637
		return 0;
	}

2638
	if (!pmd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
2639 2640 2641 2642
		gup_put_folio(folio, refs, flags);
		return 0;
	}

2643
	*nr += refs;
2644
	folio_set_referenced(folio);
2645 2646 2647 2648
	return 1;
}

static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2649 2650
			unsigned long end, unsigned int flags,
			struct page **pages, int *nr)
2651
{
2652 2653
	struct page *page;
	struct folio *folio;
2654 2655
	int refs;

2656
	if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2657 2658
		return 0;

2659 2660 2661
	if (pud_devmap(orig)) {
		if (unlikely(flags & FOLL_LONGTERM))
			return 0;
2662 2663
		return __gup_device_huge_pud(orig, pudp, addr, end, flags,
					     pages, nr);
2664
	}
2665

2666
	page = nth_page(pud_page(orig), (addr & ~PUD_MASK) >> PAGE_SHIFT);
2667
	refs = record_subpages(page, addr, end, pages + *nr);
2668

2669 2670
	folio = try_grab_folio(page, refs, flags);
	if (!folio)
2671 2672 2673
		return 0;

	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2674
		gup_put_folio(folio, refs, flags);
2675 2676 2677
		return 0;
	}

2678
	if (!pud_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
2679 2680 2681 2682
		gup_put_folio(folio, refs, flags);
		return 0;
	}

2683
	*nr += refs;
2684
	folio_set_referenced(folio);
2685 2686 2687
	return 1;
}

2688
static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2689
			unsigned long end, unsigned int flags,
2690 2691 2692
			struct page **pages, int *nr)
{
	int refs;
2693 2694
	struct page *page;
	struct folio *folio;
2695

2696
	if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2697 2698
		return 0;

2699
	BUILD_BUG_ON(pgd_devmap(orig));
2700

2701
	page = nth_page(pgd_page(orig), (addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2702
	refs = record_subpages(page, addr, end, pages + *nr);
2703

2704 2705
	folio = try_grab_folio(page, refs, flags);
	if (!folio)
2706 2707 2708
		return 0;

	if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2709
		gup_put_folio(folio, refs, flags);
2710 2711 2712
		return 0;
	}

2713
	*nr += refs;
2714
	folio_set_referenced(folio);
2715 2716 2717
	return 1;
}

2718
static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2719
		unsigned int flags, struct page **pages, int *nr)
2720 2721 2722 2723
{
	unsigned long next;
	pmd_t *pmdp;

2724
	pmdp = pmd_offset_lockless(pudp, pud, addr);
2725
	do {
2726
		pmd_t pmd = READ_ONCE(*pmdp);
2727 2728

		next = pmd_addr_end(addr, end);
2729
		if (!pmd_present(pmd))
2730 2731
			return 0;

Yu Zhao's avatar
Yu Zhao committed
2732 2733
		if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
			     pmd_devmap(pmd))) {
2734 2735
			if (pmd_protnone(pmd) &&
			    !gup_can_follow_protnone(flags))
2736 2737
				return 0;

2738
			if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2739 2740 2741
				pages, nr))
				return 0;

2742 2743 2744 2745 2746 2747
		} else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
			/*
			 * architecture have different format for hugetlbfs
			 * pmd format and THP pmd format
			 */
			if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2748
					 PMD_SHIFT, next, flags, pages, nr))
2749
				return 0;
2750
		} else if (!gup_pte_range(pmd, pmdp, addr, next, flags, pages, nr))
2751
			return 0;
2752 2753 2754 2755 2756
	} while (pmdp++, addr = next, addr != end);

	return 1;
}

2757
static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2758
			 unsigned int flags, struct page **pages, int *nr)
2759 2760 2761 2762
{
	unsigned long next;
	pud_t *pudp;

2763
	pudp = pud_offset_lockless(p4dp, p4d, addr);
2764
	do {
2765
		pud_t pud = READ_ONCE(*pudp);
2766 2767

		next = pud_addr_end(addr, end);
Qiujun Huang's avatar
Qiujun Huang committed
2768
		if (unlikely(!pud_present(pud)))
2769
			return 0;
2770
		if (unlikely(pud_huge(pud))) {
2771
			if (!gup_huge_pud(pud, pudp, addr, next, flags,
2772 2773 2774 2775
					  pages, nr))
				return 0;
		} else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
			if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2776
					 PUD_SHIFT, next, flags, pages, nr))
2777
				return 0;
2778
		} else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2779 2780 2781 2782 2783 2784
			return 0;
	} while (pudp++, addr = next, addr != end);

	return 1;
}

2785
static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2786
			 unsigned int flags, struct page **pages, int *nr)
2787 2788 2789 2790
{
	unsigned long next;
	p4d_t *p4dp;

2791
	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2792 2793 2794 2795 2796 2797 2798 2799 2800
	do {
		p4d_t p4d = READ_ONCE(*p4dp);

		next = p4d_addr_end(addr, end);
		if (p4d_none(p4d))
			return 0;
		BUILD_BUG_ON(p4d_huge(p4d));
		if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
			if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2801
					 P4D_SHIFT, next, flags, pages, nr))
2802
				return 0;
2803
		} else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2804 2805 2806 2807 2808 2809
			return 0;
	} while (p4dp++, addr = next, addr != end);

	return 1;
}

2810
static void gup_pgd_range(unsigned long addr, unsigned long end,
2811
		unsigned int flags, struct page **pages, int *nr)
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
{
	unsigned long next;
	pgd_t *pgdp;

	pgdp = pgd_offset(current->mm, addr);
	do {
		pgd_t pgd = READ_ONCE(*pgdp);

		next = pgd_addr_end(addr, end);
		if (pgd_none(pgd))
			return;
		if (unlikely(pgd_huge(pgd))) {
2824
			if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2825 2826 2827 2828
					  pages, nr))
				return;
		} else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
			if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2829
					 PGDIR_SHIFT, next, flags, pages, nr))
2830
				return;
2831
		} else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2832 2833 2834
			return;
	} while (pgdp++, addr = next, addr != end);
}
2835 2836 2837 2838 2839 2840
#else
static inline void gup_pgd_range(unsigned long addr, unsigned long end,
		unsigned int flags, struct page **pages, int *nr)
{
}
#endif /* CONFIG_HAVE_FAST_GUP */
2841 2842 2843

#ifndef gup_fast_permitted
/*
2844
 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2845 2846
 * we need to fall back to the slow version:
 */
2847
static bool gup_fast_permitted(unsigned long start, unsigned long end)
2848
{
2849
	return true;
2850 2851 2852
}
#endif

2853 2854 2855 2856 2857 2858 2859
static unsigned long lockless_pages_from_mm(unsigned long start,
					    unsigned long end,
					    unsigned int gup_flags,
					    struct page **pages)
{
	unsigned long flags;
	int nr_pinned = 0;
2860
	unsigned seq;
2861 2862 2863 2864 2865

	if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
	    !gup_fast_permitted(start, end))
		return 0;

2866 2867 2868 2869 2870 2871
	if (gup_flags & FOLL_PIN) {
		seq = raw_read_seqcount(&current->mm->write_protect_seq);
		if (seq & 1)
			return 0;
	}

2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
	/*
	 * Disable interrupts. The nested form is used, in order to allow full,
	 * general purpose use of this routine.
	 *
	 * With interrupts disabled, we block page table pages from being freed
	 * from under us. See struct mmu_table_batch comments in
	 * include/asm-generic/tlb.h for more details.
	 *
	 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
	 * that come from THPs splitting.
	 */
	local_irq_save(flags);
	gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
	local_irq_restore(flags);
2886 2887 2888 2889 2890 2891 2892

	/*
	 * When pinning pages for DMA there could be a concurrent write protect
	 * from fork() via copy_page_range(), in this case always fail fast GUP.
	 */
	if (gup_flags & FOLL_PIN) {
		if (read_seqcount_retry(&current->mm->write_protect_seq, seq)) {
2893
			unpin_user_pages_lockless(pages, nr_pinned);
2894
			return 0;
2895 2896
		} else {
			sanity_check_pinned_pages(pages, nr_pinned);
2897 2898
		}
	}
2899 2900 2901 2902 2903
	return nr_pinned;
}

static int internal_get_user_pages_fast(unsigned long start,
					unsigned long nr_pages,
2904 2905
					unsigned int gup_flags,
					struct page **pages)
2906
{
2907 2908 2909
	unsigned long len, end;
	unsigned long nr_pinned;
	int ret;
2910

2911
	if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2912
				       FOLL_FORCE | FOLL_PIN | FOLL_GET |
2913
				       FOLL_FAST_ONLY | FOLL_NOFAULT)))
2914 2915
		return -EINVAL;

2916 2917
	if (gup_flags & FOLL_PIN)
		mm_set_has_pinned_flag(&current->mm->flags);
Peter Xu's avatar
Peter Xu committed
2918

2919
	if (!(gup_flags & FOLL_FAST_ONLY))
2920
		might_lock_read(&current->mm->mmap_lock);
2921

2922
	start = untagged_addr(start) & PAGE_MASK;
2923 2924
	len = nr_pages << PAGE_SHIFT;
	if (check_add_overflow(start, len, &end))
2925
		return 0;
2926
	if (unlikely(!access_ok((void __user *)start, len)))
2927
		return -EFAULT;
2928

2929 2930 2931
	nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
	if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
		return nr_pinned;
2932

2933 2934 2935
	/* Slow path: try to get the remaining pages with get_user_pages */
	start += nr_pinned << PAGE_SHIFT;
	pages += nr_pinned;
2936 2937
	ret = get_user_pages_unlocked(start, nr_pages - nr_pinned, pages,
				      gup_flags);
2938 2939 2940 2941 2942 2943 2944 2945
	if (ret < 0) {
		/*
		 * The caller has to unpin the pages we already pinned so
		 * returning -errno is not an option
		 */
		if (nr_pinned)
			return nr_pinned;
		return ret;
2946
	}
2947
	return ret + nr_pinned;
2948
}
2949

2950 2951 2952 2953 2954 2955 2956 2957
/**
 * get_user_pages_fast_only() - pin user pages in memory
 * @start:      starting user address
 * @nr_pages:   number of pages from start to pin
 * @gup_flags:  flags modifying pin behaviour
 * @pages:      array that receives pointers to the pages pinned.
 *              Should be at least nr_pages long.
 *
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
 * the regular GUP.
 * Note a difference with get_user_pages_fast: this always returns the
 * number of pages pinned, 0 if no pages were pinned.
 *
 * If the architecture does not support this function, simply return with no
 * pages pinned.
 *
 * Careful, careful! COW breaking can go either way, so a non-write
 * access can get ambiguous page results. If you call this function without
 * 'write' set, you'd better be sure that you're ok with that ambiguity.
 */
2970 2971
int get_user_pages_fast_only(unsigned long start, int nr_pages,
			     unsigned int gup_flags, struct page **pages)
2972
{
2973
	int nr_pinned;
2974 2975 2976
	/*
	 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
	 * because gup fast is always a "pin with a +1 page refcount" request.
2977 2978 2979
	 *
	 * FOLL_FAST_ONLY is required in order to match the API description of
	 * this routine: no fall back to regular ("slow") GUP.
2980
	 */
2981
	gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2982

2983 2984
	nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
						 pages);
2985 2986

	/*
2987 2988 2989 2990
	 * As specified in the API description above, this routine is not
	 * allowed to return negative values. However, the common core
	 * routine internal_get_user_pages_fast() *can* return -errno.
	 * Therefore, correct for that here:
2991
	 */
2992 2993
	if (nr_pinned < 0)
		nr_pinned = 0;
2994 2995 2996

	return nr_pinned;
}
2997
EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2998

2999 3000
/**
 * get_user_pages_fast() - pin user pages in memory
John Hubbard's avatar
John Hubbard committed
3001 3002 3003 3004 3005
 * @start:      starting user address
 * @nr_pages:   number of pages from start to pin
 * @gup_flags:  flags modifying pin behaviour
 * @pages:      array that receives pointers to the pages pinned.
 *              Should be at least nr_pages long.
3006
 *
3007
 * Attempt to pin user pages in memory without taking mm->mmap_lock.
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
 * If not successful, it will fall back to taking the lock and
 * calling get_user_pages().
 *
 * Returns number of pages pinned. This may be fewer than the number requested.
 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
 * -errno.
 */
int get_user_pages_fast(unsigned long start, int nr_pages,
			unsigned int gup_flags, struct page **pages)
{
3018
	if (!is_valid_gup_flags(gup_flags))
3019 3020
		return -EINVAL;

3021 3022 3023 3024 3025 3026 3027
	/*
	 * The caller may or may not have explicitly set FOLL_GET; either way is
	 * OK. However, internally (within mm/gup.c), gup fast variants must set
	 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
	 * request.
	 */
	gup_flags |= FOLL_GET;
3028 3029
	return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
}
3030
EXPORT_SYMBOL_GPL(get_user_pages_fast);
3031 3032 3033 3034

/**
 * pin_user_pages_fast() - pin user pages in memory without taking locks
 *
John Hubbard's avatar
John Hubbard committed
3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
 * @start:      starting user address
 * @nr_pages:   number of pages from start to pin
 * @gup_flags:  flags modifying pin behaviour
 * @pages:      array that receives pointers to the pages pinned.
 *              Should be at least nr_pages long.
 *
 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
 * get_user_pages_fast() for documentation on the function arguments, because
 * the arguments here are identical.
 *
 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3046
 * see Documentation/core-api/pin_user_pages.rst for further details.
3047 3048 3049 3050
 */
int pin_user_pages_fast(unsigned long start, int nr_pages,
			unsigned int gup_flags, struct page **pages)
{
John Hubbard's avatar
John Hubbard committed
3051 3052 3053 3054
	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
	if (WARN_ON_ONCE(gup_flags & FOLL_GET))
		return -EINVAL;

3055 3056 3057
	if (WARN_ON_ONCE(!pages))
		return -EINVAL;

John Hubbard's avatar
John Hubbard committed
3058 3059
	gup_flags |= FOLL_PIN;
	return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
3060 3061 3062
}
EXPORT_SYMBOL_GPL(pin_user_pages_fast);

3063
/*
3064 3065
 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
 *
 * The API rules are the same, too: no negative values may be returned.
 */
int pin_user_pages_fast_only(unsigned long start, int nr_pages,
			     unsigned int gup_flags, struct page **pages)
{
	int nr_pinned;

	/*
	 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
	 * rules require returning 0, rather than -errno:
	 */
	if (WARN_ON_ONCE(gup_flags & FOLL_GET))
		return 0;
3080 3081 3082

	if (WARN_ON_ONCE(!pages))
		return 0;
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
	/*
	 * FOLL_FAST_ONLY is required in order to match the API description of
	 * this routine: no fall back to regular ("slow") GUP.
	 */
	gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
	nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
						 pages);
	/*
	 * This routine is not allowed to return negative values. However,
	 * internal_get_user_pages_fast() *can* return -errno. Therefore,
	 * correct for that here:
	 */
	if (nr_pinned < 0)
		nr_pinned = 0;

	return nr_pinned;
}
EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);

3102
/**
3103
 * pin_user_pages_remote() - pin pages of a remote process
3104
 *
John Hubbard's avatar
John Hubbard committed
3105 3106 3107 3108 3109
 * @mm:		mm_struct of target mm
 * @start:	starting user address
 * @nr_pages:	number of pages from start to pin
 * @gup_flags:	flags modifying lookup behaviour
 * @pages:	array that receives pointers to the pages pinned.
3110
 *		Should be at least nr_pages long.
John Hubbard's avatar
John Hubbard committed
3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
 * @vmas:	array of pointers to vmas corresponding to each page.
 *		Or NULL if the caller does not require them.
 * @locked:	pointer to lock flag indicating whether lock is held and
 *		subsequently whether VM_FAULT_RETRY functionality can be
 *		utilised. Lock must initially be held.
 *
 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
 * get_user_pages_remote() for documentation on the function arguments, because
 * the arguments here are identical.
 *
 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3122
 * see Documentation/core-api/pin_user_pages.rst for details.
3123
 */
3124
long pin_user_pages_remote(struct mm_struct *mm,
3125 3126 3127 3128
			   unsigned long start, unsigned long nr_pages,
			   unsigned int gup_flags, struct page **pages,
			   struct vm_area_struct **vmas, int *locked)
{
John Hubbard's avatar
John Hubbard committed
3129 3130 3131 3132
	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
	if (WARN_ON_ONCE(gup_flags & FOLL_GET))
		return -EINVAL;

3133 3134 3135
	if (WARN_ON_ONCE(!pages))
		return -EINVAL;

3136 3137 3138
	return __gup_longterm_locked(mm, start, nr_pages, pages, vmas, locked,
				     gup_flags | FOLL_PIN | FOLL_TOUCH |
					     FOLL_REMOTE);
3139 3140 3141 3142 3143 3144
}
EXPORT_SYMBOL(pin_user_pages_remote);

/**
 * pin_user_pages() - pin user pages in memory for use by other devices
 *
John Hubbard's avatar
John Hubbard committed
3145 3146 3147 3148
 * @start:	starting user address
 * @nr_pages:	number of pages from start to pin
 * @gup_flags:	flags modifying lookup behaviour
 * @pages:	array that receives pointers to the pages pinned.
3149
 *		Should be at least nr_pages long.
John Hubbard's avatar
John Hubbard committed
3150 3151 3152 3153 3154 3155 3156
 * @vmas:	array of pointers to vmas corresponding to each page.
 *		Or NULL if the caller does not require them.
 *
 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
 * FOLL_PIN is set.
 *
 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3157
 * see Documentation/core-api/pin_user_pages.rst for details.
3158 3159 3160 3161 3162
 */
long pin_user_pages(unsigned long start, unsigned long nr_pages,
		    unsigned int gup_flags, struct page **pages,
		    struct vm_area_struct **vmas)
{
John Hubbard's avatar
John Hubbard committed
3163 3164 3165 3166
	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
	if (WARN_ON_ONCE(gup_flags & FOLL_GET))
		return -EINVAL;

3167 3168 3169
	if (WARN_ON_ONCE(!pages))
		return -EINVAL;

John Hubbard's avatar
John Hubbard committed
3170
	gup_flags |= FOLL_PIN;
3171
	return __gup_longterm_locked(current->mm, start, nr_pages,
3172
				     pages, vmas, NULL, gup_flags);
3173 3174
}
EXPORT_SYMBOL(pin_user_pages);
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187

/*
 * pin_user_pages_unlocked() is the FOLL_PIN variant of
 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
 * FOLL_PIN and rejects FOLL_GET.
 */
long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
			     struct page **pages, unsigned int gup_flags)
{
	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
	if (WARN_ON_ONCE(gup_flags & FOLL_GET))
		return -EINVAL;

3188 3189 3190
	if (WARN_ON_ONCE(!pages))
		return -EINVAL;

3191 3192 3193 3194
	gup_flags |= FOLL_PIN;
	return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
}
EXPORT_SYMBOL(pin_user_pages_unlocked);