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