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