Merge linux-3.10.67 into dev-kernel-3.10
[linux-3.10.git] / mm / mmap.c
1 /*
2  * mm/mmap.c
3  *
4  * Written by obz.
5  *
6  * Address space accounting code        <alan@lxorguk.ukuu.org.uk>
7  */
8
9 #include <linux/kernel.h>
10 #include <linux/slab.h>
11 #include <linux/backing-dev.h>
12 #include <linux/mm.h>
13 #include <linux/shm.h>
14 #include <linux/mman.h>
15 #include <linux/pagemap.h>
16 #include <linux/swap.h>
17 #include <linux/syscalls.h>
18 #include <linux/capability.h>
19 #include <linux/init.h>
20 #include <linux/file.h>
21 #include <linux/fs.h>
22 #include <linux/personality.h>
23 #include <linux/security.h>
24 #include <linux/hugetlb.h>
25 #include <linux/profile.h>
26 #include <linux/export.h>
27 #include <linux/mount.h>
28 #include <linux/mempolicy.h>
29 #include <linux/rmap.h>
30 #include <linux/mmu_notifier.h>
31 #include <linux/perf_event.h>
32 #include <linux/audit.h>
33 #include <linux/khugepaged.h>
34 #include <linux/uprobes.h>
35 #include <linux/rbtree_augmented.h>
36 #include <linux/sched/sysctl.h>
37 #include <linux/notifier.h>
38 #include <linux/memory.h>
39 #include <linux/tegra_profiler.h>
40
41 #include <asm/uaccess.h>
42 #include <asm/cacheflush.h>
43 #include <asm/tlb.h>
44 #include <asm/mmu_context.h>
45
46 #include "internal.h"
47
48 #ifndef arch_mmap_check
49 #define arch_mmap_check(addr, len, flags)       (0)
50 #endif
51
52 #ifndef arch_rebalance_pgtables
53 #define arch_rebalance_pgtables(addr, len)              (addr)
54 #endif
55
56 static void unmap_region(struct mm_struct *mm,
57                 struct vm_area_struct *vma, struct vm_area_struct *prev,
58                 unsigned long start, unsigned long end);
59
60 /* description of effects of mapping type and prot in current implementation.
61  * this is due to the limited x86 page protection hardware.  The expected
62  * behavior is in parens:
63  *
64  * map_type     prot
65  *              PROT_NONE       PROT_READ       PROT_WRITE      PROT_EXEC
66  * MAP_SHARED   r: (no) no      r: (yes) yes    r: (no) yes     r: (no) yes
67  *              w: (no) no      w: (no) no      w: (yes) yes    w: (no) no
68  *              x: (no) no      x: (no) yes     x: (no) yes     x: (yes) yes
69  *              
70  * MAP_PRIVATE  r: (no) no      r: (yes) yes    r: (no) yes     r: (no) yes
71  *              w: (no) no      w: (no) no      w: (copy) copy  w: (no) no
72  *              x: (no) no      x: (no) yes     x: (no) yes     x: (yes) yes
73  *
74  */
75 pgprot_t protection_map[16] = {
76         __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
77         __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
78 };
79
80 pgprot_t vm_get_page_prot(unsigned long vm_flags)
81 {
82         return __pgprot(pgprot_val(protection_map[vm_flags &
83                                 (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
84                         pgprot_val(arch_vm_get_page_prot(vm_flags)));
85 }
86 EXPORT_SYMBOL(vm_get_page_prot);
87
88 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;  /* heuristic overcommit */
89 int sysctl_overcommit_ratio __read_mostly = 50; /* default is 50% */
90 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
91 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
92 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
93 /*
94  * Make sure vm_committed_as in one cacheline and not cacheline shared with
95  * other variables. It can be updated by several CPUs frequently.
96  */
97 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
98
99 /*
100  * The global memory commitment made in the system can be a metric
101  * that can be used to drive ballooning decisions when Linux is hosted
102  * as a guest. On Hyper-V, the host implements a policy engine for dynamically
103  * balancing memory across competing virtual machines that are hosted.
104  * Several metrics drive this policy engine including the guest reported
105  * memory commitment.
106  */
107 unsigned long vm_memory_committed(void)
108 {
109         return percpu_counter_read_positive(&vm_committed_as);
110 }
111 EXPORT_SYMBOL_GPL(vm_memory_committed);
112
113 /*
114  * Check that a process has enough memory to allocate a new virtual
115  * mapping. 0 means there is enough memory for the allocation to
116  * succeed and -ENOMEM implies there is not.
117  *
118  * We currently support three overcommit policies, which are set via the
119  * vm.overcommit_memory sysctl.  See Documentation/vm/overcommit-accounting
120  *
121  * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
122  * Additional code 2002 Jul 20 by Robert Love.
123  *
124  * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
125  *
126  * Note this is a helper function intended to be used by LSMs which
127  * wish to use this logic.
128  */
129 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
130 {
131         unsigned long free, allowed, reserve;
132
133         vm_acct_memory(pages);
134
135         /*
136          * Sometimes we want to use more memory than we have
137          */
138         if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
139                 return 0;
140
141         if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
142                 free = global_page_state(NR_FREE_PAGES);
143                 free += global_page_state(NR_FILE_PAGES);
144
145                 /*
146                  * shmem pages shouldn't be counted as free in this
147                  * case, they can't be purged, only swapped out, and
148                  * that won't affect the overall amount of available
149                  * memory in the system.
150                  */
151                 free -= global_page_state(NR_SHMEM);
152
153                 free += get_nr_swap_pages();
154
155                 /*
156                  * Any slabs which are created with the
157                  * SLAB_RECLAIM_ACCOUNT flag claim to have contents
158                  * which are reclaimable, under pressure.  The dentry
159                  * cache and most inode caches should fall into this
160                  */
161                 free += global_page_state(NR_SLAB_RECLAIMABLE);
162
163                 /*
164                  * Leave reserved pages. The pages are not for anonymous pages.
165                  */
166                 if (free <= totalreserve_pages)
167                         goto error;
168                 else
169                         free -= totalreserve_pages;
170
171                 /*
172                  * Reserve some for root
173                  */
174                 if (!cap_sys_admin)
175                         free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
176
177                 if (free > pages)
178                         return 0;
179
180                 goto error;
181         }
182
183         allowed = (totalram_pages - hugetlb_total_pages())
184                 * sysctl_overcommit_ratio / 100;
185         /*
186          * Reserve some for root
187          */
188         if (!cap_sys_admin)
189                 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
190         allowed += total_swap_pages;
191
192         /*
193          * Don't let a single process grow so big a user can't recover
194          */
195         if (mm) {
196                 reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
197                 allowed -= min(mm->total_vm / 32, reserve);
198         }
199
200         if (percpu_counter_read_positive(&vm_committed_as) < allowed)
201                 return 0;
202 error:
203         vm_unacct_memory(pages);
204
205         return -ENOMEM;
206 }
207
208 /*
209  * Requires inode->i_mapping->i_mmap_mutex
210  */
211 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
212                 struct file *file, struct address_space *mapping)
213 {
214         if (vma->vm_flags & VM_DENYWRITE)
215                 atomic_inc(&file_inode(file)->i_writecount);
216         if (vma->vm_flags & VM_SHARED)
217                 mapping->i_mmap_writable--;
218
219         flush_dcache_mmap_lock(mapping);
220         if (unlikely(vma->vm_flags & VM_NONLINEAR))
221                 list_del_init(&vma->shared.nonlinear);
222         else
223                 vma_interval_tree_remove(vma, &mapping->i_mmap);
224         flush_dcache_mmap_unlock(mapping);
225 }
226
227 /*
228  * Unlink a file-based vm structure from its interval tree, to hide
229  * vma from rmap and vmtruncate before freeing its page tables.
230  */
231 void unlink_file_vma(struct vm_area_struct *vma)
232 {
233         struct file *file = vma->vm_file;
234
235         if (file) {
236                 struct address_space *mapping = file->f_mapping;
237                 mutex_lock(&mapping->i_mmap_mutex);
238                 __remove_shared_vm_struct(vma, file, mapping);
239                 mutex_unlock(&mapping->i_mmap_mutex);
240         }
241 }
242
243 /*
244  * Close a vm structure and free it, returning the next.
245  */
246 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
247 {
248         struct vm_area_struct *next = vma->vm_next;
249
250         might_sleep();
251         if (vma->vm_ops && vma->vm_ops->close)
252                 vma->vm_ops->close(vma);
253         if (vma->vm_file)
254                 fput(vma->vm_file);
255         mpol_put(vma_policy(vma));
256         kmem_cache_free(vm_area_cachep, vma);
257         return next;
258 }
259
260 static unsigned long do_brk(unsigned long addr, unsigned long len);
261
262 SYSCALL_DEFINE1(brk, unsigned long, brk)
263 {
264         unsigned long rlim, retval;
265         unsigned long newbrk, oldbrk;
266         struct mm_struct *mm = current->mm;
267         unsigned long min_brk;
268         bool populate;
269
270         down_write(&mm->mmap_sem);
271
272 #ifdef CONFIG_COMPAT_BRK
273         /*
274          * CONFIG_COMPAT_BRK can still be overridden by setting
275          * randomize_va_space to 2, which will still cause mm->start_brk
276          * to be arbitrarily shifted
277          */
278         if (current->brk_randomized)
279                 min_brk = mm->start_brk;
280         else
281                 min_brk = mm->end_data;
282 #else
283         min_brk = mm->start_brk;
284 #endif
285         if (brk < min_brk)
286                 goto out;
287
288         /*
289          * Check against rlimit here. If this check is done later after the test
290          * of oldbrk with newbrk then it can escape the test and let the data
291          * segment grow beyond its set limit the in case where the limit is
292          * not page aligned -Ram Gupta
293          */
294         rlim = rlimit(RLIMIT_DATA);
295         if (rlim < RLIM_INFINITY && (brk - mm->start_brk) +
296                         (mm->end_data - mm->start_data) > rlim)
297                 goto out;
298
299         newbrk = PAGE_ALIGN(brk);
300         oldbrk = PAGE_ALIGN(mm->brk);
301         if (oldbrk == newbrk)
302                 goto set_brk;
303
304         /* Always allow shrinking brk. */
305         if (brk <= mm->brk) {
306                 if (!do_munmap(mm, newbrk, oldbrk-newbrk))
307                         goto set_brk;
308                 goto out;
309         }
310
311         /* Check against existing mmap mappings. */
312         if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE))
313                 goto out;
314
315         /* Ok, looks good - let it rip. */
316         if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
317                 goto out;
318
319 set_brk:
320         mm->brk = brk;
321         populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
322         up_write(&mm->mmap_sem);
323         if (populate)
324                 mm_populate(oldbrk, newbrk - oldbrk);
325         return brk;
326
327 out:
328         retval = mm->brk;
329         up_write(&mm->mmap_sem);
330         return retval;
331 }
332
333 static long vma_compute_subtree_gap(struct vm_area_struct *vma)
334 {
335         unsigned long max, subtree_gap;
336         max = vma->vm_start;
337         if (vma->vm_prev)
338                 max -= vma->vm_prev->vm_end;
339         if (vma->vm_rb.rb_left) {
340                 subtree_gap = rb_entry(vma->vm_rb.rb_left,
341                                 struct vm_area_struct, vm_rb)->rb_subtree_gap;
342                 if (subtree_gap > max)
343                         max = subtree_gap;
344         }
345         if (vma->vm_rb.rb_right) {
346                 subtree_gap = rb_entry(vma->vm_rb.rb_right,
347                                 struct vm_area_struct, vm_rb)->rb_subtree_gap;
348                 if (subtree_gap > max)
349                         max = subtree_gap;
350         }
351         return max;
352 }
353
354 #ifdef CONFIG_DEBUG_VM_RB
355 static int browse_rb(struct rb_root *root)
356 {
357         int i = 0, j, bug = 0;
358         struct rb_node *nd, *pn = NULL;
359         unsigned long prev = 0, pend = 0;
360
361         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
362                 struct vm_area_struct *vma;
363                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
364                 if (vma->vm_start < prev) {
365                         printk("vm_start %lx prev %lx\n", vma->vm_start, prev);
366                         bug = 1;
367                 }
368                 if (vma->vm_start < pend) {
369                         printk("vm_start %lx pend %lx\n", vma->vm_start, pend);
370                         bug = 1;
371                 }
372                 if (vma->vm_start > vma->vm_end) {
373                         printk("vm_end %lx < vm_start %lx\n",
374                                 vma->vm_end, vma->vm_start);
375                         bug = 1;
376                 }
377                 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
378                         printk("free gap %lx, correct %lx\n",
379                                vma->rb_subtree_gap,
380                                vma_compute_subtree_gap(vma));
381                         bug = 1;
382                 }
383                 i++;
384                 pn = nd;
385                 prev = vma->vm_start;
386                 pend = vma->vm_end;
387         }
388         j = 0;
389         for (nd = pn; nd; nd = rb_prev(nd))
390                 j++;
391         if (i != j) {
392                 printk("backwards %d, forwards %d\n", j, i);
393                 bug = 1;
394         }
395         return bug ? -1 : i;
396 }
397
398 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
399 {
400         struct rb_node *nd;
401
402         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
403                 struct vm_area_struct *vma;
404                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
405                 BUG_ON(vma != ignore &&
406                        vma->rb_subtree_gap != vma_compute_subtree_gap(vma));
407         }
408 }
409
410 void validate_mm(struct mm_struct *mm)
411 {
412         int bug = 0;
413         int i = 0;
414         unsigned long highest_address = 0;
415         struct vm_area_struct *vma = mm->mmap;
416         while (vma) {
417                 struct anon_vma_chain *avc;
418                 vma_lock_anon_vma(vma);
419                 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
420                         anon_vma_interval_tree_verify(avc);
421                 vma_unlock_anon_vma(vma);
422                 highest_address = vma->vm_end;
423                 vma = vma->vm_next;
424                 i++;
425         }
426         if (i != mm->map_count) {
427                 printk("map_count %d vm_next %d\n", mm->map_count, i);
428                 bug = 1;
429         }
430         if (highest_address != mm->highest_vm_end) {
431                 printk("mm->highest_vm_end %lx, found %lx\n",
432                        mm->highest_vm_end, highest_address);
433                 bug = 1;
434         }
435         i = browse_rb(&mm->mm_rb);
436         if (i != mm->map_count) {
437                 printk("map_count %d rb %d\n", mm->map_count, i);
438                 bug = 1;
439         }
440         BUG_ON(bug);
441 }
442 #else
443 #define validate_mm_rb(root, ignore) do { } while (0)
444 #define validate_mm(mm) do { } while (0)
445 #endif
446
447 RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,
448                      unsigned long, rb_subtree_gap, vma_compute_subtree_gap)
449
450 /*
451  * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
452  * vma->vm_prev->vm_end values changed, without modifying the vma's position
453  * in the rbtree.
454  */
455 static void vma_gap_update(struct vm_area_struct *vma)
456 {
457         /*
458          * As it turns out, RB_DECLARE_CALLBACKS() already created a callback
459          * function that does exacltly what we want.
460          */
461         vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
462 }
463
464 static inline void vma_rb_insert(struct vm_area_struct *vma,
465                                  struct rb_root *root)
466 {
467         /* All rb_subtree_gap values must be consistent prior to insertion */
468         validate_mm_rb(root, NULL);
469
470         rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
471 }
472
473 static void vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
474 {
475         /*
476          * All rb_subtree_gap values must be consistent prior to erase,
477          * with the possible exception of the vma being erased.
478          */
479         validate_mm_rb(root, vma);
480
481         /*
482          * Note rb_erase_augmented is a fairly large inline function,
483          * so make sure we instantiate it only once with our desired
484          * augmented rbtree callbacks.
485          */
486         rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
487 }
488
489 /*
490  * vma has some anon_vma assigned, and is already inserted on that
491  * anon_vma's interval trees.
492  *
493  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
494  * vma must be removed from the anon_vma's interval trees using
495  * anon_vma_interval_tree_pre_update_vma().
496  *
497  * After the update, the vma will be reinserted using
498  * anon_vma_interval_tree_post_update_vma().
499  *
500  * The entire update must be protected by exclusive mmap_sem and by
501  * the root anon_vma's mutex.
502  */
503 static inline void
504 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
505 {
506         struct anon_vma_chain *avc;
507
508         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
509                 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
510 }
511
512 static inline void
513 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
514 {
515         struct anon_vma_chain *avc;
516
517         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
518                 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
519 }
520
521 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
522                 unsigned long end, struct vm_area_struct **pprev,
523                 struct rb_node ***rb_link, struct rb_node **rb_parent)
524 {
525         struct rb_node **__rb_link, *__rb_parent, *rb_prev;
526
527         __rb_link = &mm->mm_rb.rb_node;
528         rb_prev = __rb_parent = NULL;
529
530         while (*__rb_link) {
531                 struct vm_area_struct *vma_tmp;
532
533                 __rb_parent = *__rb_link;
534                 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
535
536                 if (vma_tmp->vm_end > addr) {
537                         /* Fail if an existing vma overlaps the area */
538                         if (vma_tmp->vm_start < end)
539                                 return -ENOMEM;
540                         __rb_link = &__rb_parent->rb_left;
541                 } else {
542                         rb_prev = __rb_parent;
543                         __rb_link = &__rb_parent->rb_right;
544                 }
545         }
546
547         *pprev = NULL;
548         if (rb_prev)
549                 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
550         *rb_link = __rb_link;
551         *rb_parent = __rb_parent;
552         return 0;
553 }
554
555 static unsigned long count_vma_pages_range(struct mm_struct *mm,
556                 unsigned long addr, unsigned long end)
557 {
558         unsigned long nr_pages = 0;
559         struct vm_area_struct *vma;
560
561         /* Find first overlaping mapping */
562         vma = find_vma_intersection(mm, addr, end);
563         if (!vma)
564                 return 0;
565
566         nr_pages = (min(end, vma->vm_end) -
567                 max(addr, vma->vm_start)) >> PAGE_SHIFT;
568
569         /* Iterate over the rest of the overlaps */
570         for (vma = vma->vm_next; vma; vma = vma->vm_next) {
571                 unsigned long overlap_len;
572
573                 if (vma->vm_start > end)
574                         break;
575
576                 overlap_len = min(end, vma->vm_end) - vma->vm_start;
577                 nr_pages += overlap_len >> PAGE_SHIFT;
578         }
579
580         return nr_pages;
581 }
582
583 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
584                 struct rb_node **rb_link, struct rb_node *rb_parent)
585 {
586         /* Update tracking information for the gap following the new vma. */
587         if (vma->vm_next)
588                 vma_gap_update(vma->vm_next);
589         else
590                 mm->highest_vm_end = vma->vm_end;
591
592         /*
593          * vma->vm_prev wasn't known when we followed the rbtree to find the
594          * correct insertion point for that vma. As a result, we could not
595          * update the vma vm_rb parents rb_subtree_gap values on the way down.
596          * So, we first insert the vma with a zero rb_subtree_gap value
597          * (to be consistent with what we did on the way down), and then
598          * immediately update the gap to the correct value. Finally we
599          * rebalance the rbtree after all augmented values have been set.
600          */
601         rb_link_node(&vma->vm_rb, rb_parent, rb_link);
602         vma->rb_subtree_gap = 0;
603         vma_gap_update(vma);
604         vma_rb_insert(vma, &mm->mm_rb);
605 }
606
607 static void __vma_link_file(struct vm_area_struct *vma)
608 {
609         struct file *file;
610
611         file = vma->vm_file;
612         if (file) {
613                 struct address_space *mapping = file->f_mapping;
614
615                 if (vma->vm_flags & VM_DENYWRITE)
616                         atomic_dec(&file_inode(file)->i_writecount);
617                 if (vma->vm_flags & VM_SHARED)
618                         mapping->i_mmap_writable++;
619
620                 flush_dcache_mmap_lock(mapping);
621                 if (unlikely(vma->vm_flags & VM_NONLINEAR))
622                         vma_nonlinear_insert(vma, &mapping->i_mmap_nonlinear);
623                 else
624                         vma_interval_tree_insert(vma, &mapping->i_mmap);
625                 flush_dcache_mmap_unlock(mapping);
626         }
627 }
628
629 static void
630 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
631         struct vm_area_struct *prev, struct rb_node **rb_link,
632         struct rb_node *rb_parent)
633 {
634         __vma_link_list(mm, vma, prev, rb_parent);
635         __vma_link_rb(mm, vma, rb_link, rb_parent);
636 }
637
638 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
639                         struct vm_area_struct *prev, struct rb_node **rb_link,
640                         struct rb_node *rb_parent)
641 {
642         struct address_space *mapping = NULL;
643
644         if (vma->vm_file)
645                 mapping = vma->vm_file->f_mapping;
646
647         if (mapping)
648                 mutex_lock(&mapping->i_mmap_mutex);
649
650         __vma_link(mm, vma, prev, rb_link, rb_parent);
651         __vma_link_file(vma);
652
653         if (mapping)
654                 mutex_unlock(&mapping->i_mmap_mutex);
655
656         mm->map_count++;
657         validate_mm(mm);
658 }
659
660 /*
661  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
662  * mm's list and rbtree.  It has already been inserted into the interval tree.
663  */
664 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
665 {
666         struct vm_area_struct *prev;
667         struct rb_node **rb_link, *rb_parent;
668
669         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
670                            &prev, &rb_link, &rb_parent))
671                 BUG();
672         __vma_link(mm, vma, prev, rb_link, rb_parent);
673         mm->map_count++;
674 }
675
676 static inline void
677 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
678                 struct vm_area_struct *prev)
679 {
680         struct vm_area_struct *next;
681
682         vma_rb_erase(vma, &mm->mm_rb);
683         prev->vm_next = next = vma->vm_next;
684         if (next)
685                 next->vm_prev = prev;
686         if (mm->mmap_cache == vma)
687                 mm->mmap_cache = prev;
688 }
689
690 /*
691  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
692  * is already present in an i_mmap tree without adjusting the tree.
693  * The following helper function should be used when such adjustments
694  * are necessary.  The "insert" vma (if any) is to be inserted
695  * before we drop the necessary locks.
696  */
697 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
698         unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
699 {
700         struct mm_struct *mm = vma->vm_mm;
701         struct vm_area_struct *next = vma->vm_next;
702         struct vm_area_struct *importer = NULL;
703         struct address_space *mapping = NULL;
704         struct rb_root *root = NULL;
705         struct anon_vma *anon_vma = NULL;
706         struct file *file = vma->vm_file;
707         bool start_changed = false, end_changed = false;
708         long adjust_next = 0;
709         int remove_next = 0;
710
711         if (next && !insert) {
712                 struct vm_area_struct *exporter = NULL;
713
714                 if (end >= next->vm_end) {
715                         /*
716                          * vma expands, overlapping all the next, and
717                          * perhaps the one after too (mprotect case 6).
718                          */
719 again:                  remove_next = 1 + (end > next->vm_end);
720                         end = next->vm_end;
721                         exporter = next;
722                         importer = vma;
723                 } else if (end > next->vm_start) {
724                         /*
725                          * vma expands, overlapping part of the next:
726                          * mprotect case 5 shifting the boundary up.
727                          */
728                         adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
729                         exporter = next;
730                         importer = vma;
731                 } else if (end < vma->vm_end) {
732                         /*
733                          * vma shrinks, and !insert tells it's not
734                          * split_vma inserting another: so it must be
735                          * mprotect case 4 shifting the boundary down.
736                          */
737                         adjust_next = - ((vma->vm_end - end) >> PAGE_SHIFT);
738                         exporter = vma;
739                         importer = next;
740                 }
741
742                 /*
743                  * Easily overlooked: when mprotect shifts the boundary,
744                  * make sure the expanding vma has anon_vma set if the
745                  * shrinking vma had, to cover any anon pages imported.
746                  */
747                 if (exporter && exporter->anon_vma && !importer->anon_vma) {
748                         if (anon_vma_clone(importer, exporter))
749                                 return -ENOMEM;
750                         importer->anon_vma = exporter->anon_vma;
751                 }
752         }
753
754         if (file) {
755                 mapping = file->f_mapping;
756                 if (!(vma->vm_flags & VM_NONLINEAR)) {
757                         root = &mapping->i_mmap;
758                         uprobe_munmap(vma, vma->vm_start, vma->vm_end);
759
760                         if (adjust_next)
761                                 uprobe_munmap(next, next->vm_start,
762                                                         next->vm_end);
763                 }
764
765                 mutex_lock(&mapping->i_mmap_mutex);
766                 if (insert) {
767                         /*
768                          * Put into interval tree now, so instantiated pages
769                          * are visible to arm/parisc __flush_dcache_page
770                          * throughout; but we cannot insert into address
771                          * space until vma start or end is updated.
772                          */
773                         __vma_link_file(insert);
774                 }
775         }
776
777         vma_adjust_trans_huge(vma, start, end, adjust_next);
778
779         anon_vma = vma->anon_vma;
780         if (!anon_vma && adjust_next)
781                 anon_vma = next->anon_vma;
782         if (anon_vma) {
783                 VM_BUG_ON(adjust_next && next->anon_vma &&
784                           anon_vma != next->anon_vma);
785                 anon_vma_lock_write(anon_vma);
786                 anon_vma_interval_tree_pre_update_vma(vma);
787                 if (adjust_next)
788                         anon_vma_interval_tree_pre_update_vma(next);
789         }
790
791         if (root) {
792                 flush_dcache_mmap_lock(mapping);
793                 vma_interval_tree_remove(vma, root);
794                 if (adjust_next)
795                         vma_interval_tree_remove(next, root);
796         }
797
798         if (start != vma->vm_start) {
799                 vma->vm_start = start;
800                 start_changed = true;
801         }
802         if (end != vma->vm_end) {
803                 vma->vm_end = end;
804                 end_changed = true;
805         }
806         vma->vm_pgoff = pgoff;
807         if (adjust_next) {
808                 next->vm_start += adjust_next << PAGE_SHIFT;
809                 next->vm_pgoff += adjust_next;
810         }
811
812         if (root) {
813                 if (adjust_next)
814                         vma_interval_tree_insert(next, root);
815                 vma_interval_tree_insert(vma, root);
816                 flush_dcache_mmap_unlock(mapping);
817         }
818
819         if (remove_next) {
820                 /*
821                  * vma_merge has merged next into vma, and needs
822                  * us to remove next before dropping the locks.
823                  */
824                 __vma_unlink(mm, next, vma);
825                 if (file)
826                         __remove_shared_vm_struct(next, file, mapping);
827         } else if (insert) {
828                 /*
829                  * split_vma has split insert from vma, and needs
830                  * us to insert it before dropping the locks
831                  * (it may either follow vma or precede it).
832                  */
833                 __insert_vm_struct(mm, insert);
834         } else {
835                 if (start_changed)
836                         vma_gap_update(vma);
837                 if (end_changed) {
838                         if (!next)
839                                 mm->highest_vm_end = end;
840                         else if (!adjust_next)
841                                 vma_gap_update(next);
842                 }
843         }
844
845         if (anon_vma) {
846                 anon_vma_interval_tree_post_update_vma(vma);
847                 if (adjust_next)
848                         anon_vma_interval_tree_post_update_vma(next);
849                 anon_vma_unlock_write(anon_vma);
850         }
851         if (mapping)
852                 mutex_unlock(&mapping->i_mmap_mutex);
853
854         if (root) {
855                 uprobe_mmap(vma);
856
857                 if (adjust_next)
858                         uprobe_mmap(next);
859         }
860
861         if (remove_next) {
862                 if (file) {
863                         uprobe_munmap(next, next->vm_start, next->vm_end);
864                         fput(file);
865                 }
866                 if (next->anon_vma)
867                         anon_vma_merge(vma, next);
868                 mm->map_count--;
869                 mpol_put(vma_policy(next));
870                 kmem_cache_free(vm_area_cachep, next);
871                 /*
872                  * In mprotect's case 6 (see comments on vma_merge),
873                  * we must remove another next too. It would clutter
874                  * up the code too much to do both in one go.
875                  */
876                 next = vma->vm_next;
877                 if (remove_next == 2)
878                         goto again;
879                 else if (next)
880                         vma_gap_update(next);
881                 else
882                         mm->highest_vm_end = end;
883         }
884         if (insert && file)
885                 uprobe_mmap(insert);
886
887         validate_mm(mm);
888
889         return 0;
890 }
891
892 /*
893  * If the vma has a ->close operation then the driver probably needs to release
894  * per-vma resources, so we don't attempt to merge those.
895  */
896 static inline int is_mergeable_vma(struct vm_area_struct *vma,
897                         struct file *file, unsigned long vm_flags,
898                         const char __user *anon_name)
899 {
900         if (vma->vm_flags ^ vm_flags)
901                 return 0;
902         if (vma->vm_file != file)
903                 return 0;
904         if (vma->vm_ops && vma->vm_ops->close)
905                 return 0;
906         if (vma_get_anon_name(vma) != anon_name)
907                 return 0;
908         return 1;
909 }
910
911 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
912                                         struct anon_vma *anon_vma2,
913                                         struct vm_area_struct *vma)
914 {
915         /*
916          * The list_is_singular() test is to avoid merging VMA cloned from
917          * parents. This can improve scalability caused by anon_vma lock.
918          */
919         if ((!anon_vma1 || !anon_vma2) && (!vma ||
920                 list_is_singular(&vma->anon_vma_chain)))
921                 return 1;
922         return anon_vma1 == anon_vma2;
923 }
924
925 /*
926  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
927  * in front of (at a lower virtual address and file offset than) the vma.
928  *
929  * We cannot merge two vmas if they have differently assigned (non-NULL)
930  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
931  *
932  * We don't check here for the merged mmap wrapping around the end of pagecache
933  * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
934  * wrap, nor mmaps which cover the final page at index -1UL.
935  */
936 static int
937 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
938         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff,
939         const char __user *anon_name)
940 {
941         if (is_mergeable_vma(vma, file, vm_flags, anon_name) &&
942             is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
943                 if (vma->vm_pgoff == vm_pgoff)
944                         return 1;
945         }
946         return 0;
947 }
948
949 /*
950  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
951  * beyond (at a higher virtual address and file offset than) the vma.
952  *
953  * We cannot merge two vmas if they have differently assigned (non-NULL)
954  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
955  */
956 static int
957 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
958         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff,
959         const char __user *anon_name)
960 {
961         if (is_mergeable_vma(vma, file, vm_flags, anon_name) &&
962             is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
963                 pgoff_t vm_pglen;
964                 vm_pglen = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
965                 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
966                         return 1;
967         }
968         return 0;
969 }
970
971 /*
972  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
973  * figure out whether that can be merged with its predecessor or its
974  * successor.  Or both (it neatly fills a hole).
975  *
976  * In most cases - when called for mmap, brk or mremap - [addr,end) is
977  * certain not to be mapped by the time vma_merge is called; but when
978  * called for mprotect, it is certain to be already mapped (either at
979  * an offset within prev, or at the start of next), and the flags of
980  * this area are about to be changed to vm_flags - and the no-change
981  * case has already been eliminated.
982  *
983  * The following mprotect cases have to be considered, where AAAA is
984  * the area passed down from mprotect_fixup, never extending beyond one
985  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
986  *
987  *     AAAA             AAAA                AAAA          AAAA
988  *    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPNNNNXXXX
989  *    cannot merge    might become    might become    might become
990  *                    PPNNNNNNNNNN    PPPPPPPPPPNN    PPPPPPPPPPPP 6 or
991  *    mmap, brk or    case 4 below    case 5 below    PPPPPPPPXXXX 7 or
992  *    mremap move:                                    PPPPNNNNNNNN 8
993  *        AAAA
994  *    PPPP    NNNN    PPPPPPPPPPPP    PPPPPPPPNNNN    PPPPNNNNNNNN
995  *    might become    case 1 below    case 2 below    case 3 below
996  *
997  * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
998  * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
999  */
1000 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1001                         struct vm_area_struct *prev, unsigned long addr,
1002                         unsigned long end, unsigned long vm_flags,
1003                         struct anon_vma *anon_vma, struct file *file,
1004                         pgoff_t pgoff, struct mempolicy *policy,
1005                         const char __user *anon_name)
1006 {
1007         pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1008         struct vm_area_struct *area, *next;
1009         int err;
1010
1011         /*
1012          * We later require that vma->vm_flags == vm_flags,
1013          * so this tests vma->vm_flags & VM_SPECIAL, too.
1014          */
1015         if (vm_flags & VM_SPECIAL)
1016                 return NULL;
1017
1018         if (prev)
1019                 next = prev->vm_next;
1020         else
1021                 next = mm->mmap;
1022         area = next;
1023         if (next && next->vm_end == end)                /* cases 6, 7, 8 */
1024                 next = next->vm_next;
1025
1026         /*
1027          * Can it merge with the predecessor?
1028          */
1029         if (prev && prev->vm_end == addr &&
1030                         mpol_equal(vma_policy(prev), policy) &&
1031                         can_vma_merge_after(prev, vm_flags, anon_vma,
1032                                                 file, pgoff, anon_name)) {
1033                 /*
1034                  * OK, it can.  Can we now merge in the successor as well?
1035                  */
1036                 if (next && end == next->vm_start &&
1037                                 mpol_equal(policy, vma_policy(next)) &&
1038                                 can_vma_merge_before(next, vm_flags, anon_vma,
1039                                                 file, pgoff+pglen, anon_name) &&
1040                                 is_mergeable_anon_vma(prev->anon_vma,
1041                                                       next->anon_vma, NULL)) {
1042                                                         /* cases 1, 6 */
1043                         err = vma_adjust(prev, prev->vm_start,
1044                                 next->vm_end, prev->vm_pgoff, NULL);
1045                 } else                                  /* cases 2, 5, 7 */
1046                         err = vma_adjust(prev, prev->vm_start,
1047                                 end, prev->vm_pgoff, NULL);
1048                 if (err)
1049                         return NULL;
1050                 khugepaged_enter_vma_merge(prev);
1051                 return prev;
1052         }
1053
1054         /*
1055          * Can this new request be merged in front of next?
1056          */
1057         if (next && end == next->vm_start &&
1058                         mpol_equal(policy, vma_policy(next)) &&
1059                         can_vma_merge_before(next, vm_flags, anon_vma,
1060                                         file, pgoff+pglen, anon_name)) {
1061                 if (prev && addr < prev->vm_end)        /* case 4 */
1062                         err = vma_adjust(prev, prev->vm_start,
1063                                 addr, prev->vm_pgoff, NULL);
1064                 else                                    /* cases 3, 8 */
1065                         err = vma_adjust(area, addr, next->vm_end,
1066                                 next->vm_pgoff - pglen, NULL);
1067                 if (err)
1068                         return NULL;
1069                 khugepaged_enter_vma_merge(area);
1070                 return area;
1071         }
1072
1073         return NULL;
1074 }
1075
1076 /*
1077  * Rough compatbility check to quickly see if it's even worth looking
1078  * at sharing an anon_vma.
1079  *
1080  * They need to have the same vm_file, and the flags can only differ
1081  * in things that mprotect may change.
1082  *
1083  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1084  * we can merge the two vma's. For example, we refuse to merge a vma if
1085  * there is a vm_ops->close() function, because that indicates that the
1086  * driver is doing some kind of reference counting. But that doesn't
1087  * really matter for the anon_vma sharing case.
1088  */
1089 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1090 {
1091         return a->vm_end == b->vm_start &&
1092                 mpol_equal(vma_policy(a), vma_policy(b)) &&
1093                 a->vm_file == b->vm_file &&
1094                 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC)) &&
1095                 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1096 }
1097
1098 /*
1099  * Do some basic sanity checking to see if we can re-use the anon_vma
1100  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1101  * the same as 'old', the other will be the new one that is trying
1102  * to share the anon_vma.
1103  *
1104  * NOTE! This runs with mm_sem held for reading, so it is possible that
1105  * the anon_vma of 'old' is concurrently in the process of being set up
1106  * by another page fault trying to merge _that_. But that's ok: if it
1107  * is being set up, that automatically means that it will be a singleton
1108  * acceptable for merging, so we can do all of this optimistically. But
1109  * we do that ACCESS_ONCE() to make sure that we never re-load the pointer.
1110  *
1111  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1112  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1113  * is to return an anon_vma that is "complex" due to having gone through
1114  * a fork).
1115  *
1116  * We also make sure that the two vma's are compatible (adjacent,
1117  * and with the same memory policies). That's all stable, even with just
1118  * a read lock on the mm_sem.
1119  */
1120 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1121 {
1122         if (anon_vma_compatible(a, b)) {
1123                 struct anon_vma *anon_vma = ACCESS_ONCE(old->anon_vma);
1124
1125                 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1126                         return anon_vma;
1127         }
1128         return NULL;
1129 }
1130
1131 /*
1132  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1133  * neighbouring vmas for a suitable anon_vma, before it goes off
1134  * to allocate a new anon_vma.  It checks because a repetitive
1135  * sequence of mprotects and faults may otherwise lead to distinct
1136  * anon_vmas being allocated, preventing vma merge in subsequent
1137  * mprotect.
1138  */
1139 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1140 {
1141         struct anon_vma *anon_vma;
1142         struct vm_area_struct *near;
1143
1144         near = vma->vm_next;
1145         if (!near)
1146                 goto try_prev;
1147
1148         anon_vma = reusable_anon_vma(near, vma, near);
1149         if (anon_vma)
1150                 return anon_vma;
1151 try_prev:
1152         near = vma->vm_prev;
1153         if (!near)
1154                 goto none;
1155
1156         anon_vma = reusable_anon_vma(near, near, vma);
1157         if (anon_vma)
1158                 return anon_vma;
1159 none:
1160         /*
1161          * There's no absolute need to look only at touching neighbours:
1162          * we could search further afield for "compatible" anon_vmas.
1163          * But it would probably just be a waste of time searching,
1164          * or lead to too many vmas hanging off the same anon_vma.
1165          * We're trying to allow mprotect remerging later on,
1166          * not trying to minimize memory used for anon_vmas.
1167          */
1168         return NULL;
1169 }
1170
1171 #ifdef CONFIG_PROC_FS
1172 void vm_stat_account(struct mm_struct *mm, unsigned long flags,
1173                                                 struct file *file, long pages)
1174 {
1175         const unsigned long stack_flags
1176                 = VM_STACK_FLAGS & (VM_GROWSUP|VM_GROWSDOWN);
1177
1178         mm->total_vm += pages;
1179
1180         if (file) {
1181                 mm->shared_vm += pages;
1182                 if ((flags & (VM_EXEC|VM_WRITE)) == VM_EXEC)
1183                         mm->exec_vm += pages;
1184         } else if (flags & stack_flags)
1185                 mm->stack_vm += pages;
1186 }
1187 #endif /* CONFIG_PROC_FS */
1188
1189 /*
1190  * If a hint addr is less than mmap_min_addr change hint to be as
1191  * low as possible but still greater than mmap_min_addr
1192  */
1193 static inline unsigned long round_hint_to_min(unsigned long hint)
1194 {
1195         hint &= PAGE_MASK;
1196         if (((void *)hint != NULL) &&
1197             (hint < mmap_min_addr))
1198                 return PAGE_ALIGN(mmap_min_addr);
1199         return hint;
1200 }
1201
1202 /*
1203  * The caller must hold down_write(&current->mm->mmap_sem).
1204  */
1205
1206 unsigned long do_mmap_pgoff(struct file *file, unsigned long addr,
1207                         unsigned long len, unsigned long prot,
1208                         unsigned long flags, unsigned long pgoff,
1209                         unsigned long *populate)
1210 {
1211         struct mm_struct * mm = current->mm;
1212         struct inode *inode;
1213         vm_flags_t vm_flags;
1214
1215         *populate = 0;
1216
1217         /*
1218          * Does the application expect PROT_READ to imply PROT_EXEC?
1219          *
1220          * (the exception is when the underlying filesystem is noexec
1221          *  mounted, in which case we dont add PROT_EXEC.)
1222          */
1223         if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1224                 if (!(file && (file->f_path.mnt->mnt_flags & MNT_NOEXEC)))
1225                         prot |= PROT_EXEC;
1226
1227         if (!len)
1228                 return -EINVAL;
1229
1230         if (!(flags & MAP_FIXED))
1231                 addr = round_hint_to_min(addr);
1232
1233         /* Careful about overflows.. */
1234         len = PAGE_ALIGN(len);
1235         if (!len)
1236                 return -ENOMEM;
1237
1238         /* offset overflow? */
1239         if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1240                return -EOVERFLOW;
1241
1242         /* Too many mappings? */
1243         if (mm->map_count > sysctl_max_map_count)
1244                 return -ENOMEM;
1245
1246         /* Obtain the address to map to. we verify (or select) it and ensure
1247          * that it represents a valid section of the address space.
1248          */
1249         addr = get_unmapped_area(file, addr, len, pgoff, flags);
1250         if (addr & ~PAGE_MASK)
1251                 return addr;
1252
1253         /* Do simple checking here so the lower-level routines won't have
1254          * to. we assume access permissions have been handled by the open
1255          * of the memory object, so we don't do any here.
1256          */
1257         vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
1258                         mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1259
1260         if (flags & MAP_LOCKED)
1261                 if (!can_do_mlock())
1262                         return -EPERM;
1263
1264         /* mlock MCL_FUTURE? */
1265         if (vm_flags & VM_LOCKED) {
1266                 unsigned long locked, lock_limit;
1267                 locked = len >> PAGE_SHIFT;
1268                 locked += mm->locked_vm;
1269                 lock_limit = rlimit(RLIMIT_MEMLOCK);
1270                 lock_limit >>= PAGE_SHIFT;
1271                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1272                         return -EAGAIN;
1273         }
1274
1275         inode = file ? file_inode(file) : NULL;
1276
1277         if (file) {
1278                 switch (flags & MAP_TYPE) {
1279                 case MAP_SHARED:
1280                         if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1281                                 return -EACCES;
1282
1283                         /*
1284                          * Make sure we don't allow writing to an append-only
1285                          * file..
1286                          */
1287                         if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1288                                 return -EACCES;
1289
1290                         /*
1291                          * Make sure there are no mandatory locks on the file.
1292                          */
1293                         if (locks_verify_locked(inode))
1294                                 return -EAGAIN;
1295
1296                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1297                         if (!(file->f_mode & FMODE_WRITE))
1298                                 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1299
1300                         /* fall through */
1301                 case MAP_PRIVATE:
1302                         if (!(file->f_mode & FMODE_READ))
1303                                 return -EACCES;
1304                         if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
1305                                 if (vm_flags & VM_EXEC)
1306                                         return -EPERM;
1307                                 vm_flags &= ~VM_MAYEXEC;
1308                         }
1309
1310                         if (!file->f_op || !file->f_op->mmap)
1311                                 return -ENODEV;
1312                         break;
1313
1314                 default:
1315                         return -EINVAL;
1316                 }
1317         } else {
1318                 switch (flags & MAP_TYPE) {
1319                 case MAP_SHARED:
1320                         /*
1321                          * Ignore pgoff.
1322                          */
1323                         pgoff = 0;
1324                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1325                         break;
1326                 case MAP_PRIVATE:
1327                         /*
1328                          * Set pgoff according to addr for anon_vma.
1329                          */
1330                         pgoff = addr >> PAGE_SHIFT;
1331                         break;
1332                 default:
1333                         return -EINVAL;
1334                 }
1335         }
1336
1337         /*
1338          * Set 'VM_NORESERVE' if we should not account for the
1339          * memory use of this mapping.
1340          */
1341         if (flags & MAP_NORESERVE) {
1342                 /* We honor MAP_NORESERVE if allowed to overcommit */
1343                 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1344                         vm_flags |= VM_NORESERVE;
1345
1346                 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1347                 if (file && is_file_hugepages(file))
1348                         vm_flags |= VM_NORESERVE;
1349         }
1350
1351         addr = mmap_region(file, addr, len, vm_flags, pgoff);
1352         if (!IS_ERR_VALUE(addr) &&
1353             ((vm_flags & VM_LOCKED) ||
1354              (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1355                 *populate = len;
1356         return addr;
1357 }
1358
1359 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1360                 unsigned long, prot, unsigned long, flags,
1361                 unsigned long, fd, unsigned long, pgoff)
1362 {
1363         struct file *file = NULL;
1364         unsigned long retval = -EBADF;
1365
1366         if (!(flags & MAP_ANONYMOUS)) {
1367                 audit_mmap_fd(fd, flags);
1368                 if (unlikely(flags & MAP_HUGETLB))
1369                         return -EINVAL;
1370                 file = fget(fd);
1371                 if (!file)
1372                         goto out;
1373                 if (is_file_hugepages(file))
1374                         len = ALIGN(len, huge_page_size(hstate_file(file)));
1375         } else if (flags & MAP_HUGETLB) {
1376                 struct user_struct *user = NULL;
1377                 struct hstate *hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) &
1378                                                    SHM_HUGE_MASK);
1379
1380                 if (!hs)
1381                         return -EINVAL;
1382
1383                 len = ALIGN(len, huge_page_size(hs));
1384                 /*
1385                  * VM_NORESERVE is used because the reservations will be
1386                  * taken when vm_ops->mmap() is called
1387                  * A dummy user value is used because we are not locking
1388                  * memory so no accounting is necessary
1389                  */
1390                 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1391                                 VM_NORESERVE,
1392                                 &user, HUGETLB_ANONHUGE_INODE,
1393                                 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1394                 if (IS_ERR(file))
1395                         return PTR_ERR(file);
1396         }
1397
1398         flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1399
1400         retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1401         if (file)
1402                 fput(file);
1403 out:
1404         return retval;
1405 }
1406
1407 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1408 struct mmap_arg_struct {
1409         unsigned long addr;
1410         unsigned long len;
1411         unsigned long prot;
1412         unsigned long flags;
1413         unsigned long fd;
1414         unsigned long offset;
1415 };
1416
1417 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1418 {
1419         struct mmap_arg_struct a;
1420
1421         if (copy_from_user(&a, arg, sizeof(a)))
1422                 return -EFAULT;
1423         if (a.offset & ~PAGE_MASK)
1424                 return -EINVAL;
1425
1426         return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1427                               a.offset >> PAGE_SHIFT);
1428 }
1429 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1430
1431 /*
1432  * Some shared mappigns will want the pages marked read-only
1433  * to track write events. If so, we'll downgrade vm_page_prot
1434  * to the private version (using protection_map[] without the
1435  * VM_SHARED bit).
1436  */
1437 int vma_wants_writenotify(struct vm_area_struct *vma)
1438 {
1439         vm_flags_t vm_flags = vma->vm_flags;
1440
1441         /* If it was private or non-writable, the write bit is already clear */
1442         if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1443                 return 0;
1444
1445         /* The backer wishes to know when pages are first written to? */
1446         if (vma->vm_ops && vma->vm_ops->page_mkwrite)
1447                 return 1;
1448
1449         /* The open routine did something to the protections already? */
1450         if (pgprot_val(vma->vm_page_prot) !=
1451             pgprot_val(vm_get_page_prot(vm_flags)))
1452                 return 0;
1453
1454         /* Specialty mapping? */
1455         if (vm_flags & VM_PFNMAP)
1456                 return 0;
1457
1458         /* Can the mapping track the dirty pages? */
1459         return vma->vm_file && vma->vm_file->f_mapping &&
1460                 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1461 }
1462
1463 /*
1464  * We account for memory if it's a private writeable mapping,
1465  * not hugepages and VM_NORESERVE wasn't set.
1466  */
1467 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1468 {
1469         /*
1470          * hugetlb has its own accounting separate from the core VM
1471          * VM_HUGETLB may not be set yet so we cannot check for that flag.
1472          */
1473         if (file && is_file_hugepages(file))
1474                 return 0;
1475
1476         return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1477 }
1478
1479 unsigned long mmap_region(struct file *file, unsigned long addr,
1480                 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff)
1481 {
1482         struct mm_struct *mm = current->mm;
1483         struct vm_area_struct *vma, *prev;
1484         int correct_wcount = 0;
1485         int error;
1486         struct rb_node **rb_link, *rb_parent;
1487         unsigned long charged = 0;
1488         struct inode *inode =  file ? file_inode(file) : NULL;
1489
1490         /* Check against address space limit. */
1491         if (!may_expand_vm(mm, len >> PAGE_SHIFT)) {
1492                 unsigned long nr_pages;
1493
1494                 /*
1495                  * MAP_FIXED may remove pages of mappings that intersects with
1496                  * requested mapping. Account for the pages it would unmap.
1497                  */
1498                 if (!(vm_flags & MAP_FIXED))
1499                         return -ENOMEM;
1500
1501                 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1502
1503                 if (!may_expand_vm(mm, (len >> PAGE_SHIFT) - nr_pages))
1504                         return -ENOMEM;
1505         }
1506
1507         /* Clear old maps */
1508         error = -ENOMEM;
1509 munmap_back:
1510         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {
1511                 if (do_munmap(mm, addr, len))
1512                         return -ENOMEM;
1513                 goto munmap_back;
1514         }
1515
1516         /*
1517          * Private writable mapping: check memory availability
1518          */
1519         if (accountable_mapping(file, vm_flags)) {
1520                 charged = len >> PAGE_SHIFT;
1521                 if (security_vm_enough_memory_mm(mm, charged))
1522                         return -ENOMEM;
1523                 vm_flags |= VM_ACCOUNT;
1524         }
1525
1526         /*
1527          * Can we just expand an old mapping?
1528          */
1529         vma = vma_merge(mm, prev, addr, addr + len, vm_flags, NULL, file, pgoff,
1530                         NULL, NULL);
1531         if (vma)
1532                 goto out;
1533
1534         /*
1535          * Determine the object being mapped and call the appropriate
1536          * specific mapper. the address has already been validated, but
1537          * not unmapped, but the maps are removed from the list.
1538          */
1539         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1540         if (!vma) {
1541                 error = -ENOMEM;
1542                 goto unacct_error;
1543         }
1544
1545         vma->vm_mm = mm;
1546         vma->vm_start = addr;
1547         vma->vm_end = addr + len;
1548         vma->vm_flags = vm_flags;
1549         vma->vm_page_prot = vm_get_page_prot(vm_flags);
1550         vma->vm_pgoff = pgoff;
1551         INIT_LIST_HEAD(&vma->anon_vma_chain);
1552
1553         error = -EINVAL;        /* when rejecting VM_GROWSDOWN|VM_GROWSUP */
1554
1555         if (file) {
1556                 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1557                         goto free_vma;
1558                 if (vm_flags & VM_DENYWRITE) {
1559                         error = deny_write_access(file);
1560                         if (error)
1561                                 goto free_vma;
1562                         correct_wcount = 1;
1563                 }
1564                 vma->vm_file = get_file(file);
1565                 error = file->f_op->mmap(file, vma);
1566                 if (error)
1567                         goto unmap_and_free_vma;
1568
1569                 /* Can addr have changed??
1570                  *
1571                  * Answer: Yes, several device drivers can do it in their
1572                  *         f_op->mmap method. -DaveM
1573                  * Bug: If addr is changed, prev, rb_link, rb_parent should
1574                  *      be updated for vma_link()
1575                  */
1576                 WARN_ON_ONCE(addr != vma->vm_start);
1577
1578                 addr = vma->vm_start;
1579                 pgoff = vma->vm_pgoff;
1580                 vm_flags = vma->vm_flags;
1581         } else if (vm_flags & VM_SHARED) {
1582                 if (unlikely(vm_flags & (VM_GROWSDOWN|VM_GROWSUP)))
1583                         goto free_vma;
1584                 error = shmem_zero_setup(vma);
1585                 if (error)
1586                         goto free_vma;
1587         }
1588
1589         if (vma_wants_writenotify(vma)) {
1590                 pgprot_t pprot = vma->vm_page_prot;
1591
1592                 /* Can vma->vm_page_prot have changed??
1593                  *
1594                  * Answer: Yes, drivers may have changed it in their
1595                  *         f_op->mmap method.
1596                  *
1597                  * Ensures that vmas marked as uncached stay that way.
1598                  */
1599                 vma->vm_page_prot = vm_get_page_prot(vm_flags & ~VM_SHARED);
1600                 if (pgprot_val(pprot) == pgprot_val(pgprot_noncached(pprot)))
1601                         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1602         }
1603
1604         vma_link(mm, vma, prev, rb_link, rb_parent);
1605         file = vma->vm_file;
1606
1607         /* Once vma denies write, undo our temporary denial count */
1608         if (correct_wcount)
1609                 atomic_inc(&inode->i_writecount);
1610 out:
1611         perf_event_mmap(vma);
1612         quadd_event_mmap(vma);
1613
1614         vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1615         if (vm_flags & VM_LOCKED) {
1616                 if (!((vm_flags & VM_SPECIAL) || is_vm_hugetlb_page(vma) ||
1617                                         vma == get_gate_vma(current->mm)))
1618                         mm->locked_vm += (len >> PAGE_SHIFT);
1619                 else
1620                         vma->vm_flags &= ~VM_LOCKED;
1621         }
1622
1623         if (file)
1624                 uprobe_mmap(vma);
1625
1626         return addr;
1627
1628 unmap_and_free_vma:
1629         if (correct_wcount)
1630                 atomic_inc(&inode->i_writecount);
1631         vma->vm_file = NULL;
1632         fput(file);
1633
1634         /* Undo any partial mapping done by a device driver. */
1635         unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1636         charged = 0;
1637 free_vma:
1638         kmem_cache_free(vm_area_cachep, vma);
1639 unacct_error:
1640         if (charged)
1641                 vm_unacct_memory(charged);
1642         return error;
1643 }
1644
1645 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1646 {
1647         /*
1648          * We implement the search by looking for an rbtree node that
1649          * immediately follows a suitable gap. That is,
1650          * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1651          * - gap_end   = vma->vm_start        >= info->low_limit  + length;
1652          * - gap_end - gap_start >= length
1653          */
1654
1655         struct mm_struct *mm = current->mm;
1656         struct vm_area_struct *vma;
1657         unsigned long length, low_limit, high_limit, gap_start, gap_end;
1658
1659         /* Adjust search length to account for worst case alignment overhead */
1660         length = info->length + info->align_mask;
1661         if (length < info->length)
1662                 return -ENOMEM;
1663
1664         /* Adjust search limits by the desired length */
1665         if (info->high_limit < length)
1666                 return -ENOMEM;
1667         high_limit = info->high_limit - length;
1668
1669         if (info->low_limit > high_limit)
1670                 return -ENOMEM;
1671         low_limit = info->low_limit + length;
1672
1673         /* Check if rbtree root looks promising */
1674         if (RB_EMPTY_ROOT(&mm->mm_rb))
1675                 goto check_highest;
1676         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1677         if (vma->rb_subtree_gap < length)
1678                 goto check_highest;
1679
1680         while (true) {
1681                 /* Visit left subtree if it looks promising */
1682                 gap_end = vma->vm_start;
1683                 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1684                         struct vm_area_struct *left =
1685                                 rb_entry(vma->vm_rb.rb_left,
1686                                          struct vm_area_struct, vm_rb);
1687                         if (left->rb_subtree_gap >= length) {
1688                                 vma = left;
1689                                 continue;
1690                         }
1691                 }
1692
1693                 gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
1694 check_current:
1695                 /* Check if current node has a suitable gap */
1696                 if (gap_start > high_limit)
1697                         return -ENOMEM;
1698                 if (gap_end >= low_limit && gap_end - gap_start >= length)
1699                         goto found;
1700
1701                 /* Visit right subtree if it looks promising */
1702                 if (vma->vm_rb.rb_right) {
1703                         struct vm_area_struct *right =
1704                                 rb_entry(vma->vm_rb.rb_right,
1705                                          struct vm_area_struct, vm_rb);
1706                         if (right->rb_subtree_gap >= length) {
1707                                 vma = right;
1708                                 continue;
1709                         }
1710                 }
1711
1712                 /* Go back up the rbtree to find next candidate node */
1713                 while (true) {
1714                         struct rb_node *prev = &vma->vm_rb;
1715                         if (!rb_parent(prev))
1716                                 goto check_highest;
1717                         vma = rb_entry(rb_parent(prev),
1718                                        struct vm_area_struct, vm_rb);
1719                         if (prev == vma->vm_rb.rb_left) {
1720                                 gap_start = vma->vm_prev->vm_end;
1721                                 gap_end = vma->vm_start;
1722                                 goto check_current;
1723                         }
1724                 }
1725         }
1726
1727 check_highest:
1728         /* Check highest gap, which does not precede any rbtree node */
1729         gap_start = mm->highest_vm_end;
1730         gap_end = ULONG_MAX;  /* Only for VM_BUG_ON below */
1731         if (gap_start > high_limit)
1732                 return -ENOMEM;
1733
1734 found:
1735         /* We found a suitable gap. Clip it with the original low_limit. */
1736         if (gap_start < info->low_limit)
1737                 gap_start = info->low_limit;
1738
1739         /* Adjust gap address to the desired alignment */
1740         gap_start += (info->align_offset - gap_start) & info->align_mask;
1741
1742         VM_BUG_ON(gap_start + info->length > info->high_limit);
1743         VM_BUG_ON(gap_start + info->length > gap_end);
1744         return gap_start;
1745 }
1746
1747 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1748 {
1749         struct mm_struct *mm = current->mm;
1750         struct vm_area_struct *vma;
1751         unsigned long length, low_limit, high_limit, gap_start, gap_end;
1752
1753         /* Adjust search length to account for worst case alignment overhead */
1754         length = info->length + info->align_mask;
1755         if (length < info->length)
1756                 return -ENOMEM;
1757
1758         /*
1759          * Adjust search limits by the desired length.
1760          * See implementation comment at top of unmapped_area().
1761          */
1762         gap_end = info->high_limit;
1763         if (gap_end < length)
1764                 return -ENOMEM;
1765         high_limit = gap_end - length;
1766
1767         if (info->low_limit > high_limit)
1768                 return -ENOMEM;
1769         low_limit = info->low_limit + length;
1770
1771         /* Check highest gap, which does not precede any rbtree node */
1772         gap_start = mm->highest_vm_end;
1773         if (gap_start <= high_limit)
1774                 goto found_highest;
1775
1776         /* Check if rbtree root looks promising */
1777         if (RB_EMPTY_ROOT(&mm->mm_rb))
1778                 return -ENOMEM;
1779         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1780         if (vma->rb_subtree_gap < length)
1781                 return -ENOMEM;
1782
1783         while (true) {
1784                 /* Visit right subtree if it looks promising */
1785                 gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
1786                 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
1787                         struct vm_area_struct *right =
1788                                 rb_entry(vma->vm_rb.rb_right,
1789                                          struct vm_area_struct, vm_rb);
1790                         if (right->rb_subtree_gap >= length) {
1791                                 vma = right;
1792                                 continue;
1793                         }
1794                 }
1795
1796 check_current:
1797                 /* Check if current node has a suitable gap */
1798                 gap_end = vma->vm_start;
1799                 if (gap_end < low_limit)
1800                         return -ENOMEM;
1801                 if (gap_start <= high_limit && gap_end - gap_start >= length)
1802                         goto found;
1803
1804                 /* Visit left subtree if it looks promising */
1805                 if (vma->vm_rb.rb_left) {
1806                         struct vm_area_struct *left =
1807                                 rb_entry(vma->vm_rb.rb_left,
1808                                          struct vm_area_struct, vm_rb);
1809                         if (left->rb_subtree_gap >= length) {
1810                                 vma = left;
1811                                 continue;
1812                         }
1813                 }
1814
1815                 /* Go back up the rbtree to find next candidate node */
1816                 while (true) {
1817                         struct rb_node *prev = &vma->vm_rb;
1818                         if (!rb_parent(prev))
1819                                 return -ENOMEM;
1820                         vma = rb_entry(rb_parent(prev),
1821                                        struct vm_area_struct, vm_rb);
1822                         if (prev == vma->vm_rb.rb_right) {
1823                                 gap_start = vma->vm_prev ?
1824                                         vma->vm_prev->vm_end : 0;
1825                                 goto check_current;
1826                         }
1827                 }
1828         }
1829
1830 found:
1831         /* We found a suitable gap. Clip it with the original high_limit. */
1832         if (gap_end > info->high_limit)
1833                 gap_end = info->high_limit;
1834
1835 found_highest:
1836         /* Compute highest gap address at the desired alignment */
1837         gap_end -= info->length;
1838         gap_end -= (gap_end - info->align_offset) & info->align_mask;
1839
1840         VM_BUG_ON(gap_end < info->low_limit);
1841         VM_BUG_ON(gap_end < gap_start);
1842         return gap_end;
1843 }
1844
1845 /* Get an address range which is currently unmapped.
1846  * For shmat() with addr=0.
1847  *
1848  * Ugly calling convention alert:
1849  * Return value with the low bits set means error value,
1850  * ie
1851  *      if (ret & ~PAGE_MASK)
1852  *              error = ret;
1853  *
1854  * This function "knows" that -ENOMEM has the bits set.
1855  */
1856 #ifndef HAVE_ARCH_UNMAPPED_AREA
1857 unsigned long
1858 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1859                 unsigned long len, unsigned long pgoff, unsigned long flags)
1860 {
1861         struct mm_struct *mm = current->mm;
1862         struct vm_area_struct *vma;
1863         struct vm_unmapped_area_info info;
1864
1865         if (len > TASK_SIZE - mmap_min_addr)
1866                 return -ENOMEM;
1867
1868         if (flags & MAP_FIXED)
1869                 return addr;
1870
1871         if (addr) {
1872                 addr = PAGE_ALIGN(addr);
1873                 vma = find_vma(mm, addr);
1874                 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1875                     (!vma || addr + len <= vma->vm_start))
1876                         return addr;
1877         }
1878
1879         info.flags = 0;
1880         info.length = len;
1881         info.low_limit = mm->mmap_base;
1882         info.high_limit = TASK_SIZE;
1883         info.align_mask = 0;
1884         return vm_unmapped_area(&info);
1885 }
1886 #endif  
1887
1888 void arch_unmap_area(struct mm_struct *mm, unsigned long addr)
1889 {
1890         /*
1891          * Is this a new hole at the lowest possible address?
1892          */
1893         if (addr >= TASK_UNMAPPED_BASE && addr < mm->free_area_cache)
1894                 mm->free_area_cache = addr;
1895 }
1896
1897 /*
1898  * This mmap-allocator allocates new areas top-down from below the
1899  * stack's low limit (the base):
1900  */
1901 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1902 unsigned long
1903 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1904                           const unsigned long len, const unsigned long pgoff,
1905                           const unsigned long flags)
1906 {
1907         struct vm_area_struct *vma;
1908         struct mm_struct *mm = current->mm;
1909         unsigned long addr = addr0;
1910         struct vm_unmapped_area_info info;
1911
1912         /* requested length too big for entire address space */
1913         if (len > TASK_SIZE - mmap_min_addr)
1914                 return -ENOMEM;
1915
1916         if (flags & MAP_FIXED)
1917                 return addr;
1918
1919         /* requesting a specific address */
1920         if (addr) {
1921                 addr = PAGE_ALIGN(addr);
1922                 vma = find_vma(mm, addr);
1923                 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1924                                 (!vma || addr + len <= vma->vm_start))
1925                         return addr;
1926         }
1927
1928         info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1929         info.length = len;
1930         info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1931         info.high_limit = mm->mmap_base;
1932         info.align_mask = 0;
1933         addr = vm_unmapped_area(&info);
1934
1935         /*
1936          * A failed mmap() very likely causes application failure,
1937          * so fall back to the bottom-up function here. This scenario
1938          * can happen with large stack limits and large mmap()
1939          * allocations.
1940          */
1941         if (addr & ~PAGE_MASK) {
1942                 VM_BUG_ON(addr != -ENOMEM);
1943                 info.flags = 0;
1944                 info.low_limit = TASK_UNMAPPED_BASE;
1945                 info.high_limit = TASK_SIZE;
1946                 addr = vm_unmapped_area(&info);
1947         }
1948
1949         return addr;
1950 }
1951 #endif
1952
1953 void arch_unmap_area_topdown(struct mm_struct *mm, unsigned long addr)
1954 {
1955         /*
1956          * Is this a new hole at the highest possible address?
1957          */
1958         if (addr > mm->free_area_cache)
1959                 mm->free_area_cache = addr;
1960
1961         /* dont allow allocations above current base */
1962         if (mm->free_area_cache > mm->mmap_base)
1963                 mm->free_area_cache = mm->mmap_base;
1964 }
1965
1966 unsigned long
1967 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1968                 unsigned long pgoff, unsigned long flags)
1969 {
1970         unsigned long (*get_area)(struct file *, unsigned long,
1971                                   unsigned long, unsigned long, unsigned long);
1972
1973         unsigned long error = arch_mmap_check(addr, len, flags);
1974         if (error)
1975                 return error;
1976
1977         /* Careful about overflows.. */
1978         if (len > TASK_SIZE)
1979                 return -ENOMEM;
1980
1981         get_area = current->mm->get_unmapped_area;
1982         if (file && file->f_op && file->f_op->get_unmapped_area)
1983                 get_area = file->f_op->get_unmapped_area;
1984         addr = get_area(file, addr, len, pgoff, flags);
1985         if (IS_ERR_VALUE(addr))
1986                 return addr;
1987
1988         if (addr > TASK_SIZE - len)
1989                 return -ENOMEM;
1990         if (addr & ~PAGE_MASK)
1991                 return -EINVAL;
1992
1993         addr = arch_rebalance_pgtables(addr, len);
1994         error = security_mmap_addr(addr);
1995         return error ? error : addr;
1996 }
1997
1998 EXPORT_SYMBOL(get_unmapped_area);
1999
2000 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
2001 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2002 {
2003         struct vm_area_struct *vma = NULL;
2004
2005         /* Check the cache first. */
2006         /* (Cache hit rate is typically around 35%.) */
2007         vma = ACCESS_ONCE(mm->mmap_cache);
2008         if (!(vma && vma->vm_end > addr && vma->vm_start <= addr)) {
2009                 struct rb_node *rb_node;
2010
2011                 rb_node = mm->mm_rb.rb_node;
2012                 vma = NULL;
2013
2014                 while (rb_node) {
2015                         struct vm_area_struct *vma_tmp;
2016
2017                         vma_tmp = rb_entry(rb_node,
2018                                            struct vm_area_struct, vm_rb);
2019
2020                         if (vma_tmp->vm_end > addr) {
2021                                 vma = vma_tmp;
2022                                 if (vma_tmp->vm_start <= addr)
2023                                         break;
2024                                 rb_node = rb_node->rb_left;
2025                         } else
2026                                 rb_node = rb_node->rb_right;
2027                 }
2028                 if (vma)
2029                         mm->mmap_cache = vma;
2030         }
2031         return vma;
2032 }
2033
2034 EXPORT_SYMBOL(find_vma);
2035
2036 /*
2037  * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2038  */
2039 struct vm_area_struct *
2040 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2041                         struct vm_area_struct **pprev)
2042 {
2043         struct vm_area_struct *vma;
2044
2045         vma = find_vma(mm, addr);
2046         if (vma) {
2047                 *pprev = vma->vm_prev;
2048         } else {
2049                 struct rb_node *rb_node = mm->mm_rb.rb_node;
2050                 *pprev = NULL;
2051                 while (rb_node) {
2052                         *pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2053                         rb_node = rb_node->rb_right;
2054                 }
2055         }
2056         return vma;
2057 }
2058
2059 /*
2060  * Verify that the stack growth is acceptable and
2061  * update accounting. This is shared with both the
2062  * grow-up and grow-down cases.
2063  */
2064 static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
2065 {
2066         struct mm_struct *mm = vma->vm_mm;
2067         struct rlimit *rlim = current->signal->rlim;
2068         unsigned long new_start, actual_size;
2069
2070         /* address space limit tests */
2071         if (!may_expand_vm(mm, grow))
2072                 return -ENOMEM;
2073
2074         /* Stack limit test */
2075         actual_size = size;
2076         if (size && (vma->vm_flags & (VM_GROWSUP | VM_GROWSDOWN)))
2077                 actual_size -= PAGE_SIZE;
2078         if (actual_size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur))
2079                 return -ENOMEM;
2080
2081         /* mlock limit tests */
2082         if (vma->vm_flags & VM_LOCKED) {
2083                 unsigned long locked;
2084                 unsigned long limit;
2085                 locked = mm->locked_vm + grow;
2086                 limit = ACCESS_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
2087                 limit >>= PAGE_SHIFT;
2088                 if (locked > limit && !capable(CAP_IPC_LOCK))
2089                         return -ENOMEM;
2090         }
2091
2092         /* Check to ensure the stack will not grow into a hugetlb-only region */
2093         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2094                         vma->vm_end - size;
2095         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2096                 return -EFAULT;
2097
2098         /*
2099          * Overcommit..  This must be the final test, as it will
2100          * update security statistics.
2101          */
2102         if (security_vm_enough_memory_mm(mm, grow))
2103                 return -ENOMEM;
2104
2105         /* Ok, everything looks good - let it rip */
2106         if (vma->vm_flags & VM_LOCKED)
2107                 mm->locked_vm += grow;
2108         vm_stat_account(mm, vma->vm_flags, vma->vm_file, grow);
2109         return 0;
2110 }
2111
2112 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2113 /*
2114  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2115  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2116  */
2117 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2118 {
2119         int error;
2120
2121         if (!(vma->vm_flags & VM_GROWSUP))
2122                 return -EFAULT;
2123
2124         /*
2125          * We must make sure the anon_vma is allocated
2126          * so that the anon_vma locking is not a noop.
2127          */
2128         if (unlikely(anon_vma_prepare(vma)))
2129                 return -ENOMEM;
2130         vma_lock_anon_vma(vma);
2131
2132         /*
2133          * vma->vm_start/vm_end cannot change under us because the caller
2134          * is required to hold the mmap_sem in read mode.  We need the
2135          * anon_vma lock to serialize against concurrent expand_stacks.
2136          * Also guard against wrapping around to address 0.
2137          */
2138         if (address < PAGE_ALIGN(address+4))
2139                 address = PAGE_ALIGN(address+4);
2140         else {
2141                 vma_unlock_anon_vma(vma);
2142                 return -ENOMEM;
2143         }
2144         error = 0;
2145
2146         /* Somebody else might have raced and expanded it already */
2147         if (address > vma->vm_end) {
2148                 unsigned long size, grow;
2149
2150                 size = address - vma->vm_start;
2151                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2152
2153                 error = -ENOMEM;
2154                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2155                         error = acct_stack_growth(vma, size, grow);
2156                         if (!error) {
2157                                 /*
2158                                  * vma_gap_update() doesn't support concurrent
2159                                  * updates, but we only hold a shared mmap_sem
2160                                  * lock here, so we need to protect against
2161                                  * concurrent vma expansions.
2162                                  * vma_lock_anon_vma() doesn't help here, as
2163                                  * we don't guarantee that all growable vmas
2164                                  * in a mm share the same root anon vma.
2165                                  * So, we reuse mm->page_table_lock to guard
2166                                  * against concurrent vma expansions.
2167                                  */
2168                                 spin_lock(&vma->vm_mm->page_table_lock);
2169                                 anon_vma_interval_tree_pre_update_vma(vma);
2170                                 vma->vm_end = address;
2171                                 anon_vma_interval_tree_post_update_vma(vma);
2172                                 if (vma->vm_next)
2173                                         vma_gap_update(vma->vm_next);
2174                                 else
2175                                         vma->vm_mm->highest_vm_end = address;
2176                                 spin_unlock(&vma->vm_mm->page_table_lock);
2177
2178                                 perf_event_mmap(vma);
2179                                 quadd_event_mmap(vma);
2180                         }
2181                 }
2182         }
2183         vma_unlock_anon_vma(vma);
2184         khugepaged_enter_vma_merge(vma);
2185         validate_mm(vma->vm_mm);
2186         return error;
2187 }
2188 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2189
2190 /*
2191  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2192  */
2193 int expand_downwards(struct vm_area_struct *vma,
2194                                    unsigned long address)
2195 {
2196         int error;
2197
2198         /*
2199          * We must make sure the anon_vma is allocated
2200          * so that the anon_vma locking is not a noop.
2201          */
2202         if (unlikely(anon_vma_prepare(vma)))
2203                 return -ENOMEM;
2204
2205         address &= PAGE_MASK;
2206         error = security_mmap_addr(address);
2207         if (error)
2208                 return error;
2209
2210         vma_lock_anon_vma(vma);
2211
2212         /*
2213          * vma->vm_start/vm_end cannot change under us because the caller
2214          * is required to hold the mmap_sem in read mode.  We need the
2215          * anon_vma lock to serialize against concurrent expand_stacks.
2216          */
2217
2218         /* Somebody else might have raced and expanded it already */
2219         if (address < vma->vm_start) {
2220                 unsigned long size, grow;
2221
2222                 size = vma->vm_end - address;
2223                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2224
2225                 error = -ENOMEM;
2226                 if (grow <= vma->vm_pgoff) {
2227                         error = acct_stack_growth(vma, size, grow);
2228                         if (!error) {
2229                                 /*
2230                                  * vma_gap_update() doesn't support concurrent
2231                                  * updates, but we only hold a shared mmap_sem
2232                                  * lock here, so we need to protect against
2233                                  * concurrent vma expansions.
2234                                  * vma_lock_anon_vma() doesn't help here, as
2235                                  * we don't guarantee that all growable vmas
2236                                  * in a mm share the same root anon vma.
2237                                  * So, we reuse mm->page_table_lock to guard
2238                                  * against concurrent vma expansions.
2239                                  */
2240                                 spin_lock(&vma->vm_mm->page_table_lock);
2241                                 anon_vma_interval_tree_pre_update_vma(vma);
2242                                 vma->vm_start = address;
2243                                 vma->vm_pgoff -= grow;
2244                                 anon_vma_interval_tree_post_update_vma(vma);
2245                                 vma_gap_update(vma);
2246                                 spin_unlock(&vma->vm_mm->page_table_lock);
2247
2248                                 perf_event_mmap(vma);
2249                                 quadd_event_mmap(vma);
2250                         }
2251                 }
2252         }
2253         vma_unlock_anon_vma(vma);
2254         khugepaged_enter_vma_merge(vma);
2255         validate_mm(vma->vm_mm);
2256         return error;
2257 }
2258
2259 /*
2260  * Note how expand_stack() refuses to expand the stack all the way to
2261  * abut the next virtual mapping, *unless* that mapping itself is also
2262  * a stack mapping. We want to leave room for a guard page, after all
2263  * (the guard page itself is not added here, that is done by the
2264  * actual page faulting logic)
2265  *
2266  * This matches the behavior of the guard page logic (see mm/memory.c:
2267  * check_stack_guard_page()), which only allows the guard page to be
2268  * removed under these circumstances.
2269  */
2270 #ifdef CONFIG_STACK_GROWSUP
2271 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2272 {
2273         struct vm_area_struct *next;
2274
2275         address &= PAGE_MASK;
2276         next = vma->vm_next;
2277         if (next && next->vm_start == address + PAGE_SIZE) {
2278                 if (!(next->vm_flags & VM_GROWSUP))
2279                         return -ENOMEM;
2280         }
2281         return expand_upwards(vma, address);
2282 }
2283
2284 struct vm_area_struct *
2285 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2286 {
2287         struct vm_area_struct *vma, *prev;
2288
2289         addr &= PAGE_MASK;
2290         vma = find_vma_prev(mm, addr, &prev);
2291         if (vma && (vma->vm_start <= addr))
2292                 return vma;
2293         if (!prev || expand_stack(prev, addr))
2294                 return NULL;
2295         if (prev->vm_flags & VM_LOCKED)
2296                 __mlock_vma_pages_range(prev, addr, prev->vm_end, NULL);
2297         return prev;
2298 }
2299 #else
2300 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2301 {
2302         struct vm_area_struct *prev;
2303
2304         address &= PAGE_MASK;
2305         prev = vma->vm_prev;
2306         if (prev && prev->vm_end == address) {
2307                 if (!(prev->vm_flags & VM_GROWSDOWN))
2308                         return -ENOMEM;
2309         }
2310         return expand_downwards(vma, address);
2311 }
2312
2313 struct vm_area_struct *
2314 find_extend_vma(struct mm_struct * mm, unsigned long addr)
2315 {
2316         struct vm_area_struct * vma;
2317         unsigned long start;
2318
2319         addr &= PAGE_MASK;
2320         vma = find_vma(mm,addr);
2321         if (!vma)
2322                 return NULL;
2323         if (vma->vm_start <= addr)
2324                 return vma;
2325         if (!(vma->vm_flags & VM_GROWSDOWN))
2326                 return NULL;
2327         start = vma->vm_start;
2328         if (expand_stack(vma, addr))
2329                 return NULL;
2330         if (vma->vm_flags & VM_LOCKED)
2331                 __mlock_vma_pages_range(vma, addr, start, NULL);
2332         return vma;
2333 }
2334 #endif
2335
2336 /*
2337  * Ok - we have the memory areas we should free on the vma list,
2338  * so release them, and do the vma updates.
2339  *
2340  * Called with the mm semaphore held.
2341  */
2342 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2343 {
2344         unsigned long nr_accounted = 0;
2345
2346         /* Update high watermark before we lower total_vm */
2347         update_hiwater_vm(mm);
2348         do {
2349                 long nrpages = vma_pages(vma);
2350
2351                 if (vma->vm_flags & VM_ACCOUNT)
2352                         nr_accounted += nrpages;
2353                 vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
2354                 vma = remove_vma(vma);
2355         } while (vma);
2356         vm_unacct_memory(nr_accounted);
2357         validate_mm(mm);
2358 }
2359
2360 /*
2361  * Get rid of page table information in the indicated region.
2362  *
2363  * Called with the mm semaphore held.
2364  */
2365 static void unmap_region(struct mm_struct *mm,
2366                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2367                 unsigned long start, unsigned long end)
2368 {
2369         struct vm_area_struct *next = prev? prev->vm_next: mm->mmap;
2370         struct mmu_gather tlb;
2371
2372         lru_add_drain();
2373         tlb_gather_mmu(&tlb, mm, start, end);
2374         update_hiwater_rss(mm);
2375         unmap_vmas(&tlb, vma, start, end);
2376         free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2377                                  next ? next->vm_start : USER_PGTABLES_CEILING);
2378         tlb_finish_mmu(&tlb, start, end);
2379 }
2380
2381 /*
2382  * Create a list of vma's touched by the unmap, removing them from the mm's
2383  * vma list as we go..
2384  */
2385 static void
2386 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2387         struct vm_area_struct *prev, unsigned long end)
2388 {
2389         struct vm_area_struct **insertion_point;
2390         struct vm_area_struct *tail_vma = NULL;
2391         unsigned long addr;
2392
2393         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2394         vma->vm_prev = NULL;
2395         do {
2396                 vma_rb_erase(vma, &mm->mm_rb);
2397                 mm->map_count--;
2398                 tail_vma = vma;
2399                 vma = vma->vm_next;
2400         } while (vma && vma->vm_start < end);
2401         *insertion_point = vma;
2402         if (vma) {
2403                 vma->vm_prev = prev;
2404                 vma_gap_update(vma);
2405         } else
2406                 mm->highest_vm_end = prev ? prev->vm_end : 0;
2407         tail_vma->vm_next = NULL;
2408         if (mm->unmap_area == arch_unmap_area)
2409                 addr = prev ? prev->vm_end : mm->mmap_base;
2410         else
2411                 addr = vma ?  vma->vm_start : mm->mmap_base;
2412         mm->unmap_area(mm, addr);
2413         mm->mmap_cache = NULL;          /* Kill the cache. */
2414 }
2415
2416 /*
2417  * __split_vma() bypasses sysctl_max_map_count checking.  We use this on the
2418  * munmap path where it doesn't make sense to fail.
2419  */
2420 static int __split_vma(struct mm_struct * mm, struct vm_area_struct * vma,
2421               unsigned long addr, int new_below)
2422 {
2423         struct mempolicy *pol;
2424         struct vm_area_struct *new;
2425         int err = -ENOMEM;
2426
2427         if (is_vm_hugetlb_page(vma) && (addr &
2428                                         ~(huge_page_mask(hstate_vma(vma)))))
2429                 return -EINVAL;
2430
2431         new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2432         if (!new)
2433                 goto out_err;
2434
2435         /* most fields are the same, copy all, and then fixup */
2436         *new = *vma;
2437
2438         INIT_LIST_HEAD(&new->anon_vma_chain);
2439
2440         if (new_below)
2441                 new->vm_end = addr;
2442         else {
2443                 new->vm_start = addr;
2444                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2445         }
2446
2447         pol = mpol_dup(vma_policy(vma));
2448         if (IS_ERR(pol)) {
2449                 err = PTR_ERR(pol);
2450                 goto out_free_vma;
2451         }
2452         vma_set_policy(new, pol);
2453
2454         if (anon_vma_clone(new, vma))
2455                 goto out_free_mpol;
2456
2457         if (new->vm_file)
2458                 get_file(new->vm_file);
2459
2460         if (new->vm_ops && new->vm_ops->open)
2461                 new->vm_ops->open(new);
2462
2463         if (new_below)
2464                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2465                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2466         else
2467                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2468
2469         /* Success. */
2470         if (!err)
2471                 return 0;
2472
2473         /* Clean everything up if vma_adjust failed. */
2474         if (new->vm_ops && new->vm_ops->close)
2475                 new->vm_ops->close(new);
2476         if (new->vm_file)
2477                 fput(new->vm_file);
2478         unlink_anon_vmas(new);
2479  out_free_mpol:
2480         mpol_put(pol);
2481  out_free_vma:
2482         kmem_cache_free(vm_area_cachep, new);
2483  out_err:
2484         return err;
2485 }
2486
2487 /*
2488  * Split a vma into two pieces at address 'addr', a new vma is allocated
2489  * either for the first part or the tail.
2490  */
2491 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2492               unsigned long addr, int new_below)
2493 {
2494         if (mm->map_count >= sysctl_max_map_count)
2495                 return -ENOMEM;
2496
2497         return __split_vma(mm, vma, addr, new_below);
2498 }
2499
2500 /* Munmap is split into 2 main parts -- this part which finds
2501  * what needs doing, and the areas themselves, which do the
2502  * work.  This now handles partial unmappings.
2503  * Jeremy Fitzhardinge <jeremy@goop.org>
2504  */
2505 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2506 {
2507         unsigned long end;
2508         struct vm_area_struct *vma, *prev, *last;
2509
2510         if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
2511                 return -EINVAL;
2512
2513         if ((len = PAGE_ALIGN(len)) == 0)
2514                 return -EINVAL;
2515
2516         /* Find the first overlapping VMA */
2517         vma = find_vma(mm, start);
2518         if (!vma)
2519                 return 0;
2520         prev = vma->vm_prev;
2521         /* we have  start < vma->vm_end  */
2522
2523         /* if it doesn't overlap, we have nothing.. */
2524         end = start + len;
2525         if (vma->vm_start >= end)
2526                 return 0;
2527
2528         /*
2529          * If we need to split any vma, do it now to save pain later.
2530          *
2531          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2532          * unmapped vm_area_struct will remain in use: so lower split_vma
2533          * places tmp vma above, and higher split_vma places tmp vma below.
2534          */
2535         if (start > vma->vm_start) {
2536                 int error;
2537
2538                 /*
2539                  * Make sure that map_count on return from munmap() will
2540                  * not exceed its limit; but let map_count go just above
2541                  * its limit temporarily, to help free resources as expected.
2542                  */
2543                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2544                         return -ENOMEM;
2545
2546                 error = __split_vma(mm, vma, start, 0);
2547                 if (error)
2548                         return error;
2549                 prev = vma;
2550         }
2551
2552         /* Does it split the last one? */
2553         last = find_vma(mm, end);
2554         if (last && end > last->vm_start) {
2555                 int error = __split_vma(mm, last, end, 1);
2556                 if (error)
2557                         return error;
2558         }
2559         vma = prev? prev->vm_next: mm->mmap;
2560
2561         /*
2562          * unlock any mlock()ed ranges before detaching vmas
2563          */
2564         if (mm->locked_vm) {
2565                 struct vm_area_struct *tmp = vma;
2566                 while (tmp && tmp->vm_start < end) {
2567                         if (tmp->vm_flags & VM_LOCKED) {
2568                                 mm->locked_vm -= vma_pages(tmp);
2569                                 munlock_vma_pages_all(tmp);
2570                         }
2571                         tmp = tmp->vm_next;
2572                 }
2573         }
2574
2575         /*
2576          * Remove the vma's, and unmap the actual pages
2577          */
2578         detach_vmas_to_be_unmapped(mm, vma, prev, end);
2579         unmap_region(mm, vma, prev, start, end);
2580
2581         /* Fix up all other VM information */
2582         remove_vma_list(mm, vma);
2583
2584         return 0;
2585 }
2586
2587 int vm_munmap(unsigned long start, size_t len)
2588 {
2589         int ret;
2590         struct mm_struct *mm = current->mm;
2591
2592         down_write(&mm->mmap_sem);
2593         ret = do_munmap(mm, start, len);
2594         up_write(&mm->mmap_sem);
2595         return ret;
2596 }
2597 EXPORT_SYMBOL(vm_munmap);
2598
2599 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2600 {
2601         profile_munmap(addr);
2602         return vm_munmap(addr, len);
2603 }
2604
2605 static inline void verify_mm_writelocked(struct mm_struct *mm)
2606 {
2607 #ifdef CONFIG_DEBUG_VM
2608         if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2609                 WARN_ON(1);
2610                 up_read(&mm->mmap_sem);
2611         }
2612 #endif
2613 }
2614
2615 /*
2616  *  this is really a simplified "do_mmap".  it only handles
2617  *  anonymous maps.  eventually we may be able to do some
2618  *  brk-specific accounting here.
2619  */
2620 static unsigned long do_brk(unsigned long addr, unsigned long len)
2621 {
2622         struct mm_struct * mm = current->mm;
2623         struct vm_area_struct * vma, * prev;
2624         unsigned long flags;
2625         struct rb_node ** rb_link, * rb_parent;
2626         pgoff_t pgoff = addr >> PAGE_SHIFT;
2627         int error;
2628
2629         len = PAGE_ALIGN(len);
2630         if (!len)
2631                 return addr;
2632
2633         flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2634
2635         error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2636         if (error & ~PAGE_MASK)
2637                 return error;
2638
2639         /*
2640          * mlock MCL_FUTURE?
2641          */
2642         if (mm->def_flags & VM_LOCKED) {
2643                 unsigned long locked, lock_limit;
2644                 locked = len >> PAGE_SHIFT;
2645                 locked += mm->locked_vm;
2646                 lock_limit = rlimit(RLIMIT_MEMLOCK);
2647                 lock_limit >>= PAGE_SHIFT;
2648                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
2649                         return -EAGAIN;
2650         }
2651
2652         /*
2653          * mm->mmap_sem is required to protect against another thread
2654          * changing the mappings in case we sleep.
2655          */
2656         verify_mm_writelocked(mm);
2657
2658         /*
2659          * Clear old maps.  this also does some error checking for us
2660          */
2661  munmap_back:
2662         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {
2663                 if (do_munmap(mm, addr, len))
2664                         return -ENOMEM;
2665                 goto munmap_back;
2666         }
2667
2668         /* Check against address space limits *after* clearing old maps... */
2669         if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2670                 return -ENOMEM;
2671
2672         if (mm->map_count > sysctl_max_map_count)
2673                 return -ENOMEM;
2674
2675         if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2676                 return -ENOMEM;
2677
2678         /* Can we just expand an old private anonymous mapping? */
2679         vma = vma_merge(mm, prev, addr, addr + len, flags,
2680                                         NULL, NULL, pgoff, NULL, NULL);
2681         if (vma)
2682                 goto out;
2683
2684         /*
2685          * create a vma struct for an anonymous mapping
2686          */
2687         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2688         if (!vma) {
2689                 vm_unacct_memory(len >> PAGE_SHIFT);
2690                 return -ENOMEM;
2691         }
2692
2693         INIT_LIST_HEAD(&vma->anon_vma_chain);
2694         vma->vm_mm = mm;
2695         vma->vm_start = addr;
2696         vma->vm_end = addr + len;
2697         vma->vm_pgoff = pgoff;
2698         vma->vm_flags = flags;
2699         vma->vm_page_prot = vm_get_page_prot(flags);
2700         vma_link(mm, vma, prev, rb_link, rb_parent);
2701 out:
2702         perf_event_mmap(vma);
2703         quadd_event_mmap(vma);
2704
2705         mm->total_vm += len >> PAGE_SHIFT;
2706         if (flags & VM_LOCKED)
2707                 mm->locked_vm += (len >> PAGE_SHIFT);
2708         return addr;
2709 }
2710
2711 unsigned long vm_brk(unsigned long addr, unsigned long len)
2712 {
2713         struct mm_struct *mm = current->mm;
2714         unsigned long ret;
2715         bool populate;
2716
2717         down_write(&mm->mmap_sem);
2718         ret = do_brk(addr, len);
2719         populate = ((mm->def_flags & VM_LOCKED) != 0);
2720         up_write(&mm->mmap_sem);
2721         if (populate)
2722                 mm_populate(addr, len);
2723         return ret;
2724 }
2725 EXPORT_SYMBOL(vm_brk);
2726
2727 /* Release all mmaps. */
2728 void exit_mmap(struct mm_struct *mm)
2729 {
2730         struct mmu_gather tlb;
2731         struct vm_area_struct *vma;
2732         unsigned long nr_accounted = 0;
2733
2734         /* mm's last user has gone, and its about to be pulled down */
2735         mmu_notifier_release(mm);
2736
2737         if (mm->locked_vm) {
2738                 vma = mm->mmap;
2739                 while (vma) {
2740                         if (vma->vm_flags & VM_LOCKED)
2741                                 munlock_vma_pages_all(vma);
2742                         vma = vma->vm_next;
2743                 }
2744         }
2745
2746         arch_exit_mmap(mm);
2747
2748         vma = mm->mmap;
2749         if (!vma)       /* Can happen if dup_mmap() received an OOM */
2750                 return;
2751
2752         lru_add_drain();
2753         flush_cache_mm(mm);
2754         tlb_gather_mmu(&tlb, mm, 0, -1);
2755         /* update_hiwater_rss(mm) here? but nobody should be looking */
2756         /* Use -1 here to ensure all VMAs in the mm are unmapped */
2757         unmap_vmas(&tlb, vma, 0, -1);
2758
2759         free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
2760         tlb_finish_mmu(&tlb, 0, -1);
2761
2762         /*
2763          * Walk the list again, actually closing and freeing it,
2764          * with preemption enabled, without holding any MM locks.
2765          */
2766         while (vma) {
2767                 if (vma->vm_flags & VM_ACCOUNT)
2768                         nr_accounted += vma_pages(vma);
2769                 vma = remove_vma(vma);
2770         }
2771         vm_unacct_memory(nr_accounted);
2772
2773         WARN_ON(mm->nr_ptes > (FIRST_USER_ADDRESS+PMD_SIZE-1)>>PMD_SHIFT);
2774 }
2775
2776 /* Insert vm structure into process list sorted by address
2777  * and into the inode's i_mmap tree.  If vm_file is non-NULL
2778  * then i_mmap_mutex is taken here.
2779  */
2780 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
2781 {
2782         struct vm_area_struct *prev;
2783         struct rb_node **rb_link, *rb_parent;
2784
2785         /*
2786          * The vm_pgoff of a purely anonymous vma should be irrelevant
2787          * until its first write fault, when page's anon_vma and index
2788          * are set.  But now set the vm_pgoff it will almost certainly
2789          * end up with (unless mremap moves it elsewhere before that
2790          * first wfault), so /proc/pid/maps tells a consistent story.
2791          *
2792          * By setting it to reflect the virtual start address of the
2793          * vma, merges and splits can happen in a seamless way, just
2794          * using the existing file pgoff checks and manipulations.
2795          * Similarly in do_mmap_pgoff and in do_brk.
2796          */
2797         if (!vma->vm_file) {
2798                 BUG_ON(vma->anon_vma);
2799                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2800         }
2801         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
2802                            &prev, &rb_link, &rb_parent))
2803                 return -ENOMEM;
2804         if ((vma->vm_flags & VM_ACCOUNT) &&
2805              security_vm_enough_memory_mm(mm, vma_pages(vma)))
2806                 return -ENOMEM;
2807
2808         vma_link(mm, vma, prev, rb_link, rb_parent);
2809         return 0;
2810 }
2811
2812 /*
2813  * Copy the vma structure to a new location in the same mm,
2814  * prior to moving page table entries, to effect an mremap move.
2815  */
2816 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2817         unsigned long addr, unsigned long len, pgoff_t pgoff,
2818         bool *need_rmap_locks)
2819 {
2820         struct vm_area_struct *vma = *vmap;
2821         unsigned long vma_start = vma->vm_start;
2822         struct mm_struct *mm = vma->vm_mm;
2823         struct vm_area_struct *new_vma, *prev;
2824         struct rb_node **rb_link, *rb_parent;
2825         struct mempolicy *pol;
2826         bool faulted_in_anon_vma = true;
2827
2828         /*
2829          * If anonymous vma has not yet been faulted, update new pgoff
2830          * to match new location, to increase its chance of merging.
2831          */
2832         if (unlikely(!vma->vm_file && !vma->anon_vma)) {
2833                 pgoff = addr >> PAGE_SHIFT;
2834                 faulted_in_anon_vma = false;
2835         }
2836
2837         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
2838                 return NULL;    /* should never get here */
2839         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2840                         vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
2841                         vma_get_anon_name(vma));
2842         if (new_vma) {
2843                 /*
2844                  * Source vma may have been merged into new_vma
2845                  */
2846                 if (unlikely(vma_start >= new_vma->vm_start &&
2847                              vma_start < new_vma->vm_end)) {
2848                         /*
2849                          * The only way we can get a vma_merge with
2850                          * self during an mremap is if the vma hasn't
2851                          * been faulted in yet and we were allowed to
2852                          * reset the dst vma->vm_pgoff to the
2853                          * destination address of the mremap to allow
2854                          * the merge to happen. mremap must change the
2855                          * vm_pgoff linearity between src and dst vmas
2856                          * (in turn preventing a vma_merge) to be
2857                          * safe. It is only safe to keep the vm_pgoff
2858                          * linear if there are no pages mapped yet.
2859                          */
2860                         VM_BUG_ON(faulted_in_anon_vma);
2861                         *vmap = vma = new_vma;
2862                 }
2863                 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
2864         } else {
2865                 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2866                 if (new_vma) {
2867                         *new_vma = *vma;
2868                         new_vma->vm_start = addr;
2869                         new_vma->vm_end = addr + len;
2870                         new_vma->vm_pgoff = pgoff;
2871                         pol = mpol_dup(vma_policy(vma));
2872                         if (IS_ERR(pol))
2873                                 goto out_free_vma;
2874                         vma_set_policy(new_vma, pol);
2875                         INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2876                         if (anon_vma_clone(new_vma, vma))
2877                                 goto out_free_mempol;
2878                         if (new_vma->vm_file)
2879                                 get_file(new_vma->vm_file);
2880                         if (new_vma->vm_ops && new_vma->vm_ops->open)
2881                                 new_vma->vm_ops->open(new_vma);
2882                         vma_link(mm, new_vma, prev, rb_link, rb_parent);
2883                         *need_rmap_locks = false;
2884                 }
2885         }
2886         return new_vma;
2887
2888  out_free_mempol:
2889         mpol_put(pol);
2890  out_free_vma:
2891         kmem_cache_free(vm_area_cachep, new_vma);
2892         return NULL;
2893 }
2894
2895 /*
2896  * Return true if the calling process may expand its vm space by the passed
2897  * number of pages
2898  */
2899 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
2900 {
2901         unsigned long cur = mm->total_vm;       /* pages */
2902         unsigned long lim;
2903
2904         lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
2905
2906         if (cur + npages > lim)
2907                 return 0;
2908         return 1;
2909 }
2910
2911
2912 static int special_mapping_fault(struct vm_area_struct *vma,
2913                                 struct vm_fault *vmf)
2914 {
2915         pgoff_t pgoff;
2916         struct page **pages;
2917
2918         /*
2919          * special mappings have no vm_file, and in that case, the mm
2920          * uses vm_pgoff internally. So we have to subtract it from here.
2921          * We are allowed to do this because we are the mm; do not copy
2922          * this code into drivers!
2923          */
2924         pgoff = vmf->pgoff - vma->vm_pgoff;
2925
2926         for (pages = vma->vm_private_data; pgoff && *pages; ++pages)
2927                 pgoff--;
2928
2929         if (*pages) {
2930                 struct page *page = *pages;
2931                 get_page(page);
2932                 vmf->page = page;
2933                 return 0;
2934         }
2935
2936         return VM_FAULT_SIGBUS;
2937 }
2938
2939 /*
2940  * Having a close hook prevents vma merging regardless of flags.
2941  */
2942 static void special_mapping_close(struct vm_area_struct *vma)
2943 {
2944 }
2945
2946 static const struct vm_operations_struct special_mapping_vmops = {
2947         .close = special_mapping_close,
2948         .fault = special_mapping_fault,
2949 };
2950
2951 /*
2952  * Called with mm->mmap_sem held for writing.
2953  * Insert a new vma covering the given region, with the given flags.
2954  * Its pages are supplied by the given array of struct page *.
2955  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
2956  * The region past the last page supplied will always produce SIGBUS.
2957  * The array pointer and the pages it points to are assumed to stay alive
2958  * for as long as this mapping might exist.
2959  */
2960 int install_special_mapping(struct mm_struct *mm,
2961                             unsigned long addr, unsigned long len,
2962                             unsigned long vm_flags, struct page **pages)
2963 {
2964         int ret;
2965         struct vm_area_struct *vma;
2966
2967         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2968         if (unlikely(vma == NULL))
2969                 return -ENOMEM;
2970
2971         INIT_LIST_HEAD(&vma->anon_vma_chain);
2972         vma->vm_mm = mm;
2973         vma->vm_start = addr;
2974         vma->vm_end = addr + len;
2975
2976         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND;
2977         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
2978
2979         vma->vm_ops = &special_mapping_vmops;
2980         vma->vm_private_data = pages;
2981
2982         ret = insert_vm_struct(mm, vma);
2983         if (ret)
2984                 goto out;
2985
2986         mm->total_vm += len >> PAGE_SHIFT;
2987
2988         perf_event_mmap(vma);
2989         quadd_event_mmap(vma);
2990
2991         return 0;
2992
2993 out:
2994         kmem_cache_free(vm_area_cachep, vma);
2995         return ret;
2996 }
2997
2998 static DEFINE_MUTEX(mm_all_locks_mutex);
2999
3000 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3001 {
3002         if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3003                 /*
3004                  * The LSB of head.next can't change from under us
3005                  * because we hold the mm_all_locks_mutex.
3006                  */
3007                 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
3008                 /*
3009                  * We can safely modify head.next after taking the
3010                  * anon_vma->root->rwsem. If some other vma in this mm shares
3011                  * the same anon_vma we won't take it again.
3012                  *
3013                  * No need of atomic instructions here, head.next
3014                  * can't change from under us thanks to the
3015                  * anon_vma->root->rwsem.
3016                  */
3017                 if (__test_and_set_bit(0, (unsigned long *)
3018                                        &anon_vma->root->rb_root.rb_node))
3019                         BUG();
3020         }
3021 }
3022
3023 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3024 {
3025         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3026                 /*
3027                  * AS_MM_ALL_LOCKS can't change from under us because
3028                  * we hold the mm_all_locks_mutex.
3029                  *
3030                  * Operations on ->flags have to be atomic because
3031                  * even if AS_MM_ALL_LOCKS is stable thanks to the
3032                  * mm_all_locks_mutex, there may be other cpus
3033                  * changing other bitflags in parallel to us.
3034                  */
3035                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3036                         BUG();
3037                 mutex_lock_nest_lock(&mapping->i_mmap_mutex, &mm->mmap_sem);
3038         }
3039 }
3040
3041 /*
3042  * This operation locks against the VM for all pte/vma/mm related
3043  * operations that could ever happen on a certain mm. This includes
3044  * vmtruncate, try_to_unmap, and all page faults.
3045  *
3046  * The caller must take the mmap_sem in write mode before calling
3047  * mm_take_all_locks(). The caller isn't allowed to release the
3048  * mmap_sem until mm_drop_all_locks() returns.
3049  *
3050  * mmap_sem in write mode is required in order to block all operations
3051  * that could modify pagetables and free pages without need of
3052  * altering the vma layout (for example populate_range() with
3053  * nonlinear vmas). It's also needed in write mode to avoid new
3054  * anon_vmas to be associated with existing vmas.
3055  *
3056  * A single task can't take more than one mm_take_all_locks() in a row
3057  * or it would deadlock.
3058  *
3059  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3060  * mapping->flags avoid to take the same lock twice, if more than one
3061  * vma in this mm is backed by the same anon_vma or address_space.
3062  *
3063  * We can take all the locks in random order because the VM code
3064  * taking i_mmap_mutex or anon_vma->rwsem outside the mmap_sem never
3065  * takes more than one of them in a row. Secondly we're protected
3066  * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
3067  *
3068  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3069  * that may have to take thousand of locks.
3070  *
3071  * mm_take_all_locks() can fail if it's interrupted by signals.
3072  */
3073 int mm_take_all_locks(struct mm_struct *mm)
3074 {
3075         struct vm_area_struct *vma;
3076         struct anon_vma_chain *avc;
3077
3078         BUG_ON(down_read_trylock(&mm->mmap_sem));
3079
3080         mutex_lock(&mm_all_locks_mutex);
3081
3082         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3083                 if (signal_pending(current))
3084                         goto out_unlock;
3085                 if (vma->vm_file && vma->vm_file->f_mapping)
3086                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3087         }
3088
3089         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3090                 if (signal_pending(current))
3091                         goto out_unlock;
3092                 if (vma->anon_vma)
3093                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3094                                 vm_lock_anon_vma(mm, avc->anon_vma);
3095         }
3096
3097         return 0;
3098
3099 out_unlock:
3100         mm_drop_all_locks(mm);
3101         return -EINTR;
3102 }
3103
3104 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3105 {
3106         if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3107                 /*
3108                  * The LSB of head.next can't change to 0 from under
3109                  * us because we hold the mm_all_locks_mutex.
3110                  *
3111                  * We must however clear the bitflag before unlocking
3112                  * the vma so the users using the anon_vma->rb_root will
3113                  * never see our bitflag.
3114                  *
3115                  * No need of atomic instructions here, head.next
3116                  * can't change from under us until we release the
3117                  * anon_vma->root->rwsem.
3118                  */
3119                 if (!__test_and_clear_bit(0, (unsigned long *)
3120                                           &anon_vma->root->rb_root.rb_node))
3121                         BUG();
3122                 anon_vma_unlock_write(anon_vma);
3123         }
3124 }
3125
3126 static void vm_unlock_mapping(struct address_space *mapping)
3127 {
3128         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3129                 /*
3130                  * AS_MM_ALL_LOCKS can't change to 0 from under us
3131                  * because we hold the mm_all_locks_mutex.
3132                  */
3133                 mutex_unlock(&mapping->i_mmap_mutex);
3134                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3135                                         &mapping->flags))
3136                         BUG();
3137         }
3138 }
3139
3140 /*
3141  * The mmap_sem cannot be released by the caller until
3142  * mm_drop_all_locks() returns.
3143  */
3144 void mm_drop_all_locks(struct mm_struct *mm)
3145 {
3146         struct vm_area_struct *vma;
3147         struct anon_vma_chain *avc;
3148
3149         BUG_ON(down_read_trylock(&mm->mmap_sem));
3150         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3151
3152         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3153                 if (vma->anon_vma)
3154                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3155                                 vm_unlock_anon_vma(avc->anon_vma);
3156                 if (vma->vm_file && vma->vm_file->f_mapping)
3157                         vm_unlock_mapping(vma->vm_file->f_mapping);
3158         }
3159
3160         mutex_unlock(&mm_all_locks_mutex);
3161 }
3162
3163 /*
3164  * initialise the VMA slab
3165  */
3166 void __init mmap_init(void)
3167 {
3168         int ret;
3169
3170         ret = percpu_counter_init(&vm_committed_as, 0);
3171         VM_BUG_ON(ret);
3172 }
3173
3174 /*
3175  * Initialise sysctl_user_reserve_kbytes.
3176  *
3177  * This is intended to prevent a user from starting a single memory hogging
3178  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3179  * mode.
3180  *
3181  * The default value is min(3% of free memory, 128MB)
3182  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3183  */
3184 static int init_user_reserve(void)
3185 {
3186         unsigned long free_kbytes;
3187
3188         free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3189
3190         sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3191         return 0;
3192 }
3193 module_init(init_user_reserve)
3194
3195 /*
3196  * Initialise sysctl_admin_reserve_kbytes.
3197  *
3198  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3199  * to log in and kill a memory hogging process.
3200  *
3201  * Systems with more than 256MB will reserve 8MB, enough to recover
3202  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3203  * only reserve 3% of free pages by default.
3204  */
3205 static int init_admin_reserve(void)
3206 {
3207         unsigned long free_kbytes;
3208
3209         free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3210
3211         sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3212         return 0;
3213 }
3214 module_init(init_admin_reserve)
3215
3216 /*
3217  * Reinititalise user and admin reserves if memory is added or removed.
3218  *
3219  * The default user reserve max is 128MB, and the default max for the
3220  * admin reserve is 8MB. These are usually, but not always, enough to
3221  * enable recovery from a memory hogging process using login/sshd, a shell,
3222  * and tools like top. It may make sense to increase or even disable the
3223  * reserve depending on the existence of swap or variations in the recovery
3224  * tools. So, the admin may have changed them.
3225  *
3226  * If memory is added and the reserves have been eliminated or increased above
3227  * the default max, then we'll trust the admin.
3228  *
3229  * If memory is removed and there isn't enough free memory, then we
3230  * need to reset the reserves.
3231  *
3232  * Otherwise keep the reserve set by the admin.
3233  */
3234 static int reserve_mem_notifier(struct notifier_block *nb,
3235                              unsigned long action, void *data)
3236 {
3237         unsigned long tmp, free_kbytes;
3238
3239         switch (action) {
3240         case MEM_ONLINE:
3241                 /* Default max is 128MB. Leave alone if modified by operator. */
3242                 tmp = sysctl_user_reserve_kbytes;
3243                 if (0 < tmp && tmp < (1UL << 17))
3244                         init_user_reserve();
3245
3246                 /* Default max is 8MB.  Leave alone if modified by operator. */
3247                 tmp = sysctl_admin_reserve_kbytes;
3248                 if (0 < tmp && tmp < (1UL << 13))
3249                         init_admin_reserve();
3250
3251                 break;
3252         case MEM_OFFLINE:
3253                 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3254
3255                 if (sysctl_user_reserve_kbytes > free_kbytes) {
3256                         init_user_reserve();
3257                         pr_info("vm.user_reserve_kbytes reset to %lu\n",
3258                                 sysctl_user_reserve_kbytes);
3259                 }
3260
3261                 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3262                         init_admin_reserve();
3263                         pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3264                                 sysctl_admin_reserve_kbytes);
3265                 }
3266                 break;
3267         default:
3268                 break;
3269         }
3270         return NOTIFY_OK;
3271 }
3272
3273 static struct notifier_block reserve_mem_nb = {
3274         .notifier_call = reserve_mem_notifier,
3275 };
3276
3277 static int __meminit init_reserve_notifier(void)
3278 {
3279         if (register_hotmemory_notifier(&reserve_mem_nb))
3280                 printk("Failed registering memory add/remove notifier for admin reserve");
3281
3282         return 0;
3283 }
3284 module_init(init_reserve_notifier)