mmap.c 101.7 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
L
Linus Torvalds 已提交
2 3 4 5 6
/*
 * mm/mmap.c
 *
 * Written by obz.
 *
A
Alan Cox 已提交
7
 * Address space accounting code	<alan@lxorguk.ukuu.org.uk>
L
Linus Torvalds 已提交
8 9
 */

10 11
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

12
#include <linux/kernel.h>
L
Linus Torvalds 已提交
13
#include <linux/slab.h>
A
Alexey Dobriyan 已提交
14
#include <linux/backing-dev.h>
L
Linus Torvalds 已提交
15
#include <linux/mm.h>
16
#include <linux/mm_inline.h>
L
Linus Torvalds 已提交
17 18 19 20 21
#include <linux/shm.h>
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/syscalls.h>
22
#include <linux/capability.h>
L
Linus Torvalds 已提交
23 24 25 26 27 28
#include <linux/init.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
29
#include <linux/shmem_fs.h>
L
Linus Torvalds 已提交
30
#include <linux/profile.h>
31
#include <linux/export.h>
L
Linus Torvalds 已提交
32 33 34
#include <linux/mount.h>
#include <linux/mempolicy.h>
#include <linux/rmap.h>
A
Andrea Arcangeli 已提交
35
#include <linux/mmu_notifier.h>
36
#include <linux/mmdebug.h>
37
#include <linux/perf_event.h>
A
Al Viro 已提交
38
#include <linux/audit.h>
A
Andrea Arcangeli 已提交
39
#include <linux/khugepaged.h>
40
#include <linux/uprobes.h>
41 42
#include <linux/notifier.h>
#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>
L
Linus Torvalds 已提交
49

50
#include <linux/uaccess.h>
L
Linus Torvalds 已提交
51 52
#include <asm/cacheflush.h>
#include <asm/tlb.h>
53
#include <asm/mmu_context.h>
L
Linus Torvalds 已提交
54

55 56 57
#define CREATE_TRACE_POINTS
#include <trace/events/mmap.h>

58 59
#include "internal.h"

60 61 62 63
#ifndef arch_mmap_check
#define arch_mmap_check(addr, len, flags)	(0)
#endif

64 65 66 67 68 69 70 71 72 73 74
#ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
#endif
#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
#endif

75
static bool ignore_rlimit_data;
76
core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
77

L
Liam R. Howlett 已提交
78
static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
79
		struct vm_area_struct *vma, struct vm_area_struct *prev,
L
Liam R. Howlett 已提交
80 81
		struct vm_area_struct *next, unsigned long start,
		unsigned long end);
82

83 84 85 86 87 88 89 90 91
static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
{
	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
}

/* Update vma->vm_page_prot to reflect vma->vm_flags. */
void vma_set_page_prot(struct vm_area_struct *vma)
{
	unsigned long vm_flags = vma->vm_flags;
92
	pgprot_t vm_page_prot;
93

94 95
	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
	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
}

L
Linus Torvalds 已提交
103
/*
104
 * Requires inode->i_mapping->i_mmap_rwsem
L
Linus Torvalds 已提交
105 106 107 108 109
 */
static void __remove_shared_vm_struct(struct vm_area_struct *vma,
		struct file *file, struct address_space *mapping)
{
	if (vma->vm_flags & VM_SHARED)
110
		mapping_unmap_writable(mapping);
L
Linus Torvalds 已提交
111 112

	flush_dcache_mmap_lock(mapping);
113
	vma_interval_tree_remove(vma, &mapping->i_mmap);
L
Linus Torvalds 已提交
114 115 116 117
	flush_dcache_mmap_unlock(mapping);
}

/*
118
 * Unlink a file-based vm structure from its interval tree, to hide
119
 * vma from rmap and vmtruncate before freeing its page tables.
L
Linus Torvalds 已提交
120
 */
121
void unlink_file_vma(struct vm_area_struct *vma)
L
Linus Torvalds 已提交
122 123 124 125 126
{
	struct file *file = vma->vm_file;

	if (file) {
		struct address_space *mapping = file->f_mapping;
127
		i_mmap_lock_write(mapping);
L
Linus Torvalds 已提交
128
		__remove_shared_vm_struct(vma, file, mapping);
129
		i_mmap_unlock_write(mapping);
L
Linus Torvalds 已提交
130
	}
131 132 133
}

/*
L
Liam R. Howlett 已提交
134
 * Close a vm structure and free it.
135
 */
L
Liam R. Howlett 已提交
136
static void remove_vma(struct vm_area_struct *vma)
137 138
{
	might_sleep();
L
Linus Torvalds 已提交
139 140
	if (vma->vm_ops && vma->vm_ops->close)
		vma->vm_ops->close(vma);
141
	if (vma->vm_file)
142
		fput(vma->vm_file);
143
	mpol_put(vma_policy(vma));
144
	vm_area_free(vma);
L
Linus Torvalds 已提交
145 146
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
/*
 * check_brk_limits() - Use platform specific check of range & verify mlock
 * limits.
 * @addr: The address to check
 * @len: The size of increase.
 *
 * Return: 0 on success.
 */
static int check_brk_limits(unsigned long addr, unsigned long len)
{
	unsigned long mapped_addr;

	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
	if (IS_ERR_VALUE(mapped_addr))
		return mapped_addr;

	return mlock_future_check(current->mm, current->mm->def_flags, len);
}
static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
			 unsigned long newbrk, unsigned long oldbrk,
			 struct list_head *uf);
static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *brkvma,
L
Liam R. Howlett 已提交
169
		unsigned long addr, unsigned long request, unsigned long flags);
170
SYSCALL_DEFINE1(brk, unsigned long, brk)
L
Linus Torvalds 已提交
171
{
172
	unsigned long newbrk, oldbrk, origbrk;
L
Linus Torvalds 已提交
173
	struct mm_struct *mm = current->mm;
174
	struct vm_area_struct *brkvma, *next = NULL;
175
	unsigned long min_brk;
176
	bool populate;
177
	bool downgraded = false;
178
	LIST_HEAD(uf);
179
	MA_STATE(mas, &mm->mm_mt, 0, 0);
L
Linus Torvalds 已提交
180

181
	if (mmap_write_lock_killable(mm))
182
		return -EINTR;
L
Linus Torvalds 已提交
183

184 185
	origbrk = mm->brk;

186
#ifdef CONFIG_COMPAT_BRK
187 188 189 190 191
	/*
	 * CONFIG_COMPAT_BRK can still be overridden by setting
	 * randomize_va_space to 2, which will still cause mm->start_brk
	 * to be arbitrarily shifted
	 */
192
	if (current->brk_randomized)
193 194 195
		min_brk = mm->start_brk;
	else
		min_brk = mm->end_data;
196 197 198 199
#else
	min_brk = mm->start_brk;
#endif
	if (brk < min_brk)
L
Linus Torvalds 已提交
200
		goto out;
R
Ram Gupta 已提交
201 202 203 204 205 206 207

	/*
	 * Check against rlimit here. If this check is done later after the test
	 * of oldbrk with newbrk then it can escape the test and let the data
	 * segment grow beyond its set limit the in case where the limit is
	 * not page aligned -Ram Gupta
	 */
C
Cyrill Gorcunov 已提交
208 209
	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
			      mm->end_data, mm->start_data))
R
Ram Gupta 已提交
210 211
		goto out;

L
Linus Torvalds 已提交
212 213
	newbrk = PAGE_ALIGN(brk);
	oldbrk = PAGE_ALIGN(mm->brk);
214 215 216 217
	if (oldbrk == newbrk) {
		mm->brk = brk;
		goto success;
	}
L
Linus Torvalds 已提交
218

219 220
	/*
	 * Always allow shrinking brk.
221
	 * do_brk_munmap() may downgrade mmap_lock to read.
222
	 */
L
Linus Torvalds 已提交
223
	if (brk <= mm->brk) {
224 225
		int ret;

226 227 228 229 230 231
		/* Search one past newbrk */
		mas_set(&mas, newbrk);
		brkvma = mas_find(&mas, oldbrk);
		BUG_ON(brkvma == NULL);
		if (brkvma->vm_start >= oldbrk)
			goto out; /* mapping intersects with an existing non-brk vma. */
232
		/*
233 234 235
		 * mm->brk must be protected by write mmap_lock.
		 * do_brk_munmap() may downgrade the lock,  so update it
		 * before calling do_brk_munmap().
236 237
		 */
		mm->brk = brk;
238 239
		ret = do_brk_munmap(&mas, brkvma, newbrk, oldbrk, &uf);
		if (ret == 1)  {
240
			downgraded = true;
241 242 243 244 245 246
			goto success;
		} else if (!ret)
			goto success;

		mm->brk = origbrk;
		goto out;
L
Linus Torvalds 已提交
247 248
	}

249 250 251 252 253 254 255 256 257
	if (check_brk_limits(oldbrk, newbrk - oldbrk))
		goto out;

	/*
	 * Only check if the next VMA is within the stack_guard_gap of the
	 * expansion area
	 */
	mas_set(&mas, oldbrk);
	next = mas_find(&mas, newbrk - 1 + PAGE_SIZE + stack_guard_gap);
258
	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
L
Linus Torvalds 已提交
259 260
		goto out;

261
	brkvma = mas_prev(&mas, mm->start_brk);
L
Linus Torvalds 已提交
262
	/* Ok, looks good - let it rip. */
263
	if (do_brk_flags(&mas, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
L
Linus Torvalds 已提交
264
		goto out;
265

L
Linus Torvalds 已提交
266
	mm->brk = brk;
267 268

success:
269
	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
270
	if (downgraded)
271
		mmap_read_unlock(mm);
272
	else
273
		mmap_write_unlock(mm);
274
	userfaultfd_unmap_complete(mm, &uf);
275 276 277 278
	if (populate)
		mm_populate(oldbrk, newbrk - oldbrk);
	return brk;

L
Linus Torvalds 已提交
279
out:
280
	mmap_write_unlock(mm);
281
	return origbrk;
L
Linus Torvalds 已提交
282 283
}

284 285 286
#if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
extern void mt_validate(struct maple_tree *mt);
extern void mt_dump(const struct maple_tree *mt);
L
Linus Torvalds 已提交
287

288 289 290 291
/* Validate the maple tree */
static void validate_mm_mt(struct mm_struct *mm)
{
	struct maple_tree *mt = &mm->mm_mt;
L
Liam R. Howlett 已提交
292
	struct vm_area_struct *vma_mt;
293 294 295 296 297

	MA_STATE(mas, mt, 0, 0);

	mt_validate(&mm->mm_mt);
	mas_for_each(&mas, vma_mt, ULONG_MAX) {
L
Liam R. Howlett 已提交
298 299
		if ((vma_mt->vm_start != mas.index) ||
		    (vma_mt->vm_end - 1 != mas.last)) {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
			pr_emerg("issue in %s\n", current->comm);
			dump_stack();
			dump_vma(vma_mt);
			pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
				 mas.index, mas.last);
			pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
				 vma_mt->vm_start, vma_mt->vm_end);

			mt_dump(mas.tree);
			if (vma_mt->vm_end != mas.last + 1) {
				pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
						mm, vma_mt->vm_start, vma_mt->vm_end,
						mas.index, mas.last);
				mt_dump(mas.tree);
			}
			VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
			if (vma_mt->vm_start != mas.index) {
				pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
						mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
				mt_dump(mas.tree);
			}
			VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
		}
	}
}
L
Linus Torvalds 已提交
325

326
static void validate_mm(struct mm_struct *mm)
L
Linus Torvalds 已提交
327 328 329
{
	int bug = 0;
	int i = 0;
L
Liam R. Howlett 已提交
330 331
	struct vm_area_struct *vma;
	MA_STATE(mas, &mm->mm_mt, 0, 0);
332

L
Liam R. Howlett 已提交
333 334
	validate_mm_mt(mm);

L
Liam R. Howlett 已提交
335
	mas_for_each(&mas, vma, ULONG_MAX) {
L
Liam R. Howlett 已提交
336
#ifdef CONFIG_DEBUG_VM_RB
337
		struct anon_vma *anon_vma = vma->anon_vma;
338
		struct anon_vma_chain *avc;
339

340 341 342 343 344 345
		if (anon_vma) {
			anon_vma_lock_read(anon_vma);
			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
				anon_vma_interval_tree_verify(avc);
			anon_vma_unlock_read(anon_vma);
		}
L
Liam R. Howlett 已提交
346
#endif
L
Linus Torvalds 已提交
347 348
		i++;
	}
349
	if (i != mm->map_count) {
L
Liam R. Howlett 已提交
350
		pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
351 352
		bug = 1;
	}
S
Sasha Levin 已提交
353
	VM_BUG_ON_MM(bug, mm);
L
Linus Torvalds 已提交
354
}
L
Liam R. Howlett 已提交
355 356

#else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
357
#define validate_mm_mt(root) do { } while (0)
L
Linus Torvalds 已提交
358
#define validate_mm(mm) do { } while (0)
L
Liam R. Howlett 已提交
359
#endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
360

361 362 363 364 365 366 367 368 369 370 371
/*
 * vma has some anon_vma assigned, and is already inserted on that
 * anon_vma's interval trees.
 *
 * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
 * vma must be removed from the anon_vma's interval trees using
 * anon_vma_interval_tree_pre_update_vma().
 *
 * After the update, the vma will be reinserted using
 * anon_vma_interval_tree_post_update_vma().
 *
372
 * The entire update must be protected by exclusive mmap_lock and by
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
 * the root anon_vma's mutex.
 */
static inline void
anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
{
	struct anon_vma_chain *avc;

	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
}

static inline void
anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
{
	struct anon_vma_chain *avc;

	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
}

L
Liam R. Howlett 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405
/*
 * range_has_overlap() - Check the @start - @end range for overlapping VMAs and
 * sets up a pointer to the previous VMA
 * @mm: the mm struct
 * @start: the start address of the range
 * @end: the end address of the range
 * @pprev: the pointer to the pointer of the previous VMA
 *
 * Returns: True if there is an overlapping VMA, false otherwise
 */
static inline
bool range_has_overlap(struct mm_struct *mm, unsigned long start,
		       unsigned long end, struct vm_area_struct **pprev)
L
Linus Torvalds 已提交
406
{
L
Liam R. Howlett 已提交
407
	struct vm_area_struct *existing;
L
Linus Torvalds 已提交
408

L
Liam R. Howlett 已提交
409
	MA_STATE(mas, &mm->mm_mt, start, start);
L
Liam R. Howlett 已提交
410
	rcu_read_lock();
L
Liam R. Howlett 已提交
411 412
	existing = mas_find(&mas, end - 1);
	*pprev = mas_prev(&mas, 0);
L
Liam R. Howlett 已提交
413
	rcu_read_unlock();
L
Liam R. Howlett 已提交
414
	return existing ? true : false;
L
Linus Torvalds 已提交
415 416
}

417 418 419
static unsigned long count_vma_pages_range(struct mm_struct *mm,
		unsigned long addr, unsigned long end)
{
420
	VMA_ITERATOR(vmi, mm, addr);
421
	struct vm_area_struct *vma;
422
	unsigned long nr_pages = 0;
423

424 425 426
	for_each_vma_range(vmi, vma, end) {
		unsigned long vm_start = max(addr, vma->vm_start);
		unsigned long vm_end = min(end, vma->vm_end);
427

428
		nr_pages += PHYS_PFN(vm_end - vm_start);
429 430 431 432 433
	}

	return nr_pages;
}

D
Denys Vlasenko 已提交
434
static void __vma_link_file(struct vm_area_struct *vma)
L
Linus Torvalds 已提交
435
{
Z
ZhenwenXu 已提交
436
	struct file *file;
L
Linus Torvalds 已提交
437 438 439 440 441 442

	file = vma->vm_file;
	if (file) {
		struct address_space *mapping = file->f_mapping;

		if (vma->vm_flags & VM_SHARED)
443
			mapping_allow_writable(mapping);
L
Linus Torvalds 已提交
444 445

		flush_dcache_mmap_lock(mapping);
446
		vma_interval_tree_insert(vma, &mapping->i_mmap);
L
Linus Torvalds 已提交
447 448 449 450
		flush_dcache_mmap_unlock(mapping);
	}
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
/*
 * vma_mas_store() - Store a VMA in the maple tree.
 * @vma: The vm_area_struct
 * @mas: The maple state
 *
 * Efficient way to store a VMA in the maple tree when the @mas has already
 * walked to the correct location.
 *
 * Note: the end address is inclusive in the maple tree.
 */
void vma_mas_store(struct vm_area_struct *vma, struct ma_state *mas)
{
	trace_vma_store(mas->tree, vma);
	mas_set_range(mas, vma->vm_start, vma->vm_end - 1);
	mas_store_prealloc(mas, vma);
}

/*
 * vma_mas_remove() - Remove a VMA from the maple tree.
 * @vma: The vm_area_struct
 * @mas: The maple state
 *
 * Efficient way to remove a VMA from the maple tree when the @mas has already
 * been established and points to the correct location.
 * Note: the end address is inclusive in the maple tree.
 */
void vma_mas_remove(struct vm_area_struct *vma, struct ma_state *mas)
{
	trace_vma_mas_szero(mas->tree, vma->vm_start, vma->vm_end - 1);
	mas->index = vma->vm_start;
	mas->last = vma->vm_end - 1;
	mas_store_prealloc(mas, NULL);
}

/*
 * vma_mas_szero() - Set a given range to zero.  Used when modifying a
 * vm_area_struct start or end.
 *
 * @mm: The struct_mm
 * @start: The start address to zero
 * @end: The end address to zero.
 */
static inline void vma_mas_szero(struct ma_state *mas, unsigned long start,
				unsigned long end)
{
	trace_vma_mas_szero(mas->tree, start, end - 1);
	mas_set_range(mas, start, end - 1);
	mas_store_prealloc(mas, NULL);
}

L
Liam R. Howlett 已提交
501
static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
L
Linus Torvalds 已提交
502
{
503
	MA_STATE(mas, &mm->mm_mt, 0, 0);
L
Linus Torvalds 已提交
504 505
	struct address_space *mapping = NULL;

506 507 508
	if (mas_preallocate(&mas, vma, GFP_KERNEL))
		return -ENOMEM;

509
	if (vma->vm_file) {
L
Linus Torvalds 已提交
510
		mapping = vma->vm_file->f_mapping;
511
		i_mmap_lock_write(mapping);
512
	}
L
Linus Torvalds 已提交
513

514
	vma_mas_store(vma, &mas);
L
Linus Torvalds 已提交
515 516 517
	__vma_link_file(vma);

	if (mapping)
518
		i_mmap_unlock_write(mapping);
L
Linus Torvalds 已提交
519 520 521

	mm->map_count++;
	validate_mm(mm);
522
	return 0;
L
Linus Torvalds 已提交
523 524
}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
/*
 * vma_expand - Expand an existing VMA
 *
 * @mas: The maple state
 * @vma: The vma to expand
 * @start: The start of the vma
 * @end: The exclusive end of the vma
 * @pgoff: The page offset of vma
 * @next: The current of next vma.
 *
 * Expand @vma to @start and @end.  Can expand off the start and end.  Will
 * expand over @next if it's different from @vma and @end == @next->vm_end.
 * Checking if the @vma can expand and merge with @next needs to be handled by
 * the caller.
 *
 * Returns: 0 on success
 */
inline int vma_expand(struct ma_state *mas, struct vm_area_struct *vma,
		      unsigned long start, unsigned long end, pgoff_t pgoff,
		      struct vm_area_struct *next)
{
	struct mm_struct *mm = vma->vm_mm;
	struct address_space *mapping = NULL;
	struct rb_root_cached *root = NULL;
	struct anon_vma *anon_vma = vma->anon_vma;
	struct file *file = vma->vm_file;
	bool remove_next = false;

	if (next && (vma != next) && (end == next->vm_end)) {
		remove_next = true;
		if (next->anon_vma && !vma->anon_vma) {
			int error;

			anon_vma = next->anon_vma;
			vma->anon_vma = anon_vma;
			error = anon_vma_clone(vma, next);
			if (error)
				return error;
		}
	}

	/* Not merging but overwriting any part of next is not handled. */
	VM_BUG_ON(next && !remove_next && next != vma && end > next->vm_start);
	/* Only handles expanding */
	VM_BUG_ON(vma->vm_start < start || vma->vm_end > end);

	if (mas_preallocate(mas, vma, GFP_KERNEL))
		goto nomem;

	vma_adjust_trans_huge(vma, start, end, 0);

	if (file) {
		mapping = file->f_mapping;
		root = &mapping->i_mmap;
		uprobe_munmap(vma, vma->vm_start, vma->vm_end);
		i_mmap_lock_write(mapping);
	}

	if (anon_vma) {
		anon_vma_lock_write(anon_vma);
		anon_vma_interval_tree_pre_update_vma(vma);
	}

	if (file) {
		flush_dcache_mmap_lock(mapping);
		vma_interval_tree_remove(vma, root);
	}

	vma->vm_start = start;
	vma->vm_end = end;
	vma->vm_pgoff = pgoff;
	/* Note: mas must be pointing to the expanding VMA */
	vma_mas_store(vma, mas);

	if (file) {
		vma_interval_tree_insert(vma, root);
		flush_dcache_mmap_unlock(mapping);
	}

	/* Expanding over the next vma */
L
Liam R. Howlett 已提交
605 606
	if (remove_next && file) {
		__remove_shared_vm_struct(next, file, mapping);
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
	}

	if (anon_vma) {
		anon_vma_interval_tree_post_update_vma(vma);
		anon_vma_unlock_write(anon_vma);
	}

	if (file) {
		i_mmap_unlock_write(mapping);
		uprobe_mmap(vma);
	}

	if (remove_next) {
		if (file) {
			uprobe_munmap(next, next->vm_start, next->vm_end);
			fput(file);
		}
		if (next->anon_vma)
			anon_vma_merge(vma, next);
		mm->map_count--;
		mpol_put(vma_policy(next));
		vm_area_free(next);
	}

	validate_mm(mm);
	return 0;

nomem:
	return -ENOMEM;
}

L
Linus Torvalds 已提交
638 639 640 641 642 643 644
/*
 * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
 * is already present in an i_mmap tree without adjusting the tree.
 * The following helper function should be used when such adjustments
 * are necessary.  The "insert" vma (if any) is to be inserted
 * before we drop the necessary locks.
 */
645 646 647
int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
	unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
	struct vm_area_struct *expand)
L
Linus Torvalds 已提交
648 649
{
	struct mm_struct *mm = vma->vm_mm;
L
Liam R. Howlett 已提交
650 651
	struct vm_area_struct *next_next, *next = find_vma(mm, vma->vm_end);
	struct vm_area_struct *orig_vma = vma;
L
Linus Torvalds 已提交
652
	struct address_space *mapping = NULL;
653
	struct rb_root_cached *root = NULL;
654
	struct anon_vma *anon_vma = NULL;
L
Linus Torvalds 已提交
655
	struct file *file = vma->vm_file;
L
Liam R. Howlett 已提交
656
	bool vma_changed = false;
L
Linus Torvalds 已提交
657 658
	long adjust_next = 0;
	int remove_next = 0;
659 660
	MA_STATE(mas, &mm->mm_mt, 0, 0);
	struct vm_area_struct *exporter = NULL, *importer = NULL;
L
Linus Torvalds 已提交
661

662
	if (next && !insert) {
L
Linus Torvalds 已提交
663 664 665 666
		if (end >= next->vm_end) {
			/*
			 * vma expands, overlapping all the next, and
			 * perhaps the one after too (mprotect case 6).
667
			 * The only other cases that gets here are
668
			 * case 1, case 7 and case 8.
L
Linus Torvalds 已提交
669
			 */
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
			if (next == expand) {
				/*
				 * The only case where we don't expand "vma"
				 * and we expand "next" instead is case 8.
				 */
				VM_WARN_ON(end != next->vm_end);
				/*
				 * remove_next == 3 means we're
				 * removing "vma" and that to do so we
				 * swapped "vma" and "next".
				 */
				remove_next = 3;
				VM_WARN_ON(file != next->vm_file);
				swap(vma, next);
			} else {
				VM_WARN_ON(expand != vma);
				/*
				 * case 1, 6, 7, remove_next == 2 is case 6,
				 * remove_next == 1 is case 1 or 7.
				 */
				remove_next = 1 + (end > next->vm_end);
691 692 693
				if (remove_next == 2)
					next_next = find_vma(mm, next->vm_end);

694
				VM_WARN_ON(remove_next == 2 &&
L
Liam R. Howlett 已提交
695
					   end != next_next->vm_end);
696 697
			}

698
			exporter = next;
L
Linus Torvalds 已提交
699
			importer = vma;
700 701 702 703 704

			/*
			 * If next doesn't have anon_vma, import from vma after
			 * next, if the vma overlaps with it.
			 */
705
			if (remove_next == 2 && !next->anon_vma)
L
Liam R. Howlett 已提交
706
				exporter = next_next;
707

L
Linus Torvalds 已提交
708 709 710 711 712
		} else if (end > next->vm_start) {
			/*
			 * vma expands, overlapping part of the next:
			 * mprotect case 5 shifting the boundary up.
			 */
713
			adjust_next = (end - next->vm_start);
714
			exporter = next;
L
Linus Torvalds 已提交
715
			importer = vma;
716
			VM_WARN_ON(expand != importer);
L
Linus Torvalds 已提交
717 718 719 720 721 722
		} else if (end < vma->vm_end) {
			/*
			 * vma shrinks, and !insert tells it's not
			 * split_vma inserting another: so it must be
			 * mprotect case 4 shifting the boundary down.
			 */
723
			adjust_next = -(vma->vm_end - end);
724
			exporter = vma;
L
Linus Torvalds 已提交
725
			importer = next;
726
			VM_WARN_ON(expand != importer);
L
Linus Torvalds 已提交
727 728
		}

729 730 731 732 733
		/*
		 * Easily overlooked: when mprotect shifts the boundary,
		 * make sure the expanding vma has anon_vma set if the
		 * shrinking vma had, to cover any anon pages imported.
		 */
734
		if (exporter && exporter->anon_vma && !importer->anon_vma) {
735 736
			int error;

737
			importer->anon_vma = exporter->anon_vma;
738
			error = anon_vma_clone(importer, exporter);
739
			if (error)
740
				return error;
741 742
		}
	}
743

744 745 746 747
	if (mas_preallocate(&mas, vma, GFP_KERNEL))
		return -ENOMEM;

	vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
L
Linus Torvalds 已提交
748 749
	if (file) {
		mapping = file->f_mapping;
750 751
		root = &mapping->i_mmap;
		uprobe_munmap(vma, vma->vm_start, vma->vm_end);
752

753 754
		if (adjust_next)
			uprobe_munmap(next, next->vm_start, next->vm_end);
755

756
		i_mmap_lock_write(mapping);
L
Linus Torvalds 已提交
757 758
		if (insert) {
			/*
759
			 * Put into interval tree now, so instantiated pages
L
Linus Torvalds 已提交
760 761 762 763 764 765 766 767
			 * are visible to arm/parisc __flush_dcache_page
			 * throughout; but we cannot insert into address
			 * space until vma start or end is updated.
			 */
			__vma_link_file(insert);
		}
	}

768 769 770 771
	anon_vma = vma->anon_vma;
	if (!anon_vma && adjust_next)
		anon_vma = next->anon_vma;
	if (anon_vma) {
772 773
		VM_WARN_ON(adjust_next && next->anon_vma &&
			   anon_vma != next->anon_vma);
774
		anon_vma_lock_write(anon_vma);
775 776 777 778
		anon_vma_interval_tree_pre_update_vma(vma);
		if (adjust_next)
			anon_vma_interval_tree_pre_update_vma(next);
	}
779

780
	if (file) {
L
Linus Torvalds 已提交
781
		flush_dcache_mmap_lock(mapping);
782
		vma_interval_tree_remove(vma, root);
L
Linus Torvalds 已提交
783
		if (adjust_next)
784
			vma_interval_tree_remove(next, root);
L
Linus Torvalds 已提交
785 786
	}

787
	if (start != vma->vm_start) {
788 789
		if ((vma->vm_start < start) &&
		    (!insert || (insert->vm_end != start))) {
L
Liam R. Howlett 已提交
790
			vma_mas_szero(&mas, vma->vm_start, start);
791 792 793 794
			VM_WARN_ON(insert && insert->vm_start > vma->vm_start);
		} else {
			vma_changed = true;
		}
795 796 797
		vma->vm_start = start;
	}
	if (end != vma->vm_end) {
798 799 800
		if (vma->vm_end > end) {
			if (!insert || (insert->vm_start != end)) {
				vma_mas_szero(&mas, end, vma->vm_end);
L
Liam R. Howlett 已提交
801
				mas_reset(&mas);
802 803 804 805 806 807
				VM_WARN_ON(insert &&
					   insert->vm_end < vma->vm_end);
			}
		} else {
			vma_changed = true;
		}
808 809
		vma->vm_end = end;
	}
810

L
Liam R. Howlett 已提交
811
	if (vma_changed)
812 813
		vma_mas_store(vma, &mas);

L
Linus Torvalds 已提交
814 815
	vma->vm_pgoff = pgoff;
	if (adjust_next) {
816 817
		next->vm_start += adjust_next;
		next->vm_pgoff += adjust_next >> PAGE_SHIFT;
818
		vma_mas_store(next, &mas);
L
Linus Torvalds 已提交
819 820
	}

821
	if (file) {
L
Linus Torvalds 已提交
822
		if (adjust_next)
823 824
			vma_interval_tree_insert(next, root);
		vma_interval_tree_insert(vma, root);
L
Linus Torvalds 已提交
825 826 827
		flush_dcache_mmap_unlock(mapping);
	}

L
Liam R. Howlett 已提交
828 829
	if (remove_next && file) {
		__remove_shared_vm_struct(next, file, mapping);
L
Liam R. Howlett 已提交
830
		if (remove_next == 2)
L
Liam R. Howlett 已提交
831
			__remove_shared_vm_struct(next_next, file, mapping);
L
Linus Torvalds 已提交
832 833 834 835 836 837
	} else if (insert) {
		/*
		 * split_vma has split insert from vma, and needs
		 * us to insert it before dropping the locks
		 * (it may either follow vma or precede it).
		 */
L
Liam R. Howlett 已提交
838 839 840
		mas_reset(&mas);
		vma_mas_store(insert, &mas);
		mm->map_count++;
L
Linus Torvalds 已提交
841 842
	}

843 844 845 846
	if (anon_vma) {
		anon_vma_interval_tree_post_update_vma(vma);
		if (adjust_next)
			anon_vma_interval_tree_post_update_vma(next);
847
		anon_vma_unlock_write(anon_vma);
848
	}
L
Linus Torvalds 已提交
849

850
	if (file) {
851
		i_mmap_unlock_write(mapping);
852
		uprobe_mmap(vma);
853 854

		if (adjust_next)
855
			uprobe_mmap(next);
856 857
	}

L
Linus Torvalds 已提交
858
	if (remove_next) {
859
again:
M
Matt Helsley 已提交
860
		if (file) {
861
			uprobe_munmap(next, next->vm_start, next->vm_end);
L
Linus Torvalds 已提交
862
			fput(file);
M
Matt Helsley 已提交
863
		}
864 865
		if (next->anon_vma)
			anon_vma_merge(vma, next);
L
Linus Torvalds 已提交
866
		mm->map_count--;
867
		mpol_put(vma_policy(next));
L
Liam R. Howlett 已提交
868 869
		if (remove_next != 2)
			BUG_ON(vma->vm_end < next->vm_end);
870
		vm_area_free(next);
L
Liam R. Howlett 已提交
871

L
Linus Torvalds 已提交
872 873
		/*
		 * In mprotect's case 6 (see comments on vma_merge),
L
Liam R. Howlett 已提交
874
		 * we must remove next_next too.
L
Linus Torvalds 已提交
875
		 */
876 877
		if (remove_next == 2) {
			remove_next = 1;
L
Liam R. Howlett 已提交
878
			next = next_next;
L
Linus Torvalds 已提交
879
			goto again;
880
		}
L
Linus Torvalds 已提交
881
	}
882
	if (insert && file)
883
		uprobe_mmap(insert);
L
Linus Torvalds 已提交
884

885
	mas_destroy(&mas);
L
Linus Torvalds 已提交
886
	validate_mm(mm);
L
Liam R. Howlett 已提交
887

888
	return 0;
L
Linus Torvalds 已提交
889 890 891 892 893 894 895
}

/*
 * If the vma has a ->close operation then the driver probably needs to release
 * per-vma resources, so we don't attempt to merge those.
 */
static inline int is_mergeable_vma(struct vm_area_struct *vma,
896
				struct file *file, unsigned long vm_flags,
897
				struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
898
				struct anon_vma_name *anon_name)
L
Linus Torvalds 已提交
899
{
900 901 902 903
	/*
	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
	 * match the flags but dirty bit -- the caller should mark
	 * merged VMA as dirty. If dirty bit won't be excluded from
W
Wei Yang 已提交
904
	 * comparison, we increase pressure on the memory system forcing
905 906 907 908
	 * the kernel to generate new VMAs when old one could be
	 * extended instead.
	 */
	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
L
Linus Torvalds 已提交
909 910 911 912 913
		return 0;
	if (vma->vm_file != file)
		return 0;
	if (vma->vm_ops && vma->vm_ops->close)
		return 0;
914 915
	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
		return 0;
916
	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
917
		return 0;
L
Linus Torvalds 已提交
918 919 920 921
	return 1;
}

static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
S
Shaohua Li 已提交
922 923
					struct anon_vma *anon_vma2,
					struct vm_area_struct *vma)
L
Linus Torvalds 已提交
924
{
S
Shaohua Li 已提交
925 926 927 928 929 930 931 932
	/*
	 * The list_is_singular() test is to avoid merging VMA cloned from
	 * parents. This can improve scalability caused by anon_vma lock.
	 */
	if ((!anon_vma1 || !anon_vma2) && (!vma ||
		list_is_singular(&vma->anon_vma_chain)))
		return 1;
	return anon_vma1 == anon_vma2;
L
Linus Torvalds 已提交
933 934 935 936 937 938 939 940 941 942
}

/*
 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
 * in front of (at a lower virtual address and file offset than) the vma.
 *
 * We cannot merge two vmas if they have differently assigned (non-NULL)
 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
 *
 * We don't check here for the merged mmap wrapping around the end of pagecache
943
 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
L
Linus Torvalds 已提交
944 945 946 947
 * wrap, nor mmaps which cover the final page at index -1UL.
 */
static int
can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
948 949
		     struct anon_vma *anon_vma, struct file *file,
		     pgoff_t vm_pgoff,
950
		     struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
951
		     struct anon_vma_name *anon_name)
L
Linus Torvalds 已提交
952
{
953
	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
S
Shaohua Li 已提交
954
	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
L
Linus Torvalds 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
		if (vma->vm_pgoff == vm_pgoff)
			return 1;
	}
	return 0;
}

/*
 * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
 * beyond (at a higher virtual address and file offset than) the vma.
 *
 * We cannot merge two vmas if they have differently assigned (non-NULL)
 * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
 */
static int
can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
970 971
		    struct anon_vma *anon_vma, struct file *file,
		    pgoff_t vm_pgoff,
972
		    struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
973
		    struct anon_vma_name *anon_name)
L
Linus Torvalds 已提交
974
{
975
	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
S
Shaohua Li 已提交
976
	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
L
Linus Torvalds 已提交
977
		pgoff_t vm_pglen;
978
		vm_pglen = vma_pages(vma);
L
Linus Torvalds 已提交
979 980 981 982 983 984 985
		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
			return 1;
	}
	return 0;
}

/*
986 987 988
 * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
 * figure out whether that can be merged with its predecessor or its
 * successor.  Or both (it neatly fills a hole).
L
Linus Torvalds 已提交
989 990 991 992 993 994 995 996 997 998 999 1000
 *
 * In most cases - when called for mmap, brk or mremap - [addr,end) is
 * certain not to be mapped by the time vma_merge is called; but when
 * called for mprotect, it is certain to be already mapped (either at
 * an offset within prev, or at the start of next), and the flags of
 * this area are about to be changed to vm_flags - and the no-change
 * case has already been eliminated.
 *
 * The following mprotect cases have to be considered, where AAAA is
 * the area passed down from mprotect_fixup, never extending beyond one
 * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
 *
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
 *     AAAA             AAAA                   AAAA
 *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPNNNNNN
 *    cannot merge    might become       might become
 *                    PPNNNNNNNNNN       PPPPPPPPPPNN
 *    mmap, brk or    case 4 below       case 5 below
 *    mremap move:
 *                        AAAA               AAAA
 *                    PPPP    NNNN       PPPPNNNNXXXX
 *                    might become       might become
 *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
 *                    PPPPPPPPNNNN 2 or  PPPPPPPPXXXX 7 or
 *                    PPPPNNNNNNNN 3     PPPPXXXXXXXX 8
L
Linus Torvalds 已提交
1013
 *
W
Wei Yang 已提交
1014
 * It is important for case 8 that the vma NNNN overlapping the
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
 * region AAAA is never going to extended over XXXX. Instead XXXX must
 * be extended in region AAAA and NNNN must be removed. This way in
 * all cases where vma_merge succeeds, the moment vma_adjust drops the
 * rmap_locks, the properties of the merged vma will be already
 * correct for the whole merged range. Some of those properties like
 * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
 * be correct for the whole merged range immediately after the
 * rmap_locks are released. Otherwise if XXXX would be removed and
 * NNNN would be extended over the XXXX range, remove_migration_ptes
 * or other rmap walkers (if working on addresses beyond the "end"
 * parameter) may establish ptes with the wrong permissions of NNNN
 * instead of the right permissions of XXXX.
L
Linus Torvalds 已提交
1027 1028 1029 1030
 */
struct vm_area_struct *vma_merge(struct mm_struct *mm,
			struct vm_area_struct *prev, unsigned long addr,
			unsigned long end, unsigned long vm_flags,
V
vishnu.ps 已提交
1031
			struct anon_vma *anon_vma, struct file *file,
1032
			pgoff_t pgoff, struct mempolicy *policy,
1033
			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1034
			struct anon_vma_name *anon_name)
L
Linus Torvalds 已提交
1035 1036 1037
{
	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
	struct vm_area_struct *area, *next;
1038
	int err;
L
Linus Torvalds 已提交
1039 1040 1041 1042 1043 1044 1045 1046

	/*
	 * We later require that vma->vm_flags == vm_flags,
	 * so this tests vma->vm_flags & VM_SPECIAL, too.
	 */
	if (vm_flags & VM_SPECIAL)
		return NULL;

L
Liam R. Howlett 已提交
1047
	next = find_vma(mm, prev ? prev->vm_end : 0);
L
Linus Torvalds 已提交
1048
	area = next;
1049
	if (area && area->vm_end == end)		/* cases 6, 7, 8 */
L
Liam R. Howlett 已提交
1050
		next = find_vma(mm, next->vm_end);
L
Linus Torvalds 已提交
1051

1052 1053 1054 1055 1056
	/* verify some invariant that must be enforced by the caller */
	VM_WARN_ON(prev && addr <= prev->vm_start);
	VM_WARN_ON(area && end > area->vm_end);
	VM_WARN_ON(addr >= end);

L
Linus Torvalds 已提交
1057 1058 1059 1060
	/*
	 * Can it merge with the predecessor?
	 */
	if (prev && prev->vm_end == addr &&
V
vishnu.ps 已提交
1061
			mpol_equal(vma_policy(prev), policy) &&
L
Linus Torvalds 已提交
1062
			can_vma_merge_after(prev, vm_flags,
1063
					    anon_vma, file, pgoff,
1064
					    vm_userfaultfd_ctx, anon_name)) {
L
Linus Torvalds 已提交
1065 1066 1067 1068 1069 1070
		/*
		 * OK, it can.  Can we now merge in the successor as well?
		 */
		if (next && end == next->vm_start &&
				mpol_equal(policy, vma_policy(next)) &&
				can_vma_merge_before(next, vm_flags,
1071 1072
						     anon_vma, file,
						     pgoff+pglen,
1073
						     vm_userfaultfd_ctx, anon_name) &&
L
Linus Torvalds 已提交
1074
				is_mergeable_anon_vma(prev->anon_vma,
S
Shaohua Li 已提交
1075
						      next->anon_vma, NULL)) {
L
Linus Torvalds 已提交
1076
							/* cases 1, 6 */
1077 1078 1079
			err = __vma_adjust(prev, prev->vm_start,
					 next->vm_end, prev->vm_pgoff, NULL,
					 prev);
L
Linus Torvalds 已提交
1080
		} else					/* cases 2, 5, 7 */
1081 1082
			err = __vma_adjust(prev, prev->vm_start,
					 end, prev->vm_pgoff, NULL, prev);
1083 1084
		if (err)
			return NULL;
1085
		khugepaged_enter_vma(prev, vm_flags);
L
Linus Torvalds 已提交
1086 1087 1088 1089 1090 1091 1092
		return prev;
	}

	/*
	 * Can this new request be merged in front of next?
	 */
	if (next && end == next->vm_start &&
V
vishnu.ps 已提交
1093
			mpol_equal(policy, vma_policy(next)) &&
L
Linus Torvalds 已提交
1094
			can_vma_merge_before(next, vm_flags,
1095
					     anon_vma, file, pgoff+pglen,
1096
					     vm_userfaultfd_ctx, anon_name)) {
L
Linus Torvalds 已提交
1097
		if (prev && addr < prev->vm_end)	/* case 4 */
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
			err = __vma_adjust(prev, prev->vm_start,
					 addr, prev->vm_pgoff, NULL, next);
		else {					/* cases 3, 8 */
			err = __vma_adjust(area, addr, next->vm_end,
					 next->vm_pgoff - pglen, NULL, next);
			/*
			 * In case 3 area is already equal to next and
			 * this is a noop, but in case 8 "area" has
			 * been removed and next was expanded over it.
			 */
			area = next;
		}
1110 1111
		if (err)
			return NULL;
1112
		khugepaged_enter_vma(area, vm_flags);
L
Linus Torvalds 已提交
1113 1114 1115 1116 1117 1118
		return area;
	}

	return NULL;
}

1119
/*
1120
 * Rough compatibility check to quickly see if it's even worth looking
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
 * at sharing an anon_vma.
 *
 * They need to have the same vm_file, and the flags can only differ
 * in things that mprotect may change.
 *
 * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
 * we can merge the two vma's. For example, we refuse to merge a vma if
 * there is a vm_ops->close() function, because that indicates that the
 * driver is doing some kind of reference counting. But that doesn't
 * really matter for the anon_vma sharing case.
 */
static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
{
	return a->vm_end == b->vm_start &&
		mpol_equal(vma_policy(a), vma_policy(b)) &&
		a->vm_file == b->vm_file &&
1137
		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1138 1139 1140 1141 1142 1143 1144 1145 1146
		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
}

/*
 * Do some basic sanity checking to see if we can re-use the anon_vma
 * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
 * the same as 'old', the other will be the new one that is trying
 * to share the anon_vma.
 *
1147
 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1148 1149 1150 1151
 * the anon_vma of 'old' is concurrently in the process of being set up
 * by another page fault trying to merge _that_. But that's ok: if it
 * is being set up, that automatically means that it will be a singleton
 * acceptable for merging, so we can do all of this optimistically. But
1152
 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1153 1154 1155 1156 1157 1158 1159 1160
 *
 * IOW: that the "list_is_singular()" test on the anon_vma_chain only
 * matters for the 'stable anon_vma' case (ie the thing we want to avoid
 * is to return an anon_vma that is "complex" due to having gone through
 * a fork).
 *
 * We also make sure that the two vma's are compatible (adjacent,
 * and with the same memory policies). That's all stable, even with just
1161
 * a read lock on the mmap_lock.
1162 1163 1164 1165
 */
static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
{
	if (anon_vma_compatible(a, b)) {
1166
		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1167 1168 1169 1170 1171 1172 1173

		if (anon_vma && list_is_singular(&old->anon_vma_chain))
			return anon_vma;
	}
	return NULL;
}

L
Linus Torvalds 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
/*
 * find_mergeable_anon_vma is used by anon_vma_prepare, to check
 * neighbouring vmas for a suitable anon_vma, before it goes off
 * to allocate a new anon_vma.  It checks because a repetitive
 * sequence of mprotects and faults may otherwise lead to distinct
 * anon_vmas being allocated, preventing vma merge in subsequent
 * mprotect.
 */
struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
{
L
Liam R. Howlett 已提交
1184
	MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1185
	struct anon_vma *anon_vma = NULL;
L
Liam R. Howlett 已提交
1186
	struct vm_area_struct *prev, *next;
1187 1188

	/* Try next first. */
L
Liam R. Howlett 已提交
1189 1190 1191
	next = mas_walk(&mas);
	if (next) {
		anon_vma = reusable_anon_vma(next, vma, next);
1192 1193 1194 1195
		if (anon_vma)
			return anon_vma;
	}

L
Liam R. Howlett 已提交
1196 1197 1198
	prev = mas_prev(&mas, 0);
	VM_BUG_ON_VMA(prev != vma, vma);
	prev = mas_prev(&mas, 0);
1199
	/* Try prev next. */
L
Liam R. Howlett 已提交
1200 1201
	if (prev)
		anon_vma = reusable_anon_vma(prev, prev, vma);
1202

L
Linus Torvalds 已提交
1203
	/*
1204 1205
	 * We might reach here with anon_vma == NULL if we can't find
	 * any reusable anon_vma.
L
Linus Torvalds 已提交
1206 1207 1208 1209 1210 1211 1212
	 * There's no absolute need to look only at touching neighbours:
	 * we could search further afield for "compatible" anon_vmas.
	 * But it would probably just be a waste of time searching,
	 * or lead to too many vmas hanging off the same anon_vma.
	 * We're trying to allow mprotect remerging later on,
	 * not trying to minimize memory used for anon_vmas.
	 */
1213
	return anon_vma;
L
Linus Torvalds 已提交
1214 1215
}

A
Al Viro 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
/*
 * If a hint addr is less than mmap_min_addr change hint to be as
 * low as possible but still greater than mmap_min_addr
 */
static inline unsigned long round_hint_to_min(unsigned long hint)
{
	hint &= PAGE_MASK;
	if (((void *)hint != NULL) &&
	    (hint < mmap_min_addr))
		return PAGE_ALIGN(mmap_min_addr);
	return hint;
}

1229 1230
int mlock_future_check(struct mm_struct *mm, unsigned long flags,
		       unsigned long len)
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
{
	unsigned long locked, lock_limit;

	/*  mlock MCL_FUTURE? */
	if (flags & VM_LOCKED) {
		locked = len >> PAGE_SHIFT;
		locked += mm->locked_vm;
		lock_limit = rlimit(RLIMIT_MEMLOCK);
		lock_limit >>= PAGE_SHIFT;
		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
			return -EAGAIN;
	}
	return 0;
}

1246 1247 1248
static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
{
	if (S_ISREG(inode->i_mode))
1249
		return MAX_LFS_FILESIZE;
1250 1251 1252 1253

	if (S_ISBLK(inode->i_mode))
		return MAX_LFS_FILESIZE;

1254 1255 1256
	if (S_ISSOCK(inode->i_mode))
		return MAX_LFS_FILESIZE;

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
	/* Special "we do even unsigned file positions" case */
	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
		return 0;

	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
	return ULONG_MAX;
}

static inline bool file_mmap_ok(struct file *file, struct inode *inode,
				unsigned long pgoff, unsigned long len)
{
	u64 maxsize = file_mmap_size_max(file, inode);

	if (maxsize && len > maxsize)
		return false;
	maxsize -= len;
	if (pgoff > maxsize >> PAGE_SHIFT)
		return false;
	return true;
}

L
Linus Torvalds 已提交
1278
/*
1279
 * The caller must write-lock current->mm->mmap_lock.
L
Linus Torvalds 已提交
1280
 */
1281
unsigned long do_mmap(struct file *file, unsigned long addr,
L
Linus Torvalds 已提交
1282
			unsigned long len, unsigned long prot,
1283 1284
			unsigned long flags, unsigned long pgoff,
			unsigned long *populate, struct list_head *uf)
L
Linus Torvalds 已提交
1285
{
V
vishnu.ps 已提交
1286
	struct mm_struct *mm = current->mm;
1287
	vm_flags_t vm_flags;
1288
	int pkey = 0;
L
Linus Torvalds 已提交
1289

L
Liam R. Howlett 已提交
1290
	validate_mm(mm);
1291
	*populate = 0;
1292

1293 1294 1295
	if (!len)
		return -EINVAL;

L
Linus Torvalds 已提交
1296 1297 1298 1299 1300 1301 1302
	/*
	 * Does the application expect PROT_READ to imply PROT_EXEC?
	 *
	 * (the exception is when the underlying filesystem is noexec
	 *  mounted, in which case we dont add PROT_EXEC.)
	 */
	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1303
		if (!(file && path_noexec(&file->f_path)))
L
Linus Torvalds 已提交
1304 1305
			prot |= PROT_EXEC;

M
Michal Hocko 已提交
1306 1307 1308 1309
	/* force arch specific MAP_FIXED handling in get_unmapped_area */
	if (flags & MAP_FIXED_NOREPLACE)
		flags |= MAP_FIXED;

1310 1311 1312
	if (!(flags & MAP_FIXED))
		addr = round_hint_to_min(addr);

L
Linus Torvalds 已提交
1313 1314
	/* Careful about overflows.. */
	len = PAGE_ALIGN(len);
1315
	if (!len)
L
Linus Torvalds 已提交
1316 1317 1318 1319
		return -ENOMEM;

	/* offset overflow? */
	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
V
vishnu.ps 已提交
1320
		return -EOVERFLOW;
L
Linus Torvalds 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329

	/* Too many mappings? */
	if (mm->map_count > sysctl_max_map_count)
		return -ENOMEM;

	/* Obtain the address to map to. we verify (or select) it and ensure
	 * that it represents a valid section of the address space.
	 */
	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1330
	if (IS_ERR_VALUE(addr))
L
Linus Torvalds 已提交
1331 1332
		return addr;

M
Michal Hocko 已提交
1333
	if (flags & MAP_FIXED_NOREPLACE) {
1334
		if (find_vma_intersection(mm, addr, addr + len))
M
Michal Hocko 已提交
1335 1336 1337
			return -EEXIST;
	}

1338 1339 1340 1341 1342 1343
	if (prot == PROT_EXEC) {
		pkey = execute_only_pkey(mm);
		if (pkey < 0)
			pkey = 0;
	}

L
Linus Torvalds 已提交
1344 1345 1346 1347
	/* Do simple checking here so the lower-level routines won't have
	 * to. we assume access permissions have been handled by the open
	 * of the memory object, so we don't do any here.
	 */
1348
	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
L
Linus Torvalds 已提交
1349 1350
			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;

H
Huang Shijie 已提交
1351
	if (flags & MAP_LOCKED)
L
Linus Torvalds 已提交
1352 1353
		if (!can_do_mlock())
			return -EPERM;
1354

1355 1356
	if (mlock_future_check(mm, vm_flags, len))
		return -EAGAIN;
L
Linus Torvalds 已提交
1357 1358

	if (file) {
1359
		struct inode *inode = file_inode(file);
1360 1361
		unsigned long flags_mask;

1362 1363 1364
		if (!file_mmap_ok(file, inode, pgoff, len))
			return -EOVERFLOW;

1365
		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1366

L
Linus Torvalds 已提交
1367 1368
		switch (flags & MAP_TYPE) {
		case MAP_SHARED:
1369 1370 1371 1372 1373 1374 1375 1376
			/*
			 * Force use of MAP_SHARED_VALIDATE with non-legacy
			 * flags. E.g. MAP_SYNC is dangerous to use with
			 * MAP_SHARED as you don't know which consistency model
			 * you will get. We silently ignore unsupported flags
			 * with MAP_SHARED to preserve backward compatibility.
			 */
			flags &= LEGACY_MAP_MASK;
J
Joe Perches 已提交
1377
			fallthrough;
1378 1379 1380
		case MAP_SHARED_VALIDATE:
			if (flags & ~flags_mask)
				return -EOPNOTSUPP;
1381 1382 1383 1384 1385 1386
			if (prot & PROT_WRITE) {
				if (!(file->f_mode & FMODE_WRITE))
					return -EACCES;
				if (IS_SWAPFILE(file->f_mapping->host))
					return -ETXTBSY;
			}
L
Linus Torvalds 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

			/*
			 * Make sure we don't allow writing to an append-only
			 * file..
			 */
			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
				return -EACCES;

			vm_flags |= VM_SHARED | VM_MAYSHARE;
			if (!(file->f_mode & FMODE_WRITE))
				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
J
Joe Perches 已提交
1398
			fallthrough;
L
Linus Torvalds 已提交
1399 1400 1401
		case MAP_PRIVATE:
			if (!(file->f_mode & FMODE_READ))
				return -EACCES;
1402
			if (path_noexec(&file->f_path)) {
L
Linus Torvalds 已提交
1403 1404 1405 1406 1407
				if (vm_flags & VM_EXEC)
					return -EPERM;
				vm_flags &= ~VM_MAYEXEC;
			}

A
Al Viro 已提交
1408
			if (!file->f_op->mmap)
L
Linus Torvalds 已提交
1409
				return -ENODEV;
1410 1411
			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
				return -EINVAL;
L
Linus Torvalds 已提交
1412 1413 1414 1415 1416 1417 1418 1419
			break;

		default:
			return -EINVAL;
		}
	} else {
		switch (flags & MAP_TYPE) {
		case MAP_SHARED:
1420 1421
			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
				return -EINVAL;
1422 1423 1424 1425
			/*
			 * Ignore pgoff.
			 */
			pgoff = 0;
L
Linus Torvalds 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
			vm_flags |= VM_SHARED | VM_MAYSHARE;
			break;
		case MAP_PRIVATE:
			/*
			 * Set pgoff according to addr for anon_vma.
			 */
			pgoff = addr >> PAGE_SHIFT;
			break;
		default:
			return -EINVAL;
		}
	}

1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
	/*
	 * Set 'VM_NORESERVE' if we should not account for the
	 * memory use of this mapping.
	 */
	if (flags & MAP_NORESERVE) {
		/* We honor MAP_NORESERVE if allowed to overcommit */
		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
			vm_flags |= VM_NORESERVE;

		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
		if (file && is_file_hugepages(file))
			vm_flags |= VM_NORESERVE;
	}

1453
	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1454 1455 1456
	if (!IS_ERR_VALUE(addr) &&
	    ((vm_flags & VM_LOCKED) ||
	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1457
		*populate = len;
1458
	return addr;
M
Miklos Szeredi 已提交
1459
}
1460

1461 1462 1463
unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
			      unsigned long prot, unsigned long flags,
			      unsigned long fd, unsigned long pgoff)
H
Hugh Dickins 已提交
1464 1465
{
	struct file *file = NULL;
1466
	unsigned long retval;
H
Hugh Dickins 已提交
1467 1468

	if (!(flags & MAP_ANONYMOUS)) {
A
Al Viro 已提交
1469
		audit_mmap_fd(fd, flags);
H
Hugh Dickins 已提交
1470 1471
		file = fget(fd);
		if (!file)
1472
			return -EBADF;
1473
		if (is_file_hugepages(file)) {
1474
			len = ALIGN(len, huge_page_size(hstate_file(file)));
1475 1476
		} else if (unlikely(flags & MAP_HUGETLB)) {
			retval = -EINVAL;
1477
			goto out_fput;
1478
		}
H
Hugh Dickins 已提交
1479
	} else if (flags & MAP_HUGETLB) {
1480
		struct hstate *hs;
1481

1482
		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1483 1484 1485 1486
		if (!hs)
			return -EINVAL;

		len = ALIGN(len, huge_page_size(hs));
H
Hugh Dickins 已提交
1487 1488 1489 1490
		/*
		 * VM_NORESERVE is used because the reservations will be
		 * taken when vm_ops->mmap() is called
		 */
1491
		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1492
				VM_NORESERVE,
1493
				HUGETLB_ANONHUGE_INODE,
1494
				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
H
Hugh Dickins 已提交
1495 1496 1497 1498
		if (IS_ERR(file))
			return PTR_ERR(file);
	}

M
Michal Hocko 已提交
1499
	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1500
out_fput:
H
Hugh Dickins 已提交
1501 1502 1503 1504 1505
	if (file)
		fput(file);
	return retval;
}

1506 1507 1508 1509 1510 1511 1512
SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
		unsigned long, prot, unsigned long, flags,
		unsigned long, fd, unsigned long, pgoff)
{
	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
}

C
Christoph Hellwig 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
#ifdef __ARCH_WANT_SYS_OLD_MMAP
struct mmap_arg_struct {
	unsigned long addr;
	unsigned long len;
	unsigned long prot;
	unsigned long flags;
	unsigned long fd;
	unsigned long offset;
};

SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
{
	struct mmap_arg_struct a;

	if (copy_from_user(&a, arg, sizeof(a)))
		return -EFAULT;
1529
	if (offset_in_page(a.offset))
C
Christoph Hellwig 已提交
1530 1531
		return -EINVAL;

1532 1533
	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
			       a.offset >> PAGE_SHIFT);
C
Christoph Hellwig 已提交
1534 1535 1536
}
#endif /* __ARCH_WANT_SYS_OLD_MMAP */

A
Alexey Dobriyan 已提交
1537
/*
W
Wei Yang 已提交
1538
 * Some shared mappings will want the pages marked read-only
A
Alexey Dobriyan 已提交
1539 1540 1541 1542
 * to track write events. If so, we'll downgrade vm_page_prot
 * to the private version (using protection_map[] without the
 * VM_SHARED bit).
 */
1543
int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
A
Alexey Dobriyan 已提交
1544
{
1545
	vm_flags_t vm_flags = vma->vm_flags;
1546
	const struct vm_operations_struct *vm_ops = vma->vm_ops;
A
Alexey Dobriyan 已提交
1547 1548 1549 1550 1551 1552

	/* If it was private or non-writable, the write bit is already clear */
	if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
		return 0;

	/* The backer wishes to know when pages are first written to? */
1553
	if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
A
Alexey Dobriyan 已提交
1554 1555
		return 1;

1556 1557
	/* The open routine did something to the protections that pgprot_modify
	 * won't preserve? */
1558 1559
	if (pgprot_val(vm_page_prot) !=
	    pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
A
Alexey Dobriyan 已提交
1560 1561
		return 0;

1562 1563 1564 1565 1566
	/*
	 * Do we need to track softdirty? hugetlb does not support softdirty
	 * tracking yet.
	 */
	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1567 1568
		return 1;

A
Alexey Dobriyan 已提交
1569
	/* Specialty mapping? */
1570
	if (vm_flags & VM_PFNMAP)
A
Alexey Dobriyan 已提交
1571 1572 1573 1574
		return 0;

	/* Can the mapping track the dirty pages? */
	return vma->vm_file && vma->vm_file->f_mapping &&
1575
		mapping_can_writeback(vma->vm_file->f_mapping);
A
Alexey Dobriyan 已提交
1576 1577
}

1578 1579
/*
 * We account for memory if it's a private writeable mapping,
1580
 * not hugepages and VM_NORESERVE wasn't set.
1581
 */
1582
static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1583
{
1584 1585 1586 1587 1588 1589 1590
	/*
	 * hugetlb has its own accounting separate from the core VM
	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
	 */
	if (file && is_file_hugepages(file))
		return 0;

1591 1592 1593
	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
}

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
/**
 * unmapped_area() - Find an area between the low_limit and the high_limit with
 * the correct alignment and offset, all from @info. Note: current->mm is used
 * for the search.
 *
 * @info: The unmapped area information including the range (low_limit -
 * hight_limit), the alignment offset and mask.
 *
 * Return: A memory address or -ENOMEM.
 */
1604
static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1605
{
1606
	unsigned long length, gap;
1607

1608
	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1609 1610 1611 1612 1613 1614

	/* Adjust search length to account for worst case alignment overhead */
	length = info->length + info->align_mask;
	if (length < info->length)
		return -ENOMEM;

1615 1616
	if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
				  length))
1617 1618
		return -ENOMEM;

1619 1620 1621
	gap = mas.index;
	gap += (info->align_offset - gap) & info->align_mask;
	return gap;
1622 1623
}

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
/**
 * unmapped_area_topdown() - Find an area between the low_limit and the
 * high_limit with * the correct alignment and offset at the highest available
 * address, all from @info. Note: current->mm is used for the search.
 *
 * @info: The unmapped area information including the range (low_limit -
 * hight_limit), the alignment offset and mask.
 *
 * Return: A memory address or -ENOMEM.
 */
1634
static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1635
{
1636
	unsigned long length, gap;
1637

1638
	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1639 1640 1641 1642 1643
	/* Adjust search length to account for worst case alignment overhead */
	length = info->length + info->align_mask;
	if (length < info->length)
		return -ENOMEM;

1644 1645
	if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
				length))
1646 1647
		return -ENOMEM;

1648 1649 1650
	gap = mas.last + 1 - info->length;
	gap -= (gap - info->align_offset) & info->align_mask;
	return gap;
1651 1652
}

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
/*
 * Search for an unmapped address range.
 *
 * We are looking for a range that:
 * - does not intersect with any VMA;
 * - is contained within the [low_limit, high_limit) interval;
 * - is at least the desired size.
 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
 */
unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
{
1664 1665
	unsigned long addr;

1666
	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1667
		addr = unmapped_area_topdown(info);
1668
	else
1669 1670 1671 1672
		addr = unmapped_area(info);

	trace_vm_unmapped_area(addr, info);
	return addr;
1673
}
1674

L
Linus Torvalds 已提交
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
/* Get an address range which is currently unmapped.
 * For shmat() with addr=0.
 *
 * Ugly calling convention alert:
 * Return value with the low bits set means error value,
 * ie
 *	if (ret & ~PAGE_MASK)
 *		error = ret;
 *
 * This function "knows" that -ENOMEM has the bits set.
 */
unsigned long
1687 1688 1689
generic_get_unmapped_area(struct file *filp, unsigned long addr,
			  unsigned long len, unsigned long pgoff,
			  unsigned long flags)
L
Linus Torvalds 已提交
1690 1691
{
	struct mm_struct *mm = current->mm;
1692
	struct vm_area_struct *vma, *prev;
1693
	struct vm_unmapped_area_info info;
1694
	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
L
Linus Torvalds 已提交
1695

1696
	if (len > mmap_end - mmap_min_addr)
L
Linus Torvalds 已提交
1697 1698
		return -ENOMEM;

1699 1700 1701
	if (flags & MAP_FIXED)
		return addr;

L
Linus Torvalds 已提交
1702 1703
	if (addr) {
		addr = PAGE_ALIGN(addr);
1704
		vma = find_vma_prev(mm, addr, &prev);
1705
		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1706 1707
		    (!vma || addr + len <= vm_start_gap(vma)) &&
		    (!prev || addr >= vm_end_gap(prev)))
L
Linus Torvalds 已提交
1708 1709 1710
			return addr;
	}

1711 1712
	info.flags = 0;
	info.length = len;
1713
	info.low_limit = mm->mmap_base;
1714
	info.high_limit = mmap_end;
1715
	info.align_mask = 0;
1716
	info.align_offset = 0;
1717
	return vm_unmapped_area(&info);
L
Linus Torvalds 已提交
1718
}
1719 1720 1721 1722 1723 1724 1725 1726 1727

#ifndef HAVE_ARCH_UNMAPPED_AREA
unsigned long
arch_get_unmapped_area(struct file *filp, unsigned long addr,
		       unsigned long len, unsigned long pgoff,
		       unsigned long flags)
{
	return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
}
V
vishnu.ps 已提交
1728
#endif
L
Linus Torvalds 已提交
1729 1730 1731 1732 1733 1734

/*
 * This mmap-allocator allocates new areas top-down from below the
 * stack's low limit (the base):
 */
unsigned long
1735 1736 1737
generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
				  unsigned long len, unsigned long pgoff,
				  unsigned long flags)
L
Linus Torvalds 已提交
1738
{
1739
	struct vm_area_struct *vma, *prev;
L
Linus Torvalds 已提交
1740
	struct mm_struct *mm = current->mm;
1741
	struct vm_unmapped_area_info info;
1742
	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
L
Linus Torvalds 已提交
1743 1744

	/* requested length too big for entire address space */
1745
	if (len > mmap_end - mmap_min_addr)
L
Linus Torvalds 已提交
1746 1747
		return -ENOMEM;

1748 1749 1750
	if (flags & MAP_FIXED)
		return addr;

L
Linus Torvalds 已提交
1751 1752 1753
	/* requesting a specific address */
	if (addr) {
		addr = PAGE_ALIGN(addr);
1754
		vma = find_vma_prev(mm, addr, &prev);
1755
		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1756 1757
				(!vma || addr + len <= vm_start_gap(vma)) &&
				(!prev || addr >= vm_end_gap(prev)))
L
Linus Torvalds 已提交
1758 1759 1760
			return addr;
	}

1761 1762
	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
	info.length = len;
1763
	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1764
	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1765
	info.align_mask = 0;
1766
	info.align_offset = 0;
1767
	addr = vm_unmapped_area(&info);
1768

L
Linus Torvalds 已提交
1769 1770 1771 1772 1773 1774
	/*
	 * A failed mmap() very likely causes application failure,
	 * so fall back to the bottom-up function here. This scenario
	 * can happen with large stack limits and large mmap()
	 * allocations.
	 */
1775
	if (offset_in_page(addr)) {
1776 1777 1778
		VM_BUG_ON(addr != -ENOMEM);
		info.flags = 0;
		info.low_limit = TASK_UNMAPPED_BASE;
1779
		info.high_limit = mmap_end;
1780 1781
		addr = vm_unmapped_area(&info);
	}
L
Linus Torvalds 已提交
1782 1783 1784

	return addr;
}
1785 1786 1787 1788 1789 1790 1791 1792 1793

#ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
unsigned long
arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
			       unsigned long len, unsigned long pgoff,
			       unsigned long flags)
{
	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
}
L
Linus Torvalds 已提交
1794 1795 1796 1797 1798 1799
#endif

unsigned long
get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
		unsigned long pgoff, unsigned long flags)
{
1800 1801 1802
	unsigned long (*get_area)(struct file *, unsigned long,
				  unsigned long, unsigned long, unsigned long);

1803 1804 1805 1806 1807 1808 1809 1810
	unsigned long error = arch_mmap_check(addr, len, flags);
	if (error)
		return error;

	/* Careful about overflows.. */
	if (len > TASK_SIZE)
		return -ENOMEM;

1811
	get_area = current->mm->get_unmapped_area;
1812 1813 1814 1815 1816 1817 1818
	if (file) {
		if (file->f_op->get_unmapped_area)
			get_area = file->f_op->get_unmapped_area;
	} else if (flags & MAP_SHARED) {
		/*
		 * mmap_region() will call shmem_zero_setup() to create a file,
		 * so use shmem's get_unmapped_area in case it can be huge.
1819
		 * do_mmap() will clear pgoff, so match alignment.
1820 1821 1822
		 */
		pgoff = 0;
		get_area = shmem_get_unmapped_area;
1823 1824 1825
	} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
		/* Ensures that larger anonymous mappings are THP aligned. */
		get_area = thp_get_unmapped_area;
1826 1827
	}

1828 1829 1830
	addr = get_area(file, addr, len, pgoff, flags);
	if (IS_ERR_VALUE(addr))
		return addr;
L
Linus Torvalds 已提交
1831

1832 1833
	if (addr > TASK_SIZE - len)
		return -ENOMEM;
1834
	if (offset_in_page(addr))
1835
		return -EINVAL;
1836

1837 1838
	error = security_mmap_addr(addr);
	return error ? error : addr;
L
Linus Torvalds 已提交
1839 1840 1841 1842
}

EXPORT_SYMBOL(get_unmapped_area);

1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
/**
 * find_vma_intersection() - Look up the first VMA which intersects the interval
 * @mm: The process address space.
 * @start_addr: The inclusive start user address.
 * @end_addr: The exclusive end user address.
 *
 * Returns: The first VMA within the provided range, %NULL otherwise.  Assumes
 * start_addr < end_addr.
 */
struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
					     unsigned long start_addr,
					     unsigned long end_addr)
{
	unsigned long index = start_addr;

	mmap_assert_locked(mm);
L
Liam R. Howlett 已提交
1859
	return mt_find(&mm->mm_mt, &index, end_addr - 1);
1860 1861 1862
}
EXPORT_SYMBOL(find_vma_intersection);

1863 1864 1865 1866 1867 1868 1869 1870
/**
 * find_vma() - Find the VMA for a given address, or the next VMA.
 * @mm: The mm_struct to check
 * @addr: The address
 *
 * Returns: The VMA associated with addr, or the next VMA.
 * May return %NULL in the case of no VMA at addr or above.
 */
Z
ZhenwenXu 已提交
1871
struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
L
Linus Torvalds 已提交
1872
{
1873
	unsigned long index = addr;
L
Linus Torvalds 已提交
1874

1875
	mmap_assert_locked(mm);
L
Liam R. Howlett 已提交
1876
	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
L
Linus Torvalds 已提交
1877 1878 1879
}
EXPORT_SYMBOL(find_vma);

1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
/**
 * find_vma_prev() - Find the VMA for a given address, or the next vma and
 * set %pprev to the previous VMA, if any.
 * @mm: The mm_struct to check
 * @addr: The address
 * @pprev: The pointer to set to the previous VMA
 *
 * Note that RCU lock is missing here since the external mmap_lock() is used
 * instead.
 *
 * Returns: The VMA associated with @addr, or the next vma.
 * May return %NULL in the case of no vma at addr or above.
K
KOSAKI Motohiro 已提交
1892
 */
L
Linus Torvalds 已提交
1893 1894 1895 1896
struct vm_area_struct *
find_vma_prev(struct mm_struct *mm, unsigned long addr,
			struct vm_area_struct **pprev)
{
K
KOSAKI Motohiro 已提交
1897
	struct vm_area_struct *vma;
1898
	MA_STATE(mas, &mm->mm_mt, addr, addr);
L
Linus Torvalds 已提交
1899

1900 1901 1902 1903
	vma = mas_walk(&mas);
	*pprev = mas_prev(&mas, 0);
	if (!vma)
		vma = mas_next(&mas, ULONG_MAX);
K
KOSAKI Motohiro 已提交
1904
	return vma;
L
Linus Torvalds 已提交
1905 1906 1907 1908 1909 1910 1911
}

/*
 * Verify that the stack growth is acceptable and
 * update accounting. This is shared with both the
 * grow-up and grow-down cases.
 */
1912 1913
static int acct_stack_growth(struct vm_area_struct *vma,
			     unsigned long size, unsigned long grow)
L
Linus Torvalds 已提交
1914 1915
{
	struct mm_struct *mm = vma->vm_mm;
1916
	unsigned long new_start;
L
Linus Torvalds 已提交
1917 1918

	/* address space limit tests */
1919
	if (!may_expand_vm(mm, vma->vm_flags, grow))
L
Linus Torvalds 已提交
1920 1921 1922
		return -ENOMEM;

	/* Stack limit test */
1923
	if (size > rlimit(RLIMIT_STACK))
L
Linus Torvalds 已提交
1924 1925 1926
		return -ENOMEM;

	/* mlock limit tests */
1927 1928
	if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
		return -ENOMEM;
L
Linus Torvalds 已提交
1929

1930 1931 1932 1933 1934 1935
	/* Check to ensure the stack will not grow into a hugetlb-only region */
	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
			vma->vm_end - size;
	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
		return -EFAULT;

L
Linus Torvalds 已提交
1936 1937 1938 1939
	/*
	 * Overcommit..  This must be the final test, as it will
	 * update security statistics.
	 */
1940
	if (security_vm_enough_memory_mm(mm, grow))
L
Linus Torvalds 已提交
1941 1942 1943 1944 1945
		return -ENOMEM;

	return 0;
}

H
Hugh Dickins 已提交
1946
#if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
L
Linus Torvalds 已提交
1947
/*
H
Hugh Dickins 已提交
1948 1949
 * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
 * vma is the last one with address > vma->vm_end.  Have to extend vma.
L
Linus Torvalds 已提交
1950
 */
H
Hugh Dickins 已提交
1951
int expand_upwards(struct vm_area_struct *vma, unsigned long address)
L
Linus Torvalds 已提交
1952
{
1953
	struct mm_struct *mm = vma->vm_mm;
1954 1955
	struct vm_area_struct *next;
	unsigned long gap_addr;
1956
	int error = 0;
1957
	MA_STATE(mas, &mm->mm_mt, 0, 0);
L
Linus Torvalds 已提交
1958 1959 1960 1961

	if (!(vma->vm_flags & VM_GROWSUP))
		return -EFAULT;

1962
	/* Guard against exceeding limits of the address space. */
1963
	address &= PAGE_MASK;
1964
	if (address >= (TASK_SIZE & PAGE_MASK))
1965
		return -ENOMEM;
1966
	address += PAGE_SIZE;
1967

1968 1969
	/* Enforce stack_guard_gap */
	gap_addr = address + stack_guard_gap;
1970 1971 1972 1973 1974

	/* Guard against overflow */
	if (gap_addr < address || gap_addr > TASK_SIZE)
		gap_addr = TASK_SIZE;

L
Liam R. Howlett 已提交
1975 1976
	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
	if (next && vma_is_accessible(next)) {
1977 1978 1979 1980 1981
		if (!(next->vm_flags & VM_GROWSUP))
			return -ENOMEM;
		/* Check that both stack segments have the same anon_vma? */
	}

1982 1983 1984
	if (mas_preallocate(&mas, vma, GFP_KERNEL))
		return -ENOMEM;

1985
	/* We must make sure the anon_vma is allocated. */
1986 1987
	if (unlikely(anon_vma_prepare(vma))) {
		mas_destroy(&mas);
L
Linus Torvalds 已提交
1988
		return -ENOMEM;
1989
	}
L
Linus Torvalds 已提交
1990 1991 1992

	/*
	 * vma->vm_start/vm_end cannot change under us because the caller
1993
	 * is required to hold the mmap_lock in read mode.  We need the
L
Linus Torvalds 已提交
1994 1995
	 * anon_vma lock to serialize against concurrent expand_stacks.
	 */
1996
	anon_vma_lock_write(vma->anon_vma);
L
Linus Torvalds 已提交
1997 1998 1999 2000 2001 2002 2003 2004

	/* Somebody else might have raced and expanded it already */
	if (address > vma->vm_end) {
		unsigned long size, grow;

		size = address - vma->vm_start;
		grow = (address - vma->vm_end) >> PAGE_SHIFT;

2005 2006 2007 2008
		error = -ENOMEM;
		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
			error = acct_stack_growth(vma, size, grow);
			if (!error) {
2009
				/*
L
Liam R. Howlett 已提交
2010 2011 2012 2013 2014 2015 2016
				 * We only hold a shared mmap_lock lock here, so
				 * we need to protect against concurrent vma
				 * expansions.  anon_vma_lock_write() doesn't
				 * help here, as we don't guarantee that all
				 * growable vmas in a mm share the same root
				 * anon vma.  So, we reuse mm->page_table_lock
				 * to guard against concurrent vma expansions.
2017
				 */
2018
				spin_lock(&mm->page_table_lock);
2019
				if (vma->vm_flags & VM_LOCKED)
2020
					mm->locked_vm += grow;
2021
				vm_stat_account(mm, vma->vm_flags, grow);
2022
				anon_vma_interval_tree_pre_update_vma(vma);
2023
				vma->vm_end = address;
2024 2025
				/* Overwrite old entry in mtree. */
				vma_mas_store(vma, &mas);
2026
				anon_vma_interval_tree_post_update_vma(vma);
2027
				spin_unlock(&mm->page_table_lock);
2028

2029 2030
				perf_event_mmap(vma);
			}
2031
		}
L
Linus Torvalds 已提交
2032
	}
2033
	anon_vma_unlock_write(vma->anon_vma);
2034
	khugepaged_enter_vma(vma, vma->vm_flags);
2035
	mas_destroy(&mas);
L
Linus Torvalds 已提交
2036 2037
	return error;
}
H
Hugh Dickins 已提交
2038 2039
#endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */

L
Linus Torvalds 已提交
2040 2041 2042
/*
 * vma is the first one with address < vma->vm_start.  Have to extend vma.
 */
L
Liam R. Howlett 已提交
2043
int expand_downwards(struct vm_area_struct *vma, unsigned long address)
L
Linus Torvalds 已提交
2044
{
2045
	struct mm_struct *mm = vma->vm_mm;
L
Liam R. Howlett 已提交
2046
	MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
2047
	struct vm_area_struct *prev;
2048
	int error = 0;
L
Linus Torvalds 已提交
2049

2050
	address &= PAGE_MASK;
2051 2052
	if (address < mmap_min_addr)
		return -EPERM;
2053

2054
	/* Enforce stack_guard_gap */
L
Liam R. Howlett 已提交
2055
	prev = mas_prev(&mas, 0);
2056 2057
	/* Check that both stack segments have the same anon_vma? */
	if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2058
			vma_is_accessible(prev)) {
2059
		if (address - prev->vm_end < stack_guard_gap)
2060 2061 2062
			return -ENOMEM;
	}

2063 2064 2065
	if (mas_preallocate(&mas, vma, GFP_KERNEL))
		return -ENOMEM;

2066
	/* We must make sure the anon_vma is allocated. */
2067 2068
	if (unlikely(anon_vma_prepare(vma))) {
		mas_destroy(&mas);
2069
		return -ENOMEM;
2070
	}
L
Linus Torvalds 已提交
2071 2072 2073

	/*
	 * vma->vm_start/vm_end cannot change under us because the caller
2074
	 * is required to hold the mmap_lock in read mode.  We need the
L
Linus Torvalds 已提交
2075 2076
	 * anon_vma lock to serialize against concurrent expand_stacks.
	 */
2077
	anon_vma_lock_write(vma->anon_vma);
L
Linus Torvalds 已提交
2078 2079 2080 2081 2082 2083 2084 2085

	/* Somebody else might have raced and expanded it already */
	if (address < vma->vm_start) {
		unsigned long size, grow;

		size = vma->vm_end - address;
		grow = (vma->vm_start - address) >> PAGE_SHIFT;

2086 2087 2088 2089
		error = -ENOMEM;
		if (grow <= vma->vm_pgoff) {
			error = acct_stack_growth(vma, size, grow);
			if (!error) {
2090
				/*
L
Liam R. Howlett 已提交
2091 2092 2093 2094 2095 2096 2097
				 * We only hold a shared mmap_lock lock here, so
				 * we need to protect against concurrent vma
				 * expansions.  anon_vma_lock_write() doesn't
				 * help here, as we don't guarantee that all
				 * growable vmas in a mm share the same root
				 * anon vma.  So, we reuse mm->page_table_lock
				 * to guard against concurrent vma expansions.
2098
				 */
2099
				spin_lock(&mm->page_table_lock);
2100
				if (vma->vm_flags & VM_LOCKED)
2101
					mm->locked_vm += grow;
2102
				vm_stat_account(mm, vma->vm_flags, grow);
2103
				anon_vma_interval_tree_pre_update_vma(vma);
2104 2105
				vma->vm_start = address;
				vma->vm_pgoff -= grow;
2106 2107
				/* Overwrite old entry in mtree. */
				vma_mas_store(vma, &mas);
2108
				anon_vma_interval_tree_post_update_vma(vma);
2109
				spin_unlock(&mm->page_table_lock);
2110

2111 2112
				perf_event_mmap(vma);
			}
L
Linus Torvalds 已提交
2113 2114
		}
	}
2115
	anon_vma_unlock_write(vma->anon_vma);
2116
	khugepaged_enter_vma(vma, vma->vm_flags);
2117
	mas_destroy(&mas);
L
Linus Torvalds 已提交
2118 2119 2120
	return error;
}

2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
/* enforced gap between the expanding stack and other mappings. */
unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;

static int __init cmdline_parse_stack_guard_gap(char *p)
{
	unsigned long val;
	char *endptr;

	val = simple_strtoul(p, &endptr, 10);
	if (!*endptr)
		stack_guard_gap = val << PAGE_SHIFT;

2133
	return 1;
2134 2135 2136
}
__setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);

2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
#ifdef CONFIG_STACK_GROWSUP
int expand_stack(struct vm_area_struct *vma, unsigned long address)
{
	return expand_upwards(vma, address);
}

struct vm_area_struct *
find_extend_vma(struct mm_struct *mm, unsigned long addr)
{
	struct vm_area_struct *vma, *prev;

	addr &= PAGE_MASK;
	vma = find_vma_prev(mm, addr, &prev);
	if (vma && (vma->vm_start <= addr))
		return vma;
2152
	if (!prev || expand_stack(prev, addr))
2153
		return NULL;
2154
	if (prev->vm_flags & VM_LOCKED)
2155
		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2156 2157 2158 2159 2160 2161 2162 2163
	return prev;
}
#else
int expand_stack(struct vm_area_struct *vma, unsigned long address)
{
	return expand_downwards(vma, address);
}

L
Linus Torvalds 已提交
2164
struct vm_area_struct *
V
vishnu.ps 已提交
2165
find_extend_vma(struct mm_struct *mm, unsigned long addr)
L
Linus Torvalds 已提交
2166
{
V
vishnu.ps 已提交
2167
	struct vm_area_struct *vma;
L
Linus Torvalds 已提交
2168 2169 2170
	unsigned long start;

	addr &= PAGE_MASK;
V
vishnu.ps 已提交
2171
	vma = find_vma(mm, addr);
L
Linus Torvalds 已提交
2172 2173 2174 2175 2176 2177 2178 2179 2180
	if (!vma)
		return NULL;
	if (vma->vm_start <= addr)
		return vma;
	if (!(vma->vm_flags & VM_GROWSDOWN))
		return NULL;
	start = vma->vm_start;
	if (expand_stack(vma, addr))
		return NULL;
2181
	if (vma->vm_flags & VM_LOCKED)
2182
		populate_vma_page_range(vma, addr, start, NULL);
L
Linus Torvalds 已提交
2183 2184 2185 2186
	return vma;
}
#endif

2187 2188
EXPORT_SYMBOL_GPL(find_extend_vma);

L
Linus Torvalds 已提交
2189
/*
L
Liam R. Howlett 已提交
2190 2191
 * Ok - we have the memory areas we should free on a maple tree so release them,
 * and do the vma updates.
2192 2193
 *
 * Called with the mm semaphore held.
L
Linus Torvalds 已提交
2194
 */
L
Liam R. Howlett 已提交
2195
static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
L
Linus Torvalds 已提交
2196
{
2197
	unsigned long nr_accounted = 0;
L
Liam R. Howlett 已提交
2198
	struct vm_area_struct *vma;
2199

2200 2201
	/* Update high watermark before we lower total_vm */
	update_hiwater_vm(mm);
L
Liam R. Howlett 已提交
2202
	mas_for_each(mas, vma, ULONG_MAX) {
2203 2204
		long nrpages = vma_pages(vma);

2205 2206
		if (vma->vm_flags & VM_ACCOUNT)
			nr_accounted += nrpages;
2207
		vm_stat_account(mm, vma->vm_flags, -nrpages);
L
Liam R. Howlett 已提交
2208 2209
		remove_vma(vma);
	}
2210
	vm_unacct_memory(nr_accounted);
L
Linus Torvalds 已提交
2211 2212 2213 2214 2215 2216
	validate_mm(mm);
}

/*
 * Get rid of page table information in the indicated region.
 *
2217
 * Called with the mm semaphore held.
L
Linus Torvalds 已提交
2218
 */
L
Liam R. Howlett 已提交
2219
static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
2220
		struct vm_area_struct *vma, struct vm_area_struct *prev,
L
Liam R. Howlett 已提交
2221
		struct vm_area_struct *next,
2222
		unsigned long start, unsigned long end)
L
Linus Torvalds 已提交
2223
{
P
Peter Zijlstra 已提交
2224
	struct mmu_gather tlb;
L
Linus Torvalds 已提交
2225 2226

	lru_add_drain();
2227
	tlb_gather_mmu(&tlb, mm);
2228
	update_hiwater_rss(mm);
L
Liam R. Howlett 已提交
2229 2230
	unmap_vmas(&tlb, mt, vma, start, end);
	free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2231
				 next ? next->vm_start : USER_PGTABLES_CEILING);
2232
	tlb_finish_mmu(&tlb);
L
Linus Torvalds 已提交
2233 2234 2235
}

/*
2236 2237
 * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
 * has already been checked or doesn't make sense to fail.
L
Linus Torvalds 已提交
2238
 */
2239 2240
int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
		unsigned long addr, int new_below)
L
Linus Torvalds 已提交
2241 2242
{
	struct vm_area_struct *new;
2243
	int err;
2244
	validate_mm_mt(mm);
L
Linus Torvalds 已提交
2245

2246 2247
	if (vma->vm_ops && vma->vm_ops->may_split) {
		err = vma->vm_ops->may_split(vma, addr);
2248 2249 2250
		if (err)
			return err;
	}
L
Linus Torvalds 已提交
2251

2252
	new = vm_area_dup(vma);
L
Linus Torvalds 已提交
2253
	if (!new)
2254
		return -ENOMEM;
L
Linus Torvalds 已提交
2255 2256 2257 2258 2259 2260 2261 2262

	if (new_below)
		new->vm_end = addr;
	else {
		new->vm_start = addr;
		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
	}

2263 2264
	err = vma_dup_policy(vma, new);
	if (err)
2265
		goto out_free_vma;
L
Linus Torvalds 已提交
2266

2267 2268
	err = anon_vma_clone(new, vma);
	if (err)
2269 2270
		goto out_free_mpol;

2271
	if (new->vm_file)
L
Linus Torvalds 已提交
2272 2273 2274 2275 2276 2277
		get_file(new->vm_file);

	if (new->vm_ops && new->vm_ops->open)
		new->vm_ops->open(new);

	if (new_below)
2278
		err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
L
Linus Torvalds 已提交
2279 2280
			((addr - new->vm_start) >> PAGE_SHIFT), new);
	else
2281
		err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
L
Linus Torvalds 已提交
2282

2283 2284 2285 2286
	/* Success. */
	if (!err)
		return 0;

2287 2288 2289
	/* Avoid vm accounting in close() operation */
	new->vm_start = new->vm_end;
	new->vm_pgoff = 0;
2290
	/* Clean everything up if vma_adjust failed. */
2291 2292
	if (new->vm_ops && new->vm_ops->close)
		new->vm_ops->close(new);
2293
	if (new->vm_file)
2294
		fput(new->vm_file);
2295
	unlink_anon_vmas(new);
2296
 out_free_mpol:
2297
	mpol_put(vma_policy(new));
2298
 out_free_vma:
2299
	vm_area_free(new);
2300
	validate_mm_mt(mm);
2301
	return err;
L
Linus Torvalds 已提交
2302 2303
}

2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
/*
 * Split a vma into two pieces at address 'addr', a new vma is allocated
 * either for the first part or the tail.
 */
int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
	      unsigned long addr, int new_below)
{
	if (mm->map_count >= sysctl_max_map_count)
		return -ENOMEM;

	return __split_vma(mm, vma, addr, new_below);
}

L
Liam R. Howlett 已提交
2317 2318
static inline int munmap_sidetree(struct vm_area_struct *vma,
				   struct ma_state *mas_detach)
L
Linus Torvalds 已提交
2319
{
L
Liam R. Howlett 已提交
2320 2321 2322
	mas_set_range(mas_detach, vma->vm_start, vma->vm_end - 1);
	if (mas_store_gfp(mas_detach, vma, GFP_KERNEL))
		return -ENOMEM;
L
Linus Torvalds 已提交
2323

L
Liam R. Howlett 已提交
2324 2325
	if (vma->vm_flags & VM_LOCKED)
		vma->vm_mm->locked_vm -= vma_pages(vma);
L
Linus Torvalds 已提交
2326

L
Liam R. Howlett 已提交
2327
	return 0;
2328
}
2329

2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
/*
 * do_mas_align_munmap() - munmap the aligned region from @start to @end.
 * @mas: The maple_state, ideally set up to alter the correct tree location.
 * @vma: The starting vm_area_struct
 * @mm: The mm_struct
 * @start: The aligned start address to munmap.
 * @end: The aligned end address to munmap.
 * @uf: The userfaultfd list_head
 * @downgrade: Set to true to attempt a write downgrade of the mmap_sem
 *
 * If @downgrade is true, check return code for potential release of the lock.
 */
static int
do_mas_align_munmap(struct ma_state *mas, struct vm_area_struct *vma,
		    struct mm_struct *mm, unsigned long start,
		    unsigned long end, struct list_head *uf, bool downgrade)
{
L
Liam R. Howlett 已提交
2347 2348 2349
	struct vm_area_struct *prev, *next = NULL;
	struct maple_tree mt_detach;
	int count = 0;
2350
	int error = -ENOMEM;
L
Liam R. Howlett 已提交
2351 2352 2353
	MA_STATE(mas_detach, &mt_detach, 0, 0);
	mt_init_flags(&mt_detach, MT_FLAGS_LOCK_EXTERN);
	mt_set_external_lock(&mt_detach, &mm->mmap_lock);
2354

2355
	if (mas_preallocate(mas, vma, GFP_KERNEL))
2356
		return -ENOMEM;
L
Liam R. Howlett 已提交
2357

2358
	mas->last = end - 1;
L
Linus Torvalds 已提交
2359 2360 2361 2362 2363 2364 2365
	/*
	 * If we need to split any vma, do it now to save pain later.
	 *
	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
	 * unmapped vm_area_struct will remain in use: so lower split_vma
	 * places tmp vma above, and higher split_vma places tmp vma below.
	 */
L
Liam R. Howlett 已提交
2366 2367

	/* Does it split the first one? */
2368
	if (start > vma->vm_start) {
2369 2370 2371 2372 2373 2374 2375

		/*
		 * Make sure that map_count on return from munmap() will
		 * not exceed its limit; but let map_count go just above
		 * its limit temporarily, to help free resources as expected.
		 */
		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2376
			goto map_count_exceeded;
2377

L
Liam R. Howlett 已提交
2378 2379 2380 2381
		/*
		 * mas_pause() is not needed since mas->index needs to be set
		 * differently than vma->vm_end anyways.
		 */
2382
		error = __split_vma(mm, vma, start, 0);
L
Linus Torvalds 已提交
2383
		if (error)
L
Liam R. Howlett 已提交
2384
			goto start_split_failed;
2385

L
Liam R. Howlett 已提交
2386 2387
		mas_set(mas, start);
		vma = mas_walk(mas);
L
Linus Torvalds 已提交
2388 2389
	}

L
Liam R. Howlett 已提交
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
	prev = mas_prev(mas, 0);
	if (unlikely((!prev)))
		mas_set(mas, start);

	/*
	 * Detach a range of VMAs from the mm. Using next as a temp variable as
	 * it is always overwritten.
	 */
	mas_for_each(mas, next, end - 1) {
		/* Does it split the end? */
		if (next->vm_end > end) {
			struct vm_area_struct *split;

			error = __split_vma(mm, next, end, 1);
			if (error)
				goto end_split_failed;
2406

L
Liam R. Howlett 已提交
2407 2408 2409 2410 2411
			mas_set(mas, end);
			split = mas_prev(mas, 0);
			error = munmap_sidetree(split, &mas_detach);
			if (error)
				goto munmap_sidetree_failed;
2412

L
Liam R. Howlett 已提交
2413 2414 2415 2416 2417 2418
			count++;
			if (vma == next)
				vma = split;
			break;
		}
		error = munmap_sidetree(next, &mas_detach);
L
Linus Torvalds 已提交
2419
		if (error)
L
Liam R. Howlett 已提交
2420
			goto munmap_sidetree_failed;
2421

L
Liam R. Howlett 已提交
2422 2423 2424 2425 2426
		count++;
#ifdef CONFIG_DEBUG_VM_MAPLE_TREE
		BUG_ON(next->vm_start < start);
		BUG_ON(next->vm_start > end);
#endif
L
Linus Torvalds 已提交
2427 2428
	}

L
Liam R. Howlett 已提交
2429 2430 2431
	if (!next)
		next = mas_next(mas, ULONG_MAX);

2432 2433 2434
	if (unlikely(uf)) {
		/*
		 * If userfaultfd_unmap_prep returns an error the vmas
I
Ingo Molnar 已提交
2435
		 * will remain split, but userland will get a
2436 2437 2438 2439 2440 2441
		 * highly unexpected error anyway. This is no
		 * different than the case where the first of the two
		 * __split_vma fails, but we don't undo the first
		 * split, despite we could. This is unlikely enough
		 * failure that it's not worth optimizing it for.
		 */
2442
		error = userfaultfd_unmap_prep(mm, start, end, uf);
2443

2444
		if (error)
2445
			goto userfaultfd_error;
2446 2447
	}

L
Liam R. Howlett 已提交
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
	/* Point of no return */
	mas_set_range(mas, start, end - 1);
#if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
	/* Make sure no VMAs are about to be lost. */
	{
		MA_STATE(test, &mt_detach, start, end - 1);
		struct vm_area_struct *vma_mas, *vma_test;
		int test_count = 0;

		rcu_read_lock();
		vma_test = mas_find(&test, end - 1);
		mas_for_each(mas, vma_mas, end - 1) {
			BUG_ON(vma_mas != vma_test);
			test_count++;
			vma_test = mas_next(&test, end - 1);
		}
		rcu_read_unlock();
		BUG_ON(count != test_count);
		mas_set_range(mas, start, end - 1);
	}
#endif
2469
	mas_store_prealloc(mas, NULL);
L
Liam R. Howlett 已提交
2470
	mm->map_count -= count;
2471 2472 2473 2474 2475 2476
	/*
	 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
	 * VM_GROWSUP VMA. Such VMAs can change their size under
	 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
	 */
	if (downgrade) {
L
Liam R. Howlett 已提交
2477
		if (next && (next->vm_flags & VM_GROWSDOWN))
2478 2479 2480 2481 2482 2483
			downgrade = false;
		else if (prev && (prev->vm_flags & VM_GROWSUP))
			downgrade = false;
		else
			mmap_write_downgrade(mm);
	}
2484

L
Liam R. Howlett 已提交
2485 2486 2487 2488 2489
	unmap_region(mm, &mt_detach, vma, prev, next, start, end);
	/* Statistics and freeing VMAs */
	mas_set(&mas_detach, start);
	remove_mt(mm, &mas_detach);
	__mt_destroy(&mt_detach);
L
Linus Torvalds 已提交
2490

L
Liam R. Howlett 已提交
2491 2492

	validate_mm(mm);
2493
	return downgrade ? 1 : 0;
2494 2495

userfaultfd_error:
L
Liam R. Howlett 已提交
2496 2497 2498 2499 2500
munmap_sidetree_failed:
end_split_failed:
	__mt_destroy(&mt_detach);
start_split_failed:
map_count_exceeded:
2501
	mas_destroy(mas);
2502
	return error;
L
Linus Torvalds 已提交
2503 2504
}

2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
/*
 * do_mas_munmap() - munmap a given range.
 * @mas: The maple state
 * @mm: The mm_struct
 * @start: The start address to munmap
 * @len: The length of the range to munmap
 * @uf: The userfaultfd list_head
 * @downgrade: set to true if the user wants to attempt to write_downgrade the
 * mmap_sem
 *
 * This function takes a @mas that is either pointing to the previous VMA or set
 * to MA_START and sets it up to remove the mapping(s).  The @len will be
 * aligned and any arch_unmap work will be preformed.
 *
 * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
 */
int do_mas_munmap(struct ma_state *mas, struct mm_struct *mm,
		  unsigned long start, size_t len, struct list_head *uf,
		  bool downgrade)
{
	unsigned long end;
	struct vm_area_struct *vma;

	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
		return -EINVAL;

	end = start + PAGE_ALIGN(len);
	if (end == start)
		return -EINVAL;

	 /* arch_unmap() might do unmaps itself.  */
	arch_unmap(mm, start, end);

	/* Find the first overlapping VMA */
	vma = mas_find(mas, end - 1);
	if (!vma)
		return 0;

	return do_mas_align_munmap(mas, vma, mm, start, end, uf, downgrade);
}

/* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
 * @mm: The mm_struct
 * @start: The start address to munmap
 * @len: The length to be munmapped.
 * @uf: The userfaultfd list_head
 */
2552 2553 2554
int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
	      struct list_head *uf)
{
2555 2556 2557
	MA_STATE(mas, &mm->mm_mt, start, start);

	return do_mas_munmap(&mas, mm, start, len, uf, false);
2558 2559
}

2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
unsigned long mmap_region(struct file *file, unsigned long addr,
		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
		struct list_head *uf)
{
	struct mm_struct *mm = current->mm;
	struct vm_area_struct *vma = NULL;
	struct vm_area_struct *next, *prev, *merge;
	pgoff_t pglen = len >> PAGE_SHIFT;
	unsigned long charged = 0;
	unsigned long end = addr + len;
	unsigned long merge_start = addr, merge_end = end;
	pgoff_t vm_pgoff;
	int error;
	MA_STATE(mas, &mm->mm_mt, addr, end - 1);

	/* Check against address space limit. */
	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
		unsigned long nr_pages;

		/*
		 * MAP_FIXED may remove pages of mappings that intersects with
		 * requested mapping. Account for the pages it would unmap.
		 */
		nr_pages = count_vma_pages_range(mm, addr, end);

		if (!may_expand_vm(mm, vm_flags,
					(len >> PAGE_SHIFT) - nr_pages))
			return -ENOMEM;
	}

	/* Unmap any existing mapping in the area */
2591
	if (do_mas_munmap(&mas, mm, addr, len, uf, false))
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
		return -ENOMEM;

	/*
	 * Private writable mapping: check memory availability
	 */
	if (accountable_mapping(file, vm_flags)) {
		charged = len >> PAGE_SHIFT;
		if (security_vm_enough_memory_mm(mm, charged))
			return -ENOMEM;
		vm_flags |= VM_ACCOUNT;
	}

	next = mas_next(&mas, ULONG_MAX);
	prev = mas_prev(&mas, 0);
	if (vm_flags & VM_SPECIAL)
		goto cannot_expand;

	/* Attempt to expand an old mapping */
	/* Check next */
	if (next && next->vm_start == end && !vma_policy(next) &&
	    can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
				 NULL_VM_UFFD_CTX, NULL)) {
		merge_end = next->vm_end;
		vma = next;
		vm_pgoff = next->vm_pgoff - pglen;
	}

	/* Check prev */
	if (prev && prev->vm_end == addr && !vma_policy(prev) &&
	    (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
				       pgoff, vma->vm_userfaultfd_ctx, NULL) :
		   can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
				       NULL_VM_UFFD_CTX, NULL))) {
		merge_start = prev->vm_start;
		vma = prev;
		vm_pgoff = prev->vm_pgoff;
	}


	/* Actually expand, if possible */
	if (vma &&
	    !vma_expand(&mas, vma, merge_start, merge_end, vm_pgoff, next)) {
		khugepaged_enter_vma(vma, vm_flags);
		goto expanded;
	}

	mas.index = addr;
	mas.last = end - 1;
cannot_expand:
	/*
	 * Determine the object being mapped and call the appropriate
	 * specific mapper. the address has already been validated, but
	 * not unmapped, but the maps are removed from the list.
	 */
	vma = vm_area_alloc(mm);
	if (!vma) {
		error = -ENOMEM;
		goto unacct_error;
	}

	vma->vm_start = addr;
	vma->vm_end = end;
	vma->vm_flags = vm_flags;
	vma->vm_page_prot = vm_get_page_prot(vm_flags);
	vma->vm_pgoff = pgoff;

	if (file) {
		if (vm_flags & VM_SHARED) {
			error = mapping_map_writable(file->f_mapping);
			if (error)
				goto free_vma;
		}

		vma->vm_file = get_file(file);
		error = call_mmap(file, vma);
		if (error)
			goto unmap_and_free_vma;

		/* Can addr have changed??
		 *
		 * Answer: Yes, several device drivers can do it in their
		 *         f_op->mmap method. -DaveM
		 */
		WARN_ON_ONCE(addr != vma->vm_start);

		addr = vma->vm_start;
		mas_reset(&mas);

		/*
		 * If vm_flags changed after call_mmap(), we should try merge
		 * vma again as we may succeed this time.
		 */
		if (unlikely(vm_flags != vma->vm_flags && prev)) {
			merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
				NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
			if (merge) {
				/*
				 * ->mmap() can change vma->vm_file and fput
				 * the original file. So fput the vma->vm_file
				 * here or we would add an extra fput for file
				 * and cause general protection fault
				 * ultimately.
				 */
				fput(vma->vm_file);
				vm_area_free(vma);
				vma = merge;
				/* Update vm_flags to pick up the change. */
				addr = vma->vm_start;
				vm_flags = vma->vm_flags;
				goto unmap_writable;
			}
		}

		vm_flags = vma->vm_flags;
	} else if (vm_flags & VM_SHARED) {
		error = shmem_zero_setup(vma);
		if (error)
			goto free_vma;
	} else {
		vma_set_anonymous(vma);
	}

	/* Allow architectures to sanity-check the vm_flags */
	if (!arch_validate_flags(vma->vm_flags)) {
		error = -EINVAL;
		if (file)
			goto unmap_and_free_vma;
		else
			goto free_vma;
	}

	if (mas_preallocate(&mas, vma, GFP_KERNEL)) {
		error = -ENOMEM;
		if (file)
			goto unmap_and_free_vma;
		else
			goto free_vma;
	}

	if (vma->vm_file)
		i_mmap_lock_write(vma->vm_file->f_mapping);

	vma_mas_store(vma, &mas);
	mm->map_count++;
	if (vma->vm_file) {
		if (vma->vm_flags & VM_SHARED)
			mapping_allow_writable(vma->vm_file->f_mapping);

		flush_dcache_mmap_lock(vma->vm_file->f_mapping);
		vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
		flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
		i_mmap_unlock_write(vma->vm_file->f_mapping);
	}

	/*
	 * vma_merge() calls khugepaged_enter_vma() either, the below
	 * call covers the non-merge case.
	 */
	khugepaged_enter_vma(vma, vma->vm_flags);

	/* Once vma denies write, undo our temporary denial count */
unmap_writable:
	if (file && vm_flags & VM_SHARED)
		mapping_unmap_writable(file->f_mapping);
	file = vma->vm_file;
expanded:
	perf_event_mmap(vma);

	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
	if (vm_flags & VM_LOCKED) {
		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
					is_vm_hugetlb_page(vma) ||
					vma == get_gate_vma(current->mm))
			vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
		else
			mm->locked_vm += (len >> PAGE_SHIFT);
	}

	if (file)
		uprobe_mmap(vma);

	/*
	 * New (or expanded) vma always get soft dirty status.
	 * Otherwise user-space soft-dirty page tracker won't
	 * be able to distinguish situation when vma area unmapped,
	 * then new mapped in-place (which must be aimed as
	 * a completely new data area).
	 */
	vma->vm_flags |= VM_SOFTDIRTY;

	vma_set_page_prot(vma);

	validate_mm(mm);
	return addr;

unmap_and_free_vma:
	fput(vma->vm_file);
	vma->vm_file = NULL;

	/* Undo any partial mapping done by a device driver. */
L
Liam R. Howlett 已提交
2792
	unmap_region(mm, mas.tree, vma, prev, next, vma->vm_start, vma->vm_end);
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
	if (vm_flags & VM_SHARED)
		mapping_unmap_writable(file->f_mapping);
free_vma:
	vm_area_free(vma);
unacct_error:
	if (charged)
		vm_unacct_memory(charged);
	validate_mm(mm);
	return error;
}

2804
static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
L
Linus Torvalds 已提交
2805 2806
{
	int ret;
A
Al Viro 已提交
2807
	struct mm_struct *mm = current->mm;
2808
	LIST_HEAD(uf);
2809
	MA_STATE(mas, &mm->mm_mt, start, start);
L
Linus Torvalds 已提交
2810

2811
	if (mmap_write_lock_killable(mm))
M
Michal Hocko 已提交
2812 2813
		return -EINTR;

2814
	ret = do_mas_munmap(&mas, mm, start, len, &uf, downgrade);
2815
	/*
2816
	 * Returning 1 indicates mmap_lock is downgraded.
2817 2818 2819 2820
	 * But 1 is not legal return value of vm_munmap() and munmap(), reset
	 * it to 0 before return.
	 */
	if (ret == 1) {
2821
		mmap_read_unlock(mm);
2822 2823
		ret = 0;
	} else
2824
		mmap_write_unlock(mm);
2825

2826
	userfaultfd_unmap_complete(mm, &uf);
L
Linus Torvalds 已提交
2827 2828
	return ret;
}
2829 2830 2831 2832 2833

int vm_munmap(unsigned long start, size_t len)
{
	return __vm_munmap(start, len, false);
}
2834 2835 2836 2837
EXPORT_SYMBOL(vm_munmap);

SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
{
2838
	addr = untagged_addr(addr);
2839
	return __vm_munmap(addr, len, true);
2840
}
L
Linus Torvalds 已提交
2841

2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855

/*
 * Emulation of deprecated remap_file_pages() syscall.
 */
SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
{

	struct mm_struct *mm = current->mm;
	struct vm_area_struct *vma;
	unsigned long populate = 0;
	unsigned long ret = -EINVAL;
	struct file *file;

2856
	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
J
Joe Perches 已提交
2857
		     current->comm, current->pid);
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870

	if (prot)
		return ret;
	start = start & PAGE_MASK;
	size = size & PAGE_MASK;

	if (start + size <= start)
		return ret;

	/* Does pgoff wrap? */
	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
		return ret;

2871
	if (mmap_write_lock_killable(mm))
2872 2873
		return -EINTR;

2874
	vma = vma_lookup(mm, start);
2875 2876 2877 2878

	if (!vma || !(vma->vm_flags & VM_SHARED))
		goto out;

2879
	if (start + size > vma->vm_end) {
L
Liam R. Howlett 已提交
2880 2881
		VMA_ITERATOR(vmi, mm, vma->vm_end);
		struct vm_area_struct *next, *prev = vma;
2882

L
Liam R. Howlett 已提交
2883
		for_each_vma_range(vmi, next, start + size) {
2884
			/* hole between vmas ? */
L
Liam R. Howlett 已提交
2885
			if (next->vm_start != prev->vm_end)
2886 2887 2888 2889 2890 2891 2892 2893
				goto out;

			if (next->vm_file != vma->vm_file)
				goto out;

			if (next->vm_flags != vma->vm_flags)
				goto out;

L
Liam R. Howlett 已提交
2894
			prev = next;
2895 2896 2897 2898
		}

		if (!next)
			goto out;
2899 2900 2901 2902 2903 2904 2905 2906
	}

	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;

	flags &= MAP_NONBLOCK;
	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2907
	if (vma->vm_flags & VM_LOCKED)
2908
		flags |= MAP_LOCKED;
2909

2910
	file = get_file(vma->vm_file);
2911
	ret = do_mmap(vma->vm_file, start, size,
2912
			prot, flags, pgoff, &populate, NULL);
2913 2914
	fput(file);
out:
2915
	mmap_write_unlock(mm);
2916 2917 2918 2919 2920 2921 2922
	if (populate)
		mm_populate(ret, populate);
	if (!IS_ERR_VALUE(ret))
		ret = 0;
	return ret;
}

L
Linus Torvalds 已提交
2923
/*
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
 * brk_munmap() - Unmap a parital vma.
 * @mas: The maple tree state.
 * @vma: The vma to be modified
 * @newbrk: the start of the address to unmap
 * @oldbrk: The end of the address to unmap
 * @uf: The userfaultfd list_head
 *
 * Returns: 1 on success.
 * unmaps a partial VMA mapping.  Does not handle alignment, downgrades lock if
 * possible.
L
Linus Torvalds 已提交
2934
 */
2935 2936 2937
static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
			 unsigned long newbrk, unsigned long oldbrk,
			 struct list_head *uf)
L
Linus Torvalds 已提交
2938
{
2939 2940
	struct mm_struct *mm = vma->vm_mm;
	int ret;
2941

2942
	arch_unmap(mm, newbrk, oldbrk);
2943
	ret = do_mas_align_munmap(mas, vma, mm, newbrk, oldbrk, uf, true);
2944 2945 2946
	validate_mm_mt(mm);
	return ret;
}
L
Linus Torvalds 已提交
2947

2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
/*
 * do_brk_flags() - Increase the brk vma if the flags match.
 * @mas: The maple tree state.
 * @addr: The start address
 * @len: The length of the increase
 * @vma: The vma,
 * @flags: The VMA Flags
 *
 * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
 * do not match then create a new anonymous VMA.  Eventually we may be able to
 * do some brk-specific accounting here.
 */
static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *vma,
L
Liam R. Howlett 已提交
2961
		unsigned long addr, unsigned long len, unsigned long flags)
2962 2963
{
	struct mm_struct *mm = current->mm;
L
Linus Torvalds 已提交
2964

2965 2966 2967 2968 2969 2970
	validate_mm_mt(mm);
	/*
	 * Check against address space limits by the changed size
	 * Note: This happens *after* clearing old mappings in some code paths.
	 */
	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2971
	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
L
Linus Torvalds 已提交
2972 2973 2974 2975 2976
		return -ENOMEM;

	if (mm->map_count > sysctl_max_map_count)
		return -ENOMEM;

2977
	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
L
Linus Torvalds 已提交
2978 2979 2980
		return -ENOMEM;

	/*
2981 2982
	 * Expand the existing vma if possible; Note that singular lists do not
	 * occur after forking, so the expand will only happen on new VMAs.
L
Linus Torvalds 已提交
2983
	 */
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
	if (vma &&
	    (!vma->anon_vma || list_is_singular(&vma->anon_vma_chain)) &&
	    ((vma->vm_flags & ~VM_SOFTDIRTY) == flags)) {
		mas->index = vma->vm_start;
		mas->last = addr + len - 1;
		vma_adjust_trans_huge(vma, addr, addr + len, 0);
		if (vma->anon_vma) {
			anon_vma_lock_write(vma->anon_vma);
			anon_vma_interval_tree_pre_update_vma(vma);
		}
		vma->vm_end = addr + len;
		vma->vm_flags |= VM_SOFTDIRTY;
		if (mas_store_gfp(mas, vma, GFP_KERNEL))
			goto mas_expand_failed;

		if (vma->anon_vma) {
			anon_vma_interval_tree_post_update_vma(vma);
			anon_vma_unlock_write(vma->anon_vma);
		}
		khugepaged_enter_vma(vma, flags);
		goto out;
L
Linus Torvalds 已提交
3005
	}
3006 3007 3008 3009 3010

	/* create a vma struct for an anonymous mapping */
	vma = vm_area_alloc(mm);
	if (!vma)
		goto vma_alloc_fail;
L
Linus Torvalds 已提交
3011

3012
	vma_set_anonymous(vma);
L
Linus Torvalds 已提交
3013 3014
	vma->vm_start = addr;
	vma->vm_end = addr + len;
3015
	vma->vm_pgoff = addr >> PAGE_SHIFT;
L
Linus Torvalds 已提交
3016
	vma->vm_flags = flags;
3017
	vma->vm_page_prot = vm_get_page_prot(flags);
3018 3019 3020
	mas_set_range(mas, vma->vm_start, addr + len - 1);
	if (mas_store_gfp(mas, vma, GFP_KERNEL))
		goto mas_store_fail;
3021

3022
	mm->map_count++;
L
Linus Torvalds 已提交
3023
out:
3024
	perf_event_mmap(vma);
L
Linus Torvalds 已提交
3025
	mm->total_vm += len >> PAGE_SHIFT;
3026
	mm->data_vm += len >> PAGE_SHIFT;
3027 3028
	if (flags & VM_LOCKED)
		mm->locked_vm += (len >> PAGE_SHIFT);
3029
	vma->vm_flags |= VM_SOFTDIRTY;
L
Liam R. Howlett 已提交
3030
	validate_mm(mm);
3031
	return 0;
3032

3033
mas_store_fail:
3034
	vm_area_free(vma);
3035 3036 3037 3038 3039 3040 3041 3042 3043
vma_alloc_fail:
	vm_unacct_memory(len >> PAGE_SHIFT);
	return -ENOMEM;

mas_expand_failed:
	if (vma->anon_vma) {
		anon_vma_interval_tree_post_update_vma(vma);
		anon_vma_unlock_write(vma->anon_vma);
	}
3044
	return -ENOMEM;
L
Linus Torvalds 已提交
3045 3046
}

3047
int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3048 3049
{
	struct mm_struct *mm = current->mm;
3050
	struct vm_area_struct *vma = NULL;
3051
	unsigned long len;
3052
	int ret;
3053
	bool populate;
3054
	LIST_HEAD(uf);
3055
	MA_STATE(mas, &mm->mm_mt, addr, addr);
3056

3057 3058 3059 3060 3061 3062
	len = PAGE_ALIGN(request);
	if (len < request)
		return -ENOMEM;
	if (!len)
		return 0;

3063
	if (mmap_write_lock_killable(mm))
M
Michal Hocko 已提交
3064 3065
		return -EINTR;

3066 3067 3068 3069 3070 3071 3072 3073
	/* Until we need other flags, refuse anything except VM_EXEC. */
	if ((flags & (~VM_EXEC)) != 0)
		return -EINVAL;

	ret = check_brk_limits(addr, len);
	if (ret)
		goto limits_failed;

3074
	ret = do_mas_munmap(&mas, mm, addr, len, &uf, 0);
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084
	if (ret)
		goto munmap_failed;

	vma = mas_prev(&mas, 0);
	if (!vma || vma->vm_end != addr || vma_policy(vma) ||
	    !can_vma_merge_after(vma, flags, NULL, NULL,
				 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL))
		vma = NULL;

	ret = do_brk_flags(&mas, vma, addr, len, flags);
3085
	populate = ((mm->def_flags & VM_LOCKED) != 0);
3086
	mmap_write_unlock(mm);
3087
	userfaultfd_unmap_complete(mm, &uf);
3088
	if (populate && !ret)
3089
		mm_populate(addr, len);
3090
	return ret;
3091 3092 3093 3094 3095

munmap_failed:
limits_failed:
	mmap_write_unlock(mm);
	return ret;
3096
}
3097 3098 3099 3100 3101 3102
EXPORT_SYMBOL(vm_brk_flags);

int vm_brk(unsigned long addr, unsigned long len)
{
	return vm_brk_flags(addr, len, 0);
}
3103
EXPORT_SYMBOL(vm_brk);
L
Linus Torvalds 已提交
3104 3105 3106 3107

/* Release all mmaps. */
void exit_mmap(struct mm_struct *mm)
{
P
Peter Zijlstra 已提交
3108
	struct mmu_gather tlb;
3109
	struct vm_area_struct *vma;
L
Linus Torvalds 已提交
3110
	unsigned long nr_accounted = 0;
L
Liam R. Howlett 已提交
3111 3112
	MA_STATE(mas, &mm->mm_mt, 0, 0);
	int count = 0;
L
Linus Torvalds 已提交
3113

3114
	/* mm's last user has gone, and its about to be pulled down */
A
Andrea Arcangeli 已提交
3115
	mmu_notifier_release(mm);
3116

3117 3118 3119 3120
	if (unlikely(mm_is_oom_victim(mm))) {
		/*
		 * Manually reap the mm to free as much memory as possible.
		 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3121
		 * this mm from further consideration.  Taking mm->mmap_lock for
3122
		 * write after setting MMF_OOM_SKIP will guarantee that the oom
3123
		 * reaper will not run on this mm again after mmap_lock is
3124 3125
		 * dropped.
		 *
3126
		 * Nothing can be holding mm->mmap_lock here and the above call
3127 3128 3129
		 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
		 * __oom_reap_task_mm() will not block.
		 */
3130
		(void)__oom_reap_task_mm(mm);
3131 3132 3133
		set_bit(MMF_OOM_SKIP, &mm->flags);
	}

3134
	mmap_write_lock(mm);
3135 3136
	arch_exit_mmap(mm);

L
Liam R. Howlett 已提交
3137
	vma = mas_find(&mas, ULONG_MAX);
3138 3139 3140
	if (!vma) {
		/* Can happen if dup_mmap() received an OOM */
		mmap_write_unlock(mm);
3141
		return;
3142
	}
3143

L
Linus Torvalds 已提交
3144 3145
	lru_add_drain();
	flush_cache_mm(mm);
3146
	tlb_gather_mmu_fullmm(&tlb, mm);
3147
	/* update_hiwater_rss(mm) here? but nobody should be looking */
L
Liam R. Howlett 已提交
3148 3149 3150 3151
	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
	unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX);
	free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
		      USER_PGTABLES_CEILING);
3152
	tlb_finish_mmu(&tlb);
L
Linus Torvalds 已提交
3153

L
Liam R. Howlett 已提交
3154 3155 3156 3157 3158 3159
	/*
	 * Walk the list again, actually closing and freeing it, with preemption
	 * enabled, without holding any MM locks besides the unreachable
	 * mmap_write_lock.
	 */
	do {
3160 3161
		if (vma->vm_flags & VM_ACCOUNT)
			nr_accounted += vma_pages(vma);
L
Liam R. Howlett 已提交
3162 3163
		remove_vma(vma);
		count++;
3164
		cond_resched();
L
Liam R. Howlett 已提交
3165 3166 3167
	} while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);

	BUG_ON(count != mm->map_count);
3168 3169 3170

	trace_exit_mmap(mm);
	__mt_destroy(&mm->mm_mt);
3171
	mmap_write_unlock(mm);
3172
	vm_unacct_memory(nr_accounted);
L
Linus Torvalds 已提交
3173 3174 3175 3176
}

/* Insert vm structure into process list sorted by address
 * and into the inode's i_mmap tree.  If vm_file is non-NULL
3177
 * then i_mmap_rwsem is taken here.
L
Linus Torvalds 已提交
3178
 */
3179
int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
L
Linus Torvalds 已提交
3180
{
3181
	struct vm_area_struct *prev;
3182
	unsigned long charged = vma_pages(vma);
L
Linus Torvalds 已提交
3183

3184

L
Liam R. Howlett 已提交
3185
	if (range_has_overlap(mm, vma->vm_start, vma->vm_end, &prev))
3186
		return -ENOMEM;
3187

3188
	if ((vma->vm_flags & VM_ACCOUNT) &&
3189
	     security_vm_enough_memory_mm(mm, charged))
3190 3191
		return -ENOMEM;

L
Linus Torvalds 已提交
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
	/*
	 * The vm_pgoff of a purely anonymous vma should be irrelevant
	 * until its first write fault, when page's anon_vma and index
	 * are set.  But now set the vm_pgoff it will almost certainly
	 * end up with (unless mremap moves it elsewhere before that
	 * first wfault), so /proc/pid/maps tells a consistent story.
	 *
	 * By setting it to reflect the virtual start address of the
	 * vma, merges and splits can happen in a seamless way, just
	 * using the existing file pgoff checks and manipulations.
3202
	 * Similarly in do_mmap and in do_brk_flags.
L
Linus Torvalds 已提交
3203
	 */
3204
	if (vma_is_anonymous(vma)) {
L
Linus Torvalds 已提交
3205 3206 3207
		BUG_ON(vma->anon_vma);
		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
	}
3208

L
Liam R. Howlett 已提交
3209
	if (vma_link(mm, vma)) {
3210 3211 3212 3213
		vm_unacct_memory(charged);
		return -ENOMEM;
	}

L
Linus Torvalds 已提交
3214 3215 3216 3217 3218 3219 3220 3221
	return 0;
}

/*
 * Copy the vma structure to a new location in the same mm,
 * prior to moving page table entries, to effect an mremap move.
 */
struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3222 3223
	unsigned long addr, unsigned long len, pgoff_t pgoff,
	bool *need_rmap_locks)
L
Linus Torvalds 已提交
3224 3225 3226 3227 3228
{
	struct vm_area_struct *vma = *vmap;
	unsigned long vma_start = vma->vm_start;
	struct mm_struct *mm = vma->vm_mm;
	struct vm_area_struct *new_vma, *prev;
3229
	bool faulted_in_anon_vma = true;
L
Linus Torvalds 已提交
3230

3231
	validate_mm_mt(mm);
L
Linus Torvalds 已提交
3232 3233 3234 3235
	/*
	 * If anonymous vma has not yet been faulted, update new pgoff
	 * to match new location, to increase its chance of merging.
	 */
3236
	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
L
Linus Torvalds 已提交
3237
		pgoff = addr >> PAGE_SHIFT;
3238 3239
		faulted_in_anon_vma = false;
	}
L
Linus Torvalds 已提交
3240

L
Liam R. Howlett 已提交
3241 3242
	new_vma = find_vma_prev(mm, addr, &prev);
	if (new_vma && new_vma->vm_start < addr + len)
3243
		return NULL;	/* should never get here */
L
Liam R. Howlett 已提交
3244

L
Linus Torvalds 已提交
3245
	new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3246
			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3247
			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
L
Linus Torvalds 已提交
3248 3249 3250 3251
	if (new_vma) {
		/*
		 * Source vma may have been merged into new_vma
		 */
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
		if (unlikely(vma_start >= new_vma->vm_start &&
			     vma_start < new_vma->vm_end)) {
			/*
			 * The only way we can get a vma_merge with
			 * self during an mremap is if the vma hasn't
			 * been faulted in yet and we were allowed to
			 * reset the dst vma->vm_pgoff to the
			 * destination address of the mremap to allow
			 * the merge to happen. mremap must change the
			 * vm_pgoff linearity between src and dst vmas
			 * (in turn preventing a vma_merge) to be
			 * safe. It is only safe to keep the vm_pgoff
			 * linear if there are no pages mapped yet.
			 */
3266
			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3267
			*vmap = vma = new_vma;
3268
		}
3269
		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
L
Linus Torvalds 已提交
3270
	} else {
3271
		new_vma = vm_area_dup(vma);
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
		if (!new_vma)
			goto out;
		new_vma->vm_start = addr;
		new_vma->vm_end = addr + len;
		new_vma->vm_pgoff = pgoff;
		if (vma_dup_policy(vma, new_vma))
			goto out_free_vma;
		if (anon_vma_clone(new_vma, vma))
			goto out_free_mempol;
		if (new_vma->vm_file)
			get_file(new_vma->vm_file);
		if (new_vma->vm_ops && new_vma->vm_ops->open)
			new_vma->vm_ops->open(new_vma);
L
Liam R. Howlett 已提交
3285
		if (vma_link(mm, new_vma))
L
Liam R. Howlett 已提交
3286
			goto out_vma_link;
3287
		*need_rmap_locks = false;
L
Linus Torvalds 已提交
3288
	}
3289
	validate_mm_mt(mm);
L
Linus Torvalds 已提交
3290
	return new_vma;
3291

L
Liam R. Howlett 已提交
3292 3293 3294
out_vma_link:
	if (new_vma->vm_ops && new_vma->vm_ops->close)
		new_vma->vm_ops->close(new_vma);
3295
out_free_mempol:
3296
	mpol_put(vma_policy(new_vma));
3297
out_free_vma:
3298
	vm_area_free(new_vma);
3299
out:
3300
	validate_mm_mt(mm);
3301
	return NULL;
L
Linus Torvalds 已提交
3302
}
A
akpm@osdl.org 已提交
3303 3304 3305 3306 3307

/*
 * Return true if the calling process may expand its vm space by the passed
 * number of pages
 */
3308
bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
A
akpm@osdl.org 已提交
3309
{
3310 3311
	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
		return false;
A
akpm@osdl.org 已提交
3312

3313 3314
	if (is_data_mapping(flags) &&
	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3315 3316 3317 3318
		/* Workaround for Valgrind */
		if (rlimit(RLIMIT_DATA) == 0 &&
		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
			return true;
3319 3320 3321 3322 3323 3324 3325 3326

		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
			     current->comm, current->pid,
			     (mm->data_vm + npages) << PAGE_SHIFT,
			     rlimit(RLIMIT_DATA),
			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");

		if (!ignore_rlimit_data)
3327 3328
			return false;
	}
A
akpm@osdl.org 已提交
3329

3330 3331 3332 3333 3334
	return true;
}

void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
{
3335
	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3336

3337
	if (is_exec_mapping(flags))
3338
		mm->exec_vm += npages;
3339
	else if (is_stack_mapping(flags))
3340
		mm->stack_vm += npages;
3341
	else if (is_data_mapping(flags))
3342
		mm->data_vm += npages;
A
akpm@osdl.org 已提交
3343
}
3344

3345
static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358

/*
 * Having a close hook prevents vma merging regardless of flags.
 */
static void special_mapping_close(struct vm_area_struct *vma)
{
}

static const char *special_mapping_name(struct vm_area_struct *vma)
{
	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
}

3359
static int special_mapping_mremap(struct vm_area_struct *new_vma)
3360 3361 3362
{
	struct vm_special_mapping *sm = new_vma->vm_private_data;

3363 3364 3365
	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
		return -EFAULT;

3366 3367
	if (sm->mremap)
		return sm->mremap(sm, new_vma);
3368

3369 3370 3371
	return 0;
}

3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
{
	/*
	 * Forbid splitting special mappings - kernel has expectations over
	 * the number of pages in mapping. Together with VM_DONTEXPAND
	 * the size of vma should stay the same over the special mapping's
	 * lifetime.
	 */
	return -EINVAL;
}

3383 3384 3385
static const struct vm_operations_struct special_mapping_vmops = {
	.close = special_mapping_close,
	.fault = special_mapping_fault,
3386
	.mremap = special_mapping_mremap,
3387
	.name = special_mapping_name,
3388 3389
	/* vDSO code relies that VVAR can't be accessed remotely */
	.access = NULL,
3390
	.may_split = special_mapping_split,
3391 3392 3393 3394 3395 3396
};

static const struct vm_operations_struct legacy_special_mapping_vmops = {
	.close = special_mapping_close,
	.fault = special_mapping_fault,
};
3397

3398
static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3399
{
3400
	struct vm_area_struct *vma = vmf->vma;
N
Nick Piggin 已提交
3401
	pgoff_t pgoff;
3402 3403
	struct page **pages;

3404
	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3405
		pages = vma->vm_private_data;
3406 3407 3408 3409
	} else {
		struct vm_special_mapping *sm = vma->vm_private_data;

		if (sm->fault)
3410
			return sm->fault(sm, vmf->vma, vmf);
3411 3412 3413

		pages = sm->pages;
	}
3414

3415
	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
N
Nick Piggin 已提交
3416
		pgoff--;
3417 3418 3419 3420

	if (*pages) {
		struct page *page = *pages;
		get_page(page);
N
Nick Piggin 已提交
3421 3422
		vmf->page = page;
		return 0;
3423 3424
	}

N
Nick Piggin 已提交
3425
	return VM_FAULT_SIGBUS;
3426 3427
}

3428 3429 3430
static struct vm_area_struct *__install_special_mapping(
	struct mm_struct *mm,
	unsigned long addr, unsigned long len,
3431 3432
	unsigned long vm_flags, void *priv,
	const struct vm_operations_struct *ops)
3433
{
3434
	int ret;
3435 3436
	struct vm_area_struct *vma;

3437
	validate_mm_mt(mm);
3438
	vma = vm_area_alloc(mm);
3439
	if (unlikely(vma == NULL))
3440
		return ERR_PTR(-ENOMEM);
3441 3442 3443 3444

	vma->vm_start = addr;
	vma->vm_end = addr + len;

3445
	vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3446
	vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3447
	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3448

3449 3450
	vma->vm_ops = ops;
	vma->vm_private_data = priv;
3451

3452 3453 3454
	ret = insert_vm_struct(mm, vma);
	if (ret)
		goto out;
3455

3456
	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3457

3458
	perf_event_mmap(vma);
3459

3460
	validate_mm_mt(mm);
3461
	return vma;
3462 3463

out:
3464
	vm_area_free(vma);
3465
	validate_mm_mt(mm);
3466 3467 3468
	return ERR_PTR(ret);
}

3469 3470 3471 3472 3473 3474 3475 3476
bool vma_is_special_mapping(const struct vm_area_struct *vma,
	const struct vm_special_mapping *sm)
{
	return vma->vm_private_data == sm &&
		(vma->vm_ops == &special_mapping_vmops ||
		 vma->vm_ops == &legacy_special_mapping_vmops);
}

3477
/*
3478
 * Called with mm->mmap_lock held for writing.
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
 * Insert a new vma covering the given region, with the given flags.
 * Its pages are supplied by the given array of struct page *.
 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
 * The region past the last page supplied will always produce SIGBUS.
 * The array pointer and the pages it points to are assumed to stay alive
 * for as long as this mapping might exist.
 */
struct vm_area_struct *_install_special_mapping(
	struct mm_struct *mm,
	unsigned long addr, unsigned long len,
	unsigned long vm_flags, const struct vm_special_mapping *spec)
{
3491 3492
	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
					&special_mapping_vmops);
3493 3494
}

3495 3496 3497 3498
int install_special_mapping(struct mm_struct *mm,
			    unsigned long addr, unsigned long len,
			    unsigned long vm_flags, struct page **pages)
{
3499
	struct vm_area_struct *vma = __install_special_mapping(
3500 3501
		mm, addr, len, vm_flags, (void *)pages,
		&legacy_special_mapping_vmops);
3502

3503
	return PTR_ERR_OR_ZERO(vma);
3504
}
3505 3506 3507

static DEFINE_MUTEX(mm_all_locks_mutex);

3508
static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3509
{
3510
	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3511 3512 3513 3514
		/*
		 * The LSB of head.next can't change from under us
		 * because we hold the mm_all_locks_mutex.
		 */
3515
		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3516 3517
		/*
		 * We can safely modify head.next after taking the
3518
		 * anon_vma->root->rwsem. If some other vma in this mm shares
3519 3520 3521 3522
		 * the same anon_vma we won't take it again.
		 *
		 * No need of atomic instructions here, head.next
		 * can't change from under us thanks to the
3523
		 * anon_vma->root->rwsem.
3524 3525
		 */
		if (__test_and_set_bit(0, (unsigned long *)
3526
				       &anon_vma->root->rb_root.rb_root.rb_node))
3527 3528 3529 3530
			BUG();
	}
}

3531
static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
{
	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
		/*
		 * AS_MM_ALL_LOCKS can't change from under us because
		 * we hold the mm_all_locks_mutex.
		 *
		 * Operations on ->flags have to be atomic because
		 * even if AS_MM_ALL_LOCKS is stable thanks to the
		 * mm_all_locks_mutex, there may be other cpus
		 * changing other bitflags in parallel to us.
		 */
		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
			BUG();
3545
		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3546 3547 3548 3549 3550 3551 3552 3553
	}
}

/*
 * This operation locks against the VM for all pte/vma/mm related
 * operations that could ever happen on a certain mm. This includes
 * vmtruncate, try_to_unmap, and all page faults.
 *
3554
 * The caller must take the mmap_lock in write mode before calling
3555
 * mm_take_all_locks(). The caller isn't allowed to release the
3556
 * mmap_lock until mm_drop_all_locks() returns.
3557
 *
3558
 * mmap_lock in write mode is required in order to block all operations
3559
 * that could modify pagetables and free pages without need of
3560
 * altering the vma layout. It's also needed in write mode to avoid new
3561 3562 3563 3564 3565
 * anon_vmas to be associated with existing vmas.
 *
 * A single task can't take more than one mm_take_all_locks() in a row
 * or it would deadlock.
 *
3566
 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3567 3568 3569
 * mapping->flags avoid to take the same lock twice, if more than one
 * vma in this mm is backed by the same anon_vma or address_space.
 *
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579
 * We take locks in following order, accordingly to comment at beginning
 * of mm/rmap.c:
 *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
 *     hugetlb mapping);
 *   - all i_mmap_rwsem locks;
 *   - all anon_vma->rwseml
 *
 * We can take all locks within these types randomly because the VM code
 * doesn't nest them and we protected from parallel mm_take_all_locks() by
 * mm_all_locks_mutex.
3580 3581 3582 3583 3584 3585 3586 3587 3588
 *
 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
 * that may have to take thousand of locks.
 *
 * mm_take_all_locks() can fail if it's interrupted by signals.
 */
int mm_take_all_locks(struct mm_struct *mm)
{
	struct vm_area_struct *vma;
3589
	struct anon_vma_chain *avc;
L
Liam R. Howlett 已提交
3590
	MA_STATE(mas, &mm->mm_mt, 0, 0);
3591

3592
	mmap_assert_write_locked(mm);
3593 3594 3595

	mutex_lock(&mm_all_locks_mutex);

L
Liam R. Howlett 已提交
3596
	mas_for_each(&mas, vma, ULONG_MAX) {
3597 3598
		if (signal_pending(current))
			goto out_unlock;
3599 3600 3601 3602 3603
		if (vma->vm_file && vma->vm_file->f_mapping &&
				is_vm_hugetlb_page(vma))
			vm_lock_mapping(mm, vma->vm_file->f_mapping);
	}

L
Liam R. Howlett 已提交
3604 3605
	mas_set(&mas, 0);
	mas_for_each(&mas, vma, ULONG_MAX) {
3606 3607 3608 3609
		if (signal_pending(current))
			goto out_unlock;
		if (vma->vm_file && vma->vm_file->f_mapping &&
				!is_vm_hugetlb_page(vma))
3610
			vm_lock_mapping(mm, vma->vm_file->f_mapping);
3611
	}
3612

L
Liam R. Howlett 已提交
3613 3614
	mas_set(&mas, 0);
	mas_for_each(&mas, vma, ULONG_MAX) {
3615 3616 3617
		if (signal_pending(current))
			goto out_unlock;
		if (vma->anon_vma)
3618 3619
			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
				vm_lock_anon_vma(mm, avc->anon_vma);
3620
	}
3621

3622
	return 0;
3623 3624

out_unlock:
3625 3626
	mm_drop_all_locks(mm);
	return -EINTR;
3627 3628 3629 3630
}

static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
{
3631
	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3632 3633 3634 3635 3636
		/*
		 * The LSB of head.next can't change to 0 from under
		 * us because we hold the mm_all_locks_mutex.
		 *
		 * We must however clear the bitflag before unlocking
3637
		 * the vma so the users using the anon_vma->rb_root will
3638 3639 3640 3641
		 * never see our bitflag.
		 *
		 * No need of atomic instructions here, head.next
		 * can't change from under us until we release the
3642
		 * anon_vma->root->rwsem.
3643 3644
		 */
		if (!__test_and_clear_bit(0, (unsigned long *)
3645
					  &anon_vma->root->rb_root.rb_root.rb_node))
3646
			BUG();
3647
		anon_vma_unlock_write(anon_vma);
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
	}
}

static void vm_unlock_mapping(struct address_space *mapping)
{
	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
		/*
		 * AS_MM_ALL_LOCKS can't change to 0 from under us
		 * because we hold the mm_all_locks_mutex.
		 */
3658
		i_mmap_unlock_write(mapping);
3659 3660 3661 3662 3663 3664 3665
		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
					&mapping->flags))
			BUG();
	}
}

/*
3666
 * The mmap_lock cannot be released by the caller until
3667 3668 3669 3670 3671
 * mm_drop_all_locks() returns.
 */
void mm_drop_all_locks(struct mm_struct *mm)
{
	struct vm_area_struct *vma;
3672
	struct anon_vma_chain *avc;
L
Liam R. Howlett 已提交
3673
	MA_STATE(mas, &mm->mm_mt, 0, 0);
3674

3675
	mmap_assert_write_locked(mm);
3676 3677
	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));

L
Liam R. Howlett 已提交
3678
	mas_for_each(&mas, vma, ULONG_MAX) {
3679
		if (vma->anon_vma)
3680 3681
			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
				vm_unlock_anon_vma(avc->anon_vma);
3682 3683 3684 3685 3686 3687
		if (vma->vm_file && vma->vm_file->f_mapping)
			vm_unlock_mapping(vma->vm_file->f_mapping);
	}

	mutex_unlock(&mm_all_locks_mutex);
}
3688 3689

/*
S
seokhoon.yoon 已提交
3690
 * initialise the percpu counter for VM
3691 3692 3693
 */
void __init mmap_init(void)
{
3694 3695
	int ret;

3696
	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3697
	VM_BUG_ON(ret);
3698
}
3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709

/*
 * Initialise sysctl_user_reserve_kbytes.
 *
 * This is intended to prevent a user from starting a single memory hogging
 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
 * mode.
 *
 * The default value is min(3% of free memory, 128MB)
 * 128MB is enough to recover with sshd/login, bash, and top/kill.
 */
3710
static int init_user_reserve(void)
3711 3712 3713
{
	unsigned long free_kbytes;

3714
	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3715 3716 3717 3718

	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
	return 0;
}
3719
subsys_initcall(init_user_reserve);
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730

/*
 * Initialise sysctl_admin_reserve_kbytes.
 *
 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
 * to log in and kill a memory hogging process.
 *
 * Systems with more than 256MB will reserve 8MB, enough to recover
 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
 * only reserve 3% of free pages by default.
 */
3731
static int init_admin_reserve(void)
3732 3733 3734
{
	unsigned long free_kbytes;

3735
	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3736 3737 3738 3739

	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
	return 0;
}
3740
subsys_initcall(init_admin_reserve);
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778

/*
 * Reinititalise user and admin reserves if memory is added or removed.
 *
 * The default user reserve max is 128MB, and the default max for the
 * admin reserve is 8MB. These are usually, but not always, enough to
 * enable recovery from a memory hogging process using login/sshd, a shell,
 * and tools like top. It may make sense to increase or even disable the
 * reserve depending on the existence of swap or variations in the recovery
 * tools. So, the admin may have changed them.
 *
 * If memory is added and the reserves have been eliminated or increased above
 * the default max, then we'll trust the admin.
 *
 * If memory is removed and there isn't enough free memory, then we
 * need to reset the reserves.
 *
 * Otherwise keep the reserve set by the admin.
 */
static int reserve_mem_notifier(struct notifier_block *nb,
			     unsigned long action, void *data)
{
	unsigned long tmp, free_kbytes;

	switch (action) {
	case MEM_ONLINE:
		/* Default max is 128MB. Leave alone if modified by operator. */
		tmp = sysctl_user_reserve_kbytes;
		if (0 < tmp && tmp < (1UL << 17))
			init_user_reserve();

		/* Default max is 8MB.  Leave alone if modified by operator. */
		tmp = sysctl_admin_reserve_kbytes;
		if (0 < tmp && tmp < (1UL << 13))
			init_admin_reserve();

		break;
	case MEM_OFFLINE:
3779
		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805

		if (sysctl_user_reserve_kbytes > free_kbytes) {
			init_user_reserve();
			pr_info("vm.user_reserve_kbytes reset to %lu\n",
				sysctl_user_reserve_kbytes);
		}

		if (sysctl_admin_reserve_kbytes > free_kbytes) {
			init_admin_reserve();
			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
				sysctl_admin_reserve_kbytes);
		}
		break;
	default:
		break;
	}
	return NOTIFY_OK;
}

static struct notifier_block reserve_mem_nb = {
	.notifier_call = reserve_mem_notifier,
};

static int __meminit init_reserve_notifier(void)
{
	if (register_hotmemory_notifier(&reserve_mem_nb))
3806
		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3807 3808 3809

	return 0;
}
3810
subsys_initcall(init_reserve_notifier);