UBUNTU: Ubuntu-2.6.38-11.47
[linux-flexiantxendom0-natty.git] / mm / mmap.c
1 /*
2  * mm/mmap.c
3  *
4  * Written by obz.
5  *
6  * Address space accounting code        <alan@lxorguk.ukuu.org.uk>
7  */
8
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/module.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>
33 #include <linux/random.h>
34
35 #include <asm/uaccess.h>
36 #include <asm/cacheflush.h>
37 #include <asm/tlb.h>
38 #include <asm/mmu_context.h>
39
40 #include "internal.h"
41
42 #ifndef arch_mmap_check
43 #define arch_mmap_check(addr, len, flags)       (0)
44 #endif
45
46 #ifndef arch_rebalance_pgtables
47 #define arch_rebalance_pgtables(addr, len)              (addr)
48 #endif
49
50 /* No sane architecture will #define these to anything else */
51 #ifndef arch_add_exec_range
52 #define arch_add_exec_range(mm, limit)  do { ; } while (0)
53 #endif
54 #ifndef arch_flush_exec_range
55 #define arch_flush_exec_range(mm)       do { ; } while (0)
56 #endif
57 #ifndef arch_remove_exec_range
58 #define arch_remove_exec_range(mm, limit)       do { ; } while (0)
59 #endif
60
61
62 static void unmap_region(struct mm_struct *mm,
63                 struct vm_area_struct *vma, struct vm_area_struct *prev,
64                 unsigned long start, unsigned long end);
65
66 /*
67  * WARNING: the debugging will use recursive algorithms so never enable this
68  * unless you know what you are doing.
69  */
70 #undef DEBUG_MM_RB
71
72 /* description of effects of mapping type and prot in current implementation.
73  * this is due to the limited x86 page protection hardware.  The expected
74  * behavior is in parens:
75  *
76  * map_type     prot
77  *              PROT_NONE       PROT_READ       PROT_WRITE      PROT_EXEC
78  * MAP_SHARED   r: (no) no      r: (yes) yes    r: (no) yes     r: (no) yes
79  *              w: (no) no      w: (no) no      w: (yes) yes    w: (no) no
80  *              x: (no) no      x: (no) yes     x: (no) yes     x: (yes) yes
81  *              
82  * MAP_PRIVATE  r: (no) no      r: (yes) yes    r: (no) yes     r: (no) yes
83  *              w: (no) no      w: (no) no      w: (copy) copy  w: (no) no
84  *              x: (no) no      x: (no) yes     x: (no) yes     x: (yes) yes
85  *
86  */
87 pgprot_t protection_map[16] = {
88         __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
89         __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
90 };
91
92 pgprot_t vm_get_page_prot(unsigned long vm_flags)
93 {
94         return __pgprot(pgprot_val(protection_map[vm_flags &
95                                 (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
96                         pgprot_val(arch_vm_get_page_prot(vm_flags)));
97 }
98 EXPORT_SYMBOL(vm_get_page_prot);
99
100 int sysctl_overcommit_memory = OVERCOMMIT_GUESS;  /* heuristic overcommit */
101 int sysctl_overcommit_ratio = 50;       /* default is 50% */
102 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
103 struct percpu_counter vm_committed_as;
104
105 /*
106  * Check that a process has enough memory to allocate a new virtual
107  * mapping. 0 means there is enough memory for the allocation to
108  * succeed and -ENOMEM implies there is not.
109  *
110  * We currently support three overcommit policies, which are set via the
111  * vm.overcommit_memory sysctl.  See Documentation/vm/overcommit-accounting
112  *
113  * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
114  * Additional code 2002 Jul 20 by Robert Love.
115  *
116  * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
117  *
118  * Note this is a helper function intended to be used by LSMs which
119  * wish to use this logic.
120  */
121 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
122 {
123         unsigned long free, allowed;
124
125         vm_acct_memory(pages);
126
127         /*
128          * Sometimes we want to use more memory than we have
129          */
130         if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
131                 return 0;
132
133         if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
134                 unsigned long n;
135
136                 free = global_page_state(NR_FILE_PAGES);
137                 free += nr_swap_pages;
138
139                 /*
140                  * Any slabs which are created with the
141                  * SLAB_RECLAIM_ACCOUNT flag claim to have contents
142                  * which are reclaimable, under pressure.  The dentry
143                  * cache and most inode caches should fall into this
144                  */
145                 free += global_page_state(NR_SLAB_RECLAIMABLE);
146
147                 /*
148                  * Leave the last 3% for root
149                  */
150                 if (!cap_sys_admin)
151                         free -= free / 32;
152
153                 if (free > pages)
154                         return 0;
155
156                 /*
157                  * nr_free_pages() is very expensive on large systems,
158                  * only call if we're about to fail.
159                  */
160                 n = nr_free_pages();
161
162                 /*
163                  * Leave reserved pages. The pages are not for anonymous pages.
164                  */
165                 if (n <= totalreserve_pages)
166                         goto error;
167                 else
168                         n -= totalreserve_pages;
169
170                 /*
171                  * Leave the last 3% for root
172                  */
173                 if (!cap_sys_admin)
174                         n -= n / 32;
175                 free += n;
176
177                 if (free > pages)
178                         return 0;
179
180                 goto error;
181         }
182
183         allowed = (totalram_pages - hugetlb_total_pages())
184                 * sysctl_overcommit_ratio / 100;
185         /*
186          * Leave the last 3% for root
187          */
188         if (!cap_sys_admin)
189                 allowed -= allowed / 32;
190         allowed += total_swap_pages;
191
192         /* Don't let a single process grow too big:
193            leave 3% of the size of this process for other processes */
194         if (mm)
195                 allowed -= mm->total_vm / 32;
196
197         if (percpu_counter_read_positive(&vm_committed_as) < allowed)
198                 return 0;
199 error:
200         vm_unacct_memory(pages);
201
202         return -ENOMEM;
203 }
204
205 /*
206  * Requires inode->i_mapping->i_mmap_lock
207  */
208 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
209                 struct file *file, struct address_space *mapping)
210 {
211         if (vma->vm_flags & VM_DENYWRITE)
212                 atomic_inc(&file->f_path.dentry->d_inode->i_writecount);
213         if (vma->vm_flags & VM_SHARED)
214                 mapping->i_mmap_writable--;
215
216         flush_dcache_mmap_lock(mapping);
217         if (unlikely(vma->vm_flags & VM_NONLINEAR))
218                 list_del_init(&vma->shared.vm_set.list);
219         else
220                 vma_prio_tree_remove(vma, &mapping->i_mmap);
221         flush_dcache_mmap_unlock(mapping);
222 }
223
224 /*
225  * Unlink a file-based vm structure from its prio_tree, to hide
226  * vma from rmap and vmtruncate before freeing its page tables.
227  */
228 void unlink_file_vma(struct vm_area_struct *vma)
229 {
230         struct file *file = vma->vm_file;
231
232         if (file) {
233                 struct address_space *mapping = file->f_mapping;
234                 spin_lock(&mapping->i_mmap_lock);
235                 __remove_shared_vm_struct(vma, file, mapping);
236                 spin_unlock(&mapping->i_mmap_lock);
237         }
238 }
239
240 /*
241  * Close a vm structure and free it, returning the next.
242  */
243 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
244 {
245         struct vm_area_struct *next = vma->vm_next;
246
247         might_sleep();
248         if (vma->vm_ops && vma->vm_ops->close)
249                 vma->vm_ops->close(vma);
250         if (vma->vm_file) {
251                 fput(vma->vm_file);
252                 if (vma->vm_flags & VM_EXECUTABLE)
253                         removed_exe_file_vma(vma->vm_mm);
254         }
255         mpol_put(vma_policy(vma));
256         kmem_cache_free(vm_area_cachep, vma);
257         return next;
258 }
259
260 SYSCALL_DEFINE1(brk, unsigned long, brk)
261 {
262         unsigned long rlim, retval;
263         unsigned long newbrk, oldbrk;
264         struct mm_struct *mm = current->mm;
265         unsigned long min_brk;
266
267         down_write(&mm->mmap_sem);
268
269 #ifdef CONFIG_COMPAT_BRK
270         /*
271          * CONFIG_COMPAT_BRK can still be overridden by setting
272          * randomize_va_space to 2, which will still cause mm->start_brk
273          * to be arbitrarily shifted
274          */
275         if (current->brk_randomized)
276                 min_brk = mm->start_brk;
277         else
278                 min_brk = mm->end_data;
279 #else
280         min_brk = mm->start_brk;
281 #endif
282         if (brk < min_brk)
283                 goto out;
284
285         /*
286          * Check against rlimit here. If this check is done later after the test
287          * of oldbrk with newbrk then it can escape the test and let the data
288          * segment grow beyond its set limit the in case where the limit is
289          * not page aligned -Ram Gupta
290          */
291         rlim = rlimit(RLIMIT_DATA);
292         if (rlim < RLIM_INFINITY && (brk - mm->start_brk) +
293                         (mm->end_data - mm->start_data) > rlim)
294                 goto out;
295
296         newbrk = PAGE_ALIGN(brk);
297         oldbrk = PAGE_ALIGN(mm->brk);
298         if (oldbrk == newbrk)
299                 goto set_brk;
300
301         /* Always allow shrinking brk. */
302         if (brk <= mm->brk) {
303                 if (!do_munmap(mm, newbrk, oldbrk-newbrk))
304                         goto set_brk;
305                 goto out;
306         }
307
308         /* Check against existing mmap mappings. */
309         if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE))
310                 goto out;
311
312         /* Ok, looks good - let it rip. */
313         if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
314                 goto out;
315 set_brk:
316         mm->brk = brk;
317 out:
318         retval = mm->brk;
319         up_write(&mm->mmap_sem);
320         return retval;
321 }
322
323 #ifdef DEBUG_MM_RB
324 static int browse_rb(struct rb_root *root)
325 {
326         int i = 0, j;
327         struct rb_node *nd, *pn = NULL;
328         unsigned long prev = 0, pend = 0;
329
330         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
331                 struct vm_area_struct *vma;
332                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
333                 if (vma->vm_start < prev)
334                         printk("vm_start %lx prev %lx\n", vma->vm_start, prev), i = -1;
335                 if (vma->vm_start < pend)
336                         printk("vm_start %lx pend %lx\n", vma->vm_start, pend);
337                 if (vma->vm_start > vma->vm_end)
338                         printk("vm_end %lx < vm_start %lx\n", vma->vm_end, vma->vm_start);
339                 i++;
340                 pn = nd;
341                 prev = vma->vm_start;
342                 pend = vma->vm_end;
343         }
344         j = 0;
345         for (nd = pn; nd; nd = rb_prev(nd)) {
346                 j++;
347         }
348         if (i != j)
349                 printk("backwards %d, forwards %d\n", j, i), i = 0;
350         return i;
351 }
352
353 void validate_mm(struct mm_struct *mm)
354 {
355         int bug = 0;
356         int i = 0;
357         struct vm_area_struct *tmp = mm->mmap;
358         while (tmp) {
359                 tmp = tmp->vm_next;
360                 i++;
361         }
362         if (i != mm->map_count)
363                 printk("map_count %d vm_next %d\n", mm->map_count, i), bug = 1;
364         i = browse_rb(&mm->mm_rb);
365         if (i != mm->map_count)
366                 printk("map_count %d rb %d\n", mm->map_count, i), bug = 1;
367         BUG_ON(bug);
368 }
369 #else
370 #define validate_mm(mm) do { } while (0)
371 #endif
372
373 static struct vm_area_struct *
374 find_vma_prepare(struct mm_struct *mm, unsigned long addr,
375                 struct vm_area_struct **pprev, struct rb_node ***rb_link,
376                 struct rb_node ** rb_parent)
377 {
378         struct vm_area_struct * vma;
379         struct rb_node ** __rb_link, * __rb_parent, * rb_prev;
380
381         __rb_link = &mm->mm_rb.rb_node;
382         rb_prev = __rb_parent = NULL;
383         vma = NULL;
384
385         while (*__rb_link) {
386                 struct vm_area_struct *vma_tmp;
387
388                 __rb_parent = *__rb_link;
389                 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
390
391                 if (vma_tmp->vm_end > addr) {
392                         vma = vma_tmp;
393                         if (vma_tmp->vm_start <= addr)
394                                 break;
395                         __rb_link = &__rb_parent->rb_left;
396                 } else {
397                         rb_prev = __rb_parent;
398                         __rb_link = &__rb_parent->rb_right;
399                 }
400         }
401
402         *pprev = NULL;
403         if (rb_prev)
404                 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
405         *rb_link = __rb_link;
406         *rb_parent = __rb_parent;
407         return vma;
408 }
409
410 static inline void
411 __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
412                 struct vm_area_struct *prev, struct rb_node *rb_parent)
413 {
414         struct vm_area_struct *next;
415
416         if (vma->vm_flags & VM_EXEC)
417                 arch_add_exec_range(mm, vma->vm_end);
418
419         vma->vm_prev = prev;
420         if (prev) {
421                 next = prev->vm_next;
422                 prev->vm_next = vma;
423         } else {
424                 mm->mmap = vma;
425                 if (rb_parent)
426                         next = rb_entry(rb_parent,
427                                         struct vm_area_struct, vm_rb);
428                 else
429                         next = NULL;
430         }
431         vma->vm_next = next;
432         if (next)
433                 next->vm_prev = vma;
434 }
435
436 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
437                 struct rb_node **rb_link, struct rb_node *rb_parent)
438 {
439         rb_link_node(&vma->vm_rb, rb_parent, rb_link);
440         rb_insert_color(&vma->vm_rb, &mm->mm_rb);
441 }
442
443 static void __vma_link_file(struct vm_area_struct *vma)
444 {
445         struct file *file;
446
447         file = vma->vm_file;
448         if (file) {
449                 struct address_space *mapping = file->f_mapping;
450
451                 if (vma->vm_flags & VM_DENYWRITE)
452                         atomic_dec(&file->f_path.dentry->d_inode->i_writecount);
453                 if (vma->vm_flags & VM_SHARED)
454                         mapping->i_mmap_writable++;
455
456                 flush_dcache_mmap_lock(mapping);
457                 if (unlikely(vma->vm_flags & VM_NONLINEAR))
458                         vma_nonlinear_insert(vma, &mapping->i_mmap_nonlinear);
459                 else
460                         vma_prio_tree_insert(vma, &mapping->i_mmap);
461                 flush_dcache_mmap_unlock(mapping);
462         }
463 }
464
465 static void
466 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
467         struct vm_area_struct *prev, struct rb_node **rb_link,
468         struct rb_node *rb_parent)
469 {
470         __vma_link_list(mm, vma, prev, rb_parent);
471         __vma_link_rb(mm, vma, rb_link, rb_parent);
472 }
473
474 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
475                         struct vm_area_struct *prev, struct rb_node **rb_link,
476                         struct rb_node *rb_parent)
477 {
478         struct address_space *mapping = NULL;
479
480         if (vma->vm_file)
481                 mapping = vma->vm_file->f_mapping;
482
483         if (mapping) {
484                 spin_lock(&mapping->i_mmap_lock);
485                 vma->vm_truncate_count = mapping->truncate_count;
486         }
487
488         __vma_link(mm, vma, prev, rb_link, rb_parent);
489         __vma_link_file(vma);
490
491         if (mapping)
492                 spin_unlock(&mapping->i_mmap_lock);
493
494         mm->map_count++;
495         validate_mm(mm);
496 }
497
498 /*
499  * Helper for vma_adjust in the split_vma insert case:
500  * insert vm structure into list and rbtree and anon_vma,
501  * but it has already been inserted into prio_tree earlier.
502  */
503 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
504 {
505         struct vm_area_struct *__vma, *prev;
506         struct rb_node **rb_link, *rb_parent;
507
508         __vma = find_vma_prepare(mm, vma->vm_start,&prev, &rb_link, &rb_parent);
509         BUG_ON(__vma && __vma->vm_start < vma->vm_end);
510         __vma_link(mm, vma, prev, rb_link, rb_parent);
511         mm->map_count++;
512 }
513
514 static inline void
515 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
516                 struct vm_area_struct *prev)
517 {
518         struct vm_area_struct *next = vma->vm_next;
519
520         prev->vm_next = next;
521         if (next)
522                 next->vm_prev = prev;
523         rb_erase(&vma->vm_rb, &mm->mm_rb);
524         if (mm->mmap_cache == vma)
525                 mm->mmap_cache = prev;
526         if (vma->vm_flags & VM_EXEC)
527                 arch_remove_exec_range(mm, vma->vm_end);
528 }
529
530 /*
531  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
532  * is already present in an i_mmap tree without adjusting the tree.
533  * The following helper function should be used when such adjustments
534  * are necessary.  The "insert" vma (if any) is to be inserted
535  * before we drop the necessary locks.
536  */
537 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
538         unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
539 {
540         struct mm_struct *mm = vma->vm_mm;
541         struct vm_area_struct *next = vma->vm_next;
542         struct vm_area_struct *importer = NULL;
543         struct address_space *mapping = NULL;
544         struct prio_tree_root *root = NULL;
545         struct anon_vma *anon_vma = NULL;
546         struct file *file = vma->vm_file;
547         long adjust_next = 0;
548         int remove_next = 0;
549
550         if (next && !insert) {
551                 struct vm_area_struct *exporter = NULL;
552
553                 if (end >= next->vm_end) {
554                         /*
555                          * vma expands, overlapping all the next, and
556                          * perhaps the one after too (mprotect case 6).
557                          */
558 again:                  remove_next = 1 + (end > next->vm_end);
559                         end = next->vm_end;
560                         exporter = next;
561                         importer = vma;
562                 } else if (end > next->vm_start) {
563                         /*
564                          * vma expands, overlapping part of the next:
565                          * mprotect case 5 shifting the boundary up.
566                          */
567                         adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
568                         exporter = next;
569                         importer = vma;
570                 } else if (end < vma->vm_end) {
571                         /*
572                          * vma shrinks, and !insert tells it's not
573                          * split_vma inserting another: so it must be
574                          * mprotect case 4 shifting the boundary down.
575                          */
576                         adjust_next = - ((vma->vm_end - end) >> PAGE_SHIFT);
577                         exporter = vma;
578                         importer = next;
579                 }
580
581                 /*
582                  * Easily overlooked: when mprotect shifts the boundary,
583                  * make sure the expanding vma has anon_vma set if the
584                  * shrinking vma had, to cover any anon pages imported.
585                  */
586                 if (exporter && exporter->anon_vma && !importer->anon_vma) {
587                         if (anon_vma_clone(importer, exporter))
588                                 return -ENOMEM;
589                         importer->anon_vma = exporter->anon_vma;
590                 }
591         }
592
593         if (file) {
594                 mapping = file->f_mapping;
595                 if (!(vma->vm_flags & VM_NONLINEAR))
596                         root = &mapping->i_mmap;
597                 spin_lock(&mapping->i_mmap_lock);
598                 if (importer &&
599                     vma->vm_truncate_count != next->vm_truncate_count) {
600                         /*
601                          * unmap_mapping_range might be in progress:
602                          * ensure that the expanding vma is rescanned.
603                          */
604                         importer->vm_truncate_count = 0;
605                 }
606                 if (insert) {
607                         insert->vm_truncate_count = vma->vm_truncate_count;
608                         /*
609                          * Put into prio_tree now, so instantiated pages
610                          * are visible to arm/parisc __flush_dcache_page
611                          * throughout; but we cannot insert into address
612                          * space until vma start or end is updated.
613                          */
614                         __vma_link_file(insert);
615                 }
616         }
617
618         vma_adjust_trans_huge(vma, start, end, adjust_next);
619
620         /*
621          * When changing only vma->vm_end, we don't really need anon_vma
622          * lock. This is a fairly rare case by itself, but the anon_vma
623          * lock may be shared between many sibling processes.  Skipping
624          * the lock for brk adjustments makes a difference sometimes.
625          */
626         if (vma->anon_vma && (insert || importer || start != vma->vm_start)) {
627                 anon_vma = vma->anon_vma;
628                 anon_vma_lock(anon_vma);
629         }
630
631         if (root) {
632                 flush_dcache_mmap_lock(mapping);
633                 vma_prio_tree_remove(vma, root);
634                 if (adjust_next)
635                         vma_prio_tree_remove(next, root);
636         }
637
638         vma->vm_start = start;
639         vma->vm_end = end;
640         vma->vm_pgoff = pgoff;
641         if (adjust_next) {
642                 next->vm_start += adjust_next << PAGE_SHIFT;
643                 next->vm_pgoff += adjust_next;
644         }
645
646         if (root) {
647                 if (adjust_next)
648                         vma_prio_tree_insert(next, root);
649                 vma_prio_tree_insert(vma, root);
650                 flush_dcache_mmap_unlock(mapping);
651         }
652
653         if (remove_next) {
654                 /*
655                  * vma_merge has merged next into vma, and needs
656                  * us to remove next before dropping the locks.
657                  */
658                 __vma_unlink(mm, next, vma);
659                 if (file)
660                         __remove_shared_vm_struct(next, file, mapping);
661         } else if (insert) {
662                 /*
663                  * split_vma has split insert from vma, and needs
664                  * us to insert it before dropping the locks
665                  * (it may either follow vma or precede it).
666                  */
667                 __insert_vm_struct(mm, insert);
668         }
669
670         if (anon_vma)
671                 anon_vma_unlock(anon_vma);
672         if (mapping)
673                 spin_unlock(&mapping->i_mmap_lock);
674
675         if (remove_next) {
676                 if (file) {
677                         fput(file);
678                         if (next->vm_flags & VM_EXECUTABLE)
679                                 removed_exe_file_vma(mm);
680                 }
681                 if (next->anon_vma)
682                         anon_vma_merge(vma, next);
683                 mm->map_count--;
684                 mpol_put(vma_policy(next));
685                 kmem_cache_free(vm_area_cachep, next);
686                 /*
687                  * In mprotect's case 6 (see comments on vma_merge),
688                  * we must remove another next too. It would clutter
689                  * up the code too much to do both in one go.
690                  */
691                 if (remove_next == 2) {
692                         next = vma->vm_next;
693                         goto again;
694                 }
695         }
696
697         validate_mm(mm);
698
699         return 0;
700 }
701
702 /*
703  * If the vma has a ->close operation then the driver probably needs to release
704  * per-vma resources, so we don't attempt to merge those.
705  */
706 static inline int is_mergeable_vma(struct vm_area_struct *vma,
707                         struct file *file, unsigned long vm_flags)
708 {
709         /* VM_CAN_NONLINEAR may get set later by f_op->mmap() */
710         if ((vma->vm_flags ^ vm_flags) & ~VM_CAN_NONLINEAR)
711                 return 0;
712         if (vma->vm_file != file)
713                 return 0;
714         if (vma->vm_ops && vma->vm_ops->close)
715                 return 0;
716         return 1;
717 }
718
719 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
720                                         struct anon_vma *anon_vma2)
721 {
722         return !anon_vma1 || !anon_vma2 || (anon_vma1 == anon_vma2);
723 }
724
725 /*
726  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
727  * in front of (at a lower virtual address and file offset than) the vma.
728  *
729  * We cannot merge two vmas if they have differently assigned (non-NULL)
730  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
731  *
732  * We don't check here for the merged mmap wrapping around the end of pagecache
733  * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
734  * wrap, nor mmaps which cover the final page at index -1UL.
735  */
736 static int
737 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
738         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
739 {
740         if (is_mergeable_vma(vma, file, vm_flags) &&
741             is_mergeable_anon_vma(anon_vma, vma->anon_vma)) {
742                 if (vma->vm_pgoff == vm_pgoff)
743                         return 1;
744         }
745         return 0;
746 }
747
748 /*
749  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
750  * beyond (at a higher virtual address and file offset than) the vma.
751  *
752  * We cannot merge two vmas if they have differently assigned (non-NULL)
753  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
754  */
755 static int
756 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
757         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
758 {
759         if (is_mergeable_vma(vma, file, vm_flags) &&
760             is_mergeable_anon_vma(anon_vma, vma->anon_vma)) {
761                 pgoff_t vm_pglen;
762                 vm_pglen = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
763                 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
764                         return 1;
765         }
766         return 0;
767 }
768
769 /*
770  * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
771  * whether that can be merged with its predecessor or its successor.
772  * Or both (it neatly fills a hole).
773  *
774  * In most cases - when called for mmap, brk or mremap - [addr,end) is
775  * certain not to be mapped by the time vma_merge is called; but when
776  * called for mprotect, it is certain to be already mapped (either at
777  * an offset within prev, or at the start of next), and the flags of
778  * this area are about to be changed to vm_flags - and the no-change
779  * case has already been eliminated.
780  *
781  * The following mprotect cases have to be considered, where AAAA is
782  * the area passed down from mprotect_fixup, never extending beyond one
783  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
784  *
785  *     AAAA             AAAA                AAAA          AAAA
786  *    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPNNNNXXXX
787  *    cannot merge    might become    might become    might become
788  *                    PPNNNNNNNNNN    PPPPPPPPPPNN    PPPPPPPPPPPP 6 or
789  *    mmap, brk or    case 4 below    case 5 below    PPPPPPPPXXXX 7 or
790  *    mremap move:                                    PPPPNNNNNNNN 8
791  *        AAAA
792  *    PPPP    NNNN    PPPPPPPPPPPP    PPPPPPPPNNNN    PPPPNNNNNNNN
793  *    might become    case 1 below    case 2 below    case 3 below
794  *
795  * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
796  * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
797  */
798 struct vm_area_struct *vma_merge(struct mm_struct *mm,
799                         struct vm_area_struct *prev, unsigned long addr,
800                         unsigned long end, unsigned long vm_flags,
801                         struct anon_vma *anon_vma, struct file *file,
802                         pgoff_t pgoff, struct mempolicy *policy)
803 {
804         pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
805         struct vm_area_struct *area, *next;
806         int err;
807
808         /*
809          * We later require that vma->vm_flags == vm_flags,
810          * so this tests vma->vm_flags & VM_SPECIAL, too.
811          */
812         if (vm_flags & VM_SPECIAL)
813                 return NULL;
814
815         if (prev)
816                 next = prev->vm_next;
817         else
818                 next = mm->mmap;
819         area = next;
820         if (next && next->vm_end == end)                /* cases 6, 7, 8 */
821                 next = next->vm_next;
822
823         /*
824          * Can it merge with the predecessor?
825          */
826         if (prev && prev->vm_end == addr &&
827                         mpol_equal(vma_policy(prev), policy) &&
828                         can_vma_merge_after(prev, vm_flags,
829                                                 anon_vma, file, pgoff)) {
830                 /*
831                  * OK, it can.  Can we now merge in the successor as well?
832                  */
833                 if (next && end == next->vm_start &&
834                                 mpol_equal(policy, vma_policy(next)) &&
835                                 can_vma_merge_before(next, vm_flags,
836                                         anon_vma, file, pgoff+pglen) &&
837                                 is_mergeable_anon_vma(prev->anon_vma,
838                                                       next->anon_vma)) {
839                                                         /* cases 1, 6 */
840                         err = vma_adjust(prev, prev->vm_start,
841                                 next->vm_end, prev->vm_pgoff, NULL);
842                 } else                                  /* cases 2, 5, 7 */
843                         err = vma_adjust(prev, prev->vm_start,
844                                 end, prev->vm_pgoff, NULL);
845                 if (prev->vm_flags & VM_EXEC)
846                         arch_add_exec_range(mm, prev->vm_end);
847                 if (err)
848                         return NULL;
849                 khugepaged_enter_vma_merge(prev);
850                 return prev;
851         }
852
853         /*
854          * Can this new request be merged in front of next?
855          */
856         if (next && end == next->vm_start &&
857                         mpol_equal(policy, vma_policy(next)) &&
858                         can_vma_merge_before(next, vm_flags,
859                                         anon_vma, file, pgoff+pglen)) {
860                 if (prev && addr < prev->vm_end)        /* case 4 */
861                         err = vma_adjust(prev, prev->vm_start,
862                                 addr, prev->vm_pgoff, NULL);
863                 else                                    /* cases 3, 8 */
864                         err = vma_adjust(area, addr, next->vm_end,
865                                 next->vm_pgoff - pglen, NULL);
866                 if (err)
867                         return NULL;
868                 khugepaged_enter_vma_merge(area);
869                 return area;
870         }
871
872         return NULL;
873 }
874
875 /*
876  * Rough compatbility check to quickly see if it's even worth looking
877  * at sharing an anon_vma.
878  *
879  * They need to have the same vm_file, and the flags can only differ
880  * in things that mprotect may change.
881  *
882  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
883  * we can merge the two vma's. For example, we refuse to merge a vma if
884  * there is a vm_ops->close() function, because that indicates that the
885  * driver is doing some kind of reference counting. But that doesn't
886  * really matter for the anon_vma sharing case.
887  */
888 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
889 {
890         return a->vm_end == b->vm_start &&
891                 mpol_equal(vma_policy(a), vma_policy(b)) &&
892                 a->vm_file == b->vm_file &&
893                 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC)) &&
894                 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
895 }
896
897 /*
898  * Do some basic sanity checking to see if we can re-use the anon_vma
899  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
900  * the same as 'old', the other will be the new one that is trying
901  * to share the anon_vma.
902  *
903  * NOTE! This runs with mm_sem held for reading, so it is possible that
904  * the anon_vma of 'old' is concurrently in the process of being set up
905  * by another page fault trying to merge _that_. But that's ok: if it
906  * is being set up, that automatically means that it will be a singleton
907  * acceptable for merging, so we can do all of this optimistically. But
908  * we do that ACCESS_ONCE() to make sure that we never re-load the pointer.
909  *
910  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
911  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
912  * is to return an anon_vma that is "complex" due to having gone through
913  * a fork).
914  *
915  * We also make sure that the two vma's are compatible (adjacent,
916  * and with the same memory policies). That's all stable, even with just
917  * a read lock on the mm_sem.
918  */
919 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
920 {
921         if (anon_vma_compatible(a, b)) {
922                 struct anon_vma *anon_vma = ACCESS_ONCE(old->anon_vma);
923
924                 if (anon_vma && list_is_singular(&old->anon_vma_chain))
925                         return anon_vma;
926         }
927         return NULL;
928 }
929
930 /*
931  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
932  * neighbouring vmas for a suitable anon_vma, before it goes off
933  * to allocate a new anon_vma.  It checks because a repetitive
934  * sequence of mprotects and faults may otherwise lead to distinct
935  * anon_vmas being allocated, preventing vma merge in subsequent
936  * mprotect.
937  */
938 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
939 {
940         struct anon_vma *anon_vma;
941         struct vm_area_struct *near;
942
943         near = vma->vm_next;
944         if (!near)
945                 goto try_prev;
946
947         anon_vma = reusable_anon_vma(near, vma, near);
948         if (anon_vma)
949                 return anon_vma;
950 try_prev:
951         /*
952          * It is potentially slow to have to call find_vma_prev here.
953          * But it's only on the first write fault on the vma, not
954          * every time, and we could devise a way to avoid it later
955          * (e.g. stash info in next's anon_vma_node when assigning
956          * an anon_vma, or when trying vma_merge).  Another time.
957          */
958         BUG_ON(find_vma_prev(vma->vm_mm, vma->vm_start, &near) != vma);
959         if (!near)
960                 goto none;
961
962         anon_vma = reusable_anon_vma(near, near, vma);
963         if (anon_vma)
964                 return anon_vma;
965 none:
966         /*
967          * There's no absolute need to look only at touching neighbours:
968          * we could search further afield for "compatible" anon_vmas.
969          * But it would probably just be a waste of time searching,
970          * or lead to too many vmas hanging off the same anon_vma.
971          * We're trying to allow mprotect remerging later on,
972          * not trying to minimize memory used for anon_vmas.
973          */
974         return NULL;
975 }
976
977 #ifdef CONFIG_PROC_FS
978 void vm_stat_account(struct mm_struct *mm, unsigned long flags,
979                                                 struct file *file, long pages)
980 {
981         const unsigned long stack_flags
982                 = VM_STACK_FLAGS & (VM_GROWSUP|VM_GROWSDOWN);
983
984         if (file) {
985                 mm->shared_vm += pages;
986                 if ((flags & (VM_EXEC|VM_WRITE)) == VM_EXEC)
987                         mm->exec_vm += pages;
988         } else if (flags & stack_flags)
989                 mm->stack_vm += pages;
990         if (flags & (VM_RESERVED|VM_IO))
991                 mm->reserved_vm += pages;
992 }
993 #endif /* CONFIG_PROC_FS */
994
995 /*
996  * The caller must hold down_write(&current->mm->mmap_sem).
997  */
998
999 unsigned long do_mmap_pgoff(struct file *file, unsigned long addr,
1000                         unsigned long len, unsigned long prot,
1001                         unsigned long flags, unsigned long pgoff)
1002 {
1003         struct mm_struct * mm = current->mm;
1004         struct inode *inode;
1005         unsigned int vm_flags;
1006         int error;
1007         unsigned long reqprot = prot;
1008
1009         /*
1010          * Does the application expect PROT_READ to imply PROT_EXEC?
1011          *
1012          * (the exception is when the underlying filesystem is noexec
1013          *  mounted, in which case we dont add PROT_EXEC.)
1014          */
1015         if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1016                 if (!(file && (file->f_path.mnt->mnt_flags & MNT_NOEXEC)))
1017                         prot |= PROT_EXEC;
1018
1019         if (!len)
1020                 return -EINVAL;
1021
1022         if (!(flags & MAP_FIXED))
1023                 addr = round_hint_to_min(addr);
1024
1025         /* Careful about overflows.. */
1026         len = PAGE_ALIGN(len);
1027         if (!len)
1028                 return -ENOMEM;
1029
1030         /* offset overflow? */
1031         if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1032                return -EOVERFLOW;
1033
1034         /* Too many mappings? */
1035         if (mm->map_count > sysctl_max_map_count)
1036                 return -ENOMEM;
1037
1038         /* Obtain the address to map to. we verify (or select) it and ensure
1039          * that it represents a valid section of the address space.
1040          */
1041         addr = get_unmapped_area_prot(file, addr, len, pgoff, flags,
1042                 prot & PROT_EXEC);
1043         if (addr & ~PAGE_MASK)
1044                 return addr;
1045
1046         /* Do simple checking here so the lower-level routines won't have
1047          * to. we assume access permissions have been handled by the open
1048          * of the memory object, so we don't do any here.
1049          */
1050         vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
1051                         mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1052
1053         if (flags & MAP_LOCKED)
1054                 if (!can_do_mlock())
1055                         return -EPERM;
1056
1057         /* mlock MCL_FUTURE? */
1058         if (vm_flags & VM_LOCKED) {
1059                 unsigned long locked, lock_limit;
1060                 locked = len >> PAGE_SHIFT;
1061                 locked += mm->locked_vm;
1062                 lock_limit = rlimit(RLIMIT_MEMLOCK);
1063                 lock_limit >>= PAGE_SHIFT;
1064                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1065                         return -EAGAIN;
1066         }
1067
1068         inode = file ? file->f_path.dentry->d_inode : NULL;
1069
1070         if (file) {
1071                 switch (flags & MAP_TYPE) {
1072                 case MAP_SHARED:
1073                         if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1074                                 return -EACCES;
1075
1076                         /*
1077                          * Make sure we don't allow writing to an append-only
1078                          * file..
1079                          */
1080                         if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1081                                 return -EACCES;
1082
1083                         /*
1084                          * Make sure there are no mandatory locks on the file.
1085                          */
1086                         if (locks_verify_locked(inode))
1087                                 return -EAGAIN;
1088
1089                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1090                         if (!(file->f_mode & FMODE_WRITE))
1091                                 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1092
1093                         /* fall through */
1094                 case MAP_PRIVATE:
1095                         if (!(file->f_mode & FMODE_READ))
1096                                 return -EACCES;
1097                         if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
1098                                 if (vm_flags & VM_EXEC)
1099                                         return -EPERM;
1100                                 vm_flags &= ~VM_MAYEXEC;
1101                         }
1102
1103                         if (!file->f_op || !file->f_op->mmap)
1104                                 return -ENODEV;
1105                         break;
1106
1107                 default:
1108                         return -EINVAL;
1109                 }
1110         } else {
1111                 switch (flags & MAP_TYPE) {
1112                 case MAP_SHARED:
1113                         /*
1114                          * Ignore pgoff.
1115                          */
1116                         pgoff = 0;
1117                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1118                         break;
1119                 case MAP_PRIVATE:
1120                         /*
1121                          * Set pgoff according to addr for anon_vma.
1122                          */
1123                         pgoff = addr >> PAGE_SHIFT;
1124                         break;
1125                 default:
1126                         return -EINVAL;
1127                 }
1128         }
1129
1130         error = security_file_mmap(file, reqprot, prot, flags, addr, 0);
1131         if (error)
1132                 return error;
1133
1134         return mmap_region(file, addr, len, flags, vm_flags, pgoff);
1135 }
1136 EXPORT_SYMBOL(do_mmap_pgoff);
1137
1138 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1139                 unsigned long, prot, unsigned long, flags,
1140                 unsigned long, fd, unsigned long, pgoff)
1141 {
1142         struct file *file = NULL;
1143         unsigned long retval = -EBADF;
1144
1145         if (!(flags & MAP_ANONYMOUS)) {
1146                 audit_mmap_fd(fd, flags);
1147                 if (unlikely(flags & MAP_HUGETLB))
1148                         return -EINVAL;
1149                 file = fget(fd);
1150                 if (!file)
1151                         goto out;
1152         } else if (flags & MAP_HUGETLB) {
1153                 struct user_struct *user = NULL;
1154                 /*
1155                  * VM_NORESERVE is used because the reservations will be
1156                  * taken when vm_ops->mmap() is called
1157                  * A dummy user value is used because we are not locking
1158                  * memory so no accounting is necessary
1159                  */
1160                 len = ALIGN(len, huge_page_size(&default_hstate));
1161                 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len, VM_NORESERVE,
1162                                                 &user, HUGETLB_ANONHUGE_INODE);
1163                 if (IS_ERR(file))
1164                         return PTR_ERR(file);
1165         }
1166
1167         flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1168
1169         down_write(&current->mm->mmap_sem);
1170         retval = do_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1171         up_write(&current->mm->mmap_sem);
1172
1173         if (file)
1174                 fput(file);
1175 out:
1176         return retval;
1177 }
1178
1179 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1180 struct mmap_arg_struct {
1181         unsigned long addr;
1182         unsigned long len;
1183         unsigned long prot;
1184         unsigned long flags;
1185         unsigned long fd;
1186         unsigned long offset;
1187 };
1188
1189 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1190 {
1191         struct mmap_arg_struct a;
1192
1193         if (copy_from_user(&a, arg, sizeof(a)))
1194                 return -EFAULT;
1195         if (a.offset & ~PAGE_MASK)
1196                 return -EINVAL;
1197
1198         return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1199                               a.offset >> PAGE_SHIFT);
1200 }
1201 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1202
1203 /*
1204  * Some shared mappigns will want the pages marked read-only
1205  * to track write events. If so, we'll downgrade vm_page_prot
1206  * to the private version (using protection_map[] without the
1207  * VM_SHARED bit).
1208  */
1209 int vma_wants_writenotify(struct vm_area_struct *vma)
1210 {
1211         unsigned int vm_flags = vma->vm_flags;
1212
1213         /* If it was private or non-writable, the write bit is already clear */
1214         if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1215                 return 0;
1216
1217         /* The backer wishes to know when pages are first written to? */
1218         if (vma->vm_ops && vma->vm_ops->page_mkwrite)
1219                 return 1;
1220
1221         /* The open routine did something to the protections already? */
1222         if (pgprot_val(vma->vm_page_prot) !=
1223             pgprot_val(vm_get_page_prot(vm_flags)))
1224                 return 0;
1225
1226         /* Specialty mapping? */
1227         if (vm_flags & (VM_PFNMAP|VM_INSERTPAGE))
1228                 return 0;
1229
1230         /* Can the mapping track the dirty pages? */
1231         return vma->vm_file && vma->vm_file->f_mapping &&
1232                 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1233 }
1234
1235 /*
1236  * We account for memory if it's a private writeable mapping,
1237  * not hugepages and VM_NORESERVE wasn't set.
1238  */
1239 static inline int accountable_mapping(struct file *file, unsigned int vm_flags)
1240 {
1241         /*
1242          * hugetlb has its own accounting separate from the core VM
1243          * VM_HUGETLB may not be set yet so we cannot check for that flag.
1244          */
1245         if (file && is_file_hugepages(file))
1246                 return 0;
1247
1248         return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1249 }
1250
1251 unsigned long mmap_region(struct file *file, unsigned long addr,
1252                           unsigned long len, unsigned long flags,
1253                           unsigned int vm_flags, unsigned long pgoff)
1254 {
1255         struct mm_struct *mm = current->mm;
1256         struct vm_area_struct *vma, *prev;
1257         int correct_wcount = 0;
1258         int error;
1259         struct rb_node **rb_link, *rb_parent;
1260         unsigned long charged = 0;
1261         struct inode *inode =  file ? file->f_path.dentry->d_inode : NULL;
1262
1263         /* Clear old maps */
1264         error = -ENOMEM;
1265 munmap_back:
1266         vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
1267         if (vma && vma->vm_start < addr + len) {
1268                 if (do_munmap(mm, addr, len))
1269                         return -ENOMEM;
1270                 goto munmap_back;
1271         }
1272
1273         /* Check against address space limit. */
1274         if (!may_expand_vm(mm, len >> PAGE_SHIFT))
1275                 return -ENOMEM;
1276
1277         /*
1278          * Set 'VM_NORESERVE' if we should not account for the
1279          * memory use of this mapping.
1280          */
1281         if ((flags & MAP_NORESERVE)) {
1282                 /* We honor MAP_NORESERVE if allowed to overcommit */
1283                 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1284                         vm_flags |= VM_NORESERVE;
1285
1286                 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1287                 if (file && is_file_hugepages(file))
1288                         vm_flags |= VM_NORESERVE;
1289         }
1290
1291         /*
1292          * Private writable mapping: check memory availability
1293          */
1294         if (accountable_mapping(file, vm_flags)) {
1295                 charged = len >> PAGE_SHIFT;
1296                 if (security_vm_enough_memory(charged))
1297                         return -ENOMEM;
1298                 vm_flags |= VM_ACCOUNT;
1299         }
1300
1301         /*
1302          * Can we just expand an old mapping?
1303          */
1304         vma = vma_merge(mm, prev, addr, addr + len, vm_flags, NULL, file, pgoff, NULL);
1305         if (vma)
1306                 goto out;
1307
1308         /*
1309          * Determine the object being mapped and call the appropriate
1310          * specific mapper. the address has already been validated, but
1311          * not unmapped, but the maps are removed from the list.
1312          */
1313         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1314         if (!vma) {
1315                 error = -ENOMEM;
1316                 goto unacct_error;
1317         }
1318
1319         vma->vm_mm = mm;
1320         vma->vm_start = addr;
1321         vma->vm_end = addr + len;
1322         vma->vm_flags = vm_flags;
1323         vma->vm_page_prot = vm_get_page_prot(vm_flags);
1324         vma->vm_pgoff = pgoff;
1325         INIT_LIST_HEAD(&vma->anon_vma_chain);
1326
1327         if (file) {
1328                 error = -EINVAL;
1329                 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1330                         goto free_vma;
1331                 if (vm_flags & VM_DENYWRITE) {
1332                         error = deny_write_access(file);
1333                         if (error)
1334                                 goto free_vma;
1335                         correct_wcount = 1;
1336                 }
1337                 vma->vm_file = file;
1338                 get_file(file);
1339                 error = file->f_op->mmap(file, vma);
1340                 if (error)
1341                         goto unmap_and_free_vma;
1342                 if (vm_flags & VM_EXECUTABLE)
1343                         added_exe_file_vma(mm);
1344
1345                 /* Can addr have changed??
1346                  *
1347                  * Answer: Yes, several device drivers can do it in their
1348                  *         f_op->mmap method. -DaveM
1349                  */
1350                 addr = vma->vm_start;
1351                 pgoff = vma->vm_pgoff;
1352                 vm_flags = vma->vm_flags;
1353         } else if (vm_flags & VM_SHARED) {
1354                 error = shmem_zero_setup(vma);
1355                 if (error)
1356                         goto free_vma;
1357         }
1358
1359         if (vma_wants_writenotify(vma)) {
1360                 pgprot_t pprot = vma->vm_page_prot;
1361
1362                 /* Can vma->vm_page_prot have changed??
1363                  *
1364                  * Answer: Yes, drivers may have changed it in their
1365                  *         f_op->mmap method.
1366                  *
1367                  * Ensures that vmas marked as uncached stay that way.
1368                  */
1369                 vma->vm_page_prot = vm_get_page_prot(vm_flags & ~VM_SHARED);
1370                 if (pgprot_val(pprot) == pgprot_val(pgprot_noncached(pprot)))
1371                         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1372         }
1373
1374         vma_link(mm, vma, prev, rb_link, rb_parent);
1375         file = vma->vm_file;
1376
1377         /* Once vma denies write, undo our temporary denial count */
1378         if (correct_wcount)
1379                 atomic_inc(&inode->i_writecount);
1380 out:
1381         perf_event_mmap(vma);
1382
1383         mm->total_vm += len >> PAGE_SHIFT;
1384         vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1385         if (vm_flags & VM_LOCKED) {
1386                 if (!mlock_vma_pages_range(vma, addr, addr + len))
1387                         mm->locked_vm += (len >> PAGE_SHIFT);
1388         } else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
1389                 make_pages_present(addr, addr + len);
1390         return addr;
1391
1392 unmap_and_free_vma:
1393         if (correct_wcount)
1394                 atomic_inc(&inode->i_writecount);
1395         vma->vm_file = NULL;
1396         fput(file);
1397
1398         /* Undo any partial mapping done by a device driver. */
1399         unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1400         charged = 0;
1401 free_vma:
1402         kmem_cache_free(vm_area_cachep, vma);
1403 unacct_error:
1404         if (charged)
1405                 vm_unacct_memory(charged);
1406         return error;
1407 }
1408
1409 /* Get an address range which is currently unmapped.
1410  * For shmat() with addr=0.
1411  *
1412  * Ugly calling convention alert:
1413  * Return value with the low bits set means error value,
1414  * ie
1415  *      if (ret & ~PAGE_MASK)
1416  *              error = ret;
1417  *
1418  * This function "knows" that -ENOMEM has the bits set.
1419  */
1420 #ifndef HAVE_ARCH_UNMAPPED_AREA
1421 unsigned long
1422 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1423                 unsigned long len, unsigned long pgoff, unsigned long flags)
1424 {
1425         struct mm_struct *mm = current->mm;
1426         struct vm_area_struct *vma;
1427         unsigned long start_addr;
1428
1429         if (len > TASK_SIZE)
1430                 return -ENOMEM;
1431
1432         if (flags & MAP_FIXED)
1433                 return addr;
1434
1435         if (addr) {
1436                 addr = PAGE_ALIGN(addr);
1437                 vma = find_vma(mm, addr);
1438                 if (TASK_SIZE - len >= addr &&
1439                     (!vma || addr + len <= vma->vm_start))
1440                         return addr;
1441         }
1442         if (len > mm->cached_hole_size) {
1443                 start_addr = addr = mm->free_area_cache;
1444         } else {
1445                 start_addr = addr = TASK_UNMAPPED_BASE;
1446                 mm->cached_hole_size = 0;
1447         }
1448
1449 full_search:
1450         for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
1451                 /* At this point:  (!vma || addr < vma->vm_end). */
1452                 if (TASK_SIZE - len < addr) {
1453                         /*
1454                          * Start a new search - just in case we missed
1455                          * some holes.
1456                          */
1457                         if (start_addr != TASK_UNMAPPED_BASE) {
1458                                 addr = TASK_UNMAPPED_BASE;
1459                                 start_addr = addr;
1460                                 mm->cached_hole_size = 0;
1461                                 goto full_search;
1462                         }
1463                         return -ENOMEM;
1464                 }
1465                 if (!vma || addr + len <= vma->vm_start) {
1466                         /*
1467                          * Remember the place where we stopped the search:
1468                          */
1469                         mm->free_area_cache = addr + len;
1470                         return addr;
1471                 }
1472                 if (addr + mm->cached_hole_size < vma->vm_start)
1473                         mm->cached_hole_size = vma->vm_start - addr;
1474                 addr = vma->vm_end;
1475         }
1476 }
1477 #endif  
1478
1479 void arch_unmap_area(struct mm_struct *mm, unsigned long addr)
1480 {
1481         /*
1482          * Is this a new hole at the lowest possible address?
1483          */
1484         if (addr >= TASK_UNMAPPED_BASE && addr < mm->free_area_cache) {
1485                 mm->free_area_cache = addr;
1486                 mm->cached_hole_size = ~0UL;
1487         }
1488 }
1489
1490 /*
1491  * This mmap-allocator allocates new areas top-down from below the
1492  * stack's low limit (the base):
1493  */
1494 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1495 unsigned long
1496 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1497                           const unsigned long len, const unsigned long pgoff,
1498                           const unsigned long flags)
1499 {
1500         struct vm_area_struct *vma;
1501         struct mm_struct *mm = current->mm;
1502         unsigned long addr = addr0;
1503
1504         /* requested length too big for entire address space */
1505         if (len > TASK_SIZE)
1506                 return -ENOMEM;
1507
1508         if (flags & MAP_FIXED)
1509                 return addr;
1510
1511         /* requesting a specific address */
1512         if (addr) {
1513                 addr = PAGE_ALIGN(addr);
1514                 vma = find_vma(mm, addr);
1515                 if (TASK_SIZE - len >= addr &&
1516                                 (!vma || addr + len <= vma->vm_start))
1517                         return addr;
1518         }
1519
1520         /* check if free_area_cache is useful for us */
1521         if (len <= mm->cached_hole_size) {
1522                 mm->cached_hole_size = 0;
1523                 mm->free_area_cache = mm->mmap_base;
1524         }
1525
1526         /* either no address requested or can't fit in requested address hole */
1527         addr = mm->free_area_cache;
1528
1529         /* make sure it can fit in the remaining address space */
1530         if (addr > len) {
1531                 vma = find_vma(mm, addr-len);
1532                 if (!vma || addr <= vma->vm_start)
1533                         /* remember the address as a hint for next time */
1534                         return (mm->free_area_cache = addr-len);
1535         }
1536
1537         if (mm->mmap_base < len)
1538                 goto bottomup;
1539
1540         addr = mm->mmap_base-len;
1541
1542         do {
1543                 /*
1544                  * Lookup failure means no vma is above this address,
1545                  * else if new region fits below vma->vm_start,
1546                  * return with success:
1547                  */
1548                 vma = find_vma(mm, addr);
1549                 if (!vma || addr+len <= vma->vm_start)
1550                         /* remember the address as a hint for next time */
1551                         return (mm->free_area_cache = addr);
1552
1553                 /* remember the largest hole we saw so far */
1554                 if (addr + mm->cached_hole_size < vma->vm_start)
1555                         mm->cached_hole_size = vma->vm_start - addr;
1556
1557                 /* try just below the current vma->vm_start */
1558                 addr = vma->vm_start-len;
1559         } while (len < vma->vm_start);
1560
1561 bottomup:
1562         /*
1563          * A failed mmap() very likely causes application failure,
1564          * so fall back to the bottom-up function here. This scenario
1565          * can happen with large stack limits and large mmap()
1566          * allocations.
1567          */
1568         mm->cached_hole_size = ~0UL;
1569         mm->free_area_cache = TASK_UNMAPPED_BASE;
1570         addr = arch_get_unmapped_area(filp, addr0, len, pgoff, flags);
1571         /*
1572          * Restore the topdown base:
1573          */
1574         mm->free_area_cache = mm->mmap_base;
1575         mm->cached_hole_size = ~0UL;
1576
1577         return addr;
1578 }
1579 #endif
1580
1581 void arch_unmap_area_topdown(struct mm_struct *mm, unsigned long addr)
1582 {
1583         /*
1584          * Is this a new hole at the highest possible address?
1585          */
1586         if (addr > mm->free_area_cache)
1587                 mm->free_area_cache = addr;
1588
1589         /* dont allow allocations above current base */
1590         if (mm->free_area_cache > mm->mmap_base)
1591                 mm->free_area_cache = mm->mmap_base;
1592 }
1593
1594 unsigned long
1595 get_unmapped_area_prot(struct file *file, unsigned long addr, unsigned long len,
1596                 unsigned long pgoff, unsigned long flags, int exec)
1597 {
1598         unsigned long (*get_area)(struct file *, unsigned long,
1599                                   unsigned long, unsigned long, unsigned long);
1600
1601         unsigned long error = arch_mmap_check(addr, len, flags);
1602         if (error)
1603                 return error;
1604
1605         /* Careful about overflows.. */
1606         if (len > TASK_SIZE)
1607                 return -ENOMEM;
1608
1609         if (exec && current->mm->get_unmapped_exec_area)
1610                 get_area = current->mm->get_unmapped_exec_area;
1611         else
1612                 get_area = current->mm->get_unmapped_area;
1613
1614         if (file && file->f_op && file->f_op->get_unmapped_area)
1615                 get_area = file->f_op->get_unmapped_area;
1616         addr = get_area(file, addr, len, pgoff, flags);
1617         if (IS_ERR_VALUE(addr))
1618                 return addr;
1619
1620         if (addr > TASK_SIZE - len)
1621                 return -ENOMEM;
1622         if (addr & ~PAGE_MASK)
1623                 return -EINVAL;
1624
1625         return arch_rebalance_pgtables(addr, len);
1626 }
1627 EXPORT_SYMBOL(get_unmapped_area_prot);
1628
1629 static bool should_randomize(void)
1630 {
1631         return (current->flags & PF_RANDOMIZE) &&
1632                 !(current->personality & ADDR_NO_RANDOMIZE);
1633 }
1634
1635 #define SHLIB_BASE      0x00110000
1636
1637 unsigned long
1638 arch_get_unmapped_exec_area(struct file *filp, unsigned long addr0,
1639                 unsigned long len0, unsigned long pgoff, unsigned long flags)
1640 {
1641         unsigned long addr = addr0, len = len0;
1642         struct mm_struct *mm = current->mm;
1643         struct vm_area_struct *vma;
1644         unsigned long tmp;
1645
1646         if (len > TASK_SIZE)
1647                 return -ENOMEM;
1648
1649         if (flags & MAP_FIXED)
1650                 return addr;
1651
1652         if (!addr)
1653                 addr = !should_randomize() ? SHLIB_BASE :
1654                         randomize_range(SHLIB_BASE, 0x01000000, len);
1655
1656         if (addr) {
1657                 addr = PAGE_ALIGN(addr);
1658                 vma = find_vma(mm, addr);
1659                 if (TASK_SIZE - len >= addr &&
1660                     (!vma || addr + len <= vma->vm_start))
1661                         return addr;
1662         }
1663
1664         addr = SHLIB_BASE;
1665         for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
1666                 /* At this point:  (!vma || addr < vma->vm_end). */
1667                 if (TASK_SIZE - len < addr)
1668                         return -ENOMEM;
1669
1670                 if (!vma || addr + len <= vma->vm_start) {
1671                         /*
1672                          * Must not let a PROT_EXEC mapping get into the
1673                          * brk area:
1674                          */
1675                         if (addr + len > mm->brk)
1676                                 goto failed;
1677
1678                         /*
1679                          * Up until the brk area we randomize addresses
1680                          * as much as possible:
1681                          */
1682                         if (addr >= 0x01000000 && should_randomize()) {
1683                                 tmp = randomize_range(0x01000000,
1684                                         PAGE_ALIGN(max(mm->start_brk,
1685                                         (unsigned long)0x08000000)), len);
1686                                 vma = find_vma(mm, tmp);
1687                                 if (TASK_SIZE - len >= tmp &&
1688                                     (!vma || tmp + len <= vma->vm_start))
1689                                         return tmp;
1690                         }
1691                         /*
1692                          * Ok, randomization didnt work out - return
1693                          * the result of the linear search:
1694                          */
1695                         return addr;
1696                 }
1697                 addr = vma->vm_end;
1698         }
1699
1700 failed:
1701         return current->mm->get_unmapped_area(filp, addr0, len0, pgoff, flags);
1702 }
1703
1704
1705 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
1706 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1707 {
1708         struct vm_area_struct *vma = NULL;
1709
1710         if (mm) {
1711                 /* Check the cache first. */
1712                 /* (Cache hit rate is typically around 35%.) */
1713                 vma = mm->mmap_cache;
1714                 if (!(vma && vma->vm_end > addr && vma->vm_start <= addr)) {
1715                         struct rb_node * rb_node;
1716
1717                         rb_node = mm->mm_rb.rb_node;
1718                         vma = NULL;
1719
1720                         while (rb_node) {
1721                                 struct vm_area_struct * vma_tmp;
1722
1723                                 vma_tmp = rb_entry(rb_node,
1724                                                 struct vm_area_struct, vm_rb);
1725
1726                                 if (vma_tmp->vm_end > addr) {
1727                                         vma = vma_tmp;
1728                                         if (vma_tmp->vm_start <= addr)
1729                                                 break;
1730                                         rb_node = rb_node->rb_left;
1731                                 } else
1732                                         rb_node = rb_node->rb_right;
1733                         }
1734                         if (vma)
1735                                 mm->mmap_cache = vma;
1736                 }
1737         }
1738         return vma;
1739 }
1740
1741 EXPORT_SYMBOL(find_vma);
1742
1743 /* Same as find_vma, but also return a pointer to the previous VMA in *pprev. */
1744 struct vm_area_struct *
1745 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1746                         struct vm_area_struct **pprev)
1747 {
1748         struct vm_area_struct *vma = NULL, *prev = NULL;
1749         struct rb_node *rb_node;
1750         if (!mm)
1751                 goto out;
1752
1753         /* Guard against addr being lower than the first VMA */
1754         vma = mm->mmap;
1755
1756         /* Go through the RB tree quickly. */
1757         rb_node = mm->mm_rb.rb_node;
1758
1759         while (rb_node) {
1760                 struct vm_area_struct *vma_tmp;
1761                 vma_tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
1762
1763                 if (addr < vma_tmp->vm_end) {
1764                         rb_node = rb_node->rb_left;
1765                 } else {
1766                         prev = vma_tmp;
1767                         if (!prev->vm_next || (addr < prev->vm_next->vm_end))
1768                                 break;
1769                         rb_node = rb_node->rb_right;
1770                 }
1771         }
1772
1773 out:
1774         *pprev = prev;
1775         return prev ? prev->vm_next : vma;
1776 }
1777
1778 /*
1779  * Verify that the stack growth is acceptable and
1780  * update accounting. This is shared with both the
1781  * grow-up and grow-down cases.
1782  */
1783 static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
1784 {
1785         struct mm_struct *mm = vma->vm_mm;
1786         struct rlimit *rlim = current->signal->rlim;
1787         unsigned long new_start;
1788
1789         /* address space limit tests */
1790         if (!may_expand_vm(mm, grow))
1791                 return -ENOMEM;
1792
1793         /* Stack limit test */
1794         if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur))
1795                 return -ENOMEM;
1796
1797         /* mlock limit tests */
1798         if (vma->vm_flags & VM_LOCKED) {
1799                 unsigned long locked;
1800                 unsigned long limit;
1801                 locked = mm->locked_vm + grow;
1802                 limit = ACCESS_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
1803                 limit >>= PAGE_SHIFT;
1804                 if (locked > limit && !capable(CAP_IPC_LOCK))
1805                         return -ENOMEM;
1806         }
1807
1808         /* Check to ensure the stack will not grow into a hugetlb-only region */
1809         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
1810                         vma->vm_end - size;
1811         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
1812                 return -EFAULT;
1813
1814         /*
1815          * Overcommit..  This must be the final test, as it will
1816          * update security statistics.
1817          */
1818         if (security_vm_enough_memory_mm(mm, grow))
1819                 return -ENOMEM;
1820
1821         /* Ok, everything looks good - let it rip */
1822         mm->total_vm += grow;
1823         if (vma->vm_flags & VM_LOCKED)
1824                 mm->locked_vm += grow;
1825         vm_stat_account(mm, vma->vm_flags, vma->vm_file, grow);
1826         return 0;
1827 }
1828
1829 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
1830 /*
1831  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
1832  * vma is the last one with address > vma->vm_end.  Have to extend vma.
1833  */
1834 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
1835 {
1836         int error;
1837
1838         if (!(vma->vm_flags & VM_GROWSUP))
1839                 return -EFAULT;
1840
1841         /*
1842          * We must make sure the anon_vma is allocated
1843          * so that the anon_vma locking is not a noop.
1844          */
1845         if (unlikely(anon_vma_prepare(vma)))
1846                 return -ENOMEM;
1847         vma_lock_anon_vma(vma);
1848
1849         /*
1850          * vma->vm_start/vm_end cannot change under us because the caller
1851          * is required to hold the mmap_sem in read mode.  We need the
1852          * anon_vma lock to serialize against concurrent expand_stacks.
1853          * Also guard against wrapping around to address 0.
1854          */
1855         if (address < PAGE_ALIGN(address+4))
1856                 address = PAGE_ALIGN(address+4);
1857         else {
1858                 vma_unlock_anon_vma(vma);
1859                 return -ENOMEM;
1860         }
1861         error = 0;
1862
1863         /* Somebody else might have raced and expanded it already */
1864         if (address > vma->vm_end) {
1865                 unsigned long size, grow;
1866
1867                 size = address - vma->vm_start;
1868                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
1869
1870                 error = -ENOMEM;
1871                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
1872                         error = acct_stack_growth(vma, size, grow);
1873                         if (!error) {
1874                                 vma->vm_end = address;
1875                                 perf_event_mmap(vma);
1876                         }
1877                 }
1878         }
1879         vma_unlock_anon_vma(vma);
1880         khugepaged_enter_vma_merge(vma);
1881         return error;
1882 }
1883 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
1884
1885 /*
1886  * vma is the first one with address < vma->vm_start.  Have to extend vma.
1887  */
1888 static int expand_downwards(struct vm_area_struct *vma,
1889                                    unsigned long address)
1890 {
1891         int error;
1892
1893         /*
1894          * We must make sure the anon_vma is allocated
1895          * so that the anon_vma locking is not a noop.
1896          */
1897         if (unlikely(anon_vma_prepare(vma)))
1898                 return -ENOMEM;
1899
1900         address &= PAGE_MASK;
1901         error = security_file_mmap(NULL, 0, 0, 0, address, 1);
1902         if (error)
1903                 return error;
1904
1905         vma_lock_anon_vma(vma);
1906
1907         /*
1908          * vma->vm_start/vm_end cannot change under us because the caller
1909          * is required to hold the mmap_sem in read mode.  We need the
1910          * anon_vma lock to serialize against concurrent expand_stacks.
1911          */
1912
1913         /* Somebody else might have raced and expanded it already */
1914         if (address < vma->vm_start) {
1915                 unsigned long size, grow;
1916
1917                 size = vma->vm_end - address;
1918                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
1919
1920                 error = -ENOMEM;
1921                 if (grow <= vma->vm_pgoff) {
1922                         error = acct_stack_growth(vma, size, grow);
1923                         if (!error) {
1924                                 vma->vm_start = address;
1925                                 vma->vm_pgoff -= grow;
1926                                 perf_event_mmap(vma);
1927                         }
1928                 }
1929         }
1930         vma_unlock_anon_vma(vma);
1931         khugepaged_enter_vma_merge(vma);
1932         return error;
1933 }
1934
1935 int expand_stack_downwards(struct vm_area_struct *vma, unsigned long address)
1936 {
1937         return expand_downwards(vma, address);
1938 }
1939
1940 #ifdef CONFIG_STACK_GROWSUP
1941 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1942 {
1943         return expand_upwards(vma, address);
1944 }
1945
1946 struct vm_area_struct *
1947 find_extend_vma(struct mm_struct *mm, unsigned long addr)
1948 {
1949         struct vm_area_struct *vma, *prev;
1950
1951         addr &= PAGE_MASK;
1952         vma = find_vma_prev(mm, addr, &prev);
1953         if (vma && (vma->vm_start <= addr))
1954                 return vma;
1955         if (!prev || expand_stack(prev, addr))
1956                 return NULL;
1957         if (prev->vm_flags & VM_LOCKED) {
1958                 mlock_vma_pages_range(prev, addr, prev->vm_end);
1959         }
1960         return prev;
1961 }
1962 #else
1963 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1964 {
1965         return expand_downwards(vma, address);
1966 }
1967
1968 struct vm_area_struct *
1969 find_extend_vma(struct mm_struct * mm, unsigned long addr)
1970 {
1971         struct vm_area_struct * vma;
1972         unsigned long start;
1973
1974         addr &= PAGE_MASK;
1975         vma = find_vma(mm,addr);
1976         if (!vma)
1977                 return NULL;
1978         if (vma->vm_start <= addr)
1979                 return vma;
1980         if (!(vma->vm_flags & VM_GROWSDOWN))
1981                 return NULL;
1982         start = vma->vm_start;
1983         if (expand_stack(vma, addr))
1984                 return NULL;
1985         if (vma->vm_flags & VM_LOCKED) {
1986                 mlock_vma_pages_range(vma, addr, start);
1987         }
1988         return vma;
1989 }
1990 #endif
1991
1992 /*
1993  * Ok - we have the memory areas we should free on the vma list,
1994  * so release them, and do the vma updates.
1995  *
1996  * Called with the mm semaphore held.
1997  */
1998 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
1999 {
2000         /* Update high watermark before we lower total_vm */
2001         update_hiwater_vm(mm);
2002         do {
2003                 long nrpages = vma_pages(vma);
2004
2005                 mm->total_vm -= nrpages;
2006                 vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
2007                 vma = remove_vma(vma);
2008         } while (vma);
2009         validate_mm(mm);
2010 }
2011
2012 /*
2013  * Get rid of page table information in the indicated region.
2014  *
2015  * Called with the mm semaphore held.
2016  */
2017 static void unmap_region(struct mm_struct *mm,
2018                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2019                 unsigned long start, unsigned long end)
2020 {
2021         struct vm_area_struct *next = prev? prev->vm_next: mm->mmap;
2022         struct mmu_gather *tlb;
2023         unsigned long nr_accounted = 0;
2024
2025         lru_add_drain();
2026         tlb = tlb_gather_mmu(mm, 0);
2027         update_hiwater_rss(mm);
2028         unmap_vmas(&tlb, vma, start, end, &nr_accounted, NULL);
2029         vm_unacct_memory(nr_accounted);
2030         free_pgtables(tlb, vma, prev? prev->vm_end: FIRST_USER_ADDRESS,
2031                                  next? next->vm_start: 0);
2032         tlb_finish_mmu(tlb, start, end);
2033 }
2034
2035 /*
2036  * Create a list of vma's touched by the unmap, removing them from the mm's
2037  * vma list as we go..
2038  */
2039 static void
2040 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2041         struct vm_area_struct *prev, unsigned long end)
2042 {
2043         struct vm_area_struct **insertion_point;
2044         struct vm_area_struct *tail_vma = NULL;
2045         unsigned long addr;
2046
2047         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2048         vma->vm_prev = NULL;
2049         do {
2050                 rb_erase(&vma->vm_rb, &mm->mm_rb);
2051                 mm->map_count--;
2052                 tail_vma = vma;
2053                 vma = vma->vm_next;
2054         } while (vma && vma->vm_start < end);
2055         *insertion_point = vma;
2056         if (vma)
2057                 vma->vm_prev = prev;
2058         tail_vma->vm_next = NULL;
2059         if (mm->unmap_area == arch_unmap_area)
2060                 addr = prev ? prev->vm_end : mm->mmap_base;
2061         else
2062                 addr = vma ?  vma->vm_start : mm->mmap_base;
2063         mm->unmap_area(mm, addr);
2064         mm->mmap_cache = NULL;          /* Kill the cache. */
2065 }
2066
2067 /*
2068  * __split_vma() bypasses sysctl_max_map_count checking.  We use this on the
2069  * munmap path where it doesn't make sense to fail.
2070  */
2071 static int __split_vma(struct mm_struct * mm, struct vm_area_struct * vma,
2072               unsigned long addr, int new_below)
2073 {
2074         struct mempolicy *pol;
2075         struct vm_area_struct *new;
2076         int err = -ENOMEM;
2077
2078         if (is_vm_hugetlb_page(vma) && (addr &
2079                                         ~(huge_page_mask(hstate_vma(vma)))))
2080                 return -EINVAL;
2081
2082         new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2083         if (!new)
2084                 goto out_err;
2085
2086         /* most fields are the same, copy all, and then fixup */
2087         *new = *vma;
2088
2089         INIT_LIST_HEAD(&new->anon_vma_chain);
2090
2091         if (new_below)
2092                 new->vm_end = addr;
2093         else {
2094                 new->vm_start = addr;
2095                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2096         }
2097
2098         pol = mpol_dup(vma_policy(vma));
2099         if (IS_ERR(pol)) {
2100                 err = PTR_ERR(pol);
2101                 goto out_free_vma;
2102         }
2103         vma_set_policy(new, pol);
2104
2105         if (anon_vma_clone(new, vma))
2106                 goto out_free_mpol;
2107
2108         if (new->vm_file) {
2109                 get_file(new->vm_file);
2110                 if (vma->vm_flags & VM_EXECUTABLE)
2111                         added_exe_file_vma(mm);
2112         }
2113
2114         if (new->vm_ops && new->vm_ops->open)
2115                 new->vm_ops->open(new);
2116
2117         if (new_below) {
2118                 unsigned long old_end = vma->vm_end;
2119
2120                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2121                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2122                 if (vma->vm_flags & VM_EXEC)
2123                         arch_remove_exec_range(mm, old_end);
2124         } else
2125                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2126
2127         /* Success. */
2128         if (!err)
2129                 return 0;
2130
2131         /* Clean everything up if vma_adjust failed. */
2132         if (new->vm_ops && new->vm_ops->close)
2133                 new->vm_ops->close(new);
2134         if (new->vm_file) {
2135                 if (vma->vm_flags & VM_EXECUTABLE)
2136                         removed_exe_file_vma(mm);
2137                 fput(new->vm_file);
2138         }
2139         unlink_anon_vmas(new);
2140  out_free_mpol:
2141         mpol_put(pol);
2142  out_free_vma:
2143         kmem_cache_free(vm_area_cachep, new);
2144  out_err:
2145         return err;
2146 }
2147
2148 /*
2149  * Split a vma into two pieces at address 'addr', a new vma is allocated
2150  * either for the first part or the tail.
2151  */
2152 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2153               unsigned long addr, int new_below)
2154 {
2155         if (mm->map_count >= sysctl_max_map_count)
2156                 return -ENOMEM;
2157
2158         return __split_vma(mm, vma, addr, new_below);
2159 }
2160
2161 /* Munmap is split into 2 main parts -- this part which finds
2162  * what needs doing, and the areas themselves, which do the
2163  * work.  This now handles partial unmappings.
2164  * Jeremy Fitzhardinge <jeremy@goop.org>
2165  */
2166 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2167 {
2168         unsigned long end;
2169         struct vm_area_struct *vma, *prev, *last;
2170
2171         if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
2172                 return -EINVAL;
2173
2174         if ((len = PAGE_ALIGN(len)) == 0)
2175                 return -EINVAL;
2176
2177         /* Find the first overlapping VMA */
2178         vma = find_vma_prev(mm, start, &prev);
2179         if (!vma)
2180                 return 0;
2181         /* we have  start < vma->vm_end  */
2182
2183         /* if it doesn't overlap, we have nothing.. */
2184         end = start + len;
2185         if (vma->vm_start >= end)
2186                 return 0;
2187
2188         /*
2189          * If we need to split any vma, do it now to save pain later.
2190          *
2191          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2192          * unmapped vm_area_struct will remain in use: so lower split_vma
2193          * places tmp vma above, and higher split_vma places tmp vma below.
2194          */
2195         if (start > vma->vm_start) {
2196                 int error;
2197
2198                 /*
2199                  * Make sure that map_count on return from munmap() will
2200                  * not exceed its limit; but let map_count go just above
2201                  * its limit temporarily, to help free resources as expected.
2202                  */
2203                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2204                         return -ENOMEM;
2205
2206                 error = __split_vma(mm, vma, start, 0);
2207                 if (error)
2208                         return error;
2209                 prev = vma;
2210         }
2211
2212         /* Does it split the last one? */
2213         last = find_vma(mm, end);
2214         if (last && end > last->vm_start) {
2215                 int error = __split_vma(mm, last, end, 1);
2216                 if (error)
2217                         return error;
2218         }
2219         vma = prev? prev->vm_next: mm->mmap;
2220
2221         /*
2222          * unlock any mlock()ed ranges before detaching vmas
2223          */
2224         if (mm->locked_vm) {
2225                 struct vm_area_struct *tmp = vma;
2226                 while (tmp && tmp->vm_start < end) {
2227                         if (tmp->vm_flags & VM_LOCKED) {
2228                                 mm->locked_vm -= vma_pages(tmp);
2229                                 munlock_vma_pages_all(tmp);
2230                         }
2231                         tmp = tmp->vm_next;
2232                 }
2233         }
2234
2235         /*
2236          * Remove the vma's, and unmap the actual pages
2237          */
2238         detach_vmas_to_be_unmapped(mm, vma, prev, end);
2239         unmap_region(mm, vma, prev, start, end);
2240
2241         /* Fix up all other VM information */
2242         remove_vma_list(mm, vma);
2243
2244         return 0;
2245 }
2246
2247 EXPORT_SYMBOL(do_munmap);
2248
2249 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2250 {
2251         int ret;
2252         struct mm_struct *mm = current->mm;
2253
2254         profile_munmap(addr);
2255
2256         down_write(&mm->mmap_sem);
2257         ret = do_munmap(mm, addr, len);
2258         up_write(&mm->mmap_sem);
2259         return ret;
2260 }
2261
2262 static inline void verify_mm_writelocked(struct mm_struct *mm)
2263 {
2264 #ifdef CONFIG_DEBUG_VM
2265         if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2266                 WARN_ON(1);
2267                 up_read(&mm->mmap_sem);
2268         }
2269 #endif
2270 }
2271
2272 /*
2273  *  this is really a simplified "do_mmap".  it only handles
2274  *  anonymous maps.  eventually we may be able to do some
2275  *  brk-specific accounting here.
2276  */
2277 unsigned long do_brk(unsigned long addr, unsigned long len)
2278 {
2279         struct mm_struct * mm = current->mm;
2280         struct vm_area_struct * vma, * prev;
2281         unsigned long flags;
2282         struct rb_node ** rb_link, * rb_parent;
2283         pgoff_t pgoff = addr >> PAGE_SHIFT;
2284         int error;
2285
2286         len = PAGE_ALIGN(len);
2287         if (!len)
2288                 return addr;
2289
2290         error = security_file_mmap(NULL, 0, 0, 0, addr, 1);
2291         if (error)
2292                 return error;
2293
2294         flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2295
2296         error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2297         if (error & ~PAGE_MASK)
2298                 return error;
2299
2300         /*
2301          * mlock MCL_FUTURE?
2302          */
2303         if (mm->def_flags & VM_LOCKED) {
2304                 unsigned long locked, lock_limit;
2305                 locked = len >> PAGE_SHIFT;
2306                 locked += mm->locked_vm;
2307                 lock_limit = rlimit(RLIMIT_MEMLOCK);
2308                 lock_limit >>= PAGE_SHIFT;
2309                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
2310                         return -EAGAIN;
2311         }
2312
2313         /*
2314          * mm->mmap_sem is required to protect against another thread
2315          * changing the mappings in case we sleep.
2316          */
2317         verify_mm_writelocked(mm);
2318
2319         /*
2320          * Clear old maps.  this also does some error checking for us
2321          */
2322  munmap_back:
2323         vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
2324         if (vma && vma->vm_start < addr + len) {
2325                 if (do_munmap(mm, addr, len))
2326                         return -ENOMEM;
2327                 goto munmap_back;
2328         }
2329
2330         /* Check against address space limits *after* clearing old maps... */
2331         if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2332                 return -ENOMEM;
2333
2334         if (mm->map_count > sysctl_max_map_count)
2335                 return -ENOMEM;
2336
2337         if (security_vm_enough_memory(len >> PAGE_SHIFT))
2338                 return -ENOMEM;
2339
2340         /* Can we just expand an old private anonymous mapping? */
2341         vma = vma_merge(mm, prev, addr, addr + len, flags,
2342                                         NULL, NULL, pgoff, NULL);
2343         if (vma)
2344                 goto out;
2345
2346         /*
2347          * create a vma struct for an anonymous mapping
2348          */
2349         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2350         if (!vma) {
2351                 vm_unacct_memory(len >> PAGE_SHIFT);
2352                 return -ENOMEM;
2353         }
2354
2355         INIT_LIST_HEAD(&vma->anon_vma_chain);
2356         vma->vm_mm = mm;
2357         vma->vm_start = addr;
2358         vma->vm_end = addr + len;
2359         vma->vm_pgoff = pgoff;
2360         vma->vm_flags = flags;
2361         vma->vm_page_prot = vm_get_page_prot(flags);
2362         vma_link(mm, vma, prev, rb_link, rb_parent);
2363 out:
2364         perf_event_mmap(vma);
2365         mm->total_vm += len >> PAGE_SHIFT;
2366         if (flags & VM_LOCKED) {
2367                 if (!mlock_vma_pages_range(vma, addr, addr + len))
2368                         mm->locked_vm += (len >> PAGE_SHIFT);
2369         }
2370         return addr;
2371 }
2372
2373 EXPORT_SYMBOL(do_brk);
2374
2375 /* Release all mmaps. */
2376 void exit_mmap(struct mm_struct *mm)
2377 {
2378         struct mmu_gather *tlb;
2379         struct vm_area_struct *vma;
2380         unsigned long nr_accounted = 0;
2381         unsigned long end;
2382
2383         /* mm's last user has gone, and its about to be pulled down */
2384         mmu_notifier_release(mm);
2385
2386         if (mm->locked_vm) {
2387                 vma = mm->mmap;
2388                 while (vma) {
2389                         if (vma->vm_flags & VM_LOCKED)
2390                                 munlock_vma_pages_all(vma);
2391                         vma = vma->vm_next;
2392                 }
2393         }
2394
2395         arch_exit_mmap(mm);
2396
2397         vma = mm->mmap;
2398         if (!vma)       /* Can happen if dup_mmap() received an OOM */
2399                 return;
2400
2401         lru_add_drain();
2402         flush_cache_mm(mm);
2403         tlb = tlb_gather_mmu(mm, 1);
2404         /* update_hiwater_rss(mm) here? but nobody should be looking */
2405         /* Use -1 here to ensure all VMAs in the mm are unmapped */
2406         end = unmap_vmas(&tlb, vma, 0, -1, &nr_accounted, NULL);
2407         vm_unacct_memory(nr_accounted);
2408
2409         free_pgtables(tlb, vma, FIRST_USER_ADDRESS, 0);
2410         tlb_finish_mmu(tlb, 0, end);
2411         arch_flush_exec_range(mm);
2412
2413         /*
2414          * Walk the list again, actually closing and freeing it,
2415          * with preemption enabled, without holding any MM locks.
2416          */
2417         while (vma)
2418                 vma = remove_vma(vma);
2419
2420         BUG_ON(mm->nr_ptes > (FIRST_USER_ADDRESS+PMD_SIZE-1)>>PMD_SHIFT);
2421 }
2422
2423 /* Insert vm structure into process list sorted by address
2424  * and into the inode's i_mmap tree.  If vm_file is non-NULL
2425  * then i_mmap_lock is taken here.
2426  */
2427 int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
2428 {
2429         struct vm_area_struct * __vma, * prev;
2430         struct rb_node ** rb_link, * rb_parent;
2431
2432         /*
2433          * The vm_pgoff of a purely anonymous vma should be irrelevant
2434          * until its first write fault, when page's anon_vma and index
2435          * are set.  But now set the vm_pgoff it will almost certainly
2436          * end up with (unless mremap moves it elsewhere before that
2437          * first wfault), so /proc/pid/maps tells a consistent story.
2438          *
2439          * By setting it to reflect the virtual start address of the
2440          * vma, merges and splits can happen in a seamless way, just
2441          * using the existing file pgoff checks and manipulations.
2442          * Similarly in do_mmap_pgoff and in do_brk.
2443          */
2444         if (!vma->vm_file) {
2445                 BUG_ON(vma->anon_vma);
2446                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2447         }
2448         __vma = find_vma_prepare(mm,vma->vm_start,&prev,&rb_link,&rb_parent);
2449         if (__vma && __vma->vm_start < vma->vm_end)
2450                 return -ENOMEM;
2451         if ((vma->vm_flags & VM_ACCOUNT) &&
2452              security_vm_enough_memory_mm(mm, vma_pages(vma)))
2453                 return -ENOMEM;
2454         vma_link(mm, vma, prev, rb_link, rb_parent);
2455         return 0;
2456 }
2457
2458 /*
2459  * Copy the vma structure to a new location in the same mm,
2460  * prior to moving page table entries, to effect an mremap move.
2461  */
2462 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2463         unsigned long addr, unsigned long len, pgoff_t pgoff)
2464 {
2465         struct vm_area_struct *vma = *vmap;
2466         unsigned long vma_start = vma->vm_start;
2467         struct mm_struct *mm = vma->vm_mm;
2468         struct vm_area_struct *new_vma, *prev;
2469         struct rb_node **rb_link, *rb_parent;
2470         struct mempolicy *pol;
2471
2472         /*
2473          * If anonymous vma has not yet been faulted, update new pgoff
2474          * to match new location, to increase its chance of merging.
2475          */
2476         if (!vma->vm_file && !vma->anon_vma)
2477                 pgoff = addr >> PAGE_SHIFT;
2478
2479         find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
2480         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2481                         vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma));
2482         if (new_vma) {
2483                 /*
2484                  * Source vma may have been merged into new_vma
2485                  */
2486                 if (vma_start >= new_vma->vm_start &&
2487                     vma_start < new_vma->vm_end)
2488                         *vmap = new_vma;
2489         } else {
2490                 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2491                 if (new_vma) {
2492                         *new_vma = *vma;
2493                         pol = mpol_dup(vma_policy(vma));
2494                         if (IS_ERR(pol))
2495                                 goto out_free_vma;
2496                         INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2497                         if (anon_vma_clone(new_vma, vma))
2498                                 goto out_free_mempol;
2499                         vma_set_policy(new_vma, pol);
2500                         new_vma->vm_start = addr;
2501                         new_vma->vm_end = addr + len;
2502                         new_vma->vm_pgoff = pgoff;
2503                         if (new_vma->vm_file) {
2504                                 get_file(new_vma->vm_file);
2505                                 if (vma->vm_flags & VM_EXECUTABLE)
2506                                         added_exe_file_vma(mm);
2507                         }
2508                         if (new_vma->vm_ops && new_vma->vm_ops->open)
2509                                 new_vma->vm_ops->open(new_vma);
2510                         vma_link(mm, new_vma, prev, rb_link, rb_parent);
2511                 }
2512         }
2513         return new_vma;
2514
2515  out_free_mempol:
2516         mpol_put(pol);
2517  out_free_vma:
2518         kmem_cache_free(vm_area_cachep, new_vma);
2519         return NULL;
2520 }
2521
2522 /*
2523  * Return true if the calling process may expand its vm space by the passed
2524  * number of pages
2525  */
2526 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
2527 {
2528         unsigned long cur = mm->total_vm;       /* pages */
2529         unsigned long lim;
2530
2531         lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
2532
2533         if (cur + npages > lim)
2534                 return 0;
2535         return 1;
2536 }
2537
2538
2539 static int special_mapping_fault(struct vm_area_struct *vma,
2540                                 struct vm_fault *vmf)
2541 {
2542         pgoff_t pgoff;
2543         struct page **pages;
2544
2545         /*
2546          * special mappings have no vm_file, and in that case, the mm
2547          * uses vm_pgoff internally. So we have to subtract it from here.
2548          * We are allowed to do this because we are the mm; do not copy
2549          * this code into drivers!
2550          */
2551         pgoff = vmf->pgoff - vma->vm_pgoff;
2552
2553         for (pages = vma->vm_private_data; pgoff && *pages; ++pages)
2554                 pgoff--;
2555
2556         if (*pages) {
2557                 struct page *page = *pages;
2558                 get_page(page);
2559                 vmf->page = page;
2560                 return 0;
2561         }
2562
2563         return VM_FAULT_SIGBUS;
2564 }
2565
2566 /*
2567  * Having a close hook prevents vma merging regardless of flags.
2568  */
2569 static void special_mapping_close(struct vm_area_struct *vma)
2570 {
2571 }
2572
2573 static const struct vm_operations_struct special_mapping_vmops = {
2574         .close = special_mapping_close,
2575         .fault = special_mapping_fault,
2576 };
2577
2578 /*
2579  * Called with mm->mmap_sem held for writing.
2580  * Insert a new vma covering the given region, with the given flags.
2581  * Its pages are supplied by the given array of struct page *.
2582  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
2583  * The region past the last page supplied will always produce SIGBUS.
2584  * The array pointer and the pages it points to are assumed to stay alive
2585  * for as long as this mapping might exist.
2586  */
2587 int install_special_mapping(struct mm_struct *mm,
2588                             unsigned long addr, unsigned long len,
2589                             unsigned long vm_flags, struct page **pages)
2590 {
2591         int ret;
2592         struct vm_area_struct *vma;
2593
2594         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2595         if (unlikely(vma == NULL))
2596                 return -ENOMEM;
2597
2598         INIT_LIST_HEAD(&vma->anon_vma_chain);
2599         vma->vm_mm = mm;
2600         vma->vm_start = addr;
2601         vma->vm_end = addr + len;
2602
2603         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND;
2604         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
2605
2606         vma->vm_ops = &special_mapping_vmops;
2607         vma->vm_private_data = pages;
2608
2609         ret = security_file_mmap(NULL, 0, 0, 0, vma->vm_start, 1);
2610         if (ret)
2611                 goto out;
2612
2613         ret = insert_vm_struct(mm, vma);
2614         if (ret)
2615                 goto out;
2616
2617         mm->total_vm += len >> PAGE_SHIFT;
2618
2619         perf_event_mmap(vma);
2620
2621         return 0;
2622
2623 out:
2624         kmem_cache_free(vm_area_cachep, vma);
2625         return ret;
2626 }
2627
2628 static DEFINE_MUTEX(mm_all_locks_mutex);
2629
2630 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
2631 {
2632         if (!test_bit(0, (unsigned long *) &anon_vma->root->head.next)) {
2633                 /*
2634                  * The LSB of head.next can't change from under us
2635                  * because we hold the mm_all_locks_mutex.
2636                  */
2637                 spin_lock_nest_lock(&anon_vma->root->lock, &mm->mmap_sem);
2638                 /*
2639                  * We can safely modify head.next after taking the
2640                  * anon_vma->root->lock. If some other vma in this mm shares
2641                  * the same anon_vma we won't take it again.
2642                  *
2643                  * No need of atomic instructions here, head.next
2644                  * can't change from under us thanks to the
2645                  * anon_vma->root->lock.
2646                  */
2647                 if (__test_and_set_bit(0, (unsigned long *)
2648                                        &anon_vma->root->head.next))
2649                         BUG();
2650         }
2651 }
2652
2653 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
2654 {
2655         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2656                 /*
2657                  * AS_MM_ALL_LOCKS can't change from under us because
2658                  * we hold the mm_all_locks_mutex.
2659                  *
2660                  * Operations on ->flags have to be atomic because
2661                  * even if AS_MM_ALL_LOCKS is stable thanks to the
2662                  * mm_all_locks_mutex, there may be other cpus
2663                  * changing other bitflags in parallel to us.
2664                  */
2665                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
2666                         BUG();
2667                 spin_lock_nest_lock(&mapping->i_mmap_lock, &mm->mmap_sem);
2668         }
2669 }
2670
2671 /*
2672  * This operation locks against the VM for all pte/vma/mm related
2673  * operations that could ever happen on a certain mm. This includes
2674  * vmtruncate, try_to_unmap, and all page faults.
2675  *
2676  * The caller must take the mmap_sem in write mode before calling
2677  * mm_take_all_locks(). The caller isn't allowed to release the
2678  * mmap_sem until mm_drop_all_locks() returns.
2679  *
2680  * mmap_sem in write mode is required in order to block all operations
2681  * that could modify pagetables and free pages without need of
2682  * altering the vma layout (for example populate_range() with
2683  * nonlinear vmas). It's also needed in write mode to avoid new
2684  * anon_vmas to be associated with existing vmas.
2685  *
2686  * A single task can't take more than one mm_take_all_locks() in a row
2687  * or it would deadlock.
2688  *
2689  * The LSB in anon_vma->head.next and the AS_MM_ALL_LOCKS bitflag in
2690  * mapping->flags avoid to take the same lock twice, if more than one
2691  * vma in this mm is backed by the same anon_vma or address_space.
2692  *
2693  * We can take all the locks in random order because the VM code
2694  * taking i_mmap_lock or anon_vma->lock outside the mmap_sem never
2695  * takes more than one of them in a row. Secondly we're protected
2696  * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
2697  *
2698  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
2699  * that may have to take thousand of locks.
2700  *
2701  * mm_take_all_locks() can fail if it's interrupted by signals.
2702  */
2703 int mm_take_all_locks(struct mm_struct *mm)
2704 {
2705         struct vm_area_struct *vma;
2706         struct anon_vma_chain *avc;
2707         int ret = -EINTR;
2708
2709         BUG_ON(down_read_trylock(&mm->mmap_sem));
2710
2711         mutex_lock(&mm_all_locks_mutex);
2712
2713         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2714                 if (signal_pending(current))
2715                         goto out_unlock;
2716                 if (vma->vm_file && vma->vm_file->f_mapping)
2717                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
2718         }
2719
2720         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2721                 if (signal_pending(current))
2722                         goto out_unlock;
2723                 if (vma->anon_vma)
2724                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2725                                 vm_lock_anon_vma(mm, avc->anon_vma);
2726         }
2727
2728         ret = 0;
2729
2730 out_unlock:
2731         if (ret)
2732                 mm_drop_all_locks(mm);
2733
2734         return ret;
2735 }
2736
2737 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2738 {
2739         if (test_bit(0, (unsigned long *) &anon_vma->root->head.next)) {
2740                 /*
2741                  * The LSB of head.next can't change to 0 from under
2742                  * us because we hold the mm_all_locks_mutex.
2743                  *
2744                  * We must however clear the bitflag before unlocking
2745                  * the vma so the users using the anon_vma->head will
2746                  * never see our bitflag.
2747                  *
2748                  * No need of atomic instructions here, head.next
2749                  * can't change from under us until we release the
2750                  * anon_vma->root->lock.
2751                  */
2752                 if (!__test_and_clear_bit(0, (unsigned long *)
2753                                           &anon_vma->root->head.next))
2754                         BUG();
2755                 anon_vma_unlock(anon_vma);
2756         }
2757 }
2758
2759 static void vm_unlock_mapping(struct address_space *mapping)
2760 {
2761         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2762                 /*
2763                  * AS_MM_ALL_LOCKS can't change to 0 from under us
2764                  * because we hold the mm_all_locks_mutex.
2765                  */
2766                 spin_unlock(&mapping->i_mmap_lock);
2767                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2768                                         &mapping->flags))
2769                         BUG();
2770         }
2771 }
2772
2773 /*
2774  * The mmap_sem cannot be released by the caller until
2775  * mm_drop_all_locks() returns.
2776  */
2777 void mm_drop_all_locks(struct mm_struct *mm)
2778 {
2779         struct vm_area_struct *vma;
2780         struct anon_vma_chain *avc;
2781
2782         BUG_ON(down_read_trylock(&mm->mmap_sem));
2783         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2784
2785         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2786                 if (vma->anon_vma)
2787                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2788                                 vm_unlock_anon_vma(avc->anon_vma);
2789                 if (vma->vm_file && vma->vm_file->f_mapping)
2790                         vm_unlock_mapping(vma->vm_file->f_mapping);
2791         }
2792
2793         mutex_unlock(&mm_all_locks_mutex);
2794 }
2795
2796 /*
2797  * initialise the VMA slab
2798  */
2799 void __init mmap_init(void)
2800 {
2801         int ret;
2802
2803         ret = percpu_counter_init(&vm_committed_as, 0);
2804         VM_BUG_ON(ret);
2805 }