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>
36 SCAN_EXCEED_SHARED_PTE,
39 SCAN_PTE_MAPPED_HUGEPAGE,
41 SCAN_LACK_REFERENCED_PAGE,
54 SCAN_ALLOC_HUGE_PAGE_FAIL,
55 SCAN_CGROUP_CHARGE_FAIL,
57 SCAN_PAGE_HAS_PRIVATE,
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/huge_memory.h>
63 static struct task_struct *khugepaged_thread __read_mostly;
64 static DEFINE_MUTEX(khugepaged_mutex);
66 /* default scan 8*512 pte (or vmas) every 30 second */
67 static unsigned int khugepaged_pages_to_scan __read_mostly;
68 static unsigned int khugepaged_pages_collapsed;
69 static unsigned int khugepaged_full_scans;
70 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
71 /* during fragmentation poll the hugepage allocator once every minute */
72 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
73 static unsigned long khugepaged_sleep_expire;
74 static DEFINE_SPINLOCK(khugepaged_mm_lock);
75 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
77 * default collapse hugepages if there is at least one pte mapped like
78 * it would have happened if the vma was large enough during page
81 * Note that these are only respected if collapse was initiated by khugepaged.
83 static unsigned int khugepaged_max_ptes_none __read_mostly;
84 static unsigned int khugepaged_max_ptes_swap __read_mostly;
85 static unsigned int khugepaged_max_ptes_shared __read_mostly;
87 #define MM_SLOTS_HASH_BITS 10
88 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
90 static struct kmem_cache *mm_slot_cache __read_mostly;
92 #define MAX_PTE_MAPPED_THP 8
94 struct collapse_control {
97 /* Num pages scanned per node */
98 u32 node_load[MAX_NUMNODES];
100 /* nodemask for allocation fallback */
101 nodemask_t alloc_nmask;
105 * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
106 * @slot: hash lookup from mm to mm_slot
107 * @nr_pte_mapped_thp: number of pte mapped THP
108 * @pte_mapped_thp: address array corresponding pte mapped THP
110 struct khugepaged_mm_slot {
113 /* pte-mapped THP in this mm */
114 int nr_pte_mapped_thp;
115 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
119 * struct khugepaged_scan - cursor for scanning
120 * @mm_head: the head of the mm list to scan
121 * @mm_slot: the current mm_slot we are scanning
122 * @address: the next address inside that to be scanned
124 * There is only the one khugepaged_scan instance of this cursor structure.
126 struct khugepaged_scan {
127 struct list_head mm_head;
128 struct khugepaged_mm_slot *mm_slot;
129 unsigned long address;
132 static struct khugepaged_scan khugepaged_scan = {
133 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
137 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
138 struct kobj_attribute *attr,
141 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
144 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
145 struct kobj_attribute *attr,
146 const char *buf, size_t count)
151 err = kstrtouint(buf, 10, &msecs);
155 khugepaged_scan_sleep_millisecs = msecs;
156 khugepaged_sleep_expire = 0;
157 wake_up_interruptible(&khugepaged_wait);
161 static struct kobj_attribute scan_sleep_millisecs_attr =
162 __ATTR_RW(scan_sleep_millisecs);
164 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
165 struct kobj_attribute *attr,
168 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
171 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
172 struct kobj_attribute *attr,
173 const char *buf, size_t count)
178 err = kstrtouint(buf, 10, &msecs);
182 khugepaged_alloc_sleep_millisecs = msecs;
183 khugepaged_sleep_expire = 0;
184 wake_up_interruptible(&khugepaged_wait);
188 static struct kobj_attribute alloc_sleep_millisecs_attr =
189 __ATTR_RW(alloc_sleep_millisecs);
191 static ssize_t pages_to_scan_show(struct kobject *kobj,
192 struct kobj_attribute *attr,
195 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
197 static ssize_t pages_to_scan_store(struct kobject *kobj,
198 struct kobj_attribute *attr,
199 const char *buf, size_t count)
204 err = kstrtouint(buf, 10, &pages);
208 khugepaged_pages_to_scan = pages;
212 static struct kobj_attribute pages_to_scan_attr =
213 __ATTR_RW(pages_to_scan);
215 static ssize_t pages_collapsed_show(struct kobject *kobj,
216 struct kobj_attribute *attr,
219 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
221 static struct kobj_attribute pages_collapsed_attr =
222 __ATTR_RO(pages_collapsed);
224 static ssize_t full_scans_show(struct kobject *kobj,
225 struct kobj_attribute *attr,
228 return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
230 static struct kobj_attribute full_scans_attr =
231 __ATTR_RO(full_scans);
233 static ssize_t defrag_show(struct kobject *kobj,
234 struct kobj_attribute *attr, char *buf)
236 return single_hugepage_flag_show(kobj, attr, buf,
237 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
239 static ssize_t defrag_store(struct kobject *kobj,
240 struct kobj_attribute *attr,
241 const char *buf, size_t count)
243 return single_hugepage_flag_store(kobj, attr, buf, count,
244 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
246 static struct kobj_attribute khugepaged_defrag_attr =
250 * max_ptes_none controls if khugepaged should collapse hugepages over
251 * any unmapped ptes in turn potentially increasing the memory
252 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
253 * reduce the available free memory in the system as it
254 * runs. Increasing max_ptes_none will instead potentially reduce the
255 * free memory in the system during the khugepaged scan.
257 static ssize_t max_ptes_none_show(struct kobject *kobj,
258 struct kobj_attribute *attr,
261 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
263 static ssize_t max_ptes_none_store(struct kobject *kobj,
264 struct kobj_attribute *attr,
265 const char *buf, size_t count)
268 unsigned long max_ptes_none;
270 err = kstrtoul(buf, 10, &max_ptes_none);
271 if (err || max_ptes_none > HPAGE_PMD_NR - 1)
274 khugepaged_max_ptes_none = max_ptes_none;
278 static struct kobj_attribute khugepaged_max_ptes_none_attr =
279 __ATTR_RW(max_ptes_none);
281 static ssize_t max_ptes_swap_show(struct kobject *kobj,
282 struct kobj_attribute *attr,
285 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
288 static ssize_t max_ptes_swap_store(struct kobject *kobj,
289 struct kobj_attribute *attr,
290 const char *buf, size_t count)
293 unsigned long max_ptes_swap;
295 err = kstrtoul(buf, 10, &max_ptes_swap);
296 if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
299 khugepaged_max_ptes_swap = max_ptes_swap;
304 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
305 __ATTR_RW(max_ptes_swap);
307 static ssize_t max_ptes_shared_show(struct kobject *kobj,
308 struct kobj_attribute *attr,
311 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
314 static ssize_t max_ptes_shared_store(struct kobject *kobj,
315 struct kobj_attribute *attr,
316 const char *buf, size_t count)
319 unsigned long max_ptes_shared;
321 err = kstrtoul(buf, 10, &max_ptes_shared);
322 if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
325 khugepaged_max_ptes_shared = max_ptes_shared;
330 static struct kobj_attribute khugepaged_max_ptes_shared_attr =
331 __ATTR_RW(max_ptes_shared);
333 static struct attribute *khugepaged_attr[] = {
334 &khugepaged_defrag_attr.attr,
335 &khugepaged_max_ptes_none_attr.attr,
336 &khugepaged_max_ptes_swap_attr.attr,
337 &khugepaged_max_ptes_shared_attr.attr,
338 &pages_to_scan_attr.attr,
339 &pages_collapsed_attr.attr,
340 &full_scans_attr.attr,
341 &scan_sleep_millisecs_attr.attr,
342 &alloc_sleep_millisecs_attr.attr,
346 struct attribute_group khugepaged_attr_group = {
347 .attrs = khugepaged_attr,
348 .name = "khugepaged",
350 #endif /* CONFIG_SYSFS */
352 int hugepage_madvise(struct vm_area_struct *vma,
353 unsigned long *vm_flags, int advice)
359 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
360 * can't handle this properly after s390_enable_sie, so we simply
361 * ignore the madvise to prevent qemu from causing a SIGSEGV.
363 if (mm_has_pgste(vma->vm_mm))
366 *vm_flags &= ~VM_NOHUGEPAGE;
367 *vm_flags |= VM_HUGEPAGE;
369 * If the vma become good for khugepaged to scan,
370 * register it here without waiting a page fault that
371 * may not happen any time soon.
373 khugepaged_enter_vma(vma, *vm_flags);
375 case MADV_NOHUGEPAGE:
376 *vm_flags &= ~VM_HUGEPAGE;
377 *vm_flags |= VM_NOHUGEPAGE;
379 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
380 * this vma even if we leave the mm registered in khugepaged if
381 * it got registered before VM_NOHUGEPAGE was set.
389 int __init khugepaged_init(void)
391 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
392 sizeof(struct khugepaged_mm_slot),
393 __alignof__(struct khugepaged_mm_slot),
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 int hpage_collapse_test_exit(struct mm_struct *mm)
413 return atomic_read(&mm->mm_users) == 0;
416 void __khugepaged_enter(struct mm_struct *mm)
418 struct khugepaged_mm_slot *mm_slot;
419 struct mm_slot *slot;
422 mm_slot = mm_slot_alloc(mm_slot_cache);
426 slot = &mm_slot->slot;
428 /* __khugepaged_exit() must not run from under us */
429 VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
430 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
431 mm_slot_free(mm_slot_cache, mm_slot);
435 spin_lock(&khugepaged_mm_lock);
436 mm_slot_insert(mm_slots_hash, mm, slot);
438 * Insert just behind the scanning cursor, to let the area settle
441 wakeup = list_empty(&khugepaged_scan.mm_head);
442 list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
443 spin_unlock(&khugepaged_mm_lock);
447 wake_up_interruptible(&khugepaged_wait);
450 void khugepaged_enter_vma(struct vm_area_struct *vma,
451 unsigned long vm_flags)
453 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
454 hugepage_flags_enabled()) {
455 if (hugepage_vma_check(vma, vm_flags, false, false, true))
456 __khugepaged_enter(vma->vm_mm);
460 void __khugepaged_exit(struct mm_struct *mm)
462 struct khugepaged_mm_slot *mm_slot;
463 struct mm_slot *slot;
466 spin_lock(&khugepaged_mm_lock);
467 slot = mm_slot_lookup(mm_slots_hash, mm);
468 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
469 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
470 hash_del(&slot->hash);
471 list_del(&slot->mm_node);
474 spin_unlock(&khugepaged_mm_lock);
477 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
478 mm_slot_free(mm_slot_cache, mm_slot);
480 } else if (mm_slot) {
482 * This is required to serialize against
483 * hpage_collapse_test_exit() (which is guaranteed to run
484 * under mmap sem read mode). Stop here (after we return all
485 * pagetables will be destroyed) until khugepaged has finished
486 * working on the pagetables under the mmap_lock.
489 mmap_write_unlock(mm);
493 static void release_pte_folio(struct folio *folio)
495 node_stat_mod_folio(folio,
496 NR_ISOLATED_ANON + folio_is_file_lru(folio),
497 -folio_nr_pages(folio));
499 folio_putback_lru(folio);
502 static void release_pte_page(struct page *page)
504 release_pte_folio(page_folio(page));
507 static void release_pte_pages(pte_t *pte, pte_t *_pte,
508 struct list_head *compound_pagelist)
510 struct folio *folio, *tmp;
512 while (--_pte >= pte) {
513 pte_t pteval = *_pte;
515 folio = pfn_folio(pte_pfn(pteval));
516 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
517 !folio_test_large(folio))
518 release_pte_folio(folio);
521 list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
522 list_del(&folio->lru);
523 release_pte_folio(folio);
527 static bool is_refcount_suitable(struct page *page)
529 int expected_refcount;
531 expected_refcount = total_mapcount(page);
532 if (PageSwapCache(page))
533 expected_refcount += compound_nr(page);
535 return page_count(page) == expected_refcount;
538 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
539 unsigned long address,
541 struct collapse_control *cc,
542 struct list_head *compound_pagelist)
544 struct page *page = NULL;
546 int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
547 bool writable = false;
549 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
550 _pte++, address += PAGE_SIZE) {
551 pte_t pteval = *_pte;
552 if (pte_none(pteval) || (pte_present(pteval) &&
553 is_zero_pfn(pte_pfn(pteval)))) {
555 if (!userfaultfd_armed(vma) &&
556 (!cc->is_khugepaged ||
557 none_or_zero <= khugepaged_max_ptes_none)) {
560 result = SCAN_EXCEED_NONE_PTE;
561 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
565 if (!pte_present(pteval)) {
566 result = SCAN_PTE_NON_PRESENT;
569 page = vm_normal_page(vma, address, pteval);
570 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
571 result = SCAN_PAGE_NULL;
575 VM_BUG_ON_PAGE(!PageAnon(page), page);
577 if (page_mapcount(page) > 1) {
579 if (cc->is_khugepaged &&
580 shared > khugepaged_max_ptes_shared) {
581 result = SCAN_EXCEED_SHARED_PTE;
582 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
587 if (PageCompound(page)) {
589 page = compound_head(page);
592 * Check if we have dealt with the compound page
595 list_for_each_entry(p, compound_pagelist, lru) {
602 * We can do it before isolate_lru_page because the
603 * page can't be freed from under us. NOTE: PG_lock
604 * is needed to serialize against split_huge_page
605 * when invoked from the VM.
607 if (!trylock_page(page)) {
608 result = SCAN_PAGE_LOCK;
613 * Check if the page has any GUP (or other external) pins.
615 * The page table that maps the page has been already unlinked
616 * from the page table tree and this process cannot get
617 * an additional pin on the page.
619 * New pins can come later if the page is shared across fork,
620 * but not from this process. The other process cannot write to
621 * the page, only trigger CoW.
623 if (!is_refcount_suitable(page)) {
625 result = SCAN_PAGE_COUNT;
630 * Isolate the page to avoid collapsing an hugepage
631 * currently in use by the VM.
633 if (isolate_lru_page(page)) {
635 result = SCAN_DEL_PAGE_LRU;
638 mod_node_page_state(page_pgdat(page),
639 NR_ISOLATED_ANON + page_is_file_lru(page),
641 VM_BUG_ON_PAGE(!PageLocked(page), page);
642 VM_BUG_ON_PAGE(PageLRU(page), page);
644 if (PageCompound(page))
645 list_add_tail(&page->lru, compound_pagelist);
648 * If collapse was initiated by khugepaged, check that there is
649 * enough young pte to justify collapsing the page
651 if (cc->is_khugepaged &&
652 (pte_young(pteval) || page_is_young(page) ||
653 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
657 if (pte_write(pteval))
661 if (unlikely(!writable)) {
662 result = SCAN_PAGE_RO;
663 } else if (unlikely(cc->is_khugepaged && !referenced)) {
664 result = SCAN_LACK_REFERENCED_PAGE;
666 result = SCAN_SUCCEED;
667 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
668 referenced, writable, result);
672 release_pte_pages(pte, _pte, compound_pagelist);
673 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
674 referenced, writable, result);
678 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
679 struct vm_area_struct *vma,
680 unsigned long address,
682 struct list_head *compound_pagelist)
684 struct page *src_page, *tmp;
686 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
687 _pte++, page++, address += PAGE_SIZE) {
688 pte_t pteval = *_pte;
690 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
691 clear_user_highpage(page, address);
692 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
693 if (is_zero_pfn(pte_pfn(pteval))) {
695 * ptl mostly unnecessary.
698 ptep_clear(vma->vm_mm, address, _pte);
702 src_page = pte_page(pteval);
703 copy_user_highpage(page, src_page, address, vma);
704 if (!PageCompound(src_page))
705 release_pte_page(src_page);
707 * ptl mostly unnecessary, but preempt has to
708 * be disabled to update the per-cpu stats
709 * inside page_remove_rmap().
712 ptep_clear(vma->vm_mm, address, _pte);
713 page_remove_rmap(src_page, vma, false);
715 free_page_and_swap_cache(src_page);
719 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
720 list_del(&src_page->lru);
721 mod_node_page_state(page_pgdat(src_page),
722 NR_ISOLATED_ANON + page_is_file_lru(src_page),
723 -compound_nr(src_page));
724 unlock_page(src_page);
725 free_swap_cache(src_page);
726 putback_lru_page(src_page);
730 static void khugepaged_alloc_sleep(void)
734 add_wait_queue(&khugepaged_wait, &wait);
735 __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
736 schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
737 remove_wait_queue(&khugepaged_wait, &wait);
740 struct collapse_control khugepaged_collapse_control = {
741 .is_khugepaged = true,
744 static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
749 * If node_reclaim_mode is disabled, then no extra effort is made to
750 * allocate memory locally.
752 if (!node_reclaim_enabled())
755 /* If there is a count for this node already, it must be acceptable */
756 if (cc->node_load[nid])
759 for (i = 0; i < MAX_NUMNODES; i++) {
760 if (!cc->node_load[i])
762 if (node_distance(nid, i) > node_reclaim_distance)
768 #define khugepaged_defrag() \
769 (transparent_hugepage_flags & \
770 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
772 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
773 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
775 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
779 static int hpage_collapse_find_target_node(struct collapse_control *cc)
781 int nid, target_node = 0, max_value = 0;
783 /* find first node with max normal pages hit */
784 for (nid = 0; nid < MAX_NUMNODES; nid++)
785 if (cc->node_load[nid] > max_value) {
786 max_value = cc->node_load[nid];
790 for_each_online_node(nid) {
791 if (max_value == cc->node_load[nid])
792 node_set(nid, cc->alloc_nmask);
798 static int hpage_collapse_find_target_node(struct collapse_control *cc)
804 static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node,
807 *hpage = __alloc_pages(gfp, HPAGE_PMD_ORDER, node, nmask);
808 if (unlikely(!*hpage)) {
809 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
813 prep_transhuge_page(*hpage);
814 count_vm_event(THP_COLLAPSE_ALLOC);
819 * If mmap_lock temporarily dropped, revalidate vma
820 * before taking mmap_lock.
821 * Returns enum scan_result value.
824 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
826 struct vm_area_struct **vmap,
827 struct collapse_control *cc)
829 struct vm_area_struct *vma;
831 if (unlikely(hpage_collapse_test_exit(mm)))
832 return SCAN_ANY_PROCESS;
834 *vmap = vma = find_vma(mm, address);
836 return SCAN_VMA_NULL;
838 if (!transhuge_vma_suitable(vma, address))
839 return SCAN_ADDRESS_RANGE;
840 if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
842 return SCAN_VMA_CHECK;
844 * Anon VMA expected, the address may be unmapped then
845 * remapped to file after khugepaged reaquired the mmap_lock.
847 * hugepage_vma_check may return true for qualified file
850 if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
851 return SCAN_PAGE_ANON;
856 * See pmd_trans_unstable() for how the result may change out from
857 * underneath us, even if we hold mmap_lock in read.
859 static int find_pmd_or_thp_or_none(struct mm_struct *mm,
860 unsigned long address,
865 *pmd = mm_find_pmd(mm, address);
867 return SCAN_PMD_NULL;
869 pmde = pmdp_get_lockless(*pmd);
871 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
872 /* See comments in pmd_none_or_trans_huge_or_clear_bad() */
876 return SCAN_PMD_NONE;
877 if (!pmd_present(pmde))
878 return SCAN_PMD_NULL;
879 if (pmd_trans_huge(pmde))
880 return SCAN_PMD_MAPPED;
881 if (pmd_devmap(pmde))
882 return SCAN_PMD_NULL;
884 return SCAN_PMD_NULL;
888 static int check_pmd_still_valid(struct mm_struct *mm,
889 unsigned long address,
893 int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
895 if (result != SCAN_SUCCEED)
903 * Bring missing pages in from swap, to complete THP collapse.
904 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
906 * Called and returns without pte mapped or spinlocks held.
907 * Note that if false is returned, mmap_lock will be released.
910 static int __collapse_huge_page_swapin(struct mm_struct *mm,
911 struct vm_area_struct *vma,
912 unsigned long haddr, pmd_t *pmd,
917 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
919 for (address = haddr; address < end; address += PAGE_SIZE) {
920 struct vm_fault vmf = {
923 .pgoff = linear_page_index(vma, haddr),
924 .flags = FAULT_FLAG_ALLOW_RETRY,
928 vmf.pte = pte_offset_map(pmd, address);
929 vmf.orig_pte = *vmf.pte;
930 if (!is_swap_pte(vmf.orig_pte)) {
934 ret = do_swap_page(&vmf);
937 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
938 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
939 * we do not retry here and swap entry will remain in pagetable
940 * resulting in later failure.
942 if (ret & VM_FAULT_RETRY) {
943 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
944 /* Likely, but not guaranteed, that page lock failed */
945 return SCAN_PAGE_LOCK;
947 if (ret & VM_FAULT_ERROR) {
948 mmap_read_unlock(mm);
949 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
955 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
959 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
963 static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
964 struct collapse_control *cc)
966 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
968 int node = hpage_collapse_find_target_node(cc);
970 if (!hpage_collapse_alloc_page(hpage, gfp, node, &cc->alloc_nmask))
971 return SCAN_ALLOC_HUGE_PAGE_FAIL;
972 if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
973 return SCAN_CGROUP_CHARGE_FAIL;
974 count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
978 static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
979 int referenced, int unmapped,
980 struct collapse_control *cc)
982 LIST_HEAD(compound_pagelist);
987 spinlock_t *pmd_ptl, *pte_ptl;
988 int result = SCAN_FAIL;
989 struct vm_area_struct *vma;
990 struct mmu_notifier_range range;
992 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
995 * Before allocating the hugepage, release the mmap_lock read lock.
996 * The allocation can take potentially a long time if it involves
997 * sync compaction, and we do not need to hold the mmap_lock during
998 * that. We will recheck the vma after taking it again in write mode.
1000 mmap_read_unlock(mm);
1002 result = alloc_charge_hpage(&hpage, mm, cc);
1003 if (result != SCAN_SUCCEED)
1007 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1008 if (result != SCAN_SUCCEED) {
1009 mmap_read_unlock(mm);
1013 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1014 if (result != SCAN_SUCCEED) {
1015 mmap_read_unlock(mm);
1021 * __collapse_huge_page_swapin will return with mmap_lock
1022 * released when it fails. So we jump out_nolock directly in
1023 * that case. Continuing to collapse causes inconsistency.
1025 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1027 if (result != SCAN_SUCCEED)
1031 mmap_read_unlock(mm);
1033 * Prevent all access to pagetables with the exception of
1034 * gup_fast later handled by the ptep_clear_flush and the VM
1035 * handled by the anon_vma lock + PG_lock.
1037 mmap_write_lock(mm);
1038 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1039 if (result != SCAN_SUCCEED)
1041 /* check if the pmd is still valid */
1042 result = check_pmd_still_valid(mm, address, pmd);
1043 if (result != SCAN_SUCCEED)
1046 anon_vma_lock_write(vma->anon_vma);
1048 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
1049 address + HPAGE_PMD_SIZE);
1050 mmu_notifier_invalidate_range_start(&range);
1052 pte = pte_offset_map(pmd, address);
1053 pte_ptl = pte_lockptr(mm, pmd);
1055 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1057 * This removes any huge TLB entry from the CPU so we won't allow
1058 * huge and small TLB entries for the same virtual address to
1059 * avoid the risk of CPU bugs in that area.
1061 * Parallel fast GUP is fine since fast GUP will back off when
1062 * it detects PMD is changed.
1064 _pmd = pmdp_collapse_flush(vma, address, pmd);
1065 spin_unlock(pmd_ptl);
1066 mmu_notifier_invalidate_range_end(&range);
1067 tlb_remove_table_sync_one();
1070 result = __collapse_huge_page_isolate(vma, address, pte, cc,
1071 &compound_pagelist);
1072 spin_unlock(pte_ptl);
1074 if (unlikely(result != SCAN_SUCCEED)) {
1077 BUG_ON(!pmd_none(*pmd));
1079 * We can only use set_pmd_at when establishing
1080 * hugepmds and never for establishing regular pmds that
1081 * points to regular pagetables. Use pmd_populate for that
1083 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1084 spin_unlock(pmd_ptl);
1085 anon_vma_unlock_write(vma->anon_vma);
1090 * All pages are isolated and locked so anon_vma rmap
1091 * can't run anymore.
1093 anon_vma_unlock_write(vma->anon_vma);
1095 __collapse_huge_page_copy(pte, hpage, vma, address, pte_ptl,
1096 &compound_pagelist);
1099 * spin_lock() below is not the equivalent of smp_wmb(), but
1100 * the smp_wmb() inside __SetPageUptodate() can be reused to
1101 * avoid the copy_huge_page writes to become visible after
1102 * the set_pmd_at() write.
1104 __SetPageUptodate(hpage);
1105 pgtable = pmd_pgtable(_pmd);
1107 _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1108 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1111 BUG_ON(!pmd_none(*pmd));
1112 page_add_new_anon_rmap(hpage, vma, address);
1113 lru_cache_add_inactive_or_unevictable(hpage, vma);
1114 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1115 set_pmd_at(mm, address, pmd, _pmd);
1116 update_mmu_cache_pmd(vma, address, pmd);
1117 spin_unlock(pmd_ptl);
1121 result = SCAN_SUCCEED;
1123 mmap_write_unlock(mm);
1126 mem_cgroup_uncharge(page_folio(hpage));
1129 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1133 static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1134 struct vm_area_struct *vma,
1135 unsigned long address, bool *mmap_locked,
1136 struct collapse_control *cc)
1140 int result = SCAN_FAIL, referenced = 0;
1141 int none_or_zero = 0, shared = 0;
1142 struct page *page = NULL;
1143 unsigned long _address;
1145 int node = NUMA_NO_NODE, unmapped = 0;
1146 bool writable = false;
1148 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1150 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1151 if (result != SCAN_SUCCEED)
1154 memset(cc->node_load, 0, sizeof(cc->node_load));
1155 nodes_clear(cc->alloc_nmask);
1156 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1157 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1158 _pte++, _address += PAGE_SIZE) {
1159 pte_t pteval = *_pte;
1160 if (is_swap_pte(pteval)) {
1162 if (!cc->is_khugepaged ||
1163 unmapped <= khugepaged_max_ptes_swap) {
1165 * Always be strict with uffd-wp
1166 * enabled swap entries. Please see
1167 * comment below for pte_uffd_wp().
1169 if (pte_swp_uffd_wp(pteval)) {
1170 result = SCAN_PTE_UFFD_WP;
1175 result = SCAN_EXCEED_SWAP_PTE;
1176 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1180 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1182 if (!userfaultfd_armed(vma) &&
1183 (!cc->is_khugepaged ||
1184 none_or_zero <= khugepaged_max_ptes_none)) {
1187 result = SCAN_EXCEED_NONE_PTE;
1188 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1192 if (pte_uffd_wp(pteval)) {
1194 * Don't collapse the page if any of the small
1195 * PTEs are armed with uffd write protection.
1196 * Here we can also mark the new huge pmd as
1197 * write protected if any of the small ones is
1198 * marked but that could bring unknown
1199 * userfault messages that falls outside of
1200 * the registered range. So, just be simple.
1202 result = SCAN_PTE_UFFD_WP;
1205 if (pte_write(pteval))
1208 page = vm_normal_page(vma, _address, pteval);
1209 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1210 result = SCAN_PAGE_NULL;
1214 if (page_mapcount(page) > 1) {
1216 if (cc->is_khugepaged &&
1217 shared > khugepaged_max_ptes_shared) {
1218 result = SCAN_EXCEED_SHARED_PTE;
1219 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1224 page = compound_head(page);
1227 * Record which node the original page is from and save this
1228 * information to cc->node_load[].
1229 * Khugepaged will allocate hugepage from the node has the max
1232 node = page_to_nid(page);
1233 if (hpage_collapse_scan_abort(node, cc)) {
1234 result = SCAN_SCAN_ABORT;
1237 cc->node_load[node]++;
1238 if (!PageLRU(page)) {
1239 result = SCAN_PAGE_LRU;
1242 if (PageLocked(page)) {
1243 result = SCAN_PAGE_LOCK;
1246 if (!PageAnon(page)) {
1247 result = SCAN_PAGE_ANON;
1252 * Check if the page has any GUP (or other external) pins.
1254 * Here the check may be racy:
1255 * it may see total_mapcount > refcount in some cases?
1256 * But such case is ephemeral we could always retry collapse
1257 * later. However it may report false positive if the page
1258 * has excessive GUP pins (i.e. 512). Anyway the same check
1259 * will be done again later the risk seems low.
1261 if (!is_refcount_suitable(page)) {
1262 result = SCAN_PAGE_COUNT;
1267 * If collapse was initiated by khugepaged, check that there is
1268 * enough young pte to justify collapsing the page
1270 if (cc->is_khugepaged &&
1271 (pte_young(pteval) || page_is_young(page) ||
1272 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1277 result = SCAN_PAGE_RO;
1278 } else if (cc->is_khugepaged &&
1280 (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1281 result = SCAN_LACK_REFERENCED_PAGE;
1283 result = SCAN_SUCCEED;
1286 pte_unmap_unlock(pte, ptl);
1287 if (result == SCAN_SUCCEED) {
1288 result = collapse_huge_page(mm, address, referenced,
1290 /* collapse_huge_page will return with the mmap_lock released */
1291 *mmap_locked = false;
1294 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1295 none_or_zero, result, unmapped);
1299 static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1301 struct mm_slot *slot = &mm_slot->slot;
1302 struct mm_struct *mm = slot->mm;
1304 lockdep_assert_held(&khugepaged_mm_lock);
1306 if (hpage_collapse_test_exit(mm)) {
1308 hash_del(&slot->hash);
1309 list_del(&slot->mm_node);
1312 * Not strictly needed because the mm exited already.
1314 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1317 /* khugepaged_mm_lock actually not necessary for the below */
1318 mm_slot_free(mm_slot_cache, mm_slot);
1325 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1326 * khugepaged should try to collapse the page table.
1328 * Note that following race exists:
1329 * (1) khugepaged calls khugepaged_collapse_pte_mapped_thps() for mm_struct A,
1330 * emptying the A's ->pte_mapped_thp[] array.
1331 * (2) MADV_COLLAPSE collapses some file extent with target mm_struct B, and
1332 * retract_page_tables() finds a VMA in mm_struct A mapping the same extent
1333 * (at virtual address X) and adds an entry (for X) into mm_struct A's
1334 * ->pte-mapped_thp[] array.
1335 * (3) khugepaged calls khugepaged_collapse_scan_file() for mm_struct A at X,
1336 * sees a pte-mapped THP (SCAN_PTE_MAPPED_HUGEPAGE) and adds an entry
1337 * (for X) into mm_struct A's ->pte-mapped_thp[] array.
1338 * Thus, it's possible the same address is added multiple times for the same
1339 * mm_struct. Should this happen, we'll simply attempt
1340 * collapse_pte_mapped_thp() multiple times for the same address, under the same
1341 * exclusive mmap_lock, and assuming the first call is successful, subsequent
1342 * attempts will return quickly (without grabbing any additional locks) when
1343 * a huge pmd is found in find_pmd_or_thp_or_none(). Since this is a cheap
1344 * check, and since this is a rare occurrence, the cost of preventing this
1345 * "multiple-add" is thought to be more expensive than just handling it, should
1348 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1351 struct khugepaged_mm_slot *mm_slot;
1352 struct mm_slot *slot;
1355 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1357 spin_lock(&khugepaged_mm_lock);
1358 slot = mm_slot_lookup(mm_slots_hash, mm);
1359 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
1360 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) {
1361 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1364 spin_unlock(&khugepaged_mm_lock);
1368 /* hpage must be locked, and mmap_lock must be held in write */
1369 static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1370 pmd_t *pmdp, struct page *hpage)
1372 struct vm_fault vmf = {
1379 VM_BUG_ON(!PageTransHuge(hpage));
1380 mmap_assert_write_locked(vma->vm_mm);
1382 if (do_set_pmd(&vmf, hpage))
1386 return SCAN_SUCCEED;
1390 * A note about locking:
1391 * Trying to take the page table spinlocks would be useless here because those
1392 * are only used to synchronize:
1394 * - modifying terminal entries (ones that point to a data page, not to another
1396 * - installing *new* non-terminal entries
1398 * Instead, we need roughly the same kind of protection as free_pgtables() or
1399 * mm_take_all_locks() (but only for a single VMA):
1400 * The mmap lock together with this VMA's rmap locks covers all paths towards
1401 * the page table entries we're messing with here, except for hardware page
1402 * table walks and lockless_pages_from_mm().
1404 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1405 unsigned long addr, pmd_t *pmdp)
1408 struct mmu_notifier_range range;
1410 mmap_assert_write_locked(mm);
1412 lockdep_assert_held_write(&vma->vm_file->f_mapping->i_mmap_rwsem);
1414 * All anon_vmas attached to the VMA have the same root and are
1415 * therefore locked by the same lock.
1418 lockdep_assert_held_write(&vma->anon_vma->root->rwsem);
1420 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
1421 addr + HPAGE_PMD_SIZE);
1422 mmu_notifier_invalidate_range_start(&range);
1423 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1424 tlb_remove_table_sync_one();
1425 mmu_notifier_invalidate_range_end(&range);
1427 page_table_check_pte_clear_range(mm, addr, pmd);
1428 pte_free(mm, pmd_pgtable(pmd));
1432 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1435 * @mm: process address space where collapse happens
1436 * @addr: THP collapse address
1437 * @install_pmd: If a huge PMD should be installed
1439 * This function checks whether all the PTEs in the PMD are pointing to the
1440 * right THP. If so, retract the page table so the THP can refault in with
1441 * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1443 int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1446 unsigned long haddr = addr & HPAGE_PMD_MASK;
1447 struct vm_area_struct *vma = vma_lookup(mm, haddr);
1449 pte_t *start_pte, *pte;
1452 int count = 0, result = SCAN_FAIL;
1455 mmap_assert_write_locked(mm);
1457 /* Fast check before locking page if already PMD-mapped */
1458 result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1459 if (result == SCAN_PMD_MAPPED)
1462 if (!vma || !vma->vm_file ||
1463 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1464 return SCAN_VMA_CHECK;
1467 * If we are here, we've succeeded in replacing all the native pages
1468 * in the page cache with a single hugepage. If a mm were to fault-in
1469 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1470 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1471 * analogously elide sysfs THP settings here.
1473 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
1474 return SCAN_VMA_CHECK;
1476 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1477 if (userfaultfd_wp(vma))
1478 return SCAN_PTE_UFFD_WP;
1480 hpage = find_lock_page(vma->vm_file->f_mapping,
1481 linear_page_index(vma, haddr));
1483 return SCAN_PAGE_NULL;
1485 if (!PageHead(hpage)) {
1490 if (compound_order(hpage) != HPAGE_PMD_ORDER) {
1491 result = SCAN_PAGE_COMPOUND;
1500 * In MADV_COLLAPSE path, possible race with khugepaged where
1501 * all pte entries have been removed and pmd cleared. If so,
1502 * skip all the pte checks and just update the pmd mapping.
1504 goto maybe_install_pmd;
1510 * We need to lock the mapping so that from here on, only GUP-fast and
1511 * hardware page walks can access the parts of the page tables that
1512 * we're operating on.
1513 * See collapse_and_free_pmd().
1515 i_mmap_lock_write(vma->vm_file->f_mapping);
1518 * This spinlock should be unnecessary: Nobody else should be accessing
1519 * the page tables under spinlock protection here, only
1520 * lockless_pages_from_mm() and the hardware page walker can access page
1521 * tables while all the high-level locks are held in write mode.
1523 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1526 /* step 1: check all mapped PTEs are to the right huge page */
1527 for (i = 0, addr = haddr, pte = start_pte;
1528 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1531 /* empty pte, skip */
1535 /* page swapped out, abort */
1536 if (!pte_present(*pte)) {
1537 result = SCAN_PTE_NON_PRESENT;
1541 page = vm_normal_page(vma, addr, *pte);
1542 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1545 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1546 * page table, but the new page will not be a subpage of hpage.
1548 if (hpage + i != page)
1553 /* step 2: adjust rmap */
1554 for (i = 0, addr = haddr, pte = start_pte;
1555 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1560 page = vm_normal_page(vma, addr, *pte);
1561 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1563 page_remove_rmap(page, vma, false);
1566 pte_unmap_unlock(start_pte, ptl);
1568 /* step 3: set proper refcount and mm_counters. */
1570 page_ref_sub(hpage, count);
1571 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1574 /* step 4: remove pte entries */
1575 /* we make no change to anon, but protect concurrent anon page lookup */
1577 anon_vma_lock_write(vma->anon_vma);
1579 collapse_and_free_pmd(mm, vma, haddr, pmd);
1582 anon_vma_unlock_write(vma->anon_vma);
1583 i_mmap_unlock_write(vma->vm_file->f_mapping);
1586 /* step 5: install pmd entry */
1587 result = install_pmd
1588 ? set_huge_pmd(vma, haddr, pmd, hpage)
1597 pte_unmap_unlock(start_pte, ptl);
1598 i_mmap_unlock_write(vma->vm_file->f_mapping);
1602 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
1604 struct mm_slot *slot = &mm_slot->slot;
1605 struct mm_struct *mm = slot->mm;
1608 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1611 if (!mmap_write_trylock(mm))
1614 if (unlikely(hpage_collapse_test_exit(mm)))
1617 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1618 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i], false);
1621 mm_slot->nr_pte_mapped_thp = 0;
1622 mmap_write_unlock(mm);
1625 static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff,
1626 struct mm_struct *target_mm,
1627 unsigned long target_addr, struct page *hpage,
1628 struct collapse_control *cc)
1630 struct vm_area_struct *vma;
1631 int target_result = SCAN_FAIL;
1633 i_mmap_lock_write(mapping);
1634 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1635 int result = SCAN_FAIL;
1636 struct mm_struct *mm = NULL;
1637 unsigned long addr = 0;
1639 bool is_target = false;
1642 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1643 * got written to. These VMAs are likely not worth investing
1644 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1647 * Note that vma->anon_vma check is racy: it can be set up after
1648 * the check but before we took mmap_lock by the fault path.
1649 * But page lock would prevent establishing any new ptes of the
1650 * page, so we are safe.
1652 * An alternative would be drop the check, but check that page
1653 * table is clear before calling pmdp_collapse_flush() under
1654 * ptl. It has higher chance to recover THP for the VMA, but
1655 * has higher cost too. It would also probably require locking
1658 if (READ_ONCE(vma->anon_vma)) {
1659 result = SCAN_PAGE_ANON;
1662 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1663 if (addr & ~HPAGE_PMD_MASK ||
1664 vma->vm_end < addr + HPAGE_PMD_SIZE) {
1665 result = SCAN_VMA_CHECK;
1669 is_target = mm == target_mm && addr == target_addr;
1670 result = find_pmd_or_thp_or_none(mm, addr, &pmd);
1671 if (result != SCAN_SUCCEED)
1674 * We need exclusive mmap_lock to retract page table.
1676 * We use trylock due to lock inversion: we need to acquire
1677 * mmap_lock while holding page lock. Fault path does it in
1678 * reverse order. Trylock is a way to avoid deadlock.
1680 * Also, it's not MADV_COLLAPSE's job to collapse other
1681 * mappings - let khugepaged take care of them later.
1683 result = SCAN_PTE_MAPPED_HUGEPAGE;
1684 if ((cc->is_khugepaged || is_target) &&
1685 mmap_write_trylock(mm)) {
1687 * Re-check whether we have an ->anon_vma, because
1688 * collapse_and_free_pmd() requires that either no
1689 * ->anon_vma exists or the anon_vma is locked.
1690 * We already checked ->anon_vma above, but that check
1691 * is racy because ->anon_vma can be populated under the
1692 * mmap lock in read mode.
1694 if (vma->anon_vma) {
1695 result = SCAN_PAGE_ANON;
1699 * When a vma is registered with uffd-wp, we can't
1700 * recycle the pmd pgtable because there can be pte
1701 * markers installed. Skip it only, so the rest mm/vma
1702 * can still have the same file mapped hugely, however
1703 * it'll always mapped in small page size for uffd-wp
1704 * registered ranges.
1706 if (hpage_collapse_test_exit(mm)) {
1707 result = SCAN_ANY_PROCESS;
1710 if (userfaultfd_wp(vma)) {
1711 result = SCAN_PTE_UFFD_WP;
1714 collapse_and_free_pmd(mm, vma, addr, pmd);
1715 if (!cc->is_khugepaged && is_target)
1716 result = set_huge_pmd(vma, addr, pmd, hpage);
1718 result = SCAN_SUCCEED;
1721 mmap_write_unlock(mm);
1725 * Calling context will handle target mm/addr. Otherwise, let
1726 * khugepaged try again later.
1729 khugepaged_add_pte_mapped_thp(mm, addr);
1734 target_result = result;
1736 i_mmap_unlock_write(mapping);
1737 return target_result;
1741 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1743 * @mm: process address space where collapse happens
1744 * @addr: virtual collapse start address
1745 * @file: file that collapse on
1746 * @start: collapse start address
1747 * @cc: collapse context and scratchpad
1749 * Basic scheme is simple, details are more complex:
1750 * - allocate and lock a new huge page;
1751 * - scan page cache replacing old pages with the new one
1752 * + swap/gup in pages if necessary;
1754 * + keep old pages around in case rollback is required;
1755 * - if replacing succeeds:
1758 * + unlock huge page;
1759 * - if replacing failed;
1760 * + put all pages back and unfreeze them;
1761 * + restore gaps in the page cache;
1762 * + unlock and free huge page;
1764 static int collapse_file(struct mm_struct *mm, unsigned long addr,
1765 struct file *file, pgoff_t start,
1766 struct collapse_control *cc)
1768 struct address_space *mapping = file->f_mapping;
1770 pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1771 LIST_HEAD(pagelist);
1772 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1773 int nr_none = 0, result = SCAN_SUCCEED;
1774 bool is_shmem = shmem_file(file);
1777 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1778 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1780 result = alloc_charge_hpage(&hpage, mm, cc);
1781 if (result != SCAN_SUCCEED)
1785 * Ensure we have slots for all the pages in the range. This is
1786 * almost certainly a no-op because most of the pages must be present
1790 xas_create_range(&xas);
1791 if (!xas_error(&xas))
1793 xas_unlock_irq(&xas);
1794 if (!xas_nomem(&xas, GFP_KERNEL)) {
1800 __SetPageLocked(hpage);
1802 __SetPageSwapBacked(hpage);
1803 hpage->index = start;
1804 hpage->mapping = mapping;
1807 * At this point the hpage is locked and not up-to-date.
1808 * It's safe to insert it into the page cache, because nobody would
1809 * be able to map it or use it in another way until we unlock it.
1812 xas_set(&xas, start);
1813 for (index = start; index < end; index++) {
1814 struct page *page = xas_next(&xas);
1815 struct folio *folio;
1817 VM_BUG_ON(index != xas.xa_index);
1821 * Stop if extent has been truncated or
1822 * hole-punched, and is now completely
1825 if (index == start) {
1826 if (!xas_next_entry(&xas, end - 1)) {
1827 result = SCAN_TRUNCATED;
1830 xas_set(&xas, index);
1832 if (!shmem_charge(mapping->host, 1)) {
1836 xas_store(&xas, hpage);
1841 if (xa_is_value(page) || !PageUptodate(page)) {
1842 xas_unlock_irq(&xas);
1843 /* swap in or instantiate fallocated page */
1844 if (shmem_get_folio(mapping->host, index,
1845 &folio, SGP_NOALLOC)) {
1849 page = folio_file_page(folio, index);
1850 } else if (trylock_page(page)) {
1852 xas_unlock_irq(&xas);
1854 result = SCAN_PAGE_LOCK;
1857 } else { /* !is_shmem */
1858 if (!page || xa_is_value(page)) {
1859 xas_unlock_irq(&xas);
1860 page_cache_sync_readahead(mapping, &file->f_ra,
1863 /* drain pagevecs to help isolate_lru_page() */
1865 page = find_lock_page(mapping, index);
1866 if (unlikely(page == NULL)) {
1870 } else if (PageDirty(page)) {
1872 * khugepaged only works on read-only fd,
1873 * so this page is dirty because it hasn't
1874 * been flushed since first write. There
1875 * won't be new dirty pages.
1877 * Trigger async flush here and hope the
1878 * writeback is done when khugepaged
1879 * revisits this page.
1881 * This is a one-off situation. We are not
1882 * forcing writeback in loop.
1884 xas_unlock_irq(&xas);
1885 filemap_flush(mapping);
1888 } else if (PageWriteback(page)) {
1889 xas_unlock_irq(&xas);
1892 } else if (trylock_page(page)) {
1894 xas_unlock_irq(&xas);
1896 result = SCAN_PAGE_LOCK;
1902 * The page must be locked, so we can drop the i_pages lock
1903 * without racing with truncate.
1905 VM_BUG_ON_PAGE(!PageLocked(page), page);
1907 /* make sure the page is up to date */
1908 if (unlikely(!PageUptodate(page))) {
1914 * If file was truncated then extended, or hole-punched, before
1915 * we locked the first page, then a THP might be there already.
1916 * This will be discovered on the first iteration.
1918 if (PageTransCompound(page)) {
1919 struct page *head = compound_head(page);
1921 result = compound_order(head) == HPAGE_PMD_ORDER &&
1922 head->index == start
1923 /* Maybe PMD-mapped */
1924 ? SCAN_PTE_MAPPED_HUGEPAGE
1925 : SCAN_PAGE_COMPOUND;
1929 folio = page_folio(page);
1931 if (folio_mapping(folio) != mapping) {
1932 result = SCAN_TRUNCATED;
1936 if (!is_shmem && (folio_test_dirty(folio) ||
1937 folio_test_writeback(folio))) {
1939 * khugepaged only works on read-only fd, so this
1940 * page is dirty because it hasn't been flushed
1941 * since first write.
1947 if (folio_isolate_lru(folio)) {
1948 result = SCAN_DEL_PAGE_LRU;
1952 if (folio_has_private(folio) &&
1953 !filemap_release_folio(folio, GFP_KERNEL)) {
1954 result = SCAN_PAGE_HAS_PRIVATE;
1955 folio_putback_lru(folio);
1959 if (folio_mapped(folio))
1961 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1964 xas_set(&xas, index);
1966 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1969 * The page is expected to have page_count() == 3:
1970 * - we hold a pin on it;
1971 * - one reference from page cache;
1972 * - one from isolate_lru_page;
1974 if (!page_ref_freeze(page, 3)) {
1975 result = SCAN_PAGE_COUNT;
1976 xas_unlock_irq(&xas);
1977 putback_lru_page(page);
1982 * Add the page to the list to be able to undo the collapse if
1983 * something go wrong.
1985 list_add_tail(&page->lru, &pagelist);
1987 /* Finally, replace with the new page. */
1988 xas_store(&xas, hpage);
1995 nr = thp_nr_pages(hpage);
1998 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
2000 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
2001 filemap_nr_thps_inc(mapping);
2003 * Paired with smp_mb() in do_dentry_open() to ensure
2004 * i_writecount is up to date and the update to nr_thps is
2005 * visible. Ensures the page cache will be truncated if the
2006 * file is opened writable.
2009 if (inode_is_open_for_write(mapping->host)) {
2011 __mod_lruvec_page_state(hpage, NR_FILE_THPS, -nr);
2012 filemap_nr_thps_dec(mapping);
2018 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
2019 /* nr_none is always 0 for non-shmem. */
2020 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2023 /* Join all the small entries into a single multi-index entry */
2024 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2025 xas_store(&xas, hpage);
2027 xas_unlock_irq(&xas);
2031 * If collapse is successful, flush must be done now before copying.
2032 * If collapse is unsuccessful, does flush actually need to be done?
2033 * Do it anyway, to clear the state.
2035 try_to_unmap_flush();
2037 if (result == SCAN_SUCCEED) {
2038 struct page *page, *tmp;
2039 struct folio *folio;
2042 * Replacing old pages with new one has succeeded, now we
2043 * need to copy the content and free the old pages.
2046 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2047 while (index < page->index) {
2048 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2051 copy_highpage(hpage + (page->index % HPAGE_PMD_NR),
2053 list_del(&page->lru);
2054 page->mapping = NULL;
2055 page_ref_unfreeze(page, 1);
2056 ClearPageActive(page);
2057 ClearPageUnevictable(page);
2062 while (index < end) {
2063 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2067 folio = page_folio(hpage);
2068 folio_mark_uptodate(folio);
2069 folio_ref_add(folio, HPAGE_PMD_NR - 1);
2072 folio_mark_dirty(folio);
2073 folio_add_lru(folio);
2076 * Remove pte page tables, so we can re-fault the page as huge.
2078 result = retract_page_tables(mapping, start, mm, addr, hpage,
2085 /* Something went wrong: roll back page cache changes */
2088 mapping->nrpages -= nr_none;
2089 shmem_uncharge(mapping->host, nr_none);
2092 xas_set(&xas, start);
2093 xas_for_each(&xas, page, end - 1) {
2094 page = list_first_entry_or_null(&pagelist,
2096 if (!page || xas.xa_index < page->index) {
2100 /* Put holes back where they were */
2101 xas_store(&xas, NULL);
2105 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2107 /* Unfreeze the page. */
2108 list_del(&page->lru);
2109 page_ref_unfreeze(page, 2);
2110 xas_store(&xas, page);
2112 xas_unlock_irq(&xas);
2114 putback_lru_page(page);
2118 xas_unlock_irq(&xas);
2120 hpage->mapping = NULL;
2126 VM_BUG_ON(!list_empty(&pagelist));
2128 mem_cgroup_uncharge(page_folio(hpage));
2132 trace_mm_khugepaged_collapse_file(mm, hpage, index, is_shmem, addr, file, nr, result);
2136 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2137 struct file *file, pgoff_t start,
2138 struct collapse_control *cc)
2140 struct page *page = NULL;
2141 struct address_space *mapping = file->f_mapping;
2142 XA_STATE(xas, &mapping->i_pages, start);
2144 int node = NUMA_NO_NODE;
2145 int result = SCAN_SUCCEED;
2149 memset(cc->node_load, 0, sizeof(cc->node_load));
2150 nodes_clear(cc->alloc_nmask);
2152 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2153 if (xas_retry(&xas, page))
2156 if (xa_is_value(page)) {
2158 if (cc->is_khugepaged &&
2159 swap > khugepaged_max_ptes_swap) {
2160 result = SCAN_EXCEED_SWAP_PTE;
2161 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2168 * TODO: khugepaged should compact smaller compound pages
2169 * into a PMD sized page
2171 if (PageTransCompound(page)) {
2172 struct page *head = compound_head(page);
2174 result = compound_order(head) == HPAGE_PMD_ORDER &&
2175 head->index == start
2176 /* Maybe PMD-mapped */
2177 ? SCAN_PTE_MAPPED_HUGEPAGE
2178 : SCAN_PAGE_COMPOUND;
2180 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2181 * by the caller won't touch the page cache, and so
2182 * it's safe to skip LRU and refcount checks before
2188 node = page_to_nid(page);
2189 if (hpage_collapse_scan_abort(node, cc)) {
2190 result = SCAN_SCAN_ABORT;
2193 cc->node_load[node]++;
2195 if (!PageLRU(page)) {
2196 result = SCAN_PAGE_LRU;
2200 if (page_count(page) !=
2201 1 + page_mapcount(page) + page_has_private(page)) {
2202 result = SCAN_PAGE_COUNT;
2207 * We probably should check if the page is referenced here, but
2208 * nobody would transfer pte_young() to PageReferenced() for us.
2209 * And rmap walk here is just too costly...
2214 if (need_resched()) {
2221 if (result == SCAN_SUCCEED) {
2222 if (cc->is_khugepaged &&
2223 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2224 result = SCAN_EXCEED_NONE_PTE;
2225 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2227 result = collapse_file(mm, addr, file, start, cc);
2231 trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
2235 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2236 struct file *file, pgoff_t start,
2237 struct collapse_control *cc)
2242 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
2246 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
2253 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2254 struct collapse_control *cc)
2255 __releases(&khugepaged_mm_lock)
2256 __acquires(&khugepaged_mm_lock)
2258 struct vma_iterator vmi;
2259 struct khugepaged_mm_slot *mm_slot;
2260 struct mm_slot *slot;
2261 struct mm_struct *mm;
2262 struct vm_area_struct *vma;
2266 lockdep_assert_held(&khugepaged_mm_lock);
2267 *result = SCAN_FAIL;
2269 if (khugepaged_scan.mm_slot) {
2270 mm_slot = khugepaged_scan.mm_slot;
2271 slot = &mm_slot->slot;
2273 slot = list_entry(khugepaged_scan.mm_head.next,
2274 struct mm_slot, mm_node);
2275 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2276 khugepaged_scan.address = 0;
2277 khugepaged_scan.mm_slot = mm_slot;
2279 spin_unlock(&khugepaged_mm_lock);
2280 khugepaged_collapse_pte_mapped_thps(mm_slot);
2284 * Don't wait for semaphore (to avoid long wait times). Just move to
2285 * the next mm on the list.
2288 if (unlikely(!mmap_read_trylock(mm)))
2289 goto breakouterloop_mmap_lock;
2292 if (unlikely(hpage_collapse_test_exit(mm)))
2293 goto breakouterloop;
2295 vma_iter_init(&vmi, mm, khugepaged_scan.address);
2296 for_each_vma(vmi, vma) {
2297 unsigned long hstart, hend;
2300 if (unlikely(hpage_collapse_test_exit(mm))) {
2304 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2309 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2310 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2311 if (khugepaged_scan.address > hend)
2313 if (khugepaged_scan.address < hstart)
2314 khugepaged_scan.address = hstart;
2315 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2317 while (khugepaged_scan.address < hend) {
2318 bool mmap_locked = true;
2321 if (unlikely(hpage_collapse_test_exit(mm)))
2322 goto breakouterloop;
2324 VM_BUG_ON(khugepaged_scan.address < hstart ||
2325 khugepaged_scan.address + HPAGE_PMD_SIZE >
2327 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2328 struct file *file = get_file(vma->vm_file);
2329 pgoff_t pgoff = linear_page_index(vma,
2330 khugepaged_scan.address);
2332 mmap_read_unlock(mm);
2333 *result = hpage_collapse_scan_file(mm,
2334 khugepaged_scan.address,
2336 mmap_locked = false;
2339 *result = hpage_collapse_scan_pmd(mm, vma,
2340 khugepaged_scan.address,
2345 case SCAN_PTE_MAPPED_HUGEPAGE: {
2348 *result = find_pmd_or_thp_or_none(mm,
2349 khugepaged_scan.address,
2351 if (*result != SCAN_SUCCEED)
2353 if (!khugepaged_add_pte_mapped_thp(mm,
2354 khugepaged_scan.address))
2358 ++khugepaged_pages_collapsed;
2364 /* move to next address */
2365 khugepaged_scan.address += HPAGE_PMD_SIZE;
2366 progress += HPAGE_PMD_NR;
2369 * We released mmap_lock so break loop. Note
2370 * that we drop mmap_lock before all hugepage
2371 * allocations, so if allocation fails, we are
2372 * guaranteed to break here and report the
2373 * correct result back to caller.
2375 goto breakouterloop_mmap_lock;
2376 if (progress >= pages)
2377 goto breakouterloop;
2381 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2382 breakouterloop_mmap_lock:
2384 spin_lock(&khugepaged_mm_lock);
2385 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2387 * Release the current mm_slot if this mm is about to die, or
2388 * if we scanned all vmas of this mm.
2390 if (hpage_collapse_test_exit(mm) || !vma) {
2392 * Make sure that if mm_users is reaching zero while
2393 * khugepaged runs here, khugepaged_exit will find
2394 * mm_slot not pointing to the exiting mm.
2396 if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2397 slot = list_entry(slot->mm_node.next,
2398 struct mm_slot, mm_node);
2399 khugepaged_scan.mm_slot =
2400 mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2401 khugepaged_scan.address = 0;
2403 khugepaged_scan.mm_slot = NULL;
2404 khugepaged_full_scans++;
2407 collect_mm_slot(mm_slot);
2413 static int khugepaged_has_work(void)
2415 return !list_empty(&khugepaged_scan.mm_head) &&
2416 hugepage_flags_enabled();
2419 static int khugepaged_wait_event(void)
2421 return !list_empty(&khugepaged_scan.mm_head) ||
2422 kthread_should_stop();
2425 static void khugepaged_do_scan(struct collapse_control *cc)
2427 unsigned int progress = 0, pass_through_head = 0;
2428 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2430 int result = SCAN_SUCCEED;
2432 lru_add_drain_all();
2437 if (unlikely(kthread_should_stop() || try_to_freeze()))
2440 spin_lock(&khugepaged_mm_lock);
2441 if (!khugepaged_scan.mm_slot)
2442 pass_through_head++;
2443 if (khugepaged_has_work() &&
2444 pass_through_head < 2)
2445 progress += khugepaged_scan_mm_slot(pages - progress,
2449 spin_unlock(&khugepaged_mm_lock);
2451 if (progress >= pages)
2454 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2456 * If fail to allocate the first time, try to sleep for
2457 * a while. When hit again, cancel the scan.
2462 khugepaged_alloc_sleep();
2467 static bool khugepaged_should_wakeup(void)
2469 return kthread_should_stop() ||
2470 time_after_eq(jiffies, khugepaged_sleep_expire);
2473 static void khugepaged_wait_work(void)
2475 if (khugepaged_has_work()) {
2476 const unsigned long scan_sleep_jiffies =
2477 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2479 if (!scan_sleep_jiffies)
2482 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2483 wait_event_freezable_timeout(khugepaged_wait,
2484 khugepaged_should_wakeup(),
2485 scan_sleep_jiffies);
2489 if (hugepage_flags_enabled())
2490 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2493 static int khugepaged(void *none)
2495 struct khugepaged_mm_slot *mm_slot;
2498 set_user_nice(current, MAX_NICE);
2500 while (!kthread_should_stop()) {
2501 khugepaged_do_scan(&khugepaged_collapse_control);
2502 khugepaged_wait_work();
2505 spin_lock(&khugepaged_mm_lock);
2506 mm_slot = khugepaged_scan.mm_slot;
2507 khugepaged_scan.mm_slot = NULL;
2509 collect_mm_slot(mm_slot);
2510 spin_unlock(&khugepaged_mm_lock);
2514 static void set_recommended_min_free_kbytes(void)
2518 unsigned long recommended_min;
2520 if (!hugepage_flags_enabled()) {
2521 calculate_min_free_kbytes();
2525 for_each_populated_zone(zone) {
2527 * We don't need to worry about fragmentation of
2528 * ZONE_MOVABLE since it only has movable pages.
2530 if (zone_idx(zone) > gfp_zone(GFP_USER))
2536 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2537 recommended_min = pageblock_nr_pages * nr_zones * 2;
2540 * Make sure that on average at least two pageblocks are almost free
2541 * of another type, one for a migratetype to fall back to and a
2542 * second to avoid subsequent fallbacks of other types There are 3
2543 * MIGRATE_TYPES we care about.
2545 recommended_min += pageblock_nr_pages * nr_zones *
2546 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2548 /* don't ever allow to reserve more than 5% of the lowmem */
2549 recommended_min = min(recommended_min,
2550 (unsigned long) nr_free_buffer_pages() / 20);
2551 recommended_min <<= (PAGE_SHIFT-10);
2553 if (recommended_min > min_free_kbytes) {
2554 if (user_min_free_kbytes >= 0)
2555 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2556 min_free_kbytes, recommended_min);
2558 min_free_kbytes = recommended_min;
2562 setup_per_zone_wmarks();
2565 int start_stop_khugepaged(void)
2569 mutex_lock(&khugepaged_mutex);
2570 if (hugepage_flags_enabled()) {
2571 if (!khugepaged_thread)
2572 khugepaged_thread = kthread_run(khugepaged, NULL,
2574 if (IS_ERR(khugepaged_thread)) {
2575 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2576 err = PTR_ERR(khugepaged_thread);
2577 khugepaged_thread = NULL;
2581 if (!list_empty(&khugepaged_scan.mm_head))
2582 wake_up_interruptible(&khugepaged_wait);
2583 } else if (khugepaged_thread) {
2584 kthread_stop(khugepaged_thread);
2585 khugepaged_thread = NULL;
2587 set_recommended_min_free_kbytes();
2589 mutex_unlock(&khugepaged_mutex);
2593 void khugepaged_min_free_kbytes_update(void)
2595 mutex_lock(&khugepaged_mutex);
2596 if (hugepage_flags_enabled() && khugepaged_thread)
2597 set_recommended_min_free_kbytes();
2598 mutex_unlock(&khugepaged_mutex);
2601 bool current_is_khugepaged(void)
2603 return kthread_func(current) == khugepaged;
2606 static int madvise_collapse_errno(enum scan_result r)
2609 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2610 * actionable feedback to caller, so they may take an appropriate
2611 * fallback measure depending on the nature of the failure.
2614 case SCAN_ALLOC_HUGE_PAGE_FAIL:
2616 case SCAN_CGROUP_CHARGE_FAIL:
2618 /* Resource temporary unavailable - trying again might succeed */
2619 case SCAN_PAGE_LOCK:
2621 case SCAN_DEL_PAGE_LRU:
2624 * Other: Trying again likely not to succeed / error intrinsic to
2625 * specified memory range. khugepaged likely won't be able to collapse
2633 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2634 unsigned long start, unsigned long end)
2636 struct collapse_control *cc;
2637 struct mm_struct *mm = vma->vm_mm;
2638 unsigned long hstart, hend, addr;
2639 int thps = 0, last_fail = SCAN_FAIL;
2640 bool mmap_locked = true;
2642 BUG_ON(vma->vm_start > start);
2643 BUG_ON(vma->vm_end < end);
2647 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2650 cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2653 cc->is_khugepaged = false;
2656 lru_add_drain_all();
2658 hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2659 hend = end & HPAGE_PMD_MASK;
2661 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2662 int result = SCAN_FAIL;
2668 result = hugepage_vma_revalidate(mm, addr, false, &vma,
2670 if (result != SCAN_SUCCEED) {
2675 hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
2677 mmap_assert_locked(mm);
2678 memset(cc->node_load, 0, sizeof(cc->node_load));
2679 nodes_clear(cc->alloc_nmask);
2680 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2681 struct file *file = get_file(vma->vm_file);
2682 pgoff_t pgoff = linear_page_index(vma, addr);
2684 mmap_read_unlock(mm);
2685 mmap_locked = false;
2686 result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2690 result = hpage_collapse_scan_pmd(mm, vma, addr,
2694 *prev = NULL; /* Tell caller we dropped mmap_lock */
2699 case SCAN_PMD_MAPPED:
2702 case SCAN_PTE_MAPPED_HUGEPAGE:
2703 BUG_ON(mmap_locked);
2705 mmap_write_lock(mm);
2706 result = collapse_pte_mapped_thp(mm, addr, true);
2707 mmap_write_unlock(mm);
2709 /* Whitelisted set of results where continuing OK */
2711 case SCAN_PTE_NON_PRESENT:
2712 case SCAN_PTE_UFFD_WP:
2714 case SCAN_LACK_REFERENCED_PAGE:
2715 case SCAN_PAGE_NULL:
2716 case SCAN_PAGE_COUNT:
2717 case SCAN_PAGE_LOCK:
2718 case SCAN_PAGE_COMPOUND:
2720 case SCAN_DEL_PAGE_LRU:
2725 /* Other error, exit */
2731 /* Caller expects us to hold mmap_lock on return */
2735 mmap_assert_locked(mm);
2739 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2740 : madvise_collapse_errno(last_fail);