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>
49 #include <linux/ksm.h>
51 #include <linux/uaccess.h>
52 #include <asm/cacheflush.h>
54 #include <asm/mmu_context.h>
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/mmap.h>
61 #ifndef arch_mmap_check
62 #define arch_mmap_check(addr, len, flags) (0)
65 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
66 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
67 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
68 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
70 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
71 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
72 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
73 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
76 static bool ignore_rlimit_data;
77 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
79 static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
80 struct vm_area_struct *vma, struct vm_area_struct *prev,
81 struct vm_area_struct *next, unsigned long start,
82 unsigned long end, bool mm_wr_locked);
84 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
86 return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
89 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
90 void vma_set_page_prot(struct vm_area_struct *vma)
92 unsigned long vm_flags = vma->vm_flags;
93 pgprot_t vm_page_prot;
95 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
96 if (vma_wants_writenotify(vma, vm_page_prot)) {
97 vm_flags &= ~VM_SHARED;
98 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
100 /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
101 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
105 * Requires inode->i_mapping->i_mmap_rwsem
107 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
108 struct file *file, struct address_space *mapping)
110 if (vma->vm_flags & VM_SHARED)
111 mapping_unmap_writable(mapping);
113 flush_dcache_mmap_lock(mapping);
114 vma_interval_tree_remove(vma, &mapping->i_mmap);
115 flush_dcache_mmap_unlock(mapping);
119 * Unlink a file-based vm structure from its interval tree, to hide
120 * vma from rmap and vmtruncate before freeing its page tables.
122 void unlink_file_vma(struct vm_area_struct *vma)
124 struct file *file = vma->vm_file;
127 struct address_space *mapping = file->f_mapping;
128 i_mmap_lock_write(mapping);
129 __remove_shared_vm_struct(vma, file, mapping);
130 i_mmap_unlock_write(mapping);
135 * Close a vm structure and free it.
137 static void remove_vma(struct vm_area_struct *vma, bool unreachable)
140 if (vma->vm_ops && vma->vm_ops->close)
141 vma->vm_ops->close(vma);
144 mpol_put(vma_policy(vma));
151 static inline struct vm_area_struct *vma_prev_limit(struct vma_iterator *vmi,
154 return mas_prev(&vmi->mas, min);
157 static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
158 unsigned long start, unsigned long end, gfp_t gfp)
160 vmi->mas.index = start;
161 vmi->mas.last = end - 1;
162 mas_store_gfp(&vmi->mas, NULL, gfp);
163 if (unlikely(mas_is_err(&vmi->mas)))
170 * check_brk_limits() - Use platform specific check of range & verify mlock
172 * @addr: The address to check
173 * @len: The size of increase.
175 * Return: 0 on success.
177 static int check_brk_limits(unsigned long addr, unsigned long len)
179 unsigned long mapped_addr;
181 mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
182 if (IS_ERR_VALUE(mapped_addr))
185 return mlock_future_check(current->mm, current->mm->def_flags, len);
187 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
188 unsigned long addr, unsigned long request, unsigned long flags);
189 SYSCALL_DEFINE1(brk, unsigned long, brk)
191 unsigned long newbrk, oldbrk, origbrk;
192 struct mm_struct *mm = current->mm;
193 struct vm_area_struct *brkvma, *next = NULL;
194 unsigned long min_brk;
196 bool downgraded = false;
198 struct vma_iterator vmi;
200 if (mmap_write_lock_killable(mm))
205 #ifdef CONFIG_COMPAT_BRK
207 * CONFIG_COMPAT_BRK can still be overridden by setting
208 * randomize_va_space to 2, which will still cause mm->start_brk
209 * to be arbitrarily shifted
211 if (current->brk_randomized)
212 min_brk = mm->start_brk;
214 min_brk = mm->end_data;
216 min_brk = mm->start_brk;
222 * Check against rlimit here. If this check is done later after the test
223 * of oldbrk with newbrk then it can escape the test and let the data
224 * segment grow beyond its set limit the in case where the limit is
225 * not page aligned -Ram Gupta
227 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
228 mm->end_data, mm->start_data))
231 newbrk = PAGE_ALIGN(brk);
232 oldbrk = PAGE_ALIGN(mm->brk);
233 if (oldbrk == newbrk) {
239 * Always allow shrinking brk.
240 * do_vma_munmap() may downgrade mmap_lock to read.
242 if (brk <= mm->brk) {
245 /* Search one past newbrk */
246 vma_iter_init(&vmi, mm, newbrk);
247 brkvma = vma_find(&vmi, oldbrk);
248 if (!brkvma || brkvma->vm_start >= oldbrk)
249 goto out; /* mapping intersects with an existing non-brk vma. */
251 * mm->brk must be protected by write mmap_lock.
252 * do_vma_munmap() may downgrade the lock, so update it
253 * before calling do_vma_munmap().
256 ret = do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true);
267 if (check_brk_limits(oldbrk, newbrk - oldbrk))
271 * Only check if the next VMA is within the stack_guard_gap of the
274 vma_iter_init(&vmi, mm, oldbrk);
275 next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
276 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
279 brkvma = vma_prev_limit(&vmi, mm->start_brk);
280 /* Ok, looks good - let it rip. */
281 if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
287 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
289 mmap_read_unlock(mm);
291 mmap_write_unlock(mm);
292 userfaultfd_unmap_complete(mm, &uf);
294 mm_populate(oldbrk, newbrk - oldbrk);
298 mmap_write_unlock(mm);
302 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
303 extern void mt_validate(struct maple_tree *mt);
304 extern void mt_dump(const struct maple_tree *mt);
306 /* Validate the maple tree */
307 static void validate_mm_mt(struct mm_struct *mm)
309 struct maple_tree *mt = &mm->mm_mt;
310 struct vm_area_struct *vma_mt;
312 MA_STATE(mas, mt, 0, 0);
314 mt_validate(&mm->mm_mt);
315 mas_for_each(&mas, vma_mt, ULONG_MAX) {
316 if ((vma_mt->vm_start != mas.index) ||
317 (vma_mt->vm_end - 1 != mas.last)) {
318 pr_emerg("issue in %s\n", current->comm);
321 pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
322 mas.index, mas.last);
323 pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
324 vma_mt->vm_start, vma_mt->vm_end);
327 if (vma_mt->vm_end != mas.last + 1) {
328 pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
329 mm, vma_mt->vm_start, vma_mt->vm_end,
330 mas.index, mas.last);
333 VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
334 if (vma_mt->vm_start != mas.index) {
335 pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
336 mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
339 VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
344 static void validate_mm(struct mm_struct *mm)
348 struct vm_area_struct *vma;
349 MA_STATE(mas, &mm->mm_mt, 0, 0);
353 mas_for_each(&mas, vma, ULONG_MAX) {
354 #ifdef CONFIG_DEBUG_VM_RB
355 struct anon_vma *anon_vma = vma->anon_vma;
356 struct anon_vma_chain *avc;
359 anon_vma_lock_read(anon_vma);
360 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
361 anon_vma_interval_tree_verify(avc);
362 anon_vma_unlock_read(anon_vma);
367 if (i != mm->map_count) {
368 pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
371 VM_BUG_ON_MM(bug, mm);
374 #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
375 #define validate_mm_mt(root) do { } while (0)
376 #define validate_mm(mm) do { } while (0)
377 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
380 * vma has some anon_vma assigned, and is already inserted on that
381 * anon_vma's interval trees.
383 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
384 * vma must be removed from the anon_vma's interval trees using
385 * anon_vma_interval_tree_pre_update_vma().
387 * After the update, the vma will be reinserted using
388 * anon_vma_interval_tree_post_update_vma().
390 * The entire update must be protected by exclusive mmap_lock and by
391 * the root anon_vma's mutex.
394 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
396 struct anon_vma_chain *avc;
398 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
399 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
403 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
405 struct anon_vma_chain *avc;
407 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
408 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
411 static unsigned long count_vma_pages_range(struct mm_struct *mm,
412 unsigned long addr, unsigned long end)
414 VMA_ITERATOR(vmi, mm, addr);
415 struct vm_area_struct *vma;
416 unsigned long nr_pages = 0;
418 for_each_vma_range(vmi, vma, end) {
419 unsigned long vm_start = max(addr, vma->vm_start);
420 unsigned long vm_end = min(end, vma->vm_end);
422 nr_pages += PHYS_PFN(vm_end - vm_start);
428 static void __vma_link_file(struct vm_area_struct *vma,
429 struct address_space *mapping)
431 if (vma->vm_flags & VM_SHARED)
432 mapping_allow_writable(mapping);
434 flush_dcache_mmap_lock(mapping);
435 vma_interval_tree_insert(vma, &mapping->i_mmap);
436 flush_dcache_mmap_unlock(mapping);
439 static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
441 VMA_ITERATOR(vmi, mm, 0);
442 struct address_space *mapping = NULL;
444 if (vma_iter_prealloc(&vmi))
448 mapping = vma->vm_file->f_mapping;
449 i_mmap_lock_write(mapping);
452 vma_iter_store(&vmi, vma);
455 __vma_link_file(vma, mapping);
456 i_mmap_unlock_write(mapping);
465 * init_multi_vma_prep() - Initializer for struct vma_prepare
466 * @vp: The vma_prepare struct
467 * @vma: The vma that will be altered once locked
468 * @next: The next vma if it is to be adjusted
469 * @remove: The first vma to be removed
470 * @remove2: The second vma to be removed
472 static inline void init_multi_vma_prep(struct vma_prepare *vp,
473 struct vm_area_struct *vma, struct vm_area_struct *next,
474 struct vm_area_struct *remove, struct vm_area_struct *remove2)
476 memset(vp, 0, sizeof(struct vma_prepare));
478 vp->anon_vma = vma->anon_vma;
480 vp->remove2 = remove2;
482 if (!vp->anon_vma && next)
483 vp->anon_vma = next->anon_vma;
485 vp->file = vma->vm_file;
487 vp->mapping = vma->vm_file->f_mapping;
492 * init_vma_prep() - Initializer wrapper for vma_prepare struct
493 * @vp: The vma_prepare struct
494 * @vma: The vma that will be altered once locked
496 static inline void init_vma_prep(struct vma_prepare *vp,
497 struct vm_area_struct *vma)
499 init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
504 * vma_prepare() - Helper function for handling locking VMAs prior to altering
505 * @vp: The initialized vma_prepare struct
507 static inline void vma_prepare(struct vma_prepare *vp)
509 vma_start_write(vp->vma);
511 vma_start_write(vp->adj_next);
512 /* vp->insert is always a newly created VMA, no need for locking */
514 vma_start_write(vp->remove);
516 vma_start_write(vp->remove2);
519 uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
522 uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
523 vp->adj_next->vm_end);
525 i_mmap_lock_write(vp->mapping);
526 if (vp->insert && vp->insert->vm_file) {
528 * Put into interval tree now, so instantiated pages
529 * are visible to arm/parisc __flush_dcache_page
530 * throughout; but we cannot insert into address
531 * space until vma start or end is updated.
533 __vma_link_file(vp->insert,
534 vp->insert->vm_file->f_mapping);
539 anon_vma_lock_write(vp->anon_vma);
540 anon_vma_interval_tree_pre_update_vma(vp->vma);
542 anon_vma_interval_tree_pre_update_vma(vp->adj_next);
546 flush_dcache_mmap_lock(vp->mapping);
547 vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
549 vma_interval_tree_remove(vp->adj_next,
550 &vp->mapping->i_mmap);
556 * vma_complete- Helper function for handling the unlocking after altering VMAs,
557 * or for inserting a VMA.
559 * @vp: The vma_prepare struct
560 * @vmi: The vma iterator
563 static inline void vma_complete(struct vma_prepare *vp,
564 struct vma_iterator *vmi, struct mm_struct *mm)
568 vma_interval_tree_insert(vp->adj_next,
569 &vp->mapping->i_mmap);
570 vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
571 flush_dcache_mmap_unlock(vp->mapping);
574 if (vp->remove && vp->file) {
575 __remove_shared_vm_struct(vp->remove, vp->file, vp->mapping);
577 __remove_shared_vm_struct(vp->remove2, vp->file,
579 } else if (vp->insert) {
581 * split_vma has split insert from vma, and needs
582 * us to insert it before dropping the locks
583 * (it may either follow vma or precede it).
585 vma_iter_store(vmi, vp->insert);
590 anon_vma_interval_tree_post_update_vma(vp->vma);
592 anon_vma_interval_tree_post_update_vma(vp->adj_next);
593 anon_vma_unlock_write(vp->anon_vma);
597 i_mmap_unlock_write(vp->mapping);
598 uprobe_mmap(vp->vma);
601 uprobe_mmap(vp->adj_next);
606 vma_mark_detached(vp->remove, true);
608 uprobe_munmap(vp->remove, vp->remove->vm_start,
612 if (vp->remove->anon_vma)
613 anon_vma_merge(vp->vma, vp->remove);
615 mpol_put(vma_policy(vp->remove));
617 WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
618 vm_area_free(vp->remove);
621 * In mprotect's case 6 (see comments on vma_merge),
622 * we are removing both mid and next vmas
625 vp->remove = vp->remove2;
630 if (vp->insert && vp->file)
631 uprobe_mmap(vp->insert);
635 * dup_anon_vma() - Helper function to duplicate anon_vma
636 * @dst: The destination VMA
637 * @src: The source VMA
639 * Returns: 0 on success.
641 static inline int dup_anon_vma(struct vm_area_struct *dst,
642 struct vm_area_struct *src)
645 * Easily overlooked: when mprotect shifts the boundary, make sure the
646 * expanding vma has anon_vma set if the shrinking vma had, to cover any
647 * anon pages imported.
649 if (src->anon_vma && !dst->anon_vma) {
650 vma_start_write(dst);
651 dst->anon_vma = src->anon_vma;
652 return anon_vma_clone(dst, src);
659 * vma_expand - Expand an existing VMA
661 * @vmi: The vma iterator
662 * @vma: The vma to expand
663 * @start: The start of the vma
664 * @end: The exclusive end of the vma
665 * @pgoff: The page offset of vma
666 * @next: The current of next vma.
668 * Expand @vma to @start and @end. Can expand off the start and end. Will
669 * expand over @next if it's different from @vma and @end == @next->vm_end.
670 * Checking if the @vma can expand and merge with @next needs to be handled by
673 * Returns: 0 on success
675 int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
676 unsigned long start, unsigned long end, pgoff_t pgoff,
677 struct vm_area_struct *next)
679 bool remove_next = false;
680 struct vma_prepare vp;
682 if (next && (vma != next) && (end == next->vm_end)) {
686 ret = dup_anon_vma(vma, next);
691 init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
692 /* Not merging but overwriting any part of next is not handled. */
693 VM_WARN_ON(next && !vp.remove &&
694 next != vma && end > next->vm_start);
695 /* Only handles expanding */
696 VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);
698 if (vma_iter_prealloc(vmi))
702 vma_adjust_trans_huge(vma, start, end, 0);
703 /* VMA iterator points to previous, so set to start if necessary */
704 if (vma_iter_addr(vmi) != start)
705 vma_iter_set(vmi, start);
707 vma->vm_start = start;
709 vma->vm_pgoff = pgoff;
710 /* Note: mas must be pointing to the expanding VMA */
711 vma_iter_store(vmi, vma);
713 vma_complete(&vp, vmi, vma->vm_mm);
714 validate_mm(vma->vm_mm);
722 * vma_shrink() - Reduce an existing VMAs memory area
723 * @vmi: The vma iterator
724 * @vma: The VMA to modify
725 * @start: The new start
728 * Returns: 0 on success, -ENOMEM otherwise
730 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
731 unsigned long start, unsigned long end, pgoff_t pgoff)
733 struct vma_prepare vp;
735 WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
737 if (vma_iter_prealloc(vmi))
740 init_vma_prep(&vp, vma);
742 vma_adjust_trans_huge(vma, start, end, 0);
744 if (vma->vm_start < start)
745 vma_iter_clear(vmi, vma->vm_start, start);
747 if (vma->vm_end > end)
748 vma_iter_clear(vmi, end, vma->vm_end);
750 vma->vm_start = start;
752 vma->vm_pgoff = pgoff;
753 vma_complete(&vp, vmi, vma->vm_mm);
754 validate_mm(vma->vm_mm);
759 * If the vma has a ->close operation then the driver probably needs to release
760 * per-vma resources, so we don't attempt to merge those if the caller indicates
761 * the current vma may be removed as part of the merge.
763 static inline bool is_mergeable_vma(struct vm_area_struct *vma,
764 struct file *file, unsigned long vm_flags,
765 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
766 struct anon_vma_name *anon_name, bool may_remove_vma)
769 * VM_SOFTDIRTY should not prevent from VMA merging, if we
770 * match the flags but dirty bit -- the caller should mark
771 * merged VMA as dirty. If dirty bit won't be excluded from
772 * comparison, we increase pressure on the memory system forcing
773 * the kernel to generate new VMAs when old one could be
776 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
778 if (vma->vm_file != file)
780 if (may_remove_vma && vma->vm_ops && vma->vm_ops->close)
782 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
784 if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
789 static inline bool is_mergeable_anon_vma(struct anon_vma *anon_vma1,
790 struct anon_vma *anon_vma2, struct vm_area_struct *vma)
793 * The list_is_singular() test is to avoid merging VMA cloned from
794 * parents. This can improve scalability caused by anon_vma lock.
796 if ((!anon_vma1 || !anon_vma2) && (!vma ||
797 list_is_singular(&vma->anon_vma_chain)))
799 return anon_vma1 == anon_vma2;
803 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
804 * in front of (at a lower virtual address and file offset than) the vma.
806 * We cannot merge two vmas if they have differently assigned (non-NULL)
807 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
809 * We don't check here for the merged mmap wrapping around the end of pagecache
810 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
811 * wrap, nor mmaps which cover the final page at index -1UL.
813 * We assume the vma may be removed as part of the merge.
816 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
817 struct anon_vma *anon_vma, struct file *file,
818 pgoff_t vm_pgoff, struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
819 struct anon_vma_name *anon_name)
821 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name, true) &&
822 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
823 if (vma->vm_pgoff == vm_pgoff)
830 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
831 * beyond (at a higher virtual address and file offset than) the vma.
833 * We cannot merge two vmas if they have differently assigned (non-NULL)
834 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
836 * We assume that vma is not removed as part of the merge.
839 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
840 struct anon_vma *anon_vma, struct file *file,
841 pgoff_t vm_pgoff, struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
842 struct anon_vma_name *anon_name)
844 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name, false) &&
845 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
847 vm_pglen = vma_pages(vma);
848 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
855 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
856 * figure out whether that can be merged with its predecessor or its
857 * successor. Or both (it neatly fills a hole).
859 * In most cases - when called for mmap, brk or mremap - [addr,end) is
860 * certain not to be mapped by the time vma_merge is called; but when
861 * called for mprotect, it is certain to be already mapped (either at
862 * an offset within prev, or at the start of next), and the flags of
863 * this area are about to be changed to vm_flags - and the no-change
864 * case has already been eliminated.
866 * The following mprotect cases have to be considered, where **** is
867 * the area passed down from mprotect_fixup, never extending beyond one
868 * vma, PPPP is the previous vma, CCCC is a concurrent vma that starts
869 * at the same address as **** and is of the same or larger span, and
870 * NNNN the next vma after ****:
873 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPCCCCCC
874 * cannot merge might become might become
875 * PPNNNNNNNNNN PPPPPPPPPPCC
876 * mmap, brk or case 4 below case 5 below
879 * PPPP NNNN PPPPCCCCNNNN
880 * might become might become
881 * PPPPPPPPPPPP 1 or PPPPPPPPPPPP 6 or
882 * PPPPPPPPNNNN 2 or PPPPPPPPNNNN 7 or
883 * PPPPNNNNNNNN 3 PPPPNNNNNNNN 8
885 * It is important for case 8 that the vma CCCC overlapping the
886 * region **** is never going to extended over NNNN. Instead NNNN must
887 * be extended in region **** and CCCC must be removed. This way in
888 * all cases where vma_merge succeeds, the moment vma_merge drops the
889 * rmap_locks, the properties of the merged vma will be already
890 * correct for the whole merged range. Some of those properties like
891 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
892 * be correct for the whole merged range immediately after the
893 * rmap_locks are released. Otherwise if NNNN would be removed and
894 * CCCC would be extended over the NNNN range, remove_migration_ptes
895 * or other rmap walkers (if working on addresses beyond the "end"
896 * parameter) may establish ptes with the wrong permissions of CCCC
897 * instead of the right permissions of NNNN.
900 * PPPP is represented by *prev
901 * CCCC is represented by *curr or not represented at all (NULL)
902 * NNNN is represented by *next or not represented at all (NULL)
903 * **** is not represented - it will be merged and the vma containing the
904 * area is returned, or the function will return NULL
906 struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
907 struct vm_area_struct *prev, unsigned long addr,
908 unsigned long end, unsigned long vm_flags,
909 struct anon_vma *anon_vma, struct file *file,
910 pgoff_t pgoff, struct mempolicy *policy,
911 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
912 struct anon_vma_name *anon_name)
914 struct vm_area_struct *curr, *next, *res;
915 struct vm_area_struct *vma, *adjust, *remove, *remove2;
916 struct vma_prepare vp;
919 bool merge_prev = false;
920 bool merge_next = false;
921 bool vma_expanded = false;
922 unsigned long vma_start = addr;
923 unsigned long vma_end = end;
924 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
929 * We later require that vma->vm_flags == vm_flags,
930 * so this tests vma->vm_flags & VM_SPECIAL, too.
932 if (vm_flags & VM_SPECIAL)
935 /* Does the input range span an existing VMA? (cases 5 - 8) */
936 curr = find_vma_intersection(mm, prev ? prev->vm_end : 0, end);
938 if (!curr || /* cases 1 - 4 */
939 end == curr->vm_end) /* cases 6 - 8, adjacent VMA */
940 next = vma_lookup(mm, end);
942 next = NULL; /* case 5 */
945 vma_start = prev->vm_start;
946 vma_pgoff = prev->vm_pgoff;
948 /* Can we merge the predecessor? */
949 if (addr == prev->vm_end && mpol_equal(vma_policy(prev), policy)
950 && can_vma_merge_after(prev, vm_flags, anon_vma, file,
951 pgoff, vm_userfaultfd_ctx, anon_name)) {
957 /* Can we merge the successor? */
958 if (next && mpol_equal(policy, vma_policy(next)) &&
959 can_vma_merge_before(next, vm_flags, anon_vma, file, pgoff+pglen,
960 vm_userfaultfd_ctx, anon_name)) {
964 /* Verify some invariant that must be enforced by the caller. */
965 VM_WARN_ON(prev && addr <= prev->vm_start);
966 VM_WARN_ON(curr && (addr != curr->vm_start || end > curr->vm_end));
967 VM_WARN_ON(addr >= end);
969 if (!merge_prev && !merge_next)
970 return NULL; /* Not mergeable. */
973 remove = remove2 = adjust = NULL;
975 /* Can we merge both the predecessor and the successor? */
976 if (merge_prev && merge_next &&
977 is_mergeable_anon_vma(prev->anon_vma, next->anon_vma, NULL)) {
978 remove = next; /* case 1 */
979 vma_end = next->vm_end;
980 err = dup_anon_vma(prev, next);
981 if (curr) { /* case 6 */
985 err = dup_anon_vma(prev, curr);
987 } else if (merge_prev) { /* case 2 */
989 err = dup_anon_vma(prev, curr);
990 if (end == curr->vm_end) { /* case 7 */
992 } else { /* case 5 */
994 adj_start = (end - curr->vm_start);
997 } else { /* merge_next */
999 if (prev && addr < prev->vm_end) { /* case 4 */
1002 adj_start = -(prev->vm_end - addr);
1003 err = dup_anon_vma(next, prev);
1006 * Note that cases 3 and 8 are the ONLY ones where prev
1007 * is permitted to be (but is not necessarily) NULL.
1009 vma = next; /* case 3 */
1011 vma_end = next->vm_end;
1012 vma_pgoff = next->vm_pgoff - pglen;
1013 if (curr) { /* case 8 */
1014 vma_pgoff = curr->vm_pgoff;
1016 err = dup_anon_vma(next, curr);
1021 /* Error in anon_vma clone. */
1025 if (vma_iter_prealloc(vmi))
1028 init_multi_vma_prep(&vp, vma, adjust, remove, remove2);
1029 VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
1030 vp.anon_vma != adjust->anon_vma);
1033 vma_adjust_trans_huge(vma, vma_start, vma_end, adj_start);
1034 if (vma_start < vma->vm_start || vma_end > vma->vm_end)
1035 vma_expanded = true;
1037 vma->vm_start = vma_start;
1038 vma->vm_end = vma_end;
1039 vma->vm_pgoff = vma_pgoff;
1042 vma_iter_store(vmi, vma);
1045 adjust->vm_start += adj_start;
1046 adjust->vm_pgoff += adj_start >> PAGE_SHIFT;
1047 if (adj_start < 0) {
1048 WARN_ON(vma_expanded);
1049 vma_iter_store(vmi, next);
1053 vma_complete(&vp, vmi, mm);
1056 khugepaged_enter_vma(res, vm_flags);
1062 * Rough compatibility check to quickly see if it's even worth looking
1063 * at sharing an anon_vma.
1065 * They need to have the same vm_file, and the flags can only differ
1066 * in things that mprotect may change.
1068 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1069 * we can merge the two vma's. For example, we refuse to merge a vma if
1070 * there is a vm_ops->close() function, because that indicates that the
1071 * driver is doing some kind of reference counting. But that doesn't
1072 * really matter for the anon_vma sharing case.
1074 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1076 return a->vm_end == b->vm_start &&
1077 mpol_equal(vma_policy(a), vma_policy(b)) &&
1078 a->vm_file == b->vm_file &&
1079 !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1080 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1084 * Do some basic sanity checking to see if we can re-use the anon_vma
1085 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1086 * the same as 'old', the other will be the new one that is trying
1087 * to share the anon_vma.
1089 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1090 * the anon_vma of 'old' is concurrently in the process of being set up
1091 * by another page fault trying to merge _that_. But that's ok: if it
1092 * is being set up, that automatically means that it will be a singleton
1093 * acceptable for merging, so we can do all of this optimistically. But
1094 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1096 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1097 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1098 * is to return an anon_vma that is "complex" due to having gone through
1101 * We also make sure that the two vma's are compatible (adjacent,
1102 * and with the same memory policies). That's all stable, even with just
1103 * a read lock on the mmap_lock.
1105 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1107 if (anon_vma_compatible(a, b)) {
1108 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1110 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1117 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1118 * neighbouring vmas for a suitable anon_vma, before it goes off
1119 * to allocate a new anon_vma. It checks because a repetitive
1120 * sequence of mprotects and faults may otherwise lead to distinct
1121 * anon_vmas being allocated, preventing vma merge in subsequent
1124 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1126 MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1127 struct anon_vma *anon_vma = NULL;
1128 struct vm_area_struct *prev, *next;
1130 /* Try next first. */
1131 next = mas_walk(&mas);
1133 anon_vma = reusable_anon_vma(next, vma, next);
1138 prev = mas_prev(&mas, 0);
1139 VM_BUG_ON_VMA(prev != vma, vma);
1140 prev = mas_prev(&mas, 0);
1141 /* Try prev next. */
1143 anon_vma = reusable_anon_vma(prev, prev, vma);
1146 * We might reach here with anon_vma == NULL if we can't find
1147 * any reusable anon_vma.
1148 * There's no absolute need to look only at touching neighbours:
1149 * we could search further afield for "compatible" anon_vmas.
1150 * But it would probably just be a waste of time searching,
1151 * or lead to too many vmas hanging off the same anon_vma.
1152 * We're trying to allow mprotect remerging later on,
1153 * not trying to minimize memory used for anon_vmas.
1159 * If a hint addr is less than mmap_min_addr change hint to be as
1160 * low as possible but still greater than mmap_min_addr
1162 static inline unsigned long round_hint_to_min(unsigned long hint)
1165 if (((void *)hint != NULL) &&
1166 (hint < mmap_min_addr))
1167 return PAGE_ALIGN(mmap_min_addr);
1171 int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1174 unsigned long locked, lock_limit;
1176 /* mlock MCL_FUTURE? */
1177 if (flags & VM_LOCKED) {
1178 locked = len >> PAGE_SHIFT;
1179 locked += mm->locked_vm;
1180 lock_limit = rlimit(RLIMIT_MEMLOCK);
1181 lock_limit >>= PAGE_SHIFT;
1182 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1188 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1190 if (S_ISREG(inode->i_mode))
1191 return MAX_LFS_FILESIZE;
1193 if (S_ISBLK(inode->i_mode))
1194 return MAX_LFS_FILESIZE;
1196 if (S_ISSOCK(inode->i_mode))
1197 return MAX_LFS_FILESIZE;
1199 /* Special "we do even unsigned file positions" case */
1200 if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1203 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1207 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1208 unsigned long pgoff, unsigned long len)
1210 u64 maxsize = file_mmap_size_max(file, inode);
1212 if (maxsize && len > maxsize)
1215 if (pgoff > maxsize >> PAGE_SHIFT)
1221 * The caller must write-lock current->mm->mmap_lock.
1223 unsigned long do_mmap(struct file *file, unsigned long addr,
1224 unsigned long len, unsigned long prot,
1225 unsigned long flags, unsigned long pgoff,
1226 unsigned long *populate, struct list_head *uf)
1228 struct mm_struct *mm = current->mm;
1229 vm_flags_t vm_flags;
1239 * Does the application expect PROT_READ to imply PROT_EXEC?
1241 * (the exception is when the underlying filesystem is noexec
1242 * mounted, in which case we dont add PROT_EXEC.)
1244 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1245 if (!(file && path_noexec(&file->f_path)))
1248 /* force arch specific MAP_FIXED handling in get_unmapped_area */
1249 if (flags & MAP_FIXED_NOREPLACE)
1252 if (!(flags & MAP_FIXED))
1253 addr = round_hint_to_min(addr);
1255 /* Careful about overflows.. */
1256 len = PAGE_ALIGN(len);
1260 /* offset overflow? */
1261 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1264 /* Too many mappings? */
1265 if (mm->map_count > sysctl_max_map_count)
1268 /* Obtain the address to map to. we verify (or select) it and ensure
1269 * that it represents a valid section of the address space.
1271 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1272 if (IS_ERR_VALUE(addr))
1275 if (flags & MAP_FIXED_NOREPLACE) {
1276 if (find_vma_intersection(mm, addr, addr + len))
1280 if (prot == PROT_EXEC) {
1281 pkey = execute_only_pkey(mm);
1286 /* Do simple checking here so the lower-level routines won't have
1287 * to. we assume access permissions have been handled by the open
1288 * of the memory object, so we don't do any here.
1290 vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1291 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1293 if (flags & MAP_LOCKED)
1294 if (!can_do_mlock())
1297 if (mlock_future_check(mm, vm_flags, len))
1301 struct inode *inode = file_inode(file);
1302 unsigned long flags_mask;
1304 if (!file_mmap_ok(file, inode, pgoff, len))
1307 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1309 switch (flags & MAP_TYPE) {
1312 * Force use of MAP_SHARED_VALIDATE with non-legacy
1313 * flags. E.g. MAP_SYNC is dangerous to use with
1314 * MAP_SHARED as you don't know which consistency model
1315 * you will get. We silently ignore unsupported flags
1316 * with MAP_SHARED to preserve backward compatibility.
1318 flags &= LEGACY_MAP_MASK;
1320 case MAP_SHARED_VALIDATE:
1321 if (flags & ~flags_mask)
1323 if (prot & PROT_WRITE) {
1324 if (!(file->f_mode & FMODE_WRITE))
1326 if (IS_SWAPFILE(file->f_mapping->host))
1331 * Make sure we don't allow writing to an append-only
1334 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1337 vm_flags |= VM_SHARED | VM_MAYSHARE;
1338 if (!(file->f_mode & FMODE_WRITE))
1339 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1342 if (!(file->f_mode & FMODE_READ))
1344 if (path_noexec(&file->f_path)) {
1345 if (vm_flags & VM_EXEC)
1347 vm_flags &= ~VM_MAYEXEC;
1350 if (!file->f_op->mmap)
1352 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1360 switch (flags & MAP_TYPE) {
1362 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1368 vm_flags |= VM_SHARED | VM_MAYSHARE;
1372 * Set pgoff according to addr for anon_vma.
1374 pgoff = addr >> PAGE_SHIFT;
1382 * Set 'VM_NORESERVE' if we should not account for the
1383 * memory use of this mapping.
1385 if (flags & MAP_NORESERVE) {
1386 /* We honor MAP_NORESERVE if allowed to overcommit */
1387 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1388 vm_flags |= VM_NORESERVE;
1390 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1391 if (file && is_file_hugepages(file))
1392 vm_flags |= VM_NORESERVE;
1395 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1396 if (!IS_ERR_VALUE(addr) &&
1397 ((vm_flags & VM_LOCKED) ||
1398 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1403 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1404 unsigned long prot, unsigned long flags,
1405 unsigned long fd, unsigned long pgoff)
1407 struct file *file = NULL;
1408 unsigned long retval;
1410 if (!(flags & MAP_ANONYMOUS)) {
1411 audit_mmap_fd(fd, flags);
1415 if (is_file_hugepages(file)) {
1416 len = ALIGN(len, huge_page_size(hstate_file(file)));
1417 } else if (unlikely(flags & MAP_HUGETLB)) {
1421 } else if (flags & MAP_HUGETLB) {
1424 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1428 len = ALIGN(len, huge_page_size(hs));
1430 * VM_NORESERVE is used because the reservations will be
1431 * taken when vm_ops->mmap() is called
1433 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1435 HUGETLB_ANONHUGE_INODE,
1436 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1438 return PTR_ERR(file);
1441 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1448 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1449 unsigned long, prot, unsigned long, flags,
1450 unsigned long, fd, unsigned long, pgoff)
1452 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1455 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1456 struct mmap_arg_struct {
1460 unsigned long flags;
1462 unsigned long offset;
1465 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1467 struct mmap_arg_struct a;
1469 if (copy_from_user(&a, arg, sizeof(a)))
1471 if (offset_in_page(a.offset))
1474 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1475 a.offset >> PAGE_SHIFT);
1477 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1480 * Some shared mappings will want the pages marked read-only
1481 * to track write events. If so, we'll downgrade vm_page_prot
1482 * to the private version (using protection_map[] without the
1485 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1487 vm_flags_t vm_flags = vma->vm_flags;
1488 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1490 /* If it was private or non-writable, the write bit is already clear */
1491 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1494 /* The backer wishes to know when pages are first written to? */
1495 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1498 /* The open routine did something to the protections that pgprot_modify
1499 * won't preserve? */
1500 if (pgprot_val(vm_page_prot) !=
1501 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1505 * Do we need to track softdirty? hugetlb does not support softdirty
1508 if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1511 /* Do we need write faults for uffd-wp tracking? */
1512 if (userfaultfd_wp(vma))
1515 /* Specialty mapping? */
1516 if (vm_flags & VM_PFNMAP)
1519 /* Can the mapping track the dirty pages? */
1520 return vma->vm_file && vma->vm_file->f_mapping &&
1521 mapping_can_writeback(vma->vm_file->f_mapping);
1525 * We account for memory if it's a private writeable mapping,
1526 * not hugepages and VM_NORESERVE wasn't set.
1528 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1531 * hugetlb has its own accounting separate from the core VM
1532 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1534 if (file && is_file_hugepages(file))
1537 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1541 * unmapped_area() - Find an area between the low_limit and the high_limit with
1542 * the correct alignment and offset, all from @info. Note: current->mm is used
1545 * @info: The unmapped area information including the range [low_limit -
1546 * high_limit), the alignment offset and mask.
1548 * Return: A memory address or -ENOMEM.
1550 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1552 unsigned long length, gap;
1553 unsigned long low_limit, high_limit;
1554 struct vm_area_struct *tmp;
1556 MA_STATE(mas, ¤t->mm->mm_mt, 0, 0);
1558 /* Adjust search length to account for worst case alignment overhead */
1559 length = info->length + info->align_mask;
1560 if (length < info->length)
1563 low_limit = info->low_limit;
1564 if (low_limit < mmap_min_addr)
1565 low_limit = mmap_min_addr;
1566 high_limit = info->high_limit;
1568 if (mas_empty_area(&mas, low_limit, high_limit - 1, length))
1572 gap += (info->align_offset - gap) & info->align_mask;
1573 tmp = mas_next(&mas, ULONG_MAX);
1574 if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
1575 if (vm_start_gap(tmp) < gap + length - 1) {
1576 low_limit = tmp->vm_end;
1581 tmp = mas_prev(&mas, 0);
1582 if (tmp && vm_end_gap(tmp) > gap) {
1583 low_limit = vm_end_gap(tmp);
1593 * unmapped_area_topdown() - Find an area between the low_limit and the
1594 * high_limit with the correct alignment and offset at the highest available
1595 * address, all from @info. Note: current->mm is used for the search.
1597 * @info: The unmapped area information including the range [low_limit -
1598 * high_limit), the alignment offset and mask.
1600 * Return: A memory address or -ENOMEM.
1602 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1604 unsigned long length, gap, gap_end;
1605 unsigned long low_limit, high_limit;
1606 struct vm_area_struct *tmp;
1608 MA_STATE(mas, ¤t->mm->mm_mt, 0, 0);
1609 /* Adjust search length to account for worst case alignment overhead */
1610 length = info->length + info->align_mask;
1611 if (length < info->length)
1614 low_limit = info->low_limit;
1615 if (low_limit < mmap_min_addr)
1616 low_limit = mmap_min_addr;
1617 high_limit = info->high_limit;
1619 if (mas_empty_area_rev(&mas, low_limit, high_limit - 1, length))
1622 gap = mas.last + 1 - info->length;
1623 gap -= (gap - info->align_offset) & info->align_mask;
1625 tmp = mas_next(&mas, ULONG_MAX);
1626 if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
1627 if (vm_start_gap(tmp) <= gap_end) {
1628 high_limit = vm_start_gap(tmp);
1633 tmp = mas_prev(&mas, 0);
1634 if (tmp && vm_end_gap(tmp) > gap) {
1635 high_limit = tmp->vm_start;
1645 * Search for an unmapped address range.
1647 * We are looking for a range that:
1648 * - does not intersect with any VMA;
1649 * - is contained within the [low_limit, high_limit) interval;
1650 * - is at least the desired size.
1651 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1653 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1657 if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1658 addr = unmapped_area_topdown(info);
1660 addr = unmapped_area(info);
1662 trace_vm_unmapped_area(addr, info);
1666 /* Get an address range which is currently unmapped.
1667 * For shmat() with addr=0.
1669 * Ugly calling convention alert:
1670 * Return value with the low bits set means error value,
1672 * if (ret & ~PAGE_MASK)
1675 * This function "knows" that -ENOMEM has the bits set.
1678 generic_get_unmapped_area(struct file *filp, unsigned long addr,
1679 unsigned long len, unsigned long pgoff,
1680 unsigned long flags)
1682 struct mm_struct *mm = current->mm;
1683 struct vm_area_struct *vma, *prev;
1684 struct vm_unmapped_area_info info;
1685 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1687 if (len > mmap_end - mmap_min_addr)
1690 if (flags & MAP_FIXED)
1694 addr = PAGE_ALIGN(addr);
1695 vma = find_vma_prev(mm, addr, &prev);
1696 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1697 (!vma || addr + len <= vm_start_gap(vma)) &&
1698 (!prev || addr >= vm_end_gap(prev)))
1704 info.low_limit = mm->mmap_base;
1705 info.high_limit = mmap_end;
1706 info.align_mask = 0;
1707 info.align_offset = 0;
1708 return vm_unmapped_area(&info);
1711 #ifndef HAVE_ARCH_UNMAPPED_AREA
1713 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1714 unsigned long len, unsigned long pgoff,
1715 unsigned long flags)
1717 return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
1722 * This mmap-allocator allocates new areas top-down from below the
1723 * stack's low limit (the base):
1726 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
1727 unsigned long len, unsigned long pgoff,
1728 unsigned long flags)
1730 struct vm_area_struct *vma, *prev;
1731 struct mm_struct *mm = current->mm;
1732 struct vm_unmapped_area_info info;
1733 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1735 /* requested length too big for entire address space */
1736 if (len > mmap_end - mmap_min_addr)
1739 if (flags & MAP_FIXED)
1742 /* requesting a specific address */
1744 addr = PAGE_ALIGN(addr);
1745 vma = find_vma_prev(mm, addr, &prev);
1746 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1747 (!vma || addr + len <= vm_start_gap(vma)) &&
1748 (!prev || addr >= vm_end_gap(prev)))
1752 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1754 info.low_limit = PAGE_SIZE;
1755 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1756 info.align_mask = 0;
1757 info.align_offset = 0;
1758 addr = vm_unmapped_area(&info);
1761 * A failed mmap() very likely causes application failure,
1762 * so fall back to the bottom-up function here. This scenario
1763 * can happen with large stack limits and large mmap()
1766 if (offset_in_page(addr)) {
1767 VM_BUG_ON(addr != -ENOMEM);
1769 info.low_limit = TASK_UNMAPPED_BASE;
1770 info.high_limit = mmap_end;
1771 addr = vm_unmapped_area(&info);
1777 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1779 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
1780 unsigned long len, unsigned long pgoff,
1781 unsigned long flags)
1783 return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
1788 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1789 unsigned long pgoff, unsigned long flags)
1791 unsigned long (*get_area)(struct file *, unsigned long,
1792 unsigned long, unsigned long, unsigned long);
1794 unsigned long error = arch_mmap_check(addr, len, flags);
1798 /* Careful about overflows.. */
1799 if (len > TASK_SIZE)
1802 get_area = current->mm->get_unmapped_area;
1804 if (file->f_op->get_unmapped_area)
1805 get_area = file->f_op->get_unmapped_area;
1806 } else if (flags & MAP_SHARED) {
1808 * mmap_region() will call shmem_zero_setup() to create a file,
1809 * so use shmem's get_unmapped_area in case it can be huge.
1810 * do_mmap() will clear pgoff, so match alignment.
1813 get_area = shmem_get_unmapped_area;
1816 addr = get_area(file, addr, len, pgoff, flags);
1817 if (IS_ERR_VALUE(addr))
1820 if (addr > TASK_SIZE - len)
1822 if (offset_in_page(addr))
1825 error = security_mmap_addr(addr);
1826 return error ? error : addr;
1829 EXPORT_SYMBOL(get_unmapped_area);
1832 * find_vma_intersection() - Look up the first VMA which intersects the interval
1833 * @mm: The process address space.
1834 * @start_addr: The inclusive start user address.
1835 * @end_addr: The exclusive end user address.
1837 * Returns: The first VMA within the provided range, %NULL otherwise. Assumes
1838 * start_addr < end_addr.
1840 struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1841 unsigned long start_addr,
1842 unsigned long end_addr)
1844 unsigned long index = start_addr;
1846 mmap_assert_locked(mm);
1847 return mt_find(&mm->mm_mt, &index, end_addr - 1);
1849 EXPORT_SYMBOL(find_vma_intersection);
1852 * find_vma() - Find the VMA for a given address, or the next VMA.
1853 * @mm: The mm_struct to check
1854 * @addr: The address
1856 * Returns: The VMA associated with addr, or the next VMA.
1857 * May return %NULL in the case of no VMA at addr or above.
1859 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1861 unsigned long index = addr;
1863 mmap_assert_locked(mm);
1864 return mt_find(&mm->mm_mt, &index, ULONG_MAX);
1866 EXPORT_SYMBOL(find_vma);
1869 * find_vma_prev() - Find the VMA for a given address, or the next vma and
1870 * set %pprev to the previous VMA, if any.
1871 * @mm: The mm_struct to check
1872 * @addr: The address
1873 * @pprev: The pointer to set to the previous VMA
1875 * Note that RCU lock is missing here since the external mmap_lock() is used
1878 * Returns: The VMA associated with @addr, or the next vma.
1879 * May return %NULL in the case of no vma at addr or above.
1881 struct vm_area_struct *
1882 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1883 struct vm_area_struct **pprev)
1885 struct vm_area_struct *vma;
1886 MA_STATE(mas, &mm->mm_mt, addr, addr);
1888 vma = mas_walk(&mas);
1889 *pprev = mas_prev(&mas, 0);
1891 vma = mas_next(&mas, ULONG_MAX);
1896 * Verify that the stack growth is acceptable and
1897 * update accounting. This is shared with both the
1898 * grow-up and grow-down cases.
1900 static int acct_stack_growth(struct vm_area_struct *vma,
1901 unsigned long size, unsigned long grow)
1903 struct mm_struct *mm = vma->vm_mm;
1904 unsigned long new_start;
1906 /* address space limit tests */
1907 if (!may_expand_vm(mm, vma->vm_flags, grow))
1910 /* Stack limit test */
1911 if (size > rlimit(RLIMIT_STACK))
1914 /* mlock limit tests */
1915 if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
1918 /* Check to ensure the stack will not grow into a hugetlb-only region */
1919 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
1921 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
1925 * Overcommit.. This must be the final test, as it will
1926 * update security statistics.
1928 if (security_vm_enough_memory_mm(mm, grow))
1934 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
1936 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
1937 * vma is the last one with address > vma->vm_end. Have to extend vma.
1939 static int expand_upwards(struct vm_area_struct *vma, unsigned long address)
1941 struct mm_struct *mm = vma->vm_mm;
1942 struct vm_area_struct *next;
1943 unsigned long gap_addr;
1945 MA_STATE(mas, &mm->mm_mt, 0, 0);
1947 if (!(vma->vm_flags & VM_GROWSUP))
1950 /* Guard against exceeding limits of the address space. */
1951 address &= PAGE_MASK;
1952 if (address >= (TASK_SIZE & PAGE_MASK))
1954 address += PAGE_SIZE;
1956 /* Enforce stack_guard_gap */
1957 gap_addr = address + stack_guard_gap;
1959 /* Guard against overflow */
1960 if (gap_addr < address || gap_addr > TASK_SIZE)
1961 gap_addr = TASK_SIZE;
1963 next = find_vma_intersection(mm, vma->vm_end, gap_addr);
1964 if (next && vma_is_accessible(next)) {
1965 if (!(next->vm_flags & VM_GROWSUP))
1967 /* Check that both stack segments have the same anon_vma? */
1970 if (mas_preallocate(&mas, GFP_KERNEL))
1973 /* We must make sure the anon_vma is allocated. */
1974 if (unlikely(anon_vma_prepare(vma))) {
1979 /* Lock the VMA before expanding to prevent concurrent page faults */
1980 vma_start_write(vma);
1982 * vma->vm_start/vm_end cannot change under us because the caller
1983 * is required to hold the mmap_lock in read mode. We need the
1984 * anon_vma lock to serialize against concurrent expand_stacks.
1986 anon_vma_lock_write(vma->anon_vma);
1988 /* Somebody else might have raced and expanded it already */
1989 if (address > vma->vm_end) {
1990 unsigned long size, grow;
1992 size = address - vma->vm_start;
1993 grow = (address - vma->vm_end) >> PAGE_SHIFT;
1996 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
1997 error = acct_stack_growth(vma, size, grow);
2000 * We only hold a shared mmap_lock lock here, so
2001 * we need to protect against concurrent vma
2002 * expansions. anon_vma_lock_write() doesn't
2003 * help here, as we don't guarantee that all
2004 * growable vmas in a mm share the same root
2005 * anon vma. So, we reuse mm->page_table_lock
2006 * to guard against concurrent vma expansions.
2008 spin_lock(&mm->page_table_lock);
2009 if (vma->vm_flags & VM_LOCKED)
2010 mm->locked_vm += grow;
2011 vm_stat_account(mm, vma->vm_flags, grow);
2012 anon_vma_interval_tree_pre_update_vma(vma);
2013 vma->vm_end = address;
2014 /* Overwrite old entry in mtree. */
2015 mas_set_range(&mas, vma->vm_start, address - 1);
2016 mas_store_prealloc(&mas, vma);
2017 anon_vma_interval_tree_post_update_vma(vma);
2018 spin_unlock(&mm->page_table_lock);
2020 perf_event_mmap(vma);
2024 anon_vma_unlock_write(vma->anon_vma);
2025 khugepaged_enter_vma(vma, vma->vm_flags);
2029 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2032 * vma is the first one with address < vma->vm_start. Have to extend vma.
2033 * mmap_lock held for writing.
2035 int expand_downwards(struct vm_area_struct *vma, unsigned long address)
2037 struct mm_struct *mm = vma->vm_mm;
2038 MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
2039 struct vm_area_struct *prev;
2042 if (!(vma->vm_flags & VM_GROWSDOWN))
2045 address &= PAGE_MASK;
2046 if (address < mmap_min_addr || address < FIRST_USER_ADDRESS)
2049 /* Enforce stack_guard_gap */
2050 prev = mas_prev(&mas, 0);
2051 /* Check that both stack segments have the same anon_vma? */
2053 if (!(prev->vm_flags & VM_GROWSDOWN) &&
2054 vma_is_accessible(prev) &&
2055 (address - prev->vm_end < stack_guard_gap))
2059 if (mas_preallocate(&mas, GFP_KERNEL))
2062 /* We must make sure the anon_vma is allocated. */
2063 if (unlikely(anon_vma_prepare(vma))) {
2068 /* Lock the VMA before expanding to prevent concurrent page faults */
2069 vma_start_write(vma);
2071 * vma->vm_start/vm_end cannot change under us because the caller
2072 * is required to hold the mmap_lock in read mode. We need the
2073 * anon_vma lock to serialize against concurrent expand_stacks.
2075 anon_vma_lock_write(vma->anon_vma);
2077 /* Somebody else might have raced and expanded it already */
2078 if (address < vma->vm_start) {
2079 unsigned long size, grow;
2081 size = vma->vm_end - address;
2082 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2085 if (grow <= vma->vm_pgoff) {
2086 error = acct_stack_growth(vma, size, grow);
2089 * We only hold a shared mmap_lock lock here, so
2090 * we need to protect against concurrent vma
2091 * expansions. anon_vma_lock_write() doesn't
2092 * help here, as we don't guarantee that all
2093 * growable vmas in a mm share the same root
2094 * anon vma. So, we reuse mm->page_table_lock
2095 * to guard against concurrent vma expansions.
2097 spin_lock(&mm->page_table_lock);
2098 if (vma->vm_flags & VM_LOCKED)
2099 mm->locked_vm += grow;
2100 vm_stat_account(mm, vma->vm_flags, grow);
2101 anon_vma_interval_tree_pre_update_vma(vma);
2102 vma->vm_start = address;
2103 vma->vm_pgoff -= grow;
2104 /* Overwrite old entry in mtree. */
2105 mas_set_range(&mas, address, vma->vm_end - 1);
2106 mas_store_prealloc(&mas, vma);
2107 anon_vma_interval_tree_post_update_vma(vma);
2108 spin_unlock(&mm->page_table_lock);
2110 perf_event_mmap(vma);
2114 anon_vma_unlock_write(vma->anon_vma);
2115 khugepaged_enter_vma(vma, vma->vm_flags);
2120 /* enforced gap between the expanding stack and other mappings. */
2121 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2123 static int __init cmdline_parse_stack_guard_gap(char *p)
2128 val = simple_strtoul(p, &endptr, 10);
2130 stack_guard_gap = val << PAGE_SHIFT;
2134 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2136 #ifdef CONFIG_STACK_GROWSUP
2137 int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
2139 return expand_upwards(vma, address);
2142 struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
2144 struct vm_area_struct *vma, *prev;
2147 vma = find_vma_prev(mm, addr, &prev);
2148 if (vma && (vma->vm_start <= addr))
2152 if (expand_stack_locked(prev, addr))
2154 if (prev->vm_flags & VM_LOCKED)
2155 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2159 int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
2161 if (unlikely(!(vma->vm_flags & VM_GROWSDOWN)))
2163 return expand_downwards(vma, address);
2166 struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
2168 struct vm_area_struct *vma;
2169 unsigned long start;
2172 vma = find_vma(mm, addr);
2175 if (vma->vm_start <= addr)
2177 start = vma->vm_start;
2178 if (expand_stack_locked(vma, addr))
2180 if (vma->vm_flags & VM_LOCKED)
2181 populate_vma_page_range(vma, addr, start, NULL);
2187 * IA64 has some horrid mapping rules: it can expand both up and down,
2188 * but with various special rules.
2190 * We'll get rid of this architecture eventually, so the ugliness is
2194 static inline bool vma_expand_ok(struct vm_area_struct *vma, unsigned long addr)
2196 return REGION_NUMBER(addr) == REGION_NUMBER(vma->vm_start) &&
2197 REGION_OFFSET(addr) < RGN_MAP_LIMIT;
2201 * IA64 stacks grow down, but there's a special register backing store
2202 * that can grow up. Only sequentially, though, so the new address must
2205 static inline int vma_expand_up(struct vm_area_struct *vma, unsigned long addr)
2207 if (!vma_expand_ok(vma, addr))
2209 if (vma->vm_end != (addr & PAGE_MASK))
2211 return expand_upwards(vma, addr);
2214 static inline bool vma_expand_down(struct vm_area_struct *vma, unsigned long addr)
2216 if (!vma_expand_ok(vma, addr))
2218 return expand_downwards(vma, addr);
2221 #elif defined(CONFIG_STACK_GROWSUP)
2223 #define vma_expand_up(vma,addr) expand_upwards(vma, addr)
2224 #define vma_expand_down(vma, addr) (-EFAULT)
2228 #define vma_expand_up(vma,addr) (-EFAULT)
2229 #define vma_expand_down(vma, addr) expand_downwards(vma, addr)
2234 * expand_stack(): legacy interface for page faulting. Don't use unless
2237 * This is called with the mm locked for reading, drops the lock, takes
2238 * the lock for writing, tries to look up a vma again, expands it if
2239 * necessary, and downgrades the lock to reading again.
2241 * If no vma is found or it can't be expanded, it returns NULL and has
2244 struct vm_area_struct *expand_stack(struct mm_struct *mm, unsigned long addr)
2246 struct vm_area_struct *vma, *prev;
2248 mmap_read_unlock(mm);
2249 if (mmap_write_lock_killable(mm))
2252 vma = find_vma_prev(mm, addr, &prev);
2253 if (vma && vma->vm_start <= addr)
2256 if (prev && !vma_expand_up(prev, addr)) {
2261 if (vma && !vma_expand_down(vma, addr))
2264 mmap_write_unlock(mm);
2268 mmap_write_downgrade(mm);
2273 * Ok - we have the memory areas we should free on a maple tree so release them,
2274 * and do the vma updates.
2276 * Called with the mm semaphore held.
2278 static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
2280 unsigned long nr_accounted = 0;
2281 struct vm_area_struct *vma;
2283 /* Update high watermark before we lower total_vm */
2284 update_hiwater_vm(mm);
2285 mas_for_each(mas, vma, ULONG_MAX) {
2286 long nrpages = vma_pages(vma);
2288 if (vma->vm_flags & VM_ACCOUNT)
2289 nr_accounted += nrpages;
2290 vm_stat_account(mm, vma->vm_flags, -nrpages);
2291 remove_vma(vma, false);
2293 vm_unacct_memory(nr_accounted);
2298 * Get rid of page table information in the indicated region.
2300 * Called with the mm semaphore held.
2302 static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
2303 struct vm_area_struct *vma, struct vm_area_struct *prev,
2304 struct vm_area_struct *next,
2305 unsigned long start, unsigned long end, bool mm_wr_locked)
2307 struct mmu_gather tlb;
2310 tlb_gather_mmu(&tlb, mm);
2311 update_hiwater_rss(mm);
2312 unmap_vmas(&tlb, mt, vma, start, end, mm_wr_locked);
2313 free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2314 next ? next->vm_start : USER_PGTABLES_CEILING,
2316 tlb_finish_mmu(&tlb);
2320 * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
2321 * has already been checked or doesn't make sense to fail.
2322 * VMA Iterator will point to the end VMA.
2324 int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2325 unsigned long addr, int new_below)
2327 struct vma_prepare vp;
2328 struct vm_area_struct *new;
2331 validate_mm_mt(vma->vm_mm);
2333 WARN_ON(vma->vm_start >= addr);
2334 WARN_ON(vma->vm_end <= addr);
2336 if (vma->vm_ops && vma->vm_ops->may_split) {
2337 err = vma->vm_ops->may_split(vma, addr);
2342 new = vm_area_dup(vma);
2347 if (vma_iter_prealloc(vmi))
2353 new->vm_start = addr;
2354 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2357 err = vma_dup_policy(vma, new);
2361 err = anon_vma_clone(new, vma);
2366 get_file(new->vm_file);
2368 if (new->vm_ops && new->vm_ops->open)
2369 new->vm_ops->open(new);
2371 init_vma_prep(&vp, vma);
2374 vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
2377 vma->vm_start = addr;
2378 vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
2383 /* vma_complete stores the new vma */
2384 vma_complete(&vp, vmi, vma->vm_mm);
2389 validate_mm_mt(vma->vm_mm);
2393 mpol_put(vma_policy(new));
2398 validate_mm_mt(vma->vm_mm);
2403 * Split a vma into two pieces at address 'addr', a new vma is allocated
2404 * either for the first part or the tail.
2406 int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2407 unsigned long addr, int new_below)
2409 if (vma->vm_mm->map_count >= sysctl_max_map_count)
2412 return __split_vma(vmi, vma, addr, new_below);
2416 * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2417 * @vmi: The vma iterator
2418 * @vma: The starting vm_area_struct
2419 * @mm: The mm_struct
2420 * @start: The aligned start address to munmap.
2421 * @end: The aligned end address to munmap.
2422 * @uf: The userfaultfd list_head
2423 * @downgrade: Set to true to attempt a write downgrade of the mmap_lock
2425 * If @downgrade is true, check return code for potential release of the lock.
2428 do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2429 struct mm_struct *mm, unsigned long start,
2430 unsigned long end, struct list_head *uf, bool downgrade)
2432 struct vm_area_struct *prev, *next = NULL;
2433 struct maple_tree mt_detach;
2435 int error = -ENOMEM;
2436 unsigned long locked_vm = 0;
2437 MA_STATE(mas_detach, &mt_detach, 0, 0);
2438 mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
2439 mt_set_external_lock(&mt_detach, &mm->mmap_lock);
2442 * If we need to split any vma, do it now to save pain later.
2444 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2445 * unmapped vm_area_struct will remain in use: so lower split_vma
2446 * places tmp vma above, and higher split_vma places tmp vma below.
2449 /* Does it split the first one? */
2450 if (start > vma->vm_start) {
2453 * Make sure that map_count on return from munmap() will
2454 * not exceed its limit; but let map_count go just above
2455 * its limit temporarily, to help free resources as expected.
2457 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2458 goto map_count_exceeded;
2460 error = __split_vma(vmi, vma, start, 0);
2462 goto start_split_failed;
2464 vma = vma_iter_load(vmi);
2467 prev = vma_prev(vmi);
2468 if (unlikely((!prev)))
2469 vma_iter_set(vmi, start);
2472 * Detach a range of VMAs from the mm. Using next as a temp variable as
2473 * it is always overwritten.
2475 for_each_vma_range(*vmi, next, end) {
2476 /* Does it split the end? */
2477 if (next->vm_end > end) {
2478 error = __split_vma(vmi, next, end, 0);
2480 goto end_split_failed;
2482 vma_start_write(next);
2483 mas_set_range(&mas_detach, next->vm_start, next->vm_end - 1);
2484 error = mas_store_gfp(&mas_detach, next, GFP_KERNEL);
2486 goto munmap_gather_failed;
2487 vma_mark_detached(next, true);
2488 if (next->vm_flags & VM_LOCKED)
2489 locked_vm += vma_pages(next);
2492 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2493 BUG_ON(next->vm_start < start);
2494 BUG_ON(next->vm_start > end);
2498 next = vma_next(vmi);
2501 * If userfaultfd_unmap_prep returns an error the vmas
2502 * will remain split, but userland will get a
2503 * highly unexpected error anyway. This is no
2504 * different than the case where the first of the two
2505 * __split_vma fails, but we don't undo the first
2506 * split, despite we could. This is unlikely enough
2507 * failure that it's not worth optimizing it for.
2509 error = userfaultfd_unmap_prep(mm, start, end, uf);
2512 goto userfaultfd_error;
2515 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2516 /* Make sure no VMAs are about to be lost. */
2518 MA_STATE(test, &mt_detach, start, end - 1);
2519 struct vm_area_struct *vma_mas, *vma_test;
2522 vma_iter_set(vmi, start);
2524 vma_test = mas_find(&test, end - 1);
2525 for_each_vma_range(*vmi, vma_mas, end) {
2526 BUG_ON(vma_mas != vma_test);
2528 vma_test = mas_next(&test, end - 1);
2531 BUG_ON(count != test_count);
2534 vma_iter_set(vmi, start);
2535 error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
2537 goto clear_tree_failed;
2539 /* Point of no return */
2540 mm->locked_vm -= locked_vm;
2541 mm->map_count -= count;
2543 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2544 * VM_GROWSUP VMA. Such VMAs can change their size under
2545 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2548 if (next && (next->vm_flags & VM_GROWSDOWN))
2550 else if (prev && (prev->vm_flags & VM_GROWSUP))
2553 mmap_write_downgrade(mm);
2557 * We can free page tables without write-locking mmap_lock because VMAs
2558 * were isolated before we downgraded mmap_lock.
2560 unmap_region(mm, &mt_detach, vma, prev, next, start, end, !downgrade);
2561 /* Statistics and freeing VMAs */
2562 mas_set(&mas_detach, start);
2563 remove_mt(mm, &mas_detach);
2564 __mt_destroy(&mt_detach);
2568 return downgrade ? 1 : 0;
2572 munmap_gather_failed:
2574 mas_set(&mas_detach, 0);
2575 mas_for_each(&mas_detach, next, end)
2576 vma_mark_detached(next, false);
2578 __mt_destroy(&mt_detach);
2585 * do_vmi_munmap() - munmap a given range.
2586 * @vmi: The vma iterator
2587 * @mm: The mm_struct
2588 * @start: The start address to munmap
2589 * @len: The length of the range to munmap
2590 * @uf: The userfaultfd list_head
2591 * @downgrade: set to true if the user wants to attempt to write_downgrade the
2594 * This function takes a @mas that is either pointing to the previous VMA or set
2595 * to MA_START and sets it up to remove the mapping(s). The @len will be
2596 * aligned and any arch_unmap work will be preformed.
2598 * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
2600 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
2601 unsigned long start, size_t len, struct list_head *uf,
2605 struct vm_area_struct *vma;
2607 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2610 end = start + PAGE_ALIGN(len);
2614 /* arch_unmap() might do unmaps itself. */
2615 arch_unmap(mm, start, end);
2617 /* Find the first overlapping VMA */
2618 vma = vma_find(vmi, end);
2622 return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2625 /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
2626 * @mm: The mm_struct
2627 * @start: The start address to munmap
2628 * @len: The length to be munmapped.
2629 * @uf: The userfaultfd list_head
2631 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2632 struct list_head *uf)
2634 VMA_ITERATOR(vmi, mm, start);
2636 return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2639 unsigned long mmap_region(struct file *file, unsigned long addr,
2640 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2641 struct list_head *uf)
2643 struct mm_struct *mm = current->mm;
2644 struct vm_area_struct *vma = NULL;
2645 struct vm_area_struct *next, *prev, *merge;
2646 pgoff_t pglen = len >> PAGE_SHIFT;
2647 unsigned long charged = 0;
2648 unsigned long end = addr + len;
2649 unsigned long merge_start = addr, merge_end = end;
2652 VMA_ITERATOR(vmi, mm, addr);
2654 /* Check against address space limit. */
2655 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2656 unsigned long nr_pages;
2659 * MAP_FIXED may remove pages of mappings that intersects with
2660 * requested mapping. Account for the pages it would unmap.
2662 nr_pages = count_vma_pages_range(mm, addr, end);
2664 if (!may_expand_vm(mm, vm_flags,
2665 (len >> PAGE_SHIFT) - nr_pages))
2669 /* Unmap any existing mapping in the area */
2670 if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2674 * Private writable mapping: check memory availability
2676 if (accountable_mapping(file, vm_flags)) {
2677 charged = len >> PAGE_SHIFT;
2678 if (security_vm_enough_memory_mm(mm, charged))
2680 vm_flags |= VM_ACCOUNT;
2683 next = vma_next(&vmi);
2684 prev = vma_prev(&vmi);
2685 if (vm_flags & VM_SPECIAL)
2688 /* Attempt to expand an old mapping */
2690 if (next && next->vm_start == end && !vma_policy(next) &&
2691 can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2692 NULL_VM_UFFD_CTX, NULL)) {
2693 merge_end = next->vm_end;
2695 vm_pgoff = next->vm_pgoff - pglen;
2699 if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2700 (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2701 pgoff, vma->vm_userfaultfd_ctx, NULL) :
2702 can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2703 NULL_VM_UFFD_CTX, NULL))) {
2704 merge_start = prev->vm_start;
2706 vm_pgoff = prev->vm_pgoff;
2710 /* Actually expand, if possible */
2712 !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2713 khugepaged_enter_vma(vma, vm_flags);
2719 * Determine the object being mapped and call the appropriate
2720 * specific mapper. the address has already been validated, but
2721 * not unmapped, but the maps are removed from the list.
2723 vma = vm_area_alloc(mm);
2729 vma_iter_set(&vmi, addr);
2730 vma->vm_start = addr;
2732 vm_flags_init(vma, vm_flags);
2733 vma->vm_page_prot = vm_get_page_prot(vm_flags);
2734 vma->vm_pgoff = pgoff;
2737 if (vm_flags & VM_SHARED) {
2738 error = mapping_map_writable(file->f_mapping);
2743 vma->vm_file = get_file(file);
2744 error = call_mmap(file, vma);
2746 goto unmap_and_free_vma;
2749 * Expansion is handled above, merging is handled below.
2750 * Drivers should not alter the address of the VMA.
2753 if (WARN_ON((addr != vma->vm_start)))
2754 goto close_and_free_vma;
2756 vma_iter_set(&vmi, addr);
2758 * If vm_flags changed after call_mmap(), we should try merge
2759 * vma again as we may succeed this time.
2761 if (unlikely(vm_flags != vma->vm_flags && prev)) {
2762 merge = vma_merge(&vmi, mm, prev, vma->vm_start,
2763 vma->vm_end, vma->vm_flags, NULL,
2764 vma->vm_file, vma->vm_pgoff, NULL,
2765 NULL_VM_UFFD_CTX, NULL);
2768 * ->mmap() can change vma->vm_file and fput
2769 * the original file. So fput the vma->vm_file
2770 * here or we would add an extra fput for file
2771 * and cause general protection fault
2777 /* Update vm_flags to pick up the change. */
2778 vm_flags = vma->vm_flags;
2779 goto unmap_writable;
2783 vm_flags = vma->vm_flags;
2784 } else if (vm_flags & VM_SHARED) {
2785 error = shmem_zero_setup(vma);
2789 vma_set_anonymous(vma);
2792 if (map_deny_write_exec(vma, vma->vm_flags)) {
2794 goto close_and_free_vma;
2797 /* Allow architectures to sanity-check the vm_flags */
2799 if (!arch_validate_flags(vma->vm_flags))
2800 goto close_and_free_vma;
2803 if (vma_iter_prealloc(&vmi))
2804 goto close_and_free_vma;
2806 /* Lock the VMA since it is modified after insertion into VMA tree */
2807 vma_start_write(vma);
2809 i_mmap_lock_write(vma->vm_file->f_mapping);
2811 vma_iter_store(&vmi, vma);
2814 if (vma->vm_flags & VM_SHARED)
2815 mapping_allow_writable(vma->vm_file->f_mapping);
2817 flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2818 vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2819 flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2820 i_mmap_unlock_write(vma->vm_file->f_mapping);
2824 * vma_merge() calls khugepaged_enter_vma() either, the below
2825 * call covers the non-merge case.
2827 khugepaged_enter_vma(vma, vma->vm_flags);
2829 /* Once vma denies write, undo our temporary denial count */
2831 if (file && vm_flags & VM_SHARED)
2832 mapping_unmap_writable(file->f_mapping);
2833 file = vma->vm_file;
2836 perf_event_mmap(vma);
2838 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2839 if (vm_flags & VM_LOCKED) {
2840 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2841 is_vm_hugetlb_page(vma) ||
2842 vma == get_gate_vma(current->mm))
2843 vm_flags_clear(vma, VM_LOCKED_MASK);
2845 mm->locked_vm += (len >> PAGE_SHIFT);
2852 * New (or expanded) vma always get soft dirty status.
2853 * Otherwise user-space soft-dirty page tracker won't
2854 * be able to distinguish situation when vma area unmapped,
2855 * then new mapped in-place (which must be aimed as
2856 * a completely new data area).
2858 vm_flags_set(vma, VM_SOFTDIRTY);
2860 vma_set_page_prot(vma);
2866 if (file && vma->vm_ops && vma->vm_ops->close)
2867 vma->vm_ops->close(vma);
2869 if (file || vma->vm_file) {
2872 vma->vm_file = NULL;
2874 /* Undo any partial mapping done by a device driver. */
2875 unmap_region(mm, &mm->mm_mt, vma, prev, next, vma->vm_start,
2878 if (file && (vm_flags & VM_SHARED))
2879 mapping_unmap_writable(file->f_mapping);
2884 vm_unacct_memory(charged);
2889 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2892 struct mm_struct *mm = current->mm;
2894 VMA_ITERATOR(vmi, mm, start);
2896 if (mmap_write_lock_killable(mm))
2899 ret = do_vmi_munmap(&vmi, mm, start, len, &uf, downgrade);
2901 * Returning 1 indicates mmap_lock is downgraded.
2902 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2903 * it to 0 before return.
2906 mmap_read_unlock(mm);
2909 mmap_write_unlock(mm);
2911 userfaultfd_unmap_complete(mm, &uf);
2915 int vm_munmap(unsigned long start, size_t len)
2917 return __vm_munmap(start, len, false);
2919 EXPORT_SYMBOL(vm_munmap);
2921 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2923 addr = untagged_addr(addr);
2924 return __vm_munmap(addr, len, true);
2929 * Emulation of deprecated remap_file_pages() syscall.
2931 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2932 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2935 struct mm_struct *mm = current->mm;
2936 struct vm_area_struct *vma;
2937 unsigned long populate = 0;
2938 unsigned long ret = -EINVAL;
2941 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2942 current->comm, current->pid);
2946 start = start & PAGE_MASK;
2947 size = size & PAGE_MASK;
2949 if (start + size <= start)
2952 /* Does pgoff wrap? */
2953 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2956 if (mmap_write_lock_killable(mm))
2959 vma = vma_lookup(mm, start);
2961 if (!vma || !(vma->vm_flags & VM_SHARED))
2964 if (start + size > vma->vm_end) {
2965 VMA_ITERATOR(vmi, mm, vma->vm_end);
2966 struct vm_area_struct *next, *prev = vma;
2968 for_each_vma_range(vmi, next, start + size) {
2969 /* hole between vmas ? */
2970 if (next->vm_start != prev->vm_end)
2973 if (next->vm_file != vma->vm_file)
2976 if (next->vm_flags != vma->vm_flags)
2979 if (start + size <= next->vm_end)
2989 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2990 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2991 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2993 flags &= MAP_NONBLOCK;
2994 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2995 if (vma->vm_flags & VM_LOCKED)
2996 flags |= MAP_LOCKED;
2998 file = get_file(vma->vm_file);
2999 ret = do_mmap(vma->vm_file, start, size,
3000 prot, flags, pgoff, &populate, NULL);
3003 mmap_write_unlock(mm);
3005 mm_populate(ret, populate);
3006 if (!IS_ERR_VALUE(ret))
3012 * do_vma_munmap() - Unmap a full or partial vma.
3013 * @vmi: The vma iterator pointing at the vma
3014 * @vma: The first vma to be munmapped
3015 * @start: the start of the address to unmap
3016 * @end: The end of the address to unmap
3017 * @uf: The userfaultfd list_head
3018 * @downgrade: Attempt to downgrade or not
3020 * Returns: 0 on success and not downgraded, 1 on success and downgraded.
3021 * unmaps a VMA mapping when the vma iterator is already in position.
3022 * Does not handle alignment.
3024 int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
3025 unsigned long start, unsigned long end,
3026 struct list_head *uf, bool downgrade)
3028 struct mm_struct *mm = vma->vm_mm;
3031 arch_unmap(mm, start, end);
3032 ret = do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
3038 * do_brk_flags() - Increase the brk vma if the flags match.
3039 * @vmi: The vma iterator
3040 * @addr: The start address
3041 * @len: The length of the increase
3043 * @flags: The VMA Flags
3045 * Extend the brk VMA from addr to addr + len. If the VMA is NULL or the flags
3046 * do not match then create a new anonymous VMA. Eventually we may be able to
3047 * do some brk-specific accounting here.
3049 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
3050 unsigned long addr, unsigned long len, unsigned long flags)
3052 struct mm_struct *mm = current->mm;
3053 struct vma_prepare vp;
3057 * Check against address space limits by the changed size
3058 * Note: This happens *after* clearing old mappings in some code paths.
3060 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3061 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3064 if (mm->map_count > sysctl_max_map_count)
3067 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3071 * Expand the existing vma if possible; Note that singular lists do not
3072 * occur after forking, so the expand will only happen on new VMAs.
3074 if (vma && vma->vm_end == addr && !vma_policy(vma) &&
3075 can_vma_merge_after(vma, flags, NULL, NULL,
3076 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
3077 if (vma_iter_prealloc(vmi))
3080 init_vma_prep(&vp, vma);
3082 vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
3083 vma->vm_end = addr + len;
3084 vm_flags_set(vma, VM_SOFTDIRTY);
3085 vma_iter_store(vmi, vma);
3087 vma_complete(&vp, vmi, mm);
3088 khugepaged_enter_vma(vma, flags);
3092 /* create a vma struct for an anonymous mapping */
3093 vma = vm_area_alloc(mm);
3097 vma_set_anonymous(vma);
3098 vma->vm_start = addr;
3099 vma->vm_end = addr + len;
3100 vma->vm_pgoff = addr >> PAGE_SHIFT;
3101 vm_flags_init(vma, flags);
3102 vma->vm_page_prot = vm_get_page_prot(flags);
3103 if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
3104 goto mas_store_fail;
3109 perf_event_mmap(vma);
3110 mm->total_vm += len >> PAGE_SHIFT;
3111 mm->data_vm += len >> PAGE_SHIFT;
3112 if (flags & VM_LOCKED)
3113 mm->locked_vm += (len >> PAGE_SHIFT);
3114 vm_flags_set(vma, VM_SOFTDIRTY);
3121 vm_unacct_memory(len >> PAGE_SHIFT);
3125 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3127 struct mm_struct *mm = current->mm;
3128 struct vm_area_struct *vma = NULL;
3133 VMA_ITERATOR(vmi, mm, addr);
3135 len = PAGE_ALIGN(request);
3141 if (mmap_write_lock_killable(mm))
3144 /* Until we need other flags, refuse anything except VM_EXEC. */
3145 if ((flags & (~VM_EXEC)) != 0)
3148 ret = check_brk_limits(addr, len);
3152 ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
3156 vma = vma_prev(&vmi);
3157 ret = do_brk_flags(&vmi, vma, addr, len, flags);
3158 populate = ((mm->def_flags & VM_LOCKED) != 0);
3159 mmap_write_unlock(mm);
3160 userfaultfd_unmap_complete(mm, &uf);
3161 if (populate && !ret)
3162 mm_populate(addr, len);
3167 mmap_write_unlock(mm);
3170 EXPORT_SYMBOL(vm_brk_flags);
3172 int vm_brk(unsigned long addr, unsigned long len)
3174 return vm_brk_flags(addr, len, 0);
3176 EXPORT_SYMBOL(vm_brk);
3178 /* Release all mmaps. */
3179 void exit_mmap(struct mm_struct *mm)
3181 struct mmu_gather tlb;
3182 struct vm_area_struct *vma;
3183 unsigned long nr_accounted = 0;
3184 MA_STATE(mas, &mm->mm_mt, 0, 0);
3187 /* mm's last user has gone, and its about to be pulled down */
3188 mmu_notifier_release(mm);
3193 vma = mas_find(&mas, ULONG_MAX);
3195 /* Can happen if dup_mmap() received an OOM */
3196 mmap_read_unlock(mm);
3202 tlb_gather_mmu_fullmm(&tlb, mm);
3203 /* update_hiwater_rss(mm) here? but nobody should be looking */
3204 /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3205 unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX, false);
3206 mmap_read_unlock(mm);
3209 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3210 * because the memory has been already freed.
3212 set_bit(MMF_OOM_SKIP, &mm->flags);
3213 mmap_write_lock(mm);
3214 mt_clear_in_rcu(&mm->mm_mt);
3215 free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
3216 USER_PGTABLES_CEILING, true);
3217 tlb_finish_mmu(&tlb);
3220 * Walk the list again, actually closing and freeing it, with preemption
3221 * enabled, without holding any MM locks besides the unreachable
3225 if (vma->vm_flags & VM_ACCOUNT)
3226 nr_accounted += vma_pages(vma);
3227 remove_vma(vma, true);
3230 } while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3232 BUG_ON(count != mm->map_count);
3234 trace_exit_mmap(mm);
3235 __mt_destroy(&mm->mm_mt);
3236 mmap_write_unlock(mm);
3237 vm_unacct_memory(nr_accounted);
3240 /* Insert vm structure into process list sorted by address
3241 * and into the inode's i_mmap tree. If vm_file is non-NULL
3242 * then i_mmap_rwsem is taken here.
3244 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3246 unsigned long charged = vma_pages(vma);
3249 if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3252 if ((vma->vm_flags & VM_ACCOUNT) &&
3253 security_vm_enough_memory_mm(mm, charged))
3257 * The vm_pgoff of a purely anonymous vma should be irrelevant
3258 * until its first write fault, when page's anon_vma and index
3259 * are set. But now set the vm_pgoff it will almost certainly
3260 * end up with (unless mremap moves it elsewhere before that
3261 * first wfault), so /proc/pid/maps tells a consistent story.
3263 * By setting it to reflect the virtual start address of the
3264 * vma, merges and splits can happen in a seamless way, just
3265 * using the existing file pgoff checks and manipulations.
3266 * Similarly in do_mmap and in do_brk_flags.
3268 if (vma_is_anonymous(vma)) {
3269 BUG_ON(vma->anon_vma);
3270 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3273 if (vma_link(mm, vma)) {
3274 vm_unacct_memory(charged);
3282 * Copy the vma structure to a new location in the same mm,
3283 * prior to moving page table entries, to effect an mremap move.
3285 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3286 unsigned long addr, unsigned long len, pgoff_t pgoff,
3287 bool *need_rmap_locks)
3289 struct vm_area_struct *vma = *vmap;
3290 unsigned long vma_start = vma->vm_start;
3291 struct mm_struct *mm = vma->vm_mm;
3292 struct vm_area_struct *new_vma, *prev;
3293 bool faulted_in_anon_vma = true;
3294 VMA_ITERATOR(vmi, mm, addr);
3298 * If anonymous vma has not yet been faulted, update new pgoff
3299 * to match new location, to increase its chance of merging.
3301 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3302 pgoff = addr >> PAGE_SHIFT;
3303 faulted_in_anon_vma = false;
3306 new_vma = find_vma_prev(mm, addr, &prev);
3307 if (new_vma && new_vma->vm_start < addr + len)
3308 return NULL; /* should never get here */
3310 new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
3311 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3312 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3315 * Source vma may have been merged into new_vma
3317 if (unlikely(vma_start >= new_vma->vm_start &&
3318 vma_start < new_vma->vm_end)) {
3320 * The only way we can get a vma_merge with
3321 * self during an mremap is if the vma hasn't
3322 * been faulted in yet and we were allowed to
3323 * reset the dst vma->vm_pgoff to the
3324 * destination address of the mremap to allow
3325 * the merge to happen. mremap must change the
3326 * vm_pgoff linearity between src and dst vmas
3327 * (in turn preventing a vma_merge) to be
3328 * safe. It is only safe to keep the vm_pgoff
3329 * linear if there are no pages mapped yet.
3331 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3332 *vmap = vma = new_vma;
3334 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3336 new_vma = vm_area_dup(vma);
3339 new_vma->vm_start = addr;
3340 new_vma->vm_end = addr + len;
3341 new_vma->vm_pgoff = pgoff;
3342 if (vma_dup_policy(vma, new_vma))
3344 if (anon_vma_clone(new_vma, vma))
3345 goto out_free_mempol;
3346 if (new_vma->vm_file)
3347 get_file(new_vma->vm_file);
3348 if (new_vma->vm_ops && new_vma->vm_ops->open)
3349 new_vma->vm_ops->open(new_vma);
3350 vma_start_write(new_vma);
3351 if (vma_link(mm, new_vma))
3353 *need_rmap_locks = false;
3359 if (new_vma->vm_ops && new_vma->vm_ops->close)
3360 new_vma->vm_ops->close(new_vma);
3362 if (new_vma->vm_file)
3363 fput(new_vma->vm_file);
3365 unlink_anon_vmas(new_vma);
3367 mpol_put(vma_policy(new_vma));
3369 vm_area_free(new_vma);
3376 * Return true if the calling process may expand its vm space by the passed
3379 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3381 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3384 if (is_data_mapping(flags) &&
3385 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3386 /* Workaround for Valgrind */
3387 if (rlimit(RLIMIT_DATA) == 0 &&
3388 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3391 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3392 current->comm, current->pid,
3393 (mm->data_vm + npages) << PAGE_SHIFT,
3394 rlimit(RLIMIT_DATA),
3395 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3397 if (!ignore_rlimit_data)
3404 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3406 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3408 if (is_exec_mapping(flags))
3409 mm->exec_vm += npages;
3410 else if (is_stack_mapping(flags))
3411 mm->stack_vm += npages;
3412 else if (is_data_mapping(flags))
3413 mm->data_vm += npages;
3416 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3419 * Having a close hook prevents vma merging regardless of flags.
3421 static void special_mapping_close(struct vm_area_struct *vma)
3425 static const char *special_mapping_name(struct vm_area_struct *vma)
3427 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3430 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3432 struct vm_special_mapping *sm = new_vma->vm_private_data;
3434 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3438 return sm->mremap(sm, new_vma);
3443 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3446 * Forbid splitting special mappings - kernel has expectations over
3447 * the number of pages in mapping. Together with VM_DONTEXPAND
3448 * the size of vma should stay the same over the special mapping's
3454 static const struct vm_operations_struct special_mapping_vmops = {
3455 .close = special_mapping_close,
3456 .fault = special_mapping_fault,
3457 .mremap = special_mapping_mremap,
3458 .name = special_mapping_name,
3459 /* vDSO code relies that VVAR can't be accessed remotely */
3461 .may_split = special_mapping_split,
3464 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3465 .close = special_mapping_close,
3466 .fault = special_mapping_fault,
3469 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3471 struct vm_area_struct *vma = vmf->vma;
3473 struct page **pages;
3475 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3476 pages = vma->vm_private_data;
3478 struct vm_special_mapping *sm = vma->vm_private_data;
3481 return sm->fault(sm, vmf->vma, vmf);
3486 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3490 struct page *page = *pages;
3496 return VM_FAULT_SIGBUS;
3499 static struct vm_area_struct *__install_special_mapping(
3500 struct mm_struct *mm,
3501 unsigned long addr, unsigned long len,
3502 unsigned long vm_flags, void *priv,
3503 const struct vm_operations_struct *ops)
3506 struct vm_area_struct *vma;
3509 vma = vm_area_alloc(mm);
3510 if (unlikely(vma == NULL))
3511 return ERR_PTR(-ENOMEM);
3513 vma->vm_start = addr;
3514 vma->vm_end = addr + len;
3516 vm_flags_init(vma, (vm_flags | mm->def_flags |
3517 VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
3518 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3521 vma->vm_private_data = priv;
3523 ret = insert_vm_struct(mm, vma);
3527 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3529 perf_event_mmap(vma);
3537 return ERR_PTR(ret);
3540 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3541 const struct vm_special_mapping *sm)
3543 return vma->vm_private_data == sm &&
3544 (vma->vm_ops == &special_mapping_vmops ||
3545 vma->vm_ops == &legacy_special_mapping_vmops);
3549 * Called with mm->mmap_lock held for writing.
3550 * Insert a new vma covering the given region, with the given flags.
3551 * Its pages are supplied by the given array of struct page *.
3552 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3553 * The region past the last page supplied will always produce SIGBUS.
3554 * The array pointer and the pages it points to are assumed to stay alive
3555 * for as long as this mapping might exist.
3557 struct vm_area_struct *_install_special_mapping(
3558 struct mm_struct *mm,
3559 unsigned long addr, unsigned long len,
3560 unsigned long vm_flags, const struct vm_special_mapping *spec)
3562 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3563 &special_mapping_vmops);
3566 int install_special_mapping(struct mm_struct *mm,
3567 unsigned long addr, unsigned long len,
3568 unsigned long vm_flags, struct page **pages)
3570 struct vm_area_struct *vma = __install_special_mapping(
3571 mm, addr, len, vm_flags, (void *)pages,
3572 &legacy_special_mapping_vmops);
3574 return PTR_ERR_OR_ZERO(vma);
3577 static DEFINE_MUTEX(mm_all_locks_mutex);
3579 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3581 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3583 * The LSB of head.next can't change from under us
3584 * because we hold the mm_all_locks_mutex.
3586 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3588 * We can safely modify head.next after taking the
3589 * anon_vma->root->rwsem. If some other vma in this mm shares
3590 * the same anon_vma we won't take it again.
3592 * No need of atomic instructions here, head.next
3593 * can't change from under us thanks to the
3594 * anon_vma->root->rwsem.
3596 if (__test_and_set_bit(0, (unsigned long *)
3597 &anon_vma->root->rb_root.rb_root.rb_node))
3602 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3604 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3606 * AS_MM_ALL_LOCKS can't change from under us because
3607 * we hold the mm_all_locks_mutex.
3609 * Operations on ->flags have to be atomic because
3610 * even if AS_MM_ALL_LOCKS is stable thanks to the
3611 * mm_all_locks_mutex, there may be other cpus
3612 * changing other bitflags in parallel to us.
3614 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3616 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3621 * This operation locks against the VM for all pte/vma/mm related
3622 * operations that could ever happen on a certain mm. This includes
3623 * vmtruncate, try_to_unmap, and all page faults.
3625 * The caller must take the mmap_lock in write mode before calling
3626 * mm_take_all_locks(). The caller isn't allowed to release the
3627 * mmap_lock until mm_drop_all_locks() returns.
3629 * mmap_lock in write mode is required in order to block all operations
3630 * that could modify pagetables and free pages without need of
3631 * altering the vma layout. It's also needed in write mode to avoid new
3632 * anon_vmas to be associated with existing vmas.
3634 * A single task can't take more than one mm_take_all_locks() in a row
3635 * or it would deadlock.
3637 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3638 * mapping->flags avoid to take the same lock twice, if more than one
3639 * vma in this mm is backed by the same anon_vma or address_space.
3641 * We take locks in following order, accordingly to comment at beginning
3643 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3645 * - all vmas marked locked
3646 * - all i_mmap_rwsem locks;
3647 * - all anon_vma->rwseml
3649 * We can take all locks within these types randomly because the VM code
3650 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3651 * mm_all_locks_mutex.
3653 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3654 * that may have to take thousand of locks.
3656 * mm_take_all_locks() can fail if it's interrupted by signals.
3658 int mm_take_all_locks(struct mm_struct *mm)
3660 struct vm_area_struct *vma;
3661 struct anon_vma_chain *avc;
3662 MA_STATE(mas, &mm->mm_mt, 0, 0);
3664 mmap_assert_write_locked(mm);
3666 mutex_lock(&mm_all_locks_mutex);
3668 mas_for_each(&mas, vma, ULONG_MAX) {
3669 if (signal_pending(current))
3671 vma_start_write(vma);
3675 mas_for_each(&mas, vma, ULONG_MAX) {
3676 if (signal_pending(current))
3678 if (vma->vm_file && vma->vm_file->f_mapping &&
3679 is_vm_hugetlb_page(vma))
3680 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3684 mas_for_each(&mas, vma, ULONG_MAX) {
3685 if (signal_pending(current))
3687 if (vma->vm_file && vma->vm_file->f_mapping &&
3688 !is_vm_hugetlb_page(vma))
3689 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3693 mas_for_each(&mas, vma, ULONG_MAX) {
3694 if (signal_pending(current))
3697 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3698 vm_lock_anon_vma(mm, avc->anon_vma);
3704 mm_drop_all_locks(mm);
3708 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3710 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3712 * The LSB of head.next can't change to 0 from under
3713 * us because we hold the mm_all_locks_mutex.
3715 * We must however clear the bitflag before unlocking
3716 * the vma so the users using the anon_vma->rb_root will
3717 * never see our bitflag.
3719 * No need of atomic instructions here, head.next
3720 * can't change from under us until we release the
3721 * anon_vma->root->rwsem.
3723 if (!__test_and_clear_bit(0, (unsigned long *)
3724 &anon_vma->root->rb_root.rb_root.rb_node))
3726 anon_vma_unlock_write(anon_vma);
3730 static void vm_unlock_mapping(struct address_space *mapping)
3732 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3734 * AS_MM_ALL_LOCKS can't change to 0 from under us
3735 * because we hold the mm_all_locks_mutex.
3737 i_mmap_unlock_write(mapping);
3738 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3745 * The mmap_lock cannot be released by the caller until
3746 * mm_drop_all_locks() returns.
3748 void mm_drop_all_locks(struct mm_struct *mm)
3750 struct vm_area_struct *vma;
3751 struct anon_vma_chain *avc;
3752 MA_STATE(mas, &mm->mm_mt, 0, 0);
3754 mmap_assert_write_locked(mm);
3755 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3757 mas_for_each(&mas, vma, ULONG_MAX) {
3759 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3760 vm_unlock_anon_vma(avc->anon_vma);
3761 if (vma->vm_file && vma->vm_file->f_mapping)
3762 vm_unlock_mapping(vma->vm_file->f_mapping);
3764 vma_end_write_all(mm);
3766 mutex_unlock(&mm_all_locks_mutex);
3770 * initialise the percpu counter for VM
3772 void __init mmap_init(void)
3776 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3781 * Initialise sysctl_user_reserve_kbytes.
3783 * This is intended to prevent a user from starting a single memory hogging
3784 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3787 * The default value is min(3% of free memory, 128MB)
3788 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3790 static int init_user_reserve(void)
3792 unsigned long free_kbytes;
3794 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3796 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3799 subsys_initcall(init_user_reserve);
3802 * Initialise sysctl_admin_reserve_kbytes.
3804 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3805 * to log in and kill a memory hogging process.
3807 * Systems with more than 256MB will reserve 8MB, enough to recover
3808 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3809 * only reserve 3% of free pages by default.
3811 static int init_admin_reserve(void)
3813 unsigned long free_kbytes;
3815 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3817 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3820 subsys_initcall(init_admin_reserve);
3823 * Reinititalise user and admin reserves if memory is added or removed.
3825 * The default user reserve max is 128MB, and the default max for the
3826 * admin reserve is 8MB. These are usually, but not always, enough to
3827 * enable recovery from a memory hogging process using login/sshd, a shell,
3828 * and tools like top. It may make sense to increase or even disable the
3829 * reserve depending on the existence of swap or variations in the recovery
3830 * tools. So, the admin may have changed them.
3832 * If memory is added and the reserves have been eliminated or increased above
3833 * the default max, then we'll trust the admin.
3835 * If memory is removed and there isn't enough free memory, then we
3836 * need to reset the reserves.
3838 * Otherwise keep the reserve set by the admin.
3840 static int reserve_mem_notifier(struct notifier_block *nb,
3841 unsigned long action, void *data)
3843 unsigned long tmp, free_kbytes;
3847 /* Default max is 128MB. Leave alone if modified by operator. */
3848 tmp = sysctl_user_reserve_kbytes;
3849 if (0 < tmp && tmp < (1UL << 17))
3850 init_user_reserve();
3852 /* Default max is 8MB. Leave alone if modified by operator. */
3853 tmp = sysctl_admin_reserve_kbytes;
3854 if (0 < tmp && tmp < (1UL << 13))
3855 init_admin_reserve();
3859 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3861 if (sysctl_user_reserve_kbytes > free_kbytes) {
3862 init_user_reserve();
3863 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3864 sysctl_user_reserve_kbytes);
3867 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3868 init_admin_reserve();
3869 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3870 sysctl_admin_reserve_kbytes);
3879 static int __meminit init_reserve_notifier(void)
3881 if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3882 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3886 subsys_initcall(init_reserve_notifier);