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>
53 #include <linux/memory-tiers.h>
55 #include <asm/tlbflush.h>
57 #include <trace/events/migrate.h>
61 int isolate_movable_page(struct page *page, isolate_mode_t mode)
63 const struct movable_operations *mops;
66 * Avoid burning cycles with pages that are yet under __free_pages(),
67 * or just got freed under us.
69 * In case we 'win' a race for a movable page being freed under us and
70 * raise its refcount preventing __free_pages() from doing its job
71 * the put_page() at the end of this block will take care of
72 * release this page, thus avoiding a nasty leakage.
74 if (unlikely(!get_page_unless_zero(page)))
78 * Check PageMovable before holding a PG_lock because page's owner
79 * assumes anybody doesn't touch PG_lock of newly allocated page
80 * so unconditionally grabbing the lock ruins page's owner side.
82 if (unlikely(!__PageMovable(page)))
85 * As movable pages are not isolated from LRU lists, concurrent
86 * compaction threads can race against page migration functions
87 * as well as race against the releasing a page.
89 * In order to avoid having an already isolated movable page
90 * being (wrongly) re-isolated while it is under migration,
91 * or to avoid attempting to isolate pages being released,
92 * lets be sure we have the page lock
93 * before proceeding with the movable page isolation steps.
95 if (unlikely(!trylock_page(page)))
98 if (!PageMovable(page) || PageIsolated(page))
101 mops = page_movable_ops(page);
102 VM_BUG_ON_PAGE(!mops, page);
104 if (!mops->isolate_page(page, mode))
105 goto out_no_isolated;
107 /* Driver shouldn't use PG_isolated bit of page->flags */
108 WARN_ON_ONCE(PageIsolated(page));
109 SetPageIsolated(page);
122 static void putback_movable_page(struct page *page)
124 const struct movable_operations *mops = page_movable_ops(page);
126 mops->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 = 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_migration_entry_young(entry))
211 pte = pte_mkold(pte);
212 if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
213 pte = pte_mkdirty(pte);
214 if (is_writable_migration_entry(entry))
215 pte = maybe_mkwrite(pte, vma);
216 else if (pte_swp_uffd_wp(*pvmw.pte))
217 pte = pte_mkuffd_wp(pte);
219 pte = pte_wrprotect(pte);
221 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
222 rmap_flags |= RMAP_EXCLUSIVE;
224 if (unlikely(is_device_private_page(new))) {
226 entry = make_writable_device_private_entry(
229 entry = make_readable_device_private_entry(
231 pte = swp_entry_to_pte(entry);
232 if (pte_swp_soft_dirty(*pvmw.pte))
233 pte = pte_swp_mksoft_dirty(pte);
234 if (pte_swp_uffd_wp(*pvmw.pte))
235 pte = pte_swp_mkuffd_wp(pte);
238 #ifdef CONFIG_HUGETLB_PAGE
239 if (folio_test_hugetlb(folio)) {
240 unsigned int shift = huge_page_shift(hstate_vma(vma));
242 pte = pte_mkhuge(pte);
243 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
244 if (folio_test_anon(folio))
245 hugepage_add_anon_rmap(new, vma, pvmw.address,
248 page_dup_file_rmap(new, true);
249 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
253 if (folio_test_anon(folio))
254 page_add_anon_rmap(new, vma, pvmw.address,
257 page_add_file_rmap(new, vma, false);
258 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
260 if (vma->vm_flags & VM_LOCKED)
261 mlock_page_drain_local();
263 trace_remove_migration_pte(pvmw.address, pte_val(pte),
264 compound_order(new));
266 /* No need to invalidate - it was non-present before */
267 update_mmu_cache(vma, pvmw.address, pvmw.pte);
274 * Get rid of all migration entries and replace them by
275 * references to the indicated page.
277 void remove_migration_ptes(struct folio *src, struct folio *dst, bool locked)
279 struct rmap_walk_control rwc = {
280 .rmap_one = remove_migration_pte,
285 rmap_walk_locked(dst, &rwc);
287 rmap_walk(dst, &rwc);
291 * Something used the pte of a page under migration. We need to
292 * get to the page and wait until migration is finished.
293 * When we return from this function the fault will be retried.
295 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
303 if (!is_swap_pte(pte))
306 entry = pte_to_swp_entry(pte);
307 if (!is_migration_entry(entry))
310 migration_entry_wait_on_locked(entry, ptep, ptl);
313 pte_unmap_unlock(ptep, ptl);
316 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
317 unsigned long address)
319 spinlock_t *ptl = pte_lockptr(mm, pmd);
320 pte_t *ptep = pte_offset_map(pmd, address);
321 __migration_entry_wait(mm, ptep, ptl);
324 #ifdef CONFIG_HUGETLB_PAGE
325 void __migration_entry_wait_huge(pte_t *ptep, spinlock_t *ptl)
330 pte = huge_ptep_get(ptep);
332 if (unlikely(!is_hugetlb_entry_migration(pte)))
335 migration_entry_wait_on_locked(pte_to_swp_entry(pte), NULL, ptl);
338 void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *pte)
340 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, pte);
342 __migration_entry_wait_huge(pte, ptl);
346 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
347 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
351 ptl = pmd_lock(mm, pmd);
352 if (!is_pmd_migration_entry(*pmd))
354 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
361 static int folio_expected_refs(struct address_space *mapping,
368 refs += folio_nr_pages(folio);
369 if (folio_test_private(folio))
376 * Replace the page in the mapping.
378 * The number of remaining references must be:
379 * 1 for anonymous pages without a mapping
380 * 2 for pages with a mapping
381 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
383 int folio_migrate_mapping(struct address_space *mapping,
384 struct folio *newfolio, struct folio *folio, int extra_count)
386 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
387 struct zone *oldzone, *newzone;
389 int expected_count = folio_expected_refs(mapping, folio) + extra_count;
390 long nr = folio_nr_pages(folio);
393 /* Anonymous page without mapping */
394 if (folio_ref_count(folio) != expected_count)
397 /* No turning back from here */
398 newfolio->index = folio->index;
399 newfolio->mapping = folio->mapping;
400 if (folio_test_swapbacked(folio))
401 __folio_set_swapbacked(newfolio);
403 return MIGRATEPAGE_SUCCESS;
406 oldzone = folio_zone(folio);
407 newzone = folio_zone(newfolio);
410 if (!folio_ref_freeze(folio, expected_count)) {
411 xas_unlock_irq(&xas);
416 * Now we know that no one else is looking at the folio:
417 * no turning back from here.
419 newfolio->index = folio->index;
420 newfolio->mapping = folio->mapping;
421 folio_ref_add(newfolio, nr); /* add cache reference */
422 if (folio_test_swapbacked(folio)) {
423 __folio_set_swapbacked(newfolio);
424 if (folio_test_swapcache(folio)) {
425 folio_set_swapcache(newfolio);
426 newfolio->private = folio_get_private(folio);
429 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
432 /* Move dirty while page refs frozen and newpage not yet exposed */
433 dirty = folio_test_dirty(folio);
435 folio_clear_dirty(folio);
436 folio_set_dirty(newfolio);
439 xas_store(&xas, newfolio);
442 * Drop cache reference from old page by unfreezing
443 * to one less reference.
444 * We know this isn't the last reference.
446 folio_ref_unfreeze(folio, expected_count - nr);
449 /* Leave irq disabled to prevent preemption while updating stats */
452 * If moved to a different zone then also account
453 * the page for that zone. Other VM counters will be
454 * taken care of when we establish references to the
455 * new page and drop references to the old page.
457 * Note that anonymous pages are accounted for
458 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
459 * are mapped to swap space.
461 if (newzone != oldzone) {
462 struct lruvec *old_lruvec, *new_lruvec;
463 struct mem_cgroup *memcg;
465 memcg = folio_memcg(folio);
466 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
467 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
469 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
470 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
471 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
472 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
473 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
476 if (folio_test_swapcache(folio)) {
477 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
478 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
481 if (dirty && mapping_can_writeback(mapping)) {
482 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
483 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
484 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
485 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
490 return MIGRATEPAGE_SUCCESS;
492 EXPORT_SYMBOL(folio_migrate_mapping);
495 * The expected number of remaining references is the same as that
496 * of folio_migrate_mapping().
498 int migrate_huge_page_move_mapping(struct address_space *mapping,
499 struct folio *dst, struct folio *src)
501 XA_STATE(xas, &mapping->i_pages, folio_index(src));
505 expected_count = 2 + folio_has_private(src);
506 if (!folio_ref_freeze(src, expected_count)) {
507 xas_unlock_irq(&xas);
511 dst->index = src->index;
512 dst->mapping = src->mapping;
516 xas_store(&xas, dst);
518 folio_ref_unfreeze(src, expected_count - 1);
520 xas_unlock_irq(&xas);
522 return MIGRATEPAGE_SUCCESS;
526 * Copy the flags and some other ancillary information
528 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
532 if (folio_test_error(folio))
533 folio_set_error(newfolio);
534 if (folio_test_referenced(folio))
535 folio_set_referenced(newfolio);
536 if (folio_test_uptodate(folio))
537 folio_mark_uptodate(newfolio);
538 if (folio_test_clear_active(folio)) {
539 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
540 folio_set_active(newfolio);
541 } else if (folio_test_clear_unevictable(folio))
542 folio_set_unevictable(newfolio);
543 if (folio_test_workingset(folio))
544 folio_set_workingset(newfolio);
545 if (folio_test_checked(folio))
546 folio_set_checked(newfolio);
548 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
549 * migration entries. We can still have PG_anon_exclusive set on an
550 * effectively unmapped and unreferenced first sub-pages of an
551 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
553 if (folio_test_mappedtodisk(folio))
554 folio_set_mappedtodisk(newfolio);
556 /* Move dirty on pages not done by folio_migrate_mapping() */
557 if (folio_test_dirty(folio))
558 folio_set_dirty(newfolio);
560 if (folio_test_young(folio))
561 folio_set_young(newfolio);
562 if (folio_test_idle(folio))
563 folio_set_idle(newfolio);
566 * Copy NUMA information to the new page, to prevent over-eager
567 * future migrations of this same page.
569 cpupid = page_cpupid_xchg_last(&folio->page, -1);
571 * For memory tiering mode, when migrate between slow and fast
572 * memory node, reset cpupid, because that is used to record
573 * page access time in slow memory node.
575 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
576 bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
577 bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
579 if (f_toptier != t_toptier)
582 page_cpupid_xchg_last(&newfolio->page, cpupid);
584 folio_migrate_ksm(newfolio, folio);
586 * Please do not reorder this without considering how mm/ksm.c's
587 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
589 if (folio_test_swapcache(folio))
590 folio_clear_swapcache(folio);
591 folio_clear_private(folio);
593 /* page->private contains hugetlb specific flags */
594 if (!folio_test_hugetlb(folio))
595 folio->private = NULL;
598 * If any waiters have accumulated on the new page then
601 if (folio_test_writeback(newfolio))
602 folio_end_writeback(newfolio);
605 * PG_readahead shares the same bit with PG_reclaim. The above
606 * end_page_writeback() may clear PG_readahead mistakenly, so set the
609 if (folio_test_readahead(folio))
610 folio_set_readahead(newfolio);
612 folio_copy_owner(newfolio, folio);
614 if (!folio_test_hugetlb(folio))
615 mem_cgroup_migrate(folio, newfolio);
617 EXPORT_SYMBOL(folio_migrate_flags);
619 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
621 folio_copy(newfolio, folio);
622 folio_migrate_flags(newfolio, folio);
624 EXPORT_SYMBOL(folio_migrate_copy);
626 /************************************************************
627 * Migration functions
628 ***********************************************************/
630 int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
631 struct folio *src, enum migrate_mode mode, int extra_count)
635 BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
637 rc = folio_migrate_mapping(mapping, dst, src, extra_count);
639 if (rc != MIGRATEPAGE_SUCCESS)
642 if (mode != MIGRATE_SYNC_NO_COPY)
643 folio_migrate_copy(dst, src);
645 folio_migrate_flags(dst, src);
646 return MIGRATEPAGE_SUCCESS;
650 * migrate_folio() - Simple folio migration.
651 * @mapping: The address_space containing the folio.
652 * @dst: The folio to migrate the data to.
653 * @src: The folio containing the current data.
654 * @mode: How to migrate the page.
656 * Common logic to directly migrate a single LRU folio suitable for
657 * folios that do not use PagePrivate/PagePrivate2.
659 * Folios are locked upon entry and exit.
661 int migrate_folio(struct address_space *mapping, struct folio *dst,
662 struct folio *src, enum migrate_mode mode)
664 return migrate_folio_extra(mapping, dst, src, mode, 0);
666 EXPORT_SYMBOL(migrate_folio);
669 /* Returns true if all buffers are successfully locked */
670 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
671 enum migrate_mode mode)
673 struct buffer_head *bh = head;
675 /* Simple case, sync compaction */
676 if (mode != MIGRATE_ASYNC) {
679 bh = bh->b_this_page;
681 } while (bh != head);
686 /* async case, we cannot block on lock_buffer so use trylock_buffer */
688 if (!trylock_buffer(bh)) {
690 * We failed to lock the buffer and cannot stall in
691 * async migration. Release the taken locks
693 struct buffer_head *failed_bh = bh;
695 while (bh != failed_bh) {
697 bh = bh->b_this_page;
702 bh = bh->b_this_page;
703 } while (bh != head);
707 static int __buffer_migrate_folio(struct address_space *mapping,
708 struct folio *dst, struct folio *src, enum migrate_mode mode,
711 struct buffer_head *bh, *head;
715 head = folio_buffers(src);
717 return migrate_folio(mapping, dst, src, mode);
719 /* Check whether page does not have extra refs before we do more work */
720 expected_count = folio_expected_refs(mapping, src);
721 if (folio_ref_count(src) != expected_count)
724 if (!buffer_migrate_lock_buffers(head, mode))
729 bool invalidated = false;
733 spin_lock(&mapping->private_lock);
736 if (atomic_read(&bh->b_count)) {
740 bh = bh->b_this_page;
741 } while (bh != head);
747 spin_unlock(&mapping->private_lock);
748 invalidate_bh_lrus();
750 goto recheck_buffers;
754 rc = folio_migrate_mapping(mapping, dst, src, 0);
755 if (rc != MIGRATEPAGE_SUCCESS)
758 folio_attach_private(dst, folio_detach_private(src));
762 set_bh_page(bh, &dst->page, bh_offset(bh));
763 bh = bh->b_this_page;
764 } while (bh != head);
766 if (mode != MIGRATE_SYNC_NO_COPY)
767 folio_migrate_copy(dst, src);
769 folio_migrate_flags(dst, src);
771 rc = MIGRATEPAGE_SUCCESS;
774 spin_unlock(&mapping->private_lock);
778 bh = bh->b_this_page;
779 } while (bh != head);
785 * buffer_migrate_folio() - Migration function for folios with buffers.
786 * @mapping: The address space containing @src.
787 * @dst: The folio to migrate to.
788 * @src: The folio to migrate from.
789 * @mode: How to migrate the folio.
791 * This function can only be used if the underlying filesystem guarantees
792 * that no other references to @src exist. For example attached buffer
793 * heads are accessed only under the folio lock. If your filesystem cannot
794 * provide this guarantee, buffer_migrate_folio_norefs() may be more
797 * Return: 0 on success or a negative errno on failure.
799 int buffer_migrate_folio(struct address_space *mapping,
800 struct folio *dst, struct folio *src, enum migrate_mode mode)
802 return __buffer_migrate_folio(mapping, dst, src, mode, false);
804 EXPORT_SYMBOL(buffer_migrate_folio);
807 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
808 * @mapping: The address space containing @src.
809 * @dst: The folio to migrate to.
810 * @src: The folio to migrate from.
811 * @mode: How to migrate the folio.
813 * Like buffer_migrate_folio() except that this variant is more careful
814 * and checks that there are also no buffer head references. This function
815 * is the right one for mappings where buffer heads are directly looked
816 * up and referenced (such as block device mappings).
818 * Return: 0 on success or a negative errno on failure.
820 int buffer_migrate_folio_norefs(struct address_space *mapping,
821 struct folio *dst, struct folio *src, enum migrate_mode mode)
823 return __buffer_migrate_folio(mapping, dst, src, mode, true);
827 int filemap_migrate_folio(struct address_space *mapping,
828 struct folio *dst, struct folio *src, enum migrate_mode mode)
832 ret = folio_migrate_mapping(mapping, dst, src, 0);
833 if (ret != MIGRATEPAGE_SUCCESS)
836 if (folio_get_private(src))
837 folio_attach_private(dst, folio_detach_private(src));
839 if (mode != MIGRATE_SYNC_NO_COPY)
840 folio_migrate_copy(dst, src);
842 folio_migrate_flags(dst, src);
843 return MIGRATEPAGE_SUCCESS;
845 EXPORT_SYMBOL_GPL(filemap_migrate_folio);
848 * Writeback a folio to clean the dirty state
850 static int writeout(struct address_space *mapping, struct folio *folio)
852 struct writeback_control wbc = {
853 .sync_mode = WB_SYNC_NONE,
856 .range_end = LLONG_MAX,
861 if (!mapping->a_ops->writepage)
862 /* No write method for the address space */
865 if (!folio_clear_dirty_for_io(folio))
866 /* Someone else already triggered a write */
870 * A dirty folio may imply that the underlying filesystem has
871 * the folio on some queue. So the folio must be clean for
872 * migration. Writeout may mean we lose the lock and the
873 * folio state is no longer what we checked for earlier.
874 * At this point we know that the migration attempt cannot
877 remove_migration_ptes(folio, folio, false);
879 rc = mapping->a_ops->writepage(&folio->page, &wbc);
881 if (rc != AOP_WRITEPAGE_ACTIVATE)
882 /* unlocked. Relock */
885 return (rc < 0) ? -EIO : -EAGAIN;
889 * Default handling if a filesystem does not provide a migration function.
891 static int fallback_migrate_folio(struct address_space *mapping,
892 struct folio *dst, struct folio *src, enum migrate_mode mode)
894 if (folio_test_dirty(src)) {
895 /* Only writeback folios in full synchronous migration */
898 case MIGRATE_SYNC_NO_COPY:
903 return writeout(mapping, src);
907 * Buffers may be managed in a filesystem specific way.
908 * We must have no buffers or drop them.
910 if (folio_test_private(src) &&
911 !filemap_release_folio(src, GFP_KERNEL))
912 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
914 return migrate_folio(mapping, dst, src, mode);
918 * Move a page to a newly allocated page
919 * The page is locked and all ptes have been successfully removed.
921 * The new page will have replaced the old page if this function
926 * MIGRATEPAGE_SUCCESS - success
928 static int move_to_new_folio(struct folio *dst, struct folio *src,
929 enum migrate_mode mode)
932 bool is_lru = !__PageMovable(&src->page);
934 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
935 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
937 if (likely(is_lru)) {
938 struct address_space *mapping = folio_mapping(src);
941 rc = migrate_folio(mapping, dst, src, mode);
942 else if (mapping->a_ops->migrate_folio)
944 * Most folios have a mapping and most filesystems
945 * provide a migrate_folio callback. Anonymous folios
946 * are part of swap space which also has its own
947 * migrate_folio callback. This is the most common path
948 * for page migration.
950 rc = mapping->a_ops->migrate_folio(mapping, dst, src,
953 rc = fallback_migrate_folio(mapping, dst, src, mode);
955 const struct movable_operations *mops;
958 * In case of non-lru page, it could be released after
959 * isolation step. In that case, we shouldn't try migration.
961 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
962 if (!folio_test_movable(src)) {
963 rc = MIGRATEPAGE_SUCCESS;
964 folio_clear_isolated(src);
968 mops = page_movable_ops(&src->page);
969 rc = mops->migrate_page(&dst->page, &src->page, mode);
970 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
971 !folio_test_isolated(src));
975 * When successful, old pagecache src->mapping must be cleared before
976 * src is freed; but stats require that PageAnon be left as PageAnon.
978 if (rc == MIGRATEPAGE_SUCCESS) {
979 if (__PageMovable(&src->page)) {
980 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
983 * We clear PG_movable under page_lock so any compactor
984 * cannot try to migrate this page.
986 folio_clear_isolated(src);
990 * Anonymous and movable src->mapping will be cleared by
991 * free_pages_prepare so don't reset it here for keeping
992 * the type to work PageAnon, for example.
994 if (!folio_mapping_flags(src))
997 if (likely(!folio_is_zone_device(dst)))
998 flush_dcache_folio(dst);
1004 static int __unmap_and_move(struct folio *src, struct folio *dst,
1005 int force, enum migrate_mode mode)
1008 bool page_was_mapped = false;
1009 struct anon_vma *anon_vma = NULL;
1010 bool is_lru = !__PageMovable(&src->page);
1012 if (!folio_trylock(src)) {
1013 if (!force || mode == MIGRATE_ASYNC)
1017 * It's not safe for direct compaction to call lock_page.
1018 * For example, during page readahead pages are added locked
1019 * to the LRU. Later, when the IO completes the pages are
1020 * marked uptodate and unlocked. However, the queueing
1021 * could be merging multiple pages for one bio (e.g.
1022 * mpage_readahead). If an allocation happens for the
1023 * second or third page, the process can end up locking
1024 * the same page twice and deadlocking. Rather than
1025 * trying to be clever about what pages can be locked,
1026 * avoid the use of lock_page for direct compaction
1029 if (current->flags & PF_MEMALLOC)
1035 if (folio_test_writeback(src)) {
1037 * Only in the case of a full synchronous migration is it
1038 * necessary to wait for PageWriteback. In the async case,
1039 * the retry loop is too short and in the sync-light case,
1040 * the overhead of stalling is too much
1044 case MIGRATE_SYNC_NO_COPY:
1052 folio_wait_writeback(src);
1056 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1057 * we cannot notice that anon_vma is freed while we migrate a page.
1058 * This get_anon_vma() delays freeing anon_vma pointer until the end
1059 * of migration. File cache pages are no problem because of page_lock()
1060 * File Caches may use write_page() or lock_page() in migration, then,
1061 * just care Anon page here.
1063 * Only folio_get_anon_vma() understands the subtleties of
1064 * getting a hold on an anon_vma from outside one of its mms.
1065 * But if we cannot get anon_vma, then we won't need it anyway,
1066 * because that implies that the anon page is no longer mapped
1067 * (and cannot be remapped so long as we hold the page lock).
1069 if (folio_test_anon(src) && !folio_test_ksm(src))
1070 anon_vma = folio_get_anon_vma(src);
1073 * Block others from accessing the new page when we get around to
1074 * establishing additional references. We are usually the only one
1075 * holding a reference to dst at this point. We used to have a BUG
1076 * here if folio_trylock(dst) fails, but would like to allow for
1077 * cases where there might be a race with the previous use of dst.
1078 * This is much like races on refcount of oldpage: just don't BUG().
1080 if (unlikely(!folio_trylock(dst)))
1083 if (unlikely(!is_lru)) {
1084 rc = move_to_new_folio(dst, src, mode);
1085 goto out_unlock_both;
1089 * Corner case handling:
1090 * 1. When a new swap-cache page is read into, it is added to the LRU
1091 * and treated as swapcache but it has no rmap yet.
1092 * Calling try_to_unmap() against a src->mapping==NULL page will
1093 * trigger a BUG. So handle it here.
1094 * 2. An orphaned page (see truncate_cleanup_page) might have
1095 * fs-private metadata. The page can be picked up due to memory
1096 * offlining. Everywhere else except page reclaim, the page is
1097 * invisible to the vm, so the page can not be migrated. So try to
1098 * free the metadata, so the page can be freed.
1100 if (!src->mapping) {
1101 if (folio_test_private(src)) {
1102 try_to_free_buffers(src);
1103 goto out_unlock_both;
1105 } else if (folio_mapped(src)) {
1106 /* Establish migration ptes */
1107 VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1108 !folio_test_ksm(src) && !anon_vma, src);
1109 try_to_migrate(src, 0);
1110 page_was_mapped = true;
1113 if (!folio_mapped(src))
1114 rc = move_to_new_folio(dst, src, mode);
1117 * When successful, push dst to LRU immediately: so that if it
1118 * turns out to be an mlocked page, remove_migration_ptes() will
1119 * automatically build up the correct dst->mlock_count for it.
1121 * We would like to do something similar for the old page, when
1122 * unsuccessful, and other cases when a page has been temporarily
1123 * isolated from the unevictable LRU: but this case is the easiest.
1125 if (rc == MIGRATEPAGE_SUCCESS) {
1127 if (page_was_mapped)
1131 if (page_was_mapped)
1132 remove_migration_ptes(src,
1133 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1138 /* Drop an anon_vma reference if we took one */
1140 put_anon_vma(anon_vma);
1144 * If migration is successful, decrease refcount of dst,
1145 * which will not free the page because new page owner increased
1148 if (rc == MIGRATEPAGE_SUCCESS)
1155 * Obtain the lock on page, remove all ptes and migrate the page
1156 * to the newly allocated page in newpage.
1158 static int unmap_and_move(new_page_t get_new_page,
1159 free_page_t put_new_page,
1160 unsigned long private, struct page *page,
1161 int force, enum migrate_mode mode,
1162 enum migrate_reason reason,
1163 struct list_head *ret)
1165 struct folio *dst, *src = page_folio(page);
1166 int rc = MIGRATEPAGE_SUCCESS;
1167 struct page *newpage = NULL;
1169 if (!thp_migration_supported() && PageTransHuge(page))
1172 if (page_count(page) == 1) {
1173 /* Page was freed from under us. So we are done. */
1174 ClearPageActive(page);
1175 ClearPageUnevictable(page);
1176 /* free_pages_prepare() will clear PG_isolated. */
1180 newpage = get_new_page(page, private);
1183 dst = page_folio(newpage);
1185 newpage->private = 0;
1186 rc = __unmap_and_move(src, dst, force, mode);
1187 if (rc == MIGRATEPAGE_SUCCESS)
1188 set_page_owner_migrate_reason(newpage, reason);
1191 if (rc != -EAGAIN) {
1193 * A page that has been migrated has all references
1194 * removed and will be freed. A page that has not been
1195 * migrated will have kept its references and be restored.
1197 list_del(&page->lru);
1201 * If migration is successful, releases reference grabbed during
1202 * isolation. Otherwise, restore the page to right list unless
1205 if (rc == MIGRATEPAGE_SUCCESS) {
1207 * Compaction can migrate also non-LRU pages which are
1208 * not accounted to NR_ISOLATED_*. They can be recognized
1211 if (likely(!__PageMovable(page)))
1212 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1213 page_is_file_lru(page), -thp_nr_pages(page));
1215 if (reason != MR_MEMORY_FAILURE)
1217 * We release the page in page_handle_poison.
1222 list_add_tail(&page->lru, ret);
1225 put_new_page(newpage, private);
1234 * Counterpart of unmap_and_move_page() for hugepage migration.
1236 * This function doesn't wait the completion of hugepage I/O
1237 * because there is no race between I/O and migration for hugepage.
1238 * Note that currently hugepage I/O occurs only in direct I/O
1239 * where no lock is held and PG_writeback is irrelevant,
1240 * and writeback status of all subpages are counted in the reference
1241 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1242 * under direct I/O, the reference of the head page is 512 and a bit more.)
1243 * This means that when we try to migrate hugepage whose subpages are
1244 * doing direct I/O, some references remain after try_to_unmap() and
1245 * hugepage migration fails without data corruption.
1247 * There is also no race when direct I/O is issued on the page under migration,
1248 * because then pte is replaced with migration swap entry and direct I/O code
1249 * will wait in the page fault for migration to complete.
1251 static int unmap_and_move_huge_page(new_page_t get_new_page,
1252 free_page_t put_new_page, unsigned long private,
1253 struct page *hpage, int force,
1254 enum migrate_mode mode, int reason,
1255 struct list_head *ret)
1257 struct folio *dst, *src = page_folio(hpage);
1259 int page_was_mapped = 0;
1260 struct page *new_hpage;
1261 struct anon_vma *anon_vma = NULL;
1262 struct address_space *mapping = NULL;
1265 * Migratability of hugepages depends on architectures and their size.
1266 * This check is necessary because some callers of hugepage migration
1267 * like soft offline and memory hotremove don't walk through page
1268 * tables or check whether the hugepage is pmd-based or not before
1269 * kicking migration.
1271 if (!hugepage_migration_supported(page_hstate(hpage)))
1274 if (folio_ref_count(src) == 1) {
1275 /* page was freed from under us. So we are done. */
1276 putback_active_hugepage(hpage);
1277 return MIGRATEPAGE_SUCCESS;
1280 new_hpage = get_new_page(hpage, private);
1283 dst = page_folio(new_hpage);
1285 if (!folio_trylock(src)) {
1290 case MIGRATE_SYNC_NO_COPY:
1299 * Check for pages which are in the process of being freed. Without
1300 * folio_mapping() set, hugetlbfs specific move page routine will not
1301 * be called and we could leak usage counts for subpools.
1303 if (hugetlb_page_subpool(hpage) && !folio_mapping(src)) {
1308 if (folio_test_anon(src))
1309 anon_vma = folio_get_anon_vma(src);
1311 if (unlikely(!folio_trylock(dst)))
1314 if (folio_mapped(src)) {
1315 enum ttu_flags ttu = 0;
1317 if (!folio_test_anon(src)) {
1319 * In shared mappings, try_to_unmap could potentially
1320 * call huge_pmd_unshare. Because of this, take
1321 * semaphore in write mode here and set TTU_RMAP_LOCKED
1322 * to let lower levels know we have taken the lock.
1324 mapping = hugetlb_page_mapping_lock_write(hpage);
1325 if (unlikely(!mapping))
1326 goto unlock_put_anon;
1328 ttu = TTU_RMAP_LOCKED;
1331 try_to_migrate(src, ttu);
1332 page_was_mapped = 1;
1334 if (ttu & TTU_RMAP_LOCKED)
1335 i_mmap_unlock_write(mapping);
1338 if (!folio_mapped(src))
1339 rc = move_to_new_folio(dst, src, mode);
1341 if (page_was_mapped)
1342 remove_migration_ptes(src,
1343 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1350 put_anon_vma(anon_vma);
1352 if (rc == MIGRATEPAGE_SUCCESS) {
1353 move_hugetlb_state(hpage, new_hpage, reason);
1354 put_new_page = NULL;
1360 if (rc == MIGRATEPAGE_SUCCESS)
1361 putback_active_hugepage(hpage);
1362 else if (rc != -EAGAIN)
1363 list_move_tail(&src->lru, ret);
1366 * If migration was not successful and there's a freeing callback, use
1367 * it. Otherwise, put_page() will drop the reference grabbed during
1371 put_new_page(new_hpage, private);
1373 putback_active_hugepage(new_hpage);
1378 static inline int try_split_thp(struct page *page, struct list_head *split_pages)
1383 rc = split_huge_page_to_list(page, split_pages);
1386 list_move_tail(&page->lru, split_pages);
1392 * migrate_pages - migrate the pages specified in a list, to the free pages
1393 * supplied as the target for the page migration
1395 * @from: The list of pages to be migrated.
1396 * @get_new_page: The function used to allocate free pages to be used
1397 * as the target of the page migration.
1398 * @put_new_page: The function used to free target pages if migration
1399 * fails, or NULL if no special handling is necessary.
1400 * @private: Private data to be passed on to get_new_page()
1401 * @mode: The migration mode that specifies the constraints for
1402 * page migration, if any.
1403 * @reason: The reason for page migration.
1404 * @ret_succeeded: Set to the number of normal pages migrated successfully if
1405 * the caller passes a non-NULL pointer.
1407 * The function returns after 10 attempts or if no pages are movable any more
1408 * because the list has become empty or no retryable pages exist any more.
1409 * It is caller's responsibility to call putback_movable_pages() to return pages
1410 * to the LRU or free list only if ret != 0.
1412 * Returns the number of {normal page, THP, hugetlb} that were not migrated, or
1413 * an error code. The number of THP splits will be considered as the number of
1414 * non-migrated THP, no matter how many subpages of the THP are migrated successfully.
1416 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1417 free_page_t put_new_page, unsigned long private,
1418 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1423 int nr_failed_pages = 0;
1424 int nr_retry_pages = 0;
1425 int nr_succeeded = 0;
1426 int nr_thp_succeeded = 0;
1427 int nr_thp_failed = 0;
1428 int nr_thp_split = 0;
1430 bool is_thp = false;
1433 int rc, nr_subpages;
1434 LIST_HEAD(ret_pages);
1435 LIST_HEAD(thp_split_pages);
1436 bool nosplit = (reason == MR_NUMA_MISPLACED);
1437 bool no_subpage_counting = false;
1439 trace_mm_migrate_pages_start(mode, reason);
1441 thp_subpage_migration:
1442 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1447 list_for_each_entry_safe(page, page2, from, lru) {
1449 * THP statistics is based on the source huge page.
1450 * Capture required information that might get lost
1453 is_thp = PageTransHuge(page) && !PageHuge(page);
1454 nr_subpages = compound_nr(page);
1458 rc = unmap_and_move_huge_page(get_new_page,
1459 put_new_page, private, page,
1460 pass > 2, mode, reason,
1463 rc = unmap_and_move(get_new_page, put_new_page,
1464 private, page, pass > 2, mode,
1465 reason, &ret_pages);
1468 * Success: non hugetlb page will be freed, hugetlb
1469 * page will be put back
1470 * -EAGAIN: stay on the from list
1471 * -ENOMEM: stay on the from list
1472 * -ENOSYS: stay on the from list
1473 * Other errno: put on ret_pages list then splice to
1478 * THP migration might be unsupported or the
1479 * allocation could've failed so we should
1480 * retry on the same page with the THP split
1483 * Sub-pages are put in thp_split_pages, and
1484 * we will migrate them after the rest of the
1485 * list is processed.
1488 /* THP migration is unsupported */
1491 if (!try_split_thp(page, &thp_split_pages)) {
1495 /* Hugetlb migration is unsupported */
1496 } else if (!no_subpage_counting) {
1500 nr_failed_pages += nr_subpages;
1501 list_move_tail(&page->lru, &ret_pages);
1505 * When memory is low, don't bother to try to migrate
1506 * other pages, just exit.
1510 /* THP NUMA faulting doesn't split THP to retry. */
1511 if (!nosplit && !try_split_thp(page, &thp_split_pages)) {
1515 } else if (!no_subpage_counting) {
1519 nr_failed_pages += nr_subpages + nr_retry_pages;
1521 * There might be some subpages of fail-to-migrate THPs
1522 * left in thp_split_pages list. Move them back to migration
1523 * list so that they could be put back to the right list by
1524 * the caller otherwise the page refcnt will be leaked.
1526 list_splice_init(&thp_split_pages, from);
1527 /* nr_failed isn't updated for not used */
1528 nr_thp_failed += thp_retry;
1533 else if (!no_subpage_counting)
1535 nr_retry_pages += nr_subpages;
1537 case MIGRATEPAGE_SUCCESS:
1538 nr_succeeded += nr_subpages;
1544 * Permanent failure (-EBUSY, etc.):
1545 * unlike -EAGAIN case, the failed page is
1546 * removed from migration page list and not
1547 * retried in the next outer loop.
1551 else if (!no_subpage_counting)
1554 nr_failed_pages += nr_subpages;
1560 nr_thp_failed += thp_retry;
1561 nr_failed_pages += nr_retry_pages;
1563 * Try to migrate subpages of fail-to-migrate THPs, no nr_failed
1564 * counting in this round, since all subpages of a THP is counted
1565 * as 1 failure in the first round.
1567 if (!list_empty(&thp_split_pages)) {
1569 * Move non-migrated pages (after 10 retries) to ret_pages
1570 * to avoid migrating them again.
1572 list_splice_init(from, &ret_pages);
1573 list_splice_init(&thp_split_pages, from);
1574 no_subpage_counting = true;
1576 goto thp_subpage_migration;
1579 rc = nr_failed + nr_thp_failed;
1582 * Put the permanent failure page back to migration list, they
1583 * will be put back to the right list by the caller.
1585 list_splice(&ret_pages, from);
1588 * Return 0 in case all subpages of fail-to-migrate THPs are
1589 * migrated successfully.
1591 if (list_empty(from))
1594 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1595 count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1596 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1597 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1598 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1599 trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1600 nr_thp_failed, nr_thp_split, mode, reason);
1603 *ret_succeeded = nr_succeeded;
1608 struct page *alloc_migration_target(struct page *page, unsigned long private)
1610 struct folio *folio = page_folio(page);
1611 struct migration_target_control *mtc;
1613 unsigned int order = 0;
1614 struct folio *new_folio = NULL;
1618 mtc = (struct migration_target_control *)private;
1619 gfp_mask = mtc->gfp_mask;
1621 if (nid == NUMA_NO_NODE)
1622 nid = folio_nid(folio);
1624 if (folio_test_hugetlb(folio)) {
1625 struct hstate *h = page_hstate(&folio->page);
1627 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1628 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1631 if (folio_test_large(folio)) {
1633 * clear __GFP_RECLAIM to make the migration callback
1634 * consistent with regular THP allocations.
1636 gfp_mask &= ~__GFP_RECLAIM;
1637 gfp_mask |= GFP_TRANSHUGE;
1638 order = folio_order(folio);
1640 zidx = zone_idx(folio_zone(folio));
1641 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1642 gfp_mask |= __GFP_HIGHMEM;
1644 new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
1646 return &new_folio->page;
1651 static int store_status(int __user *status, int start, int value, int nr)
1654 if (put_user(value, status + start))
1662 static int do_move_pages_to_node(struct mm_struct *mm,
1663 struct list_head *pagelist, int node)
1666 struct migration_target_control mtc = {
1668 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1671 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1672 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1674 putback_movable_pages(pagelist);
1679 * Resolves the given address to a struct page, isolates it from the LRU and
1680 * puts it to the given pagelist.
1682 * errno - if the page cannot be found/isolated
1683 * 0 - when it doesn't have to be migrated because it is already on the
1685 * 1 - when it has been queued
1687 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1688 int node, struct list_head *pagelist, bool migrate_all)
1690 struct vm_area_struct *vma;
1696 vma = vma_lookup(mm, addr);
1697 if (!vma || !vma_migratable(vma))
1700 /* FOLL_DUMP to ignore special (like zero) pages */
1701 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1703 err = PTR_ERR(page);
1711 if (is_zone_device_page(page))
1715 if (page_to_nid(page) == node)
1719 if (page_mapcount(page) > 1 && !migrate_all)
1722 if (PageHuge(page)) {
1723 if (PageHead(page)) {
1724 err = isolate_hugetlb(page, pagelist);
1731 head = compound_head(page);
1732 err = isolate_lru_page(head);
1737 list_add_tail(&head->lru, pagelist);
1738 mod_node_page_state(page_pgdat(head),
1739 NR_ISOLATED_ANON + page_is_file_lru(head),
1740 thp_nr_pages(head));
1744 * Either remove the duplicate refcount from
1745 * isolate_lru_page() or drop the page ref if it was
1750 mmap_read_unlock(mm);
1754 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1755 struct list_head *pagelist, int __user *status,
1756 int start, int i, unsigned long nr_pages)
1760 if (list_empty(pagelist))
1763 err = do_move_pages_to_node(mm, pagelist, node);
1766 * Positive err means the number of failed
1767 * pages to migrate. Since we are going to
1768 * abort and return the number of non-migrated
1769 * pages, so need to include the rest of the
1770 * nr_pages that have not been attempted as
1774 err += nr_pages - i;
1777 return store_status(status, start, node, i - start);
1781 * Migrate an array of page address onto an array of nodes and fill
1782 * the corresponding array of status.
1784 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1785 unsigned long nr_pages,
1786 const void __user * __user *pages,
1787 const int __user *nodes,
1788 int __user *status, int flags)
1790 compat_uptr_t __user *compat_pages = (void __user *)pages;
1791 int current_node = NUMA_NO_NODE;
1792 LIST_HEAD(pagelist);
1796 lru_cache_disable();
1798 for (i = start = 0; i < nr_pages; i++) {
1799 const void __user *p;
1804 if (in_compat_syscall()) {
1807 if (get_user(cp, compat_pages + i))
1812 if (get_user(p, pages + i))
1815 if (get_user(node, nodes + i))
1817 addr = (unsigned long)untagged_addr(p);
1820 if (node < 0 || node >= MAX_NUMNODES)
1822 if (!node_state(node, N_MEMORY))
1826 if (!node_isset(node, task_nodes))
1829 if (current_node == NUMA_NO_NODE) {
1830 current_node = node;
1832 } else if (node != current_node) {
1833 err = move_pages_and_store_status(mm, current_node,
1834 &pagelist, status, start, i, nr_pages);
1838 current_node = node;
1842 * Errors in the page lookup or isolation are not fatal and we simply
1843 * report them via status
1845 err = add_page_for_migration(mm, addr, current_node,
1846 &pagelist, flags & MPOL_MF_MOVE_ALL);
1849 /* The page is successfully queued for migration */
1854 * The move_pages() man page does not have an -EEXIST choice, so
1855 * use -EFAULT instead.
1861 * If the page is already on the target node (!err), store the
1862 * node, otherwise, store the err.
1864 err = store_status(status, i, err ? : current_node, 1);
1868 err = move_pages_and_store_status(mm, current_node, &pagelist,
1869 status, start, i, nr_pages);
1871 /* We have accounted for page i */
1876 current_node = NUMA_NO_NODE;
1879 /* Make sure we do not overwrite the existing error */
1880 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1881 status, start, i, nr_pages);
1890 * Determine the nodes of an array of pages and store it in an array of status.
1892 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1893 const void __user **pages, int *status)
1899 for (i = 0; i < nr_pages; i++) {
1900 unsigned long addr = (unsigned long)(*pages);
1901 unsigned int foll_flags = FOLL_DUMP;
1902 struct vm_area_struct *vma;
1906 vma = vma_lookup(mm, addr);
1910 /* Not all huge page follow APIs support 'FOLL_GET' */
1911 if (!is_vm_hugetlb_page(vma))
1912 foll_flags |= FOLL_GET;
1914 /* FOLL_DUMP to ignore special (like zero) pages */
1915 page = follow_page(vma, addr, foll_flags);
1917 err = PTR_ERR(page);
1925 if (!is_zone_device_page(page))
1926 err = page_to_nid(page);
1928 if (foll_flags & FOLL_GET)
1937 mmap_read_unlock(mm);
1940 static int get_compat_pages_array(const void __user *chunk_pages[],
1941 const void __user * __user *pages,
1942 unsigned long chunk_nr)
1944 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1948 for (i = 0; i < chunk_nr; i++) {
1949 if (get_user(p, pages32 + i))
1951 chunk_pages[i] = compat_ptr(p);
1958 * Determine the nodes of a user array of pages and store it in
1959 * a user array of status.
1961 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1962 const void __user * __user *pages,
1965 #define DO_PAGES_STAT_CHUNK_NR 16UL
1966 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1967 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1970 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
1972 if (in_compat_syscall()) {
1973 if (get_compat_pages_array(chunk_pages, pages,
1977 if (copy_from_user(chunk_pages, pages,
1978 chunk_nr * sizeof(*chunk_pages)))
1982 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1984 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1989 nr_pages -= chunk_nr;
1991 return nr_pages ? -EFAULT : 0;
1994 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1996 struct task_struct *task;
1997 struct mm_struct *mm;
2000 * There is no need to check if current process has the right to modify
2001 * the specified process when they are same.
2005 *mem_nodes = cpuset_mems_allowed(current);
2009 /* Find the mm_struct */
2011 task = find_task_by_vpid(pid);
2014 return ERR_PTR(-ESRCH);
2016 get_task_struct(task);
2019 * Check if this process has the right to modify the specified
2020 * process. Use the regular "ptrace_may_access()" checks.
2022 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2024 mm = ERR_PTR(-EPERM);
2029 mm = ERR_PTR(security_task_movememory(task));
2032 *mem_nodes = cpuset_mems_allowed(task);
2033 mm = get_task_mm(task);
2035 put_task_struct(task);
2037 mm = ERR_PTR(-EINVAL);
2042 * Move a list of pages in the address space of the currently executing
2045 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2046 const void __user * __user *pages,
2047 const int __user *nodes,
2048 int __user *status, int flags)
2050 struct mm_struct *mm;
2052 nodemask_t task_nodes;
2055 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2058 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2061 mm = find_mm_struct(pid, &task_nodes);
2066 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2067 nodes, status, flags);
2069 err = do_pages_stat(mm, nr_pages, pages, status);
2075 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2076 const void __user * __user *, pages,
2077 const int __user *, nodes,
2078 int __user *, status, int, flags)
2080 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2083 #ifdef CONFIG_NUMA_BALANCING
2085 * Returns true if this is a safe migration target node for misplaced NUMA
2086 * pages. Currently it only checks the watermarks which is crude.
2088 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2089 unsigned long nr_migrate_pages)
2093 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2094 struct zone *zone = pgdat->node_zones + z;
2096 if (!managed_zone(zone))
2099 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2100 if (!zone_watermark_ok(zone, 0,
2101 high_wmark_pages(zone) +
2110 static struct page *alloc_misplaced_dst_page(struct page *page,
2113 int nid = (int) data;
2114 int order = compound_order(page);
2115 gfp_t gfp = __GFP_THISNODE;
2119 gfp |= GFP_TRANSHUGE_LIGHT;
2121 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2123 gfp &= ~__GFP_RECLAIM;
2125 new = __folio_alloc_node(gfp, order, nid);
2130 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2132 int nr_pages = thp_nr_pages(page);
2133 int order = compound_order(page);
2135 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2137 /* Do not migrate THP mapped by multiple processes */
2138 if (PageTransHuge(page) && total_mapcount(page) > 1)
2141 /* Avoid migrating to a node that is nearly full */
2142 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2145 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2147 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2148 if (managed_zone(pgdat->node_zones + z))
2151 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2155 if (isolate_lru_page(page))
2158 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2162 * Isolating the page has taken another reference, so the
2163 * caller's reference can be safely dropped without the page
2164 * disappearing underneath us during migration.
2171 * Attempt to migrate a misplaced page to the specified destination
2172 * node. Caller is expected to have an elevated reference count on
2173 * the page that will be dropped by this function before returning.
2175 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2178 pg_data_t *pgdat = NODE_DATA(node);
2181 unsigned int nr_succeeded;
2182 LIST_HEAD(migratepages);
2183 int nr_pages = thp_nr_pages(page);
2186 * Don't migrate file pages that are mapped in multiple processes
2187 * with execute permissions as they are probably shared libraries.
2189 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2190 (vma->vm_flags & VM_EXEC))
2194 * Also do not migrate dirty pages as not all filesystems can move
2195 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2197 if (page_is_file_lru(page) && PageDirty(page))
2200 isolated = numamigrate_isolate_page(pgdat, page);
2204 list_add(&page->lru, &migratepages);
2205 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2206 NULL, node, MIGRATE_ASYNC,
2207 MR_NUMA_MISPLACED, &nr_succeeded);
2209 if (!list_empty(&migratepages)) {
2210 list_del(&page->lru);
2211 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2212 page_is_file_lru(page), -nr_pages);
2213 putback_lru_page(page);
2218 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2219 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2220 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2223 BUG_ON(!list_empty(&migratepages));
2230 #endif /* CONFIG_NUMA_BALANCING */
2231 #endif /* CONFIG_NUMA */