xref: /linux/mm/huge_memory.c (revision ca55b2fef3a9373fcfc30f82fd26bc7fccbda732)
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/highmem.h>
13 #include <linux/hugetlb.h>
14 #include <linux/mmu_notifier.h>
15 #include <linux/rmap.h>
16 #include <linux/swap.h>
17 #include <linux/shrinker.h>
18 #include <linux/mm_inline.h>
19 #include <linux/dax.h>
20 #include <linux/kthread.h>
21 #include <linux/khugepaged.h>
22 #include <linux/freezer.h>
23 #include <linux/mman.h>
24 #include <linux/pagemap.h>
25 #include <linux/migrate.h>
26 #include <linux/hashtable.h>
27 #include <linux/userfaultfd_k.h>
28 #include <linux/page_idle.h>
29 
30 #include <asm/tlb.h>
31 #include <asm/pgalloc.h>
32 #include "internal.h"
33 
34 /*
35  * By default transparent hugepage support is disabled in order that avoid
36  * to risk increase the memory footprint of applications without a guaranteed
37  * benefit. When transparent hugepage support is enabled, is for all mappings,
38  * and khugepaged scans all mappings.
39  * Defrag is invoked by khugepaged hugepage allocations and by page faults
40  * for all hugepage allocations.
41  */
42 unsigned long transparent_hugepage_flags __read_mostly =
43 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
44 	(1<<TRANSPARENT_HUGEPAGE_FLAG)|
45 #endif
46 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
47 	(1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
48 #endif
49 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_FLAG)|
50 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
51 	(1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
52 
53 /* default scan 8*512 pte (or vmas) every 30 second */
54 static unsigned int khugepaged_pages_to_scan __read_mostly = HPAGE_PMD_NR*8;
55 static unsigned int khugepaged_pages_collapsed;
56 static unsigned int khugepaged_full_scans;
57 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
58 /* during fragmentation poll the hugepage allocator once every minute */
59 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
60 static struct task_struct *khugepaged_thread __read_mostly;
61 static DEFINE_MUTEX(khugepaged_mutex);
62 static DEFINE_SPINLOCK(khugepaged_mm_lock);
63 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
64 /*
65  * default collapse hugepages if there is at least one pte mapped like
66  * it would have happened if the vma was large enough during page
67  * fault.
68  */
69 static unsigned int khugepaged_max_ptes_none __read_mostly = HPAGE_PMD_NR-1;
70 
71 static int khugepaged(void *none);
72 static int khugepaged_slab_init(void);
73 static void khugepaged_slab_exit(void);
74 
75 #define MM_SLOTS_HASH_BITS 10
76 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
77 
78 static struct kmem_cache *mm_slot_cache __read_mostly;
79 
80 /**
81  * struct mm_slot - hash lookup from mm to mm_slot
82  * @hash: hash collision list
83  * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
84  * @mm: the mm that this information is valid for
85  */
86 struct mm_slot {
87 	struct hlist_node hash;
88 	struct list_head mm_node;
89 	struct mm_struct *mm;
90 };
91 
92 /**
93  * struct khugepaged_scan - cursor for scanning
94  * @mm_head: the head of the mm list to scan
95  * @mm_slot: the current mm_slot we are scanning
96  * @address: the next address inside that to be scanned
97  *
98  * There is only the one khugepaged_scan instance of this cursor structure.
99  */
100 struct khugepaged_scan {
101 	struct list_head mm_head;
102 	struct mm_slot *mm_slot;
103 	unsigned long address;
104 };
105 static struct khugepaged_scan khugepaged_scan = {
106 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
107 };
108 
109 
110 static void set_recommended_min_free_kbytes(void)
111 {
112 	struct zone *zone;
113 	int nr_zones = 0;
114 	unsigned long recommended_min;
115 
116 	for_each_populated_zone(zone)
117 		nr_zones++;
118 
119 	/* Make sure at least 2 hugepages are free for MIGRATE_RESERVE */
120 	recommended_min = pageblock_nr_pages * nr_zones * 2;
121 
122 	/*
123 	 * Make sure that on average at least two pageblocks are almost free
124 	 * of another type, one for a migratetype to fall back to and a
125 	 * second to avoid subsequent fallbacks of other types There are 3
126 	 * MIGRATE_TYPES we care about.
127 	 */
128 	recommended_min += pageblock_nr_pages * nr_zones *
129 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
130 
131 	/* don't ever allow to reserve more than 5% of the lowmem */
132 	recommended_min = min(recommended_min,
133 			      (unsigned long) nr_free_buffer_pages() / 20);
134 	recommended_min <<= (PAGE_SHIFT-10);
135 
136 	if (recommended_min > min_free_kbytes) {
137 		if (user_min_free_kbytes >= 0)
138 			pr_info("raising min_free_kbytes from %d to %lu "
139 				"to help transparent hugepage allocations\n",
140 				min_free_kbytes, recommended_min);
141 
142 		min_free_kbytes = recommended_min;
143 	}
144 	setup_per_zone_wmarks();
145 }
146 
147 static int start_stop_khugepaged(void)
148 {
149 	int err = 0;
150 	if (khugepaged_enabled()) {
151 		if (!khugepaged_thread)
152 			khugepaged_thread = kthread_run(khugepaged, NULL,
153 							"khugepaged");
154 		if (unlikely(IS_ERR(khugepaged_thread))) {
155 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
156 			err = PTR_ERR(khugepaged_thread);
157 			khugepaged_thread = NULL;
158 			goto fail;
159 		}
160 
161 		if (!list_empty(&khugepaged_scan.mm_head))
162 			wake_up_interruptible(&khugepaged_wait);
163 
164 		set_recommended_min_free_kbytes();
165 	} else if (khugepaged_thread) {
166 		kthread_stop(khugepaged_thread);
167 		khugepaged_thread = NULL;
168 	}
169 fail:
170 	return err;
171 }
172 
173 static atomic_t huge_zero_refcount;
174 struct page *huge_zero_page __read_mostly;
175 
176 struct page *get_huge_zero_page(void)
177 {
178 	struct page *zero_page;
179 retry:
180 	if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
181 		return READ_ONCE(huge_zero_page);
182 
183 	zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
184 			HPAGE_PMD_ORDER);
185 	if (!zero_page) {
186 		count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
187 		return NULL;
188 	}
189 	count_vm_event(THP_ZERO_PAGE_ALLOC);
190 	preempt_disable();
191 	if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
192 		preempt_enable();
193 		__free_pages(zero_page, compound_order(zero_page));
194 		goto retry;
195 	}
196 
197 	/* We take additional reference here. It will be put back by shrinker */
198 	atomic_set(&huge_zero_refcount, 2);
199 	preempt_enable();
200 	return READ_ONCE(huge_zero_page);
201 }
202 
203 static void put_huge_zero_page(void)
204 {
205 	/*
206 	 * Counter should never go to zero here. Only shrinker can put
207 	 * last reference.
208 	 */
209 	BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
210 }
211 
212 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
213 					struct shrink_control *sc)
214 {
215 	/* we can free zero page only if last reference remains */
216 	return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
217 }
218 
219 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
220 				       struct shrink_control *sc)
221 {
222 	if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
223 		struct page *zero_page = xchg(&huge_zero_page, NULL);
224 		BUG_ON(zero_page == NULL);
225 		__free_pages(zero_page, compound_order(zero_page));
226 		return HPAGE_PMD_NR;
227 	}
228 
229 	return 0;
230 }
231 
232 static struct shrinker huge_zero_page_shrinker = {
233 	.count_objects = shrink_huge_zero_page_count,
234 	.scan_objects = shrink_huge_zero_page_scan,
235 	.seeks = DEFAULT_SEEKS,
236 };
237 
238 #ifdef CONFIG_SYSFS
239 
240 static ssize_t double_flag_show(struct kobject *kobj,
241 				struct kobj_attribute *attr, char *buf,
242 				enum transparent_hugepage_flag enabled,
243 				enum transparent_hugepage_flag req_madv)
244 {
245 	if (test_bit(enabled, &transparent_hugepage_flags)) {
246 		VM_BUG_ON(test_bit(req_madv, &transparent_hugepage_flags));
247 		return sprintf(buf, "[always] madvise never\n");
248 	} else if (test_bit(req_madv, &transparent_hugepage_flags))
249 		return sprintf(buf, "always [madvise] never\n");
250 	else
251 		return sprintf(buf, "always madvise [never]\n");
252 }
253 static ssize_t double_flag_store(struct kobject *kobj,
254 				 struct kobj_attribute *attr,
255 				 const char *buf, size_t count,
256 				 enum transparent_hugepage_flag enabled,
257 				 enum transparent_hugepage_flag req_madv)
258 {
259 	if (!memcmp("always", buf,
260 		    min(sizeof("always")-1, count))) {
261 		set_bit(enabled, &transparent_hugepage_flags);
262 		clear_bit(req_madv, &transparent_hugepage_flags);
263 	} else if (!memcmp("madvise", buf,
264 			   min(sizeof("madvise")-1, count))) {
265 		clear_bit(enabled, &transparent_hugepage_flags);
266 		set_bit(req_madv, &transparent_hugepage_flags);
267 	} else if (!memcmp("never", buf,
268 			   min(sizeof("never")-1, count))) {
269 		clear_bit(enabled, &transparent_hugepage_flags);
270 		clear_bit(req_madv, &transparent_hugepage_flags);
271 	} else
272 		return -EINVAL;
273 
274 	return count;
275 }
276 
277 static ssize_t enabled_show(struct kobject *kobj,
278 			    struct kobj_attribute *attr, char *buf)
279 {
280 	return double_flag_show(kobj, attr, buf,
281 				TRANSPARENT_HUGEPAGE_FLAG,
282 				TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
283 }
284 static ssize_t enabled_store(struct kobject *kobj,
285 			     struct kobj_attribute *attr,
286 			     const char *buf, size_t count)
287 {
288 	ssize_t ret;
289 
290 	ret = double_flag_store(kobj, attr, buf, count,
291 				TRANSPARENT_HUGEPAGE_FLAG,
292 				TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
293 
294 	if (ret > 0) {
295 		int err;
296 
297 		mutex_lock(&khugepaged_mutex);
298 		err = start_stop_khugepaged();
299 		mutex_unlock(&khugepaged_mutex);
300 
301 		if (err)
302 			ret = err;
303 	}
304 
305 	return ret;
306 }
307 static struct kobj_attribute enabled_attr =
308 	__ATTR(enabled, 0644, enabled_show, enabled_store);
309 
310 static ssize_t single_flag_show(struct kobject *kobj,
311 				struct kobj_attribute *attr, char *buf,
312 				enum transparent_hugepage_flag flag)
313 {
314 	return sprintf(buf, "%d\n",
315 		       !!test_bit(flag, &transparent_hugepage_flags));
316 }
317 
318 static ssize_t single_flag_store(struct kobject *kobj,
319 				 struct kobj_attribute *attr,
320 				 const char *buf, size_t count,
321 				 enum transparent_hugepage_flag flag)
322 {
323 	unsigned long value;
324 	int ret;
325 
326 	ret = kstrtoul(buf, 10, &value);
327 	if (ret < 0)
328 		return ret;
329 	if (value > 1)
330 		return -EINVAL;
331 
332 	if (value)
333 		set_bit(flag, &transparent_hugepage_flags);
334 	else
335 		clear_bit(flag, &transparent_hugepage_flags);
336 
337 	return count;
338 }
339 
340 /*
341  * Currently defrag only disables __GFP_NOWAIT for allocation. A blind
342  * __GFP_REPEAT is too aggressive, it's never worth swapping tons of
343  * memory just to allocate one more hugepage.
344  */
345 static ssize_t defrag_show(struct kobject *kobj,
346 			   struct kobj_attribute *attr, char *buf)
347 {
348 	return double_flag_show(kobj, attr, buf,
349 				TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
350 				TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
351 }
352 static ssize_t defrag_store(struct kobject *kobj,
353 			    struct kobj_attribute *attr,
354 			    const char *buf, size_t count)
355 {
356 	return double_flag_store(kobj, attr, buf, count,
357 				 TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
358 				 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
359 }
360 static struct kobj_attribute defrag_attr =
361 	__ATTR(defrag, 0644, defrag_show, defrag_store);
362 
363 static ssize_t use_zero_page_show(struct kobject *kobj,
364 		struct kobj_attribute *attr, char *buf)
365 {
366 	return single_flag_show(kobj, attr, buf,
367 				TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
368 }
369 static ssize_t use_zero_page_store(struct kobject *kobj,
370 		struct kobj_attribute *attr, const char *buf, size_t count)
371 {
372 	return single_flag_store(kobj, attr, buf, count,
373 				 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
374 }
375 static struct kobj_attribute use_zero_page_attr =
376 	__ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
377 #ifdef CONFIG_DEBUG_VM
378 static ssize_t debug_cow_show(struct kobject *kobj,
379 				struct kobj_attribute *attr, char *buf)
380 {
381 	return single_flag_show(kobj, attr, buf,
382 				TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
383 }
384 static ssize_t debug_cow_store(struct kobject *kobj,
385 			       struct kobj_attribute *attr,
386 			       const char *buf, size_t count)
387 {
388 	return single_flag_store(kobj, attr, buf, count,
389 				 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
390 }
391 static struct kobj_attribute debug_cow_attr =
392 	__ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
393 #endif /* CONFIG_DEBUG_VM */
394 
395 static struct attribute *hugepage_attr[] = {
396 	&enabled_attr.attr,
397 	&defrag_attr.attr,
398 	&use_zero_page_attr.attr,
399 #ifdef CONFIG_DEBUG_VM
400 	&debug_cow_attr.attr,
401 #endif
402 	NULL,
403 };
404 
405 static struct attribute_group hugepage_attr_group = {
406 	.attrs = hugepage_attr,
407 };
408 
409 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
410 					 struct kobj_attribute *attr,
411 					 char *buf)
412 {
413 	return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
414 }
415 
416 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
417 					  struct kobj_attribute *attr,
418 					  const char *buf, size_t count)
419 {
420 	unsigned long msecs;
421 	int err;
422 
423 	err = kstrtoul(buf, 10, &msecs);
424 	if (err || msecs > UINT_MAX)
425 		return -EINVAL;
426 
427 	khugepaged_scan_sleep_millisecs = msecs;
428 	wake_up_interruptible(&khugepaged_wait);
429 
430 	return count;
431 }
432 static struct kobj_attribute scan_sleep_millisecs_attr =
433 	__ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
434 	       scan_sleep_millisecs_store);
435 
436 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
437 					  struct kobj_attribute *attr,
438 					  char *buf)
439 {
440 	return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
441 }
442 
443 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
444 					   struct kobj_attribute *attr,
445 					   const char *buf, size_t count)
446 {
447 	unsigned long msecs;
448 	int err;
449 
450 	err = kstrtoul(buf, 10, &msecs);
451 	if (err || msecs > UINT_MAX)
452 		return -EINVAL;
453 
454 	khugepaged_alloc_sleep_millisecs = msecs;
455 	wake_up_interruptible(&khugepaged_wait);
456 
457 	return count;
458 }
459 static struct kobj_attribute alloc_sleep_millisecs_attr =
460 	__ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
461 	       alloc_sleep_millisecs_store);
462 
463 static ssize_t pages_to_scan_show(struct kobject *kobj,
464 				  struct kobj_attribute *attr,
465 				  char *buf)
466 {
467 	return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
468 }
469 static ssize_t pages_to_scan_store(struct kobject *kobj,
470 				   struct kobj_attribute *attr,
471 				   const char *buf, size_t count)
472 {
473 	int err;
474 	unsigned long pages;
475 
476 	err = kstrtoul(buf, 10, &pages);
477 	if (err || !pages || pages > UINT_MAX)
478 		return -EINVAL;
479 
480 	khugepaged_pages_to_scan = pages;
481 
482 	return count;
483 }
484 static struct kobj_attribute pages_to_scan_attr =
485 	__ATTR(pages_to_scan, 0644, pages_to_scan_show,
486 	       pages_to_scan_store);
487 
488 static ssize_t pages_collapsed_show(struct kobject *kobj,
489 				    struct kobj_attribute *attr,
490 				    char *buf)
491 {
492 	return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
493 }
494 static struct kobj_attribute pages_collapsed_attr =
495 	__ATTR_RO(pages_collapsed);
496 
497 static ssize_t full_scans_show(struct kobject *kobj,
498 			       struct kobj_attribute *attr,
499 			       char *buf)
500 {
501 	return sprintf(buf, "%u\n", khugepaged_full_scans);
502 }
503 static struct kobj_attribute full_scans_attr =
504 	__ATTR_RO(full_scans);
505 
506 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
507 				      struct kobj_attribute *attr, char *buf)
508 {
509 	return single_flag_show(kobj, attr, buf,
510 				TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
511 }
512 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
513 				       struct kobj_attribute *attr,
514 				       const char *buf, size_t count)
515 {
516 	return single_flag_store(kobj, attr, buf, count,
517 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
518 }
519 static struct kobj_attribute khugepaged_defrag_attr =
520 	__ATTR(defrag, 0644, khugepaged_defrag_show,
521 	       khugepaged_defrag_store);
522 
523 /*
524  * max_ptes_none controls if khugepaged should collapse hugepages over
525  * any unmapped ptes in turn potentially increasing the memory
526  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
527  * reduce the available free memory in the system as it
528  * runs. Increasing max_ptes_none will instead potentially reduce the
529  * free memory in the system during the khugepaged scan.
530  */
531 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
532 					     struct kobj_attribute *attr,
533 					     char *buf)
534 {
535 	return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
536 }
537 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
538 					      struct kobj_attribute *attr,
539 					      const char *buf, size_t count)
540 {
541 	int err;
542 	unsigned long max_ptes_none;
543 
544 	err = kstrtoul(buf, 10, &max_ptes_none);
545 	if (err || max_ptes_none > HPAGE_PMD_NR-1)
546 		return -EINVAL;
547 
548 	khugepaged_max_ptes_none = max_ptes_none;
549 
550 	return count;
551 }
552 static struct kobj_attribute khugepaged_max_ptes_none_attr =
553 	__ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
554 	       khugepaged_max_ptes_none_store);
555 
556 static struct attribute *khugepaged_attr[] = {
557 	&khugepaged_defrag_attr.attr,
558 	&khugepaged_max_ptes_none_attr.attr,
559 	&pages_to_scan_attr.attr,
560 	&pages_collapsed_attr.attr,
561 	&full_scans_attr.attr,
562 	&scan_sleep_millisecs_attr.attr,
563 	&alloc_sleep_millisecs_attr.attr,
564 	NULL,
565 };
566 
567 static struct attribute_group khugepaged_attr_group = {
568 	.attrs = khugepaged_attr,
569 	.name = "khugepaged",
570 };
571 
572 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
573 {
574 	int err;
575 
576 	*hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
577 	if (unlikely(!*hugepage_kobj)) {
578 		pr_err("failed to create transparent hugepage kobject\n");
579 		return -ENOMEM;
580 	}
581 
582 	err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
583 	if (err) {
584 		pr_err("failed to register transparent hugepage group\n");
585 		goto delete_obj;
586 	}
587 
588 	err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
589 	if (err) {
590 		pr_err("failed to register transparent hugepage group\n");
591 		goto remove_hp_group;
592 	}
593 
594 	return 0;
595 
596 remove_hp_group:
597 	sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
598 delete_obj:
599 	kobject_put(*hugepage_kobj);
600 	return err;
601 }
602 
603 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
604 {
605 	sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
606 	sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
607 	kobject_put(hugepage_kobj);
608 }
609 #else
610 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
611 {
612 	return 0;
613 }
614 
615 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
616 {
617 }
618 #endif /* CONFIG_SYSFS */
619 
620 static int __init hugepage_init(void)
621 {
622 	int err;
623 	struct kobject *hugepage_kobj;
624 
625 	if (!has_transparent_hugepage()) {
626 		transparent_hugepage_flags = 0;
627 		return -EINVAL;
628 	}
629 
630 	err = hugepage_init_sysfs(&hugepage_kobj);
631 	if (err)
632 		goto err_sysfs;
633 
634 	err = khugepaged_slab_init();
635 	if (err)
636 		goto err_slab;
637 
638 	err = register_shrinker(&huge_zero_page_shrinker);
639 	if (err)
640 		goto err_hzp_shrinker;
641 
642 	/*
643 	 * By default disable transparent hugepages on smaller systems,
644 	 * where the extra memory used could hurt more than TLB overhead
645 	 * is likely to save.  The admin can still enable it through /sys.
646 	 */
647 	if (totalram_pages < (512 << (20 - PAGE_SHIFT))) {
648 		transparent_hugepage_flags = 0;
649 		return 0;
650 	}
651 
652 	err = start_stop_khugepaged();
653 	if (err)
654 		goto err_khugepaged;
655 
656 	return 0;
657 err_khugepaged:
658 	unregister_shrinker(&huge_zero_page_shrinker);
659 err_hzp_shrinker:
660 	khugepaged_slab_exit();
661 err_slab:
662 	hugepage_exit_sysfs(hugepage_kobj);
663 err_sysfs:
664 	return err;
665 }
666 subsys_initcall(hugepage_init);
667 
668 static int __init setup_transparent_hugepage(char *str)
669 {
670 	int ret = 0;
671 	if (!str)
672 		goto out;
673 	if (!strcmp(str, "always")) {
674 		set_bit(TRANSPARENT_HUGEPAGE_FLAG,
675 			&transparent_hugepage_flags);
676 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
677 			  &transparent_hugepage_flags);
678 		ret = 1;
679 	} else if (!strcmp(str, "madvise")) {
680 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
681 			  &transparent_hugepage_flags);
682 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
683 			&transparent_hugepage_flags);
684 		ret = 1;
685 	} else if (!strcmp(str, "never")) {
686 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
687 			  &transparent_hugepage_flags);
688 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
689 			  &transparent_hugepage_flags);
690 		ret = 1;
691 	}
692 out:
693 	if (!ret)
694 		pr_warn("transparent_hugepage= cannot parse, ignored\n");
695 	return ret;
696 }
697 __setup("transparent_hugepage=", setup_transparent_hugepage);
698 
699 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
700 {
701 	if (likely(vma->vm_flags & VM_WRITE))
702 		pmd = pmd_mkwrite(pmd);
703 	return pmd;
704 }
705 
706 static inline pmd_t mk_huge_pmd(struct page *page, pgprot_t prot)
707 {
708 	pmd_t entry;
709 	entry = mk_pmd(page, prot);
710 	entry = pmd_mkhuge(entry);
711 	return entry;
712 }
713 
714 static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
715 					struct vm_area_struct *vma,
716 					unsigned long address, pmd_t *pmd,
717 					struct page *page, gfp_t gfp,
718 					unsigned int flags)
719 {
720 	struct mem_cgroup *memcg;
721 	pgtable_t pgtable;
722 	spinlock_t *ptl;
723 	unsigned long haddr = address & HPAGE_PMD_MASK;
724 
725 	VM_BUG_ON_PAGE(!PageCompound(page), page);
726 
727 	if (mem_cgroup_try_charge(page, mm, gfp, &memcg)) {
728 		put_page(page);
729 		count_vm_event(THP_FAULT_FALLBACK);
730 		return VM_FAULT_FALLBACK;
731 	}
732 
733 	pgtable = pte_alloc_one(mm, haddr);
734 	if (unlikely(!pgtable)) {
735 		mem_cgroup_cancel_charge(page, memcg);
736 		put_page(page);
737 		return VM_FAULT_OOM;
738 	}
739 
740 	clear_huge_page(page, haddr, HPAGE_PMD_NR);
741 	/*
742 	 * The memory barrier inside __SetPageUptodate makes sure that
743 	 * clear_huge_page writes become visible before the set_pmd_at()
744 	 * write.
745 	 */
746 	__SetPageUptodate(page);
747 
748 	ptl = pmd_lock(mm, pmd);
749 	if (unlikely(!pmd_none(*pmd))) {
750 		spin_unlock(ptl);
751 		mem_cgroup_cancel_charge(page, memcg);
752 		put_page(page);
753 		pte_free(mm, pgtable);
754 	} else {
755 		pmd_t entry;
756 
757 		/* Deliver the page fault to userland */
758 		if (userfaultfd_missing(vma)) {
759 			int ret;
760 
761 			spin_unlock(ptl);
762 			mem_cgroup_cancel_charge(page, memcg);
763 			put_page(page);
764 			pte_free(mm, pgtable);
765 			ret = handle_userfault(vma, address, flags,
766 					       VM_UFFD_MISSING);
767 			VM_BUG_ON(ret & VM_FAULT_FALLBACK);
768 			return ret;
769 		}
770 
771 		entry = mk_huge_pmd(page, vma->vm_page_prot);
772 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
773 		page_add_new_anon_rmap(page, vma, haddr);
774 		mem_cgroup_commit_charge(page, memcg, false);
775 		lru_cache_add_active_or_unevictable(page, vma);
776 		pgtable_trans_huge_deposit(mm, pmd, pgtable);
777 		set_pmd_at(mm, haddr, pmd, entry);
778 		add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
779 		atomic_long_inc(&mm->nr_ptes);
780 		spin_unlock(ptl);
781 		count_vm_event(THP_FAULT_ALLOC);
782 	}
783 
784 	return 0;
785 }
786 
787 static inline gfp_t alloc_hugepage_gfpmask(int defrag, gfp_t extra_gfp)
788 {
789 	return (GFP_TRANSHUGE & ~(defrag ? 0 : __GFP_WAIT)) | extra_gfp;
790 }
791 
792 /* Caller must hold page table lock. */
793 static bool set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
794 		struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
795 		struct page *zero_page)
796 {
797 	pmd_t entry;
798 	if (!pmd_none(*pmd))
799 		return false;
800 	entry = mk_pmd(zero_page, vma->vm_page_prot);
801 	entry = pmd_mkhuge(entry);
802 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
803 	set_pmd_at(mm, haddr, pmd, entry);
804 	atomic_long_inc(&mm->nr_ptes);
805 	return true;
806 }
807 
808 int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
809 			       unsigned long address, pmd_t *pmd,
810 			       unsigned int flags)
811 {
812 	gfp_t gfp;
813 	struct page *page;
814 	unsigned long haddr = address & HPAGE_PMD_MASK;
815 
816 	if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
817 		return VM_FAULT_FALLBACK;
818 	if (unlikely(anon_vma_prepare(vma)))
819 		return VM_FAULT_OOM;
820 	if (unlikely(khugepaged_enter(vma, vma->vm_flags)))
821 		return VM_FAULT_OOM;
822 	if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm) &&
823 			transparent_hugepage_use_zero_page()) {
824 		spinlock_t *ptl;
825 		pgtable_t pgtable;
826 		struct page *zero_page;
827 		bool set;
828 		int ret;
829 		pgtable = pte_alloc_one(mm, haddr);
830 		if (unlikely(!pgtable))
831 			return VM_FAULT_OOM;
832 		zero_page = get_huge_zero_page();
833 		if (unlikely(!zero_page)) {
834 			pte_free(mm, pgtable);
835 			count_vm_event(THP_FAULT_FALLBACK);
836 			return VM_FAULT_FALLBACK;
837 		}
838 		ptl = pmd_lock(mm, pmd);
839 		ret = 0;
840 		set = false;
841 		if (pmd_none(*pmd)) {
842 			if (userfaultfd_missing(vma)) {
843 				spin_unlock(ptl);
844 				ret = handle_userfault(vma, address, flags,
845 						       VM_UFFD_MISSING);
846 				VM_BUG_ON(ret & VM_FAULT_FALLBACK);
847 			} else {
848 				set_huge_zero_page(pgtable, mm, vma,
849 						   haddr, pmd,
850 						   zero_page);
851 				spin_unlock(ptl);
852 				set = true;
853 			}
854 		} else
855 			spin_unlock(ptl);
856 		if (!set) {
857 			pte_free(mm, pgtable);
858 			put_huge_zero_page();
859 		}
860 		return ret;
861 	}
862 	gfp = alloc_hugepage_gfpmask(transparent_hugepage_defrag(vma), 0);
863 	page = alloc_hugepage_vma(gfp, vma, haddr, HPAGE_PMD_ORDER);
864 	if (unlikely(!page)) {
865 		count_vm_event(THP_FAULT_FALLBACK);
866 		return VM_FAULT_FALLBACK;
867 	}
868 	return __do_huge_pmd_anonymous_page(mm, vma, address, pmd, page, gfp,
869 					    flags);
870 }
871 
872 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
873 		pmd_t *pmd, unsigned long pfn, pgprot_t prot, bool write)
874 {
875 	struct mm_struct *mm = vma->vm_mm;
876 	pmd_t entry;
877 	spinlock_t *ptl;
878 
879 	ptl = pmd_lock(mm, pmd);
880 	if (pmd_none(*pmd)) {
881 		entry = pmd_mkhuge(pfn_pmd(pfn, prot));
882 		if (write) {
883 			entry = pmd_mkyoung(pmd_mkdirty(entry));
884 			entry = maybe_pmd_mkwrite(entry, vma);
885 		}
886 		set_pmd_at(mm, addr, pmd, entry);
887 		update_mmu_cache_pmd(vma, addr, pmd);
888 	}
889 	spin_unlock(ptl);
890 }
891 
892 int vmf_insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
893 			pmd_t *pmd, unsigned long pfn, bool write)
894 {
895 	pgprot_t pgprot = vma->vm_page_prot;
896 	/*
897 	 * If we had pmd_special, we could avoid all these restrictions,
898 	 * but we need to be consistent with PTEs and architectures that
899 	 * can't support a 'special' bit.
900 	 */
901 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
902 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
903 						(VM_PFNMAP|VM_MIXEDMAP));
904 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
905 	BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
906 
907 	if (addr < vma->vm_start || addr >= vma->vm_end)
908 		return VM_FAULT_SIGBUS;
909 	if (track_pfn_insert(vma, &pgprot, pfn))
910 		return VM_FAULT_SIGBUS;
911 	insert_pfn_pmd(vma, addr, pmd, pfn, pgprot, write);
912 	return VM_FAULT_NOPAGE;
913 }
914 
915 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
916 		  pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
917 		  struct vm_area_struct *vma)
918 {
919 	spinlock_t *dst_ptl, *src_ptl;
920 	struct page *src_page;
921 	pmd_t pmd;
922 	pgtable_t pgtable;
923 	int ret;
924 
925 	ret = -ENOMEM;
926 	pgtable = pte_alloc_one(dst_mm, addr);
927 	if (unlikely(!pgtable))
928 		goto out;
929 
930 	dst_ptl = pmd_lock(dst_mm, dst_pmd);
931 	src_ptl = pmd_lockptr(src_mm, src_pmd);
932 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
933 
934 	ret = -EAGAIN;
935 	pmd = *src_pmd;
936 	if (unlikely(!pmd_trans_huge(pmd))) {
937 		pte_free(dst_mm, pgtable);
938 		goto out_unlock;
939 	}
940 	/*
941 	 * When page table lock is held, the huge zero pmd should not be
942 	 * under splitting since we don't split the page itself, only pmd to
943 	 * a page table.
944 	 */
945 	if (is_huge_zero_pmd(pmd)) {
946 		struct page *zero_page;
947 		/*
948 		 * get_huge_zero_page() will never allocate a new page here,
949 		 * since we already have a zero page to copy. It just takes a
950 		 * reference.
951 		 */
952 		zero_page = get_huge_zero_page();
953 		set_huge_zero_page(pgtable, dst_mm, vma, addr, dst_pmd,
954 				zero_page);
955 		ret = 0;
956 		goto out_unlock;
957 	}
958 
959 	if (unlikely(pmd_trans_splitting(pmd))) {
960 		/* split huge page running from under us */
961 		spin_unlock(src_ptl);
962 		spin_unlock(dst_ptl);
963 		pte_free(dst_mm, pgtable);
964 
965 		wait_split_huge_page(vma->anon_vma, src_pmd); /* src_vma */
966 		goto out;
967 	}
968 	src_page = pmd_page(pmd);
969 	VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
970 	get_page(src_page);
971 	page_dup_rmap(src_page);
972 	add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
973 
974 	pmdp_set_wrprotect(src_mm, addr, src_pmd);
975 	pmd = pmd_mkold(pmd_wrprotect(pmd));
976 	pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
977 	set_pmd_at(dst_mm, addr, dst_pmd, pmd);
978 	atomic_long_inc(&dst_mm->nr_ptes);
979 
980 	ret = 0;
981 out_unlock:
982 	spin_unlock(src_ptl);
983 	spin_unlock(dst_ptl);
984 out:
985 	return ret;
986 }
987 
988 void huge_pmd_set_accessed(struct mm_struct *mm,
989 			   struct vm_area_struct *vma,
990 			   unsigned long address,
991 			   pmd_t *pmd, pmd_t orig_pmd,
992 			   int dirty)
993 {
994 	spinlock_t *ptl;
995 	pmd_t entry;
996 	unsigned long haddr;
997 
998 	ptl = pmd_lock(mm, pmd);
999 	if (unlikely(!pmd_same(*pmd, orig_pmd)))
1000 		goto unlock;
1001 
1002 	entry = pmd_mkyoung(orig_pmd);
1003 	haddr = address & HPAGE_PMD_MASK;
1004 	if (pmdp_set_access_flags(vma, haddr, pmd, entry, dirty))
1005 		update_mmu_cache_pmd(vma, address, pmd);
1006 
1007 unlock:
1008 	spin_unlock(ptl);
1009 }
1010 
1011 /*
1012  * Save CONFIG_DEBUG_PAGEALLOC from faulting falsely on tail pages
1013  * during copy_user_huge_page()'s copy_page_rep(): in the case when
1014  * the source page gets split and a tail freed before copy completes.
1015  * Called under pmd_lock of checked pmd, so safe from splitting itself.
1016  */
1017 static void get_user_huge_page(struct page *page)
1018 {
1019 	if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC)) {
1020 		struct page *endpage = page + HPAGE_PMD_NR;
1021 
1022 		atomic_add(HPAGE_PMD_NR, &page->_count);
1023 		while (++page < endpage)
1024 			get_huge_page_tail(page);
1025 	} else {
1026 		get_page(page);
1027 	}
1028 }
1029 
1030 static void put_user_huge_page(struct page *page)
1031 {
1032 	if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC)) {
1033 		struct page *endpage = page + HPAGE_PMD_NR;
1034 
1035 		while (page < endpage)
1036 			put_page(page++);
1037 	} else {
1038 		put_page(page);
1039 	}
1040 }
1041 
1042 static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
1043 					struct vm_area_struct *vma,
1044 					unsigned long address,
1045 					pmd_t *pmd, pmd_t orig_pmd,
1046 					struct page *page,
1047 					unsigned long haddr)
1048 {
1049 	struct mem_cgroup *memcg;
1050 	spinlock_t *ptl;
1051 	pgtable_t pgtable;
1052 	pmd_t _pmd;
1053 	int ret = 0, i;
1054 	struct page **pages;
1055 	unsigned long mmun_start;	/* For mmu_notifiers */
1056 	unsigned long mmun_end;		/* For mmu_notifiers */
1057 
1058 	pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
1059 			GFP_KERNEL);
1060 	if (unlikely(!pages)) {
1061 		ret |= VM_FAULT_OOM;
1062 		goto out;
1063 	}
1064 
1065 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1066 		pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
1067 					       __GFP_OTHER_NODE,
1068 					       vma, address, page_to_nid(page));
1069 		if (unlikely(!pages[i] ||
1070 			     mem_cgroup_try_charge(pages[i], mm, GFP_KERNEL,
1071 						   &memcg))) {
1072 			if (pages[i])
1073 				put_page(pages[i]);
1074 			while (--i >= 0) {
1075 				memcg = (void *)page_private(pages[i]);
1076 				set_page_private(pages[i], 0);
1077 				mem_cgroup_cancel_charge(pages[i], memcg);
1078 				put_page(pages[i]);
1079 			}
1080 			kfree(pages);
1081 			ret |= VM_FAULT_OOM;
1082 			goto out;
1083 		}
1084 		set_page_private(pages[i], (unsigned long)memcg);
1085 	}
1086 
1087 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1088 		copy_user_highpage(pages[i], page + i,
1089 				   haddr + PAGE_SIZE * i, vma);
1090 		__SetPageUptodate(pages[i]);
1091 		cond_resched();
1092 	}
1093 
1094 	mmun_start = haddr;
1095 	mmun_end   = haddr + HPAGE_PMD_SIZE;
1096 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1097 
1098 	ptl = pmd_lock(mm, pmd);
1099 	if (unlikely(!pmd_same(*pmd, orig_pmd)))
1100 		goto out_free_pages;
1101 	VM_BUG_ON_PAGE(!PageHead(page), page);
1102 
1103 	pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1104 	/* leave pmd empty until pte is filled */
1105 
1106 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1107 	pmd_populate(mm, &_pmd, pgtable);
1108 
1109 	for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1110 		pte_t *pte, entry;
1111 		entry = mk_pte(pages[i], vma->vm_page_prot);
1112 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1113 		memcg = (void *)page_private(pages[i]);
1114 		set_page_private(pages[i], 0);
1115 		page_add_new_anon_rmap(pages[i], vma, haddr);
1116 		mem_cgroup_commit_charge(pages[i], memcg, false);
1117 		lru_cache_add_active_or_unevictable(pages[i], vma);
1118 		pte = pte_offset_map(&_pmd, haddr);
1119 		VM_BUG_ON(!pte_none(*pte));
1120 		set_pte_at(mm, haddr, pte, entry);
1121 		pte_unmap(pte);
1122 	}
1123 	kfree(pages);
1124 
1125 	smp_wmb(); /* make pte visible before pmd */
1126 	pmd_populate(mm, pmd, pgtable);
1127 	page_remove_rmap(page);
1128 	spin_unlock(ptl);
1129 
1130 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1131 
1132 	ret |= VM_FAULT_WRITE;
1133 	put_page(page);
1134 
1135 out:
1136 	return ret;
1137 
1138 out_free_pages:
1139 	spin_unlock(ptl);
1140 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1141 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1142 		memcg = (void *)page_private(pages[i]);
1143 		set_page_private(pages[i], 0);
1144 		mem_cgroup_cancel_charge(pages[i], memcg);
1145 		put_page(pages[i]);
1146 	}
1147 	kfree(pages);
1148 	goto out;
1149 }
1150 
1151 int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
1152 			unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
1153 {
1154 	spinlock_t *ptl;
1155 	int ret = 0;
1156 	struct page *page = NULL, *new_page;
1157 	struct mem_cgroup *memcg;
1158 	unsigned long haddr;
1159 	unsigned long mmun_start;	/* For mmu_notifiers */
1160 	unsigned long mmun_end;		/* For mmu_notifiers */
1161 	gfp_t huge_gfp;			/* for allocation and charge */
1162 
1163 	ptl = pmd_lockptr(mm, pmd);
1164 	VM_BUG_ON_VMA(!vma->anon_vma, vma);
1165 	haddr = address & HPAGE_PMD_MASK;
1166 	if (is_huge_zero_pmd(orig_pmd))
1167 		goto alloc;
1168 	spin_lock(ptl);
1169 	if (unlikely(!pmd_same(*pmd, orig_pmd)))
1170 		goto out_unlock;
1171 
1172 	page = pmd_page(orig_pmd);
1173 	VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
1174 	if (page_mapcount(page) == 1) {
1175 		pmd_t entry;
1176 		entry = pmd_mkyoung(orig_pmd);
1177 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1178 		if (pmdp_set_access_flags(vma, haddr, pmd, entry,  1))
1179 			update_mmu_cache_pmd(vma, address, pmd);
1180 		ret |= VM_FAULT_WRITE;
1181 		goto out_unlock;
1182 	}
1183 	get_user_huge_page(page);
1184 	spin_unlock(ptl);
1185 alloc:
1186 	if (transparent_hugepage_enabled(vma) &&
1187 	    !transparent_hugepage_debug_cow()) {
1188 		huge_gfp = alloc_hugepage_gfpmask(transparent_hugepage_defrag(vma), 0);
1189 		new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
1190 	} else
1191 		new_page = NULL;
1192 
1193 	if (unlikely(!new_page)) {
1194 		if (!page) {
1195 			split_huge_page_pmd(vma, address, pmd);
1196 			ret |= VM_FAULT_FALLBACK;
1197 		} else {
1198 			ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
1199 					pmd, orig_pmd, page, haddr);
1200 			if (ret & VM_FAULT_OOM) {
1201 				split_huge_page(page);
1202 				ret |= VM_FAULT_FALLBACK;
1203 			}
1204 			put_user_huge_page(page);
1205 		}
1206 		count_vm_event(THP_FAULT_FALLBACK);
1207 		goto out;
1208 	}
1209 
1210 	if (unlikely(mem_cgroup_try_charge(new_page, mm, huge_gfp, &memcg))) {
1211 		put_page(new_page);
1212 		if (page) {
1213 			split_huge_page(page);
1214 			put_user_huge_page(page);
1215 		} else
1216 			split_huge_page_pmd(vma, address, pmd);
1217 		ret |= VM_FAULT_FALLBACK;
1218 		count_vm_event(THP_FAULT_FALLBACK);
1219 		goto out;
1220 	}
1221 
1222 	count_vm_event(THP_FAULT_ALLOC);
1223 
1224 	if (!page)
1225 		clear_huge_page(new_page, haddr, HPAGE_PMD_NR);
1226 	else
1227 		copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
1228 	__SetPageUptodate(new_page);
1229 
1230 	mmun_start = haddr;
1231 	mmun_end   = haddr + HPAGE_PMD_SIZE;
1232 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1233 
1234 	spin_lock(ptl);
1235 	if (page)
1236 		put_user_huge_page(page);
1237 	if (unlikely(!pmd_same(*pmd, orig_pmd))) {
1238 		spin_unlock(ptl);
1239 		mem_cgroup_cancel_charge(new_page, memcg);
1240 		put_page(new_page);
1241 		goto out_mn;
1242 	} else {
1243 		pmd_t entry;
1244 		entry = mk_huge_pmd(new_page, vma->vm_page_prot);
1245 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1246 		pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1247 		page_add_new_anon_rmap(new_page, vma, haddr);
1248 		mem_cgroup_commit_charge(new_page, memcg, false);
1249 		lru_cache_add_active_or_unevictable(new_page, vma);
1250 		set_pmd_at(mm, haddr, pmd, entry);
1251 		update_mmu_cache_pmd(vma, address, pmd);
1252 		if (!page) {
1253 			add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
1254 			put_huge_zero_page();
1255 		} else {
1256 			VM_BUG_ON_PAGE(!PageHead(page), page);
1257 			page_remove_rmap(page);
1258 			put_page(page);
1259 		}
1260 		ret |= VM_FAULT_WRITE;
1261 	}
1262 	spin_unlock(ptl);
1263 out_mn:
1264 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1265 out:
1266 	return ret;
1267 out_unlock:
1268 	spin_unlock(ptl);
1269 	return ret;
1270 }
1271 
1272 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1273 				   unsigned long addr,
1274 				   pmd_t *pmd,
1275 				   unsigned int flags)
1276 {
1277 	struct mm_struct *mm = vma->vm_mm;
1278 	struct page *page = NULL;
1279 
1280 	assert_spin_locked(pmd_lockptr(mm, pmd));
1281 
1282 	if (flags & FOLL_WRITE && !pmd_write(*pmd))
1283 		goto out;
1284 
1285 	/* Avoid dumping huge zero page */
1286 	if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1287 		return ERR_PTR(-EFAULT);
1288 
1289 	/* Full NUMA hinting faults to serialise migration in fault paths */
1290 	if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
1291 		goto out;
1292 
1293 	page = pmd_page(*pmd);
1294 	VM_BUG_ON_PAGE(!PageHead(page), page);
1295 	if (flags & FOLL_TOUCH) {
1296 		pmd_t _pmd;
1297 		/*
1298 		 * We should set the dirty bit only for FOLL_WRITE but
1299 		 * for now the dirty bit in the pmd is meaningless.
1300 		 * And if the dirty bit will become meaningful and
1301 		 * we'll only set it with FOLL_WRITE, an atomic
1302 		 * set_bit will be required on the pmd to set the
1303 		 * young bit, instead of the current set_pmd_at.
1304 		 */
1305 		_pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
1306 		if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1307 					  pmd, _pmd,  1))
1308 			update_mmu_cache_pmd(vma, addr, pmd);
1309 	}
1310 	if ((flags & FOLL_POPULATE) && (vma->vm_flags & VM_LOCKED)) {
1311 		if (page->mapping && trylock_page(page)) {
1312 			lru_add_drain();
1313 			if (page->mapping)
1314 				mlock_vma_page(page);
1315 			unlock_page(page);
1316 		}
1317 	}
1318 	page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1319 	VM_BUG_ON_PAGE(!PageCompound(page), page);
1320 	if (flags & FOLL_GET)
1321 		get_page_foll(page);
1322 
1323 out:
1324 	return page;
1325 }
1326 
1327 /* NUMA hinting page fault entry point for trans huge pmds */
1328 int do_huge_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
1329 				unsigned long addr, pmd_t pmd, pmd_t *pmdp)
1330 {
1331 	spinlock_t *ptl;
1332 	struct anon_vma *anon_vma = NULL;
1333 	struct page *page;
1334 	unsigned long haddr = addr & HPAGE_PMD_MASK;
1335 	int page_nid = -1, this_nid = numa_node_id();
1336 	int target_nid, last_cpupid = -1;
1337 	bool page_locked;
1338 	bool migrated = false;
1339 	bool was_writable;
1340 	int flags = 0;
1341 
1342 	/* A PROT_NONE fault should not end up here */
1343 	BUG_ON(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)));
1344 
1345 	ptl = pmd_lock(mm, pmdp);
1346 	if (unlikely(!pmd_same(pmd, *pmdp)))
1347 		goto out_unlock;
1348 
1349 	/*
1350 	 * If there are potential migrations, wait for completion and retry
1351 	 * without disrupting NUMA hinting information. Do not relock and
1352 	 * check_same as the page may no longer be mapped.
1353 	 */
1354 	if (unlikely(pmd_trans_migrating(*pmdp))) {
1355 		page = pmd_page(*pmdp);
1356 		spin_unlock(ptl);
1357 		wait_on_page_locked(page);
1358 		goto out;
1359 	}
1360 
1361 	page = pmd_page(pmd);
1362 	BUG_ON(is_huge_zero_page(page));
1363 	page_nid = page_to_nid(page);
1364 	last_cpupid = page_cpupid_last(page);
1365 	count_vm_numa_event(NUMA_HINT_FAULTS);
1366 	if (page_nid == this_nid) {
1367 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
1368 		flags |= TNF_FAULT_LOCAL;
1369 	}
1370 
1371 	/* See similar comment in do_numa_page for explanation */
1372 	if (!(vma->vm_flags & VM_WRITE))
1373 		flags |= TNF_NO_GROUP;
1374 
1375 	/*
1376 	 * Acquire the page lock to serialise THP migrations but avoid dropping
1377 	 * page_table_lock if at all possible
1378 	 */
1379 	page_locked = trylock_page(page);
1380 	target_nid = mpol_misplaced(page, vma, haddr);
1381 	if (target_nid == -1) {
1382 		/* If the page was locked, there are no parallel migrations */
1383 		if (page_locked)
1384 			goto clear_pmdnuma;
1385 	}
1386 
1387 	/* Migration could have started since the pmd_trans_migrating check */
1388 	if (!page_locked) {
1389 		spin_unlock(ptl);
1390 		wait_on_page_locked(page);
1391 		page_nid = -1;
1392 		goto out;
1393 	}
1394 
1395 	/*
1396 	 * Page is misplaced. Page lock serialises migrations. Acquire anon_vma
1397 	 * to serialises splits
1398 	 */
1399 	get_page(page);
1400 	spin_unlock(ptl);
1401 	anon_vma = page_lock_anon_vma_read(page);
1402 
1403 	/* Confirm the PMD did not change while page_table_lock was released */
1404 	spin_lock(ptl);
1405 	if (unlikely(!pmd_same(pmd, *pmdp))) {
1406 		unlock_page(page);
1407 		put_page(page);
1408 		page_nid = -1;
1409 		goto out_unlock;
1410 	}
1411 
1412 	/* Bail if we fail to protect against THP splits for any reason */
1413 	if (unlikely(!anon_vma)) {
1414 		put_page(page);
1415 		page_nid = -1;
1416 		goto clear_pmdnuma;
1417 	}
1418 
1419 	/*
1420 	 * Migrate the THP to the requested node, returns with page unlocked
1421 	 * and access rights restored.
1422 	 */
1423 	spin_unlock(ptl);
1424 	migrated = migrate_misplaced_transhuge_page(mm, vma,
1425 				pmdp, pmd, addr, page, target_nid);
1426 	if (migrated) {
1427 		flags |= TNF_MIGRATED;
1428 		page_nid = target_nid;
1429 	} else
1430 		flags |= TNF_MIGRATE_FAIL;
1431 
1432 	goto out;
1433 clear_pmdnuma:
1434 	BUG_ON(!PageLocked(page));
1435 	was_writable = pmd_write(pmd);
1436 	pmd = pmd_modify(pmd, vma->vm_page_prot);
1437 	pmd = pmd_mkyoung(pmd);
1438 	if (was_writable)
1439 		pmd = pmd_mkwrite(pmd);
1440 	set_pmd_at(mm, haddr, pmdp, pmd);
1441 	update_mmu_cache_pmd(vma, addr, pmdp);
1442 	unlock_page(page);
1443 out_unlock:
1444 	spin_unlock(ptl);
1445 
1446 out:
1447 	if (anon_vma)
1448 		page_unlock_anon_vma_read(anon_vma);
1449 
1450 	if (page_nid != -1)
1451 		task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR, flags);
1452 
1453 	return 0;
1454 }
1455 
1456 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1457 		 pmd_t *pmd, unsigned long addr)
1458 {
1459 	pmd_t orig_pmd;
1460 	spinlock_t *ptl;
1461 
1462 	if (__pmd_trans_huge_lock(pmd, vma, &ptl) != 1)
1463 		return 0;
1464 	/*
1465 	 * For architectures like ppc64 we look at deposited pgtable
1466 	 * when calling pmdp_huge_get_and_clear. So do the
1467 	 * pgtable_trans_huge_withdraw after finishing pmdp related
1468 	 * operations.
1469 	 */
1470 	orig_pmd = pmdp_huge_get_and_clear_full(tlb->mm, addr, pmd,
1471 			tlb->fullmm);
1472 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1473 	if (vma_is_dax(vma)) {
1474 		spin_unlock(ptl);
1475 		if (is_huge_zero_pmd(orig_pmd))
1476 			put_huge_zero_page();
1477 	} else if (is_huge_zero_pmd(orig_pmd)) {
1478 		pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1479 		atomic_long_dec(&tlb->mm->nr_ptes);
1480 		spin_unlock(ptl);
1481 		put_huge_zero_page();
1482 	} else {
1483 		struct page *page = pmd_page(orig_pmd);
1484 		page_remove_rmap(page);
1485 		VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1486 		add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1487 		VM_BUG_ON_PAGE(!PageHead(page), page);
1488 		pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1489 		atomic_long_dec(&tlb->mm->nr_ptes);
1490 		spin_unlock(ptl);
1491 		tlb_remove_page(tlb, page);
1492 	}
1493 	return 1;
1494 }
1495 
1496 int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1497 		  unsigned long old_addr,
1498 		  unsigned long new_addr, unsigned long old_end,
1499 		  pmd_t *old_pmd, pmd_t *new_pmd)
1500 {
1501 	spinlock_t *old_ptl, *new_ptl;
1502 	int ret = 0;
1503 	pmd_t pmd;
1504 
1505 	struct mm_struct *mm = vma->vm_mm;
1506 
1507 	if ((old_addr & ~HPAGE_PMD_MASK) ||
1508 	    (new_addr & ~HPAGE_PMD_MASK) ||
1509 	    old_end - old_addr < HPAGE_PMD_SIZE ||
1510 	    (new_vma->vm_flags & VM_NOHUGEPAGE))
1511 		goto out;
1512 
1513 	/*
1514 	 * The destination pmd shouldn't be established, free_pgtables()
1515 	 * should have release it.
1516 	 */
1517 	if (WARN_ON(!pmd_none(*new_pmd))) {
1518 		VM_BUG_ON(pmd_trans_huge(*new_pmd));
1519 		goto out;
1520 	}
1521 
1522 	/*
1523 	 * We don't have to worry about the ordering of src and dst
1524 	 * ptlocks because exclusive mmap_sem prevents deadlock.
1525 	 */
1526 	ret = __pmd_trans_huge_lock(old_pmd, vma, &old_ptl);
1527 	if (ret == 1) {
1528 		new_ptl = pmd_lockptr(mm, new_pmd);
1529 		if (new_ptl != old_ptl)
1530 			spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1531 		pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1532 		VM_BUG_ON(!pmd_none(*new_pmd));
1533 
1534 		if (pmd_move_must_withdraw(new_ptl, old_ptl)) {
1535 			pgtable_t pgtable;
1536 			pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1537 			pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1538 		}
1539 		set_pmd_at(mm, new_addr, new_pmd, pmd_mksoft_dirty(pmd));
1540 		if (new_ptl != old_ptl)
1541 			spin_unlock(new_ptl);
1542 		spin_unlock(old_ptl);
1543 	}
1544 out:
1545 	return ret;
1546 }
1547 
1548 /*
1549  * Returns
1550  *  - 0 if PMD could not be locked
1551  *  - 1 if PMD was locked but protections unchange and TLB flush unnecessary
1552  *  - HPAGE_PMD_NR is protections changed and TLB flush necessary
1553  */
1554 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1555 		unsigned long addr, pgprot_t newprot, int prot_numa)
1556 {
1557 	struct mm_struct *mm = vma->vm_mm;
1558 	spinlock_t *ptl;
1559 	int ret = 0;
1560 
1561 	if (__pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
1562 		pmd_t entry;
1563 		bool preserve_write = prot_numa && pmd_write(*pmd);
1564 		ret = 1;
1565 
1566 		/*
1567 		 * Avoid trapping faults against the zero page. The read-only
1568 		 * data is likely to be read-cached on the local CPU and
1569 		 * local/remote hits to the zero page are not interesting.
1570 		 */
1571 		if (prot_numa && is_huge_zero_pmd(*pmd)) {
1572 			spin_unlock(ptl);
1573 			return ret;
1574 		}
1575 
1576 		if (!prot_numa || !pmd_protnone(*pmd)) {
1577 			entry = pmdp_huge_get_and_clear_notify(mm, addr, pmd);
1578 			entry = pmd_modify(entry, newprot);
1579 			if (preserve_write)
1580 				entry = pmd_mkwrite(entry);
1581 			ret = HPAGE_PMD_NR;
1582 			set_pmd_at(mm, addr, pmd, entry);
1583 			BUG_ON(!preserve_write && pmd_write(entry));
1584 		}
1585 		spin_unlock(ptl);
1586 	}
1587 
1588 	return ret;
1589 }
1590 
1591 /*
1592  * Returns 1 if a given pmd maps a stable (not under splitting) thp.
1593  * Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
1594  *
1595  * Note that if it returns 1, this routine returns without unlocking page
1596  * table locks. So callers must unlock them.
1597  */
1598 int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma,
1599 		spinlock_t **ptl)
1600 {
1601 	*ptl = pmd_lock(vma->vm_mm, pmd);
1602 	if (likely(pmd_trans_huge(*pmd))) {
1603 		if (unlikely(pmd_trans_splitting(*pmd))) {
1604 			spin_unlock(*ptl);
1605 			wait_split_huge_page(vma->anon_vma, pmd);
1606 			return -1;
1607 		} else {
1608 			/* Thp mapped by 'pmd' is stable, so we can
1609 			 * handle it as it is. */
1610 			return 1;
1611 		}
1612 	}
1613 	spin_unlock(*ptl);
1614 	return 0;
1615 }
1616 
1617 /*
1618  * This function returns whether a given @page is mapped onto the @address
1619  * in the virtual space of @mm.
1620  *
1621  * When it's true, this function returns *pmd with holding the page table lock
1622  * and passing it back to the caller via @ptl.
1623  * If it's false, returns NULL without holding the page table lock.
1624  */
1625 pmd_t *page_check_address_pmd(struct page *page,
1626 			      struct mm_struct *mm,
1627 			      unsigned long address,
1628 			      enum page_check_address_pmd_flag flag,
1629 			      spinlock_t **ptl)
1630 {
1631 	pgd_t *pgd;
1632 	pud_t *pud;
1633 	pmd_t *pmd;
1634 
1635 	if (address & ~HPAGE_PMD_MASK)
1636 		return NULL;
1637 
1638 	pgd = pgd_offset(mm, address);
1639 	if (!pgd_present(*pgd))
1640 		return NULL;
1641 	pud = pud_offset(pgd, address);
1642 	if (!pud_present(*pud))
1643 		return NULL;
1644 	pmd = pmd_offset(pud, address);
1645 
1646 	*ptl = pmd_lock(mm, pmd);
1647 	if (!pmd_present(*pmd))
1648 		goto unlock;
1649 	if (pmd_page(*pmd) != page)
1650 		goto unlock;
1651 	/*
1652 	 * split_vma() may create temporary aliased mappings. There is
1653 	 * no risk as long as all huge pmd are found and have their
1654 	 * splitting bit set before __split_huge_page_refcount
1655 	 * runs. Finding the same huge pmd more than once during the
1656 	 * same rmap walk is not a problem.
1657 	 */
1658 	if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1659 	    pmd_trans_splitting(*pmd))
1660 		goto unlock;
1661 	if (pmd_trans_huge(*pmd)) {
1662 		VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1663 			  !pmd_trans_splitting(*pmd));
1664 		return pmd;
1665 	}
1666 unlock:
1667 	spin_unlock(*ptl);
1668 	return NULL;
1669 }
1670 
1671 static int __split_huge_page_splitting(struct page *page,
1672 				       struct vm_area_struct *vma,
1673 				       unsigned long address)
1674 {
1675 	struct mm_struct *mm = vma->vm_mm;
1676 	spinlock_t *ptl;
1677 	pmd_t *pmd;
1678 	int ret = 0;
1679 	/* For mmu_notifiers */
1680 	const unsigned long mmun_start = address;
1681 	const unsigned long mmun_end   = address + HPAGE_PMD_SIZE;
1682 
1683 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1684 	pmd = page_check_address_pmd(page, mm, address,
1685 			PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG, &ptl);
1686 	if (pmd) {
1687 		/*
1688 		 * We can't temporarily set the pmd to null in order
1689 		 * to split it, the pmd must remain marked huge at all
1690 		 * times or the VM won't take the pmd_trans_huge paths
1691 		 * and it won't wait on the anon_vma->root->rwsem to
1692 		 * serialize against split_huge_page*.
1693 		 */
1694 		pmdp_splitting_flush(vma, address, pmd);
1695 
1696 		ret = 1;
1697 		spin_unlock(ptl);
1698 	}
1699 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1700 
1701 	return ret;
1702 }
1703 
1704 static void __split_huge_page_refcount(struct page *page,
1705 				       struct list_head *list)
1706 {
1707 	int i;
1708 	struct zone *zone = page_zone(page);
1709 	struct lruvec *lruvec;
1710 	int tail_count = 0;
1711 
1712 	/* prevent PageLRU to go away from under us, and freeze lru stats */
1713 	spin_lock_irq(&zone->lru_lock);
1714 	lruvec = mem_cgroup_page_lruvec(page, zone);
1715 
1716 	compound_lock(page);
1717 	/* complete memcg works before add pages to LRU */
1718 	mem_cgroup_split_huge_fixup(page);
1719 
1720 	for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
1721 		struct page *page_tail = page + i;
1722 
1723 		/* tail_page->_mapcount cannot change */
1724 		BUG_ON(page_mapcount(page_tail) < 0);
1725 		tail_count += page_mapcount(page_tail);
1726 		/* check for overflow */
1727 		BUG_ON(tail_count < 0);
1728 		BUG_ON(atomic_read(&page_tail->_count) != 0);
1729 		/*
1730 		 * tail_page->_count is zero and not changing from
1731 		 * under us. But get_page_unless_zero() may be running
1732 		 * from under us on the tail_page. If we used
1733 		 * atomic_set() below instead of atomic_add(), we
1734 		 * would then run atomic_set() concurrently with
1735 		 * get_page_unless_zero(), and atomic_set() is
1736 		 * implemented in C not using locked ops. spin_unlock
1737 		 * on x86 sometime uses locked ops because of PPro
1738 		 * errata 66, 92, so unless somebody can guarantee
1739 		 * atomic_set() here would be safe on all archs (and
1740 		 * not only on x86), it's safer to use atomic_add().
1741 		 */
1742 		atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1743 			   &page_tail->_count);
1744 
1745 		/* after clearing PageTail the gup refcount can be released */
1746 		smp_mb__after_atomic();
1747 
1748 		page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1749 		page_tail->flags |= (page->flags &
1750 				     ((1L << PG_referenced) |
1751 				      (1L << PG_swapbacked) |
1752 				      (1L << PG_mlocked) |
1753 				      (1L << PG_uptodate) |
1754 				      (1L << PG_active) |
1755 				      (1L << PG_unevictable)));
1756 		page_tail->flags |= (1L << PG_dirty);
1757 
1758 		/* clear PageTail before overwriting first_page */
1759 		smp_wmb();
1760 
1761 		if (page_is_young(page))
1762 			set_page_young(page_tail);
1763 		if (page_is_idle(page))
1764 			set_page_idle(page_tail);
1765 
1766 		/*
1767 		 * __split_huge_page_splitting() already set the
1768 		 * splitting bit in all pmd that could map this
1769 		 * hugepage, that will ensure no CPU can alter the
1770 		 * mapcount on the head page. The mapcount is only
1771 		 * accounted in the head page and it has to be
1772 		 * transferred to all tail pages in the below code. So
1773 		 * for this code to be safe, the split the mapcount
1774 		 * can't change. But that doesn't mean userland can't
1775 		 * keep changing and reading the page contents while
1776 		 * we transfer the mapcount, so the pmd splitting
1777 		 * status is achieved setting a reserved bit in the
1778 		 * pmd, not by clearing the present bit.
1779 		*/
1780 		page_tail->_mapcount = page->_mapcount;
1781 
1782 		BUG_ON(page_tail->mapping);
1783 		page_tail->mapping = page->mapping;
1784 
1785 		page_tail->index = page->index + i;
1786 		page_cpupid_xchg_last(page_tail, page_cpupid_last(page));
1787 
1788 		BUG_ON(!PageAnon(page_tail));
1789 		BUG_ON(!PageUptodate(page_tail));
1790 		BUG_ON(!PageDirty(page_tail));
1791 		BUG_ON(!PageSwapBacked(page_tail));
1792 
1793 		lru_add_page_tail(page, page_tail, lruvec, list);
1794 	}
1795 	atomic_sub(tail_count, &page->_count);
1796 	BUG_ON(atomic_read(&page->_count) <= 0);
1797 
1798 	__mod_zone_page_state(zone, NR_ANON_TRANSPARENT_HUGEPAGES, -1);
1799 
1800 	ClearPageCompound(page);
1801 	compound_unlock(page);
1802 	spin_unlock_irq(&zone->lru_lock);
1803 
1804 	for (i = 1; i < HPAGE_PMD_NR; i++) {
1805 		struct page *page_tail = page + i;
1806 		BUG_ON(page_count(page_tail) <= 0);
1807 		/*
1808 		 * Tail pages may be freed if there wasn't any mapping
1809 		 * like if add_to_swap() is running on a lru page that
1810 		 * had its mapping zapped. And freeing these pages
1811 		 * requires taking the lru_lock so we do the put_page
1812 		 * of the tail pages after the split is complete.
1813 		 */
1814 		put_page(page_tail);
1815 	}
1816 
1817 	/*
1818 	 * Only the head page (now become a regular page) is required
1819 	 * to be pinned by the caller.
1820 	 */
1821 	BUG_ON(page_count(page) <= 0);
1822 }
1823 
1824 static int __split_huge_page_map(struct page *page,
1825 				 struct vm_area_struct *vma,
1826 				 unsigned long address)
1827 {
1828 	struct mm_struct *mm = vma->vm_mm;
1829 	spinlock_t *ptl;
1830 	pmd_t *pmd, _pmd;
1831 	int ret = 0, i;
1832 	pgtable_t pgtable;
1833 	unsigned long haddr;
1834 
1835 	pmd = page_check_address_pmd(page, mm, address,
1836 			PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG, &ptl);
1837 	if (pmd) {
1838 		pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1839 		pmd_populate(mm, &_pmd, pgtable);
1840 		if (pmd_write(*pmd))
1841 			BUG_ON(page_mapcount(page) != 1);
1842 
1843 		haddr = address;
1844 		for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1845 			pte_t *pte, entry;
1846 			BUG_ON(PageCompound(page+i));
1847 			/*
1848 			 * Note that NUMA hinting access restrictions are not
1849 			 * transferred to avoid any possibility of altering
1850 			 * permissions across VMAs.
1851 			 */
1852 			entry = mk_pte(page + i, vma->vm_page_prot);
1853 			entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1854 			if (!pmd_write(*pmd))
1855 				entry = pte_wrprotect(entry);
1856 			if (!pmd_young(*pmd))
1857 				entry = pte_mkold(entry);
1858 			pte = pte_offset_map(&_pmd, haddr);
1859 			BUG_ON(!pte_none(*pte));
1860 			set_pte_at(mm, haddr, pte, entry);
1861 			pte_unmap(pte);
1862 		}
1863 
1864 		smp_wmb(); /* make pte visible before pmd */
1865 		/*
1866 		 * Up to this point the pmd is present and huge and
1867 		 * userland has the whole access to the hugepage
1868 		 * during the split (which happens in place). If we
1869 		 * overwrite the pmd with the not-huge version
1870 		 * pointing to the pte here (which of course we could
1871 		 * if all CPUs were bug free), userland could trigger
1872 		 * a small page size TLB miss on the small sized TLB
1873 		 * while the hugepage TLB entry is still established
1874 		 * in the huge TLB. Some CPU doesn't like that. See
1875 		 * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1876 		 * Erratum 383 on page 93. Intel should be safe but is
1877 		 * also warns that it's only safe if the permission
1878 		 * and cache attributes of the two entries loaded in
1879 		 * the two TLB is identical (which should be the case
1880 		 * here). But it is generally safer to never allow
1881 		 * small and huge TLB entries for the same virtual
1882 		 * address to be loaded simultaneously. So instead of
1883 		 * doing "pmd_populate(); flush_tlb_range();" we first
1884 		 * mark the current pmd notpresent (atomically because
1885 		 * here the pmd_trans_huge and pmd_trans_splitting
1886 		 * must remain set at all times on the pmd until the
1887 		 * split is complete for this pmd), then we flush the
1888 		 * SMP TLB and finally we write the non-huge version
1889 		 * of the pmd entry with pmd_populate.
1890 		 */
1891 		pmdp_invalidate(vma, address, pmd);
1892 		pmd_populate(mm, pmd, pgtable);
1893 		ret = 1;
1894 		spin_unlock(ptl);
1895 	}
1896 
1897 	return ret;
1898 }
1899 
1900 /* must be called with anon_vma->root->rwsem held */
1901 static void __split_huge_page(struct page *page,
1902 			      struct anon_vma *anon_vma,
1903 			      struct list_head *list)
1904 {
1905 	int mapcount, mapcount2;
1906 	pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
1907 	struct anon_vma_chain *avc;
1908 
1909 	BUG_ON(!PageHead(page));
1910 	BUG_ON(PageTail(page));
1911 
1912 	mapcount = 0;
1913 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1914 		struct vm_area_struct *vma = avc->vma;
1915 		unsigned long addr = vma_address(page, vma);
1916 		BUG_ON(is_vma_temporary_stack(vma));
1917 		mapcount += __split_huge_page_splitting(page, vma, addr);
1918 	}
1919 	/*
1920 	 * It is critical that new vmas are added to the tail of the
1921 	 * anon_vma list. This guarantes that if copy_huge_pmd() runs
1922 	 * and establishes a child pmd before
1923 	 * __split_huge_page_splitting() freezes the parent pmd (so if
1924 	 * we fail to prevent copy_huge_pmd() from running until the
1925 	 * whole __split_huge_page() is complete), we will still see
1926 	 * the newly established pmd of the child later during the
1927 	 * walk, to be able to set it as pmd_trans_splitting too.
1928 	 */
1929 	if (mapcount != page_mapcount(page)) {
1930 		pr_err("mapcount %d page_mapcount %d\n",
1931 			mapcount, page_mapcount(page));
1932 		BUG();
1933 	}
1934 
1935 	__split_huge_page_refcount(page, list);
1936 
1937 	mapcount2 = 0;
1938 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1939 		struct vm_area_struct *vma = avc->vma;
1940 		unsigned long addr = vma_address(page, vma);
1941 		BUG_ON(is_vma_temporary_stack(vma));
1942 		mapcount2 += __split_huge_page_map(page, vma, addr);
1943 	}
1944 	if (mapcount != mapcount2) {
1945 		pr_err("mapcount %d mapcount2 %d page_mapcount %d\n",
1946 			mapcount, mapcount2, page_mapcount(page));
1947 		BUG();
1948 	}
1949 }
1950 
1951 /*
1952  * Split a hugepage into normal pages. This doesn't change the position of head
1953  * page. If @list is null, tail pages will be added to LRU list, otherwise, to
1954  * @list. Both head page and tail pages will inherit mapping, flags, and so on
1955  * from the hugepage.
1956  * Return 0 if the hugepage is split successfully otherwise return 1.
1957  */
1958 int split_huge_page_to_list(struct page *page, struct list_head *list)
1959 {
1960 	struct anon_vma *anon_vma;
1961 	int ret = 1;
1962 
1963 	BUG_ON(is_huge_zero_page(page));
1964 	BUG_ON(!PageAnon(page));
1965 
1966 	/*
1967 	 * The caller does not necessarily hold an mmap_sem that would prevent
1968 	 * the anon_vma disappearing so we first we take a reference to it
1969 	 * and then lock the anon_vma for write. This is similar to
1970 	 * page_lock_anon_vma_read except the write lock is taken to serialise
1971 	 * against parallel split or collapse operations.
1972 	 */
1973 	anon_vma = page_get_anon_vma(page);
1974 	if (!anon_vma)
1975 		goto out;
1976 	anon_vma_lock_write(anon_vma);
1977 
1978 	ret = 0;
1979 	if (!PageCompound(page))
1980 		goto out_unlock;
1981 
1982 	BUG_ON(!PageSwapBacked(page));
1983 	__split_huge_page(page, anon_vma, list);
1984 	count_vm_event(THP_SPLIT);
1985 
1986 	BUG_ON(PageCompound(page));
1987 out_unlock:
1988 	anon_vma_unlock_write(anon_vma);
1989 	put_anon_vma(anon_vma);
1990 out:
1991 	return ret;
1992 }
1993 
1994 #define VM_NO_THP (VM_SPECIAL | VM_HUGETLB | VM_SHARED | VM_MAYSHARE)
1995 
1996 int hugepage_madvise(struct vm_area_struct *vma,
1997 		     unsigned long *vm_flags, int advice)
1998 {
1999 	switch (advice) {
2000 	case MADV_HUGEPAGE:
2001 #ifdef CONFIG_S390
2002 		/*
2003 		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
2004 		 * can't handle this properly after s390_enable_sie, so we simply
2005 		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
2006 		 */
2007 		if (mm_has_pgste(vma->vm_mm))
2008 			return 0;
2009 #endif
2010 		/*
2011 		 * Be somewhat over-protective like KSM for now!
2012 		 */
2013 		if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
2014 			return -EINVAL;
2015 		*vm_flags &= ~VM_NOHUGEPAGE;
2016 		*vm_flags |= VM_HUGEPAGE;
2017 		/*
2018 		 * If the vma become good for khugepaged to scan,
2019 		 * register it here without waiting a page fault that
2020 		 * may not happen any time soon.
2021 		 */
2022 		if (unlikely(khugepaged_enter_vma_merge(vma, *vm_flags)))
2023 			return -ENOMEM;
2024 		break;
2025 	case MADV_NOHUGEPAGE:
2026 		/*
2027 		 * Be somewhat over-protective like KSM for now!
2028 		 */
2029 		if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
2030 			return -EINVAL;
2031 		*vm_flags &= ~VM_HUGEPAGE;
2032 		*vm_flags |= VM_NOHUGEPAGE;
2033 		/*
2034 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
2035 		 * this vma even if we leave the mm registered in khugepaged if
2036 		 * it got registered before VM_NOHUGEPAGE was set.
2037 		 */
2038 		break;
2039 	}
2040 
2041 	return 0;
2042 }
2043 
2044 static int __init khugepaged_slab_init(void)
2045 {
2046 	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
2047 					  sizeof(struct mm_slot),
2048 					  __alignof__(struct mm_slot), 0, NULL);
2049 	if (!mm_slot_cache)
2050 		return -ENOMEM;
2051 
2052 	return 0;
2053 }
2054 
2055 static void __init khugepaged_slab_exit(void)
2056 {
2057 	kmem_cache_destroy(mm_slot_cache);
2058 }
2059 
2060 static inline struct mm_slot *alloc_mm_slot(void)
2061 {
2062 	if (!mm_slot_cache)	/* initialization failed */
2063 		return NULL;
2064 	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
2065 }
2066 
2067 static inline void free_mm_slot(struct mm_slot *mm_slot)
2068 {
2069 	kmem_cache_free(mm_slot_cache, mm_slot);
2070 }
2071 
2072 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
2073 {
2074 	struct mm_slot *mm_slot;
2075 
2076 	hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
2077 		if (mm == mm_slot->mm)
2078 			return mm_slot;
2079 
2080 	return NULL;
2081 }
2082 
2083 static void insert_to_mm_slots_hash(struct mm_struct *mm,
2084 				    struct mm_slot *mm_slot)
2085 {
2086 	mm_slot->mm = mm;
2087 	hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
2088 }
2089 
2090 static inline int khugepaged_test_exit(struct mm_struct *mm)
2091 {
2092 	return atomic_read(&mm->mm_users) == 0;
2093 }
2094 
2095 int __khugepaged_enter(struct mm_struct *mm)
2096 {
2097 	struct mm_slot *mm_slot;
2098 	int wakeup;
2099 
2100 	mm_slot = alloc_mm_slot();
2101 	if (!mm_slot)
2102 		return -ENOMEM;
2103 
2104 	/* __khugepaged_exit() must not run from under us */
2105 	VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
2106 	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
2107 		free_mm_slot(mm_slot);
2108 		return 0;
2109 	}
2110 
2111 	spin_lock(&khugepaged_mm_lock);
2112 	insert_to_mm_slots_hash(mm, mm_slot);
2113 	/*
2114 	 * Insert just behind the scanning cursor, to let the area settle
2115 	 * down a little.
2116 	 */
2117 	wakeup = list_empty(&khugepaged_scan.mm_head);
2118 	list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
2119 	spin_unlock(&khugepaged_mm_lock);
2120 
2121 	atomic_inc(&mm->mm_count);
2122 	if (wakeup)
2123 		wake_up_interruptible(&khugepaged_wait);
2124 
2125 	return 0;
2126 }
2127 
2128 int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
2129 			       unsigned long vm_flags)
2130 {
2131 	unsigned long hstart, hend;
2132 	if (!vma->anon_vma)
2133 		/*
2134 		 * Not yet faulted in so we will register later in the
2135 		 * page fault if needed.
2136 		 */
2137 		return 0;
2138 	if (vma->vm_ops)
2139 		/* khugepaged not yet working on file or special mappings */
2140 		return 0;
2141 	VM_BUG_ON_VMA(vm_flags & VM_NO_THP, vma);
2142 	hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2143 	hend = vma->vm_end & HPAGE_PMD_MASK;
2144 	if (hstart < hend)
2145 		return khugepaged_enter(vma, vm_flags);
2146 	return 0;
2147 }
2148 
2149 void __khugepaged_exit(struct mm_struct *mm)
2150 {
2151 	struct mm_slot *mm_slot;
2152 	int free = 0;
2153 
2154 	spin_lock(&khugepaged_mm_lock);
2155 	mm_slot = get_mm_slot(mm);
2156 	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
2157 		hash_del(&mm_slot->hash);
2158 		list_del(&mm_slot->mm_node);
2159 		free = 1;
2160 	}
2161 	spin_unlock(&khugepaged_mm_lock);
2162 
2163 	if (free) {
2164 		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2165 		free_mm_slot(mm_slot);
2166 		mmdrop(mm);
2167 	} else if (mm_slot) {
2168 		/*
2169 		 * This is required to serialize against
2170 		 * khugepaged_test_exit() (which is guaranteed to run
2171 		 * under mmap sem read mode). Stop here (after we
2172 		 * return all pagetables will be destroyed) until
2173 		 * khugepaged has finished working on the pagetables
2174 		 * under the mmap_sem.
2175 		 */
2176 		down_write(&mm->mmap_sem);
2177 		up_write(&mm->mmap_sem);
2178 	}
2179 }
2180 
2181 static void release_pte_page(struct page *page)
2182 {
2183 	/* 0 stands for page_is_file_cache(page) == false */
2184 	dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
2185 	unlock_page(page);
2186 	putback_lru_page(page);
2187 }
2188 
2189 static void release_pte_pages(pte_t *pte, pte_t *_pte)
2190 {
2191 	while (--_pte >= pte) {
2192 		pte_t pteval = *_pte;
2193 		if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
2194 			release_pte_page(pte_page(pteval));
2195 	}
2196 }
2197 
2198 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
2199 					unsigned long address,
2200 					pte_t *pte)
2201 {
2202 	struct page *page;
2203 	pte_t *_pte;
2204 	int none_or_zero = 0;
2205 	bool referenced = false, writable = false;
2206 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
2207 	     _pte++, address += PAGE_SIZE) {
2208 		pte_t pteval = *_pte;
2209 		if (pte_none(pteval) || (pte_present(pteval) &&
2210 				is_zero_pfn(pte_pfn(pteval)))) {
2211 			if (!userfaultfd_armed(vma) &&
2212 			    ++none_or_zero <= khugepaged_max_ptes_none)
2213 				continue;
2214 			else
2215 				goto out;
2216 		}
2217 		if (!pte_present(pteval))
2218 			goto out;
2219 		page = vm_normal_page(vma, address, pteval);
2220 		if (unlikely(!page))
2221 			goto out;
2222 
2223 		VM_BUG_ON_PAGE(PageCompound(page), page);
2224 		VM_BUG_ON_PAGE(!PageAnon(page), page);
2225 		VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
2226 
2227 		/*
2228 		 * We can do it before isolate_lru_page because the
2229 		 * page can't be freed from under us. NOTE: PG_lock
2230 		 * is needed to serialize against split_huge_page
2231 		 * when invoked from the VM.
2232 		 */
2233 		if (!trylock_page(page))
2234 			goto out;
2235 
2236 		/*
2237 		 * cannot use mapcount: can't collapse if there's a gup pin.
2238 		 * The page must only be referenced by the scanned process
2239 		 * and page swap cache.
2240 		 */
2241 		if (page_count(page) != 1 + !!PageSwapCache(page)) {
2242 			unlock_page(page);
2243 			goto out;
2244 		}
2245 		if (pte_write(pteval)) {
2246 			writable = true;
2247 		} else {
2248 			if (PageSwapCache(page) && !reuse_swap_page(page)) {
2249 				unlock_page(page);
2250 				goto out;
2251 			}
2252 			/*
2253 			 * Page is not in the swap cache. It can be collapsed
2254 			 * into a THP.
2255 			 */
2256 		}
2257 
2258 		/*
2259 		 * Isolate the page to avoid collapsing an hugepage
2260 		 * currently in use by the VM.
2261 		 */
2262 		if (isolate_lru_page(page)) {
2263 			unlock_page(page);
2264 			goto out;
2265 		}
2266 		/* 0 stands for page_is_file_cache(page) == false */
2267 		inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
2268 		VM_BUG_ON_PAGE(!PageLocked(page), page);
2269 		VM_BUG_ON_PAGE(PageLRU(page), page);
2270 
2271 		/* If there is no mapped pte young don't collapse the page */
2272 		if (pte_young(pteval) ||
2273 		    page_is_young(page) || PageReferenced(page) ||
2274 		    mmu_notifier_test_young(vma->vm_mm, address))
2275 			referenced = true;
2276 	}
2277 	if (likely(referenced && writable))
2278 		return 1;
2279 out:
2280 	release_pte_pages(pte, _pte);
2281 	return 0;
2282 }
2283 
2284 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
2285 				      struct vm_area_struct *vma,
2286 				      unsigned long address,
2287 				      spinlock_t *ptl)
2288 {
2289 	pte_t *_pte;
2290 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
2291 		pte_t pteval = *_pte;
2292 		struct page *src_page;
2293 
2294 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
2295 			clear_user_highpage(page, address);
2296 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
2297 			if (is_zero_pfn(pte_pfn(pteval))) {
2298 				/*
2299 				 * ptl mostly unnecessary.
2300 				 */
2301 				spin_lock(ptl);
2302 				/*
2303 				 * paravirt calls inside pte_clear here are
2304 				 * superfluous.
2305 				 */
2306 				pte_clear(vma->vm_mm, address, _pte);
2307 				spin_unlock(ptl);
2308 			}
2309 		} else {
2310 			src_page = pte_page(pteval);
2311 			copy_user_highpage(page, src_page, address, vma);
2312 			VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
2313 			release_pte_page(src_page);
2314 			/*
2315 			 * ptl mostly unnecessary, but preempt has to
2316 			 * be disabled to update the per-cpu stats
2317 			 * inside page_remove_rmap().
2318 			 */
2319 			spin_lock(ptl);
2320 			/*
2321 			 * paravirt calls inside pte_clear here are
2322 			 * superfluous.
2323 			 */
2324 			pte_clear(vma->vm_mm, address, _pte);
2325 			page_remove_rmap(src_page);
2326 			spin_unlock(ptl);
2327 			free_page_and_swap_cache(src_page);
2328 		}
2329 
2330 		address += PAGE_SIZE;
2331 		page++;
2332 	}
2333 }
2334 
2335 static void khugepaged_alloc_sleep(void)
2336 {
2337 	DEFINE_WAIT(wait);
2338 
2339 	add_wait_queue(&khugepaged_wait, &wait);
2340 	freezable_schedule_timeout_interruptible(
2341 		msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
2342 	remove_wait_queue(&khugepaged_wait, &wait);
2343 }
2344 
2345 static int khugepaged_node_load[MAX_NUMNODES];
2346 
2347 static bool khugepaged_scan_abort(int nid)
2348 {
2349 	int i;
2350 
2351 	/*
2352 	 * If zone_reclaim_mode is disabled, then no extra effort is made to
2353 	 * allocate memory locally.
2354 	 */
2355 	if (!zone_reclaim_mode)
2356 		return false;
2357 
2358 	/* If there is a count for this node already, it must be acceptable */
2359 	if (khugepaged_node_load[nid])
2360 		return false;
2361 
2362 	for (i = 0; i < MAX_NUMNODES; i++) {
2363 		if (!khugepaged_node_load[i])
2364 			continue;
2365 		if (node_distance(nid, i) > RECLAIM_DISTANCE)
2366 			return true;
2367 	}
2368 	return false;
2369 }
2370 
2371 #ifdef CONFIG_NUMA
2372 static int khugepaged_find_target_node(void)
2373 {
2374 	static int last_khugepaged_target_node = NUMA_NO_NODE;
2375 	int nid, target_node = 0, max_value = 0;
2376 
2377 	/* find first node with max normal pages hit */
2378 	for (nid = 0; nid < MAX_NUMNODES; nid++)
2379 		if (khugepaged_node_load[nid] > max_value) {
2380 			max_value = khugepaged_node_load[nid];
2381 			target_node = nid;
2382 		}
2383 
2384 	/* do some balance if several nodes have the same hit record */
2385 	if (target_node <= last_khugepaged_target_node)
2386 		for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
2387 				nid++)
2388 			if (max_value == khugepaged_node_load[nid]) {
2389 				target_node = nid;
2390 				break;
2391 			}
2392 
2393 	last_khugepaged_target_node = target_node;
2394 	return target_node;
2395 }
2396 
2397 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2398 {
2399 	if (IS_ERR(*hpage)) {
2400 		if (!*wait)
2401 			return false;
2402 
2403 		*wait = false;
2404 		*hpage = NULL;
2405 		khugepaged_alloc_sleep();
2406 	} else if (*hpage) {
2407 		put_page(*hpage);
2408 		*hpage = NULL;
2409 	}
2410 
2411 	return true;
2412 }
2413 
2414 static struct page *
2415 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
2416 		       struct vm_area_struct *vma, unsigned long address,
2417 		       int node)
2418 {
2419 	VM_BUG_ON_PAGE(*hpage, *hpage);
2420 
2421 	/*
2422 	 * Before allocating the hugepage, release the mmap_sem read lock.
2423 	 * The allocation can take potentially a long time if it involves
2424 	 * sync compaction, and we do not need to hold the mmap_sem during
2425 	 * that. We will recheck the vma after taking it again in write mode.
2426 	 */
2427 	up_read(&mm->mmap_sem);
2428 
2429 	*hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
2430 	if (unlikely(!*hpage)) {
2431 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2432 		*hpage = ERR_PTR(-ENOMEM);
2433 		return NULL;
2434 	}
2435 
2436 	count_vm_event(THP_COLLAPSE_ALLOC);
2437 	return *hpage;
2438 }
2439 #else
2440 static int khugepaged_find_target_node(void)
2441 {
2442 	return 0;
2443 }
2444 
2445 static inline struct page *alloc_hugepage(int defrag)
2446 {
2447 	return alloc_pages(alloc_hugepage_gfpmask(defrag, 0),
2448 			   HPAGE_PMD_ORDER);
2449 }
2450 
2451 static struct page *khugepaged_alloc_hugepage(bool *wait)
2452 {
2453 	struct page *hpage;
2454 
2455 	do {
2456 		hpage = alloc_hugepage(khugepaged_defrag());
2457 		if (!hpage) {
2458 			count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2459 			if (!*wait)
2460 				return NULL;
2461 
2462 			*wait = false;
2463 			khugepaged_alloc_sleep();
2464 		} else
2465 			count_vm_event(THP_COLLAPSE_ALLOC);
2466 	} while (unlikely(!hpage) && likely(khugepaged_enabled()));
2467 
2468 	return hpage;
2469 }
2470 
2471 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2472 {
2473 	if (!*hpage)
2474 		*hpage = khugepaged_alloc_hugepage(wait);
2475 
2476 	if (unlikely(!*hpage))
2477 		return false;
2478 
2479 	return true;
2480 }
2481 
2482 static struct page *
2483 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
2484 		       struct vm_area_struct *vma, unsigned long address,
2485 		       int node)
2486 {
2487 	up_read(&mm->mmap_sem);
2488 	VM_BUG_ON(!*hpage);
2489 
2490 	return  *hpage;
2491 }
2492 #endif
2493 
2494 static bool hugepage_vma_check(struct vm_area_struct *vma)
2495 {
2496 	if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
2497 	    (vma->vm_flags & VM_NOHUGEPAGE))
2498 		return false;
2499 
2500 	if (!vma->anon_vma || vma->vm_ops)
2501 		return false;
2502 	if (is_vma_temporary_stack(vma))
2503 		return false;
2504 	VM_BUG_ON_VMA(vma->vm_flags & VM_NO_THP, vma);
2505 	return true;
2506 }
2507 
2508 static void collapse_huge_page(struct mm_struct *mm,
2509 				   unsigned long address,
2510 				   struct page **hpage,
2511 				   struct vm_area_struct *vma,
2512 				   int node)
2513 {
2514 	pmd_t *pmd, _pmd;
2515 	pte_t *pte;
2516 	pgtable_t pgtable;
2517 	struct page *new_page;
2518 	spinlock_t *pmd_ptl, *pte_ptl;
2519 	int isolated;
2520 	unsigned long hstart, hend;
2521 	struct mem_cgroup *memcg;
2522 	unsigned long mmun_start;	/* For mmu_notifiers */
2523 	unsigned long mmun_end;		/* For mmu_notifiers */
2524 	gfp_t gfp;
2525 
2526 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2527 
2528 	/* Only allocate from the target node */
2529 	gfp = alloc_hugepage_gfpmask(khugepaged_defrag(), __GFP_OTHER_NODE) |
2530 		__GFP_THISNODE;
2531 
2532 	/* release the mmap_sem read lock. */
2533 	new_page = khugepaged_alloc_page(hpage, gfp, mm, vma, address, node);
2534 	if (!new_page)
2535 		return;
2536 
2537 	if (unlikely(mem_cgroup_try_charge(new_page, mm,
2538 					   gfp, &memcg)))
2539 		return;
2540 
2541 	/*
2542 	 * Prevent all access to pagetables with the exception of
2543 	 * gup_fast later hanlded by the ptep_clear_flush and the VM
2544 	 * handled by the anon_vma lock + PG_lock.
2545 	 */
2546 	down_write(&mm->mmap_sem);
2547 	if (unlikely(khugepaged_test_exit(mm)))
2548 		goto out;
2549 
2550 	vma = find_vma(mm, address);
2551 	if (!vma)
2552 		goto out;
2553 	hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2554 	hend = vma->vm_end & HPAGE_PMD_MASK;
2555 	if (address < hstart || address + HPAGE_PMD_SIZE > hend)
2556 		goto out;
2557 	if (!hugepage_vma_check(vma))
2558 		goto out;
2559 	pmd = mm_find_pmd(mm, address);
2560 	if (!pmd)
2561 		goto out;
2562 
2563 	anon_vma_lock_write(vma->anon_vma);
2564 
2565 	pte = pte_offset_map(pmd, address);
2566 	pte_ptl = pte_lockptr(mm, pmd);
2567 
2568 	mmun_start = address;
2569 	mmun_end   = address + HPAGE_PMD_SIZE;
2570 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2571 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
2572 	/*
2573 	 * After this gup_fast can't run anymore. This also removes
2574 	 * any huge TLB entry from the CPU so we won't allow
2575 	 * huge and small TLB entries for the same virtual address
2576 	 * to avoid the risk of CPU bugs in that area.
2577 	 */
2578 	_pmd = pmdp_collapse_flush(vma, address, pmd);
2579 	spin_unlock(pmd_ptl);
2580 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2581 
2582 	spin_lock(pte_ptl);
2583 	isolated = __collapse_huge_page_isolate(vma, address, pte);
2584 	spin_unlock(pte_ptl);
2585 
2586 	if (unlikely(!isolated)) {
2587 		pte_unmap(pte);
2588 		spin_lock(pmd_ptl);
2589 		BUG_ON(!pmd_none(*pmd));
2590 		/*
2591 		 * We can only use set_pmd_at when establishing
2592 		 * hugepmds and never for establishing regular pmds that
2593 		 * points to regular pagetables. Use pmd_populate for that
2594 		 */
2595 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
2596 		spin_unlock(pmd_ptl);
2597 		anon_vma_unlock_write(vma->anon_vma);
2598 		goto out;
2599 	}
2600 
2601 	/*
2602 	 * All pages are isolated and locked so anon_vma rmap
2603 	 * can't run anymore.
2604 	 */
2605 	anon_vma_unlock_write(vma->anon_vma);
2606 
2607 	__collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
2608 	pte_unmap(pte);
2609 	__SetPageUptodate(new_page);
2610 	pgtable = pmd_pgtable(_pmd);
2611 
2612 	_pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
2613 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
2614 
2615 	/*
2616 	 * spin_lock() below is not the equivalent of smp_wmb(), so
2617 	 * this is needed to avoid the copy_huge_page writes to become
2618 	 * visible after the set_pmd_at() write.
2619 	 */
2620 	smp_wmb();
2621 
2622 	spin_lock(pmd_ptl);
2623 	BUG_ON(!pmd_none(*pmd));
2624 	page_add_new_anon_rmap(new_page, vma, address);
2625 	mem_cgroup_commit_charge(new_page, memcg, false);
2626 	lru_cache_add_active_or_unevictable(new_page, vma);
2627 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
2628 	set_pmd_at(mm, address, pmd, _pmd);
2629 	update_mmu_cache_pmd(vma, address, pmd);
2630 	spin_unlock(pmd_ptl);
2631 
2632 	*hpage = NULL;
2633 
2634 	khugepaged_pages_collapsed++;
2635 out_up_write:
2636 	up_write(&mm->mmap_sem);
2637 	return;
2638 
2639 out:
2640 	mem_cgroup_cancel_charge(new_page, memcg);
2641 	goto out_up_write;
2642 }
2643 
2644 static int khugepaged_scan_pmd(struct mm_struct *mm,
2645 			       struct vm_area_struct *vma,
2646 			       unsigned long address,
2647 			       struct page **hpage)
2648 {
2649 	pmd_t *pmd;
2650 	pte_t *pte, *_pte;
2651 	int ret = 0, none_or_zero = 0;
2652 	struct page *page;
2653 	unsigned long _address;
2654 	spinlock_t *ptl;
2655 	int node = NUMA_NO_NODE;
2656 	bool writable = false, referenced = false;
2657 
2658 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2659 
2660 	pmd = mm_find_pmd(mm, address);
2661 	if (!pmd)
2662 		goto out;
2663 
2664 	memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
2665 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2666 	for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2667 	     _pte++, _address += PAGE_SIZE) {
2668 		pte_t pteval = *_pte;
2669 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
2670 			if (!userfaultfd_armed(vma) &&
2671 			    ++none_or_zero <= khugepaged_max_ptes_none)
2672 				continue;
2673 			else
2674 				goto out_unmap;
2675 		}
2676 		if (!pte_present(pteval))
2677 			goto out_unmap;
2678 		if (pte_write(pteval))
2679 			writable = true;
2680 
2681 		page = vm_normal_page(vma, _address, pteval);
2682 		if (unlikely(!page))
2683 			goto out_unmap;
2684 		/*
2685 		 * Record which node the original page is from and save this
2686 		 * information to khugepaged_node_load[].
2687 		 * Khupaged will allocate hugepage from the node has the max
2688 		 * hit record.
2689 		 */
2690 		node = page_to_nid(page);
2691 		if (khugepaged_scan_abort(node))
2692 			goto out_unmap;
2693 		khugepaged_node_load[node]++;
2694 		VM_BUG_ON_PAGE(PageCompound(page), page);
2695 		if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2696 			goto out_unmap;
2697 		/*
2698 		 * cannot use mapcount: can't collapse if there's a gup pin.
2699 		 * The page must only be referenced by the scanned process
2700 		 * and page swap cache.
2701 		 */
2702 		if (page_count(page) != 1 + !!PageSwapCache(page))
2703 			goto out_unmap;
2704 		if (pte_young(pteval) ||
2705 		    page_is_young(page) || PageReferenced(page) ||
2706 		    mmu_notifier_test_young(vma->vm_mm, address))
2707 			referenced = true;
2708 	}
2709 	if (referenced && writable)
2710 		ret = 1;
2711 out_unmap:
2712 	pte_unmap_unlock(pte, ptl);
2713 	if (ret) {
2714 		node = khugepaged_find_target_node();
2715 		/* collapse_huge_page will return with the mmap_sem released */
2716 		collapse_huge_page(mm, address, hpage, vma, node);
2717 	}
2718 out:
2719 	return ret;
2720 }
2721 
2722 static void collect_mm_slot(struct mm_slot *mm_slot)
2723 {
2724 	struct mm_struct *mm = mm_slot->mm;
2725 
2726 	VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2727 
2728 	if (khugepaged_test_exit(mm)) {
2729 		/* free mm_slot */
2730 		hash_del(&mm_slot->hash);
2731 		list_del(&mm_slot->mm_node);
2732 
2733 		/*
2734 		 * Not strictly needed because the mm exited already.
2735 		 *
2736 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2737 		 */
2738 
2739 		/* khugepaged_mm_lock actually not necessary for the below */
2740 		free_mm_slot(mm_slot);
2741 		mmdrop(mm);
2742 	}
2743 }
2744 
2745 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2746 					    struct page **hpage)
2747 	__releases(&khugepaged_mm_lock)
2748 	__acquires(&khugepaged_mm_lock)
2749 {
2750 	struct mm_slot *mm_slot;
2751 	struct mm_struct *mm;
2752 	struct vm_area_struct *vma;
2753 	int progress = 0;
2754 
2755 	VM_BUG_ON(!pages);
2756 	VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2757 
2758 	if (khugepaged_scan.mm_slot)
2759 		mm_slot = khugepaged_scan.mm_slot;
2760 	else {
2761 		mm_slot = list_entry(khugepaged_scan.mm_head.next,
2762 				     struct mm_slot, mm_node);
2763 		khugepaged_scan.address = 0;
2764 		khugepaged_scan.mm_slot = mm_slot;
2765 	}
2766 	spin_unlock(&khugepaged_mm_lock);
2767 
2768 	mm = mm_slot->mm;
2769 	down_read(&mm->mmap_sem);
2770 	if (unlikely(khugepaged_test_exit(mm)))
2771 		vma = NULL;
2772 	else
2773 		vma = find_vma(mm, khugepaged_scan.address);
2774 
2775 	progress++;
2776 	for (; vma; vma = vma->vm_next) {
2777 		unsigned long hstart, hend;
2778 
2779 		cond_resched();
2780 		if (unlikely(khugepaged_test_exit(mm))) {
2781 			progress++;
2782 			break;
2783 		}
2784 		if (!hugepage_vma_check(vma)) {
2785 skip:
2786 			progress++;
2787 			continue;
2788 		}
2789 		hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2790 		hend = vma->vm_end & HPAGE_PMD_MASK;
2791 		if (hstart >= hend)
2792 			goto skip;
2793 		if (khugepaged_scan.address > hend)
2794 			goto skip;
2795 		if (khugepaged_scan.address < hstart)
2796 			khugepaged_scan.address = hstart;
2797 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2798 
2799 		while (khugepaged_scan.address < hend) {
2800 			int ret;
2801 			cond_resched();
2802 			if (unlikely(khugepaged_test_exit(mm)))
2803 				goto breakouterloop;
2804 
2805 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2806 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2807 				  hend);
2808 			ret = khugepaged_scan_pmd(mm, vma,
2809 						  khugepaged_scan.address,
2810 						  hpage);
2811 			/* move to next address */
2812 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2813 			progress += HPAGE_PMD_NR;
2814 			if (ret)
2815 				/* we released mmap_sem so break loop */
2816 				goto breakouterloop_mmap_sem;
2817 			if (progress >= pages)
2818 				goto breakouterloop;
2819 		}
2820 	}
2821 breakouterloop:
2822 	up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2823 breakouterloop_mmap_sem:
2824 
2825 	spin_lock(&khugepaged_mm_lock);
2826 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2827 	/*
2828 	 * Release the current mm_slot if this mm is about to die, or
2829 	 * if we scanned all vmas of this mm.
2830 	 */
2831 	if (khugepaged_test_exit(mm) || !vma) {
2832 		/*
2833 		 * Make sure that if mm_users is reaching zero while
2834 		 * khugepaged runs here, khugepaged_exit will find
2835 		 * mm_slot not pointing to the exiting mm.
2836 		 */
2837 		if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2838 			khugepaged_scan.mm_slot = list_entry(
2839 				mm_slot->mm_node.next,
2840 				struct mm_slot, mm_node);
2841 			khugepaged_scan.address = 0;
2842 		} else {
2843 			khugepaged_scan.mm_slot = NULL;
2844 			khugepaged_full_scans++;
2845 		}
2846 
2847 		collect_mm_slot(mm_slot);
2848 	}
2849 
2850 	return progress;
2851 }
2852 
2853 static int khugepaged_has_work(void)
2854 {
2855 	return !list_empty(&khugepaged_scan.mm_head) &&
2856 		khugepaged_enabled();
2857 }
2858 
2859 static int khugepaged_wait_event(void)
2860 {
2861 	return !list_empty(&khugepaged_scan.mm_head) ||
2862 		kthread_should_stop();
2863 }
2864 
2865 static void khugepaged_do_scan(void)
2866 {
2867 	struct page *hpage = NULL;
2868 	unsigned int progress = 0, pass_through_head = 0;
2869 	unsigned int pages = khugepaged_pages_to_scan;
2870 	bool wait = true;
2871 
2872 	barrier(); /* write khugepaged_pages_to_scan to local stack */
2873 
2874 	while (progress < pages) {
2875 		if (!khugepaged_prealloc_page(&hpage, &wait))
2876 			break;
2877 
2878 		cond_resched();
2879 
2880 		if (unlikely(kthread_should_stop() || try_to_freeze()))
2881 			break;
2882 
2883 		spin_lock(&khugepaged_mm_lock);
2884 		if (!khugepaged_scan.mm_slot)
2885 			pass_through_head++;
2886 		if (khugepaged_has_work() &&
2887 		    pass_through_head < 2)
2888 			progress += khugepaged_scan_mm_slot(pages - progress,
2889 							    &hpage);
2890 		else
2891 			progress = pages;
2892 		spin_unlock(&khugepaged_mm_lock);
2893 	}
2894 
2895 	if (!IS_ERR_OR_NULL(hpage))
2896 		put_page(hpage);
2897 }
2898 
2899 static void khugepaged_wait_work(void)
2900 {
2901 	if (khugepaged_has_work()) {
2902 		if (!khugepaged_scan_sleep_millisecs)
2903 			return;
2904 
2905 		wait_event_freezable_timeout(khugepaged_wait,
2906 					     kthread_should_stop(),
2907 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2908 		return;
2909 	}
2910 
2911 	if (khugepaged_enabled())
2912 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2913 }
2914 
2915 static int khugepaged(void *none)
2916 {
2917 	struct mm_slot *mm_slot;
2918 
2919 	set_freezable();
2920 	set_user_nice(current, MAX_NICE);
2921 
2922 	while (!kthread_should_stop()) {
2923 		khugepaged_do_scan();
2924 		khugepaged_wait_work();
2925 	}
2926 
2927 	spin_lock(&khugepaged_mm_lock);
2928 	mm_slot = khugepaged_scan.mm_slot;
2929 	khugepaged_scan.mm_slot = NULL;
2930 	if (mm_slot)
2931 		collect_mm_slot(mm_slot);
2932 	spin_unlock(&khugepaged_mm_lock);
2933 	return 0;
2934 }
2935 
2936 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2937 		unsigned long haddr, pmd_t *pmd)
2938 {
2939 	struct mm_struct *mm = vma->vm_mm;
2940 	pgtable_t pgtable;
2941 	pmd_t _pmd;
2942 	int i;
2943 
2944 	pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2945 	/* leave pmd empty until pte is filled */
2946 
2947 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2948 	pmd_populate(mm, &_pmd, pgtable);
2949 
2950 	for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
2951 		pte_t *pte, entry;
2952 		entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
2953 		entry = pte_mkspecial(entry);
2954 		pte = pte_offset_map(&_pmd, haddr);
2955 		VM_BUG_ON(!pte_none(*pte));
2956 		set_pte_at(mm, haddr, pte, entry);
2957 		pte_unmap(pte);
2958 	}
2959 	smp_wmb(); /* make pte visible before pmd */
2960 	pmd_populate(mm, pmd, pgtable);
2961 	put_huge_zero_page();
2962 }
2963 
2964 void __split_huge_page_pmd(struct vm_area_struct *vma, unsigned long address,
2965 		pmd_t *pmd)
2966 {
2967 	spinlock_t *ptl;
2968 	struct page *page = NULL;
2969 	struct mm_struct *mm = vma->vm_mm;
2970 	unsigned long haddr = address & HPAGE_PMD_MASK;
2971 	unsigned long mmun_start;	/* For mmu_notifiers */
2972 	unsigned long mmun_end;		/* For mmu_notifiers */
2973 
2974 	BUG_ON(vma->vm_start > haddr || vma->vm_end < haddr + HPAGE_PMD_SIZE);
2975 
2976 	mmun_start = haddr;
2977 	mmun_end   = haddr + HPAGE_PMD_SIZE;
2978 again:
2979 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2980 	ptl = pmd_lock(mm, pmd);
2981 	if (unlikely(!pmd_trans_huge(*pmd)))
2982 		goto unlock;
2983 	if (vma_is_dax(vma)) {
2984 		pmd_t _pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2985 		if (is_huge_zero_pmd(_pmd))
2986 			put_huge_zero_page();
2987 	} else if (is_huge_zero_pmd(*pmd)) {
2988 		__split_huge_zero_page_pmd(vma, haddr, pmd);
2989 	} else {
2990 		page = pmd_page(*pmd);
2991 		VM_BUG_ON_PAGE(!page_count(page), page);
2992 		get_page(page);
2993 	}
2994  unlock:
2995 	spin_unlock(ptl);
2996 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2997 
2998 	if (!page)
2999 		return;
3000 
3001 	split_huge_page(page);
3002 	put_page(page);
3003 
3004 	/*
3005 	 * We don't always have down_write of mmap_sem here: a racing
3006 	 * do_huge_pmd_wp_page() might have copied-on-write to another
3007 	 * huge page before our split_huge_page() got the anon_vma lock.
3008 	 */
3009 	if (unlikely(pmd_trans_huge(*pmd)))
3010 		goto again;
3011 }
3012 
3013 void split_huge_page_pmd_mm(struct mm_struct *mm, unsigned long address,
3014 		pmd_t *pmd)
3015 {
3016 	struct vm_area_struct *vma;
3017 
3018 	vma = find_vma(mm, address);
3019 	BUG_ON(vma == NULL);
3020 	split_huge_page_pmd(vma, address, pmd);
3021 }
3022 
3023 static void split_huge_page_address(struct mm_struct *mm,
3024 				    unsigned long address)
3025 {
3026 	pgd_t *pgd;
3027 	pud_t *pud;
3028 	pmd_t *pmd;
3029 
3030 	VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
3031 
3032 	pgd = pgd_offset(mm, address);
3033 	if (!pgd_present(*pgd))
3034 		return;
3035 
3036 	pud = pud_offset(pgd, address);
3037 	if (!pud_present(*pud))
3038 		return;
3039 
3040 	pmd = pmd_offset(pud, address);
3041 	if (!pmd_present(*pmd))
3042 		return;
3043 	/*
3044 	 * Caller holds the mmap_sem write mode, so a huge pmd cannot
3045 	 * materialize from under us.
3046 	 */
3047 	split_huge_page_pmd_mm(mm, address, pmd);
3048 }
3049 
3050 void vma_adjust_trans_huge(struct vm_area_struct *vma,
3051 			     unsigned long start,
3052 			     unsigned long end,
3053 			     long adjust_next)
3054 {
3055 	/*
3056 	 * If the new start address isn't hpage aligned and it could
3057 	 * previously contain an hugepage: check if we need to split
3058 	 * an huge pmd.
3059 	 */
3060 	if (start & ~HPAGE_PMD_MASK &&
3061 	    (start & HPAGE_PMD_MASK) >= vma->vm_start &&
3062 	    (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
3063 		split_huge_page_address(vma->vm_mm, start);
3064 
3065 	/*
3066 	 * If the new end address isn't hpage aligned and it could
3067 	 * previously contain an hugepage: check if we need to split
3068 	 * an huge pmd.
3069 	 */
3070 	if (end & ~HPAGE_PMD_MASK &&
3071 	    (end & HPAGE_PMD_MASK) >= vma->vm_start &&
3072 	    (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
3073 		split_huge_page_address(vma->vm_mm, end);
3074 
3075 	/*
3076 	 * If we're also updating the vma->vm_next->vm_start, if the new
3077 	 * vm_next->vm_start isn't page aligned and it could previously
3078 	 * contain an hugepage: check if we need to split an huge pmd.
3079 	 */
3080 	if (adjust_next > 0) {
3081 		struct vm_area_struct *next = vma->vm_next;
3082 		unsigned long nstart = next->vm_start;
3083 		nstart += adjust_next << PAGE_SHIFT;
3084 		if (nstart & ~HPAGE_PMD_MASK &&
3085 		    (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
3086 		    (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
3087 			split_huge_page_address(next->vm_mm, nstart);
3088 	}
3089 }
3090