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