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