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