xref: /linux/mm/huge_memory.c (revision b8e4b0529d59a3ccd0b25a31d3cfc8b0f3b34068)
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 		goto out;
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 	} else {
1732 		flags |= TNF_MIGRATE_FAIL;
1733 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1734 		if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1735 			spin_unlock(vmf->ptl);
1736 			goto out;
1737 		}
1738 		goto out_map;
1739 	}
1740 
1741 out:
1742 	if (nid != NUMA_NO_NODE)
1743 		task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags);
1744 
1745 	return 0;
1746 
1747 out_map:
1748 	/* Restore the PMD */
1749 	pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1750 	pmd = pmd_mkyoung(pmd);
1751 	if (writable)
1752 		pmd = pmd_mkwrite(pmd, vma);
1753 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
1754 	update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1755 	spin_unlock(vmf->ptl);
1756 	goto out;
1757 }
1758 
1759 /*
1760  * Return true if we do MADV_FREE successfully on entire pmd page.
1761  * Otherwise, return false.
1762  */
1763 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1764 		pmd_t *pmd, unsigned long addr, unsigned long next)
1765 {
1766 	spinlock_t *ptl;
1767 	pmd_t orig_pmd;
1768 	struct folio *folio;
1769 	struct mm_struct *mm = tlb->mm;
1770 	bool ret = false;
1771 
1772 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1773 
1774 	ptl = pmd_trans_huge_lock(pmd, vma);
1775 	if (!ptl)
1776 		goto out_unlocked;
1777 
1778 	orig_pmd = *pmd;
1779 	if (is_huge_zero_pmd(orig_pmd))
1780 		goto out;
1781 
1782 	if (unlikely(!pmd_present(orig_pmd))) {
1783 		VM_BUG_ON(thp_migration_supported() &&
1784 				  !is_pmd_migration_entry(orig_pmd));
1785 		goto out;
1786 	}
1787 
1788 	folio = pmd_folio(orig_pmd);
1789 	/*
1790 	 * If other processes are mapping this folio, we couldn't discard
1791 	 * the folio unless they all do MADV_FREE so let's skip the folio.
1792 	 */
1793 	if (folio_likely_mapped_shared(folio))
1794 		goto out;
1795 
1796 	if (!folio_trylock(folio))
1797 		goto out;
1798 
1799 	/*
1800 	 * If user want to discard part-pages of THP, split it so MADV_FREE
1801 	 * will deactivate only them.
1802 	 */
1803 	if (next - addr != HPAGE_PMD_SIZE) {
1804 		folio_get(folio);
1805 		spin_unlock(ptl);
1806 		split_folio(folio);
1807 		folio_unlock(folio);
1808 		folio_put(folio);
1809 		goto out_unlocked;
1810 	}
1811 
1812 	if (folio_test_dirty(folio))
1813 		folio_clear_dirty(folio);
1814 	folio_unlock(folio);
1815 
1816 	if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1817 		pmdp_invalidate(vma, addr, pmd);
1818 		orig_pmd = pmd_mkold(orig_pmd);
1819 		orig_pmd = pmd_mkclean(orig_pmd);
1820 
1821 		set_pmd_at(mm, addr, pmd, orig_pmd);
1822 		tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1823 	}
1824 
1825 	folio_mark_lazyfree(folio);
1826 	ret = true;
1827 out:
1828 	spin_unlock(ptl);
1829 out_unlocked:
1830 	return ret;
1831 }
1832 
1833 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
1834 {
1835 	pgtable_t pgtable;
1836 
1837 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1838 	pte_free(mm, pgtable);
1839 	mm_dec_nr_ptes(mm);
1840 }
1841 
1842 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1843 		 pmd_t *pmd, unsigned long addr)
1844 {
1845 	pmd_t orig_pmd;
1846 	spinlock_t *ptl;
1847 
1848 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1849 
1850 	ptl = __pmd_trans_huge_lock(pmd, vma);
1851 	if (!ptl)
1852 		return 0;
1853 	/*
1854 	 * For architectures like ppc64 we look at deposited pgtable
1855 	 * when calling pmdp_huge_get_and_clear. So do the
1856 	 * pgtable_trans_huge_withdraw after finishing pmdp related
1857 	 * operations.
1858 	 */
1859 	orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
1860 						tlb->fullmm);
1861 	arch_check_zapped_pmd(vma, orig_pmd);
1862 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1863 	if (vma_is_special_huge(vma)) {
1864 		if (arch_needs_pgtable_deposit())
1865 			zap_deposited_table(tlb->mm, pmd);
1866 		spin_unlock(ptl);
1867 	} else if (is_huge_zero_pmd(orig_pmd)) {
1868 		zap_deposited_table(tlb->mm, pmd);
1869 		spin_unlock(ptl);
1870 	} else {
1871 		struct folio *folio = NULL;
1872 		int flush_needed = 1;
1873 
1874 		if (pmd_present(orig_pmd)) {
1875 			struct page *page = pmd_page(orig_pmd);
1876 
1877 			folio = page_folio(page);
1878 			folio_remove_rmap_pmd(folio, page, vma);
1879 			WARN_ON_ONCE(folio_mapcount(folio) < 0);
1880 			VM_BUG_ON_PAGE(!PageHead(page), page);
1881 		} else if (thp_migration_supported()) {
1882 			swp_entry_t entry;
1883 
1884 			VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
1885 			entry = pmd_to_swp_entry(orig_pmd);
1886 			folio = pfn_swap_entry_folio(entry);
1887 			flush_needed = 0;
1888 		} else
1889 			WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
1890 
1891 		if (folio_test_anon(folio)) {
1892 			zap_deposited_table(tlb->mm, pmd);
1893 			add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1894 		} else {
1895 			if (arch_needs_pgtable_deposit())
1896 				zap_deposited_table(tlb->mm, pmd);
1897 			add_mm_counter(tlb->mm, mm_counter_file(folio),
1898 				       -HPAGE_PMD_NR);
1899 		}
1900 
1901 		spin_unlock(ptl);
1902 		if (flush_needed)
1903 			tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE);
1904 	}
1905 	return 1;
1906 }
1907 
1908 #ifndef pmd_move_must_withdraw
1909 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
1910 					 spinlock_t *old_pmd_ptl,
1911 					 struct vm_area_struct *vma)
1912 {
1913 	/*
1914 	 * With split pmd lock we also need to move preallocated
1915 	 * PTE page table if new_pmd is on different PMD page table.
1916 	 *
1917 	 * We also don't deposit and withdraw tables for file pages.
1918 	 */
1919 	return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
1920 }
1921 #endif
1922 
1923 static pmd_t move_soft_dirty_pmd(pmd_t pmd)
1924 {
1925 #ifdef CONFIG_MEM_SOFT_DIRTY
1926 	if (unlikely(is_pmd_migration_entry(pmd)))
1927 		pmd = pmd_swp_mksoft_dirty(pmd);
1928 	else if (pmd_present(pmd))
1929 		pmd = pmd_mksoft_dirty(pmd);
1930 #endif
1931 	return pmd;
1932 }
1933 
1934 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
1935 		  unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
1936 {
1937 	spinlock_t *old_ptl, *new_ptl;
1938 	pmd_t pmd;
1939 	struct mm_struct *mm = vma->vm_mm;
1940 	bool force_flush = false;
1941 
1942 	/*
1943 	 * The destination pmd shouldn't be established, free_pgtables()
1944 	 * should have released it; but move_page_tables() might have already
1945 	 * inserted a page table, if racing against shmem/file collapse.
1946 	 */
1947 	if (!pmd_none(*new_pmd)) {
1948 		VM_BUG_ON(pmd_trans_huge(*new_pmd));
1949 		return false;
1950 	}
1951 
1952 	/*
1953 	 * We don't have to worry about the ordering of src and dst
1954 	 * ptlocks because exclusive mmap_lock prevents deadlock.
1955 	 */
1956 	old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1957 	if (old_ptl) {
1958 		new_ptl = pmd_lockptr(mm, new_pmd);
1959 		if (new_ptl != old_ptl)
1960 			spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1961 		pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1962 		if (pmd_present(pmd))
1963 			force_flush = true;
1964 		VM_BUG_ON(!pmd_none(*new_pmd));
1965 
1966 		if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
1967 			pgtable_t pgtable;
1968 			pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1969 			pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1970 		}
1971 		pmd = move_soft_dirty_pmd(pmd);
1972 		set_pmd_at(mm, new_addr, new_pmd, pmd);
1973 		if (force_flush)
1974 			flush_pmd_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
1975 		if (new_ptl != old_ptl)
1976 			spin_unlock(new_ptl);
1977 		spin_unlock(old_ptl);
1978 		return true;
1979 	}
1980 	return false;
1981 }
1982 
1983 /*
1984  * Returns
1985  *  - 0 if PMD could not be locked
1986  *  - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
1987  *      or if prot_numa but THP migration is not supported
1988  *  - HPAGE_PMD_NR if protections changed and TLB flush necessary
1989  */
1990 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1991 		    pmd_t *pmd, unsigned long addr, pgprot_t newprot,
1992 		    unsigned long cp_flags)
1993 {
1994 	struct mm_struct *mm = vma->vm_mm;
1995 	spinlock_t *ptl;
1996 	pmd_t oldpmd, entry;
1997 	bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
1998 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
1999 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
2000 	int ret = 1;
2001 
2002 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
2003 
2004 	if (prot_numa && !thp_migration_supported())
2005 		return 1;
2006 
2007 	ptl = __pmd_trans_huge_lock(pmd, vma);
2008 	if (!ptl)
2009 		return 0;
2010 
2011 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
2012 	if (is_swap_pmd(*pmd)) {
2013 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
2014 		struct folio *folio = pfn_swap_entry_folio(entry);
2015 		pmd_t newpmd;
2016 
2017 		VM_BUG_ON(!is_pmd_migration_entry(*pmd));
2018 		if (is_writable_migration_entry(entry)) {
2019 			/*
2020 			 * A protection check is difficult so
2021 			 * just be safe and disable write
2022 			 */
2023 			if (folio_test_anon(folio))
2024 				entry = make_readable_exclusive_migration_entry(swp_offset(entry));
2025 			else
2026 				entry = make_readable_migration_entry(swp_offset(entry));
2027 			newpmd = swp_entry_to_pmd(entry);
2028 			if (pmd_swp_soft_dirty(*pmd))
2029 				newpmd = pmd_swp_mksoft_dirty(newpmd);
2030 		} else {
2031 			newpmd = *pmd;
2032 		}
2033 
2034 		if (uffd_wp)
2035 			newpmd = pmd_swp_mkuffd_wp(newpmd);
2036 		else if (uffd_wp_resolve)
2037 			newpmd = pmd_swp_clear_uffd_wp(newpmd);
2038 		if (!pmd_same(*pmd, newpmd))
2039 			set_pmd_at(mm, addr, pmd, newpmd);
2040 		goto unlock;
2041 	}
2042 #endif
2043 
2044 	if (prot_numa) {
2045 		struct folio *folio;
2046 		bool toptier;
2047 		/*
2048 		 * Avoid trapping faults against the zero page. The read-only
2049 		 * data is likely to be read-cached on the local CPU and
2050 		 * local/remote hits to the zero page are not interesting.
2051 		 */
2052 		if (is_huge_zero_pmd(*pmd))
2053 			goto unlock;
2054 
2055 		if (pmd_protnone(*pmd))
2056 			goto unlock;
2057 
2058 		folio = pmd_folio(*pmd);
2059 		toptier = node_is_toptier(folio_nid(folio));
2060 		/*
2061 		 * Skip scanning top tier node if normal numa
2062 		 * balancing is disabled
2063 		 */
2064 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
2065 		    toptier)
2066 			goto unlock;
2067 
2068 		if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
2069 		    !toptier)
2070 			folio_xchg_access_time(folio,
2071 					       jiffies_to_msecs(jiffies));
2072 	}
2073 	/*
2074 	 * In case prot_numa, we are under mmap_read_lock(mm). It's critical
2075 	 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
2076 	 * which is also under mmap_read_lock(mm):
2077 	 *
2078 	 *	CPU0:				CPU1:
2079 	 *				change_huge_pmd(prot_numa=1)
2080 	 *				 pmdp_huge_get_and_clear_notify()
2081 	 * madvise_dontneed()
2082 	 *  zap_pmd_range()
2083 	 *   pmd_trans_huge(*pmd) == 0 (without ptl)
2084 	 *   // skip the pmd
2085 	 *				 set_pmd_at();
2086 	 *				 // pmd is re-established
2087 	 *
2088 	 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
2089 	 * which may break userspace.
2090 	 *
2091 	 * pmdp_invalidate_ad() is required to make sure we don't miss
2092 	 * dirty/young flags set by hardware.
2093 	 */
2094 	oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
2095 
2096 	entry = pmd_modify(oldpmd, newprot);
2097 	if (uffd_wp)
2098 		entry = pmd_mkuffd_wp(entry);
2099 	else if (uffd_wp_resolve)
2100 		/*
2101 		 * Leave the write bit to be handled by PF interrupt
2102 		 * handler, then things like COW could be properly
2103 		 * handled.
2104 		 */
2105 		entry = pmd_clear_uffd_wp(entry);
2106 
2107 	/* See change_pte_range(). */
2108 	if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) && !pmd_write(entry) &&
2109 	    can_change_pmd_writable(vma, addr, entry))
2110 		entry = pmd_mkwrite(entry, vma);
2111 
2112 	ret = HPAGE_PMD_NR;
2113 	set_pmd_at(mm, addr, pmd, entry);
2114 
2115 	if (huge_pmd_needs_flush(oldpmd, entry))
2116 		tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
2117 unlock:
2118 	spin_unlock(ptl);
2119 	return ret;
2120 }
2121 
2122 #ifdef CONFIG_USERFAULTFD
2123 /*
2124  * The PT lock for src_pmd and dst_vma/src_vma (for reading) are locked by
2125  * the caller, but it must return after releasing the page_table_lock.
2126  * Just move the page from src_pmd to dst_pmd if possible.
2127  * Return zero if succeeded in moving the page, -EAGAIN if it needs to be
2128  * repeated by the caller, or other errors in case of failure.
2129  */
2130 int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pmd_t dst_pmdval,
2131 			struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
2132 			unsigned long dst_addr, unsigned long src_addr)
2133 {
2134 	pmd_t _dst_pmd, src_pmdval;
2135 	struct page *src_page;
2136 	struct folio *src_folio;
2137 	struct anon_vma *src_anon_vma;
2138 	spinlock_t *src_ptl, *dst_ptl;
2139 	pgtable_t src_pgtable;
2140 	struct mmu_notifier_range range;
2141 	int err = 0;
2142 
2143 	src_pmdval = *src_pmd;
2144 	src_ptl = pmd_lockptr(mm, src_pmd);
2145 
2146 	lockdep_assert_held(src_ptl);
2147 	vma_assert_locked(src_vma);
2148 	vma_assert_locked(dst_vma);
2149 
2150 	/* Sanity checks before the operation */
2151 	if (WARN_ON_ONCE(!pmd_none(dst_pmdval)) || WARN_ON_ONCE(src_addr & ~HPAGE_PMD_MASK) ||
2152 	    WARN_ON_ONCE(dst_addr & ~HPAGE_PMD_MASK)) {
2153 		spin_unlock(src_ptl);
2154 		return -EINVAL;
2155 	}
2156 
2157 	if (!pmd_trans_huge(src_pmdval)) {
2158 		spin_unlock(src_ptl);
2159 		if (is_pmd_migration_entry(src_pmdval)) {
2160 			pmd_migration_entry_wait(mm, &src_pmdval);
2161 			return -EAGAIN;
2162 		}
2163 		return -ENOENT;
2164 	}
2165 
2166 	src_page = pmd_page(src_pmdval);
2167 
2168 	if (!is_huge_zero_pmd(src_pmdval)) {
2169 		if (unlikely(!PageAnonExclusive(src_page))) {
2170 			spin_unlock(src_ptl);
2171 			return -EBUSY;
2172 		}
2173 
2174 		src_folio = page_folio(src_page);
2175 		folio_get(src_folio);
2176 	} else
2177 		src_folio = NULL;
2178 
2179 	spin_unlock(src_ptl);
2180 
2181 	flush_cache_range(src_vma, src_addr, src_addr + HPAGE_PMD_SIZE);
2182 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, src_addr,
2183 				src_addr + HPAGE_PMD_SIZE);
2184 	mmu_notifier_invalidate_range_start(&range);
2185 
2186 	if (src_folio) {
2187 		folio_lock(src_folio);
2188 
2189 		/*
2190 		 * split_huge_page walks the anon_vma chain without the page
2191 		 * lock. Serialize against it with the anon_vma lock, the page
2192 		 * lock is not enough.
2193 		 */
2194 		src_anon_vma = folio_get_anon_vma(src_folio);
2195 		if (!src_anon_vma) {
2196 			err = -EAGAIN;
2197 			goto unlock_folio;
2198 		}
2199 		anon_vma_lock_write(src_anon_vma);
2200 	} else
2201 		src_anon_vma = NULL;
2202 
2203 	dst_ptl = pmd_lockptr(mm, dst_pmd);
2204 	double_pt_lock(src_ptl, dst_ptl);
2205 	if (unlikely(!pmd_same(*src_pmd, src_pmdval) ||
2206 		     !pmd_same(*dst_pmd, dst_pmdval))) {
2207 		err = -EAGAIN;
2208 		goto unlock_ptls;
2209 	}
2210 	if (src_folio) {
2211 		if (folio_maybe_dma_pinned(src_folio) ||
2212 		    !PageAnonExclusive(&src_folio->page)) {
2213 			err = -EBUSY;
2214 			goto unlock_ptls;
2215 		}
2216 
2217 		if (WARN_ON_ONCE(!folio_test_head(src_folio)) ||
2218 		    WARN_ON_ONCE(!folio_test_anon(src_folio))) {
2219 			err = -EBUSY;
2220 			goto unlock_ptls;
2221 		}
2222 
2223 		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
2224 		/* Folio got pinned from under us. Put it back and fail the move. */
2225 		if (folio_maybe_dma_pinned(src_folio)) {
2226 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);
2227 			err = -EBUSY;
2228 			goto unlock_ptls;
2229 		}
2230 
2231 		folio_move_anon_rmap(src_folio, dst_vma);
2232 		src_folio->index = linear_page_index(dst_vma, dst_addr);
2233 
2234 		_dst_pmd = mk_huge_pmd(&src_folio->page, dst_vma->vm_page_prot);
2235 		/* Follow mremap() behavior and treat the entry dirty after the move */
2236 		_dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma);
2237 	} else {
2238 		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
2239 		_dst_pmd = mk_huge_pmd(src_page, dst_vma->vm_page_prot);
2240 	}
2241 	set_pmd_at(mm, dst_addr, dst_pmd, _dst_pmd);
2242 
2243 	src_pgtable = pgtable_trans_huge_withdraw(mm, src_pmd);
2244 	pgtable_trans_huge_deposit(mm, dst_pmd, src_pgtable);
2245 unlock_ptls:
2246 	double_pt_unlock(src_ptl, dst_ptl);
2247 	if (src_anon_vma) {
2248 		anon_vma_unlock_write(src_anon_vma);
2249 		put_anon_vma(src_anon_vma);
2250 	}
2251 unlock_folio:
2252 	/* unblock rmap walks */
2253 	if (src_folio)
2254 		folio_unlock(src_folio);
2255 	mmu_notifier_invalidate_range_end(&range);
2256 	if (src_folio)
2257 		folio_put(src_folio);
2258 	return err;
2259 }
2260 #endif /* CONFIG_USERFAULTFD */
2261 
2262 /*
2263  * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
2264  *
2265  * Note that if it returns page table lock pointer, this routine returns without
2266  * unlocking page table lock. So callers must unlock it.
2267  */
2268 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
2269 {
2270 	spinlock_t *ptl;
2271 	ptl = pmd_lock(vma->vm_mm, pmd);
2272 	if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
2273 			pmd_devmap(*pmd)))
2274 		return ptl;
2275 	spin_unlock(ptl);
2276 	return NULL;
2277 }
2278 
2279 /*
2280  * Returns page table lock pointer if a given pud maps a thp, NULL otherwise.
2281  *
2282  * Note that if it returns page table lock pointer, this routine returns without
2283  * unlocking page table lock. So callers must unlock it.
2284  */
2285 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
2286 {
2287 	spinlock_t *ptl;
2288 
2289 	ptl = pud_lock(vma->vm_mm, pud);
2290 	if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
2291 		return ptl;
2292 	spin_unlock(ptl);
2293 	return NULL;
2294 }
2295 
2296 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
2297 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
2298 		 pud_t *pud, unsigned long addr)
2299 {
2300 	spinlock_t *ptl;
2301 
2302 	ptl = __pud_trans_huge_lock(pud, vma);
2303 	if (!ptl)
2304 		return 0;
2305 
2306 	pudp_huge_get_and_clear_full(vma, addr, pud, tlb->fullmm);
2307 	tlb_remove_pud_tlb_entry(tlb, pud, addr);
2308 	if (vma_is_special_huge(vma)) {
2309 		spin_unlock(ptl);
2310 		/* No zero page support yet */
2311 	} else {
2312 		/* No support for anonymous PUD pages yet */
2313 		BUG();
2314 	}
2315 	return 1;
2316 }
2317 
2318 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
2319 		unsigned long haddr)
2320 {
2321 	VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
2322 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2323 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
2324 	VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
2325 
2326 	count_vm_event(THP_SPLIT_PUD);
2327 
2328 	pudp_huge_clear_flush(vma, haddr, pud);
2329 }
2330 
2331 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
2332 		unsigned long address)
2333 {
2334 	spinlock_t *ptl;
2335 	struct mmu_notifier_range range;
2336 
2337 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2338 				address & HPAGE_PUD_MASK,
2339 				(address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
2340 	mmu_notifier_invalidate_range_start(&range);
2341 	ptl = pud_lock(vma->vm_mm, pud);
2342 	if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
2343 		goto out;
2344 	__split_huge_pud_locked(vma, pud, range.start);
2345 
2346 out:
2347 	spin_unlock(ptl);
2348 	mmu_notifier_invalidate_range_end(&range);
2349 }
2350 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
2351 
2352 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2353 		unsigned long haddr, pmd_t *pmd)
2354 {
2355 	struct mm_struct *mm = vma->vm_mm;
2356 	pgtable_t pgtable;
2357 	pmd_t _pmd, old_pmd;
2358 	unsigned long addr;
2359 	pte_t *pte;
2360 	int i;
2361 
2362 	/*
2363 	 * Leave pmd empty until pte is filled note that it is fine to delay
2364 	 * notification until mmu_notifier_invalidate_range_end() as we are
2365 	 * replacing a zero pmd write protected page with a zero pte write
2366 	 * protected page.
2367 	 *
2368 	 * See Documentation/mm/mmu_notifier.rst
2369 	 */
2370 	old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
2371 
2372 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2373 	pmd_populate(mm, &_pmd, pgtable);
2374 
2375 	pte = pte_offset_map(&_pmd, haddr);
2376 	VM_BUG_ON(!pte);
2377 	for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2378 		pte_t entry;
2379 
2380 		entry = pfn_pte(my_zero_pfn(addr), vma->vm_page_prot);
2381 		entry = pte_mkspecial(entry);
2382 		if (pmd_uffd_wp(old_pmd))
2383 			entry = pte_mkuffd_wp(entry);
2384 		VM_BUG_ON(!pte_none(ptep_get(pte)));
2385 		set_pte_at(mm, addr, pte, entry);
2386 		pte++;
2387 	}
2388 	pte_unmap(pte - 1);
2389 	smp_wmb(); /* make pte visible before pmd */
2390 	pmd_populate(mm, pmd, pgtable);
2391 }
2392 
2393 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
2394 		unsigned long haddr, bool freeze)
2395 {
2396 	struct mm_struct *mm = vma->vm_mm;
2397 	struct folio *folio;
2398 	struct page *page;
2399 	pgtable_t pgtable;
2400 	pmd_t old_pmd, _pmd;
2401 	bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
2402 	bool anon_exclusive = false, dirty = false;
2403 	unsigned long addr;
2404 	pte_t *pte;
2405 	int i;
2406 
2407 	VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2408 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2409 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
2410 	VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
2411 				&& !pmd_devmap(*pmd));
2412 
2413 	count_vm_event(THP_SPLIT_PMD);
2414 
2415 	if (!vma_is_anonymous(vma)) {
2416 		old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd);
2417 		/*
2418 		 * We are going to unmap this huge page. So
2419 		 * just go ahead and zap it
2420 		 */
2421 		if (arch_needs_pgtable_deposit())
2422 			zap_deposited_table(mm, pmd);
2423 		if (vma_is_special_huge(vma))
2424 			return;
2425 		if (unlikely(is_pmd_migration_entry(old_pmd))) {
2426 			swp_entry_t entry;
2427 
2428 			entry = pmd_to_swp_entry(old_pmd);
2429 			folio = pfn_swap_entry_folio(entry);
2430 		} else {
2431 			page = pmd_page(old_pmd);
2432 			folio = page_folio(page);
2433 			if (!folio_test_dirty(folio) && pmd_dirty(old_pmd))
2434 				folio_mark_dirty(folio);
2435 			if (!folio_test_referenced(folio) && pmd_young(old_pmd))
2436 				folio_set_referenced(folio);
2437 			folio_remove_rmap_pmd(folio, page, vma);
2438 			folio_put(folio);
2439 		}
2440 		add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
2441 		return;
2442 	}
2443 
2444 	if (is_huge_zero_pmd(*pmd)) {
2445 		/*
2446 		 * FIXME: Do we want to invalidate secondary mmu by calling
2447 		 * mmu_notifier_arch_invalidate_secondary_tlbs() see comments below
2448 		 * inside __split_huge_pmd() ?
2449 		 *
2450 		 * We are going from a zero huge page write protected to zero
2451 		 * small page also write protected so it does not seems useful
2452 		 * to invalidate secondary mmu at this time.
2453 		 */
2454 		return __split_huge_zero_page_pmd(vma, haddr, pmd);
2455 	}
2456 
2457 	pmd_migration = is_pmd_migration_entry(*pmd);
2458 	if (unlikely(pmd_migration)) {
2459 		swp_entry_t entry;
2460 
2461 		old_pmd = *pmd;
2462 		entry = pmd_to_swp_entry(old_pmd);
2463 		page = pfn_swap_entry_to_page(entry);
2464 		write = is_writable_migration_entry(entry);
2465 		if (PageAnon(page))
2466 			anon_exclusive = is_readable_exclusive_migration_entry(entry);
2467 		young = is_migration_entry_young(entry);
2468 		dirty = is_migration_entry_dirty(entry);
2469 		soft_dirty = pmd_swp_soft_dirty(old_pmd);
2470 		uffd_wp = pmd_swp_uffd_wp(old_pmd);
2471 	} else {
2472 		/*
2473 		 * Up to this point the pmd is present and huge and userland has
2474 		 * the whole access to the hugepage during the split (which
2475 		 * happens in place). If we overwrite the pmd with the not-huge
2476 		 * version pointing to the pte here (which of course we could if
2477 		 * all CPUs were bug free), userland could trigger a small page
2478 		 * size TLB miss on the small sized TLB while the hugepage TLB
2479 		 * entry is still established in the huge TLB. Some CPU doesn't
2480 		 * like that. See
2481 		 * http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2482 		 * 383 on page 105. Intel should be safe but is also warns that
2483 		 * it's only safe if the permission and cache attributes of the
2484 		 * two entries loaded in the two TLB is identical (which should
2485 		 * be the case here). But it is generally safer to never allow
2486 		 * small and huge TLB entries for the same virtual address to be
2487 		 * loaded simultaneously. So instead of doing "pmd_populate();
2488 		 * flush_pmd_tlb_range();" we first mark the current pmd
2489 		 * notpresent (atomically because here the pmd_trans_huge must
2490 		 * remain set at all times on the pmd until the split is
2491 		 * complete for this pmd), then we flush the SMP TLB and finally
2492 		 * we write the non-huge version of the pmd entry with
2493 		 * pmd_populate.
2494 		 */
2495 		old_pmd = pmdp_invalidate(vma, haddr, pmd);
2496 		page = pmd_page(old_pmd);
2497 		folio = page_folio(page);
2498 		if (pmd_dirty(old_pmd)) {
2499 			dirty = true;
2500 			folio_set_dirty(folio);
2501 		}
2502 		write = pmd_write(old_pmd);
2503 		young = pmd_young(old_pmd);
2504 		soft_dirty = pmd_soft_dirty(old_pmd);
2505 		uffd_wp = pmd_uffd_wp(old_pmd);
2506 
2507 		VM_WARN_ON_FOLIO(!folio_ref_count(folio), folio);
2508 		VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
2509 
2510 		/*
2511 		 * Without "freeze", we'll simply split the PMD, propagating the
2512 		 * PageAnonExclusive() flag for each PTE by setting it for
2513 		 * each subpage -- no need to (temporarily) clear.
2514 		 *
2515 		 * With "freeze" we want to replace mapped pages by
2516 		 * migration entries right away. This is only possible if we
2517 		 * managed to clear PageAnonExclusive() -- see
2518 		 * set_pmd_migration_entry().
2519 		 *
2520 		 * In case we cannot clear PageAnonExclusive(), split the PMD
2521 		 * only and let try_to_migrate_one() fail later.
2522 		 *
2523 		 * See folio_try_share_anon_rmap_pmd(): invalidate PMD first.
2524 		 */
2525 		anon_exclusive = PageAnonExclusive(page);
2526 		if (freeze && anon_exclusive &&
2527 		    folio_try_share_anon_rmap_pmd(folio, page))
2528 			freeze = false;
2529 		if (!freeze) {
2530 			rmap_t rmap_flags = RMAP_NONE;
2531 
2532 			folio_ref_add(folio, HPAGE_PMD_NR - 1);
2533 			if (anon_exclusive)
2534 				rmap_flags |= RMAP_EXCLUSIVE;
2535 			folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR,
2536 						 vma, haddr, rmap_flags);
2537 		}
2538 	}
2539 
2540 	/*
2541 	 * Withdraw the table only after we mark the pmd entry invalid.
2542 	 * This's critical for some architectures (Power).
2543 	 */
2544 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2545 	pmd_populate(mm, &_pmd, pgtable);
2546 
2547 	pte = pte_offset_map(&_pmd, haddr);
2548 	VM_BUG_ON(!pte);
2549 
2550 	/*
2551 	 * Note that NUMA hinting access restrictions are not transferred to
2552 	 * avoid any possibility of altering permissions across VMAs.
2553 	 */
2554 	if (freeze || pmd_migration) {
2555 		for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2556 			pte_t entry;
2557 			swp_entry_t swp_entry;
2558 
2559 			if (write)
2560 				swp_entry = make_writable_migration_entry(
2561 							page_to_pfn(page + i));
2562 			else if (anon_exclusive)
2563 				swp_entry = make_readable_exclusive_migration_entry(
2564 							page_to_pfn(page + i));
2565 			else
2566 				swp_entry = make_readable_migration_entry(
2567 							page_to_pfn(page + i));
2568 			if (young)
2569 				swp_entry = make_migration_entry_young(swp_entry);
2570 			if (dirty)
2571 				swp_entry = make_migration_entry_dirty(swp_entry);
2572 			entry = swp_entry_to_pte(swp_entry);
2573 			if (soft_dirty)
2574 				entry = pte_swp_mksoft_dirty(entry);
2575 			if (uffd_wp)
2576 				entry = pte_swp_mkuffd_wp(entry);
2577 
2578 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
2579 			set_pte_at(mm, addr, pte + i, entry);
2580 		}
2581 	} else {
2582 		pte_t entry;
2583 
2584 		entry = mk_pte(page, READ_ONCE(vma->vm_page_prot));
2585 		if (write)
2586 			entry = pte_mkwrite(entry, vma);
2587 		if (!young)
2588 			entry = pte_mkold(entry);
2589 		/* NOTE: this may set soft-dirty too on some archs */
2590 		if (dirty)
2591 			entry = pte_mkdirty(entry);
2592 		if (soft_dirty)
2593 			entry = pte_mksoft_dirty(entry);
2594 		if (uffd_wp)
2595 			entry = pte_mkuffd_wp(entry);
2596 
2597 		for (i = 0; i < HPAGE_PMD_NR; i++)
2598 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
2599 
2600 		set_ptes(mm, haddr, pte, entry, HPAGE_PMD_NR);
2601 	}
2602 	pte_unmap(pte);
2603 
2604 	if (!pmd_migration)
2605 		folio_remove_rmap_pmd(folio, page, vma);
2606 	if (freeze)
2607 		put_page(page);
2608 
2609 	smp_wmb(); /* make pte visible before pmd */
2610 	pmd_populate(mm, pmd, pgtable);
2611 }
2612 
2613 void split_huge_pmd_locked(struct vm_area_struct *vma, unsigned long address,
2614 			   pmd_t *pmd, bool freeze, struct folio *folio)
2615 {
2616 	VM_WARN_ON_ONCE(folio && !folio_test_pmd_mappable(folio));
2617 	VM_WARN_ON_ONCE(!IS_ALIGNED(address, HPAGE_PMD_SIZE));
2618 	VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
2619 	VM_BUG_ON(freeze && !folio);
2620 
2621 	/*
2622 	 * When the caller requests to set up a migration entry, we
2623 	 * require a folio to check the PMD against. Otherwise, there
2624 	 * is a risk of replacing the wrong folio.
2625 	 */
2626 	if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
2627 	    is_pmd_migration_entry(*pmd)) {
2628 		if (folio && folio != pmd_folio(*pmd))
2629 			return;
2630 		__split_huge_pmd_locked(vma, pmd, address, freeze);
2631 	}
2632 }
2633 
2634 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2635 		unsigned long address, bool freeze, struct folio *folio)
2636 {
2637 	spinlock_t *ptl;
2638 	struct mmu_notifier_range range;
2639 
2640 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2641 				address & HPAGE_PMD_MASK,
2642 				(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2643 	mmu_notifier_invalidate_range_start(&range);
2644 	ptl = pmd_lock(vma->vm_mm, pmd);
2645 	split_huge_pmd_locked(vma, range.start, pmd, freeze, folio);
2646 	spin_unlock(ptl);
2647 	mmu_notifier_invalidate_range_end(&range);
2648 }
2649 
2650 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2651 		bool freeze, struct folio *folio)
2652 {
2653 	pmd_t *pmd = mm_find_pmd(vma->vm_mm, address);
2654 
2655 	if (!pmd)
2656 		return;
2657 
2658 	__split_huge_pmd(vma, pmd, address, freeze, folio);
2659 }
2660 
2661 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2662 {
2663 	/*
2664 	 * If the new address isn't hpage aligned and it could previously
2665 	 * contain an hugepage: check if we need to split an huge pmd.
2666 	 */
2667 	if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2668 	    range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2669 			 ALIGN(address, HPAGE_PMD_SIZE)))
2670 		split_huge_pmd_address(vma, address, false, NULL);
2671 }
2672 
2673 void vma_adjust_trans_huge(struct vm_area_struct *vma,
2674 			     unsigned long start,
2675 			     unsigned long end,
2676 			     long adjust_next)
2677 {
2678 	/* Check if we need to split start first. */
2679 	split_huge_pmd_if_needed(vma, start);
2680 
2681 	/* Check if we need to split end next. */
2682 	split_huge_pmd_if_needed(vma, end);
2683 
2684 	/*
2685 	 * If we're also updating the next vma vm_start,
2686 	 * check if we need to split it.
2687 	 */
2688 	if (adjust_next > 0) {
2689 		struct vm_area_struct *next = find_vma(vma->vm_mm, vma->vm_end);
2690 		unsigned long nstart = next->vm_start;
2691 		nstart += adjust_next;
2692 		split_huge_pmd_if_needed(next, nstart);
2693 	}
2694 }
2695 
2696 static void unmap_folio(struct folio *folio)
2697 {
2698 	enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SYNC |
2699 		TTU_BATCH_FLUSH;
2700 
2701 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
2702 
2703 	if (folio_test_pmd_mappable(folio))
2704 		ttu_flags |= TTU_SPLIT_HUGE_PMD;
2705 
2706 	/*
2707 	 * Anon pages need migration entries to preserve them, but file
2708 	 * pages can simply be left unmapped, then faulted back on demand.
2709 	 * If that is ever changed (perhaps for mlock), update remap_page().
2710 	 */
2711 	if (folio_test_anon(folio))
2712 		try_to_migrate(folio, ttu_flags);
2713 	else
2714 		try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
2715 
2716 	try_to_unmap_flush();
2717 }
2718 
2719 static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
2720 					    unsigned long addr, pmd_t *pmdp,
2721 					    struct folio *folio)
2722 {
2723 	struct mm_struct *mm = vma->vm_mm;
2724 	int ref_count, map_count;
2725 	pmd_t orig_pmd = *pmdp;
2726 
2727 	if (folio_test_dirty(folio) || pmd_dirty(orig_pmd))
2728 		return false;
2729 
2730 	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
2731 
2732 	/*
2733 	 * Syncing against concurrent GUP-fast:
2734 	 * - clear PMD; barrier; read refcount
2735 	 * - inc refcount; barrier; read PMD
2736 	 */
2737 	smp_mb();
2738 
2739 	ref_count = folio_ref_count(folio);
2740 	map_count = folio_mapcount(folio);
2741 
2742 	/*
2743 	 * Order reads for folio refcount and dirty flag
2744 	 * (see comments in __remove_mapping()).
2745 	 */
2746 	smp_rmb();
2747 
2748 	/*
2749 	 * If the folio or its PMD is redirtied at this point, or if there
2750 	 * are unexpected references, we will give up to discard this folio
2751 	 * and remap it.
2752 	 *
2753 	 * The only folio refs must be one from isolation plus the rmap(s).
2754 	 */
2755 	if (folio_test_dirty(folio) || pmd_dirty(orig_pmd) ||
2756 	    ref_count != map_count + 1) {
2757 		set_pmd_at(mm, addr, pmdp, orig_pmd);
2758 		return false;
2759 	}
2760 
2761 	folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma);
2762 	zap_deposited_table(mm, pmdp);
2763 	add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR);
2764 	if (vma->vm_flags & VM_LOCKED)
2765 		mlock_drain_local();
2766 	folio_put(folio);
2767 
2768 	return true;
2769 }
2770 
2771 bool unmap_huge_pmd_locked(struct vm_area_struct *vma, unsigned long addr,
2772 			   pmd_t *pmdp, struct folio *folio)
2773 {
2774 	VM_WARN_ON_FOLIO(!folio_test_pmd_mappable(folio), folio);
2775 	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
2776 	VM_WARN_ON_ONCE(!IS_ALIGNED(addr, HPAGE_PMD_SIZE));
2777 
2778 	if (folio_test_anon(folio) && !folio_test_swapbacked(folio))
2779 		return __discard_anon_folio_pmd_locked(vma, addr, pmdp, folio);
2780 
2781 	return false;
2782 }
2783 
2784 static void remap_page(struct folio *folio, unsigned long nr)
2785 {
2786 	int i = 0;
2787 
2788 	/* If unmap_folio() uses try_to_migrate() on file, remove this check */
2789 	if (!folio_test_anon(folio))
2790 		return;
2791 	for (;;) {
2792 		remove_migration_ptes(folio, folio, true);
2793 		i += folio_nr_pages(folio);
2794 		if (i >= nr)
2795 			break;
2796 		folio = folio_next(folio);
2797 	}
2798 }
2799 
2800 static void lru_add_page_tail(struct page *head, struct page *tail,
2801 		struct lruvec *lruvec, struct list_head *list)
2802 {
2803 	VM_BUG_ON_PAGE(!PageHead(head), head);
2804 	VM_BUG_ON_PAGE(PageLRU(tail), head);
2805 	lockdep_assert_held(&lruvec->lru_lock);
2806 
2807 	if (list) {
2808 		/* page reclaim is reclaiming a huge page */
2809 		VM_WARN_ON(PageLRU(head));
2810 		get_page(tail);
2811 		list_add_tail(&tail->lru, list);
2812 	} else {
2813 		/* head is still on lru (and we have it frozen) */
2814 		VM_WARN_ON(!PageLRU(head));
2815 		if (PageUnevictable(tail))
2816 			tail->mlock_count = 0;
2817 		else
2818 			list_add_tail(&tail->lru, &head->lru);
2819 		SetPageLRU(tail);
2820 	}
2821 }
2822 
2823 static void __split_huge_page_tail(struct folio *folio, int tail,
2824 		struct lruvec *lruvec, struct list_head *list,
2825 		unsigned int new_order)
2826 {
2827 	struct page *head = &folio->page;
2828 	struct page *page_tail = head + tail;
2829 	/*
2830 	 * Careful: new_folio is not a "real" folio before we cleared PageTail.
2831 	 * Don't pass it around before clear_compound_head().
2832 	 */
2833 	struct folio *new_folio = (struct folio *)page_tail;
2834 
2835 	VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
2836 
2837 	/*
2838 	 * Clone page flags before unfreezing refcount.
2839 	 *
2840 	 * After successful get_page_unless_zero() might follow flags change,
2841 	 * for example lock_page() which set PG_waiters.
2842 	 *
2843 	 * Note that for mapped sub-pages of an anonymous THP,
2844 	 * PG_anon_exclusive has been cleared in unmap_folio() and is stored in
2845 	 * the migration entry instead from where remap_page() will restore it.
2846 	 * We can still have PG_anon_exclusive set on effectively unmapped and
2847 	 * unreferenced sub-pages of an anonymous THP: we can simply drop
2848 	 * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
2849 	 */
2850 	page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
2851 	page_tail->flags |= (head->flags &
2852 			((1L << PG_referenced) |
2853 			 (1L << PG_swapbacked) |
2854 			 (1L << PG_swapcache) |
2855 			 (1L << PG_mlocked) |
2856 			 (1L << PG_uptodate) |
2857 			 (1L << PG_active) |
2858 			 (1L << PG_workingset) |
2859 			 (1L << PG_locked) |
2860 			 (1L << PG_unevictable) |
2861 #ifdef CONFIG_ARCH_USES_PG_ARCH_X
2862 			 (1L << PG_arch_2) |
2863 			 (1L << PG_arch_3) |
2864 #endif
2865 			 (1L << PG_dirty) |
2866 			 LRU_GEN_MASK | LRU_REFS_MASK));
2867 
2868 	/* ->mapping in first and second tail page is replaced by other uses */
2869 	VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
2870 			page_tail);
2871 	page_tail->mapping = head->mapping;
2872 	page_tail->index = head->index + tail;
2873 
2874 	/*
2875 	 * page->private should not be set in tail pages. Fix up and warn once
2876 	 * if private is unexpectedly set.
2877 	 */
2878 	if (unlikely(page_tail->private)) {
2879 		VM_WARN_ON_ONCE_PAGE(true, page_tail);
2880 		page_tail->private = 0;
2881 	}
2882 	if (folio_test_swapcache(folio))
2883 		new_folio->swap.val = folio->swap.val + tail;
2884 
2885 	/* Page flags must be visible before we make the page non-compound. */
2886 	smp_wmb();
2887 
2888 	/*
2889 	 * Clear PageTail before unfreezing page refcount.
2890 	 *
2891 	 * After successful get_page_unless_zero() might follow put_page()
2892 	 * which needs correct compound_head().
2893 	 */
2894 	clear_compound_head(page_tail);
2895 	if (new_order) {
2896 		prep_compound_page(page_tail, new_order);
2897 		folio_set_large_rmappable(new_folio);
2898 	}
2899 
2900 	/* Finally unfreeze refcount. Additional reference from page cache. */
2901 	page_ref_unfreeze(page_tail,
2902 		1 + ((!folio_test_anon(folio) || folio_test_swapcache(folio)) ?
2903 			     folio_nr_pages(new_folio) : 0));
2904 
2905 	if (folio_test_young(folio))
2906 		folio_set_young(new_folio);
2907 	if (folio_test_idle(folio))
2908 		folio_set_idle(new_folio);
2909 
2910 	folio_xchg_last_cpupid(new_folio, folio_last_cpupid(folio));
2911 
2912 	/*
2913 	 * always add to the tail because some iterators expect new
2914 	 * pages to show after the currently processed elements - e.g.
2915 	 * migrate_pages
2916 	 */
2917 	lru_add_page_tail(head, page_tail, lruvec, list);
2918 }
2919 
2920 static void __split_huge_page(struct page *page, struct list_head *list,
2921 		pgoff_t end, unsigned int new_order)
2922 {
2923 	struct folio *folio = page_folio(page);
2924 	struct page *head = &folio->page;
2925 	struct lruvec *lruvec;
2926 	struct address_space *swap_cache = NULL;
2927 	unsigned long offset = 0;
2928 	int i, nr_dropped = 0;
2929 	unsigned int new_nr = 1 << new_order;
2930 	int order = folio_order(folio);
2931 	unsigned int nr = 1 << order;
2932 
2933 	/* complete memcg works before add pages to LRU */
2934 	split_page_memcg(head, order, new_order);
2935 
2936 	if (folio_test_anon(folio) && folio_test_swapcache(folio)) {
2937 		offset = swap_cache_index(folio->swap);
2938 		swap_cache = swap_address_space(folio->swap);
2939 		xa_lock(&swap_cache->i_pages);
2940 	}
2941 
2942 	/* lock lru list/PageCompound, ref frozen by page_ref_freeze */
2943 	lruvec = folio_lruvec_lock(folio);
2944 
2945 	ClearPageHasHWPoisoned(head);
2946 
2947 	for (i = nr - new_nr; i >= new_nr; i -= new_nr) {
2948 		__split_huge_page_tail(folio, i, lruvec, list, new_order);
2949 		/* Some pages can be beyond EOF: drop them from page cache */
2950 		if (head[i].index >= end) {
2951 			struct folio *tail = page_folio(head + i);
2952 
2953 			if (shmem_mapping(folio->mapping))
2954 				nr_dropped++;
2955 			else if (folio_test_clear_dirty(tail))
2956 				folio_account_cleaned(tail,
2957 					inode_to_wb(folio->mapping->host));
2958 			__filemap_remove_folio(tail, NULL);
2959 			folio_put(tail);
2960 		} else if (!PageAnon(page)) {
2961 			__xa_store(&folio->mapping->i_pages, head[i].index,
2962 					head + i, 0);
2963 		} else if (swap_cache) {
2964 			__xa_store(&swap_cache->i_pages, offset + i,
2965 					head + i, 0);
2966 		}
2967 	}
2968 
2969 	if (!new_order)
2970 		ClearPageCompound(head);
2971 	else {
2972 		struct folio *new_folio = (struct folio *)head;
2973 
2974 		folio_set_order(new_folio, new_order);
2975 	}
2976 	unlock_page_lruvec(lruvec);
2977 	/* Caller disabled irqs, so they are still disabled here */
2978 
2979 	split_page_owner(head, order, new_order);
2980 	pgalloc_tag_split(head, 1 << order);
2981 
2982 	/* See comment in __split_huge_page_tail() */
2983 	if (folio_test_anon(folio)) {
2984 		/* Additional pin to swap cache */
2985 		if (folio_test_swapcache(folio)) {
2986 			folio_ref_add(folio, 1 + new_nr);
2987 			xa_unlock(&swap_cache->i_pages);
2988 		} else {
2989 			folio_ref_inc(folio);
2990 		}
2991 	} else {
2992 		/* Additional pin to page cache */
2993 		folio_ref_add(folio, 1 + new_nr);
2994 		xa_unlock(&folio->mapping->i_pages);
2995 	}
2996 	local_irq_enable();
2997 
2998 	if (nr_dropped)
2999 		shmem_uncharge(folio->mapping->host, nr_dropped);
3000 	remap_page(folio, nr);
3001 
3002 	/*
3003 	 * set page to its compound_head when split to non order-0 pages, so
3004 	 * we can skip unlocking it below, since PG_locked is transferred to
3005 	 * the compound_head of the page and the caller will unlock it.
3006 	 */
3007 	if (new_order)
3008 		page = compound_head(page);
3009 
3010 	for (i = 0; i < nr; i += new_nr) {
3011 		struct page *subpage = head + i;
3012 		struct folio *new_folio = page_folio(subpage);
3013 		if (subpage == page)
3014 			continue;
3015 		folio_unlock(new_folio);
3016 
3017 		/*
3018 		 * Subpages may be freed if there wasn't any mapping
3019 		 * like if add_to_swap() is running on a lru page that
3020 		 * had its mapping zapped. And freeing these pages
3021 		 * requires taking the lru_lock so we do the put_page
3022 		 * of the tail pages after the split is complete.
3023 		 */
3024 		free_page_and_swap_cache(subpage);
3025 	}
3026 }
3027 
3028 /* Racy check whether the huge page can be split */
3029 bool can_split_folio(struct folio *folio, int *pextra_pins)
3030 {
3031 	int extra_pins;
3032 
3033 	/* Additional pins from page cache */
3034 	if (folio_test_anon(folio))
3035 		extra_pins = folio_test_swapcache(folio) ?
3036 				folio_nr_pages(folio) : 0;
3037 	else
3038 		extra_pins = folio_nr_pages(folio);
3039 	if (pextra_pins)
3040 		*pextra_pins = extra_pins;
3041 	return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 1;
3042 }
3043 
3044 /*
3045  * This function splits a large folio into smaller folios of order @new_order.
3046  * @page can point to any page of the large folio to split. The split operation
3047  * does not change the position of @page.
3048  *
3049  * Prerequisites:
3050  *
3051  * 1) The caller must hold a reference on the @page's owning folio, also known
3052  *    as the large folio.
3053  *
3054  * 2) The large folio must be locked.
3055  *
3056  * 3) The folio must not be pinned. Any unexpected folio references, including
3057  *    GUP pins, will result in the folio not getting split; instead, the caller
3058  *    will receive an -EAGAIN.
3059  *
3060  * 4) @new_order > 1, usually. Splitting to order-1 anonymous folios is not
3061  *    supported for non-file-backed folios, because folio->_deferred_list, which
3062  *    is used by partially mapped folios, is stored in subpage 2, but an order-1
3063  *    folio only has subpages 0 and 1. File-backed order-1 folios are supported,
3064  *    since they do not use _deferred_list.
3065  *
3066  * After splitting, the caller's folio reference will be transferred to @page,
3067  * resulting in a raised refcount of @page after this call. The other pages may
3068  * be freed if they are not mapped.
3069  *
3070  * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
3071  *
3072  * Pages in @new_order will inherit the mapping, flags, and so on from the
3073  * huge page.
3074  *
3075  * Returns 0 if the huge page was split successfully.
3076  *
3077  * Returns -EAGAIN if the folio has unexpected reference (e.g., GUP) or if
3078  * the folio was concurrently removed from the page cache.
3079  *
3080  * Returns -EBUSY when trying to split the huge zeropage, if the folio is
3081  * under writeback, if fs-specific folio metadata cannot currently be
3082  * released, or if some unexpected race happened (e.g., anon VMA disappeared,
3083  * truncation).
3084  *
3085  * Returns -EINVAL when trying to split to an order that is incompatible
3086  * with the folio. Splitting to order 0 is compatible with all folios.
3087  */
3088 int split_huge_page_to_list_to_order(struct page *page, struct list_head *list,
3089 				     unsigned int new_order)
3090 {
3091 	struct folio *folio = page_folio(page);
3092 	struct deferred_split *ds_queue = get_deferred_split_queue(folio);
3093 	/* reset xarray order to new order after split */
3094 	XA_STATE_ORDER(xas, &folio->mapping->i_pages, folio->index, new_order);
3095 	struct anon_vma *anon_vma = NULL;
3096 	struct address_space *mapping = NULL;
3097 	int order = folio_order(folio);
3098 	int extra_pins, ret;
3099 	pgoff_t end;
3100 	bool is_hzp;
3101 
3102 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3103 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
3104 
3105 	if (new_order >= folio_order(folio))
3106 		return -EINVAL;
3107 
3108 	if (folio_test_anon(folio)) {
3109 		/* order-1 is not supported for anonymous THP. */
3110 		if (new_order == 1) {
3111 			VM_WARN_ONCE(1, "Cannot split to order-1 folio");
3112 			return -EINVAL;
3113 		}
3114 	} else if (new_order) {
3115 		/* Split shmem folio to non-zero order not supported */
3116 		if (shmem_mapping(folio->mapping)) {
3117 			VM_WARN_ONCE(1,
3118 				"Cannot split shmem folio to non-0 order");
3119 			return -EINVAL;
3120 		}
3121 		/*
3122 		 * No split if the file system does not support large folio.
3123 		 * Note that we might still have THPs in such mappings due to
3124 		 * CONFIG_READ_ONLY_THP_FOR_FS. But in that case, the mapping
3125 		 * does not actually support large folios properly.
3126 		 */
3127 		if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
3128 		    !mapping_large_folio_support(folio->mapping)) {
3129 			VM_WARN_ONCE(1,
3130 				"Cannot split file folio to non-0 order");
3131 			return -EINVAL;
3132 		}
3133 	}
3134 
3135 	/* Only swapping a whole PMD-mapped folio is supported */
3136 	if (folio_test_swapcache(folio) && new_order)
3137 		return -EINVAL;
3138 
3139 	is_hzp = is_huge_zero_folio(folio);
3140 	if (is_hzp) {
3141 		pr_warn_ratelimited("Called split_huge_page for huge zero page\n");
3142 		return -EBUSY;
3143 	}
3144 
3145 	if (folio_test_writeback(folio))
3146 		return -EBUSY;
3147 
3148 	if (folio_test_anon(folio)) {
3149 		/*
3150 		 * The caller does not necessarily hold an mmap_lock that would
3151 		 * prevent the anon_vma disappearing so we first we take a
3152 		 * reference to it and then lock the anon_vma for write. This
3153 		 * is similar to folio_lock_anon_vma_read except the write lock
3154 		 * is taken to serialise against parallel split or collapse
3155 		 * operations.
3156 		 */
3157 		anon_vma = folio_get_anon_vma(folio);
3158 		if (!anon_vma) {
3159 			ret = -EBUSY;
3160 			goto out;
3161 		}
3162 		end = -1;
3163 		mapping = NULL;
3164 		anon_vma_lock_write(anon_vma);
3165 	} else {
3166 		gfp_t gfp;
3167 
3168 		mapping = folio->mapping;
3169 
3170 		/* Truncated ? */
3171 		if (!mapping) {
3172 			ret = -EBUSY;
3173 			goto out;
3174 		}
3175 
3176 		gfp = current_gfp_context(mapping_gfp_mask(mapping) &
3177 							GFP_RECLAIM_MASK);
3178 
3179 		if (!filemap_release_folio(folio, gfp)) {
3180 			ret = -EBUSY;
3181 			goto out;
3182 		}
3183 
3184 		xas_split_alloc(&xas, folio, folio_order(folio), gfp);
3185 		if (xas_error(&xas)) {
3186 			ret = xas_error(&xas);
3187 			goto out;
3188 		}
3189 
3190 		anon_vma = NULL;
3191 		i_mmap_lock_read(mapping);
3192 
3193 		/*
3194 		 *__split_huge_page() may need to trim off pages beyond EOF:
3195 		 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
3196 		 * which cannot be nested inside the page tree lock. So note
3197 		 * end now: i_size itself may be changed at any moment, but
3198 		 * folio lock is good enough to serialize the trimming.
3199 		 */
3200 		end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3201 		if (shmem_mapping(mapping))
3202 			end = shmem_fallocend(mapping->host, end);
3203 	}
3204 
3205 	/*
3206 	 * Racy check if we can split the page, before unmap_folio() will
3207 	 * split PMDs
3208 	 */
3209 	if (!can_split_folio(folio, &extra_pins)) {
3210 		ret = -EAGAIN;
3211 		goto out_unlock;
3212 	}
3213 
3214 	unmap_folio(folio);
3215 
3216 	/* block interrupt reentry in xa_lock and spinlock */
3217 	local_irq_disable();
3218 	if (mapping) {
3219 		/*
3220 		 * Check if the folio is present in page cache.
3221 		 * We assume all tail are present too, if folio is there.
3222 		 */
3223 		xas_lock(&xas);
3224 		xas_reset(&xas);
3225 		if (xas_load(&xas) != folio)
3226 			goto fail;
3227 	}
3228 
3229 	/* Prevent deferred_split_scan() touching ->_refcount */
3230 	spin_lock(&ds_queue->split_queue_lock);
3231 	if (folio_ref_freeze(folio, 1 + extra_pins)) {
3232 		if (folio_order(folio) > 1 &&
3233 		    !list_empty(&folio->_deferred_list)) {
3234 			ds_queue->split_queue_len--;
3235 			/*
3236 			 * Reinitialize page_deferred_list after removing the
3237 			 * page from the split_queue, otherwise a subsequent
3238 			 * split will see list corruption when checking the
3239 			 * page_deferred_list.
3240 			 */
3241 			list_del_init(&folio->_deferred_list);
3242 		}
3243 		spin_unlock(&ds_queue->split_queue_lock);
3244 		if (mapping) {
3245 			int nr = folio_nr_pages(folio);
3246 
3247 			xas_split(&xas, folio, folio_order(folio));
3248 			if (folio_test_pmd_mappable(folio) &&
3249 			    new_order < HPAGE_PMD_ORDER) {
3250 				if (folio_test_swapbacked(folio)) {
3251 					__lruvec_stat_mod_folio(folio,
3252 							NR_SHMEM_THPS, -nr);
3253 				} else {
3254 					__lruvec_stat_mod_folio(folio,
3255 							NR_FILE_THPS, -nr);
3256 					filemap_nr_thps_dec(mapping);
3257 				}
3258 			}
3259 		}
3260 
3261 		__split_huge_page(page, list, end, new_order);
3262 		ret = 0;
3263 	} else {
3264 		spin_unlock(&ds_queue->split_queue_lock);
3265 fail:
3266 		if (mapping)
3267 			xas_unlock(&xas);
3268 		local_irq_enable();
3269 		remap_page(folio, folio_nr_pages(folio));
3270 		ret = -EAGAIN;
3271 	}
3272 
3273 out_unlock:
3274 	if (anon_vma) {
3275 		anon_vma_unlock_write(anon_vma);
3276 		put_anon_vma(anon_vma);
3277 	}
3278 	if (mapping)
3279 		i_mmap_unlock_read(mapping);
3280 out:
3281 	xas_destroy(&xas);
3282 	if (order == HPAGE_PMD_ORDER)
3283 		count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
3284 	count_mthp_stat(order, !ret ? MTHP_STAT_SPLIT : MTHP_STAT_SPLIT_FAILED);
3285 	return ret;
3286 }
3287 
3288 void __folio_undo_large_rmappable(struct folio *folio)
3289 {
3290 	struct deferred_split *ds_queue;
3291 	unsigned long flags;
3292 
3293 	ds_queue = get_deferred_split_queue(folio);
3294 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3295 	if (!list_empty(&folio->_deferred_list)) {
3296 		ds_queue->split_queue_len--;
3297 		list_del_init(&folio->_deferred_list);
3298 	}
3299 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3300 }
3301 
3302 void deferred_split_folio(struct folio *folio)
3303 {
3304 	struct deferred_split *ds_queue = get_deferred_split_queue(folio);
3305 #ifdef CONFIG_MEMCG
3306 	struct mem_cgroup *memcg = folio_memcg(folio);
3307 #endif
3308 	unsigned long flags;
3309 
3310 	/*
3311 	 * Order 1 folios have no space for a deferred list, but we also
3312 	 * won't waste much memory by not adding them to the deferred list.
3313 	 */
3314 	if (folio_order(folio) <= 1)
3315 		return;
3316 
3317 	/*
3318 	 * The try_to_unmap() in page reclaim path might reach here too,
3319 	 * this may cause a race condition to corrupt deferred split queue.
3320 	 * And, if page reclaim is already handling the same folio, it is
3321 	 * unnecessary to handle it again in shrinker.
3322 	 *
3323 	 * Check the swapcache flag to determine if the folio is being
3324 	 * handled by page reclaim since THP swap would add the folio into
3325 	 * swap cache before calling try_to_unmap().
3326 	 */
3327 	if (folio_test_swapcache(folio))
3328 		return;
3329 
3330 	if (!list_empty(&folio->_deferred_list))
3331 		return;
3332 
3333 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3334 	if (list_empty(&folio->_deferred_list)) {
3335 		if (folio_test_pmd_mappable(folio))
3336 			count_vm_event(THP_DEFERRED_SPLIT_PAGE);
3337 		count_mthp_stat(folio_order(folio), MTHP_STAT_SPLIT_DEFERRED);
3338 		list_add_tail(&folio->_deferred_list, &ds_queue->split_queue);
3339 		ds_queue->split_queue_len++;
3340 #ifdef CONFIG_MEMCG
3341 		if (memcg)
3342 			set_shrinker_bit(memcg, folio_nid(folio),
3343 					 deferred_split_shrinker->id);
3344 #endif
3345 	}
3346 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3347 }
3348 
3349 static unsigned long deferred_split_count(struct shrinker *shrink,
3350 		struct shrink_control *sc)
3351 {
3352 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
3353 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
3354 
3355 #ifdef CONFIG_MEMCG
3356 	if (sc->memcg)
3357 		ds_queue = &sc->memcg->deferred_split_queue;
3358 #endif
3359 	return READ_ONCE(ds_queue->split_queue_len);
3360 }
3361 
3362 static unsigned long deferred_split_scan(struct shrinker *shrink,
3363 		struct shrink_control *sc)
3364 {
3365 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
3366 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
3367 	unsigned long flags;
3368 	LIST_HEAD(list);
3369 	struct folio *folio, *next;
3370 	int split = 0;
3371 
3372 #ifdef CONFIG_MEMCG
3373 	if (sc->memcg)
3374 		ds_queue = &sc->memcg->deferred_split_queue;
3375 #endif
3376 
3377 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3378 	/* Take pin on all head pages to avoid freeing them under us */
3379 	list_for_each_entry_safe(folio, next, &ds_queue->split_queue,
3380 							_deferred_list) {
3381 		if (folio_try_get(folio)) {
3382 			list_move(&folio->_deferred_list, &list);
3383 		} else {
3384 			/* We lost race with folio_put() */
3385 			list_del_init(&folio->_deferred_list);
3386 			ds_queue->split_queue_len--;
3387 		}
3388 		if (!--sc->nr_to_scan)
3389 			break;
3390 	}
3391 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3392 
3393 	list_for_each_entry_safe(folio, next, &list, _deferred_list) {
3394 		if (!folio_trylock(folio))
3395 			goto next;
3396 		/* split_huge_page() removes page from list on success */
3397 		if (!split_folio(folio))
3398 			split++;
3399 		folio_unlock(folio);
3400 next:
3401 		folio_put(folio);
3402 	}
3403 
3404 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
3405 	list_splice_tail(&list, &ds_queue->split_queue);
3406 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
3407 
3408 	/*
3409 	 * Stop shrinker if we didn't split any page, but the queue is empty.
3410 	 * This can happen if pages were freed under us.
3411 	 */
3412 	if (!split && list_empty(&ds_queue->split_queue))
3413 		return SHRINK_STOP;
3414 	return split;
3415 }
3416 
3417 #ifdef CONFIG_DEBUG_FS
3418 static void split_huge_pages_all(void)
3419 {
3420 	struct zone *zone;
3421 	struct page *page;
3422 	struct folio *folio;
3423 	unsigned long pfn, max_zone_pfn;
3424 	unsigned long total = 0, split = 0;
3425 
3426 	pr_debug("Split all THPs\n");
3427 	for_each_zone(zone) {
3428 		if (!managed_zone(zone))
3429 			continue;
3430 		max_zone_pfn = zone_end_pfn(zone);
3431 		for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
3432 			int nr_pages;
3433 
3434 			page = pfn_to_online_page(pfn);
3435 			if (!page || PageTail(page))
3436 				continue;
3437 			folio = page_folio(page);
3438 			if (!folio_try_get(folio))
3439 				continue;
3440 
3441 			if (unlikely(page_folio(page) != folio))
3442 				goto next;
3443 
3444 			if (zone != folio_zone(folio))
3445 				goto next;
3446 
3447 			if (!folio_test_large(folio)
3448 				|| folio_test_hugetlb(folio)
3449 				|| !folio_test_lru(folio))
3450 				goto next;
3451 
3452 			total++;
3453 			folio_lock(folio);
3454 			nr_pages = folio_nr_pages(folio);
3455 			if (!split_folio(folio))
3456 				split++;
3457 			pfn += nr_pages - 1;
3458 			folio_unlock(folio);
3459 next:
3460 			folio_put(folio);
3461 			cond_resched();
3462 		}
3463 	}
3464 
3465 	pr_debug("%lu of %lu THP split\n", split, total);
3466 }
3467 
3468 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
3469 {
3470 	return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
3471 		    is_vm_hugetlb_page(vma);
3472 }
3473 
3474 static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
3475 				unsigned long vaddr_end, unsigned int new_order)
3476 {
3477 	int ret = 0;
3478 	struct task_struct *task;
3479 	struct mm_struct *mm;
3480 	unsigned long total = 0, split = 0;
3481 	unsigned long addr;
3482 
3483 	vaddr_start &= PAGE_MASK;
3484 	vaddr_end &= PAGE_MASK;
3485 
3486 	/* Find the task_struct from pid */
3487 	rcu_read_lock();
3488 	task = find_task_by_vpid(pid);
3489 	if (!task) {
3490 		rcu_read_unlock();
3491 		ret = -ESRCH;
3492 		goto out;
3493 	}
3494 	get_task_struct(task);
3495 	rcu_read_unlock();
3496 
3497 	/* Find the mm_struct */
3498 	mm = get_task_mm(task);
3499 	put_task_struct(task);
3500 
3501 	if (!mm) {
3502 		ret = -EINVAL;
3503 		goto out;
3504 	}
3505 
3506 	pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
3507 		 pid, vaddr_start, vaddr_end);
3508 
3509 	mmap_read_lock(mm);
3510 	/*
3511 	 * always increase addr by PAGE_SIZE, since we could have a PTE page
3512 	 * table filled with PTE-mapped THPs, each of which is distinct.
3513 	 */
3514 	for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
3515 		struct vm_area_struct *vma = vma_lookup(mm, addr);
3516 		struct page *page;
3517 		struct folio *folio;
3518 
3519 		if (!vma)
3520 			break;
3521 
3522 		/* skip special VMA and hugetlb VMA */
3523 		if (vma_not_suitable_for_thp_split(vma)) {
3524 			addr = vma->vm_end;
3525 			continue;
3526 		}
3527 
3528 		/* FOLL_DUMP to ignore special (like zero) pages */
3529 		page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
3530 
3531 		if (IS_ERR_OR_NULL(page))
3532 			continue;
3533 
3534 		folio = page_folio(page);
3535 		if (!is_transparent_hugepage(folio))
3536 			goto next;
3537 
3538 		if (new_order >= folio_order(folio))
3539 			goto next;
3540 
3541 		total++;
3542 		/*
3543 		 * For folios with private, split_huge_page_to_list_to_order()
3544 		 * will try to drop it before split and then check if the folio
3545 		 * can be split or not. So skip the check here.
3546 		 */
3547 		if (!folio_test_private(folio) &&
3548 		    !can_split_folio(folio, NULL))
3549 			goto next;
3550 
3551 		if (!folio_trylock(folio))
3552 			goto next;
3553 
3554 		if (!split_folio_to_order(folio, new_order))
3555 			split++;
3556 
3557 		folio_unlock(folio);
3558 next:
3559 		folio_put(folio);
3560 		cond_resched();
3561 	}
3562 	mmap_read_unlock(mm);
3563 	mmput(mm);
3564 
3565 	pr_debug("%lu of %lu THP split\n", split, total);
3566 
3567 out:
3568 	return ret;
3569 }
3570 
3571 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
3572 				pgoff_t off_end, unsigned int new_order)
3573 {
3574 	struct filename *file;
3575 	struct file *candidate;
3576 	struct address_space *mapping;
3577 	int ret = -EINVAL;
3578 	pgoff_t index;
3579 	int nr_pages = 1;
3580 	unsigned long total = 0, split = 0;
3581 
3582 	file = getname_kernel(file_path);
3583 	if (IS_ERR(file))
3584 		return ret;
3585 
3586 	candidate = file_open_name(file, O_RDONLY, 0);
3587 	if (IS_ERR(candidate))
3588 		goto out;
3589 
3590 	pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
3591 		 file_path, off_start, off_end);
3592 
3593 	mapping = candidate->f_mapping;
3594 
3595 	for (index = off_start; index < off_end; index += nr_pages) {
3596 		struct folio *folio = filemap_get_folio(mapping, index);
3597 
3598 		nr_pages = 1;
3599 		if (IS_ERR(folio))
3600 			continue;
3601 
3602 		if (!folio_test_large(folio))
3603 			goto next;
3604 
3605 		total++;
3606 		nr_pages = folio_nr_pages(folio);
3607 
3608 		if (new_order >= folio_order(folio))
3609 			goto next;
3610 
3611 		if (!folio_trylock(folio))
3612 			goto next;
3613 
3614 		if (!split_folio_to_order(folio, new_order))
3615 			split++;
3616 
3617 		folio_unlock(folio);
3618 next:
3619 		folio_put(folio);
3620 		cond_resched();
3621 	}
3622 
3623 	filp_close(candidate, NULL);
3624 	ret = 0;
3625 
3626 	pr_debug("%lu of %lu file-backed THP split\n", split, total);
3627 out:
3628 	putname(file);
3629 	return ret;
3630 }
3631 
3632 #define MAX_INPUT_BUF_SZ 255
3633 
3634 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
3635 				size_t count, loff_t *ppops)
3636 {
3637 	static DEFINE_MUTEX(split_debug_mutex);
3638 	ssize_t ret;
3639 	/*
3640 	 * hold pid, start_vaddr, end_vaddr, new_order or
3641 	 * file_path, off_start, off_end, new_order
3642 	 */
3643 	char input_buf[MAX_INPUT_BUF_SZ];
3644 	int pid;
3645 	unsigned long vaddr_start, vaddr_end;
3646 	unsigned int new_order = 0;
3647 
3648 	ret = mutex_lock_interruptible(&split_debug_mutex);
3649 	if (ret)
3650 		return ret;
3651 
3652 	ret = -EFAULT;
3653 
3654 	memset(input_buf, 0, MAX_INPUT_BUF_SZ);
3655 	if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
3656 		goto out;
3657 
3658 	input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
3659 
3660 	if (input_buf[0] == '/') {
3661 		char *tok;
3662 		char *buf = input_buf;
3663 		char file_path[MAX_INPUT_BUF_SZ];
3664 		pgoff_t off_start = 0, off_end = 0;
3665 		size_t input_len = strlen(input_buf);
3666 
3667 		tok = strsep(&buf, ",");
3668 		if (tok) {
3669 			strcpy(file_path, tok);
3670 		} else {
3671 			ret = -EINVAL;
3672 			goto out;
3673 		}
3674 
3675 		ret = sscanf(buf, "0x%lx,0x%lx,%d", &off_start, &off_end, &new_order);
3676 		if (ret != 2 && ret != 3) {
3677 			ret = -EINVAL;
3678 			goto out;
3679 		}
3680 		ret = split_huge_pages_in_file(file_path, off_start, off_end, new_order);
3681 		if (!ret)
3682 			ret = input_len;
3683 
3684 		goto out;
3685 	}
3686 
3687 	ret = sscanf(input_buf, "%d,0x%lx,0x%lx,%d", &pid, &vaddr_start, &vaddr_end, &new_order);
3688 	if (ret == 1 && pid == 1) {
3689 		split_huge_pages_all();
3690 		ret = strlen(input_buf);
3691 		goto out;
3692 	} else if (ret != 3 && ret != 4) {
3693 		ret = -EINVAL;
3694 		goto out;
3695 	}
3696 
3697 	ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end, new_order);
3698 	if (!ret)
3699 		ret = strlen(input_buf);
3700 out:
3701 	mutex_unlock(&split_debug_mutex);
3702 	return ret;
3703 
3704 }
3705 
3706 static const struct file_operations split_huge_pages_fops = {
3707 	.owner	 = THIS_MODULE,
3708 	.write	 = split_huge_pages_write,
3709 	.llseek  = no_llseek,
3710 };
3711 
3712 static int __init split_huge_pages_debugfs(void)
3713 {
3714 	debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3715 			    &split_huge_pages_fops);
3716 	return 0;
3717 }
3718 late_initcall(split_huge_pages_debugfs);
3719 #endif
3720 
3721 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
3722 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
3723 		struct page *page)
3724 {
3725 	struct folio *folio = page_folio(page);
3726 	struct vm_area_struct *vma = pvmw->vma;
3727 	struct mm_struct *mm = vma->vm_mm;
3728 	unsigned long address = pvmw->address;
3729 	bool anon_exclusive;
3730 	pmd_t pmdval;
3731 	swp_entry_t entry;
3732 	pmd_t pmdswp;
3733 
3734 	if (!(pvmw->pmd && !pvmw->pte))
3735 		return 0;
3736 
3737 	flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
3738 	pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
3739 
3740 	/* See folio_try_share_anon_rmap_pmd(): invalidate PMD first. */
3741 	anon_exclusive = folio_test_anon(folio) && PageAnonExclusive(page);
3742 	if (anon_exclusive && folio_try_share_anon_rmap_pmd(folio, page)) {
3743 		set_pmd_at(mm, address, pvmw->pmd, pmdval);
3744 		return -EBUSY;
3745 	}
3746 
3747 	if (pmd_dirty(pmdval))
3748 		folio_mark_dirty(folio);
3749 	if (pmd_write(pmdval))
3750 		entry = make_writable_migration_entry(page_to_pfn(page));
3751 	else if (anon_exclusive)
3752 		entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
3753 	else
3754 		entry = make_readable_migration_entry(page_to_pfn(page));
3755 	if (pmd_young(pmdval))
3756 		entry = make_migration_entry_young(entry);
3757 	if (pmd_dirty(pmdval))
3758 		entry = make_migration_entry_dirty(entry);
3759 	pmdswp = swp_entry_to_pmd(entry);
3760 	if (pmd_soft_dirty(pmdval))
3761 		pmdswp = pmd_swp_mksoft_dirty(pmdswp);
3762 	if (pmd_uffd_wp(pmdval))
3763 		pmdswp = pmd_swp_mkuffd_wp(pmdswp);
3764 	set_pmd_at(mm, address, pvmw->pmd, pmdswp);
3765 	folio_remove_rmap_pmd(folio, page, vma);
3766 	folio_put(folio);
3767 	trace_set_migration_pmd(address, pmd_val(pmdswp));
3768 
3769 	return 0;
3770 }
3771 
3772 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
3773 {
3774 	struct folio *folio = page_folio(new);
3775 	struct vm_area_struct *vma = pvmw->vma;
3776 	struct mm_struct *mm = vma->vm_mm;
3777 	unsigned long address = pvmw->address;
3778 	unsigned long haddr = address & HPAGE_PMD_MASK;
3779 	pmd_t pmde;
3780 	swp_entry_t entry;
3781 
3782 	if (!(pvmw->pmd && !pvmw->pte))
3783 		return;
3784 
3785 	entry = pmd_to_swp_entry(*pvmw->pmd);
3786 	folio_get(folio);
3787 	pmde = mk_huge_pmd(new, READ_ONCE(vma->vm_page_prot));
3788 	if (pmd_swp_soft_dirty(*pvmw->pmd))
3789 		pmde = pmd_mksoft_dirty(pmde);
3790 	if (is_writable_migration_entry(entry))
3791 		pmde = pmd_mkwrite(pmde, vma);
3792 	if (pmd_swp_uffd_wp(*pvmw->pmd))
3793 		pmde = pmd_mkuffd_wp(pmde);
3794 	if (!is_migration_entry_young(entry))
3795 		pmde = pmd_mkold(pmde);
3796 	/* NOTE: this may contain setting soft-dirty on some archs */
3797 	if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
3798 		pmde = pmd_mkdirty(pmde);
3799 
3800 	if (folio_test_anon(folio)) {
3801 		rmap_t rmap_flags = RMAP_NONE;
3802 
3803 		if (!is_readable_migration_entry(entry))
3804 			rmap_flags |= RMAP_EXCLUSIVE;
3805 
3806 		folio_add_anon_rmap_pmd(folio, new, vma, haddr, rmap_flags);
3807 	} else {
3808 		folio_add_file_rmap_pmd(folio, new, vma);
3809 	}
3810 	VM_BUG_ON(pmd_write(pmde) && folio_test_anon(folio) && !PageAnonExclusive(new));
3811 	set_pmd_at(mm, haddr, pvmw->pmd, pmde);
3812 
3813 	/* No need to invalidate - it was non-present before */
3814 	update_mmu_cache_pmd(vma, address, pvmw->pmd);
3815 	trace_remove_migration_pmd(address, pmd_val(pmde));
3816 }
3817 #endif
3818