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