]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/huge_memory.c
mm: add tail private fields to struct folio
[thirdparty/linux.git] / mm / huge_memory.c
CommitLineData
20c8ccb1 1// SPDX-License-Identifier: GPL-2.0-only
71e3aac0
AA
2/*
3 * Copyright (C) 2009 Red Hat, Inc.
71e3aac0
AA
4 */
5
ae3a8c1c
AM
6#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7
71e3aac0
AA
8#include <linux/mm.h>
9#include <linux/sched.h>
fa6c0231 10#include <linux/sched/mm.h>
f7ccbae4 11#include <linux/sched/coredump.h>
6a3827d7 12#include <linux/sched/numa_balancing.h>
71e3aac0
AA
13#include <linux/highmem.h>
14#include <linux/hugetlb.h>
15#include <linux/mmu_notifier.h>
16#include <linux/rmap.h>
17#include <linux/swap.h>
97ae1749 18#include <linux/shrinker.h>
ba76149f 19#include <linux/mm_inline.h>
e9b61f19 20#include <linux/swapops.h>
fb5c2029 21#include <linux/backing-dev.h>
4897c765 22#include <linux/dax.h>
ba76149f 23#include <linux/khugepaged.h>
878aee7d 24#include <linux/freezer.h>
f25748e3 25#include <linux/pfn_t.h>
a664b2d8 26#include <linux/mman.h>
3565fce3 27#include <linux/memremap.h>
325adeb5 28#include <linux/pagemap.h>
49071d43 29#include <linux/debugfs.h>
4daae3b4 30#include <linux/migrate.h>
43b5fbbd 31#include <linux/hashtable.h>
6b251fc9 32#include <linux/userfaultfd_k.h>
33c3fc71 33#include <linux/page_idle.h>
baa355fd 34#include <linux/shmem_fs.h>
6b31d595 35#include <linux/oom.h>
98fa15f3 36#include <linux/numa.h>
f7da677b 37#include <linux/page_owner.h>
a1a3a2fc 38#include <linux/sched/sysctl.h>
467b171a 39#include <linux/memory-tiers.h>
97ae1749 40
71e3aac0
AA
41#include <asm/tlb.h>
42#include <asm/pgalloc.h>
43#include "internal.h"
014bb1de 44#include "swap.h"
71e3aac0 45
283fd6fe
AK
46#define CREATE_TRACE_POINTS
47#include <trace/events/thp.h>
48
ba76149f 49/*
b14d595a
MD
50 * By default, transparent hugepage support is disabled in order to avoid
51 * risking an increased memory footprint for applications that are not
52 * guaranteed to benefit from it. When transparent hugepage support is
53 * enabled, it is for all mappings, and khugepaged scans all mappings.
8bfa3f9a
JW
54 * Defrag is invoked by khugepaged hugepage allocations and by page faults
55 * for all hugepage allocations.
ba76149f 56 */
71e3aac0 57unsigned long transparent_hugepage_flags __read_mostly =
13ece886 58#ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
ba76149f 59 (1<<TRANSPARENT_HUGEPAGE_FLAG)|
13ece886
AA
60#endif
61#ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
62 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
63#endif
444eb2a4 64 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
79da5407
KS
65 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
66 (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
ba76149f 67
9a982250 68static struct shrinker deferred_split_shrinker;
f000565a 69
97ae1749 70static atomic_t huge_zero_refcount;
56873f43 71struct page *huge_zero_page __read_mostly;
3b77e8c8 72unsigned long huge_zero_pfn __read_mostly = ~0UL;
4a6c1297 73
a7f4e6e4
ZK
74bool hugepage_vma_check(struct vm_area_struct *vma, unsigned long vm_flags,
75 bool smaps, bool in_pf, bool enforce_sysfs)
7635d9cb 76{
9fec5168
YS
77 if (!vma->vm_mm) /* vdso */
78 return false;
79
7da4e2cb
YS
80 /*
81 * Explicitly disabled through madvise or prctl, or some
82 * architectures may disable THP for some mappings, for
83 * example, s390 kvm.
84 * */
85 if ((vm_flags & VM_NOHUGEPAGE) ||
86 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
9fec5168 87 return false;
7da4e2cb
YS
88 /*
89 * If the hardware/firmware marked hugepage support disabled.
90 */
3c556d24 91 if (transparent_hugepage_flags & (1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED))
c0630669 92 return false;
c0630669 93
7da4e2cb 94 /* khugepaged doesn't collapse DAX vma, but page fault is fine. */
9fec5168 95 if (vma_is_dax(vma))
7da4e2cb
YS
96 return in_pf;
97
98 /*
99 * Special VMA and hugetlb VMA.
100 * Must be checked after dax since some dax mappings may have
101 * VM_MIXEDMAP set.
102 */
103 if (vm_flags & VM_NO_KHUGEPAGED)
c0630669 104 return false;
9fec5168 105
7da4e2cb
YS
106 /*
107 * Check alignment for file vma and size for both file and anon vma.
108 *
109 * Skip the check for page fault. Huge fault does the check in fault
110 * handlers. And this check is not suitable for huge PUD fault.
111 */
112 if (!in_pf &&
113 !transhuge_vma_suitable(vma, (vma->vm_end - HPAGE_PMD_SIZE)))
9fec5168
YS
114 return false;
115
7da4e2cb
YS
116 /*
117 * Enabled via shmem mount options or sysfs settings.
118 * Must be done before hugepage flags check since shmem has its
119 * own flags.
120 */
121 if (!in_pf && shmem_file(vma->vm_file))
2cf13384
DS
122 return shmem_is_huge(file_inode(vma->vm_file), vma->vm_pgoff,
123 !enforce_sysfs, vma->vm_mm, vm_flags);
9fec5168 124
a7f4e6e4
ZK
125 /* Enforce sysfs THP requirements as necessary */
126 if (enforce_sysfs &&
127 (!hugepage_flags_enabled() || (!(vm_flags & VM_HUGEPAGE) &&
128 !hugepage_flags_always())))
9fec5168
YS
129 return false;
130
131 /* Only regular file is valid */
7da4e2cb 132 if (!in_pf && file_thp_enabled(vma))
78d12c19 133 return true;
7635d9cb 134
9fec5168
YS
135 if (!vma_is_anonymous(vma))
136 return false;
137
138 if (vma_is_temporary_stack(vma))
139 return false;
140
141 /*
142 * THPeligible bit of smaps should show 1 for proper VMAs even
143 * though anon_vma is not initialized yet.
7da4e2cb
YS
144 *
145 * Allow page fault since anon_vma may be not initialized until
146 * the first page fault.
9fec5168
YS
147 */
148 if (!vma->anon_vma)
7da4e2cb 149 return (smaps || in_pf);
9fec5168
YS
150
151 return true;
7635d9cb
MH
152}
153
aaa9705b 154static bool get_huge_zero_page(void)
97ae1749
KS
155{
156 struct page *zero_page;
157retry:
158 if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
aaa9705b 159 return true;
97ae1749
KS
160
161 zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
4a6c1297 162 HPAGE_PMD_ORDER);
d8a8e1f0
KS
163 if (!zero_page) {
164 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
aaa9705b 165 return false;
d8a8e1f0 166 }
97ae1749 167 preempt_disable();
5918d10a 168 if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
97ae1749 169 preempt_enable();
5ddacbe9 170 __free_pages(zero_page, compound_order(zero_page));
97ae1749
KS
171 goto retry;
172 }
3b77e8c8 173 WRITE_ONCE(huge_zero_pfn, page_to_pfn(zero_page));
97ae1749
KS
174
175 /* We take additional reference here. It will be put back by shrinker */
176 atomic_set(&huge_zero_refcount, 2);
177 preempt_enable();
f4981502 178 count_vm_event(THP_ZERO_PAGE_ALLOC);
aaa9705b 179 return true;
4a6c1297
KS
180}
181
6fcb52a5 182static void put_huge_zero_page(void)
4a6c1297 183{
97ae1749
KS
184 /*
185 * Counter should never go to zero here. Only shrinker can put
186 * last reference.
187 */
188 BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
4a6c1297
KS
189}
190
6fcb52a5
AL
191struct page *mm_get_huge_zero_page(struct mm_struct *mm)
192{
193 if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
194 return READ_ONCE(huge_zero_page);
195
196 if (!get_huge_zero_page())
197 return NULL;
198
199 if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
200 put_huge_zero_page();
201
202 return READ_ONCE(huge_zero_page);
203}
204
205void mm_put_huge_zero_page(struct mm_struct *mm)
206{
207 if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
208 put_huge_zero_page();
209}
210
48896466
GC
211static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
212 struct shrink_control *sc)
4a6c1297 213{
48896466
GC
214 /* we can free zero page only if last reference remains */
215 return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
216}
97ae1749 217
48896466
GC
218static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
219 struct shrink_control *sc)
220{
97ae1749 221 if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
5918d10a
KS
222 struct page *zero_page = xchg(&huge_zero_page, NULL);
223 BUG_ON(zero_page == NULL);
3b77e8c8 224 WRITE_ONCE(huge_zero_pfn, ~0UL);
5ddacbe9 225 __free_pages(zero_page, compound_order(zero_page));
48896466 226 return HPAGE_PMD_NR;
97ae1749
KS
227 }
228
229 return 0;
4a6c1297
KS
230}
231
97ae1749 232static struct shrinker huge_zero_page_shrinker = {
48896466
GC
233 .count_objects = shrink_huge_zero_page_count,
234 .scan_objects = shrink_huge_zero_page_scan,
97ae1749
KS
235 .seeks = DEFAULT_SEEKS,
236};
237
71e3aac0 238#ifdef CONFIG_SYSFS
71e3aac0
AA
239static ssize_t enabled_show(struct kobject *kobj,
240 struct kobj_attribute *attr, char *buf)
241{
bfb0ffeb
JP
242 const char *output;
243
444eb2a4 244 if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
bfb0ffeb
JP
245 output = "[always] madvise never";
246 else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
247 &transparent_hugepage_flags))
248 output = "always [madvise] never";
444eb2a4 249 else
bfb0ffeb
JP
250 output = "always madvise [never]";
251
252 return sysfs_emit(buf, "%s\n", output);
71e3aac0 253}
444eb2a4 254
71e3aac0
AA
255static ssize_t enabled_store(struct kobject *kobj,
256 struct kobj_attribute *attr,
257 const char *buf, size_t count)
258{
21440d7e 259 ssize_t ret = count;
ba76149f 260
f42f2552 261 if (sysfs_streq(buf, "always")) {
21440d7e
DR
262 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
263 set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
f42f2552 264 } else if (sysfs_streq(buf, "madvise")) {
21440d7e
DR
265 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
266 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
f42f2552 267 } else if (sysfs_streq(buf, "never")) {
21440d7e
DR
268 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
269 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
270 } else
271 ret = -EINVAL;
ba76149f
AA
272
273 if (ret > 0) {
b46e756f 274 int err = start_stop_khugepaged();
ba76149f
AA
275 if (err)
276 ret = err;
277 }
ba76149f 278 return ret;
71e3aac0 279}
37139bb0
ML
280
281static struct kobj_attribute enabled_attr = __ATTR_RW(enabled);
71e3aac0 282
b46e756f 283ssize_t single_hugepage_flag_show(struct kobject *kobj,
bfb0ffeb
JP
284 struct kobj_attribute *attr, char *buf,
285 enum transparent_hugepage_flag flag)
71e3aac0 286{
bfb0ffeb
JP
287 return sysfs_emit(buf, "%d\n",
288 !!test_bit(flag, &transparent_hugepage_flags));
71e3aac0 289}
e27e6151 290
b46e756f 291ssize_t single_hugepage_flag_store(struct kobject *kobj,
71e3aac0
AA
292 struct kobj_attribute *attr,
293 const char *buf, size_t count,
294 enum transparent_hugepage_flag flag)
295{
e27e6151
BH
296 unsigned long value;
297 int ret;
298
299 ret = kstrtoul(buf, 10, &value);
300 if (ret < 0)
301 return ret;
302 if (value > 1)
303 return -EINVAL;
304
305 if (value)
71e3aac0 306 set_bit(flag, &transparent_hugepage_flags);
e27e6151 307 else
71e3aac0 308 clear_bit(flag, &transparent_hugepage_flags);
71e3aac0
AA
309
310 return count;
311}
312
71e3aac0
AA
313static ssize_t defrag_show(struct kobject *kobj,
314 struct kobj_attribute *attr, char *buf)
315{
bfb0ffeb
JP
316 const char *output;
317
318 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
319 &transparent_hugepage_flags))
320 output = "[always] defer defer+madvise madvise never";
321 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
322 &transparent_hugepage_flags))
323 output = "always [defer] defer+madvise madvise never";
324 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,
325 &transparent_hugepage_flags))
326 output = "always defer [defer+madvise] madvise never";
327 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,
328 &transparent_hugepage_flags))
329 output = "always defer defer+madvise [madvise] never";
330 else
331 output = "always defer defer+madvise madvise [never]";
332
333 return sysfs_emit(buf, "%s\n", output);
71e3aac0 334}
21440d7e 335
71e3aac0
AA
336static ssize_t defrag_store(struct kobject *kobj,
337 struct kobj_attribute *attr,
338 const char *buf, size_t count)
339{
f42f2552 340 if (sysfs_streq(buf, "always")) {
21440d7e
DR
341 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
342 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
343 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
344 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
f42f2552 345 } else if (sysfs_streq(buf, "defer+madvise")) {
21440d7e
DR
346 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
347 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
348 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
349 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
f42f2552 350 } else if (sysfs_streq(buf, "defer")) {
4fad7fb6
DR
351 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
352 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
353 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
354 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
f42f2552 355 } else if (sysfs_streq(buf, "madvise")) {
21440d7e
DR
356 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
357 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
358 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
359 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
f42f2552 360 } else if (sysfs_streq(buf, "never")) {
21440d7e
DR
361 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
362 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
363 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
364 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
365 } else
366 return -EINVAL;
367
368 return count;
71e3aac0 369}
37139bb0 370static struct kobj_attribute defrag_attr = __ATTR_RW(defrag);
71e3aac0 371
79da5407 372static ssize_t use_zero_page_show(struct kobject *kobj,
ae7a927d 373 struct kobj_attribute *attr, char *buf)
79da5407 374{
b46e756f 375 return single_hugepage_flag_show(kobj, attr, buf,
ae7a927d 376 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
79da5407
KS
377}
378static ssize_t use_zero_page_store(struct kobject *kobj,
379 struct kobj_attribute *attr, const char *buf, size_t count)
380{
b46e756f 381 return single_hugepage_flag_store(kobj, attr, buf, count,
79da5407
KS
382 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
383}
37139bb0 384static struct kobj_attribute use_zero_page_attr = __ATTR_RW(use_zero_page);
49920d28
HD
385
386static ssize_t hpage_pmd_size_show(struct kobject *kobj,
ae7a927d 387 struct kobj_attribute *attr, char *buf)
49920d28 388{
ae7a927d 389 return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE);
49920d28
HD
390}
391static struct kobj_attribute hpage_pmd_size_attr =
392 __ATTR_RO(hpage_pmd_size);
393
71e3aac0
AA
394static struct attribute *hugepage_attr[] = {
395 &enabled_attr.attr,
396 &defrag_attr.attr,
79da5407 397 &use_zero_page_attr.attr,
49920d28 398 &hpage_pmd_size_attr.attr,
396bcc52 399#ifdef CONFIG_SHMEM
5a6e75f8 400 &shmem_enabled_attr.attr,
71e3aac0
AA
401#endif
402 NULL,
403};
404
8aa95a21 405static const struct attribute_group hugepage_attr_group = {
71e3aac0 406 .attrs = hugepage_attr,
ba76149f
AA
407};
408
569e5590 409static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
71e3aac0 410{
71e3aac0
AA
411 int err;
412
569e5590
SL
413 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
414 if (unlikely(!*hugepage_kobj)) {
ae3a8c1c 415 pr_err("failed to create transparent hugepage kobject\n");
569e5590 416 return -ENOMEM;
ba76149f
AA
417 }
418
569e5590 419 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
ba76149f 420 if (err) {
ae3a8c1c 421 pr_err("failed to register transparent hugepage group\n");
569e5590 422 goto delete_obj;
ba76149f
AA
423 }
424
569e5590 425 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
ba76149f 426 if (err) {
ae3a8c1c 427 pr_err("failed to register transparent hugepage group\n");
569e5590 428 goto remove_hp_group;
ba76149f 429 }
569e5590
SL
430
431 return 0;
432
433remove_hp_group:
434 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
435delete_obj:
436 kobject_put(*hugepage_kobj);
437 return err;
438}
439
440static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
441{
442 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
443 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
444 kobject_put(hugepage_kobj);
445}
446#else
447static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
448{
449 return 0;
450}
451
452static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
453{
454}
455#endif /* CONFIG_SYSFS */
456
457static int __init hugepage_init(void)
458{
459 int err;
460 struct kobject *hugepage_kobj;
461
462 if (!has_transparent_hugepage()) {
3c556d24 463 transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED;
569e5590
SL
464 return -EINVAL;
465 }
466
ff20c2e0
KS
467 /*
468 * hugepages can't be allocated by the buddy allocator
469 */
23baf831 470 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_ORDER);
ff20c2e0
KS
471 /*
472 * we use page->mapping and page->index in second tail page
473 * as list_head: assuming THP order >= 2
474 */
475 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER < 2);
476
569e5590
SL
477 err = hugepage_init_sysfs(&hugepage_kobj);
478 if (err)
65ebb64f 479 goto err_sysfs;
ba76149f 480
b46e756f 481 err = khugepaged_init();
ba76149f 482 if (err)
65ebb64f 483 goto err_slab;
ba76149f 484
e33c267a 485 err = register_shrinker(&huge_zero_page_shrinker, "thp-zero");
65ebb64f
KS
486 if (err)
487 goto err_hzp_shrinker;
e33c267a 488 err = register_shrinker(&deferred_split_shrinker, "thp-deferred_split");
9a982250
KS
489 if (err)
490 goto err_split_shrinker;
97ae1749 491
97562cd2
RR
492 /*
493 * By default disable transparent hugepages on smaller systems,
494 * where the extra memory used could hurt more than TLB overhead
495 * is likely to save. The admin can still enable it through /sys.
496 */
ca79b0c2 497 if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) {
97562cd2 498 transparent_hugepage_flags = 0;
79553da2
KS
499 return 0;
500 }
97562cd2 501
79553da2 502 err = start_stop_khugepaged();
65ebb64f
KS
503 if (err)
504 goto err_khugepaged;
ba76149f 505
569e5590 506 return 0;
65ebb64f 507err_khugepaged:
9a982250
KS
508 unregister_shrinker(&deferred_split_shrinker);
509err_split_shrinker:
65ebb64f
KS
510 unregister_shrinker(&huge_zero_page_shrinker);
511err_hzp_shrinker:
b46e756f 512 khugepaged_destroy();
65ebb64f 513err_slab:
569e5590 514 hugepage_exit_sysfs(hugepage_kobj);
65ebb64f 515err_sysfs:
ba76149f 516 return err;
71e3aac0 517}
a64fb3cd 518subsys_initcall(hugepage_init);
71e3aac0
AA
519
520static int __init setup_transparent_hugepage(char *str)
521{
522 int ret = 0;
523 if (!str)
524 goto out;
525 if (!strcmp(str, "always")) {
526 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
527 &transparent_hugepage_flags);
528 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
529 &transparent_hugepage_flags);
530 ret = 1;
531 } else if (!strcmp(str, "madvise")) {
532 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
533 &transparent_hugepage_flags);
534 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
535 &transparent_hugepage_flags);
536 ret = 1;
537 } else if (!strcmp(str, "never")) {
538 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
539 &transparent_hugepage_flags);
540 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
541 &transparent_hugepage_flags);
542 ret = 1;
543 }
544out:
545 if (!ret)
ae3a8c1c 546 pr_warn("transparent_hugepage= cannot parse, ignored\n");
71e3aac0
AA
547 return ret;
548}
549__setup("transparent_hugepage=", setup_transparent_hugepage);
550
f55e1014 551pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
71e3aac0 552{
f55e1014 553 if (likely(vma->vm_flags & VM_WRITE))
71e3aac0
AA
554 pmd = pmd_mkwrite(pmd);
555 return pmd;
556}
557
87eaceb3 558#ifdef CONFIG_MEMCG
f8baa6be
MWO
559static inline
560struct deferred_split *get_deferred_split_queue(struct folio *folio)
9a982250 561{
f8baa6be
MWO
562 struct mem_cgroup *memcg = folio_memcg(folio);
563 struct pglist_data *pgdat = NODE_DATA(folio_nid(folio));
87eaceb3
YS
564
565 if (memcg)
566 return &memcg->deferred_split_queue;
567 else
568 return &pgdat->deferred_split_queue;
9a982250 569}
87eaceb3 570#else
f8baa6be
MWO
571static inline
572struct deferred_split *get_deferred_split_queue(struct folio *folio)
87eaceb3 573{
f8baa6be 574 struct pglist_data *pgdat = NODE_DATA(folio_nid(folio));
87eaceb3
YS
575
576 return &pgdat->deferred_split_queue;
577}
578#endif
9a982250 579
da6e7bf3 580void folio_prep_large_rmappable(struct folio *folio)
9a982250 581{
8991de90
MWO
582 VM_BUG_ON_FOLIO(folio_order(folio) < 2, folio);
583 INIT_LIST_HEAD(&folio->_deferred_list);
de53c05f 584 folio_set_large_rmappable(folio);
9a982250
KS
585}
586
562beb72 587static inline bool is_transparent_hugepage(struct page *page)
005ba37c 588{
f04029f3
MWO
589 struct folio *folio;
590
005ba37c 591 if (!PageCompound(page))
fa1f68cc 592 return false;
005ba37c 593
f04029f3
MWO
594 folio = page_folio(page);
595 return is_huge_zero_page(&folio->page) ||
de53c05f 596 folio_test_large_rmappable(folio);
005ba37c 597}
005ba37c 598
97d3d0f9
KS
599static unsigned long __thp_get_unmapped_area(struct file *filp,
600 unsigned long addr, unsigned long len,
74d2fad1
TK
601 loff_t off, unsigned long flags, unsigned long size)
602{
74d2fad1
TK
603 loff_t off_end = off + len;
604 loff_t off_align = round_up(off, size);
97d3d0f9 605 unsigned long len_pad, ret;
74d2fad1
TK
606
607 if (off_end <= off_align || (off_end - off_align) < size)
608 return 0;
609
610 len_pad = len + size;
611 if (len_pad < len || (off + len_pad) < off)
612 return 0;
613
97d3d0f9 614 ret = current->mm->get_unmapped_area(filp, addr, len_pad,
74d2fad1 615 off >> PAGE_SHIFT, flags);
97d3d0f9
KS
616
617 /*
618 * The failure might be due to length padding. The caller will retry
619 * without the padding.
620 */
621 if (IS_ERR_VALUE(ret))
74d2fad1
TK
622 return 0;
623
97d3d0f9
KS
624 /*
625 * Do not try to align to THP boundary if allocation at the address
626 * hint succeeds.
627 */
628 if (ret == addr)
629 return addr;
630
631 ret += (off - ret) & (size - 1);
632 return ret;
74d2fad1
TK
633}
634
635unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
636 unsigned long len, unsigned long pgoff, unsigned long flags)
637{
97d3d0f9 638 unsigned long ret;
74d2fad1
TK
639 loff_t off = (loff_t)pgoff << PAGE_SHIFT;
640
97d3d0f9
KS
641 ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE);
642 if (ret)
643 return ret;
1854bc6e 644
74d2fad1
TK
645 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
646}
647EXPORT_SYMBOL_GPL(thp_get_unmapped_area);
648
2b740303
SJ
649static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf,
650 struct page *page, gfp_t gfp)
71e3aac0 651{
82b0f8c3 652 struct vm_area_struct *vma = vmf->vma;
cfe3236d 653 struct folio *folio = page_folio(page);
71e3aac0 654 pgtable_t pgtable;
82b0f8c3 655 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
2b740303 656 vm_fault_t ret = 0;
71e3aac0 657
cfe3236d 658 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
00501b53 659
cfe3236d
KW
660 if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
661 folio_put(folio);
6b251fc9 662 count_vm_event(THP_FAULT_FALLBACK);
85b9f46e 663 count_vm_event(THP_FAULT_FALLBACK_CHARGE);
6b251fc9
AA
664 return VM_FAULT_FALLBACK;
665 }
cfe3236d 666 folio_throttle_swaprate(folio, gfp);
00501b53 667
4cf58924 668 pgtable = pte_alloc_one(vma->vm_mm);
00501b53 669 if (unlikely(!pgtable)) {
6b31d595
MH
670 ret = VM_FAULT_OOM;
671 goto release;
00501b53 672 }
71e3aac0 673
c79b57e4 674 clear_huge_page(page, vmf->address, HPAGE_PMD_NR);
52f37629 675 /*
cfe3236d 676 * The memory barrier inside __folio_mark_uptodate makes sure that
52f37629
MK
677 * clear_huge_page writes become visible before the set_pmd_at()
678 * write.
679 */
cfe3236d 680 __folio_mark_uptodate(folio);
71e3aac0 681
82b0f8c3
JK
682 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
683 if (unlikely(!pmd_none(*vmf->pmd))) {
6b31d595 684 goto unlock_release;
71e3aac0
AA
685 } else {
686 pmd_t entry;
6b251fc9 687
6b31d595
MH
688 ret = check_stable_address_space(vma->vm_mm);
689 if (ret)
690 goto unlock_release;
691
6b251fc9
AA
692 /* Deliver the page fault to userland */
693 if (userfaultfd_missing(vma)) {
82b0f8c3 694 spin_unlock(vmf->ptl);
cfe3236d 695 folio_put(folio);
bae473a4 696 pte_free(vma->vm_mm, pgtable);
8fd5eda4
ML
697 ret = handle_userfault(vmf, VM_UFFD_MISSING);
698 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
699 return ret;
6b251fc9
AA
700 }
701
3122359a 702 entry = mk_huge_pmd(page, vma->vm_page_prot);
f55e1014 703 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
cfe3236d
KW
704 folio_add_new_anon_rmap(folio, vma, haddr);
705 folio_add_lru_vma(folio, vma);
82b0f8c3
JK
706 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
707 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
fca40573 708 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
bae473a4 709 add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
c4812909 710 mm_inc_nr_ptes(vma->vm_mm);
82b0f8c3 711 spin_unlock(vmf->ptl);
6b251fc9 712 count_vm_event(THP_FAULT_ALLOC);
9d82c694 713 count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
71e3aac0
AA
714 }
715
aa2e878e 716 return 0;
6b31d595
MH
717unlock_release:
718 spin_unlock(vmf->ptl);
719release:
720 if (pgtable)
721 pte_free(vma->vm_mm, pgtable);
cfe3236d 722 folio_put(folio);
6b31d595
MH
723 return ret;
724
71e3aac0
AA
725}
726
444eb2a4 727/*
21440d7e
DR
728 * always: directly stall for all thp allocations
729 * defer: wake kswapd and fail if not immediately available
730 * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise
731 * fail if not immediately available
732 * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately
733 * available
734 * never: never stall for any thp allocation
444eb2a4 735 */
164cc4fe 736gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)
444eb2a4 737{
164cc4fe 738 const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE);
2f0799a0 739
ac79f78d 740 /* Always do synchronous compaction */
a8282608
AA
741 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
742 return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);
ac79f78d
DR
743
744 /* Kick kcompactd and fail quickly */
21440d7e 745 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
19deb769 746 return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;
ac79f78d
DR
747
748 /* Synchronous compaction if madvised, otherwise kick kcompactd */
21440d7e 749 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags))
19deb769
DR
750 return GFP_TRANSHUGE_LIGHT |
751 (vma_madvised ? __GFP_DIRECT_RECLAIM :
752 __GFP_KSWAPD_RECLAIM);
ac79f78d
DR
753
754 /* Only do synchronous compaction if madvised */
21440d7e 755 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
19deb769
DR
756 return GFP_TRANSHUGE_LIGHT |
757 (vma_madvised ? __GFP_DIRECT_RECLAIM : 0);
ac79f78d 758
19deb769 759 return GFP_TRANSHUGE_LIGHT;
444eb2a4
MG
760}
761
c4088ebd 762/* Caller must hold page table lock. */
2efeb8da 763static void set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
97ae1749 764 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
5918d10a 765 struct page *zero_page)
fc9fe822
KS
766{
767 pmd_t entry;
7c414164 768 if (!pmd_none(*pmd))
2efeb8da 769 return;
5918d10a 770 entry = mk_pmd(zero_page, vma->vm_page_prot);
fc9fe822 771 entry = pmd_mkhuge(entry);
c8bb4163 772 pgtable_trans_huge_deposit(mm, pmd, pgtable);
fc9fe822 773 set_pmd_at(mm, haddr, pmd, entry);
c4812909 774 mm_inc_nr_ptes(mm);
fc9fe822
KS
775}
776
2b740303 777vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf)
71e3aac0 778{
82b0f8c3 779 struct vm_area_struct *vma = vmf->vma;
077fcf11 780 gfp_t gfp;
cb196ee1 781 struct folio *folio;
82b0f8c3 782 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
71e3aac0 783
43675e6f 784 if (!transhuge_vma_suitable(vma, haddr))
c0292554 785 return VM_FAULT_FALLBACK;
128ec037
KS
786 if (unlikely(anon_vma_prepare(vma)))
787 return VM_FAULT_OOM;
4fa6893f 788 khugepaged_enter_vma(vma, vma->vm_flags);
d2081b2b 789
82b0f8c3 790 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
bae473a4 791 !mm_forbids_zeropage(vma->vm_mm) &&
128ec037
KS
792 transparent_hugepage_use_zero_page()) {
793 pgtable_t pgtable;
794 struct page *zero_page;
2b740303 795 vm_fault_t ret;
4cf58924 796 pgtable = pte_alloc_one(vma->vm_mm);
128ec037 797 if (unlikely(!pgtable))
ba76149f 798 return VM_FAULT_OOM;
6fcb52a5 799 zero_page = mm_get_huge_zero_page(vma->vm_mm);
128ec037 800 if (unlikely(!zero_page)) {
bae473a4 801 pte_free(vma->vm_mm, pgtable);
81ab4201 802 count_vm_event(THP_FAULT_FALLBACK);
c0292554 803 return VM_FAULT_FALLBACK;
b9bbfbe3 804 }
82b0f8c3 805 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
6b251fc9 806 ret = 0;
82b0f8c3 807 if (pmd_none(*vmf->pmd)) {
6b31d595
MH
808 ret = check_stable_address_space(vma->vm_mm);
809 if (ret) {
810 spin_unlock(vmf->ptl);
bfe8cc1d 811 pte_free(vma->vm_mm, pgtable);
6b31d595 812 } else if (userfaultfd_missing(vma)) {
82b0f8c3 813 spin_unlock(vmf->ptl);
bfe8cc1d 814 pte_free(vma->vm_mm, pgtable);
82b0f8c3 815 ret = handle_userfault(vmf, VM_UFFD_MISSING);
6b251fc9
AA
816 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
817 } else {
bae473a4 818 set_huge_zero_page(pgtable, vma->vm_mm, vma,
82b0f8c3 819 haddr, vmf->pmd, zero_page);
fca40573 820 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
82b0f8c3 821 spin_unlock(vmf->ptl);
6b251fc9 822 }
bfe8cc1d 823 } else {
82b0f8c3 824 spin_unlock(vmf->ptl);
bae473a4 825 pte_free(vma->vm_mm, pgtable);
bfe8cc1d 826 }
6b251fc9 827 return ret;
71e3aac0 828 }
164cc4fe 829 gfp = vma_thp_gfp_mask(vma);
cb196ee1
MWO
830 folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, vma, haddr, true);
831 if (unlikely(!folio)) {
128ec037 832 count_vm_event(THP_FAULT_FALLBACK);
c0292554 833 return VM_FAULT_FALLBACK;
128ec037 834 }
cb196ee1 835 return __do_huge_pmd_anonymous_page(vmf, &folio->page, gfp);
71e3aac0
AA
836}
837
ae18d6dc 838static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
3b6521f5
OH
839 pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write,
840 pgtable_t pgtable)
5cad465d
MW
841{
842 struct mm_struct *mm = vma->vm_mm;
843 pmd_t entry;
844 spinlock_t *ptl;
845
846 ptl = pmd_lock(mm, pmd);
c6f3c5ee
AK
847 if (!pmd_none(*pmd)) {
848 if (write) {
849 if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) {
850 WARN_ON_ONCE(!is_huge_zero_pmd(*pmd));
851 goto out_unlock;
852 }
853 entry = pmd_mkyoung(*pmd);
854 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
855 if (pmdp_set_access_flags(vma, addr, pmd, entry, 1))
856 update_mmu_cache_pmd(vma, addr, pmd);
857 }
858
859 goto out_unlock;
860 }
861
f25748e3
DW
862 entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
863 if (pfn_t_devmap(pfn))
864 entry = pmd_mkdevmap(entry);
01871e59 865 if (write) {
f55e1014
LT
866 entry = pmd_mkyoung(pmd_mkdirty(entry));
867 entry = maybe_pmd_mkwrite(entry, vma);
5cad465d 868 }
3b6521f5
OH
869
870 if (pgtable) {
871 pgtable_trans_huge_deposit(mm, pmd, pgtable);
c4812909 872 mm_inc_nr_ptes(mm);
c6f3c5ee 873 pgtable = NULL;
3b6521f5
OH
874 }
875
01871e59
RZ
876 set_pmd_at(mm, addr, pmd, entry);
877 update_mmu_cache_pmd(vma, addr, pmd);
c6f3c5ee
AK
878
879out_unlock:
5cad465d 880 spin_unlock(ptl);
c6f3c5ee
AK
881 if (pgtable)
882 pte_free(mm, pgtable);
5cad465d
MW
883}
884
9a9731b1 885/**
7b806d22 886 * vmf_insert_pfn_pmd - insert a pmd size pfn
9a9731b1
THV
887 * @vmf: Structure describing the fault
888 * @pfn: pfn to insert
9a9731b1
THV
889 * @write: whether it's a write fault
890 *
7b806d22 891 * Insert a pmd size pfn. See vmf_insert_pfn() for additional info.
9a9731b1
THV
892 *
893 * Return: vm_fault_t value.
894 */
7b806d22 895vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, pfn_t pfn, bool write)
5cad465d 896{
fce86ff5
DW
897 unsigned long addr = vmf->address & PMD_MASK;
898 struct vm_area_struct *vma = vmf->vma;
7b806d22 899 pgprot_t pgprot = vma->vm_page_prot;
3b6521f5 900 pgtable_t pgtable = NULL;
fce86ff5 901
5cad465d
MW
902 /*
903 * If we had pmd_special, we could avoid all these restrictions,
904 * but we need to be consistent with PTEs and architectures that
905 * can't support a 'special' bit.
906 */
e1fb4a08
DJ
907 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
908 !pfn_t_devmap(pfn));
5cad465d
MW
909 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
910 (VM_PFNMAP|VM_MIXEDMAP));
911 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
5cad465d
MW
912
913 if (addr < vma->vm_start || addr >= vma->vm_end)
914 return VM_FAULT_SIGBUS;
308a047c 915
3b6521f5 916 if (arch_needs_pgtable_deposit()) {
4cf58924 917 pgtable = pte_alloc_one(vma->vm_mm);
3b6521f5
OH
918 if (!pgtable)
919 return VM_FAULT_OOM;
920 }
921
308a047c
BP
922 track_pfn_insert(vma, &pgprot, pfn);
923
fce86ff5 924 insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable);
ae18d6dc 925 return VM_FAULT_NOPAGE;
5cad465d 926}
7b806d22 927EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd);
5cad465d 928
a00cc7d9 929#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
f55e1014 930static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)
a00cc7d9 931{
f55e1014 932 if (likely(vma->vm_flags & VM_WRITE))
a00cc7d9
MW
933 pud = pud_mkwrite(pud);
934 return pud;
935}
936
937static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr,
7b806d22 938 pud_t *pud, pfn_t pfn, bool write)
a00cc7d9
MW
939{
940 struct mm_struct *mm = vma->vm_mm;
7b806d22 941 pgprot_t prot = vma->vm_page_prot;
a00cc7d9
MW
942 pud_t entry;
943 spinlock_t *ptl;
944
945 ptl = pud_lock(mm, pud);
c6f3c5ee
AK
946 if (!pud_none(*pud)) {
947 if (write) {
948 if (pud_pfn(*pud) != pfn_t_to_pfn(pfn)) {
949 WARN_ON_ONCE(!is_huge_zero_pud(*pud));
950 goto out_unlock;
951 }
952 entry = pud_mkyoung(*pud);
953 entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma);
954 if (pudp_set_access_flags(vma, addr, pud, entry, 1))
955 update_mmu_cache_pud(vma, addr, pud);
956 }
957 goto out_unlock;
958 }
959
a00cc7d9
MW
960 entry = pud_mkhuge(pfn_t_pud(pfn, prot));
961 if (pfn_t_devmap(pfn))
962 entry = pud_mkdevmap(entry);
963 if (write) {
f55e1014
LT
964 entry = pud_mkyoung(pud_mkdirty(entry));
965 entry = maybe_pud_mkwrite(entry, vma);
a00cc7d9
MW
966 }
967 set_pud_at(mm, addr, pud, entry);
968 update_mmu_cache_pud(vma, addr, pud);
c6f3c5ee
AK
969
970out_unlock:
a00cc7d9
MW
971 spin_unlock(ptl);
972}
973
9a9731b1 974/**
7b806d22 975 * vmf_insert_pfn_pud - insert a pud size pfn
9a9731b1
THV
976 * @vmf: Structure describing the fault
977 * @pfn: pfn to insert
9a9731b1
THV
978 * @write: whether it's a write fault
979 *
7b806d22 980 * Insert a pud size pfn. See vmf_insert_pfn() for additional info.
9a9731b1
THV
981 *
982 * Return: vm_fault_t value.
983 */
7b806d22 984vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, pfn_t pfn, bool write)
a00cc7d9 985{
fce86ff5
DW
986 unsigned long addr = vmf->address & PUD_MASK;
987 struct vm_area_struct *vma = vmf->vma;
7b806d22 988 pgprot_t pgprot = vma->vm_page_prot;
fce86ff5 989
a00cc7d9
MW
990 /*
991 * If we had pud_special, we could avoid all these restrictions,
992 * but we need to be consistent with PTEs and architectures that
993 * can't support a 'special' bit.
994 */
62ec0d8c
DJ
995 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
996 !pfn_t_devmap(pfn));
a00cc7d9
MW
997 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
998 (VM_PFNMAP|VM_MIXEDMAP));
999 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
a00cc7d9
MW
1000
1001 if (addr < vma->vm_start || addr >= vma->vm_end)
1002 return VM_FAULT_SIGBUS;
1003
1004 track_pfn_insert(vma, &pgprot, pfn);
1005
7b806d22 1006 insert_pfn_pud(vma, addr, vmf->pud, pfn, write);
a00cc7d9
MW
1007 return VM_FAULT_NOPAGE;
1008}
7b806d22 1009EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud);
a00cc7d9
MW
1010#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1011
3565fce3 1012static void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
a69e4717 1013 pmd_t *pmd, bool write)
3565fce3
DW
1014{
1015 pmd_t _pmd;
1016
a8f97366 1017 _pmd = pmd_mkyoung(*pmd);
a69e4717 1018 if (write)
a8f97366 1019 _pmd = pmd_mkdirty(_pmd);
3565fce3 1020 if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
a69e4717 1021 pmd, _pmd, write))
3565fce3
DW
1022 update_mmu_cache_pmd(vma, addr, pmd);
1023}
1024
1025struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
df06b37f 1026 pmd_t *pmd, int flags, struct dev_pagemap **pgmap)
3565fce3
DW
1027{
1028 unsigned long pfn = pmd_pfn(*pmd);
1029 struct mm_struct *mm = vma->vm_mm;
3565fce3 1030 struct page *page;
0f089235 1031 int ret;
3565fce3
DW
1032
1033 assert_spin_locked(pmd_lockptr(mm, pmd));
1034
f6f37321 1035 if (flags & FOLL_WRITE && !pmd_write(*pmd))
3565fce3
DW
1036 return NULL;
1037
1038 if (pmd_present(*pmd) && pmd_devmap(*pmd))
1039 /* pass */;
1040 else
1041 return NULL;
1042
1043 if (flags & FOLL_TOUCH)
a69e4717 1044 touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
3565fce3
DW
1045
1046 /*
1047 * device mapped pages can only be returned if the
1048 * caller will manage the page reference count.
1049 */
3faa52c0 1050 if (!(flags & (FOLL_GET | FOLL_PIN)))
3565fce3
DW
1051 return ERR_PTR(-EEXIST);
1052
1053 pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
df06b37f
KB
1054 *pgmap = get_dev_pagemap(pfn, *pgmap);
1055 if (!*pgmap)
3565fce3
DW
1056 return ERR_PTR(-EFAULT);
1057 page = pfn_to_page(pfn);
0f089235
LG
1058 ret = try_grab_page(page, flags);
1059 if (ret)
1060 page = ERR_PTR(ret);
3565fce3
DW
1061
1062 return page;
1063}
1064
71e3aac0
AA
1065int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1066 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
8f34f1ea 1067 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
71e3aac0 1068{
c4088ebd 1069 spinlock_t *dst_ptl, *src_ptl;
71e3aac0
AA
1070 struct page *src_page;
1071 pmd_t pmd;
12c9d70b 1072 pgtable_t pgtable = NULL;
628d47ce 1073 int ret = -ENOMEM;
71e3aac0 1074
628d47ce 1075 /* Skip if can be re-fill on fault */
8f34f1ea 1076 if (!vma_is_anonymous(dst_vma))
628d47ce
KS
1077 return 0;
1078
4cf58924 1079 pgtable = pte_alloc_one(dst_mm);
628d47ce
KS
1080 if (unlikely(!pgtable))
1081 goto out;
71e3aac0 1082
c4088ebd
KS
1083 dst_ptl = pmd_lock(dst_mm, dst_pmd);
1084 src_ptl = pmd_lockptr(src_mm, src_pmd);
1085 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
71e3aac0
AA
1086
1087 ret = -EAGAIN;
1088 pmd = *src_pmd;
84c3fc4e
ZY
1089
1090#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1091 if (unlikely(is_swap_pmd(pmd))) {
1092 swp_entry_t entry = pmd_to_swp_entry(pmd);
1093
1094 VM_BUG_ON(!is_pmd_migration_entry(pmd));
6c287605 1095 if (!is_readable_migration_entry(entry)) {
4dd845b5
AP
1096 entry = make_readable_migration_entry(
1097 swp_offset(entry));
84c3fc4e 1098 pmd = swp_entry_to_pmd(entry);
ab6e3d09
NH
1099 if (pmd_swp_soft_dirty(*src_pmd))
1100 pmd = pmd_swp_mksoft_dirty(pmd);
8f34f1ea
PX
1101 if (pmd_swp_uffd_wp(*src_pmd))
1102 pmd = pmd_swp_mkuffd_wp(pmd);
84c3fc4e
ZY
1103 set_pmd_at(src_mm, addr, src_pmd, pmd);
1104 }
dd8a67f9 1105 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
af5b0f6a 1106 mm_inc_nr_ptes(dst_mm);
dd8a67f9 1107 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
8f34f1ea
PX
1108 if (!userfaultfd_wp(dst_vma))
1109 pmd = pmd_swp_clear_uffd_wp(pmd);
84c3fc4e
ZY
1110 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1111 ret = 0;
1112 goto out_unlock;
1113 }
1114#endif
1115
628d47ce 1116 if (unlikely(!pmd_trans_huge(pmd))) {
71e3aac0
AA
1117 pte_free(dst_mm, pgtable);
1118 goto out_unlock;
1119 }
fc9fe822 1120 /*
c4088ebd 1121 * When page table lock is held, the huge zero pmd should not be
fc9fe822
KS
1122 * under splitting since we don't split the page itself, only pmd to
1123 * a page table.
1124 */
1125 if (is_huge_zero_pmd(pmd)) {
97ae1749
KS
1126 /*
1127 * get_huge_zero_page() will never allocate a new page here,
1128 * since we already have a zero page to copy. It just takes a
1129 * reference.
1130 */
5fc7a5f6
PX
1131 mm_get_huge_zero_page(dst_mm);
1132 goto out_zero_page;
fc9fe822 1133 }
de466bd6 1134
628d47ce
KS
1135 src_page = pmd_page(pmd);
1136 VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
d042035e 1137
fb3d824d
DH
1138 get_page(src_page);
1139 if (unlikely(page_try_dup_anon_rmap(src_page, true, src_vma))) {
1140 /* Page maybe pinned: split and retry the fault on PTEs. */
1141 put_page(src_page);
d042035e
PX
1142 pte_free(dst_mm, pgtable);
1143 spin_unlock(src_ptl);
1144 spin_unlock(dst_ptl);
8f34f1ea 1145 __split_huge_pmd(src_vma, src_pmd, addr, false, NULL);
d042035e
PX
1146 return -EAGAIN;
1147 }
628d47ce 1148 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
5fc7a5f6 1149out_zero_page:
c4812909 1150 mm_inc_nr_ptes(dst_mm);
628d47ce 1151 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
71e3aac0 1152 pmdp_set_wrprotect(src_mm, addr, src_pmd);
8f34f1ea
PX
1153 if (!userfaultfd_wp(dst_vma))
1154 pmd = pmd_clear_uffd_wp(pmd);
71e3aac0
AA
1155 pmd = pmd_mkold(pmd_wrprotect(pmd));
1156 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
71e3aac0
AA
1157
1158 ret = 0;
1159out_unlock:
c4088ebd
KS
1160 spin_unlock(src_ptl);
1161 spin_unlock(dst_ptl);
71e3aac0
AA
1162out:
1163 return ret;
1164}
1165
a00cc7d9
MW
1166#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1167static void touch_pud(struct vm_area_struct *vma, unsigned long addr,
5fe653e9 1168 pud_t *pud, bool write)
a00cc7d9
MW
1169{
1170 pud_t _pud;
1171
a8f97366 1172 _pud = pud_mkyoung(*pud);
5fe653e9 1173 if (write)
a8f97366 1174 _pud = pud_mkdirty(_pud);
a00cc7d9 1175 if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK,
5fe653e9 1176 pud, _pud, write))
a00cc7d9
MW
1177 update_mmu_cache_pud(vma, addr, pud);
1178}
1179
1180struct page *follow_devmap_pud(struct vm_area_struct *vma, unsigned long addr,
df06b37f 1181 pud_t *pud, int flags, struct dev_pagemap **pgmap)
a00cc7d9
MW
1182{
1183 unsigned long pfn = pud_pfn(*pud);
1184 struct mm_struct *mm = vma->vm_mm;
a00cc7d9 1185 struct page *page;
0f089235 1186 int ret;
a00cc7d9
MW
1187
1188 assert_spin_locked(pud_lockptr(mm, pud));
1189
f6f37321 1190 if (flags & FOLL_WRITE && !pud_write(*pud))
a00cc7d9
MW
1191 return NULL;
1192
1193 if (pud_present(*pud) && pud_devmap(*pud))
1194 /* pass */;
1195 else
1196 return NULL;
1197
1198 if (flags & FOLL_TOUCH)
5fe653e9 1199 touch_pud(vma, addr, pud, flags & FOLL_WRITE);
a00cc7d9
MW
1200
1201 /*
1202 * device mapped pages can only be returned if the
1203 * caller will manage the page reference count.
3faa52c0
JH
1204 *
1205 * At least one of FOLL_GET | FOLL_PIN must be set, so assert that here:
a00cc7d9 1206 */
3faa52c0 1207 if (!(flags & (FOLL_GET | FOLL_PIN)))
a00cc7d9
MW
1208 return ERR_PTR(-EEXIST);
1209
1210 pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
df06b37f
KB
1211 *pgmap = get_dev_pagemap(pfn, *pgmap);
1212 if (!*pgmap)
a00cc7d9
MW
1213 return ERR_PTR(-EFAULT);
1214 page = pfn_to_page(pfn);
0f089235
LG
1215
1216 ret = try_grab_page(page, flags);
1217 if (ret)
1218 page = ERR_PTR(ret);
a00cc7d9
MW
1219
1220 return page;
1221}
1222
1223int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1224 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1225 struct vm_area_struct *vma)
1226{
1227 spinlock_t *dst_ptl, *src_ptl;
1228 pud_t pud;
1229 int ret;
1230
1231 dst_ptl = pud_lock(dst_mm, dst_pud);
1232 src_ptl = pud_lockptr(src_mm, src_pud);
1233 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1234
1235 ret = -EAGAIN;
1236 pud = *src_pud;
1237 if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud)))
1238 goto out_unlock;
1239
1240 /*
1241 * When page table lock is held, the huge zero pud should not be
1242 * under splitting since we don't split the page itself, only pud to
1243 * a page table.
1244 */
1245 if (is_huge_zero_pud(pud)) {
1246 /* No huge zero pud yet */
1247 }
1248
fb3d824d
DH
1249 /*
1250 * TODO: once we support anonymous pages, use page_try_dup_anon_rmap()
1251 * and split if duplicating fails.
1252 */
a00cc7d9
MW
1253 pudp_set_wrprotect(src_mm, addr, src_pud);
1254 pud = pud_mkold(pud_wrprotect(pud));
1255 set_pud_at(dst_mm, addr, dst_pud, pud);
1256
1257 ret = 0;
1258out_unlock:
1259 spin_unlock(src_ptl);
1260 spin_unlock(dst_ptl);
1261 return ret;
1262}
1263
1264void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)
1265{
a00cc7d9
MW
1266 bool write = vmf->flags & FAULT_FLAG_WRITE;
1267
1268 vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud);
1269 if (unlikely(!pud_same(*vmf->pud, orig_pud)))
1270 goto unlock;
1271
5fe653e9 1272 touch_pud(vmf->vma, vmf->address, vmf->pud, write);
a00cc7d9
MW
1273unlock:
1274 spin_unlock(vmf->ptl);
1275}
1276#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1277
5db4f15c 1278void huge_pmd_set_accessed(struct vm_fault *vmf)
a1dd450b 1279{
20f664aa 1280 bool write = vmf->flags & FAULT_FLAG_WRITE;
a1dd450b 1281
82b0f8c3 1282 vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd);
a69e4717 1283 if (unlikely(!pmd_same(*vmf->pmd, vmf->orig_pmd)))
a1dd450b
WD
1284 goto unlock;
1285
a69e4717 1286 touch_pmd(vmf->vma, vmf->address, vmf->pmd, write);
a1dd450b
WD
1287
1288unlock:
82b0f8c3 1289 spin_unlock(vmf->ptl);
a1dd450b
WD
1290}
1291
5db4f15c 1292vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
71e3aac0 1293{
c89357e2 1294 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
82b0f8c3 1295 struct vm_area_struct *vma = vmf->vma;
2fad3d14 1296 struct folio *folio;
3917c802 1297 struct page *page;
82b0f8c3 1298 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
5db4f15c 1299 pmd_t orig_pmd = vmf->orig_pmd;
71e3aac0 1300
82b0f8c3 1301 vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
81d1b09c 1302 VM_BUG_ON_VMA(!vma->anon_vma, vma);
3917c802 1303
93b4796d 1304 if (is_huge_zero_pmd(orig_pmd))
3917c802
KS
1305 goto fallback;
1306
82b0f8c3 1307 spin_lock(vmf->ptl);
3917c802
KS
1308
1309 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1310 spin_unlock(vmf->ptl);
1311 return 0;
1312 }
71e3aac0
AA
1313
1314 page = pmd_page(orig_pmd);
2fad3d14 1315 folio = page_folio(page);
f6004e73 1316 VM_BUG_ON_PAGE(!PageHead(page), page);
3917c802 1317
6c287605
DH
1318 /* Early check when only holding the PT lock. */
1319 if (PageAnonExclusive(page))
1320 goto reuse;
1321
2fad3d14
MWO
1322 if (!folio_trylock(folio)) {
1323 folio_get(folio);
ba3c4ce6 1324 spin_unlock(vmf->ptl);
2fad3d14 1325 folio_lock(folio);
ba3c4ce6
HY
1326 spin_lock(vmf->ptl);
1327 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
3917c802 1328 spin_unlock(vmf->ptl);
2fad3d14
MWO
1329 folio_unlock(folio);
1330 folio_put(folio);
3917c802 1331 return 0;
ba3c4ce6 1332 }
2fad3d14 1333 folio_put(folio);
ba3c4ce6 1334 }
3917c802 1335
6c287605
DH
1336 /* Recheck after temporarily dropping the PT lock. */
1337 if (PageAnonExclusive(page)) {
2fad3d14 1338 folio_unlock(folio);
6c287605
DH
1339 goto reuse;
1340 }
1341
3917c802 1342 /*
2fad3d14
MWO
1343 * See do_wp_page(): we can only reuse the folio exclusively if
1344 * there are no additional references. Note that we always drain
1fec6890 1345 * the LRU cache immediately after adding a THP.
3917c802 1346 */
2fad3d14
MWO
1347 if (folio_ref_count(folio) >
1348 1 + folio_test_swapcache(folio) * folio_nr_pages(folio))
3bff7e3f 1349 goto unlock_fallback;
2fad3d14
MWO
1350 if (folio_test_swapcache(folio))
1351 folio_free_swap(folio);
1352 if (folio_ref_count(folio) == 1) {
71e3aac0 1353 pmd_t entry;
6c54dc6c
DH
1354
1355 page_move_anon_rmap(page, vma);
2fad3d14 1356 folio_unlock(folio);
6c287605 1357reuse:
c89357e2
DH
1358 if (unlikely(unshare)) {
1359 spin_unlock(vmf->ptl);
1360 return 0;
1361 }
71e3aac0 1362 entry = pmd_mkyoung(orig_pmd);
f55e1014 1363 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3917c802 1364 if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1))
82b0f8c3 1365 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
82b0f8c3 1366 spin_unlock(vmf->ptl);
cb8d8633 1367 return 0;
71e3aac0 1368 }
3917c802 1369
3bff7e3f 1370unlock_fallback:
2fad3d14 1371 folio_unlock(folio);
82b0f8c3 1372 spin_unlock(vmf->ptl);
3917c802
KS
1373fallback:
1374 __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
1375 return VM_FAULT_FALLBACK;
71e3aac0
AA
1376}
1377
c27f479e
DH
1378static inline bool can_change_pmd_writable(struct vm_area_struct *vma,
1379 unsigned long addr, pmd_t pmd)
1380{
1381 struct page *page;
1382
1383 if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE)))
1384 return false;
1385
1386 /* Don't touch entries that are not even readable (NUMA hinting). */
1387 if (pmd_protnone(pmd))
1388 return false;
1389
1390 /* Do we need write faults for softdirty tracking? */
1391 if (vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd))
1392 return false;
1393
1394 /* Do we need write faults for uffd-wp tracking? */
1395 if (userfaultfd_huge_pmd_wp(vma, pmd))
1396 return false;
1397
1398 if (!(vma->vm_flags & VM_SHARED)) {
1399 /* See can_change_pte_writable(). */
1400 page = vm_normal_page_pmd(vma, addr, pmd);
1401 return page && PageAnon(page) && PageAnonExclusive(page);
1402 }
1403
1404 /* See can_change_pte_writable(). */
1405 return pmd_dirty(pmd);
1406}
1407
5535be30
DH
1408/* FOLL_FORCE can write to even unwritable PMDs in COW mappings. */
1409static inline bool can_follow_write_pmd(pmd_t pmd, struct page *page,
1410 struct vm_area_struct *vma,
1411 unsigned int flags)
8310d48b 1412{
5535be30
DH
1413 /* If the pmd is writable, we can write to the page. */
1414 if (pmd_write(pmd))
1415 return true;
1416
1417 /* Maybe FOLL_FORCE is set to override it? */
1418 if (!(flags & FOLL_FORCE))
1419 return false;
1420
1421 /* But FOLL_FORCE has no effect on shared mappings */
1422 if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
1423 return false;
1424
1425 /* ... or read-only private ones */
1426 if (!(vma->vm_flags & VM_MAYWRITE))
1427 return false;
1428
1429 /* ... or already writable ones that just need to take a write fault */
1430 if (vma->vm_flags & VM_WRITE)
1431 return false;
1432
1433 /*
1434 * See can_change_pte_writable(): we broke COW and could map the page
1435 * writable if we have an exclusive anonymous page ...
1436 */
1437 if (!page || !PageAnon(page) || !PageAnonExclusive(page))
1438 return false;
1439
1440 /* ... and a write-fault isn't required for other reasons. */
1441 if (vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd))
1442 return false;
1443 return !userfaultfd_huge_pmd_wp(vma, pmd);
8310d48b
KF
1444}
1445
b676b293 1446struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
71e3aac0
AA
1447 unsigned long addr,
1448 pmd_t *pmd,
1449 unsigned int flags)
1450{
b676b293 1451 struct mm_struct *mm = vma->vm_mm;
5535be30 1452 struct page *page;
0f089235 1453 int ret;
71e3aac0 1454
c4088ebd 1455 assert_spin_locked(pmd_lockptr(mm, pmd));
71e3aac0 1456
5535be30
DH
1457 page = pmd_page(*pmd);
1458 VM_BUG_ON_PAGE(!PageHead(page) && !is_zone_device_page(page), page);
1459
1460 if ((flags & FOLL_WRITE) &&
1461 !can_follow_write_pmd(*pmd, page, vma, flags))
1462 return NULL;
71e3aac0 1463
85facf25
KS
1464 /* Avoid dumping huge zero page */
1465 if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1466 return ERR_PTR(-EFAULT);
1467
d74943a2 1468 if (pmd_protnone(*pmd) && !gup_can_follow_protnone(vma, flags))
5535be30 1469 return NULL;
3faa52c0 1470
84209e87 1471 if (!pmd_write(*pmd) && gup_must_unshare(vma, flags, page))
a7f22660
DH
1472 return ERR_PTR(-EMLINK);
1473
b6a2619c
DH
1474 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
1475 !PageAnonExclusive(page), page);
1476
0f089235
LG
1477 ret = try_grab_page(page, flags);
1478 if (ret)
1479 return ERR_PTR(ret);
3faa52c0 1480
3565fce3 1481 if (flags & FOLL_TOUCH)
a69e4717 1482 touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
3faa52c0 1483
71e3aac0 1484 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
ca120cf6 1485 VM_BUG_ON_PAGE(!PageCompound(page) && !is_zone_device_page(page), page);
71e3aac0 1486
71e3aac0
AA
1487 return page;
1488}
1489
d10e63f2 1490/* NUMA hinting page fault entry point for trans huge pmds */
5db4f15c 1491vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf)
d10e63f2 1492{
82b0f8c3 1493 struct vm_area_struct *vma = vmf->vma;
c5b5a3dd
YS
1494 pmd_t oldpmd = vmf->orig_pmd;
1495 pmd_t pmd;
b32967ff 1496 struct page *page;
82b0f8c3 1497 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
c5b5a3dd 1498 int page_nid = NUMA_NO_NODE;
33024536 1499 int target_nid, last_cpupid = (-1 & LAST_CPUPID_MASK);
6a56ccbc 1500 bool migrated = false, writable = false;
6688cc05 1501 int flags = 0;
d10e63f2 1502
82b0f8c3 1503 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
c5b5a3dd 1504 if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
82b0f8c3 1505 spin_unlock(vmf->ptl);
de466bd6
MG
1506 goto out;
1507 }
1508
c5b5a3dd 1509 pmd = pmd_modify(oldpmd, vma->vm_page_prot);
6a56ccbc
DH
1510
1511 /*
1512 * Detect now whether the PMD could be writable; this information
1513 * is only valid while holding the PT lock.
1514 */
1515 writable = pmd_write(pmd);
1516 if (!writable && vma_wants_manual_pte_write_upgrade(vma) &&
1517 can_change_pmd_writable(vma, vmf->address, pmd))
1518 writable = true;
1519
c5b5a3dd
YS
1520 page = vm_normal_page_pmd(vma, haddr, pmd);
1521 if (!page)
1522 goto out_map;
1523
1524 /* See similar comment in do_numa_page for explanation */
6a56ccbc 1525 if (!writable)
c5b5a3dd
YS
1526 flags |= TNF_NO_GROUP;
1527
1528 page_nid = page_to_nid(page);
33024536
HY
1529 /*
1530 * For memory tiering mode, cpupid of slow memory page is used
1531 * to record page access time. So use default value.
1532 */
1533 if (node_is_toptier(page_nid))
1534 last_cpupid = page_cpupid_last(page);
c5b5a3dd
YS
1535 target_nid = numa_migrate_prep(page, vma, haddr, page_nid,
1536 &flags);
1537
1538 if (target_nid == NUMA_NO_NODE) {
1539 put_page(page);
1540 goto out_map;
1541 }
1542
82b0f8c3 1543 spin_unlock(vmf->ptl);
6a56ccbc 1544 writable = false;
8b1b436d 1545
c5b5a3dd 1546 migrated = migrate_misplaced_page(page, vma, target_nid);
6688cc05
PZ
1547 if (migrated) {
1548 flags |= TNF_MIGRATED;
8191acbd 1549 page_nid = target_nid;
c5b5a3dd 1550 } else {
074c2381 1551 flags |= TNF_MIGRATE_FAIL;
c5b5a3dd
YS
1552 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1553 if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1554 spin_unlock(vmf->ptl);
1555 goto out;
1556 }
1557 goto out_map;
1558 }
b8916634
MG
1559
1560out:
98fa15f3 1561 if (page_nid != NUMA_NO_NODE)
82b0f8c3 1562 task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR,
9a8b300f 1563 flags);
8191acbd 1564
d10e63f2 1565 return 0;
c5b5a3dd
YS
1566
1567out_map:
1568 /* Restore the PMD */
1569 pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1570 pmd = pmd_mkyoung(pmd);
6a56ccbc 1571 if (writable)
c5b5a3dd
YS
1572 pmd = pmd_mkwrite(pmd);
1573 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
1574 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1575 spin_unlock(vmf->ptl);
1576 goto out;
d10e63f2
MG
1577}
1578
319904ad
HY
1579/*
1580 * Return true if we do MADV_FREE successfully on entire pmd page.
1581 * Otherwise, return false.
1582 */
1583bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
b8d3c4c3 1584 pmd_t *pmd, unsigned long addr, unsigned long next)
b8d3c4c3
MK
1585{
1586 spinlock_t *ptl;
1587 pmd_t orig_pmd;
fc986a38 1588 struct folio *folio;
b8d3c4c3 1589 struct mm_struct *mm = tlb->mm;
319904ad 1590 bool ret = false;
b8d3c4c3 1591
ed6a7935 1592 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
07e32661 1593
b6ec57f4
KS
1594 ptl = pmd_trans_huge_lock(pmd, vma);
1595 if (!ptl)
25eedabe 1596 goto out_unlocked;
b8d3c4c3
MK
1597
1598 orig_pmd = *pmd;
319904ad 1599 if (is_huge_zero_pmd(orig_pmd))
b8d3c4c3 1600 goto out;
b8d3c4c3 1601
84c3fc4e
ZY
1602 if (unlikely(!pmd_present(orig_pmd))) {
1603 VM_BUG_ON(thp_migration_supported() &&
1604 !is_pmd_migration_entry(orig_pmd));
1605 goto out;
1606 }
1607
fc986a38 1608 folio = pfn_folio(pmd_pfn(orig_pmd));
b8d3c4c3 1609 /*
fc986a38
KW
1610 * If other processes are mapping this folio, we couldn't discard
1611 * the folio unless they all do MADV_FREE so let's skip the folio.
b8d3c4c3 1612 */
fc986a38 1613 if (folio_mapcount(folio) != 1)
b8d3c4c3
MK
1614 goto out;
1615
fc986a38 1616 if (!folio_trylock(folio))
b8d3c4c3
MK
1617 goto out;
1618
1619 /*
1620 * If user want to discard part-pages of THP, split it so MADV_FREE
1621 * will deactivate only them.
1622 */
1623 if (next - addr != HPAGE_PMD_SIZE) {
fc986a38 1624 folio_get(folio);
b8d3c4c3 1625 spin_unlock(ptl);
fc986a38
KW
1626 split_folio(folio);
1627 folio_unlock(folio);
1628 folio_put(folio);
b8d3c4c3
MK
1629 goto out_unlocked;
1630 }
1631
fc986a38
KW
1632 if (folio_test_dirty(folio))
1633 folio_clear_dirty(folio);
1634 folio_unlock(folio);
b8d3c4c3 1635
b8d3c4c3 1636 if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
58ceeb6b 1637 pmdp_invalidate(vma, addr, pmd);
b8d3c4c3
MK
1638 orig_pmd = pmd_mkold(orig_pmd);
1639 orig_pmd = pmd_mkclean(orig_pmd);
1640
1641 set_pmd_at(mm, addr, pmd, orig_pmd);
1642 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1643 }
802a3a92 1644
6a6fe9eb 1645 folio_mark_lazyfree(folio);
319904ad 1646 ret = true;
b8d3c4c3
MK
1647out:
1648 spin_unlock(ptl);
1649out_unlocked:
1650 return ret;
1651}
1652
953c66c2
AK
1653static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
1654{
1655 pgtable_t pgtable;
1656
1657 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1658 pte_free(mm, pgtable);
c4812909 1659 mm_dec_nr_ptes(mm);
953c66c2
AK
1660}
1661
71e3aac0 1662int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
f21760b1 1663 pmd_t *pmd, unsigned long addr)
71e3aac0 1664{
da146769 1665 pmd_t orig_pmd;
bf929152 1666 spinlock_t *ptl;
71e3aac0 1667
ed6a7935 1668 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
07e32661 1669
b6ec57f4
KS
1670 ptl = __pmd_trans_huge_lock(pmd, vma);
1671 if (!ptl)
da146769
KS
1672 return 0;
1673 /*
1674 * For architectures like ppc64 we look at deposited pgtable
1675 * when calling pmdp_huge_get_and_clear. So do the
1676 * pgtable_trans_huge_withdraw after finishing pmdp related
1677 * operations.
1678 */
93a98695
AK
1679 orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
1680 tlb->fullmm);
da146769 1681 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
2484ca9b 1682 if (vma_is_special_huge(vma)) {
3b6521f5
OH
1683 if (arch_needs_pgtable_deposit())
1684 zap_deposited_table(tlb->mm, pmd);
da146769 1685 spin_unlock(ptl);
da146769 1686 } else if (is_huge_zero_pmd(orig_pmd)) {
c14a6eb4 1687 zap_deposited_table(tlb->mm, pmd);
da146769 1688 spin_unlock(ptl);
da146769 1689 } else {
616b8371
ZY
1690 struct page *page = NULL;
1691 int flush_needed = 1;
1692
1693 if (pmd_present(orig_pmd)) {
1694 page = pmd_page(orig_pmd);
cea86fe2 1695 page_remove_rmap(page, vma, true);
616b8371
ZY
1696 VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1697 VM_BUG_ON_PAGE(!PageHead(page), page);
1698 } else if (thp_migration_supported()) {
1699 swp_entry_t entry;
1700
1701 VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
1702 entry = pmd_to_swp_entry(orig_pmd);
af5cdaf8 1703 page = pfn_swap_entry_to_page(entry);
616b8371
ZY
1704 flush_needed = 0;
1705 } else
1706 WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
1707
b5072380 1708 if (PageAnon(page)) {
c14a6eb4 1709 zap_deposited_table(tlb->mm, pmd);
b5072380
KS
1710 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1711 } else {
953c66c2
AK
1712 if (arch_needs_pgtable_deposit())
1713 zap_deposited_table(tlb->mm, pmd);
fadae295 1714 add_mm_counter(tlb->mm, mm_counter_file(page), -HPAGE_PMD_NR);
b5072380 1715 }
616b8371 1716
da146769 1717 spin_unlock(ptl);
616b8371
ZY
1718 if (flush_needed)
1719 tlb_remove_page_size(tlb, page, HPAGE_PMD_SIZE);
025c5b24 1720 }
da146769 1721 return 1;
71e3aac0
AA
1722}
1723
1dd38b6c
AK
1724#ifndef pmd_move_must_withdraw
1725static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
1726 spinlock_t *old_pmd_ptl,
1727 struct vm_area_struct *vma)
1728{
1729 /*
1730 * With split pmd lock we also need to move preallocated
1731 * PTE page table if new_pmd is on different PMD page table.
1732 *
1733 * We also don't deposit and withdraw tables for file pages.
1734 */
1735 return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
1736}
1737#endif
1738
ab6e3d09
NH
1739static pmd_t move_soft_dirty_pmd(pmd_t pmd)
1740{
1741#ifdef CONFIG_MEM_SOFT_DIRTY
1742 if (unlikely(is_pmd_migration_entry(pmd)))
1743 pmd = pmd_swp_mksoft_dirty(pmd);
1744 else if (pmd_present(pmd))
1745 pmd = pmd_mksoft_dirty(pmd);
1746#endif
1747 return pmd;
1748}
1749
bf8616d5 1750bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
b8aa9d9d 1751 unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
37a1c49a 1752{
bf929152 1753 spinlock_t *old_ptl, *new_ptl;
37a1c49a 1754 pmd_t pmd;
37a1c49a 1755 struct mm_struct *mm = vma->vm_mm;
5d190420 1756 bool force_flush = false;
37a1c49a 1757
37a1c49a
AA
1758 /*
1759 * The destination pmd shouldn't be established, free_pgtables()
a5be621e
HD
1760 * should have released it; but move_page_tables() might have already
1761 * inserted a page table, if racing against shmem/file collapse.
37a1c49a 1762 */
a5be621e 1763 if (!pmd_none(*new_pmd)) {
37a1c49a 1764 VM_BUG_ON(pmd_trans_huge(*new_pmd));
4b471e88 1765 return false;
37a1c49a
AA
1766 }
1767
bf929152
KS
1768 /*
1769 * We don't have to worry about the ordering of src and dst
c1e8d7c6 1770 * ptlocks because exclusive mmap_lock prevents deadlock.
bf929152 1771 */
b6ec57f4
KS
1772 old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1773 if (old_ptl) {
bf929152
KS
1774 new_ptl = pmd_lockptr(mm, new_pmd);
1775 if (new_ptl != old_ptl)
1776 spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
8809aa2d 1777 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
eb66ae03 1778 if (pmd_present(pmd))
a2ce2666 1779 force_flush = true;
025c5b24 1780 VM_BUG_ON(!pmd_none(*new_pmd));
3592806c 1781
1dd38b6c 1782 if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
b3084f4d 1783 pgtable_t pgtable;
3592806c
KS
1784 pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1785 pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
3592806c 1786 }
ab6e3d09
NH
1787 pmd = move_soft_dirty_pmd(pmd);
1788 set_pmd_at(mm, new_addr, new_pmd, pmd);
5d190420 1789 if (force_flush)
7c38f181 1790 flush_pmd_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
eb66ae03
LT
1791 if (new_ptl != old_ptl)
1792 spin_unlock(new_ptl);
bf929152 1793 spin_unlock(old_ptl);
4b471e88 1794 return true;
37a1c49a 1795 }
4b471e88 1796 return false;
37a1c49a
AA
1797}
1798
f123d74a
MG
1799/*
1800 * Returns
1801 * - 0 if PMD could not be locked
f0953a1b 1802 * - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
e346e668 1803 * or if prot_numa but THP migration is not supported
f0953a1b 1804 * - HPAGE_PMD_NR if protections changed and TLB flush necessary
f123d74a 1805 */
4a18419f
NA
1806int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1807 pmd_t *pmd, unsigned long addr, pgprot_t newprot,
1808 unsigned long cp_flags)
cd7548ab
JW
1809{
1810 struct mm_struct *mm = vma->vm_mm;
bf929152 1811 spinlock_t *ptl;
c9fe6656 1812 pmd_t oldpmd, entry;
58705444 1813 bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
292924b2
PX
1814 bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
1815 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
6a56ccbc 1816 int ret = 1;
cd7548ab 1817
4a18419f
NA
1818 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1819
e346e668
YS
1820 if (prot_numa && !thp_migration_supported())
1821 return 1;
1822
b6ec57f4 1823 ptl = __pmd_trans_huge_lock(pmd, vma);
0a85e51d
KS
1824 if (!ptl)
1825 return 0;
e944fd67 1826
84c3fc4e
ZY
1827#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1828 if (is_swap_pmd(*pmd)) {
1829 swp_entry_t entry = pmd_to_swp_entry(*pmd);
6c287605 1830 struct page *page = pfn_swap_entry_to_page(entry);
24bf08c4 1831 pmd_t newpmd;
84c3fc4e
ZY
1832
1833 VM_BUG_ON(!is_pmd_migration_entry(*pmd));
4dd845b5 1834 if (is_writable_migration_entry(entry)) {
84c3fc4e
ZY
1835 /*
1836 * A protection check is difficult so
1837 * just be safe and disable write
1838 */
6c287605
DH
1839 if (PageAnon(page))
1840 entry = make_readable_exclusive_migration_entry(swp_offset(entry));
1841 else
1842 entry = make_readable_migration_entry(swp_offset(entry));
84c3fc4e 1843 newpmd = swp_entry_to_pmd(entry);
ab6e3d09
NH
1844 if (pmd_swp_soft_dirty(*pmd))
1845 newpmd = pmd_swp_mksoft_dirty(newpmd);
24bf08c4
DH
1846 } else {
1847 newpmd = *pmd;
84c3fc4e 1848 }
24bf08c4
DH
1849
1850 if (uffd_wp)
1851 newpmd = pmd_swp_mkuffd_wp(newpmd);
1852 else if (uffd_wp_resolve)
1853 newpmd = pmd_swp_clear_uffd_wp(newpmd);
1854 if (!pmd_same(*pmd, newpmd))
1855 set_pmd_at(mm, addr, pmd, newpmd);
84c3fc4e
ZY
1856 goto unlock;
1857 }
1858#endif
1859
a1a3a2fc
HY
1860 if (prot_numa) {
1861 struct page *page;
33024536 1862 bool toptier;
a1a3a2fc
HY
1863 /*
1864 * Avoid trapping faults against the zero page. The read-only
1865 * data is likely to be read-cached on the local CPU and
1866 * local/remote hits to the zero page are not interesting.
1867 */
1868 if (is_huge_zero_pmd(*pmd))
1869 goto unlock;
025c5b24 1870
a1a3a2fc
HY
1871 if (pmd_protnone(*pmd))
1872 goto unlock;
0a85e51d 1873
a1a3a2fc 1874 page = pmd_page(*pmd);
33024536 1875 toptier = node_is_toptier(page_to_nid(page));
a1a3a2fc
HY
1876 /*
1877 * Skip scanning top tier node if normal numa
1878 * balancing is disabled
1879 */
1880 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
33024536 1881 toptier)
a1a3a2fc 1882 goto unlock;
33024536
HY
1883
1884 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1885 !toptier)
1886 xchg_page_access_time(page, jiffies_to_msecs(jiffies));
a1a3a2fc 1887 }
ced10803 1888 /*
3e4e28c5 1889 * In case prot_numa, we are under mmap_read_lock(mm). It's critical
ced10803 1890 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
3e4e28c5 1891 * which is also under mmap_read_lock(mm):
ced10803
KS
1892 *
1893 * CPU0: CPU1:
1894 * change_huge_pmd(prot_numa=1)
1895 * pmdp_huge_get_and_clear_notify()
1896 * madvise_dontneed()
1897 * zap_pmd_range()
1898 * pmd_trans_huge(*pmd) == 0 (without ptl)
1899 * // skip the pmd
1900 * set_pmd_at();
1901 * // pmd is re-established
1902 *
1903 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
1904 * which may break userspace.
1905 *
4f831457 1906 * pmdp_invalidate_ad() is required to make sure we don't miss
ced10803
KS
1907 * dirty/young flags set by hardware.
1908 */
4f831457 1909 oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
ced10803 1910
c9fe6656 1911 entry = pmd_modify(oldpmd, newprot);
f1eb1bac 1912 if (uffd_wp)
292924b2 1913 entry = pmd_mkuffd_wp(entry);
f1eb1bac 1914 else if (uffd_wp_resolve)
292924b2
PX
1915 /*
1916 * Leave the write bit to be handled by PF interrupt
1917 * handler, then things like COW could be properly
1918 * handled.
1919 */
1920 entry = pmd_clear_uffd_wp(entry);
c27f479e
DH
1921
1922 /* See change_pte_range(). */
1923 if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) && !pmd_write(entry) &&
1924 can_change_pmd_writable(vma, addr, entry))
1925 entry = pmd_mkwrite(entry);
1926
0a85e51d
KS
1927 ret = HPAGE_PMD_NR;
1928 set_pmd_at(mm, addr, pmd, entry);
4a18419f 1929
c9fe6656
NA
1930 if (huge_pmd_needs_flush(oldpmd, entry))
1931 tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
0a85e51d
KS
1932unlock:
1933 spin_unlock(ptl);
025c5b24
NH
1934 return ret;
1935}
1936
1937/*
8f19b0c0 1938 * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
025c5b24 1939 *
8f19b0c0
HY
1940 * Note that if it returns page table lock pointer, this routine returns without
1941 * unlocking page table lock. So callers must unlock it.
025c5b24 1942 */
b6ec57f4 1943spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
025c5b24 1944{
b6ec57f4
KS
1945 spinlock_t *ptl;
1946 ptl = pmd_lock(vma->vm_mm, pmd);
84c3fc4e
ZY
1947 if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
1948 pmd_devmap(*pmd)))
b6ec57f4
KS
1949 return ptl;
1950 spin_unlock(ptl);
1951 return NULL;
cd7548ab
JW
1952}
1953
a00cc7d9 1954/*
d965e390 1955 * Returns page table lock pointer if a given pud maps a thp, NULL otherwise.
a00cc7d9 1956 *
d965e390
ML
1957 * Note that if it returns page table lock pointer, this routine returns without
1958 * unlocking page table lock. So callers must unlock it.
a00cc7d9
MW
1959 */
1960spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
1961{
1962 spinlock_t *ptl;
1963
1964 ptl = pud_lock(vma->vm_mm, pud);
1965 if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
1966 return ptl;
1967 spin_unlock(ptl);
1968 return NULL;
1969}
1970
1971#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1972int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
1973 pud_t *pud, unsigned long addr)
1974{
a00cc7d9
MW
1975 spinlock_t *ptl;
1976
1977 ptl = __pud_trans_huge_lock(pud, vma);
1978 if (!ptl)
1979 return 0;
74929079 1980
f32928ab 1981 pudp_huge_get_and_clear_full(vma, addr, pud, tlb->fullmm);
a00cc7d9 1982 tlb_remove_pud_tlb_entry(tlb, pud, addr);
2484ca9b 1983 if (vma_is_special_huge(vma)) {
a00cc7d9
MW
1984 spin_unlock(ptl);
1985 /* No zero page support yet */
1986 } else {
1987 /* No support for anonymous PUD pages yet */
1988 BUG();
1989 }
1990 return 1;
1991}
1992
1993static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
1994 unsigned long haddr)
1995{
1996 VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
1997 VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
1998 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
1999 VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
2000
ce9311cf 2001 count_vm_event(THP_SPLIT_PUD);
a00cc7d9 2002
ec8832d0 2003 pudp_huge_clear_flush(vma, haddr, pud);
a00cc7d9
MW
2004}
2005
2006void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
2007 unsigned long address)
2008{
2009 spinlock_t *ptl;
ac46d4f3 2010 struct mmu_notifier_range range;
a00cc7d9 2011
7d4a8be0 2012 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
6f4f13e8 2013 address & HPAGE_PUD_MASK,
ac46d4f3
JG
2014 (address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
2015 mmu_notifier_invalidate_range_start(&range);
2016 ptl = pud_lock(vma->vm_mm, pud);
a00cc7d9
MW
2017 if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
2018 goto out;
ac46d4f3 2019 __split_huge_pud_locked(vma, pud, range.start);
a00cc7d9
MW
2020
2021out:
2022 spin_unlock(ptl);
ec8832d0 2023 mmu_notifier_invalidate_range_end(&range);
a00cc7d9
MW
2024}
2025#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
2026
eef1b3ba
KS
2027static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2028 unsigned long haddr, pmd_t *pmd)
2029{
2030 struct mm_struct *mm = vma->vm_mm;
2031 pgtable_t pgtable;
42b2af2c 2032 pmd_t _pmd, old_pmd;
c9c1ee20
HD
2033 unsigned long addr;
2034 pte_t *pte;
eef1b3ba
KS
2035 int i;
2036
0f10851e
JG
2037 /*
2038 * Leave pmd empty until pte is filled note that it is fine to delay
2039 * notification until mmu_notifier_invalidate_range_end() as we are
2040 * replacing a zero pmd write protected page with a zero pte write
2041 * protected page.
2042 *
ee65728e 2043 * See Documentation/mm/mmu_notifier.rst
0f10851e 2044 */
42b2af2c 2045 old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
eef1b3ba
KS
2046
2047 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2048 pmd_populate(mm, &_pmd, pgtable);
2049
c9c1ee20
HD
2050 pte = pte_offset_map(&_pmd, haddr);
2051 VM_BUG_ON(!pte);
2052 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2053 pte_t entry;
2054
2055 entry = pfn_pte(my_zero_pfn(addr), vma->vm_page_prot);
eef1b3ba 2056 entry = pte_mkspecial(entry);
42b2af2c
DH
2057 if (pmd_uffd_wp(old_pmd))
2058 entry = pte_mkuffd_wp(entry);
c33c7948 2059 VM_BUG_ON(!pte_none(ptep_get(pte)));
c9c1ee20
HD
2060 set_pte_at(mm, addr, pte, entry);
2061 pte++;
eef1b3ba 2062 }
c9c1ee20 2063 pte_unmap(pte - 1);
eef1b3ba
KS
2064 smp_wmb(); /* make pte visible before pmd */
2065 pmd_populate(mm, pmd, pgtable);
eef1b3ba
KS
2066}
2067
2068static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
ba988280 2069 unsigned long haddr, bool freeze)
eef1b3ba
KS
2070{
2071 struct mm_struct *mm = vma->vm_mm;
2072 struct page *page;
2073 pgtable_t pgtable;
423ac9af 2074 pmd_t old_pmd, _pmd;
292924b2 2075 bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
0ccf7f16 2076 bool anon_exclusive = false, dirty = false;
2ac015e2 2077 unsigned long addr;
c9c1ee20 2078 pte_t *pte;
eef1b3ba
KS
2079 int i;
2080
2081 VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2082 VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2083 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
84c3fc4e
ZY
2084 VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
2085 && !pmd_devmap(*pmd));
eef1b3ba
KS
2086
2087 count_vm_event(THP_SPLIT_PMD);
2088
d21b9e57 2089 if (!vma_is_anonymous(vma)) {
ec8832d0 2090 old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
953c66c2
AK
2091 /*
2092 * We are going to unmap this huge page. So
2093 * just go ahead and zap it
2094 */
2095 if (arch_needs_pgtable_deposit())
2096 zap_deposited_table(mm, pmd);
2484ca9b 2097 if (vma_is_special_huge(vma))
d21b9e57 2098 return;
99fa8a48
HD
2099 if (unlikely(is_pmd_migration_entry(old_pmd))) {
2100 swp_entry_t entry;
2101
2102 entry = pmd_to_swp_entry(old_pmd);
af5cdaf8 2103 page = pfn_swap_entry_to_page(entry);
99fa8a48
HD
2104 } else {
2105 page = pmd_page(old_pmd);
2106 if (!PageDirty(page) && pmd_dirty(old_pmd))
2107 set_page_dirty(page);
2108 if (!PageReferenced(page) && pmd_young(old_pmd))
2109 SetPageReferenced(page);
cea86fe2 2110 page_remove_rmap(page, vma, true);
99fa8a48
HD
2111 put_page(page);
2112 }
fadae295 2113 add_mm_counter(mm, mm_counter_file(page), -HPAGE_PMD_NR);
eef1b3ba 2114 return;
99fa8a48
HD
2115 }
2116
3b77e8c8 2117 if (is_huge_zero_pmd(*pmd)) {
4645b9fe
JG
2118 /*
2119 * FIXME: Do we want to invalidate secondary mmu by calling
1af5a810
AP
2120 * mmu_notifier_arch_invalidate_secondary_tlbs() see comments below
2121 * inside __split_huge_pmd() ?
4645b9fe
JG
2122 *
2123 * We are going from a zero huge page write protected to zero
2124 * small page also write protected so it does not seems useful
2125 * to invalidate secondary mmu at this time.
2126 */
eef1b3ba
KS
2127 return __split_huge_zero_page_pmd(vma, haddr, pmd);
2128 }
2129
423ac9af
AK
2130 /*
2131 * Up to this point the pmd is present and huge and userland has the
2132 * whole access to the hugepage during the split (which happens in
2133 * place). If we overwrite the pmd with the not-huge version pointing
2134 * to the pte here (which of course we could if all CPUs were bug
2135 * free), userland could trigger a small page size TLB miss on the
2136 * small sized TLB while the hugepage TLB entry is still established in
2137 * the huge TLB. Some CPU doesn't like that.
42742d9b
AK
2138 * See http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2139 * 383 on page 105. Intel should be safe but is also warns that it's
423ac9af
AK
2140 * only safe if the permission and cache attributes of the two entries
2141 * loaded in the two TLB is identical (which should be the case here).
2142 * But it is generally safer to never allow small and huge TLB entries
2143 * for the same virtual address to be loaded simultaneously. So instead
2144 * of doing "pmd_populate(); flush_pmd_tlb_range();" we first mark the
2145 * current pmd notpresent (atomically because here the pmd_trans_huge
2146 * must remain set at all times on the pmd until the split is complete
2147 * for this pmd), then we flush the SMP TLB and finally we write the
2148 * non-huge version of the pmd entry with pmd_populate.
2149 */
2150 old_pmd = pmdp_invalidate(vma, haddr, pmd);
2151
423ac9af 2152 pmd_migration = is_pmd_migration_entry(old_pmd);
2e83ee1d 2153 if (unlikely(pmd_migration)) {
84c3fc4e
ZY
2154 swp_entry_t entry;
2155
423ac9af 2156 entry = pmd_to_swp_entry(old_pmd);
af5cdaf8 2157 page = pfn_swap_entry_to_page(entry);
4dd845b5 2158 write = is_writable_migration_entry(entry);
6c287605
DH
2159 if (PageAnon(page))
2160 anon_exclusive = is_readable_exclusive_migration_entry(entry);
2e346877
PX
2161 young = is_migration_entry_young(entry);
2162 dirty = is_migration_entry_dirty(entry);
2e83ee1d 2163 soft_dirty = pmd_swp_soft_dirty(old_pmd);
f45ec5ff 2164 uffd_wp = pmd_swp_uffd_wp(old_pmd);
2e83ee1d 2165 } else {
423ac9af 2166 page = pmd_page(old_pmd);
0ccf7f16
PX
2167 if (pmd_dirty(old_pmd)) {
2168 dirty = true;
2e83ee1d 2169 SetPageDirty(page);
0ccf7f16 2170 }
2e83ee1d
PX
2171 write = pmd_write(old_pmd);
2172 young = pmd_young(old_pmd);
2173 soft_dirty = pmd_soft_dirty(old_pmd);
292924b2 2174 uffd_wp = pmd_uffd_wp(old_pmd);
6c287605 2175
9d84604b 2176 VM_BUG_ON_PAGE(!page_count(page), page);
6c287605
DH
2177
2178 /*
2179 * Without "freeze", we'll simply split the PMD, propagating the
2180 * PageAnonExclusive() flag for each PTE by setting it for
2181 * each subpage -- no need to (temporarily) clear.
2182 *
2183 * With "freeze" we want to replace mapped pages by
2184 * migration entries right away. This is only possible if we
2185 * managed to clear PageAnonExclusive() -- see
2186 * set_pmd_migration_entry().
2187 *
2188 * In case we cannot clear PageAnonExclusive(), split the PMD
2189 * only and let try_to_migrate_one() fail later.
088b8aa5
DH
2190 *
2191 * See page_try_share_anon_rmap(): invalidate PMD first.
6c287605
DH
2192 */
2193 anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
2194 if (freeze && anon_exclusive && page_try_share_anon_rmap(page))
2195 freeze = false;
96d82deb
HD
2196 if (!freeze)
2197 page_ref_add(page, HPAGE_PMD_NR - 1);
2e83ee1d 2198 }
eef1b3ba 2199
423ac9af
AK
2200 /*
2201 * Withdraw the table only after we mark the pmd entry invalid.
2202 * This's critical for some architectures (Power).
2203 */
eef1b3ba
KS
2204 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2205 pmd_populate(mm, &_pmd, pgtable);
2206
c9c1ee20
HD
2207 pte = pte_offset_map(&_pmd, haddr);
2208 VM_BUG_ON(!pte);
2ac015e2 2209 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
c9c1ee20 2210 pte_t entry;
eef1b3ba
KS
2211 /*
2212 * Note that NUMA hinting access restrictions are not
2213 * transferred to avoid any possibility of altering
2214 * permissions across VMAs.
2215 */
84c3fc4e 2216 if (freeze || pmd_migration) {
ba988280 2217 swp_entry_t swp_entry;
4dd845b5
AP
2218 if (write)
2219 swp_entry = make_writable_migration_entry(
2220 page_to_pfn(page + i));
6c287605
DH
2221 else if (anon_exclusive)
2222 swp_entry = make_readable_exclusive_migration_entry(
2223 page_to_pfn(page + i));
4dd845b5
AP
2224 else
2225 swp_entry = make_readable_migration_entry(
2226 page_to_pfn(page + i));
2e346877
PX
2227 if (young)
2228 swp_entry = make_migration_entry_young(swp_entry);
2229 if (dirty)
2230 swp_entry = make_migration_entry_dirty(swp_entry);
ba988280 2231 entry = swp_entry_to_pte(swp_entry);
804dd150
AA
2232 if (soft_dirty)
2233 entry = pte_swp_mksoft_dirty(entry);
f45ec5ff
PX
2234 if (uffd_wp)
2235 entry = pte_swp_mkuffd_wp(entry);
ba988280 2236 } else {
6d2329f8 2237 entry = mk_pte(page + i, READ_ONCE(vma->vm_page_prot));
1462c52e 2238 if (write)
f3ebdf04 2239 entry = pte_mkwrite(entry);
6c287605
DH
2240 if (anon_exclusive)
2241 SetPageAnonExclusive(page + i);
ba988280
KS
2242 if (!young)
2243 entry = pte_mkold(entry);
e833bc50
PX
2244 /* NOTE: this may set soft-dirty too on some archs */
2245 if (dirty)
2246 entry = pte_mkdirty(entry);
804dd150
AA
2247 if (soft_dirty)
2248 entry = pte_mksoft_dirty(entry);
292924b2
PX
2249 if (uffd_wp)
2250 entry = pte_mkuffd_wp(entry);
5ba72b4d 2251 page_add_anon_rmap(page + i, vma, addr, RMAP_NONE);
ba988280 2252 }
c33c7948 2253 VM_BUG_ON(!pte_none(ptep_get(pte)));
2ac015e2 2254 set_pte_at(mm, addr, pte, entry);
c9c1ee20 2255 pte++;
eef1b3ba 2256 }
c9c1ee20 2257 pte_unmap(pte - 1);
eef1b3ba 2258
cb67f428
HD
2259 if (!pmd_migration)
2260 page_remove_rmap(page, vma, true);
96d82deb
HD
2261 if (freeze)
2262 put_page(page);
eef1b3ba
KS
2263
2264 smp_wmb(); /* make pte visible before pmd */
2265 pmd_populate(mm, pmd, pgtable);
2266}
2267
2268void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
af28a988 2269 unsigned long address, bool freeze, struct folio *folio)
eef1b3ba
KS
2270{
2271 spinlock_t *ptl;
ac46d4f3 2272 struct mmu_notifier_range range;
eef1b3ba 2273
7d4a8be0 2274 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
6f4f13e8 2275 address & HPAGE_PMD_MASK,
ac46d4f3
JG
2276 (address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2277 mmu_notifier_invalidate_range_start(&range);
2278 ptl = pmd_lock(vma->vm_mm, pmd);
33f4751e
NH
2279
2280 /*
af28a988
MWO
2281 * If caller asks to setup a migration entry, we need a folio to check
2282 * pmd against. Otherwise we can end up replacing wrong folio.
33f4751e 2283 */
af28a988 2284 VM_BUG_ON(freeze && !folio);
83a8441f 2285 VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
33f4751e 2286
7f760917 2287 if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
83a8441f 2288 is_pmd_migration_entry(*pmd)) {
cea33328
ML
2289 /*
2290 * It's safe to call pmd_page when folio is set because it's
2291 * guaranteed that pmd is present.
2292 */
83a8441f
MWO
2293 if (folio && folio != page_folio(pmd_page(*pmd)))
2294 goto out;
7f760917 2295 __split_huge_pmd_locked(vma, pmd, range.start, freeze);
83a8441f 2296 }
7f760917 2297
e90309c9 2298out:
eef1b3ba 2299 spin_unlock(ptl);
ec8832d0 2300 mmu_notifier_invalidate_range_end(&range);
eef1b3ba
KS
2301}
2302
fec89c10 2303void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
af28a988 2304 bool freeze, struct folio *folio)
94fcc585 2305{
50722804 2306 pmd_t *pmd = mm_find_pmd(vma->vm_mm, address);
94fcc585 2307
50722804 2308 if (!pmd)
f72e7dcd
HD
2309 return;
2310
af28a988 2311 __split_huge_pmd(vma, pmd, address, freeze, folio);
94fcc585
AA
2312}
2313
71f9e58e
ML
2314static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2315{
2316 /*
2317 * If the new address isn't hpage aligned and it could previously
2318 * contain an hugepage: check if we need to split an huge pmd.
2319 */
2320 if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2321 range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2322 ALIGN(address, HPAGE_PMD_SIZE)))
2323 split_huge_pmd_address(vma, address, false, NULL);
2324}
2325
e1b9996b 2326void vma_adjust_trans_huge(struct vm_area_struct *vma,
94fcc585
AA
2327 unsigned long start,
2328 unsigned long end,
2329 long adjust_next)
2330{
71f9e58e
ML
2331 /* Check if we need to split start first. */
2332 split_huge_pmd_if_needed(vma, start);
94fcc585 2333
71f9e58e
ML
2334 /* Check if we need to split end next. */
2335 split_huge_pmd_if_needed(vma, end);
94fcc585
AA
2336
2337 /*
68540502 2338 * If we're also updating the next vma vm_start,
71f9e58e 2339 * check if we need to split it.
94fcc585
AA
2340 */
2341 if (adjust_next > 0) {
68540502 2342 struct vm_area_struct *next = find_vma(vma->vm_mm, vma->vm_end);
94fcc585 2343 unsigned long nstart = next->vm_start;
f9d86a60 2344 nstart += adjust_next;
71f9e58e 2345 split_huge_pmd_if_needed(next, nstart);
94fcc585
AA
2346 }
2347}
e9b61f19 2348
684555aa 2349static void unmap_folio(struct folio *folio)
e9b61f19 2350{
a98a2f0c
AP
2351 enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2352 TTU_SYNC;
e9b61f19 2353
684555aa 2354 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
e9b61f19 2355
a98a2f0c
AP
2356 /*
2357 * Anon pages need migration entries to preserve them, but file
2358 * pages can simply be left unmapped, then faulted back on demand.
2359 * If that is ever changed (perhaps for mlock), update remap_page().
2360 */
4b8554c5
MWO
2361 if (folio_test_anon(folio))
2362 try_to_migrate(folio, ttu_flags);
a98a2f0c 2363 else
869f7ee6 2364 try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
e9b61f19
KS
2365}
2366
4eecb8b9 2367static void remap_page(struct folio *folio, unsigned long nr)
e9b61f19 2368{
4eecb8b9 2369 int i = 0;
ab02c252 2370
684555aa 2371 /* If unmap_folio() uses try_to_migrate() on file, remove this check */
4eecb8b9 2372 if (!folio_test_anon(folio))
ab02c252 2373 return;
4eecb8b9
MWO
2374 for (;;) {
2375 remove_migration_ptes(folio, folio, true);
2376 i += folio_nr_pages(folio);
2377 if (i >= nr)
2378 break;
2379 folio = folio_next(folio);
ace71a19 2380 }
e9b61f19
KS
2381}
2382
94866635 2383static void lru_add_page_tail(struct page *head, struct page *tail,
88dcb9a3
AS
2384 struct lruvec *lruvec, struct list_head *list)
2385{
94866635
AS
2386 VM_BUG_ON_PAGE(!PageHead(head), head);
2387 VM_BUG_ON_PAGE(PageCompound(tail), head);
2388 VM_BUG_ON_PAGE(PageLRU(tail), head);
6168d0da 2389 lockdep_assert_held(&lruvec->lru_lock);
88dcb9a3 2390
6dbb5741 2391 if (list) {
88dcb9a3 2392 /* page reclaim is reclaiming a huge page */
6dbb5741 2393 VM_WARN_ON(PageLRU(head));
94866635
AS
2394 get_page(tail);
2395 list_add_tail(&tail->lru, list);
88dcb9a3 2396 } else {
6dbb5741
AS
2397 /* head is still on lru (and we have it frozen) */
2398 VM_WARN_ON(!PageLRU(head));
07ca7606
HD
2399 if (PageUnevictable(tail))
2400 tail->mlock_count = 0;
2401 else
2402 list_add_tail(&tail->lru, &head->lru);
6dbb5741 2403 SetPageLRU(tail);
88dcb9a3
AS
2404 }
2405}
2406
8df651c7 2407static void __split_huge_page_tail(struct page *head, int tail,
e9b61f19
KS
2408 struct lruvec *lruvec, struct list_head *list)
2409{
e9b61f19
KS
2410 struct page *page_tail = head + tail;
2411
8df651c7 2412 VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
e9b61f19
KS
2413
2414 /*
605ca5ed
KK
2415 * Clone page flags before unfreezing refcount.
2416 *
2417 * After successful get_page_unless_zero() might follow flags change,
8958b249 2418 * for example lock_page() which set PG_waiters.
6c287605
DH
2419 *
2420 * Note that for mapped sub-pages of an anonymous THP,
684555aa 2421 * PG_anon_exclusive has been cleared in unmap_folio() and is stored in
6c287605
DH
2422 * the migration entry instead from where remap_page() will restore it.
2423 * We can still have PG_anon_exclusive set on effectively unmapped and
2424 * unreferenced sub-pages of an anonymous THP: we can simply drop
2425 * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
e9b61f19 2426 */
e9b61f19
KS
2427 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
2428 page_tail->flags |= (head->flags &
2429 ((1L << PG_referenced) |
2430 (1L << PG_swapbacked) |
38d8b4e6 2431 (1L << PG_swapcache) |
e9b61f19
KS
2432 (1L << PG_mlocked) |
2433 (1L << PG_uptodate) |
2434 (1L << PG_active) |
1899ad18 2435 (1L << PG_workingset) |
e9b61f19 2436 (1L << PG_locked) |
b8d3c4c3 2437 (1L << PG_unevictable) |
b0284cd2 2438#ifdef CONFIG_ARCH_USES_PG_ARCH_X
72e6afa0 2439 (1L << PG_arch_2) |
ef6458b1 2440 (1L << PG_arch_3) |
72e6afa0 2441#endif
ec1c86b2
YZ
2442 (1L << PG_dirty) |
2443 LRU_GEN_MASK | LRU_REFS_MASK));
e9b61f19 2444
cb67f428 2445 /* ->mapping in first and second tail page is replaced by other uses */
173d9d9f
HD
2446 VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
2447 page_tail);
2448 page_tail->mapping = head->mapping;
2449 page_tail->index = head->index + tail;
71e2d666
MG
2450
2451 /*
2452 * page->private should not be set in tail pages with the exception
2453 * of swap cache pages that store the swp_entry_t in tail pages.
2454 * Fix up and warn once if private is unexpectedly set.
cb67f428 2455 *
94688e8e 2456 * What of 32-bit systems, on which folio->_pincount overlays
cb67f428 2457 * head[1].private? No problem: THP_SWAP is not enabled on 32-bit, and
94688e8e 2458 * pincount must be 0 for folio_ref_freeze() to have succeeded.
71e2d666
MG
2459 */
2460 if (!folio_test_swapcache(page_folio(head))) {
5aae9265 2461 VM_WARN_ON_ONCE_PAGE(page_tail->private != 0, page_tail);
71e2d666
MG
2462 page_tail->private = 0;
2463 }
173d9d9f 2464
605ca5ed 2465 /* Page flags must be visible before we make the page non-compound. */
e9b61f19
KS
2466 smp_wmb();
2467
605ca5ed
KK
2468 /*
2469 * Clear PageTail before unfreezing page refcount.
2470 *
2471 * After successful get_page_unless_zero() might follow put_page()
2472 * which needs correct compound_head().
2473 */
e9b61f19
KS
2474 clear_compound_head(page_tail);
2475
605ca5ed
KK
2476 /* Finally unfreeze refcount. Additional reference from page cache. */
2477 page_ref_unfreeze(page_tail, 1 + (!PageAnon(head) ||
2478 PageSwapCache(head)));
2479
e9b61f19
KS
2480 if (page_is_young(head))
2481 set_page_young(page_tail);
2482 if (page_is_idle(head))
2483 set_page_idle(page_tail);
2484
e9b61f19 2485 page_cpupid_xchg_last(page_tail, page_cpupid_last(head));
94723aaf
MH
2486
2487 /*
2488 * always add to the tail because some iterators expect new
2489 * pages to show after the currently processed elements - e.g.
2490 * migrate_pages
2491 */
e9b61f19 2492 lru_add_page_tail(head, page_tail, lruvec, list);
e9b61f19
KS
2493}
2494
baa355fd 2495static void __split_huge_page(struct page *page, struct list_head *list,
b6769834 2496 pgoff_t end)
e9b61f19 2497{
e809c3fe
MWO
2498 struct folio *folio = page_folio(page);
2499 struct page *head = &folio->page;
e9b61f19 2500 struct lruvec *lruvec;
4101196b
MWO
2501 struct address_space *swap_cache = NULL;
2502 unsigned long offset = 0;
8cce5475 2503 unsigned int nr = thp_nr_pages(head);
8df651c7 2504 int i;
e9b61f19 2505
e9b61f19 2506 /* complete memcg works before add pages to LRU */
be6c8982 2507 split_page_memcg(head, nr);
e9b61f19 2508
4101196b
MWO
2509 if (PageAnon(head) && PageSwapCache(head)) {
2510 swp_entry_t entry = { .val = page_private(head) };
2511
2512 offset = swp_offset(entry);
2513 swap_cache = swap_address_space(entry);
2514 xa_lock(&swap_cache->i_pages);
2515 }
2516
f0953a1b 2517 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */
e809c3fe 2518 lruvec = folio_lruvec_lock(folio);
b6769834 2519
eac96c3e
YS
2520 ClearPageHasHWPoisoned(head);
2521
8cce5475 2522 for (i = nr - 1; i >= 1; i--) {
8df651c7 2523 __split_huge_page_tail(head, i, lruvec, list);
d144bf62 2524 /* Some pages can be beyond EOF: drop them from page cache */
baa355fd 2525 if (head[i].index >= end) {
fb5c2029
MWO
2526 struct folio *tail = page_folio(head + i);
2527
d144bf62 2528 if (shmem_mapping(head->mapping))
800d8c63 2529 shmem_uncharge(head->mapping->host, 1);
fb5c2029
MWO
2530 else if (folio_test_clear_dirty(tail))
2531 folio_account_cleaned(tail,
2532 inode_to_wb(folio->mapping->host));
2533 __filemap_remove_folio(tail, NULL);
2534 folio_put(tail);
4101196b
MWO
2535 } else if (!PageAnon(page)) {
2536 __xa_store(&head->mapping->i_pages, head[i].index,
2537 head + i, 0);
2538 } else if (swap_cache) {
2539 __xa_store(&swap_cache->i_pages, offset + i,
2540 head + i, 0);
baa355fd
KS
2541 }
2542 }
e9b61f19
KS
2543
2544 ClearPageCompound(head);
6168d0da 2545 unlock_page_lruvec(lruvec);
b6769834 2546 /* Caller disabled irqs, so they are still disabled here */
f7da677b 2547
8cce5475 2548 split_page_owner(head, nr);
f7da677b 2549
baa355fd
KS
2550 /* See comment in __split_huge_page_tail() */
2551 if (PageAnon(head)) {
aa5dc07f 2552 /* Additional pin to swap cache */
4101196b 2553 if (PageSwapCache(head)) {
38d8b4e6 2554 page_ref_add(head, 2);
4101196b
MWO
2555 xa_unlock(&swap_cache->i_pages);
2556 } else {
38d8b4e6 2557 page_ref_inc(head);
4101196b 2558 }
baa355fd 2559 } else {
aa5dc07f 2560 /* Additional pin to page cache */
baa355fd 2561 page_ref_add(head, 2);
b93b0163 2562 xa_unlock(&head->mapping->i_pages);
baa355fd 2563 }
b6769834 2564 local_irq_enable();
e9b61f19 2565
4eecb8b9 2566 remap_page(folio, nr);
e9b61f19 2567
c4f9c701
HY
2568 if (PageSwapCache(head)) {
2569 swp_entry_t entry = { .val = page_private(head) };
2570
2571 split_swap_cluster(entry);
2572 }
2573
8cce5475 2574 for (i = 0; i < nr; i++) {
e9b61f19
KS
2575 struct page *subpage = head + i;
2576 if (subpage == page)
2577 continue;
2578 unlock_page(subpage);
2579
2580 /*
2581 * Subpages may be freed if there wasn't any mapping
2582 * like if add_to_swap() is running on a lru page that
2583 * had its mapping zapped. And freeing these pages
2584 * requires taking the lru_lock so we do the put_page
2585 * of the tail pages after the split is complete.
2586 */
0b175468 2587 free_page_and_swap_cache(subpage);
e9b61f19
KS
2588 }
2589}
2590
b8f593cd 2591/* Racy check whether the huge page can be split */
d4b4084a 2592bool can_split_folio(struct folio *folio, int *pextra_pins)
b8f593cd
HY
2593{
2594 int extra_pins;
2595
aa5dc07f 2596 /* Additional pins from page cache */
d4b4084a
MWO
2597 if (folio_test_anon(folio))
2598 extra_pins = folio_test_swapcache(folio) ?
2599 folio_nr_pages(folio) : 0;
b8f593cd 2600 else
d4b4084a 2601 extra_pins = folio_nr_pages(folio);
b8f593cd
HY
2602 if (pextra_pins)
2603 *pextra_pins = extra_pins;
d4b4084a 2604 return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 1;
b8f593cd
HY
2605}
2606
e9b61f19
KS
2607/*
2608 * This function splits huge page into normal pages. @page can point to any
2609 * subpage of huge page to split. Split doesn't change the position of @page.
2610 *
2611 * Only caller must hold pin on the @page, otherwise split fails with -EBUSY.
2612 * The huge page must be locked.
2613 *
2614 * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
2615 *
2616 * Both head page and tail pages will inherit mapping, flags, and so on from
2617 * the hugepage.
2618 *
2619 * GUP pin and PG_locked transferred to @page. Rest subpages can be freed if
2620 * they are not mapped.
2621 *
2622 * Returns 0 if the hugepage is split successfully.
2623 * Returns -EBUSY if the page is pinned or if anon_vma disappeared from under
2624 * us.
2625 */
2626int split_huge_page_to_list(struct page *page, struct list_head *list)
2627{
4eecb8b9 2628 struct folio *folio = page_folio(page);
f8baa6be 2629 struct deferred_split *ds_queue = get_deferred_split_queue(folio);
3e9a13da 2630 XA_STATE(xas, &folio->mapping->i_pages, folio->index);
baa355fd
KS
2631 struct anon_vma *anon_vma = NULL;
2632 struct address_space *mapping = NULL;
504e070d 2633 int extra_pins, ret;
006d3ff2 2634 pgoff_t end;
478d134e 2635 bool is_hzp;
e9b61f19 2636
3e9a13da
MWO
2637 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
2638 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
e9b61f19 2639
3e9a13da 2640 is_hzp = is_huge_zero_page(&folio->page);
4737edbb
NH
2641 if (is_hzp) {
2642 pr_warn_ratelimited("Called split_huge_page for huge zero page\n");
478d134e 2643 return -EBUSY;
4737edbb 2644 }
478d134e 2645
3e9a13da 2646 if (folio_test_writeback(folio))
59807685
HY
2647 return -EBUSY;
2648
3e9a13da 2649 if (folio_test_anon(folio)) {
baa355fd 2650 /*
c1e8d7c6 2651 * The caller does not necessarily hold an mmap_lock that would
baa355fd
KS
2652 * prevent the anon_vma disappearing so we first we take a
2653 * reference to it and then lock the anon_vma for write. This
2f031c6f 2654 * is similar to folio_lock_anon_vma_read except the write lock
baa355fd
KS
2655 * is taken to serialise against parallel split or collapse
2656 * operations.
2657 */
29eea9b5 2658 anon_vma = folio_get_anon_vma(folio);
baa355fd
KS
2659 if (!anon_vma) {
2660 ret = -EBUSY;
2661 goto out;
2662 }
006d3ff2 2663 end = -1;
baa355fd
KS
2664 mapping = NULL;
2665 anon_vma_lock_write(anon_vma);
2666 } else {
6a3edd29
YF
2667 gfp_t gfp;
2668
3e9a13da 2669 mapping = folio->mapping;
baa355fd
KS
2670
2671 /* Truncated ? */
2672 if (!mapping) {
2673 ret = -EBUSY;
2674 goto out;
2675 }
2676
6a3edd29
YF
2677 gfp = current_gfp_context(mapping_gfp_mask(mapping) &
2678 GFP_RECLAIM_MASK);
2679
0201ebf2 2680 if (!filemap_release_folio(folio, gfp)) {
6a3edd29
YF
2681 ret = -EBUSY;
2682 goto out;
2683 }
2684
3e9a13da 2685 xas_split_alloc(&xas, folio, folio_order(folio), gfp);
6b24ca4a
MWO
2686 if (xas_error(&xas)) {
2687 ret = xas_error(&xas);
2688 goto out;
2689 }
2690
baa355fd
KS
2691 anon_vma = NULL;
2692 i_mmap_lock_read(mapping);
006d3ff2
HD
2693
2694 /*
2695 *__split_huge_page() may need to trim off pages beyond EOF:
2696 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
2697 * which cannot be nested inside the page tree lock. So note
2698 * end now: i_size itself may be changed at any moment, but
3e9a13da 2699 * folio lock is good enough to serialize the trimming.
006d3ff2
HD
2700 */
2701 end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
d144bf62
HD
2702 if (shmem_mapping(mapping))
2703 end = shmem_fallocend(mapping->host, end);
e9b61f19 2704 }
e9b61f19
KS
2705
2706 /*
684555aa 2707 * Racy check if we can split the page, before unmap_folio() will
e9b61f19
KS
2708 * split PMDs
2709 */
d4b4084a 2710 if (!can_split_folio(folio, &extra_pins)) {
fd4a7ac3 2711 ret = -EAGAIN;
e9b61f19
KS
2712 goto out_unlock;
2713 }
2714
684555aa 2715 unmap_folio(folio);
e9b61f19 2716
b6769834
AS
2717 /* block interrupt reentry in xa_lock and spinlock */
2718 local_irq_disable();
baa355fd 2719 if (mapping) {
baa355fd 2720 /*
3e9a13da
MWO
2721 * Check if the folio is present in page cache.
2722 * We assume all tail are present too, if folio is there.
baa355fd 2723 */
6b24ca4a
MWO
2724 xas_lock(&xas);
2725 xas_reset(&xas);
3e9a13da 2726 if (xas_load(&xas) != folio)
baa355fd
KS
2727 goto fail;
2728 }
2729
0139aa7b 2730 /* Prevent deferred_split_scan() touching ->_refcount */
364c1eeb 2731 spin_lock(&ds_queue->split_queue_lock);
3e9a13da 2732 if (folio_ref_freeze(folio, 1 + extra_pins)) {
4375a553 2733 if (!list_empty(&folio->_deferred_list)) {
364c1eeb 2734 ds_queue->split_queue_len--;
4375a553 2735 list_del(&folio->_deferred_list);
9a982250 2736 }
afb97172 2737 spin_unlock(&ds_queue->split_queue_lock);
06d3eff6 2738 if (mapping) {
3e9a13da 2739 int nr = folio_nr_pages(folio);
bf9ecead 2740
3e9a13da
MWO
2741 xas_split(&xas, folio, folio_order(folio));
2742 if (folio_test_swapbacked(folio)) {
2743 __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS,
57b2847d 2744 -nr);
1ca7554d 2745 } else {
3e9a13da 2746 __lruvec_stat_mod_folio(folio, NR_FILE_THPS,
bf9ecead 2747 -nr);
1ca7554d
MS
2748 filemap_nr_thps_dec(mapping);
2749 }
06d3eff6
KS
2750 }
2751
b6769834 2752 __split_huge_page(page, list, end);
c4f9c701 2753 ret = 0;
e9b61f19 2754 } else {
364c1eeb 2755 spin_unlock(&ds_queue->split_queue_lock);
504e070d
YS
2756fail:
2757 if (mapping)
6b24ca4a 2758 xas_unlock(&xas);
b6769834 2759 local_irq_enable();
4eecb8b9 2760 remap_page(folio, folio_nr_pages(folio));
fd4a7ac3 2761 ret = -EAGAIN;
e9b61f19
KS
2762 }
2763
2764out_unlock:
baa355fd
KS
2765 if (anon_vma) {
2766 anon_vma_unlock_write(anon_vma);
2767 put_anon_vma(anon_vma);
2768 }
2769 if (mapping)
2770 i_mmap_unlock_read(mapping);
e9b61f19 2771out:
69a37a8b 2772 xas_destroy(&xas);
e9b61f19
KS
2773 count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
2774 return ret;
2775}
9a982250 2776
8dc4a8f1 2777void folio_undo_large_rmappable(struct folio *folio)
9a982250 2778{
8dc4a8f1 2779 struct deferred_split *ds_queue;
9a982250
KS
2780 unsigned long flags;
2781
deedad80
YF
2782 /*
2783 * At this point, there is no one trying to add the folio to
2784 * deferred_list. If folio is not in deferred_list, it's safe
2785 * to check without acquiring the split_queue_lock.
2786 */
8dc4a8f1
MWO
2787 if (data_race(list_empty(&folio->_deferred_list)))
2788 return;
2789
2790 ds_queue = get_deferred_split_queue(folio);
2791 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2792 if (!list_empty(&folio->_deferred_list)) {
2793 ds_queue->split_queue_len--;
2794 list_del(&folio->_deferred_list);
9a982250 2795 }
8dc4a8f1 2796 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
9a982250
KS
2797}
2798
f158ed61 2799void deferred_split_folio(struct folio *folio)
9a982250 2800{
f8baa6be 2801 struct deferred_split *ds_queue = get_deferred_split_queue(folio);
87eaceb3 2802#ifdef CONFIG_MEMCG
8991de90 2803 struct mem_cgroup *memcg = folio_memcg(folio);
87eaceb3 2804#endif
9a982250
KS
2805 unsigned long flags;
2806
8991de90 2807 VM_BUG_ON_FOLIO(folio_order(folio) < 2, folio);
9a982250 2808
87eaceb3
YS
2809 /*
2810 * The try_to_unmap() in page reclaim path might reach here too,
2811 * this may cause a race condition to corrupt deferred split queue.
8991de90 2812 * And, if page reclaim is already handling the same folio, it is
87eaceb3
YS
2813 * unnecessary to handle it again in shrinker.
2814 *
8991de90
MWO
2815 * Check the swapcache flag to determine if the folio is being
2816 * handled by page reclaim since THP swap would add the folio into
87eaceb3
YS
2817 * swap cache before calling try_to_unmap().
2818 */
8991de90 2819 if (folio_test_swapcache(folio))
87eaceb3
YS
2820 return;
2821
8991de90 2822 if (!list_empty(&folio->_deferred_list))
87eaceb3
YS
2823 return;
2824
364c1eeb 2825 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
8991de90 2826 if (list_empty(&folio->_deferred_list)) {
f9719a03 2827 count_vm_event(THP_DEFERRED_SPLIT_PAGE);
8991de90 2828 list_add_tail(&folio->_deferred_list, &ds_queue->split_queue);
364c1eeb 2829 ds_queue->split_queue_len++;
87eaceb3
YS
2830#ifdef CONFIG_MEMCG
2831 if (memcg)
8991de90 2832 set_shrinker_bit(memcg, folio_nid(folio),
2bfd3637 2833 deferred_split_shrinker.id);
87eaceb3 2834#endif
9a982250 2835 }
364c1eeb 2836 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
9a982250
KS
2837}
2838
2839static unsigned long deferred_split_count(struct shrinker *shrink,
2840 struct shrink_control *sc)
2841{
a3d0a918 2842 struct pglist_data *pgdata = NODE_DATA(sc->nid);
364c1eeb 2843 struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
87eaceb3
YS
2844
2845#ifdef CONFIG_MEMCG
2846 if (sc->memcg)
2847 ds_queue = &sc->memcg->deferred_split_queue;
2848#endif
364c1eeb 2849 return READ_ONCE(ds_queue->split_queue_len);
9a982250
KS
2850}
2851
2852static unsigned long deferred_split_scan(struct shrinker *shrink,
2853 struct shrink_control *sc)
2854{
a3d0a918 2855 struct pglist_data *pgdata = NODE_DATA(sc->nid);
364c1eeb 2856 struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
9a982250 2857 unsigned long flags;
4375a553
MWO
2858 LIST_HEAD(list);
2859 struct folio *folio, *next;
9a982250
KS
2860 int split = 0;
2861
87eaceb3
YS
2862#ifdef CONFIG_MEMCG
2863 if (sc->memcg)
2864 ds_queue = &sc->memcg->deferred_split_queue;
2865#endif
2866
364c1eeb 2867 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
9a982250 2868 /* Take pin on all head pages to avoid freeing them under us */
4375a553
MWO
2869 list_for_each_entry_safe(folio, next, &ds_queue->split_queue,
2870 _deferred_list) {
2871 if (folio_try_get(folio)) {
2872 list_move(&folio->_deferred_list, &list);
e3ae1953 2873 } else {
4375a553
MWO
2874 /* We lost race with folio_put() */
2875 list_del_init(&folio->_deferred_list);
364c1eeb 2876 ds_queue->split_queue_len--;
9a982250 2877 }
e3ae1953
KS
2878 if (!--sc->nr_to_scan)
2879 break;
9a982250 2880 }
364c1eeb 2881 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
9a982250 2882
4375a553
MWO
2883 list_for_each_entry_safe(folio, next, &list, _deferred_list) {
2884 if (!folio_trylock(folio))
fa41b900 2885 goto next;
9a982250 2886 /* split_huge_page() removes page from list on success */
4375a553 2887 if (!split_folio(folio))
9a982250 2888 split++;
4375a553 2889 folio_unlock(folio);
fa41b900 2890next:
4375a553 2891 folio_put(folio);
9a982250
KS
2892 }
2893
364c1eeb
YS
2894 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2895 list_splice_tail(&list, &ds_queue->split_queue);
2896 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
9a982250 2897
cb8d68ec
KS
2898 /*
2899 * Stop shrinker if we didn't split any page, but the queue is empty.
2900 * This can happen if pages were freed under us.
2901 */
364c1eeb 2902 if (!split && list_empty(&ds_queue->split_queue))
cb8d68ec
KS
2903 return SHRINK_STOP;
2904 return split;
9a982250
KS
2905}
2906
2907static struct shrinker deferred_split_shrinker = {
2908 .count_objects = deferred_split_count,
2909 .scan_objects = deferred_split_scan,
2910 .seeks = DEFAULT_SEEKS,
87eaceb3
YS
2911 .flags = SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE |
2912 SHRINKER_NONSLAB,
9a982250 2913};
49071d43
KS
2914
2915#ifdef CONFIG_DEBUG_FS
fa6c0231 2916static void split_huge_pages_all(void)
49071d43
KS
2917{
2918 struct zone *zone;
2919 struct page *page;
630e7c5e 2920 struct folio *folio;
49071d43
KS
2921 unsigned long pfn, max_zone_pfn;
2922 unsigned long total = 0, split = 0;
2923
fa6c0231 2924 pr_debug("Split all THPs\n");
a17206da
ML
2925 for_each_zone(zone) {
2926 if (!managed_zone(zone))
2927 continue;
49071d43
KS
2928 max_zone_pfn = zone_end_pfn(zone);
2929 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
a17206da 2930 int nr_pages;
49071d43 2931
2b7aa91b 2932 page = pfn_to_online_page(pfn);
630e7c5e
KW
2933 if (!page || PageTail(page))
2934 continue;
2935 folio = page_folio(page);
2936 if (!folio_try_get(folio))
49071d43
KS
2937 continue;
2938
630e7c5e 2939 if (unlikely(page_folio(page) != folio))
49071d43
KS
2940 goto next;
2941
630e7c5e 2942 if (zone != folio_zone(folio))
49071d43
KS
2943 goto next;
2944
630e7c5e
KW
2945 if (!folio_test_large(folio)
2946 || folio_test_hugetlb(folio)
2947 || !folio_test_lru(folio))
49071d43
KS
2948 goto next;
2949
2950 total++;
630e7c5e
KW
2951 folio_lock(folio);
2952 nr_pages = folio_nr_pages(folio);
2953 if (!split_folio(folio))
49071d43 2954 split++;
a17206da 2955 pfn += nr_pages - 1;
630e7c5e 2956 folio_unlock(folio);
49071d43 2957next:
630e7c5e 2958 folio_put(folio);
fa6c0231 2959 cond_resched();
49071d43
KS
2960 }
2961 }
2962
fa6c0231
ZY
2963 pr_debug("%lu of %lu THP split\n", split, total);
2964}
49071d43 2965
fa6c0231
ZY
2966static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
2967{
2968 return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
2969 is_vm_hugetlb_page(vma);
2970}
2971
2972static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
2973 unsigned long vaddr_end)
2974{
2975 int ret = 0;
2976 struct task_struct *task;
2977 struct mm_struct *mm;
2978 unsigned long total = 0, split = 0;
2979 unsigned long addr;
2980
2981 vaddr_start &= PAGE_MASK;
2982 vaddr_end &= PAGE_MASK;
2983
2984 /* Find the task_struct from pid */
2985 rcu_read_lock();
2986 task = find_task_by_vpid(pid);
2987 if (!task) {
2988 rcu_read_unlock();
2989 ret = -ESRCH;
2990 goto out;
2991 }
2992 get_task_struct(task);
2993 rcu_read_unlock();
2994
2995 /* Find the mm_struct */
2996 mm = get_task_mm(task);
2997 put_task_struct(task);
2998
2999 if (!mm) {
3000 ret = -EINVAL;
3001 goto out;
3002 }
3003
3004 pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
3005 pid, vaddr_start, vaddr_end);
3006
3007 mmap_read_lock(mm);
3008 /*
3009 * always increase addr by PAGE_SIZE, since we could have a PTE page
3010 * table filled with PTE-mapped THPs, each of which is distinct.
3011 */
3012 for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
74ba2b38 3013 struct vm_area_struct *vma = vma_lookup(mm, addr);
fa6c0231
ZY
3014 struct page *page;
3015
74ba2b38 3016 if (!vma)
fa6c0231
ZY
3017 break;
3018
3019 /* skip special VMA and hugetlb VMA */
3020 if (vma_not_suitable_for_thp_split(vma)) {
3021 addr = vma->vm_end;
3022 continue;
3023 }
3024
3025 /* FOLL_DUMP to ignore special (like zero) pages */
87d2762e 3026 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
fa6c0231 3027
f7091ed6 3028 if (IS_ERR_OR_NULL(page))
fa6c0231
ZY
3029 continue;
3030
3031 if (!is_transparent_hugepage(page))
3032 goto next;
3033
3034 total++;
d4b4084a 3035 if (!can_split_folio(page_folio(page), NULL))
fa6c0231
ZY
3036 goto next;
3037
3038 if (!trylock_page(page))
3039 goto next;
3040
3041 if (!split_huge_page(page))
3042 split++;
3043
3044 unlock_page(page);
3045next:
3046 put_page(page);
3047 cond_resched();
3048 }
3049 mmap_read_unlock(mm);
3050 mmput(mm);
3051
3052 pr_debug("%lu of %lu THP split\n", split, total);
3053
3054out:
3055 return ret;
49071d43 3056}
fa6c0231 3057
fbe37501
ZY
3058static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
3059 pgoff_t off_end)
3060{
3061 struct filename *file;
3062 struct file *candidate;
3063 struct address_space *mapping;
3064 int ret = -EINVAL;
3065 pgoff_t index;
3066 int nr_pages = 1;
3067 unsigned long total = 0, split = 0;
3068
3069 file = getname_kernel(file_path);
3070 if (IS_ERR(file))
3071 return ret;
3072
3073 candidate = file_open_name(file, O_RDONLY, 0);
3074 if (IS_ERR(candidate))
3075 goto out;
3076
3077 pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
3078 file_path, off_start, off_end);
3079
3080 mapping = candidate->f_mapping;
3081
3082 for (index = off_start; index < off_end; index += nr_pages) {
1fb130b2 3083 struct folio *folio = filemap_get_folio(mapping, index);
fbe37501
ZY
3084
3085 nr_pages = 1;
66dabbb6 3086 if (IS_ERR(folio))
fbe37501
ZY
3087 continue;
3088
9ee2c086 3089 if (!folio_test_large(folio))
fbe37501
ZY
3090 goto next;
3091
3092 total++;
9ee2c086 3093 nr_pages = folio_nr_pages(folio);
fbe37501 3094
9ee2c086 3095 if (!folio_trylock(folio))
fbe37501
ZY
3096 goto next;
3097
9ee2c086 3098 if (!split_folio(folio))
fbe37501
ZY
3099 split++;
3100
9ee2c086 3101 folio_unlock(folio);
fbe37501 3102next:
9ee2c086 3103 folio_put(folio);
fbe37501
ZY
3104 cond_resched();
3105 }
3106
3107 filp_close(candidate, NULL);
3108 ret = 0;
3109
3110 pr_debug("%lu of %lu file-backed THP split\n", split, total);
3111out:
3112 putname(file);
3113 return ret;
3114}
3115
fa6c0231
ZY
3116#define MAX_INPUT_BUF_SZ 255
3117
3118static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
3119 size_t count, loff_t *ppops)
3120{
3121 static DEFINE_MUTEX(split_debug_mutex);
3122 ssize_t ret;
fbe37501
ZY
3123 /* hold pid, start_vaddr, end_vaddr or file_path, off_start, off_end */
3124 char input_buf[MAX_INPUT_BUF_SZ];
fa6c0231
ZY
3125 int pid;
3126 unsigned long vaddr_start, vaddr_end;
3127
3128 ret = mutex_lock_interruptible(&split_debug_mutex);
3129 if (ret)
3130 return ret;
3131
3132 ret = -EFAULT;
3133
3134 memset(input_buf, 0, MAX_INPUT_BUF_SZ);
3135 if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
3136 goto out;
3137
3138 input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
fbe37501
ZY
3139
3140 if (input_buf[0] == '/') {
3141 char *tok;
3142 char *buf = input_buf;
3143 char file_path[MAX_INPUT_BUF_SZ];
3144 pgoff_t off_start = 0, off_end = 0;
3145 size_t input_len = strlen(input_buf);
3146
3147 tok = strsep(&buf, ",");
3148 if (tok) {
1212e00c 3149 strcpy(file_path, tok);
fbe37501
ZY
3150 } else {
3151 ret = -EINVAL;
3152 goto out;
3153 }
3154
3155 ret = sscanf(buf, "0x%lx,0x%lx", &off_start, &off_end);
3156 if (ret != 2) {
3157 ret = -EINVAL;
3158 goto out;
3159 }
3160 ret = split_huge_pages_in_file(file_path, off_start, off_end);
3161 if (!ret)
3162 ret = input_len;
3163
3164 goto out;
3165 }
3166
fa6c0231
ZY
3167 ret = sscanf(input_buf, "%d,0x%lx,0x%lx", &pid, &vaddr_start, &vaddr_end);
3168 if (ret == 1 && pid == 1) {
3169 split_huge_pages_all();
3170 ret = strlen(input_buf);
3171 goto out;
3172 } else if (ret != 3) {
3173 ret = -EINVAL;
3174 goto out;
3175 }
3176
3177 ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end);
3178 if (!ret)
3179 ret = strlen(input_buf);
3180out:
3181 mutex_unlock(&split_debug_mutex);
3182 return ret;
3183
3184}
3185
3186static const struct file_operations split_huge_pages_fops = {
3187 .owner = THIS_MODULE,
3188 .write = split_huge_pages_write,
3189 .llseek = no_llseek,
3190};
49071d43
KS
3191
3192static int __init split_huge_pages_debugfs(void)
3193{
d9f7979c
GKH
3194 debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3195 &split_huge_pages_fops);
49071d43
KS
3196 return 0;
3197}
3198late_initcall(split_huge_pages_debugfs);
3199#endif
616b8371
ZY
3200
3201#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
7f5abe60 3202int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
616b8371
ZY
3203 struct page *page)
3204{
3205 struct vm_area_struct *vma = pvmw->vma;
3206 struct mm_struct *mm = vma->vm_mm;
3207 unsigned long address = pvmw->address;
6c287605 3208 bool anon_exclusive;
616b8371
ZY
3209 pmd_t pmdval;
3210 swp_entry_t entry;
ab6e3d09 3211 pmd_t pmdswp;
616b8371
ZY
3212
3213 if (!(pvmw->pmd && !pvmw->pte))
7f5abe60 3214 return 0;
616b8371 3215
616b8371 3216 flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
8a8683ad 3217 pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
6c287605 3218
088b8aa5 3219 /* See page_try_share_anon_rmap(): invalidate PMD first. */
6c287605
DH
3220 anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
3221 if (anon_exclusive && page_try_share_anon_rmap(page)) {
3222 set_pmd_at(mm, address, pvmw->pmd, pmdval);
7f5abe60 3223 return -EBUSY;
6c287605
DH
3224 }
3225
616b8371
ZY
3226 if (pmd_dirty(pmdval))
3227 set_page_dirty(page);
4dd845b5
AP
3228 if (pmd_write(pmdval))
3229 entry = make_writable_migration_entry(page_to_pfn(page));
6c287605
DH
3230 else if (anon_exclusive)
3231 entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
4dd845b5
AP
3232 else
3233 entry = make_readable_migration_entry(page_to_pfn(page));
2e346877
PX
3234 if (pmd_young(pmdval))
3235 entry = make_migration_entry_young(entry);
3236 if (pmd_dirty(pmdval))
3237 entry = make_migration_entry_dirty(entry);
ab6e3d09
NH
3238 pmdswp = swp_entry_to_pmd(entry);
3239 if (pmd_soft_dirty(pmdval))
3240 pmdswp = pmd_swp_mksoft_dirty(pmdswp);
24bf08c4
DH
3241 if (pmd_uffd_wp(pmdval))
3242 pmdswp = pmd_swp_mkuffd_wp(pmdswp);
ab6e3d09 3243 set_pmd_at(mm, address, pvmw->pmd, pmdswp);
cea86fe2 3244 page_remove_rmap(page, vma, true);
616b8371 3245 put_page(page);
283fd6fe 3246 trace_set_migration_pmd(address, pmd_val(pmdswp));
7f5abe60
DH
3247
3248 return 0;
616b8371
ZY
3249}
3250
3251void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
3252{
3253 struct vm_area_struct *vma = pvmw->vma;
3254 struct mm_struct *mm = vma->vm_mm;
3255 unsigned long address = pvmw->address;
4fba8f2a 3256 unsigned long haddr = address & HPAGE_PMD_MASK;
616b8371
ZY
3257 pmd_t pmde;
3258 swp_entry_t entry;
3259
3260 if (!(pvmw->pmd && !pvmw->pte))
3261 return;
3262
3263 entry = pmd_to_swp_entry(*pvmw->pmd);
3264 get_page(new);
2e346877 3265 pmde = mk_huge_pmd(new, READ_ONCE(vma->vm_page_prot));
ab6e3d09
NH
3266 if (pmd_swp_soft_dirty(*pvmw->pmd))
3267 pmde = pmd_mksoft_dirty(pmde);
3c811f78 3268 if (is_writable_migration_entry(entry))
f3ebdf04 3269 pmde = pmd_mkwrite(pmde);
8f34f1ea 3270 if (pmd_swp_uffd_wp(*pvmw->pmd))
f1eb1bac 3271 pmde = pmd_mkuffd_wp(pmde);
2e346877
PX
3272 if (!is_migration_entry_young(entry))
3273 pmde = pmd_mkold(pmde);
3274 /* NOTE: this may contain setting soft-dirty on some archs */
3275 if (PageDirty(new) && is_migration_entry_dirty(entry))
3276 pmde = pmd_mkdirty(pmde);
616b8371 3277
6c287605
DH
3278 if (PageAnon(new)) {
3279 rmap_t rmap_flags = RMAP_COMPOUND;
3280
3281 if (!is_readable_migration_entry(entry))
3282 rmap_flags |= RMAP_EXCLUSIVE;
3283
4fba8f2a 3284 page_add_anon_rmap(new, vma, haddr, rmap_flags);
6c287605 3285 } else {
cea86fe2 3286 page_add_file_rmap(new, vma, true);
6c287605
DH
3287 }
3288 VM_BUG_ON(pmd_write(pmde) && PageAnon(new) && !PageAnonExclusive(new));
4fba8f2a 3289 set_pmd_at(mm, haddr, pvmw->pmd, pmde);
5cbcf225
MS
3290
3291 /* No need to invalidate - it was non-present before */
616b8371 3292 update_mmu_cache_pmd(vma, address, pvmw->pmd);
283fd6fe 3293 trace_remove_migration_pmd(address, pmd_val(pmde));
616b8371
ZY
3294}
3295#endif