File Index
Files and directories
Sign in
FILE

migrate.c

File preview with syntax highlighting.

linux-6.19.14/mm/migrate.c C
   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
  54static const struct movable_operations *offline_movable_ops;
  55static const struct movable_operations *zsmalloc_movable_ops;
  56
  57int 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}
  79EXPORT_SYMBOL_GPL(set_movable_ops);
  80
  81static const struct movable_operations *page_movable_ops(struct page *page)
  82{
  83	VM_WARN_ON_ONCE_PAGE(!page_has_movable_ops(page), page);
  84
  85	/*
  86	 * If we enable page migration for a page of a certain type by marking
  87	 * it as movable, the page type must be sticky until the page gets freed
  88	 * back to the buddy.
  89	 */
  90	if (PageOffline(page))
  91		/* Only balloon compaction sets PageOffline pages movable. */
  92		return offline_movable_ops;
  93	if (PageZsmalloc(page))
  94		return zsmalloc_movable_ops;
  95
  96	return NULL;
  97}
  98
  99/**
 100 * isolate_movable_ops_page - isolate a movable_ops page for migration
 101 * @page: The page.
 102 * @mode: The isolation mode.
 103 *
 104 * Try to isolate a movable_ops page for migration. Will fail if the page is
 105 * not a movable_ops page, if the page is already isolated for migration
 106 * or if the page was just was released by its owner.
 107 *
 108 * Once isolated, the page cannot get freed until it is either putback
 109 * or migrated.
 110 *
 111 * Returns true if isolation succeeded, otherwise false.
 112 */
 113bool 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
 177out_no_isolated:
 178	folio_unlock(folio);
 179out_putfolio:
 180	folio_put(folio);
 181out:
 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 */
 193static 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 */
 236static 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 */
 257void 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 */
 279bool 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
 298static 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
 338struct 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 */
 346static 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 */
 455void remove_migration_ptes(struct folio *src, struct folio *dst, int flags)
 456{
 457	struct rmap_walk_arg rmap_walk_arg = {
 458		.folio = src,
 459		.map_unused_to_zeropage = flags & RMP_USE_SHARED_ZEROPAGE,
 460	};
 461
 462	struct rmap_walk_control rwc = {
 463		.rmap_one = remove_migration_pte,
 464		.arg = &rmap_walk_arg,
 465	};
 466
 467	VM_BUG_ON_FOLIO((flags & RMP_USE_SHARED_ZEROPAGE) && (src != dst), src);
 468
 469	if (flags & RMP_LOCKED)
 470		rmap_walk_locked(dst, &rwc);
 471	else
 472		rmap_walk(dst, &rwc);
 473}
 474
 475/*
 476 * Something used the pte of a page under migration. We need to
 477 * get to the page and wait until migration is finished.
 478 * When we return from this function the fault will be retried.
 479 */
 480void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
 481			  unsigned long address)
 482{
 483	spinlock_t *ptl;
 484	pte_t *ptep;
 485	pte_t pte;
 486	softleaf_t entry;
 487
 488	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
 489	if (!ptep)
 490		return;
 491
 492	pte = ptep_get(ptep);
 493	pte_unmap(ptep);
 494
 495	if (pte_none(pte) || pte_present(pte))
 496		goto out;
 497
 498	entry = softleaf_from_pte(pte);
 499	if (!softleaf_is_migration(entry))
 500		goto out;
 501
 502	softleaf_entry_wait_on_locked(entry, ptl);
 503	return;
 504out:
 505	spin_unlock(ptl);
 506}
 507
 508#ifdef CONFIG_HUGETLB_PAGE
 509/*
 510 * The vma read lock must be held upon entry. Holding that lock prevents either
 511 * the pte or the ptl from being freed.
 512 *
 513 * This function will release the vma lock before returning.
 514 */
 515void migration_entry_wait_huge(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep)
 516{
 517	spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, ptep);
 518	softleaf_t entry;
 519	pte_t pte;
 520
 521	hugetlb_vma_assert_locked(vma);
 522	spin_lock(ptl);
 523	pte = huge_ptep_get(vma->vm_mm, addr, ptep);
 524
 525	if (huge_pte_none(pte))
 526		goto fail;
 527
 528	entry = softleaf_from_pte(pte);
 529	if (softleaf_is_migration(entry)) {
 530		/*
 531		 * If migration entry existed, safe to release vma lock
 532		 * here because the pgtable page won't be freed without the
 533		 * pgtable lock released.  See comment right above pgtable
 534		 * lock release in softleaf_entry_wait_on_locked().
 535		 */
 536		hugetlb_vma_unlock_read(vma);
 537		softleaf_entry_wait_on_locked(entry, ptl);
 538		return;
 539	}
 540
 541fail:
 542	spin_unlock(ptl);
 543	hugetlb_vma_unlock_read(vma);
 544}
 545#endif
 546
 547#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
 548void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
 549{
 550	spinlock_t *ptl;
 551
 552	ptl = pmd_lock(mm, pmd);
 553	if (!pmd_is_migration_entry(*pmd))
 554		goto unlock;
 555	softleaf_entry_wait_on_locked(softleaf_from_pmd(*pmd), ptl);
 556	return;
 557unlock:
 558	spin_unlock(ptl);
 559}
 560#endif
 561
 562/*
 563 * Replace the folio in the mapping.
 564 *
 565 * The number of remaining references must be:
 566 * 1 for anonymous folios without a mapping
 567 * 2 for folios with a mapping
 568 * 3 for folios with a mapping and the private flag set.
 569 */
 570static int __folio_migrate_mapping(struct address_space *mapping,
 571		struct folio *newfolio, struct folio *folio, int expected_count)
 572{
 573	XA_STATE(xas, &mapping->i_pages, folio->index);
 574	struct swap_cluster_info *ci = NULL;
 575	struct zone *oldzone, *newzone;
 576	int dirty;
 577	long nr = folio_nr_pages(folio);
 578
 579	if (!mapping) {
 580		/* Take off deferred split queue while frozen and memcg set */
 581		if (folio_test_large(folio) &&
 582		    folio_test_large_rmappable(folio)) {
 583			if (!folio_ref_freeze(folio, expected_count))
 584				return -EAGAIN;
 585			folio_unqueue_deferred_split(folio);
 586			folio_ref_unfreeze(folio, expected_count);
 587		}
 588
 589		/* No turning back from here */
 590		newfolio->index = folio->index;
 591		newfolio->mapping = folio->mapping;
 592		if (folio_test_anon(folio) && folio_test_large(folio))
 593			mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
 594		if (folio_test_swapbacked(folio))
 595			__folio_set_swapbacked(newfolio);
 596
 597		return 0;
 598	}
 599
 600	oldzone = folio_zone(folio);
 601	newzone = folio_zone(newfolio);
 602
 603	if (folio_test_swapcache(folio))
 604		ci = swap_cluster_get_and_lock_irq(folio);
 605	else
 606		xas_lock_irq(&xas);
 607
 608	if (!folio_ref_freeze(folio, expected_count)) {
 609		if (ci)
 610			swap_cluster_unlock_irq(ci);
 611		else
 612			xas_unlock_irq(&xas);
 613		return -EAGAIN;
 614	}
 615
 616	/* Take off deferred split queue while frozen and memcg set */
 617	folio_unqueue_deferred_split(folio);
 618
 619	/*
 620	 * Now we know that no one else is looking at the folio:
 621	 * no turning back from here.
 622	 */
 623	newfolio->index = folio->index;
 624	newfolio->mapping = folio->mapping;
 625	if (folio_test_anon(folio) && folio_test_large(folio))
 626		mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
 627	folio_ref_add(newfolio, nr); /* add cache reference */
 628	if (folio_test_swapbacked(folio))
 629		__folio_set_swapbacked(newfolio);
 630	if (folio_test_swapcache(folio)) {
 631		folio_set_swapcache(newfolio);
 632		newfolio->private = folio_get_private(folio);
 633	}
 634
 635	/* Move dirty while folio refs frozen and newfolio not yet exposed */
 636	dirty = folio_test_dirty(folio);
 637	if (dirty) {
 638		folio_clear_dirty(folio);
 639		folio_set_dirty(newfolio);
 640	}
 641
 642	if (folio_test_swapcache(folio))
 643		__swap_cache_replace_folio(ci, folio, newfolio);
 644	else
 645		xas_store(&xas, newfolio);
 646
 647	/*
 648	 * Drop cache reference from old folio by unfreezing
 649	 * to one less reference.
 650	 * We know this isn't the last reference.
 651	 */
 652	folio_ref_unfreeze(folio, expected_count - nr);
 653
 654	/* Leave irq disabled to prevent preemption while updating stats */
 655	if (ci)
 656		swap_cluster_unlock(ci);
 657	else
 658		xas_unlock(&xas);
 659
 660	/*
 661	 * If moved to a different zone then also account
 662	 * the folio for that zone. Other VM counters will be
 663	 * taken care of when we establish references to the
 664	 * new folio and drop references to the old folio.
 665	 *
 666	 * Note that anonymous folios are accounted for
 667	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
 668	 * are mapped to swap space.
 669	 */
 670	if (newzone != oldzone) {
 671		struct lruvec *old_lruvec, *new_lruvec;
 672		struct mem_cgroup *memcg;
 673
 674		memcg = folio_memcg(folio);
 675		old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
 676		new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
 677
 678		mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
 679		mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
 680		if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
 681			mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
 682			mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
 683
 684			if (folio_test_pmd_mappable(folio)) {
 685				mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr);
 686				mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr);
 687			}
 688		}
 689#ifdef CONFIG_SWAP
 690		if (folio_test_swapcache(folio)) {
 691			mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
 692			mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
 693		}
 694#endif
 695		if (dirty && mapping_can_writeback(mapping)) {
 696			mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
 697			__mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
 698			mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
 699			__mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
 700		}
 701	}
 702	local_irq_enable();
 703
 704	return 0;
 705}
 706
 707int folio_migrate_mapping(struct address_space *mapping,
 708		struct folio *newfolio, struct folio *folio, int extra_count)
 709{
 710	int expected_count = folio_expected_ref_count(folio) + extra_count + 1;
 711
 712	if (folio_ref_count(folio) != expected_count)
 713		return -EAGAIN;
 714
 715	return __folio_migrate_mapping(mapping, newfolio, folio, expected_count);
 716}
 717EXPORT_SYMBOL(folio_migrate_mapping);
 718
 719/*
 720 * The expected number of remaining references is the same as that
 721 * of folio_migrate_mapping().
 722 */
 723int migrate_huge_page_move_mapping(struct address_space *mapping,
 724				   struct folio *dst, struct folio *src)
 725{
 726	XA_STATE(xas, &mapping->i_pages, src->index);
 727	int rc, expected_count = folio_expected_ref_count(src) + 1;
 728
 729	if (folio_ref_count(src) != expected_count)
 730		return -EAGAIN;
 731
 732	rc = folio_mc_copy(dst, src);
 733	if (unlikely(rc))
 734		return rc;
 735
 736	xas_lock_irq(&xas);
 737	if (!folio_ref_freeze(src, expected_count)) {
 738		xas_unlock_irq(&xas);
 739		return -EAGAIN;
 740	}
 741
 742	dst->index = src->index;
 743	dst->mapping = src->mapping;
 744
 745	folio_ref_add(dst, folio_nr_pages(dst));
 746
 747	xas_store(&xas, dst);
 748
 749	folio_ref_unfreeze(src, expected_count - folio_nr_pages(src));
 750
 751	xas_unlock_irq(&xas);
 752
 753	return 0;
 754}
 755
 756/*
 757 * Copy the flags and some other ancillary information
 758 */
 759void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
 760{
 761	int cpupid;
 762
 763	if (folio_test_referenced(folio))
 764		folio_set_referenced(newfolio);
 765	if (folio_test_uptodate(folio))
 766		folio_mark_uptodate(newfolio);
 767	if (folio_test_clear_active(folio)) {
 768		VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
 769		folio_set_active(newfolio);
 770	} else if (folio_test_clear_unevictable(folio))
 771		folio_set_unevictable(newfolio);
 772	if (folio_test_workingset(folio))
 773		folio_set_workingset(newfolio);
 774	if (folio_test_checked(folio))
 775		folio_set_checked(newfolio);
 776	/*
 777	 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
 778	 * migration entries. We can still have PG_anon_exclusive set on an
 779	 * effectively unmapped and unreferenced first sub-pages of an
 780	 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
 781	 */
 782	if (folio_test_mappedtodisk(folio))
 783		folio_set_mappedtodisk(newfolio);
 784
 785	/* Move dirty on pages not done by folio_migrate_mapping() */
 786	if (folio_test_dirty(folio))
 787		folio_set_dirty(newfolio);
 788
 789	if (folio_test_young(folio))
 790		folio_set_young(newfolio);
 791	if (folio_test_idle(folio))
 792		folio_set_idle(newfolio);
 793
 794	folio_migrate_refs(newfolio, folio);
 795	/*
 796	 * Copy NUMA information to the new page, to prevent over-eager
 797	 * future migrations of this same page.
 798	 */
 799	cpupid = folio_xchg_last_cpupid(folio, -1);
 800	/*
 801	 * For memory tiering mode, when migrate between slow and fast
 802	 * memory node, reset cpupid, because that is used to record
 803	 * page access time in slow memory node.
 804	 */
 805	if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
 806		bool f_toptier = node_is_toptier(folio_nid(folio));
 807		bool t_toptier = node_is_toptier(folio_nid(newfolio));
 808
 809		if (f_toptier != t_toptier)
 810			cpupid = -1;
 811	}
 812	folio_xchg_last_cpupid(newfolio, cpupid);
 813
 814	folio_migrate_ksm(newfolio, folio);
 815	/*
 816	 * Please do not reorder this without considering how mm/ksm.c's
 817	 * ksm_get_folio() depends upon ksm_migrate_page() and the
 818	 * swapcache flag.
 819	 */
 820	if (folio_test_swapcache(folio))
 821		folio_clear_swapcache(folio);
 822	folio_clear_private(folio);
 823
 824	/* page->private contains hugetlb specific flags */
 825	if (!folio_test_hugetlb(folio))
 826		folio->private = NULL;
 827
 828	/*
 829	 * If any waiters have accumulated on the new page then
 830	 * wake them up.
 831	 */
 832	if (folio_test_writeback(newfolio))
 833		folio_end_writeback(newfolio);
 834
 835	/*
 836	 * PG_readahead shares the same bit with PG_reclaim.  The above
 837	 * end_page_writeback() may clear PG_readahead mistakenly, so set the
 838	 * bit after that.
 839	 */
 840	if (folio_test_readahead(folio))
 841		folio_set_readahead(newfolio);
 842
 843	folio_copy_owner(newfolio, folio);
 844	pgalloc_tag_swap(newfolio, folio);
 845
 846	mem_cgroup_migrate(folio, newfolio);
 847}
 848EXPORT_SYMBOL(folio_migrate_flags);
 849
 850/************************************************************
 851 *                    Migration functions
 852 ***********************************************************/
 853
 854static int __migrate_folio(struct address_space *mapping, struct folio *dst,
 855			   struct folio *src, void *src_private,
 856			   enum migrate_mode mode)
 857{
 858	int rc, expected_count = folio_expected_ref_count(src) + 1;
 859
 860	/* Check whether src does not have extra refs before we do more work */
 861	if (folio_ref_count(src) != expected_count)
 862		return -EAGAIN;
 863
 864	rc = folio_mc_copy(dst, src);
 865	if (unlikely(rc))
 866		return rc;
 867
 868	rc = __folio_migrate_mapping(mapping, dst, src, expected_count);
 869	if (rc)
 870		return rc;
 871
 872	if (src_private)
 873		folio_attach_private(dst, folio_detach_private(src));
 874
 875	folio_migrate_flags(dst, src);
 876	return 0;
 877}
 878
 879/**
 880 * migrate_folio() - Simple folio migration.
 881 * @mapping: The address_space containing the folio.
 882 * @dst: The folio to migrate the data to.
 883 * @src: The folio containing the current data.
 884 * @mode: How to migrate the page.
 885 *
 886 * Common logic to directly migrate a single LRU folio suitable for
 887 * folios that do not have private data.
 888 *
 889 * Folios are locked upon entry and exit.
 890 */
 891int migrate_folio(struct address_space *mapping, struct folio *dst,
 892		  struct folio *src, enum migrate_mode mode)
 893{
 894	BUG_ON(folio_test_writeback(src));	/* Writeback must be complete */
 895	return __migrate_folio(mapping, dst, src, NULL, mode);
 896}
 897EXPORT_SYMBOL(migrate_folio);
 898
 899#ifdef CONFIG_BUFFER_HEAD
 900/* Returns true if all buffers are successfully locked */
 901static bool buffer_migrate_lock_buffers(struct buffer_head *head,
 902							enum migrate_mode mode)
 903{
 904	struct buffer_head *bh = head;
 905	struct buffer_head *failed_bh;
 906
 907	do {
 908		if (!trylock_buffer(bh)) {
 909			if (mode == MIGRATE_ASYNC)
 910				goto unlock;
 911			if (mode == MIGRATE_SYNC_LIGHT && !buffer_uptodate(bh))
 912				goto unlock;
 913			lock_buffer(bh);
 914		}
 915
 916		bh = bh->b_this_page;
 917	} while (bh != head);
 918
 919	return true;
 920
 921unlock:
 922	/* We failed to lock the buffer and cannot stall. */
 923	failed_bh = bh;
 924	bh = head;
 925	while (bh != failed_bh) {
 926		unlock_buffer(bh);
 927		bh = bh->b_this_page;
 928	}
 929
 930	return false;
 931}
 932
 933static int __buffer_migrate_folio(struct address_space *mapping,
 934		struct folio *dst, struct folio *src, enum migrate_mode mode,
 935		bool check_refs)
 936{
 937	struct buffer_head *bh, *head;
 938	int rc;
 939	int expected_count;
 940
 941	head = folio_buffers(src);
 942	if (!head)
 943		return migrate_folio(mapping, dst, src, mode);
 944
 945	/* Check whether page does not have extra refs before we do more work */
 946	expected_count = folio_expected_ref_count(src) + 1;
 947	if (folio_ref_count(src) != expected_count)
 948		return -EAGAIN;
 949
 950	if (!buffer_migrate_lock_buffers(head, mode))
 951		return -EAGAIN;
 952
 953	if (check_refs) {
 954		bool busy, migrating;
 955		bool invalidated = false;
 956
 957		migrating = test_and_set_bit_lock(BH_Migrate, &head->b_state);
 958		VM_WARN_ON_ONCE(migrating);
 959recheck_buffers:
 960		busy = false;
 961		spin_lock(&mapping->i_private_lock);
 962		bh = head;
 963		do {
 964			if (atomic_read(&bh->b_count)) {
 965				busy = true;
 966				break;
 967			}
 968			bh = bh->b_this_page;
 969		} while (bh != head);
 970		spin_unlock(&mapping->i_private_lock);
 971		if (busy) {
 972			if (invalidated) {
 973				rc = -EAGAIN;
 974				goto unlock_buffers;
 975			}
 976			invalidate_bh_lrus();
 977			invalidated = true;
 978			goto recheck_buffers;
 979		}
 980	}
 981
 982	rc = filemap_migrate_folio(mapping, dst, src, mode);
 983	if (rc)
 984		goto unlock_buffers;
 985
 986	bh = head;
 987	do {
 988		folio_set_bh(bh, dst, bh_offset(bh));
 989		bh = bh->b_this_page;
 990	} while (bh != head);
 991
 992unlock_buffers:
 993	if (check_refs)
 994		clear_bit_unlock(BH_Migrate, &head->b_state);
 995	bh = head;
 996	do {
 997		unlock_buffer(bh);
 998		bh = bh->b_this_page;
 999	} while (bh != head);
1000
1001	return rc;
1002}
1003
1004/**
1005 * buffer_migrate_folio() - Migration function for folios with buffers.
1006 * @mapping: The address space containing @src.
1007 * @dst: The folio to migrate to.
1008 * @src: The folio to migrate from.
1009 * @mode: How to migrate the folio.
1010 *
1011 * This function can only be used if the underlying filesystem guarantees
1012 * that no other references to @src exist. For example attached buffer
1013 * heads are accessed only under the folio lock.  If your filesystem cannot
1014 * provide this guarantee, buffer_migrate_folio_norefs() may be more
1015 * appropriate.
1016 *
1017 * Return: 0 on success or a negative errno on failure.
1018 */
1019int buffer_migrate_folio(struct address_space *mapping,
1020		struct folio *dst, struct folio *src, enum migrate_mode mode)
1021{
1022	return __buffer_migrate_folio(mapping, dst, src, mode, false);
1023}
1024EXPORT_SYMBOL(buffer_migrate_folio);
1025
1026/**
1027 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
1028 * @mapping: The address space containing @src.
1029 * @dst: The folio to migrate to.
1030 * @src: The folio to migrate from.
1031 * @mode: How to migrate the folio.
1032 *
1033 * Like buffer_migrate_folio() except that this variant is more careful
1034 * and checks that there are also no buffer head references. This function
1035 * is the right one for mappings where buffer heads are directly looked
1036 * up and referenced (such as block device mappings).
1037 *
1038 * Return: 0 on success or a negative errno on failure.
1039 */
1040int buffer_migrate_folio_norefs(struct address_space *mapping,
1041		struct folio *dst, struct folio *src, enum migrate_mode mode)
1042{
1043	return __buffer_migrate_folio(mapping, dst, src, mode, true);
1044}
1045EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
1046#endif /* CONFIG_BUFFER_HEAD */
1047
1048int filemap_migrate_folio(struct address_space *mapping,
1049		struct folio *dst, struct folio *src, enum migrate_mode mode)
1050{
1051	return __migrate_folio(mapping, dst, src, folio_get_private(src), mode);
1052}
1053EXPORT_SYMBOL_GPL(filemap_migrate_folio);
1054
1055/*
1056 * Default handling if a filesystem does not provide a migration function.
1057 */
1058static int fallback_migrate_folio(struct address_space *mapping,
1059		struct folio *dst, struct folio *src, enum migrate_mode mode)
1060{
1061	WARN_ONCE(mapping->a_ops->writepages,
1062			"%ps does not implement migrate_folio\n",
1063			mapping->a_ops);
1064	if (folio_test_dirty(src))
1065		return -EBUSY;
1066
1067	/*
1068	 * Filesystem may have private data at folio->private that we
1069	 * can't migrate automatically.
1070	 */
1071	if (!filemap_release_folio(src, GFP_KERNEL))
1072		return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
1073
1074	return migrate_folio(mapping, dst, src, mode);
1075}
1076
1077/*
1078 * Move a src folio to a newly allocated dst folio.
1079 *
1080 * The src and dst folios are locked and the src folios was unmapped from
1081 * the page tables.
1082 *
1083 * On success, the src folio was replaced by the dst folio.
1084 *
1085 * Return value:
1086 *   < 0 - error code
1087 *     0 - success
1088 */
1089static int move_to_new_folio(struct folio *dst, struct folio *src,
1090				enum migrate_mode mode)
1091{
1092	struct address_space *mapping = folio_mapping(src);
1093	int rc = -EAGAIN;
1094
1095	VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
1096	VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
1097
1098	if (!mapping)
1099		rc = migrate_folio(mapping, dst, src, mode);
1100	else if (mapping_inaccessible(mapping))
1101		rc = -EOPNOTSUPP;
1102	else if (mapping->a_ops->migrate_folio)
1103		/*
1104		 * Most folios have a mapping and most filesystems
1105		 * provide a migrate_folio callback. Anonymous folios
1106		 * are part of swap space which also has its own
1107		 * migrate_folio callback. This is the most common path
1108		 * for page migration.
1109		 */
1110		rc = mapping->a_ops->migrate_folio(mapping, dst, src,
1111							mode);
1112	else
1113		rc = fallback_migrate_folio(mapping, dst, src, mode);
1114
1115	if (!rc) {
1116		/*
1117		 * For pagecache folios, src->mapping must be cleared before src
1118		 * is freed. Anonymous folios must stay anonymous until freed.
1119		 */
1120		if (!folio_test_anon(src))
1121			src->mapping = NULL;
1122
1123		if (likely(!folio_is_zone_device(dst)))
1124			flush_dcache_folio(dst);
1125	}
1126	return rc;
1127}
1128
1129/*
1130 * To record some information during migration, we use unused private
1131 * field of struct folio of the newly allocated destination folio.
1132 * This is safe because nobody is using it except us.
1133 */
1134enum {
1135	PAGE_WAS_MAPPED = BIT(0),
1136	PAGE_WAS_MLOCKED = BIT(1),
1137	PAGE_OLD_STATES = PAGE_WAS_MAPPED | PAGE_WAS_MLOCKED,
1138};
1139
1140static void __migrate_folio_record(struct folio *dst,
1141				   int old_page_state,
1142				   struct anon_vma *anon_vma)
1143{
1144	dst->private = (void *)anon_vma + old_page_state;
1145}
1146
1147static void __migrate_folio_extract(struct folio *dst,
1148				   int *old_page_state,
1149				   struct anon_vma **anon_vmap)
1150{
1151	unsigned long private = (unsigned long)dst->private;
1152
1153	*anon_vmap = (struct anon_vma *)(private & ~PAGE_OLD_STATES);
1154	*old_page_state = private & PAGE_OLD_STATES;
1155	dst->private = NULL;
1156}
1157
1158/* Restore the source folio to the original state upon failure */
1159static void migrate_folio_undo_src(struct folio *src,
1160				   int page_was_mapped,
1161				   struct anon_vma *anon_vma,
1162				   bool locked,
1163				   struct list_head *ret)
1164{
1165	if (page_was_mapped)
1166		remove_migration_ptes(src, src, 0);
1167	/* Drop an anon_vma reference if we took one */
1168	if (anon_vma)
1169		put_anon_vma(anon_vma);
1170	if (locked)
1171		folio_unlock(src);
1172	if (ret)
1173		list_move_tail(&src->lru, ret);
1174}
1175
1176/* Restore the destination folio to the original state upon failure */
1177static void migrate_folio_undo_dst(struct folio *dst, bool locked,
1178		free_folio_t put_new_folio, unsigned long private)
1179{
1180	if (locked)
1181		folio_unlock(dst);
1182	if (put_new_folio)
1183		put_new_folio(dst, private);
1184	else
1185		folio_put(dst);
1186}
1187
1188/* Cleanup src folio upon migration success */
1189static void migrate_folio_done(struct folio *src,
1190			       enum migrate_reason reason)
1191{
1192	if (likely(!page_has_movable_ops(&src->page)) && reason != MR_DEMOTION)
1193		mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
1194				    folio_is_file_lru(src), -folio_nr_pages(src));
1195
1196	if (reason != MR_MEMORY_FAILURE)
1197		/* We release the page in page_handle_poison. */
1198		folio_put(src);
1199}
1200
1201/* Obtain the lock on page, remove all ptes. */
1202static int migrate_folio_unmap(new_folio_t get_new_folio,
1203		free_folio_t put_new_folio, unsigned long private,
1204		struct folio *src, struct folio **dstp, enum migrate_mode mode,
1205		struct list_head *ret)
1206{
1207	struct folio *dst;
1208	int rc = -EAGAIN;
1209	int old_page_state = 0;
1210	struct anon_vma *anon_vma = NULL;
1211	bool locked = false;
1212	bool dst_locked = false;
1213
1214	dst = get_new_folio(src, private);
1215	if (!dst)
1216		return -ENOMEM;
1217	*dstp = dst;
1218
1219	dst->private = NULL;
1220
1221	if (!folio_trylock(src)) {
1222		if (mode == MIGRATE_ASYNC)
1223			goto out;
1224
1225		/*
1226		 * It's not safe for direct compaction to call lock_page.
1227		 * For example, during page readahead pages are added locked
1228		 * to the LRU. Later, when the IO completes the pages are
1229		 * marked uptodate and unlocked. However, the queueing
1230		 * could be merging multiple pages for one bio (e.g.
1231		 * mpage_readahead). If an allocation happens for the
1232		 * second or third page, the process can end up locking
1233		 * the same page twice and deadlocking. Rather than
1234		 * trying to be clever about what pages can be locked,
1235		 * avoid the use of lock_page for direct compaction
1236		 * altogether.
1237		 */
1238		if (current->flags & PF_MEMALLOC)
1239			goto out;
1240
1241		/*
1242		 * In "light" mode, we can wait for transient locks (eg
1243		 * inserting a page into the page table), but it's not
1244		 * worth waiting for I/O.
1245		 */
1246		if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
1247			goto out;
1248
1249		folio_lock(src);
1250	}
1251	locked = true;
1252	if (folio_test_mlocked(src))
1253		old_page_state |= PAGE_WAS_MLOCKED;
1254
1255	if (folio_test_writeback(src)) {
1256		/*
1257		 * Only in the case of a full synchronous migration is it
1258		 * necessary to wait for PageWriteback. In the async case,
1259		 * the retry loop is too short and in the sync-light case,
1260		 * the overhead of stalling is too much
1261		 */
1262		switch (mode) {
1263		case MIGRATE_SYNC:
1264			break;
1265		default:
1266			rc = -EBUSY;
1267			goto out;
1268		}
1269		folio_wait_writeback(src);
1270	}
1271
1272	/*
1273	 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1274	 * we cannot notice that anon_vma is freed while we migrate a page.
1275	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1276	 * of migration. File cache pages are no problem because of page_lock()
1277	 * File Caches may use write_page() or lock_page() in migration, then,
1278	 * just care Anon page here.
1279	 *
1280	 * Only folio_get_anon_vma() understands the subtleties of
1281	 * getting a hold on an anon_vma from outside one of its mms.
1282	 * But if we cannot get anon_vma, then we won't need it anyway,
1283	 * because that implies that the anon page is no longer mapped
1284	 * (and cannot be remapped so long as we hold the page lock).
1285	 */
1286	if (folio_test_anon(src) && !folio_test_ksm(src))
1287		anon_vma = folio_get_anon_vma(src);
1288
1289	/*
1290	 * Block others from accessing the new page when we get around to
1291	 * establishing additional references. We are usually the only one
1292	 * holding a reference to dst at this point. We used to have a BUG
1293	 * here if folio_trylock(dst) fails, but would like to allow for
1294	 * cases where there might be a race with the previous use of dst.
1295	 * This is much like races on refcount of oldpage: just don't BUG().
1296	 */
1297	if (unlikely(!folio_trylock(dst)))
1298		goto out;
1299	dst_locked = true;
1300
1301	if (unlikely(page_has_movable_ops(&src->page))) {
1302		__migrate_folio_record(dst, old_page_state, anon_vma);
1303		return 0;
1304	}
1305
1306	/*
1307	 * Corner case handling:
1308	 * 1. When a new swap-cache page is read into, it is added to the LRU
1309	 * and treated as swapcache but it has no rmap yet.
1310	 * Calling try_to_unmap() against a src->mapping==NULL page will
1311	 * trigger a BUG.  So handle it here.
1312	 * 2. An orphaned page (see truncate_cleanup_page) might have
1313	 * fs-private metadata. The page can be picked up due to memory
1314	 * offlining.  Everywhere else except page reclaim, the page is
1315	 * invisible to the vm, so the page can not be migrated.  So try to
1316	 * free the metadata, so the page can be freed.
1317	 */
1318	if (!src->mapping) {
1319		if (folio_test_private(src)) {
1320			try_to_free_buffers(src);
1321			goto out;
1322		}
1323	} else if (folio_mapped(src)) {
1324		/* Establish migration ptes */
1325		VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1326			       !folio_test_ksm(src) && !anon_vma, src);
1327		try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
1328		old_page_state |= PAGE_WAS_MAPPED;
1329	}
1330
1331	if (!folio_mapped(src)) {
1332		__migrate_folio_record(dst, old_page_state, anon_vma);
1333		return 0;
1334	}
1335
1336out:
1337	/*
1338	 * A folio that has not been unmapped will be restored to
1339	 * right list unless we want to retry.
1340	 */
1341	if (rc == -EAGAIN)
1342		ret = NULL;
1343
1344	migrate_folio_undo_src(src, old_page_state & PAGE_WAS_MAPPED,
1345			       anon_vma, locked, ret);
1346	migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
1347
1348	return rc;
1349}
1350
1351/* Migrate the folio to the newly allocated folio in dst. */
1352static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
1353			      struct folio *src, struct folio *dst,
1354			      enum migrate_mode mode, enum migrate_reason reason,
1355			      struct list_head *ret)
1356{
1357	int rc;
1358	int old_page_state = 0;
1359	struct anon_vma *anon_vma = NULL;
1360	struct list_head *prev;
1361
1362	__migrate_folio_extract(dst, &old_page_state, &anon_vma);
1363	prev = dst->lru.prev;
1364	list_del(&dst->lru);
1365
1366	if (unlikely(page_has_movable_ops(&src->page))) {
1367		rc = migrate_movable_ops_page(&dst->page, &src->page, mode);
1368		if (rc)
1369			goto out;
1370		goto out_unlock_both;
1371	}
1372
1373	rc = move_to_new_folio(dst, src, mode);
1374	if (rc)
1375		goto out;
1376
1377	/*
1378	 * When successful, push dst to LRU immediately: so that if it
1379	 * turns out to be an mlocked page, remove_migration_ptes() will
1380	 * automatically build up the correct dst->mlock_count for it.
1381	 *
1382	 * We would like to do something similar for the old page, when
1383	 * unsuccessful, and other cases when a page has been temporarily
1384	 * isolated from the unevictable LRU: but this case is the easiest.
1385	 */
1386	folio_add_lru(dst);
1387	if (old_page_state & PAGE_WAS_MLOCKED)
1388		lru_add_drain();
1389
1390	if (old_page_state & PAGE_WAS_MAPPED)
1391		remove_migration_ptes(src, dst, 0);
1392
1393out_unlock_both:
1394	folio_unlock(dst);
1395	folio_set_owner_migrate_reason(dst, reason);
1396	/*
1397	 * If migration is successful, decrease refcount of dst,
1398	 * which will not free the page because new page owner increased
1399	 * refcounter.
1400	 */
1401	folio_put(dst);
1402
1403	/*
1404	 * A folio that has been migrated has all references removed
1405	 * and will be freed.
1406	 */
1407	list_del(&src->lru);
1408	/* Drop an anon_vma reference if we took one */
1409	if (anon_vma)
1410		put_anon_vma(anon_vma);
1411	folio_unlock(src);
1412	migrate_folio_done(src, reason);
1413
1414	return rc;
1415out:
1416	/*
1417	 * A folio that has not been migrated will be restored to
1418	 * right list unless we want to retry.
1419	 */
1420	if (rc == -EAGAIN) {
1421		list_add(&dst->lru, prev);
1422		__migrate_folio_record(dst, old_page_state, anon_vma);
1423		return rc;
1424	}
1425
1426	migrate_folio_undo_src(src, old_page_state & PAGE_WAS_MAPPED,
1427			       anon_vma, true, ret);
1428	migrate_folio_undo_dst(dst, true, put_new_folio, private);
1429
1430	return rc;
1431}
1432
1433/*
1434 * Counterpart of unmap_and_move_page() for hugepage migration.
1435 *
1436 * This function doesn't wait the completion of hugepage I/O
1437 * because there is no race between I/O and migration for hugepage.
1438 * Note that currently hugepage I/O occurs only in direct I/O
1439 * where no lock is held and PG_writeback is irrelevant,
1440 * and writeback status of all subpages are counted in the reference
1441 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1442 * under direct I/O, the reference of the head page is 512 and a bit more.)
1443 * This means that when we try to migrate hugepage whose subpages are
1444 * doing direct I/O, some references remain after try_to_unmap() and
1445 * hugepage migration fails without data corruption.
1446 *
1447 * There is also no race when direct I/O is issued on the page under migration,
1448 * because then pte is replaced with migration swap entry and direct I/O code
1449 * will wait in the page fault for migration to complete.
1450 */
1451static int unmap_and_move_huge_page(new_folio_t get_new_folio,
1452		free_folio_t put_new_folio, unsigned long private,
1453		struct folio *src, int force, enum migrate_mode mode,
1454		int reason, struct list_head *ret)
1455{
1456	struct folio *dst;
1457	int rc = -EAGAIN;
1458	int page_was_mapped = 0;
1459	struct anon_vma *anon_vma = NULL;
1460	struct address_space *mapping = NULL;
1461	enum ttu_flags ttu = 0;
1462
1463	if (folio_ref_count(src) == 1) {
1464		/* page was freed from under us. So we are done. */
1465		folio_putback_hugetlb(src);
1466		return 0;
1467	}
1468
1469	dst = get_new_folio(src, private);
1470	if (!dst)
1471		return -ENOMEM;
1472
1473	if (!folio_trylock(src)) {
1474		if (!force)
1475			goto out;
1476		switch (mode) {
1477		case MIGRATE_SYNC:
1478			break;
1479		default:
1480			goto out;
1481		}
1482		folio_lock(src);
1483	}
1484
1485	/*
1486	 * Check for pages which are in the process of being freed.  Without
1487	 * folio_mapping() set, hugetlbfs specific move page routine will not
1488	 * be called and we could leak usage counts for subpools.
1489	 */
1490	if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1491		rc = -EBUSY;
1492		goto out_unlock;
1493	}
1494
1495	if (folio_test_anon(src))
1496		anon_vma = folio_get_anon_vma(src);
1497
1498	if (unlikely(!folio_trylock(dst)))
1499		goto put_anon;
1500
1501	if (folio_mapped(src)) {
1502		if (!folio_test_anon(src)) {
1503			/*
1504			 * In shared mappings, try_to_unmap could potentially
1505			 * call huge_pmd_unshare.  Because of this, take
1506			 * semaphore in write mode here and set TTU_RMAP_LOCKED
1507			 * to let lower levels know we have taken the lock.
1508			 */
1509			mapping = hugetlb_folio_mapping_lock_write(src);
1510			if (unlikely(!mapping))
1511				goto unlock_put_anon;
1512
1513			ttu = TTU_RMAP_LOCKED;
1514		}
1515
1516		try_to_migrate(src, ttu);
1517		page_was_mapped = 1;
1518	}
1519
1520	if (!folio_mapped(src))
1521		rc = move_to_new_folio(dst, src, mode);
1522
1523	if (page_was_mapped)
1524		remove_migration_ptes(src, !rc ? dst : src,
1525				ttu ? RMP_LOCKED : 0);
1526
1527	if (ttu & TTU_RMAP_LOCKED)
1528		i_mmap_unlock_write(mapping);
1529
1530unlock_put_anon:
1531	folio_unlock(dst);
1532
1533put_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
1542out_unlock:
1543	folio_unlock(src);
1544out:
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
1563static 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
1592struct 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 */
1610static 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
1699static 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
1751static 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 */
1783static 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;
1966move:
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;
1987out:
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
1995static 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 */
2072int 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
2093again:
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;
2139out:
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
2169struct 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
2210static 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
2221static 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
2237static 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 */
2274static 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
2301static 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 */
2331static 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	}
2416out_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;
2422out:
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 */
2430static 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		}
2460set_status:
2461		*status = err;
2462
2463		pages++;
2464		status++;
2465	}
2466
2467	mmap_read_unlock(mm);
2468}
2469
2470static 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 */
2492static 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
2526static 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);
2560out:
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 */
2571static 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
2601SYSCALL_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 */
2614static 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
2636static 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 */
2657int 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 */
2722int 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 */
~/ Read-only file preview.