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 /* Last target selected in hpage_collapse_find_target_node() */
101 int last_target_node;
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_page(struct page *page)
495 mod_node_page_state(page_pgdat(page),
496 NR_ISOLATED_ANON + page_is_file_lru(page),
499 putback_lru_page(page);
502 static void release_pte_pages(pte_t *pte, pte_t *_pte,
503 struct list_head *compound_pagelist)
505 struct page *page, *tmp;
507 while (--_pte >= pte) {
508 pte_t pteval = *_pte;
510 page = pte_page(pteval);
511 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
513 release_pte_page(page);
516 list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
517 list_del(&page->lru);
518 release_pte_page(page);
522 static bool is_refcount_suitable(struct page *page)
524 int expected_refcount;
526 expected_refcount = total_mapcount(page);
527 if (PageSwapCache(page))
528 expected_refcount += compound_nr(page);
530 return page_count(page) == expected_refcount;
533 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
534 unsigned long address,
536 struct collapse_control *cc,
537 struct list_head *compound_pagelist)
539 struct page *page = NULL;
541 int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
542 bool writable = false;
544 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
545 _pte++, address += PAGE_SIZE) {
546 pte_t pteval = *_pte;
547 if (pte_none(pteval) || (pte_present(pteval) &&
548 is_zero_pfn(pte_pfn(pteval)))) {
550 if (!userfaultfd_armed(vma) &&
551 (!cc->is_khugepaged ||
552 none_or_zero <= khugepaged_max_ptes_none)) {
555 result = SCAN_EXCEED_NONE_PTE;
556 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
560 if (!pte_present(pteval)) {
561 result = SCAN_PTE_NON_PRESENT;
564 page = vm_normal_page(vma, address, pteval);
565 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
566 result = SCAN_PAGE_NULL;
570 VM_BUG_ON_PAGE(!PageAnon(page), page);
572 if (page_mapcount(page) > 1) {
574 if (cc->is_khugepaged &&
575 shared > khugepaged_max_ptes_shared) {
576 result = SCAN_EXCEED_SHARED_PTE;
577 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
582 if (PageCompound(page)) {
584 page = compound_head(page);
587 * Check if we have dealt with the compound page
590 list_for_each_entry(p, compound_pagelist, lru) {
597 * We can do it before isolate_lru_page because the
598 * page can't be freed from under us. NOTE: PG_lock
599 * is needed to serialize against split_huge_page
600 * when invoked from the VM.
602 if (!trylock_page(page)) {
603 result = SCAN_PAGE_LOCK;
608 * Check if the page has any GUP (or other external) pins.
610 * The page table that maps the page has been already unlinked
611 * from the page table tree and this process cannot get
612 * an additional pin on the page.
614 * New pins can come later if the page is shared across fork,
615 * but not from this process. The other process cannot write to
616 * the page, only trigger CoW.
618 if (!is_refcount_suitable(page)) {
620 result = SCAN_PAGE_COUNT;
625 * Isolate the page to avoid collapsing an hugepage
626 * currently in use by the VM.
628 if (isolate_lru_page(page)) {
630 result = SCAN_DEL_PAGE_LRU;
633 mod_node_page_state(page_pgdat(page),
634 NR_ISOLATED_ANON + page_is_file_lru(page),
636 VM_BUG_ON_PAGE(!PageLocked(page), page);
637 VM_BUG_ON_PAGE(PageLRU(page), page);
639 if (PageCompound(page))
640 list_add_tail(&page->lru, compound_pagelist);
643 * If collapse was initiated by khugepaged, check that there is
644 * enough young pte to justify collapsing the page
646 if (cc->is_khugepaged &&
647 (pte_young(pteval) || page_is_young(page) ||
648 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
652 if (pte_write(pteval))
656 if (unlikely(!writable)) {
657 result = SCAN_PAGE_RO;
658 } else if (unlikely(cc->is_khugepaged && !referenced)) {
659 result = SCAN_LACK_REFERENCED_PAGE;
661 result = SCAN_SUCCEED;
662 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
663 referenced, writable, result);
667 release_pte_pages(pte, _pte, compound_pagelist);
668 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
669 referenced, writable, result);
673 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
674 struct vm_area_struct *vma,
675 unsigned long address,
677 struct list_head *compound_pagelist)
679 struct page *src_page, *tmp;
681 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
682 _pte++, page++, address += PAGE_SIZE) {
683 pte_t pteval = *_pte;
685 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
686 clear_user_highpage(page, address);
687 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
688 if (is_zero_pfn(pte_pfn(pteval))) {
690 * ptl mostly unnecessary.
693 ptep_clear(vma->vm_mm, address, _pte);
697 src_page = pte_page(pteval);
698 copy_user_highpage(page, src_page, address, vma);
699 if (!PageCompound(src_page))
700 release_pte_page(src_page);
702 * ptl mostly unnecessary, but preempt has to
703 * be disabled to update the per-cpu stats
704 * inside page_remove_rmap().
707 ptep_clear(vma->vm_mm, address, _pte);
708 page_remove_rmap(src_page, vma, false);
710 free_page_and_swap_cache(src_page);
714 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
715 list_del(&src_page->lru);
716 mod_node_page_state(page_pgdat(src_page),
717 NR_ISOLATED_ANON + page_is_file_lru(src_page),
718 -compound_nr(src_page));
719 unlock_page(src_page);
720 free_swap_cache(src_page);
721 putback_lru_page(src_page);
725 static void khugepaged_alloc_sleep(void)
729 add_wait_queue(&khugepaged_wait, &wait);
730 __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
731 schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
732 remove_wait_queue(&khugepaged_wait, &wait);
735 struct collapse_control khugepaged_collapse_control = {
736 .is_khugepaged = true,
737 .last_target_node = NUMA_NO_NODE,
740 static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
745 * If node_reclaim_mode is disabled, then no extra effort is made to
746 * allocate memory locally.
748 if (!node_reclaim_enabled())
751 /* If there is a count for this node already, it must be acceptable */
752 if (cc->node_load[nid])
755 for (i = 0; i < MAX_NUMNODES; i++) {
756 if (!cc->node_load[i])
758 if (node_distance(nid, i) > node_reclaim_distance)
764 #define khugepaged_defrag() \
765 (transparent_hugepage_flags & \
766 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
768 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
769 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
771 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
775 static int hpage_collapse_find_target_node(struct collapse_control *cc)
777 int nid, target_node = 0, max_value = 0;
779 /* find first node with max normal pages hit */
780 for (nid = 0; nid < MAX_NUMNODES; nid++)
781 if (cc->node_load[nid] > max_value) {
782 max_value = cc->node_load[nid];
786 /* do some balance if several nodes have the same hit record */
787 if (target_node <= cc->last_target_node)
788 for (nid = cc->last_target_node + 1; nid < MAX_NUMNODES;
790 if (max_value == cc->node_load[nid]) {
795 cc->last_target_node = target_node;
799 static int hpage_collapse_find_target_node(struct collapse_control *cc)
805 static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node)
807 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
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;
855 static int find_pmd_or_thp_or_none(struct mm_struct *mm,
856 unsigned long address,
861 *pmd = mm_find_pmd(mm, address);
863 return SCAN_PMD_NULL;
865 pmde = pmd_read_atomic(*pmd);
867 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
868 /* See comments in pmd_none_or_trans_huge_or_clear_bad() */
872 return SCAN_PMD_NONE;
873 if (pmd_trans_huge(pmde))
874 return SCAN_PMD_MAPPED;
876 return SCAN_PMD_NULL;
880 static int check_pmd_still_valid(struct mm_struct *mm,
881 unsigned long address,
885 int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
887 if (result != SCAN_SUCCEED)
895 * Bring missing pages in from swap, to complete THP collapse.
896 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
898 * Called and returns without pte mapped or spinlocks held.
899 * Note that if false is returned, mmap_lock will be released.
902 static int __collapse_huge_page_swapin(struct mm_struct *mm,
903 struct vm_area_struct *vma,
904 unsigned long haddr, pmd_t *pmd,
909 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
911 for (address = haddr; address < end; address += PAGE_SIZE) {
912 struct vm_fault vmf = {
915 .pgoff = linear_page_index(vma, haddr),
916 .flags = FAULT_FLAG_ALLOW_RETRY,
920 vmf.pte = pte_offset_map(pmd, address);
921 vmf.orig_pte = *vmf.pte;
922 if (!is_swap_pte(vmf.orig_pte)) {
926 ret = do_swap_page(&vmf);
929 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
930 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
931 * we do not retry here and swap entry will remain in pagetable
932 * resulting in later failure.
934 if (ret & VM_FAULT_RETRY) {
935 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
936 /* Likely, but not guaranteed, that page lock failed */
937 return SCAN_PAGE_LOCK;
939 if (ret & VM_FAULT_ERROR) {
940 mmap_read_unlock(mm);
941 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
947 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
951 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
955 static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
956 struct collapse_control *cc)
958 /* Only allocate from the target node */
959 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
960 GFP_TRANSHUGE) | __GFP_THISNODE;
961 int node = hpage_collapse_find_target_node(cc);
963 if (!hpage_collapse_alloc_page(hpage, gfp, node))
964 return SCAN_ALLOC_HUGE_PAGE_FAIL;
965 if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
966 return SCAN_CGROUP_CHARGE_FAIL;
967 count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
971 static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
972 int referenced, int unmapped,
973 struct collapse_control *cc)
975 LIST_HEAD(compound_pagelist);
980 spinlock_t *pmd_ptl, *pte_ptl;
981 int result = SCAN_FAIL;
982 struct vm_area_struct *vma;
983 struct mmu_notifier_range range;
985 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
988 * Before allocating the hugepage, release the mmap_lock read lock.
989 * The allocation can take potentially a long time if it involves
990 * sync compaction, and we do not need to hold the mmap_lock during
991 * that. We will recheck the vma after taking it again in write mode.
993 mmap_read_unlock(mm);
995 result = alloc_charge_hpage(&hpage, mm, cc);
996 if (result != SCAN_SUCCEED)
1000 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1001 if (result != SCAN_SUCCEED) {
1002 mmap_read_unlock(mm);
1006 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1007 if (result != SCAN_SUCCEED) {
1008 mmap_read_unlock(mm);
1014 * __collapse_huge_page_swapin will return with mmap_lock
1015 * released when it fails. So we jump out_nolock directly in
1016 * that case. Continuing to collapse causes inconsistency.
1018 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1020 if (result != SCAN_SUCCEED)
1024 mmap_read_unlock(mm);
1026 * Prevent all access to pagetables with the exception of
1027 * gup_fast later handled by the ptep_clear_flush and the VM
1028 * handled by the anon_vma lock + PG_lock.
1030 mmap_write_lock(mm);
1031 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1032 if (result != SCAN_SUCCEED)
1034 /* check if the pmd is still valid */
1035 result = check_pmd_still_valid(mm, address, pmd);
1036 if (result != SCAN_SUCCEED)
1039 anon_vma_lock_write(vma->anon_vma);
1041 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1042 address, address + HPAGE_PMD_SIZE);
1043 mmu_notifier_invalidate_range_start(&range);
1045 pte = pte_offset_map(pmd, address);
1046 pte_ptl = pte_lockptr(mm, pmd);
1048 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1050 * This removes any huge TLB entry from the CPU so we won't allow
1051 * huge and small TLB entries for the same virtual address to
1052 * avoid the risk of CPU bugs in that area.
1054 * Parallel fast GUP is fine since fast GUP will back off when
1055 * it detects PMD is changed.
1057 _pmd = pmdp_collapse_flush(vma, address, pmd);
1058 spin_unlock(pmd_ptl);
1059 mmu_notifier_invalidate_range_end(&range);
1062 result = __collapse_huge_page_isolate(vma, address, pte, cc,
1063 &compound_pagelist);
1064 spin_unlock(pte_ptl);
1066 if (unlikely(result != SCAN_SUCCEED)) {
1069 BUG_ON(!pmd_none(*pmd));
1071 * We can only use set_pmd_at when establishing
1072 * hugepmds and never for establishing regular pmds that
1073 * points to regular pagetables. Use pmd_populate for that
1075 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1076 spin_unlock(pmd_ptl);
1077 anon_vma_unlock_write(vma->anon_vma);
1082 * All pages are isolated and locked so anon_vma rmap
1083 * can't run anymore.
1085 anon_vma_unlock_write(vma->anon_vma);
1087 __collapse_huge_page_copy(pte, hpage, vma, address, pte_ptl,
1088 &compound_pagelist);
1091 * spin_lock() below is not the equivalent of smp_wmb(), but
1092 * the smp_wmb() inside __SetPageUptodate() can be reused to
1093 * avoid the copy_huge_page writes to become visible after
1094 * the set_pmd_at() write.
1096 __SetPageUptodate(hpage);
1097 pgtable = pmd_pgtable(_pmd);
1099 _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1100 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1103 BUG_ON(!pmd_none(*pmd));
1104 page_add_new_anon_rmap(hpage, vma, address);
1105 lru_cache_add_inactive_or_unevictable(hpage, vma);
1106 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1107 set_pmd_at(mm, address, pmd, _pmd);
1108 update_mmu_cache_pmd(vma, address, pmd);
1109 spin_unlock(pmd_ptl);
1113 result = SCAN_SUCCEED;
1115 mmap_write_unlock(mm);
1118 mem_cgroup_uncharge(page_folio(hpage));
1121 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1125 static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1126 struct vm_area_struct *vma,
1127 unsigned long address, bool *mmap_locked,
1128 struct collapse_control *cc)
1132 int result = SCAN_FAIL, referenced = 0;
1133 int none_or_zero = 0, shared = 0;
1134 struct page *page = NULL;
1135 unsigned long _address;
1137 int node = NUMA_NO_NODE, unmapped = 0;
1138 bool writable = false;
1140 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1142 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1143 if (result != SCAN_SUCCEED)
1146 memset(cc->node_load, 0, sizeof(cc->node_load));
1147 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1148 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1149 _pte++, _address += PAGE_SIZE) {
1150 pte_t pteval = *_pte;
1151 if (is_swap_pte(pteval)) {
1153 if (!cc->is_khugepaged ||
1154 unmapped <= khugepaged_max_ptes_swap) {
1156 * Always be strict with uffd-wp
1157 * enabled swap entries. Please see
1158 * comment below for pte_uffd_wp().
1160 if (pte_swp_uffd_wp(pteval)) {
1161 result = SCAN_PTE_UFFD_WP;
1166 result = SCAN_EXCEED_SWAP_PTE;
1167 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1171 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1173 if (!userfaultfd_armed(vma) &&
1174 (!cc->is_khugepaged ||
1175 none_or_zero <= khugepaged_max_ptes_none)) {
1178 result = SCAN_EXCEED_NONE_PTE;
1179 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1183 if (pte_uffd_wp(pteval)) {
1185 * Don't collapse the page if any of the small
1186 * PTEs are armed with uffd write protection.
1187 * Here we can also mark the new huge pmd as
1188 * write protected if any of the small ones is
1189 * marked but that could bring unknown
1190 * userfault messages that falls outside of
1191 * the registered range. So, just be simple.
1193 result = SCAN_PTE_UFFD_WP;
1196 if (pte_write(pteval))
1199 page = vm_normal_page(vma, _address, pteval);
1200 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1201 result = SCAN_PAGE_NULL;
1205 if (page_mapcount(page) > 1) {
1207 if (cc->is_khugepaged &&
1208 shared > khugepaged_max_ptes_shared) {
1209 result = SCAN_EXCEED_SHARED_PTE;
1210 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1215 page = compound_head(page);
1218 * Record which node the original page is from and save this
1219 * information to cc->node_load[].
1220 * Khugepaged will allocate hugepage from the node has the max
1223 node = page_to_nid(page);
1224 if (hpage_collapse_scan_abort(node, cc)) {
1225 result = SCAN_SCAN_ABORT;
1228 cc->node_load[node]++;
1229 if (!PageLRU(page)) {
1230 result = SCAN_PAGE_LRU;
1233 if (PageLocked(page)) {
1234 result = SCAN_PAGE_LOCK;
1237 if (!PageAnon(page)) {
1238 result = SCAN_PAGE_ANON;
1243 * Check if the page has any GUP (or other external) pins.
1245 * Here the check is racy it may see total_mapcount > refcount
1247 * For example, one process with one forked child process.
1248 * The parent has the PMD split due to MADV_DONTNEED, then
1249 * the child is trying unmap the whole PMD, but khugepaged
1250 * may be scanning the parent between the child has
1251 * PageDoubleMap flag cleared and dec the mapcount. So
1252 * khugepaged may see total_mapcount > refcount.
1254 * But such case is ephemeral we could always retry collapse
1255 * later. However it may report false positive if the page
1256 * has excessive GUP pins (i.e. 512). Anyway the same check
1257 * will be done again later the risk seems low.
1259 if (!is_refcount_suitable(page)) {
1260 result = SCAN_PAGE_COUNT;
1265 * If collapse was initiated by khugepaged, check that there is
1266 * enough young pte to justify collapsing the page
1268 if (cc->is_khugepaged &&
1269 (pte_young(pteval) || page_is_young(page) ||
1270 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1275 result = SCAN_PAGE_RO;
1276 } else if (cc->is_khugepaged &&
1278 (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1279 result = SCAN_LACK_REFERENCED_PAGE;
1281 result = SCAN_SUCCEED;
1284 pte_unmap_unlock(pte, ptl);
1285 if (result == SCAN_SUCCEED) {
1286 result = collapse_huge_page(mm, address, referenced,
1288 /* collapse_huge_page will return with the mmap_lock released */
1289 *mmap_locked = false;
1292 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1293 none_or_zero, result, unmapped);
1297 static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1299 struct mm_slot *slot = &mm_slot->slot;
1300 struct mm_struct *mm = slot->mm;
1302 lockdep_assert_held(&khugepaged_mm_lock);
1304 if (hpage_collapse_test_exit(mm)) {
1306 hash_del(&slot->hash);
1307 list_del(&slot->mm_node);
1310 * Not strictly needed because the mm exited already.
1312 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1315 /* khugepaged_mm_lock actually not necessary for the below */
1316 mm_slot_free(mm_slot_cache, mm_slot);
1323 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1324 * khugepaged should try to collapse the page table.
1326 * Note that following race exists:
1327 * (1) khugepaged calls khugepaged_collapse_pte_mapped_thps() for mm_struct A,
1328 * emptying the A's ->pte_mapped_thp[] array.
1329 * (2) MADV_COLLAPSE collapses some file extent with target mm_struct B, and
1330 * retract_page_tables() finds a VMA in mm_struct A mapping the same extent
1331 * (at virtual address X) and adds an entry (for X) into mm_struct A's
1332 * ->pte-mapped_thp[] array.
1333 * (3) khugepaged calls khugepaged_collapse_scan_file() for mm_struct A at X,
1334 * sees a pte-mapped THP (SCAN_PTE_MAPPED_HUGEPAGE) and adds an entry
1335 * (for X) into mm_struct A's ->pte-mapped_thp[] array.
1336 * Thus, it's possible the same address is added multiple times for the same
1337 * mm_struct. Should this happen, we'll simply attempt
1338 * collapse_pte_mapped_thp() multiple times for the same address, under the same
1339 * exclusive mmap_lock, and assuming the first call is successful, subsequent
1340 * attempts will return quickly (without grabbing any additional locks) when
1341 * a huge pmd is found in find_pmd_or_thp_or_none(). Since this is a cheap
1342 * check, and since this is a rare occurrence, the cost of preventing this
1343 * "multiple-add" is thought to be more expensive than just handling it, should
1346 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1349 struct khugepaged_mm_slot *mm_slot;
1350 struct mm_slot *slot;
1353 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1355 spin_lock(&khugepaged_mm_lock);
1356 slot = mm_slot_lookup(mm_slots_hash, mm);
1357 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
1358 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) {
1359 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1362 spin_unlock(&khugepaged_mm_lock);
1366 /* hpage must be locked, and mmap_lock must be held in write */
1367 static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1368 pmd_t *pmdp, struct page *hpage)
1370 struct vm_fault vmf = {
1377 VM_BUG_ON(!PageTransHuge(hpage));
1378 mmap_assert_write_locked(vma->vm_mm);
1380 if (do_set_pmd(&vmf, hpage))
1384 return SCAN_SUCCEED;
1387 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1388 unsigned long addr, pmd_t *pmdp)
1393 mmap_assert_write_locked(mm);
1394 ptl = pmd_lock(vma->vm_mm, pmdp);
1395 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1398 page_table_check_pte_clear_range(mm, addr, pmd);
1399 pte_free(mm, pmd_pgtable(pmd));
1403 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1406 * @mm: process address space where collapse happens
1407 * @addr: THP collapse address
1408 * @install_pmd: If a huge PMD should be installed
1410 * This function checks whether all the PTEs in the PMD are pointing to the
1411 * right THP. If so, retract the page table so the THP can refault in with
1412 * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1414 int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1417 unsigned long haddr = addr & HPAGE_PMD_MASK;
1418 struct vm_area_struct *vma = vma_lookup(mm, haddr);
1420 pte_t *start_pte, *pte;
1423 int count = 0, result = SCAN_FAIL;
1426 mmap_assert_write_locked(mm);
1428 /* Fast check before locking page if already PMD-mapped */
1429 result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1430 if (result == SCAN_PMD_MAPPED)
1433 if (!vma || !vma->vm_file ||
1434 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1435 return SCAN_VMA_CHECK;
1438 * If we are here, we've succeeded in replacing all the native pages
1439 * in the page cache with a single hugepage. If a mm were to fault-in
1440 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1441 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1442 * analogously elide sysfs THP settings here.
1444 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
1445 return SCAN_VMA_CHECK;
1447 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1448 if (userfaultfd_wp(vma))
1449 return SCAN_PTE_UFFD_WP;
1451 hpage = find_lock_page(vma->vm_file->f_mapping,
1452 linear_page_index(vma, haddr));
1454 return SCAN_PAGE_NULL;
1456 if (!PageHead(hpage)) {
1461 if (compound_order(hpage) != HPAGE_PMD_ORDER) {
1462 result = SCAN_PAGE_COMPOUND;
1471 * In MADV_COLLAPSE path, possible race with khugepaged where
1472 * all pte entries have been removed and pmd cleared. If so,
1473 * skip all the pte checks and just update the pmd mapping.
1475 goto maybe_install_pmd;
1480 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1483 /* step 1: check all mapped PTEs are to the right huge page */
1484 for (i = 0, addr = haddr, pte = start_pte;
1485 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1488 /* empty pte, skip */
1492 /* page swapped out, abort */
1493 if (!pte_present(*pte)) {
1494 result = SCAN_PTE_NON_PRESENT;
1498 page = vm_normal_page(vma, addr, *pte);
1499 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1502 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1503 * page table, but the new page will not be a subpage of hpage.
1505 if (hpage + i != page)
1510 /* step 2: adjust rmap */
1511 for (i = 0, addr = haddr, pte = start_pte;
1512 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1517 page = vm_normal_page(vma, addr, *pte);
1518 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1520 page_remove_rmap(page, vma, false);
1523 pte_unmap_unlock(start_pte, ptl);
1525 /* step 3: set proper refcount and mm_counters. */
1527 page_ref_sub(hpage, count);
1528 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1531 /* step 4: remove pte entries */
1532 collapse_and_free_pmd(mm, vma, haddr, pmd);
1535 /* step 5: install pmd entry */
1536 result = install_pmd
1537 ? set_huge_pmd(vma, haddr, pmd, hpage)
1546 pte_unmap_unlock(start_pte, ptl);
1550 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
1552 struct mm_slot *slot = &mm_slot->slot;
1553 struct mm_struct *mm = slot->mm;
1556 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1559 if (!mmap_write_trylock(mm))
1562 if (unlikely(hpage_collapse_test_exit(mm)))
1565 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1566 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i], false);
1569 mm_slot->nr_pte_mapped_thp = 0;
1570 mmap_write_unlock(mm);
1573 static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff,
1574 struct mm_struct *target_mm,
1575 unsigned long target_addr, struct page *hpage,
1576 struct collapse_control *cc)
1578 struct vm_area_struct *vma;
1579 int target_result = SCAN_FAIL;
1581 i_mmap_lock_write(mapping);
1582 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1583 int result = SCAN_FAIL;
1584 struct mm_struct *mm = NULL;
1585 unsigned long addr = 0;
1587 bool is_target = false;
1590 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1591 * got written to. These VMAs are likely not worth investing
1592 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1595 * Note that vma->anon_vma check is racy: it can be set up after
1596 * the check but before we took mmap_lock by the fault path.
1597 * But page lock would prevent establishing any new ptes of the
1598 * page, so we are safe.
1600 * An alternative would be drop the check, but check that page
1601 * table is clear before calling pmdp_collapse_flush() under
1602 * ptl. It has higher chance to recover THP for the VMA, but
1603 * has higher cost too.
1605 if (vma->anon_vma) {
1606 result = SCAN_PAGE_ANON;
1609 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1610 if (addr & ~HPAGE_PMD_MASK ||
1611 vma->vm_end < addr + HPAGE_PMD_SIZE) {
1612 result = SCAN_VMA_CHECK;
1616 is_target = mm == target_mm && addr == target_addr;
1617 result = find_pmd_or_thp_or_none(mm, addr, &pmd);
1618 if (result != SCAN_SUCCEED)
1621 * We need exclusive mmap_lock to retract page table.
1623 * We use trylock due to lock inversion: we need to acquire
1624 * mmap_lock while holding page lock. Fault path does it in
1625 * reverse order. Trylock is a way to avoid deadlock.
1627 * Also, it's not MADV_COLLAPSE's job to collapse other
1628 * mappings - let khugepaged take care of them later.
1630 result = SCAN_PTE_MAPPED_HUGEPAGE;
1631 if ((cc->is_khugepaged || is_target) &&
1632 mmap_write_trylock(mm)) {
1634 * When a vma is registered with uffd-wp, we can't
1635 * recycle the pmd pgtable because there can be pte
1636 * markers installed. Skip it only, so the rest mm/vma
1637 * can still have the same file mapped hugely, however
1638 * it'll always mapped in small page size for uffd-wp
1639 * registered ranges.
1641 if (hpage_collapse_test_exit(mm)) {
1642 result = SCAN_ANY_PROCESS;
1645 if (userfaultfd_wp(vma)) {
1646 result = SCAN_PTE_UFFD_WP;
1649 collapse_and_free_pmd(mm, vma, addr, pmd);
1650 if (!cc->is_khugepaged && is_target)
1651 result = set_huge_pmd(vma, addr, pmd, hpage);
1653 result = SCAN_SUCCEED;
1656 mmap_write_unlock(mm);
1660 * Calling context will handle target mm/addr. Otherwise, let
1661 * khugepaged try again later.
1664 khugepaged_add_pte_mapped_thp(mm, addr);
1669 target_result = result;
1671 i_mmap_unlock_write(mapping);
1672 return target_result;
1676 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1678 * @mm: process address space where collapse happens
1679 * @addr: virtual collapse start address
1680 * @file: file that collapse on
1681 * @start: collapse start address
1682 * @cc: collapse context and scratchpad
1684 * Basic scheme is simple, details are more complex:
1685 * - allocate and lock a new huge page;
1686 * - scan page cache replacing old pages with the new one
1687 * + swap/gup in pages if necessary;
1689 * + keep old pages around in case rollback is required;
1690 * - if replacing succeeds:
1693 * + unlock huge page;
1694 * - if replacing failed;
1695 * + put all pages back and unfreeze them;
1696 * + restore gaps in the page cache;
1697 * + unlock and free huge page;
1699 static int collapse_file(struct mm_struct *mm, unsigned long addr,
1700 struct file *file, pgoff_t start,
1701 struct collapse_control *cc)
1703 struct address_space *mapping = file->f_mapping;
1705 pgoff_t index, end = start + HPAGE_PMD_NR;
1706 LIST_HEAD(pagelist);
1707 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1708 int nr_none = 0, result = SCAN_SUCCEED;
1709 bool is_shmem = shmem_file(file);
1712 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1713 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1715 result = alloc_charge_hpage(&hpage, mm, cc);
1716 if (result != SCAN_SUCCEED)
1720 * Ensure we have slots for all the pages in the range. This is
1721 * almost certainly a no-op because most of the pages must be present
1725 xas_create_range(&xas);
1726 if (!xas_error(&xas))
1728 xas_unlock_irq(&xas);
1729 if (!xas_nomem(&xas, GFP_KERNEL)) {
1735 __SetPageLocked(hpage);
1737 __SetPageSwapBacked(hpage);
1738 hpage->index = start;
1739 hpage->mapping = mapping;
1742 * At this point the hpage is locked and not up-to-date.
1743 * It's safe to insert it into the page cache, because nobody would
1744 * be able to map it or use it in another way until we unlock it.
1747 xas_set(&xas, start);
1748 for (index = start; index < end; index++) {
1749 struct page *page = xas_next(&xas);
1751 VM_BUG_ON(index != xas.xa_index);
1755 * Stop if extent has been truncated or
1756 * hole-punched, and is now completely
1759 if (index == start) {
1760 if (!xas_next_entry(&xas, end - 1)) {
1761 result = SCAN_TRUNCATED;
1764 xas_set(&xas, index);
1766 if (!shmem_charge(mapping->host, 1)) {
1770 xas_store(&xas, hpage);
1775 if (xa_is_value(page) || !PageUptodate(page)) {
1776 struct folio *folio;
1778 xas_unlock_irq(&xas);
1779 /* swap in or instantiate fallocated page */
1780 if (shmem_get_folio(mapping->host, index,
1781 &folio, SGP_NOALLOC)) {
1785 page = folio_file_page(folio, index);
1786 } else if (trylock_page(page)) {
1788 xas_unlock_irq(&xas);
1790 result = SCAN_PAGE_LOCK;
1793 } else { /* !is_shmem */
1794 if (!page || xa_is_value(page)) {
1795 xas_unlock_irq(&xas);
1796 page_cache_sync_readahead(mapping, &file->f_ra,
1799 /* drain pagevecs to help isolate_lru_page() */
1801 page = find_lock_page(mapping, index);
1802 if (unlikely(page == NULL)) {
1806 } else if (PageDirty(page)) {
1808 * khugepaged only works on read-only fd,
1809 * so this page is dirty because it hasn't
1810 * been flushed since first write. There
1811 * won't be new dirty pages.
1813 * Trigger async flush here and hope the
1814 * writeback is done when khugepaged
1815 * revisits this page.
1817 * This is a one-off situation. We are not
1818 * forcing writeback in loop.
1820 xas_unlock_irq(&xas);
1821 filemap_flush(mapping);
1824 } else if (PageWriteback(page)) {
1825 xas_unlock_irq(&xas);
1828 } else if (trylock_page(page)) {
1830 xas_unlock_irq(&xas);
1832 result = SCAN_PAGE_LOCK;
1838 * The page must be locked, so we can drop the i_pages lock
1839 * without racing with truncate.
1841 VM_BUG_ON_PAGE(!PageLocked(page), page);
1843 /* make sure the page is up to date */
1844 if (unlikely(!PageUptodate(page))) {
1850 * If file was truncated then extended, or hole-punched, before
1851 * we locked the first page, then a THP might be there already.
1852 * This will be discovered on the first iteration.
1854 if (PageTransCompound(page)) {
1855 struct page *head = compound_head(page);
1857 result = compound_order(head) == HPAGE_PMD_ORDER &&
1858 head->index == start
1859 /* Maybe PMD-mapped */
1860 ? SCAN_PTE_MAPPED_HUGEPAGE
1861 : SCAN_PAGE_COMPOUND;
1865 if (page_mapping(page) != mapping) {
1866 result = SCAN_TRUNCATED;
1870 if (!is_shmem && (PageDirty(page) ||
1871 PageWriteback(page))) {
1873 * khugepaged only works on read-only fd, so this
1874 * page is dirty because it hasn't been flushed
1875 * since first write.
1881 if (isolate_lru_page(page)) {
1882 result = SCAN_DEL_PAGE_LRU;
1886 if (page_has_private(page) &&
1887 !try_to_release_page(page, GFP_KERNEL)) {
1888 result = SCAN_PAGE_HAS_PRIVATE;
1889 putback_lru_page(page);
1893 if (page_mapped(page))
1894 try_to_unmap(page_folio(page),
1895 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1898 xas_set(&xas, index);
1900 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1903 * The page is expected to have page_count() == 3:
1904 * - we hold a pin on it;
1905 * - one reference from page cache;
1906 * - one from isolate_lru_page;
1908 if (!page_ref_freeze(page, 3)) {
1909 result = SCAN_PAGE_COUNT;
1910 xas_unlock_irq(&xas);
1911 putback_lru_page(page);
1916 * Add the page to the list to be able to undo the collapse if
1917 * something go wrong.
1919 list_add_tail(&page->lru, &pagelist);
1921 /* Finally, replace with the new page. */
1922 xas_store(&xas, hpage);
1929 nr = thp_nr_pages(hpage);
1932 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
1934 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
1935 filemap_nr_thps_inc(mapping);
1937 * Paired with smp_mb() in do_dentry_open() to ensure
1938 * i_writecount is up to date and the update to nr_thps is
1939 * visible. Ensures the page cache will be truncated if the
1940 * file is opened writable.
1943 if (inode_is_open_for_write(mapping->host)) {
1945 __mod_lruvec_page_state(hpage, NR_FILE_THPS, -nr);
1946 filemap_nr_thps_dec(mapping);
1952 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
1953 /* nr_none is always 0 for non-shmem. */
1954 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
1957 /* Join all the small entries into a single multi-index entry */
1958 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
1959 xas_store(&xas, hpage);
1961 xas_unlock_irq(&xas);
1965 * If collapse is successful, flush must be done now before copying.
1966 * If collapse is unsuccessful, does flush actually need to be done?
1967 * Do it anyway, to clear the state.
1969 try_to_unmap_flush();
1971 if (result == SCAN_SUCCEED) {
1972 struct page *page, *tmp;
1975 * Replacing old pages with new one has succeeded, now we
1976 * need to copy the content and free the old pages.
1979 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1980 while (index < page->index) {
1981 clear_highpage(hpage + (index % HPAGE_PMD_NR));
1984 copy_highpage(hpage + (page->index % HPAGE_PMD_NR),
1986 list_del(&page->lru);
1987 page->mapping = NULL;
1988 page_ref_unfreeze(page, 1);
1989 ClearPageActive(page);
1990 ClearPageUnevictable(page);
1995 while (index < end) {
1996 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2000 SetPageUptodate(hpage);
2001 page_ref_add(hpage, HPAGE_PMD_NR - 1);
2003 set_page_dirty(hpage);
2004 lru_cache_add(hpage);
2007 * Remove pte page tables, so we can re-fault the page as huge.
2009 result = retract_page_tables(mapping, start, mm, addr, hpage,
2016 /* Something went wrong: roll back page cache changes */
2019 mapping->nrpages -= nr_none;
2020 shmem_uncharge(mapping->host, nr_none);
2023 xas_set(&xas, start);
2024 xas_for_each(&xas, page, end - 1) {
2025 page = list_first_entry_or_null(&pagelist,
2027 if (!page || xas.xa_index < page->index) {
2031 /* Put holes back where they were */
2032 xas_store(&xas, NULL);
2036 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2038 /* Unfreeze the page. */
2039 list_del(&page->lru);
2040 page_ref_unfreeze(page, 2);
2041 xas_store(&xas, page);
2043 xas_unlock_irq(&xas);
2045 putback_lru_page(page);
2049 xas_unlock_irq(&xas);
2051 hpage->mapping = NULL;
2057 VM_BUG_ON(!list_empty(&pagelist));
2059 mem_cgroup_uncharge(page_folio(hpage));
2062 /* TODO: tracepoints */
2066 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2067 struct file *file, pgoff_t start,
2068 struct collapse_control *cc)
2070 struct page *page = NULL;
2071 struct address_space *mapping = file->f_mapping;
2072 XA_STATE(xas, &mapping->i_pages, start);
2074 int node = NUMA_NO_NODE;
2075 int result = SCAN_SUCCEED;
2079 memset(cc->node_load, 0, sizeof(cc->node_load));
2081 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2082 if (xas_retry(&xas, page))
2085 if (xa_is_value(page)) {
2087 if (cc->is_khugepaged &&
2088 swap > khugepaged_max_ptes_swap) {
2089 result = SCAN_EXCEED_SWAP_PTE;
2090 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2097 * TODO: khugepaged should compact smaller compound pages
2098 * into a PMD sized page
2100 if (PageTransCompound(page)) {
2101 struct page *head = compound_head(page);
2103 result = compound_order(head) == HPAGE_PMD_ORDER &&
2104 head->index == start
2105 /* Maybe PMD-mapped */
2106 ? SCAN_PTE_MAPPED_HUGEPAGE
2107 : SCAN_PAGE_COMPOUND;
2109 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2110 * by the caller won't touch the page cache, and so
2111 * it's safe to skip LRU and refcount checks before
2117 node = page_to_nid(page);
2118 if (hpage_collapse_scan_abort(node, cc)) {
2119 result = SCAN_SCAN_ABORT;
2122 cc->node_load[node]++;
2124 if (!PageLRU(page)) {
2125 result = SCAN_PAGE_LRU;
2129 if (page_count(page) !=
2130 1 + page_mapcount(page) + page_has_private(page)) {
2131 result = SCAN_PAGE_COUNT;
2136 * We probably should check if the page is referenced here, but
2137 * nobody would transfer pte_young() to PageReferenced() for us.
2138 * And rmap walk here is just too costly...
2143 if (need_resched()) {
2150 if (result == SCAN_SUCCEED) {
2151 if (cc->is_khugepaged &&
2152 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2153 result = SCAN_EXCEED_NONE_PTE;
2154 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2156 result = collapse_file(mm, addr, file, start, cc);
2160 trace_mm_khugepaged_scan_file(mm, page, file->f_path.dentry->d_iname,
2161 present, swap, result);
2165 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2166 struct file *file, pgoff_t start,
2167 struct collapse_control *cc)
2172 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
2176 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
2183 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2184 struct collapse_control *cc)
2185 __releases(&khugepaged_mm_lock)
2186 __acquires(&khugepaged_mm_lock)
2188 struct vma_iterator vmi;
2189 struct khugepaged_mm_slot *mm_slot;
2190 struct mm_slot *slot;
2191 struct mm_struct *mm;
2192 struct vm_area_struct *vma;
2196 lockdep_assert_held(&khugepaged_mm_lock);
2197 *result = SCAN_FAIL;
2199 if (khugepaged_scan.mm_slot) {
2200 mm_slot = khugepaged_scan.mm_slot;
2201 slot = &mm_slot->slot;
2203 slot = list_entry(khugepaged_scan.mm_head.next,
2204 struct mm_slot, mm_node);
2205 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2206 khugepaged_scan.address = 0;
2207 khugepaged_scan.mm_slot = mm_slot;
2209 spin_unlock(&khugepaged_mm_lock);
2210 khugepaged_collapse_pte_mapped_thps(mm_slot);
2214 * Don't wait for semaphore (to avoid long wait times). Just move to
2215 * the next mm on the list.
2218 if (unlikely(!mmap_read_trylock(mm)))
2219 goto breakouterloop_mmap_lock;
2222 if (unlikely(hpage_collapse_test_exit(mm)))
2223 goto breakouterloop;
2225 vma_iter_init(&vmi, mm, khugepaged_scan.address);
2226 for_each_vma(vmi, vma) {
2227 unsigned long hstart, hend;
2230 if (unlikely(hpage_collapse_test_exit(mm))) {
2234 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2239 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2240 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2241 if (khugepaged_scan.address > hend)
2243 if (khugepaged_scan.address < hstart)
2244 khugepaged_scan.address = hstart;
2245 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2247 while (khugepaged_scan.address < hend) {
2248 bool mmap_locked = true;
2251 if (unlikely(hpage_collapse_test_exit(mm)))
2252 goto breakouterloop;
2254 VM_BUG_ON(khugepaged_scan.address < hstart ||
2255 khugepaged_scan.address + HPAGE_PMD_SIZE >
2257 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2258 struct file *file = get_file(vma->vm_file);
2259 pgoff_t pgoff = linear_page_index(vma,
2260 khugepaged_scan.address);
2262 mmap_read_unlock(mm);
2263 *result = hpage_collapse_scan_file(mm,
2264 khugepaged_scan.address,
2266 mmap_locked = false;
2269 *result = hpage_collapse_scan_pmd(mm, vma,
2270 khugepaged_scan.address,
2275 case SCAN_PTE_MAPPED_HUGEPAGE: {
2278 *result = find_pmd_or_thp_or_none(mm,
2279 khugepaged_scan.address,
2281 if (*result != SCAN_SUCCEED)
2283 if (!khugepaged_add_pte_mapped_thp(mm,
2284 khugepaged_scan.address))
2288 ++khugepaged_pages_collapsed;
2294 /* move to next address */
2295 khugepaged_scan.address += HPAGE_PMD_SIZE;
2296 progress += HPAGE_PMD_NR;
2299 * We released mmap_lock so break loop. Note
2300 * that we drop mmap_lock before all hugepage
2301 * allocations, so if allocation fails, we are
2302 * guaranteed to break here and report the
2303 * correct result back to caller.
2305 goto breakouterloop_mmap_lock;
2306 if (progress >= pages)
2307 goto breakouterloop;
2311 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2312 breakouterloop_mmap_lock:
2314 spin_lock(&khugepaged_mm_lock);
2315 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2317 * Release the current mm_slot if this mm is about to die, or
2318 * if we scanned all vmas of this mm.
2320 if (hpage_collapse_test_exit(mm) || !vma) {
2322 * Make sure that if mm_users is reaching zero while
2323 * khugepaged runs here, khugepaged_exit will find
2324 * mm_slot not pointing to the exiting mm.
2326 if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2327 slot = list_entry(slot->mm_node.next,
2328 struct mm_slot, mm_node);
2329 khugepaged_scan.mm_slot =
2330 mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2331 khugepaged_scan.address = 0;
2333 khugepaged_scan.mm_slot = NULL;
2334 khugepaged_full_scans++;
2337 collect_mm_slot(mm_slot);
2343 static int khugepaged_has_work(void)
2345 return !list_empty(&khugepaged_scan.mm_head) &&
2346 hugepage_flags_enabled();
2349 static int khugepaged_wait_event(void)
2351 return !list_empty(&khugepaged_scan.mm_head) ||
2352 kthread_should_stop();
2355 static void khugepaged_do_scan(struct collapse_control *cc)
2357 unsigned int progress = 0, pass_through_head = 0;
2358 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2360 int result = SCAN_SUCCEED;
2362 lru_add_drain_all();
2367 if (unlikely(kthread_should_stop() || try_to_freeze()))
2370 spin_lock(&khugepaged_mm_lock);
2371 if (!khugepaged_scan.mm_slot)
2372 pass_through_head++;
2373 if (khugepaged_has_work() &&
2374 pass_through_head < 2)
2375 progress += khugepaged_scan_mm_slot(pages - progress,
2379 spin_unlock(&khugepaged_mm_lock);
2381 if (progress >= pages)
2384 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2386 * If fail to allocate the first time, try to sleep for
2387 * a while. When hit again, cancel the scan.
2392 khugepaged_alloc_sleep();
2397 static bool khugepaged_should_wakeup(void)
2399 return kthread_should_stop() ||
2400 time_after_eq(jiffies, khugepaged_sleep_expire);
2403 static void khugepaged_wait_work(void)
2405 if (khugepaged_has_work()) {
2406 const unsigned long scan_sleep_jiffies =
2407 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2409 if (!scan_sleep_jiffies)
2412 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2413 wait_event_freezable_timeout(khugepaged_wait,
2414 khugepaged_should_wakeup(),
2415 scan_sleep_jiffies);
2419 if (hugepage_flags_enabled())
2420 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2423 static int khugepaged(void *none)
2425 struct khugepaged_mm_slot *mm_slot;
2428 set_user_nice(current, MAX_NICE);
2430 while (!kthread_should_stop()) {
2431 khugepaged_do_scan(&khugepaged_collapse_control);
2432 khugepaged_wait_work();
2435 spin_lock(&khugepaged_mm_lock);
2436 mm_slot = khugepaged_scan.mm_slot;
2437 khugepaged_scan.mm_slot = NULL;
2439 collect_mm_slot(mm_slot);
2440 spin_unlock(&khugepaged_mm_lock);
2444 static void set_recommended_min_free_kbytes(void)
2448 unsigned long recommended_min;
2450 if (!hugepage_flags_enabled()) {
2451 calculate_min_free_kbytes();
2455 for_each_populated_zone(zone) {
2457 * We don't need to worry about fragmentation of
2458 * ZONE_MOVABLE since it only has movable pages.
2460 if (zone_idx(zone) > gfp_zone(GFP_USER))
2466 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2467 recommended_min = pageblock_nr_pages * nr_zones * 2;
2470 * Make sure that on average at least two pageblocks are almost free
2471 * of another type, one for a migratetype to fall back to and a
2472 * second to avoid subsequent fallbacks of other types There are 3
2473 * MIGRATE_TYPES we care about.
2475 recommended_min += pageblock_nr_pages * nr_zones *
2476 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2478 /* don't ever allow to reserve more than 5% of the lowmem */
2479 recommended_min = min(recommended_min,
2480 (unsigned long) nr_free_buffer_pages() / 20);
2481 recommended_min <<= (PAGE_SHIFT-10);
2483 if (recommended_min > min_free_kbytes) {
2484 if (user_min_free_kbytes >= 0)
2485 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2486 min_free_kbytes, recommended_min);
2488 min_free_kbytes = recommended_min;
2492 setup_per_zone_wmarks();
2495 int start_stop_khugepaged(void)
2499 mutex_lock(&khugepaged_mutex);
2500 if (hugepage_flags_enabled()) {
2501 if (!khugepaged_thread)
2502 khugepaged_thread = kthread_run(khugepaged, NULL,
2504 if (IS_ERR(khugepaged_thread)) {
2505 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2506 err = PTR_ERR(khugepaged_thread);
2507 khugepaged_thread = NULL;
2511 if (!list_empty(&khugepaged_scan.mm_head))
2512 wake_up_interruptible(&khugepaged_wait);
2513 } else if (khugepaged_thread) {
2514 kthread_stop(khugepaged_thread);
2515 khugepaged_thread = NULL;
2517 set_recommended_min_free_kbytes();
2519 mutex_unlock(&khugepaged_mutex);
2523 void khugepaged_min_free_kbytes_update(void)
2525 mutex_lock(&khugepaged_mutex);
2526 if (hugepage_flags_enabled() && khugepaged_thread)
2527 set_recommended_min_free_kbytes();
2528 mutex_unlock(&khugepaged_mutex);
2531 static int madvise_collapse_errno(enum scan_result r)
2534 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2535 * actionable feedback to caller, so they may take an appropriate
2536 * fallback measure depending on the nature of the failure.
2539 case SCAN_ALLOC_HUGE_PAGE_FAIL:
2541 case SCAN_CGROUP_CHARGE_FAIL:
2543 /* Resource temporary unavailable - trying again might succeed */
2544 case SCAN_PAGE_LOCK:
2546 case SCAN_DEL_PAGE_LRU:
2549 * Other: Trying again likely not to succeed / error intrinsic to
2550 * specified memory range. khugepaged likely won't be able to collapse
2558 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2559 unsigned long start, unsigned long end)
2561 struct collapse_control *cc;
2562 struct mm_struct *mm = vma->vm_mm;
2563 unsigned long hstart, hend, addr;
2564 int thps = 0, last_fail = SCAN_FAIL;
2565 bool mmap_locked = true;
2567 BUG_ON(vma->vm_start > start);
2568 BUG_ON(vma->vm_end < end);
2572 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2575 cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2578 cc->is_khugepaged = false;
2579 cc->last_target_node = NUMA_NO_NODE;
2582 lru_add_drain_all();
2584 hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2585 hend = end & HPAGE_PMD_MASK;
2587 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2588 int result = SCAN_FAIL;
2594 result = hugepage_vma_revalidate(mm, addr, false, &vma,
2596 if (result != SCAN_SUCCEED) {
2601 hend = vma->vm_end & HPAGE_PMD_MASK;
2603 mmap_assert_locked(mm);
2604 memset(cc->node_load, 0, sizeof(cc->node_load));
2605 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2606 struct file *file = get_file(vma->vm_file);
2607 pgoff_t pgoff = linear_page_index(vma, addr);
2609 mmap_read_unlock(mm);
2610 mmap_locked = false;
2611 result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2615 result = hpage_collapse_scan_pmd(mm, vma, addr,
2619 *prev = NULL; /* Tell caller we dropped mmap_lock */
2624 case SCAN_PMD_MAPPED:
2627 case SCAN_PTE_MAPPED_HUGEPAGE:
2628 BUG_ON(mmap_locked);
2630 mmap_write_lock(mm);
2631 result = collapse_pte_mapped_thp(mm, addr, true);
2632 mmap_write_unlock(mm);
2634 /* Whitelisted set of results where continuing OK */
2636 case SCAN_PTE_NON_PRESENT:
2637 case SCAN_PTE_UFFD_WP:
2639 case SCAN_LACK_REFERENCED_PAGE:
2640 case SCAN_PAGE_NULL:
2641 case SCAN_PAGE_COUNT:
2642 case SCAN_PAGE_LOCK:
2643 case SCAN_PAGE_COMPOUND:
2645 case SCAN_DEL_PAGE_LRU:
2650 /* Other error, exit */
2656 /* Caller expects us to hold mmap_lock on return */
2660 mmap_assert_locked(mm);
2664 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2665 : madvise_collapse_errno(last_fail);