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