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 const struct movable_operations *mops;
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 mops = page_movable_ops(page);
101 VM_BUG_ON_PAGE(!mops, page);
103 if (!mops->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 const struct movable_operations *mops = page_movable_ops(page);
125 mops->putback_page(page);
126 ClearPageIsolated(page);
130 * Put previously isolated pages back onto the appropriate lists
131 * from where they were once taken off for compaction/migration.
133 * This function shall be used whenever the isolated pageset has been
134 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
135 * and isolate_hugetlb().
137 void putback_movable_pages(struct list_head *l)
142 list_for_each_entry_safe(page, page2, l, lru) {
143 if (unlikely(PageHuge(page))) {
144 putback_active_hugepage(page);
147 list_del(&page->lru);
149 * We isolated non-lru movable page so here we can use
150 * __PageMovable because LRU page's mapping cannot have
151 * PAGE_MAPPING_MOVABLE.
153 if (unlikely(__PageMovable(page))) {
154 VM_BUG_ON_PAGE(!PageIsolated(page), page);
156 if (PageMovable(page))
157 putback_movable_page(page);
159 ClearPageIsolated(page);
163 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
164 page_is_file_lru(page), -thp_nr_pages(page));
165 putback_lru_page(page);
171 * Restore a potential migration pte to a working pte entry
173 static bool remove_migration_pte(struct folio *folio,
174 struct vm_area_struct *vma, unsigned long addr, void *old)
176 DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
178 while (page_vma_mapped_walk(&pvmw)) {
179 rmap_t rmap_flags = RMAP_NONE;
183 unsigned long idx = 0;
185 /* pgoff is invalid for ksm pages, but they are never large */
186 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
187 idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
188 new = folio_page(folio, idx);
190 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
191 /* PMD-mapped THP migration entry */
193 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
194 !folio_test_pmd_mappable(folio), folio);
195 remove_migration_pmd(&pvmw, new);
201 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
202 if (pte_swp_soft_dirty(*pvmw.pte))
203 pte = pte_mksoft_dirty(pte);
206 * Recheck VMA as permissions can change since migration started
208 entry = pte_to_swp_entry(*pvmw.pte);
209 if (is_writable_migration_entry(entry))
210 pte = maybe_mkwrite(pte, vma);
211 else if (pte_swp_uffd_wp(*pvmw.pte))
212 pte = pte_mkuffd_wp(pte);
214 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
215 rmap_flags |= RMAP_EXCLUSIVE;
217 if (unlikely(is_device_private_page(new))) {
219 entry = make_writable_device_private_entry(
222 entry = make_readable_device_private_entry(
224 pte = swp_entry_to_pte(entry);
225 if (pte_swp_soft_dirty(*pvmw.pte))
226 pte = pte_swp_mksoft_dirty(pte);
227 if (pte_swp_uffd_wp(*pvmw.pte))
228 pte = pte_swp_mkuffd_wp(pte);
231 #ifdef CONFIG_HUGETLB_PAGE
232 if (folio_test_hugetlb(folio)) {
233 unsigned int shift = huge_page_shift(hstate_vma(vma));
235 pte = pte_mkhuge(pte);
236 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
237 if (folio_test_anon(folio))
238 hugepage_add_anon_rmap(new, vma, pvmw.address,
241 page_dup_file_rmap(new, true);
242 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
246 if (folio_test_anon(folio))
247 page_add_anon_rmap(new, vma, pvmw.address,
250 page_add_file_rmap(new, vma, false);
251 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
253 if (vma->vm_flags & VM_LOCKED)
254 mlock_page_drain_local();
256 trace_remove_migration_pte(pvmw.address, pte_val(pte),
257 compound_order(new));
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 folio *src, struct folio *dst, bool locked)
272 struct rmap_walk_control rwc = {
273 .rmap_one = remove_migration_pte,
278 rmap_walk_locked(dst, &rwc);
280 rmap_walk(dst, &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,
296 if (!is_swap_pte(pte))
299 entry = pte_to_swp_entry(pte);
300 if (!is_migration_entry(entry))
303 migration_entry_wait_on_locked(entry, ptep, ptl);
306 pte_unmap_unlock(ptep, ptl);
309 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
310 unsigned long address)
312 spinlock_t *ptl = pte_lockptr(mm, pmd);
313 pte_t *ptep = pte_offset_map(pmd, address);
314 __migration_entry_wait(mm, ptep, ptl);
317 #ifdef CONFIG_HUGETLB_PAGE
318 void __migration_entry_wait_huge(pte_t *ptep, spinlock_t *ptl)
323 pte = huge_ptep_get(ptep);
325 if (unlikely(!is_hugetlb_entry_migration(pte)))
328 migration_entry_wait_on_locked(pte_to_swp_entry(pte), NULL, ptl);
331 void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *pte)
333 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, pte);
335 __migration_entry_wait_huge(pte, ptl);
339 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
340 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
344 ptl = pmd_lock(mm, pmd);
345 if (!is_pmd_migration_entry(*pmd))
347 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
354 static int folio_expected_refs(struct address_space *mapping,
361 refs += folio_nr_pages(folio);
362 if (folio_test_private(folio))
369 * Replace the page in the mapping.
371 * The number of remaining references must be:
372 * 1 for anonymous pages without a mapping
373 * 2 for pages with a mapping
374 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
376 int folio_migrate_mapping(struct address_space *mapping,
377 struct folio *newfolio, struct folio *folio, int extra_count)
379 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
380 struct zone *oldzone, *newzone;
382 int expected_count = folio_expected_refs(mapping, folio) + extra_count;
383 long nr = folio_nr_pages(folio);
386 /* Anonymous page without mapping */
387 if (folio_ref_count(folio) != expected_count)
390 /* No turning back from here */
391 newfolio->index = folio->index;
392 newfolio->mapping = folio->mapping;
393 if (folio_test_swapbacked(folio))
394 __folio_set_swapbacked(newfolio);
396 return MIGRATEPAGE_SUCCESS;
399 oldzone = folio_zone(folio);
400 newzone = folio_zone(newfolio);
403 if (!folio_ref_freeze(folio, expected_count)) {
404 xas_unlock_irq(&xas);
409 * Now we know that no one else is looking at the folio:
410 * no turning back from here.
412 newfolio->index = folio->index;
413 newfolio->mapping = folio->mapping;
414 folio_ref_add(newfolio, nr); /* add cache reference */
415 if (folio_test_swapbacked(folio)) {
416 __folio_set_swapbacked(newfolio);
417 if (folio_test_swapcache(folio)) {
418 folio_set_swapcache(newfolio);
419 newfolio->private = folio_get_private(folio);
422 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
425 /* Move dirty while page refs frozen and newpage not yet exposed */
426 dirty = folio_test_dirty(folio);
428 folio_clear_dirty(folio);
429 folio_set_dirty(newfolio);
432 xas_store(&xas, newfolio);
435 * Drop cache reference from old page by unfreezing
436 * to one less reference.
437 * We know this isn't the last reference.
439 folio_ref_unfreeze(folio, expected_count - nr);
442 /* Leave irq disabled to prevent preemption while updating stats */
445 * If moved to a different zone then also account
446 * the page for that zone. Other VM counters will be
447 * taken care of when we establish references to the
448 * new page and drop references to the old page.
450 * Note that anonymous pages are accounted for
451 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
452 * are mapped to swap space.
454 if (newzone != oldzone) {
455 struct lruvec *old_lruvec, *new_lruvec;
456 struct mem_cgroup *memcg;
458 memcg = folio_memcg(folio);
459 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
460 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
462 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
463 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
464 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
465 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
466 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
469 if (folio_test_swapcache(folio)) {
470 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
471 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
474 if (dirty && mapping_can_writeback(mapping)) {
475 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
476 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
477 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
478 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
483 return MIGRATEPAGE_SUCCESS;
485 EXPORT_SYMBOL(folio_migrate_mapping);
488 * The expected number of remaining references is the same as that
489 * of folio_migrate_mapping().
491 int migrate_huge_page_move_mapping(struct address_space *mapping,
492 struct folio *dst, struct folio *src)
494 XA_STATE(xas, &mapping->i_pages, folio_index(src));
498 expected_count = 2 + folio_has_private(src);
499 if (!folio_ref_freeze(src, expected_count)) {
500 xas_unlock_irq(&xas);
504 dst->index = src->index;
505 dst->mapping = src->mapping;
509 xas_store(&xas, dst);
511 folio_ref_unfreeze(src, expected_count - 1);
513 xas_unlock_irq(&xas);
515 return MIGRATEPAGE_SUCCESS;
519 * Copy the flags and some other ancillary information
521 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
525 if (folio_test_error(folio))
526 folio_set_error(newfolio);
527 if (folio_test_referenced(folio))
528 folio_set_referenced(newfolio);
529 if (folio_test_uptodate(folio))
530 folio_mark_uptodate(newfolio);
531 if (folio_test_clear_active(folio)) {
532 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
533 folio_set_active(newfolio);
534 } else if (folio_test_clear_unevictable(folio))
535 folio_set_unevictable(newfolio);
536 if (folio_test_workingset(folio))
537 folio_set_workingset(newfolio);
538 if (folio_test_checked(folio))
539 folio_set_checked(newfolio);
541 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
542 * migration entries. We can still have PG_anon_exclusive set on an
543 * effectively unmapped and unreferenced first sub-pages of an
544 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
546 if (folio_test_mappedtodisk(folio))
547 folio_set_mappedtodisk(newfolio);
549 /* Move dirty on pages not done by folio_migrate_mapping() */
550 if (folio_test_dirty(folio))
551 folio_set_dirty(newfolio);
553 if (folio_test_young(folio))
554 folio_set_young(newfolio);
555 if (folio_test_idle(folio))
556 folio_set_idle(newfolio);
559 * Copy NUMA information to the new page, to prevent over-eager
560 * future migrations of this same page.
562 cpupid = page_cpupid_xchg_last(&folio->page, -1);
564 * For memory tiering mode, when migrate between slow and fast
565 * memory node, reset cpupid, because that is used to record
566 * page access time in slow memory node.
568 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
569 bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
570 bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
572 if (f_toptier != t_toptier)
575 page_cpupid_xchg_last(&newfolio->page, cpupid);
577 folio_migrate_ksm(newfolio, folio);
579 * Please do not reorder this without considering how mm/ksm.c's
580 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
582 if (folio_test_swapcache(folio))
583 folio_clear_swapcache(folio);
584 folio_clear_private(folio);
586 /* page->private contains hugetlb specific flags */
587 if (!folio_test_hugetlb(folio))
588 folio->private = NULL;
591 * If any waiters have accumulated on the new page then
594 if (folio_test_writeback(newfolio))
595 folio_end_writeback(newfolio);
598 * PG_readahead shares the same bit with PG_reclaim. The above
599 * end_page_writeback() may clear PG_readahead mistakenly, so set the
602 if (folio_test_readahead(folio))
603 folio_set_readahead(newfolio);
605 folio_copy_owner(newfolio, folio);
607 if (!folio_test_hugetlb(folio))
608 mem_cgroup_migrate(folio, newfolio);
610 EXPORT_SYMBOL(folio_migrate_flags);
612 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
614 folio_copy(newfolio, folio);
615 folio_migrate_flags(newfolio, folio);
617 EXPORT_SYMBOL(folio_migrate_copy);
619 /************************************************************
620 * Migration functions
621 ***********************************************************/
624 * migrate_folio() - Simple folio migration.
625 * @mapping: The address_space containing the folio.
626 * @dst: The folio to migrate the data to.
627 * @src: The folio containing the current data.
628 * @mode: How to migrate the page.
630 * Common logic to directly migrate a single LRU folio suitable for
631 * folios that do not use PagePrivate/PagePrivate2.
633 * Folios are locked upon entry and exit.
635 int migrate_folio(struct address_space *mapping, struct folio *dst,
636 struct folio *src, enum migrate_mode mode)
640 BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
642 rc = folio_migrate_mapping(mapping, dst, src, 0);
644 if (rc != MIGRATEPAGE_SUCCESS)
647 if (mode != MIGRATE_SYNC_NO_COPY)
648 folio_migrate_copy(dst, src);
650 folio_migrate_flags(dst, src);
651 return MIGRATEPAGE_SUCCESS;
653 EXPORT_SYMBOL(migrate_folio);
656 /* Returns true if all buffers are successfully locked */
657 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
658 enum migrate_mode mode)
660 struct buffer_head *bh = head;
662 /* Simple case, sync compaction */
663 if (mode != MIGRATE_ASYNC) {
666 bh = bh->b_this_page;
668 } while (bh != head);
673 /* async case, we cannot block on lock_buffer so use trylock_buffer */
675 if (!trylock_buffer(bh)) {
677 * We failed to lock the buffer and cannot stall in
678 * async migration. Release the taken locks
680 struct buffer_head *failed_bh = bh;
682 while (bh != failed_bh) {
684 bh = bh->b_this_page;
689 bh = bh->b_this_page;
690 } while (bh != head);
694 static int __buffer_migrate_folio(struct address_space *mapping,
695 struct folio *dst, struct folio *src, enum migrate_mode mode,
698 struct buffer_head *bh, *head;
702 head = folio_buffers(src);
704 return migrate_folio(mapping, dst, src, mode);
706 /* Check whether page does not have extra refs before we do more work */
707 expected_count = folio_expected_refs(mapping, src);
708 if (folio_ref_count(src) != expected_count)
711 if (!buffer_migrate_lock_buffers(head, mode))
716 bool invalidated = false;
720 spin_lock(&mapping->private_lock);
723 if (atomic_read(&bh->b_count)) {
727 bh = bh->b_this_page;
728 } while (bh != head);
734 spin_unlock(&mapping->private_lock);
735 invalidate_bh_lrus();
737 goto recheck_buffers;
741 rc = folio_migrate_mapping(mapping, dst, src, 0);
742 if (rc != MIGRATEPAGE_SUCCESS)
745 folio_attach_private(dst, folio_detach_private(src));
749 set_bh_page(bh, &dst->page, bh_offset(bh));
750 bh = bh->b_this_page;
751 } while (bh != head);
753 if (mode != MIGRATE_SYNC_NO_COPY)
754 folio_migrate_copy(dst, src);
756 folio_migrate_flags(dst, src);
758 rc = MIGRATEPAGE_SUCCESS;
761 spin_unlock(&mapping->private_lock);
765 bh = bh->b_this_page;
766 } while (bh != head);
772 * buffer_migrate_folio() - Migration function for folios with buffers.
773 * @mapping: The address space containing @src.
774 * @dst: The folio to migrate to.
775 * @src: The folio to migrate from.
776 * @mode: How to migrate the folio.
778 * This function can only be used if the underlying filesystem guarantees
779 * that no other references to @src exist. For example attached buffer
780 * heads are accessed only under the folio lock. If your filesystem cannot
781 * provide this guarantee, buffer_migrate_folio_norefs() may be more
784 * Return: 0 on success or a negative errno on failure.
786 int buffer_migrate_folio(struct address_space *mapping,
787 struct folio *dst, struct folio *src, enum migrate_mode mode)
789 return __buffer_migrate_folio(mapping, dst, src, mode, false);
791 EXPORT_SYMBOL(buffer_migrate_folio);
794 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
795 * @mapping: The address space containing @src.
796 * @dst: The folio to migrate to.
797 * @src: The folio to migrate from.
798 * @mode: How to migrate the folio.
800 * Like buffer_migrate_folio() except that this variant is more careful
801 * and checks that there are also no buffer head references. This function
802 * is the right one for mappings where buffer heads are directly looked
803 * up and referenced (such as block device mappings).
805 * Return: 0 on success or a negative errno on failure.
807 int buffer_migrate_folio_norefs(struct address_space *mapping,
808 struct folio *dst, struct folio *src, enum migrate_mode mode)
810 return __buffer_migrate_folio(mapping, dst, src, mode, true);
814 int filemap_migrate_folio(struct address_space *mapping,
815 struct folio *dst, struct folio *src, enum migrate_mode mode)
819 ret = folio_migrate_mapping(mapping, dst, src, 0);
820 if (ret != MIGRATEPAGE_SUCCESS)
823 if (folio_get_private(src))
824 folio_attach_private(dst, folio_detach_private(src));
826 if (mode != MIGRATE_SYNC_NO_COPY)
827 folio_migrate_copy(dst, src);
829 folio_migrate_flags(dst, src);
830 return MIGRATEPAGE_SUCCESS;
832 EXPORT_SYMBOL_GPL(filemap_migrate_folio);
835 * Writeback a folio to clean the dirty state
837 static int writeout(struct address_space *mapping, struct folio *folio)
839 struct writeback_control wbc = {
840 .sync_mode = WB_SYNC_NONE,
843 .range_end = LLONG_MAX,
848 if (!mapping->a_ops->writepage)
849 /* No write method for the address space */
852 if (!folio_clear_dirty_for_io(folio))
853 /* Someone else already triggered a write */
857 * A dirty folio may imply that the underlying filesystem has
858 * the folio on some queue. So the folio must be clean for
859 * migration. Writeout may mean we lose the lock and the
860 * folio state is no longer what we checked for earlier.
861 * At this point we know that the migration attempt cannot
864 remove_migration_ptes(folio, folio, false);
866 rc = mapping->a_ops->writepage(&folio->page, &wbc);
868 if (rc != AOP_WRITEPAGE_ACTIVATE)
869 /* unlocked. Relock */
872 return (rc < 0) ? -EIO : -EAGAIN;
876 * Default handling if a filesystem does not provide a migration function.
878 static int fallback_migrate_folio(struct address_space *mapping,
879 struct folio *dst, struct folio *src, enum migrate_mode mode)
881 if (folio_test_dirty(src)) {
882 /* Only writeback folios in full synchronous migration */
885 case MIGRATE_SYNC_NO_COPY:
890 return writeout(mapping, src);
894 * Buffers may be managed in a filesystem specific way.
895 * We must have no buffers or drop them.
897 if (folio_test_private(src) &&
898 !filemap_release_folio(src, GFP_KERNEL))
899 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
901 return migrate_folio(mapping, dst, src, mode);
905 * Move a page to a newly allocated page
906 * The page is locked and all ptes have been successfully removed.
908 * The new page will have replaced the old page if this function
913 * MIGRATEPAGE_SUCCESS - success
915 static int move_to_new_folio(struct folio *dst, struct folio *src,
916 enum migrate_mode mode)
919 bool is_lru = !__PageMovable(&src->page);
921 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
922 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
924 if (likely(is_lru)) {
925 struct address_space *mapping = folio_mapping(src);
928 rc = migrate_folio(mapping, dst, src, mode);
929 else if (mapping->a_ops->migrate_folio)
931 * Most folios have a mapping and most filesystems
932 * provide a migrate_folio callback. Anonymous folios
933 * are part of swap space which also has its own
934 * migrate_folio callback. This is the most common path
935 * for page migration.
937 rc = mapping->a_ops->migrate_folio(mapping, dst, src,
940 rc = fallback_migrate_folio(mapping, dst, src, mode);
942 const struct movable_operations *mops;
945 * In case of non-lru page, it could be released after
946 * isolation step. In that case, we shouldn't try migration.
948 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
949 if (!folio_test_movable(src)) {
950 rc = MIGRATEPAGE_SUCCESS;
951 folio_clear_isolated(src);
955 mops = page_movable_ops(&src->page);
956 rc = mops->migrate_page(&dst->page, &src->page, mode);
957 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
958 !folio_test_isolated(src));
962 * When successful, old pagecache src->mapping must be cleared before
963 * src is freed; but stats require that PageAnon be left as PageAnon.
965 if (rc == MIGRATEPAGE_SUCCESS) {
966 if (__PageMovable(&src->page)) {
967 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
970 * We clear PG_movable under page_lock so any compactor
971 * cannot try to migrate this page.
973 folio_clear_isolated(src);
977 * Anonymous and movable src->mapping will be cleared by
978 * free_pages_prepare so don't reset it here for keeping
979 * the type to work PageAnon, for example.
981 if (!folio_mapping_flags(src))
984 if (likely(!folio_is_zone_device(dst)))
985 flush_dcache_folio(dst);
991 static int __unmap_and_move(struct page *page, struct page *newpage,
992 int force, enum migrate_mode mode)
994 struct folio *folio = page_folio(page);
995 struct folio *dst = page_folio(newpage);
997 bool page_was_mapped = false;
998 struct anon_vma *anon_vma = NULL;
999 bool is_lru = !__PageMovable(page);
1001 if (!trylock_page(page)) {
1002 if (!force || mode == MIGRATE_ASYNC)
1006 * It's not safe for direct compaction to call lock_page.
1007 * For example, during page readahead pages are added locked
1008 * to the LRU. Later, when the IO completes the pages are
1009 * marked uptodate and unlocked. However, the queueing
1010 * could be merging multiple pages for one bio (e.g.
1011 * mpage_readahead). If an allocation happens for the
1012 * second or third page, the process can end up locking
1013 * the same page twice and deadlocking. Rather than
1014 * trying to be clever about what pages can be locked,
1015 * avoid the use of lock_page for direct compaction
1018 if (current->flags & PF_MEMALLOC)
1024 if (PageWriteback(page)) {
1026 * Only in the case of a full synchronous migration is it
1027 * necessary to wait for PageWriteback. In the async case,
1028 * the retry loop is too short and in the sync-light case,
1029 * the overhead of stalling is too much
1033 case MIGRATE_SYNC_NO_COPY:
1041 wait_on_page_writeback(page);
1045 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1046 * we cannot notice that anon_vma is freed while we migrates a page.
1047 * This get_anon_vma() delays freeing anon_vma pointer until the end
1048 * of migration. File cache pages are no problem because of page_lock()
1049 * File Caches may use write_page() or lock_page() in migration, then,
1050 * just care Anon page here.
1052 * Only page_get_anon_vma() understands the subtleties of
1053 * getting a hold on an anon_vma from outside one of its mms.
1054 * But if we cannot get anon_vma, then we won't need it anyway,
1055 * because that implies that the anon page is no longer mapped
1056 * (and cannot be remapped so long as we hold the page lock).
1058 if (PageAnon(page) && !PageKsm(page))
1059 anon_vma = page_get_anon_vma(page);
1062 * Block others from accessing the new page when we get around to
1063 * establishing additional references. We are usually the only one
1064 * holding a reference to newpage at this point. We used to have a BUG
1065 * here if trylock_page(newpage) fails, but would like to allow for
1066 * cases where there might be a race with the previous use of newpage.
1067 * This is much like races on refcount of oldpage: just don't BUG().
1069 if (unlikely(!trylock_page(newpage)))
1072 if (unlikely(!is_lru)) {
1073 rc = move_to_new_folio(dst, folio, mode);
1074 goto out_unlock_both;
1078 * Corner case handling:
1079 * 1. When a new swap-cache page is read into, it is added to the LRU
1080 * and treated as swapcache but it has no rmap yet.
1081 * Calling try_to_unmap() against a page->mapping==NULL page will
1082 * trigger a BUG. So handle it here.
1083 * 2. An orphaned page (see truncate_cleanup_page) might have
1084 * fs-private metadata. The page can be picked up due to memory
1085 * offlining. Everywhere else except page reclaim, the page is
1086 * invisible to the vm, so the page can not be migrated. So try to
1087 * free the metadata, so the page can be freed.
1089 if (!page->mapping) {
1090 VM_BUG_ON_PAGE(PageAnon(page), page);
1091 if (page_has_private(page)) {
1092 try_to_free_buffers(folio);
1093 goto out_unlock_both;
1095 } else if (page_mapped(page)) {
1096 /* Establish migration ptes */
1097 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1099 try_to_migrate(folio, 0);
1100 page_was_mapped = true;
1103 if (!page_mapped(page))
1104 rc = move_to_new_folio(dst, folio, mode);
1107 * When successful, push newpage to LRU immediately: so that if it
1108 * turns out to be an mlocked page, remove_migration_ptes() will
1109 * automatically build up the correct newpage->mlock_count for it.
1111 * We would like to do something similar for the old page, when
1112 * unsuccessful, and other cases when a page has been temporarily
1113 * isolated from the unevictable LRU: but this case is the easiest.
1115 if (rc == MIGRATEPAGE_SUCCESS) {
1116 lru_cache_add(newpage);
1117 if (page_was_mapped)
1121 if (page_was_mapped)
1122 remove_migration_ptes(folio,
1123 rc == MIGRATEPAGE_SUCCESS ? dst : folio, false);
1126 unlock_page(newpage);
1128 /* Drop an anon_vma reference if we took one */
1130 put_anon_vma(anon_vma);
1134 * If migration is successful, decrease refcount of the newpage,
1135 * which will not free the page because new page owner increased
1138 if (rc == MIGRATEPAGE_SUCCESS)
1145 * Obtain the lock on page, remove all ptes and migrate the page
1146 * to the newly allocated page in newpage.
1148 static int unmap_and_move(new_page_t get_new_page,
1149 free_page_t put_new_page,
1150 unsigned long private, struct page *page,
1151 int force, enum migrate_mode mode,
1152 enum migrate_reason reason,
1153 struct list_head *ret)
1155 int rc = MIGRATEPAGE_SUCCESS;
1156 struct page *newpage = NULL;
1158 if (!thp_migration_supported() && PageTransHuge(page))
1161 if (page_count(page) == 1) {
1162 /* Page was freed from under us. So we are done. */
1163 ClearPageActive(page);
1164 ClearPageUnevictable(page);
1165 /* free_pages_prepare() will clear PG_isolated. */
1169 newpage = get_new_page(page, private);
1173 newpage->private = 0;
1174 rc = __unmap_and_move(page, newpage, force, mode);
1175 if (rc == MIGRATEPAGE_SUCCESS)
1176 set_page_owner_migrate_reason(newpage, reason);
1179 if (rc != -EAGAIN) {
1181 * A page that has been migrated has all references
1182 * removed and will be freed. A page that has not been
1183 * migrated will have kept its references and be restored.
1185 list_del(&page->lru);
1189 * If migration is successful, releases reference grabbed during
1190 * isolation. Otherwise, restore the page to right list unless
1193 if (rc == MIGRATEPAGE_SUCCESS) {
1195 * Compaction can migrate also non-LRU pages which are
1196 * not accounted to NR_ISOLATED_*. They can be recognized
1199 if (likely(!__PageMovable(page)))
1200 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1201 page_is_file_lru(page), -thp_nr_pages(page));
1203 if (reason != MR_MEMORY_FAILURE)
1205 * We release the page in page_handle_poison.
1210 list_add_tail(&page->lru, ret);
1213 put_new_page(newpage, private);
1222 * Counterpart of unmap_and_move_page() for hugepage migration.
1224 * This function doesn't wait the completion of hugepage I/O
1225 * because there is no race between I/O and migration for hugepage.
1226 * Note that currently hugepage I/O occurs only in direct I/O
1227 * where no lock is held and PG_writeback is irrelevant,
1228 * and writeback status of all subpages are counted in the reference
1229 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1230 * under direct I/O, the reference of the head page is 512 and a bit more.)
1231 * This means that when we try to migrate hugepage whose subpages are
1232 * doing direct I/O, some references remain after try_to_unmap() and
1233 * hugepage migration fails without data corruption.
1235 * There is also no race when direct I/O is issued on the page under migration,
1236 * because then pte is replaced with migration swap entry and direct I/O code
1237 * will wait in the page fault for migration to complete.
1239 static int unmap_and_move_huge_page(new_page_t get_new_page,
1240 free_page_t put_new_page, unsigned long private,
1241 struct page *hpage, int force,
1242 enum migrate_mode mode, int reason,
1243 struct list_head *ret)
1245 struct folio *dst, *src = page_folio(hpage);
1247 int page_was_mapped = 0;
1248 struct page *new_hpage;
1249 struct anon_vma *anon_vma = NULL;
1250 struct address_space *mapping = NULL;
1253 * Migratability of hugepages depends on architectures and their size.
1254 * This check is necessary because some callers of hugepage migration
1255 * like soft offline and memory hotremove don't walk through page
1256 * tables or check whether the hugepage is pmd-based or not before
1257 * kicking migration.
1259 if (!hugepage_migration_supported(page_hstate(hpage))) {
1260 list_move_tail(&hpage->lru, ret);
1264 if (page_count(hpage) == 1) {
1265 /* page was freed from under us. So we are done. */
1266 putback_active_hugepage(hpage);
1267 return MIGRATEPAGE_SUCCESS;
1270 new_hpage = get_new_page(hpage, private);
1273 dst = page_folio(new_hpage);
1275 if (!trylock_page(hpage)) {
1280 case MIGRATE_SYNC_NO_COPY:
1289 * Check for pages which are in the process of being freed. Without
1290 * page_mapping() set, hugetlbfs specific move page routine will not
1291 * be called and we could leak usage counts for subpools.
1293 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1298 if (PageAnon(hpage))
1299 anon_vma = page_get_anon_vma(hpage);
1301 if (unlikely(!trylock_page(new_hpage)))
1304 if (page_mapped(hpage)) {
1305 enum ttu_flags ttu = 0;
1307 if (!PageAnon(hpage)) {
1309 * In shared mappings, try_to_unmap could potentially
1310 * call huge_pmd_unshare. Because of this, take
1311 * semaphore in write mode here and set TTU_RMAP_LOCKED
1312 * to let lower levels know we have taken the lock.
1314 mapping = hugetlb_page_mapping_lock_write(hpage);
1315 if (unlikely(!mapping))
1316 goto unlock_put_anon;
1318 ttu = TTU_RMAP_LOCKED;
1321 try_to_migrate(src, ttu);
1322 page_was_mapped = 1;
1324 if (ttu & TTU_RMAP_LOCKED)
1325 i_mmap_unlock_write(mapping);
1328 if (!page_mapped(hpage))
1329 rc = move_to_new_folio(dst, src, mode);
1331 if (page_was_mapped)
1332 remove_migration_ptes(src,
1333 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1336 unlock_page(new_hpage);
1340 put_anon_vma(anon_vma);
1342 if (rc == MIGRATEPAGE_SUCCESS) {
1343 move_hugetlb_state(hpage, new_hpage, reason);
1344 put_new_page = NULL;
1350 if (rc == MIGRATEPAGE_SUCCESS)
1351 putback_active_hugepage(hpage);
1352 else if (rc != -EAGAIN)
1353 list_move_tail(&hpage->lru, ret);
1356 * If migration was not successful and there's a freeing callback, use
1357 * it. Otherwise, put_page() will drop the reference grabbed during
1361 put_new_page(new_hpage, private);
1363 putback_active_hugepage(new_hpage);
1368 static inline int try_split_thp(struct page *page, struct page **page2,
1369 struct list_head *from)
1374 rc = split_huge_page_to_list(page, from);
1377 list_safe_reset_next(page, *page2, lru);
1383 * migrate_pages - migrate the pages specified in a list, to the free pages
1384 * supplied as the target for the page migration
1386 * @from: The list of pages to be migrated.
1387 * @get_new_page: The function used to allocate free pages to be used
1388 * as the target of the page migration.
1389 * @put_new_page: The function used to free target pages if migration
1390 * fails, or NULL if no special handling is necessary.
1391 * @private: Private data to be passed on to get_new_page()
1392 * @mode: The migration mode that specifies the constraints for
1393 * page migration, if any.
1394 * @reason: The reason for page migration.
1395 * @ret_succeeded: Set to the number of normal pages migrated successfully if
1396 * the caller passes a non-NULL pointer.
1398 * The function returns after 10 attempts or if no pages are movable any more
1399 * because the list has become empty or no retryable pages exist any more.
1400 * It is caller's responsibility to call putback_movable_pages() to return pages
1401 * to the LRU or free list only if ret != 0.
1403 * Returns the number of {normal page, THP, hugetlb} that were not migrated, or
1404 * an error code. The number of THP splits will be considered as the number of
1405 * non-migrated THP, no matter how many subpages of the THP are migrated successfully.
1407 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1408 free_page_t put_new_page, unsigned long private,
1409 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1414 int nr_failed_pages = 0;
1415 int nr_succeeded = 0;
1416 int nr_thp_succeeded = 0;
1417 int nr_thp_failed = 0;
1418 int nr_thp_split = 0;
1420 bool is_thp = false;
1423 int rc, nr_subpages;
1424 LIST_HEAD(ret_pages);
1425 LIST_HEAD(thp_split_pages);
1426 bool nosplit = (reason == MR_NUMA_MISPLACED);
1427 bool no_subpage_counting = false;
1429 trace_mm_migrate_pages_start(mode, reason);
1431 thp_subpage_migration:
1432 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1436 list_for_each_entry_safe(page, page2, from, lru) {
1439 * THP statistics is based on the source huge page.
1440 * Capture required information that might get lost
1443 is_thp = PageTransHuge(page) && !PageHuge(page);
1444 nr_subpages = compound_nr(page);
1448 rc = unmap_and_move_huge_page(get_new_page,
1449 put_new_page, private, page,
1450 pass > 2, mode, reason,
1453 rc = unmap_and_move(get_new_page, put_new_page,
1454 private, page, pass > 2, mode,
1455 reason, &ret_pages);
1458 * Success: non hugetlb page will be freed, hugetlb
1459 * page will be put back
1460 * -EAGAIN: stay on the from list
1461 * -ENOMEM: stay on the from list
1462 * Other errno: put on ret_pages list then splice to
1467 * THP migration might be unsupported or the
1468 * allocation could've failed so we should
1469 * retry on the same page with the THP split
1472 * Head page is retried immediately and tail
1473 * pages are added to the tail of the list so
1474 * we encounter them after the rest of the list
1478 /* THP migration is unsupported */
1481 if (!try_split_thp(page, &page2, &thp_split_pages)) {
1485 /* Hugetlb migration is unsupported */
1486 } else if (!no_subpage_counting) {
1490 nr_failed_pages += nr_subpages;
1494 * When memory is low, don't bother to try to migrate
1495 * other pages, just exit.
1496 * THP NUMA faulting doesn't split THP to retry.
1498 if (is_thp && !nosplit) {
1500 if (!try_split_thp(page, &page2, &thp_split_pages)) {
1504 } else if (!no_subpage_counting) {
1508 nr_failed_pages += nr_subpages;
1510 * There might be some subpages of fail-to-migrate THPs
1511 * left in thp_split_pages list. Move them back to migration
1512 * list so that they could be put back to the right list by
1513 * the caller otherwise the page refcnt will be leaked.
1515 list_splice_init(&thp_split_pages, from);
1516 nr_thp_failed += thp_retry;
1524 case MIGRATEPAGE_SUCCESS:
1525 nr_succeeded += nr_subpages;
1531 * Permanent failure (-EBUSY, etc.):
1532 * unlike -EAGAIN case, the failed page is
1533 * removed from migration page list and not
1534 * retried in the next outer loop.
1538 else if (!no_subpage_counting)
1541 nr_failed_pages += nr_subpages;
1547 nr_thp_failed += thp_retry;
1549 * Try to migrate subpages of fail-to-migrate THPs, no nr_failed
1550 * counting in this round, since all subpages of a THP is counted
1551 * as 1 failure in the first round.
1553 if (!list_empty(&thp_split_pages)) {
1555 * Move non-migrated pages (after 10 retries) to ret_pages
1556 * to avoid migrating them again.
1558 list_splice_init(from, &ret_pages);
1559 list_splice_init(&thp_split_pages, from);
1560 no_subpage_counting = true;
1562 goto thp_subpage_migration;
1565 rc = nr_failed + nr_thp_failed;
1568 * Put the permanent failure page back to migration list, they
1569 * will be put back to the right list by the caller.
1571 list_splice(&ret_pages, from);
1573 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1574 count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1575 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1576 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1577 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1578 trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1579 nr_thp_failed, nr_thp_split, mode, reason);
1582 *ret_succeeded = nr_succeeded;
1587 struct page *alloc_migration_target(struct page *page, unsigned long private)
1589 struct folio *folio = page_folio(page);
1590 struct migration_target_control *mtc;
1592 unsigned int order = 0;
1593 struct folio *new_folio = NULL;
1597 mtc = (struct migration_target_control *)private;
1598 gfp_mask = mtc->gfp_mask;
1600 if (nid == NUMA_NO_NODE)
1601 nid = folio_nid(folio);
1603 if (folio_test_hugetlb(folio)) {
1604 struct hstate *h = page_hstate(&folio->page);
1606 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1607 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1610 if (folio_test_large(folio)) {
1612 * clear __GFP_RECLAIM to make the migration callback
1613 * consistent with regular THP allocations.
1615 gfp_mask &= ~__GFP_RECLAIM;
1616 gfp_mask |= GFP_TRANSHUGE;
1617 order = folio_order(folio);
1619 zidx = zone_idx(folio_zone(folio));
1620 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1621 gfp_mask |= __GFP_HIGHMEM;
1623 new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
1625 return &new_folio->page;
1630 static int store_status(int __user *status, int start, int value, int nr)
1633 if (put_user(value, status + start))
1641 static int do_move_pages_to_node(struct mm_struct *mm,
1642 struct list_head *pagelist, int node)
1645 struct migration_target_control mtc = {
1647 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1650 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1651 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1653 putback_movable_pages(pagelist);
1658 * Resolves the given address to a struct page, isolates it from the LRU and
1659 * puts it to the given pagelist.
1661 * errno - if the page cannot be found/isolated
1662 * 0 - when it doesn't have to be migrated because it is already on the
1664 * 1 - when it has been queued
1666 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1667 int node, struct list_head *pagelist, bool migrate_all)
1669 struct vm_area_struct *vma;
1675 vma = vma_lookup(mm, addr);
1676 if (!vma || !vma_migratable(vma))
1679 /* FOLL_DUMP to ignore special (like zero) pages */
1680 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1682 err = PTR_ERR(page);
1687 if (!page || is_zone_device_page(page))
1691 if (page_to_nid(page) == node)
1695 if (page_mapcount(page) > 1 && !migrate_all)
1698 if (PageHuge(page)) {
1699 if (PageHead(page)) {
1700 err = isolate_hugetlb(page, pagelist);
1707 head = compound_head(page);
1708 err = isolate_lru_page(head);
1713 list_add_tail(&head->lru, pagelist);
1714 mod_node_page_state(page_pgdat(head),
1715 NR_ISOLATED_ANON + page_is_file_lru(head),
1716 thp_nr_pages(head));
1720 * Either remove the duplicate refcount from
1721 * isolate_lru_page() or drop the page ref if it was
1726 mmap_read_unlock(mm);
1730 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1731 struct list_head *pagelist, int __user *status,
1732 int start, int i, unsigned long nr_pages)
1736 if (list_empty(pagelist))
1739 err = do_move_pages_to_node(mm, pagelist, node);
1742 * Positive err means the number of failed
1743 * pages to migrate. Since we are going to
1744 * abort and return the number of non-migrated
1745 * pages, so need to include the rest of the
1746 * nr_pages that have not been attempted as
1750 err += nr_pages - i - 1;
1753 return store_status(status, start, node, i - start);
1757 * Migrate an array of page address onto an array of nodes and fill
1758 * the corresponding array of status.
1760 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1761 unsigned long nr_pages,
1762 const void __user * __user *pages,
1763 const int __user *nodes,
1764 int __user *status, int flags)
1766 int current_node = NUMA_NO_NODE;
1767 LIST_HEAD(pagelist);
1771 lru_cache_disable();
1773 for (i = start = 0; i < nr_pages; i++) {
1774 const void __user *p;
1779 if (get_user(p, pages + i))
1781 if (get_user(node, nodes + i))
1783 addr = (unsigned long)untagged_addr(p);
1786 if (node < 0 || node >= MAX_NUMNODES)
1788 if (!node_state(node, N_MEMORY))
1792 if (!node_isset(node, task_nodes))
1795 if (current_node == NUMA_NO_NODE) {
1796 current_node = node;
1798 } else if (node != current_node) {
1799 err = move_pages_and_store_status(mm, current_node,
1800 &pagelist, status, start, i, nr_pages);
1804 current_node = node;
1808 * Errors in the page lookup or isolation are not fatal and we simply
1809 * report them via status
1811 err = add_page_for_migration(mm, addr, current_node,
1812 &pagelist, flags & MPOL_MF_MOVE_ALL);
1815 /* The page is successfully queued for migration */
1820 * The move_pages() man page does not have an -EEXIST choice, so
1821 * use -EFAULT instead.
1827 * If the page is already on the target node (!err), store the
1828 * node, otherwise, store the err.
1830 err = store_status(status, i, err ? : current_node, 1);
1834 err = move_pages_and_store_status(mm, current_node, &pagelist,
1835 status, start, i, nr_pages);
1838 current_node = NUMA_NO_NODE;
1841 /* Make sure we do not overwrite the existing error */
1842 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1843 status, start, i, nr_pages);
1852 * Determine the nodes of an array of pages and store it in an array of status.
1854 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1855 const void __user **pages, int *status)
1861 for (i = 0; i < nr_pages; i++) {
1862 unsigned long addr = (unsigned long)(*pages);
1863 unsigned int foll_flags = FOLL_DUMP;
1864 struct vm_area_struct *vma;
1868 vma = vma_lookup(mm, addr);
1872 /* Not all huge page follow APIs support 'FOLL_GET' */
1873 if (!is_vm_hugetlb_page(vma))
1874 foll_flags |= FOLL_GET;
1876 /* FOLL_DUMP to ignore special (like zero) pages */
1877 page = follow_page(vma, addr, foll_flags);
1879 err = PTR_ERR(page);
1883 if (page && !is_zone_device_page(page)) {
1884 err = page_to_nid(page);
1885 if (foll_flags & FOLL_GET)
1897 mmap_read_unlock(mm);
1900 static int get_compat_pages_array(const void __user *chunk_pages[],
1901 const void __user * __user *pages,
1902 unsigned long chunk_nr)
1904 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1908 for (i = 0; i < chunk_nr; i++) {
1909 if (get_user(p, pages32 + i))
1911 chunk_pages[i] = compat_ptr(p);
1918 * Determine the nodes of a user array of pages and store it in
1919 * a user array of status.
1921 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1922 const void __user * __user *pages,
1925 #define DO_PAGES_STAT_CHUNK_NR 16UL
1926 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1927 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1930 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
1932 if (in_compat_syscall()) {
1933 if (get_compat_pages_array(chunk_pages, pages,
1937 if (copy_from_user(chunk_pages, pages,
1938 chunk_nr * sizeof(*chunk_pages)))
1942 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1944 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1949 nr_pages -= chunk_nr;
1951 return nr_pages ? -EFAULT : 0;
1954 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1956 struct task_struct *task;
1957 struct mm_struct *mm;
1960 * There is no need to check if current process has the right to modify
1961 * the specified process when they are same.
1965 *mem_nodes = cpuset_mems_allowed(current);
1969 /* Find the mm_struct */
1971 task = find_task_by_vpid(pid);
1974 return ERR_PTR(-ESRCH);
1976 get_task_struct(task);
1979 * Check if this process has the right to modify the specified
1980 * process. Use the regular "ptrace_may_access()" checks.
1982 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1984 mm = ERR_PTR(-EPERM);
1989 mm = ERR_PTR(security_task_movememory(task));
1992 *mem_nodes = cpuset_mems_allowed(task);
1993 mm = get_task_mm(task);
1995 put_task_struct(task);
1997 mm = ERR_PTR(-EINVAL);
2002 * Move a list of pages in the address space of the currently executing
2005 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2006 const void __user * __user *pages,
2007 const int __user *nodes,
2008 int __user *status, int flags)
2010 struct mm_struct *mm;
2012 nodemask_t task_nodes;
2015 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2018 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2021 mm = find_mm_struct(pid, &task_nodes);
2026 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2027 nodes, status, flags);
2029 err = do_pages_stat(mm, nr_pages, pages, status);
2035 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2036 const void __user * __user *, pages,
2037 const int __user *, nodes,
2038 int __user *, status, int, flags)
2040 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2043 #ifdef CONFIG_NUMA_BALANCING
2045 * Returns true if this is a safe migration target node for misplaced NUMA
2046 * pages. Currently it only checks the watermarks which is crude.
2048 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2049 unsigned long nr_migrate_pages)
2053 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2054 struct zone *zone = pgdat->node_zones + z;
2056 if (!managed_zone(zone))
2059 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2060 if (!zone_watermark_ok(zone, 0,
2061 high_wmark_pages(zone) +
2070 static struct page *alloc_misplaced_dst_page(struct page *page,
2073 int nid = (int) data;
2074 int order = compound_order(page);
2075 gfp_t gfp = __GFP_THISNODE;
2079 gfp |= GFP_TRANSHUGE_LIGHT;
2081 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2083 gfp &= ~__GFP_RECLAIM;
2085 new = __folio_alloc_node(gfp, order, nid);
2090 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2092 int nr_pages = thp_nr_pages(page);
2093 int order = compound_order(page);
2095 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2097 /* Do not migrate THP mapped by multiple processes */
2098 if (PageTransHuge(page) && total_mapcount(page) > 1)
2101 /* Avoid migrating to a node that is nearly full */
2102 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2105 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2107 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2108 if (managed_zone(pgdat->node_zones + z))
2111 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2115 if (isolate_lru_page(page))
2118 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2122 * Isolating the page has taken another reference, so the
2123 * caller's reference can be safely dropped without the page
2124 * disappearing underneath us during migration.
2131 * Attempt to migrate a misplaced page to the specified destination
2132 * node. Caller is expected to have an elevated reference count on
2133 * the page that will be dropped by this function before returning.
2135 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2138 pg_data_t *pgdat = NODE_DATA(node);
2141 unsigned int nr_succeeded;
2142 LIST_HEAD(migratepages);
2143 int nr_pages = thp_nr_pages(page);
2146 * Don't migrate file pages that are mapped in multiple processes
2147 * with execute permissions as they are probably shared libraries.
2149 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2150 (vma->vm_flags & VM_EXEC))
2154 * Also do not migrate dirty pages as not all filesystems can move
2155 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2157 if (page_is_file_lru(page) && PageDirty(page))
2160 isolated = numamigrate_isolate_page(pgdat, page);
2164 list_add(&page->lru, &migratepages);
2165 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2166 NULL, node, MIGRATE_ASYNC,
2167 MR_NUMA_MISPLACED, &nr_succeeded);
2169 if (!list_empty(&migratepages)) {
2170 list_del(&page->lru);
2171 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2172 page_is_file_lru(page), -nr_pages);
2173 putback_lru_page(page);
2178 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2179 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2180 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2183 BUG_ON(!list_empty(&migratepages));
2190 #endif /* CONFIG_NUMA_BALANCING */
2193 * node_demotion[] example:
2195 * Consider a system with two sockets. Each socket has
2196 * three classes of memory attached: fast, medium and slow.
2197 * Each memory class is placed in its own NUMA node. The
2198 * CPUs are placed in the node with the "fast" memory. The
2199 * 6 NUMA nodes (0-5) might be split among the sockets like
2205 * When Node 0 fills up, its memory should be migrated to
2206 * Node 1. When Node 1 fills up, it should be migrated to
2207 * Node 2. The migration path start on the nodes with the
2208 * processors (since allocations default to this node) and
2209 * fast memory, progress through medium and end with the
2212 * 0 -> 1 -> 2 -> stop
2213 * 3 -> 4 -> 5 -> stop
2215 * This is represented in the node_demotion[] like this:
2217 * { nr=1, nodes[0]=1 }, // Node 0 migrates to 1
2218 * { nr=1, nodes[0]=2 }, // Node 1 migrates to 2
2219 * { nr=0, nodes[0]=-1 }, // Node 2 does not migrate
2220 * { nr=1, nodes[0]=4 }, // Node 3 migrates to 4
2221 * { nr=1, nodes[0]=5 }, // Node 4 migrates to 5
2222 * { nr=0, nodes[0]=-1 }, // Node 5 does not migrate
2224 * Moreover some systems may have multiple slow memory nodes.
2225 * Suppose a system has one socket with 3 memory nodes, node 0
2226 * is fast memory type, and node 1/2 both are slow memory
2227 * type, and the distance between fast memory node and slow
2228 * memory node is same. So the migration path should be:
2232 * This is represented in the node_demotion[] like this:
2233 * { nr=2, {nodes[0]=1, nodes[1]=2} }, // Node 0 migrates to node 1 and node 2
2234 * { nr=0, nodes[0]=-1, }, // Node 1 dose not migrate
2235 * { nr=0, nodes[0]=-1, }, // Node 2 does not migrate
2239 * Writes to this array occur without locking. Cycles are
2240 * not allowed: Node X demotes to Y which demotes to X...
2242 * If multiple reads are performed, a single rcu_read_lock()
2243 * must be held over all reads to ensure that no cycles are
2246 #define DEFAULT_DEMOTION_TARGET_NODES 15
2248 #if MAX_NUMNODES < DEFAULT_DEMOTION_TARGET_NODES
2249 #define DEMOTION_TARGET_NODES (MAX_NUMNODES - 1)
2251 #define DEMOTION_TARGET_NODES DEFAULT_DEMOTION_TARGET_NODES
2254 struct demotion_nodes {
2256 short nodes[DEMOTION_TARGET_NODES];
2259 static struct demotion_nodes *node_demotion __read_mostly;
2262 * next_demotion_node() - Get the next node in the demotion path
2263 * @node: The starting node to lookup the next node
2265 * Return: node id for next memory node in the demotion path hierarchy
2266 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
2267 * @node online or guarantee that it *continues* to be the next demotion
2270 int next_demotion_node(int node)
2272 struct demotion_nodes *nd;
2273 unsigned short target_nr, index;
2277 return NUMA_NO_NODE;
2279 nd = &node_demotion[node];
2282 * node_demotion[] is updated without excluding this
2283 * function from running. RCU doesn't provide any
2284 * compiler barriers, so the READ_ONCE() is required
2285 * to avoid compiler reordering or read merging.
2287 * Make sure to use RCU over entire code blocks if
2288 * node_demotion[] reads need to be consistent.
2291 target_nr = READ_ONCE(nd->nr);
2293 switch (target_nr) {
2295 target = NUMA_NO_NODE;
2302 * If there are multiple target nodes, just select one
2303 * target node randomly.
2305 * In addition, we can also use round-robin to select
2306 * target node, but we should introduce another variable
2307 * for node_demotion[] to record last selected target node,
2308 * that may cause cache ping-pong due to the changing of
2309 * last target node. Or introducing per-cpu data to avoid
2310 * caching issue, which seems more complicated. So selecting
2311 * target node randomly seems better until now.
2313 index = get_random_int() % target_nr;
2317 target = READ_ONCE(nd->nodes[index]);
2324 /* Disable reclaim-based migration. */
2325 static void __disable_all_migrate_targets(void)
2332 for_each_online_node(node) {
2333 node_demotion[node].nr = 0;
2334 for (i = 0; i < DEMOTION_TARGET_NODES; i++)
2335 node_demotion[node].nodes[i] = NUMA_NO_NODE;
2339 static void disable_all_migrate_targets(void)
2341 __disable_all_migrate_targets();
2344 * Ensure that the "disable" is visible across the system.
2345 * Readers will see either a combination of before+disable
2346 * state or disable+after. They will never see before and
2347 * after state together.
2349 * The before+after state together might have cycles and
2350 * could cause readers to do things like loop until this
2351 * function finishes. This ensures they can only see a
2352 * single "bad" read and would, for instance, only loop
2359 * Find an automatic demotion target for 'node'.
2360 * Failing here is OK. It might just indicate
2361 * being at the end of a chain.
2363 static int establish_migrate_target(int node, nodemask_t *used,
2366 int migration_target, index, val;
2367 struct demotion_nodes *nd;
2370 return NUMA_NO_NODE;
2372 nd = &node_demotion[node];
2374 migration_target = find_next_best_node(node, used);
2375 if (migration_target == NUMA_NO_NODE)
2376 return NUMA_NO_NODE;
2379 * If the node has been set a migration target node before,
2380 * which means it's the best distance between them. Still
2381 * check if this node can be demoted to other target nodes
2382 * if they have a same best distance.
2384 if (best_distance != -1) {
2385 val = node_distance(node, migration_target);
2386 if (val > best_distance)
2391 if (WARN_ONCE(index >= DEMOTION_TARGET_NODES,
2392 "Exceeds maximum demotion target nodes\n"))
2395 nd->nodes[index] = migration_target;
2398 return migration_target;
2400 node_clear(migration_target, *used);
2401 return NUMA_NO_NODE;
2405 * When memory fills up on a node, memory contents can be
2406 * automatically migrated to another node instead of
2407 * discarded at reclaim.
2409 * Establish a "migration path" which will start at nodes
2410 * with CPUs and will follow the priorities used to build the
2411 * page allocator zonelists.
2413 * The difference here is that cycles must be avoided. If
2414 * node0 migrates to node1, then neither node1, nor anything
2415 * node1 migrates to can migrate to node0. Also one node can
2416 * be migrated to multiple nodes if the target nodes all have
2417 * a same best-distance against the source node.
2419 * This function can run simultaneously with readers of
2420 * node_demotion[]. However, it can not run simultaneously
2421 * with itself. Exclusion is provided by memory hotplug events
2422 * being single-threaded.
2424 static void __set_migration_target_nodes(void)
2426 nodemask_t next_pass;
2427 nodemask_t this_pass;
2428 nodemask_t used_targets = NODE_MASK_NONE;
2429 int node, best_distance;
2432 * Avoid any oddities like cycles that could occur
2433 * from changes in the topology. This will leave
2434 * a momentary gap when migration is disabled.
2436 disable_all_migrate_targets();
2439 * Allocations go close to CPUs, first. Assume that
2440 * the migration path starts at the nodes with CPUs.
2442 next_pass = node_states[N_CPU];
2444 this_pass = next_pass;
2445 next_pass = NODE_MASK_NONE;
2447 * To avoid cycles in the migration "graph", ensure
2448 * that migration sources are not future targets by
2449 * setting them in 'used_targets'. Do this only
2450 * once per pass so that multiple source nodes can
2451 * share a target node.
2453 * 'used_targets' will become unavailable in future
2454 * passes. This limits some opportunities for
2455 * multiple source nodes to share a destination.
2457 nodes_or(used_targets, used_targets, this_pass);
2459 for_each_node_mask(node, this_pass) {
2463 * Try to set up the migration path for the node, and the target
2464 * migration nodes can be multiple, so doing a loop to find all
2465 * the target nodes if they all have a best node distance.
2469 establish_migrate_target(node, &used_targets,
2472 if (target_node == NUMA_NO_NODE)
2475 if (best_distance == -1)
2476 best_distance = node_distance(node, target_node);
2479 * Visit targets from this pass in the next pass.
2480 * Eventually, every node will have been part of
2481 * a pass, and will become set in 'used_targets'.
2483 node_set(target_node, next_pass);
2487 * 'next_pass' contains nodes which became migration
2488 * targets in this pass. Make additional passes until
2489 * no more migrations targets are available.
2491 if (!nodes_empty(next_pass))
2496 * For callers that do not hold get_online_mems() already.
2498 void set_migration_target_nodes(void)
2501 __set_migration_target_nodes();
2506 * This leaves migrate-on-reclaim transiently disabled between
2507 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
2508 * whether reclaim-based migration is enabled or not, which
2509 * ensures that the user can turn reclaim-based migration at
2510 * any time without needing to recalculate migration targets.
2512 * These callbacks already hold get_online_mems(). That is why
2513 * __set_migration_target_nodes() can be used as opposed to
2514 * set_migration_target_nodes().
2516 #ifdef CONFIG_MEMORY_HOTPLUG
2517 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
2518 unsigned long action, void *_arg)
2520 struct memory_notify *arg = _arg;
2523 * Only update the node migration order when a node is
2524 * changing status, like online->offline. This avoids
2525 * the overhead of synchronize_rcu() in most cases.
2527 if (arg->status_change_nid < 0)
2528 return notifier_from_errno(0);
2531 case MEM_GOING_OFFLINE:
2533 * Make sure there are not transient states where
2534 * an offline node is a migration target. This
2535 * will leave migration disabled until the offline
2536 * completes and the MEM_OFFLINE case below runs.
2538 disable_all_migrate_targets();
2543 * Recalculate the target nodes once the node
2544 * reaches its final state (online or offline).
2546 __set_migration_target_nodes();
2548 case MEM_CANCEL_OFFLINE:
2550 * MEM_GOING_OFFLINE disabled all the migration
2551 * targets. Reenable them.
2553 __set_migration_target_nodes();
2555 case MEM_GOING_ONLINE:
2556 case MEM_CANCEL_ONLINE:
2560 return notifier_from_errno(0);
2564 void __init migrate_on_reclaim_init(void)
2566 node_demotion = kcalloc(nr_node_ids,
2567 sizeof(struct demotion_nodes),
2569 WARN_ON(!node_demotion);
2570 #ifdef CONFIG_MEMORY_HOTPLUG
2571 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
2574 * At this point, all numa nodes with memory/CPus have their state
2575 * properly set, so we can build the demotion order now.
2576 * Let us hold the cpu_hotplug lock just, as we could possibily have
2577 * CPU hotplug events during boot.
2580 set_migration_target_nodes();
2584 bool numa_demotion_enabled = false;
2587 static ssize_t numa_demotion_enabled_show(struct kobject *kobj,
2588 struct kobj_attribute *attr, char *buf)
2590 return sysfs_emit(buf, "%s\n",
2591 numa_demotion_enabled ? "true" : "false");
2594 static ssize_t numa_demotion_enabled_store(struct kobject *kobj,
2595 struct kobj_attribute *attr,
2596 const char *buf, size_t count)
2600 ret = kstrtobool(buf, &numa_demotion_enabled);
2607 static struct kobj_attribute numa_demotion_enabled_attr =
2608 __ATTR(demotion_enabled, 0644, numa_demotion_enabled_show,
2609 numa_demotion_enabled_store);
2611 static struct attribute *numa_attrs[] = {
2612 &numa_demotion_enabled_attr.attr,
2616 static const struct attribute_group numa_attr_group = {
2617 .attrs = numa_attrs,
2620 static int __init numa_init_sysfs(void)
2623 struct kobject *numa_kobj;
2625 numa_kobj = kobject_create_and_add("numa", mm_kobj);
2627 pr_err("failed to create numa kobject\n");
2630 err = sysfs_create_group(numa_kobj, &numa_attr_group);
2632 pr_err("failed to register numa group\n");
2638 kobject_put(numa_kobj);
2641 subsys_initcall(numa_init_sysfs);
2642 #endif /* CONFIG_SYSFS */
2643 #endif /* CONFIG_NUMA */