xref: /openbmc/linux/mm/huge_memory.c (revision 2fe60ec9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Copyright (C) 2009  Red Hat, Inc.
4  */
5 
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 
8 #include <linux/mm.h>
9 #include <linux/sched.h>
10 #include <linux/sched/mm.h>
11 #include <linux/sched/coredump.h>
12 #include <linux/sched/numa_balancing.h>
13 #include <linux/highmem.h>
14 #include <linux/hugetlb.h>
15 #include <linux/mmu_notifier.h>
16 #include <linux/rmap.h>
17 #include <linux/swap.h>
18 #include <linux/shrinker.h>
19 #include <linux/mm_inline.h>
20 #include <linux/swapops.h>
21 #include <linux/dax.h>
22 #include <linux/khugepaged.h>
23 #include <linux/freezer.h>
24 #include <linux/pfn_t.h>
25 #include <linux/mman.h>
26 #include <linux/memremap.h>
27 #include <linux/pagemap.h>
28 #include <linux/debugfs.h>
29 #include <linux/migrate.h>
30 #include <linux/hashtable.h>
31 #include <linux/userfaultfd_k.h>
32 #include <linux/page_idle.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/oom.h>
35 #include <linux/numa.h>
36 #include <linux/page_owner.h>
37 #include <linux/sched/sysctl.h>
38 
39 #include <asm/tlb.h>
40 #include <asm/pgalloc.h>
41 #include "internal.h"
42 #include "swap.h"
43 
44 #define CREATE_TRACE_POINTS
45 #include <trace/events/thp.h>
46 
47 /*
48  * By default, transparent hugepage support is disabled in order to avoid
49  * risking an increased memory footprint for applications that are not
50  * guaranteed to benefit from it. When transparent hugepage support is
51  * enabled, it is for all mappings, and khugepaged scans all mappings.
52  * Defrag is invoked by khugepaged hugepage allocations and by page faults
53  * for all hugepage allocations.
54  */
55 unsigned long transparent_hugepage_flags __read_mostly =
56 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
57 	(1<<TRANSPARENT_HUGEPAGE_FLAG)|
58 #endif
59 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
60 	(1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
61 #endif
62 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
63 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
64 	(1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
65 
66 static struct shrinker deferred_split_shrinker;
67 
68 static atomic_t huge_zero_refcount;
69 struct page *huge_zero_page __read_mostly;
70 unsigned long huge_zero_pfn __read_mostly = ~0UL;
71 
72 static inline bool file_thp_enabled(struct vm_area_struct *vma)
73 {
74 	return transhuge_vma_enabled(vma, vma->vm_flags) && vma->vm_file &&
75 	       !inode_is_open_for_write(vma->vm_file->f_inode) &&
76 	       (vma->vm_flags & VM_EXEC);
77 }
78 
79 bool transparent_hugepage_active(struct vm_area_struct *vma)
80 {
81 	/* The addr is used to check if the vma size fits */
82 	unsigned long addr = (vma->vm_end & HPAGE_PMD_MASK) - HPAGE_PMD_SIZE;
83 
84 	if (!transhuge_vma_suitable(vma, addr))
85 		return false;
86 	if (vma_is_anonymous(vma))
87 		return __transparent_hugepage_enabled(vma);
88 	if (vma_is_shmem(vma))
89 		return shmem_huge_enabled(vma);
90 	if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS))
91 		return file_thp_enabled(vma);
92 
93 	return false;
94 }
95 
96 static bool get_huge_zero_page(void)
97 {
98 	struct page *zero_page;
99 retry:
100 	if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
101 		return true;
102 
103 	zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
104 			HPAGE_PMD_ORDER);
105 	if (!zero_page) {
106 		count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
107 		return false;
108 	}
109 	count_vm_event(THP_ZERO_PAGE_ALLOC);
110 	preempt_disable();
111 	if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
112 		preempt_enable();
113 		__free_pages(zero_page, compound_order(zero_page));
114 		goto retry;
115 	}
116 	WRITE_ONCE(huge_zero_pfn, page_to_pfn(zero_page));
117 
118 	/* We take additional reference here. It will be put back by shrinker */
119 	atomic_set(&huge_zero_refcount, 2);
120 	preempt_enable();
121 	return true;
122 }
123 
124 static void put_huge_zero_page(void)
125 {
126 	/*
127 	 * Counter should never go to zero here. Only shrinker can put
128 	 * last reference.
129 	 */
130 	BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
131 }
132 
133 struct page *mm_get_huge_zero_page(struct mm_struct *mm)
134 {
135 	if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
136 		return READ_ONCE(huge_zero_page);
137 
138 	if (!get_huge_zero_page())
139 		return NULL;
140 
141 	if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
142 		put_huge_zero_page();
143 
144 	return READ_ONCE(huge_zero_page);
145 }
146 
147 void mm_put_huge_zero_page(struct mm_struct *mm)
148 {
149 	if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
150 		put_huge_zero_page();
151 }
152 
153 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
154 					struct shrink_control *sc)
155 {
156 	/* we can free zero page only if last reference remains */
157 	return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
158 }
159 
160 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
161 				       struct shrink_control *sc)
162 {
163 	if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
164 		struct page *zero_page = xchg(&huge_zero_page, NULL);
165 		BUG_ON(zero_page == NULL);
166 		WRITE_ONCE(huge_zero_pfn, ~0UL);
167 		__free_pages(zero_page, compound_order(zero_page));
168 		return HPAGE_PMD_NR;
169 	}
170 
171 	return 0;
172 }
173 
174 static struct shrinker huge_zero_page_shrinker = {
175 	.count_objects = shrink_huge_zero_page_count,
176 	.scan_objects = shrink_huge_zero_page_scan,
177 	.seeks = DEFAULT_SEEKS,
178 };
179 
180 #ifdef CONFIG_SYSFS
181 static ssize_t enabled_show(struct kobject *kobj,
182 			    struct kobj_attribute *attr, char *buf)
183 {
184 	const char *output;
185 
186 	if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
187 		output = "[always] madvise never";
188 	else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
189 			  &transparent_hugepage_flags))
190 		output = "always [madvise] never";
191 	else
192 		output = "always madvise [never]";
193 
194 	return sysfs_emit(buf, "%s\n", output);
195 }
196 
197 static ssize_t enabled_store(struct kobject *kobj,
198 			     struct kobj_attribute *attr,
199 			     const char *buf, size_t count)
200 {
201 	ssize_t ret = count;
202 
203 	if (sysfs_streq(buf, "always")) {
204 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
205 		set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
206 	} else if (sysfs_streq(buf, "madvise")) {
207 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
208 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
209 	} else if (sysfs_streq(buf, "never")) {
210 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
211 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
212 	} else
213 		ret = -EINVAL;
214 
215 	if (ret > 0) {
216 		int err = start_stop_khugepaged();
217 		if (err)
218 			ret = err;
219 	}
220 	return ret;
221 }
222 static struct kobj_attribute enabled_attr =
223 	__ATTR(enabled, 0644, enabled_show, enabled_store);
224 
225 ssize_t single_hugepage_flag_show(struct kobject *kobj,
226 				  struct kobj_attribute *attr, char *buf,
227 				  enum transparent_hugepage_flag flag)
228 {
229 	return sysfs_emit(buf, "%d\n",
230 			  !!test_bit(flag, &transparent_hugepage_flags));
231 }
232 
233 ssize_t single_hugepage_flag_store(struct kobject *kobj,
234 				 struct kobj_attribute *attr,
235 				 const char *buf, size_t count,
236 				 enum transparent_hugepage_flag flag)
237 {
238 	unsigned long value;
239 	int ret;
240 
241 	ret = kstrtoul(buf, 10, &value);
242 	if (ret < 0)
243 		return ret;
244 	if (value > 1)
245 		return -EINVAL;
246 
247 	if (value)
248 		set_bit(flag, &transparent_hugepage_flags);
249 	else
250 		clear_bit(flag, &transparent_hugepage_flags);
251 
252 	return count;
253 }
254 
255 static ssize_t defrag_show(struct kobject *kobj,
256 			   struct kobj_attribute *attr, char *buf)
257 {
258 	const char *output;
259 
260 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
261 		     &transparent_hugepage_flags))
262 		output = "[always] defer defer+madvise madvise never";
263 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
264 			  &transparent_hugepage_flags))
265 		output = "always [defer] defer+madvise madvise never";
266 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,
267 			  &transparent_hugepage_flags))
268 		output = "always defer [defer+madvise] madvise never";
269 	else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,
270 			  &transparent_hugepage_flags))
271 		output = "always defer defer+madvise [madvise] never";
272 	else
273 		output = "always defer defer+madvise madvise [never]";
274 
275 	return sysfs_emit(buf, "%s\n", output);
276 }
277 
278 static ssize_t defrag_store(struct kobject *kobj,
279 			    struct kobj_attribute *attr,
280 			    const char *buf, size_t count)
281 {
282 	if (sysfs_streq(buf, "always")) {
283 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
284 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
285 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
286 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
287 	} else if (sysfs_streq(buf, "defer+madvise")) {
288 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
289 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
290 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
291 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
292 	} else if (sysfs_streq(buf, "defer")) {
293 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
294 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
295 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
296 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
297 	} else if (sysfs_streq(buf, "madvise")) {
298 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
299 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
300 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
301 		set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
302 	} else if (sysfs_streq(buf, "never")) {
303 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
304 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
305 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
306 		clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
307 	} else
308 		return -EINVAL;
309 
310 	return count;
311 }
312 static struct kobj_attribute defrag_attr =
313 	__ATTR(defrag, 0644, defrag_show, defrag_store);
314 
315 static ssize_t use_zero_page_show(struct kobject *kobj,
316 				  struct kobj_attribute *attr, char *buf)
317 {
318 	return single_hugepage_flag_show(kobj, attr, buf,
319 					 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
320 }
321 static ssize_t use_zero_page_store(struct kobject *kobj,
322 		struct kobj_attribute *attr, const char *buf, size_t count)
323 {
324 	return single_hugepage_flag_store(kobj, attr, buf, count,
325 				 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
326 }
327 static struct kobj_attribute use_zero_page_attr =
328 	__ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
329 
330 static ssize_t hpage_pmd_size_show(struct kobject *kobj,
331 				   struct kobj_attribute *attr, char *buf)
332 {
333 	return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE);
334 }
335 static struct kobj_attribute hpage_pmd_size_attr =
336 	__ATTR_RO(hpage_pmd_size);
337 
338 static struct attribute *hugepage_attr[] = {
339 	&enabled_attr.attr,
340 	&defrag_attr.attr,
341 	&use_zero_page_attr.attr,
342 	&hpage_pmd_size_attr.attr,
343 #ifdef CONFIG_SHMEM
344 	&shmem_enabled_attr.attr,
345 #endif
346 	NULL,
347 };
348 
349 static const struct attribute_group hugepage_attr_group = {
350 	.attrs = hugepage_attr,
351 };
352 
353 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
354 {
355 	int err;
356 
357 	*hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
358 	if (unlikely(!*hugepage_kobj)) {
359 		pr_err("failed to create transparent hugepage kobject\n");
360 		return -ENOMEM;
361 	}
362 
363 	err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
364 	if (err) {
365 		pr_err("failed to register transparent hugepage group\n");
366 		goto delete_obj;
367 	}
368 
369 	err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
370 	if (err) {
371 		pr_err("failed to register transparent hugepage group\n");
372 		goto remove_hp_group;
373 	}
374 
375 	return 0;
376 
377 remove_hp_group:
378 	sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
379 delete_obj:
380 	kobject_put(*hugepage_kobj);
381 	return err;
382 }
383 
384 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
385 {
386 	sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
387 	sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
388 	kobject_put(hugepage_kobj);
389 }
390 #else
391 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
392 {
393 	return 0;
394 }
395 
396 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
397 {
398 }
399 #endif /* CONFIG_SYSFS */
400 
401 static int __init hugepage_init(void)
402 {
403 	int err;
404 	struct kobject *hugepage_kobj;
405 
406 	if (!has_transparent_hugepage()) {
407 		/*
408 		 * Hardware doesn't support hugepages, hence disable
409 		 * DAX PMD support.
410 		 */
411 		transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_NEVER_DAX;
412 		return -EINVAL;
413 	}
414 
415 	/*
416 	 * hugepages can't be allocated by the buddy allocator
417 	 */
418 	MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER >= MAX_ORDER);
419 	/*
420 	 * we use page->mapping and page->index in second tail page
421 	 * as list_head: assuming THP order >= 2
422 	 */
423 	MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER < 2);
424 
425 	err = hugepage_init_sysfs(&hugepage_kobj);
426 	if (err)
427 		goto err_sysfs;
428 
429 	err = khugepaged_init();
430 	if (err)
431 		goto err_slab;
432 
433 	err = register_shrinker(&huge_zero_page_shrinker);
434 	if (err)
435 		goto err_hzp_shrinker;
436 	err = register_shrinker(&deferred_split_shrinker);
437 	if (err)
438 		goto err_split_shrinker;
439 
440 	/*
441 	 * By default disable transparent hugepages on smaller systems,
442 	 * where the extra memory used could hurt more than TLB overhead
443 	 * is likely to save.  The admin can still enable it through /sys.
444 	 */
445 	if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) {
446 		transparent_hugepage_flags = 0;
447 		return 0;
448 	}
449 
450 	err = start_stop_khugepaged();
451 	if (err)
452 		goto err_khugepaged;
453 
454 	return 0;
455 err_khugepaged:
456 	unregister_shrinker(&deferred_split_shrinker);
457 err_split_shrinker:
458 	unregister_shrinker(&huge_zero_page_shrinker);
459 err_hzp_shrinker:
460 	khugepaged_destroy();
461 err_slab:
462 	hugepage_exit_sysfs(hugepage_kobj);
463 err_sysfs:
464 	return err;
465 }
466 subsys_initcall(hugepage_init);
467 
468 static int __init setup_transparent_hugepage(char *str)
469 {
470 	int ret = 0;
471 	if (!str)
472 		goto out;
473 	if (!strcmp(str, "always")) {
474 		set_bit(TRANSPARENT_HUGEPAGE_FLAG,
475 			&transparent_hugepage_flags);
476 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
477 			  &transparent_hugepage_flags);
478 		ret = 1;
479 	} else if (!strcmp(str, "madvise")) {
480 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
481 			  &transparent_hugepage_flags);
482 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
483 			&transparent_hugepage_flags);
484 		ret = 1;
485 	} else if (!strcmp(str, "never")) {
486 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
487 			  &transparent_hugepage_flags);
488 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
489 			  &transparent_hugepage_flags);
490 		ret = 1;
491 	}
492 out:
493 	if (!ret)
494 		pr_warn("transparent_hugepage= cannot parse, ignored\n");
495 	return ret;
496 }
497 __setup("transparent_hugepage=", setup_transparent_hugepage);
498 
499 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
500 {
501 	if (likely(vma->vm_flags & VM_WRITE))
502 		pmd = pmd_mkwrite(pmd);
503 	return pmd;
504 }
505 
506 #ifdef CONFIG_MEMCG
507 static inline struct deferred_split *get_deferred_split_queue(struct page *page)
508 {
509 	struct mem_cgroup *memcg = page_memcg(compound_head(page));
510 	struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
511 
512 	if (memcg)
513 		return &memcg->deferred_split_queue;
514 	else
515 		return &pgdat->deferred_split_queue;
516 }
517 #else
518 static inline struct deferred_split *get_deferred_split_queue(struct page *page)
519 {
520 	struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
521 
522 	return &pgdat->deferred_split_queue;
523 }
524 #endif
525 
526 void prep_transhuge_page(struct page *page)
527 {
528 	/*
529 	 * we use page->mapping and page->indexlru in second tail page
530 	 * as list_head: assuming THP order >= 2
531 	 */
532 
533 	INIT_LIST_HEAD(page_deferred_list(page));
534 	set_compound_page_dtor(page, TRANSHUGE_PAGE_DTOR);
535 }
536 
537 static inline bool is_transparent_hugepage(struct page *page)
538 {
539 	if (!PageCompound(page))
540 		return false;
541 
542 	page = compound_head(page);
543 	return is_huge_zero_page(page) ||
544 	       page[1].compound_dtor == TRANSHUGE_PAGE_DTOR;
545 }
546 
547 static unsigned long __thp_get_unmapped_area(struct file *filp,
548 		unsigned long addr, unsigned long len,
549 		loff_t off, unsigned long flags, unsigned long size)
550 {
551 	loff_t off_end = off + len;
552 	loff_t off_align = round_up(off, size);
553 	unsigned long len_pad, ret;
554 
555 	if (off_end <= off_align || (off_end - off_align) < size)
556 		return 0;
557 
558 	len_pad = len + size;
559 	if (len_pad < len || (off + len_pad) < off)
560 		return 0;
561 
562 	ret = current->mm->get_unmapped_area(filp, addr, len_pad,
563 					      off >> PAGE_SHIFT, flags);
564 
565 	/*
566 	 * The failure might be due to length padding. The caller will retry
567 	 * without the padding.
568 	 */
569 	if (IS_ERR_VALUE(ret))
570 		return 0;
571 
572 	/*
573 	 * Do not try to align to THP boundary if allocation at the address
574 	 * hint succeeds.
575 	 */
576 	if (ret == addr)
577 		return addr;
578 
579 	ret += (off - ret) & (size - 1);
580 	return ret;
581 }
582 
583 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
584 		unsigned long len, unsigned long pgoff, unsigned long flags)
585 {
586 	unsigned long ret;
587 	loff_t off = (loff_t)pgoff << PAGE_SHIFT;
588 
589 	ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE);
590 	if (ret)
591 		return ret;
592 
593 	return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
594 }
595 EXPORT_SYMBOL_GPL(thp_get_unmapped_area);
596 
597 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf,
598 			struct page *page, gfp_t gfp)
599 {
600 	struct vm_area_struct *vma = vmf->vma;
601 	pgtable_t pgtable;
602 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
603 	vm_fault_t ret = 0;
604 
605 	VM_BUG_ON_PAGE(!PageCompound(page), page);
606 
607 	if (mem_cgroup_charge(page_folio(page), vma->vm_mm, gfp)) {
608 		put_page(page);
609 		count_vm_event(THP_FAULT_FALLBACK);
610 		count_vm_event(THP_FAULT_FALLBACK_CHARGE);
611 		return VM_FAULT_FALLBACK;
612 	}
613 	cgroup_throttle_swaprate(page, gfp);
614 
615 	pgtable = pte_alloc_one(vma->vm_mm);
616 	if (unlikely(!pgtable)) {
617 		ret = VM_FAULT_OOM;
618 		goto release;
619 	}
620 
621 	clear_huge_page(page, vmf->address, HPAGE_PMD_NR);
622 	/*
623 	 * The memory barrier inside __SetPageUptodate makes sure that
624 	 * clear_huge_page writes become visible before the set_pmd_at()
625 	 * write.
626 	 */
627 	__SetPageUptodate(page);
628 
629 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
630 	if (unlikely(!pmd_none(*vmf->pmd))) {
631 		goto unlock_release;
632 	} else {
633 		pmd_t entry;
634 
635 		ret = check_stable_address_space(vma->vm_mm);
636 		if (ret)
637 			goto unlock_release;
638 
639 		/* Deliver the page fault to userland */
640 		if (userfaultfd_missing(vma)) {
641 			spin_unlock(vmf->ptl);
642 			put_page(page);
643 			pte_free(vma->vm_mm, pgtable);
644 			ret = handle_userfault(vmf, VM_UFFD_MISSING);
645 			VM_BUG_ON(ret & VM_FAULT_FALLBACK);
646 			return ret;
647 		}
648 
649 		entry = mk_huge_pmd(page, vma->vm_page_prot);
650 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
651 		page_add_new_anon_rmap(page, vma, haddr);
652 		lru_cache_add_inactive_or_unevictable(page, vma);
653 		pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
654 		set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
655 		update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
656 		add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
657 		mm_inc_nr_ptes(vma->vm_mm);
658 		spin_unlock(vmf->ptl);
659 		count_vm_event(THP_FAULT_ALLOC);
660 		count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
661 	}
662 
663 	return 0;
664 unlock_release:
665 	spin_unlock(vmf->ptl);
666 release:
667 	if (pgtable)
668 		pte_free(vma->vm_mm, pgtable);
669 	put_page(page);
670 	return ret;
671 
672 }
673 
674 /*
675  * always: directly stall for all thp allocations
676  * defer: wake kswapd and fail if not immediately available
677  * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise
678  *		  fail if not immediately available
679  * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately
680  *	    available
681  * never: never stall for any thp allocation
682  */
683 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)
684 {
685 	const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE);
686 
687 	/* Always do synchronous compaction */
688 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
689 		return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);
690 
691 	/* Kick kcompactd and fail quickly */
692 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
693 		return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;
694 
695 	/* Synchronous compaction if madvised, otherwise kick kcompactd */
696 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags))
697 		return GFP_TRANSHUGE_LIGHT |
698 			(vma_madvised ? __GFP_DIRECT_RECLAIM :
699 					__GFP_KSWAPD_RECLAIM);
700 
701 	/* Only do synchronous compaction if madvised */
702 	if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
703 		return GFP_TRANSHUGE_LIGHT |
704 		       (vma_madvised ? __GFP_DIRECT_RECLAIM : 0);
705 
706 	return GFP_TRANSHUGE_LIGHT;
707 }
708 
709 /* Caller must hold page table lock. */
710 static void set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
711 		struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
712 		struct page *zero_page)
713 {
714 	pmd_t entry;
715 	if (!pmd_none(*pmd))
716 		return;
717 	entry = mk_pmd(zero_page, vma->vm_page_prot);
718 	entry = pmd_mkhuge(entry);
719 	if (pgtable)
720 		pgtable_trans_huge_deposit(mm, pmd, pgtable);
721 	set_pmd_at(mm, haddr, pmd, entry);
722 	mm_inc_nr_ptes(mm);
723 }
724 
725 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf)
726 {
727 	struct vm_area_struct *vma = vmf->vma;
728 	gfp_t gfp;
729 	struct page *page;
730 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
731 
732 	if (!transhuge_vma_suitable(vma, haddr))
733 		return VM_FAULT_FALLBACK;
734 	if (unlikely(anon_vma_prepare(vma)))
735 		return VM_FAULT_OOM;
736 	if (unlikely(khugepaged_enter(vma, vma->vm_flags)))
737 		return VM_FAULT_OOM;
738 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
739 			!mm_forbids_zeropage(vma->vm_mm) &&
740 			transparent_hugepage_use_zero_page()) {
741 		pgtable_t pgtable;
742 		struct page *zero_page;
743 		vm_fault_t ret;
744 		pgtable = pte_alloc_one(vma->vm_mm);
745 		if (unlikely(!pgtable))
746 			return VM_FAULT_OOM;
747 		zero_page = mm_get_huge_zero_page(vma->vm_mm);
748 		if (unlikely(!zero_page)) {
749 			pte_free(vma->vm_mm, pgtable);
750 			count_vm_event(THP_FAULT_FALLBACK);
751 			return VM_FAULT_FALLBACK;
752 		}
753 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
754 		ret = 0;
755 		if (pmd_none(*vmf->pmd)) {
756 			ret = check_stable_address_space(vma->vm_mm);
757 			if (ret) {
758 				spin_unlock(vmf->ptl);
759 				pte_free(vma->vm_mm, pgtable);
760 			} else if (userfaultfd_missing(vma)) {
761 				spin_unlock(vmf->ptl);
762 				pte_free(vma->vm_mm, pgtable);
763 				ret = handle_userfault(vmf, VM_UFFD_MISSING);
764 				VM_BUG_ON(ret & VM_FAULT_FALLBACK);
765 			} else {
766 				set_huge_zero_page(pgtable, vma->vm_mm, vma,
767 						   haddr, vmf->pmd, zero_page);
768 				update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
769 				spin_unlock(vmf->ptl);
770 			}
771 		} else {
772 			spin_unlock(vmf->ptl);
773 			pte_free(vma->vm_mm, pgtable);
774 		}
775 		return ret;
776 	}
777 	gfp = vma_thp_gfp_mask(vma);
778 	page = alloc_hugepage_vma(gfp, vma, haddr, HPAGE_PMD_ORDER);
779 	if (unlikely(!page)) {
780 		count_vm_event(THP_FAULT_FALLBACK);
781 		return VM_FAULT_FALLBACK;
782 	}
783 	prep_transhuge_page(page);
784 	return __do_huge_pmd_anonymous_page(vmf, page, gfp);
785 }
786 
787 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
788 		pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write,
789 		pgtable_t pgtable)
790 {
791 	struct mm_struct *mm = vma->vm_mm;
792 	pmd_t entry;
793 	spinlock_t *ptl;
794 
795 	ptl = pmd_lock(mm, pmd);
796 	if (!pmd_none(*pmd)) {
797 		if (write) {
798 			if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) {
799 				WARN_ON_ONCE(!is_huge_zero_pmd(*pmd));
800 				goto out_unlock;
801 			}
802 			entry = pmd_mkyoung(*pmd);
803 			entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
804 			if (pmdp_set_access_flags(vma, addr, pmd, entry, 1))
805 				update_mmu_cache_pmd(vma, addr, pmd);
806 		}
807 
808 		goto out_unlock;
809 	}
810 
811 	entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
812 	if (pfn_t_devmap(pfn))
813 		entry = pmd_mkdevmap(entry);
814 	if (write) {
815 		entry = pmd_mkyoung(pmd_mkdirty(entry));
816 		entry = maybe_pmd_mkwrite(entry, vma);
817 	}
818 
819 	if (pgtable) {
820 		pgtable_trans_huge_deposit(mm, pmd, pgtable);
821 		mm_inc_nr_ptes(mm);
822 		pgtable = NULL;
823 	}
824 
825 	set_pmd_at(mm, addr, pmd, entry);
826 	update_mmu_cache_pmd(vma, addr, pmd);
827 
828 out_unlock:
829 	spin_unlock(ptl);
830 	if (pgtable)
831 		pte_free(mm, pgtable);
832 }
833 
834 /**
835  * vmf_insert_pfn_pmd_prot - insert a pmd size pfn
836  * @vmf: Structure describing the fault
837  * @pfn: pfn to insert
838  * @pgprot: page protection to use
839  * @write: whether it's a write fault
840  *
841  * Insert a pmd size pfn. See vmf_insert_pfn() for additional info and
842  * also consult the vmf_insert_mixed_prot() documentation when
843  * @pgprot != @vmf->vma->vm_page_prot.
844  *
845  * Return: vm_fault_t value.
846  */
847 vm_fault_t vmf_insert_pfn_pmd_prot(struct vm_fault *vmf, pfn_t pfn,
848 				   pgprot_t pgprot, bool write)
849 {
850 	unsigned long addr = vmf->address & PMD_MASK;
851 	struct vm_area_struct *vma = vmf->vma;
852 	pgtable_t pgtable = NULL;
853 
854 	/*
855 	 * If we had pmd_special, we could avoid all these restrictions,
856 	 * but we need to be consistent with PTEs and architectures that
857 	 * can't support a 'special' bit.
858 	 */
859 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
860 			!pfn_t_devmap(pfn));
861 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
862 						(VM_PFNMAP|VM_MIXEDMAP));
863 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
864 
865 	if (addr < vma->vm_start || addr >= vma->vm_end)
866 		return VM_FAULT_SIGBUS;
867 
868 	if (arch_needs_pgtable_deposit()) {
869 		pgtable = pte_alloc_one(vma->vm_mm);
870 		if (!pgtable)
871 			return VM_FAULT_OOM;
872 	}
873 
874 	track_pfn_insert(vma, &pgprot, pfn);
875 
876 	insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable);
877 	return VM_FAULT_NOPAGE;
878 }
879 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd_prot);
880 
881 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
882 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)
883 {
884 	if (likely(vma->vm_flags & VM_WRITE))
885 		pud = pud_mkwrite(pud);
886 	return pud;
887 }
888 
889 static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr,
890 		pud_t *pud, pfn_t pfn, pgprot_t prot, bool write)
891 {
892 	struct mm_struct *mm = vma->vm_mm;
893 	pud_t entry;
894 	spinlock_t *ptl;
895 
896 	ptl = pud_lock(mm, pud);
897 	if (!pud_none(*pud)) {
898 		if (write) {
899 			if (pud_pfn(*pud) != pfn_t_to_pfn(pfn)) {
900 				WARN_ON_ONCE(!is_huge_zero_pud(*pud));
901 				goto out_unlock;
902 			}
903 			entry = pud_mkyoung(*pud);
904 			entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma);
905 			if (pudp_set_access_flags(vma, addr, pud, entry, 1))
906 				update_mmu_cache_pud(vma, addr, pud);
907 		}
908 		goto out_unlock;
909 	}
910 
911 	entry = pud_mkhuge(pfn_t_pud(pfn, prot));
912 	if (pfn_t_devmap(pfn))
913 		entry = pud_mkdevmap(entry);
914 	if (write) {
915 		entry = pud_mkyoung(pud_mkdirty(entry));
916 		entry = maybe_pud_mkwrite(entry, vma);
917 	}
918 	set_pud_at(mm, addr, pud, entry);
919 	update_mmu_cache_pud(vma, addr, pud);
920 
921 out_unlock:
922 	spin_unlock(ptl);
923 }
924 
925 /**
926  * vmf_insert_pfn_pud_prot - insert a pud size pfn
927  * @vmf: Structure describing the fault
928  * @pfn: pfn to insert
929  * @pgprot: page protection to use
930  * @write: whether it's a write fault
931  *
932  * Insert a pud size pfn. See vmf_insert_pfn() for additional info and
933  * also consult the vmf_insert_mixed_prot() documentation when
934  * @pgprot != @vmf->vma->vm_page_prot.
935  *
936  * Return: vm_fault_t value.
937  */
938 vm_fault_t vmf_insert_pfn_pud_prot(struct vm_fault *vmf, pfn_t pfn,
939 				   pgprot_t pgprot, bool write)
940 {
941 	unsigned long addr = vmf->address & PUD_MASK;
942 	struct vm_area_struct *vma = vmf->vma;
943 
944 	/*
945 	 * If we had pud_special, we could avoid all these restrictions,
946 	 * but we need to be consistent with PTEs and architectures that
947 	 * can't support a 'special' bit.
948 	 */
949 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
950 			!pfn_t_devmap(pfn));
951 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
952 						(VM_PFNMAP|VM_MIXEDMAP));
953 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
954 
955 	if (addr < vma->vm_start || addr >= vma->vm_end)
956 		return VM_FAULT_SIGBUS;
957 
958 	track_pfn_insert(vma, &pgprot, pfn);
959 
960 	insert_pfn_pud(vma, addr, vmf->pud, pfn, pgprot, write);
961 	return VM_FAULT_NOPAGE;
962 }
963 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud_prot);
964 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
965 
966 static void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
967 		pmd_t *pmd, int flags)
968 {
969 	pmd_t _pmd;
970 
971 	_pmd = pmd_mkyoung(*pmd);
972 	if (flags & FOLL_WRITE)
973 		_pmd = pmd_mkdirty(_pmd);
974 	if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
975 				pmd, _pmd, flags & FOLL_WRITE))
976 		update_mmu_cache_pmd(vma, addr, pmd);
977 }
978 
979 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
980 		pmd_t *pmd, int flags, struct dev_pagemap **pgmap)
981 {
982 	unsigned long pfn = pmd_pfn(*pmd);
983 	struct mm_struct *mm = vma->vm_mm;
984 	struct page *page;
985 
986 	assert_spin_locked(pmd_lockptr(mm, pmd));
987 
988 	/*
989 	 * When we COW a devmap PMD entry, we split it into PTEs, so we should
990 	 * not be in this function with `flags & FOLL_COW` set.
991 	 */
992 	WARN_ONCE(flags & FOLL_COW, "mm: In follow_devmap_pmd with FOLL_COW set");
993 
994 	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
995 	if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
996 			 (FOLL_PIN | FOLL_GET)))
997 		return NULL;
998 
999 	if (flags & FOLL_WRITE && !pmd_write(*pmd))
1000 		return NULL;
1001 
1002 	if (pmd_present(*pmd) && pmd_devmap(*pmd))
1003 		/* pass */;
1004 	else
1005 		return NULL;
1006 
1007 	if (flags & FOLL_TOUCH)
1008 		touch_pmd(vma, addr, pmd, flags);
1009 
1010 	/*
1011 	 * device mapped pages can only be returned if the
1012 	 * caller will manage the page reference count.
1013 	 */
1014 	if (!(flags & (FOLL_GET | FOLL_PIN)))
1015 		return ERR_PTR(-EEXIST);
1016 
1017 	pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1018 	*pgmap = get_dev_pagemap(pfn, *pgmap);
1019 	if (!*pgmap)
1020 		return ERR_PTR(-EFAULT);
1021 	page = pfn_to_page(pfn);
1022 	if (!try_grab_page(page, flags))
1023 		page = ERR_PTR(-ENOMEM);
1024 
1025 	return page;
1026 }
1027 
1028 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1029 		  pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1030 		  struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1031 {
1032 	spinlock_t *dst_ptl, *src_ptl;
1033 	struct page *src_page;
1034 	pmd_t pmd;
1035 	pgtable_t pgtable = NULL;
1036 	int ret = -ENOMEM;
1037 
1038 	/* Skip if can be re-fill on fault */
1039 	if (!vma_is_anonymous(dst_vma))
1040 		return 0;
1041 
1042 	pgtable = pte_alloc_one(dst_mm);
1043 	if (unlikely(!pgtable))
1044 		goto out;
1045 
1046 	dst_ptl = pmd_lock(dst_mm, dst_pmd);
1047 	src_ptl = pmd_lockptr(src_mm, src_pmd);
1048 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1049 
1050 	ret = -EAGAIN;
1051 	pmd = *src_pmd;
1052 
1053 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1054 	if (unlikely(is_swap_pmd(pmd))) {
1055 		swp_entry_t entry = pmd_to_swp_entry(pmd);
1056 
1057 		VM_BUG_ON(!is_pmd_migration_entry(pmd));
1058 		if (!is_readable_migration_entry(entry)) {
1059 			entry = make_readable_migration_entry(
1060 							swp_offset(entry));
1061 			pmd = swp_entry_to_pmd(entry);
1062 			if (pmd_swp_soft_dirty(*src_pmd))
1063 				pmd = pmd_swp_mksoft_dirty(pmd);
1064 			if (pmd_swp_uffd_wp(*src_pmd))
1065 				pmd = pmd_swp_mkuffd_wp(pmd);
1066 			set_pmd_at(src_mm, addr, src_pmd, pmd);
1067 		}
1068 		add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1069 		mm_inc_nr_ptes(dst_mm);
1070 		pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1071 		if (!userfaultfd_wp(dst_vma))
1072 			pmd = pmd_swp_clear_uffd_wp(pmd);
1073 		set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1074 		ret = 0;
1075 		goto out_unlock;
1076 	}
1077 #endif
1078 
1079 	if (unlikely(!pmd_trans_huge(pmd))) {
1080 		pte_free(dst_mm, pgtable);
1081 		goto out_unlock;
1082 	}
1083 	/*
1084 	 * When page table lock is held, the huge zero pmd should not be
1085 	 * under splitting since we don't split the page itself, only pmd to
1086 	 * a page table.
1087 	 */
1088 	if (is_huge_zero_pmd(pmd)) {
1089 		/*
1090 		 * get_huge_zero_page() will never allocate a new page here,
1091 		 * since we already have a zero page to copy. It just takes a
1092 		 * reference.
1093 		 */
1094 		mm_get_huge_zero_page(dst_mm);
1095 		goto out_zero_page;
1096 	}
1097 
1098 	src_page = pmd_page(pmd);
1099 	VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1100 
1101 	get_page(src_page);
1102 	if (unlikely(page_try_dup_anon_rmap(src_page, true, src_vma))) {
1103 		/* Page maybe pinned: split and retry the fault on PTEs. */
1104 		put_page(src_page);
1105 		pte_free(dst_mm, pgtable);
1106 		spin_unlock(src_ptl);
1107 		spin_unlock(dst_ptl);
1108 		__split_huge_pmd(src_vma, src_pmd, addr, false, NULL);
1109 		return -EAGAIN;
1110 	}
1111 	add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1112 out_zero_page:
1113 	mm_inc_nr_ptes(dst_mm);
1114 	pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1115 	pmdp_set_wrprotect(src_mm, addr, src_pmd);
1116 	if (!userfaultfd_wp(dst_vma))
1117 		pmd = pmd_clear_uffd_wp(pmd);
1118 	pmd = pmd_mkold(pmd_wrprotect(pmd));
1119 	set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1120 
1121 	ret = 0;
1122 out_unlock:
1123 	spin_unlock(src_ptl);
1124 	spin_unlock(dst_ptl);
1125 out:
1126 	return ret;
1127 }
1128 
1129 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1130 static void touch_pud(struct vm_area_struct *vma, unsigned long addr,
1131 		pud_t *pud, int flags)
1132 {
1133 	pud_t _pud;
1134 
1135 	_pud = pud_mkyoung(*pud);
1136 	if (flags & FOLL_WRITE)
1137 		_pud = pud_mkdirty(_pud);
1138 	if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK,
1139 				pud, _pud, flags & FOLL_WRITE))
1140 		update_mmu_cache_pud(vma, addr, pud);
1141 }
1142 
1143 struct page *follow_devmap_pud(struct vm_area_struct *vma, unsigned long addr,
1144 		pud_t *pud, int flags, struct dev_pagemap **pgmap)
1145 {
1146 	unsigned long pfn = pud_pfn(*pud);
1147 	struct mm_struct *mm = vma->vm_mm;
1148 	struct page *page;
1149 
1150 	assert_spin_locked(pud_lockptr(mm, pud));
1151 
1152 	if (flags & FOLL_WRITE && !pud_write(*pud))
1153 		return NULL;
1154 
1155 	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
1156 	if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
1157 			 (FOLL_PIN | FOLL_GET)))
1158 		return NULL;
1159 
1160 	if (pud_present(*pud) && pud_devmap(*pud))
1161 		/* pass */;
1162 	else
1163 		return NULL;
1164 
1165 	if (flags & FOLL_TOUCH)
1166 		touch_pud(vma, addr, pud, flags);
1167 
1168 	/*
1169 	 * device mapped pages can only be returned if the
1170 	 * caller will manage the page reference count.
1171 	 *
1172 	 * At least one of FOLL_GET | FOLL_PIN must be set, so assert that here:
1173 	 */
1174 	if (!(flags & (FOLL_GET | FOLL_PIN)))
1175 		return ERR_PTR(-EEXIST);
1176 
1177 	pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
1178 	*pgmap = get_dev_pagemap(pfn, *pgmap);
1179 	if (!*pgmap)
1180 		return ERR_PTR(-EFAULT);
1181 	page = pfn_to_page(pfn);
1182 	if (!try_grab_page(page, flags))
1183 		page = ERR_PTR(-ENOMEM);
1184 
1185 	return page;
1186 }
1187 
1188 int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1189 		  pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1190 		  struct vm_area_struct *vma)
1191 {
1192 	spinlock_t *dst_ptl, *src_ptl;
1193 	pud_t pud;
1194 	int ret;
1195 
1196 	dst_ptl = pud_lock(dst_mm, dst_pud);
1197 	src_ptl = pud_lockptr(src_mm, src_pud);
1198 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1199 
1200 	ret = -EAGAIN;
1201 	pud = *src_pud;
1202 	if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud)))
1203 		goto out_unlock;
1204 
1205 	/*
1206 	 * When page table lock is held, the huge zero pud should not be
1207 	 * under splitting since we don't split the page itself, only pud to
1208 	 * a page table.
1209 	 */
1210 	if (is_huge_zero_pud(pud)) {
1211 		/* No huge zero pud yet */
1212 	}
1213 
1214 	/*
1215 	 * TODO: once we support anonymous pages, use page_try_dup_anon_rmap()
1216 	 * and split if duplicating fails.
1217 	 */
1218 	pudp_set_wrprotect(src_mm, addr, src_pud);
1219 	pud = pud_mkold(pud_wrprotect(pud));
1220 	set_pud_at(dst_mm, addr, dst_pud, pud);
1221 
1222 	ret = 0;
1223 out_unlock:
1224 	spin_unlock(src_ptl);
1225 	spin_unlock(dst_ptl);
1226 	return ret;
1227 }
1228 
1229 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)
1230 {
1231 	pud_t entry;
1232 	unsigned long haddr;
1233 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1234 
1235 	vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud);
1236 	if (unlikely(!pud_same(*vmf->pud, orig_pud)))
1237 		goto unlock;
1238 
1239 	entry = pud_mkyoung(orig_pud);
1240 	if (write)
1241 		entry = pud_mkdirty(entry);
1242 	haddr = vmf->address & HPAGE_PUD_MASK;
1243 	if (pudp_set_access_flags(vmf->vma, haddr, vmf->pud, entry, write))
1244 		update_mmu_cache_pud(vmf->vma, vmf->address, vmf->pud);
1245 
1246 unlock:
1247 	spin_unlock(vmf->ptl);
1248 }
1249 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1250 
1251 void huge_pmd_set_accessed(struct vm_fault *vmf)
1252 {
1253 	pmd_t entry;
1254 	unsigned long haddr;
1255 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1256 	pmd_t orig_pmd = vmf->orig_pmd;
1257 
1258 	vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd);
1259 	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
1260 		goto unlock;
1261 
1262 	entry = pmd_mkyoung(orig_pmd);
1263 	if (write)
1264 		entry = pmd_mkdirty(entry);
1265 	haddr = vmf->address & HPAGE_PMD_MASK;
1266 	if (pmdp_set_access_flags(vmf->vma, haddr, vmf->pmd, entry, write))
1267 		update_mmu_cache_pmd(vmf->vma, vmf->address, vmf->pmd);
1268 
1269 unlock:
1270 	spin_unlock(vmf->ptl);
1271 }
1272 
1273 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
1274 {
1275 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
1276 	struct vm_area_struct *vma = vmf->vma;
1277 	struct page *page;
1278 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1279 	pmd_t orig_pmd = vmf->orig_pmd;
1280 
1281 	vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
1282 	VM_BUG_ON_VMA(!vma->anon_vma, vma);
1283 
1284 	VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE));
1285 	VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE));
1286 
1287 	if (is_huge_zero_pmd(orig_pmd))
1288 		goto fallback;
1289 
1290 	spin_lock(vmf->ptl);
1291 
1292 	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1293 		spin_unlock(vmf->ptl);
1294 		return 0;
1295 	}
1296 
1297 	page = pmd_page(orig_pmd);
1298 	VM_BUG_ON_PAGE(!PageHead(page), page);
1299 
1300 	/* Early check when only holding the PT lock. */
1301 	if (PageAnonExclusive(page))
1302 		goto reuse;
1303 
1304 	if (!trylock_page(page)) {
1305 		get_page(page);
1306 		spin_unlock(vmf->ptl);
1307 		lock_page(page);
1308 		spin_lock(vmf->ptl);
1309 		if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1310 			spin_unlock(vmf->ptl);
1311 			unlock_page(page);
1312 			put_page(page);
1313 			return 0;
1314 		}
1315 		put_page(page);
1316 	}
1317 
1318 	/* Recheck after temporarily dropping the PT lock. */
1319 	if (PageAnonExclusive(page)) {
1320 		unlock_page(page);
1321 		goto reuse;
1322 	}
1323 
1324 	/*
1325 	 * See do_wp_page(): we can only reuse the page exclusively if there are
1326 	 * no additional references. Note that we always drain the LRU
1327 	 * pagevecs immediately after adding a THP.
1328 	 */
1329 	if (page_count(page) > 1 + PageSwapCache(page) * thp_nr_pages(page))
1330 		goto unlock_fallback;
1331 	if (PageSwapCache(page))
1332 		try_to_free_swap(page);
1333 	if (page_count(page) == 1) {
1334 		pmd_t entry;
1335 
1336 		page_move_anon_rmap(page, vma);
1337 		unlock_page(page);
1338 reuse:
1339 		if (unlikely(unshare)) {
1340 			spin_unlock(vmf->ptl);
1341 			return 0;
1342 		}
1343 		entry = pmd_mkyoung(orig_pmd);
1344 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1345 		if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1))
1346 			update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1347 		spin_unlock(vmf->ptl);
1348 		return VM_FAULT_WRITE;
1349 	}
1350 
1351 unlock_fallback:
1352 	unlock_page(page);
1353 	spin_unlock(vmf->ptl);
1354 fallback:
1355 	__split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
1356 	return VM_FAULT_FALLBACK;
1357 }
1358 
1359 /*
1360  * FOLL_FORCE can write to even unwritable pmd's, but only
1361  * after we've gone through a COW cycle and they are dirty.
1362  */
1363 static inline bool can_follow_write_pmd(pmd_t pmd, unsigned int flags)
1364 {
1365 	return pmd_write(pmd) ||
1366 	       ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pmd_dirty(pmd));
1367 }
1368 
1369 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1370 				   unsigned long addr,
1371 				   pmd_t *pmd,
1372 				   unsigned int flags)
1373 {
1374 	struct mm_struct *mm = vma->vm_mm;
1375 	struct page *page = NULL;
1376 
1377 	assert_spin_locked(pmd_lockptr(mm, pmd));
1378 
1379 	if (flags & FOLL_WRITE && !can_follow_write_pmd(*pmd, flags))
1380 		goto out;
1381 
1382 	/* Avoid dumping huge zero page */
1383 	if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1384 		return ERR_PTR(-EFAULT);
1385 
1386 	/* Full NUMA hinting faults to serialise migration in fault paths */
1387 	if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
1388 		goto out;
1389 
1390 	page = pmd_page(*pmd);
1391 	VM_BUG_ON_PAGE(!PageHead(page) && !is_zone_device_page(page), page);
1392 
1393 	if (!pmd_write(*pmd) && gup_must_unshare(flags, page))
1394 		return ERR_PTR(-EMLINK);
1395 
1396 	VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
1397 			!PageAnonExclusive(page), page);
1398 
1399 	if (!try_grab_page(page, flags))
1400 		return ERR_PTR(-ENOMEM);
1401 
1402 	if (flags & FOLL_TOUCH)
1403 		touch_pmd(vma, addr, pmd, flags);
1404 
1405 	page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1406 	VM_BUG_ON_PAGE(!PageCompound(page) && !is_zone_device_page(page), page);
1407 
1408 out:
1409 	return page;
1410 }
1411 
1412 /* NUMA hinting page fault entry point for trans huge pmds */
1413 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf)
1414 {
1415 	struct vm_area_struct *vma = vmf->vma;
1416 	pmd_t oldpmd = vmf->orig_pmd;
1417 	pmd_t pmd;
1418 	struct page *page;
1419 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1420 	int page_nid = NUMA_NO_NODE;
1421 	int target_nid, last_cpupid = -1;
1422 	bool migrated = false;
1423 	bool was_writable = pmd_savedwrite(oldpmd);
1424 	int flags = 0;
1425 
1426 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1427 	if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1428 		spin_unlock(vmf->ptl);
1429 		goto out;
1430 	}
1431 
1432 	pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1433 	page = vm_normal_page_pmd(vma, haddr, pmd);
1434 	if (!page)
1435 		goto out_map;
1436 
1437 	/* See similar comment in do_numa_page for explanation */
1438 	if (!was_writable)
1439 		flags |= TNF_NO_GROUP;
1440 
1441 	page_nid = page_to_nid(page);
1442 	last_cpupid = page_cpupid_last(page);
1443 	target_nid = numa_migrate_prep(page, vma, haddr, page_nid,
1444 				       &flags);
1445 
1446 	if (target_nid == NUMA_NO_NODE) {
1447 		put_page(page);
1448 		goto out_map;
1449 	}
1450 
1451 	spin_unlock(vmf->ptl);
1452 
1453 	migrated = migrate_misplaced_page(page, vma, target_nid);
1454 	if (migrated) {
1455 		flags |= TNF_MIGRATED;
1456 		page_nid = target_nid;
1457 	} else {
1458 		flags |= TNF_MIGRATE_FAIL;
1459 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1460 		if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1461 			spin_unlock(vmf->ptl);
1462 			goto out;
1463 		}
1464 		goto out_map;
1465 	}
1466 
1467 out:
1468 	if (page_nid != NUMA_NO_NODE)
1469 		task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR,
1470 				flags);
1471 
1472 	return 0;
1473 
1474 out_map:
1475 	/* Restore the PMD */
1476 	pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1477 	pmd = pmd_mkyoung(pmd);
1478 	if (was_writable)
1479 		pmd = pmd_mkwrite(pmd);
1480 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
1481 	update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1482 	spin_unlock(vmf->ptl);
1483 	goto out;
1484 }
1485 
1486 /*
1487  * Return true if we do MADV_FREE successfully on entire pmd page.
1488  * Otherwise, return false.
1489  */
1490 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1491 		pmd_t *pmd, unsigned long addr, unsigned long next)
1492 {
1493 	spinlock_t *ptl;
1494 	pmd_t orig_pmd;
1495 	struct page *page;
1496 	struct mm_struct *mm = tlb->mm;
1497 	bool ret = false;
1498 
1499 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1500 
1501 	ptl = pmd_trans_huge_lock(pmd, vma);
1502 	if (!ptl)
1503 		goto out_unlocked;
1504 
1505 	orig_pmd = *pmd;
1506 	if (is_huge_zero_pmd(orig_pmd))
1507 		goto out;
1508 
1509 	if (unlikely(!pmd_present(orig_pmd))) {
1510 		VM_BUG_ON(thp_migration_supported() &&
1511 				  !is_pmd_migration_entry(orig_pmd));
1512 		goto out;
1513 	}
1514 
1515 	page = pmd_page(orig_pmd);
1516 	/*
1517 	 * If other processes are mapping this page, we couldn't discard
1518 	 * the page unless they all do MADV_FREE so let's skip the page.
1519 	 */
1520 	if (total_mapcount(page) != 1)
1521 		goto out;
1522 
1523 	if (!trylock_page(page))
1524 		goto out;
1525 
1526 	/*
1527 	 * If user want to discard part-pages of THP, split it so MADV_FREE
1528 	 * will deactivate only them.
1529 	 */
1530 	if (next - addr != HPAGE_PMD_SIZE) {
1531 		get_page(page);
1532 		spin_unlock(ptl);
1533 		split_huge_page(page);
1534 		unlock_page(page);
1535 		put_page(page);
1536 		goto out_unlocked;
1537 	}
1538 
1539 	if (PageDirty(page))
1540 		ClearPageDirty(page);
1541 	unlock_page(page);
1542 
1543 	if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1544 		pmdp_invalidate(vma, addr, pmd);
1545 		orig_pmd = pmd_mkold(orig_pmd);
1546 		orig_pmd = pmd_mkclean(orig_pmd);
1547 
1548 		set_pmd_at(mm, addr, pmd, orig_pmd);
1549 		tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1550 	}
1551 
1552 	mark_page_lazyfree(page);
1553 	ret = true;
1554 out:
1555 	spin_unlock(ptl);
1556 out_unlocked:
1557 	return ret;
1558 }
1559 
1560 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
1561 {
1562 	pgtable_t pgtable;
1563 
1564 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1565 	pte_free(mm, pgtable);
1566 	mm_dec_nr_ptes(mm);
1567 }
1568 
1569 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1570 		 pmd_t *pmd, unsigned long addr)
1571 {
1572 	pmd_t orig_pmd;
1573 	spinlock_t *ptl;
1574 
1575 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1576 
1577 	ptl = __pmd_trans_huge_lock(pmd, vma);
1578 	if (!ptl)
1579 		return 0;
1580 	/*
1581 	 * For architectures like ppc64 we look at deposited pgtable
1582 	 * when calling pmdp_huge_get_and_clear. So do the
1583 	 * pgtable_trans_huge_withdraw after finishing pmdp related
1584 	 * operations.
1585 	 */
1586 	orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
1587 						tlb->fullmm);
1588 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1589 	if (vma_is_special_huge(vma)) {
1590 		if (arch_needs_pgtable_deposit())
1591 			zap_deposited_table(tlb->mm, pmd);
1592 		spin_unlock(ptl);
1593 	} else if (is_huge_zero_pmd(orig_pmd)) {
1594 		zap_deposited_table(tlb->mm, pmd);
1595 		spin_unlock(ptl);
1596 	} else {
1597 		struct page *page = NULL;
1598 		int flush_needed = 1;
1599 
1600 		if (pmd_present(orig_pmd)) {
1601 			page = pmd_page(orig_pmd);
1602 			page_remove_rmap(page, vma, true);
1603 			VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1604 			VM_BUG_ON_PAGE(!PageHead(page), page);
1605 		} else if (thp_migration_supported()) {
1606 			swp_entry_t entry;
1607 
1608 			VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
1609 			entry = pmd_to_swp_entry(orig_pmd);
1610 			page = pfn_swap_entry_to_page(entry);
1611 			flush_needed = 0;
1612 		} else
1613 			WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
1614 
1615 		if (PageAnon(page)) {
1616 			zap_deposited_table(tlb->mm, pmd);
1617 			add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1618 		} else {
1619 			if (arch_needs_pgtable_deposit())
1620 				zap_deposited_table(tlb->mm, pmd);
1621 			add_mm_counter(tlb->mm, mm_counter_file(page), -HPAGE_PMD_NR);
1622 		}
1623 
1624 		spin_unlock(ptl);
1625 		if (flush_needed)
1626 			tlb_remove_page_size(tlb, page, HPAGE_PMD_SIZE);
1627 	}
1628 	return 1;
1629 }
1630 
1631 #ifndef pmd_move_must_withdraw
1632 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
1633 					 spinlock_t *old_pmd_ptl,
1634 					 struct vm_area_struct *vma)
1635 {
1636 	/*
1637 	 * With split pmd lock we also need to move preallocated
1638 	 * PTE page table if new_pmd is on different PMD page table.
1639 	 *
1640 	 * We also don't deposit and withdraw tables for file pages.
1641 	 */
1642 	return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
1643 }
1644 #endif
1645 
1646 static pmd_t move_soft_dirty_pmd(pmd_t pmd)
1647 {
1648 #ifdef CONFIG_MEM_SOFT_DIRTY
1649 	if (unlikely(is_pmd_migration_entry(pmd)))
1650 		pmd = pmd_swp_mksoft_dirty(pmd);
1651 	else if (pmd_present(pmd))
1652 		pmd = pmd_mksoft_dirty(pmd);
1653 #endif
1654 	return pmd;
1655 }
1656 
1657 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
1658 		  unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
1659 {
1660 	spinlock_t *old_ptl, *new_ptl;
1661 	pmd_t pmd;
1662 	struct mm_struct *mm = vma->vm_mm;
1663 	bool force_flush = false;
1664 
1665 	/*
1666 	 * The destination pmd shouldn't be established, free_pgtables()
1667 	 * should have release it.
1668 	 */
1669 	if (WARN_ON(!pmd_none(*new_pmd))) {
1670 		VM_BUG_ON(pmd_trans_huge(*new_pmd));
1671 		return false;
1672 	}
1673 
1674 	/*
1675 	 * We don't have to worry about the ordering of src and dst
1676 	 * ptlocks because exclusive mmap_lock prevents deadlock.
1677 	 */
1678 	old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1679 	if (old_ptl) {
1680 		new_ptl = pmd_lockptr(mm, new_pmd);
1681 		if (new_ptl != old_ptl)
1682 			spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1683 		pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1684 		if (pmd_present(pmd))
1685 			force_flush = true;
1686 		VM_BUG_ON(!pmd_none(*new_pmd));
1687 
1688 		if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
1689 			pgtable_t pgtable;
1690 			pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1691 			pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1692 		}
1693 		pmd = move_soft_dirty_pmd(pmd);
1694 		set_pmd_at(mm, new_addr, new_pmd, pmd);
1695 		if (force_flush)
1696 			flush_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
1697 		if (new_ptl != old_ptl)
1698 			spin_unlock(new_ptl);
1699 		spin_unlock(old_ptl);
1700 		return true;
1701 	}
1702 	return false;
1703 }
1704 
1705 /*
1706  * Returns
1707  *  - 0 if PMD could not be locked
1708  *  - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
1709  *      or if prot_numa but THP migration is not supported
1710  *  - HPAGE_PMD_NR if protections changed and TLB flush necessary
1711  */
1712 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1713 		    pmd_t *pmd, unsigned long addr, pgprot_t newprot,
1714 		    unsigned long cp_flags)
1715 {
1716 	struct mm_struct *mm = vma->vm_mm;
1717 	spinlock_t *ptl;
1718 	pmd_t oldpmd, entry;
1719 	bool preserve_write;
1720 	int ret;
1721 	bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
1722 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
1723 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
1724 
1725 	tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1726 
1727 	if (prot_numa && !thp_migration_supported())
1728 		return 1;
1729 
1730 	ptl = __pmd_trans_huge_lock(pmd, vma);
1731 	if (!ptl)
1732 		return 0;
1733 
1734 	preserve_write = prot_numa && pmd_write(*pmd);
1735 	ret = 1;
1736 
1737 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1738 	if (is_swap_pmd(*pmd)) {
1739 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
1740 		struct page *page = pfn_swap_entry_to_page(entry);
1741 
1742 		VM_BUG_ON(!is_pmd_migration_entry(*pmd));
1743 		if (is_writable_migration_entry(entry)) {
1744 			pmd_t newpmd;
1745 			/*
1746 			 * A protection check is difficult so
1747 			 * just be safe and disable write
1748 			 */
1749 			if (PageAnon(page))
1750 				entry = make_readable_exclusive_migration_entry(swp_offset(entry));
1751 			else
1752 				entry = make_readable_migration_entry(swp_offset(entry));
1753 			newpmd = swp_entry_to_pmd(entry);
1754 			if (pmd_swp_soft_dirty(*pmd))
1755 				newpmd = pmd_swp_mksoft_dirty(newpmd);
1756 			if (pmd_swp_uffd_wp(*pmd))
1757 				newpmd = pmd_swp_mkuffd_wp(newpmd);
1758 			set_pmd_at(mm, addr, pmd, newpmd);
1759 		}
1760 		goto unlock;
1761 	}
1762 #endif
1763 
1764 	if (prot_numa) {
1765 		struct page *page;
1766 		/*
1767 		 * Avoid trapping faults against the zero page. The read-only
1768 		 * data is likely to be read-cached on the local CPU and
1769 		 * local/remote hits to the zero page are not interesting.
1770 		 */
1771 		if (is_huge_zero_pmd(*pmd))
1772 			goto unlock;
1773 
1774 		if (pmd_protnone(*pmd))
1775 			goto unlock;
1776 
1777 		page = pmd_page(*pmd);
1778 		/*
1779 		 * Skip scanning top tier node if normal numa
1780 		 * balancing is disabled
1781 		 */
1782 		if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
1783 		    node_is_toptier(page_to_nid(page)))
1784 			goto unlock;
1785 	}
1786 	/*
1787 	 * In case prot_numa, we are under mmap_read_lock(mm). It's critical
1788 	 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
1789 	 * which is also under mmap_read_lock(mm):
1790 	 *
1791 	 *	CPU0:				CPU1:
1792 	 *				change_huge_pmd(prot_numa=1)
1793 	 *				 pmdp_huge_get_and_clear_notify()
1794 	 * madvise_dontneed()
1795 	 *  zap_pmd_range()
1796 	 *   pmd_trans_huge(*pmd) == 0 (without ptl)
1797 	 *   // skip the pmd
1798 	 *				 set_pmd_at();
1799 	 *				 // pmd is re-established
1800 	 *
1801 	 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
1802 	 * which may break userspace.
1803 	 *
1804 	 * pmdp_invalidate_ad() is required to make sure we don't miss
1805 	 * dirty/young flags set by hardware.
1806 	 */
1807 	oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
1808 
1809 	entry = pmd_modify(oldpmd, newprot);
1810 	if (preserve_write)
1811 		entry = pmd_mk_savedwrite(entry);
1812 	if (uffd_wp) {
1813 		entry = pmd_wrprotect(entry);
1814 		entry = pmd_mkuffd_wp(entry);
1815 	} else if (uffd_wp_resolve) {
1816 		/*
1817 		 * Leave the write bit to be handled by PF interrupt
1818 		 * handler, then things like COW could be properly
1819 		 * handled.
1820 		 */
1821 		entry = pmd_clear_uffd_wp(entry);
1822 	}
1823 	ret = HPAGE_PMD_NR;
1824 	set_pmd_at(mm, addr, pmd, entry);
1825 
1826 	if (huge_pmd_needs_flush(oldpmd, entry))
1827 		tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
1828 
1829 	BUG_ON(vma_is_anonymous(vma) && !preserve_write && pmd_write(entry));
1830 unlock:
1831 	spin_unlock(ptl);
1832 	return ret;
1833 }
1834 
1835 /*
1836  * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
1837  *
1838  * Note that if it returns page table lock pointer, this routine returns without
1839  * unlocking page table lock. So callers must unlock it.
1840  */
1841 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1842 {
1843 	spinlock_t *ptl;
1844 	ptl = pmd_lock(vma->vm_mm, pmd);
1845 	if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
1846 			pmd_devmap(*pmd)))
1847 		return ptl;
1848 	spin_unlock(ptl);
1849 	return NULL;
1850 }
1851 
1852 /*
1853  * Returns true if a given pud maps a thp, false otherwise.
1854  *
1855  * Note that if it returns true, this routine returns without unlocking page
1856  * table lock. So callers must unlock it.
1857  */
1858 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
1859 {
1860 	spinlock_t *ptl;
1861 
1862 	ptl = pud_lock(vma->vm_mm, pud);
1863 	if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
1864 		return ptl;
1865 	spin_unlock(ptl);
1866 	return NULL;
1867 }
1868 
1869 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1870 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
1871 		 pud_t *pud, unsigned long addr)
1872 {
1873 	spinlock_t *ptl;
1874 
1875 	ptl = __pud_trans_huge_lock(pud, vma);
1876 	if (!ptl)
1877 		return 0;
1878 	/*
1879 	 * For architectures like ppc64 we look at deposited pgtable
1880 	 * when calling pudp_huge_get_and_clear. So do the
1881 	 * pgtable_trans_huge_withdraw after finishing pudp related
1882 	 * operations.
1883 	 */
1884 	pudp_huge_get_and_clear_full(tlb->mm, addr, pud, tlb->fullmm);
1885 	tlb_remove_pud_tlb_entry(tlb, pud, addr);
1886 	if (vma_is_special_huge(vma)) {
1887 		spin_unlock(ptl);
1888 		/* No zero page support yet */
1889 	} else {
1890 		/* No support for anonymous PUD pages yet */
1891 		BUG();
1892 	}
1893 	return 1;
1894 }
1895 
1896 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
1897 		unsigned long haddr)
1898 {
1899 	VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
1900 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
1901 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
1902 	VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
1903 
1904 	count_vm_event(THP_SPLIT_PUD);
1905 
1906 	pudp_huge_clear_flush_notify(vma, haddr, pud);
1907 }
1908 
1909 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
1910 		unsigned long address)
1911 {
1912 	spinlock_t *ptl;
1913 	struct mmu_notifier_range range;
1914 
1915 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1916 				address & HPAGE_PUD_MASK,
1917 				(address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
1918 	mmu_notifier_invalidate_range_start(&range);
1919 	ptl = pud_lock(vma->vm_mm, pud);
1920 	if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
1921 		goto out;
1922 	__split_huge_pud_locked(vma, pud, range.start);
1923 
1924 out:
1925 	spin_unlock(ptl);
1926 	/*
1927 	 * No need to double call mmu_notifier->invalidate_range() callback as
1928 	 * the above pudp_huge_clear_flush_notify() did already call it.
1929 	 */
1930 	mmu_notifier_invalidate_range_only_end(&range);
1931 }
1932 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1933 
1934 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
1935 		unsigned long haddr, pmd_t *pmd)
1936 {
1937 	struct mm_struct *mm = vma->vm_mm;
1938 	pgtable_t pgtable;
1939 	pmd_t _pmd;
1940 	int i;
1941 
1942 	/*
1943 	 * Leave pmd empty until pte is filled note that it is fine to delay
1944 	 * notification until mmu_notifier_invalidate_range_end() as we are
1945 	 * replacing a zero pmd write protected page with a zero pte write
1946 	 * protected page.
1947 	 *
1948 	 * See Documentation/vm/mmu_notifier.rst
1949 	 */
1950 	pmdp_huge_clear_flush(vma, haddr, pmd);
1951 
1952 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1953 	pmd_populate(mm, &_pmd, pgtable);
1954 
1955 	for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1956 		pte_t *pte, entry;
1957 		entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
1958 		entry = pte_mkspecial(entry);
1959 		pte = pte_offset_map(&_pmd, haddr);
1960 		VM_BUG_ON(!pte_none(*pte));
1961 		set_pte_at(mm, haddr, pte, entry);
1962 		pte_unmap(pte);
1963 	}
1964 	smp_wmb(); /* make pte visible before pmd */
1965 	pmd_populate(mm, pmd, pgtable);
1966 }
1967 
1968 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
1969 		unsigned long haddr, bool freeze)
1970 {
1971 	struct mm_struct *mm = vma->vm_mm;
1972 	struct page *page;
1973 	pgtable_t pgtable;
1974 	pmd_t old_pmd, _pmd;
1975 	bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
1976 	bool anon_exclusive = false;
1977 	unsigned long addr;
1978 	int i;
1979 
1980 	VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
1981 	VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
1982 	VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
1983 	VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
1984 				&& !pmd_devmap(*pmd));
1985 
1986 	count_vm_event(THP_SPLIT_PMD);
1987 
1988 	if (!vma_is_anonymous(vma)) {
1989 		old_pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1990 		/*
1991 		 * We are going to unmap this huge page. So
1992 		 * just go ahead and zap it
1993 		 */
1994 		if (arch_needs_pgtable_deposit())
1995 			zap_deposited_table(mm, pmd);
1996 		if (vma_is_special_huge(vma))
1997 			return;
1998 		if (unlikely(is_pmd_migration_entry(old_pmd))) {
1999 			swp_entry_t entry;
2000 
2001 			entry = pmd_to_swp_entry(old_pmd);
2002 			page = pfn_swap_entry_to_page(entry);
2003 		} else {
2004 			page = pmd_page(old_pmd);
2005 			if (!PageDirty(page) && pmd_dirty(old_pmd))
2006 				set_page_dirty(page);
2007 			if (!PageReferenced(page) && pmd_young(old_pmd))
2008 				SetPageReferenced(page);
2009 			page_remove_rmap(page, vma, true);
2010 			put_page(page);
2011 		}
2012 		add_mm_counter(mm, mm_counter_file(page), -HPAGE_PMD_NR);
2013 		return;
2014 	}
2015 
2016 	if (is_huge_zero_pmd(*pmd)) {
2017 		/*
2018 		 * FIXME: Do we want to invalidate secondary mmu by calling
2019 		 * mmu_notifier_invalidate_range() see comments below inside
2020 		 * __split_huge_pmd() ?
2021 		 *
2022 		 * We are going from a zero huge page write protected to zero
2023 		 * small page also write protected so it does not seems useful
2024 		 * to invalidate secondary mmu at this time.
2025 		 */
2026 		return __split_huge_zero_page_pmd(vma, haddr, pmd);
2027 	}
2028 
2029 	/*
2030 	 * Up to this point the pmd is present and huge and userland has the
2031 	 * whole access to the hugepage during the split (which happens in
2032 	 * place). If we overwrite the pmd with the not-huge version pointing
2033 	 * to the pte here (which of course we could if all CPUs were bug
2034 	 * free), userland could trigger a small page size TLB miss on the
2035 	 * small sized TLB while the hugepage TLB entry is still established in
2036 	 * the huge TLB. Some CPU doesn't like that.
2037 	 * See http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2038 	 * 383 on page 105. Intel should be safe but is also warns that it's
2039 	 * only safe if the permission and cache attributes of the two entries
2040 	 * loaded in the two TLB is identical (which should be the case here).
2041 	 * But it is generally safer to never allow small and huge TLB entries
2042 	 * for the same virtual address to be loaded simultaneously. So instead
2043 	 * of doing "pmd_populate(); flush_pmd_tlb_range();" we first mark the
2044 	 * current pmd notpresent (atomically because here the pmd_trans_huge
2045 	 * must remain set at all times on the pmd until the split is complete
2046 	 * for this pmd), then we flush the SMP TLB and finally we write the
2047 	 * non-huge version of the pmd entry with pmd_populate.
2048 	 */
2049 	old_pmd = pmdp_invalidate(vma, haddr, pmd);
2050 
2051 	pmd_migration = is_pmd_migration_entry(old_pmd);
2052 	if (unlikely(pmd_migration)) {
2053 		swp_entry_t entry;
2054 
2055 		entry = pmd_to_swp_entry(old_pmd);
2056 		page = pfn_swap_entry_to_page(entry);
2057 		write = is_writable_migration_entry(entry);
2058 		if (PageAnon(page))
2059 			anon_exclusive = is_readable_exclusive_migration_entry(entry);
2060 		young = false;
2061 		soft_dirty = pmd_swp_soft_dirty(old_pmd);
2062 		uffd_wp = pmd_swp_uffd_wp(old_pmd);
2063 	} else {
2064 		page = pmd_page(old_pmd);
2065 		if (pmd_dirty(old_pmd))
2066 			SetPageDirty(page);
2067 		write = pmd_write(old_pmd);
2068 		young = pmd_young(old_pmd);
2069 		soft_dirty = pmd_soft_dirty(old_pmd);
2070 		uffd_wp = pmd_uffd_wp(old_pmd);
2071 
2072 		VM_BUG_ON_PAGE(!page_count(page), page);
2073 		page_ref_add(page, HPAGE_PMD_NR - 1);
2074 
2075 		/*
2076 		 * Without "freeze", we'll simply split the PMD, propagating the
2077 		 * PageAnonExclusive() flag for each PTE by setting it for
2078 		 * each subpage -- no need to (temporarily) clear.
2079 		 *
2080 		 * With "freeze" we want to replace mapped pages by
2081 		 * migration entries right away. This is only possible if we
2082 		 * managed to clear PageAnonExclusive() -- see
2083 		 * set_pmd_migration_entry().
2084 		 *
2085 		 * In case we cannot clear PageAnonExclusive(), split the PMD
2086 		 * only and let try_to_migrate_one() fail later.
2087 		 */
2088 		anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
2089 		if (freeze && anon_exclusive && page_try_share_anon_rmap(page))
2090 			freeze = false;
2091 	}
2092 
2093 	/*
2094 	 * Withdraw the table only after we mark the pmd entry invalid.
2095 	 * This's critical for some architectures (Power).
2096 	 */
2097 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2098 	pmd_populate(mm, &_pmd, pgtable);
2099 
2100 	for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2101 		pte_t entry, *pte;
2102 		/*
2103 		 * Note that NUMA hinting access restrictions are not
2104 		 * transferred to avoid any possibility of altering
2105 		 * permissions across VMAs.
2106 		 */
2107 		if (freeze || pmd_migration) {
2108 			swp_entry_t swp_entry;
2109 			if (write)
2110 				swp_entry = make_writable_migration_entry(
2111 							page_to_pfn(page + i));
2112 			else if (anon_exclusive)
2113 				swp_entry = make_readable_exclusive_migration_entry(
2114 							page_to_pfn(page + i));
2115 			else
2116 				swp_entry = make_readable_migration_entry(
2117 							page_to_pfn(page + i));
2118 			entry = swp_entry_to_pte(swp_entry);
2119 			if (soft_dirty)
2120 				entry = pte_swp_mksoft_dirty(entry);
2121 			if (uffd_wp)
2122 				entry = pte_swp_mkuffd_wp(entry);
2123 		} else {
2124 			entry = mk_pte(page + i, READ_ONCE(vma->vm_page_prot));
2125 			entry = maybe_mkwrite(entry, vma);
2126 			if (anon_exclusive)
2127 				SetPageAnonExclusive(page + i);
2128 			if (!write)
2129 				entry = pte_wrprotect(entry);
2130 			if (!young)
2131 				entry = pte_mkold(entry);
2132 			if (soft_dirty)
2133 				entry = pte_mksoft_dirty(entry);
2134 			if (uffd_wp)
2135 				entry = pte_mkuffd_wp(entry);
2136 		}
2137 		pte = pte_offset_map(&_pmd, addr);
2138 		BUG_ON(!pte_none(*pte));
2139 		set_pte_at(mm, addr, pte, entry);
2140 		if (!pmd_migration)
2141 			atomic_inc(&page[i]._mapcount);
2142 		pte_unmap(pte);
2143 	}
2144 
2145 	if (!pmd_migration) {
2146 		/*
2147 		 * Set PG_double_map before dropping compound_mapcount to avoid
2148 		 * false-negative page_mapped().
2149 		 */
2150 		if (compound_mapcount(page) > 1 &&
2151 		    !TestSetPageDoubleMap(page)) {
2152 			for (i = 0; i < HPAGE_PMD_NR; i++)
2153 				atomic_inc(&page[i]._mapcount);
2154 		}
2155 
2156 		lock_page_memcg(page);
2157 		if (atomic_add_negative(-1, compound_mapcount_ptr(page))) {
2158 			/* Last compound_mapcount is gone. */
2159 			__mod_lruvec_page_state(page, NR_ANON_THPS,
2160 						-HPAGE_PMD_NR);
2161 			if (TestClearPageDoubleMap(page)) {
2162 				/* No need in mapcount reference anymore */
2163 				for (i = 0; i < HPAGE_PMD_NR; i++)
2164 					atomic_dec(&page[i]._mapcount);
2165 			}
2166 		}
2167 		unlock_page_memcg(page);
2168 
2169 		/* Above is effectively page_remove_rmap(page, vma, true) */
2170 		munlock_vma_page(page, vma, true);
2171 	}
2172 
2173 	smp_wmb(); /* make pte visible before pmd */
2174 	pmd_populate(mm, pmd, pgtable);
2175 
2176 	if (freeze) {
2177 		for (i = 0; i < HPAGE_PMD_NR; i++) {
2178 			page_remove_rmap(page + i, vma, false);
2179 			put_page(page + i);
2180 		}
2181 	}
2182 }
2183 
2184 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2185 		unsigned long address, bool freeze, struct folio *folio)
2186 {
2187 	spinlock_t *ptl;
2188 	struct mmu_notifier_range range;
2189 
2190 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
2191 				address & HPAGE_PMD_MASK,
2192 				(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2193 	mmu_notifier_invalidate_range_start(&range);
2194 	ptl = pmd_lock(vma->vm_mm, pmd);
2195 
2196 	/*
2197 	 * If caller asks to setup a migration entry, we need a folio to check
2198 	 * pmd against. Otherwise we can end up replacing wrong folio.
2199 	 */
2200 	VM_BUG_ON(freeze && !folio);
2201 	VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
2202 
2203 	if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
2204 	    is_pmd_migration_entry(*pmd)) {
2205 		if (folio && folio != page_folio(pmd_page(*pmd)))
2206 			goto out;
2207 		__split_huge_pmd_locked(vma, pmd, range.start, freeze);
2208 	}
2209 
2210 out:
2211 	spin_unlock(ptl);
2212 	/*
2213 	 * No need to double call mmu_notifier->invalidate_range() callback.
2214 	 * They are 3 cases to consider inside __split_huge_pmd_locked():
2215 	 *  1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious
2216 	 *  2) __split_huge_zero_page_pmd() read only zero page and any write
2217 	 *    fault will trigger a flush_notify before pointing to a new page
2218 	 *    (it is fine if the secondary mmu keeps pointing to the old zero
2219 	 *    page in the meantime)
2220 	 *  3) Split a huge pmd into pte pointing to the same page. No need
2221 	 *     to invalidate secondary tlb entry they are all still valid.
2222 	 *     any further changes to individual pte will notify. So no need
2223 	 *     to call mmu_notifier->invalidate_range()
2224 	 */
2225 	mmu_notifier_invalidate_range_only_end(&range);
2226 }
2227 
2228 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2229 		bool freeze, struct folio *folio)
2230 {
2231 	pgd_t *pgd;
2232 	p4d_t *p4d;
2233 	pud_t *pud;
2234 	pmd_t *pmd;
2235 
2236 	pgd = pgd_offset(vma->vm_mm, address);
2237 	if (!pgd_present(*pgd))
2238 		return;
2239 
2240 	p4d = p4d_offset(pgd, address);
2241 	if (!p4d_present(*p4d))
2242 		return;
2243 
2244 	pud = pud_offset(p4d, address);
2245 	if (!pud_present(*pud))
2246 		return;
2247 
2248 	pmd = pmd_offset(pud, address);
2249 
2250 	__split_huge_pmd(vma, pmd, address, freeze, folio);
2251 }
2252 
2253 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2254 {
2255 	/*
2256 	 * If the new address isn't hpage aligned and it could previously
2257 	 * contain an hugepage: check if we need to split an huge pmd.
2258 	 */
2259 	if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2260 	    range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2261 			 ALIGN(address, HPAGE_PMD_SIZE)))
2262 		split_huge_pmd_address(vma, address, false, NULL);
2263 }
2264 
2265 void vma_adjust_trans_huge(struct vm_area_struct *vma,
2266 			     unsigned long start,
2267 			     unsigned long end,
2268 			     long adjust_next)
2269 {
2270 	/* Check if we need to split start first. */
2271 	split_huge_pmd_if_needed(vma, start);
2272 
2273 	/* Check if we need to split end next. */
2274 	split_huge_pmd_if_needed(vma, end);
2275 
2276 	/*
2277 	 * If we're also updating the vma->vm_next->vm_start,
2278 	 * check if we need to split it.
2279 	 */
2280 	if (adjust_next > 0) {
2281 		struct vm_area_struct *next = vma->vm_next;
2282 		unsigned long nstart = next->vm_start;
2283 		nstart += adjust_next;
2284 		split_huge_pmd_if_needed(next, nstart);
2285 	}
2286 }
2287 
2288 static void unmap_page(struct page *page)
2289 {
2290 	struct folio *folio = page_folio(page);
2291 	enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2292 		TTU_SYNC;
2293 
2294 	VM_BUG_ON_PAGE(!PageHead(page), page);
2295 
2296 	/*
2297 	 * Anon pages need migration entries to preserve them, but file
2298 	 * pages can simply be left unmapped, then faulted back on demand.
2299 	 * If that is ever changed (perhaps for mlock), update remap_page().
2300 	 */
2301 	if (folio_test_anon(folio))
2302 		try_to_migrate(folio, ttu_flags);
2303 	else
2304 		try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
2305 }
2306 
2307 static void remap_page(struct folio *folio, unsigned long nr)
2308 {
2309 	int i = 0;
2310 
2311 	/* If unmap_page() uses try_to_migrate() on file, remove this check */
2312 	if (!folio_test_anon(folio))
2313 		return;
2314 	for (;;) {
2315 		remove_migration_ptes(folio, folio, true);
2316 		i += folio_nr_pages(folio);
2317 		if (i >= nr)
2318 			break;
2319 		folio = folio_next(folio);
2320 	}
2321 }
2322 
2323 static void lru_add_page_tail(struct page *head, struct page *tail,
2324 		struct lruvec *lruvec, struct list_head *list)
2325 {
2326 	VM_BUG_ON_PAGE(!PageHead(head), head);
2327 	VM_BUG_ON_PAGE(PageCompound(tail), head);
2328 	VM_BUG_ON_PAGE(PageLRU(tail), head);
2329 	lockdep_assert_held(&lruvec->lru_lock);
2330 
2331 	if (list) {
2332 		/* page reclaim is reclaiming a huge page */
2333 		VM_WARN_ON(PageLRU(head));
2334 		get_page(tail);
2335 		list_add_tail(&tail->lru, list);
2336 	} else {
2337 		/* head is still on lru (and we have it frozen) */
2338 		VM_WARN_ON(!PageLRU(head));
2339 		if (PageUnevictable(tail))
2340 			tail->mlock_count = 0;
2341 		else
2342 			list_add_tail(&tail->lru, &head->lru);
2343 		SetPageLRU(tail);
2344 	}
2345 }
2346 
2347 static void __split_huge_page_tail(struct page *head, int tail,
2348 		struct lruvec *lruvec, struct list_head *list)
2349 {
2350 	struct page *page_tail = head + tail;
2351 
2352 	VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
2353 
2354 	/*
2355 	 * Clone page flags before unfreezing refcount.
2356 	 *
2357 	 * After successful get_page_unless_zero() might follow flags change,
2358 	 * for example lock_page() which set PG_waiters.
2359 	 *
2360 	 * Note that for mapped sub-pages of an anonymous THP,
2361 	 * PG_anon_exclusive has been cleared in unmap_page() and is stored in
2362 	 * the migration entry instead from where remap_page() will restore it.
2363 	 * We can still have PG_anon_exclusive set on effectively unmapped and
2364 	 * unreferenced sub-pages of an anonymous THP: we can simply drop
2365 	 * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
2366 	 */
2367 	page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
2368 	page_tail->flags |= (head->flags &
2369 			((1L << PG_referenced) |
2370 			 (1L << PG_swapbacked) |
2371 			 (1L << PG_swapcache) |
2372 			 (1L << PG_mlocked) |
2373 			 (1L << PG_uptodate) |
2374 			 (1L << PG_active) |
2375 			 (1L << PG_workingset) |
2376 			 (1L << PG_locked) |
2377 			 (1L << PG_unevictable) |
2378 #ifdef CONFIG_64BIT
2379 			 (1L << PG_arch_2) |
2380 #endif
2381 			 (1L << PG_dirty)));
2382 
2383 	/* ->mapping in first tail page is compound_mapcount */
2384 	VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
2385 			page_tail);
2386 	page_tail->mapping = head->mapping;
2387 	page_tail->index = head->index + tail;
2388 
2389 	/* Page flags must be visible before we make the page non-compound. */
2390 	smp_wmb();
2391 
2392 	/*
2393 	 * Clear PageTail before unfreezing page refcount.
2394 	 *
2395 	 * After successful get_page_unless_zero() might follow put_page()
2396 	 * which needs correct compound_head().
2397 	 */
2398 	clear_compound_head(page_tail);
2399 
2400 	/* Finally unfreeze refcount. Additional reference from page cache. */
2401 	page_ref_unfreeze(page_tail, 1 + (!PageAnon(head) ||
2402 					  PageSwapCache(head)));
2403 
2404 	if (page_is_young(head))
2405 		set_page_young(page_tail);
2406 	if (page_is_idle(head))
2407 		set_page_idle(page_tail);
2408 
2409 	page_cpupid_xchg_last(page_tail, page_cpupid_last(head));
2410 
2411 	/*
2412 	 * always add to the tail because some iterators expect new
2413 	 * pages to show after the currently processed elements - e.g.
2414 	 * migrate_pages
2415 	 */
2416 	lru_add_page_tail(head, page_tail, lruvec, list);
2417 }
2418 
2419 static void __split_huge_page(struct page *page, struct list_head *list,
2420 		pgoff_t end)
2421 {
2422 	struct folio *folio = page_folio(page);
2423 	struct page *head = &folio->page;
2424 	struct lruvec *lruvec;
2425 	struct address_space *swap_cache = NULL;
2426 	unsigned long offset = 0;
2427 	unsigned int nr = thp_nr_pages(head);
2428 	int i;
2429 
2430 	/* complete memcg works before add pages to LRU */
2431 	split_page_memcg(head, nr);
2432 
2433 	if (PageAnon(head) && PageSwapCache(head)) {
2434 		swp_entry_t entry = { .val = page_private(head) };
2435 
2436 		offset = swp_offset(entry);
2437 		swap_cache = swap_address_space(entry);
2438 		xa_lock(&swap_cache->i_pages);
2439 	}
2440 
2441 	/* lock lru list/PageCompound, ref frozen by page_ref_freeze */
2442 	lruvec = folio_lruvec_lock(folio);
2443 
2444 	ClearPageHasHWPoisoned(head);
2445 
2446 	for (i = nr - 1; i >= 1; i--) {
2447 		__split_huge_page_tail(head, i, lruvec, list);
2448 		/* Some pages can be beyond EOF: drop them from page cache */
2449 		if (head[i].index >= end) {
2450 			ClearPageDirty(head + i);
2451 			__delete_from_page_cache(head + i, NULL);
2452 			if (shmem_mapping(head->mapping))
2453 				shmem_uncharge(head->mapping->host, 1);
2454 			put_page(head + i);
2455 		} else if (!PageAnon(page)) {
2456 			__xa_store(&head->mapping->i_pages, head[i].index,
2457 					head + i, 0);
2458 		} else if (swap_cache) {
2459 			__xa_store(&swap_cache->i_pages, offset + i,
2460 					head + i, 0);
2461 		}
2462 	}
2463 
2464 	ClearPageCompound(head);
2465 	unlock_page_lruvec(lruvec);
2466 	/* Caller disabled irqs, so they are still disabled here */
2467 
2468 	split_page_owner(head, nr);
2469 
2470 	/* See comment in __split_huge_page_tail() */
2471 	if (PageAnon(head)) {
2472 		/* Additional pin to swap cache */
2473 		if (PageSwapCache(head)) {
2474 			page_ref_add(head, 2);
2475 			xa_unlock(&swap_cache->i_pages);
2476 		} else {
2477 			page_ref_inc(head);
2478 		}
2479 	} else {
2480 		/* Additional pin to page cache */
2481 		page_ref_add(head, 2);
2482 		xa_unlock(&head->mapping->i_pages);
2483 	}
2484 	local_irq_enable();
2485 
2486 	remap_page(folio, nr);
2487 
2488 	if (PageSwapCache(head)) {
2489 		swp_entry_t entry = { .val = page_private(head) };
2490 
2491 		split_swap_cluster(entry);
2492 	}
2493 
2494 	for (i = 0; i < nr; i++) {
2495 		struct page *subpage = head + i;
2496 		if (subpage == page)
2497 			continue;
2498 		unlock_page(subpage);
2499 
2500 		/*
2501 		 * Subpages may be freed if there wasn't any mapping
2502 		 * like if add_to_swap() is running on a lru page that
2503 		 * had its mapping zapped. And freeing these pages
2504 		 * requires taking the lru_lock so we do the put_page
2505 		 * of the tail pages after the split is complete.
2506 		 */
2507 		put_page(subpage);
2508 	}
2509 }
2510 
2511 /* Racy check whether the huge page can be split */
2512 bool can_split_folio(struct folio *folio, int *pextra_pins)
2513 {
2514 	int extra_pins;
2515 
2516 	/* Additional pins from page cache */
2517 	if (folio_test_anon(folio))
2518 		extra_pins = folio_test_swapcache(folio) ?
2519 				folio_nr_pages(folio) : 0;
2520 	else
2521 		extra_pins = folio_nr_pages(folio);
2522 	if (pextra_pins)
2523 		*pextra_pins = extra_pins;
2524 	return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 1;
2525 }
2526 
2527 /*
2528  * This function splits huge page into normal pages. @page can point to any
2529  * subpage of huge page to split. Split doesn't change the position of @page.
2530  *
2531  * Only caller must hold pin on the @page, otherwise split fails with -EBUSY.
2532  * The huge page must be locked.
2533  *
2534  * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
2535  *
2536  * Both head page and tail pages will inherit mapping, flags, and so on from
2537  * the hugepage.
2538  *
2539  * GUP pin and PG_locked transferred to @page. Rest subpages can be freed if
2540  * they are not mapped.
2541  *
2542  * Returns 0 if the hugepage is split successfully.
2543  * Returns -EBUSY if the page is pinned or if anon_vma disappeared from under
2544  * us.
2545  */
2546 int split_huge_page_to_list(struct page *page, struct list_head *list)
2547 {
2548 	struct folio *folio = page_folio(page);
2549 	struct page *head = &folio->page;
2550 	struct deferred_split *ds_queue = get_deferred_split_queue(head);
2551 	XA_STATE(xas, &head->mapping->i_pages, head->index);
2552 	struct anon_vma *anon_vma = NULL;
2553 	struct address_space *mapping = NULL;
2554 	int extra_pins, ret;
2555 	pgoff_t end;
2556 
2557 	VM_BUG_ON_PAGE(is_huge_zero_page(head), head);
2558 	VM_BUG_ON_PAGE(!PageLocked(head), head);
2559 	VM_BUG_ON_PAGE(!PageCompound(head), head);
2560 
2561 	if (PageWriteback(head))
2562 		return -EBUSY;
2563 
2564 	if (PageAnon(head)) {
2565 		/*
2566 		 * The caller does not necessarily hold an mmap_lock that would
2567 		 * prevent the anon_vma disappearing so we first we take a
2568 		 * reference to it and then lock the anon_vma for write. This
2569 		 * is similar to folio_lock_anon_vma_read except the write lock
2570 		 * is taken to serialise against parallel split or collapse
2571 		 * operations.
2572 		 */
2573 		anon_vma = page_get_anon_vma(head);
2574 		if (!anon_vma) {
2575 			ret = -EBUSY;
2576 			goto out;
2577 		}
2578 		end = -1;
2579 		mapping = NULL;
2580 		anon_vma_lock_write(anon_vma);
2581 	} else {
2582 		mapping = head->mapping;
2583 
2584 		/* Truncated ? */
2585 		if (!mapping) {
2586 			ret = -EBUSY;
2587 			goto out;
2588 		}
2589 
2590 		xas_split_alloc(&xas, head, compound_order(head),
2591 				mapping_gfp_mask(mapping) & GFP_RECLAIM_MASK);
2592 		if (xas_error(&xas)) {
2593 			ret = xas_error(&xas);
2594 			goto out;
2595 		}
2596 
2597 		anon_vma = NULL;
2598 		i_mmap_lock_read(mapping);
2599 
2600 		/*
2601 		 *__split_huge_page() may need to trim off pages beyond EOF:
2602 		 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
2603 		 * which cannot be nested inside the page tree lock. So note
2604 		 * end now: i_size itself may be changed at any moment, but
2605 		 * head page lock is good enough to serialize the trimming.
2606 		 */
2607 		end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2608 		if (shmem_mapping(mapping))
2609 			end = shmem_fallocend(mapping->host, end);
2610 	}
2611 
2612 	/*
2613 	 * Racy check if we can split the page, before unmap_page() will
2614 	 * split PMDs
2615 	 */
2616 	if (!can_split_folio(folio, &extra_pins)) {
2617 		ret = -EBUSY;
2618 		goto out_unlock;
2619 	}
2620 
2621 	unmap_page(head);
2622 
2623 	/* block interrupt reentry in xa_lock and spinlock */
2624 	local_irq_disable();
2625 	if (mapping) {
2626 		/*
2627 		 * Check if the head page is present in page cache.
2628 		 * We assume all tail are present too, if head is there.
2629 		 */
2630 		xas_lock(&xas);
2631 		xas_reset(&xas);
2632 		if (xas_load(&xas) != head)
2633 			goto fail;
2634 	}
2635 
2636 	/* Prevent deferred_split_scan() touching ->_refcount */
2637 	spin_lock(&ds_queue->split_queue_lock);
2638 	if (page_ref_freeze(head, 1 + extra_pins)) {
2639 		if (!list_empty(page_deferred_list(head))) {
2640 			ds_queue->split_queue_len--;
2641 			list_del(page_deferred_list(head));
2642 		}
2643 		spin_unlock(&ds_queue->split_queue_lock);
2644 		if (mapping) {
2645 			int nr = thp_nr_pages(head);
2646 
2647 			xas_split(&xas, head, thp_order(head));
2648 			if (PageSwapBacked(head)) {
2649 				__mod_lruvec_page_state(head, NR_SHMEM_THPS,
2650 							-nr);
2651 			} else {
2652 				__mod_lruvec_page_state(head, NR_FILE_THPS,
2653 							-nr);
2654 				filemap_nr_thps_dec(mapping);
2655 			}
2656 		}
2657 
2658 		__split_huge_page(page, list, end);
2659 		ret = 0;
2660 	} else {
2661 		spin_unlock(&ds_queue->split_queue_lock);
2662 fail:
2663 		if (mapping)
2664 			xas_unlock(&xas);
2665 		local_irq_enable();
2666 		remap_page(folio, folio_nr_pages(folio));
2667 		ret = -EBUSY;
2668 	}
2669 
2670 out_unlock:
2671 	if (anon_vma) {
2672 		anon_vma_unlock_write(anon_vma);
2673 		put_anon_vma(anon_vma);
2674 	}
2675 	if (mapping)
2676 		i_mmap_unlock_read(mapping);
2677 out:
2678 	/* Free any memory we didn't use */
2679 	xas_nomem(&xas, 0);
2680 	count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
2681 	return ret;
2682 }
2683 
2684 void free_transhuge_page(struct page *page)
2685 {
2686 	struct deferred_split *ds_queue = get_deferred_split_queue(page);
2687 	unsigned long flags;
2688 
2689 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2690 	if (!list_empty(page_deferred_list(page))) {
2691 		ds_queue->split_queue_len--;
2692 		list_del(page_deferred_list(page));
2693 	}
2694 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2695 	free_compound_page(page);
2696 }
2697 
2698 void deferred_split_huge_page(struct page *page)
2699 {
2700 	struct deferred_split *ds_queue = get_deferred_split_queue(page);
2701 #ifdef CONFIG_MEMCG
2702 	struct mem_cgroup *memcg = page_memcg(compound_head(page));
2703 #endif
2704 	unsigned long flags;
2705 
2706 	VM_BUG_ON_PAGE(!PageTransHuge(page), page);
2707 
2708 	/*
2709 	 * The try_to_unmap() in page reclaim path might reach here too,
2710 	 * this may cause a race condition to corrupt deferred split queue.
2711 	 * And, if page reclaim is already handling the same page, it is
2712 	 * unnecessary to handle it again in shrinker.
2713 	 *
2714 	 * Check PageSwapCache to determine if the page is being
2715 	 * handled by page reclaim since THP swap would add the page into
2716 	 * swap cache before calling try_to_unmap().
2717 	 */
2718 	if (PageSwapCache(page))
2719 		return;
2720 
2721 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2722 	if (list_empty(page_deferred_list(page))) {
2723 		count_vm_event(THP_DEFERRED_SPLIT_PAGE);
2724 		list_add_tail(page_deferred_list(page), &ds_queue->split_queue);
2725 		ds_queue->split_queue_len++;
2726 #ifdef CONFIG_MEMCG
2727 		if (memcg)
2728 			set_shrinker_bit(memcg, page_to_nid(page),
2729 					 deferred_split_shrinker.id);
2730 #endif
2731 	}
2732 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2733 }
2734 
2735 static unsigned long deferred_split_count(struct shrinker *shrink,
2736 		struct shrink_control *sc)
2737 {
2738 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
2739 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
2740 
2741 #ifdef CONFIG_MEMCG
2742 	if (sc->memcg)
2743 		ds_queue = &sc->memcg->deferred_split_queue;
2744 #endif
2745 	return READ_ONCE(ds_queue->split_queue_len);
2746 }
2747 
2748 static unsigned long deferred_split_scan(struct shrinker *shrink,
2749 		struct shrink_control *sc)
2750 {
2751 	struct pglist_data *pgdata = NODE_DATA(sc->nid);
2752 	struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
2753 	unsigned long flags;
2754 	LIST_HEAD(list), *pos, *next;
2755 	struct page *page;
2756 	int split = 0;
2757 
2758 #ifdef CONFIG_MEMCG
2759 	if (sc->memcg)
2760 		ds_queue = &sc->memcg->deferred_split_queue;
2761 #endif
2762 
2763 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2764 	/* Take pin on all head pages to avoid freeing them under us */
2765 	list_for_each_safe(pos, next, &ds_queue->split_queue) {
2766 		page = list_entry((void *)pos, struct page, deferred_list);
2767 		page = compound_head(page);
2768 		if (get_page_unless_zero(page)) {
2769 			list_move(page_deferred_list(page), &list);
2770 		} else {
2771 			/* We lost race with put_compound_page() */
2772 			list_del_init(page_deferred_list(page));
2773 			ds_queue->split_queue_len--;
2774 		}
2775 		if (!--sc->nr_to_scan)
2776 			break;
2777 	}
2778 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2779 
2780 	list_for_each_safe(pos, next, &list) {
2781 		page = list_entry((void *)pos, struct page, deferred_list);
2782 		if (!trylock_page(page))
2783 			goto next;
2784 		/* split_huge_page() removes page from list on success */
2785 		if (!split_huge_page(page))
2786 			split++;
2787 		unlock_page(page);
2788 next:
2789 		put_page(page);
2790 	}
2791 
2792 	spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2793 	list_splice_tail(&list, &ds_queue->split_queue);
2794 	spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2795 
2796 	/*
2797 	 * Stop shrinker if we didn't split any page, but the queue is empty.
2798 	 * This can happen if pages were freed under us.
2799 	 */
2800 	if (!split && list_empty(&ds_queue->split_queue))
2801 		return SHRINK_STOP;
2802 	return split;
2803 }
2804 
2805 static struct shrinker deferred_split_shrinker = {
2806 	.count_objects = deferred_split_count,
2807 	.scan_objects = deferred_split_scan,
2808 	.seeks = DEFAULT_SEEKS,
2809 	.flags = SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE |
2810 		 SHRINKER_NONSLAB,
2811 };
2812 
2813 #ifdef CONFIG_DEBUG_FS
2814 static void split_huge_pages_all(void)
2815 {
2816 	struct zone *zone;
2817 	struct page *page;
2818 	unsigned long pfn, max_zone_pfn;
2819 	unsigned long total = 0, split = 0;
2820 
2821 	pr_debug("Split all THPs\n");
2822 	for_each_populated_zone(zone) {
2823 		max_zone_pfn = zone_end_pfn(zone);
2824 		for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
2825 			if (!pfn_valid(pfn))
2826 				continue;
2827 
2828 			page = pfn_to_page(pfn);
2829 			if (!get_page_unless_zero(page))
2830 				continue;
2831 
2832 			if (zone != page_zone(page))
2833 				goto next;
2834 
2835 			if (!PageHead(page) || PageHuge(page) || !PageLRU(page))
2836 				goto next;
2837 
2838 			total++;
2839 			lock_page(page);
2840 			if (!split_huge_page(page))
2841 				split++;
2842 			unlock_page(page);
2843 next:
2844 			put_page(page);
2845 			cond_resched();
2846 		}
2847 	}
2848 
2849 	pr_debug("%lu of %lu THP split\n", split, total);
2850 }
2851 
2852 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
2853 {
2854 	return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
2855 		    is_vm_hugetlb_page(vma);
2856 }
2857 
2858 static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
2859 				unsigned long vaddr_end)
2860 {
2861 	int ret = 0;
2862 	struct task_struct *task;
2863 	struct mm_struct *mm;
2864 	unsigned long total = 0, split = 0;
2865 	unsigned long addr;
2866 
2867 	vaddr_start &= PAGE_MASK;
2868 	vaddr_end &= PAGE_MASK;
2869 
2870 	/* Find the task_struct from pid */
2871 	rcu_read_lock();
2872 	task = find_task_by_vpid(pid);
2873 	if (!task) {
2874 		rcu_read_unlock();
2875 		ret = -ESRCH;
2876 		goto out;
2877 	}
2878 	get_task_struct(task);
2879 	rcu_read_unlock();
2880 
2881 	/* Find the mm_struct */
2882 	mm = get_task_mm(task);
2883 	put_task_struct(task);
2884 
2885 	if (!mm) {
2886 		ret = -EINVAL;
2887 		goto out;
2888 	}
2889 
2890 	pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
2891 		 pid, vaddr_start, vaddr_end);
2892 
2893 	mmap_read_lock(mm);
2894 	/*
2895 	 * always increase addr by PAGE_SIZE, since we could have a PTE page
2896 	 * table filled with PTE-mapped THPs, each of which is distinct.
2897 	 */
2898 	for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
2899 		struct vm_area_struct *vma = find_vma(mm, addr);
2900 		struct page *page;
2901 
2902 		if (!vma || addr < vma->vm_start)
2903 			break;
2904 
2905 		/* skip special VMA and hugetlb VMA */
2906 		if (vma_not_suitable_for_thp_split(vma)) {
2907 			addr = vma->vm_end;
2908 			continue;
2909 		}
2910 
2911 		/* FOLL_DUMP to ignore special (like zero) pages */
2912 		page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
2913 
2914 		if (IS_ERR(page))
2915 			continue;
2916 		if (!page)
2917 			continue;
2918 
2919 		if (!is_transparent_hugepage(page))
2920 			goto next;
2921 
2922 		total++;
2923 		if (!can_split_folio(page_folio(page), NULL))
2924 			goto next;
2925 
2926 		if (!trylock_page(page))
2927 			goto next;
2928 
2929 		if (!split_huge_page(page))
2930 			split++;
2931 
2932 		unlock_page(page);
2933 next:
2934 		put_page(page);
2935 		cond_resched();
2936 	}
2937 	mmap_read_unlock(mm);
2938 	mmput(mm);
2939 
2940 	pr_debug("%lu of %lu THP split\n", split, total);
2941 
2942 out:
2943 	return ret;
2944 }
2945 
2946 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
2947 				pgoff_t off_end)
2948 {
2949 	struct filename *file;
2950 	struct file *candidate;
2951 	struct address_space *mapping;
2952 	int ret = -EINVAL;
2953 	pgoff_t index;
2954 	int nr_pages = 1;
2955 	unsigned long total = 0, split = 0;
2956 
2957 	file = getname_kernel(file_path);
2958 	if (IS_ERR(file))
2959 		return ret;
2960 
2961 	candidate = file_open_name(file, O_RDONLY, 0);
2962 	if (IS_ERR(candidate))
2963 		goto out;
2964 
2965 	pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
2966 		 file_path, off_start, off_end);
2967 
2968 	mapping = candidate->f_mapping;
2969 
2970 	for (index = off_start; index < off_end; index += nr_pages) {
2971 		struct page *fpage = pagecache_get_page(mapping, index,
2972 						FGP_ENTRY | FGP_HEAD, 0);
2973 
2974 		nr_pages = 1;
2975 		if (xa_is_value(fpage) || !fpage)
2976 			continue;
2977 
2978 		if (!is_transparent_hugepage(fpage))
2979 			goto next;
2980 
2981 		total++;
2982 		nr_pages = thp_nr_pages(fpage);
2983 
2984 		if (!trylock_page(fpage))
2985 			goto next;
2986 
2987 		if (!split_huge_page(fpage))
2988 			split++;
2989 
2990 		unlock_page(fpage);
2991 next:
2992 		put_page(fpage);
2993 		cond_resched();
2994 	}
2995 
2996 	filp_close(candidate, NULL);
2997 	ret = 0;
2998 
2999 	pr_debug("%lu of %lu file-backed THP split\n", split, total);
3000 out:
3001 	putname(file);
3002 	return ret;
3003 }
3004 
3005 #define MAX_INPUT_BUF_SZ 255
3006 
3007 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
3008 				size_t count, loff_t *ppops)
3009 {
3010 	static DEFINE_MUTEX(split_debug_mutex);
3011 	ssize_t ret;
3012 	/* hold pid, start_vaddr, end_vaddr or file_path, off_start, off_end */
3013 	char input_buf[MAX_INPUT_BUF_SZ];
3014 	int pid;
3015 	unsigned long vaddr_start, vaddr_end;
3016 
3017 	ret = mutex_lock_interruptible(&split_debug_mutex);
3018 	if (ret)
3019 		return ret;
3020 
3021 	ret = -EFAULT;
3022 
3023 	memset(input_buf, 0, MAX_INPUT_BUF_SZ);
3024 	if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
3025 		goto out;
3026 
3027 	input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
3028 
3029 	if (input_buf[0] == '/') {
3030 		char *tok;
3031 		char *buf = input_buf;
3032 		char file_path[MAX_INPUT_BUF_SZ];
3033 		pgoff_t off_start = 0, off_end = 0;
3034 		size_t input_len = strlen(input_buf);
3035 
3036 		tok = strsep(&buf, ",");
3037 		if (tok) {
3038 			strcpy(file_path, tok);
3039 		} else {
3040 			ret = -EINVAL;
3041 			goto out;
3042 		}
3043 
3044 		ret = sscanf(buf, "0x%lx,0x%lx", &off_start, &off_end);
3045 		if (ret != 2) {
3046 			ret = -EINVAL;
3047 			goto out;
3048 		}
3049 		ret = split_huge_pages_in_file(file_path, off_start, off_end);
3050 		if (!ret)
3051 			ret = input_len;
3052 
3053 		goto out;
3054 	}
3055 
3056 	ret = sscanf(input_buf, "%d,0x%lx,0x%lx", &pid, &vaddr_start, &vaddr_end);
3057 	if (ret == 1 && pid == 1) {
3058 		split_huge_pages_all();
3059 		ret = strlen(input_buf);
3060 		goto out;
3061 	} else if (ret != 3) {
3062 		ret = -EINVAL;
3063 		goto out;
3064 	}
3065 
3066 	ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end);
3067 	if (!ret)
3068 		ret = strlen(input_buf);
3069 out:
3070 	mutex_unlock(&split_debug_mutex);
3071 	return ret;
3072 
3073 }
3074 
3075 static const struct file_operations split_huge_pages_fops = {
3076 	.owner	 = THIS_MODULE,
3077 	.write	 = split_huge_pages_write,
3078 	.llseek  = no_llseek,
3079 };
3080 
3081 static int __init split_huge_pages_debugfs(void)
3082 {
3083 	debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3084 			    &split_huge_pages_fops);
3085 	return 0;
3086 }
3087 late_initcall(split_huge_pages_debugfs);
3088 #endif
3089 
3090 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
3091 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
3092 		struct page *page)
3093 {
3094 	struct vm_area_struct *vma = pvmw->vma;
3095 	struct mm_struct *mm = vma->vm_mm;
3096 	unsigned long address = pvmw->address;
3097 	bool anon_exclusive;
3098 	pmd_t pmdval;
3099 	swp_entry_t entry;
3100 	pmd_t pmdswp;
3101 
3102 	if (!(pvmw->pmd && !pvmw->pte))
3103 		return 0;
3104 
3105 	flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
3106 	pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
3107 
3108 	anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
3109 	if (anon_exclusive && page_try_share_anon_rmap(page)) {
3110 		set_pmd_at(mm, address, pvmw->pmd, pmdval);
3111 		return -EBUSY;
3112 	}
3113 
3114 	if (pmd_dirty(pmdval))
3115 		set_page_dirty(page);
3116 	if (pmd_write(pmdval))
3117 		entry = make_writable_migration_entry(page_to_pfn(page));
3118 	else if (anon_exclusive)
3119 		entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
3120 	else
3121 		entry = make_readable_migration_entry(page_to_pfn(page));
3122 	pmdswp = swp_entry_to_pmd(entry);
3123 	if (pmd_soft_dirty(pmdval))
3124 		pmdswp = pmd_swp_mksoft_dirty(pmdswp);
3125 	set_pmd_at(mm, address, pvmw->pmd, pmdswp);
3126 	page_remove_rmap(page, vma, true);
3127 	put_page(page);
3128 	trace_set_migration_pmd(address, pmd_val(pmdswp));
3129 
3130 	return 0;
3131 }
3132 
3133 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
3134 {
3135 	struct vm_area_struct *vma = pvmw->vma;
3136 	struct mm_struct *mm = vma->vm_mm;
3137 	unsigned long address = pvmw->address;
3138 	unsigned long mmun_start = address & HPAGE_PMD_MASK;
3139 	pmd_t pmde;
3140 	swp_entry_t entry;
3141 
3142 	if (!(pvmw->pmd && !pvmw->pte))
3143 		return;
3144 
3145 	entry = pmd_to_swp_entry(*pvmw->pmd);
3146 	get_page(new);
3147 	pmde = pmd_mkold(mk_huge_pmd(new, vma->vm_page_prot));
3148 	if (pmd_swp_soft_dirty(*pvmw->pmd))
3149 		pmde = pmd_mksoft_dirty(pmde);
3150 	if (is_writable_migration_entry(entry))
3151 		pmde = maybe_pmd_mkwrite(pmde, vma);
3152 	if (pmd_swp_uffd_wp(*pvmw->pmd))
3153 		pmde = pmd_wrprotect(pmd_mkuffd_wp(pmde));
3154 
3155 	if (PageAnon(new)) {
3156 		rmap_t rmap_flags = RMAP_COMPOUND;
3157 
3158 		if (!is_readable_migration_entry(entry))
3159 			rmap_flags |= RMAP_EXCLUSIVE;
3160 
3161 		page_add_anon_rmap(new, vma, mmun_start, rmap_flags);
3162 	} else {
3163 		page_add_file_rmap(new, vma, true);
3164 	}
3165 	VM_BUG_ON(pmd_write(pmde) && PageAnon(new) && !PageAnonExclusive(new));
3166 	set_pmd_at(mm, mmun_start, pvmw->pmd, pmde);
3167 
3168 	/* No need to invalidate - it was non-present before */
3169 	update_mmu_cache_pmd(vma, address, pvmw->pmd);
3170 	trace_remove_migration_pmd(address, pmd_val(pmde));
3171 }
3172 #endif
3173