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