xref: /openbmc/linux/mm/migrate_device.c (revision 724ba675)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Device Memory Migration functionality.
4  *
5  * Originally written by Jérôme Glisse.
6  */
7 #include <linux/export.h>
8 #include <linux/memremap.h>
9 #include <linux/migrate.h>
10 #include <linux/mm.h>
11 #include <linux/mm_inline.h>
12 #include <linux/mmu_notifier.h>
13 #include <linux/oom.h>
14 #include <linux/pagewalk.h>
15 #include <linux/rmap.h>
16 #include <linux/swapops.h>
17 #include <asm/tlbflush.h>
18 #include "internal.h"
19 
20 static int migrate_vma_collect_skip(unsigned long start,
21 				    unsigned long end,
22 				    struct mm_walk *walk)
23 {
24 	struct migrate_vma *migrate = walk->private;
25 	unsigned long addr;
26 
27 	for (addr = start; addr < end; addr += PAGE_SIZE) {
28 		migrate->dst[migrate->npages] = 0;
29 		migrate->src[migrate->npages++] = 0;
30 	}
31 
32 	return 0;
33 }
34 
35 static int migrate_vma_collect_hole(unsigned long start,
36 				    unsigned long end,
37 				    __always_unused int depth,
38 				    struct mm_walk *walk)
39 {
40 	struct migrate_vma *migrate = walk->private;
41 	unsigned long addr;
42 
43 	/* Only allow populating anonymous memory. */
44 	if (!vma_is_anonymous(walk->vma))
45 		return migrate_vma_collect_skip(start, end, walk);
46 
47 	for (addr = start; addr < end; addr += PAGE_SIZE) {
48 		migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
49 		migrate->dst[migrate->npages] = 0;
50 		migrate->npages++;
51 		migrate->cpages++;
52 	}
53 
54 	return 0;
55 }
56 
57 static int migrate_vma_collect_pmd(pmd_t *pmdp,
58 				   unsigned long start,
59 				   unsigned long end,
60 				   struct mm_walk *walk)
61 {
62 	struct migrate_vma *migrate = walk->private;
63 	struct vm_area_struct *vma = walk->vma;
64 	struct mm_struct *mm = vma->vm_mm;
65 	unsigned long addr = start, unmapped = 0;
66 	spinlock_t *ptl;
67 	pte_t *ptep;
68 
69 again:
70 	if (pmd_none(*pmdp))
71 		return migrate_vma_collect_hole(start, end, -1, walk);
72 
73 	if (pmd_trans_huge(*pmdp)) {
74 		struct page *page;
75 
76 		ptl = pmd_lock(mm, pmdp);
77 		if (unlikely(!pmd_trans_huge(*pmdp))) {
78 			spin_unlock(ptl);
79 			goto again;
80 		}
81 
82 		page = pmd_page(*pmdp);
83 		if (is_huge_zero_page(page)) {
84 			spin_unlock(ptl);
85 			split_huge_pmd(vma, pmdp, addr);
86 			if (pmd_trans_unstable(pmdp))
87 				return migrate_vma_collect_skip(start, end,
88 								walk);
89 		} else {
90 			int ret;
91 
92 			get_page(page);
93 			spin_unlock(ptl);
94 			if (unlikely(!trylock_page(page)))
95 				return migrate_vma_collect_skip(start, end,
96 								walk);
97 			ret = split_huge_page(page);
98 			unlock_page(page);
99 			put_page(page);
100 			if (ret)
101 				return migrate_vma_collect_skip(start, end,
102 								walk);
103 			if (pmd_none(*pmdp))
104 				return migrate_vma_collect_hole(start, end, -1,
105 								walk);
106 		}
107 	}
108 
109 	if (unlikely(pmd_bad(*pmdp)))
110 		return migrate_vma_collect_skip(start, end, walk);
111 
112 	ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
113 	arch_enter_lazy_mmu_mode();
114 
115 	for (; addr < end; addr += PAGE_SIZE, ptep++) {
116 		unsigned long mpfn = 0, pfn;
117 		struct page *page;
118 		swp_entry_t entry;
119 		pte_t pte;
120 
121 		pte = *ptep;
122 
123 		if (pte_none(pte)) {
124 			if (vma_is_anonymous(vma)) {
125 				mpfn = MIGRATE_PFN_MIGRATE;
126 				migrate->cpages++;
127 			}
128 			goto next;
129 		}
130 
131 		if (!pte_present(pte)) {
132 			/*
133 			 * Only care about unaddressable device page special
134 			 * page table entry. Other special swap entries are not
135 			 * migratable, and we ignore regular swapped page.
136 			 */
137 			entry = pte_to_swp_entry(pte);
138 			if (!is_device_private_entry(entry))
139 				goto next;
140 
141 			page = pfn_swap_entry_to_page(entry);
142 			if (!(migrate->flags &
143 				MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
144 			    page->pgmap->owner != migrate->pgmap_owner)
145 				goto next;
146 
147 			mpfn = migrate_pfn(page_to_pfn(page)) |
148 					MIGRATE_PFN_MIGRATE;
149 			if (is_writable_device_private_entry(entry))
150 				mpfn |= MIGRATE_PFN_WRITE;
151 		} else {
152 			pfn = pte_pfn(pte);
153 			if (is_zero_pfn(pfn) &&
154 			    (migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
155 				mpfn = MIGRATE_PFN_MIGRATE;
156 				migrate->cpages++;
157 				goto next;
158 			}
159 			page = vm_normal_page(migrate->vma, addr, pte);
160 			if (page && !is_zone_device_page(page) &&
161 			    !(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
162 				goto next;
163 			else if (page && is_device_coherent_page(page) &&
164 			    (!(migrate->flags & MIGRATE_VMA_SELECT_DEVICE_COHERENT) ||
165 			     page->pgmap->owner != migrate->pgmap_owner))
166 				goto next;
167 			mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
168 			mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
169 		}
170 
171 		/* FIXME support THP */
172 		if (!page || !page->mapping || PageTransCompound(page)) {
173 			mpfn = 0;
174 			goto next;
175 		}
176 
177 		/*
178 		 * By getting a reference on the page we pin it and that blocks
179 		 * any kind of migration. Side effect is that it "freezes" the
180 		 * pte.
181 		 *
182 		 * We drop this reference after isolating the page from the lru
183 		 * for non device page (device page are not on the lru and thus
184 		 * can't be dropped from it).
185 		 */
186 		get_page(page);
187 
188 		/*
189 		 * We rely on trylock_page() to avoid deadlock between
190 		 * concurrent migrations where each is waiting on the others
191 		 * page lock. If we can't immediately lock the page we fail this
192 		 * migration as it is only best effort anyway.
193 		 *
194 		 * If we can lock the page it's safe to set up a migration entry
195 		 * now. In the common case where the page is mapped once in a
196 		 * single process setting up the migration entry now is an
197 		 * optimisation to avoid walking the rmap later with
198 		 * try_to_migrate().
199 		 */
200 		if (trylock_page(page)) {
201 			bool anon_exclusive;
202 			pte_t swp_pte;
203 
204 			flush_cache_page(vma, addr, pte_pfn(*ptep));
205 			anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
206 			if (anon_exclusive) {
207 				pte = ptep_clear_flush(vma, addr, ptep);
208 
209 				if (page_try_share_anon_rmap(page)) {
210 					set_pte_at(mm, addr, ptep, pte);
211 					unlock_page(page);
212 					put_page(page);
213 					mpfn = 0;
214 					goto next;
215 				}
216 			} else {
217 				pte = ptep_get_and_clear(mm, addr, ptep);
218 			}
219 
220 			migrate->cpages++;
221 
222 			/* Set the dirty flag on the folio now the pte is gone. */
223 			if (pte_dirty(pte))
224 				folio_mark_dirty(page_folio(page));
225 
226 			/* Setup special migration page table entry */
227 			if (mpfn & MIGRATE_PFN_WRITE)
228 				entry = make_writable_migration_entry(
229 							page_to_pfn(page));
230 			else if (anon_exclusive)
231 				entry = make_readable_exclusive_migration_entry(
232 							page_to_pfn(page));
233 			else
234 				entry = make_readable_migration_entry(
235 							page_to_pfn(page));
236 			if (pte_present(pte)) {
237 				if (pte_young(pte))
238 					entry = make_migration_entry_young(entry);
239 				if (pte_dirty(pte))
240 					entry = make_migration_entry_dirty(entry);
241 			}
242 			swp_pte = swp_entry_to_pte(entry);
243 			if (pte_present(pte)) {
244 				if (pte_soft_dirty(pte))
245 					swp_pte = pte_swp_mksoft_dirty(swp_pte);
246 				if (pte_uffd_wp(pte))
247 					swp_pte = pte_swp_mkuffd_wp(swp_pte);
248 			} else {
249 				if (pte_swp_soft_dirty(pte))
250 					swp_pte = pte_swp_mksoft_dirty(swp_pte);
251 				if (pte_swp_uffd_wp(pte))
252 					swp_pte = pte_swp_mkuffd_wp(swp_pte);
253 			}
254 			set_pte_at(mm, addr, ptep, swp_pte);
255 
256 			/*
257 			 * This is like regular unmap: we remove the rmap and
258 			 * drop page refcount. Page won't be freed, as we took
259 			 * a reference just above.
260 			 */
261 			page_remove_rmap(page, vma, false);
262 			put_page(page);
263 
264 			if (pte_present(pte))
265 				unmapped++;
266 		} else {
267 			put_page(page);
268 			mpfn = 0;
269 		}
270 
271 next:
272 		migrate->dst[migrate->npages] = 0;
273 		migrate->src[migrate->npages++] = mpfn;
274 	}
275 
276 	/* Only flush the TLB if we actually modified any entries */
277 	if (unmapped)
278 		flush_tlb_range(walk->vma, start, end);
279 
280 	arch_leave_lazy_mmu_mode();
281 	pte_unmap_unlock(ptep - 1, ptl);
282 
283 	return 0;
284 }
285 
286 static const struct mm_walk_ops migrate_vma_walk_ops = {
287 	.pmd_entry		= migrate_vma_collect_pmd,
288 	.pte_hole		= migrate_vma_collect_hole,
289 };
290 
291 /*
292  * migrate_vma_collect() - collect pages over a range of virtual addresses
293  * @migrate: migrate struct containing all migration information
294  *
295  * This will walk the CPU page table. For each virtual address backed by a
296  * valid page, it updates the src array and takes a reference on the page, in
297  * order to pin the page until we lock it and unmap it.
298  */
299 static void migrate_vma_collect(struct migrate_vma *migrate)
300 {
301 	struct mmu_notifier_range range;
302 
303 	/*
304 	 * Note that the pgmap_owner is passed to the mmu notifier callback so
305 	 * that the registered device driver can skip invalidating device
306 	 * private page mappings that won't be migrated.
307 	 */
308 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
309 		migrate->vma->vm_mm, migrate->start, migrate->end,
310 		migrate->pgmap_owner);
311 	mmu_notifier_invalidate_range_start(&range);
312 
313 	walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
314 			&migrate_vma_walk_ops, migrate);
315 
316 	mmu_notifier_invalidate_range_end(&range);
317 	migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
318 }
319 
320 /*
321  * migrate_vma_check_page() - check if page is pinned or not
322  * @page: struct page to check
323  *
324  * Pinned pages cannot be migrated. This is the same test as in
325  * folio_migrate_mapping(), except that here we allow migration of a
326  * ZONE_DEVICE page.
327  */
328 static bool migrate_vma_check_page(struct page *page, struct page *fault_page)
329 {
330 	/*
331 	 * One extra ref because caller holds an extra reference, either from
332 	 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
333 	 * a device page.
334 	 */
335 	int extra = 1 + (page == fault_page);
336 
337 	/*
338 	 * FIXME support THP (transparent huge page), it is bit more complex to
339 	 * check them than regular pages, because they can be mapped with a pmd
340 	 * or with a pte (split pte mapping).
341 	 */
342 	if (PageCompound(page))
343 		return false;
344 
345 	/* Page from ZONE_DEVICE have one extra reference */
346 	if (is_zone_device_page(page))
347 		extra++;
348 
349 	/* For file back page */
350 	if (page_mapping(page))
351 		extra += 1 + page_has_private(page);
352 
353 	if ((page_count(page) - extra) > page_mapcount(page))
354 		return false;
355 
356 	return true;
357 }
358 
359 /*
360  * Unmaps pages for migration. Returns number of source pfns marked as
361  * migrating.
362  */
363 static unsigned long migrate_device_unmap(unsigned long *src_pfns,
364 					  unsigned long npages,
365 					  struct page *fault_page)
366 {
367 	unsigned long i, restore = 0;
368 	bool allow_drain = true;
369 	unsigned long unmapped = 0;
370 
371 	lru_add_drain();
372 
373 	for (i = 0; i < npages; i++) {
374 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
375 		struct folio *folio;
376 
377 		if (!page) {
378 			if (src_pfns[i] & MIGRATE_PFN_MIGRATE)
379 				unmapped++;
380 			continue;
381 		}
382 
383 		/* ZONE_DEVICE pages are not on LRU */
384 		if (!is_zone_device_page(page)) {
385 			if (!PageLRU(page) && allow_drain) {
386 				/* Drain CPU's pagevec */
387 				lru_add_drain_all();
388 				allow_drain = false;
389 			}
390 
391 			if (!isolate_lru_page(page)) {
392 				src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
393 				restore++;
394 				continue;
395 			}
396 
397 			/* Drop the reference we took in collect */
398 			put_page(page);
399 		}
400 
401 		folio = page_folio(page);
402 		if (folio_mapped(folio))
403 			try_to_migrate(folio, 0);
404 
405 		if (page_mapped(page) ||
406 		    !migrate_vma_check_page(page, fault_page)) {
407 			if (!is_zone_device_page(page)) {
408 				get_page(page);
409 				putback_lru_page(page);
410 			}
411 
412 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
413 			restore++;
414 			continue;
415 		}
416 
417 		unmapped++;
418 	}
419 
420 	for (i = 0; i < npages && restore; i++) {
421 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
422 		struct folio *folio;
423 
424 		if (!page || (src_pfns[i] & MIGRATE_PFN_MIGRATE))
425 			continue;
426 
427 		folio = page_folio(page);
428 		remove_migration_ptes(folio, folio, false);
429 
430 		src_pfns[i] = 0;
431 		folio_unlock(folio);
432 		folio_put(folio);
433 		restore--;
434 	}
435 
436 	return unmapped;
437 }
438 
439 /*
440  * migrate_vma_unmap() - replace page mapping with special migration pte entry
441  * @migrate: migrate struct containing all migration information
442  *
443  * Isolate pages from the LRU and replace mappings (CPU page table pte) with a
444  * special migration pte entry and check if it has been pinned. Pinned pages are
445  * restored because we cannot migrate them.
446  *
447  * This is the last step before we call the device driver callback to allocate
448  * destination memory and copy contents of original page over to new page.
449  */
450 static void migrate_vma_unmap(struct migrate_vma *migrate)
451 {
452 	migrate->cpages = migrate_device_unmap(migrate->src, migrate->npages,
453 					migrate->fault_page);
454 }
455 
456 /**
457  * migrate_vma_setup() - prepare to migrate a range of memory
458  * @args: contains the vma, start, and pfns arrays for the migration
459  *
460  * Returns: negative errno on failures, 0 when 0 or more pages were migrated
461  * without an error.
462  *
463  * Prepare to migrate a range of memory virtual address range by collecting all
464  * the pages backing each virtual address in the range, saving them inside the
465  * src array.  Then lock those pages and unmap them. Once the pages are locked
466  * and unmapped, check whether each page is pinned or not.  Pages that aren't
467  * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
468  * corresponding src array entry.  Then restores any pages that are pinned, by
469  * remapping and unlocking those pages.
470  *
471  * The caller should then allocate destination memory and copy source memory to
472  * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
473  * flag set).  Once these are allocated and copied, the caller must update each
474  * corresponding entry in the dst array with the pfn value of the destination
475  * page and with MIGRATE_PFN_VALID. Destination pages must be locked via
476  * lock_page().
477  *
478  * Note that the caller does not have to migrate all the pages that are marked
479  * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
480  * device memory to system memory.  If the caller cannot migrate a device page
481  * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
482  * consequences for the userspace process, so it must be avoided if at all
483  * possible.
484  *
485  * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
486  * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
487  * allowing the caller to allocate device memory for those unbacked virtual
488  * addresses.  For this the caller simply has to allocate device memory and
489  * properly set the destination entry like for regular migration.  Note that
490  * this can still fail, and thus inside the device driver you must check if the
491  * migration was successful for those entries after calling migrate_vma_pages(),
492  * just like for regular migration.
493  *
494  * After that, the callers must call migrate_vma_pages() to go over each entry
495  * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
496  * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
497  * then migrate_vma_pages() to migrate struct page information from the source
498  * struct page to the destination struct page.  If it fails to migrate the
499  * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
500  * src array.
501  *
502  * At this point all successfully migrated pages have an entry in the src
503  * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
504  * array entry with MIGRATE_PFN_VALID flag set.
505  *
506  * Once migrate_vma_pages() returns the caller may inspect which pages were
507  * successfully migrated, and which were not.  Successfully migrated pages will
508  * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
509  *
510  * It is safe to update device page table after migrate_vma_pages() because
511  * both destination and source page are still locked, and the mmap_lock is held
512  * in read mode (hence no one can unmap the range being migrated).
513  *
514  * Once the caller is done cleaning up things and updating its page table (if it
515  * chose to do so, this is not an obligation) it finally calls
516  * migrate_vma_finalize() to update the CPU page table to point to new pages
517  * for successfully migrated pages or otherwise restore the CPU page table to
518  * point to the original source pages.
519  */
520 int migrate_vma_setup(struct migrate_vma *args)
521 {
522 	long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
523 
524 	args->start &= PAGE_MASK;
525 	args->end &= PAGE_MASK;
526 	if (!args->vma || is_vm_hugetlb_page(args->vma) ||
527 	    (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
528 		return -EINVAL;
529 	if (nr_pages <= 0)
530 		return -EINVAL;
531 	if (args->start < args->vma->vm_start ||
532 	    args->start >= args->vma->vm_end)
533 		return -EINVAL;
534 	if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
535 		return -EINVAL;
536 	if (!args->src || !args->dst)
537 		return -EINVAL;
538 	if (args->fault_page && !is_device_private_page(args->fault_page))
539 		return -EINVAL;
540 
541 	memset(args->src, 0, sizeof(*args->src) * nr_pages);
542 	args->cpages = 0;
543 	args->npages = 0;
544 
545 	migrate_vma_collect(args);
546 
547 	if (args->cpages)
548 		migrate_vma_unmap(args);
549 
550 	/*
551 	 * At this point pages are locked and unmapped, and thus they have
552 	 * stable content and can safely be copied to destination memory that
553 	 * is allocated by the drivers.
554 	 */
555 	return 0;
556 
557 }
558 EXPORT_SYMBOL(migrate_vma_setup);
559 
560 /*
561  * This code closely matches the code in:
562  *   __handle_mm_fault()
563  *     handle_pte_fault()
564  *       do_anonymous_page()
565  * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
566  * private or coherent page.
567  */
568 static void migrate_vma_insert_page(struct migrate_vma *migrate,
569 				    unsigned long addr,
570 				    struct page *page,
571 				    unsigned long *src)
572 {
573 	struct vm_area_struct *vma = migrate->vma;
574 	struct mm_struct *mm = vma->vm_mm;
575 	bool flush = false;
576 	spinlock_t *ptl;
577 	pte_t entry;
578 	pgd_t *pgdp;
579 	p4d_t *p4dp;
580 	pud_t *pudp;
581 	pmd_t *pmdp;
582 	pte_t *ptep;
583 
584 	/* Only allow populating anonymous memory */
585 	if (!vma_is_anonymous(vma))
586 		goto abort;
587 
588 	pgdp = pgd_offset(mm, addr);
589 	p4dp = p4d_alloc(mm, pgdp, addr);
590 	if (!p4dp)
591 		goto abort;
592 	pudp = pud_alloc(mm, p4dp, addr);
593 	if (!pudp)
594 		goto abort;
595 	pmdp = pmd_alloc(mm, pudp, addr);
596 	if (!pmdp)
597 		goto abort;
598 
599 	if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
600 		goto abort;
601 
602 	/*
603 	 * Use pte_alloc() instead of pte_alloc_map().  We can't run
604 	 * pte_offset_map() on pmds where a huge pmd might be created
605 	 * from a different thread.
606 	 *
607 	 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
608 	 * parallel threads are excluded by other means.
609 	 *
610 	 * Here we only have mmap_read_lock(mm).
611 	 */
612 	if (pte_alloc(mm, pmdp))
613 		goto abort;
614 
615 	/* See the comment in pte_alloc_one_map() */
616 	if (unlikely(pmd_trans_unstable(pmdp)))
617 		goto abort;
618 
619 	if (unlikely(anon_vma_prepare(vma)))
620 		goto abort;
621 	if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
622 		goto abort;
623 
624 	/*
625 	 * The memory barrier inside __SetPageUptodate makes sure that
626 	 * preceding stores to the page contents become visible before
627 	 * the set_pte_at() write.
628 	 */
629 	__SetPageUptodate(page);
630 
631 	if (is_device_private_page(page)) {
632 		swp_entry_t swp_entry;
633 
634 		if (vma->vm_flags & VM_WRITE)
635 			swp_entry = make_writable_device_private_entry(
636 						page_to_pfn(page));
637 		else
638 			swp_entry = make_readable_device_private_entry(
639 						page_to_pfn(page));
640 		entry = swp_entry_to_pte(swp_entry);
641 	} else {
642 		if (is_zone_device_page(page) &&
643 		    !is_device_coherent_page(page)) {
644 			pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
645 			goto abort;
646 		}
647 		entry = mk_pte(page, vma->vm_page_prot);
648 		if (vma->vm_flags & VM_WRITE)
649 			entry = pte_mkwrite(pte_mkdirty(entry));
650 	}
651 
652 	ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
653 
654 	if (check_stable_address_space(mm))
655 		goto unlock_abort;
656 
657 	if (pte_present(*ptep)) {
658 		unsigned long pfn = pte_pfn(*ptep);
659 
660 		if (!is_zero_pfn(pfn))
661 			goto unlock_abort;
662 		flush = true;
663 	} else if (!pte_none(*ptep))
664 		goto unlock_abort;
665 
666 	/*
667 	 * Check for userfaultfd but do not deliver the fault. Instead,
668 	 * just back off.
669 	 */
670 	if (userfaultfd_missing(vma))
671 		goto unlock_abort;
672 
673 	inc_mm_counter(mm, MM_ANONPAGES);
674 	page_add_new_anon_rmap(page, vma, addr);
675 	if (!is_zone_device_page(page))
676 		lru_cache_add_inactive_or_unevictable(page, vma);
677 	get_page(page);
678 
679 	if (flush) {
680 		flush_cache_page(vma, addr, pte_pfn(*ptep));
681 		ptep_clear_flush_notify(vma, addr, ptep);
682 		set_pte_at_notify(mm, addr, ptep, entry);
683 		update_mmu_cache(vma, addr, ptep);
684 	} else {
685 		/* No need to invalidate - it was non-present before */
686 		set_pte_at(mm, addr, ptep, entry);
687 		update_mmu_cache(vma, addr, ptep);
688 	}
689 
690 	pte_unmap_unlock(ptep, ptl);
691 	*src = MIGRATE_PFN_MIGRATE;
692 	return;
693 
694 unlock_abort:
695 	pte_unmap_unlock(ptep, ptl);
696 abort:
697 	*src &= ~MIGRATE_PFN_MIGRATE;
698 }
699 
700 static void __migrate_device_pages(unsigned long *src_pfns,
701 				unsigned long *dst_pfns, unsigned long npages,
702 				struct migrate_vma *migrate)
703 {
704 	struct mmu_notifier_range range;
705 	unsigned long i;
706 	bool notified = false;
707 
708 	for (i = 0; i < npages; i++) {
709 		struct page *newpage = migrate_pfn_to_page(dst_pfns[i]);
710 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
711 		struct address_space *mapping;
712 		int r;
713 
714 		if (!newpage) {
715 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
716 			continue;
717 		}
718 
719 		if (!page) {
720 			unsigned long addr;
721 
722 			if (!(src_pfns[i] & MIGRATE_PFN_MIGRATE))
723 				continue;
724 
725 			/*
726 			 * The only time there is no vma is when called from
727 			 * migrate_device_coherent_page(). However this isn't
728 			 * called if the page could not be unmapped.
729 			 */
730 			VM_BUG_ON(!migrate);
731 			addr = migrate->start + i*PAGE_SIZE;
732 			if (!notified) {
733 				notified = true;
734 
735 				mmu_notifier_range_init_owner(&range,
736 					MMU_NOTIFY_MIGRATE, 0,
737 					migrate->vma->vm_mm, addr, migrate->end,
738 					migrate->pgmap_owner);
739 				mmu_notifier_invalidate_range_start(&range);
740 			}
741 			migrate_vma_insert_page(migrate, addr, newpage,
742 						&src_pfns[i]);
743 			continue;
744 		}
745 
746 		mapping = page_mapping(page);
747 
748 		if (is_device_private_page(newpage) ||
749 		    is_device_coherent_page(newpage)) {
750 			/*
751 			 * For now only support anonymous memory migrating to
752 			 * device private or coherent memory.
753 			 */
754 			if (mapping) {
755 				src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
756 				continue;
757 			}
758 		} else if (is_zone_device_page(newpage)) {
759 			/*
760 			 * Other types of ZONE_DEVICE page are not supported.
761 			 */
762 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
763 			continue;
764 		}
765 
766 		if (migrate && migrate->fault_page == page)
767 			r = migrate_folio_extra(mapping, page_folio(newpage),
768 						page_folio(page),
769 						MIGRATE_SYNC_NO_COPY, 1);
770 		else
771 			r = migrate_folio(mapping, page_folio(newpage),
772 					page_folio(page), MIGRATE_SYNC_NO_COPY);
773 		if (r != MIGRATEPAGE_SUCCESS)
774 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
775 	}
776 
777 	/*
778 	 * No need to double call mmu_notifier->invalidate_range() callback as
779 	 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
780 	 * did already call it.
781 	 */
782 	if (notified)
783 		mmu_notifier_invalidate_range_only_end(&range);
784 }
785 
786 /**
787  * migrate_device_pages() - migrate meta-data from src page to dst page
788  * @src_pfns: src_pfns returned from migrate_device_range()
789  * @dst_pfns: array of pfns allocated by the driver to migrate memory to
790  * @npages: number of pages in the range
791  *
792  * Equivalent to migrate_vma_pages(). This is called to migrate struct page
793  * meta-data from source struct page to destination.
794  */
795 void migrate_device_pages(unsigned long *src_pfns, unsigned long *dst_pfns,
796 			unsigned long npages)
797 {
798 	__migrate_device_pages(src_pfns, dst_pfns, npages, NULL);
799 }
800 EXPORT_SYMBOL(migrate_device_pages);
801 
802 /**
803  * migrate_vma_pages() - migrate meta-data from src page to dst page
804  * @migrate: migrate struct containing all migration information
805  *
806  * This migrates struct page meta-data from source struct page to destination
807  * struct page. This effectively finishes the migration from source page to the
808  * destination page.
809  */
810 void migrate_vma_pages(struct migrate_vma *migrate)
811 {
812 	__migrate_device_pages(migrate->src, migrate->dst, migrate->npages, migrate);
813 }
814 EXPORT_SYMBOL(migrate_vma_pages);
815 
816 /*
817  * migrate_device_finalize() - complete page migration
818  * @src_pfns: src_pfns returned from migrate_device_range()
819  * @dst_pfns: array of pfns allocated by the driver to migrate memory to
820  * @npages: number of pages in the range
821  *
822  * Completes migration of the page by removing special migration entries.
823  * Drivers must ensure copying of page data is complete and visible to the CPU
824  * before calling this.
825  */
826 void migrate_device_finalize(unsigned long *src_pfns,
827 			unsigned long *dst_pfns, unsigned long npages)
828 {
829 	unsigned long i;
830 
831 	for (i = 0; i < npages; i++) {
832 		struct folio *dst, *src;
833 		struct page *newpage = migrate_pfn_to_page(dst_pfns[i]);
834 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
835 
836 		if (!page) {
837 			if (newpage) {
838 				unlock_page(newpage);
839 				put_page(newpage);
840 			}
841 			continue;
842 		}
843 
844 		if (!(src_pfns[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
845 			if (newpage) {
846 				unlock_page(newpage);
847 				put_page(newpage);
848 			}
849 			newpage = page;
850 		}
851 
852 		src = page_folio(page);
853 		dst = page_folio(newpage);
854 		remove_migration_ptes(src, dst, false);
855 		folio_unlock(src);
856 
857 		if (is_zone_device_page(page))
858 			put_page(page);
859 		else
860 			putback_lru_page(page);
861 
862 		if (newpage != page) {
863 			unlock_page(newpage);
864 			if (is_zone_device_page(newpage))
865 				put_page(newpage);
866 			else
867 				putback_lru_page(newpage);
868 		}
869 	}
870 }
871 EXPORT_SYMBOL(migrate_device_finalize);
872 
873 /**
874  * migrate_vma_finalize() - restore CPU page table entry
875  * @migrate: migrate struct containing all migration information
876  *
877  * This replaces the special migration pte entry with either a mapping to the
878  * new page if migration was successful for that page, or to the original page
879  * otherwise.
880  *
881  * This also unlocks the pages and puts them back on the lru, or drops the extra
882  * refcount, for device pages.
883  */
884 void migrate_vma_finalize(struct migrate_vma *migrate)
885 {
886 	migrate_device_finalize(migrate->src, migrate->dst, migrate->npages);
887 }
888 EXPORT_SYMBOL(migrate_vma_finalize);
889 
890 /**
891  * migrate_device_range() - migrate device private pfns to normal memory.
892  * @src_pfns: array large enough to hold migrating source device private pfns.
893  * @start: starting pfn in the range to migrate.
894  * @npages: number of pages to migrate.
895  *
896  * migrate_vma_setup() is similar in concept to migrate_vma_setup() except that
897  * instead of looking up pages based on virtual address mappings a range of
898  * device pfns that should be migrated to system memory is used instead.
899  *
900  * This is useful when a driver needs to free device memory but doesn't know the
901  * virtual mappings of every page that may be in device memory. For example this
902  * is often the case when a driver is being unloaded or unbound from a device.
903  *
904  * Like migrate_vma_setup() this function will take a reference and lock any
905  * migrating pages that aren't free before unmapping them. Drivers may then
906  * allocate destination pages and start copying data from the device to CPU
907  * memory before calling migrate_device_pages().
908  */
909 int migrate_device_range(unsigned long *src_pfns, unsigned long start,
910 			unsigned long npages)
911 {
912 	unsigned long i, pfn;
913 
914 	for (pfn = start, i = 0; i < npages; pfn++, i++) {
915 		struct page *page = pfn_to_page(pfn);
916 
917 		if (!get_page_unless_zero(page)) {
918 			src_pfns[i] = 0;
919 			continue;
920 		}
921 
922 		if (!trylock_page(page)) {
923 			src_pfns[i] = 0;
924 			put_page(page);
925 			continue;
926 		}
927 
928 		src_pfns[i] = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
929 	}
930 
931 	migrate_device_unmap(src_pfns, npages, NULL);
932 
933 	return 0;
934 }
935 EXPORT_SYMBOL(migrate_device_range);
936 
937 /*
938  * Migrate a device coherent page back to normal memory. The caller should have
939  * a reference on page which will be copied to the new page if migration is
940  * successful or dropped on failure.
941  */
942 int migrate_device_coherent_page(struct page *page)
943 {
944 	unsigned long src_pfn, dst_pfn = 0;
945 	struct page *dpage;
946 
947 	WARN_ON_ONCE(PageCompound(page));
948 
949 	lock_page(page);
950 	src_pfn = migrate_pfn(page_to_pfn(page)) | MIGRATE_PFN_MIGRATE;
951 
952 	/*
953 	 * We don't have a VMA and don't need to walk the page tables to find
954 	 * the source page. So call migrate_vma_unmap() directly to unmap the
955 	 * page as migrate_vma_setup() will fail if args.vma == NULL.
956 	 */
957 	migrate_device_unmap(&src_pfn, 1, NULL);
958 	if (!(src_pfn & MIGRATE_PFN_MIGRATE))
959 		return -EBUSY;
960 
961 	dpage = alloc_page(GFP_USER | __GFP_NOWARN);
962 	if (dpage) {
963 		lock_page(dpage);
964 		dst_pfn = migrate_pfn(page_to_pfn(dpage));
965 	}
966 
967 	migrate_device_pages(&src_pfn, &dst_pfn, 1);
968 	if (src_pfn & MIGRATE_PFN_MIGRATE)
969 		copy_highpage(dpage, page);
970 	migrate_device_finalize(&src_pfn, &dst_pfn, 1);
971 
972 	if (src_pfn & MIGRATE_PFN_MIGRATE)
973 		return 0;
974 	return -EBUSY;
975 }
976