~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/mm/mmap.c

Version: ~ [ linux-5.5-rc7 ] ~ [ linux-5.4.13 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.97 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.166 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.210 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.210 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.81 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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/vmacache.h>
 14 #include <linux/shm.h>
 15 #include <linux/mman.h>
 16 #include <linux/pagemap.h>
 17 #include <linux/swap.h>
 18 #include <linux/syscalls.h>
 19 #include <linux/capability.h>
 20 #include <linux/init.h>
 21 #include <linux/file.h>
 22 #include <linux/fs.h>
 23 #include <linux/personality.h>
 24 #include <linux/security.h>
 25 #include <linux/hugetlb.h>
 26 #include <linux/profile.h>
 27 #include <linux/export.h>
 28 #include <linux/mount.h>
 29 #include <linux/mempolicy.h>
 30 #include <linux/rmap.h>
 31 #include <linux/mmu_notifier.h>
 32 #include <linux/perf_event.h>
 33 #include <linux/audit.h>
 34 #include <linux/khugepaged.h>
 35 #include <linux/uprobes.h>
 36 #include <linux/rbtree_augmented.h>
 37 #include <linux/sched/sysctl.h>
 38 #include <linux/notifier.h>
 39 #include <linux/memory.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         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_t(long, 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 
687         /* Kill the cache */
688         vmacache_invalidate(mm);
689 }
690 
691 /*
692  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
693  * is already present in an i_mmap tree without adjusting the tree.
694  * The following helper function should be used when such adjustments
695  * are necessary.  The "insert" vma (if any) is to be inserted
696  * before we drop the necessary locks.
697  */
698 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
699         unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
700 {
701         struct mm_struct *mm = vma->vm_mm;
702         struct vm_area_struct *next = vma->vm_next;
703         struct vm_area_struct *importer = NULL;
704         struct address_space *mapping = NULL;
705         struct rb_root *root = NULL;
706         struct anon_vma *anon_vma = NULL;
707         struct file *file = vma->vm_file;
708         bool start_changed = false, end_changed = false;
709         long adjust_next = 0;
710         int remove_next = 0;
711 
712         if (next && !insert) {
713                 struct vm_area_struct *exporter = NULL;
714 
715                 if (end >= next->vm_end) {
716                         /*
717                          * vma expands, overlapping all the next, and
718                          * perhaps the one after too (mprotect case 6).
719                          */
720 again:                  remove_next = 1 + (end > next->vm_end);
721                         end = next->vm_end;
722                         exporter = next;
723                         importer = vma;
724                 } else if (end > next->vm_start) {
725                         /*
726                          * vma expands, overlapping part of the next:
727                          * mprotect case 5 shifting the boundary up.
728                          */
729                         adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
730                         exporter = next;
731                         importer = vma;
732                 } else if (end < vma->vm_end) {
733                         /*
734                          * vma shrinks, and !insert tells it's not
735                          * split_vma inserting another: so it must be
736                          * mprotect case 4 shifting the boundary down.
737                          */
738                         adjust_next = - ((vma->vm_end - end) >> PAGE_SHIFT);
739                         exporter = vma;
740                         importer = next;
741                 }
742 
743                 /*
744                  * Easily overlooked: when mprotect shifts the boundary,
745                  * make sure the expanding vma has anon_vma set if the
746                  * shrinking vma had, to cover any anon pages imported.
747                  */
748                 if (exporter && exporter->anon_vma && !importer->anon_vma) {
749                         int error;
750 
751                         importer->anon_vma = exporter->anon_vma;
752                         error = anon_vma_clone(importer, exporter);
753                         if (error)
754                                 return error;
755                 }
756         }
757 
758         if (file) {
759                 mapping = file->f_mapping;
760                 if (!(vma->vm_flags & VM_NONLINEAR)) {
761                         root = &mapping->i_mmap;
762                         uprobe_munmap(vma, vma->vm_start, vma->vm_end);
763 
764                         if (adjust_next)
765                                 uprobe_munmap(next, next->vm_start,
766                                                         next->vm_end);
767                 }
768 
769                 mutex_lock(&mapping->i_mmap_mutex);
770                 if (insert) {
771                         /*
772                          * Put into interval tree now, so instantiated pages
773                          * are visible to arm/parisc __flush_dcache_page
774                          * throughout; but we cannot insert into address
775                          * space until vma start or end is updated.
776                          */
777                         __vma_link_file(insert);
778                 }
779         }
780 
781         vma_adjust_trans_huge(vma, start, end, adjust_next);
782 
783         anon_vma = vma->anon_vma;
784         if (!anon_vma && adjust_next)
785                 anon_vma = next->anon_vma;
786         if (anon_vma) {
787                 VM_BUG_ON(adjust_next && next->anon_vma &&
788                           anon_vma != next->anon_vma);
789                 anon_vma_lock_write(anon_vma);
790                 anon_vma_interval_tree_pre_update_vma(vma);
791                 if (adjust_next)
792                         anon_vma_interval_tree_pre_update_vma(next);
793         }
794 
795         if (root) {
796                 flush_dcache_mmap_lock(mapping);
797                 vma_interval_tree_remove(vma, root);
798                 if (adjust_next)
799                         vma_interval_tree_remove(next, root);
800         }
801 
802         if (start != vma->vm_start) {
803                 vma->vm_start = start;
804                 start_changed = true;
805         }
806         if (end != vma->vm_end) {
807                 vma->vm_end = end;
808                 end_changed = true;
809         }
810         vma->vm_pgoff = pgoff;
811         if (adjust_next) {
812                 next->vm_start += adjust_next << PAGE_SHIFT;
813                 next->vm_pgoff += adjust_next;
814         }
815 
816         if (root) {
817                 if (adjust_next)
818                         vma_interval_tree_insert(next, root);
819                 vma_interval_tree_insert(vma, root);
820                 flush_dcache_mmap_unlock(mapping);
821         }
822 
823         if (remove_next) {
824                 /*
825                  * vma_merge has merged next into vma, and needs
826                  * us to remove next before dropping the locks.
827                  */
828                 __vma_unlink(mm, next, vma);
829                 if (file)
830                         __remove_shared_vm_struct(next, file, mapping);
831         } else if (insert) {
832                 /*
833                  * split_vma has split insert from vma, and needs
834                  * us to insert it before dropping the locks
835                  * (it may either follow vma or precede it).
836                  */
837                 __insert_vm_struct(mm, insert);
838         } else {
839                 if (start_changed)
840                         vma_gap_update(vma);
841                 if (end_changed) {
842                         if (!next)
843                                 mm->highest_vm_end = end;
844                         else if (!adjust_next)
845                                 vma_gap_update(next);
846                 }
847         }
848 
849         if (anon_vma) {
850                 anon_vma_interval_tree_post_update_vma(vma);
851                 if (adjust_next)
852                         anon_vma_interval_tree_post_update_vma(next);
853                 anon_vma_unlock_write(anon_vma);
854         }
855         if (mapping)
856                 mutex_unlock(&mapping->i_mmap_mutex);
857 
858         if (root) {
859                 uprobe_mmap(vma);
860 
861                 if (adjust_next)
862                         uprobe_mmap(next);
863         }
864 
865         if (remove_next) {
866                 if (file) {
867                         uprobe_munmap(next, next->vm_start, next->vm_end);
868                         fput(file);
869                 }
870                 if (next->anon_vma)
871                         anon_vma_merge(vma, next);
872                 mm->map_count--;
873                 mpol_put(vma_policy(next));
874                 kmem_cache_free(vm_area_cachep, next);
875                 /*
876                  * In mprotect's case 6 (see comments on vma_merge),
877                  * we must remove another next too. It would clutter
878                  * up the code too much to do both in one go.
879                  */
880                 next = vma->vm_next;
881                 if (remove_next == 2)
882                         goto again;
883                 else if (next)
884                         vma_gap_update(next);
885                 else
886                         mm->highest_vm_end = end;
887         }
888         if (insert && file)
889                 uprobe_mmap(insert);
890 
891         validate_mm(mm);
892 
893         return 0;
894 }
895 
896 /*
897  * If the vma has a ->close operation then the driver probably needs to release
898  * per-vma resources, so we don't attempt to merge those.
899  */
900 static inline int is_mergeable_vma(struct vm_area_struct *vma,
901                         struct file *file, unsigned long vm_flags)
902 {
903         /*
904          * VM_SOFTDIRTY should not prevent from VMA merging, if we
905          * match the flags but dirty bit -- the caller should mark
906          * merged VMA as dirty. If dirty bit won't be excluded from
907          * comparison, we increase pressue on the memory system forcing
908          * the kernel to generate new VMAs when old one could be
909          * extended instead.
910          */
911         if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
912                 return 0;
913         if (vma->vm_file != file)
914                 return 0;
915         if (vma->vm_ops && vma->vm_ops->close)
916                 return 0;
917         return 1;
918 }
919 
920 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
921                                         struct anon_vma *anon_vma2,
922                                         struct vm_area_struct *vma)
923 {
924         /*
925          * The list_is_singular() test is to avoid merging VMA cloned from
926          * parents. This can improve scalability caused by anon_vma lock.
927          */
928         if ((!anon_vma1 || !anon_vma2) && (!vma ||
929                 list_is_singular(&vma->anon_vma_chain)))
930                 return 1;
931         return anon_vma1 == anon_vma2;
932 }
933 
934 /*
935  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
936  * in front of (at a lower virtual address and file offset than) the vma.
937  *
938  * We cannot merge two vmas if they have differently assigned (non-NULL)
939  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
940  *
941  * We don't check here for the merged mmap wrapping around the end of pagecache
942  * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
943  * wrap, nor mmaps which cover the final page at index -1UL.
944  */
945 static int
946 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
947         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
948 {
949         if (is_mergeable_vma(vma, file, vm_flags) &&
950             is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
951                 if (vma->vm_pgoff == vm_pgoff)
952                         return 1;
953         }
954         return 0;
955 }
956 
957 /*
958  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
959  * beyond (at a higher virtual address and file offset than) the vma.
960  *
961  * We cannot merge two vmas if they have differently assigned (non-NULL)
962  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
963  */
964 static int
965 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
966         struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff)
967 {
968         if (is_mergeable_vma(vma, file, vm_flags) &&
969             is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
970                 pgoff_t vm_pglen;
971                 vm_pglen = vma_pages(vma);
972                 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
973                         return 1;
974         }
975         return 0;
976 }
977 
978 /*
979  * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
980  * whether that can be merged with its predecessor or its successor.
981  * Or both (it neatly fills a hole).
982  *
983  * In most cases - when called for mmap, brk or mremap - [addr,end) is
984  * certain not to be mapped by the time vma_merge is called; but when
985  * called for mprotect, it is certain to be already mapped (either at
986  * an offset within prev, or at the start of next), and the flags of
987  * this area are about to be changed to vm_flags - and the no-change
988  * case has already been eliminated.
989  *
990  * The following mprotect cases have to be considered, where AAAA is
991  * the area passed down from mprotect_fixup, never extending beyond one
992  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
993  *
994  *     AAAA             AAAA                AAAA          AAAA
995  *    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPNNNNXXXX
996  *    cannot merge    might become    might become    might become
997  *                    PPNNNNNNNNNN    PPPPPPPPPPNN    PPPPPPPPPPPP 6 or
998  *    mmap, brk or    case 4 below    case 5 below    PPPPPPPPXXXX 7 or
999  *    mremap move:                                    PPPPNNNNNNNN 8
1000  *        AAAA
1001  *    PPPP    NNNN    PPPPPPPPPPPP    PPPPPPPPNNNN    PPPPNNNNNNNN
1002  *    might become    case 1 below    case 2 below    case 3 below
1003  *
1004  * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
1005  * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
1006  */
1007 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1008                         struct vm_area_struct *prev, unsigned long addr,
1009                         unsigned long end, unsigned long vm_flags,
1010                         struct anon_vma *anon_vma, struct file *file,
1011                         pgoff_t pgoff, struct mempolicy *policy)
1012 {
1013         pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1014         struct vm_area_struct *area, *next;
1015         int err;
1016 
1017         /*
1018          * We later require that vma->vm_flags == vm_flags,
1019          * so this tests vma->vm_flags & VM_SPECIAL, too.
1020          */
1021         if (vm_flags & VM_SPECIAL)
1022                 return NULL;
1023 
1024         if (prev)
1025                 next = prev->vm_next;
1026         else
1027                 next = mm->mmap;
1028         area = next;
1029         if (next && next->vm_end == end)                /* cases 6, 7, 8 */
1030                 next = next->vm_next;
1031 
1032         /*
1033          * Can it merge with the predecessor?
1034          */
1035         if (prev && prev->vm_end == addr &&
1036                         mpol_equal(vma_policy(prev), policy) &&
1037                         can_vma_merge_after(prev, vm_flags,
1038                                                 anon_vma, file, pgoff)) {
1039                 /*
1040                  * OK, it can.  Can we now merge in the successor as well?
1041                  */
1042                 if (next && end == next->vm_start &&
1043                                 mpol_equal(policy, vma_policy(next)) &&
1044                                 can_vma_merge_before(next, vm_flags,
1045                                         anon_vma, file, pgoff+pglen) &&
1046                                 is_mergeable_anon_vma(prev->anon_vma,
1047                                                       next->anon_vma, NULL)) {
1048                                                         /* cases 1, 6 */
1049                         err = vma_adjust(prev, prev->vm_start,
1050                                 next->vm_end, prev->vm_pgoff, NULL);
1051                 } else                                  /* cases 2, 5, 7 */
1052                         err = vma_adjust(prev, prev->vm_start,
1053                                 end, prev->vm_pgoff, NULL);
1054                 if (err)
1055                         return NULL;
1056                 khugepaged_enter_vma_merge(prev);
1057                 return prev;
1058         }
1059 
1060         /*
1061          * Can this new request be merged in front of next?
1062          */
1063         if (next && end == next->vm_start &&
1064                         mpol_equal(policy, vma_policy(next)) &&
1065                         can_vma_merge_before(next, vm_flags,
1066                                         anon_vma, file, pgoff+pglen)) {
1067                 if (prev && addr < prev->vm_end)        /* case 4 */
1068                         err = vma_adjust(prev, prev->vm_start,
1069                                 addr, prev->vm_pgoff, NULL);
1070                 else                                    /* cases 3, 8 */
1071                         err = vma_adjust(area, addr, next->vm_end,
1072                                 next->vm_pgoff - pglen, NULL);
1073                 if (err)
1074                         return NULL;
1075                 khugepaged_enter_vma_merge(area);
1076                 return area;
1077         }
1078 
1079         return NULL;
1080 }
1081 
1082 /*
1083  * Rough compatbility check to quickly see if it's even worth looking
1084  * at sharing an anon_vma.
1085  *
1086  * They need to have the same vm_file, and the flags can only differ
1087  * in things that mprotect may change.
1088  *
1089  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1090  * we can merge the two vma's. For example, we refuse to merge a vma if
1091  * there is a vm_ops->close() function, because that indicates that the
1092  * driver is doing some kind of reference counting. But that doesn't
1093  * really matter for the anon_vma sharing case.
1094  */
1095 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1096 {
1097         return a->vm_end == b->vm_start &&
1098                 mpol_equal(vma_policy(a), vma_policy(b)) &&
1099                 a->vm_file == b->vm_file &&
1100                 !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
1101                 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1102 }
1103 
1104 /*
1105  * Do some basic sanity checking to see if we can re-use the anon_vma
1106  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1107  * the same as 'old', the other will be the new one that is trying
1108  * to share the anon_vma.
1109  *
1110  * NOTE! This runs with mm_sem held for reading, so it is possible that
1111  * the anon_vma of 'old' is concurrently in the process of being set up
1112  * by another page fault trying to merge _that_. But that's ok: if it
1113  * is being set up, that automatically means that it will be a singleton
1114  * acceptable for merging, so we can do all of this optimistically. But
1115  * we do that ACCESS_ONCE() to make sure that we never re-load the pointer.
1116  *
1117  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1118  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1119  * is to return an anon_vma that is "complex" due to having gone through
1120  * a fork).
1121  *
1122  * We also make sure that the two vma's are compatible (adjacent,
1123  * and with the same memory policies). That's all stable, even with just
1124  * a read lock on the mm_sem.
1125  */
1126 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1127 {
1128         if (anon_vma_compatible(a, b)) {
1129                 struct anon_vma *anon_vma = ACCESS_ONCE(old->anon_vma);
1130 
1131                 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1132                         return anon_vma;
1133         }
1134         return NULL;
1135 }
1136 
1137 /*
1138  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1139  * neighbouring vmas for a suitable anon_vma, before it goes off
1140  * to allocate a new anon_vma.  It checks because a repetitive
1141  * sequence of mprotects and faults may otherwise lead to distinct
1142  * anon_vmas being allocated, preventing vma merge in subsequent
1143  * mprotect.
1144  */
1145 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1146 {
1147         struct anon_vma *anon_vma;
1148         struct vm_area_struct *near;
1149 
1150         near = vma->vm_next;
1151         if (!near)
1152                 goto try_prev;
1153 
1154         anon_vma = reusable_anon_vma(near, vma, near);
1155         if (anon_vma)
1156                 return anon_vma;
1157 try_prev:
1158         near = vma->vm_prev;
1159         if (!near)
1160                 goto none;
1161 
1162         anon_vma = reusable_anon_vma(near, near, vma);
1163         if (anon_vma)
1164                 return anon_vma;
1165 none:
1166         /*
1167          * There's no absolute need to look only at touching neighbours:
1168          * we could search further afield for "compatible" anon_vmas.
1169          * But it would probably just be a waste of time searching,
1170          * or lead to too many vmas hanging off the same anon_vma.
1171          * We're trying to allow mprotect remerging later on,
1172          * not trying to minimize memory used for anon_vmas.
1173          */
1174         return NULL;
1175 }
1176 
1177 #ifdef CONFIG_PROC_FS
1178 void vm_stat_account(struct mm_struct *mm, unsigned long flags,
1179                                                 struct file *file, long pages)
1180 {
1181         const unsigned long stack_flags
1182                 = VM_STACK_FLAGS & (VM_GROWSUP|VM_GROWSDOWN);
1183 
1184         mm->total_vm += pages;
1185 
1186         if (file) {
1187                 mm->shared_vm += pages;
1188                 if ((flags & (VM_EXEC|VM_WRITE)) == VM_EXEC)
1189                         mm->exec_vm += pages;
1190         } else if (flags & stack_flags)
1191                 mm->stack_vm += pages;
1192 }
1193 #endif /* CONFIG_PROC_FS */
1194 
1195 /*
1196  * If a hint addr is less than mmap_min_addr change hint to be as
1197  * low as possible but still greater than mmap_min_addr
1198  */
1199 static inline unsigned long round_hint_to_min(unsigned long hint)
1200 {
1201         hint &= PAGE_MASK;
1202         if (((void *)hint != NULL) &&
1203             (hint < mmap_min_addr))
1204                 return PAGE_ALIGN(mmap_min_addr);
1205         return hint;
1206 }
1207 
1208 /*
1209  * The caller must hold down_write(&current->mm->mmap_sem).
1210  */
1211 
1212 unsigned long do_mmap_pgoff(struct file *file, unsigned long addr,
1213                         unsigned long len, unsigned long prot,
1214                         unsigned long flags, unsigned long pgoff,
1215                         unsigned long *populate)
1216 {
1217         struct mm_struct * mm = current->mm;
1218         vm_flags_t vm_flags;
1219 
1220         *populate = 0;
1221 
1222         /*
1223          * Does the application expect PROT_READ to imply PROT_EXEC?
1224          *
1225          * (the exception is when the underlying filesystem is noexec
1226          *  mounted, in which case we dont add PROT_EXEC.)
1227          */
1228         if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1229                 if (!(file && (file->f_path.mnt->mnt_flags & MNT_NOEXEC)))
1230                         prot |= PROT_EXEC;
1231 
1232         if (!len)
1233                 return -EINVAL;
1234 
1235         if (!(flags & MAP_FIXED))
1236                 addr = round_hint_to_min(addr);
1237 
1238         /* Careful about overflows.. */
1239         len = PAGE_ALIGN(len);
1240         if (!len)
1241                 return -ENOMEM;
1242 
1243         /* offset overflow? */
1244         if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1245                return -EOVERFLOW;
1246 
1247         /* Too many mappings? */
1248         if (mm->map_count > sysctl_max_map_count)
1249                 return -ENOMEM;
1250 
1251         /* Obtain the address to map to. we verify (or select) it and ensure
1252          * that it represents a valid section of the address space.
1253          */
1254         addr = get_unmapped_area(file, addr, len, pgoff, flags);
1255         if (addr & ~PAGE_MASK)
1256                 return addr;
1257 
1258         /* Do simple checking here so the lower-level routines won't have
1259          * to. we assume access permissions have been handled by the open
1260          * of the memory object, so we don't do any here.
1261          */
1262         vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
1263                         mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1264 
1265         if (flags & MAP_LOCKED)
1266                 if (!can_do_mlock())
1267                         return -EPERM;
1268 
1269         /* mlock MCL_FUTURE? */
1270         if (vm_flags & VM_LOCKED) {
1271                 unsigned long locked, lock_limit;
1272                 locked = len >> PAGE_SHIFT;
1273                 locked += mm->locked_vm;
1274                 lock_limit = rlimit(RLIMIT_MEMLOCK);
1275                 lock_limit >>= PAGE_SHIFT;
1276                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1277                         return -EAGAIN;
1278         }
1279 
1280         if (file) {
1281                 struct inode *inode = file_inode(file);
1282 
1283                 switch (flags & MAP_TYPE) {
1284                 case MAP_SHARED:
1285                         if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1286                                 return -EACCES;
1287 
1288                         /*
1289                          * Make sure we don't allow writing to an append-only
1290                          * file..
1291                          */
1292                         if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1293                                 return -EACCES;
1294 
1295                         /*
1296                          * Make sure there are no mandatory locks on the file.
1297                          */
1298                         if (locks_verify_locked(inode))
1299                                 return -EAGAIN;
1300 
1301                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1302                         if (!(file->f_mode & FMODE_WRITE))
1303                                 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1304 
1305                         /* fall through */
1306                 case MAP_PRIVATE:
1307                         if (!(file->f_mode & FMODE_READ))
1308                                 return -EACCES;
1309                         if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
1310                                 if (vm_flags & VM_EXEC)
1311                                         return -EPERM;
1312                                 vm_flags &= ~VM_MAYEXEC;
1313                         }
1314 
1315                         if (!file->f_op || !file->f_op->mmap)
1316                                 return -ENODEV;
1317                         if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1318                                 return -EINVAL;
1319                         break;
1320 
1321                 default:
1322                         return -EINVAL;
1323                 }
1324         } else {
1325                 switch (flags & MAP_TYPE) {
1326                 case MAP_SHARED:
1327                         if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1328                                 return -EINVAL;
1329                         /*
1330                          * Ignore pgoff.
1331                          */
1332                         pgoff = 0;
1333                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1334                         break;
1335                 case MAP_PRIVATE:
1336                         /*
1337                          * Set pgoff according to addr for anon_vma.
1338                          */
1339                         pgoff = addr >> PAGE_SHIFT;
1340                         break;
1341                 default:
1342                         return -EINVAL;
1343                 }
1344         }
1345 
1346         /*
1347          * Set 'VM_NORESERVE' if we should not account for the
1348          * memory use of this mapping.
1349          */
1350         if (flags & MAP_NORESERVE) {
1351                 /* We honor MAP_NORESERVE if allowed to overcommit */
1352                 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1353                         vm_flags |= VM_NORESERVE;
1354 
1355                 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1356                 if (file && is_file_hugepages(file))
1357                         vm_flags |= VM_NORESERVE;
1358         }
1359 
1360         addr = mmap_region(file, addr, len, vm_flags, pgoff);
1361         if (!IS_ERR_VALUE(addr) &&
1362             ((vm_flags & VM_LOCKED) ||
1363              (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1364                 *populate = len;
1365         return addr;
1366 }
1367 
1368 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1369                 unsigned long, prot, unsigned long, flags,
1370                 unsigned long, fd, unsigned long, pgoff)
1371 {
1372         struct file *file = NULL;
1373         unsigned long retval = -EBADF;
1374 
1375         if (!(flags & MAP_ANONYMOUS)) {
1376                 audit_mmap_fd(fd, flags);
1377                 file = fget(fd);
1378                 if (!file)
1379                         goto out;
1380                 if (is_file_hugepages(file))
1381                         len = ALIGN(len, huge_page_size(hstate_file(file)));
1382                 retval = -EINVAL;
1383                 if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
1384                         goto out_fput;
1385         } else if (flags & MAP_HUGETLB) {
1386                 struct user_struct *user = NULL;
1387                 struct hstate *hs;
1388 
1389                 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & SHM_HUGE_MASK);
1390                 if (!hs)
1391                         return -EINVAL;
1392 
1393                 len = ALIGN(len, huge_page_size(hs));
1394                 /*
1395                  * VM_NORESERVE is used because the reservations will be
1396                  * taken when vm_ops->mmap() is called
1397                  * A dummy user value is used because we are not locking
1398                  * memory so no accounting is necessary
1399                  */
1400                 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1401                                 VM_NORESERVE,
1402                                 &user, HUGETLB_ANONHUGE_INODE,
1403                                 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1404                 if (IS_ERR(file))
1405                         return PTR_ERR(file);
1406         }
1407 
1408         flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1409 
1410         retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1411 out_fput:
1412         if (file)
1413                 fput(file);
1414 out:
1415         return retval;
1416 }
1417 
1418 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1419 struct mmap_arg_struct {
1420         unsigned long addr;
1421         unsigned long len;
1422         unsigned long prot;
1423         unsigned long flags;
1424         unsigned long fd;
1425         unsigned long offset;
1426 };
1427 
1428 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1429 {
1430         struct mmap_arg_struct a;
1431 
1432         if (copy_from_user(&a, arg, sizeof(a)))
1433                 return -EFAULT;
1434         if (a.offset & ~PAGE_MASK)
1435                 return -EINVAL;
1436 
1437         return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1438                               a.offset >> PAGE_SHIFT);
1439 }
1440 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1441 
1442 /*
1443  * Some shared mappigns will want the pages marked read-only
1444  * to track write events. If so, we'll downgrade vm_page_prot
1445  * to the private version (using protection_map[] without the
1446  * VM_SHARED bit).
1447  */
1448 int vma_wants_writenotify(struct vm_area_struct *vma)
1449 {
1450         vm_flags_t vm_flags = vma->vm_flags;
1451 
1452         /* If it was private or non-writable, the write bit is already clear */
1453         if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1454                 return 0;
1455 
1456         /* The backer wishes to know when pages are first written to? */
1457         if (vma->vm_ops && vma->vm_ops->page_mkwrite)
1458                 return 1;
1459 
1460         /* The open routine did something to the protections already? */
1461         if (pgprot_val(vma->vm_page_prot) !=
1462             pgprot_val(vm_get_page_prot(vm_flags)))
1463                 return 0;
1464 
1465         /* Specialty mapping? */
1466         if (vm_flags & VM_PFNMAP)
1467                 return 0;
1468 
1469         /* Can the mapping track the dirty pages? */
1470         return vma->vm_file && vma->vm_file->f_mapping &&
1471                 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1472 }
1473 
1474 /*
1475  * We account for memory if it's a private writeable mapping,
1476  * not hugepages and VM_NORESERVE wasn't set.
1477  */
1478 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1479 {
1480         /*
1481          * hugetlb has its own accounting separate from the core VM
1482          * VM_HUGETLB may not be set yet so we cannot check for that flag.
1483          */
1484         if (file && is_file_hugepages(file))
1485                 return 0;
1486 
1487         return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1488 }
1489 
1490 unsigned long mmap_region(struct file *file, unsigned long addr,
1491                 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff)
1492 {
1493         struct mm_struct *mm = current->mm;
1494         struct vm_area_struct *vma, *prev;
1495         int error;
1496         struct rb_node **rb_link, *rb_parent;
1497         unsigned long charged = 0;
1498 
1499         /* Check against address space limit. */
1500         if (!may_expand_vm(mm, len >> PAGE_SHIFT)) {
1501                 unsigned long nr_pages;
1502 
1503                 /*
1504                  * MAP_FIXED may remove pages of mappings that intersects with
1505                  * requested mapping. Account for the pages it would unmap.
1506                  */
1507                 if (!(vm_flags & MAP_FIXED))
1508                         return -ENOMEM;
1509 
1510                 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1511 
1512                 if (!may_expand_vm(mm, (len >> PAGE_SHIFT) - nr_pages))
1513                         return -ENOMEM;
1514         }
1515 
1516         /* Clear old maps */
1517         error = -ENOMEM;
1518 munmap_back:
1519         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {
1520                 if (do_munmap(mm, addr, len))
1521                         return -ENOMEM;
1522                 goto munmap_back;
1523         }
1524 
1525         /*
1526          * Private writable mapping: check memory availability
1527          */
1528         if (accountable_mapping(file, vm_flags)) {
1529                 charged = len >> PAGE_SHIFT;
1530                 if (security_vm_enough_memory_mm(mm, charged))
1531                         return -ENOMEM;
1532                 vm_flags |= VM_ACCOUNT;
1533         }
1534 
1535         /*
1536          * Can we just expand an old mapping?
1537          */
1538         vma = vma_merge(mm, prev, addr, addr + len, vm_flags, NULL, file, pgoff, NULL);
1539         if (vma)
1540                 goto out;
1541 
1542         /*
1543          * Determine the object being mapped and call the appropriate
1544          * specific mapper. the address has already been validated, but
1545          * not unmapped, but the maps are removed from the list.
1546          */
1547         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1548         if (!vma) {
1549                 error = -ENOMEM;
1550                 goto unacct_error;
1551         }
1552 
1553         vma->vm_mm = mm;
1554         vma->vm_start = addr;
1555         vma->vm_end = addr + len;
1556         vma->vm_flags = vm_flags;
1557         vma->vm_page_prot = vm_get_page_prot(vm_flags);
1558         vma->vm_pgoff = pgoff;
1559         INIT_LIST_HEAD(&vma->anon_vma_chain);
1560 
1561         if (file) {
1562                 if (vm_flags & VM_DENYWRITE) {
1563                         error = deny_write_access(file);
1564                         if (error)
1565                                 goto free_vma;
1566                 }
1567                 vma->vm_file = get_file(file);
1568                 error = file->f_op->mmap(file, vma);
1569                 if (error)
1570                         goto unmap_and_free_vma;
1571 
1572                 /* Can addr have changed??
1573                  *
1574                  * Answer: Yes, several device drivers can do it in their
1575                  *         f_op->mmap method. -DaveM
1576                  * Bug: If addr is changed, prev, rb_link, rb_parent should
1577                  *      be updated for vma_link()
1578                  */
1579                 WARN_ON_ONCE(addr != vma->vm_start);
1580 
1581                 addr = vma->vm_start;
1582                 vm_flags = vma->vm_flags;
1583         } else if (vm_flags & VM_SHARED) {
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         /* Once vma denies write, undo our temporary denial count */
1606         if (vm_flags & VM_DENYWRITE)
1607                 allow_write_access(file);
1608         file = vma->vm_file;
1609 out:
1610         perf_event_mmap(vma);
1611 
1612         vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1613         if (vm_flags & VM_LOCKED) {
1614                 if (!((vm_flags & VM_SPECIAL) || is_vm_hugetlb_page(vma) ||
1615                                         vma == get_gate_vma(current->mm)))
1616                         mm->locked_vm += (len >> PAGE_SHIFT);
1617                 else
1618                         vma->vm_flags &= ~VM_LOCKED;
1619         }
1620 
1621         if (file)
1622                 uprobe_mmap(vma);
1623 
1624         /*
1625          * New (or expanded) vma always get soft dirty status.
1626          * Otherwise user-space soft-dirty page tracker won't
1627          * be able to distinguish situation when vma area unmapped,
1628          * then new mapped in-place (which must be aimed as
1629          * a completely new data area).
1630          */
1631         vma->vm_flags |= VM_SOFTDIRTY;
1632 
1633         return addr;
1634 
1635 unmap_and_free_vma:
1636         if (vm_flags & VM_DENYWRITE)
1637                 allow_write_access(file);
1638         vma->vm_file = NULL;
1639         fput(file);
1640 
1641         /* Undo any partial mapping done by a device driver. */
1642         unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1643         charged = 0;
1644 free_vma:
1645         kmem_cache_free(vm_area_cachep, vma);
1646 unacct_error:
1647         if (charged)
1648                 vm_unacct_memory(charged);
1649         return error;
1650 }
1651 
1652 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1653 {
1654         /*
1655          * We implement the search by looking for an rbtree node that
1656          * immediately follows a suitable gap. That is,
1657          * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1658          * - gap_end   = vma->vm_start        >= info->low_limit  + length;
1659          * - gap_end - gap_start >= length
1660          */
1661 
1662         struct mm_struct *mm = current->mm;
1663         struct vm_area_struct *vma;
1664         unsigned long length, low_limit, high_limit, gap_start, gap_end;
1665 
1666         /* Adjust search length to account for worst case alignment overhead */
1667         length = info->length + info->align_mask;
1668         if (length < info->length)
1669                 return -ENOMEM;
1670 
1671         /* Adjust search limits by the desired length */
1672         if (info->high_limit < length)
1673                 return -ENOMEM;
1674         high_limit = info->high_limit - length;
1675 
1676         if (info->low_limit > high_limit)
1677                 return -ENOMEM;
1678         low_limit = info->low_limit + length;
1679 
1680         /* Check if rbtree root looks promising */
1681         if (RB_EMPTY_ROOT(&mm->mm_rb))
1682                 goto check_highest;
1683         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1684         if (vma->rb_subtree_gap < length)
1685                 goto check_highest;
1686 
1687         while (true) {
1688                 /* Visit left subtree if it looks promising */
1689                 gap_end = vma->vm_start;
1690                 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1691                         struct vm_area_struct *left =
1692                                 rb_entry(vma->vm_rb.rb_left,
1693                                          struct vm_area_struct, vm_rb);
1694                         if (left->rb_subtree_gap >= length) {
1695                                 vma = left;
1696                                 continue;
1697                         }
1698                 }
1699 
1700                 gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
1701 check_current:
1702                 /* Check if current node has a suitable gap */
1703                 if (gap_start > high_limit)
1704                         return -ENOMEM;
1705                 if (gap_end >= low_limit && gap_end - gap_start >= length)
1706                         goto found;
1707 
1708                 /* Visit right subtree if it looks promising */
1709                 if (vma->vm_rb.rb_right) {
1710                         struct vm_area_struct *right =
1711                                 rb_entry(vma->vm_rb.rb_right,
1712                                          struct vm_area_struct, vm_rb);
1713                         if (right->rb_subtree_gap >= length) {
1714                                 vma = right;
1715                                 continue;
1716                         }
1717                 }
1718 
1719                 /* Go back up the rbtree to find next candidate node */
1720                 while (true) {
1721                         struct rb_node *prev = &vma->vm_rb;
1722                         if (!rb_parent(prev))
1723                                 goto check_highest;
1724                         vma = rb_entry(rb_parent(prev),
1725                                        struct vm_area_struct, vm_rb);
1726                         if (prev == vma->vm_rb.rb_left) {
1727                                 gap_start = vma->vm_prev->vm_end;
1728                                 gap_end = vma->vm_start;
1729                                 goto check_current;
1730                         }
1731                 }
1732         }
1733 
1734 check_highest:
1735         /* Check highest gap, which does not precede any rbtree node */
1736         gap_start = mm->highest_vm_end;
1737         gap_end = ULONG_MAX;  /* Only for VM_BUG_ON below */
1738         if (gap_start > high_limit)
1739                 return -ENOMEM;
1740 
1741 found:
1742         /* We found a suitable gap. Clip it with the original low_limit. */
1743         if (gap_start < info->low_limit)
1744                 gap_start = info->low_limit;
1745 
1746         /* Adjust gap address to the desired alignment */
1747         gap_start += (info->align_offset - gap_start) & info->align_mask;
1748 
1749         VM_BUG_ON(gap_start + info->length > info->high_limit);
1750         VM_BUG_ON(gap_start + info->length > gap_end);
1751         return gap_start;
1752 }
1753 
1754 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1755 {
1756         struct mm_struct *mm = current->mm;
1757         struct vm_area_struct *vma;
1758         unsigned long length, low_limit, high_limit, gap_start, gap_end;
1759 
1760         /* Adjust search length to account for worst case alignment overhead */
1761         length = info->length + info->align_mask;
1762         if (length < info->length)
1763                 return -ENOMEM;
1764 
1765         /*
1766          * Adjust search limits by the desired length.
1767          * See implementation comment at top of unmapped_area().
1768          */
1769         gap_end = info->high_limit;
1770         if (gap_end < length)
1771                 return -ENOMEM;
1772         high_limit = gap_end - length;
1773 
1774         if (info->low_limit > high_limit)
1775                 return -ENOMEM;
1776         low_limit = info->low_limit + length;
1777 
1778         /* Check highest gap, which does not precede any rbtree node */
1779         gap_start = mm->highest_vm_end;
1780         if (gap_start <= high_limit)
1781                 goto found_highest;
1782 
1783         /* Check if rbtree root looks promising */
1784         if (RB_EMPTY_ROOT(&mm->mm_rb))
1785                 return -ENOMEM;
1786         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1787         if (vma->rb_subtree_gap < length)
1788                 return -ENOMEM;
1789 
1790         while (true) {
1791                 /* Visit right subtree if it looks promising */
1792                 gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
1793                 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
1794                         struct vm_area_struct *right =
1795                                 rb_entry(vma->vm_rb.rb_right,
1796                                          struct vm_area_struct, vm_rb);
1797                         if (right->rb_subtree_gap >= length) {
1798                                 vma = right;
1799                                 continue;
1800                         }
1801                 }
1802 
1803 check_current:
1804                 /* Check if current node has a suitable gap */
1805                 gap_end = vma->vm_start;
1806                 if (gap_end < low_limit)
1807                         return -ENOMEM;
1808                 if (gap_start <= high_limit && gap_end - gap_start >= length)
1809                         goto found;
1810 
1811                 /* Visit left subtree if it looks promising */
1812                 if (vma->vm_rb.rb_left) {
1813                         struct vm_area_struct *left =
1814                                 rb_entry(vma->vm_rb.rb_left,
1815                                          struct vm_area_struct, vm_rb);
1816                         if (left->rb_subtree_gap >= length) {
1817                                 vma = left;
1818                                 continue;
1819                         }
1820                 }
1821 
1822                 /* Go back up the rbtree to find next candidate node */
1823                 while (true) {
1824                         struct rb_node *prev = &vma->vm_rb;
1825                         if (!rb_parent(prev))
1826                                 return -ENOMEM;
1827                         vma = rb_entry(rb_parent(prev),
1828                                        struct vm_area_struct, vm_rb);
1829                         if (prev == vma->vm_rb.rb_right) {
1830                                 gap_start = vma->vm_prev ?
1831                                         vma->vm_prev->vm_end : 0;
1832                                 goto check_current;
1833                         }
1834                 }
1835         }
1836 
1837 found:
1838         /* We found a suitable gap. Clip it with the original high_limit. */
1839         if (gap_end > info->high_limit)
1840                 gap_end = info->high_limit;
1841 
1842 found_highest:
1843         /* Compute highest gap address at the desired alignment */
1844         gap_end -= info->length;
1845         gap_end -= (gap_end - info->align_offset) & info->align_mask;
1846 
1847         VM_BUG_ON(gap_end < info->low_limit);
1848         VM_BUG_ON(gap_end < gap_start);
1849         return gap_end;
1850 }
1851 
1852 /* Get an address range which is currently unmapped.
1853  * For shmat() with addr=0.
1854  *
1855  * Ugly calling convention alert:
1856  * Return value with the low bits set means error value,
1857  * ie
1858  *      if (ret & ~PAGE_MASK)
1859  *              error = ret;
1860  *
1861  * This function "knows" that -ENOMEM has the bits set.
1862  */
1863 #ifndef HAVE_ARCH_UNMAPPED_AREA
1864 unsigned long
1865 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1866                 unsigned long len, unsigned long pgoff, unsigned long flags)
1867 {
1868         struct mm_struct *mm = current->mm;
1869         struct vm_area_struct *vma;
1870         struct vm_unmapped_area_info info;
1871 
1872         if (len > TASK_SIZE - mmap_min_addr)
1873                 return -ENOMEM;
1874 
1875         if (flags & MAP_FIXED)
1876                 return addr;
1877 
1878         if (addr) {
1879                 addr = PAGE_ALIGN(addr);
1880                 vma = find_vma(mm, addr);
1881                 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1882                     (!vma || addr + len <= vma->vm_start))
1883                         return addr;
1884         }
1885 
1886         info.flags = 0;
1887         info.length = len;
1888         info.low_limit = TASK_UNMAPPED_BASE;
1889         info.high_limit = TASK_SIZE;
1890         info.align_mask = 0;
1891         return vm_unmapped_area(&info);
1892 }
1893 #endif  
1894 
1895 /*
1896  * This mmap-allocator allocates new areas top-down from below the
1897  * stack's low limit (the base):
1898  */
1899 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1900 unsigned long
1901 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1902                           const unsigned long len, const unsigned long pgoff,
1903                           const unsigned long flags)
1904 {
1905         struct vm_area_struct *vma;
1906         struct mm_struct *mm = current->mm;
1907         unsigned long addr = addr0;
1908         struct vm_unmapped_area_info info;
1909 
1910         /* requested length too big for entire address space */
1911         if (len > TASK_SIZE - mmap_min_addr)
1912                 return -ENOMEM;
1913 
1914         if (flags & MAP_FIXED)
1915                 return addr;
1916 
1917         /* requesting a specific address */
1918         if (addr) {
1919                 addr = PAGE_ALIGN(addr);
1920                 vma = find_vma(mm, addr);
1921                 if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1922                                 (!vma || addr + len <= vma->vm_start))
1923                         return addr;
1924         }
1925 
1926         info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1927         info.length = len;
1928         info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1929         info.high_limit = mm->mmap_base;
1930         info.align_mask = 0;
1931         addr = vm_unmapped_area(&info);
1932 
1933         /*
1934          * A failed mmap() very likely causes application failure,
1935          * so fall back to the bottom-up function here. This scenario
1936          * can happen with large stack limits and large mmap()
1937          * allocations.
1938          */
1939         if (addr & ~PAGE_MASK) {
1940                 VM_BUG_ON(addr != -ENOMEM);
1941                 info.flags = 0;
1942                 info.low_limit = TASK_UNMAPPED_BASE;
1943                 info.high_limit = TASK_SIZE;
1944                 addr = vm_unmapped_area(&info);
1945         }
1946 
1947         return addr;
1948 }
1949 #endif
1950 
1951 unsigned long
1952 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
1953                 unsigned long pgoff, unsigned long flags)
1954 {
1955         unsigned long (*get_area)(struct file *, unsigned long,
1956                                   unsigned long, unsigned long, unsigned long);
1957 
1958         unsigned long error = arch_mmap_check(addr, len, flags);
1959         if (error)
1960                 return error;
1961 
1962         /* Careful about overflows.. */
1963         if (len > TASK_SIZE)
1964                 return -ENOMEM;
1965 
1966         get_area = current->mm->get_unmapped_area;
1967         if (file && file->f_op && file->f_op->get_unmapped_area)
1968                 get_area = file->f_op->get_unmapped_area;
1969         addr = get_area(file, addr, len, pgoff, flags);
1970         if (IS_ERR_VALUE(addr))
1971                 return addr;
1972 
1973         if (addr > TASK_SIZE - len)
1974                 return -ENOMEM;
1975         if (addr & ~PAGE_MASK)
1976                 return -EINVAL;
1977 
1978         addr = arch_rebalance_pgtables(addr, len);
1979         error = security_mmap_addr(addr);
1980         return error ? error : addr;
1981 }
1982 
1983 EXPORT_SYMBOL(get_unmapped_area);
1984 
1985 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
1986 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1987 {
1988         struct rb_node *rb_node;
1989         struct vm_area_struct *vma;
1990 
1991         /* Check the cache first. */
1992         vma = vmacache_find(mm, addr);
1993         if (likely(vma))
1994                 return vma;
1995 
1996         rb_node = mm->mm_rb.rb_node;
1997         vma = NULL;
1998 
1999         while (rb_node) {
2000                 struct vm_area_struct *tmp;
2001 
2002                 tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2003 
2004                 if (tmp->vm_end > addr) {
2005                         vma = tmp;
2006                         if (tmp->vm_start <= addr)
2007                                 break;
2008                         rb_node = rb_node->rb_left;
2009                 } else
2010                         rb_node = rb_node->rb_right;
2011         }
2012 
2013         if (vma)
2014                 vmacache_update(addr, vma);
2015         return vma;
2016 }
2017 
2018 EXPORT_SYMBOL(find_vma);
2019 
2020 /*
2021  * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2022  */
2023 struct vm_area_struct *
2024 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2025                         struct vm_area_struct **pprev)
2026 {
2027         struct vm_area_struct *vma;
2028 
2029         vma = find_vma(mm, addr);
2030         if (vma) {
2031                 *pprev = vma->vm_prev;
2032         } else {
2033                 struct rb_node *rb_node = mm->mm_rb.rb_node;
2034                 *pprev = NULL;
2035                 while (rb_node) {
2036                         *pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2037                         rb_node = rb_node->rb_right;
2038                 }
2039         }
2040         return vma;
2041 }
2042 
2043 /*
2044  * Verify that the stack growth is acceptable and
2045  * update accounting. This is shared with both the
2046  * grow-up and grow-down cases.
2047  */
2048 static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
2049 {
2050         struct mm_struct *mm = vma->vm_mm;
2051         struct rlimit *rlim = current->signal->rlim;
2052         unsigned long new_start, actual_size;
2053 
2054         /* address space limit tests */
2055         if (!may_expand_vm(mm, grow))
2056                 return -ENOMEM;
2057 
2058         /* Stack limit test */
2059         actual_size = size;
2060         if (size && (vma->vm_flags & (VM_GROWSUP | VM_GROWSDOWN)))
2061                 actual_size -= PAGE_SIZE;
2062         if (actual_size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur))
2063                 return -ENOMEM;
2064 
2065         /* mlock limit tests */
2066         if (vma->vm_flags & VM_LOCKED) {
2067                 unsigned long locked;
2068                 unsigned long limit;
2069                 locked = mm->locked_vm + grow;
2070                 limit = ACCESS_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
2071                 limit >>= PAGE_SHIFT;
2072                 if (locked > limit && !capable(CAP_IPC_LOCK))
2073                         return -ENOMEM;
2074         }
2075 
2076         /* Check to ensure the stack will not grow into a hugetlb-only region */
2077         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2078                         vma->vm_end - size;
2079         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2080                 return -EFAULT;
2081 
2082         /*
2083          * Overcommit..  This must be the final test, as it will
2084          * update security statistics.
2085          */
2086         if (security_vm_enough_memory_mm(mm, grow))
2087                 return -ENOMEM;
2088 
2089         /* Ok, everything looks good - let it rip */
2090         if (vma->vm_flags & VM_LOCKED)
2091                 mm->locked_vm += grow;
2092         vm_stat_account(mm, vma->vm_flags, vma->vm_file, grow);
2093         return 0;
2094 }
2095 
2096 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2097 /*
2098  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2099  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2100  */
2101 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2102 {
2103         int error;
2104 
2105         if (!(vma->vm_flags & VM_GROWSUP))
2106                 return -EFAULT;
2107 
2108         /*
2109          * We must make sure the anon_vma is allocated
2110          * so that the anon_vma locking is not a noop.
2111          */
2112         if (unlikely(anon_vma_prepare(vma)))
2113                 return -ENOMEM;
2114         vma_lock_anon_vma(vma);
2115 
2116         /*
2117          * vma->vm_start/vm_end cannot change under us because the caller
2118          * is required to hold the mmap_sem in read mode.  We need the
2119          * anon_vma lock to serialize against concurrent expand_stacks.
2120          * Also guard against wrapping around to address 0.
2121          */
2122         if (address < PAGE_ALIGN(address+4))
2123                 address = PAGE_ALIGN(address+4);
2124         else {
2125                 vma_unlock_anon_vma(vma);
2126                 return -ENOMEM;
2127         }
2128         error = 0;
2129 
2130         /* Somebody else might have raced and expanded it already */
2131         if (address > vma->vm_end) {
2132                 unsigned long size, grow;
2133 
2134                 size = address - vma->vm_start;
2135                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2136 
2137                 error = -ENOMEM;
2138                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2139                         error = acct_stack_growth(vma, size, grow);
2140                         if (!error) {
2141                                 /*
2142                                  * vma_gap_update() doesn't support concurrent
2143                                  * updates, but we only hold a shared mmap_sem
2144                                  * lock here, so we need to protect against
2145                                  * concurrent vma expansions.
2146                                  * vma_lock_anon_vma() doesn't help here, as
2147                                  * we don't guarantee that all growable vmas
2148                                  * in a mm share the same root anon vma.
2149                                  * So, we reuse mm->page_table_lock to guard
2150                                  * against concurrent vma expansions.
2151                                  */
2152                                 spin_lock(&vma->vm_mm->page_table_lock);
2153                                 anon_vma_interval_tree_pre_update_vma(vma);
2154                                 vma->vm_end = address;
2155                                 anon_vma_interval_tree_post_update_vma(vma);
2156                                 if (vma->vm_next)
2157                                         vma_gap_update(vma->vm_next);
2158                                 else
2159                                         vma->vm_mm->highest_vm_end = address;
2160                                 spin_unlock(&vma->vm_mm->page_table_lock);
2161 
2162                                 perf_event_mmap(vma);
2163                         }
2164                 }
2165         }
2166         vma_unlock_anon_vma(vma);
2167         khugepaged_enter_vma_merge(vma);
2168         validate_mm(vma->vm_mm);
2169         return error;
2170 }
2171 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2172 
2173 /*
2174  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2175  */
2176 int expand_downwards(struct vm_area_struct *vma,
2177                                    unsigned long address)
2178 {
2179         int error;
2180 
2181         /*
2182          * We must make sure the anon_vma is allocated
2183          * so that the anon_vma locking is not a noop.
2184          */
2185         if (unlikely(anon_vma_prepare(vma)))
2186                 return -ENOMEM;
2187 
2188         address &= PAGE_MASK;
2189         error = security_mmap_addr(address);
2190         if (error)
2191                 return error;
2192 
2193         vma_lock_anon_vma(vma);
2194 
2195         /*
2196          * vma->vm_start/vm_end cannot change under us because the caller
2197          * is required to hold the mmap_sem in read mode.  We need the
2198          * anon_vma lock to serialize against concurrent expand_stacks.
2199          */
2200 
2201         /* Somebody else might have raced and expanded it already */
2202         if (address < vma->vm_start) {
2203                 unsigned long size, grow;
2204 
2205                 size = vma->vm_end - address;
2206                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2207 
2208                 error = -ENOMEM;
2209                 if (grow <= vma->vm_pgoff) {
2210                         error = acct_stack_growth(vma, size, grow);
2211                         if (!error) {
2212                                 /*
2213                                  * vma_gap_update() doesn't support concurrent
2214                                  * updates, but we only hold a shared mmap_sem
2215                                  * lock here, so we need to protect against
2216                                  * concurrent vma expansions.
2217                                  * vma_lock_anon_vma() doesn't help here, as
2218                                  * we don't guarantee that all growable vmas
2219                                  * in a mm share the same root anon vma.
2220                                  * So, we reuse mm->page_table_lock to guard
2221                                  * against concurrent vma expansions.
2222                                  */
2223                                 spin_lock(&vma->vm_mm->page_table_lock);
2224                                 anon_vma_interval_tree_pre_update_vma(vma);
2225                                 vma->vm_start = address;
2226                                 vma->vm_pgoff -= grow;
2227                                 anon_vma_interval_tree_post_update_vma(vma);
2228                                 vma_gap_update(vma);
2229                                 spin_unlock(&vma->vm_mm->page_table_lock);
2230 
2231                                 perf_event_mmap(vma);
2232                         }
2233                 }
2234         }
2235         vma_unlock_anon_vma(vma);
2236         khugepaged_enter_vma_merge(vma);
2237         validate_mm(vma->vm_mm);
2238         return error;
2239 }
2240 
2241 /*
2242  * Note how expand_stack() refuses to expand the stack all the way to
2243  * abut the next virtual mapping, *unless* that mapping itself is also
2244  * a stack mapping. We want to leave room for a guard page, after all
2245  * (the guard page itself is not added here, that is done by the
2246  * actual page faulting logic)
2247  *
2248  * This matches the behavior of the guard page logic (see mm/memory.c:
2249  * check_stack_guard_page()), which only allows the guard page to be
2250  * removed under these circumstances.
2251  */
2252 #ifdef CONFIG_STACK_GROWSUP
2253 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2254 {
2255         struct vm_area_struct *next;
2256 
2257         address &= PAGE_MASK;
2258         next = vma->vm_next;
2259         if (next && next->vm_start == address + PAGE_SIZE) {
2260                 if (!(next->vm_flags & VM_GROWSUP))
2261                         return -ENOMEM;
2262         }
2263         return expand_upwards(vma, address);
2264 }
2265 
2266 struct vm_area_struct *
2267 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2268 {
2269         struct vm_area_struct *vma, *prev;
2270 
2271         addr &= PAGE_MASK;
2272         vma = find_vma_prev(mm, addr, &prev);
2273         if (vma && (vma->vm_start <= addr))
2274                 return vma;
2275         if (!prev || expand_stack(prev, addr))
2276                 return NULL;
2277         if (prev->vm_flags & VM_LOCKED)
2278                 __mlock_vma_pages_range(prev, addr, prev->vm_end, NULL);
2279         return prev;
2280 }
2281 #else
2282 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2283 {
2284         struct vm_area_struct *prev;
2285 
2286         address &= PAGE_MASK;
2287         prev = vma->vm_prev;
2288         if (prev && prev->vm_end == address) {
2289                 if (!(prev->vm_flags & VM_GROWSDOWN))
2290                         return -ENOMEM;
2291         }
2292         return expand_downwards(vma, address);
2293 }
2294 
2295 struct vm_area_struct *
2296 find_extend_vma(struct mm_struct * mm, unsigned long addr)
2297 {
2298         struct vm_area_struct * vma;
2299         unsigned long start;
2300 
2301         addr &= PAGE_MASK;
2302         vma = find_vma(mm,addr);
2303         if (!vma)
2304                 return NULL;
2305         if (vma->vm_start <= addr)
2306                 return vma;
2307         if (!(vma->vm_flags & VM_GROWSDOWN))
2308                 return NULL;
2309         start = vma->vm_start;
2310         if (expand_stack(vma, addr))
2311                 return NULL;
2312         if (vma->vm_flags & VM_LOCKED)
2313                 __mlock_vma_pages_range(vma, addr, start, NULL);
2314         return vma;
2315 }
2316 #endif
2317 
2318 /*
2319  * Ok - we have the memory areas we should free on the vma list,
2320  * so release them, and do the vma updates.
2321  *
2322  * Called with the mm semaphore held.
2323  */
2324 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2325 {
2326         unsigned long nr_accounted = 0;
2327 
2328         /* Update high watermark before we lower total_vm */
2329         update_hiwater_vm(mm);
2330         do {
2331                 long nrpages = vma_pages(vma);
2332 
2333                 if (vma->vm_flags & VM_ACCOUNT)
2334                         nr_accounted += nrpages;
2335                 vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
2336                 vma = remove_vma(vma);
2337         } while (vma);
2338         vm_unacct_memory(nr_accounted);
2339         validate_mm(mm);
2340 }
2341 
2342 /*
2343  * Get rid of page table information in the indicated region.
2344  *
2345  * Called with the mm semaphore held.
2346  */
2347 static void unmap_region(struct mm_struct *mm,
2348                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2349                 unsigned long start, unsigned long end)
2350 {
2351         struct vm_area_struct *next = prev? prev->vm_next: mm->mmap;
2352         struct mmu_gather tlb;
2353 
2354         lru_add_drain();
2355         tlb_gather_mmu(&tlb, mm, start, end);
2356         update_hiwater_rss(mm);
2357         unmap_vmas(&tlb, vma, start, end);
2358         free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2359                                  next ? next->vm_start : USER_PGTABLES_CEILING);
2360         tlb_finish_mmu(&tlb, start, end);
2361 }
2362 
2363 /*
2364  * Create a list of vma's touched by the unmap, removing them from the mm's
2365  * vma list as we go..
2366  */
2367 static void
2368 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2369         struct vm_area_struct *prev, unsigned long end)
2370 {
2371         struct vm_area_struct **insertion_point;
2372         struct vm_area_struct *tail_vma = NULL;
2373 
2374         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2375         vma->vm_prev = NULL;
2376         do {
2377                 vma_rb_erase(vma, &mm->mm_rb);
2378                 mm->map_count--;
2379                 tail_vma = vma;
2380                 vma = vma->vm_next;
2381         } while (vma && vma->vm_start < end);
2382         *insertion_point = vma;
2383         if (vma) {
2384                 vma->vm_prev = prev;
2385                 vma_gap_update(vma);
2386         } else
2387                 mm->highest_vm_end = prev ? prev->vm_end : 0;
2388         tail_vma->vm_next = NULL;
2389 
2390         /* Kill the cache */
2391         vmacache_invalidate(mm);
2392 }
2393 
2394 /*
2395  * __split_vma() bypasses sysctl_max_map_count checking.  We use this on the
2396  * munmap path where it doesn't make sense to fail.
2397  */
2398 static int __split_vma(struct mm_struct * mm, struct vm_area_struct * vma,
2399               unsigned long addr, int new_below)
2400 {
2401         struct vm_area_struct *new;
2402         int err = -ENOMEM;
2403 
2404         if (is_vm_hugetlb_page(vma) && (addr &
2405                                         ~(huge_page_mask(hstate_vma(vma)))))
2406                 return -EINVAL;
2407 
2408         new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2409         if (!new)
2410                 goto out_err;
2411 
2412         /* most fields are the same, copy all, and then fixup */
2413         *new = *vma;
2414 
2415         INIT_LIST_HEAD(&new->anon_vma_chain);
2416 
2417         if (new_below)
2418                 new->vm_end = addr;
2419         else {
2420                 new->vm_start = addr;
2421                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2422         }
2423 
2424         err = vma_dup_policy(vma, new);
2425         if (err)
2426                 goto out_free_vma;
2427 
2428         err = anon_vma_clone(new, vma);
2429         if (err)
2430                 goto out_free_mpol;
2431 
2432         if (new->vm_file)
2433                 get_file(new->vm_file);
2434 
2435         if (new->vm_ops && new->vm_ops->open)
2436                 new->vm_ops->open(new);
2437 
2438         if (new_below)
2439                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2440                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2441         else
2442                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2443 
2444         /* Success. */
2445         if (!err)
2446                 return 0;
2447 
2448         /* Clean everything up if vma_adjust failed. */
2449         if (new->vm_ops && new->vm_ops->close)
2450                 new->vm_ops->close(new);
2451         if (new->vm_file)
2452                 fput(new->vm_file);
2453         unlink_anon_vmas(new);
2454  out_free_mpol:
2455         mpol_put(vma_policy(new));
2456  out_free_vma:
2457         kmem_cache_free(vm_area_cachep, new);
2458  out_err:
2459         return err;
2460 }
2461 
2462 /*
2463  * Split a vma into two pieces at address 'addr', a new vma is allocated
2464  * either for the first part or the tail.
2465  */
2466 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2467               unsigned long addr, int new_below)
2468 {
2469         if (mm->map_count >= sysctl_max_map_count)
2470                 return -ENOMEM;
2471 
2472         return __split_vma(mm, vma, addr, new_below);
2473 }
2474 
2475 /* Munmap is split into 2 main parts -- this part which finds
2476  * what needs doing, and the areas themselves, which do the
2477  * work.  This now handles partial unmappings.
2478  * Jeremy Fitzhardinge <jeremy@goop.org>
2479  */
2480 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2481 {
2482         unsigned long end;
2483         struct vm_area_struct *vma, *prev, *last;
2484 
2485         if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
2486                 return -EINVAL;
2487 
2488         if ((len = PAGE_ALIGN(len)) == 0)
2489                 return -EINVAL;
2490 
2491         /* Find the first overlapping VMA */
2492         vma = find_vma(mm, start);
2493         if (!vma)
2494                 return 0;
2495         prev = vma->vm_prev;
2496         /* we have  start < vma->vm_end  */
2497 
2498         /* if it doesn't overlap, we have nothing.. */
2499         end = start + len;
2500         if (vma->vm_start >= end)
2501                 return 0;
2502 
2503         /*
2504          * If we need to split any vma, do it now to save pain later.
2505          *
2506          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2507          * unmapped vm_area_struct will remain in use: so lower split_vma
2508          * places tmp vma above, and higher split_vma places tmp vma below.
2509          */
2510         if (start > vma->vm_start) {
2511                 int error;
2512 
2513                 /*
2514                  * Make sure that map_count on return from munmap() will
2515                  * not exceed its limit; but let map_count go just above
2516                  * its limit temporarily, to help free resources as expected.
2517                  */
2518                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2519                         return -ENOMEM;
2520 
2521                 error = __split_vma(mm, vma, start, 0);
2522                 if (error)
2523                         return error;
2524                 prev = vma;
2525         }
2526 
2527         /* Does it split the last one? */
2528         last = find_vma(mm, end);
2529         if (last && end > last->vm_start) {
2530                 int error = __split_vma(mm, last, end, 1);
2531                 if (error)
2532                         return error;
2533         }
2534         vma = prev? prev->vm_next: mm->mmap;
2535 
2536         /*
2537          * unlock any mlock()ed ranges before detaching vmas
2538          */
2539         if (mm->locked_vm) {
2540                 struct vm_area_struct *tmp = vma;
2541                 while (tmp && tmp->vm_start < end) {
2542                         if (tmp->vm_flags & VM_LOCKED) {
2543                                 mm->locked_vm -= vma_pages(tmp);
2544                                 munlock_vma_pages_all(tmp);
2545                         }
2546                         tmp = tmp->vm_next;
2547                 }
2548         }
2549 
2550         /*
2551          * Remove the vma's, and unmap the actual pages
2552          */
2553         detach_vmas_to_be_unmapped(mm, vma, prev, end);
2554         unmap_region(mm, vma, prev, start, end);
2555 
2556         /* Fix up all other VM information */
2557         remove_vma_list(mm, vma);
2558 
2559         return 0;
2560 }
2561 
2562 int vm_munmap(unsigned long start, size_t len)
2563 {
2564         int ret;
2565         struct mm_struct *mm = current->mm;
2566 
2567         down_write(&mm->mmap_sem);
2568         ret = do_munmap(mm, start, len);
2569         up_write(&mm->mmap_sem);
2570         return ret;
2571 }
2572 EXPORT_SYMBOL(vm_munmap);
2573 
2574 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2575 {
2576         profile_munmap(addr);
2577         return vm_munmap(addr, len);
2578 }
2579 
2580 static inline void verify_mm_writelocked(struct mm_struct *mm)
2581 {
2582 #ifdef CONFIG_DEBUG_VM
2583         if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2584                 WARN_ON(1);
2585                 up_read(&mm->mmap_sem);
2586         }
2587 #endif
2588 }
2589 
2590 /*
2591  *  this is really a simplified "do_mmap".  it only handles
2592  *  anonymous maps.  eventually we may be able to do some
2593  *  brk-specific accounting here.
2594  */
2595 static unsigned long do_brk(unsigned long addr, unsigned long len)
2596 {
2597         struct mm_struct * mm = current->mm;
2598         struct vm_area_struct * vma, * prev;
2599         unsigned long flags;
2600         struct rb_node ** rb_link, * rb_parent;
2601         pgoff_t pgoff = addr >> PAGE_SHIFT;
2602         int error;
2603 
2604         len = PAGE_ALIGN(len);
2605         if (!len)
2606                 return addr;
2607 
2608         flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2609 
2610         error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2611         if (error & ~PAGE_MASK)
2612                 return error;
2613 
2614         /*
2615          * mlock MCL_FUTURE?
2616          */
2617         if (mm->def_flags & VM_LOCKED) {
2618                 unsigned long locked, lock_limit;
2619                 locked = len >> PAGE_SHIFT;
2620                 locked += mm->locked_vm;
2621                 lock_limit = rlimit(RLIMIT_MEMLOCK);
2622                 lock_limit >>= PAGE_SHIFT;
2623                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
2624                         return -EAGAIN;
2625         }
2626 
2627         /*
2628          * mm->mmap_sem is required to protect against another thread
2629          * changing the mappings in case we sleep.
2630          */
2631         verify_mm_writelocked(mm);
2632 
2633         /*
2634          * Clear old maps.  this also does some error checking for us
2635          */
2636  munmap_back:
2637         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {
2638                 if (do_munmap(mm, addr, len))
2639                         return -ENOMEM;
2640                 goto munmap_back;
2641         }
2642 
2643         /* Check against address space limits *after* clearing old maps... */
2644         if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2645                 return -ENOMEM;
2646 
2647         if (mm->map_count > sysctl_max_map_count)
2648                 return -ENOMEM;
2649 
2650         if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2651                 return -ENOMEM;
2652 
2653         /* Can we just expand an old private anonymous mapping? */
2654         vma = vma_merge(mm, prev, addr, addr + len, flags,
2655                                         NULL, NULL, pgoff, NULL);
2656         if (vma)
2657                 goto out;
2658 
2659         /*
2660          * create a vma struct for an anonymous mapping
2661          */
2662         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2663         if (!vma) {
2664                 vm_unacct_memory(len >> PAGE_SHIFT);
2665                 return -ENOMEM;
2666         }
2667 
2668         INIT_LIST_HEAD(&vma->anon_vma_chain);
2669         vma->vm_mm = mm;
2670         vma->vm_start = addr;
2671         vma->vm_end = addr + len;
2672         vma->vm_pgoff = pgoff;
2673         vma->vm_flags = flags;
2674         vma->vm_page_prot = vm_get_page_prot(flags);
2675         vma_link(mm, vma, prev, rb_link, rb_parent);
2676 out:
2677         perf_event_mmap(vma);
2678         mm->total_vm += len >> PAGE_SHIFT;
2679         if (flags & VM_LOCKED)
2680                 mm->locked_vm += (len >> PAGE_SHIFT);
2681         vma->vm_flags |= VM_SOFTDIRTY;
2682         return addr;
2683 }
2684 
2685 unsigned long vm_brk(unsigned long addr, unsigned long len)
2686 {
2687         struct mm_struct *mm = current->mm;
2688         unsigned long ret;
2689         bool populate;
2690 
2691         down_write(&mm->mmap_sem);
2692         ret = do_brk(addr, len);
2693         populate = ((mm->def_flags & VM_LOCKED) != 0);
2694         up_write(&mm->mmap_sem);
2695         if (populate)
2696                 mm_populate(addr, len);
2697         return ret;
2698 }
2699 EXPORT_SYMBOL(vm_brk);
2700 
2701 /* Release all mmaps. */
2702 void exit_mmap(struct mm_struct *mm)
2703 {
2704         struct mmu_gather tlb;
2705         struct vm_area_struct *vma;
2706         unsigned long nr_accounted = 0;
2707 
2708         /* mm's last user has gone, and its about to be pulled down */
2709         mmu_notifier_release(mm);
2710 
2711         if (mm->locked_vm) {
2712                 vma = mm->mmap;
2713                 while (vma) {
2714                         if (vma->vm_flags & VM_LOCKED)
2715                                 munlock_vma_pages_all(vma);
2716                         vma = vma->vm_next;
2717                 }
2718         }
2719 
2720         arch_exit_mmap(mm);
2721 
2722         vma = mm->mmap;
2723         if (!vma)       /* Can happen if dup_mmap() received an OOM */
2724                 return;
2725 
2726         lru_add_drain();
2727         flush_cache_mm(mm);
2728         tlb_gather_mmu(&tlb, mm, 0, -1);
2729         /* update_hiwater_rss(mm) here? but nobody should be looking */
2730         /* Use -1 here to ensure all VMAs in the mm are unmapped */
2731         unmap_vmas(&tlb, vma, 0, -1);
2732 
2733         free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
2734         tlb_finish_mmu(&tlb, 0, -1);
2735 
2736         /*
2737          * Walk the list again, actually closing and freeing it,
2738          * with preemption enabled, without holding any MM locks.
2739          */
2740         while (vma) {
2741                 if (vma->vm_flags & VM_ACCOUNT)
2742                         nr_accounted += vma_pages(vma);
2743                 vma = remove_vma(vma);
2744         }
2745         vm_unacct_memory(nr_accounted);
2746 
2747         WARN_ON(mm->nr_ptes > (FIRST_USER_ADDRESS+PMD_SIZE-1)>>PMD_SHIFT);
2748 }
2749 
2750 /* Insert vm structure into process list sorted by address
2751  * and into the inode's i_mmap tree.  If vm_file is non-NULL
2752  * then i_mmap_mutex is taken here.
2753  */
2754 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
2755 {
2756         struct vm_area_struct *prev;
2757         struct rb_node **rb_link, *rb_parent;
2758 
2759         /*
2760          * The vm_pgoff of a purely anonymous vma should be irrelevant
2761          * until its first write fault, when page's anon_vma and index
2762          * are set.  But now set the vm_pgoff it will almost certainly
2763          * end up with (unless mremap moves it elsewhere before that
2764          * first wfault), so /proc/pid/maps tells a consistent story.
2765          *
2766          * By setting it to reflect the virtual start address of the
2767          * vma, merges and splits can happen in a seamless way, just
2768          * using the existing file pgoff checks and manipulations.
2769          * Similarly in do_mmap_pgoff and in do_brk.
2770          */
2771         if (!vma->vm_file) {
2772                 BUG_ON(vma->anon_vma);
2773                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2774         }
2775         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
2776                            &prev, &rb_link, &rb_parent))
2777                 return -ENOMEM;
2778         if ((vma->vm_flags & VM_ACCOUNT) &&
2779              security_vm_enough_memory_mm(mm, vma_pages(vma)))
2780                 return -ENOMEM;
2781 
2782         vma_link(mm, vma, prev, rb_link, rb_parent);
2783         return 0;
2784 }
2785 
2786 /*
2787  * Copy the vma structure to a new location in the same mm,
2788  * prior to moving page table entries, to effect an mremap move.
2789  */
2790 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2791         unsigned long addr, unsigned long len, pgoff_t pgoff,
2792         bool *need_rmap_locks)
2793 {
2794         struct vm_area_struct *vma = *vmap;
2795         unsigned long vma_start = vma->vm_start;
2796         struct mm_struct *mm = vma->vm_mm;
2797         struct vm_area_struct *new_vma, *prev;
2798         struct rb_node **rb_link, *rb_parent;
2799         bool faulted_in_anon_vma = true;
2800 
2801         /*
2802          * If anonymous vma has not yet been faulted, update new pgoff
2803          * to match new location, to increase its chance of merging.
2804          */
2805         if (unlikely(!vma->vm_file && !vma->anon_vma)) {
2806                 pgoff = addr >> PAGE_SHIFT;
2807                 faulted_in_anon_vma = false;
2808         }
2809 
2810         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
2811                 return NULL;    /* should never get here */
2812         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2813                         vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma));
2814         if (new_vma) {
2815                 /*
2816                  * Source vma may have been merged into new_vma
2817                  */
2818                 if (unlikely(vma_start >= new_vma->vm_start &&
2819                              vma_start < new_vma->vm_end)) {
2820                         /*
2821                          * The only way we can get a vma_merge with
2822                          * self during an mremap is if the vma hasn't
2823                          * been faulted in yet and we were allowed to
2824                          * reset the dst vma->vm_pgoff to the
2825                          * destination address of the mremap to allow
2826                          * the merge to happen. mremap must change the
2827                          * vm_pgoff linearity between src and dst vmas
2828                          * (in turn preventing a vma_merge) to be
2829                          * safe. It is only safe to keep the vm_pgoff
2830                          * linear if there are no pages mapped yet.
2831                          */
2832                         VM_BUG_ON(faulted_in_anon_vma);
2833                         *vmap = vma = new_vma;
2834                 }
2835                 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
2836         } else {
2837                 new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2838                 if (new_vma) {
2839                         *new_vma = *vma;
2840                         new_vma->vm_start = addr;
2841                         new_vma->vm_end = addr + len;
2842                         new_vma->vm_pgoff = pgoff;
2843                         if (vma_dup_policy(vma, new_vma))
2844                                 goto out_free_vma;
2845                         INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2846                         if (anon_vma_clone(new_vma, vma))
2847                                 goto out_free_mempol;
2848                         if (new_vma->vm_file)
2849                                 get_file(new_vma->vm_file);
2850                         if (new_vma->vm_ops && new_vma->vm_ops->open)
2851                                 new_vma->vm_ops->open(new_vma);
2852                         vma_link(mm, new_vma, prev, rb_link, rb_parent);
2853                         *need_rmap_locks = false;
2854                 }
2855         }
2856         return new_vma;
2857 
2858  out_free_mempol:
2859         mpol_put(vma_policy(new_vma));
2860  out_free_vma:
2861         kmem_cache_free(vm_area_cachep, new_vma);
2862         return NULL;
2863 }
2864 
2865 /*
2866  * Return true if the calling process may expand its vm space by the passed
2867  * number of pages
2868  */
2869 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
2870 {
2871         unsigned long cur = mm->total_vm;       /* pages */
2872         unsigned long lim;
2873 
2874         lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
2875 
2876         if (cur + npages > lim)
2877                 return 0;
2878         return 1;
2879 }
2880 
2881 
2882 static int special_mapping_fault(struct vm_area_struct *vma,
2883                                 struct vm_fault *vmf)
2884 {
2885         pgoff_t pgoff;
2886         struct page **pages;
2887 
2888         /*
2889          * special mappings have no vm_file, and in that case, the mm
2890          * uses vm_pgoff internally. So we have to subtract it from here.
2891          * We are allowed to do this because we are the mm; do not copy
2892          * this code into drivers!
2893          */
2894         pgoff = vmf->pgoff - vma->vm_pgoff;
2895 
2896         for (pages = vma->vm_private_data; pgoff && *pages; ++pages)
2897                 pgoff--;
2898 
2899         if (*pages) {
2900                 struct page *page = *pages;
2901                 get_page(page);
2902                 vmf->page = page;
2903                 return 0;
2904         }
2905 
2906         return VM_FAULT_SIGBUS;
2907 }
2908 
2909 /*
2910  * Having a close hook prevents vma merging regardless of flags.
2911  */
2912 static void special_mapping_close(struct vm_area_struct *vma)
2913 {
2914 }
2915 
2916 static const struct vm_operations_struct special_mapping_vmops = {
2917         .close = special_mapping_close,
2918         .fault = special_mapping_fault,
2919 };
2920 
2921 /*
2922  * Called with mm->mmap_sem held for writing.
2923  * Insert a new vma covering the given region, with the given flags.
2924  * Its pages are supplied by the given array of struct page *.
2925  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
2926  * The region past the last page supplied will always produce SIGBUS.
2927  * The array pointer and the pages it points to are assumed to stay alive
2928  * for as long as this mapping might exist.
2929  */
2930 int install_special_mapping(struct mm_struct *mm,
2931                             unsigned long addr, unsigned long len,
2932                             unsigned long vm_flags, struct page **pages)
2933 {
2934         int ret;
2935         struct vm_area_struct *vma;
2936 
2937         vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2938         if (unlikely(vma == NULL))
2939                 return -ENOMEM;
2940 
2941         INIT_LIST_HEAD(&vma->anon_vma_chain);
2942         vma->vm_mm = mm;
2943         vma->vm_start = addr;
2944         vma->vm_end = addr + len;
2945 
2946         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
2947         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
2948 
2949         vma->vm_ops = &special_mapping_vmops;
2950         vma->vm_private_data = pages;
2951 
2952         ret = insert_vm_struct(mm, vma);
2953         if (ret)
2954                 goto out;
2955 
2956         mm->total_vm += len >> PAGE_SHIFT;
2957 
2958         perf_event_mmap(vma);
2959 
2960         return 0;
2961 
2962 out:
2963         kmem_cache_free(vm_area_cachep, vma);
2964         return ret;
2965 }
2966 
2967 static DEFINE_MUTEX(mm_all_locks_mutex);
2968 
2969 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
2970 {
2971         if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
2972                 /*
2973                  * The LSB of head.next can't change from under us
2974                  * because we hold the mm_all_locks_mutex.
2975                  */
2976                 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
2977                 /*
2978                  * We can safely modify head.next after taking the
2979                  * anon_vma->root->rwsem. If some other vma in this mm shares
2980                  * the same anon_vma we won't take it again.
2981                  *
2982                  * No need of atomic instructions here, head.next
2983                  * can't change from under us thanks to the
2984                  * anon_vma->root->rwsem.
2985                  */
2986                 if (__test_and_set_bit(0, (unsigned long *)
2987                                        &anon_vma->root->rb_root.rb_node))
2988                         BUG();
2989         }
2990 }
2991 
2992 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
2993 {
2994         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2995                 /*
2996                  * AS_MM_ALL_LOCKS can't change from under us because
2997                  * we hold the mm_all_locks_mutex.
2998                  *
2999                  * Operations on ->flags have to be atomic because
3000                  * even if AS_MM_ALL_LOCKS is stable thanks to the
3001                  * mm_all_locks_mutex, there may be other cpus
3002                  * changing other bitflags in parallel to us.
3003                  */
3004                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3005                         BUG();
3006                 mutex_lock_nest_lock(&mapping->i_mmap_mutex, &mm->mmap_sem);
3007         }
3008 }
3009 
3010 /*
3011  * This operation locks against the VM for all pte/vma/mm related
3012  * operations that could ever happen on a certain mm. This includes
3013  * vmtruncate, try_to_unmap, and all page faults.
3014  *
3015  * The caller must take the mmap_sem in write mode before calling
3016  * mm_take_all_locks(). The caller isn't allowed to release the
3017  * mmap_sem until mm_drop_all_locks() returns.
3018  *
3019  * mmap_sem in write mode is required in order to block all operations
3020  * that could modify pagetables and free pages without need of
3021  * altering the vma layout (for example populate_range() with
3022  * nonlinear vmas). It's also needed in write mode to avoid new
3023  * anon_vmas to be associated with existing vmas.
3024  *
3025  * A single task can't take more than one mm_take_all_locks() in a row
3026  * or it would deadlock.
3027  *
3028  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3029  * mapping->flags avoid to take the same lock twice, if more than one
3030  * vma in this mm is backed by the same anon_vma or address_space.
3031  *
3032  * We can take all the locks in random order because the VM code
3033  * taking i_mmap_mutex or anon_vma->rwsem outside the mmap_sem never
3034  * takes more than one of them in a row. Secondly we're protected
3035  * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
3036  *
3037  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3038  * that may have to take thousand of locks.
3039  *
3040  * mm_take_all_locks() can fail if it's interrupted by signals.
3041  */
3042 int mm_take_all_locks(struct mm_struct *mm)
3043 {
3044         struct vm_area_struct *vma;
3045         struct anon_vma_chain *avc;
3046 
3047         BUG_ON(down_read_trylock(&mm->mmap_sem));
3048 
3049         mutex_lock(&mm_all_locks_mutex);
3050 
3051         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3052                 if (signal_pending(current))
3053                         goto out_unlock;
3054                 if (vma->vm_file && vma->vm_file->f_mapping)
3055                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3056         }
3057 
3058         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3059                 if (signal_pending(current))
3060                         goto out_unlock;
3061                 if (vma->anon_vma)
3062                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3063                                 vm_lock_anon_vma(mm, avc->anon_vma);
3064         }
3065 
3066         return 0;
3067 
3068 out_unlock:
3069         mm_drop_all_locks(mm);
3070         return -EINTR;
3071 }
3072 
3073 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3074 {
3075         if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3076                 /*
3077                  * The LSB of head.next can't change to 0 from under
3078                  * us because we hold the mm_all_locks_mutex.
3079                  *
3080                  * We must however clear the bitflag before unlocking
3081                  * the vma so the users using the anon_vma->rb_root will
3082                  * never see our bitflag.
3083                  *
3084                  * No need of atomic instructions here, head.next
3085                  * can't change from under us until we release the
3086                  * anon_vma->root->rwsem.
3087                  */
3088                 if (!__test_and_clear_bit(0, (unsigned long *)
3089                                           &anon_vma->root->rb_root.rb_node))
3090                         BUG();
3091                 anon_vma_unlock_write(anon_vma);
3092         }
3093 }
3094 
3095 static void vm_unlock_mapping(struct address_space *mapping)
3096 {
3097         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3098                 /*
3099                  * AS_MM_ALL_LOCKS can't change to 0 from under us
3100                  * because we hold the mm_all_locks_mutex.
3101                  */
3102                 mutex_unlock(&mapping->i_mmap_mutex);
3103                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3104                                         &mapping->flags))
3105                         BUG();
3106         }
3107 }
3108 
3109 /*
3110  * The mmap_sem cannot be released by the caller until
3111  * mm_drop_all_locks() returns.
3112  */
3113 void mm_drop_all_locks(struct mm_struct *mm)
3114 {
3115         struct vm_area_struct *vma;
3116         struct anon_vma_chain *avc;
3117 
3118         BUG_ON(down_read_trylock(&mm->mmap_sem));
3119         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3120 
3121         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3122                 if (vma->anon_vma)
3123                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3124                                 vm_unlock_anon_vma(avc->anon_vma);
3125                 if (vma->vm_file && vma->vm_file->f_mapping)
3126                         vm_unlock_mapping(vma->vm_file->f_mapping);
3127         }
3128 
3129         mutex_unlock(&mm_all_locks_mutex);
3130 }
3131 
3132 /*
3133  * initialise the VMA slab
3134  */
3135 void __init mmap_init(void)
3136 {
3137         int ret;
3138 
3139         ret = percpu_counter_init(&vm_committed_as, 0);
3140         VM_BUG_ON(ret);
3141 }
3142 
3143 /*
3144  * Initialise sysctl_user_reserve_kbytes.
3145  *
3146  * This is intended to prevent a user from starting a single memory hogging
3147  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3148  * mode.
3149  *
3150  * The default value is min(3% of free memory, 128MB)
3151  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3152  */
3153 static int init_user_reserve(void)
3154 {
3155         unsigned long free_kbytes;
3156 
3157         free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3158 
3159         sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3160         return 0;
3161 }
3162 module_init(init_user_reserve)
3163 
3164 /*
3165  * Initialise sysctl_admin_reserve_kbytes.
3166  *
3167  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3168  * to log in and kill a memory hogging process.
3169  *
3170  * Systems with more than 256MB will reserve 8MB, enough to recover
3171  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3172  * only reserve 3% of free pages by default.
3173  */
3174 static int init_admin_reserve(void)
3175 {
3176         unsigned long free_kbytes;
3177 
3178         free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3179 
3180         sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3181         return 0;
3182 }
3183 module_init(init_admin_reserve)
3184 
3185 /*
3186  * Reinititalise user and admin reserves if memory is added or removed.
3187  *
3188  * The default user reserve max is 128MB, and the default max for the
3189  * admin reserve is 8MB. These are usually, but not always, enough to
3190  * enable recovery from a memory hogging process using login/sshd, a shell,
3191  * and tools like top. It may make sense to increase or even disable the
3192  * reserve depending on the existence of swap or variations in the recovery
3193  * tools. So, the admin may have changed them.
3194  *
3195  * If memory is added and the reserves have been eliminated or increased above
3196  * the default max, then we'll trust the admin.
3197  *
3198  * If memory is removed and there isn't enough free memory, then we
3199  * need to reset the reserves.
3200  *
3201  * Otherwise keep the reserve set by the admin.
3202  */
3203 static int reserve_mem_notifier(struct notifier_block *nb,
3204                              unsigned long action, void *data)
3205 {
3206         unsigned long tmp, free_kbytes;
3207 
3208         switch (action) {
3209         case MEM_ONLINE:
3210                 /* Default max is 128MB. Leave alone if modified by operator. */
3211                 tmp = sysctl_user_reserve_kbytes;
3212                 if (0 < tmp && tmp < (1UL << 17))
3213                         init_user_reserve();
3214 
3215                 /* Default max is 8MB.  Leave alone if modified by operator. */
3216                 tmp = sysctl_admin_reserve_kbytes;
3217                 if (0 < tmp && tmp < (1UL << 13))
3218                         init_admin_reserve();
3219 
3220                 break;
3221         case MEM_OFFLINE:
3222                 free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3223 
3224                 if (sysctl_user_reserve_kbytes > free_kbytes) {
3225                         init_user_reserve();
3226                         pr_info("vm.user_reserve_kbytes reset to %lu\n",
3227                                 sysctl_user_reserve_kbytes);
3228                 }
3229 
3230                 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3231                         init_admin_reserve();
3232                         pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3233                                 sysctl_admin_reserve_kbytes);
3234                 }
3235                 break;
3236         default:
3237                 break;
3238         }
3239         return NOTIFY_OK;
3240 }
3241 
3242 static struct notifier_block reserve_mem_nb = {
3243         .notifier_call = reserve_mem_notifier,
3244 };
3245 
3246 static int __meminit init_reserve_notifier(void)
3247 {
3248         if (register_hotmemory_notifier(&reserve_mem_nb))
3249                 printk("Failed registering memory add/remove notifier for admin reserve");
3250 
3251         return 0;
3252 }
3253 module_init(init_reserve_notifier)
3254 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp