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