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