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 #ifndef CONFIG_ARCH_HAS_VM_GET_PAGE_PROT
85 pgprot_t protection_map[16] __ro_after_init = {
89 [VM_WRITE | VM_READ] = __P011,
91 [VM_EXEC | VM_READ] = __P101,
92 [VM_EXEC | VM_WRITE] = __P110,
93 [VM_EXEC | VM_WRITE | VM_READ] = __P111,
95 [VM_SHARED | VM_READ] = __S001,
96 [VM_SHARED | VM_WRITE] = __S010,
97 [VM_SHARED | VM_WRITE | VM_READ] = __S011,
98 [VM_SHARED | VM_EXEC] = __S100,
99 [VM_SHARED | VM_EXEC | VM_READ] = __S101,
100 [VM_SHARED | VM_EXEC | VM_WRITE] = __S110,
101 [VM_SHARED | VM_EXEC | VM_WRITE | VM_READ] = __S111
103 DECLARE_VM_GET_PAGE_PROT
104 #endif /* CONFIG_ARCH_HAS_VM_GET_PAGE_PROT */
106 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
108 return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
111 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
112 void vma_set_page_prot(struct vm_area_struct *vma)
114 unsigned long vm_flags = vma->vm_flags;
115 pgprot_t vm_page_prot;
117 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
118 if (vma_wants_writenotify(vma, vm_page_prot)) {
119 vm_flags &= ~VM_SHARED;
120 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
122 /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
123 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
127 * Requires inode->i_mapping->i_mmap_rwsem
129 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
130 struct file *file, struct address_space *mapping)
132 if (vma->vm_flags & VM_SHARED)
133 mapping_unmap_writable(mapping);
135 flush_dcache_mmap_lock(mapping);
136 vma_interval_tree_remove(vma, &mapping->i_mmap);
137 flush_dcache_mmap_unlock(mapping);
141 * Unlink a file-based vm structure from its interval tree, to hide
142 * vma from rmap and vmtruncate before freeing its page tables.
144 void unlink_file_vma(struct vm_area_struct *vma)
146 struct file *file = vma->vm_file;
149 struct address_space *mapping = file->f_mapping;
150 i_mmap_lock_write(mapping);
151 __remove_shared_vm_struct(vma, file, mapping);
152 i_mmap_unlock_write(mapping);
157 * Close a vm structure and free it, returning the next.
159 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
161 struct vm_area_struct *next = vma->vm_next;
164 if (vma->vm_ops && vma->vm_ops->close)
165 vma->vm_ops->close(vma);
168 mpol_put(vma_policy(vma));
173 static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,
174 struct list_head *uf);
175 SYSCALL_DEFINE1(brk, unsigned long, brk)
177 unsigned long newbrk, oldbrk, origbrk;
178 struct mm_struct *mm = current->mm;
179 struct vm_area_struct *next;
180 unsigned long min_brk;
182 bool downgraded = false;
185 if (mmap_write_lock_killable(mm))
190 #ifdef CONFIG_COMPAT_BRK
192 * CONFIG_COMPAT_BRK can still be overridden by setting
193 * randomize_va_space to 2, which will still cause mm->start_brk
194 * to be arbitrarily shifted
196 if (current->brk_randomized)
197 min_brk = mm->start_brk;
199 min_brk = mm->end_data;
201 min_brk = mm->start_brk;
207 * Check against rlimit here. If this check is done later after the test
208 * of oldbrk with newbrk then it can escape the test and let the data
209 * segment grow beyond its set limit the in case where the limit is
210 * not page aligned -Ram Gupta
212 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
213 mm->end_data, mm->start_data))
216 newbrk = PAGE_ALIGN(brk);
217 oldbrk = PAGE_ALIGN(mm->brk);
218 if (oldbrk == newbrk) {
224 * Always allow shrinking brk.
225 * __do_munmap() may downgrade mmap_lock to read.
227 if (brk <= mm->brk) {
231 * mm->brk must to be protected by write mmap_lock so update it
232 * before downgrading mmap_lock. When __do_munmap() fails,
233 * mm->brk will be restored from origbrk.
236 ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
240 } else if (ret == 1) {
246 /* Check against existing mmap mappings. */
247 next = find_vma(mm, oldbrk);
248 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
251 /* Ok, looks good - let it rip. */
252 if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
257 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
259 mmap_read_unlock(mm);
261 mmap_write_unlock(mm);
262 userfaultfd_unmap_complete(mm, &uf);
264 mm_populate(oldbrk, newbrk - oldbrk);
268 mmap_write_unlock(mm);
272 static inline unsigned long vma_compute_gap(struct vm_area_struct *vma)
274 unsigned long gap, prev_end;
277 * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
278 * allow two stack_guard_gaps between them here, and when choosing
279 * an unmapped area; whereas when expanding we only require one.
280 * That's a little inconsistent, but keeps the code here simpler.
282 gap = vm_start_gap(vma);
284 prev_end = vm_end_gap(vma->vm_prev);
293 #ifdef CONFIG_DEBUG_VM_RB
294 static unsigned long vma_compute_subtree_gap(struct vm_area_struct *vma)
296 unsigned long max = vma_compute_gap(vma), subtree_gap;
297 if (vma->vm_rb.rb_left) {
298 subtree_gap = rb_entry(vma->vm_rb.rb_left,
299 struct vm_area_struct, vm_rb)->rb_subtree_gap;
300 if (subtree_gap > max)
303 if (vma->vm_rb.rb_right) {
304 subtree_gap = rb_entry(vma->vm_rb.rb_right,
305 struct vm_area_struct, vm_rb)->rb_subtree_gap;
306 if (subtree_gap > max)
312 static int browse_rb(struct mm_struct *mm)
314 struct rb_root *root = &mm->mm_rb;
315 int i = 0, j, bug = 0;
316 struct rb_node *nd, *pn = NULL;
317 unsigned long prev = 0, pend = 0;
319 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
320 struct vm_area_struct *vma;
321 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
322 if (vma->vm_start < prev) {
323 pr_emerg("vm_start %lx < prev %lx\n",
324 vma->vm_start, prev);
327 if (vma->vm_start < pend) {
328 pr_emerg("vm_start %lx < pend %lx\n",
329 vma->vm_start, pend);
332 if (vma->vm_start > vma->vm_end) {
333 pr_emerg("vm_start %lx > vm_end %lx\n",
334 vma->vm_start, vma->vm_end);
337 spin_lock(&mm->page_table_lock);
338 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
339 pr_emerg("free gap %lx, correct %lx\n",
341 vma_compute_subtree_gap(vma));
344 spin_unlock(&mm->page_table_lock);
347 prev = vma->vm_start;
351 for (nd = pn; nd; nd = rb_prev(nd))
354 pr_emerg("backwards %d, forwards %d\n", j, i);
360 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
364 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
365 struct vm_area_struct *vma;
366 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
367 VM_BUG_ON_VMA(vma != ignore &&
368 vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
373 static void validate_mm(struct mm_struct *mm)
377 unsigned long highest_address = 0;
378 struct vm_area_struct *vma = mm->mmap;
381 struct anon_vma *anon_vma = vma->anon_vma;
382 struct anon_vma_chain *avc;
385 anon_vma_lock_read(anon_vma);
386 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
387 anon_vma_interval_tree_verify(avc);
388 anon_vma_unlock_read(anon_vma);
391 highest_address = vm_end_gap(vma);
395 if (i != mm->map_count) {
396 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
399 if (highest_address != mm->highest_vm_end) {
400 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
401 mm->highest_vm_end, highest_address);
405 if (i != mm->map_count) {
407 pr_emerg("map_count %d rb %d\n", mm->map_count, i);
410 VM_BUG_ON_MM(bug, mm);
413 #define validate_mm_rb(root, ignore) do { } while (0)
414 #define validate_mm(mm) do { } while (0)
417 RB_DECLARE_CALLBACKS_MAX(static, vma_gap_callbacks,
418 struct vm_area_struct, vm_rb,
419 unsigned long, rb_subtree_gap, vma_compute_gap)
422 * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
423 * vma->vm_prev->vm_end values changed, without modifying the vma's position
426 static void vma_gap_update(struct vm_area_struct *vma)
429 * As it turns out, RB_DECLARE_CALLBACKS_MAX() already created
430 * a callback function that does exactly what we want.
432 vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
435 static inline void vma_rb_insert(struct vm_area_struct *vma,
436 struct rb_root *root)
438 /* All rb_subtree_gap values must be consistent prior to insertion */
439 validate_mm_rb(root, NULL);
441 rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
444 static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
447 * Note rb_erase_augmented is a fairly large inline function,
448 * so make sure we instantiate it only once with our desired
449 * augmented rbtree callbacks.
451 rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
454 static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
455 struct rb_root *root,
456 struct vm_area_struct *ignore)
459 * All rb_subtree_gap values must be consistent prior to erase,
460 * with the possible exception of
462 * a. the "next" vma being erased if next->vm_start was reduced in
463 * __vma_adjust() -> __vma_unlink()
464 * b. the vma being erased in detach_vmas_to_be_unmapped() ->
467 validate_mm_rb(root, ignore);
469 __vma_rb_erase(vma, root);
472 static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
473 struct rb_root *root)
475 vma_rb_erase_ignore(vma, root, vma);
479 * vma has some anon_vma assigned, and is already inserted on that
480 * anon_vma's interval trees.
482 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
483 * vma must be removed from the anon_vma's interval trees using
484 * anon_vma_interval_tree_pre_update_vma().
486 * After the update, the vma will be reinserted using
487 * anon_vma_interval_tree_post_update_vma().
489 * The entire update must be protected by exclusive mmap_lock and by
490 * the root anon_vma's mutex.
493 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
495 struct anon_vma_chain *avc;
497 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
498 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
502 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
504 struct anon_vma_chain *avc;
506 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
507 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
510 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
511 unsigned long end, struct vm_area_struct **pprev,
512 struct rb_node ***rb_link, struct rb_node **rb_parent)
514 struct rb_node **__rb_link, *__rb_parent, *rb_prev;
516 mmap_assert_locked(mm);
517 __rb_link = &mm->mm_rb.rb_node;
518 rb_prev = __rb_parent = NULL;
521 struct vm_area_struct *vma_tmp;
523 __rb_parent = *__rb_link;
524 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
526 if (vma_tmp->vm_end > addr) {
527 /* Fail if an existing vma overlaps the area */
528 if (vma_tmp->vm_start < end)
530 __rb_link = &__rb_parent->rb_left;
532 rb_prev = __rb_parent;
533 __rb_link = &__rb_parent->rb_right;
539 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
540 *rb_link = __rb_link;
541 *rb_parent = __rb_parent;
546 * vma_next() - Get the next VMA.
547 * @mm: The mm_struct.
548 * @vma: The current vma.
550 * If @vma is NULL, return the first vma in the mm.
552 * Returns: The next VMA after @vma.
554 static inline struct vm_area_struct *vma_next(struct mm_struct *mm,
555 struct vm_area_struct *vma)
564 * munmap_vma_range() - munmap VMAs that overlap a range.
566 * @start: The start of the range.
567 * @len: The length of the range.
568 * @pprev: pointer to the pointer that will be set to previous vm_area_struct
569 * @rb_link: the rb_node
570 * @rb_parent: the parent rb_node
572 * Find all the vm_area_struct that overlap from @start to
573 * @end and munmap them. Set @pprev to the previous vm_area_struct.
575 * Returns: -ENOMEM on munmap failure or 0 on success.
578 munmap_vma_range(struct mm_struct *mm, unsigned long start, unsigned long len,
579 struct vm_area_struct **pprev, struct rb_node ***link,
580 struct rb_node **parent, struct list_head *uf)
583 while (find_vma_links(mm, start, start + len, pprev, link, parent))
584 if (do_munmap(mm, start, len, uf))
589 static unsigned long count_vma_pages_range(struct mm_struct *mm,
590 unsigned long addr, unsigned long end)
592 unsigned long nr_pages = 0;
593 struct vm_area_struct *vma;
595 /* Find first overlapping mapping */
596 vma = find_vma_intersection(mm, addr, end);
600 nr_pages = (min(end, vma->vm_end) -
601 max(addr, vma->vm_start)) >> PAGE_SHIFT;
603 /* Iterate over the rest of the overlaps */
604 for (vma = vma->vm_next; vma; vma = vma->vm_next) {
605 unsigned long overlap_len;
607 if (vma->vm_start > end)
610 overlap_len = min(end, vma->vm_end) - vma->vm_start;
611 nr_pages += overlap_len >> PAGE_SHIFT;
617 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
618 struct rb_node **rb_link, struct rb_node *rb_parent)
620 /* Update tracking information for the gap following the new vma. */
622 vma_gap_update(vma->vm_next);
624 mm->highest_vm_end = vm_end_gap(vma);
627 * vma->vm_prev wasn't known when we followed the rbtree to find the
628 * correct insertion point for that vma. As a result, we could not
629 * update the vma vm_rb parents rb_subtree_gap values on the way down.
630 * So, we first insert the vma with a zero rb_subtree_gap value
631 * (to be consistent with what we did on the way down), and then
632 * immediately update the gap to the correct value. Finally we
633 * rebalance the rbtree after all augmented values have been set.
635 rb_link_node(&vma->vm_rb, rb_parent, rb_link);
636 vma->rb_subtree_gap = 0;
638 vma_rb_insert(vma, &mm->mm_rb);
641 static void __vma_link_file(struct vm_area_struct *vma)
647 struct address_space *mapping = file->f_mapping;
649 if (vma->vm_flags & VM_SHARED)
650 mapping_allow_writable(mapping);
652 flush_dcache_mmap_lock(mapping);
653 vma_interval_tree_insert(vma, &mapping->i_mmap);
654 flush_dcache_mmap_unlock(mapping);
659 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
660 struct vm_area_struct *prev, struct rb_node **rb_link,
661 struct rb_node *rb_parent)
663 __vma_link_list(mm, vma, prev);
664 __vma_link_rb(mm, vma, rb_link, rb_parent);
667 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
668 struct vm_area_struct *prev, struct rb_node **rb_link,
669 struct rb_node *rb_parent)
671 struct address_space *mapping = NULL;
674 mapping = vma->vm_file->f_mapping;
675 i_mmap_lock_write(mapping);
678 __vma_link(mm, vma, prev, rb_link, rb_parent);
679 __vma_link_file(vma);
682 i_mmap_unlock_write(mapping);
689 * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
690 * mm's list and rbtree. It has already been inserted into the interval tree.
692 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
694 struct vm_area_struct *prev;
695 struct rb_node **rb_link, *rb_parent;
697 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
698 &prev, &rb_link, &rb_parent))
700 __vma_link(mm, vma, prev, rb_link, rb_parent);
704 static __always_inline void __vma_unlink(struct mm_struct *mm,
705 struct vm_area_struct *vma,
706 struct vm_area_struct *ignore)
708 vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
709 __vma_unlink_list(mm, vma);
711 vmacache_invalidate(mm);
715 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
716 * is already present in an i_mmap tree without adjusting the tree.
717 * The following helper function should be used when such adjustments
718 * are necessary. The "insert" vma (if any) is to be inserted
719 * before we drop the necessary locks.
721 int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
722 unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
723 struct vm_area_struct *expand)
725 struct mm_struct *mm = vma->vm_mm;
726 struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
727 struct address_space *mapping = NULL;
728 struct rb_root_cached *root = NULL;
729 struct anon_vma *anon_vma = NULL;
730 struct file *file = vma->vm_file;
731 bool start_changed = false, end_changed = false;
732 long adjust_next = 0;
735 if (next && !insert) {
736 struct vm_area_struct *exporter = NULL, *importer = NULL;
738 if (end >= next->vm_end) {
740 * vma expands, overlapping all the next, and
741 * perhaps the one after too (mprotect case 6).
742 * The only other cases that gets here are
743 * case 1, case 7 and case 8.
745 if (next == expand) {
747 * The only case where we don't expand "vma"
748 * and we expand "next" instead is case 8.
750 VM_WARN_ON(end != next->vm_end);
752 * remove_next == 3 means we're
753 * removing "vma" and that to do so we
754 * swapped "vma" and "next".
757 VM_WARN_ON(file != next->vm_file);
760 VM_WARN_ON(expand != vma);
762 * case 1, 6, 7, remove_next == 2 is case 6,
763 * remove_next == 1 is case 1 or 7.
765 remove_next = 1 + (end > next->vm_end);
766 VM_WARN_ON(remove_next == 2 &&
767 end != next->vm_next->vm_end);
768 /* trim end to next, for case 6 first pass */
776 * If next doesn't have anon_vma, import from vma after
777 * next, if the vma overlaps with it.
779 if (remove_next == 2 && !next->anon_vma)
780 exporter = next->vm_next;
782 } else if (end > next->vm_start) {
784 * vma expands, overlapping part of the next:
785 * mprotect case 5 shifting the boundary up.
787 adjust_next = (end - next->vm_start);
790 VM_WARN_ON(expand != importer);
791 } else if (end < vma->vm_end) {
793 * vma shrinks, and !insert tells it's not
794 * split_vma inserting another: so it must be
795 * mprotect case 4 shifting the boundary down.
797 adjust_next = -(vma->vm_end - end);
800 VM_WARN_ON(expand != importer);
804 * Easily overlooked: when mprotect shifts the boundary,
805 * make sure the expanding vma has anon_vma set if the
806 * shrinking vma had, to cover any anon pages imported.
808 if (exporter && exporter->anon_vma && !importer->anon_vma) {
811 importer->anon_vma = exporter->anon_vma;
812 error = anon_vma_clone(importer, exporter);
818 vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
821 mapping = file->f_mapping;
822 root = &mapping->i_mmap;
823 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
826 uprobe_munmap(next, next->vm_start, next->vm_end);
828 i_mmap_lock_write(mapping);
831 * Put into interval tree now, so instantiated pages
832 * are visible to arm/parisc __flush_dcache_page
833 * throughout; but we cannot insert into address
834 * space until vma start or end is updated.
836 __vma_link_file(insert);
840 anon_vma = vma->anon_vma;
841 if (!anon_vma && adjust_next)
842 anon_vma = next->anon_vma;
844 VM_WARN_ON(adjust_next && next->anon_vma &&
845 anon_vma != next->anon_vma);
846 anon_vma_lock_write(anon_vma);
847 anon_vma_interval_tree_pre_update_vma(vma);
849 anon_vma_interval_tree_pre_update_vma(next);
853 flush_dcache_mmap_lock(mapping);
854 vma_interval_tree_remove(vma, root);
856 vma_interval_tree_remove(next, root);
859 if (start != vma->vm_start) {
860 vma->vm_start = start;
861 start_changed = true;
863 if (end != vma->vm_end) {
867 vma->vm_pgoff = pgoff;
869 next->vm_start += adjust_next;
870 next->vm_pgoff += adjust_next >> PAGE_SHIFT;
875 vma_interval_tree_insert(next, root);
876 vma_interval_tree_insert(vma, root);
877 flush_dcache_mmap_unlock(mapping);
882 * vma_merge has merged next into vma, and needs
883 * us to remove next before dropping the locks.
885 if (remove_next != 3)
886 __vma_unlink(mm, next, next);
889 * vma is not before next if they've been
892 * pre-swap() next->vm_start was reduced so
893 * tell validate_mm_rb to ignore pre-swap()
894 * "next" (which is stored in post-swap()
897 __vma_unlink(mm, next, vma);
899 __remove_shared_vm_struct(next, file, mapping);
902 * split_vma has split insert from vma, and needs
903 * us to insert it before dropping the locks
904 * (it may either follow vma or precede it).
906 __insert_vm_struct(mm, insert);
912 mm->highest_vm_end = vm_end_gap(vma);
913 else if (!adjust_next)
914 vma_gap_update(next);
919 anon_vma_interval_tree_post_update_vma(vma);
921 anon_vma_interval_tree_post_update_vma(next);
922 anon_vma_unlock_write(anon_vma);
926 i_mmap_unlock_write(mapping);
935 uprobe_munmap(next, next->vm_start, next->vm_end);
939 anon_vma_merge(vma, next);
941 mpol_put(vma_policy(next));
944 * In mprotect's case 6 (see comments on vma_merge),
945 * we must remove another next too. It would clutter
946 * up the code too much to do both in one go.
948 if (remove_next != 3) {
950 * If "next" was removed and vma->vm_end was
951 * expanded (up) over it, in turn
952 * "next->vm_prev->vm_end" changed and the
953 * "vma->vm_next" gap must be updated.
958 * For the scope of the comment "next" and
959 * "vma" considered pre-swap(): if "vma" was
960 * removed, next->vm_start was expanded (down)
961 * over it and the "next" gap must be updated.
962 * Because of the swap() the post-swap() "vma"
963 * actually points to pre-swap() "next"
964 * (post-swap() "next" as opposed is now a
969 if (remove_next == 2) {
975 vma_gap_update(next);
978 * If remove_next == 2 we obviously can't
981 * If remove_next == 3 we can't reach this
982 * path because pre-swap() next is always not
983 * NULL. pre-swap() "next" is not being
984 * removed and its next->vm_end is not altered
985 * (and furthermore "end" already matches
986 * next->vm_end in remove_next == 3).
988 * We reach this only in the remove_next == 1
989 * case if the "next" vma that was removed was
990 * the highest vma of the mm. However in such
991 * case next->vm_end == "end" and the extended
992 * "vma" has vma->vm_end == next->vm_end so
993 * mm->highest_vm_end doesn't need any update
994 * in remove_next == 1 case.
996 VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
1000 uprobe_mmap(insert);
1008 * If the vma has a ->close operation then the driver probably needs to release
1009 * per-vma resources, so we don't attempt to merge those.
1011 static inline int is_mergeable_vma(struct vm_area_struct *vma,
1012 struct file *file, unsigned long vm_flags,
1013 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1014 struct anon_vma_name *anon_name)
1017 * VM_SOFTDIRTY should not prevent from VMA merging, if we
1018 * match the flags but dirty bit -- the caller should mark
1019 * merged VMA as dirty. If dirty bit won't be excluded from
1020 * comparison, we increase pressure on the memory system forcing
1021 * the kernel to generate new VMAs when old one could be
1024 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
1026 if (vma->vm_file != file)
1028 if (vma->vm_ops && vma->vm_ops->close)
1030 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
1032 if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
1037 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
1038 struct anon_vma *anon_vma2,
1039 struct vm_area_struct *vma)
1042 * The list_is_singular() test is to avoid merging VMA cloned from
1043 * parents. This can improve scalability caused by anon_vma lock.
1045 if ((!anon_vma1 || !anon_vma2) && (!vma ||
1046 list_is_singular(&vma->anon_vma_chain)))
1048 return anon_vma1 == anon_vma2;
1052 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1053 * in front of (at a lower virtual address and file offset than) the vma.
1055 * We cannot merge two vmas if they have differently assigned (non-NULL)
1056 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1058 * We don't check here for the merged mmap wrapping around the end of pagecache
1059 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
1060 * wrap, nor mmaps which cover the final page at index -1UL.
1063 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
1064 struct anon_vma *anon_vma, struct file *file,
1066 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1067 struct anon_vma_name *anon_name)
1069 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1070 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1071 if (vma->vm_pgoff == vm_pgoff)
1078 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1079 * beyond (at a higher virtual address and file offset than) the vma.
1081 * We cannot merge two vmas if they have differently assigned (non-NULL)
1082 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1085 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
1086 struct anon_vma *anon_vma, struct file *file,
1088 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1089 struct anon_vma_name *anon_name)
1091 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1092 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1094 vm_pglen = vma_pages(vma);
1095 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
1102 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
1103 * figure out whether that can be merged with its predecessor or its
1104 * successor. Or both (it neatly fills a hole).
1106 * In most cases - when called for mmap, brk or mremap - [addr,end) is
1107 * certain not to be mapped by the time vma_merge is called; but when
1108 * called for mprotect, it is certain to be already mapped (either at
1109 * an offset within prev, or at the start of next), and the flags of
1110 * this area are about to be changed to vm_flags - and the no-change
1111 * case has already been eliminated.
1113 * The following mprotect cases have to be considered, where AAAA is
1114 * the area passed down from mprotect_fixup, never extending beyond one
1115 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
1118 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN
1119 * cannot merge might become might become
1120 * PPNNNNNNNNNN PPPPPPPPPPNN
1121 * mmap, brk or case 4 below case 5 below
1124 * PPPP NNNN PPPPNNNNXXXX
1125 * might become might become
1126 * PPPPPPPPPPPP 1 or PPPPPPPPPPPP 6 or
1127 * PPPPPPPPNNNN 2 or PPPPPPPPXXXX 7 or
1128 * PPPPNNNNNNNN 3 PPPPXXXXXXXX 8
1130 * It is important for case 8 that the vma NNNN overlapping the
1131 * region AAAA is never going to extended over XXXX. Instead XXXX must
1132 * be extended in region AAAA and NNNN must be removed. This way in
1133 * all cases where vma_merge succeeds, the moment vma_adjust drops the
1134 * rmap_locks, the properties of the merged vma will be already
1135 * correct for the whole merged range. Some of those properties like
1136 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1137 * be correct for the whole merged range immediately after the
1138 * rmap_locks are released. Otherwise if XXXX would be removed and
1139 * NNNN would be extended over the XXXX range, remove_migration_ptes
1140 * or other rmap walkers (if working on addresses beyond the "end"
1141 * parameter) may establish ptes with the wrong permissions of NNNN
1142 * instead of the right permissions of XXXX.
1144 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1145 struct vm_area_struct *prev, unsigned long addr,
1146 unsigned long end, unsigned long vm_flags,
1147 struct anon_vma *anon_vma, struct file *file,
1148 pgoff_t pgoff, struct mempolicy *policy,
1149 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1150 struct anon_vma_name *anon_name)
1152 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1153 struct vm_area_struct *area, *next;
1157 * We later require that vma->vm_flags == vm_flags,
1158 * so this tests vma->vm_flags & VM_SPECIAL, too.
1160 if (vm_flags & VM_SPECIAL)
1163 next = vma_next(mm, prev);
1165 if (area && area->vm_end == end) /* cases 6, 7, 8 */
1166 next = next->vm_next;
1168 /* verify some invariant that must be enforced by the caller */
1169 VM_WARN_ON(prev && addr <= prev->vm_start);
1170 VM_WARN_ON(area && end > area->vm_end);
1171 VM_WARN_ON(addr >= end);
1174 * Can it merge with the predecessor?
1176 if (prev && prev->vm_end == addr &&
1177 mpol_equal(vma_policy(prev), policy) &&
1178 can_vma_merge_after(prev, vm_flags,
1179 anon_vma, file, pgoff,
1180 vm_userfaultfd_ctx, anon_name)) {
1182 * OK, it can. Can we now merge in the successor as well?
1184 if (next && end == next->vm_start &&
1185 mpol_equal(policy, vma_policy(next)) &&
1186 can_vma_merge_before(next, vm_flags,
1189 vm_userfaultfd_ctx, anon_name) &&
1190 is_mergeable_anon_vma(prev->anon_vma,
1191 next->anon_vma, NULL)) {
1193 err = __vma_adjust(prev, prev->vm_start,
1194 next->vm_end, prev->vm_pgoff, NULL,
1196 } else /* cases 2, 5, 7 */
1197 err = __vma_adjust(prev, prev->vm_start,
1198 end, prev->vm_pgoff, NULL, prev);
1201 khugepaged_enter_vma(prev, vm_flags);
1206 * Can this new request be merged in front of next?
1208 if (next && end == next->vm_start &&
1209 mpol_equal(policy, vma_policy(next)) &&
1210 can_vma_merge_before(next, vm_flags,
1211 anon_vma, file, pgoff+pglen,
1212 vm_userfaultfd_ctx, anon_name)) {
1213 if (prev && addr < prev->vm_end) /* case 4 */
1214 err = __vma_adjust(prev, prev->vm_start,
1215 addr, prev->vm_pgoff, NULL, next);
1216 else { /* cases 3, 8 */
1217 err = __vma_adjust(area, addr, next->vm_end,
1218 next->vm_pgoff - pglen, NULL, next);
1220 * In case 3 area is already equal to next and
1221 * this is a noop, but in case 8 "area" has
1222 * been removed and next was expanded over it.
1228 khugepaged_enter_vma(area, vm_flags);
1236 * Rough compatibility check to quickly see if it's even worth looking
1237 * at sharing an anon_vma.
1239 * They need to have the same vm_file, and the flags can only differ
1240 * in things that mprotect may change.
1242 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1243 * we can merge the two vma's. For example, we refuse to merge a vma if
1244 * there is a vm_ops->close() function, because that indicates that the
1245 * driver is doing some kind of reference counting. But that doesn't
1246 * really matter for the anon_vma sharing case.
1248 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1250 return a->vm_end == b->vm_start &&
1251 mpol_equal(vma_policy(a), vma_policy(b)) &&
1252 a->vm_file == b->vm_file &&
1253 !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1254 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1258 * Do some basic sanity checking to see if we can re-use the anon_vma
1259 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1260 * the same as 'old', the other will be the new one that is trying
1261 * to share the anon_vma.
1263 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1264 * the anon_vma of 'old' is concurrently in the process of being set up
1265 * by another page fault trying to merge _that_. But that's ok: if it
1266 * is being set up, that automatically means that it will be a singleton
1267 * acceptable for merging, so we can do all of this optimistically. But
1268 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1270 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1271 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1272 * is to return an anon_vma that is "complex" due to having gone through
1275 * We also make sure that the two vma's are compatible (adjacent,
1276 * and with the same memory policies). That's all stable, even with just
1277 * a read lock on the mmap_lock.
1279 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1281 if (anon_vma_compatible(a, b)) {
1282 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1284 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1291 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1292 * neighbouring vmas for a suitable anon_vma, before it goes off
1293 * to allocate a new anon_vma. It checks because a repetitive
1294 * sequence of mprotects and faults may otherwise lead to distinct
1295 * anon_vmas being allocated, preventing vma merge in subsequent
1298 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1300 struct anon_vma *anon_vma = NULL;
1302 /* Try next first. */
1304 anon_vma = reusable_anon_vma(vma->vm_next, vma, vma->vm_next);
1309 /* Try prev next. */
1311 anon_vma = reusable_anon_vma(vma->vm_prev, vma->vm_prev, vma);
1314 * We might reach here with anon_vma == NULL if we can't find
1315 * any reusable anon_vma.
1316 * There's no absolute need to look only at touching neighbours:
1317 * we could search further afield for "compatible" anon_vmas.
1318 * But it would probably just be a waste of time searching,
1319 * or lead to too many vmas hanging off the same anon_vma.
1320 * We're trying to allow mprotect remerging later on,
1321 * not trying to minimize memory used for anon_vmas.
1327 * If a hint addr is less than mmap_min_addr change hint to be as
1328 * low as possible but still greater than mmap_min_addr
1330 static inline unsigned long round_hint_to_min(unsigned long hint)
1333 if (((void *)hint != NULL) &&
1334 (hint < mmap_min_addr))
1335 return PAGE_ALIGN(mmap_min_addr);
1339 int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1342 unsigned long locked, lock_limit;
1344 /* mlock MCL_FUTURE? */
1345 if (flags & VM_LOCKED) {
1346 locked = len >> PAGE_SHIFT;
1347 locked += mm->locked_vm;
1348 lock_limit = rlimit(RLIMIT_MEMLOCK);
1349 lock_limit >>= PAGE_SHIFT;
1350 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1356 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1358 if (S_ISREG(inode->i_mode))
1359 return MAX_LFS_FILESIZE;
1361 if (S_ISBLK(inode->i_mode))
1362 return MAX_LFS_FILESIZE;
1364 if (S_ISSOCK(inode->i_mode))
1365 return MAX_LFS_FILESIZE;
1367 /* Special "we do even unsigned file positions" case */
1368 if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1371 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1375 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1376 unsigned long pgoff, unsigned long len)
1378 u64 maxsize = file_mmap_size_max(file, inode);
1380 if (maxsize && len > maxsize)
1383 if (pgoff > maxsize >> PAGE_SHIFT)
1389 * The caller must write-lock current->mm->mmap_lock.
1391 unsigned long do_mmap(struct file *file, unsigned long addr,
1392 unsigned long len, unsigned long prot,
1393 unsigned long flags, unsigned long pgoff,
1394 unsigned long *populate, struct list_head *uf)
1396 struct mm_struct *mm = current->mm;
1397 vm_flags_t vm_flags;
1406 * Does the application expect PROT_READ to imply PROT_EXEC?
1408 * (the exception is when the underlying filesystem is noexec
1409 * mounted, in which case we dont add PROT_EXEC.)
1411 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1412 if (!(file && path_noexec(&file->f_path)))
1415 /* force arch specific MAP_FIXED handling in get_unmapped_area */
1416 if (flags & MAP_FIXED_NOREPLACE)
1419 if (!(flags & MAP_FIXED))
1420 addr = round_hint_to_min(addr);
1422 /* Careful about overflows.. */
1423 len = PAGE_ALIGN(len);
1427 /* offset overflow? */
1428 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1431 /* Too many mappings? */
1432 if (mm->map_count > sysctl_max_map_count)
1435 /* Obtain the address to map to. we verify (or select) it and ensure
1436 * that it represents a valid section of the address space.
1438 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1439 if (IS_ERR_VALUE(addr))
1442 if (flags & MAP_FIXED_NOREPLACE) {
1443 if (find_vma_intersection(mm, addr, addr + len))
1447 if (prot == PROT_EXEC) {
1448 pkey = execute_only_pkey(mm);
1453 /* Do simple checking here so the lower-level routines won't have
1454 * to. we assume access permissions have been handled by the open
1455 * of the memory object, so we don't do any here.
1457 vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1458 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1460 if (flags & MAP_LOCKED)
1461 if (!can_do_mlock())
1464 if (mlock_future_check(mm, vm_flags, len))
1468 struct inode *inode = file_inode(file);
1469 unsigned long flags_mask;
1471 if (!file_mmap_ok(file, inode, pgoff, len))
1474 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1476 switch (flags & MAP_TYPE) {
1479 * Force use of MAP_SHARED_VALIDATE with non-legacy
1480 * flags. E.g. MAP_SYNC is dangerous to use with
1481 * MAP_SHARED as you don't know which consistency model
1482 * you will get. We silently ignore unsupported flags
1483 * with MAP_SHARED to preserve backward compatibility.
1485 flags &= LEGACY_MAP_MASK;
1487 case MAP_SHARED_VALIDATE:
1488 if (flags & ~flags_mask)
1490 if (prot & PROT_WRITE) {
1491 if (!(file->f_mode & FMODE_WRITE))
1493 if (IS_SWAPFILE(file->f_mapping->host))
1498 * Make sure we don't allow writing to an append-only
1501 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1504 vm_flags |= VM_SHARED | VM_MAYSHARE;
1505 if (!(file->f_mode & FMODE_WRITE))
1506 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1509 if (!(file->f_mode & FMODE_READ))
1511 if (path_noexec(&file->f_path)) {
1512 if (vm_flags & VM_EXEC)
1514 vm_flags &= ~VM_MAYEXEC;
1517 if (!file->f_op->mmap)
1519 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1527 switch (flags & MAP_TYPE) {
1529 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1535 vm_flags |= VM_SHARED | VM_MAYSHARE;
1539 * Set pgoff according to addr for anon_vma.
1541 pgoff = addr >> PAGE_SHIFT;
1549 * Set 'VM_NORESERVE' if we should not account for the
1550 * memory use of this mapping.
1552 if (flags & MAP_NORESERVE) {
1553 /* We honor MAP_NORESERVE if allowed to overcommit */
1554 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1555 vm_flags |= VM_NORESERVE;
1557 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1558 if (file && is_file_hugepages(file))
1559 vm_flags |= VM_NORESERVE;
1562 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1563 if (!IS_ERR_VALUE(addr) &&
1564 ((vm_flags & VM_LOCKED) ||
1565 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1570 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1571 unsigned long prot, unsigned long flags,
1572 unsigned long fd, unsigned long pgoff)
1574 struct file *file = NULL;
1575 unsigned long retval;
1577 if (!(flags & MAP_ANONYMOUS)) {
1578 audit_mmap_fd(fd, flags);
1582 if (is_file_hugepages(file)) {
1583 len = ALIGN(len, huge_page_size(hstate_file(file)));
1584 } else if (unlikely(flags & MAP_HUGETLB)) {
1588 } else if (flags & MAP_HUGETLB) {
1591 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1595 len = ALIGN(len, huge_page_size(hs));
1597 * VM_NORESERVE is used because the reservations will be
1598 * taken when vm_ops->mmap() is called
1600 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1602 HUGETLB_ANONHUGE_INODE,
1603 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1605 return PTR_ERR(file);
1608 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1615 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1616 unsigned long, prot, unsigned long, flags,
1617 unsigned long, fd, unsigned long, pgoff)
1619 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1622 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1623 struct mmap_arg_struct {
1627 unsigned long flags;
1629 unsigned long offset;
1632 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1634 struct mmap_arg_struct a;
1636 if (copy_from_user(&a, arg, sizeof(a)))
1638 if (offset_in_page(a.offset))
1641 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1642 a.offset >> PAGE_SHIFT);
1644 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1647 * Some shared mappings will want the pages marked read-only
1648 * to track write events. If so, we'll downgrade vm_page_prot
1649 * to the private version (using protection_map[] without the
1652 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1654 vm_flags_t vm_flags = vma->vm_flags;
1655 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1657 /* If it was private or non-writable, the write bit is already clear */
1658 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1661 /* The backer wishes to know when pages are first written to? */
1662 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1665 /* The open routine did something to the protections that pgprot_modify
1666 * won't preserve? */
1667 if (pgprot_val(vm_page_prot) !=
1668 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1671 /* Do we need to track softdirty? */
1672 if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
1675 /* Specialty mapping? */
1676 if (vm_flags & VM_PFNMAP)
1679 /* Can the mapping track the dirty pages? */
1680 return vma->vm_file && vma->vm_file->f_mapping &&
1681 mapping_can_writeback(vma->vm_file->f_mapping);
1685 * We account for memory if it's a private writeable mapping,
1686 * not hugepages and VM_NORESERVE wasn't set.
1688 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1691 * hugetlb has its own accounting separate from the core VM
1692 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1694 if (file && is_file_hugepages(file))
1697 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1700 unsigned long mmap_region(struct file *file, unsigned long addr,
1701 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1702 struct list_head *uf)
1704 struct mm_struct *mm = current->mm;
1705 struct vm_area_struct *vma, *prev, *merge;
1707 struct rb_node **rb_link, *rb_parent;
1708 unsigned long charged = 0;
1710 /* Check against address space limit. */
1711 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1712 unsigned long nr_pages;
1715 * MAP_FIXED may remove pages of mappings that intersects with
1716 * requested mapping. Account for the pages it would unmap.
1718 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1720 if (!may_expand_vm(mm, vm_flags,
1721 (len >> PAGE_SHIFT) - nr_pages))
1725 /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
1726 if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
1729 * Private writable mapping: check memory availability
1731 if (accountable_mapping(file, vm_flags)) {
1732 charged = len >> PAGE_SHIFT;
1733 if (security_vm_enough_memory_mm(mm, charged))
1735 vm_flags |= VM_ACCOUNT;
1739 * Can we just expand an old mapping?
1741 vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1742 NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1747 * Determine the object being mapped and call the appropriate
1748 * specific mapper. the address has already been validated, but
1749 * not unmapped, but the maps are removed from the list.
1751 vma = vm_area_alloc(mm);
1757 vma->vm_start = addr;
1758 vma->vm_end = addr + len;
1759 vma->vm_flags = vm_flags;
1760 vma->vm_page_prot = vm_get_page_prot(vm_flags);
1761 vma->vm_pgoff = pgoff;
1764 if (vm_flags & VM_SHARED) {
1765 error = mapping_map_writable(file->f_mapping);
1770 vma->vm_file = get_file(file);
1771 error = call_mmap(file, vma);
1773 goto unmap_and_free_vma;
1775 /* Can addr have changed??
1777 * Answer: Yes, several device drivers can do it in their
1778 * f_op->mmap method. -DaveM
1779 * Bug: If addr is changed, prev, rb_link, rb_parent should
1780 * be updated for vma_link()
1782 WARN_ON_ONCE(addr != vma->vm_start);
1784 addr = vma->vm_start;
1786 /* If vm_flags changed after call_mmap(), we should try merge vma again
1787 * as we may succeed this time.
1789 if (unlikely(vm_flags != vma->vm_flags && prev)) {
1790 merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
1791 NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1793 /* ->mmap() can change vma->vm_file and fput the original file. So
1794 * fput the vma->vm_file here or we would add an extra fput for file
1795 * and cause general protection fault ultimately.
1800 /* Update vm_flags to pick up the change. */
1801 vm_flags = vma->vm_flags;
1802 goto unmap_writable;
1806 vm_flags = vma->vm_flags;
1807 } else if (vm_flags & VM_SHARED) {
1808 error = shmem_zero_setup(vma);
1812 vma_set_anonymous(vma);
1815 /* Allow architectures to sanity-check the vm_flags */
1816 if (!arch_validate_flags(vma->vm_flags)) {
1819 goto unmap_and_free_vma;
1824 vma_link(mm, vma, prev, rb_link, rb_parent);
1827 * vma_merge() calls khugepaged_enter_vma() either, the below
1828 * call covers the non-merge case.
1830 khugepaged_enter_vma(vma, vma->vm_flags);
1832 /* Once vma denies write, undo our temporary denial count */
1834 if (file && vm_flags & VM_SHARED)
1835 mapping_unmap_writable(file->f_mapping);
1836 file = vma->vm_file;
1838 perf_event_mmap(vma);
1840 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
1841 if (vm_flags & VM_LOCKED) {
1842 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1843 is_vm_hugetlb_page(vma) ||
1844 vma == get_gate_vma(current->mm))
1845 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1847 mm->locked_vm += (len >> PAGE_SHIFT);
1854 * New (or expanded) vma always get soft dirty status.
1855 * Otherwise user-space soft-dirty page tracker won't
1856 * be able to distinguish situation when vma area unmapped,
1857 * then new mapped in-place (which must be aimed as
1858 * a completely new data area).
1860 vma->vm_flags |= VM_SOFTDIRTY;
1862 vma_set_page_prot(vma);
1868 vma->vm_file = NULL;
1870 /* Undo any partial mapping done by a device driver. */
1871 unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1873 if (vm_flags & VM_SHARED)
1874 mapping_unmap_writable(file->f_mapping);
1879 vm_unacct_memory(charged);
1883 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1886 * We implement the search by looking for an rbtree node that
1887 * immediately follows a suitable gap. That is,
1888 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1889 * - gap_end = vma->vm_start >= info->low_limit + length;
1890 * - gap_end - gap_start >= length
1893 struct mm_struct *mm = current->mm;
1894 struct vm_area_struct *vma;
1895 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1897 /* Adjust search length to account for worst case alignment overhead */
1898 length = info->length + info->align_mask;
1899 if (length < info->length)
1902 /* Adjust search limits by the desired length */
1903 if (info->high_limit < length)
1905 high_limit = info->high_limit - length;
1907 if (info->low_limit > high_limit)
1909 low_limit = info->low_limit + length;
1911 /* Check if rbtree root looks promising */
1912 if (RB_EMPTY_ROOT(&mm->mm_rb))
1914 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1915 if (vma->rb_subtree_gap < length)
1919 /* Visit left subtree if it looks promising */
1920 gap_end = vm_start_gap(vma);
1921 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1922 struct vm_area_struct *left =
1923 rb_entry(vma->vm_rb.rb_left,
1924 struct vm_area_struct, vm_rb);
1925 if (left->rb_subtree_gap >= length) {
1931 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1933 /* Check if current node has a suitable gap */
1934 if (gap_start > high_limit)
1936 if (gap_end >= low_limit &&
1937 gap_end > gap_start && gap_end - gap_start >= length)
1940 /* Visit right subtree if it looks promising */
1941 if (vma->vm_rb.rb_right) {
1942 struct vm_area_struct *right =
1943 rb_entry(vma->vm_rb.rb_right,
1944 struct vm_area_struct, vm_rb);
1945 if (right->rb_subtree_gap >= length) {
1951 /* Go back up the rbtree to find next candidate node */
1953 struct rb_node *prev = &vma->vm_rb;
1954 if (!rb_parent(prev))
1956 vma = rb_entry(rb_parent(prev),
1957 struct vm_area_struct, vm_rb);
1958 if (prev == vma->vm_rb.rb_left) {
1959 gap_start = vm_end_gap(vma->vm_prev);
1960 gap_end = vm_start_gap(vma);
1967 /* Check highest gap, which does not precede any rbtree node */
1968 gap_start = mm->highest_vm_end;
1969 gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
1970 if (gap_start > high_limit)
1974 /* We found a suitable gap. Clip it with the original low_limit. */
1975 if (gap_start < info->low_limit)
1976 gap_start = info->low_limit;
1978 /* Adjust gap address to the desired alignment */
1979 gap_start += (info->align_offset - gap_start) & info->align_mask;
1981 VM_BUG_ON(gap_start + info->length > info->high_limit);
1982 VM_BUG_ON(gap_start + info->length > gap_end);
1986 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1988 struct mm_struct *mm = current->mm;
1989 struct vm_area_struct *vma;
1990 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1992 /* Adjust search length to account for worst case alignment overhead */
1993 length = info->length + info->align_mask;
1994 if (length < info->length)
1998 * Adjust search limits by the desired length.
1999 * See implementation comment at top of unmapped_area().
2001 gap_end = info->high_limit;
2002 if (gap_end < length)
2004 high_limit = gap_end - length;
2006 if (info->low_limit > high_limit)
2008 low_limit = info->low_limit + length;
2010 /* Check highest gap, which does not precede any rbtree node */
2011 gap_start = mm->highest_vm_end;
2012 if (gap_start <= high_limit)
2015 /* Check if rbtree root looks promising */
2016 if (RB_EMPTY_ROOT(&mm->mm_rb))
2018 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2019 if (vma->rb_subtree_gap < length)
2023 /* Visit right subtree if it looks promising */
2024 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2025 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
2026 struct vm_area_struct *right =
2027 rb_entry(vma->vm_rb.rb_right,
2028 struct vm_area_struct, vm_rb);
2029 if (right->rb_subtree_gap >= length) {
2036 /* Check if current node has a suitable gap */
2037 gap_end = vm_start_gap(vma);
2038 if (gap_end < low_limit)
2040 if (gap_start <= high_limit &&
2041 gap_end > gap_start && gap_end - gap_start >= length)
2044 /* Visit left subtree if it looks promising */
2045 if (vma->vm_rb.rb_left) {
2046 struct vm_area_struct *left =
2047 rb_entry(vma->vm_rb.rb_left,
2048 struct vm_area_struct, vm_rb);
2049 if (left->rb_subtree_gap >= length) {
2055 /* Go back up the rbtree to find next candidate node */
2057 struct rb_node *prev = &vma->vm_rb;
2058 if (!rb_parent(prev))
2060 vma = rb_entry(rb_parent(prev),
2061 struct vm_area_struct, vm_rb);
2062 if (prev == vma->vm_rb.rb_right) {
2063 gap_start = vma->vm_prev ?
2064 vm_end_gap(vma->vm_prev) : 0;
2071 /* We found a suitable gap. Clip it with the original high_limit. */
2072 if (gap_end > info->high_limit)
2073 gap_end = info->high_limit;
2076 /* Compute highest gap address at the desired alignment */
2077 gap_end -= info->length;
2078 gap_end -= (gap_end - info->align_offset) & info->align_mask;
2080 VM_BUG_ON(gap_end < info->low_limit);
2081 VM_BUG_ON(gap_end < gap_start);
2086 * Search for an unmapped address range.
2088 * We are looking for a range that:
2089 * - does not intersect with any VMA;
2090 * - is contained within the [low_limit, high_limit) interval;
2091 * - is at least the desired size.
2092 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
2094 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
2098 if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
2099 addr = unmapped_area_topdown(info);
2101 addr = unmapped_area(info);
2103 trace_vm_unmapped_area(addr, info);
2107 /* Get an address range which is currently unmapped.
2108 * For shmat() with addr=0.
2110 * Ugly calling convention alert:
2111 * Return value with the low bits set means error value,
2113 * if (ret & ~PAGE_MASK)
2116 * This function "knows" that -ENOMEM has the bits set.
2119 generic_get_unmapped_area(struct file *filp, unsigned long addr,
2120 unsigned long len, unsigned long pgoff,
2121 unsigned long flags)
2123 struct mm_struct *mm = current->mm;
2124 struct vm_area_struct *vma, *prev;
2125 struct vm_unmapped_area_info info;
2126 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2128 if (len > mmap_end - mmap_min_addr)
2131 if (flags & MAP_FIXED)
2135 addr = PAGE_ALIGN(addr);
2136 vma = find_vma_prev(mm, addr, &prev);
2137 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2138 (!vma || addr + len <= vm_start_gap(vma)) &&
2139 (!prev || addr >= vm_end_gap(prev)))
2145 info.low_limit = mm->mmap_base;
2146 info.high_limit = mmap_end;
2147 info.align_mask = 0;
2148 info.align_offset = 0;
2149 return vm_unmapped_area(&info);
2152 #ifndef HAVE_ARCH_UNMAPPED_AREA
2154 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2155 unsigned long len, unsigned long pgoff,
2156 unsigned long flags)
2158 return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
2163 * This mmap-allocator allocates new areas top-down from below the
2164 * stack's low limit (the base):
2167 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2168 unsigned long len, unsigned long pgoff,
2169 unsigned long flags)
2171 struct vm_area_struct *vma, *prev;
2172 struct mm_struct *mm = current->mm;
2173 struct vm_unmapped_area_info info;
2174 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2176 /* requested length too big for entire address space */
2177 if (len > mmap_end - mmap_min_addr)
2180 if (flags & MAP_FIXED)
2183 /* requesting a specific address */
2185 addr = PAGE_ALIGN(addr);
2186 vma = find_vma_prev(mm, addr, &prev);
2187 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2188 (!vma || addr + len <= vm_start_gap(vma)) &&
2189 (!prev || addr >= vm_end_gap(prev)))
2193 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2195 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2196 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2197 info.align_mask = 0;
2198 info.align_offset = 0;
2199 addr = vm_unmapped_area(&info);
2202 * A failed mmap() very likely causes application failure,
2203 * so fall back to the bottom-up function here. This scenario
2204 * can happen with large stack limits and large mmap()
2207 if (offset_in_page(addr)) {
2208 VM_BUG_ON(addr != -ENOMEM);
2210 info.low_limit = TASK_UNMAPPED_BASE;
2211 info.high_limit = mmap_end;
2212 addr = vm_unmapped_area(&info);
2218 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2220 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2221 unsigned long len, unsigned long pgoff,
2222 unsigned long flags)
2224 return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
2229 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2230 unsigned long pgoff, unsigned long flags)
2232 unsigned long (*get_area)(struct file *, unsigned long,
2233 unsigned long, unsigned long, unsigned long);
2235 unsigned long error = arch_mmap_check(addr, len, flags);
2239 /* Careful about overflows.. */
2240 if (len > TASK_SIZE)
2243 get_area = current->mm->get_unmapped_area;
2245 if (file->f_op->get_unmapped_area)
2246 get_area = file->f_op->get_unmapped_area;
2247 } else if (flags & MAP_SHARED) {
2249 * mmap_region() will call shmem_zero_setup() to create a file,
2250 * so use shmem's get_unmapped_area in case it can be huge.
2251 * do_mmap() will clear pgoff, so match alignment.
2254 get_area = shmem_get_unmapped_area;
2257 addr = get_area(file, addr, len, pgoff, flags);
2258 if (IS_ERR_VALUE(addr))
2261 if (addr > TASK_SIZE - len)
2263 if (offset_in_page(addr))
2266 error = security_mmap_addr(addr);
2267 return error ? error : addr;
2270 EXPORT_SYMBOL(get_unmapped_area);
2272 /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
2273 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2275 struct rb_node *rb_node;
2276 struct vm_area_struct *vma;
2278 mmap_assert_locked(mm);
2279 /* Check the cache first. */
2280 vma = vmacache_find(mm, addr);
2284 rb_node = mm->mm_rb.rb_node;
2287 struct vm_area_struct *tmp;
2289 tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2291 if (tmp->vm_end > addr) {
2293 if (tmp->vm_start <= addr)
2295 rb_node = rb_node->rb_left;
2297 rb_node = rb_node->rb_right;
2301 vmacache_update(addr, vma);
2305 EXPORT_SYMBOL(find_vma);
2308 * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2310 struct vm_area_struct *
2311 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2312 struct vm_area_struct **pprev)
2314 struct vm_area_struct *vma;
2316 vma = find_vma(mm, addr);
2318 *pprev = vma->vm_prev;
2320 struct rb_node *rb_node = rb_last(&mm->mm_rb);
2322 *pprev = rb_node ? rb_entry(rb_node, struct vm_area_struct, vm_rb) : NULL;
2328 * Verify that the stack growth is acceptable and
2329 * update accounting. This is shared with both the
2330 * grow-up and grow-down cases.
2332 static int acct_stack_growth(struct vm_area_struct *vma,
2333 unsigned long size, unsigned long grow)
2335 struct mm_struct *mm = vma->vm_mm;
2336 unsigned long new_start;
2338 /* address space limit tests */
2339 if (!may_expand_vm(mm, vma->vm_flags, grow))
2342 /* Stack limit test */
2343 if (size > rlimit(RLIMIT_STACK))
2346 /* mlock limit tests */
2347 if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
2350 /* Check to ensure the stack will not grow into a hugetlb-only region */
2351 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2353 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2357 * Overcommit.. This must be the final test, as it will
2358 * update security statistics.
2360 if (security_vm_enough_memory_mm(mm, grow))
2366 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2368 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2369 * vma is the last one with address > vma->vm_end. Have to extend vma.
2371 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2373 struct mm_struct *mm = vma->vm_mm;
2374 struct vm_area_struct *next;
2375 unsigned long gap_addr;
2378 if (!(vma->vm_flags & VM_GROWSUP))
2381 /* Guard against exceeding limits of the address space. */
2382 address &= PAGE_MASK;
2383 if (address >= (TASK_SIZE & PAGE_MASK))
2385 address += PAGE_SIZE;
2387 /* Enforce stack_guard_gap */
2388 gap_addr = address + stack_guard_gap;
2390 /* Guard against overflow */
2391 if (gap_addr < address || gap_addr > TASK_SIZE)
2392 gap_addr = TASK_SIZE;
2394 next = vma->vm_next;
2395 if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
2396 if (!(next->vm_flags & VM_GROWSUP))
2398 /* Check that both stack segments have the same anon_vma? */
2401 /* We must make sure the anon_vma is allocated. */
2402 if (unlikely(anon_vma_prepare(vma)))
2406 * vma->vm_start/vm_end cannot change under us because the caller
2407 * is required to hold the mmap_lock in read mode. We need the
2408 * anon_vma lock to serialize against concurrent expand_stacks.
2410 anon_vma_lock_write(vma->anon_vma);
2412 /* Somebody else might have raced and expanded it already */
2413 if (address > vma->vm_end) {
2414 unsigned long size, grow;
2416 size = address - vma->vm_start;
2417 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2420 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2421 error = acct_stack_growth(vma, size, grow);
2424 * vma_gap_update() doesn't support concurrent
2425 * updates, but we only hold a shared mmap_lock
2426 * lock here, so we need to protect against
2427 * concurrent vma expansions.
2428 * anon_vma_lock_write() doesn't help here, as
2429 * we don't guarantee that all growable vmas
2430 * in a mm share the same root anon vma.
2431 * So, we reuse mm->page_table_lock to guard
2432 * against concurrent vma expansions.
2434 spin_lock(&mm->page_table_lock);
2435 if (vma->vm_flags & VM_LOCKED)
2436 mm->locked_vm += grow;
2437 vm_stat_account(mm, vma->vm_flags, grow);
2438 anon_vma_interval_tree_pre_update_vma(vma);
2439 vma->vm_end = address;
2440 anon_vma_interval_tree_post_update_vma(vma);
2442 vma_gap_update(vma->vm_next);
2444 mm->highest_vm_end = vm_end_gap(vma);
2445 spin_unlock(&mm->page_table_lock);
2447 perf_event_mmap(vma);
2451 anon_vma_unlock_write(vma->anon_vma);
2452 khugepaged_enter_vma(vma, vma->vm_flags);
2456 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2459 * vma is the first one with address < vma->vm_start. Have to extend vma.
2461 int expand_downwards(struct vm_area_struct *vma,
2462 unsigned long address)
2464 struct mm_struct *mm = vma->vm_mm;
2465 struct vm_area_struct *prev;
2468 address &= PAGE_MASK;
2469 if (address < mmap_min_addr)
2472 /* Enforce stack_guard_gap */
2473 prev = vma->vm_prev;
2474 /* Check that both stack segments have the same anon_vma? */
2475 if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2476 vma_is_accessible(prev)) {
2477 if (address - prev->vm_end < stack_guard_gap)
2481 /* We must make sure the anon_vma is allocated. */
2482 if (unlikely(anon_vma_prepare(vma)))
2486 * vma->vm_start/vm_end cannot change under us because the caller
2487 * is required to hold the mmap_lock in read mode. We need the
2488 * anon_vma lock to serialize against concurrent expand_stacks.
2490 anon_vma_lock_write(vma->anon_vma);
2492 /* Somebody else might have raced and expanded it already */
2493 if (address < vma->vm_start) {
2494 unsigned long size, grow;
2496 size = vma->vm_end - address;
2497 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2500 if (grow <= vma->vm_pgoff) {
2501 error = acct_stack_growth(vma, size, grow);
2504 * vma_gap_update() doesn't support concurrent
2505 * updates, but we only hold a shared mmap_lock
2506 * lock here, so we need to protect against
2507 * concurrent vma expansions.
2508 * anon_vma_lock_write() doesn't help here, as
2509 * we don't guarantee that all growable vmas
2510 * in a mm share the same root anon vma.
2511 * So, we reuse mm->page_table_lock to guard
2512 * against concurrent vma expansions.
2514 spin_lock(&mm->page_table_lock);
2515 if (vma->vm_flags & VM_LOCKED)
2516 mm->locked_vm += grow;
2517 vm_stat_account(mm, vma->vm_flags, grow);
2518 anon_vma_interval_tree_pre_update_vma(vma);
2519 vma->vm_start = address;
2520 vma->vm_pgoff -= grow;
2521 anon_vma_interval_tree_post_update_vma(vma);
2522 vma_gap_update(vma);
2523 spin_unlock(&mm->page_table_lock);
2525 perf_event_mmap(vma);
2529 anon_vma_unlock_write(vma->anon_vma);
2530 khugepaged_enter_vma(vma, vma->vm_flags);
2535 /* enforced gap between the expanding stack and other mappings. */
2536 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2538 static int __init cmdline_parse_stack_guard_gap(char *p)
2543 val = simple_strtoul(p, &endptr, 10);
2545 stack_guard_gap = val << PAGE_SHIFT;
2549 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2551 #ifdef CONFIG_STACK_GROWSUP
2552 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2554 return expand_upwards(vma, address);
2557 struct vm_area_struct *
2558 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2560 struct vm_area_struct *vma, *prev;
2563 vma = find_vma_prev(mm, addr, &prev);
2564 if (vma && (vma->vm_start <= addr))
2566 /* don't alter vm_end if the coredump is running */
2567 if (!prev || expand_stack(prev, addr))
2569 if (prev->vm_flags & VM_LOCKED)
2570 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2574 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2576 return expand_downwards(vma, address);
2579 struct vm_area_struct *
2580 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2582 struct vm_area_struct *vma;
2583 unsigned long start;
2586 vma = find_vma(mm, addr);
2589 if (vma->vm_start <= addr)
2591 if (!(vma->vm_flags & VM_GROWSDOWN))
2593 start = vma->vm_start;
2594 if (expand_stack(vma, addr))
2596 if (vma->vm_flags & VM_LOCKED)
2597 populate_vma_page_range(vma, addr, start, NULL);
2602 EXPORT_SYMBOL_GPL(find_extend_vma);
2605 * Ok - we have the memory areas we should free on the vma list,
2606 * so release them, and do the vma updates.
2608 * Called with the mm semaphore held.
2610 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2612 unsigned long nr_accounted = 0;
2614 /* Update high watermark before we lower total_vm */
2615 update_hiwater_vm(mm);
2617 long nrpages = vma_pages(vma);
2619 if (vma->vm_flags & VM_ACCOUNT)
2620 nr_accounted += nrpages;
2621 vm_stat_account(mm, vma->vm_flags, -nrpages);
2622 vma = remove_vma(vma);
2624 vm_unacct_memory(nr_accounted);
2629 * Get rid of page table information in the indicated region.
2631 * Called with the mm semaphore held.
2633 static void unmap_region(struct mm_struct *mm,
2634 struct vm_area_struct *vma, struct vm_area_struct *prev,
2635 unsigned long start, unsigned long end)
2637 struct vm_area_struct *next = vma_next(mm, prev);
2638 struct mmu_gather tlb;
2641 tlb_gather_mmu(&tlb, mm);
2642 update_hiwater_rss(mm);
2643 unmap_vmas(&tlb, vma, start, end);
2644 free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2645 next ? next->vm_start : USER_PGTABLES_CEILING);
2646 tlb_finish_mmu(&tlb);
2650 * Create a list of vma's touched by the unmap, removing them from the mm's
2651 * vma list as we go..
2654 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2655 struct vm_area_struct *prev, unsigned long end)
2657 struct vm_area_struct **insertion_point;
2658 struct vm_area_struct *tail_vma = NULL;
2660 insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2661 vma->vm_prev = NULL;
2663 vma_rb_erase(vma, &mm->mm_rb);
2664 if (vma->vm_flags & VM_LOCKED)
2665 mm->locked_vm -= vma_pages(vma);
2669 } while (vma && vma->vm_start < end);
2670 *insertion_point = vma;
2672 vma->vm_prev = prev;
2673 vma_gap_update(vma);
2675 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2676 tail_vma->vm_next = NULL;
2678 /* Kill the cache */
2679 vmacache_invalidate(mm);
2682 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2683 * VM_GROWSUP VMA. Such VMAs can change their size under
2684 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2686 if (vma && (vma->vm_flags & VM_GROWSDOWN))
2688 if (prev && (prev->vm_flags & VM_GROWSUP))
2694 * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
2695 * has already been checked or doesn't make sense to fail.
2697 int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2698 unsigned long addr, int new_below)
2700 struct vm_area_struct *new;
2703 if (vma->vm_ops && vma->vm_ops->may_split) {
2704 err = vma->vm_ops->may_split(vma, addr);
2709 new = vm_area_dup(vma);
2716 new->vm_start = addr;
2717 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2720 err = vma_dup_policy(vma, new);
2724 err = anon_vma_clone(new, vma);
2729 get_file(new->vm_file);
2731 if (new->vm_ops && new->vm_ops->open)
2732 new->vm_ops->open(new);
2735 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2736 ((addr - new->vm_start) >> PAGE_SHIFT), new);
2738 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2744 /* Clean everything up if vma_adjust failed. */
2745 if (new->vm_ops && new->vm_ops->close)
2746 new->vm_ops->close(new);
2749 unlink_anon_vmas(new);
2751 mpol_put(vma_policy(new));
2758 * Split a vma into two pieces at address 'addr', a new vma is allocated
2759 * either for the first part or the tail.
2761 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2762 unsigned long addr, int new_below)
2764 if (mm->map_count >= sysctl_max_map_count)
2767 return __split_vma(mm, vma, addr, new_below);
2770 /* Munmap is split into 2 main parts -- this part which finds
2771 * what needs doing, and the areas themselves, which do the
2772 * work. This now handles partial unmappings.
2773 * Jeremy Fitzhardinge <jeremy@goop.org>
2775 int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2776 struct list_head *uf, bool downgrade)
2779 struct vm_area_struct *vma, *prev, *last;
2781 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2784 len = PAGE_ALIGN(len);
2790 * arch_unmap() might do unmaps itself. It must be called
2791 * and finish any rbtree manipulation before this code
2792 * runs and also starts to manipulate the rbtree.
2794 arch_unmap(mm, start, end);
2796 /* Find the first overlapping VMA where start < vma->vm_end */
2797 vma = find_vma_intersection(mm, start, end);
2800 prev = vma->vm_prev;
2803 * If we need to split any vma, do it now to save pain later.
2805 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2806 * unmapped vm_area_struct will remain in use: so lower split_vma
2807 * places tmp vma above, and higher split_vma places tmp vma below.
2809 if (start > vma->vm_start) {
2813 * Make sure that map_count on return from munmap() will
2814 * not exceed its limit; but let map_count go just above
2815 * its limit temporarily, to help free resources as expected.
2817 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2820 error = __split_vma(mm, vma, start, 0);
2826 /* Does it split the last one? */
2827 last = find_vma(mm, end);
2828 if (last && end > last->vm_start) {
2829 int error = __split_vma(mm, last, end, 1);
2833 vma = vma_next(mm, prev);
2837 * If userfaultfd_unmap_prep returns an error the vmas
2838 * will remain split, but userland will get a
2839 * highly unexpected error anyway. This is no
2840 * different than the case where the first of the two
2841 * __split_vma fails, but we don't undo the first
2842 * split, despite we could. This is unlikely enough
2843 * failure that it's not worth optimizing it for.
2845 int error = userfaultfd_unmap_prep(vma, start, end, uf);
2850 /* Detach vmas from rbtree */
2851 if (!detach_vmas_to_be_unmapped(mm, vma, prev, end))
2855 mmap_write_downgrade(mm);
2857 unmap_region(mm, vma, prev, start, end);
2859 /* Fix up all other VM information */
2860 remove_vma_list(mm, vma);
2862 return downgrade ? 1 : 0;
2865 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2866 struct list_head *uf)
2868 return __do_munmap(mm, start, len, uf, false);
2871 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2874 struct mm_struct *mm = current->mm;
2877 if (mmap_write_lock_killable(mm))
2880 ret = __do_munmap(mm, start, len, &uf, downgrade);
2882 * Returning 1 indicates mmap_lock is downgraded.
2883 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2884 * it to 0 before return.
2887 mmap_read_unlock(mm);
2890 mmap_write_unlock(mm);
2892 userfaultfd_unmap_complete(mm, &uf);
2896 int vm_munmap(unsigned long start, size_t len)
2898 return __vm_munmap(start, len, false);
2900 EXPORT_SYMBOL(vm_munmap);
2902 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2904 addr = untagged_addr(addr);
2905 return __vm_munmap(addr, len, true);
2910 * Emulation of deprecated remap_file_pages() syscall.
2912 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2913 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2916 struct mm_struct *mm = current->mm;
2917 struct vm_area_struct *vma;
2918 unsigned long populate = 0;
2919 unsigned long ret = -EINVAL;
2922 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2923 current->comm, current->pid);
2927 start = start & PAGE_MASK;
2928 size = size & PAGE_MASK;
2930 if (start + size <= start)
2933 /* Does pgoff wrap? */
2934 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2937 if (mmap_write_lock_killable(mm))
2940 vma = vma_lookup(mm, start);
2942 if (!vma || !(vma->vm_flags & VM_SHARED))
2945 if (start + size > vma->vm_end) {
2946 struct vm_area_struct *next;
2948 for (next = vma->vm_next; next; next = next->vm_next) {
2949 /* hole between vmas ? */
2950 if (next->vm_start != next->vm_prev->vm_end)
2953 if (next->vm_file != vma->vm_file)
2956 if (next->vm_flags != vma->vm_flags)
2959 if (start + size <= next->vm_end)
2967 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2968 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2969 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2971 flags &= MAP_NONBLOCK;
2972 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2973 if (vma->vm_flags & VM_LOCKED)
2974 flags |= MAP_LOCKED;
2976 file = get_file(vma->vm_file);
2977 ret = do_mmap(vma->vm_file, start, size,
2978 prot, flags, pgoff, &populate, NULL);
2981 mmap_write_unlock(mm);
2983 mm_populate(ret, populate);
2984 if (!IS_ERR_VALUE(ret))
2990 * this is really a simplified "do_mmap". it only handles
2991 * anonymous maps. eventually we may be able to do some
2992 * brk-specific accounting here.
2994 static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
2996 struct mm_struct *mm = current->mm;
2997 struct vm_area_struct *vma, *prev;
2998 struct rb_node **rb_link, *rb_parent;
2999 pgoff_t pgoff = addr >> PAGE_SHIFT;
3001 unsigned long mapped_addr;
3003 /* Until we need other flags, refuse anything except VM_EXEC. */
3004 if ((flags & (~VM_EXEC)) != 0)
3006 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3008 mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3009 if (IS_ERR_VALUE(mapped_addr))
3012 error = mlock_future_check(mm, mm->def_flags, len);
3016 /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
3017 if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
3020 /* Check against address space limits *after* clearing old maps... */
3021 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3024 if (mm->map_count > sysctl_max_map_count)
3027 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3030 /* Can we just expand an old private anonymous mapping? */
3031 vma = vma_merge(mm, prev, addr, addr + len, flags,
3032 NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
3037 * create a vma struct for an anonymous mapping
3039 vma = vm_area_alloc(mm);
3041 vm_unacct_memory(len >> PAGE_SHIFT);
3045 vma_set_anonymous(vma);
3046 vma->vm_start = addr;
3047 vma->vm_end = addr + len;
3048 vma->vm_pgoff = pgoff;
3049 vma->vm_flags = flags;
3050 vma->vm_page_prot = vm_get_page_prot(flags);
3051 vma_link(mm, vma, prev, rb_link, rb_parent);
3053 perf_event_mmap(vma);
3054 mm->total_vm += len >> PAGE_SHIFT;
3055 mm->data_vm += len >> PAGE_SHIFT;
3056 if (flags & VM_LOCKED)
3057 mm->locked_vm += (len >> PAGE_SHIFT);
3058 vma->vm_flags |= VM_SOFTDIRTY;
3062 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3064 struct mm_struct *mm = current->mm;
3070 len = PAGE_ALIGN(request);
3076 if (mmap_write_lock_killable(mm))
3079 ret = do_brk_flags(addr, len, flags, &uf);
3080 populate = ((mm->def_flags & VM_LOCKED) != 0);
3081 mmap_write_unlock(mm);
3082 userfaultfd_unmap_complete(mm, &uf);
3083 if (populate && !ret)
3084 mm_populate(addr, len);
3087 EXPORT_SYMBOL(vm_brk_flags);
3089 int vm_brk(unsigned long addr, unsigned long len)
3091 return vm_brk_flags(addr, len, 0);
3093 EXPORT_SYMBOL(vm_brk);
3095 /* Release all mmaps. */
3096 void exit_mmap(struct mm_struct *mm)
3098 struct mmu_gather tlb;
3099 struct vm_area_struct *vma;
3100 unsigned long nr_accounted = 0;
3102 /* mm's last user has gone, and its about to be pulled down */
3103 mmu_notifier_release(mm);
3105 if (unlikely(mm_is_oom_victim(mm))) {
3107 * Manually reap the mm to free as much memory as possible.
3108 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3109 * this mm from further consideration. Taking mm->mmap_lock for
3110 * write after setting MMF_OOM_SKIP will guarantee that the oom
3111 * reaper will not run on this mm again after mmap_lock is
3114 * Nothing can be holding mm->mmap_lock here and the above call
3115 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
3116 * __oom_reap_task_mm() will not block.
3118 (void)__oom_reap_task_mm(mm);
3119 set_bit(MMF_OOM_SKIP, &mm->flags);
3122 mmap_write_lock(mm);
3127 /* Can happen if dup_mmap() received an OOM */
3128 mmap_write_unlock(mm);
3134 tlb_gather_mmu_fullmm(&tlb, mm);
3135 /* update_hiwater_rss(mm) here? but nobody should be looking */
3136 /* Use -1 here to ensure all VMAs in the mm are unmapped */
3137 unmap_vmas(&tlb, vma, 0, -1);
3138 free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3139 tlb_finish_mmu(&tlb);
3141 /* Walk the list again, actually closing and freeing it. */
3143 if (vma->vm_flags & VM_ACCOUNT)
3144 nr_accounted += vma_pages(vma);
3145 vma = remove_vma(vma);
3149 mmap_write_unlock(mm);
3150 vm_unacct_memory(nr_accounted);
3153 /* Insert vm structure into process list sorted by address
3154 * and into the inode's i_mmap tree. If vm_file is non-NULL
3155 * then i_mmap_rwsem is taken here.
3157 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3159 struct vm_area_struct *prev;
3160 struct rb_node **rb_link, *rb_parent;
3162 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3163 &prev, &rb_link, &rb_parent))
3165 if ((vma->vm_flags & VM_ACCOUNT) &&
3166 security_vm_enough_memory_mm(mm, vma_pages(vma)))
3170 * The vm_pgoff of a purely anonymous vma should be irrelevant
3171 * until its first write fault, when page's anon_vma and index
3172 * are set. But now set the vm_pgoff it will almost certainly
3173 * end up with (unless mremap moves it elsewhere before that
3174 * first wfault), so /proc/pid/maps tells a consistent story.
3176 * By setting it to reflect the virtual start address of the
3177 * vma, merges and splits can happen in a seamless way, just
3178 * using the existing file pgoff checks and manipulations.
3179 * Similarly in do_mmap and in do_brk_flags.
3181 if (vma_is_anonymous(vma)) {
3182 BUG_ON(vma->anon_vma);
3183 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3186 vma_link(mm, vma, prev, rb_link, rb_parent);
3191 * Copy the vma structure to a new location in the same mm,
3192 * prior to moving page table entries, to effect an mremap move.
3194 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3195 unsigned long addr, unsigned long len, pgoff_t pgoff,
3196 bool *need_rmap_locks)
3198 struct vm_area_struct *vma = *vmap;
3199 unsigned long vma_start = vma->vm_start;
3200 struct mm_struct *mm = vma->vm_mm;
3201 struct vm_area_struct *new_vma, *prev;
3202 struct rb_node **rb_link, *rb_parent;
3203 bool faulted_in_anon_vma = true;
3206 * If anonymous vma has not yet been faulted, update new pgoff
3207 * to match new location, to increase its chance of merging.
3209 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3210 pgoff = addr >> PAGE_SHIFT;
3211 faulted_in_anon_vma = false;
3214 if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3215 return NULL; /* should never get here */
3216 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3217 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3218 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3221 * Source vma may have been merged into new_vma
3223 if (unlikely(vma_start >= new_vma->vm_start &&
3224 vma_start < new_vma->vm_end)) {
3226 * The only way we can get a vma_merge with
3227 * self during an mremap is if the vma hasn't
3228 * been faulted in yet and we were allowed to
3229 * reset the dst vma->vm_pgoff to the
3230 * destination address of the mremap to allow
3231 * the merge to happen. mremap must change the
3232 * vm_pgoff linearity between src and dst vmas
3233 * (in turn preventing a vma_merge) to be
3234 * safe. It is only safe to keep the vm_pgoff
3235 * linear if there are no pages mapped yet.
3237 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3238 *vmap = vma = new_vma;
3240 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3242 new_vma = vm_area_dup(vma);
3245 new_vma->vm_start = addr;
3246 new_vma->vm_end = addr + len;
3247 new_vma->vm_pgoff = pgoff;
3248 if (vma_dup_policy(vma, new_vma))
3250 if (anon_vma_clone(new_vma, vma))
3251 goto out_free_mempol;
3252 if (new_vma->vm_file)
3253 get_file(new_vma->vm_file);
3254 if (new_vma->vm_ops && new_vma->vm_ops->open)
3255 new_vma->vm_ops->open(new_vma);
3256 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3257 *need_rmap_locks = false;
3262 mpol_put(vma_policy(new_vma));
3264 vm_area_free(new_vma);
3270 * Return true if the calling process may expand its vm space by the passed
3273 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3275 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3278 if (is_data_mapping(flags) &&
3279 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3280 /* Workaround for Valgrind */
3281 if (rlimit(RLIMIT_DATA) == 0 &&
3282 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3285 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3286 current->comm, current->pid,
3287 (mm->data_vm + npages) << PAGE_SHIFT,
3288 rlimit(RLIMIT_DATA),
3289 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3291 if (!ignore_rlimit_data)
3298 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3300 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3302 if (is_exec_mapping(flags))
3303 mm->exec_vm += npages;
3304 else if (is_stack_mapping(flags))
3305 mm->stack_vm += npages;
3306 else if (is_data_mapping(flags))
3307 mm->data_vm += npages;
3310 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3313 * Having a close hook prevents vma merging regardless of flags.
3315 static void special_mapping_close(struct vm_area_struct *vma)
3319 static const char *special_mapping_name(struct vm_area_struct *vma)
3321 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3324 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3326 struct vm_special_mapping *sm = new_vma->vm_private_data;
3328 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3332 return sm->mremap(sm, new_vma);
3337 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3340 * Forbid splitting special mappings - kernel has expectations over
3341 * the number of pages in mapping. Together with VM_DONTEXPAND
3342 * the size of vma should stay the same over the special mapping's
3348 static const struct vm_operations_struct special_mapping_vmops = {
3349 .close = special_mapping_close,
3350 .fault = special_mapping_fault,
3351 .mremap = special_mapping_mremap,
3352 .name = special_mapping_name,
3353 /* vDSO code relies that VVAR can't be accessed remotely */
3355 .may_split = special_mapping_split,
3358 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3359 .close = special_mapping_close,
3360 .fault = special_mapping_fault,
3363 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3365 struct vm_area_struct *vma = vmf->vma;
3367 struct page **pages;
3369 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3370 pages = vma->vm_private_data;
3372 struct vm_special_mapping *sm = vma->vm_private_data;
3375 return sm->fault(sm, vmf->vma, vmf);
3380 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3384 struct page *page = *pages;
3390 return VM_FAULT_SIGBUS;
3393 static struct vm_area_struct *__install_special_mapping(
3394 struct mm_struct *mm,
3395 unsigned long addr, unsigned long len,
3396 unsigned long vm_flags, void *priv,
3397 const struct vm_operations_struct *ops)
3400 struct vm_area_struct *vma;
3402 vma = vm_area_alloc(mm);
3403 if (unlikely(vma == NULL))
3404 return ERR_PTR(-ENOMEM);
3406 vma->vm_start = addr;
3407 vma->vm_end = addr + len;
3409 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3410 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3411 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3414 vma->vm_private_data = priv;
3416 ret = insert_vm_struct(mm, vma);
3420 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3422 perf_event_mmap(vma);
3428 return ERR_PTR(ret);
3431 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3432 const struct vm_special_mapping *sm)
3434 return vma->vm_private_data == sm &&
3435 (vma->vm_ops == &special_mapping_vmops ||
3436 vma->vm_ops == &legacy_special_mapping_vmops);
3440 * Called with mm->mmap_lock held for writing.
3441 * Insert a new vma covering the given region, with the given flags.
3442 * Its pages are supplied by the given array of struct page *.
3443 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3444 * The region past the last page supplied will always produce SIGBUS.
3445 * The array pointer and the pages it points to are assumed to stay alive
3446 * for as long as this mapping might exist.
3448 struct vm_area_struct *_install_special_mapping(
3449 struct mm_struct *mm,
3450 unsigned long addr, unsigned long len,
3451 unsigned long vm_flags, const struct vm_special_mapping *spec)
3453 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3454 &special_mapping_vmops);
3457 int install_special_mapping(struct mm_struct *mm,
3458 unsigned long addr, unsigned long len,
3459 unsigned long vm_flags, struct page **pages)
3461 struct vm_area_struct *vma = __install_special_mapping(
3462 mm, addr, len, vm_flags, (void *)pages,
3463 &legacy_special_mapping_vmops);
3465 return PTR_ERR_OR_ZERO(vma);
3468 static DEFINE_MUTEX(mm_all_locks_mutex);
3470 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3472 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3474 * The LSB of head.next can't change from under us
3475 * because we hold the mm_all_locks_mutex.
3477 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3479 * We can safely modify head.next after taking the
3480 * anon_vma->root->rwsem. If some other vma in this mm shares
3481 * the same anon_vma we won't take it again.
3483 * No need of atomic instructions here, head.next
3484 * can't change from under us thanks to the
3485 * anon_vma->root->rwsem.
3487 if (__test_and_set_bit(0, (unsigned long *)
3488 &anon_vma->root->rb_root.rb_root.rb_node))
3493 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3495 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3497 * AS_MM_ALL_LOCKS can't change from under us because
3498 * we hold the mm_all_locks_mutex.
3500 * Operations on ->flags have to be atomic because
3501 * even if AS_MM_ALL_LOCKS is stable thanks to the
3502 * mm_all_locks_mutex, there may be other cpus
3503 * changing other bitflags in parallel to us.
3505 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3507 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3512 * This operation locks against the VM for all pte/vma/mm related
3513 * operations that could ever happen on a certain mm. This includes
3514 * vmtruncate, try_to_unmap, and all page faults.
3516 * The caller must take the mmap_lock in write mode before calling
3517 * mm_take_all_locks(). The caller isn't allowed to release the
3518 * mmap_lock until mm_drop_all_locks() returns.
3520 * mmap_lock in write mode is required in order to block all operations
3521 * that could modify pagetables and free pages without need of
3522 * altering the vma layout. It's also needed in write mode to avoid new
3523 * anon_vmas to be associated with existing vmas.
3525 * A single task can't take more than one mm_take_all_locks() in a row
3526 * or it would deadlock.
3528 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3529 * mapping->flags avoid to take the same lock twice, if more than one
3530 * vma in this mm is backed by the same anon_vma or address_space.
3532 * We take locks in following order, accordingly to comment at beginning
3534 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3536 * - all i_mmap_rwsem locks;
3537 * - all anon_vma->rwseml
3539 * We can take all locks within these types randomly because the VM code
3540 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3541 * mm_all_locks_mutex.
3543 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3544 * that may have to take thousand of locks.
3546 * mm_take_all_locks() can fail if it's interrupted by signals.
3548 int mm_take_all_locks(struct mm_struct *mm)
3550 struct vm_area_struct *vma;
3551 struct anon_vma_chain *avc;
3553 mmap_assert_write_locked(mm);
3555 mutex_lock(&mm_all_locks_mutex);
3557 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3558 if (signal_pending(current))
3560 if (vma->vm_file && vma->vm_file->f_mapping &&
3561 is_vm_hugetlb_page(vma))
3562 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3565 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3566 if (signal_pending(current))
3568 if (vma->vm_file && vma->vm_file->f_mapping &&
3569 !is_vm_hugetlb_page(vma))
3570 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3573 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3574 if (signal_pending(current))
3577 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3578 vm_lock_anon_vma(mm, avc->anon_vma);
3584 mm_drop_all_locks(mm);
3588 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3590 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3592 * The LSB of head.next can't change to 0 from under
3593 * us because we hold the mm_all_locks_mutex.
3595 * We must however clear the bitflag before unlocking
3596 * the vma so the users using the anon_vma->rb_root will
3597 * never see our bitflag.
3599 * No need of atomic instructions here, head.next
3600 * can't change from under us until we release the
3601 * anon_vma->root->rwsem.
3603 if (!__test_and_clear_bit(0, (unsigned long *)
3604 &anon_vma->root->rb_root.rb_root.rb_node))
3606 anon_vma_unlock_write(anon_vma);
3610 static void vm_unlock_mapping(struct address_space *mapping)
3612 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3614 * AS_MM_ALL_LOCKS can't change to 0 from under us
3615 * because we hold the mm_all_locks_mutex.
3617 i_mmap_unlock_write(mapping);
3618 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3625 * The mmap_lock cannot be released by the caller until
3626 * mm_drop_all_locks() returns.
3628 void mm_drop_all_locks(struct mm_struct *mm)
3630 struct vm_area_struct *vma;
3631 struct anon_vma_chain *avc;
3633 mmap_assert_write_locked(mm);
3634 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3636 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3638 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3639 vm_unlock_anon_vma(avc->anon_vma);
3640 if (vma->vm_file && vma->vm_file->f_mapping)
3641 vm_unlock_mapping(vma->vm_file->f_mapping);
3644 mutex_unlock(&mm_all_locks_mutex);
3648 * initialise the percpu counter for VM
3650 void __init mmap_init(void)
3654 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3659 * Initialise sysctl_user_reserve_kbytes.
3661 * This is intended to prevent a user from starting a single memory hogging
3662 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3665 * The default value is min(3% of free memory, 128MB)
3666 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3668 static int init_user_reserve(void)
3670 unsigned long free_kbytes;
3672 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3674 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3677 subsys_initcall(init_user_reserve);
3680 * Initialise sysctl_admin_reserve_kbytes.
3682 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3683 * to log in and kill a memory hogging process.
3685 * Systems with more than 256MB will reserve 8MB, enough to recover
3686 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3687 * only reserve 3% of free pages by default.
3689 static int init_admin_reserve(void)
3691 unsigned long free_kbytes;
3693 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3695 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3698 subsys_initcall(init_admin_reserve);
3701 * Reinititalise user and admin reserves if memory is added or removed.
3703 * The default user reserve max is 128MB, and the default max for the
3704 * admin reserve is 8MB. These are usually, but not always, enough to
3705 * enable recovery from a memory hogging process using login/sshd, a shell,
3706 * and tools like top. It may make sense to increase or even disable the
3707 * reserve depending on the existence of swap or variations in the recovery
3708 * tools. So, the admin may have changed them.
3710 * If memory is added and the reserves have been eliminated or increased above
3711 * the default max, then we'll trust the admin.
3713 * If memory is removed and there isn't enough free memory, then we
3714 * need to reset the reserves.
3716 * Otherwise keep the reserve set by the admin.
3718 static int reserve_mem_notifier(struct notifier_block *nb,
3719 unsigned long action, void *data)
3721 unsigned long tmp, free_kbytes;
3725 /* Default max is 128MB. Leave alone if modified by operator. */
3726 tmp = sysctl_user_reserve_kbytes;
3727 if (0 < tmp && tmp < (1UL << 17))
3728 init_user_reserve();
3730 /* Default max is 8MB. Leave alone if modified by operator. */
3731 tmp = sysctl_admin_reserve_kbytes;
3732 if (0 < tmp && tmp < (1UL << 13))
3733 init_admin_reserve();
3737 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3739 if (sysctl_user_reserve_kbytes > free_kbytes) {
3740 init_user_reserve();
3741 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3742 sysctl_user_reserve_kbytes);
3745 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3746 init_admin_reserve();
3747 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3748 sysctl_admin_reserve_kbytes);
3757 static struct notifier_block reserve_mem_nb = {
3758 .notifier_call = reserve_mem_notifier,
3761 static int __meminit init_reserve_notifier(void)
3763 if (register_hotmemory_notifier(&reserve_mem_nb))
3764 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3768 subsys_initcall(init_reserve_notifier);