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/shmem_fs.h>
29 #include <linux/profile.h>
30 #include <linux/export.h>
31 #include <linux/mount.h>
32 #include <linux/mempolicy.h>
33 #include <linux/rmap.h>
34 #include <linux/mmu_notifier.h>
35 #include <linux/mmdebug.h>
36 #include <linux/perf_event.h>
37 #include <linux/audit.h>
38 #include <linux/khugepaged.h>
39 #include <linux/uprobes.h>
40 #include <linux/rbtree_augmented.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>
48 #include <asm/uaccess.h>
49 #include <asm/cacheflush.h>
51 #include <asm/mmu_context.h>
55 #ifndef arch_mmap_check
56 #define arch_mmap_check(addr, len, flags) (0)
59 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
60 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
61 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
62 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
64 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
65 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
66 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
67 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
70 static bool ignore_rlimit_data;
71 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
73 static void unmap_region(struct mm_struct *mm,
74 struct vm_area_struct *vma, struct vm_area_struct *prev,
75 unsigned long start, unsigned long end);
77 /* description of effects of mapping type and prot in current implementation.
78 * this is due to the limited x86 page protection hardware. The expected
79 * behavior is in parens:
82 * PROT_NONE PROT_READ PROT_WRITE PROT_EXEC
83 * MAP_SHARED r: (no) no r: (yes) yes r: (no) yes r: (no) yes
84 * w: (no) no w: (no) no w: (yes) yes w: (no) no
85 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
87 * MAP_PRIVATE r: (no) no r: (yes) yes r: (no) yes r: (no) yes
88 * w: (no) no w: (no) no w: (copy) copy w: (no) no
89 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
91 * On arm64, PROT_EXEC has the following behaviour for both MAP_SHARED and
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;
119 pgprot_t vm_page_prot;
121 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
122 if (vma_wants_writenotify(vma, vm_page_prot)) {
123 vm_flags &= ~VM_SHARED;
124 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
126 /* remove_protection_ptes reads vma->vm_page_prot without mmap_sem */
127 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
131 * Requires inode->i_mapping->i_mmap_rwsem
133 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
134 struct file *file, struct address_space *mapping)
136 if (vma->vm_flags & VM_DENYWRITE)
137 atomic_inc(&file_inode(file)->i_writecount);
138 if (vma->vm_flags & VM_SHARED)
139 mapping_unmap_writable(mapping);
141 flush_dcache_mmap_lock(mapping);
142 vma_interval_tree_remove(vma, &mapping->i_mmap);
143 flush_dcache_mmap_unlock(mapping);
147 * Unlink a file-based vm structure from its interval tree, to hide
148 * vma from rmap and vmtruncate before freeing its page tables.
150 void unlink_file_vma(struct vm_area_struct *vma)
152 struct file *file = vma->vm_file;
155 struct address_space *mapping = file->f_mapping;
156 i_mmap_lock_write(mapping);
157 __remove_shared_vm_struct(vma, file, mapping);
158 i_mmap_unlock_write(mapping);
163 * Close a vm structure and free it, returning the next.
165 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
167 struct vm_area_struct *next = vma->vm_next;
170 if (vma->vm_ops && vma->vm_ops->close)
171 vma->vm_ops->close(vma);
174 mpol_put(vma_policy(vma));
175 kmem_cache_free(vm_area_cachep, vma);
179 static int do_brk(unsigned long addr, unsigned long len);
181 SYSCALL_DEFINE1(brk, unsigned long, brk)
183 unsigned long retval;
184 unsigned long newbrk, oldbrk;
185 struct mm_struct *mm = current->mm;
186 unsigned long min_brk;
189 if (down_write_killable(&mm->mmap_sem))
192 #ifdef CONFIG_COMPAT_BRK
194 * CONFIG_COMPAT_BRK can still be overridden by setting
195 * randomize_va_space to 2, which will still cause mm->start_brk
196 * to be arbitrarily shifted
198 if (current->brk_randomized)
199 min_brk = mm->start_brk;
201 min_brk = mm->end_data;
203 min_brk = mm->start_brk;
209 * Check against rlimit here. If this check is done later after the test
210 * of oldbrk with newbrk then it can escape the test and let the data
211 * segment grow beyond its set limit the in case where the limit is
212 * not page aligned -Ram Gupta
214 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
215 mm->end_data, mm->start_data))
218 newbrk = PAGE_ALIGN(brk);
219 oldbrk = PAGE_ALIGN(mm->brk);
220 if (oldbrk == newbrk)
223 /* Always allow shrinking brk. */
224 if (brk <= mm->brk) {
225 if (!do_munmap(mm, newbrk, oldbrk-newbrk))
230 /* Check against existing mmap mappings. */
231 if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE))
234 /* Ok, looks good - let it rip. */
235 if (do_brk(oldbrk, newbrk-oldbrk) < 0)
240 populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
241 up_write(&mm->mmap_sem);
243 mm_populate(oldbrk, newbrk - oldbrk);
248 up_write(&mm->mmap_sem);
252 static long vma_compute_subtree_gap(struct vm_area_struct *vma)
254 unsigned long max, subtree_gap;
257 max -= vma->vm_prev->vm_end;
258 if (vma->vm_rb.rb_left) {
259 subtree_gap = rb_entry(vma->vm_rb.rb_left,
260 struct vm_area_struct, vm_rb)->rb_subtree_gap;
261 if (subtree_gap > max)
264 if (vma->vm_rb.rb_right) {
265 subtree_gap = rb_entry(vma->vm_rb.rb_right,
266 struct vm_area_struct, vm_rb)->rb_subtree_gap;
267 if (subtree_gap > max)
273 #ifdef CONFIG_DEBUG_VM_RB
274 static int browse_rb(struct mm_struct *mm)
276 struct rb_root *root = &mm->mm_rb;
277 int i = 0, j, bug = 0;
278 struct rb_node *nd, *pn = NULL;
279 unsigned long prev = 0, pend = 0;
281 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
282 struct vm_area_struct *vma;
283 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
284 if (vma->vm_start < prev) {
285 pr_emerg("vm_start %lx < prev %lx\n",
286 vma->vm_start, prev);
289 if (vma->vm_start < pend) {
290 pr_emerg("vm_start %lx < pend %lx\n",
291 vma->vm_start, pend);
294 if (vma->vm_start > vma->vm_end) {
295 pr_emerg("vm_start %lx > vm_end %lx\n",
296 vma->vm_start, vma->vm_end);
299 spin_lock(&mm->page_table_lock);
300 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
301 pr_emerg("free gap %lx, correct %lx\n",
303 vma_compute_subtree_gap(vma));
306 spin_unlock(&mm->page_table_lock);
309 prev = vma->vm_start;
313 for (nd = pn; nd; nd = rb_prev(nd))
316 pr_emerg("backwards %d, forwards %d\n", j, i);
322 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
326 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
327 struct vm_area_struct *vma;
328 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
329 VM_BUG_ON_VMA(vma != ignore &&
330 vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
335 static void validate_mm(struct mm_struct *mm)
339 unsigned long highest_address = 0;
340 struct vm_area_struct *vma = mm->mmap;
343 struct anon_vma *anon_vma = vma->anon_vma;
344 struct anon_vma_chain *avc;
347 anon_vma_lock_read(anon_vma);
348 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
349 anon_vma_interval_tree_verify(avc);
350 anon_vma_unlock_read(anon_vma);
353 highest_address = vma->vm_end;
357 if (i != mm->map_count) {
358 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
361 if (highest_address != mm->highest_vm_end) {
362 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
363 mm->highest_vm_end, highest_address);
367 if (i != mm->map_count) {
369 pr_emerg("map_count %d rb %d\n", mm->map_count, i);
372 VM_BUG_ON_MM(bug, mm);
375 #define validate_mm_rb(root, ignore) do { } while (0)
376 #define validate_mm(mm) do { } while (0)
379 RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,
380 unsigned long, rb_subtree_gap, vma_compute_subtree_gap)
383 * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
384 * vma->vm_prev->vm_end values changed, without modifying the vma's position
387 static void vma_gap_update(struct vm_area_struct *vma)
390 * As it turns out, RB_DECLARE_CALLBACKS() already created a callback
391 * function that does exacltly what we want.
393 vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
396 static inline void vma_rb_insert(struct vm_area_struct *vma,
397 struct rb_root *root)
399 /* All rb_subtree_gap values must be consistent prior to insertion */
400 validate_mm_rb(root, NULL);
402 rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
405 static void vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
408 * All rb_subtree_gap values must be consistent prior to erase,
409 * with the possible exception of the vma being erased.
411 validate_mm_rb(root, vma);
414 * Note rb_erase_augmented is a fairly large inline function,
415 * so make sure we instantiate it only once with our desired
416 * augmented rbtree callbacks.
418 rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
422 * vma has some anon_vma assigned, and is already inserted on that
423 * anon_vma's interval trees.
425 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
426 * vma must be removed from the anon_vma's interval trees using
427 * anon_vma_interval_tree_pre_update_vma().
429 * After the update, the vma will be reinserted using
430 * anon_vma_interval_tree_post_update_vma().
432 * The entire update must be protected by exclusive mmap_sem and by
433 * the root anon_vma's mutex.
436 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
438 struct anon_vma_chain *avc;
440 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
441 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
445 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
447 struct anon_vma_chain *avc;
449 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
450 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
453 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
454 unsigned long end, struct vm_area_struct **pprev,
455 struct rb_node ***rb_link, struct rb_node **rb_parent)
457 struct rb_node **__rb_link, *__rb_parent, *rb_prev;
459 __rb_link = &mm->mm_rb.rb_node;
460 rb_prev = __rb_parent = NULL;
463 struct vm_area_struct *vma_tmp;
465 __rb_parent = *__rb_link;
466 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
468 if (vma_tmp->vm_end > addr) {
469 /* Fail if an existing vma overlaps the area */
470 if (vma_tmp->vm_start < end)
472 __rb_link = &__rb_parent->rb_left;
474 rb_prev = __rb_parent;
475 __rb_link = &__rb_parent->rb_right;
481 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
482 *rb_link = __rb_link;
483 *rb_parent = __rb_parent;
487 static unsigned long count_vma_pages_range(struct mm_struct *mm,
488 unsigned long addr, unsigned long end)
490 unsigned long nr_pages = 0;
491 struct vm_area_struct *vma;
493 /* Find first overlaping mapping */
494 vma = find_vma_intersection(mm, addr, end);
498 nr_pages = (min(end, vma->vm_end) -
499 max(addr, vma->vm_start)) >> PAGE_SHIFT;
501 /* Iterate over the rest of the overlaps */
502 for (vma = vma->vm_next; vma; vma = vma->vm_next) {
503 unsigned long overlap_len;
505 if (vma->vm_start > end)
508 overlap_len = min(end, vma->vm_end) - vma->vm_start;
509 nr_pages += overlap_len >> PAGE_SHIFT;
515 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
516 struct rb_node **rb_link, struct rb_node *rb_parent)
518 /* Update tracking information for the gap following the new vma. */
520 vma_gap_update(vma->vm_next);
522 mm->highest_vm_end = vma->vm_end;
525 * vma->vm_prev wasn't known when we followed the rbtree to find the
526 * correct insertion point for that vma. As a result, we could not
527 * update the vma vm_rb parents rb_subtree_gap values on the way down.
528 * So, we first insert the vma with a zero rb_subtree_gap value
529 * (to be consistent with what we did on the way down), and then
530 * immediately update the gap to the correct value. Finally we
531 * rebalance the rbtree after all augmented values have been set.
533 rb_link_node(&vma->vm_rb, rb_parent, rb_link);
534 vma->rb_subtree_gap = 0;
536 vma_rb_insert(vma, &mm->mm_rb);
539 static void __vma_link_file(struct vm_area_struct *vma)
545 struct address_space *mapping = file->f_mapping;
547 if (vma->vm_flags & VM_DENYWRITE)
548 atomic_dec(&file_inode(file)->i_writecount);
549 if (vma->vm_flags & VM_SHARED)
550 atomic_inc(&mapping->i_mmap_writable);
552 flush_dcache_mmap_lock(mapping);
553 vma_interval_tree_insert(vma, &mapping->i_mmap);
554 flush_dcache_mmap_unlock(mapping);
559 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
560 struct vm_area_struct *prev, struct rb_node **rb_link,
561 struct rb_node *rb_parent)
563 __vma_link_list(mm, vma, prev, rb_parent);
564 __vma_link_rb(mm, vma, rb_link, rb_parent);
567 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
568 struct vm_area_struct *prev, struct rb_node **rb_link,
569 struct rb_node *rb_parent)
571 struct address_space *mapping = NULL;
574 mapping = vma->vm_file->f_mapping;
575 i_mmap_lock_write(mapping);
578 __vma_link(mm, vma, prev, rb_link, rb_parent);
579 __vma_link_file(vma);
582 i_mmap_unlock_write(mapping);
589 * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
590 * mm's list and rbtree. It has already been inserted into the interval tree.
592 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
594 struct vm_area_struct *prev;
595 struct rb_node **rb_link, *rb_parent;
597 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
598 &prev, &rb_link, &rb_parent))
600 __vma_link(mm, vma, prev, rb_link, rb_parent);
605 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
606 struct vm_area_struct *prev)
608 struct vm_area_struct *next;
610 vma_rb_erase(vma, &mm->mm_rb);
611 prev->vm_next = next = vma->vm_next;
613 next->vm_prev = prev;
616 vmacache_invalidate(mm);
620 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
621 * is already present in an i_mmap tree without adjusting the tree.
622 * The following helper function should be used when such adjustments
623 * are necessary. The "insert" vma (if any) is to be inserted
624 * before we drop the necessary locks.
626 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
627 unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
629 struct mm_struct *mm = vma->vm_mm;
630 struct vm_area_struct *next = vma->vm_next;
631 struct address_space *mapping = NULL;
632 struct rb_root *root = NULL;
633 struct anon_vma *anon_vma = NULL;
634 struct file *file = vma->vm_file;
635 bool start_changed = false, end_changed = false;
636 long adjust_next = 0;
639 if (next && !insert) {
640 struct vm_area_struct *exporter = NULL, *importer = NULL;
642 if (end >= next->vm_end) {
644 * vma expands, overlapping all the next, and
645 * perhaps the one after too (mprotect case 6).
647 remove_next = 1 + (end > next->vm_end);
653 * If next doesn't have anon_vma, import from vma after
654 * next, if the vma overlaps with it.
656 if (remove_next == 2 && next && !next->anon_vma)
657 exporter = next->vm_next;
659 } else if (end > next->vm_start) {
661 * vma expands, overlapping part of the next:
662 * mprotect case 5 shifting the boundary up.
664 adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
667 } else if (end < vma->vm_end) {
669 * vma shrinks, and !insert tells it's not
670 * split_vma inserting another: so it must be
671 * mprotect case 4 shifting the boundary down.
673 adjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);
679 * Easily overlooked: when mprotect shifts the boundary,
680 * make sure the expanding vma has anon_vma set if the
681 * shrinking vma had, to cover any anon pages imported.
683 if (exporter && exporter->anon_vma && !importer->anon_vma) {
686 importer->anon_vma = exporter->anon_vma;
687 error = anon_vma_clone(importer, exporter);
693 vma_adjust_trans_huge(vma, start, end, adjust_next);
696 mapping = file->f_mapping;
697 root = &mapping->i_mmap;
698 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
701 uprobe_munmap(next, next->vm_start, next->vm_end);
703 i_mmap_lock_write(mapping);
706 * Put into interval tree now, so instantiated pages
707 * are visible to arm/parisc __flush_dcache_page
708 * throughout; but we cannot insert into address
709 * space until vma start or end is updated.
711 __vma_link_file(insert);
715 anon_vma = vma->anon_vma;
716 if (!anon_vma && adjust_next)
717 anon_vma = next->anon_vma;
719 VM_BUG_ON_VMA(adjust_next && next->anon_vma &&
720 anon_vma != next->anon_vma, next);
721 anon_vma_lock_write(anon_vma);
722 anon_vma_interval_tree_pre_update_vma(vma);
724 anon_vma_interval_tree_pre_update_vma(next);
728 flush_dcache_mmap_lock(mapping);
729 vma_interval_tree_remove(vma, root);
731 vma_interval_tree_remove(next, root);
734 if (start != vma->vm_start) {
735 vma->vm_start = start;
736 start_changed = true;
738 if (end != vma->vm_end) {
742 vma->vm_pgoff = pgoff;
744 next->vm_start += adjust_next << PAGE_SHIFT;
745 next->vm_pgoff += adjust_next;
750 vma_interval_tree_insert(next, root);
751 vma_interval_tree_insert(vma, root);
752 flush_dcache_mmap_unlock(mapping);
757 * vma_merge has merged next into vma, and needs
758 * us to remove next before dropping the locks.
760 __vma_unlink(mm, next, vma);
762 __remove_shared_vm_struct(next, file, mapping);
765 * split_vma has split insert from vma, and needs
766 * us to insert it before dropping the locks
767 * (it may either follow vma or precede it).
769 __insert_vm_struct(mm, insert);
775 mm->highest_vm_end = end;
776 else if (!adjust_next)
777 vma_gap_update(next);
782 anon_vma_interval_tree_post_update_vma(vma);
784 anon_vma_interval_tree_post_update_vma(next);
785 anon_vma_unlock_write(anon_vma);
788 i_mmap_unlock_write(mapping);
799 uprobe_munmap(next, next->vm_start, next->vm_end);
803 anon_vma_merge(vma, next);
805 mpol_put(vma_policy(next));
806 kmem_cache_free(vm_area_cachep, next);
808 * In mprotect's case 6 (see comments on vma_merge),
809 * we must remove another next too. It would clutter
810 * up the code too much to do both in one go.
813 if (remove_next == 2) {
819 vma_gap_update(next);
822 * If remove_next == 2 we obviously can't
825 * If remove_next == 3 we can't reach this
826 * path because pre-swap() next is always not
827 * NULL. pre-swap() "next" is not being
828 * removed and its next->vm_end is not altered
829 * (and furthermore "end" already matches
830 * next->vm_end in remove_next == 3).
832 * We reach this only in the remove_next == 1
833 * case if the "next" vma that was removed was
834 * the highest vma of the mm. However in such
835 * case next->vm_end == "end" and the extended
836 * "vma" has vma->vm_end == next->vm_end so
837 * mm->highest_vm_end doesn't need any update
838 * in remove_next == 1 case.
840 VM_WARN_ON(mm->highest_vm_end != end);
852 * If the vma has a ->close operation then the driver probably needs to release
853 * per-vma resources, so we don't attempt to merge those.
855 static inline int is_mergeable_vma(struct vm_area_struct *vma,
856 struct file *file, unsigned long vm_flags,
857 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
860 * VM_SOFTDIRTY should not prevent from VMA merging, if we
861 * match the flags but dirty bit -- the caller should mark
862 * merged VMA as dirty. If dirty bit won't be excluded from
863 * comparison, we increase pressue on the memory system forcing
864 * the kernel to generate new VMAs when old one could be
867 if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
869 if (vma->vm_file != file)
871 if (vma->vm_ops && vma->vm_ops->close)
873 if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
878 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
879 struct anon_vma *anon_vma2,
880 struct vm_area_struct *vma)
883 * The list_is_singular() test is to avoid merging VMA cloned from
884 * parents. This can improve scalability caused by anon_vma lock.
886 if ((!anon_vma1 || !anon_vma2) && (!vma ||
887 list_is_singular(&vma->anon_vma_chain)))
889 return anon_vma1 == anon_vma2;
893 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
894 * in front of (at a lower virtual address and file offset than) the vma.
896 * We cannot merge two vmas if they have differently assigned (non-NULL)
897 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
899 * We don't check here for the merged mmap wrapping around the end of pagecache
900 * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
901 * wrap, nor mmaps which cover the final page at index -1UL.
904 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
905 struct anon_vma *anon_vma, struct file *file,
907 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
909 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
910 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
911 if (vma->vm_pgoff == vm_pgoff)
918 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
919 * beyond (at a higher virtual address and file offset than) the vma.
921 * We cannot merge two vmas if they have differently assigned (non-NULL)
922 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
925 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
926 struct anon_vma *anon_vma, struct file *file,
928 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
930 if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
931 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
933 vm_pglen = vma_pages(vma);
934 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
941 * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
942 * whether that can be merged with its predecessor or its successor.
943 * Or both (it neatly fills a hole).
945 * In most cases - when called for mmap, brk or mremap - [addr,end) is
946 * certain not to be mapped by the time vma_merge is called; but when
947 * called for mprotect, it is certain to be already mapped (either at
948 * an offset within prev, or at the start of next), and the flags of
949 * this area are about to be changed to vm_flags - and the no-change
950 * case has already been eliminated.
952 * The following mprotect cases have to be considered, where AAAA is
953 * the area passed down from mprotect_fixup, never extending beyond one
954 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
956 * AAAA AAAA AAAA AAAA
957 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX
958 * cannot merge might become might become might become
959 * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or
960 * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or
961 * mremap move: PPPPNNNNNNNN 8
963 * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN
964 * might become case 1 below case 2 below case 3 below
966 * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
967 * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
969 struct vm_area_struct *vma_merge(struct mm_struct *mm,
970 struct vm_area_struct *prev, unsigned long addr,
971 unsigned long end, unsigned long vm_flags,
972 struct anon_vma *anon_vma, struct file *file,
973 pgoff_t pgoff, struct mempolicy *policy,
974 struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
976 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
977 struct vm_area_struct *area, *next;
981 * We later require that vma->vm_flags == vm_flags,
982 * so this tests vma->vm_flags & VM_SPECIAL, too.
984 if (vm_flags & VM_SPECIAL)
988 next = prev->vm_next;
992 if (next && next->vm_end == end) /* cases 6, 7, 8 */
993 next = next->vm_next;
996 * Can it merge with the predecessor?
998 if (prev && prev->vm_end == addr &&
999 mpol_equal(vma_policy(prev), policy) &&
1000 can_vma_merge_after(prev, vm_flags,
1001 anon_vma, file, pgoff,
1002 vm_userfaultfd_ctx)) {
1004 * OK, it can. Can we now merge in the successor as well?
1006 if (next && end == next->vm_start &&
1007 mpol_equal(policy, vma_policy(next)) &&
1008 can_vma_merge_before(next, vm_flags,
1011 vm_userfaultfd_ctx) &&
1012 is_mergeable_anon_vma(prev->anon_vma,
1013 next->anon_vma, NULL)) {
1015 err = vma_adjust(prev, prev->vm_start,
1016 next->vm_end, prev->vm_pgoff, NULL);
1017 } else /* cases 2, 5, 7 */
1018 err = vma_adjust(prev, prev->vm_start,
1019 end, prev->vm_pgoff, NULL);
1022 khugepaged_enter_vma_merge(prev, vm_flags);
1027 * Can this new request be merged in front of next?
1029 if (next && end == next->vm_start &&
1030 mpol_equal(policy, vma_policy(next)) &&
1031 can_vma_merge_before(next, vm_flags,
1032 anon_vma, file, pgoff+pglen,
1033 vm_userfaultfd_ctx)) {
1034 if (prev && addr < prev->vm_end) /* case 4 */
1035 err = vma_adjust(prev, prev->vm_start,
1036 addr, prev->vm_pgoff, NULL);
1037 else /* cases 3, 8 */
1038 err = vma_adjust(area, addr, next->vm_end,
1039 next->vm_pgoff - pglen, NULL);
1042 khugepaged_enter_vma_merge(area, vm_flags);
1050 * Rough compatbility check to quickly see if it's even worth looking
1051 * at sharing an anon_vma.
1053 * They need to have the same vm_file, and the flags can only differ
1054 * in things that mprotect may change.
1056 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1057 * we can merge the two vma's. For example, we refuse to merge a vma if
1058 * there is a vm_ops->close() function, because that indicates that the
1059 * driver is doing some kind of reference counting. But that doesn't
1060 * really matter for the anon_vma sharing case.
1062 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1064 return a->vm_end == b->vm_start &&
1065 mpol_equal(vma_policy(a), vma_policy(b)) &&
1066 a->vm_file == b->vm_file &&
1067 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
1068 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1072 * Do some basic sanity checking to see if we can re-use the anon_vma
1073 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1074 * the same as 'old', the other will be the new one that is trying
1075 * to share the anon_vma.
1077 * NOTE! This runs with mm_sem held for reading, so it is possible that
1078 * the anon_vma of 'old' is concurrently in the process of being set up
1079 * by another page fault trying to merge _that_. But that's ok: if it
1080 * is being set up, that automatically means that it will be a singleton
1081 * acceptable for merging, so we can do all of this optimistically. But
1082 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1084 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1085 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1086 * is to return an anon_vma that is "complex" due to having gone through
1089 * We also make sure that the two vma's are compatible (adjacent,
1090 * and with the same memory policies). That's all stable, even with just
1091 * a read lock on the mm_sem.
1093 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1095 if (anon_vma_compatible(a, b)) {
1096 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1098 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1105 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1106 * neighbouring vmas for a suitable anon_vma, before it goes off
1107 * to allocate a new anon_vma. It checks because a repetitive
1108 * sequence of mprotects and faults may otherwise lead to distinct
1109 * anon_vmas being allocated, preventing vma merge in subsequent
1112 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1114 struct anon_vma *anon_vma;
1115 struct vm_area_struct *near;
1117 near = vma->vm_next;
1121 anon_vma = reusable_anon_vma(near, vma, near);
1125 near = vma->vm_prev;
1129 anon_vma = reusable_anon_vma(near, near, vma);
1134 * There's no absolute need to look only at touching neighbours:
1135 * we could search further afield for "compatible" anon_vmas.
1136 * But it would probably just be a waste of time searching,
1137 * or lead to too many vmas hanging off the same anon_vma.
1138 * We're trying to allow mprotect remerging later on,
1139 * not trying to minimize memory used for anon_vmas.
1145 * If a hint addr is less than mmap_min_addr change hint to be as
1146 * low as possible but still greater than mmap_min_addr
1148 static inline unsigned long round_hint_to_min(unsigned long hint)
1151 if (((void *)hint != NULL) &&
1152 (hint < mmap_min_addr))
1153 return PAGE_ALIGN(mmap_min_addr);
1157 static inline int mlock_future_check(struct mm_struct *mm,
1158 unsigned long flags,
1161 unsigned long locked, lock_limit;
1163 /* mlock MCL_FUTURE? */
1164 if (flags & VM_LOCKED) {
1165 locked = len >> PAGE_SHIFT;
1166 locked += mm->locked_vm;
1167 lock_limit = rlimit(RLIMIT_MEMLOCK);
1168 lock_limit >>= PAGE_SHIFT;
1169 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1176 * The caller must hold down_write(¤t->mm->mmap_sem).
1178 unsigned long do_mmap(struct file *file, unsigned long addr,
1179 unsigned long len, unsigned long prot,
1180 unsigned long flags, vm_flags_t vm_flags,
1181 unsigned long pgoff, unsigned long *populate)
1183 struct mm_struct *mm = current->mm;
1192 * Does the application expect PROT_READ to imply PROT_EXEC?
1194 * (the exception is when the underlying filesystem is noexec
1195 * mounted, in which case we dont add PROT_EXEC.)
1197 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1198 if (!(file && path_noexec(&file->f_path)))
1201 if (!(flags & MAP_FIXED))
1202 addr = round_hint_to_min(addr);
1204 /* Careful about overflows.. */
1205 len = PAGE_ALIGN(len);
1209 /* offset overflow? */
1210 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1213 /* Too many mappings? */
1214 if (mm->map_count > sysctl_max_map_count)
1217 /* Obtain the address to map to. we verify (or select) it and ensure
1218 * that it represents a valid section of the address space.
1220 addr = get_unmapped_area(file, addr, len, pgoff, flags);
1221 if (offset_in_page(addr))
1224 if (prot == PROT_EXEC) {
1225 pkey = execute_only_pkey(mm);
1230 /* Do simple checking here so the lower-level routines won't have
1231 * to. we assume access permissions have been handled by the open
1232 * of the memory object, so we don't do any here.
1234 vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1235 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1237 if (flags & MAP_LOCKED)
1238 if (!can_do_mlock())
1241 if (mlock_future_check(mm, vm_flags, len))
1245 struct inode *inode = file_inode(file);
1247 switch (flags & MAP_TYPE) {
1249 if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1253 * Make sure we don't allow writing to an append-only
1256 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1260 * Make sure there are no mandatory locks on the file.
1262 if (locks_verify_locked(file))
1265 vm_flags |= VM_SHARED | VM_MAYSHARE;
1266 if (!(file->f_mode & FMODE_WRITE))
1267 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1271 if (!(file->f_mode & FMODE_READ))
1273 if (path_noexec(&file->f_path)) {
1274 if (vm_flags & VM_EXEC)
1276 vm_flags &= ~VM_MAYEXEC;
1279 if (!file->f_op->mmap)
1281 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1289 switch (flags & MAP_TYPE) {
1291 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1297 vm_flags |= VM_SHARED | VM_MAYSHARE;
1301 * Set pgoff according to addr for anon_vma.
1303 pgoff = addr >> PAGE_SHIFT;
1311 * Set 'VM_NORESERVE' if we should not account for the
1312 * memory use of this mapping.
1314 if (flags & MAP_NORESERVE) {
1315 /* We honor MAP_NORESERVE if allowed to overcommit */
1316 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1317 vm_flags |= VM_NORESERVE;
1319 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1320 if (file && is_file_hugepages(file))
1321 vm_flags |= VM_NORESERVE;
1324 addr = mmap_region(file, addr, len, vm_flags, pgoff);
1325 if (!IS_ERR_VALUE(addr) &&
1326 ((vm_flags & VM_LOCKED) ||
1327 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1332 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1333 unsigned long, prot, unsigned long, flags,
1334 unsigned long, fd, unsigned long, pgoff)
1336 struct file *file = NULL;
1337 unsigned long retval;
1339 if (!(flags & MAP_ANONYMOUS)) {
1340 audit_mmap_fd(fd, flags);
1344 if (is_file_hugepages(file))
1345 len = ALIGN(len, huge_page_size(hstate_file(file)));
1347 if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
1349 } else if (flags & MAP_HUGETLB) {
1350 struct user_struct *user = NULL;
1353 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & SHM_HUGE_MASK);
1357 len = ALIGN(len, huge_page_size(hs));
1359 * VM_NORESERVE is used because the reservations will be
1360 * taken when vm_ops->mmap() is called
1361 * A dummy user value is used because we are not locking
1362 * memory so no accounting is necessary
1364 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1366 &user, HUGETLB_ANONHUGE_INODE,
1367 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1369 return PTR_ERR(file);
1372 flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1374 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1381 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1382 struct mmap_arg_struct {
1386 unsigned long flags;
1388 unsigned long offset;
1391 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1393 struct mmap_arg_struct a;
1395 if (copy_from_user(&a, arg, sizeof(a)))
1397 if (offset_in_page(a.offset))
1400 return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1401 a.offset >> PAGE_SHIFT);
1403 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1406 * Some shared mappigns will want the pages marked read-only
1407 * to track write events. If so, we'll downgrade vm_page_prot
1408 * to the private version (using protection_map[] without the
1411 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1413 vm_flags_t vm_flags = vma->vm_flags;
1414 const struct vm_operations_struct *vm_ops = vma->vm_ops;
1416 /* If it was private or non-writable, the write bit is already clear */
1417 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1420 /* The backer wishes to know when pages are first written to? */
1421 if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1424 /* The open routine did something to the protections that pgprot_modify
1425 * won't preserve? */
1426 if (pgprot_val(vm_page_prot) !=
1427 pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1430 /* Do we need to track softdirty? */
1431 if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
1434 /* Specialty mapping? */
1435 if (vm_flags & VM_PFNMAP)
1438 /* Can the mapping track the dirty pages? */
1439 return vma->vm_file && vma->vm_file->f_mapping &&
1440 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1444 * We account for memory if it's a private writeable mapping,
1445 * not hugepages and VM_NORESERVE wasn't set.
1447 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1450 * hugetlb has its own accounting separate from the core VM
1451 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1453 if (file && is_file_hugepages(file))
1456 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1459 unsigned long mmap_region(struct file *file, unsigned long addr,
1460 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff)
1462 struct mm_struct *mm = current->mm;
1463 struct vm_area_struct *vma, *prev;
1465 struct rb_node **rb_link, *rb_parent;
1466 unsigned long charged = 0;
1468 /* Check against address space limit. */
1469 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1470 unsigned long nr_pages;
1473 * MAP_FIXED may remove pages of mappings that intersects with
1474 * requested mapping. Account for the pages it would unmap.
1476 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1478 if (!may_expand_vm(mm, vm_flags,
1479 (len >> PAGE_SHIFT) - nr_pages))
1483 /* Clear old maps */
1484 while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
1486 if (do_munmap(mm, addr, len))
1491 * Private writable mapping: check memory availability
1493 if (accountable_mapping(file, vm_flags)) {
1494 charged = len >> PAGE_SHIFT;
1495 if (security_vm_enough_memory_mm(mm, charged))
1497 vm_flags |= VM_ACCOUNT;
1501 * Can we just expand an old mapping?
1503 vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1504 NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);
1509 * Determine the object being mapped and call the appropriate
1510 * specific mapper. the address has already been validated, but
1511 * not unmapped, but the maps are removed from the list.
1513 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1520 vma->vm_start = addr;
1521 vma->vm_end = addr + len;
1522 vma->vm_flags = vm_flags;
1523 vma->vm_page_prot = vm_get_page_prot(vm_flags);
1524 vma->vm_pgoff = pgoff;
1525 INIT_LIST_HEAD(&vma->anon_vma_chain);
1528 if (vm_flags & VM_DENYWRITE) {
1529 error = deny_write_access(file);
1533 if (vm_flags & VM_SHARED) {
1534 error = mapping_map_writable(file->f_mapping);
1536 goto allow_write_and_free_vma;
1539 /* ->mmap() can change vma->vm_file, but must guarantee that
1540 * vma_link() below can deny write-access if VM_DENYWRITE is set
1541 * and map writably if VM_SHARED is set. This usually means the
1542 * new file must not have been exposed to user-space, yet.
1544 vma->vm_file = get_file(file);
1545 error = file->f_op->mmap(file, vma);
1547 goto unmap_and_free_vma;
1549 /* Can addr have changed??
1551 * Answer: Yes, several device drivers can do it in their
1552 * f_op->mmap method. -DaveM
1553 * Bug: If addr is changed, prev, rb_link, rb_parent should
1554 * be updated for vma_link()
1556 WARN_ON_ONCE(addr != vma->vm_start);
1558 addr = vma->vm_start;
1559 vm_flags = vma->vm_flags;
1560 } else if (vm_flags & VM_SHARED) {
1561 error = shmem_zero_setup(vma);
1566 vma_link(mm, vma, prev, rb_link, rb_parent);
1567 /* Once vma denies write, undo our temporary denial count */
1569 if (vm_flags & VM_SHARED)
1570 mapping_unmap_writable(file->f_mapping);
1571 if (vm_flags & VM_DENYWRITE)
1572 allow_write_access(file);
1574 file = vma->vm_file;
1576 perf_event_mmap(vma);
1578 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
1579 if (vm_flags & VM_LOCKED) {
1580 if (!((vm_flags & VM_SPECIAL) || is_vm_hugetlb_page(vma) ||
1581 vma == get_gate_vma(current->mm)))
1582 mm->locked_vm += (len >> PAGE_SHIFT);
1584 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1591 * New (or expanded) vma always get soft dirty status.
1592 * Otherwise user-space soft-dirty page tracker won't
1593 * be able to distinguish situation when vma area unmapped,
1594 * then new mapped in-place (which must be aimed as
1595 * a completely new data area).
1597 vma->vm_flags |= VM_SOFTDIRTY;
1599 vma_set_page_prot(vma);
1604 vma->vm_file = NULL;
1607 /* Undo any partial mapping done by a device driver. */
1608 unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1610 if (vm_flags & VM_SHARED)
1611 mapping_unmap_writable(file->f_mapping);
1612 allow_write_and_free_vma:
1613 if (vm_flags & VM_DENYWRITE)
1614 allow_write_access(file);
1616 kmem_cache_free(vm_area_cachep, vma);
1619 vm_unacct_memory(charged);
1623 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1626 * We implement the search by looking for an rbtree node that
1627 * immediately follows a suitable gap. That is,
1628 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1629 * - gap_end = vma->vm_start >= info->low_limit + length;
1630 * - gap_end - gap_start >= length
1633 struct mm_struct *mm = current->mm;
1634 struct vm_area_struct *vma;
1635 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1637 /* Adjust search length to account for worst case alignment overhead */
1638 length = info->length + info->align_mask;
1639 if (length < info->length)
1642 /* Adjust search limits by the desired length */
1643 if (info->high_limit < length)
1645 high_limit = info->high_limit - length;
1647 if (info->low_limit > high_limit)
1649 low_limit = info->low_limit + length;
1651 /* Check if rbtree root looks promising */
1652 if (RB_EMPTY_ROOT(&mm->mm_rb))
1654 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1655 if (vma->rb_subtree_gap < length)
1659 /* Visit left subtree if it looks promising */
1660 gap_end = vma->vm_start;
1661 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1662 struct vm_area_struct *left =
1663 rb_entry(vma->vm_rb.rb_left,
1664 struct vm_area_struct, vm_rb);
1665 if (left->rb_subtree_gap >= length) {
1671 gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
1673 /* Check if current node has a suitable gap */
1674 if (gap_start > high_limit)
1676 if (gap_end >= low_limit && gap_end - gap_start >= length)
1679 /* Visit right subtree if it looks promising */
1680 if (vma->vm_rb.rb_right) {
1681 struct vm_area_struct *right =
1682 rb_entry(vma->vm_rb.rb_right,
1683 struct vm_area_struct, vm_rb);
1684 if (right->rb_subtree_gap >= length) {
1690 /* Go back up the rbtree to find next candidate node */
1692 struct rb_node *prev = &vma->vm_rb;
1693 if (!rb_parent(prev))
1695 vma = rb_entry(rb_parent(prev),
1696 struct vm_area_struct, vm_rb);
1697 if (prev == vma->vm_rb.rb_left) {
1698 gap_start = vma->vm_prev->vm_end;
1699 gap_end = vma->vm_start;
1706 /* Check highest gap, which does not precede any rbtree node */
1707 gap_start = mm->highest_vm_end;
1708 gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
1709 if (gap_start > high_limit)
1713 /* We found a suitable gap. Clip it with the original low_limit. */
1714 if (gap_start < info->low_limit)
1715 gap_start = info->low_limit;
1717 /* Adjust gap address to the desired alignment */
1718 gap_start += (info->align_offset - gap_start) & info->align_mask;
1720 VM_BUG_ON(gap_start + info->length > info->high_limit);
1721 VM_BUG_ON(gap_start + info->length > gap_end);
1725 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1727 struct mm_struct *mm = current->mm;
1728 struct vm_area_struct *vma;
1729 unsigned long length, low_limit, high_limit, gap_start, gap_end;
1731 /* Adjust search length to account for worst case alignment overhead */
1732 length = info->length + info->align_mask;
1733 if (length < info->length)
1737 * Adjust search limits by the desired length.
1738 * See implementation comment at top of unmapped_area().
1740 gap_end = info->high_limit;
1741 if (gap_end < length)
1743 high_limit = gap_end - length;
1745 if (info->low_limit > high_limit)
1747 low_limit = info->low_limit + length;
1749 /* Check highest gap, which does not precede any rbtree node */
1750 gap_start = mm->highest_vm_end;
1751 if (gap_start <= high_limit)
1754 /* Check if rbtree root looks promising */
1755 if (RB_EMPTY_ROOT(&mm->mm_rb))
1757 vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1758 if (vma->rb_subtree_gap < length)
1762 /* Visit right subtree if it looks promising */
1763 gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
1764 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
1765 struct vm_area_struct *right =
1766 rb_entry(vma->vm_rb.rb_right,
1767 struct vm_area_struct, vm_rb);
1768 if (right->rb_subtree_gap >= length) {
1775 /* Check if current node has a suitable gap */
1776 gap_end = vma->vm_start;
1777 if (gap_end < low_limit)
1779 if (gap_start <= high_limit && gap_end - gap_start >= length)
1782 /* Visit left subtree if it looks promising */
1783 if (vma->vm_rb.rb_left) {
1784 struct vm_area_struct *left =
1785 rb_entry(vma->vm_rb.rb_left,
1786 struct vm_area_struct, vm_rb);
1787 if (left->rb_subtree_gap >= length) {
1793 /* Go back up the rbtree to find next candidate node */
1795 struct rb_node *prev = &vma->vm_rb;
1796 if (!rb_parent(prev))
1798 vma = rb_entry(rb_parent(prev),
1799 struct vm_area_struct, vm_rb);
1800 if (prev == vma->vm_rb.rb_right) {
1801 gap_start = vma->vm_prev ?
1802 vma->vm_prev->vm_end : 0;
1809 /* We found a suitable gap. Clip it with the original high_limit. */
1810 if (gap_end > info->high_limit)
1811 gap_end = info->high_limit;
1814 /* Compute highest gap address at the desired alignment */
1815 gap_end -= info->length;
1816 gap_end -= (gap_end - info->align_offset) & info->align_mask;
1818 VM_BUG_ON(gap_end < info->low_limit);
1819 VM_BUG_ON(gap_end < gap_start);
1823 /* Get an address range which is currently unmapped.
1824 * For shmat() with addr=0.
1826 * Ugly calling convention alert:
1827 * Return value with the low bits set means error value,
1829 * if (ret & ~PAGE_MASK)
1832 * This function "knows" that -ENOMEM has the bits set.
1834 #ifndef HAVE_ARCH_UNMAPPED_AREA
1836 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1837 unsigned long len, unsigned long pgoff, unsigned long flags)
1839 struct mm_struct *mm = current->mm;
1840 struct vm_area_struct *vma;
1841 struct vm_unmapped_area_info info;
1843 if (len > TASK_SIZE - mmap_min_addr)
1846 if (flags & MAP_FIXED)
1850 addr = PAGE_ALIGN(addr);
1851 vma = find_vma(mm, addr);
1852 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1853 (!vma || addr + len <= vma->vm_start))
1859 info.low_limit = mm->mmap_base;
1860 info.high_limit = TASK_SIZE;
1861 info.align_mask = 0;
1862 return vm_unmapped_area(&info);
1867 * This mmap-allocator allocates new areas top-down from below the
1868 * stack's low limit (the base):
1870 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1872 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1873 const unsigned long len, const unsigned long pgoff,
1874 const unsigned long flags)
1876 struct vm_area_struct *vma;
1877 struct mm_struct *mm = current->mm;
1878 unsigned long addr = addr0;
1879 struct vm_unmapped_area_info info;
1881 /* requested length too big for entire address space */
1882 if (len > TASK_SIZE - mmap_min_addr)
1885 if (flags & MAP_FIXED)
1888 /* requesting a specific address */
1890 addr = PAGE_ALIGN(addr);
1891 vma = find_vma(mm, addr);
1892 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1893 (!vma || addr + len <= vma->vm_start))
1897 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1899 info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1900 info.high_limit = mm->mmap_base;
1901 info.align_mask = 0;
1902 addr = vm_unmapped_area(&info);
1905 * A failed mmap() very likely causes application failure,
1906 * so fall back to the bottom-up function here. This scenario
1907 * can happen with large stack limits and large mmap()
1910 if (offset_in_page(addr)) {
1911 VM_BUG_ON(addr != -ENOMEM);
1913 info.low_limit = TASK_UNMAPPED_BASE;
1914 info.high_limit = TASK_SIZE;
1915 addr = vm_unmapped_area(&info);
1923 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1924 unsigned long pgoff, unsigned long flags)
1926 unsigned long (*get_area)(struct file *, unsigned long,
1927 unsigned long, unsigned long, unsigned long);
1929 unsigned long error = arch_mmap_check(addr, len, flags);
1933 /* Careful about overflows.. */
1934 if (len > TASK_SIZE)
1937 get_area = current->mm->get_unmapped_area;
1939 if (file->f_op->get_unmapped_area)
1940 get_area = file->f_op->get_unmapped_area;
1941 } else if (flags & MAP_SHARED) {
1943 * mmap_region() will call shmem_zero_setup() to create a file,
1944 * so use shmem's get_unmapped_area in case it can be huge.
1945 * do_mmap_pgoff() will clear pgoff, so match alignment.
1948 get_area = shmem_get_unmapped_area;
1951 addr = get_area(file, addr, len, pgoff, flags);
1952 if (IS_ERR_VALUE(addr))
1955 if (addr > TASK_SIZE - len)
1957 if (offset_in_page(addr))
1960 error = security_mmap_addr(addr);
1961 return error ? error : addr;
1964 EXPORT_SYMBOL(get_unmapped_area);
1966 /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
1967 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1969 struct rb_node *rb_node;
1970 struct vm_area_struct *vma;
1972 /* Check the cache first. */
1973 vma = vmacache_find(mm, addr);
1977 rb_node = mm->mm_rb.rb_node;
1980 struct vm_area_struct *tmp;
1982 tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
1984 if (tmp->vm_end > addr) {
1986 if (tmp->vm_start <= addr)
1988 rb_node = rb_node->rb_left;
1990 rb_node = rb_node->rb_right;
1994 vmacache_update(addr, vma);
1998 EXPORT_SYMBOL(find_vma);
2001 * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2003 struct vm_area_struct *
2004 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2005 struct vm_area_struct **pprev)
2007 struct vm_area_struct *vma;
2009 vma = find_vma(mm, addr);
2011 *pprev = vma->vm_prev;
2013 struct rb_node *rb_node = mm->mm_rb.rb_node;
2016 *pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2017 rb_node = rb_node->rb_right;
2024 * Verify that the stack growth is acceptable and
2025 * update accounting. This is shared with both the
2026 * grow-up and grow-down cases.
2028 static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
2030 struct mm_struct *mm = vma->vm_mm;
2031 struct rlimit *rlim = current->signal->rlim;
2032 unsigned long new_start, actual_size;
2034 /* address space limit tests */
2035 if (!may_expand_vm(mm, vma->vm_flags, grow))
2038 /* Stack limit test */
2040 if (size && (vma->vm_flags & (VM_GROWSUP | VM_GROWSDOWN)))
2041 actual_size -= PAGE_SIZE;
2042 if (actual_size > READ_ONCE(rlim[RLIMIT_STACK].rlim_cur))
2045 /* mlock limit tests */
2046 if (vma->vm_flags & VM_LOCKED) {
2047 unsigned long locked;
2048 unsigned long limit;
2049 locked = mm->locked_vm + grow;
2050 limit = READ_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
2051 limit >>= PAGE_SHIFT;
2052 if (locked > limit && !capable(CAP_IPC_LOCK))
2056 /* Check to ensure the stack will not grow into a hugetlb-only region */
2057 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2059 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2063 * Overcommit.. This must be the final test, as it will
2064 * update security statistics.
2066 if (security_vm_enough_memory_mm(mm, grow))
2072 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2074 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2075 * vma is the last one with address > vma->vm_end. Have to extend vma.
2077 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2079 struct mm_struct *mm = vma->vm_mm;
2082 if (!(vma->vm_flags & VM_GROWSUP))
2085 /* Guard against wrapping around to address 0. */
2086 if (address < PAGE_ALIGN(address+4))
2087 address = PAGE_ALIGN(address+4);
2091 /* We must make sure the anon_vma is allocated. */
2092 if (unlikely(anon_vma_prepare(vma)))
2096 * vma->vm_start/vm_end cannot change under us because the caller
2097 * is required to hold the mmap_sem in read mode. We need the
2098 * anon_vma lock to serialize against concurrent expand_stacks.
2100 anon_vma_lock_write(vma->anon_vma);
2102 /* Somebody else might have raced and expanded it already */
2103 if (address > vma->vm_end) {
2104 unsigned long size, grow;
2106 size = address - vma->vm_start;
2107 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2110 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2111 error = acct_stack_growth(vma, size, grow);
2114 * vma_gap_update() doesn't support concurrent
2115 * updates, but we only hold a shared mmap_sem
2116 * lock here, so we need to protect against
2117 * concurrent vma expansions.
2118 * anon_vma_lock_write() doesn't help here, as
2119 * we don't guarantee that all growable vmas
2120 * in a mm share the same root anon vma.
2121 * So, we reuse mm->page_table_lock to guard
2122 * against concurrent vma expansions.
2124 spin_lock(&mm->page_table_lock);
2125 if (vma->vm_flags & VM_LOCKED)
2126 mm->locked_vm += grow;
2127 vm_stat_account(mm, vma->vm_flags, grow);
2128 anon_vma_interval_tree_pre_update_vma(vma);
2129 vma->vm_end = address;
2130 anon_vma_interval_tree_post_update_vma(vma);
2132 vma_gap_update(vma->vm_next);
2134 mm->highest_vm_end = address;
2135 spin_unlock(&mm->page_table_lock);
2137 perf_event_mmap(vma);
2141 anon_vma_unlock_write(vma->anon_vma);
2142 khugepaged_enter_vma_merge(vma, vma->vm_flags);
2146 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2149 * vma is the first one with address < vma->vm_start. Have to extend vma.
2151 int expand_downwards(struct vm_area_struct *vma,
2152 unsigned long address)
2154 struct mm_struct *mm = vma->vm_mm;
2157 address &= PAGE_MASK;
2158 error = security_mmap_addr(address);
2162 /* We must make sure the anon_vma is allocated. */
2163 if (unlikely(anon_vma_prepare(vma)))
2167 * vma->vm_start/vm_end cannot change under us because the caller
2168 * is required to hold the mmap_sem in read mode. We need the
2169 * anon_vma lock to serialize against concurrent expand_stacks.
2171 anon_vma_lock_write(vma->anon_vma);
2173 /* Somebody else might have raced and expanded it already */
2174 if (address < vma->vm_start) {
2175 unsigned long size, grow;
2177 size = vma->vm_end - address;
2178 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2181 if (grow <= vma->vm_pgoff) {
2182 error = acct_stack_growth(vma, size, grow);
2185 * vma_gap_update() doesn't support concurrent
2186 * updates, but we only hold a shared mmap_sem
2187 * lock here, so we need to protect against
2188 * concurrent vma expansions.
2189 * anon_vma_lock_write() doesn't help here, as
2190 * we don't guarantee that all growable vmas
2191 * in a mm share the same root anon vma.
2192 * So, we reuse mm->page_table_lock to guard
2193 * against concurrent vma expansions.
2195 spin_lock(&mm->page_table_lock);
2196 if (vma->vm_flags & VM_LOCKED)
2197 mm->locked_vm += grow;
2198 vm_stat_account(mm, vma->vm_flags, grow);
2199 anon_vma_interval_tree_pre_update_vma(vma);
2200 vma->vm_start = address;
2201 vma->vm_pgoff -= grow;
2202 anon_vma_interval_tree_post_update_vma(vma);
2203 vma_gap_update(vma);
2204 spin_unlock(&mm->page_table_lock);
2206 perf_event_mmap(vma);
2210 anon_vma_unlock_write(vma->anon_vma);
2211 khugepaged_enter_vma_merge(vma, vma->vm_flags);
2217 * Note how expand_stack() refuses to expand the stack all the way to
2218 * abut the next virtual mapping, *unless* that mapping itself is also
2219 * a stack mapping. We want to leave room for a guard page, after all
2220 * (the guard page itself is not added here, that is done by the
2221 * actual page faulting logic)
2223 * This matches the behavior of the guard page logic (see mm/memory.c:
2224 * check_stack_guard_page()), which only allows the guard page to be
2225 * removed under these circumstances.
2227 #ifdef CONFIG_STACK_GROWSUP
2228 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2230 struct vm_area_struct *next;
2232 address &= PAGE_MASK;
2233 next = vma->vm_next;
2234 if (next && next->vm_start == address + PAGE_SIZE) {
2235 if (!(next->vm_flags & VM_GROWSUP))
2238 return expand_upwards(vma, address);
2241 struct vm_area_struct *
2242 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2244 struct vm_area_struct *vma, *prev;
2247 vma = find_vma_prev(mm, addr, &prev);
2248 if (vma && (vma->vm_start <= addr))
2250 if (!prev || expand_stack(prev, addr))
2252 if (prev->vm_flags & VM_LOCKED)
2253 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2257 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2259 struct vm_area_struct *prev;
2261 address &= PAGE_MASK;
2262 prev = vma->vm_prev;
2263 if (prev && prev->vm_end == address) {
2264 if (!(prev->vm_flags & VM_GROWSDOWN))
2267 return expand_downwards(vma, address);
2270 struct vm_area_struct *
2271 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2273 struct vm_area_struct *vma;
2274 unsigned long start;
2277 vma = find_vma(mm, addr);
2280 if (vma->vm_start <= addr)
2282 if (!(vma->vm_flags & VM_GROWSDOWN))
2284 start = vma->vm_start;
2285 if (expand_stack(vma, addr))
2287 if (vma->vm_flags & VM_LOCKED)
2288 populate_vma_page_range(vma, addr, start, NULL);
2293 EXPORT_SYMBOL_GPL(find_extend_vma);
2296 * Ok - we have the memory areas we should free on the vma list,
2297 * so release them, and do the vma updates.
2299 * Called with the mm semaphore held.
2301 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2303 unsigned long nr_accounted = 0;
2305 /* Update high watermark before we lower total_vm */
2306 update_hiwater_vm(mm);
2308 long nrpages = vma_pages(vma);
2310 if (vma->vm_flags & VM_ACCOUNT)
2311 nr_accounted += nrpages;
2312 vm_stat_account(mm, vma->vm_flags, -nrpages);
2313 vma = remove_vma(vma);
2315 vm_unacct_memory(nr_accounted);
2320 * Get rid of page table information in the indicated region.
2322 * Called with the mm semaphore held.
2324 static void unmap_region(struct mm_struct *mm,
2325 struct vm_area_struct *vma, struct vm_area_struct *prev,
2326 unsigned long start, unsigned long end)
2328 struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
2329 struct mmu_gather tlb;
2332 tlb_gather_mmu(&tlb, mm, start, end);
2333 update_hiwater_rss(mm);
2334 unmap_vmas(&tlb, vma, start, end);
2335 free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2336 next ? next->vm_start : USER_PGTABLES_CEILING);
2337 tlb_finish_mmu(&tlb, start, end);
2341 * Create a list of vma's touched by the unmap, removing them from the mm's
2342 * vma list as we go..
2345 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2346 struct vm_area_struct *prev, unsigned long end)
2348 struct vm_area_struct **insertion_point;
2349 struct vm_area_struct *tail_vma = NULL;
2351 insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2352 vma->vm_prev = NULL;
2354 vma_rb_erase(vma, &mm->mm_rb);
2358 } while (vma && vma->vm_start < end);
2359 *insertion_point = vma;
2361 vma->vm_prev = prev;
2362 vma_gap_update(vma);
2364 mm->highest_vm_end = prev ? prev->vm_end : 0;
2365 tail_vma->vm_next = NULL;
2367 /* Kill the cache */
2368 vmacache_invalidate(mm);
2372 * __split_vma() bypasses sysctl_max_map_count checking. We use this on the
2373 * munmap path where it doesn't make sense to fail.
2375 static int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2376 unsigned long addr, int new_below)
2378 struct vm_area_struct *new;
2381 if (is_vm_hugetlb_page(vma) && (addr &
2382 ~(huge_page_mask(hstate_vma(vma)))))
2385 new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2389 /* most fields are the same, copy all, and then fixup */
2392 INIT_LIST_HEAD(&new->anon_vma_chain);
2397 new->vm_start = addr;
2398 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2401 err = vma_dup_policy(vma, new);
2405 err = anon_vma_clone(new, vma);
2410 get_file(new->vm_file);
2412 if (new->vm_ops && new->vm_ops->open)
2413 new->vm_ops->open(new);
2416 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2417 ((addr - new->vm_start) >> PAGE_SHIFT), new);
2419 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2425 /* Clean everything up if vma_adjust failed. */
2426 if (new->vm_ops && new->vm_ops->close)
2427 new->vm_ops->close(new);
2430 unlink_anon_vmas(new);
2432 mpol_put(vma_policy(new));
2434 kmem_cache_free(vm_area_cachep, new);
2439 * Split a vma into two pieces at address 'addr', a new vma is allocated
2440 * either for the first part or the tail.
2442 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2443 unsigned long addr, int new_below)
2445 if (mm->map_count >= sysctl_max_map_count)
2448 return __split_vma(mm, vma, addr, new_below);
2451 /* Munmap is split into 2 main parts -- this part which finds
2452 * what needs doing, and the areas themselves, which do the
2453 * work. This now handles partial unmappings.
2454 * Jeremy Fitzhardinge <jeremy@goop.org>
2456 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2459 struct vm_area_struct *vma, *prev, *last;
2461 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2464 len = PAGE_ALIGN(len);
2468 /* Find the first overlapping VMA */
2469 vma = find_vma(mm, start);
2472 prev = vma->vm_prev;
2473 /* we have start < vma->vm_end */
2475 /* if it doesn't overlap, we have nothing.. */
2477 if (vma->vm_start >= end)
2481 * If we need to split any vma, do it now to save pain later.
2483 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2484 * unmapped vm_area_struct will remain in use: so lower split_vma
2485 * places tmp vma above, and higher split_vma places tmp vma below.
2487 if (start > vma->vm_start) {
2491 * Make sure that map_count on return from munmap() will
2492 * not exceed its limit; but let map_count go just above
2493 * its limit temporarily, to help free resources as expected.
2495 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2498 error = __split_vma(mm, vma, start, 0);
2504 /* Does it split the last one? */
2505 last = find_vma(mm, end);
2506 if (last && end > last->vm_start) {
2507 int error = __split_vma(mm, last, end, 1);
2511 vma = prev ? prev->vm_next : mm->mmap;
2514 * unlock any mlock()ed ranges before detaching vmas
2516 if (mm->locked_vm) {
2517 struct vm_area_struct *tmp = vma;
2518 while (tmp && tmp->vm_start < end) {
2519 if (tmp->vm_flags & VM_LOCKED) {
2520 mm->locked_vm -= vma_pages(tmp);
2521 munlock_vma_pages_all(tmp);
2528 * Remove the vma's, and unmap the actual pages
2530 detach_vmas_to_be_unmapped(mm, vma, prev, end);
2531 unmap_region(mm, vma, prev, start, end);
2533 arch_unmap(mm, vma, start, end);
2535 /* Fix up all other VM information */
2536 remove_vma_list(mm, vma);
2541 int vm_munmap(unsigned long start, size_t len)
2544 struct mm_struct *mm = current->mm;
2546 if (down_write_killable(&mm->mmap_sem))
2549 ret = do_munmap(mm, start, len);
2550 up_write(&mm->mmap_sem);
2553 EXPORT_SYMBOL(vm_munmap);
2555 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2558 struct mm_struct *mm = current->mm;
2560 profile_munmap(addr);
2561 if (down_write_killable(&mm->mmap_sem))
2563 ret = do_munmap(mm, addr, len);
2564 up_write(&mm->mmap_sem);
2570 * Emulation of deprecated remap_file_pages() syscall.
2572 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2573 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2576 struct mm_struct *mm = current->mm;
2577 struct vm_area_struct *vma;
2578 unsigned long populate = 0;
2579 unsigned long ret = -EINVAL;
2582 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.txt.\n",
2583 current->comm, current->pid);
2587 start = start & PAGE_MASK;
2588 size = size & PAGE_MASK;
2590 if (start + size <= start)
2593 /* Does pgoff wrap? */
2594 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2597 if (down_write_killable(&mm->mmap_sem))
2600 vma = find_vma(mm, start);
2602 if (!vma || !(vma->vm_flags & VM_SHARED))
2605 if (start < vma->vm_start)
2608 if (start + size > vma->vm_end) {
2609 struct vm_area_struct *next;
2611 for (next = vma->vm_next; next; next = next->vm_next) {
2612 /* hole between vmas ? */
2613 if (next->vm_start != next->vm_prev->vm_end)
2616 if (next->vm_file != vma->vm_file)
2619 if (next->vm_flags != vma->vm_flags)
2622 if (start + size <= next->vm_end)
2630 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2631 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2632 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2634 flags &= MAP_NONBLOCK;
2635 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2636 if (vma->vm_flags & VM_LOCKED) {
2637 struct vm_area_struct *tmp;
2638 flags |= MAP_LOCKED;
2640 /* drop PG_Mlocked flag for over-mapped range */
2641 for (tmp = vma; tmp->vm_start >= start + size;
2642 tmp = tmp->vm_next) {
2644 * Split pmd and munlock page on the border
2647 vma_adjust_trans_huge(tmp, start, start + size, 0);
2649 munlock_vma_pages_range(tmp,
2650 max(tmp->vm_start, start),
2651 min(tmp->vm_end, start + size));
2655 file = get_file(vma->vm_file);
2656 ret = do_mmap_pgoff(vma->vm_file, start, size,
2657 prot, flags, pgoff, &populate);
2660 up_write(&mm->mmap_sem);
2662 mm_populate(ret, populate);
2663 if (!IS_ERR_VALUE(ret))
2668 static inline void verify_mm_writelocked(struct mm_struct *mm)
2670 #ifdef CONFIG_DEBUG_VM
2671 if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2673 up_read(&mm->mmap_sem);
2679 * this is really a simplified "do_mmap". it only handles
2680 * anonymous maps. eventually we may be able to do some
2681 * brk-specific accounting here.
2683 static int do_brk(unsigned long addr, unsigned long request)
2685 struct mm_struct *mm = current->mm;
2686 struct vm_area_struct *vma, *prev;
2687 unsigned long flags, len;
2688 struct rb_node **rb_link, *rb_parent;
2689 pgoff_t pgoff = addr >> PAGE_SHIFT;
2692 len = PAGE_ALIGN(request);
2698 flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2700 error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2701 if (offset_in_page(error))
2704 error = mlock_future_check(mm, mm->def_flags, len);
2709 * mm->mmap_sem is required to protect against another thread
2710 * changing the mappings in case we sleep.
2712 verify_mm_writelocked(mm);
2715 * Clear old maps. this also does some error checking for us
2717 while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
2719 if (do_munmap(mm, addr, len))
2723 /* Check against address space limits *after* clearing old maps... */
2724 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
2727 if (mm->map_count > sysctl_max_map_count)
2730 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2733 /* Can we just expand an old private anonymous mapping? */
2734 vma = vma_merge(mm, prev, addr, addr + len, flags,
2735 NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);
2740 * create a vma struct for an anonymous mapping
2742 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2744 vm_unacct_memory(len >> PAGE_SHIFT);
2748 INIT_LIST_HEAD(&vma->anon_vma_chain);
2750 vma->vm_start = addr;
2751 vma->vm_end = addr + len;
2752 vma->vm_pgoff = pgoff;
2753 vma->vm_flags = flags;
2754 vma->vm_page_prot = vm_get_page_prot(flags);
2755 vma_link(mm, vma, prev, rb_link, rb_parent);
2757 perf_event_mmap(vma);
2758 mm->total_vm += len >> PAGE_SHIFT;
2759 mm->data_vm += len >> PAGE_SHIFT;
2760 if (flags & VM_LOCKED)
2761 mm->locked_vm += (len >> PAGE_SHIFT);
2762 vma->vm_flags |= VM_SOFTDIRTY;
2766 int vm_brk(unsigned long addr, unsigned long len)
2768 struct mm_struct *mm = current->mm;
2772 if (down_write_killable(&mm->mmap_sem))
2775 ret = do_brk(addr, len);
2776 populate = ((mm->def_flags & VM_LOCKED) != 0);
2777 up_write(&mm->mmap_sem);
2778 if (populate && !ret)
2779 mm_populate(addr, len);
2782 EXPORT_SYMBOL(vm_brk);
2784 /* Release all mmaps. */
2785 void exit_mmap(struct mm_struct *mm)
2787 struct mmu_gather tlb;
2788 struct vm_area_struct *vma;
2789 unsigned long nr_accounted = 0;
2791 /* mm's last user has gone, and its about to be pulled down */
2792 mmu_notifier_release(mm);
2794 if (mm->locked_vm) {
2797 if (vma->vm_flags & VM_LOCKED)
2798 munlock_vma_pages_all(vma);
2806 if (!vma) /* Can happen if dup_mmap() received an OOM */
2811 tlb_gather_mmu(&tlb, mm, 0, -1);
2812 /* update_hiwater_rss(mm) here? but nobody should be looking */
2813 /* Use -1 here to ensure all VMAs in the mm are unmapped */
2814 unmap_vmas(&tlb, vma, 0, -1);
2816 free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
2817 tlb_finish_mmu(&tlb, 0, -1);
2820 * Walk the list again, actually closing and freeing it,
2821 * with preemption enabled, without holding any MM locks.
2824 if (vma->vm_flags & VM_ACCOUNT)
2825 nr_accounted += vma_pages(vma);
2826 vma = remove_vma(vma);
2828 vm_unacct_memory(nr_accounted);
2831 /* Insert vm structure into process list sorted by address
2832 * and into the inode's i_mmap tree. If vm_file is non-NULL
2833 * then i_mmap_rwsem is taken here.
2835 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
2837 struct vm_area_struct *prev;
2838 struct rb_node **rb_link, *rb_parent;
2840 if (find_vma_links(mm, vma->vm_start, vma->vm_end,
2841 &prev, &rb_link, &rb_parent))
2843 if ((vma->vm_flags & VM_ACCOUNT) &&
2844 security_vm_enough_memory_mm(mm, vma_pages(vma)))
2848 * The vm_pgoff of a purely anonymous vma should be irrelevant
2849 * until its first write fault, when page's anon_vma and index
2850 * are set. But now set the vm_pgoff it will almost certainly
2851 * end up with (unless mremap moves it elsewhere before that
2852 * first wfault), so /proc/pid/maps tells a consistent story.
2854 * By setting it to reflect the virtual start address of the
2855 * vma, merges and splits can happen in a seamless way, just
2856 * using the existing file pgoff checks and manipulations.
2857 * Similarly in do_mmap_pgoff and in do_brk.
2859 if (vma_is_anonymous(vma)) {
2860 BUG_ON(vma->anon_vma);
2861 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2864 vma_link(mm, vma, prev, rb_link, rb_parent);
2869 * Copy the vma structure to a new location in the same mm,
2870 * prior to moving page table entries, to effect an mremap move.
2872 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2873 unsigned long addr, unsigned long len, pgoff_t pgoff,
2874 bool *need_rmap_locks)
2876 struct vm_area_struct *vma = *vmap;
2877 unsigned long vma_start = vma->vm_start;
2878 struct mm_struct *mm = vma->vm_mm;
2879 struct vm_area_struct *new_vma, *prev;
2880 struct rb_node **rb_link, *rb_parent;
2881 bool faulted_in_anon_vma = true;
2884 * If anonymous vma has not yet been faulted, update new pgoff
2885 * to match new location, to increase its chance of merging.
2887 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
2888 pgoff = addr >> PAGE_SHIFT;
2889 faulted_in_anon_vma = false;
2892 if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
2893 return NULL; /* should never get here */
2894 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2895 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
2896 vma->vm_userfaultfd_ctx);
2899 * Source vma may have been merged into new_vma
2901 if (unlikely(vma_start >= new_vma->vm_start &&
2902 vma_start < new_vma->vm_end)) {
2904 * The only way we can get a vma_merge with
2905 * self during an mremap is if the vma hasn't
2906 * been faulted in yet and we were allowed to
2907 * reset the dst vma->vm_pgoff to the
2908 * destination address of the mremap to allow
2909 * the merge to happen. mremap must change the
2910 * vm_pgoff linearity between src and dst vmas
2911 * (in turn preventing a vma_merge) to be
2912 * safe. It is only safe to keep the vm_pgoff
2913 * linear if there are no pages mapped yet.
2915 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
2916 *vmap = vma = new_vma;
2918 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
2920 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2924 new_vma->vm_start = addr;
2925 new_vma->vm_end = addr + len;
2926 new_vma->vm_pgoff = pgoff;
2927 if (vma_dup_policy(vma, new_vma))
2929 INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2930 if (anon_vma_clone(new_vma, vma))
2931 goto out_free_mempol;
2932 if (new_vma->vm_file)
2933 get_file(new_vma->vm_file);
2934 if (new_vma->vm_ops && new_vma->vm_ops->open)
2935 new_vma->vm_ops->open(new_vma);
2936 vma_link(mm, new_vma, prev, rb_link, rb_parent);
2937 *need_rmap_locks = false;
2942 mpol_put(vma_policy(new_vma));
2944 kmem_cache_free(vm_area_cachep, new_vma);
2950 * Return true if the calling process may expand its vm space by the passed
2953 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
2955 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
2958 if (is_data_mapping(flags) &&
2959 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
2960 /* Workaround for Valgrind */
2961 if (rlimit(RLIMIT_DATA) == 0 &&
2962 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
2964 if (!ignore_rlimit_data) {
2965 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits or use boot option ignore_rlimit_data.\n",
2966 current->comm, current->pid,
2967 (mm->data_vm + npages) << PAGE_SHIFT,
2968 rlimit(RLIMIT_DATA));
2976 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
2978 mm->total_vm += npages;
2980 if (is_exec_mapping(flags))
2981 mm->exec_vm += npages;
2982 else if (is_stack_mapping(flags))
2983 mm->stack_vm += npages;
2984 else if (is_data_mapping(flags))
2985 mm->data_vm += npages;
2988 static int special_mapping_fault(struct vm_area_struct *vma,
2989 struct vm_fault *vmf);
2992 * Having a close hook prevents vma merging regardless of flags.
2994 static void special_mapping_close(struct vm_area_struct *vma)
2998 static const char *special_mapping_name(struct vm_area_struct *vma)
3000 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3003 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3005 struct vm_special_mapping *sm = new_vma->vm_private_data;
3008 return sm->mremap(sm, new_vma);
3012 static const struct vm_operations_struct special_mapping_vmops = {
3013 .close = special_mapping_close,
3014 .fault = special_mapping_fault,
3015 .mremap = special_mapping_mremap,
3016 .name = special_mapping_name,
3019 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3020 .close = special_mapping_close,
3021 .fault = special_mapping_fault,
3024 static int special_mapping_fault(struct vm_area_struct *vma,
3025 struct vm_fault *vmf)
3028 struct page **pages;
3030 if (vma->vm_ops == &legacy_special_mapping_vmops) {
3031 pages = vma->vm_private_data;
3033 struct vm_special_mapping *sm = vma->vm_private_data;
3036 return sm->fault(sm, vma, vmf);
3041 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3045 struct page *page = *pages;
3051 return VM_FAULT_SIGBUS;
3054 static struct vm_area_struct *__install_special_mapping(
3055 struct mm_struct *mm,
3056 unsigned long addr, unsigned long len,
3057 unsigned long vm_flags, void *priv,
3058 const struct vm_operations_struct *ops)
3061 struct vm_area_struct *vma;
3063 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
3064 if (unlikely(vma == NULL))
3065 return ERR_PTR(-ENOMEM);
3067 INIT_LIST_HEAD(&vma->anon_vma_chain);
3069 vma->vm_start = addr;
3070 vma->vm_end = addr + len;
3072 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3073 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3076 vma->vm_private_data = priv;
3078 ret = insert_vm_struct(mm, vma);
3082 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3084 perf_event_mmap(vma);
3089 kmem_cache_free(vm_area_cachep, vma);
3090 return ERR_PTR(ret);
3093 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3094 const struct vm_special_mapping *sm)
3096 return vma->vm_private_data == sm &&
3097 (vma->vm_ops == &special_mapping_vmops ||
3098 vma->vm_ops == &legacy_special_mapping_vmops);
3102 * Called with mm->mmap_sem held for writing.
3103 * Insert a new vma covering the given region, with the given flags.
3104 * Its pages are supplied by the given array of struct page *.
3105 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3106 * The region past the last page supplied will always produce SIGBUS.
3107 * The array pointer and the pages it points to are assumed to stay alive
3108 * for as long as this mapping might exist.
3110 struct vm_area_struct *_install_special_mapping(
3111 struct mm_struct *mm,
3112 unsigned long addr, unsigned long len,
3113 unsigned long vm_flags, const struct vm_special_mapping *spec)
3115 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3116 &special_mapping_vmops);
3119 int install_special_mapping(struct mm_struct *mm,
3120 unsigned long addr, unsigned long len,
3121 unsigned long vm_flags, struct page **pages)
3123 struct vm_area_struct *vma = __install_special_mapping(
3124 mm, addr, len, vm_flags, (void *)pages,
3125 &legacy_special_mapping_vmops);
3127 return PTR_ERR_OR_ZERO(vma);
3130 static DEFINE_MUTEX(mm_all_locks_mutex);
3132 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3134 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3136 * The LSB of head.next can't change from under us
3137 * because we hold the mm_all_locks_mutex.
3139 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
3141 * We can safely modify head.next after taking the
3142 * anon_vma->root->rwsem. If some other vma in this mm shares
3143 * the same anon_vma we won't take it again.
3145 * No need of atomic instructions here, head.next
3146 * can't change from under us thanks to the
3147 * anon_vma->root->rwsem.
3149 if (__test_and_set_bit(0, (unsigned long *)
3150 &anon_vma->root->rb_root.rb_node))
3155 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3157 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3159 * AS_MM_ALL_LOCKS can't change from under us because
3160 * we hold the mm_all_locks_mutex.
3162 * Operations on ->flags have to be atomic because
3163 * even if AS_MM_ALL_LOCKS is stable thanks to the
3164 * mm_all_locks_mutex, there may be other cpus
3165 * changing other bitflags in parallel to us.
3167 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3169 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);
3174 * This operation locks against the VM for all pte/vma/mm related
3175 * operations that could ever happen on a certain mm. This includes
3176 * vmtruncate, try_to_unmap, and all page faults.
3178 * The caller must take the mmap_sem in write mode before calling
3179 * mm_take_all_locks(). The caller isn't allowed to release the
3180 * mmap_sem until mm_drop_all_locks() returns.
3182 * mmap_sem in write mode is required in order to block all operations
3183 * that could modify pagetables and free pages without need of
3184 * altering the vma layout. It's also needed in write mode to avoid new
3185 * anon_vmas to be associated with existing vmas.
3187 * A single task can't take more than one mm_take_all_locks() in a row
3188 * or it would deadlock.
3190 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3191 * mapping->flags avoid to take the same lock twice, if more than one
3192 * vma in this mm is backed by the same anon_vma or address_space.
3194 * We take locks in following order, accordingly to comment at beginning
3196 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3198 * - all i_mmap_rwsem locks;
3199 * - all anon_vma->rwseml
3201 * We can take all locks within these types randomly because the VM code
3202 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3203 * mm_all_locks_mutex.
3205 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3206 * that may have to take thousand of locks.
3208 * mm_take_all_locks() can fail if it's interrupted by signals.
3210 int mm_take_all_locks(struct mm_struct *mm)
3212 struct vm_area_struct *vma;
3213 struct anon_vma_chain *avc;
3215 BUG_ON(down_read_trylock(&mm->mmap_sem));
3217 mutex_lock(&mm_all_locks_mutex);
3219 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3220 if (signal_pending(current))
3222 if (vma->vm_file && vma->vm_file->f_mapping &&
3223 is_vm_hugetlb_page(vma))
3224 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3227 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3228 if (signal_pending(current))
3230 if (vma->vm_file && vma->vm_file->f_mapping &&
3231 !is_vm_hugetlb_page(vma))
3232 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3235 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3236 if (signal_pending(current))
3239 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3240 vm_lock_anon_vma(mm, avc->anon_vma);
3246 mm_drop_all_locks(mm);
3250 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3252 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3254 * The LSB of head.next can't change to 0 from under
3255 * us because we hold the mm_all_locks_mutex.
3257 * We must however clear the bitflag before unlocking
3258 * the vma so the users using the anon_vma->rb_root will
3259 * never see our bitflag.
3261 * No need of atomic instructions here, head.next
3262 * can't change from under us until we release the
3263 * anon_vma->root->rwsem.
3265 if (!__test_and_clear_bit(0, (unsigned long *)
3266 &anon_vma->root->rb_root.rb_node))
3268 anon_vma_unlock_write(anon_vma);
3272 static void vm_unlock_mapping(struct address_space *mapping)
3274 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3276 * AS_MM_ALL_LOCKS can't change to 0 from under us
3277 * because we hold the mm_all_locks_mutex.
3279 i_mmap_unlock_write(mapping);
3280 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3287 * The mmap_sem cannot be released by the caller until
3288 * mm_drop_all_locks() returns.
3290 void mm_drop_all_locks(struct mm_struct *mm)
3292 struct vm_area_struct *vma;
3293 struct anon_vma_chain *avc;
3295 BUG_ON(down_read_trylock(&mm->mmap_sem));
3296 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3298 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3300 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3301 vm_unlock_anon_vma(avc->anon_vma);
3302 if (vma->vm_file && vma->vm_file->f_mapping)
3303 vm_unlock_mapping(vma->vm_file->f_mapping);
3306 mutex_unlock(&mm_all_locks_mutex);
3310 * initialise the VMA slab
3312 void __init mmap_init(void)
3316 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3321 * Initialise sysctl_user_reserve_kbytes.
3323 * This is intended to prevent a user from starting a single memory hogging
3324 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3327 * The default value is min(3% of free memory, 128MB)
3328 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3330 static int init_user_reserve(void)
3332 unsigned long free_kbytes;
3334 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3336 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3339 subsys_initcall(init_user_reserve);
3342 * Initialise sysctl_admin_reserve_kbytes.
3344 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3345 * to log in and kill a memory hogging process.
3347 * Systems with more than 256MB will reserve 8MB, enough to recover
3348 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3349 * only reserve 3% of free pages by default.
3351 static int init_admin_reserve(void)
3353 unsigned long free_kbytes;
3355 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3357 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3360 subsys_initcall(init_admin_reserve);
3363 * Reinititalise user and admin reserves if memory is added or removed.
3365 * The default user reserve max is 128MB, and the default max for the
3366 * admin reserve is 8MB. These are usually, but not always, enough to
3367 * enable recovery from a memory hogging process using login/sshd, a shell,
3368 * and tools like top. It may make sense to increase or even disable the
3369 * reserve depending on the existence of swap or variations in the recovery
3370 * tools. So, the admin may have changed them.
3372 * If memory is added and the reserves have been eliminated or increased above
3373 * the default max, then we'll trust the admin.
3375 * If memory is removed and there isn't enough free memory, then we
3376 * need to reset the reserves.
3378 * Otherwise keep the reserve set by the admin.
3380 static int reserve_mem_notifier(struct notifier_block *nb,
3381 unsigned long action, void *data)
3383 unsigned long tmp, free_kbytes;
3387 /* Default max is 128MB. Leave alone if modified by operator. */
3388 tmp = sysctl_user_reserve_kbytes;
3389 if (0 < tmp && tmp < (1UL << 17))
3390 init_user_reserve();
3392 /* Default max is 8MB. Leave alone if modified by operator. */
3393 tmp = sysctl_admin_reserve_kbytes;
3394 if (0 < tmp && tmp < (1UL << 13))
3395 init_admin_reserve();
3399 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3401 if (sysctl_user_reserve_kbytes > free_kbytes) {
3402 init_user_reserve();
3403 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3404 sysctl_user_reserve_kbytes);
3407 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3408 init_admin_reserve();
3409 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3410 sysctl_admin_reserve_kbytes);
3419 static struct notifier_block reserve_mem_nb = {
3420 .notifier_call = reserve_mem_notifier,
3423 static int __meminit init_reserve_notifier(void)
3425 if (register_hotmemory_notifier(&reserve_mem_nb))
3426 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3430 subsys_initcall(init_reserve_notifier);