xref: /linux/mm/migrate.c (revision fc346d0a70a13d52fe1c4bc49516d83a42cd7c4c)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2b20a3503SChristoph Lameter /*
314e0f9bcSHugh Dickins  * Memory Migration functionality - linux/mm/migrate.c
4b20a3503SChristoph Lameter  *
5b20a3503SChristoph Lameter  * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
6b20a3503SChristoph Lameter  *
7b20a3503SChristoph Lameter  * Page migration was first developed in the context of the memory hotplug
8b20a3503SChristoph Lameter  * project. The main authors of the migration code are:
9b20a3503SChristoph Lameter  *
10b20a3503SChristoph Lameter  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
11b20a3503SChristoph Lameter  * Hirokazu Takahashi <taka@valinux.co.jp>
12b20a3503SChristoph Lameter  * Dave Hansen <haveblue@us.ibm.com>
13cde53535SChristoph Lameter  * Christoph Lameter
14b20a3503SChristoph Lameter  */
15b20a3503SChristoph Lameter 
16b20a3503SChristoph Lameter #include <linux/migrate.h>
17b95f1b31SPaul Gortmaker #include <linux/export.h>
18b20a3503SChristoph Lameter #include <linux/swap.h>
190697212aSChristoph Lameter #include <linux/swapops.h>
20b20a3503SChristoph Lameter #include <linux/pagemap.h>
21e23ca00bSChristoph Lameter #include <linux/buffer_head.h>
22b20a3503SChristoph Lameter #include <linux/mm_inline.h>
23b488893aSPavel Emelyanov #include <linux/nsproxy.h>
24e9995ef9SHugh Dickins #include <linux/ksm.h>
25b20a3503SChristoph Lameter #include <linux/rmap.h>
26b20a3503SChristoph Lameter #include <linux/topology.h>
27b20a3503SChristoph Lameter #include <linux/cpu.h>
28b20a3503SChristoph Lameter #include <linux/cpuset.h>
2904e62a29SChristoph Lameter #include <linux/writeback.h>
30742755a1SChristoph Lameter #include <linux/mempolicy.h>
31742755a1SChristoph Lameter #include <linux/vmalloc.h>
3286c3a764SDavid Quigley #include <linux/security.h>
3342cb14b1SHugh Dickins #include <linux/backing-dev.h>
34bda807d4SMinchan Kim #include <linux/compaction.h>
354f5ca265SAdrian Bunk #include <linux/syscalls.h>
367addf443SDominik Brodowski #include <linux/compat.h>
37290408d4SNaoya Horiguchi #include <linux/hugetlb.h>
388e6ac7faSAneesh Kumar K.V #include <linux/hugetlb_cgroup.h>
395a0e3ad6STejun Heo #include <linux/gfp.h>
40df6ad698SJérôme Glisse #include <linux/pfn_t.h>
41a5430ddaSJérôme Glisse #include <linux/memremap.h>
428315ada7SJérôme Glisse #include <linux/userfaultfd_k.h>
43bf6bddf1SRafael Aquini #include <linux/balloon_compaction.h>
4433c3fc71SVladimir Davydov #include <linux/page_idle.h>
45d435edcaSVlastimil Babka #include <linux/page_owner.h>
466e84f315SIngo Molnar #include <linux/sched/mm.h>
47197e7e52SLinus Torvalds #include <linux/ptrace.h>
4834290e2cSRalph Campbell #include <linux/oom.h>
49884a6e5dSDave Hansen #include <linux/memory.h>
50ac16ec83SBaolin Wang #include <linux/random.h>
51c574bbe9SHuang Ying #include <linux/sched/sysctl.h>
52467b171aSAneesh Kumar K.V #include <linux/memory-tiers.h>
53b20a3503SChristoph Lameter 
540d1836c3SMichal Nazarewicz #include <asm/tlbflush.h>
550d1836c3SMichal Nazarewicz 
567b2a2d4aSMel Gorman #include <trace/events/migrate.h>
577b2a2d4aSMel Gorman 
58b20a3503SChristoph Lameter #include "internal.h"
59b20a3503SChristoph Lameter 
60cd775580SBaolin Wang bool isolate_movable_page(struct page *page, isolate_mode_t mode)
61bda807d4SMinchan Kim {
6219979497SVishal Moola (Oracle) 	struct folio *folio = folio_get_nontail_page(page);
6368f2736aSMatthew Wilcox (Oracle) 	const struct movable_operations *mops;
64bda807d4SMinchan Kim 
65bda807d4SMinchan Kim 	/*
66bda807d4SMinchan Kim 	 * Avoid burning cycles with pages that are yet under __free_pages(),
67bda807d4SMinchan Kim 	 * or just got freed under us.
68bda807d4SMinchan Kim 	 *
69bda807d4SMinchan Kim 	 * In case we 'win' a race for a movable page being freed under us and
70bda807d4SMinchan Kim 	 * raise its refcount preventing __free_pages() from doing its job
71bda807d4SMinchan Kim 	 * the put_page() at the end of this block will take care of
72bda807d4SMinchan Kim 	 * release this page, thus avoiding a nasty leakage.
73bda807d4SMinchan Kim 	 */
7419979497SVishal Moola (Oracle) 	if (!folio)
75bda807d4SMinchan Kim 		goto out;
76bda807d4SMinchan Kim 
7719979497SVishal Moola (Oracle) 	if (unlikely(folio_test_slab(folio)))
7819979497SVishal Moola (Oracle) 		goto out_putfolio;
798b881763SVlastimil Babka 	/* Pairs with smp_wmb() in slab freeing, e.g. SLUB's __free_slab() */
808b881763SVlastimil Babka 	smp_rmb();
81bda807d4SMinchan Kim 	/*
828b881763SVlastimil Babka 	 * Check movable flag before taking the page lock because
838b881763SVlastimil Babka 	 * we use non-atomic bitops on newly allocated page flags so
848b881763SVlastimil Babka 	 * unconditionally grabbing the lock ruins page's owner side.
85bda807d4SMinchan Kim 	 */
8619979497SVishal Moola (Oracle) 	if (unlikely(!__folio_test_movable(folio)))
8719979497SVishal Moola (Oracle) 		goto out_putfolio;
888b881763SVlastimil Babka 	/* Pairs with smp_wmb() in slab allocation, e.g. SLUB's alloc_slab_page() */
898b881763SVlastimil Babka 	smp_rmb();
9019979497SVishal Moola (Oracle) 	if (unlikely(folio_test_slab(folio)))
9119979497SVishal Moola (Oracle) 		goto out_putfolio;
928b881763SVlastimil Babka 
93bda807d4SMinchan Kim 	/*
94bda807d4SMinchan Kim 	 * As movable pages are not isolated from LRU lists, concurrent
95bda807d4SMinchan Kim 	 * compaction threads can race against page migration functions
96bda807d4SMinchan Kim 	 * as well as race against the releasing a page.
97bda807d4SMinchan Kim 	 *
98bda807d4SMinchan Kim 	 * In order to avoid having an already isolated movable page
99bda807d4SMinchan Kim 	 * being (wrongly) re-isolated while it is under migration,
100bda807d4SMinchan Kim 	 * or to avoid attempting to isolate pages being released,
101bda807d4SMinchan Kim 	 * lets be sure we have the page lock
102bda807d4SMinchan Kim 	 * before proceeding with the movable page isolation steps.
103bda807d4SMinchan Kim 	 */
10419979497SVishal Moola (Oracle) 	if (unlikely(!folio_trylock(folio)))
10519979497SVishal Moola (Oracle) 		goto out_putfolio;
106bda807d4SMinchan Kim 
10719979497SVishal Moola (Oracle) 	if (!folio_test_movable(folio) || folio_test_isolated(folio))
108bda807d4SMinchan Kim 		goto out_no_isolated;
109bda807d4SMinchan Kim 
11019979497SVishal Moola (Oracle) 	mops = folio_movable_ops(folio);
11119979497SVishal Moola (Oracle) 	VM_BUG_ON_FOLIO(!mops, folio);
112bda807d4SMinchan Kim 
11319979497SVishal Moola (Oracle) 	if (!mops->isolate_page(&folio->page, mode))
114bda807d4SMinchan Kim 		goto out_no_isolated;
115bda807d4SMinchan Kim 
116bda807d4SMinchan Kim 	/* Driver shouldn't use PG_isolated bit of page->flags */
11719979497SVishal Moola (Oracle) 	WARN_ON_ONCE(folio_test_isolated(folio));
11819979497SVishal Moola (Oracle) 	folio_set_isolated(folio);
11919979497SVishal Moola (Oracle) 	folio_unlock(folio);
120bda807d4SMinchan Kim 
121cd775580SBaolin Wang 	return true;
122bda807d4SMinchan Kim 
123bda807d4SMinchan Kim out_no_isolated:
12419979497SVishal Moola (Oracle) 	folio_unlock(folio);
12519979497SVishal Moola (Oracle) out_putfolio:
12619979497SVishal Moola (Oracle) 	folio_put(folio);
127bda807d4SMinchan Kim out:
128cd775580SBaolin Wang 	return false;
129bda807d4SMinchan Kim }
130bda807d4SMinchan Kim 
131280d724aSVishal Moola (Oracle) static void putback_movable_folio(struct folio *folio)
132bda807d4SMinchan Kim {
133280d724aSVishal Moola (Oracle) 	const struct movable_operations *mops = folio_movable_ops(folio);
134bda807d4SMinchan Kim 
135280d724aSVishal Moola (Oracle) 	mops->putback_page(&folio->page);
136280d724aSVishal Moola (Oracle) 	folio_clear_isolated(folio);
137bda807d4SMinchan Kim }
138bda807d4SMinchan Kim 
139b20a3503SChristoph Lameter /*
1405733c7d1SRafael Aquini  * Put previously isolated pages back onto the appropriate lists
1415733c7d1SRafael Aquini  * from where they were once taken off for compaction/migration.
1425733c7d1SRafael Aquini  *
14359c82b70SJoonsoo Kim  * This function shall be used whenever the isolated pageset has been
14459c82b70SJoonsoo Kim  * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
1457ce82f4cSMiaohe Lin  * and isolate_hugetlb().
1465733c7d1SRafael Aquini  */
1475733c7d1SRafael Aquini void putback_movable_pages(struct list_head *l)
1485733c7d1SRafael Aquini {
149280d724aSVishal Moola (Oracle) 	struct folio *folio;
150280d724aSVishal Moola (Oracle) 	struct folio *folio2;
1515733c7d1SRafael Aquini 
152280d724aSVishal Moola (Oracle) 	list_for_each_entry_safe(folio, folio2, l, lru) {
153280d724aSVishal Moola (Oracle) 		if (unlikely(folio_test_hugetlb(folio))) {
154280d724aSVishal Moola (Oracle) 			folio_putback_active_hugetlb(folio);
15531caf665SNaoya Horiguchi 			continue;
15631caf665SNaoya Horiguchi 		}
157280d724aSVishal Moola (Oracle) 		list_del(&folio->lru);
158bda807d4SMinchan Kim 		/*
159280d724aSVishal Moola (Oracle) 		 * We isolated non-lru movable folio so here we can use
1607e2a5e5aSKefeng Wang 		 * __folio_test_movable because LRU folio's mapping cannot
1617e2a5e5aSKefeng Wang 		 * have PAGE_MAPPING_MOVABLE.
162bda807d4SMinchan Kim 		 */
163280d724aSVishal Moola (Oracle) 		if (unlikely(__folio_test_movable(folio))) {
164280d724aSVishal Moola (Oracle) 			VM_BUG_ON_FOLIO(!folio_test_isolated(folio), folio);
165280d724aSVishal Moola (Oracle) 			folio_lock(folio);
166280d724aSVishal Moola (Oracle) 			if (folio_test_movable(folio))
167280d724aSVishal Moola (Oracle) 				putback_movable_folio(folio);
168bf6bddf1SRafael Aquini 			else
169280d724aSVishal Moola (Oracle) 				folio_clear_isolated(folio);
170280d724aSVishal Moola (Oracle) 			folio_unlock(folio);
171280d724aSVishal Moola (Oracle) 			folio_put(folio);
172bda807d4SMinchan Kim 		} else {
173280d724aSVishal Moola (Oracle) 			node_stat_mod_folio(folio, NR_ISOLATED_ANON +
174280d724aSVishal Moola (Oracle) 					folio_is_file_lru(folio), -folio_nr_pages(folio));
175280d724aSVishal Moola (Oracle) 			folio_putback_lru(folio);
176b20a3503SChristoph Lameter 		}
177b20a3503SChristoph Lameter 	}
178bda807d4SMinchan Kim }
179b20a3503SChristoph Lameter 
1800697212aSChristoph Lameter /*
1810697212aSChristoph Lameter  * Restore a potential migration pte to a working pte entry
1820697212aSChristoph Lameter  */
1832f031c6fSMatthew Wilcox (Oracle) static bool remove_migration_pte(struct folio *folio,
1842f031c6fSMatthew Wilcox (Oracle) 		struct vm_area_struct *vma, unsigned long addr, void *old)
1850697212aSChristoph Lameter {
1864eecb8b9SMatthew Wilcox (Oracle) 	DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
1870697212aSChristoph Lameter 
1883fe87967SKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
1896c287605SDavid Hildenbrand 		rmap_t rmap_flags = RMAP_NONE;
190c33c7948SRyan Roberts 		pte_t old_pte;
1910697212aSChristoph Lameter 		pte_t pte;
1920697212aSChristoph Lameter 		swp_entry_t entry;
1934eecb8b9SMatthew Wilcox (Oracle) 		struct page *new;
1944eecb8b9SMatthew Wilcox (Oracle) 		unsigned long idx = 0;
1950697212aSChristoph Lameter 
1964eecb8b9SMatthew Wilcox (Oracle) 		/* pgoff is invalid for ksm pages, but they are never large */
1974eecb8b9SMatthew Wilcox (Oracle) 		if (folio_test_large(folio) && !folio_test_hugetlb(folio))
1984eecb8b9SMatthew Wilcox (Oracle) 			idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
1994eecb8b9SMatthew Wilcox (Oracle) 		new = folio_page(folio, idx);
2000697212aSChristoph Lameter 
201616b8371SZi Yan #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
202616b8371SZi Yan 		/* PMD-mapped THP migration entry */
203616b8371SZi Yan 		if (!pvmw.pte) {
2044eecb8b9SMatthew Wilcox (Oracle) 			VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
2054eecb8b9SMatthew Wilcox (Oracle) 					!folio_test_pmd_mappable(folio), folio);
206616b8371SZi Yan 			remove_migration_pmd(&pvmw, new);
207616b8371SZi Yan 			continue;
208616b8371SZi Yan 		}
209616b8371SZi Yan #endif
210616b8371SZi Yan 
2114eecb8b9SMatthew Wilcox (Oracle) 		folio_get(folio);
2122e346877SPeter Xu 		pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
213c33c7948SRyan Roberts 		old_pte = ptep_get(pvmw.pte);
214c33c7948SRyan Roberts 		if (pte_swp_soft_dirty(old_pte))
215c3d16e16SCyrill Gorcunov 			pte = pte_mksoft_dirty(pte);
216d3cb8bf6SMel Gorman 
217c33c7948SRyan Roberts 		entry = pte_to_swp_entry(old_pte);
2182e346877SPeter Xu 		if (!is_migration_entry_young(entry))
2192e346877SPeter Xu 			pte = pte_mkold(pte);
2202e346877SPeter Xu 		if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
2212e346877SPeter Xu 			pte = pte_mkdirty(pte);
2224dd845b5SAlistair Popple 		if (is_writable_migration_entry(entry))
223161e393cSRick Edgecombe 			pte = pte_mkwrite(pte, vma);
224c33c7948SRyan Roberts 		else if (pte_swp_uffd_wp(old_pte))
225f45ec5ffSPeter Xu 			pte = pte_mkuffd_wp(pte);
226d3cb8bf6SMel Gorman 
2276c287605SDavid Hildenbrand 		if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
2286c287605SDavid Hildenbrand 			rmap_flags |= RMAP_EXCLUSIVE;
2296c287605SDavid Hildenbrand 
2306128763fSRalph Campbell 		if (unlikely(is_device_private_page(new))) {
2314dd845b5SAlistair Popple 			if (pte_write(pte))
2324dd845b5SAlistair Popple 				entry = make_writable_device_private_entry(
2334dd845b5SAlistair Popple 							page_to_pfn(new));
2344dd845b5SAlistair Popple 			else
2354dd845b5SAlistair Popple 				entry = make_readable_device_private_entry(
2364dd845b5SAlistair Popple 							page_to_pfn(new));
237a5430ddaSJérôme Glisse 			pte = swp_entry_to_pte(entry);
238c33c7948SRyan Roberts 			if (pte_swp_soft_dirty(old_pte))
2393d321bf8SRalph Campbell 				pte = pte_swp_mksoft_dirty(pte);
240c33c7948SRyan Roberts 			if (pte_swp_uffd_wp(old_pte))
241ebdf8321SAlistair Popple 				pte = pte_swp_mkuffd_wp(pte);
242df6ad698SJérôme Glisse 		}
243a5430ddaSJérôme Glisse 
2443ef8fd7fSAndi Kleen #ifdef CONFIG_HUGETLB_PAGE
2454eecb8b9SMatthew Wilcox (Oracle) 		if (folio_test_hugetlb(folio)) {
246935d4f0cSRyan Roberts 			struct hstate *h = hstate_vma(vma);
247935d4f0cSRyan Roberts 			unsigned int shift = huge_page_shift(h);
248935d4f0cSRyan Roberts 			unsigned long psize = huge_page_size(h);
24979c1c594SChristophe Leroy 
25079c1c594SChristophe Leroy 			pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
2514eecb8b9SMatthew Wilcox (Oracle) 			if (folio_test_anon(folio))
25209c55050SDavid Hildenbrand 				hugepage_add_anon_rmap(folio, vma, pvmw.address,
2536c287605SDavid Hildenbrand 						       rmap_flags);
254290408d4SNaoya Horiguchi 			else
255fb3d824dSDavid Hildenbrand 				page_dup_file_rmap(new, true);
256935d4f0cSRyan Roberts 			set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte,
257935d4f0cSRyan Roberts 					psize);
258383321abSAneesh Kumar K.V 		} else
259383321abSAneesh Kumar K.V #endif
260383321abSAneesh Kumar K.V 		{
2614eecb8b9SMatthew Wilcox (Oracle) 			if (folio_test_anon(folio))
262f1e2db12SDavid Hildenbrand 				page_add_anon_rmap(new, vma, pvmw.address,
2636c287605SDavid Hildenbrand 						   rmap_flags);
26404e62a29SChristoph Lameter 			else
265cea86fe2SHugh Dickins 				page_add_file_rmap(new, vma, false);
2661eba86c0SPasha Tatashin 			set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
267383321abSAneesh Kumar K.V 		}
268b7435507SHugh Dickins 		if (vma->vm_flags & VM_LOCKED)
26996f97c43SLorenzo Stoakes 			mlock_drain_local();
270e125fe40SKirill A. Shutemov 
2714cc79b33SAnshuman Khandual 		trace_remove_migration_pte(pvmw.address, pte_val(pte),
2724cc79b33SAnshuman Khandual 					   compound_order(new));
2734cc79b33SAnshuman Khandual 
27404e62a29SChristoph Lameter 		/* No need to invalidate - it was non-present before */
2753fe87967SKirill A. Shutemov 		update_mmu_cache(vma, pvmw.address, pvmw.pte);
2763fe87967SKirill A. Shutemov 	}
2773fe87967SKirill A. Shutemov 
278e4b82222SMinchan Kim 	return true;
2790697212aSChristoph Lameter }
2800697212aSChristoph Lameter 
2810697212aSChristoph Lameter /*
28204e62a29SChristoph Lameter  * Get rid of all migration entries and replace them by
28304e62a29SChristoph Lameter  * references to the indicated page.
28404e62a29SChristoph Lameter  */
2854eecb8b9SMatthew Wilcox (Oracle) void remove_migration_ptes(struct folio *src, struct folio *dst, bool locked)
28604e62a29SChristoph Lameter {
287051ac83aSJoonsoo Kim 	struct rmap_walk_control rwc = {
288051ac83aSJoonsoo Kim 		.rmap_one = remove_migration_pte,
2894eecb8b9SMatthew Wilcox (Oracle) 		.arg = src,
290051ac83aSJoonsoo Kim 	};
291051ac83aSJoonsoo Kim 
292e388466dSKirill A. Shutemov 	if (locked)
2932f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_locked(dst, &rwc);
294e388466dSKirill A. Shutemov 	else
2952f031c6fSMatthew Wilcox (Oracle) 		rmap_walk(dst, &rwc);
29604e62a29SChristoph Lameter }
29704e62a29SChristoph Lameter 
29804e62a29SChristoph Lameter /*
2990697212aSChristoph Lameter  * Something used the pte of a page under migration. We need to
3000697212aSChristoph Lameter  * get to the page and wait until migration is finished.
3010697212aSChristoph Lameter  * When we return from this function the fault will be retried.
3020697212aSChristoph Lameter  */
3030cb8fd4dSHugh Dickins void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
3040cb8fd4dSHugh Dickins 			  unsigned long address)
3050697212aSChristoph Lameter {
3060cb8fd4dSHugh Dickins 	spinlock_t *ptl;
3070cb8fd4dSHugh Dickins 	pte_t *ptep;
30830dad309SNaoya Horiguchi 	pte_t pte;
3090697212aSChristoph Lameter 	swp_entry_t entry;
3100697212aSChristoph Lameter 
3110cb8fd4dSHugh Dickins 	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
31204dee9e8SHugh Dickins 	if (!ptep)
31304dee9e8SHugh Dickins 		return;
31404dee9e8SHugh Dickins 
315c33c7948SRyan Roberts 	pte = ptep_get(ptep);
3160cb8fd4dSHugh Dickins 	pte_unmap(ptep);
3170cb8fd4dSHugh Dickins 
3180697212aSChristoph Lameter 	if (!is_swap_pte(pte))
3190697212aSChristoph Lameter 		goto out;
3200697212aSChristoph Lameter 
3210697212aSChristoph Lameter 	entry = pte_to_swp_entry(pte);
3220697212aSChristoph Lameter 	if (!is_migration_entry(entry))
3230697212aSChristoph Lameter 		goto out;
3240697212aSChristoph Lameter 
3250cb8fd4dSHugh Dickins 	migration_entry_wait_on_locked(entry, ptl);
3260697212aSChristoph Lameter 	return;
3270697212aSChristoph Lameter out:
3280cb8fd4dSHugh Dickins 	spin_unlock(ptl);
32930dad309SNaoya Horiguchi }
33030dad309SNaoya Horiguchi 
331ad1ac596SMiaohe Lin #ifdef CONFIG_HUGETLB_PAGE
332fcd48540SPeter Xu /*
333fcd48540SPeter Xu  * The vma read lock must be held upon entry. Holding that lock prevents either
334fcd48540SPeter Xu  * the pte or the ptl from being freed.
335fcd48540SPeter Xu  *
336fcd48540SPeter Xu  * This function will release the vma lock before returning.
337fcd48540SPeter Xu  */
3380cb8fd4dSHugh Dickins void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *ptep)
33930dad309SNaoya Horiguchi {
3400cb8fd4dSHugh Dickins 	spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, ptep);
341ad1ac596SMiaohe Lin 	pte_t pte;
342ad1ac596SMiaohe Lin 
343fcd48540SPeter Xu 	hugetlb_vma_assert_locked(vma);
344ad1ac596SMiaohe Lin 	spin_lock(ptl);
345ad1ac596SMiaohe Lin 	pte = huge_ptep_get(ptep);
346ad1ac596SMiaohe Lin 
347fcd48540SPeter Xu 	if (unlikely(!is_hugetlb_entry_migration(pte))) {
348ad1ac596SMiaohe Lin 		spin_unlock(ptl);
349fcd48540SPeter Xu 		hugetlb_vma_unlock_read(vma);
350fcd48540SPeter Xu 	} else {
351fcd48540SPeter Xu 		/*
352fcd48540SPeter Xu 		 * If migration entry existed, safe to release vma lock
353fcd48540SPeter Xu 		 * here because the pgtable page won't be freed without the
354fcd48540SPeter Xu 		 * pgtable lock released.  See comment right above pgtable
355fcd48540SPeter Xu 		 * lock release in migration_entry_wait_on_locked().
356fcd48540SPeter Xu 		 */
357fcd48540SPeter Xu 		hugetlb_vma_unlock_read(vma);
3580cb8fd4dSHugh Dickins 		migration_entry_wait_on_locked(pte_to_swp_entry(pte), ptl);
35930dad309SNaoya Horiguchi 	}
360fcd48540SPeter Xu }
361ad1ac596SMiaohe Lin #endif
362ad1ac596SMiaohe Lin 
363616b8371SZi Yan #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
364616b8371SZi Yan void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
365616b8371SZi Yan {
366616b8371SZi Yan 	spinlock_t *ptl;
367616b8371SZi Yan 
368616b8371SZi Yan 	ptl = pmd_lock(mm, pmd);
369616b8371SZi Yan 	if (!is_pmd_migration_entry(*pmd))
370616b8371SZi Yan 		goto unlock;
3710cb8fd4dSHugh Dickins 	migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), ptl);
372616b8371SZi Yan 	return;
373616b8371SZi Yan unlock:
374616b8371SZi Yan 	spin_unlock(ptl);
375616b8371SZi Yan }
376616b8371SZi Yan #endif
377616b8371SZi Yan 
378108ca835SMatthew Wilcox (Oracle) static int folio_expected_refs(struct address_space *mapping,
379108ca835SMatthew Wilcox (Oracle) 		struct folio *folio)
3800b3901b3SJan Kara {
381108ca835SMatthew Wilcox (Oracle) 	int refs = 1;
382108ca835SMatthew Wilcox (Oracle) 	if (!mapping)
383108ca835SMatthew Wilcox (Oracle) 		return refs;
3840b3901b3SJan Kara 
385108ca835SMatthew Wilcox (Oracle) 	refs += folio_nr_pages(folio);
386108ca835SMatthew Wilcox (Oracle) 	if (folio_test_private(folio))
387108ca835SMatthew Wilcox (Oracle) 		refs++;
388108ca835SMatthew Wilcox (Oracle) 
389108ca835SMatthew Wilcox (Oracle) 	return refs;
3900b3901b3SJan Kara }
3910b3901b3SJan Kara 
392b20a3503SChristoph Lameter /*
393c3fcf8a5SChristoph Lameter  * Replace the page in the mapping.
3945b5c7120SChristoph Lameter  *
3955b5c7120SChristoph Lameter  * The number of remaining references must be:
3965b5c7120SChristoph Lameter  * 1 for anonymous pages without a mapping
3975b5c7120SChristoph Lameter  * 2 for pages with a mapping
398266cf658SDavid Howells  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
399b20a3503SChristoph Lameter  */
4003417013eSMatthew Wilcox (Oracle) int folio_migrate_mapping(struct address_space *mapping,
4013417013eSMatthew Wilcox (Oracle) 		struct folio *newfolio, struct folio *folio, int extra_count)
402b20a3503SChristoph Lameter {
4033417013eSMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, folio_index(folio));
40442cb14b1SHugh Dickins 	struct zone *oldzone, *newzone;
40542cb14b1SHugh Dickins 	int dirty;
406108ca835SMatthew Wilcox (Oracle) 	int expected_count = folio_expected_refs(mapping, folio) + extra_count;
4073417013eSMatthew Wilcox (Oracle) 	long nr = folio_nr_pages(folio);
408*fc346d0aSCharan Teja Kalla 	long entries, i;
4098763cb45SJérôme Glisse 
4106c5240aeSChristoph Lameter 	if (!mapping) {
4110e8c7d0fSChristoph Lameter 		/* Anonymous page without mapping */
4123417013eSMatthew Wilcox (Oracle) 		if (folio_ref_count(folio) != expected_count)
4136c5240aeSChristoph Lameter 			return -EAGAIN;
414cf4b769aSHugh Dickins 
415cf4b769aSHugh Dickins 		/* No turning back from here */
4163417013eSMatthew Wilcox (Oracle) 		newfolio->index = folio->index;
4173417013eSMatthew Wilcox (Oracle) 		newfolio->mapping = folio->mapping;
4183417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapbacked(folio))
4193417013eSMatthew Wilcox (Oracle) 			__folio_set_swapbacked(newfolio);
420cf4b769aSHugh Dickins 
42178bd5209SRafael Aquini 		return MIGRATEPAGE_SUCCESS;
4226c5240aeSChristoph Lameter 	}
4236c5240aeSChristoph Lameter 
4243417013eSMatthew Wilcox (Oracle) 	oldzone = folio_zone(folio);
4253417013eSMatthew Wilcox (Oracle) 	newzone = folio_zone(newfolio);
42642cb14b1SHugh Dickins 
42789eb946aSMatthew Wilcox 	xas_lock_irq(&xas);
4283417013eSMatthew Wilcox (Oracle) 	if (!folio_ref_freeze(folio, expected_count)) {
42989eb946aSMatthew Wilcox 		xas_unlock_irq(&xas);
430e286781dSNick Piggin 		return -EAGAIN;
431e286781dSNick Piggin 	}
432e286781dSNick Piggin 
433b20a3503SChristoph Lameter 	/*
4343417013eSMatthew Wilcox (Oracle) 	 * Now we know that no one else is looking at the folio:
435cf4b769aSHugh Dickins 	 * no turning back from here.
436b20a3503SChristoph Lameter 	 */
4373417013eSMatthew Wilcox (Oracle) 	newfolio->index = folio->index;
4383417013eSMatthew Wilcox (Oracle) 	newfolio->mapping = folio->mapping;
4393417013eSMatthew Wilcox (Oracle) 	folio_ref_add(newfolio, nr); /* add cache reference */
4403417013eSMatthew Wilcox (Oracle) 	if (folio_test_swapbacked(folio)) {
4413417013eSMatthew Wilcox (Oracle) 		__folio_set_swapbacked(newfolio);
4423417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapcache(folio)) {
4433417013eSMatthew Wilcox (Oracle) 			folio_set_swapcache(newfolio);
4443417013eSMatthew Wilcox (Oracle) 			newfolio->private = folio_get_private(folio);
445b20a3503SChristoph Lameter 		}
446*fc346d0aSCharan Teja Kalla 		entries = nr;
4476326fec1SNicholas Piggin 	} else {
4483417013eSMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
449*fc346d0aSCharan Teja Kalla 		entries = 1;
4506326fec1SNicholas Piggin 	}
451b20a3503SChristoph Lameter 
45242cb14b1SHugh Dickins 	/* Move dirty while page refs frozen and newpage not yet exposed */
4533417013eSMatthew Wilcox (Oracle) 	dirty = folio_test_dirty(folio);
45442cb14b1SHugh Dickins 	if (dirty) {
4553417013eSMatthew Wilcox (Oracle) 		folio_clear_dirty(folio);
4563417013eSMatthew Wilcox (Oracle) 		folio_set_dirty(newfolio);
45742cb14b1SHugh Dickins 	}
45842cb14b1SHugh Dickins 
459*fc346d0aSCharan Teja Kalla 	/* Swap cache still stores N entries instead of a high-order entry */
460*fc346d0aSCharan Teja Kalla 	for (i = 0; i < entries; i++) {
4613417013eSMatthew Wilcox (Oracle) 		xas_store(&xas, newfolio);
462*fc346d0aSCharan Teja Kalla 		xas_next(&xas);
463*fc346d0aSCharan Teja Kalla 	}
4647cf9c2c7SNick Piggin 
4657cf9c2c7SNick Piggin 	/*
466937a94c9SJacobo Giralt 	 * Drop cache reference from old page by unfreezing
467937a94c9SJacobo Giralt 	 * to one less reference.
4687cf9c2c7SNick Piggin 	 * We know this isn't the last reference.
4697cf9c2c7SNick Piggin 	 */
4703417013eSMatthew Wilcox (Oracle) 	folio_ref_unfreeze(folio, expected_count - nr);
4717cf9c2c7SNick Piggin 
47289eb946aSMatthew Wilcox 	xas_unlock(&xas);
47342cb14b1SHugh Dickins 	/* Leave irq disabled to prevent preemption while updating stats */
47442cb14b1SHugh Dickins 
4750e8c7d0fSChristoph Lameter 	/*
4760e8c7d0fSChristoph Lameter 	 * If moved to a different zone then also account
4770e8c7d0fSChristoph Lameter 	 * the page for that zone. Other VM counters will be
4780e8c7d0fSChristoph Lameter 	 * taken care of when we establish references to the
4790e8c7d0fSChristoph Lameter 	 * new page and drop references to the old page.
4800e8c7d0fSChristoph Lameter 	 *
4810e8c7d0fSChristoph Lameter 	 * Note that anonymous pages are accounted for
4824b9d0fabSMel Gorman 	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
4830e8c7d0fSChristoph Lameter 	 * are mapped to swap space.
4840e8c7d0fSChristoph Lameter 	 */
48542cb14b1SHugh Dickins 	if (newzone != oldzone) {
4860d1c2072SJohannes Weiner 		struct lruvec *old_lruvec, *new_lruvec;
4870d1c2072SJohannes Weiner 		struct mem_cgroup *memcg;
4880d1c2072SJohannes Weiner 
4893417013eSMatthew Wilcox (Oracle) 		memcg = folio_memcg(folio);
4900d1c2072SJohannes Weiner 		old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
4910d1c2072SJohannes Weiner 		new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
4920d1c2072SJohannes Weiner 
4935c447d27SShakeel Butt 		__mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
4945c447d27SShakeel Butt 		__mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
4953417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
4965c447d27SShakeel Butt 			__mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
4975c447d27SShakeel Butt 			__mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
4980b52c420SJan Glauber 
4990b52c420SJan Glauber 			if (folio_test_pmd_mappable(folio)) {
5000b52c420SJan Glauber 				__mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr);
5010b52c420SJan Glauber 				__mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr);
5020b52c420SJan Glauber 			}
5034b02108aSKOSAKI Motohiro 		}
504b6038942SShakeel Butt #ifdef CONFIG_SWAP
5053417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapcache(folio)) {
506b6038942SShakeel Butt 			__mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
507b6038942SShakeel Butt 			__mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
508b6038942SShakeel Butt 		}
509b6038942SShakeel Butt #endif
510f56753acSChristoph Hellwig 		if (dirty && mapping_can_writeback(mapping)) {
5115c447d27SShakeel Butt 			__mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
5125c447d27SShakeel Butt 			__mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
5135c447d27SShakeel Butt 			__mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
5145c447d27SShakeel Butt 			__mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
51542cb14b1SHugh Dickins 		}
51642cb14b1SHugh Dickins 	}
51742cb14b1SHugh Dickins 	local_irq_enable();
518b20a3503SChristoph Lameter 
51978bd5209SRafael Aquini 	return MIGRATEPAGE_SUCCESS;
520b20a3503SChristoph Lameter }
5213417013eSMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_migrate_mapping);
522b20a3503SChristoph Lameter 
523b20a3503SChristoph Lameter /*
524290408d4SNaoya Horiguchi  * The expected number of remaining references is the same as that
5253417013eSMatthew Wilcox (Oracle)  * of folio_migrate_mapping().
526290408d4SNaoya Horiguchi  */
527290408d4SNaoya Horiguchi int migrate_huge_page_move_mapping(struct address_space *mapping,
528b890ec2aSMatthew Wilcox (Oracle) 				   struct folio *dst, struct folio *src)
529290408d4SNaoya Horiguchi {
530b890ec2aSMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, folio_index(src));
531290408d4SNaoya Horiguchi 	int expected_count;
532290408d4SNaoya Horiguchi 
53389eb946aSMatthew Wilcox 	xas_lock_irq(&xas);
534a08c7193SSidhartha Kumar 	expected_count = folio_expected_refs(mapping, src);
535b890ec2aSMatthew Wilcox (Oracle) 	if (!folio_ref_freeze(src, expected_count)) {
53689eb946aSMatthew Wilcox 		xas_unlock_irq(&xas);
537290408d4SNaoya Horiguchi 		return -EAGAIN;
538290408d4SNaoya Horiguchi 	}
539290408d4SNaoya Horiguchi 
540b890ec2aSMatthew Wilcox (Oracle) 	dst->index = src->index;
541b890ec2aSMatthew Wilcox (Oracle) 	dst->mapping = src->mapping;
5426a93ca8fSJohannes Weiner 
543a08c7193SSidhartha Kumar 	folio_ref_add(dst, folio_nr_pages(dst));
544290408d4SNaoya Horiguchi 
545b890ec2aSMatthew Wilcox (Oracle) 	xas_store(&xas, dst);
546290408d4SNaoya Horiguchi 
547a08c7193SSidhartha Kumar 	folio_ref_unfreeze(src, expected_count - folio_nr_pages(src));
548290408d4SNaoya Horiguchi 
54989eb946aSMatthew Wilcox 	xas_unlock_irq(&xas);
5506a93ca8fSJohannes Weiner 
55178bd5209SRafael Aquini 	return MIGRATEPAGE_SUCCESS;
552290408d4SNaoya Horiguchi }
553290408d4SNaoya Horiguchi 
554290408d4SNaoya Horiguchi /*
55519138349SMatthew Wilcox (Oracle)  * Copy the flags and some other ancillary information
556b20a3503SChristoph Lameter  */
55719138349SMatthew Wilcox (Oracle) void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
558b20a3503SChristoph Lameter {
5597851a45cSRik van Riel 	int cpupid;
5607851a45cSRik van Riel 
56119138349SMatthew Wilcox (Oracle) 	if (folio_test_error(folio))
56219138349SMatthew Wilcox (Oracle) 		folio_set_error(newfolio);
56319138349SMatthew Wilcox (Oracle) 	if (folio_test_referenced(folio))
56419138349SMatthew Wilcox (Oracle) 		folio_set_referenced(newfolio);
56519138349SMatthew Wilcox (Oracle) 	if (folio_test_uptodate(folio))
56619138349SMatthew Wilcox (Oracle) 		folio_mark_uptodate(newfolio);
56719138349SMatthew Wilcox (Oracle) 	if (folio_test_clear_active(folio)) {
56819138349SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
56919138349SMatthew Wilcox (Oracle) 		folio_set_active(newfolio);
57019138349SMatthew Wilcox (Oracle) 	} else if (folio_test_clear_unevictable(folio))
57119138349SMatthew Wilcox (Oracle) 		folio_set_unevictable(newfolio);
57219138349SMatthew Wilcox (Oracle) 	if (folio_test_workingset(folio))
57319138349SMatthew Wilcox (Oracle) 		folio_set_workingset(newfolio);
57419138349SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
57519138349SMatthew Wilcox (Oracle) 		folio_set_checked(newfolio);
5766c287605SDavid Hildenbrand 	/*
5776c287605SDavid Hildenbrand 	 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
5786c287605SDavid Hildenbrand 	 * migration entries. We can still have PG_anon_exclusive set on an
5796c287605SDavid Hildenbrand 	 * effectively unmapped and unreferenced first sub-pages of an
5806c287605SDavid Hildenbrand 	 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
5816c287605SDavid Hildenbrand 	 */
58219138349SMatthew Wilcox (Oracle) 	if (folio_test_mappedtodisk(folio))
58319138349SMatthew Wilcox (Oracle) 		folio_set_mappedtodisk(newfolio);
584b20a3503SChristoph Lameter 
5853417013eSMatthew Wilcox (Oracle) 	/* Move dirty on pages not done by folio_migrate_mapping() */
58619138349SMatthew Wilcox (Oracle) 	if (folio_test_dirty(folio))
58719138349SMatthew Wilcox (Oracle) 		folio_set_dirty(newfolio);
588b20a3503SChristoph Lameter 
58919138349SMatthew Wilcox (Oracle) 	if (folio_test_young(folio))
59019138349SMatthew Wilcox (Oracle) 		folio_set_young(newfolio);
59119138349SMatthew Wilcox (Oracle) 	if (folio_test_idle(folio))
59219138349SMatthew Wilcox (Oracle) 		folio_set_idle(newfolio);
59333c3fc71SVladimir Davydov 
5947851a45cSRik van Riel 	/*
5957851a45cSRik van Riel 	 * Copy NUMA information to the new page, to prevent over-eager
5967851a45cSRik van Riel 	 * future migrations of this same page.
5977851a45cSRik van Riel 	 */
5984e694fe4SKefeng Wang 	cpupid = folio_xchg_last_cpupid(folio, -1);
59933024536SHuang Ying 	/*
60033024536SHuang Ying 	 * For memory tiering mode, when migrate between slow and fast
60133024536SHuang Ying 	 * memory node, reset cpupid, because that is used to record
60233024536SHuang Ying 	 * page access time in slow memory node.
60333024536SHuang Ying 	 */
60433024536SHuang Ying 	if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
6054e694fe4SKefeng Wang 		bool f_toptier = node_is_toptier(folio_nid(folio));
6064e694fe4SKefeng Wang 		bool t_toptier = node_is_toptier(folio_nid(newfolio));
60733024536SHuang Ying 
60833024536SHuang Ying 		if (f_toptier != t_toptier)
60933024536SHuang Ying 			cpupid = -1;
61033024536SHuang Ying 	}
6114e694fe4SKefeng Wang 	folio_xchg_last_cpupid(newfolio, cpupid);
6127851a45cSRik van Riel 
61319138349SMatthew Wilcox (Oracle) 	folio_migrate_ksm(newfolio, folio);
614c8d6553bSHugh Dickins 	/*
615c8d6553bSHugh Dickins 	 * Please do not reorder this without considering how mm/ksm.c's
616c8d6553bSHugh Dickins 	 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
617c8d6553bSHugh Dickins 	 */
61819138349SMatthew Wilcox (Oracle) 	if (folio_test_swapcache(folio))
61919138349SMatthew Wilcox (Oracle) 		folio_clear_swapcache(folio);
62019138349SMatthew Wilcox (Oracle) 	folio_clear_private(folio);
621ad2fa371SMuchun Song 
622ad2fa371SMuchun Song 	/* page->private contains hugetlb specific flags */
62319138349SMatthew Wilcox (Oracle) 	if (!folio_test_hugetlb(folio))
62419138349SMatthew Wilcox (Oracle) 		folio->private = NULL;
625b20a3503SChristoph Lameter 
626b20a3503SChristoph Lameter 	/*
627b20a3503SChristoph Lameter 	 * If any waiters have accumulated on the new page then
628b20a3503SChristoph Lameter 	 * wake them up.
629b20a3503SChristoph Lameter 	 */
63019138349SMatthew Wilcox (Oracle) 	if (folio_test_writeback(newfolio))
63119138349SMatthew Wilcox (Oracle) 		folio_end_writeback(newfolio);
632d435edcaSVlastimil Babka 
6336aeff241SYang Shi 	/*
6346aeff241SYang Shi 	 * PG_readahead shares the same bit with PG_reclaim.  The above
6356aeff241SYang Shi 	 * end_page_writeback() may clear PG_readahead mistakenly, so set the
6366aeff241SYang Shi 	 * bit after that.
6376aeff241SYang Shi 	 */
63819138349SMatthew Wilcox (Oracle) 	if (folio_test_readahead(folio))
63919138349SMatthew Wilcox (Oracle) 		folio_set_readahead(newfolio);
6406aeff241SYang Shi 
64119138349SMatthew Wilcox (Oracle) 	folio_copy_owner(newfolio, folio);
64274485cf2SJohannes Weiner 
643d21bba2bSMatthew Wilcox (Oracle) 	mem_cgroup_migrate(folio, newfolio);
644b20a3503SChristoph Lameter }
64519138349SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_migrate_flags);
6462916ecc0SJérôme Glisse 
647715cbfd6SMatthew Wilcox (Oracle) void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
6482916ecc0SJérôme Glisse {
649715cbfd6SMatthew Wilcox (Oracle) 	folio_copy(newfolio, folio);
650715cbfd6SMatthew Wilcox (Oracle) 	folio_migrate_flags(newfolio, folio);
6512916ecc0SJérôme Glisse }
652715cbfd6SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_migrate_copy);
653b20a3503SChristoph Lameter 
6541d8b85ccSChristoph Lameter /************************************************************
6551d8b85ccSChristoph Lameter  *                    Migration functions
6561d8b85ccSChristoph Lameter  ***********************************************************/
6571d8b85ccSChristoph Lameter 
65816ce101dSAlistair Popple int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
65916ce101dSAlistair Popple 		struct folio *src, enum migrate_mode mode, int extra_count)
66016ce101dSAlistair Popple {
66116ce101dSAlistair Popple 	int rc;
66216ce101dSAlistair Popple 
66316ce101dSAlistair Popple 	BUG_ON(folio_test_writeback(src));	/* Writeback must be complete */
66416ce101dSAlistair Popple 
66516ce101dSAlistair Popple 	rc = folio_migrate_mapping(mapping, dst, src, extra_count);
66616ce101dSAlistair Popple 
66716ce101dSAlistair Popple 	if (rc != MIGRATEPAGE_SUCCESS)
66816ce101dSAlistair Popple 		return rc;
66916ce101dSAlistair Popple 
67016ce101dSAlistair Popple 	if (mode != MIGRATE_SYNC_NO_COPY)
67116ce101dSAlistair Popple 		folio_migrate_copy(dst, src);
67216ce101dSAlistair Popple 	else
67316ce101dSAlistair Popple 		folio_migrate_flags(dst, src);
67416ce101dSAlistair Popple 	return MIGRATEPAGE_SUCCESS;
67516ce101dSAlistair Popple }
67616ce101dSAlistair Popple 
67754184650SMatthew Wilcox (Oracle) /**
67854184650SMatthew Wilcox (Oracle)  * migrate_folio() - Simple folio migration.
67954184650SMatthew Wilcox (Oracle)  * @mapping: The address_space containing the folio.
68054184650SMatthew Wilcox (Oracle)  * @dst: The folio to migrate the data to.
68154184650SMatthew Wilcox (Oracle)  * @src: The folio containing the current data.
68254184650SMatthew Wilcox (Oracle)  * @mode: How to migrate the page.
683b20a3503SChristoph Lameter  *
68454184650SMatthew Wilcox (Oracle)  * Common logic to directly migrate a single LRU folio suitable for
68554184650SMatthew Wilcox (Oracle)  * folios that do not use PagePrivate/PagePrivate2.
68654184650SMatthew Wilcox (Oracle)  *
68754184650SMatthew Wilcox (Oracle)  * Folios are locked upon entry and exit.
688b20a3503SChristoph Lameter  */
68954184650SMatthew Wilcox (Oracle) int migrate_folio(struct address_space *mapping, struct folio *dst,
69054184650SMatthew Wilcox (Oracle) 		struct folio *src, enum migrate_mode mode)
691b20a3503SChristoph Lameter {
69216ce101dSAlistair Popple 	return migrate_folio_extra(mapping, dst, src, mode, 0);
693b20a3503SChristoph Lameter }
69454184650SMatthew Wilcox (Oracle) EXPORT_SYMBOL(migrate_folio);
695b20a3503SChristoph Lameter 
696925c86a1SChristoph Hellwig #ifdef CONFIG_BUFFER_HEAD
69784ade7c1SJan Kara /* Returns true if all buffers are successfully locked */
69884ade7c1SJan Kara static bool buffer_migrate_lock_buffers(struct buffer_head *head,
69984ade7c1SJan Kara 							enum migrate_mode mode)
70084ade7c1SJan Kara {
70184ade7c1SJan Kara 	struct buffer_head *bh = head;
7024bb6dc79SDouglas Anderson 	struct buffer_head *failed_bh;
70384ade7c1SJan Kara 
70484ade7c1SJan Kara 	do {
7054bb6dc79SDouglas Anderson 		if (!trylock_buffer(bh)) {
7064bb6dc79SDouglas Anderson 			if (mode == MIGRATE_ASYNC)
7074bb6dc79SDouglas Anderson 				goto unlock;
7084bb6dc79SDouglas Anderson 			if (mode == MIGRATE_SYNC_LIGHT && !buffer_uptodate(bh))
7094bb6dc79SDouglas Anderson 				goto unlock;
71084ade7c1SJan Kara 			lock_buffer(bh);
7114bb6dc79SDouglas Anderson 		}
71284ade7c1SJan Kara 
7134bb6dc79SDouglas Anderson 		bh = bh->b_this_page;
71484ade7c1SJan Kara 	} while (bh != head);
71584ade7c1SJan Kara 
71684ade7c1SJan Kara 	return true;
71784ade7c1SJan Kara 
7184bb6dc79SDouglas Anderson unlock:
7194bb6dc79SDouglas Anderson 	/* We failed to lock the buffer and cannot stall. */
7204bb6dc79SDouglas Anderson 	failed_bh = bh;
72184ade7c1SJan Kara 	bh = head;
72284ade7c1SJan Kara 	while (bh != failed_bh) {
72384ade7c1SJan Kara 		unlock_buffer(bh);
72484ade7c1SJan Kara 		bh = bh->b_this_page;
72584ade7c1SJan Kara 	}
72684ade7c1SJan Kara 
7274bb6dc79SDouglas Anderson 	return false;
72884ade7c1SJan Kara }
72984ade7c1SJan Kara 
73067235182SMatthew Wilcox (Oracle) static int __buffer_migrate_folio(struct address_space *mapping,
73167235182SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode,
73289cb0888SJan Kara 		bool check_refs)
7331d8b85ccSChristoph Lameter {
7341d8b85ccSChristoph Lameter 	struct buffer_head *bh, *head;
7351d8b85ccSChristoph Lameter 	int rc;
736cc4f11e6SJan Kara 	int expected_count;
7371d8b85ccSChristoph Lameter 
73867235182SMatthew Wilcox (Oracle) 	head = folio_buffers(src);
73967235182SMatthew Wilcox (Oracle) 	if (!head)
74054184650SMatthew Wilcox (Oracle) 		return migrate_folio(mapping, dst, src, mode);
7411d8b85ccSChristoph Lameter 
742cc4f11e6SJan Kara 	/* Check whether page does not have extra refs before we do more work */
743108ca835SMatthew Wilcox (Oracle) 	expected_count = folio_expected_refs(mapping, src);
74467235182SMatthew Wilcox (Oracle) 	if (folio_ref_count(src) != expected_count)
745cc4f11e6SJan Kara 		return -EAGAIN;
746cc4f11e6SJan Kara 
747cc4f11e6SJan Kara 	if (!buffer_migrate_lock_buffers(head, mode))
748cc4f11e6SJan Kara 		return -EAGAIN;
7491d8b85ccSChristoph Lameter 
75089cb0888SJan Kara 	if (check_refs) {
75189cb0888SJan Kara 		bool busy;
75289cb0888SJan Kara 		bool invalidated = false;
75389cb0888SJan Kara 
75489cb0888SJan Kara recheck_buffers:
75589cb0888SJan Kara 		busy = false;
75689cb0888SJan Kara 		spin_lock(&mapping->private_lock);
75789cb0888SJan Kara 		bh = head;
75889cb0888SJan Kara 		do {
75989cb0888SJan Kara 			if (atomic_read(&bh->b_count)) {
76089cb0888SJan Kara 				busy = true;
76189cb0888SJan Kara 				break;
76289cb0888SJan Kara 			}
76389cb0888SJan Kara 			bh = bh->b_this_page;
76489cb0888SJan Kara 		} while (bh != head);
76589cb0888SJan Kara 		if (busy) {
76689cb0888SJan Kara 			if (invalidated) {
76789cb0888SJan Kara 				rc = -EAGAIN;
76889cb0888SJan Kara 				goto unlock_buffers;
76989cb0888SJan Kara 			}
770ebdf4de5SJan Kara 			spin_unlock(&mapping->private_lock);
77189cb0888SJan Kara 			invalidate_bh_lrus();
77289cb0888SJan Kara 			invalidated = true;
77389cb0888SJan Kara 			goto recheck_buffers;
77489cb0888SJan Kara 		}
77589cb0888SJan Kara 	}
77689cb0888SJan Kara 
77767235182SMatthew Wilcox (Oracle) 	rc = folio_migrate_mapping(mapping, dst, src, 0);
77878bd5209SRafael Aquini 	if (rc != MIGRATEPAGE_SUCCESS)
779cc4f11e6SJan Kara 		goto unlock_buffers;
7801d8b85ccSChristoph Lameter 
78167235182SMatthew Wilcox (Oracle) 	folio_attach_private(dst, folio_detach_private(src));
7821d8b85ccSChristoph Lameter 
7831d8b85ccSChristoph Lameter 	bh = head;
7841d8b85ccSChristoph Lameter 	do {
785d5db4f9dSMatthew Wilcox (Oracle) 		folio_set_bh(bh, dst, bh_offset(bh));
7861d8b85ccSChristoph Lameter 		bh = bh->b_this_page;
7871d8b85ccSChristoph Lameter 	} while (bh != head);
7881d8b85ccSChristoph Lameter 
7892916ecc0SJérôme Glisse 	if (mode != MIGRATE_SYNC_NO_COPY)
79067235182SMatthew Wilcox (Oracle) 		folio_migrate_copy(dst, src);
7912916ecc0SJérôme Glisse 	else
79267235182SMatthew Wilcox (Oracle) 		folio_migrate_flags(dst, src);
7931d8b85ccSChristoph Lameter 
794cc4f11e6SJan Kara 	rc = MIGRATEPAGE_SUCCESS;
795cc4f11e6SJan Kara unlock_buffers:
796ebdf4de5SJan Kara 	if (check_refs)
797ebdf4de5SJan Kara 		spin_unlock(&mapping->private_lock);
7981d8b85ccSChristoph Lameter 	bh = head;
7991d8b85ccSChristoph Lameter 	do {
8001d8b85ccSChristoph Lameter 		unlock_buffer(bh);
8011d8b85ccSChristoph Lameter 		bh = bh->b_this_page;
8021d8b85ccSChristoph Lameter 	} while (bh != head);
8031d8b85ccSChristoph Lameter 
804cc4f11e6SJan Kara 	return rc;
8051d8b85ccSChristoph Lameter }
80689cb0888SJan Kara 
80767235182SMatthew Wilcox (Oracle) /**
80867235182SMatthew Wilcox (Oracle)  * buffer_migrate_folio() - Migration function for folios with buffers.
80967235182SMatthew Wilcox (Oracle)  * @mapping: The address space containing @src.
81067235182SMatthew Wilcox (Oracle)  * @dst: The folio to migrate to.
81167235182SMatthew Wilcox (Oracle)  * @src: The folio to migrate from.
81267235182SMatthew Wilcox (Oracle)  * @mode: How to migrate the folio.
81367235182SMatthew Wilcox (Oracle)  *
81467235182SMatthew Wilcox (Oracle)  * This function can only be used if the underlying filesystem guarantees
81567235182SMatthew Wilcox (Oracle)  * that no other references to @src exist. For example attached buffer
81667235182SMatthew Wilcox (Oracle)  * heads are accessed only under the folio lock.  If your filesystem cannot
81767235182SMatthew Wilcox (Oracle)  * provide this guarantee, buffer_migrate_folio_norefs() may be more
81867235182SMatthew Wilcox (Oracle)  * appropriate.
81967235182SMatthew Wilcox (Oracle)  *
82067235182SMatthew Wilcox (Oracle)  * Return: 0 on success or a negative errno on failure.
82189cb0888SJan Kara  */
82267235182SMatthew Wilcox (Oracle) int buffer_migrate_folio(struct address_space *mapping,
82367235182SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
82489cb0888SJan Kara {
82567235182SMatthew Wilcox (Oracle) 	return __buffer_migrate_folio(mapping, dst, src, mode, false);
82689cb0888SJan Kara }
82767235182SMatthew Wilcox (Oracle) EXPORT_SYMBOL(buffer_migrate_folio);
82889cb0888SJan Kara 
82967235182SMatthew Wilcox (Oracle) /**
83067235182SMatthew Wilcox (Oracle)  * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
83167235182SMatthew Wilcox (Oracle)  * @mapping: The address space containing @src.
83267235182SMatthew Wilcox (Oracle)  * @dst: The folio to migrate to.
83367235182SMatthew Wilcox (Oracle)  * @src: The folio to migrate from.
83467235182SMatthew Wilcox (Oracle)  * @mode: How to migrate the folio.
83567235182SMatthew Wilcox (Oracle)  *
83667235182SMatthew Wilcox (Oracle)  * Like buffer_migrate_folio() except that this variant is more careful
83767235182SMatthew Wilcox (Oracle)  * and checks that there are also no buffer head references. This function
83867235182SMatthew Wilcox (Oracle)  * is the right one for mappings where buffer heads are directly looked
83967235182SMatthew Wilcox (Oracle)  * up and referenced (such as block device mappings).
84067235182SMatthew Wilcox (Oracle)  *
84167235182SMatthew Wilcox (Oracle)  * Return: 0 on success or a negative errno on failure.
84289cb0888SJan Kara  */
84367235182SMatthew Wilcox (Oracle) int buffer_migrate_folio_norefs(struct address_space *mapping,
84467235182SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
84589cb0888SJan Kara {
84667235182SMatthew Wilcox (Oracle) 	return __buffer_migrate_folio(mapping, dst, src, mode, true);
84789cb0888SJan Kara }
848e26355e2SJan Kara EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
849925c86a1SChristoph Hellwig #endif /* CONFIG_BUFFER_HEAD */
8501d8b85ccSChristoph Lameter 
8512ec810d5SMatthew Wilcox (Oracle) int filemap_migrate_folio(struct address_space *mapping,
8522ec810d5SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
8532ec810d5SMatthew Wilcox (Oracle) {
8542ec810d5SMatthew Wilcox (Oracle) 	int ret;
8552ec810d5SMatthew Wilcox (Oracle) 
8562ec810d5SMatthew Wilcox (Oracle) 	ret = folio_migrate_mapping(mapping, dst, src, 0);
8572ec810d5SMatthew Wilcox (Oracle) 	if (ret != MIGRATEPAGE_SUCCESS)
8582ec810d5SMatthew Wilcox (Oracle) 		return ret;
8592ec810d5SMatthew Wilcox (Oracle) 
8602ec810d5SMatthew Wilcox (Oracle) 	if (folio_get_private(src))
8612ec810d5SMatthew Wilcox (Oracle) 		folio_attach_private(dst, folio_detach_private(src));
8622ec810d5SMatthew Wilcox (Oracle) 
8632ec810d5SMatthew Wilcox (Oracle) 	if (mode != MIGRATE_SYNC_NO_COPY)
8642ec810d5SMatthew Wilcox (Oracle) 		folio_migrate_copy(dst, src);
8652ec810d5SMatthew Wilcox (Oracle) 	else
8662ec810d5SMatthew Wilcox (Oracle) 		folio_migrate_flags(dst, src);
8672ec810d5SMatthew Wilcox (Oracle) 	return MIGRATEPAGE_SUCCESS;
8682ec810d5SMatthew Wilcox (Oracle) }
8692ec810d5SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(filemap_migrate_folio);
8702ec810d5SMatthew Wilcox (Oracle) 
87104e62a29SChristoph Lameter /*
8722be7fa10SMatthew Wilcox (Oracle)  * Writeback a folio to clean the dirty state
87304e62a29SChristoph Lameter  */
8742be7fa10SMatthew Wilcox (Oracle) static int writeout(struct address_space *mapping, struct folio *folio)
87504e62a29SChristoph Lameter {
87604e62a29SChristoph Lameter 	struct writeback_control wbc = {
87704e62a29SChristoph Lameter 		.sync_mode = WB_SYNC_NONE,
87804e62a29SChristoph Lameter 		.nr_to_write = 1,
87904e62a29SChristoph Lameter 		.range_start = 0,
88004e62a29SChristoph Lameter 		.range_end = LLONG_MAX,
88104e62a29SChristoph Lameter 		.for_reclaim = 1
88204e62a29SChristoph Lameter 	};
88304e62a29SChristoph Lameter 	int rc;
88404e62a29SChristoph Lameter 
88504e62a29SChristoph Lameter 	if (!mapping->a_ops->writepage)
88604e62a29SChristoph Lameter 		/* No write method for the address space */
88704e62a29SChristoph Lameter 		return -EINVAL;
88804e62a29SChristoph Lameter 
8892be7fa10SMatthew Wilcox (Oracle) 	if (!folio_clear_dirty_for_io(folio))
89004e62a29SChristoph Lameter 		/* Someone else already triggered a write */
89104e62a29SChristoph Lameter 		return -EAGAIN;
89204e62a29SChristoph Lameter 
89304e62a29SChristoph Lameter 	/*
8942be7fa10SMatthew Wilcox (Oracle) 	 * A dirty folio may imply that the underlying filesystem has
8952be7fa10SMatthew Wilcox (Oracle) 	 * the folio on some queue. So the folio must be clean for
8962be7fa10SMatthew Wilcox (Oracle) 	 * migration. Writeout may mean we lose the lock and the
8972be7fa10SMatthew Wilcox (Oracle) 	 * folio state is no longer what we checked for earlier.
89804e62a29SChristoph Lameter 	 * At this point we know that the migration attempt cannot
89904e62a29SChristoph Lameter 	 * be successful.
90004e62a29SChristoph Lameter 	 */
9014eecb8b9SMatthew Wilcox (Oracle) 	remove_migration_ptes(folio, folio, false);
90204e62a29SChristoph Lameter 
9032be7fa10SMatthew Wilcox (Oracle) 	rc = mapping->a_ops->writepage(&folio->page, &wbc);
90404e62a29SChristoph Lameter 
90504e62a29SChristoph Lameter 	if (rc != AOP_WRITEPAGE_ACTIVATE)
90604e62a29SChristoph Lameter 		/* unlocked. Relock */
9072be7fa10SMatthew Wilcox (Oracle) 		folio_lock(folio);
90804e62a29SChristoph Lameter 
909bda8550dSHugh Dickins 	return (rc < 0) ? -EIO : -EAGAIN;
91004e62a29SChristoph Lameter }
91104e62a29SChristoph Lameter 
91204e62a29SChristoph Lameter /*
91304e62a29SChristoph Lameter  * Default handling if a filesystem does not provide a migration function.
91404e62a29SChristoph Lameter  */
9158faa8ef5SMatthew Wilcox (Oracle) static int fallback_migrate_folio(struct address_space *mapping,
9168faa8ef5SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
9178351a6e4SChristoph Lameter {
9188faa8ef5SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src)) {
9198faa8ef5SMatthew Wilcox (Oracle) 		/* Only writeback folios in full synchronous migration */
9202916ecc0SJérôme Glisse 		switch (mode) {
9212916ecc0SJérôme Glisse 		case MIGRATE_SYNC:
9222916ecc0SJérôme Glisse 		case MIGRATE_SYNC_NO_COPY:
9232916ecc0SJérôme Glisse 			break;
9242916ecc0SJérôme Glisse 		default:
925b969c4abSMel Gorman 			return -EBUSY;
9262916ecc0SJérôme Glisse 		}
9272be7fa10SMatthew Wilcox (Oracle) 		return writeout(mapping, src);
928b969c4abSMel Gorman 	}
9298351a6e4SChristoph Lameter 
9308351a6e4SChristoph Lameter 	/*
9318351a6e4SChristoph Lameter 	 * Buffers may be managed in a filesystem specific way.
9328351a6e4SChristoph Lameter 	 * We must have no buffers or drop them.
9338351a6e4SChristoph Lameter 	 */
9340201ebf2SDavid Howells 	if (!filemap_release_folio(src, GFP_KERNEL))
935806031bbSMel Gorman 		return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
9368351a6e4SChristoph Lameter 
93754184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
9388351a6e4SChristoph Lameter }
9398351a6e4SChristoph Lameter 
9401d8b85ccSChristoph Lameter /*
941e24f0b8fSChristoph Lameter  * Move a page to a newly allocated page
942e24f0b8fSChristoph Lameter  * The page is locked and all ptes have been successfully removed.
943b20a3503SChristoph Lameter  *
944e24f0b8fSChristoph Lameter  * The new page will have replaced the old page if this function
945e24f0b8fSChristoph Lameter  * is successful.
946894bc310SLee Schermerhorn  *
947894bc310SLee Schermerhorn  * Return value:
948894bc310SLee Schermerhorn  *   < 0 - error code
94978bd5209SRafael Aquini  *  MIGRATEPAGE_SUCCESS - success
950b20a3503SChristoph Lameter  */
951e7e3ffebSMatthew Wilcox (Oracle) static int move_to_new_folio(struct folio *dst, struct folio *src,
9525c3f9a67SHugh Dickins 				enum migrate_mode mode)
953b20a3503SChristoph Lameter {
954bda807d4SMinchan Kim 	int rc = -EAGAIN;
9557e2a5e5aSKefeng Wang 	bool is_lru = !__folio_test_movable(src);
956b20a3503SChristoph Lameter 
957e7e3ffebSMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
958e7e3ffebSMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
959b20a3503SChristoph Lameter 
960bda807d4SMinchan Kim 	if (likely(is_lru)) {
96168f2736aSMatthew Wilcox (Oracle) 		struct address_space *mapping = folio_mapping(src);
96268f2736aSMatthew Wilcox (Oracle) 
963b20a3503SChristoph Lameter 		if (!mapping)
96454184650SMatthew Wilcox (Oracle) 			rc = migrate_folio(mapping, dst, src, mode);
9655490da4fSMatthew Wilcox (Oracle) 		else if (mapping->a_ops->migrate_folio)
966b20a3503SChristoph Lameter 			/*
9675490da4fSMatthew Wilcox (Oracle) 			 * Most folios have a mapping and most filesystems
9685490da4fSMatthew Wilcox (Oracle) 			 * provide a migrate_folio callback. Anonymous folios
969bda807d4SMinchan Kim 			 * are part of swap space which also has its own
9705490da4fSMatthew Wilcox (Oracle) 			 * migrate_folio callback. This is the most common path
971bda807d4SMinchan Kim 			 * for page migration.
972b20a3503SChristoph Lameter 			 */
9735490da4fSMatthew Wilcox (Oracle) 			rc = mapping->a_ops->migrate_folio(mapping, dst, src,
9745490da4fSMatthew Wilcox (Oracle) 								mode);
9758351a6e4SChristoph Lameter 		else
9768faa8ef5SMatthew Wilcox (Oracle) 			rc = fallback_migrate_folio(mapping, dst, src, mode);
977bda807d4SMinchan Kim 	} else {
97868f2736aSMatthew Wilcox (Oracle) 		const struct movable_operations *mops;
97968f2736aSMatthew Wilcox (Oracle) 
980bda807d4SMinchan Kim 		/*
981bda807d4SMinchan Kim 		 * In case of non-lru page, it could be released after
982bda807d4SMinchan Kim 		 * isolation step. In that case, we shouldn't try migration.
983bda807d4SMinchan Kim 		 */
984e7e3ffebSMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
985e7e3ffebSMatthew Wilcox (Oracle) 		if (!folio_test_movable(src)) {
986bda807d4SMinchan Kim 			rc = MIGRATEPAGE_SUCCESS;
987e7e3ffebSMatthew Wilcox (Oracle) 			folio_clear_isolated(src);
988bda807d4SMinchan Kim 			goto out;
989bda807d4SMinchan Kim 		}
990bda807d4SMinchan Kim 
991da707a6dSVishal Moola (Oracle) 		mops = folio_movable_ops(src);
99268f2736aSMatthew Wilcox (Oracle) 		rc = mops->migrate_page(&dst->page, &src->page, mode);
993bda807d4SMinchan Kim 		WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
994e7e3ffebSMatthew Wilcox (Oracle) 				!folio_test_isolated(src));
995bda807d4SMinchan Kim 	}
996b20a3503SChristoph Lameter 
9975c3f9a67SHugh Dickins 	/*
998e7e3ffebSMatthew Wilcox (Oracle) 	 * When successful, old pagecache src->mapping must be cleared before
999e7e3ffebSMatthew Wilcox (Oracle) 	 * src is freed; but stats require that PageAnon be left as PageAnon.
10005c3f9a67SHugh Dickins 	 */
10015c3f9a67SHugh Dickins 	if (rc == MIGRATEPAGE_SUCCESS) {
10027e2a5e5aSKefeng Wang 		if (__folio_test_movable(src)) {
1003e7e3ffebSMatthew Wilcox (Oracle) 			VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
1004bda807d4SMinchan Kim 
1005bda807d4SMinchan Kim 			/*
1006bda807d4SMinchan Kim 			 * We clear PG_movable under page_lock so any compactor
1007bda807d4SMinchan Kim 			 * cannot try to migrate this page.
1008bda807d4SMinchan Kim 			 */
1009e7e3ffebSMatthew Wilcox (Oracle) 			folio_clear_isolated(src);
1010bda807d4SMinchan Kim 		}
1011bda807d4SMinchan Kim 
1012bda807d4SMinchan Kim 		/*
1013e7e3ffebSMatthew Wilcox (Oracle) 		 * Anonymous and movable src->mapping will be cleared by
1014bda807d4SMinchan Kim 		 * free_pages_prepare so don't reset it here for keeping
1015bda807d4SMinchan Kim 		 * the type to work PageAnon, for example.
1016bda807d4SMinchan Kim 		 */
1017e7e3ffebSMatthew Wilcox (Oracle) 		if (!folio_mapping_flags(src))
1018e7e3ffebSMatthew Wilcox (Oracle) 			src->mapping = NULL;
1019d2b2c6ddSLars Persson 
1020e7e3ffebSMatthew Wilcox (Oracle) 		if (likely(!folio_is_zone_device(dst)))
1021e7e3ffebSMatthew Wilcox (Oracle) 			flush_dcache_folio(dst);
10223fe2011fSMel Gorman 	}
1023bda807d4SMinchan Kim out:
1024e24f0b8fSChristoph Lameter 	return rc;
1025e24f0b8fSChristoph Lameter }
1026e24f0b8fSChristoph Lameter 
102764c8902eSHuang Ying /*
102864c8902eSHuang Ying  * To record some information during migration, we use some unused
102964c8902eSHuang Ying  * fields (mapping and private) of struct folio of the newly allocated
103064c8902eSHuang Ying  * destination folio.  This is safe because nobody is using them
103164c8902eSHuang Ying  * except us.
103264c8902eSHuang Ying  */
1033e77d587aSLinus Torvalds union migration_ptr {
1034e77d587aSLinus Torvalds 	struct anon_vma *anon_vma;
1035e77d587aSLinus Torvalds 	struct address_space *mapping;
1036e77d587aSLinus Torvalds };
1037eebb3dabSBaolin Wang 
1038eebb3dabSBaolin Wang enum {
1039eebb3dabSBaolin Wang 	PAGE_WAS_MAPPED = BIT(0),
1040eebb3dabSBaolin Wang 	PAGE_WAS_MLOCKED = BIT(1),
1041eebb3dabSBaolin Wang };
1042eebb3dabSBaolin Wang 
104364c8902eSHuang Ying static void __migrate_folio_record(struct folio *dst,
1044eebb3dabSBaolin Wang 				   unsigned long old_page_state,
104564c8902eSHuang Ying 				   struct anon_vma *anon_vma)
1046e24f0b8fSChristoph Lameter {
1047e77d587aSLinus Torvalds 	union migration_ptr ptr = { .anon_vma = anon_vma };
1048e77d587aSLinus Torvalds 	dst->mapping = ptr.mapping;
1049eebb3dabSBaolin Wang 	dst->private = (void *)old_page_state;
105064c8902eSHuang Ying }
105164c8902eSHuang Ying 
105264c8902eSHuang Ying static void __migrate_folio_extract(struct folio *dst,
1053eebb3dabSBaolin Wang 				   int *old_page_state,
105464c8902eSHuang Ying 				   struct anon_vma **anon_vmap)
105564c8902eSHuang Ying {
1056e77d587aSLinus Torvalds 	union migration_ptr ptr = { .mapping = dst->mapping };
1057e77d587aSLinus Torvalds 	*anon_vmap = ptr.anon_vma;
1058eebb3dabSBaolin Wang 	*old_page_state = (unsigned long)dst->private;
105964c8902eSHuang Ying 	dst->mapping = NULL;
106064c8902eSHuang Ying 	dst->private = NULL;
106164c8902eSHuang Ying }
106264c8902eSHuang Ying 
10635dfab109SHuang Ying /* Restore the source folio to the original state upon failure */
10645dfab109SHuang Ying static void migrate_folio_undo_src(struct folio *src,
10655dfab109SHuang Ying 				   int page_was_mapped,
10665dfab109SHuang Ying 				   struct anon_vma *anon_vma,
1067ebe75e47SHuang Ying 				   bool locked,
10685dfab109SHuang Ying 				   struct list_head *ret)
10695dfab109SHuang Ying {
10705dfab109SHuang Ying 	if (page_was_mapped)
10715dfab109SHuang Ying 		remove_migration_ptes(src, src, false);
10725dfab109SHuang Ying 	/* Drop an anon_vma reference if we took one */
10735dfab109SHuang Ying 	if (anon_vma)
10745dfab109SHuang Ying 		put_anon_vma(anon_vma);
1075ebe75e47SHuang Ying 	if (locked)
10765dfab109SHuang Ying 		folio_unlock(src);
1077ebe75e47SHuang Ying 	if (ret)
10785dfab109SHuang Ying 		list_move_tail(&src->lru, ret);
10795dfab109SHuang Ying }
10805dfab109SHuang Ying 
10815dfab109SHuang Ying /* Restore the destination folio to the original state upon failure */
10824e096ae1SMatthew Wilcox (Oracle) static void migrate_folio_undo_dst(struct folio *dst, bool locked,
10834e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private)
10845dfab109SHuang Ying {
1085ebe75e47SHuang Ying 	if (locked)
10865dfab109SHuang Ying 		folio_unlock(dst);
10874e096ae1SMatthew Wilcox (Oracle) 	if (put_new_folio)
10884e096ae1SMatthew Wilcox (Oracle) 		put_new_folio(dst, private);
10895dfab109SHuang Ying 	else
10905dfab109SHuang Ying 		folio_put(dst);
10915dfab109SHuang Ying }
10925dfab109SHuang Ying 
109364c8902eSHuang Ying /* Cleanup src folio upon migration success */
109464c8902eSHuang Ying static void migrate_folio_done(struct folio *src,
109564c8902eSHuang Ying 			       enum migrate_reason reason)
109664c8902eSHuang Ying {
109764c8902eSHuang Ying 	/*
109864c8902eSHuang Ying 	 * Compaction can migrate also non-LRU pages which are
109964c8902eSHuang Ying 	 * not accounted to NR_ISOLATED_*. They can be recognized
11007e2a5e5aSKefeng Wang 	 * as __folio_test_movable
110164c8902eSHuang Ying 	 */
110264c8902eSHuang Ying 	if (likely(!__folio_test_movable(src)))
110364c8902eSHuang Ying 		mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
110464c8902eSHuang Ying 				    folio_is_file_lru(src), -folio_nr_pages(src));
110564c8902eSHuang Ying 
110664c8902eSHuang Ying 	if (reason != MR_MEMORY_FAILURE)
110764c8902eSHuang Ying 		/* We release the page in page_handle_poison. */
110864c8902eSHuang Ying 		folio_put(src);
110964c8902eSHuang Ying }
111064c8902eSHuang Ying 
1111ebe75e47SHuang Ying /* Obtain the lock on page, remove all ptes. */
11124e096ae1SMatthew Wilcox (Oracle) static int migrate_folio_unmap(new_folio_t get_new_folio,
11134e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
11144e096ae1SMatthew Wilcox (Oracle) 		struct folio *src, struct folio **dstp, enum migrate_mode mode,
11152ef7dbb2SHuang Ying 		enum migrate_reason reason, struct list_head *ret)
1116e24f0b8fSChristoph Lameter {
1117ebe75e47SHuang Ying 	struct folio *dst;
11180dabec93SMinchan Kim 	int rc = -EAGAIN;
1119eebb3dabSBaolin Wang 	int old_page_state = 0;
11203f6c8272SMel Gorman 	struct anon_vma *anon_vma = NULL;
11217e2a5e5aSKefeng Wang 	bool is_lru = !__folio_test_movable(src);
1122ebe75e47SHuang Ying 	bool locked = false;
1123ebe75e47SHuang Ying 	bool dst_locked = false;
1124ebe75e47SHuang Ying 
1125ebe75e47SHuang Ying 	if (folio_ref_count(src) == 1) {
1126ebe75e47SHuang Ying 		/* Folio was freed from under us. So we are done. */
1127ebe75e47SHuang Ying 		folio_clear_active(src);
1128ebe75e47SHuang Ying 		folio_clear_unevictable(src);
1129ebe75e47SHuang Ying 		/* free_pages_prepare() will clear PG_isolated. */
1130ebe75e47SHuang Ying 		list_del(&src->lru);
1131ebe75e47SHuang Ying 		migrate_folio_done(src, reason);
1132ebe75e47SHuang Ying 		return MIGRATEPAGE_SUCCESS;
1133ebe75e47SHuang Ying 	}
1134ebe75e47SHuang Ying 
11354e096ae1SMatthew Wilcox (Oracle) 	dst = get_new_folio(src, private);
11364e096ae1SMatthew Wilcox (Oracle) 	if (!dst)
1137ebe75e47SHuang Ying 		return -ENOMEM;
1138ebe75e47SHuang Ying 	*dstp = dst;
1139ebe75e47SHuang Ying 
1140ebe75e47SHuang Ying 	dst->private = NULL;
114195a402c3SChristoph Lameter 
1142682a71a1SMatthew Wilcox (Oracle) 	if (!folio_trylock(src)) {
11432ef7dbb2SHuang Ying 		if (mode == MIGRATE_ASYNC)
11440dabec93SMinchan Kim 			goto out;
11453e7d3449SMel Gorman 
11463e7d3449SMel Gorman 		/*
11473e7d3449SMel Gorman 		 * It's not safe for direct compaction to call lock_page.
11483e7d3449SMel Gorman 		 * For example, during page readahead pages are added locked
11493e7d3449SMel Gorman 		 * to the LRU. Later, when the IO completes the pages are
11503e7d3449SMel Gorman 		 * marked uptodate and unlocked. However, the queueing
11513e7d3449SMel Gorman 		 * could be merging multiple pages for one bio (e.g.
1152d4388340SMatthew Wilcox (Oracle) 		 * mpage_readahead). If an allocation happens for the
11533e7d3449SMel Gorman 		 * second or third page, the process can end up locking
11543e7d3449SMel Gorman 		 * the same page twice and deadlocking. Rather than
11553e7d3449SMel Gorman 		 * trying to be clever about what pages can be locked,
11563e7d3449SMel Gorman 		 * avoid the use of lock_page for direct compaction
11573e7d3449SMel Gorman 		 * altogether.
11583e7d3449SMel Gorman 		 */
11593e7d3449SMel Gorman 		if (current->flags & PF_MEMALLOC)
11600dabec93SMinchan Kim 			goto out;
11613e7d3449SMel Gorman 
11624bb6dc79SDouglas Anderson 		/*
11634bb6dc79SDouglas Anderson 		 * In "light" mode, we can wait for transient locks (eg
11644bb6dc79SDouglas Anderson 		 * inserting a page into the page table), but it's not
11654bb6dc79SDouglas Anderson 		 * worth waiting for I/O.
11664bb6dc79SDouglas Anderson 		 */
11674bb6dc79SDouglas Anderson 		if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
11684bb6dc79SDouglas Anderson 			goto out;
11694bb6dc79SDouglas Anderson 
1170682a71a1SMatthew Wilcox (Oracle) 		folio_lock(src);
1171e24f0b8fSChristoph Lameter 	}
1172ebe75e47SHuang Ying 	locked = true;
1173eebb3dabSBaolin Wang 	if (folio_test_mlocked(src))
1174eebb3dabSBaolin Wang 		old_page_state |= PAGE_WAS_MLOCKED;
1175e24f0b8fSChristoph Lameter 
1176682a71a1SMatthew Wilcox (Oracle) 	if (folio_test_writeback(src)) {
117711bc82d6SAndrea Arcangeli 		/*
1178fed5b64aSJianguo Wu 		 * Only in the case of a full synchronous migration is it
1179a6bc32b8SMel Gorman 		 * necessary to wait for PageWriteback. In the async case,
1180a6bc32b8SMel Gorman 		 * the retry loop is too short and in the sync-light case,
1181a6bc32b8SMel Gorman 		 * the overhead of stalling is too much
118211bc82d6SAndrea Arcangeli 		 */
11832916ecc0SJérôme Glisse 		switch (mode) {
11842916ecc0SJérôme Glisse 		case MIGRATE_SYNC:
11852916ecc0SJérôme Glisse 		case MIGRATE_SYNC_NO_COPY:
11862916ecc0SJérôme Glisse 			break;
11872916ecc0SJérôme Glisse 		default:
118811bc82d6SAndrea Arcangeli 			rc = -EBUSY;
1189ebe75e47SHuang Ying 			goto out;
119011bc82d6SAndrea Arcangeli 		}
1191682a71a1SMatthew Wilcox (Oracle) 		folio_wait_writeback(src);
1192e24f0b8fSChristoph Lameter 	}
119303f15c86SHugh Dickins 
1194e24f0b8fSChristoph Lameter 	/*
1195682a71a1SMatthew Wilcox (Oracle) 	 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1196682a71a1SMatthew Wilcox (Oracle) 	 * we cannot notice that anon_vma is freed while we migrate a page.
11971ce82b69SHugh Dickins 	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1198dc386d4dSKAMEZAWA Hiroyuki 	 * of migration. File cache pages are no problem because of page_lock()
1199989f89c5SKAMEZAWA Hiroyuki 	 * File Caches may use write_page() or lock_page() in migration, then,
1200989f89c5SKAMEZAWA Hiroyuki 	 * just care Anon page here.
12013fe2011fSMel Gorman 	 *
120229eea9b5SMatthew Wilcox (Oracle) 	 * Only folio_get_anon_vma() understands the subtleties of
120303f15c86SHugh Dickins 	 * getting a hold on an anon_vma from outside one of its mms.
120403f15c86SHugh Dickins 	 * But if we cannot get anon_vma, then we won't need it anyway,
120503f15c86SHugh Dickins 	 * because that implies that the anon page is no longer mapped
120603f15c86SHugh Dickins 	 * (and cannot be remapped so long as we hold the page lock).
12073fe2011fSMel Gorman 	 */
1208682a71a1SMatthew Wilcox (Oracle) 	if (folio_test_anon(src) && !folio_test_ksm(src))
120929eea9b5SMatthew Wilcox (Oracle) 		anon_vma = folio_get_anon_vma(src);
121062e1c553SShaohua Li 
12117db7671fSHugh Dickins 	/*
12127db7671fSHugh Dickins 	 * Block others from accessing the new page when we get around to
12137db7671fSHugh Dickins 	 * establishing additional references. We are usually the only one
1214682a71a1SMatthew Wilcox (Oracle) 	 * holding a reference to dst at this point. We used to have a BUG
1215682a71a1SMatthew Wilcox (Oracle) 	 * here if folio_trylock(dst) fails, but would like to allow for
1216682a71a1SMatthew Wilcox (Oracle) 	 * cases where there might be a race with the previous use of dst.
12177db7671fSHugh Dickins 	 * This is much like races on refcount of oldpage: just don't BUG().
12187db7671fSHugh Dickins 	 */
1219682a71a1SMatthew Wilcox (Oracle) 	if (unlikely(!folio_trylock(dst)))
1220ebe75e47SHuang Ying 		goto out;
1221ebe75e47SHuang Ying 	dst_locked = true;
12227db7671fSHugh Dickins 
1223bda807d4SMinchan Kim 	if (unlikely(!is_lru)) {
1224eebb3dabSBaolin Wang 		__migrate_folio_record(dst, old_page_state, anon_vma);
122564c8902eSHuang Ying 		return MIGRATEPAGE_UNMAP;
1226bda807d4SMinchan Kim 	}
1227bda807d4SMinchan Kim 
1228dc386d4dSKAMEZAWA Hiroyuki 	/*
122962e1c553SShaohua Li 	 * Corner case handling:
123062e1c553SShaohua Li 	 * 1. When a new swap-cache page is read into, it is added to the LRU
123162e1c553SShaohua Li 	 * and treated as swapcache but it has no rmap yet.
1232682a71a1SMatthew Wilcox (Oracle) 	 * Calling try_to_unmap() against a src->mapping==NULL page will
123362e1c553SShaohua Li 	 * trigger a BUG.  So handle it here.
1234d12b8951SYang Shi 	 * 2. An orphaned page (see truncate_cleanup_page) might have
123562e1c553SShaohua Li 	 * fs-private metadata. The page can be picked up due to memory
123662e1c553SShaohua Li 	 * offlining.  Everywhere else except page reclaim, the page is
123762e1c553SShaohua Li 	 * invisible to the vm, so the page can not be migrated.  So try to
123862e1c553SShaohua Li 	 * free the metadata, so the page can be freed.
1239dc386d4dSKAMEZAWA Hiroyuki 	 */
1240682a71a1SMatthew Wilcox (Oracle) 	if (!src->mapping) {
1241682a71a1SMatthew Wilcox (Oracle) 		if (folio_test_private(src)) {
1242682a71a1SMatthew Wilcox (Oracle) 			try_to_free_buffers(src);
1243ebe75e47SHuang Ying 			goto out;
124462e1c553SShaohua Li 		}
1245682a71a1SMatthew Wilcox (Oracle) 	} else if (folio_mapped(src)) {
12467db7671fSHugh Dickins 		/* Establish migration ptes */
1247682a71a1SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1248682a71a1SMatthew Wilcox (Oracle) 			       !folio_test_ksm(src) && !anon_vma, src);
1249fb3592c4SHuang Ying 		try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
1250eebb3dabSBaolin Wang 		old_page_state |= PAGE_WAS_MAPPED;
12512ebba6b7SHugh Dickins 	}
1252dc386d4dSKAMEZAWA Hiroyuki 
125364c8902eSHuang Ying 	if (!folio_mapped(src)) {
1254eebb3dabSBaolin Wang 		__migrate_folio_record(dst, old_page_state, anon_vma);
125564c8902eSHuang Ying 		return MIGRATEPAGE_UNMAP;
125664c8902eSHuang Ying 	}
125764c8902eSHuang Ying 
125864c8902eSHuang Ying out:
125980562ba0SHuang Ying 	/*
126080562ba0SHuang Ying 	 * A folio that has not been unmapped will be restored to
126180562ba0SHuang Ying 	 * right list unless we want to retry.
126280562ba0SHuang Ying 	 */
1263fb3592c4SHuang Ying 	if (rc == -EAGAIN)
1264ebe75e47SHuang Ying 		ret = NULL;
126580562ba0SHuang Ying 
1266eebb3dabSBaolin Wang 	migrate_folio_undo_src(src, old_page_state & PAGE_WAS_MAPPED,
1267eebb3dabSBaolin Wang 			       anon_vma, locked, ret);
12684e096ae1SMatthew Wilcox (Oracle) 	migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
126980562ba0SHuang Ying 
127080562ba0SHuang Ying 	return rc;
127180562ba0SHuang Ying }
127280562ba0SHuang Ying 
1273ebe75e47SHuang Ying /* Migrate the folio to the newly allocated folio in dst. */
12744e096ae1SMatthew Wilcox (Oracle) static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
1275ebe75e47SHuang Ying 			      struct folio *src, struct folio *dst,
1276ebe75e47SHuang Ying 			      enum migrate_mode mode, enum migrate_reason reason,
1277ebe75e47SHuang Ying 			      struct list_head *ret)
127864c8902eSHuang Ying {
127964c8902eSHuang Ying 	int rc;
1280eebb3dabSBaolin Wang 	int old_page_state = 0;
128164c8902eSHuang Ying 	struct anon_vma *anon_vma = NULL;
12827e2a5e5aSKefeng Wang 	bool is_lru = !__folio_test_movable(src);
12835dfab109SHuang Ying 	struct list_head *prev;
128464c8902eSHuang Ying 
1285eebb3dabSBaolin Wang 	__migrate_folio_extract(dst, &old_page_state, &anon_vma);
12865dfab109SHuang Ying 	prev = dst->lru.prev;
12875dfab109SHuang Ying 	list_del(&dst->lru);
128864c8902eSHuang Ying 
1289682a71a1SMatthew Wilcox (Oracle) 	rc = move_to_new_folio(dst, src, mode);
1290ebe75e47SHuang Ying 	if (rc)
1291ebe75e47SHuang Ying 		goto out;
12925dfab109SHuang Ying 
129364c8902eSHuang Ying 	if (unlikely(!is_lru))
129464c8902eSHuang Ying 		goto out_unlock_both;
1295e24f0b8fSChristoph Lameter 
1296c3096e67SHugh Dickins 	/*
1297682a71a1SMatthew Wilcox (Oracle) 	 * When successful, push dst to LRU immediately: so that if it
1298c3096e67SHugh Dickins 	 * turns out to be an mlocked page, remove_migration_ptes() will
1299682a71a1SMatthew Wilcox (Oracle) 	 * automatically build up the correct dst->mlock_count for it.
1300c3096e67SHugh Dickins 	 *
1301c3096e67SHugh Dickins 	 * We would like to do something similar for the old page, when
1302c3096e67SHugh Dickins 	 * unsuccessful, and other cases when a page has been temporarily
1303c3096e67SHugh Dickins 	 * isolated from the unevictable LRU: but this case is the easiest.
1304c3096e67SHugh Dickins 	 */
1305682a71a1SMatthew Wilcox (Oracle) 	folio_add_lru(dst);
1306eebb3dabSBaolin Wang 	if (old_page_state & PAGE_WAS_MLOCKED)
1307c3096e67SHugh Dickins 		lru_add_drain();
1308c3096e67SHugh Dickins 
1309eebb3dabSBaolin Wang 	if (old_page_state & PAGE_WAS_MAPPED)
1310ebe75e47SHuang Ying 		remove_migration_ptes(src, dst, false);
13113f6c8272SMel Gorman 
13127db7671fSHugh Dickins out_unlock_both:
1313682a71a1SMatthew Wilcox (Oracle) 	folio_unlock(dst);
1314ebe75e47SHuang Ying 	set_page_owner_migrate_reason(&dst->page, reason);
1315c6c919ebSMinchan Kim 	/*
1316682a71a1SMatthew Wilcox (Oracle) 	 * If migration is successful, decrease refcount of dst,
1317c6c919ebSMinchan Kim 	 * which will not free the page because new page owner increased
1318c3096e67SHugh Dickins 	 * refcounter.
1319c6c919ebSMinchan Kim 	 */
1320682a71a1SMatthew Wilcox (Oracle) 	folio_put(dst);
1321c6c919ebSMinchan Kim 
1322ebe75e47SHuang Ying 	/*
1323ebe75e47SHuang Ying 	 * A folio that has been migrated has all references removed
1324ebe75e47SHuang Ying 	 * and will be freed.
1325ebe75e47SHuang Ying 	 */
1326ebe75e47SHuang Ying 	list_del(&src->lru);
1327ebe75e47SHuang Ying 	/* Drop an anon_vma reference if we took one */
1328ebe75e47SHuang Ying 	if (anon_vma)
1329ebe75e47SHuang Ying 		put_anon_vma(anon_vma);
1330ebe75e47SHuang Ying 	folio_unlock(src);
1331ebe75e47SHuang Ying 	migrate_folio_done(src, reason);
1332ebe75e47SHuang Ying 
1333ebe75e47SHuang Ying 	return rc;
1334ebe75e47SHuang Ying out:
1335ebe75e47SHuang Ying 	/*
1336ebe75e47SHuang Ying 	 * A folio that has not been migrated will be restored to
1337ebe75e47SHuang Ying 	 * right list unless we want to retry.
1338ebe75e47SHuang Ying 	 */
1339ebe75e47SHuang Ying 	if (rc == -EAGAIN) {
1340ebe75e47SHuang Ying 		list_add(&dst->lru, prev);
1341eebb3dabSBaolin Wang 		__migrate_folio_record(dst, old_page_state, anon_vma);
13420dabec93SMinchan Kim 		return rc;
13430dabec93SMinchan Kim 	}
134495a402c3SChristoph Lameter 
1345eebb3dabSBaolin Wang 	migrate_folio_undo_src(src, old_page_state & PAGE_WAS_MAPPED,
1346eebb3dabSBaolin Wang 			       anon_vma, true, ret);
13474e096ae1SMatthew Wilcox (Oracle) 	migrate_folio_undo_dst(dst, true, put_new_folio, private);
134868711a74SDavid Rientjes 
1349e24f0b8fSChristoph Lameter 	return rc;
1350e24f0b8fSChristoph Lameter }
1351b20a3503SChristoph Lameter 
1352e24f0b8fSChristoph Lameter /*
1353290408d4SNaoya Horiguchi  * Counterpart of unmap_and_move_page() for hugepage migration.
1354290408d4SNaoya Horiguchi  *
1355290408d4SNaoya Horiguchi  * This function doesn't wait the completion of hugepage I/O
1356290408d4SNaoya Horiguchi  * because there is no race between I/O and migration for hugepage.
1357290408d4SNaoya Horiguchi  * Note that currently hugepage I/O occurs only in direct I/O
1358290408d4SNaoya Horiguchi  * where no lock is held and PG_writeback is irrelevant,
1359290408d4SNaoya Horiguchi  * and writeback status of all subpages are counted in the reference
1360290408d4SNaoya Horiguchi  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1361290408d4SNaoya Horiguchi  * under direct I/O, the reference of the head page is 512 and a bit more.)
1362290408d4SNaoya Horiguchi  * This means that when we try to migrate hugepage whose subpages are
1363290408d4SNaoya Horiguchi  * doing direct I/O, some references remain after try_to_unmap() and
1364290408d4SNaoya Horiguchi  * hugepage migration fails without data corruption.
1365290408d4SNaoya Horiguchi  *
1366290408d4SNaoya Horiguchi  * There is also no race when direct I/O is issued on the page under migration,
1367290408d4SNaoya Horiguchi  * because then pte is replaced with migration swap entry and direct I/O code
1368290408d4SNaoya Horiguchi  * will wait in the page fault for migration to complete.
1369290408d4SNaoya Horiguchi  */
13704e096ae1SMatthew Wilcox (Oracle) static int unmap_and_move_huge_page(new_folio_t get_new_folio,
13714e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
13724e096ae1SMatthew Wilcox (Oracle) 		struct folio *src, int force, enum migrate_mode mode,
13734e096ae1SMatthew Wilcox (Oracle) 		int reason, struct list_head *ret)
1374290408d4SNaoya Horiguchi {
13754e096ae1SMatthew Wilcox (Oracle) 	struct folio *dst;
13762def7424SHugh Dickins 	int rc = -EAGAIN;
13772ebba6b7SHugh Dickins 	int page_was_mapped = 0;
1378290408d4SNaoya Horiguchi 	struct anon_vma *anon_vma = NULL;
1379c0d0381aSMike Kravetz 	struct address_space *mapping = NULL;
1380290408d4SNaoya Horiguchi 
1381c33db292SMatthew Wilcox (Oracle) 	if (folio_ref_count(src) == 1) {
138271a64f61SMuchun Song 		/* page was freed from under us. So we are done. */
1383ea8e72f4SSidhartha Kumar 		folio_putback_active_hugetlb(src);
138471a64f61SMuchun Song 		return MIGRATEPAGE_SUCCESS;
138571a64f61SMuchun Song 	}
138671a64f61SMuchun Song 
13874e096ae1SMatthew Wilcox (Oracle) 	dst = get_new_folio(src, private);
13884e096ae1SMatthew Wilcox (Oracle) 	if (!dst)
1389290408d4SNaoya Horiguchi 		return -ENOMEM;
1390290408d4SNaoya Horiguchi 
1391c33db292SMatthew Wilcox (Oracle) 	if (!folio_trylock(src)) {
13922916ecc0SJérôme Glisse 		if (!force)
1393290408d4SNaoya Horiguchi 			goto out;
13942916ecc0SJérôme Glisse 		switch (mode) {
13952916ecc0SJérôme Glisse 		case MIGRATE_SYNC:
13962916ecc0SJérôme Glisse 		case MIGRATE_SYNC_NO_COPY:
13972916ecc0SJérôme Glisse 			break;
13982916ecc0SJérôme Glisse 		default:
13992916ecc0SJérôme Glisse 			goto out;
14002916ecc0SJérôme Glisse 		}
1401c33db292SMatthew Wilcox (Oracle) 		folio_lock(src);
1402290408d4SNaoya Horiguchi 	}
1403290408d4SNaoya Horiguchi 
1404cb6acd01SMike Kravetz 	/*
1405cb6acd01SMike Kravetz 	 * Check for pages which are in the process of being freed.  Without
1406c33db292SMatthew Wilcox (Oracle) 	 * folio_mapping() set, hugetlbfs specific move page routine will not
1407cb6acd01SMike Kravetz 	 * be called and we could leak usage counts for subpools.
1408cb6acd01SMike Kravetz 	 */
1409345c62d1SSidhartha Kumar 	if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1410cb6acd01SMike Kravetz 		rc = -EBUSY;
1411cb6acd01SMike Kravetz 		goto out_unlock;
1412cb6acd01SMike Kravetz 	}
1413cb6acd01SMike Kravetz 
1414c33db292SMatthew Wilcox (Oracle) 	if (folio_test_anon(src))
141529eea9b5SMatthew Wilcox (Oracle) 		anon_vma = folio_get_anon_vma(src);
1416290408d4SNaoya Horiguchi 
1417c33db292SMatthew Wilcox (Oracle) 	if (unlikely(!folio_trylock(dst)))
14187db7671fSHugh Dickins 		goto put_anon;
14197db7671fSHugh Dickins 
1420c33db292SMatthew Wilcox (Oracle) 	if (folio_mapped(src)) {
1421a98a2f0cSAlistair Popple 		enum ttu_flags ttu = 0;
1422336bf30eSMike Kravetz 
1423c33db292SMatthew Wilcox (Oracle) 		if (!folio_test_anon(src)) {
1424c0d0381aSMike Kravetz 			/*
1425336bf30eSMike Kravetz 			 * In shared mappings, try_to_unmap could potentially
1426336bf30eSMike Kravetz 			 * call huge_pmd_unshare.  Because of this, take
1427336bf30eSMike Kravetz 			 * semaphore in write mode here and set TTU_RMAP_LOCKED
1428336bf30eSMike Kravetz 			 * to let lower levels know we have taken the lock.
1429c0d0381aSMike Kravetz 			 */
14304e096ae1SMatthew Wilcox (Oracle) 			mapping = hugetlb_page_mapping_lock_write(&src->page);
1431c0d0381aSMike Kravetz 			if (unlikely(!mapping))
1432c0d0381aSMike Kravetz 				goto unlock_put_anon;
1433c0d0381aSMike Kravetz 
14345202978bSMiaohe Lin 			ttu = TTU_RMAP_LOCKED;
1435336bf30eSMike Kravetz 		}
1436336bf30eSMike Kravetz 
14374b8554c5SMatthew Wilcox (Oracle) 		try_to_migrate(src, ttu);
14382ebba6b7SHugh Dickins 		page_was_mapped = 1;
1439336bf30eSMike Kravetz 
14405202978bSMiaohe Lin 		if (ttu & TTU_RMAP_LOCKED)
1441336bf30eSMike Kravetz 			i_mmap_unlock_write(mapping);
14422ebba6b7SHugh Dickins 	}
1443290408d4SNaoya Horiguchi 
1444c33db292SMatthew Wilcox (Oracle) 	if (!folio_mapped(src))
1445e7e3ffebSMatthew Wilcox (Oracle) 		rc = move_to_new_folio(dst, src, mode);
1446290408d4SNaoya Horiguchi 
1447336bf30eSMike Kravetz 	if (page_was_mapped)
14484eecb8b9SMatthew Wilcox (Oracle) 		remove_migration_ptes(src,
14494eecb8b9SMatthew Wilcox (Oracle) 			rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1450290408d4SNaoya Horiguchi 
1451c0d0381aSMike Kravetz unlock_put_anon:
1452c33db292SMatthew Wilcox (Oracle) 	folio_unlock(dst);
14537db7671fSHugh Dickins 
14547db7671fSHugh Dickins put_anon:
1455fd4a4663SHugh Dickins 	if (anon_vma)
14569e60109fSPeter Zijlstra 		put_anon_vma(anon_vma);
14578e6ac7faSAneesh Kumar K.V 
14582def7424SHugh Dickins 	if (rc == MIGRATEPAGE_SUCCESS) {
1459345c62d1SSidhartha Kumar 		move_hugetlb_state(src, dst, reason);
14604e096ae1SMatthew Wilcox (Oracle) 		put_new_folio = NULL;
14612def7424SHugh Dickins 	}
14628e6ac7faSAneesh Kumar K.V 
1463cb6acd01SMike Kravetz out_unlock:
1464c33db292SMatthew Wilcox (Oracle) 	folio_unlock(src);
146509761333SHillf Danton out:
1466dd4ae78aSYang Shi 	if (rc == MIGRATEPAGE_SUCCESS)
1467ea8e72f4SSidhartha Kumar 		folio_putback_active_hugetlb(src);
1468a04840c6SMiaohe Lin 	else if (rc != -EAGAIN)
1469c33db292SMatthew Wilcox (Oracle) 		list_move_tail(&src->lru, ret);
147068711a74SDavid Rientjes 
147168711a74SDavid Rientjes 	/*
147268711a74SDavid Rientjes 	 * If migration was not successful and there's a freeing callback, use
147368711a74SDavid Rientjes 	 * it.  Otherwise, put_page() will drop the reference grabbed during
147468711a74SDavid Rientjes 	 * isolation.
147568711a74SDavid Rientjes 	 */
14764e096ae1SMatthew Wilcox (Oracle) 	if (put_new_folio)
14774e096ae1SMatthew Wilcox (Oracle) 		put_new_folio(dst, private);
147868711a74SDavid Rientjes 	else
1479ea8e72f4SSidhartha Kumar 		folio_putback_active_hugetlb(dst);
148068711a74SDavid Rientjes 
1481290408d4SNaoya Horiguchi 	return rc;
1482290408d4SNaoya Horiguchi }
1483290408d4SNaoya Horiguchi 
1484eaec4e63SHuang Ying static inline int try_split_folio(struct folio *folio, struct list_head *split_folios)
1485d532e2e5SYang Shi {
14869c62ff00SHuang Ying 	int rc;
1487d532e2e5SYang Shi 
1488eaec4e63SHuang Ying 	folio_lock(folio);
1489eaec4e63SHuang Ying 	rc = split_folio_to_list(folio, split_folios);
1490eaec4e63SHuang Ying 	folio_unlock(folio);
1491e6fa8a79SHuang Ying 	if (!rc)
1492eaec4e63SHuang Ying 		list_move_tail(&folio->lru, split_folios);
1493d532e2e5SYang Shi 
1494d532e2e5SYang Shi 	return rc;
1495d532e2e5SYang Shi }
1496d532e2e5SYang Shi 
149742012e04SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
149842012e04SHuang Ying #define NR_MAX_BATCHED_MIGRATION	HPAGE_PMD_NR
149942012e04SHuang Ying #else
150042012e04SHuang Ying #define NR_MAX_BATCHED_MIGRATION	512
150142012e04SHuang Ying #endif
1502e5bfff8bSHuang Ying #define NR_MAX_MIGRATE_PAGES_RETRY	10
15032ef7dbb2SHuang Ying #define NR_MAX_MIGRATE_ASYNC_RETRY	3
15042ef7dbb2SHuang Ying #define NR_MAX_MIGRATE_SYNC_RETRY					\
15052ef7dbb2SHuang Ying 	(NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
1506e5bfff8bSHuang Ying 
15075b855937SHuang Ying struct migrate_pages_stats {
15085b855937SHuang Ying 	int nr_succeeded;	/* Normal and large folios migrated successfully, in
15095b855937SHuang Ying 				   units of base pages */
15105b855937SHuang Ying 	int nr_failed_pages;	/* Normal and large folios failed to be migrated, in
15115b855937SHuang Ying 				   units of base pages.  Untried folios aren't counted */
15125b855937SHuang Ying 	int nr_thp_succeeded;	/* THP migrated successfully */
15135b855937SHuang Ying 	int nr_thp_failed;	/* THP failed to be migrated */
15145b855937SHuang Ying 	int nr_thp_split;	/* THP split before migrating */
1515a259945eSZi Yan 	int nr_split;	/* Large folio (include THP) split before migrating */
15165b855937SHuang Ying };
15175b855937SHuang Ying 
1518290408d4SNaoya Horiguchi /*
1519e5bfff8bSHuang Ying  * Returns the number of hugetlb folios that were not migrated, or an error code
1520e5bfff8bSHuang Ying  * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
1521e5bfff8bSHuang Ying  * any more because the list has become empty or no retryable hugetlb folios
1522e5bfff8bSHuang Ying  * exist any more. It is caller's responsibility to call putback_movable_pages()
1523e5bfff8bSHuang Ying  * only if ret != 0.
1524e5bfff8bSHuang Ying  */
15254e096ae1SMatthew Wilcox (Oracle) static int migrate_hugetlbs(struct list_head *from, new_folio_t get_new_folio,
15264e096ae1SMatthew Wilcox (Oracle) 			    free_folio_t put_new_folio, unsigned long private,
1527e5bfff8bSHuang Ying 			    enum migrate_mode mode, int reason,
1528e5bfff8bSHuang Ying 			    struct migrate_pages_stats *stats,
1529e5bfff8bSHuang Ying 			    struct list_head *ret_folios)
1530e5bfff8bSHuang Ying {
1531e5bfff8bSHuang Ying 	int retry = 1;
1532e5bfff8bSHuang Ying 	int nr_failed = 0;
1533e5bfff8bSHuang Ying 	int nr_retry_pages = 0;
1534e5bfff8bSHuang Ying 	int pass = 0;
1535e5bfff8bSHuang Ying 	struct folio *folio, *folio2;
1536e5bfff8bSHuang Ying 	int rc, nr_pages;
1537e5bfff8bSHuang Ying 
1538e5bfff8bSHuang Ying 	for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
1539e5bfff8bSHuang Ying 		retry = 0;
1540e5bfff8bSHuang Ying 		nr_retry_pages = 0;
1541e5bfff8bSHuang Ying 
1542e5bfff8bSHuang Ying 		list_for_each_entry_safe(folio, folio2, from, lru) {
1543e5bfff8bSHuang Ying 			if (!folio_test_hugetlb(folio))
1544e5bfff8bSHuang Ying 				continue;
1545e5bfff8bSHuang Ying 
1546e5bfff8bSHuang Ying 			nr_pages = folio_nr_pages(folio);
1547e5bfff8bSHuang Ying 
1548e5bfff8bSHuang Ying 			cond_resched();
1549e5bfff8bSHuang Ying 
15506f7d760eSHuang Ying 			/*
15516f7d760eSHuang Ying 			 * Migratability of hugepages depends on architectures and
15526f7d760eSHuang Ying 			 * their size.  This check is necessary because some callers
15536f7d760eSHuang Ying 			 * of hugepage migration like soft offline and memory
15546f7d760eSHuang Ying 			 * hotremove don't walk through page tables or check whether
15556f7d760eSHuang Ying 			 * the hugepage is pmd-based or not before kicking migration.
15566f7d760eSHuang Ying 			 */
15576f7d760eSHuang Ying 			if (!hugepage_migration_supported(folio_hstate(folio))) {
15586f7d760eSHuang Ying 				nr_failed++;
15596f7d760eSHuang Ying 				stats->nr_failed_pages += nr_pages;
15606f7d760eSHuang Ying 				list_move_tail(&folio->lru, ret_folios);
15616f7d760eSHuang Ying 				continue;
15626f7d760eSHuang Ying 			}
15636f7d760eSHuang Ying 
15644e096ae1SMatthew Wilcox (Oracle) 			rc = unmap_and_move_huge_page(get_new_folio,
15654e096ae1SMatthew Wilcox (Oracle) 						      put_new_folio, private,
15664e096ae1SMatthew Wilcox (Oracle) 						      folio, pass > 2, mode,
1567e5bfff8bSHuang Ying 						      reason, ret_folios);
1568e5bfff8bSHuang Ying 			/*
1569e5bfff8bSHuang Ying 			 * The rules are:
1570e5bfff8bSHuang Ying 			 *	Success: hugetlb folio will be put back
1571e5bfff8bSHuang Ying 			 *	-EAGAIN: stay on the from list
1572e5bfff8bSHuang Ying 			 *	-ENOMEM: stay on the from list
1573e5bfff8bSHuang Ying 			 *	Other errno: put on ret_folios list
1574e5bfff8bSHuang Ying 			 */
1575e5bfff8bSHuang Ying 			switch(rc) {
1576e5bfff8bSHuang Ying 			case -ENOMEM:
1577e5bfff8bSHuang Ying 				/*
1578e5bfff8bSHuang Ying 				 * When memory is low, don't bother to try to migrate
1579e5bfff8bSHuang Ying 				 * other folios, just exit.
1580e5bfff8bSHuang Ying 				 */
1581e5bfff8bSHuang Ying 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
1582e5bfff8bSHuang Ying 				return -ENOMEM;
1583e5bfff8bSHuang Ying 			case -EAGAIN:
1584e5bfff8bSHuang Ying 				retry++;
1585e5bfff8bSHuang Ying 				nr_retry_pages += nr_pages;
1586e5bfff8bSHuang Ying 				break;
1587e5bfff8bSHuang Ying 			case MIGRATEPAGE_SUCCESS:
1588e5bfff8bSHuang Ying 				stats->nr_succeeded += nr_pages;
1589e5bfff8bSHuang Ying 				break;
1590e5bfff8bSHuang Ying 			default:
1591e5bfff8bSHuang Ying 				/*
1592e5bfff8bSHuang Ying 				 * Permanent failure (-EBUSY, etc.):
1593e5bfff8bSHuang Ying 				 * unlike -EAGAIN case, the failed folio is
1594e5bfff8bSHuang Ying 				 * removed from migration folio list and not
1595e5bfff8bSHuang Ying 				 * retried in the next outer loop.
1596e5bfff8bSHuang Ying 				 */
1597e5bfff8bSHuang Ying 				nr_failed++;
1598e5bfff8bSHuang Ying 				stats->nr_failed_pages += nr_pages;
1599e5bfff8bSHuang Ying 				break;
1600e5bfff8bSHuang Ying 			}
1601e5bfff8bSHuang Ying 		}
1602e5bfff8bSHuang Ying 	}
1603e5bfff8bSHuang Ying 	/*
1604e5bfff8bSHuang Ying 	 * nr_failed is number of hugetlb folios failed to be migrated.  After
1605e5bfff8bSHuang Ying 	 * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
1606e5bfff8bSHuang Ying 	 * folios as failed.
1607e5bfff8bSHuang Ying 	 */
1608e5bfff8bSHuang Ying 	nr_failed += retry;
1609e5bfff8bSHuang Ying 	stats->nr_failed_pages += nr_retry_pages;
1610e5bfff8bSHuang Ying 
1611e5bfff8bSHuang Ying 	return nr_failed;
1612e5bfff8bSHuang Ying }
1613e5bfff8bSHuang Ying 
16145dfab109SHuang Ying /*
16155dfab109SHuang Ying  * migrate_pages_batch() first unmaps folios in the from list as many as
16165dfab109SHuang Ying  * possible, then move the unmapped folios.
1617fb3592c4SHuang Ying  *
1618fb3592c4SHuang Ying  * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
1619fb3592c4SHuang Ying  * lock or bit when we have locked more than one folio.  Which may cause
1620fb3592c4SHuang Ying  * deadlock (e.g., for loop device).  So, if mode != MIGRATE_ASYNC, the
1621fb3592c4SHuang Ying  * length of the from list must be <= 1.
16225dfab109SHuang Ying  */
16234e096ae1SMatthew Wilcox (Oracle) static int migrate_pages_batch(struct list_head *from,
16244e096ae1SMatthew Wilcox (Oracle) 		new_folio_t get_new_folio, free_folio_t put_new_folio,
16254e096ae1SMatthew Wilcox (Oracle) 		unsigned long private, enum migrate_mode mode, int reason,
16264e096ae1SMatthew Wilcox (Oracle) 		struct list_head *ret_folios, struct list_head *split_folios,
16274e096ae1SMatthew Wilcox (Oracle) 		struct migrate_pages_stats *stats, int nr_pass)
162842012e04SHuang Ying {
1629a21d2133SHuang Ying 	int retry = 1;
163042012e04SHuang Ying 	int thp_retry = 1;
163142012e04SHuang Ying 	int nr_failed = 0;
163242012e04SHuang Ying 	int nr_retry_pages = 0;
163342012e04SHuang Ying 	int pass = 0;
163442012e04SHuang Ying 	bool is_thp = false;
1635a259945eSZi Yan 	bool is_large = false;
16365dfab109SHuang Ying 	struct folio *folio, *folio2, *dst = NULL, *dst2;
1637a21d2133SHuang Ying 	int rc, rc_saved = 0, nr_pages;
16385dfab109SHuang Ying 	LIST_HEAD(unmap_folios);
16395dfab109SHuang Ying 	LIST_HEAD(dst_folios);
164042012e04SHuang Ying 	bool nosplit = (reason == MR_NUMA_MISPLACED);
164142012e04SHuang Ying 
1642fb3592c4SHuang Ying 	VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
1643fb3592c4SHuang Ying 			!list_empty(from) && !list_is_singular(from));
1644a21d2133SHuang Ying 
1645124abcedSHuang Ying 	for (pass = 0; pass < nr_pass && retry; pass++) {
164642012e04SHuang Ying 		retry = 0;
164742012e04SHuang Ying 		thp_retry = 0;
164842012e04SHuang Ying 		nr_retry_pages = 0;
164942012e04SHuang Ying 
165042012e04SHuang Ying 		list_for_each_entry_safe(folio, folio2, from, lru) {
1651a259945eSZi Yan 			is_large = folio_test_large(folio);
1652a259945eSZi Yan 			is_thp = is_large && folio_test_pmd_mappable(folio);
165342012e04SHuang Ying 			nr_pages = folio_nr_pages(folio);
165442012e04SHuang Ying 
165542012e04SHuang Ying 			cond_resched();
165642012e04SHuang Ying 
16576f7d760eSHuang Ying 			/*
16586f7d760eSHuang Ying 			 * Large folio migration might be unsupported or
16596f7d760eSHuang Ying 			 * the allocation might be failed so we should retry
16606f7d760eSHuang Ying 			 * on the same folio with the large folio split
16616f7d760eSHuang Ying 			 * to normal folios.
16626f7d760eSHuang Ying 			 *
16636f7d760eSHuang Ying 			 * Split folios are put in split_folios, and
16646f7d760eSHuang Ying 			 * we will migrate them after the rest of the
16656f7d760eSHuang Ying 			 * list is processed.
16666f7d760eSHuang Ying 			 */
16676f7d760eSHuang Ying 			if (!thp_migration_supported() && is_thp) {
1668124abcedSHuang Ying 				nr_failed++;
16696f7d760eSHuang Ying 				stats->nr_thp_failed++;
1670a21d2133SHuang Ying 				if (!try_split_folio(folio, split_folios)) {
16716f7d760eSHuang Ying 					stats->nr_thp_split++;
1672a259945eSZi Yan 					stats->nr_split++;
16736f7d760eSHuang Ying 					continue;
16746f7d760eSHuang Ying 				}
16756f7d760eSHuang Ying 				stats->nr_failed_pages += nr_pages;
16766f7d760eSHuang Ying 				list_move_tail(&folio->lru, ret_folios);
16776f7d760eSHuang Ying 				continue;
16786f7d760eSHuang Ying 			}
16796f7d760eSHuang Ying 
16804e096ae1SMatthew Wilcox (Oracle) 			rc = migrate_folio_unmap(get_new_folio, put_new_folio,
16814e096ae1SMatthew Wilcox (Oracle) 					private, folio, &dst, mode, reason,
16824e096ae1SMatthew Wilcox (Oracle) 					ret_folios);
168342012e04SHuang Ying 			/*
168442012e04SHuang Ying 			 * The rules are:
168542012e04SHuang Ying 			 *	Success: folio will be freed
16865dfab109SHuang Ying 			 *	Unmap: folio will be put on unmap_folios list,
16875dfab109SHuang Ying 			 *	       dst folio put on dst_folios list
168842012e04SHuang Ying 			 *	-EAGAIN: stay on the from list
168942012e04SHuang Ying 			 *	-ENOMEM: stay on the from list
169042012e04SHuang Ying 			 *	Other errno: put on ret_folios list
169142012e04SHuang Ying 			 */
169242012e04SHuang Ying 			switch(rc) {
169342012e04SHuang Ying 			case -ENOMEM:
169442012e04SHuang Ying 				/*
169542012e04SHuang Ying 				 * When memory is low, don't bother to try to migrate
16965dfab109SHuang Ying 				 * other folios, move unmapped folios, then exit.
169742012e04SHuang Ying 				 */
1698124abcedSHuang Ying 				nr_failed++;
169942012e04SHuang Ying 				stats->nr_thp_failed += is_thp;
170042012e04SHuang Ying 				/* Large folio NUMA faulting doesn't split to retry. */
1701a259945eSZi Yan 				if (is_large && !nosplit) {
1702a21d2133SHuang Ying 					int ret = try_split_folio(folio, split_folios);
170342012e04SHuang Ying 
170442012e04SHuang Ying 					if (!ret) {
170542012e04SHuang Ying 						stats->nr_thp_split += is_thp;
170649cac03aSZi Yan 						stats->nr_split++;
170742012e04SHuang Ying 						break;
170842012e04SHuang Ying 					} else if (reason == MR_LONGTERM_PIN &&
170942012e04SHuang Ying 						   ret == -EAGAIN) {
171042012e04SHuang Ying 						/*
171142012e04SHuang Ying 						 * Try again to split large folio to
171242012e04SHuang Ying 						 * mitigate the failure of longterm pinning.
171342012e04SHuang Ying 						 */
1714124abcedSHuang Ying 						retry++;
171542012e04SHuang Ying 						thp_retry += is_thp;
171642012e04SHuang Ying 						nr_retry_pages += nr_pages;
1717851ae642SHuang Ying 						/* Undo duplicated failure counting. */
1718124abcedSHuang Ying 						nr_failed--;
1719851ae642SHuang Ying 						stats->nr_thp_failed -= is_thp;
172042012e04SHuang Ying 						break;
172142012e04SHuang Ying 					}
172242012e04SHuang Ying 				}
172342012e04SHuang Ying 
172442012e04SHuang Ying 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
172542012e04SHuang Ying 				/* nr_failed isn't updated for not used */
172642012e04SHuang Ying 				stats->nr_thp_failed += thp_retry;
17275dfab109SHuang Ying 				rc_saved = rc;
17285dfab109SHuang Ying 				if (list_empty(&unmap_folios))
172942012e04SHuang Ying 					goto out;
17305dfab109SHuang Ying 				else
17315dfab109SHuang Ying 					goto move;
173242012e04SHuang Ying 			case -EAGAIN:
173342012e04SHuang Ying 				retry++;
1734124abcedSHuang Ying 				thp_retry += is_thp;
173542012e04SHuang Ying 				nr_retry_pages += nr_pages;
173642012e04SHuang Ying 				break;
173742012e04SHuang Ying 			case MIGRATEPAGE_SUCCESS:
173842012e04SHuang Ying 				stats->nr_succeeded += nr_pages;
173942012e04SHuang Ying 				stats->nr_thp_succeeded += is_thp;
174042012e04SHuang Ying 				break;
17415dfab109SHuang Ying 			case MIGRATEPAGE_UNMAP:
17425dfab109SHuang Ying 				list_move_tail(&folio->lru, &unmap_folios);
17435dfab109SHuang Ying 				list_add_tail(&dst->lru, &dst_folios);
17445dfab109SHuang Ying 				break;
174542012e04SHuang Ying 			default:
174642012e04SHuang Ying 				/*
174742012e04SHuang Ying 				 * Permanent failure (-EBUSY, etc.):
174842012e04SHuang Ying 				 * unlike -EAGAIN case, the failed folio is
174942012e04SHuang Ying 				 * removed from migration folio list and not
175042012e04SHuang Ying 				 * retried in the next outer loop.
175142012e04SHuang Ying 				 */
175242012e04SHuang Ying 				nr_failed++;
1753124abcedSHuang Ying 				stats->nr_thp_failed += is_thp;
175442012e04SHuang Ying 				stats->nr_failed_pages += nr_pages;
175542012e04SHuang Ying 				break;
175642012e04SHuang Ying 			}
175742012e04SHuang Ying 		}
175842012e04SHuang Ying 	}
175942012e04SHuang Ying 	nr_failed += retry;
176042012e04SHuang Ying 	stats->nr_thp_failed += thp_retry;
176142012e04SHuang Ying 	stats->nr_failed_pages += nr_retry_pages;
17625dfab109SHuang Ying move:
17637e12beb8SHuang Ying 	/* Flush TLBs for all unmapped folios */
17647e12beb8SHuang Ying 	try_to_unmap_flush();
17657e12beb8SHuang Ying 
17665dfab109SHuang Ying 	retry = 1;
1767124abcedSHuang Ying 	for (pass = 0; pass < nr_pass && retry; pass++) {
17685dfab109SHuang Ying 		retry = 0;
17695dfab109SHuang Ying 		thp_retry = 0;
17705dfab109SHuang Ying 		nr_retry_pages = 0;
17715dfab109SHuang Ying 
17725dfab109SHuang Ying 		dst = list_first_entry(&dst_folios, struct folio, lru);
17735dfab109SHuang Ying 		dst2 = list_next_entry(dst, lru);
17745dfab109SHuang Ying 		list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1775124abcedSHuang Ying 			is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
17765dfab109SHuang Ying 			nr_pages = folio_nr_pages(folio);
17775dfab109SHuang Ying 
17785dfab109SHuang Ying 			cond_resched();
17795dfab109SHuang Ying 
17804e096ae1SMatthew Wilcox (Oracle) 			rc = migrate_folio_move(put_new_folio, private,
17815dfab109SHuang Ying 						folio, dst, mode,
17825dfab109SHuang Ying 						reason, ret_folios);
17835dfab109SHuang Ying 			/*
17845dfab109SHuang Ying 			 * The rules are:
17855dfab109SHuang Ying 			 *	Success: folio will be freed
17865dfab109SHuang Ying 			 *	-EAGAIN: stay on the unmap_folios list
17875dfab109SHuang Ying 			 *	Other errno: put on ret_folios list
17885dfab109SHuang Ying 			 */
17895dfab109SHuang Ying 			switch(rc) {
17905dfab109SHuang Ying 			case -EAGAIN:
17915dfab109SHuang Ying 				retry++;
1792124abcedSHuang Ying 				thp_retry += is_thp;
17935dfab109SHuang Ying 				nr_retry_pages += nr_pages;
17945dfab109SHuang Ying 				break;
17955dfab109SHuang Ying 			case MIGRATEPAGE_SUCCESS:
17965dfab109SHuang Ying 				stats->nr_succeeded += nr_pages;
17975dfab109SHuang Ying 				stats->nr_thp_succeeded += is_thp;
17985dfab109SHuang Ying 				break;
17995dfab109SHuang Ying 			default:
18005dfab109SHuang Ying 				nr_failed++;
1801124abcedSHuang Ying 				stats->nr_thp_failed += is_thp;
18025dfab109SHuang Ying 				stats->nr_failed_pages += nr_pages;
18035dfab109SHuang Ying 				break;
18045dfab109SHuang Ying 			}
18055dfab109SHuang Ying 			dst = dst2;
18065dfab109SHuang Ying 			dst2 = list_next_entry(dst, lru);
18075dfab109SHuang Ying 		}
18085dfab109SHuang Ying 	}
18095dfab109SHuang Ying 	nr_failed += retry;
18105dfab109SHuang Ying 	stats->nr_thp_failed += thp_retry;
18115dfab109SHuang Ying 	stats->nr_failed_pages += nr_retry_pages;
18125dfab109SHuang Ying 
1813124abcedSHuang Ying 	rc = rc_saved ? : nr_failed;
18145dfab109SHuang Ying out:
18155dfab109SHuang Ying 	/* Cleanup remaining folios */
18165dfab109SHuang Ying 	dst = list_first_entry(&dst_folios, struct folio, lru);
18175dfab109SHuang Ying 	dst2 = list_next_entry(dst, lru);
18185dfab109SHuang Ying 	list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1819eebb3dabSBaolin Wang 		int old_page_state = 0;
18205dfab109SHuang Ying 		struct anon_vma *anon_vma = NULL;
18215dfab109SHuang Ying 
1822eebb3dabSBaolin Wang 		__migrate_folio_extract(dst, &old_page_state, &anon_vma);
1823eebb3dabSBaolin Wang 		migrate_folio_undo_src(folio, old_page_state & PAGE_WAS_MAPPED,
1824eebb3dabSBaolin Wang 				       anon_vma, true, ret_folios);
18255dfab109SHuang Ying 		list_del(&dst->lru);
18264e096ae1SMatthew Wilcox (Oracle) 		migrate_folio_undo_dst(dst, true, put_new_folio, private);
18275dfab109SHuang Ying 		dst = dst2;
18285dfab109SHuang Ying 		dst2 = list_next_entry(dst, lru);
18295dfab109SHuang Ying 	}
18305dfab109SHuang Ying 
183142012e04SHuang Ying 	return rc;
183242012e04SHuang Ying }
183342012e04SHuang Ying 
18344e096ae1SMatthew Wilcox (Oracle) static int migrate_pages_sync(struct list_head *from, new_folio_t get_new_folio,
18354e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
18364e096ae1SMatthew Wilcox (Oracle) 		enum migrate_mode mode, int reason,
18374e096ae1SMatthew Wilcox (Oracle) 		struct list_head *ret_folios, struct list_head *split_folios,
18384e096ae1SMatthew Wilcox (Oracle) 		struct migrate_pages_stats *stats)
18392ef7dbb2SHuang Ying {
18402ef7dbb2SHuang Ying 	int rc, nr_failed = 0;
18412ef7dbb2SHuang Ying 	LIST_HEAD(folios);
18422ef7dbb2SHuang Ying 	struct migrate_pages_stats astats;
18432ef7dbb2SHuang Ying 
18442ef7dbb2SHuang Ying 	memset(&astats, 0, sizeof(astats));
18452ef7dbb2SHuang Ying 	/* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
18464e096ae1SMatthew Wilcox (Oracle) 	rc = migrate_pages_batch(from, get_new_folio, put_new_folio, private, MIGRATE_ASYNC,
18472ef7dbb2SHuang Ying 				 reason, &folios, split_folios, &astats,
18482ef7dbb2SHuang Ying 				 NR_MAX_MIGRATE_ASYNC_RETRY);
18492ef7dbb2SHuang Ying 	stats->nr_succeeded += astats.nr_succeeded;
18502ef7dbb2SHuang Ying 	stats->nr_thp_succeeded += astats.nr_thp_succeeded;
18512ef7dbb2SHuang Ying 	stats->nr_thp_split += astats.nr_thp_split;
1852a259945eSZi Yan 	stats->nr_split += astats.nr_split;
18532ef7dbb2SHuang Ying 	if (rc < 0) {
18542ef7dbb2SHuang Ying 		stats->nr_failed_pages += astats.nr_failed_pages;
18552ef7dbb2SHuang Ying 		stats->nr_thp_failed += astats.nr_thp_failed;
18562ef7dbb2SHuang Ying 		list_splice_tail(&folios, ret_folios);
18572ef7dbb2SHuang Ying 		return rc;
18582ef7dbb2SHuang Ying 	}
18592ef7dbb2SHuang Ying 	stats->nr_thp_failed += astats.nr_thp_split;
1860a259945eSZi Yan 	/*
1861a259945eSZi Yan 	 * Do not count rc, as pages will be retried below.
1862a259945eSZi Yan 	 * Count nr_split only, since it includes nr_thp_split.
1863a259945eSZi Yan 	 */
1864a259945eSZi Yan 	nr_failed += astats.nr_split;
18652ef7dbb2SHuang Ying 	/*
18662ef7dbb2SHuang Ying 	 * Fall back to migrate all failed folios one by one synchronously. All
18672ef7dbb2SHuang Ying 	 * failed folios except split THPs will be retried, so their failure
18682ef7dbb2SHuang Ying 	 * isn't counted
18692ef7dbb2SHuang Ying 	 */
18702ef7dbb2SHuang Ying 	list_splice_tail_init(&folios, from);
18712ef7dbb2SHuang Ying 	while (!list_empty(from)) {
18722ef7dbb2SHuang Ying 		list_move(from->next, &folios);
18734e096ae1SMatthew Wilcox (Oracle) 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
18742ef7dbb2SHuang Ying 					 private, mode, reason, ret_folios,
18752ef7dbb2SHuang Ying 					 split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
18762ef7dbb2SHuang Ying 		list_splice_tail_init(&folios, ret_folios);
18772ef7dbb2SHuang Ying 		if (rc < 0)
18782ef7dbb2SHuang Ying 			return rc;
18792ef7dbb2SHuang Ying 		nr_failed += rc;
18802ef7dbb2SHuang Ying 	}
18812ef7dbb2SHuang Ying 
18822ef7dbb2SHuang Ying 	return nr_failed;
18832ef7dbb2SHuang Ying }
18842ef7dbb2SHuang Ying 
1885e24f0b8fSChristoph Lameter /*
1886eaec4e63SHuang Ying  * migrate_pages - migrate the folios specified in a list, to the free folios
1887c73e5c9cSSrivatsa S. Bhat  *		   supplied as the target for the page migration
1888e24f0b8fSChristoph Lameter  *
1889eaec4e63SHuang Ying  * @from:		The list of folios to be migrated.
18904e096ae1SMatthew Wilcox (Oracle)  * @get_new_folio:	The function used to allocate free folios to be used
1891eaec4e63SHuang Ying  *			as the target of the folio migration.
18924e096ae1SMatthew Wilcox (Oracle)  * @put_new_folio:	The function used to free target folios if migration
189368711a74SDavid Rientjes  *			fails, or NULL if no special handling is necessary.
18944e096ae1SMatthew Wilcox (Oracle)  * @private:		Private data to be passed on to get_new_folio()
1895c73e5c9cSSrivatsa S. Bhat  * @mode:		The migration mode that specifies the constraints for
1896eaec4e63SHuang Ying  *			folio migration, if any.
1897eaec4e63SHuang Ying  * @reason:		The reason for folio migration.
1898eaec4e63SHuang Ying  * @ret_succeeded:	Set to the number of folios migrated successfully if
18995ac95884SYang Shi  *			the caller passes a non-NULL pointer.
1900e24f0b8fSChristoph Lameter  *
1901e5bfff8bSHuang Ying  * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
1902e5bfff8bSHuang Ying  * are movable any more because the list has become empty or no retryable folios
1903e5bfff8bSHuang Ying  * exist any more. It is caller's responsibility to call putback_movable_pages()
1904e5bfff8bSHuang Ying  * only if ret != 0.
1905e24f0b8fSChristoph Lameter  *
1906eaec4e63SHuang Ying  * Returns the number of {normal folio, large folio, hugetlb} that were not
1907eaec4e63SHuang Ying  * migrated, or an error code. The number of large folio splits will be
1908eaec4e63SHuang Ying  * considered as the number of non-migrated large folio, no matter how many
1909eaec4e63SHuang Ying  * split folios of the large folio are migrated successfully.
1910e24f0b8fSChristoph Lameter  */
19114e096ae1SMatthew Wilcox (Oracle) int migrate_pages(struct list_head *from, new_folio_t get_new_folio,
19124e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
19135ac95884SYang Shi 		enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1914e24f0b8fSChristoph Lameter {
191542012e04SHuang Ying 	int rc, rc_gather;
19162ef7dbb2SHuang Ying 	int nr_pages;
1917eaec4e63SHuang Ying 	struct folio *folio, *folio2;
191842012e04SHuang Ying 	LIST_HEAD(folios);
1919eaec4e63SHuang Ying 	LIST_HEAD(ret_folios);
1920a21d2133SHuang Ying 	LIST_HEAD(split_folios);
19215b855937SHuang Ying 	struct migrate_pages_stats stats;
19222d1db3b1SChristoph Lameter 
19237bc1aec5SLiam Mark 	trace_mm_migrate_pages_start(mode, reason);
19247bc1aec5SLiam Mark 
19255b855937SHuang Ying 	memset(&stats, 0, sizeof(stats));
1926e24f0b8fSChristoph Lameter 
19274e096ae1SMatthew Wilcox (Oracle) 	rc_gather = migrate_hugetlbs(from, get_new_folio, put_new_folio, private,
192842012e04SHuang Ying 				     mode, reason, &stats, &ret_folios);
192942012e04SHuang Ying 	if (rc_gather < 0)
193095a402c3SChristoph Lameter 		goto out;
1931fb3592c4SHuang Ying 
193242012e04SHuang Ying again:
193342012e04SHuang Ying 	nr_pages = 0;
1934b20a3503SChristoph Lameter 	list_for_each_entry_safe(folio, folio2, from, lru) {
1935e5bfff8bSHuang Ying 		/* Retried hugetlb folios will be kept in list  */
1936e5bfff8bSHuang Ying 		if (folio_test_hugetlb(folio)) {
1937e5bfff8bSHuang Ying 			list_move_tail(&folio->lru, &ret_folios);
1938e5bfff8bSHuang Ying 			continue;
1939eaec4e63SHuang Ying 		}
1940f430893bSMiaohe Lin 
194142012e04SHuang Ying 		nr_pages += folio_nr_pages(folio);
19422ef7dbb2SHuang Ying 		if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
1943e24f0b8fSChristoph Lameter 			break;
1944b20a3503SChristoph Lameter 	}
19452ef7dbb2SHuang Ying 	if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
1946fb3592c4SHuang Ying 		list_cut_before(&folios, from, &folio2->lru);
194742012e04SHuang Ying 	else
194842012e04SHuang Ying 		list_splice_init(from, &folios);
19492ef7dbb2SHuang Ying 	if (mode == MIGRATE_ASYNC)
19504e096ae1SMatthew Wilcox (Oracle) 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
19514e096ae1SMatthew Wilcox (Oracle) 				private, mode, reason, &ret_folios,
19524e096ae1SMatthew Wilcox (Oracle) 				&split_folios, &stats,
1953a21d2133SHuang Ying 				NR_MAX_MIGRATE_PAGES_RETRY);
19542ef7dbb2SHuang Ying 	else
19554e096ae1SMatthew Wilcox (Oracle) 		rc = migrate_pages_sync(&folios, get_new_folio, put_new_folio,
19564e096ae1SMatthew Wilcox (Oracle) 				private, mode, reason, &ret_folios,
19574e096ae1SMatthew Wilcox (Oracle) 				&split_folios, &stats);
195842012e04SHuang Ying 	list_splice_tail_init(&folios, &ret_folios);
195942012e04SHuang Ying 	if (rc < 0) {
196042012e04SHuang Ying 		rc_gather = rc;
1961a21d2133SHuang Ying 		list_splice_tail(&split_folios, &ret_folios);
1962b20a3503SChristoph Lameter 		goto out;
1963b20a3503SChristoph Lameter 	}
1964a21d2133SHuang Ying 	if (!list_empty(&split_folios)) {
1965a21d2133SHuang Ying 		/*
1966a21d2133SHuang Ying 		 * Failure isn't counted since all split folios of a large folio
1967a21d2133SHuang Ying 		 * is counted as 1 failure already.  And, we only try to migrate
1968a21d2133SHuang Ying 		 * with minimal effort, force MIGRATE_ASYNC mode and retry once.
1969a21d2133SHuang Ying 		 */
19704e096ae1SMatthew Wilcox (Oracle) 		migrate_pages_batch(&split_folios, get_new_folio,
19714e096ae1SMatthew Wilcox (Oracle) 				put_new_folio, private, MIGRATE_ASYNC, reason,
19724e096ae1SMatthew Wilcox (Oracle) 				&ret_folios, NULL, &stats, 1);
1973a21d2133SHuang Ying 		list_splice_tail_init(&split_folios, &ret_folios);
1974a21d2133SHuang Ying 	}
197542012e04SHuang Ying 	rc_gather += rc;
197642012e04SHuang Ying 	if (!list_empty(from))
197742012e04SHuang Ying 		goto again;
197895a402c3SChristoph Lameter out:
1979dd4ae78aSYang Shi 	/*
1980eaec4e63SHuang Ying 	 * Put the permanent failure folio back to migration list, they
1981dd4ae78aSYang Shi 	 * will be put back to the right list by the caller.
1982dd4ae78aSYang Shi 	 */
1983eaec4e63SHuang Ying 	list_splice(&ret_folios, from);
1984dd4ae78aSYang Shi 
198503e5f82eSBaolin Wang 	/*
1986eaec4e63SHuang Ying 	 * Return 0 in case all split folios of fail-to-migrate large folios
1987eaec4e63SHuang Ying 	 * are migrated successfully.
198803e5f82eSBaolin Wang 	 */
198903e5f82eSBaolin Wang 	if (list_empty(from))
199042012e04SHuang Ying 		rc_gather = 0;
199103e5f82eSBaolin Wang 
19925b855937SHuang Ying 	count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
19935b855937SHuang Ying 	count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
19945b855937SHuang Ying 	count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
19955b855937SHuang Ying 	count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
19965b855937SHuang Ying 	count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
19975b855937SHuang Ying 	trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
19985b855937SHuang Ying 			       stats.nr_thp_succeeded, stats.nr_thp_failed,
199949cac03aSZi Yan 			       stats.nr_thp_split, stats.nr_split, mode,
200049cac03aSZi Yan 			       reason);
20017b2a2d4aSMel Gorman 
20025ac95884SYang Shi 	if (ret_succeeded)
20035b855937SHuang Ying 		*ret_succeeded = stats.nr_succeeded;
20045ac95884SYang Shi 
200542012e04SHuang Ying 	return rc_gather;
2006b20a3503SChristoph Lameter }
2007b20a3503SChristoph Lameter 
20084e096ae1SMatthew Wilcox (Oracle) struct folio *alloc_migration_target(struct folio *src, unsigned long private)
2009b4b38223SJoonsoo Kim {
201019fc7bedSJoonsoo Kim 	struct migration_target_control *mtc;
201119fc7bedSJoonsoo Kim 	gfp_t gfp_mask;
2012b4b38223SJoonsoo Kim 	unsigned int order = 0;
201319fc7bedSJoonsoo Kim 	int nid;
201419fc7bedSJoonsoo Kim 	int zidx;
201519fc7bedSJoonsoo Kim 
201619fc7bedSJoonsoo Kim 	mtc = (struct migration_target_control *)private;
201719fc7bedSJoonsoo Kim 	gfp_mask = mtc->gfp_mask;
201819fc7bedSJoonsoo Kim 	nid = mtc->nid;
201919fc7bedSJoonsoo Kim 	if (nid == NUMA_NO_NODE)
20204e096ae1SMatthew Wilcox (Oracle) 		nid = folio_nid(src);
2021b4b38223SJoonsoo Kim 
20224e096ae1SMatthew Wilcox (Oracle) 	if (folio_test_hugetlb(src)) {
20234e096ae1SMatthew Wilcox (Oracle) 		struct hstate *h = folio_hstate(src);
2024d92bbc27SJoonsoo Kim 
202519fc7bedSJoonsoo Kim 		gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
20264e096ae1SMatthew Wilcox (Oracle) 		return alloc_hugetlb_folio_nodemask(h, nid,
2027e37d3e83SSidhartha Kumar 						mtc->nmask, gfp_mask);
2028d92bbc27SJoonsoo Kim 	}
2029b4b38223SJoonsoo Kim 
20304e096ae1SMatthew Wilcox (Oracle) 	if (folio_test_large(src)) {
20319933a0c8SJoonsoo Kim 		/*
20329933a0c8SJoonsoo Kim 		 * clear __GFP_RECLAIM to make the migration callback
20339933a0c8SJoonsoo Kim 		 * consistent with regular THP allocations.
20349933a0c8SJoonsoo Kim 		 */
20359933a0c8SJoonsoo Kim 		gfp_mask &= ~__GFP_RECLAIM;
2036b4b38223SJoonsoo Kim 		gfp_mask |= GFP_TRANSHUGE;
20374e096ae1SMatthew Wilcox (Oracle) 		order = folio_order(src);
2038b4b38223SJoonsoo Kim 	}
20394e096ae1SMatthew Wilcox (Oracle) 	zidx = zone_idx(folio_zone(src));
204019fc7bedSJoonsoo Kim 	if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
2041b4b38223SJoonsoo Kim 		gfp_mask |= __GFP_HIGHMEM;
2042b4b38223SJoonsoo Kim 
20434e096ae1SMatthew Wilcox (Oracle) 	return __folio_alloc(gfp_mask, order, nid, mtc->nmask);
2044b4b38223SJoonsoo Kim }
2045b4b38223SJoonsoo Kim 
2046742755a1SChristoph Lameter #ifdef CONFIG_NUMA
2047742755a1SChristoph Lameter 
2048a49bd4d7SMichal Hocko static int store_status(int __user *status, int start, int value, int nr)
2049742755a1SChristoph Lameter {
2050a49bd4d7SMichal Hocko 	while (nr-- > 0) {
2051a49bd4d7SMichal Hocko 		if (put_user(value, status + start))
2052a49bd4d7SMichal Hocko 			return -EFAULT;
2053a49bd4d7SMichal Hocko 		start++;
2054a49bd4d7SMichal Hocko 	}
2055742755a1SChristoph Lameter 
2056a49bd4d7SMichal Hocko 	return 0;
2057a49bd4d7SMichal Hocko }
2058742755a1SChristoph Lameter 
2059ec47e250SGregory Price static int do_move_pages_to_node(struct list_head *pagelist, int node)
2060a49bd4d7SMichal Hocko {
2061a49bd4d7SMichal Hocko 	int err;
2062a0976311SJoonsoo Kim 	struct migration_target_control mtc = {
2063a0976311SJoonsoo Kim 		.nid = node,
2064a0976311SJoonsoo Kim 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
2065a0976311SJoonsoo Kim 	};
2066742755a1SChristoph Lameter 
2067a0976311SJoonsoo Kim 	err = migrate_pages(pagelist, alloc_migration_target, NULL,
20685ac95884SYang Shi 		(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
2069a49bd4d7SMichal Hocko 	if (err)
2070a49bd4d7SMichal Hocko 		putback_movable_pages(pagelist);
2071a49bd4d7SMichal Hocko 	return err;
2072742755a1SChristoph Lameter }
2073742755a1SChristoph Lameter 
2074742755a1SChristoph Lameter /*
2075a49bd4d7SMichal Hocko  * Resolves the given address to a struct page, isolates it from the LRU and
2076a49bd4d7SMichal Hocko  * puts it to the given pagelist.
2077e0153fc2SYang Shi  * Returns:
2078e0153fc2SYang Shi  *     errno - if the page cannot be found/isolated
2079e0153fc2SYang Shi  *     0 - when it doesn't have to be migrated because it is already on the
2080e0153fc2SYang Shi  *         target node
2081e0153fc2SYang Shi  *     1 - when it has been queued
2082742755a1SChristoph Lameter  */
2083428e106aSKirill A. Shutemov static int add_page_for_migration(struct mm_struct *mm, const void __user *p,
2084a49bd4d7SMichal Hocko 		int node, struct list_head *pagelist, bool migrate_all)
2085742755a1SChristoph Lameter {
2086742755a1SChristoph Lameter 	struct vm_area_struct *vma;
2087428e106aSKirill A. Shutemov 	unsigned long addr;
2088742755a1SChristoph Lameter 	struct page *page;
2089d64cfccbSKefeng Wang 	struct folio *folio;
2090a49bd4d7SMichal Hocko 	int err;
2091742755a1SChristoph Lameter 
2092d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
2093428e106aSKirill A. Shutemov 	addr = (unsigned long)untagged_addr_remote(mm, p);
2094428e106aSKirill A. Shutemov 
2095742755a1SChristoph Lameter 	err = -EFAULT;
2096cb1c37b1SMiaohe Lin 	vma = vma_lookup(mm, addr);
2097cb1c37b1SMiaohe Lin 	if (!vma || !vma_migratable(vma))
2098a49bd4d7SMichal Hocko 		goto out;
2099742755a1SChristoph Lameter 
2100d899844eSKirill A. Shutemov 	/* FOLL_DUMP to ignore special (like zero) pages */
210187d2762eSMiaohe Lin 	page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
210289f5b7daSLinus Torvalds 
210389f5b7daSLinus Torvalds 	err = PTR_ERR(page);
210489f5b7daSLinus Torvalds 	if (IS_ERR(page))
2105a49bd4d7SMichal Hocko 		goto out;
210689f5b7daSLinus Torvalds 
2107742755a1SChristoph Lameter 	err = -ENOENT;
2108f7091ed6SHaiyue Wang 	if (!page)
2109a49bd4d7SMichal Hocko 		goto out;
2110742755a1SChristoph Lameter 
2111d64cfccbSKefeng Wang 	folio = page_folio(page);
2112d64cfccbSKefeng Wang 	if (folio_is_zone_device(folio))
2113d64cfccbSKefeng Wang 		goto out_putfolio;
2114f7091ed6SHaiyue Wang 
2115a49bd4d7SMichal Hocko 	err = 0;
2116d64cfccbSKefeng Wang 	if (folio_nid(folio) == node)
2117d64cfccbSKefeng Wang 		goto out_putfolio;
2118742755a1SChristoph Lameter 
2119742755a1SChristoph Lameter 	err = -EACCES;
2120a49bd4d7SMichal Hocko 	if (page_mapcount(page) > 1 && !migrate_all)
2121d64cfccbSKefeng Wang 		goto out_putfolio;
2122742755a1SChristoph Lameter 
2123f7f9c00dSBaolin Wang 	err = -EBUSY;
2124fa1df3f6SKefeng Wang 	if (folio_test_hugetlb(folio)) {
2125fa1df3f6SKefeng Wang 		if (isolate_hugetlb(folio, pagelist))
2126fa1df3f6SKefeng Wang 			err = 1;
2127fa1df3f6SKefeng Wang 	} else {
2128fa1df3f6SKefeng Wang 		if (!folio_isolate_lru(folio))
2129d64cfccbSKefeng Wang 			goto out_putfolio;
2130a49bd4d7SMichal Hocko 
2131e0153fc2SYang Shi 		err = 1;
2132d64cfccbSKefeng Wang 		list_add_tail(&folio->lru, pagelist);
2133d64cfccbSKefeng Wang 		node_stat_mod_folio(folio,
2134d64cfccbSKefeng Wang 			NR_ISOLATED_ANON + folio_is_file_lru(folio),
2135d64cfccbSKefeng Wang 			folio_nr_pages(folio));
21366d9c285aSKOSAKI Motohiro 	}
2137d64cfccbSKefeng Wang out_putfolio:
2138742755a1SChristoph Lameter 	/*
2139d64cfccbSKefeng Wang 	 * Either remove the duplicate refcount from folio_isolate_lru()
2140d64cfccbSKefeng Wang 	 * or drop the folio ref if it was not isolated.
2141742755a1SChristoph Lameter 	 */
2142d64cfccbSKefeng Wang 	folio_put(folio);
2143a49bd4d7SMichal Hocko out:
2144d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
2145742755a1SChristoph Lameter 	return err;
2146742755a1SChristoph Lameter }
2147742755a1SChristoph Lameter 
2148ec47e250SGregory Price static int move_pages_and_store_status(int node,
21497ca8783aSWei Yang 		struct list_head *pagelist, int __user *status,
21507ca8783aSWei Yang 		int start, int i, unsigned long nr_pages)
21517ca8783aSWei Yang {
21527ca8783aSWei Yang 	int err;
21537ca8783aSWei Yang 
21545d7ae891SWei Yang 	if (list_empty(pagelist))
21555d7ae891SWei Yang 		return 0;
21565d7ae891SWei Yang 
2157ec47e250SGregory Price 	err = do_move_pages_to_node(pagelist, node);
21587ca8783aSWei Yang 	if (err) {
21597ca8783aSWei Yang 		/*
21607ca8783aSWei Yang 		 * Positive err means the number of failed
21617ca8783aSWei Yang 		 * pages to migrate.  Since we are going to
21627ca8783aSWei Yang 		 * abort and return the number of non-migrated
2163ab9dd4f8SLong Li 		 * pages, so need to include the rest of the
21647ca8783aSWei Yang 		 * nr_pages that have not been attempted as
21657ca8783aSWei Yang 		 * well.
21667ca8783aSWei Yang 		 */
21677ca8783aSWei Yang 		if (err > 0)
2168a7504ed1SHuang Ying 			err += nr_pages - i;
21697ca8783aSWei Yang 		return err;
21707ca8783aSWei Yang 	}
21717ca8783aSWei Yang 	return store_status(status, start, node, i - start);
21727ca8783aSWei Yang }
21737ca8783aSWei Yang 
2174742755a1SChristoph Lameter /*
21755e9a0f02SBrice Goglin  * Migrate an array of page address onto an array of nodes and fill
21765e9a0f02SBrice Goglin  * the corresponding array of status.
21775e9a0f02SBrice Goglin  */
21783268c63eSChristoph Lameter static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
21795e9a0f02SBrice Goglin 			 unsigned long nr_pages,
21805e9a0f02SBrice Goglin 			 const void __user * __user *pages,
21815e9a0f02SBrice Goglin 			 const int __user *nodes,
21825e9a0f02SBrice Goglin 			 int __user *status, int flags)
21835e9a0f02SBrice Goglin {
2184229e2253SGregory Price 	compat_uptr_t __user *compat_pages = (void __user *)pages;
2185a49bd4d7SMichal Hocko 	int current_node = NUMA_NO_NODE;
2186a49bd4d7SMichal Hocko 	LIST_HEAD(pagelist);
2187a49bd4d7SMichal Hocko 	int start, i;
2188a49bd4d7SMichal Hocko 	int err = 0, err1;
218935282a2dSBrice Goglin 
2190361a2a22SMinchan Kim 	lru_cache_disable();
219135282a2dSBrice Goglin 
2192a49bd4d7SMichal Hocko 	for (i = start = 0; i < nr_pages; i++) {
21935e9a0f02SBrice Goglin 		const void __user *p;
21945e9a0f02SBrice Goglin 		int node;
21955e9a0f02SBrice Goglin 
21963140a227SBrice Goglin 		err = -EFAULT;
2197229e2253SGregory Price 		if (in_compat_syscall()) {
2198229e2253SGregory Price 			compat_uptr_t cp;
2199229e2253SGregory Price 
2200229e2253SGregory Price 			if (get_user(cp, compat_pages + i))
2201229e2253SGregory Price 				goto out_flush;
2202229e2253SGregory Price 
2203229e2253SGregory Price 			p = compat_ptr(cp);
2204229e2253SGregory Price 		} else {
2205a49bd4d7SMichal Hocko 			if (get_user(p, pages + i))
2206a49bd4d7SMichal Hocko 				goto out_flush;
2207229e2253SGregory Price 		}
2208a49bd4d7SMichal Hocko 		if (get_user(node, nodes + i))
2209a49bd4d7SMichal Hocko 			goto out_flush;
22105e9a0f02SBrice Goglin 
22115e9a0f02SBrice Goglin 		err = -ENODEV;
22126f5a55f1SLinus Torvalds 		if (node < 0 || node >= MAX_NUMNODES)
2213a49bd4d7SMichal Hocko 			goto out_flush;
2214389162c2SLai Jiangshan 		if (!node_state(node, N_MEMORY))
2215a49bd4d7SMichal Hocko 			goto out_flush;
22165e9a0f02SBrice Goglin 
22175e9a0f02SBrice Goglin 		err = -EACCES;
22185e9a0f02SBrice Goglin 		if (!node_isset(node, task_nodes))
2219a49bd4d7SMichal Hocko 			goto out_flush;
22205e9a0f02SBrice Goglin 
2221a49bd4d7SMichal Hocko 		if (current_node == NUMA_NO_NODE) {
2222a49bd4d7SMichal Hocko 			current_node = node;
2223a49bd4d7SMichal Hocko 			start = i;
2224a49bd4d7SMichal Hocko 		} else if (node != current_node) {
2225ec47e250SGregory Price 			err = move_pages_and_store_status(current_node,
22267ca8783aSWei Yang 					&pagelist, status, start, i, nr_pages);
2227a49bd4d7SMichal Hocko 			if (err)
2228a49bd4d7SMichal Hocko 				goto out;
2229a49bd4d7SMichal Hocko 			start = i;
2230a49bd4d7SMichal Hocko 			current_node = node;
22315e9a0f02SBrice Goglin 		}
22325e9a0f02SBrice Goglin 
2233a49bd4d7SMichal Hocko 		/*
2234a49bd4d7SMichal Hocko 		 * Errors in the page lookup or isolation are not fatal and we simply
2235a49bd4d7SMichal Hocko 		 * report them via status
2236a49bd4d7SMichal Hocko 		 */
2237428e106aSKirill A. Shutemov 		err = add_page_for_migration(mm, p, current_node, &pagelist,
2238428e106aSKirill A. Shutemov 					     flags & MPOL_MF_MOVE_ALL);
2239e0153fc2SYang Shi 
2240d08221a0SWei Yang 		if (err > 0) {
2241e0153fc2SYang Shi 			/* The page is successfully queued for migration */
2242e0153fc2SYang Shi 			continue;
2243e0153fc2SYang Shi 		}
22443140a227SBrice Goglin 
2245d08221a0SWei Yang 		/*
224665462462SJohn Hubbard 		 * The move_pages() man page does not have an -EEXIST choice, so
224765462462SJohn Hubbard 		 * use -EFAULT instead.
224865462462SJohn Hubbard 		 */
224965462462SJohn Hubbard 		if (err == -EEXIST)
225065462462SJohn Hubbard 			err = -EFAULT;
225165462462SJohn Hubbard 
225265462462SJohn Hubbard 		/*
2253d08221a0SWei Yang 		 * If the page is already on the target node (!err), store the
2254d08221a0SWei Yang 		 * node, otherwise, store the err.
2255d08221a0SWei Yang 		 */
2256d08221a0SWei Yang 		err = store_status(status, i, err ? : current_node, 1);
2257a49bd4d7SMichal Hocko 		if (err)
2258a49bd4d7SMichal Hocko 			goto out_flush;
22593140a227SBrice Goglin 
2260ec47e250SGregory Price 		err = move_pages_and_store_status(current_node, &pagelist,
22617ca8783aSWei Yang 				status, start, i, nr_pages);
2262a7504ed1SHuang Ying 		if (err) {
2263a7504ed1SHuang Ying 			/* We have accounted for page i */
2264a7504ed1SHuang Ying 			if (err > 0)
2265a7504ed1SHuang Ying 				err--;
2266a49bd4d7SMichal Hocko 			goto out;
2267a7504ed1SHuang Ying 		}
2268a49bd4d7SMichal Hocko 		current_node = NUMA_NO_NODE;
22693140a227SBrice Goglin 	}
2270a49bd4d7SMichal Hocko out_flush:
2271a49bd4d7SMichal Hocko 	/* Make sure we do not overwrite the existing error */
2272ec47e250SGregory Price 	err1 = move_pages_and_store_status(current_node, &pagelist,
22737ca8783aSWei Yang 				status, start, i, nr_pages);
2274dfe9aa23SWei Yang 	if (err >= 0)
2275a49bd4d7SMichal Hocko 		err = err1;
22765e9a0f02SBrice Goglin out:
2277361a2a22SMinchan Kim 	lru_cache_enable();
22785e9a0f02SBrice Goglin 	return err;
22795e9a0f02SBrice Goglin }
22805e9a0f02SBrice Goglin 
22815e9a0f02SBrice Goglin /*
22822f007e74SBrice Goglin  * Determine the nodes of an array of pages and store it in an array of status.
2283742755a1SChristoph Lameter  */
228480bba129SBrice Goglin static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
228580bba129SBrice Goglin 				const void __user **pages, int *status)
2286742755a1SChristoph Lameter {
22872f007e74SBrice Goglin 	unsigned long i;
2288742755a1SChristoph Lameter 
2289d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
22902f007e74SBrice Goglin 
22912f007e74SBrice Goglin 	for (i = 0; i < nr_pages; i++) {
229280bba129SBrice Goglin 		unsigned long addr = (unsigned long)(*pages);
22932f007e74SBrice Goglin 		struct vm_area_struct *vma;
22942f007e74SBrice Goglin 		struct page *page;
2295c095adbcSKOSAKI Motohiro 		int err = -EFAULT;
22962f007e74SBrice Goglin 
2297059b8b48SLiam Howlett 		vma = vma_lookup(mm, addr);
2298059b8b48SLiam Howlett 		if (!vma)
2299742755a1SChristoph Lameter 			goto set_status;
2300742755a1SChristoph Lameter 
2301d899844eSKirill A. Shutemov 		/* FOLL_DUMP to ignore special (like zero) pages */
230216fd6b31SBaolin Wang 		page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
230389f5b7daSLinus Torvalds 
230489f5b7daSLinus Torvalds 		err = PTR_ERR(page);
230589f5b7daSLinus Torvalds 		if (IS_ERR(page))
230689f5b7daSLinus Torvalds 			goto set_status;
230789f5b7daSLinus Torvalds 
2308f7091ed6SHaiyue Wang 		err = -ENOENT;
2309f7091ed6SHaiyue Wang 		if (!page)
2310f7091ed6SHaiyue Wang 			goto set_status;
2311f7091ed6SHaiyue Wang 
2312f7091ed6SHaiyue Wang 		if (!is_zone_device_page(page))
23134cd61484SMiaohe Lin 			err = page_to_nid(page);
2314f7091ed6SHaiyue Wang 
23154cd61484SMiaohe Lin 		put_page(page);
2316742755a1SChristoph Lameter set_status:
231780bba129SBrice Goglin 		*status = err;
231880bba129SBrice Goglin 
231980bba129SBrice Goglin 		pages++;
232080bba129SBrice Goglin 		status++;
232180bba129SBrice Goglin 	}
232280bba129SBrice Goglin 
2323d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
232480bba129SBrice Goglin }
232580bba129SBrice Goglin 
23265b1b561bSArnd Bergmann static int get_compat_pages_array(const void __user *chunk_pages[],
23275b1b561bSArnd Bergmann 				  const void __user * __user *pages,
23285b1b561bSArnd Bergmann 				  unsigned long chunk_nr)
23295b1b561bSArnd Bergmann {
23305b1b561bSArnd Bergmann 	compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
23315b1b561bSArnd Bergmann 	compat_uptr_t p;
23325b1b561bSArnd Bergmann 	int i;
23335b1b561bSArnd Bergmann 
23345b1b561bSArnd Bergmann 	for (i = 0; i < chunk_nr; i++) {
23355b1b561bSArnd Bergmann 		if (get_user(p, pages32 + i))
23365b1b561bSArnd Bergmann 			return -EFAULT;
23375b1b561bSArnd Bergmann 		chunk_pages[i] = compat_ptr(p);
23385b1b561bSArnd Bergmann 	}
23395b1b561bSArnd Bergmann 
23405b1b561bSArnd Bergmann 	return 0;
23415b1b561bSArnd Bergmann }
23425b1b561bSArnd Bergmann 
234380bba129SBrice Goglin /*
234480bba129SBrice Goglin  * Determine the nodes of a user array of pages and store it in
234580bba129SBrice Goglin  * a user array of status.
234680bba129SBrice Goglin  */
234780bba129SBrice Goglin static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
234880bba129SBrice Goglin 			 const void __user * __user *pages,
234980bba129SBrice Goglin 			 int __user *status)
235080bba129SBrice Goglin {
23513eefb826SMiaohe Lin #define DO_PAGES_STAT_CHUNK_NR 16UL
235280bba129SBrice Goglin 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
235380bba129SBrice Goglin 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
235480bba129SBrice Goglin 
235587b8d1adSH. Peter Anvin 	while (nr_pages) {
23563eefb826SMiaohe Lin 		unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
235787b8d1adSH. Peter Anvin 
23585b1b561bSArnd Bergmann 		if (in_compat_syscall()) {
23595b1b561bSArnd Bergmann 			if (get_compat_pages_array(chunk_pages, pages,
23605b1b561bSArnd Bergmann 						   chunk_nr))
236187b8d1adSH. Peter Anvin 				break;
23625b1b561bSArnd Bergmann 		} else {
23635b1b561bSArnd Bergmann 			if (copy_from_user(chunk_pages, pages,
23645b1b561bSArnd Bergmann 				      chunk_nr * sizeof(*chunk_pages)))
23655b1b561bSArnd Bergmann 				break;
23665b1b561bSArnd Bergmann 		}
236780bba129SBrice Goglin 
236880bba129SBrice Goglin 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
236980bba129SBrice Goglin 
237087b8d1adSH. Peter Anvin 		if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
237187b8d1adSH. Peter Anvin 			break;
2372742755a1SChristoph Lameter 
237387b8d1adSH. Peter Anvin 		pages += chunk_nr;
237487b8d1adSH. Peter Anvin 		status += chunk_nr;
237587b8d1adSH. Peter Anvin 		nr_pages -= chunk_nr;
237687b8d1adSH. Peter Anvin 	}
237787b8d1adSH. Peter Anvin 	return nr_pages ? -EFAULT : 0;
2378742755a1SChristoph Lameter }
2379742755a1SChristoph Lameter 
23804dc200ceSMiaohe Lin static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
23814dc200ceSMiaohe Lin {
23824dc200ceSMiaohe Lin 	struct task_struct *task;
23834dc200ceSMiaohe Lin 	struct mm_struct *mm;
23844dc200ceSMiaohe Lin 
23854dc200ceSMiaohe Lin 	/*
23864dc200ceSMiaohe Lin 	 * There is no need to check if current process has the right to modify
23874dc200ceSMiaohe Lin 	 * the specified process when they are same.
23884dc200ceSMiaohe Lin 	 */
23894dc200ceSMiaohe Lin 	if (!pid) {
23904dc200ceSMiaohe Lin 		mmget(current->mm);
23914dc200ceSMiaohe Lin 		*mem_nodes = cpuset_mems_allowed(current);
23924dc200ceSMiaohe Lin 		return current->mm;
23934dc200ceSMiaohe Lin 	}
23944dc200ceSMiaohe Lin 
23954dc200ceSMiaohe Lin 	/* Find the mm_struct */
23964dc200ceSMiaohe Lin 	rcu_read_lock();
23974dc200ceSMiaohe Lin 	task = find_task_by_vpid(pid);
23984dc200ceSMiaohe Lin 	if (!task) {
23994dc200ceSMiaohe Lin 		rcu_read_unlock();
24004dc200ceSMiaohe Lin 		return ERR_PTR(-ESRCH);
24014dc200ceSMiaohe Lin 	}
24024dc200ceSMiaohe Lin 	get_task_struct(task);
24034dc200ceSMiaohe Lin 
24044dc200ceSMiaohe Lin 	/*
24054dc200ceSMiaohe Lin 	 * Check if this process has the right to modify the specified
24064dc200ceSMiaohe Lin 	 * process. Use the regular "ptrace_may_access()" checks.
24074dc200ceSMiaohe Lin 	 */
24084dc200ceSMiaohe Lin 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
24094dc200ceSMiaohe Lin 		rcu_read_unlock();
24104dc200ceSMiaohe Lin 		mm = ERR_PTR(-EPERM);
24114dc200ceSMiaohe Lin 		goto out;
24124dc200ceSMiaohe Lin 	}
24134dc200ceSMiaohe Lin 	rcu_read_unlock();
24144dc200ceSMiaohe Lin 
24154dc200ceSMiaohe Lin 	mm = ERR_PTR(security_task_movememory(task));
24164dc200ceSMiaohe Lin 	if (IS_ERR(mm))
24174dc200ceSMiaohe Lin 		goto out;
24184dc200ceSMiaohe Lin 	*mem_nodes = cpuset_mems_allowed(task);
24194dc200ceSMiaohe Lin 	mm = get_task_mm(task);
24204dc200ceSMiaohe Lin out:
24214dc200ceSMiaohe Lin 	put_task_struct(task);
24224dc200ceSMiaohe Lin 	if (!mm)
24234dc200ceSMiaohe Lin 		mm = ERR_PTR(-EINVAL);
24244dc200ceSMiaohe Lin 	return mm;
24254dc200ceSMiaohe Lin }
24264dc200ceSMiaohe Lin 
2427742755a1SChristoph Lameter /*
2428742755a1SChristoph Lameter  * Move a list of pages in the address space of the currently executing
2429742755a1SChristoph Lameter  * process.
2430742755a1SChristoph Lameter  */
24317addf443SDominik Brodowski static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
24327addf443SDominik Brodowski 			     const void __user * __user *pages,
24337addf443SDominik Brodowski 			     const int __user *nodes,
24347addf443SDominik Brodowski 			     int __user *status, int flags)
2435742755a1SChristoph Lameter {
2436742755a1SChristoph Lameter 	struct mm_struct *mm;
24375e9a0f02SBrice Goglin 	int err;
24383268c63eSChristoph Lameter 	nodemask_t task_nodes;
2439742755a1SChristoph Lameter 
2440742755a1SChristoph Lameter 	/* Check flags */
2441742755a1SChristoph Lameter 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2442742755a1SChristoph Lameter 		return -EINVAL;
2443742755a1SChristoph Lameter 
2444742755a1SChristoph Lameter 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2445742755a1SChristoph Lameter 		return -EPERM;
2446742755a1SChristoph Lameter 
24474dc200ceSMiaohe Lin 	mm = find_mm_struct(pid, &task_nodes);
24484dc200ceSMiaohe Lin 	if (IS_ERR(mm))
24494dc200ceSMiaohe Lin 		return PTR_ERR(mm);
24506e8b09eaSSasha Levin 
24513268c63eSChristoph Lameter 	if (nodes)
24523268c63eSChristoph Lameter 		err = do_pages_move(mm, task_nodes, nr_pages, pages,
24533268c63eSChristoph Lameter 				    nodes, status, flags);
24543268c63eSChristoph Lameter 	else
24555e9a0f02SBrice Goglin 		err = do_pages_stat(mm, nr_pages, pages, status);
24563268c63eSChristoph Lameter 
24573268c63eSChristoph Lameter 	mmput(mm);
24583268c63eSChristoph Lameter 	return err;
2459742755a1SChristoph Lameter }
2460742755a1SChristoph Lameter 
24617addf443SDominik Brodowski SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
24627addf443SDominik Brodowski 		const void __user * __user *, pages,
24637addf443SDominik Brodowski 		const int __user *, nodes,
24647addf443SDominik Brodowski 		int __user *, status, int, flags)
24657addf443SDominik Brodowski {
24667addf443SDominik Brodowski 	return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
24677addf443SDominik Brodowski }
24687addf443SDominik Brodowski 
24697039e1dbSPeter Zijlstra #ifdef CONFIG_NUMA_BALANCING
24707039e1dbSPeter Zijlstra /*
24717039e1dbSPeter Zijlstra  * Returns true if this is a safe migration target node for misplaced NUMA
2472bc53008eSWei Yang  * pages. Currently it only checks the watermarks which is crude.
24737039e1dbSPeter Zijlstra  */
24747039e1dbSPeter Zijlstra static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
24753abef4e6SMel Gorman 				   unsigned long nr_migrate_pages)
24767039e1dbSPeter Zijlstra {
24777039e1dbSPeter Zijlstra 	int z;
2478599d0c95SMel Gorman 
24797039e1dbSPeter Zijlstra 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
24807039e1dbSPeter Zijlstra 		struct zone *zone = pgdat->node_zones + z;
24817039e1dbSPeter Zijlstra 
2482bc53008eSWei Yang 		if (!managed_zone(zone))
24837039e1dbSPeter Zijlstra 			continue;
24847039e1dbSPeter Zijlstra 
24857039e1dbSPeter Zijlstra 		/* Avoid waking kswapd by allocating pages_to_migrate pages. */
24867039e1dbSPeter Zijlstra 		if (!zone_watermark_ok(zone, 0,
24877039e1dbSPeter Zijlstra 				       high_wmark_pages(zone) +
24887039e1dbSPeter Zijlstra 				       nr_migrate_pages,
2489bfe9d006SHuang Ying 				       ZONE_MOVABLE, 0))
24907039e1dbSPeter Zijlstra 			continue;
24917039e1dbSPeter Zijlstra 		return true;
24927039e1dbSPeter Zijlstra 	}
24937039e1dbSPeter Zijlstra 	return false;
24947039e1dbSPeter Zijlstra }
24957039e1dbSPeter Zijlstra 
24964e096ae1SMatthew Wilcox (Oracle) static struct folio *alloc_misplaced_dst_folio(struct folio *src,
2497666feb21SMichal Hocko 					   unsigned long data)
24987039e1dbSPeter Zijlstra {
24997039e1dbSPeter Zijlstra 	int nid = (int) data;
25004e096ae1SMatthew Wilcox (Oracle) 	int order = folio_order(src);
2501c185e494SMatthew Wilcox (Oracle) 	gfp_t gfp = __GFP_THISNODE;
25027039e1dbSPeter Zijlstra 
2503c185e494SMatthew Wilcox (Oracle) 	if (order > 0)
2504c185e494SMatthew Wilcox (Oracle) 		gfp |= GFP_TRANSHUGE_LIGHT;
2505c185e494SMatthew Wilcox (Oracle) 	else {
2506c185e494SMatthew Wilcox (Oracle) 		gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2507c185e494SMatthew Wilcox (Oracle) 			__GFP_NOWARN;
2508c185e494SMatthew Wilcox (Oracle) 		gfp &= ~__GFP_RECLAIM;
25097039e1dbSPeter Zijlstra 	}
25104e096ae1SMatthew Wilcox (Oracle) 	return __folio_alloc_node(gfp, order, nid);
2511c5b5a3ddSYang Shi }
2512c5b5a3ddSYang Shi 
25132ac9e99fSKefeng Wang static int numamigrate_isolate_folio(pg_data_t *pgdat, struct folio *folio)
2514b32967ffSMel Gorman {
25152ac9e99fSKefeng Wang 	int nr_pages = folio_nr_pages(folio);
2516b32967ffSMel Gorman 
2517b32967ffSMel Gorman 	/* Avoid migrating to a node that is nearly full */
2518c574bbe9SHuang Ying 	if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2519c574bbe9SHuang Ying 		int z;
2520c574bbe9SHuang Ying 
2521c574bbe9SHuang Ying 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2522340ef390SHugh Dickins 			return 0;
2523c574bbe9SHuang Ying 		for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2524bc53008eSWei Yang 			if (managed_zone(pgdat->node_zones + z))
2525c574bbe9SHuang Ying 				break;
2526c574bbe9SHuang Ying 		}
25272ac9e99fSKefeng Wang 		wakeup_kswapd(pgdat->node_zones + z, 0,
25282ac9e99fSKefeng Wang 			      folio_order(folio), ZONE_MOVABLE);
2529c574bbe9SHuang Ying 		return 0;
2530c574bbe9SHuang Ying 	}
2531b32967ffSMel Gorman 
25322ac9e99fSKefeng Wang 	if (!folio_isolate_lru(folio))
2533340ef390SHugh Dickins 		return 0;
2534340ef390SHugh Dickins 
25352ac9e99fSKefeng Wang 	node_stat_mod_folio(folio, NR_ISOLATED_ANON + folio_is_file_lru(folio),
25362b9b624fSBaolin Wang 			    nr_pages);
2537b32967ffSMel Gorman 
2538b32967ffSMel Gorman 	/*
25392ac9e99fSKefeng Wang 	 * Isolating the folio has taken another reference, so the
25402ac9e99fSKefeng Wang 	 * caller's reference can be safely dropped without the folio
2541340ef390SHugh Dickins 	 * disappearing underneath us during migration.
2542b32967ffSMel Gorman 	 */
25432ac9e99fSKefeng Wang 	folio_put(folio);
2544340ef390SHugh Dickins 	return 1;
2545b32967ffSMel Gorman }
2546b32967ffSMel Gorman 
2547a8f60772SMel Gorman /*
254873eab3caSKefeng Wang  * Attempt to migrate a misplaced folio to the specified destination
25497039e1dbSPeter Zijlstra  * node. Caller is expected to have an elevated reference count on
255073eab3caSKefeng Wang  * the folio that will be dropped by this function before returning.
25517039e1dbSPeter Zijlstra  */
255273eab3caSKefeng Wang int migrate_misplaced_folio(struct folio *folio, struct vm_area_struct *vma,
25531bc115d8SMel Gorman 			    int node)
25547039e1dbSPeter Zijlstra {
2555a8f60772SMel Gorman 	pg_data_t *pgdat = NODE_DATA(node);
2556340ef390SHugh Dickins 	int isolated;
2557b32967ffSMel Gorman 	int nr_remaining;
2558e39bb6beSHuang Ying 	unsigned int nr_succeeded;
25597039e1dbSPeter Zijlstra 	LIST_HEAD(migratepages);
256073eab3caSKefeng Wang 	int nr_pages = folio_nr_pages(folio);
2561c5b5a3ddSYang Shi 
2562c5b5a3ddSYang Shi 	/*
256373eab3caSKefeng Wang 	 * Don't migrate file folios that are mapped in multiple processes
25641bc115d8SMel Gorman 	 * with execute permissions as they are probably shared libraries.
256573eab3caSKefeng Wang 	 * To check if the folio is shared, ideally we want to make sure
256673eab3caSKefeng Wang 	 * every page is mapped to the same process. Doing that is very
256773eab3caSKefeng Wang 	 * expensive, so check the estimated mapcount of the folio instead.
25687039e1dbSPeter Zijlstra 	 */
256973eab3caSKefeng Wang 	if (folio_estimated_sharers(folio) != 1 && folio_is_file_lru(folio) &&
25707ee820eeSMiaohe Lin 	    (vma->vm_flags & VM_EXEC))
25717039e1dbSPeter Zijlstra 		goto out;
25727039e1dbSPeter Zijlstra 
2573a8f60772SMel Gorman 	/*
257473eab3caSKefeng Wang 	 * Also do not migrate dirty folios as not all filesystems can move
257573eab3caSKefeng Wang 	 * dirty folios in MIGRATE_ASYNC mode which is a waste of cycles.
257609a913a7SMel Gorman 	 */
257773eab3caSKefeng Wang 	if (folio_is_file_lru(folio) && folio_test_dirty(folio))
257809a913a7SMel Gorman 		goto out;
257909a913a7SMel Gorman 
258073eab3caSKefeng Wang 	isolated = numamigrate_isolate_folio(pgdat, folio);
2581b32967ffSMel Gorman 	if (!isolated)
25827039e1dbSPeter Zijlstra 		goto out;
25837039e1dbSPeter Zijlstra 
258473eab3caSKefeng Wang 	list_add(&folio->lru, &migratepages);
25854e096ae1SMatthew Wilcox (Oracle) 	nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_folio,
2586c185e494SMatthew Wilcox (Oracle) 				     NULL, node, MIGRATE_ASYNC,
2587c185e494SMatthew Wilcox (Oracle) 				     MR_NUMA_MISPLACED, &nr_succeeded);
25887039e1dbSPeter Zijlstra 	if (nr_remaining) {
258959c82b70SJoonsoo Kim 		if (!list_empty(&migratepages)) {
259073eab3caSKefeng Wang 			list_del(&folio->lru);
259173eab3caSKefeng Wang 			node_stat_mod_folio(folio, NR_ISOLATED_ANON +
259273eab3caSKefeng Wang 					folio_is_file_lru(folio), -nr_pages);
259373eab3caSKefeng Wang 			folio_putback_lru(folio);
259459c82b70SJoonsoo Kim 		}
25957039e1dbSPeter Zijlstra 		isolated = 0;
2596e39bb6beSHuang Ying 	}
2597e39bb6beSHuang Ying 	if (nr_succeeded) {
2598e39bb6beSHuang Ying 		count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
259973eab3caSKefeng Wang 		if (!node_is_toptier(folio_nid(folio)) && node_is_toptier(node))
2600e39bb6beSHuang Ying 			mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2601e39bb6beSHuang Ying 					    nr_succeeded);
2602e39bb6beSHuang Ying 	}
26037039e1dbSPeter Zijlstra 	BUG_ON(!list_empty(&migratepages));
26047039e1dbSPeter Zijlstra 	return isolated;
2605340ef390SHugh Dickins 
2606340ef390SHugh Dickins out:
260773eab3caSKefeng Wang 	folio_put(folio);
2608340ef390SHugh Dickins 	return 0;
26097039e1dbSPeter Zijlstra }
2610220018d3SMel Gorman #endif /* CONFIG_NUMA_BALANCING */
26117d6e2d96SOscar Salvador #endif /* CONFIG_NUMA */
2612