xref: /linux/mm/migrate.c (revision d866d5bafc5e1417032255002e95f8ec3121754b)
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(new_folio_t get_new_folio,
1234 		free_folio_t put_new_folio, unsigned long private,
1235 		struct folio *src, struct folio **dstp, enum migrate_mode mode,
1236 		struct list_head *ret)
1237 {
1238 	struct folio *dst;
1239 	int rc = -EAGAIN;
1240 	int old_folio_state = 0;
1241 	struct anon_vma *anon_vma = NULL;
1242 	bool locked = false;
1243 	bool dst_locked = false;
1244 
1245 	dst = get_new_folio(src, private);
1246 	if (!dst)
1247 		return -ENOMEM;
1248 	*dstp = dst;
1249 
1250 	dst->migrate_info = 0;
1251 
1252 	if (!folio_trylock(src)) {
1253 		if (mode == MIGRATE_ASYNC)
1254 			goto out;
1255 
1256 		/*
1257 		 * It's not safe for direct compaction to call lock_page.
1258 		 * For example, during page readahead pages are added locked
1259 		 * to the LRU. Later, when the IO completes the pages are
1260 		 * marked uptodate and unlocked. However, the queueing
1261 		 * could be merging multiple pages for one bio (e.g.
1262 		 * mpage_readahead). If an allocation happens for the
1263 		 * second or third page, the process can end up locking
1264 		 * the same page twice and deadlocking. Rather than
1265 		 * trying to be clever about what pages can be locked,
1266 		 * avoid the use of lock_page for direct compaction
1267 		 * altogether.
1268 		 */
1269 		if (current->flags & PF_MEMALLOC)
1270 			goto out;
1271 
1272 		/*
1273 		 * In "light" mode, we can wait for transient locks (eg
1274 		 * inserting a page into the page table), but it's not
1275 		 * worth waiting for I/O.
1276 		 */
1277 		if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
1278 			goto out;
1279 
1280 		folio_lock(src);
1281 	}
1282 	locked = true;
1283 	if (folio_test_mlocked(src))
1284 		old_folio_state |= FOLIO_WAS_MLOCKED;
1285 
1286 	if (folio_test_writeback(src)) {
1287 		/*
1288 		 * Only in the case of a full synchronous migration is it
1289 		 * necessary to wait for writeback. In the async case,
1290 		 * the retry loop is too short and in the sync-light case,
1291 		 * the overhead of stalling is too much
1292 		 */
1293 		switch (mode) {
1294 		case MIGRATE_SYNC:
1295 			break;
1296 		default:
1297 			rc = -EBUSY;
1298 			goto out;
1299 		}
1300 		folio_wait_writeback(src);
1301 	}
1302 
1303 	/*
1304 	 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1305 	 * we cannot notice that the anon rmap is freed while we migrate a page.
1306 	 * This get_anon_vma() delays freeing the anon rmap until the end
1307 	 * of migration. File cache pages are no problem because of page_lock()
1308 	 * File Caches may use write_page() or lock_page() in migration, then,
1309 	 * just care Anon page here.
1310 	 *
1311 	 * Only folio_get_anon_vma() understands the subtleties of
1312 	 * getting a hold on an anon rmap from outside one of its mms.
1313 	 * But if we cannot get the anon rmap, then we won't need it anyway,
1314 	 * because that implies that the anon page is no longer mapped
1315 	 * (and cannot be remapped so long as we hold the page lock).
1316 	 */
1317 	if (folio_test_anon(src) && !folio_test_ksm(src))
1318 		anon_vma = folio_get_anon_vma(src);
1319 
1320 	/*
1321 	 * Block others from accessing the new page when we get around to
1322 	 * establishing additional references. We are usually the only one
1323 	 * holding a reference to dst at this point. We used to have a BUG
1324 	 * here if folio_trylock(dst) fails, but would like to allow for
1325 	 * cases where there might be a race with the previous use of dst.
1326 	 * This is much like races on refcount of oldpage: just don't BUG().
1327 	 */
1328 	if (unlikely(!folio_trylock(dst)))
1329 		goto out;
1330 	dst_locked = true;
1331 
1332 	if (unlikely(page_has_movable_ops(&src->page))) {
1333 		__migrate_folio_record(dst, old_folio_state, anon_vma);
1334 		return 0;
1335 	}
1336 
1337 	/*
1338 	 * Corner case handling:
1339 	 * 1. When a new swap-cache page is read into, it is added to the LRU
1340 	 * and treated as swapcache but it has no rmap yet.
1341 	 * Calling try_to_unmap() against a src->mapping==NULL page will
1342 	 * trigger a BUG.  So handle it here.
1343 	 * 2. An orphaned page (see truncate_cleanup_page) might have
1344 	 * fs-private metadata. The page can be picked up due to memory
1345 	 * offlining.  Everywhere else except page reclaim, the page is
1346 	 * invisible to the vm, so the page can not be migrated.  So try to
1347 	 * free the metadata, so the page can be freed.
1348 	 */
1349 	if (!src->mapping) {
1350 		if (folio_has_attached_private(src)) {
1351 			try_to_free_buffers(src);
1352 			goto out;
1353 		}
1354 	} else if (folio_mapped(src)) {
1355 		/* Establish migration ptes */
1356 		VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1357 			       !folio_test_ksm(src) && !anon_vma, src);
1358 		try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
1359 		old_folio_state |= FOLIO_WAS_MAPPED;
1360 	}
1361 
1362 	if (!folio_mapped(src)) {
1363 		__migrate_folio_record(dst, old_folio_state, anon_vma);
1364 		return 0;
1365 	}
1366 
1367 out:
1368 	/*
1369 	 * A folio that has not been unmapped will be restored to
1370 	 * right list unless we want to retry.
1371 	 */
1372 	if (rc == -EAGAIN)
1373 		ret = NULL;
1374 
1375 	migrate_folio_undo_src(src, old_folio_state & FOLIO_WAS_MAPPED,
1376 			       anon_vma, locked, ret);
1377 	migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
1378 
1379 	return rc;
1380 }
1381 
1382 /* Migrate the folio to the newly allocated folio in dst. */
1383 static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
1384 			      struct folio *src, struct folio *dst,
1385 			      enum migrate_mode mode, enum migrate_reason reason,
1386 			      struct list_head *ret)
1387 {
1388 	int rc;
1389 	int old_folio_state = 0;
1390 	struct anon_vma *anon_vma = NULL;
1391 	bool src_deferred_split = false;
1392 	bool src_partially_mapped = false;
1393 	struct list_head *prev;
1394 
1395 	__migrate_folio_extract(dst, &old_folio_state, &anon_vma);
1396 	prev = dst->lru.prev;
1397 	list_del(&dst->lru);
1398 
1399 	if (unlikely(page_has_movable_ops(&src->page))) {
1400 		rc = migrate_movable_ops_page(&dst->page, &src->page, mode);
1401 		if (rc)
1402 			goto out;
1403 		goto out_unlock_both;
1404 	}
1405 
1406 	if (folio_order(src) > 1 &&
1407 	    !data_race(list_empty(&src->_deferred_list))) {
1408 		src_deferred_split = true;
1409 		src_partially_mapped = folio_test_partially_mapped(src);
1410 	}
1411 
1412 	rc = move_to_new_folio(dst, src, mode);
1413 	if (rc)
1414 		goto out;
1415 
1416 	/*
1417 	 * Requeue the destination folio on the deferred split queue if
1418 	 * the source was on the queue.  The source is unqueued in
1419 	 * __folio_migrate_mapping(), so we recorded the state from
1420 	 * before move_to_new_folio().
1421 	 */
1422 	if (src_deferred_split)
1423 		deferred_split_folio(dst, src_partially_mapped);
1424 
1425 	/*
1426 	 * When successful, push dst to LRU immediately: so that if it
1427 	 * turns out to be an mlocked page, remove_migration_ptes() will
1428 	 * automatically build up the correct dst->mlock_count for it.
1429 	 *
1430 	 * We would like to do something similar for the old page, when
1431 	 * unsuccessful, and other cases when a page has been temporarily
1432 	 * isolated from the unevictable LRU: but this case is the easiest.
1433 	 */
1434 	folio_add_lru(dst);
1435 	if (old_folio_state & FOLIO_WAS_MLOCKED)
1436 		lru_add_drain();
1437 
1438 	if (old_folio_state & FOLIO_WAS_MAPPED)
1439 		remove_migration_ptes(src, dst, 0);
1440 
1441 out_unlock_both:
1442 	folio_unlock(dst);
1443 	folio_set_owner_migrate_reason(dst, reason);
1444 	/*
1445 	 * If migration is successful, decrease refcount of dst,
1446 	 * which will not free the page because new page owner increased
1447 	 * refcounter.
1448 	 */
1449 	folio_put(dst);
1450 
1451 	/*
1452 	 * A folio that has been migrated has all references removed
1453 	 * and will be freed.
1454 	 */
1455 	list_del(&src->lru);
1456 	/* Drop an anon rmap reference if we took one */
1457 	if (anon_vma)
1458 		put_anon_vma(anon_vma);
1459 	folio_unlock(src);
1460 	migrate_folio_done(src, reason);
1461 
1462 	return rc;
1463 out:
1464 	/*
1465 	 * A folio that has not been migrated will be restored to
1466 	 * right list unless we want to retry.
1467 	 */
1468 	if (rc == -EAGAIN) {
1469 		list_add(&dst->lru, prev);
1470 		__migrate_folio_record(dst, old_folio_state, anon_vma);
1471 		return rc;
1472 	}
1473 
1474 	migrate_folio_undo_src(src, old_folio_state & FOLIO_WAS_MAPPED,
1475 			       anon_vma, true, ret);
1476 	migrate_folio_undo_dst(dst, true, put_new_folio, private);
1477 
1478 	return rc;
1479 }
1480 
1481 /*
1482  * Counterpart of migrate_folio_unmap() and migrate_folio_move() for hugetlb
1483  * folio migration.
1484  *
1485  * This function doesn't wait the completion of hugepage I/O
1486  * because there is no race between I/O and migration for hugepage.
1487  * Note that currently hugepage I/O occurs only in direct I/O
1488  * where no lock is held and PG_writeback is irrelevant,
1489  * and writeback status of all subpages are counted in the reference
1490  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1491  * under direct I/O, the reference of the head page is 512 and a bit more.)
1492  * This means that when we try to migrate hugepage whose subpages are
1493  * doing direct I/O, some references remain after try_to_unmap() and
1494  * hugepage migration fails without data corruption.
1495  *
1496  * There is also no race when direct I/O is issued on the page under migration,
1497  * because then pte is replaced with migration swap entry and direct I/O code
1498  * will wait in the page fault for migration to complete.
1499  */
1500 static int unmap_and_move_hugetlb_folio(new_folio_t get_new_folio,
1501 		free_folio_t put_new_folio, unsigned long private,
1502 		struct folio *src, int force, enum migrate_mode mode,
1503 		enum migrate_reason reason, struct list_head *ret)
1504 {
1505 	struct folio *dst;
1506 	int rc = -EAGAIN;
1507 	int was_mapped = 0;
1508 	struct anon_vma *anon_vma = NULL;
1509 	struct address_space *mapping = NULL;
1510 	enum ttu_flags ttu = 0;
1511 
1512 	if (folio_ref_count(src) == 1) {
1513 		/* folio was freed from under us. So we are done. */
1514 		folio_putback_hugetlb(src);
1515 		return 0;
1516 	}
1517 
1518 	dst = get_new_folio(src, private);
1519 	if (!dst)
1520 		return -ENOMEM;
1521 
1522 	if (!folio_trylock(src)) {
1523 		if (!force)
1524 			goto out;
1525 		switch (mode) {
1526 		case MIGRATE_SYNC:
1527 			break;
1528 		default:
1529 			goto out;
1530 		}
1531 		folio_lock(src);
1532 	}
1533 
1534 	/*
1535 	 * Check for folios which are in the process of being freed.  Without
1536 	 * folio_mapping() set, hugetlbfs specific move folio routine will not
1537 	 * be called and we could leak usage counts for subpools.
1538 	 */
1539 	if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1540 		rc = -EBUSY;
1541 		goto out_unlock;
1542 	}
1543 
1544 	if (folio_test_anon(src))
1545 		anon_vma = folio_get_anon_vma(src);
1546 
1547 	if (unlikely(!folio_trylock(dst)))
1548 		goto put_anon;
1549 
1550 	if (folio_mapped(src)) {
1551 		if (!folio_test_anon(src)) {
1552 			/*
1553 			 * In shared mappings, try_to_unmap could potentially
1554 			 * call huge_pmd_unshare.  Because of this, take
1555 			 * semaphore in write mode here and set TTU_RMAP_LOCKED
1556 			 * to let lower levels know we have taken the lock.
1557 			 */
1558 			mapping = hugetlb_folio_mapping_lock_write(src);
1559 			if (unlikely(!mapping))
1560 				goto unlock_put_anon;
1561 
1562 			ttu = TTU_RMAP_LOCKED;
1563 		}
1564 
1565 		try_to_migrate(src, ttu);
1566 		was_mapped = 1;
1567 	}
1568 
1569 	if (!folio_mapped(src))
1570 		rc = move_to_new_folio(dst, src, mode);
1571 
1572 	if (was_mapped)
1573 		remove_migration_ptes(src, !rc ? dst : src, ttu);
1574 
1575 	if (ttu & TTU_RMAP_LOCKED)
1576 		i_mmap_unlock_write(mapping);
1577 
1578 unlock_put_anon:
1579 	folio_unlock(dst);
1580 
1581 put_anon:
1582 	if (anon_vma)
1583 		put_anon_vma(anon_vma);
1584 
1585 	if (!rc) {
1586 		move_hugetlb_state(src, dst, reason);
1587 		put_new_folio = NULL;
1588 	}
1589 
1590 out_unlock:
1591 	folio_unlock(src);
1592 out:
1593 	if (!rc)
1594 		folio_putback_hugetlb(src);
1595 	else if (rc != -EAGAIN)
1596 		list_move_tail(&src->lru, ret);
1597 
1598 	/*
1599 	 * If migration was not successful and there's a freeing callback,
1600 	 * return the folio to that special allocator. Otherwise, simply drop
1601 	 * our additional reference.
1602 	 */
1603 	if (put_new_folio)
1604 		put_new_folio(dst, private);
1605 	else
1606 		folio_put(dst);
1607 
1608 	return rc;
1609 }
1610 
1611 static inline int try_split_folio(struct folio *folio, struct list_head *split_folios,
1612 				  enum migrate_mode mode)
1613 {
1614 	int rc;
1615 
1616 	if (mode == MIGRATE_ASYNC) {
1617 		if (!folio_trylock(folio))
1618 			return -EAGAIN;
1619 	} else {
1620 		folio_lock(folio);
1621 	}
1622 	rc = split_folio_to_list(folio, split_folios);
1623 	folio_unlock(folio);
1624 	if (!rc)
1625 		list_move_tail(&folio->lru, split_folios);
1626 
1627 	return rc;
1628 }
1629 
1630 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1631 #define NR_MAX_BATCHED_MIGRATION	HPAGE_PMD_NR
1632 #else
1633 #define NR_MAX_BATCHED_MIGRATION	512
1634 #endif
1635 #define NR_MAX_MIGRATE_PAGES_RETRY	10
1636 #define NR_MAX_MIGRATE_ASYNC_RETRY	3
1637 #define NR_MAX_MIGRATE_SYNC_RETRY					\
1638 	(NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
1639 
1640 struct migrate_pages_stats {
1641 	int nr_succeeded;	/* Normal and large folios migrated successfully, in
1642 				   units of base pages */
1643 	int nr_failed_pages;	/* Normal and large folios failed to be migrated, in
1644 				   units of base pages.  Untried folios aren't counted */
1645 	int nr_thp_succeeded;	/* THP migrated successfully */
1646 	int nr_thp_failed;	/* THP failed to be migrated */
1647 	int nr_thp_split;	/* THP split before migrating */
1648 	int nr_split;	/* Large folio (include THP) split before migrating */
1649 };
1650 
1651 /*
1652  * Returns the number of hugetlb folios that were not migrated, or an error code
1653  * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
1654  * any more because the list has become empty or no retryable hugetlb folios
1655  * exist any more. It is caller's responsibility to call putback_movable_pages()
1656  * only if ret != 0.
1657  */
1658 static int migrate_hugetlbs(struct list_head *from, new_folio_t get_new_folio,
1659 			    free_folio_t put_new_folio, unsigned long private,
1660 			    enum migrate_mode mode, enum migrate_reason reason,
1661 			    struct migrate_pages_stats *stats,
1662 			    struct list_head *ret_folios)
1663 {
1664 	int retry = 1;
1665 	int nr_failed = 0;
1666 	int nr_retry_pages = 0;
1667 	int pass = 0;
1668 	struct folio *folio, *folio2;
1669 	int rc, nr_pages;
1670 
1671 	for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
1672 		retry = 0;
1673 		nr_retry_pages = 0;
1674 
1675 		list_for_each_entry_safe(folio, folio2, from, lru) {
1676 			if (!folio_test_hugetlb(folio))
1677 				continue;
1678 
1679 			nr_pages = folio_nr_pages(folio);
1680 
1681 			cond_resched();
1682 
1683 			/*
1684 			 * Migratability of hugepages depends on architectures and
1685 			 * their size.  This check is necessary because some callers
1686 			 * of hugepage migration like soft offline and memory
1687 			 * hotremove don't walk through page tables or check whether
1688 			 * the hugepage is pmd-based or not before kicking migration.
1689 			 */
1690 			if (!hugepage_migration_supported(folio_hstate(folio))) {
1691 				nr_failed++;
1692 				stats->nr_failed_pages += nr_pages;
1693 				list_move_tail(&folio->lru, ret_folios);
1694 				continue;
1695 			}
1696 
1697 			rc = unmap_and_move_hugetlb_folio(get_new_folio,
1698 							  put_new_folio, private,
1699 							  folio, pass > 2, mode,
1700 							  reason, ret_folios);
1701 			/*
1702 			 * The rules are:
1703 			 *	0: hugetlb folio will be put back
1704 			 *	-EAGAIN: stay on the from list
1705 			 *	-ENOMEM: stay on the from list
1706 			 *	Other errno: put on ret_folios list
1707 			 */
1708 			switch(rc) {
1709 			case -ENOMEM:
1710 				/*
1711 				 * When memory is low, don't bother to try to migrate
1712 				 * other folios, just exit.
1713 				 */
1714 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
1715 				return -ENOMEM;
1716 			case -EAGAIN:
1717 				retry++;
1718 				nr_retry_pages += nr_pages;
1719 				break;
1720 			case 0:
1721 				stats->nr_succeeded += nr_pages;
1722 				break;
1723 			default:
1724 				/*
1725 				 * Permanent failure (-EBUSY, etc.):
1726 				 * unlike -EAGAIN case, the failed folio is
1727 				 * removed from migration folio list and not
1728 				 * retried in the next outer loop.
1729 				 */
1730 				nr_failed++;
1731 				stats->nr_failed_pages += nr_pages;
1732 				break;
1733 			}
1734 		}
1735 	}
1736 	/*
1737 	 * nr_failed is number of hugetlb folios failed to be migrated.  After
1738 	 * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
1739 	 * folios as failed.
1740 	 */
1741 	nr_failed += retry;
1742 	stats->nr_failed_pages += nr_retry_pages;
1743 
1744 	return nr_failed;
1745 }
1746 
1747 static void migrate_folios_move(struct list_head *src_folios,
1748 		struct list_head *dst_folios,
1749 		free_folio_t put_new_folio, unsigned long private,
1750 		enum migrate_mode mode, enum migrate_reason reason,
1751 		struct list_head *ret_folios,
1752 		struct migrate_pages_stats *stats,
1753 		int *retry, int *thp_retry, int *nr_failed,
1754 		int *nr_retry_pages)
1755 {
1756 	struct folio *folio, *folio2, *dst, *dst2;
1757 	bool is_thp;
1758 	int nr_pages;
1759 	int rc;
1760 
1761 	dst = list_first_entry(dst_folios, struct folio, lru);
1762 	dst2 = list_next_entry(dst, lru);
1763 	list_for_each_entry_safe(folio, folio2, src_folios, lru) {
1764 		is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
1765 		nr_pages = folio_nr_pages(folio);
1766 
1767 		cond_resched();
1768 
1769 		rc = migrate_folio_move(put_new_folio, private,
1770 				folio, dst, mode,
1771 				reason, ret_folios);
1772 		/*
1773 		 * The rules are:
1774 		 *	0: folio will be freed
1775 		 *	-EAGAIN: stay on the src_folios list
1776 		 *	Other errno: put on ret_folios list
1777 		 */
1778 		switch (rc) {
1779 		case -EAGAIN:
1780 			*retry += 1;
1781 			*thp_retry += is_thp;
1782 			*nr_retry_pages += nr_pages;
1783 			break;
1784 		case 0:
1785 			stats->nr_succeeded += nr_pages;
1786 			stats->nr_thp_succeeded += is_thp;
1787 			break;
1788 		default:
1789 			*nr_failed += 1;
1790 			stats->nr_thp_failed += is_thp;
1791 			stats->nr_failed_pages += nr_pages;
1792 			break;
1793 		}
1794 		dst = dst2;
1795 		dst2 = list_next_entry(dst, lru);
1796 	}
1797 }
1798 
1799 static void migrate_folios_undo(struct list_head *src_folios,
1800 		struct list_head *dst_folios,
1801 		free_folio_t put_new_folio, unsigned long private,
1802 		struct list_head *ret_folios)
1803 {
1804 	struct folio *folio, *folio2, *dst, *dst2;
1805 
1806 	dst = list_first_entry(dst_folios, struct folio, lru);
1807 	dst2 = list_next_entry(dst, lru);
1808 	list_for_each_entry_safe(folio, folio2, src_folios, lru) {
1809 		int old_folio_state = 0;
1810 		struct anon_vma *anon_vma = NULL;
1811 
1812 		__migrate_folio_extract(dst, &old_folio_state, &anon_vma);
1813 		migrate_folio_undo_src(folio, old_folio_state & FOLIO_WAS_MAPPED,
1814 				anon_vma, true, ret_folios);
1815 		list_del(&dst->lru);
1816 		migrate_folio_undo_dst(dst, true, put_new_folio, private);
1817 		dst = dst2;
1818 		dst2 = list_next_entry(dst, lru);
1819 	}
1820 }
1821 
1822 /*
1823  * migrate_pages_batch() first unmaps folios in the from list as many as
1824  * possible, then move the unmapped folios.
1825  *
1826  * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
1827  * lock or bit when we have locked more than one folio.  Which may cause
1828  * deadlock (e.g., for loop device).  So, if mode != MIGRATE_ASYNC, the
1829  * length of the from list must be <= 1.
1830  */
1831 static int migrate_pages_batch(struct list_head *from,
1832 		new_folio_t get_new_folio, free_folio_t put_new_folio,
1833 		unsigned long private, enum migrate_mode mode, enum migrate_reason reason,
1834 		struct list_head *ret_folios, struct list_head *split_folios,
1835 		struct migrate_pages_stats *stats, int nr_pass)
1836 {
1837 	int retry = 1;
1838 	int thp_retry = 1;
1839 	int nr_failed = 0;
1840 	int nr_retry_pages = 0;
1841 	int pass = 0;
1842 	bool is_thp = false;
1843 	bool is_large = false;
1844 	struct folio *folio, *folio2, *dst = NULL;
1845 	int rc, rc_saved = 0, nr_pages;
1846 	LIST_HEAD(unmap_folios);
1847 	LIST_HEAD(dst_folios);
1848 	bool nosplit = (reason == MR_NUMA_MISPLACED);
1849 
1850 	VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
1851 			!list_empty(from) && !list_is_singular(from));
1852 
1853 	for (pass = 0; pass < nr_pass && retry; pass++) {
1854 		retry = 0;
1855 		thp_retry = 0;
1856 		nr_retry_pages = 0;
1857 
1858 		list_for_each_entry_safe(folio, folio2, from, lru) {
1859 			is_large = folio_test_large(folio);
1860 			is_thp = folio_test_pmd_mappable(folio);
1861 			nr_pages = folio_nr_pages(folio);
1862 
1863 			cond_resched_tasks_rcu_qs();
1864 
1865 			/*
1866 			 * The rare folio on the deferred split list should
1867 			 * be split now. It should not count as a failure:
1868 			 * but increment nr_failed because, without doing so,
1869 			 * migrate_pages() may report success with (split but
1870 			 * unmigrated) pages still on its fromlist; whereas it
1871 			 * always reports success when its fromlist is empty.
1872 			 * stats->nr_thp_failed should be increased too,
1873 			 * otherwise stats inconsistency will happen when
1874 			 * migrate_pages_batch is called via migrate_pages()
1875 			 * with MIGRATE_SYNC and MIGRATE_ASYNC.
1876 			 *
1877 			 * Only check it without removing it from the list.
1878 			 * Since the folio can be on deferred_split_scan()
1879 			 * local list and removing it can cause the local list
1880 			 * corruption. Folio split process below can handle it
1881 			 * with the help of folio_ref_freeze().
1882 			 *
1883 			 * nr_pages > 2 is needed to avoid checking order-1
1884 			 * page cache folios. They exist, in contrast to
1885 			 * non-existent order-1 anonymous folios, and do not
1886 			 * use _deferred_list.
1887 			 */
1888 			if (nr_pages > 2 &&
1889 			   !list_empty(&folio->_deferred_list) &&
1890 			   folio_test_partially_mapped(folio)) {
1891 				if (!try_split_folio(folio, split_folios, mode)) {
1892 					nr_failed++;
1893 					stats->nr_thp_failed += is_thp;
1894 					stats->nr_thp_split += is_thp;
1895 					stats->nr_split++;
1896 					continue;
1897 				}
1898 			}
1899 
1900 			/*
1901 			 * Large folio migration might be unsupported or
1902 			 * the allocation might be failed so we should retry
1903 			 * on the same folio with the large folio split
1904 			 * to normal folios.
1905 			 *
1906 			 * Split folios are put in split_folios, and
1907 			 * we will migrate them after the rest of the
1908 			 * list is processed.
1909 			 */
1910 			if (!thp_migration_supported() && is_thp) {
1911 				nr_failed++;
1912 				stats->nr_thp_failed++;
1913 				if (!try_split_folio(folio, split_folios, mode)) {
1914 					stats->nr_thp_split++;
1915 					stats->nr_split++;
1916 					continue;
1917 				}
1918 				stats->nr_failed_pages += nr_pages;
1919 				list_move_tail(&folio->lru, ret_folios);
1920 				continue;
1921 			}
1922 
1923 			/*
1924 			 * If we are holding the last folio reference, the folio
1925 			 * was freed from under us, so just drop our reference.
1926 			 */
1927 			if (likely(!page_has_movable_ops(&folio->page)) &&
1928 			    folio_ref_count(folio) == 1) {
1929 				folio_clear_active(folio);
1930 				folio_clear_unevictable(folio);
1931 				list_del(&folio->lru);
1932 				migrate_folio_done(folio, reason);
1933 				stats->nr_succeeded += nr_pages;
1934 				stats->nr_thp_succeeded += is_thp;
1935 				continue;
1936 			}
1937 
1938 			rc = migrate_folio_unmap(get_new_folio, put_new_folio,
1939 					private, folio, &dst, mode, ret_folios);
1940 			/*
1941 			 * The rules are:
1942 			 *	0: folio will be put on unmap_folios list,
1943 			 *	   dst folio put on dst_folios list
1944 			 *	-EAGAIN: stay on the from list
1945 			 *	-ENOMEM: stay on the from list
1946 			 *	Other errno: put on ret_folios list
1947 			 */
1948 			switch(rc) {
1949 			case -ENOMEM:
1950 				/*
1951 				 * When memory is low, don't bother to try to migrate
1952 				 * other folios, move unmapped folios, then exit.
1953 				 */
1954 				nr_failed++;
1955 				stats->nr_thp_failed += is_thp;
1956 				/* Large folio NUMA faulting doesn't split to retry. */
1957 				if (is_large && !nosplit) {
1958 					int ret = try_split_folio(folio, split_folios, mode);
1959 
1960 					if (!ret) {
1961 						stats->nr_thp_split += is_thp;
1962 						stats->nr_split++;
1963 						break;
1964 					} else if (reason == MR_LONGTERM_PIN &&
1965 						   ret == -EAGAIN) {
1966 						/*
1967 						 * Try again to split large folio to
1968 						 * mitigate the failure of longterm pinning.
1969 						 */
1970 						retry++;
1971 						thp_retry += is_thp;
1972 						nr_retry_pages += nr_pages;
1973 						/* Undo duplicated failure counting. */
1974 						nr_failed--;
1975 						stats->nr_thp_failed -= is_thp;
1976 						break;
1977 					}
1978 				}
1979 
1980 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
1981 				/* nr_failed isn't updated for not used */
1982 				stats->nr_thp_failed += thp_retry;
1983 				rc_saved = rc;
1984 				if (list_empty(&unmap_folios))
1985 					goto out;
1986 				else
1987 					goto move;
1988 			case -EAGAIN:
1989 				retry++;
1990 				thp_retry += is_thp;
1991 				nr_retry_pages += nr_pages;
1992 				break;
1993 			case 0:
1994 				list_move_tail(&folio->lru, &unmap_folios);
1995 				list_add_tail(&dst->lru, &dst_folios);
1996 				break;
1997 			default:
1998 				/*
1999 				 * Permanent failure (-EBUSY, etc.):
2000 				 * unlike -EAGAIN case, the failed folio is
2001 				 * removed from migration folio list and not
2002 				 * retried in the next outer loop.
2003 				 */
2004 				nr_failed++;
2005 				stats->nr_thp_failed += is_thp;
2006 				stats->nr_failed_pages += nr_pages;
2007 				break;
2008 			}
2009 		}
2010 	}
2011 	nr_failed += retry;
2012 	stats->nr_thp_failed += thp_retry;
2013 	stats->nr_failed_pages += nr_retry_pages;
2014 move:
2015 	/* Flush TLBs for all unmapped folios */
2016 	try_to_unmap_flush();
2017 
2018 	retry = 1;
2019 	for (pass = 0; pass < nr_pass && retry; pass++) {
2020 		retry = 0;
2021 		thp_retry = 0;
2022 		nr_retry_pages = 0;
2023 
2024 		/* Move the unmapped folios */
2025 		migrate_folios_move(&unmap_folios, &dst_folios,
2026 				put_new_folio, private, mode, reason,
2027 				ret_folios, stats, &retry, &thp_retry,
2028 				&nr_failed, &nr_retry_pages);
2029 	}
2030 	nr_failed += retry;
2031 	stats->nr_thp_failed += thp_retry;
2032 	stats->nr_failed_pages += nr_retry_pages;
2033 
2034 	rc = rc_saved ? : nr_failed;
2035 out:
2036 	/* Cleanup remaining folios */
2037 	migrate_folios_undo(&unmap_folios, &dst_folios,
2038 			put_new_folio, private, ret_folios);
2039 
2040 	return rc;
2041 }
2042 
2043 static int migrate_pages_sync(struct list_head *from, new_folio_t get_new_folio,
2044 		free_folio_t put_new_folio, unsigned long private,
2045 		enum migrate_mode mode, enum migrate_reason reason,
2046 		struct list_head *ret_folios, struct list_head *split_folios,
2047 		struct migrate_pages_stats *stats)
2048 {
2049 	int rc, nr_failed = 0;
2050 	LIST_HEAD(folios);
2051 	struct migrate_pages_stats astats;
2052 
2053 	memset(&astats, 0, sizeof(astats));
2054 	/* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
2055 	rc = migrate_pages_batch(from, get_new_folio, put_new_folio, private, MIGRATE_ASYNC,
2056 				 reason, &folios, split_folios, &astats,
2057 				 NR_MAX_MIGRATE_ASYNC_RETRY);
2058 	stats->nr_succeeded += astats.nr_succeeded;
2059 	stats->nr_thp_succeeded += astats.nr_thp_succeeded;
2060 	stats->nr_thp_split += astats.nr_thp_split;
2061 	stats->nr_split += astats.nr_split;
2062 	if (rc < 0) {
2063 		stats->nr_failed_pages += astats.nr_failed_pages;
2064 		stats->nr_thp_failed += astats.nr_thp_failed;
2065 		list_splice_tail(&folios, ret_folios);
2066 		return rc;
2067 	}
2068 	stats->nr_thp_failed += astats.nr_thp_split;
2069 	/*
2070 	 * Do not count rc, as pages will be retried below.
2071 	 * Count nr_split only, since it includes nr_thp_split.
2072 	 */
2073 	nr_failed += astats.nr_split;
2074 	/*
2075 	 * Fall back to migrate all failed folios one by one synchronously. All
2076 	 * failed folios except split THPs will be retried, so their failure
2077 	 * isn't counted
2078 	 */
2079 	list_splice_tail_init(&folios, from);
2080 	while (!list_empty(from)) {
2081 		list_move(from->next, &folios);
2082 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
2083 					 private, mode, reason, ret_folios,
2084 					 split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
2085 		list_splice_tail_init(&folios, ret_folios);
2086 		if (rc < 0)
2087 			return rc;
2088 		nr_failed += rc;
2089 	}
2090 
2091 	return nr_failed;
2092 }
2093 
2094 /*
2095  * migrate_pages - migrate the folios specified in a list, to the free folios
2096  *		   supplied as the target for the page migration
2097  *
2098  * @from:		The list of folios to be migrated.
2099  * @get_new_folio:	The function used to allocate free folios to be used
2100  *			as the target of the folio migration.
2101  * @put_new_folio:	The function used to free target folios if migration
2102  *			fails, or NULL if no special handling is necessary.
2103  * @private:		Private data to be passed on to get_new_folio()
2104  * @mode:		The migration mode that specifies the constraints for
2105  *			folio migration, if any.
2106  * @reason:		The reason for folio migration.
2107  * @ret_succeeded:	Set to the number of folios migrated successfully if
2108  *			the caller passes a non-NULL pointer.
2109  *
2110  * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
2111  * are movable any more because the list has become empty or no retryable folios
2112  * exist any more. It is caller's responsibility to call putback_movable_pages()
2113  * only if ret != 0.
2114  *
2115  * Returns the number of {normal folio, large folio, hugetlb} that were not
2116  * migrated, or an error code. The number of large folio splits will be
2117  * considered as the number of non-migrated large folio, no matter how many
2118  * split folios of the large folio are migrated successfully.
2119  */
2120 int migrate_pages(struct list_head *from, new_folio_t get_new_folio,
2121 		free_folio_t put_new_folio, unsigned long private,
2122 		enum migrate_mode mode, enum migrate_reason reason, unsigned int *ret_succeeded)
2123 {
2124 	int rc, rc_gather;
2125 	int nr_pages;
2126 	struct folio *folio, *folio2;
2127 	LIST_HEAD(folios);
2128 	LIST_HEAD(ret_folios);
2129 	LIST_HEAD(split_folios);
2130 	struct migrate_pages_stats stats;
2131 
2132 	trace_mm_migrate_pages_start(mode, reason);
2133 
2134 	memset(&stats, 0, sizeof(stats));
2135 
2136 	rc_gather = migrate_hugetlbs(from, get_new_folio, put_new_folio, private,
2137 				     mode, reason, &stats, &ret_folios);
2138 	if (rc_gather < 0)
2139 		goto out;
2140 
2141 again:
2142 	nr_pages = 0;
2143 	list_for_each_entry_safe(folio, folio2, from, lru) {
2144 		/* Retried hugetlb folios will be kept in list  */
2145 		if (folio_test_hugetlb(folio)) {
2146 			list_move_tail(&folio->lru, &ret_folios);
2147 			continue;
2148 		}
2149 
2150 		nr_pages += folio_nr_pages(folio);
2151 		if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
2152 			break;
2153 	}
2154 	if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
2155 		list_cut_before(&folios, from, &folio2->lru);
2156 	else
2157 		list_splice_init(from, &folios);
2158 	if (mode == MIGRATE_ASYNC)
2159 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
2160 				private, mode, reason, &ret_folios,
2161 				&split_folios, &stats,
2162 				NR_MAX_MIGRATE_PAGES_RETRY);
2163 	else
2164 		rc = migrate_pages_sync(&folios, get_new_folio, put_new_folio,
2165 				private, mode, reason, &ret_folios,
2166 				&split_folios, &stats);
2167 	list_splice_tail_init(&folios, &ret_folios);
2168 	if (rc < 0) {
2169 		rc_gather = rc;
2170 		list_splice_tail(&split_folios, &ret_folios);
2171 		goto out;
2172 	}
2173 	if (!list_empty(&split_folios)) {
2174 		/*
2175 		 * Failure isn't counted since all split folios of a large folio
2176 		 * is counted as 1 failure already.  And, we only try to migrate
2177 		 * with minimal effort, force MIGRATE_ASYNC mode and retry once.
2178 		 */
2179 		migrate_pages_batch(&split_folios, get_new_folio,
2180 				put_new_folio, private, MIGRATE_ASYNC, reason,
2181 				&ret_folios, NULL, &stats, 1);
2182 		list_splice_tail_init(&split_folios, &ret_folios);
2183 	}
2184 	rc_gather += rc;
2185 	if (!list_empty(from))
2186 		goto again;
2187 out:
2188 	/*
2189 	 * Put the permanent failure folio back to migration list, they
2190 	 * will be put back to the right list by the caller.
2191 	 */
2192 	list_splice(&ret_folios, from);
2193 
2194 	/*
2195 	 * Return 0 in case all split folios of fail-to-migrate large folios
2196 	 * are migrated successfully.
2197 	 */
2198 	if (list_empty(from))
2199 		rc_gather = 0;
2200 
2201 	count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
2202 	count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
2203 	count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
2204 	count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
2205 	count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
2206 	trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
2207 			       stats.nr_thp_succeeded, stats.nr_thp_failed,
2208 			       stats.nr_thp_split, stats.nr_split, mode,
2209 			       reason);
2210 
2211 	if (ret_succeeded)
2212 		*ret_succeeded = stats.nr_succeeded;
2213 
2214 	return rc_gather;
2215 }
2216 
2217 struct folio *alloc_migration_target(struct folio *src, unsigned long private)
2218 {
2219 	struct migration_target_control *mtc;
2220 	gfp_t gfp_mask;
2221 	unsigned int order = 0;
2222 	int nid;
2223 	enum zone_type zidx;
2224 
2225 	mtc = (struct migration_target_control *)private;
2226 	gfp_mask = mtc->gfp_mask;
2227 	nid = mtc->nid;
2228 	if (nid == NUMA_NO_NODE)
2229 		nid = folio_nid(src);
2230 
2231 	if (folio_test_hugetlb(src)) {
2232 		struct hstate *h = folio_hstate(src);
2233 
2234 		gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
2235 		return alloc_hugetlb_folio_nodemask(h, nid,
2236 						mtc->nmask, gfp_mask,
2237 						htlb_allow_alloc_fallback(mtc->reason));
2238 	}
2239 
2240 	if (folio_test_large(src)) {
2241 		/*
2242 		 * clear __GFP_RECLAIM to make the migration callback
2243 		 * consistent with regular THP allocations.
2244 		 */
2245 		gfp_mask &= ~__GFP_RECLAIM;
2246 		gfp_mask |= GFP_TRANSHUGE;
2247 		order = folio_order(src);
2248 	}
2249 	zidx = folio_zonenum(src);
2250 	if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
2251 		gfp_mask |= __GFP_HIGHMEM;
2252 
2253 	return __folio_alloc(gfp_mask, order, nid, mtc->nmask);
2254 }
2255 
2256 #ifdef CONFIG_NUMA_MIGRATION
2257 static int store_status(int __user *status, int start, int value, int nr)
2258 {
2259 	while (nr-- > 0) {
2260 		if (put_user(value, status + start))
2261 			return -EFAULT;
2262 		start++;
2263 	}
2264 
2265 	return 0;
2266 }
2267 
2268 static int do_move_pages_to_node(struct list_head *pagelist, int node)
2269 {
2270 	int err;
2271 	struct migration_target_control mtc = {
2272 		.nid = node,
2273 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
2274 		.reason = MR_SYSCALL,
2275 	};
2276 
2277 	err = migrate_pages(pagelist, alloc_migration_target, NULL,
2278 		(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
2279 	if (err)
2280 		putback_movable_pages(pagelist);
2281 	return err;
2282 }
2283 
2284 static int __add_folio_for_migration(struct folio *folio, int node,
2285 		struct list_head *pagelist, bool migrate_all)
2286 {
2287 	if (is_zero_folio(folio) || is_huge_zero_folio(folio))
2288 		return -EFAULT;
2289 
2290 	if (folio_is_zone_device(folio))
2291 		return -ENOENT;
2292 
2293 	if (folio_nid(folio) == node)
2294 		return 0;
2295 
2296 	if (folio_maybe_mapped_shared(folio) && !migrate_all)
2297 		return -EACCES;
2298 
2299 	if (folio_test_hugetlb(folio)) {
2300 		if (folio_isolate_hugetlb(folio, pagelist))
2301 			return 1;
2302 	} else if (folio_isolate_lru(folio)) {
2303 		list_add_tail(&folio->lru, pagelist);
2304 		node_stat_mod_folio(folio,
2305 			NR_ISOLATED_ANON + folio_is_file_lru(folio),
2306 			folio_nr_pages(folio));
2307 		return 1;
2308 	}
2309 	return -EBUSY;
2310 }
2311 
2312 /*
2313  * Resolves the given address to a struct folio, isolates it from the LRU and
2314  * puts it to the given pagelist.
2315  * Returns:
2316  *     errno - if the folio cannot be found/isolated
2317  *     0 - when it doesn't have to be migrated because it is already on the
2318  *         target node
2319  *     1 - when it has been queued
2320  */
2321 static int add_folio_for_migration(struct mm_struct *mm, const void __user *p,
2322 		int node, struct list_head *pagelist, bool migrate_all)
2323 {
2324 	struct vm_area_struct *vma;
2325 	struct folio_walk fw;
2326 	struct folio *folio;
2327 	unsigned long addr;
2328 	int err = -EFAULT;
2329 
2330 	mmap_read_lock(mm);
2331 	addr = (unsigned long)untagged_addr_remote(mm, p);
2332 
2333 	vma = vma_lookup(mm, addr);
2334 	if (vma && vma_migratable(vma)) {
2335 		folio = folio_walk_start(&fw, vma, addr, FW_ZEROPAGE);
2336 		if (folio) {
2337 			err = __add_folio_for_migration(folio, node, pagelist,
2338 							migrate_all);
2339 			folio_walk_end(&fw, vma);
2340 		} else {
2341 			err = -ENOENT;
2342 		}
2343 	}
2344 	mmap_read_unlock(mm);
2345 	return err;
2346 }
2347 
2348 static int move_pages_and_store_status(int node,
2349 		struct list_head *pagelist, int __user *status,
2350 		int start, int i, unsigned long nr_pages)
2351 {
2352 	int err;
2353 
2354 	if (list_empty(pagelist))
2355 		return 0;
2356 
2357 	err = do_move_pages_to_node(pagelist, node);
2358 	if (err) {
2359 		/*
2360 		 * Positive err means the number of failed
2361 		 * pages to migrate.  Since we are going to
2362 		 * abort and return the number of non-migrated
2363 		 * pages, so need to include the rest of the
2364 		 * nr_pages that have not been attempted as
2365 		 * well.
2366 		 */
2367 		if (err > 0)
2368 			err += nr_pages - i;
2369 		return err;
2370 	}
2371 	return store_status(status, start, node, i - start);
2372 }
2373 
2374 /*
2375  * Migrate an array of page address onto an array of nodes and fill
2376  * the corresponding array of status.
2377  */
2378 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
2379 			 unsigned long nr_pages,
2380 			 const void __user * __user *pages,
2381 			 const int __user *nodes,
2382 			 int __user *status, int flags)
2383 {
2384 	compat_uptr_t __user *compat_pages = (void __user *)pages;
2385 	int current_node = NUMA_NO_NODE;
2386 	LIST_HEAD(pagelist);
2387 	int start, i;
2388 	int err = 0, err1;
2389 
2390 	lru_cache_disable();
2391 
2392 	for (i = start = 0; i < nr_pages; i++) {
2393 		const void __user *p;
2394 		int node;
2395 
2396 		err = -EFAULT;
2397 		if (in_compat_syscall()) {
2398 			compat_uptr_t cp;
2399 
2400 			if (get_user(cp, compat_pages + i))
2401 				goto out_flush;
2402 
2403 			p = compat_ptr(cp);
2404 		} else {
2405 			if (get_user(p, pages + i))
2406 				goto out_flush;
2407 		}
2408 		if (get_user(node, nodes + i))
2409 			goto out_flush;
2410 
2411 		err = -ENODEV;
2412 		if (node < 0 || node >= MAX_NUMNODES)
2413 			goto out_flush;
2414 		if (!node_state(node, N_MEMORY))
2415 			goto out_flush;
2416 
2417 		err = -EACCES;
2418 		if (!node_isset(node, task_nodes))
2419 			goto out_flush;
2420 
2421 		if (current_node == NUMA_NO_NODE) {
2422 			current_node = node;
2423 			start = i;
2424 		} else if (node != current_node) {
2425 			err = move_pages_and_store_status(current_node,
2426 					&pagelist, status, start, i, nr_pages);
2427 			if (err)
2428 				goto out;
2429 			start = i;
2430 			current_node = node;
2431 		}
2432 
2433 		/*
2434 		 * Errors in the page lookup or isolation are not fatal and we simply
2435 		 * report them via status
2436 		 */
2437 		err = add_folio_for_migration(mm, p, current_node, &pagelist,
2438 					      flags & MPOL_MF_MOVE_ALL);
2439 
2440 		if (err > 0) {
2441 			/* The page is successfully queued for migration */
2442 			continue;
2443 		}
2444 
2445 		/*
2446 		 * If the page is already on the target node (!err), store the
2447 		 * node, otherwise, store the err.
2448 		 */
2449 		err = store_status(status, i, err ? : current_node, 1);
2450 		if (err)
2451 			goto out_flush;
2452 
2453 		err = move_pages_and_store_status(current_node, &pagelist,
2454 				status, start, i, nr_pages);
2455 		if (err) {
2456 			/* We have accounted for page i */
2457 			if (err > 0)
2458 				err--;
2459 			goto out;
2460 		}
2461 		current_node = NUMA_NO_NODE;
2462 	}
2463 out_flush:
2464 	/* Make sure we do not overwrite the existing error */
2465 	err1 = move_pages_and_store_status(current_node, &pagelist,
2466 				status, start, i, nr_pages);
2467 	if (err >= 0)
2468 		err = err1;
2469 out:
2470 	lru_cache_enable();
2471 	return err;
2472 }
2473 
2474 /*
2475  * Determine the nodes of an array of pages and store it in an array of status.
2476  */
2477 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
2478 				const void __user **pages, int *status)
2479 {
2480 	unsigned long i;
2481 
2482 	mmap_read_lock(mm);
2483 
2484 	for (i = 0; i < nr_pages; i++) {
2485 		unsigned long addr = (unsigned long)untagged_addr_remote(mm, *pages);
2486 		struct vm_area_struct *vma;
2487 		struct folio_walk fw;
2488 		struct folio *folio;
2489 		int err = -EFAULT;
2490 
2491 		vma = vma_lookup(mm, addr);
2492 		if (!vma)
2493 			goto set_status;
2494 
2495 		folio = folio_walk_start(&fw, vma, addr, FW_ZEROPAGE);
2496 		if (folio) {
2497 			if (is_zero_folio(folio) || is_huge_zero_folio(folio))
2498 				err = -EFAULT;
2499 			else if (folio_is_zone_device(folio))
2500 				err = -ENOENT;
2501 			else
2502 				err = folio_nid(folio);
2503 			folio_walk_end(&fw, vma);
2504 		} else {
2505 			err = -ENOENT;
2506 		}
2507 set_status:
2508 		*status = err;
2509 
2510 		pages++;
2511 		status++;
2512 	}
2513 
2514 	mmap_read_unlock(mm);
2515 }
2516 
2517 static int get_compat_pages_array(const void __user *chunk_pages[],
2518 				  const void __user * __user *pages,
2519 				  unsigned long chunk_offset,
2520 				  unsigned long chunk_nr)
2521 {
2522 	compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
2523 	compat_uptr_t p;
2524 	int i;
2525 
2526 	for (i = 0; i < chunk_nr; i++) {
2527 		if (get_user(p, pages32 + chunk_offset + i))
2528 			return -EFAULT;
2529 		chunk_pages[i] = compat_ptr(p);
2530 	}
2531 
2532 	return 0;
2533 }
2534 
2535 /*
2536  * Determine the nodes of a user array of pages and store it in
2537  * a user array of status.
2538  */
2539 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
2540 			 const void __user * __user *pages,
2541 			 int __user *status)
2542 {
2543 #define DO_PAGES_STAT_CHUNK_NR 16UL
2544 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
2545 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
2546 	unsigned long chunk_offset = 0;
2547 
2548 	while (nr_pages) {
2549 		unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
2550 
2551 		if (in_compat_syscall()) {
2552 			if (get_compat_pages_array(chunk_pages, pages,
2553 						   chunk_offset, chunk_nr))
2554 				break;
2555 		} else {
2556 			if (copy_from_user(chunk_pages, pages + chunk_offset,
2557 				      chunk_nr * sizeof(*chunk_pages)))
2558 				break;
2559 		}
2560 
2561 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
2562 
2563 		if (copy_to_user(status + chunk_offset, chunk_status,
2564 				 chunk_nr * sizeof(*status)))
2565 			break;
2566 
2567 		chunk_offset += chunk_nr;
2568 		nr_pages -= chunk_nr;
2569 	}
2570 	return nr_pages ? -EFAULT : 0;
2571 }
2572 
2573 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
2574 {
2575 	struct task_struct *task;
2576 	struct mm_struct *mm;
2577 
2578 	/*
2579 	 * There is no need to check if current process has the right to modify
2580 	 * the specified process when they are same.
2581 	 */
2582 	if (!pid) {
2583 		mmget(current->mm);
2584 		*mem_nodes = cpuset_mems_allowed(current);
2585 		return current->mm;
2586 	}
2587 
2588 	task = find_get_task_by_vpid(pid);
2589 	if (!task)
2590 		return ERR_PTR(-ESRCH);
2591 
2592 	if (down_read_killable(&task->signal->exec_update_lock)) {
2593 		mm = ERR_PTR(-EINTR);
2594 		goto out;
2595 	}
2596 	/*
2597 	 * Check if this process has the right to modify the specified
2598 	 * process. Use the regular "ptrace_may_access()" checks.
2599 	 */
2600 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2601 		mm = ERR_PTR(-EPERM);
2602 		goto unlock;
2603 	}
2604 
2605 	mm = ERR_PTR(security_task_movememory(task));
2606 	if (IS_ERR(mm))
2607 		goto unlock;
2608 	*mem_nodes = cpuset_mems_allowed(task);
2609 	mm = get_task_mm(task);
2610 unlock:
2611 	up_read(&task->signal->exec_update_lock);
2612 out:
2613 	put_task_struct(task);
2614 	if (!mm)
2615 		mm = ERR_PTR(-EINVAL);
2616 	return mm;
2617 }
2618 
2619 /*
2620  * Move a list of pages in the address space of the currently executing
2621  * process.
2622  */
2623 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2624 			     const void __user * __user *pages,
2625 			     const int __user *nodes,
2626 			     int __user *status, int flags)
2627 {
2628 	struct mm_struct *mm;
2629 	int err;
2630 	nodemask_t task_nodes;
2631 
2632 	/* Check flags */
2633 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2634 		return -EINVAL;
2635 
2636 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2637 		return -EPERM;
2638 
2639 	mm = find_mm_struct(pid, &task_nodes);
2640 	if (IS_ERR(mm))
2641 		return PTR_ERR(mm);
2642 
2643 	if (nodes)
2644 		err = do_pages_move(mm, task_nodes, nr_pages, pages,
2645 				    nodes, status, flags);
2646 	else
2647 		err = do_pages_stat(mm, nr_pages, pages, status);
2648 
2649 	mmput(mm);
2650 	return err;
2651 }
2652 
2653 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2654 		const void __user * __user *, pages,
2655 		const int __user *, nodes,
2656 		int __user *, status, int, flags)
2657 {
2658 	return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2659 }
2660 #endif /* CONFIG_NUMA_MIGRATION */
2661 
2662 #ifdef CONFIG_NUMA_BALANCING
2663 /*
2664  * Returns true if this is a safe migration target node for misplaced NUMA
2665  * pages. Currently it only checks the watermarks which is crude.
2666  */
2667 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2668 				   unsigned long nr_migrate_pages)
2669 {
2670 	int z;
2671 
2672 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2673 		struct zone *zone = pgdat->node_zones + z;
2674 
2675 		if (!managed_zone(zone))
2676 			continue;
2677 
2678 		/* Avoid waking kswapd by allocating pages_to_migrate pages. */
2679 		if (!zone_watermark_ok(zone, 0,
2680 				       high_wmark_pages(zone) +
2681 				       nr_migrate_pages,
2682 				       ZONE_MOVABLE, ALLOC_CMA))
2683 			continue;
2684 		return true;
2685 	}
2686 	return false;
2687 }
2688 
2689 static struct folio *alloc_misplaced_dst_folio(struct folio *src,
2690 					   unsigned long data)
2691 {
2692 	int nid = (int) data;
2693 	int order = folio_order(src);
2694 	gfp_t gfp = __GFP_THISNODE;
2695 
2696 	if (order > 0)
2697 		gfp |= GFP_TRANSHUGE_LIGHT;
2698 	else {
2699 		gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2700 			__GFP_NOWARN;
2701 		gfp &= ~__GFP_RECLAIM;
2702 	}
2703 	return __folio_alloc_node(gfp, order, nid);
2704 }
2705 
2706 /*
2707  * Prepare for calling migrate_misplaced_folio() by isolating the folio if
2708  * permitted. Must be called with the PTL still held.
2709  */
2710 int migrate_misplaced_folio_prepare(struct folio *folio,
2711 		struct vm_area_struct *vma, int node)
2712 {
2713 	int nr_pages = folio_nr_pages(folio);
2714 	pg_data_t *pgdat = NODE_DATA(node);
2715 
2716 	if (folio_is_file_lru(folio)) {
2717 		/*
2718 		 * Do not migrate file folios that are mapped in multiple
2719 		 * processes with execute permissions as they are probably
2720 		 * shared libraries.
2721 		 *
2722 		 * See folio_maybe_mapped_shared() on possible imprecision
2723 		 * when we cannot easily detect if a folio is shared.
2724 		 */
2725 		if ((vma->vm_flags & VM_EXEC) && folio_maybe_mapped_shared(folio))
2726 			return -EACCES;
2727 
2728 		/*
2729 		 * Do not migrate dirty folios as not all filesystems can move
2730 		 * dirty folios in MIGRATE_ASYNC mode which is a waste of
2731 		 * cycles.
2732 		 */
2733 		if (folio_test_dirty(folio))
2734 			return -EAGAIN;
2735 	}
2736 
2737 	/* Avoid migrating to a node that is nearly full */
2738 	if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2739 		int z;
2740 
2741 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2742 			return -EAGAIN;
2743 		for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2744 			if (managed_zone(pgdat->node_zones + z))
2745 				break;
2746 		}
2747 
2748 		/*
2749 		 * If there are no managed zones, it should not proceed
2750 		 * further.
2751 		 */
2752 		if (z < 0)
2753 			return -EAGAIN;
2754 
2755 		wakeup_kswapd(pgdat->node_zones + z, 0,
2756 			      folio_order(folio), ZONE_MOVABLE);
2757 		return -EAGAIN;
2758 	}
2759 
2760 	if (!folio_isolate_lru(folio))
2761 		return -EAGAIN;
2762 
2763 	node_stat_mod_folio(folio, NR_ISOLATED_ANON + folio_is_file_lru(folio),
2764 			    nr_pages);
2765 	return 0;
2766 }
2767 
2768 /*
2769  * Attempt to migrate a misplaced folio to the specified destination
2770  * node. Caller is expected to have isolated the folio by calling
2771  * migrate_misplaced_folio_prepare(), which will result in an
2772  * elevated reference count on the folio. This function will un-isolate the
2773  * folio, dereferencing the folio before returning.
2774  */
2775 int migrate_misplaced_folio(struct folio *folio, int node)
2776 {
2777 	pg_data_t *pgdat = NODE_DATA(node);
2778 	int nr_remaining;
2779 	unsigned int nr_succeeded;
2780 	int src_node = folio_nid(folio);
2781 	LIST_HEAD(migratepages);
2782 	struct mem_cgroup *memcg = get_mem_cgroup_from_folio(folio);
2783 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2784 
2785 	list_add(&folio->lru, &migratepages);
2786 	nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_folio,
2787 				     NULL, node, MIGRATE_ASYNC,
2788 				     MR_NUMA_MISPLACED, &nr_succeeded);
2789 	if (nr_remaining && !list_empty(&migratepages))
2790 		putback_movable_pages(&migratepages);
2791 	if (nr_succeeded) {
2792 		count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2793 		count_memcg_events(memcg, NUMA_PAGE_MIGRATE, nr_succeeded);
2794 		if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
2795 		    && !node_is_toptier(src_node)
2796 		    && node_is_toptier(node))
2797 			mod_lruvec_state(lruvec, PGPROMOTE_SUCCESS, nr_succeeded);
2798 	}
2799 	mem_cgroup_put(memcg);
2800 	BUG_ON(!list_empty(&migratepages));
2801 	return nr_remaining ? -EAGAIN : 0;
2802 }
2803 #endif /* CONFIG_NUMA_BALANCING */
2804