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