1 // SPDX-License-Identifier: GPL-2.0-only
7 * Address space accounting code <alan@lxorguk.ukuu.org.uk>
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 #include <linux/backing-dev.h>
16 #include <linux/mm_inline.h>
17 #include <linux/shm.h>
18 #include <linux/mman.h>
19 #include <linux/pagemap.h>
20 #include <linux/swap.h>
21 #include <linux/syscalls.h>
22 #include <linux/capability.h>
23 #include <linux/init.h>
24 #include <linux/file.h>
26 #include <linux/personality.h>
27 #include <linux/security.h>
28 #include <linux/hugetlb.h>
29 #include <linux/shmem_fs.h>
30 #include <linux/profile.h>
31 #include <linux/export.h>
32 #include <linux/mount.h>
33 #include <linux/mempolicy.h>
34 #include <linux/rmap.h>
35 #include <linux/mmu_notifier.h>
36 #include <linux/mmdebug.h>
37 #include <linux/perf_event.h>
38 #include <linux/audit.h>
39 #include <linux/khugepaged.h>
40 #include <linux/uprobes.h>
41 #include <linux/notifier.h>
42 #include <linux/memory.h>
43 #include <linux/printk.h>
44 #include <linux/userfaultfd_k.h>
45 #include <linux/moduleparam.h>
46 #include <linux/pkeys.h>
47 #include <linux/oom.h>
48 #include <linux/sched/mm.h>
50 #include <linux/uaccess.h>
51 #include <asm/cacheflush.h>
53 #include <asm/mmu_context.h>
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/mmap.h>
60 #ifndef arch_mmap_check
61 #define arch_mmap_check(addr, len, flags) (0)
64 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
65 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
66 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
67 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
69 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
70 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
71 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
72 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
75 static bool ignore_rlimit_data;
76 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
78 static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
79 struct vm_area_struct *vma, struct vm_area_struct *prev,
80 struct vm_area_struct *next, unsigned long start,
83 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
85 return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
88 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
89 void vma_set_page_prot(struct vm_area_struct *vma)
91 unsigned long vm_flags = vma->vm_flags;
92 pgprot_t vm_page_prot;
94 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
95 if (vma_wants_writenotify(vma, vm_page_prot)) {
96 vm_flags &= ~VM_SHARED;
97 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
99 /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
100 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
104 * Requires inode->i_mapping->i_mmap_rwsem
106 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
107 struct file *file, struct address_space *mapping)
109 if (vma->vm_flags & VM_SHARED)
110 mapping_unmap_writable(mapping);
112 flush_dcache_mmap_lock(mapping);
113 vma_interval_tree_remove(vma, &mapping->i_mmap);
114 flush_dcache_mmap_unlock(mapping);
118 * Unlink a file-based vm structure from its interval tree, to hide
119 * vma from rmap and vmtruncate before freeing its page tables.
121 void unlink_file_vma(struct vm_area_struct *vma)
123 struct file *file = vma->vm_file;
126 struct address_space *mapping = file->f_mapping;
127 i_mmap_lock_write(mapping);
128 __remove_shared_vm_struct(vma, file, mapping);
129 i_mmap_unlock_write(mapping);
134 * Close a vm structure and free it.
136 static void remove_vma(struct vm_area_struct *vma)
139 if (vma->vm_ops && vma->vm_ops->close)
140 vma->vm_ops->close(vma);
143 mpol_put(vma_policy(vma));
147 static inline struct vm_area_struct *vma_prev_limit(struct vma_iterator *vmi,
150 return mas_prev(&vmi->mas, min);
153 static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
154 unsigned long start, unsigned long end, gfp_t gfp)
156 vmi->mas.index = start;
157 vmi->mas.last = end - 1;
158 mas_store_gfp(&vmi->mas, NULL, gfp);
159 if (unlikely(mas_is_err(&vmi->mas)))
166 * check_brk_limits() - Use platform specific check of range & verify mlock
168 * @addr: The address to check
169 * @len: The size of increase.
171 * Return: 0 on success.
173 static int check_brk_limits(unsigned long addr, unsigned long len)
175 unsigned long mapped_addr;
177 mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
178 if (IS_ERR_VALUE(mapped_addr))
181 return mlock_future_check(current->mm, current->mm->def_flags, len);
183 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
184 unsigned long addr, unsigned long request, unsigned long flags);
185 SYSCALL_DEFINE1(brk, unsigned long, brk)
187 unsigned long newbrk, oldbrk, origbrk;
188 struct mm_struct *mm = current->mm;
189 struct vm_area_struct *brkvma, *next = NULL;
190 unsigned long min_brk;
192 bool downgraded = false;
194 struct vma_iterator vmi;
196 if (mmap_write_lock_killable(mm))
201 #ifdef CONFIG_COMPAT_BRK
203 * CONFIG_COMPAT_BRK can still be overridden by setting
204 * randomize_va_space to 2, which will still cause mm->start_brk
205 * to be arbitrarily shifted
207 if (current->brk_randomized)
208 min_brk = mm->start_brk;
210 min_brk = mm->end_data;
212 min_brk = mm->start_brk;
218 * Check against rlimit here. If this check is done later after the test
219 * of oldbrk with newbrk then it can escape the test and let the data
220 * segment grow beyond its set limit the in case where the limit is
221 * not page aligned -Ram Gupta
223 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
224 mm->end_data, mm->start_data))
227 newbrk = PAGE_ALIGN(brk);
228 oldbrk = PAGE_ALIGN(mm->brk);
229 if (oldbrk == newbrk) {
235 * Always allow shrinking brk.
236 * do_vma_munmap() may downgrade mmap_lock to read.
238 if (brk <= mm->brk) {
241 /* Search one past newbrk */
242 vma_iter_init(&vmi, mm, newbrk);
243 brkvma = vma_find(&vmi, oldbrk);
244 if (!brkvma || brkvma->vm_start >= oldbrk)
245 goto out; /* mapping intersects with an existing non-brk vma. */
247 * mm->brk must be protected by write mmap_lock.
248 * do_vma_munmap() may downgrade the lock, so update it
249 * before calling do_vma_munmap().
252 ret = do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true);
263 if (check_brk_limits(oldbrk, newbrk - oldbrk))
267 * Only check if the next VMA is within the stack_guard_gap of the
270 vma_iter_init(&vmi, mm, oldbrk);
271 next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
272 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
275 brkvma = vma_prev_limit(&vmi, mm->start_brk);
276 /* Ok, looks good - let it rip. */
277 if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
283 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
285 mmap_read_unlock(mm);
287 mmap_write_unlock(mm);
288 userfaultfd_unmap_complete(mm, &uf);
290 mm_populate(oldbrk, newbrk - oldbrk);
294 mmap_write_unlock(mm);
298 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
299 extern void mt_validate(struct maple_tree *mt);
300 extern void mt_dump(const struct maple_tree *mt);
302 /* Validate the maple tree */
303 static void validate_mm_mt(struct mm_struct *mm)
305 struct maple_tree *mt = &mm->mm_mt;
306 struct vm_area_struct *vma_mt;
308 MA_STATE(mas, mt, 0, 0);
310 mt_validate(&mm->mm_mt);
311 mas_for_each(&mas, vma_mt, ULONG_MAX) {
312 if ((vma_mt->vm_start != mas.index) ||
313 (vma_mt->vm_end - 1 != mas.last)) {
314 pr_emerg("issue in %s\n", current->comm);
317 pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
318 mas.index, mas.last);
319 pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
320 vma_mt->vm_start, vma_mt->vm_end);
323 if (vma_mt->vm_end != mas.last + 1) {
324 pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
325 mm, vma_mt->vm_start, vma_mt->vm_end,
326 mas.index, mas.last);
329 VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
330 if (vma_mt->vm_start != mas.index) {
331 pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
332 mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
335 VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
340 static void validate_mm(struct mm_struct *mm)
344 struct vm_area_struct *vma;
345 MA_STATE(mas, &mm->mm_mt, 0, 0);
349 mas_for_each(&mas, vma, ULONG_MAX) {
350 #ifdef CONFIG_DEBUG_VM_RB
351 struct anon_vma *anon_vma = vma->anon_vma;
352 struct anon_vma_chain *avc;
355 anon_vma_lock_read(anon_vma);
356 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
357 anon_vma_interval_tree_verify(avc);
358 anon_vma_unlock_read(anon_vma);
363 if (i != mm->map_count) {
364 pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
367 VM_BUG_ON_MM(bug, mm);
370 #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
371 #define validate_mm_mt(root) do { } while (0)
372 #define validate_mm(mm) do { } while (0)
373 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
376 * vma has some anon_vma assigned, and is already inserted on that
377 * anon_vma's interval trees.
379 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
380 * vma must be removed from the anon_vma's interval trees using
381 * anon_vma_interval_tree_pre_update_vma().
383 * After the update, the vma will be reinserted using
384 * anon_vma_interval_tree_post_update_vma().
386 * The entire update must be protected by exclusive mmap_lock and by
387 * the root anon_vma's mutex.
390 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
392 struct anon_vma_chain *avc;
394 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
395 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
399 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
401 struct anon_vma_chain *avc;
403 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
404 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
407 static unsigned long count_vma_pages_range(struct mm_struct *mm,
408 unsigned long addr, unsigned long end)
410 VMA_ITERATOR(vmi, mm, addr);
411 struct vm_area_struct *vma;
412 unsigned long nr_pages = 0;
414 for_each_vma_range(vmi, vma, end) {
415 unsigned long vm_start = max(addr, vma->vm_start);
416 unsigned long vm_end = min(end, vma->vm_end);
418 nr_pages += PHYS_PFN(vm_end - vm_start);
424 static void __vma_link_file(struct vm_area_struct *vma,
425 struct address_space *mapping)
427 if (vma->vm_flags & VM_SHARED)
428 mapping_allow_writable(mapping);
430 flush_dcache_mmap_lock(mapping);
431 vma_interval_tree_insert(vma, &mapping->i_mmap);
432 flush_dcache_mmap_unlock(mapping);
435 static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
437 VMA_ITERATOR(vmi, mm, 0);
438 struct address_space *mapping = NULL;
440 if (vma_iter_prealloc(&vmi))
444 mapping = vma->vm_file->f_mapping;
445 i_mmap_lock_write(mapping);
448 vma_iter_store(&vmi, vma);
451 __vma_link_file(vma, mapping);
452 i_mmap_unlock_write(mapping);
461 * vma_expand - Expand an existing VMA
463 * @mas: The maple state
464 * @vma: The vma to expand
465 * @start: The start of the vma
466 * @end: The exclusive end of the vma
467 * @pgoff: The page offset of vma
468 * @next: The current of next vma.
470 * Expand @vma to @start and @end. Can expand off the start and end. Will
471 * expand over @next if it's different from @vma and @end == @next->vm_end.
472 * Checking if the @vma can expand and merge with @next needs to be handled by
475 * Returns: 0 on success
477 inline int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
478 unsigned long start, unsigned long end, pgoff_t pgoff,
479 struct vm_area_struct *next)
481 struct mm_struct *mm = vma->vm_mm;
482 struct address_space *mapping = NULL;
483 struct rb_root_cached *root = NULL;
484 struct anon_vma *anon_vma = vma->anon_vma;
485 struct file *file = vma->vm_file;
486 bool remove_next = false;
488 if (next && (vma != next) && (end == next->vm_end)) {
490 if (next->anon_vma && !vma->anon_vma) {
493 anon_vma = next->anon_vma;
494 vma->anon_vma = anon_vma;
495 error = anon_vma_clone(vma, next);
501 /* Not merging but overwriting any part of next is not handled. */
502 VM_BUG_ON(next && !remove_next && next != vma && end > next->vm_start);
503 /* Only handles expanding */
504 VM_BUG_ON(vma->vm_start < start || vma->vm_end > end);
506 if (vma_iter_prealloc(vmi))
509 vma_adjust_trans_huge(vma, start, end, 0);
512 mapping = file->f_mapping;
513 root = &mapping->i_mmap;
514 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
515 i_mmap_lock_write(mapping);
519 anon_vma_lock_write(anon_vma);
520 anon_vma_interval_tree_pre_update_vma(vma);
524 flush_dcache_mmap_lock(mapping);
525 vma_interval_tree_remove(vma, root);
528 /* VMA iterator points to previous, so set to start if necessary */
529 if (vma_iter_addr(vmi) != start)
530 vma_iter_set(vmi, start);
532 vma->vm_start = start;
534 vma->vm_pgoff = pgoff;
535 vma_iter_store(vmi, vma);
538 vma_interval_tree_insert(vma, root);
539 flush_dcache_mmap_unlock(mapping);
542 /* Expanding over the next vma */
543 if (remove_next && file) {
544 __remove_shared_vm_struct(next, file, mapping);
548 anon_vma_interval_tree_post_update_vma(vma);
549 anon_vma_unlock_write(anon_vma);
553 i_mmap_unlock_write(mapping);
559 uprobe_munmap(next, next->vm_start, next->vm_end);
563 anon_vma_merge(vma, next);
565 mpol_put(vma_policy(next));
577 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
578 * is already present in an i_mmap tree without adjusting the tree.
579 * The following helper function should be used when such adjustments
580 * are necessary. The "insert" vma (if any) is to be inserted
581 * before we drop the necessary locks.
583 int __vma_adjust(struct vma_iterator *vmi, struct vm_area_struct *vma,
584 unsigned long start, unsigned long end, pgoff_t pgoff,
585 struct vm_area_struct *insert, struct vm_area_struct *expand)
587 struct mm_struct *mm = vma->vm_mm;
588 struct vm_area_struct *next_next = NULL; /* uninit var warning */
589 struct vm_area_struct *next = find_vma(mm, vma->vm_end);
590 struct vm_area_struct *orig_vma = vma;
591 struct address_space *mapping = NULL;
592 struct rb_root_cached *root = NULL;
593 struct anon_vma *anon_vma = NULL;
594 struct file *file = vma->vm_file;
595 bool vma_changed = false;
596 long adjust_next = 0;
598 struct vm_area_struct *exporter = NULL, *importer = NULL;
600 if (next && !insert) {
601 if (end >= next->vm_end) {
603 * vma expands, overlapping all the next, and
604 * perhaps the one after too (mprotect case 6).
605 * The only other cases that gets here are
606 * case 1, case 7 and case 8.
608 if (next == expand) {
610 * The only case where we don't expand "vma"
611 * and we expand "next" instead is case 8.
613 VM_WARN_ON(end != next->vm_end);
615 * remove_next == 3 means we're
616 * removing "vma" and that to do so we
617 * swapped "vma" and "next".
620 VM_WARN_ON(file != next->vm_file);
623 VM_WARN_ON(expand != vma);
625 * case 1, 6, 7, remove_next == 2 is case 6,
626 * remove_next == 1 is case 1 or 7.
628 remove_next = 1 + (end > next->vm_end);
629 if (remove_next == 2)
630 next_next = find_vma(mm, next->vm_end);
632 VM_WARN_ON(remove_next == 2 &&
633 end != next_next->vm_end);
640 * If next doesn't have anon_vma, import from vma after
641 * next, if the vma overlaps with it.
643 if (remove_next == 2 && !next->anon_vma)
644 exporter = next_next;
646 } else if (end > next->vm_start) {
648 * vma expands, overlapping part of the next:
649 * mprotect case 5 shifting the boundary up.
651 adjust_next = (end - next->vm_start);
654 VM_WARN_ON(expand != importer);
655 } else if (end < vma->vm_end) {
657 * vma shrinks, and !insert tells it's not
658 * split_vma inserting another: so it must be
659 * mprotect case 4 shifting the boundary down.
661 adjust_next = -(vma->vm_end - end);
664 VM_WARN_ON(expand != importer);
668 * Easily overlooked: when mprotect shifts the boundary,
669 * make sure the expanding vma has anon_vma set if the
670 * shrinking vma had, to cover any anon pages imported.
672 if (exporter && exporter->anon_vma && !importer->anon_vma) {
675 importer->anon_vma = exporter->anon_vma;
676 error = anon_vma_clone(importer, exporter);
682 if (vma_iter_prealloc(vmi))
685 anon_vma = vma->anon_vma;
686 if (!anon_vma && adjust_next)
687 anon_vma = next->anon_vma;
690 VM_WARN_ON(adjust_next && next->anon_vma &&
691 anon_vma != next->anon_vma);
693 vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
695 mapping = file->f_mapping;
696 root = &mapping->i_mmap;
697 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
700 uprobe_munmap(next, next->vm_start, next->vm_end);
702 i_mmap_lock_write(mapping);
703 if (insert && insert->vm_file) {
705 * Put into interval tree now, so instantiated pages
706 * are visible to arm/parisc __flush_dcache_page
707 * throughout; but we cannot insert into address
708 * space until vma start or end is updated.
710 __vma_link_file(insert, insert->vm_file->f_mapping);
715 anon_vma_lock_write(anon_vma);
716 anon_vma_interval_tree_pre_update_vma(vma);
718 anon_vma_interval_tree_pre_update_vma(next);
722 flush_dcache_mmap_lock(mapping);
723 vma_interval_tree_remove(vma, root);
725 vma_interval_tree_remove(next, root);
728 if (start != vma->vm_start) {
729 if (vma->vm_start < start) {
730 if (!insert || (insert->vm_end != start)) {
731 vma_iter_clear(vmi, vma->vm_start, start);
732 vma_iter_set(vmi, start);
733 VM_WARN_ON(insert && insert->vm_start > vma->vm_start);
738 vma->vm_start = start;
740 if (end != vma->vm_end) {
741 if (vma->vm_end > end) {
742 if (!insert || (insert->vm_start != end)) {
743 vma_iter_clear(vmi, end, vma->vm_end);
744 vma_iter_set(vmi, vma->vm_end);
746 insert->vm_end < vma->vm_end);
755 vma_iter_store(vmi, vma);
757 vma->vm_pgoff = pgoff;
759 next->vm_start += adjust_next;
760 next->vm_pgoff += adjust_next >> PAGE_SHIFT;
761 vma_iter_store(vmi, next);
766 vma_interval_tree_insert(next, root);
767 vma_interval_tree_insert(vma, root);
768 flush_dcache_mmap_unlock(mapping);
771 if (remove_next && file) {
772 __remove_shared_vm_struct(next, file, mapping);
773 if (remove_next == 2)
774 __remove_shared_vm_struct(next_next, file, mapping);
777 * split_vma has split insert from vma, and needs
778 * us to insert it before dropping the locks
779 * (it may either follow vma or precede it).
781 vma_iter_store(vmi, insert);
786 anon_vma_interval_tree_post_update_vma(vma);
788 anon_vma_interval_tree_post_update_vma(next);
789 anon_vma_unlock_write(anon_vma);
793 i_mmap_unlock_write(mapping);
803 uprobe_munmap(next, next->vm_start, next->vm_end);
807 anon_vma_merge(vma, next);
809 mpol_put(vma_policy(next));
810 if (remove_next != 2)
811 BUG_ON(vma->vm_end < next->vm_end);
815 * In mprotect's case 6 (see comments on vma_merge),
816 * we must remove next_next too.
818 if (remove_next == 2) {
834 * If the vma has a ->close operation then the driver probably needs to release
835 * per-vma resources, so we don't attempt to merge those.
837 static inline int is_mergeable_vma(struct vm_area_struct *vma,
838 struct file *file, unsigned long vm_flags,
839 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
840 struct anon_vma_name *anon_name)
843 * VM_SOFTDIRTY should not prevent from VMA merging, if we
844 * match the flags but dirty bit -- the caller should mark
845 * merged VMA as dirty. If dirty bit won't be excluded from
846 * comparison, we increase pressure on the memory system forcing
847 * the kernel to generate new VMAs when old one could be
850 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
852 if (vma->vm_file != file)
854 if (vma->vm_ops && vma->vm_ops->close)
856 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
858 if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
863 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
864 struct anon_vma *anon_vma2,
865 struct vm_area_struct *vma)
868 * The list_is_singular() test is to avoid merging VMA cloned from
869 * parents. This can improve scalability caused by anon_vma lock.
871 if ((!anon_vma1 || !anon_vma2) && (!vma ||
872 list_is_singular(&vma->anon_vma_chain)))
874 return anon_vma1 == anon_vma2;
878 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
879 * in front of (at a lower virtual address and file offset than) the vma.
881 * We cannot merge two vmas if they have differently assigned (non-NULL)
882 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
884 * We don't check here for the merged mmap wrapping around the end of pagecache
885 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
886 * wrap, nor mmaps which cover the final page at index -1UL.
889 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
890 struct anon_vma *anon_vma, struct file *file,
892 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
893 struct anon_vma_name *anon_name)
895 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
896 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
897 if (vma->vm_pgoff == vm_pgoff)
904 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
905 * beyond (at a higher virtual address and file offset than) the vma.
907 * We cannot merge two vmas if they have differently assigned (non-NULL)
908 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
911 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
912 struct anon_vma *anon_vma, struct file *file,
914 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
915 struct anon_vma_name *anon_name)
917 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
918 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
920 vm_pglen = vma_pages(vma);
921 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
928 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
929 * figure out whether that can be merged with its predecessor or its
930 * successor. Or both (it neatly fills a hole).
932 * In most cases - when called for mmap, brk or mremap - [addr,end) is
933 * certain not to be mapped by the time vma_merge is called; but when
934 * called for mprotect, it is certain to be already mapped (either at
935 * an offset within prev, or at the start of next), and the flags of
936 * this area are about to be changed to vm_flags - and the no-change
937 * case has already been eliminated.
939 * The following mprotect cases have to be considered, where AAAA is
940 * the area passed down from mprotect_fixup, never extending beyond one
941 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
944 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN
945 * cannot merge might become might become
946 * PPNNNNNNNNNN PPPPPPPPPPNN
947 * mmap, brk or case 4 below case 5 below
950 * PPPP NNNN PPPPNNNNXXXX
951 * might become might become
952 * PPPPPPPPPPPP 1 or PPPPPPPPPPPP 6 or
953 * PPPPPPPPNNNN 2 or PPPPPPPPXXXX 7 or
954 * PPPPNNNNNNNN 3 PPPPXXXXXXXX 8
956 * It is important for case 8 that the vma NNNN overlapping the
957 * region AAAA is never going to extended over XXXX. Instead XXXX must
958 * be extended in region AAAA and NNNN must be removed. This way in
959 * all cases where vma_merge succeeds, the moment vma_adjust drops the
960 * rmap_locks, the properties of the merged vma will be already
961 * correct for the whole merged range. Some of those properties like
962 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
963 * be correct for the whole merged range immediately after the
964 * rmap_locks are released. Otherwise if XXXX would be removed and
965 * NNNN would be extended over the XXXX range, remove_migration_ptes
966 * or other rmap walkers (if working on addresses beyond the "end"
967 * parameter) may establish ptes with the wrong permissions of NNNN
968 * instead of the right permissions of XXXX.
970 struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
971 struct vm_area_struct *prev, unsigned long addr,
972 unsigned long end, unsigned long vm_flags,
973 struct anon_vma *anon_vma, struct file *file,
974 pgoff_t pgoff, struct mempolicy *policy,
975 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
976 struct anon_vma_name *anon_name)
978 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
979 struct vm_area_struct *mid, *next, *res = NULL;
981 bool merge_prev = false;
982 bool merge_next = false;
985 * We later require that vma->vm_flags == vm_flags,
986 * so this tests vma->vm_flags & VM_SPECIAL, too.
988 if (vm_flags & VM_SPECIAL)
991 next = find_vma(mm, prev ? prev->vm_end : 0);
993 if (next && next->vm_end == end) /* cases 6, 7, 8 */
994 next = find_vma(mm, next->vm_end);
996 /* verify some invariant that must be enforced by the caller */
997 VM_WARN_ON(prev && addr <= prev->vm_start);
998 VM_WARN_ON(mid && end > mid->vm_end);
999 VM_WARN_ON(addr >= end);
1001 /* Can we merge the predecessor? */
1002 if (prev && prev->vm_end == addr &&
1003 mpol_equal(vma_policy(prev), policy) &&
1004 can_vma_merge_after(prev, vm_flags,
1005 anon_vma, file, pgoff,
1006 vm_userfaultfd_ctx, anon_name)) {
1009 /* Can we merge the successor? */
1010 if (next && end == next->vm_start &&
1011 mpol_equal(policy, vma_policy(next)) &&
1012 can_vma_merge_before(next, vm_flags,
1013 anon_vma, file, pgoff+pglen,
1014 vm_userfaultfd_ctx, anon_name)) {
1017 /* Can we merge both the predecessor and the successor? */
1018 if (merge_prev && merge_next &&
1019 is_mergeable_anon_vma(prev->anon_vma,
1020 next->anon_vma, NULL)) { /* cases 1, 6 */
1021 err = __vma_adjust(vmi, prev, prev->vm_start,
1022 next->vm_end, prev->vm_pgoff, NULL,
1025 } else if (merge_prev) { /* cases 2, 5, 7 */
1026 err = __vma_adjust(vmi, prev, prev->vm_start,
1027 end, prev->vm_pgoff, NULL, prev);
1029 } else if (merge_next) {
1030 if (prev && addr < prev->vm_end) /* case 4 */
1031 err = __vma_adjust(vmi, prev, prev->vm_start,
1032 addr, prev->vm_pgoff, NULL, next);
1033 else /* cases 3, 8 */
1034 err = __vma_adjust(vmi, mid, addr, next->vm_end,
1035 next->vm_pgoff - pglen, NULL, next);
1040 * Cannot merge with predecessor or successor or error in __vma_adjust?
1044 khugepaged_enter_vma(res, vm_flags);
1047 vma_iter_set(vmi, end);
1053 * Rough compatibility check to quickly see if it's even worth looking
1054 * at sharing an anon_vma.
1056 * They need to have the same vm_file, and the flags can only differ
1057 * in things that mprotect may change.
1059 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1060 * we can merge the two vma's. For example, we refuse to merge a vma if
1061 * there is a vm_ops->close() function, because that indicates that the
1062 * driver is doing some kind of reference counting. But that doesn't
1063 * really matter for the anon_vma sharing case.
1065 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1067 return a->vm_end == b->vm_start &&
1068 mpol_equal(vma_policy(a), vma_policy(b)) &&
1069 a->vm_file == b->vm_file &&
1070 !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1071 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1075 * Do some basic sanity checking to see if we can re-use the anon_vma
1076 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1077 * the same as 'old', the other will be the new one that is trying
1078 * to share the anon_vma.
1080 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1081 * the anon_vma of 'old' is concurrently in the process of being set up
1082 * by another page fault trying to merge _that_. But that's ok: if it
1083 * is being set up, that automatically means that it will be a singleton
1084 * acceptable for merging, so we can do all of this optimistically. But
1085 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1087 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1088 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1089 * is to return an anon_vma that is "complex" due to having gone through
1092 * We also make sure that the two vma's are compatible (adjacent,
1093 * and with the same memory policies). That's all stable, even with just
1094 * a read lock on the mmap_lock.
1096 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1098 if (anon_vma_compatible(a, b)) {
1099 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1101 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1108 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1109 * neighbouring vmas for a suitable anon_vma, before it goes off
1110 * to allocate a new anon_vma. It checks because a repetitive
1111 * sequence of mprotects and faults may otherwise lead to distinct
1112 * anon_vmas being allocated, preventing vma merge in subsequent
1115 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1117 MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1118 struct anon_vma *anon_vma = NULL;
1119 struct vm_area_struct *prev, *next;
1121 /* Try next first. */
1122 next = mas_walk(&mas);
1124 anon_vma = reusable_anon_vma(next, vma, next);
1129 prev = mas_prev(&mas, 0);
1130 VM_BUG_ON_VMA(prev != vma, vma);
1131 prev = mas_prev(&mas, 0);
1132 /* Try prev next. */
1134 anon_vma = reusable_anon_vma(prev, prev, vma);
1137 * We might reach here with anon_vma == NULL if we can't find
1138 * any reusable anon_vma.
1139 * There's no absolute need to look only at touching neighbours:
1140 * we could search further afield for "compatible" anon_vmas.
1141 * But it would probably just be a waste of time searching,
1142 * or lead to too many vmas hanging off the same anon_vma.
1143 * We're trying to allow mprotect remerging later on,
1144 * not trying to minimize memory used for anon_vmas.
1150 * If a hint addr is less than mmap_min_addr change hint to be as
1151 * low as possible but still greater than mmap_min_addr
1153 static inline unsigned long round_hint_to_min(unsigned long hint)
1156 if (((void *)hint != NULL) &&
1157 (hint < mmap_min_addr))
1158 return PAGE_ALIGN(mmap_min_addr);
1162 int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1165 unsigned long locked, lock_limit;
1167 /* mlock MCL_FUTURE? */
1168 if (flags & VM_LOCKED) {
1169 locked = len >> PAGE_SHIFT;
1170 locked += mm->locked_vm;
1171 lock_limit = rlimit(RLIMIT_MEMLOCK);
1172 lock_limit >>= PAGE_SHIFT;
1173 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1179 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1181 if (S_ISREG(inode->i_mode))
1182 return MAX_LFS_FILESIZE;
1184 if (S_ISBLK(inode->i_mode))
1185 return MAX_LFS_FILESIZE;
1187 if (S_ISSOCK(inode->i_mode))
1188 return MAX_LFS_FILESIZE;
1190 /* Special "we do even unsigned file positions" case */
1191 if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1194 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1198 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1199 unsigned long pgoff, unsigned long len)
1201 u64 maxsize = file_mmap_size_max(file, inode);
1203 if (maxsize && len > maxsize)
1206 if (pgoff > maxsize >> PAGE_SHIFT)
1212 * The caller must write-lock current->mm->mmap_lock.
1214 unsigned long do_mmap(struct file *file, unsigned long addr,
1215 unsigned long len, unsigned long prot,
1216 unsigned long flags, unsigned long pgoff,
1217 unsigned long *populate, struct list_head *uf)
1219 struct mm_struct *mm = current->mm;
1220 vm_flags_t vm_flags;
1230 * Does the application expect PROT_READ to imply PROT_EXEC?
1232 * (the exception is when the underlying filesystem is noexec
1233 * mounted, in which case we dont add PROT_EXEC.)
1235 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1236 if (!(file && path_noexec(&file->f_path)))
1239 /* force arch specific MAP_FIXED handling in get_unmapped_area */
1240 if (flags & MAP_FIXED_NOREPLACE)
1243 if (!(flags & MAP_FIXED))
1244 addr = round_hint_to_min(addr);
1246 /* Careful about overflows.. */
1247 len = PAGE_ALIGN(len);
1251 /* offset overflow? */
1252 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1255 /* Too many mappings? */
1256 if (mm->map_count > sysctl_max_map_count)
1259 /* Obtain the address to map to. we verify (or select) it and ensure
1260 * that it represents a valid section of the address space.
1262 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1263 if (IS_ERR_VALUE(addr))
1266 if (flags & MAP_FIXED_NOREPLACE) {
1267 if (find_vma_intersection(mm, addr, addr + len))
1271 if (prot == PROT_EXEC) {
1272 pkey = execute_only_pkey(mm);
1277 /* Do simple checking here so the lower-level routines won't have
1278 * to. we assume access permissions have been handled by the open
1279 * of the memory object, so we don't do any here.
1281 vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1282 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1284 if (flags & MAP_LOCKED)
1285 if (!can_do_mlock())
1288 if (mlock_future_check(mm, vm_flags, len))
1292 struct inode *inode = file_inode(file);
1293 unsigned long flags_mask;
1295 if (!file_mmap_ok(file, inode, pgoff, len))
1298 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1300 switch (flags & MAP_TYPE) {
1303 * Force use of MAP_SHARED_VALIDATE with non-legacy
1304 * flags. E.g. MAP_SYNC is dangerous to use with
1305 * MAP_SHARED as you don't know which consistency model
1306 * you will get. We silently ignore unsupported flags
1307 * with MAP_SHARED to preserve backward compatibility.
1309 flags &= LEGACY_MAP_MASK;
1311 case MAP_SHARED_VALIDATE:
1312 if (flags & ~flags_mask)
1314 if (prot & PROT_WRITE) {
1315 if (!(file->f_mode & FMODE_WRITE))
1317 if (IS_SWAPFILE(file->f_mapping->host))
1322 * Make sure we don't allow writing to an append-only
1325 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1328 vm_flags |= VM_SHARED | VM_MAYSHARE;
1329 if (!(file->f_mode & FMODE_WRITE))
1330 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1333 if (!(file->f_mode & FMODE_READ))
1335 if (path_noexec(&file->f_path)) {
1336 if (vm_flags & VM_EXEC)
1338 vm_flags &= ~VM_MAYEXEC;
1341 if (!file->f_op->mmap)
1343 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1351 switch (flags & MAP_TYPE) {
1353 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1359 vm_flags |= VM_SHARED | VM_MAYSHARE;
1363 * Set pgoff according to addr for anon_vma.
1365 pgoff = addr >> PAGE_SHIFT;
1373 * Set 'VM_NORESERVE' if we should not account for the
1374 * memory use of this mapping.
1376 if (flags & MAP_NORESERVE) {
1377 /* We honor MAP_NORESERVE if allowed to overcommit */
1378 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1379 vm_flags |= VM_NORESERVE;
1381 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1382 if (file && is_file_hugepages(file))
1383 vm_flags |= VM_NORESERVE;
1386 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1387 if (!IS_ERR_VALUE(addr) &&
1388 ((vm_flags & VM_LOCKED) ||
1389 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1394 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1395 unsigned long prot, unsigned long flags,
1396 unsigned long fd, unsigned long pgoff)
1398 struct file *file = NULL;
1399 unsigned long retval;
1401 if (!(flags & MAP_ANONYMOUS)) {
1402 audit_mmap_fd(fd, flags);
1406 if (is_file_hugepages(file)) {
1407 len = ALIGN(len, huge_page_size(hstate_file(file)));
1408 } else if (unlikely(flags & MAP_HUGETLB)) {
1412 } else if (flags & MAP_HUGETLB) {
1415 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1419 len = ALIGN(len, huge_page_size(hs));
1421 * VM_NORESERVE is used because the reservations will be
1422 * taken when vm_ops->mmap() is called
1424 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1426 HUGETLB_ANONHUGE_INODE,
1427 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1429 return PTR_ERR(file);
1432 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1439 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1440 unsigned long, prot, unsigned long, flags,
1441 unsigned long, fd, unsigned long, pgoff)
1443 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1446 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1447 struct mmap_arg_struct {
1451 unsigned long flags;
1453 unsigned long offset;
1456 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1458 struct mmap_arg_struct a;
1460 if (copy_from_user(&a, arg, sizeof(a)))
1462 if (offset_in_page(a.offset))
1465 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1466 a.offset >> PAGE_SHIFT);
1468 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1471 * Some shared mappings will want the pages marked read-only
1472 * to track write events. If so, we'll downgrade vm_page_prot
1473 * to the private version (using protection_map[] without the
1476 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1478 vm_flags_t vm_flags = vma->vm_flags;
1479 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1481 /* If it was private or non-writable, the write bit is already clear */
1482 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1485 /* The backer wishes to know when pages are first written to? */
1486 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1489 /* The open routine did something to the protections that pgprot_modify
1490 * won't preserve? */
1491 if (pgprot_val(vm_page_prot) !=
1492 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1496 * Do we need to track softdirty? hugetlb does not support softdirty
1499 if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1502 /* Do we need write faults for uffd-wp tracking? */
1503 if (userfaultfd_wp(vma))
1506 /* Specialty mapping? */
1507 if (vm_flags & VM_PFNMAP)
1510 /* Can the mapping track the dirty pages? */
1511 return vma->vm_file && vma->vm_file->f_mapping &&
1512 mapping_can_writeback(vma->vm_file->f_mapping);
1516 * We account for memory if it's a private writeable mapping,
1517 * not hugepages and VM_NORESERVE wasn't set.
1519 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1522 * hugetlb has its own accounting separate from the core VM
1523 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1525 if (file && is_file_hugepages(file))
1528 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1532 * unmapped_area() - Find an area between the low_limit and the high_limit with
1533 * the correct alignment and offset, all from @info. Note: current->mm is used
1536 * @info: The unmapped area information including the range [low_limit -
1537 * high_limit), the alignment offset and mask.
1539 * Return: A memory address or -ENOMEM.
1541 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1543 unsigned long length, gap;
1545 MA_STATE(mas, ¤t->mm->mm_mt, 0, 0);
1547 /* Adjust search length to account for worst case alignment overhead */
1548 length = info->length + info->align_mask;
1549 if (length < info->length)
1552 if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
1557 gap += (info->align_offset - gap) & info->align_mask;
1562 * unmapped_area_topdown() - Find an area between the low_limit and the
1563 * high_limit with the correct alignment and offset at the highest available
1564 * address, all from @info. Note: current->mm is used for the search.
1566 * @info: The unmapped area information including the range [low_limit -
1567 * high_limit), the alignment offset and mask.
1569 * Return: A memory address or -ENOMEM.
1571 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1573 unsigned long length, gap;
1575 MA_STATE(mas, ¤t->mm->mm_mt, 0, 0);
1576 /* Adjust search length to account for worst case alignment overhead */
1577 length = info->length + info->align_mask;
1578 if (length < info->length)
1581 if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
1585 gap = mas.last + 1 - info->length;
1586 gap -= (gap - info->align_offset) & info->align_mask;
1591 * Search for an unmapped address range.
1593 * We are looking for a range that:
1594 * - does not intersect with any VMA;
1595 * - is contained within the [low_limit, high_limit) interval;
1596 * - is at least the desired size.
1597 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1599 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1603 if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1604 addr = unmapped_area_topdown(info);
1606 addr = unmapped_area(info);
1608 trace_vm_unmapped_area(addr, info);
1612 /* Get an address range which is currently unmapped.
1613 * For shmat() with addr=0.
1615 * Ugly calling convention alert:
1616 * Return value with the low bits set means error value,
1618 * if (ret & ~PAGE_MASK)
1621 * This function "knows" that -ENOMEM has the bits set.
1624 generic_get_unmapped_area(struct file *filp, unsigned long addr,
1625 unsigned long len, unsigned long pgoff,
1626 unsigned long flags)
1628 struct mm_struct *mm = current->mm;
1629 struct vm_area_struct *vma, *prev;
1630 struct vm_unmapped_area_info info;
1631 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1633 if (len > mmap_end - mmap_min_addr)
1636 if (flags & MAP_FIXED)
1640 addr = PAGE_ALIGN(addr);
1641 vma = find_vma_prev(mm, addr, &prev);
1642 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1643 (!vma || addr + len <= vm_start_gap(vma)) &&
1644 (!prev || addr >= vm_end_gap(prev)))
1650 info.low_limit = mm->mmap_base;
1651 info.high_limit = mmap_end;
1652 info.align_mask = 0;
1653 info.align_offset = 0;
1654 return vm_unmapped_area(&info);
1657 #ifndef HAVE_ARCH_UNMAPPED_AREA
1659 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1660 unsigned long len, unsigned long pgoff,
1661 unsigned long flags)
1663 return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
1668 * This mmap-allocator allocates new areas top-down from below the
1669 * stack's low limit (the base):
1672 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
1673 unsigned long len, unsigned long pgoff,
1674 unsigned long flags)
1676 struct vm_area_struct *vma, *prev;
1677 struct mm_struct *mm = current->mm;
1678 struct vm_unmapped_area_info info;
1679 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1681 /* requested length too big for entire address space */
1682 if (len > mmap_end - mmap_min_addr)
1685 if (flags & MAP_FIXED)
1688 /* requesting a specific address */
1690 addr = PAGE_ALIGN(addr);
1691 vma = find_vma_prev(mm, addr, &prev);
1692 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1693 (!vma || addr + len <= vm_start_gap(vma)) &&
1694 (!prev || addr >= vm_end_gap(prev)))
1698 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1700 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1701 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1702 info.align_mask = 0;
1703 info.align_offset = 0;
1704 addr = vm_unmapped_area(&info);
1707 * A failed mmap() very likely causes application failure,
1708 * so fall back to the bottom-up function here. This scenario
1709 * can happen with large stack limits and large mmap()
1712 if (offset_in_page(addr)) {
1713 VM_BUG_ON(addr != -ENOMEM);
1715 info.low_limit = TASK_UNMAPPED_BASE;
1716 info.high_limit = mmap_end;
1717 addr = vm_unmapped_area(&info);
1723 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1725 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
1726 unsigned long len, unsigned long pgoff,
1727 unsigned long flags)
1729 return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
1734 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1735 unsigned long pgoff, unsigned long flags)
1737 unsigned long (*get_area)(struct file *, unsigned long,
1738 unsigned long, unsigned long, unsigned long);
1740 unsigned long error = arch_mmap_check(addr, len, flags);
1744 /* Careful about overflows.. */
1745 if (len > TASK_SIZE)
1748 get_area = current->mm->get_unmapped_area;
1750 if (file->f_op->get_unmapped_area)
1751 get_area = file->f_op->get_unmapped_area;
1752 } else if (flags & MAP_SHARED) {
1754 * mmap_region() will call shmem_zero_setup() to create a file,
1755 * so use shmem's get_unmapped_area in case it can be huge.
1756 * do_mmap() will clear pgoff, so match alignment.
1759 get_area = shmem_get_unmapped_area;
1762 addr = get_area(file, addr, len, pgoff, flags);
1763 if (IS_ERR_VALUE(addr))
1766 if (addr > TASK_SIZE - len)
1768 if (offset_in_page(addr))
1771 error = security_mmap_addr(addr);
1772 return error ? error : addr;
1775 EXPORT_SYMBOL(get_unmapped_area);
1778 * find_vma_intersection() - Look up the first VMA which intersects the interval
1779 * @mm: The process address space.
1780 * @start_addr: The inclusive start user address.
1781 * @end_addr: The exclusive end user address.
1783 * Returns: The first VMA within the provided range, %NULL otherwise. Assumes
1784 * start_addr < end_addr.
1786 struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1787 unsigned long start_addr,
1788 unsigned long end_addr)
1790 unsigned long index = start_addr;
1792 mmap_assert_locked(mm);
1793 return mt_find(&mm->mm_mt, &index, end_addr - 1);
1795 EXPORT_SYMBOL(find_vma_intersection);
1798 * find_vma() - Find the VMA for a given address, or the next VMA.
1799 * @mm: The mm_struct to check
1800 * @addr: The address
1802 * Returns: The VMA associated with addr, or the next VMA.
1803 * May return %NULL in the case of no VMA at addr or above.
1805 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1807 unsigned long index = addr;
1809 mmap_assert_locked(mm);
1810 return mt_find(&mm->mm_mt, &index, ULONG_MAX);
1812 EXPORT_SYMBOL(find_vma);
1815 * find_vma_prev() - Find the VMA for a given address, or the next vma and
1816 * set %pprev to the previous VMA, if any.
1817 * @mm: The mm_struct to check
1818 * @addr: The address
1819 * @pprev: The pointer to set to the previous VMA
1821 * Note that RCU lock is missing here since the external mmap_lock() is used
1824 * Returns: The VMA associated with @addr, or the next vma.
1825 * May return %NULL in the case of no vma at addr or above.
1827 struct vm_area_struct *
1828 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1829 struct vm_area_struct **pprev)
1831 struct vm_area_struct *vma;
1832 MA_STATE(mas, &mm->mm_mt, addr, addr);
1834 vma = mas_walk(&mas);
1835 *pprev = mas_prev(&mas, 0);
1837 vma = mas_next(&mas, ULONG_MAX);
1842 * Verify that the stack growth is acceptable and
1843 * update accounting. This is shared with both the
1844 * grow-up and grow-down cases.
1846 static int acct_stack_growth(struct vm_area_struct *vma,
1847 unsigned long size, unsigned long grow)
1849 struct mm_struct *mm = vma->vm_mm;
1850 unsigned long new_start;
1852 /* address space limit tests */
1853 if (!may_expand_vm(mm, vma->vm_flags, grow))
1856 /* Stack limit test */
1857 if (size > rlimit(RLIMIT_STACK))
1860 /* mlock limit tests */
1861 if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
1864 /* Check to ensure the stack will not grow into a hugetlb-only region */
1865 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
1867 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
1871 * Overcommit.. This must be the final test, as it will
1872 * update security statistics.
1874 if (security_vm_enough_memory_mm(mm, grow))
1880 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
1882 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
1883 * vma is the last one with address > vma->vm_end. Have to extend vma.
1885 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
1887 struct mm_struct *mm = vma->vm_mm;
1888 struct vm_area_struct *next;
1889 unsigned long gap_addr;
1891 MA_STATE(mas, &mm->mm_mt, 0, 0);
1893 if (!(vma->vm_flags & VM_GROWSUP))
1896 /* Guard against exceeding limits of the address space. */
1897 address &= PAGE_MASK;
1898 if (address >= (TASK_SIZE & PAGE_MASK))
1900 address += PAGE_SIZE;
1902 /* Enforce stack_guard_gap */
1903 gap_addr = address + stack_guard_gap;
1905 /* Guard against overflow */
1906 if (gap_addr < address || gap_addr > TASK_SIZE)
1907 gap_addr = TASK_SIZE;
1909 next = find_vma_intersection(mm, vma->vm_end, gap_addr);
1910 if (next && vma_is_accessible(next)) {
1911 if (!(next->vm_flags & VM_GROWSUP))
1913 /* Check that both stack segments have the same anon_vma? */
1916 if (mas_preallocate(&mas, GFP_KERNEL))
1919 /* We must make sure the anon_vma is allocated. */
1920 if (unlikely(anon_vma_prepare(vma))) {
1926 * vma->vm_start/vm_end cannot change under us because the caller
1927 * is required to hold the mmap_lock in read mode. We need the
1928 * anon_vma lock to serialize against concurrent expand_stacks.
1930 anon_vma_lock_write(vma->anon_vma);
1932 /* Somebody else might have raced and expanded it already */
1933 if (address > vma->vm_end) {
1934 unsigned long size, grow;
1936 size = address - vma->vm_start;
1937 grow = (address - vma->vm_end) >> PAGE_SHIFT;
1940 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
1941 error = acct_stack_growth(vma, size, grow);
1944 * We only hold a shared mmap_lock lock here, so
1945 * we need to protect against concurrent vma
1946 * expansions. anon_vma_lock_write() doesn't
1947 * help here, as we don't guarantee that all
1948 * growable vmas in a mm share the same root
1949 * anon vma. So, we reuse mm->page_table_lock
1950 * to guard against concurrent vma expansions.
1952 spin_lock(&mm->page_table_lock);
1953 if (vma->vm_flags & VM_LOCKED)
1954 mm->locked_vm += grow;
1955 vm_stat_account(mm, vma->vm_flags, grow);
1956 anon_vma_interval_tree_pre_update_vma(vma);
1957 vma->vm_end = address;
1958 /* Overwrite old entry in mtree. */
1959 mas_set_range(&mas, vma->vm_start, address - 1);
1960 mas_store_prealloc(&mas, vma);
1961 anon_vma_interval_tree_post_update_vma(vma);
1962 spin_unlock(&mm->page_table_lock);
1964 perf_event_mmap(vma);
1968 anon_vma_unlock_write(vma->anon_vma);
1969 khugepaged_enter_vma(vma, vma->vm_flags);
1973 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
1976 * vma is the first one with address < vma->vm_start. Have to extend vma.
1978 int expand_downwards(struct vm_area_struct *vma, unsigned long address)
1980 struct mm_struct *mm = vma->vm_mm;
1981 MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
1982 struct vm_area_struct *prev;
1985 address &= PAGE_MASK;
1986 if (address < mmap_min_addr)
1989 /* Enforce stack_guard_gap */
1990 prev = mas_prev(&mas, 0);
1991 /* Check that both stack segments have the same anon_vma? */
1992 if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
1993 vma_is_accessible(prev)) {
1994 if (address - prev->vm_end < stack_guard_gap)
1998 if (mas_preallocate(&mas, GFP_KERNEL))
2001 /* We must make sure the anon_vma is allocated. */
2002 if (unlikely(anon_vma_prepare(vma))) {
2008 * vma->vm_start/vm_end cannot change under us because the caller
2009 * is required to hold the mmap_lock in read mode. We need the
2010 * anon_vma lock to serialize against concurrent expand_stacks.
2012 anon_vma_lock_write(vma->anon_vma);
2014 /* Somebody else might have raced and expanded it already */
2015 if (address < vma->vm_start) {
2016 unsigned long size, grow;
2018 size = vma->vm_end - address;
2019 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2022 if (grow <= vma->vm_pgoff) {
2023 error = acct_stack_growth(vma, size, grow);
2026 * We only hold a shared mmap_lock lock here, so
2027 * we need to protect against concurrent vma
2028 * expansions. anon_vma_lock_write() doesn't
2029 * help here, as we don't guarantee that all
2030 * growable vmas in a mm share the same root
2031 * anon vma. So, we reuse mm->page_table_lock
2032 * to guard against concurrent vma expansions.
2034 spin_lock(&mm->page_table_lock);
2035 if (vma->vm_flags & VM_LOCKED)
2036 mm->locked_vm += grow;
2037 vm_stat_account(mm, vma->vm_flags, grow);
2038 anon_vma_interval_tree_pre_update_vma(vma);
2039 vma->vm_start = address;
2040 vma->vm_pgoff -= grow;
2041 /* Overwrite old entry in mtree. */
2042 mas_set_range(&mas, address, vma->vm_end - 1);
2043 mas_store_prealloc(&mas, vma);
2044 anon_vma_interval_tree_post_update_vma(vma);
2045 spin_unlock(&mm->page_table_lock);
2047 perf_event_mmap(vma);
2051 anon_vma_unlock_write(vma->anon_vma);
2052 khugepaged_enter_vma(vma, vma->vm_flags);
2057 /* enforced gap between the expanding stack and other mappings. */
2058 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2060 static int __init cmdline_parse_stack_guard_gap(char *p)
2065 val = simple_strtoul(p, &endptr, 10);
2067 stack_guard_gap = val << PAGE_SHIFT;
2071 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2073 #ifdef CONFIG_STACK_GROWSUP
2074 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2076 return expand_upwards(vma, address);
2079 struct vm_area_struct *
2080 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2082 struct vm_area_struct *vma, *prev;
2085 vma = find_vma_prev(mm, addr, &prev);
2086 if (vma && (vma->vm_start <= addr))
2088 if (!prev || expand_stack(prev, addr))
2090 if (prev->vm_flags & VM_LOCKED)
2091 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2095 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2097 return expand_downwards(vma, address);
2100 struct vm_area_struct *
2101 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2103 struct vm_area_struct *vma;
2104 unsigned long start;
2107 vma = find_vma(mm, addr);
2110 if (vma->vm_start <= addr)
2112 if (!(vma->vm_flags & VM_GROWSDOWN))
2114 start = vma->vm_start;
2115 if (expand_stack(vma, addr))
2117 if (vma->vm_flags & VM_LOCKED)
2118 populate_vma_page_range(vma, addr, start, NULL);
2123 EXPORT_SYMBOL_GPL(find_extend_vma);
2126 * Ok - we have the memory areas we should free on a maple tree so release them,
2127 * and do the vma updates.
2129 * Called with the mm semaphore held.
2131 static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
2133 unsigned long nr_accounted = 0;
2134 struct vm_area_struct *vma;
2136 /* Update high watermark before we lower total_vm */
2137 update_hiwater_vm(mm);
2138 mas_for_each(mas, vma, ULONG_MAX) {
2139 long nrpages = vma_pages(vma);
2141 if (vma->vm_flags & VM_ACCOUNT)
2142 nr_accounted += nrpages;
2143 vm_stat_account(mm, vma->vm_flags, -nrpages);
2146 vm_unacct_memory(nr_accounted);
2151 * Get rid of page table information in the indicated region.
2153 * Called with the mm semaphore held.
2155 static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
2156 struct vm_area_struct *vma, struct vm_area_struct *prev,
2157 struct vm_area_struct *next,
2158 unsigned long start, unsigned long end)
2160 struct mmu_gather tlb;
2163 tlb_gather_mmu(&tlb, mm);
2164 update_hiwater_rss(mm);
2165 unmap_vmas(&tlb, mt, vma, start, end);
2166 free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2167 next ? next->vm_start : USER_PGTABLES_CEILING);
2168 tlb_finish_mmu(&tlb);
2172 * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
2173 * has already been checked or doesn't make sense to fail.
2174 * VMA Iterator will point to the end VMA.
2176 int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2177 unsigned long addr, int new_below)
2179 struct vm_area_struct *new;
2182 validate_mm_mt(vma->vm_mm);
2184 if (vma->vm_ops && vma->vm_ops->may_split) {
2185 err = vma->vm_ops->may_split(vma, addr);
2190 new = vm_area_dup(vma);
2197 new->vm_start = addr;
2198 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2201 err = vma_dup_policy(vma, new);
2205 err = anon_vma_clone(new, vma);
2210 get_file(new->vm_file);
2212 if (new->vm_ops && new->vm_ops->open)
2213 new->vm_ops->open(new);
2216 err = vma_adjust(vmi, vma, addr, vma->vm_end,
2217 vma->vm_pgoff + ((addr - new->vm_start) >> PAGE_SHIFT),
2220 err = vma_adjust(vmi, vma, vma->vm_start, addr, vma->vm_pgoff,
2230 /* Avoid vm accounting in close() operation */
2231 new->vm_start = new->vm_end;
2233 /* Clean everything up if vma_adjust failed. */
2234 if (new->vm_ops && new->vm_ops->close)
2235 new->vm_ops->close(new);
2238 unlink_anon_vmas(new);
2240 mpol_put(vma_policy(new));
2243 validate_mm_mt(vma->vm_mm);
2248 * Split a vma into two pieces at address 'addr', a new vma is allocated
2249 * either for the first part or the tail.
2251 int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2252 unsigned long addr, int new_below)
2254 if (vma->vm_mm->map_count >= sysctl_max_map_count)
2257 return __split_vma(vmi, vma, addr, new_below);
2260 static inline int munmap_sidetree(struct vm_area_struct *vma,
2261 struct ma_state *mas_detach)
2263 mas_set_range(mas_detach, vma->vm_start, vma->vm_end - 1);
2264 if (mas_store_gfp(mas_detach, vma, GFP_KERNEL))
2267 if (vma->vm_flags & VM_LOCKED)
2268 vma->vm_mm->locked_vm -= vma_pages(vma);
2274 * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2275 * @vmi: The vma iterator
2276 * @vma: The starting vm_area_struct
2277 * @mm: The mm_struct
2278 * @start: The aligned start address to munmap.
2279 * @end: The aligned end address to munmap.
2280 * @uf: The userfaultfd list_head
2281 * @downgrade: Set to true to attempt a write downgrade of the mmap_lock
2283 * If @downgrade is true, check return code for potential release of the lock.
2286 do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2287 struct mm_struct *mm, unsigned long start,
2288 unsigned long end, struct list_head *uf, bool downgrade)
2290 struct vm_area_struct *prev, *next = NULL;
2291 struct maple_tree mt_detach;
2293 int error = -ENOMEM;
2294 MA_STATE(mas_detach, &mt_detach, 0, 0);
2295 mt_init_flags(&mt_detach, MT_FLAGS_LOCK_EXTERN);
2296 mt_set_external_lock(&mt_detach, &mm->mmap_lock);
2299 * If we need to split any vma, do it now to save pain later.
2301 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2302 * unmapped vm_area_struct will remain in use: so lower split_vma
2303 * places tmp vma above, and higher split_vma places tmp vma below.
2306 /* Does it split the first one? */
2307 if (start > vma->vm_start) {
2310 * Make sure that map_count on return from munmap() will
2311 * not exceed its limit; but let map_count go just above
2312 * its limit temporarily, to help free resources as expected.
2314 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2315 goto map_count_exceeded;
2317 error = __split_vma(vmi, vma, start, 0);
2319 goto start_split_failed;
2321 vma = vma_iter_load(vmi);
2324 prev = vma_prev(vmi);
2325 if (unlikely((!prev)))
2326 vma_iter_set(vmi, start);
2329 * Detach a range of VMAs from the mm. Using next as a temp variable as
2330 * it is always overwritten.
2332 for_each_vma_range(*vmi, next, end) {
2333 /* Does it split the end? */
2334 if (next->vm_end > end) {
2335 error = __split_vma(vmi, next, end, 0);
2337 goto end_split_failed;
2339 error = munmap_sidetree(next, &mas_detach);
2341 goto munmap_sidetree_failed;
2344 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2345 BUG_ON(next->vm_start < start);
2346 BUG_ON(next->vm_start > end);
2350 next = vma_next(vmi);
2353 * If userfaultfd_unmap_prep returns an error the vmas
2354 * will remain split, but userland will get a
2355 * highly unexpected error anyway. This is no
2356 * different than the case where the first of the two
2357 * __split_vma fails, but we don't undo the first
2358 * split, despite we could. This is unlikely enough
2359 * failure that it's not worth optimizing it for.
2361 error = userfaultfd_unmap_prep(mm, start, end, uf);
2364 goto userfaultfd_error;
2367 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2368 /* Make sure no VMAs are about to be lost. */
2370 MA_STATE(test, &mt_detach, start, end - 1);
2371 struct vm_area_struct *vma_mas, *vma_test;
2374 vma_iter_set(vmi, start);
2376 vma_test = mas_find(&test, end - 1);
2377 for_each_vma_range(*vmi, vma_mas, end) {
2378 BUG_ON(vma_mas != vma_test);
2380 vma_test = mas_next(&test, end - 1);
2383 BUG_ON(count != test_count);
2386 /* Point of no return */
2387 vma_iter_set(vmi, start);
2388 if (vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL))
2391 mm->map_count -= count;
2393 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2394 * VM_GROWSUP VMA. Such VMAs can change their size under
2395 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2398 if (next && (next->vm_flags & VM_GROWSDOWN))
2400 else if (prev && (prev->vm_flags & VM_GROWSUP))
2403 mmap_write_downgrade(mm);
2406 unmap_region(mm, &mt_detach, vma, prev, next, start, end);
2407 /* Statistics and freeing VMAs */
2408 mas_set(&mas_detach, start);
2409 remove_mt(mm, &mas_detach);
2410 __mt_destroy(&mt_detach);
2414 return downgrade ? 1 : 0;
2417 munmap_sidetree_failed:
2419 __mt_destroy(&mt_detach);
2426 * do_vmi_munmap() - munmap a given range.
2427 * @vmi: The vma iterator
2428 * @mm: The mm_struct
2429 * @start: The start address to munmap
2430 * @len: The length of the range to munmap
2431 * @uf: The userfaultfd list_head
2432 * @downgrade: set to true if the user wants to attempt to write_downgrade the
2435 * This function takes a @mas that is either pointing to the previous VMA or set
2436 * to MA_START and sets it up to remove the mapping(s). The @len will be
2437 * aligned and any arch_unmap work will be preformed.
2439 * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
2441 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
2442 unsigned long start, size_t len, struct list_head *uf,
2446 struct vm_area_struct *vma;
2448 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2451 end = start + PAGE_ALIGN(len);
2455 /* arch_unmap() might do unmaps itself. */
2456 arch_unmap(mm, start, end);
2458 /* Find the first overlapping VMA */
2459 vma = vma_find(vmi, end);
2463 return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2466 /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
2467 * @mm: The mm_struct
2468 * @start: The start address to munmap
2469 * @len: The length to be munmapped.
2470 * @uf: The userfaultfd list_head
2472 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2473 struct list_head *uf)
2475 VMA_ITERATOR(vmi, mm, start);
2477 return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2480 unsigned long mmap_region(struct file *file, unsigned long addr,
2481 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2482 struct list_head *uf)
2484 struct mm_struct *mm = current->mm;
2485 struct vm_area_struct *vma = NULL;
2486 struct vm_area_struct *next, *prev, *merge;
2487 pgoff_t pglen = len >> PAGE_SHIFT;
2488 unsigned long charged = 0;
2489 unsigned long end = addr + len;
2490 unsigned long merge_start = addr, merge_end = end;
2493 VMA_ITERATOR(vmi, mm, addr);
2495 /* Check against address space limit. */
2496 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2497 unsigned long nr_pages;
2500 * MAP_FIXED may remove pages of mappings that intersects with
2501 * requested mapping. Account for the pages it would unmap.
2503 nr_pages = count_vma_pages_range(mm, addr, end);
2505 if (!may_expand_vm(mm, vm_flags,
2506 (len >> PAGE_SHIFT) - nr_pages))
2510 /* Unmap any existing mapping in the area */
2511 if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2515 * Private writable mapping: check memory availability
2517 if (accountable_mapping(file, vm_flags)) {
2518 charged = len >> PAGE_SHIFT;
2519 if (security_vm_enough_memory_mm(mm, charged))
2521 vm_flags |= VM_ACCOUNT;
2524 next = vma_next(&vmi);
2525 prev = vma_prev(&vmi);
2526 if (vm_flags & VM_SPECIAL)
2529 /* Attempt to expand an old mapping */
2531 if (next && next->vm_start == end && !vma_policy(next) &&
2532 can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2533 NULL_VM_UFFD_CTX, NULL)) {
2534 merge_end = next->vm_end;
2536 vm_pgoff = next->vm_pgoff - pglen;
2540 if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2541 (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2542 pgoff, vma->vm_userfaultfd_ctx, NULL) :
2543 can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2544 NULL_VM_UFFD_CTX, NULL))) {
2545 merge_start = prev->vm_start;
2547 vm_pgoff = prev->vm_pgoff;
2551 /* Actually expand, if possible */
2553 !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2554 khugepaged_enter_vma(vma, vm_flags);
2560 * Determine the object being mapped and call the appropriate
2561 * specific mapper. the address has already been validated, but
2562 * not unmapped, but the maps are removed from the list.
2564 vma = vm_area_alloc(mm);
2570 vma_iter_set(&vmi, addr);
2571 vma->vm_start = addr;
2573 vma->vm_flags = vm_flags;
2574 vma->vm_page_prot = vm_get_page_prot(vm_flags);
2575 vma->vm_pgoff = pgoff;
2578 if (vm_flags & VM_SHARED) {
2579 error = mapping_map_writable(file->f_mapping);
2584 vma->vm_file = get_file(file);
2585 error = call_mmap(file, vma);
2587 goto unmap_and_free_vma;
2590 * Expansion is handled above, merging is handled below.
2591 * Drivers should not alter the address of the VMA.
2594 if (WARN_ON((addr != vma->vm_start)))
2595 goto close_and_free_vma;
2597 vma_iter_set(&vmi, addr);
2599 * If vm_flags changed after call_mmap(), we should try merge
2600 * vma again as we may succeed this time.
2602 if (unlikely(vm_flags != vma->vm_flags && prev)) {
2603 merge = vma_merge(&vmi, mm, prev, vma->vm_start,
2604 vma->vm_end, vma->vm_flags, NULL,
2605 vma->vm_file, vma->vm_pgoff, NULL,
2606 NULL_VM_UFFD_CTX, NULL);
2609 * ->mmap() can change vma->vm_file and fput
2610 * the original file. So fput the vma->vm_file
2611 * here or we would add an extra fput for file
2612 * and cause general protection fault
2618 /* Update vm_flags to pick up the change. */
2619 vm_flags = vma->vm_flags;
2620 goto unmap_writable;
2624 vm_flags = vma->vm_flags;
2625 } else if (vm_flags & VM_SHARED) {
2626 error = shmem_zero_setup(vma);
2630 vma_set_anonymous(vma);
2633 if (map_deny_write_exec(vma, vma->vm_flags)) {
2636 goto close_and_free_vma;
2637 else if (vma->vm_file)
2638 goto unmap_and_free_vma;
2643 /* Allow architectures to sanity-check the vm_flags */
2645 if (!arch_validate_flags(vma->vm_flags))
2646 goto close_and_free_vma;
2649 if (vma_iter_prealloc(&vmi))
2650 goto close_and_free_vma;
2653 i_mmap_lock_write(vma->vm_file->f_mapping);
2655 vma_iter_store(&vmi, vma);
2658 if (vma->vm_flags & VM_SHARED)
2659 mapping_allow_writable(vma->vm_file->f_mapping);
2661 flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2662 vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2663 flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2664 i_mmap_unlock_write(vma->vm_file->f_mapping);
2668 * vma_merge() calls khugepaged_enter_vma() either, the below
2669 * call covers the non-merge case.
2671 khugepaged_enter_vma(vma, vma->vm_flags);
2673 /* Once vma denies write, undo our temporary denial count */
2675 if (file && vm_flags & VM_SHARED)
2676 mapping_unmap_writable(file->f_mapping);
2677 file = vma->vm_file;
2679 perf_event_mmap(vma);
2681 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2682 if (vm_flags & VM_LOCKED) {
2683 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2684 is_vm_hugetlb_page(vma) ||
2685 vma == get_gate_vma(current->mm))
2686 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
2688 mm->locked_vm += (len >> PAGE_SHIFT);
2695 * New (or expanded) vma always get soft dirty status.
2696 * Otherwise user-space soft-dirty page tracker won't
2697 * be able to distinguish situation when vma area unmapped,
2698 * then new mapped in-place (which must be aimed as
2699 * a completely new data area).
2701 vma->vm_flags |= VM_SOFTDIRTY;
2703 vma_set_page_prot(vma);
2709 if (file && vma->vm_ops && vma->vm_ops->close)
2710 vma->vm_ops->close(vma);
2712 if (file || vma->vm_file) {
2715 vma->vm_file = NULL;
2717 /* Undo any partial mapping done by a device driver. */
2718 unmap_region(mm, &mm->mm_mt, vma, prev, next, vma->vm_start,
2721 if (file && (vm_flags & VM_SHARED))
2722 mapping_unmap_writable(file->f_mapping);
2727 vm_unacct_memory(charged);
2732 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2735 struct mm_struct *mm = current->mm;
2737 VMA_ITERATOR(vmi, mm, start);
2739 if (mmap_write_lock_killable(mm))
2742 ret = do_vmi_munmap(&vmi, mm, start, len, &uf, downgrade);
2744 * Returning 1 indicates mmap_lock is downgraded.
2745 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2746 * it to 0 before return.
2749 mmap_read_unlock(mm);
2752 mmap_write_unlock(mm);
2754 userfaultfd_unmap_complete(mm, &uf);
2758 int vm_munmap(unsigned long start, size_t len)
2760 return __vm_munmap(start, len, false);
2762 EXPORT_SYMBOL(vm_munmap);
2764 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2766 addr = untagged_addr(addr);
2767 return __vm_munmap(addr, len, true);
2772 * Emulation of deprecated remap_file_pages() syscall.
2774 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2775 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2778 struct mm_struct *mm = current->mm;
2779 struct vm_area_struct *vma;
2780 unsigned long populate = 0;
2781 unsigned long ret = -EINVAL;
2784 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2785 current->comm, current->pid);
2789 start = start & PAGE_MASK;
2790 size = size & PAGE_MASK;
2792 if (start + size <= start)
2795 /* Does pgoff wrap? */
2796 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2799 if (mmap_write_lock_killable(mm))
2802 vma = vma_lookup(mm, start);
2804 if (!vma || !(vma->vm_flags & VM_SHARED))
2807 if (start + size > vma->vm_end) {
2808 VMA_ITERATOR(vmi, mm, vma->vm_end);
2809 struct vm_area_struct *next, *prev = vma;
2811 for_each_vma_range(vmi, next, start + size) {
2812 /* hole between vmas ? */
2813 if (next->vm_start != prev->vm_end)
2816 if (next->vm_file != vma->vm_file)
2819 if (next->vm_flags != vma->vm_flags)
2822 if (start + size <= next->vm_end)
2832 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2833 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2834 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2836 flags &= MAP_NONBLOCK;
2837 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2838 if (vma->vm_flags & VM_LOCKED)
2839 flags |= MAP_LOCKED;
2841 file = get_file(vma->vm_file);
2842 ret = do_mmap(vma->vm_file, start, size,
2843 prot, flags, pgoff, &populate, NULL);
2846 mmap_write_unlock(mm);
2848 mm_populate(ret, populate);
2849 if (!IS_ERR_VALUE(ret))
2855 * do_vma_munmap() - Unmap a full or partial vma.
2856 * @vmi: The vma iterator pointing at the vma
2857 * @vma: The first vma to be munmapped
2858 * @start: the start of the address to unmap
2859 * @end: The end of the address to unmap
2860 * @uf: The userfaultfd list_head
2861 * @downgrade: Attempt to downgrade or not
2863 * Returns: 0 on success and not downgraded, 1 on success and downgraded.
2864 * unmaps a VMA mapping when the vma iterator is already in position.
2865 * Does not handle alignment.
2867 int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2868 unsigned long start, unsigned long end,
2869 struct list_head *uf, bool downgrade)
2871 struct mm_struct *mm = vma->vm_mm;
2874 arch_unmap(mm, start, end);
2875 ret = do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2881 * do_brk_flags() - Increase the brk vma if the flags match.
2882 * @vmi: The vma iterator
2883 * @addr: The start address
2884 * @len: The length of the increase
2886 * @flags: The VMA Flags
2888 * Extend the brk VMA from addr to addr + len. If the VMA is NULL or the flags
2889 * do not match then create a new anonymous VMA. Eventually we may be able to
2890 * do some brk-specific accounting here.
2892 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
2893 unsigned long addr, unsigned long len, unsigned long flags)
2895 struct mm_struct *mm = current->mm;
2899 * Check against address space limits by the changed size
2900 * Note: This happens *after* clearing old mappings in some code paths.
2902 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2903 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
2906 if (mm->map_count > sysctl_max_map_count)
2909 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2913 * Expand the existing vma if possible; Note that singular lists do not
2914 * occur after forking, so the expand will only happen on new VMAs.
2916 if (vma && vma->vm_end == addr && !vma_policy(vma) &&
2917 can_vma_merge_after(vma, flags, NULL, NULL,
2918 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
2919 if (vma_iter_prealloc(vmi))
2922 vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
2923 if (vma->anon_vma) {
2924 anon_vma_lock_write(vma->anon_vma);
2925 anon_vma_interval_tree_pre_update_vma(vma);
2927 vma->vm_end = addr + len;
2928 vma->vm_flags |= VM_SOFTDIRTY;
2929 vma_iter_store(vmi, vma);
2931 if (vma->anon_vma) {
2932 anon_vma_interval_tree_post_update_vma(vma);
2933 anon_vma_unlock_write(vma->anon_vma);
2935 khugepaged_enter_vma(vma, flags);
2939 /* create a vma struct for an anonymous mapping */
2940 vma = vm_area_alloc(mm);
2944 vma_set_anonymous(vma);
2945 vma->vm_start = addr;
2946 vma->vm_end = addr + len;
2947 vma->vm_pgoff = addr >> PAGE_SHIFT;
2948 vma->vm_flags = flags;
2949 vma->vm_page_prot = vm_get_page_prot(flags);
2950 if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
2951 goto mas_store_fail;
2955 perf_event_mmap(vma);
2956 mm->total_vm += len >> PAGE_SHIFT;
2957 mm->data_vm += len >> PAGE_SHIFT;
2958 if (flags & VM_LOCKED)
2959 mm->locked_vm += (len >> PAGE_SHIFT);
2960 vma->vm_flags |= VM_SOFTDIRTY;
2967 vm_unacct_memory(len >> PAGE_SHIFT);
2971 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
2973 struct mm_struct *mm = current->mm;
2974 struct vm_area_struct *vma = NULL;
2979 VMA_ITERATOR(vmi, mm, addr);
2981 len = PAGE_ALIGN(request);
2987 if (mmap_write_lock_killable(mm))
2990 /* Until we need other flags, refuse anything except VM_EXEC. */
2991 if ((flags & (~VM_EXEC)) != 0)
2994 ret = check_brk_limits(addr, len);
2998 ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
3002 vma = vma_prev(&vmi);
3003 ret = do_brk_flags(&vmi, vma, addr, len, flags);
3004 populate = ((mm->def_flags & VM_LOCKED) != 0);
3005 mmap_write_unlock(mm);
3006 userfaultfd_unmap_complete(mm, &uf);
3007 if (populate && !ret)
3008 mm_populate(addr, len);
3013 mmap_write_unlock(mm);
3016 EXPORT_SYMBOL(vm_brk_flags);
3018 int vm_brk(unsigned long addr, unsigned long len)
3020 return vm_brk_flags(addr, len, 0);
3022 EXPORT_SYMBOL(vm_brk);
3024 /* Release all mmaps. */
3025 void exit_mmap(struct mm_struct *mm)
3027 struct mmu_gather tlb;
3028 struct vm_area_struct *vma;
3029 unsigned long nr_accounted = 0;
3030 MA_STATE(mas, &mm->mm_mt, 0, 0);
3033 /* mm's last user has gone, and its about to be pulled down */
3034 mmu_notifier_release(mm);
3039 vma = mas_find(&mas, ULONG_MAX);
3041 /* Can happen if dup_mmap() received an OOM */
3042 mmap_read_unlock(mm);
3048 tlb_gather_mmu_fullmm(&tlb, mm);
3049 /* update_hiwater_rss(mm) here? but nobody should be looking */
3050 /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3051 unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX);
3052 mmap_read_unlock(mm);
3055 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3056 * because the memory has been already freed.
3058 set_bit(MMF_OOM_SKIP, &mm->flags);
3059 mmap_write_lock(mm);
3060 free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
3061 USER_PGTABLES_CEILING);
3062 tlb_finish_mmu(&tlb);
3065 * Walk the list again, actually closing and freeing it, with preemption
3066 * enabled, without holding any MM locks besides the unreachable
3070 if (vma->vm_flags & VM_ACCOUNT)
3071 nr_accounted += vma_pages(vma);
3075 } while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3077 BUG_ON(count != mm->map_count);
3079 trace_exit_mmap(mm);
3080 __mt_destroy(&mm->mm_mt);
3081 mmap_write_unlock(mm);
3082 vm_unacct_memory(nr_accounted);
3085 /* Insert vm structure into process list sorted by address
3086 * and into the inode's i_mmap tree. If vm_file is non-NULL
3087 * then i_mmap_rwsem is taken here.
3089 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3091 unsigned long charged = vma_pages(vma);
3094 if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3097 if ((vma->vm_flags & VM_ACCOUNT) &&
3098 security_vm_enough_memory_mm(mm, charged))
3102 * The vm_pgoff of a purely anonymous vma should be irrelevant
3103 * until its first write fault, when page's anon_vma and index
3104 * are set. But now set the vm_pgoff it will almost certainly
3105 * end up with (unless mremap moves it elsewhere before that
3106 * first wfault), so /proc/pid/maps tells a consistent story.
3108 * By setting it to reflect the virtual start address of the
3109 * vma, merges and splits can happen in a seamless way, just
3110 * using the existing file pgoff checks and manipulations.
3111 * Similarly in do_mmap and in do_brk_flags.
3113 if (vma_is_anonymous(vma)) {
3114 BUG_ON(vma->anon_vma);
3115 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3118 if (vma_link(mm, vma)) {
3119 vm_unacct_memory(charged);
3127 * Copy the vma structure to a new location in the same mm,
3128 * prior to moving page table entries, to effect an mremap move.
3130 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3131 unsigned long addr, unsigned long len, pgoff_t pgoff,
3132 bool *need_rmap_locks)
3134 struct vm_area_struct *vma = *vmap;
3135 unsigned long vma_start = vma->vm_start;
3136 struct mm_struct *mm = vma->vm_mm;
3137 struct vm_area_struct *new_vma, *prev;
3138 bool faulted_in_anon_vma = true;
3139 VMA_ITERATOR(vmi, mm, addr);
3143 * If anonymous vma has not yet been faulted, update new pgoff
3144 * to match new location, to increase its chance of merging.
3146 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3147 pgoff = addr >> PAGE_SHIFT;
3148 faulted_in_anon_vma = false;
3151 new_vma = find_vma_prev(mm, addr, &prev);
3152 if (new_vma && new_vma->vm_start < addr + len)
3153 return NULL; /* should never get here */
3155 new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
3156 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3157 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3160 * Source vma may have been merged into new_vma
3162 if (unlikely(vma_start >= new_vma->vm_start &&
3163 vma_start < new_vma->vm_end)) {
3165 * The only way we can get a vma_merge with
3166 * self during an mremap is if the vma hasn't
3167 * been faulted in yet and we were allowed to
3168 * reset the dst vma->vm_pgoff to the
3169 * destination address of the mremap to allow
3170 * the merge to happen. mremap must change the
3171 * vm_pgoff linearity between src and dst vmas
3172 * (in turn preventing a vma_merge) to be
3173 * safe. It is only safe to keep the vm_pgoff
3174 * linear if there are no pages mapped yet.
3176 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3177 *vmap = vma = new_vma;
3179 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3181 new_vma = vm_area_dup(vma);
3184 new_vma->vm_start = addr;
3185 new_vma->vm_end = addr + len;
3186 new_vma->vm_pgoff = pgoff;
3187 if (vma_dup_policy(vma, new_vma))
3189 if (anon_vma_clone(new_vma, vma))
3190 goto out_free_mempol;
3191 if (new_vma->vm_file)
3192 get_file(new_vma->vm_file);
3193 if (new_vma->vm_ops && new_vma->vm_ops->open)
3194 new_vma->vm_ops->open(new_vma);
3195 if (vma_link(mm, new_vma))
3197 *need_rmap_locks = false;
3203 if (new_vma->vm_ops && new_vma->vm_ops->close)
3204 new_vma->vm_ops->close(new_vma);
3206 if (new_vma->vm_file)
3207 fput(new_vma->vm_file);
3209 unlink_anon_vmas(new_vma);
3211 mpol_put(vma_policy(new_vma));
3213 vm_area_free(new_vma);
3220 * Return true if the calling process may expand its vm space by the passed
3223 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3225 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3228 if (is_data_mapping(flags) &&
3229 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3230 /* Workaround for Valgrind */
3231 if (rlimit(RLIMIT_DATA) == 0 &&
3232 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3235 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3236 current->comm, current->pid,
3237 (mm->data_vm + npages) << PAGE_SHIFT,
3238 rlimit(RLIMIT_DATA),
3239 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3241 if (!ignore_rlimit_data)
3248 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3250 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3252 if (is_exec_mapping(flags))
3253 mm->exec_vm += npages;
3254 else if (is_stack_mapping(flags))
3255 mm->stack_vm += npages;
3256 else if (is_data_mapping(flags))
3257 mm->data_vm += npages;
3260 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3263 * Having a close hook prevents vma merging regardless of flags.
3265 static void special_mapping_close(struct vm_area_struct *vma)
3269 static const char *special_mapping_name(struct vm_area_struct *vma)
3271 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3274 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3276 struct vm_special_mapping *sm = new_vma->vm_private_data;
3278 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3282 return sm->mremap(sm, new_vma);
3287 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3290 * Forbid splitting special mappings - kernel has expectations over
3291 * the number of pages in mapping. Together with VM_DONTEXPAND
3292 * the size of vma should stay the same over the special mapping's
3298 static const struct vm_operations_struct special_mapping_vmops = {
3299 .close = special_mapping_close,
3300 .fault = special_mapping_fault,
3301 .mremap = special_mapping_mremap,
3302 .name = special_mapping_name,
3303 /* vDSO code relies that VVAR can't be accessed remotely */
3305 .may_split = special_mapping_split,
3308 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3309 .close = special_mapping_close,
3310 .fault = special_mapping_fault,
3313 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3315 struct vm_area_struct *vma = vmf->vma;
3317 struct page **pages;
3319 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3320 pages = vma->vm_private_data;
3322 struct vm_special_mapping *sm = vma->vm_private_data;
3325 return sm->fault(sm, vmf->vma, vmf);
3330 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3334 struct page *page = *pages;
3340 return VM_FAULT_SIGBUS;
3343 static struct vm_area_struct *__install_special_mapping(
3344 struct mm_struct *mm,
3345 unsigned long addr, unsigned long len,
3346 unsigned long vm_flags, void *priv,
3347 const struct vm_operations_struct *ops)
3350 struct vm_area_struct *vma;
3353 vma = vm_area_alloc(mm);
3354 if (unlikely(vma == NULL))
3355 return ERR_PTR(-ENOMEM);
3357 vma->vm_start = addr;
3358 vma->vm_end = addr + len;
3360 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3361 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3362 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3365 vma->vm_private_data = priv;
3367 ret = insert_vm_struct(mm, vma);
3371 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3373 perf_event_mmap(vma);
3381 return ERR_PTR(ret);
3384 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3385 const struct vm_special_mapping *sm)
3387 return vma->vm_private_data == sm &&
3388 (vma->vm_ops == &special_mapping_vmops ||
3389 vma->vm_ops == &legacy_special_mapping_vmops);
3393 * Called with mm->mmap_lock held for writing.
3394 * Insert a new vma covering the given region, with the given flags.
3395 * Its pages are supplied by the given array of struct page *.
3396 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3397 * The region past the last page supplied will always produce SIGBUS.
3398 * The array pointer and the pages it points to are assumed to stay alive
3399 * for as long as this mapping might exist.
3401 struct vm_area_struct *_install_special_mapping(
3402 struct mm_struct *mm,
3403 unsigned long addr, unsigned long len,
3404 unsigned long vm_flags, const struct vm_special_mapping *spec)
3406 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3407 &special_mapping_vmops);
3410 int install_special_mapping(struct mm_struct *mm,
3411 unsigned long addr, unsigned long len,
3412 unsigned long vm_flags, struct page **pages)
3414 struct vm_area_struct *vma = __install_special_mapping(
3415 mm, addr, len, vm_flags, (void *)pages,
3416 &legacy_special_mapping_vmops);
3418 return PTR_ERR_OR_ZERO(vma);
3421 static DEFINE_MUTEX(mm_all_locks_mutex);
3423 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3425 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3427 * The LSB of head.next can't change from under us
3428 * because we hold the mm_all_locks_mutex.
3430 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3432 * We can safely modify head.next after taking the
3433 * anon_vma->root->rwsem. If some other vma in this mm shares
3434 * the same anon_vma we won't take it again.
3436 * No need of atomic instructions here, head.next
3437 * can't change from under us thanks to the
3438 * anon_vma->root->rwsem.
3440 if (__test_and_set_bit(0, (unsigned long *)
3441 &anon_vma->root->rb_root.rb_root.rb_node))
3446 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3448 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3450 * AS_MM_ALL_LOCKS can't change from under us because
3451 * we hold the mm_all_locks_mutex.
3453 * Operations on ->flags have to be atomic because
3454 * even if AS_MM_ALL_LOCKS is stable thanks to the
3455 * mm_all_locks_mutex, there may be other cpus
3456 * changing other bitflags in parallel to us.
3458 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3460 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3465 * This operation locks against the VM for all pte/vma/mm related
3466 * operations that could ever happen on a certain mm. This includes
3467 * vmtruncate, try_to_unmap, and all page faults.
3469 * The caller must take the mmap_lock in write mode before calling
3470 * mm_take_all_locks(). The caller isn't allowed to release the
3471 * mmap_lock until mm_drop_all_locks() returns.
3473 * mmap_lock in write mode is required in order to block all operations
3474 * that could modify pagetables and free pages without need of
3475 * altering the vma layout. It's also needed in write mode to avoid new
3476 * anon_vmas to be associated with existing vmas.
3478 * A single task can't take more than one mm_take_all_locks() in a row
3479 * or it would deadlock.
3481 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3482 * mapping->flags avoid to take the same lock twice, if more than one
3483 * vma in this mm is backed by the same anon_vma or address_space.
3485 * We take locks in following order, accordingly to comment at beginning
3487 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3489 * - all i_mmap_rwsem locks;
3490 * - all anon_vma->rwseml
3492 * We can take all locks within these types randomly because the VM code
3493 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3494 * mm_all_locks_mutex.
3496 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3497 * that may have to take thousand of locks.
3499 * mm_take_all_locks() can fail if it's interrupted by signals.
3501 int mm_take_all_locks(struct mm_struct *mm)
3503 struct vm_area_struct *vma;
3504 struct anon_vma_chain *avc;
3505 MA_STATE(mas, &mm->mm_mt, 0, 0);
3507 mmap_assert_write_locked(mm);
3509 mutex_lock(&mm_all_locks_mutex);
3511 mas_for_each(&mas, vma, ULONG_MAX) {
3512 if (signal_pending(current))
3514 if (vma->vm_file && vma->vm_file->f_mapping &&
3515 is_vm_hugetlb_page(vma))
3516 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3520 mas_for_each(&mas, vma, ULONG_MAX) {
3521 if (signal_pending(current))
3523 if (vma->vm_file && vma->vm_file->f_mapping &&
3524 !is_vm_hugetlb_page(vma))
3525 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3529 mas_for_each(&mas, vma, ULONG_MAX) {
3530 if (signal_pending(current))
3533 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3534 vm_lock_anon_vma(mm, avc->anon_vma);
3540 mm_drop_all_locks(mm);
3544 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3546 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3548 * The LSB of head.next can't change to 0 from under
3549 * us because we hold the mm_all_locks_mutex.
3551 * We must however clear the bitflag before unlocking
3552 * the vma so the users using the anon_vma->rb_root will
3553 * never see our bitflag.
3555 * No need of atomic instructions here, head.next
3556 * can't change from under us until we release the
3557 * anon_vma->root->rwsem.
3559 if (!__test_and_clear_bit(0, (unsigned long *)
3560 &anon_vma->root->rb_root.rb_root.rb_node))
3562 anon_vma_unlock_write(anon_vma);
3566 static void vm_unlock_mapping(struct address_space *mapping)
3568 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3570 * AS_MM_ALL_LOCKS can't change to 0 from under us
3571 * because we hold the mm_all_locks_mutex.
3573 i_mmap_unlock_write(mapping);
3574 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3581 * The mmap_lock cannot be released by the caller until
3582 * mm_drop_all_locks() returns.
3584 void mm_drop_all_locks(struct mm_struct *mm)
3586 struct vm_area_struct *vma;
3587 struct anon_vma_chain *avc;
3588 MA_STATE(mas, &mm->mm_mt, 0, 0);
3590 mmap_assert_write_locked(mm);
3591 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3593 mas_for_each(&mas, vma, ULONG_MAX) {
3595 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3596 vm_unlock_anon_vma(avc->anon_vma);
3597 if (vma->vm_file && vma->vm_file->f_mapping)
3598 vm_unlock_mapping(vma->vm_file->f_mapping);
3601 mutex_unlock(&mm_all_locks_mutex);
3605 * initialise the percpu counter for VM
3607 void __init mmap_init(void)
3611 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3616 * Initialise sysctl_user_reserve_kbytes.
3618 * This is intended to prevent a user from starting a single memory hogging
3619 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3622 * The default value is min(3% of free memory, 128MB)
3623 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3625 static int init_user_reserve(void)
3627 unsigned long free_kbytes;
3629 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3631 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3634 subsys_initcall(init_user_reserve);
3637 * Initialise sysctl_admin_reserve_kbytes.
3639 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3640 * to log in and kill a memory hogging process.
3642 * Systems with more than 256MB will reserve 8MB, enough to recover
3643 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3644 * only reserve 3% of free pages by default.
3646 static int init_admin_reserve(void)
3648 unsigned long free_kbytes;
3650 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3652 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3655 subsys_initcall(init_admin_reserve);
3658 * Reinititalise user and admin reserves if memory is added or removed.
3660 * The default user reserve max is 128MB, and the default max for the
3661 * admin reserve is 8MB. These are usually, but not always, enough to
3662 * enable recovery from a memory hogging process using login/sshd, a shell,
3663 * and tools like top. It may make sense to increase or even disable the
3664 * reserve depending on the existence of swap or variations in the recovery
3665 * tools. So, the admin may have changed them.
3667 * If memory is added and the reserves have been eliminated or increased above
3668 * the default max, then we'll trust the admin.
3670 * If memory is removed and there isn't enough free memory, then we
3671 * need to reset the reserves.
3673 * Otherwise keep the reserve set by the admin.
3675 static int reserve_mem_notifier(struct notifier_block *nb,
3676 unsigned long action, void *data)
3678 unsigned long tmp, free_kbytes;
3682 /* Default max is 128MB. Leave alone if modified by operator. */
3683 tmp = sysctl_user_reserve_kbytes;
3684 if (0 < tmp && tmp < (1UL << 17))
3685 init_user_reserve();
3687 /* Default max is 8MB. Leave alone if modified by operator. */
3688 tmp = sysctl_admin_reserve_kbytes;
3689 if (0 < tmp && tmp < (1UL << 13))
3690 init_admin_reserve();
3694 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3696 if (sysctl_user_reserve_kbytes > free_kbytes) {
3697 init_user_reserve();
3698 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3699 sysctl_user_reserve_kbytes);
3702 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3703 init_admin_reserve();
3704 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3705 sysctl_admin_reserve_kbytes);
3714 static int __meminit init_reserve_notifier(void)
3716 if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3717 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3721 subsys_initcall(init_reserve_notifier);