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/pagewalk.h>
42 #include <linux/pfn_t.h>
43 #include <linux/memremap.h>
44 #include <linux/userfaultfd_k.h>
45 #include <linux/balloon_compaction.h>
46 #include <linux/mmu_notifier.h>
47 #include <linux/page_idle.h>
48 #include <linux/page_owner.h>
49 #include <linux/sched/mm.h>
50 #include <linux/ptrace.h>
51 #include <linux/oom.h>
52 #include <linux/memory.h>
54 #include <asm/tlbflush.h>
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/migrate.h>
61 int isolate_movable_page(struct page *page, isolate_mode_t mode)
63 struct address_space *mapping;
66 * Avoid burning cycles with pages that are yet under __free_pages(),
67 * or just got freed under us.
69 * In case we 'win' a race for a movable page being freed under us and
70 * raise its refcount preventing __free_pages() from doing its job
71 * the put_page() at the end of this block will take care of
72 * release this page, thus avoiding a nasty leakage.
74 if (unlikely(!get_page_unless_zero(page)))
78 * Check PageMovable before holding a PG_lock because page's owner
79 * assumes anybody doesn't touch PG_lock of newly allocated page
80 * so unconditionally grabbing the lock ruins page's owner side.
82 if (unlikely(!__PageMovable(page)))
85 * As movable pages are not isolated from LRU lists, concurrent
86 * compaction threads can race against page migration functions
87 * as well as race against the releasing a page.
89 * In order to avoid having an already isolated movable page
90 * being (wrongly) re-isolated while it is under migration,
91 * or to avoid attempting to isolate pages being released,
92 * lets be sure we have the page lock
93 * before proceeding with the movable page isolation steps.
95 if (unlikely(!trylock_page(page)))
98 if (!PageMovable(page) || PageIsolated(page))
101 mapping = page_mapping(page);
102 VM_BUG_ON_PAGE(!mapping, page);
104 if (!mapping->a_ops->isolate_page(page, mode))
105 goto out_no_isolated;
107 /* Driver shouldn't use PG_isolated bit of page->flags */
108 WARN_ON_ONCE(PageIsolated(page));
109 __SetPageIsolated(page);
122 static void putback_movable_page(struct page *page)
124 struct address_space *mapping;
126 mapping = page_mapping(page);
127 mapping->a_ops->putback_page(page);
128 __ClearPageIsolated(page);
132 * Put previously isolated pages back onto the appropriate lists
133 * from where they were once taken off for compaction/migration.
135 * This function shall be used whenever the isolated pageset has been
136 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
137 * and isolate_hugetlb().
139 void putback_movable_pages(struct list_head *l)
144 list_for_each_entry_safe(page, page2, l, lru) {
145 if (unlikely(PageHuge(page))) {
146 putback_active_hugepage(page);
149 list_del(&page->lru);
151 * We isolated non-lru movable page so here we can use
152 * __PageMovable because LRU page's mapping cannot have
153 * PAGE_MAPPING_MOVABLE.
155 if (unlikely(__PageMovable(page))) {
156 VM_BUG_ON_PAGE(!PageIsolated(page), page);
158 if (PageMovable(page))
159 putback_movable_page(page);
161 __ClearPageIsolated(page);
165 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
166 page_is_file_lru(page), -thp_nr_pages(page));
167 putback_lru_page(page);
173 * Restore a potential migration pte to a working pte entry
175 static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
176 unsigned long addr, void *old)
178 struct page_vma_mapped_walk pvmw = {
182 .flags = PVMW_SYNC | PVMW_MIGRATION,
188 VM_BUG_ON_PAGE(PageTail(page), page);
189 while (page_vma_mapped_walk(&pvmw)) {
193 new = page - pvmw.page->index +
194 linear_page_index(vma, pvmw.address);
196 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
197 /* PMD-mapped THP migration entry */
199 VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
200 remove_migration_pmd(&pvmw, new);
206 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
207 if (pte_swp_soft_dirty(*pvmw.pte))
208 pte = pte_mksoft_dirty(pte);
211 * Recheck VMA as permissions can change since migration started
213 entry = pte_to_swp_entry(*pvmw.pte);
214 if (is_writable_migration_entry(entry))
215 pte = maybe_mkwrite(pte, vma);
216 else if (pte_swp_uffd_wp(*pvmw.pte))
217 pte = pte_mkuffd_wp(pte);
219 if (unlikely(is_device_private_page(new))) {
221 entry = make_writable_device_private_entry(
224 entry = make_readable_device_private_entry(
226 pte = swp_entry_to_pte(entry);
227 if (pte_swp_soft_dirty(*pvmw.pte))
228 pte = pte_swp_mksoft_dirty(pte);
229 if (pte_swp_uffd_wp(*pvmw.pte))
230 pte = pte_swp_mkuffd_wp(pte);
233 #ifdef CONFIG_HUGETLB_PAGE
235 unsigned int shift = huge_page_shift(hstate_vma(vma));
237 pte = pte_mkhuge(pte);
238 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
239 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
241 hugepage_add_anon_rmap(new, vma, pvmw.address);
243 page_dup_rmap(new, true);
247 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
250 page_add_anon_rmap(new, vma, pvmw.address, false);
252 page_add_file_rmap(new, false);
254 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
257 if (PageTransHuge(page) && PageMlocked(page))
258 clear_page_mlock(page);
260 /* No need to invalidate - it was non-present before */
261 update_mmu_cache(vma, pvmw.address, pvmw.pte);
268 * Get rid of all migration entries and replace them by
269 * references to the indicated page.
271 void remove_migration_ptes(struct page *old, struct page *new, bool locked)
273 struct rmap_walk_control rwc = {
274 .rmap_one = remove_migration_pte,
279 rmap_walk_locked(new, &rwc);
281 rmap_walk(new, &rwc);
285 * Something used the pte of a page under migration. We need to
286 * get to the page and wait until migration is finished.
287 * When we return from this function the fault will be retried.
289 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
298 if (!is_swap_pte(pte))
301 entry = pte_to_swp_entry(pte);
302 if (!is_migration_entry(entry))
305 page = pfn_swap_entry_to_page(entry);
306 page = compound_head(page);
309 * Once page cache replacement of page migration started, page_count
310 * is zero; but we must not call put_and_wait_on_page_locked() without
311 * a ref. Use get_page_unless_zero(), and just fault again if it fails.
313 if (!get_page_unless_zero(page))
315 pte_unmap_unlock(ptep, ptl);
316 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
319 pte_unmap_unlock(ptep, ptl);
322 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
323 unsigned long address)
325 spinlock_t *ptl = pte_lockptr(mm, pmd);
326 pte_t *ptep = pte_offset_map(pmd, address);
327 __migration_entry_wait(mm, ptep, ptl);
330 void migration_entry_wait_huge(struct vm_area_struct *vma,
331 struct mm_struct *mm, pte_t *pte)
333 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
334 __migration_entry_wait(mm, pte, ptl);
337 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
338 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
343 ptl = pmd_lock(mm, pmd);
344 if (!is_pmd_migration_entry(*pmd))
346 page = pfn_swap_entry_to_page(pmd_to_swp_entry(*pmd));
347 if (!get_page_unless_zero(page))
350 put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
357 static int expected_page_refs(struct address_space *mapping, struct page *page)
359 int expected_count = 1;
362 * Device private pages have an extra refcount as they are
365 expected_count += is_device_private_page(page);
367 expected_count += thp_nr_pages(page) + page_has_private(page);
369 return expected_count;
373 * Replace the page in the mapping.
375 * The number of remaining references must be:
376 * 1 for anonymous pages without a mapping
377 * 2 for pages with a mapping
378 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
380 int migrate_page_move_mapping(struct address_space *mapping,
381 struct page *newpage, struct page *page, int extra_count)
383 XA_STATE(xas, &mapping->i_pages, page_index(page));
384 struct zone *oldzone, *newzone;
386 int expected_count = expected_page_refs(mapping, page) + extra_count;
387 int nr = thp_nr_pages(page);
390 /* Anonymous page without mapping */
391 if (page_count(page) != expected_count)
394 /* No turning back from here */
395 newpage->index = page->index;
396 newpage->mapping = page->mapping;
397 if (PageSwapBacked(page))
398 __SetPageSwapBacked(newpage);
400 return MIGRATEPAGE_SUCCESS;
403 oldzone = page_zone(page);
404 newzone = page_zone(newpage);
407 if (page_count(page) != expected_count || xas_load(&xas) != page) {
408 xas_unlock_irq(&xas);
412 if (!page_ref_freeze(page, expected_count)) {
413 xas_unlock_irq(&xas);
418 * Now we know that no one else is looking at the page:
419 * no turning back from here.
421 newpage->index = page->index;
422 newpage->mapping = page->mapping;
423 page_ref_add(newpage, nr); /* add cache reference */
424 if (PageSwapBacked(page)) {
425 __SetPageSwapBacked(newpage);
426 if (PageSwapCache(page)) {
427 SetPageSwapCache(newpage);
428 set_page_private(newpage, page_private(page));
431 VM_BUG_ON_PAGE(PageSwapCache(page), page);
434 /* Move dirty while page refs frozen and newpage not yet exposed */
435 dirty = PageDirty(page);
437 ClearPageDirty(page);
438 SetPageDirty(newpage);
441 xas_store(&xas, newpage);
442 if (PageTransHuge(page)) {
445 for (i = 1; i < nr; i++) {
447 xas_store(&xas, newpage);
452 * Drop cache reference from old page by unfreezing
453 * to one less reference.
454 * We know this isn't the last reference.
456 page_ref_unfreeze(page, 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 = page_memcg(page);
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 (PageSwapBacked(page) && !PageSwapCache(page)) {
482 __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
483 __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
486 if (PageSwapCache(page)) {
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(migrate_page_move_mapping);
505 * The expected number of remaining references is the same as that
506 * of migrate_page_move_mapping().
508 int migrate_huge_page_move_mapping(struct address_space *mapping,
509 struct page *newpage, struct page *page)
511 XA_STATE(xas, &mapping->i_pages, page_index(page));
515 expected_count = 2 + page_has_private(page);
516 if (page_count(page) != expected_count || xas_load(&xas) != page) {
517 xas_unlock_irq(&xas);
521 if (!page_ref_freeze(page, expected_count)) {
522 xas_unlock_irq(&xas);
526 newpage->index = page->index;
527 newpage->mapping = page->mapping;
531 xas_store(&xas, newpage);
533 page_ref_unfreeze(page, expected_count - 1);
535 xas_unlock_irq(&xas);
537 return MIGRATEPAGE_SUCCESS;
541 * Copy the page to its new location
543 void migrate_page_states(struct page *newpage, struct page *page)
548 SetPageError(newpage);
549 if (PageReferenced(page))
550 SetPageReferenced(newpage);
551 if (PageUptodate(page))
552 SetPageUptodate(newpage);
553 if (TestClearPageActive(page)) {
554 VM_BUG_ON_PAGE(PageUnevictable(page), page);
555 SetPageActive(newpage);
556 } else if (TestClearPageUnevictable(page))
557 SetPageUnevictable(newpage);
558 if (PageWorkingset(page))
559 SetPageWorkingset(newpage);
560 if (PageChecked(page))
561 SetPageChecked(newpage);
562 if (PageMappedToDisk(page))
563 SetPageMappedToDisk(newpage);
565 /* Move dirty on pages not done by migrate_page_move_mapping() */
567 SetPageDirty(newpage);
569 if (page_is_young(page))
570 set_page_young(newpage);
571 if (page_is_idle(page))
572 set_page_idle(newpage);
575 * Copy NUMA information to the new page, to prevent over-eager
576 * future migrations of this same page.
578 cpupid = page_cpupid_xchg_last(page, -1);
579 page_cpupid_xchg_last(newpage, cpupid);
581 ksm_migrate_page(newpage, page);
583 * Please do not reorder this without considering how mm/ksm.c's
584 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
586 if (PageSwapCache(page))
587 ClearPageSwapCache(page);
588 ClearPagePrivate(page);
590 /* page->private contains hugetlb specific flags */
592 set_page_private(page, 0);
595 * If any waiters have accumulated on the new page then
598 if (PageWriteback(newpage))
599 end_page_writeback(newpage);
602 * PG_readahead shares the same bit with PG_reclaim. The above
603 * end_page_writeback() may clear PG_readahead mistakenly, so set the
606 if (PageReadahead(page))
607 SetPageReadahead(newpage);
609 copy_page_owner(page, newpage);
612 mem_cgroup_migrate(page, newpage);
614 EXPORT_SYMBOL(migrate_page_states);
616 void migrate_page_copy(struct page *newpage, struct page *page)
618 if (PageHuge(page) || PageTransHuge(page))
619 copy_huge_page(newpage, page);
621 copy_highpage(newpage, page);
623 migrate_page_states(newpage, page);
625 EXPORT_SYMBOL(migrate_page_copy);
627 /************************************************************
628 * Migration functions
629 ***********************************************************/
632 * Common logic to directly migrate a single LRU page suitable for
633 * pages that do not use PagePrivate/PagePrivate2.
635 * Pages are locked upon entry and exit.
637 int migrate_page(struct address_space *mapping,
638 struct page *newpage, struct page *page,
639 enum migrate_mode mode)
643 BUG_ON(PageWriteback(page)); /* Writeback must be complete */
645 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
647 if (rc != MIGRATEPAGE_SUCCESS)
650 if (mode != MIGRATE_SYNC_NO_COPY)
651 migrate_page_copy(newpage, page);
653 migrate_page_states(newpage, page);
654 return MIGRATEPAGE_SUCCESS;
656 EXPORT_SYMBOL(migrate_page);
659 /* Returns true if all buffers are successfully locked */
660 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
661 enum migrate_mode mode)
663 struct buffer_head *bh = head;
665 /* Simple case, sync compaction */
666 if (mode != MIGRATE_ASYNC) {
669 bh = bh->b_this_page;
671 } while (bh != head);
676 /* async case, we cannot block on lock_buffer so use trylock_buffer */
678 if (!trylock_buffer(bh)) {
680 * We failed to lock the buffer and cannot stall in
681 * async migration. Release the taken locks
683 struct buffer_head *failed_bh = bh;
685 while (bh != failed_bh) {
687 bh = bh->b_this_page;
692 bh = bh->b_this_page;
693 } while (bh != head);
697 static int __buffer_migrate_page(struct address_space *mapping,
698 struct page *newpage, struct page *page, enum migrate_mode mode,
701 struct buffer_head *bh, *head;
705 if (!page_has_buffers(page))
706 return migrate_page(mapping, newpage, page, mode);
708 /* Check whether page does not have extra refs before we do more work */
709 expected_count = expected_page_refs(mapping, page);
710 if (page_count(page) != expected_count)
713 head = page_buffers(page);
714 if (!buffer_migrate_lock_buffers(head, mode))
719 bool invalidated = false;
723 spin_lock(&mapping->private_lock);
726 if (atomic_read(&bh->b_count)) {
730 bh = bh->b_this_page;
731 } while (bh != head);
737 spin_unlock(&mapping->private_lock);
738 invalidate_bh_lrus();
740 goto recheck_buffers;
744 rc = migrate_page_move_mapping(mapping, newpage, page, 0);
745 if (rc != MIGRATEPAGE_SUCCESS)
748 attach_page_private(newpage, detach_page_private(page));
752 set_bh_page(bh, newpage, bh_offset(bh));
753 bh = bh->b_this_page;
755 } while (bh != head);
757 if (mode != MIGRATE_SYNC_NO_COPY)
758 migrate_page_copy(newpage, page);
760 migrate_page_states(newpage, page);
762 rc = MIGRATEPAGE_SUCCESS;
765 spin_unlock(&mapping->private_lock);
769 bh = bh->b_this_page;
771 } while (bh != head);
777 * Migration function for pages with buffers. This function can only be used
778 * if the underlying filesystem guarantees that no other references to "page"
779 * exist. For example attached buffer heads are accessed only under page lock.
781 int buffer_migrate_page(struct address_space *mapping,
782 struct page *newpage, struct page *page, enum migrate_mode mode)
784 return __buffer_migrate_page(mapping, newpage, page, mode, false);
786 EXPORT_SYMBOL(buffer_migrate_page);
789 * Same as above except that this variant is more careful and checks that there
790 * are also no buffer head references. This function is the right one for
791 * mappings where buffer heads are directly looked up and referenced (such as
792 * block device mappings).
794 int buffer_migrate_page_norefs(struct address_space *mapping,
795 struct page *newpage, struct page *page, enum migrate_mode mode)
797 return __buffer_migrate_page(mapping, newpage, page, mode, true);
802 * Writeback a page to clean the dirty state
804 static int writeout(struct address_space *mapping, struct page *page)
806 struct writeback_control wbc = {
807 .sync_mode = WB_SYNC_NONE,
810 .range_end = LLONG_MAX,
815 if (!mapping->a_ops->writepage)
816 /* No write method for the address space */
819 if (!clear_page_dirty_for_io(page))
820 /* Someone else already triggered a write */
824 * A dirty page may imply that the underlying filesystem has
825 * the page on some queue. So the page must be clean for
826 * migration. Writeout may mean we loose the lock and the
827 * page state is no longer what we checked for earlier.
828 * At this point we know that the migration attempt cannot
831 remove_migration_ptes(page, page, false);
833 rc = mapping->a_ops->writepage(page, &wbc);
835 if (rc != AOP_WRITEPAGE_ACTIVATE)
836 /* unlocked. Relock */
839 return (rc < 0) ? -EIO : -EAGAIN;
843 * Default handling if a filesystem does not provide a migration function.
845 static int fallback_migrate_page(struct address_space *mapping,
846 struct page *newpage, struct page *page, enum migrate_mode mode)
848 if (PageDirty(page)) {
849 /* Only writeback pages in full synchronous migration */
852 case MIGRATE_SYNC_NO_COPY:
857 return writeout(mapping, page);
861 * Buffers may be managed in a filesystem specific way.
862 * We must have no buffers or drop them.
864 if (page_has_private(page) &&
865 !try_to_release_page(page, GFP_KERNEL))
866 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
868 return migrate_page(mapping, newpage, page, mode);
872 * Move a page to a newly allocated page
873 * The page is locked and all ptes have been successfully removed.
875 * The new page will have replaced the old page if this function
880 * MIGRATEPAGE_SUCCESS - success
882 static int move_to_new_page(struct page *newpage, struct page *page,
883 enum migrate_mode mode)
885 struct address_space *mapping;
887 bool is_lru = !__PageMovable(page);
889 VM_BUG_ON_PAGE(!PageLocked(page), page);
890 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
892 mapping = page_mapping(page);
894 if (likely(is_lru)) {
896 rc = migrate_page(mapping, newpage, page, mode);
897 else if (mapping->a_ops->migratepage)
899 * Most pages have a mapping and most filesystems
900 * provide a migratepage callback. Anonymous pages
901 * are part of swap space which also has its own
902 * migratepage callback. This is the most common path
903 * for page migration.
905 rc = mapping->a_ops->migratepage(mapping, newpage,
908 rc = fallback_migrate_page(mapping, newpage,
912 * In case of non-lru page, it could be released after
913 * isolation step. In that case, we shouldn't try migration.
915 VM_BUG_ON_PAGE(!PageIsolated(page), page);
916 if (!PageMovable(page)) {
917 rc = MIGRATEPAGE_SUCCESS;
918 __ClearPageIsolated(page);
922 rc = mapping->a_ops->migratepage(mapping, newpage,
924 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
925 !PageIsolated(page));
929 * When successful, old pagecache page->mapping must be cleared before
930 * page is freed; but stats require that PageAnon be left as PageAnon.
932 if (rc == MIGRATEPAGE_SUCCESS) {
933 if (__PageMovable(page)) {
934 VM_BUG_ON_PAGE(!PageIsolated(page), page);
937 * We clear PG_movable under page_lock so any compactor
938 * cannot try to migrate this page.
940 __ClearPageIsolated(page);
944 * Anonymous and movable page->mapping will be cleared by
945 * free_pages_prepare so don't reset it here for keeping
946 * the type to work PageAnon, for example.
948 if (!PageMappingFlags(page))
949 page->mapping = NULL;
951 if (likely(!is_zone_device_page(newpage))) {
952 int i, nr = compound_nr(newpage);
954 for (i = 0; i < nr; i++)
955 flush_dcache_page(newpage + i);
962 static int __unmap_and_move(struct page *page, struct page *newpage,
963 int force, enum migrate_mode mode)
966 bool page_was_mapped = false;
967 struct anon_vma *anon_vma = NULL;
968 bool is_lru = !__PageMovable(page);
970 if (!trylock_page(page)) {
971 if (!force || mode == MIGRATE_ASYNC)
975 * It's not safe for direct compaction to call lock_page.
976 * For example, during page readahead pages are added locked
977 * to the LRU. Later, when the IO completes the pages are
978 * marked uptodate and unlocked. However, the queueing
979 * could be merging multiple pages for one bio (e.g.
980 * mpage_readahead). If an allocation happens for the
981 * second or third page, the process can end up locking
982 * the same page twice and deadlocking. Rather than
983 * trying to be clever about what pages can be locked,
984 * avoid the use of lock_page for direct compaction
987 if (current->flags & PF_MEMALLOC)
993 if (PageWriteback(page)) {
995 * Only in the case of a full synchronous migration is it
996 * necessary to wait for PageWriteback. In the async case,
997 * the retry loop is too short and in the sync-light case,
998 * the overhead of stalling is too much
1002 case MIGRATE_SYNC_NO_COPY:
1010 wait_on_page_writeback(page);
1014 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1015 * we cannot notice that anon_vma is freed while we migrates a page.
1016 * This get_anon_vma() delays freeing anon_vma pointer until the end
1017 * of migration. File cache pages are no problem because of page_lock()
1018 * File Caches may use write_page() or lock_page() in migration, then,
1019 * just care Anon page here.
1021 * Only page_get_anon_vma() understands the subtleties of
1022 * getting a hold on an anon_vma from outside one of its mms.
1023 * But if we cannot get anon_vma, then we won't need it anyway,
1024 * because that implies that the anon page is no longer mapped
1025 * (and cannot be remapped so long as we hold the page lock).
1027 if (PageAnon(page) && !PageKsm(page))
1028 anon_vma = page_get_anon_vma(page);
1031 * Block others from accessing the new page when we get around to
1032 * establishing additional references. We are usually the only one
1033 * holding a reference to newpage at this point. We used to have a BUG
1034 * here if trylock_page(newpage) fails, but would like to allow for
1035 * cases where there might be a race with the previous use of newpage.
1036 * This is much like races on refcount of oldpage: just don't BUG().
1038 if (unlikely(!trylock_page(newpage)))
1041 if (unlikely(!is_lru)) {
1042 rc = move_to_new_page(newpage, page, mode);
1043 goto out_unlock_both;
1047 * Corner case handling:
1048 * 1. When a new swap-cache page is read into, it is added to the LRU
1049 * and treated as swapcache but it has no rmap yet.
1050 * Calling try_to_unmap() against a page->mapping==NULL page will
1051 * trigger a BUG. So handle it here.
1052 * 2. An orphaned page (see truncate_cleanup_page) might have
1053 * fs-private metadata. The page can be picked up due to memory
1054 * offlining. Everywhere else except page reclaim, the page is
1055 * invisible to the vm, so the page can not be migrated. So try to
1056 * free the metadata, so the page can be freed.
1058 if (!page->mapping) {
1059 VM_BUG_ON_PAGE(PageAnon(page), page);
1060 if (page_has_private(page)) {
1061 try_to_free_buffers(page);
1062 goto out_unlock_both;
1064 } else if (page_mapped(page)) {
1065 /* Establish migration ptes */
1066 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1068 try_to_migrate(page, 0);
1069 page_was_mapped = true;
1072 if (!page_mapped(page))
1073 rc = move_to_new_page(newpage, page, mode);
1075 if (page_was_mapped)
1076 remove_migration_ptes(page,
1077 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1080 unlock_page(newpage);
1082 /* Drop an anon_vma reference if we took one */
1084 put_anon_vma(anon_vma);
1088 * If migration is successful, decrease refcount of the newpage
1089 * which will not free the page because new page owner increased
1090 * refcounter. As well, if it is LRU page, add the page to LRU
1091 * list in here. Use the old state of the isolated source page to
1092 * determine if we migrated a LRU page. newpage was already unlocked
1093 * and possibly modified by its owner - don't rely on the page
1096 if (rc == MIGRATEPAGE_SUCCESS) {
1097 if (unlikely(!is_lru))
1100 putback_lru_page(newpage);
1108 * node_demotion[] example:
1110 * Consider a system with two sockets. Each socket has
1111 * three classes of memory attached: fast, medium and slow.
1112 * Each memory class is placed in its own NUMA node. The
1113 * CPUs are placed in the node with the "fast" memory. The
1114 * 6 NUMA nodes (0-5) might be split among the sockets like
1120 * When Node 0 fills up, its memory should be migrated to
1121 * Node 1. When Node 1 fills up, it should be migrated to
1122 * Node 2. The migration path start on the nodes with the
1123 * processors (since allocations default to this node) and
1124 * fast memory, progress through medium and end with the
1127 * 0 -> 1 -> 2 -> stop
1128 * 3 -> 4 -> 5 -> stop
1130 * This is represented in the node_demotion[] like this:
1132 * { 1, // Node 0 migrates to 1
1133 * 2, // Node 1 migrates to 2
1134 * -1, // Node 2 does not migrate
1135 * 4, // Node 3 migrates to 4
1136 * 5, // Node 4 migrates to 5
1137 * -1} // Node 5 does not migrate
1141 * Writes to this array occur without locking. Cycles are
1142 * not allowed: Node X demotes to Y which demotes to X...
1144 * If multiple reads are performed, a single rcu_read_lock()
1145 * must be held over all reads to ensure that no cycles are
1148 static int node_demotion[MAX_NUMNODES] __read_mostly =
1149 {[0 ... MAX_NUMNODES - 1] = NUMA_NO_NODE};
1152 * next_demotion_node() - Get the next node in the demotion path
1153 * @node: The starting node to lookup the next node
1155 * Return: node id for next memory node in the demotion path hierarchy
1156 * from @node; NUMA_NO_NODE if @node is terminal. This does not keep
1157 * @node online or guarantee that it *continues* to be the next demotion
1160 int next_demotion_node(int node)
1165 * node_demotion[] is updated without excluding this
1166 * function from running. RCU doesn't provide any
1167 * compiler barriers, so the READ_ONCE() is required
1168 * to avoid compiler reordering or read merging.
1170 * Make sure to use RCU over entire code blocks if
1171 * node_demotion[] reads need to be consistent.
1174 target = READ_ONCE(node_demotion[node]);
1181 * Obtain the lock on page, remove all ptes and migrate the page
1182 * to the newly allocated page in newpage.
1184 static int unmap_and_move(new_page_t get_new_page,
1185 free_page_t put_new_page,
1186 unsigned long private, struct page *page,
1187 int force, enum migrate_mode mode,
1188 enum migrate_reason reason,
1189 struct list_head *ret)
1191 int rc = MIGRATEPAGE_SUCCESS;
1192 struct page *newpage = NULL;
1194 if (!thp_migration_supported() && PageTransHuge(page))
1197 if (page_count(page) == 1) {
1198 /* page was freed from under us. So we are done. */
1199 ClearPageActive(page);
1200 ClearPageUnevictable(page);
1201 if (unlikely(__PageMovable(page))) {
1203 if (!PageMovable(page))
1204 __ClearPageIsolated(page);
1210 newpage = get_new_page(page, private);
1214 rc = __unmap_and_move(page, newpage, force, mode);
1215 if (rc == MIGRATEPAGE_SUCCESS)
1216 set_page_owner_migrate_reason(newpage, reason);
1219 if (rc != -EAGAIN) {
1221 * A page that has been migrated has all references
1222 * removed and will be freed. A page that has not been
1223 * migrated will have kept its references and be restored.
1225 list_del(&page->lru);
1229 * If migration is successful, releases reference grabbed during
1230 * isolation. Otherwise, restore the page to right list unless
1233 if (rc == MIGRATEPAGE_SUCCESS) {
1235 * Compaction can migrate also non-LRU pages which are
1236 * not accounted to NR_ISOLATED_*. They can be recognized
1239 if (likely(!__PageMovable(page)))
1240 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1241 page_is_file_lru(page), -thp_nr_pages(page));
1243 if (reason != MR_MEMORY_FAILURE)
1245 * We release the page in page_handle_poison.
1250 list_add_tail(&page->lru, ret);
1253 put_new_page(newpage, private);
1262 * Counterpart of unmap_and_move_page() for hugepage migration.
1264 * This function doesn't wait the completion of hugepage I/O
1265 * because there is no race between I/O and migration for hugepage.
1266 * Note that currently hugepage I/O occurs only in direct I/O
1267 * where no lock is held and PG_writeback is irrelevant,
1268 * and writeback status of all subpages are counted in the reference
1269 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1270 * under direct I/O, the reference of the head page is 512 and a bit more.)
1271 * This means that when we try to migrate hugepage whose subpages are
1272 * doing direct I/O, some references remain after try_to_unmap() and
1273 * hugepage migration fails without data corruption.
1275 * There is also no race when direct I/O is issued on the page under migration,
1276 * because then pte is replaced with migration swap entry and direct I/O code
1277 * will wait in the page fault for migration to complete.
1279 static int unmap_and_move_huge_page(new_page_t get_new_page,
1280 free_page_t put_new_page, unsigned long private,
1281 struct page *hpage, int force,
1282 enum migrate_mode mode, int reason,
1283 struct list_head *ret)
1286 int page_was_mapped = 0;
1287 struct page *new_hpage;
1288 struct anon_vma *anon_vma = NULL;
1289 struct address_space *mapping = NULL;
1292 * Migratability of hugepages depends on architectures and their size.
1293 * This check is necessary because some callers of hugepage migration
1294 * like soft offline and memory hotremove don't walk through page
1295 * tables or check whether the hugepage is pmd-based or not before
1296 * kicking migration.
1298 if (!hugepage_migration_supported(page_hstate(hpage))) {
1299 list_move_tail(&hpage->lru, ret);
1303 if (page_count(hpage) == 1) {
1304 /* page was freed from under us. So we are done. */
1305 putback_active_hugepage(hpage);
1306 return MIGRATEPAGE_SUCCESS;
1309 new_hpage = get_new_page(hpage, private);
1313 if (!trylock_page(hpage)) {
1318 case MIGRATE_SYNC_NO_COPY:
1327 * Check for pages which are in the process of being freed. Without
1328 * page_mapping() set, hugetlbfs specific move page routine will not
1329 * be called and we could leak usage counts for subpools.
1331 if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1336 if (PageAnon(hpage))
1337 anon_vma = page_get_anon_vma(hpage);
1339 if (unlikely(!trylock_page(new_hpage)))
1342 if (page_mapped(hpage)) {
1343 bool mapping_locked = false;
1344 enum ttu_flags ttu = 0;
1346 if (!PageAnon(hpage)) {
1348 * In shared mappings, try_to_unmap could potentially
1349 * call huge_pmd_unshare. Because of this, take
1350 * semaphore in write mode here and set TTU_RMAP_LOCKED
1351 * to let lower levels know we have taken the lock.
1353 mapping = hugetlb_page_mapping_lock_write(hpage);
1354 if (unlikely(!mapping))
1355 goto unlock_put_anon;
1357 mapping_locked = true;
1358 ttu |= TTU_RMAP_LOCKED;
1361 try_to_migrate(hpage, ttu);
1362 page_was_mapped = 1;
1365 i_mmap_unlock_write(mapping);
1368 if (!page_mapped(hpage))
1369 rc = move_to_new_page(new_hpage, hpage, mode);
1371 if (page_was_mapped)
1372 remove_migration_ptes(hpage,
1373 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1376 unlock_page(new_hpage);
1380 put_anon_vma(anon_vma);
1382 if (rc == MIGRATEPAGE_SUCCESS) {
1383 move_hugetlb_state(hpage, new_hpage, reason);
1384 put_new_page = NULL;
1390 if (rc == MIGRATEPAGE_SUCCESS)
1391 putback_active_hugepage(hpage);
1392 else if (rc != -EAGAIN)
1393 list_move_tail(&hpage->lru, ret);
1396 * If migration was not successful and there's a freeing callback, use
1397 * it. Otherwise, put_page() will drop the reference grabbed during
1401 put_new_page(new_hpage, private);
1403 putback_active_hugepage(new_hpage);
1408 static inline int try_split_thp(struct page *page, struct page **page2,
1409 struct list_head *from)
1414 rc = split_huge_page_to_list(page, from);
1417 list_safe_reset_next(page, *page2, lru);
1423 * migrate_pages - migrate the pages specified in a list, to the free pages
1424 * supplied as the target for the page migration
1426 * @from: The list of pages to be migrated.
1427 * @get_new_page: The function used to allocate free pages to be used
1428 * as the target of the page migration.
1429 * @put_new_page: The function used to free target pages if migration
1430 * fails, or NULL if no special handling is necessary.
1431 * @private: Private data to be passed on to get_new_page()
1432 * @mode: The migration mode that specifies the constraints for
1433 * page migration, if any.
1434 * @reason: The reason for page migration.
1435 * @ret_succeeded: Set to the number of pages migrated successfully if
1436 * the caller passes a non-NULL pointer.
1438 * The function returns after 10 attempts or if no pages are movable any more
1439 * because the list has become empty or no retryable pages exist any more.
1440 * It is caller's responsibility to call putback_movable_pages() to return pages
1441 * to the LRU or free list only if ret != 0.
1443 * Returns the number of pages that were not migrated, or an error code.
1445 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1446 free_page_t put_new_page, unsigned long private,
1447 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1452 int nr_succeeded = 0;
1453 int nr_thp_succeeded = 0;
1454 int nr_thp_failed = 0;
1455 int nr_thp_split = 0;
1457 bool is_thp = false;
1460 int swapwrite = current->flags & PF_SWAPWRITE;
1461 int rc, nr_subpages;
1462 LIST_HEAD(ret_pages);
1463 bool nosplit = (reason == MR_NUMA_MISPLACED);
1465 trace_mm_migrate_pages_start(mode, reason);
1468 current->flags |= PF_SWAPWRITE;
1470 for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1474 list_for_each_entry_safe(page, page2, from, lru) {
1477 * THP statistics is based on the source huge page.
1478 * Capture required information that might get lost
1481 is_thp = PageTransHuge(page) && !PageHuge(page);
1482 nr_subpages = thp_nr_pages(page);
1486 rc = unmap_and_move_huge_page(get_new_page,
1487 put_new_page, private, page,
1488 pass > 2, mode, reason,
1491 rc = unmap_and_move(get_new_page, put_new_page,
1492 private, page, pass > 2, mode,
1493 reason, &ret_pages);
1496 * Success: non hugetlb page will be freed, hugetlb
1497 * page will be put back
1498 * -EAGAIN: stay on the from list
1499 * -ENOMEM: stay on the from list
1500 * Other errno: put on ret_pages list then splice to
1505 * THP migration might be unsupported or the
1506 * allocation could've failed so we should
1507 * retry on the same page with the THP split
1510 * Head page is retried immediately and tail
1511 * pages are added to the tail of the list so
1512 * we encounter them after the rest of the list
1516 /* THP migration is unsupported */
1518 if (!try_split_thp(page, &page2, from)) {
1524 nr_failed += nr_subpages;
1528 /* Hugetlb migration is unsupported */
1533 * When memory is low, don't bother to try to migrate
1534 * other pages, just exit.
1535 * THP NUMA faulting doesn't split THP to retry.
1537 if (is_thp && !nosplit) {
1538 if (!try_split_thp(page, &page2, from)) {
1544 nr_failed += nr_subpages;
1556 case MIGRATEPAGE_SUCCESS:
1559 nr_succeeded += nr_subpages;
1566 * Permanent failure (-EBUSY, etc.):
1567 * unlike -EAGAIN case, the failed page is
1568 * removed from migration page list and not
1569 * retried in the next outer loop.
1573 nr_failed += nr_subpages;
1581 nr_failed += retry + thp_retry;
1582 nr_thp_failed += thp_retry;
1586 * Put the permanent failure page back to migration list, they
1587 * will be put back to the right list by the caller.
1589 list_splice(&ret_pages, from);
1591 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1592 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1593 count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1594 count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1595 count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1596 trace_mm_migrate_pages(nr_succeeded, nr_failed, nr_thp_succeeded,
1597 nr_thp_failed, nr_thp_split, mode, reason);
1600 current->flags &= ~PF_SWAPWRITE;
1603 *ret_succeeded = nr_succeeded;
1608 struct page *alloc_migration_target(struct page *page, unsigned long private)
1610 struct migration_target_control *mtc;
1612 unsigned int order = 0;
1613 struct page *new_page = NULL;
1617 mtc = (struct migration_target_control *)private;
1618 gfp_mask = mtc->gfp_mask;
1620 if (nid == NUMA_NO_NODE)
1621 nid = page_to_nid(page);
1623 if (PageHuge(page)) {
1624 struct hstate *h = page_hstate(compound_head(page));
1626 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1627 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1630 if (PageTransHuge(page)) {
1632 * clear __GFP_RECLAIM to make the migration callback
1633 * consistent with regular THP allocations.
1635 gfp_mask &= ~__GFP_RECLAIM;
1636 gfp_mask |= GFP_TRANSHUGE;
1637 order = HPAGE_PMD_ORDER;
1639 zidx = zone_idx(page_zone(page));
1640 if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1641 gfp_mask |= __GFP_HIGHMEM;
1643 new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
1645 if (new_page && PageTransHuge(new_page))
1646 prep_transhuge_page(new_page);
1653 static int store_status(int __user *status, int start, int value, int nr)
1656 if (put_user(value, status + start))
1664 static int do_move_pages_to_node(struct mm_struct *mm,
1665 struct list_head *pagelist, int node)
1668 struct migration_target_control mtc = {
1670 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1673 err = migrate_pages(pagelist, alloc_migration_target, NULL,
1674 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1676 putback_movable_pages(pagelist);
1681 * Resolves the given address to a struct page, isolates it from the LRU and
1682 * puts it to the given pagelist.
1684 * errno - if the page cannot be found/isolated
1685 * 0 - when it doesn't have to be migrated because it is already on the
1687 * 1 - when it has been queued
1689 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1690 int node, struct list_head *pagelist, bool migrate_all)
1692 struct vm_area_struct *vma;
1694 unsigned int follflags;
1699 vma = find_vma(mm, addr);
1700 if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1703 /* FOLL_DUMP to ignore special (like zero) pages */
1704 follflags = FOLL_GET | FOLL_DUMP;
1705 page = follow_page(vma, addr, follflags);
1707 err = PTR_ERR(page);
1716 if (page_to_nid(page) == node)
1720 if (page_mapcount(page) > 1 && !migrate_all)
1723 if (PageHuge(page)) {
1724 if (PageHead(page)) {
1725 err = isolate_hugetlb(page, pagelist);
1732 head = compound_head(page);
1733 err = isolate_lru_page(head);
1738 list_add_tail(&head->lru, pagelist);
1739 mod_node_page_state(page_pgdat(head),
1740 NR_ISOLATED_ANON + page_is_file_lru(head),
1741 thp_nr_pages(head));
1745 * Either remove the duplicate refcount from
1746 * isolate_lru_page() or drop the page ref if it was
1751 mmap_read_unlock(mm);
1755 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1756 struct list_head *pagelist, int __user *status,
1757 int start, int i, unsigned long nr_pages)
1761 if (list_empty(pagelist))
1764 err = do_move_pages_to_node(mm, pagelist, node);
1767 * Positive err means the number of failed
1768 * pages to migrate. Since we are going to
1769 * abort and return the number of non-migrated
1770 * pages, so need to include the rest of the
1771 * nr_pages that have not been attempted as
1775 err += nr_pages - i - 1;
1778 return store_status(status, start, node, i - start);
1782 * Migrate an array of page address onto an array of nodes and fill
1783 * the corresponding array of status.
1785 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1786 unsigned long nr_pages,
1787 const void __user * __user *pages,
1788 const int __user *nodes,
1789 int __user *status, int flags)
1791 int current_node = NUMA_NO_NODE;
1792 LIST_HEAD(pagelist);
1796 lru_cache_disable();
1798 for (i = start = 0; i < nr_pages; i++) {
1799 const void __user *p;
1804 if (get_user(p, pages + i))
1806 if (get_user(node, nodes + i))
1808 addr = (unsigned long)untagged_addr(p);
1811 if (node < 0 || node >= MAX_NUMNODES)
1813 if (!node_state(node, N_MEMORY))
1817 if (!node_isset(node, task_nodes))
1820 if (current_node == NUMA_NO_NODE) {
1821 current_node = node;
1823 } else if (node != current_node) {
1824 err = move_pages_and_store_status(mm, current_node,
1825 &pagelist, status, start, i, nr_pages);
1829 current_node = node;
1833 * Errors in the page lookup or isolation are not fatal and we simply
1834 * report them via status
1836 err = add_page_for_migration(mm, addr, current_node,
1837 &pagelist, flags & MPOL_MF_MOVE_ALL);
1840 /* The page is successfully queued for migration */
1845 * If the page is already on the target node (!err), store the
1846 * node, otherwise, store the err.
1848 err = store_status(status, i, err ? : current_node, 1);
1852 err = move_pages_and_store_status(mm, current_node, &pagelist,
1853 status, start, i, nr_pages);
1856 current_node = NUMA_NO_NODE;
1859 /* Make sure we do not overwrite the existing error */
1860 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1861 status, start, i, nr_pages);
1870 * Determine the nodes of an array of pages and store it in an array of status.
1872 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1873 const void __user **pages, int *status)
1879 for (i = 0; i < nr_pages; i++) {
1880 unsigned long addr = (unsigned long)(*pages);
1881 struct vm_area_struct *vma;
1885 vma = vma_lookup(mm, addr);
1889 /* FOLL_DUMP to ignore special (like zero) pages */
1890 page = follow_page(vma, addr, FOLL_DUMP);
1892 err = PTR_ERR(page);
1896 err = page ? page_to_nid(page) : -ENOENT;
1904 mmap_read_unlock(mm);
1907 static int get_compat_pages_array(const void __user *chunk_pages[],
1908 const void __user * __user *pages,
1909 unsigned long chunk_nr)
1911 compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1915 for (i = 0; i < chunk_nr; i++) {
1916 if (get_user(p, pages32 + i))
1918 chunk_pages[i] = compat_ptr(p);
1925 * Determine the nodes of a user array of pages and store it in
1926 * a user array of status.
1928 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1929 const void __user * __user *pages,
1932 #define DO_PAGES_STAT_CHUNK_NR 16
1933 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1934 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1937 unsigned long chunk_nr;
1939 chunk_nr = nr_pages;
1940 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1941 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1943 if (in_compat_syscall()) {
1944 if (get_compat_pages_array(chunk_pages, pages,
1948 if (copy_from_user(chunk_pages, pages,
1949 chunk_nr * sizeof(*chunk_pages)))
1953 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1955 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1960 nr_pages -= chunk_nr;
1962 return nr_pages ? -EFAULT : 0;
1965 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1967 struct task_struct *task;
1968 struct mm_struct *mm;
1971 * There is no need to check if current process has the right to modify
1972 * the specified process when they are same.
1976 *mem_nodes = cpuset_mems_allowed(current);
1980 /* Find the mm_struct */
1982 task = find_task_by_vpid(pid);
1985 return ERR_PTR(-ESRCH);
1987 get_task_struct(task);
1990 * Check if this process has the right to modify the specified
1991 * process. Use the regular "ptrace_may_access()" checks.
1993 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1995 mm = ERR_PTR(-EPERM);
2000 mm = ERR_PTR(security_task_movememory(task));
2003 *mem_nodes = cpuset_mems_allowed(task);
2004 mm = get_task_mm(task);
2006 put_task_struct(task);
2008 mm = ERR_PTR(-EINVAL);
2013 * Move a list of pages in the address space of the currently executing
2016 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2017 const void __user * __user *pages,
2018 const int __user *nodes,
2019 int __user *status, int flags)
2021 struct mm_struct *mm;
2023 nodemask_t task_nodes;
2026 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2029 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2032 mm = find_mm_struct(pid, &task_nodes);
2037 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2038 nodes, status, flags);
2040 err = do_pages_stat(mm, nr_pages, pages, status);
2046 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2047 const void __user * __user *, pages,
2048 const int __user *, nodes,
2049 int __user *, status, int, flags)
2051 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2054 #ifdef CONFIG_NUMA_BALANCING
2056 * Returns true if this is a safe migration target node for misplaced NUMA
2057 * pages. Currently it only checks the watermarks which crude
2059 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2060 unsigned long nr_migrate_pages)
2064 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2065 struct zone *zone = pgdat->node_zones + z;
2067 if (!populated_zone(zone))
2070 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2071 if (!zone_watermark_ok(zone, 0,
2072 high_wmark_pages(zone) +
2081 static struct page *alloc_misplaced_dst_page(struct page *page,
2084 int nid = (int) data;
2085 struct page *newpage;
2087 newpage = __alloc_pages_node(nid,
2088 (GFP_HIGHUSER_MOVABLE |
2089 __GFP_THISNODE | __GFP_NOMEMALLOC |
2090 __GFP_NORETRY | __GFP_NOWARN) &
2096 static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2099 int nid = (int) data;
2100 struct page *newpage;
2102 newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2107 prep_transhuge_page(newpage);
2113 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2116 int nr_pages = thp_nr_pages(page);
2118 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2120 /* Do not migrate THP mapped by multiple processes */
2121 if (PageTransHuge(page) && total_mapcount(page) > 1)
2124 /* Avoid migrating to a node that is nearly full */
2125 if (!migrate_balanced_pgdat(pgdat, nr_pages))
2128 if (isolate_lru_page(page))
2131 page_lru = page_is_file_lru(page);
2132 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2136 * Isolating the page has taken another reference, so the
2137 * caller's reference can be safely dropped without the page
2138 * disappearing underneath us during migration.
2145 * Attempt to migrate a misplaced page to the specified destination
2146 * node. Caller is expected to have an elevated reference count on
2147 * the page that will be dropped by this function before returning.
2149 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2152 pg_data_t *pgdat = NODE_DATA(node);
2155 LIST_HEAD(migratepages);
2158 int nr_pages = thp_nr_pages(page);
2161 * PTE mapped THP or HugeTLB page can't reach here so the page could
2162 * be either base page or THP. And it must be head page if it is
2165 compound = PageTransHuge(page);
2168 new = alloc_misplaced_dst_page_thp;
2170 new = alloc_misplaced_dst_page;
2173 * Don't migrate file pages that are mapped in multiple processes
2174 * with execute permissions as they are probably shared libraries.
2176 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2177 (vma->vm_flags & VM_EXEC))
2181 * Also do not migrate dirty pages as not all filesystems can move
2182 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2184 if (page_is_file_lru(page) && PageDirty(page))
2187 isolated = numamigrate_isolate_page(pgdat, page);
2191 list_add(&page->lru, &migratepages);
2192 nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
2193 MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
2195 if (!list_empty(&migratepages)) {
2196 list_del(&page->lru);
2197 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2198 page_is_file_lru(page), -nr_pages);
2199 putback_lru_page(page);
2203 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
2204 BUG_ON(!list_empty(&migratepages));
2211 #endif /* CONFIG_NUMA_BALANCING */
2212 #endif /* CONFIG_NUMA */
2214 #ifdef CONFIG_DEVICE_PRIVATE
2215 static int migrate_vma_collect_skip(unsigned long start,
2217 struct mm_walk *walk)
2219 struct migrate_vma *migrate = walk->private;
2222 for (addr = start; addr < end; addr += PAGE_SIZE) {
2223 migrate->dst[migrate->npages] = 0;
2224 migrate->src[migrate->npages++] = 0;
2230 static int migrate_vma_collect_hole(unsigned long start,
2232 __always_unused int depth,
2233 struct mm_walk *walk)
2235 struct migrate_vma *migrate = walk->private;
2238 /* Only allow populating anonymous memory. */
2239 if (!vma_is_anonymous(walk->vma))
2240 return migrate_vma_collect_skip(start, end, walk);
2242 for (addr = start; addr < end; addr += PAGE_SIZE) {
2243 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2244 migrate->dst[migrate->npages] = 0;
2252 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2253 unsigned long start,
2255 struct mm_walk *walk)
2257 struct migrate_vma *migrate = walk->private;
2258 struct vm_area_struct *vma = walk->vma;
2259 struct mm_struct *mm = vma->vm_mm;
2260 unsigned long addr = start, unmapped = 0;
2265 if (pmd_none(*pmdp))
2266 return migrate_vma_collect_hole(start, end, -1, walk);
2268 if (pmd_trans_huge(*pmdp)) {
2271 ptl = pmd_lock(mm, pmdp);
2272 if (unlikely(!pmd_trans_huge(*pmdp))) {
2277 page = pmd_page(*pmdp);
2278 if (is_huge_zero_page(page)) {
2280 split_huge_pmd(vma, pmdp, addr);
2281 if (pmd_trans_unstable(pmdp))
2282 return migrate_vma_collect_skip(start, end,
2289 if (unlikely(!trylock_page(page)))
2290 return migrate_vma_collect_skip(start, end,
2292 ret = split_huge_page(page);
2296 return migrate_vma_collect_skip(start, end,
2298 if (pmd_none(*pmdp))
2299 return migrate_vma_collect_hole(start, end, -1,
2304 if (unlikely(pmd_bad(*pmdp)))
2305 return migrate_vma_collect_skip(start, end, walk);
2307 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2308 arch_enter_lazy_mmu_mode();
2310 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2311 unsigned long mpfn = 0, pfn;
2318 if (pte_none(pte)) {
2319 if (vma_is_anonymous(vma)) {
2320 mpfn = MIGRATE_PFN_MIGRATE;
2326 if (!pte_present(pte)) {
2328 * Only care about unaddressable device page special
2329 * page table entry. Other special swap entries are not
2330 * migratable, and we ignore regular swapped page.
2332 entry = pte_to_swp_entry(pte);
2333 if (!is_device_private_entry(entry))
2336 page = pfn_swap_entry_to_page(entry);
2337 if (!(migrate->flags &
2338 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2339 page->pgmap->owner != migrate->pgmap_owner)
2342 mpfn = migrate_pfn(page_to_pfn(page)) |
2343 MIGRATE_PFN_MIGRATE;
2344 if (is_writable_device_private_entry(entry))
2345 mpfn |= MIGRATE_PFN_WRITE;
2347 if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2350 if (is_zero_pfn(pfn)) {
2351 mpfn = MIGRATE_PFN_MIGRATE;
2355 page = vm_normal_page(migrate->vma, addr, pte);
2356 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2357 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2360 /* FIXME support THP */
2361 if (!page || !page->mapping || PageTransCompound(page)) {
2367 * By getting a reference on the page we pin it and that blocks
2368 * any kind of migration. Side effect is that it "freezes" the
2371 * We drop this reference after isolating the page from the lru
2372 * for non device page (device page are not on the lru and thus
2373 * can't be dropped from it).
2379 * Optimize for the common case where page is only mapped once
2380 * in one process. If we can lock the page, then we can safely
2381 * set up a special migration page table entry now.
2383 if (trylock_page(page)) {
2386 mpfn |= MIGRATE_PFN_LOCKED;
2387 ptep_get_and_clear(mm, addr, ptep);
2389 /* Setup special migration page table entry */
2390 if (mpfn & MIGRATE_PFN_WRITE)
2391 entry = make_writable_migration_entry(
2394 entry = make_readable_migration_entry(
2396 swp_pte = swp_entry_to_pte(entry);
2397 if (pte_present(pte)) {
2398 if (pte_soft_dirty(pte))
2399 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2400 if (pte_uffd_wp(pte))
2401 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2403 if (pte_swp_soft_dirty(pte))
2404 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2405 if (pte_swp_uffd_wp(pte))
2406 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2408 set_pte_at(mm, addr, ptep, swp_pte);
2411 * This is like regular unmap: we remove the rmap and
2412 * drop page refcount. Page won't be freed, as we took
2413 * a reference just above.
2415 page_remove_rmap(page, false);
2418 if (pte_present(pte))
2423 migrate->dst[migrate->npages] = 0;
2424 migrate->src[migrate->npages++] = mpfn;
2427 /* Only flush the TLB if we actually modified any entries */
2429 flush_tlb_range(walk->vma, start, end);
2431 arch_leave_lazy_mmu_mode();
2432 pte_unmap_unlock(ptep - 1, ptl);
2437 static const struct mm_walk_ops migrate_vma_walk_ops = {
2438 .pmd_entry = migrate_vma_collect_pmd,
2439 .pte_hole = migrate_vma_collect_hole,
2443 * migrate_vma_collect() - collect pages over a range of virtual addresses
2444 * @migrate: migrate struct containing all migration information
2446 * This will walk the CPU page table. For each virtual address backed by a
2447 * valid page, it updates the src array and takes a reference on the page, in
2448 * order to pin the page until we lock it and unmap it.
2450 static void migrate_vma_collect(struct migrate_vma *migrate)
2452 struct mmu_notifier_range range;
2455 * Note that the pgmap_owner is passed to the mmu notifier callback so
2456 * that the registered device driver can skip invalidating device
2457 * private page mappings that won't be migrated.
2459 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2460 migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
2461 migrate->pgmap_owner);
2462 mmu_notifier_invalidate_range_start(&range);
2464 walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2465 &migrate_vma_walk_ops, migrate);
2467 mmu_notifier_invalidate_range_end(&range);
2468 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2472 * migrate_vma_check_page() - check if page is pinned or not
2473 * @page: struct page to check
2475 * Pinned pages cannot be migrated. This is the same test as in
2476 * migrate_page_move_mapping(), except that here we allow migration of a
2479 static bool migrate_vma_check_page(struct page *page)
2482 * One extra ref because caller holds an extra reference, either from
2483 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2489 * FIXME support THP (transparent huge page), it is bit more complex to
2490 * check them than regular pages, because they can be mapped with a pmd
2491 * or with a pte (split pte mapping).
2493 if (PageCompound(page))
2496 /* Page from ZONE_DEVICE have one extra reference */
2497 if (is_zone_device_page(page)) {
2499 * Private page can never be pin as they have no valid pte and
2500 * GUP will fail for those. Yet if there is a pending migration
2501 * a thread might try to wait on the pte migration entry and
2502 * will bump the page reference count. Sadly there is no way to
2503 * differentiate a regular pin from migration wait. Hence to
2504 * avoid 2 racing thread trying to migrate back to CPU to enter
2505 * infinite loop (one stopping migration because the other is
2506 * waiting on pte migration entry). We always return true here.
2508 * FIXME proper solution is to rework migration_entry_wait() so
2509 * it does not need to take a reference on page.
2511 return is_device_private_page(page);
2514 /* For file back page */
2515 if (page_mapping(page))
2516 extra += 1 + page_has_private(page);
2518 if ((page_count(page) - extra) > page_mapcount(page))
2525 * migrate_vma_prepare() - lock pages and isolate them from the lru
2526 * @migrate: migrate struct containing all migration information
2528 * This locks pages that have been collected by migrate_vma_collect(). Once each
2529 * page is locked it is isolated from the lru (for non-device pages). Finally,
2530 * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2531 * migrated by concurrent kernel threads.
2533 static void migrate_vma_prepare(struct migrate_vma *migrate)
2535 const unsigned long npages = migrate->npages;
2536 const unsigned long start = migrate->start;
2537 unsigned long addr, i, restore = 0;
2538 bool allow_drain = true;
2542 for (i = 0; (i < npages) && migrate->cpages; i++) {
2543 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2549 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2551 * Because we are migrating several pages there can be
2552 * a deadlock between 2 concurrent migration where each
2553 * are waiting on each other page lock.
2555 * Make migrate_vma() a best effort thing and backoff
2556 * for any page we can not lock right away.
2558 if (!trylock_page(page)) {
2559 migrate->src[i] = 0;
2565 migrate->src[i] |= MIGRATE_PFN_LOCKED;
2568 /* ZONE_DEVICE pages are not on LRU */
2569 if (!is_zone_device_page(page)) {
2570 if (!PageLRU(page) && allow_drain) {
2571 /* Drain CPU's pagevec */
2572 lru_add_drain_all();
2573 allow_drain = false;
2576 if (isolate_lru_page(page)) {
2578 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2582 migrate->src[i] = 0;
2590 /* Drop the reference we took in collect */
2594 if (!migrate_vma_check_page(page)) {
2596 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2600 if (!is_zone_device_page(page)) {
2602 putback_lru_page(page);
2605 migrate->src[i] = 0;
2609 if (!is_zone_device_page(page))
2610 putback_lru_page(page);
2617 for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2618 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2620 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2623 remove_migration_pte(page, migrate->vma, addr, page);
2625 migrate->src[i] = 0;
2633 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2634 * @migrate: migrate struct containing all migration information
2636 * Replace page mapping (CPU page table pte) with a special migration pte entry
2637 * and check again if it has been pinned. Pinned pages are restored because we
2638 * cannot migrate them.
2640 * This is the last step before we call the device driver callback to allocate
2641 * destination memory and copy contents of original page over to new page.
2643 static void migrate_vma_unmap(struct migrate_vma *migrate)
2645 const unsigned long npages = migrate->npages;
2646 const unsigned long start = migrate->start;
2647 unsigned long addr, i, restore = 0;
2649 for (i = 0; i < npages; i++) {
2650 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2652 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2655 if (page_mapped(page)) {
2656 try_to_migrate(page, 0);
2657 if (page_mapped(page))
2661 if (migrate_vma_check_page(page))
2665 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2670 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2671 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2673 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2676 remove_migration_ptes(page, page, false);
2678 migrate->src[i] = 0;
2682 if (is_zone_device_page(page))
2685 putback_lru_page(page);
2690 * migrate_vma_setup() - prepare to migrate a range of memory
2691 * @args: contains the vma, start, and pfns arrays for the migration
2693 * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2696 * Prepare to migrate a range of memory virtual address range by collecting all
2697 * the pages backing each virtual address in the range, saving them inside the
2698 * src array. Then lock those pages and unmap them. Once the pages are locked
2699 * and unmapped, check whether each page is pinned or not. Pages that aren't
2700 * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2701 * corresponding src array entry. Then restores any pages that are pinned, by
2702 * remapping and unlocking those pages.
2704 * The caller should then allocate destination memory and copy source memory to
2705 * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2706 * flag set). Once these are allocated and copied, the caller must update each
2707 * corresponding entry in the dst array with the pfn value of the destination
2708 * page and with the MIGRATE_PFN_VALID and MIGRATE_PFN_LOCKED flags set
2709 * (destination pages must have their struct pages locked, via lock_page()).
2711 * Note that the caller does not have to migrate all the pages that are marked
2712 * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2713 * device memory to system memory. If the caller cannot migrate a device page
2714 * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2715 * consequences for the userspace process, so it must be avoided if at all
2718 * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2719 * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2720 * allowing the caller to allocate device memory for those unbacked virtual
2721 * addresses. For this the caller simply has to allocate device memory and
2722 * properly set the destination entry like for regular migration. Note that
2723 * this can still fail, and thus inside the device driver you must check if the
2724 * migration was successful for those entries after calling migrate_vma_pages(),
2725 * just like for regular migration.
2727 * After that, the callers must call migrate_vma_pages() to go over each entry
2728 * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2729 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2730 * then migrate_vma_pages() to migrate struct page information from the source
2731 * struct page to the destination struct page. If it fails to migrate the
2732 * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2735 * At this point all successfully migrated pages have an entry in the src
2736 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2737 * array entry with MIGRATE_PFN_VALID flag set.
2739 * Once migrate_vma_pages() returns the caller may inspect which pages were
2740 * successfully migrated, and which were not. Successfully migrated pages will
2741 * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2743 * It is safe to update device page table after migrate_vma_pages() because
2744 * both destination and source page are still locked, and the mmap_lock is held
2745 * in read mode (hence no one can unmap the range being migrated).
2747 * Once the caller is done cleaning up things and updating its page table (if it
2748 * chose to do so, this is not an obligation) it finally calls
2749 * migrate_vma_finalize() to update the CPU page table to point to new pages
2750 * for successfully migrated pages or otherwise restore the CPU page table to
2751 * point to the original source pages.
2753 int migrate_vma_setup(struct migrate_vma *args)
2755 long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2757 args->start &= PAGE_MASK;
2758 args->end &= PAGE_MASK;
2759 if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2760 (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2764 if (args->start < args->vma->vm_start ||
2765 args->start >= args->vma->vm_end)
2767 if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2769 if (!args->src || !args->dst)
2772 memset(args->src, 0, sizeof(*args->src) * nr_pages);
2776 migrate_vma_collect(args);
2779 migrate_vma_prepare(args);
2781 migrate_vma_unmap(args);
2784 * At this point pages are locked and unmapped, and thus they have
2785 * stable content and can safely be copied to destination memory that
2786 * is allocated by the drivers.
2791 EXPORT_SYMBOL(migrate_vma_setup);
2794 * This code closely matches the code in:
2795 * __handle_mm_fault()
2796 * handle_pte_fault()
2797 * do_anonymous_page()
2798 * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2801 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2806 struct vm_area_struct *vma = migrate->vma;
2807 struct mm_struct *mm = vma->vm_mm;
2817 /* Only allow populating anonymous memory */
2818 if (!vma_is_anonymous(vma))
2821 pgdp = pgd_offset(mm, addr);
2822 p4dp = p4d_alloc(mm, pgdp, addr);
2825 pudp = pud_alloc(mm, p4dp, addr);
2828 pmdp = pmd_alloc(mm, pudp, addr);
2832 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2836 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2837 * pte_offset_map() on pmds where a huge pmd might be created
2838 * from a different thread.
2840 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2841 * parallel threads are excluded by other means.
2843 * Here we only have mmap_read_lock(mm).
2845 if (pte_alloc(mm, pmdp))
2848 /* See the comment in pte_alloc_one_map() */
2849 if (unlikely(pmd_trans_unstable(pmdp)))
2852 if (unlikely(anon_vma_prepare(vma)))
2854 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
2858 * The memory barrier inside __SetPageUptodate makes sure that
2859 * preceding stores to the page contents become visible before
2860 * the set_pte_at() write.
2862 __SetPageUptodate(page);
2864 if (is_zone_device_page(page)) {
2865 if (is_device_private_page(page)) {
2866 swp_entry_t swp_entry;
2868 if (vma->vm_flags & VM_WRITE)
2869 swp_entry = make_writable_device_private_entry(
2872 swp_entry = make_readable_device_private_entry(
2874 entry = swp_entry_to_pte(swp_entry);
2877 * For now we only support migrating to un-addressable
2880 pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2884 entry = mk_pte(page, vma->vm_page_prot);
2885 if (vma->vm_flags & VM_WRITE)
2886 entry = pte_mkwrite(pte_mkdirty(entry));
2889 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2891 if (check_stable_address_space(mm))
2894 if (pte_present(*ptep)) {
2895 unsigned long pfn = pte_pfn(*ptep);
2897 if (!is_zero_pfn(pfn))
2900 } else if (!pte_none(*ptep))
2904 * Check for userfaultfd but do not deliver the fault. Instead,
2907 if (userfaultfd_missing(vma))
2910 inc_mm_counter(mm, MM_ANONPAGES);
2911 page_add_new_anon_rmap(page, vma, addr, false);
2912 if (!is_zone_device_page(page))
2913 lru_cache_add_inactive_or_unevictable(page, vma);
2917 flush_cache_page(vma, addr, pte_pfn(*ptep));
2918 ptep_clear_flush_notify(vma, addr, ptep);
2919 set_pte_at_notify(mm, addr, ptep, entry);
2920 update_mmu_cache(vma, addr, ptep);
2922 /* No need to invalidate - it was non-present before */
2923 set_pte_at(mm, addr, ptep, entry);
2924 update_mmu_cache(vma, addr, ptep);
2927 pte_unmap_unlock(ptep, ptl);
2928 *src = MIGRATE_PFN_MIGRATE;
2932 pte_unmap_unlock(ptep, ptl);
2934 *src &= ~MIGRATE_PFN_MIGRATE;
2938 * migrate_vma_pages() - migrate meta-data from src page to dst page
2939 * @migrate: migrate struct containing all migration information
2941 * This migrates struct page meta-data from source struct page to destination
2942 * struct page. This effectively finishes the migration from source page to the
2945 void migrate_vma_pages(struct migrate_vma *migrate)
2947 const unsigned long npages = migrate->npages;
2948 const unsigned long start = migrate->start;
2949 struct mmu_notifier_range range;
2950 unsigned long addr, i;
2951 bool notified = false;
2953 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2954 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2955 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2956 struct address_space *mapping;
2960 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2965 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2970 mmu_notifier_range_init_owner(&range,
2971 MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2972 migrate->vma->vm_mm, addr, migrate->end,
2973 migrate->pgmap_owner);
2974 mmu_notifier_invalidate_range_start(&range);
2976 migrate_vma_insert_page(migrate, addr, newpage,
2981 mapping = page_mapping(page);
2983 if (is_zone_device_page(newpage)) {
2984 if (is_device_private_page(newpage)) {
2986 * For now only support private anonymous when
2987 * migrating to un-addressable device memory.
2990 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2995 * Other types of ZONE_DEVICE page are not
2998 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3003 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
3004 if (r != MIGRATEPAGE_SUCCESS)
3005 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3009 * No need to double call mmu_notifier->invalidate_range() callback as
3010 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
3011 * did already call it.
3014 mmu_notifier_invalidate_range_only_end(&range);
3016 EXPORT_SYMBOL(migrate_vma_pages);
3019 * migrate_vma_finalize() - restore CPU page table entry
3020 * @migrate: migrate struct containing all migration information
3022 * This replaces the special migration pte entry with either a mapping to the
3023 * new page if migration was successful for that page, or to the original page
3026 * This also unlocks the pages and puts them back on the lru, or drops the extra
3027 * refcount, for device pages.
3029 void migrate_vma_finalize(struct migrate_vma *migrate)
3031 const unsigned long npages = migrate->npages;
3034 for (i = 0; i < npages; i++) {
3035 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
3036 struct page *page = migrate_pfn_to_page(migrate->src[i]);
3040 unlock_page(newpage);
3046 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
3048 unlock_page(newpage);
3054 remove_migration_ptes(page, newpage, false);
3057 if (is_zone_device_page(page))
3060 putback_lru_page(page);
3062 if (newpage != page) {
3063 unlock_page(newpage);
3064 if (is_zone_device_page(newpage))
3067 putback_lru_page(newpage);
3071 EXPORT_SYMBOL(migrate_vma_finalize);
3072 #endif /* CONFIG_DEVICE_PRIVATE */
3074 #if defined(CONFIG_HOTPLUG_CPU)
3075 /* Disable reclaim-based migration. */
3076 static void __disable_all_migrate_targets(void)
3080 for_each_online_node(node)
3081 node_demotion[node] = NUMA_NO_NODE;
3084 static void disable_all_migrate_targets(void)
3086 __disable_all_migrate_targets();
3089 * Ensure that the "disable" is visible across the system.
3090 * Readers will see either a combination of before+disable
3091 * state or disable+after. They will never see before and
3092 * after state together.
3094 * The before+after state together might have cycles and
3095 * could cause readers to do things like loop until this
3096 * function finishes. This ensures they can only see a
3097 * single "bad" read and would, for instance, only loop
3104 * Find an automatic demotion target for 'node'.
3105 * Failing here is OK. It might just indicate
3106 * being at the end of a chain.
3108 static int establish_migrate_target(int node, nodemask_t *used)
3110 int migration_target;
3113 * Can not set a migration target on a
3114 * node with it already set.
3116 * No need for READ_ONCE() here since this
3117 * in the write path for node_demotion[].
3118 * This should be the only thread writing.
3120 if (node_demotion[node] != NUMA_NO_NODE)
3121 return NUMA_NO_NODE;
3123 migration_target = find_next_best_node(node, used);
3124 if (migration_target == NUMA_NO_NODE)
3125 return NUMA_NO_NODE;
3127 node_demotion[node] = migration_target;
3129 return migration_target;
3133 * When memory fills up on a node, memory contents can be
3134 * automatically migrated to another node instead of
3135 * discarded at reclaim.
3137 * Establish a "migration path" which will start at nodes
3138 * with CPUs and will follow the priorities used to build the
3139 * page allocator zonelists.
3141 * The difference here is that cycles must be avoided. If
3142 * node0 migrates to node1, then neither node1, nor anything
3143 * node1 migrates to can migrate to node0.
3145 * This function can run simultaneously with readers of
3146 * node_demotion[]. However, it can not run simultaneously
3147 * with itself. Exclusion is provided by memory hotplug events
3148 * being single-threaded.
3150 static void __set_migration_target_nodes(void)
3152 nodemask_t next_pass = NODE_MASK_NONE;
3153 nodemask_t this_pass = NODE_MASK_NONE;
3154 nodemask_t used_targets = NODE_MASK_NONE;
3158 * Avoid any oddities like cycles that could occur
3159 * from changes in the topology. This will leave
3160 * a momentary gap when migration is disabled.
3162 disable_all_migrate_targets();
3165 * Allocations go close to CPUs, first. Assume that
3166 * the migration path starts at the nodes with CPUs.
3168 next_pass = node_states[N_CPU];
3170 this_pass = next_pass;
3171 next_pass = NODE_MASK_NONE;
3173 * To avoid cycles in the migration "graph", ensure
3174 * that migration sources are not future targets by
3175 * setting them in 'used_targets'. Do this only
3176 * once per pass so that multiple source nodes can
3177 * share a target node.
3179 * 'used_targets' will become unavailable in future
3180 * passes. This limits some opportunities for
3181 * multiple source nodes to share a destination.
3183 nodes_or(used_targets, used_targets, this_pass);
3184 for_each_node_mask(node, this_pass) {
3185 int target_node = establish_migrate_target(node, &used_targets);
3187 if (target_node == NUMA_NO_NODE)
3191 * Visit targets from this pass in the next pass.
3192 * Eventually, every node will have been part of
3193 * a pass, and will become set in 'used_targets'.
3195 node_set(target_node, next_pass);
3198 * 'next_pass' contains nodes which became migration
3199 * targets in this pass. Make additional passes until
3200 * no more migrations targets are available.
3202 if (!nodes_empty(next_pass))
3207 * For callers that do not hold get_online_mems() already.
3209 static void set_migration_target_nodes(void)
3212 __set_migration_target_nodes();
3217 * This leaves migrate-on-reclaim transiently disabled between
3218 * the MEM_GOING_OFFLINE and MEM_OFFLINE events. This runs
3219 * whether reclaim-based migration is enabled or not, which
3220 * ensures that the user can turn reclaim-based migration at
3221 * any time without needing to recalculate migration targets.
3223 * These callbacks already hold get_online_mems(). That is why
3224 * __set_migration_target_nodes() can be used as opposed to
3225 * set_migration_target_nodes().
3227 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
3228 unsigned long action, void *_arg)
3230 struct memory_notify *arg = _arg;
3233 * Only update the node migration order when a node is
3234 * changing status, like online->offline. This avoids
3235 * the overhead of synchronize_rcu() in most cases.
3237 if (arg->status_change_nid < 0)
3238 return notifier_from_errno(0);
3241 case MEM_GOING_OFFLINE:
3243 * Make sure there are not transient states where
3244 * an offline node is a migration target. This
3245 * will leave migration disabled until the offline
3246 * completes and the MEM_OFFLINE case below runs.
3248 disable_all_migrate_targets();
3253 * Recalculate the target nodes once the node
3254 * reaches its final state (online or offline).
3256 __set_migration_target_nodes();
3258 case MEM_CANCEL_OFFLINE:
3260 * MEM_GOING_OFFLINE disabled all the migration
3261 * targets. Reenable them.
3263 __set_migration_target_nodes();
3265 case MEM_GOING_ONLINE:
3266 case MEM_CANCEL_ONLINE:
3270 return notifier_from_errno(0);
3274 * React to hotplug events that might affect the migration targets
3275 * like events that online or offline NUMA nodes.
3277 * The ordering is also currently dependent on which nodes have
3278 * CPUs. That means we need CPU on/offline notification too.
3280 static int migration_online_cpu(unsigned int cpu)
3282 set_migration_target_nodes();
3286 static int migration_offline_cpu(unsigned int cpu)
3288 set_migration_target_nodes();
3292 static int __init migrate_on_reclaim_init(void)
3296 ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3297 NULL, migration_offline_cpu);
3299 * In the unlikely case that this fails, the automatic
3300 * migration targets may become suboptimal for nodes
3301 * where N_CPU changes. With such a small impact in a
3302 * rare case, do not bother trying to do anything special.
3305 ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3306 migration_online_cpu, NULL);
3309 hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3312 late_initcall(migrate_on_reclaim_init);
3313 #endif /* CONFIG_HOTPLUG_CPU */