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