Added _heavy_ lamport locks. A heavy lamport lock has its own dedicated lamport...
[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 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
1001             process_server_acquire_distributed_mm_lock();
1002 #else
1003             process_server_acquire_page_lock_range(addr,len);
1004 #endif
1005             down_write(&mm->mmap_sem);
1006 #endif
1007             fault_ret = process_server_pull_remote_mappings(mm,
1008                                                             NULL,
1009                                                             addr,
1010                                                             0,
1011                                                             &vma_out,
1012                                                             0);
1013             if(fault_ret) {
1014                 pserv_conflict = 1;
1015 #ifdef PROCESS_SERVER_ENFORCE_VMA_MOD_ATOMICITY
1016 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
1017                 process_server_release_heavy_lock();
1018 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
1019                 process_server_release_distributed_mm_lock();
1020 #else
1021                 process_server_release_page_lock_range(addr,len);
1022 #endif
1023 #endif
1024           
1025             }
1026             else {
1027                 pserv_conflict = 0;    
1028                 range_locked = 1;
1029             }
1030         } while(pserv_conflict);
1031     }
1032         if (addr & ~PAGE_MASK) {
1033         if(range_locked && current->enable_do_mmap_pgoff_hook) {
1034 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
1035             process_server_release_heavy_lock();
1036 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
1037             process_server_release_distributed_mm_lock();
1038 #else  
1039             process_server_release_page_lock_range(addr,len);
1040 #endif
1041
1042         }
1043                 return addr;
1044     }
1045
1046 #ifdef PROCESS_SERVER_ENFORCE_VMA_MOD_ATOMICITY
1047     if(current->enable_do_mmap_pgoff_hook && !range_locked) {
1048         up_write(&mm->mmap_sem);
1049 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
1050         process_server_acquire_heavy_lock();
1051 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
1052         process_server_acquire_distributed_mm_lock();
1053 #else
1054         process_server_acquire_page_lock_range(addr,len);
1055 #endif
1056         down_write(&mm->mmap_sem);
1057     }
1058 #endif
1059
1060     current->enable_distributed_munmap = 0;
1061
1062         /* Do simple checking here so the lower-level routines won't have
1063          * to. we assume access permissions have been handled by the open
1064          * of the memory object, so we don't do any here.
1065          */
1066         vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
1067                         mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1068
1069         if (flags & MAP_LOCKED)
1070                 if (!can_do_mlock()) {
1071                         error = -EPERM;
1072             goto err;
1073         }
1074
1075         /* mlock MCL_FUTURE? */
1076         if (vm_flags & VM_LOCKED) {
1077                 unsigned long locked, lock_limit;
1078                 locked = len >> PAGE_SHIFT;
1079                 locked += mm->locked_vm;
1080                 lock_limit = rlimit(RLIMIT_MEMLOCK);
1081                 lock_limit >>= PAGE_SHIFT;
1082                 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1083                         error = -EAGAIN;
1084             goto err;
1085         }
1086         }
1087
1088         inode = file ? file->f_path.dentry->d_inode : NULL;
1089
1090         if (file) {
1091                 switch (flags & MAP_TYPE) {
1092                 case MAP_SHARED:
1093                         if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE)) {
1094                                 error = -EACCES;
1095                 goto err;
1096             }
1097
1098                         /*
1099                          * Make sure we don't allow writing to an append-only
1100                          * file..
1101                          */
1102                         if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE)) {
1103                                 error = -EACCES;
1104                 goto err;
1105             }
1106
1107                         /*
1108                          * Make sure there are no mandatory locks on the file.
1109                          */
1110                         if (locks_verify_locked(inode)) {
1111                                 error = -EAGAIN;
1112                 goto err;
1113             }
1114
1115                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1116                         if (!(file->f_mode & FMODE_WRITE))
1117                                 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1118
1119                         /* fall through */
1120                 case MAP_PRIVATE:
1121                         if (!(file->f_mode & FMODE_READ)) {
1122                                 error = -EACCES;
1123                 goto err;
1124             }
1125                         if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
1126                                 if (vm_flags & VM_EXEC) {
1127                                         error = -EPERM;
1128                     goto err;
1129                 }
1130                                 vm_flags &= ~VM_MAYEXEC;
1131                         }
1132
1133                         if (!file->f_op || !file->f_op->mmap) {
1134                                 error = -ENODEV;
1135                 goto err;
1136             }
1137                         break;
1138
1139                 default:
1140                         error = -EINVAL;
1141             goto err;
1142                 }
1143         } else {
1144                 switch (flags & MAP_TYPE) {
1145                 case MAP_SHARED:
1146                         /*
1147                          * Ignore pgoff.
1148                          */
1149                         pgoff = 0;
1150                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1151                         break;
1152                 case MAP_PRIVATE:
1153                         /*
1154                          * Set pgoff according to addr for anon_vma.
1155                          */
1156                         pgoff = addr >> PAGE_SHIFT;
1157                         break;
1158                 default:
1159             error = -EINVAL;
1160                         goto err;
1161                 }
1162         }
1163
1164         error = security_file_mmap(file, reqprot, prot, flags, addr, 0);
1165         if (error) {
1166                 goto err;
1167     }
1168
1169     /*
1170      * Multikernel do_mmap_pgoff hook
1171      */
1172     current->enable_distributed_munmap = original_enable_distributed_munmap;
1173     process_server_do_mmap_pgoff(file, addr, len, flags, vm_flags, pgoff);
1174     current->enable_distributed_munmap = 0;
1175
1176     ret = mmap_region(file, addr, len, flags, vm_flags, pgoff);
1177
1178     current->enable_distributed_munmap = original_enable_distributed_munmap;
1179 #ifdef PROCESS_SERVER_ENFORCE_VMA_MOD_ATOMICITY
1180     if(current->enable_do_mmap_pgoff_hook) {
1181 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
1182         process_server_release_heavy_lock();
1183 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
1184         process_server_release_distributed_mm_lock();
1185 #else
1186         process_server_release_page_lock_range(addr,len);
1187 #endif
1188     }
1189 #endif
1190
1191         return ret;
1192
1193 err:
1194
1195     current->enable_distributed_munmap = original_enable_distributed_munmap;
1196 #ifdef PROCESS_SERVER_ENFORCE_VMA_MOD_ATOMICITY
1197     if(current->enable_do_mmap_pgoff_hook) {
1198 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
1199         process_server_release_heavy_lock();
1200 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
1201         process_server_release_distributed_mm_lock();
1202 #else
1203         process_server_release_page_lock_range(addr,len);
1204 #endif
1205     }
1206 #endif
1207
1208     return error;
1209
1210 }
1211 EXPORT_SYMBOL(do_mmap_pgoff);
1212
1213 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1214                 unsigned long, prot, unsigned long, flags,
1215                 unsigned long, fd, unsigned long, pgoff)
1216 {
1217         struct file *file = NULL;
1218         unsigned long retval = -EBADF;
1219
1220         if (!(flags & MAP_ANONYMOUS)) {
1221                 audit_mmap_fd(fd, flags);
1222                 if (unlikely(flags & MAP_HUGETLB))
1223                         return -EINVAL;
1224                 file = fget(fd);
1225                 if (!file)
1226                         goto out;
1227         } else if (flags & MAP_HUGETLB) {
1228                 struct user_struct *user = NULL;
1229                 /*
1230                  * VM_NORESERVE is used because the reservations will be
1231                  * taken when vm_ops->mmap() is called
1232                  * A dummy user value is used because we are not locking
1233                  * memory so no accounting is necessary
1234                  */
1235                 len = ALIGN(len, huge_page_size(&default_hstate));
1236                 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len, VM_NORESERVE,
1237                                                 &user, HUGETLB_ANONHUGE_INODE);
1238                 if (IS_ERR(file))
1239                         return PTR_ERR(file);
1240         }
1241
1242         flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1243
1244         down_write(&current->mm->mmap_sem);
1245         retval = do_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1246         up_write(&current->mm->mmap_sem);
1247
1248         if (file)
1249                 fput(file);
1250 out:
1251         return retval;
1252 }
1253
1254 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1255 struct mmap_arg_struct {
1256         unsigned long addr;
1257         unsigned long len;
1258         unsigned long prot;
1259         unsigned long flags;
1260         unsigned long fd;
1261         unsigned long offset;
1262 };
1263
1264 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1265 {
1266         struct mmap_arg_struct a;
1267
1268         if (copy_from_user(&a, arg, sizeof(a)))
1269                 return -EFAULT;
1270         if (a.offset & ~PAGE_MASK)
1271                 return -EINVAL;
1272
1273         return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1274                               a.offset >> PAGE_SHIFT);
1275 }
1276 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1277
1278 /*
1279  * Some shared mappigns will want the pages marked read-only
1280  * to track write events. If so, we'll downgrade vm_page_prot
1281  * to the private version (using protection_map[] without the
1282  * VM_SHARED bit).
1283  */
1284 int vma_wants_writenotify(struct vm_area_struct *vma)
1285 {
1286         vm_flags_t vm_flags = vma->vm_flags;
1287
1288         /* If it was private or non-writable, the write bit is already clear */
1289         if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1290                 return 0;
1291
1292         /* The backer wishes to know when pages are first written to? */
1293         if (vma->vm_ops && vma->vm_ops->page_mkwrite)
1294                 return 1;
1295
1296         /* The open routine did something to the protections already? */
1297         if (pgprot_val(vma->vm_page_prot) !=
1298             pgprot_val(vm_get_page_prot(vm_flags)))
1299                 return 0;
1300
1301         /* Specialty mapping? */
1302         if (vm_flags & (VM_PFNMAP|VM_INSERTPAGE))
1303                 return 0;
1304
1305         /* Can the mapping track the dirty pages? */
1306         return vma->vm_file && vma->vm_file->f_mapping &&
1307                 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1308 }
1309
1310 /*
1311  * We account for memory if it's a private writeable mapping,
1312  * not hugepages and VM_NORESERVE wasn't set.
1313  */
1314 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1315 {
1316         /*
1317          * hugetlb has its own accounting separate from the core VM
1318          * VM_HUGETLB may not be set yet so we cannot check for that flag.
1319          */
1320         if (file && is_file_hugepages(file))
1321                 return 0;
1322
1323         return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1324 }
1325
1326 unsigned long mmap_region(struct file *file, unsigned long addr,
1327                           unsigned long len, unsigned long flags,
1328                           vm_flags_t vm_flags, unsigned long pgoff)
1329 {
1330         struct mm_struct *mm = current->mm;
1331         struct vm_area_struct *vma, *prev;
1332         int correct_wcount = 0;
1333         int error;
1334         struct rb_node **rb_link, *rb_parent;
1335         unsigned long charged = 0;
1336         struct inode *inode =  file ? file->f_path.dentry->d_inode : NULL;
1337
1338         /* Clear old maps */
1339         error = -ENOMEM;
1340 munmap_back:
1341         vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
1342         if (vma && vma->vm_start < addr + len) {
1343                 if (do_munmap(mm, addr, len))
1344                         return -ENOMEM;
1345                 goto munmap_back;
1346         }
1347
1348         /* Check against address space limit. */
1349         if (!may_expand_vm(mm, len >> PAGE_SHIFT))
1350                 return -ENOMEM;
1351
1352         /*
1353          * Set 'VM_NORESERVE' if we should not account for the
1354          * memory use of this mapping.
1355          */
1356         if ((flags & MAP_NORESERVE)) {
1357                 /* We honor MAP_NORESERVE if allowed to overcommit */
1358                 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1359                         vm_flags |= VM_NORESERVE;
1360
1361                 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1362                 if (file && is_file_hugepages(file))
1363                         vm_flags |= VM_NORESERVE;
1364         }
1365
1366         /*
1367          * Private writable mapping: check memory availability
1368          */
1369         if (accountable_mapping(file, vm_flags)) {
1370                 charged = len >> PAGE_SHIFT;
1371                 if (security_vm_enough_memory(charged))
1372                         return -ENOMEM;
1373                 vm_flags |= VM_ACCOUNT;
1374         }
1375
1376         /*
1377          * Can we just expand an old mapping?
1378          */
1379         vma = vma_merge(mm, prev, addr, addr + len, vm_flags, NULL, file, pgoff, NULL);
1380         if (vma)
1381                 goto out;
1382
1383         /*
1384          * Determine the object being mapped and call the appropriate
1385          * specific mapper. the address has already been validated, but
1386          * not unmapped, but the maps are removed from the list.
1387          */
1388         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1389         if (!vma) {
1390                 error = -ENOMEM;
1391                 goto unacct_error;
1392         }
1393
1394         vma->vm_mm = mm;
1395         vma->vm_start = addr;
1396         vma->vm_end = addr + len;
1397         vma->vm_flags = vm_flags;
1398         vma->vm_page_prot = vm_get_page_prot(vm_flags);
1399         vma->vm_pgoff = pgoff;
1400         INIT_LIST_HEAD(&vma->anon_vma_chain);
1401
1402         if (file) {
1403                 error = -EINVAL;
1404                 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1405                         goto free_vma;
1406                 if (vm_flags & VM_DENYWRITE) {
1407                         error = deny_write_access(file);
1408                         if (error)
1409                                 goto free_vma;
1410                         correct_wcount = 1;
1411                 }
1412                 vma->vm_file = file;
1413                 get_file(file);
1414                 error = file->f_op->mmap(file, vma);
1415                 if (error)
1416                         goto unmap_and_free_vma;
1417                 if (vm_flags & VM_EXECUTABLE)
1418                         added_exe_file_vma(mm);
1419
1420                 /* Can addr have changed??
1421                  *
1422                  * Answer: Yes, several device drivers can do it in their
1423                  *         f_op->mmap method. -DaveM
1424                  */
1425                 addr = vma->vm_start;
1426                 pgoff = vma->vm_pgoff;
1427                 vm_flags = vma->vm_flags;
1428         } else if (vm_flags & VM_SHARED) {
1429                 error = shmem_zero_setup(vma);
1430                 if (error)
1431                         goto free_vma;
1432         }
1433
1434         if (vma_wants_writenotify(vma)) {
1435                 pgprot_t pprot = vma->vm_page_prot;
1436
1437                 /* Can vma->vm_page_prot have changed??
1438                  *
1439                  * Answer: Yes, drivers may have changed it in their
1440                  *         f_op->mmap method.
1441                  *
1442                  * Ensures that vmas marked as uncached stay that way.
1443                  */
1444                 vma->vm_page_prot = vm_get_page_prot(vm_flags & ~VM_SHARED);
1445                 if (pgprot_val(pprot) == pgprot_val(pgprot_noncached(pprot)))
1446                         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1447         }
1448
1449         vma_link(mm, vma, prev, rb_link, rb_parent);
1450         file = vma->vm_file;
1451
1452         /* Once vma denies write, undo our temporary denial count */
1453         if (correct_wcount)
1454                 atomic_inc(&inode->i_writecount);
1455 out:
1456         perf_event_mmap(vma);
1457
1458         mm->total_vm += len >> PAGE_SHIFT;
1459         vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1460         if (vm_flags & VM_LOCKED) {
1461                 if (!mlock_vma_pages_range(vma, addr, addr + len))
1462                         mm->locked_vm += (len >> PAGE_SHIFT);
1463         } else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
1464                 make_pages_present(addr, addr + len);
1465
1466     // Success - notify other cpus if necessary
1467     //process_server_notify_mmap(file, addr, len, flags, vm_flags, pgoff);
1468
1469         return addr;
1470
1471 unmap_and_free_vma:
1472         if (correct_wcount)
1473                 atomic_inc(&inode->i_writecount);
1474         vma->vm_file = NULL;
1475         fput(file);
1476
1477         /* Undo any partial mapping done by a device driver. */
1478         unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1479         charged = 0;
1480 free_vma:
1481         kmem_cache_free(vm_area_cachep, vma);
1482 unacct_error:
1483         if (charged)
1484                 vm_unacct_memory(charged);
1485         return error;
1486 }
1487
1488 /* Get an address range which is currently unmapped.
1489  * For shmat() with addr=0.
1490  *
1491  * Ugly calling convention alert:
1492  * Return value with the low bits set means error value,
1493  * ie
1494  *      if (ret & ~PAGE_MASK)
1495  *              error = ret;
1496  *
1497  * This function "knows" that -ENOMEM has the bits set.
1498  */
1499 #ifndef HAVE_ARCH_UNMAPPED_AREA
1500 unsigned long
1501 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1502                 unsigned long len, unsigned long pgoff, unsigned long flags)
1503 {
1504         struct mm_struct *mm = current->mm;
1505         struct vm_area_struct *vma;
1506         unsigned long start_addr;
1507
1508         if (len > TASK_SIZE)
1509                 return -ENOMEM;
1510
1511         if (flags & MAP_FIXED)
1512                 return addr;
1513
1514         if (addr) {
1515                 addr = PAGE_ALIGN(addr);
1516                 vma = find_vma(mm, addr);
1517                 if (TASK_SIZE - len >= addr &&
1518                     (!vma || addr + len <= vma->vm_start))
1519                         return addr;
1520         }
1521         if (len > mm->cached_hole_size) {
1522                 start_addr = addr = mm->free_area_cache;
1523         } else {
1524                 start_addr = addr = TASK_UNMAPPED_BASE;
1525                 mm->cached_hole_size = 0;
1526         }
1527
1528 full_search:
1529         for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
1530                 /* At this point:  (!vma || addr < vma->vm_end). */
1531                 if (TASK_SIZE - len < addr) {
1532                         /*
1533                          * Start a new search - just in case we missed
1534                          * some holes.
1535                          */
1536                         if (start_addr != TASK_UNMAPPED_BASE) {
1537                                 addr = TASK_UNMAPPED_BASE;
1538                                 start_addr = addr;
1539                                 mm->cached_hole_size = 0;
1540                                 goto full_search;
1541                         }
1542                         return -ENOMEM;
1543                 }
1544                 if (!vma || addr + len <= vma->vm_start) {
1545                         /*
1546                          * Remember the place where we stopped the search:
1547                          */
1548                         mm->free_area_cache = addr + len;
1549                         return addr;
1550                 }
1551                 if (addr + mm->cached_hole_size < vma->vm_start)
1552                         mm->cached_hole_size = vma->vm_start - addr;
1553                 addr = vma->vm_end;
1554         }
1555 }
1556 #endif  
1557
1558 void arch_unmap_area(struct mm_struct *mm, unsigned long addr)
1559 {
1560         /*
1561          * Is this a new hole at the lowest possible address?
1562          */
1563         if (addr >= TASK_UNMAPPED_BASE && addr < mm->free_area_cache) {
1564                 mm->free_area_cache = addr;
1565                 mm->cached_hole_size = ~0UL;
1566         }
1567 }
1568
1569 /*
1570  * This mmap-allocator allocates new areas top-down from below the
1571  * stack's low limit (the base):
1572  */
1573 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1574 unsigned long
1575 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1576                           const unsigned long len, const unsigned long pgoff,
1577                           const unsigned long flags)
1578 {
1579         struct vm_area_struct *vma;
1580         struct mm_struct *mm = current->mm;
1581         unsigned long addr = addr0;
1582
1583         /* requested length too big for entire address space */
1584         if (len > TASK_SIZE)
1585                 return -ENOMEM;
1586
1587         if (flags & MAP_FIXED)
1588                 return addr;
1589
1590         /* requesting a specific address */
1591         if (addr) {
1592                 addr = PAGE_ALIGN(addr);
1593                 vma = find_vma(mm, addr);
1594                 if (TASK_SIZE - len >= addr &&
1595                                 (!vma || addr + len <= vma->vm_start))
1596                         return addr;
1597         }
1598
1599         /* check if free_area_cache is useful for us */
1600         if (len <= mm->cached_hole_size) {
1601                 mm->cached_hole_size = 0;
1602                 mm->free_area_cache = mm->mmap_base;
1603         }
1604
1605         /* either no address requested or can't fit in requested address hole */
1606         addr = mm->free_area_cache;
1607
1608         /* make sure it can fit in the remaining address space */
1609         if (addr > len) {
1610                 vma = find_vma(mm, addr-len);
1611                 if (!vma || addr <= vma->vm_start)
1612                         /* remember the address as a hint for next time */
1613                         return (mm->free_area_cache = addr-len);
1614         }
1615
1616         if (mm->mmap_base < len)
1617                 goto bottomup;
1618
1619         addr = mm->mmap_base-len;
1620
1621         do {
1622                 /*
1623                  * Lookup failure means no vma is above this address,
1624                  * else if new region fits below vma->vm_start,
1625                  * return with success:
1626                  */
1627                 vma = find_vma(mm, addr);
1628                 if (!vma || addr+len <= vma->vm_start)
1629                         /* remember the address as a hint for next time */
1630                         return (mm->free_area_cache = addr);
1631
1632                 /* remember the largest hole we saw so far */
1633                 if (addr + mm->cached_hole_size < vma->vm_start)
1634                         mm->cached_hole_size = vma->vm_start - addr;
1635
1636                 /* try just below the current vma->vm_start */
1637                 addr = vma->vm_start-len;
1638         } while (len < vma->vm_start);
1639
1640 bottomup:
1641         /*
1642          * A failed mmap() very likely causes application failure,
1643          * so fall back to the bottom-up function here. This scenario
1644          * can happen with large stack limits and large mmap()
1645          * allocations.
1646          */
1647         mm->cached_hole_size = ~0UL;
1648         mm->free_area_cache = TASK_UNMAPPED_BASE;
1649         addr = arch_get_unmapped_area(filp, addr0, len, pgoff, flags);
1650         /*
1651          * Restore the topdown base:
1652          */
1653         mm->free_area_cache = mm->mmap_base;
1654         mm->cached_hole_size = ~0UL;
1655
1656         return addr;
1657 }
1658 #endif
1659
1660 void arch_unmap_area_topdown(struct mm_struct *mm, unsigned long addr)
1661 {
1662         /*
1663          * Is this a new hole at the highest possible address?
1664          */
1665         if (addr > mm->free_area_cache)
1666                 mm->free_area_cache = addr;
1667
1668         /* dont allow allocations above current base */
1669         if (mm->free_area_cache > mm->mmap_base)
1670                 mm->free_area_cache = mm->mmap_base;
1671 }
1672
1673 unsigned long
1674 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1675                 unsigned long pgoff, unsigned long flags)
1676 {
1677         unsigned long (*get_area)(struct file *, unsigned long,
1678                                   unsigned long, unsigned long, unsigned long);
1679
1680         unsigned long error = arch_mmap_check(addr, len, flags);
1681         if (error)
1682                 return error;
1683
1684         /* Careful about overflows.. */
1685         if (len > TASK_SIZE)
1686                 return -ENOMEM;
1687
1688         get_area = current->mm->get_unmapped_area;
1689         if (file && file->f_op && file->f_op->get_unmapped_area)
1690                 get_area = file->f_op->get_unmapped_area;
1691         addr = get_area(file, addr, len, pgoff, flags);
1692         if (IS_ERR_VALUE(addr))
1693                 return addr;
1694
1695         if (addr > TASK_SIZE - len)
1696                 return -ENOMEM;
1697         if (addr & ~PAGE_MASK)
1698                 return -EINVAL;
1699
1700         return arch_rebalance_pgtables(addr, len);
1701 }
1702
1703 EXPORT_SYMBOL(get_unmapped_area);
1704
1705 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
1706 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1707 {
1708         struct vm_area_struct *vma = NULL;
1709
1710         if (mm) {
1711                 /* Check the cache first. */
1712                 /* (Cache hit rate is typically around 35%.) */
1713                 vma = mm->mmap_cache;
1714                 if (!(vma && vma->vm_end > addr && vma->vm_start <= addr)) {
1715                         struct rb_node * rb_node;
1716
1717                         rb_node = mm->mm_rb.rb_node;
1718                         vma = NULL;
1719
1720                         while (rb_node) {
1721                                 struct vm_area_struct * vma_tmp;
1722
1723                                 vma_tmp = rb_entry(rb_node,
1724                                                 struct vm_area_struct, vm_rb);
1725
1726                                 if (vma_tmp->vm_end > addr) {
1727                                         vma = vma_tmp;
1728                                         if (vma_tmp->vm_start <= addr)
1729                                                 break;
1730                                         rb_node = rb_node->rb_left;
1731                                 } else
1732                                         rb_node = rb_node->rb_right;
1733                         }
1734                         if (vma)
1735                                 mm->mmap_cache = vma;
1736                 }
1737         }
1738         return vma;
1739 }
1740
1741 EXPORT_SYMBOL(find_vma);
1742
1743 /* Same as find_vma, but also return a pointer to the previous VMA in *pprev. */
1744 struct vm_area_struct *
1745 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1746                         struct vm_area_struct **pprev)
1747 {
1748         struct vm_area_struct *vma = NULL, *prev = NULL;
1749         struct rb_node *rb_node;
1750         if (!mm)
1751                 goto out;
1752
1753         /* Guard against addr being lower than the first VMA */
1754         vma = mm->mmap;
1755
1756         /* Go through the RB tree quickly. */
1757         rb_node = mm->mm_rb.rb_node;
1758
1759         while (rb_node) {
1760                 struct vm_area_struct *vma_tmp;
1761                 vma_tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
1762
1763                 if (addr < vma_tmp->vm_end) {
1764                         rb_node = rb_node->rb_left;
1765                 } else {
1766                         prev = vma_tmp;
1767                         if (!prev->vm_next || (addr < prev->vm_next->vm_end))
1768                                 break;
1769                         rb_node = rb_node->rb_right;
1770                 }
1771         }
1772
1773 out:
1774         *pprev = prev;
1775         return prev ? prev->vm_next : vma;
1776 }
1777
1778 /*
1779  * Verify that the stack growth is acceptable and
1780  * update accounting. This is shared with both the
1781  * grow-up and grow-down cases.
1782  */
1783 static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
1784 {
1785         struct mm_struct *mm = vma->vm_mm;
1786         struct rlimit *rlim = current->signal->rlim;
1787         unsigned long new_start;
1788
1789         /* address space limit tests */
1790         if (!may_expand_vm(mm, grow))
1791                 return -ENOMEM;
1792
1793         /* Stack limit test */
1794         if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur))
1795                 return -ENOMEM;
1796
1797         /* mlock limit tests */
1798         if (vma->vm_flags & VM_LOCKED) {
1799                 unsigned long locked;
1800                 unsigned long limit;
1801                 locked = mm->locked_vm + grow;
1802                 limit = ACCESS_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
1803                 limit >>= PAGE_SHIFT;
1804                 if (locked > limit && !capable(CAP_IPC_LOCK))
1805                         return -ENOMEM;
1806         }
1807
1808         /* Check to ensure the stack will not grow into a hugetlb-only region */
1809         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
1810                         vma->vm_end - size;
1811         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
1812                 return -EFAULT;
1813
1814         /*
1815          * Overcommit..  This must be the final test, as it will
1816          * update security statistics.
1817          */
1818         if (security_vm_enough_memory_mm(mm, grow))
1819                 return -ENOMEM;
1820
1821         /* Ok, everything looks good - let it rip */
1822         mm->total_vm += grow;
1823         if (vma->vm_flags & VM_LOCKED)
1824                 mm->locked_vm += grow;
1825         vm_stat_account(mm, vma->vm_flags, vma->vm_file, grow);
1826         return 0;
1827 }
1828
1829 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
1830 /*
1831  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
1832  * vma is the last one with address > vma->vm_end.  Have to extend vma.
1833  */
1834 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
1835 {
1836         int error;
1837
1838         if (!(vma->vm_flags & VM_GROWSUP))
1839                 return -EFAULT;
1840
1841         /*
1842          * We must make sure the anon_vma is allocated
1843          * so that the anon_vma locking is not a noop.
1844          */
1845         if (unlikely(anon_vma_prepare(vma)))
1846                 return -ENOMEM;
1847         vma_lock_anon_vma(vma);
1848
1849         /*
1850          * vma->vm_start/vm_end cannot change under us because the caller
1851          * is required to hold the mmap_sem in read mode.  We need the
1852          * anon_vma lock to serialize against concurrent expand_stacks.
1853          * Also guard against wrapping around to address 0.
1854          */
1855         if (address < PAGE_ALIGN(address+4))
1856                 address = PAGE_ALIGN(address+4);
1857         else {
1858                 vma_unlock_anon_vma(vma);
1859                 return -ENOMEM;
1860         }
1861         error = 0;
1862
1863         /* Somebody else might have raced and expanded it already */
1864         if (address > vma->vm_end) {
1865                 unsigned long size, grow;
1866
1867                 size = address - vma->vm_start;
1868                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
1869
1870                 error = -ENOMEM;
1871                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
1872                         error = acct_stack_growth(vma, size, grow);
1873                         if (!error) {
1874                                 vma->vm_end = address;
1875                                 perf_event_mmap(vma);
1876                         }
1877                 }
1878         }
1879         vma_unlock_anon_vma(vma);
1880         khugepaged_enter_vma_merge(vma);
1881         return error;
1882 }
1883 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
1884
1885 /*
1886  * vma is the first one with address < vma->vm_start.  Have to extend vma.
1887  */
1888 int expand_downwards(struct vm_area_struct *vma,
1889                                    unsigned long address)
1890 {
1891         int error;
1892
1893         /*
1894          * We must make sure the anon_vma is allocated
1895          * so that the anon_vma locking is not a noop.
1896          */
1897         if (unlikely(anon_vma_prepare(vma)))
1898                 return -ENOMEM;
1899
1900         address &= PAGE_MASK;
1901         error = security_file_mmap(NULL, 0, 0, 0, address, 1);
1902         if (error)
1903                 return error;
1904
1905         vma_lock_anon_vma(vma);
1906
1907         /*
1908          * vma->vm_start/vm_end cannot change under us because the caller
1909          * is required to hold the mmap_sem in read mode.  We need the
1910          * anon_vma lock to serialize against concurrent expand_stacks.
1911          */
1912
1913         /* Somebody else might have raced and expanded it already */
1914         if (address < vma->vm_start) {
1915                 unsigned long size, grow;
1916
1917                 size = vma->vm_end - address;
1918                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
1919
1920                 error = -ENOMEM;
1921                 if (grow <= vma->vm_pgoff) {
1922                         error = acct_stack_growth(vma, size, grow);
1923                         if (!error) {
1924                                 vma->vm_start = address;
1925                                 vma->vm_pgoff -= grow;
1926                                 perf_event_mmap(vma);
1927                         }
1928                 }
1929         }
1930         vma_unlock_anon_vma(vma);
1931         khugepaged_enter_vma_merge(vma);
1932         return error;
1933 }
1934
1935 #ifdef CONFIG_STACK_GROWSUP
1936 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1937 {
1938         return expand_upwards(vma, address);
1939 }
1940
1941 struct vm_area_struct *
1942 find_extend_vma(struct mm_struct *mm, unsigned long addr)
1943 {
1944         struct vm_area_struct *vma, *prev;
1945
1946         addr &= PAGE_MASK;
1947         vma = find_vma_prev(mm, addr, &prev);
1948         if (vma && (vma->vm_start <= addr))
1949                 return vma;
1950         if (!prev || expand_stack(prev, addr))
1951                 return NULL;
1952         if (prev->vm_flags & VM_LOCKED) {
1953                 mlock_vma_pages_range(prev, addr, prev->vm_end);
1954         }
1955         return prev;
1956 }
1957 #else
1958 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1959 {
1960         return expand_downwards(vma, address);
1961 }
1962
1963 struct vm_area_struct *
1964 find_extend_vma(struct mm_struct * mm, unsigned long addr)
1965 {
1966         struct vm_area_struct * vma;
1967         unsigned long start;
1968
1969         addr &= PAGE_MASK;
1970         vma = find_vma(mm,addr);
1971         if (!vma)
1972                 return NULL;
1973         if (vma->vm_start <= addr)
1974                 return vma;
1975         if (!(vma->vm_flags & VM_GROWSDOWN))
1976                 return NULL;
1977         start = vma->vm_start;
1978         if (expand_stack(vma, addr))
1979                 return NULL;
1980         if (vma->vm_flags & VM_LOCKED) {
1981                 mlock_vma_pages_range(vma, addr, start);
1982         }
1983         return vma;
1984 }
1985 #endif
1986
1987 /*
1988  * Ok - we have the memory areas we should free on the vma list,
1989  * so release them, and do the vma updates.
1990  *
1991  * Called with the mm semaphore held.
1992  */
1993 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
1994 {
1995         /* Update high watermark before we lower total_vm */
1996         update_hiwater_vm(mm);
1997         do {
1998                 long nrpages = vma_pages(vma);
1999
2000                 mm->total_vm -= nrpages;
2001                 vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
2002                 vma = remove_vma(vma);
2003         } while (vma);
2004         validate_mm(mm);
2005 }
2006
2007 /*
2008  * Get rid of page table information in the indicated region.
2009  *
2010  * Called with the mm semaphore held.
2011  */
2012 static void unmap_region(struct mm_struct *mm,
2013                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2014                 unsigned long start, unsigned long end)
2015 {
2016         struct vm_area_struct *next = prev? prev->vm_next: mm->mmap;
2017         struct mmu_gather tlb;
2018         unsigned long nr_accounted = 0;
2019
2020         lru_add_drain();
2021         tlb_gather_mmu(&tlb, mm, 0);
2022         update_hiwater_rss(mm);
2023         unmap_vmas(&tlb, vma, start, end, &nr_accounted, NULL);
2024         vm_unacct_memory(nr_accounted);
2025         free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2026                                  next ? next->vm_start : 0);
2027         tlb_finish_mmu(&tlb, start, end);
2028 }
2029
2030 /*
2031  * Create a list of vma's touched by the unmap, removing them from the mm's
2032  * vma list as we go..
2033  */
2034 static void
2035 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2036         struct vm_area_struct *prev, unsigned long end)
2037 {
2038         struct vm_area_struct **insertion_point;
2039         struct vm_area_struct *tail_vma = NULL;
2040         unsigned long addr;
2041
2042         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2043         vma->vm_prev = NULL;
2044         do {
2045                 rb_erase(&vma->vm_rb, &mm->mm_rb);
2046                 mm->map_count--;
2047                 tail_vma = vma;
2048                 vma = vma->vm_next;
2049         } while (vma && vma->vm_start < end);
2050         *insertion_point = vma;
2051         if (vma)
2052                 vma->vm_prev = prev;
2053         tail_vma->vm_next = NULL;
2054         if (mm->unmap_area == arch_unmap_area)
2055                 addr = prev ? prev->vm_end : mm->mmap_base;
2056         else
2057                 addr = vma ?  vma->vm_start : mm->mmap_base;
2058         mm->unmap_area(mm, addr);
2059         mm->mmap_cache = NULL;          /* Kill the cache. */
2060 }
2061
2062 /*
2063  * __split_vma() bypasses sysctl_max_map_count checking.  We use this on the
2064  * munmap path where it doesn't make sense to fail.
2065  */
2066 static int __split_vma(struct mm_struct * mm, struct vm_area_struct * vma,
2067               unsigned long addr, int new_below)
2068 {
2069         struct mempolicy *pol;
2070         struct vm_area_struct *new;
2071         int err = -ENOMEM;
2072
2073         if (is_vm_hugetlb_page(vma) && (addr &
2074                                         ~(huge_page_mask(hstate_vma(vma)))))
2075                 return -EINVAL;
2076
2077         new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2078         if (!new)
2079                 goto out_err;
2080
2081         /* most fields are the same, copy all, and then fixup */
2082         *new = *vma;
2083
2084         INIT_LIST_HEAD(&new->anon_vma_chain);
2085
2086         if (new_below)
2087                 new->vm_end = addr;
2088         else {
2089                 new->vm_start = addr;
2090                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2091         }
2092
2093         pol = mpol_dup(vma_policy(vma));
2094         if (IS_ERR(pol)) {
2095                 err = PTR_ERR(pol);
2096                 goto out_free_vma;
2097         }
2098         vma_set_policy(new, pol);
2099
2100         if (anon_vma_clone(new, vma))
2101                 goto out_free_mpol;
2102
2103         if (new->vm_file) {
2104                 get_file(new->vm_file);
2105                 if (vma->vm_flags & VM_EXECUTABLE)
2106                         added_exe_file_vma(mm);
2107         }
2108
2109         if (new->vm_ops && new->vm_ops->open)
2110                 new->vm_ops->open(new);
2111
2112         if (new_below)
2113                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2114                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2115         else
2116                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2117
2118         /* Success. */
2119         if (!err)
2120                 return 0;
2121
2122         /* Clean everything up if vma_adjust failed. */
2123         if (new->vm_ops && new->vm_ops->close)
2124                 new->vm_ops->close(new);
2125         if (new->vm_file) {
2126                 if (vma->vm_flags & VM_EXECUTABLE)
2127                         removed_exe_file_vma(mm);
2128                 fput(new->vm_file);
2129         }
2130         unlink_anon_vmas(new);
2131  out_free_mpol:
2132         mpol_put(pol);
2133  out_free_vma:
2134         kmem_cache_free(vm_area_cachep, new);
2135  out_err:
2136         return err;
2137 }
2138
2139 /*
2140  * Split a vma into two pieces at address 'addr', a new vma is allocated
2141  * either for the first part or the tail.
2142  */
2143 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2144               unsigned long addr, int new_below)
2145 {
2146         if (mm->map_count >= sysctl_max_map_count)
2147                 return -ENOMEM;
2148
2149         return __split_vma(mm, vma, addr, new_below);
2150 }
2151
2152 /* Munmap is split into 2 main parts -- this part which finds
2153  * what needs doing, and the areas themselves, which do the
2154  * work.  This now handles partial unmappings.
2155  * Jeremy Fitzhardinge <jeremy@goop.org>
2156  */
2157 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2158 {
2159         unsigned long end;
2160         struct vm_area_struct *vma, *prev, *last;
2161     unsigned long a;
2162         int error;
2163
2164         if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
2165                 return -EINVAL;
2166
2167         if ((len = PAGE_ALIGN(len)) == 0)
2168                 return -EINVAL;
2169
2170 #ifdef PROCESS_SERVER_ENFORCE_VMA_MOD_ATOMICITY
2171     if(current->enable_distributed_munmap) {
2172         up_write(&mm->mmap_sem);
2173 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
2174         process_server_acquire_heavy_lock();
2175 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
2176         process_server_acquire_distributed_mm_lock();
2177 #else
2178         process_server_acquire_page_lock_range(start,len);
2179 #endif
2180         down_write(&mm->mmap_sem);
2181     }
2182 #endif
2183
2184         /* Find the first overlapping VMA */
2185         vma = find_vma(mm, start);
2186         if (!vma) {
2187         error = 0;
2188         goto err;
2189     }
2190         prev = vma->vm_prev;
2191         /* we have  start < vma->vm_end  */
2192
2193         /* if it doesn't overlap, we have nothing.. */
2194         end = start + len;
2195         if (vma->vm_start >= end) {
2196                 error = 0;
2197         goto err;
2198     }
2199         
2200     /*
2201          * If we need to split any vma, do it now to save pain later.
2202          *
2203          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2204          * unmapped vm_area_struct will remain in use: so lower split_vma
2205          * places tmp vma above, and higher split_vma places tmp vma below.
2206          */
2207         if (start > vma->vm_start) {
2208
2209                 /*
2210                  * Make sure that map_count on return from munmap() will
2211                  * not exceed its limit; but let map_count go just above
2212                  * its limit temporarily, to help free resources as expected.
2213                  */
2214                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count) {
2215             error = -ENOMEM;
2216                         goto err;
2217         }
2218
2219                 error = __split_vma(mm, vma, start, 0);
2220                 if (error)
2221                         goto err;
2222                 prev = vma;
2223         }
2224
2225         /* Does it split the last one? */
2226         last = find_vma(mm, end);
2227         if (last && end > last->vm_start) {
2228                 int error = __split_vma(mm, last, end, 1);
2229                 if (error)
2230                         goto err;
2231         }
2232         vma = prev? prev->vm_next: mm->mmap;
2233
2234         /*
2235          * unlock any mlock()ed ranges before detaching vmas
2236          */
2237         if (mm->locked_vm) {
2238                 struct vm_area_struct *tmp = vma;
2239                 while (tmp && tmp->vm_start < end) {
2240                         if (tmp->vm_flags & VM_LOCKED) {
2241                                 mm->locked_vm -= vma_pages(tmp);
2242                                 munlock_vma_pages_all(tmp);
2243                         }
2244                         tmp = tmp->vm_next;
2245                 }
2246         }
2247
2248
2249     /*
2250          * Remove the vma's, and unmap the actual pages
2251          */
2252         detach_vmas_to_be_unmapped(mm, vma, prev, end);
2253         unmap_region(mm, vma, prev, start, end);
2254
2255         /* Fix up all other VM information */
2256         remove_vma_list(mm, vma);
2257
2258     /*
2259      * Memory is now munmapped locally, so before exiting this syscall, synchronize
2260      * the removal of this memory from all other thread members.
2261      */
2262     process_server_do_munmap(mm, start, len);
2263
2264     //return 0;
2265     error = 0;
2266
2267 err:
2268 #ifdef PROCESS_SERVER_ENFORCE_VMA_MOD_ATOMICITY
2269     if(current->enable_distributed_munmap) {
2270 #ifdef PROCESS_SERVER_USE_HEAVY_LOCK
2271         process_server_release_heavy_lock();
2272 #elif defined(PROCESS_SERVER_USE_DISTRIBUTED_MM_LOCK)
2273         process_server_release_distributed_mm_lock();
2274 #else
2275         process_server_release_page_lock_range(start,len);
2276 #endif
2277     }
2278 #endif
2279
2280     return error;
2281 }
2282
2283 EXPORT_SYMBOL(do_munmap);
2284
2285 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2286 {
2287         int ret;
2288         struct mm_struct *mm = current->mm;
2289
2290         profile_munmap(addr);
2291
2292         down_write(&mm->mmap_sem);
2293         ret = do_munmap(mm, addr, len);
2294         up_write(&mm->mmap_sem);
2295
2296     //process_server_do_munmap(mm, addr, len);
2297
2298         return ret;
2299 }
2300
2301 static inline void verify_mm_writelocked(struct mm_struct *mm)
2302 {
2303 #ifdef CONFIG_DEBUG_VM
2304         if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2305                 WARN_ON(1);
2306                 up_read(&mm->mmap_sem);
2307         }
2308 #endif
2309 }
2310
2311 /*
2312  *  this is really a simplified "do_mmap".  it only handles
2313  *  anonymous maps.  eventually we may be able to do some
2314  *  brk-specific accounting here.
2315  */
2316 unsigned long do_brk(unsigned long addr, unsigned long len)
2317 {
2318         struct mm_struct * mm = current->mm;
2319         struct vm_area_struct * vma, * prev;
2320         unsigned long flags;
2321         struct rb_node ** rb_link, * rb_parent;
2322         pgoff_t pgoff = addr >> PAGE_SHIFT;
2323         int error;
2324
2325         len = PAGE_ALIGN(len);
2326         if (!len)
2327                 return addr;
2328
2329         error = security_file_mmap(NULL, 0, 0, 0, addr, 1);
2330         if (error)
2331                 return error;
2332
2333         flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2334
2335         error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2336         if (error & ~PAGE_MASK)
2337                 return error;
2338
2339         /*
2340          * mlock MCL_FUTURE?
2341          */
2342         if (mm->def_flags & VM_LOCKED) {
2343                 unsigned long locked, lock_limit;
2344                 locked = len >> PAGE_SHIFT;
2345                 locked += mm->locked_vm;
2346                 lock_limit = rlimit(RLIMIT_MEMLOCK);
2347                 lock_limit >>= PAGE_SHIFT;
2348                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
2349                         return -EAGAIN;
2350         }
2351
2352         /*
2353          * mm->mmap_sem is required to protect against another thread
2354          * changing the mappings in case we sleep.
2355          */
2356         verify_mm_writelocked(mm);
2357
2358         /*
2359          * Clear old maps.  this also does some error checking for us
2360          */
2361  munmap_back:
2362         vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
2363         if (vma && vma->vm_start < addr + len) {
2364                 if (do_munmap(mm, addr, len))
2365                         return -ENOMEM;
2366                 goto munmap_back;
2367         }
2368
2369         /* Check against address space limits *after* clearing old maps... */
2370         if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2371                 return -ENOMEM;
2372
2373         if (mm->map_count > sysctl_max_map_count)
2374                 return -ENOMEM;
2375
2376         if (security_vm_enough_memory(len >> PAGE_SHIFT))
2377                 return -ENOMEM;
2378
2379         /* Can we just expand an old private anonymous mapping? */
2380         vma = vma_merge(mm, prev, addr, addr + len, flags,
2381                                         NULL, NULL, pgoff, NULL);
2382         if (vma)
2383                 goto out;
2384
2385         /*
2386          * create a vma struct for an anonymous mapping
2387          */
2388         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2389         if (!vma) {
2390                 vm_unacct_memory(len >> PAGE_SHIFT);
2391                 return -ENOMEM;
2392         }
2393
2394         INIT_LIST_HEAD(&vma->anon_vma_chain);
2395         vma->vm_mm = mm;
2396         vma->vm_start = addr;
2397         vma->vm_end = addr + len;
2398         vma->vm_pgoff = pgoff;
2399         vma->vm_flags = flags;
2400         vma->vm_page_prot = vm_get_page_prot(flags);
2401         vma_link(mm, vma, prev, rb_link, rb_parent);
2402 out:
2403         perf_event_mmap(vma);
2404         mm->total_vm += len >> PAGE_SHIFT;
2405         if (flags & VM_LOCKED) {
2406                 if (!mlock_vma_pages_range(vma, addr, addr + len))
2407                         mm->locked_vm += (len >> PAGE_SHIFT);
2408         }
2409         return addr;
2410 }
2411
2412 EXPORT_SYMBOL(do_brk);
2413
2414 /* Release all mmaps. */
2415 void exit_mmap(struct mm_struct *mm)
2416 {
2417         struct mmu_gather tlb;
2418         struct vm_area_struct *vma;
2419         unsigned long nr_accounted = 0;
2420         unsigned long end;
2421
2422         /* mm's last user has gone, and its about to be pulled down */
2423         mmu_notifier_release(mm);
2424
2425         if (mm->locked_vm) {
2426                 vma = mm->mmap;
2427                 while (vma) {
2428                         if (vma->vm_flags & VM_LOCKED)
2429                                 munlock_vma_pages_all(vma);
2430                         vma = vma->vm_next;
2431                 }
2432         }
2433
2434         arch_exit_mmap(mm);
2435
2436         vma = mm->mmap;
2437         if (!vma)       /* Can happen if dup_mmap() received an OOM */
2438                 return;
2439
2440         lru_add_drain();
2441         flush_cache_mm(mm);
2442         tlb_gather_mmu(&tlb, mm, 1);
2443         /* update_hiwater_rss(mm) here? but nobody should be looking */
2444         /* Use -1 here to ensure all VMAs in the mm are unmapped */
2445         end = unmap_vmas(&tlb, vma, 0, -1, &nr_accounted, NULL);
2446         vm_unacct_memory(nr_accounted);
2447
2448         free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, 0);
2449         tlb_finish_mmu(&tlb, 0, end);
2450
2451         /*
2452          * Walk the list again, actually closing and freeing it,
2453          * with preemption enabled, without holding any MM locks.
2454          */
2455         while (vma)
2456                 vma = remove_vma(vma);
2457
2458         BUG_ON(mm->nr_ptes > (FIRST_USER_ADDRESS+PMD_SIZE-1)>>PMD_SHIFT);
2459 }
2460
2461 /* Insert vm structure into process list sorted by address
2462  * and into the inode's i_mmap tree.  If vm_file is non-NULL
2463  * then i_mmap_mutex is taken here.
2464  */
2465 int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
2466 {
2467         struct vm_area_struct * __vma, * prev;
2468         struct rb_node ** rb_link, * rb_parent;
2469
2470         /*
2471          * The vm_pgoff of a purely anonymous vma should be irrelevant
2472          * until its first write fault, when page's anon_vma and index
2473          * are set.  But now set the vm_pgoff it will almost certainly
2474          * end up with (unless mremap moves it elsewhere before that
2475          * first wfault), so /proc/pid/maps tells a consistent story.
2476          *
2477          * By setting it to reflect the virtual start address of the
2478          * vma, merges and splits can happen in a seamless way, just
2479          * using the existing file pgoff checks and manipulations.
2480          * Similarly in do_mmap_pgoff and in do_brk.
2481          */
2482         if (!vma->vm_file) {
2483                 BUG_ON(vma->anon_vma);
2484                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2485         }
2486         __vma = find_vma_prepare(mm,vma->vm_start,&prev,&rb_link,&rb_parent);
2487         if (__vma && __vma->vm_start < vma->vm_end)
2488                 return -ENOMEM;
2489         if ((vma->vm_flags & VM_ACCOUNT) &&
2490              security_vm_enough_memory_mm(mm, vma_pages(vma)))
2491                 return -ENOMEM;
2492         vma_link(mm, vma, prev, rb_link, rb_parent);
2493         return 0;
2494 }
2495
2496 /*
2497  * Copy the vma structure to a new location in the same mm,
2498  * prior to moving page table entries, to effect an mremap move.
2499  */
2500 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2501         unsigned long addr, unsigned long len, pgoff_t pgoff)
2502 {
2503         struct vm_area_struct *vma = *vmap;
2504         unsigned long vma_start = vma->vm_start;
2505         struct mm_struct *mm = vma->vm_mm;
2506         struct vm_area_struct *new_vma, *prev;
2507         struct rb_node **rb_link, *rb_parent;
2508         struct mempolicy *pol;
2509
2510         /*
2511          * If anonymous vma has not yet been faulted, update new pgoff
2512          * to match new location, to increase its chance of merging.
2513          */
2514         if (!vma->vm_file && !vma->anon_vma)
2515                 pgoff = addr >> PAGE_SHIFT;
2516
2517         find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
2518         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2519                         vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma));
2520         if (new_vma) {
2521                 /*
2522                  * Source vma may have been merged into new_vma
2523                  */
2524                 if (vma_start >= new_vma->vm_start &&
2525                     vma_start < new_vma->vm_end)
2526                         *vmap = new_vma;
2527         } else {
2528                 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2529                 if (new_vma) {
2530                         *new_vma = *vma;
2531                         pol = mpol_dup(vma_policy(vma));
2532                         if (IS_ERR(pol))
2533                                 goto out_free_vma;
2534                         INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2535                         if (anon_vma_clone(new_vma, vma))
2536                                 goto out_free_mempol;
2537                         vma_set_policy(new_vma, pol);
2538                         new_vma->vm_start = addr;
2539                         new_vma->vm_end = addr + len;
2540                         new_vma->vm_pgoff = pgoff;
2541                         if (new_vma->vm_file) {
2542                                 get_file(new_vma->vm_file);
2543                                 if (vma->vm_flags & VM_EXECUTABLE)
2544                                         added_exe_file_vma(mm);
2545                         }
2546                         if (new_vma->vm_ops && new_vma->vm_ops->open)
2547                                 new_vma->vm_ops->open(new_vma);
2548                         vma_link(mm, new_vma, prev, rb_link, rb_parent);
2549                 }
2550         }
2551         return new_vma;
2552
2553  out_free_mempol:
2554         mpol_put(pol);
2555  out_free_vma:
2556         kmem_cache_free(vm_area_cachep, new_vma);
2557         return NULL;
2558 }
2559
2560 /*
2561  * Return true if the calling process may expand its vm space by the passed
2562  * number of pages
2563  */
2564 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
2565 {
2566         unsigned long cur = mm->total_vm;       /* pages */
2567         unsigned long lim;
2568
2569         lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
2570
2571         if (cur + npages > lim)
2572                 return 0;
2573         return 1;
2574 }
2575
2576
2577 static int special_mapping_fault(struct vm_area_struct *vma,
2578                                 struct vm_fault *vmf)
2579 {
2580         pgoff_t pgoff;
2581         struct page **pages;
2582
2583         /*
2584          * special mappings have no vm_file, and in that case, the mm
2585          * uses vm_pgoff internally. So we have to subtract it from here.
2586          * We are allowed to do this because we are the mm; do not copy
2587          * this code into drivers!
2588          */
2589         pgoff = vmf->pgoff - vma->vm_pgoff;
2590
2591         for (pages = vma->vm_private_data; pgoff && *pages; ++pages)
2592                 pgoff--;
2593
2594         if (*pages) {
2595                 struct page *page = *pages;
2596                 get_page(page);
2597                 vmf->page = page;
2598                 return 0;
2599         }
2600
2601         return VM_FAULT_SIGBUS;
2602 }
2603
2604 /*
2605  * Having a close hook prevents vma merging regardless of flags.
2606  */
2607 static void special_mapping_close(struct vm_area_struct *vma)
2608 {
2609 }
2610
2611 static const struct vm_operations_struct special_mapping_vmops = {
2612         .close = special_mapping_close,
2613         .fault = special_mapping_fault,
2614 };
2615
2616 /*
2617  * Called with mm->mmap_sem held for writing.
2618  * Insert a new vma covering the given region, with the given flags.
2619  * Its pages are supplied by the given array of struct page *.
2620  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
2621  * The region past the last page supplied will always produce SIGBUS.
2622  * The array pointer and the pages it points to are assumed to stay alive
2623  * for as long as this mapping might exist.
2624  */
2625 int install_special_mapping(struct mm_struct *mm,
2626                             unsigned long addr, unsigned long len,
2627                             unsigned long vm_flags, struct page **pages)
2628 {
2629         int ret;
2630         struct vm_area_struct *vma;
2631
2632         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2633         if (unlikely(vma == NULL))
2634                 return -ENOMEM;
2635
2636         INIT_LIST_HEAD(&vma->anon_vma_chain);
2637         vma->vm_mm = mm;
2638         vma->vm_start = addr;
2639         vma->vm_end = addr + len;
2640
2641         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND;
2642         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
2643
2644         vma->vm_ops = &special_mapping_vmops;
2645         vma->vm_private_data = pages;
2646
2647         ret = security_file_mmap(NULL, 0, 0, 0, vma->vm_start, 1);
2648         if (ret)
2649                 goto out;
2650
2651         ret = insert_vm_struct(mm, vma);
2652         if (ret)
2653                 goto out;
2654
2655         mm->total_vm += len >> PAGE_SHIFT;
2656
2657         perf_event_mmap(vma);
2658
2659         return 0;
2660
2661 out:
2662         kmem_cache_free(vm_area_cachep, vma);
2663         return ret;
2664 }
2665
2666 static DEFINE_MUTEX(mm_all_locks_mutex);
2667
2668 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
2669 {
2670         if (!test_bit(0, (unsigned long *) &anon_vma->root->head.next)) {
2671                 /*
2672                  * The LSB of head.next can't change from under us
2673                  * because we hold the mm_all_locks_mutex.
2674                  */
2675                 mutex_lock_nest_lock(&anon_vma->root->mutex, &mm->mmap_sem);
2676                 /*
2677                  * We can safely modify head.next after taking the
2678                  * anon_vma->root->mutex. If some other vma in this mm shares
2679                  * the same anon_vma we won't take it again.
2680                  *
2681                  * No need of atomic instructions here, head.next
2682                  * can't change from under us thanks to the
2683                  * anon_vma->root->mutex.
2684                  */
2685                 if (__test_and_set_bit(0, (unsigned long *)
2686                                        &anon_vma->root->head.next))
2687                         BUG();
2688         }
2689 }
2690
2691 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
2692 {
2693         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2694                 /*
2695                  * AS_MM_ALL_LOCKS can't change from under us because
2696                  * we hold the mm_all_locks_mutex.
2697                  *
2698                  * Operations on ->flags have to be atomic because
2699                  * even if AS_MM_ALL_LOCKS is stable thanks to the
2700                  * mm_all_locks_mutex, there may be other cpus
2701                  * changing other bitflags in parallel to us.
2702                  */
2703                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
2704                         BUG();
2705                 mutex_lock_nest_lock(&mapping->i_mmap_mutex, &mm->mmap_sem);
2706         }
2707 }
2708
2709 /*
2710  * This operation locks against the VM for all pte/vma/mm related
2711  * operations that could ever happen on a certain mm. This includes
2712  * vmtruncate, try_to_unmap, and all page faults.
2713  *
2714  * The caller must take the mmap_sem in write mode before calling
2715  * mm_take_all_locks(). The caller isn't allowed to release the
2716  * mmap_sem until mm_drop_all_locks() returns.
2717  *
2718  * mmap_sem in write mode is required in order to block all operations
2719  * that could modify pagetables and free pages without need of
2720  * altering the vma layout (for example populate_range() with
2721  * nonlinear vmas). It's also needed in write mode to avoid new
2722  * anon_vmas to be associated with existing vmas.
2723  *
2724  * A single task can't take more than one mm_take_all_locks() in a row
2725  * or it would deadlock.
2726  *
2727  * The LSB in anon_vma->head.next and the AS_MM_ALL_LOCKS bitflag in
2728  * mapping->flags avoid to take the same lock twice, if more than one
2729  * vma in this mm is backed by the same anon_vma or address_space.
2730  *
2731  * We can take all the locks in random order because the VM code
2732  * taking i_mmap_mutex or anon_vma->mutex outside the mmap_sem never
2733  * takes more than one of them in a row. Secondly we're protected
2734  * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
2735  *
2736  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
2737  * that may have to take thousand of locks.
2738  *
2739  * mm_take_all_locks() can fail if it's interrupted by signals.
2740  */
2741 int mm_take_all_locks(struct mm_struct *mm)
2742 {
2743         struct vm_area_struct *vma;
2744         struct anon_vma_chain *avc;
2745
2746         BUG_ON(down_read_trylock(&mm->mmap_sem));
2747
2748         mutex_lock(&mm_all_locks_mutex);
2749
2750         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2751                 if (signal_pending(current))
2752                         goto out_unlock;
2753                 if (vma->vm_file && vma->vm_file->f_mapping)
2754                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
2755         }
2756
2757         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2758                 if (signal_pending(current))
2759                         goto out_unlock;
2760                 if (vma->anon_vma)
2761                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2762                                 vm_lock_anon_vma(mm, avc->anon_vma);
2763         }
2764
2765         return 0;
2766
2767 out_unlock:
2768         mm_drop_all_locks(mm);
2769         return -EINTR;
2770 }
2771
2772 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2773 {
2774         if (test_bit(0, (unsigned long *) &anon_vma->root->head.next)) {
2775                 /*
2776                  * The LSB of head.next can't change to 0 from under
2777                  * us because we hold the mm_all_locks_mutex.
2778                  *
2779                  * We must however clear the bitflag before unlocking
2780                  * the vma so the users using the anon_vma->head will
2781                  * never see our bitflag.
2782                  *
2783                  * No need of atomic instructions here, head.next
2784                  * can't change from under us until we release the
2785                  * anon_vma->root->mutex.
2786                  */
2787                 if (!__test_and_clear_bit(0, (unsigned long *)
2788                                           &anon_vma->root->head.next))
2789                         BUG();
2790                 anon_vma_unlock(anon_vma);
2791         }
2792 }
2793
2794 static void vm_unlock_mapping(struct address_space *mapping)
2795 {
2796         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2797                 /*
2798                  * AS_MM_ALL_LOCKS can't change to 0 from under us
2799                  * because we hold the mm_all_locks_mutex.
2800                  */
2801                 mutex_unlock(&mapping->i_mmap_mutex);
2802                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2803                                         &mapping->flags))
2804                         BUG();
2805         }
2806 }
2807
2808 /*
2809  * The mmap_sem cannot be released by the caller until
2810  * mm_drop_all_locks() returns.
2811  */
2812 void mm_drop_all_locks(struct mm_struct *mm)
2813 {
2814         struct vm_area_struct *vma;
2815         struct anon_vma_chain *avc;
2816
2817         BUG_ON(down_read_trylock(&mm->mmap_sem));
2818         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2819
2820         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2821                 if (vma->anon_vma)
2822                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2823                                 vm_unlock_anon_vma(avc->anon_vma);
2824                 if (vma->vm_file && vma->vm_file->f_mapping)
2825                         vm_unlock_mapping(vma->vm_file->f_mapping);
2826         }
2827
2828         mutex_unlock(&mm_all_locks_mutex);
2829 }
2830
2831 /*
2832  * initialise the VMA slab
2833  */
2834 void __init mmap_init(void)
2835 {
2836         int ret;
2837
2838         ret = percpu_counter_init(&vm_committed_as, 0);
2839         VM_BUG_ON(ret);
2840 }