2 * Copyright (C) 2009 Red Hat, Inc.
4 * This work is licensed under the terms of the GNU GPL, version 2. See
5 * the COPYING file in the top-level directory.
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/mm_inline.h>
16 #include <linux/kthread.h>
17 #include <linux/khugepaged.h>
18 #include <linux/freezer.h>
19 #include <linux/mman.h>
20 #include <linux/pagemap.h>
22 #include <asm/pgalloc.h>
26 * By default transparent hugepage support is enabled for all mappings
27 * and khugepaged scans all mappings. Defrag is only invoked by
28 * khugepaged hugepage allocations and by page faults inside
29 * MADV_HUGEPAGE regions to avoid the risk of slowing down short lived
32 unsigned long transparent_hugepage_flags __read_mostly =
33 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
34 (1<<TRANSPARENT_HUGEPAGE_FLAG)|
36 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
37 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
39 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_FLAG)|
40 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
42 /* default scan 8*512 pte (or vmas) every 30 second */
43 static unsigned int khugepaged_pages_to_scan __read_mostly = HPAGE_PMD_NR*8;
44 static unsigned int khugepaged_pages_collapsed;
45 static unsigned int khugepaged_full_scans;
46 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
47 /* during fragmentation poll the hugepage allocator once every minute */
48 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
49 static struct task_struct *khugepaged_thread __read_mostly;
50 static DEFINE_MUTEX(khugepaged_mutex);
51 static DEFINE_SPINLOCK(khugepaged_mm_lock);
52 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
54 * default collapse hugepages if there is at least one pte mapped like
55 * it would have happened if the vma was large enough during page
58 static unsigned int khugepaged_max_ptes_none __read_mostly = HPAGE_PMD_NR-1;
60 static int khugepaged(void *none);
61 static int mm_slots_hash_init(void);
62 static int khugepaged_slab_init(void);
63 static void khugepaged_slab_free(void);
65 #define MM_SLOTS_HASH_HEADS 1024
66 static struct hlist_head *mm_slots_hash __read_mostly;
67 static struct kmem_cache *mm_slot_cache __read_mostly;
70 * struct mm_slot - hash lookup from mm to mm_slot
71 * @hash: hash collision list
72 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
73 * @mm: the mm that this information is valid for
76 struct hlist_node hash;
77 struct list_head mm_node;
82 * struct khugepaged_scan - cursor for scanning
83 * @mm_head: the head of the mm list to scan
84 * @mm_slot: the current mm_slot we are scanning
85 * @address: the next address inside that to be scanned
87 * There is only the one khugepaged_scan instance of this cursor structure.
89 struct khugepaged_scan {
90 struct list_head mm_head;
91 struct mm_slot *mm_slot;
92 unsigned long address;
94 static struct khugepaged_scan khugepaged_scan = {
95 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
99 static int set_recommended_min_free_kbytes(void)
103 unsigned long recommended_min;
104 extern int min_free_kbytes;
106 if (!khugepaged_enabled())
109 for_each_populated_zone(zone)
112 /* Make sure at least 2 hugepages are free for MIGRATE_RESERVE */
113 recommended_min = pageblock_nr_pages * nr_zones * 2;
116 * Make sure that on average at least two pageblocks are almost free
117 * of another type, one for a migratetype to fall back to and a
118 * second to avoid subsequent fallbacks of other types There are 3
119 * MIGRATE_TYPES we care about.
121 recommended_min += pageblock_nr_pages * nr_zones *
122 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
124 /* don't ever allow to reserve more than 5% of the lowmem */
125 recommended_min = min(recommended_min,
126 (unsigned long) nr_free_buffer_pages() / 20);
127 recommended_min <<= (PAGE_SHIFT-10);
129 if (recommended_min > min_free_kbytes)
130 min_free_kbytes = recommended_min;
131 setup_per_zone_wmarks();
134 late_initcall(set_recommended_min_free_kbytes);
136 static int start_khugepaged(void)
139 if (khugepaged_enabled()) {
140 if (!khugepaged_thread)
141 khugepaged_thread = kthread_run(khugepaged, NULL,
143 if (unlikely(IS_ERR(khugepaged_thread))) {
145 "khugepaged: kthread_run(khugepaged) failed\n");
146 err = PTR_ERR(khugepaged_thread);
147 khugepaged_thread = NULL;
150 if (!list_empty(&khugepaged_scan.mm_head))
151 wake_up_interruptible(&khugepaged_wait);
153 set_recommended_min_free_kbytes();
154 } else if (khugepaged_thread) {
155 kthread_stop(khugepaged_thread);
156 khugepaged_thread = NULL;
164 static ssize_t double_flag_show(struct kobject *kobj,
165 struct kobj_attribute *attr, char *buf,
166 enum transparent_hugepage_flag enabled,
167 enum transparent_hugepage_flag req_madv)
169 if (test_bit(enabled, &transparent_hugepage_flags)) {
170 VM_BUG_ON(test_bit(req_madv, &transparent_hugepage_flags));
171 return sprintf(buf, "[always] madvise never\n");
172 } else if (test_bit(req_madv, &transparent_hugepage_flags))
173 return sprintf(buf, "always [madvise] never\n");
175 return sprintf(buf, "always madvise [never]\n");
177 static ssize_t double_flag_store(struct kobject *kobj,
178 struct kobj_attribute *attr,
179 const char *buf, size_t count,
180 enum transparent_hugepage_flag enabled,
181 enum transparent_hugepage_flag req_madv)
183 if (!memcmp("always", buf,
184 min(sizeof("always")-1, count))) {
185 set_bit(enabled, &transparent_hugepage_flags);
186 clear_bit(req_madv, &transparent_hugepage_flags);
187 } else if (!memcmp("madvise", buf,
188 min(sizeof("madvise")-1, count))) {
189 clear_bit(enabled, &transparent_hugepage_flags);
190 set_bit(req_madv, &transparent_hugepage_flags);
191 } else if (!memcmp("never", buf,
192 min(sizeof("never")-1, count))) {
193 clear_bit(enabled, &transparent_hugepage_flags);
194 clear_bit(req_madv, &transparent_hugepage_flags);
201 static ssize_t enabled_show(struct kobject *kobj,
202 struct kobj_attribute *attr, char *buf)
204 return double_flag_show(kobj, attr, buf,
205 TRANSPARENT_HUGEPAGE_FLAG,
206 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
208 static ssize_t enabled_store(struct kobject *kobj,
209 struct kobj_attribute *attr,
210 const char *buf, size_t count)
214 ret = double_flag_store(kobj, attr, buf, count,
215 TRANSPARENT_HUGEPAGE_FLAG,
216 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
221 mutex_lock(&khugepaged_mutex);
222 err = start_khugepaged();
223 mutex_unlock(&khugepaged_mutex);
231 static struct kobj_attribute enabled_attr =
232 __ATTR(enabled, 0644, enabled_show, enabled_store);
234 static ssize_t single_flag_show(struct kobject *kobj,
235 struct kobj_attribute *attr, char *buf,
236 enum transparent_hugepage_flag flag)
238 return sprintf(buf, "%d\n",
239 !!test_bit(flag, &transparent_hugepage_flags));
242 static ssize_t single_flag_store(struct kobject *kobj,
243 struct kobj_attribute *attr,
244 const char *buf, size_t count,
245 enum transparent_hugepage_flag flag)
250 ret = kstrtoul(buf, 10, &value);
257 set_bit(flag, &transparent_hugepage_flags);
259 clear_bit(flag, &transparent_hugepage_flags);
265 * Currently defrag only disables __GFP_NOWAIT for allocation. A blind
266 * __GFP_REPEAT is too aggressive, it's never worth swapping tons of
267 * memory just to allocate one more hugepage.
269 static ssize_t defrag_show(struct kobject *kobj,
270 struct kobj_attribute *attr, char *buf)
272 return double_flag_show(kobj, attr, buf,
273 TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
274 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
276 static ssize_t defrag_store(struct kobject *kobj,
277 struct kobj_attribute *attr,
278 const char *buf, size_t count)
280 return double_flag_store(kobj, attr, buf, count,
281 TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
282 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
284 static struct kobj_attribute defrag_attr =
285 __ATTR(defrag, 0644, defrag_show, defrag_store);
287 #ifdef CONFIG_DEBUG_VM
288 static ssize_t debug_cow_show(struct kobject *kobj,
289 struct kobj_attribute *attr, char *buf)
291 return single_flag_show(kobj, attr, buf,
292 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
294 static ssize_t debug_cow_store(struct kobject *kobj,
295 struct kobj_attribute *attr,
296 const char *buf, size_t count)
298 return single_flag_store(kobj, attr, buf, count,
299 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
301 static struct kobj_attribute debug_cow_attr =
302 __ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
303 #endif /* CONFIG_DEBUG_VM */
305 static struct attribute *hugepage_attr[] = {
308 #ifdef CONFIG_DEBUG_VM
309 &debug_cow_attr.attr,
314 static struct attribute_group hugepage_attr_group = {
315 .attrs = hugepage_attr,
318 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
319 struct kobj_attribute *attr,
322 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
325 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
326 struct kobj_attribute *attr,
327 const char *buf, size_t count)
332 err = strict_strtoul(buf, 10, &msecs);
333 if (err || msecs > UINT_MAX)
336 khugepaged_scan_sleep_millisecs = msecs;
337 wake_up_interruptible(&khugepaged_wait);
341 static struct kobj_attribute scan_sleep_millisecs_attr =
342 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
343 scan_sleep_millisecs_store);
345 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
346 struct kobj_attribute *attr,
349 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
352 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
353 struct kobj_attribute *attr,
354 const char *buf, size_t count)
359 err = strict_strtoul(buf, 10, &msecs);
360 if (err || msecs > UINT_MAX)
363 khugepaged_alloc_sleep_millisecs = msecs;
364 wake_up_interruptible(&khugepaged_wait);
368 static struct kobj_attribute alloc_sleep_millisecs_attr =
369 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
370 alloc_sleep_millisecs_store);
372 static ssize_t pages_to_scan_show(struct kobject *kobj,
373 struct kobj_attribute *attr,
376 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
378 static ssize_t pages_to_scan_store(struct kobject *kobj,
379 struct kobj_attribute *attr,
380 const char *buf, size_t count)
385 err = strict_strtoul(buf, 10, &pages);
386 if (err || !pages || pages > UINT_MAX)
389 khugepaged_pages_to_scan = pages;
393 static struct kobj_attribute pages_to_scan_attr =
394 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
395 pages_to_scan_store);
397 static ssize_t pages_collapsed_show(struct kobject *kobj,
398 struct kobj_attribute *attr,
401 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
403 static struct kobj_attribute pages_collapsed_attr =
404 __ATTR_RO(pages_collapsed);
406 static ssize_t full_scans_show(struct kobject *kobj,
407 struct kobj_attribute *attr,
410 return sprintf(buf, "%u\n", khugepaged_full_scans);
412 static struct kobj_attribute full_scans_attr =
413 __ATTR_RO(full_scans);
415 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
416 struct kobj_attribute *attr, char *buf)
418 return single_flag_show(kobj, attr, buf,
419 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
421 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
422 struct kobj_attribute *attr,
423 const char *buf, size_t count)
425 return single_flag_store(kobj, attr, buf, count,
426 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
428 static struct kobj_attribute khugepaged_defrag_attr =
429 __ATTR(defrag, 0644, khugepaged_defrag_show,
430 khugepaged_defrag_store);
433 * max_ptes_none controls if khugepaged should collapse hugepages over
434 * any unmapped ptes in turn potentially increasing the memory
435 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
436 * reduce the available free memory in the system as it
437 * runs. Increasing max_ptes_none will instead potentially reduce the
438 * free memory in the system during the khugepaged scan.
440 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
441 struct kobj_attribute *attr,
444 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
446 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
447 struct kobj_attribute *attr,
448 const char *buf, size_t count)
451 unsigned long max_ptes_none;
453 err = strict_strtoul(buf, 10, &max_ptes_none);
454 if (err || max_ptes_none > HPAGE_PMD_NR-1)
457 khugepaged_max_ptes_none = max_ptes_none;
461 static struct kobj_attribute khugepaged_max_ptes_none_attr =
462 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
463 khugepaged_max_ptes_none_store);
465 static struct attribute *khugepaged_attr[] = {
466 &khugepaged_defrag_attr.attr,
467 &khugepaged_max_ptes_none_attr.attr,
468 &pages_to_scan_attr.attr,
469 &pages_collapsed_attr.attr,
470 &full_scans_attr.attr,
471 &scan_sleep_millisecs_attr.attr,
472 &alloc_sleep_millisecs_attr.attr,
476 static struct attribute_group khugepaged_attr_group = {
477 .attrs = khugepaged_attr,
478 .name = "khugepaged",
481 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
485 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
486 if (unlikely(!*hugepage_kobj)) {
487 printk(KERN_ERR "hugepage: failed kobject create\n");
491 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
493 printk(KERN_ERR "hugepage: failed register hugeage group\n");
497 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
499 printk(KERN_ERR "hugepage: failed register hugeage group\n");
500 goto remove_hp_group;
506 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
508 kobject_put(*hugepage_kobj);
512 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
514 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
515 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
516 kobject_put(hugepage_kobj);
519 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
524 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
527 #endif /* CONFIG_SYSFS */
529 static int __init hugepage_init(void)
532 struct kobject *hugepage_kobj;
534 if (!has_transparent_hugepage()) {
535 transparent_hugepage_flags = 0;
539 err = hugepage_init_sysfs(&hugepage_kobj);
543 err = khugepaged_slab_init();
547 err = mm_slots_hash_init();
549 khugepaged_slab_free();
554 * By default disable transparent hugepages on smaller systems,
555 * where the extra memory used could hurt more than TLB overhead
556 * is likely to save. The admin can still enable it through /sys.
558 if (totalram_pages < (512 << (20 - PAGE_SHIFT)))
559 transparent_hugepage_flags = 0;
565 hugepage_exit_sysfs(hugepage_kobj);
568 module_init(hugepage_init)
570 static int __init setup_transparent_hugepage(char *str)
575 if (!strcmp(str, "always")) {
576 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
577 &transparent_hugepage_flags);
578 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
579 &transparent_hugepage_flags);
581 } else if (!strcmp(str, "madvise")) {
582 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
583 &transparent_hugepage_flags);
584 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
585 &transparent_hugepage_flags);
587 } else if (!strcmp(str, "never")) {
588 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
589 &transparent_hugepage_flags);
590 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
591 &transparent_hugepage_flags);
597 "transparent_hugepage= cannot parse, ignored\n");
600 __setup("transparent_hugepage=", setup_transparent_hugepage);
602 static inline pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
604 if (likely(vma->vm_flags & VM_WRITE))
605 pmd = pmd_mkwrite(pmd);
609 static inline pmd_t mk_huge_pmd(struct page *page, struct vm_area_struct *vma)
612 entry = mk_pmd(page, vma->vm_page_prot);
613 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
614 entry = pmd_mkhuge(entry);
618 static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
619 struct vm_area_struct *vma,
620 unsigned long haddr, pmd_t *pmd,
625 VM_BUG_ON(!PageCompound(page));
626 pgtable = pte_alloc_one(mm, haddr);
627 if (unlikely(!pgtable))
630 clear_huge_page(page, haddr, HPAGE_PMD_NR);
631 __SetPageUptodate(page);
633 spin_lock(&mm->page_table_lock);
634 if (unlikely(!pmd_none(*pmd))) {
635 spin_unlock(&mm->page_table_lock);
636 mem_cgroup_uncharge_page(page);
638 pte_free(mm, pgtable);
641 entry = mk_huge_pmd(page, vma);
643 * The spinlocking to take the lru_lock inside
644 * page_add_new_anon_rmap() acts as a full memory
645 * barrier to be sure clear_huge_page writes become
646 * visible after the set_pmd_at() write.
648 page_add_new_anon_rmap(page, vma, haddr);
649 set_pmd_at(mm, haddr, pmd, entry);
650 pgtable_trans_huge_deposit(mm, pgtable);
651 add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
653 spin_unlock(&mm->page_table_lock);
659 static inline gfp_t alloc_hugepage_gfpmask(int defrag, gfp_t extra_gfp)
661 return (GFP_TRANSHUGE & ~(defrag ? 0 : __GFP_WAIT)) | extra_gfp;
664 static inline struct page *alloc_hugepage_vma(int defrag,
665 struct vm_area_struct *vma,
666 unsigned long haddr, int nd,
669 return alloc_pages_vma(alloc_hugepage_gfpmask(defrag, extra_gfp),
670 HPAGE_PMD_ORDER, vma, haddr, nd);
674 static inline struct page *alloc_hugepage(int defrag)
676 return alloc_pages(alloc_hugepage_gfpmask(defrag, 0),
681 int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
682 unsigned long address, pmd_t *pmd,
686 unsigned long haddr = address & HPAGE_PMD_MASK;
689 if (haddr >= vma->vm_start && haddr + HPAGE_PMD_SIZE <= vma->vm_end) {
690 if (unlikely(anon_vma_prepare(vma)))
692 if (unlikely(khugepaged_enter(vma)))
694 page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
695 vma, haddr, numa_node_id(), 0);
696 if (unlikely(!page)) {
697 count_vm_event(THP_FAULT_FALLBACK);
700 count_vm_event(THP_FAULT_ALLOC);
701 if (unlikely(mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))) {
705 if (unlikely(__do_huge_pmd_anonymous_page(mm, vma, haddr, pmd,
707 mem_cgroup_uncharge_page(page);
716 * Use __pte_alloc instead of pte_alloc_map, because we can't
717 * run pte_offset_map on the pmd, if an huge pmd could
718 * materialize from under us from a different thread.
720 if (unlikely(__pte_alloc(mm, vma, pmd, address)))
722 /* if an huge pmd materialized from under us just retry later */
723 if (unlikely(pmd_trans_huge(*pmd)))
726 * A regular pmd is established and it can't morph into a huge pmd
727 * from under us anymore at this point because we hold the mmap_sem
728 * read mode and khugepaged takes it in write mode. So now it's
729 * safe to run pte_offset_map().
731 pte = pte_offset_map(pmd, address);
732 return handle_pte_fault(mm, vma, address, pte, pmd, flags);
735 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
736 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
737 struct vm_area_struct *vma)
739 struct page *src_page;
745 pgtable = pte_alloc_one(dst_mm, addr);
746 if (unlikely(!pgtable))
749 spin_lock(&dst_mm->page_table_lock);
750 spin_lock_nested(&src_mm->page_table_lock, SINGLE_DEPTH_NESTING);
754 if (unlikely(!pmd_trans_huge(pmd))) {
755 pte_free(dst_mm, pgtable);
758 if (unlikely(pmd_trans_splitting(pmd))) {
759 /* split huge page running from under us */
760 spin_unlock(&src_mm->page_table_lock);
761 spin_unlock(&dst_mm->page_table_lock);
762 pte_free(dst_mm, pgtable);
764 wait_split_huge_page(vma->anon_vma, src_pmd); /* src_vma */
767 src_page = pmd_page(pmd);
768 VM_BUG_ON(!PageHead(src_page));
770 page_dup_rmap(src_page);
771 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
773 pmdp_set_wrprotect(src_mm, addr, src_pmd);
774 pmd = pmd_mkold(pmd_wrprotect(pmd));
775 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
776 pgtable_trans_huge_deposit(dst_mm, pgtable);
781 spin_unlock(&src_mm->page_table_lock);
782 spin_unlock(&dst_mm->page_table_lock);
787 static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
788 struct vm_area_struct *vma,
789 unsigned long address,
790 pmd_t *pmd, pmd_t orig_pmd,
798 unsigned long mmun_start; /* For mmu_notifiers */
799 unsigned long mmun_end; /* For mmu_notifiers */
801 pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
803 if (unlikely(!pages)) {
808 for (i = 0; i < HPAGE_PMD_NR; i++) {
809 pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
811 vma, address, page_to_nid(page));
812 if (unlikely(!pages[i] ||
813 mem_cgroup_newpage_charge(pages[i], mm,
817 mem_cgroup_uncharge_start();
819 mem_cgroup_uncharge_page(pages[i]);
822 mem_cgroup_uncharge_end();
829 for (i = 0; i < HPAGE_PMD_NR; i++) {
830 copy_user_highpage(pages[i], page + i,
831 haddr + PAGE_SIZE * i, vma);
832 __SetPageUptodate(pages[i]);
837 mmun_end = haddr + HPAGE_PMD_SIZE;
838 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
840 spin_lock(&mm->page_table_lock);
841 if (unlikely(!pmd_same(*pmd, orig_pmd)))
843 VM_BUG_ON(!PageHead(page));
845 pmdp_clear_flush(vma, haddr, pmd);
846 /* leave pmd empty until pte is filled */
848 pgtable = pgtable_trans_huge_withdraw(mm);
849 pmd_populate(mm, &_pmd, pgtable);
851 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
853 entry = mk_pte(pages[i], vma->vm_page_prot);
854 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
855 page_add_new_anon_rmap(pages[i], vma, haddr);
856 pte = pte_offset_map(&_pmd, haddr);
857 VM_BUG_ON(!pte_none(*pte));
858 set_pte_at(mm, haddr, pte, entry);
863 smp_wmb(); /* make pte visible before pmd */
864 pmd_populate(mm, pmd, pgtable);
865 page_remove_rmap(page);
866 spin_unlock(&mm->page_table_lock);
868 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
870 ret |= VM_FAULT_WRITE;
877 spin_unlock(&mm->page_table_lock);
878 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
879 mem_cgroup_uncharge_start();
880 for (i = 0; i < HPAGE_PMD_NR; i++) {
881 mem_cgroup_uncharge_page(pages[i]);
884 mem_cgroup_uncharge_end();
889 int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
890 unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
893 struct page *page, *new_page;
895 unsigned long mmun_start; /* For mmu_notifiers */
896 unsigned long mmun_end; /* For mmu_notifiers */
898 VM_BUG_ON(!vma->anon_vma);
899 spin_lock(&mm->page_table_lock);
900 if (unlikely(!pmd_same(*pmd, orig_pmd)))
903 page = pmd_page(orig_pmd);
904 VM_BUG_ON(!PageCompound(page) || !PageHead(page));
905 haddr = address & HPAGE_PMD_MASK;
906 if (page_mapcount(page) == 1) {
908 entry = pmd_mkyoung(orig_pmd);
909 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
910 if (pmdp_set_access_flags(vma, haddr, pmd, entry, 1))
911 update_mmu_cache_pmd(vma, address, pmd);
912 ret |= VM_FAULT_WRITE;
916 spin_unlock(&mm->page_table_lock);
918 if (transparent_hugepage_enabled(vma) &&
919 !transparent_hugepage_debug_cow())
920 new_page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
921 vma, haddr, numa_node_id(), 0);
925 if (unlikely(!new_page)) {
926 count_vm_event(THP_FAULT_FALLBACK);
927 ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
928 pmd, orig_pmd, page, haddr);
929 if (ret & VM_FAULT_OOM)
930 split_huge_page(page);
934 count_vm_event(THP_FAULT_ALLOC);
936 if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
938 split_huge_page(page);
944 copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
945 __SetPageUptodate(new_page);
948 mmun_end = haddr + HPAGE_PMD_SIZE;
949 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
951 spin_lock(&mm->page_table_lock);
953 if (unlikely(!pmd_same(*pmd, orig_pmd))) {
954 spin_unlock(&mm->page_table_lock);
955 mem_cgroup_uncharge_page(new_page);
960 VM_BUG_ON(!PageHead(page));
961 entry = mk_huge_pmd(new_page, vma);
962 pmdp_clear_flush(vma, haddr, pmd);
963 page_add_new_anon_rmap(new_page, vma, haddr);
964 set_pmd_at(mm, haddr, pmd, entry);
965 update_mmu_cache_pmd(vma, address, pmd);
966 page_remove_rmap(page);
968 ret |= VM_FAULT_WRITE;
970 spin_unlock(&mm->page_table_lock);
972 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
976 spin_unlock(&mm->page_table_lock);
980 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
985 struct mm_struct *mm = vma->vm_mm;
986 struct page *page = NULL;
988 assert_spin_locked(&mm->page_table_lock);
990 if (flags & FOLL_WRITE && !pmd_write(*pmd))
993 page = pmd_page(*pmd);
994 VM_BUG_ON(!PageHead(page));
995 if (flags & FOLL_TOUCH) {
998 * We should set the dirty bit only for FOLL_WRITE but
999 * for now the dirty bit in the pmd is meaningless.
1000 * And if the dirty bit will become meaningful and
1001 * we'll only set it with FOLL_WRITE, an atomic
1002 * set_bit will be required on the pmd to set the
1003 * young bit, instead of the current set_pmd_at.
1005 _pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
1006 set_pmd_at(mm, addr & HPAGE_PMD_MASK, pmd, _pmd);
1008 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
1009 if (page->mapping && trylock_page(page)) {
1012 mlock_vma_page(page);
1016 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1017 VM_BUG_ON(!PageCompound(page));
1018 if (flags & FOLL_GET)
1019 get_page_foll(page);
1025 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1026 pmd_t *pmd, unsigned long addr)
1030 if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1034 pgtable = pgtable_trans_huge_withdraw(tlb->mm);
1035 orig_pmd = pmdp_get_and_clear(tlb->mm, addr, pmd);
1036 page = pmd_page(orig_pmd);
1037 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1038 page_remove_rmap(page);
1039 VM_BUG_ON(page_mapcount(page) < 0);
1040 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1041 VM_BUG_ON(!PageHead(page));
1043 spin_unlock(&tlb->mm->page_table_lock);
1044 tlb_remove_page(tlb, page);
1045 pte_free(tlb->mm, pgtable);
1051 int mincore_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1052 unsigned long addr, unsigned long end,
1057 if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1059 * All logical pages in the range are present
1060 * if backed by a huge page.
1062 spin_unlock(&vma->vm_mm->page_table_lock);
1063 memset(vec, 1, (end - addr) >> PAGE_SHIFT);
1070 int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1071 unsigned long old_addr,
1072 unsigned long new_addr, unsigned long old_end,
1073 pmd_t *old_pmd, pmd_t *new_pmd)
1078 struct mm_struct *mm = vma->vm_mm;
1080 if ((old_addr & ~HPAGE_PMD_MASK) ||
1081 (new_addr & ~HPAGE_PMD_MASK) ||
1082 old_end - old_addr < HPAGE_PMD_SIZE ||
1083 (new_vma->vm_flags & VM_NOHUGEPAGE))
1087 * The destination pmd shouldn't be established, free_pgtables()
1088 * should have release it.
1090 if (WARN_ON(!pmd_none(*new_pmd))) {
1091 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1095 ret = __pmd_trans_huge_lock(old_pmd, vma);
1097 pmd = pmdp_get_and_clear(mm, old_addr, old_pmd);
1098 VM_BUG_ON(!pmd_none(*new_pmd));
1099 set_pmd_at(mm, new_addr, new_pmd, pmd);
1100 spin_unlock(&mm->page_table_lock);
1106 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1107 unsigned long addr, pgprot_t newprot)
1109 struct mm_struct *mm = vma->vm_mm;
1112 if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1114 entry = pmdp_get_and_clear(mm, addr, pmd);
1115 entry = pmd_modify(entry, newprot);
1116 set_pmd_at(mm, addr, pmd, entry);
1117 spin_unlock(&vma->vm_mm->page_table_lock);
1125 * Returns 1 if a given pmd maps a stable (not under splitting) thp.
1126 * Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
1128 * Note that if it returns 1, this routine returns without unlocking page
1129 * table locks. So callers must unlock them.
1131 int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1133 spin_lock(&vma->vm_mm->page_table_lock);
1134 if (likely(pmd_trans_huge(*pmd))) {
1135 if (unlikely(pmd_trans_splitting(*pmd))) {
1136 spin_unlock(&vma->vm_mm->page_table_lock);
1137 wait_split_huge_page(vma->anon_vma, pmd);
1140 /* Thp mapped by 'pmd' is stable, so we can
1141 * handle it as it is. */
1145 spin_unlock(&vma->vm_mm->page_table_lock);
1149 pmd_t *page_check_address_pmd(struct page *page,
1150 struct mm_struct *mm,
1151 unsigned long address,
1152 enum page_check_address_pmd_flag flag)
1154 pmd_t *pmd, *ret = NULL;
1156 if (address & ~HPAGE_PMD_MASK)
1159 pmd = mm_find_pmd(mm, address);
1164 if (pmd_page(*pmd) != page)
1167 * split_vma() may create temporary aliased mappings. There is
1168 * no risk as long as all huge pmd are found and have their
1169 * splitting bit set before __split_huge_page_refcount
1170 * runs. Finding the same huge pmd more than once during the
1171 * same rmap walk is not a problem.
1173 if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1174 pmd_trans_splitting(*pmd))
1176 if (pmd_trans_huge(*pmd)) {
1177 VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1178 !pmd_trans_splitting(*pmd));
1185 static int __split_huge_page_splitting(struct page *page,
1186 struct vm_area_struct *vma,
1187 unsigned long address)
1189 struct mm_struct *mm = vma->vm_mm;
1192 /* For mmu_notifiers */
1193 const unsigned long mmun_start = address;
1194 const unsigned long mmun_end = address + HPAGE_PMD_SIZE;
1196 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1197 spin_lock(&mm->page_table_lock);
1198 pmd = page_check_address_pmd(page, mm, address,
1199 PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
1202 * We can't temporarily set the pmd to null in order
1203 * to split it, the pmd must remain marked huge at all
1204 * times or the VM won't take the pmd_trans_huge paths
1205 * and it won't wait on the anon_vma->root->mutex to
1206 * serialize against split_huge_page*.
1208 pmdp_splitting_flush(vma, address, pmd);
1211 spin_unlock(&mm->page_table_lock);
1212 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1217 static void __split_huge_page_refcount(struct page *page)
1220 struct zone *zone = page_zone(page);
1221 struct lruvec *lruvec;
1224 /* prevent PageLRU to go away from under us, and freeze lru stats */
1225 spin_lock_irq(&zone->lru_lock);
1226 lruvec = mem_cgroup_page_lruvec(page, zone);
1228 compound_lock(page);
1229 /* complete memcg works before add pages to LRU */
1230 mem_cgroup_split_huge_fixup(page);
1232 for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
1233 struct page *page_tail = page + i;
1235 /* tail_page->_mapcount cannot change */
1236 BUG_ON(page_mapcount(page_tail) < 0);
1237 tail_count += page_mapcount(page_tail);
1238 /* check for overflow */
1239 BUG_ON(tail_count < 0);
1240 BUG_ON(atomic_read(&page_tail->_count) != 0);
1242 * tail_page->_count is zero and not changing from
1243 * under us. But get_page_unless_zero() may be running
1244 * from under us on the tail_page. If we used
1245 * atomic_set() below instead of atomic_add(), we
1246 * would then run atomic_set() concurrently with
1247 * get_page_unless_zero(), and atomic_set() is
1248 * implemented in C not using locked ops. spin_unlock
1249 * on x86 sometime uses locked ops because of PPro
1250 * errata 66, 92, so unless somebody can guarantee
1251 * atomic_set() here would be safe on all archs (and
1252 * not only on x86), it's safer to use atomic_add().
1254 atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1255 &page_tail->_count);
1257 /* after clearing PageTail the gup refcount can be released */
1261 * retain hwpoison flag of the poisoned tail page:
1262 * fix for the unsuitable process killed on Guest Machine(KVM)
1263 * by the memory-failure.
1265 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP | __PG_HWPOISON;
1266 page_tail->flags |= (page->flags &
1267 ((1L << PG_referenced) |
1268 (1L << PG_swapbacked) |
1269 (1L << PG_mlocked) |
1270 (1L << PG_uptodate)));
1271 page_tail->flags |= (1L << PG_dirty);
1273 /* clear PageTail before overwriting first_page */
1277 * __split_huge_page_splitting() already set the
1278 * splitting bit in all pmd that could map this
1279 * hugepage, that will ensure no CPU can alter the
1280 * mapcount on the head page. The mapcount is only
1281 * accounted in the head page and it has to be
1282 * transferred to all tail pages in the below code. So
1283 * for this code to be safe, the split the mapcount
1284 * can't change. But that doesn't mean userland can't
1285 * keep changing and reading the page contents while
1286 * we transfer the mapcount, so the pmd splitting
1287 * status is achieved setting a reserved bit in the
1288 * pmd, not by clearing the present bit.
1290 page_tail->_mapcount = page->_mapcount;
1292 BUG_ON(page_tail->mapping);
1293 page_tail->mapping = page->mapping;
1295 page_tail->index = page->index + i;
1297 BUG_ON(!PageAnon(page_tail));
1298 BUG_ON(!PageUptodate(page_tail));
1299 BUG_ON(!PageDirty(page_tail));
1300 BUG_ON(!PageSwapBacked(page_tail));
1302 lru_add_page_tail(page, page_tail, lruvec);
1304 atomic_sub(tail_count, &page->_count);
1305 BUG_ON(atomic_read(&page->_count) <= 0);
1307 __mod_zone_page_state(zone, NR_ANON_TRANSPARENT_HUGEPAGES, -1);
1308 __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1310 ClearPageCompound(page);
1311 compound_unlock(page);
1312 spin_unlock_irq(&zone->lru_lock);
1314 for (i = 1; i < HPAGE_PMD_NR; i++) {
1315 struct page *page_tail = page + i;
1316 BUG_ON(page_count(page_tail) <= 0);
1318 * Tail pages may be freed if there wasn't any mapping
1319 * like if add_to_swap() is running on a lru page that
1320 * had its mapping zapped. And freeing these pages
1321 * requires taking the lru_lock so we do the put_page
1322 * of the tail pages after the split is complete.
1324 put_page(page_tail);
1328 * Only the head page (now become a regular page) is required
1329 * to be pinned by the caller.
1331 BUG_ON(page_count(page) <= 0);
1334 static int __split_huge_page_map(struct page *page,
1335 struct vm_area_struct *vma,
1336 unsigned long address)
1338 struct mm_struct *mm = vma->vm_mm;
1342 unsigned long haddr;
1344 spin_lock(&mm->page_table_lock);
1345 pmd = page_check_address_pmd(page, mm, address,
1346 PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1348 pgtable = pgtable_trans_huge_withdraw(mm);
1349 pmd_populate(mm, &_pmd, pgtable);
1352 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1354 BUG_ON(PageCompound(page+i));
1355 entry = mk_pte(page + i, vma->vm_page_prot);
1356 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1357 if (!pmd_write(*pmd))
1358 entry = pte_wrprotect(entry);
1360 BUG_ON(page_mapcount(page) != 1);
1361 if (!pmd_young(*pmd))
1362 entry = pte_mkold(entry);
1363 pte = pte_offset_map(&_pmd, haddr);
1364 BUG_ON(!pte_none(*pte));
1365 set_pte_at(mm, haddr, pte, entry);
1369 smp_wmb(); /* make pte visible before pmd */
1371 * Up to this point the pmd is present and huge and
1372 * userland has the whole access to the hugepage
1373 * during the split (which happens in place). If we
1374 * overwrite the pmd with the not-huge version
1375 * pointing to the pte here (which of course we could
1376 * if all CPUs were bug free), userland could trigger
1377 * a small page size TLB miss on the small sized TLB
1378 * while the hugepage TLB entry is still established
1379 * in the huge TLB. Some CPU doesn't like that. See
1380 * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1381 * Erratum 383 on page 93. Intel should be safe but is
1382 * also warns that it's only safe if the permission
1383 * and cache attributes of the two entries loaded in
1384 * the two TLB is identical (which should be the case
1385 * here). But it is generally safer to never allow
1386 * small and huge TLB entries for the same virtual
1387 * address to be loaded simultaneously. So instead of
1388 * doing "pmd_populate(); flush_tlb_range();" we first
1389 * mark the current pmd notpresent (atomically because
1390 * here the pmd_trans_huge and pmd_trans_splitting
1391 * must remain set at all times on the pmd until the
1392 * split is complete for this pmd), then we flush the
1393 * SMP TLB and finally we write the non-huge version
1394 * of the pmd entry with pmd_populate.
1396 pmdp_invalidate(vma, address, pmd);
1397 pmd_populate(mm, pmd, pgtable);
1400 spin_unlock(&mm->page_table_lock);
1405 /* must be called with anon_vma->root->mutex hold */
1406 static void __split_huge_page(struct page *page,
1407 struct anon_vma *anon_vma)
1409 int mapcount, mapcount2;
1410 pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
1411 struct anon_vma_chain *avc;
1413 BUG_ON(!PageHead(page));
1414 BUG_ON(PageTail(page));
1417 anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1418 struct vm_area_struct *vma = avc->vma;
1419 unsigned long addr = vma_address(page, vma);
1420 BUG_ON(is_vma_temporary_stack(vma));
1421 mapcount += __split_huge_page_splitting(page, vma, addr);
1424 * It is critical that new vmas are added to the tail of the
1425 * anon_vma list. This guarantes that if copy_huge_pmd() runs
1426 * and establishes a child pmd before
1427 * __split_huge_page_splitting() freezes the parent pmd (so if
1428 * we fail to prevent copy_huge_pmd() from running until the
1429 * whole __split_huge_page() is complete), we will still see
1430 * the newly established pmd of the child later during the
1431 * walk, to be able to set it as pmd_trans_splitting too.
1433 if (mapcount != page_mapcount(page))
1434 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1435 mapcount, page_mapcount(page));
1436 BUG_ON(mapcount != page_mapcount(page));
1438 __split_huge_page_refcount(page);
1441 anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1442 struct vm_area_struct *vma = avc->vma;
1443 unsigned long addr = vma_address(page, vma);
1444 BUG_ON(is_vma_temporary_stack(vma));
1445 mapcount2 += __split_huge_page_map(page, vma, addr);
1447 if (mapcount != mapcount2)
1448 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1449 mapcount, mapcount2, page_mapcount(page));
1450 BUG_ON(mapcount != mapcount2);
1453 int split_huge_page(struct page *page)
1455 struct anon_vma *anon_vma;
1458 BUG_ON(!PageAnon(page));
1459 anon_vma = page_lock_anon_vma(page);
1463 if (!PageCompound(page))
1466 BUG_ON(!PageSwapBacked(page));
1467 __split_huge_page(page, anon_vma);
1468 count_vm_event(THP_SPLIT);
1470 BUG_ON(PageCompound(page));
1472 page_unlock_anon_vma(anon_vma);
1477 #define VM_NO_THP (VM_SPECIAL|VM_MIXEDMAP|VM_HUGETLB|VM_SHARED|VM_MAYSHARE)
1479 int hugepage_madvise(struct vm_area_struct *vma,
1480 unsigned long *vm_flags, int advice)
1482 struct mm_struct *mm = vma->vm_mm;
1487 * Be somewhat over-protective like KSM for now!
1489 if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
1491 if (mm->def_flags & VM_NOHUGEPAGE)
1493 *vm_flags &= ~VM_NOHUGEPAGE;
1494 *vm_flags |= VM_HUGEPAGE;
1496 * If the vma become good for khugepaged to scan,
1497 * register it here without waiting a page fault that
1498 * may not happen any time soon.
1500 if (unlikely(khugepaged_enter_vma_merge(vma)))
1503 case MADV_NOHUGEPAGE:
1505 * Be somewhat over-protective like KSM for now!
1507 if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
1509 *vm_flags &= ~VM_HUGEPAGE;
1510 *vm_flags |= VM_NOHUGEPAGE;
1512 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1513 * this vma even if we leave the mm registered in khugepaged if
1514 * it got registered before VM_NOHUGEPAGE was set.
1522 static int __init khugepaged_slab_init(void)
1524 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1525 sizeof(struct mm_slot),
1526 __alignof__(struct mm_slot), 0, NULL);
1533 static void __init khugepaged_slab_free(void)
1535 kmem_cache_destroy(mm_slot_cache);
1536 mm_slot_cache = NULL;
1539 static inline struct mm_slot *alloc_mm_slot(void)
1541 if (!mm_slot_cache) /* initialization failed */
1543 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1546 static inline void free_mm_slot(struct mm_slot *mm_slot)
1548 kmem_cache_free(mm_slot_cache, mm_slot);
1551 static int __init mm_slots_hash_init(void)
1553 mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1561 static void __init mm_slots_hash_free(void)
1563 kfree(mm_slots_hash);
1564 mm_slots_hash = NULL;
1568 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1570 struct mm_slot *mm_slot;
1571 struct hlist_head *bucket;
1572 struct hlist_node *node;
1574 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1575 % MM_SLOTS_HASH_HEADS];
1576 hlist_for_each_entry(mm_slot, node, bucket, hash) {
1577 if (mm == mm_slot->mm)
1583 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1584 struct mm_slot *mm_slot)
1586 struct hlist_head *bucket;
1588 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1589 % MM_SLOTS_HASH_HEADS];
1591 hlist_add_head(&mm_slot->hash, bucket);
1594 static inline int khugepaged_test_exit(struct mm_struct *mm)
1596 return atomic_read(&mm->mm_users) == 0;
1599 int __khugepaged_enter(struct mm_struct *mm)
1601 struct mm_slot *mm_slot;
1604 mm_slot = alloc_mm_slot();
1608 /* __khugepaged_exit() must not run from under us */
1609 VM_BUG_ON(khugepaged_test_exit(mm));
1610 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1611 free_mm_slot(mm_slot);
1615 spin_lock(&khugepaged_mm_lock);
1616 insert_to_mm_slots_hash(mm, mm_slot);
1618 * Insert just behind the scanning cursor, to let the area settle
1621 wakeup = list_empty(&khugepaged_scan.mm_head);
1622 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1623 spin_unlock(&khugepaged_mm_lock);
1625 atomic_inc(&mm->mm_count);
1627 wake_up_interruptible(&khugepaged_wait);
1632 int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
1634 unsigned long hstart, hend;
1637 * Not yet faulted in so we will register later in the
1638 * page fault if needed.
1642 /* khugepaged not yet working on file or special mappings */
1644 VM_BUG_ON(vma->vm_flags & VM_NO_THP);
1645 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1646 hend = vma->vm_end & HPAGE_PMD_MASK;
1648 return khugepaged_enter(vma);
1652 void __khugepaged_exit(struct mm_struct *mm)
1654 struct mm_slot *mm_slot;
1657 spin_lock(&khugepaged_mm_lock);
1658 mm_slot = get_mm_slot(mm);
1659 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1660 hlist_del(&mm_slot->hash);
1661 list_del(&mm_slot->mm_node);
1664 spin_unlock(&khugepaged_mm_lock);
1667 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1668 free_mm_slot(mm_slot);
1670 } else if (mm_slot) {
1672 * This is required to serialize against
1673 * khugepaged_test_exit() (which is guaranteed to run
1674 * under mmap sem read mode). Stop here (after we
1675 * return all pagetables will be destroyed) until
1676 * khugepaged has finished working on the pagetables
1677 * under the mmap_sem.
1679 down_write(&mm->mmap_sem);
1680 up_write(&mm->mmap_sem);
1684 static void release_pte_page(struct page *page)
1686 /* 0 stands for page_is_file_cache(page) == false */
1687 dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1689 putback_lru_page(page);
1692 static void release_pte_pages(pte_t *pte, pte_t *_pte)
1694 while (--_pte >= pte) {
1695 pte_t pteval = *_pte;
1696 if (!pte_none(pteval))
1697 release_pte_page(pte_page(pteval));
1701 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1702 unsigned long address,
1707 int referenced = 0, none = 0;
1708 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1709 _pte++, address += PAGE_SIZE) {
1710 pte_t pteval = *_pte;
1711 if (pte_none(pteval)) {
1712 if (++none <= khugepaged_max_ptes_none)
1717 if (!pte_present(pteval) || !pte_write(pteval))
1719 page = vm_normal_page(vma, address, pteval);
1720 if (unlikely(!page))
1723 VM_BUG_ON(PageCompound(page));
1724 BUG_ON(!PageAnon(page));
1725 VM_BUG_ON(!PageSwapBacked(page));
1727 /* cannot use mapcount: can't collapse if there's a gup pin */
1728 if (page_count(page) != 1)
1731 * We can do it before isolate_lru_page because the
1732 * page can't be freed from under us. NOTE: PG_lock
1733 * is needed to serialize against split_huge_page
1734 * when invoked from the VM.
1736 if (!trylock_page(page))
1739 * Isolate the page to avoid collapsing an hugepage
1740 * currently in use by the VM.
1742 if (isolate_lru_page(page)) {
1746 /* 0 stands for page_is_file_cache(page) == false */
1747 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1748 VM_BUG_ON(!PageLocked(page));
1749 VM_BUG_ON(PageLRU(page));
1751 /* If there is no mapped pte young don't collapse the page */
1752 if (pte_young(pteval) || PageReferenced(page) ||
1753 mmu_notifier_test_young(vma->vm_mm, address))
1756 if (likely(referenced))
1759 release_pte_pages(pte, _pte);
1763 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1764 struct vm_area_struct *vma,
1765 unsigned long address,
1769 for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1770 pte_t pteval = *_pte;
1771 struct page *src_page;
1773 if (pte_none(pteval)) {
1774 clear_user_highpage(page, address);
1775 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1777 src_page = pte_page(pteval);
1778 copy_user_highpage(page, src_page, address, vma);
1779 VM_BUG_ON(page_mapcount(src_page) != 1);
1780 release_pte_page(src_page);
1782 * ptl mostly unnecessary, but preempt has to
1783 * be disabled to update the per-cpu stats
1784 * inside page_remove_rmap().
1788 * paravirt calls inside pte_clear here are
1791 pte_clear(vma->vm_mm, address, _pte);
1792 page_remove_rmap(src_page);
1794 free_page_and_swap_cache(src_page);
1797 address += PAGE_SIZE;
1802 static void khugepaged_alloc_sleep(void)
1804 wait_event_freezable_timeout(khugepaged_wait, false,
1805 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
1809 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
1811 if (IS_ERR(*hpage)) {
1817 khugepaged_alloc_sleep();
1818 } else if (*hpage) {
1827 *khugepaged_alloc_page(struct page **hpage, struct mm_struct *mm,
1828 struct vm_area_struct *vma, unsigned long address,
1833 * Allocate the page while the vma is still valid and under
1834 * the mmap_sem read mode so there is no memory allocation
1835 * later when we take the mmap_sem in write mode. This is more
1836 * friendly behavior (OTOH it may actually hide bugs) to
1837 * filesystems in userland with daemons allocating memory in
1838 * the userland I/O paths. Allocating memory with the
1839 * mmap_sem in read mode is good idea also to allow greater
1842 *hpage = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
1843 node, __GFP_OTHER_NODE);
1846 * After allocating the hugepage, release the mmap_sem read lock in
1847 * preparation for taking it in write mode.
1849 up_read(&mm->mmap_sem);
1850 if (unlikely(!*hpage)) {
1851 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1852 *hpage = ERR_PTR(-ENOMEM);
1856 count_vm_event(THP_COLLAPSE_ALLOC);
1860 static struct page *khugepaged_alloc_hugepage(bool *wait)
1865 hpage = alloc_hugepage(khugepaged_defrag());
1867 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1872 khugepaged_alloc_sleep();
1874 count_vm_event(THP_COLLAPSE_ALLOC);
1875 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
1880 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
1883 *hpage = khugepaged_alloc_hugepage(wait);
1885 if (unlikely(!*hpage))
1892 *khugepaged_alloc_page(struct page **hpage, struct mm_struct *mm,
1893 struct vm_area_struct *vma, unsigned long address,
1896 up_read(&mm->mmap_sem);
1902 static bool hugepage_vma_check(struct vm_area_struct *vma)
1904 if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
1905 (vma->vm_flags & VM_NOHUGEPAGE))
1908 if (!vma->anon_vma || vma->vm_ops)
1910 if (is_vma_temporary_stack(vma))
1912 VM_BUG_ON(vma->vm_flags & VM_NO_THP);
1916 static void collapse_huge_page(struct mm_struct *mm,
1917 unsigned long address,
1918 struct page **hpage,
1919 struct vm_area_struct *vma,
1925 struct page *new_page;
1928 unsigned long hstart, hend;
1929 unsigned long mmun_start; /* For mmu_notifiers */
1930 unsigned long mmun_end; /* For mmu_notifiers */
1932 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1934 /* release the mmap_sem read lock. */
1935 new_page = khugepaged_alloc_page(hpage, mm, vma, address, node);
1939 if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL)))
1943 * Prevent all access to pagetables with the exception of
1944 * gup_fast later hanlded by the ptep_clear_flush and the VM
1945 * handled by the anon_vma lock + PG_lock.
1947 down_write(&mm->mmap_sem);
1948 if (unlikely(khugepaged_test_exit(mm)))
1951 vma = find_vma(mm, address);
1952 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1953 hend = vma->vm_end & HPAGE_PMD_MASK;
1954 if (address < hstart || address + HPAGE_PMD_SIZE > hend)
1956 if (!hugepage_vma_check(vma))
1958 pmd = mm_find_pmd(mm, address);
1961 if (pmd_trans_huge(*pmd))
1964 anon_vma_lock(vma->anon_vma);
1966 pte = pte_offset_map(pmd, address);
1967 ptl = pte_lockptr(mm, pmd);
1969 mmun_start = address;
1970 mmun_end = address + HPAGE_PMD_SIZE;
1971 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1972 spin_lock(&mm->page_table_lock); /* probably unnecessary */
1974 * After this gup_fast can't run anymore. This also removes
1975 * any huge TLB entry from the CPU so we won't allow
1976 * huge and small TLB entries for the same virtual address
1977 * to avoid the risk of CPU bugs in that area.
1979 _pmd = pmdp_clear_flush(vma, address, pmd);
1980 spin_unlock(&mm->page_table_lock);
1981 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1984 isolated = __collapse_huge_page_isolate(vma, address, pte);
1987 if (unlikely(!isolated)) {
1989 spin_lock(&mm->page_table_lock);
1990 BUG_ON(!pmd_none(*pmd));
1991 set_pmd_at(mm, address, pmd, _pmd);
1992 spin_unlock(&mm->page_table_lock);
1993 anon_vma_unlock(vma->anon_vma);
1998 * All pages are isolated and locked so anon_vma rmap
1999 * can't run anymore.
2001 anon_vma_unlock(vma->anon_vma);
2003 __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
2005 __SetPageUptodate(new_page);
2006 pgtable = pmd_pgtable(_pmd);
2008 _pmd = mk_huge_pmd(new_page, vma);
2011 * spin_lock() below is not the equivalent of smp_wmb(), so
2012 * this is needed to avoid the copy_huge_page writes to become
2013 * visible after the set_pmd_at() write.
2017 spin_lock(&mm->page_table_lock);
2018 BUG_ON(!pmd_none(*pmd));
2019 page_add_new_anon_rmap(new_page, vma, address);
2020 set_pmd_at(mm, address, pmd, _pmd);
2021 update_mmu_cache_pmd(vma, address, pmd);
2022 pgtable_trans_huge_deposit(mm, pgtable);
2023 spin_unlock(&mm->page_table_lock);
2027 khugepaged_pages_collapsed++;
2029 up_write(&mm->mmap_sem);
2033 mem_cgroup_uncharge_page(new_page);
2037 static int khugepaged_scan_pmd(struct mm_struct *mm,
2038 struct vm_area_struct *vma,
2039 unsigned long address,
2040 struct page **hpage)
2044 int ret = 0, referenced = 0, none = 0;
2046 unsigned long _address;
2050 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2052 pmd = mm_find_pmd(mm, address);
2055 if (pmd_trans_huge(*pmd))
2058 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2059 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2060 _pte++, _address += PAGE_SIZE) {
2061 pte_t pteval = *_pte;
2062 if (pte_none(pteval)) {
2063 if (++none <= khugepaged_max_ptes_none)
2068 if (!pte_present(pteval) || !pte_write(pteval))
2070 page = vm_normal_page(vma, _address, pteval);
2071 if (unlikely(!page))
2074 * Chose the node of the first page. This could
2075 * be more sophisticated and look at more pages,
2076 * but isn't for now.
2079 node = page_to_nid(page);
2080 VM_BUG_ON(PageCompound(page));
2081 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2083 /* cannot use mapcount: can't collapse if there's a gup pin */
2084 if (page_count(page) != 1)
2086 if (pte_young(pteval) || PageReferenced(page) ||
2087 mmu_notifier_test_young(vma->vm_mm, address))
2093 pte_unmap_unlock(pte, ptl);
2095 /* collapse_huge_page will return with the mmap_sem released */
2096 collapse_huge_page(mm, address, hpage, vma, node);
2101 static void collect_mm_slot(struct mm_slot *mm_slot)
2103 struct mm_struct *mm = mm_slot->mm;
2105 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2107 if (khugepaged_test_exit(mm)) {
2109 hlist_del(&mm_slot->hash);
2110 list_del(&mm_slot->mm_node);
2113 * Not strictly needed because the mm exited already.
2115 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2118 /* khugepaged_mm_lock actually not necessary for the below */
2119 free_mm_slot(mm_slot);
2124 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2125 struct page **hpage)
2126 __releases(&khugepaged_mm_lock)
2127 __acquires(&khugepaged_mm_lock)
2129 struct mm_slot *mm_slot;
2130 struct mm_struct *mm;
2131 struct vm_area_struct *vma;
2135 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2137 if (khugepaged_scan.mm_slot)
2138 mm_slot = khugepaged_scan.mm_slot;
2140 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2141 struct mm_slot, mm_node);
2142 khugepaged_scan.address = 0;
2143 khugepaged_scan.mm_slot = mm_slot;
2145 spin_unlock(&khugepaged_mm_lock);
2148 down_read(&mm->mmap_sem);
2149 if (unlikely(khugepaged_test_exit(mm)))
2152 vma = find_vma(mm, khugepaged_scan.address);
2155 for (; vma; vma = vma->vm_next) {
2156 unsigned long hstart, hend;
2159 if (unlikely(khugepaged_test_exit(mm))) {
2163 if (!hugepage_vma_check(vma)) {
2168 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2169 hend = vma->vm_end & HPAGE_PMD_MASK;
2172 if (khugepaged_scan.address > hend)
2174 if (khugepaged_scan.address < hstart)
2175 khugepaged_scan.address = hstart;
2176 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2178 while (khugepaged_scan.address < hend) {
2181 if (unlikely(khugepaged_test_exit(mm)))
2182 goto breakouterloop;
2184 VM_BUG_ON(khugepaged_scan.address < hstart ||
2185 khugepaged_scan.address + HPAGE_PMD_SIZE >
2187 ret = khugepaged_scan_pmd(mm, vma,
2188 khugepaged_scan.address,
2190 /* move to next address */
2191 khugepaged_scan.address += HPAGE_PMD_SIZE;
2192 progress += HPAGE_PMD_NR;
2194 /* we released mmap_sem so break loop */
2195 goto breakouterloop_mmap_sem;
2196 if (progress >= pages)
2197 goto breakouterloop;
2201 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2202 breakouterloop_mmap_sem:
2204 spin_lock(&khugepaged_mm_lock);
2205 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2207 * Release the current mm_slot if this mm is about to die, or
2208 * if we scanned all vmas of this mm.
2210 if (khugepaged_test_exit(mm) || !vma) {
2212 * Make sure that if mm_users is reaching zero while
2213 * khugepaged runs here, khugepaged_exit will find
2214 * mm_slot not pointing to the exiting mm.
2216 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2217 khugepaged_scan.mm_slot = list_entry(
2218 mm_slot->mm_node.next,
2219 struct mm_slot, mm_node);
2220 khugepaged_scan.address = 0;
2222 khugepaged_scan.mm_slot = NULL;
2223 khugepaged_full_scans++;
2226 collect_mm_slot(mm_slot);
2232 static int khugepaged_has_work(void)
2234 return !list_empty(&khugepaged_scan.mm_head) &&
2235 khugepaged_enabled();
2238 static int khugepaged_wait_event(void)
2240 return !list_empty(&khugepaged_scan.mm_head) ||
2241 kthread_should_stop();
2244 static void khugepaged_do_scan(void)
2246 struct page *hpage = NULL;
2247 unsigned int progress = 0, pass_through_head = 0;
2248 unsigned int pages = khugepaged_pages_to_scan;
2251 barrier(); /* write khugepaged_pages_to_scan to local stack */
2253 while (progress < pages) {
2254 if (!khugepaged_prealloc_page(&hpage, &wait))
2259 if (unlikely(kthread_should_stop() || freezing(current)))
2262 spin_lock(&khugepaged_mm_lock);
2263 if (!khugepaged_scan.mm_slot)
2264 pass_through_head++;
2265 if (khugepaged_has_work() &&
2266 pass_through_head < 2)
2267 progress += khugepaged_scan_mm_slot(pages - progress,
2271 spin_unlock(&khugepaged_mm_lock);
2274 if (!IS_ERR_OR_NULL(hpage))
2278 static void khugepaged_wait_work(void)
2282 if (khugepaged_has_work()) {
2283 if (!khugepaged_scan_sleep_millisecs)
2286 wait_event_freezable_timeout(khugepaged_wait,
2287 kthread_should_stop(),
2288 msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2292 if (khugepaged_enabled())
2293 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2296 static int khugepaged(void *none)
2298 struct mm_slot *mm_slot;
2301 set_user_nice(current, 19);
2303 while (!kthread_should_stop()) {
2304 khugepaged_do_scan();
2305 khugepaged_wait_work();
2308 spin_lock(&khugepaged_mm_lock);
2309 mm_slot = khugepaged_scan.mm_slot;
2310 khugepaged_scan.mm_slot = NULL;
2312 collect_mm_slot(mm_slot);
2313 spin_unlock(&khugepaged_mm_lock);
2317 void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2321 spin_lock(&mm->page_table_lock);
2322 if (unlikely(!pmd_trans_huge(*pmd))) {
2323 spin_unlock(&mm->page_table_lock);
2326 page = pmd_page(*pmd);
2327 VM_BUG_ON(!page_count(page));
2329 spin_unlock(&mm->page_table_lock);
2331 split_huge_page(page);
2334 BUG_ON(pmd_trans_huge(*pmd));
2337 static void split_huge_page_address(struct mm_struct *mm,
2338 unsigned long address)
2342 VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
2344 pmd = mm_find_pmd(mm, address);
2348 * Caller holds the mmap_sem write mode, so a huge pmd cannot
2349 * materialize from under us.
2351 split_huge_page_pmd(mm, pmd);
2354 void __vma_adjust_trans_huge(struct vm_area_struct *vma,
2355 unsigned long start,
2360 * If the new start address isn't hpage aligned and it could
2361 * previously contain an hugepage: check if we need to split
2364 if (start & ~HPAGE_PMD_MASK &&
2365 (start & HPAGE_PMD_MASK) >= vma->vm_start &&
2366 (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2367 split_huge_page_address(vma->vm_mm, start);
2370 * If the new end address isn't hpage aligned and it could
2371 * previously contain an hugepage: check if we need to split
2374 if (end & ~HPAGE_PMD_MASK &&
2375 (end & HPAGE_PMD_MASK) >= vma->vm_start &&
2376 (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2377 split_huge_page_address(vma->vm_mm, end);
2380 * If we're also updating the vma->vm_next->vm_start, if the new
2381 * vm_next->vm_start isn't page aligned and it could previously
2382 * contain an hugepage: check if we need to split an huge pmd.
2384 if (adjust_next > 0) {
2385 struct vm_area_struct *next = vma->vm_next;
2386 unsigned long nstart = next->vm_start;
2387 nstart += adjust_next << PAGE_SHIFT;
2388 if (nstart & ~HPAGE_PMD_MASK &&
2389 (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
2390 (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
2391 split_huge_page_address(next->vm_mm, nstart);