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