1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2009 Red Hat, Inc.
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 #include <linux/sched.h>
10 #include <linux/sched/mm.h>
11 #include <linux/sched/coredump.h>
12 #include <linux/sched/numa_balancing.h>
13 #include <linux/highmem.h>
14 #include <linux/hugetlb.h>
15 #include <linux/mmu_notifier.h>
16 #include <linux/rmap.h>
17 #include <linux/swap.h>
18 #include <linux/shrinker.h>
19 #include <linux/mm_inline.h>
20 #include <linux/swapops.h>
21 #include <linux/dax.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>
33 #include <linux/shmem_fs.h>
34 #include <linux/oom.h>
35 #include <linux/numa.h>
36 #include <linux/page_owner.h>
37 #include <linux/sched/sysctl.h>
40 #include <asm/pgalloc.h>
44 #define CREATE_TRACE_POINTS
45 #include <trace/events/thp.h>
48 * By default, transparent hugepage support is disabled in order to avoid
49 * risking an increased memory footprint for applications that are not
50 * guaranteed to benefit from it. When transparent hugepage support is
51 * enabled, it is for all mappings, and khugepaged scans all mappings.
52 * Defrag is invoked by khugepaged hugepage allocations and by page faults
53 * for all hugepage allocations.
55 unsigned long transparent_hugepage_flags __read_mostly =
56 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
57 (1<<TRANSPARENT_HUGEPAGE_FLAG)|
59 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
60 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
62 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
63 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
64 (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
66 static struct shrinker deferred_split_shrinker;
68 static atomic_t huge_zero_refcount;
69 struct page *huge_zero_page __read_mostly;
70 unsigned long huge_zero_pfn __read_mostly = ~0UL;
72 bool hugepage_vma_check(struct vm_area_struct *vma,
73 unsigned long vm_flags,
76 if (!vma->vm_mm) /* vdso */
79 if (!transhuge_vma_enabled(vma, vm_flags))
82 if (vm_flags & VM_NO_KHUGEPAGED)
85 /* Don't run khugepaged against DAX vma */
89 /* Check alignment for file vma and size for both file and anon vma */
90 if (!transhuge_vma_suitable(vma, (vma->vm_end - HPAGE_PMD_SIZE)))
93 /* Enabled via shmem mount options or sysfs settings. */
94 if (shmem_file(vma->vm_file))
95 return shmem_huge_enabled(vma);
97 if (!khugepaged_enabled())
100 /* THP settings require madvise. */
101 if (!(vm_flags & VM_HUGEPAGE) && !khugepaged_always())
104 /* Only regular file is valid */
105 if (file_thp_enabled(vma))
108 if (!vma_is_anonymous(vma))
111 if (vma_is_temporary_stack(vma))
115 * THPeligible bit of smaps should show 1 for proper VMAs even
116 * though anon_vma is not initialized yet.
124 static bool get_huge_zero_page(void)
126 struct page *zero_page;
128 if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
131 zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
134 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
137 count_vm_event(THP_ZERO_PAGE_ALLOC);
139 if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
141 __free_pages(zero_page, compound_order(zero_page));
144 WRITE_ONCE(huge_zero_pfn, page_to_pfn(zero_page));
146 /* We take additional reference here. It will be put back by shrinker */
147 atomic_set(&huge_zero_refcount, 2);
152 static void put_huge_zero_page(void)
155 * Counter should never go to zero here. Only shrinker can put
158 BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
161 struct page *mm_get_huge_zero_page(struct mm_struct *mm)
163 if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
164 return READ_ONCE(huge_zero_page);
166 if (!get_huge_zero_page())
169 if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
170 put_huge_zero_page();
172 return READ_ONCE(huge_zero_page);
175 void mm_put_huge_zero_page(struct mm_struct *mm)
177 if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
178 put_huge_zero_page();
181 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
182 struct shrink_control *sc)
184 /* we can free zero page only if last reference remains */
185 return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
188 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
189 struct shrink_control *sc)
191 if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
192 struct page *zero_page = xchg(&huge_zero_page, NULL);
193 BUG_ON(zero_page == NULL);
194 WRITE_ONCE(huge_zero_pfn, ~0UL);
195 __free_pages(zero_page, compound_order(zero_page));
202 static struct shrinker huge_zero_page_shrinker = {
203 .count_objects = shrink_huge_zero_page_count,
204 .scan_objects = shrink_huge_zero_page_scan,
205 .seeks = DEFAULT_SEEKS,
209 static ssize_t enabled_show(struct kobject *kobj,
210 struct kobj_attribute *attr, char *buf)
214 if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
215 output = "[always] madvise never";
216 else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
217 &transparent_hugepage_flags))
218 output = "always [madvise] never";
220 output = "always madvise [never]";
222 return sysfs_emit(buf, "%s\n", output);
225 static ssize_t enabled_store(struct kobject *kobj,
226 struct kobj_attribute *attr,
227 const char *buf, size_t count)
231 if (sysfs_streq(buf, "always")) {
232 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
233 set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
234 } else if (sysfs_streq(buf, "madvise")) {
235 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
236 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
237 } else if (sysfs_streq(buf, "never")) {
238 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
239 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
244 int err = start_stop_khugepaged();
250 static struct kobj_attribute enabled_attr =
251 __ATTR(enabled, 0644, enabled_show, enabled_store);
253 ssize_t single_hugepage_flag_show(struct kobject *kobj,
254 struct kobj_attribute *attr, char *buf,
255 enum transparent_hugepage_flag flag)
257 return sysfs_emit(buf, "%d\n",
258 !!test_bit(flag, &transparent_hugepage_flags));
261 ssize_t single_hugepage_flag_store(struct kobject *kobj,
262 struct kobj_attribute *attr,
263 const char *buf, size_t count,
264 enum transparent_hugepage_flag flag)
269 ret = kstrtoul(buf, 10, &value);
276 set_bit(flag, &transparent_hugepage_flags);
278 clear_bit(flag, &transparent_hugepage_flags);
283 static ssize_t defrag_show(struct kobject *kobj,
284 struct kobj_attribute *attr, char *buf)
288 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
289 &transparent_hugepage_flags))
290 output = "[always] defer defer+madvise madvise never";
291 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
292 &transparent_hugepage_flags))
293 output = "always [defer] defer+madvise madvise never";
294 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,
295 &transparent_hugepage_flags))
296 output = "always defer [defer+madvise] madvise never";
297 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,
298 &transparent_hugepage_flags))
299 output = "always defer defer+madvise [madvise] never";
301 output = "always defer defer+madvise madvise [never]";
303 return sysfs_emit(buf, "%s\n", output);
306 static ssize_t defrag_store(struct kobject *kobj,
307 struct kobj_attribute *attr,
308 const char *buf, size_t count)
310 if (sysfs_streq(buf, "always")) {
311 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
312 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
313 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
314 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
315 } else if (sysfs_streq(buf, "defer+madvise")) {
316 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
317 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
318 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
319 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
320 } else if (sysfs_streq(buf, "defer")) {
321 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
322 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
323 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
324 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
325 } else if (sysfs_streq(buf, "madvise")) {
326 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
327 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
328 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
329 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
330 } else if (sysfs_streq(buf, "never")) {
331 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
332 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
333 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
334 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
340 static struct kobj_attribute defrag_attr =
341 __ATTR(defrag, 0644, defrag_show, defrag_store);
343 static ssize_t use_zero_page_show(struct kobject *kobj,
344 struct kobj_attribute *attr, char *buf)
346 return single_hugepage_flag_show(kobj, attr, buf,
347 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
349 static ssize_t use_zero_page_store(struct kobject *kobj,
350 struct kobj_attribute *attr, const char *buf, size_t count)
352 return single_hugepage_flag_store(kobj, attr, buf, count,
353 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
355 static struct kobj_attribute use_zero_page_attr =
356 __ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
358 static ssize_t hpage_pmd_size_show(struct kobject *kobj,
359 struct kobj_attribute *attr, char *buf)
361 return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE);
363 static struct kobj_attribute hpage_pmd_size_attr =
364 __ATTR_RO(hpage_pmd_size);
366 static struct attribute *hugepage_attr[] = {
369 &use_zero_page_attr.attr,
370 &hpage_pmd_size_attr.attr,
372 &shmem_enabled_attr.attr,
377 static const struct attribute_group hugepage_attr_group = {
378 .attrs = hugepage_attr,
381 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
385 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
386 if (unlikely(!*hugepage_kobj)) {
387 pr_err("failed to create transparent hugepage kobject\n");
391 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
393 pr_err("failed to register transparent hugepage group\n");
397 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
399 pr_err("failed to register transparent hugepage group\n");
400 goto remove_hp_group;
406 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
408 kobject_put(*hugepage_kobj);
412 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
414 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
415 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
416 kobject_put(hugepage_kobj);
419 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
424 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
427 #endif /* CONFIG_SYSFS */
429 static int __init hugepage_init(void)
432 struct kobject *hugepage_kobj;
434 if (!has_transparent_hugepage()) {
436 * Hardware doesn't support hugepages, hence disable
439 transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_NEVER_DAX;
444 * hugepages can't be allocated by the buddy allocator
446 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER >= MAX_ORDER);
448 * we use page->mapping and page->index in second tail page
449 * as list_head: assuming THP order >= 2
451 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER < 2);
453 err = hugepage_init_sysfs(&hugepage_kobj);
457 err = khugepaged_init();
461 err = register_shrinker(&huge_zero_page_shrinker, "thp-zero");
463 goto err_hzp_shrinker;
464 err = register_shrinker(&deferred_split_shrinker, "thp-deferred_split");
466 goto err_split_shrinker;
469 * By default disable transparent hugepages on smaller systems,
470 * where the extra memory used could hurt more than TLB overhead
471 * is likely to save. The admin can still enable it through /sys.
473 if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) {
474 transparent_hugepage_flags = 0;
478 err = start_stop_khugepaged();
484 unregister_shrinker(&deferred_split_shrinker);
486 unregister_shrinker(&huge_zero_page_shrinker);
488 khugepaged_destroy();
490 hugepage_exit_sysfs(hugepage_kobj);
494 subsys_initcall(hugepage_init);
496 static int __init setup_transparent_hugepage(char *str)
501 if (!strcmp(str, "always")) {
502 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
503 &transparent_hugepage_flags);
504 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
505 &transparent_hugepage_flags);
507 } else if (!strcmp(str, "madvise")) {
508 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
509 &transparent_hugepage_flags);
510 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
511 &transparent_hugepage_flags);
513 } else if (!strcmp(str, "never")) {
514 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
515 &transparent_hugepage_flags);
516 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
517 &transparent_hugepage_flags);
522 pr_warn("transparent_hugepage= cannot parse, ignored\n");
525 __setup("transparent_hugepage=", setup_transparent_hugepage);
527 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
529 if (likely(vma->vm_flags & VM_WRITE))
530 pmd = pmd_mkwrite(pmd);
535 static inline struct deferred_split *get_deferred_split_queue(struct page *page)
537 struct mem_cgroup *memcg = page_memcg(compound_head(page));
538 struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
541 return &memcg->deferred_split_queue;
543 return &pgdat->deferred_split_queue;
546 static inline struct deferred_split *get_deferred_split_queue(struct page *page)
548 struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
550 return &pgdat->deferred_split_queue;
554 void prep_transhuge_page(struct page *page)
557 * we use page->mapping and page->indexlru in second tail page
558 * as list_head: assuming THP order >= 2
561 INIT_LIST_HEAD(page_deferred_list(page));
562 set_compound_page_dtor(page, TRANSHUGE_PAGE_DTOR);
565 static inline bool is_transparent_hugepage(struct page *page)
567 if (!PageCompound(page))
570 page = compound_head(page);
571 return is_huge_zero_page(page) ||
572 page[1].compound_dtor == TRANSHUGE_PAGE_DTOR;
575 static unsigned long __thp_get_unmapped_area(struct file *filp,
576 unsigned long addr, unsigned long len,
577 loff_t off, unsigned long flags, unsigned long size)
579 loff_t off_end = off + len;
580 loff_t off_align = round_up(off, size);
581 unsigned long len_pad, ret;
583 if (off_end <= off_align || (off_end - off_align) < size)
586 len_pad = len + size;
587 if (len_pad < len || (off + len_pad) < off)
590 ret = current->mm->get_unmapped_area(filp, addr, len_pad,
591 off >> PAGE_SHIFT, flags);
594 * The failure might be due to length padding. The caller will retry
595 * without the padding.
597 if (IS_ERR_VALUE(ret))
601 * Do not try to align to THP boundary if allocation at the address
607 ret += (off - ret) & (size - 1);
611 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
612 unsigned long len, unsigned long pgoff, unsigned long flags)
615 loff_t off = (loff_t)pgoff << PAGE_SHIFT;
617 ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE);
621 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
623 EXPORT_SYMBOL_GPL(thp_get_unmapped_area);
625 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf,
626 struct page *page, gfp_t gfp)
628 struct vm_area_struct *vma = vmf->vma;
630 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
633 VM_BUG_ON_PAGE(!PageCompound(page), page);
635 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, gfp)) {
637 count_vm_event(THP_FAULT_FALLBACK);
638 count_vm_event(THP_FAULT_FALLBACK_CHARGE);
639 return VM_FAULT_FALLBACK;
641 cgroup_throttle_swaprate(page, gfp);
643 pgtable = pte_alloc_one(vma->vm_mm);
644 if (unlikely(!pgtable)) {
649 clear_huge_page(page, vmf->address, HPAGE_PMD_NR);
651 * The memory barrier inside __SetPageUptodate makes sure that
652 * clear_huge_page writes become visible before the set_pmd_at()
655 __SetPageUptodate(page);
657 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
658 if (unlikely(!pmd_none(*vmf->pmd))) {
663 ret = check_stable_address_space(vma->vm_mm);
667 /* Deliver the page fault to userland */
668 if (userfaultfd_missing(vma)) {
669 spin_unlock(vmf->ptl);
671 pte_free(vma->vm_mm, pgtable);
672 ret = handle_userfault(vmf, VM_UFFD_MISSING);
673 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
677 entry = mk_huge_pmd(page, vma->vm_page_prot);
678 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
679 page_add_new_anon_rmap(page, vma, haddr);
680 lru_cache_add_inactive_or_unevictable(page, vma);
681 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
682 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
683 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
684 add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
685 mm_inc_nr_ptes(vma->vm_mm);
686 spin_unlock(vmf->ptl);
687 count_vm_event(THP_FAULT_ALLOC);
688 count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
693 spin_unlock(vmf->ptl);
696 pte_free(vma->vm_mm, pgtable);
703 * always: directly stall for all thp allocations
704 * defer: wake kswapd and fail if not immediately available
705 * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise
706 * fail if not immediately available
707 * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately
709 * never: never stall for any thp allocation
711 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)
713 const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE);
715 /* Always do synchronous compaction */
716 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
717 return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);
719 /* Kick kcompactd and fail quickly */
720 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
721 return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;
723 /* Synchronous compaction if madvised, otherwise kick kcompactd */
724 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags))
725 return GFP_TRANSHUGE_LIGHT |
726 (vma_madvised ? __GFP_DIRECT_RECLAIM :
727 __GFP_KSWAPD_RECLAIM);
729 /* Only do synchronous compaction if madvised */
730 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
731 return GFP_TRANSHUGE_LIGHT |
732 (vma_madvised ? __GFP_DIRECT_RECLAIM : 0);
734 return GFP_TRANSHUGE_LIGHT;
737 /* Caller must hold page table lock. */
738 static void set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
739 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
740 struct page *zero_page)
745 entry = mk_pmd(zero_page, vma->vm_page_prot);
746 entry = pmd_mkhuge(entry);
748 pgtable_trans_huge_deposit(mm, pmd, pgtable);
749 set_pmd_at(mm, haddr, pmd, entry);
753 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf)
755 struct vm_area_struct *vma = vmf->vma;
758 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
760 if (!transhuge_vma_suitable(vma, haddr))
761 return VM_FAULT_FALLBACK;
762 if (unlikely(anon_vma_prepare(vma)))
764 khugepaged_enter_vma(vma, vma->vm_flags);
766 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
767 !mm_forbids_zeropage(vma->vm_mm) &&
768 transparent_hugepage_use_zero_page()) {
770 struct page *zero_page;
772 pgtable = pte_alloc_one(vma->vm_mm);
773 if (unlikely(!pgtable))
775 zero_page = mm_get_huge_zero_page(vma->vm_mm);
776 if (unlikely(!zero_page)) {
777 pte_free(vma->vm_mm, pgtable);
778 count_vm_event(THP_FAULT_FALLBACK);
779 return VM_FAULT_FALLBACK;
781 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
783 if (pmd_none(*vmf->pmd)) {
784 ret = check_stable_address_space(vma->vm_mm);
786 spin_unlock(vmf->ptl);
787 pte_free(vma->vm_mm, pgtable);
788 } else if (userfaultfd_missing(vma)) {
789 spin_unlock(vmf->ptl);
790 pte_free(vma->vm_mm, pgtable);
791 ret = handle_userfault(vmf, VM_UFFD_MISSING);
792 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
794 set_huge_zero_page(pgtable, vma->vm_mm, vma,
795 haddr, vmf->pmd, zero_page);
796 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
797 spin_unlock(vmf->ptl);
800 spin_unlock(vmf->ptl);
801 pte_free(vma->vm_mm, pgtable);
805 gfp = vma_thp_gfp_mask(vma);
806 folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, vma, haddr, true);
807 if (unlikely(!folio)) {
808 count_vm_event(THP_FAULT_FALLBACK);
809 return VM_FAULT_FALLBACK;
811 return __do_huge_pmd_anonymous_page(vmf, &folio->page, gfp);
814 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
815 pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write,
818 struct mm_struct *mm = vma->vm_mm;
822 ptl = pmd_lock(mm, pmd);
823 if (!pmd_none(*pmd)) {
825 if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) {
826 WARN_ON_ONCE(!is_huge_zero_pmd(*pmd));
829 entry = pmd_mkyoung(*pmd);
830 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
831 if (pmdp_set_access_flags(vma, addr, pmd, entry, 1))
832 update_mmu_cache_pmd(vma, addr, pmd);
838 entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
839 if (pfn_t_devmap(pfn))
840 entry = pmd_mkdevmap(entry);
842 entry = pmd_mkyoung(pmd_mkdirty(entry));
843 entry = maybe_pmd_mkwrite(entry, vma);
847 pgtable_trans_huge_deposit(mm, pmd, pgtable);
852 set_pmd_at(mm, addr, pmd, entry);
853 update_mmu_cache_pmd(vma, addr, pmd);
858 pte_free(mm, pgtable);
862 * vmf_insert_pfn_pmd_prot - insert a pmd size pfn
863 * @vmf: Structure describing the fault
864 * @pfn: pfn to insert
865 * @pgprot: page protection to use
866 * @write: whether it's a write fault
868 * Insert a pmd size pfn. See vmf_insert_pfn() for additional info and
869 * also consult the vmf_insert_mixed_prot() documentation when
870 * @pgprot != @vmf->vma->vm_page_prot.
872 * Return: vm_fault_t value.
874 vm_fault_t vmf_insert_pfn_pmd_prot(struct vm_fault *vmf, pfn_t pfn,
875 pgprot_t pgprot, bool write)
877 unsigned long addr = vmf->address & PMD_MASK;
878 struct vm_area_struct *vma = vmf->vma;
879 pgtable_t pgtable = NULL;
882 * If we had pmd_special, we could avoid all these restrictions,
883 * but we need to be consistent with PTEs and architectures that
884 * can't support a 'special' bit.
886 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
888 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
889 (VM_PFNMAP|VM_MIXEDMAP));
890 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
892 if (addr < vma->vm_start || addr >= vma->vm_end)
893 return VM_FAULT_SIGBUS;
895 if (arch_needs_pgtable_deposit()) {
896 pgtable = pte_alloc_one(vma->vm_mm);
901 track_pfn_insert(vma, &pgprot, pfn);
903 insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable);
904 return VM_FAULT_NOPAGE;
906 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd_prot);
908 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
909 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)
911 if (likely(vma->vm_flags & VM_WRITE))
912 pud = pud_mkwrite(pud);
916 static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr,
917 pud_t *pud, pfn_t pfn, pgprot_t prot, bool write)
919 struct mm_struct *mm = vma->vm_mm;
923 ptl = pud_lock(mm, pud);
924 if (!pud_none(*pud)) {
926 if (pud_pfn(*pud) != pfn_t_to_pfn(pfn)) {
927 WARN_ON_ONCE(!is_huge_zero_pud(*pud));
930 entry = pud_mkyoung(*pud);
931 entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma);
932 if (pudp_set_access_flags(vma, addr, pud, entry, 1))
933 update_mmu_cache_pud(vma, addr, pud);
938 entry = pud_mkhuge(pfn_t_pud(pfn, prot));
939 if (pfn_t_devmap(pfn))
940 entry = pud_mkdevmap(entry);
942 entry = pud_mkyoung(pud_mkdirty(entry));
943 entry = maybe_pud_mkwrite(entry, vma);
945 set_pud_at(mm, addr, pud, entry);
946 update_mmu_cache_pud(vma, addr, pud);
953 * vmf_insert_pfn_pud_prot - insert a pud size pfn
954 * @vmf: Structure describing the fault
955 * @pfn: pfn to insert
956 * @pgprot: page protection to use
957 * @write: whether it's a write fault
959 * Insert a pud size pfn. See vmf_insert_pfn() for additional info and
960 * also consult the vmf_insert_mixed_prot() documentation when
961 * @pgprot != @vmf->vma->vm_page_prot.
963 * Return: vm_fault_t value.
965 vm_fault_t vmf_insert_pfn_pud_prot(struct vm_fault *vmf, pfn_t pfn,
966 pgprot_t pgprot, bool write)
968 unsigned long addr = vmf->address & PUD_MASK;
969 struct vm_area_struct *vma = vmf->vma;
972 * If we had pud_special, we could avoid all these restrictions,
973 * but we need to be consistent with PTEs and architectures that
974 * can't support a 'special' bit.
976 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
978 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
979 (VM_PFNMAP|VM_MIXEDMAP));
980 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
982 if (addr < vma->vm_start || addr >= vma->vm_end)
983 return VM_FAULT_SIGBUS;
985 track_pfn_insert(vma, &pgprot, pfn);
987 insert_pfn_pud(vma, addr, vmf->pud, pfn, pgprot, write);
988 return VM_FAULT_NOPAGE;
990 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud_prot);
991 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
993 static void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
994 pmd_t *pmd, int flags)
998 _pmd = pmd_mkyoung(*pmd);
999 if (flags & FOLL_WRITE)
1000 _pmd = pmd_mkdirty(_pmd);
1001 if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1002 pmd, _pmd, flags & FOLL_WRITE))
1003 update_mmu_cache_pmd(vma, addr, pmd);
1006 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
1007 pmd_t *pmd, int flags, struct dev_pagemap **pgmap)
1009 unsigned long pfn = pmd_pfn(*pmd);
1010 struct mm_struct *mm = vma->vm_mm;
1013 assert_spin_locked(pmd_lockptr(mm, pmd));
1016 * When we COW a devmap PMD entry, we split it into PTEs, so we should
1017 * not be in this function with `flags & FOLL_COW` set.
1019 WARN_ONCE(flags & FOLL_COW, "mm: In follow_devmap_pmd with FOLL_COW set");
1021 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
1022 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
1023 (FOLL_PIN | FOLL_GET)))
1026 if (flags & FOLL_WRITE && !pmd_write(*pmd))
1029 if (pmd_present(*pmd) && pmd_devmap(*pmd))
1034 if (flags & FOLL_TOUCH)
1035 touch_pmd(vma, addr, pmd, flags);
1038 * device mapped pages can only be returned if the
1039 * caller will manage the page reference count.
1041 if (!(flags & (FOLL_GET | FOLL_PIN)))
1042 return ERR_PTR(-EEXIST);
1044 pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1045 *pgmap = get_dev_pagemap(pfn, *pgmap);
1047 return ERR_PTR(-EFAULT);
1048 page = pfn_to_page(pfn);
1049 if (!try_grab_page(page, flags))
1050 page = ERR_PTR(-ENOMEM);
1055 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1056 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1057 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1059 spinlock_t *dst_ptl, *src_ptl;
1060 struct page *src_page;
1062 pgtable_t pgtable = NULL;
1065 /* Skip if can be re-fill on fault */
1066 if (!vma_is_anonymous(dst_vma))
1069 pgtable = pte_alloc_one(dst_mm);
1070 if (unlikely(!pgtable))
1073 dst_ptl = pmd_lock(dst_mm, dst_pmd);
1074 src_ptl = pmd_lockptr(src_mm, src_pmd);
1075 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1080 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1081 if (unlikely(is_swap_pmd(pmd))) {
1082 swp_entry_t entry = pmd_to_swp_entry(pmd);
1084 VM_BUG_ON(!is_pmd_migration_entry(pmd));
1085 if (!is_readable_migration_entry(entry)) {
1086 entry = make_readable_migration_entry(
1088 pmd = swp_entry_to_pmd(entry);
1089 if (pmd_swp_soft_dirty(*src_pmd))
1090 pmd = pmd_swp_mksoft_dirty(pmd);
1091 if (pmd_swp_uffd_wp(*src_pmd))
1092 pmd = pmd_swp_mkuffd_wp(pmd);
1093 set_pmd_at(src_mm, addr, src_pmd, pmd);
1095 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1096 mm_inc_nr_ptes(dst_mm);
1097 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1098 if (!userfaultfd_wp(dst_vma))
1099 pmd = pmd_swp_clear_uffd_wp(pmd);
1100 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1106 if (unlikely(!pmd_trans_huge(pmd))) {
1107 pte_free(dst_mm, pgtable);
1111 * When page table lock is held, the huge zero pmd should not be
1112 * under splitting since we don't split the page itself, only pmd to
1115 if (is_huge_zero_pmd(pmd)) {
1117 * get_huge_zero_page() will never allocate a new page here,
1118 * since we already have a zero page to copy. It just takes a
1121 mm_get_huge_zero_page(dst_mm);
1125 src_page = pmd_page(pmd);
1126 VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1129 if (unlikely(page_try_dup_anon_rmap(src_page, true, src_vma))) {
1130 /* Page maybe pinned: split and retry the fault on PTEs. */
1132 pte_free(dst_mm, pgtable);
1133 spin_unlock(src_ptl);
1134 spin_unlock(dst_ptl);
1135 __split_huge_pmd(src_vma, src_pmd, addr, false, NULL);
1138 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1140 mm_inc_nr_ptes(dst_mm);
1141 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1142 pmdp_set_wrprotect(src_mm, addr, src_pmd);
1143 if (!userfaultfd_wp(dst_vma))
1144 pmd = pmd_clear_uffd_wp(pmd);
1145 pmd = pmd_mkold(pmd_wrprotect(pmd));
1146 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1150 spin_unlock(src_ptl);
1151 spin_unlock(dst_ptl);
1156 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1157 static void touch_pud(struct vm_area_struct *vma, unsigned long addr,
1158 pud_t *pud, int flags)
1162 _pud = pud_mkyoung(*pud);
1163 if (flags & FOLL_WRITE)
1164 _pud = pud_mkdirty(_pud);
1165 if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK,
1166 pud, _pud, flags & FOLL_WRITE))
1167 update_mmu_cache_pud(vma, addr, pud);
1170 struct page *follow_devmap_pud(struct vm_area_struct *vma, unsigned long addr,
1171 pud_t *pud, int flags, struct dev_pagemap **pgmap)
1173 unsigned long pfn = pud_pfn(*pud);
1174 struct mm_struct *mm = vma->vm_mm;
1177 assert_spin_locked(pud_lockptr(mm, pud));
1179 if (flags & FOLL_WRITE && !pud_write(*pud))
1182 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
1183 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
1184 (FOLL_PIN | FOLL_GET)))
1187 if (pud_present(*pud) && pud_devmap(*pud))
1192 if (flags & FOLL_TOUCH)
1193 touch_pud(vma, addr, pud, flags);
1196 * device mapped pages can only be returned if the
1197 * caller will manage the page reference count.
1199 * At least one of FOLL_GET | FOLL_PIN must be set, so assert that here:
1201 if (!(flags & (FOLL_GET | FOLL_PIN)))
1202 return ERR_PTR(-EEXIST);
1204 pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
1205 *pgmap = get_dev_pagemap(pfn, *pgmap);
1207 return ERR_PTR(-EFAULT);
1208 page = pfn_to_page(pfn);
1209 if (!try_grab_page(page, flags))
1210 page = ERR_PTR(-ENOMEM);
1215 int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1216 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1217 struct vm_area_struct *vma)
1219 spinlock_t *dst_ptl, *src_ptl;
1223 dst_ptl = pud_lock(dst_mm, dst_pud);
1224 src_ptl = pud_lockptr(src_mm, src_pud);
1225 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1229 if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud)))
1233 * When page table lock is held, the huge zero pud should not be
1234 * under splitting since we don't split the page itself, only pud to
1237 if (is_huge_zero_pud(pud)) {
1238 /* No huge zero pud yet */
1242 * TODO: once we support anonymous pages, use page_try_dup_anon_rmap()
1243 * and split if duplicating fails.
1245 pudp_set_wrprotect(src_mm, addr, src_pud);
1246 pud = pud_mkold(pud_wrprotect(pud));
1247 set_pud_at(dst_mm, addr, dst_pud, pud);
1251 spin_unlock(src_ptl);
1252 spin_unlock(dst_ptl);
1256 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)
1259 unsigned long haddr;
1260 bool write = vmf->flags & FAULT_FLAG_WRITE;
1262 vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud);
1263 if (unlikely(!pud_same(*vmf->pud, orig_pud)))
1266 entry = pud_mkyoung(orig_pud);
1268 entry = pud_mkdirty(entry);
1269 haddr = vmf->address & HPAGE_PUD_MASK;
1270 if (pudp_set_access_flags(vmf->vma, haddr, vmf->pud, entry, write))
1271 update_mmu_cache_pud(vmf->vma, vmf->address, vmf->pud);
1274 spin_unlock(vmf->ptl);
1276 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1278 void huge_pmd_set_accessed(struct vm_fault *vmf)
1281 unsigned long haddr;
1282 bool write = vmf->flags & FAULT_FLAG_WRITE;
1283 pmd_t orig_pmd = vmf->orig_pmd;
1285 vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd);
1286 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
1289 entry = pmd_mkyoung(orig_pmd);
1291 entry = pmd_mkdirty(entry);
1292 haddr = vmf->address & HPAGE_PMD_MASK;
1293 if (pmdp_set_access_flags(vmf->vma, haddr, vmf->pmd, entry, write))
1294 update_mmu_cache_pmd(vmf->vma, vmf->address, vmf->pmd);
1297 spin_unlock(vmf->ptl);
1300 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
1302 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
1303 struct vm_area_struct *vma = vmf->vma;
1305 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1306 pmd_t orig_pmd = vmf->orig_pmd;
1308 vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
1309 VM_BUG_ON_VMA(!vma->anon_vma, vma);
1311 VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE));
1312 VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE));
1314 if (is_huge_zero_pmd(orig_pmd))
1317 spin_lock(vmf->ptl);
1319 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1320 spin_unlock(vmf->ptl);
1324 page = pmd_page(orig_pmd);
1325 VM_BUG_ON_PAGE(!PageHead(page), page);
1327 /* Early check when only holding the PT lock. */
1328 if (PageAnonExclusive(page))
1331 if (!trylock_page(page)) {
1333 spin_unlock(vmf->ptl);
1335 spin_lock(vmf->ptl);
1336 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1337 spin_unlock(vmf->ptl);
1345 /* Recheck after temporarily dropping the PT lock. */
1346 if (PageAnonExclusive(page)) {
1352 * See do_wp_page(): we can only reuse the page exclusively if there are
1353 * no additional references. Note that we always drain the LRU
1354 * pagevecs immediately after adding a THP.
1356 if (page_count(page) > 1 + PageSwapCache(page) * thp_nr_pages(page))
1357 goto unlock_fallback;
1358 if (PageSwapCache(page))
1359 try_to_free_swap(page);
1360 if (page_count(page) == 1) {
1363 page_move_anon_rmap(page, vma);
1366 if (unlikely(unshare)) {
1367 spin_unlock(vmf->ptl);
1370 entry = pmd_mkyoung(orig_pmd);
1371 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1372 if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1))
1373 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1374 spin_unlock(vmf->ptl);
1375 return VM_FAULT_WRITE;
1380 spin_unlock(vmf->ptl);
1382 __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
1383 return VM_FAULT_FALLBACK;
1387 * FOLL_FORCE can write to even unwritable pmd's, but only
1388 * after we've gone through a COW cycle and they are dirty.
1390 static inline bool can_follow_write_pmd(pmd_t pmd, unsigned int flags)
1392 return pmd_write(pmd) ||
1393 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pmd_dirty(pmd));
1396 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1401 struct mm_struct *mm = vma->vm_mm;
1402 struct page *page = NULL;
1404 assert_spin_locked(pmd_lockptr(mm, pmd));
1406 if (flags & FOLL_WRITE && !can_follow_write_pmd(*pmd, flags))
1409 /* Avoid dumping huge zero page */
1410 if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1411 return ERR_PTR(-EFAULT);
1413 /* Full NUMA hinting faults to serialise migration in fault paths */
1414 if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
1417 page = pmd_page(*pmd);
1418 VM_BUG_ON_PAGE(!PageHead(page) && !is_zone_device_page(page), page);
1420 if (!pmd_write(*pmd) && gup_must_unshare(flags, page))
1421 return ERR_PTR(-EMLINK);
1423 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
1424 !PageAnonExclusive(page), page);
1426 if (!try_grab_page(page, flags))
1427 return ERR_PTR(-ENOMEM);
1429 if (flags & FOLL_TOUCH)
1430 touch_pmd(vma, addr, pmd, flags);
1432 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1433 VM_BUG_ON_PAGE(!PageCompound(page) && !is_zone_device_page(page), page);
1439 /* NUMA hinting page fault entry point for trans huge pmds */
1440 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf)
1442 struct vm_area_struct *vma = vmf->vma;
1443 pmd_t oldpmd = vmf->orig_pmd;
1446 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1447 int page_nid = NUMA_NO_NODE;
1448 int target_nid, last_cpupid = -1;
1449 bool migrated = false;
1450 bool was_writable = pmd_savedwrite(oldpmd);
1453 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1454 if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1455 spin_unlock(vmf->ptl);
1459 pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1460 page = vm_normal_page_pmd(vma, haddr, pmd);
1464 /* See similar comment in do_numa_page for explanation */
1466 flags |= TNF_NO_GROUP;
1468 page_nid = page_to_nid(page);
1469 last_cpupid = page_cpupid_last(page);
1470 target_nid = numa_migrate_prep(page, vma, haddr, page_nid,
1473 if (target_nid == NUMA_NO_NODE) {
1478 spin_unlock(vmf->ptl);
1480 migrated = migrate_misplaced_page(page, vma, target_nid);
1482 flags |= TNF_MIGRATED;
1483 page_nid = target_nid;
1485 flags |= TNF_MIGRATE_FAIL;
1486 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1487 if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1488 spin_unlock(vmf->ptl);
1495 if (page_nid != NUMA_NO_NODE)
1496 task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR,
1502 /* Restore the PMD */
1503 pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1504 pmd = pmd_mkyoung(pmd);
1506 pmd = pmd_mkwrite(pmd);
1507 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
1508 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1509 spin_unlock(vmf->ptl);
1514 * Return true if we do MADV_FREE successfully on entire pmd page.
1515 * Otherwise, return false.
1517 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1518 pmd_t *pmd, unsigned long addr, unsigned long next)
1523 struct mm_struct *mm = tlb->mm;
1526 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1528 ptl = pmd_trans_huge_lock(pmd, vma);
1533 if (is_huge_zero_pmd(orig_pmd))
1536 if (unlikely(!pmd_present(orig_pmd))) {
1537 VM_BUG_ON(thp_migration_supported() &&
1538 !is_pmd_migration_entry(orig_pmd));
1542 page = pmd_page(orig_pmd);
1544 * If other processes are mapping this page, we couldn't discard
1545 * the page unless they all do MADV_FREE so let's skip the page.
1547 if (total_mapcount(page) != 1)
1550 if (!trylock_page(page))
1554 * If user want to discard part-pages of THP, split it so MADV_FREE
1555 * will deactivate only them.
1557 if (next - addr != HPAGE_PMD_SIZE) {
1560 split_huge_page(page);
1566 if (PageDirty(page))
1567 ClearPageDirty(page);
1570 if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1571 pmdp_invalidate(vma, addr, pmd);
1572 orig_pmd = pmd_mkold(orig_pmd);
1573 orig_pmd = pmd_mkclean(orig_pmd);
1575 set_pmd_at(mm, addr, pmd, orig_pmd);
1576 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1579 mark_page_lazyfree(page);
1587 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
1591 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1592 pte_free(mm, pgtable);
1596 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1597 pmd_t *pmd, unsigned long addr)
1602 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1604 ptl = __pmd_trans_huge_lock(pmd, vma);
1608 * For architectures like ppc64 we look at deposited pgtable
1609 * when calling pmdp_huge_get_and_clear. So do the
1610 * pgtable_trans_huge_withdraw after finishing pmdp related
1613 orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
1615 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1616 if (vma_is_special_huge(vma)) {
1617 if (arch_needs_pgtable_deposit())
1618 zap_deposited_table(tlb->mm, pmd);
1620 } else if (is_huge_zero_pmd(orig_pmd)) {
1621 zap_deposited_table(tlb->mm, pmd);
1624 struct page *page = NULL;
1625 int flush_needed = 1;
1627 if (pmd_present(orig_pmd)) {
1628 page = pmd_page(orig_pmd);
1629 page_remove_rmap(page, vma, true);
1630 VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1631 VM_BUG_ON_PAGE(!PageHead(page), page);
1632 } else if (thp_migration_supported()) {
1635 VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
1636 entry = pmd_to_swp_entry(orig_pmd);
1637 page = pfn_swap_entry_to_page(entry);
1640 WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
1642 if (PageAnon(page)) {
1643 zap_deposited_table(tlb->mm, pmd);
1644 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1646 if (arch_needs_pgtable_deposit())
1647 zap_deposited_table(tlb->mm, pmd);
1648 add_mm_counter(tlb->mm, mm_counter_file(page), -HPAGE_PMD_NR);
1653 tlb_remove_page_size(tlb, page, HPAGE_PMD_SIZE);
1658 #ifndef pmd_move_must_withdraw
1659 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
1660 spinlock_t *old_pmd_ptl,
1661 struct vm_area_struct *vma)
1664 * With split pmd lock we also need to move preallocated
1665 * PTE page table if new_pmd is on different PMD page table.
1667 * We also don't deposit and withdraw tables for file pages.
1669 return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
1673 static pmd_t move_soft_dirty_pmd(pmd_t pmd)
1675 #ifdef CONFIG_MEM_SOFT_DIRTY
1676 if (unlikely(is_pmd_migration_entry(pmd)))
1677 pmd = pmd_swp_mksoft_dirty(pmd);
1678 else if (pmd_present(pmd))
1679 pmd = pmd_mksoft_dirty(pmd);
1684 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
1685 unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
1687 spinlock_t *old_ptl, *new_ptl;
1689 struct mm_struct *mm = vma->vm_mm;
1690 bool force_flush = false;
1693 * The destination pmd shouldn't be established, free_pgtables()
1694 * should have release it.
1696 if (WARN_ON(!pmd_none(*new_pmd))) {
1697 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1702 * We don't have to worry about the ordering of src and dst
1703 * ptlocks because exclusive mmap_lock prevents deadlock.
1705 old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1707 new_ptl = pmd_lockptr(mm, new_pmd);
1708 if (new_ptl != old_ptl)
1709 spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1710 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1711 if (pmd_present(pmd))
1713 VM_BUG_ON(!pmd_none(*new_pmd));
1715 if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
1717 pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1718 pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1720 pmd = move_soft_dirty_pmd(pmd);
1721 set_pmd_at(mm, new_addr, new_pmd, pmd);
1723 flush_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
1724 if (new_ptl != old_ptl)
1725 spin_unlock(new_ptl);
1726 spin_unlock(old_ptl);
1734 * - 0 if PMD could not be locked
1735 * - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
1736 * or if prot_numa but THP migration is not supported
1737 * - HPAGE_PMD_NR if protections changed and TLB flush necessary
1739 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1740 pmd_t *pmd, unsigned long addr, pgprot_t newprot,
1741 unsigned long cp_flags)
1743 struct mm_struct *mm = vma->vm_mm;
1745 pmd_t oldpmd, entry;
1746 bool preserve_write;
1748 bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
1749 bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
1750 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
1752 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1754 if (prot_numa && !thp_migration_supported())
1757 ptl = __pmd_trans_huge_lock(pmd, vma);
1761 preserve_write = prot_numa && pmd_write(*pmd);
1764 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1765 if (is_swap_pmd(*pmd)) {
1766 swp_entry_t entry = pmd_to_swp_entry(*pmd);
1767 struct page *page = pfn_swap_entry_to_page(entry);
1769 VM_BUG_ON(!is_pmd_migration_entry(*pmd));
1770 if (is_writable_migration_entry(entry)) {
1773 * A protection check is difficult so
1774 * just be safe and disable write
1777 entry = make_readable_exclusive_migration_entry(swp_offset(entry));
1779 entry = make_readable_migration_entry(swp_offset(entry));
1780 newpmd = swp_entry_to_pmd(entry);
1781 if (pmd_swp_soft_dirty(*pmd))
1782 newpmd = pmd_swp_mksoft_dirty(newpmd);
1783 if (pmd_swp_uffd_wp(*pmd))
1784 newpmd = pmd_swp_mkuffd_wp(newpmd);
1785 set_pmd_at(mm, addr, pmd, newpmd);
1794 * Avoid trapping faults against the zero page. The read-only
1795 * data is likely to be read-cached on the local CPU and
1796 * local/remote hits to the zero page are not interesting.
1798 if (is_huge_zero_pmd(*pmd))
1801 if (pmd_protnone(*pmd))
1804 page = pmd_page(*pmd);
1806 * Skip scanning top tier node if normal numa
1807 * balancing is disabled
1809 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
1810 node_is_toptier(page_to_nid(page)))
1814 * In case prot_numa, we are under mmap_read_lock(mm). It's critical
1815 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
1816 * which is also under mmap_read_lock(mm):
1819 * change_huge_pmd(prot_numa=1)
1820 * pmdp_huge_get_and_clear_notify()
1821 * madvise_dontneed()
1823 * pmd_trans_huge(*pmd) == 0 (without ptl)
1826 * // pmd is re-established
1828 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
1829 * which may break userspace.
1831 * pmdp_invalidate_ad() is required to make sure we don't miss
1832 * dirty/young flags set by hardware.
1834 oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
1836 entry = pmd_modify(oldpmd, newprot);
1838 entry = pmd_mk_savedwrite(entry);
1840 entry = pmd_wrprotect(entry);
1841 entry = pmd_mkuffd_wp(entry);
1842 } else if (uffd_wp_resolve) {
1844 * Leave the write bit to be handled by PF interrupt
1845 * handler, then things like COW could be properly
1848 entry = pmd_clear_uffd_wp(entry);
1851 set_pmd_at(mm, addr, pmd, entry);
1853 if (huge_pmd_needs_flush(oldpmd, entry))
1854 tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
1856 BUG_ON(vma_is_anonymous(vma) && !preserve_write && pmd_write(entry));
1863 * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
1865 * Note that if it returns page table lock pointer, this routine returns without
1866 * unlocking page table lock. So callers must unlock it.
1868 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1871 ptl = pmd_lock(vma->vm_mm, pmd);
1872 if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
1880 * Returns true if a given pud maps a thp, false otherwise.
1882 * Note that if it returns true, this routine returns without unlocking page
1883 * table lock. So callers must unlock it.
1885 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
1889 ptl = pud_lock(vma->vm_mm, pud);
1890 if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
1896 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1897 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
1898 pud_t *pud, unsigned long addr)
1902 ptl = __pud_trans_huge_lock(pud, vma);
1906 * For architectures like ppc64 we look at deposited pgtable
1907 * when calling pudp_huge_get_and_clear. So do the
1908 * pgtable_trans_huge_withdraw after finishing pudp related
1911 pudp_huge_get_and_clear_full(tlb->mm, addr, pud, tlb->fullmm);
1912 tlb_remove_pud_tlb_entry(tlb, pud, addr);
1913 if (vma_is_special_huge(vma)) {
1915 /* No zero page support yet */
1917 /* No support for anonymous PUD pages yet */
1923 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
1924 unsigned long haddr)
1926 VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
1927 VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
1928 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
1929 VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
1931 count_vm_event(THP_SPLIT_PUD);
1933 pudp_huge_clear_flush_notify(vma, haddr, pud);
1936 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
1937 unsigned long address)
1940 struct mmu_notifier_range range;
1942 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1943 address & HPAGE_PUD_MASK,
1944 (address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
1945 mmu_notifier_invalidate_range_start(&range);
1946 ptl = pud_lock(vma->vm_mm, pud);
1947 if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
1949 __split_huge_pud_locked(vma, pud, range.start);
1954 * No need to double call mmu_notifier->invalidate_range() callback as
1955 * the above pudp_huge_clear_flush_notify() did already call it.
1957 mmu_notifier_invalidate_range_only_end(&range);
1959 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1961 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
1962 unsigned long haddr, pmd_t *pmd)
1964 struct mm_struct *mm = vma->vm_mm;
1970 * Leave pmd empty until pte is filled note that it is fine to delay
1971 * notification until mmu_notifier_invalidate_range_end() as we are
1972 * replacing a zero pmd write protected page with a zero pte write
1975 * See Documentation/mm/mmu_notifier.rst
1977 pmdp_huge_clear_flush(vma, haddr, pmd);
1979 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1980 pmd_populate(mm, &_pmd, pgtable);
1982 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1984 entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
1985 entry = pte_mkspecial(entry);
1986 pte = pte_offset_map(&_pmd, haddr);
1987 VM_BUG_ON(!pte_none(*pte));
1988 set_pte_at(mm, haddr, pte, entry);
1991 smp_wmb(); /* make pte visible before pmd */
1992 pmd_populate(mm, pmd, pgtable);
1995 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
1996 unsigned long haddr, bool freeze)
1998 struct mm_struct *mm = vma->vm_mm;
2001 pmd_t old_pmd, _pmd;
2002 bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
2003 bool anon_exclusive = false;
2007 VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2008 VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2009 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
2010 VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
2011 && !pmd_devmap(*pmd));
2013 count_vm_event(THP_SPLIT_PMD);
2015 if (!vma_is_anonymous(vma)) {
2016 old_pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2018 * We are going to unmap this huge page. So
2019 * just go ahead and zap it
2021 if (arch_needs_pgtable_deposit())
2022 zap_deposited_table(mm, pmd);
2023 if (vma_is_special_huge(vma))
2025 if (unlikely(is_pmd_migration_entry(old_pmd))) {
2028 entry = pmd_to_swp_entry(old_pmd);
2029 page = pfn_swap_entry_to_page(entry);
2031 page = pmd_page(old_pmd);
2032 if (!PageDirty(page) && pmd_dirty(old_pmd))
2033 set_page_dirty(page);
2034 if (!PageReferenced(page) && pmd_young(old_pmd))
2035 SetPageReferenced(page);
2036 page_remove_rmap(page, vma, true);
2039 add_mm_counter(mm, mm_counter_file(page), -HPAGE_PMD_NR);
2043 if (is_huge_zero_pmd(*pmd)) {
2045 * FIXME: Do we want to invalidate secondary mmu by calling
2046 * mmu_notifier_invalidate_range() see comments below inside
2047 * __split_huge_pmd() ?
2049 * We are going from a zero huge page write protected to zero
2050 * small page also write protected so it does not seems useful
2051 * to invalidate secondary mmu at this time.
2053 return __split_huge_zero_page_pmd(vma, haddr, pmd);
2057 * Up to this point the pmd is present and huge and userland has the
2058 * whole access to the hugepage during the split (which happens in
2059 * place). If we overwrite the pmd with the not-huge version pointing
2060 * to the pte here (which of course we could if all CPUs were bug
2061 * free), userland could trigger a small page size TLB miss on the
2062 * small sized TLB while the hugepage TLB entry is still established in
2063 * the huge TLB. Some CPU doesn't like that.
2064 * See http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2065 * 383 on page 105. Intel should be safe but is also warns that it's
2066 * only safe if the permission and cache attributes of the two entries
2067 * loaded in the two TLB is identical (which should be the case here).
2068 * But it is generally safer to never allow small and huge TLB entries
2069 * for the same virtual address to be loaded simultaneously. So instead
2070 * of doing "pmd_populate(); flush_pmd_tlb_range();" we first mark the
2071 * current pmd notpresent (atomically because here the pmd_trans_huge
2072 * must remain set at all times on the pmd until the split is complete
2073 * for this pmd), then we flush the SMP TLB and finally we write the
2074 * non-huge version of the pmd entry with pmd_populate.
2076 old_pmd = pmdp_invalidate(vma, haddr, pmd);
2078 pmd_migration = is_pmd_migration_entry(old_pmd);
2079 if (unlikely(pmd_migration)) {
2082 entry = pmd_to_swp_entry(old_pmd);
2083 page = pfn_swap_entry_to_page(entry);
2084 write = is_writable_migration_entry(entry);
2086 anon_exclusive = is_readable_exclusive_migration_entry(entry);
2088 soft_dirty = pmd_swp_soft_dirty(old_pmd);
2089 uffd_wp = pmd_swp_uffd_wp(old_pmd);
2091 page = pmd_page(old_pmd);
2092 if (pmd_dirty(old_pmd))
2094 write = pmd_write(old_pmd);
2095 young = pmd_young(old_pmd);
2096 soft_dirty = pmd_soft_dirty(old_pmd);
2097 uffd_wp = pmd_uffd_wp(old_pmd);
2099 VM_BUG_ON_PAGE(!page_count(page), page);
2100 page_ref_add(page, HPAGE_PMD_NR - 1);
2103 * Without "freeze", we'll simply split the PMD, propagating the
2104 * PageAnonExclusive() flag for each PTE by setting it for
2105 * each subpage -- no need to (temporarily) clear.
2107 * With "freeze" we want to replace mapped pages by
2108 * migration entries right away. This is only possible if we
2109 * managed to clear PageAnonExclusive() -- see
2110 * set_pmd_migration_entry().
2112 * In case we cannot clear PageAnonExclusive(), split the PMD
2113 * only and let try_to_migrate_one() fail later.
2115 anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
2116 if (freeze && anon_exclusive && page_try_share_anon_rmap(page))
2121 * Withdraw the table only after we mark the pmd entry invalid.
2122 * This's critical for some architectures (Power).
2124 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2125 pmd_populate(mm, &_pmd, pgtable);
2127 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2130 * Note that NUMA hinting access restrictions are not
2131 * transferred to avoid any possibility of altering
2132 * permissions across VMAs.
2134 if (freeze || pmd_migration) {
2135 swp_entry_t swp_entry;
2137 swp_entry = make_writable_migration_entry(
2138 page_to_pfn(page + i));
2139 else if (anon_exclusive)
2140 swp_entry = make_readable_exclusive_migration_entry(
2141 page_to_pfn(page + i));
2143 swp_entry = make_readable_migration_entry(
2144 page_to_pfn(page + i));
2145 entry = swp_entry_to_pte(swp_entry);
2147 entry = pte_swp_mksoft_dirty(entry);
2149 entry = pte_swp_mkuffd_wp(entry);
2151 entry = mk_pte(page + i, READ_ONCE(vma->vm_page_prot));
2152 entry = maybe_mkwrite(entry, vma);
2154 SetPageAnonExclusive(page + i);
2156 entry = pte_wrprotect(entry);
2158 entry = pte_mkold(entry);
2160 entry = pte_mksoft_dirty(entry);
2162 entry = pte_mkuffd_wp(entry);
2164 pte = pte_offset_map(&_pmd, addr);
2165 BUG_ON(!pte_none(*pte));
2166 set_pte_at(mm, addr, pte, entry);
2168 atomic_inc(&page[i]._mapcount);
2172 if (!pmd_migration) {
2174 * Set PG_double_map before dropping compound_mapcount to avoid
2175 * false-negative page_mapped().
2177 if (compound_mapcount(page) > 1 &&
2178 !TestSetPageDoubleMap(page)) {
2179 for (i = 0; i < HPAGE_PMD_NR; i++)
2180 atomic_inc(&page[i]._mapcount);
2183 lock_page_memcg(page);
2184 if (atomic_add_negative(-1, compound_mapcount_ptr(page))) {
2185 /* Last compound_mapcount is gone. */
2186 __mod_lruvec_page_state(page, NR_ANON_THPS,
2188 if (TestClearPageDoubleMap(page)) {
2189 /* No need in mapcount reference anymore */
2190 for (i = 0; i < HPAGE_PMD_NR; i++)
2191 atomic_dec(&page[i]._mapcount);
2194 unlock_page_memcg(page);
2196 /* Above is effectively page_remove_rmap(page, vma, true) */
2197 munlock_vma_page(page, vma, true);
2200 smp_wmb(); /* make pte visible before pmd */
2201 pmd_populate(mm, pmd, pgtable);
2204 for (i = 0; i < HPAGE_PMD_NR; i++) {
2205 page_remove_rmap(page + i, vma, false);
2211 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2212 unsigned long address, bool freeze, struct folio *folio)
2215 struct mmu_notifier_range range;
2217 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
2218 address & HPAGE_PMD_MASK,
2219 (address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2220 mmu_notifier_invalidate_range_start(&range);
2221 ptl = pmd_lock(vma->vm_mm, pmd);
2224 * If caller asks to setup a migration entry, we need a folio to check
2225 * pmd against. Otherwise we can end up replacing wrong folio.
2227 VM_BUG_ON(freeze && !folio);
2228 VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
2230 if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
2231 is_pmd_migration_entry(*pmd)) {
2232 if (folio && folio != page_folio(pmd_page(*pmd)))
2234 __split_huge_pmd_locked(vma, pmd, range.start, freeze);
2240 * No need to double call mmu_notifier->invalidate_range() callback.
2241 * They are 3 cases to consider inside __split_huge_pmd_locked():
2242 * 1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious
2243 * 2) __split_huge_zero_page_pmd() read only zero page and any write
2244 * fault will trigger a flush_notify before pointing to a new page
2245 * (it is fine if the secondary mmu keeps pointing to the old zero
2246 * page in the meantime)
2247 * 3) Split a huge pmd into pte pointing to the same page. No need
2248 * to invalidate secondary tlb entry they are all still valid.
2249 * any further changes to individual pte will notify. So no need
2250 * to call mmu_notifier->invalidate_range()
2252 mmu_notifier_invalidate_range_only_end(&range);
2255 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2256 bool freeze, struct folio *folio)
2263 pgd = pgd_offset(vma->vm_mm, address);
2264 if (!pgd_present(*pgd))
2267 p4d = p4d_offset(pgd, address);
2268 if (!p4d_present(*p4d))
2271 pud = pud_offset(p4d, address);
2272 if (!pud_present(*pud))
2275 pmd = pmd_offset(pud, address);
2277 __split_huge_pmd(vma, pmd, address, freeze, folio);
2280 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2283 * If the new address isn't hpage aligned and it could previously
2284 * contain an hugepage: check if we need to split an huge pmd.
2286 if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2287 range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2288 ALIGN(address, HPAGE_PMD_SIZE)))
2289 split_huge_pmd_address(vma, address, false, NULL);
2292 void vma_adjust_trans_huge(struct vm_area_struct *vma,
2293 unsigned long start,
2297 /* Check if we need to split start first. */
2298 split_huge_pmd_if_needed(vma, start);
2300 /* Check if we need to split end next. */
2301 split_huge_pmd_if_needed(vma, end);
2304 * If we're also updating the vma->vm_next->vm_start,
2305 * check if we need to split it.
2307 if (adjust_next > 0) {
2308 struct vm_area_struct *next = vma->vm_next;
2309 unsigned long nstart = next->vm_start;
2310 nstart += adjust_next;
2311 split_huge_pmd_if_needed(next, nstart);
2315 static void unmap_page(struct page *page)
2317 struct folio *folio = page_folio(page);
2318 enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2321 VM_BUG_ON_PAGE(!PageHead(page), page);
2324 * Anon pages need migration entries to preserve them, but file
2325 * pages can simply be left unmapped, then faulted back on demand.
2326 * If that is ever changed (perhaps for mlock), update remap_page().
2328 if (folio_test_anon(folio))
2329 try_to_migrate(folio, ttu_flags);
2331 try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
2334 static void remap_page(struct folio *folio, unsigned long nr)
2338 /* If unmap_page() uses try_to_migrate() on file, remove this check */
2339 if (!folio_test_anon(folio))
2342 remove_migration_ptes(folio, folio, true);
2343 i += folio_nr_pages(folio);
2346 folio = folio_next(folio);
2350 static void lru_add_page_tail(struct page *head, struct page *tail,
2351 struct lruvec *lruvec, struct list_head *list)
2353 VM_BUG_ON_PAGE(!PageHead(head), head);
2354 VM_BUG_ON_PAGE(PageCompound(tail), head);
2355 VM_BUG_ON_PAGE(PageLRU(tail), head);
2356 lockdep_assert_held(&lruvec->lru_lock);
2359 /* page reclaim is reclaiming a huge page */
2360 VM_WARN_ON(PageLRU(head));
2362 list_add_tail(&tail->lru, list);
2364 /* head is still on lru (and we have it frozen) */
2365 VM_WARN_ON(!PageLRU(head));
2366 if (PageUnevictable(tail))
2367 tail->mlock_count = 0;
2369 list_add_tail(&tail->lru, &head->lru);
2374 static void __split_huge_page_tail(struct page *head, int tail,
2375 struct lruvec *lruvec, struct list_head *list)
2377 struct page *page_tail = head + tail;
2379 VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
2382 * Clone page flags before unfreezing refcount.
2384 * After successful get_page_unless_zero() might follow flags change,
2385 * for example lock_page() which set PG_waiters.
2387 * Note that for mapped sub-pages of an anonymous THP,
2388 * PG_anon_exclusive has been cleared in unmap_page() and is stored in
2389 * the migration entry instead from where remap_page() will restore it.
2390 * We can still have PG_anon_exclusive set on effectively unmapped and
2391 * unreferenced sub-pages of an anonymous THP: we can simply drop
2392 * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
2394 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
2395 page_tail->flags |= (head->flags &
2396 ((1L << PG_referenced) |
2397 (1L << PG_swapbacked) |
2398 (1L << PG_swapcache) |
2399 (1L << PG_mlocked) |
2400 (1L << PG_uptodate) |
2402 (1L << PG_workingset) |
2404 (1L << PG_unevictable) |
2410 /* ->mapping in first tail page is compound_mapcount */
2411 VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
2413 page_tail->mapping = head->mapping;
2414 page_tail->index = head->index + tail;
2415 page_tail->private = 0;
2417 /* Page flags must be visible before we make the page non-compound. */
2421 * Clear PageTail before unfreezing page refcount.
2423 * After successful get_page_unless_zero() might follow put_page()
2424 * which needs correct compound_head().
2426 clear_compound_head(page_tail);
2428 /* Finally unfreeze refcount. Additional reference from page cache. */
2429 page_ref_unfreeze(page_tail, 1 + (!PageAnon(head) ||
2430 PageSwapCache(head)));
2432 if (page_is_young(head))
2433 set_page_young(page_tail);
2434 if (page_is_idle(head))
2435 set_page_idle(page_tail);
2437 page_cpupid_xchg_last(page_tail, page_cpupid_last(head));
2440 * always add to the tail because some iterators expect new
2441 * pages to show after the currently processed elements - e.g.
2444 lru_add_page_tail(head, page_tail, lruvec, list);
2447 static void __split_huge_page(struct page *page, struct list_head *list,
2450 struct folio *folio = page_folio(page);
2451 struct page *head = &folio->page;
2452 struct lruvec *lruvec;
2453 struct address_space *swap_cache = NULL;
2454 unsigned long offset = 0;
2455 unsigned int nr = thp_nr_pages(head);
2458 /* complete memcg works before add pages to LRU */
2459 split_page_memcg(head, nr);
2461 if (PageAnon(head) && PageSwapCache(head)) {
2462 swp_entry_t entry = { .val = page_private(head) };
2464 offset = swp_offset(entry);
2465 swap_cache = swap_address_space(entry);
2466 xa_lock(&swap_cache->i_pages);
2469 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */
2470 lruvec = folio_lruvec_lock(folio);
2472 ClearPageHasHWPoisoned(head);
2474 for (i = nr - 1; i >= 1; i--) {
2475 __split_huge_page_tail(head, i, lruvec, list);
2476 /* Some pages can be beyond EOF: drop them from page cache */
2477 if (head[i].index >= end) {
2478 ClearPageDirty(head + i);
2479 __delete_from_page_cache(head + i, NULL);
2480 if (shmem_mapping(head->mapping))
2481 shmem_uncharge(head->mapping->host, 1);
2483 } else if (!PageAnon(page)) {
2484 __xa_store(&head->mapping->i_pages, head[i].index,
2486 } else if (swap_cache) {
2487 __xa_store(&swap_cache->i_pages, offset + i,
2492 ClearPageCompound(head);
2493 unlock_page_lruvec(lruvec);
2494 /* Caller disabled irqs, so they are still disabled here */
2496 split_page_owner(head, nr);
2498 /* See comment in __split_huge_page_tail() */
2499 if (PageAnon(head)) {
2500 /* Additional pin to swap cache */
2501 if (PageSwapCache(head)) {
2502 page_ref_add(head, 2);
2503 xa_unlock(&swap_cache->i_pages);
2508 /* Additional pin to page cache */
2509 page_ref_add(head, 2);
2510 xa_unlock(&head->mapping->i_pages);
2514 remap_page(folio, nr);
2516 if (PageSwapCache(head)) {
2517 swp_entry_t entry = { .val = page_private(head) };
2519 split_swap_cluster(entry);
2522 for (i = 0; i < nr; i++) {
2523 struct page *subpage = head + i;
2524 if (subpage == page)
2526 unlock_page(subpage);
2529 * Subpages may be freed if there wasn't any mapping
2530 * like if add_to_swap() is running on a lru page that
2531 * had its mapping zapped. And freeing these pages
2532 * requires taking the lru_lock so we do the put_page
2533 * of the tail pages after the split is complete.
2539 /* Racy check whether the huge page can be split */
2540 bool can_split_folio(struct folio *folio, int *pextra_pins)
2544 /* Additional pins from page cache */
2545 if (folio_test_anon(folio))
2546 extra_pins = folio_test_swapcache(folio) ?
2547 folio_nr_pages(folio) : 0;
2549 extra_pins = folio_nr_pages(folio);
2551 *pextra_pins = extra_pins;
2552 return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 1;
2556 * This function splits huge page into normal pages. @page can point to any
2557 * subpage of huge page to split. Split doesn't change the position of @page.
2559 * Only caller must hold pin on the @page, otherwise split fails with -EBUSY.
2560 * The huge page must be locked.
2562 * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
2564 * Both head page and tail pages will inherit mapping, flags, and so on from
2567 * GUP pin and PG_locked transferred to @page. Rest subpages can be freed if
2568 * they are not mapped.
2570 * Returns 0 if the hugepage is split successfully.
2571 * Returns -EBUSY if the page is pinned or if anon_vma disappeared from under
2574 int split_huge_page_to_list(struct page *page, struct list_head *list)
2576 struct folio *folio = page_folio(page);
2577 struct page *head = &folio->page;
2578 struct deferred_split *ds_queue = get_deferred_split_queue(head);
2579 XA_STATE(xas, &head->mapping->i_pages, head->index);
2580 struct anon_vma *anon_vma = NULL;
2581 struct address_space *mapping = NULL;
2582 int extra_pins, ret;
2586 VM_BUG_ON_PAGE(!PageLocked(head), head);
2587 VM_BUG_ON_PAGE(!PageCompound(head), head);
2589 is_hzp = is_huge_zero_page(head);
2590 VM_WARN_ON_ONCE_PAGE(is_hzp, head);
2594 if (PageWriteback(head))
2597 if (PageAnon(head)) {
2599 * The caller does not necessarily hold an mmap_lock that would
2600 * prevent the anon_vma disappearing so we first we take a
2601 * reference to it and then lock the anon_vma for write. This
2602 * is similar to folio_lock_anon_vma_read except the write lock
2603 * is taken to serialise against parallel split or collapse
2606 anon_vma = page_get_anon_vma(head);
2613 anon_vma_lock_write(anon_vma);
2615 mapping = head->mapping;
2623 xas_split_alloc(&xas, head, compound_order(head),
2624 mapping_gfp_mask(mapping) & GFP_RECLAIM_MASK);
2625 if (xas_error(&xas)) {
2626 ret = xas_error(&xas);
2631 i_mmap_lock_read(mapping);
2634 *__split_huge_page() may need to trim off pages beyond EOF:
2635 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
2636 * which cannot be nested inside the page tree lock. So note
2637 * end now: i_size itself may be changed at any moment, but
2638 * head page lock is good enough to serialize the trimming.
2640 end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2641 if (shmem_mapping(mapping))
2642 end = shmem_fallocend(mapping->host, end);
2646 * Racy check if we can split the page, before unmap_page() will
2649 if (!can_split_folio(folio, &extra_pins)) {
2656 /* block interrupt reentry in xa_lock and spinlock */
2657 local_irq_disable();
2660 * Check if the head page is present in page cache.
2661 * We assume all tail are present too, if head is there.
2665 if (xas_load(&xas) != head)
2669 /* Prevent deferred_split_scan() touching ->_refcount */
2670 spin_lock(&ds_queue->split_queue_lock);
2671 if (page_ref_freeze(head, 1 + extra_pins)) {
2672 if (!list_empty(page_deferred_list(head))) {
2673 ds_queue->split_queue_len--;
2674 list_del(page_deferred_list(head));
2676 spin_unlock(&ds_queue->split_queue_lock);
2678 int nr = thp_nr_pages(head);
2680 xas_split(&xas, head, thp_order(head));
2681 if (PageSwapBacked(head)) {
2682 __mod_lruvec_page_state(head, NR_SHMEM_THPS,
2685 __mod_lruvec_page_state(head, NR_FILE_THPS,
2687 filemap_nr_thps_dec(mapping);
2691 __split_huge_page(page, list, end);
2694 spin_unlock(&ds_queue->split_queue_lock);
2699 remap_page(folio, folio_nr_pages(folio));
2705 anon_vma_unlock_write(anon_vma);
2706 put_anon_vma(anon_vma);
2709 i_mmap_unlock_read(mapping);
2712 count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
2716 void free_transhuge_page(struct page *page)
2718 struct deferred_split *ds_queue = get_deferred_split_queue(page);
2719 unsigned long flags;
2721 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2722 if (!list_empty(page_deferred_list(page))) {
2723 ds_queue->split_queue_len--;
2724 list_del(page_deferred_list(page));
2726 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2727 free_compound_page(page);
2730 void deferred_split_huge_page(struct page *page)
2732 struct deferred_split *ds_queue = get_deferred_split_queue(page);
2734 struct mem_cgroup *memcg = page_memcg(compound_head(page));
2736 unsigned long flags;
2738 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
2741 * The try_to_unmap() in page reclaim path might reach here too,
2742 * this may cause a race condition to corrupt deferred split queue.
2743 * And, if page reclaim is already handling the same page, it is
2744 * unnecessary to handle it again in shrinker.
2746 * Check PageSwapCache to determine if the page is being
2747 * handled by page reclaim since THP swap would add the page into
2748 * swap cache before calling try_to_unmap().
2750 if (PageSwapCache(page))
2753 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2754 if (list_empty(page_deferred_list(page))) {
2755 count_vm_event(THP_DEFERRED_SPLIT_PAGE);
2756 list_add_tail(page_deferred_list(page), &ds_queue->split_queue);
2757 ds_queue->split_queue_len++;
2760 set_shrinker_bit(memcg, page_to_nid(page),
2761 deferred_split_shrinker.id);
2764 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2767 static unsigned long deferred_split_count(struct shrinker *shrink,
2768 struct shrink_control *sc)
2770 struct pglist_data *pgdata = NODE_DATA(sc->nid);
2771 struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
2775 ds_queue = &sc->memcg->deferred_split_queue;
2777 return READ_ONCE(ds_queue->split_queue_len);
2780 static unsigned long deferred_split_scan(struct shrinker *shrink,
2781 struct shrink_control *sc)
2783 struct pglist_data *pgdata = NODE_DATA(sc->nid);
2784 struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
2785 unsigned long flags;
2786 LIST_HEAD(list), *pos, *next;
2792 ds_queue = &sc->memcg->deferred_split_queue;
2795 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2796 /* Take pin on all head pages to avoid freeing them under us */
2797 list_for_each_safe(pos, next, &ds_queue->split_queue) {
2798 page = list_entry((void *)pos, struct page, deferred_list);
2799 page = compound_head(page);
2800 if (get_page_unless_zero(page)) {
2801 list_move(page_deferred_list(page), &list);
2803 /* We lost race with put_compound_page() */
2804 list_del_init(page_deferred_list(page));
2805 ds_queue->split_queue_len--;
2807 if (!--sc->nr_to_scan)
2810 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2812 list_for_each_safe(pos, next, &list) {
2813 page = list_entry((void *)pos, struct page, deferred_list);
2814 if (!trylock_page(page))
2816 /* split_huge_page() removes page from list on success */
2817 if (!split_huge_page(page))
2824 spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2825 list_splice_tail(&list, &ds_queue->split_queue);
2826 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2829 * Stop shrinker if we didn't split any page, but the queue is empty.
2830 * This can happen if pages were freed under us.
2832 if (!split && list_empty(&ds_queue->split_queue))
2837 static struct shrinker deferred_split_shrinker = {
2838 .count_objects = deferred_split_count,
2839 .scan_objects = deferred_split_scan,
2840 .seeks = DEFAULT_SEEKS,
2841 .flags = SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE |
2845 #ifdef CONFIG_DEBUG_FS
2846 static void split_huge_pages_all(void)
2850 unsigned long pfn, max_zone_pfn;
2851 unsigned long total = 0, split = 0;
2853 pr_debug("Split all THPs\n");
2854 for_each_populated_zone(zone) {
2855 max_zone_pfn = zone_end_pfn(zone);
2856 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
2857 if (!pfn_valid(pfn))
2860 page = pfn_to_page(pfn);
2861 if (!get_page_unless_zero(page))
2864 if (zone != page_zone(page))
2867 if (!PageHead(page) || PageHuge(page) || !PageLRU(page))
2872 if (!split_huge_page(page))
2881 pr_debug("%lu of %lu THP split\n", split, total);
2884 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
2886 return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
2887 is_vm_hugetlb_page(vma);
2890 static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
2891 unsigned long vaddr_end)
2894 struct task_struct *task;
2895 struct mm_struct *mm;
2896 unsigned long total = 0, split = 0;
2899 vaddr_start &= PAGE_MASK;
2900 vaddr_end &= PAGE_MASK;
2902 /* Find the task_struct from pid */
2904 task = find_task_by_vpid(pid);
2910 get_task_struct(task);
2913 /* Find the mm_struct */
2914 mm = get_task_mm(task);
2915 put_task_struct(task);
2922 pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
2923 pid, vaddr_start, vaddr_end);
2927 * always increase addr by PAGE_SIZE, since we could have a PTE page
2928 * table filled with PTE-mapped THPs, each of which is distinct.
2930 for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
2931 struct vm_area_struct *vma = find_vma(mm, addr);
2934 if (!vma || addr < vma->vm_start)
2937 /* skip special VMA and hugetlb VMA */
2938 if (vma_not_suitable_for_thp_split(vma)) {
2943 /* FOLL_DUMP to ignore special (like zero) pages */
2944 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
2948 if (!page || is_zone_device_page(page))
2951 if (!is_transparent_hugepage(page))
2955 if (!can_split_folio(page_folio(page), NULL))
2958 if (!trylock_page(page))
2961 if (!split_huge_page(page))
2969 mmap_read_unlock(mm);
2972 pr_debug("%lu of %lu THP split\n", split, total);
2978 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
2981 struct filename *file;
2982 struct file *candidate;
2983 struct address_space *mapping;
2987 unsigned long total = 0, split = 0;
2989 file = getname_kernel(file_path);
2993 candidate = file_open_name(file, O_RDONLY, 0);
2994 if (IS_ERR(candidate))
2997 pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
2998 file_path, off_start, off_end);
3000 mapping = candidate->f_mapping;
3002 for (index = off_start; index < off_end; index += nr_pages) {
3003 struct page *fpage = pagecache_get_page(mapping, index,
3004 FGP_ENTRY | FGP_HEAD, 0);
3007 if (xa_is_value(fpage) || !fpage)
3010 if (!is_transparent_hugepage(fpage))
3014 nr_pages = thp_nr_pages(fpage);
3016 if (!trylock_page(fpage))
3019 if (!split_huge_page(fpage))
3028 filp_close(candidate, NULL);
3031 pr_debug("%lu of %lu file-backed THP split\n", split, total);
3037 #define MAX_INPUT_BUF_SZ 255
3039 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
3040 size_t count, loff_t *ppops)
3042 static DEFINE_MUTEX(split_debug_mutex);
3044 /* hold pid, start_vaddr, end_vaddr or file_path, off_start, off_end */
3045 char input_buf[MAX_INPUT_BUF_SZ];
3047 unsigned long vaddr_start, vaddr_end;
3049 ret = mutex_lock_interruptible(&split_debug_mutex);
3055 memset(input_buf, 0, MAX_INPUT_BUF_SZ);
3056 if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
3059 input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
3061 if (input_buf[0] == '/') {
3063 char *buf = input_buf;
3064 char file_path[MAX_INPUT_BUF_SZ];
3065 pgoff_t off_start = 0, off_end = 0;
3066 size_t input_len = strlen(input_buf);
3068 tok = strsep(&buf, ",");
3070 strcpy(file_path, tok);
3076 ret = sscanf(buf, "0x%lx,0x%lx", &off_start, &off_end);
3081 ret = split_huge_pages_in_file(file_path, off_start, off_end);
3088 ret = sscanf(input_buf, "%d,0x%lx,0x%lx", &pid, &vaddr_start, &vaddr_end);
3089 if (ret == 1 && pid == 1) {
3090 split_huge_pages_all();
3091 ret = strlen(input_buf);
3093 } else if (ret != 3) {
3098 ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end);
3100 ret = strlen(input_buf);
3102 mutex_unlock(&split_debug_mutex);
3107 static const struct file_operations split_huge_pages_fops = {
3108 .owner = THIS_MODULE,
3109 .write = split_huge_pages_write,
3110 .llseek = no_llseek,
3113 static int __init split_huge_pages_debugfs(void)
3115 debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3116 &split_huge_pages_fops);
3119 late_initcall(split_huge_pages_debugfs);
3122 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
3123 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
3126 struct vm_area_struct *vma = pvmw->vma;
3127 struct mm_struct *mm = vma->vm_mm;
3128 unsigned long address = pvmw->address;
3129 bool anon_exclusive;
3134 if (!(pvmw->pmd && !pvmw->pte))
3137 flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
3138 pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
3140 anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
3141 if (anon_exclusive && page_try_share_anon_rmap(page)) {
3142 set_pmd_at(mm, address, pvmw->pmd, pmdval);
3146 if (pmd_dirty(pmdval))
3147 set_page_dirty(page);
3148 if (pmd_write(pmdval))
3149 entry = make_writable_migration_entry(page_to_pfn(page));
3150 else if (anon_exclusive)
3151 entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
3153 entry = make_readable_migration_entry(page_to_pfn(page));
3154 pmdswp = swp_entry_to_pmd(entry);
3155 if (pmd_soft_dirty(pmdval))
3156 pmdswp = pmd_swp_mksoft_dirty(pmdswp);
3157 set_pmd_at(mm, address, pvmw->pmd, pmdswp);
3158 page_remove_rmap(page, vma, true);
3160 trace_set_migration_pmd(address, pmd_val(pmdswp));
3165 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
3167 struct vm_area_struct *vma = pvmw->vma;
3168 struct mm_struct *mm = vma->vm_mm;
3169 unsigned long address = pvmw->address;
3170 unsigned long mmun_start = address & HPAGE_PMD_MASK;
3174 if (!(pvmw->pmd && !pvmw->pte))
3177 entry = pmd_to_swp_entry(*pvmw->pmd);
3179 pmde = pmd_mkold(mk_huge_pmd(new, vma->vm_page_prot));
3180 if (pmd_swp_soft_dirty(*pvmw->pmd))
3181 pmde = pmd_mksoft_dirty(pmde);
3182 if (is_writable_migration_entry(entry))
3183 pmde = maybe_pmd_mkwrite(pmde, vma);
3184 if (pmd_swp_uffd_wp(*pvmw->pmd))
3185 pmde = pmd_wrprotect(pmd_mkuffd_wp(pmde));
3187 if (PageAnon(new)) {
3188 rmap_t rmap_flags = RMAP_COMPOUND;
3190 if (!is_readable_migration_entry(entry))
3191 rmap_flags |= RMAP_EXCLUSIVE;
3193 page_add_anon_rmap(new, vma, mmun_start, rmap_flags);
3195 page_add_file_rmap(new, vma, true);
3197 VM_BUG_ON(pmd_write(pmde) && PageAnon(new) && !PageAnonExclusive(new));
3198 set_pmd_at(mm, mmun_start, pvmw->pmd, pmde);
3200 /* No need to invalidate - it was non-present before */
3201 update_mmu_cache_pmd(vma, address, pvmw->pmd);
3202 trace_remove_migration_pmd(address, pmd_val(pmde));