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