xref: /linux/mm/migrate.c (revision abf8efadeb21b741cbd0cc13d57b8f0a207df10d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Memory Migration functionality - linux/mm/migrate.c
4  *
5  * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
6  *
7  * Page migration was first developed in the context of the memory hotplug
8  * project. The main authors of the migration code are:
9  *
10  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
11  * Hirokazu Takahashi <taka@valinux.co.jp>
12  * Dave Hansen <haveblue@us.ibm.com>
13  * Christoph Lameter
14  */
15 
16 #include <linux/migrate.h>
17 #include <linux/export.h>
18 #include <linux/swap.h>
19 #include <linux/leafops.h>
20 #include <linux/pagemap.h>
21 #include <linux/buffer_head.h>
22 #include <linux/mm_inline.h>
23 #include <linux/ksm.h>
24 #include <linux/rmap.h>
25 #include <linux/topology.h>
26 #include <linux/cpu.h>
27 #include <linux/cpuset.h>
28 #include <linux/writeback.h>
29 #include <linux/mempolicy.h>
30 #include <linux/vmalloc.h>
31 #include <linux/security.h>
32 #include <linux/backing-dev.h>
33 #include <linux/compaction.h>
34 #include <linux/syscalls.h>
35 #include <linux/compat.h>
36 #include <linux/hugetlb.h>
37 #include <linux/gfp.h>
38 #include <linux/page_idle.h>
39 #include <linux/page_owner.h>
40 #include <linux/sched/mm.h>
41 #include <linux/ptrace.h>
42 #include <linux/memory.h>
43 #include <linux/sched/sysctl.h>
44 #include <linux/memory-tiers.h>
45 #include <linux/pagewalk.h>
46 
47 #include <asm/tlbflush.h>
48 
49 #include <trace/events/migrate.h>
50 
51 #include "internal.h"
52 #include "page_alloc.h"
53 #include "swap.h"
54 
55 static const struct movable_operations *offline_movable_ops;
56 static const struct movable_operations *zsmalloc_movable_ops;
57 
58 int set_movable_ops(const struct movable_operations *ops, enum pagetype type)
59 {
60 	/*
61 	 * We only allow for selected types and don't handle concurrent
62 	 * registration attempts yet.
63 	 */
64 	switch (type) {
65 	case PGTY_offline:
66 		if (offline_movable_ops && ops)
67 			return -EBUSY;
68 		offline_movable_ops = ops;
69 		break;
70 	case PGTY_zsmalloc:
71 		if (zsmalloc_movable_ops && ops)
72 			return -EBUSY;
73 		zsmalloc_movable_ops = ops;
74 		break;
75 	default:
76 		return -EINVAL;
77 	}
78 	return 0;
79 }
80 EXPORT_SYMBOL_GPL(set_movable_ops);
81 
82 static const struct movable_operations *page_movable_ops(struct page *page)
83 {
84 	VM_WARN_ON_ONCE_PAGE(!page_has_movable_ops(page), page);
85 
86 	/*
87 	 * If we enable page migration for a page of a certain type by marking
88 	 * it as movable, the page type must be sticky until the page gets freed
89 	 * back to the buddy.
90 	 */
91 	if (PageOffline(page))
92 		/* Only balloon page migration sets PageOffline pages movable. */
93 		return offline_movable_ops;
94 	if (PageZsmalloc(page))
95 		return zsmalloc_movable_ops;
96 
97 	return NULL;
98 }
99 
100 /**
101  * isolate_movable_ops_page - isolate a movable_ops page for migration
102  * @page: The page.
103  * @mode: The isolation mode.
104  *
105  * Try to isolate a movable_ops page for migration. Will fail if the page is
106  * not a movable_ops page, if the page is already isolated for migration
107  * or if the page was just was released by its owner.
108  *
109  * Once isolated, the page cannot get freed until it is either putback
110  * or migrated.
111  *
112  * Returns true if isolation succeeded, otherwise false.
113  */
114 bool isolate_movable_ops_page(struct page *page, isolate_mode_t mode)
115 {
116 	/*
117 	 * TODO: these pages will not be folios in the future. All
118 	 * folio dependencies will have to be removed.
119 	 */
120 	struct folio *folio = folio_get_nontail_page(page);
121 	const struct movable_operations *mops;
122 
123 	/*
124 	 * Avoid burning cycles with pages that are yet under __free_pages(),
125 	 * or just got freed under us.
126 	 *
127 	 * In case we 'win' a race for a movable page being freed under us and
128 	 * raise its refcount preventing __free_pages() from doing its job
129 	 * the put_page() at the end of this block will take care of
130 	 * release this page, thus avoiding a nasty leakage.
131 	 */
132 	if (!folio)
133 		goto out;
134 
135 	/*
136 	 * Check for movable_ops pages before taking the page lock because
137 	 * we use non-atomic bitops on newly allocated page flags so
138 	 * unconditionally grabbing the lock ruins page's owner side.
139 	 *
140 	 * Note that once a page has movable_ops, it will stay that way
141 	 * until the page was freed.
142 	 */
143 	if (unlikely(!page_has_movable_ops(page)))
144 		goto out_putfolio;
145 
146 	/*
147 	 * As movable pages are not isolated from LRU lists, concurrent
148 	 * compaction threads can race against page migration functions
149 	 * as well as race against the releasing a page.
150 	 *
151 	 * In order to avoid having an already isolated movable page
152 	 * being (wrongly) re-isolated while it is under migration,
153 	 * or to avoid attempting to isolate pages being released,
154 	 * lets be sure we have the page lock
155 	 * before proceeding with the movable page isolation steps.
156 	 */
157 	if (unlikely(!folio_trylock(folio)))
158 		goto out_putfolio;
159 
160 	VM_WARN_ON_ONCE_PAGE(!page_has_movable_ops(page), page);
161 	if (PageMovableOpsIsolated(page))
162 		goto out_no_isolated;
163 
164 	mops = page_movable_ops(page);
165 	if (WARN_ON_ONCE(!mops))
166 		goto out_no_isolated;
167 
168 	if (!mops->isolate_page(page, mode))
169 		goto out_no_isolated;
170 
171 	/* Driver shouldn't use the isolated flag */
172 	VM_WARN_ON_ONCE_PAGE(PageMovableOpsIsolated(page), page);
173 	SetPageMovableOpsIsolated(page);
174 	folio_unlock(folio);
175 
176 	return true;
177 
178 out_no_isolated:
179 	folio_unlock(folio);
180 out_putfolio:
181 	folio_put(folio);
182 out:
183 	return false;
184 }
185 
186 /**
187  * putback_movable_ops_page - putback an isolated movable_ops page
188  * @page: The isolated page.
189  *
190  * Putback an isolated movable_ops page.
191  *
192  * After the page was putback, it might get freed instantly.
193  */
194 static void putback_movable_ops_page(struct page *page)
195 {
196 	/*
197 	 * TODO: these pages will not be folios in the future. All
198 	 * folio dependencies will have to be removed.
199 	 */
200 	struct folio *folio = page_folio(page);
201 
202 	VM_WARN_ON_ONCE_PAGE(!page_has_movable_ops(page), page);
203 	VM_WARN_ON_ONCE_PAGE(!PageMovableOpsIsolated(page), page);
204 	folio_lock(folio);
205 	page_movable_ops(page)->putback_page(page);
206 	ClearPageMovableOpsIsolated(page);
207 	folio_unlock(folio);
208 	folio_put(folio);
209 }
210 
211 /**
212  * migrate_movable_ops_page - migrate an isolated movable_ops page
213  * @dst: The destination page.
214  * @src: The source page.
215  * @mode: The migration mode.
216  *
217  * Migrate an isolated movable_ops page.
218  *
219  * If the src page was already released by its owner, the src page is
220  * un-isolated (putback) and migration succeeds; the migration core will be the
221  * owner of both pages.
222  *
223  * If the src page was not released by its owner and the migration was
224  * successful, the owner of the src page and the dst page are swapped and
225  * the src page is un-isolated.
226  *
227  * If migration fails, the ownership stays unmodified and the src page
228  * remains isolated: migration may be retried later or the page can be putback.
229  *
230  * TODO: migration core will treat both pages as folios and lock them before
231  * this call to unlock them after this call. Further, the folio refcounts on
232  * src and dst are also released by migration core. These pages will not be
233  * folios in the future, so that must be reworked.
234  *
235  * Returns 0 on success, otherwise a negative error code.
236  */
237 static int migrate_movable_ops_page(struct page *dst, struct page *src,
238 		enum migrate_mode mode)
239 {
240 	int rc;
241 
242 	VM_WARN_ON_ONCE_PAGE(!page_has_movable_ops(src), src);
243 	VM_WARN_ON_ONCE_PAGE(!PageMovableOpsIsolated(src), src);
244 	rc = page_movable_ops(src)->migrate_page(dst, src, mode);
245 	if (!rc)
246 		ClearPageMovableOpsIsolated(src);
247 	return rc;
248 }
249 
250 /*
251  * Put previously isolated pages back onto the appropriate lists
252  * from where they were once taken off for compaction/migration.
253  *
254  * This function shall be used whenever the isolated pageset has been
255  * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
256  * and folio_isolate_hugetlb().
257  */
258 void putback_movable_pages(struct list_head *l)
259 {
260 	struct folio *folio;
261 	struct folio *folio2;
262 
263 	list_for_each_entry_safe(folio, folio2, l, lru) {
264 		if (unlikely(folio_test_hugetlb(folio))) {
265 			folio_putback_hugetlb(folio);
266 			continue;
267 		}
268 		list_del(&folio->lru);
269 		if (unlikely(page_has_movable_ops(&folio->page))) {
270 			putback_movable_ops_page(&folio->page);
271 		} else {
272 			node_stat_mod_folio(folio, NR_ISOLATED_ANON +
273 					folio_is_file_lru(folio), -folio_nr_pages(folio));
274 			folio_putback_lru(folio);
275 		}
276 	}
277 }
278 
279 /* Must be called with an elevated refcount on the non-hugetlb folio */
280 bool isolate_folio_to_list(struct folio *folio, struct list_head *list)
281 {
282 	if (folio_test_hugetlb(folio))
283 		return folio_isolate_hugetlb(folio, list);
284 
285 	if (page_has_movable_ops(&folio->page)) {
286 		if (!isolate_movable_ops_page(&folio->page,
287 					      ISOLATE_UNEVICTABLE))
288 			return false;
289 	} else {
290 		if (!folio_isolate_lru(folio))
291 			return false;
292 		node_stat_add_folio(folio, NR_ISOLATED_ANON +
293 				    folio_is_file_lru(folio));
294 	}
295 	list_add(&folio->lru, list);
296 	return true;
297 }
298 
299 static bool try_to_map_unused_to_zeropage(struct page_vma_mapped_walk *pvmw,
300 		struct folio *folio, pte_t old_pte, unsigned long idx)
301 {
302 	struct page *page = folio_page(folio, idx);
303 	pte_t newpte;
304 
305 	if (PageCompound(page) || PageHWPoison(page))
306 		return false;
307 
308 	VM_BUG_ON_PAGE(!PageAnon(page), page);
309 	VM_BUG_ON_PAGE(!PageLocked(page), page);
310 	VM_BUG_ON_PAGE(pte_present(old_pte), page);
311 	VM_WARN_ON_ONCE_FOLIO(folio_is_device_private(folio), folio);
312 
313 	if (folio_test_mlocked(folio) || (pvmw->vma->vm_flags & VM_LOCKED) ||
314 	    mm_forbids_zeropage(pvmw->vma->vm_mm))
315 		return false;
316 
317 	/*
318 	 * The pmd entry mapping the old thp was flushed and the pte mapping
319 	 * this subpage has been non present. If the subpage is only zero-filled
320 	 * then map it to the shared zeropage.
321 	 */
322 	if (!pages_identical(page, ZERO_PAGE(0)))
323 		return false;
324 
325 	newpte = pte_mkspecial(pfn_pte(zero_pfn(pvmw->address),
326 					pvmw->vma->vm_page_prot));
327 
328 	if (pte_swp_soft_dirty(old_pte))
329 		newpte = pte_mksoft_dirty(newpte);
330 	if (pte_swp_uffd(old_pte))
331 		newpte = pte_mkuffd(newpte);
332 
333 	/* See remove_migration_pte(): restore PAGE_NONE for RWP */
334 	if (pte_swp_uffd(old_pte) && userfaultfd_rwp(pvmw->vma))
335 		newpte = pte_modify(newpte, PAGE_NONE);
336 
337 	set_pte_at(pvmw->vma->vm_mm, pvmw->address, pvmw->pte, newpte);
338 
339 	dec_mm_counter(pvmw->vma->vm_mm, mm_counter(folio));
340 	return true;
341 }
342 
343 struct rmap_walk_arg {
344 	struct folio *folio;
345 	bool map_unused_to_zeropage;
346 };
347 
348 /*
349  * Restore a potential migration pte to a working pte entry
350  */
351 static bool remove_migration_pte(struct folio *folio,
352 		struct vm_area_struct *vma, unsigned long addr, void *arg)
353 {
354 	struct rmap_walk_arg *rmap_walk_arg = arg;
355 	DEFINE_FOLIO_VMA_WALK(pvmw, rmap_walk_arg->folio, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
356 
357 	while (page_vma_mapped_walk(&pvmw)) {
358 		rmap_t rmap_flags = RMAP_NONE;
359 		unsigned long idx = 0;
360 		softleaf_t entry;
361 		struct page *new;
362 		pte_t old_pte;
363 		pte_t pte;
364 
365 #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
366 		/* PMD-mapped THP migration entry */
367 		if (!pvmw.pte) {
368 			VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
369 					!folio_test_pmd_mappable(folio), folio);
370 			remove_migration_pmd(&pvmw, folio);
371 			continue;
372 		}
373 #endif
374 		if (folio_test_hugetlb(folio))
375 			old_pte = huge_ptep_get(vma->vm_mm, pvmw.address,
376 						pvmw.pte);
377 		else
378 			old_pte = ptep_get(pvmw.pte);
379 
380 		entry = softleaf_from_pte(old_pte);
381 		if (folio_test_large(folio) && !folio_test_hugetlb(folio))
382 			idx = softleaf_to_pfn(entry) - pvmw.pfn;
383 
384 		if (rmap_walk_arg->map_unused_to_zeropage &&
385 		    try_to_map_unused_to_zeropage(&pvmw, folio, old_pte, idx))
386 			continue;
387 
388 		folio_get(folio);
389 		new = folio_page(folio, idx);
390 		pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
391 		if (!softleaf_is_migration_young(entry))
392 			pte = pte_mkold(pte);
393 		if (folio_test_dirty(folio) && softleaf_is_migration_dirty(entry))
394 			pte = pte_mkdirty(pte);
395 		if (pte_swp_soft_dirty(old_pte))
396 			pte = pte_mksoft_dirty(pte);
397 		else
398 			pte = pte_clear_soft_dirty(pte);
399 
400 		if (softleaf_is_migration_write(entry))
401 			pte = pte_mkwrite(pte, vma);
402 		else if (pte_swp_uffd(old_pte))
403 			pte = pte_mkuffd(pte);
404 
405 		/* See do_swap_page(): restore PAGE_NONE for RWP */
406 		if (pte_swp_uffd(old_pte) && userfaultfd_rwp(vma))
407 			pte = pte_modify(pte, PAGE_NONE);
408 
409 		if (folio_test_anon(folio) && !softleaf_is_migration_read(entry))
410 			rmap_flags |= RMAP_EXCLUSIVE;
411 
412 		if (unlikely(is_device_private_page(new))) {
413 			if (pte_write(pte))
414 				entry = make_writable_device_private_entry(
415 							page_to_pfn(new));
416 			else
417 				entry = make_readable_device_private_entry(
418 							page_to_pfn(new));
419 			pte = softleaf_to_pte(entry);
420 			if (pte_swp_soft_dirty(old_pte))
421 				pte = pte_swp_mksoft_dirty(pte);
422 			if (pte_swp_uffd(old_pte))
423 				pte = pte_swp_mkuffd(pte);
424 		}
425 
426 #ifdef CONFIG_HUGETLB_PAGE
427 		if (folio_test_hugetlb(folio)) {
428 			struct hstate *h = hstate_vma(vma);
429 			unsigned int shift = huge_page_shift(h);
430 			unsigned long psize = huge_page_size(h);
431 
432 			pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
433 			if (folio_test_anon(folio))
434 				hugetlb_add_anon_rmap(folio, vma, pvmw.address,
435 						      rmap_flags);
436 			else
437 				hugetlb_add_file_rmap(folio);
438 			set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte,
439 					psize);
440 		} else
441 #endif
442 		{
443 			if (folio_test_anon(folio))
444 				folio_add_anon_rmap_pte(folio, new, vma,
445 							pvmw.address, rmap_flags);
446 			else
447 				folio_add_file_rmap_pte(folio, new, vma);
448 			set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
449 		}
450 		if (READ_ONCE(vma->vm_flags) & VM_LOCKED)
451 			mlock_drain_local();
452 
453 		trace_remove_migration_pte(pvmw.address, pte_val(pte),
454 					   compound_order(new));
455 
456 		/* No need to invalidate - it was non-present before */
457 		update_mmu_cache(vma, pvmw.address, pvmw.pte);
458 	}
459 
460 	return true;
461 }
462 
463 /*
464  * Get rid of all migration entries and replace them by
465  * references to the indicated page.
466  */
467 void remove_migration_ptes(struct folio *src, struct folio *dst,
468 		enum ttu_flags flags)
469 {
470 	struct rmap_walk_arg rmap_walk_arg = {
471 		.folio = src,
472 		.map_unused_to_zeropage = flags & TTU_USE_SHARED_ZEROPAGE,
473 	};
474 
475 	struct rmap_walk_control rwc = {
476 		.rmap_one = remove_migration_pte,
477 		.arg = &rmap_walk_arg,
478 	};
479 
480 	VM_BUG_ON_FOLIO((flags & TTU_USE_SHARED_ZEROPAGE) && (src != dst), src);
481 
482 	if (flags & TTU_RMAP_LOCKED)
483 		rmap_walk_locked(dst, &rwc);
484 	else
485 		rmap_walk(dst, &rwc);
486 }
487 
488 /*
489  * Something used the pte of a page under migration. We need to
490  * get to the page and wait until migration is finished.
491  * When we return from this function the fault will be retried.
492  */
493 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
494 			  unsigned long address)
495 {
496 	spinlock_t *ptl;
497 	pte_t *ptep;
498 	pte_t pte;
499 	softleaf_t entry;
500 
501 	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
502 	if (!ptep)
503 		return;
504 
505 	pte = ptep_get(ptep);
506 	pte_unmap(ptep);
507 
508 	if (pte_none(pte) || pte_present(pte))
509 		goto out;
510 
511 	entry = softleaf_from_pte(pte);
512 	if (!softleaf_is_migration(entry))
513 		goto out;
514 
515 	softleaf_entry_wait_on_locked(entry, ptl);
516 	return;
517 out:
518 	spin_unlock(ptl);
519 }
520 
521 #ifdef CONFIG_HUGETLB_PAGE
522 /*
523  * The vma read lock must be held upon entry. Holding that lock prevents either
524  * the pte or the ptl from being freed.
525  *
526  * This function will release the vma lock before returning.
527  */
528 void migration_entry_wait_huge(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep)
529 {
530 	spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, ptep);
531 	softleaf_t entry;
532 	pte_t pte;
533 
534 	hugetlb_vma_assert_locked(vma);
535 	spin_lock(ptl);
536 	pte = huge_ptep_get(vma->vm_mm, addr, ptep);
537 
538 	if (huge_pte_none(pte))
539 		goto fail;
540 
541 	entry = softleaf_from_pte(pte);
542 	if (softleaf_is_migration(entry)) {
543 		/*
544 		 * If migration entry existed, safe to release vma lock
545 		 * here because the pgtable page won't be freed without the
546 		 * pgtable lock released.  See comment right above pgtable
547 		 * lock release in softleaf_entry_wait_on_locked().
548 		 */
549 		hugetlb_vma_unlock_read(vma);
550 		softleaf_entry_wait_on_locked(entry, ptl);
551 		return;
552 	}
553 
554 fail:
555 	spin_unlock(ptl);
556 	hugetlb_vma_unlock_read(vma);
557 }
558 #endif
559 
560 #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
561 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
562 {
563 	spinlock_t *ptl;
564 
565 	ptl = pmd_lock(mm, pmd);
566 	if (!pmd_is_migration_entry(*pmd))
567 		goto unlock;
568 	softleaf_entry_wait_on_locked(softleaf_from_pmd(*pmd), ptl);
569 	return;
570 unlock:
571 	spin_unlock(ptl);
572 }
573 #endif
574 
575 /*
576  * Replace the folio in the mapping.
577  *
578  * The number of remaining references must be:
579  * 1 for anonymous folios without a mapping
580  * 2 for folios with a mapping
581  * 3 for folios with a mapping and the private flag set.
582  */
583 static int __folio_migrate_mapping(struct address_space *mapping,
584 		struct folio *newfolio, struct folio *folio, int expected_count)
585 {
586 	XA_STATE(xas, &mapping->i_pages, folio->index);
587 	struct swap_cluster_info *ci = NULL;
588 	struct zone *oldzone, *newzone;
589 	int dirty;
590 	long nr = folio_nr_pages(folio);
591 
592 	if (!mapping) {
593 		/* Take off deferred split queue while frozen and memcg set */
594 		if (folio_test_large(folio) &&
595 		    folio_test_large_rmappable(folio)) {
596 			if (!folio_ref_freeze(folio, expected_count))
597 				return -EAGAIN;
598 			folio_unqueue_deferred_split(folio);
599 			folio_ref_unfreeze(folio, expected_count);
600 		}
601 
602 		/* No turning back from here */
603 		newfolio->index = folio->index;
604 		newfolio->mapping = folio->mapping;
605 		if (folio_test_anon(folio) && folio_test_large(folio) &&
606 		    !folio_test_hugetlb(folio))
607 			mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
608 		if (folio_test_swapbacked(folio))
609 			__folio_set_swapbacked(newfolio);
610 
611 		return 0;
612 	}
613 
614 	oldzone = folio_zone(folio);
615 	newzone = folio_zone(newfolio);
616 
617 	if (folio_test_swapcache(folio))
618 		ci = swap_cluster_get_and_lock_irq(folio);
619 	else
620 		xas_lock_irq(&xas);
621 
622 	if (!folio_ref_freeze(folio, expected_count)) {
623 		if (ci)
624 			swap_cluster_unlock_irq(ci);
625 		else
626 			xas_unlock_irq(&xas);
627 		return -EAGAIN;
628 	}
629 
630 	/* Take off deferred split queue while frozen and memcg set */
631 	folio_unqueue_deferred_split(folio);
632 
633 	/*
634 	 * Now we know that no one else is looking at the folio:
635 	 * no turning back from here.
636 	 */
637 	newfolio->index = folio->index;
638 	newfolio->mapping = folio->mapping;
639 	if (folio_test_anon(folio) && folio_test_large(folio))
640 		mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
641 	folio_ref_add(newfolio, nr); /* add cache reference */
642 	if (folio_test_swapbacked(folio))
643 		__folio_set_swapbacked(newfolio);
644 	if (folio_test_swapcache(folio)) {
645 		folio_set_swapcache(newfolio);
646 		newfolio->private = folio_get_private(folio);
647 	}
648 
649 	/* Move dirty while folio refs frozen and newfolio not yet exposed */
650 	dirty = folio_test_dirty(folio);
651 	if (dirty) {
652 		folio_clear_dirty(folio);
653 		folio_set_dirty(newfolio);
654 	}
655 
656 	if (folio_test_swapcache(folio))
657 		__swap_cache_replace_folio(ci, folio, newfolio);
658 	else
659 		xas_store(&xas, newfolio);
660 
661 	/*
662 	 * Drop cache reference from old folio by unfreezing
663 	 * to one less reference.
664 	 * We know this isn't the last reference.
665 	 */
666 	folio_ref_unfreeze(folio, expected_count - nr);
667 
668 	/* Leave irq disabled to prevent preemption while updating stats */
669 	if (ci)
670 		swap_cluster_unlock(ci);
671 	else
672 		xas_unlock(&xas);
673 
674 	/*
675 	 * If moved to a different zone then also account
676 	 * the folio for that zone. Other VM counters will be
677 	 * taken care of when we establish references to the
678 	 * new folio and drop references to the old folio.
679 	 *
680 	 * Note that anonymous folios are accounted for
681 	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
682 	 * are mapped to swap space.
683 	 */
684 	if (newzone != oldzone) {
685 		struct lruvec *old_lruvec, *new_lruvec;
686 		struct mem_cgroup *memcg;
687 
688 		rcu_read_lock();
689 		memcg = folio_memcg(folio);
690 		old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
691 		new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
692 
693 		mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
694 		mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
695 		if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
696 			mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
697 			mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
698 
699 			if (folio_test_pmd_mappable(folio)) {
700 				mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr);
701 				mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr);
702 			}
703 		}
704 #ifdef CONFIG_SWAP
705 		if (folio_test_swapcache(folio)) {
706 			mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
707 			mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
708 		}
709 #endif
710 		if (dirty && mapping_can_writeback(mapping)) {
711 			mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
712 			__mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
713 			mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
714 			__mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
715 		}
716 		rcu_read_unlock();
717 	}
718 	local_irq_enable();
719 
720 	return 0;
721 }
722 
723 int folio_migrate_mapping(struct address_space *mapping,
724 		struct folio *newfolio, struct folio *folio, int extra_count)
725 {
726 	int expected_count = folio_expected_ref_count(folio) + extra_count + 1;
727 
728 	if (folio_ref_count(folio) != expected_count)
729 		return -EAGAIN;
730 
731 	return __folio_migrate_mapping(mapping, newfolio, folio, expected_count);
732 }
733 EXPORT_SYMBOL(folio_migrate_mapping);
734 
735 /*
736  * The expected number of remaining references is the same as that
737  * of folio_migrate_mapping().
738  */
739 int migrate_huge_page_move_mapping(struct address_space *mapping,
740 				   struct folio *dst, struct folio *src)
741 {
742 	XA_STATE(xas, &mapping->i_pages, src->index);
743 	int rc, expected_count = folio_expected_ref_count(src) + 1;
744 
745 	if (folio_ref_count(src) != expected_count)
746 		return -EAGAIN;
747 
748 	rc = folio_mc_copy(dst, src);
749 	if (unlikely(rc))
750 		return rc;
751 
752 	xas_lock_irq(&xas);
753 	if (!folio_ref_freeze(src, expected_count)) {
754 		xas_unlock_irq(&xas);
755 		return -EAGAIN;
756 	}
757 
758 	dst->index = src->index;
759 	dst->mapping = src->mapping;
760 
761 	folio_ref_add(dst, folio_nr_pages(dst));
762 
763 	xas_store(&xas, dst);
764 
765 	folio_ref_unfreeze(src, expected_count - folio_nr_pages(src));
766 
767 	xas_unlock_irq(&xas);
768 
769 	return 0;
770 }
771 
772 /*
773  * Copy the flags and some other ancillary information
774  */
775 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
776 {
777 	int cpupid;
778 
779 	/* Copy the reference state, including PG_referenced */
780 	folio_migrate_lru_refs(newfolio, folio);
781 
782 	if (folio_test_uptodate(folio))
783 		folio_mark_uptodate(newfolio);
784 	if (folio_test_clear_active(folio)) {
785 		VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
786 		folio_set_active(newfolio);
787 	} else if (folio_test_clear_unevictable(folio))
788 		folio_set_unevictable(newfolio);
789 	if (folio_test_workingset(folio))
790 		folio_set_workingset(newfolio);
791 	if (folio_test_checked(folio))
792 		folio_set_checked(newfolio);
793 	/*
794 	 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
795 	 * migration entries. We can still have PG_anon_exclusive set on an
796 	 * effectively unmapped and unreferenced first sub-pages of an
797 	 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
798 	 */
799 	if (folio_test_mappedtodisk(folio))
800 		folio_set_mappedtodisk(newfolio);
801 
802 	/* Move dirty on pages not done by folio_migrate_mapping() */
803 	if (folio_test_dirty(folio))
804 		folio_set_dirty(newfolio);
805 
806 	if (folio_test_young(folio))
807 		folio_set_young(newfolio);
808 	if (folio_test_idle(folio))
809 		folio_set_idle(newfolio);
810 
811 	/*
812 	 * Copy NUMA information to the new page, to prevent over-eager
813 	 * future migrations of this same page.
814 	 */
815 	cpupid = folio_xchg_last_cpupid(folio, -1);
816 	/*
817 	 * For memory tiering mode, when migrate between slow and fast
818 	 * memory node, reset cpupid, because that is used to record
819 	 * page access time in slow memory node.
820 	 */
821 	if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
822 		bool f_toptier = node_is_toptier(folio_nid(folio));
823 		bool t_toptier = node_is_toptier(folio_nid(newfolio));
824 
825 		if (f_toptier != t_toptier)
826 			cpupid = -1;
827 	}
828 	folio_xchg_last_cpupid(newfolio, cpupid);
829 
830 	folio_migrate_ksm(newfolio, folio);
831 	/*
832 	 * Please do not reorder this without considering how mm/ksm.c's
833 	 * ksm_get_folio() depends upon ksm_migrate_page() and the
834 	 * swapcache flag.
835 	 */
836 	if (folio_test_swapcache(folio))
837 		folio_clear_swapcache(folio);
838 
839 	/* page->private contains hugetlb specific flags */
840 	if (!folio_test_hugetlb(folio))
841 		folio->private = NULL;
842 
843 	/*
844 	 * If any waiters have accumulated on the new page then
845 	 * wake them up.
846 	 */
847 	if (folio_test_writeback(newfolio))
848 		folio_end_writeback(newfolio);
849 
850 	/*
851 	 * PG_readahead shares the same bit with PG_reclaim.  The above
852 	 * end_page_writeback() may clear PG_readahead mistakenly, so set the
853 	 * bit after that.
854 	 */
855 	if (folio_test_readahead(folio))
856 		folio_set_readahead(newfolio);
857 
858 	folio_copy_owner(newfolio, folio);
859 	pgalloc_tag_swap(newfolio, folio);
860 
861 	mem_cgroup_migrate(folio, newfolio);
862 }
863 EXPORT_SYMBOL(folio_migrate_flags);
864 
865 /************************************************************
866  *                    Migration functions
867  ***********************************************************/
868 
869 static int __migrate_folio(struct address_space *mapping, struct folio *dst,
870 			   struct folio *src, void *src_private,
871 			   enum migrate_mode mode)
872 {
873 	int rc, expected_count = folio_expected_ref_count(src) + 1;
874 
875 	/* Check whether src does not have extra refs before we do more work */
876 	if (folio_ref_count(src) != expected_count)
877 		return -EAGAIN;
878 
879 	rc = folio_mc_copy(dst, src);
880 	if (unlikely(rc))
881 		return rc;
882 
883 	rc = __folio_migrate_mapping(mapping, dst, src, expected_count);
884 	if (rc)
885 		return rc;
886 
887 	if (src_private)
888 		folio_attach_private(dst, folio_detach_private(src));
889 
890 	folio_migrate_flags(dst, src);
891 	return 0;
892 }
893 
894 /**
895  * migrate_folio() - Simple folio migration.
896  * @mapping: The address_space containing the folio.
897  * @dst: The folio to migrate the data to.
898  * @src: The folio containing the current data.
899  * @mode: How to migrate the folio.
900  *
901  * Common logic to directly migrate a single LRU folio suitable for
902  * folios that do not have private data.
903  *
904  * Folios are locked upon entry and exit.
905  */
906 int migrate_folio(struct address_space *mapping, struct folio *dst,
907 		  struct folio *src, enum migrate_mode mode)
908 {
909 	BUG_ON(folio_test_writeback(src));	/* Writeback must be complete */
910 	return __migrate_folio(mapping, dst, src, NULL, mode);
911 }
912 EXPORT_SYMBOL(migrate_folio);
913 
914 #ifdef CONFIG_BUFFER_HEAD
915 /* Returns true if all buffers are successfully locked */
916 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
917 							enum migrate_mode mode)
918 {
919 	struct buffer_head *bh = head;
920 	struct buffer_head *failed_bh;
921 
922 	do {
923 		if (!trylock_buffer(bh)) {
924 			if (mode == MIGRATE_ASYNC)
925 				goto unlock;
926 			if (mode == MIGRATE_SYNC_LIGHT && !buffer_uptodate(bh))
927 				goto unlock;
928 			lock_buffer(bh);
929 		}
930 
931 		bh = bh->b_this_page;
932 	} while (bh != head);
933 
934 	return true;
935 
936 unlock:
937 	/* We failed to lock the buffer and cannot stall. */
938 	failed_bh = bh;
939 	bh = head;
940 	while (bh != failed_bh) {
941 		unlock_buffer(bh);
942 		bh = bh->b_this_page;
943 	}
944 
945 	return false;
946 }
947 
948 static int __buffer_migrate_folio(struct address_space *mapping,
949 		struct folio *dst, struct folio *src, enum migrate_mode mode,
950 		bool check_refs)
951 {
952 	struct buffer_head *bh, *head;
953 	int rc;
954 	int expected_count;
955 
956 	head = folio_buffers(src);
957 	if (!head)
958 		return migrate_folio(mapping, dst, src, mode);
959 
960 	/* Check whether page does not have extra refs before we do more work */
961 	expected_count = folio_expected_ref_count(src) + 1;
962 	if (folio_ref_count(src) != expected_count)
963 		return -EAGAIN;
964 
965 	if (!buffer_migrate_lock_buffers(head, mode))
966 		return -EAGAIN;
967 
968 	if (check_refs) {
969 		bool busy, migrating;
970 		bool invalidated = false;
971 
972 		migrating = test_and_set_bit_lock(BH_Migrate, &head->b_state);
973 		VM_WARN_ON_ONCE(migrating);
974 recheck_buffers:
975 		busy = false;
976 		spin_lock(&mapping->i_private_lock);
977 		bh = head;
978 		do {
979 			if (atomic_read(&bh->b_count)) {
980 				busy = true;
981 				break;
982 			}
983 			bh = bh->b_this_page;
984 		} while (bh != head);
985 		spin_unlock(&mapping->i_private_lock);
986 		if (busy) {
987 			if (invalidated) {
988 				rc = -EAGAIN;
989 				goto unlock_buffers;
990 			}
991 			invalidate_bh_lrus();
992 			invalidated = true;
993 			goto recheck_buffers;
994 		}
995 	}
996 
997 	rc = filemap_migrate_folio(mapping, dst, src, mode);
998 	if (rc)
999 		goto unlock_buffers;
1000 
1001 	bh = head;
1002 	do {
1003 		folio_set_bh(bh, dst, bh_offset(bh));
1004 		bh = bh->b_this_page;
1005 	} while (bh != head);
1006 
1007 unlock_buffers:
1008 	if (check_refs)
1009 		clear_bit_unlock(BH_Migrate, &head->b_state);
1010 	bh = head;
1011 	do {
1012 		unlock_buffer(bh);
1013 		bh = bh->b_this_page;
1014 	} while (bh != head);
1015 
1016 	return rc;
1017 }
1018 
1019 /**
1020  * buffer_migrate_folio() - Migration function for folios with buffers.
1021  * @mapping: The address space containing @src.
1022  * @dst: The folio to migrate to.
1023  * @src: The folio to migrate from.
1024  * @mode: How to migrate the folio.
1025  *
1026  * This function can only be used if the underlying filesystem guarantees
1027  * that no other references to @src exist. For example attached buffer
1028  * heads are accessed only under the folio lock.  If your filesystem cannot
1029  * provide this guarantee, buffer_migrate_folio_norefs() may be more
1030  * appropriate.
1031  *
1032  * Return: 0 on success or a negative errno on failure.
1033  */
1034 int buffer_migrate_folio(struct address_space *mapping,
1035 		struct folio *dst, struct folio *src, enum migrate_mode mode)
1036 {
1037 	return __buffer_migrate_folio(mapping, dst, src, mode, false);
1038 }
1039 EXPORT_SYMBOL(buffer_migrate_folio);
1040 
1041 /**
1042  * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
1043  * @mapping: The address space containing @src.
1044  * @dst: The folio to migrate to.
1045  * @src: The folio to migrate from.
1046  * @mode: How to migrate the folio.
1047  *
1048  * Like buffer_migrate_folio() except that this variant is more careful
1049  * and checks that there are also no buffer head references. This function
1050  * is the right one for mappings where buffer heads are directly looked
1051  * up and referenced (such as block device mappings).
1052  *
1053  * Return: 0 on success or a negative errno on failure.
1054  */
1055 int buffer_migrate_folio_norefs(struct address_space *mapping,
1056 		struct folio *dst, struct folio *src, enum migrate_mode mode)
1057 {
1058 	return __buffer_migrate_folio(mapping, dst, src, mode, true);
1059 }
1060 EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
1061 #endif /* CONFIG_BUFFER_HEAD */
1062 
1063 int filemap_migrate_folio(struct address_space *mapping,
1064 		struct folio *dst, struct folio *src, enum migrate_mode mode)
1065 {
1066 	return __migrate_folio(mapping, dst, src, folio_get_private(src), mode);
1067 }
1068 EXPORT_SYMBOL_GPL(filemap_migrate_folio);
1069 
1070 /*
1071  * Default handling if a filesystem does not provide a migration function.
1072  */
1073 static int fallback_migrate_folio(struct address_space *mapping,
1074 		struct folio *dst, struct folio *src, enum migrate_mode mode)
1075 {
1076 	WARN_ONCE(mapping->a_ops->writepages,
1077 			"%ps does not implement migrate_folio\n",
1078 			mapping->a_ops);
1079 	if (folio_test_dirty(src))
1080 		return -EBUSY;
1081 
1082 	/*
1083 	 * Filesystem may have private data at folio->private that we
1084 	 * can't migrate automatically.
1085 	 */
1086 	if (!filemap_release_folio(src, GFP_KERNEL))
1087 		return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
1088 
1089 	return migrate_folio(mapping, dst, src, mode);
1090 }
1091 
1092 /*
1093  * Move a src folio to a newly allocated dst folio.
1094  *
1095  * The src and dst folios are locked and the src folios was unmapped from
1096  * the page tables.
1097  *
1098  * On success, the src folio was replaced by the dst folio.
1099  *
1100  * Return value:
1101  *   < 0 - error code
1102  *     0 - success
1103  */
1104 static int move_to_new_folio(struct folio *dst, struct folio *src,
1105 				enum migrate_mode mode)
1106 {
1107 	struct address_space *mapping = folio_mapping(src);
1108 	int rc = -EAGAIN;
1109 
1110 	VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
1111 	VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
1112 
1113 	if (!mapping)
1114 		rc = migrate_folio(mapping, dst, src, mode);
1115 	else if (mapping_inaccessible(mapping))
1116 		rc = -EOPNOTSUPP;
1117 	else if (mapping->a_ops->migrate_folio)
1118 		/*
1119 		 * Most folios have a mapping and most filesystems
1120 		 * provide a migrate_folio callback. Anonymous folios
1121 		 * are part of swap space which also has its own
1122 		 * migrate_folio callback. This is the most common path
1123 		 * for page migration.
1124 		 */
1125 		rc = mapping->a_ops->migrate_folio(mapping, dst, src,
1126 							mode);
1127 	else
1128 		rc = fallback_migrate_folio(mapping, dst, src, mode);
1129 
1130 	if (!rc) {
1131 		/*
1132 		 * For pagecache folios, src->mapping must be cleared before src
1133 		 * is freed. Anonymous folios must stay anonymous until freed.
1134 		 */
1135 		if (!folio_test_anon(src))
1136 			src->mapping = NULL;
1137 
1138 		if (likely(!folio_is_zone_device(dst)))
1139 			flush_dcache_folio(dst);
1140 	}
1141 	return rc;
1142 }
1143 
1144 /*
1145  * To record some information during migration, we use the migrate_info
1146  * field of struct folio of the newly allocated destination folio.
1147  * This is safe because nobody is using it except us.
1148  */
1149 enum {
1150 	FOLIO_WAS_MAPPED = BIT(0),
1151 	FOLIO_WAS_MLOCKED = BIT(1),
1152 	FOLIO_OLD_STATES = FOLIO_WAS_MAPPED | FOLIO_WAS_MLOCKED,
1153 };
1154 
1155 static void __migrate_folio_record(struct folio *dst,
1156 		int old_folio_state, struct anon_vma *anon_vma)
1157 {
1158 	dst->migrate_info = (unsigned long)anon_vma | old_folio_state;
1159 }
1160 
1161 static void __migrate_folio_extract(struct folio *dst,
1162 		int *old_folio_state, struct anon_vma **anon_vmap)
1163 {
1164 	unsigned long info = dst->migrate_info;
1165 
1166 	*anon_vmap = (struct anon_vma *)(info & ~FOLIO_OLD_STATES);
1167 	*old_folio_state = info & FOLIO_OLD_STATES;
1168 	dst->migrate_info = 0;
1169 }
1170 
1171 /* Restore the source folio to the original state upon failure */
1172 static void migrate_folio_undo_src(struct folio *src, int was_mapped,
1173 		struct anon_vma *anon_vma, bool locked, struct list_head *ret)
1174 {
1175 	if (was_mapped)
1176 		remove_migration_ptes(src, src, 0);
1177 	/* Drop an anon_vma reference if we took one */
1178 	if (anon_vma)
1179 		put_anon_vma(anon_vma);
1180 	if (locked)
1181 		folio_unlock(src);
1182 	if (ret)
1183 		list_move_tail(&src->lru, ret);
1184 }
1185 
1186 /* Restore the destination folio to the original state upon failure */
1187 static void migrate_folio_undo_dst(struct folio *dst, bool locked,
1188 		free_folio_t put_new_folio, unsigned long private)
1189 {
1190 	if (locked)
1191 		folio_unlock(dst);
1192 	if (put_new_folio)
1193 		put_new_folio(dst, private);
1194 	else
1195 		folio_put(dst);
1196 }
1197 
1198 /* Cleanup src folio upon migration success */
1199 static void migrate_folio_done(struct folio *src,
1200 			       enum migrate_reason reason)
1201 {
1202 	if (likely(!page_has_movable_ops(&src->page)) && reason != MR_DEMOTION)
1203 		mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
1204 				    folio_is_file_lru(src), -folio_nr_pages(src));
1205 
1206 	if (reason != MR_MEMORY_FAILURE)
1207 		/* We release the page in page_handle_poison. */
1208 		folio_put(src);
1209 }
1210 
1211 /* Obtain the lock on page, remove all ptes. */
1212 static int migrate_folio_unmap(new_folio_t get_new_folio,
1213 		free_folio_t put_new_folio, unsigned long private,
1214 		struct folio *src, struct folio **dstp, enum migrate_mode mode,
1215 		struct list_head *ret)
1216 {
1217 	struct folio *dst;
1218 	int rc = -EAGAIN;
1219 	int old_folio_state = 0;
1220 	struct anon_vma *anon_vma = NULL;
1221 	bool locked = false;
1222 	bool dst_locked = false;
1223 
1224 	dst = get_new_folio(src, private);
1225 	if (!dst)
1226 		return -ENOMEM;
1227 	*dstp = dst;
1228 
1229 	dst->migrate_info = 0;
1230 
1231 	if (!folio_trylock(src)) {
1232 		if (mode == MIGRATE_ASYNC)
1233 			goto out;
1234 
1235 		/*
1236 		 * It's not safe for direct compaction to call lock_page.
1237 		 * For example, during page readahead pages are added locked
1238 		 * to the LRU. Later, when the IO completes the pages are
1239 		 * marked uptodate and unlocked. However, the queueing
1240 		 * could be merging multiple pages for one bio (e.g.
1241 		 * mpage_readahead). If an allocation happens for the
1242 		 * second or third page, the process can end up locking
1243 		 * the same page twice and deadlocking. Rather than
1244 		 * trying to be clever about what pages can be locked,
1245 		 * avoid the use of lock_page for direct compaction
1246 		 * altogether.
1247 		 */
1248 		if (current->flags & PF_MEMALLOC)
1249 			goto out;
1250 
1251 		/*
1252 		 * In "light" mode, we can wait for transient locks (eg
1253 		 * inserting a page into the page table), but it's not
1254 		 * worth waiting for I/O.
1255 		 */
1256 		if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
1257 			goto out;
1258 
1259 		folio_lock(src);
1260 	}
1261 	locked = true;
1262 	if (folio_test_mlocked(src))
1263 		old_folio_state |= FOLIO_WAS_MLOCKED;
1264 
1265 	if (folio_test_writeback(src)) {
1266 		/*
1267 		 * Only in the case of a full synchronous migration is it
1268 		 * necessary to wait for writeback. In the async case,
1269 		 * the retry loop is too short and in the sync-light case,
1270 		 * the overhead of stalling is too much
1271 		 */
1272 		switch (mode) {
1273 		case MIGRATE_SYNC:
1274 			break;
1275 		default:
1276 			rc = -EBUSY;
1277 			goto out;
1278 		}
1279 		folio_wait_writeback(src);
1280 	}
1281 
1282 	/*
1283 	 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1284 	 * we cannot notice that anon_vma is freed while we migrate a page.
1285 	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1286 	 * of migration. File cache pages are no problem because of page_lock()
1287 	 * File Caches may use write_page() or lock_page() in migration, then,
1288 	 * just care Anon page here.
1289 	 *
1290 	 * Only folio_get_anon_vma() understands the subtleties of
1291 	 * getting a hold on an anon_vma from outside one of its mms.
1292 	 * But if we cannot get anon_vma, then we won't need it anyway,
1293 	 * because that implies that the anon page is no longer mapped
1294 	 * (and cannot be remapped so long as we hold the page lock).
1295 	 */
1296 	if (folio_test_anon(src) && !folio_test_ksm(src))
1297 		anon_vma = folio_get_anon_vma(src);
1298 
1299 	/*
1300 	 * Block others from accessing the new page when we get around to
1301 	 * establishing additional references. We are usually the only one
1302 	 * holding a reference to dst at this point. We used to have a BUG
1303 	 * here if folio_trylock(dst) fails, but would like to allow for
1304 	 * cases where there might be a race with the previous use of dst.
1305 	 * This is much like races on refcount of oldpage: just don't BUG().
1306 	 */
1307 	if (unlikely(!folio_trylock(dst)))
1308 		goto out;
1309 	dst_locked = true;
1310 
1311 	if (unlikely(page_has_movable_ops(&src->page))) {
1312 		__migrate_folio_record(dst, old_folio_state, anon_vma);
1313 		return 0;
1314 	}
1315 
1316 	/*
1317 	 * Corner case handling:
1318 	 * 1. When a new swap-cache page is read into, it is added to the LRU
1319 	 * and treated as swapcache but it has no rmap yet.
1320 	 * Calling try_to_unmap() against a src->mapping==NULL page will
1321 	 * trigger a BUG.  So handle it here.
1322 	 * 2. An orphaned page (see truncate_cleanup_page) might have
1323 	 * fs-private metadata. The page can be picked up due to memory
1324 	 * offlining.  Everywhere else except page reclaim, the page is
1325 	 * invisible to the vm, so the page can not be migrated.  So try to
1326 	 * free the metadata, so the page can be freed.
1327 	 */
1328 	if (!src->mapping) {
1329 		if (folio_has_attached_private(src)) {
1330 			try_to_free_buffers(src);
1331 			goto out;
1332 		}
1333 	} else if (folio_mapped(src)) {
1334 		/* Establish migration ptes */
1335 		VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1336 			       !folio_test_ksm(src) && !anon_vma, src);
1337 		try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
1338 		old_folio_state |= FOLIO_WAS_MAPPED;
1339 	}
1340 
1341 	if (!folio_mapped(src)) {
1342 		__migrate_folio_record(dst, old_folio_state, anon_vma);
1343 		return 0;
1344 	}
1345 
1346 out:
1347 	/*
1348 	 * A folio that has not been unmapped will be restored to
1349 	 * right list unless we want to retry.
1350 	 */
1351 	if (rc == -EAGAIN)
1352 		ret = NULL;
1353 
1354 	migrate_folio_undo_src(src, old_folio_state & FOLIO_WAS_MAPPED,
1355 			       anon_vma, locked, ret);
1356 	migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
1357 
1358 	return rc;
1359 }
1360 
1361 /* Migrate the folio to the newly allocated folio in dst. */
1362 static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
1363 			      struct folio *src, struct folio *dst,
1364 			      enum migrate_mode mode, enum migrate_reason reason,
1365 			      struct list_head *ret)
1366 {
1367 	int rc;
1368 	int old_folio_state = 0;
1369 	struct anon_vma *anon_vma = NULL;
1370 	bool src_deferred_split = false;
1371 	bool src_partially_mapped = false;
1372 	struct list_head *prev;
1373 
1374 	__migrate_folio_extract(dst, &old_folio_state, &anon_vma);
1375 	prev = dst->lru.prev;
1376 	list_del(&dst->lru);
1377 
1378 	if (unlikely(page_has_movable_ops(&src->page))) {
1379 		rc = migrate_movable_ops_page(&dst->page, &src->page, mode);
1380 		if (rc)
1381 			goto out;
1382 		goto out_unlock_both;
1383 	}
1384 
1385 	if (folio_order(src) > 1 &&
1386 	    !data_race(list_empty(&src->_deferred_list))) {
1387 		src_deferred_split = true;
1388 		src_partially_mapped = folio_test_partially_mapped(src);
1389 	}
1390 
1391 	rc = move_to_new_folio(dst, src, mode);
1392 	if (rc)
1393 		goto out;
1394 
1395 	/*
1396 	 * Requeue the destination folio on the deferred split queue if
1397 	 * the source was on the queue.  The source is unqueued in
1398 	 * __folio_migrate_mapping(), so we recorded the state from
1399 	 * before move_to_new_folio().
1400 	 */
1401 	if (src_deferred_split)
1402 		deferred_split_folio(dst, src_partially_mapped);
1403 
1404 	/*
1405 	 * When successful, push dst to LRU immediately: so that if it
1406 	 * turns out to be an mlocked page, remove_migration_ptes() will
1407 	 * automatically build up the correct dst->mlock_count for it.
1408 	 *
1409 	 * We would like to do something similar for the old page, when
1410 	 * unsuccessful, and other cases when a page has been temporarily
1411 	 * isolated from the unevictable LRU: but this case is the easiest.
1412 	 */
1413 	folio_add_lru(dst);
1414 	if (old_folio_state & FOLIO_WAS_MLOCKED)
1415 		lru_add_drain();
1416 
1417 	if (old_folio_state & FOLIO_WAS_MAPPED)
1418 		remove_migration_ptes(src, dst, 0);
1419 
1420 out_unlock_both:
1421 	folio_unlock(dst);
1422 	folio_set_owner_migrate_reason(dst, reason);
1423 	/*
1424 	 * If migration is successful, decrease refcount of dst,
1425 	 * which will not free the page because new page owner increased
1426 	 * refcounter.
1427 	 */
1428 	folio_put(dst);
1429 
1430 	/*
1431 	 * A folio that has been migrated has all references removed
1432 	 * and will be freed.
1433 	 */
1434 	list_del(&src->lru);
1435 	/* Drop an anon_vma reference if we took one */
1436 	if (anon_vma)
1437 		put_anon_vma(anon_vma);
1438 	folio_unlock(src);
1439 	migrate_folio_done(src, reason);
1440 
1441 	return rc;
1442 out:
1443 	/*
1444 	 * A folio that has not been migrated will be restored to
1445 	 * right list unless we want to retry.
1446 	 */
1447 	if (rc == -EAGAIN) {
1448 		list_add(&dst->lru, prev);
1449 		__migrate_folio_record(dst, old_folio_state, anon_vma);
1450 		return rc;
1451 	}
1452 
1453 	migrate_folio_undo_src(src, old_folio_state & FOLIO_WAS_MAPPED,
1454 			       anon_vma, true, ret);
1455 	migrate_folio_undo_dst(dst, true, put_new_folio, private);
1456 
1457 	return rc;
1458 }
1459 
1460 /*
1461  * Counterpart of migrate_folio_unmap() and migrate_folio_move() for hugetlb
1462  * folio migration.
1463  *
1464  * This function doesn't wait the completion of hugepage I/O
1465  * because there is no race between I/O and migration for hugepage.
1466  * Note that currently hugepage I/O occurs only in direct I/O
1467  * where no lock is held and PG_writeback is irrelevant,
1468  * and writeback status of all subpages are counted in the reference
1469  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1470  * under direct I/O, the reference of the head page is 512 and a bit more.)
1471  * This means that when we try to migrate hugepage whose subpages are
1472  * doing direct I/O, some references remain after try_to_unmap() and
1473  * hugepage migration fails without data corruption.
1474  *
1475  * There is also no race when direct I/O is issued on the page under migration,
1476  * because then pte is replaced with migration swap entry and direct I/O code
1477  * will wait in the page fault for migration to complete.
1478  */
1479 static int unmap_and_move_hugetlb_folio(new_folio_t get_new_folio,
1480 		free_folio_t put_new_folio, unsigned long private,
1481 		struct folio *src, int force, enum migrate_mode mode,
1482 		enum migrate_reason reason, struct list_head *ret)
1483 {
1484 	struct folio *dst;
1485 	int rc = -EAGAIN;
1486 	int was_mapped = 0;
1487 	struct anon_vma *anon_vma = NULL;
1488 	struct address_space *mapping = NULL;
1489 	enum ttu_flags ttu = 0;
1490 
1491 	if (folio_ref_count(src) == 1) {
1492 		/* folio was freed from under us. So we are done. */
1493 		folio_putback_hugetlb(src);
1494 		return 0;
1495 	}
1496 
1497 	dst = get_new_folio(src, private);
1498 	if (!dst)
1499 		return -ENOMEM;
1500 
1501 	if (!folio_trylock(src)) {
1502 		if (!force)
1503 			goto out;
1504 		switch (mode) {
1505 		case MIGRATE_SYNC:
1506 			break;
1507 		default:
1508 			goto out;
1509 		}
1510 		folio_lock(src);
1511 	}
1512 
1513 	/*
1514 	 * Check for folios which are in the process of being freed.  Without
1515 	 * folio_mapping() set, hugetlbfs specific move folio routine will not
1516 	 * be called and we could leak usage counts for subpools.
1517 	 */
1518 	if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1519 		rc = -EBUSY;
1520 		goto out_unlock;
1521 	}
1522 
1523 	if (folio_test_anon(src))
1524 		anon_vma = folio_get_anon_vma(src);
1525 
1526 	if (unlikely(!folio_trylock(dst)))
1527 		goto put_anon;
1528 
1529 	if (folio_mapped(src)) {
1530 		if (!folio_test_anon(src)) {
1531 			/*
1532 			 * In shared mappings, try_to_unmap could potentially
1533 			 * call huge_pmd_unshare.  Because of this, take
1534 			 * semaphore in write mode here and set TTU_RMAP_LOCKED
1535 			 * to let lower levels know we have taken the lock.
1536 			 */
1537 			mapping = hugetlb_folio_mapping_lock_write(src);
1538 			if (unlikely(!mapping))
1539 				goto unlock_put_anon;
1540 
1541 			ttu = TTU_RMAP_LOCKED;
1542 		}
1543 
1544 		try_to_migrate(src, ttu);
1545 		was_mapped = 1;
1546 	}
1547 
1548 	if (!folio_mapped(src))
1549 		rc = move_to_new_folio(dst, src, mode);
1550 
1551 	if (was_mapped)
1552 		remove_migration_ptes(src, !rc ? dst : src, ttu);
1553 
1554 	if (ttu & TTU_RMAP_LOCKED)
1555 		i_mmap_unlock_write(mapping);
1556 
1557 unlock_put_anon:
1558 	folio_unlock(dst);
1559 
1560 put_anon:
1561 	if (anon_vma)
1562 		put_anon_vma(anon_vma);
1563 
1564 	if (!rc) {
1565 		move_hugetlb_state(src, dst, reason);
1566 		put_new_folio = NULL;
1567 	}
1568 
1569 out_unlock:
1570 	folio_unlock(src);
1571 out:
1572 	if (!rc)
1573 		folio_putback_hugetlb(src);
1574 	else if (rc != -EAGAIN)
1575 		list_move_tail(&src->lru, ret);
1576 
1577 	/*
1578 	 * If migration was not successful and there's a freeing callback,
1579 	 * return the folio to that special allocator. Otherwise, simply drop
1580 	 * our additional reference.
1581 	 */
1582 	if (put_new_folio)
1583 		put_new_folio(dst, private);
1584 	else
1585 		folio_put(dst);
1586 
1587 	return rc;
1588 }
1589 
1590 static inline int try_split_folio(struct folio *folio, struct list_head *split_folios,
1591 				  enum migrate_mode mode)
1592 {
1593 	int rc;
1594 
1595 	if (mode == MIGRATE_ASYNC) {
1596 		if (!folio_trylock(folio))
1597 			return -EAGAIN;
1598 	} else {
1599 		folio_lock(folio);
1600 	}
1601 	rc = split_folio_to_list(folio, split_folios);
1602 	folio_unlock(folio);
1603 	if (!rc)
1604 		list_move_tail(&folio->lru, split_folios);
1605 
1606 	return rc;
1607 }
1608 
1609 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1610 #define NR_MAX_BATCHED_MIGRATION	HPAGE_PMD_NR
1611 #else
1612 #define NR_MAX_BATCHED_MIGRATION	512
1613 #endif
1614 #define NR_MAX_MIGRATE_PAGES_RETRY	10
1615 #define NR_MAX_MIGRATE_ASYNC_RETRY	3
1616 #define NR_MAX_MIGRATE_SYNC_RETRY					\
1617 	(NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
1618 
1619 struct migrate_pages_stats {
1620 	int nr_succeeded;	/* Normal and large folios migrated successfully, in
1621 				   units of base pages */
1622 	int nr_failed_pages;	/* Normal and large folios failed to be migrated, in
1623 				   units of base pages.  Untried folios aren't counted */
1624 	int nr_thp_succeeded;	/* THP migrated successfully */
1625 	int nr_thp_failed;	/* THP failed to be migrated */
1626 	int nr_thp_split;	/* THP split before migrating */
1627 	int nr_split;	/* Large folio (include THP) split before migrating */
1628 };
1629 
1630 /*
1631  * Returns the number of hugetlb folios that were not migrated, or an error code
1632  * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
1633  * any more because the list has become empty or no retryable hugetlb folios
1634  * exist any more. It is caller's responsibility to call putback_movable_pages()
1635  * only if ret != 0.
1636  */
1637 static int migrate_hugetlbs(struct list_head *from, new_folio_t get_new_folio,
1638 			    free_folio_t put_new_folio, unsigned long private,
1639 			    enum migrate_mode mode, enum migrate_reason reason,
1640 			    struct migrate_pages_stats *stats,
1641 			    struct list_head *ret_folios)
1642 {
1643 	int retry = 1;
1644 	int nr_failed = 0;
1645 	int nr_retry_pages = 0;
1646 	int pass = 0;
1647 	struct folio *folio, *folio2;
1648 	int rc, nr_pages;
1649 
1650 	for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
1651 		retry = 0;
1652 		nr_retry_pages = 0;
1653 
1654 		list_for_each_entry_safe(folio, folio2, from, lru) {
1655 			if (!folio_test_hugetlb(folio))
1656 				continue;
1657 
1658 			nr_pages = folio_nr_pages(folio);
1659 
1660 			cond_resched();
1661 
1662 			/*
1663 			 * Migratability of hugepages depends on architectures and
1664 			 * their size.  This check is necessary because some callers
1665 			 * of hugepage migration like soft offline and memory
1666 			 * hotremove don't walk through page tables or check whether
1667 			 * the hugepage is pmd-based or not before kicking migration.
1668 			 */
1669 			if (!hugepage_migration_supported(folio_hstate(folio))) {
1670 				nr_failed++;
1671 				stats->nr_failed_pages += nr_pages;
1672 				list_move_tail(&folio->lru, ret_folios);
1673 				continue;
1674 			}
1675 
1676 			rc = unmap_and_move_hugetlb_folio(get_new_folio,
1677 							  put_new_folio, private,
1678 							  folio, pass > 2, mode,
1679 							  reason, ret_folios);
1680 			/*
1681 			 * The rules are:
1682 			 *	0: hugetlb folio will be put back
1683 			 *	-EAGAIN: stay on the from list
1684 			 *	-ENOMEM: stay on the from list
1685 			 *	Other errno: put on ret_folios list
1686 			 */
1687 			switch(rc) {
1688 			case -ENOMEM:
1689 				/*
1690 				 * When memory is low, don't bother to try to migrate
1691 				 * other folios, just exit.
1692 				 */
1693 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
1694 				return -ENOMEM;
1695 			case -EAGAIN:
1696 				retry++;
1697 				nr_retry_pages += nr_pages;
1698 				break;
1699 			case 0:
1700 				stats->nr_succeeded += nr_pages;
1701 				break;
1702 			default:
1703 				/*
1704 				 * Permanent failure (-EBUSY, etc.):
1705 				 * unlike -EAGAIN case, the failed folio is
1706 				 * removed from migration folio list and not
1707 				 * retried in the next outer loop.
1708 				 */
1709 				nr_failed++;
1710 				stats->nr_failed_pages += nr_pages;
1711 				break;
1712 			}
1713 		}
1714 	}
1715 	/*
1716 	 * nr_failed is number of hugetlb folios failed to be migrated.  After
1717 	 * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
1718 	 * folios as failed.
1719 	 */
1720 	nr_failed += retry;
1721 	stats->nr_failed_pages += nr_retry_pages;
1722 
1723 	return nr_failed;
1724 }
1725 
1726 static void migrate_folios_move(struct list_head *src_folios,
1727 		struct list_head *dst_folios,
1728 		free_folio_t put_new_folio, unsigned long private,
1729 		enum migrate_mode mode, enum migrate_reason reason,
1730 		struct list_head *ret_folios,
1731 		struct migrate_pages_stats *stats,
1732 		int *retry, int *thp_retry, int *nr_failed,
1733 		int *nr_retry_pages)
1734 {
1735 	struct folio *folio, *folio2, *dst, *dst2;
1736 	bool is_thp;
1737 	int nr_pages;
1738 	int rc;
1739 
1740 	dst = list_first_entry(dst_folios, struct folio, lru);
1741 	dst2 = list_next_entry(dst, lru);
1742 	list_for_each_entry_safe(folio, folio2, src_folios, lru) {
1743 		is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
1744 		nr_pages = folio_nr_pages(folio);
1745 
1746 		cond_resched();
1747 
1748 		rc = migrate_folio_move(put_new_folio, private,
1749 				folio, dst, mode,
1750 				reason, ret_folios);
1751 		/*
1752 		 * The rules are:
1753 		 *	0: folio will be freed
1754 		 *	-EAGAIN: stay on the src_folios list
1755 		 *	Other errno: put on ret_folios list
1756 		 */
1757 		switch (rc) {
1758 		case -EAGAIN:
1759 			*retry += 1;
1760 			*thp_retry += is_thp;
1761 			*nr_retry_pages += nr_pages;
1762 			break;
1763 		case 0:
1764 			stats->nr_succeeded += nr_pages;
1765 			stats->nr_thp_succeeded += is_thp;
1766 			break;
1767 		default:
1768 			*nr_failed += 1;
1769 			stats->nr_thp_failed += is_thp;
1770 			stats->nr_failed_pages += nr_pages;
1771 			break;
1772 		}
1773 		dst = dst2;
1774 		dst2 = list_next_entry(dst, lru);
1775 	}
1776 }
1777 
1778 static void migrate_folios_undo(struct list_head *src_folios,
1779 		struct list_head *dst_folios,
1780 		free_folio_t put_new_folio, unsigned long private,
1781 		struct list_head *ret_folios)
1782 {
1783 	struct folio *folio, *folio2, *dst, *dst2;
1784 
1785 	dst = list_first_entry(dst_folios, struct folio, lru);
1786 	dst2 = list_next_entry(dst, lru);
1787 	list_for_each_entry_safe(folio, folio2, src_folios, lru) {
1788 		int old_folio_state = 0;
1789 		struct anon_vma *anon_vma = NULL;
1790 
1791 		__migrate_folio_extract(dst, &old_folio_state, &anon_vma);
1792 		migrate_folio_undo_src(folio, old_folio_state & FOLIO_WAS_MAPPED,
1793 				anon_vma, true, ret_folios);
1794 		list_del(&dst->lru);
1795 		migrate_folio_undo_dst(dst, true, put_new_folio, private);
1796 		dst = dst2;
1797 		dst2 = list_next_entry(dst, lru);
1798 	}
1799 }
1800 
1801 /*
1802  * migrate_pages_batch() first unmaps folios in the from list as many as
1803  * possible, then move the unmapped folios.
1804  *
1805  * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
1806  * lock or bit when we have locked more than one folio.  Which may cause
1807  * deadlock (e.g., for loop device).  So, if mode != MIGRATE_ASYNC, the
1808  * length of the from list must be <= 1.
1809  */
1810 static int migrate_pages_batch(struct list_head *from,
1811 		new_folio_t get_new_folio, free_folio_t put_new_folio,
1812 		unsigned long private, enum migrate_mode mode, enum migrate_reason reason,
1813 		struct list_head *ret_folios, struct list_head *split_folios,
1814 		struct migrate_pages_stats *stats, int nr_pass)
1815 {
1816 	int retry = 1;
1817 	int thp_retry = 1;
1818 	int nr_failed = 0;
1819 	int nr_retry_pages = 0;
1820 	int pass = 0;
1821 	bool is_thp = false;
1822 	bool is_large = false;
1823 	struct folio *folio, *folio2, *dst = NULL;
1824 	int rc, rc_saved = 0, nr_pages;
1825 	LIST_HEAD(unmap_folios);
1826 	LIST_HEAD(dst_folios);
1827 	bool nosplit = (reason == MR_NUMA_MISPLACED);
1828 
1829 	VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
1830 			!list_empty(from) && !list_is_singular(from));
1831 
1832 	for (pass = 0; pass < nr_pass && retry; pass++) {
1833 		retry = 0;
1834 		thp_retry = 0;
1835 		nr_retry_pages = 0;
1836 
1837 		list_for_each_entry_safe(folio, folio2, from, lru) {
1838 			is_large = folio_test_large(folio);
1839 			is_thp = folio_test_pmd_mappable(folio);
1840 			nr_pages = folio_nr_pages(folio);
1841 
1842 			cond_resched_tasks_rcu_qs();
1843 
1844 			/*
1845 			 * The rare folio on the deferred split list should
1846 			 * be split now. It should not count as a failure:
1847 			 * but increment nr_failed because, without doing so,
1848 			 * migrate_pages() may report success with (split but
1849 			 * unmigrated) pages still on its fromlist; whereas it
1850 			 * always reports success when its fromlist is empty.
1851 			 * stats->nr_thp_failed should be increased too,
1852 			 * otherwise stats inconsistency will happen when
1853 			 * migrate_pages_batch is called via migrate_pages()
1854 			 * with MIGRATE_SYNC and MIGRATE_ASYNC.
1855 			 *
1856 			 * Only check it without removing it from the list.
1857 			 * Since the folio can be on deferred_split_scan()
1858 			 * local list and removing it can cause the local list
1859 			 * corruption. Folio split process below can handle it
1860 			 * with the help of folio_ref_freeze().
1861 			 *
1862 			 * nr_pages > 2 is needed to avoid checking order-1
1863 			 * page cache folios. They exist, in contrast to
1864 			 * non-existent order-1 anonymous folios, and do not
1865 			 * use _deferred_list.
1866 			 */
1867 			if (nr_pages > 2 &&
1868 			   !list_empty(&folio->_deferred_list) &&
1869 			   folio_test_partially_mapped(folio)) {
1870 				if (!try_split_folio(folio, split_folios, mode)) {
1871 					nr_failed++;
1872 					stats->nr_thp_failed += is_thp;
1873 					stats->nr_thp_split += is_thp;
1874 					stats->nr_split++;
1875 					continue;
1876 				}
1877 			}
1878 
1879 			/*
1880 			 * Large folio migration might be unsupported or
1881 			 * the allocation might be failed so we should retry
1882 			 * on the same folio with the large folio split
1883 			 * to normal folios.
1884 			 *
1885 			 * Split folios are put in split_folios, and
1886 			 * we will migrate them after the rest of the
1887 			 * list is processed.
1888 			 */
1889 			if (!thp_migration_supported() && is_thp) {
1890 				nr_failed++;
1891 				stats->nr_thp_failed++;
1892 				if (!try_split_folio(folio, split_folios, mode)) {
1893 					stats->nr_thp_split++;
1894 					stats->nr_split++;
1895 					continue;
1896 				}
1897 				stats->nr_failed_pages += nr_pages;
1898 				list_move_tail(&folio->lru, ret_folios);
1899 				continue;
1900 			}
1901 
1902 			/*
1903 			 * If we are holding the last folio reference, the folio
1904 			 * was freed from under us, so just drop our reference.
1905 			 */
1906 			if (likely(!page_has_movable_ops(&folio->page)) &&
1907 			    folio_ref_count(folio) == 1) {
1908 				folio_clear_active(folio);
1909 				folio_clear_unevictable(folio);
1910 				list_del(&folio->lru);
1911 				migrate_folio_done(folio, reason);
1912 				stats->nr_succeeded += nr_pages;
1913 				stats->nr_thp_succeeded += is_thp;
1914 				continue;
1915 			}
1916 
1917 			rc = migrate_folio_unmap(get_new_folio, put_new_folio,
1918 					private, folio, &dst, mode, ret_folios);
1919 			/*
1920 			 * The rules are:
1921 			 *	0: folio will be put on unmap_folios list,
1922 			 *	   dst folio put on dst_folios list
1923 			 *	-EAGAIN: stay on the from list
1924 			 *	-ENOMEM: stay on the from list
1925 			 *	Other errno: put on ret_folios list
1926 			 */
1927 			switch(rc) {
1928 			case -ENOMEM:
1929 				/*
1930 				 * When memory is low, don't bother to try to migrate
1931 				 * other folios, move unmapped folios, then exit.
1932 				 */
1933 				nr_failed++;
1934 				stats->nr_thp_failed += is_thp;
1935 				/* Large folio NUMA faulting doesn't split to retry. */
1936 				if (is_large && !nosplit) {
1937 					int ret = try_split_folio(folio, split_folios, mode);
1938 
1939 					if (!ret) {
1940 						stats->nr_thp_split += is_thp;
1941 						stats->nr_split++;
1942 						break;
1943 					} else if (reason == MR_LONGTERM_PIN &&
1944 						   ret == -EAGAIN) {
1945 						/*
1946 						 * Try again to split large folio to
1947 						 * mitigate the failure of longterm pinning.
1948 						 */
1949 						retry++;
1950 						thp_retry += is_thp;
1951 						nr_retry_pages += nr_pages;
1952 						/* Undo duplicated failure counting. */
1953 						nr_failed--;
1954 						stats->nr_thp_failed -= is_thp;
1955 						break;
1956 					}
1957 				}
1958 
1959 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
1960 				/* nr_failed isn't updated for not used */
1961 				stats->nr_thp_failed += thp_retry;
1962 				rc_saved = rc;
1963 				if (list_empty(&unmap_folios))
1964 					goto out;
1965 				else
1966 					goto move;
1967 			case -EAGAIN:
1968 				retry++;
1969 				thp_retry += is_thp;
1970 				nr_retry_pages += nr_pages;
1971 				break;
1972 			case 0:
1973 				list_move_tail(&folio->lru, &unmap_folios);
1974 				list_add_tail(&dst->lru, &dst_folios);
1975 				break;
1976 			default:
1977 				/*
1978 				 * Permanent failure (-EBUSY, etc.):
1979 				 * unlike -EAGAIN case, the failed folio is
1980 				 * removed from migration folio list and not
1981 				 * retried in the next outer loop.
1982 				 */
1983 				nr_failed++;
1984 				stats->nr_thp_failed += is_thp;
1985 				stats->nr_failed_pages += nr_pages;
1986 				break;
1987 			}
1988 		}
1989 	}
1990 	nr_failed += retry;
1991 	stats->nr_thp_failed += thp_retry;
1992 	stats->nr_failed_pages += nr_retry_pages;
1993 move:
1994 	/* Flush TLBs for all unmapped folios */
1995 	try_to_unmap_flush();
1996 
1997 	retry = 1;
1998 	for (pass = 0; pass < nr_pass && retry; pass++) {
1999 		retry = 0;
2000 		thp_retry = 0;
2001 		nr_retry_pages = 0;
2002 
2003 		/* Move the unmapped folios */
2004 		migrate_folios_move(&unmap_folios, &dst_folios,
2005 				put_new_folio, private, mode, reason,
2006 				ret_folios, stats, &retry, &thp_retry,
2007 				&nr_failed, &nr_retry_pages);
2008 	}
2009 	nr_failed += retry;
2010 	stats->nr_thp_failed += thp_retry;
2011 	stats->nr_failed_pages += nr_retry_pages;
2012 
2013 	rc = rc_saved ? : nr_failed;
2014 out:
2015 	/* Cleanup remaining folios */
2016 	migrate_folios_undo(&unmap_folios, &dst_folios,
2017 			put_new_folio, private, ret_folios);
2018 
2019 	return rc;
2020 }
2021 
2022 static int migrate_pages_sync(struct list_head *from, new_folio_t get_new_folio,
2023 		free_folio_t put_new_folio, unsigned long private,
2024 		enum migrate_mode mode, enum migrate_reason reason,
2025 		struct list_head *ret_folios, struct list_head *split_folios,
2026 		struct migrate_pages_stats *stats)
2027 {
2028 	int rc, nr_failed = 0;
2029 	LIST_HEAD(folios);
2030 	struct migrate_pages_stats astats;
2031 
2032 	memset(&astats, 0, sizeof(astats));
2033 	/* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
2034 	rc = migrate_pages_batch(from, get_new_folio, put_new_folio, private, MIGRATE_ASYNC,
2035 				 reason, &folios, split_folios, &astats,
2036 				 NR_MAX_MIGRATE_ASYNC_RETRY);
2037 	stats->nr_succeeded += astats.nr_succeeded;
2038 	stats->nr_thp_succeeded += astats.nr_thp_succeeded;
2039 	stats->nr_thp_split += astats.nr_thp_split;
2040 	stats->nr_split += astats.nr_split;
2041 	if (rc < 0) {
2042 		stats->nr_failed_pages += astats.nr_failed_pages;
2043 		stats->nr_thp_failed += astats.nr_thp_failed;
2044 		list_splice_tail(&folios, ret_folios);
2045 		return rc;
2046 	}
2047 	stats->nr_thp_failed += astats.nr_thp_split;
2048 	/*
2049 	 * Do not count rc, as pages will be retried below.
2050 	 * Count nr_split only, since it includes nr_thp_split.
2051 	 */
2052 	nr_failed += astats.nr_split;
2053 	/*
2054 	 * Fall back to migrate all failed folios one by one synchronously. All
2055 	 * failed folios except split THPs will be retried, so their failure
2056 	 * isn't counted
2057 	 */
2058 	list_splice_tail_init(&folios, from);
2059 	while (!list_empty(from)) {
2060 		list_move(from->next, &folios);
2061 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
2062 					 private, mode, reason, ret_folios,
2063 					 split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
2064 		list_splice_tail_init(&folios, ret_folios);
2065 		if (rc < 0)
2066 			return rc;
2067 		nr_failed += rc;
2068 	}
2069 
2070 	return nr_failed;
2071 }
2072 
2073 /*
2074  * migrate_pages - migrate the folios specified in a list, to the free folios
2075  *		   supplied as the target for the page migration
2076  *
2077  * @from:		The list of folios to be migrated.
2078  * @get_new_folio:	The function used to allocate free folios to be used
2079  *			as the target of the folio migration.
2080  * @put_new_folio:	The function used to free target folios if migration
2081  *			fails, or NULL if no special handling is necessary.
2082  * @private:		Private data to be passed on to get_new_folio()
2083  * @mode:		The migration mode that specifies the constraints for
2084  *			folio migration, if any.
2085  * @reason:		The reason for folio migration.
2086  * @ret_succeeded:	Set to the number of folios migrated successfully if
2087  *			the caller passes a non-NULL pointer.
2088  *
2089  * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
2090  * are movable any more because the list has become empty or no retryable folios
2091  * exist any more. It is caller's responsibility to call putback_movable_pages()
2092  * only if ret != 0.
2093  *
2094  * Returns the number of {normal folio, large folio, hugetlb} that were not
2095  * migrated, or an error code. The number of large folio splits will be
2096  * considered as the number of non-migrated large folio, no matter how many
2097  * split folios of the large folio are migrated successfully.
2098  */
2099 int migrate_pages(struct list_head *from, new_folio_t get_new_folio,
2100 		free_folio_t put_new_folio, unsigned long private,
2101 		enum migrate_mode mode, enum migrate_reason reason, unsigned int *ret_succeeded)
2102 {
2103 	int rc, rc_gather;
2104 	int nr_pages;
2105 	struct folio *folio, *folio2;
2106 	LIST_HEAD(folios);
2107 	LIST_HEAD(ret_folios);
2108 	LIST_HEAD(split_folios);
2109 	struct migrate_pages_stats stats;
2110 
2111 	trace_mm_migrate_pages_start(mode, reason);
2112 
2113 	memset(&stats, 0, sizeof(stats));
2114 
2115 	rc_gather = migrate_hugetlbs(from, get_new_folio, put_new_folio, private,
2116 				     mode, reason, &stats, &ret_folios);
2117 	if (rc_gather < 0)
2118 		goto out;
2119 
2120 again:
2121 	nr_pages = 0;
2122 	list_for_each_entry_safe(folio, folio2, from, lru) {
2123 		/* Retried hugetlb folios will be kept in list  */
2124 		if (folio_test_hugetlb(folio)) {
2125 			list_move_tail(&folio->lru, &ret_folios);
2126 			continue;
2127 		}
2128 
2129 		nr_pages += folio_nr_pages(folio);
2130 		if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
2131 			break;
2132 	}
2133 	if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
2134 		list_cut_before(&folios, from, &folio2->lru);
2135 	else
2136 		list_splice_init(from, &folios);
2137 	if (mode == MIGRATE_ASYNC)
2138 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
2139 				private, mode, reason, &ret_folios,
2140 				&split_folios, &stats,
2141 				NR_MAX_MIGRATE_PAGES_RETRY);
2142 	else
2143 		rc = migrate_pages_sync(&folios, get_new_folio, put_new_folio,
2144 				private, mode, reason, &ret_folios,
2145 				&split_folios, &stats);
2146 	list_splice_tail_init(&folios, &ret_folios);
2147 	if (rc < 0) {
2148 		rc_gather = rc;
2149 		list_splice_tail(&split_folios, &ret_folios);
2150 		goto out;
2151 	}
2152 	if (!list_empty(&split_folios)) {
2153 		/*
2154 		 * Failure isn't counted since all split folios of a large folio
2155 		 * is counted as 1 failure already.  And, we only try to migrate
2156 		 * with minimal effort, force MIGRATE_ASYNC mode and retry once.
2157 		 */
2158 		migrate_pages_batch(&split_folios, get_new_folio,
2159 				put_new_folio, private, MIGRATE_ASYNC, reason,
2160 				&ret_folios, NULL, &stats, 1);
2161 		list_splice_tail_init(&split_folios, &ret_folios);
2162 	}
2163 	rc_gather += rc;
2164 	if (!list_empty(from))
2165 		goto again;
2166 out:
2167 	/*
2168 	 * Put the permanent failure folio back to migration list, they
2169 	 * will be put back to the right list by the caller.
2170 	 */
2171 	list_splice(&ret_folios, from);
2172 
2173 	/*
2174 	 * Return 0 in case all split folios of fail-to-migrate large folios
2175 	 * are migrated successfully.
2176 	 */
2177 	if (list_empty(from))
2178 		rc_gather = 0;
2179 
2180 	count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
2181 	count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
2182 	count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
2183 	count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
2184 	count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
2185 	trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
2186 			       stats.nr_thp_succeeded, stats.nr_thp_failed,
2187 			       stats.nr_thp_split, stats.nr_split, mode,
2188 			       reason);
2189 
2190 	if (ret_succeeded)
2191 		*ret_succeeded = stats.nr_succeeded;
2192 
2193 	return rc_gather;
2194 }
2195 
2196 struct folio *alloc_migration_target(struct folio *src, unsigned long private)
2197 {
2198 	struct migration_target_control *mtc;
2199 	gfp_t gfp_mask;
2200 	unsigned int order = 0;
2201 	int nid;
2202 	enum zone_type zidx;
2203 
2204 	mtc = (struct migration_target_control *)private;
2205 	gfp_mask = mtc->gfp_mask;
2206 	nid = mtc->nid;
2207 	if (nid == NUMA_NO_NODE)
2208 		nid = folio_nid(src);
2209 
2210 	if (folio_test_hugetlb(src)) {
2211 		struct hstate *h = folio_hstate(src);
2212 
2213 		gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
2214 		return alloc_hugetlb_folio_nodemask(h, nid,
2215 						mtc->nmask, gfp_mask,
2216 						htlb_allow_alloc_fallback(mtc->reason));
2217 	}
2218 
2219 	if (folio_test_large(src)) {
2220 		/*
2221 		 * clear __GFP_RECLAIM to make the migration callback
2222 		 * consistent with regular THP allocations.
2223 		 */
2224 		gfp_mask &= ~__GFP_RECLAIM;
2225 		gfp_mask |= GFP_TRANSHUGE;
2226 		order = folio_order(src);
2227 	}
2228 	zidx = folio_zonenum(src);
2229 	if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
2230 		gfp_mask |= __GFP_HIGHMEM;
2231 
2232 	return __folio_alloc(gfp_mask, order, nid, mtc->nmask);
2233 }
2234 
2235 #ifdef CONFIG_NUMA_MIGRATION
2236 static int store_status(int __user *status, int start, int value, int nr)
2237 {
2238 	while (nr-- > 0) {
2239 		if (put_user(value, status + start))
2240 			return -EFAULT;
2241 		start++;
2242 	}
2243 
2244 	return 0;
2245 }
2246 
2247 static int do_move_pages_to_node(struct list_head *pagelist, int node)
2248 {
2249 	int err;
2250 	struct migration_target_control mtc = {
2251 		.nid = node,
2252 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
2253 		.reason = MR_SYSCALL,
2254 	};
2255 
2256 	err = migrate_pages(pagelist, alloc_migration_target, NULL,
2257 		(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
2258 	if (err)
2259 		putback_movable_pages(pagelist);
2260 	return err;
2261 }
2262 
2263 static int __add_folio_for_migration(struct folio *folio, int node,
2264 		struct list_head *pagelist, bool migrate_all)
2265 {
2266 	if (is_zero_folio(folio) || is_huge_zero_folio(folio))
2267 		return -EFAULT;
2268 
2269 	if (folio_is_zone_device(folio))
2270 		return -ENOENT;
2271 
2272 	if (folio_nid(folio) == node)
2273 		return 0;
2274 
2275 	if (folio_maybe_mapped_shared(folio) && !migrate_all)
2276 		return -EACCES;
2277 
2278 	if (folio_test_hugetlb(folio)) {
2279 		if (folio_isolate_hugetlb(folio, pagelist))
2280 			return 1;
2281 	} else if (folio_isolate_lru(folio)) {
2282 		list_add_tail(&folio->lru, pagelist);
2283 		node_stat_mod_folio(folio,
2284 			NR_ISOLATED_ANON + folio_is_file_lru(folio),
2285 			folio_nr_pages(folio));
2286 		return 1;
2287 	}
2288 	return -EBUSY;
2289 }
2290 
2291 /*
2292  * Resolves the given address to a struct folio, isolates it from the LRU and
2293  * puts it to the given pagelist.
2294  * Returns:
2295  *     errno - if the folio cannot be found/isolated
2296  *     0 - when it doesn't have to be migrated because it is already on the
2297  *         target node
2298  *     1 - when it has been queued
2299  */
2300 static int add_folio_for_migration(struct mm_struct *mm, const void __user *p,
2301 		int node, struct list_head *pagelist, bool migrate_all)
2302 {
2303 	struct vm_area_struct *vma;
2304 	struct folio_walk fw;
2305 	struct folio *folio;
2306 	unsigned long addr;
2307 	int err = -EFAULT;
2308 
2309 	mmap_read_lock(mm);
2310 	addr = (unsigned long)untagged_addr_remote(mm, p);
2311 
2312 	vma = vma_lookup(mm, addr);
2313 	if (vma && vma_migratable(vma)) {
2314 		folio = folio_walk_start(&fw, vma, addr, FW_ZEROPAGE);
2315 		if (folio) {
2316 			err = __add_folio_for_migration(folio, node, pagelist,
2317 							migrate_all);
2318 			folio_walk_end(&fw, vma);
2319 		} else {
2320 			err = -ENOENT;
2321 		}
2322 	}
2323 	mmap_read_unlock(mm);
2324 	return err;
2325 }
2326 
2327 static int move_pages_and_store_status(int node,
2328 		struct list_head *pagelist, int __user *status,
2329 		int start, int i, unsigned long nr_pages)
2330 {
2331 	int err;
2332 
2333 	if (list_empty(pagelist))
2334 		return 0;
2335 
2336 	err = do_move_pages_to_node(pagelist, node);
2337 	if (err) {
2338 		/*
2339 		 * Positive err means the number of failed
2340 		 * pages to migrate.  Since we are going to
2341 		 * abort and return the number of non-migrated
2342 		 * pages, so need to include the rest of the
2343 		 * nr_pages that have not been attempted as
2344 		 * well.
2345 		 */
2346 		if (err > 0)
2347 			err += nr_pages - i;
2348 		return err;
2349 	}
2350 	return store_status(status, start, node, i - start);
2351 }
2352 
2353 /*
2354  * Migrate an array of page address onto an array of nodes and fill
2355  * the corresponding array of status.
2356  */
2357 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
2358 			 unsigned long nr_pages,
2359 			 const void __user * __user *pages,
2360 			 const int __user *nodes,
2361 			 int __user *status, int flags)
2362 {
2363 	compat_uptr_t __user *compat_pages = (void __user *)pages;
2364 	int current_node = NUMA_NO_NODE;
2365 	LIST_HEAD(pagelist);
2366 	int start, i;
2367 	int err = 0, err1;
2368 
2369 	lru_cache_disable();
2370 
2371 	for (i = start = 0; i < nr_pages; i++) {
2372 		const void __user *p;
2373 		int node;
2374 
2375 		err = -EFAULT;
2376 		if (in_compat_syscall()) {
2377 			compat_uptr_t cp;
2378 
2379 			if (get_user(cp, compat_pages + i))
2380 				goto out_flush;
2381 
2382 			p = compat_ptr(cp);
2383 		} else {
2384 			if (get_user(p, pages + i))
2385 				goto out_flush;
2386 		}
2387 		if (get_user(node, nodes + i))
2388 			goto out_flush;
2389 
2390 		err = -ENODEV;
2391 		if (node < 0 || node >= MAX_NUMNODES)
2392 			goto out_flush;
2393 		if (!node_state(node, N_MEMORY))
2394 			goto out_flush;
2395 
2396 		err = -EACCES;
2397 		if (!node_isset(node, task_nodes))
2398 			goto out_flush;
2399 
2400 		if (current_node == NUMA_NO_NODE) {
2401 			current_node = node;
2402 			start = i;
2403 		} else if (node != current_node) {
2404 			err = move_pages_and_store_status(current_node,
2405 					&pagelist, status, start, i, nr_pages);
2406 			if (err)
2407 				goto out;
2408 			start = i;
2409 			current_node = node;
2410 		}
2411 
2412 		/*
2413 		 * Errors in the page lookup or isolation are not fatal and we simply
2414 		 * report them via status
2415 		 */
2416 		err = add_folio_for_migration(mm, p, current_node, &pagelist,
2417 					      flags & MPOL_MF_MOVE_ALL);
2418 
2419 		if (err > 0) {
2420 			/* The page is successfully queued for migration */
2421 			continue;
2422 		}
2423 
2424 		/*
2425 		 * If the page is already on the target node (!err), store the
2426 		 * node, otherwise, store the err.
2427 		 */
2428 		err = store_status(status, i, err ? : current_node, 1);
2429 		if (err)
2430 			goto out_flush;
2431 
2432 		err = move_pages_and_store_status(current_node, &pagelist,
2433 				status, start, i, nr_pages);
2434 		if (err) {
2435 			/* We have accounted for page i */
2436 			if (err > 0)
2437 				err--;
2438 			goto out;
2439 		}
2440 		current_node = NUMA_NO_NODE;
2441 	}
2442 out_flush:
2443 	/* Make sure we do not overwrite the existing error */
2444 	err1 = move_pages_and_store_status(current_node, &pagelist,
2445 				status, start, i, nr_pages);
2446 	if (err >= 0)
2447 		err = err1;
2448 out:
2449 	lru_cache_enable();
2450 	return err;
2451 }
2452 
2453 /*
2454  * Determine the nodes of an array of pages and store it in an array of status.
2455  */
2456 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
2457 				const void __user **pages, int *status)
2458 {
2459 	unsigned long i;
2460 
2461 	mmap_read_lock(mm);
2462 
2463 	for (i = 0; i < nr_pages; i++) {
2464 		unsigned long addr = (unsigned long)(*pages);
2465 		struct vm_area_struct *vma;
2466 		struct folio_walk fw;
2467 		struct folio *folio;
2468 		int err = -EFAULT;
2469 
2470 		vma = vma_lookup(mm, addr);
2471 		if (!vma)
2472 			goto set_status;
2473 
2474 		folio = folio_walk_start(&fw, vma, addr, FW_ZEROPAGE);
2475 		if (folio) {
2476 			if (is_zero_folio(folio) || is_huge_zero_folio(folio))
2477 				err = -EFAULT;
2478 			else if (folio_is_zone_device(folio))
2479 				err = -ENOENT;
2480 			else
2481 				err = folio_nid(folio);
2482 			folio_walk_end(&fw, vma);
2483 		} else {
2484 			err = -ENOENT;
2485 		}
2486 set_status:
2487 		*status = err;
2488 
2489 		pages++;
2490 		status++;
2491 	}
2492 
2493 	mmap_read_unlock(mm);
2494 }
2495 
2496 static int get_compat_pages_array(const void __user *chunk_pages[],
2497 				  const void __user * __user *pages,
2498 				  unsigned long chunk_offset,
2499 				  unsigned long chunk_nr)
2500 {
2501 	compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
2502 	compat_uptr_t p;
2503 	int i;
2504 
2505 	for (i = 0; i < chunk_nr; i++) {
2506 		if (get_user(p, pages32 + chunk_offset + i))
2507 			return -EFAULT;
2508 		chunk_pages[i] = compat_ptr(p);
2509 	}
2510 
2511 	return 0;
2512 }
2513 
2514 /*
2515  * Determine the nodes of a user array of pages and store it in
2516  * a user array of status.
2517  */
2518 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
2519 			 const void __user * __user *pages,
2520 			 int __user *status)
2521 {
2522 #define DO_PAGES_STAT_CHUNK_NR 16UL
2523 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
2524 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
2525 	unsigned long chunk_offset = 0;
2526 
2527 	while (nr_pages) {
2528 		unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
2529 
2530 		if (in_compat_syscall()) {
2531 			if (get_compat_pages_array(chunk_pages, pages,
2532 						   chunk_offset, chunk_nr))
2533 				break;
2534 		} else {
2535 			if (copy_from_user(chunk_pages, pages + chunk_offset,
2536 				      chunk_nr * sizeof(*chunk_pages)))
2537 				break;
2538 		}
2539 
2540 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
2541 
2542 		if (copy_to_user(status + chunk_offset, chunk_status,
2543 				 chunk_nr * sizeof(*status)))
2544 			break;
2545 
2546 		chunk_offset += chunk_nr;
2547 		nr_pages -= chunk_nr;
2548 	}
2549 	return nr_pages ? -EFAULT : 0;
2550 }
2551 
2552 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
2553 {
2554 	struct task_struct *task;
2555 	struct mm_struct *mm;
2556 
2557 	/*
2558 	 * There is no need to check if current process has the right to modify
2559 	 * the specified process when they are same.
2560 	 */
2561 	if (!pid) {
2562 		mmget(current->mm);
2563 		*mem_nodes = cpuset_mems_allowed(current);
2564 		return current->mm;
2565 	}
2566 
2567 	task = find_get_task_by_vpid(pid);
2568 	if (!task)
2569 		return ERR_PTR(-ESRCH);
2570 
2571 	if (down_read_killable(&task->signal->exec_update_lock)) {
2572 		mm = ERR_PTR(-EINTR);
2573 		goto out;
2574 	}
2575 	/*
2576 	 * Check if this process has the right to modify the specified
2577 	 * process. Use the regular "ptrace_may_access()" checks.
2578 	 */
2579 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2580 		mm = ERR_PTR(-EPERM);
2581 		goto unlock;
2582 	}
2583 
2584 	mm = ERR_PTR(security_task_movememory(task));
2585 	if (IS_ERR(mm))
2586 		goto unlock;
2587 	*mem_nodes = cpuset_mems_allowed(task);
2588 	mm = get_task_mm(task);
2589 unlock:
2590 	up_read(&task->signal->exec_update_lock);
2591 out:
2592 	put_task_struct(task);
2593 	if (!mm)
2594 		mm = ERR_PTR(-EINVAL);
2595 	return mm;
2596 }
2597 
2598 /*
2599  * Move a list of pages in the address space of the currently executing
2600  * process.
2601  */
2602 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2603 			     const void __user * __user *pages,
2604 			     const int __user *nodes,
2605 			     int __user *status, int flags)
2606 {
2607 	struct mm_struct *mm;
2608 	int err;
2609 	nodemask_t task_nodes;
2610 
2611 	/* Check flags */
2612 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2613 		return -EINVAL;
2614 
2615 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2616 		return -EPERM;
2617 
2618 	mm = find_mm_struct(pid, &task_nodes);
2619 	if (IS_ERR(mm))
2620 		return PTR_ERR(mm);
2621 
2622 	if (nodes)
2623 		err = do_pages_move(mm, task_nodes, nr_pages, pages,
2624 				    nodes, status, flags);
2625 	else
2626 		err = do_pages_stat(mm, nr_pages, pages, status);
2627 
2628 	mmput(mm);
2629 	return err;
2630 }
2631 
2632 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2633 		const void __user * __user *, pages,
2634 		const int __user *, nodes,
2635 		int __user *, status, int, flags)
2636 {
2637 	return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2638 }
2639 #endif /* CONFIG_NUMA_MIGRATION */
2640 
2641 #ifdef CONFIG_NUMA_BALANCING
2642 /*
2643  * Returns true if this is a safe migration target node for misplaced NUMA
2644  * pages. Currently it only checks the watermarks which is crude.
2645  */
2646 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2647 				   unsigned long nr_migrate_pages)
2648 {
2649 	int z;
2650 
2651 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2652 		struct zone *zone = pgdat->node_zones + z;
2653 
2654 		if (!managed_zone(zone))
2655 			continue;
2656 
2657 		/* Avoid waking kswapd by allocating pages_to_migrate pages. */
2658 		if (!zone_watermark_ok(zone, 0,
2659 				       high_wmark_pages(zone) +
2660 				       nr_migrate_pages,
2661 				       ZONE_MOVABLE, ALLOC_CMA))
2662 			continue;
2663 		return true;
2664 	}
2665 	return false;
2666 }
2667 
2668 static struct folio *alloc_misplaced_dst_folio(struct folio *src,
2669 					   unsigned long data)
2670 {
2671 	int nid = (int) data;
2672 	int order = folio_order(src);
2673 	gfp_t gfp = __GFP_THISNODE;
2674 
2675 	if (order > 0)
2676 		gfp |= GFP_TRANSHUGE_LIGHT;
2677 	else {
2678 		gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2679 			__GFP_NOWARN;
2680 		gfp &= ~__GFP_RECLAIM;
2681 	}
2682 	return __folio_alloc_node(gfp, order, nid);
2683 }
2684 
2685 /*
2686  * Prepare for calling migrate_misplaced_folio() by isolating the folio if
2687  * permitted. Must be called with the PTL still held.
2688  */
2689 int migrate_misplaced_folio_prepare(struct folio *folio,
2690 		struct vm_area_struct *vma, int node)
2691 {
2692 	int nr_pages = folio_nr_pages(folio);
2693 	pg_data_t *pgdat = NODE_DATA(node);
2694 
2695 	if (folio_is_file_lru(folio)) {
2696 		/*
2697 		 * Do not migrate file folios that are mapped in multiple
2698 		 * processes with execute permissions as they are probably
2699 		 * shared libraries.
2700 		 *
2701 		 * See folio_maybe_mapped_shared() on possible imprecision
2702 		 * when we cannot easily detect if a folio is shared.
2703 		 */
2704 		if ((vma->vm_flags & VM_EXEC) && folio_maybe_mapped_shared(folio))
2705 			return -EACCES;
2706 
2707 		/*
2708 		 * Do not migrate dirty folios as not all filesystems can move
2709 		 * dirty folios in MIGRATE_ASYNC mode which is a waste of
2710 		 * cycles.
2711 		 */
2712 		if (folio_test_dirty(folio))
2713 			return -EAGAIN;
2714 	}
2715 
2716 	/* Avoid migrating to a node that is nearly full */
2717 	if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2718 		int z;
2719 
2720 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2721 			return -EAGAIN;
2722 		for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2723 			if (managed_zone(pgdat->node_zones + z))
2724 				break;
2725 		}
2726 
2727 		/*
2728 		 * If there are no managed zones, it should not proceed
2729 		 * further.
2730 		 */
2731 		if (z < 0)
2732 			return -EAGAIN;
2733 
2734 		wakeup_kswapd(pgdat->node_zones + z, 0,
2735 			      folio_order(folio), ZONE_MOVABLE);
2736 		return -EAGAIN;
2737 	}
2738 
2739 	if (!folio_isolate_lru(folio))
2740 		return -EAGAIN;
2741 
2742 	node_stat_mod_folio(folio, NR_ISOLATED_ANON + folio_is_file_lru(folio),
2743 			    nr_pages);
2744 	return 0;
2745 }
2746 
2747 /*
2748  * Attempt to migrate a misplaced folio to the specified destination
2749  * node. Caller is expected to have isolated the folio by calling
2750  * migrate_misplaced_folio_prepare(), which will result in an
2751  * elevated reference count on the folio. This function will un-isolate the
2752  * folio, dereferencing the folio before returning.
2753  */
2754 int migrate_misplaced_folio(struct folio *folio, int node)
2755 {
2756 	pg_data_t *pgdat = NODE_DATA(node);
2757 	int nr_remaining;
2758 	unsigned int nr_succeeded;
2759 	LIST_HEAD(migratepages);
2760 	struct mem_cgroup *memcg = get_mem_cgroup_from_folio(folio);
2761 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2762 
2763 	list_add(&folio->lru, &migratepages);
2764 	nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_folio,
2765 				     NULL, node, MIGRATE_ASYNC,
2766 				     MR_NUMA_MISPLACED, &nr_succeeded);
2767 	if (nr_remaining && !list_empty(&migratepages))
2768 		putback_movable_pages(&migratepages);
2769 	if (nr_succeeded) {
2770 		count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2771 		count_memcg_events(memcg, NUMA_PAGE_MIGRATE, nr_succeeded);
2772 		if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
2773 		    && !node_is_toptier(folio_nid(folio))
2774 		    && node_is_toptier(node))
2775 			mod_lruvec_state(lruvec, PGPROMOTE_SUCCESS, nr_succeeded);
2776 	}
2777 	mem_cgroup_put(memcg);
2778 	BUG_ON(!list_empty(&migratepages));
2779 	return nr_remaining ? -EAGAIN : 0;
2780 }
2781 #endif /* CONFIG_NUMA_BALANCING */
2782