]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - mm/khugepaged.c
mm/sparsemem: fix 'mem_section' will never be NULL gcc 12 warning
[mirror_ubuntu-focal-kernel.git] / mm / khugepaged.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
b46e756f
KS
2#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3
4#include <linux/mm.h>
5#include <linux/sched.h>
6e84f315 6#include <linux/sched/mm.h>
f7ccbae4 7#include <linux/sched/coredump.h>
b46e756f
KS
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>
f3f0e1d2 20#include <linux/shmem_fs.h>
b46e756f
KS
21
22#include <asm/tlb.h>
23#include <asm/pgalloc.h>
24#include "internal.h"
25
26enum 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,
0db501f7 33 SCAN_LACK_REFERENCED_PAGE,
b46e756f
KS
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,
f3f0e1d2
KS
49 SCAN_EXCEED_SWAP_PTE,
50 SCAN_TRUNCATED,
99cb0dbd 51 SCAN_PAGE_HAS_PRIVATE,
b46e756f
KS
52};
53
54#define CREATE_TRACE_POINTS
55#include <trace/events/huge_memory.h>
56
e2c01fd0
VB
57static struct task_struct *khugepaged_thread __read_mostly;
58static DEFINE_MUTEX(khugepaged_mutex);
59
b46e756f
KS
60/* default scan 8*512 pte (or vmas) every 30 second */
61static unsigned int khugepaged_pages_to_scan __read_mostly;
62static unsigned int khugepaged_pages_collapsed;
63static unsigned int khugepaged_full_scans;
64static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
65/* during fragmentation poll the hugepage allocator once every minute */
66static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
67static unsigned long khugepaged_sleep_expire;
68static DEFINE_SPINLOCK(khugepaged_mm_lock);
69static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
70/*
71 * default collapse hugepages if there is at least one pte mapped like
72 * it would have happened if the vma was large enough during page
73 * fault.
74 */
75static unsigned int khugepaged_max_ptes_none __read_mostly;
76static unsigned int khugepaged_max_ptes_swap __read_mostly;
77
78#define MM_SLOTS_HASH_BITS 10
79static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
80
81static struct kmem_cache *mm_slot_cache __read_mostly;
82
27e1f827
SL
83#define MAX_PTE_MAPPED_THP 8
84
b46e756f
KS
85/**
86 * struct mm_slot - hash lookup from mm to mm_slot
87 * @hash: hash collision list
88 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
89 * @mm: the mm that this information is valid for
90 */
91struct mm_slot {
92 struct hlist_node hash;
93 struct list_head mm_node;
94 struct mm_struct *mm;
27e1f827
SL
95
96 /* pte-mapped THP in this mm */
97 int nr_pte_mapped_thp;
98 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
b46e756f
KS
99};
100
101/**
102 * struct khugepaged_scan - cursor for scanning
103 * @mm_head: the head of the mm list to scan
104 * @mm_slot: the current mm_slot we are scanning
105 * @address: the next address inside that to be scanned
106 *
107 * There is only the one khugepaged_scan instance of this cursor structure.
108 */
109struct khugepaged_scan {
110 struct list_head mm_head;
111 struct mm_slot *mm_slot;
112 unsigned long address;
113};
114
115static struct khugepaged_scan khugepaged_scan = {
116 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
117};
118
e1465d12 119#ifdef CONFIG_SYSFS
b46e756f
KS
120static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
121 struct kobj_attribute *attr,
122 char *buf)
123{
124 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
125}
126
127static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
128 struct kobj_attribute *attr,
129 const char *buf, size_t count)
130{
131 unsigned long msecs;
132 int err;
133
134 err = kstrtoul(buf, 10, &msecs);
135 if (err || msecs > UINT_MAX)
136 return -EINVAL;
137
138 khugepaged_scan_sleep_millisecs = msecs;
139 khugepaged_sleep_expire = 0;
140 wake_up_interruptible(&khugepaged_wait);
141
142 return count;
143}
144static struct kobj_attribute scan_sleep_millisecs_attr =
145 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
146 scan_sleep_millisecs_store);
147
148static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
149 struct kobj_attribute *attr,
150 char *buf)
151{
152 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
153}
154
155static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
156 struct kobj_attribute *attr,
157 const char *buf, size_t count)
158{
159 unsigned long msecs;
160 int err;
161
162 err = kstrtoul(buf, 10, &msecs);
163 if (err || msecs > UINT_MAX)
164 return -EINVAL;
165
166 khugepaged_alloc_sleep_millisecs = msecs;
167 khugepaged_sleep_expire = 0;
168 wake_up_interruptible(&khugepaged_wait);
169
170 return count;
171}
172static struct kobj_attribute alloc_sleep_millisecs_attr =
173 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
174 alloc_sleep_millisecs_store);
175
176static ssize_t pages_to_scan_show(struct kobject *kobj,
177 struct kobj_attribute *attr,
178 char *buf)
179{
180 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
181}
182static ssize_t pages_to_scan_store(struct kobject *kobj,
183 struct kobj_attribute *attr,
184 const char *buf, size_t count)
185{
186 int err;
187 unsigned long pages;
188
189 err = kstrtoul(buf, 10, &pages);
190 if (err || !pages || pages > UINT_MAX)
191 return -EINVAL;
192
193 khugepaged_pages_to_scan = pages;
194
195 return count;
196}
197static struct kobj_attribute pages_to_scan_attr =
198 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
199 pages_to_scan_store);
200
201static ssize_t pages_collapsed_show(struct kobject *kobj,
202 struct kobj_attribute *attr,
203 char *buf)
204{
205 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
206}
207static struct kobj_attribute pages_collapsed_attr =
208 __ATTR_RO(pages_collapsed);
209
210static ssize_t full_scans_show(struct kobject *kobj,
211 struct kobj_attribute *attr,
212 char *buf)
213{
214 return sprintf(buf, "%u\n", khugepaged_full_scans);
215}
216static struct kobj_attribute full_scans_attr =
217 __ATTR_RO(full_scans);
218
219static ssize_t khugepaged_defrag_show(struct kobject *kobj,
220 struct kobj_attribute *attr, char *buf)
221{
222 return single_hugepage_flag_show(kobj, attr, buf,
223 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
224}
225static ssize_t khugepaged_defrag_store(struct kobject *kobj,
226 struct kobj_attribute *attr,
227 const char *buf, size_t count)
228{
229 return single_hugepage_flag_store(kobj, attr, buf, count,
230 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
231}
232static struct kobj_attribute khugepaged_defrag_attr =
233 __ATTR(defrag, 0644, khugepaged_defrag_show,
234 khugepaged_defrag_store);
235
236/*
237 * max_ptes_none controls if khugepaged should collapse hugepages over
238 * any unmapped ptes in turn potentially increasing the memory
239 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
240 * reduce the available free memory in the system as it
241 * runs. Increasing max_ptes_none will instead potentially reduce the
242 * free memory in the system during the khugepaged scan.
243 */
244static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
245 struct kobj_attribute *attr,
246 char *buf)
247{
248 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
249}
250static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
251 struct kobj_attribute *attr,
252 const char *buf, size_t count)
253{
254 int err;
255 unsigned long max_ptes_none;
256
257 err = kstrtoul(buf, 10, &max_ptes_none);
258 if (err || max_ptes_none > HPAGE_PMD_NR-1)
259 return -EINVAL;
260
261 khugepaged_max_ptes_none = max_ptes_none;
262
263 return count;
264}
265static struct kobj_attribute khugepaged_max_ptes_none_attr =
266 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
267 khugepaged_max_ptes_none_store);
268
269static ssize_t khugepaged_max_ptes_swap_show(struct kobject *kobj,
270 struct kobj_attribute *attr,
271 char *buf)
272{
273 return sprintf(buf, "%u\n", khugepaged_max_ptes_swap);
274}
275
276static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
277 struct kobj_attribute *attr,
278 const char *buf, size_t count)
279{
280 int err;
281 unsigned long max_ptes_swap;
282
283 err = kstrtoul(buf, 10, &max_ptes_swap);
284 if (err || max_ptes_swap > HPAGE_PMD_NR-1)
285 return -EINVAL;
286
287 khugepaged_max_ptes_swap = max_ptes_swap;
288
289 return count;
290}
291
292static struct kobj_attribute khugepaged_max_ptes_swap_attr =
293 __ATTR(max_ptes_swap, 0644, khugepaged_max_ptes_swap_show,
294 khugepaged_max_ptes_swap_store);
295
296static struct attribute *khugepaged_attr[] = {
297 &khugepaged_defrag_attr.attr,
298 &khugepaged_max_ptes_none_attr.attr,
299 &pages_to_scan_attr.attr,
300 &pages_collapsed_attr.attr,
301 &full_scans_attr.attr,
302 &scan_sleep_millisecs_attr.attr,
303 &alloc_sleep_millisecs_attr.attr,
304 &khugepaged_max_ptes_swap_attr.attr,
305 NULL,
306};
307
308struct attribute_group khugepaged_attr_group = {
309 .attrs = khugepaged_attr,
310 .name = "khugepaged",
311};
e1465d12 312#endif /* CONFIG_SYSFS */
b46e756f 313
f3f0e1d2 314#define VM_NO_KHUGEPAGED (VM_SPECIAL | VM_HUGETLB)
b46e756f
KS
315
316int hugepage_madvise(struct vm_area_struct *vma,
317 unsigned long *vm_flags, int advice)
318{
319 switch (advice) {
320 case MADV_HUGEPAGE:
321#ifdef CONFIG_S390
322 /*
323 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
324 * can't handle this properly after s390_enable_sie, so we simply
325 * ignore the madvise to prevent qemu from causing a SIGSEGV.
326 */
327 if (mm_has_pgste(vma->vm_mm))
328 return 0;
329#endif
330 *vm_flags &= ~VM_NOHUGEPAGE;
331 *vm_flags |= VM_HUGEPAGE;
332 /*
333 * If the vma become good for khugepaged to scan,
334 * register it here without waiting a page fault that
335 * may not happen any time soon.
336 */
337 if (!(*vm_flags & VM_NO_KHUGEPAGED) &&
338 khugepaged_enter_vma_merge(vma, *vm_flags))
339 return -ENOMEM;
340 break;
341 case MADV_NOHUGEPAGE:
342 *vm_flags &= ~VM_HUGEPAGE;
343 *vm_flags |= VM_NOHUGEPAGE;
344 /*
345 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
346 * this vma even if we leave the mm registered in khugepaged if
347 * it got registered before VM_NOHUGEPAGE was set.
348 */
349 break;
350 }
351
352 return 0;
353}
354
355int __init khugepaged_init(void)
356{
357 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
358 sizeof(struct mm_slot),
359 __alignof__(struct mm_slot), 0, NULL);
360 if (!mm_slot_cache)
361 return -ENOMEM;
362
363 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
364 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
365 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
366
367 return 0;
368}
369
370void __init khugepaged_destroy(void)
371{
372 kmem_cache_destroy(mm_slot_cache);
373}
374
375static inline struct mm_slot *alloc_mm_slot(void)
376{
377 if (!mm_slot_cache) /* initialization failed */
378 return NULL;
379 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
380}
381
382static inline void free_mm_slot(struct mm_slot *mm_slot)
383{
384 kmem_cache_free(mm_slot_cache, mm_slot);
385}
386
387static struct mm_slot *get_mm_slot(struct mm_struct *mm)
388{
389 struct mm_slot *mm_slot;
390
391 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
392 if (mm == mm_slot->mm)
393 return mm_slot;
394
395 return NULL;
396}
397
398static void insert_to_mm_slots_hash(struct mm_struct *mm,
399 struct mm_slot *mm_slot)
400{
401 mm_slot->mm = mm;
402 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
403}
404
405static inline int khugepaged_test_exit(struct mm_struct *mm)
406{
05592859 407 return atomic_read(&mm->mm_users) == 0 || !mmget_still_valid(mm);
b46e756f
KS
408}
409
50f8b92f
SL
410static bool hugepage_vma_check(struct vm_area_struct *vma,
411 unsigned long vm_flags)
c2231020 412{
50f8b92f
SL
413 if ((!(vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
414 (vm_flags & VM_NOHUGEPAGE) ||
c2231020
YS
415 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
416 return false;
99cb0dbd
SL
417
418 if (shmem_file(vma->vm_file) ||
419 (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
420 vma->vm_file &&
421 (vm_flags & VM_DENYWRITE))) {
c2231020
YS
422 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
423 return false;
424 return IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) - vma->vm_pgoff,
425 HPAGE_PMD_NR);
426 }
427 if (!vma->anon_vma || vma->vm_ops)
428 return false;
429 if (is_vma_temporary_stack(vma))
430 return false;
50f8b92f 431 return !(vm_flags & VM_NO_KHUGEPAGED);
c2231020
YS
432}
433
b46e756f
KS
434int __khugepaged_enter(struct mm_struct *mm)
435{
436 struct mm_slot *mm_slot;
437 int wakeup;
438
439 mm_slot = alloc_mm_slot();
440 if (!mm_slot)
441 return -ENOMEM;
442
443 /* __khugepaged_exit() must not run from under us */
db919cd0 444 VM_BUG_ON_MM(atomic_read(&mm->mm_users) == 0, mm);
b46e756f
KS
445 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
446 free_mm_slot(mm_slot);
447 return 0;
448 }
449
450 spin_lock(&khugepaged_mm_lock);
451 insert_to_mm_slots_hash(mm, mm_slot);
452 /*
453 * Insert just behind the scanning cursor, to let the area settle
454 * down a little.
455 */
456 wakeup = list_empty(&khugepaged_scan.mm_head);
457 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
458 spin_unlock(&khugepaged_mm_lock);
459
f1f10076 460 mmgrab(mm);
b46e756f
KS
461 if (wakeup)
462 wake_up_interruptible(&khugepaged_wait);
463
464 return 0;
465}
466
467int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
468 unsigned long vm_flags)
469{
470 unsigned long hstart, hend;
c2231020
YS
471
472 /*
99cb0dbd
SL
473 * khugepaged only supports read-only files for non-shmem files.
474 * khugepaged does not yet work on special mappings. And
475 * file-private shmem THP is not supported.
c2231020 476 */
50f8b92f 477 if (!hugepage_vma_check(vma, vm_flags))
b46e756f 478 return 0;
c2231020 479
b46e756f
KS
480 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
481 hend = vma->vm_end & HPAGE_PMD_MASK;
482 if (hstart < hend)
483 return khugepaged_enter(vma, vm_flags);
484 return 0;
485}
486
487void __khugepaged_exit(struct mm_struct *mm)
488{
489 struct mm_slot *mm_slot;
490 int free = 0;
491
492 spin_lock(&khugepaged_mm_lock);
493 mm_slot = get_mm_slot(mm);
494 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
495 hash_del(&mm_slot->hash);
496 list_del(&mm_slot->mm_node);
497 free = 1;
498 }
499 spin_unlock(&khugepaged_mm_lock);
500
501 if (free) {
502 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
503 free_mm_slot(mm_slot);
504 mmdrop(mm);
505 } else if (mm_slot) {
506 /*
507 * This is required to serialize against
508 * khugepaged_test_exit() (which is guaranteed to run
509 * under mmap sem read mode). Stop here (after we
510 * return all pagetables will be destroyed) until
511 * khugepaged has finished working on the pagetables
512 * under the mmap_sem.
513 */
514 down_write(&mm->mmap_sem);
515 up_write(&mm->mmap_sem);
516 }
517}
518
519static void release_pte_page(struct page *page)
520{
d44d363f 521 dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
b46e756f
KS
522 unlock_page(page);
523 putback_lru_page(page);
524}
525
526static void release_pte_pages(pte_t *pte, pte_t *_pte)
527{
528 while (--_pte >= pte) {
529 pte_t pteval = *_pte;
530 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
531 release_pte_page(pte_page(pteval));
532 }
533}
534
535static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
536 unsigned long address,
537 pte_t *pte)
538{
539 struct page *page = NULL;
540 pte_t *_pte;
0db501f7
EA
541 int none_or_zero = 0, result = 0, referenced = 0;
542 bool writable = false;
b46e756f
KS
543
544 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
545 _pte++, address += PAGE_SIZE) {
546 pte_t pteval = *_pte;
547 if (pte_none(pteval) || (pte_present(pteval) &&
548 is_zero_pfn(pte_pfn(pteval)))) {
549 if (!userfaultfd_armed(vma) &&
550 ++none_or_zero <= khugepaged_max_ptes_none) {
551 continue;
552 } else {
553 result = SCAN_EXCEED_NONE_PTE;
554 goto out;
555 }
556 }
557 if (!pte_present(pteval)) {
558 result = SCAN_PTE_NON_PRESENT;
559 goto out;
560 }
561 page = vm_normal_page(vma, address, pteval);
562 if (unlikely(!page)) {
563 result = SCAN_PAGE_NULL;
564 goto out;
565 }
566
fece2029
KS
567 /* TODO: teach khugepaged to collapse THP mapped with pte */
568 if (PageCompound(page)) {
569 result = SCAN_PAGE_COMPOUND;
570 goto out;
571 }
572
b46e756f 573 VM_BUG_ON_PAGE(!PageAnon(page), page);
b46e756f
KS
574
575 /*
576 * We can do it before isolate_lru_page because the
577 * page can't be freed from under us. NOTE: PG_lock
578 * is needed to serialize against split_huge_page
579 * when invoked from the VM.
580 */
581 if (!trylock_page(page)) {
582 result = SCAN_PAGE_LOCK;
583 goto out;
584 }
585
586 /*
587 * cannot use mapcount: can't collapse if there's a gup pin.
588 * The page must only be referenced by the scanned process
589 * and page swap cache.
590 */
2948be5a 591 if (page_count(page) != 1 + PageSwapCache(page)) {
b46e756f
KS
592 unlock_page(page);
593 result = SCAN_PAGE_COUNT;
594 goto out;
595 }
596 if (pte_write(pteval)) {
597 writable = true;
598 } else {
599 if (PageSwapCache(page) &&
600 !reuse_swap_page(page, NULL)) {
601 unlock_page(page);
602 result = SCAN_SWAP_CACHE_PAGE;
603 goto out;
604 }
605 /*
606 * Page is not in the swap cache. It can be collapsed
607 * into a THP.
608 */
609 }
610
611 /*
612 * Isolate the page to avoid collapsing an hugepage
613 * currently in use by the VM.
614 */
615 if (isolate_lru_page(page)) {
616 unlock_page(page);
617 result = SCAN_DEL_PAGE_LRU;
618 goto out;
619 }
d44d363f
SL
620 inc_node_page_state(page,
621 NR_ISOLATED_ANON + page_is_file_cache(page));
b46e756f
KS
622 VM_BUG_ON_PAGE(!PageLocked(page), page);
623 VM_BUG_ON_PAGE(PageLRU(page), page);
624
0db501f7 625 /* There should be enough young pte to collapse the page */
b46e756f
KS
626 if (pte_young(pteval) ||
627 page_is_young(page) || PageReferenced(page) ||
628 mmu_notifier_test_young(vma->vm_mm, address))
0db501f7 629 referenced++;
b46e756f 630 }
87a1f0f0
ML
631
632 if (unlikely(!writable)) {
b46e756f 633 result = SCAN_PAGE_RO;
87a1f0f0
ML
634 } else if (unlikely(!referenced)) {
635 result = SCAN_LACK_REFERENCED_PAGE;
636 } else {
637 result = SCAN_SUCCEED;
638 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
639 referenced, writable, result);
640 return 1;
b46e756f 641 }
b46e756f
KS
642out:
643 release_pte_pages(pte, _pte);
644 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
645 referenced, writable, result);
646 return 0;
647}
648
649static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
650 struct vm_area_struct *vma,
651 unsigned long address,
652 spinlock_t *ptl)
653{
654 pte_t *_pte;
338a16ba
DR
655 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
656 _pte++, page++, address += PAGE_SIZE) {
b46e756f
KS
657 pte_t pteval = *_pte;
658 struct page *src_page;
659
660 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
661 clear_user_highpage(page, address);
662 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
663 if (is_zero_pfn(pte_pfn(pteval))) {
664 /*
665 * ptl mostly unnecessary.
666 */
667 spin_lock(ptl);
668 /*
669 * paravirt calls inside pte_clear here are
670 * superfluous.
671 */
672 pte_clear(vma->vm_mm, address, _pte);
673 spin_unlock(ptl);
674 }
675 } else {
676 src_page = pte_page(pteval);
677 copy_user_highpage(page, src_page, address, vma);
678 VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
679 release_pte_page(src_page);
680 /*
681 * ptl mostly unnecessary, but preempt has to
682 * be disabled to update the per-cpu stats
683 * inside page_remove_rmap().
684 */
685 spin_lock(ptl);
686 /*
687 * paravirt calls inside pte_clear here are
688 * superfluous.
689 */
690 pte_clear(vma->vm_mm, address, _pte);
691 page_remove_rmap(src_page, false);
692 spin_unlock(ptl);
693 free_page_and_swap_cache(src_page);
694 }
b46e756f
KS
695 }
696}
697
698static void khugepaged_alloc_sleep(void)
699{
700 DEFINE_WAIT(wait);
701
702 add_wait_queue(&khugepaged_wait, &wait);
703 freezable_schedule_timeout_interruptible(
704 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
705 remove_wait_queue(&khugepaged_wait, &wait);
706}
707
708static int khugepaged_node_load[MAX_NUMNODES];
709
710static bool khugepaged_scan_abort(int nid)
711{
712 int i;
713
714 /*
a5f5f91d 715 * If node_reclaim_mode is disabled, then no extra effort is made to
b46e756f
KS
716 * allocate memory locally.
717 */
a5f5f91d 718 if (!node_reclaim_mode)
b46e756f
KS
719 return false;
720
721 /* If there is a count for this node already, it must be acceptable */
722 if (khugepaged_node_load[nid])
723 return false;
724
725 for (i = 0; i < MAX_NUMNODES; i++) {
726 if (!khugepaged_node_load[i])
727 continue;
a55c7454 728 if (node_distance(nid, i) > node_reclaim_distance)
b46e756f
KS
729 return true;
730 }
731 return false;
732}
733
734/* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
735static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
736{
25160354 737 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
b46e756f
KS
738}
739
740#ifdef CONFIG_NUMA
741static int khugepaged_find_target_node(void)
742{
743 static int last_khugepaged_target_node = NUMA_NO_NODE;
744 int nid, target_node = 0, max_value = 0;
745
746 /* find first node with max normal pages hit */
747 for (nid = 0; nid < MAX_NUMNODES; nid++)
748 if (khugepaged_node_load[nid] > max_value) {
749 max_value = khugepaged_node_load[nid];
750 target_node = nid;
751 }
752
753 /* do some balance if several nodes have the same hit record */
754 if (target_node <= last_khugepaged_target_node)
755 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
756 nid++)
757 if (max_value == khugepaged_node_load[nid]) {
758 target_node = nid;
759 break;
760 }
761
762 last_khugepaged_target_node = target_node;
763 return target_node;
764}
765
766static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
767{
768 if (IS_ERR(*hpage)) {
769 if (!*wait)
770 return false;
771
772 *wait = false;
773 *hpage = NULL;
774 khugepaged_alloc_sleep();
775 } else if (*hpage) {
776 put_page(*hpage);
777 *hpage = NULL;
778 }
779
780 return true;
781}
782
783static struct page *
988ddb71 784khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
b46e756f
KS
785{
786 VM_BUG_ON_PAGE(*hpage, *hpage);
787
b46e756f
KS
788 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
789 if (unlikely(!*hpage)) {
790 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
791 *hpage = ERR_PTR(-ENOMEM);
792 return NULL;
793 }
794
795 prep_transhuge_page(*hpage);
796 count_vm_event(THP_COLLAPSE_ALLOC);
797 return *hpage;
798}
799#else
800static int khugepaged_find_target_node(void)
801{
802 return 0;
803}
804
805static inline struct page *alloc_khugepaged_hugepage(void)
806{
807 struct page *page;
808
809 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
810 HPAGE_PMD_ORDER);
811 if (page)
812 prep_transhuge_page(page);
813 return page;
814}
815
816static struct page *khugepaged_alloc_hugepage(bool *wait)
817{
818 struct page *hpage;
819
820 do {
821 hpage = alloc_khugepaged_hugepage();
822 if (!hpage) {
823 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
824 if (!*wait)
825 return NULL;
826
827 *wait = false;
828 khugepaged_alloc_sleep();
829 } else
830 count_vm_event(THP_COLLAPSE_ALLOC);
831 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
832
833 return hpage;
834}
835
836static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
837{
65acc81d
HD
838 /*
839 * If the hpage allocated earlier was briefly exposed in page cache
840 * before collapse_file() failed, it is possible that racing lookups
841 * have not yet completed, and would then be unpleasantly surprised by
842 * finding the hpage reused for the same mapping at a different offset.
843 * Just release the previous allocation if there is any danger of that.
844 */
845 if (*hpage && page_count(*hpage) > 1) {
846 put_page(*hpage);
847 *hpage = NULL;
848 }
849
b46e756f
KS
850 if (!*hpage)
851 *hpage = khugepaged_alloc_hugepage(wait);
852
853 if (unlikely(!*hpage))
854 return false;
855
856 return true;
857}
858
859static struct page *
988ddb71 860khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
b46e756f 861{
b46e756f
KS
862 VM_BUG_ON(!*hpage);
863
864 return *hpage;
865}
866#endif
867
b46e756f
KS
868/*
869 * If mmap_sem temporarily dropped, revalidate vma
870 * before taking mmap_sem.
871 * Return 0 if succeeds, otherwise return none-zero
872 * value (scan code).
873 */
874
c131f751
KS
875static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
876 struct vm_area_struct **vmap)
b46e756f
KS
877{
878 struct vm_area_struct *vma;
879 unsigned long hstart, hend;
880
881 if (unlikely(khugepaged_test_exit(mm)))
882 return SCAN_ANY_PROCESS;
883
c131f751 884 *vmap = vma = find_vma(mm, address);
b46e756f
KS
885 if (!vma)
886 return SCAN_VMA_NULL;
887
888 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
889 hend = vma->vm_end & HPAGE_PMD_MASK;
890 if (address < hstart || address + HPAGE_PMD_SIZE > hend)
891 return SCAN_ADDRESS_RANGE;
50f8b92f 892 if (!hugepage_vma_check(vma, vma->vm_flags))
b46e756f 893 return SCAN_VMA_CHECK;
538689b7
KS
894 /* Anon VMA expected */
895 if (!vma->anon_vma || vma->vm_ops)
896 return SCAN_VMA_CHECK;
b46e756f
KS
897 return 0;
898}
899
900/*
901 * Bring missing pages in from swap, to complete THP collapse.
902 * Only done if khugepaged_scan_pmd believes it is worthwhile.
903 *
904 * Called and returns without pte mapped or spinlocks held,
905 * but with mmap_sem held to protect against vma changes.
906 */
907
908static bool __collapse_huge_page_swapin(struct mm_struct *mm,
909 struct vm_area_struct *vma,
0db501f7
EA
910 unsigned long address, pmd_t *pmd,
911 int referenced)
b46e756f 912{
2b740303
SJ
913 int swapped_in = 0;
914 vm_fault_t ret = 0;
82b0f8c3 915 struct vm_fault vmf = {
b46e756f
KS
916 .vma = vma,
917 .address = address,
918 .flags = FAULT_FLAG_ALLOW_RETRY,
919 .pmd = pmd,
0721ec8b 920 .pgoff = linear_page_index(vma, address),
b46e756f
KS
921 };
922
982785c6
EA
923 /* we only decide to swapin, if there is enough young ptes */
924 if (referenced < HPAGE_PMD_NR/2) {
925 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
926 return false;
927 }
82b0f8c3
JK
928 vmf.pte = pte_offset_map(pmd, address);
929 for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
930 vmf.pte++, vmf.address += PAGE_SIZE) {
2994302b
JK
931 vmf.orig_pte = *vmf.pte;
932 if (!is_swap_pte(vmf.orig_pte))
b46e756f
KS
933 continue;
934 swapped_in++;
2994302b 935 ret = do_swap_page(&vmf);
0db501f7 936
b46e756f
KS
937 /* do_swap_page returns VM_FAULT_RETRY with released mmap_sem */
938 if (ret & VM_FAULT_RETRY) {
939 down_read(&mm->mmap_sem);
82b0f8c3 940 if (hugepage_vma_revalidate(mm, address, &vmf.vma)) {
47f863ea 941 /* vma is no longer available, don't continue to swapin */
0db501f7 942 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
b46e756f 943 return false;
47f863ea 944 }
b46e756f 945 /* check if the pmd is still valid */
835152a2
SP
946 if (mm_find_pmd(mm, address) != pmd) {
947 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
b46e756f 948 return false;
835152a2 949 }
b46e756f
KS
950 }
951 if (ret & VM_FAULT_ERROR) {
0db501f7 952 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
b46e756f
KS
953 return false;
954 }
955 /* pte is unmapped now, we need to map it */
82b0f8c3 956 vmf.pte = pte_offset_map(pmd, vmf.address);
b46e756f 957 }
82b0f8c3
JK
958 vmf.pte--;
959 pte_unmap(vmf.pte);
0db501f7 960 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
b46e756f
KS
961 return true;
962}
963
964static void collapse_huge_page(struct mm_struct *mm,
965 unsigned long address,
966 struct page **hpage,
0db501f7 967 int node, int referenced)
b46e756f
KS
968{
969 pmd_t *pmd, _pmd;
970 pte_t *pte;
971 pgtable_t pgtable;
972 struct page *new_page;
973 spinlock_t *pmd_ptl, *pte_ptl;
974 int isolated = 0, result = 0;
975 struct mem_cgroup *memcg;
c131f751 976 struct vm_area_struct *vma;
ac46d4f3 977 struct mmu_notifier_range range;
b46e756f
KS
978 gfp_t gfp;
979
980 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
981
982 /* Only allocate from the target node */
41b6167e 983 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
b46e756f 984
988ddb71
KS
985 /*
986 * Before allocating the hugepage, release the mmap_sem read lock.
987 * The allocation can take potentially a long time if it involves
988 * sync compaction, and we do not need to hold the mmap_sem during
989 * that. We will recheck the vma after taking it again in write mode.
990 */
991 up_read(&mm->mmap_sem);
992 new_page = khugepaged_alloc_page(hpage, gfp, node);
b46e756f
KS
993 if (!new_page) {
994 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
995 goto out_nolock;
996 }
997
2a70f6a7 998 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
b46e756f
KS
999 result = SCAN_CGROUP_CHARGE_FAIL;
1000 goto out_nolock;
1001 }
1002
1003 down_read(&mm->mmap_sem);
c131f751 1004 result = hugepage_vma_revalidate(mm, address, &vma);
b46e756f
KS
1005 if (result) {
1006 mem_cgroup_cancel_charge(new_page, memcg, true);
1007 up_read(&mm->mmap_sem);
1008 goto out_nolock;
1009 }
1010
1011 pmd = mm_find_pmd(mm, address);
1012 if (!pmd) {
1013 result = SCAN_PMD_NULL;
1014 mem_cgroup_cancel_charge(new_page, memcg, true);
1015 up_read(&mm->mmap_sem);
1016 goto out_nolock;
1017 }
1018
1019 /*
1020 * __collapse_huge_page_swapin always returns with mmap_sem locked.
47f863ea 1021 * If it fails, we release mmap_sem and jump out_nolock.
b46e756f
KS
1022 * Continuing to collapse causes inconsistency.
1023 */
0db501f7 1024 if (!__collapse_huge_page_swapin(mm, vma, address, pmd, referenced)) {
b46e756f
KS
1025 mem_cgroup_cancel_charge(new_page, memcg, true);
1026 up_read(&mm->mmap_sem);
1027 goto out_nolock;
1028 }
1029
1030 up_read(&mm->mmap_sem);
1031 /*
1032 * Prevent all access to pagetables with the exception of
1033 * gup_fast later handled by the ptep_clear_flush and the VM
1034 * handled by the anon_vma lock + PG_lock.
1035 */
1036 down_write(&mm->mmap_sem);
c131f751 1037 result = hugepage_vma_revalidate(mm, address, &vma);
b46e756f
KS
1038 if (result)
1039 goto out;
1040 /* check if the pmd is still valid */
1041 if (mm_find_pmd(mm, address) != pmd)
1042 goto out;
1043
1044 anon_vma_lock_write(vma->anon_vma);
1045
7269f999 1046 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
6f4f13e8 1047 address, address + HPAGE_PMD_SIZE);
ac46d4f3 1048 mmu_notifier_invalidate_range_start(&range);
ec649c9d
VS
1049
1050 pte = pte_offset_map(pmd, address);
1051 pte_ptl = pte_lockptr(mm, pmd);
1052
b46e756f
KS
1053 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1054 /*
1055 * After this gup_fast can't run anymore. This also removes
1056 * any huge TLB entry from the CPU so we won't allow
1057 * huge and small TLB entries for the same virtual address
1058 * to avoid the risk of CPU bugs in that area.
1059 */
1060 _pmd = pmdp_collapse_flush(vma, address, pmd);
1061 spin_unlock(pmd_ptl);
ac46d4f3 1062 mmu_notifier_invalidate_range_end(&range);
b46e756f
KS
1063
1064 spin_lock(pte_ptl);
1065 isolated = __collapse_huge_page_isolate(vma, address, pte);
1066 spin_unlock(pte_ptl);
1067
1068 if (unlikely(!isolated)) {
1069 pte_unmap(pte);
1070 spin_lock(pmd_ptl);
1071 BUG_ON(!pmd_none(*pmd));
1072 /*
1073 * We can only use set_pmd_at when establishing
1074 * hugepmds and never for establishing regular pmds that
1075 * points to regular pagetables. Use pmd_populate for that
1076 */
1077 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1078 spin_unlock(pmd_ptl);
1079 anon_vma_unlock_write(vma->anon_vma);
1080 result = SCAN_FAIL;
1081 goto out;
1082 }
1083
1084 /*
1085 * All pages are isolated and locked so anon_vma rmap
1086 * can't run anymore.
1087 */
1088 anon_vma_unlock_write(vma->anon_vma);
1089
1090 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
1091 pte_unmap(pte);
1092 __SetPageUptodate(new_page);
1093 pgtable = pmd_pgtable(_pmd);
1094
1095 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
f55e1014 1096 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
b46e756f
KS
1097
1098 /*
1099 * spin_lock() below is not the equivalent of smp_wmb(), so
1100 * this is needed to avoid the copy_huge_page writes to become
1101 * visible after the set_pmd_at() write.
1102 */
1103 smp_wmb();
1104
1105 spin_lock(pmd_ptl);
1106 BUG_ON(!pmd_none(*pmd));
1107 page_add_new_anon_rmap(new_page, vma, address, true);
1108 mem_cgroup_commit_charge(new_page, memcg, false, true);
1ff9e6e1 1109 count_memcg_events(memcg, THP_COLLAPSE_ALLOC, 1);
b46e756f
KS
1110 lru_cache_add_active_or_unevictable(new_page, vma);
1111 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1112 set_pmd_at(mm, address, pmd, _pmd);
1113 update_mmu_cache_pmd(vma, address, pmd);
1114 spin_unlock(pmd_ptl);
1115
1116 *hpage = NULL;
1117
1118 khugepaged_pages_collapsed++;
1119 result = SCAN_SUCCEED;
1120out_up_write:
1121 up_write(&mm->mmap_sem);
1122out_nolock:
1123 trace_mm_collapse_huge_page(mm, isolated, result);
1124 return;
1125out:
1126 mem_cgroup_cancel_charge(new_page, memcg, true);
1127 goto out_up_write;
1128}
1129
1130static int khugepaged_scan_pmd(struct mm_struct *mm,
1131 struct vm_area_struct *vma,
1132 unsigned long address,
1133 struct page **hpage)
1134{
1135 pmd_t *pmd;
1136 pte_t *pte, *_pte;
0db501f7 1137 int ret = 0, none_or_zero = 0, result = 0, referenced = 0;
b46e756f
KS
1138 struct page *page = NULL;
1139 unsigned long _address;
1140 spinlock_t *ptl;
1141 int node = NUMA_NO_NODE, unmapped = 0;
0db501f7 1142 bool writable = false;
b46e756f
KS
1143
1144 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1145
1146 pmd = mm_find_pmd(mm, address);
1147 if (!pmd) {
1148 result = SCAN_PMD_NULL;
1149 goto out;
1150 }
1151
1152 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1153 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1154 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1155 _pte++, _address += PAGE_SIZE) {
1156 pte_t pteval = *_pte;
1157 if (is_swap_pte(pteval)) {
1158 if (++unmapped <= khugepaged_max_ptes_swap) {
1159 continue;
1160 } else {
1161 result = SCAN_EXCEED_SWAP_PTE;
1162 goto out_unmap;
1163 }
1164 }
1165 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1166 if (!userfaultfd_armed(vma) &&
1167 ++none_or_zero <= khugepaged_max_ptes_none) {
1168 continue;
1169 } else {
1170 result = SCAN_EXCEED_NONE_PTE;
1171 goto out_unmap;
1172 }
1173 }
1174 if (!pte_present(pteval)) {
1175 result = SCAN_PTE_NON_PRESENT;
1176 goto out_unmap;
1177 }
1178 if (pte_write(pteval))
1179 writable = true;
1180
1181 page = vm_normal_page(vma, _address, pteval);
1182 if (unlikely(!page)) {
1183 result = SCAN_PAGE_NULL;
1184 goto out_unmap;
1185 }
1186
1187 /* TODO: teach khugepaged to collapse THP mapped with pte */
1188 if (PageCompound(page)) {
1189 result = SCAN_PAGE_COMPOUND;
1190 goto out_unmap;
1191 }
1192
1193 /*
1194 * Record which node the original page is from and save this
1195 * information to khugepaged_node_load[].
1196 * Khupaged will allocate hugepage from the node has the max
1197 * hit record.
1198 */
1199 node = page_to_nid(page);
1200 if (khugepaged_scan_abort(node)) {
1201 result = SCAN_SCAN_ABORT;
1202 goto out_unmap;
1203 }
1204 khugepaged_node_load[node]++;
1205 if (!PageLRU(page)) {
1206 result = SCAN_PAGE_LRU;
1207 goto out_unmap;
1208 }
1209 if (PageLocked(page)) {
1210 result = SCAN_PAGE_LOCK;
1211 goto out_unmap;
1212 }
1213 if (!PageAnon(page)) {
1214 result = SCAN_PAGE_ANON;
1215 goto out_unmap;
1216 }
1217
1218 /*
1219 * cannot use mapcount: can't collapse if there's a gup pin.
1220 * The page must only be referenced by the scanned process
1221 * and page swap cache.
1222 */
2948be5a 1223 if (page_count(page) != 1 + PageSwapCache(page)) {
b46e756f
KS
1224 result = SCAN_PAGE_COUNT;
1225 goto out_unmap;
1226 }
1227 if (pte_young(pteval) ||
1228 page_is_young(page) || PageReferenced(page) ||
1229 mmu_notifier_test_young(vma->vm_mm, address))
0db501f7 1230 referenced++;
b46e756f
KS
1231 }
1232 if (writable) {
1233 if (referenced) {
1234 result = SCAN_SUCCEED;
1235 ret = 1;
1236 } else {
0db501f7 1237 result = SCAN_LACK_REFERENCED_PAGE;
b46e756f
KS
1238 }
1239 } else {
1240 result = SCAN_PAGE_RO;
1241 }
1242out_unmap:
1243 pte_unmap_unlock(pte, ptl);
1244 if (ret) {
1245 node = khugepaged_find_target_node();
1246 /* collapse_huge_page will return with the mmap_sem released */
c131f751 1247 collapse_huge_page(mm, address, hpage, node, referenced);
b46e756f
KS
1248 }
1249out:
1250 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1251 none_or_zero, result, unmapped);
1252 return ret;
1253}
1254
1255static void collect_mm_slot(struct mm_slot *mm_slot)
1256{
1257 struct mm_struct *mm = mm_slot->mm;
1258
35f3aa39 1259 lockdep_assert_held(&khugepaged_mm_lock);
b46e756f
KS
1260
1261 if (khugepaged_test_exit(mm)) {
1262 /* free mm_slot */
1263 hash_del(&mm_slot->hash);
1264 list_del(&mm_slot->mm_node);
1265
1266 /*
1267 * Not strictly needed because the mm exited already.
1268 *
1269 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1270 */
1271
1272 /* khugepaged_mm_lock actually not necessary for the below */
1273 free_mm_slot(mm_slot);
1274 mmdrop(mm);
1275 }
1276}
1277
e496cf3d 1278#if defined(CONFIG_SHMEM) && defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE)
27e1f827
SL
1279/*
1280 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1281 * khugepaged should try to collapse the page table.
1282 */
1283static int khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1284 unsigned long addr)
1285{
1286 struct mm_slot *mm_slot;
1287
1288 VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1289
1290 spin_lock(&khugepaged_mm_lock);
1291 mm_slot = get_mm_slot(mm);
1292 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
1293 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1294 spin_unlock(&khugepaged_mm_lock);
1295 return 0;
1296}
1297
1298/**
1299 * Try to collapse a pte-mapped THP for mm at address haddr.
1300 *
1301 * This function checks whether all the PTEs in the PMD are pointing to the
1302 * right THP. If so, retract the page table so the THP can refault in with
1303 * as pmd-mapped.
1304 */
1305void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
1306{
1307 unsigned long haddr = addr & HPAGE_PMD_MASK;
1308 struct vm_area_struct *vma = find_vma(mm, haddr);
4a9892d7 1309 struct page *hpage;
27e1f827
SL
1310 pte_t *start_pte, *pte;
1311 pmd_t *pmd, _pmd;
1312 spinlock_t *ptl;
1313 int count = 0;
1314 int i;
1315
1316 if (!vma || !vma->vm_file ||
1317 vma->vm_start > haddr || vma->vm_end < haddr + HPAGE_PMD_SIZE)
1318 return;
1319
1320 /*
1321 * This vm_flags may not have VM_HUGEPAGE if the page was not
1322 * collapsed by this mm. But we can still collapse if the page is
1323 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
1324 * will not fail the vma for missing VM_HUGEPAGE
1325 */
1326 if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE))
1327 return;
1328
4a9892d7
HD
1329 hpage = find_lock_page(vma->vm_file->f_mapping,
1330 linear_page_index(vma, haddr));
1331 if (!hpage)
1332 return;
1333
1334 if (!PageHead(hpage))
1335 goto drop_hpage;
1336
27e1f827
SL
1337 pmd = mm_find_pmd(mm, haddr);
1338 if (!pmd)
4a9892d7 1339 goto drop_hpage;
27e1f827
SL
1340
1341 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1342
1343 /* step 1: check all mapped PTEs are to the right huge page */
1344 for (i = 0, addr = haddr, pte = start_pte;
1345 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1346 struct page *page;
1347
1348 /* empty pte, skip */
1349 if (pte_none(*pte))
1350 continue;
1351
1352 /* page swapped out, abort */
1353 if (!pte_present(*pte))
1354 goto abort;
1355
1356 page = vm_normal_page(vma, addr, *pte);
1357
27e1f827 1358 /*
4a9892d7
HD
1359 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1360 * page table, but the new page will not be a subpage of hpage.
27e1f827 1361 */
4a9892d7 1362 if (hpage + i != page)
27e1f827
SL
1363 goto abort;
1364 count++;
1365 }
1366
1367 /* step 2: adjust rmap */
1368 for (i = 0, addr = haddr, pte = start_pte;
1369 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1370 struct page *page;
1371
1372 if (pte_none(*pte))
1373 continue;
1374 page = vm_normal_page(vma, addr, *pte);
1375 page_remove_rmap(page, false);
1376 }
1377
1378 pte_unmap_unlock(start_pte, ptl);
1379
1380 /* step 3: set proper refcount and mm_counters. */
4a9892d7 1381 if (count) {
27e1f827
SL
1382 page_ref_sub(hpage, count);
1383 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1384 }
1385
1386 /* step 4: collapse pmd */
1387 ptl = pmd_lock(vma->vm_mm, pmd);
1eaeb33f 1388 _pmd = pmdp_collapse_flush(vma, haddr, pmd);
27e1f827
SL
1389 spin_unlock(ptl);
1390 mm_dec_nr_ptes(mm);
1391 pte_free(mm, pmd_pgtable(_pmd));
4a9892d7
HD
1392
1393drop_hpage:
1394 unlock_page(hpage);
1395 put_page(hpage);
27e1f827
SL
1396 return;
1397
1398abort:
1399 pte_unmap_unlock(start_pte, ptl);
4a9892d7 1400 goto drop_hpage;
27e1f827
SL
1401}
1402
1403static int khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1404{
1405 struct mm_struct *mm = mm_slot->mm;
1406 int i;
1407
1408 if (likely(mm_slot->nr_pte_mapped_thp == 0))
1409 return 0;
1410
1411 if (!down_write_trylock(&mm->mmap_sem))
1412 return -EBUSY;
1413
1414 if (unlikely(khugepaged_test_exit(mm)))
1415 goto out;
1416
1417 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1418 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
1419
1420out:
1421 mm_slot->nr_pte_mapped_thp = 0;
1422 up_write(&mm->mmap_sem);
1423 return 0;
1424}
1425
f3f0e1d2
KS
1426static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1427{
1428 struct vm_area_struct *vma;
3442c064 1429 struct mm_struct *mm;
f3f0e1d2
KS
1430 unsigned long addr;
1431 pmd_t *pmd, _pmd;
1432
1433 i_mmap_lock_write(mapping);
1434 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
27e1f827
SL
1435 /*
1436 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1437 * got written to. These VMAs are likely not worth investing
1438 * down_write(mmap_sem) as PMD-mapping is likely to be split
1439 * later.
1440 *
1441 * Not that vma->anon_vma check is racy: it can be set up after
1442 * the check but before we took mmap_sem by the fault path.
1443 * But page lock would prevent establishing any new ptes of the
1444 * page, so we are safe.
1445 *
1446 * An alternative would be drop the check, but check that page
1447 * table is clear before calling pmdp_collapse_flush() under
1448 * ptl. It has higher chance to recover THP for the VMA, but
1449 * has higher cost too.
1450 */
f3f0e1d2
KS
1451 if (vma->anon_vma)
1452 continue;
1453 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1454 if (addr & ~HPAGE_PMD_MASK)
1455 continue;
1456 if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1457 continue;
3442c064
HD
1458 mm = vma->vm_mm;
1459 pmd = mm_find_pmd(mm, addr);
f3f0e1d2
KS
1460 if (!pmd)
1461 continue;
1462 /*
1463 * We need exclusive mmap_sem to retract page table.
27e1f827
SL
1464 *
1465 * We use trylock due to lock inversion: we need to acquire
1466 * mmap_sem while holding page lock. Fault path does it in
1467 * reverse order. Trylock is a way to avoid deadlock.
f3f0e1d2 1468 */
3442c064
HD
1469 if (down_write_trylock(&mm->mmap_sem)) {
1470 if (!khugepaged_test_exit(mm)) {
1471 spinlock_t *ptl = pmd_lock(mm, pmd);
1472 /* assume page table is clear */
1473 _pmd = pmdp_collapse_flush(vma, addr, pmd);
1474 spin_unlock(ptl);
1475 mm_dec_nr_ptes(mm);
1476 pte_free(mm, pmd_pgtable(_pmd));
1477 }
1478 up_write(&mm->mmap_sem);
27e1f827
SL
1479 } else {
1480 /* Try again later */
3442c064 1481 khugepaged_add_pte_mapped_thp(mm, addr);
f3f0e1d2
KS
1482 }
1483 }
1484 i_mmap_unlock_write(mapping);
1485}
1486
1487/**
99cb0dbd 1488 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
f3f0e1d2
KS
1489 *
1490 * Basic scheme is simple, details are more complex:
87c460a0 1491 * - allocate and lock a new huge page;
77da9389 1492 * - scan page cache replacing old pages with the new one
99cb0dbd 1493 * + swap/gup in pages if necessary;
f3f0e1d2 1494 * + fill in gaps;
77da9389
MW
1495 * + keep old pages around in case rollback is required;
1496 * - if replacing succeeds:
f3f0e1d2
KS
1497 * + copy data over;
1498 * + free old pages;
87c460a0 1499 * + unlock huge page;
f3f0e1d2
KS
1500 * - if replacing failed;
1501 * + put all pages back and unfreeze them;
77da9389 1502 * + restore gaps in the page cache;
87c460a0 1503 * + unlock and free huge page;
f3f0e1d2 1504 */
579c571e
SL
1505static void collapse_file(struct mm_struct *mm,
1506 struct file *file, pgoff_t start,
f3f0e1d2
KS
1507 struct page **hpage, int node)
1508{
579c571e 1509 struct address_space *mapping = file->f_mapping;
f3f0e1d2 1510 gfp_t gfp;
77da9389 1511 struct page *new_page;
f3f0e1d2
KS
1512 struct mem_cgroup *memcg;
1513 pgoff_t index, end = start + HPAGE_PMD_NR;
1514 LIST_HEAD(pagelist);
77da9389 1515 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
f3f0e1d2 1516 int nr_none = 0, result = SCAN_SUCCEED;
99cb0dbd 1517 bool is_shmem = shmem_file(file);
f3f0e1d2 1518
99cb0dbd 1519 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
f3f0e1d2
KS
1520 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1521
1522 /* Only allocate from the target node */
41b6167e 1523 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
f3f0e1d2
KS
1524
1525 new_page = khugepaged_alloc_page(hpage, gfp, node);
1526 if (!new_page) {
1527 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1528 goto out;
1529 }
1530
2a70f6a7 1531 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
f3f0e1d2
KS
1532 result = SCAN_CGROUP_CHARGE_FAIL;
1533 goto out;
1534 }
1535
95feeabb
HD
1536 /* This will be less messy when we use multi-index entries */
1537 do {
1538 xas_lock_irq(&xas);
1539 xas_create_range(&xas);
1540 if (!xas_error(&xas))
1541 break;
1542 xas_unlock_irq(&xas);
1543 if (!xas_nomem(&xas, GFP_KERNEL)) {
1544 mem_cgroup_cancel_charge(new_page, memcg, true);
1545 result = SCAN_FAIL;
1546 goto out;
1547 }
1548 } while (1);
1549
042a3082 1550 __SetPageLocked(new_page);
99cb0dbd
SL
1551 if (is_shmem)
1552 __SetPageSwapBacked(new_page);
f3f0e1d2
KS
1553 new_page->index = start;
1554 new_page->mapping = mapping;
f3f0e1d2 1555
f3f0e1d2 1556 /*
87c460a0
HD
1557 * At this point the new_page is locked and not up-to-date.
1558 * It's safe to insert it into the page cache, because nobody would
1559 * be able to map it or use it in another way until we unlock it.
f3f0e1d2
KS
1560 */
1561
77da9389
MW
1562 xas_set(&xas, start);
1563 for (index = start; index < end; index++) {
1564 struct page *page = xas_next(&xas);
1565
1566 VM_BUG_ON(index != xas.xa_index);
99cb0dbd
SL
1567 if (is_shmem) {
1568 if (!page) {
1569 /*
1570 * Stop if extent has been truncated or
1571 * hole-punched, and is now completely
1572 * empty.
1573 */
1574 if (index == start) {
1575 if (!xas_next_entry(&xas, end - 1)) {
1576 result = SCAN_TRUNCATED;
1577 goto xa_locked;
1578 }
1579 xas_set(&xas, index);
1580 }
1581 if (!shmem_charge(mapping->host, 1)) {
1582 result = SCAN_FAIL;
042a3082 1583 goto xa_locked;
701270fa 1584 }
99cb0dbd
SL
1585 xas_store(&xas, new_page);
1586 nr_none++;
1587 continue;
701270fa 1588 }
99cb0dbd
SL
1589
1590 if (xa_is_value(page) || !PageUptodate(page)) {
1591 xas_unlock_irq(&xas);
1592 /* swap in or instantiate fallocated page */
1593 if (shmem_getpage(mapping->host, index, &page,
1594 SGP_NOHUGE)) {
1595 result = SCAN_FAIL;
1596 goto xa_unlocked;
1597 }
1598 } else if (trylock_page(page)) {
1599 get_page(page);
1600 xas_unlock_irq(&xas);
1601 } else {
1602 result = SCAN_PAGE_LOCK;
042a3082 1603 goto xa_locked;
77da9389 1604 }
99cb0dbd
SL
1605 } else { /* !is_shmem */
1606 if (!page || xa_is_value(page)) {
1607 xas_unlock_irq(&xas);
1608 page_cache_sync_readahead(mapping, &file->f_ra,
1609 file, index,
5b42bfe0 1610 end - index);
99cb0dbd
SL
1611 /* drain pagevecs to help isolate_lru_page() */
1612 lru_add_drain();
1613 page = find_lock_page(mapping, index);
1614 if (unlikely(page == NULL)) {
1615 result = SCAN_FAIL;
1616 goto xa_unlocked;
1617 }
99cb0dbd
SL
1618 } else if (trylock_page(page)) {
1619 get_page(page);
1620 xas_unlock_irq(&xas);
1621 } else {
1622 result = SCAN_PAGE_LOCK;
1623 goto xa_locked;
f3f0e1d2 1624 }
f3f0e1d2
KS
1625 }
1626
1627 /*
b93b0163 1628 * The page must be locked, so we can drop the i_pages lock
f3f0e1d2
KS
1629 * without racing with truncate.
1630 */
1631 VM_BUG_ON_PAGE(!PageLocked(page), page);
4655e5e5
SL
1632
1633 /* make sure the page is up to date */
1634 if (unlikely(!PageUptodate(page))) {
1635 result = SCAN_FAIL;
1636 goto out_unlock;
1637 }
06a5e126
HD
1638
1639 /*
1640 * If file was truncated then extended, or hole-punched, before
1641 * we locked the first page, then a THP might be there already.
1642 */
1643 if (PageTransCompound(page)) {
1644 result = SCAN_PAGE_COMPOUND;
1645 goto out_unlock;
1646 }
f3f0e1d2
KS
1647
1648 if (page_mapping(page) != mapping) {
1649 result = SCAN_TRUNCATED;
1650 goto out_unlock;
1651 }
f3f0e1d2 1652
4655e5e5
SL
1653 if (!is_shmem && PageDirty(page)) {
1654 /*
1655 * khugepaged only works on read-only fd, so this
1656 * page is dirty because it hasn't been flushed
1657 * since first write.
1658 */
1659 result = SCAN_FAIL;
1660 goto out_unlock;
1661 }
1662
f3f0e1d2
KS
1663 if (isolate_lru_page(page)) {
1664 result = SCAN_DEL_PAGE_LRU;
042a3082 1665 goto out_unlock;
f3f0e1d2
KS
1666 }
1667
99cb0dbd
SL
1668 if (page_has_private(page) &&
1669 !try_to_release_page(page, GFP_KERNEL)) {
1670 result = SCAN_PAGE_HAS_PRIVATE;
725e6db0 1671 putback_lru_page(page);
99cb0dbd
SL
1672 goto out_unlock;
1673 }
1674
f3f0e1d2 1675 if (page_mapped(page))
977fbdcd 1676 unmap_mapping_pages(mapping, index, 1, false);
f3f0e1d2 1677
77da9389
MW
1678 xas_lock_irq(&xas);
1679 xas_set(&xas, index);
f3f0e1d2 1680
77da9389 1681 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
f3f0e1d2
KS
1682 VM_BUG_ON_PAGE(page_mapped(page), page);
1683
1684 /*
1685 * The page is expected to have page_count() == 3:
1686 * - we hold a pin on it;
77da9389 1687 * - one reference from page cache;
f3f0e1d2
KS
1688 * - one from isolate_lru_page;
1689 */
1690 if (!page_ref_freeze(page, 3)) {
1691 result = SCAN_PAGE_COUNT;
042a3082
HD
1692 xas_unlock_irq(&xas);
1693 putback_lru_page(page);
1694 goto out_unlock;
f3f0e1d2
KS
1695 }
1696
1697 /*
1698 * Add the page to the list to be able to undo the collapse if
1699 * something go wrong.
1700 */
1701 list_add_tail(&page->lru, &pagelist);
1702
1703 /* Finally, replace with the new page. */
4101196b 1704 xas_store(&xas, new_page);
f3f0e1d2 1705 continue;
f3f0e1d2
KS
1706out_unlock:
1707 unlock_page(page);
1708 put_page(page);
042a3082 1709 goto xa_unlocked;
f3f0e1d2
KS
1710 }
1711
99cb0dbd
SL
1712 if (is_shmem)
1713 __inc_node_page_state(new_page, NR_SHMEM_THPS);
09d91cda 1714 else {
99cb0dbd 1715 __inc_node_page_state(new_page, NR_FILE_THPS);
09d91cda
SL
1716 filemap_nr_thps_inc(mapping);
1717 }
99cb0dbd 1718
042a3082
HD
1719 if (nr_none) {
1720 struct zone *zone = page_zone(new_page);
1721
1722 __mod_node_page_state(zone->zone_pgdat, NR_FILE_PAGES, nr_none);
99cb0dbd
SL
1723 if (is_shmem)
1724 __mod_node_page_state(zone->zone_pgdat,
1725 NR_SHMEM, nr_none);
042a3082
HD
1726 }
1727
1728xa_locked:
1729 xas_unlock_irq(&xas);
77da9389 1730xa_unlocked:
042a3082 1731
f3f0e1d2 1732 if (result == SCAN_SUCCEED) {
77da9389 1733 struct page *page, *tmp;
f3f0e1d2
KS
1734
1735 /*
77da9389
MW
1736 * Replacing old pages with new one has succeeded, now we
1737 * need to copy the content and free the old pages.
f3f0e1d2 1738 */
2af8ff29 1739 index = start;
f3f0e1d2 1740 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2af8ff29
HD
1741 while (index < page->index) {
1742 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1743 index++;
1744 }
f3f0e1d2
KS
1745 copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1746 page);
1747 list_del(&page->lru);
f3f0e1d2 1748 page->mapping = NULL;
042a3082 1749 page_ref_unfreeze(page, 1);
f3f0e1d2
KS
1750 ClearPageActive(page);
1751 ClearPageUnevictable(page);
042a3082 1752 unlock_page(page);
f3f0e1d2 1753 put_page(page);
2af8ff29
HD
1754 index++;
1755 }
1756 while (index < end) {
1757 clear_highpage(new_page + (index % HPAGE_PMD_NR));
1758 index++;
f3f0e1d2
KS
1759 }
1760
f3f0e1d2 1761 SetPageUptodate(new_page);
87c460a0 1762 page_ref_add(new_page, HPAGE_PMD_NR - 1);
f3f0e1d2 1763 mem_cgroup_commit_charge(new_page, memcg, false, true);
99cb0dbd
SL
1764
1765 if (is_shmem) {
1766 set_page_dirty(new_page);
1767 lru_cache_add_anon(new_page);
1768 } else {
1769 lru_cache_add_file(new_page);
1770 }
1ff9e6e1 1771 count_memcg_events(memcg, THP_COLLAPSE_ALLOC, 1);
f3f0e1d2 1772
042a3082
HD
1773 /*
1774 * Remove pte page tables, so we can re-fault the page as huge.
1775 */
1776 retract_page_tables(mapping, start);
f3f0e1d2 1777 *hpage = NULL;
87aa7529
YS
1778
1779 khugepaged_pages_collapsed++;
f3f0e1d2 1780 } else {
77da9389 1781 struct page *page;
aaa52e34 1782
77da9389 1783 /* Something went wrong: roll back page cache changes */
77da9389 1784 xas_lock_irq(&xas);
aaa52e34 1785 mapping->nrpages -= nr_none;
99cb0dbd
SL
1786
1787 if (is_shmem)
1788 shmem_uncharge(mapping->host, nr_none);
aaa52e34 1789
77da9389
MW
1790 xas_set(&xas, start);
1791 xas_for_each(&xas, page, end - 1) {
f3f0e1d2
KS
1792 page = list_first_entry_or_null(&pagelist,
1793 struct page, lru);
77da9389 1794 if (!page || xas.xa_index < page->index) {
f3f0e1d2
KS
1795 if (!nr_none)
1796 break;
f3f0e1d2 1797 nr_none--;
59749e6c 1798 /* Put holes back where they were */
77da9389 1799 xas_store(&xas, NULL);
f3f0e1d2
KS
1800 continue;
1801 }
1802
77da9389 1803 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
f3f0e1d2
KS
1804
1805 /* Unfreeze the page. */
1806 list_del(&page->lru);
1807 page_ref_unfreeze(page, 2);
77da9389
MW
1808 xas_store(&xas, page);
1809 xas_pause(&xas);
1810 xas_unlock_irq(&xas);
f3f0e1d2 1811 unlock_page(page);
042a3082 1812 putback_lru_page(page);
77da9389 1813 xas_lock_irq(&xas);
f3f0e1d2
KS
1814 }
1815 VM_BUG_ON(nr_none);
77da9389 1816 xas_unlock_irq(&xas);
f3f0e1d2 1817
f3f0e1d2 1818 mem_cgroup_cancel_charge(new_page, memcg, true);
f3f0e1d2
KS
1819 new_page->mapping = NULL;
1820 }
042a3082
HD
1821
1822 unlock_page(new_page);
f3f0e1d2
KS
1823out:
1824 VM_BUG_ON(!list_empty(&pagelist));
1825 /* TODO: tracepoints */
1826}
1827
579c571e
SL
1828static void khugepaged_scan_file(struct mm_struct *mm,
1829 struct file *file, pgoff_t start, struct page **hpage)
f3f0e1d2
KS
1830{
1831 struct page *page = NULL;
579c571e 1832 struct address_space *mapping = file->f_mapping;
85b392db 1833 XA_STATE(xas, &mapping->i_pages, start);
f3f0e1d2
KS
1834 int present, swap;
1835 int node = NUMA_NO_NODE;
1836 int result = SCAN_SUCCEED;
1837
1838 present = 0;
1839 swap = 0;
1840 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1841 rcu_read_lock();
85b392db
MW
1842 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
1843 if (xas_retry(&xas, page))
f3f0e1d2 1844 continue;
f3f0e1d2 1845
85b392db 1846 if (xa_is_value(page)) {
f3f0e1d2
KS
1847 if (++swap > khugepaged_max_ptes_swap) {
1848 result = SCAN_EXCEED_SWAP_PTE;
1849 break;
1850 }
1851 continue;
1852 }
1853
1854 if (PageTransCompound(page)) {
1855 result = SCAN_PAGE_COMPOUND;
1856 break;
1857 }
1858
1859 node = page_to_nid(page);
1860 if (khugepaged_scan_abort(node)) {
1861 result = SCAN_SCAN_ABORT;
1862 break;
1863 }
1864 khugepaged_node_load[node]++;
1865
1866 if (!PageLRU(page)) {
1867 result = SCAN_PAGE_LRU;
1868 break;
1869 }
1870
99cb0dbd
SL
1871 if (page_count(page) !=
1872 1 + page_mapcount(page) + page_has_private(page)) {
f3f0e1d2
KS
1873 result = SCAN_PAGE_COUNT;
1874 break;
1875 }
1876
1877 /*
1878 * We probably should check if the page is referenced here, but
1879 * nobody would transfer pte_young() to PageReferenced() for us.
1880 * And rmap walk here is just too costly...
1881 */
1882
1883 present++;
1884
1885 if (need_resched()) {
85b392db 1886 xas_pause(&xas);
f3f0e1d2 1887 cond_resched_rcu();
f3f0e1d2
KS
1888 }
1889 }
1890 rcu_read_unlock();
1891
1892 if (result == SCAN_SUCCEED) {
1893 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
1894 result = SCAN_EXCEED_NONE_PTE;
1895 } else {
1896 node = khugepaged_find_target_node();
579c571e 1897 collapse_file(mm, file, start, hpage, node);
f3f0e1d2
KS
1898 }
1899 }
1900
1901 /* TODO: tracepoints */
1902}
1903#else
579c571e
SL
1904static void khugepaged_scan_file(struct mm_struct *mm,
1905 struct file *file, pgoff_t start, struct page **hpage)
f3f0e1d2
KS
1906{
1907 BUILD_BUG();
1908}
27e1f827
SL
1909
1910static int khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
1911{
1912 return 0;
1913}
f3f0e1d2
KS
1914#endif
1915
b46e756f
KS
1916static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
1917 struct page **hpage)
1918 __releases(&khugepaged_mm_lock)
1919 __acquires(&khugepaged_mm_lock)
1920{
1921 struct mm_slot *mm_slot;
1922 struct mm_struct *mm;
1923 struct vm_area_struct *vma;
1924 int progress = 0;
1925
1926 VM_BUG_ON(!pages);
35f3aa39 1927 lockdep_assert_held(&khugepaged_mm_lock);
b46e756f
KS
1928
1929 if (khugepaged_scan.mm_slot)
1930 mm_slot = khugepaged_scan.mm_slot;
1931 else {
1932 mm_slot = list_entry(khugepaged_scan.mm_head.next,
1933 struct mm_slot, mm_node);
1934 khugepaged_scan.address = 0;
1935 khugepaged_scan.mm_slot = mm_slot;
1936 }
1937 spin_unlock(&khugepaged_mm_lock);
27e1f827 1938 khugepaged_collapse_pte_mapped_thps(mm_slot);
b46e756f
KS
1939
1940 mm = mm_slot->mm;
3b454ad3
YS
1941 /*
1942 * Don't wait for semaphore (to avoid long wait times). Just move to
1943 * the next mm on the list.
1944 */
1945 vma = NULL;
1946 if (unlikely(!down_read_trylock(&mm->mmap_sem)))
1947 goto breakouterloop_mmap_sem;
1948 if (likely(!khugepaged_test_exit(mm)))
b46e756f
KS
1949 vma = find_vma(mm, khugepaged_scan.address);
1950
1951 progress++;
1952 for (; vma; vma = vma->vm_next) {
1953 unsigned long hstart, hend;
1954
1955 cond_resched();
1956 if (unlikely(khugepaged_test_exit(mm))) {
1957 progress++;
1958 break;
1959 }
50f8b92f 1960 if (!hugepage_vma_check(vma, vma->vm_flags)) {
b46e756f
KS
1961skip:
1962 progress++;
1963 continue;
1964 }
1965 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1966 hend = vma->vm_end & HPAGE_PMD_MASK;
1967 if (hstart >= hend)
1968 goto skip;
1969 if (khugepaged_scan.address > hend)
1970 goto skip;
1971 if (khugepaged_scan.address < hstart)
1972 khugepaged_scan.address = hstart;
1973 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
1974
1975 while (khugepaged_scan.address < hend) {
1976 int ret;
1977 cond_resched();
1978 if (unlikely(khugepaged_test_exit(mm)))
1979 goto breakouterloop;
1980
1981 VM_BUG_ON(khugepaged_scan.address < hstart ||
1982 khugepaged_scan.address + HPAGE_PMD_SIZE >
1983 hend);
99cb0dbd 1984 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
e496cf3d 1985 struct file *file;
f3f0e1d2
KS
1986 pgoff_t pgoff = linear_page_index(vma,
1987 khugepaged_scan.address);
99cb0dbd
SL
1988
1989 if (shmem_file(vma->vm_file)
1990 && !shmem_huge_enabled(vma))
e496cf3d
KS
1991 goto skip;
1992 file = get_file(vma->vm_file);
f3f0e1d2
KS
1993 up_read(&mm->mmap_sem);
1994 ret = 1;
579c571e 1995 khugepaged_scan_file(mm, file, pgoff, hpage);
f3f0e1d2
KS
1996 fput(file);
1997 } else {
1998 ret = khugepaged_scan_pmd(mm, vma,
1999 khugepaged_scan.address,
2000 hpage);
2001 }
b46e756f
KS
2002 /* move to next address */
2003 khugepaged_scan.address += HPAGE_PMD_SIZE;
2004 progress += HPAGE_PMD_NR;
2005 if (ret)
2006 /* we released mmap_sem so break loop */
2007 goto breakouterloop_mmap_sem;
2008 if (progress >= pages)
2009 goto breakouterloop;
2010 }
2011 }
2012breakouterloop:
2013 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2014breakouterloop_mmap_sem:
2015
2016 spin_lock(&khugepaged_mm_lock);
2017 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2018 /*
2019 * Release the current mm_slot if this mm is about to die, or
2020 * if we scanned all vmas of this mm.
2021 */
2022 if (khugepaged_test_exit(mm) || !vma) {
2023 /*
2024 * Make sure that if mm_users is reaching zero while
2025 * khugepaged runs here, khugepaged_exit will find
2026 * mm_slot not pointing to the exiting mm.
2027 */
2028 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2029 khugepaged_scan.mm_slot = list_entry(
2030 mm_slot->mm_node.next,
2031 struct mm_slot, mm_node);
2032 khugepaged_scan.address = 0;
2033 } else {
2034 khugepaged_scan.mm_slot = NULL;
2035 khugepaged_full_scans++;
2036 }
2037
2038 collect_mm_slot(mm_slot);
2039 }
2040
2041 return progress;
2042}
2043
2044static int khugepaged_has_work(void)
2045{
2046 return !list_empty(&khugepaged_scan.mm_head) &&
2047 khugepaged_enabled();
2048}
2049
2050static int khugepaged_wait_event(void)
2051{
2052 return !list_empty(&khugepaged_scan.mm_head) ||
2053 kthread_should_stop();
2054}
2055
2056static void khugepaged_do_scan(void)
2057{
2058 struct page *hpage = NULL;
2059 unsigned int progress = 0, pass_through_head = 0;
2060 unsigned int pages = khugepaged_pages_to_scan;
2061 bool wait = true;
2062
2063 barrier(); /* write khugepaged_pages_to_scan to local stack */
2064
2065 while (progress < pages) {
2066 if (!khugepaged_prealloc_page(&hpage, &wait))
2067 break;
2068
2069 cond_resched();
2070
2071 if (unlikely(kthread_should_stop() || try_to_freeze()))
2072 break;
2073
2074 spin_lock(&khugepaged_mm_lock);
2075 if (!khugepaged_scan.mm_slot)
2076 pass_through_head++;
2077 if (khugepaged_has_work() &&
2078 pass_through_head < 2)
2079 progress += khugepaged_scan_mm_slot(pages - progress,
2080 &hpage);
2081 else
2082 progress = pages;
2083 spin_unlock(&khugepaged_mm_lock);
2084 }
2085
2086 if (!IS_ERR_OR_NULL(hpage))
2087 put_page(hpage);
2088}
2089
2090static bool khugepaged_should_wakeup(void)
2091{
2092 return kthread_should_stop() ||
2093 time_after_eq(jiffies, khugepaged_sleep_expire);
2094}
2095
2096static void khugepaged_wait_work(void)
2097{
2098 if (khugepaged_has_work()) {
2099 const unsigned long scan_sleep_jiffies =
2100 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2101
2102 if (!scan_sleep_jiffies)
2103 return;
2104
2105 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2106 wait_event_freezable_timeout(khugepaged_wait,
2107 khugepaged_should_wakeup(),
2108 scan_sleep_jiffies);
2109 return;
2110 }
2111
2112 if (khugepaged_enabled())
2113 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2114}
2115
2116static int khugepaged(void *none)
2117{
2118 struct mm_slot *mm_slot;
2119
2120 set_freezable();
2121 set_user_nice(current, MAX_NICE);
2122
2123 while (!kthread_should_stop()) {
2124 khugepaged_do_scan();
2125 khugepaged_wait_work();
2126 }
2127
2128 spin_lock(&khugepaged_mm_lock);
2129 mm_slot = khugepaged_scan.mm_slot;
2130 khugepaged_scan.mm_slot = NULL;
2131 if (mm_slot)
2132 collect_mm_slot(mm_slot);
2133 spin_unlock(&khugepaged_mm_lock);
2134 return 0;
2135}
2136
2137static void set_recommended_min_free_kbytes(void)
2138{
2139 struct zone *zone;
2140 int nr_zones = 0;
2141 unsigned long recommended_min;
2142
b7d349c7
JK
2143 for_each_populated_zone(zone) {
2144 /*
2145 * We don't need to worry about fragmentation of
2146 * ZONE_MOVABLE since it only has movable pages.
2147 */
2148 if (zone_idx(zone) > gfp_zone(GFP_USER))
2149 continue;
2150
b46e756f 2151 nr_zones++;
b7d349c7 2152 }
b46e756f
KS
2153
2154 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2155 recommended_min = pageblock_nr_pages * nr_zones * 2;
2156
2157 /*
2158 * Make sure that on average at least two pageblocks are almost free
2159 * of another type, one for a migratetype to fall back to and a
2160 * second to avoid subsequent fallbacks of other types There are 3
2161 * MIGRATE_TYPES we care about.
2162 */
2163 recommended_min += pageblock_nr_pages * nr_zones *
2164 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2165
2166 /* don't ever allow to reserve more than 5% of the lowmem */
2167 recommended_min = min(recommended_min,
2168 (unsigned long) nr_free_buffer_pages() / 20);
2169 recommended_min <<= (PAGE_SHIFT-10);
2170
2171 if (recommended_min > min_free_kbytes) {
2172 if (user_min_free_kbytes >= 0)
2173 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2174 min_free_kbytes, recommended_min);
2175
2176 min_free_kbytes = recommended_min;
2177 }
2178 setup_per_zone_wmarks();
2179}
2180
2181int start_stop_khugepaged(void)
2182{
b46e756f
KS
2183 int err = 0;
2184
2185 mutex_lock(&khugepaged_mutex);
2186 if (khugepaged_enabled()) {
2187 if (!khugepaged_thread)
2188 khugepaged_thread = kthread_run(khugepaged, NULL,
2189 "khugepaged");
2190 if (IS_ERR(khugepaged_thread)) {
2191 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2192 err = PTR_ERR(khugepaged_thread);
2193 khugepaged_thread = NULL;
2194 goto fail;
2195 }
2196
2197 if (!list_empty(&khugepaged_scan.mm_head))
2198 wake_up_interruptible(&khugepaged_wait);
2199
2200 set_recommended_min_free_kbytes();
2201 } else if (khugepaged_thread) {
2202 kthread_stop(khugepaged_thread);
2203 khugepaged_thread = NULL;
2204 }
2205fail:
2206 mutex_unlock(&khugepaged_mutex);
2207 return err;
2208}
e2c01fd0
VB
2209
2210void khugepaged_min_free_kbytes_update(void)
2211{
2212 mutex_lock(&khugepaged_mutex);
2213 if (khugepaged_enabled() && khugepaged_thread)
2214 set_recommended_min_free_kbytes();
2215 mutex_unlock(&khugepaged_mutex);
2216}