]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/khugepaged.c
btrfs: fix off-by-one when checking chunk map includes logical address
[thirdparty/linux.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>
e2942062 22#include <linux/ksm.h>
b46e756f
KS
23
24#include <asm/tlb.h>
25#include <asm/pgalloc.h>
26#include "internal.h"
b26e2701 27#include "mm_slot.h"
b46e756f
KS
28
29enum scan_result {
30 SCAN_FAIL,
31 SCAN_SUCCEED,
32 SCAN_PMD_NULL,
34488399 33 SCAN_PMD_NONE,
50722804 34 SCAN_PMD_MAPPED,
b46e756f 35 SCAN_EXCEED_NONE_PTE,
71a2c112
KS
36 SCAN_EXCEED_SWAP_PTE,
37 SCAN_EXCEED_SHARED_PTE,
b46e756f 38 SCAN_PTE_NON_PRESENT,
e1e267c7 39 SCAN_PTE_UFFD_WP,
58ac9a89 40 SCAN_PTE_MAPPED_HUGEPAGE,
b46e756f 41 SCAN_PAGE_RO,
0db501f7 42 SCAN_LACK_REFERENCED_PAGE,
b46e756f
KS
43 SCAN_PAGE_NULL,
44 SCAN_SCAN_ABORT,
45 SCAN_PAGE_COUNT,
46 SCAN_PAGE_LRU,
47 SCAN_PAGE_LOCK,
48 SCAN_PAGE_ANON,
49 SCAN_PAGE_COMPOUND,
50 SCAN_ANY_PROCESS,
51 SCAN_VMA_NULL,
52 SCAN_VMA_CHECK,
53 SCAN_ADDRESS_RANGE,
b46e756f
KS
54 SCAN_DEL_PAGE_LRU,
55 SCAN_ALLOC_HUGE_PAGE_FAIL,
56 SCAN_CGROUP_CHARGE_FAIL,
f3f0e1d2 57 SCAN_TRUNCATED,
99cb0dbd 58 SCAN_PAGE_HAS_PRIVATE,
2ce0bdfe 59 SCAN_STORE_FAILED,
98c76c9f 60 SCAN_COPY_MC,
ac492b9c 61 SCAN_PAGE_FILLED,
b46e756f
KS
62};
63
64#define CREATE_TRACE_POINTS
65#include <trace/events/huge_memory.h>
66
4aab2be0
VB
67static struct task_struct *khugepaged_thread __read_mostly;
68static DEFINE_MUTEX(khugepaged_mutex);
69
b46e756f
KS
70/* default scan 8*512 pte (or vmas) every 30 second */
71static unsigned int khugepaged_pages_to_scan __read_mostly;
72static unsigned int khugepaged_pages_collapsed;
73static unsigned int khugepaged_full_scans;
74static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
75/* during fragmentation poll the hugepage allocator once every minute */
76static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
77static unsigned long khugepaged_sleep_expire;
78static DEFINE_SPINLOCK(khugepaged_mm_lock);
79static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
80/*
81 * default collapse hugepages if there is at least one pte mapped like
82 * it would have happened if the vma was large enough during page
83 * fault.
d8ea7cc8
ZK
84 *
85 * Note that these are only respected if collapse was initiated by khugepaged.
b46e756f
KS
86 */
87static unsigned int khugepaged_max_ptes_none __read_mostly;
88static unsigned int khugepaged_max_ptes_swap __read_mostly;
71a2c112 89static unsigned int khugepaged_max_ptes_shared __read_mostly;
b46e756f
KS
90
91#define MM_SLOTS_HASH_BITS 10
e1ad3e66 92static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
b46e756f
KS
93
94static struct kmem_cache *mm_slot_cache __read_mostly;
95
34d6b470 96struct collapse_control {
d8ea7cc8
ZK
97 bool is_khugepaged;
98
34d6b470
ZK
99 /* Num pages scanned per node */
100 u32 node_load[MAX_NUMNODES];
101
e031ff96
YS
102 /* nodemask for allocation fallback */
103 nodemask_t alloc_nmask;
34d6b470
ZK
104};
105
b46e756f 106/**
b26e2701
QZ
107 * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
108 * @slot: hash lookup from mm to mm_slot
b46e756f 109 */
b26e2701
QZ
110struct khugepaged_mm_slot {
111 struct mm_slot slot;
b46e756f
KS
112};
113
114/**
115 * struct khugepaged_scan - cursor for scanning
116 * @mm_head: the head of the mm list to scan
117 * @mm_slot: the current mm_slot we are scanning
118 * @address: the next address inside that to be scanned
119 *
120 * There is only the one khugepaged_scan instance of this cursor structure.
121 */
122struct khugepaged_scan {
123 struct list_head mm_head;
b26e2701 124 struct khugepaged_mm_slot *mm_slot;
b46e756f
KS
125 unsigned long address;
126};
127
128static struct khugepaged_scan khugepaged_scan = {
129 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
130};
131
e1465d12 132#ifdef CONFIG_SYSFS
b46e756f
KS
133static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
134 struct kobj_attribute *attr,
135 char *buf)
136{
ae7a927d 137 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
b46e756f
KS
138}
139
140static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
141 struct kobj_attribute *attr,
142 const char *buf, size_t count)
143{
dfefd226 144 unsigned int msecs;
b46e756f
KS
145 int err;
146
dfefd226
AD
147 err = kstrtouint(buf, 10, &msecs);
148 if (err)
b46e756f
KS
149 return -EINVAL;
150
151 khugepaged_scan_sleep_millisecs = msecs;
152 khugepaged_sleep_expire = 0;
153 wake_up_interruptible(&khugepaged_wait);
154
155 return count;
156}
157static struct kobj_attribute scan_sleep_millisecs_attr =
6dcdc94d 158 __ATTR_RW(scan_sleep_millisecs);
b46e756f
KS
159
160static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
161 struct kobj_attribute *attr,
162 char *buf)
163{
ae7a927d 164 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
b46e756f
KS
165}
166
167static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
168 struct kobj_attribute *attr,
169 const char *buf, size_t count)
170{
dfefd226 171 unsigned int msecs;
b46e756f
KS
172 int err;
173
dfefd226
AD
174 err = kstrtouint(buf, 10, &msecs);
175 if (err)
b46e756f
KS
176 return -EINVAL;
177
178 khugepaged_alloc_sleep_millisecs = msecs;
179 khugepaged_sleep_expire = 0;
180 wake_up_interruptible(&khugepaged_wait);
181
182 return count;
183}
184static struct kobj_attribute alloc_sleep_millisecs_attr =
6dcdc94d 185 __ATTR_RW(alloc_sleep_millisecs);
b46e756f
KS
186
187static ssize_t pages_to_scan_show(struct kobject *kobj,
188 struct kobj_attribute *attr,
189 char *buf)
190{
ae7a927d 191 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
b46e756f
KS
192}
193static ssize_t pages_to_scan_store(struct kobject *kobj,
194 struct kobj_attribute *attr,
195 const char *buf, size_t count)
196{
dfefd226 197 unsigned int pages;
b46e756f 198 int err;
b46e756f 199
dfefd226
AD
200 err = kstrtouint(buf, 10, &pages);
201 if (err || !pages)
b46e756f
KS
202 return -EINVAL;
203
204 khugepaged_pages_to_scan = pages;
205
206 return count;
207}
208static struct kobj_attribute pages_to_scan_attr =
6dcdc94d 209 __ATTR_RW(pages_to_scan);
b46e756f
KS
210
211static ssize_t pages_collapsed_show(struct kobject *kobj,
212 struct kobj_attribute *attr,
213 char *buf)
214{
ae7a927d 215 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
b46e756f
KS
216}
217static struct kobj_attribute pages_collapsed_attr =
218 __ATTR_RO(pages_collapsed);
219
220static ssize_t full_scans_show(struct kobject *kobj,
221 struct kobj_attribute *attr,
222 char *buf)
223{
ae7a927d 224 return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
b46e756f
KS
225}
226static struct kobj_attribute full_scans_attr =
227 __ATTR_RO(full_scans);
228
6dcdc94d
ML
229static ssize_t defrag_show(struct kobject *kobj,
230 struct kobj_attribute *attr, char *buf)
b46e756f
KS
231{
232 return single_hugepage_flag_show(kobj, attr, buf,
ae7a927d 233 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
b46e756f 234}
6dcdc94d
ML
235static ssize_t defrag_store(struct kobject *kobj,
236 struct kobj_attribute *attr,
237 const char *buf, size_t count)
b46e756f
KS
238{
239 return single_hugepage_flag_store(kobj, attr, buf, count,
240 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
241}
242static struct kobj_attribute khugepaged_defrag_attr =
6dcdc94d 243 __ATTR_RW(defrag);
b46e756f
KS
244
245/*
246 * max_ptes_none controls if khugepaged should collapse hugepages over
247 * any unmapped ptes in turn potentially increasing the memory
248 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
249 * reduce the available free memory in the system as it
250 * runs. Increasing max_ptes_none will instead potentially reduce the
251 * free memory in the system during the khugepaged scan.
252 */
6dcdc94d
ML
253static ssize_t max_ptes_none_show(struct kobject *kobj,
254 struct kobj_attribute *attr,
255 char *buf)
b46e756f 256{
ae7a927d 257 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
b46e756f 258}
6dcdc94d
ML
259static ssize_t max_ptes_none_store(struct kobject *kobj,
260 struct kobj_attribute *attr,
261 const char *buf, size_t count)
b46e756f
KS
262{
263 int err;
264 unsigned long max_ptes_none;
265
266 err = kstrtoul(buf, 10, &max_ptes_none);
36ee2c78 267 if (err || max_ptes_none > HPAGE_PMD_NR - 1)
b46e756f
KS
268 return -EINVAL;
269
270 khugepaged_max_ptes_none = max_ptes_none;
271
272 return count;
273}
274static struct kobj_attribute khugepaged_max_ptes_none_attr =
6dcdc94d 275 __ATTR_RW(max_ptes_none);
b46e756f 276
6dcdc94d
ML
277static ssize_t max_ptes_swap_show(struct kobject *kobj,
278 struct kobj_attribute *attr,
279 char *buf)
b46e756f 280{
ae7a927d 281 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
b46e756f
KS
282}
283
6dcdc94d
ML
284static ssize_t max_ptes_swap_store(struct kobject *kobj,
285 struct kobj_attribute *attr,
286 const char *buf, size_t count)
b46e756f
KS
287{
288 int err;
289 unsigned long max_ptes_swap;
290
291 err = kstrtoul(buf, 10, &max_ptes_swap);
36ee2c78 292 if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
b46e756f
KS
293 return -EINVAL;
294
295 khugepaged_max_ptes_swap = max_ptes_swap;
296
297 return count;
298}
299
300static struct kobj_attribute khugepaged_max_ptes_swap_attr =
6dcdc94d 301 __ATTR_RW(max_ptes_swap);
b46e756f 302
6dcdc94d
ML
303static ssize_t max_ptes_shared_show(struct kobject *kobj,
304 struct kobj_attribute *attr,
305 char *buf)
71a2c112 306{
ae7a927d 307 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
71a2c112
KS
308}
309
6dcdc94d
ML
310static ssize_t max_ptes_shared_store(struct kobject *kobj,
311 struct kobj_attribute *attr,
312 const char *buf, size_t count)
71a2c112
KS
313{
314 int err;
315 unsigned long max_ptes_shared;
316
317 err = kstrtoul(buf, 10, &max_ptes_shared);
36ee2c78 318 if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
71a2c112
KS
319 return -EINVAL;
320
321 khugepaged_max_ptes_shared = max_ptes_shared;
322
323 return count;
324}
325
326static struct kobj_attribute khugepaged_max_ptes_shared_attr =
6dcdc94d 327 __ATTR_RW(max_ptes_shared);
71a2c112 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 */
c791576c 369 khugepaged_enter_vma(vma, *vm_flags);
b46e756f
KS
370 break;
371 case MADV_NOHUGEPAGE:
372 *vm_flags &= ~VM_HUGEPAGE;
373 *vm_flags |= VM_NOHUGEPAGE;
374 /*
375 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
376 * this vma even if we leave the mm registered in khugepaged if
377 * it got registered before VM_NOHUGEPAGE was set.
378 */
379 break;
380 }
381
382 return 0;
383}
384
385int __init khugepaged_init(void)
386{
387 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
b26e2701
QZ
388 sizeof(struct khugepaged_mm_slot),
389 __alignof__(struct khugepaged_mm_slot),
390 0, NULL);
b46e756f
KS
391 if (!mm_slot_cache)
392 return -ENOMEM;
393
394 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
395 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
396 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
71a2c112 397 khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
b46e756f
KS
398
399 return 0;
400}
401
402void __init khugepaged_destroy(void)
403{
404 kmem_cache_destroy(mm_slot_cache);
405}
406
7d2c4385 407static inline int hpage_collapse_test_exit(struct mm_struct *mm)
b46e756f 408{
4d45e75a 409 return atomic_read(&mm->mm_users) == 0;
b46e756f
KS
410}
411
d2081b2b 412void __khugepaged_enter(struct mm_struct *mm)
b46e756f 413{
b26e2701
QZ
414 struct khugepaged_mm_slot *mm_slot;
415 struct mm_slot *slot;
b46e756f
KS
416 int wakeup;
417
16618670
XH
418 /* __khugepaged_exit() must not run from under us */
419 VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
420 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags)))
421 return;
422
b26e2701 423 mm_slot = mm_slot_alloc(mm_slot_cache);
b46e756f 424 if (!mm_slot)
d2081b2b 425 return;
b46e756f 426
b26e2701
QZ
427 slot = &mm_slot->slot;
428
b46e756f 429 spin_lock(&khugepaged_mm_lock);
b26e2701 430 mm_slot_insert(mm_slots_hash, mm, slot);
b46e756f
KS
431 /*
432 * Insert just behind the scanning cursor, to let the area settle
433 * down a little.
434 */
435 wakeup = list_empty(&khugepaged_scan.mm_head);
b26e2701 436 list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
b46e756f
KS
437 spin_unlock(&khugepaged_mm_lock);
438
f1f10076 439 mmgrab(mm);
b46e756f
KS
440 if (wakeup)
441 wake_up_interruptible(&khugepaged_wait);
b46e756f
KS
442}
443
c791576c
YS
444void khugepaged_enter_vma(struct vm_area_struct *vma,
445 unsigned long vm_flags)
b46e756f 446{
2647d11b 447 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
1064026b 448 hugepage_flags_enabled()) {
a7f4e6e4 449 if (hugepage_vma_check(vma, vm_flags, false, false, true))
2647d11b
YS
450 __khugepaged_enter(vma->vm_mm);
451 }
b46e756f
KS
452}
453
454void __khugepaged_exit(struct mm_struct *mm)
455{
b26e2701
QZ
456 struct khugepaged_mm_slot *mm_slot;
457 struct mm_slot *slot;
b46e756f
KS
458 int free = 0;
459
460 spin_lock(&khugepaged_mm_lock);
b26e2701
QZ
461 slot = mm_slot_lookup(mm_slots_hash, mm);
462 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
b46e756f 463 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
b26e2701
QZ
464 hash_del(&slot->hash);
465 list_del(&slot->mm_node);
b46e756f
KS
466 free = 1;
467 }
468 spin_unlock(&khugepaged_mm_lock);
469
470 if (free) {
471 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
b26e2701 472 mm_slot_free(mm_slot_cache, mm_slot);
b46e756f
KS
473 mmdrop(mm);
474 } else if (mm_slot) {
475 /*
476 * This is required to serialize against
7d2c4385
ZK
477 * hpage_collapse_test_exit() (which is guaranteed to run
478 * under mmap sem read mode). Stop here (after we return all
479 * pagetables will be destroyed) until khugepaged has finished
480 * working on the pagetables under the mmap_lock.
b46e756f 481 */
d8ed45c5
ML
482 mmap_write_lock(mm);
483 mmap_write_unlock(mm);
b46e756f
KS
484 }
485}
486
92644f58
VMO
487static void release_pte_folio(struct folio *folio)
488{
489 node_stat_mod_folio(folio,
490 NR_ISOLATED_ANON + folio_is_file_lru(folio),
491 -folio_nr_pages(folio));
492 folio_unlock(folio);
493 folio_putback_lru(folio);
494}
495
b46e756f
KS
496static void release_pte_page(struct page *page)
497{
92644f58 498 release_pte_folio(page_folio(page));
b46e756f
KS
499}
500
5503fbf2
KS
501static void release_pte_pages(pte_t *pte, pte_t *_pte,
502 struct list_head *compound_pagelist)
b46e756f 503{
9bdfeea4 504 struct folio *folio, *tmp;
5503fbf2 505
b46e756f 506 while (--_pte >= pte) {
c33c7948 507 pte_t pteval = ptep_get(_pte);
f528260b 508 unsigned long pfn;
5503fbf2 509
f528260b
VMO
510 if (pte_none(pteval))
511 continue;
512 pfn = pte_pfn(pteval);
513 if (is_zero_pfn(pfn))
514 continue;
515 folio = pfn_folio(pfn);
516 if (folio_test_large(folio))
517 continue;
518 release_pte_folio(folio);
5503fbf2
KS
519 }
520
9bdfeea4
VMO
521 list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
522 list_del(&folio->lru);
523 release_pte_folio(folio);
b46e756f
KS
524 }
525}
526
9445689f
KS
527static bool is_refcount_suitable(struct page *page)
528{
529 int expected_refcount;
530
531 expected_refcount = total_mapcount(page);
532 if (PageSwapCache(page))
533 expected_refcount += compound_nr(page);
534
535 return page_count(page) == expected_refcount;
536}
537
b46e756f
KS
538static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
539 unsigned long address,
5503fbf2 540 pte_t *pte,
d8ea7cc8 541 struct collapse_control *cc,
5503fbf2 542 struct list_head *compound_pagelist)
b46e756f
KS
543{
544 struct page *page = NULL;
545 pte_t *_pte;
50ad2f24 546 int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
0db501f7 547 bool writable = false;
b46e756f 548
36ee2c78 549 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
b46e756f 550 _pte++, address += PAGE_SIZE) {
c33c7948 551 pte_t pteval = ptep_get(_pte);
b46e756f
KS
552 if (pte_none(pteval) || (pte_present(pteval) &&
553 is_zero_pfn(pte_pfn(pteval)))) {
d8ea7cc8 554 ++none_or_zero;
b46e756f 555 if (!userfaultfd_armed(vma) &&
d8ea7cc8
ZK
556 (!cc->is_khugepaged ||
557 none_or_zero <= khugepaged_max_ptes_none)) {
b46e756f
KS
558 continue;
559 } else {
560 result = SCAN_EXCEED_NONE_PTE;
e9ea874a 561 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
b46e756f
KS
562 goto out;
563 }
564 }
565 if (!pte_present(pteval)) {
566 result = SCAN_PTE_NON_PRESENT;
567 goto out;
568 }
dd47ac42
PX
569 if (pte_uffd_wp(pteval)) {
570 result = SCAN_PTE_UFFD_WP;
571 goto out;
572 }
b46e756f 573 page = vm_normal_page(vma, address, pteval);
3218f871 574 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
b46e756f
KS
575 result = SCAN_PAGE_NULL;
576 goto out;
577 }
578
5503fbf2
KS
579 VM_BUG_ON_PAGE(!PageAnon(page), page);
580
d8ea7cc8
ZK
581 if (page_mapcount(page) > 1) {
582 ++shared;
583 if (cc->is_khugepaged &&
584 shared > khugepaged_max_ptes_shared) {
585 result = SCAN_EXCEED_SHARED_PTE;
586 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
587 goto out;
588 }
71a2c112
KS
589 }
590
fece2029 591 if (PageCompound(page)) {
5503fbf2
KS
592 struct page *p;
593 page = compound_head(page);
fece2029 594
5503fbf2
KS
595 /*
596 * Check if we have dealt with the compound page
597 * already
598 */
599 list_for_each_entry(p, compound_pagelist, lru) {
600 if (page == p)
601 goto next;
602 }
603 }
b46e756f
KS
604
605 /*
606 * We can do it before isolate_lru_page because the
607 * page can't be freed from under us. NOTE: PG_lock
608 * is needed to serialize against split_huge_page
609 * when invoked from the VM.
610 */
611 if (!trylock_page(page)) {
612 result = SCAN_PAGE_LOCK;
613 goto out;
614 }
615
616 /*
9445689f
KS
617 * Check if the page has any GUP (or other external) pins.
618 *
619 * The page table that maps the page has been already unlinked
620 * from the page table tree and this process cannot get
f0953a1b 621 * an additional pin on the page.
9445689f
KS
622 *
623 * New pins can come later if the page is shared across fork,
624 * but not from this process. The other process cannot write to
625 * the page, only trigger CoW.
b46e756f 626 */
9445689f 627 if (!is_refcount_suitable(page)) {
b46e756f
KS
628 unlock_page(page);
629 result = SCAN_PAGE_COUNT;
630 goto out;
631 }
b46e756f
KS
632
633 /*
634 * Isolate the page to avoid collapsing an hugepage
635 * currently in use by the VM.
636 */
f7f9c00d 637 if (!isolate_lru_page(page)) {
b46e756f
KS
638 unlock_page(page);
639 result = SCAN_DEL_PAGE_LRU;
640 goto out;
641 }
5503fbf2
KS
642 mod_node_page_state(page_pgdat(page),
643 NR_ISOLATED_ANON + page_is_file_lru(page),
644 compound_nr(page));
b46e756f
KS
645 VM_BUG_ON_PAGE(!PageLocked(page), page);
646 VM_BUG_ON_PAGE(PageLRU(page), page);
647
5503fbf2
KS
648 if (PageCompound(page))
649 list_add_tail(&page->lru, compound_pagelist);
650next:
d8ea7cc8
ZK
651 /*
652 * If collapse was initiated by khugepaged, check that there is
653 * enough young pte to justify collapsing the page
654 */
655 if (cc->is_khugepaged &&
656 (pte_young(pteval) || page_is_young(page) ||
657 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
658 address)))
0db501f7 659 referenced++;
5503fbf2
KS
660
661 if (pte_write(pteval))
662 writable = true;
b46e756f 663 }
74e579bf
ML
664
665 if (unlikely(!writable)) {
b46e756f 666 result = SCAN_PAGE_RO;
d8ea7cc8 667 } else if (unlikely(cc->is_khugepaged && !referenced)) {
74e579bf
ML
668 result = SCAN_LACK_REFERENCED_PAGE;
669 } else {
670 result = SCAN_SUCCEED;
671 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
672 referenced, writable, result);
50ad2f24 673 return result;
b46e756f 674 }
b46e756f 675out:
5503fbf2 676 release_pte_pages(pte, _pte, compound_pagelist);
b46e756f
KS
677 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
678 referenced, writable, result);
50ad2f24 679 return result;
b46e756f
KS
680}
681
98c76c9f
JY
682static void __collapse_huge_page_copy_succeeded(pte_t *pte,
683 struct vm_area_struct *vma,
684 unsigned long address,
685 spinlock_t *ptl,
686 struct list_head *compound_pagelist)
b46e756f 687{
98c76c9f
JY
688 struct page *src_page;
689 struct page *tmp;
b46e756f 690 pte_t *_pte;
98c76c9f 691 pte_t pteval;
b46e756f 692
98c76c9f
JY
693 for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
694 _pte++, address += PAGE_SIZE) {
c33c7948 695 pteval = ptep_get(_pte);
b46e756f 696 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
b46e756f
KS
697 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
698 if (is_zero_pfn(pte_pfn(pteval))) {
699 /*
700 * ptl mostly unnecessary.
701 */
702 spin_lock(ptl);
08d5b29e 703 ptep_clear(vma->vm_mm, address, _pte);
b46e756f 704 spin_unlock(ptl);
6080d19f 705 ksm_might_unmap_zero_page(vma->vm_mm, pteval);
b46e756f
KS
706 }
707 } else {
708 src_page = pte_page(pteval);
5503fbf2
KS
709 if (!PageCompound(src_page))
710 release_pte_page(src_page);
b46e756f
KS
711 /*
712 * ptl mostly unnecessary, but preempt has to
713 * be disabled to update the per-cpu stats
714 * inside page_remove_rmap().
715 */
716 spin_lock(ptl);
08d5b29e 717 ptep_clear(vma->vm_mm, address, _pte);
cea86fe2 718 page_remove_rmap(src_page, vma, false);
b46e756f
KS
719 spin_unlock(ptl);
720 free_page_and_swap_cache(src_page);
721 }
b46e756f 722 }
5503fbf2
KS
723
724 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
725 list_del(&src_page->lru);
1baec203
ML
726 mod_node_page_state(page_pgdat(src_page),
727 NR_ISOLATED_ANON + page_is_file_lru(src_page),
728 -compound_nr(src_page));
729 unlock_page(src_page);
730 free_swap_cache(src_page);
731 putback_lru_page(src_page);
5503fbf2 732 }
b46e756f
KS
733}
734
98c76c9f
JY
735static void __collapse_huge_page_copy_failed(pte_t *pte,
736 pmd_t *pmd,
737 pmd_t orig_pmd,
738 struct vm_area_struct *vma,
739 struct list_head *compound_pagelist)
740{
741 spinlock_t *pmd_ptl;
742
743 /*
744 * Re-establish the PMD to point to the original page table
745 * entry. Restoring PMD needs to be done prior to releasing
746 * pages. Since pages are still isolated and locked here,
747 * acquiring anon_vma_lock_write is unnecessary.
748 */
749 pmd_ptl = pmd_lock(vma->vm_mm, pmd);
750 pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd));
751 spin_unlock(pmd_ptl);
752 /*
753 * Release both raw and compound pages isolated
754 * in __collapse_huge_page_isolate.
755 */
756 release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist);
757}
758
759/*
760 * __collapse_huge_page_copy - attempts to copy memory contents from raw
761 * pages to a hugepage. Cleans up the raw pages if copying succeeds;
762 * otherwise restores the original page table and releases isolated raw pages.
763 * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC.
764 *
765 * @pte: starting of the PTEs to copy from
766 * @page: the new hugepage to copy contents to
767 * @pmd: pointer to the new hugepage's PMD
768 * @orig_pmd: the original raw pages' PMD
769 * @vma: the original raw pages' virtual memory area
770 * @address: starting address to copy
771 * @ptl: lock on raw pages' PTEs
772 * @compound_pagelist: list that stores compound pages
773 */
774static int __collapse_huge_page_copy(pte_t *pte,
775 struct page *page,
776 pmd_t *pmd,
777 pmd_t orig_pmd,
778 struct vm_area_struct *vma,
779 unsigned long address,
780 spinlock_t *ptl,
781 struct list_head *compound_pagelist)
782{
783 struct page *src_page;
784 pte_t *_pte;
785 pte_t pteval;
786 unsigned long _address;
787 int result = SCAN_SUCCEED;
788
789 /*
790 * Copying pages' contents is subject to memory poison at any iteration.
791 */
792 for (_pte = pte, _address = address; _pte < pte + HPAGE_PMD_NR;
793 _pte++, page++, _address += PAGE_SIZE) {
c33c7948 794 pteval = ptep_get(_pte);
98c76c9f
JY
795 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
796 clear_user_highpage(page, _address);
797 continue;
798 }
799 src_page = pte_page(pteval);
800 if (copy_mc_user_highpage(page, src_page, _address, vma) > 0) {
801 result = SCAN_COPY_MC;
802 break;
803 }
804 }
805
806 if (likely(result == SCAN_SUCCEED))
807 __collapse_huge_page_copy_succeeded(pte, vma, address, ptl,
808 compound_pagelist);
809 else
810 __collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma,
811 compound_pagelist);
812
813 return result;
814}
815
b46e756f
KS
816static void khugepaged_alloc_sleep(void)
817{
818 DEFINE_WAIT(wait);
819
820 add_wait_queue(&khugepaged_wait, &wait);
f5d39b02
PZ
821 __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
822 schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
b46e756f
KS
823 remove_wait_queue(&khugepaged_wait, &wait);
824}
825
34d6b470 826struct collapse_control khugepaged_collapse_control = {
d8ea7cc8 827 .is_khugepaged = true,
34d6b470 828};
b46e756f 829
7d2c4385 830static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
b46e756f
KS
831{
832 int i;
833
834 /*
a5f5f91d 835 * If node_reclaim_mode is disabled, then no extra effort is made to
b46e756f
KS
836 * allocate memory locally.
837 */
202e35db 838 if (!node_reclaim_enabled())
b46e756f
KS
839 return false;
840
841 /* If there is a count for this node already, it must be acceptable */
34d6b470 842 if (cc->node_load[nid])
b46e756f
KS
843 return false;
844
845 for (i = 0; i < MAX_NUMNODES; i++) {
34d6b470 846 if (!cc->node_load[i])
b46e756f 847 continue;
a55c7454 848 if (node_distance(nid, i) > node_reclaim_distance)
b46e756f
KS
849 return true;
850 }
851 return false;
852}
853
1064026b
YS
854#define khugepaged_defrag() \
855 (transparent_hugepage_flags & \
856 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
857
b46e756f
KS
858/* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
859static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
860{
25160354 861 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
b46e756f
KS
862}
863
864#ifdef CONFIG_NUMA
7d2c4385 865static int hpage_collapse_find_target_node(struct collapse_control *cc)
b46e756f 866{
b46e756f
KS
867 int nid, target_node = 0, max_value = 0;
868
869 /* find first node with max normal pages hit */
870 for (nid = 0; nid < MAX_NUMNODES; nid++)
34d6b470
ZK
871 if (cc->node_load[nid] > max_value) {
872 max_value = cc->node_load[nid];
b46e756f
KS
873 target_node = nid;
874 }
875
e031ff96
YS
876 for_each_online_node(nid) {
877 if (max_value == cc->node_load[nid])
878 node_set(nid, cc->alloc_nmask);
879 }
b46e756f 880
b46e756f
KS
881 return target_node;
882}
c6a7f445 883#else
7d2c4385 884static int hpage_collapse_find_target_node(struct collapse_control *cc)
b46e756f 885{
c6a7f445 886 return 0;
b46e756f 887}
c6a7f445 888#endif
b46e756f 889
e031ff96
YS
890static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node,
891 nodemask_t *nmask)
b46e756f 892{
e031ff96 893 *hpage = __alloc_pages(gfp, HPAGE_PMD_ORDER, node, nmask);
b46e756f
KS
894 if (unlikely(!*hpage)) {
895 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
9710a78a 896 return false;
b46e756f
KS
897 }
898
da6e7bf3 899 folio_prep_large_rmappable((struct folio *)*hpage);
b46e756f 900 count_vm_event(THP_COLLAPSE_ALLOC);
b46e756f
KS
901 return true;
902}
903
b46e756f 904/*
c1e8d7c6
ML
905 * If mmap_lock temporarily dropped, revalidate vma
906 * before taking mmap_lock.
50ad2f24 907 * Returns enum scan_result value.
b46e756f
KS
908 */
909
c131f751 910static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
34488399 911 bool expect_anon,
a7f4e6e4
ZK
912 struct vm_area_struct **vmap,
913 struct collapse_control *cc)
b46e756f
KS
914{
915 struct vm_area_struct *vma;
b46e756f 916
7d2c4385 917 if (unlikely(hpage_collapse_test_exit(mm)))
b46e756f
KS
918 return SCAN_ANY_PROCESS;
919
c131f751 920 *vmap = vma = find_vma(mm, address);
b46e756f
KS
921 if (!vma)
922 return SCAN_VMA_NULL;
923
4fa6893f 924 if (!transhuge_vma_suitable(vma, address))
b46e756f 925 return SCAN_ADDRESS_RANGE;
a7f4e6e4
ZK
926 if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
927 cc->is_khugepaged))
b46e756f 928 return SCAN_VMA_CHECK;
f707fa49
YS
929 /*
930 * Anon VMA expected, the address may be unmapped then
931 * remapped to file after khugepaged reaquired the mmap_lock.
932 *
933 * hugepage_vma_check may return true for qualified file
934 * vmas.
935 */
34488399
ZK
936 if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
937 return SCAN_PAGE_ANON;
50ad2f24 938 return SCAN_SUCCEED;
b46e756f
KS
939}
940
50722804
ZK
941static int find_pmd_or_thp_or_none(struct mm_struct *mm,
942 unsigned long address,
943 pmd_t **pmd)
944{
945 pmd_t pmde;
946
947 *pmd = mm_find_pmd(mm, address);
948 if (!*pmd)
949 return SCAN_PMD_NULL;
950
dab6e717 951 pmde = pmdp_get_lockless(*pmd);
34488399
ZK
952 if (pmd_none(pmde))
953 return SCAN_PMD_NONE;
edb5d0cf
ZK
954 if (!pmd_present(pmde))
955 return SCAN_PMD_NULL;
50722804
ZK
956 if (pmd_trans_huge(pmde))
957 return SCAN_PMD_MAPPED;
edb5d0cf
ZK
958 if (pmd_devmap(pmde))
959 return SCAN_PMD_NULL;
50722804
ZK
960 if (pmd_bad(pmde))
961 return SCAN_PMD_NULL;
962 return SCAN_SUCCEED;
963}
964
965static int check_pmd_still_valid(struct mm_struct *mm,
966 unsigned long address,
967 pmd_t *pmd)
968{
969 pmd_t *new_pmd;
970 int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
971
972 if (result != SCAN_SUCCEED)
973 return result;
974 if (new_pmd != pmd)
975 return SCAN_FAIL;
976 return SCAN_SUCCEED;
b46e756f
KS
977}
978
979/*
980 * Bring missing pages in from swap, to complete THP collapse.
7d2c4385 981 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
b46e756f 982 *
4d928e20 983 * Called and returns without pte mapped or spinlocks held.
895f5ee4 984 * Returns result: if not SCAN_SUCCEED, mmap_lock has been released.
b46e756f 985 */
50ad2f24
ZK
986static int __collapse_huge_page_swapin(struct mm_struct *mm,
987 struct vm_area_struct *vma,
988 unsigned long haddr, pmd_t *pmd,
989 int referenced)
b46e756f 990{
2b740303
SJ
991 int swapped_in = 0;
992 vm_fault_t ret = 0;
2b635dd3 993 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
895f5ee4
HD
994 int result;
995 pte_t *pte = NULL;
c7ad0880 996 spinlock_t *ptl;
2b635dd3
WD
997
998 for (address = haddr; address < end; address += PAGE_SIZE) {
999 struct vm_fault vmf = {
1000 .vma = vma,
1001 .address = address,
895f5ee4 1002 .pgoff = linear_page_index(vma, address),
2b635dd3
WD
1003 .flags = FAULT_FLAG_ALLOW_RETRY,
1004 .pmd = pmd,
1005 };
1006
895f5ee4 1007 if (!pte++) {
c7ad0880 1008 pte = pte_offset_map_nolock(mm, pmd, address, &ptl);
895f5ee4
HD
1009 if (!pte) {
1010 mmap_read_unlock(mm);
1011 result = SCAN_PMD_NULL;
1012 goto out;
1013 }
2b635dd3 1014 }
895f5ee4 1015
c7ad0880 1016 vmf.orig_pte = ptep_get_lockless(pte);
895f5ee4
HD
1017 if (!is_swap_pte(vmf.orig_pte))
1018 continue;
1019
1020 vmf.pte = pte;
c7ad0880 1021 vmf.ptl = ptl;
2994302b 1022 ret = do_swap_page(&vmf);
895f5ee4
HD
1023 /* Which unmaps pte (after perhaps re-checking the entry) */
1024 pte = NULL;
0db501f7 1025
4d928e20
ML
1026 /*
1027 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
1028 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
1029 * we do not retry here and swap entry will remain in pagetable
1030 * resulting in later failure.
1031 */
b46e756f 1032 if (ret & VM_FAULT_RETRY) {
50ad2f24 1033 /* Likely, but not guaranteed, that page lock failed */
895f5ee4
HD
1034 result = SCAN_PAGE_LOCK;
1035 goto out;
b46e756f
KS
1036 }
1037 if (ret & VM_FAULT_ERROR) {
4d928e20 1038 mmap_read_unlock(mm);
895f5ee4
HD
1039 result = SCAN_FAIL;
1040 goto out;
b46e756f 1041 }
4d928e20 1042 swapped_in++;
b46e756f 1043 }
ae2c5d80 1044
895f5ee4
HD
1045 if (pte)
1046 pte_unmap(pte);
1047
1fec6890 1048 /* Drain LRU cache to remove extra pin on the swapped in pages */
ae2c5d80
KS
1049 if (swapped_in)
1050 lru_add_drain();
1051
895f5ee4
HD
1052 result = SCAN_SUCCEED;
1053out:
1054 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, result);
1055 return result;
b46e756f
KS
1056}
1057
9710a78a
ZK
1058static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
1059 struct collapse_control *cc)
1060{
7d8faaf1 1061 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
e031ff96 1062 GFP_TRANSHUGE);
7d2c4385 1063 int node = hpage_collapse_find_target_node(cc);
94c02ad7 1064 struct folio *folio;
9710a78a 1065
e031ff96 1066 if (!hpage_collapse_alloc_page(hpage, gfp, node, &cc->alloc_nmask))
9710a78a 1067 return SCAN_ALLOC_HUGE_PAGE_FAIL;
94c02ad7
PX
1068
1069 folio = page_folio(*hpage);
1070 if (unlikely(mem_cgroup_charge(folio, mm, gfp))) {
1071 folio_put(folio);
1072 *hpage = NULL;
9710a78a 1073 return SCAN_CGROUP_CHARGE_FAIL;
94c02ad7 1074 }
9710a78a 1075 count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
94c02ad7 1076
9710a78a
ZK
1077 return SCAN_SUCCEED;
1078}
1079
50ad2f24
ZK
1080static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
1081 int referenced, int unmapped,
1082 struct collapse_control *cc)
b46e756f 1083{
5503fbf2 1084 LIST_HEAD(compound_pagelist);
b46e756f
KS
1085 pmd_t *pmd, _pmd;
1086 pte_t *pte;
1087 pgtable_t pgtable;
50ad2f24 1088 struct page *hpage;
b46e756f 1089 spinlock_t *pmd_ptl, *pte_ptl;
50ad2f24 1090 int result = SCAN_FAIL;
c131f751 1091 struct vm_area_struct *vma;
ac46d4f3 1092 struct mmu_notifier_range range;
b46e756f
KS
1093
1094 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1095
988ddb71 1096 /*
c1e8d7c6 1097 * Before allocating the hugepage, release the mmap_lock read lock.
988ddb71 1098 * The allocation can take potentially a long time if it involves
c1e8d7c6 1099 * sync compaction, and we do not need to hold the mmap_lock during
988ddb71
KS
1100 * that. We will recheck the vma after taking it again in write mode.
1101 */
d8ed45c5 1102 mmap_read_unlock(mm);
b46e756f 1103
50ad2f24 1104 result = alloc_charge_hpage(&hpage, mm, cc);
9710a78a 1105 if (result != SCAN_SUCCEED)
b46e756f 1106 goto out_nolock;
b46e756f 1107
d8ed45c5 1108 mmap_read_lock(mm);
34488399 1109 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
50ad2f24 1110 if (result != SCAN_SUCCEED) {
d8ed45c5 1111 mmap_read_unlock(mm);
b46e756f
KS
1112 goto out_nolock;
1113 }
1114
50722804
ZK
1115 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1116 if (result != SCAN_SUCCEED) {
d8ed45c5 1117 mmap_read_unlock(mm);
b46e756f
KS
1118 goto out_nolock;
1119 }
1120
50ad2f24
ZK
1121 if (unmapped) {
1122 /*
1123 * __collapse_huge_page_swapin will return with mmap_lock
1124 * released when it fails. So we jump out_nolock directly in
1125 * that case. Continuing to collapse causes inconsistency.
1126 */
1127 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1128 referenced);
1129 if (result != SCAN_SUCCEED)
1130 goto out_nolock;
b46e756f
KS
1131 }
1132
d8ed45c5 1133 mmap_read_unlock(mm);
b46e756f
KS
1134 /*
1135 * Prevent all access to pagetables with the exception of
1136 * gup_fast later handled by the ptep_clear_flush and the VM
1137 * handled by the anon_vma lock + PG_lock.
1138 */
d8ed45c5 1139 mmap_write_lock(mm);
34488399 1140 result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
50ad2f24 1141 if (result != SCAN_SUCCEED)
18d24a7c 1142 goto out_up_write;
b46e756f 1143 /* check if the pmd is still valid */
50722804
ZK
1144 result = check_pmd_still_valid(mm, address, pmd);
1145 if (result != SCAN_SUCCEED)
18d24a7c 1146 goto out_up_write;
b46e756f 1147
55fd6fcc 1148 vma_start_write(vma);
b46e756f
KS
1149 anon_vma_lock_write(vma->anon_vma);
1150
7d4a8be0
AP
1151 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
1152 address + HPAGE_PMD_SIZE);
ac46d4f3 1153 mmu_notifier_invalidate_range_start(&range);
ec649c9d 1154
b46e756f
KS
1155 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1156 /*
70cbc3cc
YS
1157 * This removes any huge TLB entry from the CPU so we won't allow
1158 * huge and small TLB entries for the same virtual address to
1159 * avoid the risk of CPU bugs in that area.
1160 *
1161 * Parallel fast GUP is fine since fast GUP will back off when
1162 * it detects PMD is changed.
b46e756f
KS
1163 */
1164 _pmd = pmdp_collapse_flush(vma, address, pmd);
1165 spin_unlock(pmd_ptl);
ac46d4f3 1166 mmu_notifier_invalidate_range_end(&range);
2ba99c5e 1167 tlb_remove_table_sync_one();
b46e756f 1168
895f5ee4
HD
1169 pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl);
1170 if (pte) {
1171 result = __collapse_huge_page_isolate(vma, address, pte, cc,
1172 &compound_pagelist);
1173 spin_unlock(pte_ptl);
1174 } else {
1175 result = SCAN_PMD_NULL;
1176 }
b46e756f 1177
50ad2f24 1178 if (unlikely(result != SCAN_SUCCEED)) {
895f5ee4
HD
1179 if (pte)
1180 pte_unmap(pte);
b46e756f
KS
1181 spin_lock(pmd_ptl);
1182 BUG_ON(!pmd_none(*pmd));
1183 /*
1184 * We can only use set_pmd_at when establishing
1185 * hugepmds and never for establishing regular pmds that
1186 * points to regular pagetables. Use pmd_populate for that
1187 */
1188 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1189 spin_unlock(pmd_ptl);
1190 anon_vma_unlock_write(vma->anon_vma);
18d24a7c 1191 goto out_up_write;
b46e756f
KS
1192 }
1193
1194 /*
1195 * All pages are isolated and locked so anon_vma rmap
1196 * can't run anymore.
1197 */
1198 anon_vma_unlock_write(vma->anon_vma);
1199
98c76c9f
JY
1200 result = __collapse_huge_page_copy(pte, hpage, pmd, _pmd,
1201 vma, address, pte_ptl,
1202 &compound_pagelist);
b46e756f 1203 pte_unmap(pte);
98c76c9f
JY
1204 if (unlikely(result != SCAN_SUCCEED))
1205 goto out_up_write;
1206
588d01f9
ML
1207 /*
1208 * spin_lock() below is not the equivalent of smp_wmb(), but
1209 * the smp_wmb() inside __SetPageUptodate() can be reused to
1210 * avoid the copy_huge_page writes to become visible after
1211 * the set_pmd_at() write.
1212 */
50ad2f24 1213 __SetPageUptodate(hpage);
b46e756f
KS
1214 pgtable = pmd_pgtable(_pmd);
1215
50ad2f24 1216 _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
f55e1014 1217 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
b46e756f 1218
b46e756f
KS
1219 spin_lock(pmd_ptl);
1220 BUG_ON(!pmd_none(*pmd));
50ad2f24
ZK
1221 page_add_new_anon_rmap(hpage, vma, address);
1222 lru_cache_add_inactive_or_unevictable(hpage, vma);
b46e756f
KS
1223 pgtable_trans_huge_deposit(mm, pmd, pgtable);
1224 set_pmd_at(mm, address, pmd, _pmd);
1225 update_mmu_cache_pmd(vma, address, pmd);
1226 spin_unlock(pmd_ptl);
1227
50ad2f24 1228 hpage = NULL;
b46e756f 1229
b46e756f
KS
1230 result = SCAN_SUCCEED;
1231out_up_write:
d8ed45c5 1232 mmap_write_unlock(mm);
b46e756f 1233out_nolock:
7cb1d7ef 1234 if (hpage)
50ad2f24 1235 put_page(hpage);
50ad2f24
ZK
1236 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1237 return result;
b46e756f
KS
1238}
1239
7d2c4385
ZK
1240static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1241 struct vm_area_struct *vma,
1242 unsigned long address, bool *mmap_locked,
1243 struct collapse_control *cc)
b46e756f
KS
1244{
1245 pmd_t *pmd;
1246 pte_t *pte, *_pte;
50ad2f24 1247 int result = SCAN_FAIL, referenced = 0;
71a2c112 1248 int none_or_zero = 0, shared = 0;
b46e756f
KS
1249 struct page *page = NULL;
1250 unsigned long _address;
1251 spinlock_t *ptl;
1252 int node = NUMA_NO_NODE, unmapped = 0;
0db501f7 1253 bool writable = false;
b46e756f
KS
1254
1255 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1256
50722804
ZK
1257 result = find_pmd_or_thp_or_none(mm, address, &pmd);
1258 if (result != SCAN_SUCCEED)
b46e756f 1259 goto out;
b46e756f 1260
34d6b470 1261 memset(cc->node_load, 0, sizeof(cc->node_load));
e031ff96 1262 nodes_clear(cc->alloc_nmask);
b46e756f 1263 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
895f5ee4
HD
1264 if (!pte) {
1265 result = SCAN_PMD_NULL;
1266 goto out;
1267 }
1268
36ee2c78 1269 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
b46e756f 1270 _pte++, _address += PAGE_SIZE) {
c33c7948 1271 pte_t pteval = ptep_get(_pte);
b46e756f 1272 if (is_swap_pte(pteval)) {
d8ea7cc8
ZK
1273 ++unmapped;
1274 if (!cc->is_khugepaged ||
1275 unmapped <= khugepaged_max_ptes_swap) {
e1e267c7
PX
1276 /*
1277 * Always be strict with uffd-wp
1278 * enabled swap entries. Please see
1279 * comment below for pte_uffd_wp().
1280 */
2bad466c 1281 if (pte_swp_uffd_wp_any(pteval)) {
e1e267c7
PX
1282 result = SCAN_PTE_UFFD_WP;
1283 goto out_unmap;
1284 }
b46e756f
KS
1285 continue;
1286 } else {
1287 result = SCAN_EXCEED_SWAP_PTE;
e9ea874a 1288 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
b46e756f
KS
1289 goto out_unmap;
1290 }
1291 }
1292 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
d8ea7cc8 1293 ++none_or_zero;
b46e756f 1294 if (!userfaultfd_armed(vma) &&
d8ea7cc8
ZK
1295 (!cc->is_khugepaged ||
1296 none_or_zero <= khugepaged_max_ptes_none)) {
b46e756f
KS
1297 continue;
1298 } else {
1299 result = SCAN_EXCEED_NONE_PTE;
e9ea874a 1300 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
b46e756f
KS
1301 goto out_unmap;
1302 }
1303 }
e1e267c7
PX
1304 if (pte_uffd_wp(pteval)) {
1305 /*
1306 * Don't collapse the page if any of the small
1307 * PTEs are armed with uffd write protection.
1308 * Here we can also mark the new huge pmd as
1309 * write protected if any of the small ones is
8958b249 1310 * marked but that could bring unknown
e1e267c7
PX
1311 * userfault messages that falls outside of
1312 * the registered range. So, just be simple.
1313 */
1314 result = SCAN_PTE_UFFD_WP;
1315 goto out_unmap;
1316 }
b46e756f
KS
1317 if (pte_write(pteval))
1318 writable = true;
1319
1320 page = vm_normal_page(vma, _address, pteval);
3218f871 1321 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
b46e756f
KS
1322 result = SCAN_PAGE_NULL;
1323 goto out_unmap;
1324 }
1325
d8ea7cc8
ZK
1326 if (page_mapcount(page) > 1) {
1327 ++shared;
1328 if (cc->is_khugepaged &&
1329 shared > khugepaged_max_ptes_shared) {
1330 result = SCAN_EXCEED_SHARED_PTE;
1331 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1332 goto out_unmap;
1333 }
71a2c112
KS
1334 }
1335
5503fbf2 1336 page = compound_head(page);
b46e756f
KS
1337
1338 /*
1339 * Record which node the original page is from and save this
34d6b470 1340 * information to cc->node_load[].
0b8f0d87 1341 * Khugepaged will allocate hugepage from the node has the max
b46e756f
KS
1342 * hit record.
1343 */
1344 node = page_to_nid(page);
7d2c4385 1345 if (hpage_collapse_scan_abort(node, cc)) {
b46e756f
KS
1346 result = SCAN_SCAN_ABORT;
1347 goto out_unmap;
1348 }
34d6b470 1349 cc->node_load[node]++;
b46e756f
KS
1350 if (!PageLRU(page)) {
1351 result = SCAN_PAGE_LRU;
1352 goto out_unmap;
1353 }
1354 if (PageLocked(page)) {
1355 result = SCAN_PAGE_LOCK;
1356 goto out_unmap;
1357 }
1358 if (!PageAnon(page)) {
1359 result = SCAN_PAGE_ANON;
1360 goto out_unmap;
1361 }
1362
1363 /*
9445689f
KS
1364 * Check if the page has any GUP (or other external) pins.
1365 *
cb67f428
HD
1366 * Here the check may be racy:
1367 * it may see total_mapcount > refcount in some cases?
9445689f
KS
1368 * But such case is ephemeral we could always retry collapse
1369 * later. However it may report false positive if the page
1370 * has excessive GUP pins (i.e. 512). Anyway the same check
1371 * will be done again later the risk seems low.
b46e756f 1372 */
9445689f 1373 if (!is_refcount_suitable(page)) {
b46e756f
KS
1374 result = SCAN_PAGE_COUNT;
1375 goto out_unmap;
1376 }
d8ea7cc8
ZK
1377
1378 /*
1379 * If collapse was initiated by khugepaged, check that there is
1380 * enough young pte to justify collapsing the page
1381 */
1382 if (cc->is_khugepaged &&
1383 (pte_young(pteval) || page_is_young(page) ||
1384 PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1385 address)))
0db501f7 1386 referenced++;
b46e756f 1387 }
ffe945e6 1388 if (!writable) {
b46e756f 1389 result = SCAN_PAGE_RO;
d8ea7cc8
ZK
1390 } else if (cc->is_khugepaged &&
1391 (!referenced ||
1392 (unmapped && referenced < HPAGE_PMD_NR / 2))) {
ffe945e6
KS
1393 result = SCAN_LACK_REFERENCED_PAGE;
1394 } else {
1395 result = SCAN_SUCCEED;
b46e756f
KS
1396 }
1397out_unmap:
1398 pte_unmap_unlock(pte, ptl);
50ad2f24
ZK
1399 if (result == SCAN_SUCCEED) {
1400 result = collapse_huge_page(mm, address, referenced,
1401 unmapped, cc);
c1e8d7c6 1402 /* collapse_huge_page will return with the mmap_lock released */
50ad2f24 1403 *mmap_locked = false;
b46e756f
KS
1404 }
1405out:
1406 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1407 none_or_zero, result, unmapped);
50ad2f24 1408 return result;
b46e756f
KS
1409}
1410
b26e2701 1411static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
b46e756f 1412{
b26e2701
QZ
1413 struct mm_slot *slot = &mm_slot->slot;
1414 struct mm_struct *mm = slot->mm;
b46e756f 1415
35f3aa39 1416 lockdep_assert_held(&khugepaged_mm_lock);
b46e756f 1417
7d2c4385 1418 if (hpage_collapse_test_exit(mm)) {
b46e756f 1419 /* free mm_slot */
b26e2701
QZ
1420 hash_del(&slot->hash);
1421 list_del(&slot->mm_node);
b46e756f
KS
1422
1423 /*
1424 * Not strictly needed because the mm exited already.
1425 *
1426 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1427 */
1428
1429 /* khugepaged_mm_lock actually not necessary for the below */
b26e2701 1430 mm_slot_free(mm_slot_cache, mm_slot);
b46e756f
KS
1431 mmdrop(mm);
1432 }
1433}
1434
396bcc52 1435#ifdef CONFIG_SHMEM
1043173e 1436/* hpage must be locked, and mmap_lock must be held */
34488399
ZK
1437static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1438 pmd_t *pmdp, struct page *hpage)
1439{
1440 struct vm_fault vmf = {
1441 .vma = vma,
1442 .address = addr,
1443 .flags = 0,
1444 .pmd = pmdp,
1445 };
1446
1447 VM_BUG_ON(!PageTransHuge(hpage));
1043173e 1448 mmap_assert_locked(vma->vm_mm);
34488399
ZK
1449
1450 if (do_set_pmd(&vmf, hpage))
1451 return SCAN_FAIL;
1452
1453 get_page(hpage);
1454 return SCAN_SUCCEED;
27e1f827
SL
1455}
1456
1457/**
336e6b53
AS
1458 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1459 * address haddr.
1460 *
1461 * @mm: process address space where collapse happens
1462 * @addr: THP collapse address
34488399 1463 * @install_pmd: If a huge PMD should be installed
27e1f827
SL
1464 *
1465 * This function checks whether all the PTEs in the PMD are pointing to the
1466 * right THP. If so, retract the page table so the THP can refault in with
34488399 1467 * as pmd-mapped. Possibly install a huge PMD mapping the THP.
27e1f827 1468 */
34488399
ZK
1469int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1470 bool install_pmd)
27e1f827 1471{
1043173e
HD
1472 struct mmu_notifier_range range;
1473 bool notified = false;
27e1f827 1474 unsigned long haddr = addr & HPAGE_PMD_MASK;
94d815b2 1475 struct vm_area_struct *vma = vma_lookup(mm, haddr);
119a5fc1 1476 struct page *hpage;
27e1f827 1477 pte_t *start_pte, *pte;
1043173e 1478 pmd_t *pmd, pgt_pmd;
a9846049 1479 spinlock_t *pml = NULL, *ptl;
1043173e 1480 int nr_ptes = 0, result = SCAN_FAIL;
27e1f827
SL
1481 int i;
1482
1043173e
HD
1483 mmap_assert_locked(mm);
1484
1485 /* First check VMA found, in case page tables are being torn down */
1486 if (!vma || !vma->vm_file ||
1487 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1488 return SCAN_VMA_CHECK;
58ac9a89 1489
34488399 1490 /* Fast check before locking page if already PMD-mapped */
58ac9a89 1491 result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
34488399
ZK
1492 if (result == SCAN_PMD_MAPPED)
1493 return result;
58ac9a89 1494
27e1f827 1495 /*
a7f4e6e4
ZK
1496 * If we are here, we've succeeded in replacing all the native pages
1497 * in the page cache with a single hugepage. If a mm were to fault-in
1498 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1499 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1500 * analogously elide sysfs THP settings here.
27e1f827 1501 */
a7f4e6e4 1502 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
34488399 1503 return SCAN_VMA_CHECK;
27e1f827 1504
deb4c93a
PX
1505 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1506 if (userfaultfd_wp(vma))
34488399 1507 return SCAN_PTE_UFFD_WP;
deb4c93a 1508
119a5fc1
HD
1509 hpage = find_lock_page(vma->vm_file->f_mapping,
1510 linear_page_index(vma, haddr));
1511 if (!hpage)
34488399 1512 return SCAN_PAGE_NULL;
119a5fc1 1513
34488399
ZK
1514 if (!PageHead(hpage)) {
1515 result = SCAN_FAIL;
119a5fc1 1516 goto drop_hpage;
34488399 1517 }
119a5fc1 1518
34488399
ZK
1519 if (compound_order(hpage) != HPAGE_PMD_ORDER) {
1520 result = SCAN_PAGE_COMPOUND;
119a5fc1 1521 goto drop_hpage;
34488399 1522 }
119a5fc1 1523
1043173e 1524 result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
34488399
ZK
1525 switch (result) {
1526 case SCAN_SUCCEED:
1527 break;
1528 case SCAN_PMD_NONE:
1529 /*
1d65b771
HD
1530 * All pte entries have been removed and pmd cleared.
1531 * Skip all the pte checks and just update the pmd mapping.
34488399
ZK
1532 */
1533 goto maybe_install_pmd;
1534 default:
119a5fc1 1535 goto drop_hpage;
34488399 1536 }
27e1f827 1537
34488399 1538 result = SCAN_FAIL;
895f5ee4 1539 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1043173e
HD
1540 if (!start_pte) /* mmap_lock + page lock should prevent this */
1541 goto drop_hpage;
27e1f827
SL
1542
1543 /* step 1: check all mapped PTEs are to the right huge page */
1544 for (i = 0, addr = haddr, pte = start_pte;
1545 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1546 struct page *page;
c33c7948 1547 pte_t ptent = ptep_get(pte);
27e1f827
SL
1548
1549 /* empty pte, skip */
c33c7948 1550 if (pte_none(ptent))
27e1f827
SL
1551 continue;
1552
1553 /* page swapped out, abort */
c33c7948 1554 if (!pte_present(ptent)) {
34488399 1555 result = SCAN_PTE_NON_PRESENT;
27e1f827 1556 goto abort;
34488399 1557 }
27e1f827 1558
c33c7948 1559 page = vm_normal_page(vma, addr, ptent);
3218f871
AS
1560 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1561 page = NULL;
27e1f827 1562 /*
119a5fc1
HD
1563 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1564 * page table, but the new page will not be a subpage of hpage.
27e1f827 1565 */
119a5fc1 1566 if (hpage + i != page)
27e1f827 1567 goto abort;
27e1f827
SL
1568 }
1569
1043173e
HD
1570 pte_unmap_unlock(start_pte, ptl);
1571 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1572 haddr, haddr + HPAGE_PMD_SIZE);
1573 mmu_notifier_invalidate_range_start(&range);
1574 notified = true;
a9846049
HD
1575
1576 /*
1577 * pmd_lock covers a wider range than ptl, and (if split from mm's
1578 * page_table_lock) ptl nests inside pml. The less time we hold pml,
1579 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA
1580 * inserts a valid as-if-COWed PTE without even looking up page cache.
1581 * So page lock of hpage does not protect from it, so we must not drop
1582 * ptl before pgt_pmd is removed, so uffd private needs pml taken now.
1583 */
1584 if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED))
1585 pml = pmd_lock(mm, pmd);
1586
1587 start_pte = pte_offset_map_nolock(mm, pmd, haddr, &ptl);
1043173e
HD
1588 if (!start_pte) /* mmap_lock + page lock should prevent this */
1589 goto abort;
a9846049
HD
1590 if (!pml)
1591 spin_lock(ptl);
1592 else if (ptl != pml)
1593 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1043173e
HD
1594
1595 /* step 2: clear page table and adjust rmap */
27e1f827
SL
1596 for (i = 0, addr = haddr, pte = start_pte;
1597 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1598 struct page *page;
c33c7948 1599 pte_t ptent = ptep_get(pte);
27e1f827 1600
c33c7948 1601 if (pte_none(ptent))
27e1f827 1602 continue;
1043173e
HD
1603 /*
1604 * We dropped ptl after the first scan, to do the mmu_notifier:
1605 * page lock stops more PTEs of the hpage being faulted in, but
1606 * does not stop write faults COWing anon copies from existing
1607 * PTEs; and does not stop those being swapped out or migrated.
1608 */
1609 if (!pte_present(ptent)) {
1610 result = SCAN_PTE_NON_PRESENT;
1611 goto abort;
1612 }
c33c7948 1613 page = vm_normal_page(vma, addr, ptent);
1043173e 1614 if (hpage + i != page)
3218f871 1615 goto abort;
1043173e
HD
1616
1617 /*
1618 * Must clear entry, or a racing truncate may re-remove it.
1619 * TLB flush can be left until pmdp_collapse_flush() does it.
1620 * PTE dirty? Shmem page is already dirty; file is read-only.
1621 */
1622 ptep_clear(mm, addr, pte);
cea86fe2 1623 page_remove_rmap(page, vma, false);
1043173e 1624 nr_ptes++;
27e1f827
SL
1625 }
1626
a9846049
HD
1627 pte_unmap(start_pte);
1628 if (!pml)
1629 spin_unlock(ptl);
27e1f827
SL
1630
1631 /* step 3: set proper refcount and mm_counters. */
1043173e
HD
1632 if (nr_ptes) {
1633 page_ref_sub(hpage, nr_ptes);
1634 add_mm_counter(mm, mm_counter_file(hpage), -nr_ptes);
27e1f827
SL
1635 }
1636
a9846049
HD
1637 /* step 4: remove empty page table */
1638 if (!pml) {
1639 pml = pmd_lock(mm, pmd);
1640 if (ptl != pml)
1641 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1642 }
1043173e
HD
1643 pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd);
1644 pmdp_get_lockless_sync();
1645 if (ptl != pml)
1646 spin_unlock(ptl);
1647 spin_unlock(pml);
ab0c3f12 1648
1043173e 1649 mmu_notifier_invalidate_range_end(&range);
34488399 1650
1043173e
HD
1651 mm_dec_nr_ptes(mm);
1652 page_table_check_pte_clear_range(mm, haddr, pgt_pmd);
1653 pte_free_defer(mm, pmd_pgtable(pgt_pmd));
8d3c106e 1654
34488399
ZK
1655maybe_install_pmd:
1656 /* step 5: install pmd entry */
1657 result = install_pmd
1658 ? set_huge_pmd(vma, haddr, pmd, hpage)
1659 : SCAN_SUCCEED;
1043173e
HD
1660 goto drop_hpage;
1661abort:
1662 if (nr_ptes) {
1663 flush_tlb_mm(mm);
1664 page_ref_sub(hpage, nr_ptes);
1665 add_mm_counter(mm, mm_counter_file(hpage), -nr_ptes);
1666 }
1667 if (start_pte)
1668 pte_unmap_unlock(start_pte, ptl);
a9846049
HD
1669 if (pml && pml != ptl)
1670 spin_unlock(pml);
1043173e
HD
1671 if (notified)
1672 mmu_notifier_invalidate_range_end(&range);
119a5fc1
HD
1673drop_hpage:
1674 unlock_page(hpage);
1675 put_page(hpage);
34488399 1676 return result;
27e1f827
SL
1677}
1678
1d65b771 1679static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
f3f0e1d2
KS
1680{
1681 struct vm_area_struct *vma;
f3f0e1d2 1682
1d65b771 1683 i_mmap_lock_read(mapping);
f3f0e1d2 1684 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1d65b771
HD
1685 struct mmu_notifier_range range;
1686 struct mm_struct *mm;
1687 unsigned long addr;
1688 pmd_t *pmd, pgt_pmd;
1689 spinlock_t *pml;
1690 spinlock_t *ptl;
1691 bool skipped_uffd = false;
34488399 1692
27e1f827
SL
1693 /*
1694 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1d65b771
HD
1695 * got written to. These VMAs are likely not worth removing
1696 * page tables from, as PMD-mapping is likely to be split later.
27e1f827 1697 */
1d65b771
HD
1698 if (READ_ONCE(vma->anon_vma))
1699 continue;
1700
f3f0e1d2 1701 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
34488399 1702 if (addr & ~HPAGE_PMD_MASK ||
1d65b771
HD
1703 vma->vm_end < addr + HPAGE_PMD_SIZE)
1704 continue;
1705
18e77600 1706 mm = vma->vm_mm;
1d65b771
HD
1707 if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED)
1708 continue;
1709
1710 if (hpage_collapse_test_exit(mm))
1711 continue;
f3f0e1d2 1712 /*
1d65b771
HD
1713 * When a vma is registered with uffd-wp, we cannot recycle
1714 * the page table because there may be pte markers installed.
1715 * Other vmas can still have the same file mapped hugely, but
1716 * skip this one: it will always be mapped in small page size
1717 * for uffd-wp registered ranges.
f3f0e1d2 1718 */
1d65b771
HD
1719 if (userfaultfd_wp(vma))
1720 continue;
1721
1722 /* PTEs were notified when unmapped; but now for the PMD? */
1723 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1724 addr, addr + HPAGE_PMD_SIZE);
1725 mmu_notifier_invalidate_range_start(&range);
1726
1727 pml = pmd_lock(mm, pmd);
1728 ptl = pte_lockptr(mm, pmd);
1729 if (ptl != pml)
1730 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
55fd6fcc 1731
34488399 1732 /*
1d65b771
HD
1733 * Huge page lock is still held, so normally the page table
1734 * must remain empty; and we have already skipped anon_vma
1735 * and userfaultfd_wp() vmas. But since the mmap_lock is not
1736 * held, it is still possible for a racing userfaultfd_ioctl()
1737 * to have inserted ptes or markers. Now that we hold ptlock,
1738 * repeating the anon_vma check protects from one category,
1739 * and repeating the userfaultfd_wp() check from another.
34488399 1740 */
1d65b771
HD
1741 if (unlikely(vma->anon_vma || userfaultfd_wp(vma))) {
1742 skipped_uffd = true;
1743 } else {
1744 pgt_pmd = pmdp_collapse_flush(vma, addr, pmd);
1745 pmdp_get_lockless_sync();
1746 }
1747
1748 if (ptl != pml)
1749 spin_unlock(ptl);
1750 spin_unlock(pml);
1751
1752 mmu_notifier_invalidate_range_end(&range);
1753
1754 if (!skipped_uffd) {
1755 mm_dec_nr_ptes(mm);
1756 page_table_check_pte_clear_range(mm, addr, pgt_pmd);
1757 pte_free_defer(mm, pmd_pgtable(pgt_pmd));
f3f0e1d2
KS
1758 }
1759 }
1d65b771 1760 i_mmap_unlock_read(mapping);
f3f0e1d2
KS
1761}
1762
1763/**
99cb0dbd 1764 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
f3f0e1d2 1765 *
336e6b53 1766 * @mm: process address space where collapse happens
34488399 1767 * @addr: virtual collapse start address
336e6b53
AS
1768 * @file: file that collapse on
1769 * @start: collapse start address
9710a78a 1770 * @cc: collapse context and scratchpad
336e6b53 1771 *
f3f0e1d2 1772 * Basic scheme is simple, details are more complex:
87c460a0 1773 * - allocate and lock a new huge page;
a2e17cc2 1774 * - scan page cache, locking old pages
99cb0dbd 1775 * + swap/gup in pages if necessary;
a2e17cc2
DS
1776 * - copy data to new page
1777 * - handle shmem holes
1778 * + re-validate that holes weren't filled by someone else
1779 * + check for userfaultfd
ac492b9c 1780 * - finalize updates to the page cache;
77da9389 1781 * - if replacing succeeds:
87c460a0 1782 * + unlock huge page;
a2e17cc2 1783 * + free old pages;
f3f0e1d2 1784 * - if replacing failed;
a2e17cc2 1785 * + unlock old pages
87c460a0 1786 * + unlock and free huge page;
f3f0e1d2 1787 */
34488399
ZK
1788static int collapse_file(struct mm_struct *mm, unsigned long addr,
1789 struct file *file, pgoff_t start,
1790 struct collapse_control *cc)
f3f0e1d2 1791{
579c571e 1792 struct address_space *mapping = file->f_mapping;
50ad2f24 1793 struct page *hpage;
12904d95
JY
1794 struct page *page;
1795 struct page *tmp;
1796 struct folio *folio;
4c9473e8 1797 pgoff_t index = 0, end = start + HPAGE_PMD_NR;
f3f0e1d2 1798 LIST_HEAD(pagelist);
77da9389 1799 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
f3f0e1d2 1800 int nr_none = 0, result = SCAN_SUCCEED;
99cb0dbd 1801 bool is_shmem = shmem_file(file);
4c9473e8 1802 int nr = 0;
f3f0e1d2 1803
99cb0dbd 1804 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
f3f0e1d2
KS
1805 VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1806
50ad2f24 1807 result = alloc_charge_hpage(&hpage, mm, cc);
9710a78a 1808 if (result != SCAN_SUCCEED)
f3f0e1d2 1809 goto out;
f3f0e1d2 1810
cae106dd
DS
1811 __SetPageLocked(hpage);
1812 if (is_shmem)
1813 __SetPageSwapBacked(hpage);
1814 hpage->index = start;
1815 hpage->mapping = mapping;
1816
6b24ca4a
MWO
1817 /*
1818 * Ensure we have slots for all the pages in the range. This is
1819 * almost certainly a no-op because most of the pages must be present
1820 */
95feeabb
HD
1821 do {
1822 xas_lock_irq(&xas);
1823 xas_create_range(&xas);
1824 if (!xas_error(&xas))
1825 break;
1826 xas_unlock_irq(&xas);
1827 if (!xas_nomem(&xas, GFP_KERNEL)) {
95feeabb 1828 result = SCAN_FAIL;
cae106dd 1829 goto rollback;
95feeabb
HD
1830 }
1831 } while (1);
1832
77da9389 1833 for (index = start; index < end; index++) {
e8c716bc
HD
1834 xas_set(&xas, index);
1835 page = xas_load(&xas);
77da9389
MW
1836
1837 VM_BUG_ON(index != xas.xa_index);
99cb0dbd
SL
1838 if (is_shmem) {
1839 if (!page) {
1840 /*
1841 * Stop if extent has been truncated or
1842 * hole-punched, and is now completely
1843 * empty.
1844 */
1845 if (index == start) {
1846 if (!xas_next_entry(&xas, end - 1)) {
1847 result = SCAN_TRUNCATED;
1848 goto xa_locked;
1849 }
99cb0dbd 1850 }
99cb0dbd
SL
1851 nr_none++;
1852 continue;
701270fa 1853 }
99cb0dbd
SL
1854
1855 if (xa_is_value(page) || !PageUptodate(page)) {
1856 xas_unlock_irq(&xas);
1857 /* swap in or instantiate fallocated page */
7459c149
MWO
1858 if (shmem_get_folio(mapping->host, index,
1859 &folio, SGP_NOALLOC)) {
99cb0dbd
SL
1860 result = SCAN_FAIL;
1861 goto xa_unlocked;
1862 }
1fec6890 1863 /* drain lru cache to help isolate_lru_page() */
efa3d814 1864 lru_add_drain();
7459c149 1865 page = folio_file_page(folio, index);
99cb0dbd
SL
1866 } else if (trylock_page(page)) {
1867 get_page(page);
1868 xas_unlock_irq(&xas);
1869 } else {
1870 result = SCAN_PAGE_LOCK;
042a3082 1871 goto xa_locked;
77da9389 1872 }
99cb0dbd
SL
1873 } else { /* !is_shmem */
1874 if (!page || xa_is_value(page)) {
1875 xas_unlock_irq(&xas);
1876 page_cache_sync_readahead(mapping, &file->f_ra,
1877 file, index,
e5a59d30 1878 end - index);
1fec6890 1879 /* drain lru cache to help isolate_lru_page() */
99cb0dbd
SL
1880 lru_add_drain();
1881 page = find_lock_page(mapping, index);
1882 if (unlikely(page == NULL)) {
1883 result = SCAN_FAIL;
1884 goto xa_unlocked;
1885 }
75f36069
SL
1886 } else if (PageDirty(page)) {
1887 /*
1888 * khugepaged only works on read-only fd,
1889 * so this page is dirty because it hasn't
1890 * been flushed since first write. There
1891 * won't be new dirty pages.
1892 *
1893 * Trigger async flush here and hope the
1894 * writeback is done when khugepaged
1895 * revisits this page.
1896 *
1897 * This is a one-off situation. We are not
1898 * forcing writeback in loop.
1899 */
1900 xas_unlock_irq(&xas);
1901 filemap_flush(mapping);
1902 result = SCAN_FAIL;
1903 goto xa_unlocked;
74c42e1b
RW
1904 } else if (PageWriteback(page)) {
1905 xas_unlock_irq(&xas);
1906 result = SCAN_FAIL;
1907 goto xa_unlocked;
99cb0dbd
SL
1908 } else if (trylock_page(page)) {
1909 get_page(page);
1910 xas_unlock_irq(&xas);
1911 } else {
1912 result = SCAN_PAGE_LOCK;
1913 goto xa_locked;
f3f0e1d2 1914 }
f3f0e1d2
KS
1915 }
1916
1917 /*
b93b0163 1918 * The page must be locked, so we can drop the i_pages lock
f3f0e1d2
KS
1919 * without racing with truncate.
1920 */
1921 VM_BUG_ON_PAGE(!PageLocked(page), page);
4655e5e5
SL
1922
1923 /* make sure the page is up to date */
1924 if (unlikely(!PageUptodate(page))) {
1925 result = SCAN_FAIL;
1926 goto out_unlock;
1927 }
06a5e126
HD
1928
1929 /*
1930 * If file was truncated then extended, or hole-punched, before
1931 * we locked the first page, then a THP might be there already.
58ac9a89 1932 * This will be discovered on the first iteration.
06a5e126
HD
1933 */
1934 if (PageTransCompound(page)) {
58ac9a89
ZK
1935 struct page *head = compound_head(page);
1936
1937 result = compound_order(head) == HPAGE_PMD_ORDER &&
1938 head->index == start
1939 /* Maybe PMD-mapped */
1940 ? SCAN_PTE_MAPPED_HUGEPAGE
1941 : SCAN_PAGE_COMPOUND;
06a5e126
HD
1942 goto out_unlock;
1943 }
f3f0e1d2 1944
64ab3195
VMO
1945 folio = page_folio(page);
1946
1947 if (folio_mapping(folio) != mapping) {
f3f0e1d2
KS
1948 result = SCAN_TRUNCATED;
1949 goto out_unlock;
1950 }
f3f0e1d2 1951
64ab3195
VMO
1952 if (!is_shmem && (folio_test_dirty(folio) ||
1953 folio_test_writeback(folio))) {
4655e5e5
SL
1954 /*
1955 * khugepaged only works on read-only fd, so this
1956 * page is dirty because it hasn't been flushed
1957 * since first write.
1958 */
1959 result = SCAN_FAIL;
1960 goto out_unlock;
1961 }
1962
be2d5756 1963 if (!folio_isolate_lru(folio)) {
f3f0e1d2 1964 result = SCAN_DEL_PAGE_LRU;
042a3082 1965 goto out_unlock;
f3f0e1d2
KS
1966 }
1967
0201ebf2 1968 if (!filemap_release_folio(folio, GFP_KERNEL)) {
99cb0dbd 1969 result = SCAN_PAGE_HAS_PRIVATE;
64ab3195 1970 folio_putback_lru(folio);
99cb0dbd
SL
1971 goto out_unlock;
1972 }
1973
64ab3195
VMO
1974 if (folio_mapped(folio))
1975 try_to_unmap(folio,
869f7ee6 1976 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
f3f0e1d2 1977
77da9389 1978 xas_lock_irq(&xas);
f3f0e1d2 1979
e8c716bc 1980 VM_BUG_ON_PAGE(page != xa_load(xas.xa, index), page);
f3f0e1d2
KS
1981
1982 /*
a2e17cc2 1983 * We control three references to the page:
f3f0e1d2 1984 * - we hold a pin on it;
77da9389 1985 * - one reference from page cache;
f3f0e1d2 1986 * - one from isolate_lru_page;
a2e17cc2
DS
1987 * If those are the only references, then any new usage of the
1988 * page will have to fetch it from the page cache. That requires
1989 * locking the page to handle truncate, so any new usage will be
1990 * blocked until we unlock page after collapse/during rollback.
f3f0e1d2 1991 */
a2e17cc2 1992 if (page_count(page) != 3) {
f3f0e1d2 1993 result = SCAN_PAGE_COUNT;
042a3082
HD
1994 xas_unlock_irq(&xas);
1995 putback_lru_page(page);
1996 goto out_unlock;
f3f0e1d2
KS
1997 }
1998
1999 /*
a2e17cc2 2000 * Accumulate the pages that are being collapsed.
f3f0e1d2
KS
2001 */
2002 list_add_tail(&page->lru, &pagelist);
f3f0e1d2 2003 continue;
f3f0e1d2
KS
2004out_unlock:
2005 unlock_page(page);
2006 put_page(page);
042a3082 2007 goto xa_unlocked;
f3f0e1d2
KS
2008 }
2009
12904d95 2010 if (!is_shmem) {
09d91cda 2011 filemap_nr_thps_inc(mapping);
eb6ecbed
CF
2012 /*
2013 * Paired with smp_mb() in do_dentry_open() to ensure
2014 * i_writecount is up to date and the update to nr_thps is
2015 * visible. Ensures the page cache will be truncated if the
2016 * file is opened writable.
2017 */
2018 smp_mb();
2019 if (inode_is_open_for_write(mapping->host)) {
2020 result = SCAN_FAIL;
eb6ecbed 2021 filemap_nr_thps_dec(mapping);
eb6ecbed 2022 }
09d91cda 2023 }
99cb0dbd 2024
042a3082
HD
2025xa_locked:
2026 xas_unlock_irq(&xas);
77da9389 2027xa_unlocked:
042a3082 2028
6d9df8a5
HD
2029 /*
2030 * If collapse is successful, flush must be done now before copying.
2031 * If collapse is unsuccessful, does flush actually need to be done?
2032 * Do it anyway, to clear the state.
2033 */
2034 try_to_unmap_flush();
2035
509f0069
HD
2036 if (result == SCAN_SUCCEED && nr_none &&
2037 !shmem_charge(mapping->host, nr_none))
2038 result = SCAN_FAIL;
2039 if (result != SCAN_SUCCEED) {
2040 nr_none = 0;
cae106dd 2041 goto rollback;
509f0069 2042 }
cae106dd
DS
2043
2044 /*
a2e17cc2 2045 * The old pages are locked, so they won't change anymore.
cae106dd
DS
2046 */
2047 index = start;
2048 list_for_each_entry(page, &pagelist, lru) {
2049 while (index < page->index) {
12904d95
JY
2050 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2051 index++;
2052 }
cae106dd
DS
2053 if (copy_mc_highpage(hpage + (page->index % HPAGE_PMD_NR), page) > 0) {
2054 result = SCAN_COPY_MC;
2055 goto rollback;
2056 }
2057 index++;
2058 }
2059 while (index < end) {
2060 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2061 index++;
2062 }
2063
ac492b9c
DS
2064 if (nr_none) {
2065 struct vm_area_struct *vma;
2066 int nr_none_check = 0;
2067
2068 i_mmap_lock_read(mapping);
2069 xas_lock_irq(&xas);
2070
2071 xas_set(&xas, start);
2072 for (index = start; index < end; index++) {
2073 if (!xas_next(&xas)) {
2074 xas_store(&xas, XA_RETRY_ENTRY);
2075 if (xas_error(&xas)) {
2076 result = SCAN_STORE_FAILED;
2077 goto immap_locked;
2078 }
2079 nr_none_check++;
2080 }
2081 }
2082
2083 if (nr_none != nr_none_check) {
2084 result = SCAN_PAGE_FILLED;
2085 goto immap_locked;
2086 }
2087
2088 /*
2089 * If userspace observed a missing page in a VMA with a MODE_MISSING
2090 * userfaultfd, then it might expect a UFFD_EVENT_PAGEFAULT for that
2091 * page. If so, we need to roll back to avoid suppressing such an
2092 * event. Since wp/minor userfaultfds don't give userspace any
2093 * guarantees that the kernel doesn't fill a missing page with a zero
2094 * page, so they don't matter here.
2095 *
2096 * Any userfaultfds registered after this point will not be able to
2097 * observe any missing pages due to the previously inserted retry
2098 * entries.
2099 */
2100 vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2101 if (userfaultfd_missing(vma)) {
2102 result = SCAN_EXCEED_NONE_PTE;
2103 goto immap_locked;
2104 }
2105 }
2106
2107immap_locked:
2108 i_mmap_unlock_read(mapping);
2109 if (result != SCAN_SUCCEED) {
2110 xas_set(&xas, start);
2111 for (index = start; index < end; index++) {
2112 if (xas_next(&xas) == XA_RETRY_ENTRY)
2113 xas_store(&xas, NULL);
2114 }
2115
2116 xas_unlock_irq(&xas);
2117 goto rollback;
2118 }
2119 } else {
2120 xas_lock_irq(&xas);
12904d95
JY
2121 }
2122
2123 nr = thp_nr_pages(hpage);
cae106dd
DS
2124 if (is_shmem)
2125 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
2126 else
2127 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
12904d95 2128
cae106dd
DS
2129 if (nr_none) {
2130 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
2131 /* nr_none is always 0 for non-shmem. */
2132 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2133 }
f3f0e1d2 2134
a2e17cc2
DS
2135 /*
2136 * Mark hpage as uptodate before inserting it into the page cache so
2137 * that it isn't mistaken for an fallocated but unwritten page.
2138 */
cae106dd
DS
2139 folio = page_folio(hpage);
2140 folio_mark_uptodate(folio);
2141 folio_ref_add(folio, HPAGE_PMD_NR - 1);
284a344e 2142
cae106dd
DS
2143 if (is_shmem)
2144 folio_mark_dirty(folio);
2145 folio_add_lru(folio);
f3f0e1d2 2146
a2e17cc2
DS
2147 /* Join all the small entries into a single multi-index entry. */
2148 xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2149 xas_store(&xas, hpage);
0175ab61 2150 WARN_ON_ONCE(xas_error(&xas));
a2e17cc2
DS
2151 xas_unlock_irq(&xas);
2152
cae106dd
DS
2153 /*
2154 * Remove pte page tables, so we can re-fault the page as huge.
1d65b771 2155 * If MADV_COLLAPSE, adjust result to call collapse_pte_mapped_thp().
cae106dd 2156 */
1d65b771
HD
2157 retract_page_tables(mapping, start);
2158 if (cc && !cc->is_khugepaged)
2159 result = SCAN_PTE_MAPPED_HUGEPAGE;
cae106dd 2160 unlock_page(hpage);
ac492b9c
DS
2161
2162 /*
2163 * The collapse has succeeded, so free the old pages.
2164 */
2165 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2166 list_del(&page->lru);
2167 page->mapping = NULL;
ac492b9c
DS
2168 ClearPageActive(page);
2169 ClearPageUnevictable(page);
2170 unlock_page(page);
a2e17cc2 2171 folio_put_refs(page_folio(page), 3);
ac492b9c
DS
2172 }
2173
cae106dd
DS
2174 goto out;
2175
2176rollback:
2177 /* Something went wrong: roll back page cache changes */
cae106dd 2178 if (nr_none) {
a2e17cc2 2179 xas_lock_irq(&xas);
cae106dd 2180 mapping->nrpages -= nr_none;
a2e17cc2 2181 xas_unlock_irq(&xas);
509f0069 2182 shmem_uncharge(mapping->host, nr_none);
cae106dd 2183 }
aaa52e34 2184
a2e17cc2 2185 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
cae106dd 2186 list_del(&page->lru);
cae106dd
DS
2187 unlock_page(page);
2188 putback_lru_page(page);
a2e17cc2 2189 put_page(page);
cae106dd 2190 }
cae106dd
DS
2191 /*
2192 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
2193 * file only. This undo is not needed unless failure is
2194 * due to SCAN_COPY_MC.
2195 */
2196 if (!is_shmem && result == SCAN_COPY_MC) {
2197 filemap_nr_thps_dec(mapping);
12904d95 2198 /*
cae106dd
DS
2199 * Paired with smp_mb() in do_dentry_open() to
2200 * ensure the update to nr_thps is visible.
12904d95 2201 */
cae106dd
DS
2202 smp_mb();
2203 }
12904d95 2204
cae106dd 2205 hpage->mapping = NULL;
042a3082 2206
cae106dd
DS
2207 unlock_page(hpage);
2208 put_page(hpage);
f3f0e1d2
KS
2209out:
2210 VM_BUG_ON(!list_empty(&pagelist));
4c9473e8 2211 trace_mm_khugepaged_collapse_file(mm, hpage, index, is_shmem, addr, file, nr, result);
50ad2f24 2212 return result;
f3f0e1d2
KS
2213}
2214
34488399
ZK
2215static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2216 struct file *file, pgoff_t start,
2217 struct collapse_control *cc)
f3f0e1d2
KS
2218{
2219 struct page *page = NULL;
579c571e 2220 struct address_space *mapping = file->f_mapping;
85b392db 2221 XA_STATE(xas, &mapping->i_pages, start);
f3f0e1d2
KS
2222 int present, swap;
2223 int node = NUMA_NO_NODE;
2224 int result = SCAN_SUCCEED;
2225
2226 present = 0;
2227 swap = 0;
34d6b470 2228 memset(cc->node_load, 0, sizeof(cc->node_load));
e031ff96 2229 nodes_clear(cc->alloc_nmask);
f3f0e1d2 2230 rcu_read_lock();
85b392db
MW
2231 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2232 if (xas_retry(&xas, page))
f3f0e1d2 2233 continue;
f3f0e1d2 2234
85b392db 2235 if (xa_is_value(page)) {
d8ea7cc8
ZK
2236 ++swap;
2237 if (cc->is_khugepaged &&
2238 swap > khugepaged_max_ptes_swap) {
f3f0e1d2 2239 result = SCAN_EXCEED_SWAP_PTE;
e9ea874a 2240 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
f3f0e1d2
KS
2241 break;
2242 }
2243 continue;
2244 }
2245
6b24ca4a 2246 /*
58ac9a89 2247 * TODO: khugepaged should compact smaller compound pages
6b24ca4a
MWO
2248 * into a PMD sized page
2249 */
f3f0e1d2 2250 if (PageTransCompound(page)) {
58ac9a89
ZK
2251 struct page *head = compound_head(page);
2252
2253 result = compound_order(head) == HPAGE_PMD_ORDER &&
2254 head->index == start
2255 /* Maybe PMD-mapped */
2256 ? SCAN_PTE_MAPPED_HUGEPAGE
2257 : SCAN_PAGE_COMPOUND;
2258 /*
2259 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2260 * by the caller won't touch the page cache, and so
2261 * it's safe to skip LRU and refcount checks before
2262 * returning.
2263 */
f3f0e1d2
KS
2264 break;
2265 }
2266
2267 node = page_to_nid(page);
7d2c4385 2268 if (hpage_collapse_scan_abort(node, cc)) {
f3f0e1d2
KS
2269 result = SCAN_SCAN_ABORT;
2270 break;
2271 }
34d6b470 2272 cc->node_load[node]++;
f3f0e1d2
KS
2273
2274 if (!PageLRU(page)) {
2275 result = SCAN_PAGE_LRU;
2276 break;
2277 }
2278
99cb0dbd
SL
2279 if (page_count(page) !=
2280 1 + page_mapcount(page) + page_has_private(page)) {
f3f0e1d2
KS
2281 result = SCAN_PAGE_COUNT;
2282 break;
2283 }
2284
2285 /*
2286 * We probably should check if the page is referenced here, but
2287 * nobody would transfer pte_young() to PageReferenced() for us.
2288 * And rmap walk here is just too costly...
2289 */
2290
2291 present++;
2292
2293 if (need_resched()) {
85b392db 2294 xas_pause(&xas);
f3f0e1d2 2295 cond_resched_rcu();
f3f0e1d2
KS
2296 }
2297 }
2298 rcu_read_unlock();
2299
2300 if (result == SCAN_SUCCEED) {
d8ea7cc8
ZK
2301 if (cc->is_khugepaged &&
2302 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
f3f0e1d2 2303 result = SCAN_EXCEED_NONE_PTE;
e9ea874a 2304 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
f3f0e1d2 2305 } else {
34488399 2306 result = collapse_file(mm, addr, file, start, cc);
f3f0e1d2
KS
2307 }
2308 }
2309
045634ff 2310 trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
50ad2f24 2311 return result;
f3f0e1d2
KS
2312}
2313#else
34488399
ZK
2314static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2315 struct file *file, pgoff_t start,
2316 struct collapse_control *cc)
f3f0e1d2
KS
2317{
2318 BUILD_BUG();
2319}
2320#endif
2321
50ad2f24 2322static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
34d6b470 2323 struct collapse_control *cc)
b46e756f
KS
2324 __releases(&khugepaged_mm_lock)
2325 __acquires(&khugepaged_mm_lock)
2326{
68540502 2327 struct vma_iterator vmi;
b26e2701
QZ
2328 struct khugepaged_mm_slot *mm_slot;
2329 struct mm_slot *slot;
b46e756f
KS
2330 struct mm_struct *mm;
2331 struct vm_area_struct *vma;
2332 int progress = 0;
2333
2334 VM_BUG_ON(!pages);
35f3aa39 2335 lockdep_assert_held(&khugepaged_mm_lock);
50ad2f24 2336 *result = SCAN_FAIL;
b46e756f 2337
b26e2701 2338 if (khugepaged_scan.mm_slot) {
b46e756f 2339 mm_slot = khugepaged_scan.mm_slot;
b26e2701
QZ
2340 slot = &mm_slot->slot;
2341 } else {
2342 slot = list_entry(khugepaged_scan.mm_head.next,
b46e756f 2343 struct mm_slot, mm_node);
b26e2701 2344 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
b46e756f
KS
2345 khugepaged_scan.address = 0;
2346 khugepaged_scan.mm_slot = mm_slot;
2347 }
2348 spin_unlock(&khugepaged_mm_lock);
2349
b26e2701 2350 mm = slot->mm;
3b454ad3
YS
2351 /*
2352 * Don't wait for semaphore (to avoid long wait times). Just move to
2353 * the next mm on the list.
2354 */
2355 vma = NULL;
d8ed45c5 2356 if (unlikely(!mmap_read_trylock(mm)))
c1e8d7c6 2357 goto breakouterloop_mmap_lock;
b46e756f
KS
2358
2359 progress++;
68540502
MWO
2360 if (unlikely(hpage_collapse_test_exit(mm)))
2361 goto breakouterloop;
2362
2363 vma_iter_init(&vmi, mm, khugepaged_scan.address);
2364 for_each_vma(vmi, vma) {
b46e756f
KS
2365 unsigned long hstart, hend;
2366
2367 cond_resched();
7d2c4385 2368 if (unlikely(hpage_collapse_test_exit(mm))) {
b46e756f
KS
2369 progress++;
2370 break;
2371 }
a7f4e6e4 2372 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
b46e756f
KS
2373skip:
2374 progress++;
2375 continue;
2376 }
4fa6893f
YS
2377 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2378 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
b46e756f
KS
2379 if (khugepaged_scan.address > hend)
2380 goto skip;
2381 if (khugepaged_scan.address < hstart)
2382 khugepaged_scan.address = hstart;
2383 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2384
2385 while (khugepaged_scan.address < hend) {
50ad2f24
ZK
2386 bool mmap_locked = true;
2387
b46e756f 2388 cond_resched();
7d2c4385 2389 if (unlikely(hpage_collapse_test_exit(mm)))
b46e756f
KS
2390 goto breakouterloop;
2391
2392 VM_BUG_ON(khugepaged_scan.address < hstart ||
2393 khugepaged_scan.address + HPAGE_PMD_SIZE >
2394 hend);
99cb0dbd 2395 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
396bcc52 2396 struct file *file = get_file(vma->vm_file);
f3f0e1d2
KS
2397 pgoff_t pgoff = linear_page_index(vma,
2398 khugepaged_scan.address);
99cb0dbd 2399
d8ed45c5 2400 mmap_read_unlock(mm);
50ad2f24 2401 mmap_locked = false;
d50791c2
HD
2402 *result = hpage_collapse_scan_file(mm,
2403 khugepaged_scan.address, file, pgoff, cc);
f3f0e1d2 2404 fput(file);
d50791c2
HD
2405 if (*result == SCAN_PTE_MAPPED_HUGEPAGE) {
2406 mmap_read_lock(mm);
2407 if (hpage_collapse_test_exit(mm))
2408 goto breakouterloop;
2409 *result = collapse_pte_mapped_thp(mm,
2410 khugepaged_scan.address, false);
2411 if (*result == SCAN_PMD_MAPPED)
2412 *result = SCAN_SUCCEED;
2413 mmap_read_unlock(mm);
2414 }
f3f0e1d2 2415 } else {
7d2c4385 2416 *result = hpage_collapse_scan_pmd(mm, vma,
d50791c2 2417 khugepaged_scan.address, &mmap_locked, cc);
f3f0e1d2 2418 }
d50791c2
HD
2419
2420 if (*result == SCAN_SUCCEED)
50ad2f24 2421 ++khugepaged_pages_collapsed;
58ac9a89 2422
b46e756f
KS
2423 /* move to next address */
2424 khugepaged_scan.address += HPAGE_PMD_SIZE;
2425 progress += HPAGE_PMD_NR;
50ad2f24
ZK
2426 if (!mmap_locked)
2427 /*
2428 * We released mmap_lock so break loop. Note
2429 * that we drop mmap_lock before all hugepage
2430 * allocations, so if allocation fails, we are
2431 * guaranteed to break here and report the
2432 * correct result back to caller.
2433 */
c1e8d7c6 2434 goto breakouterloop_mmap_lock;
b46e756f
KS
2435 if (progress >= pages)
2436 goto breakouterloop;
2437 }
2438 }
2439breakouterloop:
d8ed45c5 2440 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
c1e8d7c6 2441breakouterloop_mmap_lock:
b46e756f
KS
2442
2443 spin_lock(&khugepaged_mm_lock);
2444 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2445 /*
2446 * Release the current mm_slot if this mm is about to die, or
2447 * if we scanned all vmas of this mm.
2448 */
7d2c4385 2449 if (hpage_collapse_test_exit(mm) || !vma) {
b46e756f
KS
2450 /*
2451 * Make sure that if mm_users is reaching zero while
2452 * khugepaged runs here, khugepaged_exit will find
2453 * mm_slot not pointing to the exiting mm.
2454 */
b26e2701
QZ
2455 if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2456 slot = list_entry(slot->mm_node.next,
2457 struct mm_slot, mm_node);
2458 khugepaged_scan.mm_slot =
2459 mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
b46e756f
KS
2460 khugepaged_scan.address = 0;
2461 } else {
2462 khugepaged_scan.mm_slot = NULL;
2463 khugepaged_full_scans++;
2464 }
2465
2466 collect_mm_slot(mm_slot);
2467 }
2468
2469 return progress;
2470}
2471
2472static int khugepaged_has_work(void)
2473{
2474 return !list_empty(&khugepaged_scan.mm_head) &&
1064026b 2475 hugepage_flags_enabled();
b46e756f
KS
2476}
2477
2478static int khugepaged_wait_event(void)
2479{
2480 return !list_empty(&khugepaged_scan.mm_head) ||
2481 kthread_should_stop();
2482}
2483
34d6b470 2484static void khugepaged_do_scan(struct collapse_control *cc)
b46e756f 2485{
b46e756f 2486 unsigned int progress = 0, pass_through_head = 0;
89dc6a96 2487 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
b46e756f 2488 bool wait = true;
50ad2f24 2489 int result = SCAN_SUCCEED;
b46e756f 2490
a980df33
KS
2491 lru_add_drain_all();
2492
c6a7f445 2493 while (true) {
b46e756f
KS
2494 cond_resched();
2495
2496 if (unlikely(kthread_should_stop() || try_to_freeze()))
2497 break;
2498
2499 spin_lock(&khugepaged_mm_lock);
2500 if (!khugepaged_scan.mm_slot)
2501 pass_through_head++;
2502 if (khugepaged_has_work() &&
2503 pass_through_head < 2)
2504 progress += khugepaged_scan_mm_slot(pages - progress,
50ad2f24 2505 &result, cc);
b46e756f
KS
2506 else
2507 progress = pages;
2508 spin_unlock(&khugepaged_mm_lock);
b46e756f 2509
c6a7f445
YS
2510 if (progress >= pages)
2511 break;
2512
50ad2f24 2513 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
c6a7f445
YS
2514 /*
2515 * If fail to allocate the first time, try to sleep for
2516 * a while. When hit again, cancel the scan.
2517 */
2518 if (!wait)
2519 break;
2520 wait = false;
c6a7f445
YS
2521 khugepaged_alloc_sleep();
2522 }
2523 }
b46e756f
KS
2524}
2525
2526static bool khugepaged_should_wakeup(void)
2527{
2528 return kthread_should_stop() ||
2529 time_after_eq(jiffies, khugepaged_sleep_expire);
2530}
2531
2532static void khugepaged_wait_work(void)
2533{
2534 if (khugepaged_has_work()) {
2535 const unsigned long scan_sleep_jiffies =
2536 msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2537
2538 if (!scan_sleep_jiffies)
2539 return;
2540
2541 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2542 wait_event_freezable_timeout(khugepaged_wait,
2543 khugepaged_should_wakeup(),
2544 scan_sleep_jiffies);
2545 return;
2546 }
2547
1064026b 2548 if (hugepage_flags_enabled())
b46e756f
KS
2549 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2550}
2551
2552static int khugepaged(void *none)
2553{
b26e2701 2554 struct khugepaged_mm_slot *mm_slot;
b46e756f
KS
2555
2556 set_freezable();
2557 set_user_nice(current, MAX_NICE);
2558
2559 while (!kthread_should_stop()) {
34d6b470 2560 khugepaged_do_scan(&khugepaged_collapse_control);
b46e756f
KS
2561 khugepaged_wait_work();
2562 }
2563
2564 spin_lock(&khugepaged_mm_lock);
2565 mm_slot = khugepaged_scan.mm_slot;
2566 khugepaged_scan.mm_slot = NULL;
2567 if (mm_slot)
2568 collect_mm_slot(mm_slot);
2569 spin_unlock(&khugepaged_mm_lock);
2570 return 0;
2571}
2572
2573static void set_recommended_min_free_kbytes(void)
2574{
2575 struct zone *zone;
2576 int nr_zones = 0;
2577 unsigned long recommended_min;
2578
1064026b 2579 if (!hugepage_flags_enabled()) {
bd3400ea
LF
2580 calculate_min_free_kbytes();
2581 goto update_wmarks;
2582 }
2583
b7d349c7
JK
2584 for_each_populated_zone(zone) {
2585 /*
2586 * We don't need to worry about fragmentation of
2587 * ZONE_MOVABLE since it only has movable pages.
2588 */
2589 if (zone_idx(zone) > gfp_zone(GFP_USER))
2590 continue;
2591
b46e756f 2592 nr_zones++;
b7d349c7 2593 }
b46e756f
KS
2594
2595 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2596 recommended_min = pageblock_nr_pages * nr_zones * 2;
2597
2598 /*
2599 * Make sure that on average at least two pageblocks are almost free
2600 * of another type, one for a migratetype to fall back to and a
2601 * second to avoid subsequent fallbacks of other types There are 3
2602 * MIGRATE_TYPES we care about.
2603 */
2604 recommended_min += pageblock_nr_pages * nr_zones *
2605 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2606
2607 /* don't ever allow to reserve more than 5% of the lowmem */
2608 recommended_min = min(recommended_min,
2609 (unsigned long) nr_free_buffer_pages() / 20);
2610 recommended_min <<= (PAGE_SHIFT-10);
2611
2612 if (recommended_min > min_free_kbytes) {
2613 if (user_min_free_kbytes >= 0)
2614 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2615 min_free_kbytes, recommended_min);
2616
2617 min_free_kbytes = recommended_min;
2618 }
bd3400ea
LF
2619
2620update_wmarks:
b46e756f
KS
2621 setup_per_zone_wmarks();
2622}
2623
2624int start_stop_khugepaged(void)
2625{
b46e756f
KS
2626 int err = 0;
2627
2628 mutex_lock(&khugepaged_mutex);
1064026b 2629 if (hugepage_flags_enabled()) {
b46e756f
KS
2630 if (!khugepaged_thread)
2631 khugepaged_thread = kthread_run(khugepaged, NULL,
2632 "khugepaged");
2633 if (IS_ERR(khugepaged_thread)) {
2634 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2635 err = PTR_ERR(khugepaged_thread);
2636 khugepaged_thread = NULL;
2637 goto fail;
2638 }
2639
2640 if (!list_empty(&khugepaged_scan.mm_head))
2641 wake_up_interruptible(&khugepaged_wait);
b46e756f
KS
2642 } else if (khugepaged_thread) {
2643 kthread_stop(khugepaged_thread);
2644 khugepaged_thread = NULL;
2645 }
bd3400ea 2646 set_recommended_min_free_kbytes();
b46e756f
KS
2647fail:
2648 mutex_unlock(&khugepaged_mutex);
2649 return err;
2650}
4aab2be0
VB
2651
2652void khugepaged_min_free_kbytes_update(void)
2653{
2654 mutex_lock(&khugepaged_mutex);
1064026b 2655 if (hugepage_flags_enabled() && khugepaged_thread)
4aab2be0
VB
2656 set_recommended_min_free_kbytes();
2657 mutex_unlock(&khugepaged_mutex);
2658}
7d8faaf1 2659
57e9cc50
JW
2660bool current_is_khugepaged(void)
2661{
2662 return kthread_func(current) == khugepaged;
2663}
2664
7d8faaf1
ZK
2665static int madvise_collapse_errno(enum scan_result r)
2666{
2667 /*
2668 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2669 * actionable feedback to caller, so they may take an appropriate
2670 * fallback measure depending on the nature of the failure.
2671 */
2672 switch (r) {
2673 case SCAN_ALLOC_HUGE_PAGE_FAIL:
2674 return -ENOMEM;
2675 case SCAN_CGROUP_CHARGE_FAIL:
ac492b9c 2676 case SCAN_EXCEED_NONE_PTE:
7d8faaf1
ZK
2677 return -EBUSY;
2678 /* Resource temporary unavailable - trying again might succeed */
ae63c898 2679 case SCAN_PAGE_COUNT:
7d8faaf1
ZK
2680 case SCAN_PAGE_LOCK:
2681 case SCAN_PAGE_LRU:
0f3e2a2c 2682 case SCAN_DEL_PAGE_LRU:
ac492b9c 2683 case SCAN_PAGE_FILLED:
7d8faaf1
ZK
2684 return -EAGAIN;
2685 /*
2686 * Other: Trying again likely not to succeed / error intrinsic to
2687 * specified memory range. khugepaged likely won't be able to collapse
2688 * either.
2689 */
2690 default:
2691 return -EINVAL;
2692 }
2693}
2694
2695int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2696 unsigned long start, unsigned long end)
2697{
2698 struct collapse_control *cc;
2699 struct mm_struct *mm = vma->vm_mm;
2700 unsigned long hstart, hend, addr;
2701 int thps = 0, last_fail = SCAN_FAIL;
2702 bool mmap_locked = true;
2703
2704 BUG_ON(vma->vm_start > start);
2705 BUG_ON(vma->vm_end < end);
2706
2707 *prev = vma;
2708
7d8faaf1
ZK
2709 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2710 return -EINVAL;
2711
2712 cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2713 if (!cc)
2714 return -ENOMEM;
2715 cc->is_khugepaged = false;
7d8faaf1
ZK
2716
2717 mmgrab(mm);
2718 lru_add_drain_all();
2719
2720 hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2721 hend = end & HPAGE_PMD_MASK;
2722
2723 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2724 int result = SCAN_FAIL;
2725
2726 if (!mmap_locked) {
2727 cond_resched();
2728 mmap_read_lock(mm);
2729 mmap_locked = true;
34488399
ZK
2730 result = hugepage_vma_revalidate(mm, addr, false, &vma,
2731 cc);
7d8faaf1
ZK
2732 if (result != SCAN_SUCCEED) {
2733 last_fail = result;
2734 goto out_nolock;
2735 }
4d24de94 2736
52dc0310 2737 hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
7d8faaf1
ZK
2738 }
2739 mmap_assert_locked(mm);
2740 memset(cc->node_load, 0, sizeof(cc->node_load));
e031ff96 2741 nodes_clear(cc->alloc_nmask);
34488399
ZK
2742 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2743 struct file *file = get_file(vma->vm_file);
2744 pgoff_t pgoff = linear_page_index(vma, addr);
2745
2746 mmap_read_unlock(mm);
2747 mmap_locked = false;
2748 result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2749 cc);
2750 fput(file);
2751 } else {
2752 result = hpage_collapse_scan_pmd(mm, vma, addr,
2753 &mmap_locked, cc);
2754 }
7d8faaf1
ZK
2755 if (!mmap_locked)
2756 *prev = NULL; /* Tell caller we dropped mmap_lock */
2757
34488399 2758handle_result:
7d8faaf1
ZK
2759 switch (result) {
2760 case SCAN_SUCCEED:
2761 case SCAN_PMD_MAPPED:
2762 ++thps;
2763 break;
34488399
ZK
2764 case SCAN_PTE_MAPPED_HUGEPAGE:
2765 BUG_ON(mmap_locked);
2766 BUG_ON(*prev);
1043173e 2767 mmap_read_lock(mm);
34488399 2768 result = collapse_pte_mapped_thp(mm, addr, true);
1043173e 2769 mmap_read_unlock(mm);
34488399 2770 goto handle_result;
7d8faaf1
ZK
2771 /* Whitelisted set of results where continuing OK */
2772 case SCAN_PMD_NULL:
2773 case SCAN_PTE_NON_PRESENT:
2774 case SCAN_PTE_UFFD_WP:
2775 case SCAN_PAGE_RO:
2776 case SCAN_LACK_REFERENCED_PAGE:
2777 case SCAN_PAGE_NULL:
2778 case SCAN_PAGE_COUNT:
2779 case SCAN_PAGE_LOCK:
2780 case SCAN_PAGE_COMPOUND:
2781 case SCAN_PAGE_LRU:
0f3e2a2c 2782 case SCAN_DEL_PAGE_LRU:
7d8faaf1
ZK
2783 last_fail = result;
2784 break;
2785 default:
2786 last_fail = result;
2787 /* Other error, exit */
2788 goto out_maybelock;
2789 }
2790 }
2791
2792out_maybelock:
2793 /* Caller expects us to hold mmap_lock on return */
2794 if (!mmap_locked)
2795 mmap_read_lock(mm);
2796out_nolock:
2797 mmap_assert_locked(mm);
2798 mmdrop(mm);
2799 kfree(cc);
2800
2801 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2802 : madvise_collapse_errno(last_fail);
2803}