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>
33 SCAN_LACK_REFERENCED_PAGE,
47 SCAN_ALLOC_HUGE_PAGE_FAIL,
48 SCAN_CGROUP_CHARGE_FAIL,
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/huge_memory.h>
56 /* default scan 8*512 pte (or vmas) every 30 second */
57 static unsigned int khugepaged_pages_to_scan __read_mostly;
58 static unsigned int khugepaged_pages_collapsed;
59 static unsigned int khugepaged_full_scans;
60 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
61 /* during fragmentation poll the hugepage allocator once every minute */
62 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
63 static unsigned long khugepaged_sleep_expire;
64 static DEFINE_SPINLOCK(khugepaged_mm_lock);
65 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
67 * default collapse hugepages if there is at least one pte mapped like
68 * it would have happened if the vma was large enough during page
71 static unsigned int khugepaged_max_ptes_none __read_mostly;
72 static unsigned int khugepaged_max_ptes_swap __read_mostly;
74 #define MM_SLOTS_HASH_BITS 10
75 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
77 static struct kmem_cache *mm_slot_cache __read_mostly;
80 * struct mm_slot - hash lookup from mm to mm_slot
81 * @hash: hash collision list
82 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
83 * @mm: the mm that this information is valid for
86 struct hlist_node hash;
87 struct list_head mm_node;
92 * struct khugepaged_scan - cursor for scanning
93 * @mm_head: the head of the mm list to scan
94 * @mm_slot: the current mm_slot we are scanning
95 * @address: the next address inside that to be scanned
97 * There is only the one khugepaged_scan instance of this cursor structure.
99 struct khugepaged_scan {
100 struct list_head mm_head;
101 struct mm_slot *mm_slot;
102 unsigned long address;
105 static struct khugepaged_scan khugepaged_scan = {
106 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
110 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
111 struct kobj_attribute *attr,
114 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
117 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
118 struct kobj_attribute *attr,
119 const char *buf, size_t count)
124 err = kstrtoul(buf, 10, &msecs);
125 if (err || msecs > UINT_MAX)
128 khugepaged_scan_sleep_millisecs = msecs;
129 khugepaged_sleep_expire = 0;
130 wake_up_interruptible(&khugepaged_wait);
134 static struct kobj_attribute scan_sleep_millisecs_attr =
135 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
136 scan_sleep_millisecs_store);
138 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
139 struct kobj_attribute *attr,
142 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
145 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
146 struct kobj_attribute *attr,
147 const char *buf, size_t count)
152 err = kstrtoul(buf, 10, &msecs);
153 if (err || msecs > UINT_MAX)
156 khugepaged_alloc_sleep_millisecs = msecs;
157 khugepaged_sleep_expire = 0;
158 wake_up_interruptible(&khugepaged_wait);
162 static struct kobj_attribute alloc_sleep_millisecs_attr =
163 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
164 alloc_sleep_millisecs_store);
166 static ssize_t pages_to_scan_show(struct kobject *kobj,
167 struct kobj_attribute *attr,
170 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
172 static ssize_t pages_to_scan_store(struct kobject *kobj,
173 struct kobj_attribute *attr,
174 const char *buf, size_t count)
179 err = kstrtoul(buf, 10, &pages);
180 if (err || !pages || pages > UINT_MAX)
183 khugepaged_pages_to_scan = pages;
187 static struct kobj_attribute pages_to_scan_attr =
188 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
189 pages_to_scan_store);
191 static ssize_t pages_collapsed_show(struct kobject *kobj,
192 struct kobj_attribute *attr,
195 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
197 static struct kobj_attribute pages_collapsed_attr =
198 __ATTR_RO(pages_collapsed);
200 static ssize_t full_scans_show(struct kobject *kobj,
201 struct kobj_attribute *attr,
204 return sprintf(buf, "%u\n", khugepaged_full_scans);
206 static struct kobj_attribute full_scans_attr =
207 __ATTR_RO(full_scans);
209 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
210 struct kobj_attribute *attr, char *buf)
212 return single_hugepage_flag_show(kobj, attr, buf,
213 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
215 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
216 struct kobj_attribute *attr,
217 const char *buf, size_t count)
219 return single_hugepage_flag_store(kobj, attr, buf, count,
220 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
222 static struct kobj_attribute khugepaged_defrag_attr =
223 __ATTR(defrag, 0644, khugepaged_defrag_show,
224 khugepaged_defrag_store);
227 * max_ptes_none controls if khugepaged should collapse hugepages over
228 * any unmapped ptes in turn potentially increasing the memory
229 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
230 * reduce the available free memory in the system as it
231 * runs. Increasing max_ptes_none will instead potentially reduce the
232 * free memory in the system during the khugepaged scan.
234 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
235 struct kobj_attribute *attr,
238 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
240 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
241 struct kobj_attribute *attr,
242 const char *buf, size_t count)
245 unsigned long max_ptes_none;
247 err = kstrtoul(buf, 10, &max_ptes_none);
248 if (err || max_ptes_none > HPAGE_PMD_NR-1)
251 khugepaged_max_ptes_none = max_ptes_none;
255 static struct kobj_attribute khugepaged_max_ptes_none_attr =
256 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
257 khugepaged_max_ptes_none_store);
259 static ssize_t khugepaged_max_ptes_swap_show(struct kobject *kobj,
260 struct kobj_attribute *attr,
263 return sprintf(buf, "%u\n", khugepaged_max_ptes_swap);
266 static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
267 struct kobj_attribute *attr,
268 const char *buf, size_t count)
271 unsigned long max_ptes_swap;
273 err = kstrtoul(buf, 10, &max_ptes_swap);
274 if (err || max_ptes_swap > HPAGE_PMD_NR-1)
277 khugepaged_max_ptes_swap = max_ptes_swap;
282 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
283 __ATTR(max_ptes_swap, 0644, khugepaged_max_ptes_swap_show,
284 khugepaged_max_ptes_swap_store);
286 static struct attribute *khugepaged_attr[] = {
287 &khugepaged_defrag_attr.attr,
288 &khugepaged_max_ptes_none_attr.attr,
289 &pages_to_scan_attr.attr,
290 &pages_collapsed_attr.attr,
291 &full_scans_attr.attr,
292 &scan_sleep_millisecs_attr.attr,
293 &alloc_sleep_millisecs_attr.attr,
294 &khugepaged_max_ptes_swap_attr.attr,
298 struct attribute_group khugepaged_attr_group = {
299 .attrs = khugepaged_attr,
300 .name = "khugepaged",
302 #endif /* CONFIG_SYSFS */
304 #define VM_NO_KHUGEPAGED (VM_SPECIAL | VM_HUGETLB)
306 int hugepage_madvise(struct vm_area_struct *vma,
307 unsigned long *vm_flags, int advice)
313 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
314 * can't handle this properly after s390_enable_sie, so we simply
315 * ignore the madvise to prevent qemu from causing a SIGSEGV.
317 if (mm_has_pgste(vma->vm_mm))
320 *vm_flags &= ~VM_NOHUGEPAGE;
321 *vm_flags |= VM_HUGEPAGE;
323 * If the vma become good for khugepaged to scan,
324 * register it here without waiting a page fault that
325 * may not happen any time soon.
327 if (!(*vm_flags & VM_NO_KHUGEPAGED) &&
328 khugepaged_enter_vma_merge(vma, *vm_flags))
331 case MADV_NOHUGEPAGE:
332 *vm_flags &= ~VM_HUGEPAGE;
333 *vm_flags |= VM_NOHUGEPAGE;
335 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
336 * this vma even if we leave the mm registered in khugepaged if
337 * it got registered before VM_NOHUGEPAGE was set.
345 int __init khugepaged_init(void)
347 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
348 sizeof(struct mm_slot),
349 __alignof__(struct mm_slot), 0, NULL);
353 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
354 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
355 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
360 void __init khugepaged_destroy(void)
362 kmem_cache_destroy(mm_slot_cache);
365 static inline struct mm_slot *alloc_mm_slot(void)
367 if (!mm_slot_cache) /* initialization failed */
369 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
372 static inline void free_mm_slot(struct mm_slot *mm_slot)
374 kmem_cache_free(mm_slot_cache, mm_slot);
377 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
379 struct mm_slot *mm_slot;
381 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
382 if (mm == mm_slot->mm)
388 static void insert_to_mm_slots_hash(struct mm_struct *mm,
389 struct mm_slot *mm_slot)
392 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
395 static inline int khugepaged_test_exit(struct mm_struct *mm)
397 return atomic_read(&mm->mm_users) == 0;
400 static bool hugepage_vma_check(struct vm_area_struct *vma,
401 unsigned long vm_flags)
403 if ((!(vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
404 (vm_flags & VM_NOHUGEPAGE) ||
405 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
407 if (shmem_file(vma->vm_file)) {
408 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
410 return IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) - vma->vm_pgoff,
413 if (!vma->anon_vma || vma->vm_ops)
415 if (is_vma_temporary_stack(vma))
417 return !(vm_flags & VM_NO_KHUGEPAGED);
420 int __khugepaged_enter(struct mm_struct *mm)
422 struct mm_slot *mm_slot;
425 mm_slot = alloc_mm_slot();
429 /* __khugepaged_exit() must not run from under us */
430 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
431 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
432 free_mm_slot(mm_slot);
436 spin_lock(&khugepaged_mm_lock);
437 insert_to_mm_slots_hash(mm, mm_slot);
439 * Insert just behind the scanning cursor, to let the area settle
442 wakeup = list_empty(&khugepaged_scan.mm_head);
443 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
444 spin_unlock(&khugepaged_mm_lock);
448 wake_up_interruptible(&khugepaged_wait);
453 int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
454 unsigned long vm_flags)
456 unsigned long hstart, hend;
459 * khugepaged does not yet work on non-shmem files or special
460 * mappings. And file-private shmem THP is not supported.
462 if (!hugepage_vma_check(vma, vm_flags))
465 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
466 hend = vma->vm_end & HPAGE_PMD_MASK;
468 return khugepaged_enter(vma, vm_flags);
472 void __khugepaged_exit(struct mm_struct *mm)
474 struct mm_slot *mm_slot;
477 spin_lock(&khugepaged_mm_lock);
478 mm_slot = get_mm_slot(mm);
479 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
480 hash_del(&mm_slot->hash);
481 list_del(&mm_slot->mm_node);
484 spin_unlock(&khugepaged_mm_lock);
487 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
488 free_mm_slot(mm_slot);
490 } else if (mm_slot) {
492 * This is required to serialize against
493 * khugepaged_test_exit() (which is guaranteed to run
494 * under mmap sem read mode). Stop here (after we
495 * return all pagetables will be destroyed) until
496 * khugepaged has finished working on the pagetables
497 * under the mmap_sem.
499 down_write(&mm->mmap_sem);
500 up_write(&mm->mmap_sem);
504 static void release_pte_page(struct page *page)
506 dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
508 putback_lru_page(page);
511 static void release_pte_pages(pte_t *pte, pte_t *_pte)
513 while (--_pte >= pte) {
514 pte_t pteval = *_pte;
515 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
516 release_pte_page(pte_page(pteval));
520 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
521 unsigned long address,
524 struct page *page = NULL;
526 int none_or_zero = 0, result = 0, referenced = 0;
527 bool writable = false;
529 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
530 _pte++, address += PAGE_SIZE) {
531 pte_t pteval = *_pte;
532 if (pte_none(pteval) || (pte_present(pteval) &&
533 is_zero_pfn(pte_pfn(pteval)))) {
534 if (!userfaultfd_armed(vma) &&
535 ++none_or_zero <= khugepaged_max_ptes_none) {
538 result = SCAN_EXCEED_NONE_PTE;
542 if (!pte_present(pteval)) {
543 result = SCAN_PTE_NON_PRESENT;
546 page = vm_normal_page(vma, address, pteval);
547 if (unlikely(!page)) {
548 result = SCAN_PAGE_NULL;
552 /* TODO: teach khugepaged to collapse THP mapped with pte */
553 if (PageCompound(page)) {
554 result = SCAN_PAGE_COMPOUND;
558 VM_BUG_ON_PAGE(!PageAnon(page), page);
561 * We can do it before isolate_lru_page because the
562 * page can't be freed from under us. NOTE: PG_lock
563 * is needed to serialize against split_huge_page
564 * when invoked from the VM.
566 if (!trylock_page(page)) {
567 result = SCAN_PAGE_LOCK;
572 * cannot use mapcount: can't collapse if there's a gup pin.
573 * The page must only be referenced by the scanned process
574 * and page swap cache.
576 if (page_count(page) != 1 + PageSwapCache(page)) {
578 result = SCAN_PAGE_COUNT;
581 if (pte_write(pteval)) {
584 if (PageSwapCache(page) &&
585 !reuse_swap_page(page, NULL)) {
587 result = SCAN_SWAP_CACHE_PAGE;
591 * Page is not in the swap cache. It can be collapsed
597 * Isolate the page to avoid collapsing an hugepage
598 * currently in use by the VM.
600 if (isolate_lru_page(page)) {
602 result = SCAN_DEL_PAGE_LRU;
605 inc_node_page_state(page,
606 NR_ISOLATED_ANON + page_is_file_cache(page));
607 VM_BUG_ON_PAGE(!PageLocked(page), page);
608 VM_BUG_ON_PAGE(PageLRU(page), page);
610 /* There should be enough young pte to collapse the page */
611 if (pte_young(pteval) ||
612 page_is_young(page) || PageReferenced(page) ||
613 mmu_notifier_test_young(vma->vm_mm, address))
616 if (likely(writable)) {
617 if (likely(referenced)) {
618 result = SCAN_SUCCEED;
619 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
620 referenced, writable, result);
624 result = SCAN_PAGE_RO;
628 release_pte_pages(pte, _pte);
629 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
630 referenced, writable, result);
634 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
635 struct vm_area_struct *vma,
636 unsigned long address,
640 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
641 _pte++, page++, address += PAGE_SIZE) {
642 pte_t pteval = *_pte;
643 struct page *src_page;
645 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
646 clear_user_highpage(page, address);
647 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
648 if (is_zero_pfn(pte_pfn(pteval))) {
650 * ptl mostly unnecessary.
654 * paravirt calls inside pte_clear here are
657 pte_clear(vma->vm_mm, address, _pte);
661 src_page = pte_page(pteval);
662 copy_user_highpage(page, src_page, address, vma);
663 VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
664 release_pte_page(src_page);
666 * ptl mostly unnecessary, but preempt has to
667 * be disabled to update the per-cpu stats
668 * inside page_remove_rmap().
672 * paravirt calls inside pte_clear here are
675 pte_clear(vma->vm_mm, address, _pte);
676 page_remove_rmap(src_page, false);
678 free_page_and_swap_cache(src_page);
683 static void khugepaged_alloc_sleep(void)
687 add_wait_queue(&khugepaged_wait, &wait);
688 freezable_schedule_timeout_interruptible(
689 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
690 remove_wait_queue(&khugepaged_wait, &wait);
693 static int khugepaged_node_load[MAX_NUMNODES];
695 static bool khugepaged_scan_abort(int nid)
700 * If node_reclaim_mode is disabled, then no extra effort is made to
701 * allocate memory locally.
703 if (!node_reclaim_mode)
706 /* If there is a count for this node already, it must be acceptable */
707 if (khugepaged_node_load[nid])
710 for (i = 0; i < MAX_NUMNODES; i++) {
711 if (!khugepaged_node_load[i])
713 if (node_distance(nid, i) > RECLAIM_DISTANCE)
719 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
720 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
722 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
726 static int khugepaged_find_target_node(void)
728 static int last_khugepaged_target_node = NUMA_NO_NODE;
729 int nid, target_node = 0, max_value = 0;
731 /* find first node with max normal pages hit */
732 for (nid = 0; nid < MAX_NUMNODES; nid++)
733 if (khugepaged_node_load[nid] > max_value) {
734 max_value = khugepaged_node_load[nid];
738 /* do some balance if several nodes have the same hit record */
739 if (target_node <= last_khugepaged_target_node)
740 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
742 if (max_value == khugepaged_node_load[nid]) {
747 last_khugepaged_target_node = target_node;
751 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
753 if (IS_ERR(*hpage)) {
759 khugepaged_alloc_sleep();
769 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
771 VM_BUG_ON_PAGE(*hpage, *hpage);
773 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
774 if (unlikely(!*hpage)) {
775 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
776 *hpage = ERR_PTR(-ENOMEM);
780 prep_transhuge_page(*hpage);
781 count_vm_event(THP_COLLAPSE_ALLOC);
785 static int khugepaged_find_target_node(void)
790 static inline struct page *alloc_khugepaged_hugepage(void)
794 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
797 prep_transhuge_page(page);
801 static struct page *khugepaged_alloc_hugepage(bool *wait)
806 hpage = alloc_khugepaged_hugepage();
808 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
813 khugepaged_alloc_sleep();
815 count_vm_event(THP_COLLAPSE_ALLOC);
816 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
821 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
824 *hpage = khugepaged_alloc_hugepage(wait);
826 if (unlikely(!*hpage))
833 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
842 * If mmap_sem temporarily dropped, revalidate vma
843 * before taking mmap_sem.
844 * Return 0 if succeeds, otherwise return none-zero
848 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
849 struct vm_area_struct **vmap)
851 struct vm_area_struct *vma;
852 unsigned long hstart, hend;
854 if (unlikely(khugepaged_test_exit(mm)))
855 return SCAN_ANY_PROCESS;
857 *vmap = vma = find_vma(mm, address);
859 return SCAN_VMA_NULL;
861 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
862 hend = vma->vm_end & HPAGE_PMD_MASK;
863 if (address < hstart || address + HPAGE_PMD_SIZE > hend)
864 return SCAN_ADDRESS_RANGE;
865 if (!hugepage_vma_check(vma, vma->vm_flags))
866 return SCAN_VMA_CHECK;
871 * Bring missing pages in from swap, to complete THP collapse.
872 * Only done if khugepaged_scan_pmd believes it is worthwhile.
874 * Called and returns without pte mapped or spinlocks held,
875 * but with mmap_sem held to protect against vma changes.
878 static bool __collapse_huge_page_swapin(struct mm_struct *mm,
879 struct vm_area_struct *vma,
880 unsigned long address, pmd_t *pmd,
885 struct vm_fault vmf = {
888 .flags = FAULT_FLAG_ALLOW_RETRY,
890 .pgoff = linear_page_index(vma, address),
893 /* we only decide to swapin, if there is enough young ptes */
894 if (referenced < HPAGE_PMD_NR/2) {
895 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
898 vmf.pte = pte_offset_map(pmd, address);
899 for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
900 vmf.pte++, vmf.address += PAGE_SIZE) {
901 vmf.orig_pte = *vmf.pte;
902 if (!is_swap_pte(vmf.orig_pte))
905 ret = do_swap_page(&vmf);
907 /* do_swap_page returns VM_FAULT_RETRY with released mmap_sem */
908 if (ret & VM_FAULT_RETRY) {
909 down_read(&mm->mmap_sem);
910 if (hugepage_vma_revalidate(mm, address, &vmf.vma)) {
911 /* vma is no longer available, don't continue to swapin */
912 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
915 /* check if the pmd is still valid */
916 if (mm_find_pmd(mm, address) != pmd) {
917 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
921 if (ret & VM_FAULT_ERROR) {
922 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
925 /* pte is unmapped now, we need to map it */
926 vmf.pte = pte_offset_map(pmd, vmf.address);
930 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
934 static void collapse_huge_page(struct mm_struct *mm,
935 unsigned long address,
937 int node, int referenced)
942 struct page *new_page;
943 spinlock_t *pmd_ptl, *pte_ptl;
944 int isolated = 0, result = 0;
945 struct mem_cgroup *memcg;
946 struct vm_area_struct *vma;
947 unsigned long mmun_start; /* For mmu_notifiers */
948 unsigned long mmun_end; /* For mmu_notifiers */
951 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
953 /* Only allocate from the target node */
954 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
957 * Before allocating the hugepage, release the mmap_sem read lock.
958 * The allocation can take potentially a long time if it involves
959 * sync compaction, and we do not need to hold the mmap_sem during
960 * that. We will recheck the vma after taking it again in write mode.
962 up_read(&mm->mmap_sem);
963 new_page = khugepaged_alloc_page(hpage, gfp, node);
965 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
969 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
970 result = SCAN_CGROUP_CHARGE_FAIL;
974 down_read(&mm->mmap_sem);
975 result = hugepage_vma_revalidate(mm, address, &vma);
977 mem_cgroup_cancel_charge(new_page, memcg, true);
978 up_read(&mm->mmap_sem);
982 pmd = mm_find_pmd(mm, address);
984 result = SCAN_PMD_NULL;
985 mem_cgroup_cancel_charge(new_page, memcg, true);
986 up_read(&mm->mmap_sem);
991 * __collapse_huge_page_swapin always returns with mmap_sem locked.
992 * If it fails, we release mmap_sem and jump out_nolock.
993 * Continuing to collapse causes inconsistency.
995 if (!__collapse_huge_page_swapin(mm, vma, address, pmd, referenced)) {
996 mem_cgroup_cancel_charge(new_page, memcg, true);
997 up_read(&mm->mmap_sem);
1001 up_read(&mm->mmap_sem);
1003 * Prevent all access to pagetables with the exception of
1004 * gup_fast later handled by the ptep_clear_flush and the VM
1005 * handled by the anon_vma lock + PG_lock.
1007 down_write(&mm->mmap_sem);
1008 result = hugepage_vma_revalidate(mm, address, &vma);
1011 /* check if the pmd is still valid */
1012 if (mm_find_pmd(mm, address) != pmd)
1015 anon_vma_lock_write(vma->anon_vma);
1017 pte = pte_offset_map(pmd, address);
1018 pte_ptl = pte_lockptr(mm, pmd);
1020 mmun_start = address;
1021 mmun_end = address + HPAGE_PMD_SIZE;
1022 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1023 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1025 * After this gup_fast can't run anymore. This also removes
1026 * any huge TLB entry from the CPU so we won't allow
1027 * huge and small TLB entries for the same virtual address
1028 * to avoid the risk of CPU bugs in that area.
1030 _pmd = pmdp_collapse_flush(vma, address, pmd);
1031 spin_unlock(pmd_ptl);
1032 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1035 isolated = __collapse_huge_page_isolate(vma, address, pte);
1036 spin_unlock(pte_ptl);
1038 if (unlikely(!isolated)) {
1041 BUG_ON(!pmd_none(*pmd));
1043 * We can only use set_pmd_at when establishing
1044 * hugepmds and never for establishing regular pmds that
1045 * points to regular pagetables. Use pmd_populate for that
1047 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1048 spin_unlock(pmd_ptl);
1049 anon_vma_unlock_write(vma->anon_vma);
1055 * All pages are isolated and locked so anon_vma rmap
1056 * can't run anymore.
1058 anon_vma_unlock_write(vma->anon_vma);
1060 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
1062 __SetPageUptodate(new_page);
1063 pgtable = pmd_pgtable(_pmd);
1065 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1066 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1069 * spin_lock() below is not the equivalent of smp_wmb(), so
1070 * this is needed to avoid the copy_huge_page writes to become
1071 * visible after the set_pmd_at() write.
1076 BUG_ON(!pmd_none(*pmd));
1077 page_add_new_anon_rmap(new_page, vma, address, true);
1078 mem_cgroup_commit_charge(new_page, memcg, false, true);
1079 lru_cache_add_active_or_unevictable(new_page, vma);
1080 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1081 set_pmd_at(mm, address, pmd, _pmd);
1082 update_mmu_cache_pmd(vma, address, pmd);
1083 spin_unlock(pmd_ptl);
1087 khugepaged_pages_collapsed++;
1088 result = SCAN_SUCCEED;
1090 up_write(&mm->mmap_sem);
1092 trace_mm_collapse_huge_page(mm, isolated, result);
1095 mem_cgroup_cancel_charge(new_page, memcg, true);
1099 static int khugepaged_scan_pmd(struct mm_struct *mm,
1100 struct vm_area_struct *vma,
1101 unsigned long address,
1102 struct page **hpage)
1106 int ret = 0, none_or_zero = 0, result = 0, referenced = 0;
1107 struct page *page = NULL;
1108 unsigned long _address;
1110 int node = NUMA_NO_NODE, unmapped = 0;
1111 bool writable = false;
1113 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1115 pmd = mm_find_pmd(mm, address);
1117 result = SCAN_PMD_NULL;
1121 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1122 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1123 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1124 _pte++, _address += PAGE_SIZE) {
1125 pte_t pteval = *_pte;
1126 if (is_swap_pte(pteval)) {
1127 if (++unmapped <= khugepaged_max_ptes_swap) {
1130 result = SCAN_EXCEED_SWAP_PTE;
1134 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1135 if (!userfaultfd_armed(vma) &&
1136 ++none_or_zero <= khugepaged_max_ptes_none) {
1139 result = SCAN_EXCEED_NONE_PTE;
1143 if (!pte_present(pteval)) {
1144 result = SCAN_PTE_NON_PRESENT;
1147 if (pte_write(pteval))
1150 page = vm_normal_page(vma, _address, pteval);
1151 if (unlikely(!page)) {
1152 result = SCAN_PAGE_NULL;
1156 /* TODO: teach khugepaged to collapse THP mapped with pte */
1157 if (PageCompound(page)) {
1158 result = SCAN_PAGE_COMPOUND;
1163 * Record which node the original page is from and save this
1164 * information to khugepaged_node_load[].
1165 * Khupaged will allocate hugepage from the node has the max
1168 node = page_to_nid(page);
1169 if (khugepaged_scan_abort(node)) {
1170 result = SCAN_SCAN_ABORT;
1173 khugepaged_node_load[node]++;
1174 if (!PageLRU(page)) {
1175 result = SCAN_PAGE_LRU;
1178 if (PageLocked(page)) {
1179 result = SCAN_PAGE_LOCK;
1182 if (!PageAnon(page)) {
1183 result = SCAN_PAGE_ANON;
1188 * cannot use mapcount: can't collapse if there's a gup pin.
1189 * The page must only be referenced by the scanned process
1190 * and page swap cache.
1192 if (page_count(page) != 1 + PageSwapCache(page)) {
1193 result = SCAN_PAGE_COUNT;
1196 if (pte_young(pteval) ||
1197 page_is_young(page) || PageReferenced(page) ||
1198 mmu_notifier_test_young(vma->vm_mm, address))
1203 result = SCAN_SUCCEED;
1206 result = SCAN_LACK_REFERENCED_PAGE;
1209 result = SCAN_PAGE_RO;
1212 pte_unmap_unlock(pte, ptl);
1214 node = khugepaged_find_target_node();
1215 /* collapse_huge_page will return with the mmap_sem released */
1216 collapse_huge_page(mm, address, hpage, node, referenced);
1219 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1220 none_or_zero, result, unmapped);
1224 static void collect_mm_slot(struct mm_slot *mm_slot)
1226 struct mm_struct *mm = mm_slot->mm;
1228 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
1230 if (khugepaged_test_exit(mm)) {
1232 hash_del(&mm_slot->hash);
1233 list_del(&mm_slot->mm_node);
1236 * Not strictly needed because the mm exited already.
1238 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1241 /* khugepaged_mm_lock actually not necessary for the below */
1242 free_mm_slot(mm_slot);
1247 #if defined(CONFIG_SHMEM) && defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE)
1248 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1250 struct vm_area_struct *vma;
1254 i_mmap_lock_write(mapping);
1255 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1256 /* probably overkill */
1259 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1260 if (addr & ~HPAGE_PMD_MASK)
1262 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1264 pmd = mm_find_pmd(vma->vm_mm, addr);
1268 * We need exclusive mmap_sem to retract page table.
1269 * If trylock fails we would end up with pte-mapped THP after
1270 * re-fault. Not ideal, but it's more important to not disturb
1271 * the system too much.
1273 if (down_write_trylock(&vma->vm_mm->mmap_sem)) {
1274 spinlock_t *ptl = pmd_lock(vma->vm_mm, pmd);
1275 /* assume page table is clear */
1276 _pmd = pmdp_collapse_flush(vma, addr, pmd);
1278 up_write(&vma->vm_mm->mmap_sem);
1279 mm_dec_nr_ptes(vma->vm_mm);
1280 pte_free(vma->vm_mm, pmd_pgtable(_pmd));
1283 i_mmap_unlock_write(mapping);
1287 * collapse_shmem - collapse small tmpfs/shmem pages into huge one.
1289 * Basic scheme is simple, details are more complex:
1290 * - allocate and freeze a new huge page;
1291 * - scan over radix tree replacing old pages the new one
1292 * + swap in pages if necessary;
1294 * + keep old pages around in case if rollback is required;
1295 * - if replacing succeed:
1298 * + unfreeze huge page;
1299 * - if replacing failed;
1300 * + put all pages back and unfreeze them;
1301 * + restore gaps in the radix-tree;
1304 static void collapse_shmem(struct mm_struct *mm,
1305 struct address_space *mapping, pgoff_t start,
1306 struct page **hpage, int node)
1309 struct page *page, *new_page, *tmp;
1310 struct mem_cgroup *memcg;
1311 pgoff_t index, end = start + HPAGE_PMD_NR;
1312 LIST_HEAD(pagelist);
1313 struct radix_tree_iter iter;
1315 int nr_none = 0, result = SCAN_SUCCEED;
1317 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1319 /* Only allocate from the target node */
1320 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1322 new_page = khugepaged_alloc_page(hpage, gfp, node);
1324 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1328 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
1329 result = SCAN_CGROUP_CHARGE_FAIL;
1333 new_page->index = start;
1334 new_page->mapping = mapping;
1335 __SetPageSwapBacked(new_page);
1336 __SetPageLocked(new_page);
1337 BUG_ON(!page_ref_freeze(new_page, 1));
1341 * At this point the new_page is 'frozen' (page_count() is zero), locked
1342 * and not up-to-date. It's safe to insert it into radix tree, because
1343 * nobody would be able to map it or use it in other way until we
1348 xa_lock_irq(&mapping->i_pages);
1349 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1350 int n = min(iter.index, end) - index;
1353 * Handle holes in the radix tree: charge it from shmem and
1354 * insert relevant subpage of new_page into the radix-tree.
1356 if (n && !shmem_charge(mapping->host, n)) {
1361 for (; index < min(iter.index, end); index++) {
1362 radix_tree_insert(&mapping->i_pages, index,
1363 new_page + (index % HPAGE_PMD_NR));
1370 page = radix_tree_deref_slot_protected(slot,
1371 &mapping->i_pages.xa_lock);
1372 if (radix_tree_exceptional_entry(page) || !PageUptodate(page)) {
1373 xa_unlock_irq(&mapping->i_pages);
1374 /* swap in or instantiate fallocated page */
1375 if (shmem_getpage(mapping->host, index, &page,
1380 xa_lock_irq(&mapping->i_pages);
1381 } else if (trylock_page(page)) {
1384 result = SCAN_PAGE_LOCK;
1389 * The page must be locked, so we can drop the i_pages lock
1390 * without racing with truncate.
1392 VM_BUG_ON_PAGE(!PageLocked(page), page);
1393 VM_BUG_ON_PAGE(!PageUptodate(page), page);
1394 VM_BUG_ON_PAGE(PageTransCompound(page), page);
1396 if (page_mapping(page) != mapping) {
1397 result = SCAN_TRUNCATED;
1400 xa_unlock_irq(&mapping->i_pages);
1402 if (isolate_lru_page(page)) {
1403 result = SCAN_DEL_PAGE_LRU;
1404 goto out_isolate_failed;
1407 if (page_mapped(page))
1408 unmap_mapping_pages(mapping, index, 1, false);
1410 xa_lock_irq(&mapping->i_pages);
1412 slot = radix_tree_lookup_slot(&mapping->i_pages, index);
1413 VM_BUG_ON_PAGE(page != radix_tree_deref_slot_protected(slot,
1414 &mapping->i_pages.xa_lock), page);
1415 VM_BUG_ON_PAGE(page_mapped(page), page);
1418 * The page is expected to have page_count() == 3:
1419 * - we hold a pin on it;
1420 * - one reference from radix tree;
1421 * - one from isolate_lru_page;
1423 if (!page_ref_freeze(page, 3)) {
1424 result = SCAN_PAGE_COUNT;
1429 * Add the page to the list to be able to undo the collapse if
1430 * something go wrong.
1432 list_add_tail(&page->lru, &pagelist);
1434 /* Finally, replace with the new page. */
1435 radix_tree_replace_slot(&mapping->i_pages, slot,
1436 new_page + (index % HPAGE_PMD_NR));
1438 slot = radix_tree_iter_resume(slot, &iter);
1442 xa_unlock_irq(&mapping->i_pages);
1443 putback_lru_page(page);
1455 * Handle hole in radix tree at the end of the range.
1456 * This code only triggers if there's nothing in radix tree
1459 if (result == SCAN_SUCCEED && index < end) {
1460 int n = end - index;
1462 if (!shmem_charge(mapping->host, n)) {
1467 for (; index < end; index++) {
1468 radix_tree_insert(&mapping->i_pages, index,
1469 new_page + (index % HPAGE_PMD_NR));
1475 xa_unlock_irq(&mapping->i_pages);
1478 if (result == SCAN_SUCCEED) {
1479 unsigned long flags;
1480 struct zone *zone = page_zone(new_page);
1483 * Replacing old pages with new one has succeed, now we need to
1484 * copy the content and free old pages.
1486 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1487 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1489 list_del(&page->lru);
1491 page_ref_unfreeze(page, 1);
1492 page->mapping = NULL;
1493 ClearPageActive(page);
1494 ClearPageUnevictable(page);
1498 local_irq_save(flags);
1499 __inc_node_page_state(new_page, NR_SHMEM_THPS);
1501 __mod_node_page_state(zone->zone_pgdat, NR_FILE_PAGES, nr_none);
1502 __mod_node_page_state(zone->zone_pgdat, NR_SHMEM, nr_none);
1504 local_irq_restore(flags);
1507 * Remove pte page tables, so we can re-faulti
1510 retract_page_tables(mapping, start);
1512 /* Everything is ready, let's unfreeze the new_page */
1513 set_page_dirty(new_page);
1514 SetPageUptodate(new_page);
1515 page_ref_unfreeze(new_page, HPAGE_PMD_NR);
1516 mem_cgroup_commit_charge(new_page, memcg, false, true);
1517 lru_cache_add_anon(new_page);
1518 unlock_page(new_page);
1522 khugepaged_pages_collapsed++;
1524 /* Something went wrong: rollback changes to the radix-tree */
1525 shmem_uncharge(mapping->host, nr_none);
1526 xa_lock_irq(&mapping->i_pages);
1527 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1528 if (iter.index >= end)
1530 page = list_first_entry_or_null(&pagelist,
1532 if (!page || iter.index < page->index) {
1536 /* Put holes back where they were */
1537 radix_tree_delete(&mapping->i_pages, iter.index);
1541 VM_BUG_ON_PAGE(page->index != iter.index, page);
1543 /* Unfreeze the page. */
1544 list_del(&page->lru);
1545 page_ref_unfreeze(page, 2);
1546 radix_tree_replace_slot(&mapping->i_pages, slot, page);
1547 slot = radix_tree_iter_resume(slot, &iter);
1548 xa_unlock_irq(&mapping->i_pages);
1549 putback_lru_page(page);
1551 xa_lock_irq(&mapping->i_pages);
1554 xa_unlock_irq(&mapping->i_pages);
1556 /* Unfreeze new_page, caller would take care about freeing it */
1557 page_ref_unfreeze(new_page, 1);
1558 mem_cgroup_cancel_charge(new_page, memcg, true);
1559 unlock_page(new_page);
1560 new_page->mapping = NULL;
1563 VM_BUG_ON(!list_empty(&pagelist));
1564 /* TODO: tracepoints */
1567 static void khugepaged_scan_shmem(struct mm_struct *mm,
1568 struct address_space *mapping,
1569 pgoff_t start, struct page **hpage)
1571 struct page *page = NULL;
1572 struct radix_tree_iter iter;
1575 int node = NUMA_NO_NODE;
1576 int result = SCAN_SUCCEED;
1580 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1582 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1583 if (iter.index >= start + HPAGE_PMD_NR)
1586 page = radix_tree_deref_slot(slot);
1587 if (radix_tree_deref_retry(page)) {
1588 slot = radix_tree_iter_retry(&iter);
1592 if (radix_tree_exception(page)) {
1593 if (++swap > khugepaged_max_ptes_swap) {
1594 result = SCAN_EXCEED_SWAP_PTE;
1600 if (PageTransCompound(page)) {
1601 result = SCAN_PAGE_COMPOUND;
1605 node = page_to_nid(page);
1606 if (khugepaged_scan_abort(node)) {
1607 result = SCAN_SCAN_ABORT;
1610 khugepaged_node_load[node]++;
1612 if (!PageLRU(page)) {
1613 result = SCAN_PAGE_LRU;
1617 if (page_count(page) != 1 + page_mapcount(page)) {
1618 result = SCAN_PAGE_COUNT;
1623 * We probably should check if the page is referenced here, but
1624 * nobody would transfer pte_young() to PageReferenced() for us.
1625 * And rmap walk here is just too costly...
1630 if (need_resched()) {
1631 slot = radix_tree_iter_resume(slot, &iter);
1637 if (result == SCAN_SUCCEED) {
1638 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
1639 result = SCAN_EXCEED_NONE_PTE;
1641 node = khugepaged_find_target_node();
1642 collapse_shmem(mm, mapping, start, hpage, node);
1646 /* TODO: tracepoints */
1649 static void khugepaged_scan_shmem(struct mm_struct *mm,
1650 struct address_space *mapping,
1651 pgoff_t start, struct page **hpage)
1657 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
1658 struct page **hpage)
1659 __releases(&khugepaged_mm_lock)
1660 __acquires(&khugepaged_mm_lock)
1662 struct mm_slot *mm_slot;
1663 struct mm_struct *mm;
1664 struct vm_area_struct *vma;
1668 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
1670 if (khugepaged_scan.mm_slot)
1671 mm_slot = khugepaged_scan.mm_slot;
1673 mm_slot = list_entry(khugepaged_scan.mm_head.next,
1674 struct mm_slot, mm_node);
1675 khugepaged_scan.address = 0;
1676 khugepaged_scan.mm_slot = mm_slot;
1678 spin_unlock(&khugepaged_mm_lock);
1682 * Don't wait for semaphore (to avoid long wait times). Just move to
1683 * the next mm on the list.
1686 if (unlikely(!down_read_trylock(&mm->mmap_sem)))
1687 goto breakouterloop_mmap_sem;
1688 if (likely(!khugepaged_test_exit(mm)))
1689 vma = find_vma(mm, khugepaged_scan.address);
1692 for (; vma; vma = vma->vm_next) {
1693 unsigned long hstart, hend;
1696 if (unlikely(khugepaged_test_exit(mm))) {
1700 if (!hugepage_vma_check(vma, vma->vm_flags)) {
1705 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1706 hend = vma->vm_end & HPAGE_PMD_MASK;
1709 if (khugepaged_scan.address > hend)
1711 if (khugepaged_scan.address < hstart)
1712 khugepaged_scan.address = hstart;
1713 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
1715 while (khugepaged_scan.address < hend) {
1718 if (unlikely(khugepaged_test_exit(mm)))
1719 goto breakouterloop;
1721 VM_BUG_ON(khugepaged_scan.address < hstart ||
1722 khugepaged_scan.address + HPAGE_PMD_SIZE >
1724 if (shmem_file(vma->vm_file)) {
1726 pgoff_t pgoff = linear_page_index(vma,
1727 khugepaged_scan.address);
1728 if (!shmem_huge_enabled(vma))
1730 file = get_file(vma->vm_file);
1731 up_read(&mm->mmap_sem);
1733 khugepaged_scan_shmem(mm, file->f_mapping,
1737 ret = khugepaged_scan_pmd(mm, vma,
1738 khugepaged_scan.address,
1741 /* move to next address */
1742 khugepaged_scan.address += HPAGE_PMD_SIZE;
1743 progress += HPAGE_PMD_NR;
1745 /* we released mmap_sem so break loop */
1746 goto breakouterloop_mmap_sem;
1747 if (progress >= pages)
1748 goto breakouterloop;
1752 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
1753 breakouterloop_mmap_sem:
1755 spin_lock(&khugepaged_mm_lock);
1756 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
1758 * Release the current mm_slot if this mm is about to die, or
1759 * if we scanned all vmas of this mm.
1761 if (khugepaged_test_exit(mm) || !vma) {
1763 * Make sure that if mm_users is reaching zero while
1764 * khugepaged runs here, khugepaged_exit will find
1765 * mm_slot not pointing to the exiting mm.
1767 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
1768 khugepaged_scan.mm_slot = list_entry(
1769 mm_slot->mm_node.next,
1770 struct mm_slot, mm_node);
1771 khugepaged_scan.address = 0;
1773 khugepaged_scan.mm_slot = NULL;
1774 khugepaged_full_scans++;
1777 collect_mm_slot(mm_slot);
1783 static int khugepaged_has_work(void)
1785 return !list_empty(&khugepaged_scan.mm_head) &&
1786 khugepaged_enabled();
1789 static int khugepaged_wait_event(void)
1791 return !list_empty(&khugepaged_scan.mm_head) ||
1792 kthread_should_stop();
1795 static void khugepaged_do_scan(void)
1797 struct page *hpage = NULL;
1798 unsigned int progress = 0, pass_through_head = 0;
1799 unsigned int pages = khugepaged_pages_to_scan;
1802 barrier(); /* write khugepaged_pages_to_scan to local stack */
1804 while (progress < pages) {
1805 if (!khugepaged_prealloc_page(&hpage, &wait))
1810 if (unlikely(kthread_should_stop() || try_to_freeze()))
1813 spin_lock(&khugepaged_mm_lock);
1814 if (!khugepaged_scan.mm_slot)
1815 pass_through_head++;
1816 if (khugepaged_has_work() &&
1817 pass_through_head < 2)
1818 progress += khugepaged_scan_mm_slot(pages - progress,
1822 spin_unlock(&khugepaged_mm_lock);
1825 if (!IS_ERR_OR_NULL(hpage))
1829 static bool khugepaged_should_wakeup(void)
1831 return kthread_should_stop() ||
1832 time_after_eq(jiffies, khugepaged_sleep_expire);
1835 static void khugepaged_wait_work(void)
1837 if (khugepaged_has_work()) {
1838 const unsigned long scan_sleep_jiffies =
1839 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
1841 if (!scan_sleep_jiffies)
1844 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
1845 wait_event_freezable_timeout(khugepaged_wait,
1846 khugepaged_should_wakeup(),
1847 scan_sleep_jiffies);
1851 if (khugepaged_enabled())
1852 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
1855 static int khugepaged(void *none)
1857 struct mm_slot *mm_slot;
1860 set_user_nice(current, MAX_NICE);
1862 while (!kthread_should_stop()) {
1863 khugepaged_do_scan();
1864 khugepaged_wait_work();
1867 spin_lock(&khugepaged_mm_lock);
1868 mm_slot = khugepaged_scan.mm_slot;
1869 khugepaged_scan.mm_slot = NULL;
1871 collect_mm_slot(mm_slot);
1872 spin_unlock(&khugepaged_mm_lock);
1876 static void set_recommended_min_free_kbytes(void)
1880 unsigned long recommended_min;
1882 for_each_populated_zone(zone) {
1884 * We don't need to worry about fragmentation of
1885 * ZONE_MOVABLE since it only has movable pages.
1887 if (zone_idx(zone) > gfp_zone(GFP_USER))
1893 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
1894 recommended_min = pageblock_nr_pages * nr_zones * 2;
1897 * Make sure that on average at least two pageblocks are almost free
1898 * of another type, one for a migratetype to fall back to and a
1899 * second to avoid subsequent fallbacks of other types There are 3
1900 * MIGRATE_TYPES we care about.
1902 recommended_min += pageblock_nr_pages * nr_zones *
1903 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
1905 /* don't ever allow to reserve more than 5% of the lowmem */
1906 recommended_min = min(recommended_min,
1907 (unsigned long) nr_free_buffer_pages() / 20);
1908 recommended_min <<= (PAGE_SHIFT-10);
1910 if (recommended_min > min_free_kbytes) {
1911 if (user_min_free_kbytes >= 0)
1912 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
1913 min_free_kbytes, recommended_min);
1915 min_free_kbytes = recommended_min;
1917 setup_per_zone_wmarks();
1920 int start_stop_khugepaged(void)
1922 static struct task_struct *khugepaged_thread __read_mostly;
1923 static DEFINE_MUTEX(khugepaged_mutex);
1926 mutex_lock(&khugepaged_mutex);
1927 if (khugepaged_enabled()) {
1928 if (!khugepaged_thread)
1929 khugepaged_thread = kthread_run(khugepaged, NULL,
1931 if (IS_ERR(khugepaged_thread)) {
1932 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
1933 err = PTR_ERR(khugepaged_thread);
1934 khugepaged_thread = NULL;
1938 if (!list_empty(&khugepaged_scan.mm_head))
1939 wake_up_interruptible(&khugepaged_wait);
1941 set_recommended_min_free_kbytes();
1942 } else if (khugepaged_thread) {
1943 kthread_stop(khugepaged_thread);
1944 khugepaged_thread = NULL;
1947 mutex_unlock(&khugepaged_mutex);