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