Merge tag 'dma-mapping-6.4-2023-04-28' of git://git.infradead.org/users/hch/dma-mapping
[linux-block.git] / mm / migrate.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
b20a3503 2/*
14e0f9bc 3 * Memory Migration functionality - linux/mm/migrate.c
b20a3503
CL
4 *
5 * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
6 *
7 * Page migration was first developed in the context of the memory hotplug
8 * project. The main authors of the migration code are:
9 *
10 * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
11 * Hirokazu Takahashi <taka@valinux.co.jp>
12 * Dave Hansen <haveblue@us.ibm.com>
cde53535 13 * Christoph Lameter
b20a3503
CL
14 */
15
16#include <linux/migrate.h>
b95f1b31 17#include <linux/export.h>
b20a3503 18#include <linux/swap.h>
0697212a 19#include <linux/swapops.h>
b20a3503 20#include <linux/pagemap.h>
e23ca00b 21#include <linux/buffer_head.h>
b20a3503 22#include <linux/mm_inline.h>
b488893a 23#include <linux/nsproxy.h>
b20a3503 24#include <linux/pagevec.h>
e9995ef9 25#include <linux/ksm.h>
b20a3503
CL
26#include <linux/rmap.h>
27#include <linux/topology.h>
28#include <linux/cpu.h>
29#include <linux/cpuset.h>
04e62a29 30#include <linux/writeback.h>
742755a1
CL
31#include <linux/mempolicy.h>
32#include <linux/vmalloc.h>
86c3a764 33#include <linux/security.h>
42cb14b1 34#include <linux/backing-dev.h>
bda807d4 35#include <linux/compaction.h>
4f5ca265 36#include <linux/syscalls.h>
7addf443 37#include <linux/compat.h>
290408d4 38#include <linux/hugetlb.h>
8e6ac7fa 39#include <linux/hugetlb_cgroup.h>
5a0e3ad6 40#include <linux/gfp.h>
df6ad698 41#include <linux/pfn_t.h>
a5430dda 42#include <linux/memremap.h>
8315ada7 43#include <linux/userfaultfd_k.h>
bf6bddf1 44#include <linux/balloon_compaction.h>
33c3fc71 45#include <linux/page_idle.h>
d435edca 46#include <linux/page_owner.h>
6e84f315 47#include <linux/sched/mm.h>
197e7e52 48#include <linux/ptrace.h>
34290e2c 49#include <linux/oom.h>
884a6e5d 50#include <linux/memory.h>
ac16ec83 51#include <linux/random.h>
c574bbe9 52#include <linux/sched/sysctl.h>
467b171a 53#include <linux/memory-tiers.h>
b20a3503 54
0d1836c3
MN
55#include <asm/tlbflush.h>
56
7b2a2d4a
MG
57#include <trace/events/migrate.h>
58
b20a3503
CL
59#include "internal.h"
60
cd775580 61bool isolate_movable_page(struct page *page, isolate_mode_t mode)
bda807d4 62{
19979497 63 struct folio *folio = folio_get_nontail_page(page);
68f2736a 64 const struct movable_operations *mops;
bda807d4
MK
65
66 /*
67 * Avoid burning cycles with pages that are yet under __free_pages(),
68 * or just got freed under us.
69 *
70 * In case we 'win' a race for a movable page being freed under us and
71 * raise its refcount preventing __free_pages() from doing its job
72 * the put_page() at the end of this block will take care of
73 * release this page, thus avoiding a nasty leakage.
74 */
19979497 75 if (!folio)
bda807d4
MK
76 goto out;
77
19979497
VMO
78 if (unlikely(folio_test_slab(folio)))
79 goto out_putfolio;
8b881763
VB
80 /* Pairs with smp_wmb() in slab freeing, e.g. SLUB's __free_slab() */
81 smp_rmb();
bda807d4 82 /*
8b881763
VB
83 * Check movable flag before taking the page lock because
84 * we use non-atomic bitops on newly allocated page flags so
85 * unconditionally grabbing the lock ruins page's owner side.
bda807d4 86 */
19979497
VMO
87 if (unlikely(!__folio_test_movable(folio)))
88 goto out_putfolio;
8b881763
VB
89 /* Pairs with smp_wmb() in slab allocation, e.g. SLUB's alloc_slab_page() */
90 smp_rmb();
19979497
VMO
91 if (unlikely(folio_test_slab(folio)))
92 goto out_putfolio;
8b881763 93
bda807d4
MK
94 /*
95 * As movable pages are not isolated from LRU lists, concurrent
96 * compaction threads can race against page migration functions
97 * as well as race against the releasing a page.
98 *
99 * In order to avoid having an already isolated movable page
100 * being (wrongly) re-isolated while it is under migration,
101 * or to avoid attempting to isolate pages being released,
102 * lets be sure we have the page lock
103 * before proceeding with the movable page isolation steps.
104 */
19979497
VMO
105 if (unlikely(!folio_trylock(folio)))
106 goto out_putfolio;
bda807d4 107
19979497 108 if (!folio_test_movable(folio) || folio_test_isolated(folio))
bda807d4
MK
109 goto out_no_isolated;
110
19979497
VMO
111 mops = folio_movable_ops(folio);
112 VM_BUG_ON_FOLIO(!mops, folio);
bda807d4 113
19979497 114 if (!mops->isolate_page(&folio->page, mode))
bda807d4
MK
115 goto out_no_isolated;
116
117 /* Driver shouldn't use PG_isolated bit of page->flags */
19979497
VMO
118 WARN_ON_ONCE(folio_test_isolated(folio));
119 folio_set_isolated(folio);
120 folio_unlock(folio);
bda807d4 121
cd775580 122 return true;
bda807d4
MK
123
124out_no_isolated:
19979497
VMO
125 folio_unlock(folio);
126out_putfolio:
127 folio_put(folio);
bda807d4 128out:
cd775580 129 return false;
bda807d4
MK
130}
131
280d724a 132static void putback_movable_folio(struct folio *folio)
bda807d4 133{
280d724a 134 const struct movable_operations *mops = folio_movable_ops(folio);
bda807d4 135
280d724a
VMO
136 mops->putback_page(&folio->page);
137 folio_clear_isolated(folio);
bda807d4
MK
138}
139
5733c7d1
RA
140/*
141 * Put previously isolated pages back onto the appropriate lists
142 * from where they were once taken off for compaction/migration.
143 *
59c82b70
JK
144 * This function shall be used whenever the isolated pageset has been
145 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
7ce82f4c 146 * and isolate_hugetlb().
5733c7d1
RA
147 */
148void putback_movable_pages(struct list_head *l)
149{
280d724a
VMO
150 struct folio *folio;
151 struct folio *folio2;
5733c7d1 152
280d724a
VMO
153 list_for_each_entry_safe(folio, folio2, l, lru) {
154 if (unlikely(folio_test_hugetlb(folio))) {
155 folio_putback_active_hugetlb(folio);
31caf665
NH
156 continue;
157 }
280d724a 158 list_del(&folio->lru);
bda807d4 159 /*
280d724a
VMO
160 * We isolated non-lru movable folio so here we can use
161 * __PageMovable because LRU folio's mapping cannot have
bda807d4
MK
162 * PAGE_MAPPING_MOVABLE.
163 */
280d724a
VMO
164 if (unlikely(__folio_test_movable(folio))) {
165 VM_BUG_ON_FOLIO(!folio_test_isolated(folio), folio);
166 folio_lock(folio);
167 if (folio_test_movable(folio))
168 putback_movable_folio(folio);
bda807d4 169 else
280d724a
VMO
170 folio_clear_isolated(folio);
171 folio_unlock(folio);
172 folio_put(folio);
bda807d4 173 } else {
280d724a
VMO
174 node_stat_mod_folio(folio, NR_ISOLATED_ANON +
175 folio_is_file_lru(folio), -folio_nr_pages(folio));
176 folio_putback_lru(folio);
bda807d4 177 }
b20a3503 178 }
b20a3503
CL
179}
180
0697212a
CL
181/*
182 * Restore a potential migration pte to a working pte entry
183 */
2f031c6f
MWO
184static bool remove_migration_pte(struct folio *folio,
185 struct vm_area_struct *vma, unsigned long addr, void *old)
0697212a 186{
4eecb8b9 187 DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
0697212a 188
3fe87967 189 while (page_vma_mapped_walk(&pvmw)) {
6c287605 190 rmap_t rmap_flags = RMAP_NONE;
4eecb8b9
MWO
191 pte_t pte;
192 swp_entry_t entry;
193 struct page *new;
194 unsigned long idx = 0;
195
196 /* pgoff is invalid for ksm pages, but they are never large */
197 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
198 idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
199 new = folio_page(folio, idx);
0697212a 200
616b8371
ZY
201#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
202 /* PMD-mapped THP migration entry */
203 if (!pvmw.pte) {
4eecb8b9
MWO
204 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
205 !folio_test_pmd_mappable(folio), folio);
616b8371
ZY
206 remove_migration_pmd(&pvmw, new);
207 continue;
208 }
209#endif
210
4eecb8b9 211 folio_get(folio);
2e346877 212 pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
3fe87967
KS
213 if (pte_swp_soft_dirty(*pvmw.pte))
214 pte = pte_mksoft_dirty(pte);
0697212a 215
3fe87967 216 entry = pte_to_swp_entry(*pvmw.pte);
2e346877
PX
217 if (!is_migration_entry_young(entry))
218 pte = pte_mkold(pte);
219 if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
220 pte = pte_mkdirty(pte);
4dd845b5 221 if (is_writable_migration_entry(entry))
f3ebdf04 222 pte = pte_mkwrite(pte);
f45ec5ff
PX
223 else if (pte_swp_uffd_wp(*pvmw.pte))
224 pte = pte_mkuffd_wp(pte);
d3cb8bf6 225
6c287605
DH
226 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
227 rmap_flags |= RMAP_EXCLUSIVE;
228
6128763f 229 if (unlikely(is_device_private_page(new))) {
4dd845b5
AP
230 if (pte_write(pte))
231 entry = make_writable_device_private_entry(
232 page_to_pfn(new));
233 else
234 entry = make_readable_device_private_entry(
235 page_to_pfn(new));
6128763f 236 pte = swp_entry_to_pte(entry);
3d321bf8
RC
237 if (pte_swp_soft_dirty(*pvmw.pte))
238 pte = pte_swp_mksoft_dirty(pte);
6128763f
RC
239 if (pte_swp_uffd_wp(*pvmw.pte))
240 pte = pte_swp_mkuffd_wp(pte);
d2b2c6dd 241 }
a5430dda 242
3ef8fd7f 243#ifdef CONFIG_HUGETLB_PAGE
4eecb8b9 244 if (folio_test_hugetlb(folio)) {
79c1c594
CL
245 unsigned int shift = huge_page_shift(hstate_vma(vma));
246
79c1c594 247 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
4eecb8b9 248 if (folio_test_anon(folio))
28c5209d 249 hugepage_add_anon_rmap(new, vma, pvmw.address,
6c287605 250 rmap_flags);
3fe87967 251 else
fb3d824d 252 page_dup_file_rmap(new, true);
1eba86c0 253 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
383321ab
AK
254 } else
255#endif
256 {
4eecb8b9 257 if (folio_test_anon(folio))
f1e2db12 258 page_add_anon_rmap(new, vma, pvmw.address,
6c287605 259 rmap_flags);
383321ab 260 else
cea86fe2 261 page_add_file_rmap(new, vma, false);
1eba86c0 262 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
383321ab 263 }
b7435507 264 if (vma->vm_flags & VM_LOCKED)
96f97c43 265 mlock_drain_local();
e125fe40 266
4cc79b33
AK
267 trace_remove_migration_pte(pvmw.address, pte_val(pte),
268 compound_order(new));
269
3fe87967
KS
270 /* No need to invalidate - it was non-present before */
271 update_mmu_cache(vma, pvmw.address, pvmw.pte);
272 }
51afb12b 273
e4b82222 274 return true;
0697212a
CL
275}
276
04e62a29
CL
277/*
278 * Get rid of all migration entries and replace them by
279 * references to the indicated page.
280 */
4eecb8b9 281void remove_migration_ptes(struct folio *src, struct folio *dst, bool locked)
04e62a29 282{
051ac83a
JK
283 struct rmap_walk_control rwc = {
284 .rmap_one = remove_migration_pte,
4eecb8b9 285 .arg = src,
051ac83a
JK
286 };
287
e388466d 288 if (locked)
2f031c6f 289 rmap_walk_locked(dst, &rwc);
e388466d 290 else
2f031c6f 291 rmap_walk(dst, &rwc);
04e62a29
CL
292}
293
0697212a
CL
294/*
295 * Something used the pte of a page under migration. We need to
296 * get to the page and wait until migration is finished.
297 * When we return from this function the fault will be retried.
0697212a 298 */
e66f17ff 299void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
30dad309 300 spinlock_t *ptl)
0697212a 301{
30dad309 302 pte_t pte;
0697212a 303 swp_entry_t entry;
0697212a 304
30dad309 305 spin_lock(ptl);
0697212a
CL
306 pte = *ptep;
307 if (!is_swap_pte(pte))
308 goto out;
309
310 entry = pte_to_swp_entry(pte);
311 if (!is_migration_entry(entry))
312 goto out;
313
ffa65753 314 migration_entry_wait_on_locked(entry, ptep, ptl);
0697212a
CL
315 return;
316out:
317 pte_unmap_unlock(ptep, ptl);
318}
319
30dad309
NH
320void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
321 unsigned long address)
322{
323 spinlock_t *ptl = pte_lockptr(mm, pmd);
324 pte_t *ptep = pte_offset_map(pmd, address);
325 __migration_entry_wait(mm, ptep, ptl);
326}
327
ad1ac596 328#ifdef CONFIG_HUGETLB_PAGE
fcd48540
PX
329/*
330 * The vma read lock must be held upon entry. Holding that lock prevents either
331 * the pte or the ptl from being freed.
332 *
333 * This function will release the vma lock before returning.
334 */
335void __migration_entry_wait_huge(struct vm_area_struct *vma,
336 pte_t *ptep, spinlock_t *ptl)
30dad309 337{
ad1ac596
ML
338 pte_t pte;
339
fcd48540 340 hugetlb_vma_assert_locked(vma);
ad1ac596
ML
341 spin_lock(ptl);
342 pte = huge_ptep_get(ptep);
343
fcd48540 344 if (unlikely(!is_hugetlb_entry_migration(pte))) {
ad1ac596 345 spin_unlock(ptl);
fcd48540
PX
346 hugetlb_vma_unlock_read(vma);
347 } else {
348 /*
349 * If migration entry existed, safe to release vma lock
350 * here because the pgtable page won't be freed without the
351 * pgtable lock released. See comment right above pgtable
352 * lock release in migration_entry_wait_on_locked().
353 */
354 hugetlb_vma_unlock_read(vma);
ad1ac596 355 migration_entry_wait_on_locked(pte_to_swp_entry(pte), NULL, ptl);
fcd48540 356 }
30dad309
NH
357}
358
ad1ac596
ML
359void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *pte)
360{
361 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, pte);
362
fcd48540 363 __migration_entry_wait_huge(vma, pte, ptl);
ad1ac596
ML
364}
365#endif
366
616b8371
ZY
367#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
368void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
369{
370 spinlock_t *ptl;
616b8371
ZY
371
372 ptl = pmd_lock(mm, pmd);
373 if (!is_pmd_migration_entry(*pmd))
374 goto unlock;
ffa65753 375 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
616b8371
ZY
376 return;
377unlock:
378 spin_unlock(ptl);
379}
380#endif
381
108ca835
MWO
382static int folio_expected_refs(struct address_space *mapping,
383 struct folio *folio)
0b3901b3 384{
108ca835
MWO
385 int refs = 1;
386 if (!mapping)
387 return refs;
0b3901b3 388
108ca835
MWO
389 refs += folio_nr_pages(folio);
390 if (folio_test_private(folio))
391 refs++;
392
393 return refs;
0b3901b3
JK
394}
395
b20a3503 396/*
c3fcf8a5 397 * Replace the page in the mapping.
5b5c7120
CL
398 *
399 * The number of remaining references must be:
400 * 1 for anonymous pages without a mapping
401 * 2 for pages with a mapping
266cf658 402 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
b20a3503 403 */
3417013e
MWO
404int folio_migrate_mapping(struct address_space *mapping,
405 struct folio *newfolio, struct folio *folio, int extra_count)
b20a3503 406{
3417013e 407 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
42cb14b1
HD
408 struct zone *oldzone, *newzone;
409 int dirty;
108ca835 410 int expected_count = folio_expected_refs(mapping, folio) + extra_count;
3417013e 411 long nr = folio_nr_pages(folio);
8763cb45 412
6c5240ae 413 if (!mapping) {
0e8c7d0f 414 /* Anonymous page without mapping */
3417013e 415 if (folio_ref_count(folio) != expected_count)
6c5240ae 416 return -EAGAIN;
cf4b769a
HD
417
418 /* No turning back from here */
3417013e
MWO
419 newfolio->index = folio->index;
420 newfolio->mapping = folio->mapping;
421 if (folio_test_swapbacked(folio))
422 __folio_set_swapbacked(newfolio);
cf4b769a 423
78bd5209 424 return MIGRATEPAGE_SUCCESS;
6c5240ae
CL
425 }
426
3417013e
MWO
427 oldzone = folio_zone(folio);
428 newzone = folio_zone(newfolio);
42cb14b1 429
89eb946a 430 xas_lock_irq(&xas);
3417013e 431 if (!folio_ref_freeze(folio, expected_count)) {
89eb946a 432 xas_unlock_irq(&xas);
e286781d
NP
433 return -EAGAIN;
434 }
435
b20a3503 436 /*
3417013e 437 * Now we know that no one else is looking at the folio:
cf4b769a 438 * no turning back from here.
b20a3503 439 */
3417013e
MWO
440 newfolio->index = folio->index;
441 newfolio->mapping = folio->mapping;
442 folio_ref_add(newfolio, nr); /* add cache reference */
443 if (folio_test_swapbacked(folio)) {
444 __folio_set_swapbacked(newfolio);
445 if (folio_test_swapcache(folio)) {
446 folio_set_swapcache(newfolio);
447 newfolio->private = folio_get_private(folio);
6326fec1
NP
448 }
449 } else {
3417013e 450 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
b20a3503
CL
451 }
452
42cb14b1 453 /* Move dirty while page refs frozen and newpage not yet exposed */
3417013e 454 dirty = folio_test_dirty(folio);
42cb14b1 455 if (dirty) {
3417013e
MWO
456 folio_clear_dirty(folio);
457 folio_set_dirty(newfolio);
42cb14b1
HD
458 }
459
3417013e 460 xas_store(&xas, newfolio);
7cf9c2c7
NP
461
462 /*
937a94c9
JG
463 * Drop cache reference from old page by unfreezing
464 * to one less reference.
7cf9c2c7
NP
465 * We know this isn't the last reference.
466 */
3417013e 467 folio_ref_unfreeze(folio, expected_count - nr);
7cf9c2c7 468
89eb946a 469 xas_unlock(&xas);
42cb14b1
HD
470 /* Leave irq disabled to prevent preemption while updating stats */
471
0e8c7d0f
CL
472 /*
473 * If moved to a different zone then also account
474 * the page for that zone. Other VM counters will be
475 * taken care of when we establish references to the
476 * new page and drop references to the old page.
477 *
478 * Note that anonymous pages are accounted for
4b9d0fab 479 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
0e8c7d0f
CL
480 * are mapped to swap space.
481 */
42cb14b1 482 if (newzone != oldzone) {
0d1c2072
JW
483 struct lruvec *old_lruvec, *new_lruvec;
484 struct mem_cgroup *memcg;
485
3417013e 486 memcg = folio_memcg(folio);
0d1c2072
JW
487 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
488 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
489
5c447d27
SB
490 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
491 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
3417013e 492 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
5c447d27
SB
493 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
494 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
42cb14b1 495 }
b6038942 496#ifdef CONFIG_SWAP
3417013e 497 if (folio_test_swapcache(folio)) {
b6038942
SB
498 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
499 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
500 }
501#endif
f56753ac 502 if (dirty && mapping_can_writeback(mapping)) {
5c447d27
SB
503 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
504 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
505 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
506 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
42cb14b1 507 }
4b02108a 508 }
42cb14b1 509 local_irq_enable();
b20a3503 510
78bd5209 511 return MIGRATEPAGE_SUCCESS;
b20a3503 512}
3417013e 513EXPORT_SYMBOL(folio_migrate_mapping);
b20a3503 514
290408d4
NH
515/*
516 * The expected number of remaining references is the same as that
3417013e 517 * of folio_migrate_mapping().
290408d4
NH
518 */
519int migrate_huge_page_move_mapping(struct address_space *mapping,
b890ec2a 520 struct folio *dst, struct folio *src)
290408d4 521{
b890ec2a 522 XA_STATE(xas, &mapping->i_pages, folio_index(src));
290408d4 523 int expected_count;
290408d4 524
89eb946a 525 xas_lock_irq(&xas);
b890ec2a
MWO
526 expected_count = 2 + folio_has_private(src);
527 if (!folio_ref_freeze(src, expected_count)) {
89eb946a 528 xas_unlock_irq(&xas);
290408d4
NH
529 return -EAGAIN;
530 }
531
b890ec2a
MWO
532 dst->index = src->index;
533 dst->mapping = src->mapping;
6a93ca8f 534
b890ec2a 535 folio_get(dst);
290408d4 536
b890ec2a 537 xas_store(&xas, dst);
290408d4 538
b890ec2a 539 folio_ref_unfreeze(src, expected_count - 1);
290408d4 540
89eb946a 541 xas_unlock_irq(&xas);
6a93ca8f 542
78bd5209 543 return MIGRATEPAGE_SUCCESS;
290408d4
NH
544}
545
b20a3503 546/*
19138349 547 * Copy the flags and some other ancillary information
b20a3503 548 */
19138349 549void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
b20a3503 550{
7851a45c
RR
551 int cpupid;
552
19138349
MWO
553 if (folio_test_error(folio))
554 folio_set_error(newfolio);
555 if (folio_test_referenced(folio))
556 folio_set_referenced(newfolio);
557 if (folio_test_uptodate(folio))
558 folio_mark_uptodate(newfolio);
559 if (folio_test_clear_active(folio)) {
560 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
561 folio_set_active(newfolio);
562 } else if (folio_test_clear_unevictable(folio))
563 folio_set_unevictable(newfolio);
564 if (folio_test_workingset(folio))
565 folio_set_workingset(newfolio);
566 if (folio_test_checked(folio))
567 folio_set_checked(newfolio);
6c287605
DH
568 /*
569 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
570 * migration entries. We can still have PG_anon_exclusive set on an
571 * effectively unmapped and unreferenced first sub-pages of an
572 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
573 */
19138349
MWO
574 if (folio_test_mappedtodisk(folio))
575 folio_set_mappedtodisk(newfolio);
b20a3503 576
3417013e 577 /* Move dirty on pages not done by folio_migrate_mapping() */
19138349
MWO
578 if (folio_test_dirty(folio))
579 folio_set_dirty(newfolio);
b20a3503 580
19138349
MWO
581 if (folio_test_young(folio))
582 folio_set_young(newfolio);
583 if (folio_test_idle(folio))
584 folio_set_idle(newfolio);
33c3fc71 585
7851a45c
RR
586 /*
587 * Copy NUMA information to the new page, to prevent over-eager
588 * future migrations of this same page.
589 */
19138349 590 cpupid = page_cpupid_xchg_last(&folio->page, -1);
33024536
HY
591 /*
592 * For memory tiering mode, when migrate between slow and fast
593 * memory node, reset cpupid, because that is used to record
594 * page access time in slow memory node.
595 */
596 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
597 bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
598 bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
599
600 if (f_toptier != t_toptier)
601 cpupid = -1;
602 }
19138349 603 page_cpupid_xchg_last(&newfolio->page, cpupid);
7851a45c 604
19138349 605 folio_migrate_ksm(newfolio, folio);
c8d6553b
HD
606 /*
607 * Please do not reorder this without considering how mm/ksm.c's
608 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
609 */
19138349
MWO
610 if (folio_test_swapcache(folio))
611 folio_clear_swapcache(folio);
612 folio_clear_private(folio);
ad2fa371
MS
613
614 /* page->private contains hugetlb specific flags */
19138349
MWO
615 if (!folio_test_hugetlb(folio))
616 folio->private = NULL;
b20a3503
CL
617
618 /*
619 * If any waiters have accumulated on the new page then
620 * wake them up.
621 */
19138349
MWO
622 if (folio_test_writeback(newfolio))
623 folio_end_writeback(newfolio);
d435edca 624
6aeff241
YS
625 /*
626 * PG_readahead shares the same bit with PG_reclaim. The above
627 * end_page_writeback() may clear PG_readahead mistakenly, so set the
628 * bit after that.
629 */
19138349
MWO
630 if (folio_test_readahead(folio))
631 folio_set_readahead(newfolio);
6aeff241 632
19138349 633 folio_copy_owner(newfolio, folio);
74485cf2 634
19138349 635 if (!folio_test_hugetlb(folio))
d21bba2b 636 mem_cgroup_migrate(folio, newfolio);
b20a3503 637}
19138349 638EXPORT_SYMBOL(folio_migrate_flags);
2916ecc0 639
715cbfd6 640void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
2916ecc0 641{
715cbfd6
MWO
642 folio_copy(newfolio, folio);
643 folio_migrate_flags(newfolio, folio);
2916ecc0 644}
715cbfd6 645EXPORT_SYMBOL(folio_migrate_copy);
b20a3503 646
1d8b85cc
CL
647/************************************************************
648 * Migration functions
649 ***********************************************************/
650
16ce101d
AP
651int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
652 struct folio *src, enum migrate_mode mode, int extra_count)
653{
654 int rc;
655
656 BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
657
658 rc = folio_migrate_mapping(mapping, dst, src, extra_count);
659
660 if (rc != MIGRATEPAGE_SUCCESS)
661 return rc;
662
663 if (mode != MIGRATE_SYNC_NO_COPY)
664 folio_migrate_copy(dst, src);
665 else
666 folio_migrate_flags(dst, src);
667 return MIGRATEPAGE_SUCCESS;
668}
669
54184650
MWO
670/**
671 * migrate_folio() - Simple folio migration.
672 * @mapping: The address_space containing the folio.
673 * @dst: The folio to migrate the data to.
674 * @src: The folio containing the current data.
675 * @mode: How to migrate the page.
676 *
677 * Common logic to directly migrate a single LRU folio suitable for
678 * folios that do not use PagePrivate/PagePrivate2.
b20a3503 679 *
54184650 680 * Folios are locked upon entry and exit.
b20a3503 681 */
54184650
MWO
682int migrate_folio(struct address_space *mapping, struct folio *dst,
683 struct folio *src, enum migrate_mode mode)
b20a3503 684{
16ce101d 685 return migrate_folio_extra(mapping, dst, src, mode, 0);
b20a3503 686}
54184650 687EXPORT_SYMBOL(migrate_folio);
b20a3503 688
9361401e 689#ifdef CONFIG_BLOCK
84ade7c1
JK
690/* Returns true if all buffers are successfully locked */
691static bool buffer_migrate_lock_buffers(struct buffer_head *head,
692 enum migrate_mode mode)
693{
694 struct buffer_head *bh = head;
695
696 /* Simple case, sync compaction */
697 if (mode != MIGRATE_ASYNC) {
698 do {
84ade7c1
JK
699 lock_buffer(bh);
700 bh = bh->b_this_page;
701
702 } while (bh != head);
703
704 return true;
705 }
706
707 /* async case, we cannot block on lock_buffer so use trylock_buffer */
708 do {
84ade7c1
JK
709 if (!trylock_buffer(bh)) {
710 /*
711 * We failed to lock the buffer and cannot stall in
712 * async migration. Release the taken locks
713 */
714 struct buffer_head *failed_bh = bh;
84ade7c1
JK
715 bh = head;
716 while (bh != failed_bh) {
717 unlock_buffer(bh);
84ade7c1
JK
718 bh = bh->b_this_page;
719 }
720 return false;
721 }
722
723 bh = bh->b_this_page;
724 } while (bh != head);
725 return true;
726}
727
67235182
MWO
728static int __buffer_migrate_folio(struct address_space *mapping,
729 struct folio *dst, struct folio *src, enum migrate_mode mode,
89cb0888 730 bool check_refs)
1d8b85cc 731{
1d8b85cc
CL
732 struct buffer_head *bh, *head;
733 int rc;
cc4f11e6 734 int expected_count;
1d8b85cc 735
67235182
MWO
736 head = folio_buffers(src);
737 if (!head)
54184650 738 return migrate_folio(mapping, dst, src, mode);
1d8b85cc 739
cc4f11e6 740 /* Check whether page does not have extra refs before we do more work */
108ca835 741 expected_count = folio_expected_refs(mapping, src);
67235182 742 if (folio_ref_count(src) != expected_count)
cc4f11e6 743 return -EAGAIN;
1d8b85cc 744
cc4f11e6
JK
745 if (!buffer_migrate_lock_buffers(head, mode))
746 return -EAGAIN;
1d8b85cc 747
89cb0888
JK
748 if (check_refs) {
749 bool busy;
750 bool invalidated = false;
751
752recheck_buffers:
753 busy = false;
754 spin_lock(&mapping->private_lock);
755 bh = head;
756 do {
757 if (atomic_read(&bh->b_count)) {
758 busy = true;
759 break;
760 }
761 bh = bh->b_this_page;
762 } while (bh != head);
89cb0888
JK
763 if (busy) {
764 if (invalidated) {
765 rc = -EAGAIN;
766 goto unlock_buffers;
767 }
ebdf4de5 768 spin_unlock(&mapping->private_lock);
89cb0888
JK
769 invalidate_bh_lrus();
770 invalidated = true;
771 goto recheck_buffers;
772 }
773 }
774
67235182 775 rc = folio_migrate_mapping(mapping, dst, src, 0);
78bd5209 776 if (rc != MIGRATEPAGE_SUCCESS)
cc4f11e6 777 goto unlock_buffers;
1d8b85cc 778
67235182 779 folio_attach_private(dst, folio_detach_private(src));
1d8b85cc
CL
780
781 bh = head;
782 do {
67235182 783 set_bh_page(bh, &dst->page, bh_offset(bh));
1d8b85cc 784 bh = bh->b_this_page;
1d8b85cc
CL
785 } while (bh != head);
786
2916ecc0 787 if (mode != MIGRATE_SYNC_NO_COPY)
67235182 788 folio_migrate_copy(dst, src);
2916ecc0 789 else
67235182 790 folio_migrate_flags(dst, src);
1d8b85cc 791
cc4f11e6
JK
792 rc = MIGRATEPAGE_SUCCESS;
793unlock_buffers:
ebdf4de5
JK
794 if (check_refs)
795 spin_unlock(&mapping->private_lock);
1d8b85cc
CL
796 bh = head;
797 do {
798 unlock_buffer(bh);
1d8b85cc 799 bh = bh->b_this_page;
1d8b85cc
CL
800 } while (bh != head);
801
cc4f11e6 802 return rc;
1d8b85cc 803}
89cb0888 804
67235182
MWO
805/**
806 * buffer_migrate_folio() - Migration function for folios with buffers.
807 * @mapping: The address space containing @src.
808 * @dst: The folio to migrate to.
809 * @src: The folio to migrate from.
810 * @mode: How to migrate the folio.
811 *
812 * This function can only be used if the underlying filesystem guarantees
813 * that no other references to @src exist. For example attached buffer
814 * heads are accessed only under the folio lock. If your filesystem cannot
815 * provide this guarantee, buffer_migrate_folio_norefs() may be more
816 * appropriate.
817 *
818 * Return: 0 on success or a negative errno on failure.
89cb0888 819 */
67235182
MWO
820int buffer_migrate_folio(struct address_space *mapping,
821 struct folio *dst, struct folio *src, enum migrate_mode mode)
89cb0888 822{
67235182 823 return __buffer_migrate_folio(mapping, dst, src, mode, false);
89cb0888 824}
67235182
MWO
825EXPORT_SYMBOL(buffer_migrate_folio);
826
827/**
828 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
829 * @mapping: The address space containing @src.
830 * @dst: The folio to migrate to.
831 * @src: The folio to migrate from.
832 * @mode: How to migrate the folio.
833 *
834 * Like buffer_migrate_folio() except that this variant is more careful
835 * and checks that there are also no buffer head references. This function
836 * is the right one for mappings where buffer heads are directly looked
837 * up and referenced (such as block device mappings).
838 *
839 * Return: 0 on success or a negative errno on failure.
89cb0888 840 */
67235182
MWO
841int buffer_migrate_folio_norefs(struct address_space *mapping,
842 struct folio *dst, struct folio *src, enum migrate_mode mode)
89cb0888 843{
67235182 844 return __buffer_migrate_folio(mapping, dst, src, mode, true);
89cb0888 845}
e26355e2 846EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
9361401e 847#endif
1d8b85cc 848
2ec810d5
MWO
849int filemap_migrate_folio(struct address_space *mapping,
850 struct folio *dst, struct folio *src, enum migrate_mode mode)
851{
852 int ret;
853
854 ret = folio_migrate_mapping(mapping, dst, src, 0);
855 if (ret != MIGRATEPAGE_SUCCESS)
856 return ret;
857
858 if (folio_get_private(src))
859 folio_attach_private(dst, folio_detach_private(src));
860
861 if (mode != MIGRATE_SYNC_NO_COPY)
862 folio_migrate_copy(dst, src);
863 else
864 folio_migrate_flags(dst, src);
865 return MIGRATEPAGE_SUCCESS;
866}
867EXPORT_SYMBOL_GPL(filemap_migrate_folio);
868
04e62a29 869/*
2be7fa10 870 * Writeback a folio to clean the dirty state
04e62a29 871 */
2be7fa10 872static int writeout(struct address_space *mapping, struct folio *folio)
8351a6e4 873{
04e62a29
CL
874 struct writeback_control wbc = {
875 .sync_mode = WB_SYNC_NONE,
876 .nr_to_write = 1,
877 .range_start = 0,
878 .range_end = LLONG_MAX,
04e62a29
CL
879 .for_reclaim = 1
880 };
881 int rc;
882
883 if (!mapping->a_ops->writepage)
884 /* No write method for the address space */
885 return -EINVAL;
886
2be7fa10 887 if (!folio_clear_dirty_for_io(folio))
04e62a29
CL
888 /* Someone else already triggered a write */
889 return -EAGAIN;
890
8351a6e4 891 /*
2be7fa10
MWO
892 * A dirty folio may imply that the underlying filesystem has
893 * the folio on some queue. So the folio must be clean for
894 * migration. Writeout may mean we lose the lock and the
895 * folio state is no longer what we checked for earlier.
04e62a29
CL
896 * At this point we know that the migration attempt cannot
897 * be successful.
8351a6e4 898 */
4eecb8b9 899 remove_migration_ptes(folio, folio, false);
8351a6e4 900
2be7fa10 901 rc = mapping->a_ops->writepage(&folio->page, &wbc);
8351a6e4 902
04e62a29
CL
903 if (rc != AOP_WRITEPAGE_ACTIVATE)
904 /* unlocked. Relock */
2be7fa10 905 folio_lock(folio);
04e62a29 906
bda8550d 907 return (rc < 0) ? -EIO : -EAGAIN;
04e62a29
CL
908}
909
910/*
911 * Default handling if a filesystem does not provide a migration function.
912 */
8faa8ef5
MWO
913static int fallback_migrate_folio(struct address_space *mapping,
914 struct folio *dst, struct folio *src, enum migrate_mode mode)
04e62a29 915{
8faa8ef5
MWO
916 if (folio_test_dirty(src)) {
917 /* Only writeback folios in full synchronous migration */
2916ecc0
JG
918 switch (mode) {
919 case MIGRATE_SYNC:
920 case MIGRATE_SYNC_NO_COPY:
921 break;
922 default:
b969c4ab 923 return -EBUSY;
2916ecc0 924 }
2be7fa10 925 return writeout(mapping, src);
b969c4ab 926 }
8351a6e4
CL
927
928 /*
929 * Buffers may be managed in a filesystem specific way.
930 * We must have no buffers or drop them.
931 */
8faa8ef5
MWO
932 if (folio_test_private(src) &&
933 !filemap_release_folio(src, GFP_KERNEL))
806031bb 934 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
8351a6e4 935
54184650 936 return migrate_folio(mapping, dst, src, mode);
8351a6e4
CL
937}
938
e24f0b8f
CL
939/*
940 * Move a page to a newly allocated page
941 * The page is locked and all ptes have been successfully removed.
942 *
943 * The new page will have replaced the old page if this function
944 * is successful.
894bc310
LS
945 *
946 * Return value:
947 * < 0 - error code
78bd5209 948 * MIGRATEPAGE_SUCCESS - success
e24f0b8f 949 */
e7e3ffeb 950static int move_to_new_folio(struct folio *dst, struct folio *src,
5c3f9a67 951 enum migrate_mode mode)
e24f0b8f 952{
bda807d4 953 int rc = -EAGAIN;
e7e3ffeb 954 bool is_lru = !__PageMovable(&src->page);
e24f0b8f 955
e7e3ffeb
MWO
956 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
957 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
e24f0b8f 958
bda807d4 959 if (likely(is_lru)) {
68f2736a
MWO
960 struct address_space *mapping = folio_mapping(src);
961
bda807d4 962 if (!mapping)
54184650 963 rc = migrate_folio(mapping, dst, src, mode);
5490da4f 964 else if (mapping->a_ops->migrate_folio)
bda807d4 965 /*
5490da4f
MWO
966 * Most folios have a mapping and most filesystems
967 * provide a migrate_folio callback. Anonymous folios
bda807d4 968 * are part of swap space which also has its own
5490da4f 969 * migrate_folio callback. This is the most common path
bda807d4
MK
970 * for page migration.
971 */
5490da4f
MWO
972 rc = mapping->a_ops->migrate_folio(mapping, dst, src,
973 mode);
bda807d4 974 else
8faa8ef5 975 rc = fallback_migrate_folio(mapping, dst, src, mode);
bda807d4 976 } else {
68f2736a
MWO
977 const struct movable_operations *mops;
978
e24f0b8f 979 /*
bda807d4
MK
980 * In case of non-lru page, it could be released after
981 * isolation step. In that case, we shouldn't try migration.
e24f0b8f 982 */
e7e3ffeb
MWO
983 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
984 if (!folio_test_movable(src)) {
bda807d4 985 rc = MIGRATEPAGE_SUCCESS;
e7e3ffeb 986 folio_clear_isolated(src);
bda807d4
MK
987 goto out;
988 }
989
da707a6d 990 mops = folio_movable_ops(src);
68f2736a 991 rc = mops->migrate_page(&dst->page, &src->page, mode);
bda807d4 992 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
e7e3ffeb 993 !folio_test_isolated(src));
bda807d4 994 }
e24f0b8f 995
5c3f9a67 996 /*
e7e3ffeb
MWO
997 * When successful, old pagecache src->mapping must be cleared before
998 * src is freed; but stats require that PageAnon be left as PageAnon.
5c3f9a67
HD
999 */
1000 if (rc == MIGRATEPAGE_SUCCESS) {
e7e3ffeb
MWO
1001 if (__PageMovable(&src->page)) {
1002 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
bda807d4
MK
1003
1004 /*
1005 * We clear PG_movable under page_lock so any compactor
1006 * cannot try to migrate this page.
1007 */
e7e3ffeb 1008 folio_clear_isolated(src);
bda807d4
MK
1009 }
1010
1011 /*
e7e3ffeb 1012 * Anonymous and movable src->mapping will be cleared by
bda807d4
MK
1013 * free_pages_prepare so don't reset it here for keeping
1014 * the type to work PageAnon, for example.
1015 */
e7e3ffeb
MWO
1016 if (!folio_mapping_flags(src))
1017 src->mapping = NULL;
d2b2c6dd 1018
e7e3ffeb
MWO
1019 if (likely(!folio_is_zone_device(dst)))
1020 flush_dcache_folio(dst);
3fe2011f 1021 }
bda807d4 1022out:
e24f0b8f
CL
1023 return rc;
1024}
1025
64c8902e
HY
1026/*
1027 * To record some information during migration, we use some unused
1028 * fields (mapping and private) of struct folio of the newly allocated
1029 * destination folio. This is safe because nobody is using them
1030 * except us.
1031 */
e77d587a
LT
1032union migration_ptr {
1033 struct anon_vma *anon_vma;
1034 struct address_space *mapping;
1035};
64c8902e
HY
1036static void __migrate_folio_record(struct folio *dst,
1037 unsigned long page_was_mapped,
1038 struct anon_vma *anon_vma)
1039{
e77d587a
LT
1040 union migration_ptr ptr = { .anon_vma = anon_vma };
1041 dst->mapping = ptr.mapping;
64c8902e
HY
1042 dst->private = (void *)page_was_mapped;
1043}
1044
1045static void __migrate_folio_extract(struct folio *dst,
1046 int *page_was_mappedp,
1047 struct anon_vma **anon_vmap)
1048{
e77d587a
LT
1049 union migration_ptr ptr = { .mapping = dst->mapping };
1050 *anon_vmap = ptr.anon_vma;
64c8902e
HY
1051 *page_was_mappedp = (unsigned long)dst->private;
1052 dst->mapping = NULL;
1053 dst->private = NULL;
1054}
1055
5dfab109
HY
1056/* Restore the source folio to the original state upon failure */
1057static void migrate_folio_undo_src(struct folio *src,
1058 int page_was_mapped,
1059 struct anon_vma *anon_vma,
ebe75e47 1060 bool locked,
5dfab109
HY
1061 struct list_head *ret)
1062{
1063 if (page_was_mapped)
1064 remove_migration_ptes(src, src, false);
1065 /* Drop an anon_vma reference if we took one */
1066 if (anon_vma)
1067 put_anon_vma(anon_vma);
ebe75e47
HY
1068 if (locked)
1069 folio_unlock(src);
1070 if (ret)
1071 list_move_tail(&src->lru, ret);
5dfab109
HY
1072}
1073
1074/* Restore the destination folio to the original state upon failure */
1075static void migrate_folio_undo_dst(struct folio *dst,
ebe75e47 1076 bool locked,
5dfab109
HY
1077 free_page_t put_new_page,
1078 unsigned long private)
1079{
ebe75e47
HY
1080 if (locked)
1081 folio_unlock(dst);
5dfab109
HY
1082 if (put_new_page)
1083 put_new_page(&dst->page, private);
1084 else
1085 folio_put(dst);
1086}
1087
64c8902e
HY
1088/* Cleanup src folio upon migration success */
1089static void migrate_folio_done(struct folio *src,
1090 enum migrate_reason reason)
1091{
1092 /*
1093 * Compaction can migrate also non-LRU pages which are
1094 * not accounted to NR_ISOLATED_*. They can be recognized
1095 * as __PageMovable
1096 */
1097 if (likely(!__folio_test_movable(src)))
1098 mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
1099 folio_is_file_lru(src), -folio_nr_pages(src));
1100
1101 if (reason != MR_MEMORY_FAILURE)
1102 /* We release the page in page_handle_poison. */
1103 folio_put(src);
1104}
1105
ebe75e47
HY
1106/* Obtain the lock on page, remove all ptes. */
1107static int migrate_folio_unmap(new_page_t get_new_page, free_page_t put_new_page,
1108 unsigned long private, struct folio *src,
2ef7dbb2
HY
1109 struct folio **dstp, enum migrate_mode mode,
1110 enum migrate_reason reason, struct list_head *ret)
e24f0b8f 1111{
ebe75e47 1112 struct folio *dst;
0dabec93 1113 int rc = -EAGAIN;
ebe75e47 1114 struct page *newpage = NULL;
64c8902e 1115 int page_was_mapped = 0;
3f6c8272 1116 struct anon_vma *anon_vma = NULL;
682a71a1 1117 bool is_lru = !__PageMovable(&src->page);
ebe75e47
HY
1118 bool locked = false;
1119 bool dst_locked = false;
1120
ebe75e47
HY
1121 if (folio_ref_count(src) == 1) {
1122 /* Folio was freed from under us. So we are done. */
1123 folio_clear_active(src);
1124 folio_clear_unevictable(src);
1125 /* free_pages_prepare() will clear PG_isolated. */
1126 list_del(&src->lru);
1127 migrate_folio_done(src, reason);
1128 return MIGRATEPAGE_SUCCESS;
1129 }
1130
1131 newpage = get_new_page(&src->page, private);
1132 if (!newpage)
1133 return -ENOMEM;
1134 dst = page_folio(newpage);
1135 *dstp = dst;
1136
1137 dst->private = NULL;
95a402c3 1138
682a71a1 1139 if (!folio_trylock(src)) {
2ef7dbb2 1140 if (mode == MIGRATE_ASYNC)
0dabec93 1141 goto out;
3e7d3449
MG
1142
1143 /*
1144 * It's not safe for direct compaction to call lock_page.
1145 * For example, during page readahead pages are added locked
1146 * to the LRU. Later, when the IO completes the pages are
1147 * marked uptodate and unlocked. However, the queueing
1148 * could be merging multiple pages for one bio (e.g.
d4388340 1149 * mpage_readahead). If an allocation happens for the
3e7d3449
MG
1150 * second or third page, the process can end up locking
1151 * the same page twice and deadlocking. Rather than
1152 * trying to be clever about what pages can be locked,
1153 * avoid the use of lock_page for direct compaction
1154 * altogether.
1155 */
1156 if (current->flags & PF_MEMALLOC)
0dabec93 1157 goto out;
3e7d3449 1158
682a71a1 1159 folio_lock(src);
e24f0b8f 1160 }
ebe75e47 1161 locked = true;
e24f0b8f 1162
682a71a1 1163 if (folio_test_writeback(src)) {
11bc82d6 1164 /*
fed5b64a 1165 * Only in the case of a full synchronous migration is it
a6bc32b8
MG
1166 * necessary to wait for PageWriteback. In the async case,
1167 * the retry loop is too short and in the sync-light case,
1168 * the overhead of stalling is too much
11bc82d6 1169 */
2916ecc0
JG
1170 switch (mode) {
1171 case MIGRATE_SYNC:
1172 case MIGRATE_SYNC_NO_COPY:
1173 break;
1174 default:
11bc82d6 1175 rc = -EBUSY;
ebe75e47 1176 goto out;
11bc82d6 1177 }
682a71a1 1178 folio_wait_writeback(src);
e24f0b8f 1179 }
03f15c86 1180
e24f0b8f 1181 /*
682a71a1
MWO
1182 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1183 * we cannot notice that anon_vma is freed while we migrate a page.
1ce82b69 1184 * This get_anon_vma() delays freeing anon_vma pointer until the end
dc386d4d 1185 * of migration. File cache pages are no problem because of page_lock()
989f89c5
KH
1186 * File Caches may use write_page() or lock_page() in migration, then,
1187 * just care Anon page here.
03f15c86 1188 *
29eea9b5 1189 * Only folio_get_anon_vma() understands the subtleties of
03f15c86
HD
1190 * getting a hold on an anon_vma from outside one of its mms.
1191 * But if we cannot get anon_vma, then we won't need it anyway,
1192 * because that implies that the anon page is no longer mapped
1193 * (and cannot be remapped so long as we hold the page lock).
dc386d4d 1194 */
682a71a1 1195 if (folio_test_anon(src) && !folio_test_ksm(src))
29eea9b5 1196 anon_vma = folio_get_anon_vma(src);
62e1c553 1197
7db7671f
HD
1198 /*
1199 * Block others from accessing the new page when we get around to
1200 * establishing additional references. We are usually the only one
682a71a1
MWO
1201 * holding a reference to dst at this point. We used to have a BUG
1202 * here if folio_trylock(dst) fails, but would like to allow for
1203 * cases where there might be a race with the previous use of dst.
7db7671f
HD
1204 * This is much like races on refcount of oldpage: just don't BUG().
1205 */
682a71a1 1206 if (unlikely(!folio_trylock(dst)))
ebe75e47
HY
1207 goto out;
1208 dst_locked = true;
7db7671f 1209
bda807d4 1210 if (unlikely(!is_lru)) {
64c8902e
HY
1211 __migrate_folio_record(dst, page_was_mapped, anon_vma);
1212 return MIGRATEPAGE_UNMAP;
bda807d4
MK
1213 }
1214
dc386d4d 1215 /*
62e1c553
SL
1216 * Corner case handling:
1217 * 1. When a new swap-cache page is read into, it is added to the LRU
1218 * and treated as swapcache but it has no rmap yet.
682a71a1 1219 * Calling try_to_unmap() against a src->mapping==NULL page will
62e1c553 1220 * trigger a BUG. So handle it here.
d12b8951 1221 * 2. An orphaned page (see truncate_cleanup_page) might have
62e1c553
SL
1222 * fs-private metadata. The page can be picked up due to memory
1223 * offlining. Everywhere else except page reclaim, the page is
1224 * invisible to the vm, so the page can not be migrated. So try to
1225 * free the metadata, so the page can be freed.
e24f0b8f 1226 */
682a71a1
MWO
1227 if (!src->mapping) {
1228 if (folio_test_private(src)) {
1229 try_to_free_buffers(src);
ebe75e47 1230 goto out;
62e1c553 1231 }
682a71a1 1232 } else if (folio_mapped(src)) {
7db7671f 1233 /* Establish migration ptes */
682a71a1
MWO
1234 VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1235 !folio_test_ksm(src) && !anon_vma, src);
fb3592c4 1236 try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
64c8902e 1237 page_was_mapped = 1;
2ebba6b7 1238 }
dc386d4d 1239
64c8902e
HY
1240 if (!folio_mapped(src)) {
1241 __migrate_folio_record(dst, page_was_mapped, anon_vma);
1242 return MIGRATEPAGE_UNMAP;
1243 }
1244
64c8902e 1245out:
80562ba0
HY
1246 /*
1247 * A folio that has not been unmapped will be restored to
1248 * right list unless we want to retry.
1249 */
fb3592c4 1250 if (rc == -EAGAIN)
ebe75e47 1251 ret = NULL;
80562ba0 1252
ebe75e47
HY
1253 migrate_folio_undo_src(src, page_was_mapped, anon_vma, locked, ret);
1254 migrate_folio_undo_dst(dst, dst_locked, put_new_page, private);
80562ba0
HY
1255
1256 return rc;
1257}
1258
ebe75e47
HY
1259/* Migrate the folio to the newly allocated folio in dst. */
1260static int migrate_folio_move(free_page_t put_new_page, unsigned long private,
1261 struct folio *src, struct folio *dst,
1262 enum migrate_mode mode, enum migrate_reason reason,
1263 struct list_head *ret)
64c8902e
HY
1264{
1265 int rc;
1266 int page_was_mapped = 0;
1267 struct anon_vma *anon_vma = NULL;
1268 bool is_lru = !__PageMovable(&src->page);
5dfab109 1269 struct list_head *prev;
64c8902e
HY
1270
1271 __migrate_folio_extract(dst, &page_was_mapped, &anon_vma);
5dfab109
HY
1272 prev = dst->lru.prev;
1273 list_del(&dst->lru);
64c8902e
HY
1274
1275 rc = move_to_new_folio(dst, src, mode);
ebe75e47
HY
1276 if (rc)
1277 goto out;
5dfab109 1278
64c8902e
HY
1279 if (unlikely(!is_lru))
1280 goto out_unlock_both;
e24f0b8f 1281
c3096e67 1282 /*
682a71a1 1283 * When successful, push dst to LRU immediately: so that if it
c3096e67 1284 * turns out to be an mlocked page, remove_migration_ptes() will
682a71a1 1285 * automatically build up the correct dst->mlock_count for it.
c3096e67
HD
1286 *
1287 * We would like to do something similar for the old page, when
1288 * unsuccessful, and other cases when a page has been temporarily
1289 * isolated from the unevictable LRU: but this case is the easiest.
1290 */
ebe75e47
HY
1291 folio_add_lru(dst);
1292 if (page_was_mapped)
1293 lru_add_drain();
c3096e67 1294
5c3f9a67 1295 if (page_was_mapped)
ebe75e47 1296 remove_migration_ptes(src, dst, false);
3f6c8272 1297
7db7671f 1298out_unlock_both:
682a71a1 1299 folio_unlock(dst);
ebe75e47 1300 set_page_owner_migrate_reason(&dst->page, reason);
c6c919eb 1301 /*
682a71a1 1302 * If migration is successful, decrease refcount of dst,
c6c919eb 1303 * which will not free the page because new page owner increased
c3096e67 1304 * refcounter.
c6c919eb 1305 */
ebe75e47 1306 folio_put(dst);
c6c919eb 1307
dd4ae78a 1308 /*
ebe75e47
HY
1309 * A folio that has been migrated has all references removed
1310 * and will be freed.
dd4ae78a 1311 */
ebe75e47
HY
1312 list_del(&src->lru);
1313 /* Drop an anon_vma reference if we took one */
1314 if (anon_vma)
1315 put_anon_vma(anon_vma);
1316 folio_unlock(src);
1317 migrate_folio_done(src, reason);
bf6bddf1 1318
ebe75e47 1319 return rc;
0dabec93 1320out:
dd4ae78a 1321 /*
ebe75e47
HY
1322 * A folio that has not been migrated will be restored to
1323 * right list unless we want to retry.
dd4ae78a 1324 */
ebe75e47
HY
1325 if (rc == -EAGAIN) {
1326 list_add(&dst->lru, prev);
1327 __migrate_folio_record(dst, page_was_mapped, anon_vma);
1328 return rc;
e24f0b8f 1329 }
68711a74 1330
ebe75e47
HY
1331 migrate_folio_undo_src(src, page_was_mapped, anon_vma, true, ret);
1332 migrate_folio_undo_dst(dst, true, put_new_page, private);
1333
e24f0b8f
CL
1334 return rc;
1335}
1336
290408d4
NH
1337/*
1338 * Counterpart of unmap_and_move_page() for hugepage migration.
1339 *
1340 * This function doesn't wait the completion of hugepage I/O
1341 * because there is no race between I/O and migration for hugepage.
1342 * Note that currently hugepage I/O occurs only in direct I/O
1343 * where no lock is held and PG_writeback is irrelevant,
1344 * and writeback status of all subpages are counted in the reference
1345 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1346 * under direct I/O, the reference of the head page is 512 and a bit more.)
1347 * This means that when we try to migrate hugepage whose subpages are
1348 * doing direct I/O, some references remain after try_to_unmap() and
1349 * hugepage migration fails without data corruption.
1350 *
1351 * There is also no race when direct I/O is issued on the page under migration,
1352 * because then pte is replaced with migration swap entry and direct I/O code
1353 * will wait in the page fault for migration to complete.
1354 */
1355static int unmap_and_move_huge_page(new_page_t get_new_page,
68711a74
DR
1356 free_page_t put_new_page, unsigned long private,
1357 struct page *hpage, int force,
dd4ae78a
YS
1358 enum migrate_mode mode, int reason,
1359 struct list_head *ret)
290408d4 1360{
4eecb8b9 1361 struct folio *dst, *src = page_folio(hpage);
2def7424 1362 int rc = -EAGAIN;
2ebba6b7 1363 int page_was_mapped = 0;
32665f2b 1364 struct page *new_hpage;
290408d4 1365 struct anon_vma *anon_vma = NULL;
c0d0381a 1366 struct address_space *mapping = NULL;
290408d4 1367
c33db292 1368 if (folio_ref_count(src) == 1) {
71a64f61 1369 /* page was freed from under us. So we are done. */
ea8e72f4 1370 folio_putback_active_hugetlb(src);
71a64f61
MS
1371 return MIGRATEPAGE_SUCCESS;
1372 }
1373
666feb21 1374 new_hpage = get_new_page(hpage, private);
290408d4
NH
1375 if (!new_hpage)
1376 return -ENOMEM;
4eecb8b9 1377 dst = page_folio(new_hpage);
290408d4 1378
c33db292 1379 if (!folio_trylock(src)) {
2916ecc0 1380 if (!force)
290408d4 1381 goto out;
2916ecc0
JG
1382 switch (mode) {
1383 case MIGRATE_SYNC:
1384 case MIGRATE_SYNC_NO_COPY:
1385 break;
1386 default:
1387 goto out;
1388 }
c33db292 1389 folio_lock(src);
290408d4
NH
1390 }
1391
cb6acd01
MK
1392 /*
1393 * Check for pages which are in the process of being freed. Without
c33db292 1394 * folio_mapping() set, hugetlbfs specific move page routine will not
cb6acd01
MK
1395 * be called and we could leak usage counts for subpools.
1396 */
345c62d1 1397 if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
cb6acd01
MK
1398 rc = -EBUSY;
1399 goto out_unlock;
1400 }
1401
c33db292 1402 if (folio_test_anon(src))
29eea9b5 1403 anon_vma = folio_get_anon_vma(src);
290408d4 1404
c33db292 1405 if (unlikely(!folio_trylock(dst)))
7db7671f
HD
1406 goto put_anon;
1407
c33db292 1408 if (folio_mapped(src)) {
a98a2f0c 1409 enum ttu_flags ttu = 0;
336bf30e 1410
c33db292 1411 if (!folio_test_anon(src)) {
336bf30e
MK
1412 /*
1413 * In shared mappings, try_to_unmap could potentially
1414 * call huge_pmd_unshare. Because of this, take
1415 * semaphore in write mode here and set TTU_RMAP_LOCKED
1416 * to let lower levels know we have taken the lock.
1417 */
1418 mapping = hugetlb_page_mapping_lock_write(hpage);
1419 if (unlikely(!mapping))
1420 goto unlock_put_anon;
1421
5202978b 1422 ttu = TTU_RMAP_LOCKED;
336bf30e 1423 }
c0d0381a 1424
4b8554c5 1425 try_to_migrate(src, ttu);
2ebba6b7 1426 page_was_mapped = 1;
336bf30e 1427
5202978b 1428 if (ttu & TTU_RMAP_LOCKED)
336bf30e 1429 i_mmap_unlock_write(mapping);
2ebba6b7 1430 }
290408d4 1431
c33db292 1432 if (!folio_mapped(src))
e7e3ffeb 1433 rc = move_to_new_folio(dst, src, mode);
290408d4 1434
336bf30e 1435 if (page_was_mapped)
4eecb8b9
MWO
1436 remove_migration_ptes(src,
1437 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
290408d4 1438
c0d0381a 1439unlock_put_anon:
c33db292 1440 folio_unlock(dst);
7db7671f
HD
1441
1442put_anon:
fd4a4663 1443 if (anon_vma)
9e60109f 1444 put_anon_vma(anon_vma);
8e6ac7fa 1445
2def7424 1446 if (rc == MIGRATEPAGE_SUCCESS) {
345c62d1 1447 move_hugetlb_state(src, dst, reason);
2def7424
HD
1448 put_new_page = NULL;
1449 }
8e6ac7fa 1450
cb6acd01 1451out_unlock:
c33db292 1452 folio_unlock(src);
09761333 1453out:
dd4ae78a 1454 if (rc == MIGRATEPAGE_SUCCESS)
ea8e72f4 1455 folio_putback_active_hugetlb(src);
a04840c6 1456 else if (rc != -EAGAIN)
c33db292 1457 list_move_tail(&src->lru, ret);
68711a74
DR
1458
1459 /*
1460 * If migration was not successful and there's a freeing callback, use
1461 * it. Otherwise, put_page() will drop the reference grabbed during
1462 * isolation.
1463 */
2def7424 1464 if (put_new_page)
68711a74
DR
1465 put_new_page(new_hpage, private);
1466 else
ea8e72f4 1467 folio_putback_active_hugetlb(dst);
68711a74 1468
290408d4
NH
1469 return rc;
1470}
1471
eaec4e63 1472static inline int try_split_folio(struct folio *folio, struct list_head *split_folios)
d532e2e5 1473{
9c62ff00 1474 int rc;
d532e2e5 1475
eaec4e63
HY
1476 folio_lock(folio);
1477 rc = split_folio_to_list(folio, split_folios);
1478 folio_unlock(folio);
e6fa8a79 1479 if (!rc)
eaec4e63 1480 list_move_tail(&folio->lru, split_folios);
d532e2e5
YS
1481
1482 return rc;
1483}
1484
42012e04
HY
1485#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1486#define NR_MAX_BATCHED_MIGRATION HPAGE_PMD_NR
1487#else
1488#define NR_MAX_BATCHED_MIGRATION 512
1489#endif
e5bfff8b 1490#define NR_MAX_MIGRATE_PAGES_RETRY 10
2ef7dbb2
HY
1491#define NR_MAX_MIGRATE_ASYNC_RETRY 3
1492#define NR_MAX_MIGRATE_SYNC_RETRY \
1493 (NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
e5bfff8b 1494
5b855937
HY
1495struct migrate_pages_stats {
1496 int nr_succeeded; /* Normal and large folios migrated successfully, in
1497 units of base pages */
1498 int nr_failed_pages; /* Normal and large folios failed to be migrated, in
1499 units of base pages. Untried folios aren't counted */
1500 int nr_thp_succeeded; /* THP migrated successfully */
1501 int nr_thp_failed; /* THP failed to be migrated */
1502 int nr_thp_split; /* THP split before migrating */
1503};
1504
b20a3503 1505/*
e5bfff8b
HY
1506 * Returns the number of hugetlb folios that were not migrated, or an error code
1507 * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
1508 * any more because the list has become empty or no retryable hugetlb folios
1509 * exist any more. It is caller's responsibility to call putback_movable_pages()
1510 * only if ret != 0.
b20a3503 1511 */
e5bfff8b
HY
1512static int migrate_hugetlbs(struct list_head *from, new_page_t get_new_page,
1513 free_page_t put_new_page, unsigned long private,
1514 enum migrate_mode mode, int reason,
1515 struct migrate_pages_stats *stats,
1516 struct list_head *ret_folios)
b20a3503 1517{
e24f0b8f 1518 int retry = 1;
e5bfff8b
HY
1519 int nr_failed = 0;
1520 int nr_retry_pages = 0;
1521 int pass = 0;
1522 struct folio *folio, *folio2;
1523 int rc, nr_pages;
1524
1525 for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
1526 retry = 0;
1527 nr_retry_pages = 0;
1528
1529 list_for_each_entry_safe(folio, folio2, from, lru) {
1530 if (!folio_test_hugetlb(folio))
1531 continue;
1532
1533 nr_pages = folio_nr_pages(folio);
1534
1535 cond_resched();
1536
6f7d760e
HY
1537 /*
1538 * Migratability of hugepages depends on architectures and
1539 * their size. This check is necessary because some callers
1540 * of hugepage migration like soft offline and memory
1541 * hotremove don't walk through page tables or check whether
1542 * the hugepage is pmd-based or not before kicking migration.
1543 */
1544 if (!hugepage_migration_supported(folio_hstate(folio))) {
1545 nr_failed++;
1546 stats->nr_failed_pages += nr_pages;
1547 list_move_tail(&folio->lru, ret_folios);
1548 continue;
1549 }
1550
e5bfff8b
HY
1551 rc = unmap_and_move_huge_page(get_new_page,
1552 put_new_page, private,
1553 &folio->page, pass > 2, mode,
1554 reason, ret_folios);
1555 /*
1556 * The rules are:
1557 * Success: hugetlb folio will be put back
1558 * -EAGAIN: stay on the from list
1559 * -ENOMEM: stay on the from list
e5bfff8b
HY
1560 * Other errno: put on ret_folios list
1561 */
1562 switch(rc) {
e5bfff8b
HY
1563 case -ENOMEM:
1564 /*
1565 * When memory is low, don't bother to try to migrate
1566 * other folios, just exit.
1567 */
1568 stats->nr_failed_pages += nr_pages + nr_retry_pages;
1569 return -ENOMEM;
1570 case -EAGAIN:
1571 retry++;
1572 nr_retry_pages += nr_pages;
1573 break;
1574 case MIGRATEPAGE_SUCCESS:
1575 stats->nr_succeeded += nr_pages;
1576 break;
1577 default:
1578 /*
1579 * Permanent failure (-EBUSY, etc.):
1580 * unlike -EAGAIN case, the failed folio is
1581 * removed from migration folio list and not
1582 * retried in the next outer loop.
1583 */
1584 nr_failed++;
1585 stats->nr_failed_pages += nr_pages;
1586 break;
1587 }
1588 }
1589 }
1590 /*
1591 * nr_failed is number of hugetlb folios failed to be migrated. After
1592 * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
1593 * folios as failed.
1594 */
1595 nr_failed += retry;
1596 stats->nr_failed_pages += nr_retry_pages;
1597
1598 return nr_failed;
1599}
1600
5dfab109
HY
1601/*
1602 * migrate_pages_batch() first unmaps folios in the from list as many as
1603 * possible, then move the unmapped folios.
fb3592c4
HY
1604 *
1605 * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
1606 * lock or bit when we have locked more than one folio. Which may cause
1607 * deadlock (e.g., for loop device). So, if mode != MIGRATE_ASYNC, the
1608 * length of the from list must be <= 1.
5dfab109 1609 */
42012e04 1610static int migrate_pages_batch(struct list_head *from, new_page_t get_new_page,
68711a74 1611 free_page_t put_new_page, unsigned long private,
42012e04 1612 enum migrate_mode mode, int reason, struct list_head *ret_folios,
a21d2133
HY
1613 struct list_head *split_folios, struct migrate_pages_stats *stats,
1614 int nr_pass)
b20a3503 1615{
a21d2133 1616 int retry = 1;
eaec4e63 1617 int large_retry = 1;
1a5bae25 1618 int thp_retry = 1;
b20a3503 1619 int nr_failed = 0;
077309bc 1620 int nr_retry_pages = 0;
eaec4e63 1621 int nr_large_failed = 0;
b20a3503 1622 int pass = 0;
eaec4e63 1623 bool is_large = false;
1a5bae25 1624 bool is_thp = false;
5dfab109 1625 struct folio *folio, *folio2, *dst = NULL, *dst2;
a21d2133 1626 int rc, rc_saved = 0, nr_pages;
5dfab109
HY
1627 LIST_HEAD(unmap_folios);
1628 LIST_HEAD(dst_folios);
b0b515bf 1629 bool nosplit = (reason == MR_NUMA_MISPLACED);
e5bfff8b 1630
fb3592c4
HY
1631 VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
1632 !list_empty(from) && !list_is_singular(from));
a21d2133
HY
1633
1634 for (pass = 0; pass < nr_pass && (retry || large_retry); pass++) {
e24f0b8f 1635 retry = 0;
eaec4e63 1636 large_retry = 0;
1a5bae25 1637 thp_retry = 0;
077309bc 1638 nr_retry_pages = 0;
b20a3503 1639
eaec4e63 1640 list_for_each_entry_safe(folio, folio2, from, lru) {
1a5bae25 1641 /*
eaec4e63
HY
1642 * Large folio statistics is based on the source large
1643 * folio. Capture required information that might get
1644 * lost during migration.
1a5bae25 1645 */
e5bfff8b 1646 is_large = folio_test_large(folio);
eaec4e63
HY
1647 is_thp = is_large && folio_test_pmd_mappable(folio);
1648 nr_pages = folio_nr_pages(folio);
e5bfff8b 1649
e24f0b8f 1650 cond_resched();
2d1db3b1 1651
d532e2e5 1652 /*
eaec4e63 1653 * Large folio migration might be unsupported or
6f7d760e 1654 * the allocation might be failed so we should retry
eaec4e63
HY
1655 * on the same folio with the large folio split
1656 * to normal folios.
d532e2e5 1657 *
eaec4e63 1658 * Split folios are put in split_folios, and
e6fa8a79
HY
1659 * we will migrate them after the rest of the
1660 * list is processed.
d532e2e5 1661 */
6f7d760e
HY
1662 if (!thp_migration_supported() && is_thp) {
1663 nr_large_failed++;
1664 stats->nr_thp_failed++;
a21d2133 1665 if (!try_split_folio(folio, split_folios)) {
6f7d760e
HY
1666 stats->nr_thp_split++;
1667 continue;
f430893b 1668 }
6f7d760e
HY
1669 stats->nr_failed_pages += nr_pages;
1670 list_move_tail(&folio->lru, ret_folios);
1671 continue;
1672 }
f430893b 1673
64c8902e 1674 rc = migrate_folio_unmap(get_new_page, put_new_page, private,
2ef7dbb2 1675 folio, &dst, mode, reason, ret_folios);
dd4ae78a
YS
1676 /*
1677 * The rules are:
e5bfff8b 1678 * Success: folio will be freed
5dfab109
HY
1679 * Unmap: folio will be put on unmap_folios list,
1680 * dst folio put on dst_folios list
dd4ae78a
YS
1681 * -EAGAIN: stay on the from list
1682 * -ENOMEM: stay on the from list
42012e04 1683 * Other errno: put on ret_folios list
dd4ae78a 1684 */
e24f0b8f 1685 switch(rc) {
95a402c3 1686 case -ENOMEM:
94723aaf 1687 /*
d532e2e5 1688 * When memory is low, don't bother to try to migrate
5dfab109 1689 * other folios, move unmapped folios, then exit.
94723aaf 1690 */
eaec4e63
HY
1691 if (is_large) {
1692 nr_large_failed++;
42012e04 1693 stats->nr_thp_failed += is_thp;
eaec4e63 1694 /* Large folio NUMA faulting doesn't split to retry. */
fd4a7ac3 1695 if (!nosplit) {
a21d2133 1696 int ret = try_split_folio(folio, split_folios);
fd4a7ac3
BW
1697
1698 if (!ret) {
42012e04 1699 stats->nr_thp_split += is_thp;
fd4a7ac3
BW
1700 break;
1701 } else if (reason == MR_LONGTERM_PIN &&
1702 ret == -EAGAIN) {
1703 /*
eaec4e63
HY
1704 * Try again to split large folio to
1705 * mitigate the failure of longterm pinning.
fd4a7ac3 1706 */
eaec4e63
HY
1707 large_retry++;
1708 thp_retry += is_thp;
1709 nr_retry_pages += nr_pages;
851ae642
HY
1710 /* Undo duplicated failure counting. */
1711 nr_large_failed--;
1712 stats->nr_thp_failed -= is_thp;
fd4a7ac3
BW
1713 break;
1714 }
94723aaf 1715 }
a21d2133 1716 } else {
f430893b 1717 nr_failed++;
1a5bae25 1718 }
b5bade97 1719
42012e04 1720 stats->nr_failed_pages += nr_pages + nr_retry_pages;
fbed53b4 1721 /* nr_failed isn't updated for not used */
eaec4e63 1722 nr_large_failed += large_retry;
42012e04 1723 stats->nr_thp_failed += thp_retry;
5dfab109
HY
1724 rc_saved = rc;
1725 if (list_empty(&unmap_folios))
1726 goto out;
1727 else
1728 goto move;
e24f0b8f 1729 case -EAGAIN:
eaec4e63
HY
1730 if (is_large) {
1731 large_retry++;
1732 thp_retry += is_thp;
a21d2133 1733 } else {
f430893b 1734 retry++;
eaec4e63
HY
1735 }
1736 nr_retry_pages += nr_pages;
e24f0b8f 1737 break;
78bd5209 1738 case MIGRATEPAGE_SUCCESS:
42012e04
HY
1739 stats->nr_succeeded += nr_pages;
1740 stats->nr_thp_succeeded += is_thp;
e24f0b8f 1741 break;
5dfab109 1742 case MIGRATEPAGE_UNMAP:
5dfab109
HY
1743 list_move_tail(&folio->lru, &unmap_folios);
1744 list_add_tail(&dst->lru, &dst_folios);
e24f0b8f
CL
1745 break;
1746 default:
354a3363 1747 /*
d532e2e5 1748 * Permanent failure (-EBUSY, etc.):
eaec4e63
HY
1749 * unlike -EAGAIN case, the failed folio is
1750 * removed from migration folio list and not
354a3363
NH
1751 * retried in the next outer loop.
1752 */
eaec4e63
HY
1753 if (is_large) {
1754 nr_large_failed++;
42012e04 1755 stats->nr_thp_failed += is_thp;
a21d2133 1756 } else {
b5bade97 1757 nr_failed++;
eaec4e63 1758 }
f430893b 1759
42012e04 1760 stats->nr_failed_pages += nr_pages;
e24f0b8f 1761 break;
2d1db3b1 1762 }
b20a3503
CL
1763 }
1764 }
7047b5a4 1765 nr_failed += retry;
eaec4e63 1766 nr_large_failed += large_retry;
42012e04
HY
1767 stats->nr_thp_failed += thp_retry;
1768 stats->nr_failed_pages += nr_retry_pages;
5dfab109 1769move:
7e12beb8
HY
1770 /* Flush TLBs for all unmapped folios */
1771 try_to_unmap_flush();
1772
5dfab109 1773 retry = 1;
a21d2133 1774 for (pass = 0; pass < nr_pass && (retry || large_retry); pass++) {
5dfab109
HY
1775 retry = 0;
1776 large_retry = 0;
1777 thp_retry = 0;
1778 nr_retry_pages = 0;
1779
1780 dst = list_first_entry(&dst_folios, struct folio, lru);
1781 dst2 = list_next_entry(dst, lru);
1782 list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1783 is_large = folio_test_large(folio);
1784 is_thp = is_large && folio_test_pmd_mappable(folio);
1785 nr_pages = folio_nr_pages(folio);
1786
1787 cond_resched();
1788
1789 rc = migrate_folio_move(put_new_page, private,
1790 folio, dst, mode,
1791 reason, ret_folios);
1792 /*
1793 * The rules are:
1794 * Success: folio will be freed
1795 * -EAGAIN: stay on the unmap_folios list
1796 * Other errno: put on ret_folios list
1797 */
1798 switch(rc) {
1799 case -EAGAIN:
1800 if (is_large) {
1801 large_retry++;
1802 thp_retry += is_thp;
a21d2133 1803 } else {
5dfab109
HY
1804 retry++;
1805 }
1806 nr_retry_pages += nr_pages;
1807 break;
1808 case MIGRATEPAGE_SUCCESS:
1809 stats->nr_succeeded += nr_pages;
1810 stats->nr_thp_succeeded += is_thp;
1811 break;
1812 default:
1813 if (is_large) {
1814 nr_large_failed++;
1815 stats->nr_thp_failed += is_thp;
a21d2133 1816 } else {
b5bade97 1817 nr_failed++;
eaec4e63 1818 }
f430893b 1819
5dfab109 1820 stats->nr_failed_pages += nr_pages;
e24f0b8f 1821 break;
2d1db3b1 1822 }
5dfab109
HY
1823 dst = dst2;
1824 dst2 = list_next_entry(dst, lru);
b20a3503
CL
1825 }
1826 }
7047b5a4 1827 nr_failed += retry;
eaec4e63 1828 nr_large_failed += large_retry;
5dfab109
HY
1829 stats->nr_thp_failed += thp_retry;
1830 stats->nr_failed_pages += nr_retry_pages;
1831
1832 if (rc_saved)
1833 rc = rc_saved;
1834 else
1835 rc = nr_failed + nr_large_failed;
1836out:
1837 /* Cleanup remaining folios */
1838 dst = list_first_entry(&dst_folios, struct folio, lru);
1839 dst2 = list_next_entry(dst, lru);
1840 list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1841 int page_was_mapped = 0;
1842 struct anon_vma *anon_vma = NULL;
1843
1844 __migrate_folio_extract(dst, &page_was_mapped, &anon_vma);
1845 migrate_folio_undo_src(folio, page_was_mapped, anon_vma,
ebe75e47 1846 true, ret_folios);
5dfab109 1847 list_del(&dst->lru);
ebe75e47 1848 migrate_folio_undo_dst(dst, true, put_new_page, private);
5dfab109
HY
1849 dst = dst2;
1850 dst2 = list_next_entry(dst, lru);
1851 }
1852
42012e04
HY
1853 return rc;
1854}
1855
2ef7dbb2
HY
1856static int migrate_pages_sync(struct list_head *from, new_page_t get_new_page,
1857 free_page_t put_new_page, unsigned long private,
1858 enum migrate_mode mode, int reason, struct list_head *ret_folios,
1859 struct list_head *split_folios, struct migrate_pages_stats *stats)
1860{
1861 int rc, nr_failed = 0;
1862 LIST_HEAD(folios);
1863 struct migrate_pages_stats astats;
1864
1865 memset(&astats, 0, sizeof(astats));
1866 /* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
1867 rc = migrate_pages_batch(from, get_new_page, put_new_page, private, MIGRATE_ASYNC,
1868 reason, &folios, split_folios, &astats,
1869 NR_MAX_MIGRATE_ASYNC_RETRY);
1870 stats->nr_succeeded += astats.nr_succeeded;
1871 stats->nr_thp_succeeded += astats.nr_thp_succeeded;
1872 stats->nr_thp_split += astats.nr_thp_split;
1873 if (rc < 0) {
1874 stats->nr_failed_pages += astats.nr_failed_pages;
1875 stats->nr_thp_failed += astats.nr_thp_failed;
1876 list_splice_tail(&folios, ret_folios);
1877 return rc;
1878 }
1879 stats->nr_thp_failed += astats.nr_thp_split;
1880 nr_failed += astats.nr_thp_split;
1881 /*
1882 * Fall back to migrate all failed folios one by one synchronously. All
1883 * failed folios except split THPs will be retried, so their failure
1884 * isn't counted
1885 */
1886 list_splice_tail_init(&folios, from);
1887 while (!list_empty(from)) {
1888 list_move(from->next, &folios);
1889 rc = migrate_pages_batch(&folios, get_new_page, put_new_page,
1890 private, mode, reason, ret_folios,
1891 split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
1892 list_splice_tail_init(&folios, ret_folios);
1893 if (rc < 0)
1894 return rc;
1895 nr_failed += rc;
1896 }
1897
1898 return nr_failed;
1899}
1900
42012e04
HY
1901/*
1902 * migrate_pages - migrate the folios specified in a list, to the free folios
1903 * supplied as the target for the page migration
1904 *
1905 * @from: The list of folios to be migrated.
1906 * @get_new_page: The function used to allocate free folios to be used
1907 * as the target of the folio migration.
1908 * @put_new_page: The function used to free target folios if migration
1909 * fails, or NULL if no special handling is necessary.
1910 * @private: Private data to be passed on to get_new_page()
1911 * @mode: The migration mode that specifies the constraints for
1912 * folio migration, if any.
1913 * @reason: The reason for folio migration.
1914 * @ret_succeeded: Set to the number of folios migrated successfully if
1915 * the caller passes a non-NULL pointer.
1916 *
1917 * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
1918 * are movable any more because the list has become empty or no retryable folios
1919 * exist any more. It is caller's responsibility to call putback_movable_pages()
1920 * only if ret != 0.
1921 *
1922 * Returns the number of {normal folio, large folio, hugetlb} that were not
1923 * migrated, or an error code. The number of large folio splits will be
1924 * considered as the number of non-migrated large folio, no matter how many
1925 * split folios of the large folio are migrated successfully.
1926 */
1927int migrate_pages(struct list_head *from, new_page_t get_new_page,
1928 free_page_t put_new_page, unsigned long private,
1929 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1930{
1931 int rc, rc_gather;
2ef7dbb2 1932 int nr_pages;
42012e04
HY
1933 struct folio *folio, *folio2;
1934 LIST_HEAD(folios);
1935 LIST_HEAD(ret_folios);
a21d2133 1936 LIST_HEAD(split_folios);
42012e04
HY
1937 struct migrate_pages_stats stats;
1938
1939 trace_mm_migrate_pages_start(mode, reason);
1940
1941 memset(&stats, 0, sizeof(stats));
1942
1943 rc_gather = migrate_hugetlbs(from, get_new_page, put_new_page, private,
1944 mode, reason, &stats, &ret_folios);
1945 if (rc_gather < 0)
1946 goto out;
fb3592c4 1947
42012e04
HY
1948again:
1949 nr_pages = 0;
1950 list_for_each_entry_safe(folio, folio2, from, lru) {
1951 /* Retried hugetlb folios will be kept in list */
1952 if (folio_test_hugetlb(folio)) {
1953 list_move_tail(&folio->lru, &ret_folios);
1954 continue;
1955 }
1956
1957 nr_pages += folio_nr_pages(folio);
2ef7dbb2 1958 if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
42012e04
HY
1959 break;
1960 }
2ef7dbb2 1961 if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
fb3592c4 1962 list_cut_before(&folios, from, &folio2->lru);
42012e04
HY
1963 else
1964 list_splice_init(from, &folios);
2ef7dbb2
HY
1965 if (mode == MIGRATE_ASYNC)
1966 rc = migrate_pages_batch(&folios, get_new_page, put_new_page, private,
1967 mode, reason, &ret_folios, &split_folios, &stats,
1968 NR_MAX_MIGRATE_PAGES_RETRY);
1969 else
1970 rc = migrate_pages_sync(&folios, get_new_page, put_new_page, private,
1971 mode, reason, &ret_folios, &split_folios, &stats);
42012e04
HY
1972 list_splice_tail_init(&folios, &ret_folios);
1973 if (rc < 0) {
1974 rc_gather = rc;
a21d2133 1975 list_splice_tail(&split_folios, &ret_folios);
42012e04
HY
1976 goto out;
1977 }
a21d2133
HY
1978 if (!list_empty(&split_folios)) {
1979 /*
1980 * Failure isn't counted since all split folios of a large folio
1981 * is counted as 1 failure already. And, we only try to migrate
1982 * with minimal effort, force MIGRATE_ASYNC mode and retry once.
1983 */
1984 migrate_pages_batch(&split_folios, get_new_page, put_new_page, private,
1985 MIGRATE_ASYNC, reason, &ret_folios, NULL, &stats, 1);
1986 list_splice_tail_init(&split_folios, &ret_folios);
1987 }
42012e04
HY
1988 rc_gather += rc;
1989 if (!list_empty(from))
1990 goto again;
95a402c3 1991out:
dd4ae78a 1992 /*
eaec4e63 1993 * Put the permanent failure folio back to migration list, they
dd4ae78a
YS
1994 * will be put back to the right list by the caller.
1995 */
eaec4e63 1996 list_splice(&ret_folios, from);
dd4ae78a 1997
03e5f82e 1998 /*
eaec4e63
HY
1999 * Return 0 in case all split folios of fail-to-migrate large folios
2000 * are migrated successfully.
03e5f82e
BW
2001 */
2002 if (list_empty(from))
42012e04 2003 rc_gather = 0;
03e5f82e 2004
5b855937
HY
2005 count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
2006 count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
2007 count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
2008 count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
2009 count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
2010 trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
2011 stats.nr_thp_succeeded, stats.nr_thp_failed,
2012 stats.nr_thp_split, mode, reason);
7b2a2d4a 2013
5ac95884 2014 if (ret_succeeded)
5b855937 2015 *ret_succeeded = stats.nr_succeeded;
5ac95884 2016
42012e04 2017 return rc_gather;
b20a3503 2018}
95a402c3 2019
19fc7bed 2020struct page *alloc_migration_target(struct page *page, unsigned long private)
b4b38223 2021{
ffe06786 2022 struct folio *folio = page_folio(page);
19fc7bed
JK
2023 struct migration_target_control *mtc;
2024 gfp_t gfp_mask;
b4b38223 2025 unsigned int order = 0;
e37d3e83 2026 struct folio *hugetlb_folio = NULL;
ffe06786 2027 struct folio *new_folio = NULL;
19fc7bed
JK
2028 int nid;
2029 int zidx;
2030
2031 mtc = (struct migration_target_control *)private;
2032 gfp_mask = mtc->gfp_mask;
2033 nid = mtc->nid;
2034 if (nid == NUMA_NO_NODE)
ffe06786 2035 nid = folio_nid(folio);
b4b38223 2036
ffe06786 2037 if (folio_test_hugetlb(folio)) {
e51da3a9 2038 struct hstate *h = folio_hstate(folio);
d92bbc27 2039
19fc7bed 2040 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
e37d3e83
SK
2041 hugetlb_folio = alloc_hugetlb_folio_nodemask(h, nid,
2042 mtc->nmask, gfp_mask);
2043 return &hugetlb_folio->page;
d92bbc27 2044 }
b4b38223 2045
ffe06786 2046 if (folio_test_large(folio)) {
9933a0c8
JK
2047 /*
2048 * clear __GFP_RECLAIM to make the migration callback
2049 * consistent with regular THP allocations.
2050 */
2051 gfp_mask &= ~__GFP_RECLAIM;
b4b38223 2052 gfp_mask |= GFP_TRANSHUGE;
ffe06786 2053 order = folio_order(folio);
b4b38223 2054 }
ffe06786 2055 zidx = zone_idx(folio_zone(folio));
19fc7bed 2056 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
b4b38223
JK
2057 gfp_mask |= __GFP_HIGHMEM;
2058
ffe06786 2059 new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
b4b38223 2060
ffe06786 2061 return &new_folio->page;
b4b38223
JK
2062}
2063
742755a1 2064#ifdef CONFIG_NUMA
742755a1 2065
a49bd4d7 2066static int store_status(int __user *status, int start, int value, int nr)
742755a1 2067{
a49bd4d7
MH
2068 while (nr-- > 0) {
2069 if (put_user(value, status + start))
2070 return -EFAULT;
2071 start++;
2072 }
2073
2074 return 0;
2075}
2076
2077static int do_move_pages_to_node(struct mm_struct *mm,
2078 struct list_head *pagelist, int node)
2079{
2080 int err;
a0976311
JK
2081 struct migration_target_control mtc = {
2082 .nid = node,
2083 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
2084 };
a49bd4d7 2085
a0976311 2086 err = migrate_pages(pagelist, alloc_migration_target, NULL,
5ac95884 2087 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
a49bd4d7
MH
2088 if (err)
2089 putback_movable_pages(pagelist);
2090 return err;
742755a1
CL
2091}
2092
2093/*
a49bd4d7
MH
2094 * Resolves the given address to a struct page, isolates it from the LRU and
2095 * puts it to the given pagelist.
e0153fc2
YS
2096 * Returns:
2097 * errno - if the page cannot be found/isolated
2098 * 0 - when it doesn't have to be migrated because it is already on the
2099 * target node
2100 * 1 - when it has been queued
742755a1 2101 */
428e106a 2102static int add_page_for_migration(struct mm_struct *mm, const void __user *p,
a49bd4d7 2103 int node, struct list_head *pagelist, bool migrate_all)
742755a1 2104{
a49bd4d7 2105 struct vm_area_struct *vma;
428e106a 2106 unsigned long addr;
a49bd4d7 2107 struct page *page;
742755a1 2108 int err;
9747b9e9 2109 bool isolated;
742755a1 2110
d8ed45c5 2111 mmap_read_lock(mm);
428e106a
KS
2112 addr = (unsigned long)untagged_addr_remote(mm, p);
2113
a49bd4d7 2114 err = -EFAULT;
cb1c37b1
ML
2115 vma = vma_lookup(mm, addr);
2116 if (!vma || !vma_migratable(vma))
a49bd4d7 2117 goto out;
742755a1 2118
a49bd4d7 2119 /* FOLL_DUMP to ignore special (like zero) pages */
87d2762e 2120 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
89f5b7da 2121
a49bd4d7
MH
2122 err = PTR_ERR(page);
2123 if (IS_ERR(page))
2124 goto out;
89f5b7da 2125
a49bd4d7 2126 err = -ENOENT;
f7091ed6 2127 if (!page)
a49bd4d7 2128 goto out;
742755a1 2129
f7091ed6
HW
2130 if (is_zone_device_page(page))
2131 goto out_putpage;
2132
a49bd4d7
MH
2133 err = 0;
2134 if (page_to_nid(page) == node)
2135 goto out_putpage;
742755a1 2136
a49bd4d7
MH
2137 err = -EACCES;
2138 if (page_mapcount(page) > 1 && !migrate_all)
2139 goto out_putpage;
742755a1 2140
a49bd4d7
MH
2141 if (PageHuge(page)) {
2142 if (PageHead(page)) {
9747b9e9
BW
2143 isolated = isolate_hugetlb(page_folio(page), pagelist);
2144 err = isolated ? 1 : -EBUSY;
e632a938 2145 }
a49bd4d7
MH
2146 } else {
2147 struct page *head;
e632a938 2148
e8db67eb 2149 head = compound_head(page);
f7f9c00d
BW
2150 isolated = isolate_lru_page(head);
2151 if (!isolated) {
2152 err = -EBUSY;
a49bd4d7 2153 goto out_putpage;
f7f9c00d 2154 }
742755a1 2155
e0153fc2 2156 err = 1;
a49bd4d7
MH
2157 list_add_tail(&head->lru, pagelist);
2158 mod_node_page_state(page_pgdat(head),
9de4f22a 2159 NR_ISOLATED_ANON + page_is_file_lru(head),
6c357848 2160 thp_nr_pages(head));
a49bd4d7
MH
2161 }
2162out_putpage:
2163 /*
2164 * Either remove the duplicate refcount from
2165 * isolate_lru_page() or drop the page ref if it was
2166 * not isolated.
2167 */
2168 put_page(page);
2169out:
d8ed45c5 2170 mmap_read_unlock(mm);
742755a1
CL
2171 return err;
2172}
2173
7ca8783a
WY
2174static int move_pages_and_store_status(struct mm_struct *mm, int node,
2175 struct list_head *pagelist, int __user *status,
2176 int start, int i, unsigned long nr_pages)
2177{
2178 int err;
2179
5d7ae891
WY
2180 if (list_empty(pagelist))
2181 return 0;
2182
7ca8783a
WY
2183 err = do_move_pages_to_node(mm, pagelist, node);
2184 if (err) {
2185 /*
2186 * Positive err means the number of failed
2187 * pages to migrate. Since we are going to
2188 * abort and return the number of non-migrated
ab9dd4f8 2189 * pages, so need to include the rest of the
7ca8783a
WY
2190 * nr_pages that have not been attempted as
2191 * well.
2192 */
2193 if (err > 0)
a7504ed1 2194 err += nr_pages - i;
7ca8783a
WY
2195 return err;
2196 }
2197 return store_status(status, start, node, i - start);
2198}
2199
5e9a0f02
BG
2200/*
2201 * Migrate an array of page address onto an array of nodes and fill
2202 * the corresponding array of status.
2203 */
3268c63e 2204static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
5e9a0f02
BG
2205 unsigned long nr_pages,
2206 const void __user * __user *pages,
2207 const int __user *nodes,
2208 int __user *status, int flags)
2209{
a49bd4d7
MH
2210 int current_node = NUMA_NO_NODE;
2211 LIST_HEAD(pagelist);
2212 int start, i;
2213 int err = 0, err1;
35282a2d 2214
361a2a22 2215 lru_cache_disable();
35282a2d 2216
a49bd4d7
MH
2217 for (i = start = 0; i < nr_pages; i++) {
2218 const void __user *p;
a49bd4d7 2219 int node;
3140a227 2220
a49bd4d7
MH
2221 err = -EFAULT;
2222 if (get_user(p, pages + i))
2223 goto out_flush;
2224 if (get_user(node, nodes + i))
2225 goto out_flush;
a49bd4d7
MH
2226
2227 err = -ENODEV;
2228 if (node < 0 || node >= MAX_NUMNODES)
2229 goto out_flush;
2230 if (!node_state(node, N_MEMORY))
2231 goto out_flush;
5e9a0f02 2232
a49bd4d7
MH
2233 err = -EACCES;
2234 if (!node_isset(node, task_nodes))
2235 goto out_flush;
2236
2237 if (current_node == NUMA_NO_NODE) {
2238 current_node = node;
2239 start = i;
2240 } else if (node != current_node) {
7ca8783a
WY
2241 err = move_pages_and_store_status(mm, current_node,
2242 &pagelist, status, start, i, nr_pages);
a49bd4d7
MH
2243 if (err)
2244 goto out;
2245 start = i;
2246 current_node = node;
3140a227
BG
2247 }
2248
a49bd4d7
MH
2249 /*
2250 * Errors in the page lookup or isolation are not fatal and we simply
2251 * report them via status
2252 */
428e106a
KS
2253 err = add_page_for_migration(mm, p, current_node, &pagelist,
2254 flags & MPOL_MF_MOVE_ALL);
e0153fc2 2255
d08221a0 2256 if (err > 0) {
e0153fc2
YS
2257 /* The page is successfully queued for migration */
2258 continue;
2259 }
3140a227 2260
65462462
JH
2261 /*
2262 * The move_pages() man page does not have an -EEXIST choice, so
2263 * use -EFAULT instead.
2264 */
2265 if (err == -EEXIST)
2266 err = -EFAULT;
2267
d08221a0
WY
2268 /*
2269 * If the page is already on the target node (!err), store the
2270 * node, otherwise, store the err.
2271 */
2272 err = store_status(status, i, err ? : current_node, 1);
a49bd4d7
MH
2273 if (err)
2274 goto out_flush;
5e9a0f02 2275
7ca8783a
WY
2276 err = move_pages_and_store_status(mm, current_node, &pagelist,
2277 status, start, i, nr_pages);
a7504ed1
HY
2278 if (err) {
2279 /* We have accounted for page i */
2280 if (err > 0)
2281 err--;
4afdacec 2282 goto out;
a7504ed1 2283 }
a49bd4d7 2284 current_node = NUMA_NO_NODE;
3140a227 2285 }
a49bd4d7
MH
2286out_flush:
2287 /* Make sure we do not overwrite the existing error */
7ca8783a
WY
2288 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
2289 status, start, i, nr_pages);
dfe9aa23 2290 if (err >= 0)
a49bd4d7 2291 err = err1;
5e9a0f02 2292out:
361a2a22 2293 lru_cache_enable();
5e9a0f02
BG
2294 return err;
2295}
2296
742755a1 2297/*
2f007e74 2298 * Determine the nodes of an array of pages and store it in an array of status.
742755a1 2299 */
80bba129
BG
2300static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
2301 const void __user **pages, int *status)
742755a1 2302{
2f007e74 2303 unsigned long i;
2f007e74 2304
d8ed45c5 2305 mmap_read_lock(mm);
742755a1 2306
2f007e74 2307 for (i = 0; i < nr_pages; i++) {
80bba129 2308 unsigned long addr = (unsigned long)(*pages);
742755a1
CL
2309 struct vm_area_struct *vma;
2310 struct page *page;
c095adbc 2311 int err = -EFAULT;
2f007e74 2312
059b8b48
LH
2313 vma = vma_lookup(mm, addr);
2314 if (!vma)
742755a1
CL
2315 goto set_status;
2316
d899844e 2317 /* FOLL_DUMP to ignore special (like zero) pages */
16fd6b31 2318 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
89f5b7da
LT
2319
2320 err = PTR_ERR(page);
2321 if (IS_ERR(page))
2322 goto set_status;
2323
f7091ed6
HW
2324 err = -ENOENT;
2325 if (!page)
2326 goto set_status;
2327
2328 if (!is_zone_device_page(page))
4cd61484 2329 err = page_to_nid(page);
f7091ed6 2330
16fd6b31 2331 put_page(page);
742755a1 2332set_status:
80bba129
BG
2333 *status = err;
2334
2335 pages++;
2336 status++;
2337 }
2338
d8ed45c5 2339 mmap_read_unlock(mm);
80bba129
BG
2340}
2341
5b1b561b
AB
2342static int get_compat_pages_array(const void __user *chunk_pages[],
2343 const void __user * __user *pages,
2344 unsigned long chunk_nr)
2345{
2346 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
2347 compat_uptr_t p;
2348 int i;
2349
2350 for (i = 0; i < chunk_nr; i++) {
2351 if (get_user(p, pages32 + i))
2352 return -EFAULT;
2353 chunk_pages[i] = compat_ptr(p);
2354 }
2355
2356 return 0;
2357}
2358
80bba129
BG
2359/*
2360 * Determine the nodes of a user array of pages and store it in
2361 * a user array of status.
2362 */
2363static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
2364 const void __user * __user *pages,
2365 int __user *status)
2366{
3eefb826 2367#define DO_PAGES_STAT_CHUNK_NR 16UL
80bba129
BG
2368 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
2369 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
80bba129 2370
87b8d1ad 2371 while (nr_pages) {
3eefb826 2372 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
87b8d1ad 2373
5b1b561b
AB
2374 if (in_compat_syscall()) {
2375 if (get_compat_pages_array(chunk_pages, pages,
2376 chunk_nr))
2377 break;
2378 } else {
2379 if (copy_from_user(chunk_pages, pages,
2380 chunk_nr * sizeof(*chunk_pages)))
2381 break;
2382 }
80bba129
BG
2383
2384 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
2385
87b8d1ad
PA
2386 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
2387 break;
742755a1 2388
87b8d1ad
PA
2389 pages += chunk_nr;
2390 status += chunk_nr;
2391 nr_pages -= chunk_nr;
2392 }
2393 return nr_pages ? -EFAULT : 0;
742755a1
CL
2394}
2395
4dc200ce 2396static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
742755a1 2397{
742755a1 2398 struct task_struct *task;
742755a1 2399 struct mm_struct *mm;
742755a1 2400
4dc200ce
ML
2401 /*
2402 * There is no need to check if current process has the right to modify
2403 * the specified process when they are same.
2404 */
2405 if (!pid) {
2406 mmget(current->mm);
2407 *mem_nodes = cpuset_mems_allowed(current);
2408 return current->mm;
2409 }
742755a1
CL
2410
2411 /* Find the mm_struct */
a879bf58 2412 rcu_read_lock();
4dc200ce 2413 task = find_task_by_vpid(pid);
742755a1 2414 if (!task) {
a879bf58 2415 rcu_read_unlock();
4dc200ce 2416 return ERR_PTR(-ESRCH);
742755a1 2417 }
3268c63e 2418 get_task_struct(task);
742755a1
CL
2419
2420 /*
2421 * Check if this process has the right to modify the specified
197e7e52 2422 * process. Use the regular "ptrace_may_access()" checks.
742755a1 2423 */
197e7e52 2424 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
c69e8d9c 2425 rcu_read_unlock();
4dc200ce 2426 mm = ERR_PTR(-EPERM);
5e9a0f02 2427 goto out;
742755a1 2428 }
c69e8d9c 2429 rcu_read_unlock();
742755a1 2430
4dc200ce
ML
2431 mm = ERR_PTR(security_task_movememory(task));
2432 if (IS_ERR(mm))
5e9a0f02 2433 goto out;
4dc200ce 2434 *mem_nodes = cpuset_mems_allowed(task);
3268c63e 2435 mm = get_task_mm(task);
4dc200ce 2436out:
3268c63e 2437 put_task_struct(task);
6e8b09ea 2438 if (!mm)
4dc200ce
ML
2439 mm = ERR_PTR(-EINVAL);
2440 return mm;
2441}
2442
2443/*
2444 * Move a list of pages in the address space of the currently executing
2445 * process.
2446 */
2447static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2448 const void __user * __user *pages,
2449 const int __user *nodes,
2450 int __user *status, int flags)
2451{
2452 struct mm_struct *mm;
2453 int err;
2454 nodemask_t task_nodes;
2455
2456 /* Check flags */
2457 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
6e8b09ea
SL
2458 return -EINVAL;
2459
4dc200ce
ML
2460 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2461 return -EPERM;
2462
2463 mm = find_mm_struct(pid, &task_nodes);
2464 if (IS_ERR(mm))
2465 return PTR_ERR(mm);
2466
6e8b09ea
SL
2467 if (nodes)
2468 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2469 nodes, status, flags);
2470 else
2471 err = do_pages_stat(mm, nr_pages, pages, status);
742755a1 2472
742755a1
CL
2473 mmput(mm);
2474 return err;
2475}
742755a1 2476
7addf443
DB
2477SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2478 const void __user * __user *, pages,
2479 const int __user *, nodes,
2480 int __user *, status, int, flags)
2481{
2482 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2483}
2484
7039e1db
PZ
2485#ifdef CONFIG_NUMA_BALANCING
2486/*
2487 * Returns true if this is a safe migration target node for misplaced NUMA
bc53008e 2488 * pages. Currently it only checks the watermarks which is crude.
7039e1db
PZ
2489 */
2490static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
3abef4e6 2491 unsigned long nr_migrate_pages)
7039e1db
PZ
2492{
2493 int z;
599d0c95 2494
7039e1db
PZ
2495 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2496 struct zone *zone = pgdat->node_zones + z;
2497
bc53008e 2498 if (!managed_zone(zone))
7039e1db
PZ
2499 continue;
2500
7039e1db
PZ
2501 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2502 if (!zone_watermark_ok(zone, 0,
2503 high_wmark_pages(zone) +
2504 nr_migrate_pages,
bfe9d006 2505 ZONE_MOVABLE, 0))
7039e1db
PZ
2506 continue;
2507 return true;
2508 }
2509 return false;
2510}
2511
2512static struct page *alloc_misplaced_dst_page(struct page *page,
666feb21 2513 unsigned long data)
7039e1db
PZ
2514{
2515 int nid = (int) data;
c185e494
MWO
2516 int order = compound_order(page);
2517 gfp_t gfp = __GFP_THISNODE;
2518 struct folio *new;
2519
2520 if (order > 0)
2521 gfp |= GFP_TRANSHUGE_LIGHT;
2522 else {
2523 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2524 __GFP_NOWARN;
2525 gfp &= ~__GFP_RECLAIM;
2526 }
2527 new = __folio_alloc_node(gfp, order, nid);
c5b5a3dd 2528
c185e494 2529 return &new->page;
c5b5a3dd
YS
2530}
2531
1c30e017 2532static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
b32967ff 2533{
2b9b624f 2534 int nr_pages = thp_nr_pages(page);
c574bbe9 2535 int order = compound_order(page);
a8f60772 2536
c574bbe9 2537 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
3abef4e6 2538
662aeea7
YS
2539 /* Do not migrate THP mapped by multiple processes */
2540 if (PageTransHuge(page) && total_mapcount(page) > 1)
2541 return 0;
2542
7039e1db 2543 /* Avoid migrating to a node that is nearly full */
c574bbe9
HY
2544 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2545 int z;
2546
2547 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2548 return 0;
2549 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
bc53008e 2550 if (managed_zone(pgdat->node_zones + z))
c574bbe9
HY
2551 break;
2552 }
2553 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
340ef390 2554 return 0;
c574bbe9 2555 }
7039e1db 2556
f7f9c00d 2557 if (!isolate_lru_page(page))
340ef390 2558 return 0;
7039e1db 2559
b75454e1 2560 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2b9b624f 2561 nr_pages);
340ef390 2562
149c33e1 2563 /*
340ef390
HD
2564 * Isolating the page has taken another reference, so the
2565 * caller's reference can be safely dropped without the page
2566 * disappearing underneath us during migration.
149c33e1
MG
2567 */
2568 put_page(page);
340ef390 2569 return 1;
b32967ff
MG
2570}
2571
2572/*
2573 * Attempt to migrate a misplaced page to the specified destination
2574 * node. Caller is expected to have an elevated reference count on
2575 * the page that will be dropped by this function before returning.
2576 */
1bc115d8
MG
2577int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2578 int node)
b32967ff
MG
2579{
2580 pg_data_t *pgdat = NODE_DATA(node);
340ef390 2581 int isolated;
b32967ff 2582 int nr_remaining;
e39bb6be 2583 unsigned int nr_succeeded;
b32967ff 2584 LIST_HEAD(migratepages);
b5916c02 2585 int nr_pages = thp_nr_pages(page);
c5b5a3dd 2586
b32967ff 2587 /*
1bc115d8
MG
2588 * Don't migrate file pages that are mapped in multiple processes
2589 * with execute permissions as they are probably shared libraries.
b32967ff 2590 */
7ee820ee
ML
2591 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2592 (vma->vm_flags & VM_EXEC))
b32967ff 2593 goto out;
b32967ff 2594
09a913a7
MG
2595 /*
2596 * Also do not migrate dirty pages as not all filesystems can move
2597 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2598 */
9de4f22a 2599 if (page_is_file_lru(page) && PageDirty(page))
09a913a7
MG
2600 goto out;
2601
b32967ff
MG
2602 isolated = numamigrate_isolate_page(pgdat, page);
2603 if (!isolated)
2604 goto out;
2605
2606 list_add(&page->lru, &migratepages);
c185e494
MWO
2607 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2608 NULL, node, MIGRATE_ASYNC,
2609 MR_NUMA_MISPLACED, &nr_succeeded);
b32967ff 2610 if (nr_remaining) {
59c82b70
JK
2611 if (!list_empty(&migratepages)) {
2612 list_del(&page->lru);
c5fc5c3a
YS
2613 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2614 page_is_file_lru(page), -nr_pages);
59c82b70
JK
2615 putback_lru_page(page);
2616 }
b32967ff 2617 isolated = 0;
e39bb6be
HY
2618 }
2619 if (nr_succeeded) {
2620 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2621 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2622 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2623 nr_succeeded);
2624 }
7039e1db 2625 BUG_ON(!list_empty(&migratepages));
7039e1db 2626 return isolated;
340ef390
HD
2627
2628out:
2629 put_page(page);
2630 return 0;
7039e1db 2631}
220018d3 2632#endif /* CONFIG_NUMA_BALANCING */
91952440 2633#endif /* CONFIG_NUMA */