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