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