6 * Address space accounting code <alan@lxorguk.ukuu.org.uk>
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 #include <linux/kernel.h>
12 #include <linux/slab.h>
13 #include <linux/backing-dev.h>
15 #include <linux/vmacache.h>
16 #include <linux/shm.h>
17 #include <linux/mman.h>
18 #include <linux/pagemap.h>
19 #include <linux/swap.h>
20 #include <linux/syscalls.h>
21 #include <linux/capability.h>
22 #include <linux/init.h>
23 #include <linux/file.h>
25 #include <linux/personality.h>
26 #include <linux/security.h>
27 #include <linux/hugetlb.h>
28 #include <linux/profile.h>
29 #include <linux/export.h>
30 #include <linux/mount.h>
31 #include <linux/mempolicy.h>
32 #include <linux/rmap.h>
33 #include <linux/mmu_notifier.h>
34 #include <linux/mmdebug.h>
35 #include <linux/perf_event.h>
36 #include <linux/audit.h>
37 #include <linux/khugepaged.h>
38 #include <linux/uprobes.h>
39 #include <linux/rbtree_augmented.h>
40 #include <linux/sched/sysctl.h>
41 #include <linux/notifier.h>
42 #include <linux/memory.h>
43 #include <linux/printk.h>
44 #include <linux/userfaultfd_k.h>
47 #include <asm/uaccess.h>
48 #include <asm/cacheflush.h>
50 #include <asm/mmu_context.h>
52 #ifdef CONFIG_MSM_APP_SETTINGS
53 #include <asm/app_api.h>
58 #ifndef arch_mmap_check
59 #define arch_mmap_check(addr, len, flags) (0)
62 #ifndef arch_rebalance_pgtables
63 #define arch_rebalance_pgtables(addr, len) (addr)
66 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
67 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
68 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
69 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
71 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
72 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
73 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
74 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
78 static void unmap_region(struct mm_struct *mm,
79 struct vm_area_struct *vma, struct vm_area_struct *prev,
80 unsigned long start, unsigned long end);
82 /* description of effects of mapping type and prot in current implementation.
83 * this is due to the limited x86 page protection hardware. The expected
84 * behavior is in parens:
87 * PROT_NONE PROT_READ PROT_WRITE PROT_EXEC
88 * MAP_SHARED r: (no) no r: (yes) yes r: (no) yes r: (no) yes
89 * w: (no) no w: (no) no w: (yes) yes w: (no) no
90 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
92 * MAP_PRIVATE r: (no) no r: (yes) yes r: (no) yes r: (no) yes
93 * w: (no) no w: (no) no w: (copy) copy w: (no) no
94 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
97 pgprot_t protection_map[16] = {
98 __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
99 __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
102 pgprot_t vm_get_page_prot(unsigned long vm_flags)
104 return __pgprot(pgprot_val(protection_map[vm_flags &
105 (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
106 pgprot_val(arch_vm_get_page_prot(vm_flags)));
108 EXPORT_SYMBOL(vm_get_page_prot);
110 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
112 return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
115 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
116 void vma_set_page_prot(struct vm_area_struct *vma)
118 unsigned long vm_flags = vma->vm_flags;
120 vma->vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
121 if (vma_wants_writenotify(vma)) {
122 vm_flags &= ~VM_SHARED;
123 vma->vm_page_prot = vm_pgprot_modify(vma->vm_page_prot,
129 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS; /* heuristic overcommit */
130 int sysctl_overcommit_ratio __read_mostly = 50; /* default is 50% */
131 unsigned long sysctl_overcommit_kbytes __read_mostly;
132 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
133 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
134 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
136 * Make sure vm_committed_as in one cacheline and not cacheline shared with
137 * other variables. It can be updated by several CPUs frequently.
139 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
142 * The global memory commitment made in the system can be a metric
143 * that can be used to drive ballooning decisions when Linux is hosted
144 * as a guest. On Hyper-V, the host implements a policy engine for dynamically
145 * balancing memory across competing virtual machines that are hosted.
146 * Several metrics drive this policy engine including the guest reported
149 unsigned long vm_memory_committed(void)
151 return percpu_counter_read_positive(&vm_committed_as);
153 EXPORT_SYMBOL_GPL(vm_memory_committed);
156 * Check that a process has enough memory to allocate a new virtual
157 * mapping. 0 means there is enough memory for the allocation to
158 * succeed and -ENOMEM implies there is not.
160 * We currently support three overcommit policies, which are set via the
161 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
163 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
164 * Additional code 2002 Jul 20 by Robert Love.
166 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
168 * Note this is a helper function intended to be used by LSMs which
169 * wish to use this logic.
171 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
173 long free, allowed, reserve;
175 VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
176 -(s64)vm_committed_as_batch * num_online_cpus(),
177 "memory commitment underflow");
179 vm_acct_memory(pages);
182 * Sometimes we want to use more memory than we have
184 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
187 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
188 free = global_page_state(NR_FREE_PAGES);
189 free += global_page_state(NR_FILE_PAGES);
192 * shmem pages shouldn't be counted as free in this
193 * case, they can't be purged, only swapped out, and
194 * that won't affect the overall amount of available
195 * memory in the system.
197 free -= global_page_state(NR_SHMEM);
199 free += get_nr_swap_pages();
202 * Any slabs which are created with the
203 * SLAB_RECLAIM_ACCOUNT flag claim to have contents
204 * which are reclaimable, under pressure. The dentry
205 * cache and most inode caches should fall into this
207 free += global_page_state(NR_SLAB_RECLAIMABLE);
210 * Part of the kernel memory, which can be released
211 * under memory pressure.
213 free += global_page_state(
214 NR_INDIRECTLY_RECLAIMABLE_BYTES) >> PAGE_SHIFT;
217 * Leave reserved pages. The pages are not for anonymous pages.
219 if (free <= totalreserve_pages)
222 free -= totalreserve_pages;
225 * Reserve some for root
228 free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
236 allowed = vm_commit_limit();
238 * Reserve some for root
241 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
244 * Don't let a single process grow so big a user can't recover
247 reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
248 allowed -= min_t(long, mm->total_vm / 32, reserve);
251 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
254 vm_unacct_memory(pages);
260 * Requires inode->i_mapping->i_mmap_rwsem
262 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
263 struct file *file, struct address_space *mapping)
265 if (vma->vm_flags & VM_DENYWRITE)
266 atomic_inc(&file_inode(file)->i_writecount);
267 if (vma->vm_flags & VM_SHARED)
268 mapping_unmap_writable(mapping);
270 flush_dcache_mmap_lock(mapping);
271 vma_interval_tree_remove(vma, &mapping->i_mmap);
272 flush_dcache_mmap_unlock(mapping);
276 * Unlink a file-based vm structure from its interval tree, to hide
277 * vma from rmap and vmtruncate before freeing its page tables.
279 void unlink_file_vma(struct vm_area_struct *vma)
281 struct file *file = vma->vm_file;
284 struct address_space *mapping = file->f_mapping;
285 i_mmap_lock_write(mapping);
286 __remove_shared_vm_struct(vma, file, mapping);
287 i_mmap_unlock_write(mapping);
292 * Close a vm structure and free it, returning the next.
294 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
296 struct vm_area_struct *next = vma->vm_next;
299 if (vma->vm_ops && vma->vm_ops->close)
300 vma->vm_ops->close(vma);
303 mpol_put(vma_policy(vma));
304 kmem_cache_free(vm_area_cachep, vma);
308 static unsigned long do_brk(unsigned long addr, unsigned long len);
310 SYSCALL_DEFINE1(brk, unsigned long, brk)
312 unsigned long retval;
313 unsigned long newbrk, oldbrk;
314 struct mm_struct *mm = current->mm;
315 struct vm_area_struct *next;
316 unsigned long min_brk;
319 down_write(&mm->mmap_sem);
321 #ifdef CONFIG_COMPAT_BRK
323 * CONFIG_COMPAT_BRK can still be overridden by setting
324 * randomize_va_space to 2, which will still cause mm->start_brk
325 * to be arbitrarily shifted
327 if (current->brk_randomized)
328 min_brk = mm->start_brk;
330 min_brk = mm->end_data;
332 min_brk = mm->start_brk;
338 * Check against rlimit here. If this check is done later after the test
339 * of oldbrk with newbrk then it can escape the test and let the data
340 * segment grow beyond its set limit the in case where the limit is
341 * not page aligned -Ram Gupta
343 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
344 mm->end_data, mm->start_data))
347 newbrk = PAGE_ALIGN(brk);
348 oldbrk = PAGE_ALIGN(mm->brk);
349 if (oldbrk == newbrk)
352 /* Always allow shrinking brk. */
353 if (brk <= mm->brk) {
354 if (!do_munmap(mm, newbrk, oldbrk-newbrk))
359 /* Check against existing mmap mappings. */
360 next = find_vma(mm, oldbrk);
361 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
364 /* Ok, looks good - let it rip. */
365 if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
370 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
371 up_write(&mm->mmap_sem);
373 mm_populate(oldbrk, newbrk - oldbrk);
378 up_write(&mm->mmap_sem);
382 static long vma_compute_subtree_gap(struct vm_area_struct *vma)
384 unsigned long max, prev_end, subtree_gap;
387 * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
388 * allow two stack_guard_gaps between them here, and when choosing
389 * an unmapped area; whereas when expanding we only require one.
390 * That's a little inconsistent, but keeps the code here simpler.
392 max = vm_start_gap(vma);
394 prev_end = vm_end_gap(vma->vm_prev);
400 if (vma->vm_rb.rb_left) {
401 subtree_gap = rb_entry(vma->vm_rb.rb_left,
402 struct vm_area_struct, vm_rb)->rb_subtree_gap;
403 if (subtree_gap > max)
406 if (vma->vm_rb.rb_right) {
407 subtree_gap = rb_entry(vma->vm_rb.rb_right,
408 struct vm_area_struct, vm_rb)->rb_subtree_gap;
409 if (subtree_gap > max)
415 #ifdef CONFIG_DEBUG_VM_RB
416 static int browse_rb(struct rb_root *root)
418 int i = 0, j, bug = 0;
419 struct rb_node *nd, *pn = NULL;
420 unsigned long prev = 0, pend = 0;
422 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
423 struct vm_area_struct *vma;
424 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
425 if (vma->vm_start < prev) {
426 pr_emerg("vm_start %lx < prev %lx\n",
427 vma->vm_start, prev);
430 if (vma->vm_start < pend) {
431 pr_emerg("vm_start %lx < pend %lx\n",
432 vma->vm_start, pend);
435 if (vma->vm_start > vma->vm_end) {
436 pr_emerg("vm_start %lx > vm_end %lx\n",
437 vma->vm_start, vma->vm_end);
440 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
441 pr_emerg("free gap %lx, correct %lx\n",
443 vma_compute_subtree_gap(vma));
448 prev = vma->vm_start;
452 for (nd = pn; nd; nd = rb_prev(nd))
455 pr_emerg("backwards %d, forwards %d\n", j, i);
461 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
465 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
466 struct vm_area_struct *vma;
467 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
468 VM_BUG_ON_VMA(vma != ignore &&
469 vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
474 static void validate_mm(struct mm_struct *mm)
478 unsigned long highest_address = 0;
479 struct vm_area_struct *vma = mm->mmap;
482 struct anon_vma *anon_vma = vma->anon_vma;
483 struct anon_vma_chain *avc;
486 anon_vma_lock_read(anon_vma);
487 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
488 anon_vma_interval_tree_verify(avc);
489 anon_vma_unlock_read(anon_vma);
492 highest_address = vm_end_gap(vma);
496 if (i != mm->map_count) {
497 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
500 if (highest_address != mm->highest_vm_end) {
501 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
502 mm->highest_vm_end, highest_address);
505 i = browse_rb(&mm->mm_rb);
506 if (i != mm->map_count) {
508 pr_emerg("map_count %d rb %d\n", mm->map_count, i);
511 VM_BUG_ON_MM(bug, mm);
514 #define validate_mm_rb(root, ignore) do { } while (0)
515 #define validate_mm(mm) do { } while (0)
518 RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,
519 unsigned long, rb_subtree_gap, vma_compute_subtree_gap)
522 * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
523 * vma->vm_prev->vm_end values changed, without modifying the vma's position
526 static void vma_gap_update(struct vm_area_struct *vma)
529 * As it turns out, RB_DECLARE_CALLBACKS() already created a callback
530 * function that does exacltly what we want.
532 vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
535 static inline void vma_rb_insert(struct vm_area_struct *vma,
536 struct rb_root *root)
538 /* All rb_subtree_gap values must be consistent prior to insertion */
539 validate_mm_rb(root, NULL);
541 rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
544 static void vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
547 * All rb_subtree_gap values must be consistent prior to erase,
548 * with the possible exception of the vma being erased.
550 validate_mm_rb(root, vma);
553 * Note rb_erase_augmented is a fairly large inline function,
554 * so make sure we instantiate it only once with our desired
555 * augmented rbtree callbacks.
557 rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
561 * vma has some anon_vma assigned, and is already inserted on that
562 * anon_vma's interval trees.
564 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
565 * vma must be removed from the anon_vma's interval trees using
566 * anon_vma_interval_tree_pre_update_vma().
568 * After the update, the vma will be reinserted using
569 * anon_vma_interval_tree_post_update_vma().
571 * The entire update must be protected by exclusive mmap_sem and by
572 * the root anon_vma's mutex.
575 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
577 struct anon_vma_chain *avc;
579 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
580 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
584 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
586 struct anon_vma_chain *avc;
588 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
589 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
592 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
593 unsigned long end, struct vm_area_struct **pprev,
594 struct rb_node ***rb_link, struct rb_node **rb_parent)
596 struct rb_node **__rb_link, *__rb_parent, *rb_prev;
598 __rb_link = &mm->mm_rb.rb_node;
599 rb_prev = __rb_parent = NULL;
602 struct vm_area_struct *vma_tmp;
604 __rb_parent = *__rb_link;
605 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
607 if (vma_tmp->vm_end > addr) {
608 /* Fail if an existing vma overlaps the area */
609 if (vma_tmp->vm_start < end)
611 __rb_link = &__rb_parent->rb_left;
613 rb_prev = __rb_parent;
614 __rb_link = &__rb_parent->rb_right;
620 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
621 *rb_link = __rb_link;
622 *rb_parent = __rb_parent;
626 static unsigned long count_vma_pages_range(struct mm_struct *mm,
627 unsigned long addr, unsigned long end)
629 unsigned long nr_pages = 0;
630 struct vm_area_struct *vma;
632 /* Find first overlaping mapping */
633 vma = find_vma_intersection(mm, addr, end);
637 nr_pages = (min(end, vma->vm_end) -
638 max(addr, vma->vm_start)) >> PAGE_SHIFT;
640 /* Iterate over the rest of the overlaps */
641 for (vma = vma->vm_next; vma; vma = vma->vm_next) {
642 unsigned long overlap_len;
644 if (vma->vm_start > end)
647 overlap_len = min(end, vma->vm_end) - vma->vm_start;
648 nr_pages += overlap_len >> PAGE_SHIFT;
654 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
655 struct rb_node **rb_link, struct rb_node *rb_parent)
657 /* Update tracking information for the gap following the new vma. */
659 vma_gap_update(vma->vm_next);
661 mm->highest_vm_end = vm_end_gap(vma);
664 * vma->vm_prev wasn't known when we followed the rbtree to find the
665 * correct insertion point for that vma. As a result, we could not
666 * update the vma vm_rb parents rb_subtree_gap values on the way down.
667 * So, we first insert the vma with a zero rb_subtree_gap value
668 * (to be consistent with what we did on the way down), and then
669 * immediately update the gap to the correct value. Finally we
670 * rebalance the rbtree after all augmented values have been set.
672 rb_link_node(&vma->vm_rb, rb_parent, rb_link);
673 vma->rb_subtree_gap = 0;
675 vma_rb_insert(vma, &mm->mm_rb);
678 static void __vma_link_file(struct vm_area_struct *vma)
684 struct address_space *mapping = file->f_mapping;
686 if (vma->vm_flags & VM_DENYWRITE)
687 atomic_dec(&file_inode(file)->i_writecount);
688 if (vma->vm_flags & VM_SHARED)
689 atomic_inc(&mapping->i_mmap_writable);
691 flush_dcache_mmap_lock(mapping);
692 vma_interval_tree_insert(vma, &mapping->i_mmap);
693 flush_dcache_mmap_unlock(mapping);
698 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
699 struct vm_area_struct *prev, struct rb_node **rb_link,
700 struct rb_node *rb_parent)
702 __vma_link_list(mm, vma, prev, rb_parent);
703 __vma_link_rb(mm, vma, rb_link, rb_parent);
706 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
707 struct vm_area_struct *prev, struct rb_node **rb_link,
708 struct rb_node *rb_parent)
710 struct address_space *mapping = NULL;
713 mapping = vma->vm_file->f_mapping;
714 i_mmap_lock_write(mapping);
717 __vma_link(mm, vma, prev, rb_link, rb_parent);
718 __vma_link_file(vma);
721 i_mmap_unlock_write(mapping);
728 * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
729 * mm's list and rbtree. It has already been inserted into the interval tree.
731 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
733 struct vm_area_struct *prev;
734 struct rb_node **rb_link, *rb_parent;
736 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
737 &prev, &rb_link, &rb_parent))
739 __vma_link(mm, vma, prev, rb_link, rb_parent);
744 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
745 struct vm_area_struct *prev)
747 struct vm_area_struct *next;
749 vma_rb_erase(vma, &mm->mm_rb);
750 prev->vm_next = next = vma->vm_next;
752 next->vm_prev = prev;
755 vmacache_invalidate(mm);
759 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
760 * is already present in an i_mmap tree without adjusting the tree.
761 * The following helper function should be used when such adjustments
762 * are necessary. The "insert" vma (if any) is to be inserted
763 * before we drop the necessary locks.
765 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
766 unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
768 struct mm_struct *mm = vma->vm_mm;
769 struct vm_area_struct *next = vma->vm_next;
770 struct vm_area_struct *importer = NULL;
771 struct address_space *mapping = NULL;
772 struct rb_root *root = NULL;
773 struct anon_vma *anon_vma = NULL;
774 struct file *file = vma->vm_file;
775 bool start_changed = false, end_changed = false;
776 long adjust_next = 0;
779 if (next && !insert) {
780 struct vm_area_struct *exporter = NULL;
782 if (end >= next->vm_end) {
784 * vma expands, overlapping all the next, and
785 * perhaps the one after too (mprotect case 6).
787 again: remove_next = 1 + (end > next->vm_end);
791 } else if (end > next->vm_start) {
793 * vma expands, overlapping part of the next:
794 * mprotect case 5 shifting the boundary up.
796 adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
799 } else if (end < vma->vm_end) {
801 * vma shrinks, and !insert tells it's not
802 * split_vma inserting another: so it must be
803 * mprotect case 4 shifting the boundary down.
805 adjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);
811 * Easily overlooked: when mprotect shifts the boundary,
812 * make sure the expanding vma has anon_vma set if the
813 * shrinking vma had, to cover any anon pages imported.
815 if (exporter && exporter->anon_vma && !importer->anon_vma) {
818 importer->anon_vma = exporter->anon_vma;
819 error = anon_vma_clone(importer, exporter);
826 mapping = file->f_mapping;
827 root = &mapping->i_mmap;
828 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
831 uprobe_munmap(next, next->vm_start, next->vm_end);
833 i_mmap_lock_write(mapping);
836 * Put into interval tree now, so instantiated pages
837 * are visible to arm/parisc __flush_dcache_page
838 * throughout; but we cannot insert into address
839 * space until vma start or end is updated.
841 __vma_link_file(insert);
845 vma_adjust_trans_huge(vma, start, end, adjust_next);
847 anon_vma = vma->anon_vma;
848 if (!anon_vma && adjust_next)
849 anon_vma = next->anon_vma;
851 VM_BUG_ON_VMA(adjust_next && next->anon_vma &&
852 anon_vma != next->anon_vma, next);
853 anon_vma_lock_write(anon_vma);
854 anon_vma_interval_tree_pre_update_vma(vma);
856 anon_vma_interval_tree_pre_update_vma(next);
860 flush_dcache_mmap_lock(mapping);
861 vma_interval_tree_remove(vma, root);
863 vma_interval_tree_remove(next, root);
866 if (start != vma->vm_start) {
867 vma->vm_start = start;
868 start_changed = true;
870 if (end != vma->vm_end) {
874 vma->vm_pgoff = pgoff;
876 next->vm_start += adjust_next << PAGE_SHIFT;
877 next->vm_pgoff += adjust_next;
882 vma_interval_tree_insert(next, root);
883 vma_interval_tree_insert(vma, root);
884 flush_dcache_mmap_unlock(mapping);
889 * vma_merge has merged next into vma, and needs
890 * us to remove next before dropping the locks.
892 __vma_unlink(mm, next, vma);
894 __remove_shared_vm_struct(next, file, mapping);
897 * split_vma has split insert from vma, and needs
898 * us to insert it before dropping the locks
899 * (it may either follow vma or precede it).
901 __insert_vm_struct(mm, insert);
907 mm->highest_vm_end = vm_end_gap(vma);
908 else if (!adjust_next)
909 vma_gap_update(next);
914 anon_vma_interval_tree_post_update_vma(vma);
916 anon_vma_interval_tree_post_update_vma(next);
917 anon_vma_unlock_write(anon_vma);
920 i_mmap_unlock_write(mapping);
931 uprobe_munmap(next, next->vm_start, next->vm_end);
935 anon_vma_merge(vma, next);
937 mpol_put(vma_policy(next));
938 kmem_cache_free(vm_area_cachep, next);
940 * In mprotect's case 6 (see comments on vma_merge),
941 * we must remove another next too. It would clutter
942 * up the code too much to do both in one go.
945 if (remove_next == 2)
948 vma_gap_update(next);
950 VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
961 * If the vma has a ->close operation then the driver probably needs to release
962 * per-vma resources, so we don't attempt to merge those.
964 static inline int is_mergeable_vma(struct vm_area_struct *vma,
965 struct file *file, unsigned long vm_flags,
966 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
967 const char __user *anon_name)
970 * VM_SOFTDIRTY should not prevent from VMA merging, if we
971 * match the flags but dirty bit -- the caller should mark
972 * merged VMA as dirty. If dirty bit won't be excluded from
973 * comparison, we increase pressue on the memory system forcing
974 * the kernel to generate new VMAs when old one could be
977 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
979 if (vma->vm_file != file)
981 if (vma->vm_ops && vma->vm_ops->close)
983 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
985 if (vma_get_anon_name(vma) != anon_name)
990 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
991 struct anon_vma *anon_vma2,
992 struct vm_area_struct *vma)
995 * The list_is_singular() test is to avoid merging VMA cloned from
996 * parents. This can improve scalability caused by anon_vma lock.
998 if ((!anon_vma1 || !anon_vma2) && (!vma ||
999 list_is_singular(&vma->anon_vma_chain)))
1001 return anon_vma1 == anon_vma2;
1005 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1006 * in front of (at a lower virtual address and file offset than) the vma.
1008 * We cannot merge two vmas if they have differently assigned (non-NULL)
1009 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1011 * We don't check here for the merged mmap wrapping around the end of pagecache
1012 * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
1013 * wrap, nor mmaps which cover the final page at index -1UL.
1016 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
1017 struct anon_vma *anon_vma, struct file *file,
1019 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1020 const char __user *anon_name)
1022 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1023 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1024 if (vma->vm_pgoff == vm_pgoff)
1031 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1032 * beyond (at a higher virtual address and file offset than) the vma.
1034 * We cannot merge two vmas if they have differently assigned (non-NULL)
1035 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1038 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
1039 struct anon_vma *anon_vma, struct file *file,
1041 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1042 const char __user *anon_name)
1044 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1045 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1047 vm_pglen = vma_pages(vma);
1048 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
1055 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
1056 * figure out whether that can be merged with its predecessor or its
1057 * successor. Or both (it neatly fills a hole).
1059 * In most cases - when called for mmap, brk or mremap - [addr,end) is
1060 * certain not to be mapped by the time vma_merge is called; but when
1061 * called for mprotect, it is certain to be already mapped (either at
1062 * an offset within prev, or at the start of next), and the flags of
1063 * this area are about to be changed to vm_flags - and the no-change
1064 * case has already been eliminated.
1066 * The following mprotect cases have to be considered, where AAAA is
1067 * the area passed down from mprotect_fixup, never extending beyond one
1068 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
1070 * AAAA AAAA AAAA AAAA
1071 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX
1072 * cannot merge might become might become might become
1073 * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or
1074 * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or
1075 * mremap move: PPPPNNNNNNNN 8
1077 * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN
1078 * might become case 1 below case 2 below case 3 below
1080 * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
1081 * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
1083 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1084 struct vm_area_struct *prev, unsigned long addr,
1085 unsigned long end, unsigned long vm_flags,
1086 struct anon_vma *anon_vma, struct file *file,
1087 pgoff_t pgoff, struct mempolicy *policy,
1088 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1089 const char __user *anon_name)
1091 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1092 struct vm_area_struct *area, *next;
1096 * We later require that vma->vm_flags == vm_flags,
1097 * so this tests vma->vm_flags & VM_SPECIAL, too.
1099 if (vm_flags & VM_SPECIAL)
1103 next = prev->vm_next;
1107 if (next && next->vm_end == end) /* cases 6, 7, 8 */
1108 next = next->vm_next;
1111 * Can it merge with the predecessor?
1113 if (prev && prev->vm_end == addr &&
1114 mpol_equal(vma_policy(prev), policy) &&
1115 can_vma_merge_after(prev, vm_flags,
1116 anon_vma, file, pgoff,
1120 * OK, it can. Can we now merge in the successor as well?
1122 if (next && end == next->vm_start &&
1123 mpol_equal(policy, vma_policy(next)) &&
1124 can_vma_merge_before(next, vm_flags,
1129 is_mergeable_anon_vma(prev->anon_vma,
1130 next->anon_vma, NULL)) {
1132 err = vma_adjust(prev, prev->vm_start,
1133 next->vm_end, prev->vm_pgoff, NULL);
1134 } else /* cases 2, 5, 7 */
1135 err = vma_adjust(prev, prev->vm_start,
1136 end, prev->vm_pgoff, NULL);
1139 khugepaged_enter_vma_merge(prev, vm_flags);
1144 * Can this new request be merged in front of next?
1146 if (next && end == next->vm_start &&
1147 mpol_equal(policy, vma_policy(next)) &&
1148 can_vma_merge_before(next, vm_flags,
1149 anon_vma, file, pgoff+pglen,
1152 if (prev && addr < prev->vm_end) /* case 4 */
1153 err = vma_adjust(prev, prev->vm_start,
1154 addr, prev->vm_pgoff, NULL);
1155 else /* cases 3, 8 */
1156 err = vma_adjust(area, addr, next->vm_end,
1157 next->vm_pgoff - pglen, NULL);
1160 khugepaged_enter_vma_merge(area, vm_flags);
1168 * Rough compatbility check to quickly see if it's even worth looking
1169 * at sharing an anon_vma.
1171 * They need to have the same vm_file, and the flags can only differ
1172 * in things that mprotect may change.
1174 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1175 * we can merge the two vma's. For example, we refuse to merge a vma if
1176 * there is a vm_ops->close() function, because that indicates that the
1177 * driver is doing some kind of reference counting. But that doesn't
1178 * really matter for the anon_vma sharing case.
1180 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1182 return a->vm_end == b->vm_start &&
1183 mpol_equal(vma_policy(a), vma_policy(b)) &&
1184 a->vm_file == b->vm_file &&
1185 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
1186 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1190 * Do some basic sanity checking to see if we can re-use the anon_vma
1191 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1192 * the same as 'old', the other will be the new one that is trying
1193 * to share the anon_vma.
1195 * NOTE! This runs with mm_sem held for reading, so it is possible that
1196 * the anon_vma of 'old' is concurrently in the process of being set up
1197 * by another page fault trying to merge _that_. But that's ok: if it
1198 * is being set up, that automatically means that it will be a singleton
1199 * acceptable for merging, so we can do all of this optimistically. But
1200 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1202 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1203 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1204 * is to return an anon_vma that is "complex" due to having gone through
1207 * We also make sure that the two vma's are compatible (adjacent,
1208 * and with the same memory policies). That's all stable, even with just
1209 * a read lock on the mm_sem.
1211 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1213 if (anon_vma_compatible(a, b)) {
1214 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1216 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1223 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1224 * neighbouring vmas for a suitable anon_vma, before it goes off
1225 * to allocate a new anon_vma. It checks because a repetitive
1226 * sequence of mprotects and faults may otherwise lead to distinct
1227 * anon_vmas being allocated, preventing vma merge in subsequent
1230 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1232 struct anon_vma *anon_vma;
1233 struct vm_area_struct *near;
1235 near = vma->vm_next;
1239 anon_vma = reusable_anon_vma(near, vma, near);
1243 near = vma->vm_prev;
1247 anon_vma = reusable_anon_vma(near, near, vma);
1252 * There's no absolute need to look only at touching neighbours:
1253 * we could search further afield for "compatible" anon_vmas.
1254 * But it would probably just be a waste of time searching,
1255 * or lead to too many vmas hanging off the same anon_vma.
1256 * We're trying to allow mprotect remerging later on,
1257 * not trying to minimize memory used for anon_vmas.
1262 #ifdef CONFIG_PROC_FS
1263 void vm_stat_account(struct mm_struct *mm, unsigned long flags,
1264 struct file *file, long pages)
1266 const unsigned long stack_flags
1267 = VM_STACK_FLAGS & (VM_GROWSUP|VM_GROWSDOWN);
1269 mm->total_vm += pages;
1272 mm->shared_vm += pages;
1273 if ((flags & (VM_EXEC|VM_WRITE)) == VM_EXEC)
1274 mm->exec_vm += pages;
1275 } else if (flags & stack_flags)
1276 mm->stack_vm += pages;
1278 #endif /* CONFIG_PROC_FS */
1281 * If a hint addr is less than mmap_min_addr change hint to be as
1282 * low as possible but still greater than mmap_min_addr
1284 static inline unsigned long round_hint_to_min(unsigned long hint)
1287 if (((void *)hint != NULL) &&
1288 (hint < mmap_min_addr))
1289 return PAGE_ALIGN(mmap_min_addr);
1293 static inline int mlock_future_check(struct mm_struct *mm,
1294 unsigned long flags,
1297 unsigned long locked, lock_limit;
1299 /* mlock MCL_FUTURE? */
1300 if (flags & VM_LOCKED) {
1301 locked = len >> PAGE_SHIFT;
1302 locked += mm->locked_vm;
1303 lock_limit = rlimit(RLIMIT_MEMLOCK);
1304 lock_limit >>= PAGE_SHIFT;
1305 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1311 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1313 if (S_ISREG(inode->i_mode))
1314 return MAX_LFS_FILESIZE;
1316 if (S_ISBLK(inode->i_mode))
1317 return MAX_LFS_FILESIZE;
1319 /* Special "we do even unsigned file positions" case */
1320 if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1323 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1327 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1328 unsigned long pgoff, unsigned long len)
1330 u64 maxsize = file_mmap_size_max(file, inode);
1332 if (maxsize && len > maxsize)
1335 if (pgoff > maxsize >> PAGE_SHIFT)
1341 * The caller must hold down_write(¤t->mm->mmap_sem).
1343 unsigned long do_mmap(struct file *file, unsigned long addr,
1344 unsigned long len, unsigned long prot,
1345 unsigned long flags, vm_flags_t vm_flags,
1346 unsigned long pgoff, unsigned long *populate)
1348 struct mm_struct *mm = current->mm;
1355 #ifdef CONFIG_MSM_APP_SETTINGS
1356 if (use_app_setting)
1357 apply_app_setting_bit(file);
1361 * Does the application expect PROT_READ to imply PROT_EXEC?
1363 * (the exception is when the underlying filesystem is noexec
1364 * mounted, in which case we dont add PROT_EXEC.)
1366 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1367 if (!(file && path_noexec(&file->f_path)))
1370 if (!(flags & MAP_FIXED))
1371 addr = round_hint_to_min(addr);
1373 /* Careful about overflows.. */
1374 len = PAGE_ALIGN(len);
1378 /* offset overflow? */
1379 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1382 /* Too many mappings? */
1383 if (mm->map_count > sysctl_max_map_count)
1386 /* Obtain the address to map to. we verify (or select) it and ensure
1387 * that it represents a valid section of the address space.
1389 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1390 if (offset_in_page(addr))
1393 /* Do simple checking here so the lower-level routines won't have
1394 * to. we assume access permissions have been handled by the open
1395 * of the memory object, so we don't do any here.
1397 vm_flags |= calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
1398 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1400 if (flags & MAP_LOCKED)
1401 if (!can_do_mlock())
1404 if (mlock_future_check(mm, vm_flags, len))
1408 struct inode *inode = file_inode(file);
1410 if (!file_mmap_ok(file, inode, pgoff, len))
1413 switch (flags & MAP_TYPE) {
1415 if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1419 * Make sure we don't allow writing to an append-only
1422 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1426 * Make sure there are no mandatory locks on the file.
1428 if (locks_verify_locked(file))
1431 vm_flags |= VM_SHARED | VM_MAYSHARE;
1432 if (!(file->f_mode & FMODE_WRITE))
1433 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1437 if (!(file->f_mode & FMODE_READ))
1439 if (path_noexec(&file->f_path)) {
1440 if (vm_flags & VM_EXEC)
1442 vm_flags &= ~VM_MAYEXEC;
1445 if (!file->f_op->mmap)
1447 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1455 switch (flags & MAP_TYPE) {
1457 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1463 vm_flags |= VM_SHARED | VM_MAYSHARE;
1467 * Set pgoff according to addr for anon_vma.
1469 pgoff = addr >> PAGE_SHIFT;
1477 * Set 'VM_NORESERVE' if we should not account for the
1478 * memory use of this mapping.
1480 if (flags & MAP_NORESERVE) {
1481 /* We honor MAP_NORESERVE if allowed to overcommit */
1482 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1483 vm_flags |= VM_NORESERVE;
1485 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1486 if (file && is_file_hugepages(file))
1487 vm_flags |= VM_NORESERVE;
1490 addr = mmap_region(file, addr, len, vm_flags, pgoff);
1491 if (!IS_ERR_VALUE(addr) &&
1492 ((vm_flags & VM_LOCKED) ||
1493 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1498 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1499 unsigned long, prot, unsigned long, flags,
1500 unsigned long, fd, unsigned long, pgoff)
1502 struct file *file = NULL;
1503 unsigned long retval;
1505 if (!(flags & MAP_ANONYMOUS)) {
1506 audit_mmap_fd(fd, flags);
1510 if (is_file_hugepages(file))
1511 len = ALIGN(len, huge_page_size(hstate_file(file)));
1513 if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
1515 } else if (flags & MAP_HUGETLB) {
1516 struct user_struct *user = NULL;
1519 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & SHM_HUGE_MASK);
1523 len = ALIGN(len, huge_page_size(hs));
1525 * VM_NORESERVE is used because the reservations will be
1526 * taken when vm_ops->mmap() is called
1527 * A dummy user value is used because we are not locking
1528 * memory so no accounting is necessary
1530 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1532 &user, HUGETLB_ANONHUGE_INODE,
1533 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1535 return PTR_ERR(file);
1538 flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1540 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1547 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1548 struct mmap_arg_struct {
1552 unsigned long flags;
1554 unsigned long offset;
1557 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1559 struct mmap_arg_struct a;
1561 if (copy_from_user(&a, arg, sizeof(a)))
1563 if (offset_in_page(a.offset))
1566 return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1567 a.offset >> PAGE_SHIFT);
1569 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1572 * Some shared mappigns will want the pages marked read-only
1573 * to track write events. If so, we'll downgrade vm_page_prot
1574 * to the private version (using protection_map[] without the
1577 int vma_wants_writenotify(struct vm_area_struct *vma)
1579 vm_flags_t vm_flags = vma->vm_flags;
1580 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1582 /* If it was private or non-writable, the write bit is already clear */
1583 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1586 /* The backer wishes to know when pages are first written to? */
1587 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1590 /* The open routine did something to the protections that pgprot_modify
1591 * won't preserve? */
1592 if (pgprot_val(vma->vm_page_prot) !=
1593 pgprot_val(vm_pgprot_modify(vma->vm_page_prot, vm_flags)))
1596 /* Do we need to track softdirty? */
1597 if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
1600 /* Specialty mapping? */
1601 if (vm_flags & VM_PFNMAP)
1604 /* Can the mapping track the dirty pages? */
1605 return vma->vm_file && vma->vm_file->f_mapping &&
1606 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1610 * We account for memory if it's a private writeable mapping,
1611 * not hugepages and VM_NORESERVE wasn't set.
1613 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1616 * hugetlb has its own accounting separate from the core VM
1617 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1619 if (file && is_file_hugepages(file))
1622 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1625 unsigned long mmap_region(struct file *file, unsigned long addr,
1626 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff)
1628 struct mm_struct *mm = current->mm;
1629 struct vm_area_struct *vma, *prev;
1631 struct rb_node **rb_link, *rb_parent;
1632 unsigned long charged = 0;
1634 /* Check against address space limit. */
1635 if (!may_expand_vm(mm, len >> PAGE_SHIFT)) {
1636 unsigned long nr_pages;
1639 * MAP_FIXED may remove pages of mappings that intersects with
1640 * requested mapping. Account for the pages it would unmap.
1642 if (!(vm_flags & MAP_FIXED))
1645 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1647 if (!may_expand_vm(mm, (len >> PAGE_SHIFT) - nr_pages))
1651 /* Clear old maps */
1652 while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
1654 if (do_munmap(mm, addr, len))
1659 * Private writable mapping: check memory availability
1661 if (accountable_mapping(file, vm_flags)) {
1662 charged = len >> PAGE_SHIFT;
1663 if (security_vm_enough_memory_mm(mm, charged))
1665 vm_flags |= VM_ACCOUNT;
1669 * Can we just expand an old mapping?
1671 vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1672 NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1677 * Determine the object being mapped and call the appropriate
1678 * specific mapper. the address has already been validated, but
1679 * not unmapped, but the maps are removed from the list.
1681 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1688 vma->vm_start = addr;
1689 vma->vm_end = addr + len;
1690 vma->vm_flags = vm_flags;
1691 vma->vm_page_prot = vm_get_page_prot(vm_flags);
1692 vma->vm_pgoff = pgoff;
1693 INIT_LIST_HEAD(&vma->anon_vma_chain);
1696 if (vm_flags & VM_DENYWRITE) {
1697 error = deny_write_access(file);
1701 if (vm_flags & VM_SHARED) {
1702 error = mapping_map_writable(file->f_mapping);
1704 goto allow_write_and_free_vma;
1707 /* ->mmap() can change vma->vm_file, but must guarantee that
1708 * vma_link() below can deny write-access if VM_DENYWRITE is set
1709 * and map writably if VM_SHARED is set. This usually means the
1710 * new file must not have been exposed to user-space, yet.
1712 vma->vm_file = get_file(file);
1713 error = file->f_op->mmap(file, vma);
1715 goto unmap_and_free_vma;
1717 /* Can addr have changed??
1719 * Answer: Yes, several device drivers can do it in their
1720 * f_op->mmap method. -DaveM
1721 * Bug: If addr is changed, prev, rb_link, rb_parent should
1722 * be updated for vma_link()
1724 WARN_ON_ONCE(addr != vma->vm_start);
1726 addr = vma->vm_start;
1727 vm_flags = vma->vm_flags;
1728 } else if (vm_flags & VM_SHARED) {
1729 error = shmem_zero_setup(vma);
1734 vma_link(mm, vma, prev, rb_link, rb_parent);
1735 /* Once vma denies write, undo our temporary denial count */
1737 if (vm_flags & VM_SHARED)
1738 mapping_unmap_writable(file->f_mapping);
1739 if (vm_flags & VM_DENYWRITE)
1740 allow_write_access(file);
1742 file = vma->vm_file;
1744 perf_event_mmap(vma);
1746 vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1747 if (vm_flags & VM_LOCKED) {
1748 if (!((vm_flags & VM_SPECIAL) || is_vm_hugetlb_page(vma) ||
1749 vma == get_gate_vma(current->mm)))
1750 mm->locked_vm += (len >> PAGE_SHIFT);
1752 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1759 * New (or expanded) vma always get soft dirty status.
1760 * Otherwise user-space soft-dirty page tracker won't
1761 * be able to distinguish situation when vma area unmapped,
1762 * then new mapped in-place (which must be aimed as
1763 * a completely new data area).
1765 vma->vm_flags |= VM_SOFTDIRTY;
1767 vma_set_page_prot(vma);
1772 vma->vm_file = NULL;
1775 /* Undo any partial mapping done by a device driver. */
1776 unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1778 if (vm_flags & VM_SHARED)
1779 mapping_unmap_writable(file->f_mapping);
1780 allow_write_and_free_vma:
1781 if (vm_flags & VM_DENYWRITE)
1782 allow_write_access(file);
1784 kmem_cache_free(vm_area_cachep, vma);
1787 vm_unacct_memory(charged);
1791 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1794 * We implement the search by looking for an rbtree node that
1795 * immediately follows a suitable gap. That is,
1796 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1797 * - gap_end = vma->vm_start >= info->low_limit + length;
1798 * - gap_end - gap_start >= length
1801 struct mm_struct *mm = current->mm;
1802 struct vm_area_struct *vma;
1803 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1805 /* Adjust search length to account for worst case alignment overhead */
1806 length = info->length + info->align_mask;
1807 if (length < info->length)
1810 /* Adjust search limits by the desired length */
1811 if (info->high_limit < length)
1813 high_limit = info->high_limit - length;
1815 if (info->low_limit > high_limit)
1817 low_limit = info->low_limit + length;
1819 /* Check if rbtree root looks promising */
1820 if (RB_EMPTY_ROOT(&mm->mm_rb))
1822 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1823 if (vma->rb_subtree_gap < length)
1827 /* Visit left subtree if it looks promising */
1828 gap_end = vm_start_gap(vma);
1829 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1830 struct vm_area_struct *left =
1831 rb_entry(vma->vm_rb.rb_left,
1832 struct vm_area_struct, vm_rb);
1833 if (left->rb_subtree_gap >= length) {
1839 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1841 /* Check if current node has a suitable gap */
1842 if (gap_start > high_limit)
1844 if (gap_end >= low_limit &&
1845 gap_end > gap_start && gap_end - gap_start >= length)
1848 /* Visit right subtree if it looks promising */
1849 if (vma->vm_rb.rb_right) {
1850 struct vm_area_struct *right =
1851 rb_entry(vma->vm_rb.rb_right,
1852 struct vm_area_struct, vm_rb);
1853 if (right->rb_subtree_gap >= length) {
1859 /* Go back up the rbtree to find next candidate node */
1861 struct rb_node *prev = &vma->vm_rb;
1862 if (!rb_parent(prev))
1864 vma = rb_entry(rb_parent(prev),
1865 struct vm_area_struct, vm_rb);
1866 if (prev == vma->vm_rb.rb_left) {
1867 gap_start = vm_end_gap(vma->vm_prev);
1868 gap_end = vm_start_gap(vma);
1875 /* Check highest gap, which does not precede any rbtree node */
1876 gap_start = mm->highest_vm_end;
1877 gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
1878 if (gap_start > high_limit)
1882 /* We found a suitable gap. Clip it with the original low_limit. */
1883 if (gap_start < info->low_limit)
1884 gap_start = info->low_limit;
1886 /* Adjust gap address to the desired alignment */
1887 gap_start += (info->align_offset - gap_start) & info->align_mask;
1889 VM_BUG_ON(gap_start + info->length > info->high_limit);
1890 VM_BUG_ON(gap_start + info->length > gap_end);
1894 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1896 struct mm_struct *mm = current->mm;
1897 struct vm_area_struct *vma;
1898 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1900 /* Adjust search length to account for worst case alignment overhead */
1901 length = info->length + info->align_mask;
1902 if (length < info->length)
1906 * Adjust search limits by the desired length.
1907 * See implementation comment at top of unmapped_area().
1909 gap_end = info->high_limit;
1910 if (gap_end < length)
1912 high_limit = gap_end - length;
1914 if (info->low_limit > high_limit)
1916 low_limit = info->low_limit + length;
1918 /* Check highest gap, which does not precede any rbtree node */
1919 gap_start = mm->highest_vm_end;
1920 if (gap_start <= high_limit)
1923 /* Check if rbtree root looks promising */
1924 if (RB_EMPTY_ROOT(&mm->mm_rb))
1926 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1927 if (vma->rb_subtree_gap < length)
1931 /* Visit right subtree if it looks promising */
1932 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1933 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
1934 struct vm_area_struct *right =
1935 rb_entry(vma->vm_rb.rb_right,
1936 struct vm_area_struct, vm_rb);
1937 if (right->rb_subtree_gap >= length) {
1944 /* Check if current node has a suitable gap */
1945 gap_end = vm_start_gap(vma);
1946 if (gap_end < low_limit)
1948 if (gap_start <= high_limit &&
1949 gap_end > gap_start && gap_end - gap_start >= length)
1952 /* Visit left subtree if it looks promising */
1953 if (vma->vm_rb.rb_left) {
1954 struct vm_area_struct *left =
1955 rb_entry(vma->vm_rb.rb_left,
1956 struct vm_area_struct, vm_rb);
1957 if (left->rb_subtree_gap >= length) {
1963 /* Go back up the rbtree to find next candidate node */
1965 struct rb_node *prev = &vma->vm_rb;
1966 if (!rb_parent(prev))
1968 vma = rb_entry(rb_parent(prev),
1969 struct vm_area_struct, vm_rb);
1970 if (prev == vma->vm_rb.rb_right) {
1971 gap_start = vma->vm_prev ?
1972 vm_end_gap(vma->vm_prev) : 0;
1979 /* We found a suitable gap. Clip it with the original high_limit. */
1980 if (gap_end > info->high_limit)
1981 gap_end = info->high_limit;
1984 /* Compute highest gap address at the desired alignment */
1985 gap_end -= info->length;
1986 gap_end -= (gap_end - info->align_offset) & info->align_mask;
1988 VM_BUG_ON(gap_end < info->low_limit);
1989 VM_BUG_ON(gap_end < gap_start);
1993 /* Get an address range which is currently unmapped.
1994 * For shmat() with addr=0.
1996 * Ugly calling convention alert:
1997 * Return value with the low bits set means error value,
1999 * if (ret & ~PAGE_MASK)
2002 * This function "knows" that -ENOMEM has the bits set.
2004 #ifndef HAVE_ARCH_UNMAPPED_AREA
2006 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2007 unsigned long len, unsigned long pgoff, unsigned long flags)
2009 struct mm_struct *mm = current->mm;
2010 struct vm_area_struct *vma, *prev;
2011 struct vm_unmapped_area_info info;
2013 if (len > TASK_SIZE - mmap_min_addr)
2016 if (flags & MAP_FIXED)
2020 addr = PAGE_ALIGN(addr);
2021 vma = find_vma_prev(mm, addr, &prev);
2022 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
2023 (!vma || addr + len <= vm_start_gap(vma)) &&
2024 (!prev || addr >= vm_end_gap(prev)))
2030 info.low_limit = mm->mmap_base;
2031 info.high_limit = TASK_SIZE;
2032 info.align_mask = 0;
2033 return vm_unmapped_area(&info);
2038 * This mmap-allocator allocates new areas top-down from below the
2039 * stack's low limit (the base):
2041 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2043 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
2044 const unsigned long len, const unsigned long pgoff,
2045 const unsigned long flags)
2047 struct vm_area_struct *vma, *prev;
2048 struct mm_struct *mm = current->mm;
2049 unsigned long addr = addr0;
2050 struct vm_unmapped_area_info info;
2052 /* requested length too big for entire address space */
2053 if (len > TASK_SIZE - mmap_min_addr)
2056 if (flags & MAP_FIXED)
2059 /* requesting a specific address */
2061 addr = PAGE_ALIGN(addr);
2062 vma = find_vma_prev(mm, addr, &prev);
2063 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
2064 (!vma || addr + len <= vm_start_gap(vma)) &&
2065 (!prev || addr >= vm_end_gap(prev)))
2069 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2071 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2072 info.high_limit = mm->mmap_base;
2073 info.align_mask = 0;
2074 addr = vm_unmapped_area(&info);
2077 * A failed mmap() very likely causes application failure,
2078 * so fall back to the bottom-up function here. This scenario
2079 * can happen with large stack limits and large mmap()
2082 if (offset_in_page(addr)) {
2083 VM_BUG_ON(addr != -ENOMEM);
2085 info.low_limit = TASK_UNMAPPED_BASE;
2086 info.high_limit = TASK_SIZE;
2087 addr = vm_unmapped_area(&info);
2095 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2096 unsigned long pgoff, unsigned long flags)
2098 unsigned long (*get_area)(struct file *, unsigned long,
2099 unsigned long, unsigned long, unsigned long);
2101 unsigned long error = arch_mmap_check(addr, len, flags);
2105 /* Careful about overflows.. */
2106 if (len > TASK_SIZE)
2109 get_area = current->mm->get_unmapped_area;
2110 if (file && file->f_op->get_unmapped_area)
2111 get_area = file->f_op->get_unmapped_area;
2112 addr = get_area(file, addr, len, pgoff, flags);
2113 if (IS_ERR_VALUE(addr))
2116 if (addr > TASK_SIZE - len)
2118 if (offset_in_page(addr))
2121 addr = arch_rebalance_pgtables(addr, len);
2122 error = security_mmap_addr(addr);
2123 return error ? error : addr;
2126 EXPORT_SYMBOL(get_unmapped_area);
2128 /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
2129 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2131 struct rb_node *rb_node;
2132 struct vm_area_struct *vma;
2134 /* Check the cache first. */
2135 vma = vmacache_find(mm, addr);
2139 rb_node = mm->mm_rb.rb_node;
2142 struct vm_area_struct *tmp;
2144 tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2146 if (tmp->vm_end > addr) {
2148 if (tmp->vm_start <= addr)
2150 rb_node = rb_node->rb_left;
2152 rb_node = rb_node->rb_right;
2156 vmacache_update(addr, vma);
2160 EXPORT_SYMBOL(find_vma);
2163 * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2165 struct vm_area_struct *
2166 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2167 struct vm_area_struct **pprev)
2169 struct vm_area_struct *vma;
2171 vma = find_vma(mm, addr);
2173 *pprev = vma->vm_prev;
2175 struct rb_node *rb_node = mm->mm_rb.rb_node;
2178 *pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2179 rb_node = rb_node->rb_right;
2186 * Verify that the stack growth is acceptable and
2187 * update accounting. This is shared with both the
2188 * grow-up and grow-down cases.
2190 static int acct_stack_growth(struct vm_area_struct *vma,
2191 unsigned long size, unsigned long grow)
2193 struct mm_struct *mm = vma->vm_mm;
2194 struct rlimit *rlim = current->signal->rlim;
2195 unsigned long new_start;
2197 /* address space limit tests */
2198 if (!may_expand_vm(mm, grow))
2201 /* Stack limit test */
2202 if (size > READ_ONCE(rlim[RLIMIT_STACK].rlim_cur))
2205 /* mlock limit tests */
2206 if (vma->vm_flags & VM_LOCKED) {
2207 unsigned long locked;
2208 unsigned long limit;
2209 locked = mm->locked_vm + grow;
2210 limit = READ_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
2211 limit >>= PAGE_SHIFT;
2212 if (locked > limit && !capable(CAP_IPC_LOCK))
2216 /* Check to ensure the stack will not grow into a hugetlb-only region */
2217 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2219 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2223 * Overcommit.. This must be the final test, as it will
2224 * update security statistics.
2226 if (security_vm_enough_memory_mm(mm, grow))
2232 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2234 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2235 * vma is the last one with address > vma->vm_end. Have to extend vma.
2237 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2239 struct mm_struct *mm = vma->vm_mm;
2240 struct vm_area_struct *next;
2241 unsigned long gap_addr;
2244 if (!(vma->vm_flags & VM_GROWSUP))
2247 /* Guard against exceeding limits of the address space. */
2248 address &= PAGE_MASK;
2249 if (address >= (TASK_SIZE & PAGE_MASK))
2251 address += PAGE_SIZE;
2253 /* Enforce stack_guard_gap */
2254 gap_addr = address + stack_guard_gap;
2256 /* Guard against overflow */
2257 if (gap_addr < address || gap_addr > TASK_SIZE)
2258 gap_addr = TASK_SIZE;
2260 next = vma->vm_next;
2261 if (next && next->vm_start < gap_addr &&
2262 (next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2263 if (!(next->vm_flags & VM_GROWSUP))
2265 /* Check that both stack segments have the same anon_vma? */
2268 /* We must make sure the anon_vma is allocated. */
2269 if (unlikely(anon_vma_prepare(vma)))
2273 * vma->vm_start/vm_end cannot change under us because the caller
2274 * is required to hold the mmap_sem in read mode. We need the
2275 * anon_vma lock to serialize against concurrent expand_stacks.
2277 anon_vma_lock_write(vma->anon_vma);
2279 /* Somebody else might have raced and expanded it already */
2280 if (address > vma->vm_end) {
2281 unsigned long size, grow;
2283 size = address - vma->vm_start;
2284 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2287 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2288 error = acct_stack_growth(vma, size, grow);
2291 * vma_gap_update() doesn't support concurrent
2292 * updates, but we only hold a shared mmap_sem
2293 * lock here, so we need to protect against
2294 * concurrent vma expansions.
2295 * anon_vma_lock_write() doesn't help here, as
2296 * we don't guarantee that all growable vmas
2297 * in a mm share the same root anon vma.
2298 * So, we reuse mm->page_table_lock to guard
2299 * against concurrent vma expansions.
2301 spin_lock(&mm->page_table_lock);
2302 if (vma->vm_flags & VM_LOCKED)
2303 mm->locked_vm += grow;
2304 vm_stat_account(mm, vma->vm_flags,
2305 vma->vm_file, grow);
2306 anon_vma_interval_tree_pre_update_vma(vma);
2307 vma->vm_end = address;
2308 anon_vma_interval_tree_post_update_vma(vma);
2310 vma_gap_update(vma->vm_next);
2312 mm->highest_vm_end = vm_end_gap(vma);
2313 spin_unlock(&mm->page_table_lock);
2315 perf_event_mmap(vma);
2319 anon_vma_unlock_write(vma->anon_vma);
2320 khugepaged_enter_vma_merge(vma, vma->vm_flags);
2324 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2327 * vma is the first one with address < vma->vm_start. Have to extend vma.
2329 int expand_downwards(struct vm_area_struct *vma,
2330 unsigned long address)
2332 struct mm_struct *mm = vma->vm_mm;
2333 struct vm_area_struct *prev;
2334 unsigned long gap_addr;
2337 address &= PAGE_MASK;
2338 if (address < mmap_min_addr)
2341 /* Enforce stack_guard_gap */
2342 gap_addr = address - stack_guard_gap;
2343 if (gap_addr > address)
2345 prev = vma->vm_prev;
2346 if (prev && prev->vm_end > gap_addr &&
2347 (prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2348 if (!(prev->vm_flags & VM_GROWSDOWN))
2350 /* Check that both stack segments have the same anon_vma? */
2353 /* We must make sure the anon_vma is allocated. */
2354 if (unlikely(anon_vma_prepare(vma)))
2358 * vma->vm_start/vm_end cannot change under us because the caller
2359 * is required to hold the mmap_sem in read mode. We need the
2360 * anon_vma lock to serialize against concurrent expand_stacks.
2362 anon_vma_lock_write(vma->anon_vma);
2364 /* Somebody else might have raced and expanded it already */
2365 if (address < vma->vm_start) {
2366 unsigned long size, grow;
2368 size = vma->vm_end - address;
2369 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2372 if (grow <= vma->vm_pgoff) {
2373 error = acct_stack_growth(vma, size, grow);
2376 * vma_gap_update() doesn't support concurrent
2377 * updates, but we only hold a shared mmap_sem
2378 * lock here, so we need to protect against
2379 * concurrent vma expansions.
2380 * anon_vma_lock_write() doesn't help here, as
2381 * we don't guarantee that all growable vmas
2382 * in a mm share the same root anon vma.
2383 * So, we reuse mm->page_table_lock to guard
2384 * against concurrent vma expansions.
2386 spin_lock(&mm->page_table_lock);
2387 if (vma->vm_flags & VM_LOCKED)
2388 mm->locked_vm += grow;
2389 vm_stat_account(mm, vma->vm_flags,
2390 vma->vm_file, grow);
2391 anon_vma_interval_tree_pre_update_vma(vma);
2392 vma->vm_start = address;
2393 vma->vm_pgoff -= grow;
2394 anon_vma_interval_tree_post_update_vma(vma);
2395 vma_gap_update(vma);
2396 spin_unlock(&mm->page_table_lock);
2398 perf_event_mmap(vma);
2402 anon_vma_unlock_write(vma->anon_vma);
2403 khugepaged_enter_vma_merge(vma, vma->vm_flags);
2408 /* enforced gap between the expanding stack and other mappings. */
2409 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2411 static int __init cmdline_parse_stack_guard_gap(char *p)
2416 val = simple_strtoul(p, &endptr, 10);
2418 stack_guard_gap = val << PAGE_SHIFT;
2422 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2424 #ifdef CONFIG_STACK_GROWSUP
2425 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2427 return expand_upwards(vma, address);
2430 struct vm_area_struct *
2431 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2433 struct vm_area_struct *vma, *prev;
2436 vma = find_vma_prev(mm, addr, &prev);
2437 if (vma && (vma->vm_start <= addr))
2439 /* don't alter vm_end if the coredump is running */
2440 if (!prev || !mmget_still_valid(mm) || expand_stack(prev, addr))
2442 if (prev->vm_flags & VM_LOCKED)
2443 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2447 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2449 return expand_downwards(vma, address);
2452 struct vm_area_struct *
2453 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2455 struct vm_area_struct *vma;
2456 unsigned long start;
2459 vma = find_vma(mm, addr);
2462 if (vma->vm_start <= addr)
2464 if (!(vma->vm_flags & VM_GROWSDOWN))
2466 /* don't alter vm_start if the coredump is running */
2467 if (!mmget_still_valid(mm))
2469 start = vma->vm_start;
2470 if (expand_stack(vma, addr))
2472 if (vma->vm_flags & VM_LOCKED)
2473 populate_vma_page_range(vma, addr, start, NULL);
2478 EXPORT_SYMBOL_GPL(find_extend_vma);
2481 * Ok - we have the memory areas we should free on the vma list,
2482 * so release them, and do the vma updates.
2484 * Called with the mm semaphore held.
2486 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2488 unsigned long nr_accounted = 0;
2490 /* Update high watermark before we lower total_vm */
2491 update_hiwater_vm(mm);
2493 long nrpages = vma_pages(vma);
2495 if (vma->vm_flags & VM_ACCOUNT)
2496 nr_accounted += nrpages;
2497 vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
2498 vma = remove_vma(vma);
2500 vm_unacct_memory(nr_accounted);
2505 * Get rid of page table information in the indicated region.
2507 * Called with the mm semaphore held.
2509 static void unmap_region(struct mm_struct *mm,
2510 struct vm_area_struct *vma, struct vm_area_struct *prev,
2511 unsigned long start, unsigned long end)
2513 struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
2514 struct mmu_gather tlb;
2517 tlb_gather_mmu(&tlb, mm, start, end);
2518 update_hiwater_rss(mm);
2519 unmap_vmas(&tlb, vma, start, end);
2520 free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2521 next ? next->vm_start : USER_PGTABLES_CEILING);
2522 tlb_finish_mmu(&tlb, start, end);
2526 * Create a list of vma's touched by the unmap, removing them from the mm's
2527 * vma list as we go..
2530 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2531 struct vm_area_struct *prev, unsigned long end)
2533 struct vm_area_struct **insertion_point;
2534 struct vm_area_struct *tail_vma = NULL;
2536 insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2537 vma->vm_prev = NULL;
2539 vma_rb_erase(vma, &mm->mm_rb);
2543 } while (vma && vma->vm_start < end);
2544 *insertion_point = vma;
2546 vma->vm_prev = prev;
2547 vma_gap_update(vma);
2549 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2550 tail_vma->vm_next = NULL;
2552 /* Kill the cache */
2553 vmacache_invalidate(mm);
2557 * __split_vma() bypasses sysctl_max_map_count checking. We use this on the
2558 * munmap path where it doesn't make sense to fail.
2560 static int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2561 unsigned long addr, int new_below)
2563 struct vm_area_struct *new;
2566 if (is_vm_hugetlb_page(vma) && (addr &
2567 ~(huge_page_mask(hstate_vma(vma)))))
2570 new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2574 /* most fields are the same, copy all, and then fixup */
2577 INIT_LIST_HEAD(&new->anon_vma_chain);
2582 new->vm_start = addr;
2583 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2586 err = vma_dup_policy(vma, new);
2590 err = anon_vma_clone(new, vma);
2595 get_file(new->vm_file);
2597 if (new->vm_ops && new->vm_ops->open)
2598 new->vm_ops->open(new);
2601 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2602 ((addr - new->vm_start) >> PAGE_SHIFT), new);
2604 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2610 /* Clean everything up if vma_adjust failed. */
2611 if (new->vm_ops && new->vm_ops->close)
2612 new->vm_ops->close(new);
2615 unlink_anon_vmas(new);
2617 mpol_put(vma_policy(new));
2619 kmem_cache_free(vm_area_cachep, new);
2624 * Split a vma into two pieces at address 'addr', a new vma is allocated
2625 * either for the first part or the tail.
2627 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2628 unsigned long addr, int new_below)
2630 if (mm->map_count >= sysctl_max_map_count)
2633 return __split_vma(mm, vma, addr, new_below);
2636 /* Munmap is split into 2 main parts -- this part which finds
2637 * what needs doing, and the areas themselves, which do the
2638 * work. This now handles partial unmappings.
2639 * Jeremy Fitzhardinge <jeremy@goop.org>
2641 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2644 struct vm_area_struct *vma, *prev, *last;
2646 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2649 len = PAGE_ALIGN(len);
2653 /* Find the first overlapping VMA */
2654 vma = find_vma(mm, start);
2657 prev = vma->vm_prev;
2658 /* we have start < vma->vm_end */
2660 /* if it doesn't overlap, we have nothing.. */
2662 if (vma->vm_start >= end)
2666 * If we need to split any vma, do it now to save pain later.
2668 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2669 * unmapped vm_area_struct will remain in use: so lower split_vma
2670 * places tmp vma above, and higher split_vma places tmp vma below.
2672 if (start > vma->vm_start) {
2676 * Make sure that map_count on return from munmap() will
2677 * not exceed its limit; but let map_count go just above
2678 * its limit temporarily, to help free resources as expected.
2680 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2683 error = __split_vma(mm, vma, start, 0);
2689 /* Does it split the last one? */
2690 last = find_vma(mm, end);
2691 if (last && end > last->vm_start) {
2692 int error = __split_vma(mm, last, end, 1);
2696 vma = prev ? prev->vm_next : mm->mmap;
2699 * unlock any mlock()ed ranges before detaching vmas
2701 if (mm->locked_vm) {
2702 struct vm_area_struct *tmp = vma;
2703 while (tmp && tmp->vm_start < end) {
2704 if (tmp->vm_flags & VM_LOCKED) {
2705 mm->locked_vm -= vma_pages(tmp);
2706 munlock_vma_pages_all(tmp);
2713 * Remove the vma's, and unmap the actual pages
2715 detach_vmas_to_be_unmapped(mm, vma, prev, end);
2716 unmap_region(mm, vma, prev, start, end);
2718 arch_unmap(mm, vma, start, end);
2720 /* Fix up all other VM information */
2721 remove_vma_list(mm, vma);
2725 EXPORT_SYMBOL(do_munmap);
2727 int vm_munmap(unsigned long start, size_t len)
2730 struct mm_struct *mm = current->mm;
2732 down_write(&mm->mmap_sem);
2733 ret = do_munmap(mm, start, len);
2734 up_write(&mm->mmap_sem);
2737 EXPORT_SYMBOL(vm_munmap);
2739 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2741 profile_munmap(addr);
2742 return vm_munmap(addr, len);
2747 * Emulation of deprecated remap_file_pages() syscall.
2749 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2750 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2753 struct mm_struct *mm = current->mm;
2754 struct vm_area_struct *vma;
2755 unsigned long populate = 0;
2756 unsigned long ret = -EINVAL;
2759 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.txt.\n",
2760 current->comm, current->pid);
2764 start = start & PAGE_MASK;
2765 size = size & PAGE_MASK;
2767 if (start + size <= start)
2770 /* Does pgoff wrap? */
2771 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2774 down_write(&mm->mmap_sem);
2775 vma = find_vma(mm, start);
2777 if (!vma || !(vma->vm_flags & VM_SHARED))
2780 if (start < vma->vm_start)
2783 if (start + size > vma->vm_end) {
2784 struct vm_area_struct *next;
2786 for (next = vma->vm_next; next; next = next->vm_next) {
2787 /* hole between vmas ? */
2788 if (next->vm_start != next->vm_prev->vm_end)
2791 if (next->vm_file != vma->vm_file)
2794 if (next->vm_flags != vma->vm_flags)
2797 if (start + size <= next->vm_end)
2805 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2806 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2807 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2809 flags &= MAP_NONBLOCK;
2810 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2811 if (vma->vm_flags & VM_LOCKED) {
2812 struct vm_area_struct *tmp;
2813 flags |= MAP_LOCKED;
2815 /* drop PG_Mlocked flag for over-mapped range */
2816 for (tmp = vma; tmp->vm_start >= start + size;
2817 tmp = tmp->vm_next) {
2818 munlock_vma_pages_range(tmp,
2819 max(tmp->vm_start, start),
2820 min(tmp->vm_end, start + size));
2824 file = get_file(vma->vm_file);
2825 ret = do_mmap_pgoff(vma->vm_file, start, size,
2826 prot, flags, pgoff, &populate);
2829 up_write(&mm->mmap_sem);
2831 mm_populate(ret, populate);
2832 if (!IS_ERR_VALUE(ret))
2837 static inline void verify_mm_writelocked(struct mm_struct *mm)
2839 #ifdef CONFIG_DEBUG_VM
2840 if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2842 up_read(&mm->mmap_sem);
2848 * this is really a simplified "do_mmap". it only handles
2849 * anonymous maps. eventually we may be able to do some
2850 * brk-specific accounting here.
2852 static unsigned long do_brk(unsigned long addr, unsigned long len)
2854 struct mm_struct *mm = current->mm;
2855 struct vm_area_struct *vma, *prev;
2856 unsigned long flags;
2857 struct rb_node **rb_link, *rb_parent;
2858 pgoff_t pgoff = addr >> PAGE_SHIFT;
2861 flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2863 error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2864 if (offset_in_page(error))
2867 error = mlock_future_check(mm, mm->def_flags, len);
2872 * mm->mmap_sem is required to protect against another thread
2873 * changing the mappings in case we sleep.
2875 verify_mm_writelocked(mm);
2878 * Clear old maps. this also does some error checking for us
2880 while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
2882 if (do_munmap(mm, addr, len))
2886 /* Check against address space limits *after* clearing old maps... */
2887 if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2890 if (mm->map_count > sysctl_max_map_count)
2893 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2896 /* Can we just expand an old private anonymous mapping? */
2897 vma = vma_merge(mm, prev, addr, addr + len, flags,
2898 NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
2903 * create a vma struct for an anonymous mapping
2905 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2907 vm_unacct_memory(len >> PAGE_SHIFT);
2911 INIT_LIST_HEAD(&vma->anon_vma_chain);
2913 vma->vm_start = addr;
2914 vma->vm_end = addr + len;
2915 vma->vm_pgoff = pgoff;
2916 vma->vm_flags = flags;
2917 vma->vm_page_prot = vm_get_page_prot(flags);
2918 vma_link(mm, vma, prev, rb_link, rb_parent);
2920 perf_event_mmap(vma);
2921 mm->total_vm += len >> PAGE_SHIFT;
2922 if (flags & VM_LOCKED)
2923 mm->locked_vm += (len >> PAGE_SHIFT);
2924 vma->vm_flags |= VM_SOFTDIRTY;
2928 unsigned long vm_brk(unsigned long addr, unsigned long request)
2930 struct mm_struct *mm = current->mm;
2935 len = PAGE_ALIGN(request);
2941 down_write(&mm->mmap_sem);
2942 ret = do_brk(addr, len);
2943 populate = ((mm->def_flags & VM_LOCKED) != 0);
2944 up_write(&mm->mmap_sem);
2946 mm_populate(addr, len);
2949 EXPORT_SYMBOL(vm_brk);
2951 /* Release all mmaps. */
2952 void exit_mmap(struct mm_struct *mm)
2954 struct mmu_gather tlb;
2955 struct vm_area_struct *vma;
2956 unsigned long nr_accounted = 0;
2958 /* mm's last user has gone, and its about to be pulled down */
2959 mmu_notifier_release(mm);
2961 if (mm->locked_vm) {
2964 if (vma->vm_flags & VM_LOCKED)
2965 munlock_vma_pages_all(vma);
2973 if (!vma) /* Can happen if dup_mmap() received an OOM */
2978 tlb_gather_mmu(&tlb, mm, 0, -1);
2979 /* update_hiwater_rss(mm) here? but nobody should be looking */
2980 /* Use -1 here to ensure all VMAs in the mm are unmapped */
2981 unmap_vmas(&tlb, vma, 0, -1);
2983 free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
2984 tlb_finish_mmu(&tlb, 0, -1);
2987 * Walk the list again, actually closing and freeing it,
2988 * with preemption enabled, without holding any MM locks.
2991 if (vma->vm_flags & VM_ACCOUNT)
2992 nr_accounted += vma_pages(vma);
2993 vma = remove_vma(vma);
2995 vm_unacct_memory(nr_accounted);
2998 /* Insert vm structure into process list sorted by address
2999 * and into the inode's i_mmap tree. If vm_file is non-NULL
3000 * then i_mmap_rwsem is taken here.
3002 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3004 struct vm_area_struct *prev;
3005 struct rb_node **rb_link, *rb_parent;
3007 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3008 &prev, &rb_link, &rb_parent))
3010 if ((vma->vm_flags & VM_ACCOUNT) &&
3011 security_vm_enough_memory_mm(mm, vma_pages(vma)))
3015 * The vm_pgoff of a purely anonymous vma should be irrelevant
3016 * until its first write fault, when page's anon_vma and index
3017 * are set. But now set the vm_pgoff it will almost certainly
3018 * end up with (unless mremap moves it elsewhere before that
3019 * first wfault), so /proc/pid/maps tells a consistent story.
3021 * By setting it to reflect the virtual start address of the
3022 * vma, merges and splits can happen in a seamless way, just
3023 * using the existing file pgoff checks and manipulations.
3024 * Similarly in do_mmap_pgoff and in do_brk.
3026 if (vma_is_anonymous(vma)) {
3027 BUG_ON(vma->anon_vma);
3028 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3031 vma_link(mm, vma, prev, rb_link, rb_parent);
3036 * Copy the vma structure to a new location in the same mm,
3037 * prior to moving page table entries, to effect an mremap move.
3039 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3040 unsigned long addr, unsigned long len, pgoff_t pgoff,
3041 bool *need_rmap_locks)
3043 struct vm_area_struct *vma = *vmap;
3044 unsigned long vma_start = vma->vm_start;
3045 struct mm_struct *mm = vma->vm_mm;
3046 struct vm_area_struct *new_vma, *prev;
3047 struct rb_node **rb_link, *rb_parent;
3048 bool faulted_in_anon_vma = true;
3051 * If anonymous vma has not yet been faulted, update new pgoff
3052 * to match new location, to increase its chance of merging.
3054 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3055 pgoff = addr >> PAGE_SHIFT;
3056 faulted_in_anon_vma = false;
3059 if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3060 return NULL; /* should never get here */
3061 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3062 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3063 vma->vm_userfaultfd_ctx, vma_get_anon_name(vma));
3066 * Source vma may have been merged into new_vma
3068 if (unlikely(vma_start >= new_vma->vm_start &&
3069 vma_start < new_vma->vm_end)) {
3071 * The only way we can get a vma_merge with
3072 * self during an mremap is if the vma hasn't
3073 * been faulted in yet and we were allowed to
3074 * reset the dst vma->vm_pgoff to the
3075 * destination address of the mremap to allow
3076 * the merge to happen. mremap must change the
3077 * vm_pgoff linearity between src and dst vmas
3078 * (in turn preventing a vma_merge) to be
3079 * safe. It is only safe to keep the vm_pgoff
3080 * linear if there are no pages mapped yet.
3082 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3083 *vmap = vma = new_vma;
3085 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3087 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
3091 new_vma->vm_start = addr;
3092 new_vma->vm_end = addr + len;
3093 new_vma->vm_pgoff = pgoff;
3094 if (vma_dup_policy(vma, new_vma))
3096 INIT_LIST_HEAD(&new_vma->anon_vma_chain);
3097 if (anon_vma_clone(new_vma, vma))
3098 goto out_free_mempol;
3099 if (new_vma->vm_file)
3100 get_file(new_vma->vm_file);
3101 if (new_vma->vm_ops && new_vma->vm_ops->open)
3102 new_vma->vm_ops->open(new_vma);
3103 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3104 *need_rmap_locks = false;
3109 mpol_put(vma_policy(new_vma));
3111 kmem_cache_free(vm_area_cachep, new_vma);
3117 * Return true if the calling process may expand its vm space by the passed
3120 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
3122 unsigned long cur = mm->total_vm; /* pages */
3125 lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
3127 if (cur + npages > lim)
3132 static int special_mapping_fault(struct vm_area_struct *vma,
3133 struct vm_fault *vmf);
3136 * Having a close hook prevents vma merging regardless of flags.
3138 static void special_mapping_close(struct vm_area_struct *vma)
3142 static const char *special_mapping_name(struct vm_area_struct *vma)
3144 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3147 static const struct vm_operations_struct special_mapping_vmops = {
3148 .close = special_mapping_close,
3149 .fault = special_mapping_fault,
3150 .name = special_mapping_name,
3153 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3154 .close = special_mapping_close,
3155 .fault = special_mapping_fault,
3158 static int special_mapping_fault(struct vm_area_struct *vma,
3159 struct vm_fault *vmf)
3162 struct page **pages;
3164 if (vma->vm_ops == &legacy_special_mapping_vmops)
3165 pages = vma->vm_private_data;
3167 pages = ((struct vm_special_mapping *)vma->vm_private_data)->
3170 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3174 struct page *page = *pages;
3180 return VM_FAULT_SIGBUS;
3183 static struct vm_area_struct *__install_special_mapping(
3184 struct mm_struct *mm,
3185 unsigned long addr, unsigned long len,
3186 unsigned long vm_flags, void *priv,
3187 const struct vm_operations_struct *ops)
3190 struct vm_area_struct *vma;
3192 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
3193 if (unlikely(vma == NULL))
3194 return ERR_PTR(-ENOMEM);
3196 INIT_LIST_HEAD(&vma->anon_vma_chain);
3198 vma->vm_start = addr;
3199 vma->vm_end = addr + len;
3201 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3202 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3205 vma->vm_private_data = priv;
3207 ret = insert_vm_struct(mm, vma);
3211 mm->total_vm += len >> PAGE_SHIFT;
3213 perf_event_mmap(vma);
3218 kmem_cache_free(vm_area_cachep, vma);
3219 return ERR_PTR(ret);
3223 * Called with mm->mmap_sem held for writing.
3224 * Insert a new vma covering the given region, with the given flags.
3225 * Its pages are supplied by the given array of struct page *.
3226 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3227 * The region past the last page supplied will always produce SIGBUS.
3228 * The array pointer and the pages it points to are assumed to stay alive
3229 * for as long as this mapping might exist.
3231 struct vm_area_struct *_install_special_mapping(
3232 struct mm_struct *mm,
3233 unsigned long addr, unsigned long len,
3234 unsigned long vm_flags, const struct vm_special_mapping *spec)
3236 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3237 &special_mapping_vmops);
3240 int install_special_mapping(struct mm_struct *mm,
3241 unsigned long addr, unsigned long len,
3242 unsigned long vm_flags, struct page **pages)
3244 struct vm_area_struct *vma = __install_special_mapping(
3245 mm, addr, len, vm_flags, (void *)pages,
3246 &legacy_special_mapping_vmops);
3248 return PTR_ERR_OR_ZERO(vma);
3251 static DEFINE_MUTEX(mm_all_locks_mutex);
3253 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3255 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3257 * The LSB of head.next can't change from under us
3258 * because we hold the mm_all_locks_mutex.
3260 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
3262 * We can safely modify head.next after taking the
3263 * anon_vma->root->rwsem. If some other vma in this mm shares
3264 * the same anon_vma we won't take it again.
3266 * No need of atomic instructions here, head.next
3267 * can't change from under us thanks to the
3268 * anon_vma->root->rwsem.
3270 if (__test_and_set_bit(0, (unsigned long *)
3271 &anon_vma->root->rb_root.rb_node))
3276 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3278 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3280 * AS_MM_ALL_LOCKS can't change from under us because
3281 * we hold the mm_all_locks_mutex.
3283 * Operations on ->flags have to be atomic because
3284 * even if AS_MM_ALL_LOCKS is stable thanks to the
3285 * mm_all_locks_mutex, there may be other cpus
3286 * changing other bitflags in parallel to us.
3288 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3290 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);
3295 * This operation locks against the VM for all pte/vma/mm related
3296 * operations that could ever happen on a certain mm. This includes
3297 * vmtruncate, try_to_unmap, and all page faults.
3299 * The caller must take the mmap_sem in write mode before calling
3300 * mm_take_all_locks(). The caller isn't allowed to release the
3301 * mmap_sem until mm_drop_all_locks() returns.
3303 * mmap_sem in write mode is required in order to block all operations
3304 * that could modify pagetables and free pages without need of
3305 * altering the vma layout. It's also needed in write mode to avoid new
3306 * anon_vmas to be associated with existing vmas.
3308 * A single task can't take more than one mm_take_all_locks() in a row
3309 * or it would deadlock.
3311 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3312 * mapping->flags avoid to take the same lock twice, if more than one
3313 * vma in this mm is backed by the same anon_vma or address_space.
3315 * We can take all the locks in random order because the VM code
3316 * taking i_mmap_rwsem or anon_vma->rwsem outside the mmap_sem never
3317 * takes more than one of them in a row. Secondly we're protected
3318 * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
3320 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3321 * that may have to take thousand of locks.
3323 * mm_take_all_locks() can fail if it's interrupted by signals.
3325 int mm_take_all_locks(struct mm_struct *mm)
3327 struct vm_area_struct *vma;
3328 struct anon_vma_chain *avc;
3330 BUG_ON(down_read_trylock(&mm->mmap_sem));
3332 mutex_lock(&mm_all_locks_mutex);
3334 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3335 if (signal_pending(current))
3337 if (vma->vm_file && vma->vm_file->f_mapping)
3338 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3341 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3342 if (signal_pending(current))
3345 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3346 vm_lock_anon_vma(mm, avc->anon_vma);
3352 mm_drop_all_locks(mm);
3356 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3358 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3360 * The LSB of head.next can't change to 0 from under
3361 * us because we hold the mm_all_locks_mutex.
3363 * We must however clear the bitflag before unlocking
3364 * the vma so the users using the anon_vma->rb_root will
3365 * never see our bitflag.
3367 * No need of atomic instructions here, head.next
3368 * can't change from under us until we release the
3369 * anon_vma->root->rwsem.
3371 if (!__test_and_clear_bit(0, (unsigned long *)
3372 &anon_vma->root->rb_root.rb_node))
3374 anon_vma_unlock_write(anon_vma);
3378 static void vm_unlock_mapping(struct address_space *mapping)
3380 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3382 * AS_MM_ALL_LOCKS can't change to 0 from under us
3383 * because we hold the mm_all_locks_mutex.
3385 i_mmap_unlock_write(mapping);
3386 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3393 * The mmap_sem cannot be released by the caller until
3394 * mm_drop_all_locks() returns.
3396 void mm_drop_all_locks(struct mm_struct *mm)
3398 struct vm_area_struct *vma;
3399 struct anon_vma_chain *avc;
3401 BUG_ON(down_read_trylock(&mm->mmap_sem));
3402 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3404 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3406 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3407 vm_unlock_anon_vma(avc->anon_vma);
3408 if (vma->vm_file && vma->vm_file->f_mapping)
3409 vm_unlock_mapping(vma->vm_file->f_mapping);
3412 mutex_unlock(&mm_all_locks_mutex);
3416 * initialise the VMA slab
3418 void __init mmap_init(void)
3422 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3427 * Initialise sysctl_user_reserve_kbytes.
3429 * This is intended to prevent a user from starting a single memory hogging
3430 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3433 * The default value is min(3% of free memory, 128MB)
3434 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3436 static int init_user_reserve(void)
3438 unsigned long free_kbytes;
3440 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3442 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3445 subsys_initcall(init_user_reserve);
3448 * Initialise sysctl_admin_reserve_kbytes.
3450 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3451 * to log in and kill a memory hogging process.
3453 * Systems with more than 256MB will reserve 8MB, enough to recover
3454 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3455 * only reserve 3% of free pages by default.
3457 static int init_admin_reserve(void)
3459 unsigned long free_kbytes;
3461 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3463 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3466 subsys_initcall(init_admin_reserve);
3469 * Reinititalise user and admin reserves if memory is added or removed.
3471 * The default user reserve max is 128MB, and the default max for the
3472 * admin reserve is 8MB. These are usually, but not always, enough to
3473 * enable recovery from a memory hogging process using login/sshd, a shell,
3474 * and tools like top. It may make sense to increase or even disable the
3475 * reserve depending on the existence of swap or variations in the recovery
3476 * tools. So, the admin may have changed them.
3478 * If memory is added and the reserves have been eliminated or increased above
3479 * the default max, then we'll trust the admin.
3481 * If memory is removed and there isn't enough free memory, then we
3482 * need to reset the reserves.
3484 * Otherwise keep the reserve set by the admin.
3486 static int reserve_mem_notifier(struct notifier_block *nb,
3487 unsigned long action, void *data)
3489 unsigned long tmp, free_kbytes;
3493 /* Default max is 128MB. Leave alone if modified by operator. */
3494 tmp = sysctl_user_reserve_kbytes;
3495 if (0 < tmp && tmp < (1UL << 17))
3496 init_user_reserve();
3498 /* Default max is 8MB. Leave alone if modified by operator. */
3499 tmp = sysctl_admin_reserve_kbytes;
3500 if (0 < tmp && tmp < (1UL << 13))
3501 init_admin_reserve();
3505 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3507 if (sysctl_user_reserve_kbytes > free_kbytes) {
3508 init_user_reserve();
3509 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3510 sysctl_user_reserve_kbytes);
3513 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3514 init_admin_reserve();
3515 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3516 sysctl_admin_reserve_kbytes);
3525 static struct notifier_block reserve_mem_nb = {
3526 .notifier_call = reserve_mem_notifier,
3529 static int __meminit init_reserve_notifier(void)
3531 if (register_hotmemory_notifier(&reserve_mem_nb))
3532 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3536 subsys_initcall(init_reserve_notifier);