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:
10 * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
11 * Hirokazu Takahashi <taka@valinux.co.jp>
12 * Dave Hansen <haveblue@us.ibm.com>
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/pfn_t.h>
42 #include <linux/memremap.h>
43 #include <linux/userfaultfd_k.h>
44 #include <linux/balloon_compaction.h>
45 #include <linux/page_idle.h>
46 #include <linux/page_owner.h>
47 #include <linux/sched/mm.h>
48 #include <linux/ptrace.h>
49 #include <linux/oom.h>
50 #include <linux/memory.h>
51 #include <linux/random.h>
52 #include <linux/sched/sysctl.h>
54 #include <asm/tlbflush.h>
56 #include <trace/events/migrate.h>
60 int isolate_movable_page(struct page *page, isolate_mode_t mode)
62 struct address_space *mapping;
65 * Avoid burning cycles with pages that are yet under __free_pages(),
66 * or just got freed under us.
68 * In case we 'win' a race for a movable page being freed under us and
69 * raise its refcount preventing __free_pages() from doing its job
70 * the put_page() at the end of this block will take care of
71 * release this page, thus avoiding a nasty leakage.
73 if (unlikely(!get_page_unless_zero(page)))
77 * Check PageMovable before holding a PG_lock because page's owner
78 * assumes anybody doesn't touch PG_lock of newly allocated page
79 * so unconditionally grabbing the lock ruins page's owner side.
81 if (unlikely(!__PageMovable(page)))
84 * As movable pages are not isolated from LRU lists, concurrent
85 * compaction threads can race against page migration functions
86 * as well as race against the releasing a page.
88 * In order to avoid having an already isolated movable page
89 * being (wrongly) re-isolated while it is under migration,
90 * or to avoid attempting to isolate pages being released,
91 * lets be sure we have the page lock
92 * before proceeding with the movable page isolation steps.
94 if (unlikely(!trylock_page(page)))
97 if (!PageMovable(page) || PageIsolated(page))
100 mapping = page_mapping(page);
101 VM_BUG_ON_PAGE(!mapping, page);
103 if (!mapping->a_ops->isolate_page(page, mode))
104 goto out_no_isolated;
106 /* Driver shouldn't use PG_isolated bit of page->flags */
107 WARN_ON_ONCE(PageIsolated(page));
108 SetPageIsolated(page);
121 static void putback_movable_page(struct page *page)
123 struct address_space *mapping;
125 mapping = page_mapping(page);
126 mapping->a_ops->putback_page(page);
127 ClearPageIsolated(page);
131 * Put previously isolated pages back onto the appropriate lists
132 * from where they were once taken off for compaction/migration.
134 * This function shall be used whenever the isolated pageset has been
135 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
136 * and isolate_hugetlb().
138 void putback_movable_pages(struct list_head *l)
143 list_for_each_entry_safe(page, page2, l, lru) {
144 if (unlikely(PageHuge(page))) {
145 putback_active_hugepage(page);
148 list_del(&page->lru);
150 * We isolated non-lru movable page so here we can use
151 * __PageMovable because LRU page's mapping cannot have
152 * PAGE_MAPPING_MOVABLE.
154 if (unlikely(__PageMovable(page))) {
155 VM_BUG_ON_PAGE(!PageIsolated(page), page);
157 if (PageMovable(page))
158 putback_movable_page(page);
160 ClearPageIsolated(page);
164 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
165 page_is_file_lru(page), -thp_nr_pages(page));
166 putback_lru_page(page);
172 * Restore a potential migration pte to a working pte entry
174 static bool remove_migration_pte(struct folio *folio,
175 struct vm_area_struct *vma, unsigned long addr, void *old)
177 DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
179 while (page_vma_mapped_walk(&pvmw)) {
180 rmap_t rmap_flags = RMAP_NONE;
184 unsigned long idx = 0;
186 /* pgoff is invalid for ksm pages, but they are never large */
187 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
188 idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
189 new = folio_page(folio, idx);
191 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
192 /* PMD-mapped THP migration entry */
194 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
195 !folio_test_pmd_mappable(folio), folio);
196 remove_migration_pmd(&pvmw, new);
202 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
203 if (pte_swp_soft_dirty(*pvmw.pte))
204 pte = pte_mksoft_dirty(pte);
207 * Recheck VMA as permissions can change since migration started
209 entry = pte_to_swp_entry(*pvmw.pte);
210 if (is_writable_migration_entry(entry))
211 pte = maybe_mkwrite(pte, vma);
212 else if (pte_swp_uffd_wp(*pvmw.pte))
213 pte = pte_mkuffd_wp(pte);
215 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
216 rmap_flags |= RMAP_EXCLUSIVE;
218 if (unlikely(is_device_private_page(new))) {
220 entry = make_writable_device_private_entry(
223 entry = make_readable_device_private_entry(
225 pte = swp_entry_to_pte(entry);
226 if (pte_swp_soft_dirty(*pvmw.pte))
227 pte = pte_swp_mksoft_dirty(pte);
228 if (pte_swp_uffd_wp(*pvmw.pte))
229 pte = pte_swp_mkuffd_wp(pte);
232 #ifdef CONFIG_HUGETLB_PAGE
233 if (folio_test_hugetlb(folio)) {
234 unsigned int shift = huge_page_shift(hstate_vma(vma));
236 pte = pte_mkhuge(pte);
237 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
238 if (folio_test_anon(folio))
239 hugepage_add_anon_rmap(new, vma, pvmw.address,
242 page_dup_file_rmap(new, true);
243 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
247 if (folio_test_anon(folio))
248 page_add_anon_rmap(new, vma, pvmw.address,
251 page_add_file_rmap(new, vma, false);
252 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
254 if (vma->vm_flags & VM_LOCKED)
255 mlock_page_drain_local();
257 trace_remove_migration_pte(pvmw.address, pte_val(pte),
258 compound_order(new));
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 folio *src, struct folio *dst, bool locked)
273 struct rmap_walk_control rwc = {
274 .rmap_one = remove_migration_pte,
279 rmap_walk_locked(dst, &rwc);
281 rmap_walk(dst, &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,
297 if (!is_swap_pte(pte))
300 entry = pte_to_swp_entry(pte);
301 if (!is_migration_entry(entry))
304 migration_entry_wait_on_locked(entry, ptep, ptl);
307 pte_unmap_unlock(ptep, ptl);
310 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
311 unsigned long address)
313 spinlock_t *ptl = pte_lockptr(mm, pmd);
314 pte_t *ptep = pte_offset_map(pmd, address);
315 __migration_entry_wait(mm, ptep, ptl);
318 #ifdef CONFIG_HUGETLB_PAGE
319 void __migration_entry_wait_huge(pte_t *ptep, spinlock_t *ptl)
324 pte = huge_ptep_get(ptep);
326 if (unlikely(!is_hugetlb_entry_migration(pte)))
329 migration_entry_wait_on_locked(pte_to_swp_entry(pte), NULL, ptl);
332 void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *pte)
334 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, pte);
336 __migration_entry_wait_huge(pte, ptl);
340 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
341 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
345 ptl = pmd_lock(mm, pmd);
346 if (!is_pmd_migration_entry(*pmd))
348 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
355 static int expected_page_refs(struct address_space *mapping, struct page *page)
357 int expected_count = 1;
360 expected_count += compound_nr(page) + page_has_private(page);
361 return expected_count;
365 * Replace the page in the mapping.
367 * The number of remaining references must be:
368 * 1 for anonymous pages without a mapping
369 * 2 for pages with a mapping
370 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
372 int folio_migrate_mapping(struct address_space *mapping,
373 struct folio *newfolio, struct folio *folio, int extra_count)
375 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
376 struct zone *oldzone, *newzone;
378 int expected_count = expected_page_refs(mapping, &folio->page) + extra_count;
379 long nr = folio_nr_pages(folio);
382 /* Anonymous page without mapping */
383 if (folio_ref_count(folio) != expected_count)
386 /* No turning back from here */
387 newfolio->index = folio->index;
388 newfolio->mapping = folio->mapping;
389 if (folio_test_swapbacked(folio))
390 __folio_set_swapbacked(newfolio);
392 return MIGRATEPAGE_SUCCESS;
395 oldzone = folio_zone(folio);
396 newzone = folio_zone(newfolio);
399 if (!folio_ref_freeze(folio, expected_count)) {
400 xas_unlock_irq(&xas);
405 * Now we know that no one else is looking at the folio:
406 * no turning back from here.
408 newfolio->index = folio->index;
409 newfolio->mapping = folio->mapping;
410 folio_ref_add(newfolio, nr); /* add cache reference */
411 if (folio_test_swapbacked(folio)) {
412 __folio_set_swapbacked(newfolio);
413 if (folio_test_swapcache(folio)) {
414 folio_set_swapcache(newfolio);
415 newfolio->private = folio_get_private(folio);
418 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
421 /* Move dirty while page refs frozen and newpage not yet exposed */
422 dirty = folio_test_dirty(folio);
424 folio_clear_dirty(folio);
425 folio_set_dirty(newfolio);
428 xas_store(&xas, newfolio);
431 * Drop cache reference from old page by unfreezing
432 * to one less reference.
433 * We know this isn't the last reference.
435 folio_ref_unfreeze(folio, expected_count - nr);
438 /* Leave irq disabled to prevent preemption while updating stats */
441 * If moved to a different zone then also account
442 * the page for that zone. Other VM counters will be
443 * taken care of when we establish references to the
444 * new page and drop references to the old page.
446 * Note that anonymous pages are accounted for
447 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
448 * are mapped to swap space.
450 if (newzone != oldzone) {
451 struct lruvec *old_lruvec, *new_lruvec;
452 struct mem_cgroup *memcg;
454 memcg = folio_memcg(folio);
455 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
456 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
458 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
459 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
460 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
461 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
462 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
465 if (folio_test_swapcache(folio)) {
466 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
467 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
470 if (dirty && mapping_can_writeback(mapping)) {
471 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
472 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
473 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
474 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
479 return MIGRATEPAGE_SUCCESS;
481 EXPORT_SYMBOL(folio_migrate_mapping);
484 * The expected number of remaining references is the same as that
485 * of folio_migrate_mapping().
487 int migrate_huge_page_move_mapping(struct address_space *mapping,
488 struct page *newpage, struct page *page)
490 XA_STATE(xas, &mapping->i_pages, page_index(page));
494 expected_count = 2 + page_has_private(page);
495 if (!page_ref_freeze(page, expected_count)) {
496 xas_unlock_irq(&xas);
500 newpage->index = page->index;
501 newpage->mapping = page->mapping;
505 xas_store(&xas, newpage);
507 page_ref_unfreeze(page, expected_count - 1);
509 xas_unlock_irq(&xas);
511 return MIGRATEPAGE_SUCCESS;
515 * Copy the flags and some other ancillary information
517 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
521 if (folio_test_error(folio))
522 folio_set_error(newfolio);
523 if (folio_test_referenced(folio))
524 folio_set_referenced(newfolio);
525 if (folio_test_uptodate(folio))
526 folio_mark_uptodate(newfolio);
527 if (folio_test_clear_active(folio)) {
528 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
529 folio_set_active(newfolio);
530 } else if (folio_test_clear_unevictable(folio))
531 folio_set_unevictable(newfolio);
532 if (folio_test_workingset(folio))
533 folio_set_workingset(newfolio);
534 if (folio_test_checked(folio))
535 folio_set_checked(newfolio);
537 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
538 * migration entries. We can still have PG_anon_exclusive set on an
539 * effectively unmapped and unreferenced first sub-pages of an
540 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
542 if (folio_test_mappedtodisk(folio))
543 folio_set_mappedtodisk(newfolio);
545 /* Move dirty on pages not done by folio_migrate_mapping() */
546 if (folio_test_dirty(folio))
547 folio_set_dirty(newfolio);
549 if (folio_test_young(folio))
550 folio_set_young(newfolio);
551 if (folio_test_idle(folio))
552 folio_set_idle(newfolio);
555 * Copy NUMA information to the new page, to prevent over-eager
556 * future migrations of this same page.
558 cpupid = page_cpupid_xchg_last(&folio->page, -1);
559 page_cpupid_xchg_last(&newfolio->page, cpupid);
561 folio_migrate_ksm(newfolio, folio);
563 * Please do not reorder this without considering how mm/ksm.c's
564 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
566 if (folio_test_swapcache(folio))
567 folio_clear_swapcache(folio);
568 folio_clear_private(folio);
570 /* page->private contains hugetlb specific flags */
571 if (!folio_test_hugetlb(folio))
572 folio->private = NULL;
575 * If any waiters have accumulated on the new page then
578 if (folio_test_writeback(newfolio))
579 folio_end_writeback(newfolio);
582 * PG_readahead shares the same bit with PG_reclaim. The above
583 * end_page_writeback() may clear PG_readahead mistakenly, so set the
586 if (folio_test_readahead(folio))
587 folio_set_readahead(newfolio);
589 folio_copy_owner(newfolio, folio);
591 if (!folio_test_hugetlb(folio))
592 mem_cgroup_migrate(folio, newfolio);
594 EXPORT_SYMBOL(folio_migrate_flags);
596 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
598 folio_copy(newfolio, folio);
599 folio_migrate_flags(newfolio, folio);
601 EXPORT_SYMBOL(folio_migrate_copy);
603 /************************************************************
604 * Migration functions
605 ***********************************************************/
608 * Common logic to directly migrate a single LRU page suitable for
609 * pages that do not use PagePrivate/PagePrivate2.
611 * Pages are locked upon entry and exit.
613 int migrate_page(struct address_space *mapping,
614 struct page *newpage, struct page *page,
615 enum migrate_mode mode)
617 struct folio *newfolio = page_folio(newpage);
618 struct folio *folio = page_folio(page);
621 BUG_ON(folio_test_writeback(folio)); /* Writeback must be complete */
623 rc = folio_migrate_mapping(mapping, newfolio, folio, 0);
625 if (rc != MIGRATEPAGE_SUCCESS)
628 if (mode != MIGRATE_SYNC_NO_COPY)
629 folio_migrate_copy(newfolio, folio);
631 folio_migrate_flags(newfolio, folio);
632 return MIGRATEPAGE_SUCCESS;
634 EXPORT_SYMBOL(migrate_page);
637 /* Returns true if all buffers are successfully locked */
638 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
639 enum migrate_mode mode)
641 struct buffer_head *bh = head;
643 /* Simple case, sync compaction */
644 if (mode != MIGRATE_ASYNC) {
647 bh = bh->b_this_page;
649 } while (bh != head);
654 /* async case, we cannot block on lock_buffer so use trylock_buffer */
656 if (!trylock_buffer(bh)) {
658 * We failed to lock the buffer and cannot stall in
659 * async migration. Release the taken locks
661 struct buffer_head *failed_bh = bh;
663 while (bh != failed_bh) {
665 bh = bh->b_this_page;
670 bh = bh->b_this_page;
671 } while (bh != head);
675 static int __buffer_migrate_page(struct address_space *mapping,
676 struct page *newpage, struct page *page, enum migrate_mode mode,
679 struct buffer_head *bh, *head;
683 if (!page_has_buffers(page))
684 return migrate_page(mapping, newpage, page, mode);
686 /* Check whether page does not have extra refs before we do more work */
687 expected_count = expected_page_refs(mapping, page);
688 if (page_count(page) != expected_count)
691 head = page_buffers(page);
692 if (!buffer_migrate_lock_buffers(head, mode))
697 bool invalidated = false;
701 spin_lock(&mapping->private_lock);
704 if (atomic_read(&bh->b_count)) {
708 bh = bh->b_this_page;
709 } while (bh != head);
715 spin_unlock(&mapping->private_lock);
716 invalidate_bh_lrus();
718 goto recheck_buffers;
722 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
723 if (rc != MIGRATEPAGE_SUCCESS)
726 attach_page_private(newpage, detach_page_private(page));
730 set_bh_page(bh, newpage, bh_offset(bh));
731 bh = bh->b_this_page;
733 } while (bh != head);
735 if (mode != MIGRATE_SYNC_NO_COPY)
736 migrate_page_copy(newpage, page);
738 migrate_page_states(newpage, page);
740 rc = MIGRATEPAGE_SUCCESS;
743 spin_unlock(&mapping->private_lock);
747 bh = bh->b_this_page;
749 } while (bh != head);
755 * Migration function for pages with buffers. This function can only be used
756 * if the underlying filesystem guarantees that no other references to "page"
757 * exist. For example attached buffer heads are accessed only under page lock.
759 int buffer_migrate_page(struct address_space *mapping,
760 struct page *newpage, struct page *page, enum migrate_mode mode)
762 return __buffer_migrate_page(mapping, newpage, page, mode, false);
764 EXPORT_SYMBOL(buffer_migrate_page);
767 * Same as above except that this variant is more careful and checks that there
768 * are also no buffer head references. This function is the right one for
769 * mappings where buffer heads are directly looked up and referenced (such as
770 * block device mappings).
772 int buffer_migrate_page_norefs(struct address_space *mapping,
773 struct page *newpage, struct page *page, enum migrate_mode mode)
775 return __buffer_migrate_page(mapping, newpage, page, mode, true);
780 * Writeback a page to clean the dirty state
782 static int writeout(struct address_space *mapping, struct page *page)
784 struct folio *folio = page_folio(page);
785 struct writeback_control wbc = {
786 .sync_mode = WB_SYNC_NONE,
789 .range_end = LLONG_MAX,
794 if (!mapping->a_ops->writepage)
795 /* No write method for the address space */
798 if (!clear_page_dirty_for_io(page))
799 /* Someone else already triggered a write */
803 * A dirty page may imply that the underlying filesystem has
804 * the page on some queue. So the page must be clean for
805 * migration. Writeout may mean we loose the lock and the
806 * page state is no longer what we checked for earlier.
807 * At this point we know that the migration attempt cannot
810 remove_migration_ptes(folio, folio, false);
812 rc = mapping->a_ops->writepage(page, &wbc);
814 if (rc != AOP_WRITEPAGE_ACTIVATE)
815 /* unlocked. Relock */
818 return (rc < 0) ? -EIO : -EAGAIN;
822 * Default handling if a filesystem does not provide a migration function.
824 static int fallback_migrate_page(struct address_space *mapping,
825 struct page *newpage, struct page *page, enum migrate_mode mode)
827 if (PageDirty(page)) {
828 /* Only writeback pages in full synchronous migration */
831 case MIGRATE_SYNC_NO_COPY:
836 return writeout(mapping, page);
840 * Buffers may be managed in a filesystem specific way.
841 * We must have no buffers or drop them.
843 if (page_has_private(page) &&
844 !try_to_release_page(page, GFP_KERNEL))
845 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
847 return migrate_page(mapping, newpage, page, mode);
851 * Move a page to a newly allocated page
852 * The page is locked and all ptes have been successfully removed.
854 * The new page will have replaced the old page if this function
859 * MIGRATEPAGE_SUCCESS - success
861 static int move_to_new_folio(struct folio *dst, struct folio *src,
862 enum migrate_mode mode)
864 struct address_space *mapping;
866 bool is_lru = !__PageMovable(&src->page);
868 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
869 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
871 mapping = folio_mapping(src);
873 if (likely(is_lru)) {
875 rc = migrate_page(mapping, &dst->page, &src->page, mode);
876 else if (mapping->a_ops->migratepage)
878 * Most pages have a mapping and most filesystems
879 * provide a migratepage callback. Anonymous pages
880 * are part of swap space which also has its own
881 * migratepage callback. This is the most common path
882 * for page migration.
884 rc = mapping->a_ops->migratepage(mapping, &dst->page,
887 rc = fallback_migrate_page(mapping, &dst->page,
891 * In case of non-lru page, it could be released after
892 * isolation step. In that case, we shouldn't try migration.
894 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
895 if (!folio_test_movable(src)) {
896 rc = MIGRATEPAGE_SUCCESS;
897 folio_clear_isolated(src);
901 rc = mapping->a_ops->migratepage(mapping, &dst->page,
903 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
904 !folio_test_isolated(src));
908 * When successful, old pagecache src->mapping must be cleared before
909 * src is freed; but stats require that PageAnon be left as PageAnon.
911 if (rc == MIGRATEPAGE_SUCCESS) {
912 if (__PageMovable(&src->page)) {
913 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
916 * We clear PG_movable under page_lock so any compactor
917 * cannot try to migrate this page.
919 folio_clear_isolated(src);
923 * Anonymous and movable src->mapping will be cleared by
924 * free_pages_prepare so don't reset it here for keeping
925 * the type to work PageAnon, for example.
927 if (!folio_mapping_flags(src))
930 if (likely(!folio_is_zone_device(dst)))
931 flush_dcache_folio(dst);
937 static int __unmap_and_move(struct page *page, struct page *newpage,
938 int force, enum migrate_mode mode)
940 struct folio *folio = page_folio(page);
941 struct folio *dst = page_folio(newpage);
943 bool page_was_mapped = false;
944 struct anon_vma *anon_vma = NULL;
945 bool is_lru = !__PageMovable(page);
947 if (!trylock_page(page)) {
948 if (!force || mode == MIGRATE_ASYNC)
952 * It's not safe for direct compaction to call lock_page.
953 * For example, during page readahead pages are added locked
954 * to the LRU. Later, when the IO completes the pages are
955 * marked uptodate and unlocked. However, the queueing
956 * could be merging multiple pages for one bio (e.g.
957 * mpage_readahead). If an allocation happens for the
958 * second or third page, the process can end up locking
959 * the same page twice and deadlocking. Rather than
960 * trying to be clever about what pages can be locked,
961 * avoid the use of lock_page for direct compaction
964 if (current->flags & PF_MEMALLOC)
970 if (PageWriteback(page)) {
972 * Only in the case of a full synchronous migration is it
973 * necessary to wait for PageWriteback. In the async case,
974 * the retry loop is too short and in the sync-light case,
975 * the overhead of stalling is too much
979 case MIGRATE_SYNC_NO_COPY:
987 wait_on_page_writeback(page);
991 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
992 * we cannot notice that anon_vma is freed while we migrates a page.
993 * This get_anon_vma() delays freeing anon_vma pointer until the end
994 * of migration. File cache pages are no problem because of page_lock()
995 * File Caches may use write_page() or lock_page() in migration, then,
996 * just care Anon page here.
998 * Only page_get_anon_vma() understands the subtleties of
999 * getting a hold on an anon_vma from outside one of its mms.
1000 * But if we cannot get anon_vma, then we won't need it anyway,
1001 * because that implies that the anon page is no longer mapped
1002 * (and cannot be remapped so long as we hold the page lock).
1004 if (PageAnon(page) && !PageKsm(page))
1005 anon_vma = page_get_anon_vma(page);
1008 * Block others from accessing the new page when we get around to
1009 * establishing additional references. We are usually the only one
1010 * holding a reference to newpage at this point. We used to have a BUG
1011 * here if trylock_page(newpage) fails, but would like to allow for
1012 * cases where there might be a race with the previous use of newpage.
1013 * This is much like races on refcount of oldpage: just don't BUG().
1015 if (unlikely(!trylock_page(newpage)))
1018 if (unlikely(!is_lru)) {
1019 rc = move_to_new_folio(dst, folio, mode);
1020 goto out_unlock_both;
1024 * Corner case handling:
1025 * 1. When a new swap-cache page is read into, it is added to the LRU
1026 * and treated as swapcache but it has no rmap yet.
1027 * Calling try_to_unmap() against a page->mapping==NULL page will
1028 * trigger a BUG. So handle it here.
1029 * 2. An orphaned page (see truncate_cleanup_page) might have
1030 * fs-private metadata. The page can be picked up due to memory
1031 * offlining. Everywhere else except page reclaim, the page is
1032 * invisible to the vm, so the page can not be migrated. So try to
1033 * free the metadata, so the page can be freed.
1035 if (!page->mapping) {
1036 VM_BUG_ON_PAGE(PageAnon(page), page);
1037 if (page_has_private(page)) {
1038 try_to_free_buffers(folio);
1039 goto out_unlock_both;
1041 } else if (page_mapped(page)) {
1042 /* Establish migration ptes */
1043 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1045 try_to_migrate(folio, 0);
1046 page_was_mapped = true;
1049 if (!page_mapped(page))
1050 rc = move_to_new_folio(dst, folio, mode);
1053 * When successful, push newpage to LRU immediately: so that if it
1054 * turns out to be an mlocked page, remove_migration_ptes() will
1055 * automatically build up the correct newpage->mlock_count for it.
1057 * We would like to do something similar for the old page, when
1058 * unsuccessful, and other cases when a page has been temporarily
1059 * isolated from the unevictable LRU: but this case is the easiest.
1061 if (rc == MIGRATEPAGE_SUCCESS) {
1062 lru_cache_add(newpage);
1063 if (page_was_mapped)
1067 if (page_was_mapped)
1068 remove_migration_ptes(folio,
1069 rc == MIGRATEPAGE_SUCCESS ? dst : folio, false);
1072 unlock_page(newpage);
1074 /* Drop an anon_vma reference if we took one */
1076 put_anon_vma(anon_vma);
1080 * If migration is successful, decrease refcount of the newpage,
1081 * which will not free the page because new page owner increased
1084 if (rc == MIGRATEPAGE_SUCCESS)
1091 * Obtain the lock on page, remove all ptes and migrate the page
1092 * to the newly allocated page in newpage.
1094 static int unmap_and_move(new_page_t get_new_page,
1095 free_page_t put_new_page,
1096 unsigned long private, struct page *page,
1097 int force, enum migrate_mode mode,
1098 enum migrate_reason reason,
1099 struct list_head *ret)
1101 int rc = MIGRATEPAGE_SUCCESS;
1102 struct page *newpage = NULL;
1104 if (!thp_migration_supported() && PageTransHuge(page))
1107 if (page_count(page) == 1) {
1108 /* Page was freed from under us. So we are done. */
1109 ClearPageActive(page);
1110 ClearPageUnevictable(page);
1111 /* free_pages_prepare() will clear PG_isolated. */
1115 newpage = get_new_page(page, private);
1119 newpage->private = 0;
1120 rc = __unmap_and_move(page, newpage, force, mode);
1121 if (rc == MIGRATEPAGE_SUCCESS)
1122 set_page_owner_migrate_reason(newpage, reason);
1125 if (rc != -EAGAIN) {
1127 * A page that has been migrated has all references
1128 * removed and will be freed. A page that has not been
1129 * migrated will have kept its references and be restored.
1131 list_del(&page->lru);
1135 * If migration is successful, releases reference grabbed during
1136 * isolation. Otherwise, restore the page to right list unless
1139 if (rc == MIGRATEPAGE_SUCCESS) {
1141 * Compaction can migrate also non-LRU pages which are
1142 * not accounted to NR_ISOLATED_*. They can be recognized
1145 if (likely(!__PageMovable(page)))
1146 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1147 page_is_file_lru(page), -thp_nr_pages(page));
1149 if (reason != MR_MEMORY_FAILURE)
1151 * We release the page in page_handle_poison.
1156 list_add_tail(&page->lru, ret);
1159 put_new_page(newpage, private);
1168 * Counterpart of unmap_and_move_page() for hugepage migration.
1170 * This function doesn't wait the completion of hugepage I/O
1171 * because there is no race between I/O and migration for hugepage.
1172 * Note that currently hugepage I/O occurs only in direct I/O
1173 * where no lock is held and PG_writeback is irrelevant,
1174 * and writeback status of all subpages are counted in the reference
1175 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1176 * under direct I/O, the reference of the head page is 512 and a bit more.)
1177 * This means that when we try to migrate hugepage whose subpages are
1178 * doing direct I/O, some references remain after try_to_unmap() and
1179 * hugepage migration fails without data corruption.
1181 * There is also no race when direct I/O is issued on the page under migration,
1182 * because then pte is replaced with migration swap entry and direct I/O code
1183 * will wait in the page fault for migration to complete.
1185 static int unmap_and_move_huge_page(new_page_t get_new_page,
1186 free_page_t put_new_page, unsigned long private,
1187 struct page *hpage, int force,
1188 enum migrate_mode mode, int reason,
1189 struct list_head *ret)
1191 struct folio *dst, *src = page_folio(hpage);
1193 int page_was_mapped = 0;
1194 struct page *new_hpage;
1195 struct anon_vma *anon_vma = NULL;
1196 struct address_space *mapping = NULL;
1199 * Migratability of hugepages depends on architectures and their size.
1200 * This check is necessary because some callers of hugepage migration
1201 * like soft offline and memory hotremove don't walk through page
1202 * tables or check whether the hugepage is pmd-based or not before
1203 * kicking migration.
1205 if (!hugepage_migration_supported(page_hstate(hpage))) {
1206 list_move_tail(&hpage->lru, ret);
1210 if (page_count(hpage) == 1) {
1211 /* page was freed from under us. So we are done. */
1212 putback_active_hugepage(hpage);
1213 return MIGRATEPAGE_SUCCESS;
1216 new_hpage = get_new_page(hpage, private);
1219 dst = page_folio(new_hpage);
1221 if (!trylock_page(hpage)) {
1226 case MIGRATE_SYNC_NO_COPY:
1235 * Check for pages which are in the process of being freed. Without
1236 * page_mapping() set, hugetlbfs specific move page routine will not
1237 * be called and we could leak usage counts for subpools.
1239 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1244 if (PageAnon(hpage))
1245 anon_vma = page_get_anon_vma(hpage);
1247 if (unlikely(!trylock_page(new_hpage)))
1250 if (page_mapped(hpage)) {
1251 enum ttu_flags ttu = 0;
1253 if (!PageAnon(hpage)) {
1255 * In shared mappings, try_to_unmap could potentially
1256 * call huge_pmd_unshare. Because of this, take
1257 * semaphore in write mode here and set TTU_RMAP_LOCKED
1258 * to let lower levels know we have taken the lock.
1260 mapping = hugetlb_page_mapping_lock_write(hpage);
1261 if (unlikely(!mapping))
1262 goto unlock_put_anon;
1264 ttu = TTU_RMAP_LOCKED;
1267 try_to_migrate(src, ttu);
1268 page_was_mapped = 1;
1270 if (ttu & TTU_RMAP_LOCKED)
1271 i_mmap_unlock_write(mapping);
1274 if (!page_mapped(hpage))
1275 rc = move_to_new_folio(dst, src, mode);
1277 if (page_was_mapped)
1278 remove_migration_ptes(src,
1279 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1282 unlock_page(new_hpage);
1286 put_anon_vma(anon_vma);
1288 if (rc == MIGRATEPAGE_SUCCESS) {
1289 move_hugetlb_state(hpage, new_hpage, reason);
1290 put_new_page = NULL;
1296 if (rc == MIGRATEPAGE_SUCCESS)
1297 putback_active_hugepage(hpage);
1298 else if (rc != -EAGAIN)
1299 list_move_tail(&hpage->lru, ret);
1302 * If migration was not successful and there's a freeing callback, use
1303 * it. Otherwise, put_page() will drop the reference grabbed during
1307 put_new_page(new_hpage, private);
1309 putback_active_hugepage(new_hpage);
1314 static inline int try_split_thp(struct page *page, struct page **page2,
1315 struct list_head *from)
1320 rc = split_huge_page_to_list(page, from);
1323 list_safe_reset_next(page, *page2, lru);
1329 * migrate_pages - migrate the pages specified in a list, to the free pages
1330 * supplied as the target for the page migration
1332 * @from: The list of pages to be migrated.
1333 * @get_new_page: The function used to allocate free pages to be used
1334 * as the target of the page migration.
1335 * @put_new_page: The function used to free target pages if migration
1336 * fails, or NULL if no special handling is necessary.
1337 * @private: Private data to be passed on to get_new_page()
1338 * @mode: The migration mode that specifies the constraints for
1339 * page migration, if any.
1340 * @reason: The reason for page migration.
1341 * @ret_succeeded: Set to the number of normal pages migrated successfully if
1342 * the caller passes a non-NULL pointer.
1344 * The function returns after 10 attempts or if no pages are movable any more
1345 * because the list has become empty or no retryable pages exist any more.
1346 * It is caller's responsibility to call putback_movable_pages() to return pages
1347 * to the LRU or free list only if ret != 0.
1349 * Returns the number of {normal page, THP, hugetlb} that were not migrated, or
1350 * an error code. The number of THP splits will be considered as the number of
1351 * non-migrated THP, no matter how many subpages of the THP are migrated successfully.
1353 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1354 free_page_t put_new_page, unsigned long private,
1355 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1360 int nr_failed_pages = 0;
1361 int nr_succeeded = 0;
1362 int nr_thp_succeeded = 0;
1363 int nr_thp_failed = 0;
1364 int nr_thp_split = 0;
1366 bool is_thp = false;
1369 int rc, nr_subpages;
1370 LIST_HEAD(ret_pages);
1371 LIST_HEAD(thp_split_pages);
1372 bool nosplit = (reason == MR_NUMA_MISPLACED);
1373 bool no_subpage_counting = false;
1375 trace_mm_migrate_pages_start(mode, reason);
1377 thp_subpage_migration:
1378 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1382 list_for_each_entry_safe(page, page2, from, lru) {
1385 * THP statistics is based on the source huge page.
1386 * Capture required information that might get lost
1389 is_thp = PageTransHuge(page) && !PageHuge(page);
1390 nr_subpages = compound_nr(page);
1394 rc = unmap_and_move_huge_page(get_new_page,
1395 put_new_page, private, page,
1396 pass > 2, mode, reason,
1399 rc = unmap_and_move(get_new_page, put_new_page,
1400 private, page, pass > 2, mode,
1401 reason, &ret_pages);
1404 * Success: non hugetlb page will be freed, hugetlb
1405 * page will be put back
1406 * -EAGAIN: stay on the from list
1407 * -ENOMEM: stay on the from list
1408 * Other errno: put on ret_pages list then splice to
1413 * THP migration might be unsupported or the
1414 * allocation could've failed so we should
1415 * retry on the same page with the THP split
1418 * Head page is retried immediately and tail
1419 * pages are added to the tail of the list so
1420 * we encounter them after the rest of the list
1424 /* THP migration is unsupported */
1427 if (!try_split_thp(page, &page2, &thp_split_pages)) {
1431 /* Hugetlb migration is unsupported */
1432 } else if (!no_subpage_counting) {
1436 nr_failed_pages += nr_subpages;
1440 * When memory is low, don't bother to try to migrate
1441 * other pages, just exit.
1442 * THP NUMA faulting doesn't split THP to retry.
1444 if (is_thp && !nosplit) {
1446 if (!try_split_thp(page, &page2, &thp_split_pages)) {
1450 } else if (!no_subpage_counting) {
1454 nr_failed_pages += nr_subpages;
1456 * There might be some subpages of fail-to-migrate THPs
1457 * left in thp_split_pages list. Move them back to migration
1458 * list so that they could be put back to the right list by
1459 * the caller otherwise the page refcnt will be leaked.
1461 list_splice_init(&thp_split_pages, from);
1462 nr_thp_failed += thp_retry;
1470 case MIGRATEPAGE_SUCCESS:
1471 nr_succeeded += nr_subpages;
1477 * Permanent failure (-EBUSY, etc.):
1478 * unlike -EAGAIN case, the failed page is
1479 * removed from migration page list and not
1480 * retried in the next outer loop.
1484 else if (!no_subpage_counting)
1487 nr_failed_pages += nr_subpages;
1493 nr_thp_failed += thp_retry;
1495 * Try to migrate subpages of fail-to-migrate THPs, no nr_failed
1496 * counting in this round, since all subpages of a THP is counted
1497 * as 1 failure in the first round.
1499 if (!list_empty(&thp_split_pages)) {
1501 * Move non-migrated pages (after 10 retries) to ret_pages
1502 * to avoid migrating them again.
1504 list_splice_init(from, &ret_pages);
1505 list_splice_init(&thp_split_pages, from);
1506 no_subpage_counting = true;
1508 goto thp_subpage_migration;
1511 rc = nr_failed + nr_thp_failed;
1514 * Put the permanent failure page back to migration list, they
1515 * will be put back to the right list by the caller.
1517 list_splice(&ret_pages, from);
1519 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1520 count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1521 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1522 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1523 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1524 trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1525 nr_thp_failed, nr_thp_split, mode, reason);
1528 *ret_succeeded = nr_succeeded;
1533 struct page *alloc_migration_target(struct page *page, unsigned long private)
1535 struct folio *folio = page_folio(page);
1536 struct migration_target_control *mtc;
1538 unsigned int order = 0;
1539 struct folio *new_folio = NULL;
1543 mtc = (struct migration_target_control *)private;
1544 gfp_mask = mtc->gfp_mask;
1546 if (nid == NUMA_NO_NODE)
1547 nid = folio_nid(folio);
1549 if (folio_test_hugetlb(folio)) {
1550 struct hstate *h = page_hstate(&folio->page);
1552 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1553 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1556 if (folio_test_large(folio)) {
1558 * clear __GFP_RECLAIM to make the migration callback
1559 * consistent with regular THP allocations.
1561 gfp_mask &= ~__GFP_RECLAIM;
1562 gfp_mask |= GFP_TRANSHUGE;
1563 order = folio_order(folio);
1565 zidx = zone_idx(folio_zone(folio));
1566 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1567 gfp_mask |= __GFP_HIGHMEM;
1569 new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
1571 return &new_folio->page;
1576 static int store_status(int __user *status, int start, int value, int nr)
1579 if (put_user(value, status + start))
1587 static int do_move_pages_to_node(struct mm_struct *mm,
1588 struct list_head *pagelist, int node)
1591 struct migration_target_control mtc = {
1593 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1596 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1597 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1599 putback_movable_pages(pagelist);
1604 * Resolves the given address to a struct page, isolates it from the LRU and
1605 * puts it to the given pagelist.
1607 * errno - if the page cannot be found/isolated
1608 * 0 - when it doesn't have to be migrated because it is already on the
1610 * 1 - when it has been queued
1612 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1613 int node, struct list_head *pagelist, bool migrate_all)
1615 struct vm_area_struct *vma;
1621 vma = vma_lookup(mm, addr);
1622 if (!vma || !vma_migratable(vma))
1625 /* FOLL_DUMP to ignore special (like zero) pages */
1626 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1628 err = PTR_ERR(page);
1637 if (page_to_nid(page) == node)
1641 if (page_mapcount(page) > 1 && !migrate_all)
1644 if (PageHuge(page)) {
1645 if (PageHead(page)) {
1646 err = isolate_hugetlb(page, pagelist);
1653 head = compound_head(page);
1654 err = isolate_lru_page(head);
1659 list_add_tail(&head->lru, pagelist);
1660 mod_node_page_state(page_pgdat(head),
1661 NR_ISOLATED_ANON + page_is_file_lru(head),
1662 thp_nr_pages(head));
1666 * Either remove the duplicate refcount from
1667 * isolate_lru_page() or drop the page ref if it was
1672 mmap_read_unlock(mm);
1676 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1677 struct list_head *pagelist, int __user *status,
1678 int start, int i, unsigned long nr_pages)
1682 if (list_empty(pagelist))
1685 err = do_move_pages_to_node(mm, pagelist, node);
1688 * Positive err means the number of failed
1689 * pages to migrate. Since we are going to
1690 * abort and return the number of non-migrated
1691 * pages, so need to include the rest of the
1692 * nr_pages that have not been attempted as
1696 err += nr_pages - i - 1;
1699 return store_status(status, start, node, i - start);
1703 * Migrate an array of page address onto an array of nodes and fill
1704 * the corresponding array of status.
1706 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1707 unsigned long nr_pages,
1708 const void __user * __user *pages,
1709 const int __user *nodes,
1710 int __user *status, int flags)
1712 int current_node = NUMA_NO_NODE;
1713 LIST_HEAD(pagelist);
1717 lru_cache_disable();
1719 for (i = start = 0; i < nr_pages; i++) {
1720 const void __user *p;
1725 if (get_user(p, pages + i))
1727 if (get_user(node, nodes + i))
1729 addr = (unsigned long)untagged_addr(p);
1732 if (node < 0 || node >= MAX_NUMNODES)
1734 if (!node_state(node, N_MEMORY))
1738 if (!node_isset(node, task_nodes))
1741 if (current_node == NUMA_NO_NODE) {
1742 current_node = node;
1744 } else if (node != current_node) {
1745 err = move_pages_and_store_status(mm, current_node,
1746 &pagelist, status, start, i, nr_pages);
1750 current_node = node;
1754 * Errors in the page lookup or isolation are not fatal and we simply
1755 * report them via status
1757 err = add_page_for_migration(mm, addr, current_node,
1758 &pagelist, flags & MPOL_MF_MOVE_ALL);
1761 /* The page is successfully queued for migration */
1766 * The move_pages() man page does not have an -EEXIST choice, so
1767 * use -EFAULT instead.
1773 * If the page is already on the target node (!err), store the
1774 * node, otherwise, store the err.
1776 err = store_status(status, i, err ? : current_node, 1);
1780 err = move_pages_and_store_status(mm, current_node, &pagelist,
1781 status, start, i, nr_pages);
1784 current_node = NUMA_NO_NODE;
1787 /* Make sure we do not overwrite the existing error */
1788 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1789 status, start, i, nr_pages);
1798 * Determine the nodes of an array of pages and store it in an array of status.
1800 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1801 const void __user **pages, int *status)
1807 for (i = 0; i < nr_pages; i++) {
1808 unsigned long addr = (unsigned long)(*pages);
1809 struct vm_area_struct *vma;
1813 vma = vma_lookup(mm, addr);
1817 /* FOLL_DUMP to ignore special (like zero) pages */
1818 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1820 err = PTR_ERR(page);
1825 err = page_to_nid(page);
1837 mmap_read_unlock(mm);
1840 static int get_compat_pages_array(const void __user *chunk_pages[],
1841 const void __user * __user *pages,
1842 unsigned long chunk_nr)
1844 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1848 for (i = 0; i < chunk_nr; i++) {
1849 if (get_user(p, pages32 + i))
1851 chunk_pages[i] = compat_ptr(p);
1858 * Determine the nodes of a user array of pages and store it in
1859 * a user array of status.
1861 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1862 const void __user * __user *pages,
1865 #define DO_PAGES_STAT_CHUNK_NR 16UL
1866 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1867 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1870 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
1872 if (in_compat_syscall()) {
1873 if (get_compat_pages_array(chunk_pages, pages,
1877 if (copy_from_user(chunk_pages, pages,
1878 chunk_nr * sizeof(*chunk_pages)))
1882 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1884 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1889 nr_pages -= chunk_nr;
1891 return nr_pages ? -EFAULT : 0;
1894 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1896 struct task_struct *task;
1897 struct mm_struct *mm;
1900 * There is no need to check if current process has the right to modify
1901 * the specified process when they are same.
1905 *mem_nodes = cpuset_mems_allowed(current);
1909 /* Find the mm_struct */
1911 task = find_task_by_vpid(pid);
1914 return ERR_PTR(-ESRCH);
1916 get_task_struct(task);
1919 * Check if this process has the right to modify the specified
1920 * process. Use the regular "ptrace_may_access()" checks.
1922 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1924 mm = ERR_PTR(-EPERM);
1929 mm = ERR_PTR(security_task_movememory(task));
1932 *mem_nodes = cpuset_mems_allowed(task);
1933 mm = get_task_mm(task);
1935 put_task_struct(task);
1937 mm = ERR_PTR(-EINVAL);
1942 * Move a list of pages in the address space of the currently executing
1945 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
1946 const void __user * __user *pages,
1947 const int __user *nodes,
1948 int __user *status, int flags)
1950 struct mm_struct *mm;
1952 nodemask_t task_nodes;
1955 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1958 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1961 mm = find_mm_struct(pid, &task_nodes);
1966 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1967 nodes, status, flags);
1969 err = do_pages_stat(mm, nr_pages, pages, status);
1975 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1976 const void __user * __user *, pages,
1977 const int __user *, nodes,
1978 int __user *, status, int, flags)
1980 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
1983 #ifdef CONFIG_NUMA_BALANCING
1985 * Returns true if this is a safe migration target node for misplaced NUMA
1986 * pages. Currently it only checks the watermarks which is crude.
1988 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1989 unsigned long nr_migrate_pages)
1993 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1994 struct zone *zone = pgdat->node_zones + z;
1996 if (!managed_zone(zone))
1999 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2000 if (!zone_watermark_ok(zone, 0,
2001 high_wmark_pages(zone) +
2010 static struct page *alloc_misplaced_dst_page(struct page *page,
2013 int nid = (int) data;
2014 int order = compound_order(page);
2015 gfp_t gfp = __GFP_THISNODE;
2019 gfp |= GFP_TRANSHUGE_LIGHT;
2021 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2023 gfp &= ~__GFP_RECLAIM;
2025 new = __folio_alloc_node(gfp, order, nid);
2030 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2032 int nr_pages = thp_nr_pages(page);
2033 int order = compound_order(page);
2035 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2037 /* Do not migrate THP mapped by multiple processes */
2038 if (PageTransHuge(page) && total_mapcount(page) > 1)
2041 /* Avoid migrating to a node that is nearly full */
2042 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2045 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2047 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2048 if (managed_zone(pgdat->node_zones + z))
2051 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2055 if (isolate_lru_page(page))
2058 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2062 * Isolating the page has taken another reference, so the
2063 * caller's reference can be safely dropped without the page
2064 * disappearing underneath us during migration.
2071 * Attempt to migrate a misplaced page to the specified destination
2072 * node. Caller is expected to have an elevated reference count on
2073 * the page that will be dropped by this function before returning.
2075 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2078 pg_data_t *pgdat = NODE_DATA(node);
2081 unsigned int nr_succeeded;
2082 LIST_HEAD(migratepages);
2083 int nr_pages = thp_nr_pages(page);
2086 * Don't migrate file pages that are mapped in multiple processes
2087 * with execute permissions as they are probably shared libraries.
2089 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2090 (vma->vm_flags & VM_EXEC))
2094 * Also do not migrate dirty pages as not all filesystems can move
2095 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2097 if (page_is_file_lru(page) && PageDirty(page))
2100 isolated = numamigrate_isolate_page(pgdat, page);
2104 list_add(&page->lru, &migratepages);
2105 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2106 NULL, node, MIGRATE_ASYNC,
2107 MR_NUMA_MISPLACED, &nr_succeeded);
2109 if (!list_empty(&migratepages)) {
2110 list_del(&page->lru);
2111 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2112 page_is_file_lru(page), -nr_pages);
2113 putback_lru_page(page);
2118 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2119 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2120 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2123 BUG_ON(!list_empty(&migratepages));
2130 #endif /* CONFIG_NUMA_BALANCING */
2133 * node_demotion[] example:
2135 * Consider a system with two sockets. Each socket has
2136 * three classes of memory attached: fast, medium and slow.
2137 * Each memory class is placed in its own NUMA node. The
2138 * CPUs are placed in the node with the "fast" memory. The
2139 * 6 NUMA nodes (0-5) might be split among the sockets like
2145 * When Node 0 fills up, its memory should be migrated to
2146 * Node 1. When Node 1 fills up, it should be migrated to
2147 * Node 2. The migration path start on the nodes with the
2148 * processors (since allocations default to this node) and
2149 * fast memory, progress through medium and end with the
2152 * 0 -> 1 -> 2 -> stop
2153 * 3 -> 4 -> 5 -> stop
2155 * This is represented in the node_demotion[] like this:
2157 * { nr=1, nodes[0]=1 }, // Node 0 migrates to 1
2158 * { nr=1, nodes[0]=2 }, // Node 1 migrates to 2
2159 * { nr=0, nodes[0]=-1 }, // Node 2 does not migrate
2160 * { nr=1, nodes[0]=4 }, // Node 3 migrates to 4
2161 * { nr=1, nodes[0]=5 }, // Node 4 migrates to 5
2162 * { nr=0, nodes[0]=-1 }, // Node 5 does not migrate
2164 * Moreover some systems may have multiple slow memory nodes.
2165 * Suppose a system has one socket with 3 memory nodes, node 0
2166 * is fast memory type, and node 1/2 both are slow memory
2167 * type, and the distance between fast memory node and slow
2168 * memory node is same. So the migration path should be:
2172 * This is represented in the node_demotion[] like this:
2173 * { nr=2, {nodes[0]=1, nodes[1]=2} }, // Node 0 migrates to node 1 and node 2
2174 * { nr=0, nodes[0]=-1, }, // Node 1 dose not migrate
2175 * { nr=0, nodes[0]=-1, }, // Node 2 does not migrate
2179 * Writes to this array occur without locking. Cycles are
2180 * not allowed: Node X demotes to Y which demotes to X...
2182 * If multiple reads are performed, a single rcu_read_lock()
2183 * must be held over all reads to ensure that no cycles are
2186 #define DEFAULT_DEMOTION_TARGET_NODES 15
2188 #if MAX_NUMNODES < DEFAULT_DEMOTION_TARGET_NODES
2189 #define DEMOTION_TARGET_NODES (MAX_NUMNODES - 1)
2191 #define DEMOTION_TARGET_NODES DEFAULT_DEMOTION_TARGET_NODES
2194 struct demotion_nodes {
2196 short nodes[DEMOTION_TARGET_NODES];
2199 static struct demotion_nodes *node_demotion __read_mostly;
2202 * next_demotion_node() - Get the next node in the demotion path
2203 * @node: The starting node to lookup the next node
2205 * Return: node id for next memory node in the demotion path hierarchy
2206 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
2207 * @node online or guarantee that it *continues* to be the next demotion
2210 int next_demotion_node(int node)
2212 struct demotion_nodes *nd;
2213 unsigned short target_nr, index;
2217 return NUMA_NO_NODE;
2219 nd = &node_demotion[node];
2222 * node_demotion[] is updated without excluding this
2223 * function from running. RCU doesn't provide any
2224 * compiler barriers, so the READ_ONCE() is required
2225 * to avoid compiler reordering or read merging.
2227 * Make sure to use RCU over entire code blocks if
2228 * node_demotion[] reads need to be consistent.
2231 target_nr = READ_ONCE(nd->nr);
2233 switch (target_nr) {
2235 target = NUMA_NO_NODE;
2242 * If there are multiple target nodes, just select one
2243 * target node randomly.
2245 * In addition, we can also use round-robin to select
2246 * target node, but we should introduce another variable
2247 * for node_demotion[] to record last selected target node,
2248 * that may cause cache ping-pong due to the changing of
2249 * last target node. Or introducing per-cpu data to avoid
2250 * caching issue, which seems more complicated. So selecting
2251 * target node randomly seems better until now.
2253 index = get_random_int() % target_nr;
2257 target = READ_ONCE(nd->nodes[index]);
2264 /* Disable reclaim-based migration. */
2265 static void __disable_all_migrate_targets(void)
2272 for_each_online_node(node) {
2273 node_demotion[node].nr = 0;
2274 for (i = 0; i < DEMOTION_TARGET_NODES; i++)
2275 node_demotion[node].nodes[i] = NUMA_NO_NODE;
2279 static void disable_all_migrate_targets(void)
2281 __disable_all_migrate_targets();
2284 * Ensure that the "disable" is visible across the system.
2285 * Readers will see either a combination of before+disable
2286 * state or disable+after. They will never see before and
2287 * after state together.
2289 * The before+after state together might have cycles and
2290 * could cause readers to do things like loop until this
2291 * function finishes. This ensures they can only see a
2292 * single "bad" read and would, for instance, only loop
2299 * Find an automatic demotion target for 'node'.
2300 * Failing here is OK. It might just indicate
2301 * being at the end of a chain.
2303 static int establish_migrate_target(int node, nodemask_t *used,
2306 int migration_target, index, val;
2307 struct demotion_nodes *nd;
2310 return NUMA_NO_NODE;
2312 nd = &node_demotion[node];
2314 migration_target = find_next_best_node(node, used);
2315 if (migration_target == NUMA_NO_NODE)
2316 return NUMA_NO_NODE;
2319 * If the node has been set a migration target node before,
2320 * which means it's the best distance between them. Still
2321 * check if this node can be demoted to other target nodes
2322 * if they have a same best distance.
2324 if (best_distance != -1) {
2325 val = node_distance(node, migration_target);
2326 if (val > best_distance)
2331 if (WARN_ONCE(index >= DEMOTION_TARGET_NODES,
2332 "Exceeds maximum demotion target nodes\n"))
2335 nd->nodes[index] = migration_target;
2338 return migration_target;
2340 node_clear(migration_target, *used);
2341 return NUMA_NO_NODE;
2345 * When memory fills up on a node, memory contents can be
2346 * automatically migrated to another node instead of
2347 * discarded at reclaim.
2349 * Establish a "migration path" which will start at nodes
2350 * with CPUs and will follow the priorities used to build the
2351 * page allocator zonelists.
2353 * The difference here is that cycles must be avoided. If
2354 * node0 migrates to node1, then neither node1, nor anything
2355 * node1 migrates to can migrate to node0. Also one node can
2356 * be migrated to multiple nodes if the target nodes all have
2357 * a same best-distance against the source node.
2359 * This function can run simultaneously with readers of
2360 * node_demotion[]. However, it can not run simultaneously
2361 * with itself. Exclusion is provided by memory hotplug events
2362 * being single-threaded.
2364 static void __set_migration_target_nodes(void)
2366 nodemask_t next_pass;
2367 nodemask_t this_pass;
2368 nodemask_t used_targets = NODE_MASK_NONE;
2369 int node, best_distance;
2372 * Avoid any oddities like cycles that could occur
2373 * from changes in the topology. This will leave
2374 * a momentary gap when migration is disabled.
2376 disable_all_migrate_targets();
2379 * Allocations go close to CPUs, first. Assume that
2380 * the migration path starts at the nodes with CPUs.
2382 next_pass = node_states[N_CPU];
2384 this_pass = next_pass;
2385 next_pass = NODE_MASK_NONE;
2387 * To avoid cycles in the migration "graph", ensure
2388 * that migration sources are not future targets by
2389 * setting them in 'used_targets'. Do this only
2390 * once per pass so that multiple source nodes can
2391 * share a target node.
2393 * 'used_targets' will become unavailable in future
2394 * passes. This limits some opportunities for
2395 * multiple source nodes to share a destination.
2397 nodes_or(used_targets, used_targets, this_pass);
2399 for_each_node_mask(node, this_pass) {
2403 * Try to set up the migration path for the node, and the target
2404 * migration nodes can be multiple, so doing a loop to find all
2405 * the target nodes if they all have a best node distance.
2409 establish_migrate_target(node, &used_targets,
2412 if (target_node == NUMA_NO_NODE)
2415 if (best_distance == -1)
2416 best_distance = node_distance(node, target_node);
2419 * Visit targets from this pass in the next pass.
2420 * Eventually, every node will have been part of
2421 * a pass, and will become set in 'used_targets'.
2423 node_set(target_node, next_pass);
2427 * 'next_pass' contains nodes which became migration
2428 * targets in this pass. Make additional passes until
2429 * no more migrations targets are available.
2431 if (!nodes_empty(next_pass))
2436 * For callers that do not hold get_online_mems() already.
2438 void set_migration_target_nodes(void)
2441 __set_migration_target_nodes();
2446 * This leaves migrate-on-reclaim transiently disabled between
2447 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
2448 * whether reclaim-based migration is enabled or not, which
2449 * ensures that the user can turn reclaim-based migration at
2450 * any time without needing to recalculate migration targets.
2452 * These callbacks already hold get_online_mems(). That is why
2453 * __set_migration_target_nodes() can be used as opposed to
2454 * set_migration_target_nodes().
2456 #ifdef CONFIG_MEMORY_HOTPLUG
2457 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
2458 unsigned long action, void *_arg)
2460 struct memory_notify *arg = _arg;
2463 * Only update the node migration order when a node is
2464 * changing status, like online->offline. This avoids
2465 * the overhead of synchronize_rcu() in most cases.
2467 if (arg->status_change_nid < 0)
2468 return notifier_from_errno(0);
2471 case MEM_GOING_OFFLINE:
2473 * Make sure there are not transient states where
2474 * an offline node is a migration target. This
2475 * will leave migration disabled until the offline
2476 * completes and the MEM_OFFLINE case below runs.
2478 disable_all_migrate_targets();
2483 * Recalculate the target nodes once the node
2484 * reaches its final state (online or offline).
2486 __set_migration_target_nodes();
2488 case MEM_CANCEL_OFFLINE:
2490 * MEM_GOING_OFFLINE disabled all the migration
2491 * targets. Reenable them.
2493 __set_migration_target_nodes();
2495 case MEM_GOING_ONLINE:
2496 case MEM_CANCEL_ONLINE:
2500 return notifier_from_errno(0);
2504 void __init migrate_on_reclaim_init(void)
2506 node_demotion = kcalloc(nr_node_ids,
2507 sizeof(struct demotion_nodes),
2509 WARN_ON(!node_demotion);
2510 #ifdef CONFIG_MEMORY_HOTPLUG
2511 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
2514 * At this point, all numa nodes with memory/CPus have their state
2515 * properly set, so we can build the demotion order now.
2516 * Let us hold the cpu_hotplug lock just, as we could possibily have
2517 * CPU hotplug events during boot.
2520 set_migration_target_nodes();
2524 bool numa_demotion_enabled = false;
2527 static ssize_t numa_demotion_enabled_show(struct kobject *kobj,
2528 struct kobj_attribute *attr, char *buf)
2530 return sysfs_emit(buf, "%s\n",
2531 numa_demotion_enabled ? "true" : "false");
2534 static ssize_t numa_demotion_enabled_store(struct kobject *kobj,
2535 struct kobj_attribute *attr,
2536 const char *buf, size_t count)
2540 ret = kstrtobool(buf, &numa_demotion_enabled);
2547 static struct kobj_attribute numa_demotion_enabled_attr =
2548 __ATTR(demotion_enabled, 0644, numa_demotion_enabled_show,
2549 numa_demotion_enabled_store);
2551 static struct attribute *numa_attrs[] = {
2552 &numa_demotion_enabled_attr.attr,
2556 static const struct attribute_group numa_attr_group = {
2557 .attrs = numa_attrs,
2560 static int __init numa_init_sysfs(void)
2563 struct kobject *numa_kobj;
2565 numa_kobj = kobject_create_and_add("numa", mm_kobj);
2567 pr_err("failed to create numa kobject\n");
2570 err = sysfs_create_group(numa_kobj, &numa_attr_group);
2572 pr_err("failed to register numa group\n");
2578 kobject_put(numa_kobj);
2581 subsys_initcall(numa_init_sysfs);
2582 #endif /* CONFIG_SYSFS */
2583 #endif /* CONFIG_NUMA */