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