xref: /linux/mm/migrate.c (revision 73eab3ca481e5be0f1fd8140365d604482f84ee1)
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
160280d724aSVishal Moola (Oracle) 		 * __PageMovable because LRU folio's mapping cannot have
161bda807d4SMinchan Kim 		 * 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);
4088763cb45SJérôme Glisse 
4096c5240aeSChristoph Lameter 	if (!mapping) {
4100e8c7d0fSChristoph Lameter 		/* Anonymous page without mapping */
4113417013eSMatthew Wilcox (Oracle) 		if (folio_ref_count(folio) != expected_count)
4126c5240aeSChristoph Lameter 			return -EAGAIN;
413cf4b769aSHugh Dickins 
414cf4b769aSHugh Dickins 		/* No turning back from here */
4153417013eSMatthew Wilcox (Oracle) 		newfolio->index = folio->index;
4163417013eSMatthew Wilcox (Oracle) 		newfolio->mapping = folio->mapping;
4173417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapbacked(folio))
4183417013eSMatthew Wilcox (Oracle) 			__folio_set_swapbacked(newfolio);
419cf4b769aSHugh Dickins 
42078bd5209SRafael Aquini 		return MIGRATEPAGE_SUCCESS;
4216c5240aeSChristoph Lameter 	}
4226c5240aeSChristoph Lameter 
4233417013eSMatthew Wilcox (Oracle) 	oldzone = folio_zone(folio);
4243417013eSMatthew Wilcox (Oracle) 	newzone = folio_zone(newfolio);
42542cb14b1SHugh Dickins 
42689eb946aSMatthew Wilcox 	xas_lock_irq(&xas);
4273417013eSMatthew Wilcox (Oracle) 	if (!folio_ref_freeze(folio, expected_count)) {
42889eb946aSMatthew Wilcox 		xas_unlock_irq(&xas);
429e286781dSNick Piggin 		return -EAGAIN;
430e286781dSNick Piggin 	}
431e286781dSNick Piggin 
432b20a3503SChristoph Lameter 	/*
4333417013eSMatthew Wilcox (Oracle) 	 * Now we know that no one else is looking at the folio:
434cf4b769aSHugh Dickins 	 * no turning back from here.
435b20a3503SChristoph Lameter 	 */
4363417013eSMatthew Wilcox (Oracle) 	newfolio->index = folio->index;
4373417013eSMatthew Wilcox (Oracle) 	newfolio->mapping = folio->mapping;
4383417013eSMatthew Wilcox (Oracle) 	folio_ref_add(newfolio, nr); /* add cache reference */
4393417013eSMatthew Wilcox (Oracle) 	if (folio_test_swapbacked(folio)) {
4403417013eSMatthew Wilcox (Oracle) 		__folio_set_swapbacked(newfolio);
4413417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapcache(folio)) {
4423417013eSMatthew Wilcox (Oracle) 			folio_set_swapcache(newfolio);
4433417013eSMatthew Wilcox (Oracle) 			newfolio->private = folio_get_private(folio);
444b20a3503SChristoph Lameter 		}
4456326fec1SNicholas Piggin 	} else {
4463417013eSMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
4476326fec1SNicholas Piggin 	}
448b20a3503SChristoph Lameter 
44942cb14b1SHugh Dickins 	/* Move dirty while page refs frozen and newpage not yet exposed */
4503417013eSMatthew Wilcox (Oracle) 	dirty = folio_test_dirty(folio);
45142cb14b1SHugh Dickins 	if (dirty) {
4523417013eSMatthew Wilcox (Oracle) 		folio_clear_dirty(folio);
4533417013eSMatthew Wilcox (Oracle) 		folio_set_dirty(newfolio);
45442cb14b1SHugh Dickins 	}
45542cb14b1SHugh Dickins 
4563417013eSMatthew Wilcox (Oracle) 	xas_store(&xas, newfolio);
4577cf9c2c7SNick Piggin 
4587cf9c2c7SNick Piggin 	/*
459937a94c9SJacobo Giralt 	 * Drop cache reference from old page by unfreezing
460937a94c9SJacobo Giralt 	 * to one less reference.
4617cf9c2c7SNick Piggin 	 * We know this isn't the last reference.
4627cf9c2c7SNick Piggin 	 */
4633417013eSMatthew Wilcox (Oracle) 	folio_ref_unfreeze(folio, expected_count - nr);
4647cf9c2c7SNick Piggin 
46589eb946aSMatthew Wilcox 	xas_unlock(&xas);
46642cb14b1SHugh Dickins 	/* Leave irq disabled to prevent preemption while updating stats */
46742cb14b1SHugh Dickins 
4680e8c7d0fSChristoph Lameter 	/*
4690e8c7d0fSChristoph Lameter 	 * If moved to a different zone then also account
4700e8c7d0fSChristoph Lameter 	 * the page for that zone. Other VM counters will be
4710e8c7d0fSChristoph Lameter 	 * taken care of when we establish references to the
4720e8c7d0fSChristoph Lameter 	 * new page and drop references to the old page.
4730e8c7d0fSChristoph Lameter 	 *
4740e8c7d0fSChristoph Lameter 	 * Note that anonymous pages are accounted for
4754b9d0fabSMel Gorman 	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
4760e8c7d0fSChristoph Lameter 	 * are mapped to swap space.
4770e8c7d0fSChristoph Lameter 	 */
47842cb14b1SHugh Dickins 	if (newzone != oldzone) {
4790d1c2072SJohannes Weiner 		struct lruvec *old_lruvec, *new_lruvec;
4800d1c2072SJohannes Weiner 		struct mem_cgroup *memcg;
4810d1c2072SJohannes Weiner 
4823417013eSMatthew Wilcox (Oracle) 		memcg = folio_memcg(folio);
4830d1c2072SJohannes Weiner 		old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
4840d1c2072SJohannes Weiner 		new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
4850d1c2072SJohannes Weiner 
4865c447d27SShakeel Butt 		__mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
4875c447d27SShakeel Butt 		__mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
4883417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
4895c447d27SShakeel Butt 			__mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
4905c447d27SShakeel Butt 			__mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
4910b52c420SJan Glauber 
4920b52c420SJan Glauber 			if (folio_test_pmd_mappable(folio)) {
4930b52c420SJan Glauber 				__mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr);
4940b52c420SJan Glauber 				__mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr);
4950b52c420SJan Glauber 			}
4964b02108aSKOSAKI Motohiro 		}
497b6038942SShakeel Butt #ifdef CONFIG_SWAP
4983417013eSMatthew Wilcox (Oracle) 		if (folio_test_swapcache(folio)) {
499b6038942SShakeel Butt 			__mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
500b6038942SShakeel Butt 			__mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
501b6038942SShakeel Butt 		}
502b6038942SShakeel Butt #endif
503f56753acSChristoph Hellwig 		if (dirty && mapping_can_writeback(mapping)) {
5045c447d27SShakeel Butt 			__mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
5055c447d27SShakeel Butt 			__mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
5065c447d27SShakeel Butt 			__mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
5075c447d27SShakeel Butt 			__mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
50842cb14b1SHugh Dickins 		}
50942cb14b1SHugh Dickins 	}
51042cb14b1SHugh Dickins 	local_irq_enable();
511b20a3503SChristoph Lameter 
51278bd5209SRafael Aquini 	return MIGRATEPAGE_SUCCESS;
513b20a3503SChristoph Lameter }
5143417013eSMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_migrate_mapping);
515b20a3503SChristoph Lameter 
516b20a3503SChristoph Lameter /*
517290408d4SNaoya Horiguchi  * The expected number of remaining references is the same as that
5183417013eSMatthew Wilcox (Oracle)  * of folio_migrate_mapping().
519290408d4SNaoya Horiguchi  */
520290408d4SNaoya Horiguchi int migrate_huge_page_move_mapping(struct address_space *mapping,
521b890ec2aSMatthew Wilcox (Oracle) 				   struct folio *dst, struct folio *src)
522290408d4SNaoya Horiguchi {
523b890ec2aSMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, folio_index(src));
524290408d4SNaoya Horiguchi 	int expected_count;
525290408d4SNaoya Horiguchi 
52689eb946aSMatthew Wilcox 	xas_lock_irq(&xas);
527b890ec2aSMatthew Wilcox (Oracle) 	expected_count = 2 + folio_has_private(src);
528b890ec2aSMatthew Wilcox (Oracle) 	if (!folio_ref_freeze(src, expected_count)) {
52989eb946aSMatthew Wilcox 		xas_unlock_irq(&xas);
530290408d4SNaoya Horiguchi 		return -EAGAIN;
531290408d4SNaoya Horiguchi 	}
532290408d4SNaoya Horiguchi 
533b890ec2aSMatthew Wilcox (Oracle) 	dst->index = src->index;
534b890ec2aSMatthew Wilcox (Oracle) 	dst->mapping = src->mapping;
5356a93ca8fSJohannes Weiner 
536b890ec2aSMatthew Wilcox (Oracle) 	folio_get(dst);
537290408d4SNaoya Horiguchi 
538b890ec2aSMatthew Wilcox (Oracle) 	xas_store(&xas, dst);
539290408d4SNaoya Horiguchi 
540b890ec2aSMatthew Wilcox (Oracle) 	folio_ref_unfreeze(src, expected_count - 1);
541290408d4SNaoya Horiguchi 
54289eb946aSMatthew Wilcox 	xas_unlock_irq(&xas);
5436a93ca8fSJohannes Weiner 
54478bd5209SRafael Aquini 	return MIGRATEPAGE_SUCCESS;
545290408d4SNaoya Horiguchi }
546290408d4SNaoya Horiguchi 
547290408d4SNaoya Horiguchi /*
54819138349SMatthew Wilcox (Oracle)  * Copy the flags and some other ancillary information
549b20a3503SChristoph Lameter  */
55019138349SMatthew Wilcox (Oracle) void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
551b20a3503SChristoph Lameter {
5527851a45cSRik van Riel 	int cpupid;
5537851a45cSRik van Riel 
55419138349SMatthew Wilcox (Oracle) 	if (folio_test_error(folio))
55519138349SMatthew Wilcox (Oracle) 		folio_set_error(newfolio);
55619138349SMatthew Wilcox (Oracle) 	if (folio_test_referenced(folio))
55719138349SMatthew Wilcox (Oracle) 		folio_set_referenced(newfolio);
55819138349SMatthew Wilcox (Oracle) 	if (folio_test_uptodate(folio))
55919138349SMatthew Wilcox (Oracle) 		folio_mark_uptodate(newfolio);
56019138349SMatthew Wilcox (Oracle) 	if (folio_test_clear_active(folio)) {
56119138349SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
56219138349SMatthew Wilcox (Oracle) 		folio_set_active(newfolio);
56319138349SMatthew Wilcox (Oracle) 	} else if (folio_test_clear_unevictable(folio))
56419138349SMatthew Wilcox (Oracle) 		folio_set_unevictable(newfolio);
56519138349SMatthew Wilcox (Oracle) 	if (folio_test_workingset(folio))
56619138349SMatthew Wilcox (Oracle) 		folio_set_workingset(newfolio);
56719138349SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
56819138349SMatthew Wilcox (Oracle) 		folio_set_checked(newfolio);
5696c287605SDavid Hildenbrand 	/*
5706c287605SDavid Hildenbrand 	 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
5716c287605SDavid Hildenbrand 	 * migration entries. We can still have PG_anon_exclusive set on an
5726c287605SDavid Hildenbrand 	 * effectively unmapped and unreferenced first sub-pages of an
5736c287605SDavid Hildenbrand 	 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
5746c287605SDavid Hildenbrand 	 */
57519138349SMatthew Wilcox (Oracle) 	if (folio_test_mappedtodisk(folio))
57619138349SMatthew Wilcox (Oracle) 		folio_set_mappedtodisk(newfolio);
577b20a3503SChristoph Lameter 
5783417013eSMatthew Wilcox (Oracle) 	/* Move dirty on pages not done by folio_migrate_mapping() */
57919138349SMatthew Wilcox (Oracle) 	if (folio_test_dirty(folio))
58019138349SMatthew Wilcox (Oracle) 		folio_set_dirty(newfolio);
581b20a3503SChristoph Lameter 
58219138349SMatthew Wilcox (Oracle) 	if (folio_test_young(folio))
58319138349SMatthew Wilcox (Oracle) 		folio_set_young(newfolio);
58419138349SMatthew Wilcox (Oracle) 	if (folio_test_idle(folio))
58519138349SMatthew Wilcox (Oracle) 		folio_set_idle(newfolio);
58633c3fc71SVladimir Davydov 
5877851a45cSRik van Riel 	/*
5887851a45cSRik van Riel 	 * Copy NUMA information to the new page, to prevent over-eager
5897851a45cSRik van Riel 	 * future migrations of this same page.
5907851a45cSRik van Riel 	 */
59119138349SMatthew Wilcox (Oracle) 	cpupid = page_cpupid_xchg_last(&folio->page, -1);
59233024536SHuang Ying 	/*
59333024536SHuang Ying 	 * For memory tiering mode, when migrate between slow and fast
59433024536SHuang Ying 	 * memory node, reset cpupid, because that is used to record
59533024536SHuang Ying 	 * page access time in slow memory node.
59633024536SHuang Ying 	 */
59733024536SHuang Ying 	if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
59833024536SHuang Ying 		bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
59933024536SHuang Ying 		bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
60033024536SHuang Ying 
60133024536SHuang Ying 		if (f_toptier != t_toptier)
60233024536SHuang Ying 			cpupid = -1;
60333024536SHuang Ying 	}
60419138349SMatthew Wilcox (Oracle) 	page_cpupid_xchg_last(&newfolio->page, cpupid);
6057851a45cSRik van Riel 
60619138349SMatthew Wilcox (Oracle) 	folio_migrate_ksm(newfolio, folio);
607c8d6553bSHugh Dickins 	/*
608c8d6553bSHugh Dickins 	 * Please do not reorder this without considering how mm/ksm.c's
609c8d6553bSHugh Dickins 	 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
610c8d6553bSHugh Dickins 	 */
61119138349SMatthew Wilcox (Oracle) 	if (folio_test_swapcache(folio))
61219138349SMatthew Wilcox (Oracle) 		folio_clear_swapcache(folio);
61319138349SMatthew Wilcox (Oracle) 	folio_clear_private(folio);
614ad2fa371SMuchun Song 
615ad2fa371SMuchun Song 	/* page->private contains hugetlb specific flags */
61619138349SMatthew Wilcox (Oracle) 	if (!folio_test_hugetlb(folio))
61719138349SMatthew Wilcox (Oracle) 		folio->private = NULL;
618b20a3503SChristoph Lameter 
619b20a3503SChristoph Lameter 	/*
620b20a3503SChristoph Lameter 	 * If any waiters have accumulated on the new page then
621b20a3503SChristoph Lameter 	 * wake them up.
622b20a3503SChristoph Lameter 	 */
62319138349SMatthew Wilcox (Oracle) 	if (folio_test_writeback(newfolio))
62419138349SMatthew Wilcox (Oracle) 		folio_end_writeback(newfolio);
625d435edcaSVlastimil Babka 
6266aeff241SYang Shi 	/*
6276aeff241SYang Shi 	 * PG_readahead shares the same bit with PG_reclaim.  The above
6286aeff241SYang Shi 	 * end_page_writeback() may clear PG_readahead mistakenly, so set the
6296aeff241SYang Shi 	 * bit after that.
6306aeff241SYang Shi 	 */
63119138349SMatthew Wilcox (Oracle) 	if (folio_test_readahead(folio))
63219138349SMatthew Wilcox (Oracle) 		folio_set_readahead(newfolio);
6336aeff241SYang Shi 
63419138349SMatthew Wilcox (Oracle) 	folio_copy_owner(newfolio, folio);
63574485cf2SJohannes Weiner 
63619138349SMatthew Wilcox (Oracle) 	if (!folio_test_hugetlb(folio))
637d21bba2bSMatthew Wilcox (Oracle) 		mem_cgroup_migrate(folio, newfolio);
638b20a3503SChristoph Lameter }
63919138349SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_migrate_flags);
6402916ecc0SJérôme Glisse 
641715cbfd6SMatthew Wilcox (Oracle) void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
6422916ecc0SJérôme Glisse {
643715cbfd6SMatthew Wilcox (Oracle) 	folio_copy(newfolio, folio);
644715cbfd6SMatthew Wilcox (Oracle) 	folio_migrate_flags(newfolio, folio);
6452916ecc0SJérôme Glisse }
646715cbfd6SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_migrate_copy);
647b20a3503SChristoph Lameter 
6481d8b85ccSChristoph Lameter /************************************************************
6491d8b85ccSChristoph Lameter  *                    Migration functions
6501d8b85ccSChristoph Lameter  ***********************************************************/
6511d8b85ccSChristoph Lameter 
65216ce101dSAlistair Popple int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
65316ce101dSAlistair Popple 		struct folio *src, enum migrate_mode mode, int extra_count)
65416ce101dSAlistair Popple {
65516ce101dSAlistair Popple 	int rc;
65616ce101dSAlistair Popple 
65716ce101dSAlistair Popple 	BUG_ON(folio_test_writeback(src));	/* Writeback must be complete */
65816ce101dSAlistair Popple 
65916ce101dSAlistair Popple 	rc = folio_migrate_mapping(mapping, dst, src, extra_count);
66016ce101dSAlistair Popple 
66116ce101dSAlistair Popple 	if (rc != MIGRATEPAGE_SUCCESS)
66216ce101dSAlistair Popple 		return rc;
66316ce101dSAlistair Popple 
66416ce101dSAlistair Popple 	if (mode != MIGRATE_SYNC_NO_COPY)
66516ce101dSAlistair Popple 		folio_migrate_copy(dst, src);
66616ce101dSAlistair Popple 	else
66716ce101dSAlistair Popple 		folio_migrate_flags(dst, src);
66816ce101dSAlistair Popple 	return MIGRATEPAGE_SUCCESS;
66916ce101dSAlistair Popple }
67016ce101dSAlistair Popple 
67154184650SMatthew Wilcox (Oracle) /**
67254184650SMatthew Wilcox (Oracle)  * migrate_folio() - Simple folio migration.
67354184650SMatthew Wilcox (Oracle)  * @mapping: The address_space containing the folio.
67454184650SMatthew Wilcox (Oracle)  * @dst: The folio to migrate the data to.
67554184650SMatthew Wilcox (Oracle)  * @src: The folio containing the current data.
67654184650SMatthew Wilcox (Oracle)  * @mode: How to migrate the page.
677b20a3503SChristoph Lameter  *
67854184650SMatthew Wilcox (Oracle)  * Common logic to directly migrate a single LRU folio suitable for
67954184650SMatthew Wilcox (Oracle)  * folios that do not use PagePrivate/PagePrivate2.
68054184650SMatthew Wilcox (Oracle)  *
68154184650SMatthew Wilcox (Oracle)  * Folios are locked upon entry and exit.
682b20a3503SChristoph Lameter  */
68354184650SMatthew Wilcox (Oracle) int migrate_folio(struct address_space *mapping, struct folio *dst,
68454184650SMatthew Wilcox (Oracle) 		struct folio *src, enum migrate_mode mode)
685b20a3503SChristoph Lameter {
68616ce101dSAlistair Popple 	return migrate_folio_extra(mapping, dst, src, mode, 0);
687b20a3503SChristoph Lameter }
68854184650SMatthew Wilcox (Oracle) EXPORT_SYMBOL(migrate_folio);
689b20a3503SChristoph Lameter 
690925c86a1SChristoph Hellwig #ifdef CONFIG_BUFFER_HEAD
69184ade7c1SJan Kara /* Returns true if all buffers are successfully locked */
69284ade7c1SJan Kara static bool buffer_migrate_lock_buffers(struct buffer_head *head,
69384ade7c1SJan Kara 							enum migrate_mode mode)
69484ade7c1SJan Kara {
69584ade7c1SJan Kara 	struct buffer_head *bh = head;
6964bb6dc79SDouglas Anderson 	struct buffer_head *failed_bh;
69784ade7c1SJan Kara 
69884ade7c1SJan Kara 	do {
6994bb6dc79SDouglas Anderson 		if (!trylock_buffer(bh)) {
7004bb6dc79SDouglas Anderson 			if (mode == MIGRATE_ASYNC)
7014bb6dc79SDouglas Anderson 				goto unlock;
7024bb6dc79SDouglas Anderson 			if (mode == MIGRATE_SYNC_LIGHT && !buffer_uptodate(bh))
7034bb6dc79SDouglas Anderson 				goto unlock;
70484ade7c1SJan Kara 			lock_buffer(bh);
7054bb6dc79SDouglas Anderson 		}
70684ade7c1SJan Kara 
7074bb6dc79SDouglas Anderson 		bh = bh->b_this_page;
70884ade7c1SJan Kara 	} while (bh != head);
70984ade7c1SJan Kara 
71084ade7c1SJan Kara 	return true;
71184ade7c1SJan Kara 
7124bb6dc79SDouglas Anderson unlock:
7134bb6dc79SDouglas Anderson 	/* We failed to lock the buffer and cannot stall. */
7144bb6dc79SDouglas Anderson 	failed_bh = bh;
71584ade7c1SJan Kara 	bh = head;
71684ade7c1SJan Kara 	while (bh != failed_bh) {
71784ade7c1SJan Kara 		unlock_buffer(bh);
71884ade7c1SJan Kara 		bh = bh->b_this_page;
71984ade7c1SJan Kara 	}
72084ade7c1SJan Kara 
7214bb6dc79SDouglas Anderson 	return false;
72284ade7c1SJan Kara }
72384ade7c1SJan Kara 
72467235182SMatthew Wilcox (Oracle) static int __buffer_migrate_folio(struct address_space *mapping,
72567235182SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode,
72689cb0888SJan Kara 		bool check_refs)
7271d8b85ccSChristoph Lameter {
7281d8b85ccSChristoph Lameter 	struct buffer_head *bh, *head;
7291d8b85ccSChristoph Lameter 	int rc;
730cc4f11e6SJan Kara 	int expected_count;
7311d8b85ccSChristoph Lameter 
73267235182SMatthew Wilcox (Oracle) 	head = folio_buffers(src);
73367235182SMatthew Wilcox (Oracle) 	if (!head)
73454184650SMatthew Wilcox (Oracle) 		return migrate_folio(mapping, dst, src, mode);
7351d8b85ccSChristoph Lameter 
736cc4f11e6SJan Kara 	/* Check whether page does not have extra refs before we do more work */
737108ca835SMatthew Wilcox (Oracle) 	expected_count = folio_expected_refs(mapping, src);
73867235182SMatthew Wilcox (Oracle) 	if (folio_ref_count(src) != expected_count)
739cc4f11e6SJan Kara 		return -EAGAIN;
740cc4f11e6SJan Kara 
741cc4f11e6SJan Kara 	if (!buffer_migrate_lock_buffers(head, mode))
742cc4f11e6SJan Kara 		return -EAGAIN;
7431d8b85ccSChristoph Lameter 
74489cb0888SJan Kara 	if (check_refs) {
74589cb0888SJan Kara 		bool busy;
74689cb0888SJan Kara 		bool invalidated = false;
74789cb0888SJan Kara 
74889cb0888SJan Kara recheck_buffers:
74989cb0888SJan Kara 		busy = false;
75089cb0888SJan Kara 		spin_lock(&mapping->private_lock);
75189cb0888SJan Kara 		bh = head;
75289cb0888SJan Kara 		do {
75389cb0888SJan Kara 			if (atomic_read(&bh->b_count)) {
75489cb0888SJan Kara 				busy = true;
75589cb0888SJan Kara 				break;
75689cb0888SJan Kara 			}
75789cb0888SJan Kara 			bh = bh->b_this_page;
75889cb0888SJan Kara 		} while (bh != head);
75989cb0888SJan Kara 		if (busy) {
76089cb0888SJan Kara 			if (invalidated) {
76189cb0888SJan Kara 				rc = -EAGAIN;
76289cb0888SJan Kara 				goto unlock_buffers;
76389cb0888SJan Kara 			}
764ebdf4de5SJan Kara 			spin_unlock(&mapping->private_lock);
76589cb0888SJan Kara 			invalidate_bh_lrus();
76689cb0888SJan Kara 			invalidated = true;
76789cb0888SJan Kara 			goto recheck_buffers;
76889cb0888SJan Kara 		}
76989cb0888SJan Kara 	}
77089cb0888SJan Kara 
77167235182SMatthew Wilcox (Oracle) 	rc = folio_migrate_mapping(mapping, dst, src, 0);
77278bd5209SRafael Aquini 	if (rc != MIGRATEPAGE_SUCCESS)
773cc4f11e6SJan Kara 		goto unlock_buffers;
7741d8b85ccSChristoph Lameter 
77567235182SMatthew Wilcox (Oracle) 	folio_attach_private(dst, folio_detach_private(src));
7761d8b85ccSChristoph Lameter 
7771d8b85ccSChristoph Lameter 	bh = head;
7781d8b85ccSChristoph Lameter 	do {
779d5db4f9dSMatthew Wilcox (Oracle) 		folio_set_bh(bh, dst, bh_offset(bh));
7801d8b85ccSChristoph Lameter 		bh = bh->b_this_page;
7811d8b85ccSChristoph Lameter 	} while (bh != head);
7821d8b85ccSChristoph Lameter 
7832916ecc0SJérôme Glisse 	if (mode != MIGRATE_SYNC_NO_COPY)
78467235182SMatthew Wilcox (Oracle) 		folio_migrate_copy(dst, src);
7852916ecc0SJérôme Glisse 	else
78667235182SMatthew Wilcox (Oracle) 		folio_migrate_flags(dst, src);
7871d8b85ccSChristoph Lameter 
788cc4f11e6SJan Kara 	rc = MIGRATEPAGE_SUCCESS;
789cc4f11e6SJan Kara unlock_buffers:
790ebdf4de5SJan Kara 	if (check_refs)
791ebdf4de5SJan Kara 		spin_unlock(&mapping->private_lock);
7921d8b85ccSChristoph Lameter 	bh = head;
7931d8b85ccSChristoph Lameter 	do {
7941d8b85ccSChristoph Lameter 		unlock_buffer(bh);
7951d8b85ccSChristoph Lameter 		bh = bh->b_this_page;
7961d8b85ccSChristoph Lameter 	} while (bh != head);
7971d8b85ccSChristoph Lameter 
798cc4f11e6SJan Kara 	return rc;
7991d8b85ccSChristoph Lameter }
80089cb0888SJan Kara 
80167235182SMatthew Wilcox (Oracle) /**
80267235182SMatthew Wilcox (Oracle)  * buffer_migrate_folio() - Migration function for folios with buffers.
80367235182SMatthew Wilcox (Oracle)  * @mapping: The address space containing @src.
80467235182SMatthew Wilcox (Oracle)  * @dst: The folio to migrate to.
80567235182SMatthew Wilcox (Oracle)  * @src: The folio to migrate from.
80667235182SMatthew Wilcox (Oracle)  * @mode: How to migrate the folio.
80767235182SMatthew Wilcox (Oracle)  *
80867235182SMatthew Wilcox (Oracle)  * This function can only be used if the underlying filesystem guarantees
80967235182SMatthew Wilcox (Oracle)  * that no other references to @src exist. For example attached buffer
81067235182SMatthew Wilcox (Oracle)  * heads are accessed only under the folio lock.  If your filesystem cannot
81167235182SMatthew Wilcox (Oracle)  * provide this guarantee, buffer_migrate_folio_norefs() may be more
81267235182SMatthew Wilcox (Oracle)  * appropriate.
81367235182SMatthew Wilcox (Oracle)  *
81467235182SMatthew Wilcox (Oracle)  * Return: 0 on success or a negative errno on failure.
81589cb0888SJan Kara  */
81667235182SMatthew Wilcox (Oracle) int buffer_migrate_folio(struct address_space *mapping,
81767235182SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
81889cb0888SJan Kara {
81967235182SMatthew Wilcox (Oracle) 	return __buffer_migrate_folio(mapping, dst, src, mode, false);
82089cb0888SJan Kara }
82167235182SMatthew Wilcox (Oracle) EXPORT_SYMBOL(buffer_migrate_folio);
82289cb0888SJan Kara 
82367235182SMatthew Wilcox (Oracle) /**
82467235182SMatthew Wilcox (Oracle)  * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
82567235182SMatthew Wilcox (Oracle)  * @mapping: The address space containing @src.
82667235182SMatthew Wilcox (Oracle)  * @dst: The folio to migrate to.
82767235182SMatthew Wilcox (Oracle)  * @src: The folio to migrate from.
82867235182SMatthew Wilcox (Oracle)  * @mode: How to migrate the folio.
82967235182SMatthew Wilcox (Oracle)  *
83067235182SMatthew Wilcox (Oracle)  * Like buffer_migrate_folio() except that this variant is more careful
83167235182SMatthew Wilcox (Oracle)  * and checks that there are also no buffer head references. This function
83267235182SMatthew Wilcox (Oracle)  * is the right one for mappings where buffer heads are directly looked
83367235182SMatthew Wilcox (Oracle)  * up and referenced (such as block device mappings).
83467235182SMatthew Wilcox (Oracle)  *
83567235182SMatthew Wilcox (Oracle)  * Return: 0 on success or a negative errno on failure.
83689cb0888SJan Kara  */
83767235182SMatthew Wilcox (Oracle) int buffer_migrate_folio_norefs(struct address_space *mapping,
83867235182SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
83989cb0888SJan Kara {
84067235182SMatthew Wilcox (Oracle) 	return __buffer_migrate_folio(mapping, dst, src, mode, true);
84189cb0888SJan Kara }
842e26355e2SJan Kara EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
843925c86a1SChristoph Hellwig #endif /* CONFIG_BUFFER_HEAD */
8441d8b85ccSChristoph Lameter 
8452ec810d5SMatthew Wilcox (Oracle) int filemap_migrate_folio(struct address_space *mapping,
8462ec810d5SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
8472ec810d5SMatthew Wilcox (Oracle) {
8482ec810d5SMatthew Wilcox (Oracle) 	int ret;
8492ec810d5SMatthew Wilcox (Oracle) 
8502ec810d5SMatthew Wilcox (Oracle) 	ret = folio_migrate_mapping(mapping, dst, src, 0);
8512ec810d5SMatthew Wilcox (Oracle) 	if (ret != MIGRATEPAGE_SUCCESS)
8522ec810d5SMatthew Wilcox (Oracle) 		return ret;
8532ec810d5SMatthew Wilcox (Oracle) 
8542ec810d5SMatthew Wilcox (Oracle) 	if (folio_get_private(src))
8552ec810d5SMatthew Wilcox (Oracle) 		folio_attach_private(dst, folio_detach_private(src));
8562ec810d5SMatthew Wilcox (Oracle) 
8572ec810d5SMatthew Wilcox (Oracle) 	if (mode != MIGRATE_SYNC_NO_COPY)
8582ec810d5SMatthew Wilcox (Oracle) 		folio_migrate_copy(dst, src);
8592ec810d5SMatthew Wilcox (Oracle) 	else
8602ec810d5SMatthew Wilcox (Oracle) 		folio_migrate_flags(dst, src);
8612ec810d5SMatthew Wilcox (Oracle) 	return MIGRATEPAGE_SUCCESS;
8622ec810d5SMatthew Wilcox (Oracle) }
8632ec810d5SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(filemap_migrate_folio);
8642ec810d5SMatthew Wilcox (Oracle) 
86504e62a29SChristoph Lameter /*
8662be7fa10SMatthew Wilcox (Oracle)  * Writeback a folio to clean the dirty state
86704e62a29SChristoph Lameter  */
8682be7fa10SMatthew Wilcox (Oracle) static int writeout(struct address_space *mapping, struct folio *folio)
86904e62a29SChristoph Lameter {
87004e62a29SChristoph Lameter 	struct writeback_control wbc = {
87104e62a29SChristoph Lameter 		.sync_mode = WB_SYNC_NONE,
87204e62a29SChristoph Lameter 		.nr_to_write = 1,
87304e62a29SChristoph Lameter 		.range_start = 0,
87404e62a29SChristoph Lameter 		.range_end = LLONG_MAX,
87504e62a29SChristoph Lameter 		.for_reclaim = 1
87604e62a29SChristoph Lameter 	};
87704e62a29SChristoph Lameter 	int rc;
87804e62a29SChristoph Lameter 
87904e62a29SChristoph Lameter 	if (!mapping->a_ops->writepage)
88004e62a29SChristoph Lameter 		/* No write method for the address space */
88104e62a29SChristoph Lameter 		return -EINVAL;
88204e62a29SChristoph Lameter 
8832be7fa10SMatthew Wilcox (Oracle) 	if (!folio_clear_dirty_for_io(folio))
88404e62a29SChristoph Lameter 		/* Someone else already triggered a write */
88504e62a29SChristoph Lameter 		return -EAGAIN;
88604e62a29SChristoph Lameter 
88704e62a29SChristoph Lameter 	/*
8882be7fa10SMatthew Wilcox (Oracle) 	 * A dirty folio may imply that the underlying filesystem has
8892be7fa10SMatthew Wilcox (Oracle) 	 * the folio on some queue. So the folio must be clean for
8902be7fa10SMatthew Wilcox (Oracle) 	 * migration. Writeout may mean we lose the lock and the
8912be7fa10SMatthew Wilcox (Oracle) 	 * folio state is no longer what we checked for earlier.
89204e62a29SChristoph Lameter 	 * At this point we know that the migration attempt cannot
89304e62a29SChristoph Lameter 	 * be successful.
89404e62a29SChristoph Lameter 	 */
8954eecb8b9SMatthew Wilcox (Oracle) 	remove_migration_ptes(folio, folio, false);
89604e62a29SChristoph Lameter 
8972be7fa10SMatthew Wilcox (Oracle) 	rc = mapping->a_ops->writepage(&folio->page, &wbc);
89804e62a29SChristoph Lameter 
89904e62a29SChristoph Lameter 	if (rc != AOP_WRITEPAGE_ACTIVATE)
90004e62a29SChristoph Lameter 		/* unlocked. Relock */
9012be7fa10SMatthew Wilcox (Oracle) 		folio_lock(folio);
90204e62a29SChristoph Lameter 
903bda8550dSHugh Dickins 	return (rc < 0) ? -EIO : -EAGAIN;
90404e62a29SChristoph Lameter }
90504e62a29SChristoph Lameter 
90604e62a29SChristoph Lameter /*
90704e62a29SChristoph Lameter  * Default handling if a filesystem does not provide a migration function.
90804e62a29SChristoph Lameter  */
9098faa8ef5SMatthew Wilcox (Oracle) static int fallback_migrate_folio(struct address_space *mapping,
9108faa8ef5SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
9118351a6e4SChristoph Lameter {
9128faa8ef5SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src)) {
9138faa8ef5SMatthew Wilcox (Oracle) 		/* Only writeback folios in full synchronous migration */
9142916ecc0SJérôme Glisse 		switch (mode) {
9152916ecc0SJérôme Glisse 		case MIGRATE_SYNC:
9162916ecc0SJérôme Glisse 		case MIGRATE_SYNC_NO_COPY:
9172916ecc0SJérôme Glisse 			break;
9182916ecc0SJérôme Glisse 		default:
919b969c4abSMel Gorman 			return -EBUSY;
9202916ecc0SJérôme Glisse 		}
9212be7fa10SMatthew Wilcox (Oracle) 		return writeout(mapping, src);
922b969c4abSMel Gorman 	}
9238351a6e4SChristoph Lameter 
9248351a6e4SChristoph Lameter 	/*
9258351a6e4SChristoph Lameter 	 * Buffers may be managed in a filesystem specific way.
9268351a6e4SChristoph Lameter 	 * We must have no buffers or drop them.
9278351a6e4SChristoph Lameter 	 */
9280201ebf2SDavid Howells 	if (!filemap_release_folio(src, GFP_KERNEL))
929806031bbSMel Gorman 		return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
9308351a6e4SChristoph Lameter 
93154184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
9328351a6e4SChristoph Lameter }
9338351a6e4SChristoph Lameter 
9341d8b85ccSChristoph Lameter /*
935e24f0b8fSChristoph Lameter  * Move a page to a newly allocated page
936e24f0b8fSChristoph Lameter  * The page is locked and all ptes have been successfully removed.
937b20a3503SChristoph Lameter  *
938e24f0b8fSChristoph Lameter  * The new page will have replaced the old page if this function
939e24f0b8fSChristoph Lameter  * is successful.
940894bc310SLee Schermerhorn  *
941894bc310SLee Schermerhorn  * Return value:
942894bc310SLee Schermerhorn  *   < 0 - error code
94378bd5209SRafael Aquini  *  MIGRATEPAGE_SUCCESS - success
944b20a3503SChristoph Lameter  */
945e7e3ffebSMatthew Wilcox (Oracle) static int move_to_new_folio(struct folio *dst, struct folio *src,
9465c3f9a67SHugh Dickins 				enum migrate_mode mode)
947b20a3503SChristoph Lameter {
948bda807d4SMinchan Kim 	int rc = -EAGAIN;
949e7e3ffebSMatthew Wilcox (Oracle) 	bool is_lru = !__PageMovable(&src->page);
950b20a3503SChristoph Lameter 
951e7e3ffebSMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
952e7e3ffebSMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
953b20a3503SChristoph Lameter 
954bda807d4SMinchan Kim 	if (likely(is_lru)) {
95568f2736aSMatthew Wilcox (Oracle) 		struct address_space *mapping = folio_mapping(src);
95668f2736aSMatthew Wilcox (Oracle) 
957b20a3503SChristoph Lameter 		if (!mapping)
95854184650SMatthew Wilcox (Oracle) 			rc = migrate_folio(mapping, dst, src, mode);
9595490da4fSMatthew Wilcox (Oracle) 		else if (mapping->a_ops->migrate_folio)
960b20a3503SChristoph Lameter 			/*
9615490da4fSMatthew Wilcox (Oracle) 			 * Most folios have a mapping and most filesystems
9625490da4fSMatthew Wilcox (Oracle) 			 * provide a migrate_folio callback. Anonymous folios
963bda807d4SMinchan Kim 			 * are part of swap space which also has its own
9645490da4fSMatthew Wilcox (Oracle) 			 * migrate_folio callback. This is the most common path
965bda807d4SMinchan Kim 			 * for page migration.
966b20a3503SChristoph Lameter 			 */
9675490da4fSMatthew Wilcox (Oracle) 			rc = mapping->a_ops->migrate_folio(mapping, dst, src,
9685490da4fSMatthew Wilcox (Oracle) 								mode);
9698351a6e4SChristoph Lameter 		else
9708faa8ef5SMatthew Wilcox (Oracle) 			rc = fallback_migrate_folio(mapping, dst, src, mode);
971bda807d4SMinchan Kim 	} else {
97268f2736aSMatthew Wilcox (Oracle) 		const struct movable_operations *mops;
97368f2736aSMatthew Wilcox (Oracle) 
974bda807d4SMinchan Kim 		/*
975bda807d4SMinchan Kim 		 * In case of non-lru page, it could be released after
976bda807d4SMinchan Kim 		 * isolation step. In that case, we shouldn't try migration.
977bda807d4SMinchan Kim 		 */
978e7e3ffebSMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
979e7e3ffebSMatthew Wilcox (Oracle) 		if (!folio_test_movable(src)) {
980bda807d4SMinchan Kim 			rc = MIGRATEPAGE_SUCCESS;
981e7e3ffebSMatthew Wilcox (Oracle) 			folio_clear_isolated(src);
982bda807d4SMinchan Kim 			goto out;
983bda807d4SMinchan Kim 		}
984bda807d4SMinchan Kim 
985da707a6dSVishal Moola (Oracle) 		mops = folio_movable_ops(src);
98668f2736aSMatthew Wilcox (Oracle) 		rc = mops->migrate_page(&dst->page, &src->page, mode);
987bda807d4SMinchan Kim 		WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
988e7e3ffebSMatthew Wilcox (Oracle) 				!folio_test_isolated(src));
989bda807d4SMinchan Kim 	}
990b20a3503SChristoph Lameter 
9915c3f9a67SHugh Dickins 	/*
992e7e3ffebSMatthew Wilcox (Oracle) 	 * When successful, old pagecache src->mapping must be cleared before
993e7e3ffebSMatthew Wilcox (Oracle) 	 * src is freed; but stats require that PageAnon be left as PageAnon.
9945c3f9a67SHugh Dickins 	 */
9955c3f9a67SHugh Dickins 	if (rc == MIGRATEPAGE_SUCCESS) {
996e7e3ffebSMatthew Wilcox (Oracle) 		if (__PageMovable(&src->page)) {
997e7e3ffebSMatthew Wilcox (Oracle) 			VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
998bda807d4SMinchan Kim 
999bda807d4SMinchan Kim 			/*
1000bda807d4SMinchan Kim 			 * We clear PG_movable under page_lock so any compactor
1001bda807d4SMinchan Kim 			 * cannot try to migrate this page.
1002bda807d4SMinchan Kim 			 */
1003e7e3ffebSMatthew Wilcox (Oracle) 			folio_clear_isolated(src);
1004bda807d4SMinchan Kim 		}
1005bda807d4SMinchan Kim 
1006bda807d4SMinchan Kim 		/*
1007e7e3ffebSMatthew Wilcox (Oracle) 		 * Anonymous and movable src->mapping will be cleared by
1008bda807d4SMinchan Kim 		 * free_pages_prepare so don't reset it here for keeping
1009bda807d4SMinchan Kim 		 * the type to work PageAnon, for example.
1010bda807d4SMinchan Kim 		 */
1011e7e3ffebSMatthew Wilcox (Oracle) 		if (!folio_mapping_flags(src))
1012e7e3ffebSMatthew Wilcox (Oracle) 			src->mapping = NULL;
1013d2b2c6ddSLars Persson 
1014e7e3ffebSMatthew Wilcox (Oracle) 		if (likely(!folio_is_zone_device(dst)))
1015e7e3ffebSMatthew Wilcox (Oracle) 			flush_dcache_folio(dst);
10163fe2011fSMel Gorman 	}
1017bda807d4SMinchan Kim out:
1018e24f0b8fSChristoph Lameter 	return rc;
1019e24f0b8fSChristoph Lameter }
1020e24f0b8fSChristoph Lameter 
102164c8902eSHuang Ying /*
102264c8902eSHuang Ying  * To record some information during migration, we use some unused
102364c8902eSHuang Ying  * fields (mapping and private) of struct folio of the newly allocated
102464c8902eSHuang Ying  * destination folio.  This is safe because nobody is using them
102564c8902eSHuang Ying  * except us.
102664c8902eSHuang Ying  */
1027e77d587aSLinus Torvalds union migration_ptr {
1028e77d587aSLinus Torvalds 	struct anon_vma *anon_vma;
1029e77d587aSLinus Torvalds 	struct address_space *mapping;
1030e77d587aSLinus Torvalds };
103164c8902eSHuang Ying static void __migrate_folio_record(struct folio *dst,
103264c8902eSHuang Ying 				   unsigned long page_was_mapped,
103364c8902eSHuang Ying 				   struct anon_vma *anon_vma)
1034e24f0b8fSChristoph Lameter {
1035e77d587aSLinus Torvalds 	union migration_ptr ptr = { .anon_vma = anon_vma };
1036e77d587aSLinus Torvalds 	dst->mapping = ptr.mapping;
103764c8902eSHuang Ying 	dst->private = (void *)page_was_mapped;
103864c8902eSHuang Ying }
103964c8902eSHuang Ying 
104064c8902eSHuang Ying static void __migrate_folio_extract(struct folio *dst,
104164c8902eSHuang Ying 				   int *page_was_mappedp,
104264c8902eSHuang Ying 				   struct anon_vma **anon_vmap)
104364c8902eSHuang Ying {
1044e77d587aSLinus Torvalds 	union migration_ptr ptr = { .mapping = dst->mapping };
1045e77d587aSLinus Torvalds 	*anon_vmap = ptr.anon_vma;
104664c8902eSHuang Ying 	*page_was_mappedp = (unsigned long)dst->private;
104764c8902eSHuang Ying 	dst->mapping = NULL;
104864c8902eSHuang Ying 	dst->private = NULL;
104964c8902eSHuang Ying }
105064c8902eSHuang Ying 
10515dfab109SHuang Ying /* Restore the source folio to the original state upon failure */
10525dfab109SHuang Ying static void migrate_folio_undo_src(struct folio *src,
10535dfab109SHuang Ying 				   int page_was_mapped,
10545dfab109SHuang Ying 				   struct anon_vma *anon_vma,
1055ebe75e47SHuang Ying 				   bool locked,
10565dfab109SHuang Ying 				   struct list_head *ret)
10575dfab109SHuang Ying {
10585dfab109SHuang Ying 	if (page_was_mapped)
10595dfab109SHuang Ying 		remove_migration_ptes(src, src, false);
10605dfab109SHuang Ying 	/* Drop an anon_vma reference if we took one */
10615dfab109SHuang Ying 	if (anon_vma)
10625dfab109SHuang Ying 		put_anon_vma(anon_vma);
1063ebe75e47SHuang Ying 	if (locked)
10645dfab109SHuang Ying 		folio_unlock(src);
1065ebe75e47SHuang Ying 	if (ret)
10665dfab109SHuang Ying 		list_move_tail(&src->lru, ret);
10675dfab109SHuang Ying }
10685dfab109SHuang Ying 
10695dfab109SHuang Ying /* Restore the destination folio to the original state upon failure */
10704e096ae1SMatthew Wilcox (Oracle) static void migrate_folio_undo_dst(struct folio *dst, bool locked,
10714e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private)
10725dfab109SHuang Ying {
1073ebe75e47SHuang Ying 	if (locked)
10745dfab109SHuang Ying 		folio_unlock(dst);
10754e096ae1SMatthew Wilcox (Oracle) 	if (put_new_folio)
10764e096ae1SMatthew Wilcox (Oracle) 		put_new_folio(dst, private);
10775dfab109SHuang Ying 	else
10785dfab109SHuang Ying 		folio_put(dst);
10795dfab109SHuang Ying }
10805dfab109SHuang Ying 
108164c8902eSHuang Ying /* Cleanup src folio upon migration success */
108264c8902eSHuang Ying static void migrate_folio_done(struct folio *src,
108364c8902eSHuang Ying 			       enum migrate_reason reason)
108464c8902eSHuang Ying {
108564c8902eSHuang Ying 	/*
108664c8902eSHuang Ying 	 * Compaction can migrate also non-LRU pages which are
108764c8902eSHuang Ying 	 * not accounted to NR_ISOLATED_*. They can be recognized
108864c8902eSHuang Ying 	 * as __PageMovable
108964c8902eSHuang Ying 	 */
109064c8902eSHuang Ying 	if (likely(!__folio_test_movable(src)))
109164c8902eSHuang Ying 		mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
109264c8902eSHuang Ying 				    folio_is_file_lru(src), -folio_nr_pages(src));
109364c8902eSHuang Ying 
109464c8902eSHuang Ying 	if (reason != MR_MEMORY_FAILURE)
109564c8902eSHuang Ying 		/* We release the page in page_handle_poison. */
109664c8902eSHuang Ying 		folio_put(src);
109764c8902eSHuang Ying }
109864c8902eSHuang Ying 
1099ebe75e47SHuang Ying /* Obtain the lock on page, remove all ptes. */
11004e096ae1SMatthew Wilcox (Oracle) static int migrate_folio_unmap(new_folio_t get_new_folio,
11014e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
11024e096ae1SMatthew Wilcox (Oracle) 		struct folio *src, struct folio **dstp, enum migrate_mode mode,
11032ef7dbb2SHuang Ying 		enum migrate_reason reason, struct list_head *ret)
1104e24f0b8fSChristoph Lameter {
1105ebe75e47SHuang Ying 	struct folio *dst;
11060dabec93SMinchan Kim 	int rc = -EAGAIN;
110764c8902eSHuang Ying 	int page_was_mapped = 0;
11083f6c8272SMel Gorman 	struct anon_vma *anon_vma = NULL;
1109682a71a1SMatthew Wilcox (Oracle) 	bool is_lru = !__PageMovable(&src->page);
1110ebe75e47SHuang Ying 	bool locked = false;
1111ebe75e47SHuang Ying 	bool dst_locked = false;
1112ebe75e47SHuang Ying 
1113ebe75e47SHuang Ying 	if (folio_ref_count(src) == 1) {
1114ebe75e47SHuang Ying 		/* Folio was freed from under us. So we are done. */
1115ebe75e47SHuang Ying 		folio_clear_active(src);
1116ebe75e47SHuang Ying 		folio_clear_unevictable(src);
1117ebe75e47SHuang Ying 		/* free_pages_prepare() will clear PG_isolated. */
1118ebe75e47SHuang Ying 		list_del(&src->lru);
1119ebe75e47SHuang Ying 		migrate_folio_done(src, reason);
1120ebe75e47SHuang Ying 		return MIGRATEPAGE_SUCCESS;
1121ebe75e47SHuang Ying 	}
1122ebe75e47SHuang Ying 
11234e096ae1SMatthew Wilcox (Oracle) 	dst = get_new_folio(src, private);
11244e096ae1SMatthew Wilcox (Oracle) 	if (!dst)
1125ebe75e47SHuang Ying 		return -ENOMEM;
1126ebe75e47SHuang Ying 	*dstp = dst;
1127ebe75e47SHuang Ying 
1128ebe75e47SHuang Ying 	dst->private = NULL;
112995a402c3SChristoph Lameter 
1130682a71a1SMatthew Wilcox (Oracle) 	if (!folio_trylock(src)) {
11312ef7dbb2SHuang Ying 		if (mode == MIGRATE_ASYNC)
11320dabec93SMinchan Kim 			goto out;
11333e7d3449SMel Gorman 
11343e7d3449SMel Gorman 		/*
11353e7d3449SMel Gorman 		 * It's not safe for direct compaction to call lock_page.
11363e7d3449SMel Gorman 		 * For example, during page readahead pages are added locked
11373e7d3449SMel Gorman 		 * to the LRU. Later, when the IO completes the pages are
11383e7d3449SMel Gorman 		 * marked uptodate and unlocked. However, the queueing
11393e7d3449SMel Gorman 		 * could be merging multiple pages for one bio (e.g.
1140d4388340SMatthew Wilcox (Oracle) 		 * mpage_readahead). If an allocation happens for the
11413e7d3449SMel Gorman 		 * second or third page, the process can end up locking
11423e7d3449SMel Gorman 		 * the same page twice and deadlocking. Rather than
11433e7d3449SMel Gorman 		 * trying to be clever about what pages can be locked,
11443e7d3449SMel Gorman 		 * avoid the use of lock_page for direct compaction
11453e7d3449SMel Gorman 		 * altogether.
11463e7d3449SMel Gorman 		 */
11473e7d3449SMel Gorman 		if (current->flags & PF_MEMALLOC)
11480dabec93SMinchan Kim 			goto out;
11493e7d3449SMel Gorman 
11504bb6dc79SDouglas Anderson 		/*
11514bb6dc79SDouglas Anderson 		 * In "light" mode, we can wait for transient locks (eg
11524bb6dc79SDouglas Anderson 		 * inserting a page into the page table), but it's not
11534bb6dc79SDouglas Anderson 		 * worth waiting for I/O.
11544bb6dc79SDouglas Anderson 		 */
11554bb6dc79SDouglas Anderson 		if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
11564bb6dc79SDouglas Anderson 			goto out;
11574bb6dc79SDouglas Anderson 
1158682a71a1SMatthew Wilcox (Oracle) 		folio_lock(src);
1159e24f0b8fSChristoph Lameter 	}
1160ebe75e47SHuang Ying 	locked = true;
1161e24f0b8fSChristoph Lameter 
1162682a71a1SMatthew Wilcox (Oracle) 	if (folio_test_writeback(src)) {
116311bc82d6SAndrea Arcangeli 		/*
1164fed5b64aSJianguo Wu 		 * Only in the case of a full synchronous migration is it
1165a6bc32b8SMel Gorman 		 * necessary to wait for PageWriteback. In the async case,
1166a6bc32b8SMel Gorman 		 * the retry loop is too short and in the sync-light case,
1167a6bc32b8SMel Gorman 		 * the overhead of stalling is too much
116811bc82d6SAndrea Arcangeli 		 */
11692916ecc0SJérôme Glisse 		switch (mode) {
11702916ecc0SJérôme Glisse 		case MIGRATE_SYNC:
11712916ecc0SJérôme Glisse 		case MIGRATE_SYNC_NO_COPY:
11722916ecc0SJérôme Glisse 			break;
11732916ecc0SJérôme Glisse 		default:
117411bc82d6SAndrea Arcangeli 			rc = -EBUSY;
1175ebe75e47SHuang Ying 			goto out;
117611bc82d6SAndrea Arcangeli 		}
1177682a71a1SMatthew Wilcox (Oracle) 		folio_wait_writeback(src);
1178e24f0b8fSChristoph Lameter 	}
117903f15c86SHugh Dickins 
1180e24f0b8fSChristoph Lameter 	/*
1181682a71a1SMatthew Wilcox (Oracle) 	 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1182682a71a1SMatthew Wilcox (Oracle) 	 * we cannot notice that anon_vma is freed while we migrate a page.
11831ce82b69SHugh Dickins 	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1184dc386d4dSKAMEZAWA Hiroyuki 	 * of migration. File cache pages are no problem because of page_lock()
1185989f89c5SKAMEZAWA Hiroyuki 	 * File Caches may use write_page() or lock_page() in migration, then,
1186989f89c5SKAMEZAWA Hiroyuki 	 * just care Anon page here.
11873fe2011fSMel Gorman 	 *
118829eea9b5SMatthew Wilcox (Oracle) 	 * Only folio_get_anon_vma() understands the subtleties of
118903f15c86SHugh Dickins 	 * getting a hold on an anon_vma from outside one of its mms.
119003f15c86SHugh Dickins 	 * But if we cannot get anon_vma, then we won't need it anyway,
119103f15c86SHugh Dickins 	 * because that implies that the anon page is no longer mapped
119203f15c86SHugh Dickins 	 * (and cannot be remapped so long as we hold the page lock).
11933fe2011fSMel Gorman 	 */
1194682a71a1SMatthew Wilcox (Oracle) 	if (folio_test_anon(src) && !folio_test_ksm(src))
119529eea9b5SMatthew Wilcox (Oracle) 		anon_vma = folio_get_anon_vma(src);
119662e1c553SShaohua Li 
11977db7671fSHugh Dickins 	/*
11987db7671fSHugh Dickins 	 * Block others from accessing the new page when we get around to
11997db7671fSHugh Dickins 	 * establishing additional references. We are usually the only one
1200682a71a1SMatthew Wilcox (Oracle) 	 * holding a reference to dst at this point. We used to have a BUG
1201682a71a1SMatthew Wilcox (Oracle) 	 * here if folio_trylock(dst) fails, but would like to allow for
1202682a71a1SMatthew Wilcox (Oracle) 	 * cases where there might be a race with the previous use of dst.
12037db7671fSHugh Dickins 	 * This is much like races on refcount of oldpage: just don't BUG().
12047db7671fSHugh Dickins 	 */
1205682a71a1SMatthew Wilcox (Oracle) 	if (unlikely(!folio_trylock(dst)))
1206ebe75e47SHuang Ying 		goto out;
1207ebe75e47SHuang Ying 	dst_locked = true;
12087db7671fSHugh Dickins 
1209bda807d4SMinchan Kim 	if (unlikely(!is_lru)) {
121064c8902eSHuang Ying 		__migrate_folio_record(dst, page_was_mapped, anon_vma);
121164c8902eSHuang Ying 		return MIGRATEPAGE_UNMAP;
1212bda807d4SMinchan Kim 	}
1213bda807d4SMinchan Kim 
1214dc386d4dSKAMEZAWA Hiroyuki 	/*
121562e1c553SShaohua Li 	 * Corner case handling:
121662e1c553SShaohua Li 	 * 1. When a new swap-cache page is read into, it is added to the LRU
121762e1c553SShaohua Li 	 * and treated as swapcache but it has no rmap yet.
1218682a71a1SMatthew Wilcox (Oracle) 	 * Calling try_to_unmap() against a src->mapping==NULL page will
121962e1c553SShaohua Li 	 * trigger a BUG.  So handle it here.
1220d12b8951SYang Shi 	 * 2. An orphaned page (see truncate_cleanup_page) might have
122162e1c553SShaohua Li 	 * fs-private metadata. The page can be picked up due to memory
122262e1c553SShaohua Li 	 * offlining.  Everywhere else except page reclaim, the page is
122362e1c553SShaohua Li 	 * invisible to the vm, so the page can not be migrated.  So try to
122462e1c553SShaohua Li 	 * free the metadata, so the page can be freed.
1225dc386d4dSKAMEZAWA Hiroyuki 	 */
1226682a71a1SMatthew Wilcox (Oracle) 	if (!src->mapping) {
1227682a71a1SMatthew Wilcox (Oracle) 		if (folio_test_private(src)) {
1228682a71a1SMatthew Wilcox (Oracle) 			try_to_free_buffers(src);
1229ebe75e47SHuang Ying 			goto out;
123062e1c553SShaohua Li 		}
1231682a71a1SMatthew Wilcox (Oracle) 	} else if (folio_mapped(src)) {
12327db7671fSHugh Dickins 		/* Establish migration ptes */
1233682a71a1SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1234682a71a1SMatthew Wilcox (Oracle) 			       !folio_test_ksm(src) && !anon_vma, src);
1235fb3592c4SHuang Ying 		try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
123664c8902eSHuang Ying 		page_was_mapped = 1;
12372ebba6b7SHugh Dickins 	}
1238dc386d4dSKAMEZAWA Hiroyuki 
123964c8902eSHuang Ying 	if (!folio_mapped(src)) {
124064c8902eSHuang Ying 		__migrate_folio_record(dst, page_was_mapped, anon_vma);
124164c8902eSHuang Ying 		return MIGRATEPAGE_UNMAP;
124264c8902eSHuang Ying 	}
124364c8902eSHuang Ying 
124464c8902eSHuang Ying out:
124580562ba0SHuang Ying 	/*
124680562ba0SHuang Ying 	 * A folio that has not been unmapped will be restored to
124780562ba0SHuang Ying 	 * right list unless we want to retry.
124880562ba0SHuang Ying 	 */
1249fb3592c4SHuang Ying 	if (rc == -EAGAIN)
1250ebe75e47SHuang Ying 		ret = NULL;
125180562ba0SHuang Ying 
1252ebe75e47SHuang Ying 	migrate_folio_undo_src(src, page_was_mapped, anon_vma, locked, ret);
12534e096ae1SMatthew Wilcox (Oracle) 	migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
125480562ba0SHuang Ying 
125580562ba0SHuang Ying 	return rc;
125680562ba0SHuang Ying }
125780562ba0SHuang Ying 
1258ebe75e47SHuang Ying /* Migrate the folio to the newly allocated folio in dst. */
12594e096ae1SMatthew Wilcox (Oracle) static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
1260ebe75e47SHuang Ying 			      struct folio *src, struct folio *dst,
1261ebe75e47SHuang Ying 			      enum migrate_mode mode, enum migrate_reason reason,
1262ebe75e47SHuang Ying 			      struct list_head *ret)
126364c8902eSHuang Ying {
126464c8902eSHuang Ying 	int rc;
126564c8902eSHuang Ying 	int page_was_mapped = 0;
126664c8902eSHuang Ying 	struct anon_vma *anon_vma = NULL;
126764c8902eSHuang Ying 	bool is_lru = !__PageMovable(&src->page);
12685dfab109SHuang Ying 	struct list_head *prev;
126964c8902eSHuang Ying 
127064c8902eSHuang Ying 	__migrate_folio_extract(dst, &page_was_mapped, &anon_vma);
12715dfab109SHuang Ying 	prev = dst->lru.prev;
12725dfab109SHuang Ying 	list_del(&dst->lru);
127364c8902eSHuang Ying 
1274682a71a1SMatthew Wilcox (Oracle) 	rc = move_to_new_folio(dst, src, mode);
1275ebe75e47SHuang Ying 	if (rc)
1276ebe75e47SHuang Ying 		goto out;
12775dfab109SHuang Ying 
127864c8902eSHuang Ying 	if (unlikely(!is_lru))
127964c8902eSHuang Ying 		goto out_unlock_both;
1280e24f0b8fSChristoph Lameter 
1281c3096e67SHugh Dickins 	/*
1282682a71a1SMatthew Wilcox (Oracle) 	 * When successful, push dst to LRU immediately: so that if it
1283c3096e67SHugh Dickins 	 * turns out to be an mlocked page, remove_migration_ptes() will
1284682a71a1SMatthew Wilcox (Oracle) 	 * automatically build up the correct dst->mlock_count for it.
1285c3096e67SHugh Dickins 	 *
1286c3096e67SHugh Dickins 	 * We would like to do something similar for the old page, when
1287c3096e67SHugh Dickins 	 * unsuccessful, and other cases when a page has been temporarily
1288c3096e67SHugh Dickins 	 * isolated from the unevictable LRU: but this case is the easiest.
1289c3096e67SHugh Dickins 	 */
1290682a71a1SMatthew Wilcox (Oracle) 	folio_add_lru(dst);
12915c3f9a67SHugh Dickins 	if (page_was_mapped)
1292c3096e67SHugh Dickins 		lru_add_drain();
1293c3096e67SHugh Dickins 
12945c3f9a67SHugh Dickins 	if (page_was_mapped)
1295ebe75e47SHuang Ying 		remove_migration_ptes(src, dst, false);
12963f6c8272SMel Gorman 
12977db7671fSHugh Dickins out_unlock_both:
1298682a71a1SMatthew Wilcox (Oracle) 	folio_unlock(dst);
1299ebe75e47SHuang Ying 	set_page_owner_migrate_reason(&dst->page, reason);
1300c6c919ebSMinchan Kim 	/*
1301682a71a1SMatthew Wilcox (Oracle) 	 * If migration is successful, decrease refcount of dst,
1302c6c919ebSMinchan Kim 	 * which will not free the page because new page owner increased
1303c3096e67SHugh Dickins 	 * refcounter.
1304c6c919ebSMinchan Kim 	 */
1305682a71a1SMatthew Wilcox (Oracle) 	folio_put(dst);
1306c6c919ebSMinchan Kim 
1307ebe75e47SHuang Ying 	/*
1308ebe75e47SHuang Ying 	 * A folio that has been migrated has all references removed
1309ebe75e47SHuang Ying 	 * and will be freed.
1310ebe75e47SHuang Ying 	 */
1311ebe75e47SHuang Ying 	list_del(&src->lru);
1312ebe75e47SHuang Ying 	/* Drop an anon_vma reference if we took one */
1313ebe75e47SHuang Ying 	if (anon_vma)
1314ebe75e47SHuang Ying 		put_anon_vma(anon_vma);
1315ebe75e47SHuang Ying 	folio_unlock(src);
1316ebe75e47SHuang Ying 	migrate_folio_done(src, reason);
1317ebe75e47SHuang Ying 
1318ebe75e47SHuang Ying 	return rc;
1319ebe75e47SHuang Ying out:
1320ebe75e47SHuang Ying 	/*
1321ebe75e47SHuang Ying 	 * A folio that has not been migrated will be restored to
1322ebe75e47SHuang Ying 	 * right list unless we want to retry.
1323ebe75e47SHuang Ying 	 */
1324ebe75e47SHuang Ying 	if (rc == -EAGAIN) {
1325ebe75e47SHuang Ying 		list_add(&dst->lru, prev);
1326ebe75e47SHuang Ying 		__migrate_folio_record(dst, page_was_mapped, anon_vma);
13270dabec93SMinchan Kim 		return rc;
13280dabec93SMinchan Kim 	}
132995a402c3SChristoph Lameter 
1330ebe75e47SHuang Ying 	migrate_folio_undo_src(src, page_was_mapped, anon_vma, true, ret);
13314e096ae1SMatthew Wilcox (Oracle) 	migrate_folio_undo_dst(dst, true, put_new_folio, private);
133268711a74SDavid Rientjes 
1333e24f0b8fSChristoph Lameter 	return rc;
1334e24f0b8fSChristoph Lameter }
1335b20a3503SChristoph Lameter 
1336e24f0b8fSChristoph Lameter /*
1337290408d4SNaoya Horiguchi  * Counterpart of unmap_and_move_page() for hugepage migration.
1338290408d4SNaoya Horiguchi  *
1339290408d4SNaoya Horiguchi  * This function doesn't wait the completion of hugepage I/O
1340290408d4SNaoya Horiguchi  * because there is no race between I/O and migration for hugepage.
1341290408d4SNaoya Horiguchi  * Note that currently hugepage I/O occurs only in direct I/O
1342290408d4SNaoya Horiguchi  * where no lock is held and PG_writeback is irrelevant,
1343290408d4SNaoya Horiguchi  * and writeback status of all subpages are counted in the reference
1344290408d4SNaoya Horiguchi  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1345290408d4SNaoya Horiguchi  * under direct I/O, the reference of the head page is 512 and a bit more.)
1346290408d4SNaoya Horiguchi  * This means that when we try to migrate hugepage whose subpages are
1347290408d4SNaoya Horiguchi  * doing direct I/O, some references remain after try_to_unmap() and
1348290408d4SNaoya Horiguchi  * hugepage migration fails without data corruption.
1349290408d4SNaoya Horiguchi  *
1350290408d4SNaoya Horiguchi  * There is also no race when direct I/O is issued on the page under migration,
1351290408d4SNaoya Horiguchi  * because then pte is replaced with migration swap entry and direct I/O code
1352290408d4SNaoya Horiguchi  * will wait in the page fault for migration to complete.
1353290408d4SNaoya Horiguchi  */
13544e096ae1SMatthew Wilcox (Oracle) static int unmap_and_move_huge_page(new_folio_t get_new_folio,
13554e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
13564e096ae1SMatthew Wilcox (Oracle) 		struct folio *src, int force, enum migrate_mode mode,
13574e096ae1SMatthew Wilcox (Oracle) 		int reason, struct list_head *ret)
1358290408d4SNaoya Horiguchi {
13594e096ae1SMatthew Wilcox (Oracle) 	struct folio *dst;
13602def7424SHugh Dickins 	int rc = -EAGAIN;
13612ebba6b7SHugh Dickins 	int page_was_mapped = 0;
1362290408d4SNaoya Horiguchi 	struct anon_vma *anon_vma = NULL;
1363c0d0381aSMike Kravetz 	struct address_space *mapping = NULL;
1364290408d4SNaoya Horiguchi 
1365c33db292SMatthew Wilcox (Oracle) 	if (folio_ref_count(src) == 1) {
136671a64f61SMuchun Song 		/* page was freed from under us. So we are done. */
1367ea8e72f4SSidhartha Kumar 		folio_putback_active_hugetlb(src);
136871a64f61SMuchun Song 		return MIGRATEPAGE_SUCCESS;
136971a64f61SMuchun Song 	}
137071a64f61SMuchun Song 
13714e096ae1SMatthew Wilcox (Oracle) 	dst = get_new_folio(src, private);
13724e096ae1SMatthew Wilcox (Oracle) 	if (!dst)
1373290408d4SNaoya Horiguchi 		return -ENOMEM;
1374290408d4SNaoya Horiguchi 
1375c33db292SMatthew Wilcox (Oracle) 	if (!folio_trylock(src)) {
13762916ecc0SJérôme Glisse 		if (!force)
1377290408d4SNaoya Horiguchi 			goto out;
13782916ecc0SJérôme Glisse 		switch (mode) {
13792916ecc0SJérôme Glisse 		case MIGRATE_SYNC:
13802916ecc0SJérôme Glisse 		case MIGRATE_SYNC_NO_COPY:
13812916ecc0SJérôme Glisse 			break;
13822916ecc0SJérôme Glisse 		default:
13832916ecc0SJérôme Glisse 			goto out;
13842916ecc0SJérôme Glisse 		}
1385c33db292SMatthew Wilcox (Oracle) 		folio_lock(src);
1386290408d4SNaoya Horiguchi 	}
1387290408d4SNaoya Horiguchi 
1388cb6acd01SMike Kravetz 	/*
1389cb6acd01SMike Kravetz 	 * Check for pages which are in the process of being freed.  Without
1390c33db292SMatthew Wilcox (Oracle) 	 * folio_mapping() set, hugetlbfs specific move page routine will not
1391cb6acd01SMike Kravetz 	 * be called and we could leak usage counts for subpools.
1392cb6acd01SMike Kravetz 	 */
1393345c62d1SSidhartha Kumar 	if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1394cb6acd01SMike Kravetz 		rc = -EBUSY;
1395cb6acd01SMike Kravetz 		goto out_unlock;
1396cb6acd01SMike Kravetz 	}
1397cb6acd01SMike Kravetz 
1398c33db292SMatthew Wilcox (Oracle) 	if (folio_test_anon(src))
139929eea9b5SMatthew Wilcox (Oracle) 		anon_vma = folio_get_anon_vma(src);
1400290408d4SNaoya Horiguchi 
1401c33db292SMatthew Wilcox (Oracle) 	if (unlikely(!folio_trylock(dst)))
14027db7671fSHugh Dickins 		goto put_anon;
14037db7671fSHugh Dickins 
1404c33db292SMatthew Wilcox (Oracle) 	if (folio_mapped(src)) {
1405a98a2f0cSAlistair Popple 		enum ttu_flags ttu = 0;
1406336bf30eSMike Kravetz 
1407c33db292SMatthew Wilcox (Oracle) 		if (!folio_test_anon(src)) {
1408c0d0381aSMike Kravetz 			/*
1409336bf30eSMike Kravetz 			 * In shared mappings, try_to_unmap could potentially
1410336bf30eSMike Kravetz 			 * call huge_pmd_unshare.  Because of this, take
1411336bf30eSMike Kravetz 			 * semaphore in write mode here and set TTU_RMAP_LOCKED
1412336bf30eSMike Kravetz 			 * to let lower levels know we have taken the lock.
1413c0d0381aSMike Kravetz 			 */
14144e096ae1SMatthew Wilcox (Oracle) 			mapping = hugetlb_page_mapping_lock_write(&src->page);
1415c0d0381aSMike Kravetz 			if (unlikely(!mapping))
1416c0d0381aSMike Kravetz 				goto unlock_put_anon;
1417c0d0381aSMike Kravetz 
14185202978bSMiaohe Lin 			ttu = TTU_RMAP_LOCKED;
1419336bf30eSMike Kravetz 		}
1420336bf30eSMike Kravetz 
14214b8554c5SMatthew Wilcox (Oracle) 		try_to_migrate(src, ttu);
14222ebba6b7SHugh Dickins 		page_was_mapped = 1;
1423336bf30eSMike Kravetz 
14245202978bSMiaohe Lin 		if (ttu & TTU_RMAP_LOCKED)
1425336bf30eSMike Kravetz 			i_mmap_unlock_write(mapping);
14262ebba6b7SHugh Dickins 	}
1427290408d4SNaoya Horiguchi 
1428c33db292SMatthew Wilcox (Oracle) 	if (!folio_mapped(src))
1429e7e3ffebSMatthew Wilcox (Oracle) 		rc = move_to_new_folio(dst, src, mode);
1430290408d4SNaoya Horiguchi 
1431336bf30eSMike Kravetz 	if (page_was_mapped)
14324eecb8b9SMatthew Wilcox (Oracle) 		remove_migration_ptes(src,
14334eecb8b9SMatthew Wilcox (Oracle) 			rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1434290408d4SNaoya Horiguchi 
1435c0d0381aSMike Kravetz unlock_put_anon:
1436c33db292SMatthew Wilcox (Oracle) 	folio_unlock(dst);
14377db7671fSHugh Dickins 
14387db7671fSHugh Dickins put_anon:
1439fd4a4663SHugh Dickins 	if (anon_vma)
14409e60109fSPeter Zijlstra 		put_anon_vma(anon_vma);
14418e6ac7faSAneesh Kumar K.V 
14422def7424SHugh Dickins 	if (rc == MIGRATEPAGE_SUCCESS) {
1443345c62d1SSidhartha Kumar 		move_hugetlb_state(src, dst, reason);
14444e096ae1SMatthew Wilcox (Oracle) 		put_new_folio = NULL;
14452def7424SHugh Dickins 	}
14468e6ac7faSAneesh Kumar K.V 
1447cb6acd01SMike Kravetz out_unlock:
1448c33db292SMatthew Wilcox (Oracle) 	folio_unlock(src);
144909761333SHillf Danton out:
1450dd4ae78aSYang Shi 	if (rc == MIGRATEPAGE_SUCCESS)
1451ea8e72f4SSidhartha Kumar 		folio_putback_active_hugetlb(src);
1452a04840c6SMiaohe Lin 	else if (rc != -EAGAIN)
1453c33db292SMatthew Wilcox (Oracle) 		list_move_tail(&src->lru, ret);
145468711a74SDavid Rientjes 
145568711a74SDavid Rientjes 	/*
145668711a74SDavid Rientjes 	 * If migration was not successful and there's a freeing callback, use
145768711a74SDavid Rientjes 	 * it.  Otherwise, put_page() will drop the reference grabbed during
145868711a74SDavid Rientjes 	 * isolation.
145968711a74SDavid Rientjes 	 */
14604e096ae1SMatthew Wilcox (Oracle) 	if (put_new_folio)
14614e096ae1SMatthew Wilcox (Oracle) 		put_new_folio(dst, private);
146268711a74SDavid Rientjes 	else
1463ea8e72f4SSidhartha Kumar 		folio_putback_active_hugetlb(dst);
146468711a74SDavid Rientjes 
1465290408d4SNaoya Horiguchi 	return rc;
1466290408d4SNaoya Horiguchi }
1467290408d4SNaoya Horiguchi 
1468eaec4e63SHuang Ying static inline int try_split_folio(struct folio *folio, struct list_head *split_folios)
1469d532e2e5SYang Shi {
14709c62ff00SHuang Ying 	int rc;
1471d532e2e5SYang Shi 
1472eaec4e63SHuang Ying 	folio_lock(folio);
1473eaec4e63SHuang Ying 	rc = split_folio_to_list(folio, split_folios);
1474eaec4e63SHuang Ying 	folio_unlock(folio);
1475e6fa8a79SHuang Ying 	if (!rc)
1476eaec4e63SHuang Ying 		list_move_tail(&folio->lru, split_folios);
1477d532e2e5SYang Shi 
1478d532e2e5SYang Shi 	return rc;
1479d532e2e5SYang Shi }
1480d532e2e5SYang Shi 
148142012e04SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
148242012e04SHuang Ying #define NR_MAX_BATCHED_MIGRATION	HPAGE_PMD_NR
148342012e04SHuang Ying #else
148442012e04SHuang Ying #define NR_MAX_BATCHED_MIGRATION	512
148542012e04SHuang Ying #endif
1486e5bfff8bSHuang Ying #define NR_MAX_MIGRATE_PAGES_RETRY	10
14872ef7dbb2SHuang Ying #define NR_MAX_MIGRATE_ASYNC_RETRY	3
14882ef7dbb2SHuang Ying #define NR_MAX_MIGRATE_SYNC_RETRY					\
14892ef7dbb2SHuang Ying 	(NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
1490e5bfff8bSHuang Ying 
14915b855937SHuang Ying struct migrate_pages_stats {
14925b855937SHuang Ying 	int nr_succeeded;	/* Normal and large folios migrated successfully, in
14935b855937SHuang Ying 				   units of base pages */
14945b855937SHuang Ying 	int nr_failed_pages;	/* Normal and large folios failed to be migrated, in
14955b855937SHuang Ying 				   units of base pages.  Untried folios aren't counted */
14965b855937SHuang Ying 	int nr_thp_succeeded;	/* THP migrated successfully */
14975b855937SHuang Ying 	int nr_thp_failed;	/* THP failed to be migrated */
14985b855937SHuang Ying 	int nr_thp_split;	/* THP split before migrating */
14995b855937SHuang Ying };
15005b855937SHuang Ying 
1501290408d4SNaoya Horiguchi /*
1502e5bfff8bSHuang Ying  * Returns the number of hugetlb folios that were not migrated, or an error code
1503e5bfff8bSHuang Ying  * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
1504e5bfff8bSHuang Ying  * any more because the list has become empty or no retryable hugetlb folios
1505e5bfff8bSHuang Ying  * exist any more. It is caller's responsibility to call putback_movable_pages()
1506e5bfff8bSHuang Ying  * only if ret != 0.
1507e5bfff8bSHuang Ying  */
15084e096ae1SMatthew Wilcox (Oracle) static int migrate_hugetlbs(struct list_head *from, new_folio_t get_new_folio,
15094e096ae1SMatthew Wilcox (Oracle) 			    free_folio_t put_new_folio, unsigned long private,
1510e5bfff8bSHuang Ying 			    enum migrate_mode mode, int reason,
1511e5bfff8bSHuang Ying 			    struct migrate_pages_stats *stats,
1512e5bfff8bSHuang Ying 			    struct list_head *ret_folios)
1513e5bfff8bSHuang Ying {
1514e5bfff8bSHuang Ying 	int retry = 1;
1515e5bfff8bSHuang Ying 	int nr_failed = 0;
1516e5bfff8bSHuang Ying 	int nr_retry_pages = 0;
1517e5bfff8bSHuang Ying 	int pass = 0;
1518e5bfff8bSHuang Ying 	struct folio *folio, *folio2;
1519e5bfff8bSHuang Ying 	int rc, nr_pages;
1520e5bfff8bSHuang Ying 
1521e5bfff8bSHuang Ying 	for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
1522e5bfff8bSHuang Ying 		retry = 0;
1523e5bfff8bSHuang Ying 		nr_retry_pages = 0;
1524e5bfff8bSHuang Ying 
1525e5bfff8bSHuang Ying 		list_for_each_entry_safe(folio, folio2, from, lru) {
1526e5bfff8bSHuang Ying 			if (!folio_test_hugetlb(folio))
1527e5bfff8bSHuang Ying 				continue;
1528e5bfff8bSHuang Ying 
1529e5bfff8bSHuang Ying 			nr_pages = folio_nr_pages(folio);
1530e5bfff8bSHuang Ying 
1531e5bfff8bSHuang Ying 			cond_resched();
1532e5bfff8bSHuang Ying 
15336f7d760eSHuang Ying 			/*
15346f7d760eSHuang Ying 			 * Migratability of hugepages depends on architectures and
15356f7d760eSHuang Ying 			 * their size.  This check is necessary because some callers
15366f7d760eSHuang Ying 			 * of hugepage migration like soft offline and memory
15376f7d760eSHuang Ying 			 * hotremove don't walk through page tables or check whether
15386f7d760eSHuang Ying 			 * the hugepage is pmd-based or not before kicking migration.
15396f7d760eSHuang Ying 			 */
15406f7d760eSHuang Ying 			if (!hugepage_migration_supported(folio_hstate(folio))) {
15416f7d760eSHuang Ying 				nr_failed++;
15426f7d760eSHuang Ying 				stats->nr_failed_pages += nr_pages;
15436f7d760eSHuang Ying 				list_move_tail(&folio->lru, ret_folios);
15446f7d760eSHuang Ying 				continue;
15456f7d760eSHuang Ying 			}
15466f7d760eSHuang Ying 
15474e096ae1SMatthew Wilcox (Oracle) 			rc = unmap_and_move_huge_page(get_new_folio,
15484e096ae1SMatthew Wilcox (Oracle) 						      put_new_folio, private,
15494e096ae1SMatthew Wilcox (Oracle) 						      folio, pass > 2, mode,
1550e5bfff8bSHuang Ying 						      reason, ret_folios);
1551e5bfff8bSHuang Ying 			/*
1552e5bfff8bSHuang Ying 			 * The rules are:
1553e5bfff8bSHuang Ying 			 *	Success: hugetlb folio will be put back
1554e5bfff8bSHuang Ying 			 *	-EAGAIN: stay on the from list
1555e5bfff8bSHuang Ying 			 *	-ENOMEM: stay on the from list
1556e5bfff8bSHuang Ying 			 *	Other errno: put on ret_folios list
1557e5bfff8bSHuang Ying 			 */
1558e5bfff8bSHuang Ying 			switch(rc) {
1559e5bfff8bSHuang Ying 			case -ENOMEM:
1560e5bfff8bSHuang Ying 				/*
1561e5bfff8bSHuang Ying 				 * When memory is low, don't bother to try to migrate
1562e5bfff8bSHuang Ying 				 * other folios, just exit.
1563e5bfff8bSHuang Ying 				 */
1564e5bfff8bSHuang Ying 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
1565e5bfff8bSHuang Ying 				return -ENOMEM;
1566e5bfff8bSHuang Ying 			case -EAGAIN:
1567e5bfff8bSHuang Ying 				retry++;
1568e5bfff8bSHuang Ying 				nr_retry_pages += nr_pages;
1569e5bfff8bSHuang Ying 				break;
1570e5bfff8bSHuang Ying 			case MIGRATEPAGE_SUCCESS:
1571e5bfff8bSHuang Ying 				stats->nr_succeeded += nr_pages;
1572e5bfff8bSHuang Ying 				break;
1573e5bfff8bSHuang Ying 			default:
1574e5bfff8bSHuang Ying 				/*
1575e5bfff8bSHuang Ying 				 * Permanent failure (-EBUSY, etc.):
1576e5bfff8bSHuang Ying 				 * unlike -EAGAIN case, the failed folio is
1577e5bfff8bSHuang Ying 				 * removed from migration folio list and not
1578e5bfff8bSHuang Ying 				 * retried in the next outer loop.
1579e5bfff8bSHuang Ying 				 */
1580e5bfff8bSHuang Ying 				nr_failed++;
1581e5bfff8bSHuang Ying 				stats->nr_failed_pages += nr_pages;
1582e5bfff8bSHuang Ying 				break;
1583e5bfff8bSHuang Ying 			}
1584e5bfff8bSHuang Ying 		}
1585e5bfff8bSHuang Ying 	}
1586e5bfff8bSHuang Ying 	/*
1587e5bfff8bSHuang Ying 	 * nr_failed is number of hugetlb folios failed to be migrated.  After
1588e5bfff8bSHuang Ying 	 * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
1589e5bfff8bSHuang Ying 	 * folios as failed.
1590e5bfff8bSHuang Ying 	 */
1591e5bfff8bSHuang Ying 	nr_failed += retry;
1592e5bfff8bSHuang Ying 	stats->nr_failed_pages += nr_retry_pages;
1593e5bfff8bSHuang Ying 
1594e5bfff8bSHuang Ying 	return nr_failed;
1595e5bfff8bSHuang Ying }
1596e5bfff8bSHuang Ying 
15975dfab109SHuang Ying /*
15985dfab109SHuang Ying  * migrate_pages_batch() first unmaps folios in the from list as many as
15995dfab109SHuang Ying  * possible, then move the unmapped folios.
1600fb3592c4SHuang Ying  *
1601fb3592c4SHuang Ying  * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
1602fb3592c4SHuang Ying  * lock or bit when we have locked more than one folio.  Which may cause
1603fb3592c4SHuang Ying  * deadlock (e.g., for loop device).  So, if mode != MIGRATE_ASYNC, the
1604fb3592c4SHuang Ying  * length of the from list must be <= 1.
16055dfab109SHuang Ying  */
16064e096ae1SMatthew Wilcox (Oracle) static int migrate_pages_batch(struct list_head *from,
16074e096ae1SMatthew Wilcox (Oracle) 		new_folio_t get_new_folio, free_folio_t put_new_folio,
16084e096ae1SMatthew Wilcox (Oracle) 		unsigned long private, enum migrate_mode mode, int reason,
16094e096ae1SMatthew Wilcox (Oracle) 		struct list_head *ret_folios, struct list_head *split_folios,
16104e096ae1SMatthew Wilcox (Oracle) 		struct migrate_pages_stats *stats, int nr_pass)
161142012e04SHuang Ying {
1612a21d2133SHuang Ying 	int retry = 1;
161342012e04SHuang Ying 	int thp_retry = 1;
161442012e04SHuang Ying 	int nr_failed = 0;
161542012e04SHuang Ying 	int nr_retry_pages = 0;
161642012e04SHuang Ying 	int pass = 0;
161742012e04SHuang Ying 	bool is_thp = false;
16185dfab109SHuang Ying 	struct folio *folio, *folio2, *dst = NULL, *dst2;
1619a21d2133SHuang Ying 	int rc, rc_saved = 0, nr_pages;
16205dfab109SHuang Ying 	LIST_HEAD(unmap_folios);
16215dfab109SHuang Ying 	LIST_HEAD(dst_folios);
162242012e04SHuang Ying 	bool nosplit = (reason == MR_NUMA_MISPLACED);
162342012e04SHuang Ying 
1624fb3592c4SHuang Ying 	VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
1625fb3592c4SHuang Ying 			!list_empty(from) && !list_is_singular(from));
1626a21d2133SHuang Ying 
1627124abcedSHuang Ying 	for (pass = 0; pass < nr_pass && retry; pass++) {
162842012e04SHuang Ying 		retry = 0;
162942012e04SHuang Ying 		thp_retry = 0;
163042012e04SHuang Ying 		nr_retry_pages = 0;
163142012e04SHuang Ying 
163242012e04SHuang Ying 		list_for_each_entry_safe(folio, folio2, from, lru) {
1633124abcedSHuang Ying 			is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
163442012e04SHuang Ying 			nr_pages = folio_nr_pages(folio);
163542012e04SHuang Ying 
163642012e04SHuang Ying 			cond_resched();
163742012e04SHuang Ying 
16386f7d760eSHuang Ying 			/*
16396f7d760eSHuang Ying 			 * Large folio migration might be unsupported or
16406f7d760eSHuang Ying 			 * the allocation might be failed so we should retry
16416f7d760eSHuang Ying 			 * on the same folio with the large folio split
16426f7d760eSHuang Ying 			 * to normal folios.
16436f7d760eSHuang Ying 			 *
16446f7d760eSHuang Ying 			 * Split folios are put in split_folios, and
16456f7d760eSHuang Ying 			 * we will migrate them after the rest of the
16466f7d760eSHuang Ying 			 * list is processed.
16476f7d760eSHuang Ying 			 */
16486f7d760eSHuang Ying 			if (!thp_migration_supported() && is_thp) {
1649124abcedSHuang Ying 				nr_failed++;
16506f7d760eSHuang Ying 				stats->nr_thp_failed++;
1651a21d2133SHuang Ying 				if (!try_split_folio(folio, split_folios)) {
16526f7d760eSHuang Ying 					stats->nr_thp_split++;
16536f7d760eSHuang Ying 					continue;
16546f7d760eSHuang Ying 				}
16556f7d760eSHuang Ying 				stats->nr_failed_pages += nr_pages;
16566f7d760eSHuang Ying 				list_move_tail(&folio->lru, ret_folios);
16576f7d760eSHuang Ying 				continue;
16586f7d760eSHuang Ying 			}
16596f7d760eSHuang Ying 
16604e096ae1SMatthew Wilcox (Oracle) 			rc = migrate_folio_unmap(get_new_folio, put_new_folio,
16614e096ae1SMatthew Wilcox (Oracle) 					private, folio, &dst, mode, reason,
16624e096ae1SMatthew Wilcox (Oracle) 					ret_folios);
166342012e04SHuang Ying 			/*
166442012e04SHuang Ying 			 * The rules are:
166542012e04SHuang Ying 			 *	Success: folio will be freed
16665dfab109SHuang Ying 			 *	Unmap: folio will be put on unmap_folios list,
16675dfab109SHuang Ying 			 *	       dst folio put on dst_folios list
166842012e04SHuang Ying 			 *	-EAGAIN: stay on the from list
166942012e04SHuang Ying 			 *	-ENOMEM: stay on the from list
167042012e04SHuang Ying 			 *	Other errno: put on ret_folios list
167142012e04SHuang Ying 			 */
167242012e04SHuang Ying 			switch(rc) {
167342012e04SHuang Ying 			case -ENOMEM:
167442012e04SHuang Ying 				/*
167542012e04SHuang Ying 				 * When memory is low, don't bother to try to migrate
16765dfab109SHuang Ying 				 * other folios, move unmapped folios, then exit.
167742012e04SHuang Ying 				 */
1678124abcedSHuang Ying 				nr_failed++;
167942012e04SHuang Ying 				stats->nr_thp_failed += is_thp;
168042012e04SHuang Ying 				/* Large folio NUMA faulting doesn't split to retry. */
1681124abcedSHuang Ying 				if (folio_test_large(folio) && !nosplit) {
1682a21d2133SHuang Ying 					int ret = try_split_folio(folio, split_folios);
168342012e04SHuang Ying 
168442012e04SHuang Ying 					if (!ret) {
168542012e04SHuang Ying 						stats->nr_thp_split += is_thp;
168642012e04SHuang Ying 						break;
168742012e04SHuang Ying 					} else if (reason == MR_LONGTERM_PIN &&
168842012e04SHuang Ying 						   ret == -EAGAIN) {
168942012e04SHuang Ying 						/*
169042012e04SHuang Ying 						 * Try again to split large folio to
169142012e04SHuang Ying 						 * mitigate the failure of longterm pinning.
169242012e04SHuang Ying 						 */
1693124abcedSHuang Ying 						retry++;
169442012e04SHuang Ying 						thp_retry += is_thp;
169542012e04SHuang Ying 						nr_retry_pages += nr_pages;
1696851ae642SHuang Ying 						/* Undo duplicated failure counting. */
1697124abcedSHuang Ying 						nr_failed--;
1698851ae642SHuang Ying 						stats->nr_thp_failed -= is_thp;
169942012e04SHuang Ying 						break;
170042012e04SHuang Ying 					}
170142012e04SHuang Ying 				}
170242012e04SHuang Ying 
170342012e04SHuang Ying 				stats->nr_failed_pages += nr_pages + nr_retry_pages;
170442012e04SHuang Ying 				/* nr_failed isn't updated for not used */
170542012e04SHuang Ying 				stats->nr_thp_failed += thp_retry;
17065dfab109SHuang Ying 				rc_saved = rc;
17075dfab109SHuang Ying 				if (list_empty(&unmap_folios))
170842012e04SHuang Ying 					goto out;
17095dfab109SHuang Ying 				else
17105dfab109SHuang Ying 					goto move;
171142012e04SHuang Ying 			case -EAGAIN:
171242012e04SHuang Ying 				retry++;
1713124abcedSHuang Ying 				thp_retry += is_thp;
171442012e04SHuang Ying 				nr_retry_pages += nr_pages;
171542012e04SHuang Ying 				break;
171642012e04SHuang Ying 			case MIGRATEPAGE_SUCCESS:
171742012e04SHuang Ying 				stats->nr_succeeded += nr_pages;
171842012e04SHuang Ying 				stats->nr_thp_succeeded += is_thp;
171942012e04SHuang Ying 				break;
17205dfab109SHuang Ying 			case MIGRATEPAGE_UNMAP:
17215dfab109SHuang Ying 				list_move_tail(&folio->lru, &unmap_folios);
17225dfab109SHuang Ying 				list_add_tail(&dst->lru, &dst_folios);
17235dfab109SHuang Ying 				break;
172442012e04SHuang Ying 			default:
172542012e04SHuang Ying 				/*
172642012e04SHuang Ying 				 * Permanent failure (-EBUSY, etc.):
172742012e04SHuang Ying 				 * unlike -EAGAIN case, the failed folio is
172842012e04SHuang Ying 				 * removed from migration folio list and not
172942012e04SHuang Ying 				 * retried in the next outer loop.
173042012e04SHuang Ying 				 */
173142012e04SHuang Ying 				nr_failed++;
1732124abcedSHuang Ying 				stats->nr_thp_failed += is_thp;
173342012e04SHuang Ying 				stats->nr_failed_pages += nr_pages;
173442012e04SHuang Ying 				break;
173542012e04SHuang Ying 			}
173642012e04SHuang Ying 		}
173742012e04SHuang Ying 	}
173842012e04SHuang Ying 	nr_failed += retry;
173942012e04SHuang Ying 	stats->nr_thp_failed += thp_retry;
174042012e04SHuang Ying 	stats->nr_failed_pages += nr_retry_pages;
17415dfab109SHuang Ying move:
17427e12beb8SHuang Ying 	/* Flush TLBs for all unmapped folios */
17437e12beb8SHuang Ying 	try_to_unmap_flush();
17447e12beb8SHuang Ying 
17455dfab109SHuang Ying 	retry = 1;
1746124abcedSHuang Ying 	for (pass = 0; pass < nr_pass && retry; pass++) {
17475dfab109SHuang Ying 		retry = 0;
17485dfab109SHuang Ying 		thp_retry = 0;
17495dfab109SHuang Ying 		nr_retry_pages = 0;
17505dfab109SHuang Ying 
17515dfab109SHuang Ying 		dst = list_first_entry(&dst_folios, struct folio, lru);
17525dfab109SHuang Ying 		dst2 = list_next_entry(dst, lru);
17535dfab109SHuang Ying 		list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1754124abcedSHuang Ying 			is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
17555dfab109SHuang Ying 			nr_pages = folio_nr_pages(folio);
17565dfab109SHuang Ying 
17575dfab109SHuang Ying 			cond_resched();
17585dfab109SHuang Ying 
17594e096ae1SMatthew Wilcox (Oracle) 			rc = migrate_folio_move(put_new_folio, private,
17605dfab109SHuang Ying 						folio, dst, mode,
17615dfab109SHuang Ying 						reason, ret_folios);
17625dfab109SHuang Ying 			/*
17635dfab109SHuang Ying 			 * The rules are:
17645dfab109SHuang Ying 			 *	Success: folio will be freed
17655dfab109SHuang Ying 			 *	-EAGAIN: stay on the unmap_folios list
17665dfab109SHuang Ying 			 *	Other errno: put on ret_folios list
17675dfab109SHuang Ying 			 */
17685dfab109SHuang Ying 			switch(rc) {
17695dfab109SHuang Ying 			case -EAGAIN:
17705dfab109SHuang Ying 				retry++;
1771124abcedSHuang Ying 				thp_retry += is_thp;
17725dfab109SHuang Ying 				nr_retry_pages += nr_pages;
17735dfab109SHuang Ying 				break;
17745dfab109SHuang Ying 			case MIGRATEPAGE_SUCCESS:
17755dfab109SHuang Ying 				stats->nr_succeeded += nr_pages;
17765dfab109SHuang Ying 				stats->nr_thp_succeeded += is_thp;
17775dfab109SHuang Ying 				break;
17785dfab109SHuang Ying 			default:
17795dfab109SHuang Ying 				nr_failed++;
1780124abcedSHuang Ying 				stats->nr_thp_failed += is_thp;
17815dfab109SHuang Ying 				stats->nr_failed_pages += nr_pages;
17825dfab109SHuang Ying 				break;
17835dfab109SHuang Ying 			}
17845dfab109SHuang Ying 			dst = dst2;
17855dfab109SHuang Ying 			dst2 = list_next_entry(dst, lru);
17865dfab109SHuang Ying 		}
17875dfab109SHuang Ying 	}
17885dfab109SHuang Ying 	nr_failed += retry;
17895dfab109SHuang Ying 	stats->nr_thp_failed += thp_retry;
17905dfab109SHuang Ying 	stats->nr_failed_pages += nr_retry_pages;
17915dfab109SHuang Ying 
1792124abcedSHuang Ying 	rc = rc_saved ? : nr_failed;
17935dfab109SHuang Ying out:
17945dfab109SHuang Ying 	/* Cleanup remaining folios */
17955dfab109SHuang Ying 	dst = list_first_entry(&dst_folios, struct folio, lru);
17965dfab109SHuang Ying 	dst2 = list_next_entry(dst, lru);
17975dfab109SHuang Ying 	list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
17985dfab109SHuang Ying 		int page_was_mapped = 0;
17995dfab109SHuang Ying 		struct anon_vma *anon_vma = NULL;
18005dfab109SHuang Ying 
18015dfab109SHuang Ying 		__migrate_folio_extract(dst, &page_was_mapped, &anon_vma);
18025dfab109SHuang Ying 		migrate_folio_undo_src(folio, page_was_mapped, anon_vma,
1803ebe75e47SHuang Ying 				       true, ret_folios);
18045dfab109SHuang Ying 		list_del(&dst->lru);
18054e096ae1SMatthew Wilcox (Oracle) 		migrate_folio_undo_dst(dst, true, put_new_folio, private);
18065dfab109SHuang Ying 		dst = dst2;
18075dfab109SHuang Ying 		dst2 = list_next_entry(dst, lru);
18085dfab109SHuang Ying 	}
18095dfab109SHuang Ying 
181042012e04SHuang Ying 	return rc;
181142012e04SHuang Ying }
181242012e04SHuang Ying 
18134e096ae1SMatthew Wilcox (Oracle) static int migrate_pages_sync(struct list_head *from, new_folio_t get_new_folio,
18144e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
18154e096ae1SMatthew Wilcox (Oracle) 		enum migrate_mode mode, int reason,
18164e096ae1SMatthew Wilcox (Oracle) 		struct list_head *ret_folios, struct list_head *split_folios,
18174e096ae1SMatthew Wilcox (Oracle) 		struct migrate_pages_stats *stats)
18182ef7dbb2SHuang Ying {
18192ef7dbb2SHuang Ying 	int rc, nr_failed = 0;
18202ef7dbb2SHuang Ying 	LIST_HEAD(folios);
18212ef7dbb2SHuang Ying 	struct migrate_pages_stats astats;
18222ef7dbb2SHuang Ying 
18232ef7dbb2SHuang Ying 	memset(&astats, 0, sizeof(astats));
18242ef7dbb2SHuang Ying 	/* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
18254e096ae1SMatthew Wilcox (Oracle) 	rc = migrate_pages_batch(from, get_new_folio, put_new_folio, private, MIGRATE_ASYNC,
18262ef7dbb2SHuang Ying 				 reason, &folios, split_folios, &astats,
18272ef7dbb2SHuang Ying 				 NR_MAX_MIGRATE_ASYNC_RETRY);
18282ef7dbb2SHuang Ying 	stats->nr_succeeded += astats.nr_succeeded;
18292ef7dbb2SHuang Ying 	stats->nr_thp_succeeded += astats.nr_thp_succeeded;
18302ef7dbb2SHuang Ying 	stats->nr_thp_split += astats.nr_thp_split;
18312ef7dbb2SHuang Ying 	if (rc < 0) {
18322ef7dbb2SHuang Ying 		stats->nr_failed_pages += astats.nr_failed_pages;
18332ef7dbb2SHuang Ying 		stats->nr_thp_failed += astats.nr_thp_failed;
18342ef7dbb2SHuang Ying 		list_splice_tail(&folios, ret_folios);
18352ef7dbb2SHuang Ying 		return rc;
18362ef7dbb2SHuang Ying 	}
18372ef7dbb2SHuang Ying 	stats->nr_thp_failed += astats.nr_thp_split;
18382ef7dbb2SHuang Ying 	nr_failed += astats.nr_thp_split;
18392ef7dbb2SHuang Ying 	/*
18402ef7dbb2SHuang Ying 	 * Fall back to migrate all failed folios one by one synchronously. All
18412ef7dbb2SHuang Ying 	 * failed folios except split THPs will be retried, so their failure
18422ef7dbb2SHuang Ying 	 * isn't counted
18432ef7dbb2SHuang Ying 	 */
18442ef7dbb2SHuang Ying 	list_splice_tail_init(&folios, from);
18452ef7dbb2SHuang Ying 	while (!list_empty(from)) {
18462ef7dbb2SHuang Ying 		list_move(from->next, &folios);
18474e096ae1SMatthew Wilcox (Oracle) 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
18482ef7dbb2SHuang Ying 					 private, mode, reason, ret_folios,
18492ef7dbb2SHuang Ying 					 split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
18502ef7dbb2SHuang Ying 		list_splice_tail_init(&folios, ret_folios);
18512ef7dbb2SHuang Ying 		if (rc < 0)
18522ef7dbb2SHuang Ying 			return rc;
18532ef7dbb2SHuang Ying 		nr_failed += rc;
18542ef7dbb2SHuang Ying 	}
18552ef7dbb2SHuang Ying 
18562ef7dbb2SHuang Ying 	return nr_failed;
18572ef7dbb2SHuang Ying }
18582ef7dbb2SHuang Ying 
1859e24f0b8fSChristoph Lameter /*
1860eaec4e63SHuang Ying  * migrate_pages - migrate the folios specified in a list, to the free folios
1861c73e5c9cSSrivatsa S. Bhat  *		   supplied as the target for the page migration
1862e24f0b8fSChristoph Lameter  *
1863eaec4e63SHuang Ying  * @from:		The list of folios to be migrated.
18644e096ae1SMatthew Wilcox (Oracle)  * @get_new_folio:	The function used to allocate free folios to be used
1865eaec4e63SHuang Ying  *			as the target of the folio migration.
18664e096ae1SMatthew Wilcox (Oracle)  * @put_new_folio:	The function used to free target folios if migration
186768711a74SDavid Rientjes  *			fails, or NULL if no special handling is necessary.
18684e096ae1SMatthew Wilcox (Oracle)  * @private:		Private data to be passed on to get_new_folio()
1869c73e5c9cSSrivatsa S. Bhat  * @mode:		The migration mode that specifies the constraints for
1870eaec4e63SHuang Ying  *			folio migration, if any.
1871eaec4e63SHuang Ying  * @reason:		The reason for folio migration.
1872eaec4e63SHuang Ying  * @ret_succeeded:	Set to the number of folios migrated successfully if
18735ac95884SYang Shi  *			the caller passes a non-NULL pointer.
1874e24f0b8fSChristoph Lameter  *
1875e5bfff8bSHuang Ying  * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
1876e5bfff8bSHuang Ying  * are movable any more because the list has become empty or no retryable folios
1877e5bfff8bSHuang Ying  * exist any more. It is caller's responsibility to call putback_movable_pages()
1878e5bfff8bSHuang Ying  * only if ret != 0.
1879e24f0b8fSChristoph Lameter  *
1880eaec4e63SHuang Ying  * Returns the number of {normal folio, large folio, hugetlb} that were not
1881eaec4e63SHuang Ying  * migrated, or an error code. The number of large folio splits will be
1882eaec4e63SHuang Ying  * considered as the number of non-migrated large folio, no matter how many
1883eaec4e63SHuang Ying  * split folios of the large folio are migrated successfully.
1884e24f0b8fSChristoph Lameter  */
18854e096ae1SMatthew Wilcox (Oracle) int migrate_pages(struct list_head *from, new_folio_t get_new_folio,
18864e096ae1SMatthew Wilcox (Oracle) 		free_folio_t put_new_folio, unsigned long private,
18875ac95884SYang Shi 		enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1888e24f0b8fSChristoph Lameter {
188942012e04SHuang Ying 	int rc, rc_gather;
18902ef7dbb2SHuang Ying 	int nr_pages;
1891eaec4e63SHuang Ying 	struct folio *folio, *folio2;
189242012e04SHuang Ying 	LIST_HEAD(folios);
1893eaec4e63SHuang Ying 	LIST_HEAD(ret_folios);
1894a21d2133SHuang Ying 	LIST_HEAD(split_folios);
18955b855937SHuang Ying 	struct migrate_pages_stats stats;
18962d1db3b1SChristoph Lameter 
18977bc1aec5SLiam Mark 	trace_mm_migrate_pages_start(mode, reason);
18987bc1aec5SLiam Mark 
18995b855937SHuang Ying 	memset(&stats, 0, sizeof(stats));
1900e24f0b8fSChristoph Lameter 
19014e096ae1SMatthew Wilcox (Oracle) 	rc_gather = migrate_hugetlbs(from, get_new_folio, put_new_folio, private,
190242012e04SHuang Ying 				     mode, reason, &stats, &ret_folios);
190342012e04SHuang Ying 	if (rc_gather < 0)
190495a402c3SChristoph Lameter 		goto out;
1905fb3592c4SHuang Ying 
190642012e04SHuang Ying again:
190742012e04SHuang Ying 	nr_pages = 0;
1908b20a3503SChristoph Lameter 	list_for_each_entry_safe(folio, folio2, from, lru) {
1909e5bfff8bSHuang Ying 		/* Retried hugetlb folios will be kept in list  */
1910e5bfff8bSHuang Ying 		if (folio_test_hugetlb(folio)) {
1911e5bfff8bSHuang Ying 			list_move_tail(&folio->lru, &ret_folios);
1912e5bfff8bSHuang Ying 			continue;
1913eaec4e63SHuang Ying 		}
1914f430893bSMiaohe Lin 
191542012e04SHuang Ying 		nr_pages += folio_nr_pages(folio);
19162ef7dbb2SHuang Ying 		if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
1917e24f0b8fSChristoph Lameter 			break;
1918b20a3503SChristoph Lameter 	}
19192ef7dbb2SHuang Ying 	if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
1920fb3592c4SHuang Ying 		list_cut_before(&folios, from, &folio2->lru);
192142012e04SHuang Ying 	else
192242012e04SHuang Ying 		list_splice_init(from, &folios);
19232ef7dbb2SHuang Ying 	if (mode == MIGRATE_ASYNC)
19244e096ae1SMatthew Wilcox (Oracle) 		rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
19254e096ae1SMatthew Wilcox (Oracle) 				private, mode, reason, &ret_folios,
19264e096ae1SMatthew Wilcox (Oracle) 				&split_folios, &stats,
1927a21d2133SHuang Ying 				NR_MAX_MIGRATE_PAGES_RETRY);
19282ef7dbb2SHuang Ying 	else
19294e096ae1SMatthew Wilcox (Oracle) 		rc = migrate_pages_sync(&folios, get_new_folio, put_new_folio,
19304e096ae1SMatthew Wilcox (Oracle) 				private, mode, reason, &ret_folios,
19314e096ae1SMatthew Wilcox (Oracle) 				&split_folios, &stats);
193242012e04SHuang Ying 	list_splice_tail_init(&folios, &ret_folios);
193342012e04SHuang Ying 	if (rc < 0) {
193442012e04SHuang Ying 		rc_gather = rc;
1935a21d2133SHuang Ying 		list_splice_tail(&split_folios, &ret_folios);
1936b20a3503SChristoph Lameter 		goto out;
1937b20a3503SChristoph Lameter 	}
1938a21d2133SHuang Ying 	if (!list_empty(&split_folios)) {
1939a21d2133SHuang Ying 		/*
1940a21d2133SHuang Ying 		 * Failure isn't counted since all split folios of a large folio
1941a21d2133SHuang Ying 		 * is counted as 1 failure already.  And, we only try to migrate
1942a21d2133SHuang Ying 		 * with minimal effort, force MIGRATE_ASYNC mode and retry once.
1943a21d2133SHuang Ying 		 */
19444e096ae1SMatthew Wilcox (Oracle) 		migrate_pages_batch(&split_folios, get_new_folio,
19454e096ae1SMatthew Wilcox (Oracle) 				put_new_folio, private, MIGRATE_ASYNC, reason,
19464e096ae1SMatthew Wilcox (Oracle) 				&ret_folios, NULL, &stats, 1);
1947a21d2133SHuang Ying 		list_splice_tail_init(&split_folios, &ret_folios);
1948a21d2133SHuang Ying 	}
194942012e04SHuang Ying 	rc_gather += rc;
195042012e04SHuang Ying 	if (!list_empty(from))
195142012e04SHuang Ying 		goto again;
195295a402c3SChristoph Lameter out:
1953dd4ae78aSYang Shi 	/*
1954eaec4e63SHuang Ying 	 * Put the permanent failure folio back to migration list, they
1955dd4ae78aSYang Shi 	 * will be put back to the right list by the caller.
1956dd4ae78aSYang Shi 	 */
1957eaec4e63SHuang Ying 	list_splice(&ret_folios, from);
1958dd4ae78aSYang Shi 
195903e5f82eSBaolin Wang 	/*
1960eaec4e63SHuang Ying 	 * Return 0 in case all split folios of fail-to-migrate large folios
1961eaec4e63SHuang Ying 	 * are migrated successfully.
196203e5f82eSBaolin Wang 	 */
196303e5f82eSBaolin Wang 	if (list_empty(from))
196442012e04SHuang Ying 		rc_gather = 0;
196503e5f82eSBaolin Wang 
19665b855937SHuang Ying 	count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
19675b855937SHuang Ying 	count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
19685b855937SHuang Ying 	count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
19695b855937SHuang Ying 	count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
19705b855937SHuang Ying 	count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
19715b855937SHuang Ying 	trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
19725b855937SHuang Ying 			       stats.nr_thp_succeeded, stats.nr_thp_failed,
19735b855937SHuang Ying 			       stats.nr_thp_split, mode, reason);
19747b2a2d4aSMel Gorman 
19755ac95884SYang Shi 	if (ret_succeeded)
19765b855937SHuang Ying 		*ret_succeeded = stats.nr_succeeded;
19775ac95884SYang Shi 
197842012e04SHuang Ying 	return rc_gather;
1979b20a3503SChristoph Lameter }
1980b20a3503SChristoph Lameter 
19814e096ae1SMatthew Wilcox (Oracle) struct folio *alloc_migration_target(struct folio *src, unsigned long private)
1982b4b38223SJoonsoo Kim {
198319fc7bedSJoonsoo Kim 	struct migration_target_control *mtc;
198419fc7bedSJoonsoo Kim 	gfp_t gfp_mask;
1985b4b38223SJoonsoo Kim 	unsigned int order = 0;
198619fc7bedSJoonsoo Kim 	int nid;
198719fc7bedSJoonsoo Kim 	int zidx;
198819fc7bedSJoonsoo Kim 
198919fc7bedSJoonsoo Kim 	mtc = (struct migration_target_control *)private;
199019fc7bedSJoonsoo Kim 	gfp_mask = mtc->gfp_mask;
199119fc7bedSJoonsoo Kim 	nid = mtc->nid;
199219fc7bedSJoonsoo Kim 	if (nid == NUMA_NO_NODE)
19934e096ae1SMatthew Wilcox (Oracle) 		nid = folio_nid(src);
1994b4b38223SJoonsoo Kim 
19954e096ae1SMatthew Wilcox (Oracle) 	if (folio_test_hugetlb(src)) {
19964e096ae1SMatthew Wilcox (Oracle) 		struct hstate *h = folio_hstate(src);
1997d92bbc27SJoonsoo Kim 
199819fc7bedSJoonsoo Kim 		gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
19994e096ae1SMatthew Wilcox (Oracle) 		return alloc_hugetlb_folio_nodemask(h, nid,
2000e37d3e83SSidhartha Kumar 						mtc->nmask, gfp_mask);
2001d92bbc27SJoonsoo Kim 	}
2002b4b38223SJoonsoo Kim 
20034e096ae1SMatthew Wilcox (Oracle) 	if (folio_test_large(src)) {
20049933a0c8SJoonsoo Kim 		/*
20059933a0c8SJoonsoo Kim 		 * clear __GFP_RECLAIM to make the migration callback
20069933a0c8SJoonsoo Kim 		 * consistent with regular THP allocations.
20079933a0c8SJoonsoo Kim 		 */
20089933a0c8SJoonsoo Kim 		gfp_mask &= ~__GFP_RECLAIM;
2009b4b38223SJoonsoo Kim 		gfp_mask |= GFP_TRANSHUGE;
20104e096ae1SMatthew Wilcox (Oracle) 		order = folio_order(src);
2011b4b38223SJoonsoo Kim 	}
20124e096ae1SMatthew Wilcox (Oracle) 	zidx = zone_idx(folio_zone(src));
201319fc7bedSJoonsoo Kim 	if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
2014b4b38223SJoonsoo Kim 		gfp_mask |= __GFP_HIGHMEM;
2015b4b38223SJoonsoo Kim 
20164e096ae1SMatthew Wilcox (Oracle) 	return __folio_alloc(gfp_mask, order, nid, mtc->nmask);
2017b4b38223SJoonsoo Kim }
2018b4b38223SJoonsoo Kim 
2019742755a1SChristoph Lameter #ifdef CONFIG_NUMA
2020742755a1SChristoph Lameter 
2021a49bd4d7SMichal Hocko static int store_status(int __user *status, int start, int value, int nr)
2022742755a1SChristoph Lameter {
2023a49bd4d7SMichal Hocko 	while (nr-- > 0) {
2024a49bd4d7SMichal Hocko 		if (put_user(value, status + start))
2025a49bd4d7SMichal Hocko 			return -EFAULT;
2026a49bd4d7SMichal Hocko 		start++;
2027a49bd4d7SMichal Hocko 	}
2028742755a1SChristoph Lameter 
2029a49bd4d7SMichal Hocko 	return 0;
2030a49bd4d7SMichal Hocko }
2031742755a1SChristoph Lameter 
2032a49bd4d7SMichal Hocko static int do_move_pages_to_node(struct mm_struct *mm,
2033a49bd4d7SMichal Hocko 		struct list_head *pagelist, int node)
2034a49bd4d7SMichal Hocko {
2035a49bd4d7SMichal Hocko 	int err;
2036a0976311SJoonsoo Kim 	struct migration_target_control mtc = {
2037a0976311SJoonsoo Kim 		.nid = node,
2038a0976311SJoonsoo Kim 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
2039a0976311SJoonsoo Kim 	};
2040742755a1SChristoph Lameter 
2041a0976311SJoonsoo Kim 	err = migrate_pages(pagelist, alloc_migration_target, NULL,
20425ac95884SYang Shi 		(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
2043a49bd4d7SMichal Hocko 	if (err)
2044a49bd4d7SMichal Hocko 		putback_movable_pages(pagelist);
2045a49bd4d7SMichal Hocko 	return err;
2046742755a1SChristoph Lameter }
2047742755a1SChristoph Lameter 
2048742755a1SChristoph Lameter /*
2049a49bd4d7SMichal Hocko  * Resolves the given address to a struct page, isolates it from the LRU and
2050a49bd4d7SMichal Hocko  * puts it to the given pagelist.
2051e0153fc2SYang Shi  * Returns:
2052e0153fc2SYang Shi  *     errno - if the page cannot be found/isolated
2053e0153fc2SYang Shi  *     0 - when it doesn't have to be migrated because it is already on the
2054e0153fc2SYang Shi  *         target node
2055e0153fc2SYang Shi  *     1 - when it has been queued
2056742755a1SChristoph Lameter  */
2057428e106aSKirill A. Shutemov static int add_page_for_migration(struct mm_struct *mm, const void __user *p,
2058a49bd4d7SMichal Hocko 		int node, struct list_head *pagelist, bool migrate_all)
2059742755a1SChristoph Lameter {
2060742755a1SChristoph Lameter 	struct vm_area_struct *vma;
2061428e106aSKirill A. Shutemov 	unsigned long addr;
2062742755a1SChristoph Lameter 	struct page *page;
2063a49bd4d7SMichal Hocko 	int err;
20649747b9e9SBaolin Wang 	bool isolated;
2065742755a1SChristoph Lameter 
2066d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
2067428e106aSKirill A. Shutemov 	addr = (unsigned long)untagged_addr_remote(mm, p);
2068428e106aSKirill A. Shutemov 
2069742755a1SChristoph Lameter 	err = -EFAULT;
2070cb1c37b1SMiaohe Lin 	vma = vma_lookup(mm, addr);
2071cb1c37b1SMiaohe Lin 	if (!vma || !vma_migratable(vma))
2072a49bd4d7SMichal Hocko 		goto out;
2073742755a1SChristoph Lameter 
2074d899844eSKirill A. Shutemov 	/* FOLL_DUMP to ignore special (like zero) pages */
207587d2762eSMiaohe Lin 	page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
207689f5b7daSLinus Torvalds 
207789f5b7daSLinus Torvalds 	err = PTR_ERR(page);
207889f5b7daSLinus Torvalds 	if (IS_ERR(page))
2079a49bd4d7SMichal Hocko 		goto out;
208089f5b7daSLinus Torvalds 
2081742755a1SChristoph Lameter 	err = -ENOENT;
2082f7091ed6SHaiyue Wang 	if (!page)
2083a49bd4d7SMichal Hocko 		goto out;
2084742755a1SChristoph Lameter 
2085f7091ed6SHaiyue Wang 	if (is_zone_device_page(page))
2086f7091ed6SHaiyue Wang 		goto out_putpage;
2087f7091ed6SHaiyue Wang 
2088a49bd4d7SMichal Hocko 	err = 0;
2089a49bd4d7SMichal Hocko 	if (page_to_nid(page) == node)
2090a49bd4d7SMichal Hocko 		goto out_putpage;
2091742755a1SChristoph Lameter 
2092742755a1SChristoph Lameter 	err = -EACCES;
2093a49bd4d7SMichal Hocko 	if (page_mapcount(page) > 1 && !migrate_all)
2094a49bd4d7SMichal Hocko 		goto out_putpage;
2095742755a1SChristoph Lameter 
2096e632a938SNaoya Horiguchi 	if (PageHuge(page)) {
2097e8db67ebSNaoya Horiguchi 		if (PageHead(page)) {
20989747b9e9SBaolin Wang 			isolated = isolate_hugetlb(page_folio(page), pagelist);
20999747b9e9SBaolin Wang 			err = isolated ? 1 : -EBUSY;
2100e8db67ebSNaoya Horiguchi 		}
2101a49bd4d7SMichal Hocko 	} else {
2102a49bd4d7SMichal Hocko 		struct page *head;
2103e632a938SNaoya Horiguchi 
2104e8db67ebSNaoya Horiguchi 		head = compound_head(page);
2105f7f9c00dSBaolin Wang 		isolated = isolate_lru_page(head);
2106f7f9c00dSBaolin Wang 		if (!isolated) {
2107f7f9c00dSBaolin Wang 			err = -EBUSY;
2108a49bd4d7SMichal Hocko 			goto out_putpage;
2109f7f9c00dSBaolin Wang 		}
2110a49bd4d7SMichal Hocko 
2111e0153fc2SYang Shi 		err = 1;
2112a49bd4d7SMichal Hocko 		list_add_tail(&head->lru, pagelist);
2113e8db67ebSNaoya Horiguchi 		mod_node_page_state(page_pgdat(head),
21149de4f22aSHuang Ying 			NR_ISOLATED_ANON + page_is_file_lru(head),
21156c357848SMatthew Wilcox (Oracle) 			thp_nr_pages(head));
21166d9c285aSKOSAKI Motohiro 	}
2117a49bd4d7SMichal Hocko out_putpage:
2118742755a1SChristoph Lameter 	/*
2119742755a1SChristoph Lameter 	 * Either remove the duplicate refcount from
2120742755a1SChristoph Lameter 	 * isolate_lru_page() or drop the page ref if it was
2121742755a1SChristoph Lameter 	 * not isolated.
2122742755a1SChristoph Lameter 	 */
2123742755a1SChristoph Lameter 	put_page(page);
2124a49bd4d7SMichal Hocko out:
2125d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
2126742755a1SChristoph Lameter 	return err;
2127742755a1SChristoph Lameter }
2128742755a1SChristoph Lameter 
21297ca8783aSWei Yang static int move_pages_and_store_status(struct mm_struct *mm, int node,
21307ca8783aSWei Yang 		struct list_head *pagelist, int __user *status,
21317ca8783aSWei Yang 		int start, int i, unsigned long nr_pages)
21327ca8783aSWei Yang {
21337ca8783aSWei Yang 	int err;
21347ca8783aSWei Yang 
21355d7ae891SWei Yang 	if (list_empty(pagelist))
21365d7ae891SWei Yang 		return 0;
21375d7ae891SWei Yang 
21387ca8783aSWei Yang 	err = do_move_pages_to_node(mm, pagelist, node);
21397ca8783aSWei Yang 	if (err) {
21407ca8783aSWei Yang 		/*
21417ca8783aSWei Yang 		 * Positive err means the number of failed
21427ca8783aSWei Yang 		 * pages to migrate.  Since we are going to
21437ca8783aSWei Yang 		 * abort and return the number of non-migrated
2144ab9dd4f8SLong Li 		 * pages, so need to include the rest of the
21457ca8783aSWei Yang 		 * nr_pages that have not been attempted as
21467ca8783aSWei Yang 		 * well.
21477ca8783aSWei Yang 		 */
21487ca8783aSWei Yang 		if (err > 0)
2149a7504ed1SHuang Ying 			err += nr_pages - i;
21507ca8783aSWei Yang 		return err;
21517ca8783aSWei Yang 	}
21527ca8783aSWei Yang 	return store_status(status, start, node, i - start);
21537ca8783aSWei Yang }
21547ca8783aSWei Yang 
2155742755a1SChristoph Lameter /*
21565e9a0f02SBrice Goglin  * Migrate an array of page address onto an array of nodes and fill
21575e9a0f02SBrice Goglin  * the corresponding array of status.
21585e9a0f02SBrice Goglin  */
21593268c63eSChristoph Lameter static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
21605e9a0f02SBrice Goglin 			 unsigned long nr_pages,
21615e9a0f02SBrice Goglin 			 const void __user * __user *pages,
21625e9a0f02SBrice Goglin 			 const int __user *nodes,
21635e9a0f02SBrice Goglin 			 int __user *status, int flags)
21645e9a0f02SBrice Goglin {
2165a49bd4d7SMichal Hocko 	int current_node = NUMA_NO_NODE;
2166a49bd4d7SMichal Hocko 	LIST_HEAD(pagelist);
2167a49bd4d7SMichal Hocko 	int start, i;
2168a49bd4d7SMichal Hocko 	int err = 0, err1;
216935282a2dSBrice Goglin 
2170361a2a22SMinchan Kim 	lru_cache_disable();
217135282a2dSBrice Goglin 
2172a49bd4d7SMichal Hocko 	for (i = start = 0; i < nr_pages; i++) {
21735e9a0f02SBrice Goglin 		const void __user *p;
21745e9a0f02SBrice Goglin 		int node;
21755e9a0f02SBrice Goglin 
21763140a227SBrice Goglin 		err = -EFAULT;
2177a49bd4d7SMichal Hocko 		if (get_user(p, pages + i))
2178a49bd4d7SMichal Hocko 			goto out_flush;
2179a49bd4d7SMichal Hocko 		if (get_user(node, nodes + i))
2180a49bd4d7SMichal Hocko 			goto out_flush;
21815e9a0f02SBrice Goglin 
21825e9a0f02SBrice Goglin 		err = -ENODEV;
21836f5a55f1SLinus Torvalds 		if (node < 0 || node >= MAX_NUMNODES)
2184a49bd4d7SMichal Hocko 			goto out_flush;
2185389162c2SLai Jiangshan 		if (!node_state(node, N_MEMORY))
2186a49bd4d7SMichal Hocko 			goto out_flush;
21875e9a0f02SBrice Goglin 
21885e9a0f02SBrice Goglin 		err = -EACCES;
21895e9a0f02SBrice Goglin 		if (!node_isset(node, task_nodes))
2190a49bd4d7SMichal Hocko 			goto out_flush;
21915e9a0f02SBrice Goglin 
2192a49bd4d7SMichal Hocko 		if (current_node == NUMA_NO_NODE) {
2193a49bd4d7SMichal Hocko 			current_node = node;
2194a49bd4d7SMichal Hocko 			start = i;
2195a49bd4d7SMichal Hocko 		} else if (node != current_node) {
21967ca8783aSWei Yang 			err = move_pages_and_store_status(mm, current_node,
21977ca8783aSWei Yang 					&pagelist, status, start, i, nr_pages);
2198a49bd4d7SMichal Hocko 			if (err)
2199a49bd4d7SMichal Hocko 				goto out;
2200a49bd4d7SMichal Hocko 			start = i;
2201a49bd4d7SMichal Hocko 			current_node = node;
22025e9a0f02SBrice Goglin 		}
22035e9a0f02SBrice Goglin 
2204a49bd4d7SMichal Hocko 		/*
2205a49bd4d7SMichal Hocko 		 * Errors in the page lookup or isolation are not fatal and we simply
2206a49bd4d7SMichal Hocko 		 * report them via status
2207a49bd4d7SMichal Hocko 		 */
2208428e106aSKirill A. Shutemov 		err = add_page_for_migration(mm, p, current_node, &pagelist,
2209428e106aSKirill A. Shutemov 					     flags & MPOL_MF_MOVE_ALL);
2210e0153fc2SYang Shi 
2211d08221a0SWei Yang 		if (err > 0) {
2212e0153fc2SYang Shi 			/* The page is successfully queued for migration */
2213e0153fc2SYang Shi 			continue;
2214e0153fc2SYang Shi 		}
22153140a227SBrice Goglin 
2216d08221a0SWei Yang 		/*
221765462462SJohn Hubbard 		 * The move_pages() man page does not have an -EEXIST choice, so
221865462462SJohn Hubbard 		 * use -EFAULT instead.
221965462462SJohn Hubbard 		 */
222065462462SJohn Hubbard 		if (err == -EEXIST)
222165462462SJohn Hubbard 			err = -EFAULT;
222265462462SJohn Hubbard 
222365462462SJohn Hubbard 		/*
2224d08221a0SWei Yang 		 * If the page is already on the target node (!err), store the
2225d08221a0SWei Yang 		 * node, otherwise, store the err.
2226d08221a0SWei Yang 		 */
2227d08221a0SWei Yang 		err = store_status(status, i, err ? : current_node, 1);
2228a49bd4d7SMichal Hocko 		if (err)
2229a49bd4d7SMichal Hocko 			goto out_flush;
22303140a227SBrice Goglin 
22317ca8783aSWei Yang 		err = move_pages_and_store_status(mm, current_node, &pagelist,
22327ca8783aSWei Yang 				status, start, i, nr_pages);
2233a7504ed1SHuang Ying 		if (err) {
2234a7504ed1SHuang Ying 			/* We have accounted for page i */
2235a7504ed1SHuang Ying 			if (err > 0)
2236a7504ed1SHuang Ying 				err--;
2237a49bd4d7SMichal Hocko 			goto out;
2238a7504ed1SHuang Ying 		}
2239a49bd4d7SMichal Hocko 		current_node = NUMA_NO_NODE;
22403140a227SBrice Goglin 	}
2241a49bd4d7SMichal Hocko out_flush:
2242a49bd4d7SMichal Hocko 	/* Make sure we do not overwrite the existing error */
22437ca8783aSWei Yang 	err1 = move_pages_and_store_status(mm, current_node, &pagelist,
22447ca8783aSWei Yang 				status, start, i, nr_pages);
2245dfe9aa23SWei Yang 	if (err >= 0)
2246a49bd4d7SMichal Hocko 		err = err1;
22475e9a0f02SBrice Goglin out:
2248361a2a22SMinchan Kim 	lru_cache_enable();
22495e9a0f02SBrice Goglin 	return err;
22505e9a0f02SBrice Goglin }
22515e9a0f02SBrice Goglin 
22525e9a0f02SBrice Goglin /*
22532f007e74SBrice Goglin  * Determine the nodes of an array of pages and store it in an array of status.
2254742755a1SChristoph Lameter  */
225580bba129SBrice Goglin static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
225680bba129SBrice Goglin 				const void __user **pages, int *status)
2257742755a1SChristoph Lameter {
22582f007e74SBrice Goglin 	unsigned long i;
2259742755a1SChristoph Lameter 
2260d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
22612f007e74SBrice Goglin 
22622f007e74SBrice Goglin 	for (i = 0; i < nr_pages; i++) {
226380bba129SBrice Goglin 		unsigned long addr = (unsigned long)(*pages);
22642f007e74SBrice Goglin 		struct vm_area_struct *vma;
22652f007e74SBrice Goglin 		struct page *page;
2266c095adbcSKOSAKI Motohiro 		int err = -EFAULT;
22672f007e74SBrice Goglin 
2268059b8b48SLiam Howlett 		vma = vma_lookup(mm, addr);
2269059b8b48SLiam Howlett 		if (!vma)
2270742755a1SChristoph Lameter 			goto set_status;
2271742755a1SChristoph Lameter 
2272d899844eSKirill A. Shutemov 		/* FOLL_DUMP to ignore special (like zero) pages */
227316fd6b31SBaolin Wang 		page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
227489f5b7daSLinus Torvalds 
227589f5b7daSLinus Torvalds 		err = PTR_ERR(page);
227689f5b7daSLinus Torvalds 		if (IS_ERR(page))
227789f5b7daSLinus Torvalds 			goto set_status;
227889f5b7daSLinus Torvalds 
2279f7091ed6SHaiyue Wang 		err = -ENOENT;
2280f7091ed6SHaiyue Wang 		if (!page)
2281f7091ed6SHaiyue Wang 			goto set_status;
2282f7091ed6SHaiyue Wang 
2283f7091ed6SHaiyue Wang 		if (!is_zone_device_page(page))
22844cd61484SMiaohe Lin 			err = page_to_nid(page);
2285f7091ed6SHaiyue Wang 
22864cd61484SMiaohe Lin 		put_page(page);
2287742755a1SChristoph Lameter set_status:
228880bba129SBrice Goglin 		*status = err;
228980bba129SBrice Goglin 
229080bba129SBrice Goglin 		pages++;
229180bba129SBrice Goglin 		status++;
229280bba129SBrice Goglin 	}
229380bba129SBrice Goglin 
2294d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
229580bba129SBrice Goglin }
229680bba129SBrice Goglin 
22975b1b561bSArnd Bergmann static int get_compat_pages_array(const void __user *chunk_pages[],
22985b1b561bSArnd Bergmann 				  const void __user * __user *pages,
22995b1b561bSArnd Bergmann 				  unsigned long chunk_nr)
23005b1b561bSArnd Bergmann {
23015b1b561bSArnd Bergmann 	compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
23025b1b561bSArnd Bergmann 	compat_uptr_t p;
23035b1b561bSArnd Bergmann 	int i;
23045b1b561bSArnd Bergmann 
23055b1b561bSArnd Bergmann 	for (i = 0; i < chunk_nr; i++) {
23065b1b561bSArnd Bergmann 		if (get_user(p, pages32 + i))
23075b1b561bSArnd Bergmann 			return -EFAULT;
23085b1b561bSArnd Bergmann 		chunk_pages[i] = compat_ptr(p);
23095b1b561bSArnd Bergmann 	}
23105b1b561bSArnd Bergmann 
23115b1b561bSArnd Bergmann 	return 0;
23125b1b561bSArnd Bergmann }
23135b1b561bSArnd Bergmann 
231480bba129SBrice Goglin /*
231580bba129SBrice Goglin  * Determine the nodes of a user array of pages and store it in
231680bba129SBrice Goglin  * a user array of status.
231780bba129SBrice Goglin  */
231880bba129SBrice Goglin static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
231980bba129SBrice Goglin 			 const void __user * __user *pages,
232080bba129SBrice Goglin 			 int __user *status)
232180bba129SBrice Goglin {
23223eefb826SMiaohe Lin #define DO_PAGES_STAT_CHUNK_NR 16UL
232380bba129SBrice Goglin 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
232480bba129SBrice Goglin 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
232580bba129SBrice Goglin 
232687b8d1adSH. Peter Anvin 	while (nr_pages) {
23273eefb826SMiaohe Lin 		unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
232887b8d1adSH. Peter Anvin 
23295b1b561bSArnd Bergmann 		if (in_compat_syscall()) {
23305b1b561bSArnd Bergmann 			if (get_compat_pages_array(chunk_pages, pages,
23315b1b561bSArnd Bergmann 						   chunk_nr))
233287b8d1adSH. Peter Anvin 				break;
23335b1b561bSArnd Bergmann 		} else {
23345b1b561bSArnd Bergmann 			if (copy_from_user(chunk_pages, pages,
23355b1b561bSArnd Bergmann 				      chunk_nr * sizeof(*chunk_pages)))
23365b1b561bSArnd Bergmann 				break;
23375b1b561bSArnd Bergmann 		}
233880bba129SBrice Goglin 
233980bba129SBrice Goglin 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
234080bba129SBrice Goglin 
234187b8d1adSH. Peter Anvin 		if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
234287b8d1adSH. Peter Anvin 			break;
2343742755a1SChristoph Lameter 
234487b8d1adSH. Peter Anvin 		pages += chunk_nr;
234587b8d1adSH. Peter Anvin 		status += chunk_nr;
234687b8d1adSH. Peter Anvin 		nr_pages -= chunk_nr;
234787b8d1adSH. Peter Anvin 	}
234887b8d1adSH. Peter Anvin 	return nr_pages ? -EFAULT : 0;
2349742755a1SChristoph Lameter }
2350742755a1SChristoph Lameter 
23514dc200ceSMiaohe Lin static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
23524dc200ceSMiaohe Lin {
23534dc200ceSMiaohe Lin 	struct task_struct *task;
23544dc200ceSMiaohe Lin 	struct mm_struct *mm;
23554dc200ceSMiaohe Lin 
23564dc200ceSMiaohe Lin 	/*
23574dc200ceSMiaohe Lin 	 * There is no need to check if current process has the right to modify
23584dc200ceSMiaohe Lin 	 * the specified process when they are same.
23594dc200ceSMiaohe Lin 	 */
23604dc200ceSMiaohe Lin 	if (!pid) {
23614dc200ceSMiaohe Lin 		mmget(current->mm);
23624dc200ceSMiaohe Lin 		*mem_nodes = cpuset_mems_allowed(current);
23634dc200ceSMiaohe Lin 		return current->mm;
23644dc200ceSMiaohe Lin 	}
23654dc200ceSMiaohe Lin 
23664dc200ceSMiaohe Lin 	/* Find the mm_struct */
23674dc200ceSMiaohe Lin 	rcu_read_lock();
23684dc200ceSMiaohe Lin 	task = find_task_by_vpid(pid);
23694dc200ceSMiaohe Lin 	if (!task) {
23704dc200ceSMiaohe Lin 		rcu_read_unlock();
23714dc200ceSMiaohe Lin 		return ERR_PTR(-ESRCH);
23724dc200ceSMiaohe Lin 	}
23734dc200ceSMiaohe Lin 	get_task_struct(task);
23744dc200ceSMiaohe Lin 
23754dc200ceSMiaohe Lin 	/*
23764dc200ceSMiaohe Lin 	 * Check if this process has the right to modify the specified
23774dc200ceSMiaohe Lin 	 * process. Use the regular "ptrace_may_access()" checks.
23784dc200ceSMiaohe Lin 	 */
23794dc200ceSMiaohe Lin 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
23804dc200ceSMiaohe Lin 		rcu_read_unlock();
23814dc200ceSMiaohe Lin 		mm = ERR_PTR(-EPERM);
23824dc200ceSMiaohe Lin 		goto out;
23834dc200ceSMiaohe Lin 	}
23844dc200ceSMiaohe Lin 	rcu_read_unlock();
23854dc200ceSMiaohe Lin 
23864dc200ceSMiaohe Lin 	mm = ERR_PTR(security_task_movememory(task));
23874dc200ceSMiaohe Lin 	if (IS_ERR(mm))
23884dc200ceSMiaohe Lin 		goto out;
23894dc200ceSMiaohe Lin 	*mem_nodes = cpuset_mems_allowed(task);
23904dc200ceSMiaohe Lin 	mm = get_task_mm(task);
23914dc200ceSMiaohe Lin out:
23924dc200ceSMiaohe Lin 	put_task_struct(task);
23934dc200ceSMiaohe Lin 	if (!mm)
23944dc200ceSMiaohe Lin 		mm = ERR_PTR(-EINVAL);
23954dc200ceSMiaohe Lin 	return mm;
23964dc200ceSMiaohe Lin }
23974dc200ceSMiaohe Lin 
2398742755a1SChristoph Lameter /*
2399742755a1SChristoph Lameter  * Move a list of pages in the address space of the currently executing
2400742755a1SChristoph Lameter  * process.
2401742755a1SChristoph Lameter  */
24027addf443SDominik Brodowski static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
24037addf443SDominik Brodowski 			     const void __user * __user *pages,
24047addf443SDominik Brodowski 			     const int __user *nodes,
24057addf443SDominik Brodowski 			     int __user *status, int flags)
2406742755a1SChristoph Lameter {
2407742755a1SChristoph Lameter 	struct mm_struct *mm;
24085e9a0f02SBrice Goglin 	int err;
24093268c63eSChristoph Lameter 	nodemask_t task_nodes;
2410742755a1SChristoph Lameter 
2411742755a1SChristoph Lameter 	/* Check flags */
2412742755a1SChristoph Lameter 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2413742755a1SChristoph Lameter 		return -EINVAL;
2414742755a1SChristoph Lameter 
2415742755a1SChristoph Lameter 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2416742755a1SChristoph Lameter 		return -EPERM;
2417742755a1SChristoph Lameter 
24184dc200ceSMiaohe Lin 	mm = find_mm_struct(pid, &task_nodes);
24194dc200ceSMiaohe Lin 	if (IS_ERR(mm))
24204dc200ceSMiaohe Lin 		return PTR_ERR(mm);
24216e8b09eaSSasha Levin 
24223268c63eSChristoph Lameter 	if (nodes)
24233268c63eSChristoph Lameter 		err = do_pages_move(mm, task_nodes, nr_pages, pages,
24243268c63eSChristoph Lameter 				    nodes, status, flags);
24253268c63eSChristoph Lameter 	else
24265e9a0f02SBrice Goglin 		err = do_pages_stat(mm, nr_pages, pages, status);
24273268c63eSChristoph Lameter 
24283268c63eSChristoph Lameter 	mmput(mm);
24293268c63eSChristoph Lameter 	return err;
2430742755a1SChristoph Lameter }
2431742755a1SChristoph Lameter 
24327addf443SDominik Brodowski SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
24337addf443SDominik Brodowski 		const void __user * __user *, pages,
24347addf443SDominik Brodowski 		const int __user *, nodes,
24357addf443SDominik Brodowski 		int __user *, status, int, flags)
24367addf443SDominik Brodowski {
24377addf443SDominik Brodowski 	return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
24387addf443SDominik Brodowski }
24397addf443SDominik Brodowski 
24407039e1dbSPeter Zijlstra #ifdef CONFIG_NUMA_BALANCING
24417039e1dbSPeter Zijlstra /*
24427039e1dbSPeter Zijlstra  * Returns true if this is a safe migration target node for misplaced NUMA
2443bc53008eSWei Yang  * pages. Currently it only checks the watermarks which is crude.
24447039e1dbSPeter Zijlstra  */
24457039e1dbSPeter Zijlstra static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
24463abef4e6SMel Gorman 				   unsigned long nr_migrate_pages)
24477039e1dbSPeter Zijlstra {
24487039e1dbSPeter Zijlstra 	int z;
2449599d0c95SMel Gorman 
24507039e1dbSPeter Zijlstra 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
24517039e1dbSPeter Zijlstra 		struct zone *zone = pgdat->node_zones + z;
24527039e1dbSPeter Zijlstra 
2453bc53008eSWei Yang 		if (!managed_zone(zone))
24547039e1dbSPeter Zijlstra 			continue;
24557039e1dbSPeter Zijlstra 
24567039e1dbSPeter Zijlstra 		/* Avoid waking kswapd by allocating pages_to_migrate pages. */
24577039e1dbSPeter Zijlstra 		if (!zone_watermark_ok(zone, 0,
24587039e1dbSPeter Zijlstra 				       high_wmark_pages(zone) +
24597039e1dbSPeter Zijlstra 				       nr_migrate_pages,
2460bfe9d006SHuang Ying 				       ZONE_MOVABLE, 0))
24617039e1dbSPeter Zijlstra 			continue;
24627039e1dbSPeter Zijlstra 		return true;
24637039e1dbSPeter Zijlstra 	}
24647039e1dbSPeter Zijlstra 	return false;
24657039e1dbSPeter Zijlstra }
24667039e1dbSPeter Zijlstra 
24674e096ae1SMatthew Wilcox (Oracle) static struct folio *alloc_misplaced_dst_folio(struct folio *src,
2468666feb21SMichal Hocko 					   unsigned long data)
24697039e1dbSPeter Zijlstra {
24707039e1dbSPeter Zijlstra 	int nid = (int) data;
24714e096ae1SMatthew Wilcox (Oracle) 	int order = folio_order(src);
2472c185e494SMatthew Wilcox (Oracle) 	gfp_t gfp = __GFP_THISNODE;
24737039e1dbSPeter Zijlstra 
2474c185e494SMatthew Wilcox (Oracle) 	if (order > 0)
2475c185e494SMatthew Wilcox (Oracle) 		gfp |= GFP_TRANSHUGE_LIGHT;
2476c185e494SMatthew Wilcox (Oracle) 	else {
2477c185e494SMatthew Wilcox (Oracle) 		gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2478c185e494SMatthew Wilcox (Oracle) 			__GFP_NOWARN;
2479c185e494SMatthew Wilcox (Oracle) 		gfp &= ~__GFP_RECLAIM;
24807039e1dbSPeter Zijlstra 	}
24814e096ae1SMatthew Wilcox (Oracle) 	return __folio_alloc_node(gfp, order, nid);
2482c5b5a3ddSYang Shi }
2483c5b5a3ddSYang Shi 
24842ac9e99fSKefeng Wang static int numamigrate_isolate_folio(pg_data_t *pgdat, struct folio *folio)
2485b32967ffSMel Gorman {
24862ac9e99fSKefeng Wang 	int nr_pages = folio_nr_pages(folio);
2487b32967ffSMel Gorman 
2488b32967ffSMel Gorman 	/* Avoid migrating to a node that is nearly full */
2489c574bbe9SHuang Ying 	if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2490c574bbe9SHuang Ying 		int z;
2491c574bbe9SHuang Ying 
2492c574bbe9SHuang Ying 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2493340ef390SHugh Dickins 			return 0;
2494c574bbe9SHuang Ying 		for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2495bc53008eSWei Yang 			if (managed_zone(pgdat->node_zones + z))
2496c574bbe9SHuang Ying 				break;
2497c574bbe9SHuang Ying 		}
24982ac9e99fSKefeng Wang 		wakeup_kswapd(pgdat->node_zones + z, 0,
24992ac9e99fSKefeng Wang 			      folio_order(folio), ZONE_MOVABLE);
2500c574bbe9SHuang Ying 		return 0;
2501c574bbe9SHuang Ying 	}
2502b32967ffSMel Gorman 
25032ac9e99fSKefeng Wang 	if (!folio_isolate_lru(folio))
2504340ef390SHugh Dickins 		return 0;
2505340ef390SHugh Dickins 
25062ac9e99fSKefeng Wang 	node_stat_mod_folio(folio, NR_ISOLATED_ANON + folio_is_file_lru(folio),
25072b9b624fSBaolin Wang 			    nr_pages);
2508b32967ffSMel Gorman 
2509b32967ffSMel Gorman 	/*
25102ac9e99fSKefeng Wang 	 * Isolating the folio has taken another reference, so the
25112ac9e99fSKefeng Wang 	 * caller's reference can be safely dropped without the folio
2512340ef390SHugh Dickins 	 * disappearing underneath us during migration.
2513b32967ffSMel Gorman 	 */
25142ac9e99fSKefeng Wang 	folio_put(folio);
2515340ef390SHugh Dickins 	return 1;
2516b32967ffSMel Gorman }
2517b32967ffSMel Gorman 
2518a8f60772SMel Gorman /*
2519*73eab3caSKefeng Wang  * Attempt to migrate a misplaced folio to the specified destination
25207039e1dbSPeter Zijlstra  * node. Caller is expected to have an elevated reference count on
2521*73eab3caSKefeng Wang  * the folio that will be dropped by this function before returning.
25227039e1dbSPeter Zijlstra  */
2523*73eab3caSKefeng Wang int migrate_misplaced_folio(struct folio *folio, struct vm_area_struct *vma,
25241bc115d8SMel Gorman 			    int node)
25257039e1dbSPeter Zijlstra {
2526a8f60772SMel Gorman 	pg_data_t *pgdat = NODE_DATA(node);
2527340ef390SHugh Dickins 	int isolated;
2528b32967ffSMel Gorman 	int nr_remaining;
2529e39bb6beSHuang Ying 	unsigned int nr_succeeded;
25307039e1dbSPeter Zijlstra 	LIST_HEAD(migratepages);
2531*73eab3caSKefeng Wang 	int nr_pages = folio_nr_pages(folio);
2532c5b5a3ddSYang Shi 
2533c5b5a3ddSYang Shi 	/*
2534*73eab3caSKefeng Wang 	 * Don't migrate file folios that are mapped in multiple processes
25351bc115d8SMel Gorman 	 * with execute permissions as they are probably shared libraries.
2536*73eab3caSKefeng Wang 	 * To check if the folio is shared, ideally we want to make sure
2537*73eab3caSKefeng Wang 	 * every page is mapped to the same process. Doing that is very
2538*73eab3caSKefeng Wang 	 * expensive, so check the estimated mapcount of the folio instead.
25397039e1dbSPeter Zijlstra 	 */
2540*73eab3caSKefeng Wang 	if (folio_estimated_sharers(folio) != 1 && folio_is_file_lru(folio) &&
25417ee820eeSMiaohe Lin 	    (vma->vm_flags & VM_EXEC))
25427039e1dbSPeter Zijlstra 		goto out;
25437039e1dbSPeter Zijlstra 
2544a8f60772SMel Gorman 	/*
2545*73eab3caSKefeng Wang 	 * Also do not migrate dirty folios as not all filesystems can move
2546*73eab3caSKefeng Wang 	 * dirty folios in MIGRATE_ASYNC mode which is a waste of cycles.
254709a913a7SMel Gorman 	 */
2548*73eab3caSKefeng Wang 	if (folio_is_file_lru(folio) && folio_test_dirty(folio))
254909a913a7SMel Gorman 		goto out;
255009a913a7SMel Gorman 
2551*73eab3caSKefeng Wang 	isolated = numamigrate_isolate_folio(pgdat, folio);
2552b32967ffSMel Gorman 	if (!isolated)
25537039e1dbSPeter Zijlstra 		goto out;
25547039e1dbSPeter Zijlstra 
2555*73eab3caSKefeng Wang 	list_add(&folio->lru, &migratepages);
25564e096ae1SMatthew Wilcox (Oracle) 	nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_folio,
2557c185e494SMatthew Wilcox (Oracle) 				     NULL, node, MIGRATE_ASYNC,
2558c185e494SMatthew Wilcox (Oracle) 				     MR_NUMA_MISPLACED, &nr_succeeded);
25597039e1dbSPeter Zijlstra 	if (nr_remaining) {
256059c82b70SJoonsoo Kim 		if (!list_empty(&migratepages)) {
2561*73eab3caSKefeng Wang 			list_del(&folio->lru);
2562*73eab3caSKefeng Wang 			node_stat_mod_folio(folio, NR_ISOLATED_ANON +
2563*73eab3caSKefeng Wang 					folio_is_file_lru(folio), -nr_pages);
2564*73eab3caSKefeng Wang 			folio_putback_lru(folio);
256559c82b70SJoonsoo Kim 		}
25667039e1dbSPeter Zijlstra 		isolated = 0;
2567e39bb6beSHuang Ying 	}
2568e39bb6beSHuang Ying 	if (nr_succeeded) {
2569e39bb6beSHuang Ying 		count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2570*73eab3caSKefeng Wang 		if (!node_is_toptier(folio_nid(folio)) && node_is_toptier(node))
2571e39bb6beSHuang Ying 			mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2572e39bb6beSHuang Ying 					    nr_succeeded);
2573e39bb6beSHuang Ying 	}
25747039e1dbSPeter Zijlstra 	BUG_ON(!list_empty(&migratepages));
25757039e1dbSPeter Zijlstra 	return isolated;
2576340ef390SHugh Dickins 
2577340ef390SHugh Dickins out:
2578*73eab3caSKefeng Wang 	folio_put(folio);
2579340ef390SHugh Dickins 	return 0;
25807039e1dbSPeter Zijlstra }
2581220018d3SMel Gorman #endif /* CONFIG_NUMA_BALANCING */
25827d6e2d96SOscar Salvador #endif /* CONFIG_NUMA */
2583