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 __read_mostly DEFINE_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 mm_slot = mm_slot_alloc(mm_slot_cache);
429 slot = &mm_slot->slot;
431 /* __khugepaged_exit() must not run from under us */
432 VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
433 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
434 mm_slot_free(mm_slot_cache, mm_slot);
438 spin_lock(&khugepaged_mm_lock);
439 mm_slot_insert(mm_slots_hash, mm, slot);
441 * Insert just behind the scanning cursor, to let the area settle
444 wakeup = list_empty(&khugepaged_scan.mm_head);
445 list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
446 spin_unlock(&khugepaged_mm_lock);
450 wake_up_interruptible(&khugepaged_wait);
453 void khugepaged_enter_vma(struct vm_area_struct *vma,
454 unsigned long vm_flags)
456 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
457 hugepage_flags_enabled()) {
458 if (hugepage_vma_check(vma, vm_flags, false, false, true))
459 __khugepaged_enter(vma->vm_mm);
463 void __khugepaged_exit(struct mm_struct *mm)
465 struct khugepaged_mm_slot *mm_slot;
466 struct mm_slot *slot;
469 spin_lock(&khugepaged_mm_lock);
470 slot = mm_slot_lookup(mm_slots_hash, mm);
471 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
472 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
473 hash_del(&slot->hash);
474 list_del(&slot->mm_node);
477 spin_unlock(&khugepaged_mm_lock);
480 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
481 mm_slot_free(mm_slot_cache, mm_slot);
483 } else if (mm_slot) {
485 * This is required to serialize against
486 * hpage_collapse_test_exit() (which is guaranteed to run
487 * under mmap sem read mode). Stop here (after we return all
488 * pagetables will be destroyed) until khugepaged has finished
489 * working on the pagetables under the mmap_lock.
492 mmap_write_unlock(mm);
496 static void release_pte_folio(struct folio *folio)
498 node_stat_mod_folio(folio,
499 NR_ISOLATED_ANON + folio_is_file_lru(folio),
500 -folio_nr_pages(folio));
502 folio_putback_lru(folio);
505 static void release_pte_page(struct page *page)
507 release_pte_folio(page_folio(page));
510 static void release_pte_pages(pte_t *pte, pte_t *_pte,
511 struct list_head *compound_pagelist)
513 struct folio *folio, *tmp;
515 while (--_pte >= pte) {
516 pte_t pteval = *_pte;
519 if (pte_none(pteval))
521 pfn = pte_pfn(pteval);
522 if (is_zero_pfn(pfn))
524 folio = pfn_folio(pfn);
525 if (folio_test_large(folio))
527 release_pte_folio(folio);
530 list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
531 list_del(&folio->lru);
532 release_pte_folio(folio);
536 static bool is_refcount_suitable(struct page *page)
538 int expected_refcount;
540 expected_refcount = total_mapcount(page);
541 if (PageSwapCache(page))
542 expected_refcount += compound_nr(page);
544 return page_count(page) == expected_refcount;
547 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
548 unsigned long address,
550 struct collapse_control *cc,
551 struct list_head *compound_pagelist)
553 struct page *page = NULL;
555 int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
556 bool writable = false;
558 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
559 _pte++, address += PAGE_SIZE) {
560 pte_t pteval = *_pte;
561 if (pte_none(pteval) || (pte_present(pteval) &&
562 is_zero_pfn(pte_pfn(pteval)))) {
564 if (!userfaultfd_armed(vma) &&
565 (!cc->is_khugepaged ||
566 none_or_zero <= khugepaged_max_ptes_none)) {
569 result = SCAN_EXCEED_NONE_PTE;
570 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
574 if (!pte_present(pteval)) {
575 result = SCAN_PTE_NON_PRESENT;
578 if (pte_uffd_wp(pteval)) {
579 result = SCAN_PTE_UFFD_WP;
582 page = vm_normal_page(vma, address, pteval);
583 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
584 result = SCAN_PAGE_NULL;
588 VM_BUG_ON_PAGE(!PageAnon(page), page);
590 if (page_mapcount(page) > 1) {
592 if (cc->is_khugepaged &&
593 shared > khugepaged_max_ptes_shared) {
594 result = SCAN_EXCEED_SHARED_PTE;
595 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
600 if (PageCompound(page)) {
602 page = compound_head(page);
605 * Check if we have dealt with the compound page
608 list_for_each_entry(p, compound_pagelist, lru) {
615 * We can do it before isolate_lru_page because the
616 * page can't be freed from under us. NOTE: PG_lock
617 * is needed to serialize against split_huge_page
618 * when invoked from the VM.
620 if (!trylock_page(page)) {
621 result = SCAN_PAGE_LOCK;
626 * Check if the page has any GUP (or other external) pins.
628 * The page table that maps the page has been already unlinked
629 * from the page table tree and this process cannot get
630 * an additional pin on the page.
632 * New pins can come later if the page is shared across fork,
633 * but not from this process. The other process cannot write to
634 * the page, only trigger CoW.
636 if (!is_refcount_suitable(page)) {
638 result = SCAN_PAGE_COUNT;
643 * Isolate the page to avoid collapsing an hugepage
644 * currently in use by the VM.
646 if (!isolate_lru_page(page)) {
648 result = SCAN_DEL_PAGE_LRU;
651 mod_node_page_state(page_pgdat(page),
652 NR_ISOLATED_ANON + page_is_file_lru(page),
654 VM_BUG_ON_PAGE(!PageLocked(page), page);
655 VM_BUG_ON_PAGE(PageLRU(page), page);
657 if (PageCompound(page))
658 list_add_tail(&page->lru, compound_pagelist);
661 * If collapse was initiated by khugepaged, check that there is
662 * enough young pte to justify collapsing the page
664 if (cc->is_khugepaged &&
665 (pte_young(pteval) || page_is_young(page) ||
666 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
670 if (pte_write(pteval))
674 if (unlikely(!writable)) {
675 result = SCAN_PAGE_RO;
676 } else if (unlikely(cc->is_khugepaged && !referenced)) {
677 result = SCAN_LACK_REFERENCED_PAGE;
679 result = SCAN_SUCCEED;
680 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
681 referenced, writable, result);
685 release_pte_pages(pte, _pte, compound_pagelist);
686 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
687 referenced, writable, result);
691 static void __collapse_huge_page_copy_succeeded(pte_t *pte,
692 struct vm_area_struct *vma,
693 unsigned long address,
695 struct list_head *compound_pagelist)
697 struct page *src_page;
702 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
703 _pte++, address += PAGE_SIZE) {
705 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
706 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
707 if (is_zero_pfn(pte_pfn(pteval))) {
709 * ptl mostly unnecessary.
712 ptep_clear(vma->vm_mm, address, _pte);
716 src_page = pte_page(pteval);
717 if (!PageCompound(src_page))
718 release_pte_page(src_page);
720 * ptl mostly unnecessary, but preempt has to
721 * be disabled to update the per-cpu stats
722 * inside page_remove_rmap().
725 ptep_clear(vma->vm_mm, address, _pte);
726 page_remove_rmap(src_page, vma, false);
728 free_page_and_swap_cache(src_page);
732 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
733 list_del(&src_page->lru);
734 mod_node_page_state(page_pgdat(src_page),
735 NR_ISOLATED_ANON + page_is_file_lru(src_page),
736 -compound_nr(src_page));
737 unlock_page(src_page);
738 free_swap_cache(src_page);
739 putback_lru_page(src_page);
743 static void __collapse_huge_page_copy_failed(pte_t *pte,
746 struct vm_area_struct *vma,
747 struct list_head *compound_pagelist)
752 * Re-establish the PMD to point to the original page table
753 * entry. Restoring PMD needs to be done prior to releasing
754 * pages. Since pages are still isolated and locked here,
755 * acquiring anon_vma_lock_write is unnecessary.
757 pmd_ptl = pmd_lock(vma->vm_mm, pmd);
758 pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd));
759 spin_unlock(pmd_ptl);
761 * Release both raw and compound pages isolated
762 * in __collapse_huge_page_isolate.
764 release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist);
768 * __collapse_huge_page_copy - attempts to copy memory contents from raw
769 * pages to a hugepage. Cleans up the raw pages if copying succeeds;
770 * otherwise restores the original page table and releases isolated raw pages.
771 * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC.
773 * @pte: starting of the PTEs to copy from
774 * @page: the new hugepage to copy contents to
775 * @pmd: pointer to the new hugepage's PMD
776 * @orig_pmd: the original raw pages' PMD
777 * @vma: the original raw pages' virtual memory area
778 * @address: starting address to copy
779 * @ptl: lock on raw pages' PTEs
780 * @compound_pagelist: list that stores compound pages
782 static int __collapse_huge_page_copy(pte_t *pte,
786 struct vm_area_struct *vma,
787 unsigned long address,
789 struct list_head *compound_pagelist)
791 struct page *src_page;
794 unsigned long _address;
795 int result = SCAN_SUCCEED;
798 * Copying pages' contents is subject to memory poison at any iteration.
800 for (_pte = pte, _address = address; _pte < pte + HPAGE_PMD_NR;
801 _pte++, page++, _address += PAGE_SIZE) {
803 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
804 clear_user_highpage(page, _address);
807 src_page = pte_page(pteval);
808 if (copy_mc_user_highpage(page, src_page, _address, vma) > 0) {
809 result = SCAN_COPY_MC;
814 if (likely(result == SCAN_SUCCEED))
815 __collapse_huge_page_copy_succeeded(pte, vma, address, ptl,
818 __collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma,
824 static void khugepaged_alloc_sleep(void)
828 add_wait_queue(&khugepaged_wait, &wait);
829 __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
830 schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
831 remove_wait_queue(&khugepaged_wait, &wait);
834 struct collapse_control khugepaged_collapse_control = {
835 .is_khugepaged = true,
838 static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
843 * If node_reclaim_mode is disabled, then no extra effort is made to
844 * allocate memory locally.
846 if (!node_reclaim_enabled())
849 /* If there is a count for this node already, it must be acceptable */
850 if (cc->node_load[nid])
853 for (i = 0; i < MAX_NUMNODES; i++) {
854 if (!cc->node_load[i])
856 if (node_distance(nid, i) > node_reclaim_distance)
862 #define khugepaged_defrag() \
863 (transparent_hugepage_flags & \
864 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
866 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
867 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
869 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
873 static int hpage_collapse_find_target_node(struct collapse_control *cc)
875 int nid, target_node = 0, max_value = 0;
877 /* find first node with max normal pages hit */
878 for (nid = 0; nid < MAX_NUMNODES; nid++)
879 if (cc->node_load[nid] > max_value) {
880 max_value = cc->node_load[nid];
884 for_each_online_node(nid) {
885 if (max_value == cc->node_load[nid])
886 node_set(nid, cc->alloc_nmask);
892 static int hpage_collapse_find_target_node(struct collapse_control *cc)
898 static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node,
901 *hpage = __alloc_pages(gfp, HPAGE_PMD_ORDER, node, nmask);
902 if (unlikely(!*hpage)) {
903 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
907 prep_transhuge_page(*hpage);
908 count_vm_event(THP_COLLAPSE_ALLOC);
913 * If mmap_lock temporarily dropped, revalidate vma
914 * before taking mmap_lock.
915 * Returns enum scan_result value.
918 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
920 struct vm_area_struct **vmap,
921 struct collapse_control *cc)
923 struct vm_area_struct *vma;
925 if (unlikely(hpage_collapse_test_exit(mm)))
926 return SCAN_ANY_PROCESS;
928 *vmap = vma = find_vma(mm, address);
930 return SCAN_VMA_NULL;
932 if (!transhuge_vma_suitable(vma, address))
933 return SCAN_ADDRESS_RANGE;
934 if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
936 return SCAN_VMA_CHECK;
938 * Anon VMA expected, the address may be unmapped then
939 * remapped to file after khugepaged reaquired the mmap_lock.
941 * hugepage_vma_check may return true for qualified file
944 if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
945 return SCAN_PAGE_ANON;
950 * See pmd_trans_unstable() for how the result may change out from
951 * underneath us, even if we hold mmap_lock in read.
953 static int find_pmd_or_thp_or_none(struct mm_struct *mm,
954 unsigned long address,
959 *pmd = mm_find_pmd(mm, address);
961 return SCAN_PMD_NULL;
963 pmde = pmdp_get_lockless(*pmd);
965 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
966 /* See comments in pmd_none_or_trans_huge_or_clear_bad() */
970 return SCAN_PMD_NONE;
971 if (!pmd_present(pmde))
972 return SCAN_PMD_NULL;
973 if (pmd_trans_huge(pmde))
974 return SCAN_PMD_MAPPED;
975 if (pmd_devmap(pmde))
976 return SCAN_PMD_NULL;
978 return SCAN_PMD_NULL;
982 static int check_pmd_still_valid(struct mm_struct *mm,
983 unsigned long address,
987 int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
989 if (result != SCAN_SUCCEED)
997 * Bring missing pages in from swap, to complete THP collapse.
998 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
1000 * Called and returns without pte mapped or spinlocks held.
1001 * Note that if false is returned, mmap_lock will be released.
1004 static int __collapse_huge_page_swapin(struct mm_struct *mm,
1005 struct vm_area_struct *vma,
1006 unsigned long haddr, pmd_t *pmd,
1011 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
1013 for (address = haddr; address < end; address += PAGE_SIZE) {
1014 struct vm_fault vmf = {
1017 .pgoff = linear_page_index(vma, haddr),
1018 .flags = FAULT_FLAG_ALLOW_RETRY,
1022 vmf.pte = pte_offset_map(pmd, address);
1023 vmf.orig_pte = *vmf.pte;
1024 if (!is_swap_pte(vmf.orig_pte)) {
1028 ret = do_swap_page(&vmf);
1031 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
1032 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
1033 * we do not retry here and swap entry will remain in pagetable
1034 * resulting in later failure.
1036 if (ret & VM_FAULT_RETRY) {
1037 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
1038 /* Likely, but not guaranteed, that page lock failed */
1039 return SCAN_PAGE_LOCK;
1041 if (ret & VM_FAULT_ERROR) {
1042 mmap_read_unlock(mm);
1043 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
1049 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
1053 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
1054 return SCAN_SUCCEED;
1057 static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
1058 struct collapse_control *cc)
1060 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
1062 int node = hpage_collapse_find_target_node(cc);
1063 struct folio *folio;
1065 if (!hpage_collapse_alloc_page(hpage, gfp, node, &cc->alloc_nmask))
1066 return SCAN_ALLOC_HUGE_PAGE_FAIL;
1068 folio = page_folio(*hpage);
1069 if (unlikely(mem_cgroup_charge(folio, mm, gfp))) {
1072 return SCAN_CGROUP_CHARGE_FAIL;
1074 count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
1076 return SCAN_SUCCEED;
1079 static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
1080 int referenced, int unmapped,
1081 struct collapse_control *cc)
1083 LIST_HEAD(compound_pagelist);
1088 spinlock_t *pmd_ptl, *pte_ptl;
1089 int result = SCAN_FAIL;
1090 struct vm_area_struct *vma;
1091 struct mmu_notifier_range range;
1093 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1096 * Before allocating the hugepage, release the mmap_lock read lock.
1097 * The allocation can take potentially a long time if it involves
1098 * sync compaction, and we do not need to hold the mmap_lock during
1099 * that. We will recheck the vma after taking it again in write mode.
1101 mmap_read_unlock(mm);
1103 result = alloc_charge_hpage(&hpage, mm, cc);
1104 if (result != SCAN_SUCCEED)
1108 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1109 if (result != SCAN_SUCCEED) {
1110 mmap_read_unlock(mm);
1114 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1115 if (result != SCAN_SUCCEED) {
1116 mmap_read_unlock(mm);
1122 * __collapse_huge_page_swapin will return with mmap_lock
1123 * released when it fails. So we jump out_nolock directly in
1124 * that case. Continuing to collapse causes inconsistency.
1126 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1128 if (result != SCAN_SUCCEED)
1132 mmap_read_unlock(mm);
1134 * Prevent all access to pagetables with the exception of
1135 * gup_fast later handled by the ptep_clear_flush and the VM
1136 * handled by the anon_vma lock + PG_lock.
1138 mmap_write_lock(mm);
1139 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1140 if (result != SCAN_SUCCEED)
1142 /* check if the pmd is still valid */
1143 result = check_pmd_still_valid(mm, address, pmd);
1144 if (result != SCAN_SUCCEED)
1147 vma_start_write(vma);
1148 anon_vma_lock_write(vma->anon_vma);
1150 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
1151 address + HPAGE_PMD_SIZE);
1152 mmu_notifier_invalidate_range_start(&range);
1154 pte = pte_offset_map(pmd, address);
1155 pte_ptl = pte_lockptr(mm, pmd);
1157 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1159 * This removes any huge TLB entry from the CPU so we won't allow
1160 * huge and small TLB entries for the same virtual address to
1161 * avoid the risk of CPU bugs in that area.
1163 * Parallel fast GUP is fine since fast GUP will back off when
1164 * it detects PMD is changed.
1166 _pmd = pmdp_collapse_flush(vma, address, pmd);
1167 spin_unlock(pmd_ptl);
1168 mmu_notifier_invalidate_range_end(&range);
1169 tlb_remove_table_sync_one();
1172 result = __collapse_huge_page_isolate(vma, address, pte, cc,
1173 &compound_pagelist);
1174 spin_unlock(pte_ptl);
1176 if (unlikely(result != SCAN_SUCCEED)) {
1179 BUG_ON(!pmd_none(*pmd));
1181 * We can only use set_pmd_at when establishing
1182 * hugepmds and never for establishing regular pmds that
1183 * points to regular pagetables. Use pmd_populate for that
1185 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1186 spin_unlock(pmd_ptl);
1187 anon_vma_unlock_write(vma->anon_vma);
1192 * All pages are isolated and locked so anon_vma rmap
1193 * can't run anymore.
1195 anon_vma_unlock_write(vma->anon_vma);
1197 result = __collapse_huge_page_copy(pte, hpage, pmd, _pmd,
1198 vma, address, pte_ptl,
1199 &compound_pagelist);
1201 if (unlikely(result != SCAN_SUCCEED))
1205 * spin_lock() below is not the equivalent of smp_wmb(), but
1206 * the smp_wmb() inside __SetPageUptodate() can be reused to
1207 * avoid the copy_huge_page writes to become visible after
1208 * the set_pmd_at() write.
1210 __SetPageUptodate(hpage);
1211 pgtable = pmd_pgtable(_pmd);
1213 _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1214 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1217 BUG_ON(!pmd_none(*pmd));
1218 page_add_new_anon_rmap(hpage, vma, address);
1219 lru_cache_add_inactive_or_unevictable(hpage, vma);
1220 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1221 set_pmd_at(mm, address, pmd, _pmd);
1222 update_mmu_cache_pmd(vma, address, pmd);
1223 spin_unlock(pmd_ptl);
1227 result = SCAN_SUCCEED;
1229 mmap_write_unlock(mm);
1233 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1237 static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1238 struct vm_area_struct *vma,
1239 unsigned long address, bool *mmap_locked,
1240 struct collapse_control *cc)
1244 int result = SCAN_FAIL, referenced = 0;
1245 int none_or_zero = 0, shared = 0;
1246 struct page *page = NULL;
1247 unsigned long _address;
1249 int node = NUMA_NO_NODE, unmapped = 0;
1250 bool writable = false;
1252 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1254 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1255 if (result != SCAN_SUCCEED)
1258 memset(cc->node_load, 0, sizeof(cc->node_load));
1259 nodes_clear(cc->alloc_nmask);
1260 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1261 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1262 _pte++, _address += PAGE_SIZE) {
1263 pte_t pteval = *_pte;
1264 if (is_swap_pte(pteval)) {
1266 if (!cc->is_khugepaged ||
1267 unmapped <= khugepaged_max_ptes_swap) {
1269 * Always be strict with uffd-wp
1270 * enabled swap entries. Please see
1271 * comment below for pte_uffd_wp().
1273 if (pte_swp_uffd_wp_any(pteval)) {
1274 result = SCAN_PTE_UFFD_WP;
1279 result = SCAN_EXCEED_SWAP_PTE;
1280 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1284 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1286 if (!userfaultfd_armed(vma) &&
1287 (!cc->is_khugepaged ||
1288 none_or_zero <= khugepaged_max_ptes_none)) {
1291 result = SCAN_EXCEED_NONE_PTE;
1292 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1296 if (pte_uffd_wp(pteval)) {
1298 * Don't collapse the page if any of the small
1299 * PTEs are armed with uffd write protection.
1300 * Here we can also mark the new huge pmd as
1301 * write protected if any of the small ones is
1302 * marked but that could bring unknown
1303 * userfault messages that falls outside of
1304 * the registered range. So, just be simple.
1306 result = SCAN_PTE_UFFD_WP;
1309 if (pte_write(pteval))
1312 page = vm_normal_page(vma, _address, pteval);
1313 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1314 result = SCAN_PAGE_NULL;
1318 if (page_mapcount(page) > 1) {
1320 if (cc->is_khugepaged &&
1321 shared > khugepaged_max_ptes_shared) {
1322 result = SCAN_EXCEED_SHARED_PTE;
1323 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1328 page = compound_head(page);
1331 * Record which node the original page is from and save this
1332 * information to cc->node_load[].
1333 * Khugepaged will allocate hugepage from the node has the max
1336 node = page_to_nid(page);
1337 if (hpage_collapse_scan_abort(node, cc)) {
1338 result = SCAN_SCAN_ABORT;
1341 cc->node_load[node]++;
1342 if (!PageLRU(page)) {
1343 result = SCAN_PAGE_LRU;
1346 if (PageLocked(page)) {
1347 result = SCAN_PAGE_LOCK;
1350 if (!PageAnon(page)) {
1351 result = SCAN_PAGE_ANON;
1356 * Check if the page has any GUP (or other external) pins.
1358 * Here the check may be racy:
1359 * it may see total_mapcount > refcount in some cases?
1360 * But such case is ephemeral we could always retry collapse
1361 * later. However it may report false positive if the page
1362 * has excessive GUP pins (i.e. 512). Anyway the same check
1363 * will be done again later the risk seems low.
1365 if (!is_refcount_suitable(page)) {
1366 result = SCAN_PAGE_COUNT;
1371 * If collapse was initiated by khugepaged, check that there is
1372 * enough young pte to justify collapsing the page
1374 if (cc->is_khugepaged &&
1375 (pte_young(pteval) || page_is_young(page) ||
1376 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1381 result = SCAN_PAGE_RO;
1382 } else if (cc->is_khugepaged &&
1384 (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1385 result = SCAN_LACK_REFERENCED_PAGE;
1387 result = SCAN_SUCCEED;
1390 pte_unmap_unlock(pte, ptl);
1391 if (result == SCAN_SUCCEED) {
1392 result = collapse_huge_page(mm, address, referenced,
1394 /* collapse_huge_page will return with the mmap_lock released */
1395 *mmap_locked = false;
1398 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1399 none_or_zero, result, unmapped);
1403 static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1405 struct mm_slot *slot = &mm_slot->slot;
1406 struct mm_struct *mm = slot->mm;
1408 lockdep_assert_held(&khugepaged_mm_lock);
1410 if (hpage_collapse_test_exit(mm)) {
1412 hash_del(&slot->hash);
1413 list_del(&slot->mm_node);
1416 * Not strictly needed because the mm exited already.
1418 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1421 /* khugepaged_mm_lock actually not necessary for the below */
1422 mm_slot_free(mm_slot_cache, mm_slot);
1429 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1430 * khugepaged should try to collapse the page table.
1432 * Note that following race exists:
1433 * (1) khugepaged calls khugepaged_collapse_pte_mapped_thps() for mm_struct A,
1434 * emptying the A's ->pte_mapped_thp[] array.
1435 * (2) MADV_COLLAPSE collapses some file extent with target mm_struct B, and
1436 * retract_page_tables() finds a VMA in mm_struct A mapping the same extent
1437 * (at virtual address X) and adds an entry (for X) into mm_struct A's
1438 * ->pte-mapped_thp[] array.
1439 * (3) khugepaged calls khugepaged_collapse_scan_file() for mm_struct A at X,
1440 * sees a pte-mapped THP (SCAN_PTE_MAPPED_HUGEPAGE) and adds an entry
1441 * (for X) into mm_struct A's ->pte-mapped_thp[] array.
1442 * Thus, it's possible the same address is added multiple times for the same
1443 * mm_struct. Should this happen, we'll simply attempt
1444 * collapse_pte_mapped_thp() multiple times for the same address, under the same
1445 * exclusive mmap_lock, and assuming the first call is successful, subsequent
1446 * attempts will return quickly (without grabbing any additional locks) when
1447 * a huge pmd is found in find_pmd_or_thp_or_none(). Since this is a cheap
1448 * check, and since this is a rare occurrence, the cost of preventing this
1449 * "multiple-add" is thought to be more expensive than just handling it, should
1452 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1455 struct khugepaged_mm_slot *mm_slot;
1456 struct mm_slot *slot;
1459 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1461 spin_lock(&khugepaged_mm_lock);
1462 slot = mm_slot_lookup(mm_slots_hash, mm);
1463 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
1464 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) {
1465 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1468 spin_unlock(&khugepaged_mm_lock);
1472 /* hpage must be locked, and mmap_lock must be held in write */
1473 static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1474 pmd_t *pmdp, struct page *hpage)
1476 struct vm_fault vmf = {
1483 VM_BUG_ON(!PageTransHuge(hpage));
1484 mmap_assert_write_locked(vma->vm_mm);
1486 if (do_set_pmd(&vmf, hpage))
1490 return SCAN_SUCCEED;
1494 * A note about locking:
1495 * Trying to take the page table spinlocks would be useless here because those
1496 * are only used to synchronize:
1498 * - modifying terminal entries (ones that point to a data page, not to another
1500 * - installing *new* non-terminal entries
1502 * Instead, we need roughly the same kind of protection as free_pgtables() or
1503 * mm_take_all_locks() (but only for a single VMA):
1504 * The mmap lock together with this VMA's rmap locks covers all paths towards
1505 * the page table entries we're messing with here, except for hardware page
1506 * table walks and lockless_pages_from_mm().
1508 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1509 unsigned long addr, pmd_t *pmdp)
1512 struct mmu_notifier_range range;
1514 mmap_assert_write_locked(mm);
1516 lockdep_assert_held_write(&vma->vm_file->f_mapping->i_mmap_rwsem);
1518 * All anon_vmas attached to the VMA have the same root and are
1519 * therefore locked by the same lock.
1522 lockdep_assert_held_write(&vma->anon_vma->root->rwsem);
1524 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
1525 addr + HPAGE_PMD_SIZE);
1526 mmu_notifier_invalidate_range_start(&range);
1527 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1528 tlb_remove_table_sync_one();
1529 mmu_notifier_invalidate_range_end(&range);
1531 page_table_check_pte_clear_range(mm, addr, pmd);
1532 pte_free(mm, pmd_pgtable(pmd));
1536 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1539 * @mm: process address space where collapse happens
1540 * @addr: THP collapse address
1541 * @install_pmd: If a huge PMD should be installed
1543 * This function checks whether all the PTEs in the PMD are pointing to the
1544 * right THP. If so, retract the page table so the THP can refault in with
1545 * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1547 int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1550 unsigned long haddr = addr & HPAGE_PMD_MASK;
1551 struct vm_area_struct *vma = vma_lookup(mm, haddr);
1553 pte_t *start_pte, *pte;
1556 int count = 0, result = SCAN_FAIL;
1559 mmap_assert_write_locked(mm);
1561 /* Fast check before locking page if already PMD-mapped */
1562 result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1563 if (result == SCAN_PMD_MAPPED)
1566 if (!vma || !vma->vm_file ||
1567 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1568 return SCAN_VMA_CHECK;
1571 * If we are here, we've succeeded in replacing all the native pages
1572 * in the page cache with a single hugepage. If a mm were to fault-in
1573 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1574 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1575 * analogously elide sysfs THP settings here.
1577 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
1578 return SCAN_VMA_CHECK;
1580 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1581 if (userfaultfd_wp(vma))
1582 return SCAN_PTE_UFFD_WP;
1584 hpage = find_lock_page(vma->vm_file->f_mapping,
1585 linear_page_index(vma, haddr));
1587 return SCAN_PAGE_NULL;
1589 if (!PageHead(hpage)) {
1594 if (compound_order(hpage) != HPAGE_PMD_ORDER) {
1595 result = SCAN_PAGE_COMPOUND;
1604 * In MADV_COLLAPSE path, possible race with khugepaged where
1605 * all pte entries have been removed and pmd cleared. If so,
1606 * skip all the pte checks and just update the pmd mapping.
1608 goto maybe_install_pmd;
1613 /* Lock the vma before taking i_mmap and page table locks */
1614 vma_start_write(vma);
1617 * We need to lock the mapping so that from here on, only GUP-fast and
1618 * hardware page walks can access the parts of the page tables that
1619 * we're operating on.
1620 * See collapse_and_free_pmd().
1622 i_mmap_lock_write(vma->vm_file->f_mapping);
1625 * This spinlock should be unnecessary: Nobody else should be accessing
1626 * the page tables under spinlock protection here, only
1627 * lockless_pages_from_mm() and the hardware page walker can access page
1628 * tables while all the high-level locks are held in write mode.
1630 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1633 /* step 1: check all mapped PTEs are to the right huge page */
1634 for (i = 0, addr = haddr, pte = start_pte;
1635 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1638 /* empty pte, skip */
1642 /* page swapped out, abort */
1643 if (!pte_present(*pte)) {
1644 result = SCAN_PTE_NON_PRESENT;
1648 page = vm_normal_page(vma, addr, *pte);
1649 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1652 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1653 * page table, but the new page will not be a subpage of hpage.
1655 if (hpage + i != page)
1660 /* step 2: adjust rmap */
1661 for (i = 0, addr = haddr, pte = start_pte;
1662 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1667 page = vm_normal_page(vma, addr, *pte);
1668 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1670 page_remove_rmap(page, vma, false);
1673 pte_unmap_unlock(start_pte, ptl);
1675 /* step 3: set proper refcount and mm_counters. */
1677 page_ref_sub(hpage, count);
1678 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1681 /* step 4: remove pte entries */
1682 /* we make no change to anon, but protect concurrent anon page lookup */
1684 anon_vma_lock_write(vma->anon_vma);
1686 collapse_and_free_pmd(mm, vma, haddr, pmd);
1689 anon_vma_unlock_write(vma->anon_vma);
1690 i_mmap_unlock_write(vma->vm_file->f_mapping);
1693 /* step 5: install pmd entry */
1694 result = install_pmd
1695 ? set_huge_pmd(vma, haddr, pmd, hpage)
1704 pte_unmap_unlock(start_pte, ptl);
1705 i_mmap_unlock_write(vma->vm_file->f_mapping);
1709 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
1711 struct mm_slot *slot = &mm_slot->slot;
1712 struct mm_struct *mm = slot->mm;
1715 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1718 if (!mmap_write_trylock(mm))
1721 if (unlikely(hpage_collapse_test_exit(mm)))
1724 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1725 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i], false);
1728 mm_slot->nr_pte_mapped_thp = 0;
1729 mmap_write_unlock(mm);
1732 static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff,
1733 struct mm_struct *target_mm,
1734 unsigned long target_addr, struct page *hpage,
1735 struct collapse_control *cc)
1737 struct vm_area_struct *vma;
1738 int target_result = SCAN_FAIL;
1740 i_mmap_lock_write(mapping);
1741 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1742 int result = SCAN_FAIL;
1743 struct mm_struct *mm = NULL;
1744 unsigned long addr = 0;
1746 bool is_target = false;
1749 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1750 * got written to. These VMAs are likely not worth investing
1751 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1754 * Note that vma->anon_vma check is racy: it can be set up after
1755 * the check but before we took mmap_lock by the fault path.
1756 * But page lock would prevent establishing any new ptes of the
1757 * page, so we are safe.
1759 * An alternative would be drop the check, but check that page
1760 * table is clear before calling pmdp_collapse_flush() under
1761 * ptl. It has higher chance to recover THP for the VMA, but
1762 * has higher cost too. It would also probably require locking
1765 if (READ_ONCE(vma->anon_vma)) {
1766 result = SCAN_PAGE_ANON;
1769 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1770 if (addr & ~HPAGE_PMD_MASK ||
1771 vma->vm_end < addr + HPAGE_PMD_SIZE) {
1772 result = SCAN_VMA_CHECK;
1776 is_target = mm == target_mm && addr == target_addr;
1777 result = find_pmd_or_thp_or_none(mm, addr, &pmd);
1778 if (result != SCAN_SUCCEED)
1781 * We need exclusive mmap_lock to retract page table.
1783 * We use trylock due to lock inversion: we need to acquire
1784 * mmap_lock while holding page lock. Fault path does it in
1785 * reverse order. Trylock is a way to avoid deadlock.
1787 * Also, it's not MADV_COLLAPSE's job to collapse other
1788 * mappings - let khugepaged take care of them later.
1790 result = SCAN_PTE_MAPPED_HUGEPAGE;
1791 if ((cc->is_khugepaged || is_target) &&
1792 mmap_write_trylock(mm)) {
1793 /* trylock for the same lock inversion as above */
1794 if (!vma_try_start_write(vma))
1798 * Re-check whether we have an ->anon_vma, because
1799 * collapse_and_free_pmd() requires that either no
1800 * ->anon_vma exists or the anon_vma is locked.
1801 * We already checked ->anon_vma above, but that check
1802 * is racy because ->anon_vma can be populated under the
1803 * mmap lock in read mode.
1805 if (vma->anon_vma) {
1806 result = SCAN_PAGE_ANON;
1810 * When a vma is registered with uffd-wp, we can't
1811 * recycle the pmd pgtable because there can be pte
1812 * markers installed. Skip it only, so the rest mm/vma
1813 * can still have the same file mapped hugely, however
1814 * it'll always mapped in small page size for uffd-wp
1815 * registered ranges.
1817 if (hpage_collapse_test_exit(mm)) {
1818 result = SCAN_ANY_PROCESS;
1821 if (userfaultfd_wp(vma)) {
1822 result = SCAN_PTE_UFFD_WP;
1825 collapse_and_free_pmd(mm, vma, addr, pmd);
1826 if (!cc->is_khugepaged && is_target)
1827 result = set_huge_pmd(vma, addr, pmd, hpage);
1829 result = SCAN_SUCCEED;
1832 mmap_write_unlock(mm);
1836 * Calling context will handle target mm/addr. Otherwise, let
1837 * khugepaged try again later.
1840 khugepaged_add_pte_mapped_thp(mm, addr);
1845 target_result = result;
1847 i_mmap_unlock_write(mapping);
1848 return target_result;
1852 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1854 * @mm: process address space where collapse happens
1855 * @addr: virtual collapse start address
1856 * @file: file that collapse on
1857 * @start: collapse start address
1858 * @cc: collapse context and scratchpad
1860 * Basic scheme is simple, details are more complex:
1861 * - allocate and lock a new huge page;
1862 * - scan page cache, locking old pages
1863 * + swap/gup in pages if necessary;
1864 * - copy data to new page
1865 * - handle shmem holes
1866 * + re-validate that holes weren't filled by someone else
1867 * + check for userfaultfd
1868 * - finalize updates to the page cache;
1869 * - if replacing succeeds:
1870 * + unlock huge page;
1872 * - if replacing failed;
1873 * + unlock old pages
1874 * + unlock and free huge page;
1876 static int collapse_file(struct mm_struct *mm, unsigned long addr,
1877 struct file *file, pgoff_t start,
1878 struct collapse_control *cc)
1880 struct address_space *mapping = file->f_mapping;
1884 struct folio *folio;
1885 pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1886 LIST_HEAD(pagelist);
1887 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1888 int nr_none = 0, result = SCAN_SUCCEED;
1889 bool is_shmem = shmem_file(file);
1892 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1893 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1895 result = alloc_charge_hpage(&hpage, mm, cc);
1896 if (result != SCAN_SUCCEED)
1899 __SetPageLocked(hpage);
1901 __SetPageSwapBacked(hpage);
1902 hpage->index = start;
1903 hpage->mapping = mapping;
1906 * Ensure we have slots for all the pages in the range. This is
1907 * almost certainly a no-op because most of the pages must be present
1911 xas_create_range(&xas);
1912 if (!xas_error(&xas))
1914 xas_unlock_irq(&xas);
1915 if (!xas_nomem(&xas, GFP_KERNEL)) {
1921 xas_set(&xas, start);
1922 for (index = start; index < end; index++) {
1923 page = xas_next(&xas);
1925 VM_BUG_ON(index != xas.xa_index);
1929 * Stop if extent has been truncated or
1930 * hole-punched, and is now completely
1933 if (index == start) {
1934 if (!xas_next_entry(&xas, end - 1)) {
1935 result = SCAN_TRUNCATED;
1938 xas_set(&xas, index + 1);
1940 if (!shmem_charge(mapping->host, 1)) {
1948 if (xa_is_value(page) || !PageUptodate(page)) {
1949 xas_unlock_irq(&xas);
1950 /* swap in or instantiate fallocated page */
1951 if (shmem_get_folio(mapping->host, index,
1952 &folio, SGP_NOALLOC)) {
1956 /* drain pagevecs to help isolate_lru_page() */
1958 page = folio_file_page(folio, index);
1959 } else if (trylock_page(page)) {
1961 xas_unlock_irq(&xas);
1963 result = SCAN_PAGE_LOCK;
1966 } else { /* !is_shmem */
1967 if (!page || xa_is_value(page)) {
1968 xas_unlock_irq(&xas);
1969 page_cache_sync_readahead(mapping, &file->f_ra,
1972 /* drain pagevecs to help isolate_lru_page() */
1974 page = find_lock_page(mapping, index);
1975 if (unlikely(page == NULL)) {
1979 } else if (PageDirty(page)) {
1981 * khugepaged only works on read-only fd,
1982 * so this page is dirty because it hasn't
1983 * been flushed since first write. There
1984 * won't be new dirty pages.
1986 * Trigger async flush here and hope the
1987 * writeback is done when khugepaged
1988 * revisits this page.
1990 * This is a one-off situation. We are not
1991 * forcing writeback in loop.
1993 xas_unlock_irq(&xas);
1994 filemap_flush(mapping);
1997 } else if (PageWriteback(page)) {
1998 xas_unlock_irq(&xas);
2001 } else if (trylock_page(page)) {
2003 xas_unlock_irq(&xas);
2005 result = SCAN_PAGE_LOCK;
2011 * The page must be locked, so we can drop the i_pages lock
2012 * without racing with truncate.
2014 VM_BUG_ON_PAGE(!PageLocked(page), page);
2016 /* make sure the page is up to date */
2017 if (unlikely(!PageUptodate(page))) {
2023 * If file was truncated then extended, or hole-punched, before
2024 * we locked the first page, then a THP might be there already.
2025 * This will be discovered on the first iteration.
2027 if (PageTransCompound(page)) {
2028 struct page *head = compound_head(page);
2030 result = compound_order(head) == HPAGE_PMD_ORDER &&
2031 head->index == start
2032 /* Maybe PMD-mapped */
2033 ? SCAN_PTE_MAPPED_HUGEPAGE
2034 : SCAN_PAGE_COMPOUND;
2038 folio = page_folio(page);
2040 if (folio_mapping(folio) != mapping) {
2041 result = SCAN_TRUNCATED;
2045 if (!is_shmem && (folio_test_dirty(folio) ||
2046 folio_test_writeback(folio))) {
2048 * khugepaged only works on read-only fd, so this
2049 * page is dirty because it hasn't been flushed
2050 * since first write.
2056 if (!folio_isolate_lru(folio)) {
2057 result = SCAN_DEL_PAGE_LRU;
2061 if (folio_has_private(folio) &&
2062 !filemap_release_folio(folio, GFP_KERNEL)) {
2063 result = SCAN_PAGE_HAS_PRIVATE;
2064 folio_putback_lru(folio);
2068 if (folio_mapped(folio))
2070 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
2074 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
2077 * We control three references to the page:
2078 * - we hold a pin on it;
2079 * - one reference from page cache;
2080 * - one from isolate_lru_page;
2081 * If those are the only references, then any new usage of the
2082 * page will have to fetch it from the page cache. That requires
2083 * locking the page to handle truncate, so any new usage will be
2084 * blocked until we unlock page after collapse/during rollback.
2086 if (page_count(page) != 3) {
2087 result = SCAN_PAGE_COUNT;
2088 xas_unlock_irq(&xas);
2089 putback_lru_page(page);
2094 * Accumulate the pages that are being collapsed.
2096 list_add_tail(&page->lru, &pagelist);
2105 filemap_nr_thps_inc(mapping);
2107 * Paired with smp_mb() in do_dentry_open() to ensure
2108 * i_writecount is up to date and the update to nr_thps is
2109 * visible. Ensures the page cache will be truncated if the
2110 * file is opened writable.
2113 if (inode_is_open_for_write(mapping->host)) {
2115 filemap_nr_thps_dec(mapping);
2120 xas_unlock_irq(&xas);
2124 * If collapse is successful, flush must be done now before copying.
2125 * If collapse is unsuccessful, does flush actually need to be done?
2126 * Do it anyway, to clear the state.
2128 try_to_unmap_flush();
2130 if (result != SCAN_SUCCEED)
2134 * The old pages are locked, so they won't change anymore.
2137 list_for_each_entry(page, &pagelist, lru) {
2138 while (index < page->index) {
2139 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2142 if (copy_mc_highpage(hpage + (page->index % HPAGE_PMD_NR), page) > 0) {
2143 result = SCAN_COPY_MC;
2148 while (index < end) {
2149 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2154 struct vm_area_struct *vma;
2155 int nr_none_check = 0;
2157 i_mmap_lock_read(mapping);
2160 xas_set(&xas, start);
2161 for (index = start; index < end; index++) {
2162 if (!xas_next(&xas)) {
2163 xas_store(&xas, XA_RETRY_ENTRY);
2164 if (xas_error(&xas)) {
2165 result = SCAN_STORE_FAILED;
2172 if (nr_none != nr_none_check) {
2173 result = SCAN_PAGE_FILLED;
2178 * If userspace observed a missing page in a VMA with a MODE_MISSING
2179 * userfaultfd, then it might expect a UFFD_EVENT_PAGEFAULT for that
2180 * page. If so, we need to roll back to avoid suppressing such an
2181 * event. Since wp/minor userfaultfds don't give userspace any
2182 * guarantees that the kernel doesn't fill a missing page with a zero
2183 * page, so they don't matter here.
2185 * Any userfaultfds registered after this point will not be able to
2186 * observe any missing pages due to the previously inserted retry
2189 vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2190 if (userfaultfd_missing(vma)) {
2191 result = SCAN_EXCEED_NONE_PTE;
2197 i_mmap_unlock_read(mapping);
2198 if (result != SCAN_SUCCEED) {
2199 xas_set(&xas, start);
2200 for (index = start; index < end; index++) {
2201 if (xas_next(&xas) == XA_RETRY_ENTRY)
2202 xas_store(&xas, NULL);
2205 xas_unlock_irq(&xas);
2212 nr = thp_nr_pages(hpage);
2214 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
2216 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
2219 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
2220 /* nr_none is always 0 for non-shmem. */
2221 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2225 * Mark hpage as uptodate before inserting it into the page cache so
2226 * that it isn't mistaken for an fallocated but unwritten page.
2228 folio = page_folio(hpage);
2229 folio_mark_uptodate(folio);
2230 folio_ref_add(folio, HPAGE_PMD_NR - 1);
2233 folio_mark_dirty(folio);
2234 folio_add_lru(folio);
2236 /* Join all the small entries into a single multi-index entry. */
2237 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2238 xas_store(&xas, hpage);
2239 WARN_ON_ONCE(xas_error(&xas));
2240 xas_unlock_irq(&xas);
2243 * Remove pte page tables, so we can re-fault the page as huge.
2245 result = retract_page_tables(mapping, start, mm, addr, hpage,
2250 * The collapse has succeeded, so free the old pages.
2252 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2253 list_del(&page->lru);
2254 page->mapping = NULL;
2255 ClearPageActive(page);
2256 ClearPageUnevictable(page);
2258 folio_put_refs(page_folio(page), 3);
2264 /* Something went wrong: roll back page cache changes */
2267 mapping->nrpages -= nr_none;
2268 shmem_uncharge(mapping->host, nr_none);
2269 xas_unlock_irq(&xas);
2272 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2273 list_del(&page->lru);
2275 putback_lru_page(page);
2279 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
2280 * file only. This undo is not needed unless failure is
2281 * due to SCAN_COPY_MC.
2283 if (!is_shmem && result == SCAN_COPY_MC) {
2284 filemap_nr_thps_dec(mapping);
2286 * Paired with smp_mb() in do_dentry_open() to
2287 * ensure the update to nr_thps is visible.
2292 hpage->mapping = NULL;
2297 VM_BUG_ON(!list_empty(&pagelist));
2298 trace_mm_khugepaged_collapse_file(mm, hpage, index, is_shmem, addr, file, nr, result);
2302 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2303 struct file *file, pgoff_t start,
2304 struct collapse_control *cc)
2306 struct page *page = NULL;
2307 struct address_space *mapping = file->f_mapping;
2308 XA_STATE(xas, &mapping->i_pages, start);
2310 int node = NUMA_NO_NODE;
2311 int result = SCAN_SUCCEED;
2315 memset(cc->node_load, 0, sizeof(cc->node_load));
2316 nodes_clear(cc->alloc_nmask);
2318 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2319 if (xas_retry(&xas, page))
2322 if (xa_is_value(page)) {
2324 if (cc->is_khugepaged &&
2325 swap > khugepaged_max_ptes_swap) {
2326 result = SCAN_EXCEED_SWAP_PTE;
2327 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2334 * TODO: khugepaged should compact smaller compound pages
2335 * into a PMD sized page
2337 if (PageTransCompound(page)) {
2338 struct page *head = compound_head(page);
2340 result = compound_order(head) == HPAGE_PMD_ORDER &&
2341 head->index == start
2342 /* Maybe PMD-mapped */
2343 ? SCAN_PTE_MAPPED_HUGEPAGE
2344 : SCAN_PAGE_COMPOUND;
2346 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2347 * by the caller won't touch the page cache, and so
2348 * it's safe to skip LRU and refcount checks before
2354 node = page_to_nid(page);
2355 if (hpage_collapse_scan_abort(node, cc)) {
2356 result = SCAN_SCAN_ABORT;
2359 cc->node_load[node]++;
2361 if (!PageLRU(page)) {
2362 result = SCAN_PAGE_LRU;
2366 if (page_count(page) !=
2367 1 + page_mapcount(page) + page_has_private(page)) {
2368 result = SCAN_PAGE_COUNT;
2373 * We probably should check if the page is referenced here, but
2374 * nobody would transfer pte_young() to PageReferenced() for us.
2375 * And rmap walk here is just too costly...
2380 if (need_resched()) {
2387 if (result == SCAN_SUCCEED) {
2388 if (cc->is_khugepaged &&
2389 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2390 result = SCAN_EXCEED_NONE_PTE;
2391 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2393 result = collapse_file(mm, addr, file, start, cc);
2397 trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
2401 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2402 struct file *file, pgoff_t start,
2403 struct collapse_control *cc)
2408 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
2412 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
2419 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2420 struct collapse_control *cc)
2421 __releases(&khugepaged_mm_lock)
2422 __acquires(&khugepaged_mm_lock)
2424 struct vma_iterator vmi;
2425 struct khugepaged_mm_slot *mm_slot;
2426 struct mm_slot *slot;
2427 struct mm_struct *mm;
2428 struct vm_area_struct *vma;
2432 lockdep_assert_held(&khugepaged_mm_lock);
2433 *result = SCAN_FAIL;
2435 if (khugepaged_scan.mm_slot) {
2436 mm_slot = khugepaged_scan.mm_slot;
2437 slot = &mm_slot->slot;
2439 slot = list_entry(khugepaged_scan.mm_head.next,
2440 struct mm_slot, mm_node);
2441 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2442 khugepaged_scan.address = 0;
2443 khugepaged_scan.mm_slot = mm_slot;
2445 spin_unlock(&khugepaged_mm_lock);
2446 khugepaged_collapse_pte_mapped_thps(mm_slot);
2450 * Don't wait for semaphore (to avoid long wait times). Just move to
2451 * the next mm on the list.
2454 if (unlikely(!mmap_read_trylock(mm)))
2455 goto breakouterloop_mmap_lock;
2458 if (unlikely(hpage_collapse_test_exit(mm)))
2459 goto breakouterloop;
2461 vma_iter_init(&vmi, mm, khugepaged_scan.address);
2462 for_each_vma(vmi, vma) {
2463 unsigned long hstart, hend;
2466 if (unlikely(hpage_collapse_test_exit(mm))) {
2470 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2475 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2476 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2477 if (khugepaged_scan.address > hend)
2479 if (khugepaged_scan.address < hstart)
2480 khugepaged_scan.address = hstart;
2481 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2483 while (khugepaged_scan.address < hend) {
2484 bool mmap_locked = true;
2487 if (unlikely(hpage_collapse_test_exit(mm)))
2488 goto breakouterloop;
2490 VM_BUG_ON(khugepaged_scan.address < hstart ||
2491 khugepaged_scan.address + HPAGE_PMD_SIZE >
2493 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2494 struct file *file = get_file(vma->vm_file);
2495 pgoff_t pgoff = linear_page_index(vma,
2496 khugepaged_scan.address);
2498 mmap_read_unlock(mm);
2499 *result = hpage_collapse_scan_file(mm,
2500 khugepaged_scan.address,
2502 mmap_locked = false;
2505 *result = hpage_collapse_scan_pmd(mm, vma,
2506 khugepaged_scan.address,
2511 case SCAN_PTE_MAPPED_HUGEPAGE: {
2514 *result = find_pmd_or_thp_or_none(mm,
2515 khugepaged_scan.address,
2517 if (*result != SCAN_SUCCEED)
2519 if (!khugepaged_add_pte_mapped_thp(mm,
2520 khugepaged_scan.address))
2524 ++khugepaged_pages_collapsed;
2530 /* move to next address */
2531 khugepaged_scan.address += HPAGE_PMD_SIZE;
2532 progress += HPAGE_PMD_NR;
2535 * We released mmap_lock so break loop. Note
2536 * that we drop mmap_lock before all hugepage
2537 * allocations, so if allocation fails, we are
2538 * guaranteed to break here and report the
2539 * correct result back to caller.
2541 goto breakouterloop_mmap_lock;
2542 if (progress >= pages)
2543 goto breakouterloop;
2547 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2548 breakouterloop_mmap_lock:
2550 spin_lock(&khugepaged_mm_lock);
2551 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2553 * Release the current mm_slot if this mm is about to die, or
2554 * if we scanned all vmas of this mm.
2556 if (hpage_collapse_test_exit(mm) || !vma) {
2558 * Make sure that if mm_users is reaching zero while
2559 * khugepaged runs here, khugepaged_exit will find
2560 * mm_slot not pointing to the exiting mm.
2562 if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2563 slot = list_entry(slot->mm_node.next,
2564 struct mm_slot, mm_node);
2565 khugepaged_scan.mm_slot =
2566 mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2567 khugepaged_scan.address = 0;
2569 khugepaged_scan.mm_slot = NULL;
2570 khugepaged_full_scans++;
2573 collect_mm_slot(mm_slot);
2579 static int khugepaged_has_work(void)
2581 return !list_empty(&khugepaged_scan.mm_head) &&
2582 hugepage_flags_enabled();
2585 static int khugepaged_wait_event(void)
2587 return !list_empty(&khugepaged_scan.mm_head) ||
2588 kthread_should_stop();
2591 static void khugepaged_do_scan(struct collapse_control *cc)
2593 unsigned int progress = 0, pass_through_head = 0;
2594 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2596 int result = SCAN_SUCCEED;
2598 lru_add_drain_all();
2603 if (unlikely(kthread_should_stop() || try_to_freeze()))
2606 spin_lock(&khugepaged_mm_lock);
2607 if (!khugepaged_scan.mm_slot)
2608 pass_through_head++;
2609 if (khugepaged_has_work() &&
2610 pass_through_head < 2)
2611 progress += khugepaged_scan_mm_slot(pages - progress,
2615 spin_unlock(&khugepaged_mm_lock);
2617 if (progress >= pages)
2620 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2622 * If fail to allocate the first time, try to sleep for
2623 * a while. When hit again, cancel the scan.
2628 khugepaged_alloc_sleep();
2633 static bool khugepaged_should_wakeup(void)
2635 return kthread_should_stop() ||
2636 time_after_eq(jiffies, khugepaged_sleep_expire);
2639 static void khugepaged_wait_work(void)
2641 if (khugepaged_has_work()) {
2642 const unsigned long scan_sleep_jiffies =
2643 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2645 if (!scan_sleep_jiffies)
2648 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2649 wait_event_freezable_timeout(khugepaged_wait,
2650 khugepaged_should_wakeup(),
2651 scan_sleep_jiffies);
2655 if (hugepage_flags_enabled())
2656 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2659 static int khugepaged(void *none)
2661 struct khugepaged_mm_slot *mm_slot;
2664 set_user_nice(current, MAX_NICE);
2666 while (!kthread_should_stop()) {
2667 khugepaged_do_scan(&khugepaged_collapse_control);
2668 khugepaged_wait_work();
2671 spin_lock(&khugepaged_mm_lock);
2672 mm_slot = khugepaged_scan.mm_slot;
2673 khugepaged_scan.mm_slot = NULL;
2675 collect_mm_slot(mm_slot);
2676 spin_unlock(&khugepaged_mm_lock);
2680 static void set_recommended_min_free_kbytes(void)
2684 unsigned long recommended_min;
2686 if (!hugepage_flags_enabled()) {
2687 calculate_min_free_kbytes();
2691 for_each_populated_zone(zone) {
2693 * We don't need to worry about fragmentation of
2694 * ZONE_MOVABLE since it only has movable pages.
2696 if (zone_idx(zone) > gfp_zone(GFP_USER))
2702 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2703 recommended_min = pageblock_nr_pages * nr_zones * 2;
2706 * Make sure that on average at least two pageblocks are almost free
2707 * of another type, one for a migratetype to fall back to and a
2708 * second to avoid subsequent fallbacks of other types There are 3
2709 * MIGRATE_TYPES we care about.
2711 recommended_min += pageblock_nr_pages * nr_zones *
2712 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2714 /* don't ever allow to reserve more than 5% of the lowmem */
2715 recommended_min = min(recommended_min,
2716 (unsigned long) nr_free_buffer_pages() / 20);
2717 recommended_min <<= (PAGE_SHIFT-10);
2719 if (recommended_min > min_free_kbytes) {
2720 if (user_min_free_kbytes >= 0)
2721 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2722 min_free_kbytes, recommended_min);
2724 min_free_kbytes = recommended_min;
2728 setup_per_zone_wmarks();
2731 int start_stop_khugepaged(void)
2735 mutex_lock(&khugepaged_mutex);
2736 if (hugepage_flags_enabled()) {
2737 if (!khugepaged_thread)
2738 khugepaged_thread = kthread_run(khugepaged, NULL,
2740 if (IS_ERR(khugepaged_thread)) {
2741 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2742 err = PTR_ERR(khugepaged_thread);
2743 khugepaged_thread = NULL;
2747 if (!list_empty(&khugepaged_scan.mm_head))
2748 wake_up_interruptible(&khugepaged_wait);
2749 } else if (khugepaged_thread) {
2750 kthread_stop(khugepaged_thread);
2751 khugepaged_thread = NULL;
2753 set_recommended_min_free_kbytes();
2755 mutex_unlock(&khugepaged_mutex);
2759 void khugepaged_min_free_kbytes_update(void)
2761 mutex_lock(&khugepaged_mutex);
2762 if (hugepage_flags_enabled() && khugepaged_thread)
2763 set_recommended_min_free_kbytes();
2764 mutex_unlock(&khugepaged_mutex);
2767 bool current_is_khugepaged(void)
2769 return kthread_func(current) == khugepaged;
2772 static int madvise_collapse_errno(enum scan_result r)
2775 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2776 * actionable feedback to caller, so they may take an appropriate
2777 * fallback measure depending on the nature of the failure.
2780 case SCAN_ALLOC_HUGE_PAGE_FAIL:
2782 case SCAN_CGROUP_CHARGE_FAIL:
2783 case SCAN_EXCEED_NONE_PTE:
2785 /* Resource temporary unavailable - trying again might succeed */
2786 case SCAN_PAGE_COUNT:
2787 case SCAN_PAGE_LOCK:
2789 case SCAN_DEL_PAGE_LRU:
2790 case SCAN_PAGE_FILLED:
2793 * Other: Trying again likely not to succeed / error intrinsic to
2794 * specified memory range. khugepaged likely won't be able to collapse
2802 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2803 unsigned long start, unsigned long end)
2805 struct collapse_control *cc;
2806 struct mm_struct *mm = vma->vm_mm;
2807 unsigned long hstart, hend, addr;
2808 int thps = 0, last_fail = SCAN_FAIL;
2809 bool mmap_locked = true;
2811 BUG_ON(vma->vm_start > start);
2812 BUG_ON(vma->vm_end < end);
2816 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2819 cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2822 cc->is_khugepaged = false;
2825 lru_add_drain_all();
2827 hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2828 hend = end & HPAGE_PMD_MASK;
2830 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2831 int result = SCAN_FAIL;
2837 result = hugepage_vma_revalidate(mm, addr, false, &vma,
2839 if (result != SCAN_SUCCEED) {
2844 hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
2846 mmap_assert_locked(mm);
2847 memset(cc->node_load, 0, sizeof(cc->node_load));
2848 nodes_clear(cc->alloc_nmask);
2849 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2850 struct file *file = get_file(vma->vm_file);
2851 pgoff_t pgoff = linear_page_index(vma, addr);
2853 mmap_read_unlock(mm);
2854 mmap_locked = false;
2855 result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2859 result = hpage_collapse_scan_pmd(mm, vma, addr,
2863 *prev = NULL; /* Tell caller we dropped mmap_lock */
2868 case SCAN_PMD_MAPPED:
2871 case SCAN_PTE_MAPPED_HUGEPAGE:
2872 BUG_ON(mmap_locked);
2874 mmap_write_lock(mm);
2875 result = collapse_pte_mapped_thp(mm, addr, true);
2876 mmap_write_unlock(mm);
2878 /* Whitelisted set of results where continuing OK */
2880 case SCAN_PTE_NON_PRESENT:
2881 case SCAN_PTE_UFFD_WP:
2883 case SCAN_LACK_REFERENCED_PAGE:
2884 case SCAN_PAGE_NULL:
2885 case SCAN_PAGE_COUNT:
2886 case SCAN_PAGE_LOCK:
2887 case SCAN_PAGE_COMPOUND:
2889 case SCAN_DEL_PAGE_LRU:
2894 /* Other error, exit */
2900 /* Caller expects us to hold mmap_lock on return */
2904 mmap_assert_locked(mm);
2908 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2909 : madvise_collapse_errno(last_fail);