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/vmacache.h>
18 #include <linux/shm.h>
19 #include <linux/mman.h>
20 #include <linux/pagemap.h>
21 #include <linux/swap.h>
22 #include <linux/syscalls.h>
23 #include <linux/capability.h>
24 #include <linux/init.h>
25 #include <linux/file.h>
27 #include <linux/personality.h>
28 #include <linux/security.h>
29 #include <linux/hugetlb.h>
30 #include <linux/shmem_fs.h>
31 #include <linux/profile.h>
32 #include <linux/export.h>
33 #include <linux/mount.h>
34 #include <linux/mempolicy.h>
35 #include <linux/rmap.h>
36 #include <linux/mmu_notifier.h>
37 #include <linux/mmdebug.h>
38 #include <linux/perf_event.h>
39 #include <linux/audit.h>
40 #include <linux/khugepaged.h>
41 #include <linux/uprobes.h>
42 #include <linux/rbtree_augmented.h>
43 #include <linux/notifier.h>
44 #include <linux/memory.h>
45 #include <linux/printk.h>
46 #include <linux/userfaultfd_k.h>
47 #include <linux/moduleparam.h>
48 #include <linux/pkeys.h>
49 #include <linux/oom.h>
50 #include <linux/sched/mm.h>
52 #include <linux/uaccess.h>
53 #include <asm/cacheflush.h>
55 #include <asm/mmu_context.h>
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/mmap.h>
62 #ifndef arch_mmap_check
63 #define arch_mmap_check(addr, len, flags) (0)
66 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
67 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
68 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
69 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
71 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
72 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
73 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
74 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
77 static bool ignore_rlimit_data;
78 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
80 static void unmap_region(struct mm_struct *mm,
81 struct vm_area_struct *vma, struct vm_area_struct *prev,
82 unsigned long start, unsigned long end);
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, returning the next.
137 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
139 struct vm_area_struct *next = vma->vm_next;
142 if (vma->vm_ops && vma->vm_ops->close)
143 vma->vm_ops->close(vma);
146 mpol_put(vma_policy(vma));
151 static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,
152 struct list_head *uf);
153 SYSCALL_DEFINE1(brk, unsigned long, brk)
155 unsigned long newbrk, oldbrk, origbrk;
156 struct mm_struct *mm = current->mm;
157 struct vm_area_struct *next;
158 unsigned long min_brk;
160 bool downgraded = false;
163 if (mmap_write_lock_killable(mm))
168 #ifdef CONFIG_COMPAT_BRK
170 * CONFIG_COMPAT_BRK can still be overridden by setting
171 * randomize_va_space to 2, which will still cause mm->start_brk
172 * to be arbitrarily shifted
174 if (current->brk_randomized)
175 min_brk = mm->start_brk;
177 min_brk = mm->end_data;
179 min_brk = mm->start_brk;
185 * Check against rlimit here. If this check is done later after the test
186 * of oldbrk with newbrk then it can escape the test and let the data
187 * segment grow beyond its set limit the in case where the limit is
188 * not page aligned -Ram Gupta
190 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
191 mm->end_data, mm->start_data))
194 newbrk = PAGE_ALIGN(brk);
195 oldbrk = PAGE_ALIGN(mm->brk);
196 if (oldbrk == newbrk) {
202 * Always allow shrinking brk.
203 * __do_munmap() may downgrade mmap_lock to read.
205 if (brk <= mm->brk) {
209 * mm->brk must to be protected by write mmap_lock so update it
210 * before downgrading mmap_lock. When __do_munmap() fails,
211 * mm->brk will be restored from origbrk.
214 ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
218 } else if (ret == 1) {
224 /* Check against existing mmap mappings. */
225 next = find_vma(mm, oldbrk);
226 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
229 /* Ok, looks good - let it rip. */
230 if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
235 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
237 mmap_read_unlock(mm);
239 mmap_write_unlock(mm);
240 userfaultfd_unmap_complete(mm, &uf);
242 mm_populate(oldbrk, newbrk - oldbrk);
246 mmap_write_unlock(mm);
250 static inline unsigned long vma_compute_gap(struct vm_area_struct *vma)
252 unsigned long gap, prev_end;
255 * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
256 * allow two stack_guard_gaps between them here, and when choosing
257 * an unmapped area; whereas when expanding we only require one.
258 * That's a little inconsistent, but keeps the code here simpler.
260 gap = vm_start_gap(vma);
262 prev_end = vm_end_gap(vma->vm_prev);
271 #ifdef CONFIG_DEBUG_VM_RB
272 static unsigned long vma_compute_subtree_gap(struct vm_area_struct *vma)
274 unsigned long max = vma_compute_gap(vma), subtree_gap;
275 if (vma->vm_rb.rb_left) {
276 subtree_gap = rb_entry(vma->vm_rb.rb_left,
277 struct vm_area_struct, vm_rb)->rb_subtree_gap;
278 if (subtree_gap > max)
281 if (vma->vm_rb.rb_right) {
282 subtree_gap = rb_entry(vma->vm_rb.rb_right,
283 struct vm_area_struct, vm_rb)->rb_subtree_gap;
284 if (subtree_gap > max)
290 static int browse_rb(struct mm_struct *mm)
292 struct rb_root *root = &mm->mm_rb;
293 int i = 0, j, bug = 0;
294 struct rb_node *nd, *pn = NULL;
295 unsigned long prev = 0, pend = 0;
297 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
298 struct vm_area_struct *vma;
299 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
300 if (vma->vm_start < prev) {
301 pr_emerg("vm_start %lx < prev %lx\n",
302 vma->vm_start, prev);
305 if (vma->vm_start < pend) {
306 pr_emerg("vm_start %lx < pend %lx\n",
307 vma->vm_start, pend);
310 if (vma->vm_start > vma->vm_end) {
311 pr_emerg("vm_start %lx > vm_end %lx\n",
312 vma->vm_start, vma->vm_end);
315 spin_lock(&mm->page_table_lock);
316 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
317 pr_emerg("free gap %lx, correct %lx\n",
319 vma_compute_subtree_gap(vma));
322 spin_unlock(&mm->page_table_lock);
325 prev = vma->vm_start;
329 for (nd = pn; nd; nd = rb_prev(nd))
332 pr_emerg("backwards %d, forwards %d\n", j, i);
337 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
338 extern void mt_validate(struct maple_tree *mt);
339 extern void mt_dump(const struct maple_tree *mt);
341 /* Validate the maple tree */
342 static void validate_mm_mt(struct mm_struct *mm)
344 struct maple_tree *mt = &mm->mm_mt;
345 struct vm_area_struct *vma_mt, *vma = mm->mmap;
347 MA_STATE(mas, mt, 0, 0);
349 mt_validate(&mm->mm_mt);
350 mas_for_each(&mas, vma_mt, ULONG_MAX) {
351 if (xa_is_zero(vma_mt))
357 if ((vma != vma_mt) ||
358 (vma->vm_start != vma_mt->vm_start) ||
359 (vma->vm_end != vma_mt->vm_end) ||
360 (vma->vm_start != mas.index) ||
361 (vma->vm_end - 1 != mas.last)) {
362 pr_emerg("issue in %s\n", current->comm);
364 #ifdef CONFIG_DEBUG_VM
366 pr_emerg("and next in rb\n");
367 dump_vma(vma->vm_next);
369 pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
370 mas.index, mas.last);
371 pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
372 vma_mt->vm_start, vma_mt->vm_end);
373 pr_emerg("rb vma: %p %lu - %lu\n", vma,
374 vma->vm_start, vma->vm_end);
375 pr_emerg("rb->next = %p %lu - %lu\n", vma->vm_next,
376 vma->vm_next->vm_start, vma->vm_next->vm_end);
379 if (vma_mt->vm_end != mas.last + 1) {
380 pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
381 mm, vma_mt->vm_start, vma_mt->vm_end,
382 mas.index, mas.last);
385 VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
386 if (vma_mt->vm_start != mas.index) {
387 pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
388 mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
391 VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
393 VM_BUG_ON(vma != vma_mt);
400 #define validate_mm_mt(root) do { } while (0)
402 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
406 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
407 struct vm_area_struct *vma;
408 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
409 VM_BUG_ON_VMA(vma != ignore &&
410 vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
415 static void validate_mm(struct mm_struct *mm)
419 unsigned long highest_address = 0;
420 struct vm_area_struct *vma = mm->mmap;
423 struct anon_vma *anon_vma = vma->anon_vma;
424 struct anon_vma_chain *avc;
427 anon_vma_lock_read(anon_vma);
428 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
429 anon_vma_interval_tree_verify(avc);
430 anon_vma_unlock_read(anon_vma);
433 highest_address = vm_end_gap(vma);
437 if (i != mm->map_count) {
438 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
441 if (highest_address != mm->highest_vm_end) {
442 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
443 mm->highest_vm_end, highest_address);
447 if (i != mm->map_count) {
449 pr_emerg("map_count %d rb %d\n", mm->map_count, i);
452 VM_BUG_ON_MM(bug, mm);
455 #define validate_mm_rb(root, ignore) do { } while (0)
456 #define validate_mm_mt(root) do { } while (0)
457 #define validate_mm(mm) do { } while (0)
460 RB_DECLARE_CALLBACKS_MAX(static, vma_gap_callbacks,
461 struct vm_area_struct, vm_rb,
462 unsigned long, rb_subtree_gap, vma_compute_gap)
465 * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
466 * vma->vm_prev->vm_end values changed, without modifying the vma's position
469 static void vma_gap_update(struct vm_area_struct *vma)
472 * As it turns out, RB_DECLARE_CALLBACKS_MAX() already created
473 * a callback function that does exactly what we want.
475 vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
478 static inline void vma_rb_insert(struct vm_area_struct *vma,
479 struct rb_root *root)
481 /* All rb_subtree_gap values must be consistent prior to insertion */
482 validate_mm_rb(root, NULL);
484 rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
487 static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
490 * Note rb_erase_augmented is a fairly large inline function,
491 * so make sure we instantiate it only once with our desired
492 * augmented rbtree callbacks.
494 rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
497 static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
498 struct rb_root *root,
499 struct vm_area_struct *ignore)
502 * All rb_subtree_gap values must be consistent prior to erase,
503 * with the possible exception of
505 * a. the "next" vma being erased if next->vm_start was reduced in
506 * __vma_adjust() -> __vma_unlink()
507 * b. the vma being erased in detach_vmas_to_be_unmapped() ->
510 validate_mm_rb(root, ignore);
512 __vma_rb_erase(vma, root);
515 static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
516 struct rb_root *root)
518 vma_rb_erase_ignore(vma, root, vma);
522 * vma has some anon_vma assigned, and is already inserted on that
523 * anon_vma's interval trees.
525 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
526 * vma must be removed from the anon_vma's interval trees using
527 * anon_vma_interval_tree_pre_update_vma().
529 * After the update, the vma will be reinserted using
530 * anon_vma_interval_tree_post_update_vma().
532 * The entire update must be protected by exclusive mmap_lock and by
533 * the root anon_vma's mutex.
536 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
538 struct anon_vma_chain *avc;
540 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
541 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
545 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
547 struct anon_vma_chain *avc;
549 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
550 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
553 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
554 unsigned long end, struct vm_area_struct **pprev,
555 struct rb_node ***rb_link, struct rb_node **rb_parent)
557 struct rb_node **__rb_link, *__rb_parent, *rb_prev;
559 mmap_assert_locked(mm);
560 __rb_link = &mm->mm_rb.rb_node;
561 rb_prev = __rb_parent = NULL;
564 struct vm_area_struct *vma_tmp;
566 __rb_parent = *__rb_link;
567 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
569 if (vma_tmp->vm_end > addr) {
570 /* Fail if an existing vma overlaps the area */
571 if (vma_tmp->vm_start < end)
573 __rb_link = &__rb_parent->rb_left;
575 rb_prev = __rb_parent;
576 __rb_link = &__rb_parent->rb_right;
582 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
583 *rb_link = __rb_link;
584 *rb_parent = __rb_parent;
589 * __vma_next() - Get the next VMA.
590 * @mm: The mm_struct.
591 * @vma: The current vma.
593 * If @vma is NULL, return the first vma in the mm.
595 * Returns: The next VMA after @vma.
597 static inline struct vm_area_struct *__vma_next(struct mm_struct *mm,
598 struct vm_area_struct *vma)
607 * munmap_vma_range() - munmap VMAs that overlap a range.
609 * @start: The start of the range.
610 * @len: The length of the range.
611 * @pprev: pointer to the pointer that will be set to previous vm_area_struct
612 * @rb_link: the rb_node
613 * @rb_parent: the parent rb_node
615 * Find all the vm_area_struct that overlap from @start to
616 * @end and munmap them. Set @pprev to the previous vm_area_struct.
618 * Returns: -ENOMEM on munmap failure or 0 on success.
621 munmap_vma_range(struct mm_struct *mm, unsigned long start, unsigned long len,
622 struct vm_area_struct **pprev, struct rb_node ***link,
623 struct rb_node **parent, struct list_head *uf)
626 while (find_vma_links(mm, start, start + len, pprev, link, parent))
627 if (do_munmap(mm, start, len, uf))
633 static unsigned long count_vma_pages_range(struct mm_struct *mm,
634 unsigned long addr, unsigned long end)
636 VMA_ITERATOR(vmi, mm, addr);
637 struct vm_area_struct *vma;
638 unsigned long nr_pages = 0;
640 for_each_vma_range(vmi, vma, end) {
641 unsigned long vm_start = max(addr, vma->vm_start);
642 unsigned long vm_end = min(end, vma->vm_end);
644 nr_pages += PHYS_PFN(vm_end - vm_start);
650 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
651 struct rb_node **rb_link, struct rb_node *rb_parent)
653 /* Update tracking information for the gap following the new vma. */
655 vma_gap_update(vma->vm_next);
657 mm->highest_vm_end = vm_end_gap(vma);
660 * vma->vm_prev wasn't known when we followed the rbtree to find the
661 * correct insertion point for that vma. As a result, we could not
662 * update the vma vm_rb parents rb_subtree_gap values on the way down.
663 * So, we first insert the vma with a zero rb_subtree_gap value
664 * (to be consistent with what we did on the way down), and then
665 * immediately update the gap to the correct value. Finally we
666 * rebalance the rbtree after all augmented values have been set.
668 rb_link_node(&vma->vm_rb, rb_parent, rb_link);
669 vma->rb_subtree_gap = 0;
671 vma_rb_insert(vma, &mm->mm_rb);
674 static void __vma_link_file(struct vm_area_struct *vma)
680 struct address_space *mapping = file->f_mapping;
682 if (vma->vm_flags & VM_SHARED)
683 mapping_allow_writable(mapping);
685 flush_dcache_mmap_lock(mapping);
686 vma_interval_tree_insert(vma, &mapping->i_mmap);
687 flush_dcache_mmap_unlock(mapping);
692 * vma_mas_store() - Store a VMA in the maple tree.
693 * @vma: The vm_area_struct
694 * @mas: The maple state
696 * Efficient way to store a VMA in the maple tree when the @mas has already
697 * walked to the correct location.
699 * Note: the end address is inclusive in the maple tree.
701 void vma_mas_store(struct vm_area_struct *vma, struct ma_state *mas)
703 trace_vma_store(mas->tree, vma);
704 mas_set_range(mas, vma->vm_start, vma->vm_end - 1);
705 mas_store_prealloc(mas, vma);
709 * vma_mas_remove() - Remove a VMA from the maple tree.
710 * @vma: The vm_area_struct
711 * @mas: The maple state
713 * Efficient way to remove a VMA from the maple tree when the @mas has already
714 * been established and points to the correct location.
715 * Note: the end address is inclusive in the maple tree.
717 void vma_mas_remove(struct vm_area_struct *vma, struct ma_state *mas)
719 trace_vma_mas_szero(mas->tree, vma->vm_start, vma->vm_end - 1);
720 mas->index = vma->vm_start;
721 mas->last = vma->vm_end - 1;
722 mas_store_prealloc(mas, NULL);
726 * vma_mas_szero() - Set a given range to zero. Used when modifying a
727 * vm_area_struct start or end.
730 * @start: The start address to zero
731 * @end: The end address to zero.
733 static inline void vma_mas_szero(struct ma_state *mas, unsigned long start,
736 trace_vma_mas_szero(mas->tree, start, end - 1);
737 mas_set_range(mas, start, end - 1);
738 mas_store_prealloc(mas, NULL);
742 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
743 struct vm_area_struct *prev, struct rb_node **rb_link,
744 struct rb_node *rb_parent)
746 __vma_link_list(mm, vma, prev);
747 __vma_link_rb(mm, vma, rb_link, rb_parent);
750 static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
751 struct vm_area_struct *prev, struct rb_node **rb_link,
752 struct rb_node *rb_parent)
754 MA_STATE(mas, &mm->mm_mt, 0, 0);
755 struct address_space *mapping = NULL;
757 if (mas_preallocate(&mas, vma, GFP_KERNEL))
761 mapping = vma->vm_file->f_mapping;
762 i_mmap_lock_write(mapping);
765 vma_mas_store(vma, &mas);
766 __vma_link(mm, vma, prev, rb_link, rb_parent);
767 __vma_link_file(vma);
770 i_mmap_unlock_write(mapping);
778 * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
779 * mm's list and rbtree. It has already been inserted into the interval tree.
781 static void __insert_vm_struct(struct mm_struct *mm, struct ma_state *mas,
782 struct vm_area_struct *vma)
784 struct vm_area_struct *prev;
785 struct rb_node **rb_link, *rb_parent;
787 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
788 &prev, &rb_link, &rb_parent))
791 vma_mas_store(vma, mas);
792 __vma_link_list(mm, vma, prev);
793 __vma_link_rb(mm, vma, rb_link, rb_parent);
797 static __always_inline void __vma_unlink(struct mm_struct *mm,
798 struct vm_area_struct *vma,
799 struct vm_area_struct *ignore)
801 vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
802 __vma_unlink_list(mm, vma);
804 vmacache_invalidate(mm);
808 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
809 * is already present in an i_mmap tree without adjusting the tree.
810 * The following helper function should be used when such adjustments
811 * are necessary. The "insert" vma (if any) is to be inserted
812 * before we drop the necessary locks.
814 int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
815 unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
816 struct vm_area_struct *expand)
818 struct mm_struct *mm = vma->vm_mm;
819 struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
820 struct vm_area_struct *next_next;
821 struct address_space *mapping = NULL;
822 struct rb_root_cached *root = NULL;
823 struct anon_vma *anon_vma = NULL;
824 struct file *file = vma->vm_file;
825 bool start_changed = false, end_changed = false;
826 long adjust_next = 0;
828 MA_STATE(mas, &mm->mm_mt, 0, 0);
829 struct vm_area_struct *exporter = NULL, *importer = NULL;
834 if (next && !insert) {
835 if (end >= next->vm_end) {
837 * vma expands, overlapping all the next, and
838 * perhaps the one after too (mprotect case 6).
839 * The only other cases that gets here are
840 * case 1, case 7 and case 8.
842 if (next == expand) {
844 * The only case where we don't expand "vma"
845 * and we expand "next" instead is case 8.
847 VM_WARN_ON(end != next->vm_end);
849 * remove_next == 3 means we're
850 * removing "vma" and that to do so we
851 * swapped "vma" and "next".
854 VM_WARN_ON(file != next->vm_file);
857 VM_WARN_ON(expand != vma);
859 * case 1, 6, 7, remove_next == 2 is case 6,
860 * remove_next == 1 is case 1 or 7.
862 remove_next = 1 + (end > next->vm_end);
863 if (remove_next == 2)
864 next_next = find_vma(mm, next->vm_end);
866 VM_WARN_ON(remove_next == 2 &&
867 end != next->vm_next->vm_end);
874 * If next doesn't have anon_vma, import from vma after
875 * next, if the vma overlaps with it.
877 if (remove_next == 2 && !next->anon_vma)
878 exporter = next->vm_next;
880 } else if (end > next->vm_start) {
882 * vma expands, overlapping part of the next:
883 * mprotect case 5 shifting the boundary up.
885 adjust_next = (end - next->vm_start);
888 VM_WARN_ON(expand != importer);
889 } else if (end < vma->vm_end) {
891 * vma shrinks, and !insert tells it's not
892 * split_vma inserting another: so it must be
893 * mprotect case 4 shifting the boundary down.
895 adjust_next = -(vma->vm_end - end);
898 VM_WARN_ON(expand != importer);
902 * Easily overlooked: when mprotect shifts the boundary,
903 * make sure the expanding vma has anon_vma set if the
904 * shrinking vma had, to cover any anon pages imported.
906 if (exporter && exporter->anon_vma && !importer->anon_vma) {
909 importer->anon_vma = exporter->anon_vma;
910 error = anon_vma_clone(importer, exporter);
916 if (mas_preallocate(&mas, vma, GFP_KERNEL))
919 vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
921 mapping = file->f_mapping;
922 root = &mapping->i_mmap;
923 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
926 uprobe_munmap(next, next->vm_start, next->vm_end);
928 i_mmap_lock_write(mapping);
931 * Put into interval tree now, so instantiated pages
932 * are visible to arm/parisc __flush_dcache_page
933 * throughout; but we cannot insert into address
934 * space until vma start or end is updated.
936 __vma_link_file(insert);
940 anon_vma = vma->anon_vma;
941 if (!anon_vma && adjust_next)
942 anon_vma = next->anon_vma;
944 VM_WARN_ON(adjust_next && next->anon_vma &&
945 anon_vma != next->anon_vma);
946 anon_vma_lock_write(anon_vma);
947 anon_vma_interval_tree_pre_update_vma(vma);
949 anon_vma_interval_tree_pre_update_vma(next);
953 flush_dcache_mmap_lock(mapping);
954 vma_interval_tree_remove(vma, root);
956 vma_interval_tree_remove(next, root);
959 if (start != vma->vm_start) {
960 unsigned long old_start = vma->vm_start;
961 vma->vm_start = start;
962 if (old_start < start)
963 vma_mas_szero(&mas, old_start, start);
964 start_changed = true;
966 if (end != vma->vm_end) {
967 unsigned long old_end = vma->vm_end;
970 vma_mas_szero(&mas, end, old_end);
974 if (end_changed || start_changed)
975 vma_mas_store(vma, &mas);
977 vma->vm_pgoff = pgoff;
979 next->vm_start += adjust_next;
980 next->vm_pgoff += adjust_next >> PAGE_SHIFT;
981 vma_mas_store(next, &mas);
986 vma_interval_tree_insert(next, root);
987 vma_interval_tree_insert(vma, root);
988 flush_dcache_mmap_unlock(mapping);
993 * vma_merge has merged next into vma, and needs
994 * us to remove next before dropping the locks.
995 * Since we have expanded over this vma, the maple tree will
996 * have overwritten by storing the value
998 if (remove_next != 3) {
999 __vma_unlink(mm, next, next);
1000 if (remove_next == 2)
1001 __vma_unlink(mm, next_next, next_next);
1004 * vma is not before next if they've been
1007 * pre-swap() next->vm_start was reduced so
1008 * tell validate_mm_rb to ignore pre-swap()
1009 * "next" (which is stored in post-swap()
1012 __vma_unlink(mm, next, vma);
1015 __remove_shared_vm_struct(next, file, mapping);
1016 if (remove_next == 2)
1017 __remove_shared_vm_struct(next_next, file, mapping);
1019 } else if (insert) {
1021 * split_vma has split insert from vma, and needs
1022 * us to insert it before dropping the locks
1023 * (it may either follow vma or precede it).
1025 __insert_vm_struct(mm, &mas, insert);
1028 vma_gap_update(vma);
1031 mm->highest_vm_end = vm_end_gap(vma);
1032 else if (!adjust_next)
1033 vma_gap_update(next);
1038 anon_vma_interval_tree_post_update_vma(vma);
1040 anon_vma_interval_tree_post_update_vma(next);
1041 anon_vma_unlock_write(anon_vma);
1045 i_mmap_unlock_write(mapping);
1055 uprobe_munmap(next, next->vm_start, next->vm_end);
1059 anon_vma_merge(vma, next);
1061 mpol_put(vma_policy(next));
1064 * In mprotect's case 6 (see comments on vma_merge),
1065 * we must remove another next too. It would clutter
1066 * up the code too much to do both in one go.
1068 if (remove_next != 3) {
1070 * If "next" was removed and vma->vm_end was
1071 * expanded (up) over it, in turn
1072 * "next->vm_prev->vm_end" changed and the
1073 * "vma->vm_next" gap must be updated.
1078 * For the scope of the comment "next" and
1079 * "vma" considered pre-swap(): if "vma" was
1080 * removed, next->vm_start was expanded (down)
1081 * over it and the "next" gap must be updated.
1082 * Because of the swap() the post-swap() "vma"
1083 * actually points to pre-swap() "next"
1084 * (post-swap() "next" as opposed is now a
1085 * dangling pointer).
1089 if (remove_next == 2) {
1094 vma_gap_update(next);
1097 * If remove_next == 2 we obviously can't
1100 * If remove_next == 3 we can't reach this
1101 * path because pre-swap() next is always not
1102 * NULL. pre-swap() "next" is not being
1103 * removed and its next->vm_end is not altered
1104 * (and furthermore "end" already matches
1105 * next->vm_end in remove_next == 3).
1107 * We reach this only in the remove_next == 1
1108 * case if the "next" vma that was removed was
1109 * the highest vma of the mm. However in such
1110 * case next->vm_end == "end" and the extended
1111 * "vma" has vma->vm_end == next->vm_end so
1112 * mm->highest_vm_end doesn't need any update
1113 * in remove_next == 1 case.
1115 VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
1119 uprobe_mmap(insert);
1128 * If the vma has a ->close operation then the driver probably needs to release
1129 * per-vma resources, so we don't attempt to merge those.
1131 static inline int is_mergeable_vma(struct vm_area_struct *vma,
1132 struct file *file, unsigned long vm_flags,
1133 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1134 struct anon_vma_name *anon_name)
1137 * VM_SOFTDIRTY should not prevent from VMA merging, if we
1138 * match the flags but dirty bit -- the caller should mark
1139 * merged VMA as dirty. If dirty bit won't be excluded from
1140 * comparison, we increase pressure on the memory system forcing
1141 * the kernel to generate new VMAs when old one could be
1144 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
1146 if (vma->vm_file != file)
1148 if (vma->vm_ops && vma->vm_ops->close)
1150 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
1152 if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
1157 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
1158 struct anon_vma *anon_vma2,
1159 struct vm_area_struct *vma)
1162 * The list_is_singular() test is to avoid merging VMA cloned from
1163 * parents. This can improve scalability caused by anon_vma lock.
1165 if ((!anon_vma1 || !anon_vma2) && (!vma ||
1166 list_is_singular(&vma->anon_vma_chain)))
1168 return anon_vma1 == anon_vma2;
1172 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1173 * in front of (at a lower virtual address and file offset than) the vma.
1175 * We cannot merge two vmas if they have differently assigned (non-NULL)
1176 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1178 * We don't check here for the merged mmap wrapping around the end of pagecache
1179 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
1180 * wrap, nor mmaps which cover the final page at index -1UL.
1183 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
1184 struct anon_vma *anon_vma, struct file *file,
1186 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1187 struct anon_vma_name *anon_name)
1189 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1190 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1191 if (vma->vm_pgoff == vm_pgoff)
1198 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1199 * beyond (at a higher virtual address and file offset than) the vma.
1201 * We cannot merge two vmas if they have differently assigned (non-NULL)
1202 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1205 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
1206 struct anon_vma *anon_vma, struct file *file,
1208 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1209 struct anon_vma_name *anon_name)
1211 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1212 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1214 vm_pglen = vma_pages(vma);
1215 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
1222 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
1223 * figure out whether that can be merged with its predecessor or its
1224 * successor. Or both (it neatly fills a hole).
1226 * In most cases - when called for mmap, brk or mremap - [addr,end) is
1227 * certain not to be mapped by the time vma_merge is called; but when
1228 * called for mprotect, it is certain to be already mapped (either at
1229 * an offset within prev, or at the start of next), and the flags of
1230 * this area are about to be changed to vm_flags - and the no-change
1231 * case has already been eliminated.
1233 * The following mprotect cases have to be considered, where AAAA is
1234 * the area passed down from mprotect_fixup, never extending beyond one
1235 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
1238 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN
1239 * cannot merge might become might become
1240 * PPNNNNNNNNNN PPPPPPPPPPNN
1241 * mmap, brk or case 4 below case 5 below
1244 * PPPP NNNN PPPPNNNNXXXX
1245 * might become might become
1246 * PPPPPPPPPPPP 1 or PPPPPPPPPPPP 6 or
1247 * PPPPPPPPNNNN 2 or PPPPPPPPXXXX 7 or
1248 * PPPPNNNNNNNN 3 PPPPXXXXXXXX 8
1250 * It is important for case 8 that the vma NNNN overlapping the
1251 * region AAAA is never going to extended over XXXX. Instead XXXX must
1252 * be extended in region AAAA and NNNN must be removed. This way in
1253 * all cases where vma_merge succeeds, the moment vma_adjust drops the
1254 * rmap_locks, the properties of the merged vma will be already
1255 * correct for the whole merged range. Some of those properties like
1256 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1257 * be correct for the whole merged range immediately after the
1258 * rmap_locks are released. Otherwise if XXXX would be removed and
1259 * NNNN would be extended over the XXXX range, remove_migration_ptes
1260 * or other rmap walkers (if working on addresses beyond the "end"
1261 * parameter) may establish ptes with the wrong permissions of NNNN
1262 * instead of the right permissions of XXXX.
1264 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1265 struct vm_area_struct *prev, unsigned long addr,
1266 unsigned long end, unsigned long vm_flags,
1267 struct anon_vma *anon_vma, struct file *file,
1268 pgoff_t pgoff, struct mempolicy *policy,
1269 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1270 struct anon_vma_name *anon_name)
1272 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1273 struct vm_area_struct *area, *next;
1278 * We later require that vma->vm_flags == vm_flags,
1279 * so this tests vma->vm_flags & VM_SPECIAL, too.
1281 if (vm_flags & VM_SPECIAL)
1284 next = __vma_next(mm, prev);
1286 if (area && area->vm_end == end) /* cases 6, 7, 8 */
1287 next = next->vm_next;
1289 /* verify some invariant that must be enforced by the caller */
1290 VM_WARN_ON(prev && addr <= prev->vm_start);
1291 VM_WARN_ON(area && end > area->vm_end);
1292 VM_WARN_ON(addr >= end);
1295 * Can it merge with the predecessor?
1297 if (prev && prev->vm_end == addr &&
1298 mpol_equal(vma_policy(prev), policy) &&
1299 can_vma_merge_after(prev, vm_flags,
1300 anon_vma, file, pgoff,
1301 vm_userfaultfd_ctx, anon_name)) {
1303 * OK, it can. Can we now merge in the successor as well?
1305 if (next && end == next->vm_start &&
1306 mpol_equal(policy, vma_policy(next)) &&
1307 can_vma_merge_before(next, vm_flags,
1310 vm_userfaultfd_ctx, anon_name) &&
1311 is_mergeable_anon_vma(prev->anon_vma,
1312 next->anon_vma, NULL)) {
1314 err = __vma_adjust(prev, prev->vm_start,
1315 next->vm_end, prev->vm_pgoff, NULL,
1317 } else /* cases 2, 5, 7 */
1318 err = __vma_adjust(prev, prev->vm_start,
1319 end, prev->vm_pgoff, NULL, prev);
1322 khugepaged_enter_vma(prev, vm_flags);
1327 * Can this new request be merged in front of next?
1329 if (next && end == next->vm_start &&
1330 mpol_equal(policy, vma_policy(next)) &&
1331 can_vma_merge_before(next, vm_flags,
1332 anon_vma, file, pgoff+pglen,
1333 vm_userfaultfd_ctx, anon_name)) {
1334 if (prev && addr < prev->vm_end) /* case 4 */
1335 err = __vma_adjust(prev, prev->vm_start,
1336 addr, prev->vm_pgoff, NULL, next);
1337 else { /* cases 3, 8 */
1338 err = __vma_adjust(area, addr, next->vm_end,
1339 next->vm_pgoff - pglen, NULL, next);
1341 * In case 3 area is already equal to next and
1342 * this is a noop, but in case 8 "area" has
1343 * been removed and next was expanded over it.
1349 khugepaged_enter_vma(area, vm_flags);
1358 * Rough compatibility check to quickly see if it's even worth looking
1359 * at sharing an anon_vma.
1361 * They need to have the same vm_file, and the flags can only differ
1362 * in things that mprotect may change.
1364 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1365 * we can merge the two vma's. For example, we refuse to merge a vma if
1366 * there is a vm_ops->close() function, because that indicates that the
1367 * driver is doing some kind of reference counting. But that doesn't
1368 * really matter for the anon_vma sharing case.
1370 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1372 return a->vm_end == b->vm_start &&
1373 mpol_equal(vma_policy(a), vma_policy(b)) &&
1374 a->vm_file == b->vm_file &&
1375 !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1376 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1380 * Do some basic sanity checking to see if we can re-use the anon_vma
1381 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1382 * the same as 'old', the other will be the new one that is trying
1383 * to share the anon_vma.
1385 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1386 * the anon_vma of 'old' is concurrently in the process of being set up
1387 * by another page fault trying to merge _that_. But that's ok: if it
1388 * is being set up, that automatically means that it will be a singleton
1389 * acceptable for merging, so we can do all of this optimistically. But
1390 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1392 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1393 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1394 * is to return an anon_vma that is "complex" due to having gone through
1397 * We also make sure that the two vma's are compatible (adjacent,
1398 * and with the same memory policies). That's all stable, even with just
1399 * a read lock on the mmap_lock.
1401 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1403 if (anon_vma_compatible(a, b)) {
1404 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1406 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1413 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1414 * neighbouring vmas for a suitable anon_vma, before it goes off
1415 * to allocate a new anon_vma. It checks because a repetitive
1416 * sequence of mprotects and faults may otherwise lead to distinct
1417 * anon_vmas being allocated, preventing vma merge in subsequent
1420 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1422 struct anon_vma *anon_vma = NULL;
1424 /* Try next first. */
1426 anon_vma = reusable_anon_vma(vma->vm_next, vma, vma->vm_next);
1431 /* Try prev next. */
1433 anon_vma = reusable_anon_vma(vma->vm_prev, vma->vm_prev, vma);
1436 * We might reach here with anon_vma == NULL if we can't find
1437 * any reusable anon_vma.
1438 * There's no absolute need to look only at touching neighbours:
1439 * we could search further afield for "compatible" anon_vmas.
1440 * But it would probably just be a waste of time searching,
1441 * or lead to too many vmas hanging off the same anon_vma.
1442 * We're trying to allow mprotect remerging later on,
1443 * not trying to minimize memory used for anon_vmas.
1449 * If a hint addr is less than mmap_min_addr change hint to be as
1450 * low as possible but still greater than mmap_min_addr
1452 static inline unsigned long round_hint_to_min(unsigned long hint)
1455 if (((void *)hint != NULL) &&
1456 (hint < mmap_min_addr))
1457 return PAGE_ALIGN(mmap_min_addr);
1461 int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1464 unsigned long locked, lock_limit;
1466 /* mlock MCL_FUTURE? */
1467 if (flags & VM_LOCKED) {
1468 locked = len >> PAGE_SHIFT;
1469 locked += mm->locked_vm;
1470 lock_limit = rlimit(RLIMIT_MEMLOCK);
1471 lock_limit >>= PAGE_SHIFT;
1472 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1478 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1480 if (S_ISREG(inode->i_mode))
1481 return MAX_LFS_FILESIZE;
1483 if (S_ISBLK(inode->i_mode))
1484 return MAX_LFS_FILESIZE;
1486 if (S_ISSOCK(inode->i_mode))
1487 return MAX_LFS_FILESIZE;
1489 /* Special "we do even unsigned file positions" case */
1490 if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1493 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1497 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1498 unsigned long pgoff, unsigned long len)
1500 u64 maxsize = file_mmap_size_max(file, inode);
1502 if (maxsize && len > maxsize)
1505 if (pgoff > maxsize >> PAGE_SHIFT)
1511 * The caller must write-lock current->mm->mmap_lock.
1513 unsigned long do_mmap(struct file *file, unsigned long addr,
1514 unsigned long len, unsigned long prot,
1515 unsigned long flags, unsigned long pgoff,
1516 unsigned long *populate, struct list_head *uf)
1518 struct mm_struct *mm = current->mm;
1519 vm_flags_t vm_flags;
1528 * Does the application expect PROT_READ to imply PROT_EXEC?
1530 * (the exception is when the underlying filesystem is noexec
1531 * mounted, in which case we dont add PROT_EXEC.)
1533 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1534 if (!(file && path_noexec(&file->f_path)))
1537 /* force arch specific MAP_FIXED handling in get_unmapped_area */
1538 if (flags & MAP_FIXED_NOREPLACE)
1541 if (!(flags & MAP_FIXED))
1542 addr = round_hint_to_min(addr);
1544 /* Careful about overflows.. */
1545 len = PAGE_ALIGN(len);
1549 /* offset overflow? */
1550 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1553 /* Too many mappings? */
1554 if (mm->map_count > sysctl_max_map_count)
1557 /* Obtain the address to map to. we verify (or select) it and ensure
1558 * that it represents a valid section of the address space.
1560 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1561 if (IS_ERR_VALUE(addr))
1564 if (flags & MAP_FIXED_NOREPLACE) {
1565 if (find_vma_intersection(mm, addr, addr + len))
1569 if (prot == PROT_EXEC) {
1570 pkey = execute_only_pkey(mm);
1575 /* Do simple checking here so the lower-level routines won't have
1576 * to. we assume access permissions have been handled by the open
1577 * of the memory object, so we don't do any here.
1579 vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1580 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1582 if (flags & MAP_LOCKED)
1583 if (!can_do_mlock())
1586 if (mlock_future_check(mm, vm_flags, len))
1590 struct inode *inode = file_inode(file);
1591 unsigned long flags_mask;
1593 if (!file_mmap_ok(file, inode, pgoff, len))
1596 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1598 switch (flags & MAP_TYPE) {
1601 * Force use of MAP_SHARED_VALIDATE with non-legacy
1602 * flags. E.g. MAP_SYNC is dangerous to use with
1603 * MAP_SHARED as you don't know which consistency model
1604 * you will get. We silently ignore unsupported flags
1605 * with MAP_SHARED to preserve backward compatibility.
1607 flags &= LEGACY_MAP_MASK;
1609 case MAP_SHARED_VALIDATE:
1610 if (flags & ~flags_mask)
1612 if (prot & PROT_WRITE) {
1613 if (!(file->f_mode & FMODE_WRITE))
1615 if (IS_SWAPFILE(file->f_mapping->host))
1620 * Make sure we don't allow writing to an append-only
1623 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1626 vm_flags |= VM_SHARED | VM_MAYSHARE;
1627 if (!(file->f_mode & FMODE_WRITE))
1628 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1631 if (!(file->f_mode & FMODE_READ))
1633 if (path_noexec(&file->f_path)) {
1634 if (vm_flags & VM_EXEC)
1636 vm_flags &= ~VM_MAYEXEC;
1639 if (!file->f_op->mmap)
1641 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1649 switch (flags & MAP_TYPE) {
1651 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1657 vm_flags |= VM_SHARED | VM_MAYSHARE;
1661 * Set pgoff according to addr for anon_vma.
1663 pgoff = addr >> PAGE_SHIFT;
1671 * Set 'VM_NORESERVE' if we should not account for the
1672 * memory use of this mapping.
1674 if (flags & MAP_NORESERVE) {
1675 /* We honor MAP_NORESERVE if allowed to overcommit */
1676 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1677 vm_flags |= VM_NORESERVE;
1679 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1680 if (file && is_file_hugepages(file))
1681 vm_flags |= VM_NORESERVE;
1684 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1685 if (!IS_ERR_VALUE(addr) &&
1686 ((vm_flags & VM_LOCKED) ||
1687 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1692 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1693 unsigned long prot, unsigned long flags,
1694 unsigned long fd, unsigned long pgoff)
1696 struct file *file = NULL;
1697 unsigned long retval;
1699 if (!(flags & MAP_ANONYMOUS)) {
1700 audit_mmap_fd(fd, flags);
1704 if (is_file_hugepages(file)) {
1705 len = ALIGN(len, huge_page_size(hstate_file(file)));
1706 } else if (unlikely(flags & MAP_HUGETLB)) {
1710 } else if (flags & MAP_HUGETLB) {
1713 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1717 len = ALIGN(len, huge_page_size(hs));
1719 * VM_NORESERVE is used because the reservations will be
1720 * taken when vm_ops->mmap() is called
1722 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1724 HUGETLB_ANONHUGE_INODE,
1725 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1727 return PTR_ERR(file);
1730 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1737 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1738 unsigned long, prot, unsigned long, flags,
1739 unsigned long, fd, unsigned long, pgoff)
1741 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1744 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1745 struct mmap_arg_struct {
1749 unsigned long flags;
1751 unsigned long offset;
1754 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1756 struct mmap_arg_struct a;
1758 if (copy_from_user(&a, arg, sizeof(a)))
1760 if (offset_in_page(a.offset))
1763 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1764 a.offset >> PAGE_SHIFT);
1766 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1769 * Some shared mappings will want the pages marked read-only
1770 * to track write events. If so, we'll downgrade vm_page_prot
1771 * to the private version (using protection_map[] without the
1774 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1776 vm_flags_t vm_flags = vma->vm_flags;
1777 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1779 /* If it was private or non-writable, the write bit is already clear */
1780 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1783 /* The backer wishes to know when pages are first written to? */
1784 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1787 /* The open routine did something to the protections that pgprot_modify
1788 * won't preserve? */
1789 if (pgprot_val(vm_page_prot) !=
1790 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1794 * Do we need to track softdirty? hugetlb does not support softdirty
1797 if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1800 /* Specialty mapping? */
1801 if (vm_flags & VM_PFNMAP)
1804 /* Can the mapping track the dirty pages? */
1805 return vma->vm_file && vma->vm_file->f_mapping &&
1806 mapping_can_writeback(vma->vm_file->f_mapping);
1810 * We account for memory if it's a private writeable mapping,
1811 * not hugepages and VM_NORESERVE wasn't set.
1813 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1816 * hugetlb has its own accounting separate from the core VM
1817 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1819 if (file && is_file_hugepages(file))
1822 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1825 unsigned long mmap_region(struct file *file, unsigned long addr,
1826 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1827 struct list_head *uf)
1829 struct mm_struct *mm = current->mm;
1830 struct vm_area_struct *vma, *prev, *merge;
1832 struct rb_node **rb_link, *rb_parent;
1833 unsigned long charged = 0;
1836 /* Check against address space limit. */
1837 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1838 unsigned long nr_pages;
1841 * MAP_FIXED may remove pages of mappings that intersects with
1842 * requested mapping. Account for the pages it would unmap.
1844 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1846 if (!may_expand_vm(mm, vm_flags,
1847 (len >> PAGE_SHIFT) - nr_pages))
1851 /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
1852 if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
1855 * Private writable mapping: check memory availability
1857 if (accountable_mapping(file, vm_flags)) {
1858 charged = len >> PAGE_SHIFT;
1859 if (security_vm_enough_memory_mm(mm, charged))
1861 vm_flags |= VM_ACCOUNT;
1865 * Can we just expand an old mapping?
1867 vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1868 NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1873 * Determine the object being mapped and call the appropriate
1874 * specific mapper. the address has already been validated, but
1875 * not unmapped, but the maps are removed from the list.
1877 vma = vm_area_alloc(mm);
1883 vma->vm_start = addr;
1884 vma->vm_end = addr + len;
1885 vma->vm_flags = vm_flags;
1886 vma->vm_page_prot = vm_get_page_prot(vm_flags);
1887 vma->vm_pgoff = pgoff;
1890 if (vm_flags & VM_SHARED) {
1891 error = mapping_map_writable(file->f_mapping);
1896 vma->vm_file = get_file(file);
1897 error = call_mmap(file, vma);
1899 goto unmap_and_free_vma;
1901 /* Can addr have changed??
1903 * Answer: Yes, several device drivers can do it in their
1904 * f_op->mmap method. -DaveM
1905 * Bug: If addr is changed, prev, rb_link, rb_parent should
1906 * be updated for vma_link()
1908 WARN_ON_ONCE(addr != vma->vm_start);
1910 addr = vma->vm_start;
1912 /* If vm_flags changed after call_mmap(), we should try merge vma again
1913 * as we may succeed this time.
1915 if (unlikely(vm_flags != vma->vm_flags && prev)) {
1916 merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
1917 NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1919 /* ->mmap() can change vma->vm_file and fput the original file. So
1920 * fput the vma->vm_file here or we would add an extra fput for file
1921 * and cause general protection fault ultimately.
1926 /* Update vm_flags to pick up the change. */
1927 vm_flags = vma->vm_flags;
1928 goto unmap_writable;
1932 vm_flags = vma->vm_flags;
1933 } else if (vm_flags & VM_SHARED) {
1934 error = shmem_zero_setup(vma);
1938 vma_set_anonymous(vma);
1941 /* Allow architectures to sanity-check the vm_flags */
1942 if (!arch_validate_flags(vma->vm_flags)) {
1945 goto unmap_and_free_vma;
1950 if (vma_link(mm, vma, prev, rb_link, rb_parent)) {
1953 goto unmap_and_free_vma;
1959 * vma_merge() calls khugepaged_enter_vma() either, the below
1960 * call covers the non-merge case.
1962 khugepaged_enter_vma(vma, vma->vm_flags);
1964 /* Once vma denies write, undo our temporary denial count */
1966 if (file && vm_flags & VM_SHARED)
1967 mapping_unmap_writable(file->f_mapping);
1968 file = vma->vm_file;
1970 perf_event_mmap(vma);
1972 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
1973 if (vm_flags & VM_LOCKED) {
1974 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1975 is_vm_hugetlb_page(vma) ||
1976 vma == get_gate_vma(current->mm))
1977 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1979 mm->locked_vm += (len >> PAGE_SHIFT);
1986 * New (or expanded) vma always get soft dirty status.
1987 * Otherwise user-space soft-dirty page tracker won't
1988 * be able to distinguish situation when vma area unmapped,
1989 * then new mapped in-place (which must be aimed as
1990 * a completely new data area).
1992 vma->vm_flags |= VM_SOFTDIRTY;
1994 vma_set_page_prot(vma);
2001 vma->vm_file = NULL;
2003 /* Undo any partial mapping done by a device driver. */
2004 unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
2005 if (vm_flags & VM_SHARED)
2006 mapping_unmap_writable(file->f_mapping);
2011 vm_unacct_memory(charged);
2016 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
2019 * We implement the search by looking for an rbtree node that
2020 * immediately follows a suitable gap. That is,
2021 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
2022 * - gap_end = vma->vm_start >= info->low_limit + length;
2023 * - gap_end - gap_start >= length
2026 struct mm_struct *mm = current->mm;
2027 struct vm_area_struct *vma;
2028 unsigned long length, low_limit, high_limit, gap_start, gap_end;
2030 MA_STATE(mas, &mm->mm_mt, 0, 0);
2032 /* Adjust search length to account for worst case alignment overhead */
2033 length = info->length + info->align_mask;
2034 if (length < info->length)
2037 mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
2040 gap += (info->align_offset - gap) & info->align_mask;
2042 /* Adjust search limits by the desired length */
2043 if (info->high_limit < length)
2045 high_limit = info->high_limit - length;
2047 if (info->low_limit > high_limit)
2049 low_limit = info->low_limit + length;
2051 /* Check if rbtree root looks promising */
2052 if (RB_EMPTY_ROOT(&mm->mm_rb))
2054 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2055 if (vma->rb_subtree_gap < length)
2059 /* Visit left subtree if it looks promising */
2060 gap_end = vm_start_gap(vma);
2061 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
2062 struct vm_area_struct *left =
2063 rb_entry(vma->vm_rb.rb_left,
2064 struct vm_area_struct, vm_rb);
2065 if (left->rb_subtree_gap >= length) {
2071 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2073 /* Check if current node has a suitable gap */
2074 if (gap_start > high_limit)
2076 if (gap_end >= low_limit &&
2077 gap_end > gap_start && gap_end - gap_start >= length)
2080 /* Visit right subtree if it looks promising */
2081 if (vma->vm_rb.rb_right) {
2082 struct vm_area_struct *right =
2083 rb_entry(vma->vm_rb.rb_right,
2084 struct vm_area_struct, vm_rb);
2085 if (right->rb_subtree_gap >= length) {
2091 /* Go back up the rbtree to find next candidate node */
2093 struct rb_node *prev = &vma->vm_rb;
2094 if (!rb_parent(prev))
2096 vma = rb_entry(rb_parent(prev),
2097 struct vm_area_struct, vm_rb);
2098 if (prev == vma->vm_rb.rb_left) {
2099 gap_start = vm_end_gap(vma->vm_prev);
2100 gap_end = vm_start_gap(vma);
2107 /* Check highest gap, which does not precede any rbtree node */
2108 gap_start = mm->highest_vm_end;
2109 gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
2110 if (gap_start > high_limit)
2114 /* We found a suitable gap. Clip it with the original low_limit. */
2115 if (gap_start < info->low_limit)
2116 gap_start = info->low_limit;
2118 /* Adjust gap address to the desired alignment */
2119 gap_start += (info->align_offset - gap_start) & info->align_mask;
2121 VM_BUG_ON(gap_start + info->length > info->high_limit);
2122 VM_BUG_ON(gap_start + info->length > gap_end);
2124 VM_BUG_ON(gap != gap_start);
2128 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
2130 struct mm_struct *mm = current->mm;
2131 struct vm_area_struct *vma = NULL;
2132 unsigned long length, low_limit, high_limit, gap_start, gap_end;
2135 MA_STATE(mas, &mm->mm_mt, 0, 0);
2138 /* Adjust search length to account for worst case alignment overhead */
2139 length = info->length + info->align_mask;
2140 if (length < info->length)
2143 mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
2145 gap = mas.last + 1 - info->length;
2146 gap -= (gap - info->align_offset) & info->align_mask;
2149 * Adjust search limits by the desired length.
2150 * See implementation comment at top of unmapped_area().
2152 gap_end = info->high_limit;
2153 if (gap_end < length)
2155 high_limit = gap_end - length;
2157 if (info->low_limit > high_limit)
2159 low_limit = info->low_limit + length;
2161 /* Check highest gap, which does not precede any rbtree node */
2162 gap_start = mm->highest_vm_end;
2163 if (gap_start <= high_limit)
2166 /* Check if rbtree root looks promising */
2167 if (RB_EMPTY_ROOT(&mm->mm_rb))
2169 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2170 if (vma->rb_subtree_gap < length)
2174 /* Visit right subtree if it looks promising */
2175 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2176 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
2177 struct vm_area_struct *right =
2178 rb_entry(vma->vm_rb.rb_right,
2179 struct vm_area_struct, vm_rb);
2180 if (right->rb_subtree_gap >= length) {
2187 /* Check if current node has a suitable gap */
2188 gap_end = vm_start_gap(vma);
2189 if (gap_end < low_limit)
2191 if (gap_start <= high_limit &&
2192 gap_end > gap_start && gap_end - gap_start >= length)
2195 /* Visit left subtree if it looks promising */
2196 if (vma->vm_rb.rb_left) {
2197 struct vm_area_struct *left =
2198 rb_entry(vma->vm_rb.rb_left,
2199 struct vm_area_struct, vm_rb);
2200 if (left->rb_subtree_gap >= length) {
2206 /* Go back up the rbtree to find next candidate node */
2208 struct rb_node *prev = &vma->vm_rb;
2209 if (!rb_parent(prev))
2211 vma = rb_entry(rb_parent(prev),
2212 struct vm_area_struct, vm_rb);
2213 if (prev == vma->vm_rb.rb_right) {
2214 gap_start = vma->vm_prev ?
2215 vm_end_gap(vma->vm_prev) : 0;
2222 /* We found a suitable gap. Clip it with the original high_limit. */
2223 if (gap_end > info->high_limit)
2224 gap_end = info->high_limit;
2227 /* Compute highest gap address at the desired alignment */
2228 gap_end -= info->length;
2229 gap_end -= (gap_end - info->align_offset) & info->align_mask;
2231 VM_BUG_ON(gap_end < info->low_limit);
2232 VM_BUG_ON(gap_end < gap_start);
2234 if (gap != gap_end) {
2235 pr_err("%s: %p Gap was found: mt %lu gap_end %lu\n", __func__,
2237 pr_err("window was %lu - %lu size %lu\n", info->high_limit,
2238 info->low_limit, length);
2239 pr_err("mas.min %lu max %lu mas.last %lu\n", mas.min, mas.max,
2241 pr_err("mas.index %lu align mask %lu offset %lu\n", mas.index,
2242 info->align_mask, info->align_offset);
2243 pr_err("rb_find_vma find on %lu => %p (%p)\n", mas.index,
2244 find_vma(mm, mas.index), vma);
2245 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2246 mt_dump(&mm->mm_mt);
2249 struct vm_area_struct *dv = mm->mmap;
2252 pr_err("vma %p %lu-%lu\n", dv, dv->vm_start, dv->vm_end);
2256 VM_BUG_ON(gap != gap_end);
2263 * Search for an unmapped address range.
2265 * We are looking for a range that:
2266 * - does not intersect with any VMA;
2267 * - is contained within the [low_limit, high_limit) interval;
2268 * - is at least the desired size.
2269 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
2271 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
2275 if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
2276 addr = unmapped_area_topdown(info);
2278 addr = unmapped_area(info);
2280 trace_vm_unmapped_area(addr, info);
2284 /* Get an address range which is currently unmapped.
2285 * For shmat() with addr=0.
2287 * Ugly calling convention alert:
2288 * Return value with the low bits set means error value,
2290 * if (ret & ~PAGE_MASK)
2293 * This function "knows" that -ENOMEM has the bits set.
2296 generic_get_unmapped_area(struct file *filp, unsigned long addr,
2297 unsigned long len, unsigned long pgoff,
2298 unsigned long flags)
2300 struct mm_struct *mm = current->mm;
2301 struct vm_area_struct *vma, *prev;
2302 struct vm_unmapped_area_info info;
2303 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2305 if (len > mmap_end - mmap_min_addr)
2308 if (flags & MAP_FIXED)
2312 addr = PAGE_ALIGN(addr);
2313 vma = find_vma_prev(mm, addr, &prev);
2314 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2315 (!vma || addr + len <= vm_start_gap(vma)) &&
2316 (!prev || addr >= vm_end_gap(prev)))
2322 info.low_limit = mm->mmap_base;
2323 info.high_limit = mmap_end;
2324 info.align_mask = 0;
2325 info.align_offset = 0;
2326 return vm_unmapped_area(&info);
2329 #ifndef HAVE_ARCH_UNMAPPED_AREA
2331 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2332 unsigned long len, unsigned long pgoff,
2333 unsigned long flags)
2335 return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
2340 * This mmap-allocator allocates new areas top-down from below the
2341 * stack's low limit (the base):
2344 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2345 unsigned long len, unsigned long pgoff,
2346 unsigned long flags)
2348 struct vm_area_struct *vma, *prev;
2349 struct mm_struct *mm = current->mm;
2350 struct vm_unmapped_area_info info;
2351 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2353 /* requested length too big for entire address space */
2354 if (len > mmap_end - mmap_min_addr)
2357 if (flags & MAP_FIXED)
2360 /* requesting a specific address */
2362 addr = PAGE_ALIGN(addr);
2363 vma = find_vma_prev(mm, addr, &prev);
2364 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2365 (!vma || addr + len <= vm_start_gap(vma)) &&
2366 (!prev || addr >= vm_end_gap(prev)))
2370 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2372 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2373 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2374 info.align_mask = 0;
2375 info.align_offset = 0;
2376 addr = vm_unmapped_area(&info);
2379 * A failed mmap() very likely causes application failure,
2380 * so fall back to the bottom-up function here. This scenario
2381 * can happen with large stack limits and large mmap()
2384 if (offset_in_page(addr)) {
2385 VM_BUG_ON(addr != -ENOMEM);
2387 info.low_limit = TASK_UNMAPPED_BASE;
2388 info.high_limit = mmap_end;
2389 addr = vm_unmapped_area(&info);
2395 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2397 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2398 unsigned long len, unsigned long pgoff,
2399 unsigned long flags)
2401 return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
2406 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2407 unsigned long pgoff, unsigned long flags)
2409 unsigned long (*get_area)(struct file *, unsigned long,
2410 unsigned long, unsigned long, unsigned long);
2412 unsigned long error = arch_mmap_check(addr, len, flags);
2416 /* Careful about overflows.. */
2417 if (len > TASK_SIZE)
2420 get_area = current->mm->get_unmapped_area;
2422 if (file->f_op->get_unmapped_area)
2423 get_area = file->f_op->get_unmapped_area;
2424 } else if (flags & MAP_SHARED) {
2426 * mmap_region() will call shmem_zero_setup() to create a file,
2427 * so use shmem's get_unmapped_area in case it can be huge.
2428 * do_mmap() will clear pgoff, so match alignment.
2431 get_area = shmem_get_unmapped_area;
2432 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
2433 /* Ensures that larger anonymous mappings are THP aligned. */
2434 get_area = thp_get_unmapped_area;
2437 addr = get_area(file, addr, len, pgoff, flags);
2438 if (IS_ERR_VALUE(addr))
2441 if (addr > TASK_SIZE - len)
2443 if (offset_in_page(addr))
2446 error = security_mmap_addr(addr);
2447 return error ? error : addr;
2450 EXPORT_SYMBOL(get_unmapped_area);
2453 * find_vma() - Find the VMA for a given address, or the next VMA.
2454 * @mm: The mm_struct to check
2455 * @addr: The address
2457 * Returns: The VMA associated with addr, or the next VMA.
2458 * May return %NULL in the case of no VMA at addr or above.
2460 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2462 struct vm_area_struct *vma;
2463 unsigned long index = addr;
2465 mmap_assert_locked(mm);
2466 /* Check the cache first. */
2467 vma = vmacache_find(mm, addr);
2471 vma = mt_find(&mm->mm_mt, &index, ULONG_MAX);
2473 vmacache_update(addr, vma);
2476 EXPORT_SYMBOL(find_vma);
2479 * find_vma_prev() - Find the VMA for a given address, or the next vma and
2480 * set %pprev to the previous VMA, if any.
2481 * @mm: The mm_struct to check
2482 * @addr: The address
2483 * @pprev: The pointer to set to the previous VMA
2485 * Note that RCU lock is missing here since the external mmap_lock() is used
2488 * Returns: The VMA associated with @addr, or the next vma.
2489 * May return %NULL in the case of no vma at addr or above.
2491 struct vm_area_struct *
2492 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2493 struct vm_area_struct **pprev)
2495 struct vm_area_struct *vma;
2496 MA_STATE(mas, &mm->mm_mt, addr, addr);
2498 vma = mas_walk(&mas);
2499 *pprev = mas_prev(&mas, 0);
2501 vma = mas_next(&mas, ULONG_MAX);
2506 * Verify that the stack growth is acceptable and
2507 * update accounting. This is shared with both the
2508 * grow-up and grow-down cases.
2510 static int acct_stack_growth(struct vm_area_struct *vma,
2511 unsigned long size, unsigned long grow)
2513 struct mm_struct *mm = vma->vm_mm;
2514 unsigned long new_start;
2516 /* address space limit tests */
2517 if (!may_expand_vm(mm, vma->vm_flags, grow))
2520 /* Stack limit test */
2521 if (size > rlimit(RLIMIT_STACK))
2524 /* mlock limit tests */
2525 if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
2528 /* Check to ensure the stack will not grow into a hugetlb-only region */
2529 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2531 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2535 * Overcommit.. This must be the final test, as it will
2536 * update security statistics.
2538 if (security_vm_enough_memory_mm(mm, grow))
2544 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2546 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2547 * vma is the last one with address > vma->vm_end. Have to extend vma.
2549 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2551 struct mm_struct *mm = vma->vm_mm;
2552 struct vm_area_struct *next;
2553 unsigned long gap_addr;
2555 MA_STATE(mas, &mm->mm_mt, 0, 0);
2558 if (!(vma->vm_flags & VM_GROWSUP))
2561 /* Guard against exceeding limits of the address space. */
2562 address &= PAGE_MASK;
2563 if (address >= (TASK_SIZE & PAGE_MASK))
2565 address += PAGE_SIZE;
2567 /* Enforce stack_guard_gap */
2568 gap_addr = address + stack_guard_gap;
2570 /* Guard against overflow */
2571 if (gap_addr < address || gap_addr > TASK_SIZE)
2572 gap_addr = TASK_SIZE;
2574 next = vma->vm_next;
2575 if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
2576 if (!(next->vm_flags & VM_GROWSUP))
2578 /* Check that both stack segments have the same anon_vma? */
2581 if (mas_preallocate(&mas, vma, GFP_KERNEL))
2584 /* We must make sure the anon_vma is allocated. */
2585 if (unlikely(anon_vma_prepare(vma))) {
2591 * vma->vm_start/vm_end cannot change under us because the caller
2592 * is required to hold the mmap_lock in read mode. We need the
2593 * anon_vma lock to serialize against concurrent expand_stacks.
2595 anon_vma_lock_write(vma->anon_vma);
2597 /* Somebody else might have raced and expanded it already */
2598 if (address > vma->vm_end) {
2599 unsigned long size, grow;
2601 size = address - vma->vm_start;
2602 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2605 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2606 error = acct_stack_growth(vma, size, grow);
2609 * vma_gap_update() doesn't support concurrent
2610 * updates, but we only hold a shared mmap_lock
2611 * lock here, so we need to protect against
2612 * concurrent vma expansions.
2613 * anon_vma_lock_write() doesn't help here, as
2614 * we don't guarantee that all growable vmas
2615 * in a mm share the same root anon vma.
2616 * So, we reuse mm->page_table_lock to guard
2617 * against concurrent vma expansions.
2619 spin_lock(&mm->page_table_lock);
2620 if (vma->vm_flags & VM_LOCKED)
2621 mm->locked_vm += grow;
2622 vm_stat_account(mm, vma->vm_flags, grow);
2623 anon_vma_interval_tree_pre_update_vma(vma);
2624 vma->vm_end = address;
2625 /* Overwrite old entry in mtree. */
2626 vma_mas_store(vma, &mas);
2627 anon_vma_interval_tree_post_update_vma(vma);
2629 vma_gap_update(vma->vm_next);
2631 mm->highest_vm_end = vm_end_gap(vma);
2632 spin_unlock(&mm->page_table_lock);
2634 perf_event_mmap(vma);
2638 anon_vma_unlock_write(vma->anon_vma);
2639 khugepaged_enter_vma(vma, vma->vm_flags);
2645 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2648 * vma is the first one with address < vma->vm_start. Have to extend vma.
2650 int expand_downwards(struct vm_area_struct *vma,
2651 unsigned long address)
2653 struct mm_struct *mm = vma->vm_mm;
2654 struct vm_area_struct *prev;
2656 MA_STATE(mas, &mm->mm_mt, 0, 0);
2659 address &= PAGE_MASK;
2660 if (address < mmap_min_addr)
2663 /* Enforce stack_guard_gap */
2664 prev = vma->vm_prev;
2665 /* Check that both stack segments have the same anon_vma? */
2666 if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2667 vma_is_accessible(prev)) {
2668 if (address - prev->vm_end < stack_guard_gap)
2672 if (mas_preallocate(&mas, vma, GFP_KERNEL))
2675 /* We must make sure the anon_vma is allocated. */
2676 if (unlikely(anon_vma_prepare(vma))) {
2682 * vma->vm_start/vm_end cannot change under us because the caller
2683 * is required to hold the mmap_lock in read mode. We need the
2684 * anon_vma lock to serialize against concurrent expand_stacks.
2686 anon_vma_lock_write(vma->anon_vma);
2688 /* Somebody else might have raced and expanded it already */
2689 if (address < vma->vm_start) {
2690 unsigned long size, grow;
2692 size = vma->vm_end - address;
2693 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2696 if (grow <= vma->vm_pgoff) {
2697 error = acct_stack_growth(vma, size, grow);
2700 * vma_gap_update() doesn't support concurrent
2701 * updates, but we only hold a shared mmap_lock
2702 * lock here, so we need to protect against
2703 * concurrent vma expansions.
2704 * anon_vma_lock_write() doesn't help here, as
2705 * we don't guarantee that all growable vmas
2706 * in a mm share the same root anon vma.
2707 * So, we reuse mm->page_table_lock to guard
2708 * against concurrent vma expansions.
2710 spin_lock(&mm->page_table_lock);
2711 if (vma->vm_flags & VM_LOCKED)
2712 mm->locked_vm += grow;
2713 vm_stat_account(mm, vma->vm_flags, grow);
2714 anon_vma_interval_tree_pre_update_vma(vma);
2715 vma->vm_start = address;
2716 vma->vm_pgoff -= grow;
2717 /* Overwrite old entry in mtree. */
2718 vma_mas_store(vma, &mas);
2719 anon_vma_interval_tree_post_update_vma(vma);
2720 vma_gap_update(vma);
2721 spin_unlock(&mm->page_table_lock);
2723 perf_event_mmap(vma);
2727 anon_vma_unlock_write(vma->anon_vma);
2728 khugepaged_enter_vma(vma, vma->vm_flags);
2734 /* enforced gap between the expanding stack and other mappings. */
2735 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2737 static int __init cmdline_parse_stack_guard_gap(char *p)
2742 val = simple_strtoul(p, &endptr, 10);
2744 stack_guard_gap = val << PAGE_SHIFT;
2748 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2750 #ifdef CONFIG_STACK_GROWSUP
2751 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2753 return expand_upwards(vma, address);
2756 struct vm_area_struct *
2757 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2759 struct vm_area_struct *vma, *prev;
2762 vma = find_vma_prev(mm, addr, &prev);
2763 if (vma && (vma->vm_start <= addr))
2765 if (!prev || expand_stack(prev, addr))
2767 if (prev->vm_flags & VM_LOCKED)
2768 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2772 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2774 return expand_downwards(vma, address);
2777 struct vm_area_struct *
2778 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2780 struct vm_area_struct *vma;
2781 unsigned long start;
2784 vma = find_vma(mm, addr);
2787 if (vma->vm_start <= addr)
2789 if (!(vma->vm_flags & VM_GROWSDOWN))
2791 start = vma->vm_start;
2792 if (expand_stack(vma, addr))
2794 if (vma->vm_flags & VM_LOCKED)
2795 populate_vma_page_range(vma, addr, start, NULL);
2800 EXPORT_SYMBOL_GPL(find_extend_vma);
2803 * Ok - we have the memory areas we should free on the vma list,
2804 * so release them, and do the vma updates.
2806 * Called with the mm semaphore held.
2808 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2810 unsigned long nr_accounted = 0;
2812 /* Update high watermark before we lower total_vm */
2813 update_hiwater_vm(mm);
2815 long nrpages = vma_pages(vma);
2817 if (vma->vm_flags & VM_ACCOUNT)
2818 nr_accounted += nrpages;
2819 vm_stat_account(mm, vma->vm_flags, -nrpages);
2820 vma = remove_vma(vma);
2822 vm_unacct_memory(nr_accounted);
2827 * Get rid of page table information in the indicated region.
2829 * Called with the mm semaphore held.
2831 static void unmap_region(struct mm_struct *mm,
2832 struct vm_area_struct *vma, struct vm_area_struct *prev,
2833 unsigned long start, unsigned long end)
2835 struct vm_area_struct *next = __vma_next(mm, prev);
2836 struct mmu_gather tlb;
2839 tlb_gather_mmu(&tlb, mm);
2840 update_hiwater_rss(mm);
2841 unmap_vmas(&tlb, vma, start, end);
2842 free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2843 next ? next->vm_start : USER_PGTABLES_CEILING);
2844 tlb_finish_mmu(&tlb);
2848 * Create a list of vma's touched by the unmap, removing them from the mm's
2849 * vma list as we go..
2852 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct ma_state *mas,
2853 struct vm_area_struct *vma, struct vm_area_struct *prev,
2856 struct vm_area_struct **insertion_point;
2857 struct vm_area_struct *tail_vma = NULL;
2859 insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2860 vma->vm_prev = NULL;
2861 mas_set_range(mas, vma->vm_start, end - 1);
2862 mas_store_prealloc(mas, NULL);
2864 vma_rb_erase(vma, &mm->mm_rb);
2865 if (vma->vm_flags & VM_LOCKED)
2866 mm->locked_vm -= vma_pages(vma);
2870 } while (vma && vma->vm_start < end);
2871 *insertion_point = vma;
2873 vma->vm_prev = prev;
2874 vma_gap_update(vma);
2876 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2877 tail_vma->vm_next = NULL;
2879 /* Kill the cache */
2880 vmacache_invalidate(mm);
2883 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2884 * VM_GROWSUP VMA. Such VMAs can change their size under
2885 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2887 if (vma && (vma->vm_flags & VM_GROWSDOWN))
2889 if (prev && (prev->vm_flags & VM_GROWSUP))
2895 * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
2896 * has already been checked or doesn't make sense to fail.
2898 int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2899 unsigned long addr, int new_below)
2901 struct vm_area_struct *new;
2905 if (vma->vm_ops && vma->vm_ops->may_split) {
2906 err = vma->vm_ops->may_split(vma, addr);
2911 new = vm_area_dup(vma);
2918 new->vm_start = addr;
2919 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2922 err = vma_dup_policy(vma, new);
2926 err = anon_vma_clone(new, vma);
2931 get_file(new->vm_file);
2933 if (new->vm_ops && new->vm_ops->open)
2934 new->vm_ops->open(new);
2937 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2938 ((addr - new->vm_start) >> PAGE_SHIFT), new);
2940 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2946 /* Avoid vm accounting in close() operation */
2947 new->vm_start = new->vm_end;
2949 /* Clean everything up if vma_adjust failed. */
2950 if (new->vm_ops && new->vm_ops->close)
2951 new->vm_ops->close(new);
2954 unlink_anon_vmas(new);
2956 mpol_put(vma_policy(new));
2964 * Split a vma into two pieces at address 'addr', a new vma is allocated
2965 * either for the first part or the tail.
2967 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2968 unsigned long addr, int new_below)
2970 if (mm->map_count >= sysctl_max_map_count)
2973 return __split_vma(mm, vma, addr, new_below);
2976 /* Munmap is split into 2 main parts -- this part which finds
2977 * what needs doing, and the areas themselves, which do the
2978 * work. This now handles partial unmappings.
2979 * Jeremy Fitzhardinge <jeremy@goop.org>
2981 int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2982 struct list_head *uf, bool downgrade)
2985 struct vm_area_struct *vma, *prev, *last;
2986 int error = -ENOMEM;
2987 MA_STATE(mas, &mm->mm_mt, 0, 0);
2989 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2992 len = PAGE_ALIGN(len);
2998 * arch_unmap() might do unmaps itself. It must be called
2999 * and finish any rbtree manipulation before this code
3000 * runs and also starts to manipulate the rbtree.
3002 arch_unmap(mm, start, end);
3004 /* Find the first overlapping VMA where start < vma->vm_end */
3005 vma = find_vma_intersection(mm, start, end);
3009 if (mas_preallocate(&mas, vma, GFP_KERNEL))
3011 prev = vma->vm_prev;
3014 * If we need to split any vma, do it now to save pain later.
3016 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
3017 * unmapped vm_area_struct will remain in use: so lower split_vma
3018 * places tmp vma above, and higher split_vma places tmp vma below.
3020 if (start > vma->vm_start) {
3023 * Make sure that map_count on return from munmap() will
3024 * not exceed its limit; but let map_count go just above
3025 * its limit temporarily, to help free resources as expected.
3027 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
3028 goto map_count_exceeded;
3030 error = __split_vma(mm, vma, start, 0);
3036 /* Does it split the last one? */
3037 last = find_vma(mm, end);
3038 if (last && end > last->vm_start) {
3039 error = __split_vma(mm, last, end, 1);
3043 vma = __vma_next(mm, prev);
3047 * If userfaultfd_unmap_prep returns an error the vmas
3048 * will remain split, but userland will get a
3049 * highly unexpected error anyway. This is no
3050 * different than the case where the first of the two
3051 * __split_vma fails, but we don't undo the first
3052 * split, despite we could. This is unlikely enough
3053 * failure that it's not worth optimizing it for.
3055 error = userfaultfd_unmap_prep(vma, start, end, uf);
3057 goto userfaultfd_error;
3060 /* Detach vmas from rbtree */
3061 if (!detach_vmas_to_be_unmapped(mm, &mas, vma, prev, end))
3065 mmap_write_downgrade(mm);
3067 unmap_region(mm, vma, prev, start, end);
3069 /* Fix up all other VM information */
3070 remove_vma_list(mm, vma);
3072 return downgrade ? 1 : 0;
3081 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
3082 struct list_head *uf)
3084 return __do_munmap(mm, start, len, uf, false);
3087 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
3090 struct mm_struct *mm = current->mm;
3093 if (mmap_write_lock_killable(mm))
3096 ret = __do_munmap(mm, start, len, &uf, downgrade);
3098 * Returning 1 indicates mmap_lock is downgraded.
3099 * But 1 is not legal return value of vm_munmap() and munmap(), reset
3100 * it to 0 before return.
3103 mmap_read_unlock(mm);
3106 mmap_write_unlock(mm);
3108 userfaultfd_unmap_complete(mm, &uf);
3112 int vm_munmap(unsigned long start, size_t len)
3114 return __vm_munmap(start, len, false);
3116 EXPORT_SYMBOL(vm_munmap);
3118 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
3120 addr = untagged_addr(addr);
3121 return __vm_munmap(addr, len, true);
3126 * Emulation of deprecated remap_file_pages() syscall.
3128 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
3129 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
3132 struct mm_struct *mm = current->mm;
3133 struct vm_area_struct *vma;
3134 unsigned long populate = 0;
3135 unsigned long ret = -EINVAL;
3138 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
3139 current->comm, current->pid);
3143 start = start & PAGE_MASK;
3144 size = size & PAGE_MASK;
3146 if (start + size <= start)
3149 /* Does pgoff wrap? */
3150 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
3153 if (mmap_write_lock_killable(mm))
3156 vma = vma_lookup(mm, start);
3158 if (!vma || !(vma->vm_flags & VM_SHARED))
3161 if (start + size > vma->vm_end) {
3162 struct vm_area_struct *next;
3164 for (next = vma->vm_next; next; next = next->vm_next) {
3165 /* hole between vmas ? */
3166 if (next->vm_start != next->vm_prev->vm_end)
3169 if (next->vm_file != vma->vm_file)
3172 if (next->vm_flags != vma->vm_flags)
3175 if (start + size <= next->vm_end)
3183 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
3184 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
3185 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
3187 flags &= MAP_NONBLOCK;
3188 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
3189 if (vma->vm_flags & VM_LOCKED)
3190 flags |= MAP_LOCKED;
3192 file = get_file(vma->vm_file);
3193 ret = do_mmap(vma->vm_file, start, size,
3194 prot, flags, pgoff, &populate, NULL);
3197 mmap_write_unlock(mm);
3199 mm_populate(ret, populate);
3200 if (!IS_ERR_VALUE(ret))
3206 * this is really a simplified "do_mmap". it only handles
3207 * anonymous maps. eventually we may be able to do some
3208 * brk-specific accounting here.
3210 static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
3212 struct mm_struct *mm = current->mm;
3213 struct vm_area_struct *vma, *prev;
3214 struct rb_node **rb_link, *rb_parent;
3215 pgoff_t pgoff = addr >> PAGE_SHIFT;
3217 unsigned long mapped_addr;
3220 /* Until we need other flags, refuse anything except VM_EXEC. */
3221 if ((flags & (~VM_EXEC)) != 0)
3223 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3225 mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3226 if (IS_ERR_VALUE(mapped_addr))
3229 error = mlock_future_check(mm, mm->def_flags, len);
3233 /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
3234 if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
3237 /* Check against address space limits *after* clearing old maps... */
3238 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3241 if (mm->map_count > sysctl_max_map_count)
3244 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3247 /* Can we just expand an old private anonymous mapping? */
3248 vma = vma_merge(mm, prev, addr, addr + len, flags,
3249 NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
3254 * create a vma struct for an anonymous mapping
3256 vma = vm_area_alloc(mm);
3258 vm_unacct_memory(len >> PAGE_SHIFT);
3262 vma_set_anonymous(vma);
3263 vma->vm_start = addr;
3264 vma->vm_end = addr + len;
3265 vma->vm_pgoff = pgoff;
3266 vma->vm_flags = flags;
3267 vma->vm_page_prot = vm_get_page_prot(flags);
3268 if (vma_link(mm, vma, prev, rb_link, rb_parent))
3272 perf_event_mmap(vma);
3273 mm->total_vm += len >> PAGE_SHIFT;
3274 mm->data_vm += len >> PAGE_SHIFT;
3275 if (flags & VM_LOCKED)
3276 mm->locked_vm += (len >> PAGE_SHIFT);
3277 vma->vm_flags |= VM_SOFTDIRTY;
3286 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3288 struct mm_struct *mm = current->mm;
3294 len = PAGE_ALIGN(request);
3300 if (mmap_write_lock_killable(mm))
3303 ret = do_brk_flags(addr, len, flags, &uf);
3304 populate = ((mm->def_flags & VM_LOCKED) != 0);
3305 mmap_write_unlock(mm);
3306 userfaultfd_unmap_complete(mm, &uf);
3307 if (populate && !ret)
3308 mm_populate(addr, len);
3311 EXPORT_SYMBOL(vm_brk_flags);
3313 int vm_brk(unsigned long addr, unsigned long len)
3315 return vm_brk_flags(addr, len, 0);
3317 EXPORT_SYMBOL(vm_brk);
3319 /* Release all mmaps. */
3320 void exit_mmap(struct mm_struct *mm)
3322 struct mmu_gather tlb;
3323 struct vm_area_struct *vma;
3324 unsigned long nr_accounted = 0;
3326 /* mm's last user has gone, and its about to be pulled down */
3327 mmu_notifier_release(mm);
3329 if (unlikely(mm_is_oom_victim(mm))) {
3331 * Manually reap the mm to free as much memory as possible.
3332 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3333 * this mm from further consideration. Taking mm->mmap_lock for
3334 * write after setting MMF_OOM_SKIP will guarantee that the oom
3335 * reaper will not run on this mm again after mmap_lock is
3338 * Nothing can be holding mm->mmap_lock here and the above call
3339 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
3340 * __oom_reap_task_mm() will not block.
3342 (void)__oom_reap_task_mm(mm);
3343 set_bit(MMF_OOM_SKIP, &mm->flags);
3346 mmap_write_lock(mm);
3351 /* Can happen if dup_mmap() received an OOM */
3352 mmap_write_unlock(mm);
3358 tlb_gather_mmu_fullmm(&tlb, mm);
3359 /* update_hiwater_rss(mm) here? but nobody should be looking */
3360 /* Use -1 here to ensure all VMAs in the mm are unmapped */
3361 unmap_vmas(&tlb, vma, 0, -1);
3362 free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3363 tlb_finish_mmu(&tlb);
3365 /* Walk the list again, actually closing and freeing it. */
3367 if (vma->vm_flags & VM_ACCOUNT)
3368 nr_accounted += vma_pages(vma);
3369 vma = remove_vma(vma);
3373 trace_exit_mmap(mm);
3374 __mt_destroy(&mm->mm_mt);
3376 mmap_write_unlock(mm);
3377 vm_unacct_memory(nr_accounted);
3380 /* Insert vm structure into process list sorted by address
3381 * and into the inode's i_mmap tree. If vm_file is non-NULL
3382 * then i_mmap_rwsem is taken here.
3384 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3386 struct vm_area_struct *prev;
3387 struct rb_node **rb_link, *rb_parent;
3388 unsigned long start = vma->vm_start;
3389 struct vm_area_struct *overlap = NULL;
3390 unsigned long charged = vma_pages(vma);
3392 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3393 &prev, &rb_link, &rb_parent))
3395 if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3398 overlap = mt_find(&mm->mm_mt, &start, vma->vm_end - 1);
3401 pr_err("Found vma ending at %lu\n", start - 1);
3402 pr_err("vma : %lu => %lu-%lu\n", (unsigned long)overlap,
3403 overlap->vm_start, overlap->vm_end - 1);
3404 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
3405 mt_dump(&mm->mm_mt);
3410 if ((vma->vm_flags & VM_ACCOUNT) &&
3411 security_vm_enough_memory_mm(mm, charged))
3415 * The vm_pgoff of a purely anonymous vma should be irrelevant
3416 * until its first write fault, when page's anon_vma and index
3417 * are set. But now set the vm_pgoff it will almost certainly
3418 * end up with (unless mremap moves it elsewhere before that
3419 * first wfault), so /proc/pid/maps tells a consistent story.
3421 * By setting it to reflect the virtual start address of the
3422 * vma, merges and splits can happen in a seamless way, just
3423 * using the existing file pgoff checks and manipulations.
3424 * Similarly in do_mmap and in do_brk_flags.
3426 if (vma_is_anonymous(vma)) {
3427 BUG_ON(vma->anon_vma);
3428 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3431 if (vma_link(mm, vma, prev, rb_link, rb_parent)) {
3432 vm_unacct_memory(charged);
3440 * Copy the vma structure to a new location in the same mm,
3441 * prior to moving page table entries, to effect an mremap move.
3443 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3444 unsigned long addr, unsigned long len, pgoff_t pgoff,
3445 bool *need_rmap_locks)
3447 struct vm_area_struct *vma = *vmap;
3448 unsigned long vma_start = vma->vm_start;
3449 struct mm_struct *mm = vma->vm_mm;
3450 struct vm_area_struct *new_vma, *prev;
3451 struct rb_node **rb_link, *rb_parent;
3452 bool faulted_in_anon_vma = true;
3453 unsigned long index = addr;
3457 * If anonymous vma has not yet been faulted, update new pgoff
3458 * to match new location, to increase its chance of merging.
3460 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3461 pgoff = addr >> PAGE_SHIFT;
3462 faulted_in_anon_vma = false;
3465 if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3466 return NULL; /* should never get here */
3467 if (mt_find(&mm->mm_mt, &index, addr+len - 1))
3469 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3470 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3471 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3474 * Source vma may have been merged into new_vma
3476 if (unlikely(vma_start >= new_vma->vm_start &&
3477 vma_start < new_vma->vm_end)) {
3479 * The only way we can get a vma_merge with
3480 * self during an mremap is if the vma hasn't
3481 * been faulted in yet and we were allowed to
3482 * reset the dst vma->vm_pgoff to the
3483 * destination address of the mremap to allow
3484 * the merge to happen. mremap must change the
3485 * vm_pgoff linearity between src and dst vmas
3486 * (in turn preventing a vma_merge) to be
3487 * safe. It is only safe to keep the vm_pgoff
3488 * linear if there are no pages mapped yet.
3490 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3491 *vmap = vma = new_vma;
3493 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3495 new_vma = vm_area_dup(vma);
3498 new_vma->vm_start = addr;
3499 new_vma->vm_end = addr + len;
3500 new_vma->vm_pgoff = pgoff;
3501 if (vma_dup_policy(vma, new_vma))
3503 if (anon_vma_clone(new_vma, vma))
3504 goto out_free_mempol;
3505 if (new_vma->vm_file)
3506 get_file(new_vma->vm_file);
3507 if (new_vma->vm_ops && new_vma->vm_ops->open)
3508 new_vma->vm_ops->open(new_vma);
3509 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3510 *need_rmap_locks = false;
3516 mpol_put(vma_policy(new_vma));
3518 vm_area_free(new_vma);
3525 * Return true if the calling process may expand its vm space by the passed
3528 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3530 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3533 if (is_data_mapping(flags) &&
3534 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3535 /* Workaround for Valgrind */
3536 if (rlimit(RLIMIT_DATA) == 0 &&
3537 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3540 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3541 current->comm, current->pid,
3542 (mm->data_vm + npages) << PAGE_SHIFT,
3543 rlimit(RLIMIT_DATA),
3544 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3546 if (!ignore_rlimit_data)
3553 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3555 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3557 if (is_exec_mapping(flags))
3558 mm->exec_vm += npages;
3559 else if (is_stack_mapping(flags))
3560 mm->stack_vm += npages;
3561 else if (is_data_mapping(flags))
3562 mm->data_vm += npages;
3565 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3568 * Having a close hook prevents vma merging regardless of flags.
3570 static void special_mapping_close(struct vm_area_struct *vma)
3574 static const char *special_mapping_name(struct vm_area_struct *vma)
3576 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3579 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3581 struct vm_special_mapping *sm = new_vma->vm_private_data;
3583 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3587 return sm->mremap(sm, new_vma);
3592 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3595 * Forbid splitting special mappings - kernel has expectations over
3596 * the number of pages in mapping. Together with VM_DONTEXPAND
3597 * the size of vma should stay the same over the special mapping's
3603 static const struct vm_operations_struct special_mapping_vmops = {
3604 .close = special_mapping_close,
3605 .fault = special_mapping_fault,
3606 .mremap = special_mapping_mremap,
3607 .name = special_mapping_name,
3608 /* vDSO code relies that VVAR can't be accessed remotely */
3610 .may_split = special_mapping_split,
3613 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3614 .close = special_mapping_close,
3615 .fault = special_mapping_fault,
3618 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3620 struct vm_area_struct *vma = vmf->vma;
3622 struct page **pages;
3624 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3625 pages = vma->vm_private_data;
3627 struct vm_special_mapping *sm = vma->vm_private_data;
3630 return sm->fault(sm, vmf->vma, vmf);
3635 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3639 struct page *page = *pages;
3645 return VM_FAULT_SIGBUS;
3648 static struct vm_area_struct *__install_special_mapping(
3649 struct mm_struct *mm,
3650 unsigned long addr, unsigned long len,
3651 unsigned long vm_flags, void *priv,
3652 const struct vm_operations_struct *ops)
3655 struct vm_area_struct *vma;
3658 vma = vm_area_alloc(mm);
3659 if (unlikely(vma == NULL))
3660 return ERR_PTR(-ENOMEM);
3662 vma->vm_start = addr;
3663 vma->vm_end = addr + len;
3665 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3666 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3667 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3670 vma->vm_private_data = priv;
3672 ret = insert_vm_struct(mm, vma);
3676 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3678 perf_event_mmap(vma);
3686 return ERR_PTR(ret);
3689 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3690 const struct vm_special_mapping *sm)
3692 return vma->vm_private_data == sm &&
3693 (vma->vm_ops == &special_mapping_vmops ||
3694 vma->vm_ops == &legacy_special_mapping_vmops);
3698 * Called with mm->mmap_lock held for writing.
3699 * Insert a new vma covering the given region, with the given flags.
3700 * Its pages are supplied by the given array of struct page *.
3701 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3702 * The region past the last page supplied will always produce SIGBUS.
3703 * The array pointer and the pages it points to are assumed to stay alive
3704 * for as long as this mapping might exist.
3706 struct vm_area_struct *_install_special_mapping(
3707 struct mm_struct *mm,
3708 unsigned long addr, unsigned long len,
3709 unsigned long vm_flags, const struct vm_special_mapping *spec)
3711 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3712 &special_mapping_vmops);
3715 int install_special_mapping(struct mm_struct *mm,
3716 unsigned long addr, unsigned long len,
3717 unsigned long vm_flags, struct page **pages)
3719 struct vm_area_struct *vma = __install_special_mapping(
3720 mm, addr, len, vm_flags, (void *)pages,
3721 &legacy_special_mapping_vmops);
3723 return PTR_ERR_OR_ZERO(vma);
3726 static DEFINE_MUTEX(mm_all_locks_mutex);
3728 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3730 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3732 * The LSB of head.next can't change from under us
3733 * because we hold the mm_all_locks_mutex.
3735 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3737 * We can safely modify head.next after taking the
3738 * anon_vma->root->rwsem. If some other vma in this mm shares
3739 * the same anon_vma we won't take it again.
3741 * No need of atomic instructions here, head.next
3742 * can't change from under us thanks to the
3743 * anon_vma->root->rwsem.
3745 if (__test_and_set_bit(0, (unsigned long *)
3746 &anon_vma->root->rb_root.rb_root.rb_node))
3751 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3753 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3755 * AS_MM_ALL_LOCKS can't change from under us because
3756 * we hold the mm_all_locks_mutex.
3758 * Operations on ->flags have to be atomic because
3759 * even if AS_MM_ALL_LOCKS is stable thanks to the
3760 * mm_all_locks_mutex, there may be other cpus
3761 * changing other bitflags in parallel to us.
3763 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3765 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3770 * This operation locks against the VM for all pte/vma/mm related
3771 * operations that could ever happen on a certain mm. This includes
3772 * vmtruncate, try_to_unmap, and all page faults.
3774 * The caller must take the mmap_lock in write mode before calling
3775 * mm_take_all_locks(). The caller isn't allowed to release the
3776 * mmap_lock until mm_drop_all_locks() returns.
3778 * mmap_lock in write mode is required in order to block all operations
3779 * that could modify pagetables and free pages without need of
3780 * altering the vma layout. It's also needed in write mode to avoid new
3781 * anon_vmas to be associated with existing vmas.
3783 * A single task can't take more than one mm_take_all_locks() in a row
3784 * or it would deadlock.
3786 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3787 * mapping->flags avoid to take the same lock twice, if more than one
3788 * vma in this mm is backed by the same anon_vma or address_space.
3790 * We take locks in following order, accordingly to comment at beginning
3792 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3794 * - all i_mmap_rwsem locks;
3795 * - all anon_vma->rwseml
3797 * We can take all locks within these types randomly because the VM code
3798 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3799 * mm_all_locks_mutex.
3801 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3802 * that may have to take thousand of locks.
3804 * mm_take_all_locks() can fail if it's interrupted by signals.
3806 int mm_take_all_locks(struct mm_struct *mm)
3808 struct vm_area_struct *vma;
3809 struct anon_vma_chain *avc;
3811 mmap_assert_write_locked(mm);
3813 mutex_lock(&mm_all_locks_mutex);
3815 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3816 if (signal_pending(current))
3818 if (vma->vm_file && vma->vm_file->f_mapping &&
3819 is_vm_hugetlb_page(vma))
3820 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3823 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3824 if (signal_pending(current))
3826 if (vma->vm_file && vma->vm_file->f_mapping &&
3827 !is_vm_hugetlb_page(vma))
3828 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3831 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3832 if (signal_pending(current))
3835 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3836 vm_lock_anon_vma(mm, avc->anon_vma);
3842 mm_drop_all_locks(mm);
3846 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3848 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3850 * The LSB of head.next can't change to 0 from under
3851 * us because we hold the mm_all_locks_mutex.
3853 * We must however clear the bitflag before unlocking
3854 * the vma so the users using the anon_vma->rb_root will
3855 * never see our bitflag.
3857 * No need of atomic instructions here, head.next
3858 * can't change from under us until we release the
3859 * anon_vma->root->rwsem.
3861 if (!__test_and_clear_bit(0, (unsigned long *)
3862 &anon_vma->root->rb_root.rb_root.rb_node))
3864 anon_vma_unlock_write(anon_vma);
3868 static void vm_unlock_mapping(struct address_space *mapping)
3870 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3872 * AS_MM_ALL_LOCKS can't change to 0 from under us
3873 * because we hold the mm_all_locks_mutex.
3875 i_mmap_unlock_write(mapping);
3876 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3883 * The mmap_lock cannot be released by the caller until
3884 * mm_drop_all_locks() returns.
3886 void mm_drop_all_locks(struct mm_struct *mm)
3888 struct vm_area_struct *vma;
3889 struct anon_vma_chain *avc;
3891 mmap_assert_write_locked(mm);
3892 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3894 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3896 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3897 vm_unlock_anon_vma(avc->anon_vma);
3898 if (vma->vm_file && vma->vm_file->f_mapping)
3899 vm_unlock_mapping(vma->vm_file->f_mapping);
3902 mutex_unlock(&mm_all_locks_mutex);
3906 * initialise the percpu counter for VM
3908 void __init mmap_init(void)
3912 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3917 * Initialise sysctl_user_reserve_kbytes.
3919 * This is intended to prevent a user from starting a single memory hogging
3920 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3923 * The default value is min(3% of free memory, 128MB)
3924 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3926 static int init_user_reserve(void)
3928 unsigned long free_kbytes;
3930 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3932 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3935 subsys_initcall(init_user_reserve);
3938 * Initialise sysctl_admin_reserve_kbytes.
3940 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3941 * to log in and kill a memory hogging process.
3943 * Systems with more than 256MB will reserve 8MB, enough to recover
3944 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3945 * only reserve 3% of free pages by default.
3947 static int init_admin_reserve(void)
3949 unsigned long free_kbytes;
3951 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3953 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3956 subsys_initcall(init_admin_reserve);
3959 * Reinititalise user and admin reserves if memory is added or removed.
3961 * The default user reserve max is 128MB, and the default max for the
3962 * admin reserve is 8MB. These are usually, but not always, enough to
3963 * enable recovery from a memory hogging process using login/sshd, a shell,
3964 * and tools like top. It may make sense to increase or even disable the
3965 * reserve depending on the existence of swap or variations in the recovery
3966 * tools. So, the admin may have changed them.
3968 * If memory is added and the reserves have been eliminated or increased above
3969 * the default max, then we'll trust the admin.
3971 * If memory is removed and there isn't enough free memory, then we
3972 * need to reset the reserves.
3974 * Otherwise keep the reserve set by the admin.
3976 static int reserve_mem_notifier(struct notifier_block *nb,
3977 unsigned long action, void *data)
3979 unsigned long tmp, free_kbytes;
3983 /* Default max is 128MB. Leave alone if modified by operator. */
3984 tmp = sysctl_user_reserve_kbytes;
3985 if (0 < tmp && tmp < (1UL << 17))
3986 init_user_reserve();
3988 /* Default max is 8MB. Leave alone if modified by operator. */
3989 tmp = sysctl_admin_reserve_kbytes;
3990 if (0 < tmp && tmp < (1UL << 13))
3991 init_admin_reserve();
3995 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3997 if (sysctl_user_reserve_kbytes > free_kbytes) {
3998 init_user_reserve();
3999 pr_info("vm.user_reserve_kbytes reset to %lu\n",
4000 sysctl_user_reserve_kbytes);
4003 if (sysctl_admin_reserve_kbytes > free_kbytes) {
4004 init_admin_reserve();
4005 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
4006 sysctl_admin_reserve_kbytes);
4015 static struct notifier_block reserve_mem_nb = {
4016 .notifier_call = reserve_mem_notifier,
4019 static int __meminit init_reserve_notifier(void)
4021 if (register_hotmemory_notifier(&reserve_mem_nb))
4022 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
4026 subsys_initcall(init_reserve_notifier);