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>
34 SCAN_EXCEED_SHARED_PTE,
38 SCAN_LACK_REFERENCED_PAGE,
51 SCAN_ALLOC_HUGE_PAGE_FAIL,
52 SCAN_CGROUP_CHARGE_FAIL,
54 SCAN_PAGE_HAS_PRIVATE,
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/huge_memory.h>
60 static struct task_struct *khugepaged_thread __read_mostly;
61 static DEFINE_MUTEX(khugepaged_mutex);
63 /* default scan 8*512 pte (or vmas) every 30 second */
64 static unsigned int khugepaged_pages_to_scan __read_mostly;
65 static unsigned int khugepaged_pages_collapsed;
66 static unsigned int khugepaged_full_scans;
67 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
68 /* during fragmentation poll the hugepage allocator once every minute */
69 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
70 static unsigned long khugepaged_sleep_expire;
71 static DEFINE_SPINLOCK(khugepaged_mm_lock);
72 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
74 * default collapse hugepages if there is at least one pte mapped like
75 * it would have happened if the vma was large enough during page
78 * Note that these are only respected if collapse was initiated by khugepaged.
80 static unsigned int khugepaged_max_ptes_none __read_mostly;
81 static unsigned int khugepaged_max_ptes_swap __read_mostly;
82 static unsigned int khugepaged_max_ptes_shared __read_mostly;
84 #define MM_SLOTS_HASH_BITS 10
85 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
87 static struct kmem_cache *mm_slot_cache __read_mostly;
89 #define MAX_PTE_MAPPED_THP 8
91 struct collapse_control {
94 /* Num pages scanned per node */
95 u32 node_load[MAX_NUMNODES];
97 /* Last target selected in hpage_collapse_find_target_node() */
102 * struct mm_slot - hash lookup from mm to mm_slot
103 * @hash: hash collision list
104 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
105 * @mm: the mm that this information is valid for
106 * @nr_pte_mapped_thp: number of pte mapped THP
107 * @pte_mapped_thp: address array corresponding pte mapped THP
110 struct hlist_node hash;
111 struct list_head mm_node;
112 struct mm_struct *mm;
114 /* pte-mapped THP in this mm */
115 int nr_pte_mapped_thp;
116 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
120 * struct khugepaged_scan - cursor for scanning
121 * @mm_head: the head of the mm list to scan
122 * @mm_slot: the current mm_slot we are scanning
123 * @address: the next address inside that to be scanned
125 * There is only the one khugepaged_scan instance of this cursor structure.
127 struct khugepaged_scan {
128 struct list_head mm_head;
129 struct mm_slot *mm_slot;
130 unsigned long address;
133 static struct khugepaged_scan khugepaged_scan = {
134 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
138 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
139 struct kobj_attribute *attr,
142 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
145 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
146 struct kobj_attribute *attr,
147 const char *buf, size_t count)
152 err = kstrtouint(buf, 10, &msecs);
156 khugepaged_scan_sleep_millisecs = msecs;
157 khugepaged_sleep_expire = 0;
158 wake_up_interruptible(&khugepaged_wait);
162 static struct kobj_attribute scan_sleep_millisecs_attr =
163 __ATTR_RW(scan_sleep_millisecs);
165 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
166 struct kobj_attribute *attr,
169 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
172 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
173 struct kobj_attribute *attr,
174 const char *buf, size_t count)
179 err = kstrtouint(buf, 10, &msecs);
183 khugepaged_alloc_sleep_millisecs = msecs;
184 khugepaged_sleep_expire = 0;
185 wake_up_interruptible(&khugepaged_wait);
189 static struct kobj_attribute alloc_sleep_millisecs_attr =
190 __ATTR_RW(alloc_sleep_millisecs);
192 static ssize_t pages_to_scan_show(struct kobject *kobj,
193 struct kobj_attribute *attr,
196 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
198 static ssize_t pages_to_scan_store(struct kobject *kobj,
199 struct kobj_attribute *attr,
200 const char *buf, size_t count)
205 err = kstrtouint(buf, 10, &pages);
209 khugepaged_pages_to_scan = pages;
213 static struct kobj_attribute pages_to_scan_attr =
214 __ATTR_RW(pages_to_scan);
216 static ssize_t pages_collapsed_show(struct kobject *kobj,
217 struct kobj_attribute *attr,
220 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
222 static struct kobj_attribute pages_collapsed_attr =
223 __ATTR_RO(pages_collapsed);
225 static ssize_t full_scans_show(struct kobject *kobj,
226 struct kobj_attribute *attr,
229 return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
231 static struct kobj_attribute full_scans_attr =
232 __ATTR_RO(full_scans);
234 static ssize_t defrag_show(struct kobject *kobj,
235 struct kobj_attribute *attr, char *buf)
237 return single_hugepage_flag_show(kobj, attr, buf,
238 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
240 static ssize_t defrag_store(struct kobject *kobj,
241 struct kobj_attribute *attr,
242 const char *buf, size_t count)
244 return single_hugepage_flag_store(kobj, attr, buf, count,
245 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
247 static struct kobj_attribute khugepaged_defrag_attr =
251 * max_ptes_none controls if khugepaged should collapse hugepages over
252 * any unmapped ptes in turn potentially increasing the memory
253 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
254 * reduce the available free memory in the system as it
255 * runs. Increasing max_ptes_none will instead potentially reduce the
256 * free memory in the system during the khugepaged scan.
258 static ssize_t max_ptes_none_show(struct kobject *kobj,
259 struct kobj_attribute *attr,
262 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
264 static ssize_t max_ptes_none_store(struct kobject *kobj,
265 struct kobj_attribute *attr,
266 const char *buf, size_t count)
269 unsigned long max_ptes_none;
271 err = kstrtoul(buf, 10, &max_ptes_none);
272 if (err || max_ptes_none > HPAGE_PMD_NR - 1)
275 khugepaged_max_ptes_none = max_ptes_none;
279 static struct kobj_attribute khugepaged_max_ptes_none_attr =
280 __ATTR_RW(max_ptes_none);
282 static ssize_t max_ptes_swap_show(struct kobject *kobj,
283 struct kobj_attribute *attr,
286 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
289 static ssize_t max_ptes_swap_store(struct kobject *kobj,
290 struct kobj_attribute *attr,
291 const char *buf, size_t count)
294 unsigned long max_ptes_swap;
296 err = kstrtoul(buf, 10, &max_ptes_swap);
297 if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
300 khugepaged_max_ptes_swap = max_ptes_swap;
305 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
306 __ATTR_RW(max_ptes_swap);
308 static ssize_t max_ptes_shared_show(struct kobject *kobj,
309 struct kobj_attribute *attr,
312 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
315 static ssize_t max_ptes_shared_store(struct kobject *kobj,
316 struct kobj_attribute *attr,
317 const char *buf, size_t count)
320 unsigned long max_ptes_shared;
322 err = kstrtoul(buf, 10, &max_ptes_shared);
323 if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
326 khugepaged_max_ptes_shared = max_ptes_shared;
331 static struct kobj_attribute khugepaged_max_ptes_shared_attr =
332 __ATTR_RW(max_ptes_shared);
334 static struct attribute *khugepaged_attr[] = {
335 &khugepaged_defrag_attr.attr,
336 &khugepaged_max_ptes_none_attr.attr,
337 &khugepaged_max_ptes_swap_attr.attr,
338 &khugepaged_max_ptes_shared_attr.attr,
339 &pages_to_scan_attr.attr,
340 &pages_collapsed_attr.attr,
341 &full_scans_attr.attr,
342 &scan_sleep_millisecs_attr.attr,
343 &alloc_sleep_millisecs_attr.attr,
347 struct attribute_group khugepaged_attr_group = {
348 .attrs = khugepaged_attr,
349 .name = "khugepaged",
351 #endif /* CONFIG_SYSFS */
353 int hugepage_madvise(struct vm_area_struct *vma,
354 unsigned long *vm_flags, int advice)
360 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
361 * can't handle this properly after s390_enable_sie, so we simply
362 * ignore the madvise to prevent qemu from causing a SIGSEGV.
364 if (mm_has_pgste(vma->vm_mm))
367 *vm_flags &= ~VM_NOHUGEPAGE;
368 *vm_flags |= VM_HUGEPAGE;
370 * If the vma become good for khugepaged to scan,
371 * register it here without waiting a page fault that
372 * may not happen any time soon.
374 khugepaged_enter_vma(vma, *vm_flags);
376 case MADV_NOHUGEPAGE:
377 *vm_flags &= ~VM_HUGEPAGE;
378 *vm_flags |= VM_NOHUGEPAGE;
380 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
381 * this vma even if we leave the mm registered in khugepaged if
382 * it got registered before VM_NOHUGEPAGE was set.
390 int __init khugepaged_init(void)
392 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
393 sizeof(struct mm_slot),
394 __alignof__(struct mm_slot), 0, NULL);
398 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
399 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
400 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
401 khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
406 void __init khugepaged_destroy(void)
408 kmem_cache_destroy(mm_slot_cache);
411 static inline struct mm_slot *alloc_mm_slot(void)
413 if (!mm_slot_cache) /* initialization failed */
415 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
418 static inline void free_mm_slot(struct mm_slot *mm_slot)
420 kmem_cache_free(mm_slot_cache, mm_slot);
423 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
425 struct mm_slot *mm_slot;
427 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
428 if (mm == mm_slot->mm)
434 static void insert_to_mm_slots_hash(struct mm_struct *mm,
435 struct mm_slot *mm_slot)
438 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
441 static inline int hpage_collapse_test_exit(struct mm_struct *mm)
443 return atomic_read(&mm->mm_users) == 0;
446 void __khugepaged_enter(struct mm_struct *mm)
448 struct mm_slot *mm_slot;
451 mm_slot = alloc_mm_slot();
455 /* __khugepaged_exit() must not run from under us */
456 VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
457 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
458 free_mm_slot(mm_slot);
462 spin_lock(&khugepaged_mm_lock);
463 insert_to_mm_slots_hash(mm, mm_slot);
465 * Insert just behind the scanning cursor, to let the area settle
468 wakeup = list_empty(&khugepaged_scan.mm_head);
469 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
470 spin_unlock(&khugepaged_mm_lock);
474 wake_up_interruptible(&khugepaged_wait);
477 void khugepaged_enter_vma(struct vm_area_struct *vma,
478 unsigned long vm_flags)
480 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
481 hugepage_flags_enabled()) {
482 if (hugepage_vma_check(vma, vm_flags, false, false, true))
483 __khugepaged_enter(vma->vm_mm);
487 void __khugepaged_exit(struct mm_struct *mm)
489 struct mm_slot *mm_slot;
492 spin_lock(&khugepaged_mm_lock);
493 mm_slot = get_mm_slot(mm);
494 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
495 hash_del(&mm_slot->hash);
496 list_del(&mm_slot->mm_node);
499 spin_unlock(&khugepaged_mm_lock);
502 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
503 free_mm_slot(mm_slot);
505 } else if (mm_slot) {
507 * This is required to serialize against
508 * hpage_collapse_test_exit() (which is guaranteed to run
509 * under mmap sem read mode). Stop here (after we return all
510 * pagetables will be destroyed) until khugepaged has finished
511 * working on the pagetables under the mmap_lock.
514 mmap_write_unlock(mm);
518 static void release_pte_page(struct page *page)
520 mod_node_page_state(page_pgdat(page),
521 NR_ISOLATED_ANON + page_is_file_lru(page),
524 putback_lru_page(page);
527 static void release_pte_pages(pte_t *pte, pte_t *_pte,
528 struct list_head *compound_pagelist)
530 struct page *page, *tmp;
532 while (--_pte >= pte) {
533 pte_t pteval = *_pte;
535 page = pte_page(pteval);
536 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
538 release_pte_page(page);
541 list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
542 list_del(&page->lru);
543 release_pte_page(page);
547 static bool is_refcount_suitable(struct page *page)
549 int expected_refcount;
551 expected_refcount = total_mapcount(page);
552 if (PageSwapCache(page))
553 expected_refcount += compound_nr(page);
555 return page_count(page) == expected_refcount;
558 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
559 unsigned long address,
561 struct collapse_control *cc,
562 struct list_head *compound_pagelist)
564 struct page *page = NULL;
566 int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
567 bool writable = false;
569 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
570 _pte++, address += PAGE_SIZE) {
571 pte_t pteval = *_pte;
572 if (pte_none(pteval) || (pte_present(pteval) &&
573 is_zero_pfn(pte_pfn(pteval)))) {
575 if (!userfaultfd_armed(vma) &&
576 (!cc->is_khugepaged ||
577 none_or_zero <= khugepaged_max_ptes_none)) {
580 result = SCAN_EXCEED_NONE_PTE;
581 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
585 if (!pte_present(pteval)) {
586 result = SCAN_PTE_NON_PRESENT;
589 page = vm_normal_page(vma, address, pteval);
590 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
591 result = SCAN_PAGE_NULL;
595 VM_BUG_ON_PAGE(!PageAnon(page), page);
597 if (page_mapcount(page) > 1) {
599 if (cc->is_khugepaged &&
600 shared > khugepaged_max_ptes_shared) {
601 result = SCAN_EXCEED_SHARED_PTE;
602 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
607 if (PageCompound(page)) {
609 page = compound_head(page);
612 * Check if we have dealt with the compound page
615 list_for_each_entry(p, compound_pagelist, lru) {
622 * We can do it before isolate_lru_page because the
623 * page can't be freed from under us. NOTE: PG_lock
624 * is needed to serialize against split_huge_page
625 * when invoked from the VM.
627 if (!trylock_page(page)) {
628 result = SCAN_PAGE_LOCK;
633 * Check if the page has any GUP (or other external) pins.
635 * The page table that maps the page has been already unlinked
636 * from the page table tree and this process cannot get
637 * an additional pin on the page.
639 * New pins can come later if the page is shared across fork,
640 * but not from this process. The other process cannot write to
641 * the page, only trigger CoW.
643 if (!is_refcount_suitable(page)) {
645 result = SCAN_PAGE_COUNT;
650 * Isolate the page to avoid collapsing an hugepage
651 * currently in use by the VM.
653 if (isolate_lru_page(page)) {
655 result = SCAN_DEL_PAGE_LRU;
658 mod_node_page_state(page_pgdat(page),
659 NR_ISOLATED_ANON + page_is_file_lru(page),
661 VM_BUG_ON_PAGE(!PageLocked(page), page);
662 VM_BUG_ON_PAGE(PageLRU(page), page);
664 if (PageCompound(page))
665 list_add_tail(&page->lru, compound_pagelist);
668 * If collapse was initiated by khugepaged, check that there is
669 * enough young pte to justify collapsing the page
671 if (cc->is_khugepaged &&
672 (pte_young(pteval) || page_is_young(page) ||
673 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
677 if (pte_write(pteval))
681 if (unlikely(!writable)) {
682 result = SCAN_PAGE_RO;
683 } else if (unlikely(cc->is_khugepaged && !referenced)) {
684 result = SCAN_LACK_REFERENCED_PAGE;
686 result = SCAN_SUCCEED;
687 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
688 referenced, writable, result);
692 release_pte_pages(pte, _pte, compound_pagelist);
693 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
694 referenced, writable, result);
698 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
699 struct vm_area_struct *vma,
700 unsigned long address,
702 struct list_head *compound_pagelist)
704 struct page *src_page, *tmp;
706 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
707 _pte++, page++, address += PAGE_SIZE) {
708 pte_t pteval = *_pte;
710 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
711 clear_user_highpage(page, address);
712 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
713 if (is_zero_pfn(pte_pfn(pteval))) {
715 * ptl mostly unnecessary.
718 ptep_clear(vma->vm_mm, address, _pte);
722 src_page = pte_page(pteval);
723 copy_user_highpage(page, src_page, address, vma);
724 if (!PageCompound(src_page))
725 release_pte_page(src_page);
727 * ptl mostly unnecessary, but preempt has to
728 * be disabled to update the per-cpu stats
729 * inside page_remove_rmap().
732 ptep_clear(vma->vm_mm, address, _pte);
733 page_remove_rmap(src_page, vma, false);
735 free_page_and_swap_cache(src_page);
739 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
740 list_del(&src_page->lru);
741 mod_node_page_state(page_pgdat(src_page),
742 NR_ISOLATED_ANON + page_is_file_lru(src_page),
743 -compound_nr(src_page));
744 unlock_page(src_page);
745 free_swap_cache(src_page);
746 putback_lru_page(src_page);
750 static void khugepaged_alloc_sleep(void)
754 add_wait_queue(&khugepaged_wait, &wait);
755 freezable_schedule_timeout_interruptible(
756 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
757 remove_wait_queue(&khugepaged_wait, &wait);
760 struct collapse_control khugepaged_collapse_control = {
761 .is_khugepaged = true,
762 .last_target_node = NUMA_NO_NODE,
765 static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
770 * If node_reclaim_mode is disabled, then no extra effort is made to
771 * allocate memory locally.
773 if (!node_reclaim_enabled())
776 /* If there is a count for this node already, it must be acceptable */
777 if (cc->node_load[nid])
780 for (i = 0; i < MAX_NUMNODES; i++) {
781 if (!cc->node_load[i])
783 if (node_distance(nid, i) > node_reclaim_distance)
789 #define khugepaged_defrag() \
790 (transparent_hugepage_flags & \
791 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
793 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
794 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
796 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
800 static int hpage_collapse_find_target_node(struct collapse_control *cc)
802 int nid, target_node = 0, max_value = 0;
804 /* find first node with max normal pages hit */
805 for (nid = 0; nid < MAX_NUMNODES; nid++)
806 if (cc->node_load[nid] > max_value) {
807 max_value = cc->node_load[nid];
811 /* do some balance if several nodes have the same hit record */
812 if (target_node <= cc->last_target_node)
813 for (nid = cc->last_target_node + 1; nid < MAX_NUMNODES;
815 if (max_value == cc->node_load[nid]) {
820 cc->last_target_node = target_node;
824 static int hpage_collapse_find_target_node(struct collapse_control *cc)
830 static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node)
832 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
833 if (unlikely(!*hpage)) {
834 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
838 prep_transhuge_page(*hpage);
839 count_vm_event(THP_COLLAPSE_ALLOC);
844 * If mmap_lock temporarily dropped, revalidate vma
845 * before taking mmap_lock.
846 * Returns enum scan_result value.
849 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
850 struct vm_area_struct **vmap,
851 struct collapse_control *cc)
853 struct vm_area_struct *vma;
855 if (unlikely(hpage_collapse_test_exit(mm)))
856 return SCAN_ANY_PROCESS;
858 *vmap = vma = find_vma(mm, address);
860 return SCAN_VMA_NULL;
862 if (!transhuge_vma_suitable(vma, address))
863 return SCAN_ADDRESS_RANGE;
864 if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
866 return SCAN_VMA_CHECK;
868 * Anon VMA expected, the address may be unmapped then
869 * remapped to file after khugepaged reaquired the mmap_lock.
871 * hugepage_vma_check may return true for qualified file
874 if (!vma->anon_vma || !vma_is_anonymous(vma))
875 return SCAN_VMA_CHECK;
879 static int find_pmd_or_thp_or_none(struct mm_struct *mm,
880 unsigned long address,
885 *pmd = mm_find_pmd(mm, address);
887 return SCAN_PMD_NULL;
889 pmde = pmd_read_atomic(*pmd);
891 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
892 /* See comments in pmd_none_or_trans_huge_or_clear_bad() */
895 if (!pmd_present(pmde))
896 return SCAN_PMD_NULL;
897 if (pmd_trans_huge(pmde))
898 return SCAN_PMD_MAPPED;
900 return SCAN_PMD_NULL;
904 static int check_pmd_still_valid(struct mm_struct *mm,
905 unsigned long address,
909 int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
911 if (result != SCAN_SUCCEED)
919 * Bring missing pages in from swap, to complete THP collapse.
920 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
922 * Called and returns without pte mapped or spinlocks held.
923 * Note that if false is returned, mmap_lock will be released.
926 static int __collapse_huge_page_swapin(struct mm_struct *mm,
927 struct vm_area_struct *vma,
928 unsigned long haddr, pmd_t *pmd,
933 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
935 for (address = haddr; address < end; address += PAGE_SIZE) {
936 struct vm_fault vmf = {
939 .pgoff = linear_page_index(vma, haddr),
940 .flags = FAULT_FLAG_ALLOW_RETRY,
944 vmf.pte = pte_offset_map(pmd, address);
945 vmf.orig_pte = *vmf.pte;
946 if (!is_swap_pte(vmf.orig_pte)) {
950 ret = do_swap_page(&vmf);
953 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
954 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
955 * we do not retry here and swap entry will remain in pagetable
956 * resulting in later failure.
958 if (ret & VM_FAULT_RETRY) {
959 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
960 /* Likely, but not guaranteed, that page lock failed */
961 return SCAN_PAGE_LOCK;
963 if (ret & VM_FAULT_ERROR) {
964 mmap_read_unlock(mm);
965 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
971 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
975 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
979 static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
980 struct collapse_control *cc)
982 /* Only allocate from the target node */
983 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
984 GFP_TRANSHUGE) | __GFP_THISNODE;
985 int node = hpage_collapse_find_target_node(cc);
987 if (!hpage_collapse_alloc_page(hpage, gfp, node))
988 return SCAN_ALLOC_HUGE_PAGE_FAIL;
989 if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
990 return SCAN_CGROUP_CHARGE_FAIL;
991 count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
995 static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
996 int referenced, int unmapped,
997 struct collapse_control *cc)
999 LIST_HEAD(compound_pagelist);
1004 spinlock_t *pmd_ptl, *pte_ptl;
1005 int result = SCAN_FAIL;
1006 struct vm_area_struct *vma;
1007 struct mmu_notifier_range range;
1009 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1012 * Before allocating the hugepage, release the mmap_lock read lock.
1013 * The allocation can take potentially a long time if it involves
1014 * sync compaction, and we do not need to hold the mmap_lock during
1015 * that. We will recheck the vma after taking it again in write mode.
1017 mmap_read_unlock(mm);
1019 result = alloc_charge_hpage(&hpage, mm, cc);
1020 if (result != SCAN_SUCCEED)
1024 result = hugepage_vma_revalidate(mm, address, &vma, cc);
1025 if (result != SCAN_SUCCEED) {
1026 mmap_read_unlock(mm);
1030 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1031 if (result != SCAN_SUCCEED) {
1032 mmap_read_unlock(mm);
1038 * __collapse_huge_page_swapin will return with mmap_lock
1039 * released when it fails. So we jump out_nolock directly in
1040 * that case. Continuing to collapse causes inconsistency.
1042 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1044 if (result != SCAN_SUCCEED)
1048 mmap_read_unlock(mm);
1050 * Prevent all access to pagetables with the exception of
1051 * gup_fast later handled by the ptep_clear_flush and the VM
1052 * handled by the anon_vma lock + PG_lock.
1054 mmap_write_lock(mm);
1055 result = hugepage_vma_revalidate(mm, address, &vma, cc);
1056 if (result != SCAN_SUCCEED)
1058 /* check if the pmd is still valid */
1059 result = check_pmd_still_valid(mm, address, pmd);
1060 if (result != SCAN_SUCCEED)
1063 anon_vma_lock_write(vma->anon_vma);
1065 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1066 address, address + HPAGE_PMD_SIZE);
1067 mmu_notifier_invalidate_range_start(&range);
1069 pte = pte_offset_map(pmd, address);
1070 pte_ptl = pte_lockptr(mm, pmd);
1072 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1074 * This removes any huge TLB entry from the CPU so we won't allow
1075 * huge and small TLB entries for the same virtual address to
1076 * avoid the risk of CPU bugs in that area.
1078 * Parallel fast GUP is fine since fast GUP will back off when
1079 * it detects PMD is changed.
1081 _pmd = pmdp_collapse_flush(vma, address, pmd);
1082 spin_unlock(pmd_ptl);
1083 mmu_notifier_invalidate_range_end(&range);
1086 result = __collapse_huge_page_isolate(vma, address, pte, cc,
1087 &compound_pagelist);
1088 spin_unlock(pte_ptl);
1090 if (unlikely(result != SCAN_SUCCEED)) {
1093 BUG_ON(!pmd_none(*pmd));
1095 * We can only use set_pmd_at when establishing
1096 * hugepmds and never for establishing regular pmds that
1097 * points to regular pagetables. Use pmd_populate for that
1099 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1100 spin_unlock(pmd_ptl);
1101 anon_vma_unlock_write(vma->anon_vma);
1106 * All pages are isolated and locked so anon_vma rmap
1107 * can't run anymore.
1109 anon_vma_unlock_write(vma->anon_vma);
1111 __collapse_huge_page_copy(pte, hpage, vma, address, pte_ptl,
1112 &compound_pagelist);
1115 * spin_lock() below is not the equivalent of smp_wmb(), but
1116 * the smp_wmb() inside __SetPageUptodate() can be reused to
1117 * avoid the copy_huge_page writes to become visible after
1118 * the set_pmd_at() write.
1120 __SetPageUptodate(hpage);
1121 pgtable = pmd_pgtable(_pmd);
1123 _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1124 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1127 BUG_ON(!pmd_none(*pmd));
1128 page_add_new_anon_rmap(hpage, vma, address);
1129 lru_cache_add_inactive_or_unevictable(hpage, vma);
1130 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1131 set_pmd_at(mm, address, pmd, _pmd);
1132 update_mmu_cache_pmd(vma, address, pmd);
1133 spin_unlock(pmd_ptl);
1137 result = SCAN_SUCCEED;
1139 mmap_write_unlock(mm);
1142 mem_cgroup_uncharge(page_folio(hpage));
1145 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1149 static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1150 struct vm_area_struct *vma,
1151 unsigned long address, bool *mmap_locked,
1152 struct collapse_control *cc)
1156 int result = SCAN_FAIL, referenced = 0;
1157 int none_or_zero = 0, shared = 0;
1158 struct page *page = NULL;
1159 unsigned long _address;
1161 int node = NUMA_NO_NODE, unmapped = 0;
1162 bool writable = false;
1164 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1166 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1167 if (result != SCAN_SUCCEED)
1170 memset(cc->node_load, 0, sizeof(cc->node_load));
1171 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1172 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1173 _pte++, _address += PAGE_SIZE) {
1174 pte_t pteval = *_pte;
1175 if (is_swap_pte(pteval)) {
1177 if (!cc->is_khugepaged ||
1178 unmapped <= khugepaged_max_ptes_swap) {
1180 * Always be strict with uffd-wp
1181 * enabled swap entries. Please see
1182 * comment below for pte_uffd_wp().
1184 if (pte_swp_uffd_wp(pteval)) {
1185 result = SCAN_PTE_UFFD_WP;
1190 result = SCAN_EXCEED_SWAP_PTE;
1191 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1195 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1197 if (!userfaultfd_armed(vma) &&
1198 (!cc->is_khugepaged ||
1199 none_or_zero <= khugepaged_max_ptes_none)) {
1202 result = SCAN_EXCEED_NONE_PTE;
1203 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1207 if (pte_uffd_wp(pteval)) {
1209 * Don't collapse the page if any of the small
1210 * PTEs are armed with uffd write protection.
1211 * Here we can also mark the new huge pmd as
1212 * write protected if any of the small ones is
1213 * marked but that could bring unknown
1214 * userfault messages that falls outside of
1215 * the registered range. So, just be simple.
1217 result = SCAN_PTE_UFFD_WP;
1220 if (pte_write(pteval))
1223 page = vm_normal_page(vma, _address, pteval);
1224 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1225 result = SCAN_PAGE_NULL;
1229 if (page_mapcount(page) > 1) {
1231 if (cc->is_khugepaged &&
1232 shared > khugepaged_max_ptes_shared) {
1233 result = SCAN_EXCEED_SHARED_PTE;
1234 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1239 page = compound_head(page);
1242 * Record which node the original page is from and save this
1243 * information to cc->node_load[].
1244 * Khugepaged will allocate hugepage from the node has the max
1247 node = page_to_nid(page);
1248 if (hpage_collapse_scan_abort(node, cc)) {
1249 result = SCAN_SCAN_ABORT;
1252 cc->node_load[node]++;
1253 if (!PageLRU(page)) {
1254 result = SCAN_PAGE_LRU;
1257 if (PageLocked(page)) {
1258 result = SCAN_PAGE_LOCK;
1261 if (!PageAnon(page)) {
1262 result = SCAN_PAGE_ANON;
1267 * Check if the page has any GUP (or other external) pins.
1269 * Here the check is racy it may see total_mapcount > refcount
1271 * For example, one process with one forked child process.
1272 * The parent has the PMD split due to MADV_DONTNEED, then
1273 * the child is trying unmap the whole PMD, but khugepaged
1274 * may be scanning the parent between the child has
1275 * PageDoubleMap flag cleared and dec the mapcount. So
1276 * khugepaged may see total_mapcount > refcount.
1278 * But such case is ephemeral we could always retry collapse
1279 * later. However it may report false positive if the page
1280 * has excessive GUP pins (i.e. 512). Anyway the same check
1281 * will be done again later the risk seems low.
1283 if (!is_refcount_suitable(page)) {
1284 result = SCAN_PAGE_COUNT;
1289 * If collapse was initiated by khugepaged, check that there is
1290 * enough young pte to justify collapsing the page
1292 if (cc->is_khugepaged &&
1293 (pte_young(pteval) || page_is_young(page) ||
1294 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1299 result = SCAN_PAGE_RO;
1300 } else if (cc->is_khugepaged &&
1302 (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1303 result = SCAN_LACK_REFERENCED_PAGE;
1305 result = SCAN_SUCCEED;
1308 pte_unmap_unlock(pte, ptl);
1309 if (result == SCAN_SUCCEED) {
1310 result = collapse_huge_page(mm, address, referenced,
1312 /* collapse_huge_page will return with the mmap_lock released */
1313 *mmap_locked = false;
1316 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1317 none_or_zero, result, unmapped);
1321 static void collect_mm_slot(struct mm_slot *mm_slot)
1323 struct mm_struct *mm = mm_slot->mm;
1325 lockdep_assert_held(&khugepaged_mm_lock);
1327 if (hpage_collapse_test_exit(mm)) {
1329 hash_del(&mm_slot->hash);
1330 list_del(&mm_slot->mm_node);
1333 * Not strictly needed because the mm exited already.
1335 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1338 /* khugepaged_mm_lock actually not necessary for the below */
1339 free_mm_slot(mm_slot);
1346 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1347 * khugepaged should try to collapse the page table.
1349 static void khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1352 struct mm_slot *mm_slot;
1354 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1356 spin_lock(&khugepaged_mm_lock);
1357 mm_slot = get_mm_slot(mm);
1358 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
1359 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1360 spin_unlock(&khugepaged_mm_lock);
1363 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1364 unsigned long addr, pmd_t *pmdp)
1369 mmap_assert_write_locked(mm);
1370 ptl = pmd_lock(vma->vm_mm, pmdp);
1371 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1374 page_table_check_pte_clear_range(mm, addr, pmd);
1375 pte_free(mm, pmd_pgtable(pmd));
1379 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1382 * @mm: process address space where collapse happens
1383 * @addr: THP collapse address
1385 * This function checks whether all the PTEs in the PMD are pointing to the
1386 * right THP. If so, retract the page table so the THP can refault in with
1389 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
1391 unsigned long haddr = addr & HPAGE_PMD_MASK;
1392 struct vm_area_struct *vma = find_vma(mm, haddr);
1394 pte_t *start_pte, *pte;
1400 if (!vma || !vma->vm_file ||
1401 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1405 * If we are here, we've succeeded in replacing all the native pages
1406 * in the page cache with a single hugepage. If a mm were to fault-in
1407 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1408 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1409 * analogously elide sysfs THP settings here.
1411 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
1414 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1415 if (userfaultfd_wp(vma))
1418 hpage = find_lock_page(vma->vm_file->f_mapping,
1419 linear_page_index(vma, haddr));
1423 if (!PageHead(hpage))
1426 if (find_pmd_or_thp_or_none(mm, haddr, &pmd) != SCAN_SUCCEED)
1429 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1431 /* step 1: check all mapped PTEs are to the right huge page */
1432 for (i = 0, addr = haddr, pte = start_pte;
1433 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1436 /* empty pte, skip */
1440 /* page swapped out, abort */
1441 if (!pte_present(*pte))
1444 page = vm_normal_page(vma, addr, *pte);
1445 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1448 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1449 * page table, but the new page will not be a subpage of hpage.
1451 if (hpage + i != page)
1456 /* step 2: adjust rmap */
1457 for (i = 0, addr = haddr, pte = start_pte;
1458 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1463 page = vm_normal_page(vma, addr, *pte);
1464 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1466 page_remove_rmap(page, vma, false);
1469 pte_unmap_unlock(start_pte, ptl);
1471 /* step 3: set proper refcount and mm_counters. */
1473 page_ref_sub(hpage, count);
1474 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1477 /* step 4: collapse pmd */
1478 collapse_and_free_pmd(mm, vma, haddr, pmd);
1485 pte_unmap_unlock(start_pte, ptl);
1489 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1491 struct mm_struct *mm = mm_slot->mm;
1494 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1497 if (!mmap_write_trylock(mm))
1500 if (unlikely(hpage_collapse_test_exit(mm)))
1503 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1504 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
1507 mm_slot->nr_pte_mapped_thp = 0;
1508 mmap_write_unlock(mm);
1511 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1513 struct vm_area_struct *vma;
1514 struct mm_struct *mm;
1518 i_mmap_lock_write(mapping);
1519 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1521 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1522 * got written to. These VMAs are likely not worth investing
1523 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1526 * Note that vma->anon_vma check is racy: it can be set up after
1527 * the check but before we took mmap_lock by the fault path.
1528 * But page lock would prevent establishing any new ptes of the
1529 * page, so we are safe.
1531 * An alternative would be drop the check, but check that page
1532 * table is clear before calling pmdp_collapse_flush() under
1533 * ptl. It has higher chance to recover THP for the VMA, but
1534 * has higher cost too.
1538 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1539 if (addr & ~HPAGE_PMD_MASK)
1541 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1544 if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED)
1547 * We need exclusive mmap_lock to retract page table.
1549 * We use trylock due to lock inversion: we need to acquire
1550 * mmap_lock while holding page lock. Fault path does it in
1551 * reverse order. Trylock is a way to avoid deadlock.
1553 if (mmap_write_trylock(mm)) {
1555 * When a vma is registered with uffd-wp, we can't
1556 * recycle the pmd pgtable because there can be pte
1557 * markers installed. Skip it only, so the rest mm/vma
1558 * can still have the same file mapped hugely, however
1559 * it'll always mapped in small page size for uffd-wp
1560 * registered ranges.
1562 if (!hpage_collapse_test_exit(mm) &&
1563 !userfaultfd_wp(vma))
1564 collapse_and_free_pmd(mm, vma, addr, pmd);
1565 mmap_write_unlock(mm);
1567 /* Try again later */
1568 khugepaged_add_pte_mapped_thp(mm, addr);
1571 i_mmap_unlock_write(mapping);
1575 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1577 * @mm: process address space where collapse happens
1578 * @file: file that collapse on
1579 * @start: collapse start address
1580 * @cc: collapse context and scratchpad
1582 * Basic scheme is simple, details are more complex:
1583 * - allocate and lock a new huge page;
1584 * - scan page cache replacing old pages with the new one
1585 * + swap/gup in pages if necessary;
1587 * + keep old pages around in case rollback is required;
1588 * - if replacing succeeds:
1591 * + unlock huge page;
1592 * - if replacing failed;
1593 * + put all pages back and unfreeze them;
1594 * + restore gaps in the page cache;
1595 * + unlock and free huge page;
1597 static int collapse_file(struct mm_struct *mm, struct file *file,
1598 pgoff_t start, struct collapse_control *cc)
1600 struct address_space *mapping = file->f_mapping;
1602 pgoff_t index, end = start + HPAGE_PMD_NR;
1603 LIST_HEAD(pagelist);
1604 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1605 int nr_none = 0, result = SCAN_SUCCEED;
1606 bool is_shmem = shmem_file(file);
1609 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1610 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1612 result = alloc_charge_hpage(&hpage, mm, cc);
1613 if (result != SCAN_SUCCEED)
1617 * Ensure we have slots for all the pages in the range. This is
1618 * almost certainly a no-op because most of the pages must be present
1622 xas_create_range(&xas);
1623 if (!xas_error(&xas))
1625 xas_unlock_irq(&xas);
1626 if (!xas_nomem(&xas, GFP_KERNEL)) {
1632 __SetPageLocked(hpage);
1634 __SetPageSwapBacked(hpage);
1635 hpage->index = start;
1636 hpage->mapping = mapping;
1639 * At this point the hpage is locked and not up-to-date.
1640 * It's safe to insert it into the page cache, because nobody would
1641 * be able to map it or use it in another way until we unlock it.
1644 xas_set(&xas, start);
1645 for (index = start; index < end; index++) {
1646 struct page *page = xas_next(&xas);
1648 VM_BUG_ON(index != xas.xa_index);
1652 * Stop if extent has been truncated or
1653 * hole-punched, and is now completely
1656 if (index == start) {
1657 if (!xas_next_entry(&xas, end - 1)) {
1658 result = SCAN_TRUNCATED;
1661 xas_set(&xas, index);
1663 if (!shmem_charge(mapping->host, 1)) {
1667 xas_store(&xas, hpage);
1672 if (xa_is_value(page) || !PageUptodate(page)) {
1673 xas_unlock_irq(&xas);
1674 /* swap in or instantiate fallocated page */
1675 if (shmem_getpage(mapping->host, index, &page,
1680 } else if (trylock_page(page)) {
1682 xas_unlock_irq(&xas);
1684 result = SCAN_PAGE_LOCK;
1687 } else { /* !is_shmem */
1688 if (!page || xa_is_value(page)) {
1689 xas_unlock_irq(&xas);
1690 page_cache_sync_readahead(mapping, &file->f_ra,
1693 /* drain pagevecs to help isolate_lru_page() */
1695 page = find_lock_page(mapping, index);
1696 if (unlikely(page == NULL)) {
1700 } else if (PageDirty(page)) {
1702 * khugepaged only works on read-only fd,
1703 * so this page is dirty because it hasn't
1704 * been flushed since first write. There
1705 * won't be new dirty pages.
1707 * Trigger async flush here and hope the
1708 * writeback is done when khugepaged
1709 * revisits this page.
1711 * This is a one-off situation. We are not
1712 * forcing writeback in loop.
1714 xas_unlock_irq(&xas);
1715 filemap_flush(mapping);
1718 } else if (PageWriteback(page)) {
1719 xas_unlock_irq(&xas);
1722 } else if (trylock_page(page)) {
1724 xas_unlock_irq(&xas);
1726 result = SCAN_PAGE_LOCK;
1732 * The page must be locked, so we can drop the i_pages lock
1733 * without racing with truncate.
1735 VM_BUG_ON_PAGE(!PageLocked(page), page);
1737 /* make sure the page is up to date */
1738 if (unlikely(!PageUptodate(page))) {
1744 * If file was truncated then extended, or hole-punched, before
1745 * we locked the first page, then a THP might be there already.
1747 if (PageTransCompound(page)) {
1748 result = SCAN_PAGE_COMPOUND;
1752 if (page_mapping(page) != mapping) {
1753 result = SCAN_TRUNCATED;
1757 if (!is_shmem && (PageDirty(page) ||
1758 PageWriteback(page))) {
1760 * khugepaged only works on read-only fd, so this
1761 * page is dirty because it hasn't been flushed
1762 * since first write.
1768 if (isolate_lru_page(page)) {
1769 result = SCAN_DEL_PAGE_LRU;
1773 if (page_has_private(page) &&
1774 !try_to_release_page(page, GFP_KERNEL)) {
1775 result = SCAN_PAGE_HAS_PRIVATE;
1776 putback_lru_page(page);
1780 if (page_mapped(page))
1781 try_to_unmap(page_folio(page),
1782 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1785 xas_set(&xas, index);
1787 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1790 * The page is expected to have page_count() == 3:
1791 * - we hold a pin on it;
1792 * - one reference from page cache;
1793 * - one from isolate_lru_page;
1795 if (!page_ref_freeze(page, 3)) {
1796 result = SCAN_PAGE_COUNT;
1797 xas_unlock_irq(&xas);
1798 putback_lru_page(page);
1803 * Add the page to the list to be able to undo the collapse if
1804 * something go wrong.
1806 list_add_tail(&page->lru, &pagelist);
1808 /* Finally, replace with the new page. */
1809 xas_store(&xas, hpage);
1816 nr = thp_nr_pages(hpage);
1819 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
1821 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
1822 filemap_nr_thps_inc(mapping);
1824 * Paired with smp_mb() in do_dentry_open() to ensure
1825 * i_writecount is up to date and the update to nr_thps is
1826 * visible. Ensures the page cache will be truncated if the
1827 * file is opened writable.
1830 if (inode_is_open_for_write(mapping->host)) {
1832 __mod_lruvec_page_state(hpage, NR_FILE_THPS, -nr);
1833 filemap_nr_thps_dec(mapping);
1839 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
1840 /* nr_none is always 0 for non-shmem. */
1841 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
1844 /* Join all the small entries into a single multi-index entry */
1845 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
1846 xas_store(&xas, hpage);
1848 xas_unlock_irq(&xas);
1852 * If collapse is successful, flush must be done now before copying.
1853 * If collapse is unsuccessful, does flush actually need to be done?
1854 * Do it anyway, to clear the state.
1856 try_to_unmap_flush();
1858 if (result == SCAN_SUCCEED) {
1859 struct page *page, *tmp;
1862 * Replacing old pages with new one has succeeded, now we
1863 * need to copy the content and free the old pages.
1866 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1867 while (index < page->index) {
1868 clear_highpage(hpage + (index % HPAGE_PMD_NR));
1871 copy_highpage(hpage + (page->index % HPAGE_PMD_NR),
1873 list_del(&page->lru);
1874 page->mapping = NULL;
1875 page_ref_unfreeze(page, 1);
1876 ClearPageActive(page);
1877 ClearPageUnevictable(page);
1882 while (index < end) {
1883 clear_highpage(hpage + (index % HPAGE_PMD_NR));
1887 SetPageUptodate(hpage);
1888 page_ref_add(hpage, HPAGE_PMD_NR - 1);
1890 set_page_dirty(hpage);
1891 lru_cache_add(hpage);
1894 * Remove pte page tables, so we can re-fault the page as huge.
1896 retract_page_tables(mapping, start);
1902 /* Something went wrong: roll back page cache changes */
1905 mapping->nrpages -= nr_none;
1906 shmem_uncharge(mapping->host, nr_none);
1909 xas_set(&xas, start);
1910 xas_for_each(&xas, page, end - 1) {
1911 page = list_first_entry_or_null(&pagelist,
1913 if (!page || xas.xa_index < page->index) {
1917 /* Put holes back where they were */
1918 xas_store(&xas, NULL);
1922 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1924 /* Unfreeze the page. */
1925 list_del(&page->lru);
1926 page_ref_unfreeze(page, 2);
1927 xas_store(&xas, page);
1929 xas_unlock_irq(&xas);
1931 putback_lru_page(page);
1935 xas_unlock_irq(&xas);
1937 hpage->mapping = NULL;
1943 VM_BUG_ON(!list_empty(&pagelist));
1945 mem_cgroup_uncharge(page_folio(hpage));
1948 /* TODO: tracepoints */
1952 static int khugepaged_scan_file(struct mm_struct *mm, struct file *file,
1953 pgoff_t start, struct collapse_control *cc)
1955 struct page *page = NULL;
1956 struct address_space *mapping = file->f_mapping;
1957 XA_STATE(xas, &mapping->i_pages, start);
1959 int node = NUMA_NO_NODE;
1960 int result = SCAN_SUCCEED;
1964 memset(cc->node_load, 0, sizeof(cc->node_load));
1966 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
1967 if (xas_retry(&xas, page))
1970 if (xa_is_value(page)) {
1972 if (cc->is_khugepaged &&
1973 swap > khugepaged_max_ptes_swap) {
1974 result = SCAN_EXCEED_SWAP_PTE;
1975 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1982 * XXX: khugepaged should compact smaller compound pages
1983 * into a PMD sized page
1985 if (PageTransCompound(page)) {
1986 result = SCAN_PAGE_COMPOUND;
1990 node = page_to_nid(page);
1991 if (hpage_collapse_scan_abort(node, cc)) {
1992 result = SCAN_SCAN_ABORT;
1995 cc->node_load[node]++;
1997 if (!PageLRU(page)) {
1998 result = SCAN_PAGE_LRU;
2002 if (page_count(page) !=
2003 1 + page_mapcount(page) + page_has_private(page)) {
2004 result = SCAN_PAGE_COUNT;
2009 * We probably should check if the page is referenced here, but
2010 * nobody would transfer pte_young() to PageReferenced() for us.
2011 * And rmap walk here is just too costly...
2016 if (need_resched()) {
2023 if (result == SCAN_SUCCEED) {
2024 if (cc->is_khugepaged &&
2025 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2026 result = SCAN_EXCEED_NONE_PTE;
2027 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2029 result = collapse_file(mm, file, start, cc);
2033 /* TODO: tracepoints */
2037 static int khugepaged_scan_file(struct mm_struct *mm, struct file *file,
2038 pgoff_t start, struct collapse_control *cc)
2043 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
2048 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2049 struct collapse_control *cc)
2050 __releases(&khugepaged_mm_lock)
2051 __acquires(&khugepaged_mm_lock)
2053 struct mm_slot *mm_slot;
2054 struct mm_struct *mm;
2055 struct vm_area_struct *vma;
2059 lockdep_assert_held(&khugepaged_mm_lock);
2060 *result = SCAN_FAIL;
2062 if (khugepaged_scan.mm_slot)
2063 mm_slot = khugepaged_scan.mm_slot;
2065 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2066 struct mm_slot, mm_node);
2067 khugepaged_scan.address = 0;
2068 khugepaged_scan.mm_slot = mm_slot;
2070 spin_unlock(&khugepaged_mm_lock);
2071 khugepaged_collapse_pte_mapped_thps(mm_slot);
2075 * Don't wait for semaphore (to avoid long wait times). Just move to
2076 * the next mm on the list.
2079 if (unlikely(!mmap_read_trylock(mm)))
2080 goto breakouterloop_mmap_lock;
2081 if (likely(!hpage_collapse_test_exit(mm)))
2082 vma = find_vma(mm, khugepaged_scan.address);
2085 for (; vma; vma = vma->vm_next) {
2086 unsigned long hstart, hend;
2089 if (unlikely(hpage_collapse_test_exit(mm))) {
2093 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2098 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2099 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2100 if (khugepaged_scan.address > hend)
2102 if (khugepaged_scan.address < hstart)
2103 khugepaged_scan.address = hstart;
2104 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2106 while (khugepaged_scan.address < hend) {
2107 bool mmap_locked = true;
2110 if (unlikely(hpage_collapse_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);
2122 *result = khugepaged_scan_file(mm, file, pgoff,
2124 mmap_locked = false;
2127 *result = hpage_collapse_scan_pmd(mm, vma,
2128 khugepaged_scan.address,
2132 if (*result == SCAN_SUCCEED)
2133 ++khugepaged_pages_collapsed;
2134 /* move to next address */
2135 khugepaged_scan.address += HPAGE_PMD_SIZE;
2136 progress += HPAGE_PMD_NR;
2139 * We released mmap_lock so break loop. Note
2140 * that we drop mmap_lock before all hugepage
2141 * allocations, so if allocation fails, we are
2142 * guaranteed to break here and report the
2143 * correct result back to caller.
2145 goto breakouterloop_mmap_lock;
2146 if (progress >= pages)
2147 goto breakouterloop;
2151 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2152 breakouterloop_mmap_lock:
2154 spin_lock(&khugepaged_mm_lock);
2155 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2157 * Release the current mm_slot if this mm is about to die, or
2158 * if we scanned all vmas of this mm.
2160 if (hpage_collapse_test_exit(mm) || !vma) {
2162 * Make sure that if mm_users is reaching zero while
2163 * khugepaged runs here, khugepaged_exit will find
2164 * mm_slot not pointing to the exiting mm.
2166 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2167 khugepaged_scan.mm_slot = list_entry(
2168 mm_slot->mm_node.next,
2169 struct mm_slot, mm_node);
2170 khugepaged_scan.address = 0;
2172 khugepaged_scan.mm_slot = NULL;
2173 khugepaged_full_scans++;
2176 collect_mm_slot(mm_slot);
2182 static int khugepaged_has_work(void)
2184 return !list_empty(&khugepaged_scan.mm_head) &&
2185 hugepage_flags_enabled();
2188 static int khugepaged_wait_event(void)
2190 return !list_empty(&khugepaged_scan.mm_head) ||
2191 kthread_should_stop();
2194 static void khugepaged_do_scan(struct collapse_control *cc)
2196 unsigned int progress = 0, pass_through_head = 0;
2197 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2199 int result = SCAN_SUCCEED;
2201 lru_add_drain_all();
2206 if (unlikely(kthread_should_stop() || try_to_freeze()))
2209 spin_lock(&khugepaged_mm_lock);
2210 if (!khugepaged_scan.mm_slot)
2211 pass_through_head++;
2212 if (khugepaged_has_work() &&
2213 pass_through_head < 2)
2214 progress += khugepaged_scan_mm_slot(pages - progress,
2218 spin_unlock(&khugepaged_mm_lock);
2220 if (progress >= pages)
2223 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2225 * If fail to allocate the first time, try to sleep for
2226 * a while. When hit again, cancel the scan.
2231 khugepaged_alloc_sleep();
2236 static bool khugepaged_should_wakeup(void)
2238 return kthread_should_stop() ||
2239 time_after_eq(jiffies, khugepaged_sleep_expire);
2242 static void khugepaged_wait_work(void)
2244 if (khugepaged_has_work()) {
2245 const unsigned long scan_sleep_jiffies =
2246 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2248 if (!scan_sleep_jiffies)
2251 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2252 wait_event_freezable_timeout(khugepaged_wait,
2253 khugepaged_should_wakeup(),
2254 scan_sleep_jiffies);
2258 if (hugepage_flags_enabled())
2259 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2262 static int khugepaged(void *none)
2264 struct mm_slot *mm_slot;
2267 set_user_nice(current, MAX_NICE);
2269 while (!kthread_should_stop()) {
2270 khugepaged_do_scan(&khugepaged_collapse_control);
2271 khugepaged_wait_work();
2274 spin_lock(&khugepaged_mm_lock);
2275 mm_slot = khugepaged_scan.mm_slot;
2276 khugepaged_scan.mm_slot = NULL;
2278 collect_mm_slot(mm_slot);
2279 spin_unlock(&khugepaged_mm_lock);
2283 static void set_recommended_min_free_kbytes(void)
2287 unsigned long recommended_min;
2289 if (!hugepage_flags_enabled()) {
2290 calculate_min_free_kbytes();
2294 for_each_populated_zone(zone) {
2296 * We don't need to worry about fragmentation of
2297 * ZONE_MOVABLE since it only has movable pages.
2299 if (zone_idx(zone) > gfp_zone(GFP_USER))
2305 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2306 recommended_min = pageblock_nr_pages * nr_zones * 2;
2309 * Make sure that on average at least two pageblocks are almost free
2310 * of another type, one for a migratetype to fall back to and a
2311 * second to avoid subsequent fallbacks of other types There are 3
2312 * MIGRATE_TYPES we care about.
2314 recommended_min += pageblock_nr_pages * nr_zones *
2315 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2317 /* don't ever allow to reserve more than 5% of the lowmem */
2318 recommended_min = min(recommended_min,
2319 (unsigned long) nr_free_buffer_pages() / 20);
2320 recommended_min <<= (PAGE_SHIFT-10);
2322 if (recommended_min > min_free_kbytes) {
2323 if (user_min_free_kbytes >= 0)
2324 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2325 min_free_kbytes, recommended_min);
2327 min_free_kbytes = recommended_min;
2331 setup_per_zone_wmarks();
2334 int start_stop_khugepaged(void)
2338 mutex_lock(&khugepaged_mutex);
2339 if (hugepage_flags_enabled()) {
2340 if (!khugepaged_thread)
2341 khugepaged_thread = kthread_run(khugepaged, NULL,
2343 if (IS_ERR(khugepaged_thread)) {
2344 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2345 err = PTR_ERR(khugepaged_thread);
2346 khugepaged_thread = NULL;
2350 if (!list_empty(&khugepaged_scan.mm_head))
2351 wake_up_interruptible(&khugepaged_wait);
2352 } else if (khugepaged_thread) {
2353 kthread_stop(khugepaged_thread);
2354 khugepaged_thread = NULL;
2356 set_recommended_min_free_kbytes();
2358 mutex_unlock(&khugepaged_mutex);
2362 void khugepaged_min_free_kbytes_update(void)
2364 mutex_lock(&khugepaged_mutex);
2365 if (hugepage_flags_enabled() && khugepaged_thread)
2366 set_recommended_min_free_kbytes();
2367 mutex_unlock(&khugepaged_mutex);
2370 static int madvise_collapse_errno(enum scan_result r)
2373 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2374 * actionable feedback to caller, so they may take an appropriate
2375 * fallback measure depending on the nature of the failure.
2378 case SCAN_ALLOC_HUGE_PAGE_FAIL:
2380 case SCAN_CGROUP_CHARGE_FAIL:
2382 /* Resource temporary unavailable - trying again might succeed */
2383 case SCAN_PAGE_LOCK:
2387 * Other: Trying again likely not to succeed / error intrinsic to
2388 * specified memory range. khugepaged likely won't be able to collapse
2396 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2397 unsigned long start, unsigned long end)
2399 struct collapse_control *cc;
2400 struct mm_struct *mm = vma->vm_mm;
2401 unsigned long hstart, hend, addr;
2402 int thps = 0, last_fail = SCAN_FAIL;
2403 bool mmap_locked = true;
2405 BUG_ON(vma->vm_start > start);
2406 BUG_ON(vma->vm_end < end);
2410 /* TODO: Support file/shmem */
2411 if (!vma->anon_vma || !vma_is_anonymous(vma))
2414 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2417 cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2420 cc->is_khugepaged = false;
2421 cc->last_target_node = NUMA_NO_NODE;
2424 lru_add_drain_all();
2426 hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2427 hend = end & HPAGE_PMD_MASK;
2429 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2430 int result = SCAN_FAIL;
2436 result = hugepage_vma_revalidate(mm, addr, &vma, cc);
2437 if (result != SCAN_SUCCEED) {
2442 hend = vma->vm_end & HPAGE_PMD_MASK;
2444 mmap_assert_locked(mm);
2445 memset(cc->node_load, 0, sizeof(cc->node_load));
2446 result = hpage_collapse_scan_pmd(mm, vma, addr, &mmap_locked,
2449 *prev = NULL; /* Tell caller we dropped mmap_lock */
2453 case SCAN_PMD_MAPPED:
2456 /* Whitelisted set of results where continuing OK */
2458 case SCAN_PTE_NON_PRESENT:
2459 case SCAN_PTE_UFFD_WP:
2461 case SCAN_LACK_REFERENCED_PAGE:
2462 case SCAN_PAGE_NULL:
2463 case SCAN_PAGE_COUNT:
2464 case SCAN_PAGE_LOCK:
2465 case SCAN_PAGE_COMPOUND:
2471 /* Other error, exit */
2477 /* Caller expects us to hold mmap_lock on return */
2481 mmap_assert_locked(mm);
2485 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2486 : madvise_collapse_errno(last_fail);