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 hugepage_flags_enabled()) {
469 if (hugepage_vma_check(vma, vm_flags, false, 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 #define khugepaged_defrag() \
765 (transparent_hugepage_flags & \
766 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
768 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
769 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
771 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
775 static int khugepaged_find_target_node(void)
777 static int last_khugepaged_target_node = NUMA_NO_NODE;
778 int nid, target_node = 0, max_value = 0;
780 /* find first node with max normal pages hit */
781 for (nid = 0; nid < MAX_NUMNODES; nid++)
782 if (khugepaged_node_load[nid] > max_value) {
783 max_value = khugepaged_node_load[nid];
787 /* do some balance if several nodes have the same hit record */
788 if (target_node <= last_khugepaged_target_node)
789 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
791 if (max_value == khugepaged_node_load[nid]) {
796 last_khugepaged_target_node = target_node;
800 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
802 if (IS_ERR(*hpage)) {
808 khugepaged_alloc_sleep();
818 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
820 VM_BUG_ON_PAGE(*hpage, *hpage);
822 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
823 if (unlikely(!*hpage)) {
824 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
825 *hpage = ERR_PTR(-ENOMEM);
829 prep_transhuge_page(*hpage);
830 count_vm_event(THP_COLLAPSE_ALLOC);
834 static int khugepaged_find_target_node(void)
839 static inline struct page *alloc_khugepaged_hugepage(void)
843 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
846 prep_transhuge_page(page);
850 static struct page *khugepaged_alloc_hugepage(bool *wait)
855 hpage = alloc_khugepaged_hugepage();
857 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
862 khugepaged_alloc_sleep();
864 count_vm_event(THP_COLLAPSE_ALLOC);
865 } while (unlikely(!hpage) && likely(hugepage_flags_enabled()));
870 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
873 * If the hpage allocated earlier was briefly exposed in page cache
874 * before collapse_file() failed, it is possible that racing lookups
875 * have not yet completed, and would then be unpleasantly surprised by
876 * finding the hpage reused for the same mapping at a different offset.
877 * Just release the previous allocation if there is any danger of that.
879 if (*hpage && page_count(*hpage) > 1) {
885 *hpage = khugepaged_alloc_hugepage(wait);
887 if (unlikely(!*hpage))
894 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
903 * If mmap_lock temporarily dropped, revalidate vma
904 * before taking mmap_lock.
905 * Return 0 if succeeds, otherwise return none-zero
909 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
910 struct vm_area_struct **vmap)
912 struct vm_area_struct *vma;
914 if (unlikely(khugepaged_test_exit(mm)))
915 return SCAN_ANY_PROCESS;
917 *vmap = vma = find_vma(mm, address);
919 return SCAN_VMA_NULL;
921 if (!transhuge_vma_suitable(vma, address))
922 return SCAN_ADDRESS_RANGE;
923 if (!hugepage_vma_check(vma, vma->vm_flags, false, false))
924 return SCAN_VMA_CHECK;
926 * Anon VMA expected, the address may be unmapped then
927 * remapped to file after khugepaged reaquired the mmap_lock.
929 * hugepage_vma_check may return true for qualified file
932 if (!vma->anon_vma || !vma_is_anonymous(vma))
933 return SCAN_VMA_CHECK;
938 * Bring missing pages in from swap, to complete THP collapse.
939 * Only done if khugepaged_scan_pmd believes it is worthwhile.
941 * Called and returns without pte mapped or spinlocks held.
942 * Note that if false is returned, mmap_lock will be released.
945 static bool __collapse_huge_page_swapin(struct mm_struct *mm,
946 struct vm_area_struct *vma,
947 unsigned long haddr, pmd_t *pmd,
952 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
954 for (address = haddr; address < end; address += PAGE_SIZE) {
955 struct vm_fault vmf = {
958 .pgoff = linear_page_index(vma, haddr),
959 .flags = FAULT_FLAG_ALLOW_RETRY,
963 vmf.pte = pte_offset_map(pmd, address);
964 vmf.orig_pte = *vmf.pte;
965 if (!is_swap_pte(vmf.orig_pte)) {
969 ret = do_swap_page(&vmf);
972 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
973 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
974 * we do not retry here and swap entry will remain in pagetable
975 * resulting in later failure.
977 if (ret & VM_FAULT_RETRY) {
978 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
981 if (ret & VM_FAULT_ERROR) {
982 mmap_read_unlock(mm);
983 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
989 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
993 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
997 static void collapse_huge_page(struct mm_struct *mm,
998 unsigned long address,
1000 int node, int referenced, int unmapped)
1002 LIST_HEAD(compound_pagelist);
1006 struct page *new_page;
1007 spinlock_t *pmd_ptl, *pte_ptl;
1008 int isolated = 0, result = 0;
1009 struct vm_area_struct *vma;
1010 struct mmu_notifier_range range;
1013 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1015 /* Only allocate from the target node */
1016 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1019 * Before allocating the hugepage, release the mmap_lock read lock.
1020 * The allocation can take potentially a long time if it involves
1021 * sync compaction, and we do not need to hold the mmap_lock during
1022 * that. We will recheck the vma after taking it again in write mode.
1024 mmap_read_unlock(mm);
1025 new_page = khugepaged_alloc_page(hpage, gfp, node);
1027 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1031 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) {
1032 result = SCAN_CGROUP_CHARGE_FAIL;
1035 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
1038 result = hugepage_vma_revalidate(mm, address, &vma);
1040 mmap_read_unlock(mm);
1044 pmd = mm_find_pmd(mm, address);
1046 result = SCAN_PMD_NULL;
1047 mmap_read_unlock(mm);
1052 * __collapse_huge_page_swapin will return with mmap_lock released
1053 * when it fails. So we jump out_nolock directly in that case.
1054 * Continuing to collapse causes inconsistency.
1056 if (unmapped && !__collapse_huge_page_swapin(mm, vma, address,
1061 mmap_read_unlock(mm);
1063 * Prevent all access to pagetables with the exception of
1064 * gup_fast later handled by the ptep_clear_flush and the VM
1065 * handled by the anon_vma lock + PG_lock.
1067 mmap_write_lock(mm);
1068 result = hugepage_vma_revalidate(mm, address, &vma);
1071 /* check if the pmd is still valid */
1072 if (mm_find_pmd(mm, address) != pmd)
1075 anon_vma_lock_write(vma->anon_vma);
1077 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1078 address, address + HPAGE_PMD_SIZE);
1079 mmu_notifier_invalidate_range_start(&range);
1081 pte = pte_offset_map(pmd, address);
1082 pte_ptl = pte_lockptr(mm, pmd);
1084 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1086 * After this gup_fast can't run anymore. This also removes
1087 * any huge TLB entry from the CPU so we won't allow
1088 * huge and small TLB entries for the same virtual address
1089 * to avoid the risk of CPU bugs in that area.
1091 _pmd = pmdp_collapse_flush(vma, address, pmd);
1092 spin_unlock(pmd_ptl);
1093 mmu_notifier_invalidate_range_end(&range);
1096 isolated = __collapse_huge_page_isolate(vma, address, pte,
1097 &compound_pagelist);
1098 spin_unlock(pte_ptl);
1100 if (unlikely(!isolated)) {
1103 BUG_ON(!pmd_none(*pmd));
1105 * We can only use set_pmd_at when establishing
1106 * hugepmds and never for establishing regular pmds that
1107 * points to regular pagetables. Use pmd_populate for that
1109 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1110 spin_unlock(pmd_ptl);
1111 anon_vma_unlock_write(vma->anon_vma);
1117 * All pages are isolated and locked so anon_vma rmap
1118 * can't run anymore.
1120 anon_vma_unlock_write(vma->anon_vma);
1122 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl,
1123 &compound_pagelist);
1126 * spin_lock() below is not the equivalent of smp_wmb(), but
1127 * the smp_wmb() inside __SetPageUptodate() can be reused to
1128 * avoid the copy_huge_page writes to become visible after
1129 * the set_pmd_at() write.
1131 __SetPageUptodate(new_page);
1132 pgtable = pmd_pgtable(_pmd);
1134 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1135 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1138 BUG_ON(!pmd_none(*pmd));
1139 page_add_new_anon_rmap(new_page, vma, address);
1140 lru_cache_add_inactive_or_unevictable(new_page, vma);
1141 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1142 set_pmd_at(mm, address, pmd, _pmd);
1143 update_mmu_cache_pmd(vma, address, pmd);
1144 spin_unlock(pmd_ptl);
1148 khugepaged_pages_collapsed++;
1149 result = SCAN_SUCCEED;
1151 mmap_write_unlock(mm);
1153 if (!IS_ERR_OR_NULL(*hpage))
1154 mem_cgroup_uncharge(page_folio(*hpage));
1155 trace_mm_collapse_huge_page(mm, isolated, result);
1159 static int khugepaged_scan_pmd(struct mm_struct *mm,
1160 struct vm_area_struct *vma,
1161 unsigned long address,
1162 struct page **hpage)
1166 int ret = 0, result = 0, referenced = 0;
1167 int none_or_zero = 0, shared = 0;
1168 struct page *page = NULL;
1169 unsigned long _address;
1171 int node = NUMA_NO_NODE, unmapped = 0;
1172 bool writable = false;
1174 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1176 pmd = mm_find_pmd(mm, address);
1178 result = SCAN_PMD_NULL;
1182 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1183 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1184 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1185 _pte++, _address += PAGE_SIZE) {
1186 pte_t pteval = *_pte;
1187 if (is_swap_pte(pteval)) {
1188 if (++unmapped <= khugepaged_max_ptes_swap) {
1190 * Always be strict with uffd-wp
1191 * enabled swap entries. Please see
1192 * comment below for pte_uffd_wp().
1194 if (pte_swp_uffd_wp(pteval)) {
1195 result = SCAN_PTE_UFFD_WP;
1200 result = SCAN_EXCEED_SWAP_PTE;
1201 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1205 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1206 if (!userfaultfd_armed(vma) &&
1207 ++none_or_zero <= khugepaged_max_ptes_none) {
1210 result = SCAN_EXCEED_NONE_PTE;
1211 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1215 if (pte_uffd_wp(pteval)) {
1217 * Don't collapse the page if any of the small
1218 * PTEs are armed with uffd write protection.
1219 * Here we can also mark the new huge pmd as
1220 * write protected if any of the small ones is
1221 * marked but that could bring unknown
1222 * userfault messages that falls outside of
1223 * the registered range. So, just be simple.
1225 result = SCAN_PTE_UFFD_WP;
1228 if (pte_write(pteval))
1231 page = vm_normal_page(vma, _address, pteval);
1232 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1233 result = SCAN_PAGE_NULL;
1237 if (page_mapcount(page) > 1 &&
1238 ++shared > khugepaged_max_ptes_shared) {
1239 result = SCAN_EXCEED_SHARED_PTE;
1240 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1244 page = compound_head(page);
1247 * Record which node the original page is from and save this
1248 * information to khugepaged_node_load[].
1249 * Khugepaged will allocate hugepage from the node has the max
1252 node = page_to_nid(page);
1253 if (khugepaged_scan_abort(node)) {
1254 result = SCAN_SCAN_ABORT;
1257 khugepaged_node_load[node]++;
1258 if (!PageLRU(page)) {
1259 result = SCAN_PAGE_LRU;
1262 if (PageLocked(page)) {
1263 result = SCAN_PAGE_LOCK;
1266 if (!PageAnon(page)) {
1267 result = SCAN_PAGE_ANON;
1272 * Check if the page has any GUP (or other external) pins.
1274 * Here the check is racy it may see total_mapcount > refcount
1276 * For example, one process with one forked child process.
1277 * The parent has the PMD split due to MADV_DONTNEED, then
1278 * the child is trying unmap the whole PMD, but khugepaged
1279 * may be scanning the parent between the child has
1280 * PageDoubleMap flag cleared and dec the mapcount. So
1281 * khugepaged may see total_mapcount > refcount.
1283 * But such case is ephemeral we could always retry collapse
1284 * later. However it may report false positive if the page
1285 * has excessive GUP pins (i.e. 512). Anyway the same check
1286 * will be done again later the risk seems low.
1288 if (!is_refcount_suitable(page)) {
1289 result = SCAN_PAGE_COUNT;
1292 if (pte_young(pteval) ||
1293 page_is_young(page) || PageReferenced(page) ||
1294 mmu_notifier_test_young(vma->vm_mm, address))
1298 result = SCAN_PAGE_RO;
1299 } else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
1300 result = SCAN_LACK_REFERENCED_PAGE;
1302 result = SCAN_SUCCEED;
1306 pte_unmap_unlock(pte, ptl);
1308 node = khugepaged_find_target_node();
1309 /* collapse_huge_page will return with the mmap_lock released */
1310 collapse_huge_page(mm, address, hpage, node,
1311 referenced, unmapped);
1314 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1315 none_or_zero, result, unmapped);
1319 static void collect_mm_slot(struct mm_slot *mm_slot)
1321 struct mm_struct *mm = mm_slot->mm;
1323 lockdep_assert_held(&khugepaged_mm_lock);
1325 if (khugepaged_test_exit(mm)) {
1327 hash_del(&mm_slot->hash);
1328 list_del(&mm_slot->mm_node);
1331 * Not strictly needed because the mm exited already.
1333 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1336 /* khugepaged_mm_lock actually not necessary for the below */
1337 free_mm_slot(mm_slot);
1344 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1345 * khugepaged should try to collapse the page table.
1347 static void khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1350 struct mm_slot *mm_slot;
1352 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1354 spin_lock(&khugepaged_mm_lock);
1355 mm_slot = get_mm_slot(mm);
1356 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
1357 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1358 spin_unlock(&khugepaged_mm_lock);
1361 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1362 unsigned long addr, pmd_t *pmdp)
1367 mmap_assert_write_locked(mm);
1368 ptl = pmd_lock(vma->vm_mm, pmdp);
1369 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1372 page_table_check_pte_clear_range(mm, addr, pmd);
1373 pte_free(mm, pmd_pgtable(pmd));
1377 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1380 * @mm: process address space where collapse happens
1381 * @addr: THP collapse address
1383 * This function checks whether all the PTEs in the PMD are pointing to the
1384 * right THP. If so, retract the page table so the THP can refault in with
1387 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
1389 unsigned long haddr = addr & HPAGE_PMD_MASK;
1390 struct vm_area_struct *vma = find_vma(mm, haddr);
1392 pte_t *start_pte, *pte;
1398 if (!vma || !vma->vm_file ||
1399 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1403 * This vm_flags may not have VM_HUGEPAGE if the page was not
1404 * collapsed by this mm. But we can still collapse if the page is
1405 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
1406 * will not fail the vma for missing VM_HUGEPAGE
1408 if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE, false, false))
1411 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1412 if (userfaultfd_wp(vma))
1415 hpage = find_lock_page(vma->vm_file->f_mapping,
1416 linear_page_index(vma, haddr));
1420 if (!PageHead(hpage))
1423 pmd = mm_find_pmd(mm, haddr);
1427 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1429 /* step 1: check all mapped PTEs are to the right huge page */
1430 for (i = 0, addr = haddr, pte = start_pte;
1431 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1434 /* empty pte, skip */
1438 /* page swapped out, abort */
1439 if (!pte_present(*pte))
1442 page = vm_normal_page(vma, addr, *pte);
1443 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1446 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1447 * page table, but the new page will not be a subpage of hpage.
1449 if (hpage + i != page)
1454 /* step 2: adjust rmap */
1455 for (i = 0, addr = haddr, pte = start_pte;
1456 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1461 page = vm_normal_page(vma, addr, *pte);
1462 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1464 page_remove_rmap(page, vma, false);
1467 pte_unmap_unlock(start_pte, ptl);
1469 /* step 3: set proper refcount and mm_counters. */
1471 page_ref_sub(hpage, count);
1472 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1475 /* step 4: collapse pmd */
1476 collapse_and_free_pmd(mm, vma, haddr, pmd);
1483 pte_unmap_unlock(start_pte, ptl);
1487 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1489 struct mm_struct *mm = mm_slot->mm;
1492 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1495 if (!mmap_write_trylock(mm))
1498 if (unlikely(khugepaged_test_exit(mm)))
1501 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1502 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
1505 mm_slot->nr_pte_mapped_thp = 0;
1506 mmap_write_unlock(mm);
1509 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1511 struct vm_area_struct *vma;
1512 struct mm_struct *mm;
1516 i_mmap_lock_write(mapping);
1517 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1519 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1520 * got written to. These VMAs are likely not worth investing
1521 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1524 * Note that vma->anon_vma check is racy: it can be set up after
1525 * the check but before we took mmap_lock by the fault path.
1526 * But page lock would prevent establishing any new ptes of the
1527 * page, so we are safe.
1529 * An alternative would be drop the check, but check that page
1530 * table is clear before calling pmdp_collapse_flush() under
1531 * ptl. It has higher chance to recover THP for the VMA, but
1532 * has higher cost too.
1536 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1537 if (addr & ~HPAGE_PMD_MASK)
1539 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1542 pmd = mm_find_pmd(mm, addr);
1546 * We need exclusive mmap_lock to retract page table.
1548 * We use trylock due to lock inversion: we need to acquire
1549 * mmap_lock while holding page lock. Fault path does it in
1550 * reverse order. Trylock is a way to avoid deadlock.
1552 if (mmap_write_trylock(mm)) {
1554 * When a vma is registered with uffd-wp, we can't
1555 * recycle the pmd pgtable because there can be pte
1556 * markers installed. Skip it only, so the rest mm/vma
1557 * can still have the same file mapped hugely, however
1558 * it'll always mapped in small page size for uffd-wp
1559 * registered ranges.
1561 if (!khugepaged_test_exit(mm) && !userfaultfd_wp(vma))
1562 collapse_and_free_pmd(mm, vma, addr, pmd);
1563 mmap_write_unlock(mm);
1565 /* Try again later */
1566 khugepaged_add_pte_mapped_thp(mm, addr);
1569 i_mmap_unlock_write(mapping);
1573 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1575 * @mm: process address space where collapse happens
1576 * @file: file that collapse on
1577 * @start: collapse start address
1578 * @hpage: new allocated huge page for collapse
1579 * @node: appointed node the new huge page allocate from
1581 * Basic scheme is simple, details are more complex:
1582 * - allocate and lock a new huge page;
1583 * - scan page cache replacing old pages with the new one
1584 * + swap/gup in pages if necessary;
1586 * + keep old pages around in case rollback is required;
1587 * - if replacing succeeds:
1590 * + unlock huge page;
1591 * - if replacing failed;
1592 * + put all pages back and unfreeze them;
1593 * + restore gaps in the page cache;
1594 * + unlock and free huge page;
1596 static void collapse_file(struct mm_struct *mm,
1597 struct file *file, pgoff_t start,
1598 struct page **hpage, int node)
1600 struct address_space *mapping = file->f_mapping;
1602 struct page *new_page;
1603 pgoff_t index, end = start + HPAGE_PMD_NR;
1604 LIST_HEAD(pagelist);
1605 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1606 int nr_none = 0, result = SCAN_SUCCEED;
1607 bool is_shmem = shmem_file(file);
1610 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1611 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1613 /* Only allocate from the target node */
1614 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1616 new_page = khugepaged_alloc_page(hpage, gfp, node);
1618 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1622 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) {
1623 result = SCAN_CGROUP_CHARGE_FAIL;
1626 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
1629 * Ensure we have slots for all the pages in the range. This is
1630 * almost certainly a no-op because most of the pages must be present
1634 xas_create_range(&xas);
1635 if (!xas_error(&xas))
1637 xas_unlock_irq(&xas);
1638 if (!xas_nomem(&xas, GFP_KERNEL)) {
1644 __SetPageLocked(new_page);
1646 __SetPageSwapBacked(new_page);
1647 new_page->index = start;
1648 new_page->mapping = mapping;
1651 * At this point the new_page is locked and not up-to-date.
1652 * It's safe to insert it into the page cache, because nobody would
1653 * be able to map it or use it in another way until we unlock it.
1656 xas_set(&xas, start);
1657 for (index = start; index < end; index++) {
1658 struct page *page = xas_next(&xas);
1660 VM_BUG_ON(index != xas.xa_index);
1664 * Stop if extent has been truncated or
1665 * hole-punched, and is now completely
1668 if (index == start) {
1669 if (!xas_next_entry(&xas, end - 1)) {
1670 result = SCAN_TRUNCATED;
1673 xas_set(&xas, index);
1675 if (!shmem_charge(mapping->host, 1)) {
1679 xas_store(&xas, new_page);
1684 if (xa_is_value(page) || !PageUptodate(page)) {
1685 xas_unlock_irq(&xas);
1686 /* swap in or instantiate fallocated page */
1687 if (shmem_getpage(mapping->host, index, &page,
1692 } else if (trylock_page(page)) {
1694 xas_unlock_irq(&xas);
1696 result = SCAN_PAGE_LOCK;
1699 } else { /* !is_shmem */
1700 if (!page || xa_is_value(page)) {
1701 xas_unlock_irq(&xas);
1702 page_cache_sync_readahead(mapping, &file->f_ra,
1705 /* drain pagevecs to help isolate_lru_page() */
1707 page = find_lock_page(mapping, index);
1708 if (unlikely(page == NULL)) {
1712 } else if (PageDirty(page)) {
1714 * khugepaged only works on read-only fd,
1715 * so this page is dirty because it hasn't
1716 * been flushed since first write. There
1717 * won't be new dirty pages.
1719 * Trigger async flush here and hope the
1720 * writeback is done when khugepaged
1721 * revisits this page.
1723 * This is a one-off situation. We are not
1724 * forcing writeback in loop.
1726 xas_unlock_irq(&xas);
1727 filemap_flush(mapping);
1730 } else if (PageWriteback(page)) {
1731 xas_unlock_irq(&xas);
1734 } else if (trylock_page(page)) {
1736 xas_unlock_irq(&xas);
1738 result = SCAN_PAGE_LOCK;
1744 * The page must be locked, so we can drop the i_pages lock
1745 * without racing with truncate.
1747 VM_BUG_ON_PAGE(!PageLocked(page), page);
1749 /* make sure the page is up to date */
1750 if (unlikely(!PageUptodate(page))) {
1756 * If file was truncated then extended, or hole-punched, before
1757 * we locked the first page, then a THP might be there already.
1759 if (PageTransCompound(page)) {
1760 result = SCAN_PAGE_COMPOUND;
1764 if (page_mapping(page) != mapping) {
1765 result = SCAN_TRUNCATED;
1769 if (!is_shmem && (PageDirty(page) ||
1770 PageWriteback(page))) {
1772 * khugepaged only works on read-only fd, so this
1773 * page is dirty because it hasn't been flushed
1774 * since first write.
1780 if (isolate_lru_page(page)) {
1781 result = SCAN_DEL_PAGE_LRU;
1785 if (page_has_private(page) &&
1786 !try_to_release_page(page, GFP_KERNEL)) {
1787 result = SCAN_PAGE_HAS_PRIVATE;
1788 putback_lru_page(page);
1792 if (page_mapped(page))
1793 try_to_unmap(page_folio(page),
1794 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1797 xas_set(&xas, index);
1799 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1802 * The page is expected to have page_count() == 3:
1803 * - we hold a pin on it;
1804 * - one reference from page cache;
1805 * - one from isolate_lru_page;
1807 if (!page_ref_freeze(page, 3)) {
1808 result = SCAN_PAGE_COUNT;
1809 xas_unlock_irq(&xas);
1810 putback_lru_page(page);
1815 * Add the page to the list to be able to undo the collapse if
1816 * something go wrong.
1818 list_add_tail(&page->lru, &pagelist);
1820 /* Finally, replace with the new page. */
1821 xas_store(&xas, new_page);
1828 nr = thp_nr_pages(new_page);
1831 __mod_lruvec_page_state(new_page, NR_SHMEM_THPS, nr);
1833 __mod_lruvec_page_state(new_page, NR_FILE_THPS, nr);
1834 filemap_nr_thps_inc(mapping);
1836 * Paired with smp_mb() in do_dentry_open() to ensure
1837 * i_writecount is up to date and the update to nr_thps is
1838 * visible. Ensures the page cache will be truncated if the
1839 * file is opened writable.
1842 if (inode_is_open_for_write(mapping->host)) {
1844 __mod_lruvec_page_state(new_page, NR_FILE_THPS, -nr);
1845 filemap_nr_thps_dec(mapping);
1851 __mod_lruvec_page_state(new_page, NR_FILE_PAGES, nr_none);
1852 /* nr_none is always 0 for non-shmem. */
1853 __mod_lruvec_page_state(new_page, NR_SHMEM, nr_none);
1856 /* Join all the small entries into a single multi-index entry */
1857 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
1858 xas_store(&xas, new_page);
1860 xas_unlock_irq(&xas);
1864 * If collapse is successful, flush must be done now before copying.
1865 * If collapse is unsuccessful, does flush actually need to be done?
1866 * Do it anyway, to clear the state.
1868 try_to_unmap_flush();
1870 if (result == SCAN_SUCCEED) {
1871 struct page *page, *tmp;
1874 * Replacing old pages with new one has succeeded, now we
1875 * need to copy the content and free the old pages.
1878 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1879 while (index < page->index) {
1880 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1883 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1885 list_del(&page->lru);
1886 page->mapping = NULL;
1887 page_ref_unfreeze(page, 1);
1888 ClearPageActive(page);
1889 ClearPageUnevictable(page);
1894 while (index < end) {
1895 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1899 SetPageUptodate(new_page);
1900 page_ref_add(new_page, HPAGE_PMD_NR - 1);
1902 set_page_dirty(new_page);
1903 lru_cache_add(new_page);
1906 * Remove pte page tables, so we can re-fault the page as huge.
1908 retract_page_tables(mapping, start);
1911 khugepaged_pages_collapsed++;
1915 /* Something went wrong: roll back page cache changes */
1918 mapping->nrpages -= nr_none;
1919 shmem_uncharge(mapping->host, nr_none);
1922 xas_set(&xas, start);
1923 xas_for_each(&xas, page, end - 1) {
1924 page = list_first_entry_or_null(&pagelist,
1926 if (!page || xas.xa_index < page->index) {
1930 /* Put holes back where they were */
1931 xas_store(&xas, NULL);
1935 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1937 /* Unfreeze the page. */
1938 list_del(&page->lru);
1939 page_ref_unfreeze(page, 2);
1940 xas_store(&xas, page);
1942 xas_unlock_irq(&xas);
1944 putback_lru_page(page);
1948 xas_unlock_irq(&xas);
1950 new_page->mapping = NULL;
1953 unlock_page(new_page);
1955 VM_BUG_ON(!list_empty(&pagelist));
1956 if (!IS_ERR_OR_NULL(*hpage))
1957 mem_cgroup_uncharge(page_folio(*hpage));
1958 /* TODO: tracepoints */
1961 static void khugepaged_scan_file(struct mm_struct *mm,
1962 struct file *file, pgoff_t start, struct page **hpage)
1964 struct page *page = NULL;
1965 struct address_space *mapping = file->f_mapping;
1966 XA_STATE(xas, &mapping->i_pages, start);
1968 int node = NUMA_NO_NODE;
1969 int result = SCAN_SUCCEED;
1973 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1975 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
1976 if (xas_retry(&xas, page))
1979 if (xa_is_value(page)) {
1980 if (++swap > khugepaged_max_ptes_swap) {
1981 result = SCAN_EXCEED_SWAP_PTE;
1982 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1989 * XXX: khugepaged should compact smaller compound pages
1990 * into a PMD sized page
1992 if (PageTransCompound(page)) {
1993 result = SCAN_PAGE_COMPOUND;
1997 node = page_to_nid(page);
1998 if (khugepaged_scan_abort(node)) {
1999 result = SCAN_SCAN_ABORT;
2002 khugepaged_node_load[node]++;
2004 if (!PageLRU(page)) {
2005 result = SCAN_PAGE_LRU;
2009 if (page_count(page) !=
2010 1 + page_mapcount(page) + page_has_private(page)) {
2011 result = SCAN_PAGE_COUNT;
2016 * We probably should check if the page is referenced here, but
2017 * nobody would transfer pte_young() to PageReferenced() for us.
2018 * And rmap walk here is just too costly...
2023 if (need_resched()) {
2030 if (result == SCAN_SUCCEED) {
2031 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2032 result = SCAN_EXCEED_NONE_PTE;
2033 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2035 node = khugepaged_find_target_node();
2036 collapse_file(mm, file, start, hpage, node);
2040 /* TODO: tracepoints */
2043 static void khugepaged_scan_file(struct mm_struct *mm,
2044 struct file *file, pgoff_t start, struct page **hpage)
2049 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
2054 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2055 struct page **hpage)
2056 __releases(&khugepaged_mm_lock)
2057 __acquires(&khugepaged_mm_lock)
2059 struct mm_slot *mm_slot;
2060 struct mm_struct *mm;
2061 struct vm_area_struct *vma;
2065 lockdep_assert_held(&khugepaged_mm_lock);
2067 if (khugepaged_scan.mm_slot)
2068 mm_slot = khugepaged_scan.mm_slot;
2070 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2071 struct mm_slot, mm_node);
2072 khugepaged_scan.address = 0;
2073 khugepaged_scan.mm_slot = mm_slot;
2075 spin_unlock(&khugepaged_mm_lock);
2076 khugepaged_collapse_pte_mapped_thps(mm_slot);
2080 * Don't wait for semaphore (to avoid long wait times). Just move to
2081 * the next mm on the list.
2084 if (unlikely(!mmap_read_trylock(mm)))
2085 goto breakouterloop_mmap_lock;
2086 if (likely(!khugepaged_test_exit(mm)))
2087 vma = find_vma(mm, khugepaged_scan.address);
2090 for (; vma; vma = vma->vm_next) {
2091 unsigned long hstart, hend;
2094 if (unlikely(khugepaged_test_exit(mm))) {
2098 if (!hugepage_vma_check(vma, vma->vm_flags, false, false)) {
2103 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2104 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2105 if (khugepaged_scan.address > hend)
2107 if (khugepaged_scan.address < hstart)
2108 khugepaged_scan.address = hstart;
2109 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2111 while (khugepaged_scan.address < hend) {
2114 if (unlikely(khugepaged_test_exit(mm)))
2115 goto breakouterloop;
2117 VM_BUG_ON(khugepaged_scan.address < hstart ||
2118 khugepaged_scan.address + HPAGE_PMD_SIZE >
2120 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2121 struct file *file = get_file(vma->vm_file);
2122 pgoff_t pgoff = linear_page_index(vma,
2123 khugepaged_scan.address);
2125 mmap_read_unlock(mm);
2127 khugepaged_scan_file(mm, file, pgoff, hpage);
2130 ret = khugepaged_scan_pmd(mm, vma,
2131 khugepaged_scan.address,
2134 /* move to next address */
2135 khugepaged_scan.address += HPAGE_PMD_SIZE;
2136 progress += HPAGE_PMD_NR;
2138 /* we released mmap_lock so break loop */
2139 goto breakouterloop_mmap_lock;
2140 if (progress >= pages)
2141 goto breakouterloop;
2145 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2146 breakouterloop_mmap_lock:
2148 spin_lock(&khugepaged_mm_lock);
2149 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2151 * Release the current mm_slot if this mm is about to die, or
2152 * if we scanned all vmas of this mm.
2154 if (khugepaged_test_exit(mm) || !vma) {
2156 * Make sure that if mm_users is reaching zero while
2157 * khugepaged runs here, khugepaged_exit will find
2158 * mm_slot not pointing to the exiting mm.
2160 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2161 khugepaged_scan.mm_slot = list_entry(
2162 mm_slot->mm_node.next,
2163 struct mm_slot, mm_node);
2164 khugepaged_scan.address = 0;
2166 khugepaged_scan.mm_slot = NULL;
2167 khugepaged_full_scans++;
2170 collect_mm_slot(mm_slot);
2176 static int khugepaged_has_work(void)
2178 return !list_empty(&khugepaged_scan.mm_head) &&
2179 hugepage_flags_enabled();
2182 static int khugepaged_wait_event(void)
2184 return !list_empty(&khugepaged_scan.mm_head) ||
2185 kthread_should_stop();
2188 static void khugepaged_do_scan(void)
2190 struct page *hpage = NULL;
2191 unsigned int progress = 0, pass_through_head = 0;
2192 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2195 lru_add_drain_all();
2197 while (progress < pages) {
2198 if (!khugepaged_prealloc_page(&hpage, &wait))
2203 if (unlikely(kthread_should_stop() || try_to_freeze()))
2206 spin_lock(&khugepaged_mm_lock);
2207 if (!khugepaged_scan.mm_slot)
2208 pass_through_head++;
2209 if (khugepaged_has_work() &&
2210 pass_through_head < 2)
2211 progress += khugepaged_scan_mm_slot(pages - progress,
2215 spin_unlock(&khugepaged_mm_lock);
2218 if (!IS_ERR_OR_NULL(hpage))
2222 static bool khugepaged_should_wakeup(void)
2224 return kthread_should_stop() ||
2225 time_after_eq(jiffies, khugepaged_sleep_expire);
2228 static void khugepaged_wait_work(void)
2230 if (khugepaged_has_work()) {
2231 const unsigned long scan_sleep_jiffies =
2232 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2234 if (!scan_sleep_jiffies)
2237 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2238 wait_event_freezable_timeout(khugepaged_wait,
2239 khugepaged_should_wakeup(),
2240 scan_sleep_jiffies);
2244 if (hugepage_flags_enabled())
2245 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2248 static int khugepaged(void *none)
2250 struct mm_slot *mm_slot;
2253 set_user_nice(current, MAX_NICE);
2255 while (!kthread_should_stop()) {
2256 khugepaged_do_scan();
2257 khugepaged_wait_work();
2260 spin_lock(&khugepaged_mm_lock);
2261 mm_slot = khugepaged_scan.mm_slot;
2262 khugepaged_scan.mm_slot = NULL;
2264 collect_mm_slot(mm_slot);
2265 spin_unlock(&khugepaged_mm_lock);
2269 static void set_recommended_min_free_kbytes(void)
2273 unsigned long recommended_min;
2275 if (!hugepage_flags_enabled()) {
2276 calculate_min_free_kbytes();
2280 for_each_populated_zone(zone) {
2282 * We don't need to worry about fragmentation of
2283 * ZONE_MOVABLE since it only has movable pages.
2285 if (zone_idx(zone) > gfp_zone(GFP_USER))
2291 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2292 recommended_min = pageblock_nr_pages * nr_zones * 2;
2295 * Make sure that on average at least two pageblocks are almost free
2296 * of another type, one for a migratetype to fall back to and a
2297 * second to avoid subsequent fallbacks of other types There are 3
2298 * MIGRATE_TYPES we care about.
2300 recommended_min += pageblock_nr_pages * nr_zones *
2301 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2303 /* don't ever allow to reserve more than 5% of the lowmem */
2304 recommended_min = min(recommended_min,
2305 (unsigned long) nr_free_buffer_pages() / 20);
2306 recommended_min <<= (PAGE_SHIFT-10);
2308 if (recommended_min > min_free_kbytes) {
2309 if (user_min_free_kbytes >= 0)
2310 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2311 min_free_kbytes, recommended_min);
2313 min_free_kbytes = recommended_min;
2317 setup_per_zone_wmarks();
2320 int start_stop_khugepaged(void)
2324 mutex_lock(&khugepaged_mutex);
2325 if (hugepage_flags_enabled()) {
2326 if (!khugepaged_thread)
2327 khugepaged_thread = kthread_run(khugepaged, NULL,
2329 if (IS_ERR(khugepaged_thread)) {
2330 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2331 err = PTR_ERR(khugepaged_thread);
2332 khugepaged_thread = NULL;
2336 if (!list_empty(&khugepaged_scan.mm_head))
2337 wake_up_interruptible(&khugepaged_wait);
2338 } else if (khugepaged_thread) {
2339 kthread_stop(khugepaged_thread);
2340 khugepaged_thread = NULL;
2342 set_recommended_min_free_kbytes();
2344 mutex_unlock(&khugepaged_mutex);
2348 void khugepaged_min_free_kbytes_update(void)
2350 mutex_lock(&khugepaged_mutex);
2351 if (hugepage_flags_enabled() && khugepaged_thread)
2352 set_recommended_min_free_kbytes();
2353 mutex_unlock(&khugepaged_mutex);