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