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