xref: /linux/mm/huge_memory.c (revision 0c3beacf681ec897e0b36685a9b49d01f5cb2dfb)
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/numa_balancing.h>
12 #include <linux/highmem.h>
13 #include <linux/hugetlb.h>
14 #include <linux/mmu_notifier.h>
15 #include <linux/rmap.h>
16 #include <linux/swap.h>
17 #include <linux/shrinker.h>
18 #include <linux/mm_inline.h>
19 #include <linux/swapops.h>
20 #include <linux/backing-dev.h>
21 #include <linux/dax.h>
22 #include <linux/mm_types.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 #include <linux/pgalloc_tag.h>
42 #include <linux/pagewalk.h>
43 
44 #include <asm/tlb.h>
45 #include <asm/pgalloc.h>
46 #include "internal.h"
47 #include "swap.h"
48 
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/thp.h>
51 
52 /*
53  * By default, transparent hugepage support is disabled in order to avoid
54  * risking an increased memory footprint for applications that are not
55  * guaranteed to benefit from it. When transparent hugepage support is
56  * enabled, it is for all mappings, and khugepaged scans all mappings.
57  * Defrag is invoked by khugepaged hugepage allocations and by page faults
58  * for all hugepage allocations.
59  */
60 unsigned long transparent_hugepage_flags __read_mostly =
61 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
62 	(1<<TRANSPARENT_HUGEPAGE_FLAG)|
63 #endif
64 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
65 	(1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
66 #endif
67 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
68 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
69 	(1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
70 
71 static struct shrinker *deferred_split_shrinker;
72 static unsigned long deferred_split_count(struct shrinker *shrink,
73 					  struct shrink_control *sc);
74 static unsigned long deferred_split_scan(struct shrinker *shrink,
75 					 struct shrink_control *sc);
76 static bool split_underused_thp = true;
77 
78 static atomic_t huge_zero_refcount;
79 struct folio *huge_zero_folio __read_mostly;
80 unsigned long huge_zero_pfn __read_mostly = ~0UL;
81 unsigned long huge_anon_orders_always __read_mostly;
82 unsigned long huge_anon_orders_madvise __read_mostly;
83 unsigned long huge_anon_orders_inherit __read_mostly;
84 static bool anon_orders_configured __initdata;
85 
86 static inline bool file_thp_enabled(struct vm_area_struct *vma)
87 {
88 	struct inode *inode;
89 
90 	if (!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS))
91 		return false;
92 
93 	if (!vma->vm_file)
94 		return false;
95 
96 	inode = file_inode(vma->vm_file);
97 
98 	return !inode_is_open_for_write(inode) && S_ISREG(inode->i_mode);
99 }
100 
101 unsigned long __thp_vma_allowable_orders(struct vm_area_struct *vma,
102 					 unsigned long vm_flags,
103 					 unsigned long tva_flags,
104 					 unsigned long orders)
105 {
106 	bool smaps = tva_flags & TVA_SMAPS;
107 	bool in_pf = tva_flags & TVA_IN_PF;
108 	bool enforce_sysfs = tva_flags & TVA_ENFORCE_SYSFS;
109 	unsigned long supported_orders;
110 
111 	/* Check the intersection of requested and supported orders. */
112 	if (vma_is_anonymous(vma))
113 		supported_orders = THP_ORDERS_ALL_ANON;
114 	else if (vma_is_special_huge(vma))
115 		supported_orders = THP_ORDERS_ALL_SPECIAL;
116 	else
117 		supported_orders = THP_ORDERS_ALL_FILE_DEFAULT;
118 
119 	orders &= supported_orders;
120 	if (!orders)
121 		return 0;
122 
123 	if (!vma->vm_mm)		/* vdso */
124 		return 0;
125 
126 	if (thp_disabled_by_hw() || vma_thp_disabled(vma, vm_flags))
127 		return 0;
128 
129 	/* khugepaged doesn't collapse DAX vma, but page fault is fine. */
130 	if (vma_is_dax(vma))
131 		return in_pf ? orders : 0;
132 
133 	/*
134 	 * khugepaged special VMA and hugetlb VMA.
135 	 * Must be checked after dax since some dax mappings may have
136 	 * VM_MIXEDMAP set.
137 	 */
138 	if (!in_pf && !smaps && (vm_flags & VM_NO_KHUGEPAGED))
139 		return 0;
140 
141 	/*
142 	 * Check alignment for file vma and size for both file and anon vma by
143 	 * filtering out the unsuitable orders.
144 	 *
145 	 * Skip the check for page fault. Huge fault does the check in fault
146 	 * handlers.
147 	 */
148 	if (!in_pf) {
149 		int order = highest_order(orders);
150 		unsigned long addr;
151 
152 		while (orders) {
153 			addr = vma->vm_end - (PAGE_SIZE << order);
154 			if (thp_vma_suitable_order(vma, addr, order))
155 				break;
156 			order = next_order(&orders, order);
157 		}
158 
159 		if (!orders)
160 			return 0;
161 	}
162 
163 	/*
164 	 * Enabled via shmem mount options or sysfs settings.
165 	 * Must be done before hugepage flags check since shmem has its
166 	 * own flags.
167 	 */
168 	if (!in_pf && shmem_file(vma->vm_file))
169 		return shmem_allowable_huge_orders(file_inode(vma->vm_file),
170 						   vma, vma->vm_pgoff, 0,
171 						   !enforce_sysfs);
172 
173 	if (!vma_is_anonymous(vma)) {
174 		/*
175 		 * Enforce sysfs THP requirements as necessary. Anonymous vmas
176 		 * were already handled in thp_vma_allowable_orders().
177 		 */
178 		if (enforce_sysfs &&
179 		    (!hugepage_global_enabled() || (!(vm_flags & VM_HUGEPAGE) &&
180 						    !hugepage_global_always())))
181 			return 0;
182 
183 		/*
184 		 * Trust that ->huge_fault() handlers know what they are doing
185 		 * in fault path.
186 		 */
187 		if (((in_pf || smaps)) && vma->vm_ops->huge_fault)
188 			return orders;
189 		/* Only regular file is valid in collapse path */
190 		if (((!in_pf || smaps)) && file_thp_enabled(vma))
191 			return orders;
192 		return 0;
193 	}
194 
195 	if (vma_is_temporary_stack(vma))
196 		return 0;
197 
198 	/*
199 	 * THPeligible bit of smaps should show 1 for proper VMAs even
200 	 * though anon_vma is not initialized yet.
201 	 *
202 	 * Allow page fault since anon_vma may be not initialized until
203 	 * the first page fault.
204 	 */
205 	if (!vma->anon_vma)
206 		return (smaps || in_pf) ? orders : 0;
207 
208 	return orders;
209 }
210 
211 static bool get_huge_zero_page(void)
212 {
213 	struct folio *zero_folio;
214 retry:
215 	if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
216 		return true;
217 
218 	zero_folio = folio_alloc((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
219 			HPAGE_PMD_ORDER);
220 	if (!zero_folio) {
221 		count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
222 		return false;
223 	}
224 	/* Ensure zero folio won't have large_rmappable flag set. */
225 	folio_clear_large_rmappable(zero_folio);
226 	preempt_disable();
227 	if (cmpxchg(&huge_zero_folio, NULL, zero_folio)) {
228 		preempt_enable();
229 		folio_put(zero_folio);
230 		goto retry;
231 	}
232 	WRITE_ONCE(huge_zero_pfn, folio_pfn(zero_folio));
233 
234 	/* We take additional reference here. It will be put back by shrinker */
235 	atomic_set(&huge_zero_refcount, 2);
236 	preempt_enable();
237 	count_vm_event(THP_ZERO_PAGE_ALLOC);
238 	return true;
239 }
240 
241 static void put_huge_zero_page(void)
242 {
243 	/*
244 	 * Counter should never go to zero here. Only shrinker can put
245 	 * last reference.
246 	 */
247 	BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
248 }
249 
250 struct folio *mm_get_huge_zero_folio(struct mm_struct *mm)
251 {
252 	if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
253 		return READ_ONCE(huge_zero_folio);
254 
255 	if (!get_huge_zero_page())
256 		return NULL;
257 
258 	if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
259 		put_huge_zero_page();
260 
261 	return READ_ONCE(huge_zero_folio);
262 }
263 
264 void mm_put_huge_zero_folio(struct mm_struct *mm)
265 {
266 	if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
267 		put_huge_zero_page();
268 }
269 
270 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
271 					struct shrink_control *sc)
272 {
273 	/* we can free zero page only if last reference remains */
274 	return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
275 }
276 
277 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
278 				       struct shrink_control *sc)
279 {
280 	if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
281 		struct folio *zero_folio = xchg(&huge_zero_folio, NULL);
282 		BUG_ON(zero_folio == NULL);
283 		WRITE_ONCE(huge_zero_pfn, ~0UL);
284 		folio_put(zero_folio);
285 		return HPAGE_PMD_NR;
286 	}
287 
288 	return 0;
289 }
290 
291 static struct shrinker *huge_zero_page_shrinker;
292 
293 #ifdef CONFIG_SYSFS
294 static ssize_t enabled_show(struct kobject *kobj,
295 			    struct kobj_attribute *attr, char *buf)
296 {
297 	const char *output;
298 
299 	if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
300 		output = "[always] madvise never";
301 	else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
302 			  &transparent_hugepage_flags))
303 		output = "always [madvise] never";
304 	else
305 		output = "always madvise [never]";
306 
307 	return sysfs_emit(buf, "%s\n", output);
308 }
309 
310 static ssize_t enabled_store(struct kobject *kobj,
311 			     struct kobj_attribute *attr,
312 			     const char *buf, size_t count)
313 {
314 	ssize_t ret = count;
315 
316 	if (sysfs_streq(buf, "always")) {
317 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
318 		set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
319 	} else if (sysfs_streq(buf, "madvise")) {
320 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
321 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
322 	} else if (sysfs_streq(buf, "never")) {
323 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
324 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
325 	} else
326 		ret = -EINVAL;
327 
328 	if (ret > 0) {
329 		int err = start_stop_khugepaged();
330 		if (err)
331 			ret = err;
332 	}
333 	return ret;
334 }
335 
336 static struct kobj_attribute enabled_attr = __ATTR_RW(enabled);
337 
338 ssize_t single_hugepage_flag_show(struct kobject *kobj,
339 				  struct kobj_attribute *attr, char *buf,
340 				  enum transparent_hugepage_flag flag)
341 {
342 	return sysfs_emit(buf, "%d\n",
343 			  !!test_bit(flag, &transparent_hugepage_flags));
344 }
345 
346 ssize_t single_hugepage_flag_store(struct kobject *kobj,
347 				 struct kobj_attribute *attr,
348 				 const char *buf, size_t count,
349 				 enum transparent_hugepage_flag flag)
350 {
351 	unsigned long value;
352 	int ret;
353 
354 	ret = kstrtoul(buf, 10, &value);
355 	if (ret < 0)
356 		return ret;
357 	if (value > 1)
358 		return -EINVAL;
359 
360 	if (value)
361 		set_bit(flag, &transparent_hugepage_flags);
362 	else
363 		clear_bit(flag, &transparent_hugepage_flags);
364 
365 	return count;
366 }
367 
368 static ssize_t defrag_show(struct kobject *kobj,
369 			   struct kobj_attribute *attr, char *buf)
370 {
371 	const char *output;
372 
373 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
374 		     &transparent_hugepage_flags))
375 		output = "[always] defer defer+madvise madvise never";
376 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
377 			  &transparent_hugepage_flags))
378 		output = "always [defer] defer+madvise madvise never";
379 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,
380 			  &transparent_hugepage_flags))
381 		output = "always defer [defer+madvise] madvise never";
382 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,
383 			  &transparent_hugepage_flags))
384 		output = "always defer defer+madvise [madvise] never";
385 	else
386 		output = "always defer defer+madvise madvise [never]";
387 
388 	return sysfs_emit(buf, "%s\n", output);
389 }
390 
391 static ssize_t defrag_store(struct kobject *kobj,
392 			    struct kobj_attribute *attr,
393 			    const char *buf, size_t count)
394 {
395 	if (sysfs_streq(buf, "always")) {
396 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
397 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
398 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
399 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
400 	} else if (sysfs_streq(buf, "defer+madvise")) {
401 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
402 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
403 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
404 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
405 	} else if (sysfs_streq(buf, "defer")) {
406 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
407 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
408 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
409 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
410 	} else if (sysfs_streq(buf, "madvise")) {
411 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
412 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
413 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
414 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
415 	} else if (sysfs_streq(buf, "never")) {
416 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
417 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
418 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
419 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
420 	} else
421 		return -EINVAL;
422 
423 	return count;
424 }
425 static struct kobj_attribute defrag_attr = __ATTR_RW(defrag);
426 
427 static ssize_t use_zero_page_show(struct kobject *kobj,
428 				  struct kobj_attribute *attr, char *buf)
429 {
430 	return single_hugepage_flag_show(kobj, attr, buf,
431 					 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
432 }
433 static ssize_t use_zero_page_store(struct kobject *kobj,
434 		struct kobj_attribute *attr, const char *buf, size_t count)
435 {
436 	return single_hugepage_flag_store(kobj, attr, buf, count,
437 				 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
438 }
439 static struct kobj_attribute use_zero_page_attr = __ATTR_RW(use_zero_page);
440 
441 static ssize_t hpage_pmd_size_show(struct kobject *kobj,
442 				   struct kobj_attribute *attr, char *buf)
443 {
444 	return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE);
445 }
446 static struct kobj_attribute hpage_pmd_size_attr =
447 	__ATTR_RO(hpage_pmd_size);
448 
449 static ssize_t split_underused_thp_show(struct kobject *kobj,
450 			    struct kobj_attribute *attr, char *buf)
451 {
452 	return sysfs_emit(buf, "%d\n", split_underused_thp);
453 }
454 
455 static ssize_t split_underused_thp_store(struct kobject *kobj,
456 			     struct kobj_attribute *attr,
457 			     const char *buf, size_t count)
458 {
459 	int err = kstrtobool(buf, &split_underused_thp);
460 
461 	if (err < 0)
462 		return err;
463 
464 	return count;
465 }
466 
467 static struct kobj_attribute split_underused_thp_attr = __ATTR(
468 	shrink_underused, 0644, split_underused_thp_show, split_underused_thp_store);
469 
470 static struct attribute *hugepage_attr[] = {
471 	&enabled_attr.attr,
472 	&defrag_attr.attr,
473 	&use_zero_page_attr.attr,
474 	&hpage_pmd_size_attr.attr,
475 #ifdef CONFIG_SHMEM
476 	&shmem_enabled_attr.attr,
477 #endif
478 	&split_underused_thp_attr.attr,
479 	NULL,
480 };
481 
482 static const struct attribute_group hugepage_attr_group = {
483 	.attrs = hugepage_attr,
484 };
485 
486 static void hugepage_exit_sysfs(struct kobject *hugepage_kobj);
487 static void thpsize_release(struct kobject *kobj);
488 static DEFINE_SPINLOCK(huge_anon_orders_lock);
489 static LIST_HEAD(thpsize_list);
490 
491 static ssize_t anon_enabled_show(struct kobject *kobj,
492 				 struct kobj_attribute *attr, char *buf)
493 {
494 	int order = to_thpsize(kobj)->order;
495 	const char *output;
496 
497 	if (test_bit(order, &huge_anon_orders_always))
498 		output = "[always] inherit madvise never";
499 	else if (test_bit(order, &huge_anon_orders_inherit))
500 		output = "always [inherit] madvise never";
501 	else if (test_bit(order, &huge_anon_orders_madvise))
502 		output = "always inherit [madvise] never";
503 	else
504 		output = "always inherit madvise [never]";
505 
506 	return sysfs_emit(buf, "%s\n", output);
507 }
508 
509 static ssize_t anon_enabled_store(struct kobject *kobj,
510 				  struct kobj_attribute *attr,
511 				  const char *buf, size_t count)
512 {
513 	int order = to_thpsize(kobj)->order;
514 	ssize_t ret = count;
515 
516 	if (sysfs_streq(buf, "always")) {
517 		spin_lock(&huge_anon_orders_lock);
518 		clear_bit(order, &huge_anon_orders_inherit);
519 		clear_bit(order, &huge_anon_orders_madvise);
520 		set_bit(order, &huge_anon_orders_always);
521 		spin_unlock(&huge_anon_orders_lock);
522 	} else if (sysfs_streq(buf, "inherit")) {
523 		spin_lock(&huge_anon_orders_lock);
524 		clear_bit(order, &huge_anon_orders_always);
525 		clear_bit(order, &huge_anon_orders_madvise);
526 		set_bit(order, &huge_anon_orders_inherit);
527 		spin_unlock(&huge_anon_orders_lock);
528 	} else if (sysfs_streq(buf, "madvise")) {
529 		spin_lock(&huge_anon_orders_lock);
530 		clear_bit(order, &huge_anon_orders_always);
531 		clear_bit(order, &huge_anon_orders_inherit);
532 		set_bit(order, &huge_anon_orders_madvise);
533 		spin_unlock(&huge_anon_orders_lock);
534 	} else if (sysfs_streq(buf, "never")) {
535 		spin_lock(&huge_anon_orders_lock);
536 		clear_bit(order, &huge_anon_orders_always);
537 		clear_bit(order, &huge_anon_orders_inherit);
538 		clear_bit(order, &huge_anon_orders_madvise);
539 		spin_unlock(&huge_anon_orders_lock);
540 	} else
541 		ret = -EINVAL;
542 
543 	if (ret > 0) {
544 		int err;
545 
546 		err = start_stop_khugepaged();
547 		if (err)
548 			ret = err;
549 	}
550 	return ret;
551 }
552 
553 static struct kobj_attribute anon_enabled_attr =
554 	__ATTR(enabled, 0644, anon_enabled_show, anon_enabled_store);
555 
556 static struct attribute *anon_ctrl_attrs[] = {
557 	&anon_enabled_attr.attr,
558 	NULL,
559 };
560 
561 static const struct attribute_group anon_ctrl_attr_grp = {
562 	.attrs = anon_ctrl_attrs,
563 };
564 
565 static struct attribute *file_ctrl_attrs[] = {
566 #ifdef CONFIG_SHMEM
567 	&thpsize_shmem_enabled_attr.attr,
568 #endif
569 	NULL,
570 };
571 
572 static const struct attribute_group file_ctrl_attr_grp = {
573 	.attrs = file_ctrl_attrs,
574 };
575 
576 static struct attribute *any_ctrl_attrs[] = {
577 	NULL,
578 };
579 
580 static const struct attribute_group any_ctrl_attr_grp = {
581 	.attrs = any_ctrl_attrs,
582 };
583 
584 static const struct kobj_type thpsize_ktype = {
585 	.release = &thpsize_release,
586 	.sysfs_ops = &kobj_sysfs_ops,
587 };
588 
589 DEFINE_PER_CPU(struct mthp_stat, mthp_stats) = {{{0}}};
590 
591 static unsigned long sum_mthp_stat(int order, enum mthp_stat_item item)
592 {
593 	unsigned long sum = 0;
594 	int cpu;
595 
596 	for_each_possible_cpu(cpu) {
597 		struct mthp_stat *this = &per_cpu(mthp_stats, cpu);
598 
599 		sum += this->stats[order][item];
600 	}
601 
602 	return sum;
603 }
604 
605 #define DEFINE_MTHP_STAT_ATTR(_name, _index)				\
606 static ssize_t _name##_show(struct kobject *kobj,			\
607 			struct kobj_attribute *attr, char *buf)		\
608 {									\
609 	int order = to_thpsize(kobj)->order;				\
610 									\
611 	return sysfs_emit(buf, "%lu\n", sum_mthp_stat(order, _index));	\
612 }									\
613 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
614 
615 DEFINE_MTHP_STAT_ATTR(anon_fault_alloc, MTHP_STAT_ANON_FAULT_ALLOC);
616 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback, MTHP_STAT_ANON_FAULT_FALLBACK);
617 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback_charge, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
618 DEFINE_MTHP_STAT_ATTR(swpout, MTHP_STAT_SWPOUT);
619 DEFINE_MTHP_STAT_ATTR(swpout_fallback, MTHP_STAT_SWPOUT_FALLBACK);
620 #ifdef CONFIG_SHMEM
621 DEFINE_MTHP_STAT_ATTR(shmem_alloc, MTHP_STAT_SHMEM_ALLOC);
622 DEFINE_MTHP_STAT_ATTR(shmem_fallback, MTHP_STAT_SHMEM_FALLBACK);
623 DEFINE_MTHP_STAT_ATTR(shmem_fallback_charge, MTHP_STAT_SHMEM_FALLBACK_CHARGE);
624 #endif
625 DEFINE_MTHP_STAT_ATTR(split, MTHP_STAT_SPLIT);
626 DEFINE_MTHP_STAT_ATTR(split_failed, MTHP_STAT_SPLIT_FAILED);
627 DEFINE_MTHP_STAT_ATTR(split_deferred, MTHP_STAT_SPLIT_DEFERRED);
628 DEFINE_MTHP_STAT_ATTR(nr_anon, MTHP_STAT_NR_ANON);
629 DEFINE_MTHP_STAT_ATTR(nr_anon_partially_mapped, MTHP_STAT_NR_ANON_PARTIALLY_MAPPED);
630 
631 static struct attribute *anon_stats_attrs[] = {
632 	&anon_fault_alloc_attr.attr,
633 	&anon_fault_fallback_attr.attr,
634 	&anon_fault_fallback_charge_attr.attr,
635 #ifndef CONFIG_SHMEM
636 	&swpout_attr.attr,
637 	&swpout_fallback_attr.attr,
638 #endif
639 	&split_deferred_attr.attr,
640 	&nr_anon_attr.attr,
641 	&nr_anon_partially_mapped_attr.attr,
642 	NULL,
643 };
644 
645 static struct attribute_group anon_stats_attr_grp = {
646 	.name = "stats",
647 	.attrs = anon_stats_attrs,
648 };
649 
650 static struct attribute *file_stats_attrs[] = {
651 #ifdef CONFIG_SHMEM
652 	&shmem_alloc_attr.attr,
653 	&shmem_fallback_attr.attr,
654 	&shmem_fallback_charge_attr.attr,
655 #endif
656 	NULL,
657 };
658 
659 static struct attribute_group file_stats_attr_grp = {
660 	.name = "stats",
661 	.attrs = file_stats_attrs,
662 };
663 
664 static struct attribute *any_stats_attrs[] = {
665 #ifdef CONFIG_SHMEM
666 	&swpout_attr.attr,
667 	&swpout_fallback_attr.attr,
668 #endif
669 	&split_attr.attr,
670 	&split_failed_attr.attr,
671 	NULL,
672 };
673 
674 static struct attribute_group any_stats_attr_grp = {
675 	.name = "stats",
676 	.attrs = any_stats_attrs,
677 };
678 
679 static int sysfs_add_group(struct kobject *kobj,
680 			   const struct attribute_group *grp)
681 {
682 	int ret = -ENOENT;
683 
684 	/*
685 	 * If the group is named, try to merge first, assuming the subdirectory
686 	 * was already created. This avoids the warning emitted by
687 	 * sysfs_create_group() if the directory already exists.
688 	 */
689 	if (grp->name)
690 		ret = sysfs_merge_group(kobj, grp);
691 	if (ret)
692 		ret = sysfs_create_group(kobj, grp);
693 
694 	return ret;
695 }
696 
697 static struct thpsize *thpsize_create(int order, struct kobject *parent)
698 {
699 	unsigned long size = (PAGE_SIZE << order) / SZ_1K;
700 	struct thpsize *thpsize;
701 	int ret = -ENOMEM;
702 
703 	thpsize = kzalloc(sizeof(*thpsize), GFP_KERNEL);
704 	if (!thpsize)
705 		goto err;
706 
707 	thpsize->order = order;
708 
709 	ret = kobject_init_and_add(&thpsize->kobj, &thpsize_ktype, parent,
710 				   "hugepages-%lukB", size);
711 	if (ret) {
712 		kfree(thpsize);
713 		goto err;
714 	}
715 
716 
717 	ret = sysfs_add_group(&thpsize->kobj, &any_ctrl_attr_grp);
718 	if (ret)
719 		goto err_put;
720 
721 	ret = sysfs_add_group(&thpsize->kobj, &any_stats_attr_grp);
722 	if (ret)
723 		goto err_put;
724 
725 	if (BIT(order) & THP_ORDERS_ALL_ANON) {
726 		ret = sysfs_add_group(&thpsize->kobj, &anon_ctrl_attr_grp);
727 		if (ret)
728 			goto err_put;
729 
730 		ret = sysfs_add_group(&thpsize->kobj, &anon_stats_attr_grp);
731 		if (ret)
732 			goto err_put;
733 	}
734 
735 	if (BIT(order) & THP_ORDERS_ALL_FILE_DEFAULT) {
736 		ret = sysfs_add_group(&thpsize->kobj, &file_ctrl_attr_grp);
737 		if (ret)
738 			goto err_put;
739 
740 		ret = sysfs_add_group(&thpsize->kobj, &file_stats_attr_grp);
741 		if (ret)
742 			goto err_put;
743 	}
744 
745 	return thpsize;
746 err_put:
747 	kobject_put(&thpsize->kobj);
748 err:
749 	return ERR_PTR(ret);
750 }
751 
752 static void thpsize_release(struct kobject *kobj)
753 {
754 	kfree(to_thpsize(kobj));
755 }
756 
757 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
758 {
759 	int err;
760 	struct thpsize *thpsize;
761 	unsigned long orders;
762 	int order;
763 
764 	/*
765 	 * Default to setting PMD-sized THP to inherit the global setting and
766 	 * disable all other sizes. powerpc's PMD_ORDER isn't a compile-time
767 	 * constant so we have to do this here.
768 	 */
769 	if (!anon_orders_configured)
770 		huge_anon_orders_inherit = BIT(PMD_ORDER);
771 
772 	*hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
773 	if (unlikely(!*hugepage_kobj)) {
774 		pr_err("failed to create transparent hugepage kobject\n");
775 		return -ENOMEM;
776 	}
777 
778 	err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
779 	if (err) {
780 		pr_err("failed to register transparent hugepage group\n");
781 		goto delete_obj;
782 	}
783 
784 	err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
785 	if (err) {
786 		pr_err("failed to register transparent hugepage group\n");
787 		goto remove_hp_group;
788 	}
789 
790 	orders = THP_ORDERS_ALL_ANON | THP_ORDERS_ALL_FILE_DEFAULT;
791 	order = highest_order(orders);
792 	while (orders) {
793 		thpsize = thpsize_create(order, *hugepage_kobj);
794 		if (IS_ERR(thpsize)) {
795 			pr_err("failed to create thpsize for order %d\n", order);
796 			err = PTR_ERR(thpsize);
797 			goto remove_all;
798 		}
799 		list_add(&thpsize->node, &thpsize_list);
800 		order = next_order(&orders, order);
801 	}
802 
803 	return 0;
804 
805 remove_all:
806 	hugepage_exit_sysfs(*hugepage_kobj);
807 	return err;
808 remove_hp_group:
809 	sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
810 delete_obj:
811 	kobject_put(*hugepage_kobj);
812 	return err;
813 }
814 
815 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
816 {
817 	struct thpsize *thpsize, *tmp;
818 
819 	list_for_each_entry_safe(thpsize, tmp, &thpsize_list, node) {
820 		list_del(&thpsize->node);
821 		kobject_put(&thpsize->kobj);
822 	}
823 
824 	sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
825 	sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
826 	kobject_put(hugepage_kobj);
827 }
828 #else
829 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
830 {
831 	return 0;
832 }
833 
834 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
835 {
836 }
837 #endif /* CONFIG_SYSFS */
838 
839 static int __init thp_shrinker_init(void)
840 {
841 	huge_zero_page_shrinker = shrinker_alloc(0, "thp-zero");
842 	if (!huge_zero_page_shrinker)
843 		return -ENOMEM;
844 
845 	deferred_split_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE |
846 						 SHRINKER_MEMCG_AWARE |
847 						 SHRINKER_NONSLAB,
848 						 "thp-deferred_split");
849 	if (!deferred_split_shrinker) {
850 		shrinker_free(huge_zero_page_shrinker);
851 		return -ENOMEM;
852 	}
853 
854 	huge_zero_page_shrinker->count_objects = shrink_huge_zero_page_count;
855 	huge_zero_page_shrinker->scan_objects = shrink_huge_zero_page_scan;
856 	shrinker_register(huge_zero_page_shrinker);
857 
858 	deferred_split_shrinker->count_objects = deferred_split_count;
859 	deferred_split_shrinker->scan_objects = deferred_split_scan;
860 	shrinker_register(deferred_split_shrinker);
861 
862 	return 0;
863 }
864 
865 static void __init thp_shrinker_exit(void)
866 {
867 	shrinker_free(huge_zero_page_shrinker);
868 	shrinker_free(deferred_split_shrinker);
869 }
870 
871 static int __init hugepage_init(void)
872 {
873 	int err;
874 	struct kobject *hugepage_kobj;
875 
876 	if (!has_transparent_hugepage()) {
877 		transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED;
878 		return -EINVAL;
879 	}
880 
881 	/*
882 	 * hugepages can't be allocated by the buddy allocator
883 	 */
884 	MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_PAGE_ORDER);
885 
886 	err = hugepage_init_sysfs(&hugepage_kobj);
887 	if (err)
888 		goto err_sysfs;
889 
890 	err = khugepaged_init();
891 	if (err)
892 		goto err_slab;
893 
894 	err = thp_shrinker_init();
895 	if (err)
896 		goto err_shrinker;
897 
898 	/*
899 	 * By default disable transparent hugepages on smaller systems,
900 	 * where the extra memory used could hurt more than TLB overhead
901 	 * is likely to save.  The admin can still enable it through /sys.
902 	 */
903 	if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) {
904 		transparent_hugepage_flags = 0;
905 		return 0;
906 	}
907 
908 	err = start_stop_khugepaged();
909 	if (err)
910 		goto err_khugepaged;
911 
912 	return 0;
913 err_khugepaged:
914 	thp_shrinker_exit();
915 err_shrinker:
916 	khugepaged_destroy();
917 err_slab:
918 	hugepage_exit_sysfs(hugepage_kobj);
919 err_sysfs:
920 	return err;
921 }
922 subsys_initcall(hugepage_init);
923 
924 static int __init setup_transparent_hugepage(char *str)
925 {
926 	int ret = 0;
927 	if (!str)
928 		goto out;
929 	if (!strcmp(str, "always")) {
930 		set_bit(TRANSPARENT_HUGEPAGE_FLAG,
931 			&transparent_hugepage_flags);
932 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
933 			  &transparent_hugepage_flags);
934 		ret = 1;
935 	} else if (!strcmp(str, "madvise")) {
936 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
937 			  &transparent_hugepage_flags);
938 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
939 			&transparent_hugepage_flags);
940 		ret = 1;
941 	} else if (!strcmp(str, "never")) {
942 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
943 			  &transparent_hugepage_flags);
944 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
945 			  &transparent_hugepage_flags);
946 		ret = 1;
947 	}
948 out:
949 	if (!ret)
950 		pr_warn("transparent_hugepage= cannot parse, ignored\n");
951 	return ret;
952 }
953 __setup("transparent_hugepage=", setup_transparent_hugepage);
954 
955 static inline int get_order_from_str(const char *size_str)
956 {
957 	unsigned long size;
958 	char *endptr;
959 	int order;
960 
961 	size = memparse(size_str, &endptr);
962 
963 	if (!is_power_of_2(size))
964 		goto err;
965 	order = get_order(size);
966 	if (BIT(order) & ~THP_ORDERS_ALL_ANON)
967 		goto err;
968 
969 	return order;
970 err:
971 	pr_err("invalid size %s in thp_anon boot parameter\n", size_str);
972 	return -EINVAL;
973 }
974 
975 static char str_dup[PAGE_SIZE] __initdata;
976 static int __init setup_thp_anon(char *str)
977 {
978 	char *token, *range, *policy, *subtoken;
979 	unsigned long always, inherit, madvise;
980 	char *start_size, *end_size;
981 	int start, end, nr;
982 	char *p;
983 
984 	if (!str || strlen(str) + 1 > PAGE_SIZE)
985 		goto err;
986 	strcpy(str_dup, str);
987 
988 	always = huge_anon_orders_always;
989 	madvise = huge_anon_orders_madvise;
990 	inherit = huge_anon_orders_inherit;
991 	p = str_dup;
992 	while ((token = strsep(&p, ";")) != NULL) {
993 		range = strsep(&token, ":");
994 		policy = token;
995 
996 		if (!policy)
997 			goto err;
998 
999 		while ((subtoken = strsep(&range, ",")) != NULL) {
1000 			if (strchr(subtoken, '-')) {
1001 				start_size = strsep(&subtoken, "-");
1002 				end_size = subtoken;
1003 
1004 				start = get_order_from_str(start_size);
1005 				end = get_order_from_str(end_size);
1006 			} else {
1007 				start = end = get_order_from_str(subtoken);
1008 			}
1009 
1010 			if (start < 0 || end < 0 || start > end)
1011 				goto err;
1012 
1013 			nr = end - start + 1;
1014 			if (!strcmp(policy, "always")) {
1015 				bitmap_set(&always, start, nr);
1016 				bitmap_clear(&inherit, start, nr);
1017 				bitmap_clear(&madvise, start, nr);
1018 			} else if (!strcmp(policy, "madvise")) {
1019 				bitmap_set(&madvise, start, nr);
1020 				bitmap_clear(&inherit, start, nr);
1021 				bitmap_clear(&always, start, nr);
1022 			} else if (!strcmp(policy, "inherit")) {
1023 				bitmap_set(&inherit, start, nr);
1024 				bitmap_clear(&madvise, start, nr);
1025 				bitmap_clear(&always, start, nr);
1026 			} else if (!strcmp(policy, "never")) {
1027 				bitmap_clear(&inherit, start, nr);
1028 				bitmap_clear(&madvise, start, nr);
1029 				bitmap_clear(&always, start, nr);
1030 			} else {
1031 				pr_err("invalid policy %s in thp_anon boot parameter\n", policy);
1032 				goto err;
1033 			}
1034 		}
1035 	}
1036 
1037 	huge_anon_orders_always = always;
1038 	huge_anon_orders_madvise = madvise;
1039 	huge_anon_orders_inherit = inherit;
1040 	anon_orders_configured = true;
1041 	return 1;
1042 
1043 err:
1044 	pr_warn("thp_anon=%s: error parsing string, ignoring setting\n", str);
1045 	return 0;
1046 }
1047 __setup("thp_anon=", setup_thp_anon);
1048 
1049 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
1050 {
1051 	if (likely(vma->vm_flags & VM_WRITE))
1052 		pmd = pmd_mkwrite(pmd, vma);
1053 	return pmd;
1054 }
1055 
1056 #ifdef CONFIG_MEMCG
1057 static inline
1058 struct deferred_split *get_deferred_split_queue(struct folio *folio)
1059 {
1060 	struct mem_cgroup *memcg = folio_memcg(folio);
1061 	struct pglist_data *pgdat = NODE_DATA(folio_nid(folio));
1062 
1063 	if (memcg)
1064 		return &memcg->deferred_split_queue;
1065 	else
1066 		return &pgdat->deferred_split_queue;
1067 }
1068 #else
1069 static inline
1070 struct deferred_split *get_deferred_split_queue(struct folio *folio)
1071 {
1072 	struct pglist_data *pgdat = NODE_DATA(folio_nid(folio));
1073 
1074 	return &pgdat->deferred_split_queue;
1075 }
1076 #endif
1077 
1078 static inline bool is_transparent_hugepage(const struct folio *folio)
1079 {
1080 	if (!folio_test_large(folio))
1081 		return false;
1082 
1083 	return is_huge_zero_folio(folio) ||
1084 		folio_test_large_rmappable(folio);
1085 }
1086 
1087 static unsigned long __thp_get_unmapped_area(struct file *filp,
1088 		unsigned long addr, unsigned long len,
1089 		loff_t off, unsigned long flags, unsigned long size,
1090 		vm_flags_t vm_flags)
1091 {
1092 	loff_t off_end = off + len;
1093 	loff_t off_align = round_up(off, size);
1094 	unsigned long len_pad, ret, off_sub;
1095 
1096 	if (!IS_ENABLED(CONFIG_64BIT) || in_compat_syscall())
1097 		return 0;
1098 
1099 	if (off_end <= off_align || (off_end - off_align) < size)
1100 		return 0;
1101 
1102 	len_pad = len + size;
1103 	if (len_pad < len || (off + len_pad) < off)
1104 		return 0;
1105 
1106 	ret = mm_get_unmapped_area_vmflags(current->mm, filp, addr, len_pad,
1107 					   off >> PAGE_SHIFT, flags, vm_flags);
1108 
1109 	/*
1110 	 * The failure might be due to length padding. The caller will retry
1111 	 * without the padding.
1112 	 */
1113 	if (IS_ERR_VALUE(ret))
1114 		return 0;
1115 
1116 	/*
1117 	 * Do not try to align to THP boundary if allocation at the address
1118 	 * hint succeeds.
1119 	 */
1120 	if (ret == addr)
1121 		return addr;
1122 
1123 	off_sub = (off - ret) & (size - 1);
1124 
1125 	if (test_bit(MMF_TOPDOWN, &current->mm->flags) && !off_sub)
1126 		return ret + size;
1127 
1128 	ret += off_sub;
1129 	return ret;
1130 }
1131 
1132 unsigned long thp_get_unmapped_area_vmflags(struct file *filp, unsigned long addr,
1133 		unsigned long len, unsigned long pgoff, unsigned long flags,
1134 		vm_flags_t vm_flags)
1135 {
1136 	unsigned long ret;
1137 	loff_t off = (loff_t)pgoff << PAGE_SHIFT;
1138 
1139 	ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE, vm_flags);
1140 	if (ret)
1141 		return ret;
1142 
1143 	return mm_get_unmapped_area_vmflags(current->mm, filp, addr, len, pgoff, flags,
1144 					    vm_flags);
1145 }
1146 
1147 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
1148 		unsigned long len, unsigned long pgoff, unsigned long flags)
1149 {
1150 	return thp_get_unmapped_area_vmflags(filp, addr, len, pgoff, flags, 0);
1151 }
1152 EXPORT_SYMBOL_GPL(thp_get_unmapped_area);
1153 
1154 static struct folio *vma_alloc_anon_folio_pmd(struct vm_area_struct *vma,
1155 		unsigned long addr)
1156 {
1157 	gfp_t gfp = vma_thp_gfp_mask(vma);
1158 	const int order = HPAGE_PMD_ORDER;
1159 	struct folio *folio;
1160 
1161 	folio = vma_alloc_folio(gfp, order, vma, addr & HPAGE_PMD_MASK);
1162 
1163 	if (unlikely(!folio)) {
1164 		count_vm_event(THP_FAULT_FALLBACK);
1165 		count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK);
1166 		return NULL;
1167 	}
1168 
1169 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
1170 	if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
1171 		folio_put(folio);
1172 		count_vm_event(THP_FAULT_FALLBACK);
1173 		count_vm_event(THP_FAULT_FALLBACK_CHARGE);
1174 		count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK);
1175 		count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
1176 		return NULL;
1177 	}
1178 	folio_throttle_swaprate(folio, gfp);
1179 
1180        /*
1181 	* When a folio is not zeroed during allocation (__GFP_ZERO not used),
1182 	* folio_zero_user() is used to make sure that the page corresponding
1183 	* to the faulting address will be hot in the cache after zeroing.
1184 	*/
1185 	if (!alloc_zeroed())
1186 		folio_zero_user(folio, addr);
1187 	/*
1188 	 * The memory barrier inside __folio_mark_uptodate makes sure that
1189 	 * folio_zero_user writes become visible before the set_pmd_at()
1190 	 * write.
1191 	 */
1192 	__folio_mark_uptodate(folio);
1193 	return folio;
1194 }
1195 
1196 static void map_anon_folio_pmd(struct folio *folio, pmd_t *pmd,
1197 		struct vm_area_struct *vma, unsigned long haddr)
1198 {
1199 	pmd_t entry;
1200 
1201 	entry = mk_huge_pmd(&folio->page, vma->vm_page_prot);
1202 	entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1203 	folio_add_new_anon_rmap(folio, vma, haddr, RMAP_EXCLUSIVE);
1204 	folio_add_lru_vma(folio, vma);
1205 	set_pmd_at(vma->vm_mm, haddr, pmd, entry);
1206 	update_mmu_cache_pmd(vma, haddr, pmd);
1207 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1208 	count_vm_event(THP_FAULT_ALLOC);
1209 	count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_ALLOC);
1210 	count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
1211 }
1212 
1213 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf)
1214 {
1215 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1216 	struct vm_area_struct *vma = vmf->vma;
1217 	struct folio *folio;
1218 	pgtable_t pgtable;
1219 	vm_fault_t ret = 0;
1220 
1221 	folio = vma_alloc_anon_folio_pmd(vma, vmf->address);
1222 	if (unlikely(!folio))
1223 		return VM_FAULT_FALLBACK;
1224 
1225 	pgtable = pte_alloc_one(vma->vm_mm);
1226 	if (unlikely(!pgtable)) {
1227 		ret = VM_FAULT_OOM;
1228 		goto release;
1229 	}
1230 
1231 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1232 	if (unlikely(!pmd_none(*vmf->pmd))) {
1233 		goto unlock_release;
1234 	} else {
1235 		ret = check_stable_address_space(vma->vm_mm);
1236 		if (ret)
1237 			goto unlock_release;
1238 
1239 		/* Deliver the page fault to userland */
1240 		if (userfaultfd_missing(vma)) {
1241 			spin_unlock(vmf->ptl);
1242 			folio_put(folio);
1243 			pte_free(vma->vm_mm, pgtable);
1244 			ret = handle_userfault(vmf, VM_UFFD_MISSING);
1245 			VM_BUG_ON(ret & VM_FAULT_FALLBACK);
1246 			return ret;
1247 		}
1248 		pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
1249 		map_anon_folio_pmd(folio, vmf->pmd, vma, haddr);
1250 		mm_inc_nr_ptes(vma->vm_mm);
1251 		deferred_split_folio(folio, false);
1252 		spin_unlock(vmf->ptl);
1253 	}
1254 
1255 	return 0;
1256 unlock_release:
1257 	spin_unlock(vmf->ptl);
1258 release:
1259 	if (pgtable)
1260 		pte_free(vma->vm_mm, pgtable);
1261 	folio_put(folio);
1262 	return ret;
1263 
1264 }
1265 
1266 /*
1267  * always: directly stall for all thp allocations
1268  * defer: wake kswapd and fail if not immediately available
1269  * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise
1270  *		  fail if not immediately available
1271  * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately
1272  *	    available
1273  * never: never stall for any thp allocation
1274  */
1275 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)
1276 {
1277 	const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE);
1278 
1279 	/* Always do synchronous compaction */
1280 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
1281 		return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);
1282 
1283 	/* Kick kcompactd and fail quickly */
1284 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
1285 		return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;
1286 
1287 	/* Synchronous compaction if madvised, otherwise kick kcompactd */
1288 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags))
1289 		return GFP_TRANSHUGE_LIGHT |
1290 			(vma_madvised ? __GFP_DIRECT_RECLAIM :
1291 					__GFP_KSWAPD_RECLAIM);
1292 
1293 	/* Only do synchronous compaction if madvised */
1294 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
1295 		return GFP_TRANSHUGE_LIGHT |
1296 		       (vma_madvised ? __GFP_DIRECT_RECLAIM : 0);
1297 
1298 	return GFP_TRANSHUGE_LIGHT;
1299 }
1300 
1301 /* Caller must hold page table lock. */
1302 static void set_huge_zero_folio(pgtable_t pgtable, struct mm_struct *mm,
1303 		struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
1304 		struct folio *zero_folio)
1305 {
1306 	pmd_t entry;
1307 	if (!pmd_none(*pmd))
1308 		return;
1309 	entry = mk_pmd(&zero_folio->page, vma->vm_page_prot);
1310 	entry = pmd_mkhuge(entry);
1311 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1312 	set_pmd_at(mm, haddr, pmd, entry);
1313 	mm_inc_nr_ptes(mm);
1314 }
1315 
1316 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf)
1317 {
1318 	struct vm_area_struct *vma = vmf->vma;
1319 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1320 	vm_fault_t ret;
1321 
1322 	if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER))
1323 		return VM_FAULT_FALLBACK;
1324 	ret = vmf_anon_prepare(vmf);
1325 	if (ret)
1326 		return ret;
1327 	khugepaged_enter_vma(vma, vma->vm_flags);
1328 
1329 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
1330 			!mm_forbids_zeropage(vma->vm_mm) &&
1331 			transparent_hugepage_use_zero_page()) {
1332 		pgtable_t pgtable;
1333 		struct folio *zero_folio;
1334 		vm_fault_t ret;
1335 
1336 		pgtable = pte_alloc_one(vma->vm_mm);
1337 		if (unlikely(!pgtable))
1338 			return VM_FAULT_OOM;
1339 		zero_folio = mm_get_huge_zero_folio(vma->vm_mm);
1340 		if (unlikely(!zero_folio)) {
1341 			pte_free(vma->vm_mm, pgtable);
1342 			count_vm_event(THP_FAULT_FALLBACK);
1343 			return VM_FAULT_FALLBACK;
1344 		}
1345 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1346 		ret = 0;
1347 		if (pmd_none(*vmf->pmd)) {
1348 			ret = check_stable_address_space(vma->vm_mm);
1349 			if (ret) {
1350 				spin_unlock(vmf->ptl);
1351 				pte_free(vma->vm_mm, pgtable);
1352 			} else if (userfaultfd_missing(vma)) {
1353 				spin_unlock(vmf->ptl);
1354 				pte_free(vma->vm_mm, pgtable);
1355 				ret = handle_userfault(vmf, VM_UFFD_MISSING);
1356 				VM_BUG_ON(ret & VM_FAULT_FALLBACK);
1357 			} else {
1358 				set_huge_zero_folio(pgtable, vma->vm_mm, vma,
1359 						   haddr, vmf->pmd, zero_folio);
1360 				update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1361 				spin_unlock(vmf->ptl);
1362 			}
1363 		} else {
1364 			spin_unlock(vmf->ptl);
1365 			pte_free(vma->vm_mm, pgtable);
1366 		}
1367 		return ret;
1368 	}
1369 
1370 	return __do_huge_pmd_anonymous_page(vmf);
1371 }
1372 
1373 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
1374 		pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write,
1375 		pgtable_t pgtable)
1376 {
1377 	struct mm_struct *mm = vma->vm_mm;
1378 	pmd_t entry;
1379 	spinlock_t *ptl;
1380 
1381 	ptl = pmd_lock(mm, pmd);
1382 	if (!pmd_none(*pmd)) {
1383 		if (write) {
1384 			if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) {
1385 				WARN_ON_ONCE(!is_huge_zero_pmd(*pmd));
1386 				goto out_unlock;
1387 			}
1388 			entry = pmd_mkyoung(*pmd);
1389 			entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1390 			if (pmdp_set_access_flags(vma, addr, pmd, entry, 1))
1391 				update_mmu_cache_pmd(vma, addr, pmd);
1392 		}
1393 
1394 		goto out_unlock;
1395 	}
1396 
1397 	entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
1398 	if (pfn_t_devmap(pfn))
1399 		entry = pmd_mkdevmap(entry);
1400 	else
1401 		entry = pmd_mkspecial(entry);
1402 	if (write) {
1403 		entry = pmd_mkyoung(pmd_mkdirty(entry));
1404 		entry = maybe_pmd_mkwrite(entry, vma);
1405 	}
1406 
1407 	if (pgtable) {
1408 		pgtable_trans_huge_deposit(mm, pmd, pgtable);
1409 		mm_inc_nr_ptes(mm);
1410 		pgtable = NULL;
1411 	}
1412 
1413 	set_pmd_at(mm, addr, pmd, entry);
1414 	update_mmu_cache_pmd(vma, addr, pmd);
1415 
1416 out_unlock:
1417 	spin_unlock(ptl);
1418 	if (pgtable)
1419 		pte_free(mm, pgtable);
1420 }
1421 
1422 /**
1423  * vmf_insert_pfn_pmd - insert a pmd size pfn
1424  * @vmf: Structure describing the fault
1425  * @pfn: pfn to insert
1426  * @write: whether it's a write fault
1427  *
1428  * Insert a pmd size pfn. See vmf_insert_pfn() for additional info.
1429  *
1430  * Return: vm_fault_t value.
1431  */
1432 vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, pfn_t pfn, bool write)
1433 {
1434 	unsigned long addr = vmf->address & PMD_MASK;
1435 	struct vm_area_struct *vma = vmf->vma;
1436 	pgprot_t pgprot = vma->vm_page_prot;
1437 	pgtable_t pgtable = NULL;
1438 
1439 	/*
1440 	 * If we had pmd_special, we could avoid all these restrictions,
1441 	 * but we need to be consistent with PTEs and architectures that
1442 	 * can't support a 'special' bit.
1443 	 */
1444 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
1445 			!pfn_t_devmap(pfn));
1446 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1447 						(VM_PFNMAP|VM_MIXEDMAP));
1448 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1449 
1450 	if (addr < vma->vm_start || addr >= vma->vm_end)
1451 		return VM_FAULT_SIGBUS;
1452 
1453 	if (arch_needs_pgtable_deposit()) {
1454 		pgtable = pte_alloc_one(vma->vm_mm);
1455 		if (!pgtable)
1456 			return VM_FAULT_OOM;
1457 	}
1458 
1459 	track_pfn_insert(vma, &pgprot, pfn);
1460 
1461 	insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable);
1462 	return VM_FAULT_NOPAGE;
1463 }
1464 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd);
1465 
1466 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1467 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)
1468 {
1469 	if (likely(vma->vm_flags & VM_WRITE))
1470 		pud = pud_mkwrite(pud);
1471 	return pud;
1472 }
1473 
1474 static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr,
1475 		pud_t *pud, pfn_t pfn, bool write)
1476 {
1477 	struct mm_struct *mm = vma->vm_mm;
1478 	pgprot_t prot = vma->vm_page_prot;
1479 	pud_t entry;
1480 	spinlock_t *ptl;
1481 
1482 	ptl = pud_lock(mm, pud);
1483 	if (!pud_none(*pud)) {
1484 		if (write) {
1485 			if (WARN_ON_ONCE(pud_pfn(*pud) != pfn_t_to_pfn(pfn)))
1486 				goto out_unlock;
1487 			entry = pud_mkyoung(*pud);
1488 			entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma);
1489 			if (pudp_set_access_flags(vma, addr, pud, entry, 1))
1490 				update_mmu_cache_pud(vma, addr, pud);
1491 		}
1492 		goto out_unlock;
1493 	}
1494 
1495 	entry = pud_mkhuge(pfn_t_pud(pfn, prot));
1496 	if (pfn_t_devmap(pfn))
1497 		entry = pud_mkdevmap(entry);
1498 	else
1499 		entry = pud_mkspecial(entry);
1500 	if (write) {
1501 		entry = pud_mkyoung(pud_mkdirty(entry));
1502 		entry = maybe_pud_mkwrite(entry, vma);
1503 	}
1504 	set_pud_at(mm, addr, pud, entry);
1505 	update_mmu_cache_pud(vma, addr, pud);
1506 
1507 out_unlock:
1508 	spin_unlock(ptl);
1509 }
1510 
1511 /**
1512  * vmf_insert_pfn_pud - insert a pud size pfn
1513  * @vmf: Structure describing the fault
1514  * @pfn: pfn to insert
1515  * @write: whether it's a write fault
1516  *
1517  * Insert a pud size pfn. See vmf_insert_pfn() for additional info.
1518  *
1519  * Return: vm_fault_t value.
1520  */
1521 vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, pfn_t pfn, bool write)
1522 {
1523 	unsigned long addr = vmf->address & PUD_MASK;
1524 	struct vm_area_struct *vma = vmf->vma;
1525 	pgprot_t pgprot = vma->vm_page_prot;
1526 
1527 	/*
1528 	 * If we had pud_special, we could avoid all these restrictions,
1529 	 * but we need to be consistent with PTEs and architectures that
1530 	 * can't support a 'special' bit.
1531 	 */
1532 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
1533 			!pfn_t_devmap(pfn));
1534 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1535 						(VM_PFNMAP|VM_MIXEDMAP));
1536 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1537 
1538 	if (addr < vma->vm_start || addr >= vma->vm_end)
1539 		return VM_FAULT_SIGBUS;
1540 
1541 	track_pfn_insert(vma, &pgprot, pfn);
1542 
1543 	insert_pfn_pud(vma, addr, vmf->pud, pfn, write);
1544 	return VM_FAULT_NOPAGE;
1545 }
1546 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud);
1547 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1548 
1549 void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
1550 	       pmd_t *pmd, bool write)
1551 {
1552 	pmd_t _pmd;
1553 
1554 	_pmd = pmd_mkyoung(*pmd);
1555 	if (write)
1556 		_pmd = pmd_mkdirty(_pmd);
1557 	if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1558 				  pmd, _pmd, write))
1559 		update_mmu_cache_pmd(vma, addr, pmd);
1560 }
1561 
1562 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
1563 		pmd_t *pmd, int flags, struct dev_pagemap **pgmap)
1564 {
1565 	unsigned long pfn = pmd_pfn(*pmd);
1566 	struct mm_struct *mm = vma->vm_mm;
1567 	struct page *page;
1568 	int ret;
1569 
1570 	assert_spin_locked(pmd_lockptr(mm, pmd));
1571 
1572 	if (flags & FOLL_WRITE && !pmd_write(*pmd))
1573 		return NULL;
1574 
1575 	if (pmd_present(*pmd) && pmd_devmap(*pmd))
1576 		/* pass */;
1577 	else
1578 		return NULL;
1579 
1580 	if (flags & FOLL_TOUCH)
1581 		touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
1582 
1583 	/*
1584 	 * device mapped pages can only be returned if the
1585 	 * caller will manage the page reference count.
1586 	 */
1587 	if (!(flags & (FOLL_GET | FOLL_PIN)))
1588 		return ERR_PTR(-EEXIST);
1589 
1590 	pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1591 	*pgmap = get_dev_pagemap(pfn, *pgmap);
1592 	if (!*pgmap)
1593 		return ERR_PTR(-EFAULT);
1594 	page = pfn_to_page(pfn);
1595 	ret = try_grab_folio(page_folio(page), 1, flags);
1596 	if (ret)
1597 		page = ERR_PTR(ret);
1598 
1599 	return page;
1600 }
1601 
1602 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1603 		  pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1604 		  struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1605 {
1606 	spinlock_t *dst_ptl, *src_ptl;
1607 	struct page *src_page;
1608 	struct folio *src_folio;
1609 	pmd_t pmd;
1610 	pgtable_t pgtable = NULL;
1611 	int ret = -ENOMEM;
1612 
1613 	pmd = pmdp_get_lockless(src_pmd);
1614 	if (unlikely(pmd_present(pmd) && pmd_special(pmd))) {
1615 		dst_ptl = pmd_lock(dst_mm, dst_pmd);
1616 		src_ptl = pmd_lockptr(src_mm, src_pmd);
1617 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1618 		/*
1619 		 * No need to recheck the pmd, it can't change with write
1620 		 * mmap lock held here.
1621 		 *
1622 		 * Meanwhile, making sure it's not a CoW VMA with writable
1623 		 * mapping, otherwise it means either the anon page wrongly
1624 		 * applied special bit, or we made the PRIVATE mapping be
1625 		 * able to wrongly write to the backend MMIO.
1626 		 */
1627 		VM_WARN_ON_ONCE(is_cow_mapping(src_vma->vm_flags) && pmd_write(pmd));
1628 		goto set_pmd;
1629 	}
1630 
1631 	/* Skip if can be re-fill on fault */
1632 	if (!vma_is_anonymous(dst_vma))
1633 		return 0;
1634 
1635 	pgtable = pte_alloc_one(dst_mm);
1636 	if (unlikely(!pgtable))
1637 		goto out;
1638 
1639 	dst_ptl = pmd_lock(dst_mm, dst_pmd);
1640 	src_ptl = pmd_lockptr(src_mm, src_pmd);
1641 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1642 
1643 	ret = -EAGAIN;
1644 	pmd = *src_pmd;
1645 
1646 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1647 	if (unlikely(is_swap_pmd(pmd))) {
1648 		swp_entry_t entry = pmd_to_swp_entry(pmd);
1649 
1650 		VM_BUG_ON(!is_pmd_migration_entry(pmd));
1651 		if (!is_readable_migration_entry(entry)) {
1652 			entry = make_readable_migration_entry(
1653 							swp_offset(entry));
1654 			pmd = swp_entry_to_pmd(entry);
1655 			if (pmd_swp_soft_dirty(*src_pmd))
1656 				pmd = pmd_swp_mksoft_dirty(pmd);
1657 			if (pmd_swp_uffd_wp(*src_pmd))
1658 				pmd = pmd_swp_mkuffd_wp(pmd);
1659 			set_pmd_at(src_mm, addr, src_pmd, pmd);
1660 		}
1661 		add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1662 		mm_inc_nr_ptes(dst_mm);
1663 		pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1664 		if (!userfaultfd_wp(dst_vma))
1665 			pmd = pmd_swp_clear_uffd_wp(pmd);
1666 		set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1667 		ret = 0;
1668 		goto out_unlock;
1669 	}
1670 #endif
1671 
1672 	if (unlikely(!pmd_trans_huge(pmd))) {
1673 		pte_free(dst_mm, pgtable);
1674 		goto out_unlock;
1675 	}
1676 	/*
1677 	 * When page table lock is held, the huge zero pmd should not be
1678 	 * under splitting since we don't split the page itself, only pmd to
1679 	 * a page table.
1680 	 */
1681 	if (is_huge_zero_pmd(pmd)) {
1682 		/*
1683 		 * mm_get_huge_zero_folio() will never allocate a new
1684 		 * folio here, since we already have a zero page to
1685 		 * copy. It just takes a reference.
1686 		 */
1687 		mm_get_huge_zero_folio(dst_mm);
1688 		goto out_zero_page;
1689 	}
1690 
1691 	src_page = pmd_page(pmd);
1692 	VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1693 	src_folio = page_folio(src_page);
1694 
1695 	folio_get(src_folio);
1696 	if (unlikely(folio_try_dup_anon_rmap_pmd(src_folio, src_page, src_vma))) {
1697 		/* Page maybe pinned: split and retry the fault on PTEs. */
1698 		folio_put(src_folio);
1699 		pte_free(dst_mm, pgtable);
1700 		spin_unlock(src_ptl);
1701 		spin_unlock(dst_ptl);
1702 		__split_huge_pmd(src_vma, src_pmd, addr, false, NULL);
1703 		return -EAGAIN;
1704 	}
1705 	add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1706 out_zero_page:
1707 	mm_inc_nr_ptes(dst_mm);
1708 	pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1709 	pmdp_set_wrprotect(src_mm, addr, src_pmd);
1710 	if (!userfaultfd_wp(dst_vma))
1711 		pmd = pmd_clear_uffd_wp(pmd);
1712 	pmd = pmd_wrprotect(pmd);
1713 set_pmd:
1714 	pmd = pmd_mkold(pmd);
1715 	set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1716 
1717 	ret = 0;
1718 out_unlock:
1719 	spin_unlock(src_ptl);
1720 	spin_unlock(dst_ptl);
1721 out:
1722 	return ret;
1723 }
1724 
1725 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1726 void touch_pud(struct vm_area_struct *vma, unsigned long addr,
1727 	       pud_t *pud, bool write)
1728 {
1729 	pud_t _pud;
1730 
1731 	_pud = pud_mkyoung(*pud);
1732 	if (write)
1733 		_pud = pud_mkdirty(_pud);
1734 	if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK,
1735 				  pud, _pud, write))
1736 		update_mmu_cache_pud(vma, addr, pud);
1737 }
1738 
1739 int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1740 		  pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1741 		  struct vm_area_struct *vma)
1742 {
1743 	spinlock_t *dst_ptl, *src_ptl;
1744 	pud_t pud;
1745 	int ret;
1746 
1747 	dst_ptl = pud_lock(dst_mm, dst_pud);
1748 	src_ptl = pud_lockptr(src_mm, src_pud);
1749 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1750 
1751 	ret = -EAGAIN;
1752 	pud = *src_pud;
1753 	if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud)))
1754 		goto out_unlock;
1755 
1756 	/*
1757 	 * TODO: once we support anonymous pages, use
1758 	 * folio_try_dup_anon_rmap_*() and split if duplicating fails.
1759 	 */
1760 	if (is_cow_mapping(vma->vm_flags) && pud_write(pud)) {
1761 		pudp_set_wrprotect(src_mm, addr, src_pud);
1762 		pud = pud_wrprotect(pud);
1763 	}
1764 	pud = pud_mkold(pud);
1765 	set_pud_at(dst_mm, addr, dst_pud, pud);
1766 
1767 	ret = 0;
1768 out_unlock:
1769 	spin_unlock(src_ptl);
1770 	spin_unlock(dst_ptl);
1771 	return ret;
1772 }
1773 
1774 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)
1775 {
1776 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1777 
1778 	vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud);
1779 	if (unlikely(!pud_same(*vmf->pud, orig_pud)))
1780 		goto unlock;
1781 
1782 	touch_pud(vmf->vma, vmf->address, vmf->pud, write);
1783 unlock:
1784 	spin_unlock(vmf->ptl);
1785 }
1786 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1787 
1788 void huge_pmd_set_accessed(struct vm_fault *vmf)
1789 {
1790 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1791 
1792 	vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd);
1793 	if (unlikely(!pmd_same(*vmf->pmd, vmf->orig_pmd)))
1794 		goto unlock;
1795 
1796 	touch_pmd(vmf->vma, vmf->address, vmf->pmd, write);
1797 
1798 unlock:
1799 	spin_unlock(vmf->ptl);
1800 }
1801 
1802 static vm_fault_t do_huge_zero_wp_pmd(struct vm_fault *vmf)
1803 {
1804 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1805 	struct vm_area_struct *vma = vmf->vma;
1806 	struct mmu_notifier_range range;
1807 	struct folio *folio;
1808 	vm_fault_t ret = 0;
1809 
1810 	folio = vma_alloc_anon_folio_pmd(vma, vmf->address);
1811 	if (unlikely(!folio))
1812 		return VM_FAULT_FALLBACK;
1813 
1814 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, haddr,
1815 				haddr + HPAGE_PMD_SIZE);
1816 	mmu_notifier_invalidate_range_start(&range);
1817 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1818 	if (unlikely(!pmd_same(pmdp_get(vmf->pmd), vmf->orig_pmd)))
1819 		goto release;
1820 	ret = check_stable_address_space(vma->vm_mm);
1821 	if (ret)
1822 		goto release;
1823 	(void)pmdp_huge_clear_flush(vma, haddr, vmf->pmd);
1824 	map_anon_folio_pmd(folio, vmf->pmd, vma, haddr);
1825 	goto unlock;
1826 release:
1827 	folio_put(folio);
1828 unlock:
1829 	spin_unlock(vmf->ptl);
1830 	mmu_notifier_invalidate_range_end(&range);
1831 	return ret;
1832 }
1833 
1834 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
1835 {
1836 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
1837 	struct vm_area_struct *vma = vmf->vma;
1838 	struct folio *folio;
1839 	struct page *page;
1840 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1841 	pmd_t orig_pmd = vmf->orig_pmd;
1842 
1843 	vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
1844 	VM_BUG_ON_VMA(!vma->anon_vma, vma);
1845 
1846 	if (is_huge_zero_pmd(orig_pmd)) {
1847 		vm_fault_t ret = do_huge_zero_wp_pmd(vmf);
1848 
1849 		if (!(ret & VM_FAULT_FALLBACK))
1850 			return ret;
1851 
1852 		/* Fallback to splitting PMD if THP cannot be allocated */
1853 		goto fallback;
1854 	}
1855 
1856 	spin_lock(vmf->ptl);
1857 
1858 	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1859 		spin_unlock(vmf->ptl);
1860 		return 0;
1861 	}
1862 
1863 	page = pmd_page(orig_pmd);
1864 	folio = page_folio(page);
1865 	VM_BUG_ON_PAGE(!PageHead(page), page);
1866 
1867 	/* Early check when only holding the PT lock. */
1868 	if (PageAnonExclusive(page))
1869 		goto reuse;
1870 
1871 	if (!folio_trylock(folio)) {
1872 		folio_get(folio);
1873 		spin_unlock(vmf->ptl);
1874 		folio_lock(folio);
1875 		spin_lock(vmf->ptl);
1876 		if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1877 			spin_unlock(vmf->ptl);
1878 			folio_unlock(folio);
1879 			folio_put(folio);
1880 			return 0;
1881 		}
1882 		folio_put(folio);
1883 	}
1884 
1885 	/* Recheck after temporarily dropping the PT lock. */
1886 	if (PageAnonExclusive(page)) {
1887 		folio_unlock(folio);
1888 		goto reuse;
1889 	}
1890 
1891 	/*
1892 	 * See do_wp_page(): we can only reuse the folio exclusively if
1893 	 * there are no additional references. Note that we always drain
1894 	 * the LRU cache immediately after adding a THP.
1895 	 */
1896 	if (folio_ref_count(folio) >
1897 			1 + folio_test_swapcache(folio) * folio_nr_pages(folio))
1898 		goto unlock_fallback;
1899 	if (folio_test_swapcache(folio))
1900 		folio_free_swap(folio);
1901 	if (folio_ref_count(folio) == 1) {
1902 		pmd_t entry;
1903 
1904 		folio_move_anon_rmap(folio, vma);
1905 		SetPageAnonExclusive(page);
1906 		folio_unlock(folio);
1907 reuse:
1908 		if (unlikely(unshare)) {
1909 			spin_unlock(vmf->ptl);
1910 			return 0;
1911 		}
1912 		entry = pmd_mkyoung(orig_pmd);
1913 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1914 		if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1))
1915 			update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1916 		spin_unlock(vmf->ptl);
1917 		return 0;
1918 	}
1919 
1920 unlock_fallback:
1921 	folio_unlock(folio);
1922 	spin_unlock(vmf->ptl);
1923 fallback:
1924 	__split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
1925 	return VM_FAULT_FALLBACK;
1926 }
1927 
1928 static inline bool can_change_pmd_writable(struct vm_area_struct *vma,
1929 					   unsigned long addr, pmd_t pmd)
1930 {
1931 	struct page *page;
1932 
1933 	if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE)))
1934 		return false;
1935 
1936 	/* Don't touch entries that are not even readable (NUMA hinting). */
1937 	if (pmd_protnone(pmd))
1938 		return false;
1939 
1940 	/* Do we need write faults for softdirty tracking? */
1941 	if (pmd_needs_soft_dirty_wp(vma, pmd))
1942 		return false;
1943 
1944 	/* Do we need write faults for uffd-wp tracking? */
1945 	if (userfaultfd_huge_pmd_wp(vma, pmd))
1946 		return false;
1947 
1948 	if (!(vma->vm_flags & VM_SHARED)) {
1949 		/* See can_change_pte_writable(). */
1950 		page = vm_normal_page_pmd(vma, addr, pmd);
1951 		return page && PageAnon(page) && PageAnonExclusive(page);
1952 	}
1953 
1954 	/* See can_change_pte_writable(). */
1955 	return pmd_dirty(pmd);
1956 }
1957 
1958 /* NUMA hinting page fault entry point for trans huge pmds */
1959 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf)
1960 {
1961 	struct vm_area_struct *vma = vmf->vma;
1962 	struct folio *folio;
1963 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1964 	int nid = NUMA_NO_NODE;
1965 	int target_nid, last_cpupid;
1966 	pmd_t pmd, old_pmd;
1967 	bool writable = false;
1968 	int flags = 0;
1969 
1970 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1971 	old_pmd = pmdp_get(vmf->pmd);
1972 
1973 	if (unlikely(!pmd_same(old_pmd, vmf->orig_pmd))) {
1974 		spin_unlock(vmf->ptl);
1975 		return 0;
1976 	}
1977 
1978 	pmd = pmd_modify(old_pmd, vma->vm_page_prot);
1979 
1980 	/*
1981 	 * Detect now whether the PMD could be writable; this information
1982 	 * is only valid while holding the PT lock.
1983 	 */
1984 	writable = pmd_write(pmd);
1985 	if (!writable && vma_wants_manual_pte_write_upgrade(vma) &&
1986 	    can_change_pmd_writable(vma, vmf->address, pmd))
1987 		writable = true;
1988 
1989 	folio = vm_normal_folio_pmd(vma, haddr, pmd);
1990 	if (!folio)
1991 		goto out_map;
1992 
1993 	nid = folio_nid(folio);
1994 
1995 	target_nid = numa_migrate_check(folio, vmf, haddr, &flags, writable,
1996 					&last_cpupid);
1997 	if (target_nid == NUMA_NO_NODE)
1998 		goto out_map;
1999 	if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) {
2000 		flags |= TNF_MIGRATE_FAIL;
2001 		goto out_map;
2002 	}
2003 	/* The folio is isolated and isolation code holds a folio reference. */
2004 	spin_unlock(vmf->ptl);
2005 	writable = false;
2006 
2007 	if (!migrate_misplaced_folio(folio, vma, target_nid)) {
2008 		flags |= TNF_MIGRATED;
2009 		nid = target_nid;
2010 		task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags);
2011 		return 0;
2012 	}
2013 
2014 	flags |= TNF_MIGRATE_FAIL;
2015 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
2016 	if (unlikely(!pmd_same(pmdp_get(vmf->pmd), vmf->orig_pmd))) {
2017 		spin_unlock(vmf->ptl);
2018 		return 0;
2019 	}
2020 out_map:
2021 	/* Restore the PMD */
2022 	pmd = pmd_modify(pmdp_get(vmf->pmd), vma->vm_page_prot);
2023 	pmd = pmd_mkyoung(pmd);
2024 	if (writable)
2025 		pmd = pmd_mkwrite(pmd, vma);
2026 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
2027 	update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
2028 	spin_unlock(vmf->ptl);
2029 
2030 	if (nid != NUMA_NO_NODE)
2031 		task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags);
2032 	return 0;
2033 }
2034 
2035 /*
2036  * Return true if we do MADV_FREE successfully on entire pmd page.
2037  * Otherwise, return false.
2038  */
2039 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
2040 		pmd_t *pmd, unsigned long addr, unsigned long next)
2041 {
2042 	spinlock_t *ptl;
2043 	pmd_t orig_pmd;
2044 	struct folio *folio;
2045 	struct mm_struct *mm = tlb->mm;
2046 	bool ret = false;
2047 
2048 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
2049 
2050 	ptl = pmd_trans_huge_lock(pmd, vma);
2051 	if (!ptl)
2052 		goto out_unlocked;
2053 
2054 	orig_pmd = *pmd;
2055 	if (is_huge_zero_pmd(orig_pmd))
2056 		goto out;
2057 
2058 	if (unlikely(!pmd_present(orig_pmd))) {
2059 		VM_BUG_ON(thp_migration_supported() &&
2060 				  !is_pmd_migration_entry(orig_pmd));
2061 		goto out;
2062 	}
2063 
2064 	folio = pmd_folio(orig_pmd);
2065 	/*
2066 	 * If other processes are mapping this folio, we couldn't discard
2067 	 * the folio unless they all do MADV_FREE so let's skip the folio.
2068 	 */
2069 	if (folio_likely_mapped_shared(folio))
2070 		goto out;
2071 
2072 	if (!folio_trylock(folio))
2073 		goto out;
2074 
2075 	/*
2076 	 * If user want to discard part-pages of THP, split it so MADV_FREE
2077 	 * will deactivate only them.
2078 	 */
2079 	if (next - addr != HPAGE_PMD_SIZE) {
2080 		folio_get(folio);
2081 		spin_unlock(ptl);
2082 		split_folio(folio);
2083 		folio_unlock(folio);
2084 		folio_put(folio);
2085 		goto out_unlocked;
2086 	}
2087 
2088 	if (folio_test_dirty(folio))
2089 		folio_clear_dirty(folio);
2090 	folio_unlock(folio);
2091 
2092 	if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
2093 		pmdp_invalidate(vma, addr, pmd);
2094 		orig_pmd = pmd_mkold(orig_pmd);
2095 		orig_pmd = pmd_mkclean(orig_pmd);
2096 
2097 		set_pmd_at(mm, addr, pmd, orig_pmd);
2098 		tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
2099 	}
2100 
2101 	folio_mark_lazyfree(folio);
2102 	ret = true;
2103 out:
2104 	spin_unlock(ptl);
2105 out_unlocked:
2106 	return ret;
2107 }
2108 
2109 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
2110 {
2111 	pgtable_t pgtable;
2112 
2113 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2114 	pte_free(mm, pgtable);
2115 	mm_dec_nr_ptes(mm);
2116 }
2117 
2118 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
2119 		 pmd_t *pmd, unsigned long addr)
2120 {
2121 	pmd_t orig_pmd;
2122 	spinlock_t *ptl;
2123 
2124 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
2125 
2126 	ptl = __pmd_trans_huge_lock(pmd, vma);
2127 	if (!ptl)
2128 		return 0;
2129 	/*
2130 	 * For architectures like ppc64 we look at deposited pgtable
2131 	 * when calling pmdp_huge_get_and_clear. So do the
2132 	 * pgtable_trans_huge_withdraw after finishing pmdp related
2133 	 * operations.
2134 	 */
2135 	orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
2136 						tlb->fullmm);
2137 	arch_check_zapped_pmd(vma, orig_pmd);
2138 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
2139 	if (vma_is_special_huge(vma)) {
2140 		if (arch_needs_pgtable_deposit())
2141 			zap_deposited_table(tlb->mm, pmd);
2142 		spin_unlock(ptl);
2143 	} else if (is_huge_zero_pmd(orig_pmd)) {
2144 		zap_deposited_table(tlb->mm, pmd);
2145 		spin_unlock(ptl);
2146 	} else {
2147 		struct folio *folio = NULL;
2148 		int flush_needed = 1;
2149 
2150 		if (pmd_present(orig_pmd)) {
2151 			struct page *page = pmd_page(orig_pmd);
2152 
2153 			folio = page_folio(page);
2154 			folio_remove_rmap_pmd(folio, page, vma);
2155 			WARN_ON_ONCE(folio_mapcount(folio) < 0);
2156 			VM_BUG_ON_PAGE(!PageHead(page), page);
2157 		} else if (thp_migration_supported()) {
2158 			swp_entry_t entry;
2159 
2160 			VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
2161 			entry = pmd_to_swp_entry(orig_pmd);
2162 			folio = pfn_swap_entry_folio(entry);
2163 			flush_needed = 0;
2164 		} else
2165 			WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
2166 
2167 		if (folio_test_anon(folio)) {
2168 			zap_deposited_table(tlb->mm, pmd);
2169 			add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
2170 		} else {
2171 			if (arch_needs_pgtable_deposit())
2172 				zap_deposited_table(tlb->mm, pmd);
2173 			add_mm_counter(tlb->mm, mm_counter_file(folio),
2174 				       -HPAGE_PMD_NR);
2175 		}
2176 
2177 		spin_unlock(ptl);
2178 		if (flush_needed)
2179 			tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE);
2180 	}
2181 	return 1;
2182 }
2183 
2184 #ifndef pmd_move_must_withdraw
2185 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
2186 					 spinlock_t *old_pmd_ptl,
2187 					 struct vm_area_struct *vma)
2188 {
2189 	/*
2190 	 * With split pmd lock we also need to move preallocated
2191 	 * PTE page table if new_pmd is on different PMD page table.
2192 	 *
2193 	 * We also don't deposit and withdraw tables for file pages.
2194 	 */
2195 	return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
2196 }
2197 #endif
2198 
2199 static pmd_t move_soft_dirty_pmd(pmd_t pmd)
2200 {
2201 #ifdef CONFIG_MEM_SOFT_DIRTY
2202 	if (unlikely(is_pmd_migration_entry(pmd)))
2203 		pmd = pmd_swp_mksoft_dirty(pmd);
2204 	else if (pmd_present(pmd))
2205 		pmd = pmd_mksoft_dirty(pmd);
2206 #endif
2207 	return pmd;
2208 }
2209 
2210 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
2211 		  unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
2212 {
2213 	spinlock_t *old_ptl, *new_ptl;
2214 	pmd_t pmd;
2215 	struct mm_struct *mm = vma->vm_mm;
2216 	bool force_flush = false;
2217 
2218 	/*
2219 	 * The destination pmd shouldn't be established, free_pgtables()
2220 	 * should have released it; but move_page_tables() might have already
2221 	 * inserted a page table, if racing against shmem/file collapse.
2222 	 */
2223 	if (!pmd_none(*new_pmd)) {
2224 		VM_BUG_ON(pmd_trans_huge(*new_pmd));
2225 		return false;
2226 	}
2227 
2228 	/*
2229 	 * We don't have to worry about the ordering of src and dst
2230 	 * ptlocks because exclusive mmap_lock prevents deadlock.
2231 	 */
2232 	old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
2233 	if (old_ptl) {
2234 		new_ptl = pmd_lockptr(mm, new_pmd);
2235 		if (new_ptl != old_ptl)
2236 			spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
2237 		pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
2238 		if (pmd_present(pmd))
2239 			force_flush = true;
2240 		VM_BUG_ON(!pmd_none(*new_pmd));
2241 
2242 		if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
2243 			pgtable_t pgtable;
2244 			pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
2245 			pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
2246 		}
2247 		pmd = move_soft_dirty_pmd(pmd);
2248 		set_pmd_at(mm, new_addr, new_pmd, pmd);
2249 		if (force_flush)
2250 			flush_pmd_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
2251 		if (new_ptl != old_ptl)
2252 			spin_unlock(new_ptl);
2253 		spin_unlock(old_ptl);
2254 		return true;
2255 	}
2256 	return false;
2257 }
2258 
2259 /*
2260  * Returns
2261  *  - 0 if PMD could not be locked
2262  *  - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
2263  *      or if prot_numa but THP migration is not supported
2264  *  - HPAGE_PMD_NR if protections changed and TLB flush necessary
2265  */
2266 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
2267 		    pmd_t *pmd, unsigned long addr, pgprot_t newprot,
2268 		    unsigned long cp_flags)
2269 {
2270 	struct mm_struct *mm = vma->vm_mm;
2271 	spinlock_t *ptl;
2272 	pmd_t oldpmd, entry;
2273 	bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
2274 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
2275 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
2276 	int ret = 1;
2277 
2278 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
2279 
2280 	if (prot_numa && !thp_migration_supported())
2281 		return 1;
2282 
2283 	ptl = __pmd_trans_huge_lock(pmd, vma);
2284 	if (!ptl)
2285 		return 0;
2286 
2287 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
2288 	if (is_swap_pmd(*pmd)) {
2289 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
2290 		struct folio *folio = pfn_swap_entry_folio(entry);
2291 		pmd_t newpmd;
2292 
2293 		VM_BUG_ON(!is_pmd_migration_entry(*pmd));
2294 		if (is_writable_migration_entry(entry)) {
2295 			/*
2296 			 * A protection check is difficult so
2297 			 * just be safe and disable write
2298 			 */
2299 			if (folio_test_anon(folio))
2300 				entry = make_readable_exclusive_migration_entry(swp_offset(entry));
2301 			else
2302 				entry = make_readable_migration_entry(swp_offset(entry));
2303 			newpmd = swp_entry_to_pmd(entry);
2304 			if (pmd_swp_soft_dirty(*pmd))
2305 				newpmd = pmd_swp_mksoft_dirty(newpmd);
2306 		} else {
2307 			newpmd = *pmd;
2308 		}
2309 
2310 		if (uffd_wp)
2311 			newpmd = pmd_swp_mkuffd_wp(newpmd);
2312 		else if (uffd_wp_resolve)
2313 			newpmd = pmd_swp_clear_uffd_wp(newpmd);
2314 		if (!pmd_same(*pmd, newpmd))
2315 			set_pmd_at(mm, addr, pmd, newpmd);
2316 		goto unlock;
2317 	}
2318 #endif
2319 
2320 	if (prot_numa) {
2321 		struct folio *folio;
2322 		bool toptier;
2323 		/*
2324 		 * Avoid trapping faults against the zero page. The read-only
2325 		 * data is likely to be read-cached on the local CPU and
2326 		 * local/remote hits to the zero page are not interesting.
2327 		 */
2328 		if (is_huge_zero_pmd(*pmd))
2329 			goto unlock;
2330 
2331 		if (pmd_protnone(*pmd))
2332 			goto unlock;
2333 
2334 		folio = pmd_folio(*pmd);
2335 		toptier = node_is_toptier(folio_nid(folio));
2336 		/*
2337 		 * Skip scanning top tier node if normal numa
2338 		 * balancing is disabled
2339 		 */
2340 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
2341 		    toptier)
2342 			goto unlock;
2343 
2344 		if (folio_use_access_time(folio))
2345 			folio_xchg_access_time(folio,
2346 					       jiffies_to_msecs(jiffies));
2347 	}
2348 	/*
2349 	 * In case prot_numa, we are under mmap_read_lock(mm). It's critical
2350 	 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
2351 	 * which is also under mmap_read_lock(mm):
2352 	 *
2353 	 *	CPU0:				CPU1:
2354 	 *				change_huge_pmd(prot_numa=1)
2355 	 *				 pmdp_huge_get_and_clear_notify()
2356 	 * madvise_dontneed()
2357 	 *  zap_pmd_range()
2358 	 *   pmd_trans_huge(*pmd) == 0 (without ptl)
2359 	 *   // skip the pmd
2360 	 *				 set_pmd_at();
2361 	 *				 // pmd is re-established
2362 	 *
2363 	 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
2364 	 * which may break userspace.
2365 	 *
2366 	 * pmdp_invalidate_ad() is required to make sure we don't miss
2367 	 * dirty/young flags set by hardware.
2368 	 */
2369 	oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
2370 
2371 	entry = pmd_modify(oldpmd, newprot);
2372 	if (uffd_wp)
2373 		entry = pmd_mkuffd_wp(entry);
2374 	else if (uffd_wp_resolve)
2375 		/*
2376 		 * Leave the write bit to be handled by PF interrupt
2377 		 * handler, then things like COW could be properly
2378 		 * handled.
2379 		 */
2380 		entry = pmd_clear_uffd_wp(entry);
2381 
2382 	/* See change_pte_range(). */
2383 	if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) && !pmd_write(entry) &&
2384 	    can_change_pmd_writable(vma, addr, entry))
2385 		entry = pmd_mkwrite(entry, vma);
2386 
2387 	ret = HPAGE_PMD_NR;
2388 	set_pmd_at(mm, addr, pmd, entry);
2389 
2390 	if (huge_pmd_needs_flush(oldpmd, entry))
2391 		tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
2392 unlock:
2393 	spin_unlock(ptl);
2394 	return ret;
2395 }
2396 
2397 /*
2398  * Returns:
2399  *
2400  * - 0: if pud leaf changed from under us
2401  * - 1: if pud can be skipped
2402  * - HPAGE_PUD_NR: if pud was successfully processed
2403  */
2404 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
2405 int change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
2406 		    pud_t *pudp, unsigned long addr, pgprot_t newprot,
2407 		    unsigned long cp_flags)
2408 {
2409 	struct mm_struct *mm = vma->vm_mm;
2410 	pud_t oldpud, entry;
2411 	spinlock_t *ptl;
2412 
2413 	tlb_change_page_size(tlb, HPAGE_PUD_SIZE);
2414 
2415 	/* NUMA balancing doesn't apply to dax */
2416 	if (cp_flags & MM_CP_PROT_NUMA)
2417 		return 1;
2418 
2419 	/*
2420 	 * Huge entries on userfault-wp only works with anonymous, while we
2421 	 * don't have anonymous PUDs yet.
2422 	 */
2423 	if (WARN_ON_ONCE(cp_flags & MM_CP_UFFD_WP_ALL))
2424 		return 1;
2425 
2426 	ptl = __pud_trans_huge_lock(pudp, vma);
2427 	if (!ptl)
2428 		return 0;
2429 
2430 	/*
2431 	 * Can't clear PUD or it can race with concurrent zapping.  See
2432 	 * change_huge_pmd().
2433 	 */
2434 	oldpud = pudp_invalidate(vma, addr, pudp);
2435 	entry = pud_modify(oldpud, newprot);
2436 	set_pud_at(mm, addr, pudp, entry);
2437 	tlb_flush_pud_range(tlb, addr, HPAGE_PUD_SIZE);
2438 
2439 	spin_unlock(ptl);
2440 	return HPAGE_PUD_NR;
2441 }
2442 #endif
2443 
2444 #ifdef CONFIG_USERFAULTFD
2445 /*
2446  * The PT lock for src_pmd and dst_vma/src_vma (for reading) are locked by
2447  * the caller, but it must return after releasing the page_table_lock.
2448  * Just move the page from src_pmd to dst_pmd if possible.
2449  * Return zero if succeeded in moving the page, -EAGAIN if it needs to be
2450  * repeated by the caller, or other errors in case of failure.
2451  */
2452 int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pmd_t dst_pmdval,
2453 			struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
2454 			unsigned long dst_addr, unsigned long src_addr)
2455 {
2456 	pmd_t _dst_pmd, src_pmdval;
2457 	struct page *src_page;
2458 	struct folio *src_folio;
2459 	struct anon_vma *src_anon_vma;
2460 	spinlock_t *src_ptl, *dst_ptl;
2461 	pgtable_t src_pgtable;
2462 	struct mmu_notifier_range range;
2463 	int err = 0;
2464 
2465 	src_pmdval = *src_pmd;
2466 	src_ptl = pmd_lockptr(mm, src_pmd);
2467 
2468 	lockdep_assert_held(src_ptl);
2469 	vma_assert_locked(src_vma);
2470 	vma_assert_locked(dst_vma);
2471 
2472 	/* Sanity checks before the operation */
2473 	if (WARN_ON_ONCE(!pmd_none(dst_pmdval)) || WARN_ON_ONCE(src_addr & ~HPAGE_PMD_MASK) ||
2474 	    WARN_ON_ONCE(dst_addr & ~HPAGE_PMD_MASK)) {
2475 		spin_unlock(src_ptl);
2476 		return -EINVAL;
2477 	}
2478 
2479 	if (!pmd_trans_huge(src_pmdval)) {
2480 		spin_unlock(src_ptl);
2481 		if (is_pmd_migration_entry(src_pmdval)) {
2482 			pmd_migration_entry_wait(mm, &src_pmdval);
2483 			return -EAGAIN;
2484 		}
2485 		return -ENOENT;
2486 	}
2487 
2488 	src_page = pmd_page(src_pmdval);
2489 
2490 	if (!is_huge_zero_pmd(src_pmdval)) {
2491 		if (unlikely(!PageAnonExclusive(src_page))) {
2492 			spin_unlock(src_ptl);
2493 			return -EBUSY;
2494 		}
2495 
2496 		src_folio = page_folio(src_page);
2497 		folio_get(src_folio);
2498 	} else
2499 		src_folio = NULL;
2500 
2501 	spin_unlock(src_ptl);
2502 
2503 	flush_cache_range(src_vma, src_addr, src_addr + HPAGE_PMD_SIZE);
2504 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, src_addr,
2505 				src_addr + HPAGE_PMD_SIZE);
2506 	mmu_notifier_invalidate_range_start(&range);
2507 
2508 	if (src_folio) {
2509 		folio_lock(src_folio);
2510 
2511 		/*
2512 		 * split_huge_page walks the anon_vma chain without the page
2513 		 * lock. Serialize against it with the anon_vma lock, the page
2514 		 * lock is not enough.
2515 		 */
2516 		src_anon_vma = folio_get_anon_vma(src_folio);
2517 		if (!src_anon_vma) {
2518 			err = -EAGAIN;
2519 			goto unlock_folio;
2520 		}
2521 		anon_vma_lock_write(src_anon_vma);
2522 	} else
2523 		src_anon_vma = NULL;
2524 
2525 	dst_ptl = pmd_lockptr(mm, dst_pmd);
2526 	double_pt_lock(src_ptl, dst_ptl);
2527 	if (unlikely(!pmd_same(*src_pmd, src_pmdval) ||
2528 		     !pmd_same(*dst_pmd, dst_pmdval))) {
2529 		err = -EAGAIN;
2530 		goto unlock_ptls;
2531 	}
2532 	if (src_folio) {
2533 		if (folio_maybe_dma_pinned(src_folio) ||
2534 		    !PageAnonExclusive(&src_folio->page)) {
2535 			err = -EBUSY;
2536 			goto unlock_ptls;
2537 		}
2538 
2539 		if (WARN_ON_ONCE(!folio_test_head(src_folio)) ||
2540 		    WARN_ON_ONCE(!folio_test_anon(src_folio))) {
2541 			err = -EBUSY;
2542 			goto unlock_ptls;
2543 		}
2544 
2545 		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
2546 		/* Folio got pinned from under us. Put it back and fail the move. */
2547 		if (folio_maybe_dma_pinned(src_folio)) {
2548 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);
2549 			err = -EBUSY;
2550 			goto unlock_ptls;
2551 		}
2552 
2553 		folio_move_anon_rmap(src_folio, dst_vma);
2554 		src_folio->index = linear_page_index(dst_vma, dst_addr);
2555 
2556 		_dst_pmd = mk_huge_pmd(&src_folio->page, dst_vma->vm_page_prot);
2557 		/* Follow mremap() behavior and treat the entry dirty after the move */
2558 		_dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma);
2559 	} else {
2560 		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
2561 		_dst_pmd = mk_huge_pmd(src_page, dst_vma->vm_page_prot);
2562 	}
2563 	set_pmd_at(mm, dst_addr, dst_pmd, _dst_pmd);
2564 
2565 	src_pgtable = pgtable_trans_huge_withdraw(mm, src_pmd);
2566 	pgtable_trans_huge_deposit(mm, dst_pmd, src_pgtable);
2567 unlock_ptls:
2568 	double_pt_unlock(src_ptl, dst_ptl);
2569 	if (src_anon_vma) {
2570 		anon_vma_unlock_write(src_anon_vma);
2571 		put_anon_vma(src_anon_vma);
2572 	}
2573 unlock_folio:
2574 	/* unblock rmap walks */
2575 	if (src_folio)
2576 		folio_unlock(src_folio);
2577 	mmu_notifier_invalidate_range_end(&range);
2578 	if (src_folio)
2579 		folio_put(src_folio);
2580 	return err;
2581 }
2582 #endif /* CONFIG_USERFAULTFD */
2583 
2584 /*
2585  * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
2586  *
2587  * Note that if it returns page table lock pointer, this routine returns without
2588  * unlocking page table lock. So callers must unlock it.
2589  */
2590 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
2591 {
2592 	spinlock_t *ptl;
2593 	ptl = pmd_lock(vma->vm_mm, pmd);
2594 	if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
2595 			pmd_devmap(*pmd)))
2596 		return ptl;
2597 	spin_unlock(ptl);
2598 	return NULL;
2599 }
2600 
2601 /*
2602  * Returns page table lock pointer if a given pud maps a thp, NULL otherwise.
2603  *
2604  * Note that if it returns page table lock pointer, this routine returns without
2605  * unlocking page table lock. So callers must unlock it.
2606  */
2607 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
2608 {
2609 	spinlock_t *ptl;
2610 
2611 	ptl = pud_lock(vma->vm_mm, pud);
2612 	if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
2613 		return ptl;
2614 	spin_unlock(ptl);
2615 	return NULL;
2616 }
2617 
2618 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
2619 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
2620 		 pud_t *pud, unsigned long addr)
2621 {
2622 	spinlock_t *ptl;
2623 	pud_t orig_pud;
2624 
2625 	ptl = __pud_trans_huge_lock(pud, vma);
2626 	if (!ptl)
2627 		return 0;
2628 
2629 	orig_pud = pudp_huge_get_and_clear_full(vma, addr, pud, tlb->fullmm);
2630 	arch_check_zapped_pud(vma, orig_pud);
2631 	tlb_remove_pud_tlb_entry(tlb, pud, addr);
2632 	if (vma_is_special_huge(vma)) {
2633 		spin_unlock(ptl);
2634 		/* No zero page support yet */
2635 	} else {
2636 		/* No support for anonymous PUD pages yet */
2637 		BUG();
2638 	}
2639 	return 1;
2640 }
2641 
2642 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
2643 		unsigned long haddr)
2644 {
2645 	VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
2646 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2647 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
2648 	VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
2649 
2650 	count_vm_event(THP_SPLIT_PUD);
2651 
2652 	pudp_huge_clear_flush(vma, haddr, pud);
2653 }
2654 
2655 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
2656 		unsigned long address)
2657 {
2658 	spinlock_t *ptl;
2659 	struct mmu_notifier_range range;
2660 
2661 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2662 				address & HPAGE_PUD_MASK,
2663 				(address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
2664 	mmu_notifier_invalidate_range_start(&range);
2665 	ptl = pud_lock(vma->vm_mm, pud);
2666 	if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
2667 		goto out;
2668 	__split_huge_pud_locked(vma, pud, range.start);
2669 
2670 out:
2671 	spin_unlock(ptl);
2672 	mmu_notifier_invalidate_range_end(&range);
2673 }
2674 #else
2675 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
2676 		unsigned long address)
2677 {
2678 }
2679 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
2680 
2681 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2682 		unsigned long haddr, pmd_t *pmd)
2683 {
2684 	struct mm_struct *mm = vma->vm_mm;
2685 	pgtable_t pgtable;
2686 	pmd_t _pmd, old_pmd;
2687 	unsigned long addr;
2688 	pte_t *pte;
2689 	int i;
2690 
2691 	/*
2692 	 * Leave pmd empty until pte is filled note that it is fine to delay
2693 	 * notification until mmu_notifier_invalidate_range_end() as we are
2694 	 * replacing a zero pmd write protected page with a zero pte write
2695 	 * protected page.
2696 	 *
2697 	 * See Documentation/mm/mmu_notifier.rst
2698 	 */
2699 	old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
2700 
2701 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2702 	pmd_populate(mm, &_pmd, pgtable);
2703 
2704 	pte = pte_offset_map(&_pmd, haddr);
2705 	VM_BUG_ON(!pte);
2706 	for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2707 		pte_t entry;
2708 
2709 		entry = pfn_pte(my_zero_pfn(addr), vma->vm_page_prot);
2710 		entry = pte_mkspecial(entry);
2711 		if (pmd_uffd_wp(old_pmd))
2712 			entry = pte_mkuffd_wp(entry);
2713 		VM_BUG_ON(!pte_none(ptep_get(pte)));
2714 		set_pte_at(mm, addr, pte, entry);
2715 		pte++;
2716 	}
2717 	pte_unmap(pte - 1);
2718 	smp_wmb(); /* make pte visible before pmd */
2719 	pmd_populate(mm, pmd, pgtable);
2720 }
2721 
2722 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
2723 		unsigned long haddr, bool freeze)
2724 {
2725 	struct mm_struct *mm = vma->vm_mm;
2726 	struct folio *folio;
2727 	struct page *page;
2728 	pgtable_t pgtable;
2729 	pmd_t old_pmd, _pmd;
2730 	bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
2731 	bool anon_exclusive = false, dirty = false;
2732 	unsigned long addr;
2733 	pte_t *pte;
2734 	int i;
2735 
2736 	VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2737 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2738 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
2739 	VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
2740 				&& !pmd_devmap(*pmd));
2741 
2742 	count_vm_event(THP_SPLIT_PMD);
2743 
2744 	if (!vma_is_anonymous(vma)) {
2745 		old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
2746 		/*
2747 		 * We are going to unmap this huge page. So
2748 		 * just go ahead and zap it
2749 		 */
2750 		if (arch_needs_pgtable_deposit())
2751 			zap_deposited_table(mm, pmd);
2752 		if (vma_is_special_huge(vma))
2753 			return;
2754 		if (unlikely(is_pmd_migration_entry(old_pmd))) {
2755 			swp_entry_t entry;
2756 
2757 			entry = pmd_to_swp_entry(old_pmd);
2758 			folio = pfn_swap_entry_folio(entry);
2759 		} else {
2760 			page = pmd_page(old_pmd);
2761 			folio = page_folio(page);
2762 			if (!folio_test_dirty(folio) && pmd_dirty(old_pmd))
2763 				folio_mark_dirty(folio);
2764 			if (!folio_test_referenced(folio) && pmd_young(old_pmd))
2765 				folio_set_referenced(folio);
2766 			folio_remove_rmap_pmd(folio, page, vma);
2767 			folio_put(folio);
2768 		}
2769 		add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
2770 		return;
2771 	}
2772 
2773 	if (is_huge_zero_pmd(*pmd)) {
2774 		/*
2775 		 * FIXME: Do we want to invalidate secondary mmu by calling
2776 		 * mmu_notifier_arch_invalidate_secondary_tlbs() see comments below
2777 		 * inside __split_huge_pmd() ?
2778 		 *
2779 		 * We are going from a zero huge page write protected to zero
2780 		 * small page also write protected so it does not seems useful
2781 		 * to invalidate secondary mmu at this time.
2782 		 */
2783 		return __split_huge_zero_page_pmd(vma, haddr, pmd);
2784 	}
2785 
2786 	pmd_migration = is_pmd_migration_entry(*pmd);
2787 	if (unlikely(pmd_migration)) {
2788 		swp_entry_t entry;
2789 
2790 		old_pmd = *pmd;
2791 		entry = pmd_to_swp_entry(old_pmd);
2792 		page = pfn_swap_entry_to_page(entry);
2793 		write = is_writable_migration_entry(entry);
2794 		if (PageAnon(page))
2795 			anon_exclusive = is_readable_exclusive_migration_entry(entry);
2796 		young = is_migration_entry_young(entry);
2797 		dirty = is_migration_entry_dirty(entry);
2798 		soft_dirty = pmd_swp_soft_dirty(old_pmd);
2799 		uffd_wp = pmd_swp_uffd_wp(old_pmd);
2800 	} else {
2801 		/*
2802 		 * Up to this point the pmd is present and huge and userland has
2803 		 * the whole access to the hugepage during the split (which
2804 		 * happens in place). If we overwrite the pmd with the not-huge
2805 		 * version pointing to the pte here (which of course we could if
2806 		 * all CPUs were bug free), userland could trigger a small page
2807 		 * size TLB miss on the small sized TLB while the hugepage TLB
2808 		 * entry is still established in the huge TLB. Some CPU doesn't
2809 		 * like that. See
2810 		 * http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2811 		 * 383 on page 105. Intel should be safe but is also warns that
2812 		 * it's only safe if the permission and cache attributes of the
2813 		 * two entries loaded in the two TLB is identical (which should
2814 		 * be the case here). But it is generally safer to never allow
2815 		 * small and huge TLB entries for the same virtual address to be
2816 		 * loaded simultaneously. So instead of doing "pmd_populate();
2817 		 * flush_pmd_tlb_range();" we first mark the current pmd
2818 		 * notpresent (atomically because here the pmd_trans_huge must
2819 		 * remain set at all times on the pmd until the split is
2820 		 * complete for this pmd), then we flush the SMP TLB and finally
2821 		 * we write the non-huge version of the pmd entry with
2822 		 * pmd_populate.
2823 		 */
2824 		old_pmd = pmdp_invalidate(vma, haddr, pmd);
2825 		page = pmd_page(old_pmd);
2826 		folio = page_folio(page);
2827 		if (pmd_dirty(old_pmd)) {
2828 			dirty = true;
2829 			folio_set_dirty(folio);
2830 		}
2831 		write = pmd_write(old_pmd);
2832 		young = pmd_young(old_pmd);
2833 		soft_dirty = pmd_soft_dirty(old_pmd);
2834 		uffd_wp = pmd_uffd_wp(old_pmd);
2835 
2836 		VM_WARN_ON_FOLIO(!folio_ref_count(folio), folio);
2837 		VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
2838 
2839 		/*
2840 		 * Without "freeze", we'll simply split the PMD, propagating the
2841 		 * PageAnonExclusive() flag for each PTE by setting it for
2842 		 * each subpage -- no need to (temporarily) clear.
2843 		 *
2844 		 * With "freeze" we want to replace mapped pages by
2845 		 * migration entries right away. This is only possible if we
2846 		 * managed to clear PageAnonExclusive() -- see
2847 		 * set_pmd_migration_entry().
2848 		 *
2849 		 * In case we cannot clear PageAnonExclusive(), split the PMD
2850 		 * only and let try_to_migrate_one() fail later.
2851 		 *
2852 		 * See folio_try_share_anon_rmap_pmd(): invalidate PMD first.
2853 		 */
2854 		anon_exclusive = PageAnonExclusive(page);
2855 		if (freeze && anon_exclusive &&
2856 		    folio_try_share_anon_rmap_pmd(folio, page))
2857 			freeze = false;
2858 		if (!freeze) {
2859 			rmap_t rmap_flags = RMAP_NONE;
2860 
2861 			folio_ref_add(folio, HPAGE_PMD_NR - 1);
2862 			if (anon_exclusive)
2863 				rmap_flags |= RMAP_EXCLUSIVE;
2864 			folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR,
2865 						 vma, haddr, rmap_flags);
2866 		}
2867 	}
2868 
2869 	/*
2870 	 * Withdraw the table only after we mark the pmd entry invalid.
2871 	 * This's critical for some architectures (Power).
2872 	 */
2873 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2874 	pmd_populate(mm, &_pmd, pgtable);
2875 
2876 	pte = pte_offset_map(&_pmd, haddr);
2877 	VM_BUG_ON(!pte);
2878 
2879 	/*
2880 	 * Note that NUMA hinting access restrictions are not transferred to
2881 	 * avoid any possibility of altering permissions across VMAs.
2882 	 */
2883 	if (freeze || pmd_migration) {
2884 		for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2885 			pte_t entry;
2886 			swp_entry_t swp_entry;
2887 
2888 			if (write)
2889 				swp_entry = make_writable_migration_entry(
2890 							page_to_pfn(page + i));
2891 			else if (anon_exclusive)
2892 				swp_entry = make_readable_exclusive_migration_entry(
2893 							page_to_pfn(page + i));
2894 			else
2895 				swp_entry = make_readable_migration_entry(
2896 							page_to_pfn(page + i));
2897 			if (young)
2898 				swp_entry = make_migration_entry_young(swp_entry);
2899 			if (dirty)
2900 				swp_entry = make_migration_entry_dirty(swp_entry);
2901 			entry = swp_entry_to_pte(swp_entry);
2902 			if (soft_dirty)
2903 				entry = pte_swp_mksoft_dirty(entry);
2904 			if (uffd_wp)
2905 				entry = pte_swp_mkuffd_wp(entry);
2906 
2907 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
2908 			set_pte_at(mm, addr, pte + i, entry);
2909 		}
2910 	} else {
2911 		pte_t entry;
2912 
2913 		entry = mk_pte(page, READ_ONCE(vma->vm_page_prot));
2914 		if (write)
2915 			entry = pte_mkwrite(entry, vma);
2916 		if (!young)
2917 			entry = pte_mkold(entry);
2918 		/* NOTE: this may set soft-dirty too on some archs */
2919 		if (dirty)
2920 			entry = pte_mkdirty(entry);
2921 		if (soft_dirty)
2922 			entry = pte_mksoft_dirty(entry);
2923 		if (uffd_wp)
2924 			entry = pte_mkuffd_wp(entry);
2925 
2926 		for (i = 0; i < HPAGE_PMD_NR; i++)
2927 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
2928 
2929 		set_ptes(mm, haddr, pte, entry, HPAGE_PMD_NR);
2930 	}
2931 	pte_unmap(pte);
2932 
2933 	if (!pmd_migration)
2934 		folio_remove_rmap_pmd(folio, page, vma);
2935 	if (freeze)
2936 		put_page(page);
2937 
2938 	smp_wmb(); /* make pte visible before pmd */
2939 	pmd_populate(mm, pmd, pgtable);
2940 }
2941 
2942 void split_huge_pmd_locked(struct vm_area_struct *vma, unsigned long address,
2943 			   pmd_t *pmd, bool freeze, struct folio *folio)
2944 {
2945 	VM_WARN_ON_ONCE(folio && !folio_test_pmd_mappable(folio));
2946 	VM_WARN_ON_ONCE(!IS_ALIGNED(address, HPAGE_PMD_SIZE));
2947 	VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
2948 	VM_BUG_ON(freeze && !folio);
2949 
2950 	/*
2951 	 * When the caller requests to set up a migration entry, we
2952 	 * require a folio to check the PMD against. Otherwise, there
2953 	 * is a risk of replacing the wrong folio.
2954 	 */
2955 	if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
2956 	    is_pmd_migration_entry(*pmd)) {
2957 		if (folio && folio != pmd_folio(*pmd))
2958 			return;
2959 		__split_huge_pmd_locked(vma, pmd, address, freeze);
2960 	}
2961 }
2962 
2963 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2964 		unsigned long address, bool freeze, struct folio *folio)
2965 {
2966 	spinlock_t *ptl;
2967 	struct mmu_notifier_range range;
2968 
2969 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2970 				address & HPAGE_PMD_MASK,
2971 				(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2972 	mmu_notifier_invalidate_range_start(&range);
2973 	ptl = pmd_lock(vma->vm_mm, pmd);
2974 	split_huge_pmd_locked(vma, range.start, pmd, freeze, folio);
2975 	spin_unlock(ptl);
2976 	mmu_notifier_invalidate_range_end(&range);
2977 }
2978 
2979 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2980 		bool freeze, struct folio *folio)
2981 {
2982 	pmd_t *pmd = mm_find_pmd(vma->vm_mm, address);
2983 
2984 	if (!pmd)
2985 		return;
2986 
2987 	__split_huge_pmd(vma, pmd, address, freeze, folio);
2988 }
2989 
2990 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2991 {
2992 	/*
2993 	 * If the new address isn't hpage aligned and it could previously
2994 	 * contain an hugepage: check if we need to split an huge pmd.
2995 	 */
2996 	if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2997 	    range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2998 			 ALIGN(address, HPAGE_PMD_SIZE)))
2999 		split_huge_pmd_address(vma, address, false, NULL);
3000 }
3001 
3002 void vma_adjust_trans_huge(struct vm_area_struct *vma,
3003 			     unsigned long start,
3004 			     unsigned long end,
3005 			     long adjust_next)
3006 {
3007 	/* Check if we need to split start first. */
3008 	split_huge_pmd_if_needed(vma, start);
3009 
3010 	/* Check if we need to split end next. */
3011 	split_huge_pmd_if_needed(vma, end);
3012 
3013 	/*
3014 	 * If we're also updating the next vma vm_start,
3015 	 * check if we need to split it.
3016 	 */
3017 	if (adjust_next > 0) {
3018 		struct vm_area_struct *next = find_vma(vma->vm_mm, vma->vm_end);
3019 		unsigned long nstart = next->vm_start;
3020 		nstart += adjust_next;
3021 		split_huge_pmd_if_needed(next, nstart);
3022 	}
3023 }
3024 
3025 static void unmap_folio(struct folio *folio)
3026 {
3027 	enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SYNC |
3028 		TTU_BATCH_FLUSH;
3029 
3030 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
3031 
3032 	if (folio_test_pmd_mappable(folio))
3033 		ttu_flags |= TTU_SPLIT_HUGE_PMD;
3034 
3035 	/*
3036 	 * Anon pages need migration entries to preserve them, but file
3037 	 * pages can simply be left unmapped, then faulted back on demand.
3038 	 * If that is ever changed (perhaps for mlock), update remap_page().
3039 	 */
3040 	if (folio_test_anon(folio))
3041 		try_to_migrate(folio, ttu_flags);
3042 	else
3043 		try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
3044 
3045 	try_to_unmap_flush();
3046 }
3047 
3048 static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
3049 					    unsigned long addr, pmd_t *pmdp,
3050 					    struct folio *folio)
3051 {
3052 	struct mm_struct *mm = vma->vm_mm;
3053 	int ref_count, map_count;
3054 	pmd_t orig_pmd = *pmdp;
3055 
3056 	if (folio_test_dirty(folio) || pmd_dirty(orig_pmd))
3057 		return false;
3058 
3059 	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
3060 
3061 	/*
3062 	 * Syncing against concurrent GUP-fast:
3063 	 * - clear PMD; barrier; read refcount
3064 	 * - inc refcount; barrier; read PMD
3065 	 */
3066 	smp_mb();
3067 
3068 	ref_count = folio_ref_count(folio);
3069 	map_count = folio_mapcount(folio);
3070 
3071 	/*
3072 	 * Order reads for folio refcount and dirty flag
3073 	 * (see comments in __remove_mapping()).
3074 	 */
3075 	smp_rmb();
3076 
3077 	/*
3078 	 * If the folio or its PMD is redirtied at this point, or if there
3079 	 * are unexpected references, we will give up to discard this folio
3080 	 * and remap it.
3081 	 *
3082 	 * The only folio refs must be one from isolation plus the rmap(s).
3083 	 */
3084 	if (folio_test_dirty(folio) || pmd_dirty(orig_pmd) ||
3085 	    ref_count != map_count + 1) {
3086 		set_pmd_at(mm, addr, pmdp, orig_pmd);
3087 		return false;
3088 	}
3089 
3090 	folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma);
3091 	zap_deposited_table(mm, pmdp);
3092 	add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR);
3093 	if (vma->vm_flags & VM_LOCKED)
3094 		mlock_drain_local();
3095 	folio_put(folio);
3096 
3097 	return true;
3098 }
3099 
3100 bool unmap_huge_pmd_locked(struct vm_area_struct *vma, unsigned long addr,
3101 			   pmd_t *pmdp, struct folio *folio)
3102 {
3103 	VM_WARN_ON_FOLIO(!folio_test_pmd_mappable(folio), folio);
3104 	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
3105 	VM_WARN_ON_ONCE(!IS_ALIGNED(addr, HPAGE_PMD_SIZE));
3106 
3107 	if (folio_test_anon(folio) && !folio_test_swapbacked(folio))
3108 		return __discard_anon_folio_pmd_locked(vma, addr, pmdp, folio);
3109 
3110 	return false;
3111 }
3112 
3113 static void remap_page(struct folio *folio, unsigned long nr, int flags)
3114 {
3115 	int i = 0;
3116 
3117 	/* If unmap_folio() uses try_to_migrate() on file, remove this check */
3118 	if (!folio_test_anon(folio))
3119 		return;
3120 	for (;;) {
3121 		remove_migration_ptes(folio, folio, RMP_LOCKED | flags);
3122 		i += folio_nr_pages(folio);
3123 		if (i >= nr)
3124 			break;
3125 		folio = folio_next(folio);
3126 	}
3127 }
3128 
3129 static void lru_add_page_tail(struct folio *folio, struct page *tail,
3130 		struct lruvec *lruvec, struct list_head *list)
3131 {
3132 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
3133 	VM_BUG_ON_FOLIO(PageLRU(tail), folio);
3134 	lockdep_assert_held(&lruvec->lru_lock);
3135 
3136 	if (list) {
3137 		/* page reclaim is reclaiming a huge page */
3138 		VM_WARN_ON(folio_test_lru(folio));
3139 		get_page(tail);
3140 		list_add_tail(&tail->lru, list);
3141 	} else {
3142 		/* head is still on lru (and we have it frozen) */
3143 		VM_WARN_ON(!folio_test_lru(folio));
3144 		if (folio_test_unevictable(folio))
3145 			tail->mlock_count = 0;
3146 		else
3147 			list_add_tail(&tail->lru, &folio->lru);
3148 		SetPageLRU(tail);
3149 	}
3150 }
3151 
3152 static void __split_huge_page_tail(struct folio *folio, int tail,
3153 		struct lruvec *lruvec, struct list_head *list,
3154 		unsigned int new_order)
3155 {
3156 	struct page *head = &folio->page;
3157 	struct page *page_tail = head + tail;
3158 	/*
3159 	 * Careful: new_folio is not a "real" folio before we cleared PageTail.
3160 	 * Don't pass it around before clear_compound_head().
3161 	 */
3162 	struct folio *new_folio = (struct folio *)page_tail;
3163 
3164 	VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
3165 
3166 	/*
3167 	 * Clone page flags before unfreezing refcount.
3168 	 *
3169 	 * After successful get_page_unless_zero() might follow flags change,
3170 	 * for example lock_page() which set PG_waiters.
3171 	 *
3172 	 * Note that for mapped sub-pages of an anonymous THP,
3173 	 * PG_anon_exclusive has been cleared in unmap_folio() and is stored in
3174 	 * the migration entry instead from where remap_page() will restore it.
3175 	 * We can still have PG_anon_exclusive set on effectively unmapped and
3176 	 * unreferenced sub-pages of an anonymous THP: we can simply drop
3177 	 * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
3178 	 */
3179 	page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
3180 	page_tail->flags |= (head->flags &
3181 			((1L << PG_referenced) |
3182 			 (1L << PG_swapbacked) |
3183 			 (1L << PG_swapcache) |
3184 			 (1L << PG_mlocked) |
3185 			 (1L << PG_uptodate) |
3186 			 (1L << PG_active) |
3187 			 (1L << PG_workingset) |
3188 			 (1L << PG_locked) |
3189 			 (1L << PG_unevictable) |
3190 #ifdef CONFIG_ARCH_USES_PG_ARCH_2
3191 			 (1L << PG_arch_2) |
3192 #endif
3193 #ifdef CONFIG_ARCH_USES_PG_ARCH_3
3194 			 (1L << PG_arch_3) |
3195 #endif
3196 			 (1L << PG_dirty) |
3197 			 LRU_GEN_MASK | LRU_REFS_MASK));
3198 
3199 	/* ->mapping in first and second tail page is replaced by other uses */
3200 	VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
3201 			page_tail);
3202 	page_tail->mapping = head->mapping;
3203 	page_tail->index = head->index + tail;
3204 
3205 	/*
3206 	 * page->private should not be set in tail pages. Fix up and warn once
3207 	 * if private is unexpectedly set.
3208 	 */
3209 	if (unlikely(page_tail->private)) {
3210 		VM_WARN_ON_ONCE_PAGE(true, page_tail);
3211 		page_tail->private = 0;
3212 	}
3213 	if (folio_test_swapcache(folio))
3214 		new_folio->swap.val = folio->swap.val + tail;
3215 
3216 	/* Page flags must be visible before we make the page non-compound. */
3217 	smp_wmb();
3218 
3219 	/*
3220 	 * Clear PageTail before unfreezing page refcount.
3221 	 *
3222 	 * After successful get_page_unless_zero() might follow put_page()
3223 	 * which needs correct compound_head().
3224 	 */
3225 	clear_compound_head(page_tail);
3226 	if (new_order) {
3227 		prep_compound_page(page_tail, new_order);
3228 		folio_set_large_rmappable(new_folio);
3229 	}
3230 
3231 	/* Finally unfreeze refcount. Additional reference from page cache. */
3232 	page_ref_unfreeze(page_tail,
3233 		1 + ((!folio_test_anon(folio) || folio_test_swapcache(folio)) ?
3234 			     folio_nr_pages(new_folio) : 0));
3235 
3236 	if (folio_test_young(folio))
3237 		folio_set_young(new_folio);
3238 	if (folio_test_idle(folio))
3239 		folio_set_idle(new_folio);
3240 
3241 	folio_xchg_last_cpupid(new_folio, folio_last_cpupid(folio));
3242 
3243 	/*
3244 	 * always add to the tail because some iterators expect new
3245 	 * pages to show after the currently processed elements - e.g.
3246 	 * migrate_pages
3247 	 */
3248 	lru_add_page_tail(folio, page_tail, lruvec, list);
3249 }
3250 
3251 static void __split_huge_page(struct page *page, struct list_head *list,
3252 		pgoff_t end, unsigned int new_order)
3253 {
3254 	struct folio *folio = page_folio(page);
3255 	struct page *head = &folio->page;
3256 	struct lruvec *lruvec;
3257 	struct address_space *swap_cache = NULL;
3258 	unsigned long offset = 0;
3259 	int i, nr_dropped = 0;
3260 	unsigned int new_nr = 1 << new_order;
3261 	int order = folio_order(folio);
3262 	unsigned int nr = 1 << order;
3263 
3264 	/* complete memcg works before add pages to LRU */
3265 	split_page_memcg(head, order, new_order);
3266 
3267 	if (folio_test_anon(folio) && folio_test_swapcache(folio)) {
3268 		offset = swap_cache_index(folio->swap);
3269 		swap_cache = swap_address_space(folio->swap);
3270 		xa_lock(&swap_cache->i_pages);
3271 	}
3272 
3273 	/* lock lru list/PageCompound, ref frozen by page_ref_freeze */
3274 	lruvec = folio_lruvec_lock(folio);
3275 
3276 	ClearPageHasHWPoisoned(head);
3277 
3278 	for (i = nr - new_nr; i >= new_nr; i -= new_nr) {
3279 		__split_huge_page_tail(folio, i, lruvec, list, new_order);
3280 		/* Some pages can be beyond EOF: drop them from page cache */
3281 		if (head[i].index >= end) {
3282 			struct folio *tail = page_folio(head + i);
3283 
3284 			if (shmem_mapping(folio->mapping))
3285 				nr_dropped++;
3286 			else if (folio_test_clear_dirty(tail))
3287 				folio_account_cleaned(tail,
3288 					inode_to_wb(folio->mapping->host));
3289 			__filemap_remove_folio(tail, NULL);
3290 			folio_put(tail);
3291 		} else if (!PageAnon(page)) {
3292 			__xa_store(&folio->mapping->i_pages, head[i].index,
3293 					head + i, 0);
3294 		} else if (swap_cache) {
3295 			__xa_store(&swap_cache->i_pages, offset + i,
3296 					head + i, 0);
3297 		}
3298 	}
3299 
3300 	if (!new_order)
3301 		ClearPageCompound(head);
3302 	else {
3303 		struct folio *new_folio = (struct folio *)head;
3304 
3305 		folio_set_order(new_folio, new_order);
3306 	}
3307 	unlock_page_lruvec(lruvec);
3308 	/* Caller disabled irqs, so they are still disabled here */
3309 
3310 	split_page_owner(head, order, new_order);
3311 	pgalloc_tag_split(folio, order, new_order);
3312 
3313 	/* See comment in __split_huge_page_tail() */
3314 	if (folio_test_anon(folio)) {
3315 		/* Additional pin to swap cache */
3316 		if (folio_test_swapcache(folio)) {
3317 			folio_ref_add(folio, 1 + new_nr);
3318 			xa_unlock(&swap_cache->i_pages);
3319 		} else {
3320 			folio_ref_inc(folio);
3321 		}
3322 	} else {
3323 		/* Additional pin to page cache */
3324 		folio_ref_add(folio, 1 + new_nr);
3325 		xa_unlock(&folio->mapping->i_pages);
3326 	}
3327 	local_irq_enable();
3328 
3329 	if (nr_dropped)
3330 		shmem_uncharge(folio->mapping->host, nr_dropped);
3331 	remap_page(folio, nr, PageAnon(head) ? RMP_USE_SHARED_ZEROPAGE : 0);
3332 
3333 	/*
3334 	 * set page to its compound_head when split to non order-0 pages, so
3335 	 * we can skip unlocking it below, since PG_locked is transferred to
3336 	 * the compound_head of the page and the caller will unlock it.
3337 	 */
3338 	if (new_order)
3339 		page = compound_head(page);
3340 
3341 	for (i = 0; i < nr; i += new_nr) {
3342 		struct page *subpage = head + i;
3343 		struct folio *new_folio = page_folio(subpage);
3344 		if (subpage == page)
3345 			continue;
3346 		folio_unlock(new_folio);
3347 
3348 		/*
3349 		 * Subpages may be freed if there wasn't any mapping
3350 		 * like if add_to_swap() is running on a lru page that
3351 		 * had its mapping zapped. And freeing these pages
3352 		 * requires taking the lru_lock so we do the put_page
3353 		 * of the tail pages after the split is complete.
3354 		 */
3355 		free_page_and_swap_cache(subpage);
3356 	}
3357 }
3358 
3359 /* Racy check whether the huge page can be split */
3360 bool can_split_folio(struct folio *folio, int caller_pins, int *pextra_pins)
3361 {
3362 	int extra_pins;
3363 
3364 	/* Additional pins from page cache */
3365 	if (folio_test_anon(folio))
3366 		extra_pins = folio_test_swapcache(folio) ?
3367 				folio_nr_pages(folio) : 0;
3368 	else
3369 		extra_pins = folio_nr_pages(folio);
3370 	if (pextra_pins)
3371 		*pextra_pins = extra_pins;
3372 	return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins -
3373 					caller_pins;
3374 }
3375 
3376 /*
3377  * This function splits a large folio into smaller folios of order @new_order.
3378  * @page can point to any page of the large folio to split. The split operation
3379  * does not change the position of @page.
3380  *
3381  * Prerequisites:
3382  *
3383  * 1) The caller must hold a reference on the @page's owning folio, also known
3384  *    as the large folio.
3385  *
3386  * 2) The large folio must be locked.
3387  *
3388  * 3) The folio must not be pinned. Any unexpected folio references, including
3389  *    GUP pins, will result in the folio not getting split; instead, the caller
3390  *    will receive an -EAGAIN.
3391  *
3392  * 4) @new_order > 1, usually. Splitting to order-1 anonymous folios is not
3393  *    supported for non-file-backed folios, because folio->_deferred_list, which
3394  *    is used by partially mapped folios, is stored in subpage 2, but an order-1
3395  *    folio only has subpages 0 and 1. File-backed order-1 folios are supported,
3396  *    since they do not use _deferred_list.
3397  *
3398  * After splitting, the caller's folio reference will be transferred to @page,
3399  * resulting in a raised refcount of @page after this call. The other pages may
3400  * be freed if they are not mapped.
3401  *
3402  * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
3403  *
3404  * Pages in @new_order will inherit the mapping, flags, and so on from the
3405  * huge page.
3406  *
3407  * Returns 0 if the huge page was split successfully.
3408  *
3409  * Returns -EAGAIN if the folio has unexpected reference (e.g., GUP) or if
3410  * the folio was concurrently removed from the page cache.
3411  *
3412  * Returns -EBUSY when trying to split the huge zeropage, if the folio is
3413  * under writeback, if fs-specific folio metadata cannot currently be
3414  * released, or if some unexpected race happened (e.g., anon VMA disappeared,
3415  * truncation).
3416  *
3417  * Callers should ensure that the order respects the address space mapping
3418  * min-order if one is set for non-anonymous folios.
3419  *
3420  * Returns -EINVAL when trying to split to an order that is incompatible
3421  * with the folio. Splitting to order 0 is compatible with all folios.
3422  */
3423 int split_huge_page_to_list_to_order(struct page *page, struct list_head *list,
3424 				     unsigned int new_order)
3425 {
3426 	struct folio *folio = page_folio(page);
3427 	struct deferred_split *ds_queue = get_deferred_split_queue(folio);
3428 	/* reset xarray order to new order after split */
3429 	XA_STATE_ORDER(xas, &folio->mapping->i_pages, folio->index, new_order);
3430 	bool is_anon = folio_test_anon(folio);
3431 	struct address_space *mapping = NULL;
3432 	struct anon_vma *anon_vma = NULL;
3433 	int order = folio_order(folio);
3434 	int extra_pins, ret;
3435 	pgoff_t end;
3436 	bool is_hzp;
3437 
3438 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3439 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
3440 
3441 	if (new_order >= folio_order(folio))
3442 		return -EINVAL;
3443 
3444 	if (is_anon) {
3445 		/* order-1 is not supported for anonymous THP. */
3446 		if (new_order == 1) {
3447 			VM_WARN_ONCE(1, "Cannot split to order-1 folio");
3448 			return -EINVAL;
3449 		}
3450 	} else if (new_order) {
3451 		/* Split shmem folio to non-zero order not supported */
3452 		if (shmem_mapping(folio->mapping)) {
3453 			VM_WARN_ONCE(1,
3454 				"Cannot split shmem folio to non-0 order");
3455 			return -EINVAL;
3456 		}
3457 		/*
3458 		 * No split if the file system does not support large folio.
3459 		 * Note that we might still have THPs in such mappings due to
3460 		 * CONFIG_READ_ONLY_THP_FOR_FS. But in that case, the mapping
3461 		 * does not actually support large folios properly.
3462 		 */
3463 		if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
3464 		    !mapping_large_folio_support(folio->mapping)) {
3465 			VM_WARN_ONCE(1,
3466 				"Cannot split file folio to non-0 order");
3467 			return -EINVAL;
3468 		}
3469 	}
3470 
3471 	/* Only swapping a whole PMD-mapped folio is supported */
3472 	if (folio_test_swapcache(folio) && new_order)
3473 		return -EINVAL;
3474 
3475 	is_hzp = is_huge_zero_folio(folio);
3476 	if (is_hzp) {
3477 		pr_warn_ratelimited("Called split_huge_page for huge zero page\n");
3478 		return -EBUSY;
3479 	}
3480 
3481 	if (folio_test_writeback(folio))
3482 		return -EBUSY;
3483 
3484 	if (is_anon) {
3485 		/*
3486 		 * The caller does not necessarily hold an mmap_lock that would
3487 		 * prevent the anon_vma disappearing so we first we take a
3488 		 * reference to it and then lock the anon_vma for write. This
3489 		 * is similar to folio_lock_anon_vma_read except the write lock
3490 		 * is taken to serialise against parallel split or collapse
3491 		 * operations.
3492 		 */
3493 		anon_vma = folio_get_anon_vma(folio);
3494 		if (!anon_vma) {
3495 			ret = -EBUSY;
3496 			goto out;
3497 		}
3498 		end = -1;
3499 		mapping = NULL;
3500 		anon_vma_lock_write(anon_vma);
3501 	} else {
3502 		unsigned int min_order;
3503 		gfp_t gfp;
3504 
3505 		mapping = folio->mapping;
3506 
3507 		/* Truncated ? */
3508 		if (!mapping) {
3509 			ret = -EBUSY;
3510 			goto out;
3511 		}
3512 
3513 		min_order = mapping_min_folio_order(folio->mapping);
3514 		if (new_order < min_order) {
3515 			VM_WARN_ONCE(1, "Cannot split mapped folio below min-order: %u",
3516 				     min_order);
3517 			ret = -EINVAL;
3518 			goto out;
3519 		}
3520 
3521 		gfp = current_gfp_context(mapping_gfp_mask(mapping) &
3522 							GFP_RECLAIM_MASK);
3523 
3524 		if (!filemap_release_folio(folio, gfp)) {
3525 			ret = -EBUSY;
3526 			goto out;
3527 		}
3528 
3529 		xas_split_alloc(&xas, folio, folio_order(folio), gfp);
3530 		if (xas_error(&xas)) {
3531 			ret = xas_error(&xas);
3532 			goto out;
3533 		}
3534 
3535 		anon_vma = NULL;
3536 		i_mmap_lock_read(mapping);
3537 
3538 		/*
3539 		 *__split_huge_page() may need to trim off pages beyond EOF:
3540 		 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
3541 		 * which cannot be nested inside the page tree lock. So note
3542 		 * end now: i_size itself may be changed at any moment, but
3543 		 * folio lock is good enough to serialize the trimming.
3544 		 */
3545 		end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3546 		if (shmem_mapping(mapping))
3547 			end = shmem_fallocend(mapping->host, end);
3548 	}
3549 
3550 	/*
3551 	 * Racy check if we can split the page, before unmap_folio() will
3552 	 * split PMDs
3553 	 */
3554 	if (!can_split_folio(folio, 1, &extra_pins)) {
3555 		ret = -EAGAIN;
3556 		goto out_unlock;
3557 	}
3558 
3559 	unmap_folio(folio);
3560 
3561 	/* block interrupt reentry in xa_lock and spinlock */
3562 	local_irq_disable();
3563 	if (mapping) {
3564 		/*
3565 		 * Check if the folio is present in page cache.
3566 		 * We assume all tail are present too, if folio is there.
3567 		 */
3568 		xas_lock(&xas);
3569 		xas_reset(&xas);
3570 		if (xas_load(&xas) != folio)
3571 			goto fail;
3572 	}
3573 
3574 	/* Prevent deferred_split_scan() touching ->_refcount */
3575 	spin_lock(&ds_queue->split_queue_lock);
3576 	if (folio_ref_freeze(folio, 1 + extra_pins)) {
3577 		if (folio_order(folio) > 1 &&
3578 		    !list_empty(&folio->_deferred_list)) {
3579 			ds_queue->split_queue_len--;
3580 			if (folio_test_partially_mapped(folio)) {
3581 				__folio_clear_partially_mapped(folio);
3582 				mod_mthp_stat(folio_order(folio),
3583 					      MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1);
3584 			}
3585 			/*
3586 			 * Reinitialize page_deferred_list after removing the
3587 			 * page from the split_queue, otherwise a subsequent
3588 			 * split will see list corruption when checking the
3589 			 * page_deferred_list.
3590 			 */
3591 			list_del_init(&folio->_deferred_list);
3592 		}
3593 		spin_unlock(&ds_queue->split_queue_lock);
3594 		if (mapping) {
3595 			int nr = folio_nr_pages(folio);
3596 
3597 			xas_split(&xas, folio, folio_order(folio));
3598 			if (folio_test_pmd_mappable(folio) &&
3599 			    new_order < HPAGE_PMD_ORDER) {
3600 				if (folio_test_swapbacked(folio)) {
3601 					__lruvec_stat_mod_folio(folio,
3602 							NR_SHMEM_THPS, -nr);
3603 				} else {
3604 					__lruvec_stat_mod_folio(folio,
3605 							NR_FILE_THPS, -nr);
3606 					filemap_nr_thps_dec(mapping);
3607 				}
3608 			}
3609 		}
3610 
3611 		if (is_anon) {
3612 			mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1);
3613 			mod_mthp_stat(new_order, MTHP_STAT_NR_ANON, 1 << (order - new_order));
3614 		}
3615 		__split_huge_page(page, list, end, new_order);
3616 		ret = 0;
3617 	} else {
3618 		spin_unlock(&ds_queue->split_queue_lock);
3619 fail:
3620 		if (mapping)
3621 			xas_unlock(&xas);
3622 		local_irq_enable();
3623 		remap_page(folio, folio_nr_pages(folio), 0);
3624 		ret = -EAGAIN;
3625 	}
3626 
3627 out_unlock:
3628 	if (anon_vma) {
3629 		anon_vma_unlock_write(anon_vma);
3630 		put_anon_vma(anon_vma);
3631 	}
3632 	if (mapping)
3633 		i_mmap_unlock_read(mapping);
3634 out:
3635 	xas_destroy(&xas);
3636 	if (order == HPAGE_PMD_ORDER)
3637 		count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
3638 	count_mthp_stat(order, !ret ? MTHP_STAT_SPLIT : MTHP_STAT_SPLIT_FAILED);
3639 	return ret;
3640 }
3641 
3642 int min_order_for_split(struct folio *folio)
3643 {
3644 	if (folio_test_anon(folio))
3645 		return 0;
3646 
3647 	if (!folio->mapping) {
3648 		if (folio_test_pmd_mappable(folio))
3649 			count_vm_event(THP_SPLIT_PAGE_FAILED);
3650 		return -EBUSY;
3651 	}
3652 
3653 	return mapping_min_folio_order(folio->mapping);
3654 }
3655 
3656 int split_folio_to_list(struct folio *folio, struct list_head *list)
3657 {
3658 	int ret = min_order_for_split(folio);
3659 
3660 	if (ret < 0)
3661 		return ret;
3662 
3663 	return split_huge_page_to_list_to_order(&folio->page, list, ret);
3664 }
3665 
3666 /*
3667  * __folio_unqueue_deferred_split() is not to be called directly:
3668  * the folio_unqueue_deferred_split() inline wrapper in mm/internal.h
3669  * limits its calls to those folios which may have a _deferred_list for
3670  * queueing THP splits, and that list is (racily observed to be) non-empty.
3671  *
3672  * It is unsafe to call folio_unqueue_deferred_split() until folio refcount is
3673  * zero: because even when split_queue_lock is held, a non-empty _deferred_list
3674  * might be in use on deferred_split_scan()'s unlocked on-stack list.
3675  *
3676  * If memory cgroups are enabled, split_queue_lock is in the mem_cgroup: it is
3677  * therefore important to unqueue deferred split before changing folio memcg.
3678  */
3679 bool __folio_unqueue_deferred_split(struct folio *folio)
3680 {
3681 	struct deferred_split *ds_queue;
3682 	unsigned long flags;
3683 	bool unqueued = false;
3684 
3685 	WARN_ON_ONCE(folio_ref_count(folio));
3686 	WARN_ON_ONCE(!mem_cgroup_disabled() && !folio_memcg(folio));
3687 
3688 	ds_queue = get_deferred_split_queue(folio);
3689 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3690 	if (!list_empty(&folio->_deferred_list)) {
3691 		ds_queue->split_queue_len--;
3692 		if (folio_test_partially_mapped(folio)) {
3693 			__folio_clear_partially_mapped(folio);
3694 			mod_mthp_stat(folio_order(folio),
3695 				      MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1);
3696 		}
3697 		list_del_init(&folio->_deferred_list);
3698 		unqueued = true;
3699 	}
3700 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3701 
3702 	return unqueued;	/* useful for debug warnings */
3703 }
3704 
3705 /* partially_mapped=false won't clear PG_partially_mapped folio flag */
3706 void deferred_split_folio(struct folio *folio, bool partially_mapped)
3707 {
3708 	struct deferred_split *ds_queue = get_deferred_split_queue(folio);
3709 #ifdef CONFIG_MEMCG
3710 	struct mem_cgroup *memcg = folio_memcg(folio);
3711 #endif
3712 	unsigned long flags;
3713 
3714 	/*
3715 	 * Order 1 folios have no space for a deferred list, but we also
3716 	 * won't waste much memory by not adding them to the deferred list.
3717 	 */
3718 	if (folio_order(folio) <= 1)
3719 		return;
3720 
3721 	if (!partially_mapped && !split_underused_thp)
3722 		return;
3723 
3724 	/*
3725 	 * Exclude swapcache: originally to avoid a corrupt deferred split
3726 	 * queue. Nowadays that is fully prevented by mem_cgroup_swapout();
3727 	 * but if page reclaim is already handling the same folio, it is
3728 	 * unnecessary to handle it again in the shrinker, so excluding
3729 	 * swapcache here may still be a useful optimization.
3730 	 */
3731 	if (folio_test_swapcache(folio))
3732 		return;
3733 
3734 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3735 	if (partially_mapped) {
3736 		if (!folio_test_partially_mapped(folio)) {
3737 			__folio_set_partially_mapped(folio);
3738 			if (folio_test_pmd_mappable(folio))
3739 				count_vm_event(THP_DEFERRED_SPLIT_PAGE);
3740 			count_mthp_stat(folio_order(folio), MTHP_STAT_SPLIT_DEFERRED);
3741 			mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, 1);
3742 
3743 		}
3744 	} else {
3745 		/* partially mapped folios cannot become non-partially mapped */
3746 		VM_WARN_ON_FOLIO(folio_test_partially_mapped(folio), folio);
3747 	}
3748 	if (list_empty(&folio->_deferred_list)) {
3749 		list_add_tail(&folio->_deferred_list, &ds_queue->split_queue);
3750 		ds_queue->split_queue_len++;
3751 #ifdef CONFIG_MEMCG
3752 		if (memcg)
3753 			set_shrinker_bit(memcg, folio_nid(folio),
3754 					 deferred_split_shrinker->id);
3755 #endif
3756 	}
3757 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3758 }
3759 
3760 static unsigned long deferred_split_count(struct shrinker *shrink,
3761 		struct shrink_control *sc)
3762 {
3763 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
3764 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
3765 
3766 #ifdef CONFIG_MEMCG
3767 	if (sc->memcg)
3768 		ds_queue = &sc->memcg->deferred_split_queue;
3769 #endif
3770 	return READ_ONCE(ds_queue->split_queue_len);
3771 }
3772 
3773 static bool thp_underused(struct folio *folio)
3774 {
3775 	int num_zero_pages = 0, num_filled_pages = 0;
3776 	void *kaddr;
3777 	int i;
3778 
3779 	if (khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
3780 		return false;
3781 
3782 	for (i = 0; i < folio_nr_pages(folio); i++) {
3783 		kaddr = kmap_local_folio(folio, i * PAGE_SIZE);
3784 		if (!memchr_inv(kaddr, 0, PAGE_SIZE)) {
3785 			num_zero_pages++;
3786 			if (num_zero_pages > khugepaged_max_ptes_none) {
3787 				kunmap_local(kaddr);
3788 				return true;
3789 			}
3790 		} else {
3791 			/*
3792 			 * Another path for early exit once the number
3793 			 * of non-zero filled pages exceeds threshold.
3794 			 */
3795 			num_filled_pages++;
3796 			if (num_filled_pages >= HPAGE_PMD_NR - khugepaged_max_ptes_none) {
3797 				kunmap_local(kaddr);
3798 				return false;
3799 			}
3800 		}
3801 		kunmap_local(kaddr);
3802 	}
3803 	return false;
3804 }
3805 
3806 static unsigned long deferred_split_scan(struct shrinker *shrink,
3807 		struct shrink_control *sc)
3808 {
3809 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
3810 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
3811 	unsigned long flags;
3812 	LIST_HEAD(list);
3813 	struct folio *folio, *next, *prev = NULL;
3814 	int split = 0, removed = 0;
3815 
3816 #ifdef CONFIG_MEMCG
3817 	if (sc->memcg)
3818 		ds_queue = &sc->memcg->deferred_split_queue;
3819 #endif
3820 
3821 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3822 	/* Take pin on all head pages to avoid freeing them under us */
3823 	list_for_each_entry_safe(folio, next, &ds_queue->split_queue,
3824 							_deferred_list) {
3825 		if (folio_try_get(folio)) {
3826 			list_move(&folio->_deferred_list, &list);
3827 		} else {
3828 			/* We lost race with folio_put() */
3829 			if (folio_test_partially_mapped(folio)) {
3830 				__folio_clear_partially_mapped(folio);
3831 				mod_mthp_stat(folio_order(folio),
3832 					      MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1);
3833 			}
3834 			list_del_init(&folio->_deferred_list);
3835 			ds_queue->split_queue_len--;
3836 		}
3837 		if (!--sc->nr_to_scan)
3838 			break;
3839 	}
3840 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3841 
3842 	list_for_each_entry_safe(folio, next, &list, _deferred_list) {
3843 		bool did_split = false;
3844 		bool underused = false;
3845 
3846 		if (!folio_test_partially_mapped(folio)) {
3847 			underused = thp_underused(folio);
3848 			if (!underused)
3849 				goto next;
3850 		}
3851 		if (!folio_trylock(folio))
3852 			goto next;
3853 		if (!split_folio(folio)) {
3854 			did_split = true;
3855 			if (underused)
3856 				count_vm_event(THP_UNDERUSED_SPLIT_PAGE);
3857 			split++;
3858 		}
3859 		folio_unlock(folio);
3860 next:
3861 		/*
3862 		 * split_folio() removes folio from list on success.
3863 		 * Only add back to the queue if folio is partially mapped.
3864 		 * If thp_underused returns false, or if split_folio fails
3865 		 * in the case it was underused, then consider it used and
3866 		 * don't add it back to split_queue.
3867 		 */
3868 		if (!did_split && !folio_test_partially_mapped(folio)) {
3869 			list_del_init(&folio->_deferred_list);
3870 			removed++;
3871 		} else {
3872 			/*
3873 			 * That unlocked list_del_init() above would be unsafe,
3874 			 * unless its folio is separated from any earlier folios
3875 			 * left on the list (which may be concurrently unqueued)
3876 			 * by one safe folio with refcount still raised.
3877 			 */
3878 			swap(folio, prev);
3879 		}
3880 		if (folio)
3881 			folio_put(folio);
3882 	}
3883 
3884 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3885 	list_splice_tail(&list, &ds_queue->split_queue);
3886 	ds_queue->split_queue_len -= removed;
3887 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3888 
3889 	if (prev)
3890 		folio_put(prev);
3891 
3892 	/*
3893 	 * Stop shrinker if we didn't split any page, but the queue is empty.
3894 	 * This can happen if pages were freed under us.
3895 	 */
3896 	if (!split && list_empty(&ds_queue->split_queue))
3897 		return SHRINK_STOP;
3898 	return split;
3899 }
3900 
3901 #ifdef CONFIG_DEBUG_FS
3902 static void split_huge_pages_all(void)
3903 {
3904 	struct zone *zone;
3905 	struct page *page;
3906 	struct folio *folio;
3907 	unsigned long pfn, max_zone_pfn;
3908 	unsigned long total = 0, split = 0;
3909 
3910 	pr_debug("Split all THPs\n");
3911 	for_each_zone(zone) {
3912 		if (!managed_zone(zone))
3913 			continue;
3914 		max_zone_pfn = zone_end_pfn(zone);
3915 		for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
3916 			int nr_pages;
3917 
3918 			page = pfn_to_online_page(pfn);
3919 			if (!page || PageTail(page))
3920 				continue;
3921 			folio = page_folio(page);
3922 			if (!folio_try_get(folio))
3923 				continue;
3924 
3925 			if (unlikely(page_folio(page) != folio))
3926 				goto next;
3927 
3928 			if (zone != folio_zone(folio))
3929 				goto next;
3930 
3931 			if (!folio_test_large(folio)
3932 				|| folio_test_hugetlb(folio)
3933 				|| !folio_test_lru(folio))
3934 				goto next;
3935 
3936 			total++;
3937 			folio_lock(folio);
3938 			nr_pages = folio_nr_pages(folio);
3939 			if (!split_folio(folio))
3940 				split++;
3941 			pfn += nr_pages - 1;
3942 			folio_unlock(folio);
3943 next:
3944 			folio_put(folio);
3945 			cond_resched();
3946 		}
3947 	}
3948 
3949 	pr_debug("%lu of %lu THP split\n", split, total);
3950 }
3951 
3952 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
3953 {
3954 	return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
3955 		    is_vm_hugetlb_page(vma);
3956 }
3957 
3958 static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
3959 				unsigned long vaddr_end, unsigned int new_order)
3960 {
3961 	int ret = 0;
3962 	struct task_struct *task;
3963 	struct mm_struct *mm;
3964 	unsigned long total = 0, split = 0;
3965 	unsigned long addr;
3966 
3967 	vaddr_start &= PAGE_MASK;
3968 	vaddr_end &= PAGE_MASK;
3969 
3970 	task = find_get_task_by_vpid(pid);
3971 	if (!task) {
3972 		ret = -ESRCH;
3973 		goto out;
3974 	}
3975 
3976 	/* Find the mm_struct */
3977 	mm = get_task_mm(task);
3978 	put_task_struct(task);
3979 
3980 	if (!mm) {
3981 		ret = -EINVAL;
3982 		goto out;
3983 	}
3984 
3985 	pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
3986 		 pid, vaddr_start, vaddr_end);
3987 
3988 	mmap_read_lock(mm);
3989 	/*
3990 	 * always increase addr by PAGE_SIZE, since we could have a PTE page
3991 	 * table filled with PTE-mapped THPs, each of which is distinct.
3992 	 */
3993 	for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
3994 		struct vm_area_struct *vma = vma_lookup(mm, addr);
3995 		struct folio_walk fw;
3996 		struct folio *folio;
3997 		struct address_space *mapping;
3998 		unsigned int target_order = new_order;
3999 
4000 		if (!vma)
4001 			break;
4002 
4003 		/* skip special VMA and hugetlb VMA */
4004 		if (vma_not_suitable_for_thp_split(vma)) {
4005 			addr = vma->vm_end;
4006 			continue;
4007 		}
4008 
4009 		folio = folio_walk_start(&fw, vma, addr, 0);
4010 		if (!folio)
4011 			continue;
4012 
4013 		if (!is_transparent_hugepage(folio))
4014 			goto next;
4015 
4016 		if (!folio_test_anon(folio)) {
4017 			mapping = folio->mapping;
4018 			target_order = max(new_order,
4019 					   mapping_min_folio_order(mapping));
4020 		}
4021 
4022 		if (target_order >= folio_order(folio))
4023 			goto next;
4024 
4025 		total++;
4026 		/*
4027 		 * For folios with private, split_huge_page_to_list_to_order()
4028 		 * will try to drop it before split and then check if the folio
4029 		 * can be split or not. So skip the check here.
4030 		 */
4031 		if (!folio_test_private(folio) &&
4032 		    !can_split_folio(folio, 0, NULL))
4033 			goto next;
4034 
4035 		if (!folio_trylock(folio))
4036 			goto next;
4037 		folio_get(folio);
4038 		folio_walk_end(&fw, vma);
4039 
4040 		if (!folio_test_anon(folio) && folio->mapping != mapping)
4041 			goto unlock;
4042 
4043 		if (!split_folio_to_order(folio, target_order))
4044 			split++;
4045 
4046 unlock:
4047 
4048 		folio_unlock(folio);
4049 		folio_put(folio);
4050 
4051 		cond_resched();
4052 		continue;
4053 next:
4054 		folio_walk_end(&fw, vma);
4055 		cond_resched();
4056 	}
4057 	mmap_read_unlock(mm);
4058 	mmput(mm);
4059 
4060 	pr_debug("%lu of %lu THP split\n", split, total);
4061 
4062 out:
4063 	return ret;
4064 }
4065 
4066 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
4067 				pgoff_t off_end, unsigned int new_order)
4068 {
4069 	struct filename *file;
4070 	struct file *candidate;
4071 	struct address_space *mapping;
4072 	int ret = -EINVAL;
4073 	pgoff_t index;
4074 	int nr_pages = 1;
4075 	unsigned long total = 0, split = 0;
4076 	unsigned int min_order;
4077 	unsigned int target_order;
4078 
4079 	file = getname_kernel(file_path);
4080 	if (IS_ERR(file))
4081 		return ret;
4082 
4083 	candidate = file_open_name(file, O_RDONLY, 0);
4084 	if (IS_ERR(candidate))
4085 		goto out;
4086 
4087 	pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
4088 		 file_path, off_start, off_end);
4089 
4090 	mapping = candidate->f_mapping;
4091 	min_order = mapping_min_folio_order(mapping);
4092 	target_order = max(new_order, min_order);
4093 
4094 	for (index = off_start; index < off_end; index += nr_pages) {
4095 		struct folio *folio = filemap_get_folio(mapping, index);
4096 
4097 		nr_pages = 1;
4098 		if (IS_ERR(folio))
4099 			continue;
4100 
4101 		if (!folio_test_large(folio))
4102 			goto next;
4103 
4104 		total++;
4105 		nr_pages = folio_nr_pages(folio);
4106 
4107 		if (target_order >= folio_order(folio))
4108 			goto next;
4109 
4110 		if (!folio_trylock(folio))
4111 			goto next;
4112 
4113 		if (folio->mapping != mapping)
4114 			goto unlock;
4115 
4116 		if (!split_folio_to_order(folio, target_order))
4117 			split++;
4118 
4119 unlock:
4120 		folio_unlock(folio);
4121 next:
4122 		folio_put(folio);
4123 		cond_resched();
4124 	}
4125 
4126 	filp_close(candidate, NULL);
4127 	ret = 0;
4128 
4129 	pr_debug("%lu of %lu file-backed THP split\n", split, total);
4130 out:
4131 	putname(file);
4132 	return ret;
4133 }
4134 
4135 #define MAX_INPUT_BUF_SZ 255
4136 
4137 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
4138 				size_t count, loff_t *ppops)
4139 {
4140 	static DEFINE_MUTEX(split_debug_mutex);
4141 	ssize_t ret;
4142 	/*
4143 	 * hold pid, start_vaddr, end_vaddr, new_order or
4144 	 * file_path, off_start, off_end, new_order
4145 	 */
4146 	char input_buf[MAX_INPUT_BUF_SZ];
4147 	int pid;
4148 	unsigned long vaddr_start, vaddr_end;
4149 	unsigned int new_order = 0;
4150 
4151 	ret = mutex_lock_interruptible(&split_debug_mutex);
4152 	if (ret)
4153 		return ret;
4154 
4155 	ret = -EFAULT;
4156 
4157 	memset(input_buf, 0, MAX_INPUT_BUF_SZ);
4158 	if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
4159 		goto out;
4160 
4161 	input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
4162 
4163 	if (input_buf[0] == '/') {
4164 		char *tok;
4165 		char *buf = input_buf;
4166 		char file_path[MAX_INPUT_BUF_SZ];
4167 		pgoff_t off_start = 0, off_end = 0;
4168 		size_t input_len = strlen(input_buf);
4169 
4170 		tok = strsep(&buf, ",");
4171 		if (tok) {
4172 			strcpy(file_path, tok);
4173 		} else {
4174 			ret = -EINVAL;
4175 			goto out;
4176 		}
4177 
4178 		ret = sscanf(buf, "0x%lx,0x%lx,%d", &off_start, &off_end, &new_order);
4179 		if (ret != 2 && ret != 3) {
4180 			ret = -EINVAL;
4181 			goto out;
4182 		}
4183 		ret = split_huge_pages_in_file(file_path, off_start, off_end, new_order);
4184 		if (!ret)
4185 			ret = input_len;
4186 
4187 		goto out;
4188 	}
4189 
4190 	ret = sscanf(input_buf, "%d,0x%lx,0x%lx,%d", &pid, &vaddr_start, &vaddr_end, &new_order);
4191 	if (ret == 1 && pid == 1) {
4192 		split_huge_pages_all();
4193 		ret = strlen(input_buf);
4194 		goto out;
4195 	} else if (ret != 3 && ret != 4) {
4196 		ret = -EINVAL;
4197 		goto out;
4198 	}
4199 
4200 	ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end, new_order);
4201 	if (!ret)
4202 		ret = strlen(input_buf);
4203 out:
4204 	mutex_unlock(&split_debug_mutex);
4205 	return ret;
4206 
4207 }
4208 
4209 static const struct file_operations split_huge_pages_fops = {
4210 	.owner	 = THIS_MODULE,
4211 	.write	 = split_huge_pages_write,
4212 };
4213 
4214 static int __init split_huge_pages_debugfs(void)
4215 {
4216 	debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
4217 			    &split_huge_pages_fops);
4218 	return 0;
4219 }
4220 late_initcall(split_huge_pages_debugfs);
4221 #endif
4222 
4223 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
4224 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
4225 		struct page *page)
4226 {
4227 	struct folio *folio = page_folio(page);
4228 	struct vm_area_struct *vma = pvmw->vma;
4229 	struct mm_struct *mm = vma->vm_mm;
4230 	unsigned long address = pvmw->address;
4231 	bool anon_exclusive;
4232 	pmd_t pmdval;
4233 	swp_entry_t entry;
4234 	pmd_t pmdswp;
4235 
4236 	if (!(pvmw->pmd && !pvmw->pte))
4237 		return 0;
4238 
4239 	flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
4240 	pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
4241 
4242 	/* See folio_try_share_anon_rmap_pmd(): invalidate PMD first. */
4243 	anon_exclusive = folio_test_anon(folio) && PageAnonExclusive(page);
4244 	if (anon_exclusive && folio_try_share_anon_rmap_pmd(folio, page)) {
4245 		set_pmd_at(mm, address, pvmw->pmd, pmdval);
4246 		return -EBUSY;
4247 	}
4248 
4249 	if (pmd_dirty(pmdval))
4250 		folio_mark_dirty(folio);
4251 	if (pmd_write(pmdval))
4252 		entry = make_writable_migration_entry(page_to_pfn(page));
4253 	else if (anon_exclusive)
4254 		entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
4255 	else
4256 		entry = make_readable_migration_entry(page_to_pfn(page));
4257 	if (pmd_young(pmdval))
4258 		entry = make_migration_entry_young(entry);
4259 	if (pmd_dirty(pmdval))
4260 		entry = make_migration_entry_dirty(entry);
4261 	pmdswp = swp_entry_to_pmd(entry);
4262 	if (pmd_soft_dirty(pmdval))
4263 		pmdswp = pmd_swp_mksoft_dirty(pmdswp);
4264 	if (pmd_uffd_wp(pmdval))
4265 		pmdswp = pmd_swp_mkuffd_wp(pmdswp);
4266 	set_pmd_at(mm, address, pvmw->pmd, pmdswp);
4267 	folio_remove_rmap_pmd(folio, page, vma);
4268 	folio_put(folio);
4269 	trace_set_migration_pmd(address, pmd_val(pmdswp));
4270 
4271 	return 0;
4272 }
4273 
4274 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
4275 {
4276 	struct folio *folio = page_folio(new);
4277 	struct vm_area_struct *vma = pvmw->vma;
4278 	struct mm_struct *mm = vma->vm_mm;
4279 	unsigned long address = pvmw->address;
4280 	unsigned long haddr = address & HPAGE_PMD_MASK;
4281 	pmd_t pmde;
4282 	swp_entry_t entry;
4283 
4284 	if (!(pvmw->pmd && !pvmw->pte))
4285 		return;
4286 
4287 	entry = pmd_to_swp_entry(*pvmw->pmd);
4288 	folio_get(folio);
4289 	pmde = mk_huge_pmd(new, READ_ONCE(vma->vm_page_prot));
4290 	if (pmd_swp_soft_dirty(*pvmw->pmd))
4291 		pmde = pmd_mksoft_dirty(pmde);
4292 	if (is_writable_migration_entry(entry))
4293 		pmde = pmd_mkwrite(pmde, vma);
4294 	if (pmd_swp_uffd_wp(*pvmw->pmd))
4295 		pmde = pmd_mkuffd_wp(pmde);
4296 	if (!is_migration_entry_young(entry))
4297 		pmde = pmd_mkold(pmde);
4298 	/* NOTE: this may contain setting soft-dirty on some archs */
4299 	if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
4300 		pmde = pmd_mkdirty(pmde);
4301 
4302 	if (folio_test_anon(folio)) {
4303 		rmap_t rmap_flags = RMAP_NONE;
4304 
4305 		if (!is_readable_migration_entry(entry))
4306 			rmap_flags |= RMAP_EXCLUSIVE;
4307 
4308 		folio_add_anon_rmap_pmd(folio, new, vma, haddr, rmap_flags);
4309 	} else {
4310 		folio_add_file_rmap_pmd(folio, new, vma);
4311 	}
4312 	VM_BUG_ON(pmd_write(pmde) && folio_test_anon(folio) && !PageAnonExclusive(new));
4313 	set_pmd_at(mm, haddr, pvmw->pmd, pmde);
4314 
4315 	/* No need to invalidate - it was non-present before */
4316 	update_mmu_cache_pmd(vma, address, pvmw->pmd);
4317 	trace_remove_migration_pmd(address, pmd_val(pmde));
4318 }
4319 #endif
4320