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