xref: /linux/mm/huge_memory.c (revision 656fe3ee455e8d8dfa1c18292c508da26b29a39c)
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/coredump.h>
12 #include <linux/sched/numa_balancing.h>
13 #include <linux/highmem.h>
14 #include <linux/hugetlb.h>
15 #include <linux/mmu_notifier.h>
16 #include <linux/rmap.h>
17 #include <linux/swap.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/pfn_t.h>
27 #include <linux/mman.h>
28 #include <linux/memremap.h>
29 #include <linux/pagemap.h>
30 #include <linux/debugfs.h>
31 #include <linux/migrate.h>
32 #include <linux/hashtable.h>
33 #include <linux/userfaultfd_k.h>
34 #include <linux/page_idle.h>
35 #include <linux/shmem_fs.h>
36 #include <linux/oom.h>
37 #include <linux/numa.h>
38 #include <linux/page_owner.h>
39 #include <linux/sched/sysctl.h>
40 #include <linux/memory-tiers.h>
41 #include <linux/compat.h>
42 #include <linux/pgalloc_tag.h>
43 
44 #include <asm/tlb.h>
45 #include <asm/pgalloc.h>
46 #include "internal.h"
47 #include "swap.h"
48 
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/thp.h>
51 
52 /*
53  * By default, transparent hugepage support is disabled in order to avoid
54  * risking an increased memory footprint for applications that are not
55  * guaranteed to benefit from it. When transparent hugepage support is
56  * enabled, it is for all mappings, and khugepaged scans all mappings.
57  * Defrag is invoked by khugepaged hugepage allocations and by page faults
58  * for all hugepage allocations.
59  */
60 unsigned long transparent_hugepage_flags __read_mostly =
61 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
62 	(1<<TRANSPARENT_HUGEPAGE_FLAG)|
63 #endif
64 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
65 	(1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
66 #endif
67 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
68 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
69 	(1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
70 
71 static struct shrinker *deferred_split_shrinker;
72 static unsigned long deferred_split_count(struct shrinker *shrink,
73 					  struct shrink_control *sc);
74 static unsigned long deferred_split_scan(struct shrinker *shrink,
75 					 struct shrink_control *sc);
76 
77 static atomic_t huge_zero_refcount;
78 struct folio *huge_zero_folio __read_mostly;
79 unsigned long huge_zero_pfn __read_mostly = ~0UL;
80 unsigned long huge_anon_orders_always __read_mostly;
81 unsigned long huge_anon_orders_madvise __read_mostly;
82 unsigned long huge_anon_orders_inherit __read_mostly;
83 
84 unsigned long __thp_vma_allowable_orders(struct vm_area_struct *vma,
85 					 unsigned long vm_flags,
86 					 unsigned long tva_flags,
87 					 unsigned long orders)
88 {
89 	bool smaps = tva_flags & TVA_SMAPS;
90 	bool in_pf = tva_flags & TVA_IN_PF;
91 	bool enforce_sysfs = tva_flags & TVA_ENFORCE_SYSFS;
92 	/* Check the intersection of requested and supported orders. */
93 	orders &= vma_is_anonymous(vma) ?
94 			THP_ORDERS_ALL_ANON : THP_ORDERS_ALL_FILE;
95 	if (!orders)
96 		return 0;
97 
98 	if (!vma->vm_mm)		/* vdso */
99 		return 0;
100 
101 	/*
102 	 * Explicitly disabled through madvise or prctl, or some
103 	 * architectures may disable THP for some mappings, for
104 	 * example, s390 kvm.
105 	 * */
106 	if ((vm_flags & VM_NOHUGEPAGE) ||
107 	    test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
108 		return 0;
109 	/*
110 	 * If the hardware/firmware marked hugepage support disabled.
111 	 */
112 	if (transparent_hugepage_flags & (1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED))
113 		return 0;
114 
115 	/* khugepaged doesn't collapse DAX vma, but page fault is fine. */
116 	if (vma_is_dax(vma))
117 		return in_pf ? orders : 0;
118 
119 	/*
120 	 * khugepaged special VMA and hugetlb VMA.
121 	 * Must be checked after dax since some dax mappings may have
122 	 * VM_MIXEDMAP set.
123 	 */
124 	if (!in_pf && !smaps && (vm_flags & VM_NO_KHUGEPAGED))
125 		return 0;
126 
127 	/*
128 	 * Check alignment for file vma and size for both file and anon vma by
129 	 * filtering out the unsuitable orders.
130 	 *
131 	 * Skip the check for page fault. Huge fault does the check in fault
132 	 * handlers.
133 	 */
134 	if (!in_pf) {
135 		int order = highest_order(orders);
136 		unsigned long addr;
137 
138 		while (orders) {
139 			addr = vma->vm_end - (PAGE_SIZE << order);
140 			if (thp_vma_suitable_order(vma, addr, order))
141 				break;
142 			order = next_order(&orders, order);
143 		}
144 
145 		if (!orders)
146 			return 0;
147 	}
148 
149 	/*
150 	 * Enabled via shmem mount options or sysfs settings.
151 	 * Must be done before hugepage flags check since shmem has its
152 	 * own flags.
153 	 */
154 	if (!in_pf && shmem_file(vma->vm_file))
155 		return shmem_is_huge(file_inode(vma->vm_file), vma->vm_pgoff,
156 				     !enforce_sysfs, vma->vm_mm, vm_flags)
157 			? orders : 0;
158 
159 	if (!vma_is_anonymous(vma)) {
160 		/*
161 		 * Enforce sysfs THP requirements as necessary. Anonymous vmas
162 		 * were already handled in thp_vma_allowable_orders().
163 		 */
164 		if (enforce_sysfs &&
165 		    (!hugepage_global_enabled() || (!(vm_flags & VM_HUGEPAGE) &&
166 						    !hugepage_global_always())))
167 			return 0;
168 
169 		/*
170 		 * Trust that ->huge_fault() handlers know what they are doing
171 		 * in fault path.
172 		 */
173 		if (((in_pf || smaps)) && vma->vm_ops->huge_fault)
174 			return orders;
175 		/* Only regular file is valid in collapse path */
176 		if (((!in_pf || smaps)) && file_thp_enabled(vma))
177 			return orders;
178 		return 0;
179 	}
180 
181 	if (vma_is_temporary_stack(vma))
182 		return 0;
183 
184 	/*
185 	 * THPeligible bit of smaps should show 1 for proper VMAs even
186 	 * though anon_vma is not initialized yet.
187 	 *
188 	 * Allow page fault since anon_vma may be not initialized until
189 	 * the first page fault.
190 	 */
191 	if (!vma->anon_vma)
192 		return (smaps || in_pf) ? orders : 0;
193 
194 	return orders;
195 }
196 
197 static bool get_huge_zero_page(void)
198 {
199 	struct folio *zero_folio;
200 retry:
201 	if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
202 		return true;
203 
204 	zero_folio = folio_alloc((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
205 			HPAGE_PMD_ORDER);
206 	if (!zero_folio) {
207 		count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
208 		return false;
209 	}
210 	preempt_disable();
211 	if (cmpxchg(&huge_zero_folio, NULL, zero_folio)) {
212 		preempt_enable();
213 		folio_put(zero_folio);
214 		goto retry;
215 	}
216 	WRITE_ONCE(huge_zero_pfn, folio_pfn(zero_folio));
217 
218 	/* We take additional reference here. It will be put back by shrinker */
219 	atomic_set(&huge_zero_refcount, 2);
220 	preempt_enable();
221 	count_vm_event(THP_ZERO_PAGE_ALLOC);
222 	return true;
223 }
224 
225 static void put_huge_zero_page(void)
226 {
227 	/*
228 	 * Counter should never go to zero here. Only shrinker can put
229 	 * last reference.
230 	 */
231 	BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
232 }
233 
234 struct folio *mm_get_huge_zero_folio(struct mm_struct *mm)
235 {
236 	if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
237 		return READ_ONCE(huge_zero_folio);
238 
239 	if (!get_huge_zero_page())
240 		return NULL;
241 
242 	if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
243 		put_huge_zero_page();
244 
245 	return READ_ONCE(huge_zero_folio);
246 }
247 
248 void mm_put_huge_zero_folio(struct mm_struct *mm)
249 {
250 	if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
251 		put_huge_zero_page();
252 }
253 
254 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
255 					struct shrink_control *sc)
256 {
257 	/* we can free zero page only if last reference remains */
258 	return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
259 }
260 
261 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
262 				       struct shrink_control *sc)
263 {
264 	if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
265 		struct folio *zero_folio = xchg(&huge_zero_folio, NULL);
266 		BUG_ON(zero_folio == NULL);
267 		WRITE_ONCE(huge_zero_pfn, ~0UL);
268 		folio_put(zero_folio);
269 		return HPAGE_PMD_NR;
270 	}
271 
272 	return 0;
273 }
274 
275 static struct shrinker *huge_zero_page_shrinker;
276 
277 #ifdef CONFIG_SYSFS
278 static ssize_t enabled_show(struct kobject *kobj,
279 			    struct kobj_attribute *attr, char *buf)
280 {
281 	const char *output;
282 
283 	if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
284 		output = "[always] madvise never";
285 	else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
286 			  &transparent_hugepage_flags))
287 		output = "always [madvise] never";
288 	else
289 		output = "always madvise [never]";
290 
291 	return sysfs_emit(buf, "%s\n", output);
292 }
293 
294 static ssize_t enabled_store(struct kobject *kobj,
295 			     struct kobj_attribute *attr,
296 			     const char *buf, size_t count)
297 {
298 	ssize_t ret = count;
299 
300 	if (sysfs_streq(buf, "always")) {
301 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
302 		set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
303 	} else if (sysfs_streq(buf, "madvise")) {
304 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
305 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
306 	} else if (sysfs_streq(buf, "never")) {
307 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
308 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
309 	} else
310 		ret = -EINVAL;
311 
312 	if (ret > 0) {
313 		int err = start_stop_khugepaged();
314 		if (err)
315 			ret = err;
316 	}
317 	return ret;
318 }
319 
320 static struct kobj_attribute enabled_attr = __ATTR_RW(enabled);
321 
322 ssize_t single_hugepage_flag_show(struct kobject *kobj,
323 				  struct kobj_attribute *attr, char *buf,
324 				  enum transparent_hugepage_flag flag)
325 {
326 	return sysfs_emit(buf, "%d\n",
327 			  !!test_bit(flag, &transparent_hugepage_flags));
328 }
329 
330 ssize_t single_hugepage_flag_store(struct kobject *kobj,
331 				 struct kobj_attribute *attr,
332 				 const char *buf, size_t count,
333 				 enum transparent_hugepage_flag flag)
334 {
335 	unsigned long value;
336 	int ret;
337 
338 	ret = kstrtoul(buf, 10, &value);
339 	if (ret < 0)
340 		return ret;
341 	if (value > 1)
342 		return -EINVAL;
343 
344 	if (value)
345 		set_bit(flag, &transparent_hugepage_flags);
346 	else
347 		clear_bit(flag, &transparent_hugepage_flags);
348 
349 	return count;
350 }
351 
352 static ssize_t defrag_show(struct kobject *kobj,
353 			   struct kobj_attribute *attr, char *buf)
354 {
355 	const char *output;
356 
357 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
358 		     &transparent_hugepage_flags))
359 		output = "[always] defer defer+madvise madvise never";
360 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
361 			  &transparent_hugepage_flags))
362 		output = "always [defer] defer+madvise madvise never";
363 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,
364 			  &transparent_hugepage_flags))
365 		output = "always defer [defer+madvise] madvise never";
366 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,
367 			  &transparent_hugepage_flags))
368 		output = "always defer defer+madvise [madvise] never";
369 	else
370 		output = "always defer defer+madvise madvise [never]";
371 
372 	return sysfs_emit(buf, "%s\n", output);
373 }
374 
375 static ssize_t defrag_store(struct kobject *kobj,
376 			    struct kobj_attribute *attr,
377 			    const char *buf, size_t count)
378 {
379 	if (sysfs_streq(buf, "always")) {
380 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
381 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
382 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
383 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
384 	} else if (sysfs_streq(buf, "defer+madvise")) {
385 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
386 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
387 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
388 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
389 	} else if (sysfs_streq(buf, "defer")) {
390 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
391 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
392 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
393 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
394 	} else if (sysfs_streq(buf, "madvise")) {
395 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
396 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
397 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
398 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
399 	} else if (sysfs_streq(buf, "never")) {
400 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
401 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
402 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
403 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
404 	} else
405 		return -EINVAL;
406 
407 	return count;
408 }
409 static struct kobj_attribute defrag_attr = __ATTR_RW(defrag);
410 
411 static ssize_t use_zero_page_show(struct kobject *kobj,
412 				  struct kobj_attribute *attr, char *buf)
413 {
414 	return single_hugepage_flag_show(kobj, attr, buf,
415 					 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
416 }
417 static ssize_t use_zero_page_store(struct kobject *kobj,
418 		struct kobj_attribute *attr, const char *buf, size_t count)
419 {
420 	return single_hugepage_flag_store(kobj, attr, buf, count,
421 				 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
422 }
423 static struct kobj_attribute use_zero_page_attr = __ATTR_RW(use_zero_page);
424 
425 static ssize_t hpage_pmd_size_show(struct kobject *kobj,
426 				   struct kobj_attribute *attr, char *buf)
427 {
428 	return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE);
429 }
430 static struct kobj_attribute hpage_pmd_size_attr =
431 	__ATTR_RO(hpage_pmd_size);
432 
433 static struct attribute *hugepage_attr[] = {
434 	&enabled_attr.attr,
435 	&defrag_attr.attr,
436 	&use_zero_page_attr.attr,
437 	&hpage_pmd_size_attr.attr,
438 #ifdef CONFIG_SHMEM
439 	&shmem_enabled_attr.attr,
440 #endif
441 	NULL,
442 };
443 
444 static const struct attribute_group hugepage_attr_group = {
445 	.attrs = hugepage_attr,
446 };
447 
448 static void hugepage_exit_sysfs(struct kobject *hugepage_kobj);
449 static void thpsize_release(struct kobject *kobj);
450 static DEFINE_SPINLOCK(huge_anon_orders_lock);
451 static LIST_HEAD(thpsize_list);
452 
453 static ssize_t thpsize_enabled_show(struct kobject *kobj,
454 				    struct kobj_attribute *attr, char *buf)
455 {
456 	int order = to_thpsize(kobj)->order;
457 	const char *output;
458 
459 	if (test_bit(order, &huge_anon_orders_always))
460 		output = "[always] inherit madvise never";
461 	else if (test_bit(order, &huge_anon_orders_inherit))
462 		output = "always [inherit] madvise never";
463 	else if (test_bit(order, &huge_anon_orders_madvise))
464 		output = "always inherit [madvise] never";
465 	else
466 		output = "always inherit madvise [never]";
467 
468 	return sysfs_emit(buf, "%s\n", output);
469 }
470 
471 static ssize_t thpsize_enabled_store(struct kobject *kobj,
472 				     struct kobj_attribute *attr,
473 				     const char *buf, size_t count)
474 {
475 	int order = to_thpsize(kobj)->order;
476 	ssize_t ret = count;
477 
478 	if (sysfs_streq(buf, "always")) {
479 		spin_lock(&huge_anon_orders_lock);
480 		clear_bit(order, &huge_anon_orders_inherit);
481 		clear_bit(order, &huge_anon_orders_madvise);
482 		set_bit(order, &huge_anon_orders_always);
483 		spin_unlock(&huge_anon_orders_lock);
484 	} else if (sysfs_streq(buf, "inherit")) {
485 		spin_lock(&huge_anon_orders_lock);
486 		clear_bit(order, &huge_anon_orders_always);
487 		clear_bit(order, &huge_anon_orders_madvise);
488 		set_bit(order, &huge_anon_orders_inherit);
489 		spin_unlock(&huge_anon_orders_lock);
490 	} else if (sysfs_streq(buf, "madvise")) {
491 		spin_lock(&huge_anon_orders_lock);
492 		clear_bit(order, &huge_anon_orders_always);
493 		clear_bit(order, &huge_anon_orders_inherit);
494 		set_bit(order, &huge_anon_orders_madvise);
495 		spin_unlock(&huge_anon_orders_lock);
496 	} else if (sysfs_streq(buf, "never")) {
497 		spin_lock(&huge_anon_orders_lock);
498 		clear_bit(order, &huge_anon_orders_always);
499 		clear_bit(order, &huge_anon_orders_inherit);
500 		clear_bit(order, &huge_anon_orders_madvise);
501 		spin_unlock(&huge_anon_orders_lock);
502 	} else
503 		ret = -EINVAL;
504 
505 	return ret;
506 }
507 
508 static struct kobj_attribute thpsize_enabled_attr =
509 	__ATTR(enabled, 0644, thpsize_enabled_show, thpsize_enabled_store);
510 
511 static struct attribute *thpsize_attrs[] = {
512 	&thpsize_enabled_attr.attr,
513 #ifdef CONFIG_SHMEM
514 	&thpsize_shmem_enabled_attr.attr,
515 #endif
516 	NULL,
517 };
518 
519 static const struct attribute_group thpsize_attr_group = {
520 	.attrs = thpsize_attrs,
521 };
522 
523 static const struct kobj_type thpsize_ktype = {
524 	.release = &thpsize_release,
525 	.sysfs_ops = &kobj_sysfs_ops,
526 };
527 
528 DEFINE_PER_CPU(struct mthp_stat, mthp_stats) = {{{0}}};
529 
530 static unsigned long sum_mthp_stat(int order, enum mthp_stat_item item)
531 {
532 	unsigned long sum = 0;
533 	int cpu;
534 
535 	for_each_possible_cpu(cpu) {
536 		struct mthp_stat *this = &per_cpu(mthp_stats, cpu);
537 
538 		sum += this->stats[order][item];
539 	}
540 
541 	return sum;
542 }
543 
544 #define DEFINE_MTHP_STAT_ATTR(_name, _index)				\
545 static ssize_t _name##_show(struct kobject *kobj,			\
546 			struct kobj_attribute *attr, char *buf)		\
547 {									\
548 	int order = to_thpsize(kobj)->order;				\
549 									\
550 	return sysfs_emit(buf, "%lu\n", sum_mthp_stat(order, _index));	\
551 }									\
552 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
553 
554 DEFINE_MTHP_STAT_ATTR(anon_fault_alloc, MTHP_STAT_ANON_FAULT_ALLOC);
555 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback, MTHP_STAT_ANON_FAULT_FALLBACK);
556 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback_charge, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
557 DEFINE_MTHP_STAT_ATTR(swpout, MTHP_STAT_SWPOUT);
558 DEFINE_MTHP_STAT_ATTR(swpout_fallback, MTHP_STAT_SWPOUT_FALLBACK);
559 DEFINE_MTHP_STAT_ATTR(file_alloc, MTHP_STAT_FILE_ALLOC);
560 DEFINE_MTHP_STAT_ATTR(file_fallback, MTHP_STAT_FILE_FALLBACK);
561 DEFINE_MTHP_STAT_ATTR(file_fallback_charge, MTHP_STAT_FILE_FALLBACK_CHARGE);
562 
563 static struct attribute *stats_attrs[] = {
564 	&anon_fault_alloc_attr.attr,
565 	&anon_fault_fallback_attr.attr,
566 	&anon_fault_fallback_charge_attr.attr,
567 	&swpout_attr.attr,
568 	&swpout_fallback_attr.attr,
569 	&file_alloc_attr.attr,
570 	&file_fallback_attr.attr,
571 	&file_fallback_charge_attr.attr,
572 	NULL,
573 };
574 
575 static struct attribute_group stats_attr_group = {
576 	.name = "stats",
577 	.attrs = stats_attrs,
578 };
579 
580 static struct thpsize *thpsize_create(int order, struct kobject *parent)
581 {
582 	unsigned long size = (PAGE_SIZE << order) / SZ_1K;
583 	struct thpsize *thpsize;
584 	int ret;
585 
586 	thpsize = kzalloc(sizeof(*thpsize), GFP_KERNEL);
587 	if (!thpsize)
588 		return ERR_PTR(-ENOMEM);
589 
590 	ret = kobject_init_and_add(&thpsize->kobj, &thpsize_ktype, parent,
591 				   "hugepages-%lukB", size);
592 	if (ret) {
593 		kfree(thpsize);
594 		return ERR_PTR(ret);
595 	}
596 
597 	ret = sysfs_create_group(&thpsize->kobj, &thpsize_attr_group);
598 	if (ret) {
599 		kobject_put(&thpsize->kobj);
600 		return ERR_PTR(ret);
601 	}
602 
603 	ret = sysfs_create_group(&thpsize->kobj, &stats_attr_group);
604 	if (ret) {
605 		kobject_put(&thpsize->kobj);
606 		return ERR_PTR(ret);
607 	}
608 
609 	thpsize->order = order;
610 	return thpsize;
611 }
612 
613 static void thpsize_release(struct kobject *kobj)
614 {
615 	kfree(to_thpsize(kobj));
616 }
617 
618 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
619 {
620 	int err;
621 	struct thpsize *thpsize;
622 	unsigned long orders;
623 	int order;
624 
625 	/*
626 	 * Default to setting PMD-sized THP to inherit the global setting and
627 	 * disable all other sizes. powerpc's PMD_ORDER isn't a compile-time
628 	 * constant so we have to do this here.
629 	 */
630 	huge_anon_orders_inherit = BIT(PMD_ORDER);
631 
632 	*hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
633 	if (unlikely(!*hugepage_kobj)) {
634 		pr_err("failed to create transparent hugepage kobject\n");
635 		return -ENOMEM;
636 	}
637 
638 	err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
639 	if (err) {
640 		pr_err("failed to register transparent hugepage group\n");
641 		goto delete_obj;
642 	}
643 
644 	err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
645 	if (err) {
646 		pr_err("failed to register transparent hugepage group\n");
647 		goto remove_hp_group;
648 	}
649 
650 	orders = THP_ORDERS_ALL_ANON;
651 	order = highest_order(orders);
652 	while (orders) {
653 		thpsize = thpsize_create(order, *hugepage_kobj);
654 		if (IS_ERR(thpsize)) {
655 			pr_err("failed to create thpsize for order %d\n", order);
656 			err = PTR_ERR(thpsize);
657 			goto remove_all;
658 		}
659 		list_add(&thpsize->node, &thpsize_list);
660 		order = next_order(&orders, order);
661 	}
662 
663 	return 0;
664 
665 remove_all:
666 	hugepage_exit_sysfs(*hugepage_kobj);
667 	return err;
668 remove_hp_group:
669 	sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
670 delete_obj:
671 	kobject_put(*hugepage_kobj);
672 	return err;
673 }
674 
675 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
676 {
677 	struct thpsize *thpsize, *tmp;
678 
679 	list_for_each_entry_safe(thpsize, tmp, &thpsize_list, node) {
680 		list_del(&thpsize->node);
681 		kobject_put(&thpsize->kobj);
682 	}
683 
684 	sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
685 	sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
686 	kobject_put(hugepage_kobj);
687 }
688 #else
689 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
690 {
691 	return 0;
692 }
693 
694 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
695 {
696 }
697 #endif /* CONFIG_SYSFS */
698 
699 static int __init thp_shrinker_init(void)
700 {
701 	huge_zero_page_shrinker = shrinker_alloc(0, "thp-zero");
702 	if (!huge_zero_page_shrinker)
703 		return -ENOMEM;
704 
705 	deferred_split_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE |
706 						 SHRINKER_MEMCG_AWARE |
707 						 SHRINKER_NONSLAB,
708 						 "thp-deferred_split");
709 	if (!deferred_split_shrinker) {
710 		shrinker_free(huge_zero_page_shrinker);
711 		return -ENOMEM;
712 	}
713 
714 	huge_zero_page_shrinker->count_objects = shrink_huge_zero_page_count;
715 	huge_zero_page_shrinker->scan_objects = shrink_huge_zero_page_scan;
716 	shrinker_register(huge_zero_page_shrinker);
717 
718 	deferred_split_shrinker->count_objects = deferred_split_count;
719 	deferred_split_shrinker->scan_objects = deferred_split_scan;
720 	shrinker_register(deferred_split_shrinker);
721 
722 	return 0;
723 }
724 
725 static void __init thp_shrinker_exit(void)
726 {
727 	shrinker_free(huge_zero_page_shrinker);
728 	shrinker_free(deferred_split_shrinker);
729 }
730 
731 static int __init hugepage_init(void)
732 {
733 	int err;
734 	struct kobject *hugepage_kobj;
735 
736 	if (!has_transparent_hugepage()) {
737 		transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED;
738 		return -EINVAL;
739 	}
740 
741 	/*
742 	 * hugepages can't be allocated by the buddy allocator
743 	 */
744 	MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_PAGE_ORDER);
745 
746 	err = hugepage_init_sysfs(&hugepage_kobj);
747 	if (err)
748 		goto err_sysfs;
749 
750 	err = khugepaged_init();
751 	if (err)
752 		goto err_slab;
753 
754 	err = thp_shrinker_init();
755 	if (err)
756 		goto err_shrinker;
757 
758 	/*
759 	 * By default disable transparent hugepages on smaller systems,
760 	 * where the extra memory used could hurt more than TLB overhead
761 	 * is likely to save.  The admin can still enable it through /sys.
762 	 */
763 	if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) {
764 		transparent_hugepage_flags = 0;
765 		return 0;
766 	}
767 
768 	err = start_stop_khugepaged();
769 	if (err)
770 		goto err_khugepaged;
771 
772 	return 0;
773 err_khugepaged:
774 	thp_shrinker_exit();
775 err_shrinker:
776 	khugepaged_destroy();
777 err_slab:
778 	hugepage_exit_sysfs(hugepage_kobj);
779 err_sysfs:
780 	return err;
781 }
782 subsys_initcall(hugepage_init);
783 
784 static int __init setup_transparent_hugepage(char *str)
785 {
786 	int ret = 0;
787 	if (!str)
788 		goto out;
789 	if (!strcmp(str, "always")) {
790 		set_bit(TRANSPARENT_HUGEPAGE_FLAG,
791 			&transparent_hugepage_flags);
792 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
793 			  &transparent_hugepage_flags);
794 		ret = 1;
795 	} else if (!strcmp(str, "madvise")) {
796 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
797 			  &transparent_hugepage_flags);
798 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
799 			&transparent_hugepage_flags);
800 		ret = 1;
801 	} else if (!strcmp(str, "never")) {
802 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
803 			  &transparent_hugepage_flags);
804 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
805 			  &transparent_hugepage_flags);
806 		ret = 1;
807 	}
808 out:
809 	if (!ret)
810 		pr_warn("transparent_hugepage= cannot parse, ignored\n");
811 	return ret;
812 }
813 __setup("transparent_hugepage=", setup_transparent_hugepage);
814 
815 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
816 {
817 	if (likely(vma->vm_flags & VM_WRITE))
818 		pmd = pmd_mkwrite(pmd, vma);
819 	return pmd;
820 }
821 
822 #ifdef CONFIG_MEMCG
823 static inline
824 struct deferred_split *get_deferred_split_queue(struct folio *folio)
825 {
826 	struct mem_cgroup *memcg = folio_memcg(folio);
827 	struct pglist_data *pgdat = NODE_DATA(folio_nid(folio));
828 
829 	if (memcg)
830 		return &memcg->deferred_split_queue;
831 	else
832 		return &pgdat->deferred_split_queue;
833 }
834 #else
835 static inline
836 struct deferred_split *get_deferred_split_queue(struct folio *folio)
837 {
838 	struct pglist_data *pgdat = NODE_DATA(folio_nid(folio));
839 
840 	return &pgdat->deferred_split_queue;
841 }
842 #endif
843 
844 static inline bool is_transparent_hugepage(const struct folio *folio)
845 {
846 	if (!folio_test_large(folio))
847 		return false;
848 
849 	return is_huge_zero_folio(folio) ||
850 		folio_test_large_rmappable(folio);
851 }
852 
853 static unsigned long __thp_get_unmapped_area(struct file *filp,
854 		unsigned long addr, unsigned long len,
855 		loff_t off, unsigned long flags, unsigned long size,
856 		vm_flags_t vm_flags)
857 {
858 	loff_t off_end = off + len;
859 	loff_t off_align = round_up(off, size);
860 	unsigned long len_pad, ret, off_sub;
861 
862 	if (IS_ENABLED(CONFIG_32BIT) || in_compat_syscall())
863 		return 0;
864 
865 	if (off_end <= off_align || (off_end - off_align) < size)
866 		return 0;
867 
868 	len_pad = len + size;
869 	if (len_pad < len || (off + len_pad) < off)
870 		return 0;
871 
872 	ret = mm_get_unmapped_area_vmflags(current->mm, filp, addr, len_pad,
873 					   off >> PAGE_SHIFT, flags, vm_flags);
874 
875 	/*
876 	 * The failure might be due to length padding. The caller will retry
877 	 * without the padding.
878 	 */
879 	if (IS_ERR_VALUE(ret))
880 		return 0;
881 
882 	/*
883 	 * Do not try to align to THP boundary if allocation at the address
884 	 * hint succeeds.
885 	 */
886 	if (ret == addr)
887 		return addr;
888 
889 	off_sub = (off - ret) & (size - 1);
890 
891 	if (test_bit(MMF_TOPDOWN, &current->mm->flags) && !off_sub)
892 		return ret + size;
893 
894 	ret += off_sub;
895 	return ret;
896 }
897 
898 unsigned long thp_get_unmapped_area_vmflags(struct file *filp, unsigned long addr,
899 		unsigned long len, unsigned long pgoff, unsigned long flags,
900 		vm_flags_t vm_flags)
901 {
902 	unsigned long ret;
903 	loff_t off = (loff_t)pgoff << PAGE_SHIFT;
904 
905 	ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE, vm_flags);
906 	if (ret)
907 		return ret;
908 
909 	return mm_get_unmapped_area_vmflags(current->mm, filp, addr, len, pgoff, flags,
910 					    vm_flags);
911 }
912 
913 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
914 		unsigned long len, unsigned long pgoff, unsigned long flags)
915 {
916 	return thp_get_unmapped_area_vmflags(filp, addr, len, pgoff, flags, 0);
917 }
918 EXPORT_SYMBOL_GPL(thp_get_unmapped_area);
919 
920 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf,
921 			struct page *page, gfp_t gfp)
922 {
923 	struct vm_area_struct *vma = vmf->vma;
924 	struct folio *folio = page_folio(page);
925 	pgtable_t pgtable;
926 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
927 	vm_fault_t ret = 0;
928 
929 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
930 
931 	if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
932 		folio_put(folio);
933 		count_vm_event(THP_FAULT_FALLBACK);
934 		count_vm_event(THP_FAULT_FALLBACK_CHARGE);
935 		count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK);
936 		count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
937 		return VM_FAULT_FALLBACK;
938 	}
939 	folio_throttle_swaprate(folio, gfp);
940 
941 	pgtable = pte_alloc_one(vma->vm_mm);
942 	if (unlikely(!pgtable)) {
943 		ret = VM_FAULT_OOM;
944 		goto release;
945 	}
946 
947 	clear_huge_page(page, vmf->address, HPAGE_PMD_NR);
948 	/*
949 	 * The memory barrier inside __folio_mark_uptodate makes sure that
950 	 * clear_huge_page writes become visible before the set_pmd_at()
951 	 * write.
952 	 */
953 	__folio_mark_uptodate(folio);
954 
955 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
956 	if (unlikely(!pmd_none(*vmf->pmd))) {
957 		goto unlock_release;
958 	} else {
959 		pmd_t entry;
960 
961 		ret = check_stable_address_space(vma->vm_mm);
962 		if (ret)
963 			goto unlock_release;
964 
965 		/* Deliver the page fault to userland */
966 		if (userfaultfd_missing(vma)) {
967 			spin_unlock(vmf->ptl);
968 			folio_put(folio);
969 			pte_free(vma->vm_mm, pgtable);
970 			ret = handle_userfault(vmf, VM_UFFD_MISSING);
971 			VM_BUG_ON(ret & VM_FAULT_FALLBACK);
972 			return ret;
973 		}
974 
975 		entry = mk_huge_pmd(page, vma->vm_page_prot);
976 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
977 		folio_add_new_anon_rmap(folio, vma, haddr);
978 		folio_add_lru_vma(folio, vma);
979 		pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
980 		set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
981 		update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
982 		add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
983 		mm_inc_nr_ptes(vma->vm_mm);
984 		spin_unlock(vmf->ptl);
985 		count_vm_event(THP_FAULT_ALLOC);
986 		count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_ALLOC);
987 		count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
988 	}
989 
990 	return 0;
991 unlock_release:
992 	spin_unlock(vmf->ptl);
993 release:
994 	if (pgtable)
995 		pte_free(vma->vm_mm, pgtable);
996 	folio_put(folio);
997 	return ret;
998 
999 }
1000 
1001 /*
1002  * always: directly stall for all thp allocations
1003  * defer: wake kswapd and fail if not immediately available
1004  * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise
1005  *		  fail if not immediately available
1006  * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately
1007  *	    available
1008  * never: never stall for any thp allocation
1009  */
1010 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)
1011 {
1012 	const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE);
1013 
1014 	/* Always do synchronous compaction */
1015 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
1016 		return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);
1017 
1018 	/* Kick kcompactd and fail quickly */
1019 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
1020 		return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;
1021 
1022 	/* Synchronous compaction if madvised, otherwise kick kcompactd */
1023 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags))
1024 		return GFP_TRANSHUGE_LIGHT |
1025 			(vma_madvised ? __GFP_DIRECT_RECLAIM :
1026 					__GFP_KSWAPD_RECLAIM);
1027 
1028 	/* Only do synchronous compaction if madvised */
1029 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
1030 		return GFP_TRANSHUGE_LIGHT |
1031 		       (vma_madvised ? __GFP_DIRECT_RECLAIM : 0);
1032 
1033 	return GFP_TRANSHUGE_LIGHT;
1034 }
1035 
1036 /* Caller must hold page table lock. */
1037 static void set_huge_zero_folio(pgtable_t pgtable, struct mm_struct *mm,
1038 		struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
1039 		struct folio *zero_folio)
1040 {
1041 	pmd_t entry;
1042 	if (!pmd_none(*pmd))
1043 		return;
1044 	entry = mk_pmd(&zero_folio->page, vma->vm_page_prot);
1045 	entry = pmd_mkhuge(entry);
1046 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1047 	set_pmd_at(mm, haddr, pmd, entry);
1048 	mm_inc_nr_ptes(mm);
1049 }
1050 
1051 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf)
1052 {
1053 	struct vm_area_struct *vma = vmf->vma;
1054 	gfp_t gfp;
1055 	struct folio *folio;
1056 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1057 	vm_fault_t ret;
1058 
1059 	if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER))
1060 		return VM_FAULT_FALLBACK;
1061 	ret = vmf_anon_prepare(vmf);
1062 	if (ret)
1063 		return ret;
1064 	khugepaged_enter_vma(vma, vma->vm_flags);
1065 
1066 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
1067 			!mm_forbids_zeropage(vma->vm_mm) &&
1068 			transparent_hugepage_use_zero_page()) {
1069 		pgtable_t pgtable;
1070 		struct folio *zero_folio;
1071 		vm_fault_t ret;
1072 
1073 		pgtable = pte_alloc_one(vma->vm_mm);
1074 		if (unlikely(!pgtable))
1075 			return VM_FAULT_OOM;
1076 		zero_folio = mm_get_huge_zero_folio(vma->vm_mm);
1077 		if (unlikely(!zero_folio)) {
1078 			pte_free(vma->vm_mm, pgtable);
1079 			count_vm_event(THP_FAULT_FALLBACK);
1080 			return VM_FAULT_FALLBACK;
1081 		}
1082 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1083 		ret = 0;
1084 		if (pmd_none(*vmf->pmd)) {
1085 			ret = check_stable_address_space(vma->vm_mm);
1086 			if (ret) {
1087 				spin_unlock(vmf->ptl);
1088 				pte_free(vma->vm_mm, pgtable);
1089 			} else if (userfaultfd_missing(vma)) {
1090 				spin_unlock(vmf->ptl);
1091 				pte_free(vma->vm_mm, pgtable);
1092 				ret = handle_userfault(vmf, VM_UFFD_MISSING);
1093 				VM_BUG_ON(ret & VM_FAULT_FALLBACK);
1094 			} else {
1095 				set_huge_zero_folio(pgtable, vma->vm_mm, vma,
1096 						   haddr, vmf->pmd, zero_folio);
1097 				update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1098 				spin_unlock(vmf->ptl);
1099 			}
1100 		} else {
1101 			spin_unlock(vmf->ptl);
1102 			pte_free(vma->vm_mm, pgtable);
1103 		}
1104 		return ret;
1105 	}
1106 	gfp = vma_thp_gfp_mask(vma);
1107 	folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, vma, haddr, true);
1108 	if (unlikely(!folio)) {
1109 		count_vm_event(THP_FAULT_FALLBACK);
1110 		count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK);
1111 		return VM_FAULT_FALLBACK;
1112 	}
1113 	return __do_huge_pmd_anonymous_page(vmf, &folio->page, gfp);
1114 }
1115 
1116 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
1117 		pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write,
1118 		pgtable_t pgtable)
1119 {
1120 	struct mm_struct *mm = vma->vm_mm;
1121 	pmd_t entry;
1122 	spinlock_t *ptl;
1123 
1124 	ptl = pmd_lock(mm, pmd);
1125 	if (!pmd_none(*pmd)) {
1126 		if (write) {
1127 			if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) {
1128 				WARN_ON_ONCE(!is_huge_zero_pmd(*pmd));
1129 				goto out_unlock;
1130 			}
1131 			entry = pmd_mkyoung(*pmd);
1132 			entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1133 			if (pmdp_set_access_flags(vma, addr, pmd, entry, 1))
1134 				update_mmu_cache_pmd(vma, addr, pmd);
1135 		}
1136 
1137 		goto out_unlock;
1138 	}
1139 
1140 	entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
1141 	if (pfn_t_devmap(pfn))
1142 		entry = pmd_mkdevmap(entry);
1143 	if (write) {
1144 		entry = pmd_mkyoung(pmd_mkdirty(entry));
1145 		entry = maybe_pmd_mkwrite(entry, vma);
1146 	}
1147 
1148 	if (pgtable) {
1149 		pgtable_trans_huge_deposit(mm, pmd, pgtable);
1150 		mm_inc_nr_ptes(mm);
1151 		pgtable = NULL;
1152 	}
1153 
1154 	set_pmd_at(mm, addr, pmd, entry);
1155 	update_mmu_cache_pmd(vma, addr, pmd);
1156 
1157 out_unlock:
1158 	spin_unlock(ptl);
1159 	if (pgtable)
1160 		pte_free(mm, pgtable);
1161 }
1162 
1163 /**
1164  * vmf_insert_pfn_pmd - insert a pmd size pfn
1165  * @vmf: Structure describing the fault
1166  * @pfn: pfn to insert
1167  * @write: whether it's a write fault
1168  *
1169  * Insert a pmd size pfn. See vmf_insert_pfn() for additional info.
1170  *
1171  * Return: vm_fault_t value.
1172  */
1173 vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, pfn_t pfn, bool write)
1174 {
1175 	unsigned long addr = vmf->address & PMD_MASK;
1176 	struct vm_area_struct *vma = vmf->vma;
1177 	pgprot_t pgprot = vma->vm_page_prot;
1178 	pgtable_t pgtable = NULL;
1179 
1180 	/*
1181 	 * If we had pmd_special, we could avoid all these restrictions,
1182 	 * but we need to be consistent with PTEs and architectures that
1183 	 * can't support a 'special' bit.
1184 	 */
1185 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
1186 			!pfn_t_devmap(pfn));
1187 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1188 						(VM_PFNMAP|VM_MIXEDMAP));
1189 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1190 
1191 	if (addr < vma->vm_start || addr >= vma->vm_end)
1192 		return VM_FAULT_SIGBUS;
1193 
1194 	if (arch_needs_pgtable_deposit()) {
1195 		pgtable = pte_alloc_one(vma->vm_mm);
1196 		if (!pgtable)
1197 			return VM_FAULT_OOM;
1198 	}
1199 
1200 	track_pfn_insert(vma, &pgprot, pfn);
1201 
1202 	insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable);
1203 	return VM_FAULT_NOPAGE;
1204 }
1205 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd);
1206 
1207 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1208 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)
1209 {
1210 	if (likely(vma->vm_flags & VM_WRITE))
1211 		pud = pud_mkwrite(pud);
1212 	return pud;
1213 }
1214 
1215 static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr,
1216 		pud_t *pud, pfn_t pfn, bool write)
1217 {
1218 	struct mm_struct *mm = vma->vm_mm;
1219 	pgprot_t prot = vma->vm_page_prot;
1220 	pud_t entry;
1221 	spinlock_t *ptl;
1222 
1223 	ptl = pud_lock(mm, pud);
1224 	if (!pud_none(*pud)) {
1225 		if (write) {
1226 			if (pud_pfn(*pud) != pfn_t_to_pfn(pfn)) {
1227 				WARN_ON_ONCE(!is_huge_zero_pud(*pud));
1228 				goto out_unlock;
1229 			}
1230 			entry = pud_mkyoung(*pud);
1231 			entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma);
1232 			if (pudp_set_access_flags(vma, addr, pud, entry, 1))
1233 				update_mmu_cache_pud(vma, addr, pud);
1234 		}
1235 		goto out_unlock;
1236 	}
1237 
1238 	entry = pud_mkhuge(pfn_t_pud(pfn, prot));
1239 	if (pfn_t_devmap(pfn))
1240 		entry = pud_mkdevmap(entry);
1241 	if (write) {
1242 		entry = pud_mkyoung(pud_mkdirty(entry));
1243 		entry = maybe_pud_mkwrite(entry, vma);
1244 	}
1245 	set_pud_at(mm, addr, pud, entry);
1246 	update_mmu_cache_pud(vma, addr, pud);
1247 
1248 out_unlock:
1249 	spin_unlock(ptl);
1250 }
1251 
1252 /**
1253  * vmf_insert_pfn_pud - insert a pud size pfn
1254  * @vmf: Structure describing the fault
1255  * @pfn: pfn to insert
1256  * @write: whether it's a write fault
1257  *
1258  * Insert a pud size pfn. See vmf_insert_pfn() for additional info.
1259  *
1260  * Return: vm_fault_t value.
1261  */
1262 vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, pfn_t pfn, bool write)
1263 {
1264 	unsigned long addr = vmf->address & PUD_MASK;
1265 	struct vm_area_struct *vma = vmf->vma;
1266 	pgprot_t pgprot = vma->vm_page_prot;
1267 
1268 	/*
1269 	 * If we had pud_special, we could avoid all these restrictions,
1270 	 * but we need to be consistent with PTEs and architectures that
1271 	 * can't support a 'special' bit.
1272 	 */
1273 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
1274 			!pfn_t_devmap(pfn));
1275 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1276 						(VM_PFNMAP|VM_MIXEDMAP));
1277 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1278 
1279 	if (addr < vma->vm_start || addr >= vma->vm_end)
1280 		return VM_FAULT_SIGBUS;
1281 
1282 	track_pfn_insert(vma, &pgprot, pfn);
1283 
1284 	insert_pfn_pud(vma, addr, vmf->pud, pfn, write);
1285 	return VM_FAULT_NOPAGE;
1286 }
1287 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud);
1288 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1289 
1290 void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
1291 	       pmd_t *pmd, bool write)
1292 {
1293 	pmd_t _pmd;
1294 
1295 	_pmd = pmd_mkyoung(*pmd);
1296 	if (write)
1297 		_pmd = pmd_mkdirty(_pmd);
1298 	if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1299 				  pmd, _pmd, write))
1300 		update_mmu_cache_pmd(vma, addr, pmd);
1301 }
1302 
1303 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
1304 		pmd_t *pmd, int flags, struct dev_pagemap **pgmap)
1305 {
1306 	unsigned long pfn = pmd_pfn(*pmd);
1307 	struct mm_struct *mm = vma->vm_mm;
1308 	struct page *page;
1309 	int ret;
1310 
1311 	assert_spin_locked(pmd_lockptr(mm, pmd));
1312 
1313 	if (flags & FOLL_WRITE && !pmd_write(*pmd))
1314 		return NULL;
1315 
1316 	if (pmd_present(*pmd) && pmd_devmap(*pmd))
1317 		/* pass */;
1318 	else
1319 		return NULL;
1320 
1321 	if (flags & FOLL_TOUCH)
1322 		touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
1323 
1324 	/*
1325 	 * device mapped pages can only be returned if the
1326 	 * caller will manage the page reference count.
1327 	 */
1328 	if (!(flags & (FOLL_GET | FOLL_PIN)))
1329 		return ERR_PTR(-EEXIST);
1330 
1331 	pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1332 	*pgmap = get_dev_pagemap(pfn, *pgmap);
1333 	if (!*pgmap)
1334 		return ERR_PTR(-EFAULT);
1335 	page = pfn_to_page(pfn);
1336 	ret = try_grab_page(page, flags);
1337 	if (ret)
1338 		page = ERR_PTR(ret);
1339 
1340 	return page;
1341 }
1342 
1343 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1344 		  pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1345 		  struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1346 {
1347 	spinlock_t *dst_ptl, *src_ptl;
1348 	struct page *src_page;
1349 	struct folio *src_folio;
1350 	pmd_t pmd;
1351 	pgtable_t pgtable = NULL;
1352 	int ret = -ENOMEM;
1353 
1354 	/* Skip if can be re-fill on fault */
1355 	if (!vma_is_anonymous(dst_vma))
1356 		return 0;
1357 
1358 	pgtable = pte_alloc_one(dst_mm);
1359 	if (unlikely(!pgtable))
1360 		goto out;
1361 
1362 	dst_ptl = pmd_lock(dst_mm, dst_pmd);
1363 	src_ptl = pmd_lockptr(src_mm, src_pmd);
1364 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1365 
1366 	ret = -EAGAIN;
1367 	pmd = *src_pmd;
1368 
1369 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1370 	if (unlikely(is_swap_pmd(pmd))) {
1371 		swp_entry_t entry = pmd_to_swp_entry(pmd);
1372 
1373 		VM_BUG_ON(!is_pmd_migration_entry(pmd));
1374 		if (!is_readable_migration_entry(entry)) {
1375 			entry = make_readable_migration_entry(
1376 							swp_offset(entry));
1377 			pmd = swp_entry_to_pmd(entry);
1378 			if (pmd_swp_soft_dirty(*src_pmd))
1379 				pmd = pmd_swp_mksoft_dirty(pmd);
1380 			if (pmd_swp_uffd_wp(*src_pmd))
1381 				pmd = pmd_swp_mkuffd_wp(pmd);
1382 			set_pmd_at(src_mm, addr, src_pmd, pmd);
1383 		}
1384 		add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1385 		mm_inc_nr_ptes(dst_mm);
1386 		pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1387 		if (!userfaultfd_wp(dst_vma))
1388 			pmd = pmd_swp_clear_uffd_wp(pmd);
1389 		set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1390 		ret = 0;
1391 		goto out_unlock;
1392 	}
1393 #endif
1394 
1395 	if (unlikely(!pmd_trans_huge(pmd))) {
1396 		pte_free(dst_mm, pgtable);
1397 		goto out_unlock;
1398 	}
1399 	/*
1400 	 * When page table lock is held, the huge zero pmd should not be
1401 	 * under splitting since we don't split the page itself, only pmd to
1402 	 * a page table.
1403 	 */
1404 	if (is_huge_zero_pmd(pmd)) {
1405 		/*
1406 		 * mm_get_huge_zero_folio() will never allocate a new
1407 		 * folio here, since we already have a zero page to
1408 		 * copy. It just takes a reference.
1409 		 */
1410 		mm_get_huge_zero_folio(dst_mm);
1411 		goto out_zero_page;
1412 	}
1413 
1414 	src_page = pmd_page(pmd);
1415 	VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1416 	src_folio = page_folio(src_page);
1417 
1418 	folio_get(src_folio);
1419 	if (unlikely(folio_try_dup_anon_rmap_pmd(src_folio, src_page, src_vma))) {
1420 		/* Page maybe pinned: split and retry the fault on PTEs. */
1421 		folio_put(src_folio);
1422 		pte_free(dst_mm, pgtable);
1423 		spin_unlock(src_ptl);
1424 		spin_unlock(dst_ptl);
1425 		__split_huge_pmd(src_vma, src_pmd, addr, false, NULL);
1426 		return -EAGAIN;
1427 	}
1428 	add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1429 out_zero_page:
1430 	mm_inc_nr_ptes(dst_mm);
1431 	pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1432 	pmdp_set_wrprotect(src_mm, addr, src_pmd);
1433 	if (!userfaultfd_wp(dst_vma))
1434 		pmd = pmd_clear_uffd_wp(pmd);
1435 	pmd = pmd_mkold(pmd_wrprotect(pmd));
1436 	set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1437 
1438 	ret = 0;
1439 out_unlock:
1440 	spin_unlock(src_ptl);
1441 	spin_unlock(dst_ptl);
1442 out:
1443 	return ret;
1444 }
1445 
1446 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1447 void touch_pud(struct vm_area_struct *vma, unsigned long addr,
1448 	       pud_t *pud, bool write)
1449 {
1450 	pud_t _pud;
1451 
1452 	_pud = pud_mkyoung(*pud);
1453 	if (write)
1454 		_pud = pud_mkdirty(_pud);
1455 	if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK,
1456 				  pud, _pud, write))
1457 		update_mmu_cache_pud(vma, addr, pud);
1458 }
1459 
1460 int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1461 		  pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1462 		  struct vm_area_struct *vma)
1463 {
1464 	spinlock_t *dst_ptl, *src_ptl;
1465 	pud_t pud;
1466 	int ret;
1467 
1468 	dst_ptl = pud_lock(dst_mm, dst_pud);
1469 	src_ptl = pud_lockptr(src_mm, src_pud);
1470 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1471 
1472 	ret = -EAGAIN;
1473 	pud = *src_pud;
1474 	if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud)))
1475 		goto out_unlock;
1476 
1477 	/*
1478 	 * When page table lock is held, the huge zero pud should not be
1479 	 * under splitting since we don't split the page itself, only pud to
1480 	 * a page table.
1481 	 */
1482 	if (is_huge_zero_pud(pud)) {
1483 		/* No huge zero pud yet */
1484 	}
1485 
1486 	/*
1487 	 * TODO: once we support anonymous pages, use
1488 	 * folio_try_dup_anon_rmap_*() and split if duplicating fails.
1489 	 */
1490 	pudp_set_wrprotect(src_mm, addr, src_pud);
1491 	pud = pud_mkold(pud_wrprotect(pud));
1492 	set_pud_at(dst_mm, addr, dst_pud, pud);
1493 
1494 	ret = 0;
1495 out_unlock:
1496 	spin_unlock(src_ptl);
1497 	spin_unlock(dst_ptl);
1498 	return ret;
1499 }
1500 
1501 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)
1502 {
1503 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1504 
1505 	vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud);
1506 	if (unlikely(!pud_same(*vmf->pud, orig_pud)))
1507 		goto unlock;
1508 
1509 	touch_pud(vmf->vma, vmf->address, vmf->pud, write);
1510 unlock:
1511 	spin_unlock(vmf->ptl);
1512 }
1513 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1514 
1515 void huge_pmd_set_accessed(struct vm_fault *vmf)
1516 {
1517 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1518 
1519 	vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd);
1520 	if (unlikely(!pmd_same(*vmf->pmd, vmf->orig_pmd)))
1521 		goto unlock;
1522 
1523 	touch_pmd(vmf->vma, vmf->address, vmf->pmd, write);
1524 
1525 unlock:
1526 	spin_unlock(vmf->ptl);
1527 }
1528 
1529 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
1530 {
1531 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
1532 	struct vm_area_struct *vma = vmf->vma;
1533 	struct folio *folio;
1534 	struct page *page;
1535 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1536 	pmd_t orig_pmd = vmf->orig_pmd;
1537 
1538 	vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
1539 	VM_BUG_ON_VMA(!vma->anon_vma, vma);
1540 
1541 	if (is_huge_zero_pmd(orig_pmd))
1542 		goto fallback;
1543 
1544 	spin_lock(vmf->ptl);
1545 
1546 	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1547 		spin_unlock(vmf->ptl);
1548 		return 0;
1549 	}
1550 
1551 	page = pmd_page(orig_pmd);
1552 	folio = page_folio(page);
1553 	VM_BUG_ON_PAGE(!PageHead(page), page);
1554 
1555 	/* Early check when only holding the PT lock. */
1556 	if (PageAnonExclusive(page))
1557 		goto reuse;
1558 
1559 	if (!folio_trylock(folio)) {
1560 		folio_get(folio);
1561 		spin_unlock(vmf->ptl);
1562 		folio_lock(folio);
1563 		spin_lock(vmf->ptl);
1564 		if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1565 			spin_unlock(vmf->ptl);
1566 			folio_unlock(folio);
1567 			folio_put(folio);
1568 			return 0;
1569 		}
1570 		folio_put(folio);
1571 	}
1572 
1573 	/* Recheck after temporarily dropping the PT lock. */
1574 	if (PageAnonExclusive(page)) {
1575 		folio_unlock(folio);
1576 		goto reuse;
1577 	}
1578 
1579 	/*
1580 	 * See do_wp_page(): we can only reuse the folio exclusively if
1581 	 * there are no additional references. Note that we always drain
1582 	 * the LRU cache immediately after adding a THP.
1583 	 */
1584 	if (folio_ref_count(folio) >
1585 			1 + folio_test_swapcache(folio) * folio_nr_pages(folio))
1586 		goto unlock_fallback;
1587 	if (folio_test_swapcache(folio))
1588 		folio_free_swap(folio);
1589 	if (folio_ref_count(folio) == 1) {
1590 		pmd_t entry;
1591 
1592 		folio_move_anon_rmap(folio, vma);
1593 		SetPageAnonExclusive(page);
1594 		folio_unlock(folio);
1595 reuse:
1596 		if (unlikely(unshare)) {
1597 			spin_unlock(vmf->ptl);
1598 			return 0;
1599 		}
1600 		entry = pmd_mkyoung(orig_pmd);
1601 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1602 		if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1))
1603 			update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1604 		spin_unlock(vmf->ptl);
1605 		return 0;
1606 	}
1607 
1608 unlock_fallback:
1609 	folio_unlock(folio);
1610 	spin_unlock(vmf->ptl);
1611 fallback:
1612 	__split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
1613 	return VM_FAULT_FALLBACK;
1614 }
1615 
1616 static inline bool can_change_pmd_writable(struct vm_area_struct *vma,
1617 					   unsigned long addr, pmd_t pmd)
1618 {
1619 	struct page *page;
1620 
1621 	if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE)))
1622 		return false;
1623 
1624 	/* Don't touch entries that are not even readable (NUMA hinting). */
1625 	if (pmd_protnone(pmd))
1626 		return false;
1627 
1628 	/* Do we need write faults for softdirty tracking? */
1629 	if (vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd))
1630 		return false;
1631 
1632 	/* Do we need write faults for uffd-wp tracking? */
1633 	if (userfaultfd_huge_pmd_wp(vma, pmd))
1634 		return false;
1635 
1636 	if (!(vma->vm_flags & VM_SHARED)) {
1637 		/* See can_change_pte_writable(). */
1638 		page = vm_normal_page_pmd(vma, addr, pmd);
1639 		return page && PageAnon(page) && PageAnonExclusive(page);
1640 	}
1641 
1642 	/* See can_change_pte_writable(). */
1643 	return pmd_dirty(pmd);
1644 }
1645 
1646 /* NUMA hinting page fault entry point for trans huge pmds */
1647 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf)
1648 {
1649 	struct vm_area_struct *vma = vmf->vma;
1650 	pmd_t oldpmd = vmf->orig_pmd;
1651 	pmd_t pmd;
1652 	struct folio *folio;
1653 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1654 	int nid = NUMA_NO_NODE;
1655 	int target_nid, last_cpupid = (-1 & LAST_CPUPID_MASK);
1656 	bool migrated = false, writable = false;
1657 	int flags = 0;
1658 
1659 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1660 	if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1661 		spin_unlock(vmf->ptl);
1662 		goto out;
1663 	}
1664 
1665 	pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1666 
1667 	/*
1668 	 * Detect now whether the PMD could be writable; this information
1669 	 * is only valid while holding the PT lock.
1670 	 */
1671 	writable = pmd_write(pmd);
1672 	if (!writable && vma_wants_manual_pte_write_upgrade(vma) &&
1673 	    can_change_pmd_writable(vma, vmf->address, pmd))
1674 		writable = true;
1675 
1676 	folio = vm_normal_folio_pmd(vma, haddr, pmd);
1677 	if (!folio)
1678 		goto out_map;
1679 
1680 	/* See similar comment in do_numa_page for explanation */
1681 	if (!writable)
1682 		flags |= TNF_NO_GROUP;
1683 
1684 	nid = folio_nid(folio);
1685 	/*
1686 	 * For memory tiering mode, cpupid of slow memory page is used
1687 	 * to record page access time.  So use default value.
1688 	 */
1689 	if (node_is_toptier(nid))
1690 		last_cpupid = folio_last_cpupid(folio);
1691 	target_nid = numa_migrate_prep(folio, vmf, haddr, nid, &flags);
1692 	if (target_nid == NUMA_NO_NODE) {
1693 		folio_put(folio);
1694 		goto out_map;
1695 	}
1696 
1697 	spin_unlock(vmf->ptl);
1698 	writable = false;
1699 
1700 	migrated = migrate_misplaced_folio(folio, vma, target_nid);
1701 	if (migrated) {
1702 		flags |= TNF_MIGRATED;
1703 		nid = target_nid;
1704 	} else {
1705 		flags |= TNF_MIGRATE_FAIL;
1706 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1707 		if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1708 			spin_unlock(vmf->ptl);
1709 			goto out;
1710 		}
1711 		goto out_map;
1712 	}
1713 
1714 out:
1715 	if (nid != NUMA_NO_NODE)
1716 		task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags);
1717 
1718 	return 0;
1719 
1720 out_map:
1721 	/* Restore the PMD */
1722 	pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1723 	pmd = pmd_mkyoung(pmd);
1724 	if (writable)
1725 		pmd = pmd_mkwrite(pmd, vma);
1726 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
1727 	update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1728 	spin_unlock(vmf->ptl);
1729 	goto out;
1730 }
1731 
1732 /*
1733  * Return true if we do MADV_FREE successfully on entire pmd page.
1734  * Otherwise, return false.
1735  */
1736 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1737 		pmd_t *pmd, unsigned long addr, unsigned long next)
1738 {
1739 	spinlock_t *ptl;
1740 	pmd_t orig_pmd;
1741 	struct folio *folio;
1742 	struct mm_struct *mm = tlb->mm;
1743 	bool ret = false;
1744 
1745 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1746 
1747 	ptl = pmd_trans_huge_lock(pmd, vma);
1748 	if (!ptl)
1749 		goto out_unlocked;
1750 
1751 	orig_pmd = *pmd;
1752 	if (is_huge_zero_pmd(orig_pmd))
1753 		goto out;
1754 
1755 	if (unlikely(!pmd_present(orig_pmd))) {
1756 		VM_BUG_ON(thp_migration_supported() &&
1757 				  !is_pmd_migration_entry(orig_pmd));
1758 		goto out;
1759 	}
1760 
1761 	folio = pmd_folio(orig_pmd);
1762 	/*
1763 	 * If other processes are mapping this folio, we couldn't discard
1764 	 * the folio unless they all do MADV_FREE so let's skip the folio.
1765 	 */
1766 	if (folio_likely_mapped_shared(folio))
1767 		goto out;
1768 
1769 	if (!folio_trylock(folio))
1770 		goto out;
1771 
1772 	/*
1773 	 * If user want to discard part-pages of THP, split it so MADV_FREE
1774 	 * will deactivate only them.
1775 	 */
1776 	if (next - addr != HPAGE_PMD_SIZE) {
1777 		folio_get(folio);
1778 		spin_unlock(ptl);
1779 		split_folio(folio);
1780 		folio_unlock(folio);
1781 		folio_put(folio);
1782 		goto out_unlocked;
1783 	}
1784 
1785 	if (folio_test_dirty(folio))
1786 		folio_clear_dirty(folio);
1787 	folio_unlock(folio);
1788 
1789 	if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1790 		pmdp_invalidate(vma, addr, pmd);
1791 		orig_pmd = pmd_mkold(orig_pmd);
1792 		orig_pmd = pmd_mkclean(orig_pmd);
1793 
1794 		set_pmd_at(mm, addr, pmd, orig_pmd);
1795 		tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1796 	}
1797 
1798 	folio_mark_lazyfree(folio);
1799 	ret = true;
1800 out:
1801 	spin_unlock(ptl);
1802 out_unlocked:
1803 	return ret;
1804 }
1805 
1806 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
1807 {
1808 	pgtable_t pgtable;
1809 
1810 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1811 	pte_free(mm, pgtable);
1812 	mm_dec_nr_ptes(mm);
1813 }
1814 
1815 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1816 		 pmd_t *pmd, unsigned long addr)
1817 {
1818 	pmd_t orig_pmd;
1819 	spinlock_t *ptl;
1820 
1821 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1822 
1823 	ptl = __pmd_trans_huge_lock(pmd, vma);
1824 	if (!ptl)
1825 		return 0;
1826 	/*
1827 	 * For architectures like ppc64 we look at deposited pgtable
1828 	 * when calling pmdp_huge_get_and_clear. So do the
1829 	 * pgtable_trans_huge_withdraw after finishing pmdp related
1830 	 * operations.
1831 	 */
1832 	orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
1833 						tlb->fullmm);
1834 	arch_check_zapped_pmd(vma, orig_pmd);
1835 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1836 	if (vma_is_special_huge(vma)) {
1837 		if (arch_needs_pgtable_deposit())
1838 			zap_deposited_table(tlb->mm, pmd);
1839 		spin_unlock(ptl);
1840 	} else if (is_huge_zero_pmd(orig_pmd)) {
1841 		zap_deposited_table(tlb->mm, pmd);
1842 		spin_unlock(ptl);
1843 	} else {
1844 		struct folio *folio = NULL;
1845 		int flush_needed = 1;
1846 
1847 		if (pmd_present(orig_pmd)) {
1848 			struct page *page = pmd_page(orig_pmd);
1849 
1850 			folio = page_folio(page);
1851 			folio_remove_rmap_pmd(folio, page, vma);
1852 			WARN_ON_ONCE(folio_mapcount(folio) < 0);
1853 			VM_BUG_ON_PAGE(!PageHead(page), page);
1854 		} else if (thp_migration_supported()) {
1855 			swp_entry_t entry;
1856 
1857 			VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
1858 			entry = pmd_to_swp_entry(orig_pmd);
1859 			folio = pfn_swap_entry_folio(entry);
1860 			flush_needed = 0;
1861 		} else
1862 			WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
1863 
1864 		if (folio_test_anon(folio)) {
1865 			zap_deposited_table(tlb->mm, pmd);
1866 			add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1867 		} else {
1868 			if (arch_needs_pgtable_deposit())
1869 				zap_deposited_table(tlb->mm, pmd);
1870 			add_mm_counter(tlb->mm, mm_counter_file(folio),
1871 				       -HPAGE_PMD_NR);
1872 		}
1873 
1874 		spin_unlock(ptl);
1875 		if (flush_needed)
1876 			tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE);
1877 	}
1878 	return 1;
1879 }
1880 
1881 #ifndef pmd_move_must_withdraw
1882 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
1883 					 spinlock_t *old_pmd_ptl,
1884 					 struct vm_area_struct *vma)
1885 {
1886 	/*
1887 	 * With split pmd lock we also need to move preallocated
1888 	 * PTE page table if new_pmd is on different PMD page table.
1889 	 *
1890 	 * We also don't deposit and withdraw tables for file pages.
1891 	 */
1892 	return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
1893 }
1894 #endif
1895 
1896 static pmd_t move_soft_dirty_pmd(pmd_t pmd)
1897 {
1898 #ifdef CONFIG_MEM_SOFT_DIRTY
1899 	if (unlikely(is_pmd_migration_entry(pmd)))
1900 		pmd = pmd_swp_mksoft_dirty(pmd);
1901 	else if (pmd_present(pmd))
1902 		pmd = pmd_mksoft_dirty(pmd);
1903 #endif
1904 	return pmd;
1905 }
1906 
1907 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
1908 		  unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
1909 {
1910 	spinlock_t *old_ptl, *new_ptl;
1911 	pmd_t pmd;
1912 	struct mm_struct *mm = vma->vm_mm;
1913 	bool force_flush = false;
1914 
1915 	/*
1916 	 * The destination pmd shouldn't be established, free_pgtables()
1917 	 * should have released it; but move_page_tables() might have already
1918 	 * inserted a page table, if racing against shmem/file collapse.
1919 	 */
1920 	if (!pmd_none(*new_pmd)) {
1921 		VM_BUG_ON(pmd_trans_huge(*new_pmd));
1922 		return false;
1923 	}
1924 
1925 	/*
1926 	 * We don't have to worry about the ordering of src and dst
1927 	 * ptlocks because exclusive mmap_lock prevents deadlock.
1928 	 */
1929 	old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1930 	if (old_ptl) {
1931 		new_ptl = pmd_lockptr(mm, new_pmd);
1932 		if (new_ptl != old_ptl)
1933 			spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1934 		pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1935 		if (pmd_present(pmd))
1936 			force_flush = true;
1937 		VM_BUG_ON(!pmd_none(*new_pmd));
1938 
1939 		if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
1940 			pgtable_t pgtable;
1941 			pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1942 			pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1943 		}
1944 		pmd = move_soft_dirty_pmd(pmd);
1945 		set_pmd_at(mm, new_addr, new_pmd, pmd);
1946 		if (force_flush)
1947 			flush_pmd_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
1948 		if (new_ptl != old_ptl)
1949 			spin_unlock(new_ptl);
1950 		spin_unlock(old_ptl);
1951 		return true;
1952 	}
1953 	return false;
1954 }
1955 
1956 /*
1957  * Returns
1958  *  - 0 if PMD could not be locked
1959  *  - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
1960  *      or if prot_numa but THP migration is not supported
1961  *  - HPAGE_PMD_NR if protections changed and TLB flush necessary
1962  */
1963 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1964 		    pmd_t *pmd, unsigned long addr, pgprot_t newprot,
1965 		    unsigned long cp_flags)
1966 {
1967 	struct mm_struct *mm = vma->vm_mm;
1968 	spinlock_t *ptl;
1969 	pmd_t oldpmd, entry;
1970 	bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
1971 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
1972 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
1973 	int ret = 1;
1974 
1975 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1976 
1977 	if (prot_numa && !thp_migration_supported())
1978 		return 1;
1979 
1980 	ptl = __pmd_trans_huge_lock(pmd, vma);
1981 	if (!ptl)
1982 		return 0;
1983 
1984 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1985 	if (is_swap_pmd(*pmd)) {
1986 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
1987 		struct folio *folio = pfn_swap_entry_folio(entry);
1988 		pmd_t newpmd;
1989 
1990 		VM_BUG_ON(!is_pmd_migration_entry(*pmd));
1991 		if (is_writable_migration_entry(entry)) {
1992 			/*
1993 			 * A protection check is difficult so
1994 			 * just be safe and disable write
1995 			 */
1996 			if (folio_test_anon(folio))
1997 				entry = make_readable_exclusive_migration_entry(swp_offset(entry));
1998 			else
1999 				entry = make_readable_migration_entry(swp_offset(entry));
2000 			newpmd = swp_entry_to_pmd(entry);
2001 			if (pmd_swp_soft_dirty(*pmd))
2002 				newpmd = pmd_swp_mksoft_dirty(newpmd);
2003 		} else {
2004 			newpmd = *pmd;
2005 		}
2006 
2007 		if (uffd_wp)
2008 			newpmd = pmd_swp_mkuffd_wp(newpmd);
2009 		else if (uffd_wp_resolve)
2010 			newpmd = pmd_swp_clear_uffd_wp(newpmd);
2011 		if (!pmd_same(*pmd, newpmd))
2012 			set_pmd_at(mm, addr, pmd, newpmd);
2013 		goto unlock;
2014 	}
2015 #endif
2016 
2017 	if (prot_numa) {
2018 		struct folio *folio;
2019 		bool toptier;
2020 		/*
2021 		 * Avoid trapping faults against the zero page. The read-only
2022 		 * data is likely to be read-cached on the local CPU and
2023 		 * local/remote hits to the zero page are not interesting.
2024 		 */
2025 		if (is_huge_zero_pmd(*pmd))
2026 			goto unlock;
2027 
2028 		if (pmd_protnone(*pmd))
2029 			goto unlock;
2030 
2031 		folio = pmd_folio(*pmd);
2032 		toptier = node_is_toptier(folio_nid(folio));
2033 		/*
2034 		 * Skip scanning top tier node if normal numa
2035 		 * balancing is disabled
2036 		 */
2037 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
2038 		    toptier)
2039 			goto unlock;
2040 
2041 		if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
2042 		    !toptier)
2043 			folio_xchg_access_time(folio,
2044 					       jiffies_to_msecs(jiffies));
2045 	}
2046 	/*
2047 	 * In case prot_numa, we are under mmap_read_lock(mm). It's critical
2048 	 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
2049 	 * which is also under mmap_read_lock(mm):
2050 	 *
2051 	 *	CPU0:				CPU1:
2052 	 *				change_huge_pmd(prot_numa=1)
2053 	 *				 pmdp_huge_get_and_clear_notify()
2054 	 * madvise_dontneed()
2055 	 *  zap_pmd_range()
2056 	 *   pmd_trans_huge(*pmd) == 0 (without ptl)
2057 	 *   // skip the pmd
2058 	 *				 set_pmd_at();
2059 	 *				 // pmd is re-established
2060 	 *
2061 	 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
2062 	 * which may break userspace.
2063 	 *
2064 	 * pmdp_invalidate_ad() is required to make sure we don't miss
2065 	 * dirty/young flags set by hardware.
2066 	 */
2067 	oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
2068 
2069 	entry = pmd_modify(oldpmd, newprot);
2070 	if (uffd_wp)
2071 		entry = pmd_mkuffd_wp(entry);
2072 	else if (uffd_wp_resolve)
2073 		/*
2074 		 * Leave the write bit to be handled by PF interrupt
2075 		 * handler, then things like COW could be properly
2076 		 * handled.
2077 		 */
2078 		entry = pmd_clear_uffd_wp(entry);
2079 
2080 	/* See change_pte_range(). */
2081 	if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) && !pmd_write(entry) &&
2082 	    can_change_pmd_writable(vma, addr, entry))
2083 		entry = pmd_mkwrite(entry, vma);
2084 
2085 	ret = HPAGE_PMD_NR;
2086 	set_pmd_at(mm, addr, pmd, entry);
2087 
2088 	if (huge_pmd_needs_flush(oldpmd, entry))
2089 		tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
2090 unlock:
2091 	spin_unlock(ptl);
2092 	return ret;
2093 }
2094 
2095 #ifdef CONFIG_USERFAULTFD
2096 /*
2097  * The PT lock for src_pmd and dst_vma/src_vma (for reading) are locked by
2098  * the caller, but it must return after releasing the page_table_lock.
2099  * Just move the page from src_pmd to dst_pmd if possible.
2100  * Return zero if succeeded in moving the page, -EAGAIN if it needs to be
2101  * repeated by the caller, or other errors in case of failure.
2102  */
2103 int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pmd_t dst_pmdval,
2104 			struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
2105 			unsigned long dst_addr, unsigned long src_addr)
2106 {
2107 	pmd_t _dst_pmd, src_pmdval;
2108 	struct page *src_page;
2109 	struct folio *src_folio;
2110 	struct anon_vma *src_anon_vma;
2111 	spinlock_t *src_ptl, *dst_ptl;
2112 	pgtable_t src_pgtable;
2113 	struct mmu_notifier_range range;
2114 	int err = 0;
2115 
2116 	src_pmdval = *src_pmd;
2117 	src_ptl = pmd_lockptr(mm, src_pmd);
2118 
2119 	lockdep_assert_held(src_ptl);
2120 	vma_assert_locked(src_vma);
2121 	vma_assert_locked(dst_vma);
2122 
2123 	/* Sanity checks before the operation */
2124 	if (WARN_ON_ONCE(!pmd_none(dst_pmdval)) || WARN_ON_ONCE(src_addr & ~HPAGE_PMD_MASK) ||
2125 	    WARN_ON_ONCE(dst_addr & ~HPAGE_PMD_MASK)) {
2126 		spin_unlock(src_ptl);
2127 		return -EINVAL;
2128 	}
2129 
2130 	if (!pmd_trans_huge(src_pmdval)) {
2131 		spin_unlock(src_ptl);
2132 		if (is_pmd_migration_entry(src_pmdval)) {
2133 			pmd_migration_entry_wait(mm, &src_pmdval);
2134 			return -EAGAIN;
2135 		}
2136 		return -ENOENT;
2137 	}
2138 
2139 	src_page = pmd_page(src_pmdval);
2140 
2141 	if (!is_huge_zero_pmd(src_pmdval)) {
2142 		if (unlikely(!PageAnonExclusive(src_page))) {
2143 			spin_unlock(src_ptl);
2144 			return -EBUSY;
2145 		}
2146 
2147 		src_folio = page_folio(src_page);
2148 		folio_get(src_folio);
2149 	} else
2150 		src_folio = NULL;
2151 
2152 	spin_unlock(src_ptl);
2153 
2154 	flush_cache_range(src_vma, src_addr, src_addr + HPAGE_PMD_SIZE);
2155 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, src_addr,
2156 				src_addr + HPAGE_PMD_SIZE);
2157 	mmu_notifier_invalidate_range_start(&range);
2158 
2159 	if (src_folio) {
2160 		folio_lock(src_folio);
2161 
2162 		/*
2163 		 * split_huge_page walks the anon_vma chain without the page
2164 		 * lock. Serialize against it with the anon_vma lock, the page
2165 		 * lock is not enough.
2166 		 */
2167 		src_anon_vma = folio_get_anon_vma(src_folio);
2168 		if (!src_anon_vma) {
2169 			err = -EAGAIN;
2170 			goto unlock_folio;
2171 		}
2172 		anon_vma_lock_write(src_anon_vma);
2173 	} else
2174 		src_anon_vma = NULL;
2175 
2176 	dst_ptl = pmd_lockptr(mm, dst_pmd);
2177 	double_pt_lock(src_ptl, dst_ptl);
2178 	if (unlikely(!pmd_same(*src_pmd, src_pmdval) ||
2179 		     !pmd_same(*dst_pmd, dst_pmdval))) {
2180 		err = -EAGAIN;
2181 		goto unlock_ptls;
2182 	}
2183 	if (src_folio) {
2184 		if (folio_maybe_dma_pinned(src_folio) ||
2185 		    !PageAnonExclusive(&src_folio->page)) {
2186 			err = -EBUSY;
2187 			goto unlock_ptls;
2188 		}
2189 
2190 		if (WARN_ON_ONCE(!folio_test_head(src_folio)) ||
2191 		    WARN_ON_ONCE(!folio_test_anon(src_folio))) {
2192 			err = -EBUSY;
2193 			goto unlock_ptls;
2194 		}
2195 
2196 		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
2197 		/* Folio got pinned from under us. Put it back and fail the move. */
2198 		if (folio_maybe_dma_pinned(src_folio)) {
2199 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);
2200 			err = -EBUSY;
2201 			goto unlock_ptls;
2202 		}
2203 
2204 		folio_move_anon_rmap(src_folio, dst_vma);
2205 		src_folio->index = linear_page_index(dst_vma, dst_addr);
2206 
2207 		_dst_pmd = mk_huge_pmd(&src_folio->page, dst_vma->vm_page_prot);
2208 		/* Follow mremap() behavior and treat the entry dirty after the move */
2209 		_dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma);
2210 	} else {
2211 		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
2212 		_dst_pmd = mk_huge_pmd(src_page, dst_vma->vm_page_prot);
2213 	}
2214 	set_pmd_at(mm, dst_addr, dst_pmd, _dst_pmd);
2215 
2216 	src_pgtable = pgtable_trans_huge_withdraw(mm, src_pmd);
2217 	pgtable_trans_huge_deposit(mm, dst_pmd, src_pgtable);
2218 unlock_ptls:
2219 	double_pt_unlock(src_ptl, dst_ptl);
2220 	if (src_anon_vma) {
2221 		anon_vma_unlock_write(src_anon_vma);
2222 		put_anon_vma(src_anon_vma);
2223 	}
2224 unlock_folio:
2225 	/* unblock rmap walks */
2226 	if (src_folio)
2227 		folio_unlock(src_folio);
2228 	mmu_notifier_invalidate_range_end(&range);
2229 	if (src_folio)
2230 		folio_put(src_folio);
2231 	return err;
2232 }
2233 #endif /* CONFIG_USERFAULTFD */
2234 
2235 /*
2236  * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
2237  *
2238  * Note that if it returns page table lock pointer, this routine returns without
2239  * unlocking page table lock. So callers must unlock it.
2240  */
2241 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
2242 {
2243 	spinlock_t *ptl;
2244 	ptl = pmd_lock(vma->vm_mm, pmd);
2245 	if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
2246 			pmd_devmap(*pmd)))
2247 		return ptl;
2248 	spin_unlock(ptl);
2249 	return NULL;
2250 }
2251 
2252 /*
2253  * Returns page table lock pointer if a given pud maps a thp, NULL otherwise.
2254  *
2255  * Note that if it returns page table lock pointer, this routine returns without
2256  * unlocking page table lock. So callers must unlock it.
2257  */
2258 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
2259 {
2260 	spinlock_t *ptl;
2261 
2262 	ptl = pud_lock(vma->vm_mm, pud);
2263 	if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
2264 		return ptl;
2265 	spin_unlock(ptl);
2266 	return NULL;
2267 }
2268 
2269 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
2270 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
2271 		 pud_t *pud, unsigned long addr)
2272 {
2273 	spinlock_t *ptl;
2274 
2275 	ptl = __pud_trans_huge_lock(pud, vma);
2276 	if (!ptl)
2277 		return 0;
2278 
2279 	pudp_huge_get_and_clear_full(vma, addr, pud, tlb->fullmm);
2280 	tlb_remove_pud_tlb_entry(tlb, pud, addr);
2281 	if (vma_is_special_huge(vma)) {
2282 		spin_unlock(ptl);
2283 		/* No zero page support yet */
2284 	} else {
2285 		/* No support for anonymous PUD pages yet */
2286 		BUG();
2287 	}
2288 	return 1;
2289 }
2290 
2291 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
2292 		unsigned long haddr)
2293 {
2294 	VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
2295 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2296 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
2297 	VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
2298 
2299 	count_vm_event(THP_SPLIT_PUD);
2300 
2301 	pudp_huge_clear_flush(vma, haddr, pud);
2302 }
2303 
2304 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
2305 		unsigned long address)
2306 {
2307 	spinlock_t *ptl;
2308 	struct mmu_notifier_range range;
2309 
2310 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2311 				address & HPAGE_PUD_MASK,
2312 				(address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
2313 	mmu_notifier_invalidate_range_start(&range);
2314 	ptl = pud_lock(vma->vm_mm, pud);
2315 	if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
2316 		goto out;
2317 	__split_huge_pud_locked(vma, pud, range.start);
2318 
2319 out:
2320 	spin_unlock(ptl);
2321 	mmu_notifier_invalidate_range_end(&range);
2322 }
2323 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
2324 
2325 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2326 		unsigned long haddr, pmd_t *pmd)
2327 {
2328 	struct mm_struct *mm = vma->vm_mm;
2329 	pgtable_t pgtable;
2330 	pmd_t _pmd, old_pmd;
2331 	unsigned long addr;
2332 	pte_t *pte;
2333 	int i;
2334 
2335 	/*
2336 	 * Leave pmd empty until pte is filled note that it is fine to delay
2337 	 * notification until mmu_notifier_invalidate_range_end() as we are
2338 	 * replacing a zero pmd write protected page with a zero pte write
2339 	 * protected page.
2340 	 *
2341 	 * See Documentation/mm/mmu_notifier.rst
2342 	 */
2343 	old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
2344 
2345 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2346 	pmd_populate(mm, &_pmd, pgtable);
2347 
2348 	pte = pte_offset_map(&_pmd, haddr);
2349 	VM_BUG_ON(!pte);
2350 	for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2351 		pte_t entry;
2352 
2353 		entry = pfn_pte(my_zero_pfn(addr), vma->vm_page_prot);
2354 		entry = pte_mkspecial(entry);
2355 		if (pmd_uffd_wp(old_pmd))
2356 			entry = pte_mkuffd_wp(entry);
2357 		VM_BUG_ON(!pte_none(ptep_get(pte)));
2358 		set_pte_at(mm, addr, pte, entry);
2359 		pte++;
2360 	}
2361 	pte_unmap(pte - 1);
2362 	smp_wmb(); /* make pte visible before pmd */
2363 	pmd_populate(mm, pmd, pgtable);
2364 }
2365 
2366 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
2367 		unsigned long haddr, bool freeze)
2368 {
2369 	struct mm_struct *mm = vma->vm_mm;
2370 	struct folio *folio;
2371 	struct page *page;
2372 	pgtable_t pgtable;
2373 	pmd_t old_pmd, _pmd;
2374 	bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
2375 	bool anon_exclusive = false, dirty = false;
2376 	unsigned long addr;
2377 	pte_t *pte;
2378 	int i;
2379 
2380 	VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2381 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2382 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
2383 	VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
2384 				&& !pmd_devmap(*pmd));
2385 
2386 	count_vm_event(THP_SPLIT_PMD);
2387 
2388 	if (!vma_is_anonymous(vma)) {
2389 		old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
2390 		/*
2391 		 * We are going to unmap this huge page. So
2392 		 * just go ahead and zap it
2393 		 */
2394 		if (arch_needs_pgtable_deposit())
2395 			zap_deposited_table(mm, pmd);
2396 		if (vma_is_special_huge(vma))
2397 			return;
2398 		if (unlikely(is_pmd_migration_entry(old_pmd))) {
2399 			swp_entry_t entry;
2400 
2401 			entry = pmd_to_swp_entry(old_pmd);
2402 			folio = pfn_swap_entry_folio(entry);
2403 		} else {
2404 			page = pmd_page(old_pmd);
2405 			folio = page_folio(page);
2406 			if (!folio_test_dirty(folio) && pmd_dirty(old_pmd))
2407 				folio_mark_dirty(folio);
2408 			if (!folio_test_referenced(folio) && pmd_young(old_pmd))
2409 				folio_set_referenced(folio);
2410 			folio_remove_rmap_pmd(folio, page, vma);
2411 			folio_put(folio);
2412 		}
2413 		add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
2414 		return;
2415 	}
2416 
2417 	if (is_huge_zero_pmd(*pmd)) {
2418 		/*
2419 		 * FIXME: Do we want to invalidate secondary mmu by calling
2420 		 * mmu_notifier_arch_invalidate_secondary_tlbs() see comments below
2421 		 * inside __split_huge_pmd() ?
2422 		 *
2423 		 * We are going from a zero huge page write protected to zero
2424 		 * small page also write protected so it does not seems useful
2425 		 * to invalidate secondary mmu at this time.
2426 		 */
2427 		return __split_huge_zero_page_pmd(vma, haddr, pmd);
2428 	}
2429 
2430 	pmd_migration = is_pmd_migration_entry(*pmd);
2431 	if (unlikely(pmd_migration)) {
2432 		swp_entry_t entry;
2433 
2434 		old_pmd = *pmd;
2435 		entry = pmd_to_swp_entry(old_pmd);
2436 		page = pfn_swap_entry_to_page(entry);
2437 		write = is_writable_migration_entry(entry);
2438 		if (PageAnon(page))
2439 			anon_exclusive = is_readable_exclusive_migration_entry(entry);
2440 		young = is_migration_entry_young(entry);
2441 		dirty = is_migration_entry_dirty(entry);
2442 		soft_dirty = pmd_swp_soft_dirty(old_pmd);
2443 		uffd_wp = pmd_swp_uffd_wp(old_pmd);
2444 	} else {
2445 		/*
2446 		 * Up to this point the pmd is present and huge and userland has
2447 		 * the whole access to the hugepage during the split (which
2448 		 * happens in place). If we overwrite the pmd with the not-huge
2449 		 * version pointing to the pte here (which of course we could if
2450 		 * all CPUs were bug free), userland could trigger a small page
2451 		 * size TLB miss on the small sized TLB while the hugepage TLB
2452 		 * entry is still established in the huge TLB. Some CPU doesn't
2453 		 * like that. See
2454 		 * http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2455 		 * 383 on page 105. Intel should be safe but is also warns that
2456 		 * it's only safe if the permission and cache attributes of the
2457 		 * two entries loaded in the two TLB is identical (which should
2458 		 * be the case here). But it is generally safer to never allow
2459 		 * small and huge TLB entries for the same virtual address to be
2460 		 * loaded simultaneously. So instead of doing "pmd_populate();
2461 		 * flush_pmd_tlb_range();" we first mark the current pmd
2462 		 * notpresent (atomically because here the pmd_trans_huge must
2463 		 * remain set at all times on the pmd until the split is
2464 		 * complete for this pmd), then we flush the SMP TLB and finally
2465 		 * we write the non-huge version of the pmd entry with
2466 		 * pmd_populate.
2467 		 */
2468 		old_pmd = pmdp_invalidate(vma, haddr, pmd);
2469 		page = pmd_page(old_pmd);
2470 		folio = page_folio(page);
2471 		if (pmd_dirty(old_pmd)) {
2472 			dirty = true;
2473 			folio_set_dirty(folio);
2474 		}
2475 		write = pmd_write(old_pmd);
2476 		young = pmd_young(old_pmd);
2477 		soft_dirty = pmd_soft_dirty(old_pmd);
2478 		uffd_wp = pmd_uffd_wp(old_pmd);
2479 
2480 		VM_WARN_ON_FOLIO(!folio_ref_count(folio), folio);
2481 		VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
2482 
2483 		/*
2484 		 * Without "freeze", we'll simply split the PMD, propagating the
2485 		 * PageAnonExclusive() flag for each PTE by setting it for
2486 		 * each subpage -- no need to (temporarily) clear.
2487 		 *
2488 		 * With "freeze" we want to replace mapped pages by
2489 		 * migration entries right away. This is only possible if we
2490 		 * managed to clear PageAnonExclusive() -- see
2491 		 * set_pmd_migration_entry().
2492 		 *
2493 		 * In case we cannot clear PageAnonExclusive(), split the PMD
2494 		 * only and let try_to_migrate_one() fail later.
2495 		 *
2496 		 * See folio_try_share_anon_rmap_pmd(): invalidate PMD first.
2497 		 */
2498 		anon_exclusive = PageAnonExclusive(page);
2499 		if (freeze && anon_exclusive &&
2500 		    folio_try_share_anon_rmap_pmd(folio, page))
2501 			freeze = false;
2502 		if (!freeze) {
2503 			rmap_t rmap_flags = RMAP_NONE;
2504 
2505 			folio_ref_add(folio, HPAGE_PMD_NR - 1);
2506 			if (anon_exclusive)
2507 				rmap_flags |= RMAP_EXCLUSIVE;
2508 			folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR,
2509 						 vma, haddr, rmap_flags);
2510 		}
2511 	}
2512 
2513 	/*
2514 	 * Withdraw the table only after we mark the pmd entry invalid.
2515 	 * This's critical for some architectures (Power).
2516 	 */
2517 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2518 	pmd_populate(mm, &_pmd, pgtable);
2519 
2520 	pte = pte_offset_map(&_pmd, haddr);
2521 	VM_BUG_ON(!pte);
2522 
2523 	/*
2524 	 * Note that NUMA hinting access restrictions are not transferred to
2525 	 * avoid any possibility of altering permissions across VMAs.
2526 	 */
2527 	if (freeze || pmd_migration) {
2528 		for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2529 			pte_t entry;
2530 			swp_entry_t swp_entry;
2531 
2532 			if (write)
2533 				swp_entry = make_writable_migration_entry(
2534 							page_to_pfn(page + i));
2535 			else if (anon_exclusive)
2536 				swp_entry = make_readable_exclusive_migration_entry(
2537 							page_to_pfn(page + i));
2538 			else
2539 				swp_entry = make_readable_migration_entry(
2540 							page_to_pfn(page + i));
2541 			if (young)
2542 				swp_entry = make_migration_entry_young(swp_entry);
2543 			if (dirty)
2544 				swp_entry = make_migration_entry_dirty(swp_entry);
2545 			entry = swp_entry_to_pte(swp_entry);
2546 			if (soft_dirty)
2547 				entry = pte_swp_mksoft_dirty(entry);
2548 			if (uffd_wp)
2549 				entry = pte_swp_mkuffd_wp(entry);
2550 
2551 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
2552 			set_pte_at(mm, addr, pte + i, entry);
2553 		}
2554 	} else {
2555 		pte_t entry;
2556 
2557 		entry = mk_pte(page, READ_ONCE(vma->vm_page_prot));
2558 		if (write)
2559 			entry = pte_mkwrite(entry, vma);
2560 		if (!young)
2561 			entry = pte_mkold(entry);
2562 		/* NOTE: this may set soft-dirty too on some archs */
2563 		if (dirty)
2564 			entry = pte_mkdirty(entry);
2565 		if (soft_dirty)
2566 			entry = pte_mksoft_dirty(entry);
2567 		if (uffd_wp)
2568 			entry = pte_mkuffd_wp(entry);
2569 
2570 		for (i = 0; i < HPAGE_PMD_NR; i++)
2571 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
2572 
2573 		set_ptes(mm, haddr, pte, entry, HPAGE_PMD_NR);
2574 	}
2575 	pte_unmap(pte);
2576 
2577 	if (!pmd_migration)
2578 		folio_remove_rmap_pmd(folio, page, vma);
2579 	if (freeze)
2580 		put_page(page);
2581 
2582 	smp_wmb(); /* make pte visible before pmd */
2583 	pmd_populate(mm, pmd, pgtable);
2584 }
2585 
2586 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2587 		unsigned long address, bool freeze, struct folio *folio)
2588 {
2589 	spinlock_t *ptl;
2590 	struct mmu_notifier_range range;
2591 
2592 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2593 				address & HPAGE_PMD_MASK,
2594 				(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2595 	mmu_notifier_invalidate_range_start(&range);
2596 	ptl = pmd_lock(vma->vm_mm, pmd);
2597 
2598 	/*
2599 	 * If caller asks to setup a migration entry, we need a folio to check
2600 	 * pmd against. Otherwise we can end up replacing wrong folio.
2601 	 */
2602 	VM_BUG_ON(freeze && !folio);
2603 	VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
2604 
2605 	if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
2606 	    is_pmd_migration_entry(*pmd)) {
2607 		/*
2608 		 * It's safe to call pmd_page when folio is set because it's
2609 		 * guaranteed that pmd is present.
2610 		 */
2611 		if (folio && folio != pmd_folio(*pmd))
2612 			goto out;
2613 		__split_huge_pmd_locked(vma, pmd, range.start, freeze);
2614 	}
2615 
2616 out:
2617 	spin_unlock(ptl);
2618 	mmu_notifier_invalidate_range_end(&range);
2619 }
2620 
2621 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2622 		bool freeze, struct folio *folio)
2623 {
2624 	pmd_t *pmd = mm_find_pmd(vma->vm_mm, address);
2625 
2626 	if (!pmd)
2627 		return;
2628 
2629 	__split_huge_pmd(vma, pmd, address, freeze, folio);
2630 }
2631 
2632 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2633 {
2634 	/*
2635 	 * If the new address isn't hpage aligned and it could previously
2636 	 * contain an hugepage: check if we need to split an huge pmd.
2637 	 */
2638 	if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2639 	    range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2640 			 ALIGN(address, HPAGE_PMD_SIZE)))
2641 		split_huge_pmd_address(vma, address, false, NULL);
2642 }
2643 
2644 void vma_adjust_trans_huge(struct vm_area_struct *vma,
2645 			     unsigned long start,
2646 			     unsigned long end,
2647 			     long adjust_next)
2648 {
2649 	/* Check if we need to split start first. */
2650 	split_huge_pmd_if_needed(vma, start);
2651 
2652 	/* Check if we need to split end next. */
2653 	split_huge_pmd_if_needed(vma, end);
2654 
2655 	/*
2656 	 * If we're also updating the next vma vm_start,
2657 	 * check if we need to split it.
2658 	 */
2659 	if (adjust_next > 0) {
2660 		struct vm_area_struct *next = find_vma(vma->vm_mm, vma->vm_end);
2661 		unsigned long nstart = next->vm_start;
2662 		nstart += adjust_next;
2663 		split_huge_pmd_if_needed(next, nstart);
2664 	}
2665 }
2666 
2667 static void unmap_folio(struct folio *folio)
2668 {
2669 	enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SYNC |
2670 		TTU_BATCH_FLUSH;
2671 
2672 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
2673 
2674 	if (folio_test_pmd_mappable(folio))
2675 		ttu_flags |= TTU_SPLIT_HUGE_PMD;
2676 
2677 	/*
2678 	 * Anon pages need migration entries to preserve them, but file
2679 	 * pages can simply be left unmapped, then faulted back on demand.
2680 	 * If that is ever changed (perhaps for mlock), update remap_page().
2681 	 */
2682 	if (folio_test_anon(folio))
2683 		try_to_migrate(folio, ttu_flags);
2684 	else
2685 		try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
2686 
2687 	try_to_unmap_flush();
2688 }
2689 
2690 static void remap_page(struct folio *folio, unsigned long nr)
2691 {
2692 	int i = 0;
2693 
2694 	/* If unmap_folio() uses try_to_migrate() on file, remove this check */
2695 	if (!folio_test_anon(folio))
2696 		return;
2697 	for (;;) {
2698 		remove_migration_ptes(folio, folio, true);
2699 		i += folio_nr_pages(folio);
2700 		if (i >= nr)
2701 			break;
2702 		folio = folio_next(folio);
2703 	}
2704 }
2705 
2706 static void lru_add_page_tail(struct page *head, struct page *tail,
2707 		struct lruvec *lruvec, struct list_head *list)
2708 {
2709 	VM_BUG_ON_PAGE(!PageHead(head), head);
2710 	VM_BUG_ON_PAGE(PageLRU(tail), head);
2711 	lockdep_assert_held(&lruvec->lru_lock);
2712 
2713 	if (list) {
2714 		/* page reclaim is reclaiming a huge page */
2715 		VM_WARN_ON(PageLRU(head));
2716 		get_page(tail);
2717 		list_add_tail(&tail->lru, list);
2718 	} else {
2719 		/* head is still on lru (and we have it frozen) */
2720 		VM_WARN_ON(!PageLRU(head));
2721 		if (PageUnevictable(tail))
2722 			tail->mlock_count = 0;
2723 		else
2724 			list_add_tail(&tail->lru, &head->lru);
2725 		SetPageLRU(tail);
2726 	}
2727 }
2728 
2729 static void __split_huge_page_tail(struct folio *folio, int tail,
2730 		struct lruvec *lruvec, struct list_head *list,
2731 		unsigned int new_order)
2732 {
2733 	struct page *head = &folio->page;
2734 	struct page *page_tail = head + tail;
2735 	/*
2736 	 * Careful: new_folio is not a "real" folio before we cleared PageTail.
2737 	 * Don't pass it around before clear_compound_head().
2738 	 */
2739 	struct folio *new_folio = (struct folio *)page_tail;
2740 
2741 	VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
2742 
2743 	/*
2744 	 * Clone page flags before unfreezing refcount.
2745 	 *
2746 	 * After successful get_page_unless_zero() might follow flags change,
2747 	 * for example lock_page() which set PG_waiters.
2748 	 *
2749 	 * Note that for mapped sub-pages of an anonymous THP,
2750 	 * PG_anon_exclusive has been cleared in unmap_folio() and is stored in
2751 	 * the migration entry instead from where remap_page() will restore it.
2752 	 * We can still have PG_anon_exclusive set on effectively unmapped and
2753 	 * unreferenced sub-pages of an anonymous THP: we can simply drop
2754 	 * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
2755 	 */
2756 	page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
2757 	page_tail->flags |= (head->flags &
2758 			((1L << PG_referenced) |
2759 			 (1L << PG_swapbacked) |
2760 			 (1L << PG_swapcache) |
2761 			 (1L << PG_mlocked) |
2762 			 (1L << PG_uptodate) |
2763 			 (1L << PG_active) |
2764 			 (1L << PG_workingset) |
2765 			 (1L << PG_locked) |
2766 			 (1L << PG_unevictable) |
2767 #ifdef CONFIG_ARCH_USES_PG_ARCH_X
2768 			 (1L << PG_arch_2) |
2769 			 (1L << PG_arch_3) |
2770 #endif
2771 			 (1L << PG_dirty) |
2772 			 LRU_GEN_MASK | LRU_REFS_MASK));
2773 
2774 	/* ->mapping in first and second tail page is replaced by other uses */
2775 	VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
2776 			page_tail);
2777 	page_tail->mapping = head->mapping;
2778 	page_tail->index = head->index + tail;
2779 
2780 	/*
2781 	 * page->private should not be set in tail pages. Fix up and warn once
2782 	 * if private is unexpectedly set.
2783 	 */
2784 	if (unlikely(page_tail->private)) {
2785 		VM_WARN_ON_ONCE_PAGE(true, page_tail);
2786 		page_tail->private = 0;
2787 	}
2788 	if (folio_test_swapcache(folio))
2789 		new_folio->swap.val = folio->swap.val + tail;
2790 
2791 	/* Page flags must be visible before we make the page non-compound. */
2792 	smp_wmb();
2793 
2794 	/*
2795 	 * Clear PageTail before unfreezing page refcount.
2796 	 *
2797 	 * After successful get_page_unless_zero() might follow put_page()
2798 	 * which needs correct compound_head().
2799 	 */
2800 	clear_compound_head(page_tail);
2801 	if (new_order) {
2802 		prep_compound_page(page_tail, new_order);
2803 		folio_set_large_rmappable(new_folio);
2804 	}
2805 
2806 	/* Finally unfreeze refcount. Additional reference from page cache. */
2807 	page_ref_unfreeze(page_tail,
2808 		1 + ((!folio_test_anon(folio) || folio_test_swapcache(folio)) ?
2809 			     folio_nr_pages(new_folio) : 0));
2810 
2811 	if (folio_test_young(folio))
2812 		folio_set_young(new_folio);
2813 	if (folio_test_idle(folio))
2814 		folio_set_idle(new_folio);
2815 
2816 	folio_xchg_last_cpupid(new_folio, folio_last_cpupid(folio));
2817 
2818 	/*
2819 	 * always add to the tail because some iterators expect new
2820 	 * pages to show after the currently processed elements - e.g.
2821 	 * migrate_pages
2822 	 */
2823 	lru_add_page_tail(head, page_tail, lruvec, list);
2824 }
2825 
2826 static void __split_huge_page(struct page *page, struct list_head *list,
2827 		pgoff_t end, unsigned int new_order)
2828 {
2829 	struct folio *folio = page_folio(page);
2830 	struct page *head = &folio->page;
2831 	struct lruvec *lruvec;
2832 	struct address_space *swap_cache = NULL;
2833 	unsigned long offset = 0;
2834 	int i, nr_dropped = 0;
2835 	unsigned int new_nr = 1 << new_order;
2836 	int order = folio_order(folio);
2837 	unsigned int nr = 1 << order;
2838 
2839 	/* complete memcg works before add pages to LRU */
2840 	split_page_memcg(head, order, new_order);
2841 
2842 	if (folio_test_anon(folio) && folio_test_swapcache(folio)) {
2843 		offset = swap_cache_index(folio->swap);
2844 		swap_cache = swap_address_space(folio->swap);
2845 		xa_lock(&swap_cache->i_pages);
2846 	}
2847 
2848 	/* lock lru list/PageCompound, ref frozen by page_ref_freeze */
2849 	lruvec = folio_lruvec_lock(folio);
2850 
2851 	ClearPageHasHWPoisoned(head);
2852 
2853 	for (i = nr - new_nr; i >= new_nr; i -= new_nr) {
2854 		__split_huge_page_tail(folio, i, lruvec, list, new_order);
2855 		/* Some pages can be beyond EOF: drop them from page cache */
2856 		if (head[i].index >= end) {
2857 			struct folio *tail = page_folio(head + i);
2858 
2859 			if (shmem_mapping(folio->mapping))
2860 				nr_dropped++;
2861 			else if (folio_test_clear_dirty(tail))
2862 				folio_account_cleaned(tail,
2863 					inode_to_wb(folio->mapping->host));
2864 			__filemap_remove_folio(tail, NULL);
2865 			folio_put(tail);
2866 		} else if (!PageAnon(page)) {
2867 			__xa_store(&folio->mapping->i_pages, head[i].index,
2868 					head + i, 0);
2869 		} else if (swap_cache) {
2870 			__xa_store(&swap_cache->i_pages, offset + i,
2871 					head + i, 0);
2872 		}
2873 	}
2874 
2875 	if (!new_order)
2876 		ClearPageCompound(head);
2877 	else {
2878 		struct folio *new_folio = (struct folio *)head;
2879 
2880 		folio_set_order(new_folio, new_order);
2881 	}
2882 	unlock_page_lruvec(lruvec);
2883 	/* Caller disabled irqs, so they are still disabled here */
2884 
2885 	split_page_owner(head, order, new_order);
2886 	pgalloc_tag_split(head, 1 << order);
2887 
2888 	/* See comment in __split_huge_page_tail() */
2889 	if (folio_test_anon(folio)) {
2890 		/* Additional pin to swap cache */
2891 		if (folio_test_swapcache(folio)) {
2892 			folio_ref_add(folio, 1 + new_nr);
2893 			xa_unlock(&swap_cache->i_pages);
2894 		} else {
2895 			folio_ref_inc(folio);
2896 		}
2897 	} else {
2898 		/* Additional pin to page cache */
2899 		folio_ref_add(folio, 1 + new_nr);
2900 		xa_unlock(&folio->mapping->i_pages);
2901 	}
2902 	local_irq_enable();
2903 
2904 	if (nr_dropped)
2905 		shmem_uncharge(folio->mapping->host, nr_dropped);
2906 	remap_page(folio, nr);
2907 
2908 	/*
2909 	 * set page to its compound_head when split to non order-0 pages, so
2910 	 * we can skip unlocking it below, since PG_locked is transferred to
2911 	 * the compound_head of the page and the caller will unlock it.
2912 	 */
2913 	if (new_order)
2914 		page = compound_head(page);
2915 
2916 	for (i = 0; i < nr; i += new_nr) {
2917 		struct page *subpage = head + i;
2918 		struct folio *new_folio = page_folio(subpage);
2919 		if (subpage == page)
2920 			continue;
2921 		folio_unlock(new_folio);
2922 
2923 		/*
2924 		 * Subpages may be freed if there wasn't any mapping
2925 		 * like if add_to_swap() is running on a lru page that
2926 		 * had its mapping zapped. And freeing these pages
2927 		 * requires taking the lru_lock so we do the put_page
2928 		 * of the tail pages after the split is complete.
2929 		 */
2930 		free_page_and_swap_cache(subpage);
2931 	}
2932 }
2933 
2934 /* Racy check whether the huge page can be split */
2935 bool can_split_folio(struct folio *folio, int *pextra_pins)
2936 {
2937 	int extra_pins;
2938 
2939 	/* Additional pins from page cache */
2940 	if (folio_test_anon(folio))
2941 		extra_pins = folio_test_swapcache(folio) ?
2942 				folio_nr_pages(folio) : 0;
2943 	else
2944 		extra_pins = folio_nr_pages(folio);
2945 	if (pextra_pins)
2946 		*pextra_pins = extra_pins;
2947 	return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 1;
2948 }
2949 
2950 /*
2951  * This function splits a large folio into smaller folios of order @new_order.
2952  * @page can point to any page of the large folio to split. The split operation
2953  * does not change the position of @page.
2954  *
2955  * Prerequisites:
2956  *
2957  * 1) The caller must hold a reference on the @page's owning folio, also known
2958  *    as the large folio.
2959  *
2960  * 2) The large folio must be locked.
2961  *
2962  * 3) The folio must not be pinned. Any unexpected folio references, including
2963  *    GUP pins, will result in the folio not getting split; instead, the caller
2964  *    will receive an -EAGAIN.
2965  *
2966  * 4) @new_order > 1, usually. Splitting to order-1 anonymous folios is not
2967  *    supported for non-file-backed folios, because folio->_deferred_list, which
2968  *    is used by partially mapped folios, is stored in subpage 2, but an order-1
2969  *    folio only has subpages 0 and 1. File-backed order-1 folios are supported,
2970  *    since they do not use _deferred_list.
2971  *
2972  * After splitting, the caller's folio reference will be transferred to @page,
2973  * resulting in a raised refcount of @page after this call. The other pages may
2974  * be freed if they are not mapped.
2975  *
2976  * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
2977  *
2978  * Pages in @new_order will inherit the mapping, flags, and so on from the
2979  * huge page.
2980  *
2981  * Returns 0 if the huge page was split successfully.
2982  *
2983  * Returns -EAGAIN if the folio has unexpected reference (e.g., GUP) or if
2984  * the folio was concurrently removed from the page cache.
2985  *
2986  * Returns -EBUSY when trying to split the huge zeropage, if the folio is
2987  * under writeback, if fs-specific folio metadata cannot currently be
2988  * released, or if some unexpected race happened (e.g., anon VMA disappeared,
2989  * truncation).
2990  *
2991  * Returns -EINVAL when trying to split to an order that is incompatible
2992  * with the folio. Splitting to order 0 is compatible with all folios.
2993  */
2994 int split_huge_page_to_list_to_order(struct page *page, struct list_head *list,
2995 				     unsigned int new_order)
2996 {
2997 	struct folio *folio = page_folio(page);
2998 	struct deferred_split *ds_queue = get_deferred_split_queue(folio);
2999 	/* reset xarray order to new order after split */
3000 	XA_STATE_ORDER(xas, &folio->mapping->i_pages, folio->index, new_order);
3001 	struct anon_vma *anon_vma = NULL;
3002 	struct address_space *mapping = NULL;
3003 	bool is_thp = folio_test_pmd_mappable(folio);
3004 	int extra_pins, ret;
3005 	pgoff_t end;
3006 	bool is_hzp;
3007 
3008 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3009 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
3010 
3011 	if (new_order >= folio_order(folio))
3012 		return -EINVAL;
3013 
3014 	if (folio_test_anon(folio)) {
3015 		/* order-1 is not supported for anonymous THP. */
3016 		if (new_order == 1) {
3017 			VM_WARN_ONCE(1, "Cannot split to order-1 folio");
3018 			return -EINVAL;
3019 		}
3020 	} else if (new_order) {
3021 		/* Split shmem folio to non-zero order not supported */
3022 		if (shmem_mapping(folio->mapping)) {
3023 			VM_WARN_ONCE(1,
3024 				"Cannot split shmem folio to non-0 order");
3025 			return -EINVAL;
3026 		}
3027 		/*
3028 		 * No split if the file system does not support large folio.
3029 		 * Note that we might still have THPs in such mappings due to
3030 		 * CONFIG_READ_ONLY_THP_FOR_FS. But in that case, the mapping
3031 		 * does not actually support large folios properly.
3032 		 */
3033 		if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
3034 		    !mapping_large_folio_support(folio->mapping)) {
3035 			VM_WARN_ONCE(1,
3036 				"Cannot split file folio to non-0 order");
3037 			return -EINVAL;
3038 		}
3039 	}
3040 
3041 	/* Only swapping a whole PMD-mapped folio is supported */
3042 	if (folio_test_swapcache(folio) && new_order)
3043 		return -EINVAL;
3044 
3045 	is_hzp = is_huge_zero_folio(folio);
3046 	if (is_hzp) {
3047 		pr_warn_ratelimited("Called split_huge_page for huge zero page\n");
3048 		return -EBUSY;
3049 	}
3050 
3051 	if (folio_test_writeback(folio))
3052 		return -EBUSY;
3053 
3054 	if (folio_test_anon(folio)) {
3055 		/*
3056 		 * The caller does not necessarily hold an mmap_lock that would
3057 		 * prevent the anon_vma disappearing so we first we take a
3058 		 * reference to it and then lock the anon_vma for write. This
3059 		 * is similar to folio_lock_anon_vma_read except the write lock
3060 		 * is taken to serialise against parallel split or collapse
3061 		 * operations.
3062 		 */
3063 		anon_vma = folio_get_anon_vma(folio);
3064 		if (!anon_vma) {
3065 			ret = -EBUSY;
3066 			goto out;
3067 		}
3068 		end = -1;
3069 		mapping = NULL;
3070 		anon_vma_lock_write(anon_vma);
3071 	} else {
3072 		gfp_t gfp;
3073 
3074 		mapping = folio->mapping;
3075 
3076 		/* Truncated ? */
3077 		if (!mapping) {
3078 			ret = -EBUSY;
3079 			goto out;
3080 		}
3081 
3082 		gfp = current_gfp_context(mapping_gfp_mask(mapping) &
3083 							GFP_RECLAIM_MASK);
3084 
3085 		if (!filemap_release_folio(folio, gfp)) {
3086 			ret = -EBUSY;
3087 			goto out;
3088 		}
3089 
3090 		xas_split_alloc(&xas, folio, folio_order(folio), gfp);
3091 		if (xas_error(&xas)) {
3092 			ret = xas_error(&xas);
3093 			goto out;
3094 		}
3095 
3096 		anon_vma = NULL;
3097 		i_mmap_lock_read(mapping);
3098 
3099 		/*
3100 		 *__split_huge_page() may need to trim off pages beyond EOF:
3101 		 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
3102 		 * which cannot be nested inside the page tree lock. So note
3103 		 * end now: i_size itself may be changed at any moment, but
3104 		 * folio lock is good enough to serialize the trimming.
3105 		 */
3106 		end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3107 		if (shmem_mapping(mapping))
3108 			end = shmem_fallocend(mapping->host, end);
3109 	}
3110 
3111 	/*
3112 	 * Racy check if we can split the page, before unmap_folio() will
3113 	 * split PMDs
3114 	 */
3115 	if (!can_split_folio(folio, &extra_pins)) {
3116 		ret = -EAGAIN;
3117 		goto out_unlock;
3118 	}
3119 
3120 	unmap_folio(folio);
3121 
3122 	/* block interrupt reentry in xa_lock and spinlock */
3123 	local_irq_disable();
3124 	if (mapping) {
3125 		/*
3126 		 * Check if the folio is present in page cache.
3127 		 * We assume all tail are present too, if folio is there.
3128 		 */
3129 		xas_lock(&xas);
3130 		xas_reset(&xas);
3131 		if (xas_load(&xas) != folio)
3132 			goto fail;
3133 	}
3134 
3135 	/* Prevent deferred_split_scan() touching ->_refcount */
3136 	spin_lock(&ds_queue->split_queue_lock);
3137 	if (folio_ref_freeze(folio, 1 + extra_pins)) {
3138 		if (folio_order(folio) > 1 &&
3139 		    !list_empty(&folio->_deferred_list)) {
3140 			ds_queue->split_queue_len--;
3141 			/*
3142 			 * Reinitialize page_deferred_list after removing the
3143 			 * page from the split_queue, otherwise a subsequent
3144 			 * split will see list corruption when checking the
3145 			 * page_deferred_list.
3146 			 */
3147 			list_del_init(&folio->_deferred_list);
3148 		}
3149 		spin_unlock(&ds_queue->split_queue_lock);
3150 		if (mapping) {
3151 			int nr = folio_nr_pages(folio);
3152 
3153 			xas_split(&xas, folio, folio_order(folio));
3154 			if (folio_test_pmd_mappable(folio) &&
3155 			    new_order < HPAGE_PMD_ORDER) {
3156 				if (folio_test_swapbacked(folio)) {
3157 					__lruvec_stat_mod_folio(folio,
3158 							NR_SHMEM_THPS, -nr);
3159 				} else {
3160 					__lruvec_stat_mod_folio(folio,
3161 							NR_FILE_THPS, -nr);
3162 					filemap_nr_thps_dec(mapping);
3163 				}
3164 			}
3165 		}
3166 
3167 		__split_huge_page(page, list, end, new_order);
3168 		ret = 0;
3169 	} else {
3170 		spin_unlock(&ds_queue->split_queue_lock);
3171 fail:
3172 		if (mapping)
3173 			xas_unlock(&xas);
3174 		local_irq_enable();
3175 		remap_page(folio, folio_nr_pages(folio));
3176 		ret = -EAGAIN;
3177 	}
3178 
3179 out_unlock:
3180 	if (anon_vma) {
3181 		anon_vma_unlock_write(anon_vma);
3182 		put_anon_vma(anon_vma);
3183 	}
3184 	if (mapping)
3185 		i_mmap_unlock_read(mapping);
3186 out:
3187 	xas_destroy(&xas);
3188 	if (is_thp)
3189 		count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
3190 	return ret;
3191 }
3192 
3193 void folio_undo_large_rmappable(struct folio *folio)
3194 {
3195 	struct deferred_split *ds_queue;
3196 	unsigned long flags;
3197 
3198 	if (folio_order(folio) <= 1)
3199 		return;
3200 
3201 	/*
3202 	 * At this point, there is no one trying to add the folio to
3203 	 * deferred_list. If folio is not in deferred_list, it's safe
3204 	 * to check without acquiring the split_queue_lock.
3205 	 */
3206 	if (data_race(list_empty(&folio->_deferred_list)))
3207 		return;
3208 
3209 	ds_queue = get_deferred_split_queue(folio);
3210 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3211 	if (!list_empty(&folio->_deferred_list)) {
3212 		ds_queue->split_queue_len--;
3213 		list_del_init(&folio->_deferred_list);
3214 	}
3215 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3216 }
3217 
3218 void deferred_split_folio(struct folio *folio)
3219 {
3220 	struct deferred_split *ds_queue = get_deferred_split_queue(folio);
3221 #ifdef CONFIG_MEMCG
3222 	struct mem_cgroup *memcg = folio_memcg(folio);
3223 #endif
3224 	unsigned long flags;
3225 
3226 	/*
3227 	 * Order 1 folios have no space for a deferred list, but we also
3228 	 * won't waste much memory by not adding them to the deferred list.
3229 	 */
3230 	if (folio_order(folio) <= 1)
3231 		return;
3232 
3233 	/*
3234 	 * The try_to_unmap() in page reclaim path might reach here too,
3235 	 * this may cause a race condition to corrupt deferred split queue.
3236 	 * And, if page reclaim is already handling the same folio, it is
3237 	 * unnecessary to handle it again in shrinker.
3238 	 *
3239 	 * Check the swapcache flag to determine if the folio is being
3240 	 * handled by page reclaim since THP swap would add the folio into
3241 	 * swap cache before calling try_to_unmap().
3242 	 */
3243 	if (folio_test_swapcache(folio))
3244 		return;
3245 
3246 	if (!list_empty(&folio->_deferred_list))
3247 		return;
3248 
3249 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3250 	if (list_empty(&folio->_deferred_list)) {
3251 		if (folio_test_pmd_mappable(folio))
3252 			count_vm_event(THP_DEFERRED_SPLIT_PAGE);
3253 		list_add_tail(&folio->_deferred_list, &ds_queue->split_queue);
3254 		ds_queue->split_queue_len++;
3255 #ifdef CONFIG_MEMCG
3256 		if (memcg)
3257 			set_shrinker_bit(memcg, folio_nid(folio),
3258 					 deferred_split_shrinker->id);
3259 #endif
3260 	}
3261 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3262 }
3263 
3264 static unsigned long deferred_split_count(struct shrinker *shrink,
3265 		struct shrink_control *sc)
3266 {
3267 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
3268 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
3269 
3270 #ifdef CONFIG_MEMCG
3271 	if (sc->memcg)
3272 		ds_queue = &sc->memcg->deferred_split_queue;
3273 #endif
3274 	return READ_ONCE(ds_queue->split_queue_len);
3275 }
3276 
3277 static unsigned long deferred_split_scan(struct shrinker *shrink,
3278 		struct shrink_control *sc)
3279 {
3280 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
3281 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
3282 	unsigned long flags;
3283 	LIST_HEAD(list);
3284 	struct folio *folio, *next;
3285 	int split = 0;
3286 
3287 #ifdef CONFIG_MEMCG
3288 	if (sc->memcg)
3289 		ds_queue = &sc->memcg->deferred_split_queue;
3290 #endif
3291 
3292 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3293 	/* Take pin on all head pages to avoid freeing them under us */
3294 	list_for_each_entry_safe(folio, next, &ds_queue->split_queue,
3295 							_deferred_list) {
3296 		if (folio_try_get(folio)) {
3297 			list_move(&folio->_deferred_list, &list);
3298 		} else {
3299 			/* We lost race with folio_put() */
3300 			list_del_init(&folio->_deferred_list);
3301 			ds_queue->split_queue_len--;
3302 		}
3303 		if (!--sc->nr_to_scan)
3304 			break;
3305 	}
3306 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3307 
3308 	list_for_each_entry_safe(folio, next, &list, _deferred_list) {
3309 		if (!folio_trylock(folio))
3310 			goto next;
3311 		/* split_huge_page() removes page from list on success */
3312 		if (!split_folio(folio))
3313 			split++;
3314 		folio_unlock(folio);
3315 next:
3316 		folio_put(folio);
3317 	}
3318 
3319 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3320 	list_splice_tail(&list, &ds_queue->split_queue);
3321 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3322 
3323 	/*
3324 	 * Stop shrinker if we didn't split any page, but the queue is empty.
3325 	 * This can happen if pages were freed under us.
3326 	 */
3327 	if (!split && list_empty(&ds_queue->split_queue))
3328 		return SHRINK_STOP;
3329 	return split;
3330 }
3331 
3332 #ifdef CONFIG_DEBUG_FS
3333 static void split_huge_pages_all(void)
3334 {
3335 	struct zone *zone;
3336 	struct page *page;
3337 	struct folio *folio;
3338 	unsigned long pfn, max_zone_pfn;
3339 	unsigned long total = 0, split = 0;
3340 
3341 	pr_debug("Split all THPs\n");
3342 	for_each_zone(zone) {
3343 		if (!managed_zone(zone))
3344 			continue;
3345 		max_zone_pfn = zone_end_pfn(zone);
3346 		for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
3347 			int nr_pages;
3348 
3349 			page = pfn_to_online_page(pfn);
3350 			if (!page || PageTail(page))
3351 				continue;
3352 			folio = page_folio(page);
3353 			if (!folio_try_get(folio))
3354 				continue;
3355 
3356 			if (unlikely(page_folio(page) != folio))
3357 				goto next;
3358 
3359 			if (zone != folio_zone(folio))
3360 				goto next;
3361 
3362 			if (!folio_test_large(folio)
3363 				|| folio_test_hugetlb(folio)
3364 				|| !folio_test_lru(folio))
3365 				goto next;
3366 
3367 			total++;
3368 			folio_lock(folio);
3369 			nr_pages = folio_nr_pages(folio);
3370 			if (!split_folio(folio))
3371 				split++;
3372 			pfn += nr_pages - 1;
3373 			folio_unlock(folio);
3374 next:
3375 			folio_put(folio);
3376 			cond_resched();
3377 		}
3378 	}
3379 
3380 	pr_debug("%lu of %lu THP split\n", split, total);
3381 }
3382 
3383 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
3384 {
3385 	return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
3386 		    is_vm_hugetlb_page(vma);
3387 }
3388 
3389 static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
3390 				unsigned long vaddr_end, unsigned int new_order)
3391 {
3392 	int ret = 0;
3393 	struct task_struct *task;
3394 	struct mm_struct *mm;
3395 	unsigned long total = 0, split = 0;
3396 	unsigned long addr;
3397 
3398 	vaddr_start &= PAGE_MASK;
3399 	vaddr_end &= PAGE_MASK;
3400 
3401 	/* Find the task_struct from pid */
3402 	rcu_read_lock();
3403 	task = find_task_by_vpid(pid);
3404 	if (!task) {
3405 		rcu_read_unlock();
3406 		ret = -ESRCH;
3407 		goto out;
3408 	}
3409 	get_task_struct(task);
3410 	rcu_read_unlock();
3411 
3412 	/* Find the mm_struct */
3413 	mm = get_task_mm(task);
3414 	put_task_struct(task);
3415 
3416 	if (!mm) {
3417 		ret = -EINVAL;
3418 		goto out;
3419 	}
3420 
3421 	pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
3422 		 pid, vaddr_start, vaddr_end);
3423 
3424 	mmap_read_lock(mm);
3425 	/*
3426 	 * always increase addr by PAGE_SIZE, since we could have a PTE page
3427 	 * table filled with PTE-mapped THPs, each of which is distinct.
3428 	 */
3429 	for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
3430 		struct vm_area_struct *vma = vma_lookup(mm, addr);
3431 		struct page *page;
3432 		struct folio *folio;
3433 
3434 		if (!vma)
3435 			break;
3436 
3437 		/* skip special VMA and hugetlb VMA */
3438 		if (vma_not_suitable_for_thp_split(vma)) {
3439 			addr = vma->vm_end;
3440 			continue;
3441 		}
3442 
3443 		/* FOLL_DUMP to ignore special (like zero) pages */
3444 		page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
3445 
3446 		if (IS_ERR_OR_NULL(page))
3447 			continue;
3448 
3449 		folio = page_folio(page);
3450 		if (!is_transparent_hugepage(folio))
3451 			goto next;
3452 
3453 		if (new_order >= folio_order(folio))
3454 			goto next;
3455 
3456 		total++;
3457 		/*
3458 		 * For folios with private, split_huge_page_to_list_to_order()
3459 		 * will try to drop it before split and then check if the folio
3460 		 * can be split or not. So skip the check here.
3461 		 */
3462 		if (!folio_test_private(folio) &&
3463 		    !can_split_folio(folio, NULL))
3464 			goto next;
3465 
3466 		if (!folio_trylock(folio))
3467 			goto next;
3468 
3469 		if (!split_folio_to_order(folio, new_order))
3470 			split++;
3471 
3472 		folio_unlock(folio);
3473 next:
3474 		folio_put(folio);
3475 		cond_resched();
3476 	}
3477 	mmap_read_unlock(mm);
3478 	mmput(mm);
3479 
3480 	pr_debug("%lu of %lu THP split\n", split, total);
3481 
3482 out:
3483 	return ret;
3484 }
3485 
3486 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
3487 				pgoff_t off_end, unsigned int new_order)
3488 {
3489 	struct filename *file;
3490 	struct file *candidate;
3491 	struct address_space *mapping;
3492 	int ret = -EINVAL;
3493 	pgoff_t index;
3494 	int nr_pages = 1;
3495 	unsigned long total = 0, split = 0;
3496 
3497 	file = getname_kernel(file_path);
3498 	if (IS_ERR(file))
3499 		return ret;
3500 
3501 	candidate = file_open_name(file, O_RDONLY, 0);
3502 	if (IS_ERR(candidate))
3503 		goto out;
3504 
3505 	pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
3506 		 file_path, off_start, off_end);
3507 
3508 	mapping = candidate->f_mapping;
3509 
3510 	for (index = off_start; index < off_end; index += nr_pages) {
3511 		struct folio *folio = filemap_get_folio(mapping, index);
3512 
3513 		nr_pages = 1;
3514 		if (IS_ERR(folio))
3515 			continue;
3516 
3517 		if (!folio_test_large(folio))
3518 			goto next;
3519 
3520 		total++;
3521 		nr_pages = folio_nr_pages(folio);
3522 
3523 		if (new_order >= folio_order(folio))
3524 			goto next;
3525 
3526 		if (!folio_trylock(folio))
3527 			goto next;
3528 
3529 		if (!split_folio_to_order(folio, new_order))
3530 			split++;
3531 
3532 		folio_unlock(folio);
3533 next:
3534 		folio_put(folio);
3535 		cond_resched();
3536 	}
3537 
3538 	filp_close(candidate, NULL);
3539 	ret = 0;
3540 
3541 	pr_debug("%lu of %lu file-backed THP split\n", split, total);
3542 out:
3543 	putname(file);
3544 	return ret;
3545 }
3546 
3547 #define MAX_INPUT_BUF_SZ 255
3548 
3549 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
3550 				size_t count, loff_t *ppops)
3551 {
3552 	static DEFINE_MUTEX(split_debug_mutex);
3553 	ssize_t ret;
3554 	/*
3555 	 * hold pid, start_vaddr, end_vaddr, new_order or
3556 	 * file_path, off_start, off_end, new_order
3557 	 */
3558 	char input_buf[MAX_INPUT_BUF_SZ];
3559 	int pid;
3560 	unsigned long vaddr_start, vaddr_end;
3561 	unsigned int new_order = 0;
3562 
3563 	ret = mutex_lock_interruptible(&split_debug_mutex);
3564 	if (ret)
3565 		return ret;
3566 
3567 	ret = -EFAULT;
3568 
3569 	memset(input_buf, 0, MAX_INPUT_BUF_SZ);
3570 	if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
3571 		goto out;
3572 
3573 	input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
3574 
3575 	if (input_buf[0] == '/') {
3576 		char *tok;
3577 		char *buf = input_buf;
3578 		char file_path[MAX_INPUT_BUF_SZ];
3579 		pgoff_t off_start = 0, off_end = 0;
3580 		size_t input_len = strlen(input_buf);
3581 
3582 		tok = strsep(&buf, ",");
3583 		if (tok) {
3584 			strcpy(file_path, tok);
3585 		} else {
3586 			ret = -EINVAL;
3587 			goto out;
3588 		}
3589 
3590 		ret = sscanf(buf, "0x%lx,0x%lx,%d", &off_start, &off_end, &new_order);
3591 		if (ret != 2 && ret != 3) {
3592 			ret = -EINVAL;
3593 			goto out;
3594 		}
3595 		ret = split_huge_pages_in_file(file_path, off_start, off_end, new_order);
3596 		if (!ret)
3597 			ret = input_len;
3598 
3599 		goto out;
3600 	}
3601 
3602 	ret = sscanf(input_buf, "%d,0x%lx,0x%lx,%d", &pid, &vaddr_start, &vaddr_end, &new_order);
3603 	if (ret == 1 && pid == 1) {
3604 		split_huge_pages_all();
3605 		ret = strlen(input_buf);
3606 		goto out;
3607 	} else if (ret != 3 && ret != 4) {
3608 		ret = -EINVAL;
3609 		goto out;
3610 	}
3611 
3612 	ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end, new_order);
3613 	if (!ret)
3614 		ret = strlen(input_buf);
3615 out:
3616 	mutex_unlock(&split_debug_mutex);
3617 	return ret;
3618 
3619 }
3620 
3621 static const struct file_operations split_huge_pages_fops = {
3622 	.owner	 = THIS_MODULE,
3623 	.write	 = split_huge_pages_write,
3624 	.llseek  = no_llseek,
3625 };
3626 
3627 static int __init split_huge_pages_debugfs(void)
3628 {
3629 	debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3630 			    &split_huge_pages_fops);
3631 	return 0;
3632 }
3633 late_initcall(split_huge_pages_debugfs);
3634 #endif
3635 
3636 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
3637 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
3638 		struct page *page)
3639 {
3640 	struct folio *folio = page_folio(page);
3641 	struct vm_area_struct *vma = pvmw->vma;
3642 	struct mm_struct *mm = vma->vm_mm;
3643 	unsigned long address = pvmw->address;
3644 	bool anon_exclusive;
3645 	pmd_t pmdval;
3646 	swp_entry_t entry;
3647 	pmd_t pmdswp;
3648 
3649 	if (!(pvmw->pmd && !pvmw->pte))
3650 		return 0;
3651 
3652 	flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
3653 	pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
3654 
3655 	/* See folio_try_share_anon_rmap_pmd(): invalidate PMD first. */
3656 	anon_exclusive = folio_test_anon(folio) && PageAnonExclusive(page);
3657 	if (anon_exclusive && folio_try_share_anon_rmap_pmd(folio, page)) {
3658 		set_pmd_at(mm, address, pvmw->pmd, pmdval);
3659 		return -EBUSY;
3660 	}
3661 
3662 	if (pmd_dirty(pmdval))
3663 		folio_mark_dirty(folio);
3664 	if (pmd_write(pmdval))
3665 		entry = make_writable_migration_entry(page_to_pfn(page));
3666 	else if (anon_exclusive)
3667 		entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
3668 	else
3669 		entry = make_readable_migration_entry(page_to_pfn(page));
3670 	if (pmd_young(pmdval))
3671 		entry = make_migration_entry_young(entry);
3672 	if (pmd_dirty(pmdval))
3673 		entry = make_migration_entry_dirty(entry);
3674 	pmdswp = swp_entry_to_pmd(entry);
3675 	if (pmd_soft_dirty(pmdval))
3676 		pmdswp = pmd_swp_mksoft_dirty(pmdswp);
3677 	if (pmd_uffd_wp(pmdval))
3678 		pmdswp = pmd_swp_mkuffd_wp(pmdswp);
3679 	set_pmd_at(mm, address, pvmw->pmd, pmdswp);
3680 	folio_remove_rmap_pmd(folio, page, vma);
3681 	folio_put(folio);
3682 	trace_set_migration_pmd(address, pmd_val(pmdswp));
3683 
3684 	return 0;
3685 }
3686 
3687 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
3688 {
3689 	struct folio *folio = page_folio(new);
3690 	struct vm_area_struct *vma = pvmw->vma;
3691 	struct mm_struct *mm = vma->vm_mm;
3692 	unsigned long address = pvmw->address;
3693 	unsigned long haddr = address & HPAGE_PMD_MASK;
3694 	pmd_t pmde;
3695 	swp_entry_t entry;
3696 
3697 	if (!(pvmw->pmd && !pvmw->pte))
3698 		return;
3699 
3700 	entry = pmd_to_swp_entry(*pvmw->pmd);
3701 	folio_get(folio);
3702 	pmde = mk_huge_pmd(new, READ_ONCE(vma->vm_page_prot));
3703 	if (pmd_swp_soft_dirty(*pvmw->pmd))
3704 		pmde = pmd_mksoft_dirty(pmde);
3705 	if (is_writable_migration_entry(entry))
3706 		pmde = pmd_mkwrite(pmde, vma);
3707 	if (pmd_swp_uffd_wp(*pvmw->pmd))
3708 		pmde = pmd_mkuffd_wp(pmde);
3709 	if (!is_migration_entry_young(entry))
3710 		pmde = pmd_mkold(pmde);
3711 	/* NOTE: this may contain setting soft-dirty on some archs */
3712 	if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
3713 		pmde = pmd_mkdirty(pmde);
3714 
3715 	if (folio_test_anon(folio)) {
3716 		rmap_t rmap_flags = RMAP_NONE;
3717 
3718 		if (!is_readable_migration_entry(entry))
3719 			rmap_flags |= RMAP_EXCLUSIVE;
3720 
3721 		folio_add_anon_rmap_pmd(folio, new, vma, haddr, rmap_flags);
3722 	} else {
3723 		folio_add_file_rmap_pmd(folio, new, vma);
3724 	}
3725 	VM_BUG_ON(pmd_write(pmde) && folio_test_anon(folio) && !PageAnonExclusive(new));
3726 	set_pmd_at(mm, haddr, pvmw->pmd, pmde);
3727 
3728 	/* No need to invalidate - it was non-present before */
3729 	update_mmu_cache_pmd(vma, address, pvmw->pmd);
3730 	trace_remove_migration_pmd(address, pmd_val(pmde));
3731 }
3732 #endif
3733