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