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