xref: /linux/mm/migrate_device.c (revision 7db28abbea0f7dc1ec4fdfdc149db5fbd9e4c994)
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/leafops.h>
17 #include <linux/pgalloc.h>
18 #include <asm/tlbflush.h>
19 #include "internal.h"
20 
21 static int migrate_vma_collect_skip(unsigned long start,
22 				    unsigned long end,
23 				    struct mm_walk *walk)
24 {
25 	struct migrate_vma *migrate = walk->private;
26 	unsigned long addr;
27 
28 	for (addr = start; addr < end; addr += PAGE_SIZE) {
29 		migrate->dst[migrate->npages] = 0;
30 		migrate->src[migrate->npages++] = 0;
31 	}
32 
33 	return 0;
34 }
35 
36 static int migrate_vma_collect_hole(unsigned long start,
37 				    unsigned long end,
38 				    __always_unused int depth,
39 				    struct mm_walk *walk)
40 {
41 	struct migrate_vma *migrate = walk->private;
42 	unsigned long addr;
43 
44 	/* Only allow populating anonymous memory. */
45 	if (!vma_is_anonymous(walk->vma))
46 		return migrate_vma_collect_skip(start, end, walk);
47 
48 	if (thp_migration_supported() &&
49 		(migrate->flags & MIGRATE_VMA_SELECT_COMPOUND) &&
50 		(IS_ALIGNED(start, HPAGE_PMD_SIZE) &&
51 		 IS_ALIGNED(end, HPAGE_PMD_SIZE))) {
52 		migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE |
53 						MIGRATE_PFN_COMPOUND;
54 		migrate->dst[migrate->npages] = 0;
55 		migrate->npages++;
56 		migrate->cpages++;
57 
58 		/*
59 		 * Collect the remaining entries as holes, in case we
60 		 * need to split later
61 		 */
62 		return migrate_vma_collect_skip(start + PAGE_SIZE, end, walk);
63 	}
64 
65 	for (addr = start; addr < end; addr += PAGE_SIZE) {
66 		migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
67 		migrate->dst[migrate->npages] = 0;
68 		migrate->npages++;
69 		migrate->cpages++;
70 	}
71 
72 	return 0;
73 }
74 
75 /**
76  * migrate_vma_split_folio() - Helper function to split a THP folio
77  * @folio: the folio to split
78  * @fault_page: struct page associated with the fault if any
79  *
80  * If @folio is not the folio containing @fault_page, the caller must hold a
81  * reference on @folio. The helper consumes that reference.
82  *
83  * Returns 0 on success
84  */
85 static int migrate_vma_split_folio(struct folio *folio,
86 				   struct page *fault_page)
87 {
88 	int ret;
89 	struct folio *fault_folio = fault_page ? page_folio(fault_page) : NULL;
90 	struct folio *new_fault_folio = NULL;
91 
92 	if (folio != fault_folio)
93 		folio_lock(folio);
94 
95 	ret = split_folio(folio);
96 	if (ret) {
97 		if (folio != fault_folio) {
98 			folio_unlock(folio);
99 			folio_put(folio);
100 		}
101 		return ret;
102 	}
103 
104 	new_fault_folio = fault_page ? page_folio(fault_page) : NULL;
105 
106 	/*
107 	 * Ensure the lock is held on the correct
108 	 * folio after the split
109 	 */
110 	if (!new_fault_folio) {
111 		folio_unlock(folio);
112 		folio_put(folio);
113 	} else if (folio != new_fault_folio) {
114 		if (new_fault_folio != fault_folio) {
115 			folio_get(new_fault_folio);
116 			folio_lock(new_fault_folio);
117 		}
118 		folio_unlock(folio);
119 		folio_put(folio);
120 	}
121 
122 	return 0;
123 }
124 
125 /** migrate_vma_collect_huge_pmd - collect THP pages without splitting the
126  * folio for device private pages.
127  * @pmdp: pointer to pmd entry
128  * @start: start address of the range for migration
129  * @end: end address of the range for migration
130  * @walk: mm_walk callback structure
131  * @fault_folio: folio associated with the fault if any
132  *
133  * Collect the huge pmd entry at @pmdp for migration and set the
134  * MIGRATE_PFN_COMPOUND flag in the migrate src entry to indicate that
135  * migration will occur at HPAGE_PMD granularity
136  */
137 static int migrate_vma_collect_huge_pmd(pmd_t *pmdp, unsigned long start,
138 					unsigned long end, struct mm_walk *walk,
139 					struct folio *fault_folio)
140 {
141 	struct mm_struct *mm = walk->mm;
142 	struct folio *folio;
143 	struct migrate_vma *migrate = walk->private;
144 	spinlock_t *ptl;
145 	int ret;
146 	unsigned long write = 0;
147 
148 	ptl = pmd_lock(mm, pmdp);
149 	if (pmd_none(*pmdp)) {
150 		spin_unlock(ptl);
151 		return migrate_vma_collect_hole(start, end, -1, walk);
152 	}
153 
154 	if (pmd_trans_huge(*pmdp)) {
155 		if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
156 			spin_unlock(ptl);
157 			return migrate_vma_collect_skip(start, end, walk);
158 		}
159 
160 		folio = pmd_folio(*pmdp);
161 		if (is_huge_zero_folio(folio)) {
162 			spin_unlock(ptl);
163 			return migrate_vma_collect_hole(start, end, -1, walk);
164 		}
165 		if (pmd_write(*pmdp))
166 			write = MIGRATE_PFN_WRITE;
167 	} else if (!pmd_present(*pmdp)) {
168 		const softleaf_t entry = softleaf_from_pmd(*pmdp);
169 
170 		if (!softleaf_is_device_private(entry) ||
171 		    !(migrate->flags & MIGRATE_VMA_SELECT_DEVICE_PRIVATE)) {
172 			spin_unlock(ptl);
173 			return migrate_vma_collect_skip(start, end, walk);
174 		}
175 
176 		folio = softleaf_to_folio(entry);
177 		if (folio->pgmap->owner != migrate->pgmap_owner) {
178 			spin_unlock(ptl);
179 			return migrate_vma_collect_skip(start, end, walk);
180 		}
181 
182 		if (softleaf_is_device_private_write(entry))
183 			write = MIGRATE_PFN_WRITE;
184 	} else {
185 		spin_unlock(ptl);
186 		return -EAGAIN;
187 	}
188 
189 	folio_get(folio);
190 	if (folio != fault_folio && unlikely(!folio_trylock(folio))) {
191 		spin_unlock(ptl);
192 		folio_put(folio);
193 		return migrate_vma_collect_skip(start, end, walk);
194 	}
195 
196 	if (thp_migration_supported() &&
197 		(migrate->flags & MIGRATE_VMA_SELECT_COMPOUND) &&
198 		(IS_ALIGNED(start, HPAGE_PMD_SIZE) &&
199 		 IS_ALIGNED(end, HPAGE_PMD_SIZE))) {
200 
201 		struct page_vma_mapped_walk pvmw = {
202 			.ptl = ptl,
203 			.address = start,
204 			.pmd = pmdp,
205 			.vma = walk->vma,
206 		};
207 
208 		unsigned long pfn = page_to_pfn(folio_page(folio, 0));
209 
210 		migrate->src[migrate->npages] = migrate_pfn(pfn) | write
211 						| MIGRATE_PFN_MIGRATE
212 						| MIGRATE_PFN_COMPOUND;
213 		migrate->dst[migrate->npages++] = 0;
214 		migrate->cpages++;
215 		ret = set_pmd_migration_entry(&pvmw, folio_page(folio, 0));
216 		if (ret) {
217 			migrate->npages--;
218 			migrate->cpages--;
219 			migrate->src[migrate->npages] = 0;
220 			migrate->dst[migrate->npages] = 0;
221 			goto fallback;
222 		}
223 		migrate_vma_collect_skip(start + PAGE_SIZE, end, walk);
224 		spin_unlock(ptl);
225 		return 0;
226 	}
227 
228 fallback:
229 	spin_unlock(ptl);
230 	if (!folio_test_large(folio))
231 		goto done;
232 	ret = split_folio(folio);
233 	if (fault_folio != folio)
234 		folio_unlock(folio);
235 	folio_put(folio);
236 	if (ret)
237 		return migrate_vma_collect_skip(start, end, walk);
238 	if (pmd_none(pmdp_get_lockless(pmdp)))
239 		return migrate_vma_collect_hole(start, end, -1, walk);
240 
241 done:
242 	return -ENOENT;
243 }
244 
245 static int migrate_vma_collect_pmd(pmd_t *pmdp,
246 				   unsigned long start,
247 				   unsigned long end,
248 				   struct mm_walk *walk)
249 {
250 	struct migrate_vma *migrate = walk->private;
251 	struct vm_area_struct *vma = walk->vma;
252 	struct mm_struct *mm = vma->vm_mm;
253 	unsigned long addr = start, unmapped = 0;
254 	spinlock_t *ptl;
255 	struct folio *fault_folio = migrate->fault_page ?
256 		page_folio(migrate->fault_page) : NULL;
257 	pte_t *ptep;
258 
259 again:
260 	if (pmd_trans_huge(*pmdp) || !pmd_present(*pmdp)) {
261 		int ret = migrate_vma_collect_huge_pmd(pmdp, start, end, walk, fault_folio);
262 
263 		if (ret == -EAGAIN)
264 			goto again;
265 		if (ret == 0)
266 			return 0;
267 	}
268 
269 	ptep = pte_offset_map_lock(mm, pmdp, start, &ptl);
270 	if (!ptep)
271 		goto again;
272 	lazy_mmu_mode_enable();
273 	ptep += (addr - start) / PAGE_SIZE;
274 
275 	for (; addr < end; addr += PAGE_SIZE, ptep++) {
276 		struct dev_pagemap *pgmap;
277 		unsigned long mpfn = 0, pfn;
278 		struct folio *folio;
279 		struct page *page;
280 		softleaf_t entry;
281 		pte_t pte;
282 
283 		pte = ptep_get(ptep);
284 
285 		if (pte_none(pte)) {
286 			if (vma_is_anonymous(vma)) {
287 				mpfn = MIGRATE_PFN_MIGRATE;
288 				migrate->cpages++;
289 			}
290 			goto next;
291 		}
292 
293 		if (!pte_present(pte)) {
294 			/*
295 			 * Only care about unaddressable device page special
296 			 * page table entry. Other special swap entries are not
297 			 * migratable, and we ignore regular swapped page.
298 			 */
299 			entry = softleaf_from_pte(pte);
300 			if (!softleaf_is_device_private(entry))
301 				goto next;
302 
303 			page = softleaf_to_page(entry);
304 			pgmap = page_pgmap(page);
305 			if (!(migrate->flags &
306 				MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
307 			    pgmap->owner != migrate->pgmap_owner)
308 				goto next;
309 
310 			folio = page_folio(page);
311 			if (folio_test_large(folio)) {
312 				int ret;
313 
314 				/* migrate_vma_split_folio() consumes this reference */
315 				if (folio != fault_folio)
316 					folio_get(folio);
317 				lazy_mmu_mode_disable();
318 				pte_unmap_unlock(ptep, ptl);
319 				ret = migrate_vma_split_folio(folio,
320 							  migrate->fault_page);
321 
322 				if (ret) {
323 					if (unmapped)
324 						flush_tlb_range(walk->vma, start, end);
325 
326 					return migrate_vma_collect_skip(addr, end, walk);
327 				}
328 
329 				goto again;
330 			}
331 
332 			mpfn = migrate_pfn(page_to_pfn(page)) |
333 					MIGRATE_PFN_MIGRATE;
334 			if (softleaf_is_device_private_write(entry))
335 				mpfn |= MIGRATE_PFN_WRITE;
336 		} else {
337 			pfn = pte_pfn(pte);
338 			if (is_zero_pfn(pfn) &&
339 			    (migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
340 				mpfn = MIGRATE_PFN_MIGRATE;
341 				migrate->cpages++;
342 				goto next;
343 			}
344 			page = vm_normal_page(migrate->vma, addr, pte);
345 			if (page && !is_zone_device_page(page) &&
346 			    !(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
347 				goto next;
348 			} else if (page && is_device_coherent_page(page)) {
349 				pgmap = page_pgmap(page);
350 
351 				if (!(migrate->flags &
352 					MIGRATE_VMA_SELECT_DEVICE_COHERENT) ||
353 					pgmap->owner != migrate->pgmap_owner)
354 					goto next;
355 			}
356 			folio = page ? page_folio(page) : NULL;
357 			if (folio && folio_test_large(folio)) {
358 				int ret;
359 
360 				/* migrate_vma_split_folio() consumes this reference */
361 				if (folio != fault_folio)
362 					folio_get(folio);
363 				lazy_mmu_mode_disable();
364 				pte_unmap_unlock(ptep, ptl);
365 				ret = migrate_vma_split_folio(folio,
366 							  migrate->fault_page);
367 
368 				if (ret) {
369 					if (unmapped)
370 						flush_tlb_range(walk->vma, start, end);
371 
372 					return migrate_vma_collect_skip(addr, end, walk);
373 				}
374 
375 				goto again;
376 			}
377 			mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
378 			mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
379 		}
380 
381 		if (!page || !page->mapping) {
382 			mpfn = 0;
383 			goto next;
384 		}
385 
386 		/*
387 		 * By getting a reference on the folio we pin it and that blocks
388 		 * any kind of migration. Side effect is that it "freezes" the
389 		 * pte.
390 		 *
391 		 * We drop this reference after isolating the folio from the lru
392 		 * for non device folio (device folio are not on the lru and thus
393 		 * can't be dropped from it).
394 		 */
395 		folio = page_folio(page);
396 		folio_get(folio);
397 
398 		/*
399 		 * We rely on folio_trylock() to avoid deadlock between
400 		 * concurrent migrations where each is waiting on the others
401 		 * folio lock. If we can't immediately lock the folio we fail this
402 		 * migration as it is only best effort anyway.
403 		 *
404 		 * If we can lock the folio it's safe to set up a migration entry
405 		 * now. In the common case where the folio is mapped once in a
406 		 * single process setting up the migration entry now is an
407 		 * optimisation to avoid walking the rmap later with
408 		 * try_to_migrate().
409 		 */
410 		if (fault_folio == folio || folio_trylock(folio)) {
411 			bool anon_exclusive;
412 			pte_t swp_pte;
413 
414 			if (pte_present(pte))
415 				flush_cache_page(vma, addr, pte_pfn(pte));
416 			anon_exclusive = folio_test_anon(folio) &&
417 					  PageAnonExclusive(page);
418 			if (anon_exclusive) {
419 				pte = ptep_clear_flush(vma, addr, ptep);
420 
421 				if (folio_try_share_anon_rmap_pte(folio, page)) {
422 					set_pte_at(mm, addr, ptep, pte);
423 					if (fault_folio != folio)
424 						folio_unlock(folio);
425 					folio_put(folio);
426 					mpfn = 0;
427 					goto next;
428 				}
429 			} else {
430 				pte = ptep_get_and_clear(mm, addr, ptep);
431 			}
432 
433 			migrate->cpages++;
434 
435 			/* Set the dirty flag on the folio now the pte is gone. */
436 			if (pte_present(pte) && pte_dirty(pte))
437 				folio_mark_dirty(folio);
438 
439 			/* Setup special migration page table entry */
440 			if (mpfn & MIGRATE_PFN_WRITE)
441 				entry = make_writable_migration_entry(
442 							page_to_pfn(page));
443 			else if (anon_exclusive)
444 				entry = make_readable_exclusive_migration_entry(
445 							page_to_pfn(page));
446 			else
447 				entry = make_readable_migration_entry(
448 							page_to_pfn(page));
449 			if (pte_present(pte)) {
450 				if (pte_young(pte))
451 					entry = make_migration_entry_young(entry);
452 				if (pte_dirty(pte))
453 					entry = make_migration_entry_dirty(entry);
454 			}
455 			swp_pte = swp_entry_to_pte(entry);
456 			if (pte_present(pte)) {
457 				if (pte_soft_dirty(pte))
458 					swp_pte = pte_swp_mksoft_dirty(swp_pte);
459 				if (pte_uffd(pte))
460 					swp_pte = pte_swp_mkuffd(swp_pte);
461 			} else {
462 				if (pte_swp_soft_dirty(pte))
463 					swp_pte = pte_swp_mksoft_dirty(swp_pte);
464 				if (pte_swp_uffd(pte))
465 					swp_pte = pte_swp_mkuffd(swp_pte);
466 			}
467 			set_pte_at(mm, addr, ptep, swp_pte);
468 
469 			/*
470 			 * This is like regular unmap: we remove the rmap and
471 			 * drop the folio refcount. The folio won't be freed, as
472 			 * we took a reference just above.
473 			 */
474 			folio_remove_rmap_pte(folio, page, vma);
475 			folio_put(folio);
476 
477 			if (pte_present(pte))
478 				unmapped++;
479 		} else {
480 			folio_put(folio);
481 			mpfn = 0;
482 		}
483 
484 next:
485 		migrate->dst[migrate->npages] = 0;
486 		migrate->src[migrate->npages++] = mpfn;
487 	}
488 
489 	/* Only flush the TLB if we actually modified any entries */
490 	if (unmapped)
491 		flush_tlb_range(walk->vma, start, end);
492 
493 	lazy_mmu_mode_disable();
494 	pte_unmap_unlock(ptep - 1, ptl);
495 
496 	return 0;
497 }
498 
499 static const struct mm_walk_ops migrate_vma_walk_ops = {
500 	.pmd_entry		= migrate_vma_collect_pmd,
501 	.pte_hole		= migrate_vma_collect_hole,
502 	.walk_lock		= PGWALK_RDLOCK,
503 };
504 
505 /*
506  * migrate_vma_collect() - collect pages over a range of virtual addresses
507  * @migrate: migrate struct containing all migration information
508  *
509  * This will walk the CPU page table. For each virtual address backed by a
510  * valid page, it updates the src array and takes a reference on the page, in
511  * order to pin the page until we lock it and unmap it.
512  */
513 static void migrate_vma_collect(struct migrate_vma *migrate)
514 {
515 	struct mmu_notifier_range range;
516 
517 	/*
518 	 * Note that the pgmap_owner is passed to the mmu notifier callback so
519 	 * that the registered device driver can skip invalidating device
520 	 * private page mappings that won't be migrated.
521 	 */
522 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
523 		migrate->vma->vm_mm, migrate->start, migrate->end,
524 		migrate->pgmap_owner);
525 	mmu_notifier_invalidate_range_start(&range);
526 
527 	walk_page_range_vma(migrate->vma, migrate->start, migrate->end,
528 			&migrate_vma_walk_ops, migrate);
529 
530 	mmu_notifier_invalidate_range_end(&range);
531 	migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
532 }
533 
534 /*
535  * migrate_vma_check_page() - check if page is pinned or not
536  * @page: struct page to check
537  *
538  * Pinned pages cannot be migrated. This is the same test as in
539  * folio_migrate_mapping(), except that here we allow migration of a
540  * ZONE_DEVICE page.
541  */
542 static bool migrate_vma_check_page(struct page *page, struct page *fault_page)
543 {
544 	struct folio *folio = page_folio(page);
545 
546 	/*
547 	 * One extra ref because caller holds an extra reference, either from
548 	 * folio_isolate_lru() for a regular folio, or migrate_vma_collect() for
549 	 * a device folio.
550 	 */
551 	int extra = 1 + (page == fault_page);
552 
553 	/* Page from ZONE_DEVICE have one extra reference */
554 	if (folio_is_zone_device(folio))
555 		extra++;
556 
557 	/* For file back page */
558 	if (folio_mapping(folio))
559 		extra += 1 + folio_has_private(folio);
560 
561 	if ((folio_ref_count(folio) - extra) > folio_mapcount(folio))
562 		return false;
563 
564 	return true;
565 }
566 
567 /*
568  * Unmaps pages for migration. Returns number of source pfns marked as
569  * migrating.
570  */
571 static unsigned long migrate_device_unmap(unsigned long *src_pfns,
572 					  unsigned long npages,
573 					  struct page *fault_page)
574 {
575 	struct folio *fault_folio = fault_page ?
576 		page_folio(fault_page) : NULL;
577 	unsigned long i, restore = 0;
578 	bool allow_drain = true;
579 	unsigned long unmapped = 0;
580 
581 	lru_add_drain();
582 
583 	for (i = 0; i < npages; ) {
584 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
585 		struct folio *folio;
586 		unsigned int nr = 1;
587 
588 		if (!page) {
589 			if (src_pfns[i] & MIGRATE_PFN_MIGRATE)
590 				unmapped++;
591 			goto next;
592 		}
593 
594 		folio =	page_folio(page);
595 		nr = folio_nr_pages(folio);
596 
597 		if (nr > 1)
598 			src_pfns[i] |= MIGRATE_PFN_COMPOUND;
599 
600 
601 		/* ZONE_DEVICE folios are not on LRU */
602 		if (!folio_is_zone_device(folio)) {
603 			if (!folio_test_lru(folio) && allow_drain) {
604 				/* Drain CPU's lru cache */
605 				lru_add_drain_all();
606 				allow_drain = false;
607 			}
608 
609 			if (!folio_isolate_lru(folio)) {
610 				src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
611 				restore++;
612 				goto next;
613 			}
614 
615 			/* Drop the reference we took in collect */
616 			folio_put(folio);
617 		}
618 
619 		if (folio_mapped(folio))
620 			try_to_migrate(folio, 0);
621 
622 		if (folio_mapped(folio) ||
623 		    !migrate_vma_check_page(page, fault_page)) {
624 			if (!folio_is_zone_device(folio)) {
625 				folio_get(folio);
626 				folio_putback_lru(folio);
627 			}
628 
629 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
630 			restore++;
631 			goto next;
632 		}
633 
634 		unmapped++;
635 next:
636 		i += nr;
637 	}
638 
639 	for (i = 0; i < npages && restore; i++) {
640 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
641 		struct folio *folio;
642 
643 		if (!page || (src_pfns[i] & MIGRATE_PFN_MIGRATE))
644 			continue;
645 
646 		folio = page_folio(page);
647 		remove_migration_ptes(folio, folio, 0);
648 
649 		src_pfns[i] = 0;
650 		if (fault_folio != folio)
651 			folio_unlock(folio);
652 		folio_put(folio);
653 		restore--;
654 	}
655 
656 	return unmapped;
657 }
658 
659 /*
660  * migrate_vma_unmap() - replace page mapping with special migration pte entry
661  * @migrate: migrate struct containing all migration information
662  *
663  * Isolate pages from the LRU and replace mappings (CPU page table pte) with a
664  * special migration pte entry and check if it has been pinned. Pinned pages are
665  * restored because we cannot migrate them.
666  *
667  * This is the last step before we call the device driver callback to allocate
668  * destination memory and copy contents of original page over to new page.
669  */
670 static void migrate_vma_unmap(struct migrate_vma *migrate)
671 {
672 	migrate->cpages = migrate_device_unmap(migrate->src, migrate->npages,
673 					migrate->fault_page);
674 }
675 
676 /**
677  * migrate_vma_setup() - prepare to migrate a range of memory
678  * @args: contains the vma, start, and pfns arrays for the migration
679  *
680  * Returns: negative errno on failures, 0 when 0 or more pages were migrated
681  * without an error.
682  *
683  * Prepare to migrate a range of memory virtual address range by collecting all
684  * the pages backing each virtual address in the range, saving them inside the
685  * src array.  Then lock those pages and unmap them. Once the pages are locked
686  * and unmapped, check whether each page is pinned or not.  Pages that aren't
687  * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
688  * corresponding src array entry.  Then restores any pages that are pinned, by
689  * remapping and unlocking those pages.
690  *
691  * The caller should then allocate destination memory and copy source memory to
692  * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
693  * flag set).  Once these are allocated and copied, the caller must update each
694  * corresponding entry in the dst array with the pfn value of the destination
695  * page and with MIGRATE_PFN_VALID. Destination pages must be locked via
696  * lock_page().
697  *
698  * Note that the caller does not have to migrate all the pages that are marked
699  * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
700  * device memory to system memory.  If the caller cannot migrate a device page
701  * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
702  * consequences for the userspace process, so it must be avoided if at all
703  * possible.
704  *
705  * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
706  * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
707  * allowing the caller to allocate device memory for those unbacked virtual
708  * addresses.  For this the caller simply has to allocate device memory and
709  * properly set the destination entry like for regular migration.  Note that
710  * this can still fail, and thus inside the device driver you must check if the
711  * migration was successful for those entries after calling migrate_vma_pages(),
712  * just like for regular migration.
713  *
714  * After that, the callers must call migrate_vma_pages() to go over each entry
715  * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
716  * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
717  * then migrate_vma_pages() to migrate struct page information from the source
718  * struct page to the destination struct page.  If it fails to migrate the
719  * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
720  * src array.
721  *
722  * At this point all successfully migrated pages have an entry in the src
723  * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
724  * array entry with MIGRATE_PFN_VALID flag set.
725  *
726  * Once migrate_vma_pages() returns the caller may inspect which pages were
727  * successfully migrated, and which were not.  Successfully migrated pages will
728  * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
729  *
730  * It is safe to update device page table after migrate_vma_pages() because
731  * both destination and source page are still locked, and the mmap_lock is held
732  * in read mode (hence no one can unmap the range being migrated).
733  *
734  * Once the caller is done cleaning up things and updating its page table (if it
735  * chose to do so, this is not an obligation) it finally calls
736  * migrate_vma_finalize() to update the CPU page table to point to new pages
737  * for successfully migrated pages or otherwise restore the CPU page table to
738  * point to the original source pages.
739  */
740 int migrate_vma_setup(struct migrate_vma *args)
741 {
742 	long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
743 
744 	args->start &= PAGE_MASK;
745 	args->end &= PAGE_MASK;
746 	if (!args->vma || is_vm_hugetlb_page(args->vma) ||
747 	    (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
748 		return -EINVAL;
749 	if (nr_pages <= 0)
750 		return -EINVAL;
751 	if (args->start < args->vma->vm_start ||
752 	    args->start >= args->vma->vm_end)
753 		return -EINVAL;
754 	if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
755 		return -EINVAL;
756 	if (!args->src || !args->dst)
757 		return -EINVAL;
758 	if (args->fault_page && !is_device_private_page(args->fault_page))
759 		return -EINVAL;
760 	if (args->fault_page && !PageLocked(args->fault_page))
761 		return -EINVAL;
762 
763 	memset(args->src, 0, sizeof(*args->src) * nr_pages);
764 	args->cpages = 0;
765 	args->npages = 0;
766 
767 	migrate_vma_collect(args);
768 
769 	if (args->cpages)
770 		migrate_vma_unmap(args);
771 
772 	/*
773 	 * At this point pages are locked and unmapped, and thus they have
774 	 * stable content and can safely be copied to destination memory that
775 	 * is allocated by the drivers.
776 	 */
777 	return 0;
778 
779 }
780 EXPORT_SYMBOL(migrate_vma_setup);
781 
782 #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
783 /**
784  * migrate_vma_insert_huge_pmd_page: Insert a huge folio into @migrate->vma->vm_mm
785  * at @addr. folio is already allocated as a part of the migration process with
786  * large page.
787  *
788  * @page needs to be initialized and setup after it's allocated. The code bits
789  * here follow closely the code in __do_huge_pmd_anonymous_page(). This API does
790  * not support THP zero pages.
791  *
792  * @migrate: migrate_vma arguments
793  * @addr: address where the folio will be inserted
794  * @page: page to be inserted at @addr
795  * @src: src pfn which is being migrated
796  * @pmdp: pointer to the pmd
797  */
798 static int migrate_vma_insert_huge_pmd_page(struct migrate_vma *migrate,
799 					 unsigned long addr,
800 					 struct page *page,
801 					 unsigned long *src,
802 					 pmd_t *pmdp)
803 {
804 	struct vm_area_struct *vma = migrate->vma;
805 	gfp_t gfp = vma_thp_gfp_mask(vma);
806 	struct folio *folio = page_folio(page);
807 	int ret;
808 	vm_fault_t csa_ret;
809 	spinlock_t *ptl;
810 	pgtable_t pgtable;
811 	pmd_t entry;
812 	bool flush = false;
813 	unsigned long i;
814 
815 	VM_WARN_ON_ONCE(!folio);
816 
817 	if (!thp_vma_suitable_order(vma, addr, HPAGE_PMD_ORDER))
818 		return -EINVAL;
819 
820 	ret = anon_vma_prepare(vma);
821 	if (ret)
822 		return ret;
823 
824 	folio_set_order(folio, HPAGE_PMD_ORDER);
825 	folio_set_large_rmappable(folio);
826 
827 	if (mem_cgroup_charge(folio, migrate->vma->vm_mm, gfp)) {
828 		count_vm_event(THP_FAULT_FALLBACK);
829 		count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
830 		ret = -ENOMEM;
831 		goto abort;
832 	}
833 
834 	__folio_mark_uptodate(folio);
835 
836 	pgtable = pte_alloc_one(vma->vm_mm);
837 	if (unlikely(!pgtable))
838 		goto abort;
839 
840 	if (folio_is_device_private(folio)) {
841 		swp_entry_t swp_entry;
842 
843 		if (vma->vm_flags & VM_WRITE)
844 			swp_entry = make_writable_device_private_entry(
845 						page_to_pfn(page));
846 		else
847 			swp_entry = make_readable_device_private_entry(
848 						page_to_pfn(page));
849 		entry = softleaf_to_pmd(swp_entry);
850 	} else {
851 		if (folio_is_zone_device(folio) &&
852 		    !folio_is_device_coherent(folio)) {
853 			goto free_abort;
854 		}
855 		entry = folio_mk_pmd(folio, vma->vm_page_prot);
856 		if (vma->vm_flags & VM_WRITE)
857 			entry = pmd_mkwrite(pmd_mkdirty(entry), vma);
858 	}
859 
860 	ptl = pmd_lock(vma->vm_mm, pmdp);
861 	csa_ret = check_stable_address_space(vma->vm_mm);
862 	if (csa_ret)
863 		goto unlock_abort;
864 
865 	/*
866 	 * Check for userfaultfd but do not deliver the fault. Instead,
867 	 * just back off.
868 	 */
869 	if (userfaultfd_missing(vma))
870 		goto unlock_abort;
871 
872 	if (is_huge_zero_pmd(*pmdp))
873 		flush = true;
874 	else if (!pmd_none(*pmdp))
875 		goto unlock_abort;
876 
877 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
878 	folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
879 	if (!folio_is_zone_device(folio))
880 		folio_add_lru_vma(folio, vma);
881 	folio_get(folio);
882 
883 	if (flush) {
884 		pte_free(vma->vm_mm, pgtable);
885 		flush_cache_range(vma, addr, addr + HPAGE_PMD_SIZE);
886 		pmdp_invalidate(vma, addr, pmdp);
887 	} else {
888 		pgtable_trans_huge_deposit(vma->vm_mm, pmdp, pgtable);
889 		mm_inc_nr_ptes(vma->vm_mm);
890 	}
891 	set_pmd_at(vma->vm_mm, addr, pmdp, entry);
892 	update_mmu_cache_pmd(vma, addr, pmdp);
893 
894 	spin_unlock(ptl);
895 
896 	count_vm_event(THP_FAULT_ALLOC);
897 	count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_ALLOC);
898 	count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
899 
900 	return 0;
901 
902 unlock_abort:
903 	spin_unlock(ptl);
904 free_abort:
905 	pte_free(vma->vm_mm, pgtable);
906 abort:
907 	for (i = 0; i < HPAGE_PMD_NR; i++)
908 		src[i] &= ~MIGRATE_PFN_MIGRATE;
909 	return 0;
910 }
911 
912 static int migrate_vma_split_unmapped_folio(struct migrate_vma *migrate,
913 					    unsigned long idx, unsigned long addr,
914 					    struct folio *folio)
915 {
916 	unsigned long i;
917 	unsigned long pfn;
918 	unsigned long flags;
919 	int ret = 0;
920 
921 	/*
922 	 * take a reference, since split_huge_pmd_address() with freeze = true
923 	 * drops a reference at the end.
924 	 */
925 	folio_get(folio);
926 	split_huge_pmd_address(migrate->vma, addr, true);
927 	ret = folio_split_unmapped(folio, 0);
928 	if (ret)
929 		return ret;
930 	migrate->src[idx] &= ~MIGRATE_PFN_COMPOUND;
931 	flags = migrate->src[idx] & ((1UL << MIGRATE_PFN_SHIFT) - 1);
932 	pfn = migrate->src[idx] >> MIGRATE_PFN_SHIFT;
933 	for (i = 1; i < HPAGE_PMD_NR; i++)
934 		migrate->src[i+idx] = migrate_pfn(pfn + i) | flags;
935 	return ret;
936 }
937 #else /* !CONFIG_ARCH_HAS_PMD_SOFTLEAVES */
938 static int migrate_vma_insert_huge_pmd_page(struct migrate_vma *migrate,
939 					 unsigned long addr,
940 					 struct page *page,
941 					 unsigned long *src,
942 					 pmd_t *pmdp)
943 {
944 	return 0;
945 }
946 
947 static int migrate_vma_split_unmapped_folio(struct migrate_vma *migrate,
948 					    unsigned long idx, unsigned long addr,
949 					    struct folio *folio)
950 {
951 	return 0;
952 }
953 #endif
954 
955 static unsigned long migrate_vma_nr_pages(unsigned long *src)
956 {
957 	unsigned long nr = 1;
958 #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
959 	if (*src & MIGRATE_PFN_COMPOUND)
960 		nr = HPAGE_PMD_NR;
961 #else
962 	if (*src & MIGRATE_PFN_COMPOUND)
963 		VM_WARN_ON_ONCE(true);
964 #endif
965 	return nr;
966 }
967 
968 /*
969  * This code closely matches the code in:
970  *   __handle_mm_fault()
971  *     handle_pte_fault()
972  *       do_anonymous_page()
973  * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
974  * private or coherent page.
975  */
976 static void migrate_vma_insert_page(struct migrate_vma *migrate,
977 				    unsigned long addr,
978 				    unsigned long *dst,
979 				    unsigned long *src)
980 {
981 	struct page *page = migrate_pfn_to_page(*dst);
982 	struct folio *folio = page_folio(page);
983 	struct vm_area_struct *vma = migrate->vma;
984 	struct mm_struct *mm = vma->vm_mm;
985 	bool flush = false;
986 	spinlock_t *ptl;
987 	pte_t entry;
988 	pgd_t *pgdp;
989 	p4d_t *p4dp;
990 	pud_t *pudp;
991 	pmd_t *pmdp;
992 	pte_t *ptep;
993 	pte_t orig_pte;
994 
995 	/* Only allow populating anonymous memory */
996 	if (!vma_is_anonymous(vma))
997 		goto abort;
998 
999 	pgdp = pgd_offset(mm, addr);
1000 	p4dp = p4d_alloc(mm, pgdp, addr);
1001 	if (!p4dp)
1002 		goto abort;
1003 	pudp = pud_alloc(mm, p4dp, addr);
1004 	if (!pudp)
1005 		goto abort;
1006 	pmdp = pmd_alloc(mm, pudp, addr);
1007 	if (!pmdp)
1008 		goto abort;
1009 
1010 	if (thp_migration_supported() && (*dst & MIGRATE_PFN_COMPOUND)) {
1011 		int ret = migrate_vma_insert_huge_pmd_page(migrate, addr, page,
1012 								src, pmdp);
1013 		if (ret)
1014 			goto abort;
1015 		return;
1016 	}
1017 
1018 	if (!pmd_none(*pmdp)) {
1019 		if (pmd_trans_huge(*pmdp)) {
1020 			if (!is_huge_zero_pmd(*pmdp))
1021 				goto abort;
1022 			split_huge_pmd(vma, pmdp, addr);
1023 		} else if (pmd_leaf(*pmdp))
1024 			goto abort;
1025 	}
1026 
1027 	if (pte_alloc(mm, pmdp))
1028 		goto abort;
1029 	if (unlikely(anon_vma_prepare(vma)))
1030 		goto abort;
1031 	if (mem_cgroup_charge(folio, vma->vm_mm, GFP_KERNEL))
1032 		goto abort;
1033 
1034 	/*
1035 	 * The memory barrier inside __folio_mark_uptodate makes sure that
1036 	 * preceding stores to the folio contents become visible before
1037 	 * the set_pte_at() write.
1038 	 */
1039 	__folio_mark_uptodate(folio);
1040 
1041 	if (folio_is_device_private(folio)) {
1042 		swp_entry_t swp_entry;
1043 
1044 		if (vma->vm_flags & VM_WRITE)
1045 			swp_entry = make_writable_device_private_entry(
1046 						page_to_pfn(page));
1047 		else
1048 			swp_entry = make_readable_device_private_entry(
1049 						page_to_pfn(page));
1050 		entry = swp_entry_to_pte(swp_entry);
1051 	} else {
1052 		if (folio_is_zone_device(folio) &&
1053 		    !folio_is_device_coherent(folio)) {
1054 			pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
1055 			goto abort;
1056 		}
1057 		entry = mk_pte(page, vma->vm_page_prot);
1058 		if (vma->vm_flags & VM_WRITE)
1059 			entry = pte_mkwrite(pte_mkdirty(entry), vma);
1060 	}
1061 
1062 	ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
1063 	if (!ptep)
1064 		goto abort;
1065 	orig_pte = ptep_get(ptep);
1066 
1067 	if (check_stable_address_space(mm))
1068 		goto unlock_abort;
1069 
1070 	if (pte_present(orig_pte)) {
1071 		unsigned long pfn = pte_pfn(orig_pte);
1072 
1073 		if (!is_zero_pfn(pfn))
1074 			goto unlock_abort;
1075 		flush = true;
1076 	} else if (!pte_none(orig_pte))
1077 		goto unlock_abort;
1078 
1079 	/*
1080 	 * Check for userfaultfd but do not deliver the fault. Instead,
1081 	 * just back off.
1082 	 */
1083 	if (userfaultfd_missing(vma))
1084 		goto unlock_abort;
1085 
1086 	inc_mm_counter(mm, MM_ANONPAGES);
1087 	folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
1088 	if (!folio_is_zone_device(folio))
1089 		folio_add_lru_vma(folio, vma);
1090 	folio_get(folio);
1091 
1092 	if (flush) {
1093 		flush_cache_page(vma, addr, pte_pfn(orig_pte));
1094 		ptep_clear_flush(vma, addr, ptep);
1095 	}
1096 	set_pte_at(mm, addr, ptep, entry);
1097 	update_mmu_cache(vma, addr, ptep);
1098 
1099 	pte_unmap_unlock(ptep, ptl);
1100 	*src = MIGRATE_PFN_MIGRATE;
1101 	return;
1102 
1103 unlock_abort:
1104 	pte_unmap_unlock(ptep, ptl);
1105 abort:
1106 	*src &= ~MIGRATE_PFN_MIGRATE;
1107 }
1108 
1109 static void __migrate_device_pages(unsigned long *src_pfns,
1110 				unsigned long *dst_pfns, unsigned long npages,
1111 				struct migrate_vma *migrate)
1112 {
1113 	struct mmu_notifier_range range;
1114 	unsigned long i, j;
1115 	bool notified = false;
1116 	unsigned long addr;
1117 
1118 	for (i = 0; i < npages; ) {
1119 		struct page *newpage = migrate_pfn_to_page(dst_pfns[i]);
1120 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
1121 		struct address_space *mapping;
1122 		struct folio *newfolio, *folio;
1123 		int r, extra_cnt = 0;
1124 		unsigned long nr = 1;
1125 
1126 		if (!newpage) {
1127 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
1128 			goto next;
1129 		}
1130 
1131 		if (!page) {
1132 			unsigned long addr;
1133 
1134 			if (!(src_pfns[i] & MIGRATE_PFN_MIGRATE))
1135 				goto next;
1136 
1137 			/*
1138 			 * The only time there is no vma is when called from
1139 			 * migrate_device_coherent_folio(). However this isn't
1140 			 * called if the page could not be unmapped.
1141 			 */
1142 			VM_BUG_ON(!migrate);
1143 			addr = migrate->start + i*PAGE_SIZE;
1144 			if (!notified) {
1145 				notified = true;
1146 
1147 				mmu_notifier_range_init_owner(&range,
1148 					MMU_NOTIFY_MIGRATE, 0,
1149 					migrate->vma->vm_mm, addr, migrate->end,
1150 					migrate->pgmap_owner);
1151 				mmu_notifier_invalidate_range_start(&range);
1152 			}
1153 
1154 			if ((src_pfns[i] & MIGRATE_PFN_COMPOUND) &&
1155 				(!(dst_pfns[i] & MIGRATE_PFN_COMPOUND))) {
1156 				nr = migrate_vma_nr_pages(&src_pfns[i]);
1157 				src_pfns[i] &= ~MIGRATE_PFN_COMPOUND;
1158 			} else {
1159 				nr = 1;
1160 			}
1161 
1162 			for (j = 0; j < nr && i + j < npages; j++) {
1163 				src_pfns[i+j] |= MIGRATE_PFN_MIGRATE;
1164 				migrate_vma_insert_page(migrate,
1165 					addr + j * PAGE_SIZE,
1166 					&dst_pfns[i+j], &src_pfns[i+j]);
1167 			}
1168 			goto next;
1169 		}
1170 
1171 		newfolio = page_folio(newpage);
1172 		folio = page_folio(page);
1173 		mapping = folio_mapping(folio);
1174 
1175 		/*
1176 		 * If THP migration is enabled, check if both src and dst
1177 		 * can migrate large pages
1178 		 */
1179 		if (thp_migration_supported()) {
1180 			if ((src_pfns[i] & MIGRATE_PFN_MIGRATE) &&
1181 				(src_pfns[i] & MIGRATE_PFN_COMPOUND) &&
1182 				!(dst_pfns[i] & MIGRATE_PFN_COMPOUND)) {
1183 
1184 				if (!migrate) {
1185 					src_pfns[i] &= ~(MIGRATE_PFN_MIGRATE |
1186 							 MIGRATE_PFN_COMPOUND);
1187 					goto next;
1188 				}
1189 				nr = 1 << folio_order(folio);
1190 				addr = migrate->start + i * PAGE_SIZE;
1191 				if (migrate_vma_split_unmapped_folio(migrate, i, addr, folio)) {
1192 					src_pfns[i] &= ~(MIGRATE_PFN_MIGRATE |
1193 							 MIGRATE_PFN_COMPOUND);
1194 					goto next;
1195 				}
1196 
1197 				/*
1198 				 * reset nr so that only first after-split folio
1199 				 * is processed below
1200 				 */
1201 				VM_WARN_ON_ONCE(folio_test_large(folio));
1202 				nr = 1;
1203 			} else if ((src_pfns[i] & MIGRATE_PFN_MIGRATE) &&
1204 				(dst_pfns[i] & MIGRATE_PFN_COMPOUND) &&
1205 				!(src_pfns[i] & MIGRATE_PFN_COMPOUND)) {
1206 				src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
1207 			}
1208 		}
1209 
1210 
1211 		if (folio_is_device_private(newfolio) ||
1212 		    folio_is_device_coherent(newfolio)) {
1213 			if (mapping) {
1214 				/*
1215 				 * For now only support anonymous memory migrating to
1216 				 * device private or coherent memory.
1217 				 *
1218 				 * Try to get rid of swap cache if possible.
1219 				 */
1220 				if (!folio_test_anon(folio) ||
1221 				    !folio_free_swap(folio)) {
1222 					src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
1223 					goto next;
1224 				}
1225 			}
1226 		} else if (folio_is_zone_device(newfolio)) {
1227 			/*
1228 			 * Other types of ZONE_DEVICE page are not supported.
1229 			 */
1230 			src_pfns[i] &= ~MIGRATE_PFN_MIGRATE;
1231 			goto next;
1232 		}
1233 
1234 		BUG_ON(folio_test_writeback(folio));
1235 
1236 		if (migrate && migrate->fault_page == page)
1237 			extra_cnt = 1;
1238 		for (j = 0; j < nr && i + j < npages; j++) {
1239 			folio = page_folio(migrate_pfn_to_page(src_pfns[i+j]));
1240 			newfolio = page_folio(migrate_pfn_to_page(dst_pfns[i+j]));
1241 
1242 			/*
1243 			 * folio_free_swap() removed the folio from the swap
1244 			 * cache. Refresh the saved mapping before migration.
1245 			 */
1246 			mapping = folio_mapping(folio);
1247 
1248 			r = folio_migrate_mapping(mapping, newfolio, folio, extra_cnt);
1249 			if (r)
1250 				src_pfns[i+j] &= ~MIGRATE_PFN_MIGRATE;
1251 			else
1252 				folio_migrate_flags(newfolio, folio);
1253 		}
1254 next:
1255 		i += nr;
1256 	}
1257 
1258 	if (notified)
1259 		mmu_notifier_invalidate_range_end(&range);
1260 }
1261 
1262 /**
1263  * migrate_device_pages() - migrate meta-data from src page to dst page
1264  * @src_pfns: src_pfns returned from migrate_device_range()
1265  * @dst_pfns: array of pfns allocated by the driver to migrate memory to
1266  * @npages: number of pages in the range
1267  *
1268  * Equivalent to migrate_vma_pages(). This is called to migrate struct page
1269  * meta-data from source struct page to destination.
1270  */
1271 void migrate_device_pages(unsigned long *src_pfns, unsigned long *dst_pfns,
1272 			unsigned long npages)
1273 {
1274 	__migrate_device_pages(src_pfns, dst_pfns, npages, NULL);
1275 }
1276 EXPORT_SYMBOL(migrate_device_pages);
1277 
1278 /**
1279  * migrate_vma_pages() - migrate meta-data from src page to dst page
1280  * @migrate: migrate struct containing all migration information
1281  *
1282  * This migrates struct page meta-data from source struct page to destination
1283  * struct page. This effectively finishes the migration from source page to the
1284  * destination page.
1285  */
1286 void migrate_vma_pages(struct migrate_vma *migrate)
1287 {
1288 	__migrate_device_pages(migrate->src, migrate->dst, migrate->npages, migrate);
1289 }
1290 EXPORT_SYMBOL(migrate_vma_pages);
1291 
1292 static void __migrate_device_finalize(unsigned long *src_pfns,
1293 				      unsigned long *dst_pfns,
1294 				      unsigned long npages,
1295 				      struct page *fault_page)
1296 {
1297 	struct folio *fault_folio = fault_page ?
1298 		page_folio(fault_page) : NULL;
1299 	unsigned long i;
1300 
1301 	for (i = 0; i < npages; i++) {
1302 		struct folio *dst = NULL, *src = NULL;
1303 		struct page *newpage = migrate_pfn_to_page(dst_pfns[i]);
1304 		struct page *page = migrate_pfn_to_page(src_pfns[i]);
1305 
1306 		if (newpage)
1307 			dst = page_folio(newpage);
1308 
1309 		if (!page) {
1310 			if (dst) {
1311 				WARN_ON_ONCE(fault_folio == dst);
1312 				folio_unlock(dst);
1313 				folio_put(dst);
1314 			}
1315 			continue;
1316 		}
1317 
1318 		src = page_folio(page);
1319 
1320 		if (!(src_pfns[i] & MIGRATE_PFN_MIGRATE) || !dst) {
1321 			if (dst) {
1322 				WARN_ON_ONCE(fault_folio == dst);
1323 				folio_unlock(dst);
1324 				folio_put(dst);
1325 			}
1326 			dst = src;
1327 		}
1328 
1329 		if (!folio_is_zone_device(dst))
1330 			folio_add_lru(dst);
1331 		remove_migration_ptes(src, dst, 0);
1332 		if (fault_folio != src)
1333 			folio_unlock(src);
1334 		folio_put(src);
1335 
1336 		if (dst != src) {
1337 			WARN_ON_ONCE(fault_folio == dst);
1338 			folio_unlock(dst);
1339 			folio_put(dst);
1340 		}
1341 	}
1342 }
1343 
1344 /*
1345  * migrate_device_finalize() - complete page migration
1346  * @src_pfns: src_pfns returned from migrate_device_range()
1347  * @dst_pfns: array of pfns allocated by the driver to migrate memory to
1348  * @npages: number of pages in the range
1349  *
1350  * Completes migration of the page by removing special migration entries.
1351  * Drivers must ensure copying of page data is complete and visible to the CPU
1352  * before calling this.
1353  */
1354 void migrate_device_finalize(unsigned long *src_pfns,
1355 			     unsigned long *dst_pfns, unsigned long npages)
1356 {
1357 	return __migrate_device_finalize(src_pfns, dst_pfns, npages, NULL);
1358 }
1359 EXPORT_SYMBOL(migrate_device_finalize);
1360 
1361 /**
1362  * migrate_vma_finalize() - restore CPU page table entry
1363  * @migrate: migrate struct containing all migration information
1364  *
1365  * This replaces the special migration pte entry with either a mapping to the
1366  * new page if migration was successful for that page, or to the original page
1367  * otherwise.
1368  *
1369  * This also unlocks the pages and puts them back on the lru, or drops the extra
1370  * refcount, for device pages.
1371  */
1372 void migrate_vma_finalize(struct migrate_vma *migrate)
1373 {
1374 	__migrate_device_finalize(migrate->src, migrate->dst, migrate->npages,
1375 				  migrate->fault_page);
1376 }
1377 EXPORT_SYMBOL(migrate_vma_finalize);
1378 
1379 static unsigned long migrate_device_pfn_lock(unsigned long pfn)
1380 {
1381 	struct folio *folio;
1382 
1383 	folio = folio_get_nontail_page(pfn_to_page(pfn));
1384 	if (!folio)
1385 		return 0;
1386 
1387 	if (!folio_trylock(folio)) {
1388 		folio_put(folio);
1389 		return 0;
1390 	}
1391 
1392 	return migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
1393 }
1394 
1395 /**
1396  * migrate_device_range() - migrate device private pfns to normal memory.
1397  * @src_pfns: array large enough to hold migrating source device private pfns.
1398  * @start: starting pfn in the range to migrate.
1399  * @npages: number of pages to migrate.
1400  *
1401  * migrate_vma_setup() is similar in concept to migrate_vma_setup() except that
1402  * instead of looking up pages based on virtual address mappings a range of
1403  * device pfns that should be migrated to system memory is used instead.
1404  *
1405  * This is useful when a driver needs to free device memory but doesn't know the
1406  * virtual mappings of every page that may be in device memory. For example this
1407  * is often the case when a driver is being unloaded or unbound from a device.
1408  *
1409  * Like migrate_vma_setup() this function will take a reference and lock any
1410  * migrating pages that aren't free before unmapping them. Drivers may then
1411  * allocate destination pages and start copying data from the device to CPU
1412  * memory before calling migrate_device_pages().
1413  */
1414 int migrate_device_range(unsigned long *src_pfns, unsigned long start,
1415 			unsigned long npages)
1416 {
1417 	unsigned long i, j, pfn;
1418 
1419 	for (pfn = start, i = 0; i < npages; pfn++, i++) {
1420 		struct page *page = pfn_to_page(pfn);
1421 		struct folio *folio = page_folio(page);
1422 		unsigned int nr = 1;
1423 
1424 		src_pfns[i] = migrate_device_pfn_lock(pfn);
1425 		nr = folio_nr_pages(folio);
1426 		if (nr > 1) {
1427 			src_pfns[i] |= MIGRATE_PFN_COMPOUND;
1428 			for (j = 1; j < nr; j++)
1429 				src_pfns[i+j] = 0;
1430 			i += j - 1;
1431 			pfn += j - 1;
1432 		}
1433 	}
1434 
1435 	migrate_device_unmap(src_pfns, npages, NULL);
1436 
1437 	return 0;
1438 }
1439 EXPORT_SYMBOL(migrate_device_range);
1440 
1441 /**
1442  * migrate_device_pfns() - migrate device private pfns to normal memory.
1443  * @src_pfns: pre-populated array of source device private pfns to migrate.
1444  * @npages: number of pages to migrate.
1445  *
1446  * Similar to migrate_device_range() but supports non-contiguous pre-populated
1447  * array of device pages to migrate.
1448  */
1449 int migrate_device_pfns(unsigned long *src_pfns, unsigned long npages)
1450 {
1451 	unsigned long i, j;
1452 
1453 	for (i = 0; i < npages; i++) {
1454 		struct page *page = pfn_to_page(src_pfns[i]);
1455 		struct folio *folio = page_folio(page);
1456 		unsigned int nr = 1;
1457 
1458 		src_pfns[i] = migrate_device_pfn_lock(src_pfns[i]);
1459 		nr = folio_nr_pages(folio);
1460 		if (nr > 1) {
1461 			src_pfns[i] |= MIGRATE_PFN_COMPOUND;
1462 			for (j = 1; j < nr; j++)
1463 				src_pfns[i+j] = 0;
1464 			i += j - 1;
1465 		}
1466 	}
1467 
1468 	migrate_device_unmap(src_pfns, npages, NULL);
1469 
1470 	return 0;
1471 }
1472 EXPORT_SYMBOL(migrate_device_pfns);
1473 
1474 /*
1475  * Migrate a device coherent folio back to normal memory. The caller should have
1476  * a reference on folio which will be copied to the new folio if migration is
1477  * successful or dropped on failure.
1478  */
1479 int migrate_device_coherent_folio(struct folio *folio)
1480 {
1481 	unsigned long src_pfn, dst_pfn = 0;
1482 	struct folio *dfolio;
1483 
1484 	WARN_ON_ONCE(folio_test_large(folio));
1485 
1486 	folio_lock(folio);
1487 	src_pfn = migrate_pfn(folio_pfn(folio)) | MIGRATE_PFN_MIGRATE;
1488 
1489 	/*
1490 	 * We don't have a VMA and don't need to walk the page tables to find
1491 	 * the source folio. So call migrate_vma_unmap() directly to unmap the
1492 	 * folio as migrate_vma_setup() will fail if args.vma == NULL.
1493 	 */
1494 	migrate_device_unmap(&src_pfn, 1, NULL);
1495 	if (!(src_pfn & MIGRATE_PFN_MIGRATE))
1496 		return -EBUSY;
1497 
1498 	dfolio = folio_alloc(GFP_USER | __GFP_NOWARN, 0);
1499 	if (dfolio) {
1500 		folio_lock(dfolio);
1501 		dst_pfn = migrate_pfn(folio_pfn(dfolio));
1502 	}
1503 
1504 	migrate_device_pages(&src_pfn, &dst_pfn, 1);
1505 	if (src_pfn & MIGRATE_PFN_MIGRATE)
1506 		folio_copy(dfolio, folio);
1507 	migrate_device_finalize(&src_pfn, &dst_pfn, 1);
1508 
1509 	if (src_pfn & MIGRATE_PFN_MIGRATE)
1510 		return 0;
1511 	return -EBUSY;
1512 }
1513