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);
240 hugepage_add_anon_rmap(new, vma, pvmw.address);
242 page_dup_rmap(new, true);
243 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
248 page_add_anon_rmap(new, vma, pvmw.address, false);
250 page_add_file_rmap(new, false);
251 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
253 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
256 if (PageTransHuge(page) && PageMlocked(page))
257 clear_page_mlock(page);
259 /* No need to invalidate - it was non-present before */
260 update_mmu_cache(vma, pvmw.address, pvmw.pte);
267 * Get rid of all migration entries and replace them by
268 * references to the indicated page.
270 void remove_migration_ptes(struct page *old, struct page *new, bool locked)
272 struct rmap_walk_control rwc = {
273 .rmap_one = remove_migration_pte,
278 rmap_walk_locked(new, &rwc);
280 rmap_walk(new, &rwc);
284 * Something used the pte of a page under migration. We need to
285 * get to the page and wait until migration is finished.
286 * When we return from this function the fault will be retried.
288 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
297 if (!is_swap_pte(pte))
300 entry = pte_to_swp_entry(pte);
301 if (!is_migration_entry(entry))
304 page = pfn_swap_entry_to_page(entry);
305 page = compound_head(page);
308 * Once page cache replacement of page migration started, page_count
309 * is zero; but we must not call put_and_wait_on_page_locked() without
310 * a ref. Use get_page_unless_zero(), and just fault again if it fails.
312 if (!get_page_unless_zero(page))
314 pte_unmap_unlock(ptep, ptl);
315 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
318 pte_unmap_unlock(ptep, ptl);
321 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
322 unsigned long address)
324 spinlock_t *ptl = pte_lockptr(mm, pmd);
325 pte_t *ptep = pte_offset_map(pmd, address);
326 __migration_entry_wait(mm, ptep, ptl);
329 void migration_entry_wait_huge(struct vm_area_struct *vma,
330 struct mm_struct *mm, pte_t *pte)
332 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
333 __migration_entry_wait(mm, pte, ptl);
336 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
337 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
342 ptl = pmd_lock(mm, pmd);
343 if (!is_pmd_migration_entry(*pmd))
345 page = pfn_swap_entry_to_page(pmd_to_swp_entry(*pmd));
346 if (!get_page_unless_zero(page))
349 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
356 static int expected_page_refs(struct address_space *mapping, struct page *page)
358 int expected_count = 1;
361 * Device private pages have an extra refcount as they are
364 expected_count += is_device_private_page(page);
366 expected_count += compound_nr(page) + page_has_private(page);
368 return expected_count;
372 * Replace the page in the mapping.
374 * The number of remaining references must be:
375 * 1 for anonymous pages without a mapping
376 * 2 for pages with a mapping
377 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
379 int folio_migrate_mapping(struct address_space *mapping,
380 struct folio *newfolio, struct folio *folio, int extra_count)
382 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
383 struct zone *oldzone, *newzone;
385 int expected_count = expected_page_refs(mapping, &folio->page) + extra_count;
386 long nr = folio_nr_pages(folio);
389 /* Anonymous page without mapping */
390 if (folio_ref_count(folio) != expected_count)
393 /* No turning back from here */
394 newfolio->index = folio->index;
395 newfolio->mapping = folio->mapping;
396 if (folio_test_swapbacked(folio))
397 __folio_set_swapbacked(newfolio);
399 return MIGRATEPAGE_SUCCESS;
402 oldzone = folio_zone(folio);
403 newzone = folio_zone(newfolio);
406 if (!folio_ref_freeze(folio, expected_count)) {
407 xas_unlock_irq(&xas);
412 * Now we know that no one else is looking at the folio:
413 * no turning back from here.
415 newfolio->index = folio->index;
416 newfolio->mapping = folio->mapping;
417 folio_ref_add(newfolio, nr); /* add cache reference */
418 if (folio_test_swapbacked(folio)) {
419 __folio_set_swapbacked(newfolio);
420 if (folio_test_swapcache(folio)) {
421 folio_set_swapcache(newfolio);
422 newfolio->private = folio_get_private(folio);
425 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
428 /* Move dirty while page refs frozen and newpage not yet exposed */
429 dirty = folio_test_dirty(folio);
431 folio_clear_dirty(folio);
432 folio_set_dirty(newfolio);
435 xas_store(&xas, newfolio);
439 for (i = 1; i < nr; i++) {
441 xas_store(&xas, newfolio);
446 * Drop cache reference from old page by unfreezing
447 * to one less reference.
448 * We know this isn't the last reference.
450 folio_ref_unfreeze(folio, expected_count - nr);
453 /* Leave irq disabled to prevent preemption while updating stats */
456 * If moved to a different zone then also account
457 * the page for that zone. Other VM counters will be
458 * taken care of when we establish references to the
459 * new page and drop references to the old page.
461 * Note that anonymous pages are accounted for
462 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
463 * are mapped to swap space.
465 if (newzone != oldzone) {
466 struct lruvec *old_lruvec, *new_lruvec;
467 struct mem_cgroup *memcg;
469 memcg = folio_memcg(folio);
470 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
471 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
473 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
474 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
475 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
476 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
477 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
480 if (folio_test_swapcache(folio)) {
481 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
482 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
485 if (dirty && mapping_can_writeback(mapping)) {
486 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
487 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
488 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
489 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
494 return MIGRATEPAGE_SUCCESS;
496 EXPORT_SYMBOL(folio_migrate_mapping);
499 * The expected number of remaining references is the same as that
500 * of folio_migrate_mapping().
502 int migrate_huge_page_move_mapping(struct address_space *mapping,
503 struct page *newpage, struct page *page)
505 XA_STATE(xas, &mapping->i_pages, page_index(page));
509 expected_count = 2 + page_has_private(page);
510 if (page_count(page) != expected_count || xas_load(&xas) != page) {
511 xas_unlock_irq(&xas);
515 if (!page_ref_freeze(page, expected_count)) {
516 xas_unlock_irq(&xas);
520 newpage->index = page->index;
521 newpage->mapping = page->mapping;
525 xas_store(&xas, newpage);
527 page_ref_unfreeze(page, expected_count - 1);
529 xas_unlock_irq(&xas);
531 return MIGRATEPAGE_SUCCESS;
535 * Copy the flags and some other ancillary information
537 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
541 if (folio_test_error(folio))
542 folio_set_error(newfolio);
543 if (folio_test_referenced(folio))
544 folio_set_referenced(newfolio);
545 if (folio_test_uptodate(folio))
546 folio_mark_uptodate(newfolio);
547 if (folio_test_clear_active(folio)) {
548 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
549 folio_set_active(newfolio);
550 } else if (folio_test_clear_unevictable(folio))
551 folio_set_unevictable(newfolio);
552 if (folio_test_workingset(folio))
553 folio_set_workingset(newfolio);
554 if (folio_test_checked(folio))
555 folio_set_checked(newfolio);
556 if (folio_test_mappedtodisk(folio))
557 folio_set_mappedtodisk(newfolio);
559 /* Move dirty on pages not done by folio_migrate_mapping() */
560 if (folio_test_dirty(folio))
561 folio_set_dirty(newfolio);
563 if (folio_test_young(folio))
564 folio_set_young(newfolio);
565 if (folio_test_idle(folio))
566 folio_set_idle(newfolio);
569 * Copy NUMA information to the new page, to prevent over-eager
570 * future migrations of this same page.
572 cpupid = page_cpupid_xchg_last(&folio->page, -1);
573 page_cpupid_xchg_last(&newfolio->page, cpupid);
575 folio_migrate_ksm(newfolio, folio);
577 * Please do not reorder this without considering how mm/ksm.c's
578 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
580 if (folio_test_swapcache(folio))
581 folio_clear_swapcache(folio);
582 folio_clear_private(folio);
584 /* page->private contains hugetlb specific flags */
585 if (!folio_test_hugetlb(folio))
586 folio->private = NULL;
589 * If any waiters have accumulated on the new page then
592 if (folio_test_writeback(newfolio))
593 folio_end_writeback(newfolio);
596 * PG_readahead shares the same bit with PG_reclaim. The above
597 * end_page_writeback() may clear PG_readahead mistakenly, so set the
600 if (folio_test_readahead(folio))
601 folio_set_readahead(newfolio);
603 folio_copy_owner(newfolio, folio);
605 if (!folio_test_hugetlb(folio))
606 mem_cgroup_migrate(folio, newfolio);
608 EXPORT_SYMBOL(folio_migrate_flags);
610 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
612 folio_copy(newfolio, folio);
613 folio_migrate_flags(newfolio, folio);
615 EXPORT_SYMBOL(folio_migrate_copy);
617 /************************************************************
618 * Migration functions
619 ***********************************************************/
622 * Common logic to directly migrate a single LRU page suitable for
623 * pages that do not use PagePrivate/PagePrivate2.
625 * Pages are locked upon entry and exit.
627 int migrate_page(struct address_space *mapping,
628 struct page *newpage, struct page *page,
629 enum migrate_mode mode)
631 struct folio *newfolio = page_folio(newpage);
632 struct folio *folio = page_folio(page);
635 BUG_ON(folio_test_writeback(folio)); /* Writeback must be complete */
637 rc = folio_migrate_mapping(mapping, newfolio, folio, 0);
639 if (rc != MIGRATEPAGE_SUCCESS)
642 if (mode != MIGRATE_SYNC_NO_COPY)
643 folio_migrate_copy(newfolio, folio);
645 folio_migrate_flags(newfolio, folio);
646 return MIGRATEPAGE_SUCCESS;
648 EXPORT_SYMBOL(migrate_page);
651 /* Returns true if all buffers are successfully locked */
652 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
653 enum migrate_mode mode)
655 struct buffer_head *bh = head;
657 /* Simple case, sync compaction */
658 if (mode != MIGRATE_ASYNC) {
661 bh = bh->b_this_page;
663 } while (bh != head);
668 /* async case, we cannot block on lock_buffer so use trylock_buffer */
670 if (!trylock_buffer(bh)) {
672 * We failed to lock the buffer and cannot stall in
673 * async migration. Release the taken locks
675 struct buffer_head *failed_bh = bh;
677 while (bh != failed_bh) {
679 bh = bh->b_this_page;
684 bh = bh->b_this_page;
685 } while (bh != head);
689 static int __buffer_migrate_page(struct address_space *mapping,
690 struct page *newpage, struct page *page, enum migrate_mode mode,
693 struct buffer_head *bh, *head;
697 if (!page_has_buffers(page))
698 return migrate_page(mapping, newpage, page, mode);
700 /* Check whether page does not have extra refs before we do more work */
701 expected_count = expected_page_refs(mapping, page);
702 if (page_count(page) != expected_count)
705 head = page_buffers(page);
706 if (!buffer_migrate_lock_buffers(head, mode))
711 bool invalidated = false;
715 spin_lock(&mapping->private_lock);
718 if (atomic_read(&bh->b_count)) {
722 bh = bh->b_this_page;
723 } while (bh != head);
729 spin_unlock(&mapping->private_lock);
730 invalidate_bh_lrus();
732 goto recheck_buffers;
736 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
737 if (rc != MIGRATEPAGE_SUCCESS)
740 attach_page_private(newpage, detach_page_private(page));
744 set_bh_page(bh, newpage, bh_offset(bh));
745 bh = bh->b_this_page;
747 } while (bh != head);
749 if (mode != MIGRATE_SYNC_NO_COPY)
750 migrate_page_copy(newpage, page);
752 migrate_page_states(newpage, page);
754 rc = MIGRATEPAGE_SUCCESS;
757 spin_unlock(&mapping->private_lock);
761 bh = bh->b_this_page;
763 } while (bh != head);
769 * Migration function for pages with buffers. This function can only be used
770 * if the underlying filesystem guarantees that no other references to "page"
771 * exist. For example attached buffer heads are accessed only under page lock.
773 int buffer_migrate_page(struct address_space *mapping,
774 struct page *newpage, struct page *page, enum migrate_mode mode)
776 return __buffer_migrate_page(mapping, newpage, page, mode, false);
778 EXPORT_SYMBOL(buffer_migrate_page);
781 * Same as above except that this variant is more careful and checks that there
782 * are also no buffer head references. This function is the right one for
783 * mappings where buffer heads are directly looked up and referenced (such as
784 * block device mappings).
786 int buffer_migrate_page_norefs(struct address_space *mapping,
787 struct page *newpage, struct page *page, enum migrate_mode mode)
789 return __buffer_migrate_page(mapping, newpage, page, mode, true);
794 * Writeback a page to clean the dirty state
796 static int writeout(struct address_space *mapping, struct page *page)
798 struct writeback_control wbc = {
799 .sync_mode = WB_SYNC_NONE,
802 .range_end = LLONG_MAX,
807 if (!mapping->a_ops->writepage)
808 /* No write method for the address space */
811 if (!clear_page_dirty_for_io(page))
812 /* Someone else already triggered a write */
816 * A dirty page may imply that the underlying filesystem has
817 * the page on some queue. So the page must be clean for
818 * migration. Writeout may mean we loose the lock and the
819 * page state is no longer what we checked for earlier.
820 * At this point we know that the migration attempt cannot
823 remove_migration_ptes(page, page, false);
825 rc = mapping->a_ops->writepage(page, &wbc);
827 if (rc != AOP_WRITEPAGE_ACTIVATE)
828 /* unlocked. Relock */
831 return (rc < 0) ? -EIO : -EAGAIN;
835 * Default handling if a filesystem does not provide a migration function.
837 static int fallback_migrate_page(struct address_space *mapping,
838 struct page *newpage, struct page *page, enum migrate_mode mode)
840 if (PageDirty(page)) {
841 /* Only writeback pages in full synchronous migration */
844 case MIGRATE_SYNC_NO_COPY:
849 return writeout(mapping, page);
853 * Buffers may be managed in a filesystem specific way.
854 * We must have no buffers or drop them.
856 if (page_has_private(page) &&
857 !try_to_release_page(page, GFP_KERNEL))
858 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
860 return migrate_page(mapping, newpage, page, mode);
864 * Move a page to a newly allocated page
865 * The page is locked and all ptes have been successfully removed.
867 * The new page will have replaced the old page if this function
872 * MIGRATEPAGE_SUCCESS - success
874 static int move_to_new_page(struct page *newpage, struct page *page,
875 enum migrate_mode mode)
877 struct address_space *mapping;
879 bool is_lru = !__PageMovable(page);
881 VM_BUG_ON_PAGE(!PageLocked(page), page);
882 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
884 mapping = page_mapping(page);
886 if (likely(is_lru)) {
888 rc = migrate_page(mapping, newpage, page, mode);
889 else if (mapping->a_ops->migratepage)
891 * Most pages have a mapping and most filesystems
892 * provide a migratepage callback. Anonymous pages
893 * are part of swap space which also has its own
894 * migratepage callback. This is the most common path
895 * for page migration.
897 rc = mapping->a_ops->migratepage(mapping, newpage,
900 rc = fallback_migrate_page(mapping, newpage,
904 * In case of non-lru page, it could be released after
905 * isolation step. In that case, we shouldn't try migration.
907 VM_BUG_ON_PAGE(!PageIsolated(page), page);
908 if (!PageMovable(page)) {
909 rc = MIGRATEPAGE_SUCCESS;
910 __ClearPageIsolated(page);
914 rc = mapping->a_ops->migratepage(mapping, newpage,
916 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
917 !PageIsolated(page));
921 * When successful, old pagecache page->mapping must be cleared before
922 * page is freed; but stats require that PageAnon be left as PageAnon.
924 if (rc == MIGRATEPAGE_SUCCESS) {
925 if (__PageMovable(page)) {
926 VM_BUG_ON_PAGE(!PageIsolated(page), page);
929 * We clear PG_movable under page_lock so any compactor
930 * cannot try to migrate this page.
932 __ClearPageIsolated(page);
936 * Anonymous and movable page->mapping will be cleared by
937 * free_pages_prepare so don't reset it here for keeping
938 * the type to work PageAnon, for example.
940 if (!PageMappingFlags(page))
941 page->mapping = NULL;
943 if (likely(!is_zone_device_page(newpage)))
944 flush_dcache_page(newpage);
951 static int __unmap_and_move(struct page *page, struct page *newpage,
952 int force, enum migrate_mode mode)
955 bool page_was_mapped = false;
956 struct anon_vma *anon_vma = NULL;
957 bool is_lru = !__PageMovable(page);
959 if (!trylock_page(page)) {
960 if (!force || mode == MIGRATE_ASYNC)
964 * It's not safe for direct compaction to call lock_page.
965 * For example, during page readahead pages are added locked
966 * to the LRU. Later, when the IO completes the pages are
967 * marked uptodate and unlocked. However, the queueing
968 * could be merging multiple pages for one bio (e.g.
969 * mpage_readahead). If an allocation happens for the
970 * second or third page, the process can end up locking
971 * the same page twice and deadlocking. Rather than
972 * trying to be clever about what pages can be locked,
973 * avoid the use of lock_page for direct compaction
976 if (current->flags & PF_MEMALLOC)
982 if (PageWriteback(page)) {
984 * Only in the case of a full synchronous migration is it
985 * necessary to wait for PageWriteback. In the async case,
986 * the retry loop is too short and in the sync-light case,
987 * the overhead of stalling is too much
991 case MIGRATE_SYNC_NO_COPY:
999 wait_on_page_writeback(page);
1003 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1004 * we cannot notice that anon_vma is freed while we migrates a page.
1005 * This get_anon_vma() delays freeing anon_vma pointer until the end
1006 * of migration. File cache pages are no problem because of page_lock()
1007 * File Caches may use write_page() or lock_page() in migration, then,
1008 * just care Anon page here.
1010 * Only page_get_anon_vma() understands the subtleties of
1011 * getting a hold on an anon_vma from outside one of its mms.
1012 * But if we cannot get anon_vma, then we won't need it anyway,
1013 * because that implies that the anon page is no longer mapped
1014 * (and cannot be remapped so long as we hold the page lock).
1016 if (PageAnon(page) && !PageKsm(page))
1017 anon_vma = page_get_anon_vma(page);
1020 * Block others from accessing the new page when we get around to
1021 * establishing additional references. We are usually the only one
1022 * holding a reference to newpage at this point. We used to have a BUG
1023 * here if trylock_page(newpage) fails, but would like to allow for
1024 * cases where there might be a race with the previous use of newpage.
1025 * This is much like races on refcount of oldpage: just don't BUG().
1027 if (unlikely(!trylock_page(newpage)))
1030 if (unlikely(!is_lru)) {
1031 rc = move_to_new_page(newpage, page, mode);
1032 goto out_unlock_both;
1036 * Corner case handling:
1037 * 1. When a new swap-cache page is read into, it is added to the LRU
1038 * and treated as swapcache but it has no rmap yet.
1039 * Calling try_to_unmap() against a page->mapping==NULL page will
1040 * trigger a BUG. So handle it here.
1041 * 2. An orphaned page (see truncate_cleanup_page) might have
1042 * fs-private metadata. The page can be picked up due to memory
1043 * offlining. Everywhere else except page reclaim, the page is
1044 * invisible to the vm, so the page can not be migrated. So try to
1045 * free the metadata, so the page can be freed.
1047 if (!page->mapping) {
1048 VM_BUG_ON_PAGE(PageAnon(page), page);
1049 if (page_has_private(page)) {
1050 try_to_free_buffers(page);
1051 goto out_unlock_both;
1053 } else if (page_mapped(page)) {
1054 /* Establish migration ptes */
1055 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1057 try_to_migrate(page, 0);
1058 page_was_mapped = true;
1061 if (!page_mapped(page))
1062 rc = move_to_new_page(newpage, page, mode);
1064 if (page_was_mapped)
1065 remove_migration_ptes(page,
1066 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1069 unlock_page(newpage);
1071 /* Drop an anon_vma reference if we took one */
1073 put_anon_vma(anon_vma);
1077 * If migration is successful, decrease refcount of the newpage
1078 * which will not free the page because new page owner increased
1079 * refcounter. As well, if it is LRU page, add the page to LRU
1080 * list in here. Use the old state of the isolated source page to
1081 * determine if we migrated a LRU page. newpage was already unlocked
1082 * and possibly modified by its owner - don't rely on the page
1085 if (rc == MIGRATEPAGE_SUCCESS) {
1086 if (unlikely(!is_lru))
1089 putback_lru_page(newpage);
1097 * node_demotion[] example:
1099 * Consider a system with two sockets. Each socket has
1100 * three classes of memory attached: fast, medium and slow.
1101 * Each memory class is placed in its own NUMA node. The
1102 * CPUs are placed in the node with the "fast" memory. The
1103 * 6 NUMA nodes (0-5) might be split among the sockets like
1109 * When Node 0 fills up, its memory should be migrated to
1110 * Node 1. When Node 1 fills up, it should be migrated to
1111 * Node 2. The migration path start on the nodes with the
1112 * processors (since allocations default to this node) and
1113 * fast memory, progress through medium and end with the
1116 * 0 -> 1 -> 2 -> stop
1117 * 3 -> 4 -> 5 -> stop
1119 * This is represented in the node_demotion[] like this:
1121 * { 1, // Node 0 migrates to 1
1122 * 2, // Node 1 migrates to 2
1123 * -1, // Node 2 does not migrate
1124 * 4, // Node 3 migrates to 4
1125 * 5, // Node 4 migrates to 5
1126 * -1} // Node 5 does not migrate
1130 * Writes to this array occur without locking. Cycles are
1131 * not allowed: Node X demotes to Y which demotes to X...
1133 * If multiple reads are performed, a single rcu_read_lock()
1134 * must be held over all reads to ensure that no cycles are
1137 static int node_demotion[MAX_NUMNODES] __read_mostly =
1138 {[0 ... MAX_NUMNODES - 1] = NUMA_NO_NODE};
1141 * next_demotion_node() - Get the next node in the demotion path
1142 * @node: The starting node to lookup the next node
1144 * Return: node id for next memory node in the demotion path hierarchy
1145 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
1146 * @node online or guarantee that it *continues* to be the next demotion
1149 int next_demotion_node(int node)
1154 * node_demotion[] is updated without excluding this
1155 * function from running. RCU doesn't provide any
1156 * compiler barriers, so the READ_ONCE() is required
1157 * to avoid compiler reordering or read merging.
1159 * Make sure to use RCU over entire code blocks if
1160 * node_demotion[] reads need to be consistent.
1163 target = READ_ONCE(node_demotion[node]);
1170 * Obtain the lock on page, remove all ptes and migrate the page
1171 * to the newly allocated page in newpage.
1173 static int unmap_and_move(new_page_t get_new_page,
1174 free_page_t put_new_page,
1175 unsigned long private, struct page *page,
1176 int force, enum migrate_mode mode,
1177 enum migrate_reason reason,
1178 struct list_head *ret)
1180 int rc = MIGRATEPAGE_SUCCESS;
1181 struct page *newpage = NULL;
1183 if (!thp_migration_supported() && PageTransHuge(page))
1186 if (page_count(page) == 1) {
1187 /* page was freed from under us. So we are done. */
1188 ClearPageActive(page);
1189 ClearPageUnevictable(page);
1190 if (unlikely(__PageMovable(page))) {
1192 if (!PageMovable(page))
1193 __ClearPageIsolated(page);
1199 newpage = get_new_page(page, private);
1203 rc = __unmap_and_move(page, newpage, force, mode);
1204 if (rc == MIGRATEPAGE_SUCCESS)
1205 set_page_owner_migrate_reason(newpage, reason);
1208 if (rc != -EAGAIN) {
1210 * A page that has been migrated has all references
1211 * removed and will be freed. A page that has not been
1212 * migrated will have kept its references and be restored.
1214 list_del(&page->lru);
1218 * If migration is successful, releases reference grabbed during
1219 * isolation. Otherwise, restore the page to right list unless
1222 if (rc == MIGRATEPAGE_SUCCESS) {
1224 * Compaction can migrate also non-LRU pages which are
1225 * not accounted to NR_ISOLATED_*. They can be recognized
1228 if (likely(!__PageMovable(page)))
1229 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1230 page_is_file_lru(page), -thp_nr_pages(page));
1232 if (reason != MR_MEMORY_FAILURE)
1234 * We release the page in page_handle_poison.
1239 list_add_tail(&page->lru, ret);
1242 put_new_page(newpage, private);
1251 * Counterpart of unmap_and_move_page() for hugepage migration.
1253 * This function doesn't wait the completion of hugepage I/O
1254 * because there is no race between I/O and migration for hugepage.
1255 * Note that currently hugepage I/O occurs only in direct I/O
1256 * where no lock is held and PG_writeback is irrelevant,
1257 * and writeback status of all subpages are counted in the reference
1258 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1259 * under direct I/O, the reference of the head page is 512 and a bit more.)
1260 * This means that when we try to migrate hugepage whose subpages are
1261 * doing direct I/O, some references remain after try_to_unmap() and
1262 * hugepage migration fails without data corruption.
1264 * There is also no race when direct I/O is issued on the page under migration,
1265 * because then pte is replaced with migration swap entry and direct I/O code
1266 * will wait in the page fault for migration to complete.
1268 static int unmap_and_move_huge_page(new_page_t get_new_page,
1269 free_page_t put_new_page, unsigned long private,
1270 struct page *hpage, int force,
1271 enum migrate_mode mode, int reason,
1272 struct list_head *ret)
1275 int page_was_mapped = 0;
1276 struct page *new_hpage;
1277 struct anon_vma *anon_vma = NULL;
1278 struct address_space *mapping = NULL;
1281 * Migratability of hugepages depends on architectures and their size.
1282 * This check is necessary because some callers of hugepage migration
1283 * like soft offline and memory hotremove don't walk through page
1284 * tables or check whether the hugepage is pmd-based or not before
1285 * kicking migration.
1287 if (!hugepage_migration_supported(page_hstate(hpage))) {
1288 list_move_tail(&hpage->lru, ret);
1292 if (page_count(hpage) == 1) {
1293 /* page was freed from under us. So we are done. */
1294 putback_active_hugepage(hpage);
1295 return MIGRATEPAGE_SUCCESS;
1298 new_hpage = get_new_page(hpage, private);
1302 if (!trylock_page(hpage)) {
1307 case MIGRATE_SYNC_NO_COPY:
1316 * Check for pages which are in the process of being freed. Without
1317 * page_mapping() set, hugetlbfs specific move page routine will not
1318 * be called and we could leak usage counts for subpools.
1320 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1325 if (PageAnon(hpage))
1326 anon_vma = page_get_anon_vma(hpage);
1328 if (unlikely(!trylock_page(new_hpage)))
1331 if (page_mapped(hpage)) {
1332 bool mapping_locked = false;
1333 enum ttu_flags ttu = 0;
1335 if (!PageAnon(hpage)) {
1337 * In shared mappings, try_to_unmap could potentially
1338 * call huge_pmd_unshare. Because of this, take
1339 * semaphore in write mode here and set TTU_RMAP_LOCKED
1340 * to let lower levels know we have taken the lock.
1342 mapping = hugetlb_page_mapping_lock_write(hpage);
1343 if (unlikely(!mapping))
1344 goto unlock_put_anon;
1346 mapping_locked = true;
1347 ttu |= TTU_RMAP_LOCKED;
1350 try_to_migrate(hpage, ttu);
1351 page_was_mapped = 1;
1354 i_mmap_unlock_write(mapping);
1357 if (!page_mapped(hpage))
1358 rc = move_to_new_page(new_hpage, hpage, mode);
1360 if (page_was_mapped)
1361 remove_migration_ptes(hpage,
1362 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1365 unlock_page(new_hpage);
1369 put_anon_vma(anon_vma);
1371 if (rc == MIGRATEPAGE_SUCCESS) {
1372 move_hugetlb_state(hpage, new_hpage, reason);
1373 put_new_page = NULL;
1379 if (rc == MIGRATEPAGE_SUCCESS)
1380 putback_active_hugepage(hpage);
1381 else if (rc != -EAGAIN)
1382 list_move_tail(&hpage->lru, ret);
1385 * If migration was not successful and there's a freeing callback, use
1386 * it. Otherwise, put_page() will drop the reference grabbed during
1390 put_new_page(new_hpage, private);
1392 putback_active_hugepage(new_hpage);
1397 static inline int try_split_thp(struct page *page, struct page **page2,
1398 struct list_head *from)
1403 rc = split_huge_page_to_list(page, from);
1406 list_safe_reset_next(page, *page2, lru);
1412 * migrate_pages - migrate the pages specified in a list, to the free pages
1413 * supplied as the target for the page migration
1415 * @from: The list of pages to be migrated.
1416 * @get_new_page: The function used to allocate free pages to be used
1417 * as the target of the page migration.
1418 * @put_new_page: The function used to free target pages if migration
1419 * fails, or NULL if no special handling is necessary.
1420 * @private: Private data to be passed on to get_new_page()
1421 * @mode: The migration mode that specifies the constraints for
1422 * page migration, if any.
1423 * @reason: The reason for page migration.
1424 * @ret_succeeded: Set to the number of normal pages migrated successfully if
1425 * the caller passes a non-NULL pointer.
1427 * The function returns after 10 attempts or if no pages are movable any more
1428 * because the list has become empty or no retryable pages exist any more.
1429 * It is caller's responsibility to call putback_movable_pages() to return pages
1430 * to the LRU or free list only if ret != 0.
1432 * Returns the number of {normal page, THP} that were not migrated, or an error code.
1433 * The number of THP splits will be considered as the number of non-migrated THP,
1434 * no matter how many subpages of the THP are migrated successfully.
1436 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1437 free_page_t put_new_page, unsigned long private,
1438 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1443 int nr_failed_pages = 0;
1444 int nr_succeeded = 0;
1445 int nr_thp_succeeded = 0;
1446 int nr_thp_failed = 0;
1447 int nr_thp_split = 0;
1449 bool is_thp = false;
1452 int swapwrite = current->flags & PF_SWAPWRITE;
1453 int rc, nr_subpages;
1454 LIST_HEAD(ret_pages);
1455 LIST_HEAD(thp_split_pages);
1456 bool nosplit = (reason == MR_NUMA_MISPLACED);
1457 bool no_subpage_counting = false;
1459 trace_mm_migrate_pages_start(mode, reason);
1462 current->flags |= PF_SWAPWRITE;
1464 thp_subpage_migration:
1465 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1469 list_for_each_entry_safe(page, page2, from, lru) {
1472 * THP statistics is based on the source huge page.
1473 * Capture required information that might get lost
1476 is_thp = PageTransHuge(page) && !PageHuge(page);
1477 nr_subpages = thp_nr_pages(page);
1481 rc = unmap_and_move_huge_page(get_new_page,
1482 put_new_page, private, page,
1483 pass > 2, mode, reason,
1486 rc = unmap_and_move(get_new_page, put_new_page,
1487 private, page, pass > 2, mode,
1488 reason, &ret_pages);
1491 * Success: non hugetlb page will be freed, hugetlb
1492 * page will be put back
1493 * -EAGAIN: stay on the from list
1494 * -ENOMEM: stay on the from list
1495 * Other errno: put on ret_pages list then splice to
1500 * THP migration might be unsupported or the
1501 * allocation could've failed so we should
1502 * retry on the same page with the THP split
1505 * Head page is retried immediately and tail
1506 * pages are added to the tail of the list so
1507 * we encounter them after the rest of the list
1511 /* THP migration is unsupported */
1514 if (!try_split_thp(page, &page2, &thp_split_pages)) {
1519 nr_failed_pages += nr_subpages;
1523 /* Hugetlb migration is unsupported */
1524 if (!no_subpage_counting)
1530 * When memory is low, don't bother to try to migrate
1531 * other pages, just exit.
1532 * THP NUMA faulting doesn't split THP to retry.
1534 if (is_thp && !nosplit) {
1536 if (!try_split_thp(page, &page2, &thp_split_pages)) {
1541 nr_failed_pages += nr_subpages;
1545 if (!no_subpage_counting)
1556 case MIGRATEPAGE_SUCCESS:
1559 nr_succeeded += nr_subpages;
1566 * Permanent failure (-EBUSY, etc.):
1567 * unlike -EAGAIN case, the failed page is
1568 * removed from migration page list and not
1569 * retried in the next outer loop.
1573 nr_failed_pages += nr_subpages;
1577 if (!no_subpage_counting)
1585 nr_thp_failed += thp_retry;
1587 * Try to migrate subpages of fail-to-migrate THPs, no nr_failed
1588 * counting in this round, since all subpages of a THP is counted
1589 * as 1 failure in the first round.
1591 if (!list_empty(&thp_split_pages)) {
1593 * Move non-migrated pages (after 10 retries) to ret_pages
1594 * to avoid migrating them again.
1596 list_splice_init(from, &ret_pages);
1597 list_splice_init(&thp_split_pages, from);
1598 no_subpage_counting = true;
1600 goto thp_subpage_migration;
1603 rc = nr_failed + nr_thp_failed;
1606 * Put the permanent failure page back to migration list, they
1607 * will be put back to the right list by the caller.
1609 list_splice(&ret_pages, from);
1611 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1612 count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1613 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1614 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1615 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1616 trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1617 nr_thp_failed, nr_thp_split, mode, reason);
1620 current->flags &= ~PF_SWAPWRITE;
1623 *ret_succeeded = nr_succeeded;
1628 struct page *alloc_migration_target(struct page *page, unsigned long private)
1630 struct migration_target_control *mtc;
1632 unsigned int order = 0;
1633 struct page *new_page = NULL;
1637 mtc = (struct migration_target_control *)private;
1638 gfp_mask = mtc->gfp_mask;
1640 if (nid == NUMA_NO_NODE)
1641 nid = page_to_nid(page);
1643 if (PageHuge(page)) {
1644 struct hstate *h = page_hstate(compound_head(page));
1646 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1647 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1650 if (PageTransHuge(page)) {
1652 * clear __GFP_RECLAIM to make the migration callback
1653 * consistent with regular THP allocations.
1655 gfp_mask &= ~__GFP_RECLAIM;
1656 gfp_mask |= GFP_TRANSHUGE;
1657 order = HPAGE_PMD_ORDER;
1659 zidx = zone_idx(page_zone(page));
1660 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1661 gfp_mask |= __GFP_HIGHMEM;
1663 new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
1665 if (new_page && PageTransHuge(new_page))
1666 prep_transhuge_page(new_page);
1673 static int store_status(int __user *status, int start, int value, int nr)
1676 if (put_user(value, status + start))
1684 static int do_move_pages_to_node(struct mm_struct *mm,
1685 struct list_head *pagelist, int node)
1688 struct migration_target_control mtc = {
1690 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1693 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1694 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1696 putback_movable_pages(pagelist);
1701 * Resolves the given address to a struct page, isolates it from the LRU and
1702 * puts it to the given pagelist.
1704 * errno - if the page cannot be found/isolated
1705 * 0 - when it doesn't have to be migrated because it is already on the
1707 * 1 - when it has been queued
1709 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1710 int node, struct list_head *pagelist, bool migrate_all)
1712 struct vm_area_struct *vma;
1714 unsigned int follflags;
1719 vma = find_vma(mm, addr);
1720 if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1723 /* FOLL_DUMP to ignore special (like zero) pages */
1724 follflags = FOLL_GET | FOLL_DUMP;
1725 page = follow_page(vma, addr, follflags);
1727 err = PTR_ERR(page);
1736 if (page_to_nid(page) == node)
1740 if (page_mapcount(page) > 1 && !migrate_all)
1743 if (PageHuge(page)) {
1744 if (PageHead(page)) {
1745 isolate_huge_page(page, pagelist);
1751 head = compound_head(page);
1752 err = isolate_lru_page(head);
1757 list_add_tail(&head->lru, pagelist);
1758 mod_node_page_state(page_pgdat(head),
1759 NR_ISOLATED_ANON + page_is_file_lru(head),
1760 thp_nr_pages(head));
1764 * Either remove the duplicate refcount from
1765 * isolate_lru_page() or drop the page ref if it was
1770 mmap_read_unlock(mm);
1774 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1775 struct list_head *pagelist, int __user *status,
1776 int start, int i, unsigned long nr_pages)
1780 if (list_empty(pagelist))
1783 err = do_move_pages_to_node(mm, pagelist, node);
1786 * Positive err means the number of failed
1787 * pages to migrate. Since we are going to
1788 * abort and return the number of non-migrated
1789 * pages, so need to include the rest of the
1790 * nr_pages that have not been attempted as
1794 err += nr_pages - i - 1;
1797 return store_status(status, start, node, i - start);
1801 * Migrate an array of page address onto an array of nodes and fill
1802 * the corresponding array of status.
1804 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1805 unsigned long nr_pages,
1806 const void __user * __user *pages,
1807 const int __user *nodes,
1808 int __user *status, int flags)
1810 int current_node = NUMA_NO_NODE;
1811 LIST_HEAD(pagelist);
1815 lru_cache_disable();
1817 for (i = start = 0; i < nr_pages; i++) {
1818 const void __user *p;
1823 if (get_user(p, pages + i))
1825 if (get_user(node, nodes + i))
1827 addr = (unsigned long)untagged_addr(p);
1830 if (node < 0 || node >= MAX_NUMNODES)
1832 if (!node_state(node, N_MEMORY))
1836 if (!node_isset(node, task_nodes))
1839 if (current_node == NUMA_NO_NODE) {
1840 current_node = node;
1842 } else if (node != current_node) {
1843 err = move_pages_and_store_status(mm, current_node,
1844 &pagelist, status, start, i, nr_pages);
1848 current_node = node;
1852 * Errors in the page lookup or isolation are not fatal and we simply
1853 * report them via status
1855 err = add_page_for_migration(mm, addr, current_node,
1856 &pagelist, flags & MPOL_MF_MOVE_ALL);
1859 /* The page is successfully queued for migration */
1864 * If the page is already on the target node (!err), store the
1865 * node, otherwise, store the err.
1867 err = store_status(status, i, err ? : current_node, 1);
1871 err = move_pages_and_store_status(mm, current_node, &pagelist,
1872 status, start, i, nr_pages);
1875 current_node = NUMA_NO_NODE;
1878 /* Make sure we do not overwrite the existing error */
1879 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1880 status, start, i, nr_pages);
1889 * Determine the nodes of an array of pages and store it in an array of status.
1891 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1892 const void __user **pages, int *status)
1898 for (i = 0; i < nr_pages; i++) {
1899 unsigned long addr = (unsigned long)(*pages);
1900 struct vm_area_struct *vma;
1904 vma = vma_lookup(mm, addr);
1908 /* FOLL_DUMP to ignore special (like zero) pages */
1909 page = follow_page(vma, addr, FOLL_DUMP);
1911 err = PTR_ERR(page);
1915 err = page ? page_to_nid(page) : -ENOENT;
1923 mmap_read_unlock(mm);
1926 static int get_compat_pages_array(const void __user *chunk_pages[],
1927 const void __user * __user *pages,
1928 unsigned long chunk_nr)
1930 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1934 for (i = 0; i < chunk_nr; i++) {
1935 if (get_user(p, pages32 + i))
1937 chunk_pages[i] = compat_ptr(p);
1944 * Determine the nodes of a user array of pages and store it in
1945 * a user array of status.
1947 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1948 const void __user * __user *pages,
1951 #define DO_PAGES_STAT_CHUNK_NR 16
1952 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1953 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1956 unsigned long chunk_nr;
1958 chunk_nr = nr_pages;
1959 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1960 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1962 if (in_compat_syscall()) {
1963 if (get_compat_pages_array(chunk_pages, pages,
1967 if (copy_from_user(chunk_pages, pages,
1968 chunk_nr * sizeof(*chunk_pages)))
1972 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1974 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1979 nr_pages -= chunk_nr;
1981 return nr_pages ? -EFAULT : 0;
1984 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1986 struct task_struct *task;
1987 struct mm_struct *mm;
1990 * There is no need to check if current process has the right to modify
1991 * the specified process when they are same.
1995 *mem_nodes = cpuset_mems_allowed(current);
1999 /* Find the mm_struct */
2001 task = find_task_by_vpid(pid);
2004 return ERR_PTR(-ESRCH);
2006 get_task_struct(task);
2009 * Check if this process has the right to modify the specified
2010 * process. Use the regular "ptrace_may_access()" checks.
2012 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2014 mm = ERR_PTR(-EPERM);
2019 mm = ERR_PTR(security_task_movememory(task));
2022 *mem_nodes = cpuset_mems_allowed(task);
2023 mm = get_task_mm(task);
2025 put_task_struct(task);
2027 mm = ERR_PTR(-EINVAL);
2032 * Move a list of pages in the address space of the currently executing
2035 static int kernel_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 struct mm_struct *mm;
2042 nodemask_t task_nodes;
2045 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2048 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2051 mm = find_mm_struct(pid, &task_nodes);
2056 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2057 nodes, status, flags);
2059 err = do_pages_stat(mm, nr_pages, pages, status);
2065 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2066 const void __user * __user *, pages,
2067 const int __user *, nodes,
2068 int __user *, status, int, flags)
2070 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2073 #ifdef CONFIG_NUMA_BALANCING
2075 * Returns true if this is a safe migration target node for misplaced NUMA
2076 * pages. Currently it only checks the watermarks which crude
2078 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2079 unsigned long nr_migrate_pages)
2083 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2084 struct zone *zone = pgdat->node_zones + z;
2086 if (!populated_zone(zone))
2089 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2090 if (!zone_watermark_ok(zone, 0,
2091 high_wmark_pages(zone) +
2100 static struct page *alloc_misplaced_dst_page(struct page *page,
2103 int nid = (int) data;
2104 struct page *newpage;
2106 newpage = __alloc_pages_node(nid,
2107 (GFP_HIGHUSER_MOVABLE |
2108 __GFP_THISNODE | __GFP_NOMEMALLOC |
2109 __GFP_NORETRY | __GFP_NOWARN) &
2115 static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2118 int nid = (int) data;
2119 struct page *newpage;
2121 newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2126 prep_transhuge_page(newpage);
2132 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2135 int nr_pages = thp_nr_pages(page);
2137 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2139 /* Do not migrate THP mapped by multiple processes */
2140 if (PageTransHuge(page) && total_mapcount(page) > 1)
2143 /* Avoid migrating to a node that is nearly full */
2144 if (!migrate_balanced_pgdat(pgdat, nr_pages))
2147 if (isolate_lru_page(page))
2150 page_lru = page_is_file_lru(page);
2151 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2155 * Isolating the page has taken another reference, so the
2156 * caller's reference can be safely dropped without the page
2157 * disappearing underneath us during migration.
2164 * Attempt to migrate a misplaced page to the specified destination
2165 * node. Caller is expected to have an elevated reference count on
2166 * the page that will be dropped by this function before returning.
2168 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2171 pg_data_t *pgdat = NODE_DATA(node);
2174 LIST_HEAD(migratepages);
2177 int nr_pages = thp_nr_pages(page);
2180 * PTE mapped THP or HugeTLB page can't reach here so the page could
2181 * be either base page or THP. And it must be head page if it is
2184 compound = PageTransHuge(page);
2187 new = alloc_misplaced_dst_page_thp;
2189 new = alloc_misplaced_dst_page;
2192 * Don't migrate file pages that are mapped in multiple processes
2193 * with execute permissions as they are probably shared libraries.
2195 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2196 (vma->vm_flags & VM_EXEC))
2200 * Also do not migrate dirty pages as not all filesystems can move
2201 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2203 if (page_is_file_lru(page) && PageDirty(page))
2206 isolated = numamigrate_isolate_page(pgdat, page);
2210 list_add(&page->lru, &migratepages);
2211 nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
2212 MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
2214 if (!list_empty(&migratepages)) {
2215 list_del(&page->lru);
2216 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2217 page_is_file_lru(page), -nr_pages);
2218 putback_lru_page(page);
2222 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
2223 BUG_ON(!list_empty(&migratepages));
2230 #endif /* CONFIG_NUMA_BALANCING */
2231 #endif /* CONFIG_NUMA */
2233 #ifdef CONFIG_DEVICE_PRIVATE
2234 static int migrate_vma_collect_skip(unsigned long start,
2236 struct mm_walk *walk)
2238 struct migrate_vma *migrate = walk->private;
2241 for (addr = start; addr < end; addr += PAGE_SIZE) {
2242 migrate->dst[migrate->npages] = 0;
2243 migrate->src[migrate->npages++] = 0;
2249 static int migrate_vma_collect_hole(unsigned long start,
2251 __always_unused int depth,
2252 struct mm_walk *walk)
2254 struct migrate_vma *migrate = walk->private;
2257 /* Only allow populating anonymous memory. */
2258 if (!vma_is_anonymous(walk->vma))
2259 return migrate_vma_collect_skip(start, end, walk);
2261 for (addr = start; addr < end; addr += PAGE_SIZE) {
2262 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2263 migrate->dst[migrate->npages] = 0;
2271 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2272 unsigned long start,
2274 struct mm_walk *walk)
2276 struct migrate_vma *migrate = walk->private;
2277 struct vm_area_struct *vma = walk->vma;
2278 struct mm_struct *mm = vma->vm_mm;
2279 unsigned long addr = start, unmapped = 0;
2284 if (pmd_none(*pmdp))
2285 return migrate_vma_collect_hole(start, end, -1, walk);
2287 if (pmd_trans_huge(*pmdp)) {
2290 ptl = pmd_lock(mm, pmdp);
2291 if (unlikely(!pmd_trans_huge(*pmdp))) {
2296 page = pmd_page(*pmdp);
2297 if (is_huge_zero_page(page)) {
2299 split_huge_pmd(vma, pmdp, addr);
2300 if (pmd_trans_unstable(pmdp))
2301 return migrate_vma_collect_skip(start, end,
2308 if (unlikely(!trylock_page(page)))
2309 return migrate_vma_collect_skip(start, end,
2311 ret = split_huge_page(page);
2315 return migrate_vma_collect_skip(start, end,
2317 if (pmd_none(*pmdp))
2318 return migrate_vma_collect_hole(start, end, -1,
2323 if (unlikely(pmd_bad(*pmdp)))
2324 return migrate_vma_collect_skip(start, end, walk);
2326 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2327 arch_enter_lazy_mmu_mode();
2329 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2330 unsigned long mpfn = 0, pfn;
2337 if (pte_none(pte)) {
2338 if (vma_is_anonymous(vma)) {
2339 mpfn = MIGRATE_PFN_MIGRATE;
2345 if (!pte_present(pte)) {
2347 * Only care about unaddressable device page special
2348 * page table entry. Other special swap entries are not
2349 * migratable, and we ignore regular swapped page.
2351 entry = pte_to_swp_entry(pte);
2352 if (!is_device_private_entry(entry))
2355 page = pfn_swap_entry_to_page(entry);
2356 if (!(migrate->flags &
2357 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2358 page->pgmap->owner != migrate->pgmap_owner)
2361 mpfn = migrate_pfn(page_to_pfn(page)) |
2362 MIGRATE_PFN_MIGRATE;
2363 if (is_writable_device_private_entry(entry))
2364 mpfn |= MIGRATE_PFN_WRITE;
2366 if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2369 if (is_zero_pfn(pfn)) {
2370 mpfn = MIGRATE_PFN_MIGRATE;
2374 page = vm_normal_page(migrate->vma, addr, pte);
2375 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2376 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2379 /* FIXME support THP */
2380 if (!page || !page->mapping || PageTransCompound(page)) {
2386 * By getting a reference on the page we pin it and that blocks
2387 * any kind of migration. Side effect is that it "freezes" the
2390 * We drop this reference after isolating the page from the lru
2391 * for non device page (device page are not on the lru and thus
2392 * can't be dropped from it).
2397 * Optimize for the common case where page is only mapped once
2398 * in one process. If we can lock the page, then we can safely
2399 * set up a special migration page table entry now.
2401 if (trylock_page(page)) {
2405 ptep_get_and_clear(mm, addr, ptep);
2407 /* Setup special migration page table entry */
2408 if (mpfn & MIGRATE_PFN_WRITE)
2409 entry = make_writable_migration_entry(
2412 entry = make_readable_migration_entry(
2414 swp_pte = swp_entry_to_pte(entry);
2415 if (pte_present(pte)) {
2416 if (pte_soft_dirty(pte))
2417 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2418 if (pte_uffd_wp(pte))
2419 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2421 if (pte_swp_soft_dirty(pte))
2422 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2423 if (pte_swp_uffd_wp(pte))
2424 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2426 set_pte_at(mm, addr, ptep, swp_pte);
2429 * This is like regular unmap: we remove the rmap and
2430 * drop page refcount. Page won't be freed, as we took
2431 * a reference just above.
2433 page_remove_rmap(page, false);
2436 if (pte_present(pte))
2444 migrate->dst[migrate->npages] = 0;
2445 migrate->src[migrate->npages++] = mpfn;
2447 arch_leave_lazy_mmu_mode();
2448 pte_unmap_unlock(ptep - 1, ptl);
2450 /* Only flush the TLB if we actually modified any entries */
2452 flush_tlb_range(walk->vma, start, end);
2457 static const struct mm_walk_ops migrate_vma_walk_ops = {
2458 .pmd_entry = migrate_vma_collect_pmd,
2459 .pte_hole = migrate_vma_collect_hole,
2463 * migrate_vma_collect() - collect pages over a range of virtual addresses
2464 * @migrate: migrate struct containing all migration information
2466 * This will walk the CPU page table. For each virtual address backed by a
2467 * valid page, it updates the src array and takes a reference on the page, in
2468 * order to pin the page until we lock it and unmap it.
2470 static void migrate_vma_collect(struct migrate_vma *migrate)
2472 struct mmu_notifier_range range;
2475 * Note that the pgmap_owner is passed to the mmu notifier callback so
2476 * that the registered device driver can skip invalidating device
2477 * private page mappings that won't be migrated.
2479 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2480 migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
2481 migrate->pgmap_owner);
2482 mmu_notifier_invalidate_range_start(&range);
2484 walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2485 &migrate_vma_walk_ops, migrate);
2487 mmu_notifier_invalidate_range_end(&range);
2488 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2492 * migrate_vma_check_page() - check if page is pinned or not
2493 * @page: struct page to check
2495 * Pinned pages cannot be migrated. This is the same test as in
2496 * folio_migrate_mapping(), except that here we allow migration of a
2499 static bool migrate_vma_check_page(struct page *page)
2502 * One extra ref because caller holds an extra reference, either from
2503 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2509 * FIXME support THP (transparent huge page), it is bit more complex to
2510 * check them than regular pages, because they can be mapped with a pmd
2511 * or with a pte (split pte mapping).
2513 if (PageCompound(page))
2516 /* Page from ZONE_DEVICE have one extra reference */
2517 if (is_zone_device_page(page)) {
2519 * Private page can never be pin as they have no valid pte and
2520 * GUP will fail for those. Yet if there is a pending migration
2521 * a thread might try to wait on the pte migration entry and
2522 * will bump the page reference count. Sadly there is no way to
2523 * differentiate a regular pin from migration wait. Hence to
2524 * avoid 2 racing thread trying to migrate back to CPU to enter
2525 * infinite loop (one stopping migration because the other is
2526 * waiting on pte migration entry). We always return true here.
2528 * FIXME proper solution is to rework migration_entry_wait() so
2529 * it does not need to take a reference on page.
2531 return is_device_private_page(page);
2534 /* For file back page */
2535 if (page_mapping(page))
2536 extra += 1 + page_has_private(page);
2538 if ((page_count(page) - extra) > page_mapcount(page))
2545 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2546 * @migrate: migrate struct containing all migration information
2548 * Isolate pages from the LRU and replace mappings (CPU page table pte) with a
2549 * special migration pte entry and check if it has been pinned. Pinned pages are
2550 * restored because we cannot migrate them.
2552 * This is the last step before we call the device driver callback to allocate
2553 * destination memory and copy contents of original page over to new page.
2555 static void migrate_vma_unmap(struct migrate_vma *migrate)
2557 const unsigned long npages = migrate->npages;
2558 const unsigned long start = migrate->start;
2559 unsigned long addr, i, restore = 0;
2560 bool allow_drain = true;
2564 for (i = 0; i < npages; i++) {
2565 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2570 /* ZONE_DEVICE pages are not on LRU */
2571 if (!is_zone_device_page(page)) {
2572 if (!PageLRU(page) && allow_drain) {
2573 /* Drain CPU's pagevec */
2574 lru_add_drain_all();
2575 allow_drain = false;
2578 if (isolate_lru_page(page)) {
2579 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2585 /* Drop the reference we took in collect */
2589 if (page_mapped(page))
2590 try_to_migrate(page, 0);
2592 if (page_mapped(page) || !migrate_vma_check_page(page)) {
2593 if (!is_zone_device_page(page)) {
2595 putback_lru_page(page);
2598 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2605 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2606 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2608 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2611 remove_migration_ptes(page, page, false);
2613 migrate->src[i] = 0;
2621 * migrate_vma_setup() - prepare to migrate a range of memory
2622 * @args: contains the vma, start, and pfns arrays for the migration
2624 * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2627 * Prepare to migrate a range of memory virtual address range by collecting all
2628 * the pages backing each virtual address in the range, saving them inside the
2629 * src array. Then lock those pages and unmap them. Once the pages are locked
2630 * and unmapped, check whether each page is pinned or not. Pages that aren't
2631 * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2632 * corresponding src array entry. Then restores any pages that are pinned, by
2633 * remapping and unlocking those pages.
2635 * The caller should then allocate destination memory and copy source memory to
2636 * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2637 * flag set). Once these are allocated and copied, the caller must update each
2638 * corresponding entry in the dst array with the pfn value of the destination
2639 * page and with MIGRATE_PFN_VALID. Destination pages must be locked via
2642 * Note that the caller does not have to migrate all the pages that are marked
2643 * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2644 * device memory to system memory. If the caller cannot migrate a device page
2645 * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2646 * consequences for the userspace process, so it must be avoided if at all
2649 * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2650 * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2651 * allowing the caller to allocate device memory for those unbacked virtual
2652 * addresses. For this the caller simply has to allocate device memory and
2653 * properly set the destination entry like for regular migration. Note that
2654 * this can still fail, and thus inside the device driver you must check if the
2655 * migration was successful for those entries after calling migrate_vma_pages(),
2656 * just like for regular migration.
2658 * After that, the callers must call migrate_vma_pages() to go over each entry
2659 * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2660 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2661 * then migrate_vma_pages() to migrate struct page information from the source
2662 * struct page to the destination struct page. If it fails to migrate the
2663 * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2666 * At this point all successfully migrated pages have an entry in the src
2667 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2668 * array entry with MIGRATE_PFN_VALID flag set.
2670 * Once migrate_vma_pages() returns the caller may inspect which pages were
2671 * successfully migrated, and which were not. Successfully migrated pages will
2672 * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2674 * It is safe to update device page table after migrate_vma_pages() because
2675 * both destination and source page are still locked, and the mmap_lock is held
2676 * in read mode (hence no one can unmap the range being migrated).
2678 * Once the caller is done cleaning up things and updating its page table (if it
2679 * chose to do so, this is not an obligation) it finally calls
2680 * migrate_vma_finalize() to update the CPU page table to point to new pages
2681 * for successfully migrated pages or otherwise restore the CPU page table to
2682 * point to the original source pages.
2684 int migrate_vma_setup(struct migrate_vma *args)
2686 long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2688 args->start &= PAGE_MASK;
2689 args->end &= PAGE_MASK;
2690 if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2691 (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2695 if (args->start < args->vma->vm_start ||
2696 args->start >= args->vma->vm_end)
2698 if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2700 if (!args->src || !args->dst)
2703 memset(args->src, 0, sizeof(*args->src) * nr_pages);
2707 migrate_vma_collect(args);
2710 migrate_vma_unmap(args);
2713 * At this point pages are locked and unmapped, and thus they have
2714 * stable content and can safely be copied to destination memory that
2715 * is allocated by the drivers.
2720 EXPORT_SYMBOL(migrate_vma_setup);
2723 * This code closely matches the code in:
2724 * __handle_mm_fault()
2725 * handle_pte_fault()
2726 * do_anonymous_page()
2727 * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2730 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2735 struct vm_area_struct *vma = migrate->vma;
2736 struct mm_struct *mm = vma->vm_mm;
2746 /* Only allow populating anonymous memory */
2747 if (!vma_is_anonymous(vma))
2750 pgdp = pgd_offset(mm, addr);
2751 p4dp = p4d_alloc(mm, pgdp, addr);
2754 pudp = pud_alloc(mm, p4dp, addr);
2757 pmdp = pmd_alloc(mm, pudp, addr);
2761 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2765 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2766 * pte_offset_map() on pmds where a huge pmd might be created
2767 * from a different thread.
2769 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2770 * parallel threads are excluded by other means.
2772 * Here we only have mmap_read_lock(mm).
2774 if (pte_alloc(mm, pmdp))
2777 /* See the comment in pte_alloc_one_map() */
2778 if (unlikely(pmd_trans_unstable(pmdp)))
2781 if (unlikely(anon_vma_prepare(vma)))
2783 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
2787 * The memory barrier inside __SetPageUptodate makes sure that
2788 * preceding stores to the page contents become visible before
2789 * the set_pte_at() write.
2791 __SetPageUptodate(page);
2793 if (is_zone_device_page(page)) {
2794 if (is_device_private_page(page)) {
2795 swp_entry_t swp_entry;
2797 if (vma->vm_flags & VM_WRITE)
2798 swp_entry = make_writable_device_private_entry(
2801 swp_entry = make_readable_device_private_entry(
2803 entry = swp_entry_to_pte(swp_entry);
2806 * For now we only support migrating to un-addressable
2809 pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2813 entry = mk_pte(page, vma->vm_page_prot);
2814 if (vma->vm_flags & VM_WRITE)
2815 entry = pte_mkwrite(pte_mkdirty(entry));
2818 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2820 if (check_stable_address_space(mm))
2823 if (pte_present(*ptep)) {
2824 unsigned long pfn = pte_pfn(*ptep);
2826 if (!is_zero_pfn(pfn))
2829 } else if (!pte_none(*ptep))
2833 * Check for userfaultfd but do not deliver the fault. Instead,
2836 if (userfaultfd_missing(vma))
2839 inc_mm_counter(mm, MM_ANONPAGES);
2840 page_add_new_anon_rmap(page, vma, addr, false);
2841 if (!is_zone_device_page(page))
2842 lru_cache_add_inactive_or_unevictable(page, vma);
2846 flush_cache_page(vma, addr, pte_pfn(*ptep));
2847 ptep_clear_flush_notify(vma, addr, ptep);
2848 set_pte_at_notify(mm, addr, ptep, entry);
2849 update_mmu_cache(vma, addr, ptep);
2851 /* No need to invalidate - it was non-present before */
2852 set_pte_at(mm, addr, ptep, entry);
2853 update_mmu_cache(vma, addr, ptep);
2856 pte_unmap_unlock(ptep, ptl);
2857 *src = MIGRATE_PFN_MIGRATE;
2861 pte_unmap_unlock(ptep, ptl);
2863 *src &= ~MIGRATE_PFN_MIGRATE;
2867 * migrate_vma_pages() - migrate meta-data from src page to dst page
2868 * @migrate: migrate struct containing all migration information
2870 * This migrates struct page meta-data from source struct page to destination
2871 * struct page. This effectively finishes the migration from source page to the
2874 void migrate_vma_pages(struct migrate_vma *migrate)
2876 const unsigned long npages = migrate->npages;
2877 const unsigned long start = migrate->start;
2878 struct mmu_notifier_range range;
2879 unsigned long addr, i;
2880 bool notified = false;
2882 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2883 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2884 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2885 struct address_space *mapping;
2889 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2894 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2899 mmu_notifier_range_init_owner(&range,
2900 MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2901 migrate->vma->vm_mm, addr, migrate->end,
2902 migrate->pgmap_owner);
2903 mmu_notifier_invalidate_range_start(&range);
2905 migrate_vma_insert_page(migrate, addr, newpage,
2910 mapping = page_mapping(page);
2912 if (is_zone_device_page(newpage)) {
2913 if (is_device_private_page(newpage)) {
2915 * For now only support private anonymous when
2916 * migrating to un-addressable device memory.
2919 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2924 * Other types of ZONE_DEVICE page are not
2927 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2932 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2933 if (r != MIGRATEPAGE_SUCCESS)
2934 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2938 * No need to double call mmu_notifier->invalidate_range() callback as
2939 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
2940 * did already call it.
2943 mmu_notifier_invalidate_range_only_end(&range);
2945 EXPORT_SYMBOL(migrate_vma_pages);
2948 * migrate_vma_finalize() - restore CPU page table entry
2949 * @migrate: migrate struct containing all migration information
2951 * This replaces the special migration pte entry with either a mapping to the
2952 * new page if migration was successful for that page, or to the original page
2955 * This also unlocks the pages and puts them back on the lru, or drops the extra
2956 * refcount, for device pages.
2958 void migrate_vma_finalize(struct migrate_vma *migrate)
2960 const unsigned long npages = migrate->npages;
2963 for (i = 0; i < npages; i++) {
2964 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2965 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2969 unlock_page(newpage);
2975 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
2977 unlock_page(newpage);
2983 remove_migration_ptes(page, newpage, false);
2986 if (is_zone_device_page(page))
2989 putback_lru_page(page);
2991 if (newpage != page) {
2992 unlock_page(newpage);
2993 if (is_zone_device_page(newpage))
2996 putback_lru_page(newpage);
3000 EXPORT_SYMBOL(migrate_vma_finalize);
3001 #endif /* CONFIG_DEVICE_PRIVATE */
3003 #if defined(CONFIG_HOTPLUG_CPU)
3004 /* Disable reclaim-based migration. */
3005 static void __disable_all_migrate_targets(void)
3009 for_each_online_node(node)
3010 node_demotion[node] = NUMA_NO_NODE;
3013 static void disable_all_migrate_targets(void)
3015 __disable_all_migrate_targets();
3018 * Ensure that the "disable" is visible across the system.
3019 * Readers will see either a combination of before+disable
3020 * state or disable+after. They will never see before and
3021 * after state together.
3023 * The before+after state together might have cycles and
3024 * could cause readers to do things like loop until this
3025 * function finishes. This ensures they can only see a
3026 * single "bad" read and would, for instance, only loop
3033 * Find an automatic demotion target for 'node'.
3034 * Failing here is OK. It might just indicate
3035 * being at the end of a chain.
3037 static int establish_migrate_target(int node, nodemask_t *used)
3039 int migration_target;
3042 * Can not set a migration target on a
3043 * node with it already set.
3045 * No need for READ_ONCE() here since this
3046 * in the write path for node_demotion[].
3047 * This should be the only thread writing.
3049 if (node_demotion[node] != NUMA_NO_NODE)
3050 return NUMA_NO_NODE;
3052 migration_target = find_next_best_node(node, used);
3053 if (migration_target == NUMA_NO_NODE)
3054 return NUMA_NO_NODE;
3056 node_demotion[node] = migration_target;
3058 return migration_target;
3062 * When memory fills up on a node, memory contents can be
3063 * automatically migrated to another node instead of
3064 * discarded at reclaim.
3066 * Establish a "migration path" which will start at nodes
3067 * with CPUs and will follow the priorities used to build the
3068 * page allocator zonelists.
3070 * The difference here is that cycles must be avoided. If
3071 * node0 migrates to node1, then neither node1, nor anything
3072 * node1 migrates to can migrate to node0.
3074 * This function can run simultaneously with readers of
3075 * node_demotion[]. However, it can not run simultaneously
3076 * with itself. Exclusion is provided by memory hotplug events
3077 * being single-threaded.
3079 static void __set_migration_target_nodes(void)
3081 nodemask_t next_pass = NODE_MASK_NONE;
3082 nodemask_t this_pass = NODE_MASK_NONE;
3083 nodemask_t used_targets = NODE_MASK_NONE;
3087 * Avoid any oddities like cycles that could occur
3088 * from changes in the topology. This will leave
3089 * a momentary gap when migration is disabled.
3091 disable_all_migrate_targets();
3094 * Allocations go close to CPUs, first. Assume that
3095 * the migration path starts at the nodes with CPUs.
3097 next_pass = node_states[N_CPU];
3099 this_pass = next_pass;
3100 next_pass = NODE_MASK_NONE;
3102 * To avoid cycles in the migration "graph", ensure
3103 * that migration sources are not future targets by
3104 * setting them in 'used_targets'. Do this only
3105 * once per pass so that multiple source nodes can
3106 * share a target node.
3108 * 'used_targets' will become unavailable in future
3109 * passes. This limits some opportunities for
3110 * multiple source nodes to share a destination.
3112 nodes_or(used_targets, used_targets, this_pass);
3113 for_each_node_mask(node, this_pass) {
3114 int target_node = establish_migrate_target(node, &used_targets);
3116 if (target_node == NUMA_NO_NODE)
3120 * Visit targets from this pass in the next pass.
3121 * Eventually, every node will have been part of
3122 * a pass, and will become set in 'used_targets'.
3124 node_set(target_node, next_pass);
3127 * 'next_pass' contains nodes which became migration
3128 * targets in this pass. Make additional passes until
3129 * no more migrations targets are available.
3131 if (!nodes_empty(next_pass))
3136 * For callers that do not hold get_online_mems() already.
3138 static void set_migration_target_nodes(void)
3141 __set_migration_target_nodes();
3146 * This leaves migrate-on-reclaim transiently disabled between
3147 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
3148 * whether reclaim-based migration is enabled or not, which
3149 * ensures that the user can turn reclaim-based migration at
3150 * any time without needing to recalculate migration targets.
3152 * These callbacks already hold get_online_mems(). That is why
3153 * __set_migration_target_nodes() can be used as opposed to
3154 * set_migration_target_nodes().
3156 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
3157 unsigned long action, void *_arg)
3159 struct memory_notify *arg = _arg;
3162 * Only update the node migration order when a node is
3163 * changing status, like online->offline. This avoids
3164 * the overhead of synchronize_rcu() in most cases.
3166 if (arg->status_change_nid < 0)
3167 return notifier_from_errno(0);
3170 case MEM_GOING_OFFLINE:
3172 * Make sure there are not transient states where
3173 * an offline node is a migration target. This
3174 * will leave migration disabled until the offline
3175 * completes and the MEM_OFFLINE case below runs.
3177 disable_all_migrate_targets();
3182 * Recalculate the target nodes once the node
3183 * reaches its final state (online or offline).
3185 __set_migration_target_nodes();
3187 case MEM_CANCEL_OFFLINE:
3189 * MEM_GOING_OFFLINE disabled all the migration
3190 * targets. Reenable them.
3192 __set_migration_target_nodes();
3194 case MEM_GOING_ONLINE:
3195 case MEM_CANCEL_ONLINE:
3199 return notifier_from_errno(0);
3203 * React to hotplug events that might affect the migration targets
3204 * like events that online or offline NUMA nodes.
3206 * The ordering is also currently dependent on which nodes have
3207 * CPUs. That means we need CPU on/offline notification too.
3209 static int migration_online_cpu(unsigned int cpu)
3211 set_migration_target_nodes();
3215 static int migration_offline_cpu(unsigned int cpu)
3217 set_migration_target_nodes();
3221 static int __init migrate_on_reclaim_init(void)
3225 ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3226 NULL, migration_offline_cpu);
3228 * In the unlikely case that this fails, the automatic
3229 * migration targets may become suboptimal for nodes
3230 * where N_CPU changes. With such a small impact in a
3231 * rare case, do not bother trying to do anything special.
3234 ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3235 migration_online_cpu, NULL);
3238 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3241 late_initcall(migrate_on_reclaim_init);
3242 #endif /* CONFIG_HOTPLUG_CPU */
3244 bool numa_demotion_enabled = false;
3247 static ssize_t numa_demotion_enabled_show(struct kobject *kobj,
3248 struct kobj_attribute *attr, char *buf)
3250 return sysfs_emit(buf, "%s\n",
3251 numa_demotion_enabled ? "true" : "false");
3254 static ssize_t numa_demotion_enabled_store(struct kobject *kobj,
3255 struct kobj_attribute *attr,
3256 const char *buf, size_t count)
3258 if (!strncmp(buf, "true", 4) || !strncmp(buf, "1", 1))
3259 numa_demotion_enabled = true;
3260 else if (!strncmp(buf, "false", 5) || !strncmp(buf, "0", 1))
3261 numa_demotion_enabled = false;
3268 static struct kobj_attribute numa_demotion_enabled_attr =
3269 __ATTR(demotion_enabled, 0644, numa_demotion_enabled_show,
3270 numa_demotion_enabled_store);
3272 static struct attribute *numa_attrs[] = {
3273 &numa_demotion_enabled_attr.attr,
3277 static const struct attribute_group numa_attr_group = {
3278 .attrs = numa_attrs,
3281 static int __init numa_init_sysfs(void)
3284 struct kobject *numa_kobj;
3286 numa_kobj = kobject_create_and_add("numa", mm_kobj);
3288 pr_err("failed to create numa kobject\n");
3291 err = sysfs_create_group(numa_kobj, &numa_attr_group);
3293 pr_err("failed to register numa group\n");
3299 kobject_put(numa_kobj);
3302 subsys_initcall(numa_init_sysfs);