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