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