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