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