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