1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
5 #include <linux/sched.h>
6 #include <linux/sched/mm.h>
7 #include <linux/sched/coredump.h>
8 #include <linux/mmu_notifier.h>
9 #include <linux/rmap.h>
10 #include <linux/swap.h>
11 #include <linux/mm_inline.h>
12 #include <linux/kthread.h>
13 #include <linux/khugepaged.h>
14 #include <linux/freezer.h>
15 #include <linux/mman.h>
16 #include <linux/hashtable.h>
17 #include <linux/userfaultfd_k.h>
18 #include <linux/page_idle.h>
19 #include <linux/page_table_check.h>
20 #include <linux/swapops.h>
21 #include <linux/shmem_fs.h>
24 #include <asm/pgalloc.h>
33 SCAN_EXCEED_SHARED_PTE,
37 SCAN_LACK_REFERENCED_PAGE,
51 SCAN_ALLOC_HUGE_PAGE_FAIL,
52 SCAN_CGROUP_CHARGE_FAIL,
54 SCAN_PAGE_HAS_PRIVATE,
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/huge_memory.h>
60 static struct task_struct *khugepaged_thread __read_mostly;
61 static DEFINE_MUTEX(khugepaged_mutex);
63 /* default scan 8*512 pte (or vmas) every 30 second */
64 static unsigned int khugepaged_pages_to_scan __read_mostly;
65 static unsigned int khugepaged_pages_collapsed;
66 static unsigned int khugepaged_full_scans;
67 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
68 /* during fragmentation poll the hugepage allocator once every minute */
69 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
70 static unsigned long khugepaged_sleep_expire;
71 static DEFINE_SPINLOCK(khugepaged_mm_lock);
72 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
74 * default collapse hugepages if there is at least one pte mapped like
75 * it would have happened if the vma was large enough during page
78 static unsigned int khugepaged_max_ptes_none __read_mostly;
79 static unsigned int khugepaged_max_ptes_swap __read_mostly;
80 static unsigned int khugepaged_max_ptes_shared __read_mostly;
82 #define MM_SLOTS_HASH_BITS 10
83 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
85 static struct kmem_cache *mm_slot_cache __read_mostly;
87 #define MAX_PTE_MAPPED_THP 8
90 * struct mm_slot - hash lookup from mm to mm_slot
91 * @hash: hash collision list
92 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
93 * @mm: the mm that this information is valid for
94 * @nr_pte_mapped_thp: number of pte mapped THP
95 * @pte_mapped_thp: address array corresponding pte mapped THP
98 struct hlist_node hash;
99 struct list_head mm_node;
100 struct mm_struct *mm;
102 /* pte-mapped THP in this mm */
103 int nr_pte_mapped_thp;
104 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
108 * struct khugepaged_scan - cursor for scanning
109 * @mm_head: the head of the mm list to scan
110 * @mm_slot: the current mm_slot we are scanning
111 * @address: the next address inside that to be scanned
113 * There is only the one khugepaged_scan instance of this cursor structure.
115 struct khugepaged_scan {
116 struct list_head mm_head;
117 struct mm_slot *mm_slot;
118 unsigned long address;
121 static struct khugepaged_scan khugepaged_scan = {
122 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
126 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
127 struct kobj_attribute *attr,
130 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
133 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
134 struct kobj_attribute *attr,
135 const char *buf, size_t count)
140 err = kstrtouint(buf, 10, &msecs);
144 khugepaged_scan_sleep_millisecs = msecs;
145 khugepaged_sleep_expire = 0;
146 wake_up_interruptible(&khugepaged_wait);
150 static struct kobj_attribute scan_sleep_millisecs_attr =
151 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
152 scan_sleep_millisecs_store);
154 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
155 struct kobj_attribute *attr,
158 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
161 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
162 struct kobj_attribute *attr,
163 const char *buf, size_t count)
168 err = kstrtouint(buf, 10, &msecs);
172 khugepaged_alloc_sleep_millisecs = msecs;
173 khugepaged_sleep_expire = 0;
174 wake_up_interruptible(&khugepaged_wait);
178 static struct kobj_attribute alloc_sleep_millisecs_attr =
179 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
180 alloc_sleep_millisecs_store);
182 static ssize_t pages_to_scan_show(struct kobject *kobj,
183 struct kobj_attribute *attr,
186 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
188 static ssize_t pages_to_scan_store(struct kobject *kobj,
189 struct kobj_attribute *attr,
190 const char *buf, size_t count)
195 err = kstrtouint(buf, 10, &pages);
199 khugepaged_pages_to_scan = pages;
203 static struct kobj_attribute pages_to_scan_attr =
204 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
205 pages_to_scan_store);
207 static ssize_t pages_collapsed_show(struct kobject *kobj,
208 struct kobj_attribute *attr,
211 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
213 static struct kobj_attribute pages_collapsed_attr =
214 __ATTR_RO(pages_collapsed);
216 static ssize_t full_scans_show(struct kobject *kobj,
217 struct kobj_attribute *attr,
220 return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
222 static struct kobj_attribute full_scans_attr =
223 __ATTR_RO(full_scans);
225 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
226 struct kobj_attribute *attr, char *buf)
228 return single_hugepage_flag_show(kobj, attr, buf,
229 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
231 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
232 struct kobj_attribute *attr,
233 const char *buf, size_t count)
235 return single_hugepage_flag_store(kobj, attr, buf, count,
236 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
238 static struct kobj_attribute khugepaged_defrag_attr =
239 __ATTR(defrag, 0644, khugepaged_defrag_show,
240 khugepaged_defrag_store);
243 * max_ptes_none controls if khugepaged should collapse hugepages over
244 * any unmapped ptes in turn potentially increasing the memory
245 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
246 * reduce the available free memory in the system as it
247 * runs. Increasing max_ptes_none will instead potentially reduce the
248 * free memory in the system during the khugepaged scan.
250 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
251 struct kobj_attribute *attr,
254 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
256 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
257 struct kobj_attribute *attr,
258 const char *buf, size_t count)
261 unsigned long max_ptes_none;
263 err = kstrtoul(buf, 10, &max_ptes_none);
264 if (err || max_ptes_none > HPAGE_PMD_NR-1)
267 khugepaged_max_ptes_none = max_ptes_none;
271 static struct kobj_attribute khugepaged_max_ptes_none_attr =
272 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
273 khugepaged_max_ptes_none_store);
275 static ssize_t khugepaged_max_ptes_swap_show(struct kobject *kobj,
276 struct kobj_attribute *attr,
279 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
282 static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
283 struct kobj_attribute *attr,
284 const char *buf, size_t count)
287 unsigned long max_ptes_swap;
289 err = kstrtoul(buf, 10, &max_ptes_swap);
290 if (err || max_ptes_swap > HPAGE_PMD_NR-1)
293 khugepaged_max_ptes_swap = max_ptes_swap;
298 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
299 __ATTR(max_ptes_swap, 0644, khugepaged_max_ptes_swap_show,
300 khugepaged_max_ptes_swap_store);
302 static ssize_t khugepaged_max_ptes_shared_show(struct kobject *kobj,
303 struct kobj_attribute *attr,
306 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
309 static ssize_t khugepaged_max_ptes_shared_store(struct kobject *kobj,
310 struct kobj_attribute *attr,
311 const char *buf, size_t count)
314 unsigned long max_ptes_shared;
316 err = kstrtoul(buf, 10, &max_ptes_shared);
317 if (err || max_ptes_shared > HPAGE_PMD_NR-1)
320 khugepaged_max_ptes_shared = max_ptes_shared;
325 static struct kobj_attribute khugepaged_max_ptes_shared_attr =
326 __ATTR(max_ptes_shared, 0644, khugepaged_max_ptes_shared_show,
327 khugepaged_max_ptes_shared_store);
329 static struct attribute *khugepaged_attr[] = {
330 &khugepaged_defrag_attr.attr,
331 &khugepaged_max_ptes_none_attr.attr,
332 &khugepaged_max_ptes_swap_attr.attr,
333 &khugepaged_max_ptes_shared_attr.attr,
334 &pages_to_scan_attr.attr,
335 &pages_collapsed_attr.attr,
336 &full_scans_attr.attr,
337 &scan_sleep_millisecs_attr.attr,
338 &alloc_sleep_millisecs_attr.attr,
342 struct attribute_group khugepaged_attr_group = {
343 .attrs = khugepaged_attr,
344 .name = "khugepaged",
346 #endif /* CONFIG_SYSFS */
348 int hugepage_madvise(struct vm_area_struct *vma,
349 unsigned long *vm_flags, int advice)
355 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
356 * can't handle this properly after s390_enable_sie, so we simply
357 * ignore the madvise to prevent qemu from causing a SIGSEGV.
359 if (mm_has_pgste(vma->vm_mm))
362 *vm_flags &= ~VM_NOHUGEPAGE;
363 *vm_flags |= VM_HUGEPAGE;
365 * If the vma become good for khugepaged to scan,
366 * register it here without waiting a page fault that
367 * may not happen any time soon.
369 if (!(*vm_flags & VM_NO_KHUGEPAGED) &&
370 khugepaged_enter_vma_merge(vma, *vm_flags))
373 case MADV_NOHUGEPAGE:
374 *vm_flags &= ~VM_HUGEPAGE;
375 *vm_flags |= VM_NOHUGEPAGE;
377 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
378 * this vma even if we leave the mm registered in khugepaged if
379 * it got registered before VM_NOHUGEPAGE was set.
387 int __init khugepaged_init(void)
389 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
390 sizeof(struct mm_slot),
391 __alignof__(struct mm_slot), 0, NULL);
395 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
396 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
397 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
398 khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
403 void __init khugepaged_destroy(void)
405 kmem_cache_destroy(mm_slot_cache);
408 static inline struct mm_slot *alloc_mm_slot(void)
410 if (!mm_slot_cache) /* initialization failed */
412 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
415 static inline void free_mm_slot(struct mm_slot *mm_slot)
417 kmem_cache_free(mm_slot_cache, mm_slot);
420 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
422 struct mm_slot *mm_slot;
424 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
425 if (mm == mm_slot->mm)
431 static void insert_to_mm_slots_hash(struct mm_struct *mm,
432 struct mm_slot *mm_slot)
435 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
438 static inline int khugepaged_test_exit(struct mm_struct *mm)
440 return atomic_read(&mm->mm_users) == 0;
443 static bool hugepage_vma_check(struct vm_area_struct *vma,
444 unsigned long vm_flags)
446 if (!transhuge_vma_enabled(vma, vm_flags))
449 if (vma->vm_file && !IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) -
450 vma->vm_pgoff, HPAGE_PMD_NR))
453 /* Enabled via shmem mount options or sysfs settings. */
454 if (shmem_file(vma->vm_file))
455 return shmem_huge_enabled(vma);
457 /* THP settings require madvise. */
458 if (!(vm_flags & VM_HUGEPAGE) && !khugepaged_always())
461 /* Only regular file is valid */
462 if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && vma->vm_file &&
463 (vm_flags & VM_EXEC)) {
464 struct inode *inode = vma->vm_file->f_inode;
466 return !inode_is_open_for_write(inode) &&
467 S_ISREG(inode->i_mode);
470 if (!vma->anon_vma || vma->vm_ops)
472 if (vma_is_temporary_stack(vma))
474 return !(vm_flags & VM_NO_KHUGEPAGED);
477 int __khugepaged_enter(struct mm_struct *mm)
479 struct mm_slot *mm_slot;
482 mm_slot = alloc_mm_slot();
486 /* __khugepaged_exit() must not run from under us */
487 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
488 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
489 free_mm_slot(mm_slot);
493 spin_lock(&khugepaged_mm_lock);
494 insert_to_mm_slots_hash(mm, mm_slot);
496 * Insert just behind the scanning cursor, to let the area settle
499 wakeup = list_empty(&khugepaged_scan.mm_head);
500 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
501 spin_unlock(&khugepaged_mm_lock);
505 wake_up_interruptible(&khugepaged_wait);
510 int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
511 unsigned long vm_flags)
513 unsigned long hstart, hend;
516 * khugepaged only supports read-only files for non-shmem files.
517 * khugepaged does not yet work on special mappings. And
518 * file-private shmem THP is not supported.
520 if (!hugepage_vma_check(vma, vm_flags))
523 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
524 hend = vma->vm_end & HPAGE_PMD_MASK;
526 return khugepaged_enter(vma, vm_flags);
530 void __khugepaged_exit(struct mm_struct *mm)
532 struct mm_slot *mm_slot;
535 spin_lock(&khugepaged_mm_lock);
536 mm_slot = get_mm_slot(mm);
537 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
538 hash_del(&mm_slot->hash);
539 list_del(&mm_slot->mm_node);
542 spin_unlock(&khugepaged_mm_lock);
545 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
546 free_mm_slot(mm_slot);
548 } else if (mm_slot) {
550 * This is required to serialize against
551 * khugepaged_test_exit() (which is guaranteed to run
552 * under mmap sem read mode). Stop here (after we
553 * return all pagetables will be destroyed) until
554 * khugepaged has finished working on the pagetables
555 * under the mmap_lock.
558 mmap_write_unlock(mm);
562 static void release_pte_page(struct page *page)
564 mod_node_page_state(page_pgdat(page),
565 NR_ISOLATED_ANON + page_is_file_lru(page),
568 putback_lru_page(page);
571 static void release_pte_pages(pte_t *pte, pte_t *_pte,
572 struct list_head *compound_pagelist)
574 struct page *page, *tmp;
576 while (--_pte >= pte) {
577 pte_t pteval = *_pte;
579 page = pte_page(pteval);
580 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
582 release_pte_page(page);
585 list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
586 list_del(&page->lru);
587 release_pte_page(page);
591 static bool is_refcount_suitable(struct page *page)
593 int expected_refcount;
595 expected_refcount = total_mapcount(page);
596 if (PageSwapCache(page))
597 expected_refcount += compound_nr(page);
599 return page_count(page) == expected_refcount;
602 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
603 unsigned long address,
605 struct list_head *compound_pagelist)
607 struct page *page = NULL;
609 int none_or_zero = 0, shared = 0, result = 0, referenced = 0;
610 bool writable = false;
612 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
613 _pte++, address += PAGE_SIZE) {
614 pte_t pteval = *_pte;
615 if (pte_none(pteval) || (pte_present(pteval) &&
616 is_zero_pfn(pte_pfn(pteval)))) {
617 if (!userfaultfd_armed(vma) &&
618 ++none_or_zero <= khugepaged_max_ptes_none) {
621 result = SCAN_EXCEED_NONE_PTE;
622 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
626 if (!pte_present(pteval)) {
627 result = SCAN_PTE_NON_PRESENT;
630 page = vm_normal_page(vma, address, pteval);
631 if (unlikely(!page)) {
632 result = SCAN_PAGE_NULL;
636 VM_BUG_ON_PAGE(!PageAnon(page), page);
638 if (page_mapcount(page) > 1 &&
639 ++shared > khugepaged_max_ptes_shared) {
640 result = SCAN_EXCEED_SHARED_PTE;
641 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
645 if (PageCompound(page)) {
647 page = compound_head(page);
650 * Check if we have dealt with the compound page
653 list_for_each_entry(p, compound_pagelist, lru) {
660 * We can do it before isolate_lru_page because the
661 * page can't be freed from under us. NOTE: PG_lock
662 * is needed to serialize against split_huge_page
663 * when invoked from the VM.
665 if (!trylock_page(page)) {
666 result = SCAN_PAGE_LOCK;
671 * Check if the page has any GUP (or other external) pins.
673 * The page table that maps the page has been already unlinked
674 * from the page table tree and this process cannot get
675 * an additional pin on the page.
677 * New pins can come later if the page is shared across fork,
678 * but not from this process. The other process cannot write to
679 * the page, only trigger CoW.
681 if (!is_refcount_suitable(page)) {
683 result = SCAN_PAGE_COUNT;
686 if (!pte_write(pteval) && PageSwapCache(page) &&
687 !reuse_swap_page(page)) {
689 * Page is in the swap cache and cannot be re-used.
690 * It cannot be collapsed into a THP.
693 result = SCAN_SWAP_CACHE_PAGE;
698 * Isolate the page to avoid collapsing an hugepage
699 * currently in use by the VM.
701 if (isolate_lru_page(page)) {
703 result = SCAN_DEL_PAGE_LRU;
706 mod_node_page_state(page_pgdat(page),
707 NR_ISOLATED_ANON + page_is_file_lru(page),
709 VM_BUG_ON_PAGE(!PageLocked(page), page);
710 VM_BUG_ON_PAGE(PageLRU(page), page);
712 if (PageCompound(page))
713 list_add_tail(&page->lru, compound_pagelist);
715 /* There should be enough young pte to collapse the page */
716 if (pte_young(pteval) ||
717 page_is_young(page) || PageReferenced(page) ||
718 mmu_notifier_test_young(vma->vm_mm, address))
721 if (pte_write(pteval))
725 if (unlikely(!writable)) {
726 result = SCAN_PAGE_RO;
727 } else if (unlikely(!referenced)) {
728 result = SCAN_LACK_REFERENCED_PAGE;
730 result = SCAN_SUCCEED;
731 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
732 referenced, writable, result);
736 release_pte_pages(pte, _pte, compound_pagelist);
737 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
738 referenced, writable, result);
742 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
743 struct vm_area_struct *vma,
744 unsigned long address,
746 struct list_head *compound_pagelist)
748 struct page *src_page, *tmp;
750 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
751 _pte++, page++, address += PAGE_SIZE) {
752 pte_t pteval = *_pte;
754 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
755 clear_user_highpage(page, address);
756 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
757 if (is_zero_pfn(pte_pfn(pteval))) {
759 * ptl mostly unnecessary.
762 ptep_clear(vma->vm_mm, address, _pte);
766 src_page = pte_page(pteval);
767 copy_user_highpage(page, src_page, address, vma);
768 if (!PageCompound(src_page))
769 release_pte_page(src_page);
771 * ptl mostly unnecessary, but preempt has to
772 * be disabled to update the per-cpu stats
773 * inside page_remove_rmap().
776 ptep_clear(vma->vm_mm, address, _pte);
777 page_remove_rmap(src_page, false);
779 free_page_and_swap_cache(src_page);
783 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
784 list_del(&src_page->lru);
785 release_pte_page(src_page);
789 static void khugepaged_alloc_sleep(void)
793 add_wait_queue(&khugepaged_wait, &wait);
794 freezable_schedule_timeout_interruptible(
795 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
796 remove_wait_queue(&khugepaged_wait, &wait);
799 static int khugepaged_node_load[MAX_NUMNODES];
801 static bool khugepaged_scan_abort(int nid)
806 * If node_reclaim_mode is disabled, then no extra effort is made to
807 * allocate memory locally.
809 if (!node_reclaim_enabled())
812 /* If there is a count for this node already, it must be acceptable */
813 if (khugepaged_node_load[nid])
816 for (i = 0; i < MAX_NUMNODES; i++) {
817 if (!khugepaged_node_load[i])
819 if (node_distance(nid, i) > node_reclaim_distance)
825 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
826 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
828 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
832 static int khugepaged_find_target_node(void)
834 static int last_khugepaged_target_node = NUMA_NO_NODE;
835 int nid, target_node = 0, max_value = 0;
837 /* find first node with max normal pages hit */
838 for (nid = 0; nid < MAX_NUMNODES; nid++)
839 if (khugepaged_node_load[nid] > max_value) {
840 max_value = khugepaged_node_load[nid];
844 /* do some balance if several nodes have the same hit record */
845 if (target_node <= last_khugepaged_target_node)
846 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
848 if (max_value == khugepaged_node_load[nid]) {
853 last_khugepaged_target_node = target_node;
857 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
859 if (IS_ERR(*hpage)) {
865 khugepaged_alloc_sleep();
875 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
877 VM_BUG_ON_PAGE(*hpage, *hpage);
879 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
880 if (unlikely(!*hpage)) {
881 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
882 *hpage = ERR_PTR(-ENOMEM);
886 prep_transhuge_page(*hpage);
887 count_vm_event(THP_COLLAPSE_ALLOC);
891 static int khugepaged_find_target_node(void)
896 static inline struct page *alloc_khugepaged_hugepage(void)
900 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
903 prep_transhuge_page(page);
907 static struct page *khugepaged_alloc_hugepage(bool *wait)
912 hpage = alloc_khugepaged_hugepage();
914 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
919 khugepaged_alloc_sleep();
921 count_vm_event(THP_COLLAPSE_ALLOC);
922 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
927 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
930 * If the hpage allocated earlier was briefly exposed in page cache
931 * before collapse_file() failed, it is possible that racing lookups
932 * have not yet completed, and would then be unpleasantly surprised by
933 * finding the hpage reused for the same mapping at a different offset.
934 * Just release the previous allocation if there is any danger of that.
936 if (*hpage && page_count(*hpage) > 1) {
942 *hpage = khugepaged_alloc_hugepage(wait);
944 if (unlikely(!*hpage))
951 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
960 * If mmap_lock temporarily dropped, revalidate vma
961 * before taking mmap_lock.
962 * Return 0 if succeeds, otherwise return none-zero
966 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
967 struct vm_area_struct **vmap)
969 struct vm_area_struct *vma;
970 unsigned long hstart, hend;
972 if (unlikely(khugepaged_test_exit(mm)))
973 return SCAN_ANY_PROCESS;
975 *vmap = vma = find_vma(mm, address);
977 return SCAN_VMA_NULL;
979 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
980 hend = vma->vm_end & HPAGE_PMD_MASK;
981 if (address < hstart || address + HPAGE_PMD_SIZE > hend)
982 return SCAN_ADDRESS_RANGE;
983 if (!hugepage_vma_check(vma, vma->vm_flags))
984 return SCAN_VMA_CHECK;
985 /* Anon VMA expected */
986 if (!vma->anon_vma || vma->vm_ops)
987 return SCAN_VMA_CHECK;
992 * Bring missing pages in from swap, to complete THP collapse.
993 * Only done if khugepaged_scan_pmd believes it is worthwhile.
995 * Called and returns without pte mapped or spinlocks held,
996 * but with mmap_lock held to protect against vma changes.
999 static bool __collapse_huge_page_swapin(struct mm_struct *mm,
1000 struct vm_area_struct *vma,
1001 unsigned long haddr, pmd_t *pmd,
1006 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
1008 for (address = haddr; address < end; address += PAGE_SIZE) {
1009 struct vm_fault vmf = {
1012 .pgoff = linear_page_index(vma, haddr),
1013 .flags = FAULT_FLAG_ALLOW_RETRY,
1017 vmf.pte = pte_offset_map(pmd, address);
1018 vmf.orig_pte = *vmf.pte;
1019 if (!is_swap_pte(vmf.orig_pte)) {
1024 ret = do_swap_page(&vmf);
1026 /* do_swap_page returns VM_FAULT_RETRY with released mmap_lock */
1027 if (ret & VM_FAULT_RETRY) {
1029 if (hugepage_vma_revalidate(mm, haddr, &vma)) {
1030 /* vma is no longer available, don't continue to swapin */
1031 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
1034 /* check if the pmd is still valid */
1035 if (mm_find_pmd(mm, haddr) != pmd) {
1036 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
1040 if (ret & VM_FAULT_ERROR) {
1041 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
1046 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
1050 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
1054 static void collapse_huge_page(struct mm_struct *mm,
1055 unsigned long address,
1056 struct page **hpage,
1057 int node, int referenced, int unmapped)
1059 LIST_HEAD(compound_pagelist);
1063 struct page *new_page;
1064 spinlock_t *pmd_ptl, *pte_ptl;
1065 int isolated = 0, result = 0;
1066 struct vm_area_struct *vma;
1067 struct mmu_notifier_range range;
1070 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1072 /* Only allocate from the target node */
1073 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1076 * Before allocating the hugepage, release the mmap_lock read lock.
1077 * The allocation can take potentially a long time if it involves
1078 * sync compaction, and we do not need to hold the mmap_lock during
1079 * that. We will recheck the vma after taking it again in write mode.
1081 mmap_read_unlock(mm);
1082 new_page = khugepaged_alloc_page(hpage, gfp, node);
1084 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1088 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) {
1089 result = SCAN_CGROUP_CHARGE_FAIL;
1092 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
1095 result = hugepage_vma_revalidate(mm, address, &vma);
1097 mmap_read_unlock(mm);
1101 pmd = mm_find_pmd(mm, address);
1103 result = SCAN_PMD_NULL;
1104 mmap_read_unlock(mm);
1109 * __collapse_huge_page_swapin always returns with mmap_lock locked.
1110 * If it fails, we release mmap_lock and jump out_nolock.
1111 * Continuing to collapse causes inconsistency.
1113 if (unmapped && !__collapse_huge_page_swapin(mm, vma, address,
1115 mmap_read_unlock(mm);
1119 mmap_read_unlock(mm);
1121 * Prevent all access to pagetables with the exception of
1122 * gup_fast later handled by the ptep_clear_flush and the VM
1123 * handled by the anon_vma lock + PG_lock.
1125 mmap_write_lock(mm);
1126 result = hugepage_vma_revalidate(mm, address, &vma);
1129 /* check if the pmd is still valid */
1130 if (mm_find_pmd(mm, address) != pmd)
1133 anon_vma_lock_write(vma->anon_vma);
1135 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1136 address, address + HPAGE_PMD_SIZE);
1137 mmu_notifier_invalidate_range_start(&range);
1139 pte = pte_offset_map(pmd, address);
1140 pte_ptl = pte_lockptr(mm, pmd);
1142 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1144 * After this gup_fast can't run anymore. This also removes
1145 * any huge TLB entry from the CPU so we won't allow
1146 * huge and small TLB entries for the same virtual address
1147 * to avoid the risk of CPU bugs in that area.
1149 _pmd = pmdp_collapse_flush(vma, address, pmd);
1150 spin_unlock(pmd_ptl);
1151 mmu_notifier_invalidate_range_end(&range);
1154 isolated = __collapse_huge_page_isolate(vma, address, pte,
1155 &compound_pagelist);
1156 spin_unlock(pte_ptl);
1158 if (unlikely(!isolated)) {
1161 BUG_ON(!pmd_none(*pmd));
1163 * We can only use set_pmd_at when establishing
1164 * hugepmds and never for establishing regular pmds that
1165 * points to regular pagetables. Use pmd_populate for that
1167 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1168 spin_unlock(pmd_ptl);
1169 anon_vma_unlock_write(vma->anon_vma);
1175 * All pages are isolated and locked so anon_vma rmap
1176 * can't run anymore.
1178 anon_vma_unlock_write(vma->anon_vma);
1180 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl,
1181 &compound_pagelist);
1184 * spin_lock() below is not the equivalent of smp_wmb(), but
1185 * the smp_wmb() inside __SetPageUptodate() can be reused to
1186 * avoid the copy_huge_page writes to become visible after
1187 * the set_pmd_at() write.
1189 __SetPageUptodate(new_page);
1190 pgtable = pmd_pgtable(_pmd);
1192 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1193 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1196 BUG_ON(!pmd_none(*pmd));
1197 page_add_new_anon_rmap(new_page, vma, address, true);
1198 lru_cache_add_inactive_or_unevictable(new_page, vma);
1199 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1200 set_pmd_at(mm, address, pmd, _pmd);
1201 update_mmu_cache_pmd(vma, address, pmd);
1202 spin_unlock(pmd_ptl);
1206 khugepaged_pages_collapsed++;
1207 result = SCAN_SUCCEED;
1209 mmap_write_unlock(mm);
1211 if (!IS_ERR_OR_NULL(*hpage))
1212 mem_cgroup_uncharge(page_folio(*hpage));
1213 trace_mm_collapse_huge_page(mm, isolated, result);
1217 static int khugepaged_scan_pmd(struct mm_struct *mm,
1218 struct vm_area_struct *vma,
1219 unsigned long address,
1220 struct page **hpage)
1224 int ret = 0, result = 0, referenced = 0;
1225 int none_or_zero = 0, shared = 0;
1226 struct page *page = NULL;
1227 unsigned long _address;
1229 int node = NUMA_NO_NODE, unmapped = 0;
1230 bool writable = false;
1232 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1234 pmd = mm_find_pmd(mm, address);
1236 result = SCAN_PMD_NULL;
1240 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1241 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1242 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1243 _pte++, _address += PAGE_SIZE) {
1244 pte_t pteval = *_pte;
1245 if (is_swap_pte(pteval)) {
1246 if (++unmapped <= khugepaged_max_ptes_swap) {
1248 * Always be strict with uffd-wp
1249 * enabled swap entries. Please see
1250 * comment below for pte_uffd_wp().
1252 if (pte_swp_uffd_wp(pteval)) {
1253 result = SCAN_PTE_UFFD_WP;
1258 result = SCAN_EXCEED_SWAP_PTE;
1259 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1263 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1264 if (!userfaultfd_armed(vma) &&
1265 ++none_or_zero <= khugepaged_max_ptes_none) {
1268 result = SCAN_EXCEED_NONE_PTE;
1269 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1273 if (pte_uffd_wp(pteval)) {
1275 * Don't collapse the page if any of the small
1276 * PTEs are armed with uffd write protection.
1277 * Here we can also mark the new huge pmd as
1278 * write protected if any of the small ones is
1279 * marked but that could bring unknown
1280 * userfault messages that falls outside of
1281 * the registered range. So, just be simple.
1283 result = SCAN_PTE_UFFD_WP;
1286 if (pte_write(pteval))
1289 page = vm_normal_page(vma, _address, pteval);
1290 if (unlikely(!page)) {
1291 result = SCAN_PAGE_NULL;
1295 if (page_mapcount(page) > 1 &&
1296 ++shared > khugepaged_max_ptes_shared) {
1297 result = SCAN_EXCEED_SHARED_PTE;
1298 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1302 page = compound_head(page);
1305 * Record which node the original page is from and save this
1306 * information to khugepaged_node_load[].
1307 * Khugepaged will allocate hugepage from the node has the max
1310 node = page_to_nid(page);
1311 if (khugepaged_scan_abort(node)) {
1312 result = SCAN_SCAN_ABORT;
1315 khugepaged_node_load[node]++;
1316 if (!PageLRU(page)) {
1317 result = SCAN_PAGE_LRU;
1320 if (PageLocked(page)) {
1321 result = SCAN_PAGE_LOCK;
1324 if (!PageAnon(page)) {
1325 result = SCAN_PAGE_ANON;
1330 * Check if the page has any GUP (or other external) pins.
1332 * Here the check is racy it may see totmal_mapcount > refcount
1334 * For example, one process with one forked child process.
1335 * The parent has the PMD split due to MADV_DONTNEED, then
1336 * the child is trying unmap the whole PMD, but khugepaged
1337 * may be scanning the parent between the child has
1338 * PageDoubleMap flag cleared and dec the mapcount. So
1339 * khugepaged may see total_mapcount > refcount.
1341 * But such case is ephemeral we could always retry collapse
1342 * later. However it may report false positive if the page
1343 * has excessive GUP pins (i.e. 512). Anyway the same check
1344 * will be done again later the risk seems low.
1346 if (!is_refcount_suitable(page)) {
1347 result = SCAN_PAGE_COUNT;
1350 if (pte_young(pteval) ||
1351 page_is_young(page) || PageReferenced(page) ||
1352 mmu_notifier_test_young(vma->vm_mm, address))
1356 result = SCAN_PAGE_RO;
1357 } else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
1358 result = SCAN_LACK_REFERENCED_PAGE;
1360 result = SCAN_SUCCEED;
1364 pte_unmap_unlock(pte, ptl);
1366 node = khugepaged_find_target_node();
1367 /* collapse_huge_page will return with the mmap_lock released */
1368 collapse_huge_page(mm, address, hpage, node,
1369 referenced, unmapped);
1372 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1373 none_or_zero, result, unmapped);
1377 static void collect_mm_slot(struct mm_slot *mm_slot)
1379 struct mm_struct *mm = mm_slot->mm;
1381 lockdep_assert_held(&khugepaged_mm_lock);
1383 if (khugepaged_test_exit(mm)) {
1385 hash_del(&mm_slot->hash);
1386 list_del(&mm_slot->mm_node);
1389 * Not strictly needed because the mm exited already.
1391 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1394 /* khugepaged_mm_lock actually not necessary for the below */
1395 free_mm_slot(mm_slot);
1402 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1403 * khugepaged should try to collapse the page table.
1405 static int khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1408 struct mm_slot *mm_slot;
1410 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1412 spin_lock(&khugepaged_mm_lock);
1413 mm_slot = get_mm_slot(mm);
1414 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
1415 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1416 spin_unlock(&khugepaged_mm_lock);
1420 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1421 unsigned long addr, pmd_t *pmdp)
1426 mmap_assert_write_locked(mm);
1427 ptl = pmd_lock(vma->vm_mm, pmdp);
1428 pmd = pmdp_collapse_flush(vma, addr, pmdp);
1431 page_table_check_pte_clear_range(mm, addr, pmd);
1432 pte_free(mm, pmd_pgtable(pmd));
1436 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1439 * @mm: process address space where collapse happens
1440 * @addr: THP collapse address
1442 * This function checks whether all the PTEs in the PMD are pointing to the
1443 * right THP. If so, retract the page table so the THP can refault in with
1446 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
1448 unsigned long haddr = addr & HPAGE_PMD_MASK;
1449 struct vm_area_struct *vma = find_vma(mm, haddr);
1451 pte_t *start_pte, *pte;
1457 if (!vma || !vma->vm_file ||
1458 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1462 * This vm_flags may not have VM_HUGEPAGE if the page was not
1463 * collapsed by this mm. But we can still collapse if the page is
1464 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
1465 * will not fail the vma for missing VM_HUGEPAGE
1467 if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE))
1470 hpage = find_lock_page(vma->vm_file->f_mapping,
1471 linear_page_index(vma, haddr));
1475 if (!PageHead(hpage))
1478 pmd = mm_find_pmd(mm, haddr);
1482 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1484 /* step 1: check all mapped PTEs are to the right huge page */
1485 for (i = 0, addr = haddr, pte = start_pte;
1486 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1489 /* empty pte, skip */
1493 /* page swapped out, abort */
1494 if (!pte_present(*pte))
1497 page = vm_normal_page(vma, addr, *pte);
1500 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1501 * page table, but the new page will not be a subpage of hpage.
1503 if (hpage + i != page)
1508 /* step 2: adjust rmap */
1509 for (i = 0, addr = haddr, pte = start_pte;
1510 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1515 page = vm_normal_page(vma, addr, *pte);
1516 page_remove_rmap(page, false);
1519 pte_unmap_unlock(start_pte, ptl);
1521 /* step 3: set proper refcount and mm_counters. */
1523 page_ref_sub(hpage, count);
1524 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1527 /* step 4: collapse pmd */
1528 collapse_and_free_pmd(mm, vma, haddr, pmd);
1535 pte_unmap_unlock(start_pte, ptl);
1539 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1541 struct mm_struct *mm = mm_slot->mm;
1544 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1547 if (!mmap_write_trylock(mm))
1550 if (unlikely(khugepaged_test_exit(mm)))
1553 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1554 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
1557 mm_slot->nr_pte_mapped_thp = 0;
1558 mmap_write_unlock(mm);
1561 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1563 struct vm_area_struct *vma;
1564 struct mm_struct *mm;
1568 i_mmap_lock_write(mapping);
1569 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1571 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1572 * got written to. These VMAs are likely not worth investing
1573 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1576 * Not that vma->anon_vma check is racy: it can be set up after
1577 * the check but before we took mmap_lock by the fault path.
1578 * But page lock would prevent establishing any new ptes of the
1579 * page, so we are safe.
1581 * An alternative would be drop the check, but check that page
1582 * table is clear before calling pmdp_collapse_flush() under
1583 * ptl. It has higher chance to recover THP for the VMA, but
1584 * has higher cost too.
1588 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1589 if (addr & ~HPAGE_PMD_MASK)
1591 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1594 pmd = mm_find_pmd(mm, addr);
1598 * We need exclusive mmap_lock to retract page table.
1600 * We use trylock due to lock inversion: we need to acquire
1601 * mmap_lock while holding page lock. Fault path does it in
1602 * reverse order. Trylock is a way to avoid deadlock.
1604 if (mmap_write_trylock(mm)) {
1605 if (!khugepaged_test_exit(mm))
1606 collapse_and_free_pmd(mm, vma, addr, pmd);
1607 mmap_write_unlock(mm);
1609 /* Try again later */
1610 khugepaged_add_pte_mapped_thp(mm, addr);
1613 i_mmap_unlock_write(mapping);
1617 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1619 * @mm: process address space where collapse happens
1620 * @file: file that collapse on
1621 * @start: collapse start address
1622 * @hpage: new allocated huge page for collapse
1623 * @node: appointed node the new huge page allocate from
1625 * Basic scheme is simple, details are more complex:
1626 * - allocate and lock a new huge page;
1627 * - scan page cache replacing old pages with the new one
1628 * + swap/gup in pages if necessary;
1630 * + keep old pages around in case rollback is required;
1631 * - if replacing succeeds:
1634 * + unlock huge page;
1635 * - if replacing failed;
1636 * + put all pages back and unfreeze them;
1637 * + restore gaps in the page cache;
1638 * + unlock and free huge page;
1640 static void collapse_file(struct mm_struct *mm,
1641 struct file *file, pgoff_t start,
1642 struct page **hpage, int node)
1644 struct address_space *mapping = file->f_mapping;
1646 struct page *new_page;
1647 pgoff_t index, end = start + HPAGE_PMD_NR;
1648 LIST_HEAD(pagelist);
1649 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1650 int nr_none = 0, result = SCAN_SUCCEED;
1651 bool is_shmem = shmem_file(file);
1654 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1655 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1657 /* Only allocate from the target node */
1658 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1660 new_page = khugepaged_alloc_page(hpage, gfp, node);
1662 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1666 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) {
1667 result = SCAN_CGROUP_CHARGE_FAIL;
1670 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
1673 * Ensure we have slots for all the pages in the range. This is
1674 * almost certainly a no-op because most of the pages must be present
1678 xas_create_range(&xas);
1679 if (!xas_error(&xas))
1681 xas_unlock_irq(&xas);
1682 if (!xas_nomem(&xas, GFP_KERNEL)) {
1688 __SetPageLocked(new_page);
1690 __SetPageSwapBacked(new_page);
1691 new_page->index = start;
1692 new_page->mapping = mapping;
1695 * At this point the new_page is locked and not up-to-date.
1696 * It's safe to insert it into the page cache, because nobody would
1697 * be able to map it or use it in another way until we unlock it.
1700 xas_set(&xas, start);
1701 for (index = start; index < end; index++) {
1702 struct page *page = xas_next(&xas);
1704 VM_BUG_ON(index != xas.xa_index);
1708 * Stop if extent has been truncated or
1709 * hole-punched, and is now completely
1712 if (index == start) {
1713 if (!xas_next_entry(&xas, end - 1)) {
1714 result = SCAN_TRUNCATED;
1717 xas_set(&xas, index);
1719 if (!shmem_charge(mapping->host, 1)) {
1723 xas_store(&xas, new_page);
1728 if (xa_is_value(page) || !PageUptodate(page)) {
1729 xas_unlock_irq(&xas);
1730 /* swap in or instantiate fallocated page */
1731 if (shmem_getpage(mapping->host, index, &page,
1736 } else if (trylock_page(page)) {
1738 xas_unlock_irq(&xas);
1740 result = SCAN_PAGE_LOCK;
1743 } else { /* !is_shmem */
1744 if (!page || xa_is_value(page)) {
1745 xas_unlock_irq(&xas);
1746 page_cache_sync_readahead(mapping, &file->f_ra,
1749 /* drain pagevecs to help isolate_lru_page() */
1751 page = find_lock_page(mapping, index);
1752 if (unlikely(page == NULL)) {
1756 } else if (PageDirty(page)) {
1758 * khugepaged only works on read-only fd,
1759 * so this page is dirty because it hasn't
1760 * been flushed since first write. There
1761 * won't be new dirty pages.
1763 * Trigger async flush here and hope the
1764 * writeback is done when khugepaged
1765 * revisits this page.
1767 * This is a one-off situation. We are not
1768 * forcing writeback in loop.
1770 xas_unlock_irq(&xas);
1771 filemap_flush(mapping);
1774 } else if (PageWriteback(page)) {
1775 xas_unlock_irq(&xas);
1778 } else if (trylock_page(page)) {
1780 xas_unlock_irq(&xas);
1782 result = SCAN_PAGE_LOCK;
1788 * The page must be locked, so we can drop the i_pages lock
1789 * without racing with truncate.
1791 VM_BUG_ON_PAGE(!PageLocked(page), page);
1793 /* make sure the page is up to date */
1794 if (unlikely(!PageUptodate(page))) {
1800 * If file was truncated then extended, or hole-punched, before
1801 * we locked the first page, then a THP might be there already.
1803 if (PageTransCompound(page)) {
1804 result = SCAN_PAGE_COMPOUND;
1808 if (page_mapping(page) != mapping) {
1809 result = SCAN_TRUNCATED;
1813 if (!is_shmem && (PageDirty(page) ||
1814 PageWriteback(page))) {
1816 * khugepaged only works on read-only fd, so this
1817 * page is dirty because it hasn't been flushed
1818 * since first write.
1824 if (isolate_lru_page(page)) {
1825 result = SCAN_DEL_PAGE_LRU;
1829 if (page_has_private(page) &&
1830 !try_to_release_page(page, GFP_KERNEL)) {
1831 result = SCAN_PAGE_HAS_PRIVATE;
1832 putback_lru_page(page);
1836 if (page_mapped(page))
1837 unmap_mapping_pages(mapping, index, 1, false);
1840 xas_set(&xas, index);
1842 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1843 VM_BUG_ON_PAGE(page_mapped(page), page);
1846 * The page is expected to have page_count() == 3:
1847 * - we hold a pin on it;
1848 * - one reference from page cache;
1849 * - one from isolate_lru_page;
1851 if (!page_ref_freeze(page, 3)) {
1852 result = SCAN_PAGE_COUNT;
1853 xas_unlock_irq(&xas);
1854 putback_lru_page(page);
1859 * Add the page to the list to be able to undo the collapse if
1860 * something go wrong.
1862 list_add_tail(&page->lru, &pagelist);
1864 /* Finally, replace with the new page. */
1865 xas_store(&xas, new_page);
1872 nr = thp_nr_pages(new_page);
1875 __mod_lruvec_page_state(new_page, NR_SHMEM_THPS, nr);
1877 __mod_lruvec_page_state(new_page, NR_FILE_THPS, nr);
1878 filemap_nr_thps_inc(mapping);
1880 * Paired with smp_mb() in do_dentry_open() to ensure
1881 * i_writecount is up to date and the update to nr_thps is
1882 * visible. Ensures the page cache will be truncated if the
1883 * file is opened writable.
1886 if (inode_is_open_for_write(mapping->host)) {
1888 __mod_lruvec_page_state(new_page, NR_FILE_THPS, -nr);
1889 filemap_nr_thps_dec(mapping);
1895 __mod_lruvec_page_state(new_page, NR_FILE_PAGES, nr_none);
1897 __mod_lruvec_page_state(new_page, NR_SHMEM, nr_none);
1900 /* Join all the small entries into a single multi-index entry */
1901 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
1902 xas_store(&xas, new_page);
1904 xas_unlock_irq(&xas);
1907 if (result == SCAN_SUCCEED) {
1908 struct page *page, *tmp;
1911 * Replacing old pages with new one has succeeded, now we
1912 * need to copy the content and free the old pages.
1915 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1916 while (index < page->index) {
1917 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1920 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1922 list_del(&page->lru);
1923 page->mapping = NULL;
1924 page_ref_unfreeze(page, 1);
1925 ClearPageActive(page);
1926 ClearPageUnevictable(page);
1931 while (index < end) {
1932 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1936 SetPageUptodate(new_page);
1937 page_ref_add(new_page, HPAGE_PMD_NR - 1);
1939 set_page_dirty(new_page);
1940 lru_cache_add(new_page);
1943 * Remove pte page tables, so we can re-fault the page as huge.
1945 retract_page_tables(mapping, start);
1948 khugepaged_pages_collapsed++;
1952 /* Something went wrong: roll back page cache changes */
1954 mapping->nrpages -= nr_none;
1957 shmem_uncharge(mapping->host, nr_none);
1959 xas_set(&xas, start);
1960 xas_for_each(&xas, page, end - 1) {
1961 page = list_first_entry_or_null(&pagelist,
1963 if (!page || xas.xa_index < page->index) {
1967 /* Put holes back where they were */
1968 xas_store(&xas, NULL);
1972 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1974 /* Unfreeze the page. */
1975 list_del(&page->lru);
1976 page_ref_unfreeze(page, 2);
1977 xas_store(&xas, page);
1979 xas_unlock_irq(&xas);
1981 putback_lru_page(page);
1985 xas_unlock_irq(&xas);
1987 new_page->mapping = NULL;
1990 unlock_page(new_page);
1992 VM_BUG_ON(!list_empty(&pagelist));
1993 if (!IS_ERR_OR_NULL(*hpage))
1994 mem_cgroup_uncharge(page_folio(*hpage));
1995 /* TODO: tracepoints */
1998 static void khugepaged_scan_file(struct mm_struct *mm,
1999 struct file *file, pgoff_t start, struct page **hpage)
2001 struct page *page = NULL;
2002 struct address_space *mapping = file->f_mapping;
2003 XA_STATE(xas, &mapping->i_pages, start);
2005 int node = NUMA_NO_NODE;
2006 int result = SCAN_SUCCEED;
2010 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
2012 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2013 if (xas_retry(&xas, page))
2016 if (xa_is_value(page)) {
2017 if (++swap > khugepaged_max_ptes_swap) {
2018 result = SCAN_EXCEED_SWAP_PTE;
2019 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2026 * XXX: khugepaged should compact smaller compound pages
2027 * into a PMD sized page
2029 if (PageTransCompound(page)) {
2030 result = SCAN_PAGE_COMPOUND;
2034 node = page_to_nid(page);
2035 if (khugepaged_scan_abort(node)) {
2036 result = SCAN_SCAN_ABORT;
2039 khugepaged_node_load[node]++;
2041 if (!PageLRU(page)) {
2042 result = SCAN_PAGE_LRU;
2046 if (page_count(page) !=
2047 1 + page_mapcount(page) + page_has_private(page)) {
2048 result = SCAN_PAGE_COUNT;
2053 * We probably should check if the page is referenced here, but
2054 * nobody would transfer pte_young() to PageReferenced() for us.
2055 * And rmap walk here is just too costly...
2060 if (need_resched()) {
2067 if (result == SCAN_SUCCEED) {
2068 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2069 result = SCAN_EXCEED_NONE_PTE;
2070 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2072 node = khugepaged_find_target_node();
2073 collapse_file(mm, file, start, hpage, node);
2077 /* TODO: tracepoints */
2080 static void khugepaged_scan_file(struct mm_struct *mm,
2081 struct file *file, pgoff_t start, struct page **hpage)
2086 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
2091 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2092 struct page **hpage)
2093 __releases(&khugepaged_mm_lock)
2094 __acquires(&khugepaged_mm_lock)
2096 struct mm_slot *mm_slot;
2097 struct mm_struct *mm;
2098 struct vm_area_struct *vma;
2102 lockdep_assert_held(&khugepaged_mm_lock);
2104 if (khugepaged_scan.mm_slot)
2105 mm_slot = khugepaged_scan.mm_slot;
2107 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2108 struct mm_slot, mm_node);
2109 khugepaged_scan.address = 0;
2110 khugepaged_scan.mm_slot = mm_slot;
2112 spin_unlock(&khugepaged_mm_lock);
2113 khugepaged_collapse_pte_mapped_thps(mm_slot);
2117 * Don't wait for semaphore (to avoid long wait times). Just move to
2118 * the next mm on the list.
2121 if (unlikely(!mmap_read_trylock(mm)))
2122 goto breakouterloop_mmap_lock;
2123 if (likely(!khugepaged_test_exit(mm)))
2124 vma = find_vma(mm, khugepaged_scan.address);
2127 for (; vma; vma = vma->vm_next) {
2128 unsigned long hstart, hend;
2131 if (unlikely(khugepaged_test_exit(mm))) {
2135 if (!hugepage_vma_check(vma, vma->vm_flags)) {
2140 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2141 hend = vma->vm_end & HPAGE_PMD_MASK;
2144 if (khugepaged_scan.address > hend)
2146 if (khugepaged_scan.address < hstart)
2147 khugepaged_scan.address = hstart;
2148 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2149 if (shmem_file(vma->vm_file) && !shmem_huge_enabled(vma))
2152 while (khugepaged_scan.address < hend) {
2155 if (unlikely(khugepaged_test_exit(mm)))
2156 goto breakouterloop;
2158 VM_BUG_ON(khugepaged_scan.address < hstart ||
2159 khugepaged_scan.address + HPAGE_PMD_SIZE >
2161 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2162 struct file *file = get_file(vma->vm_file);
2163 pgoff_t pgoff = linear_page_index(vma,
2164 khugepaged_scan.address);
2166 mmap_read_unlock(mm);
2168 khugepaged_scan_file(mm, file, pgoff, hpage);
2171 ret = khugepaged_scan_pmd(mm, vma,
2172 khugepaged_scan.address,
2175 /* move to next address */
2176 khugepaged_scan.address += HPAGE_PMD_SIZE;
2177 progress += HPAGE_PMD_NR;
2179 /* we released mmap_lock so break loop */
2180 goto breakouterloop_mmap_lock;
2181 if (progress >= pages)
2182 goto breakouterloop;
2186 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2187 breakouterloop_mmap_lock:
2189 spin_lock(&khugepaged_mm_lock);
2190 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2192 * Release the current mm_slot if this mm is about to die, or
2193 * if we scanned all vmas of this mm.
2195 if (khugepaged_test_exit(mm) || !vma) {
2197 * Make sure that if mm_users is reaching zero while
2198 * khugepaged runs here, khugepaged_exit will find
2199 * mm_slot not pointing to the exiting mm.
2201 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2202 khugepaged_scan.mm_slot = list_entry(
2203 mm_slot->mm_node.next,
2204 struct mm_slot, mm_node);
2205 khugepaged_scan.address = 0;
2207 khugepaged_scan.mm_slot = NULL;
2208 khugepaged_full_scans++;
2211 collect_mm_slot(mm_slot);
2217 static int khugepaged_has_work(void)
2219 return !list_empty(&khugepaged_scan.mm_head) &&
2220 khugepaged_enabled();
2223 static int khugepaged_wait_event(void)
2225 return !list_empty(&khugepaged_scan.mm_head) ||
2226 kthread_should_stop();
2229 static void khugepaged_do_scan(void)
2231 struct page *hpage = NULL;
2232 unsigned int progress = 0, pass_through_head = 0;
2233 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2236 lru_add_drain_all();
2238 while (progress < pages) {
2239 if (!khugepaged_prealloc_page(&hpage, &wait))
2244 if (unlikely(kthread_should_stop() || try_to_freeze()))
2247 spin_lock(&khugepaged_mm_lock);
2248 if (!khugepaged_scan.mm_slot)
2249 pass_through_head++;
2250 if (khugepaged_has_work() &&
2251 pass_through_head < 2)
2252 progress += khugepaged_scan_mm_slot(pages - progress,
2256 spin_unlock(&khugepaged_mm_lock);
2259 if (!IS_ERR_OR_NULL(hpage))
2263 static bool khugepaged_should_wakeup(void)
2265 return kthread_should_stop() ||
2266 time_after_eq(jiffies, khugepaged_sleep_expire);
2269 static void khugepaged_wait_work(void)
2271 if (khugepaged_has_work()) {
2272 const unsigned long scan_sleep_jiffies =
2273 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2275 if (!scan_sleep_jiffies)
2278 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2279 wait_event_freezable_timeout(khugepaged_wait,
2280 khugepaged_should_wakeup(),
2281 scan_sleep_jiffies);
2285 if (khugepaged_enabled())
2286 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2289 static int khugepaged(void *none)
2291 struct mm_slot *mm_slot;
2294 set_user_nice(current, MAX_NICE);
2296 while (!kthread_should_stop()) {
2297 khugepaged_do_scan();
2298 khugepaged_wait_work();
2301 spin_lock(&khugepaged_mm_lock);
2302 mm_slot = khugepaged_scan.mm_slot;
2303 khugepaged_scan.mm_slot = NULL;
2305 collect_mm_slot(mm_slot);
2306 spin_unlock(&khugepaged_mm_lock);
2310 static void set_recommended_min_free_kbytes(void)
2314 unsigned long recommended_min;
2316 if (!khugepaged_enabled()) {
2317 calculate_min_free_kbytes();
2321 for_each_populated_zone(zone) {
2323 * We don't need to worry about fragmentation of
2324 * ZONE_MOVABLE since it only has movable pages.
2326 if (zone_idx(zone) > gfp_zone(GFP_USER))
2332 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2333 recommended_min = pageblock_nr_pages * nr_zones * 2;
2336 * Make sure that on average at least two pageblocks are almost free
2337 * of another type, one for a migratetype to fall back to and a
2338 * second to avoid subsequent fallbacks of other types There are 3
2339 * MIGRATE_TYPES we care about.
2341 recommended_min += pageblock_nr_pages * nr_zones *
2342 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2344 /* don't ever allow to reserve more than 5% of the lowmem */
2345 recommended_min = min(recommended_min,
2346 (unsigned long) nr_free_buffer_pages() / 20);
2347 recommended_min <<= (PAGE_SHIFT-10);
2349 if (recommended_min > min_free_kbytes) {
2350 if (user_min_free_kbytes >= 0)
2351 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2352 min_free_kbytes, recommended_min);
2354 min_free_kbytes = recommended_min;
2358 setup_per_zone_wmarks();
2361 int start_stop_khugepaged(void)
2365 mutex_lock(&khugepaged_mutex);
2366 if (khugepaged_enabled()) {
2367 if (!khugepaged_thread)
2368 khugepaged_thread = kthread_run(khugepaged, NULL,
2370 if (IS_ERR(khugepaged_thread)) {
2371 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2372 err = PTR_ERR(khugepaged_thread);
2373 khugepaged_thread = NULL;
2377 if (!list_empty(&khugepaged_scan.mm_head))
2378 wake_up_interruptible(&khugepaged_wait);
2379 } else if (khugepaged_thread) {
2380 kthread_stop(khugepaged_thread);
2381 khugepaged_thread = NULL;
2383 set_recommended_min_free_kbytes();
2385 mutex_unlock(&khugepaged_mutex);
2389 void khugepaged_min_free_kbytes_update(void)
2391 mutex_lock(&khugepaged_mutex);
2392 if (khugepaged_enabled() && khugepaged_thread)
2393 set_recommended_min_free_kbytes();
2394 mutex_unlock(&khugepaged_mutex);