Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs-2.6
[pandora-kernel.git] / mm / nommu.c
1 /*
2  *  linux/mm/nommu.c
3  *
4  *  Replacement code for mm functions to support CPU's that don't
5  *  have any form of memory management unit (thus no virtual memory).
6  *
7  *  See Documentation/nommu-mmap.txt
8  *
9  *  Copyright (c) 2004-2008 David Howells <dhowells@redhat.com>
10  *  Copyright (c) 2000-2003 David McCullough <davidm@snapgear.com>
11  *  Copyright (c) 2000-2001 D Jeff Dionne <jeff@uClinux.org>
12  *  Copyright (c) 2002      Greg Ungerer <gerg@snapgear.com>
13  *  Copyright (c) 2007-2009 Paul Mundt <lethal@linux-sh.org>
14  */
15
16 #include <linux/module.h>
17 #include <linux/mm.h>
18 #include <linux/mman.h>
19 #include <linux/swap.h>
20 #include <linux/file.h>
21 #include <linux/highmem.h>
22 #include <linux/pagemap.h>
23 #include <linux/slab.h>
24 #include <linux/vmalloc.h>
25 #include <linux/tracehook.h>
26 #include <linux/blkdev.h>
27 #include <linux/backing-dev.h>
28 #include <linux/mount.h>
29 #include <linux/personality.h>
30 #include <linux/security.h>
31 #include <linux/syscalls.h>
32
33 #include <asm/uaccess.h>
34 #include <asm/tlb.h>
35 #include <asm/tlbflush.h>
36 #include <asm/mmu_context.h>
37 #include "internal.h"
38
39 #if 0
40 #define kenter(FMT, ...) \
41         printk(KERN_DEBUG "==> %s("FMT")\n", __func__, ##__VA_ARGS__)
42 #define kleave(FMT, ...) \
43         printk(KERN_DEBUG "<== %s()"FMT"\n", __func__, ##__VA_ARGS__)
44 #define kdebug(FMT, ...) \
45         printk(KERN_DEBUG "xxx" FMT"yyy\n", ##__VA_ARGS__)
46 #else
47 #define kenter(FMT, ...) \
48         no_printk(KERN_DEBUG "==> %s("FMT")\n", __func__, ##__VA_ARGS__)
49 #define kleave(FMT, ...) \
50         no_printk(KERN_DEBUG "<== %s()"FMT"\n", __func__, ##__VA_ARGS__)
51 #define kdebug(FMT, ...) \
52         no_printk(KERN_DEBUG FMT"\n", ##__VA_ARGS__)
53 #endif
54
55 void *high_memory;
56 struct page *mem_map;
57 unsigned long max_mapnr;
58 unsigned long num_physpages;
59 unsigned long highest_memmap_pfn;
60 struct percpu_counter vm_committed_as;
61 int sysctl_overcommit_memory = OVERCOMMIT_GUESS; /* heuristic overcommit */
62 int sysctl_overcommit_ratio = 50; /* default is 50% */
63 int sysctl_max_map_count = DEFAULT_MAX_MAP_COUNT;
64 int sysctl_nr_trim_pages = CONFIG_NOMMU_INITIAL_TRIM_EXCESS;
65 int heap_stack_gap = 0;
66
67 atomic_long_t mmap_pages_allocated;
68
69 EXPORT_SYMBOL(mem_map);
70 EXPORT_SYMBOL(num_physpages);
71
72 /* list of mapped, potentially shareable regions */
73 static struct kmem_cache *vm_region_jar;
74 struct rb_root nommu_region_tree = RB_ROOT;
75 DECLARE_RWSEM(nommu_region_sem);
76
77 const struct vm_operations_struct generic_file_vm_ops = {
78 };
79
80 /*
81  * Return the total memory allocated for this pointer, not
82  * just what the caller asked for.
83  *
84  * Doesn't have to be accurate, i.e. may have races.
85  */
86 unsigned int kobjsize(const void *objp)
87 {
88         struct page *page;
89
90         /*
91          * If the object we have should not have ksize performed on it,
92          * return size of 0
93          */
94         if (!objp || !virt_addr_valid(objp))
95                 return 0;
96
97         page = virt_to_head_page(objp);
98
99         /*
100          * If the allocator sets PageSlab, we know the pointer came from
101          * kmalloc().
102          */
103         if (PageSlab(page))
104                 return ksize(objp);
105
106         /*
107          * If it's not a compound page, see if we have a matching VMA
108          * region. This test is intentionally done in reverse order,
109          * so if there's no VMA, we still fall through and hand back
110          * PAGE_SIZE for 0-order pages.
111          */
112         if (!PageCompound(page)) {
113                 struct vm_area_struct *vma;
114
115                 vma = find_vma(current->mm, (unsigned long)objp);
116                 if (vma)
117                         return vma->vm_end - vma->vm_start;
118         }
119
120         /*
121          * The ksize() function is only guaranteed to work for pointers
122          * returned by kmalloc(). So handle arbitrary pointers here.
123          */
124         return PAGE_SIZE << compound_order(page);
125 }
126
127 int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
128                      unsigned long start, int nr_pages, unsigned int foll_flags,
129                      struct page **pages, struct vm_area_struct **vmas)
130 {
131         struct vm_area_struct *vma;
132         unsigned long vm_flags;
133         int i;
134
135         /* calculate required read or write permissions.
136          * If FOLL_FORCE is set, we only require the "MAY" flags.
137          */
138         vm_flags  = (foll_flags & FOLL_WRITE) ?
139                         (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
140         vm_flags &= (foll_flags & FOLL_FORCE) ?
141                         (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
142
143         for (i = 0; i < nr_pages; i++) {
144                 vma = find_vma(mm, start);
145                 if (!vma)
146                         goto finish_or_fault;
147
148                 /* protect what we can, including chardevs */
149                 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
150                     !(vm_flags & vma->vm_flags))
151                         goto finish_or_fault;
152
153                 if (pages) {
154                         pages[i] = virt_to_page(start);
155                         if (pages[i])
156                                 page_cache_get(pages[i]);
157                 }
158                 if (vmas)
159                         vmas[i] = vma;
160                 start = (start + PAGE_SIZE) & PAGE_MASK;
161         }
162
163         return i;
164
165 finish_or_fault:
166         return i ? : -EFAULT;
167 }
168
169 /*
170  * get a list of pages in an address range belonging to the specified process
171  * and indicate the VMA that covers each page
172  * - this is potentially dodgy as we may end incrementing the page count of a
173  *   slab page or a secondary page from a compound page
174  * - don't permit access to VMAs that don't support it, such as I/O mappings
175  */
176 int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
177         unsigned long start, int nr_pages, int write, int force,
178         struct page **pages, struct vm_area_struct **vmas)
179 {
180         int flags = 0;
181
182         if (write)
183                 flags |= FOLL_WRITE;
184         if (force)
185                 flags |= FOLL_FORCE;
186
187         return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas);
188 }
189 EXPORT_SYMBOL(get_user_pages);
190
191 /**
192  * follow_pfn - look up PFN at a user virtual address
193  * @vma: memory mapping
194  * @address: user virtual address
195  * @pfn: location to store found PFN
196  *
197  * Only IO mappings and raw PFN mappings are allowed.
198  *
199  * Returns zero and the pfn at @pfn on success, -ve otherwise.
200  */
201 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
202         unsigned long *pfn)
203 {
204         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
205                 return -EINVAL;
206
207         *pfn = address >> PAGE_SHIFT;
208         return 0;
209 }
210 EXPORT_SYMBOL(follow_pfn);
211
212 DEFINE_RWLOCK(vmlist_lock);
213 struct vm_struct *vmlist;
214
215 void vfree(const void *addr)
216 {
217         kfree(addr);
218 }
219 EXPORT_SYMBOL(vfree);
220
221 void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot)
222 {
223         /*
224          *  You can't specify __GFP_HIGHMEM with kmalloc() since kmalloc()
225          * returns only a logical address.
226          */
227         return kmalloc(size, (gfp_mask | __GFP_COMP) & ~__GFP_HIGHMEM);
228 }
229 EXPORT_SYMBOL(__vmalloc);
230
231 void *vmalloc_user(unsigned long size)
232 {
233         void *ret;
234
235         ret = __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO,
236                         PAGE_KERNEL);
237         if (ret) {
238                 struct vm_area_struct *vma;
239
240                 down_write(&current->mm->mmap_sem);
241                 vma = find_vma(current->mm, (unsigned long)ret);
242                 if (vma)
243                         vma->vm_flags |= VM_USERMAP;
244                 up_write(&current->mm->mmap_sem);
245         }
246
247         return ret;
248 }
249 EXPORT_SYMBOL(vmalloc_user);
250
251 struct page *vmalloc_to_page(const void *addr)
252 {
253         return virt_to_page(addr);
254 }
255 EXPORT_SYMBOL(vmalloc_to_page);
256
257 unsigned long vmalloc_to_pfn(const void *addr)
258 {
259         return page_to_pfn(virt_to_page(addr));
260 }
261 EXPORT_SYMBOL(vmalloc_to_pfn);
262
263 long vread(char *buf, char *addr, unsigned long count)
264 {
265         memcpy(buf, addr, count);
266         return count;
267 }
268
269 long vwrite(char *buf, char *addr, unsigned long count)
270 {
271         /* Don't allow overflow */
272         if ((unsigned long) addr + count < count)
273                 count = -(unsigned long) addr;
274
275         memcpy(addr, buf, count);
276         return(count);
277 }
278
279 /*
280  *      vmalloc  -  allocate virtually continguos memory
281  *
282  *      @size:          allocation size
283  *
284  *      Allocate enough pages to cover @size from the page level
285  *      allocator and map them into continguos kernel virtual space.
286  *
287  *      For tight control over page level allocator and protection flags
288  *      use __vmalloc() instead.
289  */
290 void *vmalloc(unsigned long size)
291 {
292        return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL);
293 }
294 EXPORT_SYMBOL(vmalloc);
295
296 /*
297  *      vzalloc - allocate virtually continguos memory with zero fill
298  *
299  *      @size:          allocation size
300  *
301  *      Allocate enough pages to cover @size from the page level
302  *      allocator and map them into continguos kernel virtual space.
303  *      The memory allocated is set to zero.
304  *
305  *      For tight control over page level allocator and protection flags
306  *      use __vmalloc() instead.
307  */
308 void *vzalloc(unsigned long size)
309 {
310         return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO,
311                         PAGE_KERNEL);
312 }
313 EXPORT_SYMBOL(vzalloc);
314
315 /**
316  * vmalloc_node - allocate memory on a specific node
317  * @size:       allocation size
318  * @node:       numa node
319  *
320  * Allocate enough pages to cover @size from the page level
321  * allocator and map them into contiguous kernel virtual space.
322  *
323  * For tight control over page level allocator and protection flags
324  * use __vmalloc() instead.
325  */
326 void *vmalloc_node(unsigned long size, int node)
327 {
328         return vmalloc(size);
329 }
330
331 /**
332  * vzalloc_node - allocate memory on a specific node with zero fill
333  * @size:       allocation size
334  * @node:       numa node
335  *
336  * Allocate enough pages to cover @size from the page level
337  * allocator and map them into contiguous kernel virtual space.
338  * The memory allocated is set to zero.
339  *
340  * For tight control over page level allocator and protection flags
341  * use __vmalloc() instead.
342  */
343 void *vzalloc_node(unsigned long size, int node)
344 {
345         return vzalloc(size);
346 }
347 EXPORT_SYMBOL(vzalloc_node);
348
349 #ifndef PAGE_KERNEL_EXEC
350 # define PAGE_KERNEL_EXEC PAGE_KERNEL
351 #endif
352
353 /**
354  *      vmalloc_exec  -  allocate virtually contiguous, executable memory
355  *      @size:          allocation size
356  *
357  *      Kernel-internal function to allocate enough pages to cover @size
358  *      the page level allocator and map them into contiguous and
359  *      executable kernel virtual space.
360  *
361  *      For tight control over page level allocator and protection flags
362  *      use __vmalloc() instead.
363  */
364
365 void *vmalloc_exec(unsigned long size)
366 {
367         return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL_EXEC);
368 }
369
370 /**
371  * vmalloc_32  -  allocate virtually contiguous memory (32bit addressable)
372  *      @size:          allocation size
373  *
374  *      Allocate enough 32bit PA addressable pages to cover @size from the
375  *      page level allocator and map them into continguos kernel virtual space.
376  */
377 void *vmalloc_32(unsigned long size)
378 {
379         return __vmalloc(size, GFP_KERNEL, PAGE_KERNEL);
380 }
381 EXPORT_SYMBOL(vmalloc_32);
382
383 /**
384  * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
385  *      @size:          allocation size
386  *
387  * The resulting memory area is 32bit addressable and zeroed so it can be
388  * mapped to userspace without leaking data.
389  *
390  * VM_USERMAP is set on the corresponding VMA so that subsequent calls to
391  * remap_vmalloc_range() are permissible.
392  */
393 void *vmalloc_32_user(unsigned long size)
394 {
395         /*
396          * We'll have to sort out the ZONE_DMA bits for 64-bit,
397          * but for now this can simply use vmalloc_user() directly.
398          */
399         return vmalloc_user(size);
400 }
401 EXPORT_SYMBOL(vmalloc_32_user);
402
403 void *vmap(struct page **pages, unsigned int count, unsigned long flags, pgprot_t prot)
404 {
405         BUG();
406         return NULL;
407 }
408 EXPORT_SYMBOL(vmap);
409
410 void vunmap(const void *addr)
411 {
412         BUG();
413 }
414 EXPORT_SYMBOL(vunmap);
415
416 void *vm_map_ram(struct page **pages, unsigned int count, int node, pgprot_t prot)
417 {
418         BUG();
419         return NULL;
420 }
421 EXPORT_SYMBOL(vm_map_ram);
422
423 void vm_unmap_ram(const void *mem, unsigned int count)
424 {
425         BUG();
426 }
427 EXPORT_SYMBOL(vm_unmap_ram);
428
429 void vm_unmap_aliases(void)
430 {
431 }
432 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
433
434 /*
435  * Implement a stub for vmalloc_sync_all() if the architecture chose not to
436  * have one.
437  */
438 void  __attribute__((weak)) vmalloc_sync_all(void)
439 {
440 }
441
442 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
443                    struct page *page)
444 {
445         return -EINVAL;
446 }
447 EXPORT_SYMBOL(vm_insert_page);
448
449 /*
450  *  sys_brk() for the most part doesn't need the global kernel
451  *  lock, except when an application is doing something nasty
452  *  like trying to un-brk an area that has already been mapped
453  *  to a regular file.  in this case, the unmapping will need
454  *  to invoke file system routines that need the global lock.
455  */
456 SYSCALL_DEFINE1(brk, unsigned long, brk)
457 {
458         struct mm_struct *mm = current->mm;
459
460         if (brk < mm->start_brk || brk > mm->context.end_brk)
461                 return mm->brk;
462
463         if (mm->brk == brk)
464                 return mm->brk;
465
466         /*
467          * Always allow shrinking brk
468          */
469         if (brk <= mm->brk) {
470                 mm->brk = brk;
471                 return brk;
472         }
473
474         /*
475          * Ok, looks good - let it rip.
476          */
477         flush_icache_range(mm->brk, brk);
478         return mm->brk = brk;
479 }
480
481 /*
482  * initialise the VMA and region record slabs
483  */
484 void __init mmap_init(void)
485 {
486         int ret;
487
488         ret = percpu_counter_init(&vm_committed_as, 0);
489         VM_BUG_ON(ret);
490         vm_region_jar = KMEM_CACHE(vm_region, SLAB_PANIC);
491 }
492
493 /*
494  * validate the region tree
495  * - the caller must hold the region lock
496  */
497 #ifdef CONFIG_DEBUG_NOMMU_REGIONS
498 static noinline void validate_nommu_regions(void)
499 {
500         struct vm_region *region, *last;
501         struct rb_node *p, *lastp;
502
503         lastp = rb_first(&nommu_region_tree);
504         if (!lastp)
505                 return;
506
507         last = rb_entry(lastp, struct vm_region, vm_rb);
508         BUG_ON(unlikely(last->vm_end <= last->vm_start));
509         BUG_ON(unlikely(last->vm_top < last->vm_end));
510
511         while ((p = rb_next(lastp))) {
512                 region = rb_entry(p, struct vm_region, vm_rb);
513                 last = rb_entry(lastp, struct vm_region, vm_rb);
514
515                 BUG_ON(unlikely(region->vm_end <= region->vm_start));
516                 BUG_ON(unlikely(region->vm_top < region->vm_end));
517                 BUG_ON(unlikely(region->vm_start < last->vm_top));
518
519                 lastp = p;
520         }
521 }
522 #else
523 static void validate_nommu_regions(void)
524 {
525 }
526 #endif
527
528 /*
529  * add a region into the global tree
530  */
531 static void add_nommu_region(struct vm_region *region)
532 {
533         struct vm_region *pregion;
534         struct rb_node **p, *parent;
535
536         validate_nommu_regions();
537
538         parent = NULL;
539         p = &nommu_region_tree.rb_node;
540         while (*p) {
541                 parent = *p;
542                 pregion = rb_entry(parent, struct vm_region, vm_rb);
543                 if (region->vm_start < pregion->vm_start)
544                         p = &(*p)->rb_left;
545                 else if (region->vm_start > pregion->vm_start)
546                         p = &(*p)->rb_right;
547                 else if (pregion == region)
548                         return;
549                 else
550                         BUG();
551         }
552
553         rb_link_node(&region->vm_rb, parent, p);
554         rb_insert_color(&region->vm_rb, &nommu_region_tree);
555
556         validate_nommu_regions();
557 }
558
559 /*
560  * delete a region from the global tree
561  */
562 static void delete_nommu_region(struct vm_region *region)
563 {
564         BUG_ON(!nommu_region_tree.rb_node);
565
566         validate_nommu_regions();
567         rb_erase(&region->vm_rb, &nommu_region_tree);
568         validate_nommu_regions();
569 }
570
571 /*
572  * free a contiguous series of pages
573  */
574 static void free_page_series(unsigned long from, unsigned long to)
575 {
576         for (; from < to; from += PAGE_SIZE) {
577                 struct page *page = virt_to_page(from);
578
579                 kdebug("- free %lx", from);
580                 atomic_long_dec(&mmap_pages_allocated);
581                 if (page_count(page) != 1)
582                         kdebug("free page %p: refcount not one: %d",
583                                page, page_count(page));
584                 put_page(page);
585         }
586 }
587
588 /*
589  * release a reference to a region
590  * - the caller must hold the region semaphore for writing, which this releases
591  * - the region may not have been added to the tree yet, in which case vm_top
592  *   will equal vm_start
593  */
594 static void __put_nommu_region(struct vm_region *region)
595         __releases(nommu_region_sem)
596 {
597         kenter("%p{%d}", region, region->vm_usage);
598
599         BUG_ON(!nommu_region_tree.rb_node);
600
601         if (--region->vm_usage == 0) {
602                 if (region->vm_top > region->vm_start)
603                         delete_nommu_region(region);
604                 up_write(&nommu_region_sem);
605
606                 if (region->vm_file)
607                         fput(region->vm_file);
608
609                 /* IO memory and memory shared directly out of the pagecache
610                  * from ramfs/tmpfs mustn't be released here */
611                 if (region->vm_flags & VM_MAPPED_COPY) {
612                         kdebug("free series");
613                         free_page_series(region->vm_start, region->vm_top);
614                 }
615                 kmem_cache_free(vm_region_jar, region);
616         } else {
617                 up_write(&nommu_region_sem);
618         }
619 }
620
621 /*
622  * release a reference to a region
623  */
624 static void put_nommu_region(struct vm_region *region)
625 {
626         down_write(&nommu_region_sem);
627         __put_nommu_region(region);
628 }
629
630 /*
631  * update protection on a vma
632  */
633 static void protect_vma(struct vm_area_struct *vma, unsigned long flags)
634 {
635 #ifdef CONFIG_MPU
636         struct mm_struct *mm = vma->vm_mm;
637         long start = vma->vm_start & PAGE_MASK;
638         while (start < vma->vm_end) {
639                 protect_page(mm, start, flags);
640                 start += PAGE_SIZE;
641         }
642         update_protections(mm);
643 #endif
644 }
645
646 /*
647  * add a VMA into a process's mm_struct in the appropriate place in the list
648  * and tree and add to the address space's page tree also if not an anonymous
649  * page
650  * - should be called with mm->mmap_sem held writelocked
651  */
652 static void add_vma_to_mm(struct mm_struct *mm, struct vm_area_struct *vma)
653 {
654         struct vm_area_struct *pvma, **pp, *next;
655         struct address_space *mapping;
656         struct rb_node **p, *parent;
657
658         kenter(",%p", vma);
659
660         BUG_ON(!vma->vm_region);
661
662         mm->map_count++;
663         vma->vm_mm = mm;
664
665         protect_vma(vma, vma->vm_flags);
666
667         /* add the VMA to the mapping */
668         if (vma->vm_file) {
669                 mapping = vma->vm_file->f_mapping;
670
671                 flush_dcache_mmap_lock(mapping);
672                 vma_prio_tree_insert(vma, &mapping->i_mmap);
673                 flush_dcache_mmap_unlock(mapping);
674         }
675
676         /* add the VMA to the tree */
677         parent = NULL;
678         p = &mm->mm_rb.rb_node;
679         while (*p) {
680                 parent = *p;
681                 pvma = rb_entry(parent, struct vm_area_struct, vm_rb);
682
683                 /* sort by: start addr, end addr, VMA struct addr in that order
684                  * (the latter is necessary as we may get identical VMAs) */
685                 if (vma->vm_start < pvma->vm_start)
686                         p = &(*p)->rb_left;
687                 else if (vma->vm_start > pvma->vm_start)
688                         p = &(*p)->rb_right;
689                 else if (vma->vm_end < pvma->vm_end)
690                         p = &(*p)->rb_left;
691                 else if (vma->vm_end > pvma->vm_end)
692                         p = &(*p)->rb_right;
693                 else if (vma < pvma)
694                         p = &(*p)->rb_left;
695                 else if (vma > pvma)
696                         p = &(*p)->rb_right;
697                 else
698                         BUG();
699         }
700
701         rb_link_node(&vma->vm_rb, parent, p);
702         rb_insert_color(&vma->vm_rb, &mm->mm_rb);
703
704         /* add VMA to the VMA list also */
705         for (pp = &mm->mmap; (pvma = *pp); pp = &(*pp)->vm_next) {
706                 if (pvma->vm_start > vma->vm_start)
707                         break;
708                 if (pvma->vm_start < vma->vm_start)
709                         continue;
710                 if (pvma->vm_end < vma->vm_end)
711                         break;
712         }
713
714         next = *pp;
715         *pp = vma;
716         vma->vm_next = next;
717         if (next)
718                 next->vm_prev = vma;
719 }
720
721 /*
722  * delete a VMA from its owning mm_struct and address space
723  */
724 static void delete_vma_from_mm(struct vm_area_struct *vma)
725 {
726         struct vm_area_struct **pp;
727         struct address_space *mapping;
728         struct mm_struct *mm = vma->vm_mm;
729
730         kenter("%p", vma);
731
732         protect_vma(vma, 0);
733
734         mm->map_count--;
735         if (mm->mmap_cache == vma)
736                 mm->mmap_cache = NULL;
737
738         /* remove the VMA from the mapping */
739         if (vma->vm_file) {
740                 mapping = vma->vm_file->f_mapping;
741
742                 flush_dcache_mmap_lock(mapping);
743                 vma_prio_tree_remove(vma, &mapping->i_mmap);
744                 flush_dcache_mmap_unlock(mapping);
745         }
746
747         /* remove from the MM's tree and list */
748         rb_erase(&vma->vm_rb, &mm->mm_rb);
749         for (pp = &mm->mmap; *pp; pp = &(*pp)->vm_next) {
750                 if (*pp == vma) {
751                         *pp = vma->vm_next;
752                         break;
753                 }
754         }
755
756         vma->vm_mm = NULL;
757 }
758
759 /*
760  * destroy a VMA record
761  */
762 static void delete_vma(struct mm_struct *mm, struct vm_area_struct *vma)
763 {
764         kenter("%p", vma);
765         if (vma->vm_ops && vma->vm_ops->close)
766                 vma->vm_ops->close(vma);
767         if (vma->vm_file) {
768                 fput(vma->vm_file);
769                 if (vma->vm_flags & VM_EXECUTABLE)
770                         removed_exe_file_vma(mm);
771         }
772         put_nommu_region(vma->vm_region);
773         kmem_cache_free(vm_area_cachep, vma);
774 }
775
776 /*
777  * look up the first VMA in which addr resides, NULL if none
778  * - should be called with mm->mmap_sem at least held readlocked
779  */
780 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
781 {
782         struct vm_area_struct *vma;
783         struct rb_node *n = mm->mm_rb.rb_node;
784
785         /* check the cache first */
786         vma = mm->mmap_cache;
787         if (vma && vma->vm_start <= addr && vma->vm_end > addr)
788                 return vma;
789
790         /* trawl the tree (there may be multiple mappings in which addr
791          * resides) */
792         for (n = rb_first(&mm->mm_rb); n; n = rb_next(n)) {
793                 vma = rb_entry(n, struct vm_area_struct, vm_rb);
794                 if (vma->vm_start > addr)
795                         return NULL;
796                 if (vma->vm_end > addr) {
797                         mm->mmap_cache = vma;
798                         return vma;
799                 }
800         }
801
802         return NULL;
803 }
804 EXPORT_SYMBOL(find_vma);
805
806 /*
807  * find a VMA
808  * - we don't extend stack VMAs under NOMMU conditions
809  */
810 struct vm_area_struct *find_extend_vma(struct mm_struct *mm, unsigned long addr)
811 {
812         return find_vma(mm, addr);
813 }
814
815 /*
816  * expand a stack to a given address
817  * - not supported under NOMMU conditions
818  */
819 int expand_stack(struct vm_area_struct *vma, unsigned long address)
820 {
821         return -ENOMEM;
822 }
823
824 /*
825  * look up the first VMA exactly that exactly matches addr
826  * - should be called with mm->mmap_sem at least held readlocked
827  */
828 static struct vm_area_struct *find_vma_exact(struct mm_struct *mm,
829                                              unsigned long addr,
830                                              unsigned long len)
831 {
832         struct vm_area_struct *vma;
833         struct rb_node *n = mm->mm_rb.rb_node;
834         unsigned long end = addr + len;
835
836         /* check the cache first */
837         vma = mm->mmap_cache;
838         if (vma && vma->vm_start == addr && vma->vm_end == end)
839                 return vma;
840
841         /* trawl the tree (there may be multiple mappings in which addr
842          * resides) */
843         for (n = rb_first(&mm->mm_rb); n; n = rb_next(n)) {
844                 vma = rb_entry(n, struct vm_area_struct, vm_rb);
845                 if (vma->vm_start < addr)
846                         continue;
847                 if (vma->vm_start > addr)
848                         return NULL;
849                 if (vma->vm_end == end) {
850                         mm->mmap_cache = vma;
851                         return vma;
852                 }
853         }
854
855         return NULL;
856 }
857
858 /*
859  * determine whether a mapping should be permitted and, if so, what sort of
860  * mapping we're capable of supporting
861  */
862 static int validate_mmap_request(struct file *file,
863                                  unsigned long addr,
864                                  unsigned long len,
865                                  unsigned long prot,
866                                  unsigned long flags,
867                                  unsigned long pgoff,
868                                  unsigned long *_capabilities)
869 {
870         unsigned long capabilities, rlen;
871         unsigned long reqprot = prot;
872         int ret;
873
874         /* do the simple checks first */
875         if (flags & MAP_FIXED) {
876                 printk(KERN_DEBUG
877                        "%d: Can't do fixed-address/overlay mmap of RAM\n",
878                        current->pid);
879                 return -EINVAL;
880         }
881
882         if ((flags & MAP_TYPE) != MAP_PRIVATE &&
883             (flags & MAP_TYPE) != MAP_SHARED)
884                 return -EINVAL;
885
886         if (!len)
887                 return -EINVAL;
888
889         /* Careful about overflows.. */
890         rlen = PAGE_ALIGN(len);
891         if (!rlen || rlen > TASK_SIZE)
892                 return -ENOMEM;
893
894         /* offset overflow? */
895         if ((pgoff + (rlen >> PAGE_SHIFT)) < pgoff)
896                 return -EOVERFLOW;
897
898         if (file) {
899                 /* validate file mapping requests */
900                 struct address_space *mapping;
901
902                 /* files must support mmap */
903                 if (!file->f_op || !file->f_op->mmap)
904                         return -ENODEV;
905
906                 /* work out if what we've got could possibly be shared
907                  * - we support chardevs that provide their own "memory"
908                  * - we support files/blockdevs that are memory backed
909                  */
910                 mapping = file->f_mapping;
911                 if (!mapping)
912                         mapping = file->f_path.dentry->d_inode->i_mapping;
913
914                 capabilities = 0;
915                 if (mapping && mapping->backing_dev_info)
916                         capabilities = mapping->backing_dev_info->capabilities;
917
918                 if (!capabilities) {
919                         /* no explicit capabilities set, so assume some
920                          * defaults */
921                         switch (file->f_path.dentry->d_inode->i_mode & S_IFMT) {
922                         case S_IFREG:
923                         case S_IFBLK:
924                                 capabilities = BDI_CAP_MAP_COPY;
925                                 break;
926
927                         case S_IFCHR:
928                                 capabilities =
929                                         BDI_CAP_MAP_DIRECT |
930                                         BDI_CAP_READ_MAP |
931                                         BDI_CAP_WRITE_MAP;
932                                 break;
933
934                         default:
935                                 return -EINVAL;
936                         }
937                 }
938
939                 /* eliminate any capabilities that we can't support on this
940                  * device */
941                 if (!file->f_op->get_unmapped_area)
942                         capabilities &= ~BDI_CAP_MAP_DIRECT;
943                 if (!file->f_op->read)
944                         capabilities &= ~BDI_CAP_MAP_COPY;
945
946                 /* The file shall have been opened with read permission. */
947                 if (!(file->f_mode & FMODE_READ))
948                         return -EACCES;
949
950                 if (flags & MAP_SHARED) {
951                         /* do checks for writing, appending and locking */
952                         if ((prot & PROT_WRITE) &&
953                             !(file->f_mode & FMODE_WRITE))
954                                 return -EACCES;
955
956                         if (IS_APPEND(file->f_path.dentry->d_inode) &&
957                             (file->f_mode & FMODE_WRITE))
958                                 return -EACCES;
959
960                         if (locks_verify_locked(file->f_path.dentry->d_inode))
961                                 return -EAGAIN;
962
963                         if (!(capabilities & BDI_CAP_MAP_DIRECT))
964                                 return -ENODEV;
965
966                         /* we mustn't privatise shared mappings */
967                         capabilities &= ~BDI_CAP_MAP_COPY;
968                 }
969                 else {
970                         /* we're going to read the file into private memory we
971                          * allocate */
972                         if (!(capabilities & BDI_CAP_MAP_COPY))
973                                 return -ENODEV;
974
975                         /* we don't permit a private writable mapping to be
976                          * shared with the backing device */
977                         if (prot & PROT_WRITE)
978                                 capabilities &= ~BDI_CAP_MAP_DIRECT;
979                 }
980
981                 if (capabilities & BDI_CAP_MAP_DIRECT) {
982                         if (((prot & PROT_READ)  && !(capabilities & BDI_CAP_READ_MAP))  ||
983                             ((prot & PROT_WRITE) && !(capabilities & BDI_CAP_WRITE_MAP)) ||
984                             ((prot & PROT_EXEC)  && !(capabilities & BDI_CAP_EXEC_MAP))
985                             ) {
986                                 capabilities &= ~BDI_CAP_MAP_DIRECT;
987                                 if (flags & MAP_SHARED) {
988                                         printk(KERN_WARNING
989                                                "MAP_SHARED not completely supported on !MMU\n");
990                                         return -EINVAL;
991                                 }
992                         }
993                 }
994
995                 /* handle executable mappings and implied executable
996                  * mappings */
997                 if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
998                         if (prot & PROT_EXEC)
999                                 return -EPERM;
1000                 }
1001                 else if ((prot & PROT_READ) && !(prot & PROT_EXEC)) {
1002                         /* handle implication of PROT_EXEC by PROT_READ */
1003                         if (current->personality & READ_IMPLIES_EXEC) {
1004                                 if (capabilities & BDI_CAP_EXEC_MAP)
1005                                         prot |= PROT_EXEC;
1006                         }
1007                 }
1008                 else if ((prot & PROT_READ) &&
1009                          (prot & PROT_EXEC) &&
1010                          !(capabilities & BDI_CAP_EXEC_MAP)
1011                          ) {
1012                         /* backing file is not executable, try to copy */
1013                         capabilities &= ~BDI_CAP_MAP_DIRECT;
1014                 }
1015         }
1016         else {
1017                 /* anonymous mappings are always memory backed and can be
1018                  * privately mapped
1019                  */
1020                 capabilities = BDI_CAP_MAP_COPY;
1021
1022                 /* handle PROT_EXEC implication by PROT_READ */
1023                 if ((prot & PROT_READ) &&
1024                     (current->personality & READ_IMPLIES_EXEC))
1025                         prot |= PROT_EXEC;
1026         }
1027
1028         /* allow the security API to have its say */
1029         ret = security_file_mmap(file, reqprot, prot, flags, addr, 0);
1030         if (ret < 0)
1031                 return ret;
1032
1033         /* looks okay */
1034         *_capabilities = capabilities;
1035         return 0;
1036 }
1037
1038 /*
1039  * we've determined that we can make the mapping, now translate what we
1040  * now know into VMA flags
1041  */
1042 static unsigned long determine_vm_flags(struct file *file,
1043                                         unsigned long prot,
1044                                         unsigned long flags,
1045                                         unsigned long capabilities)
1046 {
1047         unsigned long vm_flags;
1048
1049         vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags);
1050         /* vm_flags |= mm->def_flags; */
1051
1052         if (!(capabilities & BDI_CAP_MAP_DIRECT)) {
1053                 /* attempt to share read-only copies of mapped file chunks */
1054                 vm_flags |= VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1055                 if (file && !(prot & PROT_WRITE))
1056                         vm_flags |= VM_MAYSHARE;
1057         } else {
1058                 /* overlay a shareable mapping on the backing device or inode
1059                  * if possible - used for chardevs, ramfs/tmpfs/shmfs and
1060                  * romfs/cramfs */
1061                 vm_flags |= VM_MAYSHARE | (capabilities & BDI_CAP_VMFLAGS);
1062                 if (flags & MAP_SHARED)
1063                         vm_flags |= VM_SHARED;
1064         }
1065
1066         /* refuse to let anyone share private mappings with this process if
1067          * it's being traced - otherwise breakpoints set in it may interfere
1068          * with another untraced process
1069          */
1070         if ((flags & MAP_PRIVATE) && tracehook_expect_breakpoints(current))
1071                 vm_flags &= ~VM_MAYSHARE;
1072
1073         return vm_flags;
1074 }
1075
1076 /*
1077  * set up a shared mapping on a file (the driver or filesystem provides and
1078  * pins the storage)
1079  */
1080 static int do_mmap_shared_file(struct vm_area_struct *vma)
1081 {
1082         int ret;
1083
1084         ret = vma->vm_file->f_op->mmap(vma->vm_file, vma);
1085         if (ret == 0) {
1086                 vma->vm_region->vm_top = vma->vm_region->vm_end;
1087                 return 0;
1088         }
1089         if (ret != -ENOSYS)
1090                 return ret;
1091
1092         /* getting -ENOSYS indicates that direct mmap isn't possible (as
1093          * opposed to tried but failed) so we can only give a suitable error as
1094          * it's not possible to make a private copy if MAP_SHARED was given */
1095         return -ENODEV;
1096 }
1097
1098 /*
1099  * set up a private mapping or an anonymous shared mapping
1100  */
1101 static int do_mmap_private(struct vm_area_struct *vma,
1102                            struct vm_region *region,
1103                            unsigned long len,
1104                            unsigned long capabilities)
1105 {
1106         struct page *pages;
1107         unsigned long total, point, n, rlen;
1108         void *base;
1109         int ret, order;
1110
1111         /* invoke the file's mapping function so that it can keep track of
1112          * shared mappings on devices or memory
1113          * - VM_MAYSHARE will be set if it may attempt to share
1114          */
1115         if (capabilities & BDI_CAP_MAP_DIRECT) {
1116                 ret = vma->vm_file->f_op->mmap(vma->vm_file, vma);
1117                 if (ret == 0) {
1118                         /* shouldn't return success if we're not sharing */
1119                         BUG_ON(!(vma->vm_flags & VM_MAYSHARE));
1120                         vma->vm_region->vm_top = vma->vm_region->vm_end;
1121                         return 0;
1122                 }
1123                 if (ret != -ENOSYS)
1124                         return ret;
1125
1126                 /* getting an ENOSYS error indicates that direct mmap isn't
1127                  * possible (as opposed to tried but failed) so we'll try to
1128                  * make a private copy of the data and map that instead */
1129         }
1130
1131         rlen = PAGE_ALIGN(len);
1132
1133         /* allocate some memory to hold the mapping
1134          * - note that this may not return a page-aligned address if the object
1135          *   we're allocating is smaller than a page
1136          */
1137         order = get_order(rlen);
1138         kdebug("alloc order %d for %lx", order, len);
1139
1140         pages = alloc_pages(GFP_KERNEL, order);
1141         if (!pages)
1142                 goto enomem;
1143
1144         total = 1 << order;
1145         atomic_long_add(total, &mmap_pages_allocated);
1146
1147         point = rlen >> PAGE_SHIFT;
1148
1149         /* we allocated a power-of-2 sized page set, so we may want to trim off
1150          * the excess */
1151         if (sysctl_nr_trim_pages && total - point >= sysctl_nr_trim_pages) {
1152                 while (total > point) {
1153                         order = ilog2(total - point);
1154                         n = 1 << order;
1155                         kdebug("shave %lu/%lu @%lu", n, total - point, total);
1156                         atomic_long_sub(n, &mmap_pages_allocated);
1157                         total -= n;
1158                         set_page_refcounted(pages + total);
1159                         __free_pages(pages + total, order);
1160                 }
1161         }
1162
1163         for (point = 1; point < total; point++)
1164                 set_page_refcounted(&pages[point]);
1165
1166         base = page_address(pages);
1167         region->vm_flags = vma->vm_flags |= VM_MAPPED_COPY;
1168         region->vm_start = (unsigned long) base;
1169         region->vm_end   = region->vm_start + rlen;
1170         region->vm_top   = region->vm_start + (total << PAGE_SHIFT);
1171
1172         vma->vm_start = region->vm_start;
1173         vma->vm_end   = region->vm_start + len;
1174
1175         if (vma->vm_file) {
1176                 /* read the contents of a file into the copy */
1177                 mm_segment_t old_fs;
1178                 loff_t fpos;
1179
1180                 fpos = vma->vm_pgoff;
1181                 fpos <<= PAGE_SHIFT;
1182
1183                 old_fs = get_fs();
1184                 set_fs(KERNEL_DS);
1185                 ret = vma->vm_file->f_op->read(vma->vm_file, base, rlen, &fpos);
1186                 set_fs(old_fs);
1187
1188                 if (ret < 0)
1189                         goto error_free;
1190
1191                 /* clear the last little bit */
1192                 if (ret < rlen)
1193                         memset(base + ret, 0, rlen - ret);
1194
1195         }
1196
1197         return 0;
1198
1199 error_free:
1200         free_page_series(region->vm_start, region->vm_end);
1201         region->vm_start = vma->vm_start = 0;
1202         region->vm_end   = vma->vm_end = 0;
1203         region->vm_top   = 0;
1204         return ret;
1205
1206 enomem:
1207         printk("Allocation of length %lu from process %d (%s) failed\n",
1208                len, current->pid, current->comm);
1209         show_free_areas();
1210         return -ENOMEM;
1211 }
1212
1213 /*
1214  * handle mapping creation for uClinux
1215  */
1216 unsigned long do_mmap_pgoff(struct file *file,
1217                             unsigned long addr,
1218                             unsigned long len,
1219                             unsigned long prot,
1220                             unsigned long flags,
1221                             unsigned long pgoff)
1222 {
1223         struct vm_area_struct *vma;
1224         struct vm_region *region;
1225         struct rb_node *rb;
1226         unsigned long capabilities, vm_flags, result;
1227         int ret;
1228
1229         kenter(",%lx,%lx,%lx,%lx,%lx", addr, len, prot, flags, pgoff);
1230
1231         /* decide whether we should attempt the mapping, and if so what sort of
1232          * mapping */
1233         ret = validate_mmap_request(file, addr, len, prot, flags, pgoff,
1234                                     &capabilities);
1235         if (ret < 0) {
1236                 kleave(" = %d [val]", ret);
1237                 return ret;
1238         }
1239
1240         /* we ignore the address hint */
1241         addr = 0;
1242
1243         /* we've determined that we can make the mapping, now translate what we
1244          * now know into VMA flags */
1245         vm_flags = determine_vm_flags(file, prot, flags, capabilities);
1246
1247         /* we're going to need to record the mapping */
1248         region = kmem_cache_zalloc(vm_region_jar, GFP_KERNEL);
1249         if (!region)
1250                 goto error_getting_region;
1251
1252         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1253         if (!vma)
1254                 goto error_getting_vma;
1255
1256         region->vm_usage = 1;
1257         region->vm_flags = vm_flags;
1258         region->vm_pgoff = pgoff;
1259
1260         INIT_LIST_HEAD(&vma->anon_vma_chain);
1261         vma->vm_flags = vm_flags;
1262         vma->vm_pgoff = pgoff;
1263
1264         if (file) {
1265                 region->vm_file = file;
1266                 get_file(file);
1267                 vma->vm_file = file;
1268                 get_file(file);
1269                 if (vm_flags & VM_EXECUTABLE) {
1270                         added_exe_file_vma(current->mm);
1271                         vma->vm_mm = current->mm;
1272                 }
1273         }
1274
1275         down_write(&nommu_region_sem);
1276
1277         /* if we want to share, we need to check for regions created by other
1278          * mmap() calls that overlap with our proposed mapping
1279          * - we can only share with a superset match on most regular files
1280          * - shared mappings on character devices and memory backed files are
1281          *   permitted to overlap inexactly as far as we are concerned for in
1282          *   these cases, sharing is handled in the driver or filesystem rather
1283          *   than here
1284          */
1285         if (vm_flags & VM_MAYSHARE) {
1286                 struct vm_region *pregion;
1287                 unsigned long pglen, rpglen, pgend, rpgend, start;
1288
1289                 pglen = (len + PAGE_SIZE - 1) >> PAGE_SHIFT;
1290                 pgend = pgoff + pglen;
1291
1292                 for (rb = rb_first(&nommu_region_tree); rb; rb = rb_next(rb)) {
1293                         pregion = rb_entry(rb, struct vm_region, vm_rb);
1294
1295                         if (!(pregion->vm_flags & VM_MAYSHARE))
1296                                 continue;
1297
1298                         /* search for overlapping mappings on the same file */
1299                         if (pregion->vm_file->f_path.dentry->d_inode !=
1300                             file->f_path.dentry->d_inode)
1301                                 continue;
1302
1303                         if (pregion->vm_pgoff >= pgend)
1304                                 continue;
1305
1306                         rpglen = pregion->vm_end - pregion->vm_start;
1307                         rpglen = (rpglen + PAGE_SIZE - 1) >> PAGE_SHIFT;
1308                         rpgend = pregion->vm_pgoff + rpglen;
1309                         if (pgoff >= rpgend)
1310                                 continue;
1311
1312                         /* handle inexactly overlapping matches between
1313                          * mappings */
1314                         if ((pregion->vm_pgoff != pgoff || rpglen != pglen) &&
1315                             !(pgoff >= pregion->vm_pgoff && pgend <= rpgend)) {
1316                                 /* new mapping is not a subset of the region */
1317                                 if (!(capabilities & BDI_CAP_MAP_DIRECT))
1318                                         goto sharing_violation;
1319                                 continue;
1320                         }
1321
1322                         /* we've found a region we can share */
1323                         pregion->vm_usage++;
1324                         vma->vm_region = pregion;
1325                         start = pregion->vm_start;
1326                         start += (pgoff - pregion->vm_pgoff) << PAGE_SHIFT;
1327                         vma->vm_start = start;
1328                         vma->vm_end = start + len;
1329
1330                         if (pregion->vm_flags & VM_MAPPED_COPY) {
1331                                 kdebug("share copy");
1332                                 vma->vm_flags |= VM_MAPPED_COPY;
1333                         } else {
1334                                 kdebug("share mmap");
1335                                 ret = do_mmap_shared_file(vma);
1336                                 if (ret < 0) {
1337                                         vma->vm_region = NULL;
1338                                         vma->vm_start = 0;
1339                                         vma->vm_end = 0;
1340                                         pregion->vm_usage--;
1341                                         pregion = NULL;
1342                                         goto error_just_free;
1343                                 }
1344                         }
1345                         fput(region->vm_file);
1346                         kmem_cache_free(vm_region_jar, region);
1347                         region = pregion;
1348                         result = start;
1349                         goto share;
1350                 }
1351
1352                 /* obtain the address at which to make a shared mapping
1353                  * - this is the hook for quasi-memory character devices to
1354                  *   tell us the location of a shared mapping
1355                  */
1356                 if (capabilities & BDI_CAP_MAP_DIRECT) {
1357                         addr = file->f_op->get_unmapped_area(file, addr, len,
1358                                                              pgoff, flags);
1359                         if (IS_ERR((void *) addr)) {
1360                                 ret = addr;
1361                                 if (ret != (unsigned long) -ENOSYS)
1362                                         goto error_just_free;
1363
1364                                 /* the driver refused to tell us where to site
1365                                  * the mapping so we'll have to attempt to copy
1366                                  * it */
1367                                 ret = (unsigned long) -ENODEV;
1368                                 if (!(capabilities & BDI_CAP_MAP_COPY))
1369                                         goto error_just_free;
1370
1371                                 capabilities &= ~BDI_CAP_MAP_DIRECT;
1372                         } else {
1373                                 vma->vm_start = region->vm_start = addr;
1374                                 vma->vm_end = region->vm_end = addr + len;
1375                         }
1376                 }
1377         }
1378
1379         vma->vm_region = region;
1380
1381         /* set up the mapping
1382          * - the region is filled in if BDI_CAP_MAP_DIRECT is still set
1383          */
1384         if (file && vma->vm_flags & VM_SHARED)
1385                 ret = do_mmap_shared_file(vma);
1386         else
1387                 ret = do_mmap_private(vma, region, len, capabilities);
1388         if (ret < 0)
1389                 goto error_just_free;
1390         add_nommu_region(region);
1391
1392         /* clear anonymous mappings that don't ask for uninitialized data */
1393         if (!vma->vm_file && !(flags & MAP_UNINITIALIZED))
1394                 memset((void *)region->vm_start, 0,
1395                        region->vm_end - region->vm_start);
1396
1397         /* okay... we have a mapping; now we have to register it */
1398         result = vma->vm_start;
1399
1400         current->mm->total_vm += len >> PAGE_SHIFT;
1401
1402 share:
1403         add_vma_to_mm(current->mm, vma);
1404
1405         /* we flush the region from the icache only when the first executable
1406          * mapping of it is made  */
1407         if (vma->vm_flags & VM_EXEC && !region->vm_icache_flushed) {
1408                 flush_icache_range(region->vm_start, region->vm_end);
1409                 region->vm_icache_flushed = true;
1410         }
1411
1412         up_write(&nommu_region_sem);
1413
1414         kleave(" = %lx", result);
1415         return result;
1416
1417 error_just_free:
1418         up_write(&nommu_region_sem);
1419 error:
1420         if (region->vm_file)
1421                 fput(region->vm_file);
1422         kmem_cache_free(vm_region_jar, region);
1423         if (vma->vm_file)
1424                 fput(vma->vm_file);
1425         if (vma->vm_flags & VM_EXECUTABLE)
1426                 removed_exe_file_vma(vma->vm_mm);
1427         kmem_cache_free(vm_area_cachep, vma);
1428         kleave(" = %d", ret);
1429         return ret;
1430
1431 sharing_violation:
1432         up_write(&nommu_region_sem);
1433         printk(KERN_WARNING "Attempt to share mismatched mappings\n");
1434         ret = -EINVAL;
1435         goto error;
1436
1437 error_getting_vma:
1438         kmem_cache_free(vm_region_jar, region);
1439         printk(KERN_WARNING "Allocation of vma for %lu byte allocation"
1440                " from process %d failed\n",
1441                len, current->pid);
1442         show_free_areas();
1443         return -ENOMEM;
1444
1445 error_getting_region:
1446         printk(KERN_WARNING "Allocation of vm region for %lu byte allocation"
1447                " from process %d failed\n",
1448                len, current->pid);
1449         show_free_areas();
1450         return -ENOMEM;
1451 }
1452 EXPORT_SYMBOL(do_mmap_pgoff);
1453
1454 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1455                 unsigned long, prot, unsigned long, flags,
1456                 unsigned long, fd, unsigned long, pgoff)
1457 {
1458         struct file *file = NULL;
1459         unsigned long retval = -EBADF;
1460
1461         if (!(flags & MAP_ANONYMOUS)) {
1462                 file = fget(fd);
1463                 if (!file)
1464                         goto out;
1465         }
1466
1467         flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1468
1469         down_write(&current->mm->mmap_sem);
1470         retval = do_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1471         up_write(&current->mm->mmap_sem);
1472
1473         if (file)
1474                 fput(file);
1475 out:
1476         return retval;
1477 }
1478
1479 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1480 struct mmap_arg_struct {
1481         unsigned long addr;
1482         unsigned long len;
1483         unsigned long prot;
1484         unsigned long flags;
1485         unsigned long fd;
1486         unsigned long offset;
1487 };
1488
1489 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1490 {
1491         struct mmap_arg_struct a;
1492
1493         if (copy_from_user(&a, arg, sizeof(a)))
1494                 return -EFAULT;
1495         if (a.offset & ~PAGE_MASK)
1496                 return -EINVAL;
1497
1498         return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1499                               a.offset >> PAGE_SHIFT);
1500 }
1501 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1502
1503 /*
1504  * split a vma into two pieces at address 'addr', a new vma is allocated either
1505  * for the first part or the tail.
1506  */
1507 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
1508               unsigned long addr, int new_below)
1509 {
1510         struct vm_area_struct *new;
1511         struct vm_region *region;
1512         unsigned long npages;
1513
1514         kenter("");
1515
1516         /* we're only permitted to split anonymous regions (these should have
1517          * only a single usage on the region) */
1518         if (vma->vm_file)
1519                 return -ENOMEM;
1520
1521         if (mm->map_count >= sysctl_max_map_count)
1522                 return -ENOMEM;
1523
1524         region = kmem_cache_alloc(vm_region_jar, GFP_KERNEL);
1525         if (!region)
1526                 return -ENOMEM;
1527
1528         new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
1529         if (!new) {
1530                 kmem_cache_free(vm_region_jar, region);
1531                 return -ENOMEM;
1532         }
1533
1534         /* most fields are the same, copy all, and then fixup */
1535         *new = *vma;
1536         *region = *vma->vm_region;
1537         new->vm_region = region;
1538
1539         npages = (addr - vma->vm_start) >> PAGE_SHIFT;
1540
1541         if (new_below) {
1542                 region->vm_top = region->vm_end = new->vm_end = addr;
1543         } else {
1544                 region->vm_start = new->vm_start = addr;
1545                 region->vm_pgoff = new->vm_pgoff += npages;
1546         }
1547
1548         if (new->vm_ops && new->vm_ops->open)
1549                 new->vm_ops->open(new);
1550
1551         delete_vma_from_mm(vma);
1552         down_write(&nommu_region_sem);
1553         delete_nommu_region(vma->vm_region);
1554         if (new_below) {
1555                 vma->vm_region->vm_start = vma->vm_start = addr;
1556                 vma->vm_region->vm_pgoff = vma->vm_pgoff += npages;
1557         } else {
1558                 vma->vm_region->vm_end = vma->vm_end = addr;
1559                 vma->vm_region->vm_top = addr;
1560         }
1561         add_nommu_region(vma->vm_region);
1562         add_nommu_region(new->vm_region);
1563         up_write(&nommu_region_sem);
1564         add_vma_to_mm(mm, vma);
1565         add_vma_to_mm(mm, new);
1566         return 0;
1567 }
1568
1569 /*
1570  * shrink a VMA by removing the specified chunk from either the beginning or
1571  * the end
1572  */
1573 static int shrink_vma(struct mm_struct *mm,
1574                       struct vm_area_struct *vma,
1575                       unsigned long from, unsigned long to)
1576 {
1577         struct vm_region *region;
1578
1579         kenter("");
1580
1581         /* adjust the VMA's pointers, which may reposition it in the MM's tree
1582          * and list */
1583         delete_vma_from_mm(vma);
1584         if (from > vma->vm_start)
1585                 vma->vm_end = from;
1586         else
1587                 vma->vm_start = to;
1588         add_vma_to_mm(mm, vma);
1589
1590         /* cut the backing region down to size */
1591         region = vma->vm_region;
1592         BUG_ON(region->vm_usage != 1);
1593
1594         down_write(&nommu_region_sem);
1595         delete_nommu_region(region);
1596         if (from > region->vm_start) {
1597                 to = region->vm_top;
1598                 region->vm_top = region->vm_end = from;
1599         } else {
1600                 region->vm_start = to;
1601         }
1602         add_nommu_region(region);
1603         up_write(&nommu_region_sem);
1604
1605         free_page_series(from, to);
1606         return 0;
1607 }
1608
1609 /*
1610  * release a mapping
1611  * - under NOMMU conditions the chunk to be unmapped must be backed by a single
1612  *   VMA, though it need not cover the whole VMA
1613  */
1614 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
1615 {
1616         struct vm_area_struct *vma;
1617         struct rb_node *rb;
1618         unsigned long end = start + len;
1619         int ret;
1620
1621         kenter(",%lx,%zx", start, len);
1622
1623         if (len == 0)
1624                 return -EINVAL;
1625
1626         /* find the first potentially overlapping VMA */
1627         vma = find_vma(mm, start);
1628         if (!vma) {
1629                 static int limit = 0;
1630                 if (limit < 5) {
1631                         printk(KERN_WARNING
1632                                "munmap of memory not mmapped by process %d"
1633                                " (%s): 0x%lx-0x%lx\n",
1634                                current->pid, current->comm,
1635                                start, start + len - 1);
1636                         limit++;
1637                 }
1638                 return -EINVAL;
1639         }
1640
1641         /* we're allowed to split an anonymous VMA but not a file-backed one */
1642         if (vma->vm_file) {
1643                 do {
1644                         if (start > vma->vm_start) {
1645                                 kleave(" = -EINVAL [miss]");
1646                                 return -EINVAL;
1647                         }
1648                         if (end == vma->vm_end)
1649                                 goto erase_whole_vma;
1650                         rb = rb_next(&vma->vm_rb);
1651                         vma = rb_entry(rb, struct vm_area_struct, vm_rb);
1652                 } while (rb);
1653                 kleave(" = -EINVAL [split file]");
1654                 return -EINVAL;
1655         } else {
1656                 /* the chunk must be a subset of the VMA found */
1657                 if (start == vma->vm_start && end == vma->vm_end)
1658                         goto erase_whole_vma;
1659                 if (start < vma->vm_start || end > vma->vm_end) {
1660                         kleave(" = -EINVAL [superset]");
1661                         return -EINVAL;
1662                 }
1663                 if (start & ~PAGE_MASK) {
1664                         kleave(" = -EINVAL [unaligned start]");
1665                         return -EINVAL;
1666                 }
1667                 if (end != vma->vm_end && end & ~PAGE_MASK) {
1668                         kleave(" = -EINVAL [unaligned split]");
1669                         return -EINVAL;
1670                 }
1671                 if (start != vma->vm_start && end != vma->vm_end) {
1672                         ret = split_vma(mm, vma, start, 1);
1673                         if (ret < 0) {
1674                                 kleave(" = %d [split]", ret);
1675                                 return ret;
1676                         }
1677                 }
1678                 return shrink_vma(mm, vma, start, end);
1679         }
1680
1681 erase_whole_vma:
1682         delete_vma_from_mm(vma);
1683         delete_vma(mm, vma);
1684         kleave(" = 0");
1685         return 0;
1686 }
1687 EXPORT_SYMBOL(do_munmap);
1688
1689 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
1690 {
1691         int ret;
1692         struct mm_struct *mm = current->mm;
1693
1694         down_write(&mm->mmap_sem);
1695         ret = do_munmap(mm, addr, len);
1696         up_write(&mm->mmap_sem);
1697         return ret;
1698 }
1699
1700 /*
1701  * release all the mappings made in a process's VM space
1702  */
1703 void exit_mmap(struct mm_struct *mm)
1704 {
1705         struct vm_area_struct *vma;
1706
1707         if (!mm)
1708                 return;
1709
1710         kenter("");
1711
1712         mm->total_vm = 0;
1713
1714         while ((vma = mm->mmap)) {
1715                 mm->mmap = vma->vm_next;
1716                 delete_vma_from_mm(vma);
1717                 delete_vma(mm, vma);
1718         }
1719
1720         kleave("");
1721 }
1722
1723 unsigned long do_brk(unsigned long addr, unsigned long len)
1724 {
1725         return -ENOMEM;
1726 }
1727
1728 /*
1729  * expand (or shrink) an existing mapping, potentially moving it at the same
1730  * time (controlled by the MREMAP_MAYMOVE flag and available VM space)
1731  *
1732  * under NOMMU conditions, we only permit changing a mapping's size, and only
1733  * as long as it stays within the region allocated by do_mmap_private() and the
1734  * block is not shareable
1735  *
1736  * MREMAP_FIXED is not supported under NOMMU conditions
1737  */
1738 unsigned long do_mremap(unsigned long addr,
1739                         unsigned long old_len, unsigned long new_len,
1740                         unsigned long flags, unsigned long new_addr)
1741 {
1742         struct vm_area_struct *vma;
1743
1744         /* insanity checks first */
1745         if (old_len == 0 || new_len == 0)
1746                 return (unsigned long) -EINVAL;
1747
1748         if (addr & ~PAGE_MASK)
1749                 return -EINVAL;
1750
1751         if (flags & MREMAP_FIXED && new_addr != addr)
1752                 return (unsigned long) -EINVAL;
1753
1754         vma = find_vma_exact(current->mm, addr, old_len);
1755         if (!vma)
1756                 return (unsigned long) -EINVAL;
1757
1758         if (vma->vm_end != vma->vm_start + old_len)
1759                 return (unsigned long) -EFAULT;
1760
1761         if (vma->vm_flags & VM_MAYSHARE)
1762                 return (unsigned long) -EPERM;
1763
1764         if (new_len > vma->vm_region->vm_end - vma->vm_region->vm_start)
1765                 return (unsigned long) -ENOMEM;
1766
1767         /* all checks complete - do it */
1768         vma->vm_end = vma->vm_start + new_len;
1769         return vma->vm_start;
1770 }
1771 EXPORT_SYMBOL(do_mremap);
1772
1773 SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,
1774                 unsigned long, new_len, unsigned long, flags,
1775                 unsigned long, new_addr)
1776 {
1777         unsigned long ret;
1778
1779         down_write(&current->mm->mmap_sem);
1780         ret = do_mremap(addr, old_len, new_len, flags, new_addr);
1781         up_write(&current->mm->mmap_sem);
1782         return ret;
1783 }
1784
1785 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
1786                         unsigned int foll_flags)
1787 {
1788         return NULL;
1789 }
1790
1791 int remap_pfn_range(struct vm_area_struct *vma, unsigned long from,
1792                 unsigned long to, unsigned long size, pgprot_t prot)
1793 {
1794         vma->vm_start = vma->vm_pgoff << PAGE_SHIFT;
1795         return 0;
1796 }
1797 EXPORT_SYMBOL(remap_pfn_range);
1798
1799 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
1800                         unsigned long pgoff)
1801 {
1802         unsigned int size = vma->vm_end - vma->vm_start;
1803
1804         if (!(vma->vm_flags & VM_USERMAP))
1805                 return -EINVAL;
1806
1807         vma->vm_start = (unsigned long)(addr + (pgoff << PAGE_SHIFT));
1808         vma->vm_end = vma->vm_start + size;
1809
1810         return 0;
1811 }
1812 EXPORT_SYMBOL(remap_vmalloc_range);
1813
1814 void swap_unplug_io_fn(struct backing_dev_info *bdi, struct page *page)
1815 {
1816 }
1817
1818 unsigned long arch_get_unmapped_area(struct file *file, unsigned long addr,
1819         unsigned long len, unsigned long pgoff, unsigned long flags)
1820 {
1821         return -ENOMEM;
1822 }
1823
1824 void arch_unmap_area(struct mm_struct *mm, unsigned long addr)
1825 {
1826 }
1827
1828 void unmap_mapping_range(struct address_space *mapping,
1829                          loff_t const holebegin, loff_t const holelen,
1830                          int even_cows)
1831 {
1832 }
1833 EXPORT_SYMBOL(unmap_mapping_range);
1834
1835 /*
1836  * Check that a process has enough memory to allocate a new virtual
1837  * mapping. 0 means there is enough memory for the allocation to
1838  * succeed and -ENOMEM implies there is not.
1839  *
1840  * We currently support three overcommit policies, which are set via the
1841  * vm.overcommit_memory sysctl.  See Documentation/vm/overcommit-accounting
1842  *
1843  * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
1844  * Additional code 2002 Jul 20 by Robert Love.
1845  *
1846  * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
1847  *
1848  * Note this is a helper function intended to be used by LSMs which
1849  * wish to use this logic.
1850  */
1851 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
1852 {
1853         unsigned long free, allowed;
1854
1855         vm_acct_memory(pages);
1856
1857         /*
1858          * Sometimes we want to use more memory than we have
1859          */
1860         if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
1861                 return 0;
1862
1863         if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
1864                 unsigned long n;
1865
1866                 free = global_page_state(NR_FILE_PAGES);
1867                 free += nr_swap_pages;
1868
1869                 /*
1870                  * Any slabs which are created with the
1871                  * SLAB_RECLAIM_ACCOUNT flag claim to have contents
1872                  * which are reclaimable, under pressure.  The dentry
1873                  * cache and most inode caches should fall into this
1874                  */
1875                 free += global_page_state(NR_SLAB_RECLAIMABLE);
1876
1877                 /*
1878                  * Leave the last 3% for root
1879                  */
1880                 if (!cap_sys_admin)
1881                         free -= free / 32;
1882
1883                 if (free > pages)
1884                         return 0;
1885
1886                 /*
1887                  * nr_free_pages() is very expensive on large systems,
1888                  * only call if we're about to fail.
1889                  */
1890                 n = nr_free_pages();
1891
1892                 /*
1893                  * Leave reserved pages. The pages are not for anonymous pages.
1894                  */
1895                 if (n <= totalreserve_pages)
1896                         goto error;
1897                 else
1898                         n -= totalreserve_pages;
1899
1900                 /*
1901                  * Leave the last 3% for root
1902                  */
1903                 if (!cap_sys_admin)
1904                         n -= n / 32;
1905                 free += n;
1906
1907                 if (free > pages)
1908                         return 0;
1909
1910                 goto error;
1911         }
1912
1913         allowed = totalram_pages * sysctl_overcommit_ratio / 100;
1914         /*
1915          * Leave the last 3% for root
1916          */
1917         if (!cap_sys_admin)
1918                 allowed -= allowed / 32;
1919         allowed += total_swap_pages;
1920
1921         /* Don't let a single process grow too big:
1922            leave 3% of the size of this process for other processes */
1923         if (mm)
1924                 allowed -= mm->total_vm / 32;
1925
1926         if (percpu_counter_read_positive(&vm_committed_as) < allowed)
1927                 return 0;
1928
1929 error:
1930         vm_unacct_memory(pages);
1931
1932         return -ENOMEM;
1933 }
1934
1935 int in_gate_area_no_task(unsigned long addr)
1936 {
1937         return 0;
1938 }
1939
1940 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1941 {
1942         BUG();
1943         return 0;
1944 }
1945 EXPORT_SYMBOL(filemap_fault);
1946
1947 /*
1948  * Access another process' address space.
1949  * - source/target buffer must be kernel space
1950  */
1951 int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write)
1952 {
1953         struct vm_area_struct *vma;
1954         struct mm_struct *mm;
1955
1956         if (addr + len < addr)
1957                 return 0;
1958
1959         mm = get_task_mm(tsk);
1960         if (!mm)
1961                 return 0;
1962
1963         down_read(&mm->mmap_sem);
1964
1965         /* the access must start within one of the target process's mappings */
1966         vma = find_vma(mm, addr);
1967         if (vma) {
1968                 /* don't overrun this mapping */
1969                 if (addr + len >= vma->vm_end)
1970                         len = vma->vm_end - addr;
1971
1972                 /* only read or write mappings where it is permitted */
1973                 if (write && vma->vm_flags & VM_MAYWRITE)
1974                         copy_to_user_page(vma, NULL, addr,
1975                                          (void *) addr, buf, len);
1976                 else if (!write && vma->vm_flags & VM_MAYREAD)
1977                         copy_from_user_page(vma, NULL, addr,
1978                                             buf, (void *) addr, len);
1979                 else
1980                         len = 0;
1981         } else {
1982                 len = 0;
1983         }
1984
1985         up_read(&mm->mmap_sem);
1986         mmput(mm);
1987         return len;
1988 }
1989
1990 /**
1991  * nommu_shrink_inode_mappings - Shrink the shared mappings on an inode
1992  * @inode: The inode to check
1993  * @size: The current filesize of the inode
1994  * @newsize: The proposed filesize of the inode
1995  *
1996  * Check the shared mappings on an inode on behalf of a shrinking truncate to
1997  * make sure that that any outstanding VMAs aren't broken and then shrink the
1998  * vm_regions that extend that beyond so that do_mmap_pgoff() doesn't
1999  * automatically grant mappings that are too large.
2000  */
2001 int nommu_shrink_inode_mappings(struct inode *inode, size_t size,
2002                                 size_t newsize)
2003 {
2004         struct vm_area_struct *vma;
2005         struct prio_tree_iter iter;
2006         struct vm_region *region;
2007         pgoff_t low, high;
2008         size_t r_size, r_top;
2009
2010         low = newsize >> PAGE_SHIFT;
2011         high = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2012
2013         down_write(&nommu_region_sem);
2014
2015         /* search for VMAs that fall within the dead zone */
2016         vma_prio_tree_foreach(vma, &iter, &inode->i_mapping->i_mmap,
2017                               low, high) {
2018                 /* found one - only interested if it's shared out of the page
2019                  * cache */
2020                 if (vma->vm_flags & VM_SHARED) {
2021                         up_write(&nommu_region_sem);
2022                         return -ETXTBSY; /* not quite true, but near enough */
2023                 }
2024         }
2025
2026         /* reduce any regions that overlap the dead zone - if in existence,
2027          * these will be pointed to by VMAs that don't overlap the dead zone
2028          *
2029          * we don't check for any regions that start beyond the EOF as there
2030          * shouldn't be any
2031          */
2032         vma_prio_tree_foreach(vma, &iter, &inode->i_mapping->i_mmap,
2033                               0, ULONG_MAX) {
2034                 if (!(vma->vm_flags & VM_SHARED))
2035                         continue;
2036
2037                 region = vma->vm_region;
2038                 r_size = region->vm_top - region->vm_start;
2039                 r_top = (region->vm_pgoff << PAGE_SHIFT) + r_size;
2040
2041                 if (r_top > newsize) {
2042                         region->vm_top -= r_top - newsize;
2043                         if (region->vm_end > region->vm_top)
2044                                 region->vm_end = region->vm_top;
2045                 }
2046         }
2047
2048         up_write(&nommu_region_sem);
2049         return 0;
2050 }