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 bool isolate_movable_page(struct page *page, isolate_mode_t mode)
63 struct folio *folio = folio_get_nontail_page(page);
64 const struct movable_operations *mops;
67 * Avoid burning cycles with pages that are yet under __free_pages(),
68 * or just got freed under us.
70 * In case we 'win' a race for a movable page being freed under us and
71 * raise its refcount preventing __free_pages() from doing its job
72 * the put_page() at the end of this block will take care of
73 * release this page, thus avoiding a nasty leakage.
78 if (unlikely(folio_test_slab(folio)))
80 /* Pairs with smp_wmb() in slab freeing, e.g. SLUB's __free_slab() */
83 * Check movable flag before taking the page lock because
84 * we use non-atomic bitops on newly allocated page flags so
85 * unconditionally grabbing the lock ruins page's owner side.
87 if (unlikely(!__folio_test_movable(folio)))
89 /* Pairs with smp_wmb() in slab allocation, e.g. SLUB's alloc_slab_page() */
91 if (unlikely(folio_test_slab(folio)))
95 * As movable pages are not isolated from LRU lists, concurrent
96 * compaction threads can race against page migration functions
97 * as well as race against the releasing a page.
99 * In order to avoid having an already isolated movable page
100 * being (wrongly) re-isolated while it is under migration,
101 * or to avoid attempting to isolate pages being released,
102 * lets be sure we have the page lock
103 * before proceeding with the movable page isolation steps.
105 if (unlikely(!folio_trylock(folio)))
108 if (!folio_test_movable(folio) || folio_test_isolated(folio))
109 goto out_no_isolated;
111 mops = folio_movable_ops(folio);
112 VM_BUG_ON_FOLIO(!mops, folio);
114 if (!mops->isolate_page(&folio->page, mode))
115 goto out_no_isolated;
117 /* Driver shouldn't use PG_isolated bit of page->flags */
118 WARN_ON_ONCE(folio_test_isolated(folio));
119 folio_set_isolated(folio);
132 static void putback_movable_folio(struct folio *folio)
134 const struct movable_operations *mops = folio_movable_ops(folio);
136 mops->putback_page(&folio->page);
137 folio_clear_isolated(folio);
141 * Put previously isolated pages back onto the appropriate lists
142 * from where they were once taken off for compaction/migration.
144 * This function shall be used whenever the isolated pageset has been
145 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
146 * and isolate_hugetlb().
148 void putback_movable_pages(struct list_head *l)
151 struct folio *folio2;
153 list_for_each_entry_safe(folio, folio2, l, lru) {
154 if (unlikely(folio_test_hugetlb(folio))) {
155 folio_putback_active_hugetlb(folio);
158 list_del(&folio->lru);
160 * We isolated non-lru movable folio so here we can use
161 * __PageMovable because LRU folio's mapping cannot have
162 * PAGE_MAPPING_MOVABLE.
164 if (unlikely(__folio_test_movable(folio))) {
165 VM_BUG_ON_FOLIO(!folio_test_isolated(folio), folio);
167 if (folio_test_movable(folio))
168 putback_movable_folio(folio);
170 folio_clear_isolated(folio);
174 node_stat_mod_folio(folio, NR_ISOLATED_ANON +
175 folio_is_file_lru(folio), -folio_nr_pages(folio));
176 folio_putback_lru(folio);
182 * Restore a potential migration pte to a working pte entry
184 static bool remove_migration_pte(struct folio *folio,
185 struct vm_area_struct *vma, unsigned long addr, void *old)
187 DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
189 while (page_vma_mapped_walk(&pvmw)) {
190 rmap_t rmap_flags = RMAP_NONE;
194 unsigned long idx = 0;
196 /* pgoff is invalid for ksm pages, but they are never large */
197 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
198 idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
199 new = folio_page(folio, idx);
201 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
202 /* PMD-mapped THP migration entry */
204 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
205 !folio_test_pmd_mappable(folio), folio);
206 remove_migration_pmd(&pvmw, new);
212 pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
213 if (pte_swp_soft_dirty(*pvmw.pte))
214 pte = pte_mksoft_dirty(pte);
216 entry = pte_to_swp_entry(*pvmw.pte);
217 if (!is_migration_entry_young(entry))
218 pte = pte_mkold(pte);
219 if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
220 pte = pte_mkdirty(pte);
221 if (is_writable_migration_entry(entry))
222 pte = pte_mkwrite(pte);
223 else if (pte_swp_uffd_wp(*pvmw.pte))
224 pte = pte_mkuffd_wp(pte);
226 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
227 rmap_flags |= RMAP_EXCLUSIVE;
229 if (unlikely(is_device_private_page(new))) {
231 entry = make_writable_device_private_entry(
234 entry = make_readable_device_private_entry(
236 pte = swp_entry_to_pte(entry);
237 if (pte_swp_soft_dirty(*pvmw.pte))
238 pte = pte_swp_mksoft_dirty(pte);
239 if (pte_swp_uffd_wp(*pvmw.pte))
240 pte = pte_swp_mkuffd_wp(pte);
243 #ifdef CONFIG_HUGETLB_PAGE
244 if (folio_test_hugetlb(folio)) {
245 unsigned int shift = huge_page_shift(hstate_vma(vma));
247 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
248 if (folio_test_anon(folio))
249 hugepage_add_anon_rmap(new, vma, pvmw.address,
252 page_dup_file_rmap(new, true);
253 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
257 if (folio_test_anon(folio))
258 page_add_anon_rmap(new, vma, pvmw.address,
261 page_add_file_rmap(new, vma, false);
262 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
264 if (vma->vm_flags & VM_LOCKED)
267 trace_remove_migration_pte(pvmw.address, pte_val(pte),
268 compound_order(new));
270 /* No need to invalidate - it was non-present before */
271 update_mmu_cache(vma, pvmw.address, pvmw.pte);
278 * Get rid of all migration entries and replace them by
279 * references to the indicated page.
281 void remove_migration_ptes(struct folio *src, struct folio *dst, bool locked)
283 struct rmap_walk_control rwc = {
284 .rmap_one = remove_migration_pte,
289 rmap_walk_locked(dst, &rwc);
291 rmap_walk(dst, &rwc);
295 * Something used the pte of a page under migration. We need to
296 * get to the page and wait until migration is finished.
297 * When we return from this function the fault will be retried.
299 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
300 unsigned long address)
307 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
311 if (!is_swap_pte(pte))
314 entry = pte_to_swp_entry(pte);
315 if (!is_migration_entry(entry))
318 migration_entry_wait_on_locked(entry, ptl);
324 #ifdef CONFIG_HUGETLB_PAGE
326 * The vma read lock must be held upon entry. Holding that lock prevents either
327 * the pte or the ptl from being freed.
329 * This function will release the vma lock before returning.
331 void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *ptep)
333 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, ptep);
336 hugetlb_vma_assert_locked(vma);
338 pte = huge_ptep_get(ptep);
340 if (unlikely(!is_hugetlb_entry_migration(pte))) {
342 hugetlb_vma_unlock_read(vma);
345 * If migration entry existed, safe to release vma lock
346 * here because the pgtable page won't be freed without the
347 * pgtable lock released. See comment right above pgtable
348 * lock release in migration_entry_wait_on_locked().
350 hugetlb_vma_unlock_read(vma);
351 migration_entry_wait_on_locked(pte_to_swp_entry(pte), ptl);
356 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
357 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
361 ptl = pmd_lock(mm, pmd);
362 if (!is_pmd_migration_entry(*pmd))
364 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), ptl);
371 static int folio_expected_refs(struct address_space *mapping,
378 refs += folio_nr_pages(folio);
379 if (folio_test_private(folio))
386 * Replace the page in the mapping.
388 * The number of remaining references must be:
389 * 1 for anonymous pages without a mapping
390 * 2 for pages with a mapping
391 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
393 int folio_migrate_mapping(struct address_space *mapping,
394 struct folio *newfolio, struct folio *folio, int extra_count)
396 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
397 struct zone *oldzone, *newzone;
399 int expected_count = folio_expected_refs(mapping, folio) + extra_count;
400 long nr = folio_nr_pages(folio);
403 /* Anonymous page without mapping */
404 if (folio_ref_count(folio) != expected_count)
407 /* No turning back from here */
408 newfolio->index = folio->index;
409 newfolio->mapping = folio->mapping;
410 if (folio_test_swapbacked(folio))
411 __folio_set_swapbacked(newfolio);
413 return MIGRATEPAGE_SUCCESS;
416 oldzone = folio_zone(folio);
417 newzone = folio_zone(newfolio);
420 if (!folio_ref_freeze(folio, expected_count)) {
421 xas_unlock_irq(&xas);
426 * Now we know that no one else is looking at the folio:
427 * no turning back from here.
429 newfolio->index = folio->index;
430 newfolio->mapping = folio->mapping;
431 folio_ref_add(newfolio, nr); /* add cache reference */
432 if (folio_test_swapbacked(folio)) {
433 __folio_set_swapbacked(newfolio);
434 if (folio_test_swapcache(folio)) {
435 folio_set_swapcache(newfolio);
436 newfolio->private = folio_get_private(folio);
439 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
442 /* Move dirty while page refs frozen and newpage not yet exposed */
443 dirty = folio_test_dirty(folio);
445 folio_clear_dirty(folio);
446 folio_set_dirty(newfolio);
449 xas_store(&xas, newfolio);
452 * Drop cache reference from old page by unfreezing
453 * to one less reference.
454 * We know this isn't the last reference.
456 folio_ref_unfreeze(folio, expected_count - nr);
459 /* Leave irq disabled to prevent preemption while updating stats */
462 * If moved to a different zone then also account
463 * the page for that zone. Other VM counters will be
464 * taken care of when we establish references to the
465 * new page and drop references to the old page.
467 * Note that anonymous pages are accounted for
468 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
469 * are mapped to swap space.
471 if (newzone != oldzone) {
472 struct lruvec *old_lruvec, *new_lruvec;
473 struct mem_cgroup *memcg;
475 memcg = folio_memcg(folio);
476 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
477 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
479 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
480 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
481 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
482 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
483 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
486 if (folio_test_swapcache(folio)) {
487 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
488 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
491 if (dirty && mapping_can_writeback(mapping)) {
492 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
493 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
494 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
495 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
500 return MIGRATEPAGE_SUCCESS;
502 EXPORT_SYMBOL(folio_migrate_mapping);
505 * The expected number of remaining references is the same as that
506 * of folio_migrate_mapping().
508 int migrate_huge_page_move_mapping(struct address_space *mapping,
509 struct folio *dst, struct folio *src)
511 XA_STATE(xas, &mapping->i_pages, folio_index(src));
515 expected_count = 2 + folio_has_private(src);
516 if (!folio_ref_freeze(src, expected_count)) {
517 xas_unlock_irq(&xas);
521 dst->index = src->index;
522 dst->mapping = src->mapping;
526 xas_store(&xas, dst);
528 folio_ref_unfreeze(src, expected_count - 1);
530 xas_unlock_irq(&xas);
532 return MIGRATEPAGE_SUCCESS;
536 * Copy the flags and some other ancillary information
538 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
542 if (folio_test_error(folio))
543 folio_set_error(newfolio);
544 if (folio_test_referenced(folio))
545 folio_set_referenced(newfolio);
546 if (folio_test_uptodate(folio))
547 folio_mark_uptodate(newfolio);
548 if (folio_test_clear_active(folio)) {
549 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
550 folio_set_active(newfolio);
551 } else if (folio_test_clear_unevictable(folio))
552 folio_set_unevictable(newfolio);
553 if (folio_test_workingset(folio))
554 folio_set_workingset(newfolio);
555 if (folio_test_checked(folio))
556 folio_set_checked(newfolio);
558 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
559 * migration entries. We can still have PG_anon_exclusive set on an
560 * effectively unmapped and unreferenced first sub-pages of an
561 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
563 if (folio_test_mappedtodisk(folio))
564 folio_set_mappedtodisk(newfolio);
566 /* Move dirty on pages not done by folio_migrate_mapping() */
567 if (folio_test_dirty(folio))
568 folio_set_dirty(newfolio);
570 if (folio_test_young(folio))
571 folio_set_young(newfolio);
572 if (folio_test_idle(folio))
573 folio_set_idle(newfolio);
576 * Copy NUMA information to the new page, to prevent over-eager
577 * future migrations of this same page.
579 cpupid = page_cpupid_xchg_last(&folio->page, -1);
581 * For memory tiering mode, when migrate between slow and fast
582 * memory node, reset cpupid, because that is used to record
583 * page access time in slow memory node.
585 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
586 bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
587 bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
589 if (f_toptier != t_toptier)
592 page_cpupid_xchg_last(&newfolio->page, cpupid);
594 folio_migrate_ksm(newfolio, folio);
596 * Please do not reorder this without considering how mm/ksm.c's
597 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
599 if (folio_test_swapcache(folio))
600 folio_clear_swapcache(folio);
601 folio_clear_private(folio);
603 /* page->private contains hugetlb specific flags */
604 if (!folio_test_hugetlb(folio))
605 folio->private = NULL;
608 * If any waiters have accumulated on the new page then
611 if (folio_test_writeback(newfolio))
612 folio_end_writeback(newfolio);
615 * PG_readahead shares the same bit with PG_reclaim. The above
616 * end_page_writeback() may clear PG_readahead mistakenly, so set the
619 if (folio_test_readahead(folio))
620 folio_set_readahead(newfolio);
622 folio_copy_owner(newfolio, folio);
624 if (!folio_test_hugetlb(folio))
625 mem_cgroup_migrate(folio, newfolio);
627 EXPORT_SYMBOL(folio_migrate_flags);
629 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
631 folio_copy(newfolio, folio);
632 folio_migrate_flags(newfolio, folio);
634 EXPORT_SYMBOL(folio_migrate_copy);
636 /************************************************************
637 * Migration functions
638 ***********************************************************/
640 int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
641 struct folio *src, enum migrate_mode mode, int extra_count)
645 BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
647 rc = folio_migrate_mapping(mapping, dst, src, extra_count);
649 if (rc != MIGRATEPAGE_SUCCESS)
652 if (mode != MIGRATE_SYNC_NO_COPY)
653 folio_migrate_copy(dst, src);
655 folio_migrate_flags(dst, src);
656 return MIGRATEPAGE_SUCCESS;
660 * migrate_folio() - Simple folio migration.
661 * @mapping: The address_space containing the folio.
662 * @dst: The folio to migrate the data to.
663 * @src: The folio containing the current data.
664 * @mode: How to migrate the page.
666 * Common logic to directly migrate a single LRU folio suitable for
667 * folios that do not use PagePrivate/PagePrivate2.
669 * Folios are locked upon entry and exit.
671 int migrate_folio(struct address_space *mapping, struct folio *dst,
672 struct folio *src, enum migrate_mode mode)
674 return migrate_folio_extra(mapping, dst, src, mode, 0);
676 EXPORT_SYMBOL(migrate_folio);
679 /* Returns true if all buffers are successfully locked */
680 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
681 enum migrate_mode mode)
683 struct buffer_head *bh = head;
684 struct buffer_head *failed_bh;
687 if (!trylock_buffer(bh)) {
688 if (mode == MIGRATE_ASYNC)
690 if (mode == MIGRATE_SYNC_LIGHT && !buffer_uptodate(bh))
695 bh = bh->b_this_page;
696 } while (bh != head);
701 /* We failed to lock the buffer and cannot stall. */
704 while (bh != failed_bh) {
706 bh = bh->b_this_page;
712 static int __buffer_migrate_folio(struct address_space *mapping,
713 struct folio *dst, struct folio *src, enum migrate_mode mode,
716 struct buffer_head *bh, *head;
720 head = folio_buffers(src);
722 return migrate_folio(mapping, dst, src, mode);
724 /* Check whether page does not have extra refs before we do more work */
725 expected_count = folio_expected_refs(mapping, src);
726 if (folio_ref_count(src) != expected_count)
729 if (!buffer_migrate_lock_buffers(head, mode))
734 bool invalidated = false;
738 spin_lock(&mapping->private_lock);
741 if (atomic_read(&bh->b_count)) {
745 bh = bh->b_this_page;
746 } while (bh != head);
752 spin_unlock(&mapping->private_lock);
753 invalidate_bh_lrus();
755 goto recheck_buffers;
759 rc = folio_migrate_mapping(mapping, dst, src, 0);
760 if (rc != MIGRATEPAGE_SUCCESS)
763 folio_attach_private(dst, folio_detach_private(src));
767 set_bh_page(bh, &dst->page, bh_offset(bh));
768 bh = bh->b_this_page;
769 } while (bh != head);
771 if (mode != MIGRATE_SYNC_NO_COPY)
772 folio_migrate_copy(dst, src);
774 folio_migrate_flags(dst, src);
776 rc = MIGRATEPAGE_SUCCESS;
779 spin_unlock(&mapping->private_lock);
783 bh = bh->b_this_page;
784 } while (bh != head);
790 * buffer_migrate_folio() - Migration function for folios with buffers.
791 * @mapping: The address space containing @src.
792 * @dst: The folio to migrate to.
793 * @src: The folio to migrate from.
794 * @mode: How to migrate the folio.
796 * This function can only be used if the underlying filesystem guarantees
797 * that no other references to @src exist. For example attached buffer
798 * heads are accessed only under the folio lock. If your filesystem cannot
799 * provide this guarantee, buffer_migrate_folio_norefs() may be more
802 * Return: 0 on success or a negative errno on failure.
804 int buffer_migrate_folio(struct address_space *mapping,
805 struct folio *dst, struct folio *src, enum migrate_mode mode)
807 return __buffer_migrate_folio(mapping, dst, src, mode, false);
809 EXPORT_SYMBOL(buffer_migrate_folio);
812 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
813 * @mapping: The address space containing @src.
814 * @dst: The folio to migrate to.
815 * @src: The folio to migrate from.
816 * @mode: How to migrate the folio.
818 * Like buffer_migrate_folio() except that this variant is more careful
819 * and checks that there are also no buffer head references. This function
820 * is the right one for mappings where buffer heads are directly looked
821 * up and referenced (such as block device mappings).
823 * Return: 0 on success or a negative errno on failure.
825 int buffer_migrate_folio_norefs(struct address_space *mapping,
826 struct folio *dst, struct folio *src, enum migrate_mode mode)
828 return __buffer_migrate_folio(mapping, dst, src, mode, true);
830 EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
833 int filemap_migrate_folio(struct address_space *mapping,
834 struct folio *dst, struct folio *src, enum migrate_mode mode)
838 ret = folio_migrate_mapping(mapping, dst, src, 0);
839 if (ret != MIGRATEPAGE_SUCCESS)
842 if (folio_get_private(src))
843 folio_attach_private(dst, folio_detach_private(src));
845 if (mode != MIGRATE_SYNC_NO_COPY)
846 folio_migrate_copy(dst, src);
848 folio_migrate_flags(dst, src);
849 return MIGRATEPAGE_SUCCESS;
851 EXPORT_SYMBOL_GPL(filemap_migrate_folio);
854 * Writeback a folio to clean the dirty state
856 static int writeout(struct address_space *mapping, struct folio *folio)
858 struct writeback_control wbc = {
859 .sync_mode = WB_SYNC_NONE,
862 .range_end = LLONG_MAX,
867 if (!mapping->a_ops->writepage)
868 /* No write method for the address space */
871 if (!folio_clear_dirty_for_io(folio))
872 /* Someone else already triggered a write */
876 * A dirty folio may imply that the underlying filesystem has
877 * the folio on some queue. So the folio must be clean for
878 * migration. Writeout may mean we lose the lock and the
879 * folio state is no longer what we checked for earlier.
880 * At this point we know that the migration attempt cannot
883 remove_migration_ptes(folio, folio, false);
885 rc = mapping->a_ops->writepage(&folio->page, &wbc);
887 if (rc != AOP_WRITEPAGE_ACTIVATE)
888 /* unlocked. Relock */
891 return (rc < 0) ? -EIO : -EAGAIN;
895 * Default handling if a filesystem does not provide a migration function.
897 static int fallback_migrate_folio(struct address_space *mapping,
898 struct folio *dst, struct folio *src, enum migrate_mode mode)
900 if (folio_test_dirty(src)) {
901 /* Only writeback folios in full synchronous migration */
904 case MIGRATE_SYNC_NO_COPY:
909 return writeout(mapping, src);
913 * Buffers may be managed in a filesystem specific way.
914 * We must have no buffers or drop them.
916 if (folio_test_private(src) &&
917 !filemap_release_folio(src, GFP_KERNEL))
918 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
920 return migrate_folio(mapping, dst, src, mode);
924 * Move a page to a newly allocated page
925 * The page is locked and all ptes have been successfully removed.
927 * The new page will have replaced the old page if this function
932 * MIGRATEPAGE_SUCCESS - success
934 static int move_to_new_folio(struct folio *dst, struct folio *src,
935 enum migrate_mode mode)
938 bool is_lru = !__PageMovable(&src->page);
940 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
941 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
943 if (likely(is_lru)) {
944 struct address_space *mapping = folio_mapping(src);
947 rc = migrate_folio(mapping, dst, src, mode);
948 else if (mapping->a_ops->migrate_folio)
950 * Most folios have a mapping and most filesystems
951 * provide a migrate_folio callback. Anonymous folios
952 * are part of swap space which also has its own
953 * migrate_folio callback. This is the most common path
954 * for page migration.
956 rc = mapping->a_ops->migrate_folio(mapping, dst, src,
959 rc = fallback_migrate_folio(mapping, dst, src, mode);
961 const struct movable_operations *mops;
964 * In case of non-lru page, it could be released after
965 * isolation step. In that case, we shouldn't try migration.
967 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
968 if (!folio_test_movable(src)) {
969 rc = MIGRATEPAGE_SUCCESS;
970 folio_clear_isolated(src);
974 mops = folio_movable_ops(src);
975 rc = mops->migrate_page(&dst->page, &src->page, mode);
976 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
977 !folio_test_isolated(src));
981 * When successful, old pagecache src->mapping must be cleared before
982 * src is freed; but stats require that PageAnon be left as PageAnon.
984 if (rc == MIGRATEPAGE_SUCCESS) {
985 if (__PageMovable(&src->page)) {
986 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
989 * We clear PG_movable under page_lock so any compactor
990 * cannot try to migrate this page.
992 folio_clear_isolated(src);
996 * Anonymous and movable src->mapping will be cleared by
997 * free_pages_prepare so don't reset it here for keeping
998 * the type to work PageAnon, for example.
1000 if (!folio_mapping_flags(src))
1001 src->mapping = NULL;
1003 if (likely(!folio_is_zone_device(dst)))
1004 flush_dcache_folio(dst);
1011 * To record some information during migration, we use some unused
1012 * fields (mapping and private) of struct folio of the newly allocated
1013 * destination folio. This is safe because nobody is using them
1016 union migration_ptr {
1017 struct anon_vma *anon_vma;
1018 struct address_space *mapping;
1020 static void __migrate_folio_record(struct folio *dst,
1021 unsigned long page_was_mapped,
1022 struct anon_vma *anon_vma)
1024 union migration_ptr ptr = { .anon_vma = anon_vma };
1025 dst->mapping = ptr.mapping;
1026 dst->private = (void *)page_was_mapped;
1029 static void __migrate_folio_extract(struct folio *dst,
1030 int *page_was_mappedp,
1031 struct anon_vma **anon_vmap)
1033 union migration_ptr ptr = { .mapping = dst->mapping };
1034 *anon_vmap = ptr.anon_vma;
1035 *page_was_mappedp = (unsigned long)dst->private;
1036 dst->mapping = NULL;
1037 dst->private = NULL;
1040 /* Restore the source folio to the original state upon failure */
1041 static void migrate_folio_undo_src(struct folio *src,
1042 int page_was_mapped,
1043 struct anon_vma *anon_vma,
1045 struct list_head *ret)
1047 if (page_was_mapped)
1048 remove_migration_ptes(src, src, false);
1049 /* Drop an anon_vma reference if we took one */
1051 put_anon_vma(anon_vma);
1055 list_move_tail(&src->lru, ret);
1058 /* Restore the destination folio to the original state upon failure */
1059 static void migrate_folio_undo_dst(struct folio *dst, bool locked,
1060 free_folio_t put_new_folio, unsigned long private)
1065 put_new_folio(dst, private);
1070 /* Cleanup src folio upon migration success */
1071 static void migrate_folio_done(struct folio *src,
1072 enum migrate_reason reason)
1075 * Compaction can migrate also non-LRU pages which are
1076 * not accounted to NR_ISOLATED_*. They can be recognized
1079 if (likely(!__folio_test_movable(src)))
1080 mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
1081 folio_is_file_lru(src), -folio_nr_pages(src));
1083 if (reason != MR_MEMORY_FAILURE)
1084 /* We release the page in page_handle_poison. */
1088 /* Obtain the lock on page, remove all ptes. */
1089 static int migrate_folio_unmap(new_folio_t get_new_folio,
1090 free_folio_t put_new_folio, unsigned long private,
1091 struct folio *src, struct folio **dstp, enum migrate_mode mode,
1092 enum migrate_reason reason, struct list_head *ret)
1096 int page_was_mapped = 0;
1097 struct anon_vma *anon_vma = NULL;
1098 bool is_lru = !__PageMovable(&src->page);
1099 bool locked = false;
1100 bool dst_locked = false;
1102 if (folio_ref_count(src) == 1) {
1103 /* Folio was freed from under us. So we are done. */
1104 folio_clear_active(src);
1105 folio_clear_unevictable(src);
1106 /* free_pages_prepare() will clear PG_isolated. */
1107 list_del(&src->lru);
1108 migrate_folio_done(src, reason);
1109 return MIGRATEPAGE_SUCCESS;
1112 dst = get_new_folio(src, private);
1117 dst->private = NULL;
1119 if (!folio_trylock(src)) {
1120 if (mode == MIGRATE_ASYNC)
1124 * It's not safe for direct compaction to call lock_page.
1125 * For example, during page readahead pages are added locked
1126 * to the LRU. Later, when the IO completes the pages are
1127 * marked uptodate and unlocked. However, the queueing
1128 * could be merging multiple pages for one bio (e.g.
1129 * mpage_readahead). If an allocation happens for the
1130 * second or third page, the process can end up locking
1131 * the same page twice and deadlocking. Rather than
1132 * trying to be clever about what pages can be locked,
1133 * avoid the use of lock_page for direct compaction
1136 if (current->flags & PF_MEMALLOC)
1140 * In "light" mode, we can wait for transient locks (eg
1141 * inserting a page into the page table), but it's not
1142 * worth waiting for I/O.
1144 if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
1151 if (folio_test_writeback(src)) {
1153 * Only in the case of a full synchronous migration is it
1154 * necessary to wait for PageWriteback. In the async case,
1155 * the retry loop is too short and in the sync-light case,
1156 * the overhead of stalling is too much
1160 case MIGRATE_SYNC_NO_COPY:
1166 folio_wait_writeback(src);
1170 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1171 * we cannot notice that anon_vma is freed while we migrate a page.
1172 * This get_anon_vma() delays freeing anon_vma pointer until the end
1173 * of migration. File cache pages are no problem because of page_lock()
1174 * File Caches may use write_page() or lock_page() in migration, then,
1175 * just care Anon page here.
1177 * Only folio_get_anon_vma() understands the subtleties of
1178 * getting a hold on an anon_vma from outside one of its mms.
1179 * But if we cannot get anon_vma, then we won't need it anyway,
1180 * because that implies that the anon page is no longer mapped
1181 * (and cannot be remapped so long as we hold the page lock).
1183 if (folio_test_anon(src) && !folio_test_ksm(src))
1184 anon_vma = folio_get_anon_vma(src);
1187 * Block others from accessing the new page when we get around to
1188 * establishing additional references. We are usually the only one
1189 * holding a reference to dst at this point. We used to have a BUG
1190 * here if folio_trylock(dst) fails, but would like to allow for
1191 * cases where there might be a race with the previous use of dst.
1192 * This is much like races on refcount of oldpage: just don't BUG().
1194 if (unlikely(!folio_trylock(dst)))
1198 if (unlikely(!is_lru)) {
1199 __migrate_folio_record(dst, page_was_mapped, anon_vma);
1200 return MIGRATEPAGE_UNMAP;
1204 * Corner case handling:
1205 * 1. When a new swap-cache page is read into, it is added to the LRU
1206 * and treated as swapcache but it has no rmap yet.
1207 * Calling try_to_unmap() against a src->mapping==NULL page will
1208 * trigger a BUG. So handle it here.
1209 * 2. An orphaned page (see truncate_cleanup_page) might have
1210 * fs-private metadata. The page can be picked up due to memory
1211 * offlining. Everywhere else except page reclaim, the page is
1212 * invisible to the vm, so the page can not be migrated. So try to
1213 * free the metadata, so the page can be freed.
1215 if (!src->mapping) {
1216 if (folio_test_private(src)) {
1217 try_to_free_buffers(src);
1220 } else if (folio_mapped(src)) {
1221 /* Establish migration ptes */
1222 VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1223 !folio_test_ksm(src) && !anon_vma, src);
1224 try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
1225 page_was_mapped = 1;
1228 if (!folio_mapped(src)) {
1229 __migrate_folio_record(dst, page_was_mapped, anon_vma);
1230 return MIGRATEPAGE_UNMAP;
1235 * A folio that has not been unmapped will be restored to
1236 * right list unless we want to retry.
1241 migrate_folio_undo_src(src, page_was_mapped, anon_vma, locked, ret);
1242 migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
1247 /* Migrate the folio to the newly allocated folio in dst. */
1248 static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
1249 struct folio *src, struct folio *dst,
1250 enum migrate_mode mode, enum migrate_reason reason,
1251 struct list_head *ret)
1254 int page_was_mapped = 0;
1255 struct anon_vma *anon_vma = NULL;
1256 bool is_lru = !__PageMovable(&src->page);
1257 struct list_head *prev;
1259 __migrate_folio_extract(dst, &page_was_mapped, &anon_vma);
1260 prev = dst->lru.prev;
1261 list_del(&dst->lru);
1263 rc = move_to_new_folio(dst, src, mode);
1267 if (unlikely(!is_lru))
1268 goto out_unlock_both;
1271 * When successful, push dst to LRU immediately: so that if it
1272 * turns out to be an mlocked page, remove_migration_ptes() will
1273 * automatically build up the correct dst->mlock_count for it.
1275 * We would like to do something similar for the old page, when
1276 * unsuccessful, and other cases when a page has been temporarily
1277 * isolated from the unevictable LRU: but this case is the easiest.
1280 if (page_was_mapped)
1283 if (page_was_mapped)
1284 remove_migration_ptes(src, dst, false);
1288 set_page_owner_migrate_reason(&dst->page, reason);
1290 * If migration is successful, decrease refcount of dst,
1291 * which will not free the page because new page owner increased
1297 * A folio that has been migrated has all references removed
1298 * and will be freed.
1300 list_del(&src->lru);
1301 /* Drop an anon_vma reference if we took one */
1303 put_anon_vma(anon_vma);
1305 migrate_folio_done(src, reason);
1310 * A folio that has not been migrated will be restored to
1311 * right list unless we want to retry.
1313 if (rc == -EAGAIN) {
1314 list_add(&dst->lru, prev);
1315 __migrate_folio_record(dst, page_was_mapped, anon_vma);
1319 migrate_folio_undo_src(src, page_was_mapped, anon_vma, true, ret);
1320 migrate_folio_undo_dst(dst, true, put_new_folio, private);
1326 * Counterpart of unmap_and_move_page() for hugepage migration.
1328 * This function doesn't wait the completion of hugepage I/O
1329 * because there is no race between I/O and migration for hugepage.
1330 * Note that currently hugepage I/O occurs only in direct I/O
1331 * where no lock is held and PG_writeback is irrelevant,
1332 * and writeback status of all subpages are counted in the reference
1333 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1334 * under direct I/O, the reference of the head page is 512 and a bit more.)
1335 * This means that when we try to migrate hugepage whose subpages are
1336 * doing direct I/O, some references remain after try_to_unmap() and
1337 * hugepage migration fails without data corruption.
1339 * There is also no race when direct I/O is issued on the page under migration,
1340 * because then pte is replaced with migration swap entry and direct I/O code
1341 * will wait in the page fault for migration to complete.
1343 static int unmap_and_move_huge_page(new_folio_t get_new_folio,
1344 free_folio_t put_new_folio, unsigned long private,
1345 struct folio *src, int force, enum migrate_mode mode,
1346 int reason, struct list_head *ret)
1350 int page_was_mapped = 0;
1351 struct anon_vma *anon_vma = NULL;
1352 struct address_space *mapping = NULL;
1354 if (folio_ref_count(src) == 1) {
1355 /* page was freed from under us. So we are done. */
1356 folio_putback_active_hugetlb(src);
1357 return MIGRATEPAGE_SUCCESS;
1360 dst = get_new_folio(src, private);
1364 if (!folio_trylock(src)) {
1369 case MIGRATE_SYNC_NO_COPY:
1378 * Check for pages which are in the process of being freed. Without
1379 * folio_mapping() set, hugetlbfs specific move page routine will not
1380 * be called and we could leak usage counts for subpools.
1382 if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1387 if (folio_test_anon(src))
1388 anon_vma = folio_get_anon_vma(src);
1390 if (unlikely(!folio_trylock(dst)))
1393 if (folio_mapped(src)) {
1394 enum ttu_flags ttu = 0;
1396 if (!folio_test_anon(src)) {
1398 * In shared mappings, try_to_unmap could potentially
1399 * call huge_pmd_unshare. Because of this, take
1400 * semaphore in write mode here and set TTU_RMAP_LOCKED
1401 * to let lower levels know we have taken the lock.
1403 mapping = hugetlb_page_mapping_lock_write(&src->page);
1404 if (unlikely(!mapping))
1405 goto unlock_put_anon;
1407 ttu = TTU_RMAP_LOCKED;
1410 try_to_migrate(src, ttu);
1411 page_was_mapped = 1;
1413 if (ttu & TTU_RMAP_LOCKED)
1414 i_mmap_unlock_write(mapping);
1417 if (!folio_mapped(src))
1418 rc = move_to_new_folio(dst, src, mode);
1420 if (page_was_mapped)
1421 remove_migration_ptes(src,
1422 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1429 put_anon_vma(anon_vma);
1431 if (rc == MIGRATEPAGE_SUCCESS) {
1432 move_hugetlb_state(src, dst, reason);
1433 put_new_folio = NULL;
1439 if (rc == MIGRATEPAGE_SUCCESS)
1440 folio_putback_active_hugetlb(src);
1441 else if (rc != -EAGAIN)
1442 list_move_tail(&src->lru, ret);
1445 * If migration was not successful and there's a freeing callback, use
1446 * it. Otherwise, put_page() will drop the reference grabbed during
1450 put_new_folio(dst, private);
1452 folio_putback_active_hugetlb(dst);
1457 static inline int try_split_folio(struct folio *folio, struct list_head *split_folios)
1462 rc = split_folio_to_list(folio, split_folios);
1463 folio_unlock(folio);
1465 list_move_tail(&folio->lru, split_folios);
1470 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1471 #define NR_MAX_BATCHED_MIGRATION HPAGE_PMD_NR
1473 #define NR_MAX_BATCHED_MIGRATION 512
1475 #define NR_MAX_MIGRATE_PAGES_RETRY 10
1476 #define NR_MAX_MIGRATE_ASYNC_RETRY 3
1477 #define NR_MAX_MIGRATE_SYNC_RETRY \
1478 (NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
1480 struct migrate_pages_stats {
1481 int nr_succeeded; /* Normal and large folios migrated successfully, in
1482 units of base pages */
1483 int nr_failed_pages; /* Normal and large folios failed to be migrated, in
1484 units of base pages. Untried folios aren't counted */
1485 int nr_thp_succeeded; /* THP migrated successfully */
1486 int nr_thp_failed; /* THP failed to be migrated */
1487 int nr_thp_split; /* THP split before migrating */
1491 * Returns the number of hugetlb folios that were not migrated, or an error code
1492 * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
1493 * any more because the list has become empty or no retryable hugetlb folios
1494 * exist any more. It is caller's responsibility to call putback_movable_pages()
1497 static int migrate_hugetlbs(struct list_head *from, new_folio_t get_new_folio,
1498 free_folio_t put_new_folio, unsigned long private,
1499 enum migrate_mode mode, int reason,
1500 struct migrate_pages_stats *stats,
1501 struct list_head *ret_folios)
1505 int nr_retry_pages = 0;
1507 struct folio *folio, *folio2;
1510 for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
1514 list_for_each_entry_safe(folio, folio2, from, lru) {
1515 if (!folio_test_hugetlb(folio))
1518 nr_pages = folio_nr_pages(folio);
1523 * Migratability of hugepages depends on architectures and
1524 * their size. This check is necessary because some callers
1525 * of hugepage migration like soft offline and memory
1526 * hotremove don't walk through page tables or check whether
1527 * the hugepage is pmd-based or not before kicking migration.
1529 if (!hugepage_migration_supported(folio_hstate(folio))) {
1531 stats->nr_failed_pages += nr_pages;
1532 list_move_tail(&folio->lru, ret_folios);
1536 rc = unmap_and_move_huge_page(get_new_folio,
1537 put_new_folio, private,
1538 folio, pass > 2, mode,
1539 reason, ret_folios);
1542 * Success: hugetlb folio will be put back
1543 * -EAGAIN: stay on the from list
1544 * -ENOMEM: stay on the from list
1545 * Other errno: put on ret_folios list
1550 * When memory is low, don't bother to try to migrate
1551 * other folios, just exit.
1553 stats->nr_failed_pages += nr_pages + nr_retry_pages;
1557 nr_retry_pages += nr_pages;
1559 case MIGRATEPAGE_SUCCESS:
1560 stats->nr_succeeded += nr_pages;
1564 * Permanent failure (-EBUSY, etc.):
1565 * unlike -EAGAIN case, the failed folio is
1566 * removed from migration folio list and not
1567 * retried in the next outer loop.
1570 stats->nr_failed_pages += nr_pages;
1576 * nr_failed is number of hugetlb folios failed to be migrated. After
1577 * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
1581 stats->nr_failed_pages += nr_retry_pages;
1587 * migrate_pages_batch() first unmaps folios in the from list as many as
1588 * possible, then move the unmapped folios.
1590 * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
1591 * lock or bit when we have locked more than one folio. Which may cause
1592 * deadlock (e.g., for loop device). So, if mode != MIGRATE_ASYNC, the
1593 * length of the from list must be <= 1.
1595 static int migrate_pages_batch(struct list_head *from,
1596 new_folio_t get_new_folio, free_folio_t put_new_folio,
1597 unsigned long private, enum migrate_mode mode, int reason,
1598 struct list_head *ret_folios, struct list_head *split_folios,
1599 struct migrate_pages_stats *stats, int nr_pass)
1604 int nr_retry_pages = 0;
1606 bool is_thp = false;
1607 struct folio *folio, *folio2, *dst = NULL, *dst2;
1608 int rc, rc_saved = 0, nr_pages;
1609 LIST_HEAD(unmap_folios);
1610 LIST_HEAD(dst_folios);
1611 bool nosplit = (reason == MR_NUMA_MISPLACED);
1613 VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
1614 !list_empty(from) && !list_is_singular(from));
1616 for (pass = 0; pass < nr_pass && retry; pass++) {
1621 list_for_each_entry_safe(folio, folio2, from, lru) {
1622 is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
1623 nr_pages = folio_nr_pages(folio);
1628 * Large folio migration might be unsupported or
1629 * the allocation might be failed so we should retry
1630 * on the same folio with the large folio split
1633 * Split folios are put in split_folios, and
1634 * we will migrate them after the rest of the
1635 * list is processed.
1637 if (!thp_migration_supported() && is_thp) {
1639 stats->nr_thp_failed++;
1640 if (!try_split_folio(folio, split_folios)) {
1641 stats->nr_thp_split++;
1644 stats->nr_failed_pages += nr_pages;
1645 list_move_tail(&folio->lru, ret_folios);
1649 rc = migrate_folio_unmap(get_new_folio, put_new_folio,
1650 private, folio, &dst, mode, reason,
1654 * Success: folio will be freed
1655 * Unmap: folio will be put on unmap_folios list,
1656 * dst folio put on dst_folios list
1657 * -EAGAIN: stay on the from list
1658 * -ENOMEM: stay on the from list
1659 * Other errno: put on ret_folios list
1664 * When memory is low, don't bother to try to migrate
1665 * other folios, move unmapped folios, then exit.
1668 stats->nr_thp_failed += is_thp;
1669 /* Large folio NUMA faulting doesn't split to retry. */
1670 if (folio_test_large(folio) && !nosplit) {
1671 int ret = try_split_folio(folio, split_folios);
1674 stats->nr_thp_split += is_thp;
1676 } else if (reason == MR_LONGTERM_PIN &&
1679 * Try again to split large folio to
1680 * mitigate the failure of longterm pinning.
1683 thp_retry += is_thp;
1684 nr_retry_pages += nr_pages;
1685 /* Undo duplicated failure counting. */
1687 stats->nr_thp_failed -= is_thp;
1692 stats->nr_failed_pages += nr_pages + nr_retry_pages;
1693 /* nr_failed isn't updated for not used */
1694 stats->nr_thp_failed += thp_retry;
1696 if (list_empty(&unmap_folios))
1702 thp_retry += is_thp;
1703 nr_retry_pages += nr_pages;
1705 case MIGRATEPAGE_SUCCESS:
1706 stats->nr_succeeded += nr_pages;
1707 stats->nr_thp_succeeded += is_thp;
1709 case MIGRATEPAGE_UNMAP:
1710 list_move_tail(&folio->lru, &unmap_folios);
1711 list_add_tail(&dst->lru, &dst_folios);
1715 * Permanent failure (-EBUSY, etc.):
1716 * unlike -EAGAIN case, the failed folio is
1717 * removed from migration folio list and not
1718 * retried in the next outer loop.
1721 stats->nr_thp_failed += is_thp;
1722 stats->nr_failed_pages += nr_pages;
1728 stats->nr_thp_failed += thp_retry;
1729 stats->nr_failed_pages += nr_retry_pages;
1731 /* Flush TLBs for all unmapped folios */
1732 try_to_unmap_flush();
1735 for (pass = 0; pass < nr_pass && retry; pass++) {
1740 dst = list_first_entry(&dst_folios, struct folio, lru);
1741 dst2 = list_next_entry(dst, lru);
1742 list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1743 is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
1744 nr_pages = folio_nr_pages(folio);
1748 rc = migrate_folio_move(put_new_folio, private,
1750 reason, ret_folios);
1753 * Success: folio will be freed
1754 * -EAGAIN: stay on the unmap_folios list
1755 * Other errno: put on ret_folios list
1760 thp_retry += is_thp;
1761 nr_retry_pages += nr_pages;
1763 case MIGRATEPAGE_SUCCESS:
1764 stats->nr_succeeded += nr_pages;
1765 stats->nr_thp_succeeded += is_thp;
1769 stats->nr_thp_failed += is_thp;
1770 stats->nr_failed_pages += nr_pages;
1774 dst2 = list_next_entry(dst, lru);
1778 stats->nr_thp_failed += thp_retry;
1779 stats->nr_failed_pages += nr_retry_pages;
1781 rc = rc_saved ? : nr_failed;
1783 /* Cleanup remaining folios */
1784 dst = list_first_entry(&dst_folios, struct folio, lru);
1785 dst2 = list_next_entry(dst, lru);
1786 list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
1787 int page_was_mapped = 0;
1788 struct anon_vma *anon_vma = NULL;
1790 __migrate_folio_extract(dst, &page_was_mapped, &anon_vma);
1791 migrate_folio_undo_src(folio, page_was_mapped, anon_vma,
1793 list_del(&dst->lru);
1794 migrate_folio_undo_dst(dst, true, put_new_folio, private);
1796 dst2 = list_next_entry(dst, lru);
1802 static int migrate_pages_sync(struct list_head *from, new_folio_t get_new_folio,
1803 free_folio_t put_new_folio, unsigned long private,
1804 enum migrate_mode mode, int reason,
1805 struct list_head *ret_folios, struct list_head *split_folios,
1806 struct migrate_pages_stats *stats)
1808 int rc, nr_failed = 0;
1810 struct migrate_pages_stats astats;
1812 memset(&astats, 0, sizeof(astats));
1813 /* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
1814 rc = migrate_pages_batch(from, get_new_folio, put_new_folio, private, MIGRATE_ASYNC,
1815 reason, &folios, split_folios, &astats,
1816 NR_MAX_MIGRATE_ASYNC_RETRY);
1817 stats->nr_succeeded += astats.nr_succeeded;
1818 stats->nr_thp_succeeded += astats.nr_thp_succeeded;
1819 stats->nr_thp_split += astats.nr_thp_split;
1821 stats->nr_failed_pages += astats.nr_failed_pages;
1822 stats->nr_thp_failed += astats.nr_thp_failed;
1823 list_splice_tail(&folios, ret_folios);
1826 stats->nr_thp_failed += astats.nr_thp_split;
1827 nr_failed += astats.nr_thp_split;
1829 * Fall back to migrate all failed folios one by one synchronously. All
1830 * failed folios except split THPs will be retried, so their failure
1833 list_splice_tail_init(&folios, from);
1834 while (!list_empty(from)) {
1835 list_move(from->next, &folios);
1836 rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
1837 private, mode, reason, ret_folios,
1838 split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
1839 list_splice_tail_init(&folios, ret_folios);
1849 * migrate_pages - migrate the folios specified in a list, to the free folios
1850 * supplied as the target for the page migration
1852 * @from: The list of folios to be migrated.
1853 * @get_new_folio: The function used to allocate free folios to be used
1854 * as the target of the folio migration.
1855 * @put_new_folio: The function used to free target folios if migration
1856 * fails, or NULL if no special handling is necessary.
1857 * @private: Private data to be passed on to get_new_folio()
1858 * @mode: The migration mode that specifies the constraints for
1859 * folio migration, if any.
1860 * @reason: The reason for folio migration.
1861 * @ret_succeeded: Set to the number of folios migrated successfully if
1862 * the caller passes a non-NULL pointer.
1864 * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
1865 * are movable any more because the list has become empty or no retryable folios
1866 * exist any more. It is caller's responsibility to call putback_movable_pages()
1869 * Returns the number of {normal folio, large folio, hugetlb} that were not
1870 * migrated, or an error code. The number of large folio splits will be
1871 * considered as the number of non-migrated large folio, no matter how many
1872 * split folios of the large folio are migrated successfully.
1874 int migrate_pages(struct list_head *from, new_folio_t get_new_folio,
1875 free_folio_t put_new_folio, unsigned long private,
1876 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1880 struct folio *folio, *folio2;
1882 LIST_HEAD(ret_folios);
1883 LIST_HEAD(split_folios);
1884 struct migrate_pages_stats stats;
1886 trace_mm_migrate_pages_start(mode, reason);
1888 memset(&stats, 0, sizeof(stats));
1890 rc_gather = migrate_hugetlbs(from, get_new_folio, put_new_folio, private,
1891 mode, reason, &stats, &ret_folios);
1897 list_for_each_entry_safe(folio, folio2, from, lru) {
1898 /* Retried hugetlb folios will be kept in list */
1899 if (folio_test_hugetlb(folio)) {
1900 list_move_tail(&folio->lru, &ret_folios);
1904 nr_pages += folio_nr_pages(folio);
1905 if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
1908 if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
1909 list_cut_before(&folios, from, &folio2->lru);
1911 list_splice_init(from, &folios);
1912 if (mode == MIGRATE_ASYNC)
1913 rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
1914 private, mode, reason, &ret_folios,
1915 &split_folios, &stats,
1916 NR_MAX_MIGRATE_PAGES_RETRY);
1918 rc = migrate_pages_sync(&folios, get_new_folio, put_new_folio,
1919 private, mode, reason, &ret_folios,
1920 &split_folios, &stats);
1921 list_splice_tail_init(&folios, &ret_folios);
1924 list_splice_tail(&split_folios, &ret_folios);
1927 if (!list_empty(&split_folios)) {
1929 * Failure isn't counted since all split folios of a large folio
1930 * is counted as 1 failure already. And, we only try to migrate
1931 * with minimal effort, force MIGRATE_ASYNC mode and retry once.
1933 migrate_pages_batch(&split_folios, get_new_folio,
1934 put_new_folio, private, MIGRATE_ASYNC, reason,
1935 &ret_folios, NULL, &stats, 1);
1936 list_splice_tail_init(&split_folios, &ret_folios);
1939 if (!list_empty(from))
1943 * Put the permanent failure folio back to migration list, they
1944 * will be put back to the right list by the caller.
1946 list_splice(&ret_folios, from);
1949 * Return 0 in case all split folios of fail-to-migrate large folios
1950 * are migrated successfully.
1952 if (list_empty(from))
1955 count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
1956 count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
1957 count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
1958 count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
1959 count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
1960 trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
1961 stats.nr_thp_succeeded, stats.nr_thp_failed,
1962 stats.nr_thp_split, mode, reason);
1965 *ret_succeeded = stats.nr_succeeded;
1970 struct folio *alloc_migration_target(struct folio *src, unsigned long private)
1972 struct migration_target_control *mtc;
1974 unsigned int order = 0;
1978 mtc = (struct migration_target_control *)private;
1979 gfp_mask = mtc->gfp_mask;
1981 if (nid == NUMA_NO_NODE)
1982 nid = folio_nid(src);
1984 if (folio_test_hugetlb(src)) {
1985 struct hstate *h = folio_hstate(src);
1987 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1988 return alloc_hugetlb_folio_nodemask(h, nid,
1989 mtc->nmask, gfp_mask);
1992 if (folio_test_large(src)) {
1994 * clear __GFP_RECLAIM to make the migration callback
1995 * consistent with regular THP allocations.
1997 gfp_mask &= ~__GFP_RECLAIM;
1998 gfp_mask |= GFP_TRANSHUGE;
1999 order = folio_order(src);
2001 zidx = zone_idx(folio_zone(src));
2002 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
2003 gfp_mask |= __GFP_HIGHMEM;
2005 return __folio_alloc(gfp_mask, order, nid, mtc->nmask);
2010 static int store_status(int __user *status, int start, int value, int nr)
2013 if (put_user(value, status + start))
2021 static int do_move_pages_to_node(struct mm_struct *mm,
2022 struct list_head *pagelist, int node)
2025 struct migration_target_control mtc = {
2027 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
2030 err = migrate_pages(pagelist, alloc_migration_target, NULL,
2031 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
2033 putback_movable_pages(pagelist);
2038 * Resolves the given address to a struct page, isolates it from the LRU and
2039 * puts it to the given pagelist.
2041 * errno - if the page cannot be found/isolated
2042 * 0 - when it doesn't have to be migrated because it is already on the
2044 * 1 - when it has been queued
2046 static int add_page_for_migration(struct mm_struct *mm, const void __user *p,
2047 int node, struct list_head *pagelist, bool migrate_all)
2049 struct vm_area_struct *vma;
2056 addr = (unsigned long)untagged_addr_remote(mm, p);
2059 vma = vma_lookup(mm, addr);
2060 if (!vma || !vma_migratable(vma))
2063 /* FOLL_DUMP to ignore special (like zero) pages */
2064 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
2066 err = PTR_ERR(page);
2074 if (is_zone_device_page(page))
2078 if (page_to_nid(page) == node)
2082 if (page_mapcount(page) > 1 && !migrate_all)
2085 if (PageHuge(page)) {
2086 if (PageHead(page)) {
2087 isolated = isolate_hugetlb(page_folio(page), pagelist);
2088 err = isolated ? 1 : -EBUSY;
2093 head = compound_head(page);
2094 isolated = isolate_lru_page(head);
2101 list_add_tail(&head->lru, pagelist);
2102 mod_node_page_state(page_pgdat(head),
2103 NR_ISOLATED_ANON + page_is_file_lru(head),
2104 thp_nr_pages(head));
2108 * Either remove the duplicate refcount from
2109 * isolate_lru_page() or drop the page ref if it was
2114 mmap_read_unlock(mm);
2118 static int move_pages_and_store_status(struct mm_struct *mm, int node,
2119 struct list_head *pagelist, int __user *status,
2120 int start, int i, unsigned long nr_pages)
2124 if (list_empty(pagelist))
2127 err = do_move_pages_to_node(mm, pagelist, node);
2130 * Positive err means the number of failed
2131 * pages to migrate. Since we are going to
2132 * abort and return the number of non-migrated
2133 * pages, so need to include the rest of the
2134 * nr_pages that have not been attempted as
2138 err += nr_pages - i;
2141 return store_status(status, start, node, i - start);
2145 * Migrate an array of page address onto an array of nodes and fill
2146 * the corresponding array of status.
2148 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
2149 unsigned long nr_pages,
2150 const void __user * __user *pages,
2151 const int __user *nodes,
2152 int __user *status, int flags)
2154 int current_node = NUMA_NO_NODE;
2155 LIST_HEAD(pagelist);
2159 lru_cache_disable();
2161 for (i = start = 0; i < nr_pages; i++) {
2162 const void __user *p;
2166 if (get_user(p, pages + i))
2168 if (get_user(node, nodes + i))
2172 if (node < 0 || node >= MAX_NUMNODES)
2174 if (!node_state(node, N_MEMORY))
2178 if (!node_isset(node, task_nodes))
2181 if (current_node == NUMA_NO_NODE) {
2182 current_node = node;
2184 } else if (node != current_node) {
2185 err = move_pages_and_store_status(mm, current_node,
2186 &pagelist, status, start, i, nr_pages);
2190 current_node = node;
2194 * Errors in the page lookup or isolation are not fatal and we simply
2195 * report them via status
2197 err = add_page_for_migration(mm, p, current_node, &pagelist,
2198 flags & MPOL_MF_MOVE_ALL);
2201 /* The page is successfully queued for migration */
2206 * The move_pages() man page does not have an -EEXIST choice, so
2207 * use -EFAULT instead.
2213 * If the page is already on the target node (!err), store the
2214 * node, otherwise, store the err.
2216 err = store_status(status, i, err ? : current_node, 1);
2220 err = move_pages_and_store_status(mm, current_node, &pagelist,
2221 status, start, i, nr_pages);
2223 /* We have accounted for page i */
2228 current_node = NUMA_NO_NODE;
2231 /* Make sure we do not overwrite the existing error */
2232 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
2233 status, start, i, nr_pages);
2242 * Determine the nodes of an array of pages and store it in an array of status.
2244 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
2245 const void __user **pages, int *status)
2251 for (i = 0; i < nr_pages; i++) {
2252 unsigned long addr = (unsigned long)(*pages);
2253 struct vm_area_struct *vma;
2257 vma = vma_lookup(mm, addr);
2261 /* FOLL_DUMP to ignore special (like zero) pages */
2262 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
2264 err = PTR_ERR(page);
2272 if (!is_zone_device_page(page))
2273 err = page_to_nid(page);
2283 mmap_read_unlock(mm);
2286 static int get_compat_pages_array(const void __user *chunk_pages[],
2287 const void __user * __user *pages,
2288 unsigned long chunk_nr)
2290 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
2294 for (i = 0; i < chunk_nr; i++) {
2295 if (get_user(p, pages32 + i))
2297 chunk_pages[i] = compat_ptr(p);
2304 * Determine the nodes of a user array of pages and store it in
2305 * a user array of status.
2307 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
2308 const void __user * __user *pages,
2311 #define DO_PAGES_STAT_CHUNK_NR 16UL
2312 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
2313 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
2316 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
2318 if (in_compat_syscall()) {
2319 if (get_compat_pages_array(chunk_pages, pages,
2323 if (copy_from_user(chunk_pages, pages,
2324 chunk_nr * sizeof(*chunk_pages)))
2328 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
2330 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
2335 nr_pages -= chunk_nr;
2337 return nr_pages ? -EFAULT : 0;
2340 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
2342 struct task_struct *task;
2343 struct mm_struct *mm;
2346 * There is no need to check if current process has the right to modify
2347 * the specified process when they are same.
2351 *mem_nodes = cpuset_mems_allowed(current);
2355 /* Find the mm_struct */
2357 task = find_task_by_vpid(pid);
2360 return ERR_PTR(-ESRCH);
2362 get_task_struct(task);
2365 * Check if this process has the right to modify the specified
2366 * process. Use the regular "ptrace_may_access()" checks.
2368 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2370 mm = ERR_PTR(-EPERM);
2375 mm = ERR_PTR(security_task_movememory(task));
2378 *mem_nodes = cpuset_mems_allowed(task);
2379 mm = get_task_mm(task);
2381 put_task_struct(task);
2383 mm = ERR_PTR(-EINVAL);
2388 * Move a list of pages in the address space of the currently executing
2391 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2392 const void __user * __user *pages,
2393 const int __user *nodes,
2394 int __user *status, int flags)
2396 struct mm_struct *mm;
2398 nodemask_t task_nodes;
2401 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2404 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2407 mm = find_mm_struct(pid, &task_nodes);
2412 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2413 nodes, status, flags);
2415 err = do_pages_stat(mm, nr_pages, pages, status);
2421 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2422 const void __user * __user *, pages,
2423 const int __user *, nodes,
2424 int __user *, status, int, flags)
2426 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2429 #ifdef CONFIG_NUMA_BALANCING
2431 * Returns true if this is a safe migration target node for misplaced NUMA
2432 * pages. Currently it only checks the watermarks which is crude.
2434 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2435 unsigned long nr_migrate_pages)
2439 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2440 struct zone *zone = pgdat->node_zones + z;
2442 if (!managed_zone(zone))
2445 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2446 if (!zone_watermark_ok(zone, 0,
2447 high_wmark_pages(zone) +
2456 static struct folio *alloc_misplaced_dst_folio(struct folio *src,
2459 int nid = (int) data;
2460 int order = folio_order(src);
2461 gfp_t gfp = __GFP_THISNODE;
2464 gfp |= GFP_TRANSHUGE_LIGHT;
2466 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2468 gfp &= ~__GFP_RECLAIM;
2470 return __folio_alloc_node(gfp, order, nid);
2473 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2475 int nr_pages = thp_nr_pages(page);
2476 int order = compound_order(page);
2478 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2480 /* Do not migrate THP mapped by multiple processes */
2481 if (PageTransHuge(page) && total_mapcount(page) > 1)
2484 /* Avoid migrating to a node that is nearly full */
2485 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2488 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2490 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2491 if (managed_zone(pgdat->node_zones + z))
2494 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2498 if (!isolate_lru_page(page))
2501 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2505 * Isolating the page has taken another reference, so the
2506 * caller's reference can be safely dropped without the page
2507 * disappearing underneath us during migration.
2514 * Attempt to migrate a misplaced page to the specified destination
2515 * node. Caller is expected to have an elevated reference count on
2516 * the page that will be dropped by this function before returning.
2518 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2521 pg_data_t *pgdat = NODE_DATA(node);
2524 unsigned int nr_succeeded;
2525 LIST_HEAD(migratepages);
2526 int nr_pages = thp_nr_pages(page);
2529 * Don't migrate file pages that are mapped in multiple processes
2530 * with execute permissions as they are probably shared libraries.
2532 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2533 (vma->vm_flags & VM_EXEC))
2537 * Also do not migrate dirty pages as not all filesystems can move
2538 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2540 if (page_is_file_lru(page) && PageDirty(page))
2543 isolated = numamigrate_isolate_page(pgdat, page);
2547 list_add(&page->lru, &migratepages);
2548 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_folio,
2549 NULL, node, MIGRATE_ASYNC,
2550 MR_NUMA_MISPLACED, &nr_succeeded);
2552 if (!list_empty(&migratepages)) {
2553 list_del(&page->lru);
2554 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2555 page_is_file_lru(page), -nr_pages);
2556 putback_lru_page(page);
2561 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2562 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2563 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2566 BUG_ON(!list_empty(&migratepages));
2573 #endif /* CONFIG_NUMA_BALANCING */
2574 #endif /* CONFIG_NUMA */