1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
5 #include <linux/sched.h>
6 #include <linux/sched/mm.h>
7 #include <linux/sched/coredump.h>
8 #include <linux/mmu_notifier.h>
9 #include <linux/rmap.h>
10 #include <linux/swap.h>
11 #include <linux/mm_inline.h>
12 #include <linux/kthread.h>
13 #include <linux/khugepaged.h>
14 #include <linux/freezer.h>
15 #include <linux/mman.h>
16 #include <linux/hashtable.h>
17 #include <linux/userfaultfd_k.h>
18 #include <linux/page_idle.h>
19 #include <linux/page_table_check.h>
20 #include <linux/swapops.h>
21 #include <linux/shmem_fs.h>
24 #include <asm/pgalloc.h>
33 SCAN_EXCEED_SHARED_PTE,
37 SCAN_LACK_REFERENCED_PAGE,
50 SCAN_ALLOC_HUGE_PAGE_FAIL,
51 SCAN_CGROUP_CHARGE_FAIL,
53 SCAN_PAGE_HAS_PRIVATE,
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/huge_memory.h>
59 static struct task_struct *khugepaged_thread __read_mostly;
60 static DEFINE_MUTEX(khugepaged_mutex);
62 /* default scan 8*512 pte (or vmas) every 30 second */
63 static unsigned int khugepaged_pages_to_scan __read_mostly;
64 static unsigned int khugepaged_pages_collapsed;
65 static unsigned int khugepaged_full_scans;
66 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
67 /* during fragmentation poll the hugepage allocator once every minute */
68 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
69 static unsigned long khugepaged_sleep_expire;
70 static DEFINE_SPINLOCK(khugepaged_mm_lock);
71 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
73 * default collapse hugepages if there is at least one pte mapped like
74 * it would have happened if the vma was large enough during page
77 static unsigned int khugepaged_max_ptes_none __read_mostly;
78 static unsigned int khugepaged_max_ptes_swap __read_mostly;
79 static unsigned int khugepaged_max_ptes_shared __read_mostly;
81 #define MM_SLOTS_HASH_BITS 10
82 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
84 static struct kmem_cache *mm_slot_cache __read_mostly;
86 #define MAX_PTE_MAPPED_THP 8
89 * struct mm_slot - hash lookup from mm to mm_slot
90 * @hash: hash collision list
91 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
92 * @mm: the mm that this information is valid for
93 * @nr_pte_mapped_thp: number of pte mapped THP
94 * @pte_mapped_thp: address array corresponding pte mapped THP
97 struct hlist_node hash;
98 struct list_head mm_node;
101 /* pte-mapped THP in this mm */
102 int nr_pte_mapped_thp;
103 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
107 * struct khugepaged_scan - cursor for scanning
108 * @mm_head: the head of the mm list to scan
109 * @mm_slot: the current mm_slot we are scanning
110 * @address: the next address inside that to be scanned
112 * There is only the one khugepaged_scan instance of this cursor structure.
114 struct khugepaged_scan {
115 struct list_head mm_head;
116 struct mm_slot *mm_slot;
117 unsigned long address;
120 static struct khugepaged_scan khugepaged_scan = {
121 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
125 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
126 struct kobj_attribute *attr,
129 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
132 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
133 struct kobj_attribute *attr,
134 const char *buf, size_t count)
139 err = kstrtouint(buf, 10, &msecs);
143 khugepaged_scan_sleep_millisecs = msecs;
144 khugepaged_sleep_expire = 0;
145 wake_up_interruptible(&khugepaged_wait);
149 static struct kobj_attribute scan_sleep_millisecs_attr =
150 __ATTR_RW(scan_sleep_millisecs);
152 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
153 struct kobj_attribute *attr,
156 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
159 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
160 struct kobj_attribute *attr,
161 const char *buf, size_t count)
166 err = kstrtouint(buf, 10, &msecs);
170 khugepaged_alloc_sleep_millisecs = msecs;
171 khugepaged_sleep_expire = 0;
172 wake_up_interruptible(&khugepaged_wait);
176 static struct kobj_attribute alloc_sleep_millisecs_attr =
177 __ATTR_RW(alloc_sleep_millisecs);
179 static ssize_t pages_to_scan_show(struct kobject *kobj,
180 struct kobj_attribute *attr,
183 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
185 static ssize_t pages_to_scan_store(struct kobject *kobj,
186 struct kobj_attribute *attr,
187 const char *buf, size_t count)
192 err = kstrtouint(buf, 10, &pages);
196 khugepaged_pages_to_scan = pages;
200 static struct kobj_attribute pages_to_scan_attr =
201 __ATTR_RW(pages_to_scan);
203 static ssize_t pages_collapsed_show(struct kobject *kobj,
204 struct kobj_attribute *attr,
207 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
209 static struct kobj_attribute pages_collapsed_attr =
210 __ATTR_RO(pages_collapsed);
212 static ssize_t full_scans_show(struct kobject *kobj,
213 struct kobj_attribute *attr,
216 return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
218 static struct kobj_attribute full_scans_attr =
219 __ATTR_RO(full_scans);
221 static ssize_t defrag_show(struct kobject *kobj,
222 struct kobj_attribute *attr, char *buf)
224 return single_hugepage_flag_show(kobj, attr, buf,
225 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
227 static ssize_t defrag_store(struct kobject *kobj,
228 struct kobj_attribute *attr,
229 const char *buf, size_t count)
231 return single_hugepage_flag_store(kobj, attr, buf, count,
232 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
234 static struct kobj_attribute khugepaged_defrag_attr =
238 * max_ptes_none controls if khugepaged should collapse hugepages over
239 * any unmapped ptes in turn potentially increasing the memory
240 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
241 * reduce the available free memory in the system as it
242 * runs. Increasing max_ptes_none will instead potentially reduce the
243 * free memory in the system during the khugepaged scan.
245 static ssize_t max_ptes_none_show(struct kobject *kobj,
246 struct kobj_attribute *attr,
249 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
251 static ssize_t max_ptes_none_store(struct kobject *kobj,
252 struct kobj_attribute *attr,
253 const char *buf, size_t count)
256 unsigned long max_ptes_none;
258 err = kstrtoul(buf, 10, &max_ptes_none);
259 if (err || max_ptes_none > HPAGE_PMD_NR - 1)
262 khugepaged_max_ptes_none = max_ptes_none;
266 static struct kobj_attribute khugepaged_max_ptes_none_attr =
267 __ATTR_RW(max_ptes_none);
269 static ssize_t max_ptes_swap_show(struct kobject *kobj,
270 struct kobj_attribute *attr,
273 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
276 static ssize_t max_ptes_swap_store(struct kobject *kobj,
277 struct kobj_attribute *attr,
278 const char *buf, size_t count)
281 unsigned long max_ptes_swap;
283 err = kstrtoul(buf, 10, &max_ptes_swap);
284 if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
287 khugepaged_max_ptes_swap = max_ptes_swap;
292 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
293 __ATTR_RW(max_ptes_swap);
295 static ssize_t max_ptes_shared_show(struct kobject *kobj,
296 struct kobj_attribute *attr,
299 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
302 static ssize_t max_ptes_shared_store(struct kobject *kobj,
303 struct kobj_attribute *attr,
304 const char *buf, size_t count)
307 unsigned long max_ptes_shared;
309 err = kstrtoul(buf, 10, &max_ptes_shared);
310 if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
313 khugepaged_max_ptes_shared = max_ptes_shared;
318 static struct kobj_attribute khugepaged_max_ptes_shared_attr =
319 __ATTR_RW(max_ptes_shared);
321 static struct attribute *khugepaged_attr[] = {
322 &khugepaged_defrag_attr.attr,
323 &khugepaged_max_ptes_none_attr.attr,
324 &khugepaged_max_ptes_swap_attr.attr,
325 &khugepaged_max_ptes_shared_attr.attr,
326 &pages_to_scan_attr.attr,
327 &pages_collapsed_attr.attr,
328 &full_scans_attr.attr,
329 &scan_sleep_millisecs_attr.attr,
330 &alloc_sleep_millisecs_attr.attr,
334 struct attribute_group khugepaged_attr_group = {
335 .attrs = khugepaged_attr,
336 .name = "khugepaged",
338 #endif /* CONFIG_SYSFS */
340 int hugepage_madvise(struct vm_area_struct *vma,
341 unsigned long *vm_flags, int advice)
347 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
348 * can't handle this properly after s390_enable_sie, so we simply
349 * ignore the madvise to prevent qemu from causing a SIGSEGV.
351 if (mm_has_pgste(vma->vm_mm))
354 *vm_flags &= ~VM_NOHUGEPAGE;
355 *vm_flags |= VM_HUGEPAGE;
357 * If the vma become good for khugepaged to scan,
358 * register it here without waiting a page fault that
359 * may not happen any time soon.
361 khugepaged_enter_vma(vma, *vm_flags);
363 case MADV_NOHUGEPAGE:
364 *vm_flags &= ~VM_HUGEPAGE;
365 *vm_flags |= VM_NOHUGEPAGE;
367 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
368 * this vma even if we leave the mm registered in khugepaged if
369 * it got registered before VM_NOHUGEPAGE was set.
377 int __init khugepaged_init(void)
379 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
380 sizeof(struct mm_slot),
381 __alignof__(struct mm_slot), 0, NULL);
385 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
386 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
387 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
388 khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
393 void __init khugepaged_destroy(void)
395 kmem_cache_destroy(mm_slot_cache);
398 static inline struct mm_slot *alloc_mm_slot(void)
400 if (!mm_slot_cache) /* initialization failed */
402 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
405 static inline void free_mm_slot(struct mm_slot *mm_slot)
407 kmem_cache_free(mm_slot_cache, mm_slot);
410 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
412 struct mm_slot *mm_slot;
414 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
415 if (mm == mm_slot->mm)
421 static void insert_to_mm_slots_hash(struct mm_struct *mm,
422 struct mm_slot *mm_slot)
425 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
428 static inline int khugepaged_test_exit(struct mm_struct *mm)
430 return atomic_read(&mm->mm_users) == 0;
433 void __khugepaged_enter(struct mm_struct *mm)
435 struct mm_slot *mm_slot;
438 mm_slot = alloc_mm_slot();
442 /* __khugepaged_exit() must not run from under us */
443 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
444 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
445 free_mm_slot(mm_slot);
449 spin_lock(&khugepaged_mm_lock);
450 insert_to_mm_slots_hash(mm, mm_slot);
452 * Insert just behind the scanning cursor, to let the area settle
455 wakeup = list_empty(&khugepaged_scan.mm_head);
456 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
457 spin_unlock(&khugepaged_mm_lock);
461 wake_up_interruptible(&khugepaged_wait);
464 void khugepaged_enter_vma(struct vm_area_struct *vma,
465 unsigned long vm_flags)
467 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
468 khugepaged_enabled()) {
469 if (hugepage_vma_check(vma, vm_flags, false))
470 __khugepaged_enter(vma->vm_mm);
474 void __khugepaged_exit(struct mm_struct *mm)
476 struct mm_slot *mm_slot;
479 spin_lock(&khugepaged_mm_lock);
480 mm_slot = get_mm_slot(mm);
481 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
482 hash_del(&mm_slot->hash);
483 list_del(&mm_slot->mm_node);
486 spin_unlock(&khugepaged_mm_lock);
489 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
490 free_mm_slot(mm_slot);
492 } else if (mm_slot) {
494 * This is required to serialize against
495 * khugepaged_test_exit() (which is guaranteed to run
496 * under mmap sem read mode). Stop here (after we
497 * return all pagetables will be destroyed) until
498 * khugepaged has finished working on the pagetables
499 * under the mmap_lock.
502 mmap_write_unlock(mm);
506 static void release_pte_page(struct page *page)
508 mod_node_page_state(page_pgdat(page),
509 NR_ISOLATED_ANON + page_is_file_lru(page),
512 putback_lru_page(page);
515 static void release_pte_pages(pte_t *pte, pte_t *_pte,
516 struct list_head *compound_pagelist)
518 struct page *page, *tmp;
520 while (--_pte >= pte) {
521 pte_t pteval = *_pte;
523 page = pte_page(pteval);
524 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
526 release_pte_page(page);
529 list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
530 list_del(&page->lru);
531 release_pte_page(page);
535 static bool is_refcount_suitable(struct page *page)
537 int expected_refcount;
539 expected_refcount = total_mapcount(page);
540 if (PageSwapCache(page))
541 expected_refcount += compound_nr(page);
543 return page_count(page) == expected_refcount;
546 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
547 unsigned long address,
549 struct list_head *compound_pagelist)
551 struct page *page = NULL;
553 int none_or_zero = 0, shared = 0, result = 0, referenced = 0;
554 bool writable = false;
556 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
557 _pte++, address += PAGE_SIZE) {
558 pte_t pteval = *_pte;
559 if (pte_none(pteval) || (pte_present(pteval) &&
560 is_zero_pfn(pte_pfn(pteval)))) {
561 if (!userfaultfd_armed(vma) &&
562 ++none_or_zero <= khugepaged_max_ptes_none) {
565 result = SCAN_EXCEED_NONE_PTE;
566 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
570 if (!pte_present(pteval)) {
571 result = SCAN_PTE_NON_PRESENT;
574 page = vm_normal_page(vma, address, pteval);
575 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
576 result = SCAN_PAGE_NULL;
580 VM_BUG_ON_PAGE(!PageAnon(page), page);
582 if (page_mapcount(page) > 1 &&
583 ++shared > khugepaged_max_ptes_shared) {
584 result = SCAN_EXCEED_SHARED_PTE;
585 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
589 if (PageCompound(page)) {
591 page = compound_head(page);
594 * Check if we have dealt with the compound page
597 list_for_each_entry(p, compound_pagelist, lru) {
604 * We can do it before isolate_lru_page because the
605 * page can't be freed from under us. NOTE: PG_lock
606 * is needed to serialize against split_huge_page
607 * when invoked from the VM.
609 if (!trylock_page(page)) {
610 result = SCAN_PAGE_LOCK;
615 * Check if the page has any GUP (or other external) pins.
617 * The page table that maps the page has been already unlinked
618 * from the page table tree and this process cannot get
619 * an additional pin on the page.
621 * New pins can come later if the page is shared across fork,
622 * but not from this process. The other process cannot write to
623 * the page, only trigger CoW.
625 if (!is_refcount_suitable(page)) {
627 result = SCAN_PAGE_COUNT;
632 * Isolate the page to avoid collapsing an hugepage
633 * currently in use by the VM.
635 if (isolate_lru_page(page)) {
637 result = SCAN_DEL_PAGE_LRU;
640 mod_node_page_state(page_pgdat(page),
641 NR_ISOLATED_ANON + page_is_file_lru(page),
643 VM_BUG_ON_PAGE(!PageLocked(page), page);
644 VM_BUG_ON_PAGE(PageLRU(page), page);
646 if (PageCompound(page))
647 list_add_tail(&page->lru, compound_pagelist);
649 /* There should be enough young pte to collapse the page */
650 if (pte_young(pteval) ||
651 page_is_young(page) || PageReferenced(page) ||
652 mmu_notifier_test_young(vma->vm_mm, address))
655 if (pte_write(pteval))
659 if (unlikely(!writable)) {
660 result = SCAN_PAGE_RO;
661 } else if (unlikely(!referenced)) {
662 result = SCAN_LACK_REFERENCED_PAGE;
664 result = SCAN_SUCCEED;
665 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
666 referenced, writable, result);
670 release_pte_pages(pte, _pte, compound_pagelist);
671 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
672 referenced, writable, result);
676 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
677 struct vm_area_struct *vma,
678 unsigned long address,
680 struct list_head *compound_pagelist)
682 struct page *src_page, *tmp;
684 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
685 _pte++, page++, address += PAGE_SIZE) {
686 pte_t pteval = *_pte;
688 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
689 clear_user_highpage(page, address);
690 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
691 if (is_zero_pfn(pte_pfn(pteval))) {
693 * ptl mostly unnecessary.
696 ptep_clear(vma->vm_mm, address, _pte);
700 src_page = pte_page(pteval);
701 copy_user_highpage(page, src_page, address, vma);
702 if (!PageCompound(src_page))
703 release_pte_page(src_page);
705 * ptl mostly unnecessary, but preempt has to
706 * be disabled to update the per-cpu stats
707 * inside page_remove_rmap().
710 ptep_clear(vma->vm_mm, address, _pte);
711 page_remove_rmap(src_page, vma, false);
713 free_page_and_swap_cache(src_page);
717 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
718 list_del(&src_page->lru);
719 mod_node_page_state(page_pgdat(src_page),
720 NR_ISOLATED_ANON + page_is_file_lru(src_page),
721 -compound_nr(src_page));
722 unlock_page(src_page);
723 free_swap_cache(src_page);
724 putback_lru_page(src_page);
728 static void khugepaged_alloc_sleep(void)
732 add_wait_queue(&khugepaged_wait, &wait);
733 freezable_schedule_timeout_interruptible(
734 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
735 remove_wait_queue(&khugepaged_wait, &wait);
738 static int khugepaged_node_load[MAX_NUMNODES];
740 static bool khugepaged_scan_abort(int nid)
745 * If node_reclaim_mode is disabled, then no extra effort is made to
746 * allocate memory locally.
748 if (!node_reclaim_enabled())
751 /* If there is a count for this node already, it must be acceptable */
752 if (khugepaged_node_load[nid])
755 for (i = 0; i < MAX_NUMNODES; i++) {
756 if (!khugepaged_node_load[i])
758 if (node_distance(nid, i) > node_reclaim_distance)
764 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
765 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
767 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
771 static int khugepaged_find_target_node(void)
773 static int last_khugepaged_target_node = NUMA_NO_NODE;
774 int nid, target_node = 0, max_value = 0;
776 /* find first node with max normal pages hit */
777 for (nid = 0; nid < MAX_NUMNODES; nid++)
778 if (khugepaged_node_load[nid] > max_value) {
779 max_value = khugepaged_node_load[nid];
783 /* do some balance if several nodes have the same hit record */
784 if (target_node <= last_khugepaged_target_node)
785 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
787 if (max_value == khugepaged_node_load[nid]) {
792 last_khugepaged_target_node = target_node;
796 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
798 if (IS_ERR(*hpage)) {
804 khugepaged_alloc_sleep();
814 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
816 VM_BUG_ON_PAGE(*hpage, *hpage);
818 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
819 if (unlikely(!*hpage)) {
820 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
821 *hpage = ERR_PTR(-ENOMEM);
825 prep_transhuge_page(*hpage);
826 count_vm_event(THP_COLLAPSE_ALLOC);
830 static int khugepaged_find_target_node(void)
835 static inline struct page *alloc_khugepaged_hugepage(void)
839 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
842 prep_transhuge_page(page);
846 static struct page *khugepaged_alloc_hugepage(bool *wait)
851 hpage = alloc_khugepaged_hugepage();
853 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
858 khugepaged_alloc_sleep();
860 count_vm_event(THP_COLLAPSE_ALLOC);
861 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
866 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
869 * If the hpage allocated earlier was briefly exposed in page cache
870 * before collapse_file() failed, it is possible that racing lookups
871 * have not yet completed, and would then be unpleasantly surprised by
872 * finding the hpage reused for the same mapping at a different offset.
873 * Just release the previous allocation if there is any danger of that.
875 if (*hpage && page_count(*hpage) > 1) {
881 *hpage = khugepaged_alloc_hugepage(wait);
883 if (unlikely(!*hpage))
890 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
899 * If mmap_lock temporarily dropped, revalidate vma
900 * before taking mmap_lock.
901 * Return 0 if succeeds, otherwise return none-zero
905 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
906 struct vm_area_struct **vmap)
908 struct vm_area_struct *vma;
910 if (unlikely(khugepaged_test_exit(mm)))
911 return SCAN_ANY_PROCESS;
913 *vmap = vma = find_vma(mm, address);
915 return SCAN_VMA_NULL;
917 if (!transhuge_vma_suitable(vma, address))
918 return SCAN_ADDRESS_RANGE;
919 if (!hugepage_vma_check(vma, vma->vm_flags, false))
920 return SCAN_VMA_CHECK;
922 * Anon VMA expected, the address may be unmapped then
923 * remapped to file after khugepaged reaquired the mmap_lock.
925 * hugepage_vma_check may return true for qualified file
928 if (!vma->anon_vma || !vma_is_anonymous(vma))
929 return SCAN_VMA_CHECK;
934 * Bring missing pages in from swap, to complete THP collapse.
935 * Only done if khugepaged_scan_pmd believes it is worthwhile.
937 * Called and returns without pte mapped or spinlocks held.
938 * Note that if false is returned, mmap_lock will be released.
941 static bool __collapse_huge_page_swapin(struct mm_struct *mm,
942 struct vm_area_struct *vma,
943 unsigned long haddr, pmd_t *pmd,
948 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
950 for (address = haddr; address < end; address += PAGE_SIZE) {
951 struct vm_fault vmf = {
954 .pgoff = linear_page_index(vma, haddr),
955 .flags = FAULT_FLAG_ALLOW_RETRY,
959 vmf.pte = pte_offset_map(pmd, address);
960 vmf.orig_pte = *vmf.pte;
961 if (!is_swap_pte(vmf.orig_pte)) {
965 ret = do_swap_page(&vmf);
968 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
969 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
970 * we do not retry here and swap entry will remain in pagetable
971 * resulting in later failure.
973 if (ret & VM_FAULT_RETRY) {
974 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
977 if (ret & VM_FAULT_ERROR) {
978 mmap_read_unlock(mm);
979 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
985 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
989 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
993 static void collapse_huge_page(struct mm_struct *mm,
994 unsigned long address,
996 int node, int referenced, int unmapped)
998 LIST_HEAD(compound_pagelist);
1002 struct page *new_page;
1003 spinlock_t *pmd_ptl, *pte_ptl;
1004 int isolated = 0, result = 0;
1005 struct vm_area_struct *vma;
1006 struct mmu_notifier_range range;
1009 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1011 /* Only allocate from the target node */
1012 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1015 * Before allocating the hugepage, release the mmap_lock read lock.
1016 * The allocation can take potentially a long time if it involves
1017 * sync compaction, and we do not need to hold the mmap_lock during
1018 * that. We will recheck the vma after taking it again in write mode.
1020 mmap_read_unlock(mm);
1021 new_page = khugepaged_alloc_page(hpage, gfp, node);
1023 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1027 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) {
1028 result = SCAN_CGROUP_CHARGE_FAIL;
1031 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
1034 result = hugepage_vma_revalidate(mm, address, &vma);
1036 mmap_read_unlock(mm);
1040 pmd = mm_find_pmd(mm, address);
1042 result = SCAN_PMD_NULL;
1043 mmap_read_unlock(mm);
1048 * __collapse_huge_page_swapin will return with mmap_lock released
1049 * when it fails. So we jump out_nolock directly in that case.
1050 * Continuing to collapse causes inconsistency.
1052 if (unmapped && !__collapse_huge_page_swapin(mm, vma, address,
1057 mmap_read_unlock(mm);
1059 * Prevent all access to pagetables with the exception of
1060 * gup_fast later handled by the ptep_clear_flush and the VM
1061 * handled by the anon_vma lock + PG_lock.
1063 mmap_write_lock(mm);
1064 result = hugepage_vma_revalidate(mm, address, &vma);
1067 /* check if the pmd is still valid */
1068 if (mm_find_pmd(mm, address) != pmd)
1071 anon_vma_lock_write(vma->anon_vma);
1073 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1074 address, address + HPAGE_PMD_SIZE);
1075 mmu_notifier_invalidate_range_start(&range);
1077 pte = pte_offset_map(pmd, address);
1078 pte_ptl = pte_lockptr(mm, pmd);
1080 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1082 * After this gup_fast can't run anymore. This also removes
1083 * any huge TLB entry from the CPU so we won't allow
1084 * huge and small TLB entries for the same virtual address
1085 * to avoid the risk of CPU bugs in that area.
1087 _pmd = pmdp_collapse_flush(vma, address, pmd);
1088 spin_unlock(pmd_ptl);
1089 mmu_notifier_invalidate_range_end(&range);
1092 isolated = __collapse_huge_page_isolate(vma, address, pte,
1093 &compound_pagelist);
1094 spin_unlock(pte_ptl);
1096 if (unlikely(!isolated)) {
1099 BUG_ON(!pmd_none(*pmd));
1101 * We can only use set_pmd_at when establishing
1102 * hugepmds and never for establishing regular pmds that
1103 * points to regular pagetables. Use pmd_populate for that
1105 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1106 spin_unlock(pmd_ptl);
1107 anon_vma_unlock_write(vma->anon_vma);
1113 * All pages are isolated and locked so anon_vma rmap
1114 * can't run anymore.
1116 anon_vma_unlock_write(vma->anon_vma);
1118 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl,
1119 &compound_pagelist);
1122 * spin_lock() below is not the equivalent of smp_wmb(), but
1123 * the smp_wmb() inside __SetPageUptodate() can be reused to
1124 * avoid the copy_huge_page writes to become visible after
1125 * the set_pmd_at() write.
1127 __SetPageUptodate(new_page);
1128 pgtable = pmd_pgtable(_pmd);
1130 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1131 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1134 BUG_ON(!pmd_none(*pmd));
1135 page_add_new_anon_rmap(new_page, vma, address);
1136 lru_cache_add_inactive_or_unevictable(new_page, vma);
1137 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1138 set_pmd_at(mm, address, pmd, _pmd);
1139 update_mmu_cache_pmd(vma, address, pmd);
1140 spin_unlock(pmd_ptl);
1144 khugepaged_pages_collapsed++;
1145 result = SCAN_SUCCEED;
1147 mmap_write_unlock(mm);
1149 if (!IS_ERR_OR_NULL(*hpage))
1150 mem_cgroup_uncharge(page_folio(*hpage));
1151 trace_mm_collapse_huge_page(mm, isolated, result);
1155 static int khugepaged_scan_pmd(struct mm_struct *mm,
1156 struct vm_area_struct *vma,
1157 unsigned long address,
1158 struct page **hpage)
1162 int ret = 0, result = 0, referenced = 0;
1163 int none_or_zero = 0, shared = 0;
1164 struct page *page = NULL;
1165 unsigned long _address;
1167 int node = NUMA_NO_NODE, unmapped = 0;
1168 bool writable = false;
1170 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1172 pmd = mm_find_pmd(mm, address);
1174 result = SCAN_PMD_NULL;
1178 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1179 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1180 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1181 _pte++, _address += PAGE_SIZE) {
1182 pte_t pteval = *_pte;
1183 if (is_swap_pte(pteval)) {
1184 if (++unmapped <= khugepaged_max_ptes_swap) {
1186 * Always be strict with uffd-wp
1187 * enabled swap entries. Please see
1188 * comment below for pte_uffd_wp().
1190 if (pte_swp_uffd_wp(pteval)) {
1191 result = SCAN_PTE_UFFD_WP;
1196 result = SCAN_EXCEED_SWAP_PTE;
1197 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1201 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1202 if (!userfaultfd_armed(vma) &&
1203 ++none_or_zero <= khugepaged_max_ptes_none) {
1206 result = SCAN_EXCEED_NONE_PTE;
1207 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1211 if (pte_uffd_wp(pteval)) {
1213 * Don't collapse the page if any of the small
1214 * PTEs are armed with uffd write protection.
1215 * Here we can also mark the new huge pmd as
1216 * write protected if any of the small ones is
1217 * marked but that could bring unknown
1218 * userfault messages that falls outside of
1219 * the registered range. So, just be simple.
1221 result = SCAN_PTE_UFFD_WP;
1224 if (pte_write(pteval))
1227 page = vm_normal_page(vma, _address, pteval);
1228 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1229 result = SCAN_PAGE_NULL;
1233 if (page_mapcount(page) > 1 &&
1234 ++shared > khugepaged_max_ptes_shared) {
1235 result = SCAN_EXCEED_SHARED_PTE;
1236 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1240 page = compound_head(page);
1243 * Record which node the original page is from and save this
1244 * information to khugepaged_node_load[].
1245 * Khugepaged will allocate hugepage from the node has the max
1248 node = page_to_nid(page);
1249 if (khugepaged_scan_abort(node)) {
1250 result = SCAN_SCAN_ABORT;
1253 khugepaged_node_load[node]++;
1254 if (!PageLRU(page)) {
1255 result = SCAN_PAGE_LRU;
1258 if (PageLocked(page)) {
1259 result = SCAN_PAGE_LOCK;
1262 if (!PageAnon(page)) {
1263 result = SCAN_PAGE_ANON;
1268 * Check if the page has any GUP (or other external) pins.
1270 * Here the check is racy it may see total_mapcount > refcount
1272 * For example, one process with one forked child process.
1273 * The parent has the PMD split due to MADV_DONTNEED, then
1274 * the child is trying unmap the whole PMD, but khugepaged
1275 * may be scanning the parent between the child has
1276 * PageDoubleMap flag cleared and dec the mapcount. So
1277 * khugepaged may see total_mapcount > refcount.
1279 * But such case is ephemeral we could always retry collapse
1280 * later. However it may report false positive if the page
1281 * has excessive GUP pins (i.e. 512). Anyway the same check
1282 * will be done again later the risk seems low.
1284 if (!is_refcount_suitable(page)) {
1285 result = SCAN_PAGE_COUNT;
1288 if (pte_young(pteval) ||
1289 page_is_young(page) || PageReferenced(page) ||
1290 mmu_notifier_test_young(vma->vm_mm, address))
1294 result = SCAN_PAGE_RO;
1295 } else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
1296 result = SCAN_LACK_REFERENCED_PAGE;
1298 result = SCAN_SUCCEED;
1302 pte_unmap_unlock(pte, ptl);
1304 node = khugepaged_find_target_node();
1305 /* collapse_huge_page will return with the mmap_lock released */
1306 collapse_huge_page(mm, address, hpage, node,
1307 referenced, unmapped);
1310 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1311 none_or_zero, result, unmapped);
1315 static void collect_mm_slot(struct mm_slot *mm_slot)
1317 struct mm_struct *mm = mm_slot->mm;
1319 lockdep_assert_held(&khugepaged_mm_lock);
1321 if (khugepaged_test_exit(mm)) {
1323 hash_del(&mm_slot->hash);
1324 list_del(&mm_slot->mm_node);
1327 * Not strictly needed because the mm exited already.
1329 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1332 /* khugepaged_mm_lock actually not necessary for the below */
1333 free_mm_slot(mm_slot);
1340 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1341 * khugepaged should try to collapse the page table.
1343 static void khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1346 struct mm_slot *mm_slot;
1348 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1350 spin_lock(&khugepaged_mm_lock);
1351 mm_slot = get_mm_slot(mm);
1352 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
1353 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1354 spin_unlock(&khugepaged_mm_lock);
1357 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1358 unsigned long addr, pmd_t *pmdp)
1363 mmap_assert_write_locked(mm);
1364 ptl = pmd_lock(vma->vm_mm, pmdp);
1365 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1368 page_table_check_pte_clear_range(mm, addr, pmd);
1369 pte_free(mm, pmd_pgtable(pmd));
1373 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1376 * @mm: process address space where collapse happens
1377 * @addr: THP collapse address
1379 * This function checks whether all the PTEs in the PMD are pointing to the
1380 * right THP. If so, retract the page table so the THP can refault in with
1383 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
1385 unsigned long haddr = addr & HPAGE_PMD_MASK;
1386 struct vm_area_struct *vma = find_vma(mm, haddr);
1388 pte_t *start_pte, *pte;
1394 if (!vma || !vma->vm_file ||
1395 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1399 * This vm_flags may not have VM_HUGEPAGE if the page was not
1400 * collapsed by this mm. But we can still collapse if the page is
1401 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
1402 * will not fail the vma for missing VM_HUGEPAGE
1404 if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE, false))
1407 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1408 if (userfaultfd_wp(vma))
1411 hpage = find_lock_page(vma->vm_file->f_mapping,
1412 linear_page_index(vma, haddr));
1416 if (!PageHead(hpage))
1419 pmd = mm_find_pmd(mm, haddr);
1423 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1425 /* step 1: check all mapped PTEs are to the right huge page */
1426 for (i = 0, addr = haddr, pte = start_pte;
1427 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1430 /* empty pte, skip */
1434 /* page swapped out, abort */
1435 if (!pte_present(*pte))
1438 page = vm_normal_page(vma, addr, *pte);
1439 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1442 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1443 * page table, but the new page will not be a subpage of hpage.
1445 if (hpage + i != page)
1450 /* step 2: adjust rmap */
1451 for (i = 0, addr = haddr, pte = start_pte;
1452 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1457 page = vm_normal_page(vma, addr, *pte);
1458 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1460 page_remove_rmap(page, vma, false);
1463 pte_unmap_unlock(start_pte, ptl);
1465 /* step 3: set proper refcount and mm_counters. */
1467 page_ref_sub(hpage, count);
1468 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1471 /* step 4: collapse pmd */
1472 collapse_and_free_pmd(mm, vma, haddr, pmd);
1479 pte_unmap_unlock(start_pte, ptl);
1483 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1485 struct mm_struct *mm = mm_slot->mm;
1488 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1491 if (!mmap_write_trylock(mm))
1494 if (unlikely(khugepaged_test_exit(mm)))
1497 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1498 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
1501 mm_slot->nr_pte_mapped_thp = 0;
1502 mmap_write_unlock(mm);
1505 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1507 struct vm_area_struct *vma;
1508 struct mm_struct *mm;
1512 i_mmap_lock_write(mapping);
1513 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1515 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1516 * got written to. These VMAs are likely not worth investing
1517 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1520 * Note that vma->anon_vma check is racy: it can be set up after
1521 * the check but before we took mmap_lock by the fault path.
1522 * But page lock would prevent establishing any new ptes of the
1523 * page, so we are safe.
1525 * An alternative would be drop the check, but check that page
1526 * table is clear before calling pmdp_collapse_flush() under
1527 * ptl. It has higher chance to recover THP for the VMA, but
1528 * has higher cost too.
1532 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1533 if (addr & ~HPAGE_PMD_MASK)
1535 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1538 pmd = mm_find_pmd(mm, addr);
1542 * We need exclusive mmap_lock to retract page table.
1544 * We use trylock due to lock inversion: we need to acquire
1545 * mmap_lock while holding page lock. Fault path does it in
1546 * reverse order. Trylock is a way to avoid deadlock.
1548 if (mmap_write_trylock(mm)) {
1550 * When a vma is registered with uffd-wp, we can't
1551 * recycle the pmd pgtable because there can be pte
1552 * markers installed. Skip it only, so the rest mm/vma
1553 * can still have the same file mapped hugely, however
1554 * it'll always mapped in small page size for uffd-wp
1555 * registered ranges.
1557 if (!khugepaged_test_exit(mm) && !userfaultfd_wp(vma))
1558 collapse_and_free_pmd(mm, vma, addr, pmd);
1559 mmap_write_unlock(mm);
1561 /* Try again later */
1562 khugepaged_add_pte_mapped_thp(mm, addr);
1565 i_mmap_unlock_write(mapping);
1569 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1571 * @mm: process address space where collapse happens
1572 * @file: file that collapse on
1573 * @start: collapse start address
1574 * @hpage: new allocated huge page for collapse
1575 * @node: appointed node the new huge page allocate from
1577 * Basic scheme is simple, details are more complex:
1578 * - allocate and lock a new huge page;
1579 * - scan page cache replacing old pages with the new one
1580 * + swap/gup in pages if necessary;
1582 * + keep old pages around in case rollback is required;
1583 * - if replacing succeeds:
1586 * + unlock huge page;
1587 * - if replacing failed;
1588 * + put all pages back and unfreeze them;
1589 * + restore gaps in the page cache;
1590 * + unlock and free huge page;
1592 static void collapse_file(struct mm_struct *mm,
1593 struct file *file, pgoff_t start,
1594 struct page **hpage, int node)
1596 struct address_space *mapping = file->f_mapping;
1598 struct page *new_page;
1599 pgoff_t index, end = start + HPAGE_PMD_NR;
1600 LIST_HEAD(pagelist);
1601 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1602 int nr_none = 0, result = SCAN_SUCCEED;
1603 bool is_shmem = shmem_file(file);
1606 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1607 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1609 /* Only allocate from the target node */
1610 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1612 new_page = khugepaged_alloc_page(hpage, gfp, node);
1614 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1618 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) {
1619 result = SCAN_CGROUP_CHARGE_FAIL;
1622 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
1625 * Ensure we have slots for all the pages in the range. This is
1626 * almost certainly a no-op because most of the pages must be present
1630 xas_create_range(&xas);
1631 if (!xas_error(&xas))
1633 xas_unlock_irq(&xas);
1634 if (!xas_nomem(&xas, GFP_KERNEL)) {
1640 __SetPageLocked(new_page);
1642 __SetPageSwapBacked(new_page);
1643 new_page->index = start;
1644 new_page->mapping = mapping;
1647 * At this point the new_page is locked and not up-to-date.
1648 * It's safe to insert it into the page cache, because nobody would
1649 * be able to map it or use it in another way until we unlock it.
1652 xas_set(&xas, start);
1653 for (index = start; index < end; index++) {
1654 struct page *page = xas_next(&xas);
1656 VM_BUG_ON(index != xas.xa_index);
1660 * Stop if extent has been truncated or
1661 * hole-punched, and is now completely
1664 if (index == start) {
1665 if (!xas_next_entry(&xas, end - 1)) {
1666 result = SCAN_TRUNCATED;
1669 xas_set(&xas, index);
1671 if (!shmem_charge(mapping->host, 1)) {
1675 xas_store(&xas, new_page);
1680 if (xa_is_value(page) || !PageUptodate(page)) {
1681 xas_unlock_irq(&xas);
1682 /* swap in or instantiate fallocated page */
1683 if (shmem_getpage(mapping->host, index, &page,
1688 } else if (trylock_page(page)) {
1690 xas_unlock_irq(&xas);
1692 result = SCAN_PAGE_LOCK;
1695 } else { /* !is_shmem */
1696 if (!page || xa_is_value(page)) {
1697 xas_unlock_irq(&xas);
1698 page_cache_sync_readahead(mapping, &file->f_ra,
1701 /* drain pagevecs to help isolate_lru_page() */
1703 page = find_lock_page(mapping, index);
1704 if (unlikely(page == NULL)) {
1708 } else if (PageDirty(page)) {
1710 * khugepaged only works on read-only fd,
1711 * so this page is dirty because it hasn't
1712 * been flushed since first write. There
1713 * won't be new dirty pages.
1715 * Trigger async flush here and hope the
1716 * writeback is done when khugepaged
1717 * revisits this page.
1719 * This is a one-off situation. We are not
1720 * forcing writeback in loop.
1722 xas_unlock_irq(&xas);
1723 filemap_flush(mapping);
1726 } else if (PageWriteback(page)) {
1727 xas_unlock_irq(&xas);
1730 } else if (trylock_page(page)) {
1732 xas_unlock_irq(&xas);
1734 result = SCAN_PAGE_LOCK;
1740 * The page must be locked, so we can drop the i_pages lock
1741 * without racing with truncate.
1743 VM_BUG_ON_PAGE(!PageLocked(page), page);
1745 /* make sure the page is up to date */
1746 if (unlikely(!PageUptodate(page))) {
1752 * If file was truncated then extended, or hole-punched, before
1753 * we locked the first page, then a THP might be there already.
1755 if (PageTransCompound(page)) {
1756 result = SCAN_PAGE_COMPOUND;
1760 if (page_mapping(page) != mapping) {
1761 result = SCAN_TRUNCATED;
1765 if (!is_shmem && (PageDirty(page) ||
1766 PageWriteback(page))) {
1768 * khugepaged only works on read-only fd, so this
1769 * page is dirty because it hasn't been flushed
1770 * since first write.
1776 if (isolate_lru_page(page)) {
1777 result = SCAN_DEL_PAGE_LRU;
1781 if (page_has_private(page) &&
1782 !try_to_release_page(page, GFP_KERNEL)) {
1783 result = SCAN_PAGE_HAS_PRIVATE;
1784 putback_lru_page(page);
1788 if (page_mapped(page))
1789 try_to_unmap(page_folio(page),
1790 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1793 xas_set(&xas, index);
1795 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1798 * The page is expected to have page_count() == 3:
1799 * - we hold a pin on it;
1800 * - one reference from page cache;
1801 * - one from isolate_lru_page;
1803 if (!page_ref_freeze(page, 3)) {
1804 result = SCAN_PAGE_COUNT;
1805 xas_unlock_irq(&xas);
1806 putback_lru_page(page);
1811 * Add the page to the list to be able to undo the collapse if
1812 * something go wrong.
1814 list_add_tail(&page->lru, &pagelist);
1816 /* Finally, replace with the new page. */
1817 xas_store(&xas, new_page);
1824 nr = thp_nr_pages(new_page);
1827 __mod_lruvec_page_state(new_page, NR_SHMEM_THPS, nr);
1829 __mod_lruvec_page_state(new_page, NR_FILE_THPS, nr);
1830 filemap_nr_thps_inc(mapping);
1832 * Paired with smp_mb() in do_dentry_open() to ensure
1833 * i_writecount is up to date and the update to nr_thps is
1834 * visible. Ensures the page cache will be truncated if the
1835 * file is opened writable.
1838 if (inode_is_open_for_write(mapping->host)) {
1840 __mod_lruvec_page_state(new_page, NR_FILE_THPS, -nr);
1841 filemap_nr_thps_dec(mapping);
1847 __mod_lruvec_page_state(new_page, NR_FILE_PAGES, nr_none);
1848 /* nr_none is always 0 for non-shmem. */
1849 __mod_lruvec_page_state(new_page, NR_SHMEM, nr_none);
1852 /* Join all the small entries into a single multi-index entry */
1853 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
1854 xas_store(&xas, new_page);
1856 xas_unlock_irq(&xas);
1860 * If collapse is successful, flush must be done now before copying.
1861 * If collapse is unsuccessful, does flush actually need to be done?
1862 * Do it anyway, to clear the state.
1864 try_to_unmap_flush();
1866 if (result == SCAN_SUCCEED) {
1867 struct page *page, *tmp;
1870 * Replacing old pages with new one has succeeded, now we
1871 * need to copy the content and free the old pages.
1874 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1875 while (index < page->index) {
1876 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1879 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1881 list_del(&page->lru);
1882 page->mapping = NULL;
1883 page_ref_unfreeze(page, 1);
1884 ClearPageActive(page);
1885 ClearPageUnevictable(page);
1890 while (index < end) {
1891 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1895 SetPageUptodate(new_page);
1896 page_ref_add(new_page, HPAGE_PMD_NR - 1);
1898 set_page_dirty(new_page);
1899 lru_cache_add(new_page);
1902 * Remove pte page tables, so we can re-fault the page as huge.
1904 retract_page_tables(mapping, start);
1907 khugepaged_pages_collapsed++;
1911 /* Something went wrong: roll back page cache changes */
1914 mapping->nrpages -= nr_none;
1915 shmem_uncharge(mapping->host, nr_none);
1918 xas_set(&xas, start);
1919 xas_for_each(&xas, page, end - 1) {
1920 page = list_first_entry_or_null(&pagelist,
1922 if (!page || xas.xa_index < page->index) {
1926 /* Put holes back where they were */
1927 xas_store(&xas, NULL);
1931 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1933 /* Unfreeze the page. */
1934 list_del(&page->lru);
1935 page_ref_unfreeze(page, 2);
1936 xas_store(&xas, page);
1938 xas_unlock_irq(&xas);
1940 putback_lru_page(page);
1944 xas_unlock_irq(&xas);
1946 new_page->mapping = NULL;
1949 unlock_page(new_page);
1951 VM_BUG_ON(!list_empty(&pagelist));
1952 if (!IS_ERR_OR_NULL(*hpage))
1953 mem_cgroup_uncharge(page_folio(*hpage));
1954 /* TODO: tracepoints */
1957 static void khugepaged_scan_file(struct mm_struct *mm,
1958 struct file *file, pgoff_t start, struct page **hpage)
1960 struct page *page = NULL;
1961 struct address_space *mapping = file->f_mapping;
1962 XA_STATE(xas, &mapping->i_pages, start);
1964 int node = NUMA_NO_NODE;
1965 int result = SCAN_SUCCEED;
1969 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1971 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
1972 if (xas_retry(&xas, page))
1975 if (xa_is_value(page)) {
1976 if (++swap > khugepaged_max_ptes_swap) {
1977 result = SCAN_EXCEED_SWAP_PTE;
1978 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1985 * XXX: khugepaged should compact smaller compound pages
1986 * into a PMD sized page
1988 if (PageTransCompound(page)) {
1989 result = SCAN_PAGE_COMPOUND;
1993 node = page_to_nid(page);
1994 if (khugepaged_scan_abort(node)) {
1995 result = SCAN_SCAN_ABORT;
1998 khugepaged_node_load[node]++;
2000 if (!PageLRU(page)) {
2001 result = SCAN_PAGE_LRU;
2005 if (page_count(page) !=
2006 1 + page_mapcount(page) + page_has_private(page)) {
2007 result = SCAN_PAGE_COUNT;
2012 * We probably should check if the page is referenced here, but
2013 * nobody would transfer pte_young() to PageReferenced() for us.
2014 * And rmap walk here is just too costly...
2019 if (need_resched()) {
2026 if (result == SCAN_SUCCEED) {
2027 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2028 result = SCAN_EXCEED_NONE_PTE;
2029 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2031 node = khugepaged_find_target_node();
2032 collapse_file(mm, file, start, hpage, node);
2036 /* TODO: tracepoints */
2039 static void khugepaged_scan_file(struct mm_struct *mm,
2040 struct file *file, pgoff_t start, struct page **hpage)
2045 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
2050 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2051 struct page **hpage)
2052 __releases(&khugepaged_mm_lock)
2053 __acquires(&khugepaged_mm_lock)
2055 struct mm_slot *mm_slot;
2056 struct mm_struct *mm;
2057 struct vm_area_struct *vma;
2061 lockdep_assert_held(&khugepaged_mm_lock);
2063 if (khugepaged_scan.mm_slot)
2064 mm_slot = khugepaged_scan.mm_slot;
2066 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2067 struct mm_slot, mm_node);
2068 khugepaged_scan.address = 0;
2069 khugepaged_scan.mm_slot = mm_slot;
2071 spin_unlock(&khugepaged_mm_lock);
2072 khugepaged_collapse_pte_mapped_thps(mm_slot);
2076 * Don't wait for semaphore (to avoid long wait times). Just move to
2077 * the next mm on the list.
2080 if (unlikely(!mmap_read_trylock(mm)))
2081 goto breakouterloop_mmap_lock;
2082 if (likely(!khugepaged_test_exit(mm)))
2083 vma = find_vma(mm, khugepaged_scan.address);
2086 for (; vma; vma = vma->vm_next) {
2087 unsigned long hstart, hend;
2090 if (unlikely(khugepaged_test_exit(mm))) {
2094 if (!hugepage_vma_check(vma, vma->vm_flags, false)) {
2099 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2100 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2101 if (khugepaged_scan.address > hend)
2103 if (khugepaged_scan.address < hstart)
2104 khugepaged_scan.address = hstart;
2105 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2107 while (khugepaged_scan.address < hend) {
2110 if (unlikely(khugepaged_test_exit(mm)))
2111 goto breakouterloop;
2113 VM_BUG_ON(khugepaged_scan.address < hstart ||
2114 khugepaged_scan.address + HPAGE_PMD_SIZE >
2116 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2117 struct file *file = get_file(vma->vm_file);
2118 pgoff_t pgoff = linear_page_index(vma,
2119 khugepaged_scan.address);
2121 mmap_read_unlock(mm);
2123 khugepaged_scan_file(mm, file, pgoff, hpage);
2126 ret = khugepaged_scan_pmd(mm, vma,
2127 khugepaged_scan.address,
2130 /* move to next address */
2131 khugepaged_scan.address += HPAGE_PMD_SIZE;
2132 progress += HPAGE_PMD_NR;
2134 /* we released mmap_lock so break loop */
2135 goto breakouterloop_mmap_lock;
2136 if (progress >= pages)
2137 goto breakouterloop;
2141 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2142 breakouterloop_mmap_lock:
2144 spin_lock(&khugepaged_mm_lock);
2145 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2147 * Release the current mm_slot if this mm is about to die, or
2148 * if we scanned all vmas of this mm.
2150 if (khugepaged_test_exit(mm) || !vma) {
2152 * Make sure that if mm_users is reaching zero while
2153 * khugepaged runs here, khugepaged_exit will find
2154 * mm_slot not pointing to the exiting mm.
2156 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2157 khugepaged_scan.mm_slot = list_entry(
2158 mm_slot->mm_node.next,
2159 struct mm_slot, mm_node);
2160 khugepaged_scan.address = 0;
2162 khugepaged_scan.mm_slot = NULL;
2163 khugepaged_full_scans++;
2166 collect_mm_slot(mm_slot);
2172 static int khugepaged_has_work(void)
2174 return !list_empty(&khugepaged_scan.mm_head) &&
2175 khugepaged_enabled();
2178 static int khugepaged_wait_event(void)
2180 return !list_empty(&khugepaged_scan.mm_head) ||
2181 kthread_should_stop();
2184 static void khugepaged_do_scan(void)
2186 struct page *hpage = NULL;
2187 unsigned int progress = 0, pass_through_head = 0;
2188 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2191 lru_add_drain_all();
2193 while (progress < pages) {
2194 if (!khugepaged_prealloc_page(&hpage, &wait))
2199 if (unlikely(kthread_should_stop() || try_to_freeze()))
2202 spin_lock(&khugepaged_mm_lock);
2203 if (!khugepaged_scan.mm_slot)
2204 pass_through_head++;
2205 if (khugepaged_has_work() &&
2206 pass_through_head < 2)
2207 progress += khugepaged_scan_mm_slot(pages - progress,
2211 spin_unlock(&khugepaged_mm_lock);
2214 if (!IS_ERR_OR_NULL(hpage))
2218 static bool khugepaged_should_wakeup(void)
2220 return kthread_should_stop() ||
2221 time_after_eq(jiffies, khugepaged_sleep_expire);
2224 static void khugepaged_wait_work(void)
2226 if (khugepaged_has_work()) {
2227 const unsigned long scan_sleep_jiffies =
2228 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2230 if (!scan_sleep_jiffies)
2233 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2234 wait_event_freezable_timeout(khugepaged_wait,
2235 khugepaged_should_wakeup(),
2236 scan_sleep_jiffies);
2240 if (khugepaged_enabled())
2241 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2244 static int khugepaged(void *none)
2246 struct mm_slot *mm_slot;
2249 set_user_nice(current, MAX_NICE);
2251 while (!kthread_should_stop()) {
2252 khugepaged_do_scan();
2253 khugepaged_wait_work();
2256 spin_lock(&khugepaged_mm_lock);
2257 mm_slot = khugepaged_scan.mm_slot;
2258 khugepaged_scan.mm_slot = NULL;
2260 collect_mm_slot(mm_slot);
2261 spin_unlock(&khugepaged_mm_lock);
2265 static void set_recommended_min_free_kbytes(void)
2269 unsigned long recommended_min;
2271 if (!khugepaged_enabled()) {
2272 calculate_min_free_kbytes();
2276 for_each_populated_zone(zone) {
2278 * We don't need to worry about fragmentation of
2279 * ZONE_MOVABLE since it only has movable pages.
2281 if (zone_idx(zone) > gfp_zone(GFP_USER))
2287 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2288 recommended_min = pageblock_nr_pages * nr_zones * 2;
2291 * Make sure that on average at least two pageblocks are almost free
2292 * of another type, one for a migratetype to fall back to and a
2293 * second to avoid subsequent fallbacks of other types There are 3
2294 * MIGRATE_TYPES we care about.
2296 recommended_min += pageblock_nr_pages * nr_zones *
2297 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2299 /* don't ever allow to reserve more than 5% of the lowmem */
2300 recommended_min = min(recommended_min,
2301 (unsigned long) nr_free_buffer_pages() / 20);
2302 recommended_min <<= (PAGE_SHIFT-10);
2304 if (recommended_min > min_free_kbytes) {
2305 if (user_min_free_kbytes >= 0)
2306 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2307 min_free_kbytes, recommended_min);
2309 min_free_kbytes = recommended_min;
2313 setup_per_zone_wmarks();
2316 int start_stop_khugepaged(void)
2320 mutex_lock(&khugepaged_mutex);
2321 if (khugepaged_enabled()) {
2322 if (!khugepaged_thread)
2323 khugepaged_thread = kthread_run(khugepaged, NULL,
2325 if (IS_ERR(khugepaged_thread)) {
2326 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2327 err = PTR_ERR(khugepaged_thread);
2328 khugepaged_thread = NULL;
2332 if (!list_empty(&khugepaged_scan.mm_head))
2333 wake_up_interruptible(&khugepaged_wait);
2334 } else if (khugepaged_thread) {
2335 kthread_stop(khugepaged_thread);
2336 khugepaged_thread = NULL;
2338 set_recommended_min_free_kbytes();
2340 mutex_unlock(&khugepaged_mutex);
2344 void khugepaged_min_free_kbytes_update(void)
2346 mutex_lock(&khugepaged_mutex);
2347 if (khugepaged_enabled() && khugepaged_thread)
2348 set_recommended_min_free_kbytes();
2349 mutex_unlock(&khugepaged_mutex);