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