xref: /linux/mm/mmap.c (revision 4d047d4f8ab4bbbd0b017fb287fcdad083e081ea)
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 #include <linux/ksm.h>
50 #include <linux/memfd.h>
51 
52 #include <linux/uaccess.h>
53 #include <asm/cacheflush.h>
54 #include <asm/tlb.h>
55 #include <asm/mmu_context.h>
56 
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/mmap.h>
59 
60 #include "internal.h"
61 
62 #ifndef arch_mmap_check
63 #define arch_mmap_check(addr, len, flags)	(0)
64 #endif
65 
66 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
67 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
68 int mmap_rnd_bits_max __ro_after_init = CONFIG_ARCH_MMAP_RND_BITS_MAX;
69 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
70 #endif
71 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
72 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
73 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
74 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
75 #endif
76 
77 static bool ignore_rlimit_data;
78 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
79 
80 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
81 void vma_set_page_prot(struct vm_area_struct *vma)
82 {
83 	unsigned long vm_flags = vma->vm_flags;
84 	pgprot_t vm_page_prot;
85 
86 	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
87 	if (vma_wants_writenotify(vma, vm_page_prot)) {
88 		vm_flags &= ~VM_SHARED;
89 		vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
90 	}
91 	/* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
92 	WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
93 }
94 
95 /*
96  * check_brk_limits() - Use platform specific check of range & verify mlock
97  * limits.
98  * @addr: The address to check
99  * @len: The size of increase.
100  *
101  * Return: 0 on success.
102  */
103 static int check_brk_limits(unsigned long addr, unsigned long len)
104 {
105 	unsigned long mapped_addr;
106 
107 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
108 	if (IS_ERR_VALUE(mapped_addr))
109 		return mapped_addr;
110 
111 	return mlock_future_ok(current->mm, current->mm->def_flags, len)
112 		? 0 : -EAGAIN;
113 }
114 
115 SYSCALL_DEFINE1(brk, unsigned long, brk)
116 {
117 	unsigned long newbrk, oldbrk, origbrk;
118 	struct mm_struct *mm = current->mm;
119 	struct vm_area_struct *brkvma, *next = NULL;
120 	unsigned long min_brk;
121 	bool populate = false;
122 	LIST_HEAD(uf);
123 	struct vma_iterator vmi;
124 
125 	if (mmap_write_lock_killable(mm))
126 		return -EINTR;
127 
128 	origbrk = mm->brk;
129 
130 #ifdef CONFIG_COMPAT_BRK
131 	/*
132 	 * CONFIG_COMPAT_BRK can still be overridden by setting
133 	 * randomize_va_space to 2, which will still cause mm->start_brk
134 	 * to be arbitrarily shifted
135 	 */
136 	if (current->brk_randomized)
137 		min_brk = mm->start_brk;
138 	else
139 		min_brk = mm->end_data;
140 #else
141 	min_brk = mm->start_brk;
142 #endif
143 	if (brk < min_brk)
144 		goto out;
145 
146 	/*
147 	 * Check against rlimit here. If this check is done later after the test
148 	 * of oldbrk with newbrk then it can escape the test and let the data
149 	 * segment grow beyond its set limit the in case where the limit is
150 	 * not page aligned -Ram Gupta
151 	 */
152 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
153 			      mm->end_data, mm->start_data))
154 		goto out;
155 
156 	newbrk = PAGE_ALIGN(brk);
157 	oldbrk = PAGE_ALIGN(mm->brk);
158 	if (oldbrk == newbrk) {
159 		mm->brk = brk;
160 		goto success;
161 	}
162 
163 	/* Always allow shrinking brk. */
164 	if (brk <= mm->brk) {
165 		/* Search one past newbrk */
166 		vma_iter_init(&vmi, mm, newbrk);
167 		brkvma = vma_find(&vmi, oldbrk);
168 		if (!brkvma || brkvma->vm_start >= oldbrk)
169 			goto out; /* mapping intersects with an existing non-brk vma. */
170 		/*
171 		 * mm->brk must be protected by write mmap_lock.
172 		 * do_vmi_align_munmap() will drop the lock on success,  so
173 		 * update it before calling do_vma_munmap().
174 		 */
175 		mm->brk = brk;
176 		if (do_vmi_align_munmap(&vmi, brkvma, mm, newbrk, oldbrk, &uf,
177 					/* unlock = */ true))
178 			goto out;
179 
180 		goto success_unlocked;
181 	}
182 
183 	if (check_brk_limits(oldbrk, newbrk - oldbrk))
184 		goto out;
185 
186 	/*
187 	 * Only check if the next VMA is within the stack_guard_gap of the
188 	 * expansion area
189 	 */
190 	vma_iter_init(&vmi, mm, oldbrk);
191 	next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
192 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
193 		goto out;
194 
195 	brkvma = vma_prev_limit(&vmi, mm->start_brk);
196 	/* Ok, looks good - let it rip. */
197 	if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
198 		goto out;
199 
200 	mm->brk = brk;
201 	if (mm->def_flags & VM_LOCKED)
202 		populate = true;
203 
204 success:
205 	mmap_write_unlock(mm);
206 success_unlocked:
207 	userfaultfd_unmap_complete(mm, &uf);
208 	if (populate)
209 		mm_populate(oldbrk, newbrk - oldbrk);
210 	return brk;
211 
212 out:
213 	mm->brk = origbrk;
214 	mmap_write_unlock(mm);
215 	return origbrk;
216 }
217 
218 /*
219  * If a hint addr is less than mmap_min_addr change hint to be as
220  * low as possible but still greater than mmap_min_addr
221  */
222 static inline unsigned long round_hint_to_min(unsigned long hint)
223 {
224 	hint &= PAGE_MASK;
225 	if (((void *)hint != NULL) &&
226 	    (hint < mmap_min_addr))
227 		return PAGE_ALIGN(mmap_min_addr);
228 	return hint;
229 }
230 
231 bool mlock_future_ok(struct mm_struct *mm, unsigned long flags,
232 			unsigned long bytes)
233 {
234 	unsigned long locked_pages, limit_pages;
235 
236 	if (!(flags & VM_LOCKED) || capable(CAP_IPC_LOCK))
237 		return true;
238 
239 	locked_pages = bytes >> PAGE_SHIFT;
240 	locked_pages += mm->locked_vm;
241 
242 	limit_pages = rlimit(RLIMIT_MEMLOCK);
243 	limit_pages >>= PAGE_SHIFT;
244 
245 	return locked_pages <= limit_pages;
246 }
247 
248 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
249 {
250 	if (S_ISREG(inode->i_mode))
251 		return MAX_LFS_FILESIZE;
252 
253 	if (S_ISBLK(inode->i_mode))
254 		return MAX_LFS_FILESIZE;
255 
256 	if (S_ISSOCK(inode->i_mode))
257 		return MAX_LFS_FILESIZE;
258 
259 	/* Special "we do even unsigned file positions" case */
260 	if (file->f_op->fop_flags & FOP_UNSIGNED_OFFSET)
261 		return 0;
262 
263 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
264 	return ULONG_MAX;
265 }
266 
267 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
268 				unsigned long pgoff, unsigned long len)
269 {
270 	u64 maxsize = file_mmap_size_max(file, inode);
271 
272 	if (maxsize && len > maxsize)
273 		return false;
274 	maxsize -= len;
275 	if (pgoff > maxsize >> PAGE_SHIFT)
276 		return false;
277 	return true;
278 }
279 
280 /**
281  * do_mmap() - Perform a userland memory mapping into the current process
282  * address space of length @len with protection bits @prot, mmap flags @flags
283  * (from which VMA flags will be inferred), and any additional VMA flags to
284  * apply @vm_flags. If this is a file-backed mapping then the file is specified
285  * in @file and page offset into the file via @pgoff.
286  *
287  * This function does not perform security checks on the file and assumes, if
288  * @uf is non-NULL, the caller has provided a list head to track unmap events
289  * for userfaultfd @uf.
290  *
291  * It also simply indicates whether memory population is required by setting
292  * @populate, which must be non-NULL, expecting the caller to actually perform
293  * this task itself if appropriate.
294  *
295  * This function will invoke architecture-specific (and if provided and
296  * relevant, file system-specific) logic to determine the most appropriate
297  * unmapped area in which to place the mapping if not MAP_FIXED.
298  *
299  * Callers which require userland mmap() behaviour should invoke vm_mmap(),
300  * which is also exported for module use.
301  *
302  * Those which require this behaviour less security checks, userfaultfd and
303  * populate behaviour, and who handle the mmap write lock themselves, should
304  * call this function.
305  *
306  * Note that the returned address may reside within a merged VMA if an
307  * appropriate merge were to take place, so it doesn't necessarily specify the
308  * start of a VMA, rather only the start of a valid mapped range of length
309  * @len bytes, rounded down to the nearest page size.
310  *
311  * The caller must write-lock current->mm->mmap_lock.
312  *
313  * @file: An optional struct file pointer describing the file which is to be
314  * mapped, if a file-backed mapping.
315  * @addr: If non-zero, hints at (or if @flags has MAP_FIXED set, specifies) the
316  * address at which to perform this mapping. See mmap (2) for details. Must be
317  * page-aligned.
318  * @len: The length of the mapping. Will be page-aligned and must be at least 1
319  * page in size.
320  * @prot: Protection bits describing access required to the mapping. See mmap
321  * (2) for details.
322  * @flags: Flags specifying how the mapping should be performed, see mmap (2)
323  * for details.
324  * @vm_flags: VMA flags which should be set by default, or 0 otherwise.
325  * @pgoff: Page offset into the @file if file-backed, should be 0 otherwise.
326  * @populate: A pointer to a value which will be set to 0 if no population of
327  * the range is required, or the number of bytes to populate if it is. Must be
328  * non-NULL. See mmap (2) for details as to under what circumstances population
329  * of the range occurs.
330  * @uf: An optional pointer to a list head to track userfaultfd unmap events
331  * should unmapping events arise. If provided, it is up to the caller to manage
332  * this.
333  *
334  * Returns: Either an error, or the address at which the requested mapping has
335  * been performed.
336  */
337 unsigned long do_mmap(struct file *file, unsigned long addr,
338 			unsigned long len, unsigned long prot,
339 			unsigned long flags, vm_flags_t vm_flags,
340 			unsigned long pgoff, unsigned long *populate,
341 			struct list_head *uf)
342 {
343 	struct mm_struct *mm = current->mm;
344 	int pkey = 0;
345 
346 	*populate = 0;
347 
348 	mmap_assert_write_locked(mm);
349 
350 	if (!len)
351 		return -EINVAL;
352 
353 	/*
354 	 * Does the application expect PROT_READ to imply PROT_EXEC?
355 	 *
356 	 * (the exception is when the underlying filesystem is noexec
357 	 *  mounted, in which case we don't add PROT_EXEC.)
358 	 */
359 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
360 		if (!(file && path_noexec(&file->f_path)))
361 			prot |= PROT_EXEC;
362 
363 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
364 	if (flags & MAP_FIXED_NOREPLACE)
365 		flags |= MAP_FIXED;
366 
367 	if (!(flags & MAP_FIXED))
368 		addr = round_hint_to_min(addr);
369 
370 	/* Careful about overflows.. */
371 	len = PAGE_ALIGN(len);
372 	if (!len)
373 		return -ENOMEM;
374 
375 	/* offset overflow? */
376 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
377 		return -EOVERFLOW;
378 
379 	/* Too many mappings? */
380 	if (mm->map_count > sysctl_max_map_count)
381 		return -ENOMEM;
382 
383 	/*
384 	 * addr is returned from get_unmapped_area,
385 	 * There are two cases:
386 	 * 1> MAP_FIXED == false
387 	 *	unallocated memory, no need to check sealing.
388 	 * 1> MAP_FIXED == true
389 	 *	sealing is checked inside mmap_region when
390 	 *	do_vmi_munmap is called.
391 	 */
392 
393 	if (prot == PROT_EXEC) {
394 		pkey = execute_only_pkey(mm);
395 		if (pkey < 0)
396 			pkey = 0;
397 	}
398 
399 	/* Do simple checking here so the lower-level routines won't have
400 	 * to. we assume access permissions have been handled by the open
401 	 * of the memory object, so we don't do any here.
402 	 */
403 	vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(file, flags) |
404 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
405 
406 	/* Obtain the address to map to. we verify (or select) it and ensure
407 	 * that it represents a valid section of the address space.
408 	 */
409 	addr = __get_unmapped_area(file, addr, len, pgoff, flags, vm_flags);
410 	if (IS_ERR_VALUE(addr))
411 		return addr;
412 
413 	if (flags & MAP_FIXED_NOREPLACE) {
414 		if (find_vma_intersection(mm, addr, addr + len))
415 			return -EEXIST;
416 	}
417 
418 	if (flags & MAP_LOCKED)
419 		if (!can_do_mlock())
420 			return -EPERM;
421 
422 	if (!mlock_future_ok(mm, vm_flags, len))
423 		return -EAGAIN;
424 
425 	if (file) {
426 		struct inode *inode = file_inode(file);
427 		unsigned long flags_mask;
428 		int err;
429 
430 		if (!file_mmap_ok(file, inode, pgoff, len))
431 			return -EOVERFLOW;
432 
433 		flags_mask = LEGACY_MAP_MASK;
434 		if (file->f_op->fop_flags & FOP_MMAP_SYNC)
435 			flags_mask |= MAP_SYNC;
436 
437 		switch (flags & MAP_TYPE) {
438 		case MAP_SHARED:
439 			/*
440 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
441 			 * flags. E.g. MAP_SYNC is dangerous to use with
442 			 * MAP_SHARED as you don't know which consistency model
443 			 * you will get. We silently ignore unsupported flags
444 			 * with MAP_SHARED to preserve backward compatibility.
445 			 */
446 			flags &= LEGACY_MAP_MASK;
447 			fallthrough;
448 		case MAP_SHARED_VALIDATE:
449 			if (flags & ~flags_mask)
450 				return -EOPNOTSUPP;
451 			if (prot & PROT_WRITE) {
452 				if (!(file->f_mode & FMODE_WRITE))
453 					return -EACCES;
454 				if (IS_SWAPFILE(file->f_mapping->host))
455 					return -ETXTBSY;
456 			}
457 
458 			/*
459 			 * Make sure we don't allow writing to an append-only
460 			 * file..
461 			 */
462 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
463 				return -EACCES;
464 
465 			vm_flags |= VM_SHARED | VM_MAYSHARE;
466 			if (!(file->f_mode & FMODE_WRITE))
467 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
468 			fallthrough;
469 		case MAP_PRIVATE:
470 			if (!(file->f_mode & FMODE_READ))
471 				return -EACCES;
472 			if (path_noexec(&file->f_path)) {
473 				if (vm_flags & VM_EXEC)
474 					return -EPERM;
475 				vm_flags &= ~VM_MAYEXEC;
476 			}
477 
478 			if (!file->f_op->mmap)
479 				return -ENODEV;
480 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
481 				return -EINVAL;
482 			break;
483 
484 		default:
485 			return -EINVAL;
486 		}
487 
488 		/*
489 		 * Check to see if we are violating any seals and update VMA
490 		 * flags if necessary to avoid future seal violations.
491 		 */
492 		err = memfd_check_seals_mmap(file, &vm_flags);
493 		if (err)
494 			return (unsigned long)err;
495 	} else {
496 		switch (flags & MAP_TYPE) {
497 		case MAP_SHARED:
498 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
499 				return -EINVAL;
500 			/*
501 			 * Ignore pgoff.
502 			 */
503 			pgoff = 0;
504 			vm_flags |= VM_SHARED | VM_MAYSHARE;
505 			break;
506 		case MAP_DROPPABLE:
507 			if (VM_DROPPABLE == VM_NONE)
508 				return -ENOTSUPP;
509 			/*
510 			 * A locked or stack area makes no sense to be droppable.
511 			 *
512 			 * Also, since droppable pages can just go away at any time
513 			 * it makes no sense to copy them on fork or dump them.
514 			 *
515 			 * And don't attempt to combine with hugetlb for now.
516 			 */
517 			if (flags & (MAP_LOCKED | MAP_HUGETLB))
518 			        return -EINVAL;
519 			if (vm_flags & (VM_GROWSDOWN | VM_GROWSUP))
520 			        return -EINVAL;
521 
522 			vm_flags |= VM_DROPPABLE;
523 
524 			/*
525 			 * If the pages can be dropped, then it doesn't make
526 			 * sense to reserve them.
527 			 */
528 			vm_flags |= VM_NORESERVE;
529 
530 			/*
531 			 * Likewise, they're volatile enough that they
532 			 * shouldn't survive forks or coredumps.
533 			 */
534 			vm_flags |= VM_WIPEONFORK | VM_DONTDUMP;
535 			fallthrough;
536 		case MAP_PRIVATE:
537 			/*
538 			 * Set pgoff according to addr for anon_vma.
539 			 */
540 			pgoff = addr >> PAGE_SHIFT;
541 			break;
542 		default:
543 			return -EINVAL;
544 		}
545 	}
546 
547 	/*
548 	 * Set 'VM_NORESERVE' if we should not account for the
549 	 * memory use of this mapping.
550 	 */
551 	if (flags & MAP_NORESERVE) {
552 		/* We honor MAP_NORESERVE if allowed to overcommit */
553 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
554 			vm_flags |= VM_NORESERVE;
555 
556 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
557 		if (file && is_file_hugepages(file))
558 			vm_flags |= VM_NORESERVE;
559 	}
560 
561 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
562 	if (!IS_ERR_VALUE(addr) &&
563 	    ((vm_flags & VM_LOCKED) ||
564 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
565 		*populate = len;
566 	return addr;
567 }
568 
569 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
570 			      unsigned long prot, unsigned long flags,
571 			      unsigned long fd, unsigned long pgoff)
572 {
573 	struct file *file = NULL;
574 	unsigned long retval;
575 
576 	if (!(flags & MAP_ANONYMOUS)) {
577 		audit_mmap_fd(fd, flags);
578 		file = fget(fd);
579 		if (!file)
580 			return -EBADF;
581 		if (is_file_hugepages(file)) {
582 			len = ALIGN(len, huge_page_size(hstate_file(file)));
583 		} else if (unlikely(flags & MAP_HUGETLB)) {
584 			retval = -EINVAL;
585 			goto out_fput;
586 		}
587 	} else if (flags & MAP_HUGETLB) {
588 		struct hstate *hs;
589 
590 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
591 		if (!hs)
592 			return -EINVAL;
593 
594 		len = ALIGN(len, huge_page_size(hs));
595 		/*
596 		 * VM_NORESERVE is used because the reservations will be
597 		 * taken when vm_ops->mmap() is called
598 		 */
599 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
600 				VM_NORESERVE,
601 				HUGETLB_ANONHUGE_INODE,
602 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
603 		if (IS_ERR(file))
604 			return PTR_ERR(file);
605 	}
606 
607 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
608 out_fput:
609 	if (file)
610 		fput(file);
611 	return retval;
612 }
613 
614 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
615 		unsigned long, prot, unsigned long, flags,
616 		unsigned long, fd, unsigned long, pgoff)
617 {
618 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
619 }
620 
621 #ifdef __ARCH_WANT_SYS_OLD_MMAP
622 struct mmap_arg_struct {
623 	unsigned long addr;
624 	unsigned long len;
625 	unsigned long prot;
626 	unsigned long flags;
627 	unsigned long fd;
628 	unsigned long offset;
629 };
630 
631 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
632 {
633 	struct mmap_arg_struct a;
634 
635 	if (copy_from_user(&a, arg, sizeof(a)))
636 		return -EFAULT;
637 	if (offset_in_page(a.offset))
638 		return -EINVAL;
639 
640 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
641 			       a.offset >> PAGE_SHIFT);
642 }
643 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
644 
645 /*
646  * Determine if the allocation needs to ensure that there is no
647  * existing mapping within it's guard gaps, for use as start_gap.
648  */
649 static inline unsigned long stack_guard_placement(vm_flags_t vm_flags)
650 {
651 	if (vm_flags & VM_SHADOW_STACK)
652 		return PAGE_SIZE;
653 
654 	return 0;
655 }
656 
657 /*
658  * Search for an unmapped address range.
659  *
660  * We are looking for a range that:
661  * - does not intersect with any VMA;
662  * - is contained within the [low_limit, high_limit) interval;
663  * - is at least the desired size.
664  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
665  */
666 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
667 {
668 	unsigned long addr;
669 
670 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
671 		addr = unmapped_area_topdown(info);
672 	else
673 		addr = unmapped_area(info);
674 
675 	trace_vm_unmapped_area(addr, info);
676 	return addr;
677 }
678 
679 /* Get an address range which is currently unmapped.
680  * For shmat() with addr=0.
681  *
682  * Ugly calling convention alert:
683  * Return value with the low bits set means error value,
684  * ie
685  *	if (ret & ~PAGE_MASK)
686  *		error = ret;
687  *
688  * This function "knows" that -ENOMEM has the bits set.
689  */
690 unsigned long
691 generic_get_unmapped_area(struct file *filp, unsigned long addr,
692 			  unsigned long len, unsigned long pgoff,
693 			  unsigned long flags, vm_flags_t vm_flags)
694 {
695 	struct mm_struct *mm = current->mm;
696 	struct vm_area_struct *vma, *prev;
697 	struct vm_unmapped_area_info info = {};
698 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
699 
700 	if (len > mmap_end - mmap_min_addr)
701 		return -ENOMEM;
702 
703 	if (flags & MAP_FIXED)
704 		return addr;
705 
706 	if (addr) {
707 		addr = PAGE_ALIGN(addr);
708 		vma = find_vma_prev(mm, addr, &prev);
709 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
710 		    (!vma || addr + len <= vm_start_gap(vma)) &&
711 		    (!prev || addr >= vm_end_gap(prev)))
712 			return addr;
713 	}
714 
715 	info.length = len;
716 	info.low_limit = mm->mmap_base;
717 	info.high_limit = mmap_end;
718 	info.start_gap = stack_guard_placement(vm_flags);
719 	if (filp && is_file_hugepages(filp))
720 		info.align_mask = huge_page_mask_align(filp);
721 	return vm_unmapped_area(&info);
722 }
723 
724 #ifndef HAVE_ARCH_UNMAPPED_AREA
725 unsigned long
726 arch_get_unmapped_area(struct file *filp, unsigned long addr,
727 		       unsigned long len, unsigned long pgoff,
728 		       unsigned long flags, vm_flags_t vm_flags)
729 {
730 	return generic_get_unmapped_area(filp, addr, len, pgoff, flags,
731 					 vm_flags);
732 }
733 #endif
734 
735 /*
736  * This mmap-allocator allocates new areas top-down from below the
737  * stack's low limit (the base):
738  */
739 unsigned long
740 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
741 				  unsigned long len, unsigned long pgoff,
742 				  unsigned long flags, vm_flags_t vm_flags)
743 {
744 	struct vm_area_struct *vma, *prev;
745 	struct mm_struct *mm = current->mm;
746 	struct vm_unmapped_area_info info = {};
747 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
748 
749 	/* requested length too big for entire address space */
750 	if (len > mmap_end - mmap_min_addr)
751 		return -ENOMEM;
752 
753 	if (flags & MAP_FIXED)
754 		return addr;
755 
756 	/* requesting a specific address */
757 	if (addr) {
758 		addr = PAGE_ALIGN(addr);
759 		vma = find_vma_prev(mm, addr, &prev);
760 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
761 				(!vma || addr + len <= vm_start_gap(vma)) &&
762 				(!prev || addr >= vm_end_gap(prev)))
763 			return addr;
764 	}
765 
766 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
767 	info.length = len;
768 	info.low_limit = PAGE_SIZE;
769 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
770 	info.start_gap = stack_guard_placement(vm_flags);
771 	if (filp && is_file_hugepages(filp))
772 		info.align_mask = huge_page_mask_align(filp);
773 	addr = vm_unmapped_area(&info);
774 
775 	/*
776 	 * A failed mmap() very likely causes application failure,
777 	 * so fall back to the bottom-up function here. This scenario
778 	 * can happen with large stack limits and large mmap()
779 	 * allocations.
780 	 */
781 	if (offset_in_page(addr)) {
782 		VM_BUG_ON(addr != -ENOMEM);
783 		info.flags = 0;
784 		info.low_limit = TASK_UNMAPPED_BASE;
785 		info.high_limit = mmap_end;
786 		addr = vm_unmapped_area(&info);
787 	}
788 
789 	return addr;
790 }
791 
792 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
793 unsigned long
794 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
795 			       unsigned long len, unsigned long pgoff,
796 			       unsigned long flags, vm_flags_t vm_flags)
797 {
798 	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags,
799 						 vm_flags);
800 }
801 #endif
802 
803 unsigned long mm_get_unmapped_area_vmflags(struct mm_struct *mm, struct file *filp,
804 					   unsigned long addr, unsigned long len,
805 					   unsigned long pgoff, unsigned long flags,
806 					   vm_flags_t vm_flags)
807 {
808 	if (test_bit(MMF_TOPDOWN, &mm->flags))
809 		return arch_get_unmapped_area_topdown(filp, addr, len, pgoff,
810 						      flags, vm_flags);
811 	return arch_get_unmapped_area(filp, addr, len, pgoff, flags, vm_flags);
812 }
813 
814 unsigned long
815 __get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
816 		unsigned long pgoff, unsigned long flags, vm_flags_t vm_flags)
817 {
818 	unsigned long (*get_area)(struct file *, unsigned long,
819 				  unsigned long, unsigned long, unsigned long)
820 				  = NULL;
821 
822 	unsigned long error = arch_mmap_check(addr, len, flags);
823 	if (error)
824 		return error;
825 
826 	/* Careful about overflows.. */
827 	if (len > TASK_SIZE)
828 		return -ENOMEM;
829 
830 	if (file) {
831 		if (file->f_op->get_unmapped_area)
832 			get_area = file->f_op->get_unmapped_area;
833 	} else if (flags & MAP_SHARED) {
834 		/*
835 		 * mmap_region() will call shmem_zero_setup() to create a file,
836 		 * so use shmem's get_unmapped_area in case it can be huge.
837 		 */
838 		get_area = shmem_get_unmapped_area;
839 	}
840 
841 	/* Always treat pgoff as zero for anonymous memory. */
842 	if (!file)
843 		pgoff = 0;
844 
845 	if (get_area) {
846 		addr = get_area(file, addr, len, pgoff, flags);
847 	} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && !file
848 		   && !addr /* no hint */
849 		   && IS_ALIGNED(len, PMD_SIZE)) {
850 		/* Ensures that larger anonymous mappings are THP aligned. */
851 		addr = thp_get_unmapped_area_vmflags(file, addr, len,
852 						     pgoff, flags, vm_flags);
853 	} else {
854 		addr = mm_get_unmapped_area_vmflags(current->mm, file, addr, len,
855 						    pgoff, flags, vm_flags);
856 	}
857 	if (IS_ERR_VALUE(addr))
858 		return addr;
859 
860 	if (addr > TASK_SIZE - len)
861 		return -ENOMEM;
862 	if (offset_in_page(addr))
863 		return -EINVAL;
864 
865 	error = security_mmap_addr(addr);
866 	return error ? error : addr;
867 }
868 
869 unsigned long
870 mm_get_unmapped_area(struct mm_struct *mm, struct file *file,
871 		     unsigned long addr, unsigned long len,
872 		     unsigned long pgoff, unsigned long flags)
873 {
874 	if (test_bit(MMF_TOPDOWN, &mm->flags))
875 		return arch_get_unmapped_area_topdown(file, addr, len, pgoff, flags, 0);
876 	return arch_get_unmapped_area(file, addr, len, pgoff, flags, 0);
877 }
878 EXPORT_SYMBOL(mm_get_unmapped_area);
879 
880 /**
881  * find_vma_intersection() - Look up the first VMA which intersects the interval
882  * @mm: The process address space.
883  * @start_addr: The inclusive start user address.
884  * @end_addr: The exclusive end user address.
885  *
886  * Returns: The first VMA within the provided range, %NULL otherwise.  Assumes
887  * start_addr < end_addr.
888  */
889 struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
890 					     unsigned long start_addr,
891 					     unsigned long end_addr)
892 {
893 	unsigned long index = start_addr;
894 
895 	mmap_assert_locked(mm);
896 	return mt_find(&mm->mm_mt, &index, end_addr - 1);
897 }
898 EXPORT_SYMBOL(find_vma_intersection);
899 
900 /**
901  * find_vma() - Find the VMA for a given address, or the next VMA.
902  * @mm: The mm_struct to check
903  * @addr: The address
904  *
905  * Returns: The VMA associated with addr, or the next VMA.
906  * May return %NULL in the case of no VMA at addr or above.
907  */
908 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
909 {
910 	unsigned long index = addr;
911 
912 	mmap_assert_locked(mm);
913 	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
914 }
915 EXPORT_SYMBOL(find_vma);
916 
917 /**
918  * find_vma_prev() - Find the VMA for a given address, or the next vma and
919  * set %pprev to the previous VMA, if any.
920  * @mm: The mm_struct to check
921  * @addr: The address
922  * @pprev: The pointer to set to the previous VMA
923  *
924  * Note that RCU lock is missing here since the external mmap_lock() is used
925  * instead.
926  *
927  * Returns: The VMA associated with @addr, or the next vma.
928  * May return %NULL in the case of no vma at addr or above.
929  */
930 struct vm_area_struct *
931 find_vma_prev(struct mm_struct *mm, unsigned long addr,
932 			struct vm_area_struct **pprev)
933 {
934 	struct vm_area_struct *vma;
935 	VMA_ITERATOR(vmi, mm, addr);
936 
937 	vma = vma_iter_load(&vmi);
938 	*pprev = vma_prev(&vmi);
939 	if (!vma)
940 		vma = vma_next(&vmi);
941 	return vma;
942 }
943 
944 /* enforced gap between the expanding stack and other mappings. */
945 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
946 
947 static int __init cmdline_parse_stack_guard_gap(char *p)
948 {
949 	unsigned long val;
950 	char *endptr;
951 
952 	val = simple_strtoul(p, &endptr, 10);
953 	if (!*endptr)
954 		stack_guard_gap = val << PAGE_SHIFT;
955 
956 	return 1;
957 }
958 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
959 
960 #ifdef CONFIG_STACK_GROWSUP
961 int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
962 {
963 	return expand_upwards(vma, address);
964 }
965 
966 struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
967 {
968 	struct vm_area_struct *vma, *prev;
969 
970 	addr &= PAGE_MASK;
971 	vma = find_vma_prev(mm, addr, &prev);
972 	if (vma && (vma->vm_start <= addr))
973 		return vma;
974 	if (!prev)
975 		return NULL;
976 	if (expand_stack_locked(prev, addr))
977 		return NULL;
978 	if (prev->vm_flags & VM_LOCKED)
979 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
980 	return prev;
981 }
982 #else
983 int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
984 {
985 	return expand_downwards(vma, address);
986 }
987 
988 struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
989 {
990 	struct vm_area_struct *vma;
991 	unsigned long start;
992 
993 	addr &= PAGE_MASK;
994 	vma = find_vma(mm, addr);
995 	if (!vma)
996 		return NULL;
997 	if (vma->vm_start <= addr)
998 		return vma;
999 	start = vma->vm_start;
1000 	if (expand_stack_locked(vma, addr))
1001 		return NULL;
1002 	if (vma->vm_flags & VM_LOCKED)
1003 		populate_vma_page_range(vma, addr, start, NULL);
1004 	return vma;
1005 }
1006 #endif
1007 
1008 #if defined(CONFIG_STACK_GROWSUP)
1009 
1010 #define vma_expand_up(vma,addr) expand_upwards(vma, addr)
1011 #define vma_expand_down(vma, addr) (-EFAULT)
1012 
1013 #else
1014 
1015 #define vma_expand_up(vma,addr) (-EFAULT)
1016 #define vma_expand_down(vma, addr) expand_downwards(vma, addr)
1017 
1018 #endif
1019 
1020 /*
1021  * expand_stack(): legacy interface for page faulting. Don't use unless
1022  * you have to.
1023  *
1024  * This is called with the mm locked for reading, drops the lock, takes
1025  * the lock for writing, tries to look up a vma again, expands it if
1026  * necessary, and downgrades the lock to reading again.
1027  *
1028  * If no vma is found or it can't be expanded, it returns NULL and has
1029  * dropped the lock.
1030  */
1031 struct vm_area_struct *expand_stack(struct mm_struct *mm, unsigned long addr)
1032 {
1033 	struct vm_area_struct *vma, *prev;
1034 
1035 	mmap_read_unlock(mm);
1036 	if (mmap_write_lock_killable(mm))
1037 		return NULL;
1038 
1039 	vma = find_vma_prev(mm, addr, &prev);
1040 	if (vma && vma->vm_start <= addr)
1041 		goto success;
1042 
1043 	if (prev && !vma_expand_up(prev, addr)) {
1044 		vma = prev;
1045 		goto success;
1046 	}
1047 
1048 	if (vma && !vma_expand_down(vma, addr))
1049 		goto success;
1050 
1051 	mmap_write_unlock(mm);
1052 	return NULL;
1053 
1054 success:
1055 	mmap_write_downgrade(mm);
1056 	return vma;
1057 }
1058 
1059 /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
1060  * @mm: The mm_struct
1061  * @start: The start address to munmap
1062  * @len: The length to be munmapped.
1063  * @uf: The userfaultfd list_head
1064  *
1065  * Return: 0 on success, error otherwise.
1066  */
1067 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
1068 	      struct list_head *uf)
1069 {
1070 	VMA_ITERATOR(vmi, mm, start);
1071 
1072 	return do_vmi_munmap(&vmi, mm, start, len, uf, false);
1073 }
1074 
1075 /**
1076  * mmap_region() - Actually perform the userland mapping of a VMA into
1077  * current->mm with known, aligned and overflow-checked @addr and @len, and
1078  * correctly determined VMA flags @vm_flags and page offset @pgoff.
1079  *
1080  * This is an internal memory management function, and should not be used
1081  * directly.
1082  *
1083  * The caller must write-lock current->mm->mmap_lock.
1084  *
1085  * @file: If a file-backed mapping, a pointer to the struct file describing the
1086  * file to be mapped, otherwise NULL.
1087  * @addr: The page-aligned address at which to perform the mapping.
1088  * @len: The page-aligned, non-zero, length of the mapping.
1089  * @vm_flags: The VMA flags which should be applied to the mapping.
1090  * @pgoff: If @file is specified, the page offset into the file, if not then
1091  * the virtual page offset in memory of the anonymous mapping.
1092  * @uf: Optionally, a pointer to a list head used for tracking userfaultfd unmap
1093  * events.
1094  *
1095  * Returns: Either an error, or the address at which the requested mapping has
1096  * been performed.
1097  */
1098 unsigned long mmap_region(struct file *file, unsigned long addr,
1099 			  unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1100 			  struct list_head *uf)
1101 {
1102 	unsigned long ret;
1103 	bool writable_file_mapping = false;
1104 
1105 	mmap_assert_write_locked(current->mm);
1106 
1107 	/* Check to see if MDWE is applicable. */
1108 	if (map_deny_write_exec(vm_flags, vm_flags))
1109 		return -EACCES;
1110 
1111 	/* Allow architectures to sanity-check the vm_flags. */
1112 	if (!arch_validate_flags(vm_flags))
1113 		return -EINVAL;
1114 
1115 	/* Map writable and ensure this isn't a sealed memfd. */
1116 	if (file && is_shared_maywrite(vm_flags)) {
1117 		int error = mapping_map_writable(file->f_mapping);
1118 
1119 		if (error)
1120 			return error;
1121 		writable_file_mapping = true;
1122 	}
1123 
1124 	ret = __mmap_region(file, addr, len, vm_flags, pgoff, uf);
1125 
1126 	/* Clear our write mapping regardless of error. */
1127 	if (writable_file_mapping)
1128 		mapping_unmap_writable(file->f_mapping);
1129 
1130 	validate_mm(current->mm);
1131 	return ret;
1132 }
1133 
1134 int vm_munmap(unsigned long start, size_t len)
1135 {
1136 	return __vm_munmap(start, len, false);
1137 }
1138 EXPORT_SYMBOL(vm_munmap);
1139 
1140 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
1141 {
1142 	addr = untagged_addr(addr);
1143 	return __vm_munmap(addr, len, true);
1144 }
1145 
1146 
1147 /*
1148  * Emulation of deprecated remap_file_pages() syscall.
1149  */
1150 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
1151 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
1152 {
1153 
1154 	struct mm_struct *mm = current->mm;
1155 	struct vm_area_struct *vma;
1156 	unsigned long populate = 0;
1157 	unsigned long ret = -EINVAL;
1158 	struct file *file;
1159 	vm_flags_t vm_flags;
1160 
1161 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
1162 		     current->comm, current->pid);
1163 
1164 	if (prot)
1165 		return ret;
1166 	start = start & PAGE_MASK;
1167 	size = size & PAGE_MASK;
1168 
1169 	if (start + size <= start)
1170 		return ret;
1171 
1172 	/* Does pgoff wrap? */
1173 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
1174 		return ret;
1175 
1176 	if (mmap_read_lock_killable(mm))
1177 		return -EINTR;
1178 
1179 	/*
1180 	 * Look up VMA under read lock first so we can perform the security
1181 	 * without holding locks (which can be problematic). We reacquire a
1182 	 * write lock later and check nothing changed underneath us.
1183 	 */
1184 	vma = vma_lookup(mm, start);
1185 
1186 	if (!vma || !(vma->vm_flags & VM_SHARED)) {
1187 		mmap_read_unlock(mm);
1188 		return -EINVAL;
1189 	}
1190 
1191 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
1192 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
1193 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
1194 
1195 	flags &= MAP_NONBLOCK;
1196 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
1197 	if (vma->vm_flags & VM_LOCKED)
1198 		flags |= MAP_LOCKED;
1199 
1200 	/* Save vm_flags used to calculate prot and flags, and recheck later. */
1201 	vm_flags = vma->vm_flags;
1202 	file = get_file(vma->vm_file);
1203 
1204 	mmap_read_unlock(mm);
1205 
1206 	/* Call outside mmap_lock to be consistent with other callers. */
1207 	ret = security_mmap_file(file, prot, flags);
1208 	if (ret) {
1209 		fput(file);
1210 		return ret;
1211 	}
1212 
1213 	ret = -EINVAL;
1214 
1215 	/* OK security check passed, take write lock + let it rip. */
1216 	if (mmap_write_lock_killable(mm)) {
1217 		fput(file);
1218 		return -EINTR;
1219 	}
1220 
1221 	vma = vma_lookup(mm, start);
1222 
1223 	if (!vma)
1224 		goto out;
1225 
1226 	/* Make sure things didn't change under us. */
1227 	if (vma->vm_flags != vm_flags)
1228 		goto out;
1229 	if (vma->vm_file != file)
1230 		goto out;
1231 
1232 	if (start + size > vma->vm_end) {
1233 		VMA_ITERATOR(vmi, mm, vma->vm_end);
1234 		struct vm_area_struct *next, *prev = vma;
1235 
1236 		for_each_vma_range(vmi, next, start + size) {
1237 			/* hole between vmas ? */
1238 			if (next->vm_start != prev->vm_end)
1239 				goto out;
1240 
1241 			if (next->vm_file != vma->vm_file)
1242 				goto out;
1243 
1244 			if (next->vm_flags != vma->vm_flags)
1245 				goto out;
1246 
1247 			if (start + size <= next->vm_end)
1248 				break;
1249 
1250 			prev = next;
1251 		}
1252 
1253 		if (!next)
1254 			goto out;
1255 	}
1256 
1257 	ret = do_mmap(vma->vm_file, start, size,
1258 			prot, flags, 0, pgoff, &populate, NULL);
1259 out:
1260 	mmap_write_unlock(mm);
1261 	fput(file);
1262 	if (populate)
1263 		mm_populate(ret, populate);
1264 	if (!IS_ERR_VALUE(ret))
1265 		ret = 0;
1266 	return ret;
1267 }
1268 
1269 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
1270 {
1271 	struct mm_struct *mm = current->mm;
1272 	struct vm_area_struct *vma = NULL;
1273 	unsigned long len;
1274 	int ret;
1275 	bool populate;
1276 	LIST_HEAD(uf);
1277 	VMA_ITERATOR(vmi, mm, addr);
1278 
1279 	len = PAGE_ALIGN(request);
1280 	if (len < request)
1281 		return -ENOMEM;
1282 	if (!len)
1283 		return 0;
1284 
1285 	/* Until we need other flags, refuse anything except VM_EXEC. */
1286 	if ((flags & (~VM_EXEC)) != 0)
1287 		return -EINVAL;
1288 
1289 	if (mmap_write_lock_killable(mm))
1290 		return -EINTR;
1291 
1292 	ret = check_brk_limits(addr, len);
1293 	if (ret)
1294 		goto limits_failed;
1295 
1296 	ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
1297 	if (ret)
1298 		goto munmap_failed;
1299 
1300 	vma = vma_prev(&vmi);
1301 	ret = do_brk_flags(&vmi, vma, addr, len, flags);
1302 	populate = ((mm->def_flags & VM_LOCKED) != 0);
1303 	mmap_write_unlock(mm);
1304 	userfaultfd_unmap_complete(mm, &uf);
1305 	if (populate && !ret)
1306 		mm_populate(addr, len);
1307 	return ret;
1308 
1309 munmap_failed:
1310 limits_failed:
1311 	mmap_write_unlock(mm);
1312 	return ret;
1313 }
1314 EXPORT_SYMBOL(vm_brk_flags);
1315 
1316 /* Release all mmaps. */
1317 void exit_mmap(struct mm_struct *mm)
1318 {
1319 	struct mmu_gather tlb;
1320 	struct vm_area_struct *vma;
1321 	unsigned long nr_accounted = 0;
1322 	VMA_ITERATOR(vmi, mm, 0);
1323 	int count = 0;
1324 
1325 	/* mm's last user has gone, and its about to be pulled down */
1326 	mmu_notifier_release(mm);
1327 
1328 	mmap_read_lock(mm);
1329 	arch_exit_mmap(mm);
1330 
1331 	vma = vma_next(&vmi);
1332 	if (!vma || unlikely(xa_is_zero(vma))) {
1333 		/* Can happen if dup_mmap() received an OOM */
1334 		mmap_read_unlock(mm);
1335 		mmap_write_lock(mm);
1336 		goto destroy;
1337 	}
1338 
1339 	flush_cache_mm(mm);
1340 	tlb_gather_mmu_fullmm(&tlb, mm);
1341 	/* update_hiwater_rss(mm) here? but nobody should be looking */
1342 	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
1343 	unmap_vmas(&tlb, &vmi.mas, vma, 0, ULONG_MAX, ULONG_MAX, false);
1344 	mmap_read_unlock(mm);
1345 
1346 	/*
1347 	 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
1348 	 * because the memory has been already freed.
1349 	 */
1350 	set_bit(MMF_OOM_SKIP, &mm->flags);
1351 	mmap_write_lock(mm);
1352 	mt_clear_in_rcu(&mm->mm_mt);
1353 	vma_iter_set(&vmi, vma->vm_end);
1354 	free_pgtables(&tlb, &vmi.mas, vma, FIRST_USER_ADDRESS,
1355 		      USER_PGTABLES_CEILING, true);
1356 	tlb_finish_mmu(&tlb);
1357 
1358 	/*
1359 	 * Walk the list again, actually closing and freeing it, with preemption
1360 	 * enabled, without holding any MM locks besides the unreachable
1361 	 * mmap_write_lock.
1362 	 */
1363 	vma_iter_set(&vmi, vma->vm_end);
1364 	do {
1365 		if (vma->vm_flags & VM_ACCOUNT)
1366 			nr_accounted += vma_pages(vma);
1367 		remove_vma(vma, /* unreachable = */ true);
1368 		count++;
1369 		cond_resched();
1370 		vma = vma_next(&vmi);
1371 	} while (vma && likely(!xa_is_zero(vma)));
1372 
1373 	BUG_ON(count != mm->map_count);
1374 
1375 	trace_exit_mmap(mm);
1376 destroy:
1377 	__mt_destroy(&mm->mm_mt);
1378 	mmap_write_unlock(mm);
1379 	vm_unacct_memory(nr_accounted);
1380 }
1381 
1382 /* Insert vm structure into process list sorted by address
1383  * and into the inode's i_mmap tree.  If vm_file is non-NULL
1384  * then i_mmap_rwsem is taken here.
1385  */
1386 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
1387 {
1388 	unsigned long charged = vma_pages(vma);
1389 
1390 
1391 	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
1392 		return -ENOMEM;
1393 
1394 	if ((vma->vm_flags & VM_ACCOUNT) &&
1395 	     security_vm_enough_memory_mm(mm, charged))
1396 		return -ENOMEM;
1397 
1398 	/*
1399 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
1400 	 * until its first write fault, when page's anon_vma and index
1401 	 * are set.  But now set the vm_pgoff it will almost certainly
1402 	 * end up with (unless mremap moves it elsewhere before that
1403 	 * first wfault), so /proc/pid/maps tells a consistent story.
1404 	 *
1405 	 * By setting it to reflect the virtual start address of the
1406 	 * vma, merges and splits can happen in a seamless way, just
1407 	 * using the existing file pgoff checks and manipulations.
1408 	 * Similarly in do_mmap and in do_brk_flags.
1409 	 */
1410 	if (vma_is_anonymous(vma)) {
1411 		BUG_ON(vma->anon_vma);
1412 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
1413 	}
1414 
1415 	if (vma_link(mm, vma)) {
1416 		if (vma->vm_flags & VM_ACCOUNT)
1417 			vm_unacct_memory(charged);
1418 		return -ENOMEM;
1419 	}
1420 
1421 	return 0;
1422 }
1423 
1424 /*
1425  * Return true if the calling process may expand its vm space by the passed
1426  * number of pages
1427  */
1428 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
1429 {
1430 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
1431 		return false;
1432 
1433 	if (is_data_mapping(flags) &&
1434 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
1435 		/* Workaround for Valgrind */
1436 		if (rlimit(RLIMIT_DATA) == 0 &&
1437 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
1438 			return true;
1439 
1440 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
1441 			     current->comm, current->pid,
1442 			     (mm->data_vm + npages) << PAGE_SHIFT,
1443 			     rlimit(RLIMIT_DATA),
1444 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
1445 
1446 		if (!ignore_rlimit_data)
1447 			return false;
1448 	}
1449 
1450 	return true;
1451 }
1452 
1453 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
1454 {
1455 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
1456 
1457 	if (is_exec_mapping(flags))
1458 		mm->exec_vm += npages;
1459 	else if (is_stack_mapping(flags))
1460 		mm->stack_vm += npages;
1461 	else if (is_data_mapping(flags))
1462 		mm->data_vm += npages;
1463 }
1464 
1465 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
1466 
1467 /*
1468  * Close hook, called for unmap() and on the old vma for mremap().
1469  *
1470  * Having a close hook prevents vma merging regardless of flags.
1471  */
1472 static void special_mapping_close(struct vm_area_struct *vma)
1473 {
1474 	const struct vm_special_mapping *sm = vma->vm_private_data;
1475 
1476 	if (sm->close)
1477 		sm->close(sm, vma);
1478 }
1479 
1480 static const char *special_mapping_name(struct vm_area_struct *vma)
1481 {
1482 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
1483 }
1484 
1485 static int special_mapping_mremap(struct vm_area_struct *new_vma)
1486 {
1487 	struct vm_special_mapping *sm = new_vma->vm_private_data;
1488 
1489 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
1490 		return -EFAULT;
1491 
1492 	if (sm->mremap)
1493 		return sm->mremap(sm, new_vma);
1494 
1495 	return 0;
1496 }
1497 
1498 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
1499 {
1500 	/*
1501 	 * Forbid splitting special mappings - kernel has expectations over
1502 	 * the number of pages in mapping. Together with VM_DONTEXPAND
1503 	 * the size of vma should stay the same over the special mapping's
1504 	 * lifetime.
1505 	 */
1506 	return -EINVAL;
1507 }
1508 
1509 static const struct vm_operations_struct special_mapping_vmops = {
1510 	.close = special_mapping_close,
1511 	.fault = special_mapping_fault,
1512 	.mremap = special_mapping_mremap,
1513 	.name = special_mapping_name,
1514 	/* vDSO code relies that VVAR can't be accessed remotely */
1515 	.access = NULL,
1516 	.may_split = special_mapping_split,
1517 };
1518 
1519 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
1520 {
1521 	struct vm_area_struct *vma = vmf->vma;
1522 	pgoff_t pgoff;
1523 	struct page **pages;
1524 	struct vm_special_mapping *sm = vma->vm_private_data;
1525 
1526 	if (sm->fault)
1527 		return sm->fault(sm, vmf->vma, vmf);
1528 
1529 	pages = sm->pages;
1530 
1531 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
1532 		pgoff--;
1533 
1534 	if (*pages) {
1535 		struct page *page = *pages;
1536 		get_page(page);
1537 		vmf->page = page;
1538 		return 0;
1539 	}
1540 
1541 	return VM_FAULT_SIGBUS;
1542 }
1543 
1544 static struct vm_area_struct *__install_special_mapping(
1545 	struct mm_struct *mm,
1546 	unsigned long addr, unsigned long len,
1547 	unsigned long vm_flags, void *priv,
1548 	const struct vm_operations_struct *ops)
1549 {
1550 	int ret;
1551 	struct vm_area_struct *vma;
1552 
1553 	vma = vm_area_alloc(mm);
1554 	if (unlikely(vma == NULL))
1555 		return ERR_PTR(-ENOMEM);
1556 
1557 	vma_set_range(vma, addr, addr + len, 0);
1558 	vm_flags_init(vma, (vm_flags | mm->def_flags |
1559 		      VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
1560 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
1561 
1562 	vma->vm_ops = ops;
1563 	vma->vm_private_data = priv;
1564 
1565 	ret = insert_vm_struct(mm, vma);
1566 	if (ret)
1567 		goto out;
1568 
1569 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
1570 
1571 	perf_event_mmap(vma);
1572 
1573 	return vma;
1574 
1575 out:
1576 	vm_area_free(vma);
1577 	return ERR_PTR(ret);
1578 }
1579 
1580 bool vma_is_special_mapping(const struct vm_area_struct *vma,
1581 	const struct vm_special_mapping *sm)
1582 {
1583 	return vma->vm_private_data == sm &&
1584 		vma->vm_ops == &special_mapping_vmops;
1585 }
1586 
1587 /*
1588  * Called with mm->mmap_lock held for writing.
1589  * Insert a new vma covering the given region, with the given flags.
1590  * Its pages are supplied by the given array of struct page *.
1591  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
1592  * The region past the last page supplied will always produce SIGBUS.
1593  * The array pointer and the pages it points to are assumed to stay alive
1594  * for as long as this mapping might exist.
1595  */
1596 struct vm_area_struct *_install_special_mapping(
1597 	struct mm_struct *mm,
1598 	unsigned long addr, unsigned long len,
1599 	unsigned long vm_flags, const struct vm_special_mapping *spec)
1600 {
1601 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
1602 					&special_mapping_vmops);
1603 }
1604 
1605 /*
1606  * initialise the percpu counter for VM
1607  */
1608 void __init mmap_init(void)
1609 {
1610 	int ret;
1611 
1612 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
1613 	VM_BUG_ON(ret);
1614 }
1615 
1616 /*
1617  * Initialise sysctl_user_reserve_kbytes.
1618  *
1619  * This is intended to prevent a user from starting a single memory hogging
1620  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
1621  * mode.
1622  *
1623  * The default value is min(3% of free memory, 128MB)
1624  * 128MB is enough to recover with sshd/login, bash, and top/kill.
1625  */
1626 static int init_user_reserve(void)
1627 {
1628 	unsigned long free_kbytes;
1629 
1630 	free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
1631 
1632 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, SZ_128K);
1633 	return 0;
1634 }
1635 subsys_initcall(init_user_reserve);
1636 
1637 /*
1638  * Initialise sysctl_admin_reserve_kbytes.
1639  *
1640  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
1641  * to log in and kill a memory hogging process.
1642  *
1643  * Systems with more than 256MB will reserve 8MB, enough to recover
1644  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
1645  * only reserve 3% of free pages by default.
1646  */
1647 static int init_admin_reserve(void)
1648 {
1649 	unsigned long free_kbytes;
1650 
1651 	free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
1652 
1653 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, SZ_8K);
1654 	return 0;
1655 }
1656 subsys_initcall(init_admin_reserve);
1657 
1658 /*
1659  * Reinititalise user and admin reserves if memory is added or removed.
1660  *
1661  * The default user reserve max is 128MB, and the default max for the
1662  * admin reserve is 8MB. These are usually, but not always, enough to
1663  * enable recovery from a memory hogging process using login/sshd, a shell,
1664  * and tools like top. It may make sense to increase or even disable the
1665  * reserve depending on the existence of swap or variations in the recovery
1666  * tools. So, the admin may have changed them.
1667  *
1668  * If memory is added and the reserves have been eliminated or increased above
1669  * the default max, then we'll trust the admin.
1670  *
1671  * If memory is removed and there isn't enough free memory, then we
1672  * need to reset the reserves.
1673  *
1674  * Otherwise keep the reserve set by the admin.
1675  */
1676 static int reserve_mem_notifier(struct notifier_block *nb,
1677 			     unsigned long action, void *data)
1678 {
1679 	unsigned long tmp, free_kbytes;
1680 
1681 	switch (action) {
1682 	case MEM_ONLINE:
1683 		/* Default max is 128MB. Leave alone if modified by operator. */
1684 		tmp = sysctl_user_reserve_kbytes;
1685 		if (tmp > 0 && tmp < SZ_128K)
1686 			init_user_reserve();
1687 
1688 		/* Default max is 8MB.  Leave alone if modified by operator. */
1689 		tmp = sysctl_admin_reserve_kbytes;
1690 		if (tmp > 0 && tmp < SZ_8K)
1691 			init_admin_reserve();
1692 
1693 		break;
1694 	case MEM_OFFLINE:
1695 		free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
1696 
1697 		if (sysctl_user_reserve_kbytes > free_kbytes) {
1698 			init_user_reserve();
1699 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
1700 				sysctl_user_reserve_kbytes);
1701 		}
1702 
1703 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
1704 			init_admin_reserve();
1705 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
1706 				sysctl_admin_reserve_kbytes);
1707 		}
1708 		break;
1709 	default:
1710 		break;
1711 	}
1712 	return NOTIFY_OK;
1713 }
1714 
1715 static int __meminit init_reserve_notifier(void)
1716 {
1717 	if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
1718 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
1719 
1720 	return 0;
1721 }
1722 subsys_initcall(init_reserve_notifier);
1723 
1724 /*
1725  * Relocate a VMA downwards by shift bytes. There cannot be any VMAs between
1726  * this VMA and its relocated range, which will now reside at [vma->vm_start -
1727  * shift, vma->vm_end - shift).
1728  *
1729  * This function is almost certainly NOT what you want for anything other than
1730  * early executable temporary stack relocation.
1731  */
1732 int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
1733 {
1734 	/*
1735 	 * The process proceeds as follows:
1736 	 *
1737 	 * 1) Use shift to calculate the new vma endpoints.
1738 	 * 2) Extend vma to cover both the old and new ranges.  This ensures the
1739 	 *    arguments passed to subsequent functions are consistent.
1740 	 * 3) Move vma's page tables to the new range.
1741 	 * 4) Free up any cleared pgd range.
1742 	 * 5) Shrink the vma to cover only the new range.
1743 	 */
1744 
1745 	struct mm_struct *mm = vma->vm_mm;
1746 	unsigned long old_start = vma->vm_start;
1747 	unsigned long old_end = vma->vm_end;
1748 	unsigned long length = old_end - old_start;
1749 	unsigned long new_start = old_start - shift;
1750 	unsigned long new_end = old_end - shift;
1751 	VMA_ITERATOR(vmi, mm, new_start);
1752 	VMG_STATE(vmg, mm, &vmi, new_start, old_end, 0, vma->vm_pgoff);
1753 	struct vm_area_struct *next;
1754 	struct mmu_gather tlb;
1755 
1756 	BUG_ON(new_start > new_end);
1757 
1758 	/*
1759 	 * ensure there are no vmas between where we want to go
1760 	 * and where we are
1761 	 */
1762 	if (vma != vma_next(&vmi))
1763 		return -EFAULT;
1764 
1765 	vma_iter_prev_range(&vmi);
1766 	/*
1767 	 * cover the whole range: [new_start, old_end)
1768 	 */
1769 	vmg.vma = vma;
1770 	if (vma_expand(&vmg))
1771 		return -ENOMEM;
1772 
1773 	/*
1774 	 * move the page tables downwards, on failure we rely on
1775 	 * process cleanup to remove whatever mess we made.
1776 	 */
1777 	if (length != move_page_tables(vma, old_start,
1778 				       vma, new_start, length, false, true))
1779 		return -ENOMEM;
1780 
1781 	tlb_gather_mmu(&tlb, mm);
1782 	next = vma_next(&vmi);
1783 	if (new_end > old_start) {
1784 		/*
1785 		 * when the old and new regions overlap clear from new_end.
1786 		 */
1787 		free_pgd_range(&tlb, new_end, old_end, new_end,
1788 			next ? next->vm_start : USER_PGTABLES_CEILING);
1789 	} else {
1790 		/*
1791 		 * otherwise, clean from old_start; this is done to not touch
1792 		 * the address space in [new_end, old_start) some architectures
1793 		 * have constraints on va-space that make this illegal (IA64) -
1794 		 * for the others its just a little faster.
1795 		 */
1796 		free_pgd_range(&tlb, old_start, old_end, new_end,
1797 			next ? next->vm_start : USER_PGTABLES_CEILING);
1798 	}
1799 	tlb_finish_mmu(&tlb);
1800 
1801 	vma_prev(&vmi);
1802 	/* Shrink the vma to just the new range */
1803 	return vma_shrink(&vmi, vma, new_start, new_end, vma->vm_pgoff);
1804 }
1805 
1806 #ifdef CONFIG_MMU
1807 /*
1808  * Obtain a read lock on mm->mmap_lock, if the specified address is below the
1809  * start of the VMA, the intent is to perform a write, and it is a
1810  * downward-growing stack, then attempt to expand the stack to contain it.
1811  *
1812  * This function is intended only for obtaining an argument page from an ELF
1813  * image, and is almost certainly NOT what you want to use for any other
1814  * purpose.
1815  *
1816  * IMPORTANT - VMA fields are accessed without an mmap lock being held, so the
1817  * VMA referenced must not be linked in any user-visible tree, i.e. it must be a
1818  * new VMA being mapped.
1819  *
1820  * The function assumes that addr is either contained within the VMA or below
1821  * it, and makes no attempt to validate this value beyond that.
1822  *
1823  * Returns true if the read lock was obtained and a stack was perhaps expanded,
1824  * false if the stack expansion failed.
1825  *
1826  * On stack expansion the function temporarily acquires an mmap write lock
1827  * before downgrading it.
1828  */
1829 bool mmap_read_lock_maybe_expand(struct mm_struct *mm,
1830 				 struct vm_area_struct *new_vma,
1831 				 unsigned long addr, bool write)
1832 {
1833 	if (!write || addr >= new_vma->vm_start) {
1834 		mmap_read_lock(mm);
1835 		return true;
1836 	}
1837 
1838 	if (!(new_vma->vm_flags & VM_GROWSDOWN))
1839 		return false;
1840 
1841 	mmap_write_lock(mm);
1842 	if (expand_downwards(new_vma, addr)) {
1843 		mmap_write_unlock(mm);
1844 		return false;
1845 	}
1846 
1847 	mmap_write_downgrade(mm);
1848 	return true;
1849 }
1850 #else
1851 bool mmap_read_lock_maybe_expand(struct mm_struct *mm, struct vm_area_struct *vma,
1852 				 unsigned long addr, bool write)
1853 {
1854 	return false;
1855 }
1856 #endif
1857