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:
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)
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
333 * The vma read lock must be held upon entry. Holding that lock prevents either
334 * the pte or the ptl from being freed.
336 * This function will release the vma lock before returning.
338 void __migration_entry_wait_huge(struct vm_area_struct *vma,
339 pte_t *ptep, spinlock_t *ptl)
343 hugetlb_vma_assert_locked(vma);
345 pte = huge_ptep_get(ptep);
347 if (unlikely(!is_hugetlb_entry_migration(pte))) {
349 hugetlb_vma_unlock_read(vma);
352 * If migration entry existed, safe to release vma lock
353 * here because the pgtable page won't be freed without the
354 * pgtable lock released. See comment right above pgtable
355 * lock release in migration_entry_wait_on_locked().
357 hugetlb_vma_unlock_read(vma);
358 migration_entry_wait_on_locked(pte_to_swp_entry(pte), NULL, ptl);
362 void migration_entry_wait_huge(struct vm_area_struct *vma, pte_t *pte)
364 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, pte);
366 __migration_entry_wait_huge(vma, pte, ptl);
370 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
371 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
375 ptl = pmd_lock(mm, pmd);
376 if (!is_pmd_migration_entry(*pmd))
378 migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
385 static int folio_expected_refs(struct address_space *mapping,
392 refs += folio_nr_pages(folio);
393 if (folio_test_private(folio))
400 * Replace the page in the mapping.
402 * The number of remaining references must be:
403 * 1 for anonymous pages without a mapping
404 * 2 for pages with a mapping
405 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
407 int folio_migrate_mapping(struct address_space *mapping,
408 struct folio *newfolio, struct folio *folio, int extra_count)
410 XA_STATE(xas, &mapping->i_pages, folio_index(folio));
411 struct zone *oldzone, *newzone;
413 int expected_count = folio_expected_refs(mapping, folio) + extra_count;
414 long nr = folio_nr_pages(folio);
417 /* Anonymous page without mapping */
418 if (folio_ref_count(folio) != expected_count)
421 /* No turning back from here */
422 newfolio->index = folio->index;
423 newfolio->mapping = folio->mapping;
424 if (folio_test_swapbacked(folio))
425 __folio_set_swapbacked(newfolio);
427 return MIGRATEPAGE_SUCCESS;
430 oldzone = folio_zone(folio);
431 newzone = folio_zone(newfolio);
434 if (!folio_ref_freeze(folio, expected_count)) {
435 xas_unlock_irq(&xas);
440 * Now we know that no one else is looking at the folio:
441 * no turning back from here.
443 newfolio->index = folio->index;
444 newfolio->mapping = folio->mapping;
445 folio_ref_add(newfolio, nr); /* add cache reference */
446 if (folio_test_swapbacked(folio)) {
447 __folio_set_swapbacked(newfolio);
448 if (folio_test_swapcache(folio)) {
449 folio_set_swapcache(newfolio);
450 newfolio->private = folio_get_private(folio);
453 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
456 /* Move dirty while page refs frozen and newpage not yet exposed */
457 dirty = folio_test_dirty(folio);
459 folio_clear_dirty(folio);
460 folio_set_dirty(newfolio);
463 xas_store(&xas, newfolio);
466 * Drop cache reference from old page by unfreezing
467 * to one less reference.
468 * We know this isn't the last reference.
470 folio_ref_unfreeze(folio, expected_count - nr);
473 /* Leave irq disabled to prevent preemption while updating stats */
476 * If moved to a different zone then also account
477 * the page for that zone. Other VM counters will be
478 * taken care of when we establish references to the
479 * new page and drop references to the old page.
481 * Note that anonymous pages are accounted for
482 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
483 * are mapped to swap space.
485 if (newzone != oldzone) {
486 struct lruvec *old_lruvec, *new_lruvec;
487 struct mem_cgroup *memcg;
489 memcg = folio_memcg(folio);
490 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
491 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
493 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
494 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
495 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
496 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
497 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
500 if (folio_test_swapcache(folio)) {
501 __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
502 __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
505 if (dirty && mapping_can_writeback(mapping)) {
506 __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
507 __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
508 __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
509 __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
514 return MIGRATEPAGE_SUCCESS;
516 EXPORT_SYMBOL(folio_migrate_mapping);
519 * The expected number of remaining references is the same as that
520 * of folio_migrate_mapping().
522 int migrate_huge_page_move_mapping(struct address_space *mapping,
523 struct folio *dst, struct folio *src)
525 XA_STATE(xas, &mapping->i_pages, folio_index(src));
529 expected_count = 2 + folio_has_private(src);
530 if (!folio_ref_freeze(src, expected_count)) {
531 xas_unlock_irq(&xas);
535 dst->index = src->index;
536 dst->mapping = src->mapping;
540 xas_store(&xas, dst);
542 folio_ref_unfreeze(src, expected_count - 1);
544 xas_unlock_irq(&xas);
546 return MIGRATEPAGE_SUCCESS;
550 * Copy the flags and some other ancillary information
552 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
556 if (folio_test_error(folio))
557 folio_set_error(newfolio);
558 if (folio_test_referenced(folio))
559 folio_set_referenced(newfolio);
560 if (folio_test_uptodate(folio))
561 folio_mark_uptodate(newfolio);
562 if (folio_test_clear_active(folio)) {
563 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
564 folio_set_active(newfolio);
565 } else if (folio_test_clear_unevictable(folio))
566 folio_set_unevictable(newfolio);
567 if (folio_test_workingset(folio))
568 folio_set_workingset(newfolio);
569 if (folio_test_checked(folio))
570 folio_set_checked(newfolio);
572 * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
573 * migration entries. We can still have PG_anon_exclusive set on an
574 * effectively unmapped and unreferenced first sub-pages of an
575 * anonymous THP: we can simply copy it here via PG_mappedtodisk.
577 if (folio_test_mappedtodisk(folio))
578 folio_set_mappedtodisk(newfolio);
580 /* Move dirty on pages not done by folio_migrate_mapping() */
581 if (folio_test_dirty(folio))
582 folio_set_dirty(newfolio);
584 if (folio_test_young(folio))
585 folio_set_young(newfolio);
586 if (folio_test_idle(folio))
587 folio_set_idle(newfolio);
590 * Copy NUMA information to the new page, to prevent over-eager
591 * future migrations of this same page.
593 cpupid = page_cpupid_xchg_last(&folio->page, -1);
595 * For memory tiering mode, when migrate between slow and fast
596 * memory node, reset cpupid, because that is used to record
597 * page access time in slow memory node.
599 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
600 bool f_toptier = node_is_toptier(page_to_nid(&folio->page));
601 bool t_toptier = node_is_toptier(page_to_nid(&newfolio->page));
603 if (f_toptier != t_toptier)
606 page_cpupid_xchg_last(&newfolio->page, cpupid);
608 folio_migrate_ksm(newfolio, folio);
610 * Please do not reorder this without considering how mm/ksm.c's
611 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
613 if (folio_test_swapcache(folio))
614 folio_clear_swapcache(folio);
615 folio_clear_private(folio);
617 /* page->private contains hugetlb specific flags */
618 if (!folio_test_hugetlb(folio))
619 folio->private = NULL;
622 * If any waiters have accumulated on the new page then
625 if (folio_test_writeback(newfolio))
626 folio_end_writeback(newfolio);
629 * PG_readahead shares the same bit with PG_reclaim. The above
630 * end_page_writeback() may clear PG_readahead mistakenly, so set the
633 if (folio_test_readahead(folio))
634 folio_set_readahead(newfolio);
636 folio_copy_owner(newfolio, folio);
638 if (!folio_test_hugetlb(folio))
639 mem_cgroup_migrate(folio, newfolio);
641 EXPORT_SYMBOL(folio_migrate_flags);
643 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
645 folio_copy(newfolio, folio);
646 folio_migrate_flags(newfolio, folio);
648 EXPORT_SYMBOL(folio_migrate_copy);
650 /************************************************************
651 * Migration functions
652 ***********************************************************/
654 int migrate_folio_extra(struct address_space *mapping, struct folio *dst,
655 struct folio *src, enum migrate_mode mode, int extra_count)
659 BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
661 rc = folio_migrate_mapping(mapping, dst, src, extra_count);
663 if (rc != MIGRATEPAGE_SUCCESS)
666 if (mode != MIGRATE_SYNC_NO_COPY)
667 folio_migrate_copy(dst, src);
669 folio_migrate_flags(dst, src);
670 return MIGRATEPAGE_SUCCESS;
674 * migrate_folio() - Simple folio migration.
675 * @mapping: The address_space containing the folio.
676 * @dst: The folio to migrate the data to.
677 * @src: The folio containing the current data.
678 * @mode: How to migrate the page.
680 * Common logic to directly migrate a single LRU folio suitable for
681 * folios that do not use PagePrivate/PagePrivate2.
683 * Folios are locked upon entry and exit.
685 int migrate_folio(struct address_space *mapping, struct folio *dst,
686 struct folio *src, enum migrate_mode mode)
688 return migrate_folio_extra(mapping, dst, src, mode, 0);
690 EXPORT_SYMBOL(migrate_folio);
693 /* Returns true if all buffers are successfully locked */
694 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
695 enum migrate_mode mode)
697 struct buffer_head *bh = head;
699 /* Simple case, sync compaction */
700 if (mode != MIGRATE_ASYNC) {
703 bh = bh->b_this_page;
705 } while (bh != head);
710 /* async case, we cannot block on lock_buffer so use trylock_buffer */
712 if (!trylock_buffer(bh)) {
714 * We failed to lock the buffer and cannot stall in
715 * async migration. Release the taken locks
717 struct buffer_head *failed_bh = bh;
719 while (bh != failed_bh) {
721 bh = bh->b_this_page;
726 bh = bh->b_this_page;
727 } while (bh != head);
731 static int __buffer_migrate_folio(struct address_space *mapping,
732 struct folio *dst, struct folio *src, enum migrate_mode mode,
735 struct buffer_head *bh, *head;
739 head = folio_buffers(src);
741 return migrate_folio(mapping, dst, src, mode);
743 /* Check whether page does not have extra refs before we do more work */
744 expected_count = folio_expected_refs(mapping, src);
745 if (folio_ref_count(src) != expected_count)
748 if (!buffer_migrate_lock_buffers(head, mode))
753 bool invalidated = false;
757 spin_lock(&mapping->private_lock);
760 if (atomic_read(&bh->b_count)) {
764 bh = bh->b_this_page;
765 } while (bh != head);
771 spin_unlock(&mapping->private_lock);
772 invalidate_bh_lrus();
774 goto recheck_buffers;
778 rc = folio_migrate_mapping(mapping, dst, src, 0);
779 if (rc != MIGRATEPAGE_SUCCESS)
782 folio_attach_private(dst, folio_detach_private(src));
786 set_bh_page(bh, &dst->page, bh_offset(bh));
787 bh = bh->b_this_page;
788 } while (bh != head);
790 if (mode != MIGRATE_SYNC_NO_COPY)
791 folio_migrate_copy(dst, src);
793 folio_migrate_flags(dst, src);
795 rc = MIGRATEPAGE_SUCCESS;
798 spin_unlock(&mapping->private_lock);
802 bh = bh->b_this_page;
803 } while (bh != head);
809 * buffer_migrate_folio() - Migration function for folios with buffers.
810 * @mapping: The address space containing @src.
811 * @dst: The folio to migrate to.
812 * @src: The folio to migrate from.
813 * @mode: How to migrate the folio.
815 * This function can only be used if the underlying filesystem guarantees
816 * that no other references to @src exist. For example attached buffer
817 * heads are accessed only under the folio lock. If your filesystem cannot
818 * provide this guarantee, buffer_migrate_folio_norefs() may be more
821 * Return: 0 on success or a negative errno on failure.
823 int buffer_migrate_folio(struct address_space *mapping,
824 struct folio *dst, struct folio *src, enum migrate_mode mode)
826 return __buffer_migrate_folio(mapping, dst, src, mode, false);
828 EXPORT_SYMBOL(buffer_migrate_folio);
831 * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
832 * @mapping: The address space containing @src.
833 * @dst: The folio to migrate to.
834 * @src: The folio to migrate from.
835 * @mode: How to migrate the folio.
837 * Like buffer_migrate_folio() except that this variant is more careful
838 * and checks that there are also no buffer head references. This function
839 * is the right one for mappings where buffer heads are directly looked
840 * up and referenced (such as block device mappings).
842 * Return: 0 on success or a negative errno on failure.
844 int buffer_migrate_folio_norefs(struct address_space *mapping,
845 struct folio *dst, struct folio *src, enum migrate_mode mode)
847 return __buffer_migrate_folio(mapping, dst, src, mode, true);
849 EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
852 int filemap_migrate_folio(struct address_space *mapping,
853 struct folio *dst, struct folio *src, enum migrate_mode mode)
857 ret = folio_migrate_mapping(mapping, dst, src, 0);
858 if (ret != MIGRATEPAGE_SUCCESS)
861 if (folio_get_private(src))
862 folio_attach_private(dst, folio_detach_private(src));
864 if (mode != MIGRATE_SYNC_NO_COPY)
865 folio_migrate_copy(dst, src);
867 folio_migrate_flags(dst, src);
868 return MIGRATEPAGE_SUCCESS;
870 EXPORT_SYMBOL_GPL(filemap_migrate_folio);
873 * Writeback a folio to clean the dirty state
875 static int writeout(struct address_space *mapping, struct folio *folio)
877 struct writeback_control wbc = {
878 .sync_mode = WB_SYNC_NONE,
881 .range_end = LLONG_MAX,
886 if (!mapping->a_ops->writepage)
887 /* No write method for the address space */
890 if (!folio_clear_dirty_for_io(folio))
891 /* Someone else already triggered a write */
895 * A dirty folio may imply that the underlying filesystem has
896 * the folio on some queue. So the folio must be clean for
897 * migration. Writeout may mean we lose the lock and the
898 * folio state is no longer what we checked for earlier.
899 * At this point we know that the migration attempt cannot
902 remove_migration_ptes(folio, folio, false);
904 rc = mapping->a_ops->writepage(&folio->page, &wbc);
906 if (rc != AOP_WRITEPAGE_ACTIVATE)
907 /* unlocked. Relock */
910 return (rc < 0) ? -EIO : -EAGAIN;
914 * Default handling if a filesystem does not provide a migration function.
916 static int fallback_migrate_folio(struct address_space *mapping,
917 struct folio *dst, struct folio *src, enum migrate_mode mode)
919 if (folio_test_dirty(src)) {
920 /* Only writeback folios in full synchronous migration */
923 case MIGRATE_SYNC_NO_COPY:
928 return writeout(mapping, src);
932 * Buffers may be managed in a filesystem specific way.
933 * We must have no buffers or drop them.
935 if (folio_test_private(src) &&
936 !filemap_release_folio(src, GFP_KERNEL))
937 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
939 return migrate_folio(mapping, dst, src, mode);
943 * Move a page to a newly allocated page
944 * The page is locked and all ptes have been successfully removed.
946 * The new page will have replaced the old page if this function
951 * MIGRATEPAGE_SUCCESS - success
953 static int move_to_new_folio(struct folio *dst, struct folio *src,
954 enum migrate_mode mode)
957 bool is_lru = !__PageMovable(&src->page);
959 VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
960 VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
962 if (likely(is_lru)) {
963 struct address_space *mapping = folio_mapping(src);
966 rc = migrate_folio(mapping, dst, src, mode);
967 else if (mapping->a_ops->migrate_folio)
969 * Most folios have a mapping and most filesystems
970 * provide a migrate_folio callback. Anonymous folios
971 * are part of swap space which also has its own
972 * migrate_folio callback. This is the most common path
973 * for page migration.
975 rc = mapping->a_ops->migrate_folio(mapping, dst, src,
978 rc = fallback_migrate_folio(mapping, dst, src, mode);
980 const struct movable_operations *mops;
983 * In case of non-lru page, it could be released after
984 * isolation step. In that case, we shouldn't try migration.
986 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
987 if (!folio_test_movable(src)) {
988 rc = MIGRATEPAGE_SUCCESS;
989 folio_clear_isolated(src);
993 mops = page_movable_ops(&src->page);
994 rc = mops->migrate_page(&dst->page, &src->page, mode);
995 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
996 !folio_test_isolated(src));
1000 * When successful, old pagecache src->mapping must be cleared before
1001 * src is freed; but stats require that PageAnon be left as PageAnon.
1003 if (rc == MIGRATEPAGE_SUCCESS) {
1004 if (__PageMovable(&src->page)) {
1005 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
1008 * We clear PG_movable under page_lock so any compactor
1009 * cannot try to migrate this page.
1011 folio_clear_isolated(src);
1015 * Anonymous and movable src->mapping will be cleared by
1016 * free_pages_prepare so don't reset it here for keeping
1017 * the type to work PageAnon, for example.
1019 if (!folio_mapping_flags(src))
1020 src->mapping = NULL;
1022 if (likely(!folio_is_zone_device(dst)))
1023 flush_dcache_folio(dst);
1029 static int __unmap_and_move(struct folio *src, struct folio *dst,
1030 int force, enum migrate_mode mode)
1033 bool page_was_mapped = false;
1034 struct anon_vma *anon_vma = NULL;
1035 bool is_lru = !__PageMovable(&src->page);
1037 if (!folio_trylock(src)) {
1038 if (!force || mode == MIGRATE_ASYNC)
1042 * It's not safe for direct compaction to call lock_page.
1043 * For example, during page readahead pages are added locked
1044 * to the LRU. Later, when the IO completes the pages are
1045 * marked uptodate and unlocked. However, the queueing
1046 * could be merging multiple pages for one bio (e.g.
1047 * mpage_readahead). If an allocation happens for the
1048 * second or third page, the process can end up locking
1049 * the same page twice and deadlocking. Rather than
1050 * trying to be clever about what pages can be locked,
1051 * avoid the use of lock_page for direct compaction
1054 if (current->flags & PF_MEMALLOC)
1060 if (folio_test_writeback(src)) {
1062 * Only in the case of a full synchronous migration is it
1063 * necessary to wait for PageWriteback. In the async case,
1064 * the retry loop is too short and in the sync-light case,
1065 * the overhead of stalling is too much
1069 case MIGRATE_SYNC_NO_COPY:
1077 folio_wait_writeback(src);
1081 * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
1082 * we cannot notice that anon_vma is freed while we migrate a page.
1083 * This get_anon_vma() delays freeing anon_vma pointer until the end
1084 * of migration. File cache pages are no problem because of page_lock()
1085 * File Caches may use write_page() or lock_page() in migration, then,
1086 * just care Anon page here.
1088 * Only folio_get_anon_vma() understands the subtleties of
1089 * getting a hold on an anon_vma from outside one of its mms.
1090 * But if we cannot get anon_vma, then we won't need it anyway,
1091 * because that implies that the anon page is no longer mapped
1092 * (and cannot be remapped so long as we hold the page lock).
1094 if (folio_test_anon(src) && !folio_test_ksm(src))
1095 anon_vma = folio_get_anon_vma(src);
1098 * Block others from accessing the new page when we get around to
1099 * establishing additional references. We are usually the only one
1100 * holding a reference to dst at this point. We used to have a BUG
1101 * here if folio_trylock(dst) fails, but would like to allow for
1102 * cases where there might be a race with the previous use of dst.
1103 * This is much like races on refcount of oldpage: just don't BUG().
1105 if (unlikely(!folio_trylock(dst)))
1108 if (unlikely(!is_lru)) {
1109 rc = move_to_new_folio(dst, src, mode);
1110 goto out_unlock_both;
1114 * Corner case handling:
1115 * 1. When a new swap-cache page is read into, it is added to the LRU
1116 * and treated as swapcache but it has no rmap yet.
1117 * Calling try_to_unmap() against a src->mapping==NULL page will
1118 * trigger a BUG. So handle it here.
1119 * 2. An orphaned page (see truncate_cleanup_page) might have
1120 * fs-private metadata. The page can be picked up due to memory
1121 * offlining. Everywhere else except page reclaim, the page is
1122 * invisible to the vm, so the page can not be migrated. So try to
1123 * free the metadata, so the page can be freed.
1125 if (!src->mapping) {
1126 if (folio_test_private(src)) {
1127 try_to_free_buffers(src);
1128 goto out_unlock_both;
1130 } else if (folio_mapped(src)) {
1131 /* Establish migration ptes */
1132 VM_BUG_ON_FOLIO(folio_test_anon(src) &&
1133 !folio_test_ksm(src) && !anon_vma, src);
1134 try_to_migrate(src, 0);
1135 page_was_mapped = true;
1138 if (!folio_mapped(src))
1139 rc = move_to_new_folio(dst, src, mode);
1142 * When successful, push dst to LRU immediately: so that if it
1143 * turns out to be an mlocked page, remove_migration_ptes() will
1144 * automatically build up the correct dst->mlock_count for it.
1146 * We would like to do something similar for the old page, when
1147 * unsuccessful, and other cases when a page has been temporarily
1148 * isolated from the unevictable LRU: but this case is the easiest.
1150 if (rc == MIGRATEPAGE_SUCCESS) {
1152 if (page_was_mapped)
1156 if (page_was_mapped)
1157 remove_migration_ptes(src,
1158 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1163 /* Drop an anon_vma reference if we took one */
1165 put_anon_vma(anon_vma);
1169 * If migration is successful, decrease refcount of dst,
1170 * which will not free the page because new page owner increased
1173 if (rc == MIGRATEPAGE_SUCCESS)
1180 * Obtain the lock on folio, remove all ptes and migrate the folio
1181 * to the newly allocated folio in dst.
1183 static int unmap_and_move(new_page_t get_new_page,
1184 free_page_t put_new_page,
1185 unsigned long private, struct folio *src,
1186 int force, enum migrate_mode mode,
1187 enum migrate_reason reason,
1188 struct list_head *ret)
1191 int rc = MIGRATEPAGE_SUCCESS;
1192 struct page *newpage = NULL;
1194 if (!thp_migration_supported() && folio_test_transhuge(src))
1197 if (folio_ref_count(src) == 1) {
1198 /* Folio was freed from under us. So we are done. */
1199 folio_clear_active(src);
1200 folio_clear_unevictable(src);
1201 /* free_pages_prepare() will clear PG_isolated. */
1205 newpage = get_new_page(&src->page, private);
1208 dst = page_folio(newpage);
1210 dst->private = NULL;
1211 rc = __unmap_and_move(src, dst, force, mode);
1212 if (rc == MIGRATEPAGE_SUCCESS)
1213 set_page_owner_migrate_reason(&dst->page, reason);
1216 if (rc != -EAGAIN) {
1218 * A folio that has been migrated has all references
1219 * removed and will be freed. A folio that has not been
1220 * migrated will have kept its references and be restored.
1222 list_del(&src->lru);
1226 * If migration is successful, releases reference grabbed during
1227 * isolation. Otherwise, restore the folio to right list unless
1230 if (rc == MIGRATEPAGE_SUCCESS) {
1232 * Compaction can migrate also non-LRU folios which are
1233 * not accounted to NR_ISOLATED_*. They can be recognized
1234 * as __folio_test_movable
1236 if (likely(!__folio_test_movable(src)))
1237 mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
1238 folio_is_file_lru(src), -folio_nr_pages(src));
1240 if (reason != MR_MEMORY_FAILURE)
1242 * We release the folio in page_handle_poison.
1247 list_add_tail(&src->lru, ret);
1250 put_new_page(&dst->page, private);
1259 * Counterpart of unmap_and_move_page() for hugepage migration.
1261 * This function doesn't wait the completion of hugepage I/O
1262 * because there is no race between I/O and migration for hugepage.
1263 * Note that currently hugepage I/O occurs only in direct I/O
1264 * where no lock is held and PG_writeback is irrelevant,
1265 * and writeback status of all subpages are counted in the reference
1266 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1267 * under direct I/O, the reference of the head page is 512 and a bit more.)
1268 * This means that when we try to migrate hugepage whose subpages are
1269 * doing direct I/O, some references remain after try_to_unmap() and
1270 * hugepage migration fails without data corruption.
1272 * There is also no race when direct I/O is issued on the page under migration,
1273 * because then pte is replaced with migration swap entry and direct I/O code
1274 * will wait in the page fault for migration to complete.
1276 static int unmap_and_move_huge_page(new_page_t get_new_page,
1277 free_page_t put_new_page, unsigned long private,
1278 struct page *hpage, int force,
1279 enum migrate_mode mode, int reason,
1280 struct list_head *ret)
1282 struct folio *dst, *src = page_folio(hpage);
1284 int page_was_mapped = 0;
1285 struct page *new_hpage;
1286 struct anon_vma *anon_vma = NULL;
1287 struct address_space *mapping = NULL;
1290 * Migratability of hugepages depends on architectures and their size.
1291 * This check is necessary because some callers of hugepage migration
1292 * like soft offline and memory hotremove don't walk through page
1293 * tables or check whether the hugepage is pmd-based or not before
1294 * kicking migration.
1296 if (!hugepage_migration_supported(page_hstate(hpage)))
1299 if (folio_ref_count(src) == 1) {
1300 /* page was freed from under us. So we are done. */
1301 putback_active_hugepage(hpage);
1302 return MIGRATEPAGE_SUCCESS;
1305 new_hpage = get_new_page(hpage, private);
1308 dst = page_folio(new_hpage);
1310 if (!folio_trylock(src)) {
1315 case MIGRATE_SYNC_NO_COPY:
1324 * Check for pages which are in the process of being freed. Without
1325 * folio_mapping() set, hugetlbfs specific move page routine will not
1326 * be called and we could leak usage counts for subpools.
1328 if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
1333 if (folio_test_anon(src))
1334 anon_vma = folio_get_anon_vma(src);
1336 if (unlikely(!folio_trylock(dst)))
1339 if (folio_mapped(src)) {
1340 enum ttu_flags ttu = 0;
1342 if (!folio_test_anon(src)) {
1344 * In shared mappings, try_to_unmap could potentially
1345 * call huge_pmd_unshare. Because of this, take
1346 * semaphore in write mode here and set TTU_RMAP_LOCKED
1347 * to let lower levels know we have taken the lock.
1349 mapping = hugetlb_page_mapping_lock_write(hpage);
1350 if (unlikely(!mapping))
1351 goto unlock_put_anon;
1353 ttu = TTU_RMAP_LOCKED;
1356 try_to_migrate(src, ttu);
1357 page_was_mapped = 1;
1359 if (ttu & TTU_RMAP_LOCKED)
1360 i_mmap_unlock_write(mapping);
1363 if (!folio_mapped(src))
1364 rc = move_to_new_folio(dst, src, mode);
1366 if (page_was_mapped)
1367 remove_migration_ptes(src,
1368 rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1375 put_anon_vma(anon_vma);
1377 if (rc == MIGRATEPAGE_SUCCESS) {
1378 move_hugetlb_state(src, dst, reason);
1379 put_new_page = NULL;
1385 if (rc == MIGRATEPAGE_SUCCESS)
1386 putback_active_hugepage(hpage);
1387 else if (rc != -EAGAIN)
1388 list_move_tail(&src->lru, ret);
1391 * If migration was not successful and there's a freeing callback, use
1392 * it. Otherwise, put_page() will drop the reference grabbed during
1396 put_new_page(new_hpage, private);
1398 putback_active_hugepage(new_hpage);
1403 static inline int try_split_folio(struct folio *folio, struct list_head *split_folios)
1408 rc = split_folio_to_list(folio, split_folios);
1409 folio_unlock(folio);
1411 list_move_tail(&folio->lru, split_folios);
1417 * migrate_pages - migrate the folios specified in a list, to the free folios
1418 * supplied as the target for the page migration
1420 * @from: The list of folios to be migrated.
1421 * @get_new_page: The function used to allocate free folios to be used
1422 * as the target of the folio migration.
1423 * @put_new_page: The function used to free target folios if migration
1424 * fails, or NULL if no special handling is necessary.
1425 * @private: Private data to be passed on to get_new_page()
1426 * @mode: The migration mode that specifies the constraints for
1427 * folio migration, if any.
1428 * @reason: The reason for folio migration.
1429 * @ret_succeeded: Set to the number of folios migrated successfully if
1430 * the caller passes a non-NULL pointer.
1432 * The function returns after 10 attempts or if no folios are movable any more
1433 * because the list has become empty or no retryable folios exist any more.
1434 * It is caller's responsibility to call putback_movable_pages() to return folios
1435 * to the LRU or free list only if ret != 0.
1437 * Returns the number of {normal folio, large folio, hugetlb} that were not
1438 * migrated, or an error code. The number of large folio splits will be
1439 * considered as the number of non-migrated large folio, no matter how many
1440 * split folios of the large folio are migrated successfully.
1442 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1443 free_page_t put_new_page, unsigned long private,
1444 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1447 int large_retry = 1;
1450 int nr_failed_pages = 0;
1451 int nr_retry_pages = 0;
1452 int nr_succeeded = 0;
1453 int nr_thp_succeeded = 0;
1454 int nr_large_failed = 0;
1455 int nr_thp_failed = 0;
1456 int nr_thp_split = 0;
1458 bool is_large = false;
1459 bool is_thp = false;
1460 struct folio *folio, *folio2;
1462 LIST_HEAD(ret_folios);
1463 LIST_HEAD(split_folios);
1464 bool nosplit = (reason == MR_NUMA_MISPLACED);
1465 bool no_split_folio_counting = false;
1467 trace_mm_migrate_pages_start(mode, reason);
1469 split_folio_migration:
1470 for (pass = 0; pass < 10 && (retry || large_retry); pass++) {
1476 list_for_each_entry_safe(folio, folio2, from, lru) {
1478 * Large folio statistics is based on the source large
1479 * folio. Capture required information that might get
1480 * lost during migration.
1482 is_large = folio_test_large(folio) && !folio_test_hugetlb(folio);
1483 is_thp = is_large && folio_test_pmd_mappable(folio);
1484 nr_pages = folio_nr_pages(folio);
1487 if (folio_test_hugetlb(folio))
1488 rc = unmap_and_move_huge_page(get_new_page,
1489 put_new_page, private,
1490 &folio->page, pass > 2, mode,
1494 rc = unmap_and_move(get_new_page, put_new_page,
1495 private, folio, pass > 2, mode,
1496 reason, &ret_folios);
1499 * Success: non hugetlb folio will be freed, hugetlb
1500 * folio will be put back
1501 * -EAGAIN: stay on the from list
1502 * -ENOMEM: stay on the from list
1503 * -ENOSYS: stay on the from list
1504 * Other errno: put on ret_folios list then splice to
1509 * Large folio migration might be unsupported or
1510 * the allocation could've failed so we should retry
1511 * on the same folio with the large folio split
1514 * Split folios are put in split_folios, and
1515 * we will migrate them after the rest of the
1516 * list is processed.
1519 /* Large folio migration is unsupported */
1522 nr_thp_failed += is_thp;
1523 if (!try_split_folio(folio, &split_folios)) {
1524 nr_thp_split += is_thp;
1527 /* Hugetlb migration is unsupported */
1528 } else if (!no_split_folio_counting) {
1532 nr_failed_pages += nr_pages;
1533 list_move_tail(&folio->lru, &ret_folios);
1537 * When memory is low, don't bother to try to migrate
1538 * other folios, just exit.
1542 nr_thp_failed += is_thp;
1543 /* Large folio NUMA faulting doesn't split to retry. */
1545 int ret = try_split_folio(folio, &split_folios);
1548 nr_thp_split += is_thp;
1550 } else if (reason == MR_LONGTERM_PIN &&
1553 * Try again to split large folio to
1554 * mitigate the failure of longterm pinning.
1557 thp_retry += is_thp;
1558 nr_retry_pages += nr_pages;
1562 } else if (!no_split_folio_counting) {
1566 nr_failed_pages += nr_pages + nr_retry_pages;
1568 * There might be some split folios of fail-to-migrate large
1569 * folios left in split_folios list. Move them back to migration
1570 * list so that they could be put back to the right list by
1571 * the caller otherwise the folio refcnt will be leaked.
1573 list_splice_init(&split_folios, from);
1574 /* nr_failed isn't updated for not used */
1575 nr_large_failed += large_retry;
1576 nr_thp_failed += thp_retry;
1581 thp_retry += is_thp;
1582 } else if (!no_split_folio_counting) {
1585 nr_retry_pages += nr_pages;
1587 case MIGRATEPAGE_SUCCESS:
1588 nr_succeeded += nr_pages;
1589 nr_thp_succeeded += is_thp;
1593 * Permanent failure (-EBUSY, etc.):
1594 * unlike -EAGAIN case, the failed folio is
1595 * removed from migration folio list and not
1596 * retried in the next outer loop.
1600 nr_thp_failed += is_thp;
1601 } else if (!no_split_folio_counting) {
1605 nr_failed_pages += nr_pages;
1611 nr_large_failed += large_retry;
1612 nr_thp_failed += thp_retry;
1613 nr_failed_pages += nr_retry_pages;
1615 * Try to migrate split folios of fail-to-migrate large folios, no
1616 * nr_failed counting in this round, since all split folios of a
1617 * large folio is counted as 1 failure in the first round.
1619 if (!list_empty(&split_folios)) {
1621 * Move non-migrated folios (after 10 retries) to ret_folios
1622 * to avoid migrating them again.
1624 list_splice_init(from, &ret_folios);
1625 list_splice_init(&split_folios, from);
1626 no_split_folio_counting = true;
1628 goto split_folio_migration;
1631 rc = nr_failed + nr_large_failed;
1634 * Put the permanent failure folio back to migration list, they
1635 * will be put back to the right list by the caller.
1637 list_splice(&ret_folios, from);
1640 * Return 0 in case all split folios of fail-to-migrate large folios
1641 * are migrated successfully.
1643 if (list_empty(from))
1646 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1647 count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1648 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1649 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1650 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1651 trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1652 nr_thp_failed, nr_thp_split, mode, reason);
1655 *ret_succeeded = nr_succeeded;
1660 struct page *alloc_migration_target(struct page *page, unsigned long private)
1662 struct folio *folio = page_folio(page);
1663 struct migration_target_control *mtc;
1665 unsigned int order = 0;
1666 struct folio *new_folio = NULL;
1670 mtc = (struct migration_target_control *)private;
1671 gfp_mask = mtc->gfp_mask;
1673 if (nid == NUMA_NO_NODE)
1674 nid = folio_nid(folio);
1676 if (folio_test_hugetlb(folio)) {
1677 struct hstate *h = folio_hstate(folio);
1679 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1680 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1683 if (folio_test_large(folio)) {
1685 * clear __GFP_RECLAIM to make the migration callback
1686 * consistent with regular THP allocations.
1688 gfp_mask &= ~__GFP_RECLAIM;
1689 gfp_mask |= GFP_TRANSHUGE;
1690 order = folio_order(folio);
1692 zidx = zone_idx(folio_zone(folio));
1693 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1694 gfp_mask |= __GFP_HIGHMEM;
1696 new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
1698 return &new_folio->page;
1703 static int store_status(int __user *status, int start, int value, int nr)
1706 if (put_user(value, status + start))
1714 static int do_move_pages_to_node(struct mm_struct *mm,
1715 struct list_head *pagelist, int node)
1718 struct migration_target_control mtc = {
1720 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1723 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1724 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1726 putback_movable_pages(pagelist);
1731 * Resolves the given address to a struct page, isolates it from the LRU and
1732 * puts it to the given pagelist.
1734 * errno - if the page cannot be found/isolated
1735 * 0 - when it doesn't have to be migrated because it is already on the
1737 * 1 - when it has been queued
1739 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1740 int node, struct list_head *pagelist, bool migrate_all)
1742 struct vm_area_struct *vma;
1748 vma = vma_lookup(mm, addr);
1749 if (!vma || !vma_migratable(vma))
1752 /* FOLL_DUMP to ignore special (like zero) pages */
1753 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1755 err = PTR_ERR(page);
1763 if (is_zone_device_page(page))
1767 if (page_to_nid(page) == node)
1771 if (page_mapcount(page) > 1 && !migrate_all)
1774 if (PageHuge(page)) {
1775 if (PageHead(page)) {
1776 err = isolate_hugetlb(page, pagelist);
1783 head = compound_head(page);
1784 err = isolate_lru_page(head);
1789 list_add_tail(&head->lru, pagelist);
1790 mod_node_page_state(page_pgdat(head),
1791 NR_ISOLATED_ANON + page_is_file_lru(head),
1792 thp_nr_pages(head));
1796 * Either remove the duplicate refcount from
1797 * isolate_lru_page() or drop the page ref if it was
1802 mmap_read_unlock(mm);
1806 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1807 struct list_head *pagelist, int __user *status,
1808 int start, int i, unsigned long nr_pages)
1812 if (list_empty(pagelist))
1815 err = do_move_pages_to_node(mm, pagelist, node);
1818 * Positive err means the number of failed
1819 * pages to migrate. Since we are going to
1820 * abort and return the number of non-migrated
1821 * pages, so need to include the rest of the
1822 * nr_pages that have not been attempted as
1826 err += nr_pages - i;
1829 return store_status(status, start, node, i - start);
1833 * Migrate an array of page address onto an array of nodes and fill
1834 * the corresponding array of status.
1836 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1837 unsigned long nr_pages,
1838 const void __user * __user *pages,
1839 const int __user *nodes,
1840 int __user *status, int flags)
1842 int current_node = NUMA_NO_NODE;
1843 LIST_HEAD(pagelist);
1847 lru_cache_disable();
1849 for (i = start = 0; i < nr_pages; i++) {
1850 const void __user *p;
1855 if (get_user(p, pages + i))
1857 if (get_user(node, nodes + i))
1859 addr = (unsigned long)untagged_addr(p);
1862 if (node < 0 || node >= MAX_NUMNODES)
1864 if (!node_state(node, N_MEMORY))
1868 if (!node_isset(node, task_nodes))
1871 if (current_node == NUMA_NO_NODE) {
1872 current_node = node;
1874 } else if (node != current_node) {
1875 err = move_pages_and_store_status(mm, current_node,
1876 &pagelist, status, start, i, nr_pages);
1880 current_node = node;
1884 * Errors in the page lookup or isolation are not fatal and we simply
1885 * report them via status
1887 err = add_page_for_migration(mm, addr, current_node,
1888 &pagelist, flags & MPOL_MF_MOVE_ALL);
1891 /* The page is successfully queued for migration */
1896 * The move_pages() man page does not have an -EEXIST choice, so
1897 * use -EFAULT instead.
1903 * If the page is already on the target node (!err), store the
1904 * node, otherwise, store the err.
1906 err = store_status(status, i, err ? : current_node, 1);
1910 err = move_pages_and_store_status(mm, current_node, &pagelist,
1911 status, start, i, nr_pages);
1913 /* We have accounted for page i */
1918 current_node = NUMA_NO_NODE;
1921 /* Make sure we do not overwrite the existing error */
1922 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1923 status, start, i, nr_pages);
1932 * Determine the nodes of an array of pages and store it in an array of status.
1934 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1935 const void __user **pages, int *status)
1941 for (i = 0; i < nr_pages; i++) {
1942 unsigned long addr = (unsigned long)(*pages);
1943 struct vm_area_struct *vma;
1947 vma = vma_lookup(mm, addr);
1951 /* FOLL_DUMP to ignore special (like zero) pages */
1952 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1954 err = PTR_ERR(page);
1962 if (!is_zone_device_page(page))
1963 err = page_to_nid(page);
1973 mmap_read_unlock(mm);
1976 static int get_compat_pages_array(const void __user *chunk_pages[],
1977 const void __user * __user *pages,
1978 unsigned long chunk_nr)
1980 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1984 for (i = 0; i < chunk_nr; i++) {
1985 if (get_user(p, pages32 + i))
1987 chunk_pages[i] = compat_ptr(p);
1994 * Determine the nodes of a user array of pages and store it in
1995 * a user array of status.
1997 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1998 const void __user * __user *pages,
2001 #define DO_PAGES_STAT_CHUNK_NR 16UL
2002 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
2003 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
2006 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
2008 if (in_compat_syscall()) {
2009 if (get_compat_pages_array(chunk_pages, pages,
2013 if (copy_from_user(chunk_pages, pages,
2014 chunk_nr * sizeof(*chunk_pages)))
2018 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
2020 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
2025 nr_pages -= chunk_nr;
2027 return nr_pages ? -EFAULT : 0;
2030 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
2032 struct task_struct *task;
2033 struct mm_struct *mm;
2036 * There is no need to check if current process has the right to modify
2037 * the specified process when they are same.
2041 *mem_nodes = cpuset_mems_allowed(current);
2045 /* Find the mm_struct */
2047 task = find_task_by_vpid(pid);
2050 return ERR_PTR(-ESRCH);
2052 get_task_struct(task);
2055 * Check if this process has the right to modify the specified
2056 * process. Use the regular "ptrace_may_access()" checks.
2058 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2060 mm = ERR_PTR(-EPERM);
2065 mm = ERR_PTR(security_task_movememory(task));
2068 *mem_nodes = cpuset_mems_allowed(task);
2069 mm = get_task_mm(task);
2071 put_task_struct(task);
2073 mm = ERR_PTR(-EINVAL);
2078 * Move a list of pages in the address space of the currently executing
2081 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2082 const void __user * __user *pages,
2083 const int __user *nodes,
2084 int __user *status, int flags)
2086 struct mm_struct *mm;
2088 nodemask_t task_nodes;
2091 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2094 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2097 mm = find_mm_struct(pid, &task_nodes);
2102 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2103 nodes, status, flags);
2105 err = do_pages_stat(mm, nr_pages, pages, status);
2111 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2112 const void __user * __user *, pages,
2113 const int __user *, nodes,
2114 int __user *, status, int, flags)
2116 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2119 #ifdef CONFIG_NUMA_BALANCING
2121 * Returns true if this is a safe migration target node for misplaced NUMA
2122 * pages. Currently it only checks the watermarks which is crude.
2124 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2125 unsigned long nr_migrate_pages)
2129 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2130 struct zone *zone = pgdat->node_zones + z;
2132 if (!managed_zone(zone))
2135 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2136 if (!zone_watermark_ok(zone, 0,
2137 high_wmark_pages(zone) +
2146 static struct page *alloc_misplaced_dst_page(struct page *page,
2149 int nid = (int) data;
2150 int order = compound_order(page);
2151 gfp_t gfp = __GFP_THISNODE;
2155 gfp |= GFP_TRANSHUGE_LIGHT;
2157 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2159 gfp &= ~__GFP_RECLAIM;
2161 new = __folio_alloc_node(gfp, order, nid);
2166 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2168 int nr_pages = thp_nr_pages(page);
2169 int order = compound_order(page);
2171 VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2173 /* Do not migrate THP mapped by multiple processes */
2174 if (PageTransHuge(page) && total_mapcount(page) > 1)
2177 /* Avoid migrating to a node that is nearly full */
2178 if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2181 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2183 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2184 if (managed_zone(pgdat->node_zones + z))
2187 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2191 if (isolate_lru_page(page))
2194 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2198 * Isolating the page has taken another reference, so the
2199 * caller's reference can be safely dropped without the page
2200 * disappearing underneath us during migration.
2207 * Attempt to migrate a misplaced page to the specified destination
2208 * node. Caller is expected to have an elevated reference count on
2209 * the page that will be dropped by this function before returning.
2211 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2214 pg_data_t *pgdat = NODE_DATA(node);
2217 unsigned int nr_succeeded;
2218 LIST_HEAD(migratepages);
2219 int nr_pages = thp_nr_pages(page);
2222 * Don't migrate file pages that are mapped in multiple processes
2223 * with execute permissions as they are probably shared libraries.
2225 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2226 (vma->vm_flags & VM_EXEC))
2230 * Also do not migrate dirty pages as not all filesystems can move
2231 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2233 if (page_is_file_lru(page) && PageDirty(page))
2236 isolated = numamigrate_isolate_page(pgdat, page);
2240 list_add(&page->lru, &migratepages);
2241 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2242 NULL, node, MIGRATE_ASYNC,
2243 MR_NUMA_MISPLACED, &nr_succeeded);
2245 if (!list_empty(&migratepages)) {
2246 list_del(&page->lru);
2247 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2248 page_is_file_lru(page), -nr_pages);
2249 putback_lru_page(page);
2254 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2255 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2256 mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2259 BUG_ON(!list_empty(&migratepages));
2266 #endif /* CONFIG_NUMA_BALANCING */
2267 #endif /* CONFIG_NUMA */