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/vmacache.h>
17 #include <linux/shm.h>
18 #include <linux/mman.h>
19 #include <linux/pagemap.h>
20 #include <linux/swap.h>
21 #include <linux/syscalls.h>
22 #include <linux/capability.h>
23 #include <linux/init.h>
24 #include <linux/file.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/hugetlb.h>
29 #include <linux/shmem_fs.h>
30 #include <linux/profile.h>
31 #include <linux/export.h>
32 #include <linux/mount.h>
33 #include <linux/mempolicy.h>
34 #include <linux/rmap.h>
35 #include <linux/mmu_notifier.h>
36 #include <linux/mmdebug.h>
37 #include <linux/perf_event.h>
38 #include <linux/audit.h>
39 #include <linux/khugepaged.h>
40 #include <linux/uprobes.h>
41 #include <linux/rbtree_augmented.h>
42 #include <linux/notifier.h>
43 #include <linux/memory.h>
44 #include <linux/printk.h>
45 #include <linux/userfaultfd_k.h>
46 #include <linux/moduleparam.h>
47 #include <linux/pkeys.h>
48 #include <linux/oom.h>
49 #include <linux/sched/mm.h>
51 #include <linux/uaccess.h>
52 #include <asm/cacheflush.h>
54 #include <asm/mmu_context.h>
58 #ifndef arch_mmap_check
59 #define arch_mmap_check(addr, len, flags) (0)
62 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
63 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
64 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
65 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
67 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
68 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
69 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
70 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
73 static bool ignore_rlimit_data;
74 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
76 static void unmap_region(struct mm_struct *mm,
77 struct vm_area_struct *vma, struct vm_area_struct *prev,
78 unsigned long start, unsigned long end);
80 /* description of effects of mapping type and prot in current implementation.
81 * this is due to the limited x86 page protection hardware. The expected
82 * behavior is in parens:
85 * PROT_NONE PROT_READ PROT_WRITE PROT_EXEC
86 * MAP_SHARED r: (no) no r: (yes) yes r: (no) yes r: (no) yes
87 * w: (no) no w: (no) no w: (yes) yes w: (no) no
88 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
90 * MAP_PRIVATE r: (no) no r: (yes) yes r: (no) yes r: (no) yes
91 * w: (no) no w: (no) no w: (copy) copy w: (no) no
92 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
94 pgprot_t protection_map[16] __ro_after_init = {
95 __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
96 __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
99 #ifndef CONFIG_ARCH_HAS_FILTER_PGPROT
100 static inline pgprot_t arch_filter_pgprot(pgprot_t prot)
106 pgprot_t vm_get_page_prot(unsigned long vm_flags)
108 pgprot_t ret = __pgprot(pgprot_val(protection_map[vm_flags &
109 (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
110 pgprot_val(arch_vm_get_page_prot(vm_flags)));
112 return arch_filter_pgprot(ret);
114 EXPORT_SYMBOL(vm_get_page_prot);
116 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
118 return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
121 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
122 void vma_set_page_prot(struct vm_area_struct *vma)
124 unsigned long vm_flags = vma->vm_flags;
125 pgprot_t vm_page_prot;
127 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
128 if (vma_wants_writenotify(vma, vm_page_prot)) {
129 vm_flags &= ~VM_SHARED;
130 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
132 /* remove_protection_ptes reads vma->vm_page_prot without mmap_sem */
133 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
137 * Requires inode->i_mapping->i_mmap_rwsem
139 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
140 struct file *file, struct address_space *mapping)
142 if (vma->vm_flags & VM_DENYWRITE)
143 atomic_inc(&file_inode(file)->i_writecount);
144 if (vma->vm_flags & VM_SHARED)
145 mapping_unmap_writable(mapping);
147 flush_dcache_mmap_lock(mapping);
148 vma_interval_tree_remove(vma, &mapping->i_mmap);
149 flush_dcache_mmap_unlock(mapping);
153 * Unlink a file-based vm structure from its interval tree, to hide
154 * vma from rmap and vmtruncate before freeing its page tables.
156 void unlink_file_vma(struct vm_area_struct *vma)
158 struct file *file = vma->vm_file;
161 struct address_space *mapping = file->f_mapping;
162 i_mmap_lock_write(mapping);
163 __remove_shared_vm_struct(vma, file, mapping);
164 i_mmap_unlock_write(mapping);
169 * Close a vm structure and free it, returning the next.
171 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
173 struct vm_area_struct *next = vma->vm_next;
176 if (vma->vm_ops && vma->vm_ops->close)
177 vma->vm_ops->close(vma);
180 mpol_put(vma_policy(vma));
185 static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,
186 struct list_head *uf);
187 SYSCALL_DEFINE1(brk, unsigned long, brk)
189 unsigned long retval;
190 unsigned long newbrk, oldbrk, origbrk;
191 struct mm_struct *mm = current->mm;
192 struct vm_area_struct *next;
193 unsigned long min_brk;
195 bool downgraded = false;
198 brk = untagged_addr(brk);
200 if (down_write_killable(&mm->mmap_sem))
205 #ifdef CONFIG_COMPAT_BRK
207 * CONFIG_COMPAT_BRK can still be overridden by setting
208 * randomize_va_space to 2, which will still cause mm->start_brk
209 * to be arbitrarily shifted
211 if (current->brk_randomized)
212 min_brk = mm->start_brk;
214 min_brk = mm->end_data;
216 min_brk = mm->start_brk;
222 * Check against rlimit here. If this check is done later after the test
223 * of oldbrk with newbrk then it can escape the test and let the data
224 * segment grow beyond its set limit the in case where the limit is
225 * not page aligned -Ram Gupta
227 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
228 mm->end_data, mm->start_data))
231 newbrk = PAGE_ALIGN(brk);
232 oldbrk = PAGE_ALIGN(mm->brk);
233 if (oldbrk == newbrk) {
239 * Always allow shrinking brk.
240 * __do_munmap() may downgrade mmap_sem to read.
242 if (brk <= mm->brk) {
246 * mm->brk must to be protected by write mmap_sem so update it
247 * before downgrading mmap_sem. When __do_munmap() fails,
248 * mm->brk will be restored from origbrk.
251 ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
255 } else if (ret == 1) {
261 /* Check against existing mmap mappings. */
262 next = find_vma(mm, oldbrk);
263 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
266 /* Ok, looks good - let it rip. */
267 if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
272 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
274 up_read(&mm->mmap_sem);
276 up_write(&mm->mmap_sem);
277 userfaultfd_unmap_complete(mm, &uf);
279 mm_populate(oldbrk, newbrk - oldbrk);
284 up_write(&mm->mmap_sem);
288 static inline unsigned long vma_compute_gap(struct vm_area_struct *vma)
290 unsigned long gap, prev_end;
293 * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
294 * allow two stack_guard_gaps between them here, and when choosing
295 * an unmapped area; whereas when expanding we only require one.
296 * That's a little inconsistent, but keeps the code here simpler.
298 gap = vm_start_gap(vma);
300 prev_end = vm_end_gap(vma->vm_prev);
309 #ifdef CONFIG_DEBUG_VM_RB
310 static unsigned long vma_compute_subtree_gap(struct vm_area_struct *vma)
312 unsigned long max = vma_compute_gap(vma), subtree_gap;
313 if (vma->vm_rb.rb_left) {
314 subtree_gap = rb_entry(vma->vm_rb.rb_left,
315 struct vm_area_struct, vm_rb)->rb_subtree_gap;
316 if (subtree_gap > max)
319 if (vma->vm_rb.rb_right) {
320 subtree_gap = rb_entry(vma->vm_rb.rb_right,
321 struct vm_area_struct, vm_rb)->rb_subtree_gap;
322 if (subtree_gap > max)
328 static int browse_rb(struct mm_struct *mm)
330 struct rb_root *root = &mm->mm_rb;
331 int i = 0, j, bug = 0;
332 struct rb_node *nd, *pn = NULL;
333 unsigned long prev = 0, pend = 0;
335 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
336 struct vm_area_struct *vma;
337 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
338 if (vma->vm_start < prev) {
339 pr_emerg("vm_start %lx < prev %lx\n",
340 vma->vm_start, prev);
343 if (vma->vm_start < pend) {
344 pr_emerg("vm_start %lx < pend %lx\n",
345 vma->vm_start, pend);
348 if (vma->vm_start > vma->vm_end) {
349 pr_emerg("vm_start %lx > vm_end %lx\n",
350 vma->vm_start, vma->vm_end);
353 spin_lock(&mm->page_table_lock);
354 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
355 pr_emerg("free gap %lx, correct %lx\n",
357 vma_compute_subtree_gap(vma));
360 spin_unlock(&mm->page_table_lock);
363 prev = vma->vm_start;
367 for (nd = pn; nd; nd = rb_prev(nd))
370 pr_emerg("backwards %d, forwards %d\n", j, i);
376 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
380 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
381 struct vm_area_struct *vma;
382 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
383 VM_BUG_ON_VMA(vma != ignore &&
384 vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
389 static void validate_mm(struct mm_struct *mm)
393 unsigned long highest_address = 0;
394 struct vm_area_struct *vma = mm->mmap;
397 struct anon_vma *anon_vma = vma->anon_vma;
398 struct anon_vma_chain *avc;
401 anon_vma_lock_read(anon_vma);
402 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
403 anon_vma_interval_tree_verify(avc);
404 anon_vma_unlock_read(anon_vma);
407 highest_address = vm_end_gap(vma);
411 if (i != mm->map_count) {
412 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
415 if (highest_address != mm->highest_vm_end) {
416 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
417 mm->highest_vm_end, highest_address);
421 if (i != mm->map_count) {
423 pr_emerg("map_count %d rb %d\n", mm->map_count, i);
426 VM_BUG_ON_MM(bug, mm);
429 #define validate_mm_rb(root, ignore) do { } while (0)
430 #define validate_mm(mm) do { } while (0)
433 RB_DECLARE_CALLBACKS_MAX(static, vma_gap_callbacks,
434 struct vm_area_struct, vm_rb,
435 unsigned long, rb_subtree_gap, vma_compute_gap)
438 * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
439 * vma->vm_prev->vm_end values changed, without modifying the vma's position
442 static void vma_gap_update(struct vm_area_struct *vma)
445 * As it turns out, RB_DECLARE_CALLBACKS_MAX() already created
446 * a callback function that does exactly what we want.
448 vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
451 static inline void vma_rb_insert(struct vm_area_struct *vma,
452 struct rb_root *root)
454 /* All rb_subtree_gap values must be consistent prior to insertion */
455 validate_mm_rb(root, NULL);
457 rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
460 static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
463 * Note rb_erase_augmented is a fairly large inline function,
464 * so make sure we instantiate it only once with our desired
465 * augmented rbtree callbacks.
467 rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
470 static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
471 struct rb_root *root,
472 struct vm_area_struct *ignore)
475 * All rb_subtree_gap values must be consistent prior to erase,
476 * with the possible exception of the "next" vma being erased if
477 * next->vm_start was reduced.
479 validate_mm_rb(root, ignore);
481 __vma_rb_erase(vma, root);
484 static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
485 struct rb_root *root)
488 * All rb_subtree_gap values must be consistent prior to erase,
489 * with the possible exception of the vma being erased.
491 validate_mm_rb(root, vma);
493 __vma_rb_erase(vma, root);
497 * vma has some anon_vma assigned, and is already inserted on that
498 * anon_vma's interval trees.
500 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
501 * vma must be removed from the anon_vma's interval trees using
502 * anon_vma_interval_tree_pre_update_vma().
504 * After the update, the vma will be reinserted using
505 * anon_vma_interval_tree_post_update_vma().
507 * The entire update must be protected by exclusive mmap_sem and by
508 * the root anon_vma's mutex.
511 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
513 struct anon_vma_chain *avc;
515 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
516 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
520 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
522 struct anon_vma_chain *avc;
524 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
525 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
528 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
529 unsigned long end, struct vm_area_struct **pprev,
530 struct rb_node ***rb_link, struct rb_node **rb_parent)
532 struct rb_node **__rb_link, *__rb_parent, *rb_prev;
534 __rb_link = &mm->mm_rb.rb_node;
535 rb_prev = __rb_parent = NULL;
538 struct vm_area_struct *vma_tmp;
540 __rb_parent = *__rb_link;
541 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
543 if (vma_tmp->vm_end > addr) {
544 /* Fail if an existing vma overlaps the area */
545 if (vma_tmp->vm_start < end)
547 __rb_link = &__rb_parent->rb_left;
549 rb_prev = __rb_parent;
550 __rb_link = &__rb_parent->rb_right;
556 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
557 *rb_link = __rb_link;
558 *rb_parent = __rb_parent;
562 static unsigned long count_vma_pages_range(struct mm_struct *mm,
563 unsigned long addr, unsigned long end)
565 unsigned long nr_pages = 0;
566 struct vm_area_struct *vma;
568 /* Find first overlaping mapping */
569 vma = find_vma_intersection(mm, addr, end);
573 nr_pages = (min(end, vma->vm_end) -
574 max(addr, vma->vm_start)) >> PAGE_SHIFT;
576 /* Iterate over the rest of the overlaps */
577 for (vma = vma->vm_next; vma; vma = vma->vm_next) {
578 unsigned long overlap_len;
580 if (vma->vm_start > end)
583 overlap_len = min(end, vma->vm_end) - vma->vm_start;
584 nr_pages += overlap_len >> PAGE_SHIFT;
590 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
591 struct rb_node **rb_link, struct rb_node *rb_parent)
593 /* Update tracking information for the gap following the new vma. */
595 vma_gap_update(vma->vm_next);
597 mm->highest_vm_end = vm_end_gap(vma);
600 * vma->vm_prev wasn't known when we followed the rbtree to find the
601 * correct insertion point for that vma. As a result, we could not
602 * update the vma vm_rb parents rb_subtree_gap values on the way down.
603 * So, we first insert the vma with a zero rb_subtree_gap value
604 * (to be consistent with what we did on the way down), and then
605 * immediately update the gap to the correct value. Finally we
606 * rebalance the rbtree after all augmented values have been set.
608 rb_link_node(&vma->vm_rb, rb_parent, rb_link);
609 vma->rb_subtree_gap = 0;
611 vma_rb_insert(vma, &mm->mm_rb);
614 static void __vma_link_file(struct vm_area_struct *vma)
620 struct address_space *mapping = file->f_mapping;
622 if (vma->vm_flags & VM_DENYWRITE)
623 atomic_dec(&file_inode(file)->i_writecount);
624 if (vma->vm_flags & VM_SHARED)
625 atomic_inc(&mapping->i_mmap_writable);
627 flush_dcache_mmap_lock(mapping);
628 vma_interval_tree_insert(vma, &mapping->i_mmap);
629 flush_dcache_mmap_unlock(mapping);
634 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
635 struct vm_area_struct *prev, struct rb_node **rb_link,
636 struct rb_node *rb_parent)
638 __vma_link_list(mm, vma, prev, rb_parent);
639 __vma_link_rb(mm, vma, rb_link, rb_parent);
642 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
643 struct vm_area_struct *prev, struct rb_node **rb_link,
644 struct rb_node *rb_parent)
646 struct address_space *mapping = NULL;
649 mapping = vma->vm_file->f_mapping;
650 i_mmap_lock_write(mapping);
653 __vma_link(mm, vma, prev, rb_link, rb_parent);
654 __vma_link_file(vma);
657 i_mmap_unlock_write(mapping);
664 * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
665 * mm's list and rbtree. It has already been inserted into the interval tree.
667 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
669 struct vm_area_struct *prev;
670 struct rb_node **rb_link, *rb_parent;
672 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
673 &prev, &rb_link, &rb_parent))
675 __vma_link(mm, vma, prev, rb_link, rb_parent);
679 static __always_inline void __vma_unlink_common(struct mm_struct *mm,
680 struct vm_area_struct *vma,
681 struct vm_area_struct *prev,
683 struct vm_area_struct *ignore)
685 struct vm_area_struct *next;
687 vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
690 prev->vm_next = next;
694 prev->vm_next = next;
699 next->vm_prev = prev;
702 vmacache_invalidate(mm);
705 static inline void __vma_unlink_prev(struct mm_struct *mm,
706 struct vm_area_struct *vma,
707 struct vm_area_struct *prev)
709 __vma_unlink_common(mm, vma, prev, true, vma);
713 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
714 * is already present in an i_mmap tree without adjusting the tree.
715 * The following helper function should be used when such adjustments
716 * are necessary. The "insert" vma (if any) is to be inserted
717 * before we drop the necessary locks.
719 int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
720 unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
721 struct vm_area_struct *expand)
723 struct mm_struct *mm = vma->vm_mm;
724 struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
725 struct address_space *mapping = NULL;
726 struct rb_root_cached *root = NULL;
727 struct anon_vma *anon_vma = NULL;
728 struct file *file = vma->vm_file;
729 bool start_changed = false, end_changed = false;
730 long adjust_next = 0;
733 if (next && !insert) {
734 struct vm_area_struct *exporter = NULL, *importer = NULL;
736 if (end >= next->vm_end) {
738 * vma expands, overlapping all the next, and
739 * perhaps the one after too (mprotect case 6).
740 * The only other cases that gets here are
741 * case 1, case 7 and case 8.
743 if (next == expand) {
745 * The only case where we don't expand "vma"
746 * and we expand "next" instead is case 8.
748 VM_WARN_ON(end != next->vm_end);
750 * remove_next == 3 means we're
751 * removing "vma" and that to do so we
752 * swapped "vma" and "next".
755 VM_WARN_ON(file != next->vm_file);
758 VM_WARN_ON(expand != vma);
760 * case 1, 6, 7, remove_next == 2 is case 6,
761 * remove_next == 1 is case 1 or 7.
763 remove_next = 1 + (end > next->vm_end);
764 VM_WARN_ON(remove_next == 2 &&
765 end != next->vm_next->vm_end);
766 VM_WARN_ON(remove_next == 1 &&
767 end != 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) >> PAGE_SHIFT;
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) >> PAGE_SHIFT);
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 << PAGE_SHIFT;
870 next->vm_pgoff += adjust_next;
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_prev(mm, next, vma);
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_common(mm, next, NULL, false, 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);
925 i_mmap_unlock_write(mapping);
936 uprobe_munmap(next, next->vm_start, next->vm_end);
940 anon_vma_merge(vma, next);
942 mpol_put(vma_policy(next));
945 * In mprotect's case 6 (see comments on vma_merge),
946 * we must remove another next too. It would clutter
947 * up the code too much to do both in one go.
949 if (remove_next != 3) {
951 * If "next" was removed and vma->vm_end was
952 * expanded (up) over it, in turn
953 * "next->vm_prev->vm_end" changed and the
954 * "vma->vm_next" gap must be updated.
959 * For the scope of the comment "next" and
960 * "vma" considered pre-swap(): if "vma" was
961 * removed, next->vm_start was expanded (down)
962 * over it and the "next" gap must be updated.
963 * Because of the swap() the post-swap() "vma"
964 * actually points to pre-swap() "next"
965 * (post-swap() "next" as opposed is now a
970 if (remove_next == 2) {
976 vma_gap_update(next);
979 * If remove_next == 2 we obviously can't
982 * If remove_next == 3 we can't reach this
983 * path because pre-swap() next is always not
984 * NULL. pre-swap() "next" is not being
985 * removed and its next->vm_end is not altered
986 * (and furthermore "end" already matches
987 * next->vm_end in remove_next == 3).
989 * We reach this only in the remove_next == 1
990 * case if the "next" vma that was removed was
991 * the highest vma of the mm. However in such
992 * case next->vm_end == "end" and the extended
993 * "vma" has vma->vm_end == next->vm_end so
994 * mm->highest_vm_end doesn't need any update
995 * in remove_next == 1 case.
997 VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
1001 uprobe_mmap(insert);
1009 * If the vma has a ->close operation then the driver probably needs to release
1010 * per-vma resources, so we don't attempt to merge those.
1012 static inline int is_mergeable_vma(struct vm_area_struct *vma,
1013 struct file *file, unsigned long vm_flags,
1014 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
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))
1035 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
1036 struct anon_vma *anon_vma2,
1037 struct vm_area_struct *vma)
1040 * The list_is_singular() test is to avoid merging VMA cloned from
1041 * parents. This can improve scalability caused by anon_vma lock.
1043 if ((!anon_vma1 || !anon_vma2) && (!vma ||
1044 list_is_singular(&vma->anon_vma_chain)))
1046 return anon_vma1 == anon_vma2;
1050 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1051 * in front of (at a lower virtual address and file offset than) the vma.
1053 * We cannot merge two vmas if they have differently assigned (non-NULL)
1054 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1056 * We don't check here for the merged mmap wrapping around the end of pagecache
1057 * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
1058 * wrap, nor mmaps which cover the final page at index -1UL.
1061 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
1062 struct anon_vma *anon_vma, struct file *file,
1064 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
1066 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
1067 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1068 if (vma->vm_pgoff == vm_pgoff)
1075 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1076 * beyond (at a higher virtual address and file offset than) the vma.
1078 * We cannot merge two vmas if they have differently assigned (non-NULL)
1079 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1082 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
1083 struct anon_vma *anon_vma, struct file *file,
1085 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
1087 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
1088 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1090 vm_pglen = vma_pages(vma);
1091 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
1098 * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
1099 * whether that can be merged with its predecessor or its successor.
1100 * Or both (it neatly fills a hole).
1102 * In most cases - when called for mmap, brk or mremap - [addr,end) is
1103 * certain not to be mapped by the time vma_merge is called; but when
1104 * called for mprotect, it is certain to be already mapped (either at
1105 * an offset within prev, or at the start of next), and the flags of
1106 * this area are about to be changed to vm_flags - and the no-change
1107 * case has already been eliminated.
1109 * The following mprotect cases have to be considered, where AAAA is
1110 * the area passed down from mprotect_fixup, never extending beyond one
1111 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
1113 * AAAA AAAA AAAA AAAA
1114 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX
1115 * cannot merge might become might become might become
1116 * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or
1117 * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or
1118 * mremap move: PPPPXXXXXXXX 8
1120 * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN
1121 * might become case 1 below case 2 below case 3 below
1123 * It is important for case 8 that the vma NNNN overlapping the
1124 * region AAAA is never going to extended over XXXX. Instead XXXX must
1125 * be extended in region AAAA and NNNN must be removed. This way in
1126 * all cases where vma_merge succeeds, the moment vma_adjust drops the
1127 * rmap_locks, the properties of the merged vma will be already
1128 * correct for the whole merged range. Some of those properties like
1129 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1130 * be correct for the whole merged range immediately after the
1131 * rmap_locks are released. Otherwise if XXXX would be removed and
1132 * NNNN would be extended over the XXXX range, remove_migration_ptes
1133 * or other rmap walkers (if working on addresses beyond the "end"
1134 * parameter) may establish ptes with the wrong permissions of NNNN
1135 * instead of the right permissions of XXXX.
1137 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1138 struct vm_area_struct *prev, unsigned long addr,
1139 unsigned long end, unsigned long vm_flags,
1140 struct anon_vma *anon_vma, struct file *file,
1141 pgoff_t pgoff, struct mempolicy *policy,
1142 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
1144 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1145 struct vm_area_struct *area, *next;
1149 * We later require that vma->vm_flags == vm_flags,
1150 * so this tests vma->vm_flags & VM_SPECIAL, too.
1152 if (vm_flags & VM_SPECIAL)
1156 next = prev->vm_next;
1160 if (area && area->vm_end == end) /* cases 6, 7, 8 */
1161 next = next->vm_next;
1163 /* verify some invariant that must be enforced by the caller */
1164 VM_WARN_ON(prev && addr <= prev->vm_start);
1165 VM_WARN_ON(area && end > area->vm_end);
1166 VM_WARN_ON(addr >= end);
1169 * Can it merge with the predecessor?
1171 if (prev && prev->vm_end == addr &&
1172 mpol_equal(vma_policy(prev), policy) &&
1173 can_vma_merge_after(prev, vm_flags,
1174 anon_vma, file, pgoff,
1175 vm_userfaultfd_ctx)) {
1177 * OK, it can. Can we now merge in the successor as well?
1179 if (next && end == next->vm_start &&
1180 mpol_equal(policy, vma_policy(next)) &&
1181 can_vma_merge_before(next, vm_flags,
1184 vm_userfaultfd_ctx) &&
1185 is_mergeable_anon_vma(prev->anon_vma,
1186 next->anon_vma, NULL)) {
1188 err = __vma_adjust(prev, prev->vm_start,
1189 next->vm_end, prev->vm_pgoff, NULL,
1191 } else /* cases 2, 5, 7 */
1192 err = __vma_adjust(prev, prev->vm_start,
1193 end, prev->vm_pgoff, NULL, prev);
1196 khugepaged_enter_vma_merge(prev, vm_flags);
1201 * Can this new request be merged in front of next?
1203 if (next && end == next->vm_start &&
1204 mpol_equal(policy, vma_policy(next)) &&
1205 can_vma_merge_before(next, vm_flags,
1206 anon_vma, file, pgoff+pglen,
1207 vm_userfaultfd_ctx)) {
1208 if (prev && addr < prev->vm_end) /* case 4 */
1209 err = __vma_adjust(prev, prev->vm_start,
1210 addr, prev->vm_pgoff, NULL, next);
1211 else { /* cases 3, 8 */
1212 err = __vma_adjust(area, addr, next->vm_end,
1213 next->vm_pgoff - pglen, NULL, next);
1215 * In case 3 area is already equal to next and
1216 * this is a noop, but in case 8 "area" has
1217 * been removed and next was expanded over it.
1223 khugepaged_enter_vma_merge(area, vm_flags);
1231 * Rough compatbility check to quickly see if it's even worth looking
1232 * at sharing an anon_vma.
1234 * They need to have the same vm_file, and the flags can only differ
1235 * in things that mprotect may change.
1237 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1238 * we can merge the two vma's. For example, we refuse to merge a vma if
1239 * there is a vm_ops->close() function, because that indicates that the
1240 * driver is doing some kind of reference counting. But that doesn't
1241 * really matter for the anon_vma sharing case.
1243 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1245 return a->vm_end == b->vm_start &&
1246 mpol_equal(vma_policy(a), vma_policy(b)) &&
1247 a->vm_file == b->vm_file &&
1248 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
1249 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1253 * Do some basic sanity checking to see if we can re-use the anon_vma
1254 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1255 * the same as 'old', the other will be the new one that is trying
1256 * to share the anon_vma.
1258 * NOTE! This runs with mm_sem held for reading, so it is possible that
1259 * the anon_vma of 'old' is concurrently in the process of being set up
1260 * by another page fault trying to merge _that_. But that's ok: if it
1261 * is being set up, that automatically means that it will be a singleton
1262 * acceptable for merging, so we can do all of this optimistically. But
1263 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1265 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1266 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1267 * is to return an anon_vma that is "complex" due to having gone through
1270 * We also make sure that the two vma's are compatible (adjacent,
1271 * and with the same memory policies). That's all stable, even with just
1272 * a read lock on the mm_sem.
1274 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1276 if (anon_vma_compatible(a, b)) {
1277 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1279 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1286 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1287 * neighbouring vmas for a suitable anon_vma, before it goes off
1288 * to allocate a new anon_vma. It checks because a repetitive
1289 * sequence of mprotects and faults may otherwise lead to distinct
1290 * anon_vmas being allocated, preventing vma merge in subsequent
1293 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1295 struct anon_vma *anon_vma;
1296 struct vm_area_struct *near;
1298 near = vma->vm_next;
1302 anon_vma = reusable_anon_vma(near, vma, near);
1306 near = vma->vm_prev;
1310 anon_vma = reusable_anon_vma(near, near, vma);
1315 * There's no absolute need to look only at touching neighbours:
1316 * we could search further afield for "compatible" anon_vmas.
1317 * But it would probably just be a waste of time searching,
1318 * or lead to too many vmas hanging off the same anon_vma.
1319 * We're trying to allow mprotect remerging later on,
1320 * not trying to minimize memory used for anon_vmas.
1326 * If a hint addr is less than mmap_min_addr change hint to be as
1327 * low as possible but still greater than mmap_min_addr
1329 static inline unsigned long round_hint_to_min(unsigned long hint)
1332 if (((void *)hint != NULL) &&
1333 (hint < mmap_min_addr))
1334 return PAGE_ALIGN(mmap_min_addr);
1338 static inline int mlock_future_check(struct mm_struct *mm,
1339 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 hold down_write(¤t->mm->mmap_sem).
1391 unsigned long do_mmap(struct file *file, unsigned long addr,
1392 unsigned long len, unsigned long prot,
1393 unsigned long flags, vm_flags_t vm_flags,
1394 unsigned long pgoff, unsigned long *populate,
1395 struct list_head *uf)
1397 struct mm_struct *mm = current->mm;
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 (offset_in_page(addr))
1442 if (flags & MAP_FIXED_NOREPLACE) {
1443 struct vm_area_struct *vma = find_vma(mm, addr);
1445 if (vma && vma->vm_start < addr + len)
1449 if (prot == PROT_EXEC) {
1450 pkey = execute_only_pkey(mm);
1455 /* Do simple checking here so the lower-level routines won't have
1456 * to. we assume access permissions have been handled by the open
1457 * of the memory object, so we don't do any here.
1459 vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1460 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1462 if (flags & MAP_LOCKED)
1463 if (!can_do_mlock())
1466 if (mlock_future_check(mm, vm_flags, len))
1470 struct inode *inode = file_inode(file);
1471 unsigned long flags_mask;
1473 if (!file_mmap_ok(file, inode, pgoff, len))
1476 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1478 switch (flags & MAP_TYPE) {
1481 * Force use of MAP_SHARED_VALIDATE with non-legacy
1482 * flags. E.g. MAP_SYNC is dangerous to use with
1483 * MAP_SHARED as you don't know which consistency model
1484 * you will get. We silently ignore unsupported flags
1485 * with MAP_SHARED to preserve backward compatibility.
1487 flags &= LEGACY_MAP_MASK;
1489 case MAP_SHARED_VALIDATE:
1490 if (flags & ~flags_mask)
1492 if (prot & PROT_WRITE) {
1493 if (!(file->f_mode & FMODE_WRITE))
1495 if (IS_SWAPFILE(file->f_mapping->host))
1500 * Make sure we don't allow writing to an append-only
1503 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1507 * Make sure there are no mandatory locks on the file.
1509 if (locks_verify_locked(file))
1512 vm_flags |= VM_SHARED | VM_MAYSHARE;
1513 if (!(file->f_mode & FMODE_WRITE))
1514 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1518 if (!(file->f_mode & FMODE_READ))
1520 if (path_noexec(&file->f_path)) {
1521 if (vm_flags & VM_EXEC)
1523 vm_flags &= ~VM_MAYEXEC;
1526 if (!file->f_op->mmap)
1528 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1536 switch (flags & MAP_TYPE) {
1538 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1544 vm_flags |= VM_SHARED | VM_MAYSHARE;
1548 * Set pgoff according to addr for anon_vma.
1550 pgoff = addr >> PAGE_SHIFT;
1558 * Set 'VM_NORESERVE' if we should not account for the
1559 * memory use of this mapping.
1561 if (flags & MAP_NORESERVE) {
1562 /* We honor MAP_NORESERVE if allowed to overcommit */
1563 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1564 vm_flags |= VM_NORESERVE;
1566 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1567 if (file && is_file_hugepages(file))
1568 vm_flags |= VM_NORESERVE;
1571 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1572 if (!IS_ERR_VALUE(addr) &&
1573 ((vm_flags & VM_LOCKED) ||
1574 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1579 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1580 unsigned long prot, unsigned long flags,
1581 unsigned long fd, unsigned long pgoff)
1583 struct file *file = NULL;
1584 unsigned long retval;
1586 addr = untagged_addr(addr);
1588 if (!(flags & MAP_ANONYMOUS)) {
1589 audit_mmap_fd(fd, flags);
1593 if (is_file_hugepages(file))
1594 len = ALIGN(len, huge_page_size(hstate_file(file)));
1596 if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
1598 } else if (flags & MAP_HUGETLB) {
1599 struct user_struct *user = NULL;
1602 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1606 len = ALIGN(len, huge_page_size(hs));
1608 * VM_NORESERVE is used because the reservations will be
1609 * taken when vm_ops->mmap() is called
1610 * A dummy user value is used because we are not locking
1611 * memory so no accounting is necessary
1613 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1615 &user, HUGETLB_ANONHUGE_INODE,
1616 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1618 return PTR_ERR(file);
1621 flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1623 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1630 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1631 unsigned long, prot, unsigned long, flags,
1632 unsigned long, fd, unsigned long, pgoff)
1634 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1637 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1638 struct mmap_arg_struct {
1642 unsigned long flags;
1644 unsigned long offset;
1647 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1649 struct mmap_arg_struct a;
1651 if (copy_from_user(&a, arg, sizeof(a)))
1653 if (offset_in_page(a.offset))
1656 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1657 a.offset >> PAGE_SHIFT);
1659 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1662 * Some shared mappings will want the pages marked read-only
1663 * to track write events. If so, we'll downgrade vm_page_prot
1664 * to the private version (using protection_map[] without the
1667 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1669 vm_flags_t vm_flags = vma->vm_flags;
1670 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1672 /* If it was private or non-writable, the write bit is already clear */
1673 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1676 /* The backer wishes to know when pages are first written to? */
1677 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1680 /* The open routine did something to the protections that pgprot_modify
1681 * won't preserve? */
1682 if (pgprot_val(vm_page_prot) !=
1683 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1686 /* Do we need to track softdirty? */
1687 if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
1690 /* Specialty mapping? */
1691 if (vm_flags & VM_PFNMAP)
1694 /* Can the mapping track the dirty pages? */
1695 return vma->vm_file && vma->vm_file->f_mapping &&
1696 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1700 * We account for memory if it's a private writeable mapping,
1701 * not hugepages and VM_NORESERVE wasn't set.
1703 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1706 * hugetlb has its own accounting separate from the core VM
1707 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1709 if (file && is_file_hugepages(file))
1712 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1715 unsigned long mmap_region(struct file *file, unsigned long addr,
1716 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1717 struct list_head *uf)
1719 struct mm_struct *mm = current->mm;
1720 struct vm_area_struct *vma, *prev;
1722 struct rb_node **rb_link, *rb_parent;
1723 unsigned long charged = 0;
1725 /* Check against address space limit. */
1726 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1727 unsigned long nr_pages;
1730 * MAP_FIXED may remove pages of mappings that intersects with
1731 * requested mapping. Account for the pages it would unmap.
1733 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1735 if (!may_expand_vm(mm, vm_flags,
1736 (len >> PAGE_SHIFT) - nr_pages))
1740 /* Clear old maps */
1741 while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
1743 if (do_munmap(mm, addr, len, uf))
1748 * Private writable mapping: check memory availability
1750 if (accountable_mapping(file, vm_flags)) {
1751 charged = len >> PAGE_SHIFT;
1752 if (security_vm_enough_memory_mm(mm, charged))
1754 vm_flags |= VM_ACCOUNT;
1758 * Can we just expand an old mapping?
1760 vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1761 NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);
1766 * Determine the object being mapped and call the appropriate
1767 * specific mapper. the address has already been validated, but
1768 * not unmapped, but the maps are removed from the list.
1770 vma = vm_area_alloc(mm);
1776 vma->vm_start = addr;
1777 vma->vm_end = addr + len;
1778 vma->vm_flags = vm_flags;
1779 vma->vm_page_prot = vm_get_page_prot(vm_flags);
1780 vma->vm_pgoff = pgoff;
1783 if (vm_flags & VM_DENYWRITE) {
1784 error = deny_write_access(file);
1788 if (vm_flags & VM_SHARED) {
1789 error = mapping_map_writable(file->f_mapping);
1791 goto allow_write_and_free_vma;
1794 /* ->mmap() can change vma->vm_file, but must guarantee that
1795 * vma_link() below can deny write-access if VM_DENYWRITE is set
1796 * and map writably if VM_SHARED is set. This usually means the
1797 * new file must not have been exposed to user-space, yet.
1799 vma->vm_file = get_file(file);
1800 error = call_mmap(file, vma);
1802 goto unmap_and_free_vma;
1804 /* Can addr have changed??
1806 * Answer: Yes, several device drivers can do it in their
1807 * f_op->mmap method. -DaveM
1808 * Bug: If addr is changed, prev, rb_link, rb_parent should
1809 * be updated for vma_link()
1811 WARN_ON_ONCE(addr != vma->vm_start);
1813 addr = vma->vm_start;
1814 vm_flags = vma->vm_flags;
1815 } else if (vm_flags & VM_SHARED) {
1816 error = shmem_zero_setup(vma);
1820 vma_set_anonymous(vma);
1823 vma_link(mm, vma, prev, rb_link, rb_parent);
1824 /* Once vma denies write, undo our temporary denial count */
1826 if (vm_flags & VM_SHARED)
1827 mapping_unmap_writable(file->f_mapping);
1828 if (vm_flags & VM_DENYWRITE)
1829 allow_write_access(file);
1831 file = vma->vm_file;
1833 perf_event_mmap(vma);
1835 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
1836 if (vm_flags & VM_LOCKED) {
1837 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1838 is_vm_hugetlb_page(vma) ||
1839 vma == get_gate_vma(current->mm))
1840 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1842 mm->locked_vm += (len >> PAGE_SHIFT);
1849 * New (or expanded) vma always get soft dirty status.
1850 * Otherwise user-space soft-dirty page tracker won't
1851 * be able to distinguish situation when vma area unmapped,
1852 * then new mapped in-place (which must be aimed as
1853 * a completely new data area).
1855 vma->vm_flags |= VM_SOFTDIRTY;
1857 vma_set_page_prot(vma);
1862 vma->vm_file = NULL;
1865 /* Undo any partial mapping done by a device driver. */
1866 unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1868 if (vm_flags & VM_SHARED)
1869 mapping_unmap_writable(file->f_mapping);
1870 allow_write_and_free_vma:
1871 if (vm_flags & VM_DENYWRITE)
1872 allow_write_access(file);
1877 vm_unacct_memory(charged);
1881 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1884 * We implement the search by looking for an rbtree node that
1885 * immediately follows a suitable gap. That is,
1886 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1887 * - gap_end = vma->vm_start >= info->low_limit + length;
1888 * - gap_end - gap_start >= length
1891 struct mm_struct *mm = current->mm;
1892 struct vm_area_struct *vma;
1893 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1895 /* Adjust search length to account for worst case alignment overhead */
1896 length = info->length + info->align_mask;
1897 if (length < info->length)
1900 /* Adjust search limits by the desired length */
1901 if (info->high_limit < length)
1903 high_limit = info->high_limit - length;
1905 if (info->low_limit > high_limit)
1907 low_limit = info->low_limit + length;
1909 /* Check if rbtree root looks promising */
1910 if (RB_EMPTY_ROOT(&mm->mm_rb))
1912 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1913 if (vma->rb_subtree_gap < length)
1917 /* Visit left subtree if it looks promising */
1918 gap_end = vm_start_gap(vma);
1919 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1920 struct vm_area_struct *left =
1921 rb_entry(vma->vm_rb.rb_left,
1922 struct vm_area_struct, vm_rb);
1923 if (left->rb_subtree_gap >= length) {
1929 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1931 /* Check if current node has a suitable gap */
1932 if (gap_start > high_limit)
1934 if (gap_end >= low_limit &&
1935 gap_end > gap_start && gap_end - gap_start >= length)
1938 /* Visit right subtree if it looks promising */
1939 if (vma->vm_rb.rb_right) {
1940 struct vm_area_struct *right =
1941 rb_entry(vma->vm_rb.rb_right,
1942 struct vm_area_struct, vm_rb);
1943 if (right->rb_subtree_gap >= length) {
1949 /* Go back up the rbtree to find next candidate node */
1951 struct rb_node *prev = &vma->vm_rb;
1952 if (!rb_parent(prev))
1954 vma = rb_entry(rb_parent(prev),
1955 struct vm_area_struct, vm_rb);
1956 if (prev == vma->vm_rb.rb_left) {
1957 gap_start = vm_end_gap(vma->vm_prev);
1958 gap_end = vm_start_gap(vma);
1965 /* Check highest gap, which does not precede any rbtree node */
1966 gap_start = mm->highest_vm_end;
1967 gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
1968 if (gap_start > high_limit)
1972 /* We found a suitable gap. Clip it with the original low_limit. */
1973 if (gap_start < info->low_limit)
1974 gap_start = info->low_limit;
1976 /* Adjust gap address to the desired alignment */
1977 gap_start += (info->align_offset - gap_start) & info->align_mask;
1979 VM_BUG_ON(gap_start + info->length > info->high_limit);
1980 VM_BUG_ON(gap_start + info->length > gap_end);
1984 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1986 struct mm_struct *mm = current->mm;
1987 struct vm_area_struct *vma;
1988 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1990 /* Adjust search length to account for worst case alignment overhead */
1991 length = info->length + info->align_mask;
1992 if (length < info->length)
1996 * Adjust search limits by the desired length.
1997 * See implementation comment at top of unmapped_area().
1999 gap_end = info->high_limit;
2000 if (gap_end < length)
2002 high_limit = gap_end - length;
2004 if (info->low_limit > high_limit)
2006 low_limit = info->low_limit + length;
2008 /* Check highest gap, which does not precede any rbtree node */
2009 gap_start = mm->highest_vm_end;
2010 if (gap_start <= high_limit)
2013 /* Check if rbtree root looks promising */
2014 if (RB_EMPTY_ROOT(&mm->mm_rb))
2016 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2017 if (vma->rb_subtree_gap < length)
2021 /* Visit right subtree if it looks promising */
2022 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2023 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
2024 struct vm_area_struct *right =
2025 rb_entry(vma->vm_rb.rb_right,
2026 struct vm_area_struct, vm_rb);
2027 if (right->rb_subtree_gap >= length) {
2034 /* Check if current node has a suitable gap */
2035 gap_end = vm_start_gap(vma);
2036 if (gap_end < low_limit)
2038 if (gap_start <= high_limit &&
2039 gap_end > gap_start && gap_end - gap_start >= length)
2042 /* Visit left subtree if it looks promising */
2043 if (vma->vm_rb.rb_left) {
2044 struct vm_area_struct *left =
2045 rb_entry(vma->vm_rb.rb_left,
2046 struct vm_area_struct, vm_rb);
2047 if (left->rb_subtree_gap >= length) {
2053 /* Go back up the rbtree to find next candidate node */
2055 struct rb_node *prev = &vma->vm_rb;
2056 if (!rb_parent(prev))
2058 vma = rb_entry(rb_parent(prev),
2059 struct vm_area_struct, vm_rb);
2060 if (prev == vma->vm_rb.rb_right) {
2061 gap_start = vma->vm_prev ?
2062 vm_end_gap(vma->vm_prev) : 0;
2069 /* We found a suitable gap. Clip it with the original high_limit. */
2070 if (gap_end > info->high_limit)
2071 gap_end = info->high_limit;
2074 /* Compute highest gap address at the desired alignment */
2075 gap_end -= info->length;
2076 gap_end -= (gap_end - info->align_offset) & info->align_mask;
2078 VM_BUG_ON(gap_end < info->low_limit);
2079 VM_BUG_ON(gap_end < gap_start);
2084 #ifndef arch_get_mmap_end
2085 #define arch_get_mmap_end(addr) (TASK_SIZE)
2088 #ifndef arch_get_mmap_base
2089 #define arch_get_mmap_base(addr, base) (base)
2092 /* Get an address range which is currently unmapped.
2093 * For shmat() with addr=0.
2095 * Ugly calling convention alert:
2096 * Return value with the low bits set means error value,
2098 * if (ret & ~PAGE_MASK)
2101 * This function "knows" that -ENOMEM has the bits set.
2103 #ifndef HAVE_ARCH_UNMAPPED_AREA
2105 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2106 unsigned long len, unsigned long pgoff, unsigned long flags)
2108 struct mm_struct *mm = current->mm;
2109 struct vm_area_struct *vma, *prev;
2110 struct vm_unmapped_area_info info;
2111 const unsigned long mmap_end = arch_get_mmap_end(addr);
2113 if (len > mmap_end - mmap_min_addr)
2116 if (flags & MAP_FIXED)
2120 addr = PAGE_ALIGN(addr);
2121 vma = find_vma_prev(mm, addr, &prev);
2122 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2123 (!vma || addr + len <= vm_start_gap(vma)) &&
2124 (!prev || addr >= vm_end_gap(prev)))
2130 info.low_limit = mm->mmap_base;
2131 info.high_limit = mmap_end;
2132 info.align_mask = 0;
2133 return vm_unmapped_area(&info);
2138 * This mmap-allocator allocates new areas top-down from below the
2139 * stack's low limit (the base):
2141 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2143 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2144 unsigned long len, unsigned long pgoff,
2145 unsigned long flags)
2147 struct vm_area_struct *vma, *prev;
2148 struct mm_struct *mm = current->mm;
2149 struct vm_unmapped_area_info info;
2150 const unsigned long mmap_end = arch_get_mmap_end(addr);
2152 /* requested length too big for entire address space */
2153 if (len > mmap_end - mmap_min_addr)
2156 if (flags & MAP_FIXED)
2159 /* requesting a specific address */
2161 addr = PAGE_ALIGN(addr);
2162 vma = find_vma_prev(mm, addr, &prev);
2163 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2164 (!vma || addr + len <= vm_start_gap(vma)) &&
2165 (!prev || addr >= vm_end_gap(prev)))
2169 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2171 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2172 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2173 info.align_mask = 0;
2174 addr = vm_unmapped_area(&info);
2177 * A failed mmap() very likely causes application failure,
2178 * so fall back to the bottom-up function here. This scenario
2179 * can happen with large stack limits and large mmap()
2182 if (offset_in_page(addr)) {
2183 VM_BUG_ON(addr != -ENOMEM);
2185 info.low_limit = TASK_UNMAPPED_BASE;
2186 info.high_limit = mmap_end;
2187 addr = vm_unmapped_area(&info);
2195 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2196 unsigned long pgoff, unsigned long flags)
2198 unsigned long (*get_area)(struct file *, unsigned long,
2199 unsigned long, unsigned long, unsigned long);
2201 unsigned long error = arch_mmap_check(addr, len, flags);
2205 /* Careful about overflows.. */
2206 if (len > TASK_SIZE)
2209 get_area = current->mm->get_unmapped_area;
2211 if (file->f_op->get_unmapped_area)
2212 get_area = file->f_op->get_unmapped_area;
2213 } else if (flags & MAP_SHARED) {
2215 * mmap_region() will call shmem_zero_setup() to create a file,
2216 * so use shmem's get_unmapped_area in case it can be huge.
2217 * do_mmap_pgoff() will clear pgoff, so match alignment.
2220 get_area = shmem_get_unmapped_area;
2223 addr = get_area(file, addr, len, pgoff, flags);
2224 if (IS_ERR_VALUE(addr))
2227 if (addr > TASK_SIZE - len)
2229 if (offset_in_page(addr))
2232 error = security_mmap_addr(addr);
2233 return error ? error : addr;
2236 EXPORT_SYMBOL(get_unmapped_area);
2238 /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
2239 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2241 struct rb_node *rb_node;
2242 struct vm_area_struct *vma;
2244 /* Check the cache first. */
2245 vma = vmacache_find(mm, addr);
2249 rb_node = mm->mm_rb.rb_node;
2252 struct vm_area_struct *tmp;
2254 tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2256 if (tmp->vm_end > addr) {
2258 if (tmp->vm_start <= addr)
2260 rb_node = rb_node->rb_left;
2262 rb_node = rb_node->rb_right;
2266 vmacache_update(addr, vma);
2270 EXPORT_SYMBOL(find_vma);
2273 * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2275 struct vm_area_struct *
2276 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2277 struct vm_area_struct **pprev)
2279 struct vm_area_struct *vma;
2281 vma = find_vma(mm, addr);
2283 *pprev = vma->vm_prev;
2285 struct rb_node *rb_node = rb_last(&mm->mm_rb);
2287 *pprev = rb_node ? rb_entry(rb_node, struct vm_area_struct, vm_rb) : NULL;
2293 * Verify that the stack growth is acceptable and
2294 * update accounting. This is shared with both the
2295 * grow-up and grow-down cases.
2297 static int acct_stack_growth(struct vm_area_struct *vma,
2298 unsigned long size, unsigned long grow)
2300 struct mm_struct *mm = vma->vm_mm;
2301 unsigned long new_start;
2303 /* address space limit tests */
2304 if (!may_expand_vm(mm, vma->vm_flags, grow))
2307 /* Stack limit test */
2308 if (size > rlimit(RLIMIT_STACK))
2311 /* mlock limit tests */
2312 if (vma->vm_flags & VM_LOCKED) {
2313 unsigned long locked;
2314 unsigned long limit;
2315 locked = mm->locked_vm + grow;
2316 limit = rlimit(RLIMIT_MEMLOCK);
2317 limit >>= PAGE_SHIFT;
2318 if (locked > limit && !capable(CAP_IPC_LOCK))
2322 /* Check to ensure the stack will not grow into a hugetlb-only region */
2323 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2325 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2329 * Overcommit.. This must be the final test, as it will
2330 * update security statistics.
2332 if (security_vm_enough_memory_mm(mm, grow))
2338 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2340 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2341 * vma is the last one with address > vma->vm_end. Have to extend vma.
2343 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2345 struct mm_struct *mm = vma->vm_mm;
2346 struct vm_area_struct *next;
2347 unsigned long gap_addr;
2350 if (!(vma->vm_flags & VM_GROWSUP))
2353 /* Guard against exceeding limits of the address space. */
2354 address &= PAGE_MASK;
2355 if (address >= (TASK_SIZE & PAGE_MASK))
2357 address += PAGE_SIZE;
2359 /* Enforce stack_guard_gap */
2360 gap_addr = address + stack_guard_gap;
2362 /* Guard against overflow */
2363 if (gap_addr < address || gap_addr > TASK_SIZE)
2364 gap_addr = TASK_SIZE;
2366 next = vma->vm_next;
2367 if (next && next->vm_start < gap_addr &&
2368 (next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2369 if (!(next->vm_flags & VM_GROWSUP))
2371 /* Check that both stack segments have the same anon_vma? */
2374 /* We must make sure the anon_vma is allocated. */
2375 if (unlikely(anon_vma_prepare(vma)))
2379 * vma->vm_start/vm_end cannot change under us because the caller
2380 * is required to hold the mmap_sem in read mode. We need the
2381 * anon_vma lock to serialize against concurrent expand_stacks.
2383 anon_vma_lock_write(vma->anon_vma);
2385 /* Somebody else might have raced and expanded it already */
2386 if (address > vma->vm_end) {
2387 unsigned long size, grow;
2389 size = address - vma->vm_start;
2390 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2393 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2394 error = acct_stack_growth(vma, size, grow);
2397 * vma_gap_update() doesn't support concurrent
2398 * updates, but we only hold a shared mmap_sem
2399 * lock here, so we need to protect against
2400 * concurrent vma expansions.
2401 * anon_vma_lock_write() doesn't help here, as
2402 * we don't guarantee that all growable vmas
2403 * in a mm share the same root anon vma.
2404 * So, we reuse mm->page_table_lock to guard
2405 * against concurrent vma expansions.
2407 spin_lock(&mm->page_table_lock);
2408 if (vma->vm_flags & VM_LOCKED)
2409 mm->locked_vm += grow;
2410 vm_stat_account(mm, vma->vm_flags, grow);
2411 anon_vma_interval_tree_pre_update_vma(vma);
2412 vma->vm_end = address;
2413 anon_vma_interval_tree_post_update_vma(vma);
2415 vma_gap_update(vma->vm_next);
2417 mm->highest_vm_end = vm_end_gap(vma);
2418 spin_unlock(&mm->page_table_lock);
2420 perf_event_mmap(vma);
2424 anon_vma_unlock_write(vma->anon_vma);
2425 khugepaged_enter_vma_merge(vma, vma->vm_flags);
2429 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2432 * vma is the first one with address < vma->vm_start. Have to extend vma.
2434 int expand_downwards(struct vm_area_struct *vma,
2435 unsigned long address)
2437 struct mm_struct *mm = vma->vm_mm;
2438 struct vm_area_struct *prev;
2441 address &= PAGE_MASK;
2442 if (address < mmap_min_addr)
2445 /* Enforce stack_guard_gap */
2446 prev = vma->vm_prev;
2447 /* Check that both stack segments have the same anon_vma? */
2448 if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2449 (prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2450 if (address - prev->vm_end < stack_guard_gap)
2454 /* We must make sure the anon_vma is allocated. */
2455 if (unlikely(anon_vma_prepare(vma)))
2459 * vma->vm_start/vm_end cannot change under us because the caller
2460 * is required to hold the mmap_sem in read mode. We need the
2461 * anon_vma lock to serialize against concurrent expand_stacks.
2463 anon_vma_lock_write(vma->anon_vma);
2465 /* Somebody else might have raced and expanded it already */
2466 if (address < vma->vm_start) {
2467 unsigned long size, grow;
2469 size = vma->vm_end - address;
2470 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2473 if (grow <= vma->vm_pgoff) {
2474 error = acct_stack_growth(vma, size, grow);
2477 * vma_gap_update() doesn't support concurrent
2478 * updates, but we only hold a shared mmap_sem
2479 * lock here, so we need to protect against
2480 * concurrent vma expansions.
2481 * anon_vma_lock_write() doesn't help here, as
2482 * we don't guarantee that all growable vmas
2483 * in a mm share the same root anon vma.
2484 * So, we reuse mm->page_table_lock to guard
2485 * against concurrent vma expansions.
2487 spin_lock(&mm->page_table_lock);
2488 if (vma->vm_flags & VM_LOCKED)
2489 mm->locked_vm += grow;
2490 vm_stat_account(mm, vma->vm_flags, grow);
2491 anon_vma_interval_tree_pre_update_vma(vma);
2492 vma->vm_start = address;
2493 vma->vm_pgoff -= grow;
2494 anon_vma_interval_tree_post_update_vma(vma);
2495 vma_gap_update(vma);
2496 spin_unlock(&mm->page_table_lock);
2498 perf_event_mmap(vma);
2502 anon_vma_unlock_write(vma->anon_vma);
2503 khugepaged_enter_vma_merge(vma, vma->vm_flags);
2508 /* enforced gap between the expanding stack and other mappings. */
2509 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2511 static int __init cmdline_parse_stack_guard_gap(char *p)
2516 val = simple_strtoul(p, &endptr, 10);
2518 stack_guard_gap = val << PAGE_SHIFT;
2522 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2524 #ifdef CONFIG_STACK_GROWSUP
2525 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2527 return expand_upwards(vma, address);
2530 struct vm_area_struct *
2531 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2533 struct vm_area_struct *vma, *prev;
2536 vma = find_vma_prev(mm, addr, &prev);
2537 if (vma && (vma->vm_start <= addr))
2539 /* don't alter vm_end if the coredump is running */
2540 if (!prev || !mmget_still_valid(mm) || expand_stack(prev, addr))
2542 if (prev->vm_flags & VM_LOCKED)
2543 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2547 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2549 return expand_downwards(vma, address);
2552 struct vm_area_struct *
2553 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2555 struct vm_area_struct *vma;
2556 unsigned long start;
2559 vma = find_vma(mm, addr);
2562 if (vma->vm_start <= addr)
2564 if (!(vma->vm_flags & VM_GROWSDOWN))
2566 /* don't alter vm_start if the coredump is running */
2567 if (!mmget_still_valid(mm))
2569 start = vma->vm_start;
2570 if (expand_stack(vma, addr))
2572 if (vma->vm_flags & VM_LOCKED)
2573 populate_vma_page_range(vma, addr, start, NULL);
2578 EXPORT_SYMBOL_GPL(find_extend_vma);
2581 * Ok - we have the memory areas we should free on the vma list,
2582 * so release them, and do the vma updates.
2584 * Called with the mm semaphore held.
2586 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2588 unsigned long nr_accounted = 0;
2590 /* Update high watermark before we lower total_vm */
2591 update_hiwater_vm(mm);
2593 long nrpages = vma_pages(vma);
2595 if (vma->vm_flags & VM_ACCOUNT)
2596 nr_accounted += nrpages;
2597 vm_stat_account(mm, vma->vm_flags, -nrpages);
2598 vma = remove_vma(vma);
2600 vm_unacct_memory(nr_accounted);
2605 * Get rid of page table information in the indicated region.
2607 * Called with the mm semaphore held.
2609 static void unmap_region(struct mm_struct *mm,
2610 struct vm_area_struct *vma, struct vm_area_struct *prev,
2611 unsigned long start, unsigned long end)
2613 struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
2614 struct mmu_gather tlb;
2617 tlb_gather_mmu(&tlb, mm, start, end);
2618 update_hiwater_rss(mm);
2619 unmap_vmas(&tlb, vma, start, end);
2620 free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2621 next ? next->vm_start : USER_PGTABLES_CEILING);
2622 tlb_finish_mmu(&tlb, start, end);
2626 * Create a list of vma's touched by the unmap, removing them from the mm's
2627 * vma list as we go..
2630 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2631 struct vm_area_struct *prev, unsigned long end)
2633 struct vm_area_struct **insertion_point;
2634 struct vm_area_struct *tail_vma = NULL;
2636 insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2637 vma->vm_prev = NULL;
2639 vma_rb_erase(vma, &mm->mm_rb);
2643 } while (vma && vma->vm_start < end);
2644 *insertion_point = vma;
2646 vma->vm_prev = prev;
2647 vma_gap_update(vma);
2649 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2650 tail_vma->vm_next = NULL;
2652 /* Kill the cache */
2653 vmacache_invalidate(mm);
2657 * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
2658 * has already been checked or doesn't make sense to fail.
2660 int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2661 unsigned long addr, int new_below)
2663 struct vm_area_struct *new;
2666 if (vma->vm_ops && vma->vm_ops->split) {
2667 err = vma->vm_ops->split(vma, addr);
2672 new = vm_area_dup(vma);
2679 new->vm_start = addr;
2680 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2683 err = vma_dup_policy(vma, new);
2687 err = anon_vma_clone(new, vma);
2692 get_file(new->vm_file);
2694 if (new->vm_ops && new->vm_ops->open)
2695 new->vm_ops->open(new);
2698 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2699 ((addr - new->vm_start) >> PAGE_SHIFT), new);
2701 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2707 /* Clean everything up if vma_adjust failed. */
2708 if (new->vm_ops && new->vm_ops->close)
2709 new->vm_ops->close(new);
2712 unlink_anon_vmas(new);
2714 mpol_put(vma_policy(new));
2721 * Split a vma into two pieces at address 'addr', a new vma is allocated
2722 * either for the first part or the tail.
2724 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2725 unsigned long addr, int new_below)
2727 if (mm->map_count >= sysctl_max_map_count)
2730 return __split_vma(mm, vma, addr, new_below);
2733 /* Munmap is split into 2 main parts -- this part which finds
2734 * what needs doing, and the areas themselves, which do the
2735 * work. This now handles partial unmappings.
2736 * Jeremy Fitzhardinge <jeremy@goop.org>
2738 int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2739 struct list_head *uf, bool downgrade)
2742 struct vm_area_struct *vma, *prev, *last;
2744 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2747 len = PAGE_ALIGN(len);
2753 * arch_unmap() might do unmaps itself. It must be called
2754 * and finish any rbtree manipulation before this code
2755 * runs and also starts to manipulate the rbtree.
2757 arch_unmap(mm, start, end);
2759 /* Find the first overlapping VMA */
2760 vma = find_vma(mm, start);
2763 prev = vma->vm_prev;
2764 /* we have start < vma->vm_end */
2766 /* if it doesn't overlap, we have nothing.. */
2767 if (vma->vm_start >= end)
2771 * If we need to split any vma, do it now to save pain later.
2773 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2774 * unmapped vm_area_struct will remain in use: so lower split_vma
2775 * places tmp vma above, and higher split_vma places tmp vma below.
2777 if (start > vma->vm_start) {
2781 * Make sure that map_count on return from munmap() will
2782 * not exceed its limit; but let map_count go just above
2783 * its limit temporarily, to help free resources as expected.
2785 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2788 error = __split_vma(mm, vma, start, 0);
2794 /* Does it split the last one? */
2795 last = find_vma(mm, end);
2796 if (last && end > last->vm_start) {
2797 int error = __split_vma(mm, last, end, 1);
2801 vma = prev ? prev->vm_next : mm->mmap;
2805 * If userfaultfd_unmap_prep returns an error the vmas
2806 * will remain splitted, but userland will get a
2807 * highly unexpected error anyway. This is no
2808 * different than the case where the first of the two
2809 * __split_vma fails, but we don't undo the first
2810 * split, despite we could. This is unlikely enough
2811 * failure that it's not worth optimizing it for.
2813 int error = userfaultfd_unmap_prep(vma, start, end, uf);
2819 * unlock any mlock()ed ranges before detaching vmas
2821 if (mm->locked_vm) {
2822 struct vm_area_struct *tmp = vma;
2823 while (tmp && tmp->vm_start < end) {
2824 if (tmp->vm_flags & VM_LOCKED) {
2825 mm->locked_vm -= vma_pages(tmp);
2826 munlock_vma_pages_all(tmp);
2833 /* Detach vmas from rbtree */
2834 detach_vmas_to_be_unmapped(mm, vma, prev, end);
2837 downgrade_write(&mm->mmap_sem);
2839 unmap_region(mm, vma, prev, start, end);
2841 /* Fix up all other VM information */
2842 remove_vma_list(mm, vma);
2844 return downgrade ? 1 : 0;
2847 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2848 struct list_head *uf)
2850 return __do_munmap(mm, start, len, uf, false);
2853 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2856 struct mm_struct *mm = current->mm;
2859 if (down_write_killable(&mm->mmap_sem))
2862 ret = __do_munmap(mm, start, len, &uf, downgrade);
2864 * Returning 1 indicates mmap_sem is downgraded.
2865 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2866 * it to 0 before return.
2869 up_read(&mm->mmap_sem);
2872 up_write(&mm->mmap_sem);
2874 userfaultfd_unmap_complete(mm, &uf);
2878 int vm_munmap(unsigned long start, size_t len)
2880 return __vm_munmap(start, len, false);
2882 EXPORT_SYMBOL(vm_munmap);
2884 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2886 addr = untagged_addr(addr);
2887 profile_munmap(addr);
2888 return __vm_munmap(addr, len, true);
2893 * Emulation of deprecated remap_file_pages() syscall.
2895 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2896 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2899 struct mm_struct *mm = current->mm;
2900 struct vm_area_struct *vma;
2901 unsigned long populate = 0;
2902 unsigned long ret = -EINVAL;
2905 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.rst.\n",
2906 current->comm, current->pid);
2910 start = start & PAGE_MASK;
2911 size = size & PAGE_MASK;
2913 if (start + size <= start)
2916 /* Does pgoff wrap? */
2917 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2920 if (down_write_killable(&mm->mmap_sem))
2923 vma = find_vma(mm, start);
2925 if (!vma || !(vma->vm_flags & VM_SHARED))
2928 if (start < vma->vm_start)
2931 if (start + size > vma->vm_end) {
2932 struct vm_area_struct *next;
2934 for (next = vma->vm_next; next; next = next->vm_next) {
2935 /* hole between vmas ? */
2936 if (next->vm_start != next->vm_prev->vm_end)
2939 if (next->vm_file != vma->vm_file)
2942 if (next->vm_flags != vma->vm_flags)
2945 if (start + size <= next->vm_end)
2953 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2954 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2955 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2957 flags &= MAP_NONBLOCK;
2958 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2959 if (vma->vm_flags & VM_LOCKED) {
2960 struct vm_area_struct *tmp;
2961 flags |= MAP_LOCKED;
2963 /* drop PG_Mlocked flag for over-mapped range */
2964 for (tmp = vma; tmp->vm_start >= start + size;
2965 tmp = tmp->vm_next) {
2967 * Split pmd and munlock page on the border
2970 vma_adjust_trans_huge(tmp, start, start + size, 0);
2972 munlock_vma_pages_range(tmp,
2973 max(tmp->vm_start, start),
2974 min(tmp->vm_end, start + size));
2978 file = get_file(vma->vm_file);
2979 ret = do_mmap_pgoff(vma->vm_file, start, size,
2980 prot, flags, pgoff, &populate, NULL);
2983 up_write(&mm->mmap_sem);
2985 mm_populate(ret, populate);
2986 if (!IS_ERR_VALUE(ret))
2992 * this is really a simplified "do_mmap". it only handles
2993 * anonymous maps. eventually we may be able to do some
2994 * brk-specific accounting here.
2996 static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
2998 struct mm_struct *mm = current->mm;
2999 struct vm_area_struct *vma, *prev;
3000 struct rb_node **rb_link, *rb_parent;
3001 pgoff_t pgoff = addr >> PAGE_SHIFT;
3004 /* Until we need other flags, refuse anything except VM_EXEC. */
3005 if ((flags & (~VM_EXEC)) != 0)
3007 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3009 error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3010 if (offset_in_page(error))
3013 error = mlock_future_check(mm, mm->def_flags, len);
3018 * Clear old maps. this also does some error checking for us
3020 while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
3022 if (do_munmap(mm, addr, len, uf))
3026 /* Check against address space limits *after* clearing old maps... */
3027 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3030 if (mm->map_count > sysctl_max_map_count)
3033 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3036 /* Can we just expand an old private anonymous mapping? */
3037 vma = vma_merge(mm, prev, addr, addr + len, flags,
3038 NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);
3043 * create a vma struct for an anonymous mapping
3045 vma = vm_area_alloc(mm);
3047 vm_unacct_memory(len >> PAGE_SHIFT);
3051 vma_set_anonymous(vma);
3052 vma->vm_start = addr;
3053 vma->vm_end = addr + len;
3054 vma->vm_pgoff = pgoff;
3055 vma->vm_flags = flags;
3056 vma->vm_page_prot = vm_get_page_prot(flags);
3057 vma_link(mm, vma, prev, rb_link, rb_parent);
3059 perf_event_mmap(vma);
3060 mm->total_vm += len >> PAGE_SHIFT;
3061 mm->data_vm += len >> PAGE_SHIFT;
3062 if (flags & VM_LOCKED)
3063 mm->locked_vm += (len >> PAGE_SHIFT);
3064 vma->vm_flags |= VM_SOFTDIRTY;
3068 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3070 struct mm_struct *mm = current->mm;
3076 len = PAGE_ALIGN(request);
3082 if (down_write_killable(&mm->mmap_sem))
3085 ret = do_brk_flags(addr, len, flags, &uf);
3086 populate = ((mm->def_flags & VM_LOCKED) != 0);
3087 up_write(&mm->mmap_sem);
3088 userfaultfd_unmap_complete(mm, &uf);
3089 if (populate && !ret)
3090 mm_populate(addr, len);
3093 EXPORT_SYMBOL(vm_brk_flags);
3095 int vm_brk(unsigned long addr, unsigned long len)
3097 return vm_brk_flags(addr, len, 0);
3099 EXPORT_SYMBOL(vm_brk);
3101 /* Release all mmaps. */
3102 void exit_mmap(struct mm_struct *mm)
3104 struct mmu_gather tlb;
3105 struct vm_area_struct *vma;
3106 unsigned long nr_accounted = 0;
3108 /* mm's last user has gone, and its about to be pulled down */
3109 mmu_notifier_release(mm);
3111 if (unlikely(mm_is_oom_victim(mm))) {
3113 * Manually reap the mm to free as much memory as possible.
3114 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3115 * this mm from further consideration. Taking mm->mmap_sem for
3116 * write after setting MMF_OOM_SKIP will guarantee that the oom
3117 * reaper will not run on this mm again after mmap_sem is
3120 * Nothing can be holding mm->mmap_sem here and the above call
3121 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
3122 * __oom_reap_task_mm() will not block.
3124 * This needs to be done before calling munlock_vma_pages_all(),
3125 * which clears VM_LOCKED, otherwise the oom reaper cannot
3128 (void)__oom_reap_task_mm(mm);
3130 set_bit(MMF_OOM_SKIP, &mm->flags);
3131 down_write(&mm->mmap_sem);
3132 up_write(&mm->mmap_sem);
3135 if (mm->locked_vm) {
3138 if (vma->vm_flags & VM_LOCKED)
3139 munlock_vma_pages_all(vma);
3147 if (!vma) /* Can happen if dup_mmap() received an OOM */
3152 tlb_gather_mmu(&tlb, mm, 0, -1);
3153 /* update_hiwater_rss(mm) here? but nobody should be looking */
3154 /* Use -1 here to ensure all VMAs in the mm are unmapped */
3155 unmap_vmas(&tlb, vma, 0, -1);
3156 free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3157 tlb_finish_mmu(&tlb, 0, -1);
3160 * Walk the list again, actually closing and freeing it,
3161 * with preemption enabled, without holding any MM locks.
3164 if (vma->vm_flags & VM_ACCOUNT)
3165 nr_accounted += vma_pages(vma);
3166 vma = remove_vma(vma);
3168 vm_unacct_memory(nr_accounted);
3171 /* Insert vm structure into process list sorted by address
3172 * and into the inode's i_mmap tree. If vm_file is non-NULL
3173 * then i_mmap_rwsem is taken here.
3175 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3177 struct vm_area_struct *prev;
3178 struct rb_node **rb_link, *rb_parent;
3180 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3181 &prev, &rb_link, &rb_parent))
3183 if ((vma->vm_flags & VM_ACCOUNT) &&
3184 security_vm_enough_memory_mm(mm, vma_pages(vma)))
3188 * The vm_pgoff of a purely anonymous vma should be irrelevant
3189 * until its first write fault, when page's anon_vma and index
3190 * are set. But now set the vm_pgoff it will almost certainly
3191 * end up with (unless mremap moves it elsewhere before that
3192 * first wfault), so /proc/pid/maps tells a consistent story.
3194 * By setting it to reflect the virtual start address of the
3195 * vma, merges and splits can happen in a seamless way, just
3196 * using the existing file pgoff checks and manipulations.
3197 * Similarly in do_mmap_pgoff and in do_brk.
3199 if (vma_is_anonymous(vma)) {
3200 BUG_ON(vma->anon_vma);
3201 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3204 vma_link(mm, vma, prev, rb_link, rb_parent);
3209 * Copy the vma structure to a new location in the same mm,
3210 * prior to moving page table entries, to effect an mremap move.
3212 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3213 unsigned long addr, unsigned long len, pgoff_t pgoff,
3214 bool *need_rmap_locks)
3216 struct vm_area_struct *vma = *vmap;
3217 unsigned long vma_start = vma->vm_start;
3218 struct mm_struct *mm = vma->vm_mm;
3219 struct vm_area_struct *new_vma, *prev;
3220 struct rb_node **rb_link, *rb_parent;
3221 bool faulted_in_anon_vma = true;
3224 * If anonymous vma has not yet been faulted, update new pgoff
3225 * to match new location, to increase its chance of merging.
3227 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3228 pgoff = addr >> PAGE_SHIFT;
3229 faulted_in_anon_vma = false;
3232 if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3233 return NULL; /* should never get here */
3234 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3235 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3236 vma->vm_userfaultfd_ctx);
3239 * Source vma may have been merged into new_vma
3241 if (unlikely(vma_start >= new_vma->vm_start &&
3242 vma_start < new_vma->vm_end)) {
3244 * The only way we can get a vma_merge with
3245 * self during an mremap is if the vma hasn't
3246 * been faulted in yet and we were allowed to
3247 * reset the dst vma->vm_pgoff to the
3248 * destination address of the mremap to allow
3249 * the merge to happen. mremap must change the
3250 * vm_pgoff linearity between src and dst vmas
3251 * (in turn preventing a vma_merge) to be
3252 * safe. It is only safe to keep the vm_pgoff
3253 * linear if there are no pages mapped yet.
3255 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3256 *vmap = vma = new_vma;
3258 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3260 new_vma = vm_area_dup(vma);
3263 new_vma->vm_start = addr;
3264 new_vma->vm_end = addr + len;
3265 new_vma->vm_pgoff = pgoff;
3266 if (vma_dup_policy(vma, new_vma))
3268 if (anon_vma_clone(new_vma, vma))
3269 goto out_free_mempol;
3270 if (new_vma->vm_file)
3271 get_file(new_vma->vm_file);
3272 if (new_vma->vm_ops && new_vma->vm_ops->open)
3273 new_vma->vm_ops->open(new_vma);
3274 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3275 *need_rmap_locks = false;
3280 mpol_put(vma_policy(new_vma));
3282 vm_area_free(new_vma);
3288 * Return true if the calling process may expand its vm space by the passed
3291 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3293 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3296 if (is_data_mapping(flags) &&
3297 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3298 /* Workaround for Valgrind */
3299 if (rlimit(RLIMIT_DATA) == 0 &&
3300 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3303 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3304 current->comm, current->pid,
3305 (mm->data_vm + npages) << PAGE_SHIFT,
3306 rlimit(RLIMIT_DATA),
3307 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3309 if (!ignore_rlimit_data)
3316 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3318 mm->total_vm += npages;
3320 if (is_exec_mapping(flags))
3321 mm->exec_vm += npages;
3322 else if (is_stack_mapping(flags))
3323 mm->stack_vm += npages;
3324 else if (is_data_mapping(flags))
3325 mm->data_vm += npages;
3328 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3331 * Having a close hook prevents vma merging regardless of flags.
3333 static void special_mapping_close(struct vm_area_struct *vma)
3337 static const char *special_mapping_name(struct vm_area_struct *vma)
3339 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3342 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3344 struct vm_special_mapping *sm = new_vma->vm_private_data;
3346 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3350 return sm->mremap(sm, new_vma);
3355 static const struct vm_operations_struct special_mapping_vmops = {
3356 .close = special_mapping_close,
3357 .fault = special_mapping_fault,
3358 .mremap = special_mapping_mremap,
3359 .name = special_mapping_name,
3362 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3363 .close = special_mapping_close,
3364 .fault = special_mapping_fault,
3367 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3369 struct vm_area_struct *vma = vmf->vma;
3371 struct page **pages;
3373 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3374 pages = vma->vm_private_data;
3376 struct vm_special_mapping *sm = vma->vm_private_data;
3379 return sm->fault(sm, vmf->vma, vmf);
3384 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3388 struct page *page = *pages;
3394 return VM_FAULT_SIGBUS;
3397 static struct vm_area_struct *__install_special_mapping(
3398 struct mm_struct *mm,
3399 unsigned long addr, unsigned long len,
3400 unsigned long vm_flags, void *priv,
3401 const struct vm_operations_struct *ops)
3404 struct vm_area_struct *vma;
3406 vma = vm_area_alloc(mm);
3407 if (unlikely(vma == NULL))
3408 return ERR_PTR(-ENOMEM);
3410 vma->vm_start = addr;
3411 vma->vm_end = addr + len;
3413 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3414 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3417 vma->vm_private_data = priv;
3419 ret = insert_vm_struct(mm, vma);
3423 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3425 perf_event_mmap(vma);
3431 return ERR_PTR(ret);
3434 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3435 const struct vm_special_mapping *sm)
3437 return vma->vm_private_data == sm &&
3438 (vma->vm_ops == &special_mapping_vmops ||
3439 vma->vm_ops == &legacy_special_mapping_vmops);
3443 * Called with mm->mmap_sem held for writing.
3444 * Insert a new vma covering the given region, with the given flags.
3445 * Its pages are supplied by the given array of struct page *.
3446 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3447 * The region past the last page supplied will always produce SIGBUS.
3448 * The array pointer and the pages it points to are assumed to stay alive
3449 * for as long as this mapping might exist.
3451 struct vm_area_struct *_install_special_mapping(
3452 struct mm_struct *mm,
3453 unsigned long addr, unsigned long len,
3454 unsigned long vm_flags, const struct vm_special_mapping *spec)
3456 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3457 &special_mapping_vmops);
3460 int install_special_mapping(struct mm_struct *mm,
3461 unsigned long addr, unsigned long len,
3462 unsigned long vm_flags, struct page **pages)
3464 struct vm_area_struct *vma = __install_special_mapping(
3465 mm, addr, len, vm_flags, (void *)pages,
3466 &legacy_special_mapping_vmops);
3468 return PTR_ERR_OR_ZERO(vma);
3471 static DEFINE_MUTEX(mm_all_locks_mutex);
3473 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3475 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3477 * The LSB of head.next can't change from under us
3478 * because we hold the mm_all_locks_mutex.
3480 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
3482 * We can safely modify head.next after taking the
3483 * anon_vma->root->rwsem. If some other vma in this mm shares
3484 * the same anon_vma we won't take it again.
3486 * No need of atomic instructions here, head.next
3487 * can't change from under us thanks to the
3488 * anon_vma->root->rwsem.
3490 if (__test_and_set_bit(0, (unsigned long *)
3491 &anon_vma->root->rb_root.rb_root.rb_node))
3496 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3498 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3500 * AS_MM_ALL_LOCKS can't change from under us because
3501 * we hold the mm_all_locks_mutex.
3503 * Operations on ->flags have to be atomic because
3504 * even if AS_MM_ALL_LOCKS is stable thanks to the
3505 * mm_all_locks_mutex, there may be other cpus
3506 * changing other bitflags in parallel to us.
3508 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3510 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);
3515 * This operation locks against the VM for all pte/vma/mm related
3516 * operations that could ever happen on a certain mm. This includes
3517 * vmtruncate, try_to_unmap, and all page faults.
3519 * The caller must take the mmap_sem in write mode before calling
3520 * mm_take_all_locks(). The caller isn't allowed to release the
3521 * mmap_sem until mm_drop_all_locks() returns.
3523 * mmap_sem in write mode is required in order to block all operations
3524 * that could modify pagetables and free pages without need of
3525 * altering the vma layout. It's also needed in write mode to avoid new
3526 * anon_vmas to be associated with existing vmas.
3528 * A single task can't take more than one mm_take_all_locks() in a row
3529 * or it would deadlock.
3531 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3532 * mapping->flags avoid to take the same lock twice, if more than one
3533 * vma in this mm is backed by the same anon_vma or address_space.
3535 * We take locks in following order, accordingly to comment at beginning
3537 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3539 * - all i_mmap_rwsem locks;
3540 * - all anon_vma->rwseml
3542 * We can take all locks within these types randomly because the VM code
3543 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3544 * mm_all_locks_mutex.
3546 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3547 * that may have to take thousand of locks.
3549 * mm_take_all_locks() can fail if it's interrupted by signals.
3551 int mm_take_all_locks(struct mm_struct *mm)
3553 struct vm_area_struct *vma;
3554 struct anon_vma_chain *avc;
3556 BUG_ON(down_read_trylock(&mm->mmap_sem));
3558 mutex_lock(&mm_all_locks_mutex);
3560 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3561 if (signal_pending(current))
3563 if (vma->vm_file && vma->vm_file->f_mapping &&
3564 is_vm_hugetlb_page(vma))
3565 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3568 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3569 if (signal_pending(current))
3571 if (vma->vm_file && vma->vm_file->f_mapping &&
3572 !is_vm_hugetlb_page(vma))
3573 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3576 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3577 if (signal_pending(current))
3580 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3581 vm_lock_anon_vma(mm, avc->anon_vma);
3587 mm_drop_all_locks(mm);
3591 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3593 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3595 * The LSB of head.next can't change to 0 from under
3596 * us because we hold the mm_all_locks_mutex.
3598 * We must however clear the bitflag before unlocking
3599 * the vma so the users using the anon_vma->rb_root will
3600 * never see our bitflag.
3602 * No need of atomic instructions here, head.next
3603 * can't change from under us until we release the
3604 * anon_vma->root->rwsem.
3606 if (!__test_and_clear_bit(0, (unsigned long *)
3607 &anon_vma->root->rb_root.rb_root.rb_node))
3609 anon_vma_unlock_write(anon_vma);
3613 static void vm_unlock_mapping(struct address_space *mapping)
3615 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3617 * AS_MM_ALL_LOCKS can't change to 0 from under us
3618 * because we hold the mm_all_locks_mutex.
3620 i_mmap_unlock_write(mapping);
3621 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3628 * The mmap_sem cannot be released by the caller until
3629 * mm_drop_all_locks() returns.
3631 void mm_drop_all_locks(struct mm_struct *mm)
3633 struct vm_area_struct *vma;
3634 struct anon_vma_chain *avc;
3636 BUG_ON(down_read_trylock(&mm->mmap_sem));
3637 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3639 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3641 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3642 vm_unlock_anon_vma(avc->anon_vma);
3643 if (vma->vm_file && vma->vm_file->f_mapping)
3644 vm_unlock_mapping(vma->vm_file->f_mapping);
3647 mutex_unlock(&mm_all_locks_mutex);
3651 * initialise the percpu counter for VM
3653 void __init mmap_init(void)
3657 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3662 * Initialise sysctl_user_reserve_kbytes.
3664 * This is intended to prevent a user from starting a single memory hogging
3665 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3668 * The default value is min(3% of free memory, 128MB)
3669 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3671 static int init_user_reserve(void)
3673 unsigned long free_kbytes;
3675 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3677 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3680 subsys_initcall(init_user_reserve);
3683 * Initialise sysctl_admin_reserve_kbytes.
3685 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3686 * to log in and kill a memory hogging process.
3688 * Systems with more than 256MB will reserve 8MB, enough to recover
3689 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3690 * only reserve 3% of free pages by default.
3692 static int init_admin_reserve(void)
3694 unsigned long free_kbytes;
3696 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3698 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3701 subsys_initcall(init_admin_reserve);
3704 * Reinititalise user and admin reserves if memory is added or removed.
3706 * The default user reserve max is 128MB, and the default max for the
3707 * admin reserve is 8MB. These are usually, but not always, enough to
3708 * enable recovery from a memory hogging process using login/sshd, a shell,
3709 * and tools like top. It may make sense to increase or even disable the
3710 * reserve depending on the existence of swap or variations in the recovery
3711 * tools. So, the admin may have changed them.
3713 * If memory is added and the reserves have been eliminated or increased above
3714 * the default max, then we'll trust the admin.
3716 * If memory is removed and there isn't enough free memory, then we
3717 * need to reset the reserves.
3719 * Otherwise keep the reserve set by the admin.
3721 static int reserve_mem_notifier(struct notifier_block *nb,
3722 unsigned long action, void *data)
3724 unsigned long tmp, free_kbytes;
3728 /* Default max is 128MB. Leave alone if modified by operator. */
3729 tmp = sysctl_user_reserve_kbytes;
3730 if (0 < tmp && tmp < (1UL << 17))
3731 init_user_reserve();
3733 /* Default max is 8MB. Leave alone if modified by operator. */
3734 tmp = sysctl_admin_reserve_kbytes;
3735 if (0 < tmp && tmp < (1UL << 13))
3736 init_admin_reserve();
3740 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3742 if (sysctl_user_reserve_kbytes > free_kbytes) {
3743 init_user_reserve();
3744 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3745 sysctl_user_reserve_kbytes);
3748 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3749 init_admin_reserve();
3750 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3751 sysctl_admin_reserve_kbytes);
3760 static struct notifier_block reserve_mem_nb = {
3761 .notifier_call = reserve_mem_notifier,
3764 static int __meminit init_reserve_notifier(void)
3766 if (register_hotmemory_notifier(&reserve_mem_nb))
3767 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3771 subsys_initcall(init_reserve_notifier);