]> git.proxmox.com Git - mirror_ubuntu-kernels.git/blame - mm/migrate.c
mm/migrate: fix CPUHP state to update node demotion order
[mirror_ubuntu-kernels.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>
a520110e 41#include <linux/pagewalk.h>
df6ad698 42#include <linux/pfn_t.h>
a5430dda 43#include <linux/memremap.h>
8315ada7 44#include <linux/userfaultfd_k.h>
bf6bddf1 45#include <linux/balloon_compaction.h>
f714f4f2 46#include <linux/mmu_notifier.h>
33c3fc71 47#include <linux/page_idle.h>
d435edca 48#include <linux/page_owner.h>
6e84f315 49#include <linux/sched/mm.h>
197e7e52 50#include <linux/ptrace.h>
34290e2c 51#include <linux/oom.h>
884a6e5d 52#include <linux/memory.h>
b20a3503 53
0d1836c3
MN
54#include <asm/tlbflush.h>
55
7b2a2d4a
MG
56#define CREATE_TRACE_POINTS
57#include <trace/events/migrate.h>
58
b20a3503
CL
59#include "internal.h"
60
9e5bcd61 61int isolate_movable_page(struct page *page, isolate_mode_t mode)
bda807d4
MK
62{
63 struct address_space *mapping;
64
65 /*
66 * Avoid burning cycles with pages that are yet under __free_pages(),
67 * or just got freed under us.
68 *
69 * In case we 'win' a race for a movable page being freed under us and
70 * raise its refcount preventing __free_pages() from doing its job
71 * the put_page() at the end of this block will take care of
72 * release this page, thus avoiding a nasty leakage.
73 */
74 if (unlikely(!get_page_unless_zero(page)))
75 goto out;
76
77 /*
78 * Check PageMovable before holding a PG_lock because page's owner
79 * assumes anybody doesn't touch PG_lock of newly allocated page
8bb4e7a2 80 * so unconditionally grabbing the lock ruins page's owner side.
bda807d4
MK
81 */
82 if (unlikely(!__PageMovable(page)))
83 goto out_putpage;
84 /*
85 * As movable pages are not isolated from LRU lists, concurrent
86 * compaction threads can race against page migration functions
87 * as well as race against the releasing a page.
88 *
89 * In order to avoid having an already isolated movable page
90 * being (wrongly) re-isolated while it is under migration,
91 * or to avoid attempting to isolate pages being released,
92 * lets be sure we have the page lock
93 * before proceeding with the movable page isolation steps.
94 */
95 if (unlikely(!trylock_page(page)))
96 goto out_putpage;
97
98 if (!PageMovable(page) || PageIsolated(page))
99 goto out_no_isolated;
100
101 mapping = page_mapping(page);
102 VM_BUG_ON_PAGE(!mapping, page);
103
104 if (!mapping->a_ops->isolate_page(page, mode))
105 goto out_no_isolated;
106
107 /* Driver shouldn't use PG_isolated bit of page->flags */
108 WARN_ON_ONCE(PageIsolated(page));
109 __SetPageIsolated(page);
110 unlock_page(page);
111
9e5bcd61 112 return 0;
bda807d4
MK
113
114out_no_isolated:
115 unlock_page(page);
116out_putpage:
117 put_page(page);
118out:
9e5bcd61 119 return -EBUSY;
bda807d4
MK
120}
121
606a6f71 122static void putback_movable_page(struct page *page)
bda807d4
MK
123{
124 struct address_space *mapping;
125
bda807d4
MK
126 mapping = page_mapping(page);
127 mapping->a_ops->putback_page(page);
128 __ClearPageIsolated(page);
129}
130
5733c7d1
RA
131/*
132 * Put previously isolated pages back onto the appropriate lists
133 * from where they were once taken off for compaction/migration.
134 *
59c82b70
JK
135 * This function shall be used whenever the isolated pageset has been
136 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
137 * and isolate_huge_page().
5733c7d1
RA
138 */
139void putback_movable_pages(struct list_head *l)
140{
141 struct page *page;
142 struct page *page2;
143
b20a3503 144 list_for_each_entry_safe(page, page2, l, lru) {
31caf665
NH
145 if (unlikely(PageHuge(page))) {
146 putback_active_hugepage(page);
147 continue;
148 }
e24f0b8f 149 list_del(&page->lru);
bda807d4
MK
150 /*
151 * We isolated non-lru movable page so here we can use
152 * __PageMovable because LRU page's mapping cannot have
153 * PAGE_MAPPING_MOVABLE.
154 */
b1123ea6 155 if (unlikely(__PageMovable(page))) {
bda807d4
MK
156 VM_BUG_ON_PAGE(!PageIsolated(page), page);
157 lock_page(page);
158 if (PageMovable(page))
159 putback_movable_page(page);
160 else
161 __ClearPageIsolated(page);
162 unlock_page(page);
163 put_page(page);
164 } else {
e8db67eb 165 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
6c357848 166 page_is_file_lru(page), -thp_nr_pages(page));
fc280fe8 167 putback_lru_page(page);
bda807d4 168 }
b20a3503 169 }
b20a3503
CL
170}
171
0697212a
CL
172/*
173 * Restore a potential migration pte to a working pte entry
174 */
e4b82222 175static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
e9995ef9 176 unsigned long addr, void *old)
0697212a 177{
3fe87967
KS
178 struct page_vma_mapped_walk pvmw = {
179 .page = old,
180 .vma = vma,
181 .address = addr,
182 .flags = PVMW_SYNC | PVMW_MIGRATION,
183 };
184 struct page *new;
185 pte_t pte;
0697212a 186 swp_entry_t entry;
0697212a 187
3fe87967
KS
188 VM_BUG_ON_PAGE(PageTail(page), page);
189 while (page_vma_mapped_walk(&pvmw)) {
4b0ece6f
NH
190 if (PageKsm(page))
191 new = page;
192 else
193 new = page - pvmw.page->index +
194 linear_page_index(vma, pvmw.address);
0697212a 195
616b8371
ZY
196#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
197 /* PMD-mapped THP migration entry */
198 if (!pvmw.pte) {
199 VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
200 remove_migration_pmd(&pvmw, new);
201 continue;
202 }
203#endif
204
3fe87967
KS
205 get_page(new);
206 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
207 if (pte_swp_soft_dirty(*pvmw.pte))
208 pte = pte_mksoft_dirty(pte);
0697212a 209
3fe87967
KS
210 /*
211 * Recheck VMA as permissions can change since migration started
212 */
213 entry = pte_to_swp_entry(*pvmw.pte);
4dd845b5 214 if (is_writable_migration_entry(entry))
3fe87967 215 pte = maybe_mkwrite(pte, vma);
f45ec5ff
PX
216 else if (pte_swp_uffd_wp(*pvmw.pte))
217 pte = pte_mkuffd_wp(pte);
d3cb8bf6 218
6128763f 219 if (unlikely(is_device_private_page(new))) {
4dd845b5
AP
220 if (pte_write(pte))
221 entry = make_writable_device_private_entry(
222 page_to_pfn(new));
223 else
224 entry = make_readable_device_private_entry(
225 page_to_pfn(new));
6128763f 226 pte = swp_entry_to_pte(entry);
3d321bf8
RC
227 if (pte_swp_soft_dirty(*pvmw.pte))
228 pte = pte_swp_mksoft_dirty(pte);
6128763f
RC
229 if (pte_swp_uffd_wp(*pvmw.pte))
230 pte = pte_swp_mkuffd_wp(pte);
d2b2c6dd 231 }
a5430dda 232
3ef8fd7f 233#ifdef CONFIG_HUGETLB_PAGE
3fe87967 234 if (PageHuge(new)) {
79c1c594
CL
235 unsigned int shift = huge_page_shift(hstate_vma(vma));
236
3fe87967 237 pte = pte_mkhuge(pte);
79c1c594 238 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
383321ab 239 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
3fe87967
KS
240 if (PageAnon(new))
241 hugepage_add_anon_rmap(new, vma, pvmw.address);
242 else
243 page_dup_rmap(new, true);
383321ab
AK
244 } else
245#endif
246 {
247 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
04e62a29 248
383321ab
AK
249 if (PageAnon(new))
250 page_add_anon_rmap(new, vma, pvmw.address, false);
251 else
252 page_add_file_rmap(new, false);
253 }
3fe87967
KS
254 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
255 mlock_vma_page(new);
256
e125fe40
KS
257 if (PageTransHuge(page) && PageMlocked(page))
258 clear_page_mlock(page);
259
3fe87967
KS
260 /* No need to invalidate - it was non-present before */
261 update_mmu_cache(vma, pvmw.address, pvmw.pte);
262 }
51afb12b 263
e4b82222 264 return true;
0697212a
CL
265}
266
04e62a29
CL
267/*
268 * Get rid of all migration entries and replace them by
269 * references to the indicated page.
270 */
e388466d 271void remove_migration_ptes(struct page *old, struct page *new, bool locked)
04e62a29 272{
051ac83a
JK
273 struct rmap_walk_control rwc = {
274 .rmap_one = remove_migration_pte,
275 .arg = old,
276 };
277
e388466d
KS
278 if (locked)
279 rmap_walk_locked(new, &rwc);
280 else
281 rmap_walk(new, &rwc);
04e62a29
CL
282}
283
0697212a
CL
284/*
285 * Something used the pte of a page under migration. We need to
286 * get to the page and wait until migration is finished.
287 * When we return from this function the fault will be retried.
0697212a 288 */
e66f17ff 289void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
30dad309 290 spinlock_t *ptl)
0697212a 291{
30dad309 292 pte_t pte;
0697212a
CL
293 swp_entry_t entry;
294 struct page *page;
295
30dad309 296 spin_lock(ptl);
0697212a
CL
297 pte = *ptep;
298 if (!is_swap_pte(pte))
299 goto out;
300
301 entry = pte_to_swp_entry(pte);
302 if (!is_migration_entry(entry))
303 goto out;
304
af5cdaf8 305 page = pfn_swap_entry_to_page(entry);
ffc90cbb 306 page = compound_head(page);
0697212a 307
e286781d 308 /*
89eb946a 309 * Once page cache replacement of page migration started, page_count
9a1ea439
HD
310 * is zero; but we must not call put_and_wait_on_page_locked() without
311 * a ref. Use get_page_unless_zero(), and just fault again if it fails.
e286781d
NP
312 */
313 if (!get_page_unless_zero(page))
314 goto out;
0697212a 315 pte_unmap_unlock(ptep, ptl);
48054625 316 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
0697212a
CL
317 return;
318out:
319 pte_unmap_unlock(ptep, ptl);
320}
321
30dad309
NH
322void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
323 unsigned long address)
324{
325 spinlock_t *ptl = pte_lockptr(mm, pmd);
326 pte_t *ptep = pte_offset_map(pmd, address);
327 __migration_entry_wait(mm, ptep, ptl);
328}
329
cb900f41
KS
330void migration_entry_wait_huge(struct vm_area_struct *vma,
331 struct mm_struct *mm, pte_t *pte)
30dad309 332{
cb900f41 333 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
30dad309
NH
334 __migration_entry_wait(mm, pte, ptl);
335}
336
616b8371
ZY
337#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
338void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
339{
340 spinlock_t *ptl;
341 struct page *page;
342
343 ptl = pmd_lock(mm, pmd);
344 if (!is_pmd_migration_entry(*pmd))
345 goto unlock;
af5cdaf8 346 page = pfn_swap_entry_to_page(pmd_to_swp_entry(*pmd));
616b8371
ZY
347 if (!get_page_unless_zero(page))
348 goto unlock;
349 spin_unlock(ptl);
48054625 350 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
616b8371
ZY
351 return;
352unlock:
353 spin_unlock(ptl);
354}
355#endif
356
f900482d 357static int expected_page_refs(struct address_space *mapping, struct page *page)
0b3901b3
JK
358{
359 int expected_count = 1;
360
361 /*
f1f4f3ab 362 * Device private pages have an extra refcount as they are
0b3901b3
JK
363 * ZONE_DEVICE pages.
364 */
365 expected_count += is_device_private_page(page);
f900482d 366 if (mapping)
6c357848 367 expected_count += thp_nr_pages(page) + page_has_private(page);
0b3901b3
JK
368
369 return expected_count;
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 */
36bc08cc 380int migrate_page_move_mapping(struct address_space *mapping,
37109694 381 struct page *newpage, struct page *page, int extra_count)
b20a3503 382{
89eb946a 383 XA_STATE(xas, &mapping->i_pages, page_index(page));
42cb14b1
HD
384 struct zone *oldzone, *newzone;
385 int dirty;
f900482d 386 int expected_count = expected_page_refs(mapping, page) + extra_count;
5c447d27 387 int nr = thp_nr_pages(page);
8763cb45 388
6c5240ae 389 if (!mapping) {
0e8c7d0f 390 /* Anonymous page without mapping */
8e321fef 391 if (page_count(page) != expected_count)
6c5240ae 392 return -EAGAIN;
cf4b769a
HD
393
394 /* No turning back from here */
cf4b769a
HD
395 newpage->index = page->index;
396 newpage->mapping = page->mapping;
397 if (PageSwapBacked(page))
fa9949da 398 __SetPageSwapBacked(newpage);
cf4b769a 399
78bd5209 400 return MIGRATEPAGE_SUCCESS;
6c5240ae
CL
401 }
402
42cb14b1
HD
403 oldzone = page_zone(page);
404 newzone = page_zone(newpage);
405
89eb946a 406 xas_lock_irq(&xas);
89eb946a
MW
407 if (page_count(page) != expected_count || xas_load(&xas) != page) {
408 xas_unlock_irq(&xas);
e23ca00b 409 return -EAGAIN;
b20a3503
CL
410 }
411
fe896d18 412 if (!page_ref_freeze(page, expected_count)) {
89eb946a 413 xas_unlock_irq(&xas);
e286781d
NP
414 return -EAGAIN;
415 }
416
b20a3503 417 /*
cf4b769a
HD
418 * Now we know that no one else is looking at the page:
419 * no turning back from here.
b20a3503 420 */
cf4b769a
HD
421 newpage->index = page->index;
422 newpage->mapping = page->mapping;
5c447d27 423 page_ref_add(newpage, nr); /* add cache reference */
6326fec1
NP
424 if (PageSwapBacked(page)) {
425 __SetPageSwapBacked(newpage);
426 if (PageSwapCache(page)) {
427 SetPageSwapCache(newpage);
428 set_page_private(newpage, page_private(page));
429 }
430 } else {
431 VM_BUG_ON_PAGE(PageSwapCache(page), page);
b20a3503
CL
432 }
433
42cb14b1
HD
434 /* Move dirty while page refs frozen and newpage not yet exposed */
435 dirty = PageDirty(page);
436 if (dirty) {
437 ClearPageDirty(page);
438 SetPageDirty(newpage);
439 }
440
89eb946a 441 xas_store(&xas, newpage);
e71769ae
NH
442 if (PageTransHuge(page)) {
443 int i;
e71769ae 444
5c447d27 445 for (i = 1; i < nr; i++) {
89eb946a 446 xas_next(&xas);
4101196b 447 xas_store(&xas, newpage);
e71769ae 448 }
e71769ae 449 }
7cf9c2c7
NP
450
451 /*
937a94c9
JG
452 * Drop cache reference from old page by unfreezing
453 * to one less reference.
7cf9c2c7
NP
454 * We know this isn't the last reference.
455 */
5c447d27 456 page_ref_unfreeze(page, expected_count - nr);
7cf9c2c7 457
89eb946a 458 xas_unlock(&xas);
42cb14b1
HD
459 /* Leave irq disabled to prevent preemption while updating stats */
460
0e8c7d0f
CL
461 /*
462 * If moved to a different zone then also account
463 * the page for that zone. Other VM counters will be
464 * taken care of when we establish references to the
465 * new page and drop references to the old page.
466 *
467 * Note that anonymous pages are accounted for
4b9d0fab 468 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
0e8c7d0f
CL
469 * are mapped to swap space.
470 */
42cb14b1 471 if (newzone != oldzone) {
0d1c2072
JW
472 struct lruvec *old_lruvec, *new_lruvec;
473 struct mem_cgroup *memcg;
474
475 memcg = page_memcg(page);
476 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
477 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
478
5c447d27
SB
479 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
480 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
42cb14b1 481 if (PageSwapBacked(page) && !PageSwapCache(page)) {
5c447d27
SB
482 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
483 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
42cb14b1 484 }
b6038942
SB
485#ifdef CONFIG_SWAP
486 if (PageSwapCache(page)) {
487 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
488 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
489 }
490#endif
f56753ac 491 if (dirty && mapping_can_writeback(mapping)) {
5c447d27
SB
492 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
493 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
494 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
495 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
42cb14b1 496 }
4b02108a 497 }
42cb14b1 498 local_irq_enable();
b20a3503 499
78bd5209 500 return MIGRATEPAGE_SUCCESS;
b20a3503 501}
1118dce7 502EXPORT_SYMBOL(migrate_page_move_mapping);
b20a3503 503
290408d4
NH
504/*
505 * The expected number of remaining references is the same as that
506 * of migrate_page_move_mapping().
507 */
508int migrate_huge_page_move_mapping(struct address_space *mapping,
509 struct page *newpage, struct page *page)
510{
89eb946a 511 XA_STATE(xas, &mapping->i_pages, page_index(page));
290408d4 512 int expected_count;
290408d4 513
89eb946a 514 xas_lock_irq(&xas);
290408d4 515 expected_count = 2 + page_has_private(page);
89eb946a
MW
516 if (page_count(page) != expected_count || xas_load(&xas) != page) {
517 xas_unlock_irq(&xas);
290408d4
NH
518 return -EAGAIN;
519 }
520
fe896d18 521 if (!page_ref_freeze(page, expected_count)) {
89eb946a 522 xas_unlock_irq(&xas);
290408d4
NH
523 return -EAGAIN;
524 }
525
cf4b769a
HD
526 newpage->index = page->index;
527 newpage->mapping = page->mapping;
6a93ca8f 528
290408d4
NH
529 get_page(newpage);
530
89eb946a 531 xas_store(&xas, newpage);
290408d4 532
fe896d18 533 page_ref_unfreeze(page, expected_count - 1);
290408d4 534
89eb946a 535 xas_unlock_irq(&xas);
6a93ca8f 536
78bd5209 537 return MIGRATEPAGE_SUCCESS;
290408d4
NH
538}
539
b20a3503
CL
540/*
541 * Copy the page to its new location
542 */
2916ecc0 543void migrate_page_states(struct page *newpage, struct page *page)
b20a3503 544{
7851a45c
RR
545 int cpupid;
546
b20a3503
CL
547 if (PageError(page))
548 SetPageError(newpage);
549 if (PageReferenced(page))
550 SetPageReferenced(newpage);
551 if (PageUptodate(page))
552 SetPageUptodate(newpage);
894bc310 553 if (TestClearPageActive(page)) {
309381fe 554 VM_BUG_ON_PAGE(PageUnevictable(page), page);
b20a3503 555 SetPageActive(newpage);
418b27ef
LS
556 } else if (TestClearPageUnevictable(page))
557 SetPageUnevictable(newpage);
1899ad18
JW
558 if (PageWorkingset(page))
559 SetPageWorkingset(newpage);
b20a3503
CL
560 if (PageChecked(page))
561 SetPageChecked(newpage);
562 if (PageMappedToDisk(page))
563 SetPageMappedToDisk(newpage);
564
42cb14b1
HD
565 /* Move dirty on pages not done by migrate_page_move_mapping() */
566 if (PageDirty(page))
567 SetPageDirty(newpage);
b20a3503 568
33c3fc71
VD
569 if (page_is_young(page))
570 set_page_young(newpage);
571 if (page_is_idle(page))
572 set_page_idle(newpage);
573
7851a45c
RR
574 /*
575 * Copy NUMA information to the new page, to prevent over-eager
576 * future migrations of this same page.
577 */
578 cpupid = page_cpupid_xchg_last(page, -1);
579 page_cpupid_xchg_last(newpage, cpupid);
580
e9995ef9 581 ksm_migrate_page(newpage, page);
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 */
b3b3a99c
NH
586 if (PageSwapCache(page))
587 ClearPageSwapCache(page);
b20a3503 588 ClearPagePrivate(page);
ad2fa371
MS
589
590 /* page->private contains hugetlb specific flags */
591 if (!PageHuge(page))
592 set_page_private(page, 0);
b20a3503
CL
593
594 /*
595 * If any waiters have accumulated on the new page then
596 * wake them up.
597 */
598 if (PageWriteback(newpage))
599 end_page_writeback(newpage);
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 */
606 if (PageReadahead(page))
607 SetPageReadahead(newpage);
608
d435edca 609 copy_page_owner(page, newpage);
74485cf2 610
a333e3e7
HD
611 if (!PageHuge(page))
612 mem_cgroup_migrate(page, newpage);
b20a3503 613}
2916ecc0
JG
614EXPORT_SYMBOL(migrate_page_states);
615
616void migrate_page_copy(struct page *newpage, struct page *page)
617{
618 if (PageHuge(page) || PageTransHuge(page))
619 copy_huge_page(newpage, page);
620 else
621 copy_highpage(newpage, page);
622
623 migrate_page_states(newpage, page);
624}
1118dce7 625EXPORT_SYMBOL(migrate_page_copy);
b20a3503 626
1d8b85cc
CL
627/************************************************************
628 * Migration functions
629 ***********************************************************/
630
b20a3503 631/*
bda807d4 632 * Common logic to directly migrate a single LRU page suitable for
266cf658 633 * pages that do not use PagePrivate/PagePrivate2.
b20a3503
CL
634 *
635 * Pages are locked upon entry and exit.
636 */
2d1db3b1 637int migrate_page(struct address_space *mapping,
a6bc32b8
MG
638 struct page *newpage, struct page *page,
639 enum migrate_mode mode)
b20a3503
CL
640{
641 int rc;
642
643 BUG_ON(PageWriteback(page)); /* Writeback must be complete */
644
37109694 645 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
b20a3503 646
78bd5209 647 if (rc != MIGRATEPAGE_SUCCESS)
b20a3503
CL
648 return rc;
649
2916ecc0
JG
650 if (mode != MIGRATE_SYNC_NO_COPY)
651 migrate_page_copy(newpage, page);
652 else
653 migrate_page_states(newpage, page);
78bd5209 654 return MIGRATEPAGE_SUCCESS;
b20a3503
CL
655}
656EXPORT_SYMBOL(migrate_page);
657
9361401e 658#ifdef CONFIG_BLOCK
84ade7c1
JK
659/* Returns true if all buffers are successfully locked */
660static bool buffer_migrate_lock_buffers(struct buffer_head *head,
661 enum migrate_mode mode)
662{
663 struct buffer_head *bh = head;
664
665 /* Simple case, sync compaction */
666 if (mode != MIGRATE_ASYNC) {
667 do {
84ade7c1
JK
668 lock_buffer(bh);
669 bh = bh->b_this_page;
670
671 } while (bh != head);
672
673 return true;
674 }
675
676 /* async case, we cannot block on lock_buffer so use trylock_buffer */
677 do {
84ade7c1
JK
678 if (!trylock_buffer(bh)) {
679 /*
680 * We failed to lock the buffer and cannot stall in
681 * async migration. Release the taken locks
682 */
683 struct buffer_head *failed_bh = bh;
84ade7c1
JK
684 bh = head;
685 while (bh != failed_bh) {
686 unlock_buffer(bh);
84ade7c1
JK
687 bh = bh->b_this_page;
688 }
689 return false;
690 }
691
692 bh = bh->b_this_page;
693 } while (bh != head);
694 return true;
695}
696
89cb0888
JK
697static int __buffer_migrate_page(struct address_space *mapping,
698 struct page *newpage, struct page *page, enum migrate_mode mode,
699 bool check_refs)
1d8b85cc 700{
1d8b85cc
CL
701 struct buffer_head *bh, *head;
702 int rc;
cc4f11e6 703 int expected_count;
1d8b85cc 704
1d8b85cc 705 if (!page_has_buffers(page))
a6bc32b8 706 return migrate_page(mapping, newpage, page, mode);
1d8b85cc 707
cc4f11e6 708 /* Check whether page does not have extra refs before we do more work */
f900482d 709 expected_count = expected_page_refs(mapping, page);
cc4f11e6
JK
710 if (page_count(page) != expected_count)
711 return -EAGAIN;
1d8b85cc 712
cc4f11e6
JK
713 head = page_buffers(page);
714 if (!buffer_migrate_lock_buffers(head, mode))
715 return -EAGAIN;
1d8b85cc 716
89cb0888
JK
717 if (check_refs) {
718 bool busy;
719 bool invalidated = false;
720
721recheck_buffers:
722 busy = false;
723 spin_lock(&mapping->private_lock);
724 bh = head;
725 do {
726 if (atomic_read(&bh->b_count)) {
727 busy = true;
728 break;
729 }
730 bh = bh->b_this_page;
731 } while (bh != head);
89cb0888
JK
732 if (busy) {
733 if (invalidated) {
734 rc = -EAGAIN;
735 goto unlock_buffers;
736 }
ebdf4de5 737 spin_unlock(&mapping->private_lock);
89cb0888
JK
738 invalidate_bh_lrus();
739 invalidated = true;
740 goto recheck_buffers;
741 }
742 }
743
37109694 744 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
78bd5209 745 if (rc != MIGRATEPAGE_SUCCESS)
cc4f11e6 746 goto unlock_buffers;
1d8b85cc 747
cd0f3715 748 attach_page_private(newpage, detach_page_private(page));
1d8b85cc
CL
749
750 bh = head;
751 do {
752 set_bh_page(bh, newpage, bh_offset(bh));
753 bh = bh->b_this_page;
754
755 } while (bh != head);
756
2916ecc0
JG
757 if (mode != MIGRATE_SYNC_NO_COPY)
758 migrate_page_copy(newpage, page);
759 else
760 migrate_page_states(newpage, page);
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
CL
769 bh = bh->b_this_page;
770
771 } while (bh != head);
772
cc4f11e6 773 return rc;
1d8b85cc 774}
89cb0888
JK
775
776/*
777 * Migration function for pages with buffers. This function can only be used
778 * if the underlying filesystem guarantees that no other references to "page"
779 * exist. For example attached buffer heads are accessed only under page lock.
780 */
781int buffer_migrate_page(struct address_space *mapping,
782 struct page *newpage, struct page *page, enum migrate_mode mode)
783{
784 return __buffer_migrate_page(mapping, newpage, page, mode, false);
785}
1d8b85cc 786EXPORT_SYMBOL(buffer_migrate_page);
89cb0888
JK
787
788/*
789 * Same as above except that this variant is more careful and checks that there
790 * are also no buffer head references. This function is the right one for
791 * mappings where buffer heads are directly looked up and referenced (such as
792 * block device mappings).
793 */
794int buffer_migrate_page_norefs(struct address_space *mapping,
795 struct page *newpage, struct page *page, enum migrate_mode mode)
796{
797 return __buffer_migrate_page(mapping, newpage, page, mode, true);
798}
9361401e 799#endif
1d8b85cc 800
04e62a29
CL
801/*
802 * Writeback a page to clean the dirty state
803 */
804static int writeout(struct address_space *mapping, struct page *page)
8351a6e4 805{
04e62a29
CL
806 struct writeback_control wbc = {
807 .sync_mode = WB_SYNC_NONE,
808 .nr_to_write = 1,
809 .range_start = 0,
810 .range_end = LLONG_MAX,
04e62a29
CL
811 .for_reclaim = 1
812 };
813 int rc;
814
815 if (!mapping->a_ops->writepage)
816 /* No write method for the address space */
817 return -EINVAL;
818
819 if (!clear_page_dirty_for_io(page))
820 /* Someone else already triggered a write */
821 return -EAGAIN;
822
8351a6e4 823 /*
04e62a29
CL
824 * A dirty page may imply that the underlying filesystem has
825 * the page on some queue. So the page must be clean for
826 * migration. Writeout may mean we loose the lock and the
827 * page state is no longer what we checked for earlier.
828 * At this point we know that the migration attempt cannot
829 * be successful.
8351a6e4 830 */
e388466d 831 remove_migration_ptes(page, page, false);
8351a6e4 832
04e62a29 833 rc = mapping->a_ops->writepage(page, &wbc);
8351a6e4 834
04e62a29
CL
835 if (rc != AOP_WRITEPAGE_ACTIVATE)
836 /* unlocked. Relock */
837 lock_page(page);
838
bda8550d 839 return (rc < 0) ? -EIO : -EAGAIN;
04e62a29
CL
840}
841
842/*
843 * Default handling if a filesystem does not provide a migration function.
844 */
845static int fallback_migrate_page(struct address_space *mapping,
a6bc32b8 846 struct page *newpage, struct page *page, enum migrate_mode mode)
04e62a29 847{
b969c4ab 848 if (PageDirty(page)) {
a6bc32b8 849 /* Only writeback pages in full synchronous migration */
2916ecc0
JG
850 switch (mode) {
851 case MIGRATE_SYNC:
852 case MIGRATE_SYNC_NO_COPY:
853 break;
854 default:
b969c4ab 855 return -EBUSY;
2916ecc0 856 }
04e62a29 857 return writeout(mapping, page);
b969c4ab 858 }
8351a6e4
CL
859
860 /*
861 * Buffers may be managed in a filesystem specific way.
862 * We must have no buffers or drop them.
863 */
266cf658 864 if (page_has_private(page) &&
8351a6e4 865 !try_to_release_page(page, GFP_KERNEL))
806031bb 866 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
8351a6e4 867
a6bc32b8 868 return migrate_page(mapping, newpage, page, mode);
8351a6e4
CL
869}
870
e24f0b8f
CL
871/*
872 * Move a page to a newly allocated page
873 * The page is locked and all ptes have been successfully removed.
874 *
875 * The new page will have replaced the old page if this function
876 * is successful.
894bc310
LS
877 *
878 * Return value:
879 * < 0 - error code
78bd5209 880 * MIGRATEPAGE_SUCCESS - success
e24f0b8f 881 */
3fe2011f 882static int move_to_new_page(struct page *newpage, struct page *page,
5c3f9a67 883 enum migrate_mode mode)
e24f0b8f
CL
884{
885 struct address_space *mapping;
bda807d4
MK
886 int rc = -EAGAIN;
887 bool is_lru = !__PageMovable(page);
e24f0b8f 888
7db7671f
HD
889 VM_BUG_ON_PAGE(!PageLocked(page), page);
890 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
e24f0b8f 891
e24f0b8f 892 mapping = page_mapping(page);
bda807d4
MK
893
894 if (likely(is_lru)) {
895 if (!mapping)
896 rc = migrate_page(mapping, newpage, page, mode);
897 else if (mapping->a_ops->migratepage)
898 /*
899 * Most pages have a mapping and most filesystems
900 * provide a migratepage callback. Anonymous pages
901 * are part of swap space which also has its own
902 * migratepage callback. This is the most common path
903 * for page migration.
904 */
905 rc = mapping->a_ops->migratepage(mapping, newpage,
906 page, mode);
907 else
908 rc = fallback_migrate_page(mapping, newpage,
909 page, mode);
910 } else {
e24f0b8f 911 /*
bda807d4
MK
912 * In case of non-lru page, it could be released after
913 * isolation step. In that case, we shouldn't try migration.
e24f0b8f 914 */
bda807d4
MK
915 VM_BUG_ON_PAGE(!PageIsolated(page), page);
916 if (!PageMovable(page)) {
917 rc = MIGRATEPAGE_SUCCESS;
918 __ClearPageIsolated(page);
919 goto out;
920 }
921
922 rc = mapping->a_ops->migratepage(mapping, newpage,
923 page, mode);
924 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
925 !PageIsolated(page));
926 }
e24f0b8f 927
5c3f9a67
HD
928 /*
929 * When successful, old pagecache page->mapping must be cleared before
930 * page is freed; but stats require that PageAnon be left as PageAnon.
931 */
932 if (rc == MIGRATEPAGE_SUCCESS) {
bda807d4
MK
933 if (__PageMovable(page)) {
934 VM_BUG_ON_PAGE(!PageIsolated(page), page);
935
936 /*
937 * We clear PG_movable under page_lock so any compactor
938 * cannot try to migrate this page.
939 */
940 __ClearPageIsolated(page);
941 }
942
943 /*
c23a0c99 944 * Anonymous and movable page->mapping will be cleared by
bda807d4
MK
945 * free_pages_prepare so don't reset it here for keeping
946 * the type to work PageAnon, for example.
947 */
948 if (!PageMappingFlags(page))
5c3f9a67 949 page->mapping = NULL;
d2b2c6dd 950
25b2995a 951 if (likely(!is_zone_device_page(newpage)))
d2b2c6dd
LP
952 flush_dcache_page(newpage);
953
3fe2011f 954 }
bda807d4 955out:
e24f0b8f
CL
956 return rc;
957}
958
0dabec93 959static int __unmap_and_move(struct page *page, struct page *newpage,
9c620e2b 960 int force, enum migrate_mode mode)
e24f0b8f 961{
0dabec93 962 int rc = -EAGAIN;
213ecb31 963 bool page_was_mapped = false;
3f6c8272 964 struct anon_vma *anon_vma = NULL;
bda807d4 965 bool is_lru = !__PageMovable(page);
95a402c3 966
529ae9aa 967 if (!trylock_page(page)) {
a6bc32b8 968 if (!force || mode == MIGRATE_ASYNC)
0dabec93 969 goto out;
3e7d3449
MG
970
971 /*
972 * It's not safe for direct compaction to call lock_page.
973 * For example, during page readahead pages are added locked
974 * to the LRU. Later, when the IO completes the pages are
975 * marked uptodate and unlocked. However, the queueing
976 * could be merging multiple pages for one bio (e.g.
d4388340 977 * mpage_readahead). If an allocation happens for the
3e7d3449
MG
978 * second or third page, the process can end up locking
979 * the same page twice and deadlocking. Rather than
980 * trying to be clever about what pages can be locked,
981 * avoid the use of lock_page for direct compaction
982 * altogether.
983 */
984 if (current->flags & PF_MEMALLOC)
0dabec93 985 goto out;
3e7d3449 986
e24f0b8f
CL
987 lock_page(page);
988 }
989
990 if (PageWriteback(page)) {
11bc82d6 991 /*
fed5b64a 992 * Only in the case of a full synchronous migration is it
a6bc32b8
MG
993 * necessary to wait for PageWriteback. In the async case,
994 * the retry loop is too short and in the sync-light case,
995 * the overhead of stalling is too much
11bc82d6 996 */
2916ecc0
JG
997 switch (mode) {
998 case MIGRATE_SYNC:
999 case MIGRATE_SYNC_NO_COPY:
1000 break;
1001 default:
11bc82d6 1002 rc = -EBUSY;
0a31bc97 1003 goto out_unlock;
11bc82d6
AA
1004 }
1005 if (!force)
0a31bc97 1006 goto out_unlock;
e24f0b8f
CL
1007 wait_on_page_writeback(page);
1008 }
03f15c86 1009
e24f0b8f 1010 /*
68a9843f 1011 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
dc386d4d 1012 * we cannot notice that anon_vma is freed while we migrates a page.
1ce82b69 1013 * This get_anon_vma() delays freeing anon_vma pointer until the end
dc386d4d 1014 * of migration. File cache pages are no problem because of page_lock()
989f89c5
KH
1015 * File Caches may use write_page() or lock_page() in migration, then,
1016 * just care Anon page here.
03f15c86
HD
1017 *
1018 * Only page_get_anon_vma() understands the subtleties of
1019 * getting a hold on an anon_vma from outside one of its mms.
1020 * But if we cannot get anon_vma, then we won't need it anyway,
1021 * because that implies that the anon page is no longer mapped
1022 * (and cannot be remapped so long as we hold the page lock).
dc386d4d 1023 */
03f15c86 1024 if (PageAnon(page) && !PageKsm(page))
746b18d4 1025 anon_vma = page_get_anon_vma(page);
62e1c553 1026
7db7671f
HD
1027 /*
1028 * Block others from accessing the new page when we get around to
1029 * establishing additional references. We are usually the only one
1030 * holding a reference to newpage at this point. We used to have a BUG
1031 * here if trylock_page(newpage) fails, but would like to allow for
1032 * cases where there might be a race with the previous use of newpage.
1033 * This is much like races on refcount of oldpage: just don't BUG().
1034 */
1035 if (unlikely(!trylock_page(newpage)))
1036 goto out_unlock;
1037
bda807d4
MK
1038 if (unlikely(!is_lru)) {
1039 rc = move_to_new_page(newpage, page, mode);
1040 goto out_unlock_both;
1041 }
1042
dc386d4d 1043 /*
62e1c553
SL
1044 * Corner case handling:
1045 * 1. When a new swap-cache page is read into, it is added to the LRU
1046 * and treated as swapcache but it has no rmap yet.
1047 * Calling try_to_unmap() against a page->mapping==NULL page will
1048 * trigger a BUG. So handle it here.
d12b8951 1049 * 2. An orphaned page (see truncate_cleanup_page) might have
62e1c553
SL
1050 * fs-private metadata. The page can be picked up due to memory
1051 * offlining. Everywhere else except page reclaim, the page is
1052 * invisible to the vm, so the page can not be migrated. So try to
1053 * free the metadata, so the page can be freed.
e24f0b8f 1054 */
62e1c553 1055 if (!page->mapping) {
309381fe 1056 VM_BUG_ON_PAGE(PageAnon(page), page);
1ce82b69 1057 if (page_has_private(page)) {
62e1c553 1058 try_to_free_buffers(page);
7db7671f 1059 goto out_unlock_both;
62e1c553 1060 }
7db7671f
HD
1061 } else if (page_mapped(page)) {
1062 /* Establish migration ptes */
03f15c86
HD
1063 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1064 page);
a98a2f0c 1065 try_to_migrate(page, 0);
213ecb31 1066 page_was_mapped = true;
2ebba6b7 1067 }
dc386d4d 1068
e6a1530d 1069 if (!page_mapped(page))
5c3f9a67 1070 rc = move_to_new_page(newpage, page, mode);
e24f0b8f 1071
5c3f9a67
HD
1072 if (page_was_mapped)
1073 remove_migration_ptes(page,
e388466d 1074 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
3f6c8272 1075
7db7671f
HD
1076out_unlock_both:
1077 unlock_page(newpage);
1078out_unlock:
3f6c8272 1079 /* Drop an anon_vma reference if we took one */
76545066 1080 if (anon_vma)
9e60109f 1081 put_anon_vma(anon_vma);
e24f0b8f 1082 unlock_page(page);
0dabec93 1083out:
c6c919eb
MK
1084 /*
1085 * If migration is successful, decrease refcount of the newpage
1086 * which will not free the page because new page owner increased
1087 * refcounter. As well, if it is LRU page, add the page to LRU
e0a352fa
DH
1088 * list in here. Use the old state of the isolated source page to
1089 * determine if we migrated a LRU page. newpage was already unlocked
1090 * and possibly modified by its owner - don't rely on the page
1091 * state.
c6c919eb
MK
1092 */
1093 if (rc == MIGRATEPAGE_SUCCESS) {
e0a352fa 1094 if (unlikely(!is_lru))
c6c919eb
MK
1095 put_page(newpage);
1096 else
1097 putback_lru_page(newpage);
1098 }
1099
0dabec93
MK
1100 return rc;
1101}
95a402c3 1102
79c28a41
DH
1103
1104/*
1105 * node_demotion[] example:
1106 *
1107 * Consider a system with two sockets. Each socket has
1108 * three classes of memory attached: fast, medium and slow.
1109 * Each memory class is placed in its own NUMA node. The
1110 * CPUs are placed in the node with the "fast" memory. The
1111 * 6 NUMA nodes (0-5) might be split among the sockets like
1112 * this:
1113 *
1114 * Socket A: 0, 1, 2
1115 * Socket B: 3, 4, 5
1116 *
1117 * When Node 0 fills up, its memory should be migrated to
1118 * Node 1. When Node 1 fills up, it should be migrated to
1119 * Node 2. The migration path start on the nodes with the
1120 * processors (since allocations default to this node) and
1121 * fast memory, progress through medium and end with the
1122 * slow memory:
1123 *
1124 * 0 -> 1 -> 2 -> stop
1125 * 3 -> 4 -> 5 -> stop
1126 *
1127 * This is represented in the node_demotion[] like this:
1128 *
1129 * { 1, // Node 0 migrates to 1
1130 * 2, // Node 1 migrates to 2
1131 * -1, // Node 2 does not migrate
1132 * 4, // Node 3 migrates to 4
1133 * 5, // Node 4 migrates to 5
1134 * -1} // Node 5 does not migrate
1135 */
1136
1137/*
1138 * Writes to this array occur without locking. Cycles are
1139 * not allowed: Node X demotes to Y which demotes to X...
1140 *
1141 * If multiple reads are performed, a single rcu_read_lock()
1142 * must be held over all reads to ensure that no cycles are
1143 * observed.
1144 */
1145static int node_demotion[MAX_NUMNODES] __read_mostly =
1146 {[0 ... MAX_NUMNODES - 1] = NUMA_NO_NODE};
1147
1148/**
1149 * next_demotion_node() - Get the next node in the demotion path
1150 * @node: The starting node to lookup the next node
1151 *
c9bd7d18 1152 * Return: node id for next memory node in the demotion path hierarchy
79c28a41
DH
1153 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
1154 * @node online or guarantee that it *continues* to be the next demotion
1155 * target.
1156 */
1157int next_demotion_node(int node)
1158{
1159 int target;
1160
1161 /*
1162 * node_demotion[] is updated without excluding this
1163 * function from running. RCU doesn't provide any
1164 * compiler barriers, so the READ_ONCE() is required
1165 * to avoid compiler reordering or read merging.
1166 *
1167 * Make sure to use RCU over entire code blocks if
1168 * node_demotion[] reads need to be consistent.
1169 */
1170 rcu_read_lock();
1171 target = READ_ONCE(node_demotion[node]);
1172 rcu_read_unlock();
1173
1174 return target;
1175}
1176
0dabec93
MK
1177/*
1178 * Obtain the lock on page, remove all ptes and migrate the page
1179 * to the newly allocated page in newpage.
1180 */
6ec4476a 1181static int unmap_and_move(new_page_t get_new_page,
ef2a5153
GU
1182 free_page_t put_new_page,
1183 unsigned long private, struct page *page,
add05cec 1184 int force, enum migrate_mode mode,
dd4ae78a
YS
1185 enum migrate_reason reason,
1186 struct list_head *ret)
0dabec93 1187{
2def7424 1188 int rc = MIGRATEPAGE_SUCCESS;
74d4a579 1189 struct page *newpage = NULL;
0dabec93 1190
94723aaf 1191 if (!thp_migration_supported() && PageTransHuge(page))
d532e2e5 1192 return -ENOSYS;
94723aaf 1193
0dabec93
MK
1194 if (page_count(page) == 1) {
1195 /* page was freed from under us. So we are done. */
c6c919eb
MK
1196 ClearPageActive(page);
1197 ClearPageUnevictable(page);
bda807d4
MK
1198 if (unlikely(__PageMovable(page))) {
1199 lock_page(page);
1200 if (!PageMovable(page))
1201 __ClearPageIsolated(page);
1202 unlock_page(page);
1203 }
0dabec93
MK
1204 goto out;
1205 }
1206
74d4a579
YS
1207 newpage = get_new_page(page, private);
1208 if (!newpage)
1209 return -ENOMEM;
1210
9c620e2b 1211 rc = __unmap_and_move(page, newpage, force, mode);
c6c919eb 1212 if (rc == MIGRATEPAGE_SUCCESS)
7cd12b4a 1213 set_page_owner_migrate_reason(newpage, reason);
bf6bddf1 1214
0dabec93 1215out:
e24f0b8f 1216 if (rc != -EAGAIN) {
0dabec93
MK
1217 /*
1218 * A page that has been migrated has all references
1219 * removed and will be freed. A page that has not been
c23a0c99 1220 * migrated will have kept its references and be restored.
0dabec93
MK
1221 */
1222 list_del(&page->lru);
dd4ae78a 1223 }
6afcf8ef 1224
dd4ae78a
YS
1225 /*
1226 * If migration is successful, releases reference grabbed during
1227 * isolation. Otherwise, restore the page to right list unless
1228 * we want to retry.
1229 */
1230 if (rc == MIGRATEPAGE_SUCCESS) {
6afcf8ef
ML
1231 /*
1232 * Compaction can migrate also non-LRU pages which are
1233 * not accounted to NR_ISOLATED_*. They can be recognized
1234 * as __PageMovable
1235 */
1236 if (likely(!__PageMovable(page)))
e8db67eb 1237 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
6c357848 1238 page_is_file_lru(page), -thp_nr_pages(page));
c6c919eb 1239
79f5f8fa 1240 if (reason != MR_MEMORY_FAILURE)
d7e69488 1241 /*
79f5f8fa 1242 * We release the page in page_handle_poison.
d7e69488 1243 */
79f5f8fa 1244 put_page(page);
c6c919eb 1245 } else {
dd4ae78a
YS
1246 if (rc != -EAGAIN)
1247 list_add_tail(&page->lru, ret);
bda807d4 1248
c6c919eb
MK
1249 if (put_new_page)
1250 put_new_page(newpage, private);
1251 else
1252 put_page(newpage);
e24f0b8f 1253 }
68711a74 1254
e24f0b8f
CL
1255 return rc;
1256}
1257
290408d4
NH
1258/*
1259 * Counterpart of unmap_and_move_page() for hugepage migration.
1260 *
1261 * This function doesn't wait the completion of hugepage I/O
1262 * because there is no race between I/O and migration for hugepage.
1263 * Note that currently hugepage I/O occurs only in direct I/O
1264 * where no lock is held and PG_writeback is irrelevant,
1265 * and writeback status of all subpages are counted in the reference
1266 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1267 * under direct I/O, the reference of the head page is 512 and a bit more.)
1268 * This means that when we try to migrate hugepage whose subpages are
1269 * doing direct I/O, some references remain after try_to_unmap() and
1270 * hugepage migration fails without data corruption.
1271 *
1272 * There is also no race when direct I/O is issued on the page under migration,
1273 * because then pte is replaced with migration swap entry and direct I/O code
1274 * will wait in the page fault for migration to complete.
1275 */
1276static int unmap_and_move_huge_page(new_page_t get_new_page,
68711a74
DR
1277 free_page_t put_new_page, unsigned long private,
1278 struct page *hpage, int force,
dd4ae78a
YS
1279 enum migrate_mode mode, int reason,
1280 struct list_head *ret)
290408d4 1281{
2def7424 1282 int rc = -EAGAIN;
2ebba6b7 1283 int page_was_mapped = 0;
32665f2b 1284 struct page *new_hpage;
290408d4 1285 struct anon_vma *anon_vma = NULL;
c0d0381a 1286 struct address_space *mapping = NULL;
290408d4 1287
83467efb 1288 /*
7ed2c31d 1289 * Migratability of hugepages depends on architectures and their size.
83467efb
NH
1290 * This check is necessary because some callers of hugepage migration
1291 * like soft offline and memory hotremove don't walk through page
1292 * tables or check whether the hugepage is pmd-based or not before
1293 * kicking migration.
1294 */
100873d7 1295 if (!hugepage_migration_supported(page_hstate(hpage))) {
dd4ae78a 1296 list_move_tail(&hpage->lru, ret);
83467efb 1297 return -ENOSYS;
32665f2b 1298 }
83467efb 1299
71a64f61
MS
1300 if (page_count(hpage) == 1) {
1301 /* page was freed from under us. So we are done. */
1302 putback_active_hugepage(hpage);
1303 return MIGRATEPAGE_SUCCESS;
1304 }
1305
666feb21 1306 new_hpage = get_new_page(hpage, private);
290408d4
NH
1307 if (!new_hpage)
1308 return -ENOMEM;
1309
290408d4 1310 if (!trylock_page(hpage)) {
2916ecc0 1311 if (!force)
290408d4 1312 goto out;
2916ecc0
JG
1313 switch (mode) {
1314 case MIGRATE_SYNC:
1315 case MIGRATE_SYNC_NO_COPY:
1316 break;
1317 default:
1318 goto out;
1319 }
290408d4
NH
1320 lock_page(hpage);
1321 }
1322
cb6acd01
MK
1323 /*
1324 * Check for pages which are in the process of being freed. Without
1325 * page_mapping() set, hugetlbfs specific move page routine will not
1326 * be called and we could leak usage counts for subpools.
1327 */
6acfb5ba 1328 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
cb6acd01
MK
1329 rc = -EBUSY;
1330 goto out_unlock;
1331 }
1332
746b18d4
PZ
1333 if (PageAnon(hpage))
1334 anon_vma = page_get_anon_vma(hpage);
290408d4 1335
7db7671f
HD
1336 if (unlikely(!trylock_page(new_hpage)))
1337 goto put_anon;
1338
2ebba6b7 1339 if (page_mapped(hpage)) {
336bf30e 1340 bool mapping_locked = false;
a98a2f0c 1341 enum ttu_flags ttu = 0;
336bf30e
MK
1342
1343 if (!PageAnon(hpage)) {
1344 /*
1345 * In shared mappings, try_to_unmap could potentially
1346 * call huge_pmd_unshare. Because of this, take
1347 * semaphore in write mode here and set TTU_RMAP_LOCKED
1348 * to let lower levels know we have taken the lock.
1349 */
1350 mapping = hugetlb_page_mapping_lock_write(hpage);
1351 if (unlikely(!mapping))
1352 goto unlock_put_anon;
1353
1354 mapping_locked = true;
1355 ttu |= TTU_RMAP_LOCKED;
1356 }
c0d0381a 1357
a98a2f0c 1358 try_to_migrate(hpage, ttu);
2ebba6b7 1359 page_was_mapped = 1;
336bf30e
MK
1360
1361 if (mapping_locked)
1362 i_mmap_unlock_write(mapping);
2ebba6b7 1363 }
290408d4
NH
1364
1365 if (!page_mapped(hpage))
5c3f9a67 1366 rc = move_to_new_page(new_hpage, hpage, mode);
290408d4 1367
336bf30e 1368 if (page_was_mapped)
5c3f9a67 1369 remove_migration_ptes(hpage,
336bf30e 1370 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
290408d4 1371
c0d0381a 1372unlock_put_anon:
7db7671f
HD
1373 unlock_page(new_hpage);
1374
1375put_anon:
fd4a4663 1376 if (anon_vma)
9e60109f 1377 put_anon_vma(anon_vma);
8e6ac7fa 1378
2def7424 1379 if (rc == MIGRATEPAGE_SUCCESS) {
ab5ac90a 1380 move_hugetlb_state(hpage, new_hpage, reason);
2def7424
HD
1381 put_new_page = NULL;
1382 }
8e6ac7fa 1383
cb6acd01 1384out_unlock:
290408d4 1385 unlock_page(hpage);
09761333 1386out:
dd4ae78a 1387 if (rc == MIGRATEPAGE_SUCCESS)
b8ec1cee 1388 putback_active_hugepage(hpage);
a04840c6 1389 else if (rc != -EAGAIN)
dd4ae78a 1390 list_move_tail(&hpage->lru, ret);
68711a74
DR
1391
1392 /*
1393 * If migration was not successful and there's a freeing callback, use
1394 * it. Otherwise, put_page() will drop the reference grabbed during
1395 * isolation.
1396 */
2def7424 1397 if (put_new_page)
68711a74
DR
1398 put_new_page(new_hpage, private);
1399 else
3aaa76e1 1400 putback_active_hugepage(new_hpage);
68711a74 1401
290408d4
NH
1402 return rc;
1403}
1404
d532e2e5
YS
1405static inline int try_split_thp(struct page *page, struct page **page2,
1406 struct list_head *from)
1407{
1408 int rc = 0;
1409
1410 lock_page(page);
1411 rc = split_huge_page_to_list(page, from);
1412 unlock_page(page);
1413 if (!rc)
1414 list_safe_reset_next(page, *page2, lru);
1415
1416 return rc;
1417}
1418
b20a3503 1419/*
c73e5c9c
SB
1420 * migrate_pages - migrate the pages specified in a list, to the free pages
1421 * supplied as the target for the page migration
b20a3503 1422 *
c73e5c9c
SB
1423 * @from: The list of pages to be migrated.
1424 * @get_new_page: The function used to allocate free pages to be used
1425 * as the target of the page migration.
68711a74
DR
1426 * @put_new_page: The function used to free target pages if migration
1427 * fails, or NULL if no special handling is necessary.
c73e5c9c
SB
1428 * @private: Private data to be passed on to get_new_page()
1429 * @mode: The migration mode that specifies the constraints for
1430 * page migration, if any.
1431 * @reason: The reason for page migration.
5ac95884
YS
1432 * @ret_succeeded: Set to the number of pages migrated successfully if
1433 * the caller passes a non-NULL pointer.
b20a3503 1434 *
c73e5c9c
SB
1435 * The function returns after 10 attempts or if no pages are movable any more
1436 * because the list has become empty or no retryable pages exist any more.
dd4ae78a
YS
1437 * It is caller's responsibility to call putback_movable_pages() to return pages
1438 * to the LRU or free list only if ret != 0.
b20a3503 1439 *
c73e5c9c 1440 * Returns the number of pages that were not migrated, or an error code.
b20a3503 1441 */
9c620e2b 1442int migrate_pages(struct list_head *from, new_page_t get_new_page,
68711a74 1443 free_page_t put_new_page, unsigned long private,
5ac95884 1444 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
b20a3503 1445{
e24f0b8f 1446 int retry = 1;
1a5bae25 1447 int thp_retry = 1;
b20a3503 1448 int nr_failed = 0;
5647bc29 1449 int nr_succeeded = 0;
1a5bae25
AK
1450 int nr_thp_succeeded = 0;
1451 int nr_thp_failed = 0;
1452 int nr_thp_split = 0;
b20a3503 1453 int pass = 0;
1a5bae25 1454 bool is_thp = false;
b20a3503
CL
1455 struct page *page;
1456 struct page *page2;
1457 int swapwrite = current->flags & PF_SWAPWRITE;
1a5bae25 1458 int rc, nr_subpages;
dd4ae78a 1459 LIST_HEAD(ret_pages);
b0b515bf 1460 bool nosplit = (reason == MR_NUMA_MISPLACED);
b20a3503 1461
7bc1aec5
LM
1462 trace_mm_migrate_pages_start(mode, reason);
1463
b20a3503
CL
1464 if (!swapwrite)
1465 current->flags |= PF_SWAPWRITE;
1466
1a5bae25 1467 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
e24f0b8f 1468 retry = 0;
1a5bae25 1469 thp_retry = 0;
b20a3503 1470
e24f0b8f 1471 list_for_each_entry_safe(page, page2, from, lru) {
94723aaf 1472retry:
1a5bae25
AK
1473 /*
1474 * THP statistics is based on the source huge page.
1475 * Capture required information that might get lost
1476 * during migration.
1477 */
6c5c7b9f 1478 is_thp = PageTransHuge(page) && !PageHuge(page);
6c357848 1479 nr_subpages = thp_nr_pages(page);
e24f0b8f 1480 cond_resched();
2d1db3b1 1481
31caf665
NH
1482 if (PageHuge(page))
1483 rc = unmap_and_move_huge_page(get_new_page,
68711a74 1484 put_new_page, private, page,
dd4ae78a
YS
1485 pass > 2, mode, reason,
1486 &ret_pages);
31caf665 1487 else
68711a74 1488 rc = unmap_and_move(get_new_page, put_new_page,
add05cec 1489 private, page, pass > 2, mode,
dd4ae78a
YS
1490 reason, &ret_pages);
1491 /*
1492 * The rules are:
1493 * Success: non hugetlb page will be freed, hugetlb
1494 * page will be put back
1495 * -EAGAIN: stay on the from list
1496 * -ENOMEM: stay on the from list
1497 * Other errno: put on ret_pages list then splice to
1498 * from list
1499 */
e24f0b8f 1500 switch(rc) {
d532e2e5
YS
1501 /*
1502 * THP migration might be unsupported or the
1503 * allocation could've failed so we should
1504 * retry on the same page with the THP split
1505 * to base pages.
1506 *
1507 * Head page is retried immediately and tail
1508 * pages are added to the tail of the list so
1509 * we encounter them after the rest of the list
1510 * is processed.
1511 */
1512 case -ENOSYS:
1513 /* THP migration is unsupported */
1514 if (is_thp) {
1515 if (!try_split_thp(page, &page2, from)) {
1516 nr_thp_split++;
1517 goto retry;
1518 }
1519
1520 nr_thp_failed++;
1521 nr_failed += nr_subpages;
1522 break;
1523 }
1524
1525 /* Hugetlb migration is unsupported */
1526 nr_failed++;
1527 break;
95a402c3 1528 case -ENOMEM:
94723aaf 1529 /*
d532e2e5
YS
1530 * When memory is low, don't bother to try to migrate
1531 * other pages, just exit.
b0b515bf 1532 * THP NUMA faulting doesn't split THP to retry.
94723aaf 1533 */
b0b515bf 1534 if (is_thp && !nosplit) {
d532e2e5 1535 if (!try_split_thp(page, &page2, from)) {
1a5bae25 1536 nr_thp_split++;
94723aaf
MH
1537 goto retry;
1538 }
6c5c7b9f 1539
1a5bae25
AK
1540 nr_thp_failed++;
1541 nr_failed += nr_subpages;
1542 goto out;
1543 }
dfef2ef4 1544 nr_failed++;
95a402c3 1545 goto out;
e24f0b8f 1546 case -EAGAIN:
1a5bae25
AK
1547 if (is_thp) {
1548 thp_retry++;
1549 break;
1550 }
2d1db3b1 1551 retry++;
e24f0b8f 1552 break;
78bd5209 1553 case MIGRATEPAGE_SUCCESS:
1a5bae25
AK
1554 if (is_thp) {
1555 nr_thp_succeeded++;
1556 nr_succeeded += nr_subpages;
1557 break;
1558 }
5647bc29 1559 nr_succeeded++;
e24f0b8f
CL
1560 break;
1561 default:
354a3363 1562 /*
d532e2e5 1563 * Permanent failure (-EBUSY, etc.):
354a3363
NH
1564 * unlike -EAGAIN case, the failed page is
1565 * removed from migration page list and not
1566 * retried in the next outer loop.
1567 */
1a5bae25
AK
1568 if (is_thp) {
1569 nr_thp_failed++;
1570 nr_failed += nr_subpages;
1571 break;
1572 }
2d1db3b1 1573 nr_failed++;
e24f0b8f 1574 break;
2d1db3b1 1575 }
b20a3503
CL
1576 }
1577 }
1a5bae25
AK
1578 nr_failed += retry + thp_retry;
1579 nr_thp_failed += thp_retry;
f2f81fb2 1580 rc = nr_failed;
95a402c3 1581out:
dd4ae78a
YS
1582 /*
1583 * Put the permanent failure page back to migration list, they
1584 * will be put back to the right list by the caller.
1585 */
1586 list_splice(&ret_pages, from);
1587
1a5bae25
AK
1588 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1589 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1590 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1591 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1592 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1593 trace_mm_migrate_pages(nr_succeeded, nr_failed, nr_thp_succeeded,
1594 nr_thp_failed, nr_thp_split, mode, reason);
7b2a2d4a 1595
b20a3503
CL
1596 if (!swapwrite)
1597 current->flags &= ~PF_SWAPWRITE;
1598
5ac95884
YS
1599 if (ret_succeeded)
1600 *ret_succeeded = nr_succeeded;
1601
78bd5209 1602 return rc;
b20a3503 1603}
95a402c3 1604
19fc7bed 1605struct page *alloc_migration_target(struct page *page, unsigned long private)
b4b38223 1606{
19fc7bed
JK
1607 struct migration_target_control *mtc;
1608 gfp_t gfp_mask;
b4b38223
JK
1609 unsigned int order = 0;
1610 struct page *new_page = NULL;
19fc7bed
JK
1611 int nid;
1612 int zidx;
1613
1614 mtc = (struct migration_target_control *)private;
1615 gfp_mask = mtc->gfp_mask;
1616 nid = mtc->nid;
1617 if (nid == NUMA_NO_NODE)
1618 nid = page_to_nid(page);
b4b38223 1619
d92bbc27
JK
1620 if (PageHuge(page)) {
1621 struct hstate *h = page_hstate(compound_head(page));
1622
19fc7bed
JK
1623 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1624 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
d92bbc27 1625 }
b4b38223
JK
1626
1627 if (PageTransHuge(page)) {
9933a0c8
JK
1628 /*
1629 * clear __GFP_RECLAIM to make the migration callback
1630 * consistent with regular THP allocations.
1631 */
1632 gfp_mask &= ~__GFP_RECLAIM;
b4b38223
JK
1633 gfp_mask |= GFP_TRANSHUGE;
1634 order = HPAGE_PMD_ORDER;
1635 }
19fc7bed
JK
1636 zidx = zone_idx(page_zone(page));
1637 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
b4b38223
JK
1638 gfp_mask |= __GFP_HIGHMEM;
1639
84172f4b 1640 new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
b4b38223
JK
1641
1642 if (new_page && PageTransHuge(new_page))
1643 prep_transhuge_page(new_page);
1644
1645 return new_page;
1646}
1647
742755a1 1648#ifdef CONFIG_NUMA
742755a1 1649
a49bd4d7 1650static int store_status(int __user *status, int start, int value, int nr)
742755a1 1651{
a49bd4d7
MH
1652 while (nr-- > 0) {
1653 if (put_user(value, status + start))
1654 return -EFAULT;
1655 start++;
1656 }
1657
1658 return 0;
1659}
1660
1661static int do_move_pages_to_node(struct mm_struct *mm,
1662 struct list_head *pagelist, int node)
1663{
1664 int err;
a0976311
JK
1665 struct migration_target_control mtc = {
1666 .nid = node,
1667 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1668 };
a49bd4d7 1669
a0976311 1670 err = migrate_pages(pagelist, alloc_migration_target, NULL,
5ac95884 1671 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
a49bd4d7
MH
1672 if (err)
1673 putback_movable_pages(pagelist);
1674 return err;
742755a1
CL
1675}
1676
1677/*
a49bd4d7
MH
1678 * Resolves the given address to a struct page, isolates it from the LRU and
1679 * puts it to the given pagelist.
e0153fc2
YS
1680 * Returns:
1681 * errno - if the page cannot be found/isolated
1682 * 0 - when it doesn't have to be migrated because it is already on the
1683 * target node
1684 * 1 - when it has been queued
742755a1 1685 */
a49bd4d7
MH
1686static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1687 int node, struct list_head *pagelist, bool migrate_all)
742755a1 1688{
a49bd4d7
MH
1689 struct vm_area_struct *vma;
1690 struct page *page;
1691 unsigned int follflags;
742755a1 1692 int err;
742755a1 1693
d8ed45c5 1694 mmap_read_lock(mm);
a49bd4d7
MH
1695 err = -EFAULT;
1696 vma = find_vma(mm, addr);
1697 if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1698 goto out;
742755a1 1699
a49bd4d7
MH
1700 /* FOLL_DUMP to ignore special (like zero) pages */
1701 follflags = FOLL_GET | FOLL_DUMP;
a49bd4d7 1702 page = follow_page(vma, addr, follflags);
89f5b7da 1703
a49bd4d7
MH
1704 err = PTR_ERR(page);
1705 if (IS_ERR(page))
1706 goto out;
89f5b7da 1707
a49bd4d7
MH
1708 err = -ENOENT;
1709 if (!page)
1710 goto out;
742755a1 1711
a49bd4d7
MH
1712 err = 0;
1713 if (page_to_nid(page) == node)
1714 goto out_putpage;
742755a1 1715
a49bd4d7
MH
1716 err = -EACCES;
1717 if (page_mapcount(page) > 1 && !migrate_all)
1718 goto out_putpage;
742755a1 1719
a49bd4d7
MH
1720 if (PageHuge(page)) {
1721 if (PageHead(page)) {
1722 isolate_huge_page(page, pagelist);
e0153fc2 1723 err = 1;
e632a938 1724 }
a49bd4d7
MH
1725 } else {
1726 struct page *head;
e632a938 1727
e8db67eb
NH
1728 head = compound_head(page);
1729 err = isolate_lru_page(head);
cf608ac1 1730 if (err)
a49bd4d7 1731 goto out_putpage;
742755a1 1732
e0153fc2 1733 err = 1;
a49bd4d7
MH
1734 list_add_tail(&head->lru, pagelist);
1735 mod_node_page_state(page_pgdat(head),
9de4f22a 1736 NR_ISOLATED_ANON + page_is_file_lru(head),
6c357848 1737 thp_nr_pages(head));
a49bd4d7
MH
1738 }
1739out_putpage:
1740 /*
1741 * Either remove the duplicate refcount from
1742 * isolate_lru_page() or drop the page ref if it was
1743 * not isolated.
1744 */
1745 put_page(page);
1746out:
d8ed45c5 1747 mmap_read_unlock(mm);
742755a1
CL
1748 return err;
1749}
1750
7ca8783a
WY
1751static int move_pages_and_store_status(struct mm_struct *mm, int node,
1752 struct list_head *pagelist, int __user *status,
1753 int start, int i, unsigned long nr_pages)
1754{
1755 int err;
1756
5d7ae891
WY
1757 if (list_empty(pagelist))
1758 return 0;
1759
7ca8783a
WY
1760 err = do_move_pages_to_node(mm, pagelist, node);
1761 if (err) {
1762 /*
1763 * Positive err means the number of failed
1764 * pages to migrate. Since we are going to
1765 * abort and return the number of non-migrated
ab9dd4f8 1766 * pages, so need to include the rest of the
7ca8783a
WY
1767 * nr_pages that have not been attempted as
1768 * well.
1769 */
1770 if (err > 0)
1771 err += nr_pages - i - 1;
1772 return err;
1773 }
1774 return store_status(status, start, node, i - start);
1775}
1776
5e9a0f02
BG
1777/*
1778 * Migrate an array of page address onto an array of nodes and fill
1779 * the corresponding array of status.
1780 */
3268c63e 1781static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
5e9a0f02
BG
1782 unsigned long nr_pages,
1783 const void __user * __user *pages,
1784 const int __user *nodes,
1785 int __user *status, int flags)
1786{
a49bd4d7
MH
1787 int current_node = NUMA_NO_NODE;
1788 LIST_HEAD(pagelist);
1789 int start, i;
1790 int err = 0, err1;
35282a2d 1791
361a2a22 1792 lru_cache_disable();
35282a2d 1793
a49bd4d7
MH
1794 for (i = start = 0; i < nr_pages; i++) {
1795 const void __user *p;
1796 unsigned long addr;
1797 int node;
3140a227 1798
a49bd4d7
MH
1799 err = -EFAULT;
1800 if (get_user(p, pages + i))
1801 goto out_flush;
1802 if (get_user(node, nodes + i))
1803 goto out_flush;
057d3389 1804 addr = (unsigned long)untagged_addr(p);
a49bd4d7
MH
1805
1806 err = -ENODEV;
1807 if (node < 0 || node >= MAX_NUMNODES)
1808 goto out_flush;
1809 if (!node_state(node, N_MEMORY))
1810 goto out_flush;
5e9a0f02 1811
a49bd4d7
MH
1812 err = -EACCES;
1813 if (!node_isset(node, task_nodes))
1814 goto out_flush;
1815
1816 if (current_node == NUMA_NO_NODE) {
1817 current_node = node;
1818 start = i;
1819 } else if (node != current_node) {
7ca8783a
WY
1820 err = move_pages_and_store_status(mm, current_node,
1821 &pagelist, status, start, i, nr_pages);
a49bd4d7
MH
1822 if (err)
1823 goto out;
1824 start = i;
1825 current_node = node;
3140a227
BG
1826 }
1827
a49bd4d7
MH
1828 /*
1829 * Errors in the page lookup or isolation are not fatal and we simply
1830 * report them via status
1831 */
1832 err = add_page_for_migration(mm, addr, current_node,
1833 &pagelist, flags & MPOL_MF_MOVE_ALL);
e0153fc2 1834
d08221a0 1835 if (err > 0) {
e0153fc2
YS
1836 /* The page is successfully queued for migration */
1837 continue;
1838 }
3140a227 1839
d08221a0
WY
1840 /*
1841 * If the page is already on the target node (!err), store the
1842 * node, otherwise, store the err.
1843 */
1844 err = store_status(status, i, err ? : current_node, 1);
a49bd4d7
MH
1845 if (err)
1846 goto out_flush;
5e9a0f02 1847
7ca8783a
WY
1848 err = move_pages_and_store_status(mm, current_node, &pagelist,
1849 status, start, i, nr_pages);
4afdacec
WY
1850 if (err)
1851 goto out;
a49bd4d7 1852 current_node = NUMA_NO_NODE;
3140a227 1853 }
a49bd4d7
MH
1854out_flush:
1855 /* Make sure we do not overwrite the existing error */
7ca8783a
WY
1856 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1857 status, start, i, nr_pages);
dfe9aa23 1858 if (err >= 0)
a49bd4d7 1859 err = err1;
5e9a0f02 1860out:
361a2a22 1861 lru_cache_enable();
5e9a0f02
BG
1862 return err;
1863}
1864
742755a1 1865/*
2f007e74 1866 * Determine the nodes of an array of pages and store it in an array of status.
742755a1 1867 */
80bba129
BG
1868static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1869 const void __user **pages, int *status)
742755a1 1870{
2f007e74 1871 unsigned long i;
2f007e74 1872
d8ed45c5 1873 mmap_read_lock(mm);
742755a1 1874
2f007e74 1875 for (i = 0; i < nr_pages; i++) {
80bba129 1876 unsigned long addr = (unsigned long)(*pages);
742755a1
CL
1877 struct vm_area_struct *vma;
1878 struct page *page;
c095adbc 1879 int err = -EFAULT;
2f007e74 1880
059b8b48
LH
1881 vma = vma_lookup(mm, addr);
1882 if (!vma)
742755a1
CL
1883 goto set_status;
1884
d899844e
KS
1885 /* FOLL_DUMP to ignore special (like zero) pages */
1886 page = follow_page(vma, addr, FOLL_DUMP);
89f5b7da
LT
1887
1888 err = PTR_ERR(page);
1889 if (IS_ERR(page))
1890 goto set_status;
1891
d899844e 1892 err = page ? page_to_nid(page) : -ENOENT;
742755a1 1893set_status:
80bba129
BG
1894 *status = err;
1895
1896 pages++;
1897 status++;
1898 }
1899
d8ed45c5 1900 mmap_read_unlock(mm);
80bba129
BG
1901}
1902
5b1b561b
AB
1903static int get_compat_pages_array(const void __user *chunk_pages[],
1904 const void __user * __user *pages,
1905 unsigned long chunk_nr)
1906{
1907 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1908 compat_uptr_t p;
1909 int i;
1910
1911 for (i = 0; i < chunk_nr; i++) {
1912 if (get_user(p, pages32 + i))
1913 return -EFAULT;
1914 chunk_pages[i] = compat_ptr(p);
1915 }
1916
1917 return 0;
1918}
1919
80bba129
BG
1920/*
1921 * Determine the nodes of a user array of pages and store it in
1922 * a user array of status.
1923 */
1924static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1925 const void __user * __user *pages,
1926 int __user *status)
1927{
1928#define DO_PAGES_STAT_CHUNK_NR 16
1929 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1930 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
80bba129 1931
87b8d1ad
PA
1932 while (nr_pages) {
1933 unsigned long chunk_nr;
80bba129 1934
87b8d1ad
PA
1935 chunk_nr = nr_pages;
1936 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1937 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1938
5b1b561b
AB
1939 if (in_compat_syscall()) {
1940 if (get_compat_pages_array(chunk_pages, pages,
1941 chunk_nr))
1942 break;
1943 } else {
1944 if (copy_from_user(chunk_pages, pages,
1945 chunk_nr * sizeof(*chunk_pages)))
1946 break;
1947 }
80bba129
BG
1948
1949 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1950
87b8d1ad
PA
1951 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1952 break;
742755a1 1953
87b8d1ad
PA
1954 pages += chunk_nr;
1955 status += chunk_nr;
1956 nr_pages -= chunk_nr;
1957 }
1958 return nr_pages ? -EFAULT : 0;
742755a1
CL
1959}
1960
4dc200ce 1961static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
742755a1 1962{
742755a1 1963 struct task_struct *task;
742755a1 1964 struct mm_struct *mm;
742755a1 1965
4dc200ce
ML
1966 /*
1967 * There is no need to check if current process has the right to modify
1968 * the specified process when they are same.
1969 */
1970 if (!pid) {
1971 mmget(current->mm);
1972 *mem_nodes = cpuset_mems_allowed(current);
1973 return current->mm;
1974 }
742755a1
CL
1975
1976 /* Find the mm_struct */
a879bf58 1977 rcu_read_lock();
4dc200ce 1978 task = find_task_by_vpid(pid);
742755a1 1979 if (!task) {
a879bf58 1980 rcu_read_unlock();
4dc200ce 1981 return ERR_PTR(-ESRCH);
742755a1 1982 }
3268c63e 1983 get_task_struct(task);
742755a1
CL
1984
1985 /*
1986 * Check if this process has the right to modify the specified
197e7e52 1987 * process. Use the regular "ptrace_may_access()" checks.
742755a1 1988 */
197e7e52 1989 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
c69e8d9c 1990 rcu_read_unlock();
4dc200ce 1991 mm = ERR_PTR(-EPERM);
5e9a0f02 1992 goto out;
742755a1 1993 }
c69e8d9c 1994 rcu_read_unlock();
742755a1 1995
4dc200ce
ML
1996 mm = ERR_PTR(security_task_movememory(task));
1997 if (IS_ERR(mm))
5e9a0f02 1998 goto out;
4dc200ce 1999 *mem_nodes = cpuset_mems_allowed(task);
3268c63e 2000 mm = get_task_mm(task);
4dc200ce 2001out:
3268c63e 2002 put_task_struct(task);
6e8b09ea 2003 if (!mm)
4dc200ce
ML
2004 mm = ERR_PTR(-EINVAL);
2005 return mm;
2006}
2007
2008/*
2009 * Move a list of pages in the address space of the currently executing
2010 * process.
2011 */
2012static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2013 const void __user * __user *pages,
2014 const int __user *nodes,
2015 int __user *status, int flags)
2016{
2017 struct mm_struct *mm;
2018 int err;
2019 nodemask_t task_nodes;
2020
2021 /* Check flags */
2022 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
6e8b09ea
SL
2023 return -EINVAL;
2024
4dc200ce
ML
2025 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2026 return -EPERM;
2027
2028 mm = find_mm_struct(pid, &task_nodes);
2029 if (IS_ERR(mm))
2030 return PTR_ERR(mm);
2031
6e8b09ea
SL
2032 if (nodes)
2033 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2034 nodes, status, flags);
2035 else
2036 err = do_pages_stat(mm, nr_pages, pages, status);
742755a1 2037
742755a1
CL
2038 mmput(mm);
2039 return err;
2040}
742755a1 2041
7addf443
DB
2042SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2043 const void __user * __user *, pages,
2044 const int __user *, nodes,
2045 int __user *, status, int, flags)
2046{
2047 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2048}
2049
7039e1db
PZ
2050#ifdef CONFIG_NUMA_BALANCING
2051/*
2052 * Returns true if this is a safe migration target node for misplaced NUMA
2053 * pages. Currently it only checks the watermarks which crude
2054 */
2055static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
3abef4e6 2056 unsigned long nr_migrate_pages)
7039e1db
PZ
2057{
2058 int z;
599d0c95 2059
7039e1db
PZ
2060 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2061 struct zone *zone = pgdat->node_zones + z;
2062
2063 if (!populated_zone(zone))
2064 continue;
2065
7039e1db
PZ
2066 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2067 if (!zone_watermark_ok(zone, 0,
2068 high_wmark_pages(zone) +
2069 nr_migrate_pages,
bfe9d006 2070 ZONE_MOVABLE, 0))
7039e1db
PZ
2071 continue;
2072 return true;
2073 }
2074 return false;
2075}
2076
2077static struct page *alloc_misplaced_dst_page(struct page *page,
666feb21 2078 unsigned long data)
7039e1db
PZ
2079{
2080 int nid = (int) data;
2081 struct page *newpage;
2082
96db800f 2083 newpage = __alloc_pages_node(nid,
e97ca8e5
JW
2084 (GFP_HIGHUSER_MOVABLE |
2085 __GFP_THISNODE | __GFP_NOMEMALLOC |
2086 __GFP_NORETRY | __GFP_NOWARN) &
8479eba7 2087 ~__GFP_RECLAIM, 0);
bac0382c 2088
7039e1db
PZ
2089 return newpage;
2090}
2091
c5b5a3dd
YS
2092static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2093 unsigned long data)
2094{
2095 int nid = (int) data;
2096 struct page *newpage;
2097
2098 newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2099 HPAGE_PMD_ORDER);
2100 if (!newpage)
2101 goto out;
2102
2103 prep_transhuge_page(newpage);
2104
2105out:
2106 return newpage;
2107}
2108
1c30e017 2109static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
b32967ff 2110{
340ef390 2111 int page_lru;
2b9b624f 2112 int nr_pages = thp_nr_pages(page);
a8f60772 2113
309381fe 2114 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
3abef4e6 2115
662aeea7
YS
2116 /* Do not migrate THP mapped by multiple processes */
2117 if (PageTransHuge(page) && total_mapcount(page) > 1)
2118 return 0;
2119
7039e1db 2120 /* Avoid migrating to a node that is nearly full */
2b9b624f 2121 if (!migrate_balanced_pgdat(pgdat, nr_pages))
340ef390 2122 return 0;
7039e1db 2123
340ef390
HD
2124 if (isolate_lru_page(page))
2125 return 0;
7039e1db 2126
9de4f22a 2127 page_lru = page_is_file_lru(page);
599d0c95 2128 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2b9b624f 2129 nr_pages);
340ef390 2130
149c33e1 2131 /*
340ef390
HD
2132 * Isolating the page has taken another reference, so the
2133 * caller's reference can be safely dropped without the page
2134 * disappearing underneath us during migration.
149c33e1
MG
2135 */
2136 put_page(page);
340ef390 2137 return 1;
b32967ff
MG
2138}
2139
2140/*
2141 * Attempt to migrate a misplaced page to the specified destination
2142 * node. Caller is expected to have an elevated reference count on
2143 * the page that will be dropped by this function before returning.
2144 */
1bc115d8
MG
2145int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2146 int node)
b32967ff
MG
2147{
2148 pg_data_t *pgdat = NODE_DATA(node);
340ef390 2149 int isolated;
b32967ff
MG
2150 int nr_remaining;
2151 LIST_HEAD(migratepages);
c5b5a3dd
YS
2152 new_page_t *new;
2153 bool compound;
b5916c02 2154 int nr_pages = thp_nr_pages(page);
c5b5a3dd
YS
2155
2156 /*
2157 * PTE mapped THP or HugeTLB page can't reach here so the page could
2158 * be either base page or THP. And it must be head page if it is
2159 * THP.
2160 */
2161 compound = PageTransHuge(page);
2162
2163 if (compound)
2164 new = alloc_misplaced_dst_page_thp;
2165 else
2166 new = alloc_misplaced_dst_page;
b32967ff
MG
2167
2168 /*
1bc115d8
MG
2169 * Don't migrate file pages that are mapped in multiple processes
2170 * with execute permissions as they are probably shared libraries.
b32967ff 2171 */
7ee820ee
ML
2172 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2173 (vma->vm_flags & VM_EXEC))
b32967ff 2174 goto out;
b32967ff 2175
09a913a7
MG
2176 /*
2177 * Also do not migrate dirty pages as not all filesystems can move
2178 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2179 */
9de4f22a 2180 if (page_is_file_lru(page) && PageDirty(page))
09a913a7
MG
2181 goto out;
2182
b32967ff
MG
2183 isolated = numamigrate_isolate_page(pgdat, page);
2184 if (!isolated)
2185 goto out;
2186
2187 list_add(&page->lru, &migratepages);
c5b5a3dd 2188 nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
5ac95884 2189 MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
b32967ff 2190 if (nr_remaining) {
59c82b70
JK
2191 if (!list_empty(&migratepages)) {
2192 list_del(&page->lru);
c5fc5c3a
YS
2193 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2194 page_is_file_lru(page), -nr_pages);
59c82b70
JK
2195 putback_lru_page(page);
2196 }
b32967ff
MG
2197 isolated = 0;
2198 } else
c5fc5c3a 2199 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
7039e1db 2200 BUG_ON(!list_empty(&migratepages));
7039e1db 2201 return isolated;
340ef390
HD
2202
2203out:
2204 put_page(page);
2205 return 0;
7039e1db 2206}
220018d3 2207#endif /* CONFIG_NUMA_BALANCING */
7039e1db 2208#endif /* CONFIG_NUMA */
8763cb45 2209
9b2ed9cb 2210#ifdef CONFIG_DEVICE_PRIVATE
843e1be1 2211static int migrate_vma_collect_skip(unsigned long start,
8763cb45
JG
2212 unsigned long end,
2213 struct mm_walk *walk)
2214{
2215 struct migrate_vma *migrate = walk->private;
2216 unsigned long addr;
2217
872ea707 2218 for (addr = start; addr < end; addr += PAGE_SIZE) {
8315ada7 2219 migrate->dst[migrate->npages] = 0;
843e1be1 2220 migrate->src[migrate->npages++] = 0;
8315ada7
JG
2221 }
2222
2223 return 0;
2224}
2225
843e1be1 2226static int migrate_vma_collect_hole(unsigned long start,
8315ada7 2227 unsigned long end,
843e1be1 2228 __always_unused int depth,
8315ada7
JG
2229 struct mm_walk *walk)
2230{
2231 struct migrate_vma *migrate = walk->private;
2232 unsigned long addr;
2233
843e1be1
ML
2234 /* Only allow populating anonymous memory. */
2235 if (!vma_is_anonymous(walk->vma))
2236 return migrate_vma_collect_skip(start, end, walk);
2237
872ea707 2238 for (addr = start; addr < end; addr += PAGE_SIZE) {
843e1be1 2239 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
8763cb45 2240 migrate->dst[migrate->npages] = 0;
843e1be1
ML
2241 migrate->npages++;
2242 migrate->cpages++;
8763cb45
JG
2243 }
2244
2245 return 0;
2246}
2247
2248static int migrate_vma_collect_pmd(pmd_t *pmdp,
2249 unsigned long start,
2250 unsigned long end,
2251 struct mm_walk *walk)
2252{
2253 struct migrate_vma *migrate = walk->private;
2254 struct vm_area_struct *vma = walk->vma;
2255 struct mm_struct *mm = vma->vm_mm;
8c3328f1 2256 unsigned long addr = start, unmapped = 0;
8763cb45
JG
2257 spinlock_t *ptl;
2258 pte_t *ptep;
2259
2260again:
2261 if (pmd_none(*pmdp))
b7a16c7a 2262 return migrate_vma_collect_hole(start, end, -1, walk);
8763cb45
JG
2263
2264 if (pmd_trans_huge(*pmdp)) {
2265 struct page *page;
2266
2267 ptl = pmd_lock(mm, pmdp);
2268 if (unlikely(!pmd_trans_huge(*pmdp))) {
2269 spin_unlock(ptl);
2270 goto again;
2271 }
2272
2273 page = pmd_page(*pmdp);
2274 if (is_huge_zero_page(page)) {
2275 spin_unlock(ptl);
2276 split_huge_pmd(vma, pmdp, addr);
2277 if (pmd_trans_unstable(pmdp))
8315ada7 2278 return migrate_vma_collect_skip(start, end,
8763cb45
JG
2279 walk);
2280 } else {
2281 int ret;
2282
2283 get_page(page);
2284 spin_unlock(ptl);
2285 if (unlikely(!trylock_page(page)))
8315ada7 2286 return migrate_vma_collect_skip(start, end,
8763cb45
JG
2287 walk);
2288 ret = split_huge_page(page);
2289 unlock_page(page);
2290 put_page(page);
8315ada7
JG
2291 if (ret)
2292 return migrate_vma_collect_skip(start, end,
2293 walk);
2294 if (pmd_none(*pmdp))
b7a16c7a 2295 return migrate_vma_collect_hole(start, end, -1,
8763cb45
JG
2296 walk);
2297 }
2298 }
2299
2300 if (unlikely(pmd_bad(*pmdp)))
8315ada7 2301 return migrate_vma_collect_skip(start, end, walk);
8763cb45
JG
2302
2303 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
8c3328f1
JG
2304 arch_enter_lazy_mmu_mode();
2305
8763cb45 2306 for (; addr < end; addr += PAGE_SIZE, ptep++) {
800bb1c8 2307 unsigned long mpfn = 0, pfn;
8763cb45 2308 struct page *page;
8c3328f1 2309 swp_entry_t entry;
8763cb45
JG
2310 pte_t pte;
2311
2312 pte = *ptep;
8763cb45 2313
a5430dda 2314 if (pte_none(pte)) {
0744f280
RC
2315 if (vma_is_anonymous(vma)) {
2316 mpfn = MIGRATE_PFN_MIGRATE;
2317 migrate->cpages++;
2318 }
8763cb45
JG
2319 goto next;
2320 }
2321
a5430dda 2322 if (!pte_present(pte)) {
a5430dda
JG
2323 /*
2324 * Only care about unaddressable device page special
2325 * page table entry. Other special swap entries are not
2326 * migratable, and we ignore regular swapped page.
2327 */
2328 entry = pte_to_swp_entry(pte);
2329 if (!is_device_private_entry(entry))
2330 goto next;
2331
af5cdaf8 2332 page = pfn_swap_entry_to_page(entry);
5143192c
RC
2333 if (!(migrate->flags &
2334 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2335 page->pgmap->owner != migrate->pgmap_owner)
800bb1c8
CH
2336 goto next;
2337
06d462be
CH
2338 mpfn = migrate_pfn(page_to_pfn(page)) |
2339 MIGRATE_PFN_MIGRATE;
4dd845b5 2340 if (is_writable_device_private_entry(entry))
a5430dda
JG
2341 mpfn |= MIGRATE_PFN_WRITE;
2342 } else {
5143192c 2343 if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
800bb1c8 2344 goto next;
276f756d 2345 pfn = pte_pfn(pte);
8315ada7
JG
2346 if (is_zero_pfn(pfn)) {
2347 mpfn = MIGRATE_PFN_MIGRATE;
2348 migrate->cpages++;
8315ada7
JG
2349 goto next;
2350 }
25b2995a 2351 page = vm_normal_page(migrate->vma, addr, pte);
a5430dda
JG
2352 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2353 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2354 }
2355
8763cb45 2356 /* FIXME support THP */
8763cb45 2357 if (!page || !page->mapping || PageTransCompound(page)) {
276f756d 2358 mpfn = 0;
8763cb45
JG
2359 goto next;
2360 }
2361
2362 /*
2363 * By getting a reference on the page we pin it and that blocks
2364 * any kind of migration. Side effect is that it "freezes" the
2365 * pte.
2366 *
2367 * We drop this reference after isolating the page from the lru
2368 * for non device page (device page are not on the lru and thus
2369 * can't be dropped from it).
2370 */
2371 get_page(page);
2372 migrate->cpages++;
8763cb45 2373
8c3328f1
JG
2374 /*
2375 * Optimize for the common case where page is only mapped once
2376 * in one process. If we can lock the page, then we can safely
2377 * set up a special migration page table entry now.
2378 */
2379 if (trylock_page(page)) {
2380 pte_t swp_pte;
2381
2382 mpfn |= MIGRATE_PFN_LOCKED;
2383 ptep_get_and_clear(mm, addr, ptep);
2384
2385 /* Setup special migration page table entry */
4dd845b5
AP
2386 if (mpfn & MIGRATE_PFN_WRITE)
2387 entry = make_writable_migration_entry(
2388 page_to_pfn(page));
2389 else
2390 entry = make_readable_migration_entry(
2391 page_to_pfn(page));
8c3328f1 2392 swp_pte = swp_entry_to_pte(entry);
ad7df764
AP
2393 if (pte_present(pte)) {
2394 if (pte_soft_dirty(pte))
2395 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2396 if (pte_uffd_wp(pte))
2397 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2398 } else {
2399 if (pte_swp_soft_dirty(pte))
2400 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2401 if (pte_swp_uffd_wp(pte))
2402 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2403 }
8c3328f1
JG
2404 set_pte_at(mm, addr, ptep, swp_pte);
2405
2406 /*
2407 * This is like regular unmap: we remove the rmap and
2408 * drop page refcount. Page won't be freed, as we took
2409 * a reference just above.
2410 */
2411 page_remove_rmap(page, false);
2412 put_page(page);
a5430dda
JG
2413
2414 if (pte_present(pte))
2415 unmapped++;
8c3328f1
JG
2416 }
2417
8763cb45 2418next:
a5430dda 2419 migrate->dst[migrate->npages] = 0;
8763cb45
JG
2420 migrate->src[migrate->npages++] = mpfn;
2421 }
8c3328f1 2422 arch_leave_lazy_mmu_mode();
8763cb45
JG
2423 pte_unmap_unlock(ptep - 1, ptl);
2424
8c3328f1
JG
2425 /* Only flush the TLB if we actually modified any entries */
2426 if (unmapped)
2427 flush_tlb_range(walk->vma, start, end);
2428
8763cb45
JG
2429 return 0;
2430}
2431
7b86ac33
CH
2432static const struct mm_walk_ops migrate_vma_walk_ops = {
2433 .pmd_entry = migrate_vma_collect_pmd,
2434 .pte_hole = migrate_vma_collect_hole,
2435};
2436
8763cb45
JG
2437/*
2438 * migrate_vma_collect() - collect pages over a range of virtual addresses
2439 * @migrate: migrate struct containing all migration information
2440 *
2441 * This will walk the CPU page table. For each virtual address backed by a
2442 * valid page, it updates the src array and takes a reference on the page, in
2443 * order to pin the page until we lock it and unmap it.
2444 */
2445static void migrate_vma_collect(struct migrate_vma *migrate)
2446{
ac46d4f3 2447 struct mmu_notifier_range range;
8763cb45 2448
998427b3
RC
2449 /*
2450 * Note that the pgmap_owner is passed to the mmu notifier callback so
2451 * that the registered device driver can skip invalidating device
2452 * private page mappings that won't be migrated.
2453 */
6b49bf6d
AP
2454 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2455 migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
c1a06df6 2456 migrate->pgmap_owner);
ac46d4f3 2457 mmu_notifier_invalidate_range_start(&range);
8763cb45 2458
7b86ac33
CH
2459 walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2460 &migrate_vma_walk_ops, migrate);
2461
2462 mmu_notifier_invalidate_range_end(&range);
8763cb45
JG
2463 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2464}
2465
2466/*
2467 * migrate_vma_check_page() - check if page is pinned or not
2468 * @page: struct page to check
2469 *
2470 * Pinned pages cannot be migrated. This is the same test as in
2471 * migrate_page_move_mapping(), except that here we allow migration of a
2472 * ZONE_DEVICE page.
2473 */
2474static bool migrate_vma_check_page(struct page *page)
2475{
2476 /*
2477 * One extra ref because caller holds an extra reference, either from
2478 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2479 * a device page.
2480 */
2481 int extra = 1;
2482
2483 /*
2484 * FIXME support THP (transparent huge page), it is bit more complex to
2485 * check them than regular pages, because they can be mapped with a pmd
2486 * or with a pte (split pte mapping).
2487 */
2488 if (PageCompound(page))
2489 return false;
2490
a5430dda
JG
2491 /* Page from ZONE_DEVICE have one extra reference */
2492 if (is_zone_device_page(page)) {
2493 /*
2494 * Private page can never be pin as they have no valid pte and
2495 * GUP will fail for those. Yet if there is a pending migration
2496 * a thread might try to wait on the pte migration entry and
2497 * will bump the page reference count. Sadly there is no way to
2498 * differentiate a regular pin from migration wait. Hence to
2499 * avoid 2 racing thread trying to migrate back to CPU to enter
8958b249 2500 * infinite loop (one stopping migration because the other is
a5430dda
JG
2501 * waiting on pte migration entry). We always return true here.
2502 *
2503 * FIXME proper solution is to rework migration_entry_wait() so
2504 * it does not need to take a reference on page.
2505 */
25b2995a 2506 return is_device_private_page(page);
a5430dda
JG
2507 }
2508
df6ad698
JG
2509 /* For file back page */
2510 if (page_mapping(page))
2511 extra += 1 + page_has_private(page);
2512
8763cb45
JG
2513 if ((page_count(page) - extra) > page_mapcount(page))
2514 return false;
2515
2516 return true;
2517}
2518
2519/*
2520 * migrate_vma_prepare() - lock pages and isolate them from the lru
2521 * @migrate: migrate struct containing all migration information
2522 *
2523 * This locks pages that have been collected by migrate_vma_collect(). Once each
2524 * page is locked it is isolated from the lru (for non-device pages). Finally,
2525 * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2526 * migrated by concurrent kernel threads.
2527 */
2528static void migrate_vma_prepare(struct migrate_vma *migrate)
2529{
2530 const unsigned long npages = migrate->npages;
8c3328f1
JG
2531 const unsigned long start = migrate->start;
2532 unsigned long addr, i, restore = 0;
8763cb45 2533 bool allow_drain = true;
8763cb45
JG
2534
2535 lru_add_drain();
2536
2537 for (i = 0; (i < npages) && migrate->cpages; i++) {
2538 struct page *page = migrate_pfn_to_page(migrate->src[i]);
8c3328f1 2539 bool remap = true;
8763cb45
JG
2540
2541 if (!page)
2542 continue;
2543
8c3328f1
JG
2544 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2545 /*
2546 * Because we are migrating several pages there can be
2547 * a deadlock between 2 concurrent migration where each
2548 * are waiting on each other page lock.
2549 *
2550 * Make migrate_vma() a best effort thing and backoff
2551 * for any page we can not lock right away.
2552 */
2553 if (!trylock_page(page)) {
2554 migrate->src[i] = 0;
2555 migrate->cpages--;
2556 put_page(page);
2557 continue;
2558 }
2559 remap = false;
2560 migrate->src[i] |= MIGRATE_PFN_LOCKED;
8763cb45 2561 }
8763cb45 2562
a5430dda
JG
2563 /* ZONE_DEVICE pages are not on LRU */
2564 if (!is_zone_device_page(page)) {
2565 if (!PageLRU(page) && allow_drain) {
2566 /* Drain CPU's pagevec */
2567 lru_add_drain_all();
2568 allow_drain = false;
2569 }
8763cb45 2570
a5430dda
JG
2571 if (isolate_lru_page(page)) {
2572 if (remap) {
2573 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2574 migrate->cpages--;
2575 restore++;
2576 } else {
2577 migrate->src[i] = 0;
2578 unlock_page(page);
2579 migrate->cpages--;
2580 put_page(page);
2581 }
2582 continue;
8c3328f1 2583 }
a5430dda
JG
2584
2585 /* Drop the reference we took in collect */
2586 put_page(page);
8763cb45
JG
2587 }
2588
2589 if (!migrate_vma_check_page(page)) {
8c3328f1
JG
2590 if (remap) {
2591 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2592 migrate->cpages--;
2593 restore++;
8763cb45 2594
a5430dda
JG
2595 if (!is_zone_device_page(page)) {
2596 get_page(page);
2597 putback_lru_page(page);
2598 }
8c3328f1
JG
2599 } else {
2600 migrate->src[i] = 0;
2601 unlock_page(page);
2602 migrate->cpages--;
2603
a5430dda
JG
2604 if (!is_zone_device_page(page))
2605 putback_lru_page(page);
2606 else
2607 put_page(page);
8c3328f1 2608 }
8763cb45
JG
2609 }
2610 }
8c3328f1
JG
2611
2612 for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2613 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2614
2615 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2616 continue;
2617
2618 remove_migration_pte(page, migrate->vma, addr, page);
2619
2620 migrate->src[i] = 0;
2621 unlock_page(page);
2622 put_page(page);
2623 restore--;
2624 }
8763cb45
JG
2625}
2626
2627/*
2628 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2629 * @migrate: migrate struct containing all migration information
2630 *
2631 * Replace page mapping (CPU page table pte) with a special migration pte entry
2632 * and check again if it has been pinned. Pinned pages are restored because we
2633 * cannot migrate them.
2634 *
2635 * This is the last step before we call the device driver callback to allocate
2636 * destination memory and copy contents of original page over to new page.
2637 */
2638static void migrate_vma_unmap(struct migrate_vma *migrate)
2639{
8763cb45
JG
2640 const unsigned long npages = migrate->npages;
2641 const unsigned long start = migrate->start;
2642 unsigned long addr, i, restore = 0;
2643
2644 for (i = 0; i < npages; i++) {
2645 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2646
2647 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2648 continue;
2649
8c3328f1 2650 if (page_mapped(page)) {
a98a2f0c 2651 try_to_migrate(page, 0);
8c3328f1
JG
2652 if (page_mapped(page))
2653 goto restore;
8763cb45 2654 }
8c3328f1
JG
2655
2656 if (migrate_vma_check_page(page))
2657 continue;
2658
2659restore:
2660 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2661 migrate->cpages--;
2662 restore++;
8763cb45
JG
2663 }
2664
2665 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2666 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2667
2668 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2669 continue;
2670
2671 remove_migration_ptes(page, page, false);
2672
2673 migrate->src[i] = 0;
2674 unlock_page(page);
2675 restore--;
2676
a5430dda
JG
2677 if (is_zone_device_page(page))
2678 put_page(page);
2679 else
2680 putback_lru_page(page);
8763cb45
JG
2681 }
2682}
2683
a7d1f22b
CH
2684/**
2685 * migrate_vma_setup() - prepare to migrate a range of memory
eaf444de 2686 * @args: contains the vma, start, and pfns arrays for the migration
a7d1f22b
CH
2687 *
2688 * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2689 * without an error.
2690 *
2691 * Prepare to migrate a range of memory virtual address range by collecting all
2692 * the pages backing each virtual address in the range, saving them inside the
2693 * src array. Then lock those pages and unmap them. Once the pages are locked
2694 * and unmapped, check whether each page is pinned or not. Pages that aren't
2695 * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2696 * corresponding src array entry. Then restores any pages that are pinned, by
2697 * remapping and unlocking those pages.
2698 *
2699 * The caller should then allocate destination memory and copy source memory to
2700 * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2701 * flag set). Once these are allocated and copied, the caller must update each
2702 * corresponding entry in the dst array with the pfn value of the destination
2703 * page and with the MIGRATE_PFN_VALID and MIGRATE_PFN_LOCKED flags set
2704 * (destination pages must have their struct pages locked, via lock_page()).
2705 *
2706 * Note that the caller does not have to migrate all the pages that are marked
2707 * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2708 * device memory to system memory. If the caller cannot migrate a device page
2709 * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2710 * consequences for the userspace process, so it must be avoided if at all
2711 * possible.
2712 *
2713 * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2714 * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
f0953a1b
IM
2715 * allowing the caller to allocate device memory for those unbacked virtual
2716 * addresses. For this the caller simply has to allocate device memory and
a7d1f22b 2717 * properly set the destination entry like for regular migration. Note that
f0953a1b
IM
2718 * this can still fail, and thus inside the device driver you must check if the
2719 * migration was successful for those entries after calling migrate_vma_pages(),
a7d1f22b
CH
2720 * just like for regular migration.
2721 *
2722 * After that, the callers must call migrate_vma_pages() to go over each entry
2723 * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2724 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2725 * then migrate_vma_pages() to migrate struct page information from the source
2726 * struct page to the destination struct page. If it fails to migrate the
2727 * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2728 * src array.
2729 *
2730 * At this point all successfully migrated pages have an entry in the src
2731 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2732 * array entry with MIGRATE_PFN_VALID flag set.
2733 *
2734 * Once migrate_vma_pages() returns the caller may inspect which pages were
2735 * successfully migrated, and which were not. Successfully migrated pages will
2736 * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2737 *
2738 * It is safe to update device page table after migrate_vma_pages() because
c1e8d7c6 2739 * both destination and source page are still locked, and the mmap_lock is held
a7d1f22b
CH
2740 * in read mode (hence no one can unmap the range being migrated).
2741 *
2742 * Once the caller is done cleaning up things and updating its page table (if it
2743 * chose to do so, this is not an obligation) it finally calls
2744 * migrate_vma_finalize() to update the CPU page table to point to new pages
2745 * for successfully migrated pages or otherwise restore the CPU page table to
2746 * point to the original source pages.
2747 */
2748int migrate_vma_setup(struct migrate_vma *args)
2749{
2750 long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2751
2752 args->start &= PAGE_MASK;
2753 args->end &= PAGE_MASK;
2754 if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2755 (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2756 return -EINVAL;
2757 if (nr_pages <= 0)
2758 return -EINVAL;
2759 if (args->start < args->vma->vm_start ||
2760 args->start >= args->vma->vm_end)
2761 return -EINVAL;
2762 if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2763 return -EINVAL;
2764 if (!args->src || !args->dst)
2765 return -EINVAL;
2766
2767 memset(args->src, 0, sizeof(*args->src) * nr_pages);
2768 args->cpages = 0;
2769 args->npages = 0;
2770
2771 migrate_vma_collect(args);
2772
2773 if (args->cpages)
2774 migrate_vma_prepare(args);
2775 if (args->cpages)
2776 migrate_vma_unmap(args);
2777
2778 /*
2779 * At this point pages are locked and unmapped, and thus they have
2780 * stable content and can safely be copied to destination memory that
2781 * is allocated by the drivers.
2782 */
2783 return 0;
2784
2785}
2786EXPORT_SYMBOL(migrate_vma_setup);
2787
34290e2c
RC
2788/*
2789 * This code closely matches the code in:
2790 * __handle_mm_fault()
2791 * handle_pte_fault()
2792 * do_anonymous_page()
2793 * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2794 * private page.
2795 */
8315ada7
JG
2796static void migrate_vma_insert_page(struct migrate_vma *migrate,
2797 unsigned long addr,
2798 struct page *page,
d85c6db4 2799 unsigned long *src)
8315ada7
JG
2800{
2801 struct vm_area_struct *vma = migrate->vma;
2802 struct mm_struct *mm = vma->vm_mm;
8315ada7
JG
2803 bool flush = false;
2804 spinlock_t *ptl;
2805 pte_t entry;
2806 pgd_t *pgdp;
2807 p4d_t *p4dp;
2808 pud_t *pudp;
2809 pmd_t *pmdp;
2810 pte_t *ptep;
2811
2812 /* Only allow populating anonymous memory */
2813 if (!vma_is_anonymous(vma))
2814 goto abort;
2815
2816 pgdp = pgd_offset(mm, addr);
2817 p4dp = p4d_alloc(mm, pgdp, addr);
2818 if (!p4dp)
2819 goto abort;
2820 pudp = pud_alloc(mm, p4dp, addr);
2821 if (!pudp)
2822 goto abort;
2823 pmdp = pmd_alloc(mm, pudp, addr);
2824 if (!pmdp)
2825 goto abort;
2826
2827 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2828 goto abort;
2829
2830 /*
2831 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2832 * pte_offset_map() on pmds where a huge pmd might be created
2833 * from a different thread.
2834 *
3e4e28c5 2835 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
8315ada7
JG
2836 * parallel threads are excluded by other means.
2837 *
3e4e28c5 2838 * Here we only have mmap_read_lock(mm).
8315ada7 2839 */
4cf58924 2840 if (pte_alloc(mm, pmdp))
8315ada7
JG
2841 goto abort;
2842
2843 /* See the comment in pte_alloc_one_map() */
2844 if (unlikely(pmd_trans_unstable(pmdp)))
2845 goto abort;
2846
2847 if (unlikely(anon_vma_prepare(vma)))
2848 goto abort;
d9eb1ea2 2849 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
8315ada7
JG
2850 goto abort;
2851
2852 /*
2853 * The memory barrier inside __SetPageUptodate makes sure that
2854 * preceding stores to the page contents become visible before
2855 * the set_pte_at() write.
2856 */
2857 __SetPageUptodate(page);
2858
df6ad698
JG
2859 if (is_zone_device_page(page)) {
2860 if (is_device_private_page(page)) {
2861 swp_entry_t swp_entry;
2862
4dd845b5
AP
2863 if (vma->vm_flags & VM_WRITE)
2864 swp_entry = make_writable_device_private_entry(
2865 page_to_pfn(page));
2866 else
2867 swp_entry = make_readable_device_private_entry(
2868 page_to_pfn(page));
df6ad698 2869 entry = swp_entry_to_pte(swp_entry);
34f5e9b9
ML
2870 } else {
2871 /*
2872 * For now we only support migrating to un-addressable
2873 * device memory.
2874 */
2875 pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2876 goto abort;
df6ad698 2877 }
8315ada7
JG
2878 } else {
2879 entry = mk_pte(page, vma->vm_page_prot);
2880 if (vma->vm_flags & VM_WRITE)
2881 entry = pte_mkwrite(pte_mkdirty(entry));
2882 }
2883
2884 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2885
34290e2c
RC
2886 if (check_stable_address_space(mm))
2887 goto unlock_abort;
2888
8315ada7
JG
2889 if (pte_present(*ptep)) {
2890 unsigned long pfn = pte_pfn(*ptep);
2891
c23a0c99
RC
2892 if (!is_zero_pfn(pfn))
2893 goto unlock_abort;
8315ada7 2894 flush = true;
c23a0c99
RC
2895 } else if (!pte_none(*ptep))
2896 goto unlock_abort;
8315ada7
JG
2897
2898 /*
c23a0c99 2899 * Check for userfaultfd but do not deliver the fault. Instead,
8315ada7
JG
2900 * just back off.
2901 */
c23a0c99
RC
2902 if (userfaultfd_missing(vma))
2903 goto unlock_abort;
8315ada7
JG
2904
2905 inc_mm_counter(mm, MM_ANONPAGES);
be5d0a74 2906 page_add_new_anon_rmap(page, vma, addr, false);
8315ada7 2907 if (!is_zone_device_page(page))
b518154e 2908 lru_cache_add_inactive_or_unevictable(page, vma);
8315ada7
JG
2909 get_page(page);
2910
2911 if (flush) {
2912 flush_cache_page(vma, addr, pte_pfn(*ptep));
2913 ptep_clear_flush_notify(vma, addr, ptep);
2914 set_pte_at_notify(mm, addr, ptep, entry);
2915 update_mmu_cache(vma, addr, ptep);
2916 } else {
2917 /* No need to invalidate - it was non-present before */
2918 set_pte_at(mm, addr, ptep, entry);
2919 update_mmu_cache(vma, addr, ptep);
2920 }
2921
2922 pte_unmap_unlock(ptep, ptl);
2923 *src = MIGRATE_PFN_MIGRATE;
2924 return;
2925
c23a0c99
RC
2926unlock_abort:
2927 pte_unmap_unlock(ptep, ptl);
8315ada7
JG
2928abort:
2929 *src &= ~MIGRATE_PFN_MIGRATE;
2930}
2931
a7d1f22b 2932/**
8763cb45
JG
2933 * migrate_vma_pages() - migrate meta-data from src page to dst page
2934 * @migrate: migrate struct containing all migration information
2935 *
2936 * This migrates struct page meta-data from source struct page to destination
2937 * struct page. This effectively finishes the migration from source page to the
2938 * destination page.
2939 */
a7d1f22b 2940void migrate_vma_pages(struct migrate_vma *migrate)
8763cb45
JG
2941{
2942 const unsigned long npages = migrate->npages;
2943 const unsigned long start = migrate->start;
ac46d4f3
JG
2944 struct mmu_notifier_range range;
2945 unsigned long addr, i;
8315ada7 2946 bool notified = false;
8763cb45
JG
2947
2948 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2949 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2950 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2951 struct address_space *mapping;
2952 int r;
2953
8315ada7
JG
2954 if (!newpage) {
2955 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
8763cb45 2956 continue;
8315ada7
JG
2957 }
2958
2959 if (!page) {
c23a0c99 2960 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
8315ada7 2961 continue;
8315ada7 2962 if (!notified) {
8315ada7 2963 notified = true;
ac46d4f3 2964
6b49bf6d
AP
2965 mmu_notifier_range_init_owner(&range,
2966 MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2967 migrate->vma->vm_mm, addr, migrate->end,
5e5dda81 2968 migrate->pgmap_owner);
ac46d4f3 2969 mmu_notifier_invalidate_range_start(&range);
8315ada7
JG
2970 }
2971 migrate_vma_insert_page(migrate, addr, newpage,
d85c6db4 2972 &migrate->src[i]);
8763cb45 2973 continue;
8315ada7 2974 }
8763cb45
JG
2975
2976 mapping = page_mapping(page);
2977
a5430dda
JG
2978 if (is_zone_device_page(newpage)) {
2979 if (is_device_private_page(newpage)) {
2980 /*
2981 * For now only support private anonymous when
2982 * migrating to un-addressable device memory.
2983 */
2984 if (mapping) {
2985 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2986 continue;
2987 }
25b2995a 2988 } else {
a5430dda
JG
2989 /*
2990 * Other types of ZONE_DEVICE page are not
2991 * supported.
2992 */
2993 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2994 continue;
2995 }
2996 }
2997
8763cb45
JG
2998 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2999 if (r != MIGRATEPAGE_SUCCESS)
3000 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3001 }
8315ada7 3002
4645b9fe
JG
3003 /*
3004 * No need to double call mmu_notifier->invalidate_range() callback as
3005 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
3006 * did already call it.
3007 */
8315ada7 3008 if (notified)
ac46d4f3 3009 mmu_notifier_invalidate_range_only_end(&range);
8763cb45 3010}
a7d1f22b 3011EXPORT_SYMBOL(migrate_vma_pages);
8763cb45 3012
a7d1f22b 3013/**
8763cb45
JG
3014 * migrate_vma_finalize() - restore CPU page table entry
3015 * @migrate: migrate struct containing all migration information
3016 *
3017 * This replaces the special migration pte entry with either a mapping to the
3018 * new page if migration was successful for that page, or to the original page
3019 * otherwise.
3020 *
3021 * This also unlocks the pages and puts them back on the lru, or drops the extra
3022 * refcount, for device pages.
3023 */
a7d1f22b 3024void migrate_vma_finalize(struct migrate_vma *migrate)
8763cb45
JG
3025{
3026 const unsigned long npages = migrate->npages;
3027 unsigned long i;
3028
3029 for (i = 0; i < npages; i++) {
3030 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
3031 struct page *page = migrate_pfn_to_page(migrate->src[i]);
3032
8315ada7
JG
3033 if (!page) {
3034 if (newpage) {
3035 unlock_page(newpage);
3036 put_page(newpage);
3037 }
8763cb45 3038 continue;
8315ada7
JG
3039 }
3040
8763cb45
JG
3041 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
3042 if (newpage) {
3043 unlock_page(newpage);
3044 put_page(newpage);
3045 }
3046 newpage = page;
3047 }
3048
3049 remove_migration_ptes(page, newpage, false);
3050 unlock_page(page);
8763cb45 3051
a5430dda
JG
3052 if (is_zone_device_page(page))
3053 put_page(page);
3054 else
3055 putback_lru_page(page);
8763cb45
JG
3056
3057 if (newpage != page) {
3058 unlock_page(newpage);
a5430dda
JG
3059 if (is_zone_device_page(newpage))
3060 put_page(newpage);
3061 else
3062 putback_lru_page(newpage);
8763cb45
JG
3063 }
3064 }
3065}
a7d1f22b 3066EXPORT_SYMBOL(migrate_vma_finalize);
9b2ed9cb 3067#endif /* CONFIG_DEVICE_PRIVATE */
79c28a41 3068
76af6a05 3069#if defined(CONFIG_HOTPLUG_CPU)
79c28a41
DH
3070/* Disable reclaim-based migration. */
3071static void __disable_all_migrate_targets(void)
3072{
3073 int node;
3074
3075 for_each_online_node(node)
3076 node_demotion[node] = NUMA_NO_NODE;
3077}
3078
3079static void disable_all_migrate_targets(void)
3080{
3081 __disable_all_migrate_targets();
3082
3083 /*
3084 * Ensure that the "disable" is visible across the system.
3085 * Readers will see either a combination of before+disable
3086 * state or disable+after. They will never see before and
3087 * after state together.
3088 *
3089 * The before+after state together might have cycles and
3090 * could cause readers to do things like loop until this
3091 * function finishes. This ensures they can only see a
3092 * single "bad" read and would, for instance, only loop
3093 * once.
3094 */
3095 synchronize_rcu();
3096}
3097
3098/*
3099 * Find an automatic demotion target for 'node'.
3100 * Failing here is OK. It might just indicate
3101 * being at the end of a chain.
3102 */
3103static int establish_migrate_target(int node, nodemask_t *used)
3104{
3105 int migration_target;
3106
3107 /*
3108 * Can not set a migration target on a
3109 * node with it already set.
3110 *
3111 * No need for READ_ONCE() here since this
3112 * in the write path for node_demotion[].
3113 * This should be the only thread writing.
3114 */
3115 if (node_demotion[node] != NUMA_NO_NODE)
3116 return NUMA_NO_NODE;
3117
3118 migration_target = find_next_best_node(node, used);
3119 if (migration_target == NUMA_NO_NODE)
3120 return NUMA_NO_NODE;
3121
3122 node_demotion[node] = migration_target;
3123
3124 return migration_target;
3125}
3126
3127/*
3128 * When memory fills up on a node, memory contents can be
3129 * automatically migrated to another node instead of
3130 * discarded at reclaim.
3131 *
3132 * Establish a "migration path" which will start at nodes
3133 * with CPUs and will follow the priorities used to build the
3134 * page allocator zonelists.
3135 *
3136 * The difference here is that cycles must be avoided. If
3137 * node0 migrates to node1, then neither node1, nor anything
3138 * node1 migrates to can migrate to node0.
3139 *
3140 * This function can run simultaneously with readers of
3141 * node_demotion[]. However, it can not run simultaneously
3142 * with itself. Exclusion is provided by memory hotplug events
3143 * being single-threaded.
3144 */
3145static void __set_migration_target_nodes(void)
3146{
3147 nodemask_t next_pass = NODE_MASK_NONE;
3148 nodemask_t this_pass = NODE_MASK_NONE;
3149 nodemask_t used_targets = NODE_MASK_NONE;
3150 int node;
3151
3152 /*
3153 * Avoid any oddities like cycles that could occur
3154 * from changes in the topology. This will leave
3155 * a momentary gap when migration is disabled.
3156 */
3157 disable_all_migrate_targets();
3158
3159 /*
3160 * Allocations go close to CPUs, first. Assume that
3161 * the migration path starts at the nodes with CPUs.
3162 */
3163 next_pass = node_states[N_CPU];
3164again:
3165 this_pass = next_pass;
3166 next_pass = NODE_MASK_NONE;
3167 /*
3168 * To avoid cycles in the migration "graph", ensure
3169 * that migration sources are not future targets by
3170 * setting them in 'used_targets'. Do this only
3171 * once per pass so that multiple source nodes can
3172 * share a target node.
3173 *
3174 * 'used_targets' will become unavailable in future
3175 * passes. This limits some opportunities for
3176 * multiple source nodes to share a destination.
3177 */
3178 nodes_or(used_targets, used_targets, this_pass);
3179 for_each_node_mask(node, this_pass) {
3180 int target_node = establish_migrate_target(node, &used_targets);
3181
3182 if (target_node == NUMA_NO_NODE)
3183 continue;
3184
3185 /*
3186 * Visit targets from this pass in the next pass.
3187 * Eventually, every node will have been part of
3188 * a pass, and will become set in 'used_targets'.
3189 */
3190 node_set(target_node, next_pass);
3191 }
3192 /*
3193 * 'next_pass' contains nodes which became migration
3194 * targets in this pass. Make additional passes until
3195 * no more migrations targets are available.
3196 */
3197 if (!nodes_empty(next_pass))
3198 goto again;
3199}
3200
3201/*
3202 * For callers that do not hold get_online_mems() already.
3203 */
79c28a41
DH
3204static void set_migration_target_nodes(void)
3205{
3206 get_online_mems();
3207 __set_migration_target_nodes();
3208 put_online_mems();
3209}
884a6e5d 3210
884a6e5d
DH
3211/*
3212 * This leaves migrate-on-reclaim transiently disabled between
3213 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
3214 * whether reclaim-based migration is enabled or not, which
3215 * ensures that the user can turn reclaim-based migration at
3216 * any time without needing to recalculate migration targets.
3217 *
3218 * These callbacks already hold get_online_mems(). That is why
3219 * __set_migration_target_nodes() can be used as opposed to
3220 * set_migration_target_nodes().
3221 */
3222static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
295be91f 3223 unsigned long action, void *_arg)
884a6e5d 3224{
295be91f
DH
3225 struct memory_notify *arg = _arg;
3226
3227 /*
3228 * Only update the node migration order when a node is
3229 * changing status, like online->offline. This avoids
3230 * the overhead of synchronize_rcu() in most cases.
3231 */
3232 if (arg->status_change_nid < 0)
3233 return notifier_from_errno(0);
3234
884a6e5d
DH
3235 switch (action) {
3236 case MEM_GOING_OFFLINE:
3237 /*
3238 * Make sure there are not transient states where
3239 * an offline node is a migration target. This
3240 * will leave migration disabled until the offline
3241 * completes and the MEM_OFFLINE case below runs.
3242 */
3243 disable_all_migrate_targets();
3244 break;
3245 case MEM_OFFLINE:
3246 case MEM_ONLINE:
3247 /*
3248 * Recalculate the target nodes once the node
3249 * reaches its final state (online or offline).
3250 */
3251 __set_migration_target_nodes();
3252 break;
3253 case MEM_CANCEL_OFFLINE:
3254 /*
3255 * MEM_GOING_OFFLINE disabled all the migration
3256 * targets. Reenable them.
3257 */
3258 __set_migration_target_nodes();
3259 break;
3260 case MEM_GOING_ONLINE:
3261 case MEM_CANCEL_ONLINE:
3262 break;
3263 }
3264
3265 return notifier_from_errno(0);
3266}
3267
76af6a05
DH
3268/*
3269 * React to hotplug events that might affect the migration targets
3270 * like events that online or offline NUMA nodes.
3271 *
3272 * The ordering is also currently dependent on which nodes have
3273 * CPUs. That means we need CPU on/offline notification too.
3274 */
3275static int migration_online_cpu(unsigned int cpu)
3276{
3277 set_migration_target_nodes();
3278 return 0;
3279}
3280
3281static int migration_offline_cpu(unsigned int cpu)
3282{
3283 set_migration_target_nodes();
3284 return 0;
3285}
3286
884a6e5d
DH
3287static int __init migrate_on_reclaim_init(void)
3288{
3289 int ret;
3290
a6a0251c
HY
3291 ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3292 NULL, migration_offline_cpu);
884a6e5d
DH
3293 /*
3294 * In the unlikely case that this fails, the automatic
3295 * migration targets may become suboptimal for nodes
3296 * where N_CPU changes. With such a small impact in a
3297 * rare case, do not bother trying to do anything special.
3298 */
3299 WARN_ON(ret < 0);
a6a0251c
HY
3300 ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3301 migration_online_cpu, NULL);
3302 WARN_ON(ret < 0);
884a6e5d
DH
3303
3304 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3305 return 0;
3306}
3307late_initcall(migrate_on_reclaim_init);
76af6a05 3308#endif /* CONFIG_HOTPLUG_CPU */