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