1 // SPDX-License-Identifier: GPL-2.0-only
7 * Address space accounting code <alan@lxorguk.ukuu.org.uk>
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 #include <linux/backing-dev.h>
16 #include <linux/mm_inline.h>
17 #include <linux/shm.h>
18 #include <linux/mman.h>
19 #include <linux/pagemap.h>
20 #include <linux/swap.h>
21 #include <linux/syscalls.h>
22 #include <linux/capability.h>
23 #include <linux/init.h>
24 #include <linux/file.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/hugetlb.h>
29 #include <linux/shmem_fs.h>
30 #include <linux/profile.h>
31 #include <linux/export.h>
32 #include <linux/mount.h>
33 #include <linux/mempolicy.h>
34 #include <linux/rmap.h>
35 #include <linux/mmu_notifier.h>
36 #include <linux/mmdebug.h>
37 #include <linux/perf_event.h>
38 #include <linux/audit.h>
39 #include <linux/khugepaged.h>
40 #include <linux/uprobes.h>
41 #include <linux/notifier.h>
42 #include <linux/memory.h>
43 #include <linux/printk.h>
44 #include <linux/userfaultfd_k.h>
45 #include <linux/moduleparam.h>
46 #include <linux/pkeys.h>
47 #include <linux/oom.h>
48 #include <linux/sched/mm.h>
50 #include <linux/uaccess.h>
51 #include <asm/cacheflush.h>
53 #include <asm/mmu_context.h>
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/mmap.h>
60 #ifndef arch_mmap_check
61 #define arch_mmap_check(addr, len, flags) (0)
64 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
65 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
66 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
67 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
69 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
70 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
71 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
72 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
75 static bool ignore_rlimit_data;
76 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
78 static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
79 struct vm_area_struct *vma, struct vm_area_struct *prev,
80 struct vm_area_struct *next, unsigned long start,
81 unsigned long end, bool mm_wr_locked);
83 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
85 return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
88 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
89 void vma_set_page_prot(struct vm_area_struct *vma)
91 unsigned long vm_flags = vma->vm_flags;
92 pgprot_t vm_page_prot;
94 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
95 if (vma_wants_writenotify(vma, vm_page_prot)) {
96 vm_flags &= ~VM_SHARED;
97 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
99 /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
100 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
104 * Requires inode->i_mapping->i_mmap_rwsem
106 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
107 struct file *file, struct address_space *mapping)
109 if (vma->vm_flags & VM_SHARED)
110 mapping_unmap_writable(mapping);
112 flush_dcache_mmap_lock(mapping);
113 vma_interval_tree_remove(vma, &mapping->i_mmap);
114 flush_dcache_mmap_unlock(mapping);
118 * Unlink a file-based vm structure from its interval tree, to hide
119 * vma from rmap and vmtruncate before freeing its page tables.
121 void unlink_file_vma(struct vm_area_struct *vma)
123 struct file *file = vma->vm_file;
126 struct address_space *mapping = file->f_mapping;
127 i_mmap_lock_write(mapping);
128 __remove_shared_vm_struct(vma, file, mapping);
129 i_mmap_unlock_write(mapping);
134 * Close a vm structure and free it.
136 static void remove_vma(struct vm_area_struct *vma)
139 if (vma->vm_ops && vma->vm_ops->close)
140 vma->vm_ops->close(vma);
143 mpol_put(vma_policy(vma));
147 static inline struct vm_area_struct *vma_prev_limit(struct vma_iterator *vmi,
150 return mas_prev(&vmi->mas, min);
153 static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
154 unsigned long start, unsigned long end, gfp_t gfp)
156 vmi->mas.index = start;
157 vmi->mas.last = end - 1;
158 mas_store_gfp(&vmi->mas, NULL, gfp);
159 if (unlikely(mas_is_err(&vmi->mas)))
166 * check_brk_limits() - Use platform specific check of range & verify mlock
168 * @addr: The address to check
169 * @len: The size of increase.
171 * Return: 0 on success.
173 static int check_brk_limits(unsigned long addr, unsigned long len)
175 unsigned long mapped_addr;
177 mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
178 if (IS_ERR_VALUE(mapped_addr))
181 return mlock_future_check(current->mm, current->mm->def_flags, len);
183 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
184 unsigned long addr, unsigned long request, unsigned long flags);
185 SYSCALL_DEFINE1(brk, unsigned long, brk)
187 unsigned long newbrk, oldbrk, origbrk;
188 struct mm_struct *mm = current->mm;
189 struct vm_area_struct *brkvma, *next = NULL;
190 unsigned long min_brk;
192 bool downgraded = false;
194 struct vma_iterator vmi;
196 if (mmap_write_lock_killable(mm))
201 #ifdef CONFIG_COMPAT_BRK
203 * CONFIG_COMPAT_BRK can still be overridden by setting
204 * randomize_va_space to 2, which will still cause mm->start_brk
205 * to be arbitrarily shifted
207 if (current->brk_randomized)
208 min_brk = mm->start_brk;
210 min_brk = mm->end_data;
212 min_brk = mm->start_brk;
218 * Check against rlimit here. If this check is done later after the test
219 * of oldbrk with newbrk then it can escape the test and let the data
220 * segment grow beyond its set limit the in case where the limit is
221 * not page aligned -Ram Gupta
223 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
224 mm->end_data, mm->start_data))
227 newbrk = PAGE_ALIGN(brk);
228 oldbrk = PAGE_ALIGN(mm->brk);
229 if (oldbrk == newbrk) {
235 * Always allow shrinking brk.
236 * do_vma_munmap() may downgrade mmap_lock to read.
238 if (brk <= mm->brk) {
241 /* Search one past newbrk */
242 vma_iter_init(&vmi, mm, newbrk);
243 brkvma = vma_find(&vmi, oldbrk);
244 if (!brkvma || brkvma->vm_start >= oldbrk)
245 goto out; /* mapping intersects with an existing non-brk vma. */
247 * mm->brk must be protected by write mmap_lock.
248 * do_vma_munmap() may downgrade the lock, so update it
249 * before calling do_vma_munmap().
252 ret = do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true);
263 if (check_brk_limits(oldbrk, newbrk - oldbrk))
267 * Only check if the next VMA is within the stack_guard_gap of the
270 vma_iter_init(&vmi, mm, oldbrk);
271 next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
272 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
275 brkvma = vma_prev_limit(&vmi, mm->start_brk);
276 /* Ok, looks good - let it rip. */
277 if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
283 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
285 mmap_read_unlock(mm);
287 mmap_write_unlock(mm);
288 userfaultfd_unmap_complete(mm, &uf);
290 mm_populate(oldbrk, newbrk - oldbrk);
294 mmap_write_unlock(mm);
298 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
299 extern void mt_validate(struct maple_tree *mt);
300 extern void mt_dump(const struct maple_tree *mt);
302 /* Validate the maple tree */
303 static void validate_mm_mt(struct mm_struct *mm)
305 struct maple_tree *mt = &mm->mm_mt;
306 struct vm_area_struct *vma_mt;
308 MA_STATE(mas, mt, 0, 0);
310 mt_validate(&mm->mm_mt);
311 mas_for_each(&mas, vma_mt, ULONG_MAX) {
312 if ((vma_mt->vm_start != mas.index) ||
313 (vma_mt->vm_end - 1 != mas.last)) {
314 pr_emerg("issue in %s\n", current->comm);
317 pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
318 mas.index, mas.last);
319 pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
320 vma_mt->vm_start, vma_mt->vm_end);
323 if (vma_mt->vm_end != mas.last + 1) {
324 pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
325 mm, vma_mt->vm_start, vma_mt->vm_end,
326 mas.index, mas.last);
329 VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
330 if (vma_mt->vm_start != mas.index) {
331 pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
332 mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
335 VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
340 static void validate_mm(struct mm_struct *mm)
344 struct vm_area_struct *vma;
345 MA_STATE(mas, &mm->mm_mt, 0, 0);
349 mas_for_each(&mas, vma, ULONG_MAX) {
350 #ifdef CONFIG_DEBUG_VM_RB
351 struct anon_vma *anon_vma = vma->anon_vma;
352 struct anon_vma_chain *avc;
355 anon_vma_lock_read(anon_vma);
356 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
357 anon_vma_interval_tree_verify(avc);
358 anon_vma_unlock_read(anon_vma);
363 if (i != mm->map_count) {
364 pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
367 VM_BUG_ON_MM(bug, mm);
370 #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
371 #define validate_mm_mt(root) do { } while (0)
372 #define validate_mm(mm) do { } while (0)
373 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
376 * vma has some anon_vma assigned, and is already inserted on that
377 * anon_vma's interval trees.
379 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
380 * vma must be removed from the anon_vma's interval trees using
381 * anon_vma_interval_tree_pre_update_vma().
383 * After the update, the vma will be reinserted using
384 * anon_vma_interval_tree_post_update_vma().
386 * The entire update must be protected by exclusive mmap_lock and by
387 * the root anon_vma's mutex.
390 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
392 struct anon_vma_chain *avc;
394 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
395 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
399 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
401 struct anon_vma_chain *avc;
403 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
404 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
407 static unsigned long count_vma_pages_range(struct mm_struct *mm,
408 unsigned long addr, unsigned long end)
410 VMA_ITERATOR(vmi, mm, addr);
411 struct vm_area_struct *vma;
412 unsigned long nr_pages = 0;
414 for_each_vma_range(vmi, vma, end) {
415 unsigned long vm_start = max(addr, vma->vm_start);
416 unsigned long vm_end = min(end, vma->vm_end);
418 nr_pages += PHYS_PFN(vm_end - vm_start);
424 static void __vma_link_file(struct vm_area_struct *vma,
425 struct address_space *mapping)
427 if (vma->vm_flags & VM_SHARED)
428 mapping_allow_writable(mapping);
430 flush_dcache_mmap_lock(mapping);
431 vma_interval_tree_insert(vma, &mapping->i_mmap);
432 flush_dcache_mmap_unlock(mapping);
435 static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
437 VMA_ITERATOR(vmi, mm, 0);
438 struct address_space *mapping = NULL;
440 if (vma_iter_prealloc(&vmi))
444 mapping = vma->vm_file->f_mapping;
445 i_mmap_lock_write(mapping);
448 vma_iter_store(&vmi, vma);
451 __vma_link_file(vma, mapping);
452 i_mmap_unlock_write(mapping);
461 * init_multi_vma_prep() - Initializer for struct vma_prepare
462 * @vp: The vma_prepare struct
463 * @vma: The vma that will be altered once locked
464 * @next: The next vma if it is to be adjusted
465 * @remove: The first vma to be removed
466 * @remove2: The second vma to be removed
468 static inline void init_multi_vma_prep(struct vma_prepare *vp,
469 struct vm_area_struct *vma, struct vm_area_struct *next,
470 struct vm_area_struct *remove, struct vm_area_struct *remove2)
472 memset(vp, 0, sizeof(struct vma_prepare));
474 vp->anon_vma = vma->anon_vma;
476 vp->remove2 = remove2;
478 if (!vp->anon_vma && next)
479 vp->anon_vma = next->anon_vma;
481 vp->file = vma->vm_file;
483 vp->mapping = vma->vm_file->f_mapping;
488 * init_vma_prep() - Initializer wrapper for vma_prepare struct
489 * @vp: The vma_prepare struct
490 * @vma: The vma that will be altered once locked
492 static inline void init_vma_prep(struct vma_prepare *vp,
493 struct vm_area_struct *vma)
495 init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
500 * vma_prepare() - Helper function for handling locking VMAs prior to altering
501 * @vp: The initialized vma_prepare struct
503 static inline void vma_prepare(struct vma_prepare *vp)
506 uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
509 uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
510 vp->adj_next->vm_end);
512 i_mmap_lock_write(vp->mapping);
513 if (vp->insert && vp->insert->vm_file) {
515 * Put into interval tree now, so instantiated pages
516 * are visible to arm/parisc __flush_dcache_page
517 * throughout; but we cannot insert into address
518 * space until vma start or end is updated.
520 __vma_link_file(vp->insert,
521 vp->insert->vm_file->f_mapping);
526 anon_vma_lock_write(vp->anon_vma);
527 anon_vma_interval_tree_pre_update_vma(vp->vma);
529 anon_vma_interval_tree_pre_update_vma(vp->adj_next);
533 flush_dcache_mmap_lock(vp->mapping);
534 vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
536 vma_interval_tree_remove(vp->adj_next,
537 &vp->mapping->i_mmap);
543 * vma_complete- Helper function for handling the unlocking after altering VMAs,
544 * or for inserting a VMA.
546 * @vp: The vma_prepare struct
547 * @vmi: The vma iterator
550 static inline void vma_complete(struct vma_prepare *vp,
551 struct vma_iterator *vmi, struct mm_struct *mm)
555 vma_interval_tree_insert(vp->adj_next,
556 &vp->mapping->i_mmap);
557 vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
558 flush_dcache_mmap_unlock(vp->mapping);
561 if (vp->remove && vp->file) {
562 __remove_shared_vm_struct(vp->remove, vp->file, vp->mapping);
564 __remove_shared_vm_struct(vp->remove2, vp->file,
566 } else if (vp->insert) {
568 * split_vma has split insert from vma, and needs
569 * us to insert it before dropping the locks
570 * (it may either follow vma or precede it).
572 vma_iter_store(vmi, vp->insert);
577 anon_vma_interval_tree_post_update_vma(vp->vma);
579 anon_vma_interval_tree_post_update_vma(vp->adj_next);
580 anon_vma_unlock_write(vp->anon_vma);
584 i_mmap_unlock_write(vp->mapping);
585 uprobe_mmap(vp->vma);
588 uprobe_mmap(vp->adj_next);
594 uprobe_munmap(vp->remove, vp->remove->vm_start,
598 if (vp->remove->anon_vma)
599 anon_vma_merge(vp->vma, vp->remove);
601 mpol_put(vma_policy(vp->remove));
603 WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
604 vm_area_free(vp->remove);
607 * In mprotect's case 6 (see comments on vma_merge),
608 * we must remove the one after next as well.
611 vp->remove = vp->remove2;
616 if (vp->insert && vp->file)
617 uprobe_mmap(vp->insert);
621 * dup_anon_vma() - Helper function to duplicate anon_vma
622 * @dst: The destination VMA
623 * @src: The source VMA
625 * Returns: 0 on success.
627 static inline int dup_anon_vma(struct vm_area_struct *dst,
628 struct vm_area_struct *src)
631 * Easily overlooked: when mprotect shifts the boundary, make sure the
632 * expanding vma has anon_vma set if the shrinking vma had, to cover any
633 * anon pages imported.
635 if (src->anon_vma && !dst->anon_vma) {
636 dst->anon_vma = src->anon_vma;
637 return anon_vma_clone(dst, src);
644 * vma_expand - Expand an existing VMA
646 * @vmi: The vma iterator
647 * @vma: The vma to expand
648 * @start: The start of the vma
649 * @end: The exclusive end of the vma
650 * @pgoff: The page offset of vma
651 * @next: The current of next vma.
653 * Expand @vma to @start and @end. Can expand off the start and end. Will
654 * expand over @next if it's different from @vma and @end == @next->vm_end.
655 * Checking if the @vma can expand and merge with @next needs to be handled by
658 * Returns: 0 on success
660 int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
661 unsigned long start, unsigned long end, pgoff_t pgoff,
662 struct vm_area_struct *next)
664 bool remove_next = false;
665 struct vma_prepare vp;
667 if (next && (vma != next) && (end == next->vm_end)) {
671 ret = dup_anon_vma(vma, next);
676 init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
677 /* Not merging but overwriting any part of next is not handled. */
678 VM_WARN_ON(next && !vp.remove &&
679 next != vma && end > next->vm_start);
680 /* Only handles expanding */
681 VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);
683 if (vma_iter_prealloc(vmi))
686 vma_adjust_trans_huge(vma, start, end, 0);
687 /* VMA iterator points to previous, so set to start if necessary */
688 if (vma_iter_addr(vmi) != start)
689 vma_iter_set(vmi, start);
692 vma->vm_start = start;
694 vma->vm_pgoff = pgoff;
695 /* Note: mas must be pointing to the expanding VMA */
696 vma_iter_store(vmi, vma);
698 vma_complete(&vp, vmi, vma->vm_mm);
699 validate_mm(vma->vm_mm);
707 * vma_shrink() - Reduce an existing VMAs memory area
708 * @vmi: The vma iterator
709 * @vma: The VMA to modify
710 * @start: The new start
713 * Returns: 0 on success, -ENOMEM otherwise
715 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
716 unsigned long start, unsigned long end, pgoff_t pgoff)
718 struct vma_prepare vp;
720 WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
722 if (vma_iter_prealloc(vmi))
725 init_vma_prep(&vp, vma);
726 vma_adjust_trans_huge(vma, start, end, 0);
729 if (vma->vm_start < start)
730 vma_iter_clear(vmi, vma->vm_start, start);
732 if (vma->vm_end > end)
733 vma_iter_clear(vmi, end, vma->vm_end);
735 vma->vm_start = start;
737 vma->vm_pgoff = pgoff;
738 vma_complete(&vp, vmi, vma->vm_mm);
739 validate_mm(vma->vm_mm);
744 * If the vma has a ->close operation then the driver probably needs to release
745 * per-vma resources, so we don't attempt to merge those.
747 static inline int is_mergeable_vma(struct vm_area_struct *vma,
748 struct file *file, unsigned long vm_flags,
749 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
750 struct anon_vma_name *anon_name)
753 * VM_SOFTDIRTY should not prevent from VMA merging, if we
754 * match the flags but dirty bit -- the caller should mark
755 * merged VMA as dirty. If dirty bit won't be excluded from
756 * comparison, we increase pressure on the memory system forcing
757 * the kernel to generate new VMAs when old one could be
760 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
762 if (vma->vm_file != file)
764 if (vma->vm_ops && vma->vm_ops->close)
766 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
768 if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
773 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
774 struct anon_vma *anon_vma2,
775 struct vm_area_struct *vma)
778 * The list_is_singular() test is to avoid merging VMA cloned from
779 * parents. This can improve scalability caused by anon_vma lock.
781 if ((!anon_vma1 || !anon_vma2) && (!vma ||
782 list_is_singular(&vma->anon_vma_chain)))
784 return anon_vma1 == anon_vma2;
788 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
789 * in front of (at a lower virtual address and file offset than) the vma.
791 * We cannot merge two vmas if they have differently assigned (non-NULL)
792 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
794 * We don't check here for the merged mmap wrapping around the end of pagecache
795 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
796 * wrap, nor mmaps which cover the final page at index -1UL.
799 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
800 struct anon_vma *anon_vma, struct file *file,
802 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
803 struct anon_vma_name *anon_name)
805 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
806 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
807 if (vma->vm_pgoff == vm_pgoff)
814 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
815 * beyond (at a higher virtual address and file offset than) the vma.
817 * We cannot merge two vmas if they have differently assigned (non-NULL)
818 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
821 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
822 struct anon_vma *anon_vma, struct file *file,
824 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
825 struct anon_vma_name *anon_name)
827 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
828 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
830 vm_pglen = vma_pages(vma);
831 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
838 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
839 * figure out whether that can be merged with its predecessor or its
840 * successor. Or both (it neatly fills a hole).
842 * In most cases - when called for mmap, brk or mremap - [addr,end) is
843 * certain not to be mapped by the time vma_merge is called; but when
844 * called for mprotect, it is certain to be already mapped (either at
845 * an offset within prev, or at the start of next), and the flags of
846 * this area are about to be changed to vm_flags - and the no-change
847 * case has already been eliminated.
849 * The following mprotect cases have to be considered, where AAAA is
850 * the area passed down from mprotect_fixup, never extending beyond one
851 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
854 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN
855 * cannot merge might become might become
856 * PPNNNNNNNNNN PPPPPPPPPPNN
857 * mmap, brk or case 4 below case 5 below
860 * PPPP NNNN PPPPNNNNXXXX
861 * might become might become
862 * PPPPPPPPPPPP 1 or PPPPPPPPPPPP 6 or
863 * PPPPPPPPNNNN 2 or PPPPPPPPXXXX 7 or
864 * PPPPNNNNNNNN 3 PPPPXXXXXXXX 8
866 * It is important for case 8 that the vma NNNN overlapping the
867 * region AAAA is never going to extended over XXXX. Instead XXXX must
868 * be extended in region AAAA and NNNN must be removed. This way in
869 * all cases where vma_merge succeeds, the moment vma_merge drops the
870 * rmap_locks, the properties of the merged vma will be already
871 * correct for the whole merged range. Some of those properties like
872 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
873 * be correct for the whole merged range immediately after the
874 * rmap_locks are released. Otherwise if XXXX would be removed and
875 * NNNN would be extended over the XXXX range, remove_migration_ptes
876 * or other rmap walkers (if working on addresses beyond the "end"
877 * parameter) may establish ptes with the wrong permissions of NNNN
878 * instead of the right permissions of XXXX.
881 * PPPP is represented by *prev
882 * NNNN is represented by *mid (and possibly equal to *next)
883 * XXXX is represented by *next or not represented at all.
884 * AAAA is not represented - it will be merged or the function will return NULL
886 struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
887 struct vm_area_struct *prev, unsigned long addr,
888 unsigned long end, unsigned long vm_flags,
889 struct anon_vma *anon_vma, struct file *file,
890 pgoff_t pgoff, struct mempolicy *policy,
891 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
892 struct anon_vma_name *anon_name)
894 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
896 struct vm_area_struct *mid, *next, *res = NULL;
897 struct vm_area_struct *vma, *adjust, *remove, *remove2;
899 bool merge_prev = false;
900 bool merge_next = false;
901 bool vma_expanded = false;
902 struct vma_prepare vp;
903 unsigned long vma_end = end;
905 unsigned long vma_start = addr;
909 * We later require that vma->vm_flags == vm_flags,
910 * so this tests vma->vm_flags & VM_SPECIAL, too.
912 if (vm_flags & VM_SPECIAL)
915 next = find_vma(mm, prev ? prev->vm_end : 0);
917 if (next && next->vm_end == end) /* cases 6, 7, 8 */
918 next = find_vma(mm, next->vm_end);
920 /* verify some invariant that must be enforced by the caller */
921 VM_WARN_ON(prev && addr <= prev->vm_start);
922 VM_WARN_ON(mid && end > mid->vm_end);
923 VM_WARN_ON(addr >= end);
928 vma_start = prev->vm_start;
929 vma_pgoff = prev->vm_pgoff;
930 /* Can we merge the predecessor? */
931 if (prev->vm_end == addr && mpol_equal(vma_policy(prev), policy)
932 && can_vma_merge_after(prev, vm_flags, anon_vma, file,
933 pgoff, vm_userfaultfd_ctx, anon_name)) {
938 /* Can we merge the successor? */
939 if (next && end == next->vm_start &&
940 mpol_equal(policy, vma_policy(next)) &&
941 can_vma_merge_before(next, vm_flags,
942 anon_vma, file, pgoff+pglen,
943 vm_userfaultfd_ctx, anon_name)) {
947 remove = remove2 = adjust = NULL;
948 /* Can we merge both the predecessor and the successor? */
949 if (merge_prev && merge_next &&
950 is_mergeable_anon_vma(prev->anon_vma, next->anon_vma, NULL)) {
951 remove = mid; /* case 1 */
952 vma_end = next->vm_end;
953 err = dup_anon_vma(res, remove);
954 if (mid != next) { /* case 6 */
956 if (!remove->anon_vma)
957 err = dup_anon_vma(res, remove2);
959 } else if (merge_prev) {
960 err = 0; /* case 2 */
961 if (mid && end > mid->vm_start) {
962 err = dup_anon_vma(res, mid);
963 if (end == mid->vm_end) { /* case 7 */
965 } else { /* case 5 */
967 adj_next = (end - mid->vm_start);
970 } else if (merge_next) {
972 if (prev && addr < prev->vm_end) { /* case 4 */
975 adj_next = -(vma->vm_end - addr);
976 err = dup_anon_vma(adjust, prev);
978 vma = next; /* case 3 */
980 vma_end = next->vm_end;
981 vma_pgoff = next->vm_pgoff - pglen;
983 if (mid != next) { /* case 8 */
985 err = dup_anon_vma(res, remove);
990 /* Cannot merge or error in anon_vma clone */
994 if (vma_iter_prealloc(vmi))
997 vma_adjust_trans_huge(vma, vma_start, vma_end, adj_next);
998 init_multi_vma_prep(&vp, vma, adjust, remove, remove2);
999 VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
1000 vp.anon_vma != adjust->anon_vma);
1003 if (vma_start < vma->vm_start || vma_end > vma->vm_end)
1004 vma_expanded = true;
1006 vma->vm_start = vma_start;
1007 vma->vm_end = vma_end;
1008 vma->vm_pgoff = vma_pgoff;
1011 vma_iter_store(vmi, vma);
1014 adjust->vm_start += adj_next;
1015 adjust->vm_pgoff += adj_next >> PAGE_SHIFT;
1017 WARN_ON(vma_expanded);
1018 vma_iter_store(vmi, next);
1022 vma_complete(&vp, vmi, mm);
1025 khugepaged_enter_vma(res, vm_flags);
1031 * Rough compatibility check to quickly see if it's even worth looking
1032 * at sharing an anon_vma.
1034 * They need to have the same vm_file, and the flags can only differ
1035 * in things that mprotect may change.
1037 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1038 * we can merge the two vma's. For example, we refuse to merge a vma if
1039 * there is a vm_ops->close() function, because that indicates that the
1040 * driver is doing some kind of reference counting. But that doesn't
1041 * really matter for the anon_vma sharing case.
1043 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1045 return a->vm_end == b->vm_start &&
1046 mpol_equal(vma_policy(a), vma_policy(b)) &&
1047 a->vm_file == b->vm_file &&
1048 !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1049 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1053 * Do some basic sanity checking to see if we can re-use the anon_vma
1054 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1055 * the same as 'old', the other will be the new one that is trying
1056 * to share the anon_vma.
1058 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1059 * the anon_vma of 'old' is concurrently in the process of being set up
1060 * by another page fault trying to merge _that_. But that's ok: if it
1061 * is being set up, that automatically means that it will be a singleton
1062 * acceptable for merging, so we can do all of this optimistically. But
1063 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1065 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1066 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1067 * is to return an anon_vma that is "complex" due to having gone through
1070 * We also make sure that the two vma's are compatible (adjacent,
1071 * and with the same memory policies). That's all stable, even with just
1072 * a read lock on the mmap_lock.
1074 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1076 if (anon_vma_compatible(a, b)) {
1077 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1079 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1086 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1087 * neighbouring vmas for a suitable anon_vma, before it goes off
1088 * to allocate a new anon_vma. It checks because a repetitive
1089 * sequence of mprotects and faults may otherwise lead to distinct
1090 * anon_vmas being allocated, preventing vma merge in subsequent
1093 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1095 MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1096 struct anon_vma *anon_vma = NULL;
1097 struct vm_area_struct *prev, *next;
1099 /* Try next first. */
1100 next = mas_walk(&mas);
1102 anon_vma = reusable_anon_vma(next, vma, next);
1107 prev = mas_prev(&mas, 0);
1108 VM_BUG_ON_VMA(prev != vma, vma);
1109 prev = mas_prev(&mas, 0);
1110 /* Try prev next. */
1112 anon_vma = reusable_anon_vma(prev, prev, vma);
1115 * We might reach here with anon_vma == NULL if we can't find
1116 * any reusable anon_vma.
1117 * There's no absolute need to look only at touching neighbours:
1118 * we could search further afield for "compatible" anon_vmas.
1119 * But it would probably just be a waste of time searching,
1120 * or lead to too many vmas hanging off the same anon_vma.
1121 * We're trying to allow mprotect remerging later on,
1122 * not trying to minimize memory used for anon_vmas.
1128 * If a hint addr is less than mmap_min_addr change hint to be as
1129 * low as possible but still greater than mmap_min_addr
1131 static inline unsigned long round_hint_to_min(unsigned long hint)
1134 if (((void *)hint != NULL) &&
1135 (hint < mmap_min_addr))
1136 return PAGE_ALIGN(mmap_min_addr);
1140 int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1143 unsigned long locked, lock_limit;
1145 /* mlock MCL_FUTURE? */
1146 if (flags & VM_LOCKED) {
1147 locked = len >> PAGE_SHIFT;
1148 locked += mm->locked_vm;
1149 lock_limit = rlimit(RLIMIT_MEMLOCK);
1150 lock_limit >>= PAGE_SHIFT;
1151 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1157 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1159 if (S_ISREG(inode->i_mode))
1160 return MAX_LFS_FILESIZE;
1162 if (S_ISBLK(inode->i_mode))
1163 return MAX_LFS_FILESIZE;
1165 if (S_ISSOCK(inode->i_mode))
1166 return MAX_LFS_FILESIZE;
1168 /* Special "we do even unsigned file positions" case */
1169 if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1172 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1176 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1177 unsigned long pgoff, unsigned long len)
1179 u64 maxsize = file_mmap_size_max(file, inode);
1181 if (maxsize && len > maxsize)
1184 if (pgoff > maxsize >> PAGE_SHIFT)
1190 * The caller must write-lock current->mm->mmap_lock.
1192 unsigned long do_mmap(struct file *file, unsigned long addr,
1193 unsigned long len, unsigned long prot,
1194 unsigned long flags, unsigned long pgoff,
1195 unsigned long *populate, struct list_head *uf)
1197 struct mm_struct *mm = current->mm;
1198 vm_flags_t vm_flags;
1208 * Does the application expect PROT_READ to imply PROT_EXEC?
1210 * (the exception is when the underlying filesystem is noexec
1211 * mounted, in which case we dont add PROT_EXEC.)
1213 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1214 if (!(file && path_noexec(&file->f_path)))
1217 /* force arch specific MAP_FIXED handling in get_unmapped_area */
1218 if (flags & MAP_FIXED_NOREPLACE)
1221 if (!(flags & MAP_FIXED))
1222 addr = round_hint_to_min(addr);
1224 /* Careful about overflows.. */
1225 len = PAGE_ALIGN(len);
1229 /* offset overflow? */
1230 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1233 /* Too many mappings? */
1234 if (mm->map_count > sysctl_max_map_count)
1237 /* Obtain the address to map to. we verify (or select) it and ensure
1238 * that it represents a valid section of the address space.
1240 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1241 if (IS_ERR_VALUE(addr))
1244 if (flags & MAP_FIXED_NOREPLACE) {
1245 if (find_vma_intersection(mm, addr, addr + len))
1249 if (prot == PROT_EXEC) {
1250 pkey = execute_only_pkey(mm);
1255 /* Do simple checking here so the lower-level routines won't have
1256 * to. we assume access permissions have been handled by the open
1257 * of the memory object, so we don't do any here.
1259 vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1260 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1262 if (flags & MAP_LOCKED)
1263 if (!can_do_mlock())
1266 if (mlock_future_check(mm, vm_flags, len))
1270 struct inode *inode = file_inode(file);
1271 unsigned long flags_mask;
1273 if (!file_mmap_ok(file, inode, pgoff, len))
1276 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1278 switch (flags & MAP_TYPE) {
1281 * Force use of MAP_SHARED_VALIDATE with non-legacy
1282 * flags. E.g. MAP_SYNC is dangerous to use with
1283 * MAP_SHARED as you don't know which consistency model
1284 * you will get. We silently ignore unsupported flags
1285 * with MAP_SHARED to preserve backward compatibility.
1287 flags &= LEGACY_MAP_MASK;
1289 case MAP_SHARED_VALIDATE:
1290 if (flags & ~flags_mask)
1292 if (prot & PROT_WRITE) {
1293 if (!(file->f_mode & FMODE_WRITE))
1295 if (IS_SWAPFILE(file->f_mapping->host))
1300 * Make sure we don't allow writing to an append-only
1303 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1306 vm_flags |= VM_SHARED | VM_MAYSHARE;
1307 if (!(file->f_mode & FMODE_WRITE))
1308 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1311 if (!(file->f_mode & FMODE_READ))
1313 if (path_noexec(&file->f_path)) {
1314 if (vm_flags & VM_EXEC)
1316 vm_flags &= ~VM_MAYEXEC;
1319 if (!file->f_op->mmap)
1321 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1329 switch (flags & MAP_TYPE) {
1331 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1337 vm_flags |= VM_SHARED | VM_MAYSHARE;
1341 * Set pgoff according to addr for anon_vma.
1343 pgoff = addr >> PAGE_SHIFT;
1351 * Set 'VM_NORESERVE' if we should not account for the
1352 * memory use of this mapping.
1354 if (flags & MAP_NORESERVE) {
1355 /* We honor MAP_NORESERVE if allowed to overcommit */
1356 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1357 vm_flags |= VM_NORESERVE;
1359 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1360 if (file && is_file_hugepages(file))
1361 vm_flags |= VM_NORESERVE;
1364 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1365 if (!IS_ERR_VALUE(addr) &&
1366 ((vm_flags & VM_LOCKED) ||
1367 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1372 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1373 unsigned long prot, unsigned long flags,
1374 unsigned long fd, unsigned long pgoff)
1376 struct file *file = NULL;
1377 unsigned long retval;
1379 if (!(flags & MAP_ANONYMOUS)) {
1380 audit_mmap_fd(fd, flags);
1384 if (is_file_hugepages(file)) {
1385 len = ALIGN(len, huge_page_size(hstate_file(file)));
1386 } else if (unlikely(flags & MAP_HUGETLB)) {
1390 } else if (flags & MAP_HUGETLB) {
1393 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1397 len = ALIGN(len, huge_page_size(hs));
1399 * VM_NORESERVE is used because the reservations will be
1400 * taken when vm_ops->mmap() is called
1402 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1404 HUGETLB_ANONHUGE_INODE,
1405 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1407 return PTR_ERR(file);
1410 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1417 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1418 unsigned long, prot, unsigned long, flags,
1419 unsigned long, fd, unsigned long, pgoff)
1421 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1424 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1425 struct mmap_arg_struct {
1429 unsigned long flags;
1431 unsigned long offset;
1434 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1436 struct mmap_arg_struct a;
1438 if (copy_from_user(&a, arg, sizeof(a)))
1440 if (offset_in_page(a.offset))
1443 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1444 a.offset >> PAGE_SHIFT);
1446 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1449 * Some shared mappings will want the pages marked read-only
1450 * to track write events. If so, we'll downgrade vm_page_prot
1451 * to the private version (using protection_map[] without the
1454 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1456 vm_flags_t vm_flags = vma->vm_flags;
1457 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1459 /* If it was private or non-writable, the write bit is already clear */
1460 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1463 /* The backer wishes to know when pages are first written to? */
1464 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1467 /* The open routine did something to the protections that pgprot_modify
1468 * won't preserve? */
1469 if (pgprot_val(vm_page_prot) !=
1470 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1474 * Do we need to track softdirty? hugetlb does not support softdirty
1477 if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1480 /* Do we need write faults for uffd-wp tracking? */
1481 if (userfaultfd_wp(vma))
1484 /* Specialty mapping? */
1485 if (vm_flags & VM_PFNMAP)
1488 /* Can the mapping track the dirty pages? */
1489 return vma->vm_file && vma->vm_file->f_mapping &&
1490 mapping_can_writeback(vma->vm_file->f_mapping);
1494 * We account for memory if it's a private writeable mapping,
1495 * not hugepages and VM_NORESERVE wasn't set.
1497 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1500 * hugetlb has its own accounting separate from the core VM
1501 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1503 if (file && is_file_hugepages(file))
1506 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1510 * unmapped_area() - Find an area between the low_limit and the high_limit with
1511 * the correct alignment and offset, all from @info. Note: current->mm is used
1514 * @info: The unmapped area information including the range [low_limit -
1515 * high_limit), the alignment offset and mask.
1517 * Return: A memory address or -ENOMEM.
1519 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1521 unsigned long length, gap, low_limit;
1522 struct vm_area_struct *tmp;
1524 MA_STATE(mas, ¤t->mm->mm_mt, 0, 0);
1526 /* Adjust search length to account for worst case alignment overhead */
1527 length = info->length + info->align_mask;
1528 if (length < info->length)
1531 low_limit = info->low_limit;
1533 if (mas_empty_area(&mas, low_limit, info->high_limit - 1, length))
1537 gap += (info->align_offset - gap) & info->align_mask;
1538 tmp = mas_next(&mas, ULONG_MAX);
1539 if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
1540 if (vm_start_gap(tmp) < gap + length - 1) {
1541 low_limit = tmp->vm_end;
1546 tmp = mas_prev(&mas, 0);
1547 if (tmp && vm_end_gap(tmp) > gap) {
1548 low_limit = vm_end_gap(tmp);
1558 * unmapped_area_topdown() - Find an area between the low_limit and the
1559 * high_limit with the correct alignment and offset at the highest available
1560 * address, all from @info. Note: current->mm is used for the search.
1562 * @info: The unmapped area information including the range [low_limit -
1563 * high_limit), the alignment offset and mask.
1565 * Return: A memory address or -ENOMEM.
1567 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1569 unsigned long length, gap, high_limit, gap_end;
1570 struct vm_area_struct *tmp;
1572 MA_STATE(mas, ¤t->mm->mm_mt, 0, 0);
1573 /* Adjust search length to account for worst case alignment overhead */
1574 length = info->length + info->align_mask;
1575 if (length < info->length)
1578 high_limit = info->high_limit;
1580 if (mas_empty_area_rev(&mas, info->low_limit, high_limit - 1,
1584 gap = mas.last + 1 - info->length;
1585 gap -= (gap - info->align_offset) & info->align_mask;
1587 tmp = mas_next(&mas, ULONG_MAX);
1588 if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
1589 if (vm_start_gap(tmp) <= gap_end) {
1590 high_limit = vm_start_gap(tmp);
1595 tmp = mas_prev(&mas, 0);
1596 if (tmp && vm_end_gap(tmp) > gap) {
1597 high_limit = tmp->vm_start;
1607 * Search for an unmapped address range.
1609 * We are looking for a range that:
1610 * - does not intersect with any VMA;
1611 * - is contained within the [low_limit, high_limit) interval;
1612 * - is at least the desired size.
1613 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1615 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1619 if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1620 addr = unmapped_area_topdown(info);
1622 addr = unmapped_area(info);
1624 trace_vm_unmapped_area(addr, info);
1628 /* Get an address range which is currently unmapped.
1629 * For shmat() with addr=0.
1631 * Ugly calling convention alert:
1632 * Return value with the low bits set means error value,
1634 * if (ret & ~PAGE_MASK)
1637 * This function "knows" that -ENOMEM has the bits set.
1640 generic_get_unmapped_area(struct file *filp, unsigned long addr,
1641 unsigned long len, unsigned long pgoff,
1642 unsigned long flags)
1644 struct mm_struct *mm = current->mm;
1645 struct vm_area_struct *vma, *prev;
1646 struct vm_unmapped_area_info info;
1647 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1649 if (len > mmap_end - mmap_min_addr)
1652 if (flags & MAP_FIXED)
1656 addr = PAGE_ALIGN(addr);
1657 vma = find_vma_prev(mm, addr, &prev);
1658 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1659 (!vma || addr + len <= vm_start_gap(vma)) &&
1660 (!prev || addr >= vm_end_gap(prev)))
1666 info.low_limit = mm->mmap_base;
1667 info.high_limit = mmap_end;
1668 info.align_mask = 0;
1669 info.align_offset = 0;
1670 return vm_unmapped_area(&info);
1673 #ifndef HAVE_ARCH_UNMAPPED_AREA
1675 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1676 unsigned long len, unsigned long pgoff,
1677 unsigned long flags)
1679 return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
1684 * This mmap-allocator allocates new areas top-down from below the
1685 * stack's low limit (the base):
1688 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
1689 unsigned long len, unsigned long pgoff,
1690 unsigned long flags)
1692 struct vm_area_struct *vma, *prev;
1693 struct mm_struct *mm = current->mm;
1694 struct vm_unmapped_area_info info;
1695 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1697 /* requested length too big for entire address space */
1698 if (len > mmap_end - mmap_min_addr)
1701 if (flags & MAP_FIXED)
1704 /* requesting a specific address */
1706 addr = PAGE_ALIGN(addr);
1707 vma = find_vma_prev(mm, addr, &prev);
1708 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1709 (!vma || addr + len <= vm_start_gap(vma)) &&
1710 (!prev || addr >= vm_end_gap(prev)))
1714 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1716 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1717 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1718 info.align_mask = 0;
1719 info.align_offset = 0;
1720 addr = vm_unmapped_area(&info);
1723 * A failed mmap() very likely causes application failure,
1724 * so fall back to the bottom-up function here. This scenario
1725 * can happen with large stack limits and large mmap()
1728 if (offset_in_page(addr)) {
1729 VM_BUG_ON(addr != -ENOMEM);
1731 info.low_limit = TASK_UNMAPPED_BASE;
1732 info.high_limit = mmap_end;
1733 addr = vm_unmapped_area(&info);
1739 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1741 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
1742 unsigned long len, unsigned long pgoff,
1743 unsigned long flags)
1745 return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
1750 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1751 unsigned long pgoff, unsigned long flags)
1753 unsigned long (*get_area)(struct file *, unsigned long,
1754 unsigned long, unsigned long, unsigned long);
1756 unsigned long error = arch_mmap_check(addr, len, flags);
1760 /* Careful about overflows.. */
1761 if (len > TASK_SIZE)
1764 get_area = current->mm->get_unmapped_area;
1766 if (file->f_op->get_unmapped_area)
1767 get_area = file->f_op->get_unmapped_area;
1768 } else if (flags & MAP_SHARED) {
1770 * mmap_region() will call shmem_zero_setup() to create a file,
1771 * so use shmem's get_unmapped_area in case it can be huge.
1772 * do_mmap() will clear pgoff, so match alignment.
1775 get_area = shmem_get_unmapped_area;
1778 addr = get_area(file, addr, len, pgoff, flags);
1779 if (IS_ERR_VALUE(addr))
1782 if (addr > TASK_SIZE - len)
1784 if (offset_in_page(addr))
1787 error = security_mmap_addr(addr);
1788 return error ? error : addr;
1791 EXPORT_SYMBOL(get_unmapped_area);
1794 * find_vma_intersection() - Look up the first VMA which intersects the interval
1795 * @mm: The process address space.
1796 * @start_addr: The inclusive start user address.
1797 * @end_addr: The exclusive end user address.
1799 * Returns: The first VMA within the provided range, %NULL otherwise. Assumes
1800 * start_addr < end_addr.
1802 struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1803 unsigned long start_addr,
1804 unsigned long end_addr)
1806 unsigned long index = start_addr;
1808 mmap_assert_locked(mm);
1809 return mt_find(&mm->mm_mt, &index, end_addr - 1);
1811 EXPORT_SYMBOL(find_vma_intersection);
1814 * find_vma() - Find the VMA for a given address, or the next VMA.
1815 * @mm: The mm_struct to check
1816 * @addr: The address
1818 * Returns: The VMA associated with addr, or the next VMA.
1819 * May return %NULL in the case of no VMA at addr or above.
1821 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1823 unsigned long index = addr;
1825 mmap_assert_locked(mm);
1826 return mt_find(&mm->mm_mt, &index, ULONG_MAX);
1828 EXPORT_SYMBOL(find_vma);
1831 * find_vma_prev() - Find the VMA for a given address, or the next vma and
1832 * set %pprev to the previous VMA, if any.
1833 * @mm: The mm_struct to check
1834 * @addr: The address
1835 * @pprev: The pointer to set to the previous VMA
1837 * Note that RCU lock is missing here since the external mmap_lock() is used
1840 * Returns: The VMA associated with @addr, or the next vma.
1841 * May return %NULL in the case of no vma at addr or above.
1843 struct vm_area_struct *
1844 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1845 struct vm_area_struct **pprev)
1847 struct vm_area_struct *vma;
1848 MA_STATE(mas, &mm->mm_mt, addr, addr);
1850 vma = mas_walk(&mas);
1851 *pprev = mas_prev(&mas, 0);
1853 vma = mas_next(&mas, ULONG_MAX);
1858 * Verify that the stack growth is acceptable and
1859 * update accounting. This is shared with both the
1860 * grow-up and grow-down cases.
1862 static int acct_stack_growth(struct vm_area_struct *vma,
1863 unsigned long size, unsigned long grow)
1865 struct mm_struct *mm = vma->vm_mm;
1866 unsigned long new_start;
1868 /* address space limit tests */
1869 if (!may_expand_vm(mm, vma->vm_flags, grow))
1872 /* Stack limit test */
1873 if (size > rlimit(RLIMIT_STACK))
1876 /* mlock limit tests */
1877 if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
1880 /* Check to ensure the stack will not grow into a hugetlb-only region */
1881 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
1883 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
1887 * Overcommit.. This must be the final test, as it will
1888 * update security statistics.
1890 if (security_vm_enough_memory_mm(mm, grow))
1896 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
1898 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
1899 * vma is the last one with address > vma->vm_end. Have to extend vma.
1901 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
1903 struct mm_struct *mm = vma->vm_mm;
1904 struct vm_area_struct *next;
1905 unsigned long gap_addr;
1907 MA_STATE(mas, &mm->mm_mt, 0, 0);
1909 if (!(vma->vm_flags & VM_GROWSUP))
1912 /* Guard against exceeding limits of the address space. */
1913 address &= PAGE_MASK;
1914 if (address >= (TASK_SIZE & PAGE_MASK))
1916 address += PAGE_SIZE;
1918 /* Enforce stack_guard_gap */
1919 gap_addr = address + stack_guard_gap;
1921 /* Guard against overflow */
1922 if (gap_addr < address || gap_addr > TASK_SIZE)
1923 gap_addr = TASK_SIZE;
1925 next = find_vma_intersection(mm, vma->vm_end, gap_addr);
1926 if (next && vma_is_accessible(next)) {
1927 if (!(next->vm_flags & VM_GROWSUP))
1929 /* Check that both stack segments have the same anon_vma? */
1932 if (mas_preallocate(&mas, GFP_KERNEL))
1935 /* We must make sure the anon_vma is allocated. */
1936 if (unlikely(anon_vma_prepare(vma))) {
1942 * vma->vm_start/vm_end cannot change under us because the caller
1943 * is required to hold the mmap_lock in read mode. We need the
1944 * anon_vma lock to serialize against concurrent expand_stacks.
1946 anon_vma_lock_write(vma->anon_vma);
1948 /* Somebody else might have raced and expanded it already */
1949 if (address > vma->vm_end) {
1950 unsigned long size, grow;
1952 size = address - vma->vm_start;
1953 grow = (address - vma->vm_end) >> PAGE_SHIFT;
1956 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
1957 error = acct_stack_growth(vma, size, grow);
1960 * We only hold a shared mmap_lock lock here, so
1961 * we need to protect against concurrent vma
1962 * expansions. anon_vma_lock_write() doesn't
1963 * help here, as we don't guarantee that all
1964 * growable vmas in a mm share the same root
1965 * anon vma. So, we reuse mm->page_table_lock
1966 * to guard against concurrent vma expansions.
1968 spin_lock(&mm->page_table_lock);
1969 if (vma->vm_flags & VM_LOCKED)
1970 mm->locked_vm += grow;
1971 vm_stat_account(mm, vma->vm_flags, grow);
1972 anon_vma_interval_tree_pre_update_vma(vma);
1973 vma->vm_end = address;
1974 /* Overwrite old entry in mtree. */
1975 mas_set_range(&mas, vma->vm_start, address - 1);
1976 mas_store_prealloc(&mas, vma);
1977 anon_vma_interval_tree_post_update_vma(vma);
1978 spin_unlock(&mm->page_table_lock);
1980 perf_event_mmap(vma);
1984 anon_vma_unlock_write(vma->anon_vma);
1985 khugepaged_enter_vma(vma, vma->vm_flags);
1989 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
1992 * vma is the first one with address < vma->vm_start. Have to extend vma.
1994 int expand_downwards(struct vm_area_struct *vma, unsigned long address)
1996 struct mm_struct *mm = vma->vm_mm;
1997 MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
1998 struct vm_area_struct *prev;
2001 address &= PAGE_MASK;
2002 if (address < mmap_min_addr)
2005 /* Enforce stack_guard_gap */
2006 prev = mas_prev(&mas, 0);
2007 /* Check that both stack segments have the same anon_vma? */
2008 if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2009 vma_is_accessible(prev)) {
2010 if (address - prev->vm_end < stack_guard_gap)
2014 if (mas_preallocate(&mas, GFP_KERNEL))
2017 /* We must make sure the anon_vma is allocated. */
2018 if (unlikely(anon_vma_prepare(vma))) {
2024 * vma->vm_start/vm_end cannot change under us because the caller
2025 * is required to hold the mmap_lock in read mode. We need the
2026 * anon_vma lock to serialize against concurrent expand_stacks.
2028 anon_vma_lock_write(vma->anon_vma);
2030 /* Somebody else might have raced and expanded it already */
2031 if (address < vma->vm_start) {
2032 unsigned long size, grow;
2034 size = vma->vm_end - address;
2035 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2038 if (grow <= vma->vm_pgoff) {
2039 error = acct_stack_growth(vma, size, grow);
2042 * We only hold a shared mmap_lock lock here, so
2043 * we need to protect against concurrent vma
2044 * expansions. anon_vma_lock_write() doesn't
2045 * help here, as we don't guarantee that all
2046 * growable vmas in a mm share the same root
2047 * anon vma. So, we reuse mm->page_table_lock
2048 * to guard against concurrent vma expansions.
2050 spin_lock(&mm->page_table_lock);
2051 if (vma->vm_flags & VM_LOCKED)
2052 mm->locked_vm += grow;
2053 vm_stat_account(mm, vma->vm_flags, grow);
2054 anon_vma_interval_tree_pre_update_vma(vma);
2055 vma->vm_start = address;
2056 vma->vm_pgoff -= grow;
2057 /* Overwrite old entry in mtree. */
2058 mas_set_range(&mas, address, vma->vm_end - 1);
2059 mas_store_prealloc(&mas, vma);
2060 anon_vma_interval_tree_post_update_vma(vma);
2061 spin_unlock(&mm->page_table_lock);
2063 perf_event_mmap(vma);
2067 anon_vma_unlock_write(vma->anon_vma);
2068 khugepaged_enter_vma(vma, vma->vm_flags);
2073 /* enforced gap between the expanding stack and other mappings. */
2074 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2076 static int __init cmdline_parse_stack_guard_gap(char *p)
2081 val = simple_strtoul(p, &endptr, 10);
2083 stack_guard_gap = val << PAGE_SHIFT;
2087 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2089 #ifdef CONFIG_STACK_GROWSUP
2090 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2092 return expand_upwards(vma, address);
2095 struct vm_area_struct *
2096 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2098 struct vm_area_struct *vma, *prev;
2101 vma = find_vma_prev(mm, addr, &prev);
2102 if (vma && (vma->vm_start <= addr))
2104 if (!prev || expand_stack(prev, addr))
2106 if (prev->vm_flags & VM_LOCKED)
2107 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2111 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2113 return expand_downwards(vma, address);
2116 struct vm_area_struct *
2117 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2119 struct vm_area_struct *vma;
2120 unsigned long start;
2123 vma = find_vma(mm, addr);
2126 if (vma->vm_start <= addr)
2128 if (!(vma->vm_flags & VM_GROWSDOWN))
2130 start = vma->vm_start;
2131 if (expand_stack(vma, addr))
2133 if (vma->vm_flags & VM_LOCKED)
2134 populate_vma_page_range(vma, addr, start, NULL);
2139 EXPORT_SYMBOL_GPL(find_extend_vma);
2142 * Ok - we have the memory areas we should free on a maple tree so release them,
2143 * and do the vma updates.
2145 * Called with the mm semaphore held.
2147 static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
2149 unsigned long nr_accounted = 0;
2150 struct vm_area_struct *vma;
2152 /* Update high watermark before we lower total_vm */
2153 update_hiwater_vm(mm);
2154 mas_for_each(mas, vma, ULONG_MAX) {
2155 long nrpages = vma_pages(vma);
2157 if (vma->vm_flags & VM_ACCOUNT)
2158 nr_accounted += nrpages;
2159 vm_stat_account(mm, vma->vm_flags, -nrpages);
2162 vm_unacct_memory(nr_accounted);
2167 * Get rid of page table information in the indicated region.
2169 * Called with the mm semaphore held.
2171 static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
2172 struct vm_area_struct *vma, struct vm_area_struct *prev,
2173 struct vm_area_struct *next,
2174 unsigned long start, unsigned long end, bool mm_wr_locked)
2176 struct mmu_gather tlb;
2179 tlb_gather_mmu(&tlb, mm);
2180 update_hiwater_rss(mm);
2181 unmap_vmas(&tlb, mt, vma, start, end, mm_wr_locked);
2182 free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2183 next ? next->vm_start : USER_PGTABLES_CEILING);
2184 tlb_finish_mmu(&tlb);
2188 * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
2189 * has already been checked or doesn't make sense to fail.
2190 * VMA Iterator will point to the end VMA.
2192 int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2193 unsigned long addr, int new_below)
2195 struct vma_prepare vp;
2196 struct vm_area_struct *new;
2199 validate_mm_mt(vma->vm_mm);
2201 WARN_ON(vma->vm_start >= addr);
2202 WARN_ON(vma->vm_end <= addr);
2204 if (vma->vm_ops && vma->vm_ops->may_split) {
2205 err = vma->vm_ops->may_split(vma, addr);
2210 new = vm_area_dup(vma);
2215 if (vma_iter_prealloc(vmi))
2221 new->vm_start = addr;
2222 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2225 err = vma_dup_policy(vma, new);
2229 err = anon_vma_clone(new, vma);
2234 get_file(new->vm_file);
2236 if (new->vm_ops && new->vm_ops->open)
2237 new->vm_ops->open(new);
2239 vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
2240 init_vma_prep(&vp, vma);
2245 vma->vm_start = addr;
2246 vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
2251 /* vma_complete stores the new vma */
2252 vma_complete(&vp, vmi, vma->vm_mm);
2257 validate_mm_mt(vma->vm_mm);
2261 mpol_put(vma_policy(new));
2266 validate_mm_mt(vma->vm_mm);
2271 * Split a vma into two pieces at address 'addr', a new vma is allocated
2272 * either for the first part or the tail.
2274 int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2275 unsigned long addr, int new_below)
2277 if (vma->vm_mm->map_count >= sysctl_max_map_count)
2280 return __split_vma(vmi, vma, addr, new_below);
2283 static inline int munmap_sidetree(struct vm_area_struct *vma,
2284 struct ma_state *mas_detach)
2286 mas_set_range(mas_detach, vma->vm_start, vma->vm_end - 1);
2287 if (mas_store_gfp(mas_detach, vma, GFP_KERNEL))
2290 if (vma->vm_flags & VM_LOCKED)
2291 vma->vm_mm->locked_vm -= vma_pages(vma);
2297 * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2298 * @vmi: The vma iterator
2299 * @vma: The starting vm_area_struct
2300 * @mm: The mm_struct
2301 * @start: The aligned start address to munmap.
2302 * @end: The aligned end address to munmap.
2303 * @uf: The userfaultfd list_head
2304 * @downgrade: Set to true to attempt a write downgrade of the mmap_lock
2306 * If @downgrade is true, check return code for potential release of the lock.
2309 do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2310 struct mm_struct *mm, unsigned long start,
2311 unsigned long end, struct list_head *uf, bool downgrade)
2313 struct vm_area_struct *prev, *next = NULL;
2314 struct maple_tree mt_detach;
2316 int error = -ENOMEM;
2317 MA_STATE(mas_detach, &mt_detach, 0, 0);
2318 mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
2319 mt_set_external_lock(&mt_detach, &mm->mmap_lock);
2322 * If we need to split any vma, do it now to save pain later.
2324 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2325 * unmapped vm_area_struct will remain in use: so lower split_vma
2326 * places tmp vma above, and higher split_vma places tmp vma below.
2329 /* Does it split the first one? */
2330 if (start > vma->vm_start) {
2333 * Make sure that map_count on return from munmap() will
2334 * not exceed its limit; but let map_count go just above
2335 * its limit temporarily, to help free resources as expected.
2337 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2338 goto map_count_exceeded;
2340 error = __split_vma(vmi, vma, start, 0);
2342 goto start_split_failed;
2344 vma = vma_iter_load(vmi);
2347 prev = vma_prev(vmi);
2348 if (unlikely((!prev)))
2349 vma_iter_set(vmi, start);
2352 * Detach a range of VMAs from the mm. Using next as a temp variable as
2353 * it is always overwritten.
2355 for_each_vma_range(*vmi, next, end) {
2356 /* Does it split the end? */
2357 if (next->vm_end > end) {
2358 error = __split_vma(vmi, next, end, 0);
2360 goto end_split_failed;
2362 error = munmap_sidetree(next, &mas_detach);
2364 goto munmap_sidetree_failed;
2367 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2368 BUG_ON(next->vm_start < start);
2369 BUG_ON(next->vm_start > end);
2373 next = vma_next(vmi);
2376 * If userfaultfd_unmap_prep returns an error the vmas
2377 * will remain split, but userland will get a
2378 * highly unexpected error anyway. This is no
2379 * different than the case where the first of the two
2380 * __split_vma fails, but we don't undo the first
2381 * split, despite we could. This is unlikely enough
2382 * failure that it's not worth optimizing it for.
2384 error = userfaultfd_unmap_prep(mm, start, end, uf);
2387 goto userfaultfd_error;
2390 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2391 /* Make sure no VMAs are about to be lost. */
2393 MA_STATE(test, &mt_detach, start, end - 1);
2394 struct vm_area_struct *vma_mas, *vma_test;
2397 vma_iter_set(vmi, start);
2399 vma_test = mas_find(&test, end - 1);
2400 for_each_vma_range(*vmi, vma_mas, end) {
2401 BUG_ON(vma_mas != vma_test);
2403 vma_test = mas_next(&test, end - 1);
2406 BUG_ON(count != test_count);
2409 /* Point of no return */
2410 vma_iter_set(vmi, start);
2411 if (vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL))
2414 mm->map_count -= count;
2416 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2417 * VM_GROWSUP VMA. Such VMAs can change their size under
2418 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2421 if (next && (next->vm_flags & VM_GROWSDOWN))
2423 else if (prev && (prev->vm_flags & VM_GROWSUP))
2426 mmap_write_downgrade(mm);
2430 * We can free page tables without write-locking mmap_lock because VMAs
2431 * were isolated before we downgraded mmap_lock.
2433 unmap_region(mm, &mt_detach, vma, prev, next, start, end, !downgrade);
2434 /* Statistics and freeing VMAs */
2435 mas_set(&mas_detach, start);
2436 remove_mt(mm, &mas_detach);
2437 __mt_destroy(&mt_detach);
2441 return downgrade ? 1 : 0;
2444 munmap_sidetree_failed:
2446 __mt_destroy(&mt_detach);
2453 * do_vmi_munmap() - munmap a given range.
2454 * @vmi: The vma iterator
2455 * @mm: The mm_struct
2456 * @start: The start address to munmap
2457 * @len: The length of the range to munmap
2458 * @uf: The userfaultfd list_head
2459 * @downgrade: set to true if the user wants to attempt to write_downgrade the
2462 * This function takes a @mas that is either pointing to the previous VMA or set
2463 * to MA_START and sets it up to remove the mapping(s). The @len will be
2464 * aligned and any arch_unmap work will be preformed.
2466 * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
2468 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
2469 unsigned long start, size_t len, struct list_head *uf,
2473 struct vm_area_struct *vma;
2475 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2478 end = start + PAGE_ALIGN(len);
2482 /* arch_unmap() might do unmaps itself. */
2483 arch_unmap(mm, start, end);
2485 /* Find the first overlapping VMA */
2486 vma = vma_find(vmi, end);
2490 return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2493 /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
2494 * @mm: The mm_struct
2495 * @start: The start address to munmap
2496 * @len: The length to be munmapped.
2497 * @uf: The userfaultfd list_head
2499 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2500 struct list_head *uf)
2502 VMA_ITERATOR(vmi, mm, start);
2504 return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2507 unsigned long mmap_region(struct file *file, unsigned long addr,
2508 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2509 struct list_head *uf)
2511 struct mm_struct *mm = current->mm;
2512 struct vm_area_struct *vma = NULL;
2513 struct vm_area_struct *next, *prev, *merge;
2514 pgoff_t pglen = len >> PAGE_SHIFT;
2515 unsigned long charged = 0;
2516 unsigned long end = addr + len;
2517 unsigned long merge_start = addr, merge_end = end;
2520 VMA_ITERATOR(vmi, mm, addr);
2522 /* Check against address space limit. */
2523 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2524 unsigned long nr_pages;
2527 * MAP_FIXED may remove pages of mappings that intersects with
2528 * requested mapping. Account for the pages it would unmap.
2530 nr_pages = count_vma_pages_range(mm, addr, end);
2532 if (!may_expand_vm(mm, vm_flags,
2533 (len >> PAGE_SHIFT) - nr_pages))
2537 /* Unmap any existing mapping in the area */
2538 if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2542 * Private writable mapping: check memory availability
2544 if (accountable_mapping(file, vm_flags)) {
2545 charged = len >> PAGE_SHIFT;
2546 if (security_vm_enough_memory_mm(mm, charged))
2548 vm_flags |= VM_ACCOUNT;
2551 next = vma_next(&vmi);
2552 prev = vma_prev(&vmi);
2553 if (vm_flags & VM_SPECIAL)
2556 /* Attempt to expand an old mapping */
2558 if (next && next->vm_start == end && !vma_policy(next) &&
2559 can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2560 NULL_VM_UFFD_CTX, NULL)) {
2561 merge_end = next->vm_end;
2563 vm_pgoff = next->vm_pgoff - pglen;
2567 if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2568 (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2569 pgoff, vma->vm_userfaultfd_ctx, NULL) :
2570 can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2571 NULL_VM_UFFD_CTX, NULL))) {
2572 merge_start = prev->vm_start;
2574 vm_pgoff = prev->vm_pgoff;
2578 /* Actually expand, if possible */
2580 !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2581 khugepaged_enter_vma(vma, vm_flags);
2587 * Determine the object being mapped and call the appropriate
2588 * specific mapper. the address has already been validated, but
2589 * not unmapped, but the maps are removed from the list.
2591 vma = vm_area_alloc(mm);
2597 vma_iter_set(&vmi, addr);
2598 vma->vm_start = addr;
2600 vm_flags_init(vma, vm_flags);
2601 vma->vm_page_prot = vm_get_page_prot(vm_flags);
2602 vma->vm_pgoff = pgoff;
2605 if (vm_flags & VM_SHARED) {
2606 error = mapping_map_writable(file->f_mapping);
2611 vma->vm_file = get_file(file);
2612 error = call_mmap(file, vma);
2614 goto unmap_and_free_vma;
2617 * Expansion is handled above, merging is handled below.
2618 * Drivers should not alter the address of the VMA.
2621 if (WARN_ON((addr != vma->vm_start)))
2622 goto close_and_free_vma;
2624 vma_iter_set(&vmi, addr);
2626 * If vm_flags changed after call_mmap(), we should try merge
2627 * vma again as we may succeed this time.
2629 if (unlikely(vm_flags != vma->vm_flags && prev)) {
2630 merge = vma_merge(&vmi, mm, prev, vma->vm_start,
2631 vma->vm_end, vma->vm_flags, NULL,
2632 vma->vm_file, vma->vm_pgoff, NULL,
2633 NULL_VM_UFFD_CTX, NULL);
2636 * ->mmap() can change vma->vm_file and fput
2637 * the original file. So fput the vma->vm_file
2638 * here or we would add an extra fput for file
2639 * and cause general protection fault
2645 /* Update vm_flags to pick up the change. */
2646 vm_flags = vma->vm_flags;
2647 goto unmap_writable;
2651 vm_flags = vma->vm_flags;
2652 } else if (vm_flags & VM_SHARED) {
2653 error = shmem_zero_setup(vma);
2657 vma_set_anonymous(vma);
2660 if (map_deny_write_exec(vma, vma->vm_flags)) {
2662 goto close_and_free_vma;
2665 /* Allow architectures to sanity-check the vm_flags */
2667 if (!arch_validate_flags(vma->vm_flags))
2668 goto close_and_free_vma;
2671 if (vma_iter_prealloc(&vmi))
2672 goto close_and_free_vma;
2675 i_mmap_lock_write(vma->vm_file->f_mapping);
2677 vma_iter_store(&vmi, vma);
2680 if (vma->vm_flags & VM_SHARED)
2681 mapping_allow_writable(vma->vm_file->f_mapping);
2683 flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2684 vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2685 flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2686 i_mmap_unlock_write(vma->vm_file->f_mapping);
2690 * vma_merge() calls khugepaged_enter_vma() either, the below
2691 * call covers the non-merge case.
2693 khugepaged_enter_vma(vma, vma->vm_flags);
2695 /* Once vma denies write, undo our temporary denial count */
2697 if (file && vm_flags & VM_SHARED)
2698 mapping_unmap_writable(file->f_mapping);
2699 file = vma->vm_file;
2701 perf_event_mmap(vma);
2703 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2704 if (vm_flags & VM_LOCKED) {
2705 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2706 is_vm_hugetlb_page(vma) ||
2707 vma == get_gate_vma(current->mm))
2708 vm_flags_clear(vma, VM_LOCKED_MASK);
2710 mm->locked_vm += (len >> PAGE_SHIFT);
2717 * New (or expanded) vma always get soft dirty status.
2718 * Otherwise user-space soft-dirty page tracker won't
2719 * be able to distinguish situation when vma area unmapped,
2720 * then new mapped in-place (which must be aimed as
2721 * a completely new data area).
2723 vm_flags_set(vma, VM_SOFTDIRTY);
2725 vma_set_page_prot(vma);
2731 if (file && vma->vm_ops && vma->vm_ops->close)
2732 vma->vm_ops->close(vma);
2734 if (file || vma->vm_file) {
2737 vma->vm_file = NULL;
2739 /* Undo any partial mapping done by a device driver. */
2740 unmap_region(mm, &mm->mm_mt, vma, prev, next, vma->vm_start,
2743 if (file && (vm_flags & VM_SHARED))
2744 mapping_unmap_writable(file->f_mapping);
2749 vm_unacct_memory(charged);
2754 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2757 struct mm_struct *mm = current->mm;
2759 VMA_ITERATOR(vmi, mm, start);
2761 if (mmap_write_lock_killable(mm))
2764 ret = do_vmi_munmap(&vmi, mm, start, len, &uf, downgrade);
2766 * Returning 1 indicates mmap_lock is downgraded.
2767 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2768 * it to 0 before return.
2771 mmap_read_unlock(mm);
2774 mmap_write_unlock(mm);
2776 userfaultfd_unmap_complete(mm, &uf);
2780 int vm_munmap(unsigned long start, size_t len)
2782 return __vm_munmap(start, len, false);
2784 EXPORT_SYMBOL(vm_munmap);
2786 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2788 addr = untagged_addr(addr);
2789 return __vm_munmap(addr, len, true);
2794 * Emulation of deprecated remap_file_pages() syscall.
2796 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2797 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2800 struct mm_struct *mm = current->mm;
2801 struct vm_area_struct *vma;
2802 unsigned long populate = 0;
2803 unsigned long ret = -EINVAL;
2806 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2807 current->comm, current->pid);
2811 start = start & PAGE_MASK;
2812 size = size & PAGE_MASK;
2814 if (start + size <= start)
2817 /* Does pgoff wrap? */
2818 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2821 if (mmap_write_lock_killable(mm))
2824 vma = vma_lookup(mm, start);
2826 if (!vma || !(vma->vm_flags & VM_SHARED))
2829 if (start + size > vma->vm_end) {
2830 VMA_ITERATOR(vmi, mm, vma->vm_end);
2831 struct vm_area_struct *next, *prev = vma;
2833 for_each_vma_range(vmi, next, start + size) {
2834 /* hole between vmas ? */
2835 if (next->vm_start != prev->vm_end)
2838 if (next->vm_file != vma->vm_file)
2841 if (next->vm_flags != vma->vm_flags)
2844 if (start + size <= next->vm_end)
2854 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2855 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2856 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2858 flags &= MAP_NONBLOCK;
2859 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2860 if (vma->vm_flags & VM_LOCKED)
2861 flags |= MAP_LOCKED;
2863 file = get_file(vma->vm_file);
2864 ret = do_mmap(vma->vm_file, start, size,
2865 prot, flags, pgoff, &populate, NULL);
2868 mmap_write_unlock(mm);
2870 mm_populate(ret, populate);
2871 if (!IS_ERR_VALUE(ret))
2877 * do_vma_munmap() - Unmap a full or partial vma.
2878 * @vmi: The vma iterator pointing at the vma
2879 * @vma: The first vma to be munmapped
2880 * @start: the start of the address to unmap
2881 * @end: The end of the address to unmap
2882 * @uf: The userfaultfd list_head
2883 * @downgrade: Attempt to downgrade or not
2885 * Returns: 0 on success and not downgraded, 1 on success and downgraded.
2886 * unmaps a VMA mapping when the vma iterator is already in position.
2887 * Does not handle alignment.
2889 int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2890 unsigned long start, unsigned long end,
2891 struct list_head *uf, bool downgrade)
2893 struct mm_struct *mm = vma->vm_mm;
2896 arch_unmap(mm, start, end);
2897 ret = do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2903 * do_brk_flags() - Increase the brk vma if the flags match.
2904 * @vmi: The vma iterator
2905 * @addr: The start address
2906 * @len: The length of the increase
2908 * @flags: The VMA Flags
2910 * Extend the brk VMA from addr to addr + len. If the VMA is NULL or the flags
2911 * do not match then create a new anonymous VMA. Eventually we may be able to
2912 * do some brk-specific accounting here.
2914 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
2915 unsigned long addr, unsigned long len, unsigned long flags)
2917 struct mm_struct *mm = current->mm;
2918 struct vma_prepare vp;
2922 * Check against address space limits by the changed size
2923 * Note: This happens *after* clearing old mappings in some code paths.
2925 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2926 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
2929 if (mm->map_count > sysctl_max_map_count)
2932 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2936 * Expand the existing vma if possible; Note that singular lists do not
2937 * occur after forking, so the expand will only happen on new VMAs.
2939 if (vma && vma->vm_end == addr && !vma_policy(vma) &&
2940 can_vma_merge_after(vma, flags, NULL, NULL,
2941 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
2942 if (vma_iter_prealloc(vmi))
2945 vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
2946 init_vma_prep(&vp, vma);
2948 vma->vm_end = addr + len;
2949 vm_flags_set(vma, VM_SOFTDIRTY);
2950 vma_iter_store(vmi, vma);
2952 vma_complete(&vp, vmi, mm);
2953 khugepaged_enter_vma(vma, flags);
2957 /* create a vma struct for an anonymous mapping */
2958 vma = vm_area_alloc(mm);
2962 vma_set_anonymous(vma);
2963 vma->vm_start = addr;
2964 vma->vm_end = addr + len;
2965 vma->vm_pgoff = addr >> PAGE_SHIFT;
2966 vm_flags_init(vma, flags);
2967 vma->vm_page_prot = vm_get_page_prot(flags);
2968 if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
2969 goto mas_store_fail;
2973 perf_event_mmap(vma);
2974 mm->total_vm += len >> PAGE_SHIFT;
2975 mm->data_vm += len >> PAGE_SHIFT;
2976 if (flags & VM_LOCKED)
2977 mm->locked_vm += (len >> PAGE_SHIFT);
2978 vm_flags_set(vma, VM_SOFTDIRTY);
2985 vm_unacct_memory(len >> PAGE_SHIFT);
2989 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
2991 struct mm_struct *mm = current->mm;
2992 struct vm_area_struct *vma = NULL;
2997 VMA_ITERATOR(vmi, mm, addr);
2999 len = PAGE_ALIGN(request);
3005 if (mmap_write_lock_killable(mm))
3008 /* Until we need other flags, refuse anything except VM_EXEC. */
3009 if ((flags & (~VM_EXEC)) != 0)
3012 ret = check_brk_limits(addr, len);
3016 ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
3020 vma = vma_prev(&vmi);
3021 ret = do_brk_flags(&vmi, vma, addr, len, flags);
3022 populate = ((mm->def_flags & VM_LOCKED) != 0);
3023 mmap_write_unlock(mm);
3024 userfaultfd_unmap_complete(mm, &uf);
3025 if (populate && !ret)
3026 mm_populate(addr, len);
3031 mmap_write_unlock(mm);
3034 EXPORT_SYMBOL(vm_brk_flags);
3036 int vm_brk(unsigned long addr, unsigned long len)
3038 return vm_brk_flags(addr, len, 0);
3040 EXPORT_SYMBOL(vm_brk);
3042 /* Release all mmaps. */
3043 void exit_mmap(struct mm_struct *mm)
3045 struct mmu_gather tlb;
3046 struct vm_area_struct *vma;
3047 unsigned long nr_accounted = 0;
3048 MA_STATE(mas, &mm->mm_mt, 0, 0);
3051 /* mm's last user has gone, and its about to be pulled down */
3052 mmu_notifier_release(mm);
3057 vma = mas_find(&mas, ULONG_MAX);
3059 /* Can happen if dup_mmap() received an OOM */
3060 mmap_read_unlock(mm);
3066 tlb_gather_mmu_fullmm(&tlb, mm);
3067 /* update_hiwater_rss(mm) here? but nobody should be looking */
3068 /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3069 unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX, false);
3070 mmap_read_unlock(mm);
3073 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3074 * because the memory has been already freed.
3076 set_bit(MMF_OOM_SKIP, &mm->flags);
3077 mmap_write_lock(mm);
3078 mt_clear_in_rcu(&mm->mm_mt);
3079 free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
3080 USER_PGTABLES_CEILING);
3081 tlb_finish_mmu(&tlb);
3084 * Walk the list again, actually closing and freeing it, with preemption
3085 * enabled, without holding any MM locks besides the unreachable
3089 if (vma->vm_flags & VM_ACCOUNT)
3090 nr_accounted += vma_pages(vma);
3094 } while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3096 BUG_ON(count != mm->map_count);
3098 trace_exit_mmap(mm);
3099 __mt_destroy(&mm->mm_mt);
3100 mmap_write_unlock(mm);
3101 vm_unacct_memory(nr_accounted);
3104 /* Insert vm structure into process list sorted by address
3105 * and into the inode's i_mmap tree. If vm_file is non-NULL
3106 * then i_mmap_rwsem is taken here.
3108 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3110 unsigned long charged = vma_pages(vma);
3113 if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3116 if ((vma->vm_flags & VM_ACCOUNT) &&
3117 security_vm_enough_memory_mm(mm, charged))
3121 * The vm_pgoff of a purely anonymous vma should be irrelevant
3122 * until its first write fault, when page's anon_vma and index
3123 * are set. But now set the vm_pgoff it will almost certainly
3124 * end up with (unless mremap moves it elsewhere before that
3125 * first wfault), so /proc/pid/maps tells a consistent story.
3127 * By setting it to reflect the virtual start address of the
3128 * vma, merges and splits can happen in a seamless way, just
3129 * using the existing file pgoff checks and manipulations.
3130 * Similarly in do_mmap and in do_brk_flags.
3132 if (vma_is_anonymous(vma)) {
3133 BUG_ON(vma->anon_vma);
3134 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3137 if (vma_link(mm, vma)) {
3138 vm_unacct_memory(charged);
3146 * Copy the vma structure to a new location in the same mm,
3147 * prior to moving page table entries, to effect an mremap move.
3149 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3150 unsigned long addr, unsigned long len, pgoff_t pgoff,
3151 bool *need_rmap_locks)
3153 struct vm_area_struct *vma = *vmap;
3154 unsigned long vma_start = vma->vm_start;
3155 struct mm_struct *mm = vma->vm_mm;
3156 struct vm_area_struct *new_vma, *prev;
3157 bool faulted_in_anon_vma = true;
3158 VMA_ITERATOR(vmi, mm, addr);
3162 * If anonymous vma has not yet been faulted, update new pgoff
3163 * to match new location, to increase its chance of merging.
3165 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3166 pgoff = addr >> PAGE_SHIFT;
3167 faulted_in_anon_vma = false;
3170 new_vma = find_vma_prev(mm, addr, &prev);
3171 if (new_vma && new_vma->vm_start < addr + len)
3172 return NULL; /* should never get here */
3174 new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
3175 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3176 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3179 * Source vma may have been merged into new_vma
3181 if (unlikely(vma_start >= new_vma->vm_start &&
3182 vma_start < new_vma->vm_end)) {
3184 * The only way we can get a vma_merge with
3185 * self during an mremap is if the vma hasn't
3186 * been faulted in yet and we were allowed to
3187 * reset the dst vma->vm_pgoff to the
3188 * destination address of the mremap to allow
3189 * the merge to happen. mremap must change the
3190 * vm_pgoff linearity between src and dst vmas
3191 * (in turn preventing a vma_merge) to be
3192 * safe. It is only safe to keep the vm_pgoff
3193 * linear if there are no pages mapped yet.
3195 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3196 *vmap = vma = new_vma;
3198 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3200 new_vma = vm_area_dup(vma);
3203 new_vma->vm_start = addr;
3204 new_vma->vm_end = addr + len;
3205 new_vma->vm_pgoff = pgoff;
3206 if (vma_dup_policy(vma, new_vma))
3208 if (anon_vma_clone(new_vma, vma))
3209 goto out_free_mempol;
3210 if (new_vma->vm_file)
3211 get_file(new_vma->vm_file);
3212 if (new_vma->vm_ops && new_vma->vm_ops->open)
3213 new_vma->vm_ops->open(new_vma);
3214 if (vma_link(mm, new_vma))
3216 *need_rmap_locks = false;
3222 if (new_vma->vm_ops && new_vma->vm_ops->close)
3223 new_vma->vm_ops->close(new_vma);
3225 if (new_vma->vm_file)
3226 fput(new_vma->vm_file);
3228 unlink_anon_vmas(new_vma);
3230 mpol_put(vma_policy(new_vma));
3232 vm_area_free(new_vma);
3239 * Return true if the calling process may expand its vm space by the passed
3242 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3244 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3247 if (is_data_mapping(flags) &&
3248 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3249 /* Workaround for Valgrind */
3250 if (rlimit(RLIMIT_DATA) == 0 &&
3251 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3254 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3255 current->comm, current->pid,
3256 (mm->data_vm + npages) << PAGE_SHIFT,
3257 rlimit(RLIMIT_DATA),
3258 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3260 if (!ignore_rlimit_data)
3267 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3269 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3271 if (is_exec_mapping(flags))
3272 mm->exec_vm += npages;
3273 else if (is_stack_mapping(flags))
3274 mm->stack_vm += npages;
3275 else if (is_data_mapping(flags))
3276 mm->data_vm += npages;
3279 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3282 * Having a close hook prevents vma merging regardless of flags.
3284 static void special_mapping_close(struct vm_area_struct *vma)
3288 static const char *special_mapping_name(struct vm_area_struct *vma)
3290 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3293 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3295 struct vm_special_mapping *sm = new_vma->vm_private_data;
3297 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3301 return sm->mremap(sm, new_vma);
3306 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3309 * Forbid splitting special mappings - kernel has expectations over
3310 * the number of pages in mapping. Together with VM_DONTEXPAND
3311 * the size of vma should stay the same over the special mapping's
3317 static const struct vm_operations_struct special_mapping_vmops = {
3318 .close = special_mapping_close,
3319 .fault = special_mapping_fault,
3320 .mremap = special_mapping_mremap,
3321 .name = special_mapping_name,
3322 /* vDSO code relies that VVAR can't be accessed remotely */
3324 .may_split = special_mapping_split,
3327 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3328 .close = special_mapping_close,
3329 .fault = special_mapping_fault,
3332 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3334 struct vm_area_struct *vma = vmf->vma;
3336 struct page **pages;
3338 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3339 pages = vma->vm_private_data;
3341 struct vm_special_mapping *sm = vma->vm_private_data;
3344 return sm->fault(sm, vmf->vma, vmf);
3349 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3353 struct page *page = *pages;
3359 return VM_FAULT_SIGBUS;
3362 static struct vm_area_struct *__install_special_mapping(
3363 struct mm_struct *mm,
3364 unsigned long addr, unsigned long len,
3365 unsigned long vm_flags, void *priv,
3366 const struct vm_operations_struct *ops)
3369 struct vm_area_struct *vma;
3372 vma = vm_area_alloc(mm);
3373 if (unlikely(vma == NULL))
3374 return ERR_PTR(-ENOMEM);
3376 vma->vm_start = addr;
3377 vma->vm_end = addr + len;
3379 vm_flags_init(vma, (vm_flags | mm->def_flags |
3380 VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
3381 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3384 vma->vm_private_data = priv;
3386 ret = insert_vm_struct(mm, vma);
3390 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3392 perf_event_mmap(vma);
3400 return ERR_PTR(ret);
3403 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3404 const struct vm_special_mapping *sm)
3406 return vma->vm_private_data == sm &&
3407 (vma->vm_ops == &special_mapping_vmops ||
3408 vma->vm_ops == &legacy_special_mapping_vmops);
3412 * Called with mm->mmap_lock held for writing.
3413 * Insert a new vma covering the given region, with the given flags.
3414 * Its pages are supplied by the given array of struct page *.
3415 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3416 * The region past the last page supplied will always produce SIGBUS.
3417 * The array pointer and the pages it points to are assumed to stay alive
3418 * for as long as this mapping might exist.
3420 struct vm_area_struct *_install_special_mapping(
3421 struct mm_struct *mm,
3422 unsigned long addr, unsigned long len,
3423 unsigned long vm_flags, const struct vm_special_mapping *spec)
3425 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3426 &special_mapping_vmops);
3429 int install_special_mapping(struct mm_struct *mm,
3430 unsigned long addr, unsigned long len,
3431 unsigned long vm_flags, struct page **pages)
3433 struct vm_area_struct *vma = __install_special_mapping(
3434 mm, addr, len, vm_flags, (void *)pages,
3435 &legacy_special_mapping_vmops);
3437 return PTR_ERR_OR_ZERO(vma);
3440 static DEFINE_MUTEX(mm_all_locks_mutex);
3442 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3444 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3446 * The LSB of head.next can't change from under us
3447 * because we hold the mm_all_locks_mutex.
3449 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3451 * We can safely modify head.next after taking the
3452 * anon_vma->root->rwsem. If some other vma in this mm shares
3453 * the same anon_vma we won't take it again.
3455 * No need of atomic instructions here, head.next
3456 * can't change from under us thanks to the
3457 * anon_vma->root->rwsem.
3459 if (__test_and_set_bit(0, (unsigned long *)
3460 &anon_vma->root->rb_root.rb_root.rb_node))
3465 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3467 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3469 * AS_MM_ALL_LOCKS can't change from under us because
3470 * we hold the mm_all_locks_mutex.
3472 * Operations on ->flags have to be atomic because
3473 * even if AS_MM_ALL_LOCKS is stable thanks to the
3474 * mm_all_locks_mutex, there may be other cpus
3475 * changing other bitflags in parallel to us.
3477 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3479 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3484 * This operation locks against the VM for all pte/vma/mm related
3485 * operations that could ever happen on a certain mm. This includes
3486 * vmtruncate, try_to_unmap, and all page faults.
3488 * The caller must take the mmap_lock in write mode before calling
3489 * mm_take_all_locks(). The caller isn't allowed to release the
3490 * mmap_lock until mm_drop_all_locks() returns.
3492 * mmap_lock in write mode is required in order to block all operations
3493 * that could modify pagetables and free pages without need of
3494 * altering the vma layout. It's also needed in write mode to avoid new
3495 * anon_vmas to be associated with existing vmas.
3497 * A single task can't take more than one mm_take_all_locks() in a row
3498 * or it would deadlock.
3500 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3501 * mapping->flags avoid to take the same lock twice, if more than one
3502 * vma in this mm is backed by the same anon_vma or address_space.
3504 * We take locks in following order, accordingly to comment at beginning
3506 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3508 * - all i_mmap_rwsem locks;
3509 * - all anon_vma->rwseml
3511 * We can take all locks within these types randomly because the VM code
3512 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3513 * mm_all_locks_mutex.
3515 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3516 * that may have to take thousand of locks.
3518 * mm_take_all_locks() can fail if it's interrupted by signals.
3520 int mm_take_all_locks(struct mm_struct *mm)
3522 struct vm_area_struct *vma;
3523 struct anon_vma_chain *avc;
3524 MA_STATE(mas, &mm->mm_mt, 0, 0);
3526 mmap_assert_write_locked(mm);
3528 mutex_lock(&mm_all_locks_mutex);
3530 mas_for_each(&mas, vma, ULONG_MAX) {
3531 if (signal_pending(current))
3533 if (vma->vm_file && vma->vm_file->f_mapping &&
3534 is_vm_hugetlb_page(vma))
3535 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3539 mas_for_each(&mas, vma, ULONG_MAX) {
3540 if (signal_pending(current))
3542 if (vma->vm_file && vma->vm_file->f_mapping &&
3543 !is_vm_hugetlb_page(vma))
3544 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3548 mas_for_each(&mas, vma, ULONG_MAX) {
3549 if (signal_pending(current))
3552 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3553 vm_lock_anon_vma(mm, avc->anon_vma);
3559 mm_drop_all_locks(mm);
3563 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3565 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3567 * The LSB of head.next can't change to 0 from under
3568 * us because we hold the mm_all_locks_mutex.
3570 * We must however clear the bitflag before unlocking
3571 * the vma so the users using the anon_vma->rb_root will
3572 * never see our bitflag.
3574 * No need of atomic instructions here, head.next
3575 * can't change from under us until we release the
3576 * anon_vma->root->rwsem.
3578 if (!__test_and_clear_bit(0, (unsigned long *)
3579 &anon_vma->root->rb_root.rb_root.rb_node))
3581 anon_vma_unlock_write(anon_vma);
3585 static void vm_unlock_mapping(struct address_space *mapping)
3587 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3589 * AS_MM_ALL_LOCKS can't change to 0 from under us
3590 * because we hold the mm_all_locks_mutex.
3592 i_mmap_unlock_write(mapping);
3593 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3600 * The mmap_lock cannot be released by the caller until
3601 * mm_drop_all_locks() returns.
3603 void mm_drop_all_locks(struct mm_struct *mm)
3605 struct vm_area_struct *vma;
3606 struct anon_vma_chain *avc;
3607 MA_STATE(mas, &mm->mm_mt, 0, 0);
3609 mmap_assert_write_locked(mm);
3610 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3612 mas_for_each(&mas, vma, ULONG_MAX) {
3614 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3615 vm_unlock_anon_vma(avc->anon_vma);
3616 if (vma->vm_file && vma->vm_file->f_mapping)
3617 vm_unlock_mapping(vma->vm_file->f_mapping);
3620 mutex_unlock(&mm_all_locks_mutex);
3624 * initialise the percpu counter for VM
3626 void __init mmap_init(void)
3630 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3635 * Initialise sysctl_user_reserve_kbytes.
3637 * This is intended to prevent a user from starting a single memory hogging
3638 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3641 * The default value is min(3% of free memory, 128MB)
3642 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3644 static int init_user_reserve(void)
3646 unsigned long free_kbytes;
3648 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3650 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3653 subsys_initcall(init_user_reserve);
3656 * Initialise sysctl_admin_reserve_kbytes.
3658 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3659 * to log in and kill a memory hogging process.
3661 * Systems with more than 256MB will reserve 8MB, enough to recover
3662 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3663 * only reserve 3% of free pages by default.
3665 static int init_admin_reserve(void)
3667 unsigned long free_kbytes;
3669 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3671 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3674 subsys_initcall(init_admin_reserve);
3677 * Reinititalise user and admin reserves if memory is added or removed.
3679 * The default user reserve max is 128MB, and the default max for the
3680 * admin reserve is 8MB. These are usually, but not always, enough to
3681 * enable recovery from a memory hogging process using login/sshd, a shell,
3682 * and tools like top. It may make sense to increase or even disable the
3683 * reserve depending on the existence of swap or variations in the recovery
3684 * tools. So, the admin may have changed them.
3686 * If memory is added and the reserves have been eliminated or increased above
3687 * the default max, then we'll trust the admin.
3689 * If memory is removed and there isn't enough free memory, then we
3690 * need to reset the reserves.
3692 * Otherwise keep the reserve set by the admin.
3694 static int reserve_mem_notifier(struct notifier_block *nb,
3695 unsigned long action, void *data)
3697 unsigned long tmp, free_kbytes;
3701 /* Default max is 128MB. Leave alone if modified by operator. */
3702 tmp = sysctl_user_reserve_kbytes;
3703 if (0 < tmp && tmp < (1UL << 17))
3704 init_user_reserve();
3706 /* Default max is 8MB. Leave alone if modified by operator. */
3707 tmp = sysctl_admin_reserve_kbytes;
3708 if (0 < tmp && tmp < (1UL << 13))
3709 init_admin_reserve();
3713 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3715 if (sysctl_user_reserve_kbytes > free_kbytes) {
3716 init_user_reserve();
3717 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3718 sysctl_user_reserve_kbytes);
3721 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3722 init_admin_reserve();
3723 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3724 sysctl_admin_reserve_kbytes);
3733 static int __meminit init_reserve_notifier(void)
3735 if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3736 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3740 subsys_initcall(init_reserve_notifier);