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