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