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