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

TOMOYO Linux Cross Reference
Linux/mm/mmap.c

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

~ [ 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