1 // SPDX-License-Identifier: GPL-2.0
3 * Memory Migration functionality - linux/mm/migrate.c
5 * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
7 * Page migration was first developed in the context of the memory hotplug
8 * project. The main authors of the migration code are:
16 #include <linux/migrate.h>
17 #include <linux/export.h>
18 #include <linux/swap.h>
19 #include <linux/swapops.h>
20 #include <linux/pagemap.h>
21 #include <linux/buffer_head.h>
22 #include <linux/mm_inline.h>
23 #include <linux/nsproxy.h>
24 #include <linux/pagevec.h>
25 #include <linux/ksm.h>
26 #include <linux/rmap.h>
27 #include <linux/topology.h>
28 #include <linux/cpu.h>
29 #include <linux/cpuset.h>
30 #include <linux/writeback.h>
31 #include <linux/mempolicy.h>
32 #include <linux/vmalloc.h>
33 #include <linux/security.h>
34 #include <linux/backing-dev.h>
35 #include <linux/compaction.h>
36 #include <linux/syscalls.h>
37 #include <linux/compat.h>
38 #include <linux/hugetlb.h>
39 #include <linux/hugetlb_cgroup.h>
40 #include <linux/gfp.h>
41 #include <linux/pagewalk.h>
42 #include <linux/pfn_t.h>
43 #include <linux/memremap.h>
44 #include <linux/userfaultfd_k.h>
45 #include <linux/balloon_compaction.h>
46 #include <linux/mmu_notifier.h>
47 #include <linux/page_idle.h>
48 #include <linux/page_owner.h>
49 #include <linux/sched/mm.h>
50 #include <linux/ptrace.h>
51 #include <linux/oom.h>
52 #include <linux/memory.h>
54 #include <asm/tlbflush.h>
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/migrate.h>
61 int isolate_movable_page(struct page *page, isolate_mode_t mode)
63 struct address_space *mapping;
66 * Avoid burning cycles with pages that are yet under __free_pages(),
67 * or just got freed under us.
69 * In case we 'win' a race for a movable page being freed under us and
70 * raise its refcount preventing __free_pages() from doing its job
71 * the put_page() at the end of this block will take care of
72 * release this page, thus avoiding a nasty leakage.
74 if (unlikely(!get_page_unless_zero(page)))
78 * Check PageMovable before holding a PG_lock because page's owner
79 * assumes anybody doesn't touch PG_lock of newly allocated page
80 * so unconditionally grabbing the lock ruins page's owner side.
82 if (unlikely(!__PageMovable(page)))
85 * As movable pages are not isolated from LRU lists, concurrent
86 * compaction threads can race against page migration functions
87 * as well as race against the releasing a page.
89 * In order to avoid having an already isolated movable page
90 * being (wrongly) re-isolated while it is under migration,
91 * or to avoid attempting to isolate pages being released,
92 * lets be sure we have the page lock
93 * before proceeding with the movable page isolation steps.
95 if (unlikely(!trylock_page(page)))
98 if (!PageMovable(page) || PageIsolated(page))
101 mapping = page_mapping(page);
102 VM_BUG_ON_PAGE(!mapping, page);
104 if (!mapping->a_ops->isolate_page(page, mode))
105 goto out_no_isolated;
107 /* Driver shouldn't use PG_isolated bit of page->flags */
108 WARN_ON_ONCE(PageIsolated(page));
109 __SetPageIsolated(page);
122 static void putback_movable_page(struct page *page)
124 struct address_space *mapping;
126 mapping = page_mapping(page);
127 mapping->a_ops->putback_page(page);
128 __ClearPageIsolated(page);
132 * Put previously isolated pages back onto the appropriate lists
133 * from where they were once taken off for compaction/migration.
135 * This function shall be used whenever the isolated pageset has been
136 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
137 * and isolate_huge_page().
139 void putback_movable_pages(struct list_head *l)
144 list_for_each_entry_safe(page, page2, l, lru) {
145 if (unlikely(PageHuge(page))) {
146 putback_active_hugepage(page);
149 list_del(&page->lru);
151 * We isolated non-lru movable page so here we can use
152 * __PageMovable because LRU page's mapping cannot have
153 * PAGE_MAPPING_MOVABLE.
155 if (unlikely(__PageMovable(page))) {
156 VM_BUG_ON_PAGE(!PageIsolated(page), page);
158 if (PageMovable(page))
159 putback_movable_page(page);
161 __ClearPageIsolated(page);
165 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
166 page_is_file_lru(page), -thp_nr_pages(page));
167 putback_lru_page(page);
173 * Restore a potential migration pte to a working pte entry
175 static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
176 unsigned long addr, void *old)
178 struct page_vma_mapped_walk pvmw = {
182 .flags = PVMW_SYNC | PVMW_MIGRATION,
188 VM_BUG_ON_PAGE(PageTail(page), page);
189 while (page_vma_mapped_walk(&pvmw)) {
193 new = page - pvmw.page->index +
194 linear_page_index(vma, pvmw.address);
196 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
197 /* PMD-mapped THP migration entry */
199 VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
200 remove_migration_pmd(&pvmw, new);
206 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
207 if (pte_swp_soft_dirty(*pvmw.pte))
208 pte = pte_mksoft_dirty(pte);
211 * Recheck VMA as permissions can change since migration started
213 entry = pte_to_swp_entry(*pvmw.pte);
214 if (is_writable_migration_entry(entry))
215 pte = maybe_mkwrite(pte, vma);
216 else if (pte_swp_uffd_wp(*pvmw.pte))
217 pte = pte_mkuffd_wp(pte);
219 if (unlikely(is_device_private_page(new))) {
221 entry = make_writable_device_private_entry(
224 entry = make_readable_device_private_entry(
226 pte = swp_entry_to_pte(entry);
227 if (pte_swp_soft_dirty(*pvmw.pte))
228 pte = pte_swp_mksoft_dirty(pte);
229 if (pte_swp_uffd_wp(*pvmw.pte))
230 pte = pte_swp_mkuffd_wp(pte);
233 #ifdef CONFIG_HUGETLB_PAGE
235 unsigned int shift = huge_page_shift(hstate_vma(vma));
237 pte = pte_mkhuge(pte);
238 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
239 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
241 hugepage_add_anon_rmap(new, vma, pvmw.address);
243 page_dup_rmap(new, true);
247 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
250 page_add_anon_rmap(new, vma, pvmw.address, false);
252 page_add_file_rmap(new, false);
254 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
257 if (PageTransHuge(page) && PageMlocked(page))
258 clear_page_mlock(page);
260 /* No need to invalidate - it was non-present before */
261 update_mmu_cache(vma, pvmw.address, pvmw.pte);
268 * Get rid of all migration entries and replace them by
269 * references to the indicated page.
271 void remove_migration_ptes(struct page *old, struct page *new, bool locked)
273 struct rmap_walk_control rwc = {
274 .rmap_one = remove_migration_pte,
279 rmap_walk_locked(new, &rwc);
281 rmap_walk(new, &rwc);
285 * Something used the pte of a page under migration. We need to
286 * get to the page and wait until migration is finished.
287 * When we return from this function the fault will be retried.
289 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
298 if (!is_swap_pte(pte))
301 entry = pte_to_swp_entry(pte);
302 if (!is_migration_entry(entry))
305 page = pfn_swap_entry_to_page(entry);
306 page = compound_head(page);
309 * Once page cache replacement of page migration started, page_count
310 * is zero; but we must not call put_and_wait_on_page_locked() without
311 * a ref. Use get_page_unless_zero(), and just fault again if it fails.
313 if (!get_page_unless_zero(page))
315 pte_unmap_unlock(ptep, ptl);
316 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
319 pte_unmap_unlock(ptep, ptl);
322 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
323 unsigned long address)
325 spinlock_t *ptl = pte_lockptr(mm, pmd);
326 pte_t *ptep = pte_offset_map(pmd, address);
327 __migration_entry_wait(mm, ptep, ptl);
330 void migration_entry_wait_huge(struct vm_area_struct *vma,
331 struct mm_struct *mm, pte_t *pte)
333 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
334 __migration_entry_wait(mm, pte, ptl);
337 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
338 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
343 ptl = pmd_lock(mm, pmd);
344 if (!is_pmd_migration_entry(*pmd))
346 page = pfn_swap_entry_to_page(pmd_to_swp_entry(*pmd));
347 if (!get_page_unless_zero(page))
350 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
357 static int expected_page_refs(struct address_space *mapping, struct page *page)
359 int expected_count = 1;
362 * Device private pages have an extra refcount as they are
365 expected_count += is_device_private_page(page);
367 expected_count += compound_nr(page) + page_has_private(page);
369 return expected_count;
373 * Replace the page in the mapping.
375 * The number of remaining references must be:
376 * 1 for anonymous pages without a mapping
377 * 2 for pages with a mapping
378 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
380 int folio_migrate_mapping(struct address_space *mapping,
381 struct folio *newfolio, struct folio *folio, int extra_count)
383 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
384 struct zone *oldzone, *newzone;
386 int expected_count = expected_page_refs(mapping, &folio->page) + extra_count;
387 long nr = folio_nr_pages(folio);
390 /* Anonymous page without mapping */
391 if (folio_ref_count(folio) != expected_count)
394 /* No turning back from here */
395 newfolio->index = folio->index;
396 newfolio->mapping = folio->mapping;
397 if (folio_test_swapbacked(folio))
398 __folio_set_swapbacked(newfolio);
400 return MIGRATEPAGE_SUCCESS;
403 oldzone = folio_zone(folio);
404 newzone = folio_zone(newfolio);
407 if (!folio_ref_freeze(folio, expected_count)) {
408 xas_unlock_irq(&xas);
413 * Now we know that no one else is looking at the folio:
414 * no turning back from here.
416 newfolio->index = folio->index;
417 newfolio->mapping = folio->mapping;
418 folio_ref_add(newfolio, nr); /* add cache reference */
419 if (folio_test_swapbacked(folio)) {
420 __folio_set_swapbacked(newfolio);
421 if (folio_test_swapcache(folio)) {
422 folio_set_swapcache(newfolio);
423 newfolio->private = folio_get_private(folio);
426 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
429 /* Move dirty while page refs frozen and newpage not yet exposed */
430 dirty = folio_test_dirty(folio);
432 folio_clear_dirty(folio);
433 folio_set_dirty(newfolio);
436 xas_store(&xas, newfolio);
440 for (i = 1; i < nr; i++) {
442 xas_store(&xas, newfolio);
447 * Drop cache reference from old page by unfreezing
448 * to one less reference.
449 * We know this isn't the last reference.
451 folio_ref_unfreeze(folio, expected_count - nr);
454 /* Leave irq disabled to prevent preemption while updating stats */
457 * If moved to a different zone then also account
458 * the page for that zone. Other VM counters will be
459 * taken care of when we establish references to the
460 * new page and drop references to the old page.
462 * Note that anonymous pages are accounted for
463 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
464 * are mapped to swap space.
466 if (newzone != oldzone) {
467 struct lruvec *old_lruvec, *new_lruvec;
468 struct mem_cgroup *memcg;
470 memcg = folio_memcg(folio);
471 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
472 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
474 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
475 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
476 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
477 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
478 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
481 if (folio_test_swapcache(folio)) {
482 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
483 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
486 if (dirty && mapping_can_writeback(mapping)) {
487 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
488 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
489 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
490 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
495 return MIGRATEPAGE_SUCCESS;
497 EXPORT_SYMBOL(folio_migrate_mapping);
500 * The expected number of remaining references is the same as that
501 * of folio_migrate_mapping().
503 int migrate_huge_page_move_mapping(struct address_space *mapping,
504 struct page *newpage, struct page *page)
506 XA_STATE(xas, &mapping->i_pages, page_index(page));
510 expected_count = 2 + page_has_private(page);
511 if (page_count(page) != expected_count || xas_load(&xas) != page) {
512 xas_unlock_irq(&xas);
516 if (!page_ref_freeze(page, expected_count)) {
517 xas_unlock_irq(&xas);
521 newpage->index = page->index;
522 newpage->mapping = page->mapping;
526 xas_store(&xas, newpage);
528 page_ref_unfreeze(page, expected_count - 1);
530 xas_unlock_irq(&xas);
532 return MIGRATEPAGE_SUCCESS;
536 * Copy the flags and some other ancillary information
538 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
542 if (folio_test_error(folio))
543 folio_set_error(newfolio);
544 if (folio_test_referenced(folio))
545 folio_set_referenced(newfolio);
546 if (folio_test_uptodate(folio))
547 folio_mark_uptodate(newfolio);
548 if (folio_test_clear_active(folio)) {
549 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
550 folio_set_active(newfolio);
551 } else if (folio_test_clear_unevictable(folio))
552 folio_set_unevictable(newfolio);
553 if (folio_test_workingset(folio))
554 folio_set_workingset(newfolio);
555 if (folio_test_checked(folio))
556 folio_set_checked(newfolio);
557 if (folio_test_mappedtodisk(folio))
558 folio_set_mappedtodisk(newfolio);
560 /* Move dirty on pages not done by folio_migrate_mapping() */
561 if (folio_test_dirty(folio))
562 folio_set_dirty(newfolio);
564 if (folio_test_young(folio))
565 folio_set_young(newfolio);
566 if (folio_test_idle(folio))
567 folio_set_idle(newfolio);
570 * Copy NUMA information to the new page, to prevent over-eager
571 * future migrations of this same page.
573 cpupid = page_cpupid_xchg_last(&folio->page, -1);
574 page_cpupid_xchg_last(&newfolio->page, cpupid);
576 folio_migrate_ksm(newfolio, folio);
578 * Please do not reorder this without considering how mm/ksm.c's
579 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
581 if (folio_test_swapcache(folio))
582 folio_clear_swapcache(folio);
583 folio_clear_private(folio);
585 /* page->private contains hugetlb specific flags */
586 if (!folio_test_hugetlb(folio))
587 folio->private = NULL;
590 * If any waiters have accumulated on the new page then
593 if (folio_test_writeback(newfolio))
594 folio_end_writeback(newfolio);
597 * PG_readahead shares the same bit with PG_reclaim. The above
598 * end_page_writeback() may clear PG_readahead mistakenly, so set the
601 if (folio_test_readahead(folio))
602 folio_set_readahead(newfolio);
604 folio_copy_owner(newfolio, folio);
606 if (!folio_test_hugetlb(folio))
607 mem_cgroup_migrate(folio, newfolio);
609 EXPORT_SYMBOL(folio_migrate_flags);
611 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
613 folio_copy(newfolio, folio);
614 folio_migrate_flags(newfolio, folio);
616 EXPORT_SYMBOL(folio_migrate_copy);
618 /************************************************************
619 * Migration functions
620 ***********************************************************/
623 * Common logic to directly migrate a single LRU page suitable for
624 * pages that do not use PagePrivate/PagePrivate2.
626 * Pages are locked upon entry and exit.
628 int migrate_page(struct address_space *mapping,
629 struct page *newpage, struct page *page,
630 enum migrate_mode mode)
632 struct folio *newfolio = page_folio(newpage);
633 struct folio *folio = page_folio(page);
636 BUG_ON(folio_test_writeback(folio)); /* Writeback must be complete */
638 rc = folio_migrate_mapping(mapping, newfolio, folio, 0);
640 if (rc != MIGRATEPAGE_SUCCESS)
643 if (mode != MIGRATE_SYNC_NO_COPY)
644 folio_migrate_copy(newfolio, folio);
646 folio_migrate_flags(newfolio, folio);
647 return MIGRATEPAGE_SUCCESS;
649 EXPORT_SYMBOL(migrate_page);
652 /* Returns true if all buffers are successfully locked */
653 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
654 enum migrate_mode mode)
656 struct buffer_head *bh = head;
658 /* Simple case, sync compaction */
659 if (mode != MIGRATE_ASYNC) {
662 bh = bh->b_this_page;
664 } while (bh != head);
669 /* async case, we cannot block on lock_buffer so use trylock_buffer */
671 if (!trylock_buffer(bh)) {
673 * We failed to lock the buffer and cannot stall in
674 * async migration. Release the taken locks
676 struct buffer_head *failed_bh = bh;
678 while (bh != failed_bh) {
680 bh = bh->b_this_page;
685 bh = bh->b_this_page;
686 } while (bh != head);
690 static int __buffer_migrate_page(struct address_space *mapping,
691 struct page *newpage, struct page *page, enum migrate_mode mode,
694 struct buffer_head *bh, *head;
698 if (!page_has_buffers(page))
699 return migrate_page(mapping, newpage, page, mode);
701 /* Check whether page does not have extra refs before we do more work */
702 expected_count = expected_page_refs(mapping, page);
703 if (page_count(page) != expected_count)
706 head = page_buffers(page);
707 if (!buffer_migrate_lock_buffers(head, mode))
712 bool invalidated = false;
716 spin_lock(&mapping->private_lock);
719 if (atomic_read(&bh->b_count)) {
723 bh = bh->b_this_page;
724 } while (bh != head);
730 spin_unlock(&mapping->private_lock);
731 invalidate_bh_lrus();
733 goto recheck_buffers;
737 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
738 if (rc != MIGRATEPAGE_SUCCESS)
741 attach_page_private(newpage, detach_page_private(page));
745 set_bh_page(bh, newpage, bh_offset(bh));
746 bh = bh->b_this_page;
748 } while (bh != head);
750 if (mode != MIGRATE_SYNC_NO_COPY)
751 migrate_page_copy(newpage, page);
753 migrate_page_states(newpage, page);
755 rc = MIGRATEPAGE_SUCCESS;
758 spin_unlock(&mapping->private_lock);
762 bh = bh->b_this_page;
764 } while (bh != head);
770 * Migration function for pages with buffers. This function can only be used
771 * if the underlying filesystem guarantees that no other references to "page"
772 * exist. For example attached buffer heads are accessed only under page lock.
774 int buffer_migrate_page(struct address_space *mapping,
775 struct page *newpage, struct page *page, enum migrate_mode mode)
777 return __buffer_migrate_page(mapping, newpage, page, mode, false);
779 EXPORT_SYMBOL(buffer_migrate_page);
782 * Same as above except that this variant is more careful and checks that there
783 * are also no buffer head references. This function is the right one for
784 * mappings where buffer heads are directly looked up and referenced (such as
785 * block device mappings).
787 int buffer_migrate_page_norefs(struct address_space *mapping,
788 struct page *newpage, struct page *page, enum migrate_mode mode)
790 return __buffer_migrate_page(mapping, newpage, page, mode, true);
795 * Writeback a page to clean the dirty state
797 static int writeout(struct address_space *mapping, struct page *page)
799 struct writeback_control wbc = {
800 .sync_mode = WB_SYNC_NONE,
803 .range_end = LLONG_MAX,
808 if (!mapping->a_ops->writepage)
809 /* No write method for the address space */
812 if (!clear_page_dirty_for_io(page))
813 /* Someone else already triggered a write */
817 * A dirty page may imply that the underlying filesystem has
818 * the page on some queue. So the page must be clean for
819 * migration. Writeout may mean we loose the lock and the
820 * page state is no longer what we checked for earlier.
821 * At this point we know that the migration attempt cannot
824 remove_migration_ptes(page, page, false);
826 rc = mapping->a_ops->writepage(page, &wbc);
828 if (rc != AOP_WRITEPAGE_ACTIVATE)
829 /* unlocked. Relock */
832 return (rc < 0) ? -EIO : -EAGAIN;
836 * Default handling if a filesystem does not provide a migration function.
838 static int fallback_migrate_page(struct address_space *mapping,
839 struct page *newpage, struct page *page, enum migrate_mode mode)
841 if (PageDirty(page)) {
842 /* Only writeback pages in full synchronous migration */
845 case MIGRATE_SYNC_NO_COPY:
850 return writeout(mapping, page);
854 * Buffers may be managed in a filesystem specific way.
855 * We must have no buffers or drop them.
857 if (page_has_private(page) &&
858 !try_to_release_page(page, GFP_KERNEL))
859 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
861 return migrate_page(mapping, newpage, page, mode);
865 * Move a page to a newly allocated page
866 * The page is locked and all ptes have been successfully removed.
868 * The new page will have replaced the old page if this function
873 * MIGRATEPAGE_SUCCESS - success
875 static int move_to_new_page(struct page *newpage, struct page *page,
876 enum migrate_mode mode)
878 struct address_space *mapping;
880 bool is_lru = !__PageMovable(page);
882 VM_BUG_ON_PAGE(!PageLocked(page), page);
883 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
885 mapping = page_mapping(page);
887 if (likely(is_lru)) {
889 rc = migrate_page(mapping, newpage, page, mode);
890 else if (mapping->a_ops->migratepage)
892 * Most pages have a mapping and most filesystems
893 * provide a migratepage callback. Anonymous pages
894 * are part of swap space which also has its own
895 * migratepage callback. This is the most common path
896 * for page migration.
898 rc = mapping->a_ops->migratepage(mapping, newpage,
901 rc = fallback_migrate_page(mapping, newpage,
905 * In case of non-lru page, it could be released after
906 * isolation step. In that case, we shouldn't try migration.
908 VM_BUG_ON_PAGE(!PageIsolated(page), page);
909 if (!PageMovable(page)) {
910 rc = MIGRATEPAGE_SUCCESS;
911 __ClearPageIsolated(page);
915 rc = mapping->a_ops->migratepage(mapping, newpage,
917 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
918 !PageIsolated(page));
922 * When successful, old pagecache page->mapping must be cleared before
923 * page is freed; but stats require that PageAnon be left as PageAnon.
925 if (rc == MIGRATEPAGE_SUCCESS) {
926 if (__PageMovable(page)) {
927 VM_BUG_ON_PAGE(!PageIsolated(page), page);
930 * We clear PG_movable under page_lock so any compactor
931 * cannot try to migrate this page.
933 __ClearPageIsolated(page);
937 * Anonymous and movable page->mapping will be cleared by
938 * free_pages_prepare so don't reset it here for keeping
939 * the type to work PageAnon, for example.
941 if (!PageMappingFlags(page))
942 page->mapping = NULL;
944 if (likely(!is_zone_device_page(newpage)))
945 flush_dcache_page(newpage);
952 static int __unmap_and_move(struct page *page, struct page *newpage,
953 int force, enum migrate_mode mode)
956 bool page_was_mapped = false;
957 struct anon_vma *anon_vma = NULL;
958 bool is_lru = !__PageMovable(page);
960 if (!trylock_page(page)) {
961 if (!force || mode == MIGRATE_ASYNC)
965 * It's not safe for direct compaction to call lock_page.
966 * For example, during page readahead pages are added locked
967 * to the LRU. Later, when the IO completes the pages are
968 * marked uptodate and unlocked. However, the queueing
969 * could be merging multiple pages for one bio (e.g.
970 * mpage_readahead). If an allocation happens for the
971 * second or third page, the process can end up locking
972 * the same page twice and deadlocking. Rather than
973 * trying to be clever about what pages can be locked,
974 * avoid the use of lock_page for direct compaction
977 if (current->flags & PF_MEMALLOC)
983 if (PageWriteback(page)) {
985 * Only in the case of a full synchronous migration is it
986 * necessary to wait for PageWriteback. In the async case,
987 * the retry loop is too short and in the sync-light case,
988 * the overhead of stalling is too much
992 case MIGRATE_SYNC_NO_COPY:
1000 wait_on_page_writeback(page);
1004 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1005 * we cannot notice that anon_vma is freed while we migrates a page.
1006 * This get_anon_vma() delays freeing anon_vma pointer until the end
1007 * of migration. File cache pages are no problem because of page_lock()
1008 * File Caches may use write_page() or lock_page() in migration, then,
1009 * just care Anon page here.
1011 * Only page_get_anon_vma() understands the subtleties of
1012 * getting a hold on an anon_vma from outside one of its mms.
1013 * But if we cannot get anon_vma, then we won't need it anyway,
1014 * because that implies that the anon page is no longer mapped
1015 * (and cannot be remapped so long as we hold the page lock).
1017 if (PageAnon(page) && !PageKsm(page))
1018 anon_vma = page_get_anon_vma(page);
1021 * Block others from accessing the new page when we get around to
1022 * establishing additional references. We are usually the only one
1023 * holding a reference to newpage at this point. We used to have a BUG
1024 * here if trylock_page(newpage) fails, but would like to allow for
1025 * cases where there might be a race with the previous use of newpage.
1026 * This is much like races on refcount of oldpage: just don't BUG().
1028 if (unlikely(!trylock_page(newpage)))
1031 if (unlikely(!is_lru)) {
1032 rc = move_to_new_page(newpage, page, mode);
1033 goto out_unlock_both;
1037 * Corner case handling:
1038 * 1. When a new swap-cache page is read into, it is added to the LRU
1039 * and treated as swapcache but it has no rmap yet.
1040 * Calling try_to_unmap() against a page->mapping==NULL page will
1041 * trigger a BUG. So handle it here.
1042 * 2. An orphaned page (see truncate_cleanup_page) might have
1043 * fs-private metadata. The page can be picked up due to memory
1044 * offlining. Everywhere else except page reclaim, the page is
1045 * invisible to the vm, so the page can not be migrated. So try to
1046 * free the metadata, so the page can be freed.
1048 if (!page->mapping) {
1049 VM_BUG_ON_PAGE(PageAnon(page), page);
1050 if (page_has_private(page)) {
1051 try_to_free_buffers(page);
1052 goto out_unlock_both;
1054 } else if (page_mapped(page)) {
1055 /* Establish migration ptes */
1056 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1058 try_to_migrate(page, 0);
1059 page_was_mapped = true;
1062 if (!page_mapped(page))
1063 rc = move_to_new_page(newpage, page, mode);
1065 if (page_was_mapped)
1066 remove_migration_ptes(page,
1067 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1070 unlock_page(newpage);
1072 /* Drop an anon_vma reference if we took one */
1074 put_anon_vma(anon_vma);
1078 * If migration is successful, decrease refcount of the newpage
1079 * which will not free the page because new page owner increased
1080 * refcounter. As well, if it is LRU page, add the page to LRU
1081 * list in here. Use the old state of the isolated source page to
1082 * determine if we migrated a LRU page. newpage was already unlocked
1083 * and possibly modified by its owner - don't rely on the page
1086 if (rc == MIGRATEPAGE_SUCCESS) {
1087 if (unlikely(!is_lru))
1090 putback_lru_page(newpage);
1098 * node_demotion[] example:
1100 * Consider a system with two sockets. Each socket has
1101 * three classes of memory attached: fast, medium and slow.
1102 * Each memory class is placed in its own NUMA node. The
1103 * CPUs are placed in the node with the "fast" memory. The
1104 * 6 NUMA nodes (0-5) might be split among the sockets like
1110 * When Node 0 fills up, its memory should be migrated to
1111 * Node 1. When Node 1 fills up, it should be migrated to
1112 * Node 2. The migration path start on the nodes with the
1113 * processors (since allocations default to this node) and
1114 * fast memory, progress through medium and end with the
1117 * 0 -> 1 -> 2 -> stop
1118 * 3 -> 4 -> 5 -> stop
1120 * This is represented in the node_demotion[] like this:
1122 * { 1, // Node 0 migrates to 1
1123 * 2, // Node 1 migrates to 2
1124 * -1, // Node 2 does not migrate
1125 * 4, // Node 3 migrates to 4
1126 * 5, // Node 4 migrates to 5
1127 * -1} // Node 5 does not migrate
1131 * Writes to this array occur without locking. Cycles are
1132 * not allowed: Node X demotes to Y which demotes to X...
1134 * If multiple reads are performed, a single rcu_read_lock()
1135 * must be held over all reads to ensure that no cycles are
1138 static int node_demotion[MAX_NUMNODES] __read_mostly =
1139 {[0 ... MAX_NUMNODES - 1] = NUMA_NO_NODE};
1142 * next_demotion_node() - Get the next node in the demotion path
1143 * @node: The starting node to lookup the next node
1145 * Return: node id for next memory node in the demotion path hierarchy
1146 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
1147 * @node online or guarantee that it *continues* to be the next demotion
1150 int next_demotion_node(int node)
1155 * node_demotion[] is updated without excluding this
1156 * function from running. RCU doesn't provide any
1157 * compiler barriers, so the READ_ONCE() is required
1158 * to avoid compiler reordering or read merging.
1160 * Make sure to use RCU over entire code blocks if
1161 * node_demotion[] reads need to be consistent.
1164 target = READ_ONCE(node_demotion[node]);
1171 * Obtain the lock on page, remove all ptes and migrate the page
1172 * to the newly allocated page in newpage.
1174 static int unmap_and_move(new_page_t get_new_page,
1175 free_page_t put_new_page,
1176 unsigned long private, struct page *page,
1177 int force, enum migrate_mode mode,
1178 enum migrate_reason reason,
1179 struct list_head *ret)
1181 int rc = MIGRATEPAGE_SUCCESS;
1182 struct page *newpage = NULL;
1184 if (!thp_migration_supported() && PageTransHuge(page))
1187 if (page_count(page) == 1) {
1188 /* page was freed from under us. So we are done. */
1189 ClearPageActive(page);
1190 ClearPageUnevictable(page);
1191 if (unlikely(__PageMovable(page))) {
1193 if (!PageMovable(page))
1194 __ClearPageIsolated(page);
1200 newpage = get_new_page(page, private);
1204 rc = __unmap_and_move(page, newpage, force, mode);
1205 if (rc == MIGRATEPAGE_SUCCESS)
1206 set_page_owner_migrate_reason(newpage, reason);
1209 if (rc != -EAGAIN) {
1211 * A page that has been migrated has all references
1212 * removed and will be freed. A page that has not been
1213 * migrated will have kept its references and be restored.
1215 list_del(&page->lru);
1219 * If migration is successful, releases reference grabbed during
1220 * isolation. Otherwise, restore the page to right list unless
1223 if (rc == MIGRATEPAGE_SUCCESS) {
1225 * Compaction can migrate also non-LRU pages which are
1226 * not accounted to NR_ISOLATED_*. They can be recognized
1229 if (likely(!__PageMovable(page)))
1230 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1231 page_is_file_lru(page), -thp_nr_pages(page));
1233 if (reason != MR_MEMORY_FAILURE)
1235 * We release the page in page_handle_poison.
1240 list_add_tail(&page->lru, ret);
1243 put_new_page(newpage, private);
1252 * Counterpart of unmap_and_move_page() for hugepage migration.
1254 * This function doesn't wait the completion of hugepage I/O
1255 * because there is no race between I/O and migration for hugepage.
1256 * Note that currently hugepage I/O occurs only in direct I/O
1257 * where no lock is held and PG_writeback is irrelevant,
1258 * and writeback status of all subpages are counted in the reference
1259 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1260 * under direct I/O, the reference of the head page is 512 and a bit more.)
1261 * This means that when we try to migrate hugepage whose subpages are
1262 * doing direct I/O, some references remain after try_to_unmap() and
1263 * hugepage migration fails without data corruption.
1265 * There is also no race when direct I/O is issued on the page under migration,
1266 * because then pte is replaced with migration swap entry and direct I/O code
1267 * will wait in the page fault for migration to complete.
1269 static int unmap_and_move_huge_page(new_page_t get_new_page,
1270 free_page_t put_new_page, unsigned long private,
1271 struct page *hpage, int force,
1272 enum migrate_mode mode, int reason,
1273 struct list_head *ret)
1276 int page_was_mapped = 0;
1277 struct page *new_hpage;
1278 struct anon_vma *anon_vma = NULL;
1279 struct address_space *mapping = NULL;
1282 * Migratability of hugepages depends on architectures and their size.
1283 * This check is necessary because some callers of hugepage migration
1284 * like soft offline and memory hotremove don't walk through page
1285 * tables or check whether the hugepage is pmd-based or not before
1286 * kicking migration.
1288 if (!hugepage_migration_supported(page_hstate(hpage))) {
1289 list_move_tail(&hpage->lru, ret);
1293 if (page_count(hpage) == 1) {
1294 /* page was freed from under us. So we are done. */
1295 putback_active_hugepage(hpage);
1296 return MIGRATEPAGE_SUCCESS;
1299 new_hpage = get_new_page(hpage, private);
1303 if (!trylock_page(hpage)) {
1308 case MIGRATE_SYNC_NO_COPY:
1317 * Check for pages which are in the process of being freed. Without
1318 * page_mapping() set, hugetlbfs specific move page routine will not
1319 * be called and we could leak usage counts for subpools.
1321 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1326 if (PageAnon(hpage))
1327 anon_vma = page_get_anon_vma(hpage);
1329 if (unlikely(!trylock_page(new_hpage)))
1332 if (page_mapped(hpage)) {
1333 bool mapping_locked = false;
1334 enum ttu_flags ttu = 0;
1336 if (!PageAnon(hpage)) {
1338 * In shared mappings, try_to_unmap could potentially
1339 * call huge_pmd_unshare. Because of this, take
1340 * semaphore in write mode here and set TTU_RMAP_LOCKED
1341 * to let lower levels know we have taken the lock.
1343 mapping = hugetlb_page_mapping_lock_write(hpage);
1344 if (unlikely(!mapping))
1345 goto unlock_put_anon;
1347 mapping_locked = true;
1348 ttu |= TTU_RMAP_LOCKED;
1351 try_to_migrate(hpage, ttu);
1352 page_was_mapped = 1;
1355 i_mmap_unlock_write(mapping);
1358 if (!page_mapped(hpage))
1359 rc = move_to_new_page(new_hpage, hpage, mode);
1361 if (page_was_mapped)
1362 remove_migration_ptes(hpage,
1363 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1366 unlock_page(new_hpage);
1370 put_anon_vma(anon_vma);
1372 if (rc == MIGRATEPAGE_SUCCESS) {
1373 move_hugetlb_state(hpage, new_hpage, reason);
1374 put_new_page = NULL;
1380 if (rc == MIGRATEPAGE_SUCCESS)
1381 putback_active_hugepage(hpage);
1382 else if (rc != -EAGAIN)
1383 list_move_tail(&hpage->lru, ret);
1386 * If migration was not successful and there's a freeing callback, use
1387 * it. Otherwise, put_page() will drop the reference grabbed during
1391 put_new_page(new_hpage, private);
1393 putback_active_hugepage(new_hpage);
1398 static inline int try_split_thp(struct page *page, struct page **page2,
1399 struct list_head *from)
1404 rc = split_huge_page_to_list(page, from);
1407 list_safe_reset_next(page, *page2, lru);
1413 * migrate_pages - migrate the pages specified in a list, to the free pages
1414 * supplied as the target for the page migration
1416 * @from: The list of pages to be migrated.
1417 * @get_new_page: The function used to allocate free pages to be used
1418 * as the target of the page migration.
1419 * @put_new_page: The function used to free target pages if migration
1420 * fails, or NULL if no special handling is necessary.
1421 * @private: Private data to be passed on to get_new_page()
1422 * @mode: The migration mode that specifies the constraints for
1423 * page migration, if any.
1424 * @reason: The reason for page migration.
1425 * @ret_succeeded: Set to the number of pages migrated successfully if
1426 * the caller passes a non-NULL pointer.
1428 * The function returns after 10 attempts or if no pages are movable any more
1429 * because the list has become empty or no retryable pages exist any more.
1430 * It is caller's responsibility to call putback_movable_pages() to return pages
1431 * to the LRU or free list only if ret != 0.
1433 * Returns the number of pages that were not migrated, or an error code.
1435 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1436 free_page_t put_new_page, unsigned long private,
1437 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1442 int nr_succeeded = 0;
1443 int nr_thp_succeeded = 0;
1444 int nr_thp_failed = 0;
1445 int nr_thp_split = 0;
1447 bool is_thp = false;
1450 int swapwrite = current->flags & PF_SWAPWRITE;
1451 int rc, nr_subpages;
1452 LIST_HEAD(ret_pages);
1453 bool nosplit = (reason == MR_NUMA_MISPLACED);
1455 trace_mm_migrate_pages_start(mode, reason);
1458 current->flags |= PF_SWAPWRITE;
1460 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1464 list_for_each_entry_safe(page, page2, from, lru) {
1467 * THP statistics is based on the source huge page.
1468 * Capture required information that might get lost
1471 is_thp = PageTransHuge(page) && !PageHuge(page);
1472 nr_subpages = thp_nr_pages(page);
1476 rc = unmap_and_move_huge_page(get_new_page,
1477 put_new_page, private, page,
1478 pass > 2, mode, reason,
1481 rc = unmap_and_move(get_new_page, put_new_page,
1482 private, page, pass > 2, mode,
1483 reason, &ret_pages);
1486 * Success: non hugetlb page will be freed, hugetlb
1487 * page will be put back
1488 * -EAGAIN: stay on the from list
1489 * -ENOMEM: stay on the from list
1490 * Other errno: put on ret_pages list then splice to
1495 * THP migration might be unsupported or the
1496 * allocation could've failed so we should
1497 * retry on the same page with the THP split
1500 * Head page is retried immediately and tail
1501 * pages are added to the tail of the list so
1502 * we encounter them after the rest of the list
1506 /* THP migration is unsupported */
1508 if (!try_split_thp(page, &page2, from)) {
1514 nr_failed += nr_subpages;
1518 /* Hugetlb migration is unsupported */
1523 * When memory is low, don't bother to try to migrate
1524 * other pages, just exit.
1525 * THP NUMA faulting doesn't split THP to retry.
1527 if (is_thp && !nosplit) {
1528 if (!try_split_thp(page, &page2, from)) {
1534 nr_failed += nr_subpages;
1546 case MIGRATEPAGE_SUCCESS:
1549 nr_succeeded += nr_subpages;
1556 * Permanent failure (-EBUSY, etc.):
1557 * unlike -EAGAIN case, the failed page is
1558 * removed from migration page list and not
1559 * retried in the next outer loop.
1563 nr_failed += nr_subpages;
1571 nr_failed += retry + thp_retry;
1572 nr_thp_failed += thp_retry;
1576 * Put the permanent failure page back to migration list, they
1577 * will be put back to the right list by the caller.
1579 list_splice(&ret_pages, from);
1581 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1582 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1583 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1584 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1585 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1586 trace_mm_migrate_pages(nr_succeeded, nr_failed, nr_thp_succeeded,
1587 nr_thp_failed, nr_thp_split, mode, reason);
1590 current->flags &= ~PF_SWAPWRITE;
1593 *ret_succeeded = nr_succeeded;
1598 struct page *alloc_migration_target(struct page *page, unsigned long private)
1600 struct migration_target_control *mtc;
1602 unsigned int order = 0;
1603 struct page *new_page = NULL;
1607 mtc = (struct migration_target_control *)private;
1608 gfp_mask = mtc->gfp_mask;
1610 if (nid == NUMA_NO_NODE)
1611 nid = page_to_nid(page);
1613 if (PageHuge(page)) {
1614 struct hstate *h = page_hstate(compound_head(page));
1616 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1617 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1620 if (PageTransHuge(page)) {
1622 * clear __GFP_RECLAIM to make the migration callback
1623 * consistent with regular THP allocations.
1625 gfp_mask &= ~__GFP_RECLAIM;
1626 gfp_mask |= GFP_TRANSHUGE;
1627 order = HPAGE_PMD_ORDER;
1629 zidx = zone_idx(page_zone(page));
1630 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1631 gfp_mask |= __GFP_HIGHMEM;
1633 new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
1635 if (new_page && PageTransHuge(new_page))
1636 prep_transhuge_page(new_page);
1643 static int store_status(int __user *status, int start, int value, int nr)
1646 if (put_user(value, status + start))
1654 static int do_move_pages_to_node(struct mm_struct *mm,
1655 struct list_head *pagelist, int node)
1658 struct migration_target_control mtc = {
1660 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1663 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1664 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1666 putback_movable_pages(pagelist);
1671 * Resolves the given address to a struct page, isolates it from the LRU and
1672 * puts it to the given pagelist.
1674 * errno - if the page cannot be found/isolated
1675 * 0 - when it doesn't have to be migrated because it is already on the
1677 * 1 - when it has been queued
1679 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1680 int node, struct list_head *pagelist, bool migrate_all)
1682 struct vm_area_struct *vma;
1684 unsigned int follflags;
1689 vma = find_vma(mm, addr);
1690 if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1693 /* FOLL_DUMP to ignore special (like zero) pages */
1694 follflags = FOLL_GET | FOLL_DUMP;
1695 page = follow_page(vma, addr, follflags);
1697 err = PTR_ERR(page);
1706 if (page_to_nid(page) == node)
1710 if (page_mapcount(page) > 1 && !migrate_all)
1713 if (PageHuge(page)) {
1714 if (PageHead(page)) {
1715 isolate_huge_page(page, pagelist);
1721 head = compound_head(page);
1722 err = isolate_lru_page(head);
1727 list_add_tail(&head->lru, pagelist);
1728 mod_node_page_state(page_pgdat(head),
1729 NR_ISOLATED_ANON + page_is_file_lru(head),
1730 thp_nr_pages(head));
1734 * Either remove the duplicate refcount from
1735 * isolate_lru_page() or drop the page ref if it was
1740 mmap_read_unlock(mm);
1744 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1745 struct list_head *pagelist, int __user *status,
1746 int start, int i, unsigned long nr_pages)
1750 if (list_empty(pagelist))
1753 err = do_move_pages_to_node(mm, pagelist, node);
1756 * Positive err means the number of failed
1757 * pages to migrate. Since we are going to
1758 * abort and return the number of non-migrated
1759 * pages, so need to include the rest of the
1760 * nr_pages that have not been attempted as
1764 err += nr_pages - i - 1;
1767 return store_status(status, start, node, i - start);
1771 * Migrate an array of page address onto an array of nodes and fill
1772 * the corresponding array of status.
1774 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1775 unsigned long nr_pages,
1776 const void __user * __user *pages,
1777 const int __user *nodes,
1778 int __user *status, int flags)
1780 int current_node = NUMA_NO_NODE;
1781 LIST_HEAD(pagelist);
1785 lru_cache_disable();
1787 for (i = start = 0; i < nr_pages; i++) {
1788 const void __user *p;
1793 if (get_user(p, pages + i))
1795 if (get_user(node, nodes + i))
1797 addr = (unsigned long)untagged_addr(p);
1800 if (node < 0 || node >= MAX_NUMNODES)
1802 if (!node_state(node, N_MEMORY))
1806 if (!node_isset(node, task_nodes))
1809 if (current_node == NUMA_NO_NODE) {
1810 current_node = node;
1812 } else if (node != current_node) {
1813 err = move_pages_and_store_status(mm, current_node,
1814 &pagelist, status, start, i, nr_pages);
1818 current_node = node;
1822 * Errors in the page lookup or isolation are not fatal and we simply
1823 * report them via status
1825 err = add_page_for_migration(mm, addr, current_node,
1826 &pagelist, flags & MPOL_MF_MOVE_ALL);
1829 /* The page is successfully queued for migration */
1834 * If the page is already on the target node (!err), store the
1835 * node, otherwise, store the err.
1837 err = store_status(status, i, err ? : current_node, 1);
1841 err = move_pages_and_store_status(mm, current_node, &pagelist,
1842 status, start, i, nr_pages);
1845 current_node = NUMA_NO_NODE;
1848 /* Make sure we do not overwrite the existing error */
1849 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1850 status, start, i, nr_pages);
1859 * Determine the nodes of an array of pages and store it in an array of status.
1861 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1862 const void __user **pages, int *status)
1868 for (i = 0; i < nr_pages; i++) {
1869 unsigned long addr = (unsigned long)(*pages);
1870 struct vm_area_struct *vma;
1874 vma = vma_lookup(mm, addr);
1878 /* FOLL_DUMP to ignore special (like zero) pages */
1879 page = follow_page(vma, addr, FOLL_DUMP);
1881 err = PTR_ERR(page);
1885 err = page ? page_to_nid(page) : -ENOENT;
1893 mmap_read_unlock(mm);
1896 static int get_compat_pages_array(const void __user *chunk_pages[],
1897 const void __user * __user *pages,
1898 unsigned long chunk_nr)
1900 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1904 for (i = 0; i < chunk_nr; i++) {
1905 if (get_user(p, pages32 + i))
1907 chunk_pages[i] = compat_ptr(p);
1914 * Determine the nodes of a user array of pages and store it in
1915 * a user array of status.
1917 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1918 const void __user * __user *pages,
1921 #define DO_PAGES_STAT_CHUNK_NR 16
1922 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1923 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1926 unsigned long chunk_nr;
1928 chunk_nr = nr_pages;
1929 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1930 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1932 if (in_compat_syscall()) {
1933 if (get_compat_pages_array(chunk_pages, pages,
1937 if (copy_from_user(chunk_pages, pages,
1938 chunk_nr * sizeof(*chunk_pages)))
1942 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1944 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1949 nr_pages -= chunk_nr;
1951 return nr_pages ? -EFAULT : 0;
1954 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1956 struct task_struct *task;
1957 struct mm_struct *mm;
1960 * There is no need to check if current process has the right to modify
1961 * the specified process when they are same.
1965 *mem_nodes = cpuset_mems_allowed(current);
1969 /* Find the mm_struct */
1971 task = find_task_by_vpid(pid);
1974 return ERR_PTR(-ESRCH);
1976 get_task_struct(task);
1979 * Check if this process has the right to modify the specified
1980 * process. Use the regular "ptrace_may_access()" checks.
1982 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1984 mm = ERR_PTR(-EPERM);
1989 mm = ERR_PTR(security_task_movememory(task));
1992 *mem_nodes = cpuset_mems_allowed(task);
1993 mm = get_task_mm(task);
1995 put_task_struct(task);
1997 mm = ERR_PTR(-EINVAL);
2002 * Move a list of pages in the address space of the currently executing
2005 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2006 const void __user * __user *pages,
2007 const int __user *nodes,
2008 int __user *status, int flags)
2010 struct mm_struct *mm;
2012 nodemask_t task_nodes;
2015 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2018 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2021 mm = find_mm_struct(pid, &task_nodes);
2026 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2027 nodes, status, flags);
2029 err = do_pages_stat(mm, nr_pages, pages, status);
2035 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2036 const void __user * __user *, pages,
2037 const int __user *, nodes,
2038 int __user *, status, int, flags)
2040 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2043 #ifdef CONFIG_NUMA_BALANCING
2045 * Returns true if this is a safe migration target node for misplaced NUMA
2046 * pages. Currently it only checks the watermarks which crude
2048 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2049 unsigned long nr_migrate_pages)
2053 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2054 struct zone *zone = pgdat->node_zones + z;
2056 if (!populated_zone(zone))
2059 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2060 if (!zone_watermark_ok(zone, 0,
2061 high_wmark_pages(zone) +
2070 static struct page *alloc_misplaced_dst_page(struct page *page,
2073 int nid = (int) data;
2074 struct page *newpage;
2076 newpage = __alloc_pages_node(nid,
2077 (GFP_HIGHUSER_MOVABLE |
2078 __GFP_THISNODE | __GFP_NOMEMALLOC |
2079 __GFP_NORETRY | __GFP_NOWARN) &
2085 static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2088 int nid = (int) data;
2089 struct page *newpage;
2091 newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2096 prep_transhuge_page(newpage);
2102 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2105 int nr_pages = thp_nr_pages(page);
2107 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2109 /* Do not migrate THP mapped by multiple processes */
2110 if (PageTransHuge(page) && total_mapcount(page) > 1)
2113 /* Avoid migrating to a node that is nearly full */
2114 if (!migrate_balanced_pgdat(pgdat, nr_pages))
2117 if (isolate_lru_page(page))
2120 page_lru = page_is_file_lru(page);
2121 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2125 * Isolating the page has taken another reference, so the
2126 * caller's reference can be safely dropped without the page
2127 * disappearing underneath us during migration.
2134 * Attempt to migrate a misplaced page to the specified destination
2135 * node. Caller is expected to have an elevated reference count on
2136 * the page that will be dropped by this function before returning.
2138 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2141 pg_data_t *pgdat = NODE_DATA(node);
2144 LIST_HEAD(migratepages);
2147 int nr_pages = thp_nr_pages(page);
2150 * PTE mapped THP or HugeTLB page can't reach here so the page could
2151 * be either base page or THP. And it must be head page if it is
2154 compound = PageTransHuge(page);
2157 new = alloc_misplaced_dst_page_thp;
2159 new = alloc_misplaced_dst_page;
2162 * Don't migrate file pages that are mapped in multiple processes
2163 * with execute permissions as they are probably shared libraries.
2165 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2166 (vma->vm_flags & VM_EXEC))
2170 * Also do not migrate dirty pages as not all filesystems can move
2171 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2173 if (page_is_file_lru(page) && PageDirty(page))
2176 isolated = numamigrate_isolate_page(pgdat, page);
2180 list_add(&page->lru, &migratepages);
2181 nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
2182 MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
2184 if (!list_empty(&migratepages)) {
2185 list_del(&page->lru);
2186 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2187 page_is_file_lru(page), -nr_pages);
2188 putback_lru_page(page);
2192 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
2193 BUG_ON(!list_empty(&migratepages));
2200 #endif /* CONFIG_NUMA_BALANCING */
2201 #endif /* CONFIG_NUMA */
2203 #ifdef CONFIG_DEVICE_PRIVATE
2204 static int migrate_vma_collect_skip(unsigned long start,
2206 struct mm_walk *walk)
2208 struct migrate_vma *migrate = walk->private;
2211 for (addr = start; addr < end; addr += PAGE_SIZE) {
2212 migrate->dst[migrate->npages] = 0;
2213 migrate->src[migrate->npages++] = 0;
2219 static int migrate_vma_collect_hole(unsigned long start,
2221 __always_unused int depth,
2222 struct mm_walk *walk)
2224 struct migrate_vma *migrate = walk->private;
2227 /* Only allow populating anonymous memory. */
2228 if (!vma_is_anonymous(walk->vma))
2229 return migrate_vma_collect_skip(start, end, walk);
2231 for (addr = start; addr < end; addr += PAGE_SIZE) {
2232 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2233 migrate->dst[migrate->npages] = 0;
2241 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2242 unsigned long start,
2244 struct mm_walk *walk)
2246 struct migrate_vma *migrate = walk->private;
2247 struct vm_area_struct *vma = walk->vma;
2248 struct mm_struct *mm = vma->vm_mm;
2249 unsigned long addr = start, unmapped = 0;
2254 if (pmd_none(*pmdp))
2255 return migrate_vma_collect_hole(start, end, -1, walk);
2257 if (pmd_trans_huge(*pmdp)) {
2260 ptl = pmd_lock(mm, pmdp);
2261 if (unlikely(!pmd_trans_huge(*pmdp))) {
2266 page = pmd_page(*pmdp);
2267 if (is_huge_zero_page(page)) {
2269 split_huge_pmd(vma, pmdp, addr);
2270 if (pmd_trans_unstable(pmdp))
2271 return migrate_vma_collect_skip(start, end,
2278 if (unlikely(!trylock_page(page)))
2279 return migrate_vma_collect_skip(start, end,
2281 ret = split_huge_page(page);
2285 return migrate_vma_collect_skip(start, end,
2287 if (pmd_none(*pmdp))
2288 return migrate_vma_collect_hole(start, end, -1,
2293 if (unlikely(pmd_bad(*pmdp)))
2294 return migrate_vma_collect_skip(start, end, walk);
2296 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2297 arch_enter_lazy_mmu_mode();
2299 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2300 unsigned long mpfn = 0, pfn;
2307 if (pte_none(pte)) {
2308 if (vma_is_anonymous(vma)) {
2309 mpfn = MIGRATE_PFN_MIGRATE;
2315 if (!pte_present(pte)) {
2317 * Only care about unaddressable device page special
2318 * page table entry. Other special swap entries are not
2319 * migratable, and we ignore regular swapped page.
2321 entry = pte_to_swp_entry(pte);
2322 if (!is_device_private_entry(entry))
2325 page = pfn_swap_entry_to_page(entry);
2326 if (!(migrate->flags &
2327 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2328 page->pgmap->owner != migrate->pgmap_owner)
2331 mpfn = migrate_pfn(page_to_pfn(page)) |
2332 MIGRATE_PFN_MIGRATE;
2333 if (is_writable_device_private_entry(entry))
2334 mpfn |= MIGRATE_PFN_WRITE;
2336 if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2339 if (is_zero_pfn(pfn)) {
2340 mpfn = MIGRATE_PFN_MIGRATE;
2344 page = vm_normal_page(migrate->vma, addr, pte);
2345 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2346 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2349 /* FIXME support THP */
2350 if (!page || !page->mapping || PageTransCompound(page)) {
2356 * By getting a reference on the page we pin it and that blocks
2357 * any kind of migration. Side effect is that it "freezes" the
2360 * We drop this reference after isolating the page from the lru
2361 * for non device page (device page are not on the lru and thus
2362 * can't be dropped from it).
2367 * Optimize for the common case where page is only mapped once
2368 * in one process. If we can lock the page, then we can safely
2369 * set up a special migration page table entry now.
2371 if (trylock_page(page)) {
2375 ptep_get_and_clear(mm, addr, ptep);
2377 /* Setup special migration page table entry */
2378 if (mpfn & MIGRATE_PFN_WRITE)
2379 entry = make_writable_migration_entry(
2382 entry = make_readable_migration_entry(
2384 swp_pte = swp_entry_to_pte(entry);
2385 if (pte_present(pte)) {
2386 if (pte_soft_dirty(pte))
2387 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2388 if (pte_uffd_wp(pte))
2389 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2391 if (pte_swp_soft_dirty(pte))
2392 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2393 if (pte_swp_uffd_wp(pte))
2394 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2396 set_pte_at(mm, addr, ptep, swp_pte);
2399 * This is like regular unmap: we remove the rmap and
2400 * drop page refcount. Page won't be freed, as we took
2401 * a reference just above.
2403 page_remove_rmap(page, false);
2406 if (pte_present(pte))
2414 migrate->dst[migrate->npages] = 0;
2415 migrate->src[migrate->npages++] = mpfn;
2417 arch_leave_lazy_mmu_mode();
2418 pte_unmap_unlock(ptep - 1, ptl);
2420 /* Only flush the TLB if we actually modified any entries */
2422 flush_tlb_range(walk->vma, start, end);
2427 static const struct mm_walk_ops migrate_vma_walk_ops = {
2428 .pmd_entry = migrate_vma_collect_pmd,
2429 .pte_hole = migrate_vma_collect_hole,
2433 * migrate_vma_collect() - collect pages over a range of virtual addresses
2434 * @migrate: migrate struct containing all migration information
2436 * This will walk the CPU page table. For each virtual address backed by a
2437 * valid page, it updates the src array and takes a reference on the page, in
2438 * order to pin the page until we lock it and unmap it.
2440 static void migrate_vma_collect(struct migrate_vma *migrate)
2442 struct mmu_notifier_range range;
2445 * Note that the pgmap_owner is passed to the mmu notifier callback so
2446 * that the registered device driver can skip invalidating device
2447 * private page mappings that won't be migrated.
2449 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2450 migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
2451 migrate->pgmap_owner);
2452 mmu_notifier_invalidate_range_start(&range);
2454 walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2455 &migrate_vma_walk_ops, migrate);
2457 mmu_notifier_invalidate_range_end(&range);
2458 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2462 * migrate_vma_check_page() - check if page is pinned or not
2463 * @page: struct page to check
2465 * Pinned pages cannot be migrated. This is the same test as in
2466 * folio_migrate_mapping(), except that here we allow migration of a
2469 static bool migrate_vma_check_page(struct page *page)
2472 * One extra ref because caller holds an extra reference, either from
2473 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2479 * FIXME support THP (transparent huge page), it is bit more complex to
2480 * check them than regular pages, because they can be mapped with a pmd
2481 * or with a pte (split pte mapping).
2483 if (PageCompound(page))
2486 /* Page from ZONE_DEVICE have one extra reference */
2487 if (is_zone_device_page(page)) {
2489 * Private page can never be pin as they have no valid pte and
2490 * GUP will fail for those. Yet if there is a pending migration
2491 * a thread might try to wait on the pte migration entry and
2492 * will bump the page reference count. Sadly there is no way to
2493 * differentiate a regular pin from migration wait. Hence to
2494 * avoid 2 racing thread trying to migrate back to CPU to enter
2495 * infinite loop (one stopping migration because the other is
2496 * waiting on pte migration entry). We always return true here.
2498 * FIXME proper solution is to rework migration_entry_wait() so
2499 * it does not need to take a reference on page.
2501 return is_device_private_page(page);
2504 /* For file back page */
2505 if (page_mapping(page))
2506 extra += 1 + page_has_private(page);
2508 if ((page_count(page) - extra) > page_mapcount(page))
2515 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2516 * @migrate: migrate struct containing all migration information
2518 * Isolate pages from the LRU and replace mappings (CPU page table pte) with a
2519 * special migration pte entry and check if it has been pinned. Pinned pages are
2520 * restored because we cannot migrate them.
2522 * This is the last step before we call the device driver callback to allocate
2523 * destination memory and copy contents of original page over to new page.
2525 static void migrate_vma_unmap(struct migrate_vma *migrate)
2527 const unsigned long npages = migrate->npages;
2528 const unsigned long start = migrate->start;
2529 unsigned long addr, i, restore = 0;
2530 bool allow_drain = true;
2534 for (i = 0; i < npages; i++) {
2535 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2540 /* ZONE_DEVICE pages are not on LRU */
2541 if (!is_zone_device_page(page)) {
2542 if (!PageLRU(page) && allow_drain) {
2543 /* Drain CPU's pagevec */
2544 lru_add_drain_all();
2545 allow_drain = false;
2548 if (isolate_lru_page(page)) {
2549 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2555 /* Drop the reference we took in collect */
2559 if (page_mapped(page))
2560 try_to_migrate(page, 0);
2562 if (page_mapped(page) || !migrate_vma_check_page(page)) {
2563 if (!is_zone_device_page(page)) {
2565 putback_lru_page(page);
2568 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2575 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2576 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2578 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2581 remove_migration_ptes(page, page, false);
2583 migrate->src[i] = 0;
2591 * migrate_vma_setup() - prepare to migrate a range of memory
2592 * @args: contains the vma, start, and pfns arrays for the migration
2594 * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2597 * Prepare to migrate a range of memory virtual address range by collecting all
2598 * the pages backing each virtual address in the range, saving them inside the
2599 * src array. Then lock those pages and unmap them. Once the pages are locked
2600 * and unmapped, check whether each page is pinned or not. Pages that aren't
2601 * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2602 * corresponding src array entry. Then restores any pages that are pinned, by
2603 * remapping and unlocking those pages.
2605 * The caller should then allocate destination memory and copy source memory to
2606 * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2607 * flag set). Once these are allocated and copied, the caller must update each
2608 * corresponding entry in the dst array with the pfn value of the destination
2609 * page and with MIGRATE_PFN_VALID. Destination pages must be locked via
2612 * Note that the caller does not have to migrate all the pages that are marked
2613 * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2614 * device memory to system memory. If the caller cannot migrate a device page
2615 * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2616 * consequences for the userspace process, so it must be avoided if at all
2619 * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2620 * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2621 * allowing the caller to allocate device memory for those unbacked virtual
2622 * addresses. For this the caller simply has to allocate device memory and
2623 * properly set the destination entry like for regular migration. Note that
2624 * this can still fail, and thus inside the device driver you must check if the
2625 * migration was successful for those entries after calling migrate_vma_pages(),
2626 * just like for regular migration.
2628 * After that, the callers must call migrate_vma_pages() to go over each entry
2629 * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2630 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2631 * then migrate_vma_pages() to migrate struct page information from the source
2632 * struct page to the destination struct page. If it fails to migrate the
2633 * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2636 * At this point all successfully migrated pages have an entry in the src
2637 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2638 * array entry with MIGRATE_PFN_VALID flag set.
2640 * Once migrate_vma_pages() returns the caller may inspect which pages were
2641 * successfully migrated, and which were not. Successfully migrated pages will
2642 * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2644 * It is safe to update device page table after migrate_vma_pages() because
2645 * both destination and source page are still locked, and the mmap_lock is held
2646 * in read mode (hence no one can unmap the range being migrated).
2648 * Once the caller is done cleaning up things and updating its page table (if it
2649 * chose to do so, this is not an obligation) it finally calls
2650 * migrate_vma_finalize() to update the CPU page table to point to new pages
2651 * for successfully migrated pages or otherwise restore the CPU page table to
2652 * point to the original source pages.
2654 int migrate_vma_setup(struct migrate_vma *args)
2656 long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2658 args->start &= PAGE_MASK;
2659 args->end &= PAGE_MASK;
2660 if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2661 (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2665 if (args->start < args->vma->vm_start ||
2666 args->start >= args->vma->vm_end)
2668 if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2670 if (!args->src || !args->dst)
2673 memset(args->src, 0, sizeof(*args->src) * nr_pages);
2677 migrate_vma_collect(args);
2680 migrate_vma_unmap(args);
2683 * At this point pages are locked and unmapped, and thus they have
2684 * stable content and can safely be copied to destination memory that
2685 * is allocated by the drivers.
2690 EXPORT_SYMBOL(migrate_vma_setup);
2693 * This code closely matches the code in:
2694 * __handle_mm_fault()
2695 * handle_pte_fault()
2696 * do_anonymous_page()
2697 * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2700 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2705 struct vm_area_struct *vma = migrate->vma;
2706 struct mm_struct *mm = vma->vm_mm;
2716 /* Only allow populating anonymous memory */
2717 if (!vma_is_anonymous(vma))
2720 pgdp = pgd_offset(mm, addr);
2721 p4dp = p4d_alloc(mm, pgdp, addr);
2724 pudp = pud_alloc(mm, p4dp, addr);
2727 pmdp = pmd_alloc(mm, pudp, addr);
2731 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2735 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2736 * pte_offset_map() on pmds where a huge pmd might be created
2737 * from a different thread.
2739 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2740 * parallel threads are excluded by other means.
2742 * Here we only have mmap_read_lock(mm).
2744 if (pte_alloc(mm, pmdp))
2747 /* See the comment in pte_alloc_one_map() */
2748 if (unlikely(pmd_trans_unstable(pmdp)))
2751 if (unlikely(anon_vma_prepare(vma)))
2753 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
2757 * The memory barrier inside __SetPageUptodate makes sure that
2758 * preceding stores to the page contents become visible before
2759 * the set_pte_at() write.
2761 __SetPageUptodate(page);
2763 if (is_zone_device_page(page)) {
2764 if (is_device_private_page(page)) {
2765 swp_entry_t swp_entry;
2767 if (vma->vm_flags & VM_WRITE)
2768 swp_entry = make_writable_device_private_entry(
2771 swp_entry = make_readable_device_private_entry(
2773 entry = swp_entry_to_pte(swp_entry);
2776 * For now we only support migrating to un-addressable
2779 pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2783 entry = mk_pte(page, vma->vm_page_prot);
2784 if (vma->vm_flags & VM_WRITE)
2785 entry = pte_mkwrite(pte_mkdirty(entry));
2788 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2790 if (check_stable_address_space(mm))
2793 if (pte_present(*ptep)) {
2794 unsigned long pfn = pte_pfn(*ptep);
2796 if (!is_zero_pfn(pfn))
2799 } else if (!pte_none(*ptep))
2803 * Check for userfaultfd but do not deliver the fault. Instead,
2806 if (userfaultfd_missing(vma))
2809 inc_mm_counter(mm, MM_ANONPAGES);
2810 page_add_new_anon_rmap(page, vma, addr, false);
2811 if (!is_zone_device_page(page))
2812 lru_cache_add_inactive_or_unevictable(page, vma);
2816 flush_cache_page(vma, addr, pte_pfn(*ptep));
2817 ptep_clear_flush_notify(vma, addr, ptep);
2818 set_pte_at_notify(mm, addr, ptep, entry);
2819 update_mmu_cache(vma, addr, ptep);
2821 /* No need to invalidate - it was non-present before */
2822 set_pte_at(mm, addr, ptep, entry);
2823 update_mmu_cache(vma, addr, ptep);
2826 pte_unmap_unlock(ptep, ptl);
2827 *src = MIGRATE_PFN_MIGRATE;
2831 pte_unmap_unlock(ptep, ptl);
2833 *src &= ~MIGRATE_PFN_MIGRATE;
2837 * migrate_vma_pages() - migrate meta-data from src page to dst page
2838 * @migrate: migrate struct containing all migration information
2840 * This migrates struct page meta-data from source struct page to destination
2841 * struct page. This effectively finishes the migration from source page to the
2844 void migrate_vma_pages(struct migrate_vma *migrate)
2846 const unsigned long npages = migrate->npages;
2847 const unsigned long start = migrate->start;
2848 struct mmu_notifier_range range;
2849 unsigned long addr, i;
2850 bool notified = false;
2852 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2853 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2854 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2855 struct address_space *mapping;
2859 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2864 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2869 mmu_notifier_range_init_owner(&range,
2870 MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2871 migrate->vma->vm_mm, addr, migrate->end,
2872 migrate->pgmap_owner);
2873 mmu_notifier_invalidate_range_start(&range);
2875 migrate_vma_insert_page(migrate, addr, newpage,
2880 mapping = page_mapping(page);
2882 if (is_zone_device_page(newpage)) {
2883 if (is_device_private_page(newpage)) {
2885 * For now only support private anonymous when
2886 * migrating to un-addressable device memory.
2889 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2894 * Other types of ZONE_DEVICE page are not
2897 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2902 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2903 if (r != MIGRATEPAGE_SUCCESS)
2904 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2908 * No need to double call mmu_notifier->invalidate_range() callback as
2909 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
2910 * did already call it.
2913 mmu_notifier_invalidate_range_only_end(&range);
2915 EXPORT_SYMBOL(migrate_vma_pages);
2918 * migrate_vma_finalize() - restore CPU page table entry
2919 * @migrate: migrate struct containing all migration information
2921 * This replaces the special migration pte entry with either a mapping to the
2922 * new page if migration was successful for that page, or to the original page
2925 * This also unlocks the pages and puts them back on the lru, or drops the extra
2926 * refcount, for device pages.
2928 void migrate_vma_finalize(struct migrate_vma *migrate)
2930 const unsigned long npages = migrate->npages;
2933 for (i = 0; i < npages; i++) {
2934 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2935 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2939 unlock_page(newpage);
2945 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
2947 unlock_page(newpage);
2953 remove_migration_ptes(page, newpage, false);
2956 if (is_zone_device_page(page))
2959 putback_lru_page(page);
2961 if (newpage != page) {
2962 unlock_page(newpage);
2963 if (is_zone_device_page(newpage))
2966 putback_lru_page(newpage);
2970 EXPORT_SYMBOL(migrate_vma_finalize);
2971 #endif /* CONFIG_DEVICE_PRIVATE */
2973 #if defined(CONFIG_HOTPLUG_CPU)
2974 /* Disable reclaim-based migration. */
2975 static void __disable_all_migrate_targets(void)
2979 for_each_online_node(node)
2980 node_demotion[node] = NUMA_NO_NODE;
2983 static void disable_all_migrate_targets(void)
2985 __disable_all_migrate_targets();
2988 * Ensure that the "disable" is visible across the system.
2989 * Readers will see either a combination of before+disable
2990 * state or disable+after. They will never see before and
2991 * after state together.
2993 * The before+after state together might have cycles and
2994 * could cause readers to do things like loop until this
2995 * function finishes. This ensures they can only see a
2996 * single "bad" read and would, for instance, only loop
3003 * Find an automatic demotion target for 'node'.
3004 * Failing here is OK. It might just indicate
3005 * being at the end of a chain.
3007 static int establish_migrate_target(int node, nodemask_t *used)
3009 int migration_target;
3012 * Can not set a migration target on a
3013 * node with it already set.
3015 * No need for READ_ONCE() here since this
3016 * in the write path for node_demotion[].
3017 * This should be the only thread writing.
3019 if (node_demotion[node] != NUMA_NO_NODE)
3020 return NUMA_NO_NODE;
3022 migration_target = find_next_best_node(node, used);
3023 if (migration_target == NUMA_NO_NODE)
3024 return NUMA_NO_NODE;
3026 node_demotion[node] = migration_target;
3028 return migration_target;
3032 * When memory fills up on a node, memory contents can be
3033 * automatically migrated to another node instead of
3034 * discarded at reclaim.
3036 * Establish a "migration path" which will start at nodes
3037 * with CPUs and will follow the priorities used to build the
3038 * page allocator zonelists.
3040 * The difference here is that cycles must be avoided. If
3041 * node0 migrates to node1, then neither node1, nor anything
3042 * node1 migrates to can migrate to node0.
3044 * This function can run simultaneously with readers of
3045 * node_demotion[]. However, it can not run simultaneously
3046 * with itself. Exclusion is provided by memory hotplug events
3047 * being single-threaded.
3049 static void __set_migration_target_nodes(void)
3051 nodemask_t next_pass = NODE_MASK_NONE;
3052 nodemask_t this_pass = NODE_MASK_NONE;
3053 nodemask_t used_targets = NODE_MASK_NONE;
3057 * Avoid any oddities like cycles that could occur
3058 * from changes in the topology. This will leave
3059 * a momentary gap when migration is disabled.
3061 disable_all_migrate_targets();
3064 * Allocations go close to CPUs, first. Assume that
3065 * the migration path starts at the nodes with CPUs.
3067 next_pass = node_states[N_CPU];
3069 this_pass = next_pass;
3070 next_pass = NODE_MASK_NONE;
3072 * To avoid cycles in the migration "graph", ensure
3073 * that migration sources are not future targets by
3074 * setting them in 'used_targets'. Do this only
3075 * once per pass so that multiple source nodes can
3076 * share a target node.
3078 * 'used_targets' will become unavailable in future
3079 * passes. This limits some opportunities for
3080 * multiple source nodes to share a destination.
3082 nodes_or(used_targets, used_targets, this_pass);
3083 for_each_node_mask(node, this_pass) {
3084 int target_node = establish_migrate_target(node, &used_targets);
3086 if (target_node == NUMA_NO_NODE)
3090 * Visit targets from this pass in the next pass.
3091 * Eventually, every node will have been part of
3092 * a pass, and will become set in 'used_targets'.
3094 node_set(target_node, next_pass);
3097 * 'next_pass' contains nodes which became migration
3098 * targets in this pass. Make additional passes until
3099 * no more migrations targets are available.
3101 if (!nodes_empty(next_pass))
3106 * For callers that do not hold get_online_mems() already.
3108 static void set_migration_target_nodes(void)
3111 __set_migration_target_nodes();
3116 * This leaves migrate-on-reclaim transiently disabled between
3117 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
3118 * whether reclaim-based migration is enabled or not, which
3119 * ensures that the user can turn reclaim-based migration at
3120 * any time without needing to recalculate migration targets.
3122 * These callbacks already hold get_online_mems(). That is why
3123 * __set_migration_target_nodes() can be used as opposed to
3124 * set_migration_target_nodes().
3126 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
3127 unsigned long action, void *_arg)
3129 struct memory_notify *arg = _arg;
3132 * Only update the node migration order when a node is
3133 * changing status, like online->offline. This avoids
3134 * the overhead of synchronize_rcu() in most cases.
3136 if (arg->status_change_nid < 0)
3137 return notifier_from_errno(0);
3140 case MEM_GOING_OFFLINE:
3142 * Make sure there are not transient states where
3143 * an offline node is a migration target. This
3144 * will leave migration disabled until the offline
3145 * completes and the MEM_OFFLINE case below runs.
3147 disable_all_migrate_targets();
3152 * Recalculate the target nodes once the node
3153 * reaches its final state (online or offline).
3155 __set_migration_target_nodes();
3157 case MEM_CANCEL_OFFLINE:
3159 * MEM_GOING_OFFLINE disabled all the migration
3160 * targets. Reenable them.
3162 __set_migration_target_nodes();
3164 case MEM_GOING_ONLINE:
3165 case MEM_CANCEL_ONLINE:
3169 return notifier_from_errno(0);
3173 * React to hotplug events that might affect the migration targets
3174 * like events that online or offline NUMA nodes.
3176 * The ordering is also currently dependent on which nodes have
3177 * CPUs. That means we need CPU on/offline notification too.
3179 static int migration_online_cpu(unsigned int cpu)
3181 set_migration_target_nodes();
3185 static int migration_offline_cpu(unsigned int cpu)
3187 set_migration_target_nodes();
3191 static int __init migrate_on_reclaim_init(void)
3195 ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3196 NULL, migration_offline_cpu);
3198 * In the unlikely case that this fails, the automatic
3199 * migration targets may become suboptimal for nodes
3200 * where N_CPU changes. With such a small impact in a
3201 * rare case, do not bother trying to do anything special.
3204 ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3205 migration_online_cpu, NULL);
3208 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3211 late_initcall(migrate_on_reclaim_init);
3212 #endif /* CONFIG_HOTPLUG_CPU */
3214 bool numa_demotion_enabled = false;
3217 static ssize_t numa_demotion_enabled_show(struct kobject *kobj,
3218 struct kobj_attribute *attr, char *buf)
3220 return sysfs_emit(buf, "%s\n",
3221 numa_demotion_enabled ? "true" : "false");
3224 static ssize_t numa_demotion_enabled_store(struct kobject *kobj,
3225 struct kobj_attribute *attr,
3226 const char *buf, size_t count)
3228 if (!strncmp(buf, "true", 4) || !strncmp(buf, "1", 1))
3229 numa_demotion_enabled = true;
3230 else if (!strncmp(buf, "false", 5) || !strncmp(buf, "0", 1))
3231 numa_demotion_enabled = false;
3238 static struct kobj_attribute numa_demotion_enabled_attr =
3239 __ATTR(demotion_enabled, 0644, numa_demotion_enabled_show,
3240 numa_demotion_enabled_store);
3242 static struct attribute *numa_attrs[] = {
3243 &numa_demotion_enabled_attr.attr,
3247 static const struct attribute_group numa_attr_group = {
3248 .attrs = numa_attrs,
3251 static int __init numa_init_sysfs(void)
3254 struct kobject *numa_kobj;
3256 numa_kobj = kobject_create_and_add("numa", mm_kobj);
3258 pr_err("failed to create numa kobject\n");
3261 err = sysfs_create_group(numa_kobj, &numa_attr_group);
3263 pr_err("failed to register numa group\n");
3269 kobject_put(numa_kobj);
3272 subsys_initcall(numa_init_sysfs);