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