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