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.
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 #include <linux/sched.h>
12 #include <linux/highmem.h>
13 #include <linux/hugetlb.h>
14 #include <linux/mmu_notifier.h>
15 #include <linux/rmap.h>
16 #include <linux/swap.h>
17 #include <linux/shrinker.h>
18 #include <linux/mm_inline.h>
19 #include <linux/swapops.h>
20 #include <linux/dax.h>
21 #include <linux/kthread.h>
22 #include <linux/khugepaged.h>
23 #include <linux/freezer.h>
24 #include <linux/pfn_t.h>
25 #include <linux/mman.h>
26 #include <linux/memremap.h>
27 #include <linux/pagemap.h>
28 #include <linux/debugfs.h>
29 #include <linux/migrate.h>
30 #include <linux/hashtable.h>
31 #include <linux/userfaultfd_k.h>
32 #include <linux/page_idle.h>
35 #include <asm/pgalloc.h>
45 SCAN_NO_REFERENCED_PAGE,
59 SCAN_ALLOC_HUGE_PAGE_FAIL,
60 SCAN_CGROUP_CHARGE_FAIL
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/huge_memory.h>
67 * By default transparent hugepage support is disabled in order that avoid
68 * to risk increase the memory footprint of applications without a guaranteed
69 * benefit. When transparent hugepage support is enabled, is for all mappings,
70 * and khugepaged scans all mappings.
71 * Defrag is invoked by khugepaged hugepage allocations and by page faults
72 * for all hugepage allocations.
74 unsigned long transparent_hugepage_flags __read_mostly =
75 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
76 (1<<TRANSPARENT_HUGEPAGE_FLAG)|
78 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
79 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
81 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
82 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
83 (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
85 /* default scan 8*512 pte (or vmas) every 30 second */
86 static unsigned int khugepaged_pages_to_scan __read_mostly;
87 static unsigned int khugepaged_pages_collapsed;
88 static unsigned int khugepaged_full_scans;
89 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
90 /* during fragmentation poll the hugepage allocator once every minute */
91 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
92 static struct task_struct *khugepaged_thread __read_mostly;
93 static DEFINE_MUTEX(khugepaged_mutex);
94 static DEFINE_SPINLOCK(khugepaged_mm_lock);
95 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
97 * default collapse hugepages if there is at least one pte mapped like
98 * it would have happened if the vma was large enough during page
101 static unsigned int khugepaged_max_ptes_none __read_mostly;
103 static int khugepaged(void *none);
104 static int khugepaged_slab_init(void);
105 static void khugepaged_slab_exit(void);
107 #define MM_SLOTS_HASH_BITS 10
108 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
110 static struct kmem_cache *mm_slot_cache __read_mostly;
113 * struct mm_slot - hash lookup from mm to mm_slot
114 * @hash: hash collision list
115 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
116 * @mm: the mm that this information is valid for
119 struct hlist_node hash;
120 struct list_head mm_node;
121 struct mm_struct *mm;
125 * struct khugepaged_scan - cursor for scanning
126 * @mm_head: the head of the mm list to scan
127 * @mm_slot: the current mm_slot we are scanning
128 * @address: the next address inside that to be scanned
130 * There is only the one khugepaged_scan instance of this cursor structure.
132 struct khugepaged_scan {
133 struct list_head mm_head;
134 struct mm_slot *mm_slot;
135 unsigned long address;
137 static struct khugepaged_scan khugepaged_scan = {
138 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
141 static struct shrinker deferred_split_shrinker;
143 static void set_recommended_min_free_kbytes(void)
147 unsigned long recommended_min;
149 for_each_populated_zone(zone)
152 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
153 recommended_min = pageblock_nr_pages * nr_zones * 2;
156 * Make sure that on average at least two pageblocks are almost free
157 * of another type, one for a migratetype to fall back to and a
158 * second to avoid subsequent fallbacks of other types There are 3
159 * MIGRATE_TYPES we care about.
161 recommended_min += pageblock_nr_pages * nr_zones *
162 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
164 /* don't ever allow to reserve more than 5% of the lowmem */
165 recommended_min = min(recommended_min,
166 (unsigned long) nr_free_buffer_pages() / 20);
167 recommended_min <<= (PAGE_SHIFT-10);
169 if (recommended_min > min_free_kbytes) {
170 if (user_min_free_kbytes >= 0)
171 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
172 min_free_kbytes, recommended_min);
174 min_free_kbytes = recommended_min;
176 setup_per_zone_wmarks();
179 static int start_stop_khugepaged(void)
182 if (khugepaged_enabled()) {
183 if (!khugepaged_thread)
184 khugepaged_thread = kthread_run(khugepaged, NULL,
186 if (IS_ERR(khugepaged_thread)) {
187 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
188 err = PTR_ERR(khugepaged_thread);
189 khugepaged_thread = NULL;
193 if (!list_empty(&khugepaged_scan.mm_head))
194 wake_up_interruptible(&khugepaged_wait);
196 set_recommended_min_free_kbytes();
197 } else if (khugepaged_thread) {
198 kthread_stop(khugepaged_thread);
199 khugepaged_thread = NULL;
205 static atomic_t huge_zero_refcount;
206 struct page *huge_zero_page __read_mostly;
208 struct page *get_huge_zero_page(void)
210 struct page *zero_page;
212 if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
213 return READ_ONCE(huge_zero_page);
215 zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
218 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
221 count_vm_event(THP_ZERO_PAGE_ALLOC);
223 if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
225 __free_pages(zero_page, compound_order(zero_page));
229 /* We take additional reference here. It will be put back by shrinker */
230 atomic_set(&huge_zero_refcount, 2);
232 return READ_ONCE(huge_zero_page);
235 void put_huge_zero_page(void)
238 * Counter should never go to zero here. Only shrinker can put
241 BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
244 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
245 struct shrink_control *sc)
247 /* we can free zero page only if last reference remains */
248 return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
251 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
252 struct shrink_control *sc)
254 if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
255 struct page *zero_page = xchg(&huge_zero_page, NULL);
256 BUG_ON(zero_page == NULL);
257 __free_pages(zero_page, compound_order(zero_page));
264 static struct shrinker huge_zero_page_shrinker = {
265 .count_objects = shrink_huge_zero_page_count,
266 .scan_objects = shrink_huge_zero_page_scan,
267 .seeks = DEFAULT_SEEKS,
272 static ssize_t triple_flag_store(struct kobject *kobj,
273 struct kobj_attribute *attr,
274 const char *buf, size_t count,
275 enum transparent_hugepage_flag enabled,
276 enum transparent_hugepage_flag deferred,
277 enum transparent_hugepage_flag req_madv)
279 if (!memcmp("defer", buf,
280 min(sizeof("defer")-1, count))) {
281 if (enabled == deferred)
283 clear_bit(enabled, &transparent_hugepage_flags);
284 clear_bit(req_madv, &transparent_hugepage_flags);
285 set_bit(deferred, &transparent_hugepage_flags);
286 } else if (!memcmp("always", buf,
287 min(sizeof("always")-1, count))) {
288 clear_bit(deferred, &transparent_hugepage_flags);
289 clear_bit(req_madv, &transparent_hugepage_flags);
290 set_bit(enabled, &transparent_hugepage_flags);
291 } else if (!memcmp("madvise", buf,
292 min(sizeof("madvise")-1, count))) {
293 clear_bit(enabled, &transparent_hugepage_flags);
294 clear_bit(deferred, &transparent_hugepage_flags);
295 set_bit(req_madv, &transparent_hugepage_flags);
296 } else if (!memcmp("never", buf,
297 min(sizeof("never")-1, count))) {
298 clear_bit(enabled, &transparent_hugepage_flags);
299 clear_bit(req_madv, &transparent_hugepage_flags);
300 clear_bit(deferred, &transparent_hugepage_flags);
307 static ssize_t enabled_show(struct kobject *kobj,
308 struct kobj_attribute *attr, char *buf)
310 if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
311 return sprintf(buf, "[always] madvise never\n");
312 else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags))
313 return sprintf(buf, "always [madvise] never\n");
315 return sprintf(buf, "always madvise [never]\n");
318 static ssize_t enabled_store(struct kobject *kobj,
319 struct kobj_attribute *attr,
320 const char *buf, size_t count)
324 ret = triple_flag_store(kobj, attr, buf, count,
325 TRANSPARENT_HUGEPAGE_FLAG,
326 TRANSPARENT_HUGEPAGE_FLAG,
327 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
332 mutex_lock(&khugepaged_mutex);
333 err = start_stop_khugepaged();
334 mutex_unlock(&khugepaged_mutex);
342 static struct kobj_attribute enabled_attr =
343 __ATTR(enabled, 0644, enabled_show, enabled_store);
345 static ssize_t single_flag_show(struct kobject *kobj,
346 struct kobj_attribute *attr, char *buf,
347 enum transparent_hugepage_flag flag)
349 return sprintf(buf, "%d\n",
350 !!test_bit(flag, &transparent_hugepage_flags));
353 static ssize_t single_flag_store(struct kobject *kobj,
354 struct kobj_attribute *attr,
355 const char *buf, size_t count,
356 enum transparent_hugepage_flag flag)
361 ret = kstrtoul(buf, 10, &value);
368 set_bit(flag, &transparent_hugepage_flags);
370 clear_bit(flag, &transparent_hugepage_flags);
376 * Currently defrag only disables __GFP_NOWAIT for allocation. A blind
377 * __GFP_REPEAT is too aggressive, it's never worth swapping tons of
378 * memory just to allocate one more hugepage.
380 static ssize_t defrag_show(struct kobject *kobj,
381 struct kobj_attribute *attr, char *buf)
383 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
384 return sprintf(buf, "[always] defer madvise never\n");
385 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
386 return sprintf(buf, "always [defer] madvise never\n");
387 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
388 return sprintf(buf, "always defer [madvise] never\n");
390 return sprintf(buf, "always defer madvise [never]\n");
393 static ssize_t defrag_store(struct kobject *kobj,
394 struct kobj_attribute *attr,
395 const char *buf, size_t count)
397 return triple_flag_store(kobj, attr, buf, count,
398 TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
399 TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
400 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
402 static struct kobj_attribute defrag_attr =
403 __ATTR(defrag, 0644, defrag_show, defrag_store);
405 static ssize_t use_zero_page_show(struct kobject *kobj,
406 struct kobj_attribute *attr, char *buf)
408 return single_flag_show(kobj, attr, buf,
409 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
411 static ssize_t use_zero_page_store(struct kobject *kobj,
412 struct kobj_attribute *attr, const char *buf, size_t count)
414 return single_flag_store(kobj, attr, buf, count,
415 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
417 static struct kobj_attribute use_zero_page_attr =
418 __ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
419 #ifdef CONFIG_DEBUG_VM
420 static ssize_t debug_cow_show(struct kobject *kobj,
421 struct kobj_attribute *attr, char *buf)
423 return single_flag_show(kobj, attr, buf,
424 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
426 static ssize_t debug_cow_store(struct kobject *kobj,
427 struct kobj_attribute *attr,
428 const char *buf, size_t count)
430 return single_flag_store(kobj, attr, buf, count,
431 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
433 static struct kobj_attribute debug_cow_attr =
434 __ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
435 #endif /* CONFIG_DEBUG_VM */
437 static struct attribute *hugepage_attr[] = {
440 &use_zero_page_attr.attr,
441 #ifdef CONFIG_DEBUG_VM
442 &debug_cow_attr.attr,
447 static struct attribute_group hugepage_attr_group = {
448 .attrs = hugepage_attr,
451 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
452 struct kobj_attribute *attr,
455 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
458 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
459 struct kobj_attribute *attr,
460 const char *buf, size_t count)
465 err = kstrtoul(buf, 10, &msecs);
466 if (err || msecs > UINT_MAX)
469 khugepaged_scan_sleep_millisecs = msecs;
470 wake_up_interruptible(&khugepaged_wait);
474 static struct kobj_attribute scan_sleep_millisecs_attr =
475 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
476 scan_sleep_millisecs_store);
478 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
479 struct kobj_attribute *attr,
482 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
485 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
486 struct kobj_attribute *attr,
487 const char *buf, size_t count)
492 err = kstrtoul(buf, 10, &msecs);
493 if (err || msecs > UINT_MAX)
496 khugepaged_alloc_sleep_millisecs = msecs;
497 wake_up_interruptible(&khugepaged_wait);
501 static struct kobj_attribute alloc_sleep_millisecs_attr =
502 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
503 alloc_sleep_millisecs_store);
505 static ssize_t pages_to_scan_show(struct kobject *kobj,
506 struct kobj_attribute *attr,
509 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
511 static ssize_t pages_to_scan_store(struct kobject *kobj,
512 struct kobj_attribute *attr,
513 const char *buf, size_t count)
518 err = kstrtoul(buf, 10, &pages);
519 if (err || !pages || pages > UINT_MAX)
522 khugepaged_pages_to_scan = pages;
526 static struct kobj_attribute pages_to_scan_attr =
527 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
528 pages_to_scan_store);
530 static ssize_t pages_collapsed_show(struct kobject *kobj,
531 struct kobj_attribute *attr,
534 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
536 static struct kobj_attribute pages_collapsed_attr =
537 __ATTR_RO(pages_collapsed);
539 static ssize_t full_scans_show(struct kobject *kobj,
540 struct kobj_attribute *attr,
543 return sprintf(buf, "%u\n", khugepaged_full_scans);
545 static struct kobj_attribute full_scans_attr =
546 __ATTR_RO(full_scans);
548 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
549 struct kobj_attribute *attr, char *buf)
551 return single_flag_show(kobj, attr, buf,
552 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
554 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
555 struct kobj_attribute *attr,
556 const char *buf, size_t count)
558 return single_flag_store(kobj, attr, buf, count,
559 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
561 static struct kobj_attribute khugepaged_defrag_attr =
562 __ATTR(defrag, 0644, khugepaged_defrag_show,
563 khugepaged_defrag_store);
566 * max_ptes_none controls if khugepaged should collapse hugepages over
567 * any unmapped ptes in turn potentially increasing the memory
568 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
569 * reduce the available free memory in the system as it
570 * runs. Increasing max_ptes_none will instead potentially reduce the
571 * free memory in the system during the khugepaged scan.
573 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
574 struct kobj_attribute *attr,
577 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
579 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
580 struct kobj_attribute *attr,
581 const char *buf, size_t count)
584 unsigned long max_ptes_none;
586 err = kstrtoul(buf, 10, &max_ptes_none);
587 if (err || max_ptes_none > HPAGE_PMD_NR-1)
590 khugepaged_max_ptes_none = max_ptes_none;
594 static struct kobj_attribute khugepaged_max_ptes_none_attr =
595 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
596 khugepaged_max_ptes_none_store);
598 static struct attribute *khugepaged_attr[] = {
599 &khugepaged_defrag_attr.attr,
600 &khugepaged_max_ptes_none_attr.attr,
601 &pages_to_scan_attr.attr,
602 &pages_collapsed_attr.attr,
603 &full_scans_attr.attr,
604 &scan_sleep_millisecs_attr.attr,
605 &alloc_sleep_millisecs_attr.attr,
609 static struct attribute_group khugepaged_attr_group = {
610 .attrs = khugepaged_attr,
611 .name = "khugepaged",
614 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
618 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
619 if (unlikely(!*hugepage_kobj)) {
620 pr_err("failed to create transparent hugepage kobject\n");
624 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
626 pr_err("failed to register transparent hugepage group\n");
630 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
632 pr_err("failed to register transparent hugepage group\n");
633 goto remove_hp_group;
639 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
641 kobject_put(*hugepage_kobj);
645 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
647 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
648 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
649 kobject_put(hugepage_kobj);
652 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
657 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
660 #endif /* CONFIG_SYSFS */
662 static int __init hugepage_init(void)
665 struct kobject *hugepage_kobj;
667 if (!has_transparent_hugepage()) {
668 transparent_hugepage_flags = 0;
672 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
673 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
675 * hugepages can't be allocated by the buddy allocator
677 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER >= MAX_ORDER);
679 * we use page->mapping and page->index in second tail page
680 * as list_head: assuming THP order >= 2
682 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER < 2);
684 err = hugepage_init_sysfs(&hugepage_kobj);
688 err = khugepaged_slab_init();
692 err = register_shrinker(&huge_zero_page_shrinker);
694 goto err_hzp_shrinker;
695 err = register_shrinker(&deferred_split_shrinker);
697 goto err_split_shrinker;
700 * By default disable transparent hugepages on smaller systems,
701 * where the extra memory used could hurt more than TLB overhead
702 * is likely to save. The admin can still enable it through /sys.
704 if (totalram_pages < (512 << (20 - PAGE_SHIFT))) {
705 transparent_hugepage_flags = 0;
709 err = start_stop_khugepaged();
715 unregister_shrinker(&deferred_split_shrinker);
717 unregister_shrinker(&huge_zero_page_shrinker);
719 khugepaged_slab_exit();
721 hugepage_exit_sysfs(hugepage_kobj);
725 subsys_initcall(hugepage_init);
727 static int __init setup_transparent_hugepage(char *str)
732 if (!strcmp(str, "always")) {
733 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
734 &transparent_hugepage_flags);
735 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
736 &transparent_hugepage_flags);
738 } else if (!strcmp(str, "madvise")) {
739 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
740 &transparent_hugepage_flags);
741 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
742 &transparent_hugepage_flags);
744 } else if (!strcmp(str, "never")) {
745 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
746 &transparent_hugepage_flags);
747 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
748 &transparent_hugepage_flags);
753 pr_warn("transparent_hugepage= cannot parse, ignored\n");
756 __setup("transparent_hugepage=", setup_transparent_hugepage);
758 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
760 if (likely(vma->vm_flags & VM_WRITE))
761 pmd = pmd_mkwrite(pmd);
765 static inline pmd_t mk_huge_pmd(struct page *page, pgprot_t prot)
767 return pmd_mkhuge(mk_pmd(page, prot));
770 static inline struct list_head *page_deferred_list(struct page *page)
773 * ->lru in the tail pages is occupied by compound_head.
774 * Let's use ->mapping + ->index in the second tail page as list_head.
776 return (struct list_head *)&page[2].mapping;
779 void prep_transhuge_page(struct page *page)
782 * we use page->mapping and page->indexlru in second tail page
783 * as list_head: assuming THP order >= 2
786 INIT_LIST_HEAD(page_deferred_list(page));
787 set_compound_page_dtor(page, TRANSHUGE_PAGE_DTOR);
790 static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
791 struct vm_area_struct *vma,
792 unsigned long address, pmd_t *pmd,
793 struct page *page, gfp_t gfp,
796 struct mem_cgroup *memcg;
799 unsigned long haddr = address & HPAGE_PMD_MASK;
801 VM_BUG_ON_PAGE(!PageCompound(page), page);
803 if (mem_cgroup_try_charge(page, mm, gfp, &memcg, true)) {
805 count_vm_event(THP_FAULT_FALLBACK);
806 return VM_FAULT_FALLBACK;
809 pgtable = pte_alloc_one(mm, haddr);
810 if (unlikely(!pgtable)) {
811 mem_cgroup_cancel_charge(page, memcg, true);
816 clear_huge_page(page, haddr, HPAGE_PMD_NR);
818 * The memory barrier inside __SetPageUptodate makes sure that
819 * clear_huge_page writes become visible before the set_pmd_at()
822 __SetPageUptodate(page);
824 ptl = pmd_lock(mm, pmd);
825 if (unlikely(!pmd_none(*pmd))) {
827 mem_cgroup_cancel_charge(page, memcg, true);
829 pte_free(mm, pgtable);
833 /* Deliver the page fault to userland */
834 if (userfaultfd_missing(vma)) {
838 mem_cgroup_cancel_charge(page, memcg, true);
840 pte_free(mm, pgtable);
841 ret = handle_userfault(vma, address, flags,
843 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
847 entry = mk_huge_pmd(page, vma->vm_page_prot);
848 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
849 page_add_new_anon_rmap(page, vma, haddr, true);
850 mem_cgroup_commit_charge(page, memcg, false, true);
851 lru_cache_add_active_or_unevictable(page, vma);
852 pgtable_trans_huge_deposit(mm, pmd, pgtable);
853 set_pmd_at(mm, haddr, pmd, entry);
854 add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
855 atomic_long_inc(&mm->nr_ptes);
857 count_vm_event(THP_FAULT_ALLOC);
864 * If THP is set to always then directly reclaim/compact as necessary
865 * If set to defer then do no reclaim and defer to khugepaged
866 * If set to madvise and the VMA is flagged then directly reclaim/compact
868 static inline gfp_t alloc_hugepage_direct_gfpmask(struct vm_area_struct *vma)
870 gfp_t reclaim_flags = 0;
872 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags) &&
873 (vma->vm_flags & VM_HUGEPAGE))
874 reclaim_flags = __GFP_DIRECT_RECLAIM;
875 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
876 reclaim_flags = __GFP_KSWAPD_RECLAIM;
877 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
878 reclaim_flags = __GFP_DIRECT_RECLAIM;
880 return GFP_TRANSHUGE | reclaim_flags;
883 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
884 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
886 return GFP_TRANSHUGE | (khugepaged_defrag() ? __GFP_DIRECT_RECLAIM : 0);
889 /* Caller must hold page table lock. */
890 static bool set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
891 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
892 struct page *zero_page)
897 entry = mk_pmd(zero_page, vma->vm_page_prot);
898 entry = pmd_mkhuge(entry);
900 pgtable_trans_huge_deposit(mm, pmd, pgtable);
901 set_pmd_at(mm, haddr, pmd, entry);
902 atomic_long_inc(&mm->nr_ptes);
906 int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
907 unsigned long address, pmd_t *pmd,
912 unsigned long haddr = address & HPAGE_PMD_MASK;
914 if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
915 return VM_FAULT_FALLBACK;
916 if (unlikely(anon_vma_prepare(vma)))
918 if (unlikely(khugepaged_enter(vma, vma->vm_flags)))
920 if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm) &&
921 transparent_hugepage_use_zero_page()) {
924 struct page *zero_page;
927 pgtable = pte_alloc_one(mm, haddr);
928 if (unlikely(!pgtable))
930 zero_page = get_huge_zero_page();
931 if (unlikely(!zero_page)) {
932 pte_free(mm, pgtable);
933 count_vm_event(THP_FAULT_FALLBACK);
934 return VM_FAULT_FALLBACK;
936 ptl = pmd_lock(mm, pmd);
939 if (pmd_none(*pmd)) {
940 if (userfaultfd_missing(vma)) {
942 ret = handle_userfault(vma, address, flags,
944 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
946 set_huge_zero_page(pgtable, mm, vma,
955 pte_free(mm, pgtable);
956 put_huge_zero_page();
960 gfp = alloc_hugepage_direct_gfpmask(vma);
961 page = alloc_hugepage_vma(gfp, vma, haddr, HPAGE_PMD_ORDER);
962 if (unlikely(!page)) {
963 count_vm_event(THP_FAULT_FALLBACK);
964 return VM_FAULT_FALLBACK;
966 prep_transhuge_page(page);
967 return __do_huge_pmd_anonymous_page(mm, vma, address, pmd, page, gfp,
971 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
972 pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write)
974 struct mm_struct *mm = vma->vm_mm;
978 ptl = pmd_lock(mm, pmd);
979 entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
980 if (pfn_t_devmap(pfn))
981 entry = pmd_mkdevmap(entry);
983 entry = pmd_mkyoung(pmd_mkdirty(entry));
984 entry = maybe_pmd_mkwrite(entry, vma);
986 set_pmd_at(mm, addr, pmd, entry);
987 update_mmu_cache_pmd(vma, addr, pmd);
991 int vmf_insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
992 pmd_t *pmd, pfn_t pfn, bool write)
994 pgprot_t pgprot = vma->vm_page_prot;
996 * If we had pmd_special, we could avoid all these restrictions,
997 * but we need to be consistent with PTEs and architectures that
998 * can't support a 'special' bit.
1000 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1001 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1002 (VM_PFNMAP|VM_MIXEDMAP));
1003 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1004 BUG_ON(!pfn_t_devmap(pfn));
1006 if (addr < vma->vm_start || addr >= vma->vm_end)
1007 return VM_FAULT_SIGBUS;
1008 if (track_pfn_insert(vma, &pgprot, pfn))
1009 return VM_FAULT_SIGBUS;
1010 insert_pfn_pmd(vma, addr, pmd, pfn, pgprot, write);
1011 return VM_FAULT_NOPAGE;
1014 static void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
1020 * We should set the dirty bit only for FOLL_WRITE but for now
1021 * the dirty bit in the pmd is meaningless. And if the dirty
1022 * bit will become meaningful and we'll only set it with
1023 * FOLL_WRITE, an atomic set_bit will be required on the pmd to
1024 * set the young bit, instead of the current set_pmd_at.
1026 _pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
1027 if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1029 update_mmu_cache_pmd(vma, addr, pmd);
1032 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
1033 pmd_t *pmd, int flags)
1035 unsigned long pfn = pmd_pfn(*pmd);
1036 struct mm_struct *mm = vma->vm_mm;
1037 struct dev_pagemap *pgmap;
1040 assert_spin_locked(pmd_lockptr(mm, pmd));
1042 if (flags & FOLL_WRITE && !pmd_write(*pmd))
1045 if (pmd_present(*pmd) && pmd_devmap(*pmd))
1050 if (flags & FOLL_TOUCH)
1051 touch_pmd(vma, addr, pmd);
1054 * device mapped pages can only be returned if the
1055 * caller will manage the page reference count.
1057 if (!(flags & FOLL_GET))
1058 return ERR_PTR(-EEXIST);
1060 pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1061 pgmap = get_dev_pagemap(pfn, NULL);
1063 return ERR_PTR(-EFAULT);
1064 page = pfn_to_page(pfn);
1066 put_dev_pagemap(pgmap);
1071 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1072 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1073 struct vm_area_struct *vma)
1075 spinlock_t *dst_ptl, *src_ptl;
1076 struct page *src_page;
1078 pgtable_t pgtable = NULL;
1081 if (!vma_is_dax(vma)) {
1083 pgtable = pte_alloc_one(dst_mm, addr);
1084 if (unlikely(!pgtable))
1088 dst_ptl = pmd_lock(dst_mm, dst_pmd);
1089 src_ptl = pmd_lockptr(src_mm, src_pmd);
1090 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1094 if (unlikely(!pmd_trans_huge(pmd) && !pmd_devmap(pmd))) {
1095 pte_free(dst_mm, pgtable);
1099 * When page table lock is held, the huge zero pmd should not be
1100 * under splitting since we don't split the page itself, only pmd to
1103 if (is_huge_zero_pmd(pmd)) {
1104 struct page *zero_page;
1106 * get_huge_zero_page() will never allocate a new page here,
1107 * since we already have a zero page to copy. It just takes a
1110 zero_page = get_huge_zero_page();
1111 set_huge_zero_page(pgtable, dst_mm, vma, addr, dst_pmd,
1117 if (!vma_is_dax(vma)) {
1118 /* thp accounting separate from pmd_devmap accounting */
1119 src_page = pmd_page(pmd);
1120 VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1122 page_dup_rmap(src_page, true);
1123 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1124 atomic_long_inc(&dst_mm->nr_ptes);
1125 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1128 pmdp_set_wrprotect(src_mm, addr, src_pmd);
1129 pmd = pmd_mkold(pmd_wrprotect(pmd));
1130 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1134 spin_unlock(src_ptl);
1135 spin_unlock(dst_ptl);
1140 void huge_pmd_set_accessed(struct mm_struct *mm,
1141 struct vm_area_struct *vma,
1142 unsigned long address,
1143 pmd_t *pmd, pmd_t orig_pmd,
1148 unsigned long haddr;
1150 ptl = pmd_lock(mm, pmd);
1151 if (unlikely(!pmd_same(*pmd, orig_pmd)))
1154 entry = pmd_mkyoung(orig_pmd);
1155 haddr = address & HPAGE_PMD_MASK;
1156 if (pmdp_set_access_flags(vma, haddr, pmd, entry, dirty))
1157 update_mmu_cache_pmd(vma, address, pmd);
1163 static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
1164 struct vm_area_struct *vma,
1165 unsigned long address,
1166 pmd_t *pmd, pmd_t orig_pmd,
1168 unsigned long haddr)
1170 struct mem_cgroup *memcg;
1175 struct page **pages;
1176 unsigned long mmun_start; /* For mmu_notifiers */
1177 unsigned long mmun_end; /* For mmu_notifiers */
1179 pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
1181 if (unlikely(!pages)) {
1182 ret |= VM_FAULT_OOM;
1186 for (i = 0; i < HPAGE_PMD_NR; i++) {
1187 pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
1189 vma, address, page_to_nid(page));
1190 if (unlikely(!pages[i] ||
1191 mem_cgroup_try_charge(pages[i], mm, GFP_KERNEL,
1196 memcg = (void *)page_private(pages[i]);
1197 set_page_private(pages[i], 0);
1198 mem_cgroup_cancel_charge(pages[i], memcg,
1203 ret |= VM_FAULT_OOM;
1206 set_page_private(pages[i], (unsigned long)memcg);
1209 for (i = 0; i < HPAGE_PMD_NR; i++) {
1210 copy_user_highpage(pages[i], page + i,
1211 haddr + PAGE_SIZE * i, vma);
1212 __SetPageUptodate(pages[i]);
1217 mmun_end = haddr + HPAGE_PMD_SIZE;
1218 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1220 ptl = pmd_lock(mm, pmd);
1221 if (unlikely(!pmd_same(*pmd, orig_pmd)))
1222 goto out_free_pages;
1223 VM_BUG_ON_PAGE(!PageHead(page), page);
1225 pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1226 /* leave pmd empty until pte is filled */
1228 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1229 pmd_populate(mm, &_pmd, pgtable);
1231 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1233 entry = mk_pte(pages[i], vma->vm_page_prot);
1234 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1235 memcg = (void *)page_private(pages[i]);
1236 set_page_private(pages[i], 0);
1237 page_add_new_anon_rmap(pages[i], vma, haddr, false);
1238 mem_cgroup_commit_charge(pages[i], memcg, false, false);
1239 lru_cache_add_active_or_unevictable(pages[i], vma);
1240 pte = pte_offset_map(&_pmd, haddr);
1241 VM_BUG_ON(!pte_none(*pte));
1242 set_pte_at(mm, haddr, pte, entry);
1247 smp_wmb(); /* make pte visible before pmd */
1248 pmd_populate(mm, pmd, pgtable);
1249 page_remove_rmap(page, true);
1252 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1254 ret |= VM_FAULT_WRITE;
1262 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1263 for (i = 0; i < HPAGE_PMD_NR; i++) {
1264 memcg = (void *)page_private(pages[i]);
1265 set_page_private(pages[i], 0);
1266 mem_cgroup_cancel_charge(pages[i], memcg, false);
1273 int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
1274 unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
1278 struct page *page = NULL, *new_page;
1279 struct mem_cgroup *memcg;
1280 unsigned long haddr;
1281 unsigned long mmun_start; /* For mmu_notifiers */
1282 unsigned long mmun_end; /* For mmu_notifiers */
1283 gfp_t huge_gfp; /* for allocation and charge */
1285 ptl = pmd_lockptr(mm, pmd);
1286 VM_BUG_ON_VMA(!vma->anon_vma, vma);
1287 haddr = address & HPAGE_PMD_MASK;
1288 if (is_huge_zero_pmd(orig_pmd))
1291 if (unlikely(!pmd_same(*pmd, orig_pmd)))
1294 page = pmd_page(orig_pmd);
1295 VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
1297 * We can only reuse the page if nobody else maps the huge page or it's
1300 if (page_trans_huge_mapcount(page, NULL) == 1) {
1302 entry = pmd_mkyoung(orig_pmd);
1303 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1304 if (pmdp_set_access_flags(vma, haddr, pmd, entry, 1))
1305 update_mmu_cache_pmd(vma, address, pmd);
1306 ret |= VM_FAULT_WRITE;
1312 if (transparent_hugepage_enabled(vma) &&
1313 !transparent_hugepage_debug_cow()) {
1314 huge_gfp = alloc_hugepage_direct_gfpmask(vma);
1315 new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
1319 if (likely(new_page)) {
1320 prep_transhuge_page(new_page);
1323 split_huge_pmd(vma, pmd, address);
1324 ret |= VM_FAULT_FALLBACK;
1326 ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
1327 pmd, orig_pmd, page, haddr);
1328 if (ret & VM_FAULT_OOM) {
1329 split_huge_pmd(vma, pmd, address);
1330 ret |= VM_FAULT_FALLBACK;
1334 count_vm_event(THP_FAULT_FALLBACK);
1338 if (unlikely(mem_cgroup_try_charge(new_page, mm, huge_gfp, &memcg,
1342 split_huge_pmd(vma, pmd, address);
1345 split_huge_pmd(vma, pmd, address);
1346 ret |= VM_FAULT_FALLBACK;
1347 count_vm_event(THP_FAULT_FALLBACK);
1351 count_vm_event(THP_FAULT_ALLOC);
1354 clear_huge_page(new_page, haddr, HPAGE_PMD_NR);
1356 copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
1357 __SetPageUptodate(new_page);
1360 mmun_end = haddr + HPAGE_PMD_SIZE;
1361 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1366 if (unlikely(!pmd_same(*pmd, orig_pmd))) {
1368 mem_cgroup_cancel_charge(new_page, memcg, true);
1373 entry = mk_huge_pmd(new_page, vma->vm_page_prot);
1374 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1375 pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1376 page_add_new_anon_rmap(new_page, vma, haddr, true);
1377 mem_cgroup_commit_charge(new_page, memcg, false, true);
1378 lru_cache_add_active_or_unevictable(new_page, vma);
1379 set_pmd_at(mm, haddr, pmd, entry);
1380 update_mmu_cache_pmd(vma, address, pmd);
1382 add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
1383 put_huge_zero_page();
1385 VM_BUG_ON_PAGE(!PageHead(page), page);
1386 page_remove_rmap(page, true);
1389 ret |= VM_FAULT_WRITE;
1393 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1401 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1406 struct mm_struct *mm = vma->vm_mm;
1407 struct page *page = NULL;
1409 assert_spin_locked(pmd_lockptr(mm, pmd));
1411 if (flags & FOLL_WRITE && !pmd_write(*pmd))
1414 /* Avoid dumping huge zero page */
1415 if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1416 return ERR_PTR(-EFAULT);
1418 /* Full NUMA hinting faults to serialise migration in fault paths */
1419 if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
1422 page = pmd_page(*pmd);
1423 VM_BUG_ON_PAGE(!PageHead(page), page);
1424 if (flags & FOLL_TOUCH)
1425 touch_pmd(vma, addr, pmd);
1426 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
1428 * We don't mlock() pte-mapped THPs. This way we can avoid
1429 * leaking mlocked pages into non-VM_LOCKED VMAs.
1431 * In most cases the pmd is the only mapping of the page as we
1432 * break COW for the mlock() -- see gup_flags |= FOLL_WRITE for
1433 * writable private mappings in populate_vma_page_range().
1435 * The only scenario when we have the page shared here is if we
1436 * mlocking read-only mapping shared over fork(). We skip
1437 * mlocking such pages.
1439 if (compound_mapcount(page) == 1 && !PageDoubleMap(page) &&
1440 page->mapping && trylock_page(page)) {
1443 mlock_vma_page(page);
1447 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1448 VM_BUG_ON_PAGE(!PageCompound(page), page);
1449 if (flags & FOLL_GET)
1456 /* NUMA hinting page fault entry point for trans huge pmds */
1457 int do_huge_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
1458 unsigned long addr, pmd_t pmd, pmd_t *pmdp)
1461 struct anon_vma *anon_vma = NULL;
1463 unsigned long haddr = addr & HPAGE_PMD_MASK;
1464 int page_nid = -1, this_nid = numa_node_id();
1465 int target_nid, last_cpupid = -1;
1467 bool migrated = false;
1471 /* A PROT_NONE fault should not end up here */
1472 BUG_ON(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)));
1474 ptl = pmd_lock(mm, pmdp);
1475 if (unlikely(!pmd_same(pmd, *pmdp)))
1479 * If there are potential migrations, wait for completion and retry
1480 * without disrupting NUMA hinting information. Do not relock and
1481 * check_same as the page may no longer be mapped.
1483 if (unlikely(pmd_trans_migrating(*pmdp))) {
1484 page = pmd_page(*pmdp);
1486 wait_on_page_locked(page);
1490 page = pmd_page(pmd);
1491 BUG_ON(is_huge_zero_page(page));
1492 page_nid = page_to_nid(page);
1493 last_cpupid = page_cpupid_last(page);
1494 count_vm_numa_event(NUMA_HINT_FAULTS);
1495 if (page_nid == this_nid) {
1496 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
1497 flags |= TNF_FAULT_LOCAL;
1500 /* See similar comment in do_numa_page for explanation */
1501 if (!(vma->vm_flags & VM_WRITE))
1502 flags |= TNF_NO_GROUP;
1505 * Acquire the page lock to serialise THP migrations but avoid dropping
1506 * page_table_lock if at all possible
1508 page_locked = trylock_page(page);
1509 target_nid = mpol_misplaced(page, vma, haddr);
1510 if (target_nid == -1) {
1511 /* If the page was locked, there are no parallel migrations */
1516 /* Migration could have started since the pmd_trans_migrating check */
1519 wait_on_page_locked(page);
1525 * Page is misplaced. Page lock serialises migrations. Acquire anon_vma
1526 * to serialises splits
1530 anon_vma = page_lock_anon_vma_read(page);
1532 /* Confirm the PMD did not change while page_table_lock was released */
1534 if (unlikely(!pmd_same(pmd, *pmdp))) {
1541 /* Bail if we fail to protect against THP splits for any reason */
1542 if (unlikely(!anon_vma)) {
1549 * Migrate the THP to the requested node, returns with page unlocked
1550 * and access rights restored.
1553 migrated = migrate_misplaced_transhuge_page(mm, vma,
1554 pmdp, pmd, addr, page, target_nid);
1556 flags |= TNF_MIGRATED;
1557 page_nid = target_nid;
1559 flags |= TNF_MIGRATE_FAIL;
1563 BUG_ON(!PageLocked(page));
1564 was_writable = pmd_write(pmd);
1565 pmd = pmd_modify(pmd, vma->vm_page_prot);
1566 pmd = pmd_mkyoung(pmd);
1568 pmd = pmd_mkwrite(pmd);
1569 set_pmd_at(mm, haddr, pmdp, pmd);
1570 update_mmu_cache_pmd(vma, addr, pmdp);
1577 page_unlock_anon_vma_read(anon_vma);
1580 task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR, flags);
1585 int madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1586 pmd_t *pmd, unsigned long addr, unsigned long next)
1592 struct mm_struct *mm = tlb->mm;
1595 ptl = pmd_trans_huge_lock(pmd, vma);
1600 if (is_huge_zero_pmd(orig_pmd)) {
1605 page = pmd_page(orig_pmd);
1607 * If other processes are mapping this page, we couldn't discard
1608 * the page unless they all do MADV_FREE so let's skip the page.
1610 if (page_mapcount(page) != 1)
1613 if (!trylock_page(page))
1617 * If user want to discard part-pages of THP, split it so MADV_FREE
1618 * will deactivate only them.
1620 if (next - addr != HPAGE_PMD_SIZE) {
1623 if (split_huge_page(page)) {
1634 if (PageDirty(page))
1635 ClearPageDirty(page);
1638 if (PageActive(page))
1639 deactivate_page(page);
1641 if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1642 orig_pmd = pmdp_huge_get_and_clear_full(tlb->mm, addr, pmd,
1644 orig_pmd = pmd_mkold(orig_pmd);
1645 orig_pmd = pmd_mkclean(orig_pmd);
1647 set_pmd_at(mm, addr, pmd, orig_pmd);
1648 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1657 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1658 pmd_t *pmd, unsigned long addr)
1663 ptl = __pmd_trans_huge_lock(pmd, vma);
1667 * For architectures like ppc64 we look at deposited pgtable
1668 * when calling pmdp_huge_get_and_clear. So do the
1669 * pgtable_trans_huge_withdraw after finishing pmdp related
1672 orig_pmd = pmdp_huge_get_and_clear_full(tlb->mm, addr, pmd,
1674 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1675 if (vma_is_dax(vma)) {
1677 if (is_huge_zero_pmd(orig_pmd))
1678 tlb_remove_page(tlb, pmd_page(orig_pmd));
1679 } else if (is_huge_zero_pmd(orig_pmd)) {
1680 pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1681 atomic_long_dec(&tlb->mm->nr_ptes);
1683 tlb_remove_page(tlb, pmd_page(orig_pmd));
1685 struct page *page = pmd_page(orig_pmd);
1686 page_remove_rmap(page, true);
1687 VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1688 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1689 VM_BUG_ON_PAGE(!PageHead(page), page);
1690 pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1691 atomic_long_dec(&tlb->mm->nr_ptes);
1693 tlb_remove_page(tlb, page);
1698 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
1699 unsigned long new_addr, unsigned long old_end,
1700 pmd_t *old_pmd, pmd_t *new_pmd)
1702 spinlock_t *old_ptl, *new_ptl;
1704 struct mm_struct *mm = vma->vm_mm;
1706 if ((old_addr & ~HPAGE_PMD_MASK) ||
1707 (new_addr & ~HPAGE_PMD_MASK) ||
1708 old_end - old_addr < HPAGE_PMD_SIZE)
1712 * The destination pmd shouldn't be established, free_pgtables()
1713 * should have release it.
1715 if (WARN_ON(!pmd_none(*new_pmd))) {
1716 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1721 * We don't have to worry about the ordering of src and dst
1722 * ptlocks because exclusive mmap_sem prevents deadlock.
1724 old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1726 new_ptl = pmd_lockptr(mm, new_pmd);
1727 if (new_ptl != old_ptl)
1728 spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1729 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1730 VM_BUG_ON(!pmd_none(*new_pmd));
1732 if (pmd_move_must_withdraw(new_ptl, old_ptl) &&
1733 vma_is_anonymous(vma)) {
1735 pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1736 pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1738 set_pmd_at(mm, new_addr, new_pmd, pmd_mksoft_dirty(pmd));
1739 if (new_ptl != old_ptl)
1740 spin_unlock(new_ptl);
1741 spin_unlock(old_ptl);
1749 * - 0 if PMD could not be locked
1750 * - 1 if PMD was locked but protections unchange and TLB flush unnecessary
1751 * - HPAGE_PMD_NR is protections changed and TLB flush necessary
1753 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1754 unsigned long addr, pgprot_t newprot, int prot_numa)
1756 struct mm_struct *mm = vma->vm_mm;
1760 ptl = __pmd_trans_huge_lock(pmd, vma);
1763 bool preserve_write = prot_numa && pmd_write(*pmd);
1767 * Avoid trapping faults against the zero page. The read-only
1768 * data is likely to be read-cached on the local CPU and
1769 * local/remote hits to the zero page are not interesting.
1771 if (prot_numa && is_huge_zero_pmd(*pmd)) {
1776 if (!prot_numa || !pmd_protnone(*pmd)) {
1777 entry = pmdp_huge_get_and_clear_notify(mm, addr, pmd);
1778 entry = pmd_modify(entry, newprot);
1780 entry = pmd_mkwrite(entry);
1782 set_pmd_at(mm, addr, pmd, entry);
1783 BUG_ON(!preserve_write && pmd_write(entry));
1792 * Returns true if a given pmd maps a thp, false otherwise.
1794 * Note that if it returns true, this routine returns without unlocking page
1795 * table lock. So callers must unlock it.
1797 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1800 ptl = pmd_lock(vma->vm_mm, pmd);
1801 if (likely(pmd_trans_huge(*pmd) || pmd_devmap(*pmd)))
1807 #define VM_NO_THP (VM_SPECIAL | VM_HUGETLB | VM_SHARED | VM_MAYSHARE)
1809 int hugepage_madvise(struct vm_area_struct *vma,
1810 unsigned long *vm_flags, int advice)
1816 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
1817 * can't handle this properly after s390_enable_sie, so we simply
1818 * ignore the madvise to prevent qemu from causing a SIGSEGV.
1820 if (mm_has_pgste(vma->vm_mm))
1824 * Be somewhat over-protective like KSM for now!
1826 if (*vm_flags & VM_NO_THP)
1828 *vm_flags &= ~VM_NOHUGEPAGE;
1829 *vm_flags |= VM_HUGEPAGE;
1831 * If the vma become good for khugepaged to scan,
1832 * register it here without waiting a page fault that
1833 * may not happen any time soon.
1835 if (unlikely(khugepaged_enter_vma_merge(vma, *vm_flags)))
1838 case MADV_NOHUGEPAGE:
1840 * Be somewhat over-protective like KSM for now!
1842 if (*vm_flags & VM_NO_THP)
1844 *vm_flags &= ~VM_HUGEPAGE;
1845 *vm_flags |= VM_NOHUGEPAGE;
1847 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1848 * this vma even if we leave the mm registered in khugepaged if
1849 * it got registered before VM_NOHUGEPAGE was set.
1857 static int __init khugepaged_slab_init(void)
1859 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1860 sizeof(struct mm_slot),
1861 __alignof__(struct mm_slot), 0, NULL);
1868 static void __init khugepaged_slab_exit(void)
1870 kmem_cache_destroy(mm_slot_cache);
1873 static inline struct mm_slot *alloc_mm_slot(void)
1875 if (!mm_slot_cache) /* initialization failed */
1877 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1880 static inline void free_mm_slot(struct mm_slot *mm_slot)
1882 kmem_cache_free(mm_slot_cache, mm_slot);
1885 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1887 struct mm_slot *mm_slot;
1889 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
1890 if (mm == mm_slot->mm)
1896 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1897 struct mm_slot *mm_slot)
1900 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
1903 static inline int khugepaged_test_exit(struct mm_struct *mm)
1905 return atomic_read(&mm->mm_users) == 0;
1908 int __khugepaged_enter(struct mm_struct *mm)
1910 struct mm_slot *mm_slot;
1913 mm_slot = alloc_mm_slot();
1917 /* __khugepaged_exit() must not run from under us */
1918 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
1919 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1920 free_mm_slot(mm_slot);
1924 spin_lock(&khugepaged_mm_lock);
1925 insert_to_mm_slots_hash(mm, mm_slot);
1927 * Insert just behind the scanning cursor, to let the area settle
1930 wakeup = list_empty(&khugepaged_scan.mm_head);
1931 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1932 spin_unlock(&khugepaged_mm_lock);
1934 atomic_inc(&mm->mm_count);
1936 wake_up_interruptible(&khugepaged_wait);
1941 int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
1942 unsigned long vm_flags)
1944 unsigned long hstart, hend;
1947 * Not yet faulted in so we will register later in the
1948 * page fault if needed.
1951 if (vma->vm_ops || (vm_flags & VM_NO_THP))
1952 /* khugepaged not yet working on file or special mappings */
1954 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1955 hend = vma->vm_end & HPAGE_PMD_MASK;
1957 return khugepaged_enter(vma, vm_flags);
1961 void __khugepaged_exit(struct mm_struct *mm)
1963 struct mm_slot *mm_slot;
1966 spin_lock(&khugepaged_mm_lock);
1967 mm_slot = get_mm_slot(mm);
1968 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1969 hash_del(&mm_slot->hash);
1970 list_del(&mm_slot->mm_node);
1973 spin_unlock(&khugepaged_mm_lock);
1976 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1977 free_mm_slot(mm_slot);
1979 } else if (mm_slot) {
1981 * This is required to serialize against
1982 * khugepaged_test_exit() (which is guaranteed to run
1983 * under mmap sem read mode). Stop here (after we
1984 * return all pagetables will be destroyed) until
1985 * khugepaged has finished working on the pagetables
1986 * under the mmap_sem.
1988 down_write(&mm->mmap_sem);
1989 up_write(&mm->mmap_sem);
1993 static void release_pte_page(struct page *page)
1995 /* 0 stands for page_is_file_cache(page) == false */
1996 dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1998 putback_lru_page(page);
2001 static void release_pte_pages(pte_t *pte, pte_t *_pte)
2003 while (--_pte >= pte) {
2004 pte_t pteval = *_pte;
2005 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
2006 release_pte_page(pte_page(pteval));
2010 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
2011 unsigned long address,
2014 struct page *page = NULL;
2016 int none_or_zero = 0, result = 0;
2017 bool referenced = false, writable = false;
2019 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
2020 _pte++, address += PAGE_SIZE) {
2021 pte_t pteval = *_pte;
2022 if (pte_none(pteval) || (pte_present(pteval) &&
2023 is_zero_pfn(pte_pfn(pteval)))) {
2024 if (!userfaultfd_armed(vma) &&
2025 ++none_or_zero <= khugepaged_max_ptes_none) {
2028 result = SCAN_EXCEED_NONE_PTE;
2032 if (!pte_present(pteval)) {
2033 result = SCAN_PTE_NON_PRESENT;
2036 page = vm_normal_page(vma, address, pteval);
2037 if (unlikely(!page)) {
2038 result = SCAN_PAGE_NULL;
2042 VM_BUG_ON_PAGE(PageCompound(page), page);
2043 VM_BUG_ON_PAGE(!PageAnon(page), page);
2044 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
2047 * We can do it before isolate_lru_page because the
2048 * page can't be freed from under us. NOTE: PG_lock
2049 * is needed to serialize against split_huge_page
2050 * when invoked from the VM.
2052 if (!trylock_page(page)) {
2053 result = SCAN_PAGE_LOCK;
2058 * cannot use mapcount: can't collapse if there's a gup pin.
2059 * The page must only be referenced by the scanned process
2060 * and page swap cache.
2062 if (page_count(page) != 1 + !!PageSwapCache(page)) {
2064 result = SCAN_PAGE_COUNT;
2067 if (pte_write(pteval)) {
2070 if (PageSwapCache(page) &&
2071 !reuse_swap_page(page, NULL)) {
2073 result = SCAN_SWAP_CACHE_PAGE;
2077 * Page is not in the swap cache. It can be collapsed
2083 * Isolate the page to avoid collapsing an hugepage
2084 * currently in use by the VM.
2086 if (isolate_lru_page(page)) {
2088 result = SCAN_DEL_PAGE_LRU;
2091 /* 0 stands for page_is_file_cache(page) == false */
2092 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
2093 VM_BUG_ON_PAGE(!PageLocked(page), page);
2094 VM_BUG_ON_PAGE(PageLRU(page), page);
2096 /* If there is no mapped pte young don't collapse the page */
2097 if (pte_young(pteval) ||
2098 page_is_young(page) || PageReferenced(page) ||
2099 mmu_notifier_test_young(vma->vm_mm, address))
2102 if (likely(writable)) {
2103 if (likely(referenced)) {
2104 result = SCAN_SUCCEED;
2105 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
2106 referenced, writable, result);
2110 result = SCAN_PAGE_RO;
2114 release_pte_pages(pte, _pte);
2115 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
2116 referenced, writable, result);
2120 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
2121 struct vm_area_struct *vma,
2122 unsigned long address,
2126 for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
2127 pte_t pteval = *_pte;
2128 struct page *src_page;
2130 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
2131 clear_user_highpage(page, address);
2132 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
2133 if (is_zero_pfn(pte_pfn(pteval))) {
2135 * ptl mostly unnecessary.
2139 * paravirt calls inside pte_clear here are
2142 pte_clear(vma->vm_mm, address, _pte);
2146 src_page = pte_page(pteval);
2147 copy_user_highpage(page, src_page, address, vma);
2148 VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
2149 release_pte_page(src_page);
2151 * ptl mostly unnecessary, but preempt has to
2152 * be disabled to update the per-cpu stats
2153 * inside page_remove_rmap().
2157 * paravirt calls inside pte_clear here are
2160 pte_clear(vma->vm_mm, address, _pte);
2161 page_remove_rmap(src_page, false);
2163 free_page_and_swap_cache(src_page);
2166 address += PAGE_SIZE;
2171 static void khugepaged_alloc_sleep(void)
2175 add_wait_queue(&khugepaged_wait, &wait);
2176 freezable_schedule_timeout_interruptible(
2177 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
2178 remove_wait_queue(&khugepaged_wait, &wait);
2181 static int khugepaged_node_load[MAX_NUMNODES];
2183 static bool khugepaged_scan_abort(int nid)
2188 * If zone_reclaim_mode is disabled, then no extra effort is made to
2189 * allocate memory locally.
2191 if (!zone_reclaim_mode)
2194 /* If there is a count for this node already, it must be acceptable */
2195 if (khugepaged_node_load[nid])
2198 for (i = 0; i < MAX_NUMNODES; i++) {
2199 if (!khugepaged_node_load[i])
2201 if (node_distance(nid, i) > RECLAIM_DISTANCE)
2208 static int khugepaged_find_target_node(void)
2210 static int last_khugepaged_target_node = NUMA_NO_NODE;
2211 int nid, target_node = 0, max_value = 0;
2213 /* find first node with max normal pages hit */
2214 for (nid = 0; nid < MAX_NUMNODES; nid++)
2215 if (khugepaged_node_load[nid] > max_value) {
2216 max_value = khugepaged_node_load[nid];
2220 /* do some balance if several nodes have the same hit record */
2221 if (target_node <= last_khugepaged_target_node)
2222 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
2224 if (max_value == khugepaged_node_load[nid]) {
2229 last_khugepaged_target_node = target_node;
2233 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2235 if (IS_ERR(*hpage)) {
2241 khugepaged_alloc_sleep();
2242 } else if (*hpage) {
2250 static struct page *
2251 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
2252 unsigned long address, int node)
2254 VM_BUG_ON_PAGE(*hpage, *hpage);
2257 * Before allocating the hugepage, release the mmap_sem read lock.
2258 * The allocation can take potentially a long time if it involves
2259 * sync compaction, and we do not need to hold the mmap_sem during
2260 * that. We will recheck the vma after taking it again in write mode.
2262 up_read(&mm->mmap_sem);
2264 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
2265 if (unlikely(!*hpage)) {
2266 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2267 *hpage = ERR_PTR(-ENOMEM);
2271 prep_transhuge_page(*hpage);
2272 count_vm_event(THP_COLLAPSE_ALLOC);
2276 static int khugepaged_find_target_node(void)
2281 static inline struct page *alloc_khugepaged_hugepage(void)
2285 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
2288 prep_transhuge_page(page);
2292 static struct page *khugepaged_alloc_hugepage(bool *wait)
2297 hpage = alloc_khugepaged_hugepage();
2299 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2304 khugepaged_alloc_sleep();
2306 count_vm_event(THP_COLLAPSE_ALLOC);
2307 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
2312 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2315 *hpage = khugepaged_alloc_hugepage(wait);
2317 if (unlikely(!*hpage))
2323 static struct page *
2324 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
2325 unsigned long address, int node)
2327 up_read(&mm->mmap_sem);
2334 static bool hugepage_vma_check(struct vm_area_struct *vma)
2336 if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
2337 (vma->vm_flags & VM_NOHUGEPAGE))
2339 if (!vma->anon_vma || vma->vm_ops)
2341 if (is_vma_temporary_stack(vma))
2343 return !(vma->vm_flags & VM_NO_THP);
2346 static void collapse_huge_page(struct mm_struct *mm,
2347 unsigned long address,
2348 struct page **hpage,
2349 struct vm_area_struct *vma,
2355 struct page *new_page;
2356 spinlock_t *pmd_ptl, *pte_ptl;
2357 int isolated = 0, result = 0;
2358 unsigned long hstart, hend;
2359 struct mem_cgroup *memcg;
2360 unsigned long mmun_start; /* For mmu_notifiers */
2361 unsigned long mmun_end; /* For mmu_notifiers */
2364 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2366 /* Only allocate from the target node */
2367 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_OTHER_NODE | __GFP_THISNODE;
2369 /* release the mmap_sem read lock. */
2370 new_page = khugepaged_alloc_page(hpage, gfp, mm, address, node);
2372 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
2376 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
2377 result = SCAN_CGROUP_CHARGE_FAIL;
2382 * Prevent all access to pagetables with the exception of
2383 * gup_fast later hanlded by the ptep_clear_flush and the VM
2384 * handled by the anon_vma lock + PG_lock.
2386 down_write(&mm->mmap_sem);
2387 if (unlikely(khugepaged_test_exit(mm))) {
2388 result = SCAN_ANY_PROCESS;
2392 vma = find_vma(mm, address);
2394 result = SCAN_VMA_NULL;
2397 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2398 hend = vma->vm_end & HPAGE_PMD_MASK;
2399 if (address < hstart || address + HPAGE_PMD_SIZE > hend) {
2400 result = SCAN_ADDRESS_RANGE;
2403 if (!hugepage_vma_check(vma)) {
2404 result = SCAN_VMA_CHECK;
2407 pmd = mm_find_pmd(mm, address);
2409 result = SCAN_PMD_NULL;
2413 anon_vma_lock_write(vma->anon_vma);
2415 pte = pte_offset_map(pmd, address);
2416 pte_ptl = pte_lockptr(mm, pmd);
2418 mmun_start = address;
2419 mmun_end = address + HPAGE_PMD_SIZE;
2420 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2421 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
2423 * After this gup_fast can't run anymore. This also removes
2424 * any huge TLB entry from the CPU so we won't allow
2425 * huge and small TLB entries for the same virtual address
2426 * to avoid the risk of CPU bugs in that area.
2428 _pmd = pmdp_collapse_flush(vma, address, pmd);
2429 spin_unlock(pmd_ptl);
2430 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2433 isolated = __collapse_huge_page_isolate(vma, address, pte);
2434 spin_unlock(pte_ptl);
2436 if (unlikely(!isolated)) {
2439 BUG_ON(!pmd_none(*pmd));
2441 * We can only use set_pmd_at when establishing
2442 * hugepmds and never for establishing regular pmds that
2443 * points to regular pagetables. Use pmd_populate for that
2445 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
2446 spin_unlock(pmd_ptl);
2447 anon_vma_unlock_write(vma->anon_vma);
2453 * All pages are isolated and locked so anon_vma rmap
2454 * can't run anymore.
2456 anon_vma_unlock_write(vma->anon_vma);
2458 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
2460 __SetPageUptodate(new_page);
2461 pgtable = pmd_pgtable(_pmd);
2463 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
2464 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
2467 * spin_lock() below is not the equivalent of smp_wmb(), so
2468 * this is needed to avoid the copy_huge_page writes to become
2469 * visible after the set_pmd_at() write.
2474 BUG_ON(!pmd_none(*pmd));
2475 page_add_new_anon_rmap(new_page, vma, address, true);
2476 mem_cgroup_commit_charge(new_page, memcg, false, true);
2477 lru_cache_add_active_or_unevictable(new_page, vma);
2478 pgtable_trans_huge_deposit(mm, pmd, pgtable);
2479 set_pmd_at(mm, address, pmd, _pmd);
2480 update_mmu_cache_pmd(vma, address, pmd);
2481 spin_unlock(pmd_ptl);
2485 khugepaged_pages_collapsed++;
2486 result = SCAN_SUCCEED;
2488 up_write(&mm->mmap_sem);
2489 trace_mm_collapse_huge_page(mm, isolated, result);
2493 trace_mm_collapse_huge_page(mm, isolated, result);
2496 mem_cgroup_cancel_charge(new_page, memcg, true);
2500 static int khugepaged_scan_pmd(struct mm_struct *mm,
2501 struct vm_area_struct *vma,
2502 unsigned long address,
2503 struct page **hpage)
2507 int ret = 0, none_or_zero = 0, result = 0;
2508 struct page *page = NULL;
2509 unsigned long _address;
2511 int node = NUMA_NO_NODE;
2512 bool writable = false, referenced = false;
2514 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2516 pmd = mm_find_pmd(mm, address);
2518 result = SCAN_PMD_NULL;
2522 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
2523 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2524 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2525 _pte++, _address += PAGE_SIZE) {
2526 pte_t pteval = *_pte;
2527 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
2528 if (!userfaultfd_armed(vma) &&
2529 ++none_or_zero <= khugepaged_max_ptes_none) {
2532 result = SCAN_EXCEED_NONE_PTE;
2536 if (!pte_present(pteval)) {
2537 result = SCAN_PTE_NON_PRESENT;
2540 if (pte_write(pteval))
2543 page = vm_normal_page(vma, _address, pteval);
2544 if (unlikely(!page)) {
2545 result = SCAN_PAGE_NULL;
2549 /* TODO: teach khugepaged to collapse THP mapped with pte */
2550 if (PageCompound(page)) {
2551 result = SCAN_PAGE_COMPOUND;
2556 * Record which node the original page is from and save this
2557 * information to khugepaged_node_load[].
2558 * Khupaged will allocate hugepage from the node has the max
2561 node = page_to_nid(page);
2562 if (khugepaged_scan_abort(node)) {
2563 result = SCAN_SCAN_ABORT;
2566 khugepaged_node_load[node]++;
2567 if (!PageLRU(page)) {
2568 result = SCAN_PAGE_LRU;
2571 if (PageLocked(page)) {
2572 result = SCAN_PAGE_LOCK;
2575 if (!PageAnon(page)) {
2576 result = SCAN_PAGE_ANON;
2581 * cannot use mapcount: can't collapse if there's a gup pin.
2582 * The page must only be referenced by the scanned process
2583 * and page swap cache.
2585 if (page_count(page) != 1 + !!PageSwapCache(page)) {
2586 result = SCAN_PAGE_COUNT;
2589 if (pte_young(pteval) ||
2590 page_is_young(page) || PageReferenced(page) ||
2591 mmu_notifier_test_young(vma->vm_mm, address))
2596 result = SCAN_SUCCEED;
2599 result = SCAN_NO_REFERENCED_PAGE;
2602 result = SCAN_PAGE_RO;
2605 pte_unmap_unlock(pte, ptl);
2607 node = khugepaged_find_target_node();
2608 /* collapse_huge_page will return with the mmap_sem released */
2609 collapse_huge_page(mm, address, hpage, vma, node);
2612 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
2613 none_or_zero, result);
2617 static void collect_mm_slot(struct mm_slot *mm_slot)
2619 struct mm_struct *mm = mm_slot->mm;
2621 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2623 if (khugepaged_test_exit(mm)) {
2625 hash_del(&mm_slot->hash);
2626 list_del(&mm_slot->mm_node);
2629 * Not strictly needed because the mm exited already.
2631 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2634 /* khugepaged_mm_lock actually not necessary for the below */
2635 free_mm_slot(mm_slot);
2640 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2641 struct page **hpage)
2642 __releases(&khugepaged_mm_lock)
2643 __acquires(&khugepaged_mm_lock)
2645 struct mm_slot *mm_slot;
2646 struct mm_struct *mm;
2647 struct vm_area_struct *vma;
2651 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2653 if (khugepaged_scan.mm_slot)
2654 mm_slot = khugepaged_scan.mm_slot;
2656 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2657 struct mm_slot, mm_node);
2658 khugepaged_scan.address = 0;
2659 khugepaged_scan.mm_slot = mm_slot;
2661 spin_unlock(&khugepaged_mm_lock);
2664 down_read(&mm->mmap_sem);
2665 if (unlikely(khugepaged_test_exit(mm)))
2668 vma = find_vma(mm, khugepaged_scan.address);
2671 for (; vma; vma = vma->vm_next) {
2672 unsigned long hstart, hend;
2675 if (unlikely(khugepaged_test_exit(mm))) {
2679 if (!hugepage_vma_check(vma)) {
2684 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2685 hend = vma->vm_end & HPAGE_PMD_MASK;
2688 if (khugepaged_scan.address > hend)
2690 if (khugepaged_scan.address < hstart)
2691 khugepaged_scan.address = hstart;
2692 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2694 while (khugepaged_scan.address < hend) {
2697 if (unlikely(khugepaged_test_exit(mm)))
2698 goto breakouterloop;
2700 VM_BUG_ON(khugepaged_scan.address < hstart ||
2701 khugepaged_scan.address + HPAGE_PMD_SIZE >
2703 ret = khugepaged_scan_pmd(mm, vma,
2704 khugepaged_scan.address,
2706 /* move to next address */
2707 khugepaged_scan.address += HPAGE_PMD_SIZE;
2708 progress += HPAGE_PMD_NR;
2710 /* we released mmap_sem so break loop */
2711 goto breakouterloop_mmap_sem;
2712 if (progress >= pages)
2713 goto breakouterloop;
2717 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2718 breakouterloop_mmap_sem:
2720 spin_lock(&khugepaged_mm_lock);
2721 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2723 * Release the current mm_slot if this mm is about to die, or
2724 * if we scanned all vmas of this mm.
2726 if (khugepaged_test_exit(mm) || !vma) {
2728 * Make sure that if mm_users is reaching zero while
2729 * khugepaged runs here, khugepaged_exit will find
2730 * mm_slot not pointing to the exiting mm.
2732 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2733 khugepaged_scan.mm_slot = list_entry(
2734 mm_slot->mm_node.next,
2735 struct mm_slot, mm_node);
2736 khugepaged_scan.address = 0;
2738 khugepaged_scan.mm_slot = NULL;
2739 khugepaged_full_scans++;
2742 collect_mm_slot(mm_slot);
2748 static int khugepaged_has_work(void)
2750 return !list_empty(&khugepaged_scan.mm_head) &&
2751 khugepaged_enabled();
2754 static int khugepaged_wait_event(void)
2756 return !list_empty(&khugepaged_scan.mm_head) ||
2757 kthread_should_stop();
2760 static void khugepaged_do_scan(void)
2762 struct page *hpage = NULL;
2763 unsigned int progress = 0, pass_through_head = 0;
2764 unsigned int pages = khugepaged_pages_to_scan;
2767 barrier(); /* write khugepaged_pages_to_scan to local stack */
2769 while (progress < pages) {
2770 if (!khugepaged_prealloc_page(&hpage, &wait))
2775 if (unlikely(kthread_should_stop() || try_to_freeze()))
2778 spin_lock(&khugepaged_mm_lock);
2779 if (!khugepaged_scan.mm_slot)
2780 pass_through_head++;
2781 if (khugepaged_has_work() &&
2782 pass_through_head < 2)
2783 progress += khugepaged_scan_mm_slot(pages - progress,
2787 spin_unlock(&khugepaged_mm_lock);
2790 if (!IS_ERR_OR_NULL(hpage))
2794 static void khugepaged_wait_work(void)
2796 if (khugepaged_has_work()) {
2797 if (!khugepaged_scan_sleep_millisecs)
2800 wait_event_freezable_timeout(khugepaged_wait,
2801 kthread_should_stop(),
2802 msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2806 if (khugepaged_enabled())
2807 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2810 static int khugepaged(void *none)
2812 struct mm_slot *mm_slot;
2815 set_user_nice(current, MAX_NICE);
2817 while (!kthread_should_stop()) {
2818 khugepaged_do_scan();
2819 khugepaged_wait_work();
2822 spin_lock(&khugepaged_mm_lock);
2823 mm_slot = khugepaged_scan.mm_slot;
2824 khugepaged_scan.mm_slot = NULL;
2826 collect_mm_slot(mm_slot);
2827 spin_unlock(&khugepaged_mm_lock);
2831 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2832 unsigned long haddr, pmd_t *pmd)
2834 struct mm_struct *mm = vma->vm_mm;
2839 /* leave pmd empty until pte is filled */
2840 pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2842 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2843 pmd_populate(mm, &_pmd, pgtable);
2845 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
2847 entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
2848 entry = pte_mkspecial(entry);
2849 pte = pte_offset_map(&_pmd, haddr);
2850 VM_BUG_ON(!pte_none(*pte));
2851 set_pte_at(mm, haddr, pte, entry);
2854 smp_wmb(); /* make pte visible before pmd */
2855 pmd_populate(mm, pmd, pgtable);
2856 put_huge_zero_page();
2859 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
2860 unsigned long haddr, bool freeze)
2862 struct mm_struct *mm = vma->vm_mm;
2866 bool young, write, dirty;
2870 VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2871 VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2872 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
2873 VM_BUG_ON(!pmd_trans_huge(*pmd) && !pmd_devmap(*pmd));
2875 count_vm_event(THP_SPLIT_PMD);
2877 if (vma_is_dax(vma)) {
2878 pmd_t _pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2879 if (is_huge_zero_pmd(_pmd))
2880 put_huge_zero_page();
2882 } else if (is_huge_zero_pmd(*pmd)) {
2883 return __split_huge_zero_page_pmd(vma, haddr, pmd);
2886 page = pmd_page(*pmd);
2887 VM_BUG_ON_PAGE(!page_count(page), page);
2888 page_ref_add(page, HPAGE_PMD_NR - 1);
2889 write = pmd_write(*pmd);
2890 young = pmd_young(*pmd);
2891 dirty = pmd_dirty(*pmd);
2893 pmdp_huge_split_prepare(vma, haddr, pmd);
2894 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2895 pmd_populate(mm, &_pmd, pgtable);
2897 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2900 * Note that NUMA hinting access restrictions are not
2901 * transferred to avoid any possibility of altering
2902 * permissions across VMAs.
2905 swp_entry_t swp_entry;
2906 swp_entry = make_migration_entry(page + i, write);
2907 entry = swp_entry_to_pte(swp_entry);
2909 entry = mk_pte(page + i, vma->vm_page_prot);
2910 entry = maybe_mkwrite(entry, vma);
2912 entry = pte_wrprotect(entry);
2914 entry = pte_mkold(entry);
2917 SetPageDirty(page + i);
2918 pte = pte_offset_map(&_pmd, addr);
2919 BUG_ON(!pte_none(*pte));
2920 set_pte_at(mm, addr, pte, entry);
2921 atomic_inc(&page[i]._mapcount);
2926 * Set PG_double_map before dropping compound_mapcount to avoid
2927 * false-negative page_mapped().
2929 if (compound_mapcount(page) > 1 && !TestSetPageDoubleMap(page)) {
2930 for (i = 0; i < HPAGE_PMD_NR; i++)
2931 atomic_inc(&page[i]._mapcount);
2934 if (atomic_add_negative(-1, compound_mapcount_ptr(page))) {
2935 /* Last compound_mapcount is gone. */
2936 __dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
2937 if (TestClearPageDoubleMap(page)) {
2938 /* No need in mapcount reference anymore */
2939 for (i = 0; i < HPAGE_PMD_NR; i++)
2940 atomic_dec(&page[i]._mapcount);
2944 smp_wmb(); /* make pte visible before pmd */
2946 * Up to this point the pmd is present and huge and userland has the
2947 * whole access to the hugepage during the split (which happens in
2948 * place). If we overwrite the pmd with the not-huge version pointing
2949 * to the pte here (which of course we could if all CPUs were bug
2950 * free), userland could trigger a small page size TLB miss on the
2951 * small sized TLB while the hugepage TLB entry is still established in
2952 * the huge TLB. Some CPU doesn't like that.
2953 * See http://support.amd.com/us/Processor_TechDocs/41322.pdf, Erratum
2954 * 383 on page 93. Intel should be safe but is also warns that it's
2955 * only safe if the permission and cache attributes of the two entries
2956 * loaded in the two TLB is identical (which should be the case here).
2957 * But it is generally safer to never allow small and huge TLB entries
2958 * for the same virtual address to be loaded simultaneously. So instead
2959 * of doing "pmd_populate(); flush_pmd_tlb_range();" we first mark the
2960 * current pmd notpresent (atomically because here the pmd_trans_huge
2961 * and pmd_trans_splitting must remain set at all times on the pmd
2962 * until the split is complete for this pmd), then we flush the SMP TLB
2963 * and finally we write the non-huge version of the pmd entry with
2966 pmdp_invalidate(vma, haddr, pmd);
2967 pmd_populate(mm, pmd, pgtable);
2970 for (i = 0; i < HPAGE_PMD_NR; i++) {
2971 page_remove_rmap(page + i, false);
2977 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2978 unsigned long address, bool freeze)
2981 struct mm_struct *mm = vma->vm_mm;
2982 unsigned long haddr = address & HPAGE_PMD_MASK;
2984 mmu_notifier_invalidate_range_start(mm, haddr, haddr + HPAGE_PMD_SIZE);
2985 ptl = pmd_lock(mm, pmd);
2986 if (pmd_trans_huge(*pmd)) {
2987 struct page *page = pmd_page(*pmd);
2988 if (PageMlocked(page))
2989 clear_page_mlock(page);
2990 } else if (!pmd_devmap(*pmd))
2992 __split_huge_pmd_locked(vma, pmd, haddr, freeze);
2995 mmu_notifier_invalidate_range_end(mm, haddr, haddr + HPAGE_PMD_SIZE);
2998 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2999 bool freeze, struct page *page)
3005 pgd = pgd_offset(vma->vm_mm, address);
3006 if (!pgd_present(*pgd))
3009 pud = pud_offset(pgd, address);
3010 if (!pud_present(*pud))
3013 pmd = pmd_offset(pud, address);
3014 if (!pmd_present(*pmd) || (!pmd_trans_huge(*pmd) && !pmd_devmap(*pmd)))
3018 * If caller asks to setup a migration entries, we need a page to check
3019 * pmd against. Otherwise we can end up replacing wrong page.
3021 VM_BUG_ON(freeze && !page);
3022 if (page && page != pmd_page(*pmd))
3026 * Caller holds the mmap_sem write mode, so a huge pmd cannot
3027 * materialize from under us.
3029 __split_huge_pmd(vma, pmd, address, freeze);
3032 void vma_adjust_trans_huge(struct vm_area_struct *vma,
3033 unsigned long start,
3038 * If the new start address isn't hpage aligned and it could
3039 * previously contain an hugepage: check if we need to split
3042 if (start & ~HPAGE_PMD_MASK &&
3043 (start & HPAGE_PMD_MASK) >= vma->vm_start &&
3044 (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
3045 split_huge_pmd_address(vma, start, false, NULL);
3048 * If the new end address isn't hpage aligned and it could
3049 * previously contain an hugepage: check if we need to split
3052 if (end & ~HPAGE_PMD_MASK &&
3053 (end & HPAGE_PMD_MASK) >= vma->vm_start &&
3054 (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
3055 split_huge_pmd_address(vma, end, false, NULL);
3058 * If we're also updating the vma->vm_next->vm_start, if the new
3059 * vm_next->vm_start isn't page aligned and it could previously
3060 * contain an hugepage: check if we need to split an huge pmd.
3062 if (adjust_next > 0) {
3063 struct vm_area_struct *next = vma->vm_next;
3064 unsigned long nstart = next->vm_start;
3065 nstart += adjust_next << PAGE_SHIFT;
3066 if (nstart & ~HPAGE_PMD_MASK &&
3067 (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
3068 (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
3069 split_huge_pmd_address(next, nstart, false, NULL);
3073 static void freeze_page(struct page *page)
3075 enum ttu_flags ttu_flags = TTU_MIGRATION | TTU_IGNORE_MLOCK |
3076 TTU_IGNORE_ACCESS | TTU_RMAP_LOCKED;
3079 VM_BUG_ON_PAGE(!PageHead(page), page);
3081 /* We only need TTU_SPLIT_HUGE_PMD once */
3082 ret = try_to_unmap(page, ttu_flags | TTU_SPLIT_HUGE_PMD);
3083 for (i = 1; !ret && i < HPAGE_PMD_NR; i++) {
3084 /* Cut short if the page is unmapped */
3085 if (page_count(page) == 1)
3088 ret = try_to_unmap(page + i, ttu_flags);
3093 static void unfreeze_page(struct page *page)
3097 for (i = 0; i < HPAGE_PMD_NR; i++)
3098 remove_migration_ptes(page + i, page + i, true);
3101 static void __split_huge_page_tail(struct page *head, int tail,
3102 struct lruvec *lruvec, struct list_head *list)
3104 struct page *page_tail = head + tail;
3106 VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
3107 VM_BUG_ON_PAGE(page_ref_count(page_tail) != 0, page_tail);
3110 * tail_page->_refcount is zero and not changing from under us. But
3111 * get_page_unless_zero() may be running from under us on the
3112 * tail_page. If we used atomic_set() below instead of atomic_inc(), we
3113 * would then run atomic_set() concurrently with
3114 * get_page_unless_zero(), and atomic_set() is implemented in C not
3115 * using locked ops. spin_unlock on x86 sometime uses locked ops
3116 * because of PPro errata 66, 92, so unless somebody can guarantee
3117 * atomic_set() here would be safe on all archs (and not only on x86),
3118 * it's safer to use atomic_inc().
3120 page_ref_inc(page_tail);
3122 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
3123 page_tail->flags |= (head->flags &
3124 ((1L << PG_referenced) |
3125 (1L << PG_swapbacked) |
3126 (1L << PG_mlocked) |
3127 (1L << PG_uptodate) |
3130 (1L << PG_unevictable) |
3134 * After clearing PageTail the gup refcount can be released.
3135 * Page flags also must be visible before we make the page non-compound.
3139 clear_compound_head(page_tail);
3141 if (page_is_young(head))
3142 set_page_young(page_tail);
3143 if (page_is_idle(head))
3144 set_page_idle(page_tail);
3146 /* ->mapping in first tail page is compound_mapcount */
3147 VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
3149 page_tail->mapping = head->mapping;
3151 page_tail->index = head->index + tail;
3152 page_cpupid_xchg_last(page_tail, page_cpupid_last(head));
3153 lru_add_page_tail(head, page_tail, lruvec, list);
3156 static void __split_huge_page(struct page *page, struct list_head *list)
3158 struct page *head = compound_head(page);
3159 struct zone *zone = page_zone(head);
3160 struct lruvec *lruvec;
3163 /* prevent PageLRU to go away from under us, and freeze lru stats */
3164 spin_lock_irq(&zone->lru_lock);
3165 lruvec = mem_cgroup_page_lruvec(head, zone);
3167 /* complete memcg works before add pages to LRU */
3168 mem_cgroup_split_huge_fixup(head);
3170 for (i = HPAGE_PMD_NR - 1; i >= 1; i--)
3171 __split_huge_page_tail(head, i, lruvec, list);
3173 ClearPageCompound(head);
3174 spin_unlock_irq(&zone->lru_lock);
3176 unfreeze_page(head);
3178 for (i = 0; i < HPAGE_PMD_NR; i++) {
3179 struct page *subpage = head + i;
3180 if (subpage == page)
3182 unlock_page(subpage);
3185 * Subpages may be freed if there wasn't any mapping
3186 * like if add_to_swap() is running on a lru page that
3187 * had its mapping zapped. And freeing these pages
3188 * requires taking the lru_lock so we do the put_page
3189 * of the tail pages after the split is complete.
3195 int total_mapcount(struct page *page)
3199 VM_BUG_ON_PAGE(PageTail(page), page);
3201 if (likely(!PageCompound(page)))
3202 return atomic_read(&page->_mapcount) + 1;
3204 ret = compound_mapcount(page);
3207 for (i = 0; i < HPAGE_PMD_NR; i++)
3208 ret += atomic_read(&page[i]._mapcount) + 1;
3209 if (PageDoubleMap(page))
3210 ret -= HPAGE_PMD_NR;
3215 * This calculates accurately how many mappings a transparent hugepage
3216 * has (unlike page_mapcount() which isn't fully accurate). This full
3217 * accuracy is primarily needed to know if copy-on-write faults can
3218 * reuse the page and change the mapping to read-write instead of
3219 * copying them. At the same time this returns the total_mapcount too.
3221 * The function returns the highest mapcount any one of the subpages
3222 * has. If the return value is one, even if different processes are
3223 * mapping different subpages of the transparent hugepage, they can
3224 * all reuse it, because each process is reusing a different subpage.
3226 * The total_mapcount is instead counting all virtual mappings of the
3227 * subpages. If the total_mapcount is equal to "one", it tells the
3228 * caller all mappings belong to the same "mm" and in turn the
3229 * anon_vma of the transparent hugepage can become the vma->anon_vma
3230 * local one as no other process may be mapping any of the subpages.
3232 * It would be more accurate to replace page_mapcount() with
3233 * page_trans_huge_mapcount(), however we only use
3234 * page_trans_huge_mapcount() in the copy-on-write faults where we
3235 * need full accuracy to avoid breaking page pinning, because
3236 * page_trans_huge_mapcount() is slower than page_mapcount().
3238 int page_trans_huge_mapcount(struct page *page, int *total_mapcount)
3240 int i, ret, _total_mapcount, mapcount;
3242 /* hugetlbfs shouldn't call it */
3243 VM_BUG_ON_PAGE(PageHuge(page), page);
3245 if (likely(!PageTransCompound(page))) {
3246 mapcount = atomic_read(&page->_mapcount) + 1;
3248 *total_mapcount = mapcount;
3252 page = compound_head(page);
3254 _total_mapcount = ret = 0;
3255 for (i = 0; i < HPAGE_PMD_NR; i++) {
3256 mapcount = atomic_read(&page[i]._mapcount) + 1;
3257 ret = max(ret, mapcount);
3258 _total_mapcount += mapcount;
3260 if (PageDoubleMap(page)) {
3262 _total_mapcount -= HPAGE_PMD_NR;
3264 mapcount = compound_mapcount(page);
3266 _total_mapcount += mapcount;
3268 *total_mapcount = _total_mapcount;
3273 * This function splits huge page into normal pages. @page can point to any
3274 * subpage of huge page to split. Split doesn't change the position of @page.
3276 * Only caller must hold pin on the @page, otherwise split fails with -EBUSY.
3277 * The huge page must be locked.
3279 * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
3281 * Both head page and tail pages will inherit mapping, flags, and so on from
3284 * GUP pin and PG_locked transferred to @page. Rest subpages can be freed if
3285 * they are not mapped.
3287 * Returns 0 if the hugepage is split successfully.
3288 * Returns -EBUSY if the page is pinned or if anon_vma disappeared from under
3291 int split_huge_page_to_list(struct page *page, struct list_head *list)
3293 struct page *head = compound_head(page);
3294 struct pglist_data *pgdata = NODE_DATA(page_to_nid(head));
3295 struct anon_vma *anon_vma;
3296 int count, mapcount, ret;
3298 unsigned long flags;
3300 VM_BUG_ON_PAGE(is_huge_zero_page(page), page);
3301 VM_BUG_ON_PAGE(!PageAnon(page), page);
3302 VM_BUG_ON_PAGE(!PageLocked(page), page);
3303 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
3304 VM_BUG_ON_PAGE(!PageCompound(page), page);
3307 * The caller does not necessarily hold an mmap_sem that would prevent
3308 * the anon_vma disappearing so we first we take a reference to it
3309 * and then lock the anon_vma for write. This is similar to
3310 * page_lock_anon_vma_read except the write lock is taken to serialise
3311 * against parallel split or collapse operations.
3313 anon_vma = page_get_anon_vma(head);
3318 anon_vma_lock_write(anon_vma);
3321 * Racy check if we can split the page, before freeze_page() will
3324 if (total_mapcount(head) != page_count(head) - 1) {
3329 mlocked = PageMlocked(page);
3331 VM_BUG_ON_PAGE(compound_mapcount(head), head);
3333 /* Make sure the page is not on per-CPU pagevec as it takes pin */
3337 /* Prevent deferred_split_scan() touching ->_refcount */
3338 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
3339 count = page_count(head);
3340 mapcount = total_mapcount(head);
3341 if (!mapcount && count == 1) {
3342 if (!list_empty(page_deferred_list(head))) {
3343 pgdata->split_queue_len--;
3344 list_del(page_deferred_list(head));
3346 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3347 __split_huge_page(page, list);
3349 } else if (IS_ENABLED(CONFIG_DEBUG_VM) && mapcount) {
3350 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3351 pr_alert("total_mapcount: %u, page_count(): %u\n",
3354 dump_page(head, NULL);
3355 dump_page(page, "total_mapcount(head) > 0");
3358 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3359 unfreeze_page(head);
3364 anon_vma_unlock_write(anon_vma);
3365 put_anon_vma(anon_vma);
3367 count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
3371 void free_transhuge_page(struct page *page)
3373 struct pglist_data *pgdata = NODE_DATA(page_to_nid(page));
3374 unsigned long flags;
3376 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
3377 if (!list_empty(page_deferred_list(page))) {
3378 pgdata->split_queue_len--;
3379 list_del(page_deferred_list(page));
3381 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3382 free_compound_page(page);
3385 void deferred_split_huge_page(struct page *page)
3387 struct pglist_data *pgdata = NODE_DATA(page_to_nid(page));
3388 unsigned long flags;
3390 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
3392 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
3393 if (list_empty(page_deferred_list(page))) {
3394 count_vm_event(THP_DEFERRED_SPLIT_PAGE);
3395 list_add_tail(page_deferred_list(page), &pgdata->split_queue);
3396 pgdata->split_queue_len++;
3398 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3401 static unsigned long deferred_split_count(struct shrinker *shrink,
3402 struct shrink_control *sc)
3404 struct pglist_data *pgdata = NODE_DATA(sc->nid);
3405 return ACCESS_ONCE(pgdata->split_queue_len);
3408 static unsigned long deferred_split_scan(struct shrinker *shrink,
3409 struct shrink_control *sc)
3411 struct pglist_data *pgdata = NODE_DATA(sc->nid);
3412 unsigned long flags;
3413 LIST_HEAD(list), *pos, *next;
3417 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
3418 /* Take pin on all head pages to avoid freeing them under us */
3419 list_for_each_safe(pos, next, &pgdata->split_queue) {
3420 page = list_entry((void *)pos, struct page, mapping);
3421 page = compound_head(page);
3422 if (get_page_unless_zero(page)) {
3423 list_move(page_deferred_list(page), &list);
3425 /* We lost race with put_compound_page() */
3426 list_del_init(page_deferred_list(page));
3427 pgdata->split_queue_len--;
3429 if (!--sc->nr_to_scan)
3432 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3434 list_for_each_safe(pos, next, &list) {
3435 page = list_entry((void *)pos, struct page, mapping);
3437 /* split_huge_page() removes page from list on success */
3438 if (!split_huge_page(page))
3444 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
3445 list_splice_tail(&list, &pgdata->split_queue);
3446 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
3449 * Stop shrinker if we didn't split any page, but the queue is empty.
3450 * This can happen if pages were freed under us.
3452 if (!split && list_empty(&pgdata->split_queue))
3457 static struct shrinker deferred_split_shrinker = {
3458 .count_objects = deferred_split_count,
3459 .scan_objects = deferred_split_scan,
3460 .seeks = DEFAULT_SEEKS,
3461 .flags = SHRINKER_NUMA_AWARE,
3464 #ifdef CONFIG_DEBUG_FS
3465 static int split_huge_pages_set(void *data, u64 val)
3469 unsigned long pfn, max_zone_pfn;
3470 unsigned long total = 0, split = 0;
3475 for_each_populated_zone(zone) {
3476 max_zone_pfn = zone_end_pfn(zone);
3477 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
3478 if (!pfn_valid(pfn))
3481 page = pfn_to_page(pfn);
3482 if (!get_page_unless_zero(page))
3485 if (zone != page_zone(page))
3488 if (!PageHead(page) || !PageAnon(page) ||
3494 if (!split_huge_page(page))
3502 pr_info("%lu of %lu THP split\n", split, total);
3506 DEFINE_SIMPLE_ATTRIBUTE(split_huge_pages_fops, NULL, split_huge_pages_set,
3509 static int __init split_huge_pages_debugfs(void)
3513 ret = debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3514 &split_huge_pages_fops);
3516 pr_warn("Failed to create split_huge_pages in debugfs");
3519 late_initcall(split_huge_pages_debugfs);