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