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