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