1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1999 Linus Torvalds
6 * Copyright (C) 2002 Christoph Hellwig
9 #include <linux/mman.h>
10 #include <linux/pagemap.h>
11 #include <linux/syscalls.h>
12 #include <linux/mempolicy.h>
13 #include <linux/page-isolation.h>
14 #include <linux/page_idle.h>
15 #include <linux/userfaultfd_k.h>
16 #include <linux/hugetlb.h>
17 #include <linux/falloc.h>
18 #include <linux/fadvise.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
21 #include <linux/mm_inline.h>
22 #include <linux/string.h>
23 #include <linux/uio.h>
24 #include <linux/ksm.h>
26 #include <linux/file.h>
27 #include <linux/blkdev.h>
28 #include <linux/backing-dev.h>
29 #include <linux/pagewalk.h>
30 #include <linux/swap.h>
31 #include <linux/swapops.h>
32 #include <linux/shmem_fs.h>
33 #include <linux/mmu_notifier.h>
39 struct madvise_walk_private {
40 struct mmu_gather *tlb;
45 * Any behaviour which results in changes to the vma->vm_flags needs to
46 * take mmap_lock for writing. Others, which simply traverse vmas, need
47 * to only take it for reading.
49 static int madvise_need_mmap_write(int behavior)
58 case MADV_POPULATE_READ:
59 case MADV_POPULATE_WRITE:
62 /* be safe, default to 1. list exceptions explicitly */
67 #ifdef CONFIG_ANON_VMA_NAME
68 struct anon_vma_name *anon_vma_name_alloc(const char *name)
70 struct anon_vma_name *anon_name;
73 /* Add 1 for NUL terminator at the end of the anon_name->name */
74 count = strlen(name) + 1;
75 anon_name = kmalloc(struct_size(anon_name, name, count), GFP_KERNEL);
77 kref_init(&anon_name->kref);
78 memcpy(anon_name->name, name, count);
84 void anon_vma_name_free(struct kref *kref)
86 struct anon_vma_name *anon_name =
87 container_of(kref, struct anon_vma_name, kref);
91 struct anon_vma_name *anon_vma_name(struct vm_area_struct *vma)
93 mmap_assert_locked(vma->vm_mm);
98 return vma->anon_name;
101 /* mmap_lock should be write-locked */
102 static int replace_anon_vma_name(struct vm_area_struct *vma,
103 struct anon_vma_name *anon_name)
105 struct anon_vma_name *orig_name = anon_vma_name(vma);
108 vma->anon_name = NULL;
109 anon_vma_name_put(orig_name);
113 if (anon_vma_name_eq(orig_name, anon_name))
116 vma->anon_name = anon_vma_name_reuse(anon_name);
117 anon_vma_name_put(orig_name);
121 #else /* CONFIG_ANON_VMA_NAME */
122 static int replace_anon_vma_name(struct vm_area_struct *vma,
123 struct anon_vma_name *anon_name)
130 #endif /* CONFIG_ANON_VMA_NAME */
132 * Update the vm_flags on region of a vma, splitting it or merging it as
133 * necessary. Must be called with mmap_sem held for writing;
134 * Caller should ensure anon_name stability by raising its refcount even when
135 * anon_name belongs to a valid vma because this function might free that vma.
137 static int madvise_update_vma(struct vm_area_struct *vma,
138 struct vm_area_struct **prev, unsigned long start,
139 unsigned long end, unsigned long new_flags,
140 struct anon_vma_name *anon_name)
142 struct mm_struct *mm = vma->vm_mm;
146 if (new_flags == vma->vm_flags && anon_vma_name_eq(anon_vma_name(vma), anon_name)) {
151 pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
152 *prev = vma_merge(mm, *prev, start, end, new_flags, vma->anon_vma,
153 vma->vm_file, pgoff, vma_policy(vma),
154 vma->vm_userfaultfd_ctx, anon_name);
162 if (start != vma->vm_start) {
163 if (unlikely(mm->map_count >= sysctl_max_map_count))
165 error = __split_vma(mm, vma, start, 1);
170 if (end != vma->vm_end) {
171 if (unlikely(mm->map_count >= sysctl_max_map_count))
173 error = __split_vma(mm, vma, end, 0);
180 * vm_flags is protected by the mmap_lock held in write mode.
182 vma->vm_flags = new_flags;
184 error = replace_anon_vma_name(vma, anon_name);
193 static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
194 unsigned long end, struct mm_walk *walk)
197 struct vm_area_struct *vma = walk->private;
200 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
203 for (index = start; index != end; index += PAGE_SIZE) {
209 orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, start, &ptl);
210 pte = *(orig_pte + ((index - start) / PAGE_SIZE));
211 pte_unmap_unlock(orig_pte, ptl);
213 if (pte_present(pte) || pte_none(pte))
215 entry = pte_to_swp_entry(pte);
216 if (unlikely(non_swap_entry(entry)))
219 page = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE,
228 static const struct mm_walk_ops swapin_walk_ops = {
229 .pmd_entry = swapin_walk_pmd_entry,
232 static void force_shm_swapin_readahead(struct vm_area_struct *vma,
233 unsigned long start, unsigned long end,
234 struct address_space *mapping)
236 XA_STATE(xas, &mapping->i_pages, linear_page_index(vma, start));
237 pgoff_t end_index = linear_page_index(vma, end + PAGE_SIZE - 1);
241 xas_for_each(&xas, page, end_index) {
244 if (!xa_is_value(page))
249 swap = radix_to_swp_entry(page);
250 page = read_swap_cache_async(swap, GFP_HIGHUSER_MOVABLE,
259 lru_add_drain(); /* Push any new pages onto the LRU now */
261 #endif /* CONFIG_SWAP */
264 * Schedule all required I/O operations. Do not wait for completion.
266 static long madvise_willneed(struct vm_area_struct *vma,
267 struct vm_area_struct **prev,
268 unsigned long start, unsigned long end)
270 struct mm_struct *mm = vma->vm_mm;
271 struct file *file = vma->vm_file;
277 walk_page_range(vma->vm_mm, start, end, &swapin_walk_ops, vma);
278 lru_add_drain(); /* Push any new pages onto the LRU now */
282 if (shmem_mapping(file->f_mapping)) {
283 force_shm_swapin_readahead(vma, start, end,
292 if (IS_DAX(file_inode(file))) {
293 /* no bad return value, but ignore advice */
298 * Filesystem's fadvise may need to take various locks. We need to
299 * explicitly grab a reference because the vma (and hence the
300 * vma's reference to the file) can go away as soon as we drop
303 *prev = NULL; /* tell sys_madvise we drop mmap_lock */
305 offset = (loff_t)(start - vma->vm_start)
306 + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
307 mmap_read_unlock(mm);
308 vfs_fadvise(file, offset, end - start, POSIX_FADV_WILLNEED);
314 static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
315 unsigned long addr, unsigned long end,
316 struct mm_walk *walk)
318 struct madvise_walk_private *private = walk->private;
319 struct mmu_gather *tlb = private->tlb;
320 bool pageout = private->pageout;
321 struct mm_struct *mm = tlb->mm;
322 struct vm_area_struct *vma = walk->vma;
323 pte_t *orig_pte, *pte, ptent;
325 struct page *page = NULL;
326 LIST_HEAD(page_list);
328 if (fatal_signal_pending(current))
331 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
332 if (pmd_trans_huge(*pmd)) {
334 unsigned long next = pmd_addr_end(addr, end);
336 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
337 ptl = pmd_trans_huge_lock(pmd, vma);
342 if (is_huge_zero_pmd(orig_pmd))
345 if (unlikely(!pmd_present(orig_pmd))) {
346 VM_BUG_ON(thp_migration_supported() &&
347 !is_pmd_migration_entry(orig_pmd));
351 page = pmd_page(orig_pmd);
353 /* Do not interfere with other mappings of this page */
354 if (page_mapcount(page) != 1)
357 if (next - addr != HPAGE_PMD_SIZE) {
363 err = split_huge_page(page);
371 if (pmd_young(orig_pmd)) {
372 pmdp_invalidate(vma, addr, pmd);
373 orig_pmd = pmd_mkold(orig_pmd);
375 set_pmd_at(mm, addr, pmd, orig_pmd);
376 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
379 ClearPageReferenced(page);
380 test_and_clear_page_young(page);
382 if (!isolate_lru_page(page)) {
383 if (PageUnevictable(page))
384 putback_lru_page(page);
386 list_add(&page->lru, &page_list);
389 deactivate_page(page);
393 reclaim_pages(&page_list);
398 if (pmd_trans_unstable(pmd))
401 tlb_change_page_size(tlb, PAGE_SIZE);
402 orig_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
403 flush_tlb_batched_pending(mm);
404 arch_enter_lazy_mmu_mode();
405 for (; addr < end; pte++, addr += PAGE_SIZE) {
411 if (!pte_present(ptent))
414 page = vm_normal_page(vma, addr, ptent);
419 * Creating a THP page is expensive so split it only if we
420 * are sure it's worth. Split it if we are only owner.
422 if (PageTransCompound(page)) {
423 if (page_mapcount(page) != 1)
426 if (!trylock_page(page)) {
430 pte_unmap_unlock(orig_pte, ptl);
431 if (split_huge_page(page)) {
434 pte_offset_map_lock(mm, pmd, addr, &ptl);
439 pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
445 /* Do not interfere with other mappings of this page */
446 if (page_mapcount(page) != 1)
449 VM_BUG_ON_PAGE(PageTransCompound(page), page);
451 if (pte_young(ptent)) {
452 ptent = ptep_get_and_clear_full(mm, addr, pte,
454 ptent = pte_mkold(ptent);
455 set_pte_at(mm, addr, pte, ptent);
456 tlb_remove_tlb_entry(tlb, pte, addr);
460 * We are deactivating a page for accelerating reclaiming.
461 * VM couldn't reclaim the page unless we clear PG_young.
462 * As a side effect, it makes confuse idle-page tracking
463 * because they will miss recent referenced history.
465 ClearPageReferenced(page);
466 test_and_clear_page_young(page);
468 if (!isolate_lru_page(page)) {
469 if (PageUnevictable(page))
470 putback_lru_page(page);
472 list_add(&page->lru, &page_list);
475 deactivate_page(page);
478 arch_leave_lazy_mmu_mode();
479 pte_unmap_unlock(orig_pte, ptl);
481 reclaim_pages(&page_list);
487 static const struct mm_walk_ops cold_walk_ops = {
488 .pmd_entry = madvise_cold_or_pageout_pte_range,
491 static void madvise_cold_page_range(struct mmu_gather *tlb,
492 struct vm_area_struct *vma,
493 unsigned long addr, unsigned long end)
495 struct madvise_walk_private walk_private = {
500 tlb_start_vma(tlb, vma);
501 walk_page_range(vma->vm_mm, addr, end, &cold_walk_ops, &walk_private);
502 tlb_end_vma(tlb, vma);
505 static long madvise_cold(struct vm_area_struct *vma,
506 struct vm_area_struct **prev,
507 unsigned long start_addr, unsigned long end_addr)
509 struct mm_struct *mm = vma->vm_mm;
510 struct mmu_gather tlb;
513 if (!can_madv_lru_vma(vma))
517 tlb_gather_mmu(&tlb, mm);
518 madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
519 tlb_finish_mmu(&tlb);
524 static void madvise_pageout_page_range(struct mmu_gather *tlb,
525 struct vm_area_struct *vma,
526 unsigned long addr, unsigned long end)
528 struct madvise_walk_private walk_private = {
533 tlb_start_vma(tlb, vma);
534 walk_page_range(vma->vm_mm, addr, end, &cold_walk_ops, &walk_private);
535 tlb_end_vma(tlb, vma);
538 static inline bool can_do_pageout(struct vm_area_struct *vma)
540 if (vma_is_anonymous(vma))
545 * paging out pagecache only for non-anonymous mappings that correspond
546 * to the files the calling process could (if tried) open for writing;
547 * otherwise we'd be including shared non-exclusive mappings, which
548 * opens a side channel.
550 return inode_owner_or_capable(&init_user_ns,
551 file_inode(vma->vm_file)) ||
552 file_permission(vma->vm_file, MAY_WRITE) == 0;
555 static long madvise_pageout(struct vm_area_struct *vma,
556 struct vm_area_struct **prev,
557 unsigned long start_addr, unsigned long end_addr)
559 struct mm_struct *mm = vma->vm_mm;
560 struct mmu_gather tlb;
563 if (!can_madv_lru_vma(vma))
566 if (!can_do_pageout(vma))
570 tlb_gather_mmu(&tlb, mm);
571 madvise_pageout_page_range(&tlb, vma, start_addr, end_addr);
572 tlb_finish_mmu(&tlb);
577 static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
578 unsigned long end, struct mm_walk *walk)
581 struct mmu_gather *tlb = walk->private;
582 struct mm_struct *mm = tlb->mm;
583 struct vm_area_struct *vma = walk->vma;
585 pte_t *orig_pte, *pte, ptent;
590 next = pmd_addr_end(addr, end);
591 if (pmd_trans_huge(*pmd))
592 if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
595 if (pmd_trans_unstable(pmd))
598 tlb_change_page_size(tlb, PAGE_SIZE);
599 orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
600 flush_tlb_batched_pending(mm);
601 arch_enter_lazy_mmu_mode();
602 for (; addr != end; pte++, addr += PAGE_SIZE) {
608 * If the pte has swp_entry, just clear page table to
609 * prevent swap-in which is more expensive rather than
610 * (page allocation + zeroing).
612 if (!pte_present(ptent)) {
615 entry = pte_to_swp_entry(ptent);
616 if (non_swap_entry(entry))
619 free_swap_and_cache(entry);
620 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
624 page = vm_normal_page(vma, addr, ptent);
629 * If pmd isn't transhuge but the page is THP and
630 * is owned by only this process, split it and
631 * deactivate all pages.
633 if (PageTransCompound(page)) {
634 if (page_mapcount(page) != 1)
637 if (!trylock_page(page)) {
641 pte_unmap_unlock(orig_pte, ptl);
642 if (split_huge_page(page)) {
645 pte_offset_map_lock(mm, pmd, addr, &ptl);
650 pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
656 VM_BUG_ON_PAGE(PageTransCompound(page), page);
658 if (PageSwapCache(page) || PageDirty(page)) {
659 if (!trylock_page(page))
662 * If page is shared with others, we couldn't clear
663 * PG_dirty of the page.
665 if (page_mapcount(page) != 1) {
670 if (PageSwapCache(page) && !try_to_free_swap(page)) {
675 ClearPageDirty(page);
679 if (pte_young(ptent) || pte_dirty(ptent)) {
681 * Some of architecture(ex, PPC) don't update TLB
682 * with set_pte_at and tlb_remove_tlb_entry so for
683 * the portability, remap the pte with old|clean
684 * after pte clearing.
686 ptent = ptep_get_and_clear_full(mm, addr, pte,
689 ptent = pte_mkold(ptent);
690 ptent = pte_mkclean(ptent);
691 set_pte_at(mm, addr, pte, ptent);
692 tlb_remove_tlb_entry(tlb, pte, addr);
694 mark_page_lazyfree(page);
698 if (current->mm == mm)
701 add_mm_counter(mm, MM_SWAPENTS, nr_swap);
703 arch_leave_lazy_mmu_mode();
704 pte_unmap_unlock(orig_pte, ptl);
710 static const struct mm_walk_ops madvise_free_walk_ops = {
711 .pmd_entry = madvise_free_pte_range,
714 static int madvise_free_single_vma(struct vm_area_struct *vma,
715 unsigned long start_addr, unsigned long end_addr)
717 struct mm_struct *mm = vma->vm_mm;
718 struct mmu_notifier_range range;
719 struct mmu_gather tlb;
721 /* MADV_FREE works for only anon vma at the moment */
722 if (!vma_is_anonymous(vma))
725 range.start = max(vma->vm_start, start_addr);
726 if (range.start >= vma->vm_end)
728 range.end = min(vma->vm_end, end_addr);
729 if (range.end <= vma->vm_start)
731 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
732 range.start, range.end);
735 tlb_gather_mmu(&tlb, mm);
736 update_hiwater_rss(mm);
738 mmu_notifier_invalidate_range_start(&range);
739 tlb_start_vma(&tlb, vma);
740 walk_page_range(vma->vm_mm, range.start, range.end,
741 &madvise_free_walk_ops, &tlb);
742 tlb_end_vma(&tlb, vma);
743 mmu_notifier_invalidate_range_end(&range);
744 tlb_finish_mmu(&tlb);
750 * Application no longer needs these pages. If the pages are dirty,
751 * it's OK to just throw them away. The app will be more careful about
752 * data it wants to keep. Be sure to free swap resources too. The
753 * zap_page_range call sets things up for shrink_active_list to actually free
754 * these pages later if no one else has touched them in the meantime,
755 * although we could add these pages to a global reuse list for
756 * shrink_active_list to pick up before reclaiming other pages.
758 * NB: This interface discards data rather than pushes it out to swap,
759 * as some implementations do. This has performance implications for
760 * applications like large transactional databases which want to discard
761 * pages in anonymous maps after committing to backing store the data
762 * that was kept in them. There is no reason to write this data out to
763 * the swap area if the application is discarding it.
765 * An interface that causes the system to free clean pages and flush
766 * dirty pages is already available as msync(MS_INVALIDATE).
768 static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
769 unsigned long start, unsigned long end)
771 zap_page_range(vma, start, end - start);
775 static long madvise_dontneed_free(struct vm_area_struct *vma,
776 struct vm_area_struct **prev,
777 unsigned long start, unsigned long end,
780 struct mm_struct *mm = vma->vm_mm;
783 if (!can_madv_lru_vma(vma))
786 if (!userfaultfd_remove(vma, start, end)) {
787 *prev = NULL; /* mmap_lock has been dropped, prev is stale */
790 vma = find_vma(mm, start);
793 if (start < vma->vm_start) {
795 * This "vma" under revalidation is the one
796 * with the lowest vma->vm_start where start
797 * is also < vma->vm_end. If start <
798 * vma->vm_start it means an hole materialized
799 * in the user address space within the
800 * virtual range passed to MADV_DONTNEED
805 if (!can_madv_lru_vma(vma))
807 if (end > vma->vm_end) {
809 * Don't fail if end > vma->vm_end. If the old
810 * vma was split while the mmap_lock was
811 * released the effect of the concurrent
812 * operation may not cause madvise() to
813 * have an undefined result. There may be an
814 * adjacent next vma that we'll walk
815 * next. userfaultfd_remove() will generate an
816 * UFFD_EVENT_REMOVE repetition on the
817 * end-vma->vm_end range, but the manager can
818 * handle a repetition fine.
822 VM_WARN_ON(start >= end);
825 if (behavior == MADV_DONTNEED)
826 return madvise_dontneed_single_vma(vma, start, end);
827 else if (behavior == MADV_FREE)
828 return madvise_free_single_vma(vma, start, end);
833 static long madvise_populate(struct vm_area_struct *vma,
834 struct vm_area_struct **prev,
835 unsigned long start, unsigned long end,
838 const bool write = behavior == MADV_POPULATE_WRITE;
839 struct mm_struct *mm = vma->vm_mm;
840 unsigned long tmp_end;
846 while (start < end) {
848 * We might have temporarily dropped the lock. For example,
849 * our VMA might have been split.
851 if (!vma || start >= vma->vm_end) {
852 vma = find_vma(mm, start);
853 if (!vma || start < vma->vm_start)
857 tmp_end = min_t(unsigned long, end, vma->vm_end);
858 /* Populate (prefault) page tables readable/writable. */
859 pages = faultin_vma_page_range(vma, start, tmp_end, write,
871 case -EINVAL: /* Incompatible mappings / permissions. */
875 case -EFAULT: /* VM_FAULT_SIGBUS or VM_FAULT_SIGSEGV */
878 pr_warn_once("%s: unhandled return value: %ld\n",
885 start += pages * PAGE_SIZE;
891 * Application wants to free up the pages and associated backing store.
892 * This is effectively punching a hole into the middle of a file.
894 static long madvise_remove(struct vm_area_struct *vma,
895 struct vm_area_struct **prev,
896 unsigned long start, unsigned long end)
901 struct mm_struct *mm = vma->vm_mm;
903 *prev = NULL; /* tell sys_madvise we drop mmap_lock */
905 if (vma->vm_flags & VM_LOCKED)
910 if (!f || !f->f_mapping || !f->f_mapping->host) {
914 if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
917 offset = (loff_t)(start - vma->vm_start)
918 + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
921 * Filesystem's fallocate may need to take i_rwsem. We need to
922 * explicitly grab a reference because the vma (and hence the
923 * vma's reference to the file) can go away as soon as we drop
927 if (userfaultfd_remove(vma, start, end)) {
928 /* mmap_lock was not released by userfaultfd_remove() */
929 mmap_read_unlock(mm);
931 error = vfs_fallocate(f,
932 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
933 offset, end - start);
940 * Apply an madvise behavior to a region of a vma. madvise_update_vma
941 * will handle splitting a vm area into separate areas, each area with its own
944 static int madvise_vma_behavior(struct vm_area_struct *vma,
945 struct vm_area_struct **prev,
946 unsigned long start, unsigned long end,
947 unsigned long behavior)
950 struct anon_vma_name *anon_name;
951 unsigned long new_flags = vma->vm_flags;
955 return madvise_remove(vma, prev, start, end);
957 return madvise_willneed(vma, prev, start, end);
959 return madvise_cold(vma, prev, start, end);
961 return madvise_pageout(vma, prev, start, end);
964 return madvise_dontneed_free(vma, prev, start, end, behavior);
965 case MADV_POPULATE_READ:
966 case MADV_POPULATE_WRITE:
967 return madvise_populate(vma, prev, start, end, behavior);
969 new_flags = new_flags & ~VM_RAND_READ & ~VM_SEQ_READ;
971 case MADV_SEQUENTIAL:
972 new_flags = (new_flags & ~VM_RAND_READ) | VM_SEQ_READ;
975 new_flags = (new_flags & ~VM_SEQ_READ) | VM_RAND_READ;
978 new_flags |= VM_DONTCOPY;
981 if (vma->vm_flags & VM_IO)
983 new_flags &= ~VM_DONTCOPY;
985 case MADV_WIPEONFORK:
986 /* MADV_WIPEONFORK is only supported on anonymous memory. */
987 if (vma->vm_file || vma->vm_flags & VM_SHARED)
989 new_flags |= VM_WIPEONFORK;
991 case MADV_KEEPONFORK:
992 new_flags &= ~VM_WIPEONFORK;
995 new_flags |= VM_DONTDUMP;
998 if (!is_vm_hugetlb_page(vma) && new_flags & VM_SPECIAL)
1000 new_flags &= ~VM_DONTDUMP;
1002 case MADV_MERGEABLE:
1003 case MADV_UNMERGEABLE:
1004 error = ksm_madvise(vma, start, end, behavior, &new_flags);
1009 case MADV_NOHUGEPAGE:
1010 error = hugepage_madvise(vma, &new_flags, behavior);
1016 anon_name = anon_vma_name(vma);
1017 anon_vma_name_get(anon_name);
1018 error = madvise_update_vma(vma, prev, start, end, new_flags,
1020 anon_vma_name_put(anon_name);
1024 * madvise() returns EAGAIN if kernel resources, such as
1025 * slab, are temporarily unavailable.
1027 if (error == -ENOMEM)
1032 #ifdef CONFIG_MEMORY_FAILURE
1034 * Error injection support for memory error handling.
1036 static int madvise_inject_error(int behavior,
1037 unsigned long start, unsigned long end)
1041 if (!capable(CAP_SYS_ADMIN))
1045 for (; start < end; start += size) {
1050 ret = get_user_pages_fast(start, 1, 0, &page);
1053 pfn = page_to_pfn(page);
1056 * When soft offlining hugepages, after migrating the page
1057 * we dissolve it, therefore in the second loop "page" will
1058 * no longer be a compound page.
1060 size = page_size(compound_head(page));
1062 if (behavior == MADV_SOFT_OFFLINE) {
1063 pr_info("Soft offlining pfn %#lx at process virtual address %#lx\n",
1065 ret = soft_offline_page(pfn, MF_COUNT_INCREASED);
1067 pr_info("Injecting memory failure for pfn %#lx at process virtual address %#lx\n",
1069 ret = memory_failure(pfn, MF_COUNT_INCREASED);
1070 if (ret == -EOPNOTSUPP)
1083 madvise_behavior_valid(int behavior)
1089 case MADV_SEQUENTIAL:
1097 case MADV_POPULATE_READ:
1098 case MADV_POPULATE_WRITE:
1100 case MADV_MERGEABLE:
1101 case MADV_UNMERGEABLE:
1103 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1105 case MADV_NOHUGEPAGE:
1109 case MADV_WIPEONFORK:
1110 case MADV_KEEPONFORK:
1111 #ifdef CONFIG_MEMORY_FAILURE
1112 case MADV_SOFT_OFFLINE:
1123 process_madvise_behavior_valid(int behavior)
1136 * Walk the vmas in range [start,end), and call the visit function on each one.
1137 * The visit function will get start and end parameters that cover the overlap
1138 * between the current vma and the original range. Any unmapped regions in the
1139 * original range will result in this function returning -ENOMEM while still
1140 * calling the visit function on all of the existing vmas in the range.
1141 * Must be called with the mmap_lock held for reading or writing.
1144 int madvise_walk_vmas(struct mm_struct *mm, unsigned long start,
1145 unsigned long end, unsigned long arg,
1146 int (*visit)(struct vm_area_struct *vma,
1147 struct vm_area_struct **prev, unsigned long start,
1148 unsigned long end, unsigned long arg))
1150 struct vm_area_struct *vma;
1151 struct vm_area_struct *prev;
1153 int unmapped_error = 0;
1156 * If the interval [start,end) covers some unmapped address
1157 * ranges, just ignore them, but return -ENOMEM at the end.
1158 * - different from the way of handling in mlock etc.
1160 vma = find_vma_prev(mm, start, &prev);
1161 if (vma && start > vma->vm_start)
1167 /* Still start < end. */
1171 /* Here start < (end|vma->vm_end). */
1172 if (start < vma->vm_start) {
1173 unmapped_error = -ENOMEM;
1174 start = vma->vm_start;
1179 /* Here vma->vm_start <= start < (end|vma->vm_end) */
1184 /* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
1185 error = visit(vma, &prev, start, tmp, arg);
1189 if (prev && start < prev->vm_end)
1190 start = prev->vm_end;
1194 vma = prev->vm_next;
1195 else /* madvise_remove dropped mmap_lock */
1196 vma = find_vma(mm, start);
1199 return unmapped_error;
1202 #ifdef CONFIG_ANON_VMA_NAME
1203 static int madvise_vma_anon_name(struct vm_area_struct *vma,
1204 struct vm_area_struct **prev,
1205 unsigned long start, unsigned long end,
1206 unsigned long anon_name)
1210 /* Only anonymous mappings can be named */
1214 error = madvise_update_vma(vma, prev, start, end, vma->vm_flags,
1215 (struct anon_vma_name *)anon_name);
1218 * madvise() returns EAGAIN if kernel resources, such as
1219 * slab, are temporarily unavailable.
1221 if (error == -ENOMEM)
1226 int madvise_set_anon_name(struct mm_struct *mm, unsigned long start,
1227 unsigned long len_in, struct anon_vma_name *anon_name)
1232 if (start & ~PAGE_MASK)
1234 len = (len_in + ~PAGE_MASK) & PAGE_MASK;
1236 /* Check to see whether len was rounded up from small -ve to zero */
1247 return madvise_walk_vmas(mm, start, end, (unsigned long)anon_name,
1248 madvise_vma_anon_name);
1250 #endif /* CONFIG_ANON_VMA_NAME */
1252 * The madvise(2) system call.
1254 * Applications can use madvise() to advise the kernel how it should
1255 * handle paging I/O in this VM area. The idea is to help the kernel
1256 * use appropriate read-ahead and caching techniques. The information
1257 * provided is advisory only, and can be safely disregarded by the
1258 * kernel without affecting the correct operation of the application.
1261 * MADV_NORMAL - the default behavior is to read clusters. This
1262 * results in some read-ahead and read-behind.
1263 * MADV_RANDOM - the system should read the minimum amount of data
1264 * on any access, since it is unlikely that the appli-
1265 * cation will need more than what it asks for.
1266 * MADV_SEQUENTIAL - pages in the given range will probably be accessed
1267 * once, so they can be aggressively read ahead, and
1268 * can be freed soon after they are accessed.
1269 * MADV_WILLNEED - the application is notifying the system to read
1271 * MADV_DONTNEED - the application is finished with the given range,
1272 * so the kernel can free resources associated with it.
1273 * MADV_FREE - the application marks pages in the given range as lazy free,
1274 * where actual purges are postponed until memory pressure happens.
1275 * MADV_REMOVE - the application wants to free up the given range of
1276 * pages and associated backing store.
1277 * MADV_DONTFORK - omit this area from child's address space when forking:
1278 * typically, to avoid COWing pages pinned by get_user_pages().
1279 * MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
1280 * MADV_WIPEONFORK - present the child process with zero-filled memory in this
1281 * range after a fork.
1282 * MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
1283 * MADV_HWPOISON - trigger memory error handler as if the given memory range
1284 * were corrupted by unrecoverable hardware memory failure.
1285 * MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
1286 * MADV_MERGEABLE - the application recommends that KSM try to merge pages in
1287 * this area with pages of identical content from other such areas.
1288 * MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
1289 * MADV_HUGEPAGE - the application wants to back the given range by transparent
1290 * huge pages in the future. Existing pages might be coalesced and
1291 * new pages might be allocated as THP.
1292 * MADV_NOHUGEPAGE - mark the given range as not worth being backed by
1293 * transparent huge pages so the existing pages will not be
1294 * coalesced into THP and new pages will not be allocated as THP.
1295 * MADV_DONTDUMP - the application wants to prevent pages in the given range
1296 * from being included in its core dump.
1297 * MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
1298 * MADV_COLD - the application is not expected to use this memory soon,
1299 * deactivate pages in this range so that they can be reclaimed
1300 * easily if memory pressure happens.
1301 * MADV_PAGEOUT - the application is not expected to use this memory soon,
1302 * page out the pages in this range immediately.
1303 * MADV_POPULATE_READ - populate (prefault) page tables readable by
1304 * triggering read faults if required
1305 * MADV_POPULATE_WRITE - populate (prefault) page tables writable by
1306 * triggering write faults if required
1310 * -EINVAL - start + len < 0, start is not page-aligned,
1311 * "behavior" is not a valid value, or application
1312 * is attempting to release locked or shared pages,
1313 * or the specified address range includes file, Huge TLB,
1314 * MAP_SHARED or VMPFNMAP range.
1315 * -ENOMEM - addresses in the specified range are not currently
1316 * mapped, or are outside the AS of the process.
1317 * -EIO - an I/O error occurred while paging in data.
1318 * -EBADF - map exists, but area maps something that isn't a file.
1319 * -EAGAIN - a kernel resource was temporarily unavailable.
1321 int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int behavior)
1327 struct blk_plug plug;
1329 start = untagged_addr(start);
1331 if (!madvise_behavior_valid(behavior))
1334 if (!PAGE_ALIGNED(start))
1336 len = PAGE_ALIGN(len_in);
1338 /* Check to see whether len was rounded up from small -ve to zero */
1349 #ifdef CONFIG_MEMORY_FAILURE
1350 if (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)
1351 return madvise_inject_error(behavior, start, start + len_in);
1354 write = madvise_need_mmap_write(behavior);
1356 if (mmap_write_lock_killable(mm))
1362 blk_start_plug(&plug);
1363 error = madvise_walk_vmas(mm, start, end, behavior,
1364 madvise_vma_behavior);
1365 blk_finish_plug(&plug);
1367 mmap_write_unlock(mm);
1369 mmap_read_unlock(mm);
1374 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
1376 return do_madvise(current->mm, start, len_in, behavior);
1379 SYSCALL_DEFINE5(process_madvise, int, pidfd, const struct iovec __user *, vec,
1380 size_t, vlen, int, behavior, unsigned int, flags)
1383 struct iovec iovstack[UIO_FASTIOV], iovec;
1384 struct iovec *iov = iovstack;
1385 struct iov_iter iter;
1386 struct task_struct *task;
1387 struct mm_struct *mm;
1389 unsigned int f_flags;
1396 ret = import_iovec(READ, vec, vlen, ARRAY_SIZE(iovstack), &iov, &iter);
1400 task = pidfd_get_task(pidfd, &f_flags);
1402 ret = PTR_ERR(task);
1406 if (!process_madvise_behavior_valid(behavior)) {
1411 /* Require PTRACE_MODE_READ to avoid leaking ASLR metadata. */
1412 mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
1413 if (IS_ERR_OR_NULL(mm)) {
1414 ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
1419 * Require CAP_SYS_NICE for influencing process performance. Note that
1420 * only non-destructive hints are currently supported.
1422 if (!capable(CAP_SYS_NICE)) {
1427 total_len = iov_iter_count(&iter);
1429 while (iov_iter_count(&iter)) {
1430 iovec = iov_iter_iovec(&iter);
1431 ret = do_madvise(mm, (unsigned long)iovec.iov_base,
1432 iovec.iov_len, behavior);
1435 iov_iter_advance(&iter, iovec.iov_len);
1439 ret = total_len - iov_iter_count(&iter);
1444 put_task_struct(task);