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