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