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