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)))
77 if (unlikely(PageSlab(page)))
79 /* Pairs with smp_wmb() in slab freeing, e.g. SLUB's __free_slab() */
82 * Check movable flag before taking the page lock because
83 * we use non-atomic bitops on newly allocated page flags so
84 * unconditionally grabbing the lock ruins page's owner side.
86 if (unlikely(!__PageMovable(page)))
88 /* Pairs with smp_wmb() in slab allocation, e.g. SLUB's alloc_slab_page() */
90 if (unlikely(PageSlab(page)))
94 * As movable pages are not isolated from LRU lists, concurrent
95 * compaction threads can race against page migration functions
96 * as well as race against the releasing a page.
98 * In order to avoid having an already isolated movable page
99 * being (wrongly) re-isolated while it is under migration,
100 * or to avoid attempting to isolate pages being released,
101 * lets be sure we have the page lock
102 * before proceeding with the movable page isolation steps.
104 if (unlikely(!trylock_page(page)))
107 if (!PageMovable(page) || PageIsolated(page))
108 goto out_no_isolated;
110 mops = page_movable_ops(page);
111 VM_BUG_ON_PAGE(!mops, page);
113 if (!mops->isolate_page(page, mode))
114 goto out_no_isolated;
116 /* Driver shouldn't use PG_isolated bit of page->flags */
117 WARN_ON_ONCE(PageIsolated(page));
118 SetPageIsolated(page);
131 static void putback_movable_page(struct page *page)
133 const struct movable_operations *mops = page_movable_ops(page);
135 mops->putback_page(page);
136 ClearPageIsolated(page);
140 * Put previously isolated pages back onto the appropriate lists
141 * from where they were once taken off for compaction/migration.
143 * This function shall be used whenever the isolated pageset has been
144 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
145 * and isolate_hugetlb().
147 void putback_movable_pages(struct list_head *l)
152 list_for_each_entry_safe(page, page2, l, lru) {
153 if (unlikely(PageHuge(page))) {
154 putback_active_hugepage(page);
157 list_del(&page->lru);
159 * We isolated non-lru movable page so here we can use
160 * __PageMovable because LRU page's mapping cannot have
161 * PAGE_MAPPING_MOVABLE.
163 if (unlikely(__PageMovable(page))) {
164 VM_BUG_ON_PAGE(!PageIsolated(page), page);
166 if (PageMovable(page))
167 putback_movable_page(page);
169 ClearPageIsolated(page);
173 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
174 page_is_file_lru(page), -thp_nr_pages(page));
175 putback_lru_page(page);
181 * Restore a potential migration pte to a working pte entry
183 static bool remove_migration_pte(struct folio *folio,
184 struct vm_area_struct *vma, unsigned long addr, void *old)
186 DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
188 while (page_vma_mapped_walk(&pvmw)) {
189 rmap_t rmap_flags = RMAP_NONE;
193 unsigned long idx = 0;
195 /* pgoff is invalid for ksm pages, but they are never large */
196 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
197 idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
198 new = folio_page(folio, idx);
200 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
201 /* PMD-mapped THP migration entry */
203 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
204 !folio_test_pmd_mappable(folio), folio);
205 remove_migration_pmd(&pvmw, new);
211 pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
212 if (pte_swp_soft_dirty(*pvmw.pte))
213 pte = pte_mksoft_dirty(pte);
216 * Recheck VMA as permissions can change since migration started
218 entry = pte_to_swp_entry(*pvmw.pte);
219 if (!is_migration_entry_young(entry))
220 pte = pte_mkold(pte);
221 if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
222 pte = pte_mkdirty(pte);
223 if (is_writable_migration_entry(entry))
224 pte = maybe_mkwrite(pte, vma);
225 else if (pte_swp_uffd_wp(*pvmw.pte))
226 pte = pte_mkuffd_wp(pte);
228 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
229 rmap_flags |= RMAP_EXCLUSIVE;
231 if (unlikely(is_device_private_page(new))) {
233 entry = make_writable_device_private_entry(
236 entry = make_readable_device_private_entry(
238 pte = swp_entry_to_pte(entry);
239 if (pte_swp_soft_dirty(*pvmw.pte))
240 pte = pte_swp_mksoft_dirty(pte);
241 if (pte_swp_uffd_wp(*pvmw.pte))
242 pte = pte_swp_mkuffd_wp(pte);
245 #ifdef CONFIG_HUGETLB_PAGE
246 if (folio_test_hugetlb(folio)) {
247 unsigned int shift = huge_page_shift(hstate_vma(vma));
249 pte = pte_mkhuge(pte);
250 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
251 if (folio_test_anon(folio))
252 hugepage_add_anon_rmap(new, vma, pvmw.address,
255 page_dup_file_rmap(new, true);
256 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
260 if (folio_test_anon(folio))
261 page_add_anon_rmap(new, vma, pvmw.address,
264 page_add_file_rmap(new, vma, false);
265 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
267 if (vma->vm_flags & VM_LOCKED)
268 mlock_page_drain_local();
270 trace_remove_migration_pte(pvmw.address, pte_val(pte),
271 compound_order(new));
273 /* No need to invalidate - it was non-present before */
274 update_mmu_cache(vma, pvmw.address, pvmw.pte);
281 * Get rid of all migration entries and replace them by
282 * references to the indicated page.
284 void remove_migration_ptes(struct folio *src, struct folio *dst, bool locked)
286 struct rmap_walk_control rwc = {
287 .rmap_one = remove_migration_pte,
292 rmap_walk_locked(dst, &rwc);
294 rmap_walk(dst, &rwc);
298 * Something used the pte of a page under migration. We need to
299 * get to the page and wait until migration is finished.
300 * When we return from this function the fault will be retried.
302 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
310 if (!is_swap_pte(pte))
313 entry = pte_to_swp_entry(pte);
314 if (!is_migration_entry(entry))
317 migration_entry_wait_on_locked(entry, ptep, ptl);
320 pte_unmap_unlock(ptep, ptl);
323 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
324 unsigned long address)
326 spinlock_t *ptl = pte_lockptr(mm, pmd);
327 pte_t *ptep = pte_offset_map(pmd, address);
328 __migration_entry_wait(mm, ptep, ptl);
331 #ifdef CONFIG_HUGETLB_PAGE
332 void __migration_entry_wait_huge(pte_t *ptep, spinlock_t *ptl)
337 pte = huge_ptep_get(ptep);
339 if (unlikely(!is_hugetlb_entry_migration(pte)))
342 migration_entry_wait_on_locked(pte_to_swp_entry(pte), NULL, ptl);
345 void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *pte)
347 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, pte);
349 __migration_entry_wait_huge(pte, ptl);
353 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
354 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
358 ptl = pmd_lock(mm, pmd);
359 if (!is_pmd_migration_entry(*pmd))
361 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
368 static int folio_expected_refs(struct address_space *mapping,
375 refs += folio_nr_pages(folio);
376 if (folio_test_private(folio))
383 * Replace the page in the mapping.
385 * The number of remaining references must be:
386 * 1 for anonymous pages without a mapping
387 * 2 for pages with a mapping
388 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
390 int folio_migrate_mapping(struct address_space *mapping,
391 struct folio *newfolio, struct folio *folio, int extra_count)
393 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
394 struct zone *oldzone, *newzone;
396 int expected_count = folio_expected_refs(mapping, folio) + extra_count;
397 long nr = folio_nr_pages(folio);
400 /* Anonymous page without mapping */
401 if (folio_ref_count(folio) != expected_count)
404 /* No turning back from here */
405 newfolio->index = folio->index;
406 newfolio->mapping = folio->mapping;
407 if (folio_test_swapbacked(folio))
408 __folio_set_swapbacked(newfolio);
410 return MIGRATEPAGE_SUCCESS;
413 oldzone = folio_zone(folio);
414 newzone = folio_zone(newfolio);
417 if (!folio_ref_freeze(folio, expected_count)) {
418 xas_unlock_irq(&xas);
423 * Now we know that no one else is looking at the folio:
424 * no turning back from here.
426 newfolio->index = folio->index;
427 newfolio->mapping = folio->mapping;
428 folio_ref_add(newfolio, nr); /* add cache reference */
429 if (folio_test_swapbacked(folio)) {
430 __folio_set_swapbacked(newfolio);
431 if (folio_test_swapcache(folio)) {
432 folio_set_swapcache(newfolio);
433 newfolio->private = folio_get_private(folio);
436 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
439 /* Move dirty while page refs frozen and newpage not yet exposed */
440 dirty = folio_test_dirty(folio);
442 folio_clear_dirty(folio);
443 folio_set_dirty(newfolio);
446 xas_store(&xas, newfolio);
449 * Drop cache reference from old page by unfreezing
450 * to one less reference.
451 * We know this isn't the last reference.
453 folio_ref_unfreeze(folio, expected_count - nr);
456 /* Leave irq disabled to prevent preemption while updating stats */
459 * If moved to a different zone then also account
460 * the page for that zone. Other VM counters will be
461 * taken care of when we establish references to the
462 * new page and drop references to the old page.
464 * Note that anonymous pages are accounted for
465 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
466 * are mapped to swap space.
468 if (newzone != oldzone) {
469 struct lruvec *old_lruvec, *new_lruvec;
470 struct mem_cgroup *memcg;
472 memcg = folio_memcg(folio);
473 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
474 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
476 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
477 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
478 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
479 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
480 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
483 if (folio_test_swapcache(folio)) {
484 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
485 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
488 if (dirty && mapping_can_writeback(mapping)) {
489 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
490 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
491 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
492 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
497 return MIGRATEPAGE_SUCCESS;
499 EXPORT_SYMBOL(folio_migrate_mapping);
502 * The expected number of remaining references is the same as that
503 * of folio_migrate_mapping().
505 int migrate_huge_page_move_mapping(struct address_space *mapping,
506 struct folio *dst, struct folio *src)
508 XA_STATE(xas, &mapping->i_pages, folio_index(src));
512 expected_count = 2 + folio_has_private(src);
513 if (!folio_ref_freeze(src, expected_count)) {
514 xas_unlock_irq(&xas);
518 dst->index = src->index;
519 dst->mapping = src->mapping;
523 xas_store(&xas, dst);
525 folio_ref_unfreeze(src, expected_count - 1);
527 xas_unlock_irq(&xas);
529 return MIGRATEPAGE_SUCCESS;
533 * Copy the flags and some other ancillary information
535 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
539 if (folio_test_error(folio))
540 folio_set_error(newfolio);
541 if (folio_test_referenced(folio))
542 folio_set_referenced(newfolio);
543 if (folio_test_uptodate(folio))
544 folio_mark_uptodate(newfolio);
545 if (folio_test_clear_active(folio)) {
546 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
547 folio_set_active(newfolio);
548 } else if (folio_test_clear_unevictable(folio))
549 folio_set_unevictable(newfolio);
550 if (folio_test_workingset(folio))
551 folio_set_workingset(newfolio);
552 if (folio_test_checked(folio))
553 folio_set_checked(newfolio);
555 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
556 * migration entries. We can still have PG_anon_exclusive set on an
557 * effectively unmapped and unreferenced first sub-pages of an
558 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
560 if (folio_test_mappedtodisk(folio))
561 folio_set_mappedtodisk(newfolio);
563 /* Move dirty on pages not done by folio_migrate_mapping() */
564 if (folio_test_dirty(folio))
565 folio_set_dirty(newfolio);
567 if (folio_test_young(folio))
568 folio_set_young(newfolio);
569 if (folio_test_idle(folio))
570 folio_set_idle(newfolio);
573 * Copy NUMA information to the new page, to prevent over-eager
574 * future migrations of this same page.
576 cpupid = page_cpupid_xchg_last(&folio->page, -1);
578 * For memory tiering mode, when migrate between slow and fast
579 * memory node, reset cpupid, because that is used to record
580 * page access time in slow memory node.
582 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
583 bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
584 bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
586 if (f_toptier != t_toptier)
589 page_cpupid_xchg_last(&newfolio->page, cpupid);
591 folio_migrate_ksm(newfolio, folio);
593 * Please do not reorder this without considering how mm/ksm.c's
594 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
596 if (folio_test_swapcache(folio))
597 folio_clear_swapcache(folio);
598 folio_clear_private(folio);
600 /* page->private contains hugetlb specific flags */
601 if (!folio_test_hugetlb(folio))
602 folio->private = NULL;
605 * If any waiters have accumulated on the new page then
608 if (folio_test_writeback(newfolio))
609 folio_end_writeback(newfolio);
612 * PG_readahead shares the same bit with PG_reclaim. The above
613 * end_page_writeback() may clear PG_readahead mistakenly, so set the
616 if (folio_test_readahead(folio))
617 folio_set_readahead(newfolio);
619 folio_copy_owner(newfolio, folio);
621 if (!folio_test_hugetlb(folio))
622 mem_cgroup_migrate(folio, newfolio);
624 EXPORT_SYMBOL(folio_migrate_flags);
626 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
628 folio_copy(newfolio, folio);
629 folio_migrate_flags(newfolio, folio);
631 EXPORT_SYMBOL(folio_migrate_copy);
633 /************************************************************
634 * Migration functions
635 ***********************************************************/
637 int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
638 struct folio *src, enum migrate_mode mode, int extra_count)
642 BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
644 rc = folio_migrate_mapping(mapping, dst, src, extra_count);
646 if (rc != MIGRATEPAGE_SUCCESS)
649 if (mode != MIGRATE_SYNC_NO_COPY)
650 folio_migrate_copy(dst, src);
652 folio_migrate_flags(dst, src);
653 return MIGRATEPAGE_SUCCESS;
657 * migrate_folio() - Simple folio migration.
658 * @mapping: The address_space containing the folio.
659 * @dst: The folio to migrate the data to.
660 * @src: The folio containing the current data.
661 * @mode: How to migrate the page.
663 * Common logic to directly migrate a single LRU folio suitable for
664 * folios that do not use PagePrivate/PagePrivate2.
666 * Folios are locked upon entry and exit.
668 int migrate_folio(struct address_space *mapping, struct folio *dst,
669 struct folio *src, enum migrate_mode mode)
671 return migrate_folio_extra(mapping, dst, src, mode, 0);
673 EXPORT_SYMBOL(migrate_folio);
676 /* Returns true if all buffers are successfully locked */
677 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
678 enum migrate_mode mode)
680 struct buffer_head *bh = head;
682 /* Simple case, sync compaction */
683 if (mode != MIGRATE_ASYNC) {
686 bh = bh->b_this_page;
688 } while (bh != head);
693 /* async case, we cannot block on lock_buffer so use trylock_buffer */
695 if (!trylock_buffer(bh)) {
697 * We failed to lock the buffer and cannot stall in
698 * async migration. Release the taken locks
700 struct buffer_head *failed_bh = bh;
702 while (bh != failed_bh) {
704 bh = bh->b_this_page;
709 bh = bh->b_this_page;
710 } while (bh != head);
714 static int __buffer_migrate_folio(struct address_space *mapping,
715 struct folio *dst, struct folio *src, enum migrate_mode mode,
718 struct buffer_head *bh, *head;
722 head = folio_buffers(src);
724 return migrate_folio(mapping, dst, src, mode);
726 /* Check whether page does not have extra refs before we do more work */
727 expected_count = folio_expected_refs(mapping, src);
728 if (folio_ref_count(src) != expected_count)
731 if (!buffer_migrate_lock_buffers(head, mode))
736 bool invalidated = false;
740 spin_lock(&mapping->private_lock);
743 if (atomic_read(&bh->b_count)) {
747 bh = bh->b_this_page;
748 } while (bh != head);
754 spin_unlock(&mapping->private_lock);
755 invalidate_bh_lrus();
757 goto recheck_buffers;
761 rc = folio_migrate_mapping(mapping, dst, src, 0);
762 if (rc != MIGRATEPAGE_SUCCESS)
765 folio_attach_private(dst, folio_detach_private(src));
769 set_bh_page(bh, &dst->page, bh_offset(bh));
770 bh = bh->b_this_page;
771 } while (bh != head);
773 if (mode != MIGRATE_SYNC_NO_COPY)
774 folio_migrate_copy(dst, src);
776 folio_migrate_flags(dst, src);
778 rc = MIGRATEPAGE_SUCCESS;
781 spin_unlock(&mapping->private_lock);
785 bh = bh->b_this_page;
786 } while (bh != head);
792 * buffer_migrate_folio() - Migration function for folios with buffers.
793 * @mapping: The address space containing @src.
794 * @dst: The folio to migrate to.
795 * @src: The folio to migrate from.
796 * @mode: How to migrate the folio.
798 * This function can only be used if the underlying filesystem guarantees
799 * that no other references to @src exist. For example attached buffer
800 * heads are accessed only under the folio lock. If your filesystem cannot
801 * provide this guarantee, buffer_migrate_folio_norefs() may be more
804 * Return: 0 on success or a negative errno on failure.
806 int buffer_migrate_folio(struct address_space *mapping,
807 struct folio *dst, struct folio *src, enum migrate_mode mode)
809 return __buffer_migrate_folio(mapping, dst, src, mode, false);
811 EXPORT_SYMBOL(buffer_migrate_folio);
814 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
815 * @mapping: The address space containing @src.
816 * @dst: The folio to migrate to.
817 * @src: The folio to migrate from.
818 * @mode: How to migrate the folio.
820 * Like buffer_migrate_folio() except that this variant is more careful
821 * and checks that there are also no buffer head references. This function
822 * is the right one for mappings where buffer heads are directly looked
823 * up and referenced (such as block device mappings).
825 * Return: 0 on success or a negative errno on failure.
827 int buffer_migrate_folio_norefs(struct address_space *mapping,
828 struct folio *dst, struct folio *src, enum migrate_mode mode)
830 return __buffer_migrate_folio(mapping, dst, src, mode, true);
832 EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
835 int filemap_migrate_folio(struct address_space *mapping,
836 struct folio *dst, struct folio *src, enum migrate_mode mode)
840 ret = folio_migrate_mapping(mapping, dst, src, 0);
841 if (ret != MIGRATEPAGE_SUCCESS)
844 if (folio_get_private(src))
845 folio_attach_private(dst, folio_detach_private(src));
847 if (mode != MIGRATE_SYNC_NO_COPY)
848 folio_migrate_copy(dst, src);
850 folio_migrate_flags(dst, src);
851 return MIGRATEPAGE_SUCCESS;
853 EXPORT_SYMBOL_GPL(filemap_migrate_folio);
856 * Writeback a folio to clean the dirty state
858 static int writeout(struct address_space *mapping, struct folio *folio)
860 struct writeback_control wbc = {
861 .sync_mode = WB_SYNC_NONE,
864 .range_end = LLONG_MAX,
869 if (!mapping->a_ops->writepage)
870 /* No write method for the address space */
873 if (!folio_clear_dirty_for_io(folio))
874 /* Someone else already triggered a write */
878 * A dirty folio may imply that the underlying filesystem has
879 * the folio on some queue. So the folio must be clean for
880 * migration. Writeout may mean we lose the lock and the
881 * folio state is no longer what we checked for earlier.
882 * At this point we know that the migration attempt cannot
885 remove_migration_ptes(folio, folio, false);
887 rc = mapping->a_ops->writepage(&folio->page, &wbc);
889 if (rc != AOP_WRITEPAGE_ACTIVATE)
890 /* unlocked. Relock */
893 return (rc < 0) ? -EIO : -EAGAIN;
897 * Default handling if a filesystem does not provide a migration function.
899 static int fallback_migrate_folio(struct address_space *mapping,
900 struct folio *dst, struct folio *src, enum migrate_mode mode)
902 if (folio_test_dirty(src)) {
903 /* Only writeback folios in full synchronous migration */
906 case MIGRATE_SYNC_NO_COPY:
911 return writeout(mapping, src);
915 * Buffers may be managed in a filesystem specific way.
916 * We must have no buffers or drop them.
918 if (folio_test_private(src) &&
919 !filemap_release_folio(src, GFP_KERNEL))
920 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
922 return migrate_folio(mapping, dst, src, mode);
926 * Move a page to a newly allocated page
927 * The page is locked and all ptes have been successfully removed.
929 * The new page will have replaced the old page if this function
934 * MIGRATEPAGE_SUCCESS - success
936 static int move_to_new_folio(struct folio *dst, struct folio *src,
937 enum migrate_mode mode)
940 bool is_lru = !__PageMovable(&src->page);
942 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
943 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
945 if (likely(is_lru)) {
946 struct address_space *mapping = folio_mapping(src);
949 rc = migrate_folio(mapping, dst, src, mode);
950 else if (mapping->a_ops->migrate_folio)
952 * Most folios have a mapping and most filesystems
953 * provide a migrate_folio callback. Anonymous folios
954 * are part of swap space which also has its own
955 * migrate_folio callback. This is the most common path
956 * for page migration.
958 rc = mapping->a_ops->migrate_folio(mapping, dst, src,
961 rc = fallback_migrate_folio(mapping, dst, src, mode);
963 const struct movable_operations *mops;
966 * In case of non-lru page, it could be released after
967 * isolation step. In that case, we shouldn't try migration.
969 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
970 if (!folio_test_movable(src)) {
971 rc = MIGRATEPAGE_SUCCESS;
972 folio_clear_isolated(src);
976 mops = page_movable_ops(&src->page);
977 rc = mops->migrate_page(&dst->page, &src->page, mode);
978 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
979 !folio_test_isolated(src));
983 * When successful, old pagecache src->mapping must be cleared before
984 * src is freed; but stats require that PageAnon be left as PageAnon.
986 if (rc == MIGRATEPAGE_SUCCESS) {
987 if (__PageMovable(&src->page)) {
988 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
991 * We clear PG_movable under page_lock so any compactor
992 * cannot try to migrate this page.
994 folio_clear_isolated(src);
998 * Anonymous and movable src->mapping will be cleared by
999 * free_pages_prepare so don't reset it here for keeping
1000 * the type to work PageAnon, for example.
1002 if (!folio_mapping_flags(src))
1003 src->mapping = NULL;
1005 if (likely(!folio_is_zone_device(dst)))
1006 flush_dcache_folio(dst);
1012 static int __unmap_and_move(struct folio *src, struct folio *dst,
1013 int force, enum migrate_mode mode)
1016 bool page_was_mapped = false;
1017 struct anon_vma *anon_vma = NULL;
1018 bool is_lru = !__PageMovable(&src->page);
1020 if (!folio_trylock(src)) {
1021 if (!force || mode == MIGRATE_ASYNC)
1025 * It's not safe for direct compaction to call lock_page.
1026 * For example, during page readahead pages are added locked
1027 * to the LRU. Later, when the IO completes the pages are
1028 * marked uptodate and unlocked. However, the queueing
1029 * could be merging multiple pages for one bio (e.g.
1030 * mpage_readahead). If an allocation happens for the
1031 * second or third page, the process can end up locking
1032 * the same page twice and deadlocking. Rather than
1033 * trying to be clever about what pages can be locked,
1034 * avoid the use of lock_page for direct compaction
1037 if (current->flags & PF_MEMALLOC)
1043 if (folio_test_writeback(src)) {
1045 * Only in the case of a full synchronous migration is it
1046 * necessary to wait for PageWriteback. In the async case,
1047 * the retry loop is too short and in the sync-light case,
1048 * the overhead of stalling is too much
1052 case MIGRATE_SYNC_NO_COPY:
1060 folio_wait_writeback(src);
1064 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1065 * we cannot notice that anon_vma is freed while we migrate a page.
1066 * This get_anon_vma() delays freeing anon_vma pointer until the end
1067 * of migration. File cache pages are no problem because of page_lock()
1068 * File Caches may use write_page() or lock_page() in migration, then,
1069 * just care Anon page here.
1071 * Only folio_get_anon_vma() understands the subtleties of
1072 * getting a hold on an anon_vma from outside one of its mms.
1073 * But if we cannot get anon_vma, then we won't need it anyway,
1074 * because that implies that the anon page is no longer mapped
1075 * (and cannot be remapped so long as we hold the page lock).
1077 if (folio_test_anon(src) && !folio_test_ksm(src))
1078 anon_vma = folio_get_anon_vma(src);
1081 * Block others from accessing the new page when we get around to
1082 * establishing additional references. We are usually the only one
1083 * holding a reference to dst at this point. We used to have a BUG
1084 * here if folio_trylock(dst) fails, but would like to allow for
1085 * cases where there might be a race with the previous use of dst.
1086 * This is much like races on refcount of oldpage: just don't BUG().
1088 if (unlikely(!folio_trylock(dst)))
1091 if (unlikely(!is_lru)) {
1092 rc = move_to_new_folio(dst, src, mode);
1093 goto out_unlock_both;
1097 * Corner case handling:
1098 * 1. When a new swap-cache page is read into, it is added to the LRU
1099 * and treated as swapcache but it has no rmap yet.
1100 * Calling try_to_unmap() against a src->mapping==NULL page will
1101 * trigger a BUG. So handle it here.
1102 * 2. An orphaned page (see truncate_cleanup_page) might have
1103 * fs-private metadata. The page can be picked up due to memory
1104 * offlining. Everywhere else except page reclaim, the page is
1105 * invisible to the vm, so the page can not be migrated. So try to
1106 * free the metadata, so the page can be freed.
1108 if (!src->mapping) {
1109 if (folio_test_private(src)) {
1110 try_to_free_buffers(src);
1111 goto out_unlock_both;
1113 } else if (folio_mapped(src)) {
1114 /* Establish migration ptes */
1115 VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1116 !folio_test_ksm(src) && !anon_vma, src);
1117 try_to_migrate(src, 0);
1118 page_was_mapped = true;
1121 if (!folio_mapped(src))
1122 rc = move_to_new_folio(dst, src, mode);
1125 * When successful, push dst to LRU immediately: so that if it
1126 * turns out to be an mlocked page, remove_migration_ptes() will
1127 * automatically build up the correct dst->mlock_count for it.
1129 * We would like to do something similar for the old page, when
1130 * unsuccessful, and other cases when a page has been temporarily
1131 * isolated from the unevictable LRU: but this case is the easiest.
1133 if (rc == MIGRATEPAGE_SUCCESS) {
1135 if (page_was_mapped)
1139 if (page_was_mapped)
1140 remove_migration_ptes(src,
1141 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1146 /* Drop an anon_vma reference if we took one */
1148 put_anon_vma(anon_vma);
1152 * If migration is successful, decrease refcount of dst,
1153 * which will not free the page because new page owner increased
1156 if (rc == MIGRATEPAGE_SUCCESS)
1163 * Obtain the lock on folio, remove all ptes and migrate the folio
1164 * to the newly allocated folio in dst.
1166 static int unmap_and_move(new_page_t get_new_page,
1167 free_page_t put_new_page,
1168 unsigned long private, struct folio *src,
1169 int force, enum migrate_mode mode,
1170 enum migrate_reason reason,
1171 struct list_head *ret)
1174 int rc = MIGRATEPAGE_SUCCESS;
1175 struct page *newpage = NULL;
1177 if (!thp_migration_supported() && folio_test_transhuge(src))
1180 if (folio_ref_count(src) == 1) {
1181 /* Folio was freed from under us. So we are done. */
1182 folio_clear_active(src);
1183 folio_clear_unevictable(src);
1184 /* free_pages_prepare() will clear PG_isolated. */
1188 newpage = get_new_page(&src->page, private);
1191 dst = page_folio(newpage);
1193 dst->private = NULL;
1194 rc = __unmap_and_move(src, dst, force, mode);
1195 if (rc == MIGRATEPAGE_SUCCESS)
1196 set_page_owner_migrate_reason(&dst->page, reason);
1199 if (rc != -EAGAIN) {
1201 * A folio that has been migrated has all references
1202 * removed and will be freed. A folio that has not been
1203 * migrated will have kept its references and be restored.
1205 list_del(&src->lru);
1209 * If migration is successful, releases reference grabbed during
1210 * isolation. Otherwise, restore the folio to right list unless
1213 if (rc == MIGRATEPAGE_SUCCESS) {
1215 * Compaction can migrate also non-LRU folios which are
1216 * not accounted to NR_ISOLATED_*. They can be recognized
1217 * as __folio_test_movable
1219 if (likely(!__folio_test_movable(src)))
1220 mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
1221 folio_is_file_lru(src), -folio_nr_pages(src));
1223 if (reason != MR_MEMORY_FAILURE)
1225 * We release the folio in page_handle_poison.
1230 list_add_tail(&src->lru, ret);
1233 put_new_page(&dst->page, private);
1242 * Counterpart of unmap_and_move_page() for hugepage migration.
1244 * This function doesn't wait the completion of hugepage I/O
1245 * because there is no race between I/O and migration for hugepage.
1246 * Note that currently hugepage I/O occurs only in direct I/O
1247 * where no lock is held and PG_writeback is irrelevant,
1248 * and writeback status of all subpages are counted in the reference
1249 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1250 * under direct I/O, the reference of the head page is 512 and a bit more.)
1251 * This means that when we try to migrate hugepage whose subpages are
1252 * doing direct I/O, some references remain after try_to_unmap() and
1253 * hugepage migration fails without data corruption.
1255 * There is also no race when direct I/O is issued on the page under migration,
1256 * because then pte is replaced with migration swap entry and direct I/O code
1257 * will wait in the page fault for migration to complete.
1259 static int unmap_and_move_huge_page(new_page_t get_new_page,
1260 free_page_t put_new_page, unsigned long private,
1261 struct page *hpage, int force,
1262 enum migrate_mode mode, int reason,
1263 struct list_head *ret)
1265 struct folio *dst, *src = page_folio(hpage);
1267 int page_was_mapped = 0;
1268 struct page *new_hpage;
1269 struct anon_vma *anon_vma = NULL;
1270 struct address_space *mapping = NULL;
1273 * Migratability of hugepages depends on architectures and their size.
1274 * This check is necessary because some callers of hugepage migration
1275 * like soft offline and memory hotremove don't walk through page
1276 * tables or check whether the hugepage is pmd-based or not before
1277 * kicking migration.
1279 if (!hugepage_migration_supported(page_hstate(hpage)))
1282 if (folio_ref_count(src) == 1) {
1283 /* page was freed from under us. So we are done. */
1284 putback_active_hugepage(hpage);
1285 return MIGRATEPAGE_SUCCESS;
1288 new_hpage = get_new_page(hpage, private);
1291 dst = page_folio(new_hpage);
1293 if (!folio_trylock(src)) {
1298 case MIGRATE_SYNC_NO_COPY:
1307 * Check for pages which are in the process of being freed. Without
1308 * folio_mapping() set, hugetlbfs specific move page routine will not
1309 * be called and we could leak usage counts for subpools.
1311 if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1316 if (folio_test_anon(src))
1317 anon_vma = folio_get_anon_vma(src);
1319 if (unlikely(!folio_trylock(dst)))
1322 if (folio_mapped(src)) {
1323 enum ttu_flags ttu = 0;
1325 if (!folio_test_anon(src)) {
1327 * In shared mappings, try_to_unmap could potentially
1328 * call huge_pmd_unshare. Because of this, take
1329 * semaphore in write mode here and set TTU_RMAP_LOCKED
1330 * to let lower levels know we have taken the lock.
1332 mapping = hugetlb_page_mapping_lock_write(hpage);
1333 if (unlikely(!mapping))
1334 goto unlock_put_anon;
1336 ttu = TTU_RMAP_LOCKED;
1339 try_to_migrate(src, ttu);
1340 page_was_mapped = 1;
1342 if (ttu & TTU_RMAP_LOCKED)
1343 i_mmap_unlock_write(mapping);
1346 if (!folio_mapped(src))
1347 rc = move_to_new_folio(dst, src, mode);
1349 if (page_was_mapped)
1350 remove_migration_ptes(src,
1351 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1358 put_anon_vma(anon_vma);
1360 if (rc == MIGRATEPAGE_SUCCESS) {
1361 move_hugetlb_state(src, dst, reason);
1362 put_new_page = NULL;
1368 if (rc == MIGRATEPAGE_SUCCESS)
1369 putback_active_hugepage(hpage);
1370 else if (rc != -EAGAIN)
1371 list_move_tail(&src->lru, ret);
1374 * If migration was not successful and there's a freeing callback, use
1375 * it. Otherwise, put_page() will drop the reference grabbed during
1379 put_new_page(new_hpage, private);
1381 putback_active_hugepage(new_hpage);
1386 static inline int try_split_folio(struct folio *folio, struct list_head *split_folios)
1391 rc = split_folio_to_list(folio, split_folios);
1392 folio_unlock(folio);
1394 list_move_tail(&folio->lru, split_folios);
1400 * migrate_pages - migrate the folios specified in a list, to the free folios
1401 * supplied as the target for the page migration
1403 * @from: The list of folios to be migrated.
1404 * @get_new_page: The function used to allocate free folios to be used
1405 * as the target of the folio migration.
1406 * @put_new_page: The function used to free target folios if migration
1407 * fails, or NULL if no special handling is necessary.
1408 * @private: Private data to be passed on to get_new_page()
1409 * @mode: The migration mode that specifies the constraints for
1410 * folio migration, if any.
1411 * @reason: The reason for folio migration.
1412 * @ret_succeeded: Set to the number of folios migrated successfully if
1413 * the caller passes a non-NULL pointer.
1415 * The function returns after 10 attempts or if no folios are movable any more
1416 * because the list has become empty or no retryable folios exist any more.
1417 * It is caller's responsibility to call putback_movable_pages() to return folios
1418 * to the LRU or free list only if ret != 0.
1420 * Returns the number of {normal folio, large folio, hugetlb} that were not
1421 * migrated, or an error code. The number of large folio splits will be
1422 * considered as the number of non-migrated large folio, no matter how many
1423 * split folios of the large folio are migrated successfully.
1425 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1426 free_page_t put_new_page, unsigned long private,
1427 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1430 int large_retry = 1;
1433 int nr_failed_pages = 0;
1434 int nr_retry_pages = 0;
1435 int nr_succeeded = 0;
1436 int nr_thp_succeeded = 0;
1437 int nr_large_failed = 0;
1438 int nr_thp_failed = 0;
1439 int nr_thp_split = 0;
1441 bool is_large = false;
1442 bool is_thp = false;
1443 struct folio *folio, *folio2;
1445 LIST_HEAD(ret_folios);
1446 LIST_HEAD(split_folios);
1447 bool nosplit = (reason == MR_NUMA_MISPLACED);
1448 bool no_split_folio_counting = false;
1450 trace_mm_migrate_pages_start(mode, reason);
1452 split_folio_migration:
1453 for (pass = 0; pass < 10 && (retry || large_retry); pass++) {
1459 list_for_each_entry_safe(folio, folio2, from, lru) {
1461 * Large folio statistics is based on the source large
1462 * folio. Capture required information that might get
1463 * lost during migration.
1465 is_large = folio_test_large(folio) && !folio_test_hugetlb(folio);
1466 is_thp = is_large && folio_test_pmd_mappable(folio);
1467 nr_pages = folio_nr_pages(folio);
1470 if (folio_test_hugetlb(folio))
1471 rc = unmap_and_move_huge_page(get_new_page,
1472 put_new_page, private,
1473 &folio->page, pass > 2, mode,
1477 rc = unmap_and_move(get_new_page, put_new_page,
1478 private, folio, pass > 2, mode,
1479 reason, &ret_folios);
1482 * Success: non hugetlb folio will be freed, hugetlb
1483 * folio will be put back
1484 * -EAGAIN: stay on the from list
1485 * -ENOMEM: stay on the from list
1486 * -ENOSYS: stay on the from list
1487 * Other errno: put on ret_folios list then splice to
1492 * Large folio migration might be unsupported or
1493 * the allocation could've failed so we should retry
1494 * on the same folio with the large folio split
1497 * Split folios are put in split_folios, and
1498 * we will migrate them after the rest of the
1499 * list is processed.
1502 /* Large folio migration is unsupported */
1505 nr_thp_failed += is_thp;
1506 if (!try_split_folio(folio, &split_folios)) {
1507 nr_thp_split += is_thp;
1510 /* Hugetlb migration is unsupported */
1511 } else if (!no_split_folio_counting) {
1515 nr_failed_pages += nr_pages;
1516 list_move_tail(&folio->lru, &ret_folios);
1520 * When memory is low, don't bother to try to migrate
1521 * other folios, just exit.
1525 nr_thp_failed += is_thp;
1526 /* Large folio NUMA faulting doesn't split to retry. */
1528 int ret = try_split_folio(folio, &split_folios);
1531 nr_thp_split += is_thp;
1533 } else if (reason == MR_LONGTERM_PIN &&
1536 * Try again to split large folio to
1537 * mitigate the failure of longterm pinning.
1540 thp_retry += is_thp;
1541 nr_retry_pages += nr_pages;
1545 } else if (!no_split_folio_counting) {
1549 nr_failed_pages += nr_pages + nr_retry_pages;
1551 * There might be some split folios of fail-to-migrate large
1552 * folios left in split_folios list. Move them back to migration
1553 * list so that they could be put back to the right list by
1554 * the caller otherwise the folio refcnt will be leaked.
1556 list_splice_init(&split_folios, from);
1557 /* nr_failed isn't updated for not used */
1558 nr_large_failed += large_retry;
1559 nr_thp_failed += thp_retry;
1564 thp_retry += is_thp;
1565 } else if (!no_split_folio_counting) {
1568 nr_retry_pages += nr_pages;
1570 case MIGRATEPAGE_SUCCESS:
1571 nr_succeeded += nr_pages;
1572 nr_thp_succeeded += is_thp;
1576 * Permanent failure (-EBUSY, etc.):
1577 * unlike -EAGAIN case, the failed folio is
1578 * removed from migration folio list and not
1579 * retried in the next outer loop.
1583 nr_thp_failed += is_thp;
1584 } else if (!no_split_folio_counting) {
1588 nr_failed_pages += nr_pages;
1594 nr_large_failed += large_retry;
1595 nr_thp_failed += thp_retry;
1596 nr_failed_pages += nr_retry_pages;
1598 * Try to migrate split folios of fail-to-migrate large folios, no
1599 * nr_failed counting in this round, since all split folios of a
1600 * large folio is counted as 1 failure in the first round.
1602 if (!list_empty(&split_folios)) {
1604 * Move non-migrated folios (after 10 retries) to ret_folios
1605 * to avoid migrating them again.
1607 list_splice_init(from, &ret_folios);
1608 list_splice_init(&split_folios, from);
1609 no_split_folio_counting = true;
1611 goto split_folio_migration;
1614 rc = nr_failed + nr_large_failed;
1617 * Put the permanent failure folio back to migration list, they
1618 * will be put back to the right list by the caller.
1620 list_splice(&ret_folios, from);
1623 * Return 0 in case all split folios of fail-to-migrate large folios
1624 * are migrated successfully.
1626 if (list_empty(from))
1629 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1630 count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1631 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1632 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1633 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1634 trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1635 nr_thp_failed, nr_thp_split, mode, reason);
1638 *ret_succeeded = nr_succeeded;
1643 struct page *alloc_migration_target(struct page *page, unsigned long private)
1645 struct folio *folio = page_folio(page);
1646 struct migration_target_control *mtc;
1648 unsigned int order = 0;
1649 struct folio *new_folio = NULL;
1653 mtc = (struct migration_target_control *)private;
1654 gfp_mask = mtc->gfp_mask;
1656 if (nid == NUMA_NO_NODE)
1657 nid = folio_nid(folio);
1659 if (folio_test_hugetlb(folio)) {
1660 struct hstate *h = folio_hstate(folio);
1662 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1663 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1666 if (folio_test_large(folio)) {
1668 * clear __GFP_RECLAIM to make the migration callback
1669 * consistent with regular THP allocations.
1671 gfp_mask &= ~__GFP_RECLAIM;
1672 gfp_mask |= GFP_TRANSHUGE;
1673 order = folio_order(folio);
1675 zidx = zone_idx(folio_zone(folio));
1676 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1677 gfp_mask |= __GFP_HIGHMEM;
1679 new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
1681 return &new_folio->page;
1686 static int store_status(int __user *status, int start, int value, int nr)
1689 if (put_user(value, status + start))
1697 static int do_move_pages_to_node(struct mm_struct *mm,
1698 struct list_head *pagelist, int node)
1701 struct migration_target_control mtc = {
1703 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1706 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1707 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1709 putback_movable_pages(pagelist);
1714 * Resolves the given address to a struct page, isolates it from the LRU and
1715 * puts it to the given pagelist.
1717 * errno - if the page cannot be found/isolated
1718 * 0 - when it doesn't have to be migrated because it is already on the
1720 * 1 - when it has been queued
1722 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1723 int node, struct list_head *pagelist, bool migrate_all)
1725 struct vm_area_struct *vma;
1731 vma = vma_lookup(mm, addr);
1732 if (!vma || !vma_migratable(vma))
1735 /* FOLL_DUMP to ignore special (like zero) pages */
1736 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1738 err = PTR_ERR(page);
1746 if (is_zone_device_page(page))
1750 if (page_to_nid(page) == node)
1754 if (page_mapcount(page) > 1 && !migrate_all)
1757 if (PageHuge(page)) {
1758 if (PageHead(page)) {
1759 err = isolate_hugetlb(page, pagelist);
1766 head = compound_head(page);
1767 err = isolate_lru_page(head);
1772 list_add_tail(&head->lru, pagelist);
1773 mod_node_page_state(page_pgdat(head),
1774 NR_ISOLATED_ANON + page_is_file_lru(head),
1775 thp_nr_pages(head));
1779 * Either remove the duplicate refcount from
1780 * isolate_lru_page() or drop the page ref if it was
1785 mmap_read_unlock(mm);
1789 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1790 struct list_head *pagelist, int __user *status,
1791 int start, int i, unsigned long nr_pages)
1795 if (list_empty(pagelist))
1798 err = do_move_pages_to_node(mm, pagelist, node);
1801 * Positive err means the number of failed
1802 * pages to migrate. Since we are going to
1803 * abort and return the number of non-migrated
1804 * pages, so need to include the rest of the
1805 * nr_pages that have not been attempted as
1809 err += nr_pages - i;
1812 return store_status(status, start, node, i - start);
1816 * Migrate an array of page address onto an array of nodes and fill
1817 * the corresponding array of status.
1819 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1820 unsigned long nr_pages,
1821 const void __user * __user *pages,
1822 const int __user *nodes,
1823 int __user *status, int flags)
1825 int current_node = NUMA_NO_NODE;
1826 LIST_HEAD(pagelist);
1830 lru_cache_disable();
1832 for (i = start = 0; i < nr_pages; i++) {
1833 const void __user *p;
1838 if (get_user(p, pages + i))
1840 if (get_user(node, nodes + i))
1842 addr = (unsigned long)untagged_addr(p);
1845 if (node < 0 || node >= MAX_NUMNODES)
1847 if (!node_state(node, N_MEMORY))
1851 if (!node_isset(node, task_nodes))
1854 if (current_node == NUMA_NO_NODE) {
1855 current_node = node;
1857 } else if (node != current_node) {
1858 err = move_pages_and_store_status(mm, current_node,
1859 &pagelist, status, start, i, nr_pages);
1863 current_node = node;
1867 * Errors in the page lookup or isolation are not fatal and we simply
1868 * report them via status
1870 err = add_page_for_migration(mm, addr, current_node,
1871 &pagelist, flags & MPOL_MF_MOVE_ALL);
1874 /* The page is successfully queued for migration */
1879 * The move_pages() man page does not have an -EEXIST choice, so
1880 * use -EFAULT instead.
1886 * If the page is already on the target node (!err), store the
1887 * node, otherwise, store the err.
1889 err = store_status(status, i, err ? : current_node, 1);
1893 err = move_pages_and_store_status(mm, current_node, &pagelist,
1894 status, start, i, nr_pages);
1896 /* We have accounted for page i */
1901 current_node = NUMA_NO_NODE;
1904 /* Make sure we do not overwrite the existing error */
1905 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1906 status, start, i, nr_pages);
1915 * Determine the nodes of an array of pages and store it in an array of status.
1917 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1918 const void __user **pages, int *status)
1924 for (i = 0; i < nr_pages; i++) {
1925 unsigned long addr = (unsigned long)(*pages);
1926 struct vm_area_struct *vma;
1930 vma = vma_lookup(mm, addr);
1934 /* FOLL_DUMP to ignore special (like zero) pages */
1935 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1937 err = PTR_ERR(page);
1945 if (!is_zone_device_page(page))
1946 err = page_to_nid(page);
1956 mmap_read_unlock(mm);
1959 static int get_compat_pages_array(const void __user *chunk_pages[],
1960 const void __user * __user *pages,
1961 unsigned long chunk_nr)
1963 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1967 for (i = 0; i < chunk_nr; i++) {
1968 if (get_user(p, pages32 + i))
1970 chunk_pages[i] = compat_ptr(p);
1977 * Determine the nodes of a user array of pages and store it in
1978 * a user array of status.
1980 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1981 const void __user * __user *pages,
1984 #define DO_PAGES_STAT_CHUNK_NR 16UL
1985 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1986 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1989 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
1991 if (in_compat_syscall()) {
1992 if (get_compat_pages_array(chunk_pages, pages,
1996 if (copy_from_user(chunk_pages, pages,
1997 chunk_nr * sizeof(*chunk_pages)))
2001 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
2003 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
2008 nr_pages -= chunk_nr;
2010 return nr_pages ? -EFAULT : 0;
2013 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
2015 struct task_struct *task;
2016 struct mm_struct *mm;
2019 * There is no need to check if current process has the right to modify
2020 * the specified process when they are same.
2024 *mem_nodes = cpuset_mems_allowed(current);
2028 /* Find the mm_struct */
2030 task = find_task_by_vpid(pid);
2033 return ERR_PTR(-ESRCH);
2035 get_task_struct(task);
2038 * Check if this process has the right to modify the specified
2039 * process. Use the regular "ptrace_may_access()" checks.
2041 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2043 mm = ERR_PTR(-EPERM);
2048 mm = ERR_PTR(security_task_movememory(task));
2051 *mem_nodes = cpuset_mems_allowed(task);
2052 mm = get_task_mm(task);
2054 put_task_struct(task);
2056 mm = ERR_PTR(-EINVAL);
2061 * Move a list of pages in the address space of the currently executing
2064 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2065 const void __user * __user *pages,
2066 const int __user *nodes,
2067 int __user *status, int flags)
2069 struct mm_struct *mm;
2071 nodemask_t task_nodes;
2074 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2077 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2080 mm = find_mm_struct(pid, &task_nodes);
2085 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2086 nodes, status, flags);
2088 err = do_pages_stat(mm, nr_pages, pages, status);
2094 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2095 const void __user * __user *, pages,
2096 const int __user *, nodes,
2097 int __user *, status, int, flags)
2099 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2102 #ifdef CONFIG_NUMA_BALANCING
2104 * Returns true if this is a safe migration target node for misplaced NUMA
2105 * pages. Currently it only checks the watermarks which is crude.
2107 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2108 unsigned long nr_migrate_pages)
2112 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2113 struct zone *zone = pgdat->node_zones + z;
2115 if (!managed_zone(zone))
2118 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2119 if (!zone_watermark_ok(zone, 0,
2120 high_wmark_pages(zone) +
2129 static struct page *alloc_misplaced_dst_page(struct page *page,
2132 int nid = (int) data;
2133 int order = compound_order(page);
2134 gfp_t gfp = __GFP_THISNODE;
2138 gfp |= GFP_TRANSHUGE_LIGHT;
2140 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2142 gfp &= ~__GFP_RECLAIM;
2144 new = __folio_alloc_node(gfp, order, nid);
2149 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2151 int nr_pages = thp_nr_pages(page);
2152 int order = compound_order(page);
2154 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2156 /* Do not migrate THP mapped by multiple processes */
2157 if (PageTransHuge(page) && total_mapcount(page) > 1)
2160 /* Avoid migrating to a node that is nearly full */
2161 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2164 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2166 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2167 if (managed_zone(pgdat->node_zones + z))
2170 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2174 if (isolate_lru_page(page))
2177 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2181 * Isolating the page has taken another reference, so the
2182 * caller's reference can be safely dropped without the page
2183 * disappearing underneath us during migration.
2190 * Attempt to migrate a misplaced page to the specified destination
2191 * node. Caller is expected to have an elevated reference count on
2192 * the page that will be dropped by this function before returning.
2194 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2197 pg_data_t *pgdat = NODE_DATA(node);
2200 unsigned int nr_succeeded;
2201 LIST_HEAD(migratepages);
2202 int nr_pages = thp_nr_pages(page);
2205 * Don't migrate file pages that are mapped in multiple processes
2206 * with execute permissions as they are probably shared libraries.
2208 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2209 (vma->vm_flags & VM_EXEC))
2213 * Also do not migrate dirty pages as not all filesystems can move
2214 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2216 if (page_is_file_lru(page) && PageDirty(page))
2219 isolated = numamigrate_isolate_page(pgdat, page);
2223 list_add(&page->lru, &migratepages);
2224 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2225 NULL, node, MIGRATE_ASYNC,
2226 MR_NUMA_MISPLACED, &nr_succeeded);
2228 if (!list_empty(&migratepages)) {
2229 list_del(&page->lru);
2230 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2231 page_is_file_lru(page), -nr_pages);
2232 putback_lru_page(page);
2237 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2238 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2239 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2242 BUG_ON(!list_empty(&migratepages));
2249 #endif /* CONFIG_NUMA_BALANCING */
2250 #endif /* CONFIG_NUMA */