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>
40 struct madvise_walk_private {
41 struct mmu_gather *tlb;
46 * Any behaviour which results in changes to the vma->vm_flags needs to
47 * take mmap_lock for writing. Others, which simply traverse vmas, need
48 * to only take it for reading.
50 static int madvise_need_mmap_write(int behavior)
56 case MADV_DONTNEED_LOCKED:
60 case MADV_POPULATE_READ:
61 case MADV_POPULATE_WRITE:
64 /* be safe, default to 1. list exceptions explicitly */
69 #ifdef CONFIG_ANON_VMA_NAME
70 struct anon_vma_name *anon_vma_name_alloc(const char *name)
72 struct anon_vma_name *anon_name;
75 /* Add 1 for NUL terminator at the end of the anon_name->name */
76 count = strlen(name) + 1;
77 anon_name = kmalloc(struct_size(anon_name, name, count), GFP_KERNEL);
79 kref_init(&anon_name->kref);
80 memcpy(anon_name->name, name, count);
86 void anon_vma_name_free(struct kref *kref)
88 struct anon_vma_name *anon_name =
89 container_of(kref, struct anon_vma_name, kref);
93 struct anon_vma_name *anon_vma_name(struct vm_area_struct *vma)
95 mmap_assert_locked(vma->vm_mm);
100 return vma->anon_name;
103 /* mmap_lock should be write-locked */
104 static int replace_anon_vma_name(struct vm_area_struct *vma,
105 struct anon_vma_name *anon_name)
107 struct anon_vma_name *orig_name = anon_vma_name(vma);
110 vma->anon_name = NULL;
111 anon_vma_name_put(orig_name);
115 if (anon_vma_name_eq(orig_name, anon_name))
118 vma->anon_name = anon_vma_name_reuse(anon_name);
119 anon_vma_name_put(orig_name);
123 #else /* CONFIG_ANON_VMA_NAME */
124 static int replace_anon_vma_name(struct vm_area_struct *vma,
125 struct anon_vma_name *anon_name)
132 #endif /* CONFIG_ANON_VMA_NAME */
134 * Update the vm_flags on region of a vma, splitting it or merging it as
135 * necessary. Must be called with mmap_sem held for writing;
136 * Caller should ensure anon_name stability by raising its refcount even when
137 * anon_name belongs to a valid vma because this function might free that vma.
139 static int madvise_update_vma(struct vm_area_struct *vma,
140 struct vm_area_struct **prev, unsigned long start,
141 unsigned long end, unsigned long new_flags,
142 struct anon_vma_name *anon_name)
144 struct mm_struct *mm = vma->vm_mm;
148 if (new_flags == vma->vm_flags && anon_vma_name_eq(anon_vma_name(vma), anon_name)) {
153 pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
154 *prev = vma_merge(mm, *prev, start, end, new_flags, vma->anon_vma,
155 vma->vm_file, pgoff, vma_policy(vma),
156 vma->vm_userfaultfd_ctx, anon_name);
164 if (start != vma->vm_start) {
165 if (unlikely(mm->map_count >= sysctl_max_map_count))
167 error = __split_vma(mm, vma, start, 1);
172 if (end != vma->vm_end) {
173 if (unlikely(mm->map_count >= sysctl_max_map_count))
175 error = __split_vma(mm, vma, end, 0);
182 * vm_flags is protected by the mmap_lock held in write mode.
184 vma->vm_flags = new_flags;
186 error = replace_anon_vma_name(vma, anon_name);
195 static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
196 unsigned long end, struct mm_walk *walk)
199 struct vm_area_struct *vma = walk->private;
201 struct swap_iocb *splug = NULL;
203 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
206 for (index = start; index != end; index += PAGE_SIZE) {
212 orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, start, &ptl);
213 pte = *(orig_pte + ((index - start) / PAGE_SIZE));
214 pte_unmap_unlock(orig_pte, ptl);
216 if (pte_present(pte) || pte_none(pte))
218 entry = pte_to_swp_entry(pte);
219 if (unlikely(non_swap_entry(entry)))
222 page = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE,
223 vma, index, false, &splug);
227 swap_read_unplug(splug);
232 static const struct mm_walk_ops swapin_walk_ops = {
233 .pmd_entry = swapin_walk_pmd_entry,
236 static void force_shm_swapin_readahead(struct vm_area_struct *vma,
237 unsigned long start, unsigned long end,
238 struct address_space *mapping)
240 XA_STATE(xas, &mapping->i_pages, linear_page_index(vma, start));
241 pgoff_t end_index = linear_page_index(vma, end + PAGE_SIZE - 1);
243 struct swap_iocb *splug = NULL;
246 xas_for_each(&xas, page, end_index) {
249 if (!xa_is_value(page))
254 swap = radix_to_swp_entry(page);
255 page = read_swap_cache_async(swap, GFP_HIGHUSER_MOVABLE,
256 NULL, 0, false, &splug);
263 swap_read_unplug(splug);
265 lru_add_drain(); /* Push any new pages onto the LRU now */
267 #endif /* CONFIG_SWAP */
270 * Schedule all required I/O operations. Do not wait for completion.
272 static long madvise_willneed(struct vm_area_struct *vma,
273 struct vm_area_struct **prev,
274 unsigned long start, unsigned long end)
276 struct mm_struct *mm = vma->vm_mm;
277 struct file *file = vma->vm_file;
283 walk_page_range(vma->vm_mm, start, end, &swapin_walk_ops, vma);
284 lru_add_drain(); /* Push any new pages onto the LRU now */
288 if (shmem_mapping(file->f_mapping)) {
289 force_shm_swapin_readahead(vma, start, end,
298 if (IS_DAX(file_inode(file))) {
299 /* no bad return value, but ignore advice */
304 * Filesystem's fadvise may need to take various locks. We need to
305 * explicitly grab a reference because the vma (and hence the
306 * vma's reference to the file) can go away as soon as we drop
309 *prev = NULL; /* tell sys_madvise we drop mmap_lock */
311 offset = (loff_t)(start - vma->vm_start)
312 + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
313 mmap_read_unlock(mm);
314 vfs_fadvise(file, offset, end - start, POSIX_FADV_WILLNEED);
320 static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
321 unsigned long addr, unsigned long end,
322 struct mm_walk *walk)
324 struct madvise_walk_private *private = walk->private;
325 struct mmu_gather *tlb = private->tlb;
326 bool pageout = private->pageout;
327 struct mm_struct *mm = tlb->mm;
328 struct vm_area_struct *vma = walk->vma;
329 pte_t *orig_pte, *pte, ptent;
331 struct page *page = NULL;
332 LIST_HEAD(page_list);
334 if (fatal_signal_pending(current))
337 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
338 if (pmd_trans_huge(*pmd)) {
340 unsigned long next = pmd_addr_end(addr, end);
342 tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
343 ptl = pmd_trans_huge_lock(pmd, vma);
348 if (is_huge_zero_pmd(orig_pmd))
351 if (unlikely(!pmd_present(orig_pmd))) {
352 VM_BUG_ON(thp_migration_supported() &&
353 !is_pmd_migration_entry(orig_pmd));
357 page = pmd_page(orig_pmd);
359 /* Do not interfere with other mappings of this page */
360 if (page_mapcount(page) != 1)
363 if (next - addr != HPAGE_PMD_SIZE) {
369 err = split_huge_page(page);
377 if (pmd_young(orig_pmd)) {
378 pmdp_invalidate(vma, addr, pmd);
379 orig_pmd = pmd_mkold(orig_pmd);
381 set_pmd_at(mm, addr, pmd, orig_pmd);
382 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
385 ClearPageReferenced(page);
386 test_and_clear_page_young(page);
388 if (!isolate_lru_page(page)) {
389 if (PageUnevictable(page))
390 putback_lru_page(page);
392 list_add(&page->lru, &page_list);
395 deactivate_page(page);
399 reclaim_pages(&page_list);
404 if (pmd_trans_unstable(pmd))
407 tlb_change_page_size(tlb, PAGE_SIZE);
408 orig_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
409 flush_tlb_batched_pending(mm);
410 arch_enter_lazy_mmu_mode();
411 for (; addr < end; pte++, addr += PAGE_SIZE) {
417 if (!pte_present(ptent))
420 page = vm_normal_page(vma, addr, ptent);
425 * Creating a THP page is expensive so split it only if we
426 * are sure it's worth. Split it if we are only owner.
428 if (PageTransCompound(page)) {
429 if (page_mapcount(page) != 1)
432 if (!trylock_page(page)) {
436 pte_unmap_unlock(orig_pte, ptl);
437 if (split_huge_page(page)) {
440 orig_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
445 orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
451 /* Do not interfere with other mappings of this page */
452 if (page_mapcount(page) != 1)
455 VM_BUG_ON_PAGE(PageTransCompound(page), page);
457 if (pte_young(ptent)) {
458 ptent = ptep_get_and_clear_full(mm, addr, pte,
460 ptent = pte_mkold(ptent);
461 set_pte_at(mm, addr, pte, ptent);
462 tlb_remove_tlb_entry(tlb, pte, addr);
466 * We are deactivating a page for accelerating reclaiming.
467 * VM couldn't reclaim the page unless we clear PG_young.
468 * As a side effect, it makes confuse idle-page tracking
469 * because they will miss recent referenced history.
471 ClearPageReferenced(page);
472 test_and_clear_page_young(page);
474 if (!isolate_lru_page(page)) {
475 if (PageUnevictable(page))
476 putback_lru_page(page);
478 list_add(&page->lru, &page_list);
481 deactivate_page(page);
484 arch_leave_lazy_mmu_mode();
485 pte_unmap_unlock(orig_pte, ptl);
487 reclaim_pages(&page_list);
493 static const struct mm_walk_ops cold_walk_ops = {
494 .pmd_entry = madvise_cold_or_pageout_pte_range,
497 static void madvise_cold_page_range(struct mmu_gather *tlb,
498 struct vm_area_struct *vma,
499 unsigned long addr, unsigned long end)
501 struct madvise_walk_private walk_private = {
506 tlb_start_vma(tlb, vma);
507 walk_page_range(vma->vm_mm, addr, end, &cold_walk_ops, &walk_private);
508 tlb_end_vma(tlb, vma);
511 static inline bool can_madv_lru_vma(struct vm_area_struct *vma)
513 return !(vma->vm_flags & (VM_LOCKED|VM_PFNMAP|VM_HUGETLB));
516 static long madvise_cold(struct vm_area_struct *vma,
517 struct vm_area_struct **prev,
518 unsigned long start_addr, unsigned long end_addr)
520 struct mm_struct *mm = vma->vm_mm;
521 struct mmu_gather tlb;
524 if (!can_madv_lru_vma(vma))
528 tlb_gather_mmu(&tlb, mm);
529 madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
530 tlb_finish_mmu(&tlb);
535 static void madvise_pageout_page_range(struct mmu_gather *tlb,
536 struct vm_area_struct *vma,
537 unsigned long addr, unsigned long end)
539 struct madvise_walk_private walk_private = {
544 tlb_start_vma(tlb, vma);
545 walk_page_range(vma->vm_mm, addr, end, &cold_walk_ops, &walk_private);
546 tlb_end_vma(tlb, vma);
549 static inline bool can_do_pageout(struct vm_area_struct *vma)
551 if (vma_is_anonymous(vma))
556 * paging out pagecache only for non-anonymous mappings that correspond
557 * to the files the calling process could (if tried) open for writing;
558 * otherwise we'd be including shared non-exclusive mappings, which
559 * opens a side channel.
561 return inode_owner_or_capable(&init_user_ns,
562 file_inode(vma->vm_file)) ||
563 file_permission(vma->vm_file, MAY_WRITE) == 0;
566 static long madvise_pageout(struct vm_area_struct *vma,
567 struct vm_area_struct **prev,
568 unsigned long start_addr, unsigned long end_addr)
570 struct mm_struct *mm = vma->vm_mm;
571 struct mmu_gather tlb;
574 if (!can_madv_lru_vma(vma))
577 if (!can_do_pageout(vma))
581 tlb_gather_mmu(&tlb, mm);
582 madvise_pageout_page_range(&tlb, vma, start_addr, end_addr);
583 tlb_finish_mmu(&tlb);
588 static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
589 unsigned long end, struct mm_walk *walk)
592 struct mmu_gather *tlb = walk->private;
593 struct mm_struct *mm = tlb->mm;
594 struct vm_area_struct *vma = walk->vma;
596 pte_t *orig_pte, *pte, ptent;
601 next = pmd_addr_end(addr, end);
602 if (pmd_trans_huge(*pmd))
603 if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
606 if (pmd_trans_unstable(pmd))
609 tlb_change_page_size(tlb, PAGE_SIZE);
610 orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
611 flush_tlb_batched_pending(mm);
612 arch_enter_lazy_mmu_mode();
613 for (; addr != end; pte++, addr += PAGE_SIZE) {
619 * If the pte has swp_entry, just clear page table to
620 * prevent swap-in which is more expensive rather than
621 * (page allocation + zeroing).
623 if (!pte_present(ptent)) {
626 entry = pte_to_swp_entry(ptent);
627 if (non_swap_entry(entry))
630 free_swap_and_cache(entry);
631 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
635 page = vm_normal_page(vma, addr, ptent);
640 * If pmd isn't transhuge but the page is THP and
641 * is owned by only this process, split it and
642 * deactivate all pages.
644 if (PageTransCompound(page)) {
645 if (page_mapcount(page) != 1)
648 if (!trylock_page(page)) {
652 pte_unmap_unlock(orig_pte, ptl);
653 if (split_huge_page(page)) {
656 orig_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
661 orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
667 VM_BUG_ON_PAGE(PageTransCompound(page), page);
669 if (PageSwapCache(page) || PageDirty(page)) {
670 if (!trylock_page(page))
673 * If page is shared with others, we couldn't clear
674 * PG_dirty of the page.
676 if (page_mapcount(page) != 1) {
681 if (PageSwapCache(page) && !try_to_free_swap(page)) {
686 ClearPageDirty(page);
690 if (pte_young(ptent) || pte_dirty(ptent)) {
692 * Some of architecture(ex, PPC) don't update TLB
693 * with set_pte_at and tlb_remove_tlb_entry so for
694 * the portability, remap the pte with old|clean
695 * after pte clearing.
697 ptent = ptep_get_and_clear_full(mm, addr, pte,
700 ptent = pte_mkold(ptent);
701 ptent = pte_mkclean(ptent);
702 set_pte_at(mm, addr, pte, ptent);
703 tlb_remove_tlb_entry(tlb, pte, addr);
705 mark_page_lazyfree(page);
709 if (current->mm == mm)
712 add_mm_counter(mm, MM_SWAPENTS, nr_swap);
714 arch_leave_lazy_mmu_mode();
715 pte_unmap_unlock(orig_pte, ptl);
721 static const struct mm_walk_ops madvise_free_walk_ops = {
722 .pmd_entry = madvise_free_pte_range,
725 static int madvise_free_single_vma(struct vm_area_struct *vma,
726 unsigned long start_addr, unsigned long end_addr)
728 struct mm_struct *mm = vma->vm_mm;
729 struct mmu_notifier_range range;
730 struct mmu_gather tlb;
732 /* MADV_FREE works for only anon vma at the moment */
733 if (!vma_is_anonymous(vma))
736 range.start = max(vma->vm_start, start_addr);
737 if (range.start >= vma->vm_end)
739 range.end = min(vma->vm_end, end_addr);
740 if (range.end <= vma->vm_start)
742 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
743 range.start, range.end);
746 tlb_gather_mmu(&tlb, mm);
747 update_hiwater_rss(mm);
749 mmu_notifier_invalidate_range_start(&range);
750 tlb_start_vma(&tlb, vma);
751 walk_page_range(vma->vm_mm, range.start, range.end,
752 &madvise_free_walk_ops, &tlb);
753 tlb_end_vma(&tlb, vma);
754 mmu_notifier_invalidate_range_end(&range);
755 tlb_finish_mmu(&tlb);
761 * Application no longer needs these pages. If the pages are dirty,
762 * it's OK to just throw them away. The app will be more careful about
763 * data it wants to keep. Be sure to free swap resources too. The
764 * zap_page_range call sets things up for shrink_active_list to actually free
765 * these pages later if no one else has touched them in the meantime,
766 * although we could add these pages to a global reuse list for
767 * shrink_active_list to pick up before reclaiming other pages.
769 * NB: This interface discards data rather than pushes it out to swap,
770 * as some implementations do. This has performance implications for
771 * applications like large transactional databases which want to discard
772 * pages in anonymous maps after committing to backing store the data
773 * that was kept in them. There is no reason to write this data out to
774 * the swap area if the application is discarding it.
776 * An interface that causes the system to free clean pages and flush
777 * dirty pages is already available as msync(MS_INVALIDATE).
779 static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
780 unsigned long start, unsigned long end)
782 zap_page_range(vma, start, end - start);
786 static bool madvise_dontneed_free_valid_vma(struct vm_area_struct *vma,
791 if (!is_vm_hugetlb_page(vma)) {
792 unsigned int forbidden = VM_PFNMAP;
794 if (behavior != MADV_DONTNEED_LOCKED)
795 forbidden |= VM_LOCKED;
797 return !(vma->vm_flags & forbidden);
800 if (behavior != MADV_DONTNEED && behavior != MADV_DONTNEED_LOCKED)
802 if (start & ~huge_page_mask(hstate_vma(vma)))
805 *end = ALIGN(*end, huge_page_size(hstate_vma(vma)));
809 static long madvise_dontneed_free(struct vm_area_struct *vma,
810 struct vm_area_struct **prev,
811 unsigned long start, unsigned long end,
814 struct mm_struct *mm = vma->vm_mm;
817 if (!madvise_dontneed_free_valid_vma(vma, start, &end, behavior))
820 if (!userfaultfd_remove(vma, start, end)) {
821 *prev = NULL; /* mmap_lock has been dropped, prev is stale */
824 vma = find_vma(mm, start);
827 if (start < vma->vm_start) {
829 * This "vma" under revalidation is the one
830 * with the lowest vma->vm_start where start
831 * is also < vma->vm_end. If start <
832 * vma->vm_start it means an hole materialized
833 * in the user address space within the
834 * virtual range passed to MADV_DONTNEED
840 * Potential end adjustment for hugetlb vma is OK as
841 * the check below keeps end within vma.
843 if (!madvise_dontneed_free_valid_vma(vma, start, &end,
846 if (end > vma->vm_end) {
848 * Don't fail if end > vma->vm_end. If the old
849 * vma was split while the mmap_lock was
850 * released the effect of the concurrent
851 * operation may not cause madvise() to
852 * have an undefined result. There may be an
853 * adjacent next vma that we'll walk
854 * next. userfaultfd_remove() will generate an
855 * UFFD_EVENT_REMOVE repetition on the
856 * end-vma->vm_end range, but the manager can
857 * handle a repetition fine.
861 VM_WARN_ON(start >= end);
864 if (behavior == MADV_DONTNEED || behavior == MADV_DONTNEED_LOCKED)
865 return madvise_dontneed_single_vma(vma, start, end);
866 else if (behavior == MADV_FREE)
867 return madvise_free_single_vma(vma, start, end);
872 static long madvise_populate(struct vm_area_struct *vma,
873 struct vm_area_struct **prev,
874 unsigned long start, unsigned long end,
877 const bool write = behavior == MADV_POPULATE_WRITE;
878 struct mm_struct *mm = vma->vm_mm;
879 unsigned long tmp_end;
885 while (start < end) {
887 * We might have temporarily dropped the lock. For example,
888 * our VMA might have been split.
890 if (!vma || start >= vma->vm_end) {
891 vma = vma_lookup(mm, start);
896 tmp_end = min_t(unsigned long, end, vma->vm_end);
897 /* Populate (prefault) page tables readable/writable. */
898 pages = faultin_vma_page_range(vma, start, tmp_end, write,
910 case -EINVAL: /* Incompatible mappings / permissions. */
914 case -EFAULT: /* VM_FAULT_SIGBUS or VM_FAULT_SIGSEGV */
917 pr_warn_once("%s: unhandled return value: %ld\n",
924 start += pages * PAGE_SIZE;
930 * Application wants to free up the pages and associated backing store.
931 * This is effectively punching a hole into the middle of a file.
933 static long madvise_remove(struct vm_area_struct *vma,
934 struct vm_area_struct **prev,
935 unsigned long start, unsigned long end)
940 struct mm_struct *mm = vma->vm_mm;
942 *prev = NULL; /* tell sys_madvise we drop mmap_lock */
944 if (vma->vm_flags & VM_LOCKED)
949 if (!f || !f->f_mapping || !f->f_mapping->host) {
953 if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
956 offset = (loff_t)(start - vma->vm_start)
957 + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
960 * Filesystem's fallocate may need to take i_rwsem. We need to
961 * explicitly grab a reference because the vma (and hence the
962 * vma's reference to the file) can go away as soon as we drop
966 if (userfaultfd_remove(vma, start, end)) {
967 /* mmap_lock was not released by userfaultfd_remove() */
968 mmap_read_unlock(mm);
970 error = vfs_fallocate(f,
971 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
972 offset, end - start);
979 * Apply an madvise behavior to a region of a vma. madvise_update_vma
980 * will handle splitting a vm area into separate areas, each area with its own
983 static int madvise_vma_behavior(struct vm_area_struct *vma,
984 struct vm_area_struct **prev,
985 unsigned long start, unsigned long end,
986 unsigned long behavior)
989 struct anon_vma_name *anon_name;
990 unsigned long new_flags = vma->vm_flags;
994 return madvise_remove(vma, prev, start, end);
996 return madvise_willneed(vma, prev, start, end);
998 return madvise_cold(vma, prev, start, end);
1000 return madvise_pageout(vma, prev, start, end);
1003 case MADV_DONTNEED_LOCKED:
1004 return madvise_dontneed_free(vma, prev, start, end, behavior);
1005 case MADV_POPULATE_READ:
1006 case MADV_POPULATE_WRITE:
1007 return madvise_populate(vma, prev, start, end, behavior);
1009 new_flags = new_flags & ~VM_RAND_READ & ~VM_SEQ_READ;
1011 case MADV_SEQUENTIAL:
1012 new_flags = (new_flags & ~VM_RAND_READ) | VM_SEQ_READ;
1015 new_flags = (new_flags & ~VM_SEQ_READ) | VM_RAND_READ;
1018 new_flags |= VM_DONTCOPY;
1021 if (vma->vm_flags & VM_IO)
1023 new_flags &= ~VM_DONTCOPY;
1025 case MADV_WIPEONFORK:
1026 /* MADV_WIPEONFORK is only supported on anonymous memory. */
1027 if (vma->vm_file || vma->vm_flags & VM_SHARED)
1029 new_flags |= VM_WIPEONFORK;
1031 case MADV_KEEPONFORK:
1032 new_flags &= ~VM_WIPEONFORK;
1035 new_flags |= VM_DONTDUMP;
1038 if (!is_vm_hugetlb_page(vma) && new_flags & VM_SPECIAL)
1040 new_flags &= ~VM_DONTDUMP;
1042 case MADV_MERGEABLE:
1043 case MADV_UNMERGEABLE:
1044 error = ksm_madvise(vma, start, end, behavior, &new_flags);
1049 case MADV_NOHUGEPAGE:
1050 error = hugepage_madvise(vma, &new_flags, behavior);
1056 anon_name = anon_vma_name(vma);
1057 anon_vma_name_get(anon_name);
1058 error = madvise_update_vma(vma, prev, start, end, new_flags,
1060 anon_vma_name_put(anon_name);
1064 * madvise() returns EAGAIN if kernel resources, such as
1065 * slab, are temporarily unavailable.
1067 if (error == -ENOMEM)
1072 #ifdef CONFIG_MEMORY_FAILURE
1074 * Error injection support for memory error handling.
1076 static int madvise_inject_error(int behavior,
1077 unsigned long start, unsigned long end)
1081 if (!capable(CAP_SYS_ADMIN))
1085 for (; start < end; start += size) {
1090 ret = get_user_pages_fast(start, 1, 0, &page);
1093 pfn = page_to_pfn(page);
1096 * When soft offlining hugepages, after migrating the page
1097 * we dissolve it, therefore in the second loop "page" will
1098 * no longer be a compound page.
1100 size = page_size(compound_head(page));
1102 if (behavior == MADV_SOFT_OFFLINE) {
1103 pr_info("Soft offlining pfn %#lx at process virtual address %#lx\n",
1105 ret = soft_offline_page(pfn, MF_COUNT_INCREASED);
1107 pr_info("Injecting memory failure for pfn %#lx at process virtual address %#lx\n",
1109 ret = memory_failure(pfn, MF_COUNT_INCREASED);
1110 if (ret == -EOPNOTSUPP)
1123 madvise_behavior_valid(int behavior)
1129 case MADV_SEQUENTIAL:
1134 case MADV_DONTNEED_LOCKED:
1138 case MADV_POPULATE_READ:
1139 case MADV_POPULATE_WRITE:
1141 case MADV_MERGEABLE:
1142 case MADV_UNMERGEABLE:
1144 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1146 case MADV_NOHUGEPAGE:
1150 case MADV_WIPEONFORK:
1151 case MADV_KEEPONFORK:
1152 #ifdef CONFIG_MEMORY_FAILURE
1153 case MADV_SOFT_OFFLINE:
1164 process_madvise_behavior_valid(int behavior)
1177 * Walk the vmas in range [start,end), and call the visit function on each one.
1178 * The visit function will get start and end parameters that cover the overlap
1179 * between the current vma and the original range. Any unmapped regions in the
1180 * original range will result in this function returning -ENOMEM while still
1181 * calling the visit function on all of the existing vmas in the range.
1182 * Must be called with the mmap_lock held for reading or writing.
1185 int madvise_walk_vmas(struct mm_struct *mm, unsigned long start,
1186 unsigned long end, unsigned long arg,
1187 int (*visit)(struct vm_area_struct *vma,
1188 struct vm_area_struct **prev, unsigned long start,
1189 unsigned long end, unsigned long arg))
1191 struct vm_area_struct *vma;
1192 struct vm_area_struct *prev;
1194 int unmapped_error = 0;
1197 * If the interval [start,end) covers some unmapped address
1198 * ranges, just ignore them, but return -ENOMEM at the end.
1199 * - different from the way of handling in mlock etc.
1201 vma = find_vma_prev(mm, start, &prev);
1202 if (vma && start > vma->vm_start)
1208 /* Still start < end. */
1212 /* Here start < (end|vma->vm_end). */
1213 if (start < vma->vm_start) {
1214 unmapped_error = -ENOMEM;
1215 start = vma->vm_start;
1220 /* Here vma->vm_start <= start < (end|vma->vm_end) */
1225 /* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
1226 error = visit(vma, &prev, start, tmp, arg);
1230 if (prev && start < prev->vm_end)
1231 start = prev->vm_end;
1235 vma = prev->vm_next;
1236 else /* madvise_remove dropped mmap_lock */
1237 vma = find_vma(mm, start);
1240 return unmapped_error;
1243 #ifdef CONFIG_ANON_VMA_NAME
1244 static int madvise_vma_anon_name(struct vm_area_struct *vma,
1245 struct vm_area_struct **prev,
1246 unsigned long start, unsigned long end,
1247 unsigned long anon_name)
1251 /* Only anonymous mappings can be named */
1255 error = madvise_update_vma(vma, prev, start, end, vma->vm_flags,
1256 (struct anon_vma_name *)anon_name);
1259 * madvise() returns EAGAIN if kernel resources, such as
1260 * slab, are temporarily unavailable.
1262 if (error == -ENOMEM)
1267 int madvise_set_anon_name(struct mm_struct *mm, unsigned long start,
1268 unsigned long len_in, struct anon_vma_name *anon_name)
1273 if (start & ~PAGE_MASK)
1275 len = (len_in + ~PAGE_MASK) & PAGE_MASK;
1277 /* Check to see whether len was rounded up from small -ve to zero */
1288 return madvise_walk_vmas(mm, start, end, (unsigned long)anon_name,
1289 madvise_vma_anon_name);
1291 #endif /* CONFIG_ANON_VMA_NAME */
1293 * The madvise(2) system call.
1295 * Applications can use madvise() to advise the kernel how it should
1296 * handle paging I/O in this VM area. The idea is to help the kernel
1297 * use appropriate read-ahead and caching techniques. The information
1298 * provided is advisory only, and can be safely disregarded by the
1299 * kernel without affecting the correct operation of the application.
1302 * MADV_NORMAL - the default behavior is to read clusters. This
1303 * results in some read-ahead and read-behind.
1304 * MADV_RANDOM - the system should read the minimum amount of data
1305 * on any access, since it is unlikely that the appli-
1306 * cation will need more than what it asks for.
1307 * MADV_SEQUENTIAL - pages in the given range will probably be accessed
1308 * once, so they can be aggressively read ahead, and
1309 * can be freed soon after they are accessed.
1310 * MADV_WILLNEED - the application is notifying the system to read
1312 * MADV_DONTNEED - the application is finished with the given range,
1313 * so the kernel can free resources associated with it.
1314 * MADV_FREE - the application marks pages in the given range as lazy free,
1315 * where actual purges are postponed until memory pressure happens.
1316 * MADV_REMOVE - the application wants to free up the given range of
1317 * pages and associated backing store.
1318 * MADV_DONTFORK - omit this area from child's address space when forking:
1319 * typically, to avoid COWing pages pinned by get_user_pages().
1320 * MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
1321 * MADV_WIPEONFORK - present the child process with zero-filled memory in this
1322 * range after a fork.
1323 * MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
1324 * MADV_HWPOISON - trigger memory error handler as if the given memory range
1325 * were corrupted by unrecoverable hardware memory failure.
1326 * MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
1327 * MADV_MERGEABLE - the application recommends that KSM try to merge pages in
1328 * this area with pages of identical content from other such areas.
1329 * MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
1330 * MADV_HUGEPAGE - the application wants to back the given range by transparent
1331 * huge pages in the future. Existing pages might be coalesced and
1332 * new pages might be allocated as THP.
1333 * MADV_NOHUGEPAGE - mark the given range as not worth being backed by
1334 * transparent huge pages so the existing pages will not be
1335 * coalesced into THP and new pages will not be allocated as THP.
1336 * MADV_DONTDUMP - the application wants to prevent pages in the given range
1337 * from being included in its core dump.
1338 * MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
1339 * MADV_COLD - the application is not expected to use this memory soon,
1340 * deactivate pages in this range so that they can be reclaimed
1341 * easily if memory pressure happens.
1342 * MADV_PAGEOUT - the application is not expected to use this memory soon,
1343 * page out the pages in this range immediately.
1344 * MADV_POPULATE_READ - populate (prefault) page tables readable by
1345 * triggering read faults if required
1346 * MADV_POPULATE_WRITE - populate (prefault) page tables writable by
1347 * triggering write faults if required
1351 * -EINVAL - start + len < 0, start is not page-aligned,
1352 * "behavior" is not a valid value, or application
1353 * is attempting to release locked or shared pages,
1354 * or the specified address range includes file, Huge TLB,
1355 * MAP_SHARED or VMPFNMAP range.
1356 * -ENOMEM - addresses in the specified range are not currently
1357 * mapped, or are outside the AS of the process.
1358 * -EIO - an I/O error occurred while paging in data.
1359 * -EBADF - map exists, but area maps something that isn't a file.
1360 * -EAGAIN - a kernel resource was temporarily unavailable.
1362 int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int behavior)
1368 struct blk_plug plug;
1370 start = untagged_addr(start);
1372 if (!madvise_behavior_valid(behavior))
1375 if (!PAGE_ALIGNED(start))
1377 len = PAGE_ALIGN(len_in);
1379 /* Check to see whether len was rounded up from small -ve to zero */
1390 #ifdef CONFIG_MEMORY_FAILURE
1391 if (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)
1392 return madvise_inject_error(behavior, start, start + len_in);
1395 write = madvise_need_mmap_write(behavior);
1397 if (mmap_write_lock_killable(mm))
1403 blk_start_plug(&plug);
1404 error = madvise_walk_vmas(mm, start, end, behavior,
1405 madvise_vma_behavior);
1406 blk_finish_plug(&plug);
1408 mmap_write_unlock(mm);
1410 mmap_read_unlock(mm);
1415 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
1417 return do_madvise(current->mm, start, len_in, behavior);
1420 SYSCALL_DEFINE5(process_madvise, int, pidfd, const struct iovec __user *, vec,
1421 size_t, vlen, int, behavior, unsigned int, flags)
1424 struct iovec iovstack[UIO_FASTIOV], iovec;
1425 struct iovec *iov = iovstack;
1426 struct iov_iter iter;
1427 struct task_struct *task;
1428 struct mm_struct *mm;
1430 unsigned int f_flags;
1437 ret = import_iovec(READ, vec, vlen, ARRAY_SIZE(iovstack), &iov, &iter);
1441 task = pidfd_get_task(pidfd, &f_flags);
1443 ret = PTR_ERR(task);
1447 if (!process_madvise_behavior_valid(behavior)) {
1452 /* Require PTRACE_MODE_READ to avoid leaking ASLR metadata. */
1453 mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
1454 if (IS_ERR_OR_NULL(mm)) {
1455 ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
1460 * Require CAP_SYS_NICE for influencing process performance. Note that
1461 * only non-destructive hints are currently supported.
1463 if (!capable(CAP_SYS_NICE)) {
1468 total_len = iov_iter_count(&iter);
1470 while (iov_iter_count(&iter)) {
1471 iovec = iov_iter_iovec(&iter);
1472 ret = do_madvise(mm, (unsigned long)iovec.iov_base,
1473 iovec.iov_len, behavior);
1476 iov_iter_advance(&iter, iovec.iov_len);
1479 ret = (total_len - iov_iter_count(&iter)) ? : ret;
1484 put_task_struct(task);