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