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/swapops.h>
20 #include <linux/shmem_fs.h>
23 #include <asm/pgalloc.h>
34 SCAN_LACK_REFERENCED_PAGE,
48 SCAN_ALLOC_HUGE_PAGE_FAIL,
49 SCAN_CGROUP_CHARGE_FAIL,
52 SCAN_PAGE_HAS_PRIVATE,
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/huge_memory.h>
58 /* default scan 8*512 pte (or vmas) every 30 second */
59 static unsigned int khugepaged_pages_to_scan __read_mostly;
60 static unsigned int khugepaged_pages_collapsed;
61 static unsigned int khugepaged_full_scans;
62 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
63 /* during fragmentation poll the hugepage allocator once every minute */
64 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
65 static unsigned long khugepaged_sleep_expire;
66 static DEFINE_SPINLOCK(khugepaged_mm_lock);
67 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
69 * default collapse hugepages if there is at least one pte mapped like
70 * it would have happened if the vma was large enough during page
73 static unsigned int khugepaged_max_ptes_none __read_mostly;
74 static unsigned int khugepaged_max_ptes_swap __read_mostly;
76 #define MM_SLOTS_HASH_BITS 10
77 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
79 static struct kmem_cache *mm_slot_cache __read_mostly;
81 #define MAX_PTE_MAPPED_THP 8
84 * struct mm_slot - hash lookup from mm to mm_slot
85 * @hash: hash collision list
86 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
87 * @mm: the mm that this information is valid for
90 struct hlist_node hash;
91 struct list_head mm_node;
94 /* pte-mapped THP in this mm */
95 int nr_pte_mapped_thp;
96 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
100 * struct khugepaged_scan - cursor for scanning
101 * @mm_head: the head of the mm list to scan
102 * @mm_slot: the current mm_slot we are scanning
103 * @address: the next address inside that to be scanned
105 * There is only the one khugepaged_scan instance of this cursor structure.
107 struct khugepaged_scan {
108 struct list_head mm_head;
109 struct mm_slot *mm_slot;
110 unsigned long address;
113 static struct khugepaged_scan khugepaged_scan = {
114 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
118 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
119 struct kobj_attribute *attr,
122 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
125 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
126 struct kobj_attribute *attr,
127 const char *buf, size_t count)
132 err = kstrtoul(buf, 10, &msecs);
133 if (err || msecs > UINT_MAX)
136 khugepaged_scan_sleep_millisecs = msecs;
137 khugepaged_sleep_expire = 0;
138 wake_up_interruptible(&khugepaged_wait);
142 static struct kobj_attribute scan_sleep_millisecs_attr =
143 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
144 scan_sleep_millisecs_store);
146 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
147 struct kobj_attribute *attr,
150 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
153 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
154 struct kobj_attribute *attr,
155 const char *buf, size_t count)
160 err = kstrtoul(buf, 10, &msecs);
161 if (err || msecs > UINT_MAX)
164 khugepaged_alloc_sleep_millisecs = msecs;
165 khugepaged_sleep_expire = 0;
166 wake_up_interruptible(&khugepaged_wait);
170 static struct kobj_attribute alloc_sleep_millisecs_attr =
171 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
172 alloc_sleep_millisecs_store);
174 static ssize_t pages_to_scan_show(struct kobject *kobj,
175 struct kobj_attribute *attr,
178 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
180 static ssize_t pages_to_scan_store(struct kobject *kobj,
181 struct kobj_attribute *attr,
182 const char *buf, size_t count)
187 err = kstrtoul(buf, 10, &pages);
188 if (err || !pages || pages > UINT_MAX)
191 khugepaged_pages_to_scan = pages;
195 static struct kobj_attribute pages_to_scan_attr =
196 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
197 pages_to_scan_store);
199 static ssize_t pages_collapsed_show(struct kobject *kobj,
200 struct kobj_attribute *attr,
203 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
205 static struct kobj_attribute pages_collapsed_attr =
206 __ATTR_RO(pages_collapsed);
208 static ssize_t full_scans_show(struct kobject *kobj,
209 struct kobj_attribute *attr,
212 return sprintf(buf, "%u\n", khugepaged_full_scans);
214 static struct kobj_attribute full_scans_attr =
215 __ATTR_RO(full_scans);
217 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
218 struct kobj_attribute *attr, char *buf)
220 return single_hugepage_flag_show(kobj, attr, buf,
221 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
223 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
224 struct kobj_attribute *attr,
225 const char *buf, size_t count)
227 return single_hugepage_flag_store(kobj, attr, buf, count,
228 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
230 static struct kobj_attribute khugepaged_defrag_attr =
231 __ATTR(defrag, 0644, khugepaged_defrag_show,
232 khugepaged_defrag_store);
235 * max_ptes_none controls if khugepaged should collapse hugepages over
236 * any unmapped ptes in turn potentially increasing the memory
237 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
238 * reduce the available free memory in the system as it
239 * runs. Increasing max_ptes_none will instead potentially reduce the
240 * free memory in the system during the khugepaged scan.
242 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
243 struct kobj_attribute *attr,
246 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
248 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
249 struct kobj_attribute *attr,
250 const char *buf, size_t count)
253 unsigned long max_ptes_none;
255 err = kstrtoul(buf, 10, &max_ptes_none);
256 if (err || max_ptes_none > HPAGE_PMD_NR-1)
259 khugepaged_max_ptes_none = max_ptes_none;
263 static struct kobj_attribute khugepaged_max_ptes_none_attr =
264 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
265 khugepaged_max_ptes_none_store);
267 static ssize_t khugepaged_max_ptes_swap_show(struct kobject *kobj,
268 struct kobj_attribute *attr,
271 return sprintf(buf, "%u\n", khugepaged_max_ptes_swap);
274 static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
275 struct kobj_attribute *attr,
276 const char *buf, size_t count)
279 unsigned long max_ptes_swap;
281 err = kstrtoul(buf, 10, &max_ptes_swap);
282 if (err || max_ptes_swap > HPAGE_PMD_NR-1)
285 khugepaged_max_ptes_swap = max_ptes_swap;
290 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
291 __ATTR(max_ptes_swap, 0644, khugepaged_max_ptes_swap_show,
292 khugepaged_max_ptes_swap_store);
294 static struct attribute *khugepaged_attr[] = {
295 &khugepaged_defrag_attr.attr,
296 &khugepaged_max_ptes_none_attr.attr,
297 &pages_to_scan_attr.attr,
298 &pages_collapsed_attr.attr,
299 &full_scans_attr.attr,
300 &scan_sleep_millisecs_attr.attr,
301 &alloc_sleep_millisecs_attr.attr,
302 &khugepaged_max_ptes_swap_attr.attr,
306 struct attribute_group khugepaged_attr_group = {
307 .attrs = khugepaged_attr,
308 .name = "khugepaged",
310 #endif /* CONFIG_SYSFS */
312 int hugepage_madvise(struct vm_area_struct *vma,
313 unsigned long *vm_flags, int advice)
319 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
320 * can't handle this properly after s390_enable_sie, so we simply
321 * ignore the madvise to prevent qemu from causing a SIGSEGV.
323 if (mm_has_pgste(vma->vm_mm))
326 *vm_flags &= ~VM_NOHUGEPAGE;
327 *vm_flags |= VM_HUGEPAGE;
329 * If the vma become good for khugepaged to scan,
330 * register it here without waiting a page fault that
331 * may not happen any time soon.
333 if (!(*vm_flags & VM_NO_KHUGEPAGED) &&
334 khugepaged_enter_vma_merge(vma, *vm_flags))
337 case MADV_NOHUGEPAGE:
338 *vm_flags &= ~VM_HUGEPAGE;
339 *vm_flags |= VM_NOHUGEPAGE;
341 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
342 * this vma even if we leave the mm registered in khugepaged if
343 * it got registered before VM_NOHUGEPAGE was set.
351 int __init khugepaged_init(void)
353 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
354 sizeof(struct mm_slot),
355 __alignof__(struct mm_slot), 0, NULL);
359 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
360 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
361 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
366 void __init khugepaged_destroy(void)
368 kmem_cache_destroy(mm_slot_cache);
371 static inline struct mm_slot *alloc_mm_slot(void)
373 if (!mm_slot_cache) /* initialization failed */
375 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
378 static inline void free_mm_slot(struct mm_slot *mm_slot)
380 kmem_cache_free(mm_slot_cache, mm_slot);
383 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
385 struct mm_slot *mm_slot;
387 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
388 if (mm == mm_slot->mm)
394 static void insert_to_mm_slots_hash(struct mm_struct *mm,
395 struct mm_slot *mm_slot)
398 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
401 static inline int khugepaged_test_exit(struct mm_struct *mm)
403 return atomic_read(&mm->mm_users) == 0;
406 static bool hugepage_vma_check(struct vm_area_struct *vma,
407 unsigned long vm_flags)
409 if ((!(vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
410 (vm_flags & VM_NOHUGEPAGE) ||
411 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
414 if (shmem_file(vma->vm_file) ||
415 (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
417 (vm_flags & VM_DENYWRITE))) {
418 return IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) - vma->vm_pgoff,
421 if (!vma->anon_vma || vma->vm_ops)
423 if (vma_is_temporary_stack(vma))
425 return !(vm_flags & VM_NO_KHUGEPAGED);
428 int __khugepaged_enter(struct mm_struct *mm)
430 struct mm_slot *mm_slot;
433 mm_slot = alloc_mm_slot();
437 /* __khugepaged_exit() must not run from under us */
438 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
439 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
440 free_mm_slot(mm_slot);
444 spin_lock(&khugepaged_mm_lock);
445 insert_to_mm_slots_hash(mm, mm_slot);
447 * Insert just behind the scanning cursor, to let the area settle
450 wakeup = list_empty(&khugepaged_scan.mm_head);
451 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
452 spin_unlock(&khugepaged_mm_lock);
456 wake_up_interruptible(&khugepaged_wait);
461 int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
462 unsigned long vm_flags)
464 unsigned long hstart, hend;
467 * khugepaged only supports read-only files for non-shmem files.
468 * khugepaged does not yet work on special mappings. And
469 * file-private shmem THP is not supported.
471 if (!hugepage_vma_check(vma, vm_flags))
474 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
475 hend = vma->vm_end & HPAGE_PMD_MASK;
477 return khugepaged_enter(vma, vm_flags);
481 void __khugepaged_exit(struct mm_struct *mm)
483 struct mm_slot *mm_slot;
486 spin_lock(&khugepaged_mm_lock);
487 mm_slot = get_mm_slot(mm);
488 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
489 hash_del(&mm_slot->hash);
490 list_del(&mm_slot->mm_node);
493 spin_unlock(&khugepaged_mm_lock);
496 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
497 free_mm_slot(mm_slot);
499 } else if (mm_slot) {
501 * This is required to serialize against
502 * khugepaged_test_exit() (which is guaranteed to run
503 * under mmap sem read mode). Stop here (after we
504 * return all pagetables will be destroyed) until
505 * khugepaged has finished working on the pagetables
506 * under the mmap_sem.
508 down_write(&mm->mmap_sem);
509 up_write(&mm->mmap_sem);
513 static void release_pte_page(struct page *page)
515 mod_node_page_state(page_pgdat(page),
516 NR_ISOLATED_ANON + page_is_file_lru(page),
519 putback_lru_page(page);
522 static void release_pte_pages(pte_t *pte, pte_t *_pte,
523 struct list_head *compound_pagelist)
525 struct page *page, *tmp;
527 while (--_pte >= pte) {
528 pte_t pteval = *_pte;
530 page = pte_page(pteval);
531 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
533 release_pte_page(page);
536 list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
537 list_del(&page->lru);
538 release_pte_page(page);
542 static bool is_refcount_suitable(struct page *page)
544 int expected_refcount;
546 expected_refcount = total_mapcount(page);
547 if (PageSwapCache(page))
548 expected_refcount += compound_nr(page);
550 return page_count(page) == expected_refcount;
553 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
554 unsigned long address,
556 struct list_head *compound_pagelist)
558 struct page *page = NULL;
560 int none_or_zero = 0, result = 0, referenced = 0;
561 bool writable = false;
563 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
564 _pte++, address += PAGE_SIZE) {
565 pte_t pteval = *_pte;
566 if (pte_none(pteval) || (pte_present(pteval) &&
567 is_zero_pfn(pte_pfn(pteval)))) {
568 if (!userfaultfd_armed(vma) &&
569 ++none_or_zero <= khugepaged_max_ptes_none) {
572 result = SCAN_EXCEED_NONE_PTE;
576 if (!pte_present(pteval)) {
577 result = SCAN_PTE_NON_PRESENT;
580 page = vm_normal_page(vma, address, pteval);
581 if (unlikely(!page)) {
582 result = SCAN_PAGE_NULL;
586 VM_BUG_ON_PAGE(!PageAnon(page), page);
588 if (PageCompound(page)) {
590 page = compound_head(page);
593 * Check if we have dealt with the compound page
596 list_for_each_entry(p, compound_pagelist, lru) {
603 * We can do it before isolate_lru_page because the
604 * page can't be freed from under us. NOTE: PG_lock
605 * is needed to serialize against split_huge_page
606 * when invoked from the VM.
608 if (!trylock_page(page)) {
609 result = SCAN_PAGE_LOCK;
614 * Check if the page has any GUP (or other external) pins.
616 * The page table that maps the page has been already unlinked
617 * from the page table tree and this process cannot get
618 * an additinal pin on the page.
620 * New pins can come later if the page is shared across fork,
621 * but not from this process. The other process cannot write to
622 * the page, only trigger CoW.
624 if (!is_refcount_suitable(page)) {
626 result = SCAN_PAGE_COUNT;
629 if (!pte_write(pteval) && PageSwapCache(page) &&
630 !reuse_swap_page(page, NULL)) {
632 * Page is in the swap cache and cannot be re-used.
633 * It cannot be collapsed into a THP.
636 result = SCAN_SWAP_CACHE_PAGE;
641 * Isolate the page to avoid collapsing an hugepage
642 * currently in use by the VM.
644 if (isolate_lru_page(page)) {
646 result = SCAN_DEL_PAGE_LRU;
649 mod_node_page_state(page_pgdat(page),
650 NR_ISOLATED_ANON + page_is_file_lru(page),
652 VM_BUG_ON_PAGE(!PageLocked(page), page);
653 VM_BUG_ON_PAGE(PageLRU(page), page);
655 if (PageCompound(page))
656 list_add_tail(&page->lru, compound_pagelist);
658 /* There should be enough young pte to collapse the page */
659 if (pte_young(pteval) ||
660 page_is_young(page) || PageReferenced(page) ||
661 mmu_notifier_test_young(vma->vm_mm, address))
664 if (pte_write(pteval))
667 if (likely(writable)) {
668 if (likely(referenced)) {
669 result = SCAN_SUCCEED;
670 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
671 referenced, writable, result);
675 result = SCAN_PAGE_RO;
679 release_pte_pages(pte, _pte, compound_pagelist);
680 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
681 referenced, writable, result);
685 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
686 struct vm_area_struct *vma,
687 unsigned long address,
689 struct list_head *compound_pagelist)
691 struct page *src_page, *tmp;
693 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
694 _pte++, page++, address += PAGE_SIZE) {
695 pte_t pteval = *_pte;
697 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
698 clear_user_highpage(page, address);
699 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
700 if (is_zero_pfn(pte_pfn(pteval))) {
702 * ptl mostly unnecessary.
706 * paravirt calls inside pte_clear here are
709 pte_clear(vma->vm_mm, address, _pte);
713 src_page = pte_page(pteval);
714 copy_user_highpage(page, src_page, address, vma);
715 if (!PageCompound(src_page))
716 release_pte_page(src_page);
718 * ptl mostly unnecessary, but preempt has to
719 * be disabled to update the per-cpu stats
720 * inside page_remove_rmap().
724 * paravirt calls inside pte_clear here are
727 pte_clear(vma->vm_mm, address, _pte);
728 page_remove_rmap(src_page, false);
730 free_page_and_swap_cache(src_page);
734 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
735 list_del(&src_page->lru);
736 release_pte_page(src_page);
740 static void khugepaged_alloc_sleep(void)
744 add_wait_queue(&khugepaged_wait, &wait);
745 freezable_schedule_timeout_interruptible(
746 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
747 remove_wait_queue(&khugepaged_wait, &wait);
750 static int khugepaged_node_load[MAX_NUMNODES];
752 static bool khugepaged_scan_abort(int nid)
757 * If node_reclaim_mode is disabled, then no extra effort is made to
758 * allocate memory locally.
760 if (!node_reclaim_mode)
763 /* If there is a count for this node already, it must be acceptable */
764 if (khugepaged_node_load[nid])
767 for (i = 0; i < MAX_NUMNODES; i++) {
768 if (!khugepaged_node_load[i])
770 if (node_distance(nid, i) > node_reclaim_distance)
776 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
777 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
779 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
783 static int khugepaged_find_target_node(void)
785 static int last_khugepaged_target_node = NUMA_NO_NODE;
786 int nid, target_node = 0, max_value = 0;
788 /* find first node with max normal pages hit */
789 for (nid = 0; nid < MAX_NUMNODES; nid++)
790 if (khugepaged_node_load[nid] > max_value) {
791 max_value = khugepaged_node_load[nid];
795 /* do some balance if several nodes have the same hit record */
796 if (target_node <= last_khugepaged_target_node)
797 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
799 if (max_value == khugepaged_node_load[nid]) {
804 last_khugepaged_target_node = target_node;
808 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
810 if (IS_ERR(*hpage)) {
816 khugepaged_alloc_sleep();
826 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
828 VM_BUG_ON_PAGE(*hpage, *hpage);
830 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
831 if (unlikely(!*hpage)) {
832 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
833 *hpage = ERR_PTR(-ENOMEM);
837 prep_transhuge_page(*hpage);
838 count_vm_event(THP_COLLAPSE_ALLOC);
842 static int khugepaged_find_target_node(void)
847 static inline struct page *alloc_khugepaged_hugepage(void)
851 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
854 prep_transhuge_page(page);
858 static struct page *khugepaged_alloc_hugepage(bool *wait)
863 hpage = alloc_khugepaged_hugepage();
865 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
870 khugepaged_alloc_sleep();
872 count_vm_event(THP_COLLAPSE_ALLOC);
873 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
878 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
881 *hpage = khugepaged_alloc_hugepage(wait);
883 if (unlikely(!*hpage))
890 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
899 * If mmap_sem temporarily dropped, revalidate vma
900 * before taking mmap_sem.
901 * Return 0 if succeeds, otherwise return none-zero
905 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
906 struct vm_area_struct **vmap)
908 struct vm_area_struct *vma;
909 unsigned long hstart, hend;
911 if (unlikely(khugepaged_test_exit(mm)))
912 return SCAN_ANY_PROCESS;
914 *vmap = vma = find_vma(mm, address);
916 return SCAN_VMA_NULL;
918 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
919 hend = vma->vm_end & HPAGE_PMD_MASK;
920 if (address < hstart || address + HPAGE_PMD_SIZE > hend)
921 return SCAN_ADDRESS_RANGE;
922 if (!hugepage_vma_check(vma, vma->vm_flags))
923 return SCAN_VMA_CHECK;
928 * Bring missing pages in from swap, to complete THP collapse.
929 * Only done if khugepaged_scan_pmd believes it is worthwhile.
931 * Called and returns without pte mapped or spinlocks held,
932 * but with mmap_sem held to protect against vma changes.
935 static bool __collapse_huge_page_swapin(struct mm_struct *mm,
936 struct vm_area_struct *vma,
937 unsigned long address, pmd_t *pmd,
942 struct vm_fault vmf = {
945 .flags = FAULT_FLAG_ALLOW_RETRY,
947 .pgoff = linear_page_index(vma, address),
950 vmf.pte = pte_offset_map(pmd, address);
951 for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
952 vmf.pte++, vmf.address += PAGE_SIZE) {
953 vmf.orig_pte = *vmf.pte;
954 if (!is_swap_pte(vmf.orig_pte))
957 ret = do_swap_page(&vmf);
959 /* do_swap_page returns VM_FAULT_RETRY with released mmap_sem */
960 if (ret & VM_FAULT_RETRY) {
961 down_read(&mm->mmap_sem);
962 if (hugepage_vma_revalidate(mm, address, &vmf.vma)) {
963 /* vma is no longer available, don't continue to swapin */
964 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
967 /* check if the pmd is still valid */
968 if (mm_find_pmd(mm, address) != pmd) {
969 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
973 if (ret & VM_FAULT_ERROR) {
974 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
977 /* pte is unmapped now, we need to map it */
978 vmf.pte = pte_offset_map(pmd, vmf.address);
983 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
987 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
991 static void collapse_huge_page(struct mm_struct *mm,
992 unsigned long address,
994 int node, int referenced, int unmapped)
996 LIST_HEAD(compound_pagelist);
1000 struct page *new_page;
1001 spinlock_t *pmd_ptl, *pte_ptl;
1002 int isolated = 0, result = 0;
1003 struct mem_cgroup *memcg;
1004 struct vm_area_struct *vma;
1005 struct mmu_notifier_range range;
1008 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1010 /* Only allocate from the target node */
1011 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1014 * Before allocating the hugepage, release the mmap_sem read lock.
1015 * The allocation can take potentially a long time if it involves
1016 * sync compaction, and we do not need to hold the mmap_sem during
1017 * that. We will recheck the vma after taking it again in write mode.
1019 up_read(&mm->mmap_sem);
1020 new_page = khugepaged_alloc_page(hpage, gfp, node);
1022 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1026 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
1027 result = SCAN_CGROUP_CHARGE_FAIL;
1031 down_read(&mm->mmap_sem);
1032 result = hugepage_vma_revalidate(mm, address, &vma);
1034 mem_cgroup_cancel_charge(new_page, memcg, true);
1035 up_read(&mm->mmap_sem);
1039 pmd = mm_find_pmd(mm, address);
1041 result = SCAN_PMD_NULL;
1042 mem_cgroup_cancel_charge(new_page, memcg, true);
1043 up_read(&mm->mmap_sem);
1048 * __collapse_huge_page_swapin always returns with mmap_sem locked.
1049 * If it fails, we release mmap_sem and jump out_nolock.
1050 * Continuing to collapse causes inconsistency.
1052 if (unmapped && !__collapse_huge_page_swapin(mm, vma, address,
1054 mem_cgroup_cancel_charge(new_page, memcg, true);
1055 up_read(&mm->mmap_sem);
1059 up_read(&mm->mmap_sem);
1061 * Prevent all access to pagetables with the exception of
1062 * gup_fast later handled by the ptep_clear_flush and the VM
1063 * handled by the anon_vma lock + PG_lock.
1065 down_write(&mm->mmap_sem);
1066 result = SCAN_ANY_PROCESS;
1067 if (!mmget_still_valid(mm))
1069 result = hugepage_vma_revalidate(mm, address, &vma);
1072 /* check if the pmd is still valid */
1073 if (mm_find_pmd(mm, address) != pmd)
1076 anon_vma_lock_write(vma->anon_vma);
1078 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1079 address, address + HPAGE_PMD_SIZE);
1080 mmu_notifier_invalidate_range_start(&range);
1082 pte = pte_offset_map(pmd, address);
1083 pte_ptl = pte_lockptr(mm, pmd);
1085 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1087 * After this gup_fast can't run anymore. This also removes
1088 * any huge TLB entry from the CPU so we won't allow
1089 * huge and small TLB entries for the same virtual address
1090 * to avoid the risk of CPU bugs in that area.
1092 _pmd = pmdp_collapse_flush(vma, address, pmd);
1093 spin_unlock(pmd_ptl);
1094 mmu_notifier_invalidate_range_end(&range);
1097 isolated = __collapse_huge_page_isolate(vma, address, pte,
1098 &compound_pagelist);
1099 spin_unlock(pte_ptl);
1101 if (unlikely(!isolated)) {
1104 BUG_ON(!pmd_none(*pmd));
1106 * We can only use set_pmd_at when establishing
1107 * hugepmds and never for establishing regular pmds that
1108 * points to regular pagetables. Use pmd_populate for that
1110 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1111 spin_unlock(pmd_ptl);
1112 anon_vma_unlock_write(vma->anon_vma);
1118 * All pages are isolated and locked so anon_vma rmap
1119 * can't run anymore.
1121 anon_vma_unlock_write(vma->anon_vma);
1123 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl,
1124 &compound_pagelist);
1126 __SetPageUptodate(new_page);
1127 pgtable = pmd_pgtable(_pmd);
1129 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1130 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1133 * spin_lock() below is not the equivalent of smp_wmb(), so
1134 * this is needed to avoid the copy_huge_page writes to become
1135 * visible after the set_pmd_at() write.
1140 BUG_ON(!pmd_none(*pmd));
1141 page_add_new_anon_rmap(new_page, vma, address, true);
1142 mem_cgroup_commit_charge(new_page, memcg, false, true);
1143 count_memcg_events(memcg, THP_COLLAPSE_ALLOC, 1);
1144 lru_cache_add_active_or_unevictable(new_page, vma);
1145 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1146 set_pmd_at(mm, address, pmd, _pmd);
1147 update_mmu_cache_pmd(vma, address, pmd);
1148 spin_unlock(pmd_ptl);
1152 khugepaged_pages_collapsed++;
1153 result = SCAN_SUCCEED;
1155 up_write(&mm->mmap_sem);
1157 trace_mm_collapse_huge_page(mm, isolated, result);
1160 mem_cgroup_cancel_charge(new_page, memcg, true);
1164 static int khugepaged_scan_pmd(struct mm_struct *mm,
1165 struct vm_area_struct *vma,
1166 unsigned long address,
1167 struct page **hpage)
1171 int ret = 0, none_or_zero = 0, result = 0, referenced = 0;
1172 struct page *page = NULL;
1173 unsigned long _address;
1175 int node = NUMA_NO_NODE, unmapped = 0;
1176 bool writable = false;
1178 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1180 pmd = mm_find_pmd(mm, address);
1182 result = SCAN_PMD_NULL;
1186 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1187 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1188 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1189 _pte++, _address += PAGE_SIZE) {
1190 pte_t pteval = *_pte;
1191 if (is_swap_pte(pteval)) {
1192 if (++unmapped <= khugepaged_max_ptes_swap) {
1194 * Always be strict with uffd-wp
1195 * enabled swap entries. Please see
1196 * comment below for pte_uffd_wp().
1198 if (pte_swp_uffd_wp(pteval)) {
1199 result = SCAN_PTE_UFFD_WP;
1204 result = SCAN_EXCEED_SWAP_PTE;
1208 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1209 if (!userfaultfd_armed(vma) &&
1210 ++none_or_zero <= khugepaged_max_ptes_none) {
1213 result = SCAN_EXCEED_NONE_PTE;
1217 if (!pte_present(pteval)) {
1218 result = SCAN_PTE_NON_PRESENT;
1221 if (pte_uffd_wp(pteval)) {
1223 * Don't collapse the page if any of the small
1224 * PTEs are armed with uffd write protection.
1225 * Here we can also mark the new huge pmd as
1226 * write protected if any of the small ones is
1227 * marked but that could bring uknown
1228 * userfault messages that falls outside of
1229 * the registered range. So, just be simple.
1231 result = SCAN_PTE_UFFD_WP;
1234 if (pte_write(pteval))
1237 page = vm_normal_page(vma, _address, pteval);
1238 if (unlikely(!page)) {
1239 result = SCAN_PAGE_NULL;
1243 page = compound_head(page);
1246 * Record which node the original page is from and save this
1247 * information to khugepaged_node_load[].
1248 * Khupaged will allocate hugepage from the node has the max
1251 node = page_to_nid(page);
1252 if (khugepaged_scan_abort(node)) {
1253 result = SCAN_SCAN_ABORT;
1256 khugepaged_node_load[node]++;
1257 if (!PageLRU(page)) {
1258 result = SCAN_PAGE_LRU;
1261 if (PageLocked(page)) {
1262 result = SCAN_PAGE_LOCK;
1265 if (!PageAnon(page)) {
1266 result = SCAN_PAGE_ANON;
1271 * Check if the page has any GUP (or other external) pins.
1273 * Here the check is racy it may see totmal_mapcount > refcount
1275 * For example, one process with one forked child process.
1276 * The parent has the PMD split due to MADV_DONTNEED, then
1277 * the child is trying unmap the whole PMD, but khugepaged
1278 * may be scanning the parent between the child has
1279 * PageDoubleMap flag cleared and dec the mapcount. So
1280 * khugepaged may see total_mapcount > refcount.
1282 * But such case is ephemeral we could always retry collapse
1283 * later. However it may report false positive if the page
1284 * has excessive GUP pins (i.e. 512). Anyway the same check
1285 * will be done again later the risk seems low.
1287 if (!is_refcount_suitable(page)) {
1288 result = SCAN_PAGE_COUNT;
1291 if (pte_young(pteval) ||
1292 page_is_young(page) || PageReferenced(page) ||
1293 mmu_notifier_test_young(vma->vm_mm, address))
1297 result = SCAN_PAGE_RO;
1298 } else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
1299 result = SCAN_LACK_REFERENCED_PAGE;
1301 result = SCAN_SUCCEED;
1305 pte_unmap_unlock(pte, ptl);
1307 node = khugepaged_find_target_node();
1308 /* collapse_huge_page will return with the mmap_sem released */
1309 collapse_huge_page(mm, address, hpage, node,
1310 referenced, unmapped);
1313 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1314 none_or_zero, result, unmapped);
1318 static void collect_mm_slot(struct mm_slot *mm_slot)
1320 struct mm_struct *mm = mm_slot->mm;
1322 lockdep_assert_held(&khugepaged_mm_lock);
1324 if (khugepaged_test_exit(mm)) {
1326 hash_del(&mm_slot->hash);
1327 list_del(&mm_slot->mm_node);
1330 * Not strictly needed because the mm exited already.
1332 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1335 /* khugepaged_mm_lock actually not necessary for the below */
1336 free_mm_slot(mm_slot);
1343 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1344 * khugepaged should try to collapse the page table.
1346 static int khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1349 struct mm_slot *mm_slot;
1351 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1353 spin_lock(&khugepaged_mm_lock);
1354 mm_slot = get_mm_slot(mm);
1355 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
1356 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1357 spin_unlock(&khugepaged_mm_lock);
1362 * Try to collapse a pte-mapped THP for mm at address haddr.
1364 * This function checks whether all the PTEs in the PMD are pointing to the
1365 * right THP. If so, retract the page table so the THP can refault in with
1368 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
1370 unsigned long haddr = addr & HPAGE_PMD_MASK;
1371 struct vm_area_struct *vma = find_vma(mm, haddr);
1372 struct page *hpage = NULL;
1373 pte_t *start_pte, *pte;
1379 if (!vma || !vma->vm_file ||
1380 vma->vm_start > haddr || vma->vm_end < haddr + HPAGE_PMD_SIZE)
1384 * This vm_flags may not have VM_HUGEPAGE if the page was not
1385 * collapsed by this mm. But we can still collapse if the page is
1386 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
1387 * will not fail the vma for missing VM_HUGEPAGE
1389 if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE))
1392 pmd = mm_find_pmd(mm, haddr);
1396 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1398 /* step 1: check all mapped PTEs are to the right huge page */
1399 for (i = 0, addr = haddr, pte = start_pte;
1400 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1403 /* empty pte, skip */
1407 /* page swapped out, abort */
1408 if (!pte_present(*pte))
1411 page = vm_normal_page(vma, addr, *pte);
1413 if (!page || !PageCompound(page))
1417 hpage = compound_head(page);
1419 * The mapping of the THP should not change.
1421 * Note that uprobe, debugger, or MAP_PRIVATE may
1422 * change the page table, but the new page will
1423 * not pass PageCompound() check.
1425 if (WARN_ON(hpage->mapping != vma->vm_file->f_mapping))
1430 * Confirm the page maps to the correct subpage.
1432 * Note that uprobe, debugger, or MAP_PRIVATE may change
1433 * the page table, but the new page will not pass
1434 * PageCompound() check.
1436 if (WARN_ON(hpage + i != page))
1441 /* step 2: adjust rmap */
1442 for (i = 0, addr = haddr, pte = start_pte;
1443 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1448 page = vm_normal_page(vma, addr, *pte);
1449 page_remove_rmap(page, false);
1452 pte_unmap_unlock(start_pte, ptl);
1454 /* step 3: set proper refcount and mm_counters. */
1456 page_ref_sub(hpage, count);
1457 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1460 /* step 4: collapse pmd */
1461 ptl = pmd_lock(vma->vm_mm, pmd);
1462 _pmd = pmdp_collapse_flush(vma, addr, pmd);
1465 pte_free(mm, pmd_pgtable(_pmd));
1469 pte_unmap_unlock(start_pte, ptl);
1472 static int khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1474 struct mm_struct *mm = mm_slot->mm;
1477 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1480 if (!down_write_trylock(&mm->mmap_sem))
1483 if (unlikely(khugepaged_test_exit(mm)))
1486 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1487 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
1490 mm_slot->nr_pte_mapped_thp = 0;
1491 up_write(&mm->mmap_sem);
1495 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1497 struct vm_area_struct *vma;
1501 i_mmap_lock_write(mapping);
1502 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1504 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1505 * got written to. These VMAs are likely not worth investing
1506 * down_write(mmap_sem) as PMD-mapping is likely to be split
1509 * Not that vma->anon_vma check is racy: it can be set up after
1510 * the check but before we took mmap_sem by the fault path.
1511 * But page lock would prevent establishing any new ptes of the
1512 * page, so we are safe.
1514 * An alternative would be drop the check, but check that page
1515 * table is clear before calling pmdp_collapse_flush() under
1516 * ptl. It has higher chance to recover THP for the VMA, but
1517 * has higher cost too.
1521 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1522 if (addr & ~HPAGE_PMD_MASK)
1524 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1526 pmd = mm_find_pmd(vma->vm_mm, addr);
1530 * We need exclusive mmap_sem to retract page table.
1532 * We use trylock due to lock inversion: we need to acquire
1533 * mmap_sem while holding page lock. Fault path does it in
1534 * reverse order. Trylock is a way to avoid deadlock.
1536 if (down_write_trylock(&vma->vm_mm->mmap_sem)) {
1537 spinlock_t *ptl = pmd_lock(vma->vm_mm, pmd);
1538 /* assume page table is clear */
1539 _pmd = pmdp_collapse_flush(vma, addr, pmd);
1541 up_write(&vma->vm_mm->mmap_sem);
1542 mm_dec_nr_ptes(vma->vm_mm);
1543 pte_free(vma->vm_mm, pmd_pgtable(_pmd));
1545 /* Try again later */
1546 khugepaged_add_pte_mapped_thp(vma->vm_mm, addr);
1549 i_mmap_unlock_write(mapping);
1553 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1555 * Basic scheme is simple, details are more complex:
1556 * - allocate and lock a new huge page;
1557 * - scan page cache replacing old pages with the new one
1558 * + swap/gup in pages if necessary;
1560 * + keep old pages around in case rollback is required;
1561 * - if replacing succeeds:
1564 * + unlock huge page;
1565 * - if replacing failed;
1566 * + put all pages back and unfreeze them;
1567 * + restore gaps in the page cache;
1568 * + unlock and free huge page;
1570 static void collapse_file(struct mm_struct *mm,
1571 struct file *file, pgoff_t start,
1572 struct page **hpage, int node)
1574 struct address_space *mapping = file->f_mapping;
1576 struct page *new_page;
1577 struct mem_cgroup *memcg;
1578 pgoff_t index, end = start + HPAGE_PMD_NR;
1579 LIST_HEAD(pagelist);
1580 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1581 int nr_none = 0, result = SCAN_SUCCEED;
1582 bool is_shmem = shmem_file(file);
1584 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1585 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1587 /* Only allocate from the target node */
1588 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1590 new_page = khugepaged_alloc_page(hpage, gfp, node);
1592 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1596 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
1597 result = SCAN_CGROUP_CHARGE_FAIL;
1601 /* This will be less messy when we use multi-index entries */
1604 xas_create_range(&xas);
1605 if (!xas_error(&xas))
1607 xas_unlock_irq(&xas);
1608 if (!xas_nomem(&xas, GFP_KERNEL)) {
1609 mem_cgroup_cancel_charge(new_page, memcg, true);
1615 __SetPageLocked(new_page);
1617 __SetPageSwapBacked(new_page);
1618 new_page->index = start;
1619 new_page->mapping = mapping;
1622 * At this point the new_page is locked and not up-to-date.
1623 * It's safe to insert it into the page cache, because nobody would
1624 * be able to map it or use it in another way until we unlock it.
1627 xas_set(&xas, start);
1628 for (index = start; index < end; index++) {
1629 struct page *page = xas_next(&xas);
1631 VM_BUG_ON(index != xas.xa_index);
1635 * Stop if extent has been truncated or
1636 * hole-punched, and is now completely
1639 if (index == start) {
1640 if (!xas_next_entry(&xas, end - 1)) {
1641 result = SCAN_TRUNCATED;
1644 xas_set(&xas, index);
1646 if (!shmem_charge(mapping->host, 1)) {
1650 xas_store(&xas, new_page);
1655 if (xa_is_value(page) || !PageUptodate(page)) {
1656 xas_unlock_irq(&xas);
1657 /* swap in or instantiate fallocated page */
1658 if (shmem_getpage(mapping->host, index, &page,
1663 } else if (trylock_page(page)) {
1665 xas_unlock_irq(&xas);
1667 result = SCAN_PAGE_LOCK;
1670 } else { /* !is_shmem */
1671 if (!page || xa_is_value(page)) {
1672 xas_unlock_irq(&xas);
1673 page_cache_sync_readahead(mapping, &file->f_ra,
1676 /* drain pagevecs to help isolate_lru_page() */
1678 page = find_lock_page(mapping, index);
1679 if (unlikely(page == NULL)) {
1683 } else if (PageDirty(page)) {
1685 * khugepaged only works on read-only fd,
1686 * so this page is dirty because it hasn't
1687 * been flushed since first write. There
1688 * won't be new dirty pages.
1690 * Trigger async flush here and hope the
1691 * writeback is done when khugepaged
1692 * revisits this page.
1694 * This is a one-off situation. We are not
1695 * forcing writeback in loop.
1697 xas_unlock_irq(&xas);
1698 filemap_flush(mapping);
1701 } else if (trylock_page(page)) {
1703 xas_unlock_irq(&xas);
1705 result = SCAN_PAGE_LOCK;
1711 * The page must be locked, so we can drop the i_pages lock
1712 * without racing with truncate.
1714 VM_BUG_ON_PAGE(!PageLocked(page), page);
1716 /* make sure the page is up to date */
1717 if (unlikely(!PageUptodate(page))) {
1723 * If file was truncated then extended, or hole-punched, before
1724 * we locked the first page, then a THP might be there already.
1726 if (PageTransCompound(page)) {
1727 result = SCAN_PAGE_COMPOUND;
1731 if (page_mapping(page) != mapping) {
1732 result = SCAN_TRUNCATED;
1736 if (!is_shmem && PageDirty(page)) {
1738 * khugepaged only works on read-only fd, so this
1739 * page is dirty because it hasn't been flushed
1740 * since first write.
1746 if (isolate_lru_page(page)) {
1747 result = SCAN_DEL_PAGE_LRU;
1751 if (page_has_private(page) &&
1752 !try_to_release_page(page, GFP_KERNEL)) {
1753 result = SCAN_PAGE_HAS_PRIVATE;
1754 putback_lru_page(page);
1758 if (page_mapped(page))
1759 unmap_mapping_pages(mapping, index, 1, false);
1762 xas_set(&xas, index);
1764 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1765 VM_BUG_ON_PAGE(page_mapped(page), page);
1768 * The page is expected to have page_count() == 3:
1769 * - we hold a pin on it;
1770 * - one reference from page cache;
1771 * - one from isolate_lru_page;
1773 if (!page_ref_freeze(page, 3)) {
1774 result = SCAN_PAGE_COUNT;
1775 xas_unlock_irq(&xas);
1776 putback_lru_page(page);
1781 * Add the page to the list to be able to undo the collapse if
1782 * something go wrong.
1784 list_add_tail(&page->lru, &pagelist);
1786 /* Finally, replace with the new page. */
1787 xas_store(&xas, new_page);
1796 __inc_node_page_state(new_page, NR_SHMEM_THPS);
1798 __inc_node_page_state(new_page, NR_FILE_THPS);
1799 filemap_nr_thps_inc(mapping);
1803 struct zone *zone = page_zone(new_page);
1805 __mod_node_page_state(zone->zone_pgdat, NR_FILE_PAGES, nr_none);
1807 __mod_node_page_state(zone->zone_pgdat,
1812 xas_unlock_irq(&xas);
1815 if (result == SCAN_SUCCEED) {
1816 struct page *page, *tmp;
1819 * Replacing old pages with new one has succeeded, now we
1820 * need to copy the content and free the old pages.
1823 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1824 while (index < page->index) {
1825 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1828 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1830 list_del(&page->lru);
1831 page->mapping = NULL;
1832 page_ref_unfreeze(page, 1);
1833 ClearPageActive(page);
1834 ClearPageUnevictable(page);
1839 while (index < end) {
1840 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1844 SetPageUptodate(new_page);
1845 page_ref_add(new_page, HPAGE_PMD_NR - 1);
1846 mem_cgroup_commit_charge(new_page, memcg, false, true);
1849 set_page_dirty(new_page);
1850 lru_cache_add_anon(new_page);
1852 lru_cache_add_file(new_page);
1854 count_memcg_events(memcg, THP_COLLAPSE_ALLOC, 1);
1857 * Remove pte page tables, so we can re-fault the page as huge.
1859 retract_page_tables(mapping, start);
1862 khugepaged_pages_collapsed++;
1866 /* Something went wrong: roll back page cache changes */
1868 mapping->nrpages -= nr_none;
1871 shmem_uncharge(mapping->host, nr_none);
1873 xas_set(&xas, start);
1874 xas_for_each(&xas, page, end - 1) {
1875 page = list_first_entry_or_null(&pagelist,
1877 if (!page || xas.xa_index < page->index) {
1881 /* Put holes back where they were */
1882 xas_store(&xas, NULL);
1886 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1888 /* Unfreeze the page. */
1889 list_del(&page->lru);
1890 page_ref_unfreeze(page, 2);
1891 xas_store(&xas, page);
1893 xas_unlock_irq(&xas);
1895 putback_lru_page(page);
1899 xas_unlock_irq(&xas);
1901 mem_cgroup_cancel_charge(new_page, memcg, true);
1902 new_page->mapping = NULL;
1905 unlock_page(new_page);
1907 VM_BUG_ON(!list_empty(&pagelist));
1908 /* TODO: tracepoints */
1911 static void khugepaged_scan_file(struct mm_struct *mm,
1912 struct file *file, pgoff_t start, struct page **hpage)
1914 struct page *page = NULL;
1915 struct address_space *mapping = file->f_mapping;
1916 XA_STATE(xas, &mapping->i_pages, start);
1918 int node = NUMA_NO_NODE;
1919 int result = SCAN_SUCCEED;
1923 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1925 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
1926 if (xas_retry(&xas, page))
1929 if (xa_is_value(page)) {
1930 if (++swap > khugepaged_max_ptes_swap) {
1931 result = SCAN_EXCEED_SWAP_PTE;
1937 if (PageTransCompound(page)) {
1938 result = SCAN_PAGE_COMPOUND;
1942 node = page_to_nid(page);
1943 if (khugepaged_scan_abort(node)) {
1944 result = SCAN_SCAN_ABORT;
1947 khugepaged_node_load[node]++;
1949 if (!PageLRU(page)) {
1950 result = SCAN_PAGE_LRU;
1954 if (page_count(page) !=
1955 1 + page_mapcount(page) + page_has_private(page)) {
1956 result = SCAN_PAGE_COUNT;
1961 * We probably should check if the page is referenced here, but
1962 * nobody would transfer pte_young() to PageReferenced() for us.
1963 * And rmap walk here is just too costly...
1968 if (need_resched()) {
1975 if (result == SCAN_SUCCEED) {
1976 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
1977 result = SCAN_EXCEED_NONE_PTE;
1979 node = khugepaged_find_target_node();
1980 collapse_file(mm, file, start, hpage, node);
1984 /* TODO: tracepoints */
1987 static void khugepaged_scan_file(struct mm_struct *mm,
1988 struct file *file, pgoff_t start, struct page **hpage)
1993 static int khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1999 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2000 struct page **hpage)
2001 __releases(&khugepaged_mm_lock)
2002 __acquires(&khugepaged_mm_lock)
2004 struct mm_slot *mm_slot;
2005 struct mm_struct *mm;
2006 struct vm_area_struct *vma;
2010 lockdep_assert_held(&khugepaged_mm_lock);
2012 if (khugepaged_scan.mm_slot)
2013 mm_slot = khugepaged_scan.mm_slot;
2015 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2016 struct mm_slot, mm_node);
2017 khugepaged_scan.address = 0;
2018 khugepaged_scan.mm_slot = mm_slot;
2020 spin_unlock(&khugepaged_mm_lock);
2021 khugepaged_collapse_pte_mapped_thps(mm_slot);
2025 * Don't wait for semaphore (to avoid long wait times). Just move to
2026 * the next mm on the list.
2029 if (unlikely(!down_read_trylock(&mm->mmap_sem)))
2030 goto breakouterloop_mmap_sem;
2031 if (likely(!khugepaged_test_exit(mm)))
2032 vma = find_vma(mm, khugepaged_scan.address);
2035 for (; vma; vma = vma->vm_next) {
2036 unsigned long hstart, hend;
2039 if (unlikely(khugepaged_test_exit(mm))) {
2043 if (!hugepage_vma_check(vma, vma->vm_flags)) {
2048 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2049 hend = vma->vm_end & HPAGE_PMD_MASK;
2052 if (khugepaged_scan.address > hend)
2054 if (khugepaged_scan.address < hstart)
2055 khugepaged_scan.address = hstart;
2056 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2057 if (shmem_file(vma->vm_file) && !shmem_huge_enabled(vma))
2060 while (khugepaged_scan.address < hend) {
2063 if (unlikely(khugepaged_test_exit(mm)))
2064 goto breakouterloop;
2066 VM_BUG_ON(khugepaged_scan.address < hstart ||
2067 khugepaged_scan.address + HPAGE_PMD_SIZE >
2069 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2070 struct file *file = get_file(vma->vm_file);
2071 pgoff_t pgoff = linear_page_index(vma,
2072 khugepaged_scan.address);
2074 up_read(&mm->mmap_sem);
2076 khugepaged_scan_file(mm, file, pgoff, hpage);
2079 ret = khugepaged_scan_pmd(mm, vma,
2080 khugepaged_scan.address,
2083 /* move to next address */
2084 khugepaged_scan.address += HPAGE_PMD_SIZE;
2085 progress += HPAGE_PMD_NR;
2087 /* we released mmap_sem so break loop */
2088 goto breakouterloop_mmap_sem;
2089 if (progress >= pages)
2090 goto breakouterloop;
2094 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2095 breakouterloop_mmap_sem:
2097 spin_lock(&khugepaged_mm_lock);
2098 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2100 * Release the current mm_slot if this mm is about to die, or
2101 * if we scanned all vmas of this mm.
2103 if (khugepaged_test_exit(mm) || !vma) {
2105 * Make sure that if mm_users is reaching zero while
2106 * khugepaged runs here, khugepaged_exit will find
2107 * mm_slot not pointing to the exiting mm.
2109 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2110 khugepaged_scan.mm_slot = list_entry(
2111 mm_slot->mm_node.next,
2112 struct mm_slot, mm_node);
2113 khugepaged_scan.address = 0;
2115 khugepaged_scan.mm_slot = NULL;
2116 khugepaged_full_scans++;
2119 collect_mm_slot(mm_slot);
2125 static int khugepaged_has_work(void)
2127 return !list_empty(&khugepaged_scan.mm_head) &&
2128 khugepaged_enabled();
2131 static int khugepaged_wait_event(void)
2133 return !list_empty(&khugepaged_scan.mm_head) ||
2134 kthread_should_stop();
2137 static void khugepaged_do_scan(void)
2139 struct page *hpage = NULL;
2140 unsigned int progress = 0, pass_through_head = 0;
2141 unsigned int pages = khugepaged_pages_to_scan;
2144 barrier(); /* write khugepaged_pages_to_scan to local stack */
2146 lru_add_drain_all();
2148 while (progress < pages) {
2149 if (!khugepaged_prealloc_page(&hpage, &wait))
2154 if (unlikely(kthread_should_stop() || try_to_freeze()))
2157 spin_lock(&khugepaged_mm_lock);
2158 if (!khugepaged_scan.mm_slot)
2159 pass_through_head++;
2160 if (khugepaged_has_work() &&
2161 pass_through_head < 2)
2162 progress += khugepaged_scan_mm_slot(pages - progress,
2166 spin_unlock(&khugepaged_mm_lock);
2169 if (!IS_ERR_OR_NULL(hpage))
2173 static bool khugepaged_should_wakeup(void)
2175 return kthread_should_stop() ||
2176 time_after_eq(jiffies, khugepaged_sleep_expire);
2179 static void khugepaged_wait_work(void)
2181 if (khugepaged_has_work()) {
2182 const unsigned long scan_sleep_jiffies =
2183 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2185 if (!scan_sleep_jiffies)
2188 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2189 wait_event_freezable_timeout(khugepaged_wait,
2190 khugepaged_should_wakeup(),
2191 scan_sleep_jiffies);
2195 if (khugepaged_enabled())
2196 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2199 static int khugepaged(void *none)
2201 struct mm_slot *mm_slot;
2204 set_user_nice(current, MAX_NICE);
2206 while (!kthread_should_stop()) {
2207 khugepaged_do_scan();
2208 khugepaged_wait_work();
2211 spin_lock(&khugepaged_mm_lock);
2212 mm_slot = khugepaged_scan.mm_slot;
2213 khugepaged_scan.mm_slot = NULL;
2215 collect_mm_slot(mm_slot);
2216 spin_unlock(&khugepaged_mm_lock);
2220 static void set_recommended_min_free_kbytes(void)
2224 unsigned long recommended_min;
2226 for_each_populated_zone(zone) {
2228 * We don't need to worry about fragmentation of
2229 * ZONE_MOVABLE since it only has movable pages.
2231 if (zone_idx(zone) > gfp_zone(GFP_USER))
2237 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2238 recommended_min = pageblock_nr_pages * nr_zones * 2;
2241 * Make sure that on average at least two pageblocks are almost free
2242 * of another type, one for a migratetype to fall back to and a
2243 * second to avoid subsequent fallbacks of other types There are 3
2244 * MIGRATE_TYPES we care about.
2246 recommended_min += pageblock_nr_pages * nr_zones *
2247 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2249 /* don't ever allow to reserve more than 5% of the lowmem */
2250 recommended_min = min(recommended_min,
2251 (unsigned long) nr_free_buffer_pages() / 20);
2252 recommended_min <<= (PAGE_SHIFT-10);
2254 if (recommended_min > min_free_kbytes) {
2255 if (user_min_free_kbytes >= 0)
2256 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2257 min_free_kbytes, recommended_min);
2259 min_free_kbytes = recommended_min;
2261 setup_per_zone_wmarks();
2264 int start_stop_khugepaged(void)
2266 static struct task_struct *khugepaged_thread __read_mostly;
2267 static DEFINE_MUTEX(khugepaged_mutex);
2270 mutex_lock(&khugepaged_mutex);
2271 if (khugepaged_enabled()) {
2272 if (!khugepaged_thread)
2273 khugepaged_thread = kthread_run(khugepaged, NULL,
2275 if (IS_ERR(khugepaged_thread)) {
2276 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2277 err = PTR_ERR(khugepaged_thread);
2278 khugepaged_thread = NULL;
2282 if (!list_empty(&khugepaged_scan.mm_head))
2283 wake_up_interruptible(&khugepaged_wait);
2285 set_recommended_min_free_kbytes();
2286 } else if (khugepaged_thread) {
2287 kthread_stop(khugepaged_thread);
2288 khugepaged_thread = NULL;
2291 mutex_unlock(&khugepaged_mutex);