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