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>
32 SCAN_EXCEED_SHARED_PTE
,
36 SCAN_LACK_REFERENCED_PAGE
,
50 SCAN_ALLOC_HUGE_PAGE_FAIL
,
51 SCAN_CGROUP_CHARGE_FAIL
,
53 SCAN_PAGE_HAS_PRIVATE
,
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/huge_memory.h>
59 /* default scan 8*512 pte (or vmas) every 30 second */
60 static unsigned int khugepaged_pages_to_scan __read_mostly
;
61 static unsigned int khugepaged_pages_collapsed
;
62 static unsigned int khugepaged_full_scans
;
63 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly
= 10000;
64 /* during fragmentation poll the hugepage allocator once every minute */
65 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly
= 60000;
66 static unsigned long khugepaged_sleep_expire
;
67 static DEFINE_SPINLOCK(khugepaged_mm_lock
);
68 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait
);
70 * default collapse hugepages if there is at least one pte mapped like
71 * it would have happened if the vma was large enough during page
74 static unsigned int khugepaged_max_ptes_none __read_mostly
;
75 static unsigned int khugepaged_max_ptes_swap __read_mostly
;
76 static unsigned int khugepaged_max_ptes_shared __read_mostly
;
78 #define MM_SLOTS_HASH_BITS 10
79 static __read_mostly
DEFINE_HASHTABLE(mm_slots_hash
, MM_SLOTS_HASH_BITS
);
81 static struct kmem_cache
*mm_slot_cache __read_mostly
;
83 #define MAX_PTE_MAPPED_THP 8
86 * struct mm_slot - hash lookup from mm to mm_slot
87 * @hash: hash collision list
88 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
89 * @mm: the mm that this information is valid for
92 struct hlist_node hash
;
93 struct list_head mm_node
;
96 /* pte-mapped THP in this mm */
97 int nr_pte_mapped_thp
;
98 unsigned long pte_mapped_thp
[MAX_PTE_MAPPED_THP
];
102 * struct khugepaged_scan - cursor for scanning
103 * @mm_head: the head of the mm list to scan
104 * @mm_slot: the current mm_slot we are scanning
105 * @address: the next address inside that to be scanned
107 * There is only the one khugepaged_scan instance of this cursor structure.
109 struct khugepaged_scan
{
110 struct list_head mm_head
;
111 struct mm_slot
*mm_slot
;
112 unsigned long address
;
115 static struct khugepaged_scan khugepaged_scan
= {
116 .mm_head
= LIST_HEAD_INIT(khugepaged_scan
.mm_head
),
120 static ssize_t
scan_sleep_millisecs_show(struct kobject
*kobj
,
121 struct kobj_attribute
*attr
,
124 return sprintf(buf
, "%u\n", khugepaged_scan_sleep_millisecs
);
127 static ssize_t
scan_sleep_millisecs_store(struct kobject
*kobj
,
128 struct kobj_attribute
*attr
,
129 const char *buf
, size_t count
)
134 err
= kstrtoul(buf
, 10, &msecs
);
135 if (err
|| msecs
> UINT_MAX
)
138 khugepaged_scan_sleep_millisecs
= msecs
;
139 khugepaged_sleep_expire
= 0;
140 wake_up_interruptible(&khugepaged_wait
);
144 static struct kobj_attribute scan_sleep_millisecs_attr
=
145 __ATTR(scan_sleep_millisecs
, 0644, scan_sleep_millisecs_show
,
146 scan_sleep_millisecs_store
);
148 static ssize_t
alloc_sleep_millisecs_show(struct kobject
*kobj
,
149 struct kobj_attribute
*attr
,
152 return sprintf(buf
, "%u\n", khugepaged_alloc_sleep_millisecs
);
155 static ssize_t
alloc_sleep_millisecs_store(struct kobject
*kobj
,
156 struct kobj_attribute
*attr
,
157 const char *buf
, size_t count
)
162 err
= kstrtoul(buf
, 10, &msecs
);
163 if (err
|| msecs
> UINT_MAX
)
166 khugepaged_alloc_sleep_millisecs
= msecs
;
167 khugepaged_sleep_expire
= 0;
168 wake_up_interruptible(&khugepaged_wait
);
172 static struct kobj_attribute alloc_sleep_millisecs_attr
=
173 __ATTR(alloc_sleep_millisecs
, 0644, alloc_sleep_millisecs_show
,
174 alloc_sleep_millisecs_store
);
176 static ssize_t
pages_to_scan_show(struct kobject
*kobj
,
177 struct kobj_attribute
*attr
,
180 return sprintf(buf
, "%u\n", khugepaged_pages_to_scan
);
182 static ssize_t
pages_to_scan_store(struct kobject
*kobj
,
183 struct kobj_attribute
*attr
,
184 const char *buf
, size_t count
)
189 err
= kstrtoul(buf
, 10, &pages
);
190 if (err
|| !pages
|| pages
> UINT_MAX
)
193 khugepaged_pages_to_scan
= pages
;
197 static struct kobj_attribute pages_to_scan_attr
=
198 __ATTR(pages_to_scan
, 0644, pages_to_scan_show
,
199 pages_to_scan_store
);
201 static ssize_t
pages_collapsed_show(struct kobject
*kobj
,
202 struct kobj_attribute
*attr
,
205 return sprintf(buf
, "%u\n", khugepaged_pages_collapsed
);
207 static struct kobj_attribute pages_collapsed_attr
=
208 __ATTR_RO(pages_collapsed
);
210 static ssize_t
full_scans_show(struct kobject
*kobj
,
211 struct kobj_attribute
*attr
,
214 return sprintf(buf
, "%u\n", khugepaged_full_scans
);
216 static struct kobj_attribute full_scans_attr
=
217 __ATTR_RO(full_scans
);
219 static ssize_t
khugepaged_defrag_show(struct kobject
*kobj
,
220 struct kobj_attribute
*attr
, char *buf
)
222 return single_hugepage_flag_show(kobj
, attr
, buf
,
223 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG
);
225 static ssize_t
khugepaged_defrag_store(struct kobject
*kobj
,
226 struct kobj_attribute
*attr
,
227 const char *buf
, size_t count
)
229 return single_hugepage_flag_store(kobj
, attr
, buf
, count
,
230 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG
);
232 static struct kobj_attribute khugepaged_defrag_attr
=
233 __ATTR(defrag
, 0644, khugepaged_defrag_show
,
234 khugepaged_defrag_store
);
237 * max_ptes_none controls if khugepaged should collapse hugepages over
238 * any unmapped ptes in turn potentially increasing the memory
239 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
240 * reduce the available free memory in the system as it
241 * runs. Increasing max_ptes_none will instead potentially reduce the
242 * free memory in the system during the khugepaged scan.
244 static ssize_t
khugepaged_max_ptes_none_show(struct kobject
*kobj
,
245 struct kobj_attribute
*attr
,
248 return sprintf(buf
, "%u\n", khugepaged_max_ptes_none
);
250 static ssize_t
khugepaged_max_ptes_none_store(struct kobject
*kobj
,
251 struct kobj_attribute
*attr
,
252 const char *buf
, size_t count
)
255 unsigned long max_ptes_none
;
257 err
= kstrtoul(buf
, 10, &max_ptes_none
);
258 if (err
|| max_ptes_none
> HPAGE_PMD_NR
-1)
261 khugepaged_max_ptes_none
= max_ptes_none
;
265 static struct kobj_attribute khugepaged_max_ptes_none_attr
=
266 __ATTR(max_ptes_none
, 0644, khugepaged_max_ptes_none_show
,
267 khugepaged_max_ptes_none_store
);
269 static ssize_t
khugepaged_max_ptes_swap_show(struct kobject
*kobj
,
270 struct kobj_attribute
*attr
,
273 return sprintf(buf
, "%u\n", khugepaged_max_ptes_swap
);
276 static ssize_t
khugepaged_max_ptes_swap_store(struct kobject
*kobj
,
277 struct kobj_attribute
*attr
,
278 const char *buf
, size_t count
)
281 unsigned long max_ptes_swap
;
283 err
= kstrtoul(buf
, 10, &max_ptes_swap
);
284 if (err
|| max_ptes_swap
> HPAGE_PMD_NR
-1)
287 khugepaged_max_ptes_swap
= max_ptes_swap
;
292 static struct kobj_attribute khugepaged_max_ptes_swap_attr
=
293 __ATTR(max_ptes_swap
, 0644, khugepaged_max_ptes_swap_show
,
294 khugepaged_max_ptes_swap_store
);
296 static ssize_t
khugepaged_max_ptes_shared_show(struct kobject
*kobj
,
297 struct kobj_attribute
*attr
,
300 return sprintf(buf
, "%u\n", khugepaged_max_ptes_shared
);
303 static ssize_t
khugepaged_max_ptes_shared_store(struct kobject
*kobj
,
304 struct kobj_attribute
*attr
,
305 const char *buf
, size_t count
)
308 unsigned long max_ptes_shared
;
310 err
= kstrtoul(buf
, 10, &max_ptes_shared
);
311 if (err
|| max_ptes_shared
> HPAGE_PMD_NR
-1)
314 khugepaged_max_ptes_shared
= max_ptes_shared
;
319 static struct kobj_attribute khugepaged_max_ptes_shared_attr
=
320 __ATTR(max_ptes_shared
, 0644, khugepaged_max_ptes_shared_show
,
321 khugepaged_max_ptes_shared_store
);
323 static struct attribute
*khugepaged_attr
[] = {
324 &khugepaged_defrag_attr
.attr
,
325 &khugepaged_max_ptes_none_attr
.attr
,
326 &khugepaged_max_ptes_swap_attr
.attr
,
327 &khugepaged_max_ptes_shared_attr
.attr
,
328 &pages_to_scan_attr
.attr
,
329 &pages_collapsed_attr
.attr
,
330 &full_scans_attr
.attr
,
331 &scan_sleep_millisecs_attr
.attr
,
332 &alloc_sleep_millisecs_attr
.attr
,
336 struct attribute_group khugepaged_attr_group
= {
337 .attrs
= khugepaged_attr
,
338 .name
= "khugepaged",
340 #endif /* CONFIG_SYSFS */
342 int hugepage_madvise(struct vm_area_struct
*vma
,
343 unsigned long *vm_flags
, int advice
)
349 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
350 * can't handle this properly after s390_enable_sie, so we simply
351 * ignore the madvise to prevent qemu from causing a SIGSEGV.
353 if (mm_has_pgste(vma
->vm_mm
))
356 *vm_flags
&= ~VM_NOHUGEPAGE
;
357 *vm_flags
|= VM_HUGEPAGE
;
359 * If the vma become good for khugepaged to scan,
360 * register it here without waiting a page fault that
361 * may not happen any time soon.
363 if (!(*vm_flags
& VM_NO_KHUGEPAGED
) &&
364 khugepaged_enter_vma_merge(vma
, *vm_flags
))
367 case MADV_NOHUGEPAGE
:
368 *vm_flags
&= ~VM_HUGEPAGE
;
369 *vm_flags
|= VM_NOHUGEPAGE
;
371 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
372 * this vma even if we leave the mm registered in khugepaged if
373 * it got registered before VM_NOHUGEPAGE was set.
381 int __init
khugepaged_init(void)
383 mm_slot_cache
= kmem_cache_create("khugepaged_mm_slot",
384 sizeof(struct mm_slot
),
385 __alignof__(struct mm_slot
), 0, NULL
);
389 khugepaged_pages_to_scan
= HPAGE_PMD_NR
* 8;
390 khugepaged_max_ptes_none
= HPAGE_PMD_NR
- 1;
391 khugepaged_max_ptes_swap
= HPAGE_PMD_NR
/ 8;
392 khugepaged_max_ptes_shared
= HPAGE_PMD_NR
/ 2;
397 void __init
khugepaged_destroy(void)
399 kmem_cache_destroy(mm_slot_cache
);
402 static inline struct mm_slot
*alloc_mm_slot(void)
404 if (!mm_slot_cache
) /* initialization failed */
406 return kmem_cache_zalloc(mm_slot_cache
, GFP_KERNEL
);
409 static inline void free_mm_slot(struct mm_slot
*mm_slot
)
411 kmem_cache_free(mm_slot_cache
, mm_slot
);
414 static struct mm_slot
*get_mm_slot(struct mm_struct
*mm
)
416 struct mm_slot
*mm_slot
;
418 hash_for_each_possible(mm_slots_hash
, mm_slot
, hash
, (unsigned long)mm
)
419 if (mm
== mm_slot
->mm
)
425 static void insert_to_mm_slots_hash(struct mm_struct
*mm
,
426 struct mm_slot
*mm_slot
)
429 hash_add(mm_slots_hash
, &mm_slot
->hash
, (long)mm
);
432 static inline int khugepaged_test_exit(struct mm_struct
*mm
)
434 return atomic_read(&mm
->mm_users
) == 0;
437 static bool hugepage_vma_check(struct vm_area_struct
*vma
,
438 unsigned long vm_flags
)
440 if ((!(vm_flags
& VM_HUGEPAGE
) && !khugepaged_always()) ||
441 (vm_flags
& VM_NOHUGEPAGE
) ||
442 test_bit(MMF_DISABLE_THP
, &vma
->vm_mm
->flags
))
445 if (shmem_file(vma
->vm_file
) ||
446 (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS
) &&
448 (vm_flags
& VM_DENYWRITE
))) {
449 return IS_ALIGNED((vma
->vm_start
>> PAGE_SHIFT
) - vma
->vm_pgoff
,
452 if (!vma
->anon_vma
|| vma
->vm_ops
)
454 if (vma_is_temporary_stack(vma
))
456 return !(vm_flags
& VM_NO_KHUGEPAGED
);
459 int __khugepaged_enter(struct mm_struct
*mm
)
461 struct mm_slot
*mm_slot
;
464 mm_slot
= alloc_mm_slot();
468 /* __khugepaged_exit() must not run from under us */
469 VM_BUG_ON_MM(khugepaged_test_exit(mm
), mm
);
470 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE
, &mm
->flags
))) {
471 free_mm_slot(mm_slot
);
475 spin_lock(&khugepaged_mm_lock
);
476 insert_to_mm_slots_hash(mm
, mm_slot
);
478 * Insert just behind the scanning cursor, to let the area settle
481 wakeup
= list_empty(&khugepaged_scan
.mm_head
);
482 list_add_tail(&mm_slot
->mm_node
, &khugepaged_scan
.mm_head
);
483 spin_unlock(&khugepaged_mm_lock
);
487 wake_up_interruptible(&khugepaged_wait
);
492 int khugepaged_enter_vma_merge(struct vm_area_struct
*vma
,
493 unsigned long vm_flags
)
495 unsigned long hstart
, hend
;
498 * khugepaged only supports read-only files for non-shmem files.
499 * khugepaged does not yet work on special mappings. And
500 * file-private shmem THP is not supported.
502 if (!hugepage_vma_check(vma
, vm_flags
))
505 hstart
= (vma
->vm_start
+ ~HPAGE_PMD_MASK
) & HPAGE_PMD_MASK
;
506 hend
= vma
->vm_end
& HPAGE_PMD_MASK
;
508 return khugepaged_enter(vma
, vm_flags
);
512 void __khugepaged_exit(struct mm_struct
*mm
)
514 struct mm_slot
*mm_slot
;
517 spin_lock(&khugepaged_mm_lock
);
518 mm_slot
= get_mm_slot(mm
);
519 if (mm_slot
&& khugepaged_scan
.mm_slot
!= mm_slot
) {
520 hash_del(&mm_slot
->hash
);
521 list_del(&mm_slot
->mm_node
);
524 spin_unlock(&khugepaged_mm_lock
);
527 clear_bit(MMF_VM_HUGEPAGE
, &mm
->flags
);
528 free_mm_slot(mm_slot
);
530 } else if (mm_slot
) {
532 * This is required to serialize against
533 * khugepaged_test_exit() (which is guaranteed to run
534 * under mmap sem read mode). Stop here (after we
535 * return all pagetables will be destroyed) until
536 * khugepaged has finished working on the pagetables
537 * under the mmap_lock.
540 mmap_write_unlock(mm
);
544 static void release_pte_page(struct page
*page
)
546 mod_node_page_state(page_pgdat(page
),
547 NR_ISOLATED_ANON
+ page_is_file_lru(page
),
550 putback_lru_page(page
);
553 static void release_pte_pages(pte_t
*pte
, pte_t
*_pte
,
554 struct list_head
*compound_pagelist
)
556 struct page
*page
, *tmp
;
558 while (--_pte
>= pte
) {
559 pte_t pteval
= *_pte
;
561 page
= pte_page(pteval
);
562 if (!pte_none(pteval
) && !is_zero_pfn(pte_pfn(pteval
)) &&
564 release_pte_page(page
);
567 list_for_each_entry_safe(page
, tmp
, compound_pagelist
, lru
) {
568 list_del(&page
->lru
);
569 release_pte_page(page
);
573 static bool is_refcount_suitable(struct page
*page
)
575 int expected_refcount
;
577 expected_refcount
= total_mapcount(page
);
578 if (PageSwapCache(page
))
579 expected_refcount
+= compound_nr(page
);
581 return page_count(page
) == expected_refcount
;
584 static int __collapse_huge_page_isolate(struct vm_area_struct
*vma
,
585 unsigned long address
,
587 struct list_head
*compound_pagelist
)
589 struct page
*page
= NULL
;
591 int none_or_zero
= 0, shared
= 0, result
= 0, referenced
= 0;
592 bool writable
= false;
594 for (_pte
= pte
; _pte
< pte
+HPAGE_PMD_NR
;
595 _pte
++, address
+= PAGE_SIZE
) {
596 pte_t pteval
= *_pte
;
597 if (pte_none(pteval
) || (pte_present(pteval
) &&
598 is_zero_pfn(pte_pfn(pteval
)))) {
599 if (!userfaultfd_armed(vma
) &&
600 ++none_or_zero
<= khugepaged_max_ptes_none
) {
603 result
= SCAN_EXCEED_NONE_PTE
;
607 if (!pte_present(pteval
)) {
608 result
= SCAN_PTE_NON_PRESENT
;
611 page
= vm_normal_page(vma
, address
, pteval
);
612 if (unlikely(!page
)) {
613 result
= SCAN_PAGE_NULL
;
617 VM_BUG_ON_PAGE(!PageAnon(page
), page
);
619 if (page_mapcount(page
) > 1 &&
620 ++shared
> khugepaged_max_ptes_shared
) {
621 result
= SCAN_EXCEED_SHARED_PTE
;
625 if (PageCompound(page
)) {
627 page
= compound_head(page
);
630 * Check if we have dealt with the compound page
633 list_for_each_entry(p
, compound_pagelist
, lru
) {
640 * We can do it before isolate_lru_page because the
641 * page can't be freed from under us. NOTE: PG_lock
642 * is needed to serialize against split_huge_page
643 * when invoked from the VM.
645 if (!trylock_page(page
)) {
646 result
= SCAN_PAGE_LOCK
;
651 * Check if the page has any GUP (or other external) pins.
653 * The page table that maps the page has been already unlinked
654 * from the page table tree and this process cannot get
655 * an additinal pin on the page.
657 * New pins can come later if the page is shared across fork,
658 * but not from this process. The other process cannot write to
659 * the page, only trigger CoW.
661 if (!is_refcount_suitable(page
)) {
663 result
= SCAN_PAGE_COUNT
;
666 if (!pte_write(pteval
) && PageSwapCache(page
) &&
667 !reuse_swap_page(page
, NULL
)) {
669 * Page is in the swap cache and cannot be re-used.
670 * It cannot be collapsed into a THP.
673 result
= SCAN_SWAP_CACHE_PAGE
;
678 * Isolate the page to avoid collapsing an hugepage
679 * currently in use by the VM.
681 if (isolate_lru_page(page
)) {
683 result
= SCAN_DEL_PAGE_LRU
;
686 mod_node_page_state(page_pgdat(page
),
687 NR_ISOLATED_ANON
+ page_is_file_lru(page
),
689 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
690 VM_BUG_ON_PAGE(PageLRU(page
), page
);
692 if (PageCompound(page
))
693 list_add_tail(&page
->lru
, compound_pagelist
);
695 /* There should be enough young pte to collapse the page */
696 if (pte_young(pteval
) ||
697 page_is_young(page
) || PageReferenced(page
) ||
698 mmu_notifier_test_young(vma
->vm_mm
, address
))
701 if (pte_write(pteval
))
704 if (likely(writable
)) {
705 if (likely(referenced
)) {
706 result
= SCAN_SUCCEED
;
707 trace_mm_collapse_huge_page_isolate(page
, none_or_zero
,
708 referenced
, writable
, result
);
712 result
= SCAN_PAGE_RO
;
716 release_pte_pages(pte
, _pte
, compound_pagelist
);
717 trace_mm_collapse_huge_page_isolate(page
, none_or_zero
,
718 referenced
, writable
, result
);
722 static void __collapse_huge_page_copy(pte_t
*pte
, struct page
*page
,
723 struct vm_area_struct
*vma
,
724 unsigned long address
,
726 struct list_head
*compound_pagelist
)
728 struct page
*src_page
, *tmp
;
730 for (_pte
= pte
; _pte
< pte
+ HPAGE_PMD_NR
;
731 _pte
++, page
++, address
+= PAGE_SIZE
) {
732 pte_t pteval
= *_pte
;
734 if (pte_none(pteval
) || is_zero_pfn(pte_pfn(pteval
))) {
735 clear_user_highpage(page
, address
);
736 add_mm_counter(vma
->vm_mm
, MM_ANONPAGES
, 1);
737 if (is_zero_pfn(pte_pfn(pteval
))) {
739 * ptl mostly unnecessary.
743 * paravirt calls inside pte_clear here are
746 pte_clear(vma
->vm_mm
, address
, _pte
);
750 src_page
= pte_page(pteval
);
751 copy_user_highpage(page
, src_page
, address
, vma
);
752 if (!PageCompound(src_page
))
753 release_pte_page(src_page
);
755 * ptl mostly unnecessary, but preempt has to
756 * be disabled to update the per-cpu stats
757 * inside page_remove_rmap().
761 * paravirt calls inside pte_clear here are
764 pte_clear(vma
->vm_mm
, address
, _pte
);
765 page_remove_rmap(src_page
, false);
767 free_page_and_swap_cache(src_page
);
771 list_for_each_entry_safe(src_page
, tmp
, compound_pagelist
, lru
) {
772 list_del(&src_page
->lru
);
773 release_pte_page(src_page
);
777 static void khugepaged_alloc_sleep(void)
781 add_wait_queue(&khugepaged_wait
, &wait
);
782 freezable_schedule_timeout_interruptible(
783 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs
));
784 remove_wait_queue(&khugepaged_wait
, &wait
);
787 static int khugepaged_node_load
[MAX_NUMNODES
];
789 static bool khugepaged_scan_abort(int nid
)
794 * If node_reclaim_mode is disabled, then no extra effort is made to
795 * allocate memory locally.
797 if (!node_reclaim_mode
)
800 /* If there is a count for this node already, it must be acceptable */
801 if (khugepaged_node_load
[nid
])
804 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
805 if (!khugepaged_node_load
[i
])
807 if (node_distance(nid
, i
) > node_reclaim_distance
)
813 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
814 static inline gfp_t
alloc_hugepage_khugepaged_gfpmask(void)
816 return khugepaged_defrag() ? GFP_TRANSHUGE
: GFP_TRANSHUGE_LIGHT
;
820 static int khugepaged_find_target_node(void)
822 static int last_khugepaged_target_node
= NUMA_NO_NODE
;
823 int nid
, target_node
= 0, max_value
= 0;
825 /* find first node with max normal pages hit */
826 for (nid
= 0; nid
< MAX_NUMNODES
; nid
++)
827 if (khugepaged_node_load
[nid
] > max_value
) {
828 max_value
= khugepaged_node_load
[nid
];
832 /* do some balance if several nodes have the same hit record */
833 if (target_node
<= last_khugepaged_target_node
)
834 for (nid
= last_khugepaged_target_node
+ 1; nid
< MAX_NUMNODES
;
836 if (max_value
== khugepaged_node_load
[nid
]) {
841 last_khugepaged_target_node
= target_node
;
845 static bool khugepaged_prealloc_page(struct page
**hpage
, bool *wait
)
847 if (IS_ERR(*hpage
)) {
853 khugepaged_alloc_sleep();
863 khugepaged_alloc_page(struct page
**hpage
, gfp_t gfp
, int node
)
865 VM_BUG_ON_PAGE(*hpage
, *hpage
);
867 *hpage
= __alloc_pages_node(node
, gfp
, HPAGE_PMD_ORDER
);
868 if (unlikely(!*hpage
)) {
869 count_vm_event(THP_COLLAPSE_ALLOC_FAILED
);
870 *hpage
= ERR_PTR(-ENOMEM
);
874 prep_transhuge_page(*hpage
);
875 count_vm_event(THP_COLLAPSE_ALLOC
);
879 static int khugepaged_find_target_node(void)
884 static inline struct page
*alloc_khugepaged_hugepage(void)
888 page
= alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
891 prep_transhuge_page(page
);
895 static struct page
*khugepaged_alloc_hugepage(bool *wait
)
900 hpage
= alloc_khugepaged_hugepage();
902 count_vm_event(THP_COLLAPSE_ALLOC_FAILED
);
907 khugepaged_alloc_sleep();
909 count_vm_event(THP_COLLAPSE_ALLOC
);
910 } while (unlikely(!hpage
) && likely(khugepaged_enabled()));
915 static bool khugepaged_prealloc_page(struct page
**hpage
, bool *wait
)
918 *hpage
= khugepaged_alloc_hugepage(wait
);
920 if (unlikely(!*hpage
))
927 khugepaged_alloc_page(struct page
**hpage
, gfp_t gfp
, int node
)
936 * If mmap_lock temporarily dropped, revalidate vma
937 * before taking mmap_lock.
938 * Return 0 if succeeds, otherwise return none-zero
942 static int hugepage_vma_revalidate(struct mm_struct
*mm
, unsigned long address
,
943 struct vm_area_struct
**vmap
)
945 struct vm_area_struct
*vma
;
946 unsigned long hstart
, hend
;
948 if (unlikely(khugepaged_test_exit(mm
)))
949 return SCAN_ANY_PROCESS
;
951 *vmap
= vma
= find_vma(mm
, address
);
953 return SCAN_VMA_NULL
;
955 hstart
= (vma
->vm_start
+ ~HPAGE_PMD_MASK
) & HPAGE_PMD_MASK
;
956 hend
= vma
->vm_end
& HPAGE_PMD_MASK
;
957 if (address
< hstart
|| address
+ HPAGE_PMD_SIZE
> hend
)
958 return SCAN_ADDRESS_RANGE
;
959 if (!hugepage_vma_check(vma
, vma
->vm_flags
))
960 return SCAN_VMA_CHECK
;
961 /* Anon VMA expected */
962 if (!vma
->anon_vma
|| vma
->vm_ops
)
963 return SCAN_VMA_CHECK
;
968 * Bring missing pages in from swap, to complete THP collapse.
969 * Only done if khugepaged_scan_pmd believes it is worthwhile.
971 * Called and returns without pte mapped or spinlocks held,
972 * but with mmap_lock held to protect against vma changes.
975 static bool __collapse_huge_page_swapin(struct mm_struct
*mm
,
976 struct vm_area_struct
*vma
,
977 unsigned long address
, pmd_t
*pmd
,
982 struct vm_fault vmf
= {
985 .flags
= FAULT_FLAG_ALLOW_RETRY
,
987 .pgoff
= linear_page_index(vma
, address
),
990 vmf
.pte
= pte_offset_map(pmd
, address
);
991 for (; vmf
.address
< address
+ HPAGE_PMD_NR
*PAGE_SIZE
;
992 vmf
.pte
++, vmf
.address
+= PAGE_SIZE
) {
993 vmf
.orig_pte
= *vmf
.pte
;
994 if (!is_swap_pte(vmf
.orig_pte
))
997 ret
= do_swap_page(&vmf
);
999 /* do_swap_page returns VM_FAULT_RETRY with released mmap_lock */
1000 if (ret
& VM_FAULT_RETRY
) {
1002 if (hugepage_vma_revalidate(mm
, address
, &vmf
.vma
)) {
1003 /* vma is no longer available, don't continue to swapin */
1004 trace_mm_collapse_huge_page_swapin(mm
, swapped_in
, referenced
, 0);
1007 /* check if the pmd is still valid */
1008 if (mm_find_pmd(mm
, address
) != pmd
) {
1009 trace_mm_collapse_huge_page_swapin(mm
, swapped_in
, referenced
, 0);
1013 if (ret
& VM_FAULT_ERROR
) {
1014 trace_mm_collapse_huge_page_swapin(mm
, swapped_in
, referenced
, 0);
1017 /* pte is unmapped now, we need to map it */
1018 vmf
.pte
= pte_offset_map(pmd
, vmf
.address
);
1023 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
1027 trace_mm_collapse_huge_page_swapin(mm
, swapped_in
, referenced
, 1);
1031 static void collapse_huge_page(struct mm_struct
*mm
,
1032 unsigned long address
,
1033 struct page
**hpage
,
1034 int node
, int referenced
, int unmapped
)
1036 LIST_HEAD(compound_pagelist
);
1040 struct page
*new_page
;
1041 spinlock_t
*pmd_ptl
, *pte_ptl
;
1042 int isolated
= 0, result
= 0;
1043 struct vm_area_struct
*vma
;
1044 struct mmu_notifier_range range
;
1047 VM_BUG_ON(address
& ~HPAGE_PMD_MASK
);
1049 /* Only allocate from the target node */
1050 gfp
= alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE
;
1053 * Before allocating the hugepage, release the mmap_lock read lock.
1054 * The allocation can take potentially a long time if it involves
1055 * sync compaction, and we do not need to hold the mmap_lock during
1056 * that. We will recheck the vma after taking it again in write mode.
1058 mmap_read_unlock(mm
);
1059 new_page
= khugepaged_alloc_page(hpage
, gfp
, node
);
1061 result
= SCAN_ALLOC_HUGE_PAGE_FAIL
;
1065 if (unlikely(mem_cgroup_charge(new_page
, mm
, gfp
))) {
1066 result
= SCAN_CGROUP_CHARGE_FAIL
;
1069 count_memcg_page_event(new_page
, THP_COLLAPSE_ALLOC
);
1072 result
= hugepage_vma_revalidate(mm
, address
, &vma
);
1074 mmap_read_unlock(mm
);
1078 pmd
= mm_find_pmd(mm
, address
);
1080 result
= SCAN_PMD_NULL
;
1081 mmap_read_unlock(mm
);
1086 * __collapse_huge_page_swapin always returns with mmap_lock locked.
1087 * If it fails, we release mmap_lock and jump out_nolock.
1088 * Continuing to collapse causes inconsistency.
1090 if (unmapped
&& !__collapse_huge_page_swapin(mm
, vma
, address
,
1092 mmap_read_unlock(mm
);
1096 mmap_read_unlock(mm
);
1098 * Prevent all access to pagetables with the exception of
1099 * gup_fast later handled by the ptep_clear_flush and the VM
1100 * handled by the anon_vma lock + PG_lock.
1102 mmap_write_lock(mm
);
1103 result
= SCAN_ANY_PROCESS
;
1104 if (!mmget_still_valid(mm
))
1106 result
= hugepage_vma_revalidate(mm
, address
, &vma
);
1109 /* check if the pmd is still valid */
1110 if (mm_find_pmd(mm
, address
) != pmd
)
1113 anon_vma_lock_write(vma
->anon_vma
);
1115 mmu_notifier_range_init(&range
, MMU_NOTIFY_CLEAR
, 0, NULL
, mm
,
1116 address
, address
+ HPAGE_PMD_SIZE
);
1117 mmu_notifier_invalidate_range_start(&range
);
1119 pte
= pte_offset_map(pmd
, address
);
1120 pte_ptl
= pte_lockptr(mm
, pmd
);
1122 pmd_ptl
= pmd_lock(mm
, pmd
); /* probably unnecessary */
1124 * After this gup_fast can't run anymore. This also removes
1125 * any huge TLB entry from the CPU so we won't allow
1126 * huge and small TLB entries for the same virtual address
1127 * to avoid the risk of CPU bugs in that area.
1129 _pmd
= pmdp_collapse_flush(vma
, address
, pmd
);
1130 spin_unlock(pmd_ptl
);
1131 mmu_notifier_invalidate_range_end(&range
);
1134 isolated
= __collapse_huge_page_isolate(vma
, address
, pte
,
1135 &compound_pagelist
);
1136 spin_unlock(pte_ptl
);
1138 if (unlikely(!isolated
)) {
1141 BUG_ON(!pmd_none(*pmd
));
1143 * We can only use set_pmd_at when establishing
1144 * hugepmds and never for establishing regular pmds that
1145 * points to regular pagetables. Use pmd_populate for that
1147 pmd_populate(mm
, pmd
, pmd_pgtable(_pmd
));
1148 spin_unlock(pmd_ptl
);
1149 anon_vma_unlock_write(vma
->anon_vma
);
1155 * All pages are isolated and locked so anon_vma rmap
1156 * can't run anymore.
1158 anon_vma_unlock_write(vma
->anon_vma
);
1160 __collapse_huge_page_copy(pte
, new_page
, vma
, address
, pte_ptl
,
1161 &compound_pagelist
);
1163 __SetPageUptodate(new_page
);
1164 pgtable
= pmd_pgtable(_pmd
);
1166 _pmd
= mk_huge_pmd(new_page
, vma
->vm_page_prot
);
1167 _pmd
= maybe_pmd_mkwrite(pmd_mkdirty(_pmd
), vma
);
1170 * spin_lock() below is not the equivalent of smp_wmb(), so
1171 * this is needed to avoid the copy_huge_page writes to become
1172 * visible after the set_pmd_at() write.
1177 BUG_ON(!pmd_none(*pmd
));
1178 page_add_new_anon_rmap(new_page
, vma
, address
, true);
1179 lru_cache_add_active_or_unevictable(new_page
, vma
);
1180 pgtable_trans_huge_deposit(mm
, pmd
, pgtable
);
1181 set_pmd_at(mm
, address
, pmd
, _pmd
);
1182 update_mmu_cache_pmd(vma
, address
, pmd
);
1183 spin_unlock(pmd_ptl
);
1187 khugepaged_pages_collapsed
++;
1188 result
= SCAN_SUCCEED
;
1190 mmap_write_unlock(mm
);
1192 if (!IS_ERR_OR_NULL(*hpage
))
1193 mem_cgroup_uncharge(*hpage
);
1194 trace_mm_collapse_huge_page(mm
, isolated
, result
);
1200 static int khugepaged_scan_pmd(struct mm_struct
*mm
,
1201 struct vm_area_struct
*vma
,
1202 unsigned long address
,
1203 struct page
**hpage
)
1207 int ret
= 0, result
= 0, referenced
= 0;
1208 int none_or_zero
= 0, shared
= 0;
1209 struct page
*page
= NULL
;
1210 unsigned long _address
;
1212 int node
= NUMA_NO_NODE
, unmapped
= 0;
1213 bool writable
= false;
1215 VM_BUG_ON(address
& ~HPAGE_PMD_MASK
);
1217 pmd
= mm_find_pmd(mm
, address
);
1219 result
= SCAN_PMD_NULL
;
1223 memset(khugepaged_node_load
, 0, sizeof(khugepaged_node_load
));
1224 pte
= pte_offset_map_lock(mm
, pmd
, address
, &ptl
);
1225 for (_address
= address
, _pte
= pte
; _pte
< pte
+HPAGE_PMD_NR
;
1226 _pte
++, _address
+= PAGE_SIZE
) {
1227 pte_t pteval
= *_pte
;
1228 if (is_swap_pte(pteval
)) {
1229 if (++unmapped
<= khugepaged_max_ptes_swap
) {
1231 * Always be strict with uffd-wp
1232 * enabled swap entries. Please see
1233 * comment below for pte_uffd_wp().
1235 if (pte_swp_uffd_wp(pteval
)) {
1236 result
= SCAN_PTE_UFFD_WP
;
1241 result
= SCAN_EXCEED_SWAP_PTE
;
1245 if (pte_none(pteval
) || is_zero_pfn(pte_pfn(pteval
))) {
1246 if (!userfaultfd_armed(vma
) &&
1247 ++none_or_zero
<= khugepaged_max_ptes_none
) {
1250 result
= SCAN_EXCEED_NONE_PTE
;
1254 if (!pte_present(pteval
)) {
1255 result
= SCAN_PTE_NON_PRESENT
;
1258 if (pte_uffd_wp(pteval
)) {
1260 * Don't collapse the page if any of the small
1261 * PTEs are armed with uffd write protection.
1262 * Here we can also mark the new huge pmd as
1263 * write protected if any of the small ones is
1264 * marked but that could bring uknown
1265 * userfault messages that falls outside of
1266 * the registered range. So, just be simple.
1268 result
= SCAN_PTE_UFFD_WP
;
1271 if (pte_write(pteval
))
1274 page
= vm_normal_page(vma
, _address
, pteval
);
1275 if (unlikely(!page
)) {
1276 result
= SCAN_PAGE_NULL
;
1280 if (page_mapcount(page
) > 1 &&
1281 ++shared
> khugepaged_max_ptes_shared
) {
1282 result
= SCAN_EXCEED_SHARED_PTE
;
1286 page
= compound_head(page
);
1289 * Record which node the original page is from and save this
1290 * information to khugepaged_node_load[].
1291 * Khupaged will allocate hugepage from the node has the max
1294 node
= page_to_nid(page
);
1295 if (khugepaged_scan_abort(node
)) {
1296 result
= SCAN_SCAN_ABORT
;
1299 khugepaged_node_load
[node
]++;
1300 if (!PageLRU(page
)) {
1301 result
= SCAN_PAGE_LRU
;
1304 if (PageLocked(page
)) {
1305 result
= SCAN_PAGE_LOCK
;
1308 if (!PageAnon(page
)) {
1309 result
= SCAN_PAGE_ANON
;
1314 * Check if the page has any GUP (or other external) pins.
1316 * Here the check is racy it may see totmal_mapcount > refcount
1318 * For example, one process with one forked child process.
1319 * The parent has the PMD split due to MADV_DONTNEED, then
1320 * the child is trying unmap the whole PMD, but khugepaged
1321 * may be scanning the parent between the child has
1322 * PageDoubleMap flag cleared and dec the mapcount. So
1323 * khugepaged may see total_mapcount > refcount.
1325 * But such case is ephemeral we could always retry collapse
1326 * later. However it may report false positive if the page
1327 * has excessive GUP pins (i.e. 512). Anyway the same check
1328 * will be done again later the risk seems low.
1330 if (!is_refcount_suitable(page
)) {
1331 result
= SCAN_PAGE_COUNT
;
1334 if (pte_young(pteval
) ||
1335 page_is_young(page
) || PageReferenced(page
) ||
1336 mmu_notifier_test_young(vma
->vm_mm
, address
))
1340 result
= SCAN_PAGE_RO
;
1341 } else if (!referenced
|| (unmapped
&& referenced
< HPAGE_PMD_NR
/2)) {
1342 result
= SCAN_LACK_REFERENCED_PAGE
;
1344 result
= SCAN_SUCCEED
;
1348 pte_unmap_unlock(pte
, ptl
);
1350 node
= khugepaged_find_target_node();
1351 /* collapse_huge_page will return with the mmap_lock released */
1352 collapse_huge_page(mm
, address
, hpage
, node
,
1353 referenced
, unmapped
);
1356 trace_mm_khugepaged_scan_pmd(mm
, page
, writable
, referenced
,
1357 none_or_zero
, result
, unmapped
);
1361 static void collect_mm_slot(struct mm_slot
*mm_slot
)
1363 struct mm_struct
*mm
= mm_slot
->mm
;
1365 lockdep_assert_held(&khugepaged_mm_lock
);
1367 if (khugepaged_test_exit(mm
)) {
1369 hash_del(&mm_slot
->hash
);
1370 list_del(&mm_slot
->mm_node
);
1373 * Not strictly needed because the mm exited already.
1375 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1378 /* khugepaged_mm_lock actually not necessary for the below */
1379 free_mm_slot(mm_slot
);
1386 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1387 * khugepaged should try to collapse the page table.
1389 static int khugepaged_add_pte_mapped_thp(struct mm_struct
*mm
,
1392 struct mm_slot
*mm_slot
;
1394 VM_BUG_ON(addr
& ~HPAGE_PMD_MASK
);
1396 spin_lock(&khugepaged_mm_lock
);
1397 mm_slot
= get_mm_slot(mm
);
1398 if (likely(mm_slot
&& mm_slot
->nr_pte_mapped_thp
< MAX_PTE_MAPPED_THP
))
1399 mm_slot
->pte_mapped_thp
[mm_slot
->nr_pte_mapped_thp
++] = addr
;
1400 spin_unlock(&khugepaged_mm_lock
);
1405 * Try to collapse a pte-mapped THP for mm at address haddr.
1407 * This function checks whether all the PTEs in the PMD are pointing to the
1408 * right THP. If so, retract the page table so the THP can refault in with
1411 void collapse_pte_mapped_thp(struct mm_struct
*mm
, unsigned long addr
)
1413 unsigned long haddr
= addr
& HPAGE_PMD_MASK
;
1414 struct vm_area_struct
*vma
= find_vma(mm
, haddr
);
1415 struct page
*hpage
= NULL
;
1416 pte_t
*start_pte
, *pte
;
1422 if (!vma
|| !vma
->vm_file
||
1423 vma
->vm_start
> haddr
|| vma
->vm_end
< haddr
+ HPAGE_PMD_SIZE
)
1427 * This vm_flags may not have VM_HUGEPAGE if the page was not
1428 * collapsed by this mm. But we can still collapse if the page is
1429 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
1430 * will not fail the vma for missing VM_HUGEPAGE
1432 if (!hugepage_vma_check(vma
, vma
->vm_flags
| VM_HUGEPAGE
))
1435 pmd
= mm_find_pmd(mm
, haddr
);
1439 start_pte
= pte_offset_map_lock(mm
, pmd
, haddr
, &ptl
);
1441 /* step 1: check all mapped PTEs are to the right huge page */
1442 for (i
= 0, addr
= haddr
, pte
= start_pte
;
1443 i
< HPAGE_PMD_NR
; i
++, addr
+= PAGE_SIZE
, pte
++) {
1446 /* empty pte, skip */
1450 /* page swapped out, abort */
1451 if (!pte_present(*pte
))
1454 page
= vm_normal_page(vma
, addr
, *pte
);
1456 if (!page
|| !PageCompound(page
))
1460 hpage
= compound_head(page
);
1462 * The mapping of the THP should not change.
1464 * Note that uprobe, debugger, or MAP_PRIVATE may
1465 * change the page table, but the new page will
1466 * not pass PageCompound() check.
1468 if (WARN_ON(hpage
->mapping
!= vma
->vm_file
->f_mapping
))
1473 * Confirm the page maps to the correct subpage.
1475 * Note that uprobe, debugger, or MAP_PRIVATE may change
1476 * the page table, but the new page will not pass
1477 * PageCompound() check.
1479 if (WARN_ON(hpage
+ i
!= page
))
1484 /* step 2: adjust rmap */
1485 for (i
= 0, addr
= haddr
, pte
= start_pte
;
1486 i
< HPAGE_PMD_NR
; i
++, addr
+= PAGE_SIZE
, pte
++) {
1491 page
= vm_normal_page(vma
, addr
, *pte
);
1492 page_remove_rmap(page
, false);
1495 pte_unmap_unlock(start_pte
, ptl
);
1497 /* step 3: set proper refcount and mm_counters. */
1499 page_ref_sub(hpage
, count
);
1500 add_mm_counter(vma
->vm_mm
, mm_counter_file(hpage
), -count
);
1503 /* step 4: collapse pmd */
1504 ptl
= pmd_lock(vma
->vm_mm
, pmd
);
1505 _pmd
= pmdp_collapse_flush(vma
, addr
, pmd
);
1508 pte_free(mm
, pmd_pgtable(_pmd
));
1512 pte_unmap_unlock(start_pte
, ptl
);
1515 static int khugepaged_collapse_pte_mapped_thps(struct mm_slot
*mm_slot
)
1517 struct mm_struct
*mm
= mm_slot
->mm
;
1520 if (likely(mm_slot
->nr_pte_mapped_thp
== 0))
1523 if (!mmap_write_trylock(mm
))
1526 if (unlikely(khugepaged_test_exit(mm
)))
1529 for (i
= 0; i
< mm_slot
->nr_pte_mapped_thp
; i
++)
1530 collapse_pte_mapped_thp(mm
, mm_slot
->pte_mapped_thp
[i
]);
1533 mm_slot
->nr_pte_mapped_thp
= 0;
1534 mmap_write_unlock(mm
);
1538 static void retract_page_tables(struct address_space
*mapping
, pgoff_t pgoff
)
1540 struct vm_area_struct
*vma
;
1544 i_mmap_lock_write(mapping
);
1545 vma_interval_tree_foreach(vma
, &mapping
->i_mmap
, pgoff
, pgoff
) {
1547 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1548 * got written to. These VMAs are likely not worth investing
1549 * mmap_write_lock(mm) as PMD-mapping is likely to be split
1552 * Not that vma->anon_vma check is racy: it can be set up after
1553 * the check but before we took mmap_lock by the fault path.
1554 * But page lock would prevent establishing any new ptes of the
1555 * page, so we are safe.
1557 * An alternative would be drop the check, but check that page
1558 * table is clear before calling pmdp_collapse_flush() under
1559 * ptl. It has higher chance to recover THP for the VMA, but
1560 * has higher cost too.
1564 addr
= vma
->vm_start
+ ((pgoff
- vma
->vm_pgoff
) << PAGE_SHIFT
);
1565 if (addr
& ~HPAGE_PMD_MASK
)
1567 if (vma
->vm_end
< addr
+ HPAGE_PMD_SIZE
)
1569 pmd
= mm_find_pmd(vma
->vm_mm
, addr
);
1573 * We need exclusive mmap_lock to retract page table.
1575 * We use trylock due to lock inversion: we need to acquire
1576 * mmap_lock while holding page lock. Fault path does it in
1577 * reverse order. Trylock is a way to avoid deadlock.
1579 if (mmap_write_trylock(vma
->vm_mm
)) {
1580 spinlock_t
*ptl
= pmd_lock(vma
->vm_mm
, pmd
);
1581 /* assume page table is clear */
1582 _pmd
= pmdp_collapse_flush(vma
, addr
, pmd
);
1584 mmap_write_unlock(vma
->vm_mm
);
1585 mm_dec_nr_ptes(vma
->vm_mm
);
1586 pte_free(vma
->vm_mm
, pmd_pgtable(_pmd
));
1588 /* Try again later */
1589 khugepaged_add_pte_mapped_thp(vma
->vm_mm
, addr
);
1592 i_mmap_unlock_write(mapping
);
1596 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1598 * Basic scheme is simple, details are more complex:
1599 * - allocate and lock a new huge page;
1600 * - scan page cache replacing old pages with the new one
1601 * + swap/gup in pages if necessary;
1603 * + keep old pages around in case rollback is required;
1604 * - if replacing succeeds:
1607 * + unlock huge page;
1608 * - if replacing failed;
1609 * + put all pages back and unfreeze them;
1610 * + restore gaps in the page cache;
1611 * + unlock and free huge page;
1613 static void collapse_file(struct mm_struct
*mm
,
1614 struct file
*file
, pgoff_t start
,
1615 struct page
**hpage
, int node
)
1617 struct address_space
*mapping
= file
->f_mapping
;
1619 struct page
*new_page
;
1620 pgoff_t index
, end
= start
+ HPAGE_PMD_NR
;
1621 LIST_HEAD(pagelist
);
1622 XA_STATE_ORDER(xas
, &mapping
->i_pages
, start
, HPAGE_PMD_ORDER
);
1623 int nr_none
= 0, result
= SCAN_SUCCEED
;
1624 bool is_shmem
= shmem_file(file
);
1626 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS
) && !is_shmem
);
1627 VM_BUG_ON(start
& (HPAGE_PMD_NR
- 1));
1629 /* Only allocate from the target node */
1630 gfp
= alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE
;
1632 new_page
= khugepaged_alloc_page(hpage
, gfp
, node
);
1634 result
= SCAN_ALLOC_HUGE_PAGE_FAIL
;
1638 if (unlikely(mem_cgroup_charge(new_page
, mm
, gfp
))) {
1639 result
= SCAN_CGROUP_CHARGE_FAIL
;
1642 count_memcg_page_event(new_page
, THP_COLLAPSE_ALLOC
);
1644 /* This will be less messy when we use multi-index entries */
1647 xas_create_range(&xas
);
1648 if (!xas_error(&xas
))
1650 xas_unlock_irq(&xas
);
1651 if (!xas_nomem(&xas
, GFP_KERNEL
)) {
1657 __SetPageLocked(new_page
);
1659 __SetPageSwapBacked(new_page
);
1660 new_page
->index
= start
;
1661 new_page
->mapping
= mapping
;
1664 * At this point the new_page is locked and not up-to-date.
1665 * It's safe to insert it into the page cache, because nobody would
1666 * be able to map it or use it in another way until we unlock it.
1669 xas_set(&xas
, start
);
1670 for (index
= start
; index
< end
; index
++) {
1671 struct page
*page
= xas_next(&xas
);
1673 VM_BUG_ON(index
!= xas
.xa_index
);
1677 * Stop if extent has been truncated or
1678 * hole-punched, and is now completely
1681 if (index
== start
) {
1682 if (!xas_next_entry(&xas
, end
- 1)) {
1683 result
= SCAN_TRUNCATED
;
1686 xas_set(&xas
, index
);
1688 if (!shmem_charge(mapping
->host
, 1)) {
1692 xas_store(&xas
, new_page
);
1697 if (xa_is_value(page
) || !PageUptodate(page
)) {
1698 xas_unlock_irq(&xas
);
1699 /* swap in or instantiate fallocated page */
1700 if (shmem_getpage(mapping
->host
, index
, &page
,
1705 } else if (trylock_page(page
)) {
1707 xas_unlock_irq(&xas
);
1709 result
= SCAN_PAGE_LOCK
;
1712 } else { /* !is_shmem */
1713 if (!page
|| xa_is_value(page
)) {
1714 xas_unlock_irq(&xas
);
1715 page_cache_sync_readahead(mapping
, &file
->f_ra
,
1718 /* drain pagevecs to help isolate_lru_page() */
1720 page
= find_lock_page(mapping
, index
);
1721 if (unlikely(page
== NULL
)) {
1725 } else if (PageDirty(page
)) {
1727 * khugepaged only works on read-only fd,
1728 * so this page is dirty because it hasn't
1729 * been flushed since first write. There
1730 * won't be new dirty pages.
1732 * Trigger async flush here and hope the
1733 * writeback is done when khugepaged
1734 * revisits this page.
1736 * This is a one-off situation. We are not
1737 * forcing writeback in loop.
1739 xas_unlock_irq(&xas
);
1740 filemap_flush(mapping
);
1743 } else if (trylock_page(page
)) {
1745 xas_unlock_irq(&xas
);
1747 result
= SCAN_PAGE_LOCK
;
1753 * The page must be locked, so we can drop the i_pages lock
1754 * without racing with truncate.
1756 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
1758 /* make sure the page is up to date */
1759 if (unlikely(!PageUptodate(page
))) {
1765 * If file was truncated then extended, or hole-punched, before
1766 * we locked the first page, then a THP might be there already.
1768 if (PageTransCompound(page
)) {
1769 result
= SCAN_PAGE_COMPOUND
;
1773 if (page_mapping(page
) != mapping
) {
1774 result
= SCAN_TRUNCATED
;
1778 if (!is_shmem
&& PageDirty(page
)) {
1780 * khugepaged only works on read-only fd, so this
1781 * page is dirty because it hasn't been flushed
1782 * since first write.
1788 if (isolate_lru_page(page
)) {
1789 result
= SCAN_DEL_PAGE_LRU
;
1793 if (page_has_private(page
) &&
1794 !try_to_release_page(page
, GFP_KERNEL
)) {
1795 result
= SCAN_PAGE_HAS_PRIVATE
;
1796 putback_lru_page(page
);
1800 if (page_mapped(page
))
1801 unmap_mapping_pages(mapping
, index
, 1, false);
1804 xas_set(&xas
, index
);
1806 VM_BUG_ON_PAGE(page
!= xas_load(&xas
), page
);
1807 VM_BUG_ON_PAGE(page_mapped(page
), page
);
1810 * The page is expected to have page_count() == 3:
1811 * - we hold a pin on it;
1812 * - one reference from page cache;
1813 * - one from isolate_lru_page;
1815 if (!page_ref_freeze(page
, 3)) {
1816 result
= SCAN_PAGE_COUNT
;
1817 xas_unlock_irq(&xas
);
1818 putback_lru_page(page
);
1823 * Add the page to the list to be able to undo the collapse if
1824 * something go wrong.
1826 list_add_tail(&page
->lru
, &pagelist
);
1828 /* Finally, replace with the new page. */
1829 xas_store(&xas
, new_page
);
1838 __inc_node_page_state(new_page
, NR_SHMEM_THPS
);
1840 __inc_node_page_state(new_page
, NR_FILE_THPS
);
1841 filemap_nr_thps_inc(mapping
);
1845 __mod_lruvec_page_state(new_page
, NR_FILE_PAGES
, nr_none
);
1847 __mod_lruvec_page_state(new_page
, NR_SHMEM
, nr_none
);
1851 xas_unlock_irq(&xas
);
1854 if (result
== SCAN_SUCCEED
) {
1855 struct page
*page
, *tmp
;
1858 * Replacing old pages with new one has succeeded, now we
1859 * need to copy the content and free the old pages.
1862 list_for_each_entry_safe(page
, tmp
, &pagelist
, lru
) {
1863 while (index
< page
->index
) {
1864 clear_highpage(new_page
+ (index
% HPAGE_PMD_NR
));
1867 copy_highpage(new_page
+ (page
->index
% HPAGE_PMD_NR
),
1869 list_del(&page
->lru
);
1870 page
->mapping
= NULL
;
1871 page_ref_unfreeze(page
, 1);
1872 ClearPageActive(page
);
1873 ClearPageUnevictable(page
);
1878 while (index
< end
) {
1879 clear_highpage(new_page
+ (index
% HPAGE_PMD_NR
));
1883 SetPageUptodate(new_page
);
1884 page_ref_add(new_page
, HPAGE_PMD_NR
- 1);
1886 set_page_dirty(new_page
);
1887 lru_cache_add(new_page
);
1890 * Remove pte page tables, so we can re-fault the page as huge.
1892 retract_page_tables(mapping
, start
);
1895 khugepaged_pages_collapsed
++;
1899 /* Something went wrong: roll back page cache changes */
1901 mapping
->nrpages
-= nr_none
;
1904 shmem_uncharge(mapping
->host
, nr_none
);
1906 xas_set(&xas
, start
);
1907 xas_for_each(&xas
, page
, end
- 1) {
1908 page
= list_first_entry_or_null(&pagelist
,
1910 if (!page
|| xas
.xa_index
< page
->index
) {
1914 /* Put holes back where they were */
1915 xas_store(&xas
, NULL
);
1919 VM_BUG_ON_PAGE(page
->index
!= xas
.xa_index
, page
);
1921 /* Unfreeze the page. */
1922 list_del(&page
->lru
);
1923 page_ref_unfreeze(page
, 2);
1924 xas_store(&xas
, page
);
1926 xas_unlock_irq(&xas
);
1928 putback_lru_page(page
);
1932 xas_unlock_irq(&xas
);
1934 new_page
->mapping
= NULL
;
1937 unlock_page(new_page
);
1939 VM_BUG_ON(!list_empty(&pagelist
));
1940 if (!IS_ERR_OR_NULL(*hpage
))
1941 mem_cgroup_uncharge(*hpage
);
1942 /* TODO: tracepoints */
1945 static void khugepaged_scan_file(struct mm_struct
*mm
,
1946 struct file
*file
, pgoff_t start
, struct page
**hpage
)
1948 struct page
*page
= NULL
;
1949 struct address_space
*mapping
= file
->f_mapping
;
1950 XA_STATE(xas
, &mapping
->i_pages
, start
);
1952 int node
= NUMA_NO_NODE
;
1953 int result
= SCAN_SUCCEED
;
1957 memset(khugepaged_node_load
, 0, sizeof(khugepaged_node_load
));
1959 xas_for_each(&xas
, page
, start
+ HPAGE_PMD_NR
- 1) {
1960 if (xas_retry(&xas
, page
))
1963 if (xa_is_value(page
)) {
1964 if (++swap
> khugepaged_max_ptes_swap
) {
1965 result
= SCAN_EXCEED_SWAP_PTE
;
1971 if (PageTransCompound(page
)) {
1972 result
= SCAN_PAGE_COMPOUND
;
1976 node
= page_to_nid(page
);
1977 if (khugepaged_scan_abort(node
)) {
1978 result
= SCAN_SCAN_ABORT
;
1981 khugepaged_node_load
[node
]++;
1983 if (!PageLRU(page
)) {
1984 result
= SCAN_PAGE_LRU
;
1988 if (page_count(page
) !=
1989 1 + page_mapcount(page
) + page_has_private(page
)) {
1990 result
= SCAN_PAGE_COUNT
;
1995 * We probably should check if the page is referenced here, but
1996 * nobody would transfer pte_young() to PageReferenced() for us.
1997 * And rmap walk here is just too costly...
2002 if (need_resched()) {
2009 if (result
== SCAN_SUCCEED
) {
2010 if (present
< HPAGE_PMD_NR
- khugepaged_max_ptes_none
) {
2011 result
= SCAN_EXCEED_NONE_PTE
;
2013 node
= khugepaged_find_target_node();
2014 collapse_file(mm
, file
, start
, hpage
, node
);
2018 /* TODO: tracepoints */
2021 static void khugepaged_scan_file(struct mm_struct
*mm
,
2022 struct file
*file
, pgoff_t start
, struct page
**hpage
)
2027 static int khugepaged_collapse_pte_mapped_thps(struct mm_slot
*mm_slot
)
2033 static unsigned int khugepaged_scan_mm_slot(unsigned int pages
,
2034 struct page
**hpage
)
2035 __releases(&khugepaged_mm_lock
)
2036 __acquires(&khugepaged_mm_lock
)
2038 struct mm_slot
*mm_slot
;
2039 struct mm_struct
*mm
;
2040 struct vm_area_struct
*vma
;
2044 lockdep_assert_held(&khugepaged_mm_lock
);
2046 if (khugepaged_scan
.mm_slot
)
2047 mm_slot
= khugepaged_scan
.mm_slot
;
2049 mm_slot
= list_entry(khugepaged_scan
.mm_head
.next
,
2050 struct mm_slot
, mm_node
);
2051 khugepaged_scan
.address
= 0;
2052 khugepaged_scan
.mm_slot
= mm_slot
;
2054 spin_unlock(&khugepaged_mm_lock
);
2055 khugepaged_collapse_pte_mapped_thps(mm_slot
);
2059 * Don't wait for semaphore (to avoid long wait times). Just move to
2060 * the next mm on the list.
2063 if (unlikely(!mmap_read_trylock(mm
)))
2064 goto breakouterloop_mmap_lock
;
2065 if (likely(!khugepaged_test_exit(mm
)))
2066 vma
= find_vma(mm
, khugepaged_scan
.address
);
2069 for (; vma
; vma
= vma
->vm_next
) {
2070 unsigned long hstart
, hend
;
2073 if (unlikely(khugepaged_test_exit(mm
))) {
2077 if (!hugepage_vma_check(vma
, vma
->vm_flags
)) {
2082 hstart
= (vma
->vm_start
+ ~HPAGE_PMD_MASK
) & HPAGE_PMD_MASK
;
2083 hend
= vma
->vm_end
& HPAGE_PMD_MASK
;
2086 if (khugepaged_scan
.address
> hend
)
2088 if (khugepaged_scan
.address
< hstart
)
2089 khugepaged_scan
.address
= hstart
;
2090 VM_BUG_ON(khugepaged_scan
.address
& ~HPAGE_PMD_MASK
);
2091 if (shmem_file(vma
->vm_file
) && !shmem_huge_enabled(vma
))
2094 while (khugepaged_scan
.address
< hend
) {
2097 if (unlikely(khugepaged_test_exit(mm
)))
2098 goto breakouterloop
;
2100 VM_BUG_ON(khugepaged_scan
.address
< hstart
||
2101 khugepaged_scan
.address
+ HPAGE_PMD_SIZE
>
2103 if (IS_ENABLED(CONFIG_SHMEM
) && vma
->vm_file
) {
2104 struct file
*file
= get_file(vma
->vm_file
);
2105 pgoff_t pgoff
= linear_page_index(vma
,
2106 khugepaged_scan
.address
);
2108 mmap_read_unlock(mm
);
2110 khugepaged_scan_file(mm
, file
, pgoff
, hpage
);
2113 ret
= khugepaged_scan_pmd(mm
, vma
,
2114 khugepaged_scan
.address
,
2117 /* move to next address */
2118 khugepaged_scan
.address
+= HPAGE_PMD_SIZE
;
2119 progress
+= HPAGE_PMD_NR
;
2121 /* we released mmap_lock so break loop */
2122 goto breakouterloop_mmap_lock
;
2123 if (progress
>= pages
)
2124 goto breakouterloop
;
2128 mmap_read_unlock(mm
); /* exit_mmap will destroy ptes after this */
2129 breakouterloop_mmap_lock
:
2131 spin_lock(&khugepaged_mm_lock
);
2132 VM_BUG_ON(khugepaged_scan
.mm_slot
!= mm_slot
);
2134 * Release the current mm_slot if this mm is about to die, or
2135 * if we scanned all vmas of this mm.
2137 if (khugepaged_test_exit(mm
) || !vma
) {
2139 * Make sure that if mm_users is reaching zero while
2140 * khugepaged runs here, khugepaged_exit will find
2141 * mm_slot not pointing to the exiting mm.
2143 if (mm_slot
->mm_node
.next
!= &khugepaged_scan
.mm_head
) {
2144 khugepaged_scan
.mm_slot
= list_entry(
2145 mm_slot
->mm_node
.next
,
2146 struct mm_slot
, mm_node
);
2147 khugepaged_scan
.address
= 0;
2149 khugepaged_scan
.mm_slot
= NULL
;
2150 khugepaged_full_scans
++;
2153 collect_mm_slot(mm_slot
);
2159 static int khugepaged_has_work(void)
2161 return !list_empty(&khugepaged_scan
.mm_head
) &&
2162 khugepaged_enabled();
2165 static int khugepaged_wait_event(void)
2167 return !list_empty(&khugepaged_scan
.mm_head
) ||
2168 kthread_should_stop();
2171 static void khugepaged_do_scan(void)
2173 struct page
*hpage
= NULL
;
2174 unsigned int progress
= 0, pass_through_head
= 0;
2175 unsigned int pages
= khugepaged_pages_to_scan
;
2178 barrier(); /* write khugepaged_pages_to_scan to local stack */
2180 lru_add_drain_all();
2182 while (progress
< pages
) {
2183 if (!khugepaged_prealloc_page(&hpage
, &wait
))
2188 if (unlikely(kthread_should_stop() || try_to_freeze()))
2191 spin_lock(&khugepaged_mm_lock
);
2192 if (!khugepaged_scan
.mm_slot
)
2193 pass_through_head
++;
2194 if (khugepaged_has_work() &&
2195 pass_through_head
< 2)
2196 progress
+= khugepaged_scan_mm_slot(pages
- progress
,
2200 spin_unlock(&khugepaged_mm_lock
);
2203 if (!IS_ERR_OR_NULL(hpage
))
2207 static bool khugepaged_should_wakeup(void)
2209 return kthread_should_stop() ||
2210 time_after_eq(jiffies
, khugepaged_sleep_expire
);
2213 static void khugepaged_wait_work(void)
2215 if (khugepaged_has_work()) {
2216 const unsigned long scan_sleep_jiffies
=
2217 msecs_to_jiffies(khugepaged_scan_sleep_millisecs
);
2219 if (!scan_sleep_jiffies
)
2222 khugepaged_sleep_expire
= jiffies
+ scan_sleep_jiffies
;
2223 wait_event_freezable_timeout(khugepaged_wait
,
2224 khugepaged_should_wakeup(),
2225 scan_sleep_jiffies
);
2229 if (khugepaged_enabled())
2230 wait_event_freezable(khugepaged_wait
, khugepaged_wait_event());
2233 static int khugepaged(void *none
)
2235 struct mm_slot
*mm_slot
;
2238 set_user_nice(current
, MAX_NICE
);
2240 while (!kthread_should_stop()) {
2241 khugepaged_do_scan();
2242 khugepaged_wait_work();
2245 spin_lock(&khugepaged_mm_lock
);
2246 mm_slot
= khugepaged_scan
.mm_slot
;
2247 khugepaged_scan
.mm_slot
= NULL
;
2249 collect_mm_slot(mm_slot
);
2250 spin_unlock(&khugepaged_mm_lock
);
2254 static void set_recommended_min_free_kbytes(void)
2258 unsigned long recommended_min
;
2260 for_each_populated_zone(zone
) {
2262 * We don't need to worry about fragmentation of
2263 * ZONE_MOVABLE since it only has movable pages.
2265 if (zone_idx(zone
) > gfp_zone(GFP_USER
))
2271 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2272 recommended_min
= pageblock_nr_pages
* nr_zones
* 2;
2275 * Make sure that on average at least two pageblocks are almost free
2276 * of another type, one for a migratetype to fall back to and a
2277 * second to avoid subsequent fallbacks of other types There are 3
2278 * MIGRATE_TYPES we care about.
2280 recommended_min
+= pageblock_nr_pages
* nr_zones
*
2281 MIGRATE_PCPTYPES
* MIGRATE_PCPTYPES
;
2283 /* don't ever allow to reserve more than 5% of the lowmem */
2284 recommended_min
= min(recommended_min
,
2285 (unsigned long) nr_free_buffer_pages() / 20);
2286 recommended_min
<<= (PAGE_SHIFT
-10);
2288 if (recommended_min
> min_free_kbytes
) {
2289 if (user_min_free_kbytes
>= 0)
2290 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2291 min_free_kbytes
, recommended_min
);
2293 min_free_kbytes
= recommended_min
;
2295 setup_per_zone_wmarks();
2298 int start_stop_khugepaged(void)
2300 static struct task_struct
*khugepaged_thread __read_mostly
;
2301 static DEFINE_MUTEX(khugepaged_mutex
);
2304 mutex_lock(&khugepaged_mutex
);
2305 if (khugepaged_enabled()) {
2306 if (!khugepaged_thread
)
2307 khugepaged_thread
= kthread_run(khugepaged
, NULL
,
2309 if (IS_ERR(khugepaged_thread
)) {
2310 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2311 err
= PTR_ERR(khugepaged_thread
);
2312 khugepaged_thread
= NULL
;
2316 if (!list_empty(&khugepaged_scan
.mm_head
))
2317 wake_up_interruptible(&khugepaged_wait
);
2319 set_recommended_min_free_kbytes();
2320 } else if (khugepaged_thread
) {
2321 kthread_stop(khugepaged_thread
);
2322 khugepaged_thread
= NULL
;
2325 mutex_unlock(&khugepaged_mutex
);