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)
55 case MADV_DONTNEED_LOCKED:
59 case MADV_POPULATE_READ:
60 case MADV_POPULATE_WRITE:
63 /* be safe, default to 1. list exceptions explicitly */
68 #ifdef CONFIG_ANON_VMA_NAME
69 struct anon_vma_name *anon_vma_name_alloc(const char *name)
71 struct anon_vma_name *anon_name;
74 /* Add 1 for NUL terminator at the end of the anon_name->name */
75 count = strlen(name) + 1;
76 anon_name = kmalloc(struct_size(anon_name, name, count), GFP_KERNEL);
78 kref_init(&anon_name->kref);
79 memcpy(anon_name->name, name, count);
85 void anon_vma_name_free(struct kref *kref)
87 struct anon_vma_name *anon_name =
88 container_of(kref, struct anon_vma_name, kref);
92 struct anon_vma_name *anon_vma_name(struct vm_area_struct *vma)
94 mmap_assert_locked(vma->vm_mm);
99 return vma->anon_name;
102 /* mmap_lock should be write-locked */
103 static int replace_anon_vma_name(struct vm_area_struct *vma,
104 struct anon_vma_name *anon_name)
106 struct anon_vma_name *orig_name = anon_vma_name(vma);
109 vma->anon_name = NULL;
110 anon_vma_name_put(orig_name);
114 if (anon_vma_name_eq(orig_name, anon_name))
117 vma->anon_name = anon_vma_name_reuse(anon_name);
118 anon_vma_name_put(orig_name);
122 #else /* CONFIG_ANON_VMA_NAME */
123 static int replace_anon_vma_name(struct vm_area_struct *vma,
124 struct anon_vma_name *anon_name)
131 #endif /* CONFIG_ANON_VMA_NAME */
133 * Update the vm_flags on region of a vma, splitting it or merging it as
134 * necessary. Must be called with mmap_sem held for writing;
135 * Caller should ensure anon_name stability by raising its refcount even when
136 * anon_name belongs to a valid vma because this function might free that vma.
138 static int madvise_update_vma(struct vm_area_struct *vma,
139 struct vm_area_struct **prev, unsigned long start,
140 unsigned long end, unsigned long new_flags,
141 struct anon_vma_name *anon_name)
143 struct mm_struct *mm = vma->vm_mm;
147 if (new_flags == vma->vm_flags && anon_vma_name_eq(anon_vma_name(vma), anon_name)) {
152 pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
153 *prev = vma_merge(mm, *prev, start, end, new_flags, vma->anon_vma,
154 vma->vm_file, pgoff, vma_policy(vma),
155 vma->vm_userfaultfd_ctx, anon_name);
163 if (start != vma->vm_start) {
164 if (unlikely(mm->map_count >= sysctl_max_map_count))
166 error = __split_vma(mm, vma, start, 1);
171 if (end != vma->vm_end) {
172 if (unlikely(mm->map_count >= sysctl_max_map_count))
174 error = __split_vma(mm, vma, end, 0);
181 * vm_flags is protected by the mmap_lock held in write mode.
183 vma->vm_flags = new_flags;
185 error = replace_anon_vma_name(vma, anon_name);
194 static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
195 unsigned long end, struct mm_walk *walk)
198 struct vm_area_struct *vma = walk->private;
201 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
204 for (index = start; index != end; index += PAGE_SIZE) {
210 orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, start, &ptl);
211 pte = *(orig_pte + ((index - start) / PAGE_SIZE));
212 pte_unmap_unlock(orig_pte, ptl);
214 if (pte_present(pte) || pte_none(pte))
216 entry = pte_to_swp_entry(pte);
217 if (unlikely(non_swap_entry(entry)))
220 page = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE,
229 static const struct mm_walk_ops swapin_walk_ops = {
230 .pmd_entry = swapin_walk_pmd_entry,
233 static void force_shm_swapin_readahead(struct vm_area_struct *vma,
234 unsigned long start, unsigned long end,
235 struct address_space *mapping)
237 XA_STATE(xas, &mapping->i_pages, linear_page_index(vma, start));
238 pgoff_t end_index = linear_page_index(vma, end + PAGE_SIZE - 1);
242 xas_for_each(&xas, page, end_index) {
245 if (!xa_is_value(page))
250 swap = radix_to_swp_entry(page);
251 page = read_swap_cache_async(swap, GFP_HIGHUSER_MOVABLE,
260 lru_add_drain(); /* Push any new pages onto the LRU now */
262 #endif /* CONFIG_SWAP */
265 * Schedule all required I/O operations. Do not wait for completion.
267 static long madvise_willneed(struct vm_area_struct *vma,
268 struct vm_area_struct **prev,
269 unsigned long start, unsigned long end)
271 struct mm_struct *mm = vma->vm_mm;
272 struct file *file = vma->vm_file;
278 walk_page_range(vma->vm_mm, start, end, &swapin_walk_ops, vma);
279 lru_add_drain(); /* Push any new pages onto the LRU now */
283 if (shmem_mapping(file->f_mapping)) {
284 force_shm_swapin_readahead(vma, start, end,
293 if (IS_DAX(file_inode(file))) {
294 /* no bad return value, but ignore advice */
299 * Filesystem's fadvise may need to take various locks. We need to
300 * explicitly grab a reference because the vma (and hence the
301 * vma's reference to the file) can go away as soon as we drop
304 *prev = NULL; /* tell sys_madvise we drop mmap_lock */
306 offset = (loff_t)(start - vma->vm_start)
307 + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
308 mmap_read_unlock(mm);
309 vfs_fadvise(file, offset, end - start, POSIX_FADV_WILLNEED);
315 static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
316 unsigned long addr, unsigned long end,
317 struct mm_walk *walk)
319 struct madvise_walk_private *private = walk->private;
320 struct mmu_gather *tlb = private->tlb;
321 bool pageout = private->pageout;
322 struct mm_struct *mm = tlb->mm;
323 struct vm_area_struct *vma = walk->vma;
324 pte_t *orig_pte, *pte, ptent;
326 struct page *page = NULL;
327 LIST_HEAD(page_list);
329 if (fatal_signal_pending(current))
332 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
333 if (pmd_trans_huge(*pmd)) {
335 unsigned long next = pmd_addr_end(addr, end);
337 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
338 ptl = pmd_trans_huge_lock(pmd, vma);
343 if (is_huge_zero_pmd(orig_pmd))
346 if (unlikely(!pmd_present(orig_pmd))) {
347 VM_BUG_ON(thp_migration_supported() &&
348 !is_pmd_migration_entry(orig_pmd));
352 page = pmd_page(orig_pmd);
354 /* Do not interfere with other mappings of this page */
355 if (page_mapcount(page) != 1)
358 if (next - addr != HPAGE_PMD_SIZE) {
364 err = split_huge_page(page);
372 if (pmd_young(orig_pmd)) {
373 pmdp_invalidate(vma, addr, pmd);
374 orig_pmd = pmd_mkold(orig_pmd);
376 set_pmd_at(mm, addr, pmd, orig_pmd);
377 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
380 ClearPageReferenced(page);
381 test_and_clear_page_young(page);
383 if (!isolate_lru_page(page)) {
384 if (PageUnevictable(page))
385 putback_lru_page(page);
387 list_add(&page->lru, &page_list);
390 deactivate_page(page);
394 reclaim_pages(&page_list);
399 if (pmd_trans_unstable(pmd))
402 tlb_change_page_size(tlb, PAGE_SIZE);
403 orig_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
404 flush_tlb_batched_pending(mm);
405 arch_enter_lazy_mmu_mode();
406 for (; addr < end; pte++, addr += PAGE_SIZE) {
412 if (!pte_present(ptent))
415 page = vm_normal_page(vma, addr, ptent);
420 * Creating a THP page is expensive so split it only if we
421 * are sure it's worth. Split it if we are only owner.
423 if (PageTransCompound(page)) {
424 if (page_mapcount(page) != 1)
427 if (!trylock_page(page)) {
431 pte_unmap_unlock(orig_pte, ptl);
432 if (split_huge_page(page)) {
435 pte_offset_map_lock(mm, pmd, addr, &ptl);
440 pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
446 /* Do not interfere with other mappings of this page */
447 if (page_mapcount(page) != 1)
450 VM_BUG_ON_PAGE(PageTransCompound(page), page);
452 if (pte_young(ptent)) {
453 ptent = ptep_get_and_clear_full(mm, addr, pte,
455 ptent = pte_mkold(ptent);
456 set_pte_at(mm, addr, pte, ptent);
457 tlb_remove_tlb_entry(tlb, pte, addr);
461 * We are deactivating a page for accelerating reclaiming.
462 * VM couldn't reclaim the page unless we clear PG_young.
463 * As a side effect, it makes confuse idle-page tracking
464 * because they will miss recent referenced history.
466 ClearPageReferenced(page);
467 test_and_clear_page_young(page);
469 if (!isolate_lru_page(page)) {
470 if (PageUnevictable(page))
471 putback_lru_page(page);
473 list_add(&page->lru, &page_list);
476 deactivate_page(page);
479 arch_leave_lazy_mmu_mode();
480 pte_unmap_unlock(orig_pte, ptl);
482 reclaim_pages(&page_list);
488 static const struct mm_walk_ops cold_walk_ops = {
489 .pmd_entry = madvise_cold_or_pageout_pte_range,
492 static void madvise_cold_page_range(struct mmu_gather *tlb,
493 struct vm_area_struct *vma,
494 unsigned long addr, unsigned long end)
496 struct madvise_walk_private walk_private = {
501 tlb_start_vma(tlb, vma);
502 walk_page_range(vma->vm_mm, addr, end, &cold_walk_ops, &walk_private);
503 tlb_end_vma(tlb, vma);
506 static inline bool can_madv_lru_vma(struct vm_area_struct *vma)
508 return !(vma->vm_flags & (VM_LOCKED|VM_PFNMAP|VM_HUGETLB));
511 static long madvise_cold(struct vm_area_struct *vma,
512 struct vm_area_struct **prev,
513 unsigned long start_addr, unsigned long end_addr)
515 struct mm_struct *mm = vma->vm_mm;
516 struct mmu_gather tlb;
519 if (!can_madv_lru_vma(vma))
523 tlb_gather_mmu(&tlb, mm);
524 madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
525 tlb_finish_mmu(&tlb);
530 static void madvise_pageout_page_range(struct mmu_gather *tlb,
531 struct vm_area_struct *vma,
532 unsigned long addr, unsigned long end)
534 struct madvise_walk_private walk_private = {
539 tlb_start_vma(tlb, vma);
540 walk_page_range(vma->vm_mm, addr, end, &cold_walk_ops, &walk_private);
541 tlb_end_vma(tlb, vma);
544 static inline bool can_do_pageout(struct vm_area_struct *vma)
546 if (vma_is_anonymous(vma))
551 * paging out pagecache only for non-anonymous mappings that correspond
552 * to the files the calling process could (if tried) open for writing;
553 * otherwise we'd be including shared non-exclusive mappings, which
554 * opens a side channel.
556 return inode_owner_or_capable(&init_user_ns,
557 file_inode(vma->vm_file)) ||
558 file_permission(vma->vm_file, MAY_WRITE) == 0;
561 static long madvise_pageout(struct vm_area_struct *vma,
562 struct vm_area_struct **prev,
563 unsigned long start_addr, unsigned long end_addr)
565 struct mm_struct *mm = vma->vm_mm;
566 struct mmu_gather tlb;
569 if (!can_madv_lru_vma(vma))
572 if (!can_do_pageout(vma))
576 tlb_gather_mmu(&tlb, mm);
577 madvise_pageout_page_range(&tlb, vma, start_addr, end_addr);
578 tlb_finish_mmu(&tlb);
583 static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
584 unsigned long end, struct mm_walk *walk)
587 struct mmu_gather *tlb = walk->private;
588 struct mm_struct *mm = tlb->mm;
589 struct vm_area_struct *vma = walk->vma;
591 pte_t *orig_pte, *pte, ptent;
596 next = pmd_addr_end(addr, end);
597 if (pmd_trans_huge(*pmd))
598 if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
601 if (pmd_trans_unstable(pmd))
604 tlb_change_page_size(tlb, PAGE_SIZE);
605 orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
606 flush_tlb_batched_pending(mm);
607 arch_enter_lazy_mmu_mode();
608 for (; addr != end; pte++, addr += PAGE_SIZE) {
614 * If the pte has swp_entry, just clear page table to
615 * prevent swap-in which is more expensive rather than
616 * (page allocation + zeroing).
618 if (!pte_present(ptent)) {
621 entry = pte_to_swp_entry(ptent);
622 if (non_swap_entry(entry))
625 free_swap_and_cache(entry);
626 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
630 page = vm_normal_page(vma, addr, ptent);
635 * If pmd isn't transhuge but the page is THP and
636 * is owned by only this process, split it and
637 * deactivate all pages.
639 if (PageTransCompound(page)) {
640 if (page_mapcount(page) != 1)
643 if (!trylock_page(page)) {
647 pte_unmap_unlock(orig_pte, ptl);
648 if (split_huge_page(page)) {
651 pte_offset_map_lock(mm, pmd, addr, &ptl);
656 pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
662 VM_BUG_ON_PAGE(PageTransCompound(page), page);
664 if (PageSwapCache(page) || PageDirty(page)) {
665 if (!trylock_page(page))
668 * If page is shared with others, we couldn't clear
669 * PG_dirty of the page.
671 if (page_mapcount(page) != 1) {
676 if (PageSwapCache(page) && !try_to_free_swap(page)) {
681 ClearPageDirty(page);
685 if (pte_young(ptent) || pte_dirty(ptent)) {
687 * Some of architecture(ex, PPC) don't update TLB
688 * with set_pte_at and tlb_remove_tlb_entry so for
689 * the portability, remap the pte with old|clean
690 * after pte clearing.
692 ptent = ptep_get_and_clear_full(mm, addr, pte,
695 ptent = pte_mkold(ptent);
696 ptent = pte_mkclean(ptent);
697 set_pte_at(mm, addr, pte, ptent);
698 tlb_remove_tlb_entry(tlb, pte, addr);
700 mark_page_lazyfree(page);
704 if (current->mm == mm)
707 add_mm_counter(mm, MM_SWAPENTS, nr_swap);
709 arch_leave_lazy_mmu_mode();
710 pte_unmap_unlock(orig_pte, ptl);
716 static const struct mm_walk_ops madvise_free_walk_ops = {
717 .pmd_entry = madvise_free_pte_range,
720 static int madvise_free_single_vma(struct vm_area_struct *vma,
721 unsigned long start_addr, unsigned long end_addr)
723 struct mm_struct *mm = vma->vm_mm;
724 struct mmu_notifier_range range;
725 struct mmu_gather tlb;
727 /* MADV_FREE works for only anon vma at the moment */
728 if (!vma_is_anonymous(vma))
731 range.start = max(vma->vm_start, start_addr);
732 if (range.start >= vma->vm_end)
734 range.end = min(vma->vm_end, end_addr);
735 if (range.end <= vma->vm_start)
737 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
738 range.start, range.end);
741 tlb_gather_mmu(&tlb, mm);
742 update_hiwater_rss(mm);
744 mmu_notifier_invalidate_range_start(&range);
745 tlb_start_vma(&tlb, vma);
746 walk_page_range(vma->vm_mm, range.start, range.end,
747 &madvise_free_walk_ops, &tlb);
748 tlb_end_vma(&tlb, vma);
749 mmu_notifier_invalidate_range_end(&range);
750 tlb_finish_mmu(&tlb);
756 * Application no longer needs these pages. If the pages are dirty,
757 * it's OK to just throw them away. The app will be more careful about
758 * data it wants to keep. Be sure to free swap resources too. The
759 * zap_page_range call sets things up for shrink_active_list to actually free
760 * these pages later if no one else has touched them in the meantime,
761 * although we could add these pages to a global reuse list for
762 * shrink_active_list to pick up before reclaiming other pages.
764 * NB: This interface discards data rather than pushes it out to swap,
765 * as some implementations do. This has performance implications for
766 * applications like large transactional databases which want to discard
767 * pages in anonymous maps after committing to backing store the data
768 * that was kept in them. There is no reason to write this data out to
769 * the swap area if the application is discarding it.
771 * An interface that causes the system to free clean pages and flush
772 * dirty pages is already available as msync(MS_INVALIDATE).
774 static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
775 unsigned long start, unsigned long end)
777 zap_page_range(vma, start, end - start);
781 static bool madvise_dontneed_free_valid_vma(struct vm_area_struct *vma,
786 if (!is_vm_hugetlb_page(vma)) {
787 unsigned int forbidden = VM_PFNMAP;
789 if (behavior != MADV_DONTNEED_LOCKED)
790 forbidden |= VM_LOCKED;
792 return !(vma->vm_flags & forbidden);
795 if (behavior != MADV_DONTNEED && behavior != MADV_DONTNEED_LOCKED)
797 if (start & ~huge_page_mask(hstate_vma(vma)))
800 *end = ALIGN(*end, huge_page_size(hstate_vma(vma)));
804 static long madvise_dontneed_free(struct vm_area_struct *vma,
805 struct vm_area_struct **prev,
806 unsigned long start, unsigned long end,
809 struct mm_struct *mm = vma->vm_mm;
812 if (!madvise_dontneed_free_valid_vma(vma, start, &end, behavior))
815 if (!userfaultfd_remove(vma, start, end)) {
816 *prev = NULL; /* mmap_lock has been dropped, prev is stale */
819 vma = find_vma(mm, start);
822 if (start < vma->vm_start) {
824 * This "vma" under revalidation is the one
825 * with the lowest vma->vm_start where start
826 * is also < vma->vm_end. If start <
827 * vma->vm_start it means an hole materialized
828 * in the user address space within the
829 * virtual range passed to MADV_DONTNEED
835 * Potential end adjustment for hugetlb vma is OK as
836 * the check below keeps end within vma.
838 if (!madvise_dontneed_free_valid_vma(vma, start, &end,
841 if (end > vma->vm_end) {
843 * Don't fail if end > vma->vm_end. If the old
844 * vma was split while the mmap_lock was
845 * released the effect of the concurrent
846 * operation may not cause madvise() to
847 * have an undefined result. There may be an
848 * adjacent next vma that we'll walk
849 * next. userfaultfd_remove() will generate an
850 * UFFD_EVENT_REMOVE repetition on the
851 * end-vma->vm_end range, but the manager can
852 * handle a repetition fine.
856 VM_WARN_ON(start >= end);
859 if (behavior == MADV_DONTNEED || behavior == MADV_DONTNEED_LOCKED)
860 return madvise_dontneed_single_vma(vma, start, end);
861 else if (behavior == MADV_FREE)
862 return madvise_free_single_vma(vma, start, end);
867 static long madvise_populate(struct vm_area_struct *vma,
868 struct vm_area_struct **prev,
869 unsigned long start, unsigned long end,
872 const bool write = behavior == MADV_POPULATE_WRITE;
873 struct mm_struct *mm = vma->vm_mm;
874 unsigned long tmp_end;
880 while (start < end) {
882 * We might have temporarily dropped the lock. For example,
883 * our VMA might have been split.
885 if (!vma || start >= vma->vm_end) {
886 vma = vma_lookup(mm, start);
891 tmp_end = min_t(unsigned long, end, vma->vm_end);
892 /* Populate (prefault) page tables readable/writable. */
893 pages = faultin_vma_page_range(vma, start, tmp_end, write,
905 case -EINVAL: /* Incompatible mappings / permissions. */
909 case -EFAULT: /* VM_FAULT_SIGBUS or VM_FAULT_SIGSEGV */
912 pr_warn_once("%s: unhandled return value: %ld\n",
919 start += pages * PAGE_SIZE;
925 * Application wants to free up the pages and associated backing store.
926 * This is effectively punching a hole into the middle of a file.
928 static long madvise_remove(struct vm_area_struct *vma,
929 struct vm_area_struct **prev,
930 unsigned long start, unsigned long end)
935 struct mm_struct *mm = vma->vm_mm;
937 *prev = NULL; /* tell sys_madvise we drop mmap_lock */
939 if (vma->vm_flags & VM_LOCKED)
944 if (!f || !f->f_mapping || !f->f_mapping->host) {
948 if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
951 offset = (loff_t)(start - vma->vm_start)
952 + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
955 * Filesystem's fallocate may need to take i_rwsem. We need to
956 * explicitly grab a reference because the vma (and hence the
957 * vma's reference to the file) can go away as soon as we drop
961 if (userfaultfd_remove(vma, start, end)) {
962 /* mmap_lock was not released by userfaultfd_remove() */
963 mmap_read_unlock(mm);
965 error = vfs_fallocate(f,
966 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
967 offset, end - start);
974 * Apply an madvise behavior to a region of a vma. madvise_update_vma
975 * will handle splitting a vm area into separate areas, each area with its own
978 static int madvise_vma_behavior(struct vm_area_struct *vma,
979 struct vm_area_struct **prev,
980 unsigned long start, unsigned long end,
981 unsigned long behavior)
984 struct anon_vma_name *anon_name;
985 unsigned long new_flags = vma->vm_flags;
989 return madvise_remove(vma, prev, start, end);
991 return madvise_willneed(vma, prev, start, end);
993 return madvise_cold(vma, prev, start, end);
995 return madvise_pageout(vma, prev, start, end);
998 case MADV_DONTNEED_LOCKED:
999 return madvise_dontneed_free(vma, prev, start, end, behavior);
1000 case MADV_POPULATE_READ:
1001 case MADV_POPULATE_WRITE:
1002 return madvise_populate(vma, prev, start, end, behavior);
1004 new_flags = new_flags & ~VM_RAND_READ & ~VM_SEQ_READ;
1006 case MADV_SEQUENTIAL:
1007 new_flags = (new_flags & ~VM_RAND_READ) | VM_SEQ_READ;
1010 new_flags = (new_flags & ~VM_SEQ_READ) | VM_RAND_READ;
1013 new_flags |= VM_DONTCOPY;
1016 if (vma->vm_flags & VM_IO)
1018 new_flags &= ~VM_DONTCOPY;
1020 case MADV_WIPEONFORK:
1021 /* MADV_WIPEONFORK is only supported on anonymous memory. */
1022 if (vma->vm_file || vma->vm_flags & VM_SHARED)
1024 new_flags |= VM_WIPEONFORK;
1026 case MADV_KEEPONFORK:
1027 new_flags &= ~VM_WIPEONFORK;
1030 new_flags |= VM_DONTDUMP;
1033 if (!is_vm_hugetlb_page(vma) && new_flags & VM_SPECIAL)
1035 new_flags &= ~VM_DONTDUMP;
1037 case MADV_MERGEABLE:
1038 case MADV_UNMERGEABLE:
1039 error = ksm_madvise(vma, start, end, behavior, &new_flags);
1044 case MADV_NOHUGEPAGE:
1045 error = hugepage_madvise(vma, &new_flags, behavior);
1051 anon_name = anon_vma_name(vma);
1052 anon_vma_name_get(anon_name);
1053 error = madvise_update_vma(vma, prev, start, end, new_flags,
1055 anon_vma_name_put(anon_name);
1059 * madvise() returns EAGAIN if kernel resources, such as
1060 * slab, are temporarily unavailable.
1062 if (error == -ENOMEM)
1067 #ifdef CONFIG_MEMORY_FAILURE
1069 * Error injection support for memory error handling.
1071 static int madvise_inject_error(int behavior,
1072 unsigned long start, unsigned long end)
1076 if (!capable(CAP_SYS_ADMIN))
1080 for (; start < end; start += size) {
1085 ret = get_user_pages_fast(start, 1, 0, &page);
1088 pfn = page_to_pfn(page);
1091 * When soft offlining hugepages, after migrating the page
1092 * we dissolve it, therefore in the second loop "page" will
1093 * no longer be a compound page.
1095 size = page_size(compound_head(page));
1097 if (behavior == MADV_SOFT_OFFLINE) {
1098 pr_info("Soft offlining pfn %#lx at process virtual address %#lx\n",
1100 ret = soft_offline_page(pfn, MF_COUNT_INCREASED);
1102 pr_info("Injecting memory failure for pfn %#lx at process virtual address %#lx\n",
1104 ret = memory_failure(pfn, MF_COUNT_INCREASED);
1105 if (ret == -EOPNOTSUPP)
1118 madvise_behavior_valid(int behavior)
1124 case MADV_SEQUENTIAL:
1129 case MADV_DONTNEED_LOCKED:
1133 case MADV_POPULATE_READ:
1134 case MADV_POPULATE_WRITE:
1136 case MADV_MERGEABLE:
1137 case MADV_UNMERGEABLE:
1139 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1141 case MADV_NOHUGEPAGE:
1145 case MADV_WIPEONFORK:
1146 case MADV_KEEPONFORK:
1147 #ifdef CONFIG_MEMORY_FAILURE
1148 case MADV_SOFT_OFFLINE:
1159 process_madvise_behavior_valid(int behavior)
1172 * Walk the vmas in range [start,end), and call the visit function on each one.
1173 * The visit function will get start and end parameters that cover the overlap
1174 * between the current vma and the original range. Any unmapped regions in the
1175 * original range will result in this function returning -ENOMEM while still
1176 * calling the visit function on all of the existing vmas in the range.
1177 * Must be called with the mmap_lock held for reading or writing.
1180 int madvise_walk_vmas(struct mm_struct *mm, unsigned long start,
1181 unsigned long end, unsigned long arg,
1182 int (*visit)(struct vm_area_struct *vma,
1183 struct vm_area_struct **prev, unsigned long start,
1184 unsigned long end, unsigned long arg))
1186 struct vm_area_struct *vma;
1187 struct vm_area_struct *prev;
1189 int unmapped_error = 0;
1192 * If the interval [start,end) covers some unmapped address
1193 * ranges, just ignore them, but return -ENOMEM at the end.
1194 * - different from the way of handling in mlock etc.
1196 vma = find_vma_prev(mm, start, &prev);
1197 if (vma && start > vma->vm_start)
1203 /* Still start < end. */
1207 /* Here start < (end|vma->vm_end). */
1208 if (start < vma->vm_start) {
1209 unmapped_error = -ENOMEM;
1210 start = vma->vm_start;
1215 /* Here vma->vm_start <= start < (end|vma->vm_end) */
1220 /* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
1221 error = visit(vma, &prev, start, tmp, arg);
1225 if (prev && start < prev->vm_end)
1226 start = prev->vm_end;
1230 vma = prev->vm_next;
1231 else /* madvise_remove dropped mmap_lock */
1232 vma = find_vma(mm, start);
1235 return unmapped_error;
1238 #ifdef CONFIG_ANON_VMA_NAME
1239 static int madvise_vma_anon_name(struct vm_area_struct *vma,
1240 struct vm_area_struct **prev,
1241 unsigned long start, unsigned long end,
1242 unsigned long anon_name)
1246 /* Only anonymous mappings can be named */
1250 error = madvise_update_vma(vma, prev, start, end, vma->vm_flags,
1251 (struct anon_vma_name *)anon_name);
1254 * madvise() returns EAGAIN if kernel resources, such as
1255 * slab, are temporarily unavailable.
1257 if (error == -ENOMEM)
1262 int madvise_set_anon_name(struct mm_struct *mm, unsigned long start,
1263 unsigned long len_in, struct anon_vma_name *anon_name)
1268 if (start & ~PAGE_MASK)
1270 len = (len_in + ~PAGE_MASK) & PAGE_MASK;
1272 /* Check to see whether len was rounded up from small -ve to zero */
1283 return madvise_walk_vmas(mm, start, end, (unsigned long)anon_name,
1284 madvise_vma_anon_name);
1286 #endif /* CONFIG_ANON_VMA_NAME */
1288 * The madvise(2) system call.
1290 * Applications can use madvise() to advise the kernel how it should
1291 * handle paging I/O in this VM area. The idea is to help the kernel
1292 * use appropriate read-ahead and caching techniques. The information
1293 * provided is advisory only, and can be safely disregarded by the
1294 * kernel without affecting the correct operation of the application.
1297 * MADV_NORMAL - the default behavior is to read clusters. This
1298 * results in some read-ahead and read-behind.
1299 * MADV_RANDOM - the system should read the minimum amount of data
1300 * on any access, since it is unlikely that the appli-
1301 * cation will need more than what it asks for.
1302 * MADV_SEQUENTIAL - pages in the given range will probably be accessed
1303 * once, so they can be aggressively read ahead, and
1304 * can be freed soon after they are accessed.
1305 * MADV_WILLNEED - the application is notifying the system to read
1307 * MADV_DONTNEED - the application is finished with the given range,
1308 * so the kernel can free resources associated with it.
1309 * MADV_FREE - the application marks pages in the given range as lazy free,
1310 * where actual purges are postponed until memory pressure happens.
1311 * MADV_REMOVE - the application wants to free up the given range of
1312 * pages and associated backing store.
1313 * MADV_DONTFORK - omit this area from child's address space when forking:
1314 * typically, to avoid COWing pages pinned by get_user_pages().
1315 * MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
1316 * MADV_WIPEONFORK - present the child process with zero-filled memory in this
1317 * range after a fork.
1318 * MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
1319 * MADV_HWPOISON - trigger memory error handler as if the given memory range
1320 * were corrupted by unrecoverable hardware memory failure.
1321 * MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
1322 * MADV_MERGEABLE - the application recommends that KSM try to merge pages in
1323 * this area with pages of identical content from other such areas.
1324 * MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
1325 * MADV_HUGEPAGE - the application wants to back the given range by transparent
1326 * huge pages in the future. Existing pages might be coalesced and
1327 * new pages might be allocated as THP.
1328 * MADV_NOHUGEPAGE - mark the given range as not worth being backed by
1329 * transparent huge pages so the existing pages will not be
1330 * coalesced into THP and new pages will not be allocated as THP.
1331 * MADV_DONTDUMP - the application wants to prevent pages in the given range
1332 * from being included in its core dump.
1333 * MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
1334 * MADV_COLD - the application is not expected to use this memory soon,
1335 * deactivate pages in this range so that they can be reclaimed
1336 * easily if memory pressure happens.
1337 * MADV_PAGEOUT - the application is not expected to use this memory soon,
1338 * page out the pages in this range immediately.
1339 * MADV_POPULATE_READ - populate (prefault) page tables readable by
1340 * triggering read faults if required
1341 * MADV_POPULATE_WRITE - populate (prefault) page tables writable by
1342 * triggering write faults if required
1346 * -EINVAL - start + len < 0, start is not page-aligned,
1347 * "behavior" is not a valid value, or application
1348 * is attempting to release locked or shared pages,
1349 * or the specified address range includes file, Huge TLB,
1350 * MAP_SHARED or VMPFNMAP range.
1351 * -ENOMEM - addresses in the specified range are not currently
1352 * mapped, or are outside the AS of the process.
1353 * -EIO - an I/O error occurred while paging in data.
1354 * -EBADF - map exists, but area maps something that isn't a file.
1355 * -EAGAIN - a kernel resource was temporarily unavailable.
1357 int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int behavior)
1363 struct blk_plug plug;
1365 start = untagged_addr(start);
1367 if (!madvise_behavior_valid(behavior))
1370 if (!PAGE_ALIGNED(start))
1372 len = PAGE_ALIGN(len_in);
1374 /* Check to see whether len was rounded up from small -ve to zero */
1385 #ifdef CONFIG_MEMORY_FAILURE
1386 if (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)
1387 return madvise_inject_error(behavior, start, start + len_in);
1390 write = madvise_need_mmap_write(behavior);
1392 if (mmap_write_lock_killable(mm))
1398 blk_start_plug(&plug);
1399 error = madvise_walk_vmas(mm, start, end, behavior,
1400 madvise_vma_behavior);
1401 blk_finish_plug(&plug);
1403 mmap_write_unlock(mm);
1405 mmap_read_unlock(mm);
1410 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
1412 return do_madvise(current->mm, start, len_in, behavior);
1415 SYSCALL_DEFINE5(process_madvise, int, pidfd, const struct iovec __user *, vec,
1416 size_t, vlen, int, behavior, unsigned int, flags)
1419 struct iovec iovstack[UIO_FASTIOV], iovec;
1420 struct iovec *iov = iovstack;
1421 struct iov_iter iter;
1422 struct task_struct *task;
1423 struct mm_struct *mm;
1425 unsigned int f_flags;
1432 ret = import_iovec(READ, vec, vlen, ARRAY_SIZE(iovstack), &iov, &iter);
1436 task = pidfd_get_task(pidfd, &f_flags);
1438 ret = PTR_ERR(task);
1442 if (!process_madvise_behavior_valid(behavior)) {
1447 /* Require PTRACE_MODE_READ to avoid leaking ASLR metadata. */
1448 mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
1449 if (IS_ERR_OR_NULL(mm)) {
1450 ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
1455 * Require CAP_SYS_NICE for influencing process performance. Note that
1456 * only non-destructive hints are currently supported.
1458 if (!capable(CAP_SYS_NICE)) {
1463 total_len = iov_iter_count(&iter);
1465 while (iov_iter_count(&iter)) {
1466 iovec = iov_iter_iovec(&iter);
1468 * do_madvise returns ENOMEM if unmapped holes are present
1469 * in the passed VMA. process_madvise() is expected to skip
1470 * unmapped holes passed to it in the 'struct iovec' list
1471 * and not fail because of them. Thus treat -ENOMEM return
1472 * from do_madvise as valid and continue processing.
1474 ret = do_madvise(mm, (unsigned long)iovec.iov_base,
1475 iovec.iov_len, behavior);
1476 if (ret < 0 && ret != -ENOMEM)
1478 iov_iter_advance(&iter, iovec.iov_len);
1481 ret = (total_len - iov_iter_count(&iter)) ? : ret;
1486 put_task_struct(task);