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