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