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_count(folio) != expected_count ||
408 xas_load(&xas) != folio) {
409 xas_unlock_irq(&xas);
413 if (!folio_ref_freeze(folio, expected_count)) {
414 xas_unlock_irq(&xas);
419 * Now we know that no one else is looking at the folio:
420 * no turning back from here.
422 newfolio->index = folio->index;
423 newfolio->mapping = folio->mapping;
424 folio_ref_add(newfolio, nr); /* add cache reference */
425 if (folio_test_swapbacked(folio)) {
426 __folio_set_swapbacked(newfolio);
427 if (folio_test_swapcache(folio)) {
428 folio_set_swapcache(newfolio);
429 newfolio->private = folio_get_private(folio);
432 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
435 /* Move dirty while page refs frozen and newpage not yet exposed */
436 dirty = folio_test_dirty(folio);
438 folio_clear_dirty(folio);
439 folio_set_dirty(newfolio);
442 xas_store(&xas, newfolio);
446 for (i = 1; i < nr; i++) {
448 xas_store(&xas, newfolio);
453 * Drop cache reference from old page by unfreezing
454 * to one less reference.
455 * We know this isn't the last reference.
457 folio_ref_unfreeze(folio, expected_count - nr);
460 /* Leave irq disabled to prevent preemption while updating stats */
463 * If moved to a different zone then also account
464 * the page for that zone. Other VM counters will be
465 * taken care of when we establish references to the
466 * new page and drop references to the old page.
468 * Note that anonymous pages are accounted for
469 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
470 * are mapped to swap space.
472 if (newzone != oldzone) {
473 struct lruvec *old_lruvec, *new_lruvec;
474 struct mem_cgroup *memcg;
476 memcg = folio_memcg(folio);
477 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
478 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
480 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
481 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
482 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
483 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
484 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
487 if (folio_test_swapcache(folio)) {
488 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
489 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
492 if (dirty && mapping_can_writeback(mapping)) {
493 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
494 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
495 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
496 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
501 return MIGRATEPAGE_SUCCESS;
503 EXPORT_SYMBOL(folio_migrate_mapping);
506 * The expected number of remaining references is the same as that
507 * of folio_migrate_mapping().
509 int migrate_huge_page_move_mapping(struct address_space *mapping,
510 struct page *newpage, struct page *page)
512 XA_STATE(xas, &mapping->i_pages, page_index(page));
516 expected_count = 2 + page_has_private(page);
517 if (page_count(page) != expected_count || xas_load(&xas) != page) {
518 xas_unlock_irq(&xas);
522 if (!page_ref_freeze(page, expected_count)) {
523 xas_unlock_irq(&xas);
527 newpage->index = page->index;
528 newpage->mapping = page->mapping;
532 xas_store(&xas, newpage);
534 page_ref_unfreeze(page, expected_count - 1);
536 xas_unlock_irq(&xas);
538 return MIGRATEPAGE_SUCCESS;
542 * Copy the flags and some other ancillary information
544 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
548 if (folio_test_error(folio))
549 folio_set_error(newfolio);
550 if (folio_test_referenced(folio))
551 folio_set_referenced(newfolio);
552 if (folio_test_uptodate(folio))
553 folio_mark_uptodate(newfolio);
554 if (folio_test_clear_active(folio)) {
555 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
556 folio_set_active(newfolio);
557 } else if (folio_test_clear_unevictable(folio))
558 folio_set_unevictable(newfolio);
559 if (folio_test_workingset(folio))
560 folio_set_workingset(newfolio);
561 if (folio_test_checked(folio))
562 folio_set_checked(newfolio);
563 if (folio_test_mappedtodisk(folio))
564 folio_set_mappedtodisk(newfolio);
566 /* Move dirty on pages not done by folio_migrate_mapping() */
567 if (folio_test_dirty(folio))
568 folio_set_dirty(newfolio);
570 if (folio_test_young(folio))
571 folio_set_young(newfolio);
572 if (folio_test_idle(folio))
573 folio_set_idle(newfolio);
576 * Copy NUMA information to the new page, to prevent over-eager
577 * future migrations of this same page.
579 cpupid = page_cpupid_xchg_last(&folio->page, -1);
580 page_cpupid_xchg_last(&newfolio->page, cpupid);
582 folio_migrate_ksm(newfolio, folio);
584 * Please do not reorder this without considering how mm/ksm.c's
585 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
587 if (folio_test_swapcache(folio))
588 folio_clear_swapcache(folio);
589 folio_clear_private(folio);
591 /* page->private contains hugetlb specific flags */
592 if (!folio_test_hugetlb(folio))
593 folio->private = NULL;
596 * If any waiters have accumulated on the new page then
599 if (folio_test_writeback(newfolio))
600 folio_end_writeback(newfolio);
603 * PG_readahead shares the same bit with PG_reclaim. The above
604 * end_page_writeback() may clear PG_readahead mistakenly, so set the
607 if (folio_test_readahead(folio))
608 folio_set_readahead(newfolio);
610 folio_copy_owner(newfolio, folio);
612 if (!folio_test_hugetlb(folio))
613 mem_cgroup_migrate(folio, newfolio);
615 EXPORT_SYMBOL(folio_migrate_flags);
617 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
619 folio_copy(newfolio, folio);
620 folio_migrate_flags(newfolio, folio);
622 EXPORT_SYMBOL(folio_migrate_copy);
624 /************************************************************
625 * Migration functions
626 ***********************************************************/
629 * Common logic to directly migrate a single LRU page suitable for
630 * pages that do not use PagePrivate/PagePrivate2.
632 * Pages are locked upon entry and exit.
634 int migrate_page(struct address_space *mapping,
635 struct page *newpage, struct page *page,
636 enum migrate_mode mode)
638 struct folio *newfolio = page_folio(newpage);
639 struct folio *folio = page_folio(page);
642 BUG_ON(folio_test_writeback(folio)); /* Writeback must be complete */
644 rc = folio_migrate_mapping(mapping, newfolio, folio, 0);
646 if (rc != MIGRATEPAGE_SUCCESS)
649 if (mode != MIGRATE_SYNC_NO_COPY)
650 folio_migrate_copy(newfolio, folio);
652 folio_migrate_flags(newfolio, folio);
653 return MIGRATEPAGE_SUCCESS;
655 EXPORT_SYMBOL(migrate_page);
658 /* Returns true if all buffers are successfully locked */
659 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
660 enum migrate_mode mode)
662 struct buffer_head *bh = head;
664 /* Simple case, sync compaction */
665 if (mode != MIGRATE_ASYNC) {
668 bh = bh->b_this_page;
670 } while (bh != head);
675 /* async case, we cannot block on lock_buffer so use trylock_buffer */
677 if (!trylock_buffer(bh)) {
679 * We failed to lock the buffer and cannot stall in
680 * async migration. Release the taken locks
682 struct buffer_head *failed_bh = bh;
684 while (bh != failed_bh) {
686 bh = bh->b_this_page;
691 bh = bh->b_this_page;
692 } while (bh != head);
696 static int __buffer_migrate_page(struct address_space *mapping,
697 struct page *newpage, struct page *page, enum migrate_mode mode,
700 struct buffer_head *bh, *head;
704 if (!page_has_buffers(page))
705 return migrate_page(mapping, newpage, page, mode);
707 /* Check whether page does not have extra refs before we do more work */
708 expected_count = expected_page_refs(mapping, page);
709 if (page_count(page) != expected_count)
712 head = page_buffers(page);
713 if (!buffer_migrate_lock_buffers(head, mode))
718 bool invalidated = false;
722 spin_lock(&mapping->private_lock);
725 if (atomic_read(&bh->b_count)) {
729 bh = bh->b_this_page;
730 } while (bh != head);
736 spin_unlock(&mapping->private_lock);
737 invalidate_bh_lrus();
739 goto recheck_buffers;
743 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
744 if (rc != MIGRATEPAGE_SUCCESS)
747 attach_page_private(newpage, detach_page_private(page));
751 set_bh_page(bh, newpage, bh_offset(bh));
752 bh = bh->b_this_page;
754 } while (bh != head);
756 if (mode != MIGRATE_SYNC_NO_COPY)
757 migrate_page_copy(newpage, page);
759 migrate_page_states(newpage, page);
761 rc = MIGRATEPAGE_SUCCESS;
764 spin_unlock(&mapping->private_lock);
768 bh = bh->b_this_page;
770 } while (bh != head);
776 * Migration function for pages with buffers. This function can only be used
777 * if the underlying filesystem guarantees that no other references to "page"
778 * exist. For example attached buffer heads are accessed only under page lock.
780 int buffer_migrate_page(struct address_space *mapping,
781 struct page *newpage, struct page *page, enum migrate_mode mode)
783 return __buffer_migrate_page(mapping, newpage, page, mode, false);
785 EXPORT_SYMBOL(buffer_migrate_page);
788 * Same as above except that this variant is more careful and checks that there
789 * are also no buffer head references. This function is the right one for
790 * mappings where buffer heads are directly looked up and referenced (such as
791 * block device mappings).
793 int buffer_migrate_page_norefs(struct address_space *mapping,
794 struct page *newpage, struct page *page, enum migrate_mode mode)
796 return __buffer_migrate_page(mapping, newpage, page, mode, true);
801 * Writeback a page to clean the dirty state
803 static int writeout(struct address_space *mapping, struct page *page)
805 struct writeback_control wbc = {
806 .sync_mode = WB_SYNC_NONE,
809 .range_end = LLONG_MAX,
814 if (!mapping->a_ops->writepage)
815 /* No write method for the address space */
818 if (!clear_page_dirty_for_io(page))
819 /* Someone else already triggered a write */
823 * A dirty page may imply that the underlying filesystem has
824 * the page on some queue. So the page must be clean for
825 * migration. Writeout may mean we loose the lock and the
826 * page state is no longer what we checked for earlier.
827 * At this point we know that the migration attempt cannot
830 remove_migration_ptes(page, page, false);
832 rc = mapping->a_ops->writepage(page, &wbc);
834 if (rc != AOP_WRITEPAGE_ACTIVATE)
835 /* unlocked. Relock */
838 return (rc < 0) ? -EIO : -EAGAIN;
842 * Default handling if a filesystem does not provide a migration function.
844 static int fallback_migrate_page(struct address_space *mapping,
845 struct page *newpage, struct page *page, enum migrate_mode mode)
847 if (PageDirty(page)) {
848 /* Only writeback pages in full synchronous migration */
851 case MIGRATE_SYNC_NO_COPY:
856 return writeout(mapping, page);
860 * Buffers may be managed in a filesystem specific way.
861 * We must have no buffers or drop them.
863 if (page_has_private(page) &&
864 !try_to_release_page(page, GFP_KERNEL))
865 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
867 return migrate_page(mapping, newpage, page, mode);
871 * Move a page to a newly allocated page
872 * The page is locked and all ptes have been successfully removed.
874 * The new page will have replaced the old page if this function
879 * MIGRATEPAGE_SUCCESS - success
881 static int move_to_new_page(struct page *newpage, struct page *page,
882 enum migrate_mode mode)
884 struct address_space *mapping;
886 bool is_lru = !__PageMovable(page);
888 VM_BUG_ON_PAGE(!PageLocked(page), page);
889 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
891 mapping = page_mapping(page);
893 if (likely(is_lru)) {
895 rc = migrate_page(mapping, newpage, page, mode);
896 else if (mapping->a_ops->migratepage)
898 * Most pages have a mapping and most filesystems
899 * provide a migratepage callback. Anonymous pages
900 * are part of swap space which also has its own
901 * migratepage callback. This is the most common path
902 * for page migration.
904 rc = mapping->a_ops->migratepage(mapping, newpage,
907 rc = fallback_migrate_page(mapping, newpage,
911 * In case of non-lru page, it could be released after
912 * isolation step. In that case, we shouldn't try migration.
914 VM_BUG_ON_PAGE(!PageIsolated(page), page);
915 if (!PageMovable(page)) {
916 rc = MIGRATEPAGE_SUCCESS;
917 __ClearPageIsolated(page);
921 rc = mapping->a_ops->migratepage(mapping, newpage,
923 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
924 !PageIsolated(page));
928 * When successful, old pagecache page->mapping must be cleared before
929 * page is freed; but stats require that PageAnon be left as PageAnon.
931 if (rc == MIGRATEPAGE_SUCCESS) {
932 if (__PageMovable(page)) {
933 VM_BUG_ON_PAGE(!PageIsolated(page), page);
936 * We clear PG_movable under page_lock so any compactor
937 * cannot try to migrate this page.
939 __ClearPageIsolated(page);
943 * Anonymous and movable page->mapping will be cleared by
944 * free_pages_prepare so don't reset it here for keeping
945 * the type to work PageAnon, for example.
947 if (!PageMappingFlags(page))
948 page->mapping = NULL;
950 if (likely(!is_zone_device_page(newpage)))
951 flush_dcache_page(newpage);
958 static int __unmap_and_move(struct page *page, struct page *newpage,
959 int force, enum migrate_mode mode)
962 bool page_was_mapped = false;
963 struct anon_vma *anon_vma = NULL;
964 bool is_lru = !__PageMovable(page);
966 if (!trylock_page(page)) {
967 if (!force || mode == MIGRATE_ASYNC)
971 * It's not safe for direct compaction to call lock_page.
972 * For example, during page readahead pages are added locked
973 * to the LRU. Later, when the IO completes the pages are
974 * marked uptodate and unlocked. However, the queueing
975 * could be merging multiple pages for one bio (e.g.
976 * mpage_readahead). If an allocation happens for the
977 * second or third page, the process can end up locking
978 * the same page twice and deadlocking. Rather than
979 * trying to be clever about what pages can be locked,
980 * avoid the use of lock_page for direct compaction
983 if (current->flags & PF_MEMALLOC)
989 if (PageWriteback(page)) {
991 * Only in the case of a full synchronous migration is it
992 * necessary to wait for PageWriteback. In the async case,
993 * the retry loop is too short and in the sync-light case,
994 * the overhead of stalling is too much
998 case MIGRATE_SYNC_NO_COPY:
1006 wait_on_page_writeback(page);
1010 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1011 * we cannot notice that anon_vma is freed while we migrates a page.
1012 * This get_anon_vma() delays freeing anon_vma pointer until the end
1013 * of migration. File cache pages are no problem because of page_lock()
1014 * File Caches may use write_page() or lock_page() in migration, then,
1015 * just care Anon page here.
1017 * Only page_get_anon_vma() understands the subtleties of
1018 * getting a hold on an anon_vma from outside one of its mms.
1019 * But if we cannot get anon_vma, then we won't need it anyway,
1020 * because that implies that the anon page is no longer mapped
1021 * (and cannot be remapped so long as we hold the page lock).
1023 if (PageAnon(page) && !PageKsm(page))
1024 anon_vma = page_get_anon_vma(page);
1027 * Block others from accessing the new page when we get around to
1028 * establishing additional references. We are usually the only one
1029 * holding a reference to newpage at this point. We used to have a BUG
1030 * here if trylock_page(newpage) fails, but would like to allow for
1031 * cases where there might be a race with the previous use of newpage.
1032 * This is much like races on refcount of oldpage: just don't BUG().
1034 if (unlikely(!trylock_page(newpage)))
1037 if (unlikely(!is_lru)) {
1038 rc = move_to_new_page(newpage, page, mode);
1039 goto out_unlock_both;
1043 * Corner case handling:
1044 * 1. When a new swap-cache page is read into, it is added to the LRU
1045 * and treated as swapcache but it has no rmap yet.
1046 * Calling try_to_unmap() against a page->mapping==NULL page will
1047 * trigger a BUG. So handle it here.
1048 * 2. An orphaned page (see truncate_cleanup_page) might have
1049 * fs-private metadata. The page can be picked up due to memory
1050 * offlining. Everywhere else except page reclaim, the page is
1051 * invisible to the vm, so the page can not be migrated. So try to
1052 * free the metadata, so the page can be freed.
1054 if (!page->mapping) {
1055 VM_BUG_ON_PAGE(PageAnon(page), page);
1056 if (page_has_private(page)) {
1057 try_to_free_buffers(page);
1058 goto out_unlock_both;
1060 } else if (page_mapped(page)) {
1061 /* Establish migration ptes */
1062 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1064 try_to_migrate(page, 0);
1065 page_was_mapped = true;
1068 if (!page_mapped(page))
1069 rc = move_to_new_page(newpage, page, mode);
1071 if (page_was_mapped)
1072 remove_migration_ptes(page,
1073 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1076 unlock_page(newpage);
1078 /* Drop an anon_vma reference if we took one */
1080 put_anon_vma(anon_vma);
1084 * If migration is successful, decrease refcount of the newpage
1085 * which will not free the page because new page owner increased
1086 * refcounter. As well, if it is LRU page, add the page to LRU
1087 * list in here. Use the old state of the isolated source page to
1088 * determine if we migrated a LRU page. newpage was already unlocked
1089 * and possibly modified by its owner - don't rely on the page
1092 if (rc == MIGRATEPAGE_SUCCESS) {
1093 if (unlikely(!is_lru))
1096 putback_lru_page(newpage);
1104 * node_demotion[] example:
1106 * Consider a system with two sockets. Each socket has
1107 * three classes of memory attached: fast, medium and slow.
1108 * Each memory class is placed in its own NUMA node. The
1109 * CPUs are placed in the node with the "fast" memory. The
1110 * 6 NUMA nodes (0-5) might be split among the sockets like
1116 * When Node 0 fills up, its memory should be migrated to
1117 * Node 1. When Node 1 fills up, it should be migrated to
1118 * Node 2. The migration path start on the nodes with the
1119 * processors (since allocations default to this node) and
1120 * fast memory, progress through medium and end with the
1123 * 0 -> 1 -> 2 -> stop
1124 * 3 -> 4 -> 5 -> stop
1126 * This is represented in the node_demotion[] like this:
1128 * { 1, // Node 0 migrates to 1
1129 * 2, // Node 1 migrates to 2
1130 * -1, // Node 2 does not migrate
1131 * 4, // Node 3 migrates to 4
1132 * 5, // Node 4 migrates to 5
1133 * -1} // Node 5 does not migrate
1137 * Writes to this array occur without locking. Cycles are
1138 * not allowed: Node X demotes to Y which demotes to X...
1140 * If multiple reads are performed, a single rcu_read_lock()
1141 * must be held over all reads to ensure that no cycles are
1144 static int node_demotion[MAX_NUMNODES] __read_mostly =
1145 {[0 ... MAX_NUMNODES - 1] = NUMA_NO_NODE};
1148 * next_demotion_node() - Get the next node in the demotion path
1149 * @node: The starting node to lookup the next node
1151 * Return: node id for next memory node in the demotion path hierarchy
1152 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
1153 * @node online or guarantee that it *continues* to be the next demotion
1156 int next_demotion_node(int node)
1161 * node_demotion[] is updated without excluding this
1162 * function from running. RCU doesn't provide any
1163 * compiler barriers, so the READ_ONCE() is required
1164 * to avoid compiler reordering or read merging.
1166 * Make sure to use RCU over entire code blocks if
1167 * node_demotion[] reads need to be consistent.
1170 target = READ_ONCE(node_demotion[node]);
1177 * Obtain the lock on page, remove all ptes and migrate the page
1178 * to the newly allocated page in newpage.
1180 static int unmap_and_move(new_page_t get_new_page,
1181 free_page_t put_new_page,
1182 unsigned long private, struct page *page,
1183 int force, enum migrate_mode mode,
1184 enum migrate_reason reason,
1185 struct list_head *ret)
1187 int rc = MIGRATEPAGE_SUCCESS;
1188 struct page *newpage = NULL;
1190 if (!thp_migration_supported() && PageTransHuge(page))
1193 if (page_count(page) == 1) {
1194 /* page was freed from under us. So we are done. */
1195 ClearPageActive(page);
1196 ClearPageUnevictable(page);
1197 if (unlikely(__PageMovable(page))) {
1199 if (!PageMovable(page))
1200 __ClearPageIsolated(page);
1206 newpage = get_new_page(page, private);
1210 rc = __unmap_and_move(page, newpage, force, mode);
1211 if (rc == MIGRATEPAGE_SUCCESS)
1212 set_page_owner_migrate_reason(newpage, reason);
1215 if (rc != -EAGAIN) {
1217 * A page that has been migrated has all references
1218 * removed and will be freed. A page that has not been
1219 * migrated will have kept its references and be restored.
1221 list_del(&page->lru);
1225 * If migration is successful, releases reference grabbed during
1226 * isolation. Otherwise, restore the page to right list unless
1229 if (rc == MIGRATEPAGE_SUCCESS) {
1231 * Compaction can migrate also non-LRU pages which are
1232 * not accounted to NR_ISOLATED_*. They can be recognized
1235 if (likely(!__PageMovable(page)))
1236 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1237 page_is_file_lru(page), -thp_nr_pages(page));
1239 if (reason != MR_MEMORY_FAILURE)
1241 * We release the page in page_handle_poison.
1246 list_add_tail(&page->lru, ret);
1249 put_new_page(newpage, private);
1258 * Counterpart of unmap_and_move_page() for hugepage migration.
1260 * This function doesn't wait the completion of hugepage I/O
1261 * because there is no race between I/O and migration for hugepage.
1262 * Note that currently hugepage I/O occurs only in direct I/O
1263 * where no lock is held and PG_writeback is irrelevant,
1264 * and writeback status of all subpages are counted in the reference
1265 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1266 * under direct I/O, the reference of the head page is 512 and a bit more.)
1267 * This means that when we try to migrate hugepage whose subpages are
1268 * doing direct I/O, some references remain after try_to_unmap() and
1269 * hugepage migration fails without data corruption.
1271 * There is also no race when direct I/O is issued on the page under migration,
1272 * because then pte is replaced with migration swap entry and direct I/O code
1273 * will wait in the page fault for migration to complete.
1275 static int unmap_and_move_huge_page(new_page_t get_new_page,
1276 free_page_t put_new_page, unsigned long private,
1277 struct page *hpage, int force,
1278 enum migrate_mode mode, int reason,
1279 struct list_head *ret)
1282 int page_was_mapped = 0;
1283 struct page *new_hpage;
1284 struct anon_vma *anon_vma = NULL;
1285 struct address_space *mapping = NULL;
1288 * Migratability of hugepages depends on architectures and their size.
1289 * This check is necessary because some callers of hugepage migration
1290 * like soft offline and memory hotremove don't walk through page
1291 * tables or check whether the hugepage is pmd-based or not before
1292 * kicking migration.
1294 if (!hugepage_migration_supported(page_hstate(hpage))) {
1295 list_move_tail(&hpage->lru, ret);
1299 if (page_count(hpage) == 1) {
1300 /* page was freed from under us. So we are done. */
1301 putback_active_hugepage(hpage);
1302 return MIGRATEPAGE_SUCCESS;
1305 new_hpage = get_new_page(hpage, private);
1309 if (!trylock_page(hpage)) {
1314 case MIGRATE_SYNC_NO_COPY:
1323 * Check for pages which are in the process of being freed. Without
1324 * page_mapping() set, hugetlbfs specific move page routine will not
1325 * be called and we could leak usage counts for subpools.
1327 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1332 if (PageAnon(hpage))
1333 anon_vma = page_get_anon_vma(hpage);
1335 if (unlikely(!trylock_page(new_hpage)))
1338 if (page_mapped(hpage)) {
1339 bool mapping_locked = false;
1340 enum ttu_flags ttu = 0;
1342 if (!PageAnon(hpage)) {
1344 * In shared mappings, try_to_unmap could potentially
1345 * call huge_pmd_unshare. Because of this, take
1346 * semaphore in write mode here and set TTU_RMAP_LOCKED
1347 * to let lower levels know we have taken the lock.
1349 mapping = hugetlb_page_mapping_lock_write(hpage);
1350 if (unlikely(!mapping))
1351 goto unlock_put_anon;
1353 mapping_locked = true;
1354 ttu |= TTU_RMAP_LOCKED;
1357 try_to_migrate(hpage, ttu);
1358 page_was_mapped = 1;
1361 i_mmap_unlock_write(mapping);
1364 if (!page_mapped(hpage))
1365 rc = move_to_new_page(new_hpage, hpage, mode);
1367 if (page_was_mapped)
1368 remove_migration_ptes(hpage,
1369 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1372 unlock_page(new_hpage);
1376 put_anon_vma(anon_vma);
1378 if (rc == MIGRATEPAGE_SUCCESS) {
1379 move_hugetlb_state(hpage, new_hpage, reason);
1380 put_new_page = NULL;
1386 if (rc == MIGRATEPAGE_SUCCESS)
1387 putback_active_hugepage(hpage);
1388 else if (rc != -EAGAIN)
1389 list_move_tail(&hpage->lru, ret);
1392 * If migration was not successful and there's a freeing callback, use
1393 * it. Otherwise, put_page() will drop the reference grabbed during
1397 put_new_page(new_hpage, private);
1399 putback_active_hugepage(new_hpage);
1404 static inline int try_split_thp(struct page *page, struct page **page2,
1405 struct list_head *from)
1410 rc = split_huge_page_to_list(page, from);
1413 list_safe_reset_next(page, *page2, lru);
1419 * migrate_pages - migrate the pages specified in a list, to the free pages
1420 * supplied as the target for the page migration
1422 * @from: The list of pages to be migrated.
1423 * @get_new_page: The function used to allocate free pages to be used
1424 * as the target of the page migration.
1425 * @put_new_page: The function used to free target pages if migration
1426 * fails, or NULL if no special handling is necessary.
1427 * @private: Private data to be passed on to get_new_page()
1428 * @mode: The migration mode that specifies the constraints for
1429 * page migration, if any.
1430 * @reason: The reason for page migration.
1431 * @ret_succeeded: Set to the number of pages migrated successfully if
1432 * the caller passes a non-NULL pointer.
1434 * The function returns after 10 attempts or if no pages are movable any more
1435 * because the list has become empty or no retryable pages exist any more.
1436 * It is caller's responsibility to call putback_movable_pages() to return pages
1437 * to the LRU or free list only if ret != 0.
1439 * Returns the number of pages that were not migrated, or an error code.
1441 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1442 free_page_t put_new_page, unsigned long private,
1443 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1448 int nr_succeeded = 0;
1449 int nr_thp_succeeded = 0;
1450 int nr_thp_failed = 0;
1451 int nr_thp_split = 0;
1453 bool is_thp = false;
1456 int swapwrite = current->flags & PF_SWAPWRITE;
1457 int rc, nr_subpages;
1458 LIST_HEAD(ret_pages);
1459 bool nosplit = (reason == MR_NUMA_MISPLACED);
1461 trace_mm_migrate_pages_start(mode, reason);
1464 current->flags |= PF_SWAPWRITE;
1466 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1470 list_for_each_entry_safe(page, page2, from, lru) {
1473 * THP statistics is based on the source huge page.
1474 * Capture required information that might get lost
1477 is_thp = PageTransHuge(page) && !PageHuge(page);
1478 nr_subpages = thp_nr_pages(page);
1482 rc = unmap_and_move_huge_page(get_new_page,
1483 put_new_page, private, page,
1484 pass > 2, mode, reason,
1487 rc = unmap_and_move(get_new_page, put_new_page,
1488 private, page, pass > 2, mode,
1489 reason, &ret_pages);
1492 * Success: non hugetlb page will be freed, hugetlb
1493 * page will be put back
1494 * -EAGAIN: stay on the from list
1495 * -ENOMEM: stay on the from list
1496 * Other errno: put on ret_pages list then splice to
1501 * THP migration might be unsupported or the
1502 * allocation could've failed so we should
1503 * retry on the same page with the THP split
1506 * Head page is retried immediately and tail
1507 * pages are added to the tail of the list so
1508 * we encounter them after the rest of the list
1512 /* THP migration is unsupported */
1514 if (!try_split_thp(page, &page2, from)) {
1520 nr_failed += nr_subpages;
1524 /* Hugetlb migration is unsupported */
1529 * When memory is low, don't bother to try to migrate
1530 * other pages, just exit.
1531 * THP NUMA faulting doesn't split THP to retry.
1533 if (is_thp && !nosplit) {
1534 if (!try_split_thp(page, &page2, from)) {
1540 nr_failed += nr_subpages;
1552 case MIGRATEPAGE_SUCCESS:
1555 nr_succeeded += nr_subpages;
1562 * Permanent failure (-EBUSY, etc.):
1563 * unlike -EAGAIN case, the failed page is
1564 * removed from migration page list and not
1565 * retried in the next outer loop.
1569 nr_failed += nr_subpages;
1577 nr_failed += retry + thp_retry;
1578 nr_thp_failed += thp_retry;
1582 * Put the permanent failure page back to migration list, they
1583 * will be put back to the right list by the caller.
1585 list_splice(&ret_pages, from);
1587 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1588 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1589 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1590 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1591 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1592 trace_mm_migrate_pages(nr_succeeded, nr_failed, nr_thp_succeeded,
1593 nr_thp_failed, nr_thp_split, mode, reason);
1596 current->flags &= ~PF_SWAPWRITE;
1599 *ret_succeeded = nr_succeeded;
1604 struct page *alloc_migration_target(struct page *page, unsigned long private)
1606 struct migration_target_control *mtc;
1608 unsigned int order = 0;
1609 struct page *new_page = NULL;
1613 mtc = (struct migration_target_control *)private;
1614 gfp_mask = mtc->gfp_mask;
1616 if (nid == NUMA_NO_NODE)
1617 nid = page_to_nid(page);
1619 if (PageHuge(page)) {
1620 struct hstate *h = page_hstate(compound_head(page));
1622 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1623 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1626 if (PageTransHuge(page)) {
1628 * clear __GFP_RECLAIM to make the migration callback
1629 * consistent with regular THP allocations.
1631 gfp_mask &= ~__GFP_RECLAIM;
1632 gfp_mask |= GFP_TRANSHUGE;
1633 order = HPAGE_PMD_ORDER;
1635 zidx = zone_idx(page_zone(page));
1636 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1637 gfp_mask |= __GFP_HIGHMEM;
1639 new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
1641 if (new_page && PageTransHuge(new_page))
1642 prep_transhuge_page(new_page);
1649 static int store_status(int __user *status, int start, int value, int nr)
1652 if (put_user(value, status + start))
1660 static int do_move_pages_to_node(struct mm_struct *mm,
1661 struct list_head *pagelist, int node)
1664 struct migration_target_control mtc = {
1666 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1669 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1670 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1672 putback_movable_pages(pagelist);
1677 * Resolves the given address to a struct page, isolates it from the LRU and
1678 * puts it to the given pagelist.
1680 * errno - if the page cannot be found/isolated
1681 * 0 - when it doesn't have to be migrated because it is already on the
1683 * 1 - when it has been queued
1685 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1686 int node, struct list_head *pagelist, bool migrate_all)
1688 struct vm_area_struct *vma;
1690 unsigned int follflags;
1695 vma = find_vma(mm, addr);
1696 if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1699 /* FOLL_DUMP to ignore special (like zero) pages */
1700 follflags = FOLL_GET | FOLL_DUMP;
1701 page = follow_page(vma, addr, follflags);
1703 err = PTR_ERR(page);
1712 if (page_to_nid(page) == node)
1716 if (page_mapcount(page) > 1 && !migrate_all)
1719 if (PageHuge(page)) {
1720 if (PageHead(page)) {
1721 isolate_huge_page(page, pagelist);
1727 head = compound_head(page);
1728 err = isolate_lru_page(head);
1733 list_add_tail(&head->lru, pagelist);
1734 mod_node_page_state(page_pgdat(head),
1735 NR_ISOLATED_ANON + page_is_file_lru(head),
1736 thp_nr_pages(head));
1740 * Either remove the duplicate refcount from
1741 * isolate_lru_page() or drop the page ref if it was
1746 mmap_read_unlock(mm);
1750 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1751 struct list_head *pagelist, int __user *status,
1752 int start, int i, unsigned long nr_pages)
1756 if (list_empty(pagelist))
1759 err = do_move_pages_to_node(mm, pagelist, node);
1762 * Positive err means the number of failed
1763 * pages to migrate. Since we are going to
1764 * abort and return the number of non-migrated
1765 * pages, so need to include the rest of the
1766 * nr_pages that have not been attempted as
1770 err += nr_pages - i - 1;
1773 return store_status(status, start, node, i - start);
1777 * Migrate an array of page address onto an array of nodes and fill
1778 * the corresponding array of status.
1780 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1781 unsigned long nr_pages,
1782 const void __user * __user *pages,
1783 const int __user *nodes,
1784 int __user *status, int flags)
1786 int current_node = NUMA_NO_NODE;
1787 LIST_HEAD(pagelist);
1791 lru_cache_disable();
1793 for (i = start = 0; i < nr_pages; i++) {
1794 const void __user *p;
1799 if (get_user(p, pages + i))
1801 if (get_user(node, nodes + i))
1803 addr = (unsigned long)untagged_addr(p);
1806 if (node < 0 || node >= MAX_NUMNODES)
1808 if (!node_state(node, N_MEMORY))
1812 if (!node_isset(node, task_nodes))
1815 if (current_node == NUMA_NO_NODE) {
1816 current_node = node;
1818 } else if (node != current_node) {
1819 err = move_pages_and_store_status(mm, current_node,
1820 &pagelist, status, start, i, nr_pages);
1824 current_node = node;
1828 * Errors in the page lookup or isolation are not fatal and we simply
1829 * report them via status
1831 err = add_page_for_migration(mm, addr, current_node,
1832 &pagelist, flags & MPOL_MF_MOVE_ALL);
1835 /* The page is successfully queued for migration */
1840 * If the page is already on the target node (!err), store the
1841 * node, otherwise, store the err.
1843 err = store_status(status, i, err ? : current_node, 1);
1847 err = move_pages_and_store_status(mm, current_node, &pagelist,
1848 status, start, i, nr_pages);
1851 current_node = NUMA_NO_NODE;
1854 /* Make sure we do not overwrite the existing error */
1855 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1856 status, start, i, nr_pages);
1865 * Determine the nodes of an array of pages and store it in an array of status.
1867 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1868 const void __user **pages, int *status)
1874 for (i = 0; i < nr_pages; i++) {
1875 unsigned long addr = (unsigned long)(*pages);
1876 struct vm_area_struct *vma;
1880 vma = vma_lookup(mm, addr);
1884 /* FOLL_DUMP to ignore special (like zero) pages */
1885 page = follow_page(vma, addr, FOLL_DUMP);
1887 err = PTR_ERR(page);
1891 err = page ? page_to_nid(page) : -ENOENT;
1899 mmap_read_unlock(mm);
1902 static int get_compat_pages_array(const void __user *chunk_pages[],
1903 const void __user * __user *pages,
1904 unsigned long chunk_nr)
1906 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1910 for (i = 0; i < chunk_nr; i++) {
1911 if (get_user(p, pages32 + i))
1913 chunk_pages[i] = compat_ptr(p);
1920 * Determine the nodes of a user array of pages and store it in
1921 * a user array of status.
1923 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1924 const void __user * __user *pages,
1927 #define DO_PAGES_STAT_CHUNK_NR 16
1928 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1929 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1932 unsigned long chunk_nr;
1934 chunk_nr = nr_pages;
1935 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1936 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1938 if (in_compat_syscall()) {
1939 if (get_compat_pages_array(chunk_pages, pages,
1943 if (copy_from_user(chunk_pages, pages,
1944 chunk_nr * sizeof(*chunk_pages)))
1948 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1950 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1955 nr_pages -= chunk_nr;
1957 return nr_pages ? -EFAULT : 0;
1960 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1962 struct task_struct *task;
1963 struct mm_struct *mm;
1966 * There is no need to check if current process has the right to modify
1967 * the specified process when they are same.
1971 *mem_nodes = cpuset_mems_allowed(current);
1975 /* Find the mm_struct */
1977 task = find_task_by_vpid(pid);
1980 return ERR_PTR(-ESRCH);
1982 get_task_struct(task);
1985 * Check if this process has the right to modify the specified
1986 * process. Use the regular "ptrace_may_access()" checks.
1988 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1990 mm = ERR_PTR(-EPERM);
1995 mm = ERR_PTR(security_task_movememory(task));
1998 *mem_nodes = cpuset_mems_allowed(task);
1999 mm = get_task_mm(task);
2001 put_task_struct(task);
2003 mm = ERR_PTR(-EINVAL);
2008 * Move a list of pages in the address space of the currently executing
2011 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2012 const void __user * __user *pages,
2013 const int __user *nodes,
2014 int __user *status, int flags)
2016 struct mm_struct *mm;
2018 nodemask_t task_nodes;
2021 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2024 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2027 mm = find_mm_struct(pid, &task_nodes);
2032 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2033 nodes, status, flags);
2035 err = do_pages_stat(mm, nr_pages, pages, status);
2041 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2042 const void __user * __user *, pages,
2043 const int __user *, nodes,
2044 int __user *, status, int, flags)
2046 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2049 #ifdef CONFIG_NUMA_BALANCING
2051 * Returns true if this is a safe migration target node for misplaced NUMA
2052 * pages. Currently it only checks the watermarks which crude
2054 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2055 unsigned long nr_migrate_pages)
2059 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2060 struct zone *zone = pgdat->node_zones + z;
2062 if (!populated_zone(zone))
2065 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2066 if (!zone_watermark_ok(zone, 0,
2067 high_wmark_pages(zone) +
2076 static struct page *alloc_misplaced_dst_page(struct page *page,
2079 int nid = (int) data;
2080 struct page *newpage;
2082 newpage = __alloc_pages_node(nid,
2083 (GFP_HIGHUSER_MOVABLE |
2084 __GFP_THISNODE | __GFP_NOMEMALLOC |
2085 __GFP_NORETRY | __GFP_NOWARN) &
2091 static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2094 int nid = (int) data;
2095 struct page *newpage;
2097 newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2102 prep_transhuge_page(newpage);
2108 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2111 int nr_pages = thp_nr_pages(page);
2113 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2115 /* Do not migrate THP mapped by multiple processes */
2116 if (PageTransHuge(page) && total_mapcount(page) > 1)
2119 /* Avoid migrating to a node that is nearly full */
2120 if (!migrate_balanced_pgdat(pgdat, nr_pages))
2123 if (isolate_lru_page(page))
2126 page_lru = page_is_file_lru(page);
2127 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2131 * Isolating the page has taken another reference, so the
2132 * caller's reference can be safely dropped without the page
2133 * disappearing underneath us during migration.
2140 * Attempt to migrate a misplaced page to the specified destination
2141 * node. Caller is expected to have an elevated reference count on
2142 * the page that will be dropped by this function before returning.
2144 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2147 pg_data_t *pgdat = NODE_DATA(node);
2150 LIST_HEAD(migratepages);
2153 int nr_pages = thp_nr_pages(page);
2156 * PTE mapped THP or HugeTLB page can't reach here so the page could
2157 * be either base page or THP. And it must be head page if it is
2160 compound = PageTransHuge(page);
2163 new = alloc_misplaced_dst_page_thp;
2165 new = alloc_misplaced_dst_page;
2168 * Don't migrate file pages that are mapped in multiple processes
2169 * with execute permissions as they are probably shared libraries.
2171 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2172 (vma->vm_flags & VM_EXEC))
2176 * Also do not migrate dirty pages as not all filesystems can move
2177 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2179 if (page_is_file_lru(page) && PageDirty(page))
2182 isolated = numamigrate_isolate_page(pgdat, page);
2186 list_add(&page->lru, &migratepages);
2187 nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
2188 MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
2190 if (!list_empty(&migratepages)) {
2191 list_del(&page->lru);
2192 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2193 page_is_file_lru(page), -nr_pages);
2194 putback_lru_page(page);
2198 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
2199 BUG_ON(!list_empty(&migratepages));
2206 #endif /* CONFIG_NUMA_BALANCING */
2207 #endif /* CONFIG_NUMA */
2209 #ifdef CONFIG_DEVICE_PRIVATE
2210 static int migrate_vma_collect_skip(unsigned long start,
2212 struct mm_walk *walk)
2214 struct migrate_vma *migrate = walk->private;
2217 for (addr = start; addr < end; addr += PAGE_SIZE) {
2218 migrate->dst[migrate->npages] = 0;
2219 migrate->src[migrate->npages++] = 0;
2225 static int migrate_vma_collect_hole(unsigned long start,
2227 __always_unused int depth,
2228 struct mm_walk *walk)
2230 struct migrate_vma *migrate = walk->private;
2233 /* Only allow populating anonymous memory. */
2234 if (!vma_is_anonymous(walk->vma))
2235 return migrate_vma_collect_skip(start, end, walk);
2237 for (addr = start; addr < end; addr += PAGE_SIZE) {
2238 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2239 migrate->dst[migrate->npages] = 0;
2247 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2248 unsigned long start,
2250 struct mm_walk *walk)
2252 struct migrate_vma *migrate = walk->private;
2253 struct vm_area_struct *vma = walk->vma;
2254 struct mm_struct *mm = vma->vm_mm;
2255 unsigned long addr = start, unmapped = 0;
2260 if (pmd_none(*pmdp))
2261 return migrate_vma_collect_hole(start, end, -1, walk);
2263 if (pmd_trans_huge(*pmdp)) {
2266 ptl = pmd_lock(mm, pmdp);
2267 if (unlikely(!pmd_trans_huge(*pmdp))) {
2272 page = pmd_page(*pmdp);
2273 if (is_huge_zero_page(page)) {
2275 split_huge_pmd(vma, pmdp, addr);
2276 if (pmd_trans_unstable(pmdp))
2277 return migrate_vma_collect_skip(start, end,
2284 if (unlikely(!trylock_page(page)))
2285 return migrate_vma_collect_skip(start, end,
2287 ret = split_huge_page(page);
2291 return migrate_vma_collect_skip(start, end,
2293 if (pmd_none(*pmdp))
2294 return migrate_vma_collect_hole(start, end, -1,
2299 if (unlikely(pmd_bad(*pmdp)))
2300 return migrate_vma_collect_skip(start, end, walk);
2302 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2303 arch_enter_lazy_mmu_mode();
2305 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2306 unsigned long mpfn = 0, pfn;
2313 if (pte_none(pte)) {
2314 if (vma_is_anonymous(vma)) {
2315 mpfn = MIGRATE_PFN_MIGRATE;
2321 if (!pte_present(pte)) {
2323 * Only care about unaddressable device page special
2324 * page table entry. Other special swap entries are not
2325 * migratable, and we ignore regular swapped page.
2327 entry = pte_to_swp_entry(pte);
2328 if (!is_device_private_entry(entry))
2331 page = pfn_swap_entry_to_page(entry);
2332 if (!(migrate->flags &
2333 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2334 page->pgmap->owner != migrate->pgmap_owner)
2337 mpfn = migrate_pfn(page_to_pfn(page)) |
2338 MIGRATE_PFN_MIGRATE;
2339 if (is_writable_device_private_entry(entry))
2340 mpfn |= MIGRATE_PFN_WRITE;
2342 if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2345 if (is_zero_pfn(pfn)) {
2346 mpfn = MIGRATE_PFN_MIGRATE;
2350 page = vm_normal_page(migrate->vma, addr, pte);
2351 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2352 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2355 /* FIXME support THP */
2356 if (!page || !page->mapping || PageTransCompound(page)) {
2362 * By getting a reference on the page we pin it and that blocks
2363 * any kind of migration. Side effect is that it "freezes" the
2366 * We drop this reference after isolating the page from the lru
2367 * for non device page (device page are not on the lru and thus
2368 * can't be dropped from it).
2374 * Optimize for the common case where page is only mapped once
2375 * in one process. If we can lock the page, then we can safely
2376 * set up a special migration page table entry now.
2378 if (trylock_page(page)) {
2381 mpfn |= MIGRATE_PFN_LOCKED;
2382 ptep_get_and_clear(mm, addr, ptep);
2384 /* Setup special migration page table entry */
2385 if (mpfn & MIGRATE_PFN_WRITE)
2386 entry = make_writable_migration_entry(
2389 entry = make_readable_migration_entry(
2391 swp_pte = swp_entry_to_pte(entry);
2392 if (pte_present(pte)) {
2393 if (pte_soft_dirty(pte))
2394 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2395 if (pte_uffd_wp(pte))
2396 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2398 if (pte_swp_soft_dirty(pte))
2399 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2400 if (pte_swp_uffd_wp(pte))
2401 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2403 set_pte_at(mm, addr, ptep, swp_pte);
2406 * This is like regular unmap: we remove the rmap and
2407 * drop page refcount. Page won't be freed, as we took
2408 * a reference just above.
2410 page_remove_rmap(page, false);
2413 if (pte_present(pte))
2418 migrate->dst[migrate->npages] = 0;
2419 migrate->src[migrate->npages++] = mpfn;
2421 arch_leave_lazy_mmu_mode();
2422 pte_unmap_unlock(ptep - 1, ptl);
2424 /* Only flush the TLB if we actually modified any entries */
2426 flush_tlb_range(walk->vma, start, end);
2431 static const struct mm_walk_ops migrate_vma_walk_ops = {
2432 .pmd_entry = migrate_vma_collect_pmd,
2433 .pte_hole = migrate_vma_collect_hole,
2437 * migrate_vma_collect() - collect pages over a range of virtual addresses
2438 * @migrate: migrate struct containing all migration information
2440 * This will walk the CPU page table. For each virtual address backed by a
2441 * valid page, it updates the src array and takes a reference on the page, in
2442 * order to pin the page until we lock it and unmap it.
2444 static void migrate_vma_collect(struct migrate_vma *migrate)
2446 struct mmu_notifier_range range;
2449 * Note that the pgmap_owner is passed to the mmu notifier callback so
2450 * that the registered device driver can skip invalidating device
2451 * private page mappings that won't be migrated.
2453 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2454 migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
2455 migrate->pgmap_owner);
2456 mmu_notifier_invalidate_range_start(&range);
2458 walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2459 &migrate_vma_walk_ops, migrate);
2461 mmu_notifier_invalidate_range_end(&range);
2462 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2466 * migrate_vma_check_page() - check if page is pinned or not
2467 * @page: struct page to check
2469 * Pinned pages cannot be migrated. This is the same test as in
2470 * folio_migrate_mapping(), except that here we allow migration of a
2473 static bool migrate_vma_check_page(struct page *page)
2476 * One extra ref because caller holds an extra reference, either from
2477 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2483 * FIXME support THP (transparent huge page), it is bit more complex to
2484 * check them than regular pages, because they can be mapped with a pmd
2485 * or with a pte (split pte mapping).
2487 if (PageCompound(page))
2490 /* Page from ZONE_DEVICE have one extra reference */
2491 if (is_zone_device_page(page)) {
2493 * Private page can never be pin as they have no valid pte and
2494 * GUP will fail for those. Yet if there is a pending migration
2495 * a thread might try to wait on the pte migration entry and
2496 * will bump the page reference count. Sadly there is no way to
2497 * differentiate a regular pin from migration wait. Hence to
2498 * avoid 2 racing thread trying to migrate back to CPU to enter
2499 * infinite loop (one stopping migration because the other is
2500 * waiting on pte migration entry). We always return true here.
2502 * FIXME proper solution is to rework migration_entry_wait() so
2503 * it does not need to take a reference on page.
2505 return is_device_private_page(page);
2508 /* For file back page */
2509 if (page_mapping(page))
2510 extra += 1 + page_has_private(page);
2512 if ((page_count(page) - extra) > page_mapcount(page))
2519 * migrate_vma_prepare() - lock pages and isolate them from the lru
2520 * @migrate: migrate struct containing all migration information
2522 * This locks pages that have been collected by migrate_vma_collect(). Once each
2523 * page is locked it is isolated from the lru (for non-device pages). Finally,
2524 * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2525 * migrated by concurrent kernel threads.
2527 static void migrate_vma_prepare(struct migrate_vma *migrate)
2529 const unsigned long npages = migrate->npages;
2530 const unsigned long start = migrate->start;
2531 unsigned long addr, i, restore = 0;
2532 bool allow_drain = true;
2536 for (i = 0; (i < npages) && migrate->cpages; i++) {
2537 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2543 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2545 * Because we are migrating several pages there can be
2546 * a deadlock between 2 concurrent migration where each
2547 * are waiting on each other page lock.
2549 * Make migrate_vma() a best effort thing and backoff
2550 * for any page we can not lock right away.
2552 if (!trylock_page(page)) {
2553 migrate->src[i] = 0;
2559 migrate->src[i] |= MIGRATE_PFN_LOCKED;
2562 /* ZONE_DEVICE pages are not on LRU */
2563 if (!is_zone_device_page(page)) {
2564 if (!PageLRU(page) && allow_drain) {
2565 /* Drain CPU's pagevec */
2566 lru_add_drain_all();
2567 allow_drain = false;
2570 if (isolate_lru_page(page)) {
2572 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2576 migrate->src[i] = 0;
2584 /* Drop the reference we took in collect */
2588 if (!migrate_vma_check_page(page)) {
2590 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2594 if (!is_zone_device_page(page)) {
2596 putback_lru_page(page);
2599 migrate->src[i] = 0;
2603 if (!is_zone_device_page(page))
2604 putback_lru_page(page);
2611 for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2612 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2614 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2617 remove_migration_pte(page, migrate->vma, addr, page);
2619 migrate->src[i] = 0;
2627 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2628 * @migrate: migrate struct containing all migration information
2630 * Replace page mapping (CPU page table pte) with a special migration pte entry
2631 * and check again if it has been pinned. Pinned pages are restored because we
2632 * cannot migrate them.
2634 * This is the last step before we call the device driver callback to allocate
2635 * destination memory and copy contents of original page over to new page.
2637 static void migrate_vma_unmap(struct migrate_vma *migrate)
2639 const unsigned long npages = migrate->npages;
2640 const unsigned long start = migrate->start;
2641 unsigned long addr, i, restore = 0;
2643 for (i = 0; i < npages; i++) {
2644 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2646 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2649 if (page_mapped(page)) {
2650 try_to_migrate(page, 0);
2651 if (page_mapped(page))
2655 if (migrate_vma_check_page(page))
2659 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2664 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2665 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2667 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2670 remove_migration_ptes(page, page, false);
2672 migrate->src[i] = 0;
2676 if (is_zone_device_page(page))
2679 putback_lru_page(page);
2684 * migrate_vma_setup() - prepare to migrate a range of memory
2685 * @args: contains the vma, start, and pfns arrays for the migration
2687 * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2690 * Prepare to migrate a range of memory virtual address range by collecting all
2691 * the pages backing each virtual address in the range, saving them inside the
2692 * src array. Then lock those pages and unmap them. Once the pages are locked
2693 * and unmapped, check whether each page is pinned or not. Pages that aren't
2694 * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2695 * corresponding src array entry. Then restores any pages that are pinned, by
2696 * remapping and unlocking those pages.
2698 * The caller should then allocate destination memory and copy source memory to
2699 * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2700 * flag set). Once these are allocated and copied, the caller must update each
2701 * corresponding entry in the dst array with the pfn value of the destination
2702 * page and with the MIGRATE_PFN_VALID and MIGRATE_PFN_LOCKED flags set
2703 * (destination pages must have their struct pages locked, via lock_page()).
2705 * Note that the caller does not have to migrate all the pages that are marked
2706 * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2707 * device memory to system memory. If the caller cannot migrate a device page
2708 * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2709 * consequences for the userspace process, so it must be avoided if at all
2712 * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2713 * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2714 * allowing the caller to allocate device memory for those unbacked virtual
2715 * addresses. For this the caller simply has to allocate device memory and
2716 * properly set the destination entry like for regular migration. Note that
2717 * this can still fail, and thus inside the device driver you must check if the
2718 * migration was successful for those entries after calling migrate_vma_pages(),
2719 * just like for regular migration.
2721 * After that, the callers must call migrate_vma_pages() to go over each entry
2722 * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2723 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2724 * then migrate_vma_pages() to migrate struct page information from the source
2725 * struct page to the destination struct page. If it fails to migrate the
2726 * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2729 * At this point all successfully migrated pages have an entry in the src
2730 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2731 * array entry with MIGRATE_PFN_VALID flag set.
2733 * Once migrate_vma_pages() returns the caller may inspect which pages were
2734 * successfully migrated, and which were not. Successfully migrated pages will
2735 * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2737 * It is safe to update device page table after migrate_vma_pages() because
2738 * both destination and source page are still locked, and the mmap_lock is held
2739 * in read mode (hence no one can unmap the range being migrated).
2741 * Once the caller is done cleaning up things and updating its page table (if it
2742 * chose to do so, this is not an obligation) it finally calls
2743 * migrate_vma_finalize() to update the CPU page table to point to new pages
2744 * for successfully migrated pages or otherwise restore the CPU page table to
2745 * point to the original source pages.
2747 int migrate_vma_setup(struct migrate_vma *args)
2749 long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2751 args->start &= PAGE_MASK;
2752 args->end &= PAGE_MASK;
2753 if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2754 (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2758 if (args->start < args->vma->vm_start ||
2759 args->start >= args->vma->vm_end)
2761 if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2763 if (!args->src || !args->dst)
2766 memset(args->src, 0, sizeof(*args->src) * nr_pages);
2770 migrate_vma_collect(args);
2773 migrate_vma_prepare(args);
2775 migrate_vma_unmap(args);
2778 * At this point pages are locked and unmapped, and thus they have
2779 * stable content and can safely be copied to destination memory that
2780 * is allocated by the drivers.
2785 EXPORT_SYMBOL(migrate_vma_setup);
2788 * This code closely matches the code in:
2789 * __handle_mm_fault()
2790 * handle_pte_fault()
2791 * do_anonymous_page()
2792 * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2795 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2800 struct vm_area_struct *vma = migrate->vma;
2801 struct mm_struct *mm = vma->vm_mm;
2811 /* Only allow populating anonymous memory */
2812 if (!vma_is_anonymous(vma))
2815 pgdp = pgd_offset(mm, addr);
2816 p4dp = p4d_alloc(mm, pgdp, addr);
2819 pudp = pud_alloc(mm, p4dp, addr);
2822 pmdp = pmd_alloc(mm, pudp, addr);
2826 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2830 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2831 * pte_offset_map() on pmds where a huge pmd might be created
2832 * from a different thread.
2834 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2835 * parallel threads are excluded by other means.
2837 * Here we only have mmap_read_lock(mm).
2839 if (pte_alloc(mm, pmdp))
2842 /* See the comment in pte_alloc_one_map() */
2843 if (unlikely(pmd_trans_unstable(pmdp)))
2846 if (unlikely(anon_vma_prepare(vma)))
2848 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
2852 * The memory barrier inside __SetPageUptodate makes sure that
2853 * preceding stores to the page contents become visible before
2854 * the set_pte_at() write.
2856 __SetPageUptodate(page);
2858 if (is_zone_device_page(page)) {
2859 if (is_device_private_page(page)) {
2860 swp_entry_t swp_entry;
2862 if (vma->vm_flags & VM_WRITE)
2863 swp_entry = make_writable_device_private_entry(
2866 swp_entry = make_readable_device_private_entry(
2868 entry = swp_entry_to_pte(swp_entry);
2871 * For now we only support migrating to un-addressable
2874 pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2878 entry = mk_pte(page, vma->vm_page_prot);
2879 if (vma->vm_flags & VM_WRITE)
2880 entry = pte_mkwrite(pte_mkdirty(entry));
2883 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2885 if (check_stable_address_space(mm))
2888 if (pte_present(*ptep)) {
2889 unsigned long pfn = pte_pfn(*ptep);
2891 if (!is_zero_pfn(pfn))
2894 } else if (!pte_none(*ptep))
2898 * Check for userfaultfd but do not deliver the fault. Instead,
2901 if (userfaultfd_missing(vma))
2904 inc_mm_counter(mm, MM_ANONPAGES);
2905 page_add_new_anon_rmap(page, vma, addr, false);
2906 if (!is_zone_device_page(page))
2907 lru_cache_add_inactive_or_unevictable(page, vma);
2911 flush_cache_page(vma, addr, pte_pfn(*ptep));
2912 ptep_clear_flush_notify(vma, addr, ptep);
2913 set_pte_at_notify(mm, addr, ptep, entry);
2914 update_mmu_cache(vma, addr, ptep);
2916 /* No need to invalidate - it was non-present before */
2917 set_pte_at(mm, addr, ptep, entry);
2918 update_mmu_cache(vma, addr, ptep);
2921 pte_unmap_unlock(ptep, ptl);
2922 *src = MIGRATE_PFN_MIGRATE;
2926 pte_unmap_unlock(ptep, ptl);
2928 *src &= ~MIGRATE_PFN_MIGRATE;
2932 * migrate_vma_pages() - migrate meta-data from src page to dst page
2933 * @migrate: migrate struct containing all migration information
2935 * This migrates struct page meta-data from source struct page to destination
2936 * struct page. This effectively finishes the migration from source page to the
2939 void migrate_vma_pages(struct migrate_vma *migrate)
2941 const unsigned long npages = migrate->npages;
2942 const unsigned long start = migrate->start;
2943 struct mmu_notifier_range range;
2944 unsigned long addr, i;
2945 bool notified = false;
2947 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2948 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2949 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2950 struct address_space *mapping;
2954 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2959 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2964 mmu_notifier_range_init_owner(&range,
2965 MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2966 migrate->vma->vm_mm, addr, migrate->end,
2967 migrate->pgmap_owner);
2968 mmu_notifier_invalidate_range_start(&range);
2970 migrate_vma_insert_page(migrate, addr, newpage,
2975 mapping = page_mapping(page);
2977 if (is_zone_device_page(newpage)) {
2978 if (is_device_private_page(newpage)) {
2980 * For now only support private anonymous when
2981 * migrating to un-addressable device memory.
2984 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2989 * Other types of ZONE_DEVICE page are not
2992 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2997 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2998 if (r != MIGRATEPAGE_SUCCESS)
2999 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3003 * No need to double call mmu_notifier->invalidate_range() callback as
3004 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
3005 * did already call it.
3008 mmu_notifier_invalidate_range_only_end(&range);
3010 EXPORT_SYMBOL(migrate_vma_pages);
3013 * migrate_vma_finalize() - restore CPU page table entry
3014 * @migrate: migrate struct containing all migration information
3016 * This replaces the special migration pte entry with either a mapping to the
3017 * new page if migration was successful for that page, or to the original page
3020 * This also unlocks the pages and puts them back on the lru, or drops the extra
3021 * refcount, for device pages.
3023 void migrate_vma_finalize(struct migrate_vma *migrate)
3025 const unsigned long npages = migrate->npages;
3028 for (i = 0; i < npages; i++) {
3029 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
3030 struct page *page = migrate_pfn_to_page(migrate->src[i]);
3034 unlock_page(newpage);
3040 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
3042 unlock_page(newpage);
3048 remove_migration_ptes(page, newpage, false);
3051 if (is_zone_device_page(page))
3054 putback_lru_page(page);
3056 if (newpage != page) {
3057 unlock_page(newpage);
3058 if (is_zone_device_page(newpage))
3061 putback_lru_page(newpage);
3065 EXPORT_SYMBOL(migrate_vma_finalize);
3066 #endif /* CONFIG_DEVICE_PRIVATE */
3068 #if defined(CONFIG_HOTPLUG_CPU)
3069 /* Disable reclaim-based migration. */
3070 static void __disable_all_migrate_targets(void)
3074 for_each_online_node(node)
3075 node_demotion[node] = NUMA_NO_NODE;
3078 static void disable_all_migrate_targets(void)
3080 __disable_all_migrate_targets();
3083 * Ensure that the "disable" is visible across the system.
3084 * Readers will see either a combination of before+disable
3085 * state or disable+after. They will never see before and
3086 * after state together.
3088 * The before+after state together might have cycles and
3089 * could cause readers to do things like loop until this
3090 * function finishes. This ensures they can only see a
3091 * single "bad" read and would, for instance, only loop
3098 * Find an automatic demotion target for 'node'.
3099 * Failing here is OK. It might just indicate
3100 * being at the end of a chain.
3102 static int establish_migrate_target(int node, nodemask_t *used)
3104 int migration_target;
3107 * Can not set a migration target on a
3108 * node with it already set.
3110 * No need for READ_ONCE() here since this
3111 * in the write path for node_demotion[].
3112 * This should be the only thread writing.
3114 if (node_demotion[node] != NUMA_NO_NODE)
3115 return NUMA_NO_NODE;
3117 migration_target = find_next_best_node(node, used);
3118 if (migration_target == NUMA_NO_NODE)
3119 return NUMA_NO_NODE;
3121 node_demotion[node] = migration_target;
3123 return migration_target;
3127 * When memory fills up on a node, memory contents can be
3128 * automatically migrated to another node instead of
3129 * discarded at reclaim.
3131 * Establish a "migration path" which will start at nodes
3132 * with CPUs and will follow the priorities used to build the
3133 * page allocator zonelists.
3135 * The difference here is that cycles must be avoided. If
3136 * node0 migrates to node1, then neither node1, nor anything
3137 * node1 migrates to can migrate to node0.
3139 * This function can run simultaneously with readers of
3140 * node_demotion[]. However, it can not run simultaneously
3141 * with itself. Exclusion is provided by memory hotplug events
3142 * being single-threaded.
3144 static void __set_migration_target_nodes(void)
3146 nodemask_t next_pass = NODE_MASK_NONE;
3147 nodemask_t this_pass = NODE_MASK_NONE;
3148 nodemask_t used_targets = NODE_MASK_NONE;
3152 * Avoid any oddities like cycles that could occur
3153 * from changes in the topology. This will leave
3154 * a momentary gap when migration is disabled.
3156 disable_all_migrate_targets();
3159 * Allocations go close to CPUs, first. Assume that
3160 * the migration path starts at the nodes with CPUs.
3162 next_pass = node_states[N_CPU];
3164 this_pass = next_pass;
3165 next_pass = NODE_MASK_NONE;
3167 * To avoid cycles in the migration "graph", ensure
3168 * that migration sources are not future targets by
3169 * setting them in 'used_targets'. Do this only
3170 * once per pass so that multiple source nodes can
3171 * share a target node.
3173 * 'used_targets' will become unavailable in future
3174 * passes. This limits some opportunities for
3175 * multiple source nodes to share a destination.
3177 nodes_or(used_targets, used_targets, this_pass);
3178 for_each_node_mask(node, this_pass) {
3179 int target_node = establish_migrate_target(node, &used_targets);
3181 if (target_node == NUMA_NO_NODE)
3185 * Visit targets from this pass in the next pass.
3186 * Eventually, every node will have been part of
3187 * a pass, and will become set in 'used_targets'.
3189 node_set(target_node, next_pass);
3192 * 'next_pass' contains nodes which became migration
3193 * targets in this pass. Make additional passes until
3194 * no more migrations targets are available.
3196 if (!nodes_empty(next_pass))
3201 * For callers that do not hold get_online_mems() already.
3203 static void set_migration_target_nodes(void)
3206 __set_migration_target_nodes();
3211 * This leaves migrate-on-reclaim transiently disabled between
3212 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
3213 * whether reclaim-based migration is enabled or not, which
3214 * ensures that the user can turn reclaim-based migration at
3215 * any time without needing to recalculate migration targets.
3217 * These callbacks already hold get_online_mems(). That is why
3218 * __set_migration_target_nodes() can be used as opposed to
3219 * set_migration_target_nodes().
3221 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
3222 unsigned long action, void *_arg)
3224 struct memory_notify *arg = _arg;
3227 * Only update the node migration order when a node is
3228 * changing status, like online->offline. This avoids
3229 * the overhead of synchronize_rcu() in most cases.
3231 if (arg->status_change_nid < 0)
3232 return notifier_from_errno(0);
3235 case MEM_GOING_OFFLINE:
3237 * Make sure there are not transient states where
3238 * an offline node is a migration target. This
3239 * will leave migration disabled until the offline
3240 * completes and the MEM_OFFLINE case below runs.
3242 disable_all_migrate_targets();
3247 * Recalculate the target nodes once the node
3248 * reaches its final state (online or offline).
3250 __set_migration_target_nodes();
3252 case MEM_CANCEL_OFFLINE:
3254 * MEM_GOING_OFFLINE disabled all the migration
3255 * targets. Reenable them.
3257 __set_migration_target_nodes();
3259 case MEM_GOING_ONLINE:
3260 case MEM_CANCEL_ONLINE:
3264 return notifier_from_errno(0);
3268 * React to hotplug events that might affect the migration targets
3269 * like events that online or offline NUMA nodes.
3271 * The ordering is also currently dependent on which nodes have
3272 * CPUs. That means we need CPU on/offline notification too.
3274 static int migration_online_cpu(unsigned int cpu)
3276 set_migration_target_nodes();
3280 static int migration_offline_cpu(unsigned int cpu)
3282 set_migration_target_nodes();
3286 static int __init migrate_on_reclaim_init(void)
3290 ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3291 NULL, migration_offline_cpu);
3293 * In the unlikely case that this fails, the automatic
3294 * migration targets may become suboptimal for nodes
3295 * where N_CPU changes. With such a small impact in a
3296 * rare case, do not bother trying to do anything special.
3299 ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3300 migration_online_cpu, NULL);
3303 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3306 late_initcall(migrate_on_reclaim_init);
3307 #endif /* CONFIG_HOTPLUG_CPU */
3309 bool numa_demotion_enabled = false;
3312 static ssize_t numa_demotion_enabled_show(struct kobject *kobj,
3313 struct kobj_attribute *attr, char *buf)
3315 return sysfs_emit(buf, "%s\n",
3316 numa_demotion_enabled ? "true" : "false");
3319 static ssize_t numa_demotion_enabled_store(struct kobject *kobj,
3320 struct kobj_attribute *attr,
3321 const char *buf, size_t count)
3323 if (!strncmp(buf, "true", 4) || !strncmp(buf, "1", 1))
3324 numa_demotion_enabled = true;
3325 else if (!strncmp(buf, "false", 5) || !strncmp(buf, "0", 1))
3326 numa_demotion_enabled = false;
3333 static struct kobj_attribute numa_demotion_enabled_attr =
3334 __ATTR(demotion_enabled, 0644, numa_demotion_enabled_show,
3335 numa_demotion_enabled_store);
3337 static struct attribute *numa_attrs[] = {
3338 &numa_demotion_enabled_attr.attr,
3342 static const struct attribute_group numa_attr_group = {
3343 .attrs = numa_attrs,
3346 static int __init numa_init_sysfs(void)
3349 struct kobject *numa_kobj;
3351 numa_kobj = kobject_create_and_add("numa", mm_kobj);
3353 pr_err("failed to create numa kobject\n");
3356 err = sysfs_create_group(numa_kobj, &numa_attr_group);
3358 pr_err("failed to register numa group\n");
3364 kobject_put(numa_kobj);
3367 subsys_initcall(numa_init_sysfs);