aufs: tiny, lockdep sub-classing
[zen-stable.git] / mm / mmap.c
blobc2f8898b858b4cd50e1d9474daf9b8aa044186c4
1 /*
2 * mm/mmap.c
4 * Written by obz.
6 * Address space accounting code <alan@lxorguk.ukuu.org.uk>
7 */
9 #include <linux/slab.h>
10 #include <linux/backing-dev.h>
11 #include <linux/mm.h>
12 #include <linux/shm.h>
13 #include <linux/mman.h>
14 #include <linux/pagemap.h>
15 #include <linux/swap.h>
16 #include <linux/syscalls.h>
17 #include <linux/capability.h>
18 #include <linux/init.h>
19 #include <linux/file.h>
20 #include <linux/fs.h>
21 #include <linux/personality.h>
22 #include <linux/security.h>
23 #include <linux/hugetlb.h>
24 #include <linux/profile.h>
25 #include <linux/export.h>
26 #include <linux/mount.h>
27 #include <linux/mempolicy.h>
28 #include <linux/rmap.h>
29 #include <linux/mmu_notifier.h>
30 #include <linux/perf_event.h>
31 #include <linux/audit.h>
32 #include <linux/khugepaged.h>
34 #include <asm/uaccess.h>
35 #include <asm/cacheflush.h>
36 #include <asm/tlb.h>
37 #include <asm/mmu_context.h>
39 #include "internal.h"
41 #ifndef arch_mmap_check
42 #define arch_mmap_check(addr, len, flags) (0)
43 #endif
45 #ifndef arch_rebalance_pgtables
46 #define arch_rebalance_pgtables(addr, len) (addr)
47 #endif
49 static void unmap_region(struct mm_struct *mm,
50 struct vm_area_struct *vma, struct vm_area_struct *prev,
51 unsigned long start, unsigned long end);
54 * WARNING: the debugging will use recursive algorithms so never enable this
55 * unless you know what you are doing.
57 #undef DEBUG_MM_RB
59 /* description of effects of mapping type and prot in current implementation.
60 * this is due to the limited x86 page protection hardware. The expected
61 * behavior is in parens:
63 * map_type prot
64 * PROT_NONE PROT_READ PROT_WRITE PROT_EXEC
65 * MAP_SHARED r: (no) no r: (yes) yes r: (no) yes r: (no) yes
66 * w: (no) no w: (no) no w: (yes) yes w: (no) no
67 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
69 * MAP_PRIVATE r: (no) no r: (yes) yes r: (no) yes r: (no) yes
70 * w: (no) no w: (no) no w: (copy) copy w: (no) no
71 * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
74 pgprot_t protection_map[16] = {
75 __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
76 __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
79 pgprot_t vm_get_page_prot(unsigned long vm_flags)
81 return __pgprot(pgprot_val(protection_map[vm_flags &
82 (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
83 pgprot_val(arch_vm_get_page_prot(vm_flags)));
85 EXPORT_SYMBOL(vm_get_page_prot);
87 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS; /* heuristic overcommit */
88 int sysctl_overcommit_ratio __read_mostly = 50; /* default is 50% */
89 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
91 * Make sure vm_committed_as in one cacheline and not cacheline shared with
92 * other variables. It can be updated by several CPUs frequently.
94 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
97 * Check that a process has enough memory to allocate a new virtual
98 * mapping. 0 means there is enough memory for the allocation to
99 * succeed and -ENOMEM implies there is not.
101 * We currently support three overcommit policies, which are set via the
102 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
104 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
105 * Additional code 2002 Jul 20 by Robert Love.
107 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
109 * Note this is a helper function intended to be used by LSMs which
110 * wish to use this logic.
112 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
114 unsigned long free, allowed;
116 vm_acct_memory(pages);
119 * Sometimes we want to use more memory than we have
121 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
122 return 0;
124 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
125 free = global_page_state(NR_FREE_PAGES);
126 free += global_page_state(NR_FILE_PAGES);
129 * shmem pages shouldn't be counted as free in this
130 * case, they can't be purged, only swapped out, and
131 * that won't affect the overall amount of available
132 * memory in the system.
134 free -= global_page_state(NR_SHMEM);
136 free += nr_swap_pages;
139 * Any slabs which are created with the
140 * SLAB_RECLAIM_ACCOUNT flag claim to have contents
141 * which are reclaimable, under pressure. The dentry
142 * cache and most inode caches should fall into this
144 free += global_page_state(NR_SLAB_RECLAIMABLE);
147 * Leave reserved pages. The pages are not for anonymous pages.
149 if (free <= totalreserve_pages)
150 goto error;
151 else
152 free -= totalreserve_pages;
155 * Leave the last 3% for root
157 if (!cap_sys_admin)
158 free -= free / 32;
160 if (free > pages)
161 return 0;
163 goto error;
166 allowed = (totalram_pages - hugetlb_total_pages())
167 * sysctl_overcommit_ratio / 100;
169 * Leave the last 3% for root
171 if (!cap_sys_admin)
172 allowed -= allowed / 32;
173 allowed += total_swap_pages;
175 /* Don't let a single process grow too big:
176 leave 3% of the size of this process for other processes */
177 if (mm)
178 allowed -= mm->total_vm / 32;
180 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
181 return 0;
182 error:
183 vm_unacct_memory(pages);
185 return -ENOMEM;
189 * Requires inode->i_mapping->i_mmap_mutex
191 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
192 struct file *file, struct address_space *mapping)
194 if (vma->vm_flags & VM_DENYWRITE)
195 atomic_inc(&file->f_path.dentry->d_inode->i_writecount);
196 if (vma->vm_flags & VM_SHARED)
197 mapping->i_mmap_writable--;
199 flush_dcache_mmap_lock(mapping);
200 if (unlikely(vma->vm_flags & VM_NONLINEAR))
201 list_del_init(&vma->shared.vm_set.list);
202 else
203 vma_prio_tree_remove(vma, &mapping->i_mmap);
204 flush_dcache_mmap_unlock(mapping);
208 * Unlink a file-based vm structure from its prio_tree, to hide
209 * vma from rmap and vmtruncate before freeing its page tables.
211 void unlink_file_vma(struct vm_area_struct *vma)
213 struct file *file = vma->vm_file;
215 if (file) {
216 struct address_space *mapping = file->f_mapping;
217 mutex_lock(&mapping->i_mmap_mutex);
218 __remove_shared_vm_struct(vma, file, mapping);
219 mutex_unlock(&mapping->i_mmap_mutex);
224 * Close a vm structure and free it, returning the next.
226 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
228 struct vm_area_struct *next = vma->vm_next;
230 might_sleep();
231 if (vma->vm_ops && vma->vm_ops->close)
232 vma->vm_ops->close(vma);
233 if (vma->vm_file) {
234 fput(vma->vm_file);
235 if (vma->vm_prfile)
236 fput(vma->vm_prfile);
237 if (vma->vm_flags & VM_EXECUTABLE)
238 removed_exe_file_vma(vma->vm_mm);
240 mpol_put(vma_policy(vma));
241 kmem_cache_free(vm_area_cachep, vma);
242 return next;
245 SYSCALL_DEFINE1(brk, unsigned long, brk)
247 unsigned long rlim, retval;
248 unsigned long newbrk, oldbrk;
249 struct mm_struct *mm = current->mm;
250 unsigned long min_brk;
252 down_write(&mm->mmap_sem);
254 #ifdef CONFIG_COMPAT_BRK
256 * CONFIG_COMPAT_BRK can still be overridden by setting
257 * randomize_va_space to 2, which will still cause mm->start_brk
258 * to be arbitrarily shifted
260 if (current->brk_randomized)
261 min_brk = mm->start_brk;
262 else
263 min_brk = mm->end_data;
264 #else
265 min_brk = mm->start_brk;
266 #endif
267 if (brk < min_brk)
268 goto out;
271 * Check against rlimit here. If this check is done later after the test
272 * of oldbrk with newbrk then it can escape the test and let the data
273 * segment grow beyond its set limit the in case where the limit is
274 * not page aligned -Ram Gupta
276 rlim = rlimit(RLIMIT_DATA);
277 if (rlim < RLIM_INFINITY && (brk - mm->start_brk) +
278 (mm->end_data - mm->start_data) > rlim)
279 goto out;
281 newbrk = PAGE_ALIGN(brk);
282 oldbrk = PAGE_ALIGN(mm->brk);
283 if (oldbrk == newbrk)
284 goto set_brk;
286 /* Always allow shrinking brk. */
287 if (brk <= mm->brk) {
288 if (!do_munmap(mm, newbrk, oldbrk-newbrk))
289 goto set_brk;
290 goto out;
293 /* Check against existing mmap mappings. */
294 if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE))
295 goto out;
297 /* Ok, looks good - let it rip. */
298 if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
299 goto out;
300 set_brk:
301 mm->brk = brk;
302 out:
303 retval = mm->brk;
304 up_write(&mm->mmap_sem);
305 return retval;
308 #ifdef DEBUG_MM_RB
309 static int browse_rb(struct rb_root *root)
311 int i = 0, j;
312 struct rb_node *nd, *pn = NULL;
313 unsigned long prev = 0, pend = 0;
315 for (nd = rb_first(root); nd; nd = rb_next(nd)) {
316 struct vm_area_struct *vma;
317 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
318 if (vma->vm_start < prev)
319 printk("vm_start %lx prev %lx\n", vma->vm_start, prev), i = -1;
320 if (vma->vm_start < pend)
321 printk("vm_start %lx pend %lx\n", vma->vm_start, pend);
322 if (vma->vm_start > vma->vm_end)
323 printk("vm_end %lx < vm_start %lx\n", vma->vm_end, vma->vm_start);
324 i++;
325 pn = nd;
326 prev = vma->vm_start;
327 pend = vma->vm_end;
329 j = 0;
330 for (nd = pn; nd; nd = rb_prev(nd)) {
331 j++;
333 if (i != j)
334 printk("backwards %d, forwards %d\n", j, i), i = 0;
335 return i;
338 void validate_mm(struct mm_struct *mm)
340 int bug = 0;
341 int i = 0;
342 struct vm_area_struct *tmp = mm->mmap;
343 while (tmp) {
344 tmp = tmp->vm_next;
345 i++;
347 if (i != mm->map_count)
348 printk("map_count %d vm_next %d\n", mm->map_count, i), bug = 1;
349 i = browse_rb(&mm->mm_rb);
350 if (i != mm->map_count)
351 printk("map_count %d rb %d\n", mm->map_count, i), bug = 1;
352 BUG_ON(bug);
354 #else
355 #define validate_mm(mm) do { } while (0)
356 #endif
358 static struct vm_area_struct *
359 find_vma_prepare(struct mm_struct *mm, unsigned long addr,
360 struct vm_area_struct **pprev, struct rb_node ***rb_link,
361 struct rb_node ** rb_parent)
363 struct vm_area_struct * vma;
364 struct rb_node ** __rb_link, * __rb_parent, * rb_prev;
366 __rb_link = &mm->mm_rb.rb_node;
367 rb_prev = __rb_parent = NULL;
368 vma = NULL;
370 while (*__rb_link) {
371 struct vm_area_struct *vma_tmp;
373 __rb_parent = *__rb_link;
374 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
376 if (vma_tmp->vm_end > addr) {
377 vma = vma_tmp;
378 if (vma_tmp->vm_start <= addr)
379 break;
380 __rb_link = &__rb_parent->rb_left;
381 } else {
382 rb_prev = __rb_parent;
383 __rb_link = &__rb_parent->rb_right;
387 *pprev = NULL;
388 if (rb_prev)
389 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
390 *rb_link = __rb_link;
391 *rb_parent = __rb_parent;
392 return vma;
395 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
396 struct rb_node **rb_link, struct rb_node *rb_parent)
398 rb_link_node(&vma->vm_rb, rb_parent, rb_link);
399 rb_insert_color(&vma->vm_rb, &mm->mm_rb);
402 static void __vma_link_file(struct vm_area_struct *vma)
404 struct file *file;
406 file = vma->vm_file;
407 if (file) {
408 struct address_space *mapping = file->f_mapping;
410 if (vma->vm_flags & VM_DENYWRITE)
411 atomic_dec(&file->f_path.dentry->d_inode->i_writecount);
412 if (vma->vm_flags & VM_SHARED)
413 mapping->i_mmap_writable++;
415 flush_dcache_mmap_lock(mapping);
416 if (unlikely(vma->vm_flags & VM_NONLINEAR))
417 vma_nonlinear_insert(vma, &mapping->i_mmap_nonlinear);
418 else
419 vma_prio_tree_insert(vma, &mapping->i_mmap);
420 flush_dcache_mmap_unlock(mapping);
424 static void
425 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
426 struct vm_area_struct *prev, struct rb_node **rb_link,
427 struct rb_node *rb_parent)
429 __vma_link_list(mm, vma, prev, rb_parent);
430 __vma_link_rb(mm, vma, rb_link, rb_parent);
433 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
434 struct vm_area_struct *prev, struct rb_node **rb_link,
435 struct rb_node *rb_parent)
437 struct address_space *mapping = NULL;
439 if (vma->vm_file)
440 mapping = vma->vm_file->f_mapping;
442 if (mapping)
443 mutex_lock(&mapping->i_mmap_mutex);
445 __vma_link(mm, vma, prev, rb_link, rb_parent);
446 __vma_link_file(vma);
448 if (mapping)
449 mutex_unlock(&mapping->i_mmap_mutex);
451 mm->map_count++;
452 validate_mm(mm);
456 * Helper for vma_adjust in the split_vma insert case:
457 * insert vm structure into list and rbtree and anon_vma,
458 * but it has already been inserted into prio_tree earlier.
460 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
462 struct vm_area_struct *__vma, *prev;
463 struct rb_node **rb_link, *rb_parent;
465 __vma = find_vma_prepare(mm, vma->vm_start,&prev, &rb_link, &rb_parent);
466 BUG_ON(__vma && __vma->vm_start < vma->vm_end);
467 __vma_link(mm, vma, prev, rb_link, rb_parent);
468 mm->map_count++;
471 static inline void
472 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
473 struct vm_area_struct *prev)
475 struct vm_area_struct *next = vma->vm_next;
477 prev->vm_next = next;
478 if (next)
479 next->vm_prev = prev;
480 rb_erase(&vma->vm_rb, &mm->mm_rb);
481 if (mm->mmap_cache == vma)
482 mm->mmap_cache = prev;
486 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
487 * is already present in an i_mmap tree without adjusting the tree.
488 * The following helper function should be used when such adjustments
489 * are necessary. The "insert" vma (if any) is to be inserted
490 * before we drop the necessary locks.
492 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
493 unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
495 struct mm_struct *mm = vma->vm_mm;
496 struct vm_area_struct *next = vma->vm_next;
497 struct vm_area_struct *importer = NULL;
498 struct address_space *mapping = NULL;
499 struct prio_tree_root *root = NULL;
500 struct anon_vma *anon_vma = NULL;
501 struct file *file = vma->vm_file;
502 long adjust_next = 0;
503 int remove_next = 0;
505 if (next && !insert) {
506 struct vm_area_struct *exporter = NULL;
508 if (end >= next->vm_end) {
510 * vma expands, overlapping all the next, and
511 * perhaps the one after too (mprotect case 6).
513 again: remove_next = 1 + (end > next->vm_end);
514 end = next->vm_end;
515 exporter = next;
516 importer = vma;
517 } else if (end > next->vm_start) {
519 * vma expands, overlapping part of the next:
520 * mprotect case 5 shifting the boundary up.
522 adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
523 exporter = next;
524 importer = vma;
525 } else if (end < vma->vm_end) {
527 * vma shrinks, and !insert tells it's not
528 * split_vma inserting another: so it must be
529 * mprotect case 4 shifting the boundary down.
531 adjust_next = - ((vma->vm_end - end) >> PAGE_SHIFT);
532 exporter = vma;
533 importer = next;
537 * Easily overlooked: when mprotect shifts the boundary,
538 * make sure the expanding vma has anon_vma set if the
539 * shrinking vma had, to cover any anon pages imported.
541 if (exporter && exporter->anon_vma && !importer->anon_vma) {
542 if (anon_vma_clone(importer, exporter))
543 return -ENOMEM;
544 importer->anon_vma = exporter->anon_vma;
548 if (file) {
549 mapping = file->f_mapping;
550 if (!(vma->vm_flags & VM_NONLINEAR))
551 root = &mapping->i_mmap;
552 mutex_lock(&mapping->i_mmap_mutex);
553 if (insert) {
555 * Put into prio_tree now, so instantiated pages
556 * are visible to arm/parisc __flush_dcache_page
557 * throughout; but we cannot insert into address
558 * space until vma start or end is updated.
560 __vma_link_file(insert);
564 vma_adjust_trans_huge(vma, start, end, adjust_next);
567 * When changing only vma->vm_end, we don't really need anon_vma
568 * lock. This is a fairly rare case by itself, but the anon_vma
569 * lock may be shared between many sibling processes. Skipping
570 * the lock for brk adjustments makes a difference sometimes.
572 if (vma->anon_vma && (importer || start != vma->vm_start)) {
573 anon_vma = vma->anon_vma;
574 anon_vma_lock(anon_vma);
577 if (root) {
578 flush_dcache_mmap_lock(mapping);
579 vma_prio_tree_remove(vma, root);
580 if (adjust_next)
581 vma_prio_tree_remove(next, root);
584 vma->vm_start = start;
585 vma->vm_end = end;
586 vma->vm_pgoff = pgoff;
587 if (adjust_next) {
588 next->vm_start += adjust_next << PAGE_SHIFT;
589 next->vm_pgoff += adjust_next;
592 if (root) {
593 if (adjust_next)
594 vma_prio_tree_insert(next, root);
595 vma_prio_tree_insert(vma, root);
596 flush_dcache_mmap_unlock(mapping);
599 if (remove_next) {
601 * vma_merge has merged next into vma, and needs
602 * us to remove next before dropping the locks.
604 __vma_unlink(mm, next, vma);
605 if (file)
606 __remove_shared_vm_struct(next, file, mapping);
607 } else if (insert) {
609 * split_vma has split insert from vma, and needs
610 * us to insert it before dropping the locks
611 * (it may either follow vma or precede it).
613 __insert_vm_struct(mm, insert);
616 if (anon_vma)
617 anon_vma_unlock(anon_vma);
618 if (mapping)
619 mutex_unlock(&mapping->i_mmap_mutex);
621 if (remove_next) {
622 if (file) {
623 fput(file);
624 if (vma->vm_prfile)
625 fput(vma->vm_prfile);
626 if (next->vm_flags & VM_EXECUTABLE)
627 removed_exe_file_vma(mm);
629 if (next->anon_vma)
630 anon_vma_merge(vma, next);
631 mm->map_count--;
632 mpol_put(vma_policy(next));
633 kmem_cache_free(vm_area_cachep, next);
635 * In mprotect's case 6 (see comments on vma_merge),
636 * we must remove another next too. It would clutter
637 * up the code too much to do both in one go.
639 if (remove_next == 2) {
640 next = vma->vm_next;
641 goto again;
645 validate_mm(mm);
647 return 0;
651 * If the vma has a ->close operation then the driver probably needs to release
652 * per-vma resources, so we don't attempt to merge those.
654 static inline int is_mergeable_vma(struct vm_area_struct *vma,
655 struct file *file, unsigned long vm_flags)
657 /* VM_CAN_NONLINEAR may get set later by f_op->mmap() */
658 if ((vma->vm_flags ^ vm_flags) & ~VM_CAN_NONLINEAR)
659 return 0;
660 if (vma->vm_file != file)
661 return 0;
662 if (vma->vm_ops && vma->vm_ops->close)
663 return 0;
664 return 1;
667 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
668 struct anon_vma *anon_vma2,
669 struct vm_area_struct *vma)
672 * The list_is_singular() test is to avoid merging VMA cloned from
673 * parents. This can improve scalability caused by anon_vma lock.
675 if ((!anon_vma1 || !anon_vma2) && (!vma ||
676 list_is_singular(&vma->anon_vma_chain)))
677 return 1;
678 return anon_vma1 == anon_vma2;
682 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
683 * in front of (at a lower virtual address and file offset than) the vma.
685 * We cannot merge two vmas if they have differently assigned (non-NULL)
686 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
688 * We don't check here for the merged mmap wrapping around the end of pagecache
689 * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
690 * wrap, nor mmaps which cover the final page at index -1UL.
692 static int
693 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
694 struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
696 if (is_mergeable_vma(vma, file, vm_flags) &&
697 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
698 if (vma->vm_pgoff == vm_pgoff)
699 return 1;
701 return 0;
705 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
706 * beyond (at a higher virtual address and file offset than) the vma.
708 * We cannot merge two vmas if they have differently assigned (non-NULL)
709 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
711 static int
712 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
713 struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
715 if (is_mergeable_vma(vma, file, vm_flags) &&
716 is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
717 pgoff_t vm_pglen;
718 vm_pglen = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
719 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
720 return 1;
722 return 0;
726 * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
727 * whether that can be merged with its predecessor or its successor.
728 * Or both (it neatly fills a hole).
730 * In most cases - when called for mmap, brk or mremap - [addr,end) is
731 * certain not to be mapped by the time vma_merge is called; but when
732 * called for mprotect, it is certain to be already mapped (either at
733 * an offset within prev, or at the start of next), and the flags of
734 * this area are about to be changed to vm_flags - and the no-change
735 * case has already been eliminated.
737 * The following mprotect cases have to be considered, where AAAA is
738 * the area passed down from mprotect_fixup, never extending beyond one
739 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
741 * AAAA AAAA AAAA AAAA
742 * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX
743 * cannot merge might become might become might become
744 * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or
745 * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or
746 * mremap move: PPPPNNNNNNNN 8
747 * AAAA
748 * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN
749 * might become case 1 below case 2 below case 3 below
751 * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
752 * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
754 struct vm_area_struct *vma_merge(struct mm_struct *mm,
755 struct vm_area_struct *prev, unsigned long addr,
756 unsigned long end, unsigned long vm_flags,
757 struct anon_vma *anon_vma, struct file *file,
758 pgoff_t pgoff, struct mempolicy *policy)
760 pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
761 struct vm_area_struct *area, *next;
762 int err;
765 * We later require that vma->vm_flags == vm_flags,
766 * so this tests vma->vm_flags & VM_SPECIAL, too.
768 if (vm_flags & VM_SPECIAL)
769 return NULL;
771 if (prev)
772 next = prev->vm_next;
773 else
774 next = mm->mmap;
775 area = next;
776 if (next && next->vm_end == end) /* cases 6, 7, 8 */
777 next = next->vm_next;
780 * Can it merge with the predecessor?
782 if (prev && prev->vm_end == addr &&
783 mpol_equal(vma_policy(prev), policy) &&
784 can_vma_merge_after(prev, vm_flags,
785 anon_vma, file, pgoff)) {
787 * OK, it can. Can we now merge in the successor as well?
789 if (next && end == next->vm_start &&
790 mpol_equal(policy, vma_policy(next)) &&
791 can_vma_merge_before(next, vm_flags,
792 anon_vma, file, pgoff+pglen) &&
793 is_mergeable_anon_vma(prev->anon_vma,
794 next->anon_vma, NULL)) {
795 /* cases 1, 6 */
796 err = vma_adjust(prev, prev->vm_start,
797 next->vm_end, prev->vm_pgoff, NULL);
798 } else /* cases 2, 5, 7 */
799 err = vma_adjust(prev, prev->vm_start,
800 end, prev->vm_pgoff, NULL);
801 if (err)
802 return NULL;
803 khugepaged_enter_vma_merge(prev);
804 return prev;
808 * Can this new request be merged in front of next?
810 if (next && end == next->vm_start &&
811 mpol_equal(policy, vma_policy(next)) &&
812 can_vma_merge_before(next, vm_flags,
813 anon_vma, file, pgoff+pglen)) {
814 if (prev && addr < prev->vm_end) /* case 4 */
815 err = vma_adjust(prev, prev->vm_start,
816 addr, prev->vm_pgoff, NULL);
817 else /* cases 3, 8 */
818 err = vma_adjust(area, addr, next->vm_end,
819 next->vm_pgoff - pglen, NULL);
820 if (err)
821 return NULL;
822 khugepaged_enter_vma_merge(area);
823 return area;
826 return NULL;
830 * Rough compatbility check to quickly see if it's even worth looking
831 * at sharing an anon_vma.
833 * They need to have the same vm_file, and the flags can only differ
834 * in things that mprotect may change.
836 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
837 * we can merge the two vma's. For example, we refuse to merge a vma if
838 * there is a vm_ops->close() function, because that indicates that the
839 * driver is doing some kind of reference counting. But that doesn't
840 * really matter for the anon_vma sharing case.
842 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
844 return a->vm_end == b->vm_start &&
845 mpol_equal(vma_policy(a), vma_policy(b)) &&
846 a->vm_file == b->vm_file &&
847 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC)) &&
848 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
852 * Do some basic sanity checking to see if we can re-use the anon_vma
853 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
854 * the same as 'old', the other will be the new one that is trying
855 * to share the anon_vma.
857 * NOTE! This runs with mm_sem held for reading, so it is possible that
858 * the anon_vma of 'old' is concurrently in the process of being set up
859 * by another page fault trying to merge _that_. But that's ok: if it
860 * is being set up, that automatically means that it will be a singleton
861 * acceptable for merging, so we can do all of this optimistically. But
862 * we do that ACCESS_ONCE() to make sure that we never re-load the pointer.
864 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
865 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
866 * is to return an anon_vma that is "complex" due to having gone through
867 * a fork).
869 * We also make sure that the two vma's are compatible (adjacent,
870 * and with the same memory policies). That's all stable, even with just
871 * a read lock on the mm_sem.
873 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
875 if (anon_vma_compatible(a, b)) {
876 struct anon_vma *anon_vma = ACCESS_ONCE(old->anon_vma);
878 if (anon_vma && list_is_singular(&old->anon_vma_chain))
879 return anon_vma;
881 return NULL;
885 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
886 * neighbouring vmas for a suitable anon_vma, before it goes off
887 * to allocate a new anon_vma. It checks because a repetitive
888 * sequence of mprotects and faults may otherwise lead to distinct
889 * anon_vmas being allocated, preventing vma merge in subsequent
890 * mprotect.
892 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
894 struct anon_vma *anon_vma;
895 struct vm_area_struct *near;
897 near = vma->vm_next;
898 if (!near)
899 goto try_prev;
901 anon_vma = reusable_anon_vma(near, vma, near);
902 if (anon_vma)
903 return anon_vma;
904 try_prev:
905 near = vma->vm_prev;
906 if (!near)
907 goto none;
909 anon_vma = reusable_anon_vma(near, near, vma);
910 if (anon_vma)
911 return anon_vma;
912 none:
914 * There's no absolute need to look only at touching neighbours:
915 * we could search further afield for "compatible" anon_vmas.
916 * But it would probably just be a waste of time searching,
917 * or lead to too many vmas hanging off the same anon_vma.
918 * We're trying to allow mprotect remerging later on,
919 * not trying to minimize memory used for anon_vmas.
921 return NULL;
924 #ifdef CONFIG_PROC_FS
925 void vm_stat_account(struct mm_struct *mm, unsigned long flags,
926 struct file *file, long pages)
928 const unsigned long stack_flags
929 = VM_STACK_FLAGS & (VM_GROWSUP|VM_GROWSDOWN);
931 if (file) {
932 mm->shared_vm += pages;
933 if ((flags & (VM_EXEC|VM_WRITE)) == VM_EXEC)
934 mm->exec_vm += pages;
935 } else if (flags & stack_flags)
936 mm->stack_vm += pages;
937 if (flags & (VM_RESERVED|VM_IO))
938 mm->reserved_vm += pages;
940 #endif /* CONFIG_PROC_FS */
943 * The caller must hold down_write(&current->mm->mmap_sem).
946 unsigned long do_mmap_pgoff(struct file *file, unsigned long addr,
947 unsigned long len, unsigned long prot,
948 unsigned long flags, unsigned long pgoff)
950 struct mm_struct * mm = current->mm;
951 struct inode *inode;
952 vm_flags_t vm_flags;
953 int error;
954 unsigned long reqprot = prot;
957 * Does the application expect PROT_READ to imply PROT_EXEC?
959 * (the exception is when the underlying filesystem is noexec
960 * mounted, in which case we dont add PROT_EXEC.)
962 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
963 if (!(file && (file->f_path.mnt->mnt_flags & MNT_NOEXEC)))
964 prot |= PROT_EXEC;
966 if (!len)
967 return -EINVAL;
969 if (!(flags & MAP_FIXED))
970 addr = round_hint_to_min(addr);
972 /* Careful about overflows.. */
973 len = PAGE_ALIGN(len);
974 if (!len)
975 return -ENOMEM;
977 /* offset overflow? */
978 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
979 return -EOVERFLOW;
981 /* Too many mappings? */
982 if (mm->map_count > sysctl_max_map_count)
983 return -ENOMEM;
985 /* Obtain the address to map to. we verify (or select) it and ensure
986 * that it represents a valid section of the address space.
988 addr = get_unmapped_area(file, addr, len, pgoff, flags);
989 if (addr & ~PAGE_MASK)
990 return addr;
992 /* Do simple checking here so the lower-level routines won't have
993 * to. we assume access permissions have been handled by the open
994 * of the memory object, so we don't do any here.
996 vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
997 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
999 if (flags & MAP_LOCKED)
1000 if (!can_do_mlock())
1001 return -EPERM;
1003 /* mlock MCL_FUTURE? */
1004 if (vm_flags & VM_LOCKED) {
1005 unsigned long locked, lock_limit;
1006 locked = len >> PAGE_SHIFT;
1007 locked += mm->locked_vm;
1008 lock_limit = rlimit(RLIMIT_MEMLOCK);
1009 lock_limit >>= PAGE_SHIFT;
1010 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1011 return -EAGAIN;
1014 inode = file ? file->f_path.dentry->d_inode : NULL;
1016 if (file) {
1017 switch (flags & MAP_TYPE) {
1018 case MAP_SHARED:
1019 if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1020 return -EACCES;
1023 * Make sure we don't allow writing to an append-only
1024 * file..
1026 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1027 return -EACCES;
1030 * Make sure there are no mandatory locks on the file.
1032 if (locks_verify_locked(inode))
1033 return -EAGAIN;
1035 vm_flags |= VM_SHARED | VM_MAYSHARE;
1036 if (!(file->f_mode & FMODE_WRITE))
1037 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1039 /* fall through */
1040 case MAP_PRIVATE:
1041 if (!(file->f_mode & FMODE_READ))
1042 return -EACCES;
1043 if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
1044 if (vm_flags & VM_EXEC)
1045 return -EPERM;
1046 vm_flags &= ~VM_MAYEXEC;
1049 if (!file->f_op || !file->f_op->mmap)
1050 return -ENODEV;
1051 break;
1053 default:
1054 return -EINVAL;
1056 } else {
1057 switch (flags & MAP_TYPE) {
1058 case MAP_SHARED:
1060 * Ignore pgoff.
1062 pgoff = 0;
1063 vm_flags |= VM_SHARED | VM_MAYSHARE;
1064 break;
1065 case MAP_PRIVATE:
1067 * Set pgoff according to addr for anon_vma.
1069 pgoff = addr >> PAGE_SHIFT;
1070 break;
1071 default:
1072 return -EINVAL;
1076 error = security_file_mmap(file, reqprot, prot, flags, addr, 0);
1077 if (error)
1078 return error;
1080 return mmap_region(file, addr, len, flags, vm_flags, pgoff);
1082 EXPORT_SYMBOL(do_mmap_pgoff);
1084 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1085 unsigned long, prot, unsigned long, flags,
1086 unsigned long, fd, unsigned long, pgoff)
1088 struct file *file = NULL;
1089 unsigned long retval = -EBADF;
1091 if (!(flags & MAP_ANONYMOUS)) {
1092 audit_mmap_fd(fd, flags);
1093 if (unlikely(flags & MAP_HUGETLB))
1094 return -EINVAL;
1095 file = fget(fd);
1096 if (!file)
1097 goto out;
1098 } else if (flags & MAP_HUGETLB) {
1099 struct user_struct *user = NULL;
1101 * VM_NORESERVE is used because the reservations will be
1102 * taken when vm_ops->mmap() is called
1103 * A dummy user value is used because we are not locking
1104 * memory so no accounting is necessary
1106 len = ALIGN(len, huge_page_size(&default_hstate));
1107 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len, VM_NORESERVE,
1108 &user, HUGETLB_ANONHUGE_INODE);
1109 if (IS_ERR(file))
1110 return PTR_ERR(file);
1113 flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1115 down_write(&current->mm->mmap_sem);
1116 retval = do_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1117 up_write(&current->mm->mmap_sem);
1119 if (file)
1120 fput(file);
1121 out:
1122 return retval;
1125 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1126 struct mmap_arg_struct {
1127 unsigned long addr;
1128 unsigned long len;
1129 unsigned long prot;
1130 unsigned long flags;
1131 unsigned long fd;
1132 unsigned long offset;
1135 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1137 struct mmap_arg_struct a;
1139 if (copy_from_user(&a, arg, sizeof(a)))
1140 return -EFAULT;
1141 if (a.offset & ~PAGE_MASK)
1142 return -EINVAL;
1144 return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1145 a.offset >> PAGE_SHIFT);
1147 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1150 * Some shared mappigns will want the pages marked read-only
1151 * to track write events. If so, we'll downgrade vm_page_prot
1152 * to the private version (using protection_map[] without the
1153 * VM_SHARED bit).
1155 int vma_wants_writenotify(struct vm_area_struct *vma)
1157 vm_flags_t vm_flags = vma->vm_flags;
1159 /* If it was private or non-writable, the write bit is already clear */
1160 if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1161 return 0;
1163 /* The backer wishes to know when pages are first written to? */
1164 if (vma->vm_ops && vma->vm_ops->page_mkwrite)
1165 return 1;
1167 /* The open routine did something to the protections already? */
1168 if (pgprot_val(vma->vm_page_prot) !=
1169 pgprot_val(vm_get_page_prot(vm_flags)))
1170 return 0;
1172 /* Specialty mapping? */
1173 if (vm_flags & (VM_PFNMAP|VM_INSERTPAGE))
1174 return 0;
1176 /* Can the mapping track the dirty pages? */
1177 return vma->vm_file && vma->vm_file->f_mapping &&
1178 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1182 * We account for memory if it's a private writeable mapping,
1183 * not hugepages and VM_NORESERVE wasn't set.
1185 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1188 * hugetlb has its own accounting separate from the core VM
1189 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1191 if (file && is_file_hugepages(file))
1192 return 0;
1194 return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1197 unsigned long mmap_region(struct file *file, unsigned long addr,
1198 unsigned long len, unsigned long flags,
1199 vm_flags_t vm_flags, unsigned long pgoff)
1201 struct mm_struct *mm = current->mm;
1202 struct vm_area_struct *vma, *prev;
1203 int correct_wcount = 0;
1204 int error;
1205 struct rb_node **rb_link, *rb_parent;
1206 unsigned long charged = 0;
1207 struct inode *inode = file ? file->f_path.dentry->d_inode : NULL;
1209 /* Clear old maps */
1210 error = -ENOMEM;
1211 munmap_back:
1212 vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
1213 if (vma && vma->vm_start < addr + len) {
1214 if (do_munmap(mm, addr, len))
1215 return -ENOMEM;
1216 goto munmap_back;
1219 /* Check against address space limit. */
1220 if (!may_expand_vm(mm, len >> PAGE_SHIFT))
1221 return -ENOMEM;
1224 * Set 'VM_NORESERVE' if we should not account for the
1225 * memory use of this mapping.
1227 if ((flags & MAP_NORESERVE)) {
1228 /* We honor MAP_NORESERVE if allowed to overcommit */
1229 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1230 vm_flags |= VM_NORESERVE;
1232 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1233 if (file && is_file_hugepages(file))
1234 vm_flags |= VM_NORESERVE;
1238 * Private writable mapping: check memory availability
1240 if (accountable_mapping(file, vm_flags)) {
1241 charged = len >> PAGE_SHIFT;
1242 if (security_vm_enough_memory(charged))
1243 return -ENOMEM;
1244 vm_flags |= VM_ACCOUNT;
1248 * Can we just expand an old mapping?
1250 vma = vma_merge(mm, prev, addr, addr + len, vm_flags, NULL, file, pgoff, NULL);
1251 if (vma)
1252 goto out;
1255 * Determine the object being mapped and call the appropriate
1256 * specific mapper. the address has already been validated, but
1257 * not unmapped, but the maps are removed from the list.
1259 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1260 if (!vma) {
1261 error = -ENOMEM;
1262 goto unacct_error;
1265 vma->vm_mm = mm;
1266 vma->vm_start = addr;
1267 vma->vm_end = addr + len;
1268 vma->vm_flags = vm_flags;
1269 vma->vm_page_prot = vm_get_page_prot(vm_flags);
1270 vma->vm_pgoff = pgoff;
1271 INIT_LIST_HEAD(&vma->anon_vma_chain);
1273 error = -EINVAL; /* when rejecting VM_GROWSDOWN|VM_GROWSUP */
1275 if (file) {
1276 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1277 goto free_vma;
1278 if (vm_flags & VM_DENYWRITE) {
1279 error = deny_write_access(file);
1280 if (error)
1281 goto free_vma;
1282 correct_wcount = 1;
1284 vma->vm_file = file;
1285 get_file(file);
1286 error = file->f_op->mmap(file, vma);
1287 if (error)
1288 goto unmap_and_free_vma;
1289 if (vm_flags & VM_EXECUTABLE)
1290 added_exe_file_vma(mm);
1292 /* Can addr have changed??
1294 * Answer: Yes, several device drivers can do it in their
1295 * f_op->mmap method. -DaveM
1297 addr = vma->vm_start;
1298 pgoff = vma->vm_pgoff;
1299 vm_flags = vma->vm_flags;
1300 } else if (vm_flags & VM_SHARED) {
1301 if (unlikely(vm_flags & (VM_GROWSDOWN|VM_GROWSUP)))
1302 goto free_vma;
1303 error = shmem_zero_setup(vma);
1304 if (error)
1305 goto free_vma;
1308 if (vma_wants_writenotify(vma)) {
1309 pgprot_t pprot = vma->vm_page_prot;
1311 /* Can vma->vm_page_prot have changed??
1313 * Answer: Yes, drivers may have changed it in their
1314 * f_op->mmap method.
1316 * Ensures that vmas marked as uncached stay that way.
1318 vma->vm_page_prot = vm_get_page_prot(vm_flags & ~VM_SHARED);
1319 if (pgprot_val(pprot) == pgprot_val(pgprot_noncached(pprot)))
1320 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1323 vma_link(mm, vma, prev, rb_link, rb_parent);
1324 file = vma->vm_file;
1326 /* Once vma denies write, undo our temporary denial count */
1327 if (correct_wcount)
1328 atomic_inc(&inode->i_writecount);
1329 out:
1330 perf_event_mmap(vma);
1332 mm->total_vm += len >> PAGE_SHIFT;
1333 vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1334 if (vm_flags & VM_LOCKED) {
1335 if (!mlock_vma_pages_range(vma, addr, addr + len))
1336 mm->locked_vm += (len >> PAGE_SHIFT);
1337 } else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
1338 make_pages_present(addr, addr + len);
1339 return addr;
1341 unmap_and_free_vma:
1342 if (correct_wcount)
1343 atomic_inc(&inode->i_writecount);
1344 vma->vm_file = NULL;
1345 fput(file);
1347 /* Undo any partial mapping done by a device driver. */
1348 unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1349 charged = 0;
1350 free_vma:
1351 kmem_cache_free(vm_area_cachep, vma);
1352 unacct_error:
1353 if (charged)
1354 vm_unacct_memory(charged);
1355 return error;
1358 /* Get an address range which is currently unmapped.
1359 * For shmat() with addr=0.
1361 * Ugly calling convention alert:
1362 * Return value with the low bits set means error value,
1363 * ie
1364 * if (ret & ~PAGE_MASK)
1365 * error = ret;
1367 * This function "knows" that -ENOMEM has the bits set.
1369 #ifndef HAVE_ARCH_UNMAPPED_AREA
1370 unsigned long
1371 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1372 unsigned long len, unsigned long pgoff, unsigned long flags)
1374 struct mm_struct *mm = current->mm;
1375 struct vm_area_struct *vma;
1376 unsigned long start_addr;
1378 if (len > TASK_SIZE)
1379 return -ENOMEM;
1381 if (flags & MAP_FIXED)
1382 return addr;
1384 if (addr) {
1385 addr = PAGE_ALIGN(addr);
1386 vma = find_vma(mm, addr);
1387 if (TASK_SIZE - len >= addr &&
1388 (!vma || addr + len <= vma->vm_start))
1389 return addr;
1391 if (len > mm->cached_hole_size) {
1392 start_addr = addr = mm->free_area_cache;
1393 } else {
1394 start_addr = addr = TASK_UNMAPPED_BASE;
1395 mm->cached_hole_size = 0;
1398 full_search:
1399 for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
1400 /* At this point: (!vma || addr < vma->vm_end). */
1401 if (TASK_SIZE - len < addr) {
1403 * Start a new search - just in case we missed
1404 * some holes.
1406 if (start_addr != TASK_UNMAPPED_BASE) {
1407 addr = TASK_UNMAPPED_BASE;
1408 start_addr = addr;
1409 mm->cached_hole_size = 0;
1410 goto full_search;
1412 return -ENOMEM;
1414 if (!vma || addr + len <= vma->vm_start) {
1416 * Remember the place where we stopped the search:
1418 mm->free_area_cache = addr + len;
1419 return addr;
1421 if (addr + mm->cached_hole_size < vma->vm_start)
1422 mm->cached_hole_size = vma->vm_start - addr;
1423 addr = vma->vm_end;
1426 #endif
1428 void arch_unmap_area(struct mm_struct *mm, unsigned long addr)
1431 * Is this a new hole at the lowest possible address?
1433 if (addr >= TASK_UNMAPPED_BASE && addr < mm->free_area_cache) {
1434 mm->free_area_cache = addr;
1435 mm->cached_hole_size = ~0UL;
1440 * This mmap-allocator allocates new areas top-down from below the
1441 * stack's low limit (the base):
1443 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1444 unsigned long
1445 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1446 const unsigned long len, const unsigned long pgoff,
1447 const unsigned long flags)
1449 struct vm_area_struct *vma;
1450 struct mm_struct *mm = current->mm;
1451 unsigned long addr = addr0;
1453 /* requested length too big for entire address space */
1454 if (len > TASK_SIZE)
1455 return -ENOMEM;
1457 if (flags & MAP_FIXED)
1458 return addr;
1460 /* requesting a specific address */
1461 if (addr) {
1462 addr = PAGE_ALIGN(addr);
1463 vma = find_vma(mm, addr);
1464 if (TASK_SIZE - len >= addr &&
1465 (!vma || addr + len <= vma->vm_start))
1466 return addr;
1469 /* check if free_area_cache is useful for us */
1470 if (len <= mm->cached_hole_size) {
1471 mm->cached_hole_size = 0;
1472 mm->free_area_cache = mm->mmap_base;
1475 /* either no address requested or can't fit in requested address hole */
1476 addr = mm->free_area_cache;
1478 /* make sure it can fit in the remaining address space */
1479 if (addr > len) {
1480 vma = find_vma(mm, addr-len);
1481 if (!vma || addr <= vma->vm_start)
1482 /* remember the address as a hint for next time */
1483 return (mm->free_area_cache = addr-len);
1486 if (mm->mmap_base < len)
1487 goto bottomup;
1489 addr = mm->mmap_base-len;
1491 do {
1493 * Lookup failure means no vma is above this address,
1494 * else if new region fits below vma->vm_start,
1495 * return with success:
1497 vma = find_vma(mm, addr);
1498 if (!vma || addr+len <= vma->vm_start)
1499 /* remember the address as a hint for next time */
1500 return (mm->free_area_cache = addr);
1502 /* remember the largest hole we saw so far */
1503 if (addr + mm->cached_hole_size < vma->vm_start)
1504 mm->cached_hole_size = vma->vm_start - addr;
1506 /* try just below the current vma->vm_start */
1507 addr = vma->vm_start-len;
1508 } while (len < vma->vm_start);
1510 bottomup:
1512 * A failed mmap() very likely causes application failure,
1513 * so fall back to the bottom-up function here. This scenario
1514 * can happen with large stack limits and large mmap()
1515 * allocations.
1517 mm->cached_hole_size = ~0UL;
1518 mm->free_area_cache = TASK_UNMAPPED_BASE;
1519 addr = arch_get_unmapped_area(filp, addr0, len, pgoff, flags);
1521 * Restore the topdown base:
1523 mm->free_area_cache = mm->mmap_base;
1524 mm->cached_hole_size = ~0UL;
1526 return addr;
1528 #endif
1530 void arch_unmap_area_topdown(struct mm_struct *mm, unsigned long addr)
1533 * Is this a new hole at the highest possible address?
1535 if (addr > mm->free_area_cache)
1536 mm->free_area_cache = addr;
1538 /* dont allow allocations above current base */
1539 if (mm->free_area_cache > mm->mmap_base)
1540 mm->free_area_cache = mm->mmap_base;
1543 unsigned long
1544 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1545 unsigned long pgoff, unsigned long flags)
1547 unsigned long (*get_area)(struct file *, unsigned long,
1548 unsigned long, unsigned long, unsigned long);
1550 unsigned long error = arch_mmap_check(addr, len, flags);
1551 if (error)
1552 return error;
1554 /* Careful about overflows.. */
1555 if (len > TASK_SIZE)
1556 return -ENOMEM;
1558 get_area = current->mm->get_unmapped_area;
1559 if (file && file->f_op && file->f_op->get_unmapped_area)
1560 get_area = file->f_op->get_unmapped_area;
1561 addr = get_area(file, addr, len, pgoff, flags);
1562 if (IS_ERR_VALUE(addr))
1563 return addr;
1565 if (addr > TASK_SIZE - len)
1566 return -ENOMEM;
1567 if (addr & ~PAGE_MASK)
1568 return -EINVAL;
1570 return arch_rebalance_pgtables(addr, len);
1573 EXPORT_SYMBOL(get_unmapped_area);
1575 /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
1576 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1578 struct vm_area_struct *vma = NULL;
1580 if (mm) {
1581 /* Check the cache first. */
1582 /* (Cache hit rate is typically around 35%.) */
1583 vma = mm->mmap_cache;
1584 if (!(vma && vma->vm_end > addr && vma->vm_start <= addr)) {
1585 struct rb_node * rb_node;
1587 rb_node = mm->mm_rb.rb_node;
1588 vma = NULL;
1590 while (rb_node) {
1591 struct vm_area_struct * vma_tmp;
1593 vma_tmp = rb_entry(rb_node,
1594 struct vm_area_struct, vm_rb);
1596 if (vma_tmp->vm_end > addr) {
1597 vma = vma_tmp;
1598 if (vma_tmp->vm_start <= addr)
1599 break;
1600 rb_node = rb_node->rb_left;
1601 } else
1602 rb_node = rb_node->rb_right;
1604 if (vma)
1605 mm->mmap_cache = vma;
1608 return vma;
1611 EXPORT_SYMBOL(find_vma);
1614 * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
1616 struct vm_area_struct *
1617 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1618 struct vm_area_struct **pprev)
1620 struct vm_area_struct *vma;
1622 vma = find_vma(mm, addr);
1623 if (vma) {
1624 *pprev = vma->vm_prev;
1625 } else {
1626 struct rb_node *rb_node = mm->mm_rb.rb_node;
1627 *pprev = NULL;
1628 while (rb_node) {
1629 *pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
1630 rb_node = rb_node->rb_right;
1633 return vma;
1637 * Verify that the stack growth is acceptable and
1638 * update accounting. This is shared with both the
1639 * grow-up and grow-down cases.
1641 static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
1643 struct mm_struct *mm = vma->vm_mm;
1644 struct rlimit *rlim = current->signal->rlim;
1645 unsigned long new_start;
1647 /* address space limit tests */
1648 if (!may_expand_vm(mm, grow))
1649 return -ENOMEM;
1651 /* Stack limit test */
1652 if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur))
1653 return -ENOMEM;
1655 /* mlock limit tests */
1656 if (vma->vm_flags & VM_LOCKED) {
1657 unsigned long locked;
1658 unsigned long limit;
1659 locked = mm->locked_vm + grow;
1660 limit = ACCESS_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
1661 limit >>= PAGE_SHIFT;
1662 if (locked > limit && !capable(CAP_IPC_LOCK))
1663 return -ENOMEM;
1666 /* Check to ensure the stack will not grow into a hugetlb-only region */
1667 new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
1668 vma->vm_end - size;
1669 if (is_hugepage_only_range(vma->vm_mm, new_start, size))
1670 return -EFAULT;
1673 * Overcommit.. This must be the final test, as it will
1674 * update security statistics.
1676 if (security_vm_enough_memory_mm(mm, grow))
1677 return -ENOMEM;
1679 /* Ok, everything looks good - let it rip */
1680 mm->total_vm += grow;
1681 if (vma->vm_flags & VM_LOCKED)
1682 mm->locked_vm += grow;
1683 vm_stat_account(mm, vma->vm_flags, vma->vm_file, grow);
1684 return 0;
1687 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
1689 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
1690 * vma is the last one with address > vma->vm_end. Have to extend vma.
1692 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
1694 int error;
1696 if (!(vma->vm_flags & VM_GROWSUP))
1697 return -EFAULT;
1700 * We must make sure the anon_vma is allocated
1701 * so that the anon_vma locking is not a noop.
1703 if (unlikely(anon_vma_prepare(vma)))
1704 return -ENOMEM;
1705 vma_lock_anon_vma(vma);
1708 * vma->vm_start/vm_end cannot change under us because the caller
1709 * is required to hold the mmap_sem in read mode. We need the
1710 * anon_vma lock to serialize against concurrent expand_stacks.
1711 * Also guard against wrapping around to address 0.
1713 if (address < PAGE_ALIGN(address+4))
1714 address = PAGE_ALIGN(address+4);
1715 else {
1716 vma_unlock_anon_vma(vma);
1717 return -ENOMEM;
1719 error = 0;
1721 /* Somebody else might have raced and expanded it already */
1722 if (address > vma->vm_end) {
1723 unsigned long size, grow;
1725 size = address - vma->vm_start;
1726 grow = (address - vma->vm_end) >> PAGE_SHIFT;
1728 error = -ENOMEM;
1729 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
1730 error = acct_stack_growth(vma, size, grow);
1731 if (!error) {
1732 vma->vm_end = address;
1733 perf_event_mmap(vma);
1737 vma_unlock_anon_vma(vma);
1738 khugepaged_enter_vma_merge(vma);
1739 return error;
1741 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
1744 * vma is the first one with address < vma->vm_start. Have to extend vma.
1746 int expand_downwards(struct vm_area_struct *vma,
1747 unsigned long address)
1749 int error;
1752 * We must make sure the anon_vma is allocated
1753 * so that the anon_vma locking is not a noop.
1755 if (unlikely(anon_vma_prepare(vma)))
1756 return -ENOMEM;
1758 address &= PAGE_MASK;
1759 error = security_file_mmap(NULL, 0, 0, 0, address, 1);
1760 if (error)
1761 return error;
1763 vma_lock_anon_vma(vma);
1766 * vma->vm_start/vm_end cannot change under us because the caller
1767 * is required to hold the mmap_sem in read mode. We need the
1768 * anon_vma lock to serialize against concurrent expand_stacks.
1771 /* Somebody else might have raced and expanded it already */
1772 if (address < vma->vm_start) {
1773 unsigned long size, grow;
1775 size = vma->vm_end - address;
1776 grow = (vma->vm_start - address) >> PAGE_SHIFT;
1778 error = -ENOMEM;
1779 if (grow <= vma->vm_pgoff) {
1780 error = acct_stack_growth(vma, size, grow);
1781 if (!error) {
1782 vma->vm_start = address;
1783 vma->vm_pgoff -= grow;
1784 perf_event_mmap(vma);
1788 vma_unlock_anon_vma(vma);
1789 khugepaged_enter_vma_merge(vma);
1790 return error;
1793 #ifdef CONFIG_STACK_GROWSUP
1794 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1796 return expand_upwards(vma, address);
1799 struct vm_area_struct *
1800 find_extend_vma(struct mm_struct *mm, unsigned long addr)
1802 struct vm_area_struct *vma, *prev;
1804 addr &= PAGE_MASK;
1805 vma = find_vma_prev(mm, addr, &prev);
1806 if (vma && (vma->vm_start <= addr))
1807 return vma;
1808 if (!prev || expand_stack(prev, addr))
1809 return NULL;
1810 if (prev->vm_flags & VM_LOCKED) {
1811 mlock_vma_pages_range(prev, addr, prev->vm_end);
1813 return prev;
1815 #else
1816 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1818 return expand_downwards(vma, address);
1821 struct vm_area_struct *
1822 find_extend_vma(struct mm_struct * mm, unsigned long addr)
1824 struct vm_area_struct * vma;
1825 unsigned long start;
1827 addr &= PAGE_MASK;
1828 vma = find_vma(mm,addr);
1829 if (!vma)
1830 return NULL;
1831 if (vma->vm_start <= addr)
1832 return vma;
1833 if (!(vma->vm_flags & VM_GROWSDOWN))
1834 return NULL;
1835 start = vma->vm_start;
1836 if (expand_stack(vma, addr))
1837 return NULL;
1838 if (vma->vm_flags & VM_LOCKED) {
1839 mlock_vma_pages_range(vma, addr, start);
1841 return vma;
1843 #endif
1846 * Ok - we have the memory areas we should free on the vma list,
1847 * so release them, and do the vma updates.
1849 * Called with the mm semaphore held.
1851 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
1853 /* Update high watermark before we lower total_vm */
1854 update_hiwater_vm(mm);
1855 do {
1856 long nrpages = vma_pages(vma);
1858 mm->total_vm -= nrpages;
1859 vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
1860 vma = remove_vma(vma);
1861 } while (vma);
1862 validate_mm(mm);
1866 * Get rid of page table information in the indicated region.
1868 * Called with the mm semaphore held.
1870 static void unmap_region(struct mm_struct *mm,
1871 struct vm_area_struct *vma, struct vm_area_struct *prev,
1872 unsigned long start, unsigned long end)
1874 struct vm_area_struct *next = prev? prev->vm_next: mm->mmap;
1875 struct mmu_gather tlb;
1876 unsigned long nr_accounted = 0;
1878 lru_add_drain();
1879 tlb_gather_mmu(&tlb, mm, 0);
1880 update_hiwater_rss(mm);
1881 unmap_vmas(&tlb, vma, start, end, &nr_accounted, NULL);
1882 vm_unacct_memory(nr_accounted);
1883 free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
1884 next ? next->vm_start : 0);
1885 tlb_finish_mmu(&tlb, start, end);
1889 * Create a list of vma's touched by the unmap, removing them from the mm's
1890 * vma list as we go..
1892 static void
1893 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
1894 struct vm_area_struct *prev, unsigned long end)
1896 struct vm_area_struct **insertion_point;
1897 struct vm_area_struct *tail_vma = NULL;
1898 unsigned long addr;
1900 insertion_point = (prev ? &prev->vm_next : &mm->mmap);
1901 vma->vm_prev = NULL;
1902 do {
1903 rb_erase(&vma->vm_rb, &mm->mm_rb);
1904 mm->map_count--;
1905 tail_vma = vma;
1906 vma = vma->vm_next;
1907 } while (vma && vma->vm_start < end);
1908 *insertion_point = vma;
1909 if (vma)
1910 vma->vm_prev = prev;
1911 tail_vma->vm_next = NULL;
1912 if (mm->unmap_area == arch_unmap_area)
1913 addr = prev ? prev->vm_end : mm->mmap_base;
1914 else
1915 addr = vma ? vma->vm_start : mm->mmap_base;
1916 mm->unmap_area(mm, addr);
1917 mm->mmap_cache = NULL; /* Kill the cache. */
1921 * __split_vma() bypasses sysctl_max_map_count checking. We use this on the
1922 * munmap path where it doesn't make sense to fail.
1924 static int __split_vma(struct mm_struct * mm, struct vm_area_struct * vma,
1925 unsigned long addr, int new_below)
1927 struct mempolicy *pol;
1928 struct vm_area_struct *new;
1929 int err = -ENOMEM;
1931 if (is_vm_hugetlb_page(vma) && (addr &
1932 ~(huge_page_mask(hstate_vma(vma)))))
1933 return -EINVAL;
1935 new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
1936 if (!new)
1937 goto out_err;
1939 /* most fields are the same, copy all, and then fixup */
1940 *new = *vma;
1942 INIT_LIST_HEAD(&new->anon_vma_chain);
1944 if (new_below)
1945 new->vm_end = addr;
1946 else {
1947 new->vm_start = addr;
1948 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
1951 pol = mpol_dup(vma_policy(vma));
1952 if (IS_ERR(pol)) {
1953 err = PTR_ERR(pol);
1954 goto out_free_vma;
1956 vma_set_policy(new, pol);
1958 if (anon_vma_clone(new, vma))
1959 goto out_free_mpol;
1961 if (new->vm_file) {
1962 get_file(new->vm_file);
1963 if (new->vm_prfile)
1964 get_file(new->vm_prfile);
1965 if (vma->vm_flags & VM_EXECUTABLE)
1966 added_exe_file_vma(mm);
1969 if (new->vm_ops && new->vm_ops->open)
1970 new->vm_ops->open(new);
1972 if (new_below)
1973 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
1974 ((addr - new->vm_start) >> PAGE_SHIFT), new);
1975 else
1976 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
1978 /* Success. */
1979 if (!err)
1980 return 0;
1982 /* Clean everything up if vma_adjust failed. */
1983 if (new->vm_ops && new->vm_ops->close)
1984 new->vm_ops->close(new);
1985 if (new->vm_file) {
1986 if (vma->vm_flags & VM_EXECUTABLE)
1987 removed_exe_file_vma(mm);
1988 fput(new->vm_file);
1989 if (new->vm_prfile)
1990 fput(new->vm_prfile);
1992 unlink_anon_vmas(new);
1993 out_free_mpol:
1994 mpol_put(pol);
1995 out_free_vma:
1996 kmem_cache_free(vm_area_cachep, new);
1997 out_err:
1998 return err;
2002 * Split a vma into two pieces at address 'addr', a new vma is allocated
2003 * either for the first part or the tail.
2005 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2006 unsigned long addr, int new_below)
2008 if (mm->map_count >= sysctl_max_map_count)
2009 return -ENOMEM;
2011 return __split_vma(mm, vma, addr, new_below);
2014 /* Munmap is split into 2 main parts -- this part which finds
2015 * what needs doing, and the areas themselves, which do the
2016 * work. This now handles partial unmappings.
2017 * Jeremy Fitzhardinge <jeremy@goop.org>
2019 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2021 unsigned long end;
2022 struct vm_area_struct *vma, *prev, *last;
2024 if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
2025 return -EINVAL;
2027 if ((len = PAGE_ALIGN(len)) == 0)
2028 return -EINVAL;
2030 /* Find the first overlapping VMA */
2031 vma = find_vma(mm, start);
2032 if (!vma)
2033 return 0;
2034 prev = vma->vm_prev;
2035 /* we have start < vma->vm_end */
2037 /* if it doesn't overlap, we have nothing.. */
2038 end = start + len;
2039 if (vma->vm_start >= end)
2040 return 0;
2043 * If we need to split any vma, do it now to save pain later.
2045 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2046 * unmapped vm_area_struct will remain in use: so lower split_vma
2047 * places tmp vma above, and higher split_vma places tmp vma below.
2049 if (start > vma->vm_start) {
2050 int error;
2053 * Make sure that map_count on return from munmap() will
2054 * not exceed its limit; but let map_count go just above
2055 * its limit temporarily, to help free resources as expected.
2057 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2058 return -ENOMEM;
2060 error = __split_vma(mm, vma, start, 0);
2061 if (error)
2062 return error;
2063 prev = vma;
2066 /* Does it split the last one? */
2067 last = find_vma(mm, end);
2068 if (last && end > last->vm_start) {
2069 int error = __split_vma(mm, last, end, 1);
2070 if (error)
2071 return error;
2073 vma = prev? prev->vm_next: mm->mmap;
2076 * unlock any mlock()ed ranges before detaching vmas
2078 if (mm->locked_vm) {
2079 struct vm_area_struct *tmp = vma;
2080 while (tmp && tmp->vm_start < end) {
2081 if (tmp->vm_flags & VM_LOCKED) {
2082 mm->locked_vm -= vma_pages(tmp);
2083 munlock_vma_pages_all(tmp);
2085 tmp = tmp->vm_next;
2090 * Remove the vma's, and unmap the actual pages
2092 detach_vmas_to_be_unmapped(mm, vma, prev, end);
2093 unmap_region(mm, vma, prev, start, end);
2095 /* Fix up all other VM information */
2096 remove_vma_list(mm, vma);
2098 return 0;
2101 EXPORT_SYMBOL(do_munmap);
2103 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2105 int ret;
2106 struct mm_struct *mm = current->mm;
2108 profile_munmap(addr);
2110 down_write(&mm->mmap_sem);
2111 ret = do_munmap(mm, addr, len);
2112 up_write(&mm->mmap_sem);
2113 return ret;
2116 static inline void verify_mm_writelocked(struct mm_struct *mm)
2118 #ifdef CONFIG_DEBUG_VM
2119 if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2120 WARN_ON(1);
2121 up_read(&mm->mmap_sem);
2123 #endif
2127 * this is really a simplified "do_mmap". it only handles
2128 * anonymous maps. eventually we may be able to do some
2129 * brk-specific accounting here.
2131 unsigned long do_brk(unsigned long addr, unsigned long len)
2133 struct mm_struct * mm = current->mm;
2134 struct vm_area_struct * vma, * prev;
2135 unsigned long flags;
2136 struct rb_node ** rb_link, * rb_parent;
2137 pgoff_t pgoff = addr >> PAGE_SHIFT;
2138 int error;
2140 len = PAGE_ALIGN(len);
2141 if (!len)
2142 return addr;
2144 error = security_file_mmap(NULL, 0, 0, 0, addr, 1);
2145 if (error)
2146 return error;
2148 flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2150 error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2151 if (error & ~PAGE_MASK)
2152 return error;
2155 * mlock MCL_FUTURE?
2157 if (mm->def_flags & VM_LOCKED) {
2158 unsigned long locked, lock_limit;
2159 locked = len >> PAGE_SHIFT;
2160 locked += mm->locked_vm;
2161 lock_limit = rlimit(RLIMIT_MEMLOCK);
2162 lock_limit >>= PAGE_SHIFT;
2163 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
2164 return -EAGAIN;
2168 * mm->mmap_sem is required to protect against another thread
2169 * changing the mappings in case we sleep.
2171 verify_mm_writelocked(mm);
2174 * Clear old maps. this also does some error checking for us
2176 munmap_back:
2177 vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
2178 if (vma && vma->vm_start < addr + len) {
2179 if (do_munmap(mm, addr, len))
2180 return -ENOMEM;
2181 goto munmap_back;
2184 /* Check against address space limits *after* clearing old maps... */
2185 if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2186 return -ENOMEM;
2188 if (mm->map_count > sysctl_max_map_count)
2189 return -ENOMEM;
2191 if (security_vm_enough_memory(len >> PAGE_SHIFT))
2192 return -ENOMEM;
2194 /* Can we just expand an old private anonymous mapping? */
2195 vma = vma_merge(mm, prev, addr, addr + len, flags,
2196 NULL, NULL, pgoff, NULL);
2197 if (vma)
2198 goto out;
2201 * create a vma struct for an anonymous mapping
2203 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2204 if (!vma) {
2205 vm_unacct_memory(len >> PAGE_SHIFT);
2206 return -ENOMEM;
2209 INIT_LIST_HEAD(&vma->anon_vma_chain);
2210 vma->vm_mm = mm;
2211 vma->vm_start = addr;
2212 vma->vm_end = addr + len;
2213 vma->vm_pgoff = pgoff;
2214 vma->vm_flags = flags;
2215 vma->vm_page_prot = vm_get_page_prot(flags);
2216 vma_link(mm, vma, prev, rb_link, rb_parent);
2217 out:
2218 perf_event_mmap(vma);
2219 mm->total_vm += len >> PAGE_SHIFT;
2220 if (flags & VM_LOCKED) {
2221 if (!mlock_vma_pages_range(vma, addr, addr + len))
2222 mm->locked_vm += (len >> PAGE_SHIFT);
2224 return addr;
2227 EXPORT_SYMBOL(do_brk);
2229 /* Release all mmaps. */
2230 void exit_mmap(struct mm_struct *mm)
2232 struct mmu_gather tlb;
2233 struct vm_area_struct *vma;
2234 unsigned long nr_accounted = 0;
2235 unsigned long end;
2237 /* mm's last user has gone, and its about to be pulled down */
2238 mmu_notifier_release(mm);
2240 if (mm->locked_vm) {
2241 vma = mm->mmap;
2242 while (vma) {
2243 if (vma->vm_flags & VM_LOCKED)
2244 munlock_vma_pages_all(vma);
2245 vma = vma->vm_next;
2249 arch_exit_mmap(mm);
2251 vma = mm->mmap;
2252 if (!vma) /* Can happen if dup_mmap() received an OOM */
2253 return;
2255 lru_add_drain();
2256 flush_cache_mm(mm);
2257 tlb_gather_mmu(&tlb, mm, 1);
2258 /* update_hiwater_rss(mm) here? but nobody should be looking */
2259 /* Use -1 here to ensure all VMAs in the mm are unmapped */
2260 end = unmap_vmas(&tlb, vma, 0, -1, &nr_accounted, NULL);
2261 vm_unacct_memory(nr_accounted);
2263 free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, 0);
2264 tlb_finish_mmu(&tlb, 0, end);
2267 * Walk the list again, actually closing and freeing it,
2268 * with preemption enabled, without holding any MM locks.
2270 while (vma)
2271 vma = remove_vma(vma);
2273 BUG_ON(mm->nr_ptes > (FIRST_USER_ADDRESS+PMD_SIZE-1)>>PMD_SHIFT);
2276 /* Insert vm structure into process list sorted by address
2277 * and into the inode's i_mmap tree. If vm_file is non-NULL
2278 * then i_mmap_mutex is taken here.
2280 int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
2282 struct vm_area_struct * __vma, * prev;
2283 struct rb_node ** rb_link, * rb_parent;
2286 * The vm_pgoff of a purely anonymous vma should be irrelevant
2287 * until its first write fault, when page's anon_vma and index
2288 * are set. But now set the vm_pgoff it will almost certainly
2289 * end up with (unless mremap moves it elsewhere before that
2290 * first wfault), so /proc/pid/maps tells a consistent story.
2292 * By setting it to reflect the virtual start address of the
2293 * vma, merges and splits can happen in a seamless way, just
2294 * using the existing file pgoff checks and manipulations.
2295 * Similarly in do_mmap_pgoff and in do_brk.
2297 if (!vma->vm_file) {
2298 BUG_ON(vma->anon_vma);
2299 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2301 __vma = find_vma_prepare(mm,vma->vm_start,&prev,&rb_link,&rb_parent);
2302 if (__vma && __vma->vm_start < vma->vm_end)
2303 return -ENOMEM;
2304 if ((vma->vm_flags & VM_ACCOUNT) &&
2305 security_vm_enough_memory_mm(mm, vma_pages(vma)))
2306 return -ENOMEM;
2307 vma_link(mm, vma, prev, rb_link, rb_parent);
2308 return 0;
2312 * Copy the vma structure to a new location in the same mm,
2313 * prior to moving page table entries, to effect an mremap move.
2315 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2316 unsigned long addr, unsigned long len, pgoff_t pgoff)
2318 struct vm_area_struct *vma = *vmap;
2319 unsigned long vma_start = vma->vm_start;
2320 struct mm_struct *mm = vma->vm_mm;
2321 struct vm_area_struct *new_vma, *prev;
2322 struct rb_node **rb_link, *rb_parent;
2323 struct mempolicy *pol;
2324 bool faulted_in_anon_vma = true;
2327 * If anonymous vma has not yet been faulted, update new pgoff
2328 * to match new location, to increase its chance of merging.
2330 if (unlikely(!vma->vm_file && !vma->anon_vma)) {
2331 pgoff = addr >> PAGE_SHIFT;
2332 faulted_in_anon_vma = false;
2335 find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
2336 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2337 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma));
2338 if (new_vma) {
2340 * Source vma may have been merged into new_vma
2342 if (unlikely(vma_start >= new_vma->vm_start &&
2343 vma_start < new_vma->vm_end)) {
2345 * The only way we can get a vma_merge with
2346 * self during an mremap is if the vma hasn't
2347 * been faulted in yet and we were allowed to
2348 * reset the dst vma->vm_pgoff to the
2349 * destination address of the mremap to allow
2350 * the merge to happen. mremap must change the
2351 * vm_pgoff linearity between src and dst vmas
2352 * (in turn preventing a vma_merge) to be
2353 * safe. It is only safe to keep the vm_pgoff
2354 * linear if there are no pages mapped yet.
2356 VM_BUG_ON(faulted_in_anon_vma);
2357 *vmap = new_vma;
2358 } else
2359 anon_vma_moveto_tail(new_vma);
2360 } else {
2361 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2362 if (new_vma) {
2363 *new_vma = *vma;
2364 pol = mpol_dup(vma_policy(vma));
2365 if (IS_ERR(pol))
2366 goto out_free_vma;
2367 INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2368 if (anon_vma_clone(new_vma, vma))
2369 goto out_free_mempol;
2370 vma_set_policy(new_vma, pol);
2371 new_vma->vm_start = addr;
2372 new_vma->vm_end = addr + len;
2373 new_vma->vm_pgoff = pgoff;
2374 if (new_vma->vm_file) {
2375 get_file(new_vma->vm_file);
2376 if (new_vma->vm_prfile)
2377 get_file(new_vma->vm_prfile);
2378 if (vma->vm_flags & VM_EXECUTABLE)
2379 added_exe_file_vma(mm);
2381 if (new_vma->vm_ops && new_vma->vm_ops->open)
2382 new_vma->vm_ops->open(new_vma);
2383 vma_link(mm, new_vma, prev, rb_link, rb_parent);
2386 return new_vma;
2388 out_free_mempol:
2389 mpol_put(pol);
2390 out_free_vma:
2391 kmem_cache_free(vm_area_cachep, new_vma);
2392 return NULL;
2396 * Return true if the calling process may expand its vm space by the passed
2397 * number of pages
2399 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
2401 unsigned long cur = mm->total_vm; /* pages */
2402 unsigned long lim;
2404 lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
2406 if (cur + npages > lim)
2407 return 0;
2408 return 1;
2412 static int special_mapping_fault(struct vm_area_struct *vma,
2413 struct vm_fault *vmf)
2415 pgoff_t pgoff;
2416 struct page **pages;
2419 * special mappings have no vm_file, and in that case, the mm
2420 * uses vm_pgoff internally. So we have to subtract it from here.
2421 * We are allowed to do this because we are the mm; do not copy
2422 * this code into drivers!
2424 pgoff = vmf->pgoff - vma->vm_pgoff;
2426 for (pages = vma->vm_private_data; pgoff && *pages; ++pages)
2427 pgoff--;
2429 if (*pages) {
2430 struct page *page = *pages;
2431 get_page(page);
2432 vmf->page = page;
2433 return 0;
2436 return VM_FAULT_SIGBUS;
2440 * Having a close hook prevents vma merging regardless of flags.
2442 static void special_mapping_close(struct vm_area_struct *vma)
2446 static const struct vm_operations_struct special_mapping_vmops = {
2447 .close = special_mapping_close,
2448 .fault = special_mapping_fault,
2452 * Called with mm->mmap_sem held for writing.
2453 * Insert a new vma covering the given region, with the given flags.
2454 * Its pages are supplied by the given array of struct page *.
2455 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
2456 * The region past the last page supplied will always produce SIGBUS.
2457 * The array pointer and the pages it points to are assumed to stay alive
2458 * for as long as this mapping might exist.
2460 int install_special_mapping(struct mm_struct *mm,
2461 unsigned long addr, unsigned long len,
2462 unsigned long vm_flags, struct page **pages)
2464 int ret;
2465 struct vm_area_struct *vma;
2467 vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2468 if (unlikely(vma == NULL))
2469 return -ENOMEM;
2471 INIT_LIST_HEAD(&vma->anon_vma_chain);
2472 vma->vm_mm = mm;
2473 vma->vm_start = addr;
2474 vma->vm_end = addr + len;
2476 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND;
2477 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
2479 vma->vm_ops = &special_mapping_vmops;
2480 vma->vm_private_data = pages;
2482 ret = security_file_mmap(NULL, 0, 0, 0, vma->vm_start, 1);
2483 if (ret)
2484 goto out;
2486 ret = insert_vm_struct(mm, vma);
2487 if (ret)
2488 goto out;
2490 mm->total_vm += len >> PAGE_SHIFT;
2492 perf_event_mmap(vma);
2494 return 0;
2496 out:
2497 kmem_cache_free(vm_area_cachep, vma);
2498 return ret;
2501 static DEFINE_MUTEX(mm_all_locks_mutex);
2503 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
2505 if (!test_bit(0, (unsigned long *) &anon_vma->root->head.next)) {
2507 * The LSB of head.next can't change from under us
2508 * because we hold the mm_all_locks_mutex.
2510 mutex_lock_nest_lock(&anon_vma->root->mutex, &mm->mmap_sem);
2512 * We can safely modify head.next after taking the
2513 * anon_vma->root->mutex. If some other vma in this mm shares
2514 * the same anon_vma we won't take it again.
2516 * No need of atomic instructions here, head.next
2517 * can't change from under us thanks to the
2518 * anon_vma->root->mutex.
2520 if (__test_and_set_bit(0, (unsigned long *)
2521 &anon_vma->root->head.next))
2522 BUG();
2526 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
2528 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2530 * AS_MM_ALL_LOCKS can't change from under us because
2531 * we hold the mm_all_locks_mutex.
2533 * Operations on ->flags have to be atomic because
2534 * even if AS_MM_ALL_LOCKS is stable thanks to the
2535 * mm_all_locks_mutex, there may be other cpus
2536 * changing other bitflags in parallel to us.
2538 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
2539 BUG();
2540 mutex_lock_nest_lock(&mapping->i_mmap_mutex, &mm->mmap_sem);
2545 * This operation locks against the VM for all pte/vma/mm related
2546 * operations that could ever happen on a certain mm. This includes
2547 * vmtruncate, try_to_unmap, and all page faults.
2549 * The caller must take the mmap_sem in write mode before calling
2550 * mm_take_all_locks(). The caller isn't allowed to release the
2551 * mmap_sem until mm_drop_all_locks() returns.
2553 * mmap_sem in write mode is required in order to block all operations
2554 * that could modify pagetables and free pages without need of
2555 * altering the vma layout (for example populate_range() with
2556 * nonlinear vmas). It's also needed in write mode to avoid new
2557 * anon_vmas to be associated with existing vmas.
2559 * A single task can't take more than one mm_take_all_locks() in a row
2560 * or it would deadlock.
2562 * The LSB in anon_vma->head.next and the AS_MM_ALL_LOCKS bitflag in
2563 * mapping->flags avoid to take the same lock twice, if more than one
2564 * vma in this mm is backed by the same anon_vma or address_space.
2566 * We can take all the locks in random order because the VM code
2567 * taking i_mmap_mutex or anon_vma->mutex outside the mmap_sem never
2568 * takes more than one of them in a row. Secondly we're protected
2569 * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
2571 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
2572 * that may have to take thousand of locks.
2574 * mm_take_all_locks() can fail if it's interrupted by signals.
2576 int mm_take_all_locks(struct mm_struct *mm)
2578 struct vm_area_struct *vma;
2579 struct anon_vma_chain *avc;
2581 BUG_ON(down_read_trylock(&mm->mmap_sem));
2583 mutex_lock(&mm_all_locks_mutex);
2585 for (vma = mm->mmap; vma; vma = vma->vm_next) {
2586 if (signal_pending(current))
2587 goto out_unlock;
2588 if (vma->vm_file && vma->vm_file->f_mapping)
2589 vm_lock_mapping(mm, vma->vm_file->f_mapping);
2592 for (vma = mm->mmap; vma; vma = vma->vm_next) {
2593 if (signal_pending(current))
2594 goto out_unlock;
2595 if (vma->anon_vma)
2596 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2597 vm_lock_anon_vma(mm, avc->anon_vma);
2600 return 0;
2602 out_unlock:
2603 mm_drop_all_locks(mm);
2604 return -EINTR;
2607 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2609 if (test_bit(0, (unsigned long *) &anon_vma->root->head.next)) {
2611 * The LSB of head.next can't change to 0 from under
2612 * us because we hold the mm_all_locks_mutex.
2614 * We must however clear the bitflag before unlocking
2615 * the vma so the users using the anon_vma->head will
2616 * never see our bitflag.
2618 * No need of atomic instructions here, head.next
2619 * can't change from under us until we release the
2620 * anon_vma->root->mutex.
2622 if (!__test_and_clear_bit(0, (unsigned long *)
2623 &anon_vma->root->head.next))
2624 BUG();
2625 anon_vma_unlock(anon_vma);
2629 static void vm_unlock_mapping(struct address_space *mapping)
2631 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2633 * AS_MM_ALL_LOCKS can't change to 0 from under us
2634 * because we hold the mm_all_locks_mutex.
2636 mutex_unlock(&mapping->i_mmap_mutex);
2637 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2638 &mapping->flags))
2639 BUG();
2644 * The mmap_sem cannot be released by the caller until
2645 * mm_drop_all_locks() returns.
2647 void mm_drop_all_locks(struct mm_struct *mm)
2649 struct vm_area_struct *vma;
2650 struct anon_vma_chain *avc;
2652 BUG_ON(down_read_trylock(&mm->mmap_sem));
2653 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2655 for (vma = mm->mmap; vma; vma = vma->vm_next) {
2656 if (vma->anon_vma)
2657 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2658 vm_unlock_anon_vma(avc->anon_vma);
2659 if (vma->vm_file && vma->vm_file->f_mapping)
2660 vm_unlock_mapping(vma->vm_file->f_mapping);
2663 mutex_unlock(&mm_all_locks_mutex);
2667 * initialise the VMA slab
2669 void __init mmap_init(void)
2671 int ret;
2673 ret = percpu_counter_init(&vm_committed_as, 0);
2674 VM_BUG_ON(ret);