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