cafada378a8c501907f8b5d466f90caa09509043
[linux-2.6.git] / mm / mmap.c
1 /*
2  * mm/mmap.c
3  *
4  * Written by obz.
5  *
6  * Address space accounting code        <alan@redhat.com>
7  */
8
9 #include <linux/slab.h>
10 #include <linux/shm.h>
11 #include <linux/mman.h>
12 #include <linux/pagemap.h>
13 #include <linux/swap.h>
14 #include <linux/syscalls.h>
15 #include <linux/init.h>
16 #include <linux/file.h>
17 #include <linux/fs.h>
18 #include <linux/personality.h>
19 #include <linux/security.h>
20 #include <linux/hugetlb.h>
21 #include <linux/profile.h>
22 #include <linux/module.h>
23 #include <linux/mount.h>
24 #include <linux/mempolicy.h>
25 #include <linux/rmap.h>
26
27 #include <asm/uaccess.h>
28 #include <asm/pgalloc.h>
29 #include <asm/cacheflush.h>
30 #include <asm/tlb.h>
31
32 /*
33  * WARNING: the debugging will use recursive algorithms so never enable this
34  * unless you know what you are doing.
35  */
36 #undef DEBUG_MM_RB
37
38 /* description of effects of mapping type and prot in current implementation.
39  * this is due to the limited x86 page protection hardware.  The expected
40  * behavior is in parens:
41  *
42  * map_type     prot
43  *              PROT_NONE       PROT_READ       PROT_WRITE      PROT_EXEC
44  * MAP_SHARED   r: (no) no      r: (yes) yes    r: (no) yes     r: (no) yes
45  *              w: (no) no      w: (no) no      w: (yes) yes    w: (no) no
46  *              x: (no) no      x: (no) yes     x: (no) yes     x: (yes) yes
47  *              
48  * MAP_PRIVATE  r: (no) no      r: (yes) yes    r: (no) yes     r: (no) yes
49  *              w: (no) no      w: (no) no      w: (copy) copy  w: (no) no
50  *              x: (no) no      x: (no) yes     x: (no) yes     x: (yes) yes
51  *
52  */
53 pgprot_t protection_map[16] = {
54         __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
55         __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
56 };
57
58 int sysctl_overcommit_memory = 0;       /* default is heuristic overcommit */
59 int sysctl_overcommit_ratio = 50;       /* default is 50% */
60 int sysctl_max_map_count = DEFAULT_MAX_MAP_COUNT;
61 atomic_t vm_committed_space = ATOMIC_INIT(0);
62
63 EXPORT_SYMBOL(sysctl_overcommit_memory);
64 EXPORT_SYMBOL(sysctl_overcommit_ratio);
65 EXPORT_SYMBOL(sysctl_max_map_count);
66 EXPORT_SYMBOL(vm_committed_space);
67
68 /*
69  * Requires inode->i_mapping->i_mmap_lock
70  */
71 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
72                 struct file *file, struct address_space *mapping)
73 {
74         if (vma->vm_flags & VM_DENYWRITE)
75                 atomic_inc(&file->f_dentry->d_inode->i_writecount);
76         if (vma->vm_flags & VM_SHARED)
77                 mapping->i_mmap_writable--;
78
79         flush_dcache_mmap_lock(mapping);
80         if (unlikely(vma->vm_flags & VM_NONLINEAR))
81                 list_del_init(&vma->shared.vm_set.list);
82         else
83                 vma_prio_tree_remove(vma, &mapping->i_mmap);
84         flush_dcache_mmap_unlock(mapping);
85 }
86
87 /*
88  * Remove one vm structure and free it.
89  */
90 static void remove_vm_struct(struct vm_area_struct *vma)
91 {
92         struct file *file = vma->vm_file;
93
94         if (file) {
95                 struct address_space *mapping = file->f_mapping;
96                 spin_lock(&mapping->i_mmap_lock);
97                 __remove_shared_vm_struct(vma, file, mapping);
98                 spin_unlock(&mapping->i_mmap_lock);
99         }
100         if (vma->vm_ops && vma->vm_ops->close)
101                 vma->vm_ops->close(vma);
102         if (file)
103                 fput(file);
104         anon_vma_unlink(vma);
105         mpol_free(vma_policy(vma));
106         kmem_cache_free(vm_area_cachep, vma);
107 }
108
109 /*
110  *  sys_brk() for the most part doesn't need the global kernel
111  *  lock, except when an application is doing something nasty
112  *  like trying to un-brk an area that has already been mapped
113  *  to a regular file.  in this case, the unmapping will need
114  *  to invoke file system routines that need the global lock.
115  */
116 asmlinkage unsigned long sys_brk(unsigned long brk)
117 {
118         unsigned long rlim, retval;
119         unsigned long newbrk, oldbrk;
120         struct mm_struct *mm = current->mm;
121
122         down_write(&mm->mmap_sem);
123
124         if (brk < mm->end_code)
125                 goto out;
126         newbrk = PAGE_ALIGN(brk);
127         oldbrk = PAGE_ALIGN(mm->brk);
128         if (oldbrk == newbrk)
129                 goto set_brk;
130
131         /* Always allow shrinking brk. */
132         if (brk <= mm->brk) {
133                 if (!do_munmap(mm, newbrk, oldbrk-newbrk))
134                         goto set_brk;
135                 goto out;
136         }
137
138         /* Check against rlimit.. */
139         rlim = current->rlim[RLIMIT_DATA].rlim_cur;
140         if (rlim < RLIM_INFINITY && brk - mm->start_data > rlim)
141                 goto out;
142
143         /* Check against existing mmap mappings. */
144         if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE))
145                 goto out;
146
147         /* Ok, looks good - let it rip. */
148         if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
149                 goto out;
150 set_brk:
151         mm->brk = brk;
152 out:
153         retval = mm->brk;
154         up_write(&mm->mmap_sem);
155         return retval;
156 }
157
158 #ifdef DEBUG_MM_RB
159 static int browse_rb(struct rb_root *root)
160 {
161         int i = 0, j;
162         struct rb_node *nd, *pn = NULL;
163         unsigned long prev = 0, pend = 0;
164
165         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
166                 struct vm_area_struct *vma;
167                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
168                 if (vma->vm_start < prev)
169                         printk("vm_start %lx prev %lx\n", vma->vm_start, prev), i = -1;
170                 if (vma->vm_start < pend)
171                         printk("vm_start %lx pend %lx\n", vma->vm_start, pend);
172                 if (vma->vm_start > vma->vm_end)
173                         printk("vm_end %lx < vm_start %lx\n", vma->vm_end, vma->vm_start);
174                 i++;
175                 pn = nd;
176         }
177         j = 0;
178         for (nd = pn; nd; nd = rb_prev(nd)) {
179                 j++;
180         }
181         if (i != j)
182                 printk("backwards %d, forwards %d\n", j, i), i = 0;
183         return i;
184 }
185
186 void validate_mm(struct mm_struct *mm)
187 {
188         int bug = 0;
189         int i = 0;
190         struct vm_area_struct *tmp = mm->mmap;
191         while (tmp) {
192                 tmp = tmp->vm_next;
193                 i++;
194         }
195         if (i != mm->map_count)
196                 printk("map_count %d vm_next %d\n", mm->map_count, i), bug = 1;
197         i = browse_rb(&mm->mm_rb);
198         if (i != mm->map_count)
199                 printk("map_count %d rb %d\n", mm->map_count, i), bug = 1;
200         if (bug)
201                 BUG();
202 }
203 #else
204 #define validate_mm(mm) do { } while (0)
205 #endif
206
207 static struct vm_area_struct *
208 find_vma_prepare(struct mm_struct *mm, unsigned long addr,
209                 struct vm_area_struct **pprev, struct rb_node ***rb_link,
210                 struct rb_node ** rb_parent)
211 {
212         struct vm_area_struct * vma;
213         struct rb_node ** __rb_link, * __rb_parent, * rb_prev;
214
215         __rb_link = &mm->mm_rb.rb_node;
216         rb_prev = __rb_parent = NULL;
217         vma = NULL;
218
219         while (*__rb_link) {
220                 struct vm_area_struct *vma_tmp;
221
222                 __rb_parent = *__rb_link;
223                 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
224
225                 if (vma_tmp->vm_end > addr) {
226                         vma = vma_tmp;
227                         if (vma_tmp->vm_start <= addr)
228                                 return vma;
229                         __rb_link = &__rb_parent->rb_left;
230                 } else {
231                         rb_prev = __rb_parent;
232                         __rb_link = &__rb_parent->rb_right;
233                 }
234         }
235
236         *pprev = NULL;
237         if (rb_prev)
238                 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
239         *rb_link = __rb_link;
240         *rb_parent = __rb_parent;
241         return vma;
242 }
243
244 static inline void
245 __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
246                 struct vm_area_struct *prev, struct rb_node *rb_parent)
247 {
248         if (vma->vm_flags & VM_EXEC)
249                 arch_add_exec_range(mm, vma->vm_end);
250         if (prev) {
251                 vma->vm_next = prev->vm_next;
252                 prev->vm_next = vma;
253         } else {
254                 mm->mmap = vma;
255                 if (rb_parent)
256                         vma->vm_next = rb_entry(rb_parent,
257                                         struct vm_area_struct, vm_rb);
258                 else
259                         vma->vm_next = NULL;
260         }
261 }
262
263 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
264                 struct rb_node **rb_link, struct rb_node *rb_parent)
265 {
266         rb_link_node(&vma->vm_rb, rb_parent, rb_link);
267         rb_insert_color(&vma->vm_rb, &mm->mm_rb);
268 }
269
270 static inline void __vma_link_file(struct vm_area_struct *vma)
271 {
272         struct file * file;
273
274         file = vma->vm_file;
275         if (file) {
276                 struct address_space *mapping = file->f_mapping;
277
278                 if (vma->vm_flags & VM_DENYWRITE)
279                         atomic_dec(&file->f_dentry->d_inode->i_writecount);
280                 if (vma->vm_flags & VM_SHARED)
281                         mapping->i_mmap_writable++;
282
283                 flush_dcache_mmap_lock(mapping);
284                 if (unlikely(vma->vm_flags & VM_NONLINEAR))
285                         list_add_tail(&vma->shared.vm_set.list,
286                                         &mapping->i_mmap_nonlinear);
287                 else
288                         vma_prio_tree_insert(vma, &mapping->i_mmap);
289                 flush_dcache_mmap_unlock(mapping);
290         }
291 }
292
293 static void
294 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
295         struct vm_area_struct *prev, struct rb_node **rb_link,
296         struct rb_node *rb_parent)
297 {
298         vma_prio_tree_init(vma);
299         __vma_link_list(mm, vma, prev, rb_parent);
300         __vma_link_rb(mm, vma, rb_link, rb_parent);
301         __vma_link_file(vma);
302         __anon_vma_link(vma);
303 }
304
305 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
306                         struct vm_area_struct *prev, struct rb_node **rb_link,
307                         struct rb_node *rb_parent)
308 {
309         struct address_space *mapping = NULL;
310
311         if (vma->vm_file)
312                 mapping = vma->vm_file->f_mapping;
313
314         if (mapping)
315                 spin_lock(&mapping->i_mmap_lock);
316         anon_vma_lock(vma);
317         __vma_link(mm, vma, prev, rb_link, rb_parent);
318         anon_vma_unlock(vma);
319         if (mapping)
320                 spin_unlock(&mapping->i_mmap_lock);
321
322         mark_mm_hugetlb(mm, vma);
323         mm->map_count++;
324         validate_mm(mm);
325 }
326
327 /*
328  * Insert vm structure into process list sorted by address and into the
329  * inode's i_mmap tree. The caller should hold mm->mmap_sem and
330  * ->f_mappping->i_mmap_lock if vm_file is non-NULL.
331  */
332 static void
333 __insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
334 {
335         struct vm_area_struct * __vma, * prev;
336         struct rb_node ** rb_link, * rb_parent;
337
338         __vma = find_vma_prepare(mm, vma->vm_start,&prev, &rb_link, &rb_parent);
339         if (__vma && __vma->vm_start < vma->vm_end)
340                 BUG();
341         __vma_link(mm, vma, prev, rb_link, rb_parent);
342         mark_mm_hugetlb(mm, vma);
343         mm->map_count++;
344         validate_mm(mm);
345 }
346
347 static inline void
348 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
349                 struct vm_area_struct *prev)
350 {
351         prev->vm_next = vma->vm_next;
352         rb_erase(&vma->vm_rb, &mm->mm_rb);
353         if (mm->mmap_cache == vma)
354                 mm->mmap_cache = prev;
355         if (vma->vm_flags & VM_EXEC)
356                 arch_remove_exec_range(mm, vma->vm_end);
357 }
358
359 /*
360  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
361  * is already present in an i_mmap tree without adjusting the tree.
362  * The following helper function should be used when such adjustments
363  * are necessary.  The "insert" vma (if any) is to be inserted
364  * before we drop the necessary locks.
365  */
366 void vma_adjust(struct vm_area_struct *vma, unsigned long start,
367         unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
368 {
369         struct mm_struct *mm = vma->vm_mm;
370         struct vm_area_struct *next = vma->vm_next;
371         struct address_space *mapping = NULL;
372         struct prio_tree_root *root = NULL;
373         struct file *file = vma->vm_file;
374         struct anon_vma *anon_vma = NULL;
375         long adjust_next = 0;
376         int remove_next = 0;
377
378         if (next && !insert) {
379                 if (end >= next->vm_end) {
380 again:                  remove_next = 1 + (end > next->vm_end);
381                         end = next->vm_end;
382                         anon_vma = next->anon_vma;
383                 } else if (end < vma->vm_end || end > next->vm_start) {
384                         /*
385                          * vma shrinks, and !insert tells it's not
386                          * split_vma inserting another: so it must
387                          * be mprotect shifting the boundary down.
388                          *   Or:
389                          * vma expands, overlapping part of the next:
390                          * must be mprotect shifting the boundary up.
391                          */
392                         BUG_ON(vma->vm_end != next->vm_start);
393                         adjust_next = end - next->vm_start;
394                         anon_vma = next->anon_vma;
395                 }
396         }
397
398         if (file) {
399                 mapping = file->f_mapping;
400                 if (!(vma->vm_flags & VM_NONLINEAR))
401                         root = &mapping->i_mmap;
402                 spin_lock(&mapping->i_mmap_lock);
403         }
404
405         /*
406          * When changing only vma->vm_end, we don't really need
407          * anon_vma lock: but is that case worth optimizing out?
408          */
409         if (vma->anon_vma)
410                 anon_vma = vma->anon_vma;
411         if (anon_vma)
412                 spin_lock(&anon_vma->lock);
413
414         if (root) {
415                 flush_dcache_mmap_lock(mapping);
416                 vma_prio_tree_remove(vma, root);
417                 if (adjust_next)
418                         vma_prio_tree_remove(next, root);
419         }
420
421         vma->vm_start = start;
422         vma->vm_end = end;
423         vma->vm_pgoff = pgoff;
424         if (adjust_next) {
425                 next->vm_start += adjust_next;
426                 next->vm_pgoff += adjust_next >> PAGE_SHIFT;
427         }
428
429         if (root) {
430                 if (adjust_next) {
431                         vma_prio_tree_init(next);
432                         vma_prio_tree_insert(next, root);
433                 }
434                 vma_prio_tree_init(vma);
435                 vma_prio_tree_insert(vma, root);
436                 flush_dcache_mmap_unlock(mapping);
437         }
438
439         if (remove_next) {
440                 /*
441                  * vma_merge has merged next into vma, and needs
442                  * us to remove next before dropping the locks.
443                  */
444                 __vma_unlink(mm, next, vma);
445                 if (file)
446                         __remove_shared_vm_struct(next, file, mapping);
447                 if (next->anon_vma)
448                         __anon_vma_merge(vma, next);
449         } else if (insert) {
450                 /*
451                  * split_vma has split insert from vma, and needs
452                  * us to insert it before dropping the locks
453                  * (it may either follow vma or precede it).
454                  */
455                 __insert_vm_struct(mm, insert);
456         }
457
458         if (anon_vma)
459                 spin_unlock(&anon_vma->lock);
460         if (mapping)
461                 spin_unlock(&mapping->i_mmap_lock);
462
463         if (remove_next) {
464                 if (file)
465                         fput(file);
466                 mm->map_count--;
467                 mpol_free(vma_policy(next));
468                 kmem_cache_free(vm_area_cachep, next);
469                 /*
470                  * In mprotect's case 6 (see comments on vma_merge),
471                  * we must remove another next too. It would clutter
472                  * up the code too much to do both in one go.
473                  */
474                 if (remove_next == 2) {
475                         next = vma->vm_next;
476                         goto again;
477                 }
478         }
479
480         validate_mm(mm);
481 }
482
483 /*
484  * If the vma has a ->close operation then the driver probably needs to release
485  * per-vma resources, so we don't attempt to merge those.
486  */
487 #define VM_SPECIAL (VM_IO | VM_DONTCOPY | VM_DONTEXPAND | VM_RESERVED)
488
489 static inline int is_mergeable_vma(struct vm_area_struct *vma,
490                         struct file *file, unsigned long vm_flags)
491 {
492         if (vma->vm_flags != vm_flags)
493                 return 0;
494         if (vma->vm_file != file)
495                 return 0;
496         if (vma->vm_ops && vma->vm_ops->close)
497                 return 0;
498         return 1;
499 }
500
501 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
502                                         struct anon_vma *anon_vma2)
503 {
504         return !anon_vma1 || !anon_vma2 || (anon_vma1 == anon_vma2);
505 }
506
507 /*
508  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
509  * in front of (at a lower virtual address and file offset than) the vma.
510  *
511  * We cannot merge two vmas if they have differently assigned (non-NULL)
512  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
513  *
514  * We don't check here for the merged mmap wrapping around the end of pagecache
515  * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
516  * wrap, nor mmaps which cover the final page at index -1UL.
517  */
518 static int
519 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
520         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
521 {
522         if (is_mergeable_vma(vma, file, vm_flags) &&
523             is_mergeable_anon_vma(anon_vma, vma->anon_vma)) {
524                 if (vma->vm_pgoff == vm_pgoff)
525                         return 1;
526         }
527         return 0;
528 }
529
530 /*
531  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
532  * beyond (at a higher virtual address and file offset than) the vma.
533  *
534  * We cannot merge two vmas if they have differently assigned (non-NULL)
535  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
536  */
537 static int
538 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
539         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
540 {
541         if (is_mergeable_vma(vma, file, vm_flags) &&
542             is_mergeable_anon_vma(anon_vma, vma->anon_vma)) {
543                 pgoff_t vm_pglen;
544                 vm_pglen = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
545                 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
546                         return 1;
547         }
548         return 0;
549 }
550
551 /*
552  * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
553  * whether that can be merged with its predecessor or its successor.
554  * Or both (it neatly fills a hole).
555  *
556  * In most cases - when called for mmap, brk or mremap - [addr,end) is
557  * certain not to be mapped by the time vma_merge is called; but when
558  * called for mprotect, it is certain to be already mapped (either at
559  * an offset within prev, or at the start of next), and the flags of
560  * this area are about to be changed to vm_flags - and the no-change
561  * case has already been eliminated.
562  *
563  * The following mprotect cases have to be considered, where AAAA is
564  * the area passed down from mprotect_fixup, never extending beyond one
565  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
566  *
567  *     AAAA             AAAA                AAAA          AAAA
568  *    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPNNNNXXXX
569  *    cannot merge    might become    might become    might become
570  *                    PPNNNNNNNNNN    PPPPPPPPPPNN    PPPPPPPPPPPP 6 or
571  *    mmap, brk or    case 4 below    case 5 below    PPPPPPPPXXXX 7 or
572  *    mremap move:                                    PPPPNNNNNNNN 8
573  *        AAAA
574  *    PPPP    NNNN    PPPPPPPPPPPP    PPPPPPPPNNNN    PPPPNNNNNNNN
575  *    might become    case 1 below    case 2 below    case 3 below
576  *
577  * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
578  * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
579  */
580 struct vm_area_struct *vma_merge(struct mm_struct *mm,
581                         struct vm_area_struct *prev, unsigned long addr,
582                         unsigned long end, unsigned long vm_flags,
583                         struct anon_vma *anon_vma, struct file *file,
584                         pgoff_t pgoff, struct mempolicy *policy)
585 {
586         pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
587         struct vm_area_struct *area, *next;
588
589         /*
590          * We later require that vma->vm_flags == vm_flags,
591          * so this tests vma->vm_flags & VM_SPECIAL, too.
592          */
593         if (vm_flags & VM_SPECIAL)
594                 return NULL;
595
596         if (prev)
597                 next = prev->vm_next;
598         else
599                 next = mm->mmap;
600         area = next;
601         if (next && next->vm_end == end)                /* cases 6, 7, 8 */
602                 next = next->vm_next;
603
604         /*
605          * Can it merge with the predecessor?
606          */
607         if (prev && prev->vm_end == addr &&
608                         mpol_equal(vma_policy(prev), policy) &&
609                         can_vma_merge_after(prev, vm_flags,
610                                                 anon_vma, file, pgoff)) {
611                 /*
612                  * OK, it can.  Can we now merge in the successor as well?
613                  */
614                 if (next && end == next->vm_start &&
615                                 mpol_equal(policy, vma_policy(next)) &&
616                                 can_vma_merge_before(next, vm_flags,
617                                         anon_vma, file, pgoff+pglen) &&
618                                 is_mergeable_anon_vma(prev->anon_vma,
619                                                       next->anon_vma)) {
620                                                         /* cases 1, 6 */
621                         vma_adjust(prev, prev->vm_start,
622                                 next->vm_end, prev->vm_pgoff, NULL);
623                 } else                                  /* cases 2, 5, 7 */
624                         vma_adjust(prev, prev->vm_start,
625                                 end, prev->vm_pgoff, NULL);
626                 if (prev->vm_flags & VM_EXEC)
627                         arch_add_exec_range(mm, prev->vm_end);
628                 return prev;
629         }
630
631         /*
632          * Can this new request be merged in front of next?
633          */
634         if (next && end == next->vm_start &&
635                         mpol_equal(policy, vma_policy(next)) &&
636                         can_vma_merge_before(next, vm_flags,
637                                         anon_vma, file, pgoff+pglen)) {
638                 if (prev && addr < prev->vm_end)        /* case 4 */
639                         vma_adjust(prev, prev->vm_start,
640                                 addr, prev->vm_pgoff, NULL);
641                 else                                    /* cases 3, 8 */
642                         vma_adjust(area, addr, next->vm_end,
643                                 next->vm_pgoff - pglen, NULL);
644                 return area;
645         }
646
647         return NULL;
648 }
649
650 /*
651  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
652  * neighbouring vmas for a suitable anon_vma, before it goes off
653  * to allocate a new anon_vma.  It checks because a repetitive
654  * sequence of mprotects and faults may otherwise lead to distinct
655  * anon_vmas being allocated, preventing vma merge in subsequent
656  * mprotect.
657  */
658 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
659 {
660         struct vm_area_struct *near;
661         unsigned long vm_flags;
662
663         near = vma->vm_next;
664         if (!near)
665                 goto try_prev;
666
667         /*
668          * Since only mprotect tries to remerge vmas, match flags
669          * which might be mprotected into each other later on.
670          * Neither mlock nor madvise tries to remerge at present,
671          * so leave their flags as obstructing a merge.
672          */
673         vm_flags = vma->vm_flags & ~(VM_READ|VM_WRITE|VM_EXEC);
674         vm_flags |= near->vm_flags & (VM_READ|VM_WRITE|VM_EXEC);
675
676         if (near->anon_vma && vma->vm_end == near->vm_start &&
677                         mpol_equal(vma_policy(vma), vma_policy(near)) &&
678                         can_vma_merge_before(near, vm_flags,
679                                 NULL, vma->vm_file, vma->vm_pgoff +
680                                 ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT)))
681                 return near->anon_vma;
682 try_prev:
683         /*
684          * It is potentially slow to have to call find_vma_prev here.
685          * But it's only on the first write fault on the vma, not
686          * every time, and we could devise a way to avoid it later
687          * (e.g. stash info in next's anon_vma_node when assigning
688          * an anon_vma, or when trying vma_merge).  Another time.
689          */
690         if (find_vma_prev(vma->vm_mm, vma->vm_start, &near) != vma)
691                 BUG();
692         if (!near)
693                 goto none;
694
695         vm_flags = vma->vm_flags & ~(VM_READ|VM_WRITE|VM_EXEC);
696         vm_flags |= near->vm_flags & (VM_READ|VM_WRITE|VM_EXEC);
697
698         if (near->anon_vma && near->vm_end == vma->vm_start &&
699                         mpol_equal(vma_policy(near), vma_policy(vma)) &&
700                         can_vma_merge_after(near, vm_flags,
701                                 NULL, vma->vm_file, vma->vm_pgoff))
702                 return near->anon_vma;
703 none:
704         /*
705          * There's no absolute need to look only at touching neighbours:
706          * we could search further afield for "compatible" anon_vmas.
707          * But it would probably just be a waste of time searching,
708          * or lead to too many vmas hanging off the same anon_vma.
709          * We're trying to allow mprotect remerging later on,
710          * not trying to minimize memory used for anon_vmas.
711          */
712         return NULL;
713 }
714
715 /*
716  * The caller must hold down_write(current->mm->mmap_sem).
717  */
718
719 unsigned long do_mmap_pgoff(struct mm_struct *mm, struct file * file, 
720                             unsigned long addr, unsigned long len,
721                             unsigned long prot, unsigned long flags,
722                             unsigned long pgoff)
723 {
724         struct vm_area_struct * vma, * prev;
725         struct inode *inode;
726         unsigned int vm_flags;
727         int correct_wcount = 0;
728         int error;
729         struct rb_node ** rb_link, * rb_parent;
730         int accountable = 1;
731         unsigned long charged = 0;
732
733         if (file) {
734                 if (is_file_hugepages(file))
735                         accountable = 0;
736
737                 if (!file->f_op || !file->f_op->mmap)
738                         return -ENODEV;
739
740                 if ((prot & PROT_EXEC) &&
741                     (file->f_vfsmnt->mnt_flags & MNT_NOEXEC))
742                         return -EPERM;
743         }
744
745         if (!len)
746                 return addr;
747
748         /* Careful about overflows.. */
749         len = PAGE_ALIGN(len);
750         if (!len || len > TASK_SIZE)
751                 return -EINVAL;
752
753         /* offset overflow? */
754         if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
755                 return -EINVAL;
756
757         /* Too many mappings? */
758         if (mm->map_count > sysctl_max_map_count)
759                 return -ENOMEM;
760
761         /* Obtain the address to map to. we verify (or select) it and ensure
762          * that it represents a valid section of the address space.
763          */
764         addr = get_unmapped_area(file, addr, len, pgoff, flags, prot & PROT_EXEC);
765         if (addr & ~PAGE_MASK)
766                 return addr;
767
768         /* Do simple checking here so the lower-level routines won't have
769          * to. we assume access permissions have been handled by the open
770          * of the memory object, so we don't do any here.
771          */
772         vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
773                         mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
774
775         if (flags & MAP_LOCKED) {
776                 if (!can_do_mlock())
777                         return -EPERM;
778                 vm_flags |= VM_LOCKED;
779         }
780         /* mlock MCL_FUTURE? */
781         if (vm_flags & VM_LOCKED) {
782                 unsigned long locked, lock_limit;
783                 locked = mm->locked_vm << PAGE_SHIFT;
784                 lock_limit = current->rlim[RLIMIT_MEMLOCK].rlim_cur;
785                 locked += len;
786                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
787                         return -EAGAIN;
788         }
789
790         inode = file ? file->f_dentry->d_inode : NULL;
791
792         if (file) {
793                 switch (flags & MAP_TYPE) {
794                 case MAP_SHARED:
795                         if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
796                                 return -EACCES;
797
798                         /*
799                          * Make sure we don't allow writing to an append-only
800                          * file..
801                          */
802                         if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
803                                 return -EACCES;
804
805                         /*
806                          * Make sure there are no mandatory locks on the file.
807                          */
808                         if (locks_verify_locked(inode))
809                                 return -EAGAIN;
810
811                         vm_flags |= VM_SHARED | VM_MAYSHARE;
812                         if (!(file->f_mode & FMODE_WRITE))
813                                 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
814
815                         /* fall through */
816                 case MAP_PRIVATE:
817                         if (!(file->f_mode & FMODE_READ))
818                                 return -EACCES;
819                         break;
820
821                 default:
822                         return -EINVAL;
823                 }
824         } else {
825                 switch (flags & MAP_TYPE) {
826                 case MAP_SHARED:
827                         vm_flags |= VM_SHARED | VM_MAYSHARE;
828                         break;
829                 case MAP_PRIVATE:
830                         /*
831                          * Set pgoff according to addr for anon_vma.
832                          */
833                         pgoff = addr >> PAGE_SHIFT;
834                         break;
835                 default:
836                         return -EINVAL;
837                 }
838         }
839
840         error = security_file_mmap(file, prot, flags);
841         if (error)
842                 return error;
843                 
844         /* Clear old maps */
845         error = -ENOMEM;
846 munmap_back:
847         vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
848         if (vma && vma->vm_start < addr + len) {
849                 if (do_munmap(mm, addr, len))
850                         return -ENOMEM;
851                 goto munmap_back;
852         }
853
854         /* Check against address space limit. */
855         if ((mm->total_vm << PAGE_SHIFT) + len
856             > current->rlim[RLIMIT_AS].rlim_cur)
857                 return -ENOMEM;
858
859         /* check context space, maybe only Private writable mapping? */
860         if (!vx_vmpages_avail(mm, len >> PAGE_SHIFT))
861                 return -ENOMEM;
862
863         if (accountable && (!(flags & MAP_NORESERVE) ||
864                         sysctl_overcommit_memory > 1)) {
865                 if (vm_flags & VM_SHARED) {
866                         /* Check memory availability in shmem_file_setup? */
867                         vm_flags |= VM_ACCOUNT;
868                 } else if (vm_flags & VM_WRITE) {
869                         /*
870                          * Private writable mapping: check memory availability
871                          */
872                         charged = len >> PAGE_SHIFT;
873                         if (security_vm_enough_memory(charged))
874                                 return -ENOMEM;
875                         vm_flags |= VM_ACCOUNT;
876                 }
877         }
878
879         /*
880          * Can we just expand an old private anonymous mapping?
881          * The VM_SHARED test is necessary because shmem_zero_setup
882          * will create the file object for a shared anonymous map below.
883          */
884         if (!file && !(vm_flags & VM_SHARED) &&
885             vma_merge(mm, prev, addr, addr + len, vm_flags,
886                                         NULL, NULL, pgoff, NULL))
887                 goto out;
888
889         /*
890          * Determine the object being mapped and call the appropriate
891          * specific mapper. the address has already been validated, but
892          * not unmapped, but the maps are removed from the list.
893          */
894         vma = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
895         if (!vma) {
896                 error = -ENOMEM;
897                 goto unacct_error;
898         }
899         memset(vma, 0, sizeof(*vma));
900
901         vma->vm_mm = mm;
902         vma->vm_start = addr;
903         vma->vm_end = addr + len;
904         vma->vm_flags = vm_flags;
905         vma->vm_page_prot = protection_map[vm_flags & 0x0f];
906         vma->vm_pgoff = pgoff;
907
908         if (file) {
909                 error = -EINVAL;
910                 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
911                         goto free_vma;
912                 if (vm_flags & VM_DENYWRITE) {
913                         error = deny_write_access(file);
914                         if (error)
915                                 goto free_vma;
916                         correct_wcount = 1;
917                 }
918                 vma->vm_file = file;
919                 get_file(file);
920                 error = file->f_op->mmap(file, vma);
921                 if (error)
922                         goto unmap_and_free_vma;
923         } else if (vm_flags & VM_SHARED) {
924                 error = shmem_zero_setup(vma);
925                 if (error)
926                         goto free_vma;
927         }
928
929         /* We set VM_ACCOUNT in a shared mapping's vm_flags, to inform
930          * shmem_zero_setup (perhaps called through /dev/zero's ->mmap)
931          * that memory reservation must be checked; but that reservation
932          * belongs to shared memory object, not to vma: so now clear it.
933          */
934         if ((vm_flags & (VM_SHARED|VM_ACCOUNT)) == (VM_SHARED|VM_ACCOUNT))
935                 vma->vm_flags &= ~VM_ACCOUNT;
936
937         /* Can addr have changed??
938          *
939          * Answer: Yes, several device drivers can do it in their
940          *         f_op->mmap method. -DaveM
941          */
942         addr = vma->vm_start;
943
944         if (!file || !vma_merge(mm, prev, addr, vma->vm_end,
945                         vma->vm_flags, NULL, file, pgoff, vma_policy(vma))) {
946                 vma_link(mm, vma, prev, rb_link, rb_parent);
947                 if (correct_wcount)
948                         atomic_inc(&inode->i_writecount);
949         } else {
950                 if (file) {
951                         if (correct_wcount)
952                                 atomic_inc(&inode->i_writecount);
953                         fput(file);
954                 }
955                 mpol_free(vma_policy(vma));
956                 kmem_cache_free(vm_area_cachep, vma);
957         }
958 out:    
959         // mm->total_vm += len >> PAGE_SHIFT;
960         vx_vmpages_add(mm, len >> PAGE_SHIFT);
961         if (vm_flags & VM_LOCKED) {
962                 // mm->locked_vm += len >> PAGE_SHIFT;
963                 vx_vmlocked_add(mm, len >> PAGE_SHIFT);
964                 make_pages_present(addr, addr + len);
965         }
966         if (flags & MAP_POPULATE) {
967                 up_write(&mm->mmap_sem);
968                 sys_remap_file_pages(addr, len, 0,
969                                         pgoff, flags & MAP_NONBLOCK);
970                 down_write(&mm->mmap_sem);
971         }
972         return addr;
973
974 unmap_and_free_vma:
975         if (correct_wcount)
976                 atomic_inc(&inode->i_writecount);
977         vma->vm_file = NULL;
978         fput(file);
979
980         /* Undo any partial mapping done by a device driver. */
981         zap_page_range(vma, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
982 free_vma:
983         kmem_cache_free(vm_area_cachep, vma);
984 unacct_error:
985         if (charged)
986                 vm_unacct_memory(charged);
987         return error;
988 }
989
990 EXPORT_SYMBOL(do_mmap_pgoff);
991
992 /* Get an address range which is currently unmapped.
993  * For shmat() with addr=0.
994  *
995  * Ugly calling convention alert:
996  * Return value with the low bits set means error value,
997  * ie
998  *      if (ret & ~PAGE_MASK)
999  *              error = ret;
1000  *
1001  * This function "knows" that -ENOMEM has the bits set.
1002  */
1003 #ifndef HAVE_ARCH_UNMAPPED_AREA
1004 static inline unsigned long
1005 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1006                 unsigned long len, unsigned long pgoff, unsigned long flags, unsigned long exec)
1007 {
1008         struct mm_struct *mm = current->mm;
1009         struct vm_area_struct *vma;
1010         unsigned long start_addr;
1011
1012         if (len > TASK_SIZE)
1013                 return -ENOMEM;
1014
1015         if (addr) {
1016                 addr = PAGE_ALIGN(addr);
1017                 vma = find_vma(mm, addr);
1018                 if (TASK_SIZE - len >= addr &&
1019                     (!vma || addr + len <= vma->vm_start))
1020                         return addr;
1021         }
1022         start_addr = addr = mm->free_area_cache;
1023
1024 full_search:
1025         for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
1026                 /* At this point:  (!vma || addr < vma->vm_end). */
1027                 if (TASK_SIZE - len < addr) {
1028                         /*
1029                          * Start a new search - just in case we missed
1030                          * some holes.
1031                          */
1032                         if (start_addr != TASK_UNMAPPED_BASE) {
1033                                 start_addr = addr = TASK_UNMAPPED_BASE;
1034                                 goto full_search;
1035                         }
1036                         return -ENOMEM;
1037                 }
1038                 if (!vma || addr + len <= vma->vm_start) {
1039                         /*
1040                          * Remember the place where we stopped the search:
1041                          */
1042                         mm->free_area_cache = addr + len;
1043                         return addr;
1044                 }
1045                 addr = vma->vm_end;
1046         }
1047 }
1048 #else
1049 extern unsigned long
1050 arch_get_unmapped_area(struct file *, unsigned long, unsigned long,
1051                         unsigned long, unsigned long, unsigned long);
1052 #endif  
1053
1054 unsigned long
1055 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1056                 unsigned long pgoff, unsigned long flags, unsigned long exec)
1057 {
1058         if (flags & MAP_FIXED) {
1059                 unsigned long ret;
1060
1061                 if (addr > TASK_SIZE - len)
1062                         return -ENOMEM;
1063                 if (addr & ~PAGE_MASK)
1064                         return -EINVAL;
1065                 if (file && is_file_hugepages(file))  {
1066                         /*
1067                          * Check if the given range is hugepage aligned, and
1068                          * can be made suitable for hugepages.
1069                          */
1070                         ret = prepare_hugepage_range(addr, len);
1071                 } else {
1072                         /*
1073                          * Ensure that a normal request is not falling in a
1074                          * reserved hugepage range.  For some archs like IA-64,
1075                          * there is a separate region for hugepages.
1076                          */
1077                         ret = is_hugepage_only_range(addr, len);
1078                 }
1079                 if (ret)
1080                         return -EINVAL;
1081                 return addr;
1082         }
1083
1084         if (file && file->f_op && file->f_op->get_unmapped_area)
1085                 return file->f_op->get_unmapped_area(file, addr, len,
1086                                                 pgoff, flags);
1087
1088         return arch_get_unmapped_area(file, addr, len, pgoff, flags, exec);
1089 }
1090
1091 EXPORT_SYMBOL(get_unmapped_area);
1092
1093 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
1094 struct vm_area_struct * find_vma(struct mm_struct * mm, unsigned long addr)
1095 {
1096         struct vm_area_struct *vma = NULL;
1097
1098         if (mm) {
1099                 /* Check the cache first. */
1100                 /* (Cache hit rate is typically around 35%.) */
1101                 vma = mm->mmap_cache;
1102                 if (!(vma && vma->vm_end > addr && vma->vm_start <= addr)) {
1103                         struct rb_node * rb_node;
1104
1105                         rb_node = mm->mm_rb.rb_node;
1106                         vma = NULL;
1107
1108                         while (rb_node) {
1109                                 struct vm_area_struct * vma_tmp;
1110
1111                                 vma_tmp = rb_entry(rb_node,
1112                                                 struct vm_area_struct, vm_rb);
1113
1114                                 if (vma_tmp->vm_end > addr) {
1115                                         vma = vma_tmp;
1116                                         if (vma_tmp->vm_start <= addr)
1117                                                 break;
1118                                         rb_node = rb_node->rb_left;
1119                                 } else
1120                                         rb_node = rb_node->rb_right;
1121                         }
1122                         if (vma)
1123                                 mm->mmap_cache = vma;
1124                 }
1125         }
1126         return vma;
1127 }
1128
1129 EXPORT_SYMBOL(find_vma);
1130
1131 /* Same as find_vma, but also return a pointer to the previous VMA in *pprev. */
1132 struct vm_area_struct *
1133 find_vma_prev(struct mm_struct *mm, unsigned long addr,
1134                         struct vm_area_struct **pprev)
1135 {
1136         struct vm_area_struct *vma = NULL, *prev = NULL;
1137         struct rb_node * rb_node;
1138         if (!mm)
1139                 goto out;
1140
1141         /* Guard against addr being lower than the first VMA */
1142         vma = mm->mmap;
1143
1144         /* Go through the RB tree quickly. */
1145         rb_node = mm->mm_rb.rb_node;
1146
1147         while (rb_node) {
1148                 struct vm_area_struct *vma_tmp;
1149                 vma_tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
1150
1151                 if (addr < vma_tmp->vm_end) {
1152                         rb_node = rb_node->rb_left;
1153                 } else {
1154                         prev = vma_tmp;
1155                         if (!prev->vm_next || (addr < prev->vm_next->vm_end))
1156                                 break;
1157                         rb_node = rb_node->rb_right;
1158                 }
1159         }
1160
1161 out:
1162         *pprev = prev;
1163         return prev ? prev->vm_next : vma;
1164 }
1165
1166
1167 static int over_stack_limit(unsigned long sz)
1168 {
1169         if (sz < EXEC_STACK_BIAS)
1170                 return 0;
1171         return (sz - EXEC_STACK_BIAS) > current->rlim[RLIMIT_STACK].rlim_cur;
1172 }
1173
1174 #ifdef CONFIG_STACK_GROWSUP
1175 /*
1176  * vma is the first one with address > vma->vm_end.  Have to extend vma.
1177  */
1178 int expand_stack(struct vm_area_struct * vma, unsigned long address)
1179 {
1180         unsigned long grow;
1181
1182         if (!(vma->vm_flags & VM_GROWSUP))
1183                 return -EFAULT;
1184
1185         /*
1186          * We must make sure the anon_vma is allocated
1187          * so that the anon_vma locking is not a noop.
1188          */
1189         if (unlikely(anon_vma_prepare(vma)))
1190                 return -ENOMEM;
1191         anon_vma_lock(vma);
1192
1193         /*
1194          * vma->vm_start/vm_end cannot change under us because the caller
1195          * is required to hold the mmap_sem in read mode.  We need the
1196          * anon_vma lock to serialize against concurrent expand_stacks.
1197          */
1198         address += 4 + PAGE_SIZE - 1;
1199         address &= PAGE_MASK;
1200         grow = (address - vma->vm_end) >> PAGE_SHIFT;
1201
1202         /* Overcommit.. */
1203         if (security_vm_enough_memory(grow) ||
1204                 !vx_vmpages_avail(vma->vm_mm, grow)) {
1205                 anon_vma_unlock(vma);
1206                 return -ENOMEM;
1207         }
1208         
1209         if (over_stack_limit(address - vma->vm_start) ||
1210                         ((vma->vm_mm->total_vm + grow) << PAGE_SHIFT) >
1211                         current->rlim[RLIMIT_AS].rlim_cur) {
1212                 anon_vma_unlock(vma);
1213                 vm_unacct_memory(grow);
1214                 return -ENOMEM;
1215         }
1216
1217         vma->vm_end = address;
1218         // vma->vm_mm->total_vm += grow;
1219         vx_vmpages_add(vma->vm_mm, grow);
1220         if (vma->vm_flags & VM_LOCKED)
1221                 // vma->vm_mm->locked_vm += grow;
1222                 vx_vmlocked_add(vma->vm_mm, grow);
1223         anon_vma_unlock(vma);
1224         return 0;
1225 }
1226
1227 struct vm_area_struct *
1228 find_extend_vma(struct mm_struct *mm, unsigned long addr)
1229 {
1230         struct vm_area_struct *vma, *prev;
1231
1232         addr &= PAGE_MASK;
1233         vma = find_vma_prev(mm, addr, &prev);
1234         if (vma && (vma->vm_start <= addr))
1235                 return vma;
1236         if (!prev || expand_stack(prev, addr))
1237                 return NULL;
1238         if (prev->vm_flags & VM_LOCKED) {
1239                 make_pages_present(addr, prev->vm_end);
1240         }
1241         return prev;
1242 }
1243 #else
1244 /*
1245  * vma is the first one with address < vma->vm_start.  Have to extend vma.
1246  */
1247 int expand_stack(struct vm_area_struct *vma, unsigned long address)
1248 {
1249         unsigned long grow;
1250
1251         /*
1252          * We must make sure the anon_vma is allocated
1253          * so that the anon_vma locking is not a noop.
1254          */
1255         if (unlikely(anon_vma_prepare(vma)))
1256                 return -ENOMEM;
1257         anon_vma_lock(vma);
1258
1259         /*
1260          * vma->vm_start/vm_end cannot change under us because the caller
1261          * is required to hold the mmap_sem in read mode.  We need the
1262          * anon_vma lock to serialize against concurrent expand_stacks.
1263          */
1264         address &= PAGE_MASK;
1265         grow = (vma->vm_start - address) >> PAGE_SHIFT;
1266
1267         /* Overcommit.. */
1268         if (security_vm_enough_memory(grow) ||
1269                 !vx_vmpages_avail(vma->vm_mm, grow)) {
1270                 anon_vma_unlock(vma);
1271                 return -ENOMEM;
1272         }
1273         
1274         if (over_stack_limit(vma->vm_end - address) ||
1275                         ((vma->vm_mm->total_vm + grow) << PAGE_SHIFT) >
1276                         current->rlim[RLIMIT_AS].rlim_cur) {
1277                 anon_vma_unlock(vma);
1278                 vm_unacct_memory(grow);
1279                 return -ENOMEM;
1280         }
1281
1282         vma->vm_start = address;
1283         vma->vm_pgoff -= grow;
1284         // vma->vm_mm->total_vm += grow;
1285         vx_vmpages_add(vma->vm_mm, grow);
1286         if (vma->vm_flags & VM_LOCKED)
1287                 // vma->vm_mm->locked_vm += grow;
1288                 vx_vmlocked_add(vma->vm_mm, grow);
1289         anon_vma_unlock(vma);
1290         return 0;
1291 }
1292
1293 struct vm_area_struct *
1294 find_extend_vma(struct mm_struct * mm, unsigned long addr)
1295 {
1296         struct vm_area_struct * vma;
1297         unsigned long start;
1298
1299         addr &= PAGE_MASK;
1300         vma = find_vma(mm,addr);
1301         if (!vma)
1302                 return NULL;
1303         if (vma->vm_start <= addr)
1304                 return vma;
1305         if (!(vma->vm_flags & VM_GROWSDOWN))
1306                 return NULL;
1307         start = vma->vm_start;
1308         if (expand_stack(vma, addr))
1309                 return NULL;
1310         if (vma->vm_flags & VM_LOCKED) {
1311                 make_pages_present(addr, start);
1312         }
1313         return vma;
1314 }
1315 #endif
1316
1317 /*
1318  * Try to free as many page directory entries as we can,
1319  * without having to work very hard at actually scanning
1320  * the page tables themselves.
1321  *
1322  * Right now we try to free page tables if we have a nice
1323  * PGDIR-aligned area that got free'd up. We could be more
1324  * granular if we want to, but this is fast and simple,
1325  * and covers the bad cases.
1326  *
1327  * "prev", if it exists, points to a vma before the one
1328  * we just free'd - but there's no telling how much before.
1329  */
1330 static void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *prev,
1331         unsigned long start, unsigned long end)
1332 {
1333         unsigned long first = start & PGDIR_MASK;
1334         unsigned long last = end + PGDIR_SIZE - 1;
1335         unsigned long start_index, end_index;
1336         struct mm_struct *mm = tlb->mm;
1337
1338         if (!prev) {
1339                 prev = mm->mmap;
1340                 if (!prev)
1341                         goto no_mmaps;
1342                 if (prev->vm_end > start) {
1343                         if (last > prev->vm_start)
1344                                 last = prev->vm_start;
1345                         goto no_mmaps;
1346                 }
1347         }
1348         for (;;) {
1349                 struct vm_area_struct *next = prev->vm_next;
1350
1351                 if (next) {
1352                         if (next->vm_start < start) {
1353                                 prev = next;
1354                                 continue;
1355                         }
1356                         if (last > next->vm_start)
1357                                 last = next->vm_start;
1358                 }
1359                 if (prev->vm_end > first)
1360                         first = prev->vm_end + PGDIR_SIZE - 1;
1361                 break;
1362         }
1363 no_mmaps:
1364         if (last < first)       /* for arches with discontiguous pgd indices */
1365                 return;
1366         /*
1367          * If the PGD bits are not consecutive in the virtual address, the
1368          * old method of shifting the VA >> by PGDIR_SHIFT doesn't work.
1369          */
1370         start_index = pgd_index(first);
1371         if (start_index < FIRST_USER_PGD_NR)
1372                 start_index = FIRST_USER_PGD_NR;
1373         end_index = pgd_index(last);
1374         if (end_index > start_index) {
1375                 clear_page_tables(tlb, start_index, end_index - start_index);
1376                 flush_tlb_pgtables(mm, first & PGDIR_MASK, last & PGDIR_MASK);
1377         }
1378 }
1379
1380 /* Normal function to fix up a mapping
1381  * This function is the default for when an area has no specific
1382  * function.  This may be used as part of a more specific routine.
1383  *
1384  * By the time this function is called, the area struct has been
1385  * removed from the process mapping list.
1386  */
1387 static void unmap_vma(struct mm_struct *mm, struct vm_area_struct *area)
1388 {
1389         size_t len = area->vm_end - area->vm_start;
1390         unsigned long old_end = area->vm_end;
1391
1392         // area->vm_mm->total_vm -= len >> PAGE_SHIFT;
1393         vx_vmpages_sub(area->vm_mm, len >> PAGE_SHIFT);
1394         
1395         if (area->vm_flags & VM_LOCKED)
1396                 // area->vm_mm->locked_vm -= len >> PAGE_SHIFT;
1397                 vx_vmlocked_sub(area->vm_mm, len >> PAGE_SHIFT);
1398         /*
1399          * Is this a new hole at the lowest possible address?
1400          */
1401         if (area->vm_start >= TASK_UNMAPPED_BASE &&
1402                                 area->vm_start < area->vm_mm->free_area_cache)
1403               area->vm_mm->free_area_cache = area->vm_start;
1404         /*
1405          * Is this a new hole at the highest possible address?
1406          */
1407         if (area->vm_start > area->vm_mm->non_executable_cache)
1408                 area->vm_mm->non_executable_cache = area->vm_start;
1409         remove_vm_struct(area);
1410         if (unlikely(area->vm_flags & VM_EXEC))
1411                 arch_remove_exec_range(mm, old_end);
1412 }
1413
1414 /*
1415  * Update the VMA and inode share lists.
1416  *
1417  * Ok - we have the memory areas we should free on the 'free' list,
1418  * so release them, and do the vma updates.
1419  */
1420 static void unmap_vma_list(struct mm_struct *mm,
1421         struct vm_area_struct *mpnt)
1422 {
1423         do {
1424                 struct vm_area_struct *next = mpnt->vm_next;
1425                 unmap_vma(mm, mpnt);
1426                 mpnt = next;
1427         } while (mpnt != NULL);
1428         validate_mm(mm);
1429 }
1430
1431 /*
1432  * Get rid of page table information in the indicated region.
1433  *
1434  * Called with the page table lock held.
1435  */
1436 static void unmap_region(struct mm_struct *mm,
1437         struct vm_area_struct *vma,
1438         struct vm_area_struct *prev,
1439         unsigned long start,
1440         unsigned long end)
1441 {
1442         struct mmu_gather *tlb;
1443         unsigned long nr_accounted = 0;
1444
1445         lru_add_drain();
1446         tlb = tlb_gather_mmu(mm, 0);
1447         unmap_vmas(&tlb, mm, vma, start, end, &nr_accounted, NULL);
1448         vm_unacct_memory(nr_accounted);
1449
1450         if (is_hugepage_only_range(start, end - start))
1451                 hugetlb_free_pgtables(tlb, prev, start, end);
1452         else
1453                 free_pgtables(tlb, prev, start, end);
1454         tlb_finish_mmu(tlb, start, end);
1455 }
1456
1457 /*
1458  * Create a list of vma's touched by the unmap, removing them from the mm's
1459  * vma list as we go..
1460  */
1461 static void
1462 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
1463         struct vm_area_struct *prev, unsigned long end)
1464 {
1465         struct vm_area_struct **insertion_point;
1466         struct vm_area_struct *tail_vma = NULL;
1467
1468         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
1469         do {
1470                 rb_erase(&vma->vm_rb, &mm->mm_rb);
1471                 mm->map_count--;
1472                 tail_vma = vma;
1473                 vma = vma->vm_next;
1474         } while (vma && vma->vm_start < end);
1475         *insertion_point = vma;
1476         tail_vma->vm_next = NULL;
1477         mm->mmap_cache = NULL;          /* Kill the cache. */
1478 }
1479
1480 /*
1481  * Split a vma into two pieces at address 'addr', a new vma is allocated
1482  * either for the first part or the the tail.
1483  */
1484 int split_vma(struct mm_struct * mm, struct vm_area_struct * vma,
1485               unsigned long addr, int new_below)
1486 {
1487         struct mempolicy *pol;
1488         struct vm_area_struct *new;
1489
1490         if (mm->map_count >= sysctl_max_map_count)
1491                 return -ENOMEM;
1492
1493         new = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
1494         if (!new)
1495                 return -ENOMEM;
1496
1497         /* most fields are the same, copy all, and then fixup */
1498         *new = *vma;
1499
1500         if (new_below)
1501                 new->vm_end = addr;
1502         else {
1503                 new->vm_start = addr;
1504                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
1505         }
1506
1507         pol = mpol_copy(vma_policy(vma));
1508         if (IS_ERR(pol)) {
1509                 kmem_cache_free(vm_area_cachep, new);
1510                 return PTR_ERR(pol);
1511         }
1512         vma_set_policy(new, pol);
1513
1514         if (new->vm_file)
1515                 get_file(new->vm_file);
1516
1517         if (new->vm_ops && new->vm_ops->open)
1518                 new->vm_ops->open(new);
1519
1520         if (new_below) {
1521                 unsigned long old_end = vma->vm_end;
1522
1523                 vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
1524                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
1525                 if (vma->vm_flags & VM_EXEC)
1526                         arch_remove_exec_range(mm, old_end);
1527         } else
1528                 vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
1529
1530         return 0;
1531 }
1532
1533 /* Munmap is split into 2 main parts -- this part which finds
1534  * what needs doing, and the areas themselves, which do the
1535  * work.  This now handles partial unmappings.
1536  * Jeremy Fitzhardinge <jeremy@goop.org>
1537  */
1538 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
1539 {
1540         unsigned long end;
1541         struct vm_area_struct *mpnt, *prev, *last;
1542
1543         if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
1544                 return -EINVAL;
1545
1546         if ((len = PAGE_ALIGN(len)) == 0)
1547                 return -EINVAL;
1548
1549         /* Find the first overlapping VMA */
1550         mpnt = find_vma_prev(mm, start, &prev);
1551         if (!mpnt)
1552                 return 0;
1553         /* we have  start < mpnt->vm_end  */
1554
1555         if (is_vm_hugetlb_page(mpnt)) {
1556                 int ret = is_aligned_hugepage_range(start, len);
1557
1558                 if (ret)
1559                         return ret;
1560         }
1561
1562         /* if it doesn't overlap, we have nothing.. */
1563         end = start + len;
1564         if (mpnt->vm_start >= end)
1565                 return 0;
1566
1567         /* Something will probably happen, so notify. */
1568         if (mpnt->vm_file && (mpnt->vm_flags & VM_EXEC))
1569                 profile_exec_unmap(mm);
1570  
1571         /*
1572          * If we need to split any vma, do it now to save pain later.
1573          *
1574          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
1575          * unmapped vm_area_struct will remain in use: so lower split_vma
1576          * places tmp vma above, and higher split_vma places tmp vma below.
1577          */
1578         if (start > mpnt->vm_start) {
1579                 if (split_vma(mm, mpnt, start, 0))
1580                         return -ENOMEM;
1581                 prev = mpnt;
1582         }
1583
1584         /* Does it split the last one? */
1585         last = find_vma(mm, end);
1586         if (last && end > last->vm_start) {
1587                 if (split_vma(mm, last, end, 1))
1588                         return -ENOMEM;
1589         }
1590         mpnt = prev? prev->vm_next: mm->mmap;
1591
1592         /*
1593          * Remove the vma's, and unmap the actual pages
1594          */
1595         detach_vmas_to_be_unmapped(mm, mpnt, prev, end);
1596         spin_lock(&mm->page_table_lock);
1597         unmap_region(mm, mpnt, prev, start, end);
1598         spin_unlock(&mm->page_table_lock);
1599
1600         /* Fix up all other VM information */
1601         unmap_vma_list(mm, mpnt);
1602
1603         return 0;
1604 }
1605
1606 EXPORT_SYMBOL(do_munmap);
1607
1608 asmlinkage long sys_munmap(unsigned long addr, size_t len)
1609 {
1610         int ret;
1611         struct mm_struct *mm = current->mm;
1612
1613         down_write(&mm->mmap_sem);
1614         ret = do_munmap(mm, addr, len);
1615         up_write(&mm->mmap_sem);
1616         return ret;
1617 }
1618
1619 /*
1620  *  this is really a simplified "do_mmap".  it only handles
1621  *  anonymous maps.  eventually we may be able to do some
1622  *  brk-specific accounting here.
1623  */
1624 unsigned long do_brk(unsigned long addr, unsigned long len)
1625 {
1626         struct mm_struct * mm = current->mm;
1627         struct vm_area_struct * vma, * prev;
1628         unsigned long flags;
1629         struct rb_node ** rb_link, * rb_parent;
1630         pgoff_t pgoff = addr >> PAGE_SHIFT;
1631
1632         len = PAGE_ALIGN(len);
1633         if (!len)
1634                 return addr;
1635
1636         if ((addr + len) > TASK_SIZE || (addr + len) < addr)
1637                 return -EINVAL;
1638
1639         /*
1640          * mlock MCL_FUTURE?
1641          */
1642         if (mm->def_flags & VM_LOCKED) {
1643                 unsigned long locked, lock_limit;
1644                 locked = mm->locked_vm << PAGE_SHIFT;
1645                 lock_limit = current->rlim[RLIMIT_MEMLOCK].rlim_cur;
1646                 locked += len;
1647                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1648                         return -EAGAIN;
1649                 /* vserver checks ? */
1650         }
1651
1652         /*
1653          * Clear old maps.  this also does some error checking for us
1654          */
1655  munmap_back:
1656         vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
1657         if (vma && vma->vm_start < addr + len) {
1658                 if (do_munmap(mm, addr, len))
1659                         return -ENOMEM;
1660                 goto munmap_back;
1661         }
1662
1663         /* Check against address space limits *after* clearing old maps... */
1664         if ((mm->total_vm << PAGE_SHIFT) + len
1665             > current->rlim[RLIMIT_AS].rlim_cur)
1666                 return -ENOMEM;
1667
1668         if (mm->map_count > sysctl_max_map_count)
1669                 return -ENOMEM;
1670
1671         if (security_vm_enough_memory(len >> PAGE_SHIFT) ||
1672                 !vx_vmpages_avail(mm, len >> PAGE_SHIFT))
1673                 return -ENOMEM;
1674
1675         flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
1676
1677         /* Can we just expand an old private anonymous mapping? */
1678         if (vma_merge(mm, prev, addr, addr + len, flags,
1679                                         NULL, NULL, pgoff, NULL))
1680                 goto out;
1681
1682         /*
1683          * create a vma struct for an anonymous mapping
1684          */
1685         vma = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
1686         if (!vma) {
1687                 vm_unacct_memory(len >> PAGE_SHIFT);
1688                 return -ENOMEM;
1689         }
1690         memset(vma, 0, sizeof(*vma));
1691
1692         vma->vm_mm = mm;
1693         vma->vm_start = addr;
1694         vma->vm_end = addr + len;
1695         vma->vm_pgoff = pgoff;
1696         vma->vm_flags = flags;
1697         vma->vm_page_prot = protection_map[flags & 0x0f];
1698         vma_link(mm, vma, prev, rb_link, rb_parent);
1699 out:
1700         // mm->total_vm += len >> PAGE_SHIFT;
1701         vx_vmpages_add(mm, len >> PAGE_SHIFT);
1702         if (flags & VM_LOCKED) {
1703                 // mm->locked_vm += len >> PAGE_SHIFT;
1704                 vx_vmlocked_add(mm, len >> PAGE_SHIFT);
1705                 make_pages_present(addr, addr + len);
1706         }
1707         return addr;
1708 }
1709
1710 EXPORT_SYMBOL(do_brk);
1711
1712 /* Release all mmaps. */
1713 void exit_mmap(struct mm_struct *mm)
1714 {
1715         struct mmu_gather *tlb;
1716         struct vm_area_struct *vma;
1717         unsigned long nr_accounted = 0;
1718
1719         profile_exit_mmap(mm);
1720  
1721         lru_add_drain();
1722
1723         spin_lock(&mm->page_table_lock);
1724
1725         tlb = tlb_gather_mmu(mm, 1);
1726         flush_cache_mm(mm);
1727         /* Use ~0UL here to ensure all VMAs in the mm are unmapped */
1728         mm->map_count -= unmap_vmas(&tlb, mm, mm->mmap, 0,
1729                                         ~0UL, &nr_accounted, NULL);
1730         vm_unacct_memory(nr_accounted);
1731         BUG_ON(mm->map_count);  /* This is just debugging */
1732         clear_page_tables(tlb, FIRST_USER_PGD_NR, USER_PTRS_PER_PGD);
1733         tlb_finish_mmu(tlb, 0, MM_VM_SIZE(mm));
1734
1735         vma = mm->mmap;
1736         mm->mmap = mm->mmap_cache = NULL;
1737         mm->mm_rb = RB_ROOT;
1738         // mm->rss = 0;
1739         vx_rsspages_sub(mm, mm->rss);
1740         // mm->total_vm = 0;
1741         vx_vmpages_sub(mm, mm->total_vm);
1742         // mm->locked_vm = 0;
1743         vx_vmlocked_sub(mm, mm->locked_vm);
1744         arch_flush_exec_range(mm);
1745
1746         spin_unlock(&mm->page_table_lock);
1747
1748         /*
1749          * Walk the list again, actually closing and freeing it
1750          * without holding any MM locks.
1751          */
1752         while (vma) {
1753                 struct vm_area_struct *next = vma->vm_next;
1754                 remove_vm_struct(vma);
1755                 vma = next;
1756         }
1757 }
1758
1759 /* Insert vm structure into process list sorted by address
1760  * and into the inode's i_mmap tree.  If vm_file is non-NULL
1761  * then i_mmap_lock is taken here.
1762  */
1763 void insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
1764 {
1765         struct vm_area_struct * __vma, * prev;
1766         struct rb_node ** rb_link, * rb_parent;
1767
1768         /*
1769          * The vm_pgoff of a purely anonymous vma should be irrelevant
1770          * until its first write fault, when page's anon_vma and index
1771          * are set.  But now set the vm_pgoff it will almost certainly
1772          * end up with (unless mremap moves it elsewhere before that
1773          * first wfault), so /proc/pid/maps tells a consistent story.
1774          *
1775          * By setting it to reflect the virtual start address of the
1776          * vma, merges and splits can happen in a seamless way, just
1777          * using the existing file pgoff checks and manipulations.
1778          * Similarly in do_mmap_pgoff and in do_brk.
1779          */
1780         if (!vma->vm_file) {
1781                 BUG_ON(vma->anon_vma);
1782                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
1783         }
1784         __vma = find_vma_prepare(mm,vma->vm_start,&prev,&rb_link,&rb_parent);
1785         if (__vma && __vma->vm_start < vma->vm_end)
1786                 BUG();
1787         vma_link(mm, vma, prev, rb_link, rb_parent);
1788 }
1789
1790 /*
1791  * Copy the vma structure to a new location in the same mm,
1792  * prior to moving page table entries, to effect an mremap move.
1793  */
1794 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1795         unsigned long addr, unsigned long len, pgoff_t pgoff)
1796 {
1797         struct vm_area_struct *vma = *vmap;
1798         unsigned long vma_start = vma->vm_start;
1799         struct mm_struct *mm = vma->vm_mm;
1800         struct vm_area_struct *new_vma, *prev;
1801         struct rb_node **rb_link, *rb_parent;
1802         struct mempolicy *pol;
1803
1804         /*
1805          * If anonymous vma has not yet been faulted, update new pgoff
1806          * to match new location, to increase its chance of merging.
1807          */
1808         if (!vma->vm_file && !vma->anon_vma)
1809                 pgoff = addr >> PAGE_SHIFT;
1810
1811         find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent);
1812         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
1813                         vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma));
1814         if (new_vma) {
1815                 /*
1816                  * Source vma may have been merged into new_vma
1817                  */
1818                 if (vma_start >= new_vma->vm_start &&
1819                     vma_start < new_vma->vm_end)
1820                         *vmap = new_vma;
1821         } else {
1822                 new_vma = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
1823                 if (new_vma) {
1824                         *new_vma = *vma;
1825                         pol = mpol_copy(vma_policy(vma));
1826                         if (IS_ERR(pol)) {
1827                                 kmem_cache_free(vm_area_cachep, new_vma);
1828                                 return NULL;
1829                         }
1830                         vma_set_policy(new_vma, pol);
1831                         new_vma->vm_start = addr;
1832                         new_vma->vm_end = addr + len;
1833                         new_vma->vm_pgoff = pgoff;
1834                         if (new_vma->vm_file)
1835                                 get_file(new_vma->vm_file);
1836                         if (new_vma->vm_ops && new_vma->vm_ops->open)
1837                                 new_vma->vm_ops->open(new_vma);
1838                         vma_link(mm, new_vma, prev, rb_link, rb_parent);
1839                 }
1840         }
1841         return new_vma;
1842 }