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,
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/huge_memory.h>
66 static struct task_struct *khugepaged_thread __read_mostly;
67 static DEFINE_MUTEX(khugepaged_mutex);
69 /* default scan 8*512 pte (or vmas) every 30 second */
70 static unsigned int khugepaged_pages_to_scan __read_mostly;
71 static unsigned int khugepaged_pages_collapsed;
72 static unsigned int khugepaged_full_scans;
73 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
74 /* during fragmentation poll the hugepage allocator once every minute */
75 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
76 static unsigned long khugepaged_sleep_expire;
77 static DEFINE_SPINLOCK(khugepaged_mm_lock);
78 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
80 * default collapse hugepages if there is at least one pte mapped like
81 * it would have happened if the vma was large enough during page
84 * Note that these are only respected if collapse was initiated by khugepaged.
86 static unsigned int khugepaged_max_ptes_none __read_mostly;
87 static unsigned int khugepaged_max_ptes_swap __read_mostly;
88 static unsigned int khugepaged_max_ptes_shared __read_mostly;
90 #define MM_SLOTS_HASH_BITS 10
91 static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
93 static struct kmem_cache *mm_slot_cache __read_mostly;
95 #define MAX_PTE_MAPPED_THP 8
97 struct collapse_control {
100 /* Num pages scanned per node */
101 u32 node_load[MAX_NUMNODES];
103 /* nodemask for allocation fallback */
104 nodemask_t alloc_nmask;
108 * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
109 * @slot: hash lookup from mm to mm_slot
110 * @nr_pte_mapped_thp: number of pte mapped THP
111 * @pte_mapped_thp: address array corresponding pte mapped THP
113 struct khugepaged_mm_slot {
116 /* pte-mapped THP in this mm */
117 int nr_pte_mapped_thp;
118 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
122 * struct khugepaged_scan - cursor for scanning
123 * @mm_head: the head of the mm list to scan
124 * @mm_slot: the current mm_slot we are scanning
125 * @address: the next address inside that to be scanned
127 * There is only the one khugepaged_scan instance of this cursor structure.
129 struct khugepaged_scan {
130 struct list_head mm_head;
131 struct khugepaged_mm_slot *mm_slot;
132 unsigned long address;
135 static struct khugepaged_scan khugepaged_scan = {
136 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
140 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
141 struct kobj_attribute *attr,
144 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
147 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
148 struct kobj_attribute *attr,
149 const char *buf, size_t count)
154 err = kstrtouint(buf, 10, &msecs);
158 khugepaged_scan_sleep_millisecs = msecs;
159 khugepaged_sleep_expire = 0;
160 wake_up_interruptible(&khugepaged_wait);
164 static struct kobj_attribute scan_sleep_millisecs_attr =
165 __ATTR_RW(scan_sleep_millisecs);
167 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
168 struct kobj_attribute *attr,
171 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
174 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
175 struct kobj_attribute *attr,
176 const char *buf, size_t count)
181 err = kstrtouint(buf, 10, &msecs);
185 khugepaged_alloc_sleep_millisecs = msecs;
186 khugepaged_sleep_expire = 0;
187 wake_up_interruptible(&khugepaged_wait);
191 static struct kobj_attribute alloc_sleep_millisecs_attr =
192 __ATTR_RW(alloc_sleep_millisecs);
194 static ssize_t pages_to_scan_show(struct kobject *kobj,
195 struct kobj_attribute *attr,
198 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
200 static ssize_t pages_to_scan_store(struct kobject *kobj,
201 struct kobj_attribute *attr,
202 const char *buf, size_t count)
207 err = kstrtouint(buf, 10, &pages);
211 khugepaged_pages_to_scan = pages;
215 static struct kobj_attribute pages_to_scan_attr =
216 __ATTR_RW(pages_to_scan);
218 static ssize_t pages_collapsed_show(struct kobject *kobj,
219 struct kobj_attribute *attr,
222 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
224 static struct kobj_attribute pages_collapsed_attr =
225 __ATTR_RO(pages_collapsed);
227 static ssize_t full_scans_show(struct kobject *kobj,
228 struct kobj_attribute *attr,
231 return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
233 static struct kobj_attribute full_scans_attr =
234 __ATTR_RO(full_scans);
236 static ssize_t defrag_show(struct kobject *kobj,
237 struct kobj_attribute *attr, char *buf)
239 return single_hugepage_flag_show(kobj, attr, buf,
240 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
242 static ssize_t defrag_store(struct kobject *kobj,
243 struct kobj_attribute *attr,
244 const char *buf, size_t count)
246 return single_hugepage_flag_store(kobj, attr, buf, count,
247 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
249 static struct kobj_attribute khugepaged_defrag_attr =
253 * max_ptes_none controls if khugepaged should collapse hugepages over
254 * any unmapped ptes in turn potentially increasing the memory
255 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
256 * reduce the available free memory in the system as it
257 * runs. Increasing max_ptes_none will instead potentially reduce the
258 * free memory in the system during the khugepaged scan.
260 static ssize_t max_ptes_none_show(struct kobject *kobj,
261 struct kobj_attribute *attr,
264 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
266 static ssize_t max_ptes_none_store(struct kobject *kobj,
267 struct kobj_attribute *attr,
268 const char *buf, size_t count)
271 unsigned long max_ptes_none;
273 err = kstrtoul(buf, 10, &max_ptes_none);
274 if (err || max_ptes_none > HPAGE_PMD_NR - 1)
277 khugepaged_max_ptes_none = max_ptes_none;
281 static struct kobj_attribute khugepaged_max_ptes_none_attr =
282 __ATTR_RW(max_ptes_none);
284 static ssize_t max_ptes_swap_show(struct kobject *kobj,
285 struct kobj_attribute *attr,
288 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
291 static ssize_t max_ptes_swap_store(struct kobject *kobj,
292 struct kobj_attribute *attr,
293 const char *buf, size_t count)
296 unsigned long max_ptes_swap;
298 err = kstrtoul(buf, 10, &max_ptes_swap);
299 if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
302 khugepaged_max_ptes_swap = max_ptes_swap;
307 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
308 __ATTR_RW(max_ptes_swap);
310 static ssize_t max_ptes_shared_show(struct kobject *kobj,
311 struct kobj_attribute *attr,
314 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
317 static ssize_t max_ptes_shared_store(struct kobject *kobj,
318 struct kobj_attribute *attr,
319 const char *buf, size_t count)
322 unsigned long max_ptes_shared;
324 err = kstrtoul(buf, 10, &max_ptes_shared);
325 if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
328 khugepaged_max_ptes_shared = max_ptes_shared;
333 static struct kobj_attribute khugepaged_max_ptes_shared_attr =
334 __ATTR_RW(max_ptes_shared);
336 static struct attribute *khugepaged_attr[] = {
337 &khugepaged_defrag_attr.attr,
338 &khugepaged_max_ptes_none_attr.attr,
339 &khugepaged_max_ptes_swap_attr.attr,
340 &khugepaged_max_ptes_shared_attr.attr,
341 &pages_to_scan_attr.attr,
342 &pages_collapsed_attr.attr,
343 &full_scans_attr.attr,
344 &scan_sleep_millisecs_attr.attr,
345 &alloc_sleep_millisecs_attr.attr,
349 struct attribute_group khugepaged_attr_group = {
350 .attrs = khugepaged_attr,
351 .name = "khugepaged",
353 #endif /* CONFIG_SYSFS */
355 int hugepage_madvise(struct vm_area_struct *vma,
356 unsigned long *vm_flags, int advice)
362 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
363 * can't handle this properly after s390_enable_sie, so we simply
364 * ignore the madvise to prevent qemu from causing a SIGSEGV.
366 if (mm_has_pgste(vma->vm_mm))
369 *vm_flags &= ~VM_NOHUGEPAGE;
370 *vm_flags |= VM_HUGEPAGE;
372 * If the vma become good for khugepaged to scan,
373 * register it here without waiting a page fault that
374 * may not happen any time soon.
376 khugepaged_enter_vma(vma, *vm_flags);
378 case MADV_NOHUGEPAGE:
379 *vm_flags &= ~VM_HUGEPAGE;
380 *vm_flags |= VM_NOHUGEPAGE;
382 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
383 * this vma even if we leave the mm registered in khugepaged if
384 * it got registered before VM_NOHUGEPAGE was set.
392 int __init khugepaged_init(void)
394 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
395 sizeof(struct khugepaged_mm_slot),
396 __alignof__(struct khugepaged_mm_slot),
401 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
402 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
403 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
404 khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
409 void __init khugepaged_destroy(void)
411 kmem_cache_destroy(mm_slot_cache);
414 static inline int hpage_collapse_test_exit(struct mm_struct *mm)
416 return atomic_read(&mm->mm_users) == 0;
419 void __khugepaged_enter(struct mm_struct *mm)
421 struct khugepaged_mm_slot *mm_slot;
422 struct mm_slot *slot;
425 /* __khugepaged_exit() must not run from under us */
426 VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
427 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags)))
430 mm_slot = mm_slot_alloc(mm_slot_cache);
434 slot = &mm_slot->slot;
436 spin_lock(&khugepaged_mm_lock);
437 mm_slot_insert(mm_slots_hash, mm, slot);
439 * Insert just behind the scanning cursor, to let the area settle
442 wakeup = list_empty(&khugepaged_scan.mm_head);
443 list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
444 spin_unlock(&khugepaged_mm_lock);
448 wake_up_interruptible(&khugepaged_wait);
451 void khugepaged_enter_vma(struct vm_area_struct *vma,
452 unsigned long vm_flags)
454 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
455 hugepage_flags_enabled()) {
456 if (hugepage_vma_check(vma, vm_flags, false, false, true))
457 __khugepaged_enter(vma->vm_mm);
461 void __khugepaged_exit(struct mm_struct *mm)
463 struct khugepaged_mm_slot *mm_slot;
464 struct mm_slot *slot;
467 spin_lock(&khugepaged_mm_lock);
468 slot = mm_slot_lookup(mm_slots_hash, mm);
469 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
470 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
471 hash_del(&slot->hash);
472 list_del(&slot->mm_node);
475 spin_unlock(&khugepaged_mm_lock);
478 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
479 mm_slot_free(mm_slot_cache, mm_slot);
481 } else if (mm_slot) {
483 * This is required to serialize against
484 * hpage_collapse_test_exit() (which is guaranteed to run
485 * under mmap sem read mode). Stop here (after we return all
486 * pagetables will be destroyed) until khugepaged has finished
487 * working on the pagetables under the mmap_lock.
490 mmap_write_unlock(mm);
494 static void release_pte_folio(struct folio *folio)
496 node_stat_mod_folio(folio,
497 NR_ISOLATED_ANON + folio_is_file_lru(folio),
498 -folio_nr_pages(folio));
500 folio_putback_lru(folio);
503 static void release_pte_page(struct page *page)
505 release_pte_folio(page_folio(page));
508 static void release_pte_pages(pte_t *pte, pte_t *_pte,
509 struct list_head *compound_pagelist)
511 struct folio *folio, *tmp;
513 while (--_pte >= pte) {
514 pte_t pteval = ptep_get(_pte);
517 if (pte_none(pteval))
519 pfn = pte_pfn(pteval);
520 if (is_zero_pfn(pfn))
522 folio = pfn_folio(pfn);
523 if (folio_test_large(folio))
525 release_pte_folio(folio);
528 list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
529 list_del(&folio->lru);
530 release_pte_folio(folio);
534 static bool is_refcount_suitable(struct page *page)
536 int expected_refcount;
538 expected_refcount = total_mapcount(page);
539 if (PageSwapCache(page))
540 expected_refcount += compound_nr(page);
542 return page_count(page) == expected_refcount;
545 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
546 unsigned long address,
548 struct collapse_control *cc,
549 struct list_head *compound_pagelist)
551 struct page *page = NULL;
553 int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
554 bool writable = false;
556 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
557 _pte++, address += PAGE_SIZE) {
558 pte_t pteval = ptep_get(_pte);
559 if (pte_none(pteval) || (pte_present(pteval) &&
560 is_zero_pfn(pte_pfn(pteval)))) {
562 if (!userfaultfd_armed(vma) &&
563 (!cc->is_khugepaged ||
564 none_or_zero <= khugepaged_max_ptes_none)) {
567 result = SCAN_EXCEED_NONE_PTE;
568 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
572 if (!pte_present(pteval)) {
573 result = SCAN_PTE_NON_PRESENT;
576 if (pte_uffd_wp(pteval)) {
577 result = SCAN_PTE_UFFD_WP;
580 page = vm_normal_page(vma, address, pteval);
581 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
582 result = SCAN_PAGE_NULL;
586 VM_BUG_ON_PAGE(!PageAnon(page), page);
588 if (page_mapcount(page) > 1) {
590 if (cc->is_khugepaged &&
591 shared > khugepaged_max_ptes_shared) {
592 result = SCAN_EXCEED_SHARED_PTE;
593 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
598 if (PageCompound(page)) {
600 page = compound_head(page);
603 * Check if we have dealt with the compound page
606 list_for_each_entry(p, compound_pagelist, lru) {
613 * We can do it before isolate_lru_page because the
614 * page can't be freed from under us. NOTE: PG_lock
615 * is needed to serialize against split_huge_page
616 * when invoked from the VM.
618 if (!trylock_page(page)) {
619 result = SCAN_PAGE_LOCK;
624 * Check if the page has any GUP (or other external) pins.
626 * The page table that maps the page has been already unlinked
627 * from the page table tree and this process cannot get
628 * an additional pin on the page.
630 * New pins can come later if the page is shared across fork,
631 * but not from this process. The other process cannot write to
632 * the page, only trigger CoW.
634 if (!is_refcount_suitable(page)) {
636 result = SCAN_PAGE_COUNT;
641 * Isolate the page to avoid collapsing an hugepage
642 * currently in use by the VM.
644 if (!isolate_lru_page(page)) {
646 result = SCAN_DEL_PAGE_LRU;
649 mod_node_page_state(page_pgdat(page),
650 NR_ISOLATED_ANON + page_is_file_lru(page),
652 VM_BUG_ON_PAGE(!PageLocked(page), page);
653 VM_BUG_ON_PAGE(PageLRU(page), page);
655 if (PageCompound(page))
656 list_add_tail(&page->lru, compound_pagelist);
659 * If collapse was initiated by khugepaged, check that there is
660 * enough young pte to justify collapsing the page
662 if (cc->is_khugepaged &&
663 (pte_young(pteval) || page_is_young(page) ||
664 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
668 if (pte_write(pteval))
672 if (unlikely(!writable)) {
673 result = SCAN_PAGE_RO;
674 } else if (unlikely(cc->is_khugepaged && !referenced)) {
675 result = SCAN_LACK_REFERENCED_PAGE;
677 result = SCAN_SUCCEED;
678 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
679 referenced, writable, result);
683 release_pte_pages(pte, _pte, compound_pagelist);
684 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
685 referenced, writable, result);
689 static void __collapse_huge_page_copy_succeeded(pte_t *pte,
690 struct vm_area_struct *vma,
691 unsigned long address,
693 struct list_head *compound_pagelist)
695 struct page *src_page;
700 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
701 _pte++, address += PAGE_SIZE) {
702 pteval = ptep_get(_pte);
703 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
704 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
705 if (is_zero_pfn(pte_pfn(pteval))) {
707 * ptl mostly unnecessary.
710 ptep_clear(vma->vm_mm, address, _pte);
714 src_page = pte_page(pteval);
715 if (!PageCompound(src_page))
716 release_pte_page(src_page);
718 * ptl mostly unnecessary, but preempt has to
719 * be disabled to update the per-cpu stats
720 * inside page_remove_rmap().
723 ptep_clear(vma->vm_mm, address, _pte);
724 page_remove_rmap(src_page, vma, false);
726 free_page_and_swap_cache(src_page);
730 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
731 list_del(&src_page->lru);
732 mod_node_page_state(page_pgdat(src_page),
733 NR_ISOLATED_ANON + page_is_file_lru(src_page),
734 -compound_nr(src_page));
735 unlock_page(src_page);
736 free_swap_cache(src_page);
737 putback_lru_page(src_page);
741 static void __collapse_huge_page_copy_failed(pte_t *pte,
744 struct vm_area_struct *vma,
745 struct list_head *compound_pagelist)
750 * Re-establish the PMD to point to the original page table
751 * entry. Restoring PMD needs to be done prior to releasing
752 * pages. Since pages are still isolated and locked here,
753 * acquiring anon_vma_lock_write is unnecessary.
755 pmd_ptl = pmd_lock(vma->vm_mm, pmd);
756 pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd));
757 spin_unlock(pmd_ptl);
759 * Release both raw and compound pages isolated
760 * in __collapse_huge_page_isolate.
762 release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist);
766 * __collapse_huge_page_copy - attempts to copy memory contents from raw
767 * pages to a hugepage. Cleans up the raw pages if copying succeeds;
768 * otherwise restores the original page table and releases isolated raw pages.
769 * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC.
771 * @pte: starting of the PTEs to copy from
772 * @page: the new hugepage to copy contents to
773 * @pmd: pointer to the new hugepage's PMD
774 * @orig_pmd: the original raw pages' PMD
775 * @vma: the original raw pages' virtual memory area
776 * @address: starting address to copy
777 * @ptl: lock on raw pages' PTEs
778 * @compound_pagelist: list that stores compound pages
780 static int __collapse_huge_page_copy(pte_t *pte,
784 struct vm_area_struct *vma,
785 unsigned long address,
787 struct list_head *compound_pagelist)
789 struct page *src_page;
792 unsigned long _address;
793 int result = SCAN_SUCCEED;
796 * Copying pages' contents is subject to memory poison at any iteration.
798 for (_pte = pte, _address = address; _pte < pte + HPAGE_PMD_NR;
799 _pte++, page++, _address += PAGE_SIZE) {
800 pteval = ptep_get(_pte);
801 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
802 clear_user_highpage(page, _address);
805 src_page = pte_page(pteval);
806 if (copy_mc_user_highpage(page, src_page, _address, vma) > 0) {
807 result = SCAN_COPY_MC;
812 if (likely(result == SCAN_SUCCEED))
813 __collapse_huge_page_copy_succeeded(pte, vma, address, ptl,
816 __collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma,
822 static void khugepaged_alloc_sleep(void)
826 add_wait_queue(&khugepaged_wait, &wait);
827 __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
828 schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
829 remove_wait_queue(&khugepaged_wait, &wait);
832 struct collapse_control khugepaged_collapse_control = {
833 .is_khugepaged = true,
836 static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
841 * If node_reclaim_mode is disabled, then no extra effort is made to
842 * allocate memory locally.
844 if (!node_reclaim_enabled())
847 /* If there is a count for this node already, it must be acceptable */
848 if (cc->node_load[nid])
851 for (i = 0; i < MAX_NUMNODES; i++) {
852 if (!cc->node_load[i])
854 if (node_distance(nid, i) > node_reclaim_distance)
860 #define khugepaged_defrag() \
861 (transparent_hugepage_flags & \
862 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
864 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
865 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
867 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
871 static int hpage_collapse_find_target_node(struct collapse_control *cc)
873 int nid, target_node = 0, max_value = 0;
875 /* find first node with max normal pages hit */
876 for (nid = 0; nid < MAX_NUMNODES; nid++)
877 if (cc->node_load[nid] > max_value) {
878 max_value = cc->node_load[nid];
882 for_each_online_node(nid) {
883 if (max_value == cc->node_load[nid])
884 node_set(nid, cc->alloc_nmask);
890 static int hpage_collapse_find_target_node(struct collapse_control *cc)
896 static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node,
899 *hpage = __alloc_pages(gfp, HPAGE_PMD_ORDER, node, nmask);
900 if (unlikely(!*hpage)) {
901 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
905 prep_transhuge_page(*hpage);
906 count_vm_event(THP_COLLAPSE_ALLOC);
911 * If mmap_lock temporarily dropped, revalidate vma
912 * before taking mmap_lock.
913 * Returns enum scan_result value.
916 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
918 struct vm_area_struct **vmap,
919 struct collapse_control *cc)
921 struct vm_area_struct *vma;
923 if (unlikely(hpage_collapse_test_exit(mm)))
924 return SCAN_ANY_PROCESS;
926 *vmap = vma = find_vma(mm, address);
928 return SCAN_VMA_NULL;
930 if (!transhuge_vma_suitable(vma, address))
931 return SCAN_ADDRESS_RANGE;
932 if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
934 return SCAN_VMA_CHECK;
936 * Anon VMA expected, the address may be unmapped then
937 * remapped to file after khugepaged reaquired the mmap_lock.
939 * hugepage_vma_check may return true for qualified file
942 if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
943 return SCAN_PAGE_ANON;
947 static int find_pmd_or_thp_or_none(struct mm_struct *mm,
948 unsigned long address,
953 *pmd = mm_find_pmd(mm, address);
955 return SCAN_PMD_NULL;
957 pmde = pmdp_get_lockless(*pmd);
959 return SCAN_PMD_NONE;
960 if (!pmd_present(pmde))
961 return SCAN_PMD_NULL;
962 if (pmd_trans_huge(pmde))
963 return SCAN_PMD_MAPPED;
964 if (pmd_devmap(pmde))
965 return SCAN_PMD_NULL;
967 return SCAN_PMD_NULL;
971 static int check_pmd_still_valid(struct mm_struct *mm,
972 unsigned long address,
976 int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
978 if (result != SCAN_SUCCEED)
986 * Bring missing pages in from swap, to complete THP collapse.
987 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
989 * Called and returns without pte mapped or spinlocks held.
990 * Returns result: if not SCAN_SUCCEED, mmap_lock has been released.
992 static int __collapse_huge_page_swapin(struct mm_struct *mm,
993 struct vm_area_struct *vma,
994 unsigned long haddr, pmd_t *pmd,
999 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
1004 for (address = haddr; address < end; address += PAGE_SIZE) {
1005 struct vm_fault vmf = {
1008 .pgoff = linear_page_index(vma, address),
1009 .flags = FAULT_FLAG_ALLOW_RETRY,
1014 pte = pte_offset_map_nolock(mm, pmd, address, &ptl);
1016 mmap_read_unlock(mm);
1017 result = SCAN_PMD_NULL;
1022 vmf.orig_pte = ptep_get_lockless(pte);
1023 if (!is_swap_pte(vmf.orig_pte))
1028 ret = do_swap_page(&vmf);
1029 /* Which unmaps pte (after perhaps re-checking the entry) */
1033 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
1034 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
1035 * we do not retry here and swap entry will remain in pagetable
1036 * resulting in later failure.
1038 if (ret & VM_FAULT_RETRY) {
1039 /* Likely, but not guaranteed, that page lock failed */
1040 result = SCAN_PAGE_LOCK;
1043 if (ret & VM_FAULT_ERROR) {
1044 mmap_read_unlock(mm);
1054 /* Drain LRU cache to remove extra pin on the swapped in pages */
1058 result = SCAN_SUCCEED;
1060 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, result);
1064 static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
1065 struct collapse_control *cc)
1067 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
1069 int node = hpage_collapse_find_target_node(cc);
1070 struct folio *folio;
1072 if (!hpage_collapse_alloc_page(hpage, gfp, node, &cc->alloc_nmask))
1073 return SCAN_ALLOC_HUGE_PAGE_FAIL;
1075 folio = page_folio(*hpage);
1076 if (unlikely(mem_cgroup_charge(folio, mm, gfp))) {
1079 return SCAN_CGROUP_CHARGE_FAIL;
1081 count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
1083 return SCAN_SUCCEED;
1086 static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
1087 int referenced, int unmapped,
1088 struct collapse_control *cc)
1090 LIST_HEAD(compound_pagelist);
1095 spinlock_t *pmd_ptl, *pte_ptl;
1096 int result = SCAN_FAIL;
1097 struct vm_area_struct *vma;
1098 struct mmu_notifier_range range;
1100 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1103 * Before allocating the hugepage, release the mmap_lock read lock.
1104 * The allocation can take potentially a long time if it involves
1105 * sync compaction, and we do not need to hold the mmap_lock during
1106 * that. We will recheck the vma after taking it again in write mode.
1108 mmap_read_unlock(mm);
1110 result = alloc_charge_hpage(&hpage, mm, cc);
1111 if (result != SCAN_SUCCEED)
1115 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1116 if (result != SCAN_SUCCEED) {
1117 mmap_read_unlock(mm);
1121 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1122 if (result != SCAN_SUCCEED) {
1123 mmap_read_unlock(mm);
1129 * __collapse_huge_page_swapin will return with mmap_lock
1130 * released when it fails. So we jump out_nolock directly in
1131 * that case. Continuing to collapse causes inconsistency.
1133 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1135 if (result != SCAN_SUCCEED)
1139 mmap_read_unlock(mm);
1141 * Prevent all access to pagetables with the exception of
1142 * gup_fast later handled by the ptep_clear_flush and the VM
1143 * handled by the anon_vma lock + PG_lock.
1145 mmap_write_lock(mm);
1146 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1147 if (result != SCAN_SUCCEED)
1149 /* check if the pmd is still valid */
1150 result = check_pmd_still_valid(mm, address, pmd);
1151 if (result != SCAN_SUCCEED)
1154 vma_start_write(vma);
1155 anon_vma_lock_write(vma->anon_vma);
1157 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
1158 address + HPAGE_PMD_SIZE);
1159 mmu_notifier_invalidate_range_start(&range);
1161 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1163 * This removes any huge TLB entry from the CPU so we won't allow
1164 * huge and small TLB entries for the same virtual address to
1165 * avoid the risk of CPU bugs in that area.
1167 * Parallel fast GUP is fine since fast GUP will back off when
1168 * it detects PMD is changed.
1170 _pmd = pmdp_collapse_flush(vma, address, pmd);
1171 spin_unlock(pmd_ptl);
1172 mmu_notifier_invalidate_range_end(&range);
1173 tlb_remove_table_sync_one();
1175 pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl);
1177 result = __collapse_huge_page_isolate(vma, address, pte, cc,
1178 &compound_pagelist);
1179 spin_unlock(pte_ptl);
1181 result = SCAN_PMD_NULL;
1184 if (unlikely(result != SCAN_SUCCEED)) {
1188 BUG_ON(!pmd_none(*pmd));
1190 * We can only use set_pmd_at when establishing
1191 * hugepmds and never for establishing regular pmds that
1192 * points to regular pagetables. Use pmd_populate for that
1194 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1195 spin_unlock(pmd_ptl);
1196 anon_vma_unlock_write(vma->anon_vma);
1201 * All pages are isolated and locked so anon_vma rmap
1202 * can't run anymore.
1204 anon_vma_unlock_write(vma->anon_vma);
1206 result = __collapse_huge_page_copy(pte, hpage, pmd, _pmd,
1207 vma, address, pte_ptl,
1208 &compound_pagelist);
1210 if (unlikely(result != SCAN_SUCCEED))
1214 * spin_lock() below is not the equivalent of smp_wmb(), but
1215 * the smp_wmb() inside __SetPageUptodate() can be reused to
1216 * avoid the copy_huge_page writes to become visible after
1217 * the set_pmd_at() write.
1219 __SetPageUptodate(hpage);
1220 pgtable = pmd_pgtable(_pmd);
1222 _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1223 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1226 BUG_ON(!pmd_none(*pmd));
1227 page_add_new_anon_rmap(hpage, vma, address);
1228 lru_cache_add_inactive_or_unevictable(hpage, vma);
1229 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1230 set_pmd_at(mm, address, pmd, _pmd);
1231 update_mmu_cache_pmd(vma, address, pmd);
1232 spin_unlock(pmd_ptl);
1236 result = SCAN_SUCCEED;
1238 mmap_write_unlock(mm);
1242 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1246 static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1247 struct vm_area_struct *vma,
1248 unsigned long address, bool *mmap_locked,
1249 struct collapse_control *cc)
1253 int result = SCAN_FAIL, referenced = 0;
1254 int none_or_zero = 0, shared = 0;
1255 struct page *page = NULL;
1256 unsigned long _address;
1258 int node = NUMA_NO_NODE, unmapped = 0;
1259 bool writable = false;
1261 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1263 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1264 if (result != SCAN_SUCCEED)
1267 memset(cc->node_load, 0, sizeof(cc->node_load));
1268 nodes_clear(cc->alloc_nmask);
1269 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1271 result = SCAN_PMD_NULL;
1275 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1276 _pte++, _address += PAGE_SIZE) {
1277 pte_t pteval = ptep_get(_pte);
1278 if (is_swap_pte(pteval)) {
1280 if (!cc->is_khugepaged ||
1281 unmapped <= khugepaged_max_ptes_swap) {
1283 * Always be strict with uffd-wp
1284 * enabled swap entries. Please see
1285 * comment below for pte_uffd_wp().
1287 if (pte_swp_uffd_wp_any(pteval)) {
1288 result = SCAN_PTE_UFFD_WP;
1293 result = SCAN_EXCEED_SWAP_PTE;
1294 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1298 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1300 if (!userfaultfd_armed(vma) &&
1301 (!cc->is_khugepaged ||
1302 none_or_zero <= khugepaged_max_ptes_none)) {
1305 result = SCAN_EXCEED_NONE_PTE;
1306 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1310 if (pte_uffd_wp(pteval)) {
1312 * Don't collapse the page if any of the small
1313 * PTEs are armed with uffd write protection.
1314 * Here we can also mark the new huge pmd as
1315 * write protected if any of the small ones is
1316 * marked but that could bring unknown
1317 * userfault messages that falls outside of
1318 * the registered range. So, just be simple.
1320 result = SCAN_PTE_UFFD_WP;
1323 if (pte_write(pteval))
1326 page = vm_normal_page(vma, _address, pteval);
1327 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1328 result = SCAN_PAGE_NULL;
1332 if (page_mapcount(page) > 1) {
1334 if (cc->is_khugepaged &&
1335 shared > khugepaged_max_ptes_shared) {
1336 result = SCAN_EXCEED_SHARED_PTE;
1337 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1342 page = compound_head(page);
1345 * Record which node the original page is from and save this
1346 * information to cc->node_load[].
1347 * Khugepaged will allocate hugepage from the node has the max
1350 node = page_to_nid(page);
1351 if (hpage_collapse_scan_abort(node, cc)) {
1352 result = SCAN_SCAN_ABORT;
1355 cc->node_load[node]++;
1356 if (!PageLRU(page)) {
1357 result = SCAN_PAGE_LRU;
1360 if (PageLocked(page)) {
1361 result = SCAN_PAGE_LOCK;
1364 if (!PageAnon(page)) {
1365 result = SCAN_PAGE_ANON;
1370 * Check if the page has any GUP (or other external) pins.
1372 * Here the check may be racy:
1373 * it may see total_mapcount > refcount in some cases?
1374 * But such case is ephemeral we could always retry collapse
1375 * later. However it may report false positive if the page
1376 * has excessive GUP pins (i.e. 512). Anyway the same check
1377 * will be done again later the risk seems low.
1379 if (!is_refcount_suitable(page)) {
1380 result = SCAN_PAGE_COUNT;
1385 * If collapse was initiated by khugepaged, check that there is
1386 * enough young pte to justify collapsing the page
1388 if (cc->is_khugepaged &&
1389 (pte_young(pteval) || page_is_young(page) ||
1390 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1395 result = SCAN_PAGE_RO;
1396 } else if (cc->is_khugepaged &&
1398 (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1399 result = SCAN_LACK_REFERENCED_PAGE;
1401 result = SCAN_SUCCEED;
1404 pte_unmap_unlock(pte, ptl);
1405 if (result == SCAN_SUCCEED) {
1406 result = collapse_huge_page(mm, address, referenced,
1408 /* collapse_huge_page will return with the mmap_lock released */
1409 *mmap_locked = false;
1412 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1413 none_or_zero, result, unmapped);
1417 static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1419 struct mm_slot *slot = &mm_slot->slot;
1420 struct mm_struct *mm = slot->mm;
1422 lockdep_assert_held(&khugepaged_mm_lock);
1424 if (hpage_collapse_test_exit(mm)) {
1426 hash_del(&slot->hash);
1427 list_del(&slot->mm_node);
1430 * Not strictly needed because the mm exited already.
1432 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1435 /* khugepaged_mm_lock actually not necessary for the below */
1436 mm_slot_free(mm_slot_cache, mm_slot);
1443 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1444 * khugepaged should try to collapse the page table.
1446 * Note that following race exists:
1447 * (1) khugepaged calls khugepaged_collapse_pte_mapped_thps() for mm_struct A,
1448 * emptying the A's ->pte_mapped_thp[] array.
1449 * (2) MADV_COLLAPSE collapses some file extent with target mm_struct B, and
1450 * retract_page_tables() finds a VMA in mm_struct A mapping the same extent
1451 * (at virtual address X) and adds an entry (for X) into mm_struct A's
1452 * ->pte-mapped_thp[] array.
1453 * (3) khugepaged calls khugepaged_collapse_scan_file() for mm_struct A at X,
1454 * sees a pte-mapped THP (SCAN_PTE_MAPPED_HUGEPAGE) and adds an entry
1455 * (for X) into mm_struct A's ->pte-mapped_thp[] array.
1456 * Thus, it's possible the same address is added multiple times for the same
1457 * mm_struct. Should this happen, we'll simply attempt
1458 * collapse_pte_mapped_thp() multiple times for the same address, under the same
1459 * exclusive mmap_lock, and assuming the first call is successful, subsequent
1460 * attempts will return quickly (without grabbing any additional locks) when
1461 * a huge pmd is found in find_pmd_or_thp_or_none(). Since this is a cheap
1462 * check, and since this is a rare occurrence, the cost of preventing this
1463 * "multiple-add" is thought to be more expensive than just handling it, should
1466 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1469 struct khugepaged_mm_slot *mm_slot;
1470 struct mm_slot *slot;
1473 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1475 spin_lock(&khugepaged_mm_lock);
1476 slot = mm_slot_lookup(mm_slots_hash, mm);
1477 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
1478 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) {
1479 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1482 spin_unlock(&khugepaged_mm_lock);
1486 /* hpage must be locked, and mmap_lock must be held in write */
1487 static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1488 pmd_t *pmdp, struct page *hpage)
1490 struct vm_fault vmf = {
1497 VM_BUG_ON(!PageTransHuge(hpage));
1498 mmap_assert_write_locked(vma->vm_mm);
1500 if (do_set_pmd(&vmf, hpage))
1504 return SCAN_SUCCEED;
1508 * A note about locking:
1509 * Trying to take the page table spinlocks would be useless here because those
1510 * are only used to synchronize:
1512 * - modifying terminal entries (ones that point to a data page, not to another
1514 * - installing *new* non-terminal entries
1516 * Instead, we need roughly the same kind of protection as free_pgtables() or
1517 * mm_take_all_locks() (but only for a single VMA):
1518 * The mmap lock together with this VMA's rmap locks covers all paths towards
1519 * the page table entries we're messing with here, except for hardware page
1520 * table walks and lockless_pages_from_mm().
1522 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1523 unsigned long addr, pmd_t *pmdp)
1526 struct mmu_notifier_range range;
1528 mmap_assert_write_locked(mm);
1530 lockdep_assert_held_write(&vma->vm_file->f_mapping->i_mmap_rwsem);
1532 * All anon_vmas attached to the VMA have the same root and are
1533 * therefore locked by the same lock.
1536 lockdep_assert_held_write(&vma->anon_vma->root->rwsem);
1538 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
1539 addr + HPAGE_PMD_SIZE);
1540 mmu_notifier_invalidate_range_start(&range);
1541 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1542 tlb_remove_table_sync_one();
1543 mmu_notifier_invalidate_range_end(&range);
1545 page_table_check_pte_clear_range(mm, addr, pmd);
1546 pte_free(mm, pmd_pgtable(pmd));
1550 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1553 * @mm: process address space where collapse happens
1554 * @addr: THP collapse address
1555 * @install_pmd: If a huge PMD should be installed
1557 * This function checks whether all the PTEs in the PMD are pointing to the
1558 * right THP. If so, retract the page table so the THP can refault in with
1559 * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1561 int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1564 unsigned long haddr = addr & HPAGE_PMD_MASK;
1565 struct vm_area_struct *vma = vma_lookup(mm, haddr);
1567 pte_t *start_pte, *pte;
1570 int count = 0, result = SCAN_FAIL;
1573 mmap_assert_write_locked(mm);
1575 /* Fast check before locking page if already PMD-mapped */
1576 result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1577 if (result == SCAN_PMD_MAPPED)
1580 if (!vma || !vma->vm_file ||
1581 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1582 return SCAN_VMA_CHECK;
1585 * If we are here, we've succeeded in replacing all the native pages
1586 * in the page cache with a single hugepage. If a mm were to fault-in
1587 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1588 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1589 * analogously elide sysfs THP settings here.
1591 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
1592 return SCAN_VMA_CHECK;
1594 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1595 if (userfaultfd_wp(vma))
1596 return SCAN_PTE_UFFD_WP;
1598 hpage = find_lock_page(vma->vm_file->f_mapping,
1599 linear_page_index(vma, haddr));
1601 return SCAN_PAGE_NULL;
1603 if (!PageHead(hpage)) {
1608 if (compound_order(hpage) != HPAGE_PMD_ORDER) {
1609 result = SCAN_PAGE_COMPOUND;
1618 * In MADV_COLLAPSE path, possible race with khugepaged where
1619 * all pte entries have been removed and pmd cleared. If so,
1620 * skip all the pte checks and just update the pmd mapping.
1622 goto maybe_install_pmd;
1627 /* Lock the vma before taking i_mmap and page table locks */
1628 vma_start_write(vma);
1631 * We need to lock the mapping so that from here on, only GUP-fast and
1632 * hardware page walks can access the parts of the page tables that
1633 * we're operating on.
1634 * See collapse_and_free_pmd().
1636 i_mmap_lock_write(vma->vm_file->f_mapping);
1639 * This spinlock should be unnecessary: Nobody else should be accessing
1640 * the page tables under spinlock protection here, only
1641 * lockless_pages_from_mm() and the hardware page walker can access page
1642 * tables while all the high-level locks are held in write mode.
1645 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1649 /* step 1: check all mapped PTEs are to the right huge page */
1650 for (i = 0, addr = haddr, pte = start_pte;
1651 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1653 pte_t ptent = ptep_get(pte);
1655 /* empty pte, skip */
1656 if (pte_none(ptent))
1659 /* page swapped out, abort */
1660 if (!pte_present(ptent)) {
1661 result = SCAN_PTE_NON_PRESENT;
1665 page = vm_normal_page(vma, addr, ptent);
1666 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1669 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1670 * page table, but the new page will not be a subpage of hpage.
1672 if (hpage + i != page)
1677 /* step 2: adjust rmap */
1678 for (i = 0, addr = haddr, pte = start_pte;
1679 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1681 pte_t ptent = ptep_get(pte);
1683 if (pte_none(ptent))
1685 page = vm_normal_page(vma, addr, ptent);
1686 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1688 page_remove_rmap(page, vma, false);
1691 pte_unmap_unlock(start_pte, ptl);
1693 /* step 3: set proper refcount and mm_counters. */
1695 page_ref_sub(hpage, count);
1696 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1699 /* step 4: remove pte entries */
1700 /* we make no change to anon, but protect concurrent anon page lookup */
1702 anon_vma_lock_write(vma->anon_vma);
1704 collapse_and_free_pmd(mm, vma, haddr, pmd);
1707 anon_vma_unlock_write(vma->anon_vma);
1708 i_mmap_unlock_write(vma->vm_file->f_mapping);
1711 /* step 5: install pmd entry */
1712 result = install_pmd
1713 ? set_huge_pmd(vma, haddr, pmd, hpage)
1722 pte_unmap_unlock(start_pte, ptl);
1724 i_mmap_unlock_write(vma->vm_file->f_mapping);
1728 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
1730 struct mm_slot *slot = &mm_slot->slot;
1731 struct mm_struct *mm = slot->mm;
1734 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1737 if (!mmap_write_trylock(mm))
1740 if (unlikely(hpage_collapse_test_exit(mm)))
1743 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1744 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i], false);
1747 mm_slot->nr_pte_mapped_thp = 0;
1748 mmap_write_unlock(mm);
1751 static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff,
1752 struct mm_struct *target_mm,
1753 unsigned long target_addr, struct page *hpage,
1754 struct collapse_control *cc)
1756 struct vm_area_struct *vma;
1757 int target_result = SCAN_FAIL;
1759 i_mmap_lock_write(mapping);
1760 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1761 int result = SCAN_FAIL;
1762 struct mm_struct *mm = NULL;
1763 unsigned long addr = 0;
1765 bool is_target = false;
1768 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1769 * got written to. These VMAs are likely not worth investing
1770 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1773 * Note that vma->anon_vma check is racy: it can be set up after
1774 * the check but before we took mmap_lock by the fault path.
1775 * But page lock would prevent establishing any new ptes of the
1776 * page, so we are safe.
1778 * An alternative would be drop the check, but check that page
1779 * table is clear before calling pmdp_collapse_flush() under
1780 * ptl. It has higher chance to recover THP for the VMA, but
1781 * has higher cost too. It would also probably require locking
1784 if (READ_ONCE(vma->anon_vma)) {
1785 result = SCAN_PAGE_ANON;
1788 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1789 if (addr & ~HPAGE_PMD_MASK ||
1790 vma->vm_end < addr + HPAGE_PMD_SIZE) {
1791 result = SCAN_VMA_CHECK;
1795 is_target = mm == target_mm && addr == target_addr;
1796 result = find_pmd_or_thp_or_none(mm, addr, &pmd);
1797 if (result != SCAN_SUCCEED)
1800 * We need exclusive mmap_lock to retract page table.
1802 * We use trylock due to lock inversion: we need to acquire
1803 * mmap_lock while holding page lock. Fault path does it in
1804 * reverse order. Trylock is a way to avoid deadlock.
1806 * Also, it's not MADV_COLLAPSE's job to collapse other
1807 * mappings - let khugepaged take care of them later.
1809 result = SCAN_PTE_MAPPED_HUGEPAGE;
1810 if ((cc->is_khugepaged || is_target) &&
1811 mmap_write_trylock(mm)) {
1812 /* trylock for the same lock inversion as above */
1813 if (!vma_try_start_write(vma))
1817 * Re-check whether we have an ->anon_vma, because
1818 * collapse_and_free_pmd() requires that either no
1819 * ->anon_vma exists or the anon_vma is locked.
1820 * We already checked ->anon_vma above, but that check
1821 * is racy because ->anon_vma can be populated under the
1822 * mmap lock in read mode.
1824 if (vma->anon_vma) {
1825 result = SCAN_PAGE_ANON;
1829 * When a vma is registered with uffd-wp, we can't
1830 * recycle the pmd pgtable because there can be pte
1831 * markers installed. Skip it only, so the rest mm/vma
1832 * can still have the same file mapped hugely, however
1833 * it'll always mapped in small page size for uffd-wp
1834 * registered ranges.
1836 if (hpage_collapse_test_exit(mm)) {
1837 result = SCAN_ANY_PROCESS;
1840 if (userfaultfd_wp(vma)) {
1841 result = SCAN_PTE_UFFD_WP;
1844 collapse_and_free_pmd(mm, vma, addr, pmd);
1845 if (!cc->is_khugepaged && is_target)
1846 result = set_huge_pmd(vma, addr, pmd, hpage);
1848 result = SCAN_SUCCEED;
1851 mmap_write_unlock(mm);
1855 * Calling context will handle target mm/addr. Otherwise, let
1856 * khugepaged try again later.
1859 khugepaged_add_pte_mapped_thp(mm, addr);
1864 target_result = result;
1866 i_mmap_unlock_write(mapping);
1867 return target_result;
1871 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1873 * @mm: process address space where collapse happens
1874 * @addr: virtual collapse start address
1875 * @file: file that collapse on
1876 * @start: collapse start address
1877 * @cc: collapse context and scratchpad
1879 * Basic scheme is simple, details are more complex:
1880 * - allocate and lock a new huge page;
1881 * - scan page cache, locking old pages
1882 * + swap/gup in pages if necessary;
1883 * - copy data to new page
1884 * - handle shmem holes
1885 * + re-validate that holes weren't filled by someone else
1886 * + check for userfaultfd
1887 * - finalize updates to the page cache;
1888 * - if replacing succeeds:
1889 * + unlock huge page;
1891 * - if replacing failed;
1892 * + unlock old pages
1893 * + unlock and free huge page;
1895 static int collapse_file(struct mm_struct *mm, unsigned long addr,
1896 struct file *file, pgoff_t start,
1897 struct collapse_control *cc)
1899 struct address_space *mapping = file->f_mapping;
1903 struct folio *folio;
1904 pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1905 LIST_HEAD(pagelist);
1906 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1907 int nr_none = 0, result = SCAN_SUCCEED;
1908 bool is_shmem = shmem_file(file);
1911 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1912 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1914 result = alloc_charge_hpage(&hpage, mm, cc);
1915 if (result != SCAN_SUCCEED)
1918 __SetPageLocked(hpage);
1920 __SetPageSwapBacked(hpage);
1921 hpage->index = start;
1922 hpage->mapping = mapping;
1925 * Ensure we have slots for all the pages in the range. This is
1926 * almost certainly a no-op because most of the pages must be present
1930 xas_create_range(&xas);
1931 if (!xas_error(&xas))
1933 xas_unlock_irq(&xas);
1934 if (!xas_nomem(&xas, GFP_KERNEL)) {
1940 for (index = start; index < end; index++) {
1941 xas_set(&xas, index);
1942 page = xas_load(&xas);
1944 VM_BUG_ON(index != xas.xa_index);
1948 * Stop if extent has been truncated or
1949 * hole-punched, and is now completely
1952 if (index == start) {
1953 if (!xas_next_entry(&xas, end - 1)) {
1954 result = SCAN_TRUNCATED;
1958 if (!shmem_charge(mapping->host, 1)) {
1966 if (xa_is_value(page) || !PageUptodate(page)) {
1967 xas_unlock_irq(&xas);
1968 /* swap in or instantiate fallocated page */
1969 if (shmem_get_folio(mapping->host, index,
1970 &folio, SGP_NOALLOC)) {
1974 /* drain lru cache to help isolate_lru_page() */
1976 page = folio_file_page(folio, index);
1977 } else if (trylock_page(page)) {
1979 xas_unlock_irq(&xas);
1981 result = SCAN_PAGE_LOCK;
1984 } else { /* !is_shmem */
1985 if (!page || xa_is_value(page)) {
1986 xas_unlock_irq(&xas);
1987 page_cache_sync_readahead(mapping, &file->f_ra,
1990 /* drain lru cache to help isolate_lru_page() */
1992 page = find_lock_page(mapping, index);
1993 if (unlikely(page == NULL)) {
1997 } else if (PageDirty(page)) {
1999 * khugepaged only works on read-only fd,
2000 * so this page is dirty because it hasn't
2001 * been flushed since first write. There
2002 * won't be new dirty pages.
2004 * Trigger async flush here and hope the
2005 * writeback is done when khugepaged
2006 * revisits this page.
2008 * This is a one-off situation. We are not
2009 * forcing writeback in loop.
2011 xas_unlock_irq(&xas);
2012 filemap_flush(mapping);
2015 } else if (PageWriteback(page)) {
2016 xas_unlock_irq(&xas);
2019 } else if (trylock_page(page)) {
2021 xas_unlock_irq(&xas);
2023 result = SCAN_PAGE_LOCK;
2029 * The page must be locked, so we can drop the i_pages lock
2030 * without racing with truncate.
2032 VM_BUG_ON_PAGE(!PageLocked(page), page);
2034 /* make sure the page is up to date */
2035 if (unlikely(!PageUptodate(page))) {
2041 * If file was truncated then extended, or hole-punched, before
2042 * we locked the first page, then a THP might be there already.
2043 * This will be discovered on the first iteration.
2045 if (PageTransCompound(page)) {
2046 struct page *head = compound_head(page);
2048 result = compound_order(head) == HPAGE_PMD_ORDER &&
2049 head->index == start
2050 /* Maybe PMD-mapped */
2051 ? SCAN_PTE_MAPPED_HUGEPAGE
2052 : SCAN_PAGE_COMPOUND;
2056 folio = page_folio(page);
2058 if (folio_mapping(folio) != mapping) {
2059 result = SCAN_TRUNCATED;
2063 if (!is_shmem && (folio_test_dirty(folio) ||
2064 folio_test_writeback(folio))) {
2066 * khugepaged only works on read-only fd, so this
2067 * page is dirty because it hasn't been flushed
2068 * since first write.
2074 if (!folio_isolate_lru(folio)) {
2075 result = SCAN_DEL_PAGE_LRU;
2079 if (folio_has_private(folio) &&
2080 !filemap_release_folio(folio, GFP_KERNEL)) {
2081 result = SCAN_PAGE_HAS_PRIVATE;
2082 folio_putback_lru(folio);
2086 if (folio_mapped(folio))
2088 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
2092 VM_BUG_ON_PAGE(page != xa_load(xas.xa, index), page);
2095 * We control three references to the page:
2096 * - we hold a pin on it;
2097 * - one reference from page cache;
2098 * - one from isolate_lru_page;
2099 * If those are the only references, then any new usage of the
2100 * page will have to fetch it from the page cache. That requires
2101 * locking the page to handle truncate, so any new usage will be
2102 * blocked until we unlock page after collapse/during rollback.
2104 if (page_count(page) != 3) {
2105 result = SCAN_PAGE_COUNT;
2106 xas_unlock_irq(&xas);
2107 putback_lru_page(page);
2112 * Accumulate the pages that are being collapsed.
2114 list_add_tail(&page->lru, &pagelist);
2123 filemap_nr_thps_inc(mapping);
2125 * Paired with smp_mb() in do_dentry_open() to ensure
2126 * i_writecount is up to date and the update to nr_thps is
2127 * visible. Ensures the page cache will be truncated if the
2128 * file is opened writable.
2131 if (inode_is_open_for_write(mapping->host)) {
2133 filemap_nr_thps_dec(mapping);
2138 xas_unlock_irq(&xas);
2142 * If collapse is successful, flush must be done now before copying.
2143 * If collapse is unsuccessful, does flush actually need to be done?
2144 * Do it anyway, to clear the state.
2146 try_to_unmap_flush();
2148 if (result != SCAN_SUCCEED)
2152 * The old pages are locked, so they won't change anymore.
2155 list_for_each_entry(page, &pagelist, lru) {
2156 while (index < page->index) {
2157 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2160 if (copy_mc_highpage(hpage + (page->index % HPAGE_PMD_NR), page) > 0) {
2161 result = SCAN_COPY_MC;
2166 while (index < end) {
2167 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2172 struct vm_area_struct *vma;
2173 int nr_none_check = 0;
2175 i_mmap_lock_read(mapping);
2178 xas_set(&xas, start);
2179 for (index = start; index < end; index++) {
2180 if (!xas_next(&xas)) {
2181 xas_store(&xas, XA_RETRY_ENTRY);
2182 if (xas_error(&xas)) {
2183 result = SCAN_STORE_FAILED;
2190 if (nr_none != nr_none_check) {
2191 result = SCAN_PAGE_FILLED;
2196 * If userspace observed a missing page in a VMA with a MODE_MISSING
2197 * userfaultfd, then it might expect a UFFD_EVENT_PAGEFAULT for that
2198 * page. If so, we need to roll back to avoid suppressing such an
2199 * event. Since wp/minor userfaultfds don't give userspace any
2200 * guarantees that the kernel doesn't fill a missing page with a zero
2201 * page, so they don't matter here.
2203 * Any userfaultfds registered after this point will not be able to
2204 * observe any missing pages due to the previously inserted retry
2207 vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2208 if (userfaultfd_missing(vma)) {
2209 result = SCAN_EXCEED_NONE_PTE;
2215 i_mmap_unlock_read(mapping);
2216 if (result != SCAN_SUCCEED) {
2217 xas_set(&xas, start);
2218 for (index = start; index < end; index++) {
2219 if (xas_next(&xas) == XA_RETRY_ENTRY)
2220 xas_store(&xas, NULL);
2223 xas_unlock_irq(&xas);
2230 nr = thp_nr_pages(hpage);
2232 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
2234 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
2237 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
2238 /* nr_none is always 0 for non-shmem. */
2239 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2243 * Mark hpage as uptodate before inserting it into the page cache so
2244 * that it isn't mistaken for an fallocated but unwritten page.
2246 folio = page_folio(hpage);
2247 folio_mark_uptodate(folio);
2248 folio_ref_add(folio, HPAGE_PMD_NR - 1);
2251 folio_mark_dirty(folio);
2252 folio_add_lru(folio);
2254 /* Join all the small entries into a single multi-index entry. */
2255 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2256 xas_store(&xas, hpage);
2257 WARN_ON_ONCE(xas_error(&xas));
2258 xas_unlock_irq(&xas);
2261 * Remove pte page tables, so we can re-fault the page as huge.
2263 result = retract_page_tables(mapping, start, mm, addr, hpage,
2268 * The collapse has succeeded, so free the old pages.
2270 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2271 list_del(&page->lru);
2272 page->mapping = NULL;
2273 ClearPageActive(page);
2274 ClearPageUnevictable(page);
2276 folio_put_refs(page_folio(page), 3);
2282 /* Something went wrong: roll back page cache changes */
2285 mapping->nrpages -= nr_none;
2286 shmem_uncharge(mapping->host, nr_none);
2287 xas_unlock_irq(&xas);
2290 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2291 list_del(&page->lru);
2293 putback_lru_page(page);
2297 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
2298 * file only. This undo is not needed unless failure is
2299 * due to SCAN_COPY_MC.
2301 if (!is_shmem && result == SCAN_COPY_MC) {
2302 filemap_nr_thps_dec(mapping);
2304 * Paired with smp_mb() in do_dentry_open() to
2305 * ensure the update to nr_thps is visible.
2310 hpage->mapping = NULL;
2315 VM_BUG_ON(!list_empty(&pagelist));
2316 trace_mm_khugepaged_collapse_file(mm, hpage, index, is_shmem, addr, file, nr, result);
2320 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2321 struct file *file, pgoff_t start,
2322 struct collapse_control *cc)
2324 struct page *page = NULL;
2325 struct address_space *mapping = file->f_mapping;
2326 XA_STATE(xas, &mapping->i_pages, start);
2328 int node = NUMA_NO_NODE;
2329 int result = SCAN_SUCCEED;
2333 memset(cc->node_load, 0, sizeof(cc->node_load));
2334 nodes_clear(cc->alloc_nmask);
2336 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2337 if (xas_retry(&xas, page))
2340 if (xa_is_value(page)) {
2342 if (cc->is_khugepaged &&
2343 swap > khugepaged_max_ptes_swap) {
2344 result = SCAN_EXCEED_SWAP_PTE;
2345 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2352 * TODO: khugepaged should compact smaller compound pages
2353 * into a PMD sized page
2355 if (PageTransCompound(page)) {
2356 struct page *head = compound_head(page);
2358 result = compound_order(head) == HPAGE_PMD_ORDER &&
2359 head->index == start
2360 /* Maybe PMD-mapped */
2361 ? SCAN_PTE_MAPPED_HUGEPAGE
2362 : SCAN_PAGE_COMPOUND;
2364 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2365 * by the caller won't touch the page cache, and so
2366 * it's safe to skip LRU and refcount checks before
2372 node = page_to_nid(page);
2373 if (hpage_collapse_scan_abort(node, cc)) {
2374 result = SCAN_SCAN_ABORT;
2377 cc->node_load[node]++;
2379 if (!PageLRU(page)) {
2380 result = SCAN_PAGE_LRU;
2384 if (page_count(page) !=
2385 1 + page_mapcount(page) + page_has_private(page)) {
2386 result = SCAN_PAGE_COUNT;
2391 * We probably should check if the page is referenced here, but
2392 * nobody would transfer pte_young() to PageReferenced() for us.
2393 * And rmap walk here is just too costly...
2398 if (need_resched()) {
2405 if (result == SCAN_SUCCEED) {
2406 if (cc->is_khugepaged &&
2407 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2408 result = SCAN_EXCEED_NONE_PTE;
2409 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2411 result = collapse_file(mm, addr, file, start, cc);
2415 trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
2419 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2420 struct file *file, pgoff_t start,
2421 struct collapse_control *cc)
2426 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
2430 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
2437 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2438 struct collapse_control *cc)
2439 __releases(&khugepaged_mm_lock)
2440 __acquires(&khugepaged_mm_lock)
2442 struct vma_iterator vmi;
2443 struct khugepaged_mm_slot *mm_slot;
2444 struct mm_slot *slot;
2445 struct mm_struct *mm;
2446 struct vm_area_struct *vma;
2450 lockdep_assert_held(&khugepaged_mm_lock);
2451 *result = SCAN_FAIL;
2453 if (khugepaged_scan.mm_slot) {
2454 mm_slot = khugepaged_scan.mm_slot;
2455 slot = &mm_slot->slot;
2457 slot = list_entry(khugepaged_scan.mm_head.next,
2458 struct mm_slot, mm_node);
2459 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2460 khugepaged_scan.address = 0;
2461 khugepaged_scan.mm_slot = mm_slot;
2463 spin_unlock(&khugepaged_mm_lock);
2464 khugepaged_collapse_pte_mapped_thps(mm_slot);
2468 * Don't wait for semaphore (to avoid long wait times). Just move to
2469 * the next mm on the list.
2472 if (unlikely(!mmap_read_trylock(mm)))
2473 goto breakouterloop_mmap_lock;
2476 if (unlikely(hpage_collapse_test_exit(mm)))
2477 goto breakouterloop;
2479 vma_iter_init(&vmi, mm, khugepaged_scan.address);
2480 for_each_vma(vmi, vma) {
2481 unsigned long hstart, hend;
2484 if (unlikely(hpage_collapse_test_exit(mm))) {
2488 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2493 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2494 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2495 if (khugepaged_scan.address > hend)
2497 if (khugepaged_scan.address < hstart)
2498 khugepaged_scan.address = hstart;
2499 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2501 while (khugepaged_scan.address < hend) {
2502 bool mmap_locked = true;
2505 if (unlikely(hpage_collapse_test_exit(mm)))
2506 goto breakouterloop;
2508 VM_BUG_ON(khugepaged_scan.address < hstart ||
2509 khugepaged_scan.address + HPAGE_PMD_SIZE >
2511 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2512 struct file *file = get_file(vma->vm_file);
2513 pgoff_t pgoff = linear_page_index(vma,
2514 khugepaged_scan.address);
2516 mmap_read_unlock(mm);
2517 *result = hpage_collapse_scan_file(mm,
2518 khugepaged_scan.address,
2520 mmap_locked = false;
2523 *result = hpage_collapse_scan_pmd(mm, vma,
2524 khugepaged_scan.address,
2529 case SCAN_PTE_MAPPED_HUGEPAGE: {
2532 *result = find_pmd_or_thp_or_none(mm,
2533 khugepaged_scan.address,
2535 if (*result != SCAN_SUCCEED)
2537 if (!khugepaged_add_pte_mapped_thp(mm,
2538 khugepaged_scan.address))
2542 ++khugepaged_pages_collapsed;
2548 /* move to next address */
2549 khugepaged_scan.address += HPAGE_PMD_SIZE;
2550 progress += HPAGE_PMD_NR;
2553 * We released mmap_lock so break loop. Note
2554 * that we drop mmap_lock before all hugepage
2555 * allocations, so if allocation fails, we are
2556 * guaranteed to break here and report the
2557 * correct result back to caller.
2559 goto breakouterloop_mmap_lock;
2560 if (progress >= pages)
2561 goto breakouterloop;
2565 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2566 breakouterloop_mmap_lock:
2568 spin_lock(&khugepaged_mm_lock);
2569 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2571 * Release the current mm_slot if this mm is about to die, or
2572 * if we scanned all vmas of this mm.
2574 if (hpage_collapse_test_exit(mm) || !vma) {
2576 * Make sure that if mm_users is reaching zero while
2577 * khugepaged runs here, khugepaged_exit will find
2578 * mm_slot not pointing to the exiting mm.
2580 if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2581 slot = list_entry(slot->mm_node.next,
2582 struct mm_slot, mm_node);
2583 khugepaged_scan.mm_slot =
2584 mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2585 khugepaged_scan.address = 0;
2587 khugepaged_scan.mm_slot = NULL;
2588 khugepaged_full_scans++;
2591 collect_mm_slot(mm_slot);
2597 static int khugepaged_has_work(void)
2599 return !list_empty(&khugepaged_scan.mm_head) &&
2600 hugepage_flags_enabled();
2603 static int khugepaged_wait_event(void)
2605 return !list_empty(&khugepaged_scan.mm_head) ||
2606 kthread_should_stop();
2609 static void khugepaged_do_scan(struct collapse_control *cc)
2611 unsigned int progress = 0, pass_through_head = 0;
2612 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2614 int result = SCAN_SUCCEED;
2616 lru_add_drain_all();
2621 if (unlikely(kthread_should_stop() || try_to_freeze()))
2624 spin_lock(&khugepaged_mm_lock);
2625 if (!khugepaged_scan.mm_slot)
2626 pass_through_head++;
2627 if (khugepaged_has_work() &&
2628 pass_through_head < 2)
2629 progress += khugepaged_scan_mm_slot(pages - progress,
2633 spin_unlock(&khugepaged_mm_lock);
2635 if (progress >= pages)
2638 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2640 * If fail to allocate the first time, try to sleep for
2641 * a while. When hit again, cancel the scan.
2646 khugepaged_alloc_sleep();
2651 static bool khugepaged_should_wakeup(void)
2653 return kthread_should_stop() ||
2654 time_after_eq(jiffies, khugepaged_sleep_expire);
2657 static void khugepaged_wait_work(void)
2659 if (khugepaged_has_work()) {
2660 const unsigned long scan_sleep_jiffies =
2661 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2663 if (!scan_sleep_jiffies)
2666 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2667 wait_event_freezable_timeout(khugepaged_wait,
2668 khugepaged_should_wakeup(),
2669 scan_sleep_jiffies);
2673 if (hugepage_flags_enabled())
2674 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2677 static int khugepaged(void *none)
2679 struct khugepaged_mm_slot *mm_slot;
2682 set_user_nice(current, MAX_NICE);
2684 while (!kthread_should_stop()) {
2685 khugepaged_do_scan(&khugepaged_collapse_control);
2686 khugepaged_wait_work();
2689 spin_lock(&khugepaged_mm_lock);
2690 mm_slot = khugepaged_scan.mm_slot;
2691 khugepaged_scan.mm_slot = NULL;
2693 collect_mm_slot(mm_slot);
2694 spin_unlock(&khugepaged_mm_lock);
2698 static void set_recommended_min_free_kbytes(void)
2702 unsigned long recommended_min;
2704 if (!hugepage_flags_enabled()) {
2705 calculate_min_free_kbytes();
2709 for_each_populated_zone(zone) {
2711 * We don't need to worry about fragmentation of
2712 * ZONE_MOVABLE since it only has movable pages.
2714 if (zone_idx(zone) > gfp_zone(GFP_USER))
2720 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2721 recommended_min = pageblock_nr_pages * nr_zones * 2;
2724 * Make sure that on average at least two pageblocks are almost free
2725 * of another type, one for a migratetype to fall back to and a
2726 * second to avoid subsequent fallbacks of other types There are 3
2727 * MIGRATE_TYPES we care about.
2729 recommended_min += pageblock_nr_pages * nr_zones *
2730 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2732 /* don't ever allow to reserve more than 5% of the lowmem */
2733 recommended_min = min(recommended_min,
2734 (unsigned long) nr_free_buffer_pages() / 20);
2735 recommended_min <<= (PAGE_SHIFT-10);
2737 if (recommended_min > min_free_kbytes) {
2738 if (user_min_free_kbytes >= 0)
2739 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2740 min_free_kbytes, recommended_min);
2742 min_free_kbytes = recommended_min;
2746 setup_per_zone_wmarks();
2749 int start_stop_khugepaged(void)
2753 mutex_lock(&khugepaged_mutex);
2754 if (hugepage_flags_enabled()) {
2755 if (!khugepaged_thread)
2756 khugepaged_thread = kthread_run(khugepaged, NULL,
2758 if (IS_ERR(khugepaged_thread)) {
2759 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2760 err = PTR_ERR(khugepaged_thread);
2761 khugepaged_thread = NULL;
2765 if (!list_empty(&khugepaged_scan.mm_head))
2766 wake_up_interruptible(&khugepaged_wait);
2767 } else if (khugepaged_thread) {
2768 kthread_stop(khugepaged_thread);
2769 khugepaged_thread = NULL;
2771 set_recommended_min_free_kbytes();
2773 mutex_unlock(&khugepaged_mutex);
2777 void khugepaged_min_free_kbytes_update(void)
2779 mutex_lock(&khugepaged_mutex);
2780 if (hugepage_flags_enabled() && khugepaged_thread)
2781 set_recommended_min_free_kbytes();
2782 mutex_unlock(&khugepaged_mutex);
2785 bool current_is_khugepaged(void)
2787 return kthread_func(current) == khugepaged;
2790 static int madvise_collapse_errno(enum scan_result r)
2793 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2794 * actionable feedback to caller, so they may take an appropriate
2795 * fallback measure depending on the nature of the failure.
2798 case SCAN_ALLOC_HUGE_PAGE_FAIL:
2800 case SCAN_CGROUP_CHARGE_FAIL:
2801 case SCAN_EXCEED_NONE_PTE:
2803 /* Resource temporary unavailable - trying again might succeed */
2804 case SCAN_PAGE_COUNT:
2805 case SCAN_PAGE_LOCK:
2807 case SCAN_DEL_PAGE_LRU:
2808 case SCAN_PAGE_FILLED:
2811 * Other: Trying again likely not to succeed / error intrinsic to
2812 * specified memory range. khugepaged likely won't be able to collapse
2820 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2821 unsigned long start, unsigned long end)
2823 struct collapse_control *cc;
2824 struct mm_struct *mm = vma->vm_mm;
2825 unsigned long hstart, hend, addr;
2826 int thps = 0, last_fail = SCAN_FAIL;
2827 bool mmap_locked = true;
2829 BUG_ON(vma->vm_start > start);
2830 BUG_ON(vma->vm_end < end);
2834 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2837 cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2840 cc->is_khugepaged = false;
2843 lru_add_drain_all();
2845 hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2846 hend = end & HPAGE_PMD_MASK;
2848 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2849 int result = SCAN_FAIL;
2855 result = hugepage_vma_revalidate(mm, addr, false, &vma,
2857 if (result != SCAN_SUCCEED) {
2862 hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
2864 mmap_assert_locked(mm);
2865 memset(cc->node_load, 0, sizeof(cc->node_load));
2866 nodes_clear(cc->alloc_nmask);
2867 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2868 struct file *file = get_file(vma->vm_file);
2869 pgoff_t pgoff = linear_page_index(vma, addr);
2871 mmap_read_unlock(mm);
2872 mmap_locked = false;
2873 result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2877 result = hpage_collapse_scan_pmd(mm, vma, addr,
2881 *prev = NULL; /* Tell caller we dropped mmap_lock */
2886 case SCAN_PMD_MAPPED:
2889 case SCAN_PTE_MAPPED_HUGEPAGE:
2890 BUG_ON(mmap_locked);
2892 mmap_write_lock(mm);
2893 result = collapse_pte_mapped_thp(mm, addr, true);
2894 mmap_write_unlock(mm);
2896 /* Whitelisted set of results where continuing OK */
2898 case SCAN_PTE_NON_PRESENT:
2899 case SCAN_PTE_UFFD_WP:
2901 case SCAN_LACK_REFERENCED_PAGE:
2902 case SCAN_PAGE_NULL:
2903 case SCAN_PAGE_COUNT:
2904 case SCAN_PAGE_LOCK:
2905 case SCAN_PAGE_COMPOUND:
2907 case SCAN_DEL_PAGE_LRU:
2912 /* Other error, exit */
2918 /* Caller expects us to hold mmap_lock on return */
2922 mmap_assert_locked(mm);
2926 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2927 : madvise_collapse_errno(last_fail);