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