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