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