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