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