unicore: Drop pointless include
[linux/fpc-iii.git] / mm / khugepaged.c
blobeaaa21b2321565decde43a03f73dffabd443eba3
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
4 #include <linux/mm.h>
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>
22 #include <asm/tlb.h>
23 #include <asm/pgalloc.h>
24 #include "internal.h"
26 enum scan_result {
27 SCAN_FAIL,
28 SCAN_SUCCEED,
29 SCAN_PMD_NULL,
30 SCAN_EXCEED_NONE_PTE,
31 SCAN_PTE_NON_PRESENT,
32 SCAN_PAGE_RO,
33 SCAN_LACK_REFERENCED_PAGE,
34 SCAN_PAGE_NULL,
35 SCAN_SCAN_ABORT,
36 SCAN_PAGE_COUNT,
37 SCAN_PAGE_LRU,
38 SCAN_PAGE_LOCK,
39 SCAN_PAGE_ANON,
40 SCAN_PAGE_COMPOUND,
41 SCAN_ANY_PROCESS,
42 SCAN_VMA_NULL,
43 SCAN_VMA_CHECK,
44 SCAN_ADDRESS_RANGE,
45 SCAN_SWAP_CACHE_PAGE,
46 SCAN_DEL_PAGE_LRU,
47 SCAN_ALLOC_HUGE_PAGE_FAIL,
48 SCAN_CGROUP_CHARGE_FAIL,
49 SCAN_EXCEED_SWAP_PTE,
50 SCAN_TRUNCATED,
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
69 * fault.
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;
79 /**
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
85 struct mm_slot {
86 struct hlist_node hash;
87 struct list_head mm_node;
88 struct mm_struct *mm;
91 /**
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),
109 #ifdef CONFIG_SYSFS
110 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
111 struct kobj_attribute *attr,
112 char *buf)
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)
121 unsigned long msecs;
122 int err;
124 err = kstrtoul(buf, 10, &msecs);
125 if (err || msecs > UINT_MAX)
126 return -EINVAL;
128 khugepaged_scan_sleep_millisecs = msecs;
129 khugepaged_sleep_expire = 0;
130 wake_up_interruptible(&khugepaged_wait);
132 return count;
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,
140 char *buf)
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)
149 unsigned long msecs;
150 int err;
152 err = kstrtoul(buf, 10, &msecs);
153 if (err || msecs > UINT_MAX)
154 return -EINVAL;
156 khugepaged_alloc_sleep_millisecs = msecs;
157 khugepaged_sleep_expire = 0;
158 wake_up_interruptible(&khugepaged_wait);
160 return count;
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,
168 char *buf)
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)
176 int err;
177 unsigned long pages;
179 err = kstrtoul(buf, 10, &pages);
180 if (err || !pages || pages > UINT_MAX)
181 return -EINVAL;
183 khugepaged_pages_to_scan = pages;
185 return count;
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,
193 char *buf)
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,
202 char *buf)
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,
236 char *buf)
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)
244 int err;
245 unsigned long max_ptes_none;
247 err = kstrtoul(buf, 10, &max_ptes_none);
248 if (err || max_ptes_none > HPAGE_PMD_NR-1)
249 return -EINVAL;
251 khugepaged_max_ptes_none = max_ptes_none;
253 return count;
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,
261 char *buf)
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)
270 int err;
271 unsigned long max_ptes_swap;
273 err = kstrtoul(buf, 10, &max_ptes_swap);
274 if (err || max_ptes_swap > HPAGE_PMD_NR-1)
275 return -EINVAL;
277 khugepaged_max_ptes_swap = max_ptes_swap;
279 return count;
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,
295 NULL,
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)
309 switch (advice) {
310 case MADV_HUGEPAGE:
311 #ifdef CONFIG_S390
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))
318 return 0;
319 #endif
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))
329 return -ENOMEM;
330 break;
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.
339 break;
342 return 0;
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);
350 if (!mm_slot_cache)
351 return -ENOMEM;
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;
357 return 0;
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 */
368 return NULL;
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)
383 return mm_slot;
385 return NULL;
388 static void insert_to_mm_slots_hash(struct mm_struct *mm,
389 struct mm_slot *mm_slot)
391 mm_slot->mm = mm;
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))
406 return false;
407 if (shmem_file(vma->vm_file)) {
408 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
409 return false;
410 return IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) - vma->vm_pgoff,
411 HPAGE_PMD_NR);
413 if (!vma->anon_vma || vma->vm_ops)
414 return false;
415 if (is_vma_temporary_stack(vma))
416 return false;
417 return !(vm_flags & VM_NO_KHUGEPAGED);
420 int __khugepaged_enter(struct mm_struct *mm)
422 struct mm_slot *mm_slot;
423 int wakeup;
425 mm_slot = alloc_mm_slot();
426 if (!mm_slot)
427 return -ENOMEM;
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);
433 return 0;
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
440 * down a little.
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);
446 mmgrab(mm);
447 if (wakeup)
448 wake_up_interruptible(&khugepaged_wait);
450 return 0;
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))
463 return 0;
465 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
466 hend = vma->vm_end & HPAGE_PMD_MASK;
467 if (hstart < hend)
468 return khugepaged_enter(vma, vm_flags);
469 return 0;
472 void __khugepaged_exit(struct mm_struct *mm)
474 struct mm_slot *mm_slot;
475 int free = 0;
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);
482 free = 1;
484 spin_unlock(&khugepaged_mm_lock);
486 if (free) {
487 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
488 free_mm_slot(mm_slot);
489 mmdrop(mm);
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));
507 unlock_page(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,
522 pte_t *pte)
524 struct page *page = NULL;
525 pte_t *_pte;
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) {
536 continue;
537 } else {
538 result = SCAN_EXCEED_NONE_PTE;
539 goto out;
542 if (!pte_present(pteval)) {
543 result = SCAN_PTE_NON_PRESENT;
544 goto out;
546 page = vm_normal_page(vma, address, pteval);
547 if (unlikely(!page)) {
548 result = SCAN_PAGE_NULL;
549 goto out;
552 /* TODO: teach khugepaged to collapse THP mapped with pte */
553 if (PageCompound(page)) {
554 result = SCAN_PAGE_COMPOUND;
555 goto out;
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;
568 goto out;
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)) {
577 unlock_page(page);
578 result = SCAN_PAGE_COUNT;
579 goto out;
581 if (pte_write(pteval)) {
582 writable = true;
583 } else {
584 if (PageSwapCache(page) &&
585 !reuse_swap_page(page, NULL)) {
586 unlock_page(page);
587 result = SCAN_SWAP_CACHE_PAGE;
588 goto out;
591 * Page is not in the swap cache. It can be collapsed
592 * into a THP.
597 * Isolate the page to avoid collapsing an hugepage
598 * currently in use by the VM.
600 if (isolate_lru_page(page)) {
601 unlock_page(page);
602 result = SCAN_DEL_PAGE_LRU;
603 goto out;
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))
614 referenced++;
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);
621 return 1;
623 } else {
624 result = SCAN_PAGE_RO;
627 out:
628 release_pte_pages(pte, _pte);
629 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
630 referenced, writable, result);
631 return 0;
634 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
635 struct vm_area_struct *vma,
636 unsigned long address,
637 spinlock_t *ptl)
639 pte_t *_pte;
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.
652 spin_lock(ptl);
654 * paravirt calls inside pte_clear here are
655 * superfluous.
657 pte_clear(vma->vm_mm, address, _pte);
658 spin_unlock(ptl);
660 } else {
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().
670 spin_lock(ptl);
672 * paravirt calls inside pte_clear here are
673 * superfluous.
675 pte_clear(vma->vm_mm, address, _pte);
676 page_remove_rmap(src_page, false);
677 spin_unlock(ptl);
678 free_page_and_swap_cache(src_page);
683 static void khugepaged_alloc_sleep(void)
685 DEFINE_WAIT(wait);
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)
697 int i;
700 * If node_reclaim_mode is disabled, then no extra effort is made to
701 * allocate memory locally.
703 if (!node_reclaim_mode)
704 return false;
706 /* If there is a count for this node already, it must be acceptable */
707 if (khugepaged_node_load[nid])
708 return false;
710 for (i = 0; i < MAX_NUMNODES; i++) {
711 if (!khugepaged_node_load[i])
712 continue;
713 if (node_distance(nid, i) > RECLAIM_DISTANCE)
714 return true;
716 return false;
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;
725 #ifdef CONFIG_NUMA
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];
735 target_node = 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;
741 nid++)
742 if (max_value == khugepaged_node_load[nid]) {
743 target_node = nid;
744 break;
747 last_khugepaged_target_node = target_node;
748 return target_node;
751 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
753 if (IS_ERR(*hpage)) {
754 if (!*wait)
755 return false;
757 *wait = false;
758 *hpage = NULL;
759 khugepaged_alloc_sleep();
760 } else if (*hpage) {
761 put_page(*hpage);
762 *hpage = NULL;
765 return true;
768 static struct page *
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);
777 return NULL;
780 prep_transhuge_page(*hpage);
781 count_vm_event(THP_COLLAPSE_ALLOC);
782 return *hpage;
784 #else
785 static int khugepaged_find_target_node(void)
787 return 0;
790 static inline struct page *alloc_khugepaged_hugepage(void)
792 struct page *page;
794 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
795 HPAGE_PMD_ORDER);
796 if (page)
797 prep_transhuge_page(page);
798 return page;
801 static struct page *khugepaged_alloc_hugepage(bool *wait)
803 struct page *hpage;
805 do {
806 hpage = alloc_khugepaged_hugepage();
807 if (!hpage) {
808 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
809 if (!*wait)
810 return NULL;
812 *wait = false;
813 khugepaged_alloc_sleep();
814 } else
815 count_vm_event(THP_COLLAPSE_ALLOC);
816 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
818 return hpage;
821 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
823 if (!*hpage)
824 *hpage = khugepaged_alloc_hugepage(wait);
826 if (unlikely(!*hpage))
827 return false;
829 return true;
832 static struct page *
833 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
835 VM_BUG_ON(!*hpage);
837 return *hpage;
839 #endif
842 * If mmap_sem temporarily dropped, revalidate vma
843 * before taking mmap_sem.
844 * Return 0 if succeeds, otherwise return none-zero
845 * value (scan code).
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);
858 if (!vma)
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;
867 return 0;
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,
881 int referenced)
883 int swapped_in = 0;
884 vm_fault_t ret = 0;
885 struct vm_fault vmf = {
886 .vma = vma,
887 .address = address,
888 .flags = FAULT_FLAG_ALLOW_RETRY,
889 .pmd = pmd,
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);
896 return false;
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))
903 continue;
904 swapped_in++;
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);
913 return false;
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);
918 return false;
921 if (ret & VM_FAULT_ERROR) {
922 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
923 return false;
925 /* pte is unmapped now, we need to map it */
926 vmf.pte = pte_offset_map(pmd, vmf.address);
928 vmf.pte--;
929 pte_unmap(vmf.pte);
930 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
931 return true;
934 static void collapse_huge_page(struct mm_struct *mm,
935 unsigned long address,
936 struct page **hpage,
937 int node, int referenced)
939 pmd_t *pmd, _pmd;
940 pte_t *pte;
941 pgtable_t pgtable;
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 struct mmu_notifier_range range;
948 gfp_t gfp;
950 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
952 /* Only allocate from the target node */
953 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
956 * Before allocating the hugepage, release the mmap_sem read lock.
957 * The allocation can take potentially a long time if it involves
958 * sync compaction, and we do not need to hold the mmap_sem during
959 * that. We will recheck the vma after taking it again in write mode.
961 up_read(&mm->mmap_sem);
962 new_page = khugepaged_alloc_page(hpage, gfp, node);
963 if (!new_page) {
964 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
965 goto out_nolock;
968 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
969 result = SCAN_CGROUP_CHARGE_FAIL;
970 goto out_nolock;
973 down_read(&mm->mmap_sem);
974 result = hugepage_vma_revalidate(mm, address, &vma);
975 if (result) {
976 mem_cgroup_cancel_charge(new_page, memcg, true);
977 up_read(&mm->mmap_sem);
978 goto out_nolock;
981 pmd = mm_find_pmd(mm, address);
982 if (!pmd) {
983 result = SCAN_PMD_NULL;
984 mem_cgroup_cancel_charge(new_page, memcg, true);
985 up_read(&mm->mmap_sem);
986 goto out_nolock;
990 * __collapse_huge_page_swapin always returns with mmap_sem locked.
991 * If it fails, we release mmap_sem and jump out_nolock.
992 * Continuing to collapse causes inconsistency.
994 if (!__collapse_huge_page_swapin(mm, vma, address, pmd, referenced)) {
995 mem_cgroup_cancel_charge(new_page, memcg, true);
996 up_read(&mm->mmap_sem);
997 goto out_nolock;
1000 up_read(&mm->mmap_sem);
1002 * Prevent all access to pagetables with the exception of
1003 * gup_fast later handled by the ptep_clear_flush and the VM
1004 * handled by the anon_vma lock + PG_lock.
1006 down_write(&mm->mmap_sem);
1007 result = SCAN_ANY_PROCESS;
1008 if (!mmget_still_valid(mm))
1009 goto out;
1010 result = hugepage_vma_revalidate(mm, address, &vma);
1011 if (result)
1012 goto out;
1013 /* check if the pmd is still valid */
1014 if (mm_find_pmd(mm, address) != pmd)
1015 goto out;
1017 anon_vma_lock_write(vma->anon_vma);
1019 pte = pte_offset_map(pmd, address);
1020 pte_ptl = pte_lockptr(mm, pmd);
1022 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1023 address, address + HPAGE_PMD_SIZE);
1024 mmu_notifier_invalidate_range_start(&range);
1025 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1027 * After this gup_fast can't run anymore. This also removes
1028 * any huge TLB entry from the CPU so we won't allow
1029 * huge and small TLB entries for the same virtual address
1030 * to avoid the risk of CPU bugs in that area.
1032 _pmd = pmdp_collapse_flush(vma, address, pmd);
1033 spin_unlock(pmd_ptl);
1034 mmu_notifier_invalidate_range_end(&range);
1036 spin_lock(pte_ptl);
1037 isolated = __collapse_huge_page_isolate(vma, address, pte);
1038 spin_unlock(pte_ptl);
1040 if (unlikely(!isolated)) {
1041 pte_unmap(pte);
1042 spin_lock(pmd_ptl);
1043 BUG_ON(!pmd_none(*pmd));
1045 * We can only use set_pmd_at when establishing
1046 * hugepmds and never for establishing regular pmds that
1047 * points to regular pagetables. Use pmd_populate for that
1049 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1050 spin_unlock(pmd_ptl);
1051 anon_vma_unlock_write(vma->anon_vma);
1052 result = SCAN_FAIL;
1053 goto out;
1057 * All pages are isolated and locked so anon_vma rmap
1058 * can't run anymore.
1060 anon_vma_unlock_write(vma->anon_vma);
1062 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
1063 pte_unmap(pte);
1064 __SetPageUptodate(new_page);
1065 pgtable = pmd_pgtable(_pmd);
1067 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1068 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1071 * spin_lock() below is not the equivalent of smp_wmb(), so
1072 * this is needed to avoid the copy_huge_page writes to become
1073 * visible after the set_pmd_at() write.
1075 smp_wmb();
1077 spin_lock(pmd_ptl);
1078 BUG_ON(!pmd_none(*pmd));
1079 page_add_new_anon_rmap(new_page, vma, address, true);
1080 mem_cgroup_commit_charge(new_page, memcg, false, true);
1081 count_memcg_events(memcg, THP_COLLAPSE_ALLOC, 1);
1082 lru_cache_add_active_or_unevictable(new_page, vma);
1083 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1084 set_pmd_at(mm, address, pmd, _pmd);
1085 update_mmu_cache_pmd(vma, address, pmd);
1086 spin_unlock(pmd_ptl);
1088 *hpage = NULL;
1090 khugepaged_pages_collapsed++;
1091 result = SCAN_SUCCEED;
1092 out_up_write:
1093 up_write(&mm->mmap_sem);
1094 out_nolock:
1095 trace_mm_collapse_huge_page(mm, isolated, result);
1096 return;
1097 out:
1098 mem_cgroup_cancel_charge(new_page, memcg, true);
1099 goto out_up_write;
1102 static int khugepaged_scan_pmd(struct mm_struct *mm,
1103 struct vm_area_struct *vma,
1104 unsigned long address,
1105 struct page **hpage)
1107 pmd_t *pmd;
1108 pte_t *pte, *_pte;
1109 int ret = 0, none_or_zero = 0, result = 0, referenced = 0;
1110 struct page *page = NULL;
1111 unsigned long _address;
1112 spinlock_t *ptl;
1113 int node = NUMA_NO_NODE, unmapped = 0;
1114 bool writable = false;
1116 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1118 pmd = mm_find_pmd(mm, address);
1119 if (!pmd) {
1120 result = SCAN_PMD_NULL;
1121 goto out;
1124 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1125 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1126 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1127 _pte++, _address += PAGE_SIZE) {
1128 pte_t pteval = *_pte;
1129 if (is_swap_pte(pteval)) {
1130 if (++unmapped <= khugepaged_max_ptes_swap) {
1131 continue;
1132 } else {
1133 result = SCAN_EXCEED_SWAP_PTE;
1134 goto out_unmap;
1137 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1138 if (!userfaultfd_armed(vma) &&
1139 ++none_or_zero <= khugepaged_max_ptes_none) {
1140 continue;
1141 } else {
1142 result = SCAN_EXCEED_NONE_PTE;
1143 goto out_unmap;
1146 if (!pte_present(pteval)) {
1147 result = SCAN_PTE_NON_PRESENT;
1148 goto out_unmap;
1150 if (pte_write(pteval))
1151 writable = true;
1153 page = vm_normal_page(vma, _address, pteval);
1154 if (unlikely(!page)) {
1155 result = SCAN_PAGE_NULL;
1156 goto out_unmap;
1159 /* TODO: teach khugepaged to collapse THP mapped with pte */
1160 if (PageCompound(page)) {
1161 result = SCAN_PAGE_COMPOUND;
1162 goto out_unmap;
1166 * Record which node the original page is from and save this
1167 * information to khugepaged_node_load[].
1168 * Khupaged will allocate hugepage from the node has the max
1169 * hit record.
1171 node = page_to_nid(page);
1172 if (khugepaged_scan_abort(node)) {
1173 result = SCAN_SCAN_ABORT;
1174 goto out_unmap;
1176 khugepaged_node_load[node]++;
1177 if (!PageLRU(page)) {
1178 result = SCAN_PAGE_LRU;
1179 goto out_unmap;
1181 if (PageLocked(page)) {
1182 result = SCAN_PAGE_LOCK;
1183 goto out_unmap;
1185 if (!PageAnon(page)) {
1186 result = SCAN_PAGE_ANON;
1187 goto out_unmap;
1191 * cannot use mapcount: can't collapse if there's a gup pin.
1192 * The page must only be referenced by the scanned process
1193 * and page swap cache.
1195 if (page_count(page) != 1 + PageSwapCache(page)) {
1196 result = SCAN_PAGE_COUNT;
1197 goto out_unmap;
1199 if (pte_young(pteval) ||
1200 page_is_young(page) || PageReferenced(page) ||
1201 mmu_notifier_test_young(vma->vm_mm, address))
1202 referenced++;
1204 if (writable) {
1205 if (referenced) {
1206 result = SCAN_SUCCEED;
1207 ret = 1;
1208 } else {
1209 result = SCAN_LACK_REFERENCED_PAGE;
1211 } else {
1212 result = SCAN_PAGE_RO;
1214 out_unmap:
1215 pte_unmap_unlock(pte, ptl);
1216 if (ret) {
1217 node = khugepaged_find_target_node();
1218 /* collapse_huge_page will return with the mmap_sem released */
1219 collapse_huge_page(mm, address, hpage, node, referenced);
1221 out:
1222 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1223 none_or_zero, result, unmapped);
1224 return ret;
1227 static void collect_mm_slot(struct mm_slot *mm_slot)
1229 struct mm_struct *mm = mm_slot->mm;
1231 lockdep_assert_held(&khugepaged_mm_lock);
1233 if (khugepaged_test_exit(mm)) {
1234 /* free mm_slot */
1235 hash_del(&mm_slot->hash);
1236 list_del(&mm_slot->mm_node);
1239 * Not strictly needed because the mm exited already.
1241 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1244 /* khugepaged_mm_lock actually not necessary for the below */
1245 free_mm_slot(mm_slot);
1246 mmdrop(mm);
1250 #if defined(CONFIG_SHMEM) && defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE)
1251 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1253 struct vm_area_struct *vma;
1254 unsigned long addr;
1255 pmd_t *pmd, _pmd;
1257 i_mmap_lock_write(mapping);
1258 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1259 /* probably overkill */
1260 if (vma->anon_vma)
1261 continue;
1262 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1263 if (addr & ~HPAGE_PMD_MASK)
1264 continue;
1265 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1266 continue;
1267 pmd = mm_find_pmd(vma->vm_mm, addr);
1268 if (!pmd)
1269 continue;
1271 * We need exclusive mmap_sem to retract page table.
1272 * If trylock fails we would end up with pte-mapped THP after
1273 * re-fault. Not ideal, but it's more important to not disturb
1274 * the system too much.
1276 if (down_write_trylock(&vma->vm_mm->mmap_sem)) {
1277 spinlock_t *ptl = pmd_lock(vma->vm_mm, pmd);
1278 /* assume page table is clear */
1279 _pmd = pmdp_collapse_flush(vma, addr, pmd);
1280 spin_unlock(ptl);
1281 up_write(&vma->vm_mm->mmap_sem);
1282 mm_dec_nr_ptes(vma->vm_mm);
1283 pte_free(vma->vm_mm, pmd_pgtable(_pmd));
1286 i_mmap_unlock_write(mapping);
1290 * collapse_shmem - collapse small tmpfs/shmem pages into huge one.
1292 * Basic scheme is simple, details are more complex:
1293 * - allocate and lock a new huge page;
1294 * - scan page cache replacing old pages with the new one
1295 * + swap in pages if necessary;
1296 * + fill in gaps;
1297 * + keep old pages around in case rollback is required;
1298 * - if replacing succeeds:
1299 * + copy data over;
1300 * + free old pages;
1301 * + unlock huge page;
1302 * - if replacing failed;
1303 * + put all pages back and unfreeze them;
1304 * + restore gaps in the page cache;
1305 * + unlock and free huge page;
1307 static void collapse_shmem(struct mm_struct *mm,
1308 struct address_space *mapping, pgoff_t start,
1309 struct page **hpage, int node)
1311 gfp_t gfp;
1312 struct page *new_page;
1313 struct mem_cgroup *memcg;
1314 pgoff_t index, end = start + HPAGE_PMD_NR;
1315 LIST_HEAD(pagelist);
1316 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1317 int nr_none = 0, result = SCAN_SUCCEED;
1319 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1321 /* Only allocate from the target node */
1322 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1324 new_page = khugepaged_alloc_page(hpage, gfp, node);
1325 if (!new_page) {
1326 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1327 goto out;
1330 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
1331 result = SCAN_CGROUP_CHARGE_FAIL;
1332 goto out;
1335 /* This will be less messy when we use multi-index entries */
1336 do {
1337 xas_lock_irq(&xas);
1338 xas_create_range(&xas);
1339 if (!xas_error(&xas))
1340 break;
1341 xas_unlock_irq(&xas);
1342 if (!xas_nomem(&xas, GFP_KERNEL)) {
1343 mem_cgroup_cancel_charge(new_page, memcg, true);
1344 result = SCAN_FAIL;
1345 goto out;
1347 } while (1);
1349 __SetPageLocked(new_page);
1350 __SetPageSwapBacked(new_page);
1351 new_page->index = start;
1352 new_page->mapping = mapping;
1355 * At this point the new_page is locked and not up-to-date.
1356 * It's safe to insert it into the page cache, because nobody would
1357 * be able to map it or use it in another way until we unlock it.
1360 xas_set(&xas, start);
1361 for (index = start; index < end; index++) {
1362 struct page *page = xas_next(&xas);
1364 VM_BUG_ON(index != xas.xa_index);
1365 if (!page) {
1367 * Stop if extent has been truncated or hole-punched,
1368 * and is now completely empty.
1370 if (index == start) {
1371 if (!xas_next_entry(&xas, end - 1)) {
1372 result = SCAN_TRUNCATED;
1373 goto xa_locked;
1375 xas_set(&xas, index);
1377 if (!shmem_charge(mapping->host, 1)) {
1378 result = SCAN_FAIL;
1379 goto xa_locked;
1381 xas_store(&xas, new_page + (index % HPAGE_PMD_NR));
1382 nr_none++;
1383 continue;
1386 if (xa_is_value(page) || !PageUptodate(page)) {
1387 xas_unlock_irq(&xas);
1388 /* swap in or instantiate fallocated page */
1389 if (shmem_getpage(mapping->host, index, &page,
1390 SGP_NOHUGE)) {
1391 result = SCAN_FAIL;
1392 goto xa_unlocked;
1394 } else if (trylock_page(page)) {
1395 get_page(page);
1396 xas_unlock_irq(&xas);
1397 } else {
1398 result = SCAN_PAGE_LOCK;
1399 goto xa_locked;
1403 * The page must be locked, so we can drop the i_pages lock
1404 * without racing with truncate.
1406 VM_BUG_ON_PAGE(!PageLocked(page), page);
1407 VM_BUG_ON_PAGE(!PageUptodate(page), page);
1410 * If file was truncated then extended, or hole-punched, before
1411 * we locked the first page, then a THP might be there already.
1413 if (PageTransCompound(page)) {
1414 result = SCAN_PAGE_COMPOUND;
1415 goto out_unlock;
1418 if (page_mapping(page) != mapping) {
1419 result = SCAN_TRUNCATED;
1420 goto out_unlock;
1423 if (isolate_lru_page(page)) {
1424 result = SCAN_DEL_PAGE_LRU;
1425 goto out_unlock;
1428 if (page_mapped(page))
1429 unmap_mapping_pages(mapping, index, 1, false);
1431 xas_lock_irq(&xas);
1432 xas_set(&xas, index);
1434 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1435 VM_BUG_ON_PAGE(page_mapped(page), page);
1438 * The page is expected to have page_count() == 3:
1439 * - we hold a pin on it;
1440 * - one reference from page cache;
1441 * - one from isolate_lru_page;
1443 if (!page_ref_freeze(page, 3)) {
1444 result = SCAN_PAGE_COUNT;
1445 xas_unlock_irq(&xas);
1446 putback_lru_page(page);
1447 goto out_unlock;
1451 * Add the page to the list to be able to undo the collapse if
1452 * something go wrong.
1454 list_add_tail(&page->lru, &pagelist);
1456 /* Finally, replace with the new page. */
1457 xas_store(&xas, new_page + (index % HPAGE_PMD_NR));
1458 continue;
1459 out_unlock:
1460 unlock_page(page);
1461 put_page(page);
1462 goto xa_unlocked;
1465 __inc_node_page_state(new_page, NR_SHMEM_THPS);
1466 if (nr_none) {
1467 struct zone *zone = page_zone(new_page);
1469 __mod_node_page_state(zone->zone_pgdat, NR_FILE_PAGES, nr_none);
1470 __mod_node_page_state(zone->zone_pgdat, NR_SHMEM, nr_none);
1473 xa_locked:
1474 xas_unlock_irq(&xas);
1475 xa_unlocked:
1477 if (result == SCAN_SUCCEED) {
1478 struct page *page, *tmp;
1481 * Replacing old pages with new one has succeeded, now we
1482 * need to copy the content and free the old pages.
1484 index = start;
1485 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1486 while (index < page->index) {
1487 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1488 index++;
1490 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1491 page);
1492 list_del(&page->lru);
1493 page->mapping = NULL;
1494 page_ref_unfreeze(page, 1);
1495 ClearPageActive(page);
1496 ClearPageUnevictable(page);
1497 unlock_page(page);
1498 put_page(page);
1499 index++;
1501 while (index < end) {
1502 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1503 index++;
1506 SetPageUptodate(new_page);
1507 page_ref_add(new_page, HPAGE_PMD_NR - 1);
1508 set_page_dirty(new_page);
1509 mem_cgroup_commit_charge(new_page, memcg, false, true);
1510 count_memcg_events(memcg, THP_COLLAPSE_ALLOC, 1);
1511 lru_cache_add_anon(new_page);
1514 * Remove pte page tables, so we can re-fault the page as huge.
1516 retract_page_tables(mapping, start);
1517 *hpage = NULL;
1519 khugepaged_pages_collapsed++;
1520 } else {
1521 struct page *page;
1523 /* Something went wrong: roll back page cache changes */
1524 xas_lock_irq(&xas);
1525 mapping->nrpages -= nr_none;
1526 shmem_uncharge(mapping->host, nr_none);
1528 xas_set(&xas, start);
1529 xas_for_each(&xas, page, end - 1) {
1530 page = list_first_entry_or_null(&pagelist,
1531 struct page, lru);
1532 if (!page || xas.xa_index < page->index) {
1533 if (!nr_none)
1534 break;
1535 nr_none--;
1536 /* Put holes back where they were */
1537 xas_store(&xas, NULL);
1538 continue;
1541 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1543 /* Unfreeze the page. */
1544 list_del(&page->lru);
1545 page_ref_unfreeze(page, 2);
1546 xas_store(&xas, page);
1547 xas_pause(&xas);
1548 xas_unlock_irq(&xas);
1549 unlock_page(page);
1550 putback_lru_page(page);
1551 xas_lock_irq(&xas);
1553 VM_BUG_ON(nr_none);
1554 xas_unlock_irq(&xas);
1556 mem_cgroup_cancel_charge(new_page, memcg, true);
1557 new_page->mapping = NULL;
1560 unlock_page(new_page);
1561 out:
1562 VM_BUG_ON(!list_empty(&pagelist));
1563 /* TODO: tracepoints */
1566 static void khugepaged_scan_shmem(struct mm_struct *mm,
1567 struct address_space *mapping,
1568 pgoff_t start, struct page **hpage)
1570 struct page *page = NULL;
1571 XA_STATE(xas, &mapping->i_pages, start);
1572 int present, swap;
1573 int node = NUMA_NO_NODE;
1574 int result = SCAN_SUCCEED;
1576 present = 0;
1577 swap = 0;
1578 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1579 rcu_read_lock();
1580 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
1581 if (xas_retry(&xas, page))
1582 continue;
1584 if (xa_is_value(page)) {
1585 if (++swap > khugepaged_max_ptes_swap) {
1586 result = SCAN_EXCEED_SWAP_PTE;
1587 break;
1589 continue;
1592 if (PageTransCompound(page)) {
1593 result = SCAN_PAGE_COMPOUND;
1594 break;
1597 node = page_to_nid(page);
1598 if (khugepaged_scan_abort(node)) {
1599 result = SCAN_SCAN_ABORT;
1600 break;
1602 khugepaged_node_load[node]++;
1604 if (!PageLRU(page)) {
1605 result = SCAN_PAGE_LRU;
1606 break;
1609 if (page_count(page) != 1 + page_mapcount(page)) {
1610 result = SCAN_PAGE_COUNT;
1611 break;
1615 * We probably should check if the page is referenced here, but
1616 * nobody would transfer pte_young() to PageReferenced() for us.
1617 * And rmap walk here is just too costly...
1620 present++;
1622 if (need_resched()) {
1623 xas_pause(&xas);
1624 cond_resched_rcu();
1627 rcu_read_unlock();
1629 if (result == SCAN_SUCCEED) {
1630 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
1631 result = SCAN_EXCEED_NONE_PTE;
1632 } else {
1633 node = khugepaged_find_target_node();
1634 collapse_shmem(mm, mapping, start, hpage, node);
1638 /* TODO: tracepoints */
1640 #else
1641 static void khugepaged_scan_shmem(struct mm_struct *mm,
1642 struct address_space *mapping,
1643 pgoff_t start, struct page **hpage)
1645 BUILD_BUG();
1647 #endif
1649 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
1650 struct page **hpage)
1651 __releases(&khugepaged_mm_lock)
1652 __acquires(&khugepaged_mm_lock)
1654 struct mm_slot *mm_slot;
1655 struct mm_struct *mm;
1656 struct vm_area_struct *vma;
1657 int progress = 0;
1659 VM_BUG_ON(!pages);
1660 lockdep_assert_held(&khugepaged_mm_lock);
1662 if (khugepaged_scan.mm_slot)
1663 mm_slot = khugepaged_scan.mm_slot;
1664 else {
1665 mm_slot = list_entry(khugepaged_scan.mm_head.next,
1666 struct mm_slot, mm_node);
1667 khugepaged_scan.address = 0;
1668 khugepaged_scan.mm_slot = mm_slot;
1670 spin_unlock(&khugepaged_mm_lock);
1672 mm = mm_slot->mm;
1674 * Don't wait for semaphore (to avoid long wait times). Just move to
1675 * the next mm on the list.
1677 vma = NULL;
1678 if (unlikely(!down_read_trylock(&mm->mmap_sem)))
1679 goto breakouterloop_mmap_sem;
1680 if (likely(!khugepaged_test_exit(mm)))
1681 vma = find_vma(mm, khugepaged_scan.address);
1683 progress++;
1684 for (; vma; vma = vma->vm_next) {
1685 unsigned long hstart, hend;
1687 cond_resched();
1688 if (unlikely(khugepaged_test_exit(mm))) {
1689 progress++;
1690 break;
1692 if (!hugepage_vma_check(vma, vma->vm_flags)) {
1693 skip:
1694 progress++;
1695 continue;
1697 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1698 hend = vma->vm_end & HPAGE_PMD_MASK;
1699 if (hstart >= hend)
1700 goto skip;
1701 if (khugepaged_scan.address > hend)
1702 goto skip;
1703 if (khugepaged_scan.address < hstart)
1704 khugepaged_scan.address = hstart;
1705 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
1707 while (khugepaged_scan.address < hend) {
1708 int ret;
1709 cond_resched();
1710 if (unlikely(khugepaged_test_exit(mm)))
1711 goto breakouterloop;
1713 VM_BUG_ON(khugepaged_scan.address < hstart ||
1714 khugepaged_scan.address + HPAGE_PMD_SIZE >
1715 hend);
1716 if (shmem_file(vma->vm_file)) {
1717 struct file *file;
1718 pgoff_t pgoff = linear_page_index(vma,
1719 khugepaged_scan.address);
1720 if (!shmem_huge_enabled(vma))
1721 goto skip;
1722 file = get_file(vma->vm_file);
1723 up_read(&mm->mmap_sem);
1724 ret = 1;
1725 khugepaged_scan_shmem(mm, file->f_mapping,
1726 pgoff, hpage);
1727 fput(file);
1728 } else {
1729 ret = khugepaged_scan_pmd(mm, vma,
1730 khugepaged_scan.address,
1731 hpage);
1733 /* move to next address */
1734 khugepaged_scan.address += HPAGE_PMD_SIZE;
1735 progress += HPAGE_PMD_NR;
1736 if (ret)
1737 /* we released mmap_sem so break loop */
1738 goto breakouterloop_mmap_sem;
1739 if (progress >= pages)
1740 goto breakouterloop;
1743 breakouterloop:
1744 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
1745 breakouterloop_mmap_sem:
1747 spin_lock(&khugepaged_mm_lock);
1748 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
1750 * Release the current mm_slot if this mm is about to die, or
1751 * if we scanned all vmas of this mm.
1753 if (khugepaged_test_exit(mm) || !vma) {
1755 * Make sure that if mm_users is reaching zero while
1756 * khugepaged runs here, khugepaged_exit will find
1757 * mm_slot not pointing to the exiting mm.
1759 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
1760 khugepaged_scan.mm_slot = list_entry(
1761 mm_slot->mm_node.next,
1762 struct mm_slot, mm_node);
1763 khugepaged_scan.address = 0;
1764 } else {
1765 khugepaged_scan.mm_slot = NULL;
1766 khugepaged_full_scans++;
1769 collect_mm_slot(mm_slot);
1772 return progress;
1775 static int khugepaged_has_work(void)
1777 return !list_empty(&khugepaged_scan.mm_head) &&
1778 khugepaged_enabled();
1781 static int khugepaged_wait_event(void)
1783 return !list_empty(&khugepaged_scan.mm_head) ||
1784 kthread_should_stop();
1787 static void khugepaged_do_scan(void)
1789 struct page *hpage = NULL;
1790 unsigned int progress = 0, pass_through_head = 0;
1791 unsigned int pages = khugepaged_pages_to_scan;
1792 bool wait = true;
1794 barrier(); /* write khugepaged_pages_to_scan to local stack */
1796 while (progress < pages) {
1797 if (!khugepaged_prealloc_page(&hpage, &wait))
1798 break;
1800 cond_resched();
1802 if (unlikely(kthread_should_stop() || try_to_freeze()))
1803 break;
1805 spin_lock(&khugepaged_mm_lock);
1806 if (!khugepaged_scan.mm_slot)
1807 pass_through_head++;
1808 if (khugepaged_has_work() &&
1809 pass_through_head < 2)
1810 progress += khugepaged_scan_mm_slot(pages - progress,
1811 &hpage);
1812 else
1813 progress = pages;
1814 spin_unlock(&khugepaged_mm_lock);
1817 if (!IS_ERR_OR_NULL(hpage))
1818 put_page(hpage);
1821 static bool khugepaged_should_wakeup(void)
1823 return kthread_should_stop() ||
1824 time_after_eq(jiffies, khugepaged_sleep_expire);
1827 static void khugepaged_wait_work(void)
1829 if (khugepaged_has_work()) {
1830 const unsigned long scan_sleep_jiffies =
1831 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
1833 if (!scan_sleep_jiffies)
1834 return;
1836 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
1837 wait_event_freezable_timeout(khugepaged_wait,
1838 khugepaged_should_wakeup(),
1839 scan_sleep_jiffies);
1840 return;
1843 if (khugepaged_enabled())
1844 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
1847 static int khugepaged(void *none)
1849 struct mm_slot *mm_slot;
1851 set_freezable();
1852 set_user_nice(current, MAX_NICE);
1854 while (!kthread_should_stop()) {
1855 khugepaged_do_scan();
1856 khugepaged_wait_work();
1859 spin_lock(&khugepaged_mm_lock);
1860 mm_slot = khugepaged_scan.mm_slot;
1861 khugepaged_scan.mm_slot = NULL;
1862 if (mm_slot)
1863 collect_mm_slot(mm_slot);
1864 spin_unlock(&khugepaged_mm_lock);
1865 return 0;
1868 static void set_recommended_min_free_kbytes(void)
1870 struct zone *zone;
1871 int nr_zones = 0;
1872 unsigned long recommended_min;
1874 for_each_populated_zone(zone) {
1876 * We don't need to worry about fragmentation of
1877 * ZONE_MOVABLE since it only has movable pages.
1879 if (zone_idx(zone) > gfp_zone(GFP_USER))
1880 continue;
1882 nr_zones++;
1885 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
1886 recommended_min = pageblock_nr_pages * nr_zones * 2;
1889 * Make sure that on average at least two pageblocks are almost free
1890 * of another type, one for a migratetype to fall back to and a
1891 * second to avoid subsequent fallbacks of other types There are 3
1892 * MIGRATE_TYPES we care about.
1894 recommended_min += pageblock_nr_pages * nr_zones *
1895 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
1897 /* don't ever allow to reserve more than 5% of the lowmem */
1898 recommended_min = min(recommended_min,
1899 (unsigned long) nr_free_buffer_pages() / 20);
1900 recommended_min <<= (PAGE_SHIFT-10);
1902 if (recommended_min > min_free_kbytes) {
1903 if (user_min_free_kbytes >= 0)
1904 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
1905 min_free_kbytes, recommended_min);
1907 min_free_kbytes = recommended_min;
1909 setup_per_zone_wmarks();
1912 int start_stop_khugepaged(void)
1914 static struct task_struct *khugepaged_thread __read_mostly;
1915 static DEFINE_MUTEX(khugepaged_mutex);
1916 int err = 0;
1918 mutex_lock(&khugepaged_mutex);
1919 if (khugepaged_enabled()) {
1920 if (!khugepaged_thread)
1921 khugepaged_thread = kthread_run(khugepaged, NULL,
1922 "khugepaged");
1923 if (IS_ERR(khugepaged_thread)) {
1924 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
1925 err = PTR_ERR(khugepaged_thread);
1926 khugepaged_thread = NULL;
1927 goto fail;
1930 if (!list_empty(&khugepaged_scan.mm_head))
1931 wake_up_interruptible(&khugepaged_wait);
1933 set_recommended_min_free_kbytes();
1934 } else if (khugepaged_thread) {
1935 kthread_stop(khugepaged_thread);
1936 khugepaged_thread = NULL;
1938 fail:
1939 mutex_unlock(&khugepaged_mutex);
1940 return err;