]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - mm/migrate.c
vhost: make sure used idx is seen before log in vhost_add_used_n()
[mirror_ubuntu-bionic-kernel.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>
290408d4 37#include <linux/hugetlb.h>
8e6ac7fa 38#include <linux/hugetlb_cgroup.h>
5a0e3ad6 39#include <linux/gfp.h>
df6ad698 40#include <linux/pfn_t.h>
a5430dda 41#include <linux/memremap.h>
8315ada7 42#include <linux/userfaultfd_k.h>
bf6bddf1 43#include <linux/balloon_compaction.h>
f714f4f2 44#include <linux/mmu_notifier.h>
33c3fc71 45#include <linux/page_idle.h>
d435edca 46#include <linux/page_owner.h>
6e84f315 47#include <linux/sched/mm.h>
197e7e52 48#include <linux/ptrace.h>
b20a3503 49
0d1836c3
MN
50#include <asm/tlbflush.h>
51
7b2a2d4a
MG
52#define CREATE_TRACE_POINTS
53#include <trace/events/migrate.h>
54
b20a3503
CL
55#include "internal.h"
56
b20a3503 57/*
742755a1 58 * migrate_prep() needs to be called before we start compiling a list of pages
748446bb
MG
59 * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
60 * undesirable, use migrate_prep_local()
b20a3503
CL
61 */
62int migrate_prep(void)
63{
b20a3503
CL
64 /*
65 * Clear the LRU lists so pages can be isolated.
66 * Note that pages may be moved off the LRU after we have
67 * drained them. Those pages will fail to migrate like other
68 * pages that may be busy.
69 */
70 lru_add_drain_all();
71
72 return 0;
73}
74
748446bb
MG
75/* Do the necessary work of migrate_prep but not if it involves other CPUs */
76int migrate_prep_local(void)
77{
78 lru_add_drain();
79
80 return 0;
81}
82
9e5bcd61 83int isolate_movable_page(struct page *page, isolate_mode_t mode)
bda807d4
MK
84{
85 struct address_space *mapping;
86
87 /*
88 * Avoid burning cycles with pages that are yet under __free_pages(),
89 * or just got freed under us.
90 *
91 * In case we 'win' a race for a movable page being freed under us and
92 * raise its refcount preventing __free_pages() from doing its job
93 * the put_page() at the end of this block will take care of
94 * release this page, thus avoiding a nasty leakage.
95 */
96 if (unlikely(!get_page_unless_zero(page)))
97 goto out;
98
99 /*
100 * Check PageMovable before holding a PG_lock because page's owner
101 * assumes anybody doesn't touch PG_lock of newly allocated page
102 * so unconditionally grapping the lock ruins page's owner side.
103 */
104 if (unlikely(!__PageMovable(page)))
105 goto out_putpage;
106 /*
107 * As movable pages are not isolated from LRU lists, concurrent
108 * compaction threads can race against page migration functions
109 * as well as race against the releasing a page.
110 *
111 * In order to avoid having an already isolated movable page
112 * being (wrongly) re-isolated while it is under migration,
113 * or to avoid attempting to isolate pages being released,
114 * lets be sure we have the page lock
115 * before proceeding with the movable page isolation steps.
116 */
117 if (unlikely(!trylock_page(page)))
118 goto out_putpage;
119
120 if (!PageMovable(page) || PageIsolated(page))
121 goto out_no_isolated;
122
123 mapping = page_mapping(page);
124 VM_BUG_ON_PAGE(!mapping, page);
125
126 if (!mapping->a_ops->isolate_page(page, mode))
127 goto out_no_isolated;
128
129 /* Driver shouldn't use PG_isolated bit of page->flags */
130 WARN_ON_ONCE(PageIsolated(page));
131 __SetPageIsolated(page);
132 unlock_page(page);
133
9e5bcd61 134 return 0;
bda807d4
MK
135
136out_no_isolated:
137 unlock_page(page);
138out_putpage:
139 put_page(page);
140out:
9e5bcd61 141 return -EBUSY;
bda807d4
MK
142}
143
144/* It should be called on page which is PG_movable */
145void putback_movable_page(struct page *page)
146{
147 struct address_space *mapping;
148
149 VM_BUG_ON_PAGE(!PageLocked(page), page);
150 VM_BUG_ON_PAGE(!PageMovable(page), page);
151 VM_BUG_ON_PAGE(!PageIsolated(page), page);
152
153 mapping = page_mapping(page);
154 mapping->a_ops->putback_page(page);
155 __ClearPageIsolated(page);
156}
157
5733c7d1
RA
158/*
159 * Put previously isolated pages back onto the appropriate lists
160 * from where they were once taken off for compaction/migration.
161 *
59c82b70
JK
162 * This function shall be used whenever the isolated pageset has been
163 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
164 * and isolate_huge_page().
5733c7d1
RA
165 */
166void putback_movable_pages(struct list_head *l)
167{
168 struct page *page;
169 struct page *page2;
170
b20a3503 171 list_for_each_entry_safe(page, page2, l, lru) {
31caf665
NH
172 if (unlikely(PageHuge(page))) {
173 putback_active_hugepage(page);
174 continue;
175 }
e24f0b8f 176 list_del(&page->lru);
bda807d4
MK
177 /*
178 * We isolated non-lru movable page so here we can use
179 * __PageMovable because LRU page's mapping cannot have
180 * PAGE_MAPPING_MOVABLE.
181 */
b1123ea6 182 if (unlikely(__PageMovable(page))) {
bda807d4
MK
183 VM_BUG_ON_PAGE(!PageIsolated(page), page);
184 lock_page(page);
185 if (PageMovable(page))
186 putback_movable_page(page);
187 else
188 __ClearPageIsolated(page);
189 unlock_page(page);
190 put_page(page);
191 } else {
e8db67eb
NH
192 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
193 page_is_file_cache(page), -hpage_nr_pages(page));
fc280fe8 194 putback_lru_page(page);
bda807d4 195 }
b20a3503 196 }
b20a3503
CL
197}
198
0697212a
CL
199/*
200 * Restore a potential migration pte to a working pte entry
201 */
e4b82222 202static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
e9995ef9 203 unsigned long addr, void *old)
0697212a 204{
3fe87967
KS
205 struct page_vma_mapped_walk pvmw = {
206 .page = old,
207 .vma = vma,
208 .address = addr,
209 .flags = PVMW_SYNC | PVMW_MIGRATION,
210 };
211 struct page *new;
212 pte_t pte;
0697212a 213 swp_entry_t entry;
0697212a 214
3fe87967
KS
215 VM_BUG_ON_PAGE(PageTail(page), page);
216 while (page_vma_mapped_walk(&pvmw)) {
4b0ece6f
NH
217 if (PageKsm(page))
218 new = page;
219 else
220 new = page - pvmw.page->index +
221 linear_page_index(vma, pvmw.address);
0697212a 222
616b8371
ZY
223#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
224 /* PMD-mapped THP migration entry */
225 if (!pvmw.pte) {
226 VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
227 remove_migration_pmd(&pvmw, new);
228 continue;
229 }
230#endif
231
3fe87967
KS
232 get_page(new);
233 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
234 if (pte_swp_soft_dirty(*pvmw.pte))
235 pte = pte_mksoft_dirty(pte);
0697212a 236
3fe87967
KS
237 /*
238 * Recheck VMA as permissions can change since migration started
239 */
240 entry = pte_to_swp_entry(*pvmw.pte);
241 if (is_write_migration_entry(entry))
242 pte = maybe_mkwrite(pte, vma);
d3cb8bf6 243
df6ad698
JG
244 if (unlikely(is_zone_device_page(new))) {
245 if (is_device_private_page(new)) {
246 entry = make_device_private_entry(new, pte_write(pte));
247 pte = swp_entry_to_pte(entry);
248 } else if (is_device_public_page(new)) {
249 pte = pte_mkdevmap(pte);
250 flush_dcache_page(new);
251 }
a5430dda
JG
252 } else
253 flush_dcache_page(new);
254
3ef8fd7f 255#ifdef CONFIG_HUGETLB_PAGE
3fe87967
KS
256 if (PageHuge(new)) {
257 pte = pte_mkhuge(pte);
258 pte = arch_make_huge_pte(pte, vma, new, 0);
383321ab 259 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
3fe87967
KS
260 if (PageAnon(new))
261 hugepage_add_anon_rmap(new, vma, pvmw.address);
262 else
263 page_dup_rmap(new, true);
383321ab
AK
264 } else
265#endif
266 {
267 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
04e62a29 268
383321ab
AK
269 if (PageAnon(new))
270 page_add_anon_rmap(new, vma, pvmw.address, false);
271 else
272 page_add_file_rmap(new, false);
273 }
3fe87967
KS
274 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
275 mlock_vma_page(new);
276
0e1e3cac
KS
277 if (PageTransHuge(page) && PageMlocked(page))
278 clear_page_mlock(page);
279
3fe87967
KS
280 /* No need to invalidate - it was non-present before */
281 update_mmu_cache(vma, pvmw.address, pvmw.pte);
282 }
51afb12b 283
e4b82222 284 return true;
0697212a
CL
285}
286
04e62a29
CL
287/*
288 * Get rid of all migration entries and replace them by
289 * references to the indicated page.
290 */
e388466d 291void remove_migration_ptes(struct page *old, struct page *new, bool locked)
04e62a29 292{
051ac83a
JK
293 struct rmap_walk_control rwc = {
294 .rmap_one = remove_migration_pte,
295 .arg = old,
296 };
297
e388466d
KS
298 if (locked)
299 rmap_walk_locked(new, &rwc);
300 else
301 rmap_walk(new, &rwc);
04e62a29
CL
302}
303
0697212a
CL
304/*
305 * Something used the pte of a page under migration. We need to
306 * get to the page and wait until migration is finished.
307 * When we return from this function the fault will be retried.
0697212a 308 */
e66f17ff 309void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
30dad309 310 spinlock_t *ptl)
0697212a 311{
30dad309 312 pte_t pte;
0697212a
CL
313 swp_entry_t entry;
314 struct page *page;
315
30dad309 316 spin_lock(ptl);
0697212a
CL
317 pte = *ptep;
318 if (!is_swap_pte(pte))
319 goto out;
320
321 entry = pte_to_swp_entry(pte);
322 if (!is_migration_entry(entry))
323 goto out;
324
325 page = migration_entry_to_page(entry);
326
e286781d
NP
327 /*
328 * Once radix-tree replacement of page migration started, page_count
329 * *must* be zero. And, we don't want to call wait_on_page_locked()
330 * against a page without get_page().
331 * So, we use get_page_unless_zero(), here. Even failed, page fault
332 * will occur again.
333 */
334 if (!get_page_unless_zero(page))
335 goto out;
0697212a
CL
336 pte_unmap_unlock(ptep, ptl);
337 wait_on_page_locked(page);
338 put_page(page);
339 return;
340out:
341 pte_unmap_unlock(ptep, ptl);
342}
343
30dad309
NH
344void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
345 unsigned long address)
346{
347 spinlock_t *ptl = pte_lockptr(mm, pmd);
348 pte_t *ptep = pte_offset_map(pmd, address);
349 __migration_entry_wait(mm, ptep, ptl);
350}
351
cb900f41
KS
352void migration_entry_wait_huge(struct vm_area_struct *vma,
353 struct mm_struct *mm, pte_t *pte)
30dad309 354{
cb900f41 355 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
30dad309
NH
356 __migration_entry_wait(mm, pte, ptl);
357}
358
616b8371
ZY
359#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
360void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
361{
362 spinlock_t *ptl;
363 struct page *page;
364
365 ptl = pmd_lock(mm, pmd);
366 if (!is_pmd_migration_entry(*pmd))
367 goto unlock;
368 page = migration_entry_to_page(pmd_to_swp_entry(*pmd));
369 if (!get_page_unless_zero(page))
370 goto unlock;
371 spin_unlock(ptl);
372 wait_on_page_locked(page);
373 put_page(page);
374 return;
375unlock:
376 spin_unlock(ptl);
377}
378#endif
379
b969c4ab
MG
380#ifdef CONFIG_BLOCK
381/* Returns true if all buffers are successfully locked */
a6bc32b8
MG
382static bool buffer_migrate_lock_buffers(struct buffer_head *head,
383 enum migrate_mode mode)
b969c4ab
MG
384{
385 struct buffer_head *bh = head;
386
387 /* Simple case, sync compaction */
a6bc32b8 388 if (mode != MIGRATE_ASYNC) {
b969c4ab
MG
389 do {
390 get_bh(bh);
391 lock_buffer(bh);
392 bh = bh->b_this_page;
393
394 } while (bh != head);
395
396 return true;
397 }
398
399 /* async case, we cannot block on lock_buffer so use trylock_buffer */
400 do {
401 get_bh(bh);
402 if (!trylock_buffer(bh)) {
403 /*
404 * We failed to lock the buffer and cannot stall in
405 * async migration. Release the taken locks
406 */
407 struct buffer_head *failed_bh = bh;
408 put_bh(failed_bh);
409 bh = head;
410 while (bh != failed_bh) {
411 unlock_buffer(bh);
412 put_bh(bh);
413 bh = bh->b_this_page;
414 }
415 return false;
416 }
417
418 bh = bh->b_this_page;
419 } while (bh != head);
420 return true;
421}
422#else
423static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
a6bc32b8 424 enum migrate_mode mode)
b969c4ab
MG
425{
426 return true;
427}
428#endif /* CONFIG_BLOCK */
429
b20a3503 430/*
c3fcf8a5 431 * Replace the page in the mapping.
5b5c7120
CL
432 *
433 * The number of remaining references must be:
434 * 1 for anonymous pages without a mapping
435 * 2 for pages with a mapping
266cf658 436 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
b20a3503 437 */
36bc08cc 438int migrate_page_move_mapping(struct address_space *mapping,
b969c4ab 439 struct page *newpage, struct page *page,
8e321fef
BL
440 struct buffer_head *head, enum migrate_mode mode,
441 int extra_count)
b20a3503 442{
42cb14b1
HD
443 struct zone *oldzone, *newzone;
444 int dirty;
8e321fef 445 int expected_count = 1 + extra_count;
7cf9c2c7 446 void **pslot;
b20a3503 447
8763cb45 448 /*
df6ad698
JG
449 * Device public or private pages have an extra refcount as they are
450 * ZONE_DEVICE pages.
8763cb45 451 */
df6ad698
JG
452 expected_count += is_device_private_page(page);
453 expected_count += is_device_public_page(page);
8763cb45 454
6c5240ae 455 if (!mapping) {
0e8c7d0f 456 /* Anonymous page without mapping */
8e321fef 457 if (page_count(page) != expected_count)
6c5240ae 458 return -EAGAIN;
cf4b769a
HD
459
460 /* No turning back from here */
cf4b769a
HD
461 newpage->index = page->index;
462 newpage->mapping = page->mapping;
463 if (PageSwapBacked(page))
fa9949da 464 __SetPageSwapBacked(newpage);
cf4b769a 465
78bd5209 466 return MIGRATEPAGE_SUCCESS;
6c5240ae
CL
467 }
468
42cb14b1
HD
469 oldzone = page_zone(page);
470 newzone = page_zone(newpage);
471
19fd6231 472 spin_lock_irq(&mapping->tree_lock);
b20a3503 473
7cf9c2c7
NP
474 pslot = radix_tree_lookup_slot(&mapping->page_tree,
475 page_index(page));
b20a3503 476
8e321fef 477 expected_count += 1 + page_has_private(page);
e286781d 478 if (page_count(page) != expected_count ||
29c1f677 479 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
19fd6231 480 spin_unlock_irq(&mapping->tree_lock);
e23ca00b 481 return -EAGAIN;
b20a3503
CL
482 }
483
fe896d18 484 if (!page_ref_freeze(page, expected_count)) {
19fd6231 485 spin_unlock_irq(&mapping->tree_lock);
e286781d
NP
486 return -EAGAIN;
487 }
488
b969c4ab
MG
489 /*
490 * In the async migration case of moving a page with buffers, lock the
491 * buffers using trylock before the mapping is moved. If the mapping
492 * was moved, we later failed to lock the buffers and could not move
493 * the mapping back due to an elevated page count, we would have to
494 * block waiting on other references to be dropped.
495 */
a6bc32b8
MG
496 if (mode == MIGRATE_ASYNC && head &&
497 !buffer_migrate_lock_buffers(head, mode)) {
fe896d18 498 page_ref_unfreeze(page, expected_count);
b969c4ab
MG
499 spin_unlock_irq(&mapping->tree_lock);
500 return -EAGAIN;
501 }
502
b20a3503 503 /*
cf4b769a
HD
504 * Now we know that no one else is looking at the page:
505 * no turning back from here.
b20a3503 506 */
cf4b769a
HD
507 newpage->index = page->index;
508 newpage->mapping = page->mapping;
7cf9c2c7 509 get_page(newpage); /* add cache reference */
6326fec1
NP
510 if (PageSwapBacked(page)) {
511 __SetPageSwapBacked(newpage);
512 if (PageSwapCache(page)) {
513 SetPageSwapCache(newpage);
514 set_page_private(newpage, page_private(page));
515 }
516 } else {
517 VM_BUG_ON_PAGE(PageSwapCache(page), page);
b20a3503
CL
518 }
519
42cb14b1
HD
520 /* Move dirty while page refs frozen and newpage not yet exposed */
521 dirty = PageDirty(page);
522 if (dirty) {
523 ClearPageDirty(page);
524 SetPageDirty(newpage);
525 }
526
6d75f366 527 radix_tree_replace_slot(&mapping->page_tree, pslot, newpage);
7cf9c2c7
NP
528
529 /*
937a94c9
JG
530 * Drop cache reference from old page by unfreezing
531 * to one less reference.
7cf9c2c7
NP
532 * We know this isn't the last reference.
533 */
fe896d18 534 page_ref_unfreeze(page, expected_count - 1);
7cf9c2c7 535
42cb14b1
HD
536 spin_unlock(&mapping->tree_lock);
537 /* Leave irq disabled to prevent preemption while updating stats */
538
0e8c7d0f
CL
539 /*
540 * If moved to a different zone then also account
541 * the page for that zone. Other VM counters will be
542 * taken care of when we establish references to the
543 * new page and drop references to the old page.
544 *
545 * Note that anonymous pages are accounted for
4b9d0fab 546 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
0e8c7d0f
CL
547 * are mapped to swap space.
548 */
42cb14b1 549 if (newzone != oldzone) {
11fb9989
MG
550 __dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES);
551 __inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES);
42cb14b1 552 if (PageSwapBacked(page) && !PageSwapCache(page)) {
11fb9989
MG
553 __dec_node_state(oldzone->zone_pgdat, NR_SHMEM);
554 __inc_node_state(newzone->zone_pgdat, NR_SHMEM);
42cb14b1
HD
555 }
556 if (dirty && mapping_cap_account_dirty(mapping)) {
11fb9989 557 __dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY);
5a1c84b4 558 __dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING);
11fb9989 559 __inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY);
5a1c84b4 560 __inc_zone_state(newzone, NR_ZONE_WRITE_PENDING);
42cb14b1 561 }
4b02108a 562 }
42cb14b1 563 local_irq_enable();
b20a3503 564
78bd5209 565 return MIGRATEPAGE_SUCCESS;
b20a3503 566}
1118dce7 567EXPORT_SYMBOL(migrate_page_move_mapping);
b20a3503 568
290408d4
NH
569/*
570 * The expected number of remaining references is the same as that
571 * of migrate_page_move_mapping().
572 */
573int migrate_huge_page_move_mapping(struct address_space *mapping,
574 struct page *newpage, struct page *page)
575{
576 int expected_count;
577 void **pslot;
578
290408d4
NH
579 spin_lock_irq(&mapping->tree_lock);
580
581 pslot = radix_tree_lookup_slot(&mapping->page_tree,
582 page_index(page));
583
584 expected_count = 2 + page_has_private(page);
585 if (page_count(page) != expected_count ||
29c1f677 586 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
290408d4
NH
587 spin_unlock_irq(&mapping->tree_lock);
588 return -EAGAIN;
589 }
590
fe896d18 591 if (!page_ref_freeze(page, expected_count)) {
290408d4
NH
592 spin_unlock_irq(&mapping->tree_lock);
593 return -EAGAIN;
594 }
595
cf4b769a
HD
596 newpage->index = page->index;
597 newpage->mapping = page->mapping;
6a93ca8f 598
290408d4
NH
599 get_page(newpage);
600
6d75f366 601 radix_tree_replace_slot(&mapping->page_tree, pslot, newpage);
290408d4 602
fe896d18 603 page_ref_unfreeze(page, expected_count - 1);
290408d4
NH
604
605 spin_unlock_irq(&mapping->tree_lock);
6a93ca8f 606
78bd5209 607 return MIGRATEPAGE_SUCCESS;
290408d4
NH
608}
609
30b0a105
DH
610/*
611 * Gigantic pages are so large that we do not guarantee that page++ pointer
612 * arithmetic will work across the entire page. We need something more
613 * specialized.
614 */
615static void __copy_gigantic_page(struct page *dst, struct page *src,
616 int nr_pages)
617{
618 int i;
619 struct page *dst_base = dst;
620 struct page *src_base = src;
621
622 for (i = 0; i < nr_pages; ) {
623 cond_resched();
624 copy_highpage(dst, src);
625
626 i++;
627 dst = mem_map_next(dst, dst_base, i);
628 src = mem_map_next(src, src_base, i);
629 }
630}
631
632static void copy_huge_page(struct page *dst, struct page *src)
633{
634 int i;
635 int nr_pages;
636
637 if (PageHuge(src)) {
638 /* hugetlbfs page */
639 struct hstate *h = page_hstate(src);
640 nr_pages = pages_per_huge_page(h);
641
642 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) {
643 __copy_gigantic_page(dst, src, nr_pages);
644 return;
645 }
646 } else {
647 /* thp page */
648 BUG_ON(!PageTransHuge(src));
649 nr_pages = hpage_nr_pages(src);
650 }
651
652 for (i = 0; i < nr_pages; i++) {
653 cond_resched();
654 copy_highpage(dst + i, src + i);
655 }
656}
657
b20a3503
CL
658/*
659 * Copy the page to its new location
660 */
2916ecc0 661void migrate_page_states(struct page *newpage, struct page *page)
b20a3503 662{
7851a45c
RR
663 int cpupid;
664
b20a3503
CL
665 if (PageError(page))
666 SetPageError(newpage);
667 if (PageReferenced(page))
668 SetPageReferenced(newpage);
669 if (PageUptodate(page))
670 SetPageUptodate(newpage);
894bc310 671 if (TestClearPageActive(page)) {
309381fe 672 VM_BUG_ON_PAGE(PageUnevictable(page), page);
b20a3503 673 SetPageActive(newpage);
418b27ef
LS
674 } else if (TestClearPageUnevictable(page))
675 SetPageUnevictable(newpage);
b20a3503
CL
676 if (PageChecked(page))
677 SetPageChecked(newpage);
678 if (PageMappedToDisk(page))
679 SetPageMappedToDisk(newpage);
680
42cb14b1
HD
681 /* Move dirty on pages not done by migrate_page_move_mapping() */
682 if (PageDirty(page))
683 SetPageDirty(newpage);
b20a3503 684
33c3fc71
VD
685 if (page_is_young(page))
686 set_page_young(newpage);
687 if (page_is_idle(page))
688 set_page_idle(newpage);
689
7851a45c
RR
690 /*
691 * Copy NUMA information to the new page, to prevent over-eager
692 * future migrations of this same page.
693 */
694 cpupid = page_cpupid_xchg_last(page, -1);
695 page_cpupid_xchg_last(newpage, cpupid);
696
e9995ef9 697 ksm_migrate_page(newpage, page);
c8d6553b
HD
698 /*
699 * Please do not reorder this without considering how mm/ksm.c's
700 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
701 */
b3b3a99c
NH
702 if (PageSwapCache(page))
703 ClearPageSwapCache(page);
b20a3503
CL
704 ClearPagePrivate(page);
705 set_page_private(page, 0);
b20a3503
CL
706
707 /*
708 * If any waiters have accumulated on the new page then
709 * wake them up.
710 */
711 if (PageWriteback(newpage))
712 end_page_writeback(newpage);
d435edca
VB
713
714 copy_page_owner(page, newpage);
74485cf2
JW
715
716 mem_cgroup_migrate(page, newpage);
b20a3503 717}
2916ecc0
JG
718EXPORT_SYMBOL(migrate_page_states);
719
720void migrate_page_copy(struct page *newpage, struct page *page)
721{
722 if (PageHuge(page) || PageTransHuge(page))
723 copy_huge_page(newpage, page);
724 else
725 copy_highpage(newpage, page);
726
727 migrate_page_states(newpage, page);
728}
1118dce7 729EXPORT_SYMBOL(migrate_page_copy);
b20a3503 730
1d8b85cc
CL
731/************************************************************
732 * Migration functions
733 ***********************************************************/
734
b20a3503 735/*
bda807d4 736 * Common logic to directly migrate a single LRU page suitable for
266cf658 737 * pages that do not use PagePrivate/PagePrivate2.
b20a3503
CL
738 *
739 * Pages are locked upon entry and exit.
740 */
2d1db3b1 741int migrate_page(struct address_space *mapping,
a6bc32b8
MG
742 struct page *newpage, struct page *page,
743 enum migrate_mode mode)
b20a3503
CL
744{
745 int rc;
746
747 BUG_ON(PageWriteback(page)); /* Writeback must be complete */
748
8e321fef 749 rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0);
b20a3503 750
78bd5209 751 if (rc != MIGRATEPAGE_SUCCESS)
b20a3503
CL
752 return rc;
753
2916ecc0
JG
754 if (mode != MIGRATE_SYNC_NO_COPY)
755 migrate_page_copy(newpage, page);
756 else
757 migrate_page_states(newpage, page);
78bd5209 758 return MIGRATEPAGE_SUCCESS;
b20a3503
CL
759}
760EXPORT_SYMBOL(migrate_page);
761
9361401e 762#ifdef CONFIG_BLOCK
1d8b85cc
CL
763/*
764 * Migration function for pages with buffers. This function can only be used
765 * if the underlying filesystem guarantees that no other references to "page"
766 * exist.
767 */
2d1db3b1 768int buffer_migrate_page(struct address_space *mapping,
a6bc32b8 769 struct page *newpage, struct page *page, enum migrate_mode mode)
1d8b85cc 770{
1d8b85cc
CL
771 struct buffer_head *bh, *head;
772 int rc;
773
1d8b85cc 774 if (!page_has_buffers(page))
a6bc32b8 775 return migrate_page(mapping, newpage, page, mode);
1d8b85cc
CL
776
777 head = page_buffers(page);
778
8e321fef 779 rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0);
1d8b85cc 780
78bd5209 781 if (rc != MIGRATEPAGE_SUCCESS)
1d8b85cc
CL
782 return rc;
783
b969c4ab
MG
784 /*
785 * In the async case, migrate_page_move_mapping locked the buffers
786 * with an IRQ-safe spinlock held. In the sync case, the buffers
787 * need to be locked now
788 */
a6bc32b8
MG
789 if (mode != MIGRATE_ASYNC)
790 BUG_ON(!buffer_migrate_lock_buffers(head, mode));
1d8b85cc
CL
791
792 ClearPagePrivate(page);
793 set_page_private(newpage, page_private(page));
794 set_page_private(page, 0);
795 put_page(page);
796 get_page(newpage);
797
798 bh = head;
799 do {
800 set_bh_page(bh, newpage, bh_offset(bh));
801 bh = bh->b_this_page;
802
803 } while (bh != head);
804
805 SetPagePrivate(newpage);
806
2916ecc0
JG
807 if (mode != MIGRATE_SYNC_NO_COPY)
808 migrate_page_copy(newpage, page);
809 else
810 migrate_page_states(newpage, page);
1d8b85cc
CL
811
812 bh = head;
813 do {
814 unlock_buffer(bh);
2916ecc0 815 put_bh(bh);
1d8b85cc
CL
816 bh = bh->b_this_page;
817
818 } while (bh != head);
819
78bd5209 820 return MIGRATEPAGE_SUCCESS;
1d8b85cc
CL
821}
822EXPORT_SYMBOL(buffer_migrate_page);
9361401e 823#endif
1d8b85cc 824
04e62a29
CL
825/*
826 * Writeback a page to clean the dirty state
827 */
828static int writeout(struct address_space *mapping, struct page *page)
8351a6e4 829{
04e62a29
CL
830 struct writeback_control wbc = {
831 .sync_mode = WB_SYNC_NONE,
832 .nr_to_write = 1,
833 .range_start = 0,
834 .range_end = LLONG_MAX,
04e62a29
CL
835 .for_reclaim = 1
836 };
837 int rc;
838
839 if (!mapping->a_ops->writepage)
840 /* No write method for the address space */
841 return -EINVAL;
842
843 if (!clear_page_dirty_for_io(page))
844 /* Someone else already triggered a write */
845 return -EAGAIN;
846
8351a6e4 847 /*
04e62a29
CL
848 * A dirty page may imply that the underlying filesystem has
849 * the page on some queue. So the page must be clean for
850 * migration. Writeout may mean we loose the lock and the
851 * page state is no longer what we checked for earlier.
852 * At this point we know that the migration attempt cannot
853 * be successful.
8351a6e4 854 */
e388466d 855 remove_migration_ptes(page, page, false);
8351a6e4 856
04e62a29 857 rc = mapping->a_ops->writepage(page, &wbc);
8351a6e4 858
04e62a29
CL
859 if (rc != AOP_WRITEPAGE_ACTIVATE)
860 /* unlocked. Relock */
861 lock_page(page);
862
bda8550d 863 return (rc < 0) ? -EIO : -EAGAIN;
04e62a29
CL
864}
865
866/*
867 * Default handling if a filesystem does not provide a migration function.
868 */
869static int fallback_migrate_page(struct address_space *mapping,
a6bc32b8 870 struct page *newpage, struct page *page, enum migrate_mode mode)
04e62a29 871{
b969c4ab 872 if (PageDirty(page)) {
a6bc32b8 873 /* Only writeback pages in full synchronous migration */
2916ecc0
JG
874 switch (mode) {
875 case MIGRATE_SYNC:
876 case MIGRATE_SYNC_NO_COPY:
877 break;
878 default:
b969c4ab 879 return -EBUSY;
2916ecc0 880 }
04e62a29 881 return writeout(mapping, page);
b969c4ab 882 }
8351a6e4
CL
883
884 /*
885 * Buffers may be managed in a filesystem specific way.
886 * We must have no buffers or drop them.
887 */
266cf658 888 if (page_has_private(page) &&
8351a6e4
CL
889 !try_to_release_page(page, GFP_KERNEL))
890 return -EAGAIN;
891
a6bc32b8 892 return migrate_page(mapping, newpage, page, mode);
8351a6e4
CL
893}
894
e24f0b8f
CL
895/*
896 * Move a page to a newly allocated page
897 * The page is locked and all ptes have been successfully removed.
898 *
899 * The new page will have replaced the old page if this function
900 * is successful.
894bc310
LS
901 *
902 * Return value:
903 * < 0 - error code
78bd5209 904 * MIGRATEPAGE_SUCCESS - success
e24f0b8f 905 */
3fe2011f 906static int move_to_new_page(struct page *newpage, struct page *page,
5c3f9a67 907 enum migrate_mode mode)
e24f0b8f
CL
908{
909 struct address_space *mapping;
bda807d4
MK
910 int rc = -EAGAIN;
911 bool is_lru = !__PageMovable(page);
e24f0b8f 912
7db7671f
HD
913 VM_BUG_ON_PAGE(!PageLocked(page), page);
914 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
e24f0b8f 915
e24f0b8f 916 mapping = page_mapping(page);
bda807d4
MK
917
918 if (likely(is_lru)) {
919 if (!mapping)
920 rc = migrate_page(mapping, newpage, page, mode);
921 else if (mapping->a_ops->migratepage)
922 /*
923 * Most pages have a mapping and most filesystems
924 * provide a migratepage callback. Anonymous pages
925 * are part of swap space which also has its own
926 * migratepage callback. This is the most common path
927 * for page migration.
928 */
929 rc = mapping->a_ops->migratepage(mapping, newpage,
930 page, mode);
931 else
932 rc = fallback_migrate_page(mapping, newpage,
933 page, mode);
934 } else {
e24f0b8f 935 /*
bda807d4
MK
936 * In case of non-lru page, it could be released after
937 * isolation step. In that case, we shouldn't try migration.
e24f0b8f 938 */
bda807d4
MK
939 VM_BUG_ON_PAGE(!PageIsolated(page), page);
940 if (!PageMovable(page)) {
941 rc = MIGRATEPAGE_SUCCESS;
942 __ClearPageIsolated(page);
943 goto out;
944 }
945
946 rc = mapping->a_ops->migratepage(mapping, newpage,
947 page, mode);
948 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
949 !PageIsolated(page));
950 }
e24f0b8f 951
5c3f9a67
HD
952 /*
953 * When successful, old pagecache page->mapping must be cleared before
954 * page is freed; but stats require that PageAnon be left as PageAnon.
955 */
956 if (rc == MIGRATEPAGE_SUCCESS) {
bda807d4
MK
957 if (__PageMovable(page)) {
958 VM_BUG_ON_PAGE(!PageIsolated(page), page);
959
960 /*
961 * We clear PG_movable under page_lock so any compactor
962 * cannot try to migrate this page.
963 */
964 __ClearPageIsolated(page);
965 }
966
967 /*
968 * Anonymous and movable page->mapping will be cleard by
969 * free_pages_prepare so don't reset it here for keeping
970 * the type to work PageAnon, for example.
971 */
972 if (!PageMappingFlags(page))
5c3f9a67 973 page->mapping = NULL;
3fe2011f 974 }
bda807d4 975out:
e24f0b8f
CL
976 return rc;
977}
978
0dabec93 979static int __unmap_and_move(struct page *page, struct page *newpage,
9c620e2b 980 int force, enum migrate_mode mode)
e24f0b8f 981{
0dabec93 982 int rc = -EAGAIN;
2ebba6b7 983 int page_was_mapped = 0;
3f6c8272 984 struct anon_vma *anon_vma = NULL;
bda807d4 985 bool is_lru = !__PageMovable(page);
95a402c3 986
529ae9aa 987 if (!trylock_page(page)) {
a6bc32b8 988 if (!force || mode == MIGRATE_ASYNC)
0dabec93 989 goto out;
3e7d3449
MG
990
991 /*
992 * It's not safe for direct compaction to call lock_page.
993 * For example, during page readahead pages are added locked
994 * to the LRU. Later, when the IO completes the pages are
995 * marked uptodate and unlocked. However, the queueing
996 * could be merging multiple pages for one bio (e.g.
997 * mpage_readpages). If an allocation happens for the
998 * second or third page, the process can end up locking
999 * the same page twice and deadlocking. Rather than
1000 * trying to be clever about what pages can be locked,
1001 * avoid the use of lock_page for direct compaction
1002 * altogether.
1003 */
1004 if (current->flags & PF_MEMALLOC)
0dabec93 1005 goto out;
3e7d3449 1006
e24f0b8f
CL
1007 lock_page(page);
1008 }
1009
1010 if (PageWriteback(page)) {
11bc82d6 1011 /*
fed5b64a 1012 * Only in the case of a full synchronous migration is it
a6bc32b8
MG
1013 * necessary to wait for PageWriteback. In the async case,
1014 * the retry loop is too short and in the sync-light case,
1015 * the overhead of stalling is too much
11bc82d6 1016 */
2916ecc0
JG
1017 switch (mode) {
1018 case MIGRATE_SYNC:
1019 case MIGRATE_SYNC_NO_COPY:
1020 break;
1021 default:
11bc82d6 1022 rc = -EBUSY;
0a31bc97 1023 goto out_unlock;
11bc82d6
AA
1024 }
1025 if (!force)
0a31bc97 1026 goto out_unlock;
e24f0b8f
CL
1027 wait_on_page_writeback(page);
1028 }
03f15c86 1029
e24f0b8f 1030 /*
dc386d4d
KH
1031 * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
1032 * we cannot notice that anon_vma is freed while we migrates a page.
1ce82b69 1033 * This get_anon_vma() delays freeing anon_vma pointer until the end
dc386d4d 1034 * of migration. File cache pages are no problem because of page_lock()
989f89c5
KH
1035 * File Caches may use write_page() or lock_page() in migration, then,
1036 * just care Anon page here.
03f15c86
HD
1037 *
1038 * Only page_get_anon_vma() understands the subtleties of
1039 * getting a hold on an anon_vma from outside one of its mms.
1040 * But if we cannot get anon_vma, then we won't need it anyway,
1041 * because that implies that the anon page is no longer mapped
1042 * (and cannot be remapped so long as we hold the page lock).
dc386d4d 1043 */
03f15c86 1044 if (PageAnon(page) && !PageKsm(page))
746b18d4 1045 anon_vma = page_get_anon_vma(page);
62e1c553 1046
7db7671f
HD
1047 /*
1048 * Block others from accessing the new page when we get around to
1049 * establishing additional references. We are usually the only one
1050 * holding a reference to newpage at this point. We used to have a BUG
1051 * here if trylock_page(newpage) fails, but would like to allow for
1052 * cases where there might be a race with the previous use of newpage.
1053 * This is much like races on refcount of oldpage: just don't BUG().
1054 */
1055 if (unlikely(!trylock_page(newpage)))
1056 goto out_unlock;
1057
bda807d4
MK
1058 if (unlikely(!is_lru)) {
1059 rc = move_to_new_page(newpage, page, mode);
1060 goto out_unlock_both;
1061 }
1062
dc386d4d 1063 /*
62e1c553
SL
1064 * Corner case handling:
1065 * 1. When a new swap-cache page is read into, it is added to the LRU
1066 * and treated as swapcache but it has no rmap yet.
1067 * Calling try_to_unmap() against a page->mapping==NULL page will
1068 * trigger a BUG. So handle it here.
1069 * 2. An orphaned page (see truncate_complete_page) might have
1070 * fs-private metadata. The page can be picked up due to memory
1071 * offlining. Everywhere else except page reclaim, the page is
1072 * invisible to the vm, so the page can not be migrated. So try to
1073 * free the metadata, so the page can be freed.
e24f0b8f 1074 */
62e1c553 1075 if (!page->mapping) {
309381fe 1076 VM_BUG_ON_PAGE(PageAnon(page), page);
1ce82b69 1077 if (page_has_private(page)) {
62e1c553 1078 try_to_free_buffers(page);
7db7671f 1079 goto out_unlock_both;
62e1c553 1080 }
7db7671f
HD
1081 } else if (page_mapped(page)) {
1082 /* Establish migration ptes */
03f15c86
HD
1083 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1084 page);
2ebba6b7 1085 try_to_unmap(page,
da1b13cc 1086 TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
2ebba6b7
HD
1087 page_was_mapped = 1;
1088 }
dc386d4d 1089
e6a1530d 1090 if (!page_mapped(page))
5c3f9a67 1091 rc = move_to_new_page(newpage, page, mode);
e24f0b8f 1092
5c3f9a67
HD
1093 if (page_was_mapped)
1094 remove_migration_ptes(page,
e388466d 1095 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
3f6c8272 1096
7db7671f
HD
1097out_unlock_both:
1098 unlock_page(newpage);
1099out_unlock:
3f6c8272 1100 /* Drop an anon_vma reference if we took one */
76545066 1101 if (anon_vma)
9e60109f 1102 put_anon_vma(anon_vma);
e24f0b8f 1103 unlock_page(page);
0dabec93 1104out:
c6c919eb
MK
1105 /*
1106 * If migration is successful, decrease refcount of the newpage
1107 * which will not free the page because new page owner increased
1108 * refcounter. As well, if it is LRU page, add the page to LRU
1109 * list in here.
1110 */
1111 if (rc == MIGRATEPAGE_SUCCESS) {
b1123ea6 1112 if (unlikely(__PageMovable(newpage)))
c6c919eb
MK
1113 put_page(newpage);
1114 else
1115 putback_lru_page(newpage);
1116 }
1117
0dabec93
MK
1118 return rc;
1119}
95a402c3 1120
ef2a5153
GU
1121/*
1122 * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work
1123 * around it.
1124 */
1125#if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM)
1126#define ICE_noinline noinline
1127#else
1128#define ICE_noinline
1129#endif
1130
0dabec93
MK
1131/*
1132 * Obtain the lock on page, remove all ptes and migrate the page
1133 * to the newly allocated page in newpage.
1134 */
ef2a5153
GU
1135static ICE_noinline int unmap_and_move(new_page_t get_new_page,
1136 free_page_t put_new_page,
1137 unsigned long private, struct page *page,
add05cec
NH
1138 int force, enum migrate_mode mode,
1139 enum migrate_reason reason)
0dabec93 1140{
2def7424 1141 int rc = MIGRATEPAGE_SUCCESS;
0dabec93 1142 int *result = NULL;
2def7424 1143 struct page *newpage;
0dabec93 1144
2def7424 1145 newpage = get_new_page(page, private, &result);
0dabec93
MK
1146 if (!newpage)
1147 return -ENOMEM;
1148
1149 if (page_count(page) == 1) {
1150 /* page was freed from under us. So we are done. */
c6c919eb
MK
1151 ClearPageActive(page);
1152 ClearPageUnevictable(page);
bda807d4
MK
1153 if (unlikely(__PageMovable(page))) {
1154 lock_page(page);
1155 if (!PageMovable(page))
1156 __ClearPageIsolated(page);
1157 unlock_page(page);
1158 }
c6c919eb
MK
1159 if (put_new_page)
1160 put_new_page(newpage, private);
1161 else
1162 put_page(newpage);
0dabec93
MK
1163 goto out;
1164 }
1165
616b8371 1166 if (unlikely(PageTransHuge(page) && !PageTransHuge(newpage))) {
4d2fa965
KS
1167 lock_page(page);
1168 rc = split_huge_page(page);
1169 unlock_page(page);
1170 if (rc)
0dabec93 1171 goto out;
4d2fa965 1172 }
0dabec93 1173
9c620e2b 1174 rc = __unmap_and_move(page, newpage, force, mode);
c6c919eb 1175 if (rc == MIGRATEPAGE_SUCCESS)
7cd12b4a 1176 set_page_owner_migrate_reason(newpage, reason);
bf6bddf1 1177
0dabec93 1178out:
e24f0b8f 1179 if (rc != -EAGAIN) {
0dabec93
MK
1180 /*
1181 * A page that has been migrated has all references
1182 * removed and will be freed. A page that has not been
1183 * migrated will have kepts its references and be
1184 * restored.
1185 */
1186 list_del(&page->lru);
6afcf8ef
ML
1187
1188 /*
1189 * Compaction can migrate also non-LRU pages which are
1190 * not accounted to NR_ISOLATED_*. They can be recognized
1191 * as __PageMovable
1192 */
1193 if (likely(!__PageMovable(page)))
e8db67eb
NH
1194 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1195 page_is_file_cache(page), -hpage_nr_pages(page));
c6c919eb
MK
1196 }
1197
1198 /*
1199 * If migration is successful, releases reference grabbed during
1200 * isolation. Otherwise, restore the page to right list unless
1201 * we want to retry.
1202 */
1203 if (rc == MIGRATEPAGE_SUCCESS) {
1204 put_page(page);
1205 if (reason == MR_MEMORY_FAILURE) {
d7e69488 1206 /*
c6c919eb
MK
1207 * Set PG_HWPoison on just freed page
1208 * intentionally. Although it's rather weird,
1209 * it's how HWPoison flag works at the moment.
d7e69488 1210 */
da1b13cc
WL
1211 if (!test_set_page_hwpoison(page))
1212 num_poisoned_pages_inc();
c6c919eb
MK
1213 }
1214 } else {
bda807d4
MK
1215 if (rc != -EAGAIN) {
1216 if (likely(!__PageMovable(page))) {
1217 putback_lru_page(page);
1218 goto put_new;
1219 }
1220
1221 lock_page(page);
1222 if (PageMovable(page))
1223 putback_movable_page(page);
1224 else
1225 __ClearPageIsolated(page);
1226 unlock_page(page);
1227 put_page(page);
1228 }
1229put_new:
c6c919eb
MK
1230 if (put_new_page)
1231 put_new_page(newpage, private);
1232 else
1233 put_page(newpage);
e24f0b8f 1234 }
68711a74 1235
742755a1
CL
1236 if (result) {
1237 if (rc)
1238 *result = rc;
1239 else
1240 *result = page_to_nid(newpage);
1241 }
e24f0b8f
CL
1242 return rc;
1243}
1244
290408d4
NH
1245/*
1246 * Counterpart of unmap_and_move_page() for hugepage migration.
1247 *
1248 * This function doesn't wait the completion of hugepage I/O
1249 * because there is no race between I/O and migration for hugepage.
1250 * Note that currently hugepage I/O occurs only in direct I/O
1251 * where no lock is held and PG_writeback is irrelevant,
1252 * and writeback status of all subpages are counted in the reference
1253 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1254 * under direct I/O, the reference of the head page is 512 and a bit more.)
1255 * This means that when we try to migrate hugepage whose subpages are
1256 * doing direct I/O, some references remain after try_to_unmap() and
1257 * hugepage migration fails without data corruption.
1258 *
1259 * There is also no race when direct I/O is issued on the page under migration,
1260 * because then pte is replaced with migration swap entry and direct I/O code
1261 * will wait in the page fault for migration to complete.
1262 */
1263static int unmap_and_move_huge_page(new_page_t get_new_page,
68711a74
DR
1264 free_page_t put_new_page, unsigned long private,
1265 struct page *hpage, int force,
7cd12b4a 1266 enum migrate_mode mode, int reason)
290408d4 1267{
2def7424 1268 int rc = -EAGAIN;
290408d4 1269 int *result = NULL;
2ebba6b7 1270 int page_was_mapped = 0;
32665f2b 1271 struct page *new_hpage;
290408d4
NH
1272 struct anon_vma *anon_vma = NULL;
1273
83467efb
NH
1274 /*
1275 * Movability of hugepages depends on architectures and hugepage size.
1276 * This check is necessary because some callers of hugepage migration
1277 * like soft offline and memory hotremove don't walk through page
1278 * tables or check whether the hugepage is pmd-based or not before
1279 * kicking migration.
1280 */
100873d7 1281 if (!hugepage_migration_supported(page_hstate(hpage))) {
32665f2b 1282 putback_active_hugepage(hpage);
83467efb 1283 return -ENOSYS;
32665f2b 1284 }
83467efb 1285
32665f2b 1286 new_hpage = get_new_page(hpage, private, &result);
290408d4
NH
1287 if (!new_hpage)
1288 return -ENOMEM;
1289
290408d4 1290 if (!trylock_page(hpage)) {
2916ecc0 1291 if (!force)
290408d4 1292 goto out;
2916ecc0
JG
1293 switch (mode) {
1294 case MIGRATE_SYNC:
1295 case MIGRATE_SYNC_NO_COPY:
1296 break;
1297 default:
1298 goto out;
1299 }
290408d4
NH
1300 lock_page(hpage);
1301 }
1302
746b18d4
PZ
1303 if (PageAnon(hpage))
1304 anon_vma = page_get_anon_vma(hpage);
290408d4 1305
7db7671f
HD
1306 if (unlikely(!trylock_page(new_hpage)))
1307 goto put_anon;
1308
2ebba6b7
HD
1309 if (page_mapped(hpage)) {
1310 try_to_unmap(hpage,
1311 TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1312 page_was_mapped = 1;
1313 }
290408d4
NH
1314
1315 if (!page_mapped(hpage))
5c3f9a67 1316 rc = move_to_new_page(new_hpage, hpage, mode);
290408d4 1317
5c3f9a67
HD
1318 if (page_was_mapped)
1319 remove_migration_ptes(hpage,
e388466d 1320 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
290408d4 1321
7db7671f
HD
1322 unlock_page(new_hpage);
1323
1324put_anon:
fd4a4663 1325 if (anon_vma)
9e60109f 1326 put_anon_vma(anon_vma);
8e6ac7fa 1327
2def7424 1328 if (rc == MIGRATEPAGE_SUCCESS) {
8e6ac7fa 1329 hugetlb_cgroup_migrate(hpage, new_hpage);
2def7424 1330 put_new_page = NULL;
7cd12b4a 1331 set_page_owner_migrate_reason(new_hpage, reason);
2def7424 1332 }
8e6ac7fa 1333
290408d4 1334 unlock_page(hpage);
09761333 1335out:
b8ec1cee
NH
1336 if (rc != -EAGAIN)
1337 putback_active_hugepage(hpage);
c3114a84
AK
1338 if (reason == MR_MEMORY_FAILURE && !test_set_page_hwpoison(hpage))
1339 num_poisoned_pages_inc();
68711a74
DR
1340
1341 /*
1342 * If migration was not successful and there's a freeing callback, use
1343 * it. Otherwise, put_page() will drop the reference grabbed during
1344 * isolation.
1345 */
2def7424 1346 if (put_new_page)
68711a74
DR
1347 put_new_page(new_hpage, private);
1348 else
3aaa76e1 1349 putback_active_hugepage(new_hpage);
68711a74 1350
290408d4
NH
1351 if (result) {
1352 if (rc)
1353 *result = rc;
1354 else
1355 *result = page_to_nid(new_hpage);
1356 }
1357 return rc;
1358}
1359
b20a3503 1360/*
c73e5c9c
SB
1361 * migrate_pages - migrate the pages specified in a list, to the free pages
1362 * supplied as the target for the page migration
b20a3503 1363 *
c73e5c9c
SB
1364 * @from: The list of pages to be migrated.
1365 * @get_new_page: The function used to allocate free pages to be used
1366 * as the target of the page migration.
68711a74
DR
1367 * @put_new_page: The function used to free target pages if migration
1368 * fails, or NULL if no special handling is necessary.
c73e5c9c
SB
1369 * @private: Private data to be passed on to get_new_page()
1370 * @mode: The migration mode that specifies the constraints for
1371 * page migration, if any.
1372 * @reason: The reason for page migration.
b20a3503 1373 *
c73e5c9c
SB
1374 * The function returns after 10 attempts or if no pages are movable any more
1375 * because the list has become empty or no retryable pages exist any more.
14e0f9bc 1376 * The caller should call putback_movable_pages() to return pages to the LRU
28bd6578 1377 * or free list only if ret != 0.
b20a3503 1378 *
c73e5c9c 1379 * Returns the number of pages that were not migrated, or an error code.
b20a3503 1380 */
9c620e2b 1381int migrate_pages(struct list_head *from, new_page_t get_new_page,
68711a74
DR
1382 free_page_t put_new_page, unsigned long private,
1383 enum migrate_mode mode, int reason)
b20a3503 1384{
e24f0b8f 1385 int retry = 1;
b20a3503 1386 int nr_failed = 0;
5647bc29 1387 int nr_succeeded = 0;
b20a3503
CL
1388 int pass = 0;
1389 struct page *page;
1390 struct page *page2;
1391 int swapwrite = current->flags & PF_SWAPWRITE;
1392 int rc;
1393
1394 if (!swapwrite)
1395 current->flags |= PF_SWAPWRITE;
1396
e24f0b8f
CL
1397 for(pass = 0; pass < 10 && retry; pass++) {
1398 retry = 0;
b20a3503 1399
e24f0b8f 1400 list_for_each_entry_safe(page, page2, from, lru) {
e24f0b8f 1401 cond_resched();
2d1db3b1 1402
31caf665
NH
1403 if (PageHuge(page))
1404 rc = unmap_and_move_huge_page(get_new_page,
68711a74 1405 put_new_page, private, page,
7cd12b4a 1406 pass > 2, mode, reason);
31caf665 1407 else
68711a74 1408 rc = unmap_and_move(get_new_page, put_new_page,
add05cec
NH
1409 private, page, pass > 2, mode,
1410 reason);
2d1db3b1 1411
e24f0b8f 1412 switch(rc) {
95a402c3 1413 case -ENOMEM:
dfef2ef4 1414 nr_failed++;
95a402c3 1415 goto out;
e24f0b8f 1416 case -EAGAIN:
2d1db3b1 1417 retry++;
e24f0b8f 1418 break;
78bd5209 1419 case MIGRATEPAGE_SUCCESS:
5647bc29 1420 nr_succeeded++;
e24f0b8f
CL
1421 break;
1422 default:
354a3363
NH
1423 /*
1424 * Permanent failure (-EBUSY, -ENOSYS, etc.):
1425 * unlike -EAGAIN case, the failed page is
1426 * removed from migration page list and not
1427 * retried in the next outer loop.
1428 */
2d1db3b1 1429 nr_failed++;
e24f0b8f 1430 break;
2d1db3b1 1431 }
b20a3503
CL
1432 }
1433 }
f2f81fb2
VB
1434 nr_failed += retry;
1435 rc = nr_failed;
95a402c3 1436out:
5647bc29
MG
1437 if (nr_succeeded)
1438 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1439 if (nr_failed)
1440 count_vm_events(PGMIGRATE_FAIL, nr_failed);
7b2a2d4a
MG
1441 trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason);
1442
b20a3503
CL
1443 if (!swapwrite)
1444 current->flags &= ~PF_SWAPWRITE;
1445
78bd5209 1446 return rc;
b20a3503 1447}
95a402c3 1448
742755a1
CL
1449#ifdef CONFIG_NUMA
1450/*
1451 * Move a list of individual pages
1452 */
1453struct page_to_node {
1454 unsigned long addr;
1455 struct page *page;
1456 int node;
1457 int status;
1458};
1459
1460static struct page *new_page_node(struct page *p, unsigned long private,
1461 int **result)
1462{
1463 struct page_to_node *pm = (struct page_to_node *)private;
1464
1465 while (pm->node != MAX_NUMNODES && pm->page != p)
1466 pm++;
1467
1468 if (pm->node == MAX_NUMNODES)
1469 return NULL;
1470
1471 *result = &pm->status;
1472
e632a938
NH
1473 if (PageHuge(p))
1474 return alloc_huge_page_node(page_hstate(compound_head(p)),
1475 pm->node);
e8db67eb
NH
1476 else if (thp_migration_supported() && PageTransHuge(p)) {
1477 struct page *thp;
1478
1479 thp = alloc_pages_node(pm->node,
1480 (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_RECLAIM,
1481 HPAGE_PMD_ORDER);
1482 if (!thp)
1483 return NULL;
1484 prep_transhuge_page(thp);
1485 return thp;
1486 } else
96db800f 1487 return __alloc_pages_node(pm->node,
e97ca8e5 1488 GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0);
742755a1
CL
1489}
1490
1491/*
1492 * Move a set of pages as indicated in the pm array. The addr
1493 * field must be set to the virtual address of the page to be moved
1494 * and the node number must contain a valid target node.
5e9a0f02 1495 * The pm array ends with node = MAX_NUMNODES.
742755a1 1496 */
5e9a0f02
BG
1497static int do_move_page_to_node_array(struct mm_struct *mm,
1498 struct page_to_node *pm,
1499 int migrate_all)
742755a1
CL
1500{
1501 int err;
1502 struct page_to_node *pp;
1503 LIST_HEAD(pagelist);
1504
1505 down_read(&mm->mmap_sem);
1506
1507 /*
1508 * Build a list of pages to migrate
1509 */
742755a1
CL
1510 for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
1511 struct vm_area_struct *vma;
1512 struct page *page;
e8db67eb
NH
1513 struct page *head;
1514 unsigned int follflags;
742755a1 1515
742755a1
CL
1516 err = -EFAULT;
1517 vma = find_vma(mm, pp->addr);
70384dc6 1518 if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma))
742755a1
CL
1519 goto set_status;
1520
d899844e 1521 /* FOLL_DUMP to ignore special (like zero) pages */
e8db67eb
NH
1522 follflags = FOLL_GET | FOLL_DUMP;
1523 if (!thp_migration_supported())
1524 follflags |= FOLL_SPLIT;
1525 page = follow_page(vma, pp->addr, follflags);
89f5b7da
LT
1526
1527 err = PTR_ERR(page);
1528 if (IS_ERR(page))
1529 goto set_status;
1530
742755a1
CL
1531 err = -ENOENT;
1532 if (!page)
1533 goto set_status;
1534
742755a1
CL
1535 err = page_to_nid(page);
1536
1537 if (err == pp->node)
1538 /*
1539 * Node already in the right place
1540 */
1541 goto put_and_set;
1542
1543 err = -EACCES;
1544 if (page_mapcount(page) > 1 &&
1545 !migrate_all)
1546 goto put_and_set;
1547
e632a938 1548 if (PageHuge(page)) {
e8db67eb 1549 if (PageHead(page)) {
e66f17ff 1550 isolate_huge_page(page, &pagelist);
e8db67eb
NH
1551 err = 0;
1552 pp->page = page;
1553 }
e632a938
NH
1554 goto put_and_set;
1555 }
1556
e8db67eb
NH
1557 pp->page = compound_head(page);
1558 head = compound_head(page);
1559 err = isolate_lru_page(head);
6d9c285a 1560 if (!err) {
e8db67eb
NH
1561 list_add_tail(&head->lru, &pagelist);
1562 mod_node_page_state(page_pgdat(head),
1563 NR_ISOLATED_ANON + page_is_file_cache(head),
1564 hpage_nr_pages(head));
6d9c285a 1565 }
742755a1
CL
1566put_and_set:
1567 /*
1568 * Either remove the duplicate refcount from
1569 * isolate_lru_page() or drop the page ref if it was
1570 * not isolated.
1571 */
1572 put_page(page);
1573set_status:
1574 pp->status = err;
1575 }
1576
e78bbfa8 1577 err = 0;
cf608ac1 1578 if (!list_empty(&pagelist)) {
68711a74 1579 err = migrate_pages(&pagelist, new_page_node, NULL,
9c620e2b 1580 (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL);
cf608ac1 1581 if (err)
e632a938 1582 putback_movable_pages(&pagelist);
cf608ac1 1583 }
742755a1
CL
1584
1585 up_read(&mm->mmap_sem);
1586 return err;
1587}
1588
5e9a0f02
BG
1589/*
1590 * Migrate an array of page address onto an array of nodes and fill
1591 * the corresponding array of status.
1592 */
3268c63e 1593static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
5e9a0f02
BG
1594 unsigned long nr_pages,
1595 const void __user * __user *pages,
1596 const int __user *nodes,
1597 int __user *status, int flags)
1598{
3140a227 1599 struct page_to_node *pm;
3140a227
BG
1600 unsigned long chunk_nr_pages;
1601 unsigned long chunk_start;
1602 int err;
5e9a0f02 1603
3140a227
BG
1604 err = -ENOMEM;
1605 pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
1606 if (!pm)
5e9a0f02 1607 goto out;
35282a2d
BG
1608
1609 migrate_prep();
1610
5e9a0f02 1611 /*
3140a227
BG
1612 * Store a chunk of page_to_node array in a page,
1613 * but keep the last one as a marker
5e9a0f02 1614 */
3140a227 1615 chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
5e9a0f02 1616
3140a227
BG
1617 for (chunk_start = 0;
1618 chunk_start < nr_pages;
1619 chunk_start += chunk_nr_pages) {
1620 int j;
5e9a0f02 1621
3140a227
BG
1622 if (chunk_start + chunk_nr_pages > nr_pages)
1623 chunk_nr_pages = nr_pages - chunk_start;
1624
1625 /* fill the chunk pm with addrs and nodes from user-space */
1626 for (j = 0; j < chunk_nr_pages; j++) {
1627 const void __user *p;
5e9a0f02
BG
1628 int node;
1629
3140a227
BG
1630 err = -EFAULT;
1631 if (get_user(p, pages + j + chunk_start))
1632 goto out_pm;
1633 pm[j].addr = (unsigned long) p;
1634
1635 if (get_user(node, nodes + j + chunk_start))
5e9a0f02
BG
1636 goto out_pm;
1637
1638 err = -ENODEV;
6f5a55f1
LT
1639 if (node < 0 || node >= MAX_NUMNODES)
1640 goto out_pm;
1641
389162c2 1642 if (!node_state(node, N_MEMORY))
5e9a0f02
BG
1643 goto out_pm;
1644
1645 err = -EACCES;
1646 if (!node_isset(node, task_nodes))
1647 goto out_pm;
1648
3140a227
BG
1649 pm[j].node = node;
1650 }
1651
1652 /* End marker for this chunk */
1653 pm[chunk_nr_pages].node = MAX_NUMNODES;
1654
1655 /* Migrate this chunk */
1656 err = do_move_page_to_node_array(mm, pm,
1657 flags & MPOL_MF_MOVE_ALL);
1658 if (err < 0)
1659 goto out_pm;
5e9a0f02 1660
5e9a0f02 1661 /* Return status information */
3140a227
BG
1662 for (j = 0; j < chunk_nr_pages; j++)
1663 if (put_user(pm[j].status, status + j + chunk_start)) {
5e9a0f02 1664 err = -EFAULT;
3140a227
BG
1665 goto out_pm;
1666 }
1667 }
1668 err = 0;
5e9a0f02
BG
1669
1670out_pm:
3140a227 1671 free_page((unsigned long)pm);
5e9a0f02
BG
1672out:
1673 return err;
1674}
1675
742755a1 1676/*
2f007e74 1677 * Determine the nodes of an array of pages and store it in an array of status.
742755a1 1678 */
80bba129
BG
1679static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1680 const void __user **pages, int *status)
742755a1 1681{
2f007e74 1682 unsigned long i;
2f007e74 1683
742755a1
CL
1684 down_read(&mm->mmap_sem);
1685
2f007e74 1686 for (i = 0; i < nr_pages; i++) {
80bba129 1687 unsigned long addr = (unsigned long)(*pages);
742755a1
CL
1688 struct vm_area_struct *vma;
1689 struct page *page;
c095adbc 1690 int err = -EFAULT;
2f007e74
BG
1691
1692 vma = find_vma(mm, addr);
70384dc6 1693 if (!vma || addr < vma->vm_start)
742755a1
CL
1694 goto set_status;
1695
d899844e
KS
1696 /* FOLL_DUMP to ignore special (like zero) pages */
1697 page = follow_page(vma, addr, FOLL_DUMP);
89f5b7da
LT
1698
1699 err = PTR_ERR(page);
1700 if (IS_ERR(page))
1701 goto set_status;
1702
d899844e 1703 err = page ? page_to_nid(page) : -ENOENT;
742755a1 1704set_status:
80bba129
BG
1705 *status = err;
1706
1707 pages++;
1708 status++;
1709 }
1710
1711 up_read(&mm->mmap_sem);
1712}
1713
1714/*
1715 * Determine the nodes of a user array of pages and store it in
1716 * a user array of status.
1717 */
1718static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1719 const void __user * __user *pages,
1720 int __user *status)
1721{
1722#define DO_PAGES_STAT_CHUNK_NR 16
1723 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1724 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
80bba129 1725
87b8d1ad
PA
1726 while (nr_pages) {
1727 unsigned long chunk_nr;
80bba129 1728
87b8d1ad
PA
1729 chunk_nr = nr_pages;
1730 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1731 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1732
1733 if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1734 break;
80bba129
BG
1735
1736 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1737
87b8d1ad
PA
1738 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1739 break;
742755a1 1740
87b8d1ad
PA
1741 pages += chunk_nr;
1742 status += chunk_nr;
1743 nr_pages -= chunk_nr;
1744 }
1745 return nr_pages ? -EFAULT : 0;
742755a1
CL
1746}
1747
1748/*
1749 * Move a list of pages in the address space of the currently executing
1750 * process.
1751 */
938bb9f5
HC
1752SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1753 const void __user * __user *, pages,
1754 const int __user *, nodes,
1755 int __user *, status, int, flags)
742755a1 1756{
742755a1 1757 struct task_struct *task;
742755a1 1758 struct mm_struct *mm;
5e9a0f02 1759 int err;
3268c63e 1760 nodemask_t task_nodes;
742755a1
CL
1761
1762 /* Check flags */
1763 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1764 return -EINVAL;
1765
1766 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1767 return -EPERM;
1768
1769 /* Find the mm_struct */
a879bf58 1770 rcu_read_lock();
228ebcbe 1771 task = pid ? find_task_by_vpid(pid) : current;
742755a1 1772 if (!task) {
a879bf58 1773 rcu_read_unlock();
742755a1
CL
1774 return -ESRCH;
1775 }
3268c63e 1776 get_task_struct(task);
742755a1
CL
1777
1778 /*
1779 * Check if this process has the right to modify the specified
197e7e52 1780 * process. Use the regular "ptrace_may_access()" checks.
742755a1 1781 */
197e7e52 1782 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
c69e8d9c 1783 rcu_read_unlock();
742755a1 1784 err = -EPERM;
5e9a0f02 1785 goto out;
742755a1 1786 }
c69e8d9c 1787 rcu_read_unlock();
742755a1 1788
86c3a764
DQ
1789 err = security_task_movememory(task);
1790 if (err)
5e9a0f02 1791 goto out;
86c3a764 1792
3268c63e
CL
1793 task_nodes = cpuset_mems_allowed(task);
1794 mm = get_task_mm(task);
1795 put_task_struct(task);
1796
6e8b09ea
SL
1797 if (!mm)
1798 return -EINVAL;
1799
1800 if (nodes)
1801 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1802 nodes, status, flags);
1803 else
1804 err = do_pages_stat(mm, nr_pages, pages, status);
742755a1 1805
742755a1
CL
1806 mmput(mm);
1807 return err;
3268c63e
CL
1808
1809out:
1810 put_task_struct(task);
1811 return err;
742755a1 1812}
742755a1 1813
7039e1db
PZ
1814#ifdef CONFIG_NUMA_BALANCING
1815/*
1816 * Returns true if this is a safe migration target node for misplaced NUMA
1817 * pages. Currently it only checks the watermarks which crude
1818 */
1819static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
3abef4e6 1820 unsigned long nr_migrate_pages)
7039e1db
PZ
1821{
1822 int z;
599d0c95 1823
7039e1db
PZ
1824 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1825 struct zone *zone = pgdat->node_zones + z;
1826
1827 if (!populated_zone(zone))
1828 continue;
1829
7039e1db
PZ
1830 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
1831 if (!zone_watermark_ok(zone, 0,
1832 high_wmark_pages(zone) +
1833 nr_migrate_pages,
1834 0, 0))
1835 continue;
1836 return true;
1837 }
1838 return false;
1839}
1840
1841static struct page *alloc_misplaced_dst_page(struct page *page,
1842 unsigned long data,
1843 int **result)
1844{
1845 int nid = (int) data;
1846 struct page *newpage;
1847
96db800f 1848 newpage = __alloc_pages_node(nid,
e97ca8e5
JW
1849 (GFP_HIGHUSER_MOVABLE |
1850 __GFP_THISNODE | __GFP_NOMEMALLOC |
1851 __GFP_NORETRY | __GFP_NOWARN) &
8479eba7 1852 ~__GFP_RECLAIM, 0);
bac0382c 1853
7039e1db
PZ
1854 return newpage;
1855}
1856
a8f60772
MG
1857/*
1858 * page migration rate limiting control.
1859 * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs
1860 * window of time. Default here says do not migrate more than 1280M per second.
1861 */
1862static unsigned int migrate_interval_millisecs __read_mostly = 100;
1863static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT);
1864
b32967ff 1865/* Returns true if the node is migrate rate-limited after the update */
1c30e017
MG
1866static bool numamigrate_update_ratelimit(pg_data_t *pgdat,
1867 unsigned long nr_pages)
7039e1db 1868{
a8f60772
MG
1869 /*
1870 * Rate-limit the amount of data that is being migrated to a node.
1871 * Optimal placement is no good if the memory bus is saturated and
1872 * all the time is being spent migrating!
1873 */
a8f60772 1874 if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) {
1c5e9c27 1875 spin_lock(&pgdat->numabalancing_migrate_lock);
a8f60772
MG
1876 pgdat->numabalancing_migrate_nr_pages = 0;
1877 pgdat->numabalancing_migrate_next_window = jiffies +
1878 msecs_to_jiffies(migrate_interval_millisecs);
1c5e9c27 1879 spin_unlock(&pgdat->numabalancing_migrate_lock);
a8f60772 1880 }
af1839d7
MG
1881 if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) {
1882 trace_mm_numa_migrate_ratelimit(current, pgdat->node_id,
1883 nr_pages);
1c5e9c27 1884 return true;
af1839d7 1885 }
1c5e9c27
MG
1886
1887 /*
1888 * This is an unlocked non-atomic update so errors are possible.
1889 * The consequences are failing to migrate when we potentiall should
1890 * have which is not severe enough to warrant locking. If it is ever
1891 * a problem, it can be converted to a per-cpu counter.
1892 */
1893 pgdat->numabalancing_migrate_nr_pages += nr_pages;
1894 return false;
b32967ff
MG
1895}
1896
1c30e017 1897static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
b32967ff 1898{
340ef390 1899 int page_lru;
a8f60772 1900
309381fe 1901 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
3abef4e6 1902
7039e1db 1903 /* Avoid migrating to a node that is nearly full */
340ef390
HD
1904 if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page)))
1905 return 0;
7039e1db 1906
340ef390
HD
1907 if (isolate_lru_page(page))
1908 return 0;
7039e1db 1909
340ef390
HD
1910 /*
1911 * migrate_misplaced_transhuge_page() skips page migration's usual
1912 * check on page_count(), so we must do it here, now that the page
1913 * has been isolated: a GUP pin, or any other pin, prevents migration.
1914 * The expected page count is 3: 1 for page's mapcount and 1 for the
1915 * caller's pin and 1 for the reference taken by isolate_lru_page().
1916 */
1917 if (PageTransHuge(page) && page_count(page) != 3) {
1918 putback_lru_page(page);
1919 return 0;
7039e1db
PZ
1920 }
1921
340ef390 1922 page_lru = page_is_file_cache(page);
599d0c95 1923 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
340ef390
HD
1924 hpage_nr_pages(page));
1925
149c33e1 1926 /*
340ef390
HD
1927 * Isolating the page has taken another reference, so the
1928 * caller's reference can be safely dropped without the page
1929 * disappearing underneath us during migration.
149c33e1
MG
1930 */
1931 put_page(page);
340ef390 1932 return 1;
b32967ff
MG
1933}
1934
de466bd6
MG
1935bool pmd_trans_migrating(pmd_t pmd)
1936{
1937 struct page *page = pmd_page(pmd);
1938 return PageLocked(page);
1939}
1940
b32967ff
MG
1941/*
1942 * Attempt to migrate a misplaced page to the specified destination
1943 * node. Caller is expected to have an elevated reference count on
1944 * the page that will be dropped by this function before returning.
1945 */
1bc115d8
MG
1946int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
1947 int node)
b32967ff
MG
1948{
1949 pg_data_t *pgdat = NODE_DATA(node);
340ef390 1950 int isolated;
b32967ff
MG
1951 int nr_remaining;
1952 LIST_HEAD(migratepages);
1953
1954 /*
1bc115d8
MG
1955 * Don't migrate file pages that are mapped in multiple processes
1956 * with execute permissions as they are probably shared libraries.
b32967ff 1957 */
1bc115d8
MG
1958 if (page_mapcount(page) != 1 && page_is_file_cache(page) &&
1959 (vma->vm_flags & VM_EXEC))
b32967ff 1960 goto out;
b32967ff
MG
1961
1962 /*
1963 * Rate-limit the amount of data that is being migrated to a node.
1964 * Optimal placement is no good if the memory bus is saturated and
1965 * all the time is being spent migrating!
1966 */
340ef390 1967 if (numamigrate_update_ratelimit(pgdat, 1))
b32967ff 1968 goto out;
b32967ff
MG
1969
1970 isolated = numamigrate_isolate_page(pgdat, page);
1971 if (!isolated)
1972 goto out;
1973
1974 list_add(&page->lru, &migratepages);
9c620e2b 1975 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
68711a74
DR
1976 NULL, node, MIGRATE_ASYNC,
1977 MR_NUMA_MISPLACED);
b32967ff 1978 if (nr_remaining) {
59c82b70
JK
1979 if (!list_empty(&migratepages)) {
1980 list_del(&page->lru);
599d0c95 1981 dec_node_page_state(page, NR_ISOLATED_ANON +
59c82b70
JK
1982 page_is_file_cache(page));
1983 putback_lru_page(page);
1984 }
b32967ff
MG
1985 isolated = 0;
1986 } else
1987 count_vm_numa_event(NUMA_PAGE_MIGRATE);
7039e1db 1988 BUG_ON(!list_empty(&migratepages));
7039e1db 1989 return isolated;
340ef390
HD
1990
1991out:
1992 put_page(page);
1993 return 0;
7039e1db 1994}
220018d3 1995#endif /* CONFIG_NUMA_BALANCING */
b32967ff 1996
220018d3 1997#if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
340ef390
HD
1998/*
1999 * Migrates a THP to a given target node. page must be locked and is unlocked
2000 * before returning.
2001 */
b32967ff
MG
2002int migrate_misplaced_transhuge_page(struct mm_struct *mm,
2003 struct vm_area_struct *vma,
2004 pmd_t *pmd, pmd_t entry,
2005 unsigned long address,
2006 struct page *page, int node)
2007{
c4088ebd 2008 spinlock_t *ptl;
b32967ff
MG
2009 pg_data_t *pgdat = NODE_DATA(node);
2010 int isolated = 0;
2011 struct page *new_page = NULL;
b32967ff 2012 int page_lru = page_is_file_cache(page);
f714f4f2
MG
2013 unsigned long mmun_start = address & HPAGE_PMD_MASK;
2014 unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE;
b32967ff 2015
b32967ff
MG
2016 /*
2017 * Rate-limit the amount of data that is being migrated to a node.
2018 * Optimal placement is no good if the memory bus is saturated and
2019 * all the time is being spent migrating!
2020 */
d28d4335 2021 if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR))
b32967ff
MG
2022 goto out_dropref;
2023
2024 new_page = alloc_pages_node(node,
25160354 2025 (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
e97ca8e5 2026 HPAGE_PMD_ORDER);
340ef390
HD
2027 if (!new_page)
2028 goto out_fail;
9a982250 2029 prep_transhuge_page(new_page);
340ef390 2030
b32967ff 2031 isolated = numamigrate_isolate_page(pgdat, page);
340ef390 2032 if (!isolated) {
b32967ff 2033 put_page(new_page);
340ef390 2034 goto out_fail;
b32967ff 2035 }
b0943d61 2036
b32967ff 2037 /* Prepare a page as a migration target */
48c935ad 2038 __SetPageLocked(new_page);
d44d363f
SL
2039 if (PageSwapBacked(page))
2040 __SetPageSwapBacked(new_page);
b32967ff
MG
2041
2042 /* anon mapping, we can simply copy page->mapping to the new page: */
2043 new_page->mapping = page->mapping;
2044 new_page->index = page->index;
2045 migrate_page_copy(new_page, page);
2046 WARN_ON(PageLRU(new_page));
2047
2048 /* Recheck the target PMD */
f714f4f2 2049 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
c4088ebd 2050 ptl = pmd_lock(mm, pmd);
f4e177d1 2051 if (unlikely(!pmd_same(*pmd, entry) || !page_ref_freeze(page, 2))) {
c4088ebd 2052 spin_unlock(ptl);
f714f4f2 2053 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
b32967ff
MG
2054
2055 /* Reverse changes made by migrate_page_copy() */
2056 if (TestClearPageActive(new_page))
2057 SetPageActive(page);
2058 if (TestClearPageUnevictable(new_page))
2059 SetPageUnevictable(page);
b32967ff
MG
2060
2061 unlock_page(new_page);
2062 put_page(new_page); /* Free it */
2063
a54a407f
MG
2064 /* Retake the callers reference and putback on LRU */
2065 get_page(page);
b32967ff 2066 putback_lru_page(page);
599d0c95 2067 mod_node_page_state(page_pgdat(page),
a54a407f 2068 NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);
eb4489f6
MG
2069
2070 goto out_unlock;
b32967ff
MG
2071 }
2072
10102459 2073 entry = mk_huge_pmd(new_page, vma->vm_page_prot);
f55e1014 2074 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
b32967ff 2075
2b4847e7
MG
2076 /*
2077 * Clear the old entry under pagetable lock and establish the new PTE.
2078 * Any parallel GUP will either observe the old page blocking on the
2079 * page lock, block on the page table lock or observe the new page.
2080 * The SetPageUptodate on the new page and page_add_new_anon_rmap
2081 * guarantee the copy is visible before the pagetable update.
2082 */
f714f4f2 2083 flush_cache_range(vma, mmun_start, mmun_end);
d281ee61 2084 page_add_anon_rmap(new_page, vma, mmun_start, true);
8809aa2d 2085 pmdp_huge_clear_flush_notify(vma, mmun_start, pmd);
f714f4f2 2086 set_pmd_at(mm, mmun_start, pmd, entry);
ce4a9cc5 2087 update_mmu_cache_pmd(vma, address, &entry);
2b4847e7 2088
f4e177d1 2089 page_ref_unfreeze(page, 2);
51afb12b 2090 mlock_migrate_page(new_page, page);
d281ee61 2091 page_remove_rmap(page, true);
7cd12b4a 2092 set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED);
2b4847e7 2093
c4088ebd 2094 spin_unlock(ptl);
4645b9fe
JG
2095 /*
2096 * No need to double call mmu_notifier->invalidate_range() callback as
2097 * the above pmdp_huge_clear_flush_notify() did already call it.
2098 */
2099 mmu_notifier_invalidate_range_only_end(mm, mmun_start, mmun_end);
b32967ff 2100
11de9927
MG
2101 /* Take an "isolate" reference and put new page on the LRU. */
2102 get_page(new_page);
2103 putback_lru_page(new_page);
2104
b32967ff
MG
2105 unlock_page(new_page);
2106 unlock_page(page);
2107 put_page(page); /* Drop the rmap reference */
2108 put_page(page); /* Drop the LRU isolation reference */
2109
2110 count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
2111 count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
2112
599d0c95 2113 mod_node_page_state(page_pgdat(page),
b32967ff
MG
2114 NR_ISOLATED_ANON + page_lru,
2115 -HPAGE_PMD_NR);
2116 return isolated;
2117
340ef390
HD
2118out_fail:
2119 count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
b32967ff 2120out_dropref:
2b4847e7
MG
2121 ptl = pmd_lock(mm, pmd);
2122 if (pmd_same(*pmd, entry)) {
4d942466 2123 entry = pmd_modify(entry, vma->vm_page_prot);
f714f4f2 2124 set_pmd_at(mm, mmun_start, pmd, entry);
2b4847e7
MG
2125 update_mmu_cache_pmd(vma, address, &entry);
2126 }
2127 spin_unlock(ptl);
a54a407f 2128
eb4489f6 2129out_unlock:
340ef390 2130 unlock_page(page);
b32967ff 2131 put_page(page);
b32967ff
MG
2132 return 0;
2133}
7039e1db
PZ
2134#endif /* CONFIG_NUMA_BALANCING */
2135
2136#endif /* CONFIG_NUMA */
8763cb45 2137
6b368cd4 2138#if defined(CONFIG_MIGRATE_VMA_HELPER)
8763cb45
JG
2139struct migrate_vma {
2140 struct vm_area_struct *vma;
2141 unsigned long *dst;
2142 unsigned long *src;
2143 unsigned long cpages;
2144 unsigned long npages;
2145 unsigned long start;
2146 unsigned long end;
2147};
2148
2149static int migrate_vma_collect_hole(unsigned long start,
2150 unsigned long end,
2151 struct mm_walk *walk)
2152{
2153 struct migrate_vma *migrate = walk->private;
2154 unsigned long addr;
2155
8315ada7 2156 for (addr = start & PAGE_MASK; addr < end; addr += PAGE_SIZE) {
e20d103b 2157 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
8315ada7 2158 migrate->dst[migrate->npages] = 0;
e20d103b 2159 migrate->npages++;
8315ada7
JG
2160 migrate->cpages++;
2161 }
2162
2163 return 0;
2164}
2165
2166static int migrate_vma_collect_skip(unsigned long start,
2167 unsigned long end,
2168 struct mm_walk *walk)
2169{
2170 struct migrate_vma *migrate = walk->private;
2171 unsigned long addr;
2172
8763cb45
JG
2173 for (addr = start & PAGE_MASK; addr < end; addr += PAGE_SIZE) {
2174 migrate->dst[migrate->npages] = 0;
2175 migrate->src[migrate->npages++] = 0;
2176 }
2177
2178 return 0;
2179}
2180
2181static int migrate_vma_collect_pmd(pmd_t *pmdp,
2182 unsigned long start,
2183 unsigned long end,
2184 struct mm_walk *walk)
2185{
2186 struct migrate_vma *migrate = walk->private;
2187 struct vm_area_struct *vma = walk->vma;
2188 struct mm_struct *mm = vma->vm_mm;
8c3328f1 2189 unsigned long addr = start, unmapped = 0;
8763cb45
JG
2190 spinlock_t *ptl;
2191 pte_t *ptep;
2192
2193again:
2194 if (pmd_none(*pmdp))
2195 return migrate_vma_collect_hole(start, end, walk);
2196
2197 if (pmd_trans_huge(*pmdp)) {
2198 struct page *page;
2199
2200 ptl = pmd_lock(mm, pmdp);
2201 if (unlikely(!pmd_trans_huge(*pmdp))) {
2202 spin_unlock(ptl);
2203 goto again;
2204 }
2205
2206 page = pmd_page(*pmdp);
2207 if (is_huge_zero_page(page)) {
2208 spin_unlock(ptl);
2209 split_huge_pmd(vma, pmdp, addr);
2210 if (pmd_trans_unstable(pmdp))
8315ada7 2211 return migrate_vma_collect_skip(start, end,
8763cb45
JG
2212 walk);
2213 } else {
2214 int ret;
2215
2216 get_page(page);
2217 spin_unlock(ptl);
2218 if (unlikely(!trylock_page(page)))
8315ada7 2219 return migrate_vma_collect_skip(start, end,
8763cb45
JG
2220 walk);
2221 ret = split_huge_page(page);
2222 unlock_page(page);
2223 put_page(page);
8315ada7
JG
2224 if (ret)
2225 return migrate_vma_collect_skip(start, end,
2226 walk);
2227 if (pmd_none(*pmdp))
8763cb45
JG
2228 return migrate_vma_collect_hole(start, end,
2229 walk);
2230 }
2231 }
2232
2233 if (unlikely(pmd_bad(*pmdp)))
8315ada7 2234 return migrate_vma_collect_skip(start, end, walk);
8763cb45
JG
2235
2236 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
8c3328f1
JG
2237 arch_enter_lazy_mmu_mode();
2238
8763cb45
JG
2239 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2240 unsigned long mpfn, pfn;
2241 struct page *page;
8c3328f1 2242 swp_entry_t entry;
8763cb45
JG
2243 pte_t pte;
2244
2245 pte = *ptep;
2246 pfn = pte_pfn(pte);
2247
a5430dda 2248 if (pte_none(pte)) {
8315ada7
JG
2249 mpfn = MIGRATE_PFN_MIGRATE;
2250 migrate->cpages++;
2251 pfn = 0;
8763cb45
JG
2252 goto next;
2253 }
2254
a5430dda
JG
2255 if (!pte_present(pte)) {
2256 mpfn = pfn = 0;
2257
2258 /*
2259 * Only care about unaddressable device page special
2260 * page table entry. Other special swap entries are not
2261 * migratable, and we ignore regular swapped page.
2262 */
2263 entry = pte_to_swp_entry(pte);
2264 if (!is_device_private_entry(entry))
2265 goto next;
2266
2267 page = device_private_entry_to_page(entry);
2268 mpfn = migrate_pfn(page_to_pfn(page))|
2269 MIGRATE_PFN_DEVICE | MIGRATE_PFN_MIGRATE;
2270 if (is_write_device_private_entry(entry))
2271 mpfn |= MIGRATE_PFN_WRITE;
2272 } else {
8315ada7
JG
2273 if (is_zero_pfn(pfn)) {
2274 mpfn = MIGRATE_PFN_MIGRATE;
2275 migrate->cpages++;
2276 pfn = 0;
2277 goto next;
2278 }
df6ad698 2279 page = _vm_normal_page(migrate->vma, addr, pte, true);
a5430dda
JG
2280 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2281 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2282 }
2283
8763cb45 2284 /* FIXME support THP */
8763cb45
JG
2285 if (!page || !page->mapping || PageTransCompound(page)) {
2286 mpfn = pfn = 0;
2287 goto next;
2288 }
a5430dda 2289 pfn = page_to_pfn(page);
8763cb45
JG
2290
2291 /*
2292 * By getting a reference on the page we pin it and that blocks
2293 * any kind of migration. Side effect is that it "freezes" the
2294 * pte.
2295 *
2296 * We drop this reference after isolating the page from the lru
2297 * for non device page (device page are not on the lru and thus
2298 * can't be dropped from it).
2299 */
2300 get_page(page);
2301 migrate->cpages++;
8763cb45 2302
8c3328f1
JG
2303 /*
2304 * Optimize for the common case where page is only mapped once
2305 * in one process. If we can lock the page, then we can safely
2306 * set up a special migration page table entry now.
2307 */
2308 if (trylock_page(page)) {
2309 pte_t swp_pte;
2310
2311 mpfn |= MIGRATE_PFN_LOCKED;
2312 ptep_get_and_clear(mm, addr, ptep);
2313
2314 /* Setup special migration page table entry */
2315 entry = make_migration_entry(page, pte_write(pte));
2316 swp_pte = swp_entry_to_pte(entry);
2317 if (pte_soft_dirty(pte))
2318 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2319 set_pte_at(mm, addr, ptep, swp_pte);
2320
2321 /*
2322 * This is like regular unmap: we remove the rmap and
2323 * drop page refcount. Page won't be freed, as we took
2324 * a reference just above.
2325 */
2326 page_remove_rmap(page, false);
2327 put_page(page);
a5430dda
JG
2328
2329 if (pte_present(pte))
2330 unmapped++;
8c3328f1
JG
2331 }
2332
8763cb45 2333next:
a5430dda 2334 migrate->dst[migrate->npages] = 0;
8763cb45
JG
2335 migrate->src[migrate->npages++] = mpfn;
2336 }
8c3328f1 2337 arch_leave_lazy_mmu_mode();
8763cb45
JG
2338 pte_unmap_unlock(ptep - 1, ptl);
2339
8c3328f1
JG
2340 /* Only flush the TLB if we actually modified any entries */
2341 if (unmapped)
2342 flush_tlb_range(walk->vma, start, end);
2343
8763cb45
JG
2344 return 0;
2345}
2346
2347/*
2348 * migrate_vma_collect() - collect pages over a range of virtual addresses
2349 * @migrate: migrate struct containing all migration information
2350 *
2351 * This will walk the CPU page table. For each virtual address backed by a
2352 * valid page, it updates the src array and takes a reference on the page, in
2353 * order to pin the page until we lock it and unmap it.
2354 */
2355static void migrate_vma_collect(struct migrate_vma *migrate)
2356{
2357 struct mm_walk mm_walk;
2358
2359 mm_walk.pmd_entry = migrate_vma_collect_pmd;
2360 mm_walk.pte_entry = NULL;
2361 mm_walk.pte_hole = migrate_vma_collect_hole;
2362 mm_walk.hugetlb_entry = NULL;
2363 mm_walk.test_walk = NULL;
2364 mm_walk.vma = migrate->vma;
2365 mm_walk.mm = migrate->vma->vm_mm;
2366 mm_walk.private = migrate;
2367
8c3328f1
JG
2368 mmu_notifier_invalidate_range_start(mm_walk.mm,
2369 migrate->start,
2370 migrate->end);
8763cb45 2371 walk_page_range(migrate->start, migrate->end, &mm_walk);
8c3328f1
JG
2372 mmu_notifier_invalidate_range_end(mm_walk.mm,
2373 migrate->start,
2374 migrate->end);
8763cb45
JG
2375
2376 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2377}
2378
2379/*
2380 * migrate_vma_check_page() - check if page is pinned or not
2381 * @page: struct page to check
2382 *
2383 * Pinned pages cannot be migrated. This is the same test as in
2384 * migrate_page_move_mapping(), except that here we allow migration of a
2385 * ZONE_DEVICE page.
2386 */
2387static bool migrate_vma_check_page(struct page *page)
2388{
2389 /*
2390 * One extra ref because caller holds an extra reference, either from
2391 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2392 * a device page.
2393 */
2394 int extra = 1;
2395
2396 /*
2397 * FIXME support THP (transparent huge page), it is bit more complex to
2398 * check them than regular pages, because they can be mapped with a pmd
2399 * or with a pte (split pte mapping).
2400 */
2401 if (PageCompound(page))
2402 return false;
2403
a5430dda
JG
2404 /* Page from ZONE_DEVICE have one extra reference */
2405 if (is_zone_device_page(page)) {
2406 /*
2407 * Private page can never be pin as they have no valid pte and
2408 * GUP will fail for those. Yet if there is a pending migration
2409 * a thread might try to wait on the pte migration entry and
2410 * will bump the page reference count. Sadly there is no way to
2411 * differentiate a regular pin from migration wait. Hence to
2412 * avoid 2 racing thread trying to migrate back to CPU to enter
2413 * infinite loop (one stoping migration because the other is
2414 * waiting on pte migration entry). We always return true here.
2415 *
2416 * FIXME proper solution is to rework migration_entry_wait() so
2417 * it does not need to take a reference on page.
2418 */
2419 if (is_device_private_page(page))
2420 return true;
2421
df6ad698
JG
2422 /*
2423 * Only allow device public page to be migrated and account for
2424 * the extra reference count imply by ZONE_DEVICE pages.
2425 */
2426 if (!is_device_public_page(page))
2427 return false;
2428 extra++;
a5430dda
JG
2429 }
2430
df6ad698
JG
2431 /* For file back page */
2432 if (page_mapping(page))
2433 extra += 1 + page_has_private(page);
2434
8763cb45
JG
2435 if ((page_count(page) - extra) > page_mapcount(page))
2436 return false;
2437
2438 return true;
2439}
2440
2441/*
2442 * migrate_vma_prepare() - lock pages and isolate them from the lru
2443 * @migrate: migrate struct containing all migration information
2444 *
2445 * This locks pages that have been collected by migrate_vma_collect(). Once each
2446 * page is locked it is isolated from the lru (for non-device pages). Finally,
2447 * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2448 * migrated by concurrent kernel threads.
2449 */
2450static void migrate_vma_prepare(struct migrate_vma *migrate)
2451{
2452 const unsigned long npages = migrate->npages;
8c3328f1
JG
2453 const unsigned long start = migrate->start;
2454 unsigned long addr, i, restore = 0;
8763cb45 2455 bool allow_drain = true;
8763cb45
JG
2456
2457 lru_add_drain();
2458
2459 for (i = 0; (i < npages) && migrate->cpages; i++) {
2460 struct page *page = migrate_pfn_to_page(migrate->src[i]);
8c3328f1 2461 bool remap = true;
8763cb45
JG
2462
2463 if (!page)
2464 continue;
2465
8c3328f1
JG
2466 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2467 /*
2468 * Because we are migrating several pages there can be
2469 * a deadlock between 2 concurrent migration where each
2470 * are waiting on each other page lock.
2471 *
2472 * Make migrate_vma() a best effort thing and backoff
2473 * for any page we can not lock right away.
2474 */
2475 if (!trylock_page(page)) {
2476 migrate->src[i] = 0;
2477 migrate->cpages--;
2478 put_page(page);
2479 continue;
2480 }
2481 remap = false;
2482 migrate->src[i] |= MIGRATE_PFN_LOCKED;
8763cb45 2483 }
8763cb45 2484
a5430dda
JG
2485 /* ZONE_DEVICE pages are not on LRU */
2486 if (!is_zone_device_page(page)) {
2487 if (!PageLRU(page) && allow_drain) {
2488 /* Drain CPU's pagevec */
2489 lru_add_drain_all();
2490 allow_drain = false;
2491 }
8763cb45 2492
a5430dda
JG
2493 if (isolate_lru_page(page)) {
2494 if (remap) {
2495 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2496 migrate->cpages--;
2497 restore++;
2498 } else {
2499 migrate->src[i] = 0;
2500 unlock_page(page);
2501 migrate->cpages--;
2502 put_page(page);
2503 }
2504 continue;
8c3328f1 2505 }
a5430dda
JG
2506
2507 /* Drop the reference we took in collect */
2508 put_page(page);
8763cb45
JG
2509 }
2510
2511 if (!migrate_vma_check_page(page)) {
8c3328f1
JG
2512 if (remap) {
2513 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2514 migrate->cpages--;
2515 restore++;
8763cb45 2516
a5430dda
JG
2517 if (!is_zone_device_page(page)) {
2518 get_page(page);
2519 putback_lru_page(page);
2520 }
8c3328f1
JG
2521 } else {
2522 migrate->src[i] = 0;
2523 unlock_page(page);
2524 migrate->cpages--;
2525
a5430dda
JG
2526 if (!is_zone_device_page(page))
2527 putback_lru_page(page);
2528 else
2529 put_page(page);
8c3328f1 2530 }
8763cb45
JG
2531 }
2532 }
8c3328f1
JG
2533
2534 for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2535 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2536
2537 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2538 continue;
2539
2540 remove_migration_pte(page, migrate->vma, addr, page);
2541
2542 migrate->src[i] = 0;
2543 unlock_page(page);
2544 put_page(page);
2545 restore--;
2546 }
8763cb45
JG
2547}
2548
2549/*
2550 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2551 * @migrate: migrate struct containing all migration information
2552 *
2553 * Replace page mapping (CPU page table pte) with a special migration pte entry
2554 * and check again if it has been pinned. Pinned pages are restored because we
2555 * cannot migrate them.
2556 *
2557 * This is the last step before we call the device driver callback to allocate
2558 * destination memory and copy contents of original page over to new page.
2559 */
2560static void migrate_vma_unmap(struct migrate_vma *migrate)
2561{
2562 int flags = TTU_MIGRATION | TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS;
2563 const unsigned long npages = migrate->npages;
2564 const unsigned long start = migrate->start;
2565 unsigned long addr, i, restore = 0;
2566
2567 for (i = 0; i < npages; i++) {
2568 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2569
2570 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2571 continue;
2572
8c3328f1
JG
2573 if (page_mapped(page)) {
2574 try_to_unmap(page, flags);
2575 if (page_mapped(page))
2576 goto restore;
8763cb45 2577 }
8c3328f1
JG
2578
2579 if (migrate_vma_check_page(page))
2580 continue;
2581
2582restore:
2583 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2584 migrate->cpages--;
2585 restore++;
8763cb45
JG
2586 }
2587
2588 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2589 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2590
2591 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2592 continue;
2593
2594 remove_migration_ptes(page, page, false);
2595
2596 migrate->src[i] = 0;
2597 unlock_page(page);
2598 restore--;
2599
a5430dda
JG
2600 if (is_zone_device_page(page))
2601 put_page(page);
2602 else
2603 putback_lru_page(page);
8763cb45
JG
2604 }
2605}
2606
8315ada7
JG
2607static void migrate_vma_insert_page(struct migrate_vma *migrate,
2608 unsigned long addr,
2609 struct page *page,
2610 unsigned long *src,
2611 unsigned long *dst)
2612{
2613 struct vm_area_struct *vma = migrate->vma;
2614 struct mm_struct *mm = vma->vm_mm;
2615 struct mem_cgroup *memcg;
2616 bool flush = false;
2617 spinlock_t *ptl;
2618 pte_t entry;
2619 pgd_t *pgdp;
2620 p4d_t *p4dp;
2621 pud_t *pudp;
2622 pmd_t *pmdp;
2623 pte_t *ptep;
2624
2625 /* Only allow populating anonymous memory */
2626 if (!vma_is_anonymous(vma))
2627 goto abort;
2628
2629 pgdp = pgd_offset(mm, addr);
2630 p4dp = p4d_alloc(mm, pgdp, addr);
2631 if (!p4dp)
2632 goto abort;
2633 pudp = pud_alloc(mm, p4dp, addr);
2634 if (!pudp)
2635 goto abort;
2636 pmdp = pmd_alloc(mm, pudp, addr);
2637 if (!pmdp)
2638 goto abort;
2639
2640 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2641 goto abort;
2642
2643 /*
2644 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2645 * pte_offset_map() on pmds where a huge pmd might be created
2646 * from a different thread.
2647 *
2648 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
2649 * parallel threads are excluded by other means.
2650 *
2651 * Here we only have down_read(mmap_sem).
2652 */
2653 if (pte_alloc(mm, pmdp, addr))
2654 goto abort;
2655
2656 /* See the comment in pte_alloc_one_map() */
2657 if (unlikely(pmd_trans_unstable(pmdp)))
2658 goto abort;
2659
2660 if (unlikely(anon_vma_prepare(vma)))
2661 goto abort;
2662 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
2663 goto abort;
2664
2665 /*
2666 * The memory barrier inside __SetPageUptodate makes sure that
2667 * preceding stores to the page contents become visible before
2668 * the set_pte_at() write.
2669 */
2670 __SetPageUptodate(page);
2671
df6ad698
JG
2672 if (is_zone_device_page(page)) {
2673 if (is_device_private_page(page)) {
2674 swp_entry_t swp_entry;
2675
2676 swp_entry = make_device_private_entry(page, vma->vm_flags & VM_WRITE);
2677 entry = swp_entry_to_pte(swp_entry);
2678 } else if (is_device_public_page(page)) {
2679 entry = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
2680 if (vma->vm_flags & VM_WRITE)
2681 entry = pte_mkwrite(pte_mkdirty(entry));
2682 entry = pte_mkdevmap(entry);
2683 }
8315ada7
JG
2684 } else {
2685 entry = mk_pte(page, vma->vm_page_prot);
2686 if (vma->vm_flags & VM_WRITE)
2687 entry = pte_mkwrite(pte_mkdirty(entry));
2688 }
2689
2690 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2691
2692 if (pte_present(*ptep)) {
2693 unsigned long pfn = pte_pfn(*ptep);
2694
2695 if (!is_zero_pfn(pfn)) {
2696 pte_unmap_unlock(ptep, ptl);
2697 mem_cgroup_cancel_charge(page, memcg, false);
2698 goto abort;
2699 }
2700 flush = true;
2701 } else if (!pte_none(*ptep)) {
2702 pte_unmap_unlock(ptep, ptl);
2703 mem_cgroup_cancel_charge(page, memcg, false);
2704 goto abort;
2705 }
2706
2707 /*
2708 * Check for usefaultfd but do not deliver the fault. Instead,
2709 * just back off.
2710 */
2711 if (userfaultfd_missing(vma)) {
2712 pte_unmap_unlock(ptep, ptl);
2713 mem_cgroup_cancel_charge(page, memcg, false);
2714 goto abort;
2715 }
2716
2717 inc_mm_counter(mm, MM_ANONPAGES);
2718 page_add_new_anon_rmap(page, vma, addr, false);
2719 mem_cgroup_commit_charge(page, memcg, false, false);
2720 if (!is_zone_device_page(page))
2721 lru_cache_add_active_or_unevictable(page, vma);
2722 get_page(page);
2723
2724 if (flush) {
2725 flush_cache_page(vma, addr, pte_pfn(*ptep));
2726 ptep_clear_flush_notify(vma, addr, ptep);
2727 set_pte_at_notify(mm, addr, ptep, entry);
2728 update_mmu_cache(vma, addr, ptep);
2729 } else {
2730 /* No need to invalidate - it was non-present before */
2731 set_pte_at(mm, addr, ptep, entry);
2732 update_mmu_cache(vma, addr, ptep);
2733 }
2734
2735 pte_unmap_unlock(ptep, ptl);
2736 *src = MIGRATE_PFN_MIGRATE;
2737 return;
2738
2739abort:
2740 *src &= ~MIGRATE_PFN_MIGRATE;
2741}
2742
8763cb45
JG
2743/*
2744 * migrate_vma_pages() - migrate meta-data from src page to dst page
2745 * @migrate: migrate struct containing all migration information
2746 *
2747 * This migrates struct page meta-data from source struct page to destination
2748 * struct page. This effectively finishes the migration from source page to the
2749 * destination page.
2750 */
2751static void migrate_vma_pages(struct migrate_vma *migrate)
2752{
2753 const unsigned long npages = migrate->npages;
2754 const unsigned long start = migrate->start;
8315ada7
JG
2755 struct vm_area_struct *vma = migrate->vma;
2756 struct mm_struct *mm = vma->vm_mm;
2757 unsigned long addr, i, mmu_start;
2758 bool notified = false;
8763cb45
JG
2759
2760 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2761 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2762 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2763 struct address_space *mapping;
2764 int r;
2765
8315ada7
JG
2766 if (!newpage) {
2767 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
8763cb45 2768 continue;
8315ada7
JG
2769 }
2770
2771 if (!page) {
2772 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE)) {
2773 continue;
2774 }
2775 if (!notified) {
2776 mmu_start = addr;
2777 notified = true;
2778 mmu_notifier_invalidate_range_start(mm,
2779 mmu_start,
2780 migrate->end);
2781 }
2782 migrate_vma_insert_page(migrate, addr, newpage,
2783 &migrate->src[i],
2784 &migrate->dst[i]);
8763cb45 2785 continue;
8315ada7 2786 }
8763cb45
JG
2787
2788 mapping = page_mapping(page);
2789
a5430dda
JG
2790 if (is_zone_device_page(newpage)) {
2791 if (is_device_private_page(newpage)) {
2792 /*
2793 * For now only support private anonymous when
2794 * migrating to un-addressable device memory.
2795 */
2796 if (mapping) {
2797 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2798 continue;
2799 }
df6ad698 2800 } else if (!is_device_public_page(newpage)) {
a5430dda
JG
2801 /*
2802 * Other types of ZONE_DEVICE page are not
2803 * supported.
2804 */
2805 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2806 continue;
2807 }
2808 }
2809
8763cb45
JG
2810 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2811 if (r != MIGRATEPAGE_SUCCESS)
2812 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2813 }
8315ada7 2814
4645b9fe
JG
2815 /*
2816 * No need to double call mmu_notifier->invalidate_range() callback as
2817 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
2818 * did already call it.
2819 */
8315ada7 2820 if (notified)
4645b9fe
JG
2821 mmu_notifier_invalidate_range_only_end(mm, mmu_start,
2822 migrate->end);
8763cb45
JG
2823}
2824
2825/*
2826 * migrate_vma_finalize() - restore CPU page table entry
2827 * @migrate: migrate struct containing all migration information
2828 *
2829 * This replaces the special migration pte entry with either a mapping to the
2830 * new page if migration was successful for that page, or to the original page
2831 * otherwise.
2832 *
2833 * This also unlocks the pages and puts them back on the lru, or drops the extra
2834 * refcount, for device pages.
2835 */
2836static void migrate_vma_finalize(struct migrate_vma *migrate)
2837{
2838 const unsigned long npages = migrate->npages;
2839 unsigned long i;
2840
2841 for (i = 0; i < npages; i++) {
2842 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2843 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2844
8315ada7
JG
2845 if (!page) {
2846 if (newpage) {
2847 unlock_page(newpage);
2848 put_page(newpage);
2849 }
8763cb45 2850 continue;
8315ada7
JG
2851 }
2852
8763cb45
JG
2853 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
2854 if (newpage) {
2855 unlock_page(newpage);
2856 put_page(newpage);
2857 }
2858 newpage = page;
2859 }
2860
2861 remove_migration_ptes(page, newpage, false);
2862 unlock_page(page);
2863 migrate->cpages--;
2864
a5430dda
JG
2865 if (is_zone_device_page(page))
2866 put_page(page);
2867 else
2868 putback_lru_page(page);
8763cb45
JG
2869
2870 if (newpage != page) {
2871 unlock_page(newpage);
a5430dda
JG
2872 if (is_zone_device_page(newpage))
2873 put_page(newpage);
2874 else
2875 putback_lru_page(newpage);
8763cb45
JG
2876 }
2877 }
2878}
2879
2880/*
2881 * migrate_vma() - migrate a range of memory inside vma
2882 *
2883 * @ops: migration callback for allocating destination memory and copying
2884 * @vma: virtual memory area containing the range to be migrated
2885 * @start: start address of the range to migrate (inclusive)
2886 * @end: end address of the range to migrate (exclusive)
2887 * @src: array of hmm_pfn_t containing source pfns
2888 * @dst: array of hmm_pfn_t containing destination pfns
2889 * @private: pointer passed back to each of the callback
2890 * Returns: 0 on success, error code otherwise
2891 *
2892 * This function tries to migrate a range of memory virtual address range, using
2893 * callbacks to allocate and copy memory from source to destination. First it
2894 * collects all the pages backing each virtual address in the range, saving this
2895 * inside the src array. Then it locks those pages and unmaps them. Once the pages
2896 * are locked and unmapped, it checks whether each page is pinned or not. Pages
2897 * that aren't pinned have the MIGRATE_PFN_MIGRATE flag set (by this function)
2898 * in the corresponding src array entry. It then restores any pages that are
2899 * pinned, by remapping and unlocking those pages.
2900 *
2901 * At this point it calls the alloc_and_copy() callback. For documentation on
2902 * what is expected from that callback, see struct migrate_vma_ops comments in
2903 * include/linux/migrate.h
2904 *
2905 * After the alloc_and_copy() callback, this function goes over each entry in
2906 * the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2907 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2908 * then the function tries to migrate struct page information from the source
2909 * struct page to the destination struct page. If it fails to migrate the struct
2910 * page information, then it clears the MIGRATE_PFN_MIGRATE flag in the src
2911 * array.
2912 *
2913 * At this point all successfully migrated pages have an entry in the src
2914 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2915 * array entry with MIGRATE_PFN_VALID flag set.
2916 *
2917 * It then calls the finalize_and_map() callback. See comments for "struct
2918 * migrate_vma_ops", in include/linux/migrate.h for details about
2919 * finalize_and_map() behavior.
2920 *
2921 * After the finalize_and_map() callback, for successfully migrated pages, this
2922 * function updates the CPU page table to point to new pages, otherwise it
2923 * restores the CPU page table to point to the original source pages.
2924 *
2925 * Function returns 0 after the above steps, even if no pages were migrated
2926 * (The function only returns an error if any of the arguments are invalid.)
2927 *
2928 * Both src and dst array must be big enough for (end - start) >> PAGE_SHIFT
2929 * unsigned long entries.
2930 */
2931int migrate_vma(const struct migrate_vma_ops *ops,
2932 struct vm_area_struct *vma,
2933 unsigned long start,
2934 unsigned long end,
2935 unsigned long *src,
2936 unsigned long *dst,
2937 void *private)
2938{
2939 struct migrate_vma migrate;
2940
2941 /* Sanity check the arguments */
2942 start &= PAGE_MASK;
2943 end &= PAGE_MASK;
2944 if (!vma || is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_SPECIAL))
2945 return -EINVAL;
2946 if (start < vma->vm_start || start >= vma->vm_end)
2947 return -EINVAL;
2948 if (end <= vma->vm_start || end > vma->vm_end)
2949 return -EINVAL;
2950 if (!ops || !src || !dst || start >= end)
2951 return -EINVAL;
2952
2953 memset(src, 0, sizeof(*src) * ((end - start) >> PAGE_SHIFT));
2954 migrate.src = src;
2955 migrate.dst = dst;
2956 migrate.start = start;
2957 migrate.npages = 0;
2958 migrate.cpages = 0;
2959 migrate.end = end;
2960 migrate.vma = vma;
2961
2962 /* Collect, and try to unmap source pages */
2963 migrate_vma_collect(&migrate);
2964 if (!migrate.cpages)
2965 return 0;
2966
2967 /* Lock and isolate page */
2968 migrate_vma_prepare(&migrate);
2969 if (!migrate.cpages)
2970 return 0;
2971
2972 /* Unmap pages */
2973 migrate_vma_unmap(&migrate);
2974 if (!migrate.cpages)
2975 return 0;
2976
2977 /*
2978 * At this point pages are locked and unmapped, and thus they have
2979 * stable content and can safely be copied to destination memory that
2980 * is allocated by the callback.
2981 *
2982 * Note that migration can fail in migrate_vma_struct_page() for each
2983 * individual page.
2984 */
2985 ops->alloc_and_copy(vma, src, dst, start, end, private);
2986
2987 /* This does the real migration of struct page */
2988 migrate_vma_pages(&migrate);
2989
2990 ops->finalize_and_map(vma, src, dst, start, end, private);
2991
2992 /* Unlock and remap pages */
2993 migrate_vma_finalize(&migrate);
2994
2995 return 0;
2996}
2997EXPORT_SYMBOL(migrate_vma);
6b368cd4 2998#endif /* defined(MIGRATE_VMA_HELPER) */