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

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

12
#include <linux/kernel.h>
Linus Torvalds's avatar
Linus Torvalds committed
13
#include <linux/slab.h>
14
#include <linux/backing-dev.h>
Linus Torvalds's avatar
Linus Torvalds committed
15
#include <linux/mm.h>
16
#include <linux/mm_inline.h>
Linus Torvalds's avatar
Linus Torvalds committed
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>
Linus Torvalds's avatar
Linus Torvalds committed
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>
Linus Torvalds's avatar
Linus Torvalds committed
30
#include <linux/profile.h>
31
#include <linux/export.h>
Linus Torvalds's avatar
Linus Torvalds committed
32 33 34
#include <linux/mount.h>
#include <linux/mempolicy.h>
#include <linux/rmap.h>
Andrea Arcangeli's avatar
Andrea Arcangeli committed
35
#include <linux/mmu_notifier.h>
36
#include <linux/mmdebug.h>
37
#include <linux/perf_event.h>
Al Viro's avatar
Al Viro committed
38
#include <linux/audit.h>
Andrea Arcangeli's avatar
Andrea Arcangeli committed
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>
Linus Torvalds's avatar
Linus Torvalds committed
49

50
#include <linux/uaccess.h>
Linus Torvalds's avatar
Linus Torvalds committed
51 52
#include <asm/cacheflush.h>
#include <asm/tlb.h>
53
#include <asm/mmu_context.h>
Linus Torvalds's avatar
Linus Torvalds committed
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

78
static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
79
		struct vm_area_struct *vma, struct vm_area_struct *prev,
80 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
}

Linus Torvalds's avatar
Linus Torvalds committed
103
/*
104
 * Requires inode->i_mapping->i_mmap_rwsem
Linus Torvalds's avatar
Linus Torvalds committed
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);
Linus Torvalds's avatar
Linus Torvalds committed
111 112

	flush_dcache_mmap_lock(mapping);
113
	vma_interval_tree_remove(vma, &mapping->i_mmap);
Linus Torvalds's avatar
Linus Torvalds committed
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.
Linus Torvalds's avatar
Linus Torvalds committed
120
 */
121
void unlink_file_vma(struct vm_area_struct *vma)
Linus Torvalds's avatar
Linus Torvalds committed
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);
Linus Torvalds's avatar
Linus Torvalds committed
128
		__remove_shared_vm_struct(vma, file, mapping);
129
		i_mmap_unlock_write(mapping);
Linus Torvalds's avatar
Linus Torvalds committed
130
	}
131 132 133
}

/*
134
 * Close a vm structure and free it.
135
 */
136
static void remove_vma(struct vm_area_struct *vma)
137 138
{
	might_sleep();
Linus Torvalds's avatar
Linus Torvalds committed
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);
Linus Torvalds's avatar
Linus Torvalds committed
145 146
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
static inline struct vm_area_struct *vma_prev_limit(struct vma_iterator *vmi,
						    unsigned long min)
{
	return mas_prev(&vmi->mas, min);
}

static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
			unsigned long start, unsigned long end, gfp_t gfp)
{
	vmi->mas.index = start;
	vmi->mas.last = end - 1;
	mas_store_gfp(&vmi->mas, NULL, gfp);
	if (unlikely(mas_is_err(&vmi->mas)))
		return -ENOMEM;

	return 0;
}

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/*
 * 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);
}
183
static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
184
		unsigned long addr, unsigned long request, unsigned long flags);
185
SYSCALL_DEFINE1(brk, unsigned long, brk)
Linus Torvalds's avatar
Linus Torvalds committed
186
{
187
	unsigned long newbrk, oldbrk, origbrk;
Linus Torvalds's avatar
Linus Torvalds committed
188
	struct mm_struct *mm = current->mm;
189
	struct vm_area_struct *brkvma, *next = NULL;
190
	unsigned long min_brk;
191
	bool populate;
192
	bool downgraded = false;
193
	LIST_HEAD(uf);
194
	struct vma_iterator vmi;
Linus Torvalds's avatar
Linus Torvalds committed
195

196
	if (mmap_write_lock_killable(mm))
197
		return -EINTR;
Linus Torvalds's avatar
Linus Torvalds committed
198

199 200
	origbrk = mm->brk;

201
#ifdef CONFIG_COMPAT_BRK
202 203 204 205 206
	/*
	 * 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
	 */
207
	if (current->brk_randomized)
208 209 210
		min_brk = mm->start_brk;
	else
		min_brk = mm->end_data;
211 212 213 214
#else
	min_brk = mm->start_brk;
#endif
	if (brk < min_brk)
Linus Torvalds's avatar
Linus Torvalds committed
215
		goto out;
Ram Gupta's avatar
Ram Gupta committed
216 217 218 219 220 221 222

	/*
	 * 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
	 */
223 224
	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
			      mm->end_data, mm->start_data))
Ram Gupta's avatar
Ram Gupta committed
225 226
		goto out;

Linus Torvalds's avatar
Linus Torvalds committed
227 228
	newbrk = PAGE_ALIGN(brk);
	oldbrk = PAGE_ALIGN(mm->brk);
229 230 231 232
	if (oldbrk == newbrk) {
		mm->brk = brk;
		goto success;
	}
Linus Torvalds's avatar
Linus Torvalds committed
233

234 235
	/*
	 * Always allow shrinking brk.
236
	 * do_vma_munmap() may downgrade mmap_lock to read.
237
	 */
Linus Torvalds's avatar
Linus Torvalds committed
238
	if (brk <= mm->brk) {
239 240
		int ret;

241
		/* Search one past newbrk */
242 243
		vma_iter_init(&vmi, mm, newbrk);
		brkvma = vma_find(&vmi, oldbrk);
244
		if (!brkvma || brkvma->vm_start >= oldbrk)
245
			goto out; /* mapping intersects with an existing non-brk vma. */
246
		/*
247
		 * mm->brk must be protected by write mmap_lock.
248 249
		 * do_vma_munmap() may downgrade the lock,  so update it
		 * before calling do_vma_munmap().
250 251
		 */
		mm->brk = brk;
252
		ret = do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true);
253
		if (ret == 1)  {
254
			downgraded = true;
255 256 257 258 259 260
			goto success;
		} else if (!ret)
			goto success;

		mm->brk = origbrk;
		goto out;
Linus Torvalds's avatar
Linus Torvalds committed
261 262
	}

263 264 265 266 267 268 269
	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
	 */
270 271
	vma_iter_init(&vmi, mm, oldbrk);
	next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
272
	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
Linus Torvalds's avatar
Linus Torvalds committed
273 274
		goto out;

275
	brkvma = vma_prev_limit(&vmi, mm->start_brk);
Linus Torvalds's avatar
Linus Torvalds committed
276
	/* Ok, looks good - let it rip. */
277
	if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
Linus Torvalds's avatar
Linus Torvalds committed
278
		goto out;
279

Linus Torvalds's avatar
Linus Torvalds committed
280
	mm->brk = brk;
281 282

success:
283
	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
284
	if (downgraded)
285
		mmap_read_unlock(mm);
286
	else
287
		mmap_write_unlock(mm);
288
	userfaultfd_unmap_complete(mm, &uf);
289 290 291 292
	if (populate)
		mm_populate(oldbrk, newbrk - oldbrk);
	return brk;

Linus Torvalds's avatar
Linus Torvalds committed
293
out:
294
	mmap_write_unlock(mm);
295
	return origbrk;
Linus Torvalds's avatar
Linus Torvalds committed
296 297
}

298 299 300
#if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
extern void mt_validate(struct maple_tree *mt);
extern void mt_dump(const struct maple_tree *mt);
Linus Torvalds's avatar
Linus Torvalds committed
301

302 303 304 305
/* Validate the maple tree */
static void validate_mm_mt(struct mm_struct *mm)
{
	struct maple_tree *mt = &mm->mm_mt;
306
	struct vm_area_struct *vma_mt;
307 308 309 310 311

	MA_STATE(mas, mt, 0, 0);

	mt_validate(&mm->mm_mt);
	mas_for_each(&mas, vma_mt, ULONG_MAX) {
312 313
		if ((vma_mt->vm_start != mas.index) ||
		    (vma_mt->vm_end - 1 != mas.last)) {
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
			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);
		}
	}
}
Linus Torvalds's avatar
Linus Torvalds committed
339

340
static void validate_mm(struct mm_struct *mm)
Linus Torvalds's avatar
Linus Torvalds committed
341 342 343
{
	int bug = 0;
	int i = 0;
344 345
	struct vm_area_struct *vma;
	MA_STATE(mas, &mm->mm_mt, 0, 0);
346

Liam R. Howlett's avatar
Liam R. Howlett committed
347 348
	validate_mm_mt(mm);

349
	mas_for_each(&mas, vma, ULONG_MAX) {
Liam R. Howlett's avatar
Liam R. Howlett committed
350
#ifdef CONFIG_DEBUG_VM_RB
351
		struct anon_vma *anon_vma = vma->anon_vma;
352
		struct anon_vma_chain *avc;
353

354 355 356 357 358 359
		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);
		}
Liam R. Howlett's avatar
Liam R. Howlett committed
360
#endif
Linus Torvalds's avatar
Linus Torvalds committed
361 362
		i++;
	}
363
	if (i != mm->map_count) {
364
		pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
365 366
		bug = 1;
	}
367
	VM_BUG_ON_MM(bug, mm);
Linus Torvalds's avatar
Linus Torvalds committed
368
}
Liam R. Howlett's avatar
Liam R. Howlett committed
369 370

#else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
371
#define validate_mm_mt(root) do { } while (0)
Linus Torvalds's avatar
Linus Torvalds committed
372
#define validate_mm(mm) do { } while (0)
Liam R. Howlett's avatar
Liam R. Howlett committed
373
#endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
374

375 376 377 378 379 380 381 382 383 384 385
/*
 * 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().
 *
386
 * The entire update must be protected by exclusive mmap_lock and by
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
 * 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);
}

407 408 409
static unsigned long count_vma_pages_range(struct mm_struct *mm,
		unsigned long addr, unsigned long end)
{
410
	VMA_ITERATOR(vmi, mm, addr);
411
	struct vm_area_struct *vma;
412
	unsigned long nr_pages = 0;
413

414 415 416
	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);
417

418
		nr_pages += PHYS_PFN(vm_end - vm_start);
419 420 421 422 423
	}

	return nr_pages;
}

424 425
static void __vma_link_file(struct vm_area_struct *vma,
			    struct address_space *mapping)
Linus Torvalds's avatar
Linus Torvalds committed
426
{
427 428
	if (vma->vm_flags & VM_SHARED)
		mapping_allow_writable(mapping);
Linus Torvalds's avatar
Linus Torvalds committed
429

430 431 432
	flush_dcache_mmap_lock(mapping);
	vma_interval_tree_insert(vma, &mapping->i_mmap);
	flush_dcache_mmap_unlock(mapping);
Linus Torvalds's avatar
Linus Torvalds committed
433 434
}

435
static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
Linus Torvalds's avatar
Linus Torvalds committed
436
{
437
	VMA_ITERATOR(vmi, mm, 0);
Linus Torvalds's avatar
Linus Torvalds committed
438 439
	struct address_space *mapping = NULL;

440
	if (vma_iter_prealloc(&vmi))
441 442
		return -ENOMEM;

443
	if (vma->vm_file) {
Linus Torvalds's avatar
Linus Torvalds committed
444
		mapping = vma->vm_file->f_mapping;
445
		i_mmap_lock_write(mapping);
446
	}
Linus Torvalds's avatar
Linus Torvalds committed
447

448
	vma_iter_store(&vmi, vma);
Linus Torvalds's avatar
Linus Torvalds committed
449

450 451
	if (mapping) {
		__vma_link_file(vma, mapping);
452
		i_mmap_unlock_write(mapping);
453
	}
Linus Torvalds's avatar
Linus Torvalds committed
454 455 456

	mm->map_count++;
	validate_mm(mm);
457
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
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
/*
 * init_multi_vma_prep() - Initializer for struct vma_prepare
 * @vp: The vma_prepare struct
 * @vma: The vma that will be altered once locked
 * @next: The next vma if it is to be adjusted
 * @remove: The first vma to be removed
 * @remove2: The second vma to be removed
 */
static inline void init_multi_vma_prep(struct vma_prepare *vp,
		struct vm_area_struct *vma, struct vm_area_struct *next,
		struct vm_area_struct *remove, struct vm_area_struct *remove2)
{
	memset(vp, 0, sizeof(struct vma_prepare));
	vp->vma = vma;
	vp->anon_vma = vma->anon_vma;
	vp->remove = remove;
	vp->remove2 = remove2;
	vp->adj_next = next;
	if (!vp->anon_vma && next)
		vp->anon_vma = next->anon_vma;

	vp->file = vma->vm_file;
	if (vp->file)
		vp->mapping = vma->vm_file->f_mapping;

}

/*
 * init_vma_prep() - Initializer wrapper for vma_prepare struct
 * @vp: The vma_prepare struct
 * @vma: The vma that will be altered once locked
 */
static inline void init_vma_prep(struct vma_prepare *vp,
				 struct vm_area_struct *vma)
{
	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
}


499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 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 605 606 607
/*
 * vma_prepare() - Helper function for handling locking VMAs prior to altering
 * @vp: The initialized vma_prepare struct
 */
static inline void vma_prepare(struct vma_prepare *vp)
{
	if (vp->file) {
		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);

		if (vp->adj_next)
			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
				      vp->adj_next->vm_end);

		i_mmap_lock_write(vp->mapping);
		if (vp->insert && vp->insert->vm_file) {
			/*
			 * Put into interval tree now, so instantiated pages
			 * 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(vp->insert,
					vp->insert->vm_file->f_mapping);
		}
	}

	if (vp->anon_vma) {
		anon_vma_lock_write(vp->anon_vma);
		anon_vma_interval_tree_pre_update_vma(vp->vma);
		if (vp->adj_next)
			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
	}

	if (vp->file) {
		flush_dcache_mmap_lock(vp->mapping);
		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
		if (vp->adj_next)
			vma_interval_tree_remove(vp->adj_next,
						 &vp->mapping->i_mmap);
	}

}

/*
 * vma_complete- Helper function for handling the unlocking after altering VMAs,
 * or for inserting a VMA.
 *
 * @vp: The vma_prepare struct
 * @vmi: The vma iterator
 * @mm: The mm_struct
 */
static inline void vma_complete(struct vma_prepare *vp,
				struct vma_iterator *vmi, struct mm_struct *mm)
{
	if (vp->file) {
		if (vp->adj_next)
			vma_interval_tree_insert(vp->adj_next,
						 &vp->mapping->i_mmap);
		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
		flush_dcache_mmap_unlock(vp->mapping);
	}

	if (vp->remove && vp->file) {
		__remove_shared_vm_struct(vp->remove, vp->file, vp->mapping);
		if (vp->remove2)
			__remove_shared_vm_struct(vp->remove2, vp->file,
						  vp->mapping);
	} else if (vp->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).
		 */
		vma_iter_store(vmi, vp->insert);
		mm->map_count++;
	}

	if (vp->anon_vma) {
		anon_vma_interval_tree_post_update_vma(vp->vma);
		if (vp->adj_next)
			anon_vma_interval_tree_post_update_vma(vp->adj_next);
		anon_vma_unlock_write(vp->anon_vma);
	}

	if (vp->file) {
		i_mmap_unlock_write(vp->mapping);
		uprobe_mmap(vp->vma);

		if (vp->adj_next)
			uprobe_mmap(vp->adj_next);
	}

	if (vp->remove) {
again:
		if (vp->file) {
			uprobe_munmap(vp->remove, vp->remove->vm_start,
				      vp->remove->vm_end);
			fput(vp->file);
		}
		if (vp->remove->anon_vma)
			anon_vma_merge(vp->vma, vp->remove);
		mm->map_count--;
		mpol_put(vma_policy(vp->remove));
		if (!vp->remove2)
			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
		vm_area_free(vp->remove);

		/*
		 * In mprotect's case 6 (see comments on vma_merge),
608
		 * we must remove the one after next as well.
609 610 611 612 613 614 615 616 617 618 619
		 */
		if (vp->remove2) {
			vp->remove = vp->remove2;
			vp->remove2 = NULL;
			goto again;
		}
	}
	if (vp->insert && vp->file)
		uprobe_mmap(vp->insert);
}

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
/*
 * vma_expand - Expand an existing VMA
 *
 * @vmi: The vma iterator
 * @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
 */
637 638 639
int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
	       unsigned long start, unsigned long end, pgoff_t pgoff,
	       struct vm_area_struct *next)
640
{
641
	bool remove_next = false;
642 643 644
	struct vma_prepare vp;

	if (next && (vma != next) && (end == next->vm_end)) {
645
		remove_next = true;
646 647 648 649 650 651 652 653 654 655
		if (next->anon_vma && !vma->anon_vma) {
			int error;

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

656
	init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
	/* Not merging but overwriting any part of next is not handled. */
	VM_WARN_ON(next && !vp.remove &&
		  next != vma && end > next->vm_start);
	/* Only handles expanding */
	VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);

	if (vma_iter_prealloc(vmi))
		goto nomem;

	vma_adjust_trans_huge(vma, start, end, 0);
	/* VMA iterator points to previous, so set to start if necessary */
	if (vma_iter_addr(vmi) != start)
		vma_iter_set(vmi, start);

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

	vma_complete(&vp, vmi, vma->vm_mm);
	validate_mm(vma->vm_mm);
	return 0;

nomem:
	return -ENOMEM;
}
Linus Torvalds's avatar
Linus Torvalds committed
685 686 687 688 689 690 691
/*
 * 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.
 */
692 693
int __vma_adjust(struct vma_iterator *vmi, struct vm_area_struct *vma,
	unsigned long start, unsigned long end, pgoff_t pgoff,
694
	struct vm_area_struct *expand)
Linus Torvalds's avatar
Linus Torvalds committed
695 696
{
	struct mm_struct *mm = vma->vm_mm;
697 698
	struct vm_area_struct *remove2 = NULL;
	struct vm_area_struct *remove = NULL;
699
	struct vm_area_struct *next = find_vma(mm, vma->vm_end);
Liam R. Howlett's avatar
Liam R. Howlett committed
700
	struct vm_area_struct *orig_vma = vma;
Linus Torvalds's avatar
Linus Torvalds committed
701
	struct file *file = vma->vm_file;
Liam R. Howlett's avatar
Liam R. Howlett committed
702
	bool vma_changed = false;
Linus Torvalds's avatar
Linus Torvalds committed
703
	long adjust_next = 0;
704
	struct vm_area_struct *exporter = NULL, *importer = NULL;
705
	struct vma_prepare vma_prep;
Linus Torvalds's avatar
Linus Torvalds committed
706

707
	if (next) {
Linus Torvalds's avatar
Linus Torvalds committed
708 709 710 711
		if (end >= next->vm_end) {
			/*
			 * vma expands, overlapping all the next, and
			 * perhaps the one after too (mprotect case 6).
712
			 * The only other cases that gets here are
713
			 * case 1, case 7 and case 8.
Linus Torvalds's avatar
Linus Torvalds committed
714
			 */
715 716 717 718 719 720 721
			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);
				/*
722
				 * we're removing "vma" and that to do so we
723 724 725 726
				 * swapped "vma" and "next".
				 */
				VM_WARN_ON(file != next->vm_file);
				swap(vma, next);
727
				remove = next;
728 729 730
			} else {
				VM_WARN_ON(expand != vma);
				/*
731 732
				 * case 1, 6, 7, remove next.
				 * case 6 also removes the one beyond next
733
				 */
734 735 736
				remove = next;
				if (end > next->vm_end)
					remove2 = find_vma(mm, next->vm_end);
737

738 739
				VM_WARN_ON(remove2 != NULL &&
					   end != remove2->vm_end);
740 741
			}

742
			exporter = next;
Linus Torvalds's avatar
Linus Torvalds committed
743
			importer = vma;
744 745 746 747 748

			/*
			 * If next doesn't have anon_vma, import from vma after
			 * next, if the vma overlaps with it.
			 */
749 750
			if (remove2 != NULL && !next->anon_vma)
				exporter = remove2;
751

Linus Torvalds's avatar
Linus Torvalds committed
752 753 754 755 756
		} else if (end > next->vm_start) {
			/*
			 * vma expands, overlapping part of the next:
			 * mprotect case 5 shifting the boundary up.
			 */
757
			adjust_next = (end - next->vm_start);
758
			exporter = next;
Linus Torvalds's avatar
Linus Torvalds committed
759
			importer = vma;
760
			VM_WARN_ON(expand != importer);
Linus Torvalds's avatar
Linus Torvalds committed
761 762 763 764 765 766
		} 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.
			 */
767
			adjust_next = -(vma->vm_end - end);
768
			exporter = vma;
Linus Torvalds's avatar
Linus Torvalds committed
769
			importer = next;
770
			VM_WARN_ON(expand != importer);
Linus Torvalds's avatar
Linus Torvalds committed
771 772
		}

773 774 775 776 777
		/*
		 * 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.
		 */
778
		if (exporter && exporter->anon_vma && !importer->anon_vma) {
779 780
			int error;

781
			importer->anon_vma = exporter->anon_vma;
782
			error = anon_vma_clone(importer, exporter);
783
			if (error)
784
				return error;
785 786
		}
	}
787

788
	if (vma_iter_prealloc(vmi))
789 790 791
		return -ENOMEM;

	vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
Linus Torvalds's avatar
Linus Torvalds committed
792

793 794 795 796
	init_multi_vma_prep(&vma_prep, vma, adjust_next ? next : NULL, remove,
			    remove2);
	VM_WARN_ON(vma_prep.anon_vma && adjust_next && next->anon_vma &&
		   vma_prep.anon_vma != next->anon_vma);
797

798
	vma_prepare(&vma_prep);
Linus Torvalds's avatar
Linus Torvalds committed
799

800 801 802 803 804 805 806 807 808 809 810 811 812
	if (vma->vm_start < start)
		vma_iter_clear(vmi, vma->vm_start, start);
	else if (start != vma->vm_start)
		vma_changed = true;

	if (vma->vm_end > end)
		vma_iter_clear(vmi, end, vma->vm_end);
	else if (end != vma->vm_end)
		vma_changed = true;

	vma->vm_start = start;
	vma->vm_end = end;
	vma->vm_pgoff = pgoff;
813

Liam R. Howlett's avatar
Liam R. Howlett committed
814
	if (vma_changed)
815
		vma_iter_store(vmi, vma);
816

Linus Torvalds's avatar
Linus Torvalds committed
817
	if (adjust_next) {
818 819
		next->vm_start += adjust_next;
		next->vm_pgoff += adjust_next >> PAGE_SHIFT;
820
		vma_iter_store(vmi, next);
Linus Torvalds's avatar
Linus Torvalds committed
821 822
	}

823
	vma_complete(&vma_prep, vmi, mm);
824
	vma_iter_free(vmi);
Linus Torvalds's avatar
Linus Torvalds committed
825
	validate_mm(mm);
826

827
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
828 829 830 831 832 833 834
}

/*
 * 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,
835 836 837
				   struct file *file, unsigned long vm_flags,
				   struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
				   struct anon_vma_name *anon_name)
Linus Torvalds's avatar
Linus Torvalds committed
838
{
839 840 841 842
	/*
	 * 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
843
	 * comparison, we increase pressure on the memory system forcing
844 845 846 847
	 * the kernel to generate new VMAs when old one could be
	 * extended instead.
	 */
	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
Linus Torvalds's avatar
Linus Torvalds committed
848 849 850 851 852
		return 0;
	if (vma->vm_file != file)
		return 0;
	if (vma->vm_ops && vma->vm_ops->close)
		return 0;
853 854
	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
		return 0;
855
	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
856
		return 0;
Linus Torvalds's avatar
Linus Torvalds committed
857 858 859 860
	return 1;
}

static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
Shaohua Li's avatar
Shaohua Li committed
861 862
					struct anon_vma *anon_vma2,
					struct vm_area_struct *vma)
Linus Torvalds's avatar
Linus Torvalds committed
863
{
Shaohua Li's avatar
Shaohua Li committed
864 865 866 867 868 869 870 871
	/*
	 * 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;
Linus Torvalds's avatar
Linus Torvalds committed
872 873 874 875 876 877 878 879 880 881
}

/*
 * 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
882
 * indices (16TB on ia32) because do_mmap() does not permit mmap's which
Linus Torvalds's avatar
Linus Torvalds committed
883 884 885 886
 * 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,
887 888
		     struct anon_vma *anon_vma, struct file *file,
		     pgoff_t vm_pgoff,
889
		     struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
890
		     struct anon_vma_name *anon_name)
Linus Torvalds's avatar
Linus Torvalds committed
891
{
892
	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
Shaohua Li's avatar
Shaohua Li committed
893
	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
Linus Torvalds's avatar
Linus Torvalds committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
		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,
909 910
		    struct anon_vma *anon_vma, struct file *file,
		    pgoff_t vm_pgoff,
911
		    struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
912
		    struct anon_vma_name *anon_name)
Linus Torvalds's avatar
Linus Torvalds committed
913
{
914
	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
Shaohua Li's avatar
Shaohua Li committed
915
	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
Linus Torvalds's avatar
Linus Torvalds committed
916
		pgoff_t vm_pglen;
917
		vm_pglen = vma_pages(vma);
Linus Torvalds's avatar
Linus Torvalds committed
918 919 920 921 922 923 924
		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
			return 1;
	}
	return 0;
}

/*
925 926 927
 * 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).
Linus Torvalds's avatar
Linus Torvalds committed
928 929 930 931 932 933 934 935 936 937 938 939
 *
 * 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:
 *
940 941 942 943 944 945 946 947 948 949 950 951
 *     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
Linus Torvalds's avatar
Linus Torvalds committed
952
 *
953
 * It is important for case 8 that the vma NNNN overlapping the
954 955 956 957 958 959 960 961 962 963 964 965
 * 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.
Linus Torvalds's avatar
Linus Torvalds committed
966
 */
967
struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
Linus Torvalds's avatar
Linus Torvalds committed
968 969
			struct vm_area_struct *prev, unsigned long addr,
			unsigned long end, unsigned long vm_flags,
vishnu.ps's avatar
vishnu.ps committed
970
			struct anon_vma *anon_vma, struct file *file,
971
			pgoff_t pgoff, struct mempolicy *policy,
972
			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
973
			struct anon_vma_name *anon_name)
Linus Torvalds's avatar
Linus Torvalds committed
974 975
{
	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
976
	struct vm_area_struct *mid, *next, *res = NULL;
977 978 979
	int err = -1;
	bool merge_prev = false;
	bool merge_next = false;
Linus Torvalds's avatar
Linus Torvalds committed
980 981 982 983 984 985 986 987

	/*
	 * 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;

988
	next = find_vma(mm, prev ? prev->vm_end : 0);
989 990
	mid = next;
	if (next && next->vm_end == end)		/* cases 6, 7, 8 */
991
		next = find_vma(mm, next->vm_end);
Linus Torvalds's avatar
Linus Torvalds committed
992

993 994
	/* verify some invariant that must be enforced by the caller */
	VM_WARN_ON(prev && addr <= prev->vm_start);
995
	VM_WARN_ON(mid && end > mid->vm_end);
996 997
	VM_WARN_ON(addr >= end);

998
	/* Can we merge the predecessor? */
Linus Torvalds's avatar
Linus Torvalds committed
999
	if (prev && prev->vm_end == addr &&
vishnu.ps's avatar
vishnu.ps committed
1000
			mpol_equal(vma_policy(prev), policy) &&
Linus Torvalds's avatar
Linus Torvalds committed
1001
			can_vma_merge_after(prev, vm_flags,
1002
					    anon_vma, file, pgoff,
1003
					    vm_userfaultfd_ctx, anon_name)) {
1004
		merge_prev = true;
Linus Torvalds's avatar
Linus Torvalds committed
1005
	}
1006
	/* Can we merge the successor? */
Linus Torvalds's avatar
Linus Torvalds committed
1007
	if (next && end == next->vm_start &&
vishnu.ps's avatar
vishnu.ps committed
1008
			mpol_equal(policy, vma_policy(next)) &&
Linus Torvalds's avatar
Linus Torvalds committed
1009
			can_vma_merge_before(next, vm_flags,
1010
					     anon_vma, file, pgoff+pglen,
1011
					     vm_userfaultfd_ctx, anon_name)) {
1012 1013 1014 1015 1016 1017
		merge_next = true;
	}
	/* Can we merge both the predecessor and the successor? */
	if (merge_prev && merge_next &&
			is_mergeable_anon_vma(prev->anon_vma,
				next->anon_vma, NULL)) {	 /* cases 1, 6 */
1018
		err = __vma_adjust(vmi, prev, prev->vm_start,
1019
					next->vm_end, prev->vm_pgoff, prev);
1020 1021
		res = prev;
	} else if (merge_prev) {			/* cases 2, 5, 7 */
1022
		err = __vma_adjust(vmi, prev, prev->vm_start,
1023
					end, prev->vm_pgoff, prev);
1024 1025
		res = prev;
	} else if (merge_next) {
Linus Torvalds's avatar
Linus Torvalds committed
1026
		if (prev && addr < prev->vm_end)	/* case 4 */
1027
			err = __vma_adjust(vmi, prev, prev->vm_start,
1028
					addr, prev->vm_pgoff, next);
1029
		else					/* cases 3, 8 */
1030
			err = __vma_adjust(vmi, mid, addr, next->vm_end,
1031
					next->vm_pgoff - pglen, next);
1032
		res = next;
Linus Torvalds's avatar
Linus Torvalds committed
1033 1034
	}

1035 1036 1037 1038 1039 1040
	/*
	 * Cannot merge with predecessor or successor or error in __vma_adjust?
	 */
	if (err)
		return NULL;
	khugepaged_enter_vma(res, vm_flags);
Linus Torvalds's avatar
Linus Torvalds committed
1041

1042
	if (res)
1043 1044
		vma_iter_set(vmi, end);

1045
	return res;
1046 1047
}

1048
/*
1049
 * Rough compatibility check to quickly see if it's even worth looking
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
 * 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 &&
1066
		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1067 1068 1069 1070 1071 1072 1073 1074 1075
		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.
 *
1076
 * NOTE! This runs with mmap_lock held for reading, so it is possible that
1077 1078 1079 1080
 * 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
1081
 * we do that READ_ONCE() to make sure that we never re-load the pointer.
1082 1083 1084 1085 1086 1087 1088 1089
 *
 * 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
1090
 * a read lock on the mmap_lock.
1091 1092 1093 1094
 */
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)) {
1095
		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1096 1097 1098 1099 1100 1101 1102

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

Linus Torvalds's avatar
Linus Torvalds committed
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
/*
 * 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)
{
1113
	MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1114
	struct anon_vma *anon_vma = NULL;
1115
	struct vm_area_struct *prev, *next;
1116 1117

	/* Try next first. */
1118 1119 1120
	next = mas_walk(&mas);
	if (next) {
		anon_vma = reusable_anon_vma(next, vma, next);
1121 1122 1123 1124
		if (anon_vma)
			return anon_vma;
	}

1125 1126 1127
	prev = mas_prev(&mas, 0);
	VM_BUG_ON_VMA(prev != vma, vma);
	prev = mas_prev(&mas, 0);
1128
	/* Try prev next. */
1129 1130
	if (prev)
		anon_vma = reusable_anon_vma(prev, prev, vma);
1131

Linus Torvalds's avatar
Linus Torvalds committed
1132
	/*
1133 1134
	 * We might reach here with anon_vma == NULL if we can't find
	 * any reusable anon_vma.
Linus Torvalds's avatar
Linus Torvalds committed
1135 1136 1137 1138 1139 1140 1141
	 * 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.
	 */
1142
	return anon_vma;
Linus Torvalds's avatar
Linus Torvalds committed
1143 1144
}

Al Viro's avatar
Al Viro committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
/*
 * 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;
}

1158 1159
int mlock_future_check(struct mm_struct *mm, unsigned long flags,
		       unsigned long len)
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
{
	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;
}

1175 1176 1177
static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
{
	if (S_ISREG(inode->i_mode))
1178
		return MAX_LFS_FILESIZE;
1179 1180 1181 1182

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

1183 1184 1185
	if (S_ISSOCK(inode->i_mode))
		return MAX_LFS_FILESIZE;

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	/* 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;
}

Linus Torvalds's avatar
Linus Torvalds committed
1207
/*
1208
 * The caller must write-lock current->mm->mmap_lock.
Linus Torvalds's avatar
Linus Torvalds committed
1209
 */
1210
unsigned long do_mmap(struct file *file, unsigned long addr,
Linus Torvalds's avatar
Linus Torvalds committed
1211
			unsigned long len, unsigned long prot,
1212 1213
			unsigned long flags, unsigned long pgoff,
			unsigned long *populate, struct list_head *uf)
Linus Torvalds's avatar
Linus Torvalds committed
1214
{
vishnu.ps's avatar
vishnu.ps committed
1215
	struct mm_struct *mm = current->mm;
1216
	vm_flags_t vm_flags;
1217
	int pkey = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1218

Liam R. Howlett's avatar
Liam R. Howlett committed
1219
	validate_mm(mm);
1220
	*populate = 0;
1221

1222 1223 1224
	if (!len)
		return -EINVAL;

Linus Torvalds's avatar
Linus Torvalds committed
1225 1226 1227 1228 1229 1230 1231
	/*
	 * 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))
1232
		if (!(file && path_noexec(&file->f_path)))
Linus Torvalds's avatar
Linus Torvalds committed
1233 1234
			prot |= PROT_EXEC;

1235 1236 1237 1238
	/* force arch specific MAP_FIXED handling in get_unmapped_area */
	if (flags & MAP_FIXED_NOREPLACE)
		flags |= MAP_FIXED;

1239 1240 1241
	if (!(flags & MAP_FIXED))
		addr = round_hint_to_min(addr);

Linus Torvalds's avatar
Linus Torvalds committed
1242 1243
	/* Careful about overflows.. */
	len = PAGE_ALIGN(len);
1244
	if (!len)
Linus Torvalds's avatar
Linus Torvalds committed
1245 1246 1247 1248
		return -ENOMEM;

	/* offset overflow? */
	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
vishnu.ps's avatar
vishnu.ps committed
1249
		return -EOVERFLOW;
Linus Torvalds's avatar
Linus Torvalds committed
1250 1251 1252 1253 1254 1255 1256 1257 1258

	/* 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);
1259
	if (IS_ERR_VALUE(addr))
Linus Torvalds's avatar
Linus Torvalds committed
1260 1261
		return addr;

1262
	if (flags & MAP_FIXED_NOREPLACE) {
1263
		if (find_vma_intersection(mm, addr, addr + len))
1264 1265 1266
			return -EEXIST;
	}

1267 1268 1269 1270 1271 1272
	if (prot == PROT_EXEC) {
		pkey = execute_only_pkey(mm);
		if (pkey < 0)
			pkey = 0;
	}

Linus Torvalds's avatar
Linus Torvalds committed
1273 1274 1275 1276
	/* 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.
	 */
1277
	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
Linus Torvalds's avatar
Linus Torvalds committed
1278 1279
			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;

Huang Shijie's avatar
Huang Shijie committed
1280
	if (flags & MAP_LOCKED)
Linus Torvalds's avatar
Linus Torvalds committed
1281 1282
		if (!can_do_mlock())
			return -EPERM;
1283

1284 1285
	if (mlock_future_check(mm, vm_flags, len))
		return -EAGAIN;
Linus Torvalds's avatar
Linus Torvalds committed
1286 1287

	if (file) {
1288
		struct inode *inode = file_inode(file);
1289 1290
		unsigned long flags_mask;

1291 1292 1293
		if (!file_mmap_ok(file, inode, pgoff, len))
			return -EOVERFLOW;

1294
		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1295

Linus Torvalds's avatar
Linus Torvalds committed
1296 1297
		switch (flags & MAP_TYPE) {
		case MAP_SHARED:
1298 1299 1300 1301 1302 1303 1304 1305
			/*
			 * 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;
Joe Perches's avatar
Joe Perches committed
1306
			fallthrough;
1307 1308 1309
		case MAP_SHARED_VALIDATE:
			if (flags & ~flags_mask)
				return -EOPNOTSUPP;
1310 1311 1312 1313 1314 1315
			if (prot & PROT_WRITE) {
				if (!(file->f_mode & FMODE_WRITE))
					return -EACCES;
				if (IS_SWAPFILE(file->f_mapping->host))
					return -ETXTBSY;
			}
Linus Torvalds's avatar
Linus Torvalds committed
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326

			/*
			 * 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);
Joe Perches's avatar
Joe Perches committed
1327
			fallthrough;
Linus Torvalds's avatar
Linus Torvalds committed
1328 1329 1330
		case MAP_PRIVATE:
			if (!(file->f_mode & FMODE_READ))
				return -EACCES;
1331
			if (path_noexec(&file->f_path)) {
Linus Torvalds's avatar
Linus Torvalds committed
1332 1333 1334 1335 1336
				if (vm_flags & VM_EXEC)
					return -EPERM;
				vm_flags &= ~VM_MAYEXEC;
			}

Al Viro's avatar
Al Viro committed
1337
			if (!file->f_op->mmap)
Linus Torvalds's avatar
Linus Torvalds committed
1338
				return -ENODEV;
1339 1340
			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
				return -EINVAL;
Linus Torvalds's avatar
Linus Torvalds committed
1341 1342 1343 1344 1345 1346 1347 1348
			break;

		default:
			return -EINVAL;
		}
	} else {
		switch (flags & MAP_TYPE) {
		case MAP_SHARED:
1349 1350
			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
				return -EINVAL;
1351 1352 1353 1354
			/*
			 * Ignore pgoff.
			 */
			pgoff = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
			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;
		}
	}

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
	/*
	 * 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;
	}

1382
	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1383 1384 1385
	if (!IS_ERR_VALUE(addr) &&
	    ((vm_flags & VM_LOCKED) ||
	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1386
		*populate = len;
1387
	return addr;
Miklos Szeredi's avatar
Miklos Szeredi committed
1388
}
1389

1390 1391 1392
unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
			      unsigned long prot, unsigned long flags,
			      unsigned long fd, unsigned long pgoff)
1393 1394
{
	struct file *file = NULL;
1395
	unsigned long retval;
1396 1397

	if (!(flags & MAP_ANONYMOUS)) {
Al Viro's avatar
Al Viro committed
1398
		audit_mmap_fd(fd, flags);
1399 1400
		file = fget(fd);
		if (!file)
1401
			return -EBADF;
1402
		if (is_file_hugepages(file)) {
1403
			len = ALIGN(len, huge_page_size(hstate_file(file)));
1404 1405
		} else if (unlikely(flags & MAP_HUGETLB)) {
			retval = -EINVAL;
1406
			goto out_fput;
1407
		}
1408
	} else if (flags & MAP_HUGETLB) {
1409
		struct hstate *hs;
1410

1411
		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1412 1413 1414 1415
		if (!hs)
			return -EINVAL;

		len = ALIGN(len, huge_page_size(hs));
1416 1417 1418 1419
		/*
		 * VM_NORESERVE is used because the reservations will be
		 * taken when vm_ops->mmap() is called
		 */
1420
		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1421
				VM_NORESERVE,
1422
				HUGETLB_ANONHUGE_INODE,
1423
				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1424 1425 1426 1427
		if (IS_ERR(file))
			return PTR_ERR(file);
	}

Michal Hocko's avatar
Michal Hocko committed
1428
	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1429
out_fput:
1430 1431 1432 1433 1434
	if (file)
		fput(file);
	return retval;
}

1435 1436 1437 1438 1439 1440 1441
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);
}

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
#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;
1458
	if (offset_in_page(a.offset))
1459 1460
		return -EINVAL;

1461 1462
	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
			       a.offset >> PAGE_SHIFT);
1463 1464 1465
}
#endif /* __ARCH_WANT_SYS_OLD_MMAP */

Alexey Dobriyan's avatar
Alexey Dobriyan committed
1466
/*
1467
 * Some shared mappings will want the pages marked read-only
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1468 1469 1470 1471
 * to track write events. If so, we'll downgrade vm_page_prot
 * to the private version (using protection_map[] without the
 * VM_SHARED bit).
 */
1472
int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1473
{
1474
	vm_flags_t vm_flags = vma->vm_flags;
1475
	const struct vm_operations_struct *vm_ops = vma->vm_ops;
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1476 1477 1478 1479 1480 1481

	/* 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? */
1482
	if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1483 1484
		return 1;

1485 1486
	/* The open routine did something to the protections that pgprot_modify
	 * won't preserve? */
1487 1488
	if (pgprot_val(vm_page_prot) !=
	    pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1489 1490
		return 0;

1491 1492 1493 1494 1495
	/*
	 * Do we need to track softdirty? hugetlb does not support softdirty
	 * tracking yet.
	 */
	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1496 1497
		return 1;

1498 1499 1500 1501
	/* Do we need write faults for uffd-wp tracking? */
	if (userfaultfd_wp(vma))
		return 1;

Alexey Dobriyan's avatar
Alexey Dobriyan committed
1502
	/* Specialty mapping? */
1503
	if (vm_flags & VM_PFNMAP)
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1504 1505 1506 1507
		return 0;

	/* Can the mapping track the dirty pages? */
	return vma->vm_file && vma->vm_file->f_mapping &&
1508
		mapping_can_writeback(vma->vm_file->f_mapping);
Alexey Dobriyan's avatar
Alexey Dobriyan committed
1509 1510
}

1511 1512
/*
 * We account for memory if it's a private writeable mapping,
1513
 * not hugepages and VM_NORESERVE wasn't set.
1514
 */
1515
static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1516
{
1517 1518 1519 1520 1521 1522 1523
	/*
	 * 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;

1524 1525 1526
	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
}

1527 1528 1529 1530 1531
/**
 * 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.
 *
1532 1533
 * @info: The unmapped area information including the range [low_limit -
 * high_limit), the alignment offset and mask.
1534 1535 1536
 *
 * Return: A memory address or -ENOMEM.
 */
1537
static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1538
{
1539
	unsigned long length, gap;
1540

1541
	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1542 1543 1544 1545 1546 1547

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

1548 1549
	if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
				  length))
1550 1551
		return -ENOMEM;

1552 1553 1554
	gap = mas.index;
	gap += (info->align_offset - gap) & info->align_mask;
	return gap;
1555 1556
}

1557 1558
/**
 * unmapped_area_topdown() - Find an area between the low_limit and the
1559
 * high_limit with the correct alignment and offset at the highest available
1560 1561
 * address, all from @info. Note: current->mm is used for the search.
 *
1562 1563
 * @info: The unmapped area information including the range [low_limit -
 * high_limit), the alignment offset and mask.
1564 1565 1566
 *
 * Return: A memory address or -ENOMEM.
 */
1567
static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1568
{
1569
	unsigned long length, gap;
1570

1571
	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1572 1573 1574 1575 1576
	/* Adjust search length to account for worst case alignment overhead */
	length = info->length + info->align_mask;
	if (length < info->length)
		return -ENOMEM;

1577 1578
	if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
				length))
1579 1580
		return -ENOMEM;

1581 1582 1583
	gap = mas.last + 1 - info->length;
	gap -= (gap - info->align_offset) & info->align_mask;
	return gap;
1584 1585
}

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
/*
 * 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)
{
1597 1598
	unsigned long addr;

1599
	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1600
		addr = unmapped_area_topdown(info);
1601
	else
1602 1603 1604 1605
		addr = unmapped_area(info);

	trace_vm_unmapped_area(addr, info);
	return addr;
1606
}
1607

Linus Torvalds's avatar
Linus Torvalds committed
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
/* 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
1620 1621 1622
generic_get_unmapped_area(struct file *filp, unsigned long addr,
			  unsigned long len, unsigned long pgoff,
			  unsigned long flags)
Linus Torvalds's avatar
Linus Torvalds committed
1623 1624
{
	struct mm_struct *mm = current->mm;
1625
	struct vm_area_struct *vma, *prev;
1626
	struct vm_unmapped_area_info info;
1627
	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
Linus Torvalds's avatar
Linus Torvalds committed
1628

1629
	if (len > mmap_end - mmap_min_addr)
Linus Torvalds's avatar
Linus Torvalds committed
1630 1631
		return -ENOMEM;

1632 1633 1634
	if (flags & MAP_FIXED)
		return addr;

Linus Torvalds's avatar
Linus Torvalds committed
1635 1636
	if (addr) {
		addr = PAGE_ALIGN(addr);
1637
		vma = find_vma_prev(mm, addr, &prev);
1638
		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1639 1640
		    (!vma || addr + len <= vm_start_gap(vma)) &&
		    (!prev || addr >= vm_end_gap(prev)))
Linus Torvalds's avatar
Linus Torvalds committed
1641 1642 1643
			return addr;
	}

1644 1645
	info.flags = 0;
	info.length = len;
1646
	info.low_limit = mm->mmap_base;
1647
	info.high_limit = mmap_end;
1648
	info.align_mask = 0;
1649
	info.align_offset = 0;
1650
	return vm_unmapped_area(&info);
Linus Torvalds's avatar
Linus Torvalds committed
1651
}
1652 1653 1654 1655 1656 1657 1658 1659 1660

#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);
}
vishnu.ps's avatar
vishnu.ps committed
1661
#endif
Linus Torvalds's avatar
Linus Torvalds committed
1662 1663 1664 1665 1666 1667

/*
 * This mmap-allocator allocates new areas top-down from below the
 * stack's low limit (the base):
 */
unsigned long
1668 1669 1670
generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
				  unsigned long len, unsigned long pgoff,
				  unsigned long flags)
Linus Torvalds's avatar
Linus Torvalds committed
1671
{
1672
	struct vm_area_struct *vma, *prev;
Linus Torvalds's avatar
Linus Torvalds committed
1673
	struct mm_struct *mm = current->mm;
1674
	struct vm_unmapped_area_info info;
1675
	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
Linus Torvalds's avatar
Linus Torvalds committed
1676 1677

	/* requested length too big for entire address space */
1678
	if (len > mmap_end - mmap_min_addr)
Linus Torvalds's avatar
Linus Torvalds committed
1679 1680
		return -ENOMEM;

1681 1682 1683
	if (flags & MAP_FIXED)
		return addr;

Linus Torvalds's avatar
Linus Torvalds committed
1684 1685 1686
	/* requesting a specific address */
	if (addr) {
		addr = PAGE_ALIGN(addr);
1687
		vma = find_vma_prev(mm, addr, &prev);
1688
		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1689 1690
				(!vma || addr + len <= vm_start_gap(vma)) &&
				(!prev || addr >= vm_end_gap(prev)))
Linus Torvalds's avatar
Linus Torvalds committed
1691 1692 1693
			return addr;
	}

1694 1695
	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
	info.length = len;
1696
	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1697
	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1698
	info.align_mask = 0;
1699
	info.align_offset = 0;
1700
	addr = vm_unmapped_area(&info);
1701

Linus Torvalds's avatar
Linus Torvalds committed
1702 1703 1704 1705 1706 1707
	/*
	 * 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.
	 */
1708
	if (offset_in_page(addr)) {
1709 1710 1711
		VM_BUG_ON(addr != -ENOMEM);
		info.flags = 0;
		info.low_limit = TASK_UNMAPPED_BASE;
1712
		info.high_limit = mmap_end;
1713 1714
		addr = vm_unmapped_area(&info);
	}
Linus Torvalds's avatar
Linus Torvalds committed
1715 1716 1717

	return addr;
}
1718 1719 1720 1721 1722 1723 1724 1725 1726

#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);
}
Linus Torvalds's avatar
Linus Torvalds committed
1727 1728 1729 1730 1731 1732
#endif

unsigned long
get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
		unsigned long pgoff, unsigned long flags)
{
1733 1734 1735
	unsigned long (*get_area)(struct file *, unsigned long,
				  unsigned long, unsigned long, unsigned long);

1736 1737 1738 1739 1740 1741 1742 1743
	unsigned long error = arch_mmap_check(addr, len, flags);
	if (error)
		return error;

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

1744
	get_area = current->mm->get_unmapped_area;
1745 1746 1747 1748 1749 1750 1751
	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.
1752
		 * do_mmap() will clear pgoff, so match alignment.
1753 1754 1755 1756 1757
		 */
		pgoff = 0;
		get_area = shmem_get_unmapped_area;
	}

1758 1759 1760
	addr = get_area(file, addr, len, pgoff, flags);
	if (IS_ERR_VALUE(addr))
		return addr;
Linus Torvalds's avatar
Linus Torvalds committed
1761

1762 1763
	if (addr > TASK_SIZE - len)
		return -ENOMEM;
1764
	if (offset_in_page(addr))
1765
		return -EINVAL;
1766

1767 1768
	error = security_mmap_addr(addr);
	return error ? error : addr;
Linus Torvalds's avatar
Linus Torvalds committed
1769 1770 1771 1772
}

EXPORT_SYMBOL(get_unmapped_area);

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
/**
 * 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);
Liam R. Howlett's avatar
Liam R. Howlett committed
1789
	return mt_find(&mm->mm_mt, &index, end_addr - 1);
1790 1791 1792
}
EXPORT_SYMBOL(find_vma_intersection);

1793 1794 1795 1796 1797 1798 1799 1800
/**
 * 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.
 */
ZhenwenXu's avatar
ZhenwenXu committed
1801
struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
Linus Torvalds's avatar
Linus Torvalds committed
1802
{
1803
	unsigned long index = addr;
Linus Torvalds's avatar
Linus Torvalds committed
1804

1805
	mmap_assert_locked(mm);
Liam R. Howlett's avatar
Liam R. Howlett committed
1806
	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
Linus Torvalds's avatar
Linus Torvalds committed
1807 1808 1809
}
EXPORT_SYMBOL(find_vma);

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
/**
 * 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.
1822
 */
Linus Torvalds's avatar
Linus Torvalds committed
1823 1824 1825 1826
struct vm_area_struct *
find_vma_prev(struct mm_struct *mm, unsigned long addr,
			struct vm_area_struct **pprev)
{
1827
	struct vm_area_struct *vma;
1828
	MA_STATE(mas, &mm->mm_mt, addr, addr);
Linus Torvalds's avatar
Linus Torvalds committed
1829

1830 1831 1832 1833
	vma = mas_walk(&mas);
	*pprev = mas_prev(&mas, 0);
	if (!vma)
		vma = mas_next(&mas, ULONG_MAX);
1834
	return vma;
Linus Torvalds's avatar
Linus Torvalds committed
1835 1836 1837 1838 1839 1840 1841
}

/*
 * Verify that the stack growth is acceptable and
 * update accounting. This is shared with both the
 * grow-up and grow-down cases.
 */
1842 1843
static int acct_stack_growth(struct vm_area_struct *vma,
			     unsigned long size, unsigned long grow)
Linus Torvalds's avatar
Linus Torvalds committed
1844 1845
{
	struct mm_struct *mm = vma->vm_mm;
1846
	unsigned long new_start;
Linus Torvalds's avatar
Linus Torvalds committed
1847 1848

	/* address space limit tests */
1849
	if (!may_expand_vm(mm, vma->vm_flags, grow))
Linus Torvalds's avatar
Linus Torvalds committed
1850 1851 1852
		return -ENOMEM;

	/* Stack limit test */
1853
	if (size > rlimit(RLIMIT_STACK))
Linus Torvalds's avatar
Linus Torvalds committed
1854 1855 1856
		return -ENOMEM;

	/* mlock limit tests */
1857 1858
	if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
		return -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
1859

1860 1861 1862 1863 1864 1865
	/* 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;

Linus Torvalds's avatar
Linus Torvalds committed
1866 1867 1868 1869
	/*
	 * Overcommit..  This must be the final test, as it will
	 * update security statistics.
	 */
1870
	if (security_vm_enough_memory_mm(mm, grow))
Linus Torvalds's avatar
Linus Torvalds committed
1871 1872 1873 1874 1875
		return -ENOMEM;

	return 0;
}

1876
#if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
Linus Torvalds's avatar
Linus Torvalds committed
1877
/*
1878 1879
 * 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.
Linus Torvalds's avatar
Linus Torvalds committed
1880
 */
1881
int expand_upwards(struct vm_area_struct *vma, unsigned long address)
Linus Torvalds's avatar
Linus Torvalds committed
1882
{
1883
	struct mm_struct *mm = vma->vm_mm;
1884 1885
	struct vm_area_struct *next;
	unsigned long gap_addr;
1886
	int error = 0;
1887
	MA_STATE(mas, &mm->mm_mt, 0, 0);
Linus Torvalds's avatar
Linus Torvalds committed
1888 1889 1890 1891

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

1892
	/* Guard against exceeding limits of the address space. */
1893
	address &= PAGE_MASK;
1894
	if (address >= (TASK_SIZE & PAGE_MASK))
1895
		return -ENOMEM;
1896
	address += PAGE_SIZE;
1897

1898 1899
	/* Enforce stack_guard_gap */
	gap_addr = address + stack_guard_gap;
1900 1901 1902 1903 1904

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

1905 1906
	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
	if (next && vma_is_accessible(next)) {
1907 1908 1909 1910 1911
		if (!(next->vm_flags & VM_GROWSUP))
			return -ENOMEM;
		/* Check that both stack segments have the same anon_vma? */
	}

1912
	if (mas_preallocate(&mas, GFP_KERNEL))
1913 1914
		return -ENOMEM;

1915
	/* We must make sure the anon_vma is allocated. */
1916 1917
	if (unlikely(anon_vma_prepare(vma))) {
		mas_destroy(&mas);
Linus Torvalds's avatar
Linus Torvalds committed
1918
		return -ENOMEM;
1919
	}
Linus Torvalds's avatar
Linus Torvalds committed
1920 1921 1922

	/*
	 * vma->vm_start/vm_end cannot change under us because the caller
1923
	 * is required to hold the mmap_lock in read mode.  We need the
Linus Torvalds's avatar
Linus Torvalds committed
1924 1925
	 * anon_vma lock to serialize against concurrent expand_stacks.
	 */
1926
	anon_vma_lock_write(vma->anon_vma);
Linus Torvalds's avatar
Linus Torvalds committed
1927 1928 1929 1930 1931 1932 1933 1934

	/* 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;

1935 1936 1937 1938
		error = -ENOMEM;
		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
			error = acct_stack_growth(vma, size, grow);
			if (!error) {
1939
				/*
Liam R. Howlett's avatar
Liam R. Howlett committed
1940 1941 1942 1943 1944 1945 1946
				 * 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.
1947
				 */
1948
				spin_lock(&mm->page_table_lock);
1949
				if (vma->vm_flags & VM_LOCKED)
1950
					mm->locked_vm += grow;
1951
				vm_stat_account(mm, vma->vm_flags, grow);
1952
				anon_vma_interval_tree_pre_update_vma(vma);
1953
				vma->vm_end = address;
1954
				/* Overwrite old entry in mtree. */
1955 1956
				mas_set_range(&mas, vma->vm_start, address - 1);
				mas_store_prealloc(&mas, vma);
1957
				anon_vma_interval_tree_post_update_vma(vma);
1958
				spin_unlock(&mm->page_table_lock);
1959

1960 1961
				perf_event_mmap(vma);
			}
1962
		}
Linus Torvalds's avatar
Linus Torvalds committed
1963
	}
1964
	anon_vma_unlock_write(vma->anon_vma);
1965
	khugepaged_enter_vma(vma, vma->vm_flags);
1966
	mas_destroy(&mas);
Linus Torvalds's avatar
Linus Torvalds committed
1967 1968
	return error;
}
1969 1970
#endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */

Linus Torvalds's avatar
Linus Torvalds committed
1971 1972 1973
/*
 * vma is the first one with address < vma->vm_start.  Have to extend vma.
 */
Liam R. Howlett's avatar
Liam R. Howlett committed
1974
int expand_downwards(struct vm_area_struct *vma, unsigned long address)
Linus Torvalds's avatar
Linus Torvalds committed
1975
{
1976
	struct mm_struct *mm = vma->vm_mm;
1977
	MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
1978
	struct vm_area_struct *prev;
1979
	int error = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1980

1981
	address &= PAGE_MASK;
1982 1983
	if (address < mmap_min_addr)
		return -EPERM;
1984

1985
	/* Enforce stack_guard_gap */
1986
	prev = mas_prev(&mas, 0);
1987 1988
	/* Check that both stack segments have the same anon_vma? */
	if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
1989
			vma_is_accessible(prev)) {
1990
		if (address - prev->vm_end < stack_guard_gap)
1991 1992 1993
			return -ENOMEM;
	}

1994
	if (mas_preallocate(&mas, GFP_KERNEL))
1995 1996
		return -ENOMEM;

1997
	/* We must make sure the anon_vma is allocated. */
1998 1999
	if (unlikely(anon_vma_prepare(vma))) {
		mas_destroy(&mas);
2000
		return -ENOMEM;
2001
	}
Linus Torvalds's avatar
Linus Torvalds committed
2002 2003 2004

	/*
	 * vma->vm_start/vm_end cannot change under us because the caller
2005
	 * is required to hold the mmap_lock in read mode.  We need the
Linus Torvalds's avatar
Linus Torvalds committed
2006 2007
	 * anon_vma lock to serialize against concurrent expand_stacks.
	 */
2008
	anon_vma_lock_write(vma->anon_vma);
Linus Torvalds's avatar
Linus Torvalds committed
2009 2010 2011 2012 2013 2014 2015 2016

	/* 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;

2017 2018 2019 2020
		error = -ENOMEM;
		if (grow <= vma->vm_pgoff) {
			error = acct_stack_growth(vma, size, grow);
			if (!error) {
2021
				/*
Liam R. Howlett's avatar
Liam R. Howlett committed
2022 2023 2024 2025 2026 2027 2028
				 * 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.
2029
				 */
2030
				spin_lock(&mm->page_table_lock);
2031
				if (vma->vm_flags & VM_LOCKED)
2032
					mm->locked_vm += grow;
2033
				vm_stat_account(mm, vma->vm_flags, grow);
2034
				anon_vma_interval_tree_pre_update_vma(vma);
2035 2036
				vma->vm_start = address;
				vma->vm_pgoff -= grow;
2037
				/* Overwrite old entry in mtree. */
2038 2039
				mas_set_range(&mas, address, vma->vm_end - 1);
				mas_store_prealloc(&mas, vma);
2040
				anon_vma_interval_tree_post_update_vma(vma);
2041
				spin_unlock(&mm->page_table_lock);
2042

2043 2044
				perf_event_mmap(vma);
			}
Linus Torvalds's avatar
Linus Torvalds committed
2045 2046
		}
	}
2047
	anon_vma_unlock_write(vma->anon_vma);
2048
	khugepaged_enter_vma(vma, vma->vm_flags);
2049
	mas_destroy(&mas);
Linus Torvalds's avatar
Linus Torvalds committed
2050 2051 2052
	return error;
}

2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
/* 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;

2065
	return 1;
2066 2067 2068
}
__setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
#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;
2084
	if (!prev || expand_stack(prev, addr))
2085
		return NULL;
2086
	if (prev->vm_flags & VM_LOCKED)
2087
		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2088 2089 2090 2091 2092 2093 2094 2095
	return prev;
}
#else
int expand_stack(struct vm_area_struct *vma, unsigned long address)
{
	return expand_downwards(vma, address);
}

Linus Torvalds's avatar
Linus Torvalds committed
2096
struct vm_area_struct *
vishnu.ps's avatar
vishnu.ps committed
2097
find_extend_vma(struct mm_struct *mm, unsigned long addr)
Linus Torvalds's avatar
Linus Torvalds committed
2098
{
vishnu.ps's avatar
vishnu.ps committed
2099
	struct vm_area_struct *vma;
Linus Torvalds's avatar
Linus Torvalds committed
2100 2101 2102
	unsigned long start;

	addr &= PAGE_MASK;
vishnu.ps's avatar
vishnu.ps committed
2103
	vma = find_vma(mm, addr);
Linus Torvalds's avatar
Linus Torvalds committed
2104 2105 2106 2107 2108 2109 2110 2111 2112
	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;
2113
	if (vma->vm_flags & VM_LOCKED)
2114
		populate_vma_page_range(vma, addr, start, NULL);
Linus Torvalds's avatar
Linus Torvalds committed
2115 2116 2117 2118
	return vma;
}
#endif

2119 2120
EXPORT_SYMBOL_GPL(find_extend_vma);

Linus Torvalds's avatar
Linus Torvalds committed
2121
/*
2122 2123
 * Ok - we have the memory areas we should free on a maple tree so release them,
 * and do the vma updates.
2124 2125
 *
 * Called with the mm semaphore held.
Linus Torvalds's avatar
Linus Torvalds committed
2126
 */
2127
static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
Linus Torvalds's avatar
Linus Torvalds committed
2128
{
2129
	unsigned long nr_accounted = 0;
2130
	struct vm_area_struct *vma;
2131

2132 2133
	/* Update high watermark before we lower total_vm */
	update_hiwater_vm(mm);
2134
	mas_for_each(mas, vma, ULONG_MAX) {
2135 2136
		long nrpages = vma_pages(vma);

2137 2138
		if (vma->vm_flags & VM_ACCOUNT)
			nr_accounted += nrpages;
2139
		vm_stat_account(mm, vma->vm_flags, -nrpages);
2140 2141
		remove_vma(vma);
	}
2142
	vm_unacct_memory(nr_accounted);
Linus Torvalds's avatar
Linus Torvalds committed
2143 2144 2145 2146 2147 2148
	validate_mm(mm);
}

/*
 * Get rid of page table information in the indicated region.
 *
2149
 * Called with the mm semaphore held.
Linus Torvalds's avatar
Linus Torvalds committed
2150
 */
2151
static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
2152
		struct vm_area_struct *vma, struct vm_area_struct *prev,
2153
		struct vm_area_struct *next,
2154
		unsigned long start, unsigned long end)
Linus Torvalds's avatar
Linus Torvalds committed
2155
{
Peter Zijlstra's avatar
Peter Zijlstra committed
2156
	struct mmu_gather tlb;
Linus Torvalds's avatar
Linus Torvalds committed
2157 2158

	lru_add_drain();
2159
	tlb_gather_mmu(&tlb, mm);
2160
	update_hiwater_rss(mm);
2161 2162
	unmap_vmas(&tlb, mt, vma, start, end);
	free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2163
				 next ? next->vm_start : USER_PGTABLES_CEILING);
2164
	tlb_finish_mmu(&tlb);
Linus Torvalds's avatar
Linus Torvalds committed
2165 2166 2167
}

/*
2168 2169
 * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
 * has already been checked or doesn't make sense to fail.
2170
 * VMA Iterator will point to the end VMA.
Linus Torvalds's avatar
Linus Torvalds committed
2171
 */
2172
int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2173
		unsigned long addr, int new_below)
Linus Torvalds's avatar
Linus Torvalds committed
2174
{
2175
	struct vma_prepare vp;
Linus Torvalds's avatar
Linus Torvalds committed
2176
	struct vm_area_struct *new;
2177
	int err;
2178 2179

	validate_mm_mt(vma->vm_mm);
Linus Torvalds's avatar
Linus Torvalds committed
2180

2181 2182 2183
	WARN_ON(vma->vm_start >= addr);
	WARN_ON(vma->vm_end <= addr);

2184 2185
	if (vma->vm_ops && vma->vm_ops->may_split) {
		err = vma->vm_ops->may_split(vma, addr);
2186 2187 2188
		if (err)
			return err;
	}
Linus Torvalds's avatar
Linus Torvalds committed
2189

2190
	new = vm_area_dup(vma);
Linus Torvalds's avatar
Linus Torvalds committed
2191
	if (!new)
2192
		return -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
2193

2194 2195 2196 2197 2198
	err = -ENOMEM;
	if (vma_iter_prealloc(vmi))
		goto out_free_vma;

	if (new_below) {
Linus Torvalds's avatar
Linus Torvalds committed
2199
		new->vm_end = addr;
2200
	} else {
Linus Torvalds's avatar
Linus Torvalds committed
2201 2202 2203 2204
		new->vm_start = addr;
		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
	}

2205 2206
	err = vma_dup_policy(vma, new);
	if (err)
2207
		goto out_free_vmi;
Linus Torvalds's avatar
Linus Torvalds committed
2208

2209 2210
	err = anon_vma_clone(new, vma);
	if (err)
2211 2212
		goto out_free_mpol;

2213
	if (new->vm_file)
Linus Torvalds's avatar
Linus Torvalds committed
2214 2215 2216 2217 2218
		get_file(new->vm_file);

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

2219 2220 2221 2222
	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
	init_vma_prep(&vp, vma);
	vp.insert = new;
	vma_prepare(&vp);
Linus Torvalds's avatar
Linus Torvalds committed
2223

2224 2225 2226 2227 2228
	if (new_below) {
		vma->vm_start = addr;
		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
	} else {
		vma->vm_end = addr;
2229
	}
2230

2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
	/* vma_complete stores the new vma */
	vma_complete(&vp, vmi, vma->vm_mm);

	/* Success. */
	if (new_below)
		vma_next(vmi);
	validate_mm_mt(vma->vm_mm);
	return 0;

out_free_mpol:
2241
	mpol_put(vma_policy(new));
2242 2243 2244
out_free_vmi:
	vma_iter_free(vmi);
out_free_vma:
2245
	vm_area_free(new);
2246
	validate_mm_mt(vma->vm_mm);
2247
	return err;
Linus Torvalds's avatar
Linus Torvalds committed
2248 2249
}

2250 2251 2252 2253
/*
 * Split a vma into two pieces at address 'addr', a new vma is allocated
 * either for the first part or the tail.
 */
2254
int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2255 2256
	      unsigned long addr, int new_below)
{
2257
	if (vma->vm_mm->map_count >= sysctl_max_map_count)
2258 2259
		return -ENOMEM;

2260
	return __split_vma(vmi, vma, addr, new_below);
2261 2262
}

2263 2264
static inline int munmap_sidetree(struct vm_area_struct *vma,
				   struct ma_state *mas_detach)
Linus Torvalds's avatar
Linus Torvalds committed
2265
{
2266 2267 2268
	mas_set_range(mas_detach, vma->vm_start, vma->vm_end - 1);
	if (mas_store_gfp(mas_detach, vma, GFP_KERNEL))
		return -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
2269

2270 2271
	if (vma->vm_flags & VM_LOCKED)
		vma->vm_mm->locked_vm -= vma_pages(vma);
Linus Torvalds's avatar
Linus Torvalds committed
2272

2273
	return 0;
2274
}
2275

2276
/*
2277 2278
 * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
 * @vmi: The vma iterator
2279 2280 2281 2282 2283
 * @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
2284
 * @downgrade: Set to true to attempt a write downgrade of the mmap_lock
2285 2286 2287 2288
 *
 * If @downgrade is true, check return code for potential release of the lock.
 */
static int
2289
do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2290 2291 2292
		    struct mm_struct *mm, unsigned long start,
		    unsigned long end, struct list_head *uf, bool downgrade)
{
2293 2294 2295
	struct vm_area_struct *prev, *next = NULL;
	struct maple_tree mt_detach;
	int count = 0;
2296
	int error = -ENOMEM;
2297 2298 2299
	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);
2300

Linus Torvalds's avatar
Linus Torvalds committed
2301 2302 2303 2304 2305 2306 2307
	/*
	 * 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.
	 */
2308 2309

	/* Does it split the first one? */
2310
	if (start > vma->vm_start) {
2311 2312 2313 2314 2315 2316 2317

		/*
		 * 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)
2318
			goto map_count_exceeded;
2319

2320
		error = __split_vma(vmi, vma, start, 0);
Linus Torvalds's avatar
Linus Torvalds committed
2321
		if (error)
2322
			goto start_split_failed;
2323

2324
		vma = vma_iter_load(vmi);
Linus Torvalds's avatar
Linus Torvalds committed
2325 2326
	}

2327
	prev = vma_prev(vmi);
2328
	if (unlikely((!prev)))
2329
		vma_iter_set(vmi, start);
2330 2331 2332 2333 2334

	/*
	 * Detach a range of VMAs from the mm. Using next as a temp variable as
	 * it is always overwritten.
	 */
2335
	for_each_vma_range(*vmi, next, end) {
2336 2337
		/* Does it split the end? */
		if (next->vm_end > end) {
2338
			error = __split_vma(vmi, next, end, 0);
2339 2340 2341 2342
			if (error)
				goto end_split_failed;
		}
		error = munmap_sidetree(next, &mas_detach);
Linus Torvalds's avatar
Linus Torvalds committed
2343
		if (error)
2344
			goto munmap_sidetree_failed;
2345

2346 2347 2348 2349 2350
		count++;
#ifdef CONFIG_DEBUG_VM_MAPLE_TREE
		BUG_ON(next->vm_start < start);
		BUG_ON(next->vm_start > end);
#endif
Linus Torvalds's avatar
Linus Torvalds committed
2351 2352
	}

2353
	next = vma_next(vmi);
2354 2355 2356
	if (unlikely(uf)) {
		/*
		 * If userfaultfd_unmap_prep returns an error the vmas
Ingo Molnar's avatar
Ingo Molnar committed
2357
		 * will remain split, but userland will get a
2358 2359 2360 2361 2362 2363
		 * 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.
		 */
2364
		error = userfaultfd_unmap_prep(mm, start, end, uf);
2365

2366
		if (error)
2367
			goto userfaultfd_error;
2368 2369
	}

2370 2371 2372 2373 2374 2375 2376
#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;

2377
		vma_iter_set(vmi, start);
2378 2379
		rcu_read_lock();
		vma_test = mas_find(&test, end - 1);
2380
		for_each_vma_range(*vmi, vma_mas, end) {
2381 2382 2383 2384 2385 2386 2387 2388
			BUG_ON(vma_mas != vma_test);
			test_count++;
			vma_test = mas_next(&test, end - 1);
		}
		rcu_read_unlock();
		BUG_ON(count != test_count);
	}
#endif
2389
	/* Point of no return */
2390 2391
	vma_iter_set(vmi, start);
	if (vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL))
2392 2393
		return -ENOMEM;

2394
	mm->map_count -= count;
2395 2396 2397 2398 2399 2400
	/*
	 * 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) {
2401
		if (next && (next->vm_flags & VM_GROWSDOWN))
2402 2403 2404 2405 2406 2407
			downgrade = false;
		else if (prev && (prev->vm_flags & VM_GROWSUP))
			downgrade = false;
		else
			mmap_write_downgrade(mm);
	}
2408

2409 2410 2411 2412 2413
	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);
Linus Torvalds's avatar
Linus Torvalds committed
2414

Liam R. Howlett's avatar
Liam R. Howlett committed
2415 2416

	validate_mm(mm);
2417
	return downgrade ? 1 : 0;
2418 2419

userfaultfd_error:
2420 2421 2422 2423 2424
munmap_sidetree_failed:
end_split_failed:
	__mt_destroy(&mt_detach);
start_split_failed:
map_count_exceeded:
2425
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
2426 2427
}

2428
/*
2429 2430
 * do_vmi_munmap() - munmap a given range.
 * @vmi: The vma iterator
2431 2432 2433 2434 2435
 * @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
2436
 * mmap_lock
2437 2438 2439 2440 2441 2442 2443
 *
 * 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.
 */
2444
int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
		  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 */
2462
	vma = vma_find(vmi, end);
2463 2464 2465
	if (!vma)
		return 0;

2466
	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2467 2468 2469 2470 2471 2472 2473 2474
}

/* 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
 */
2475 2476 2477
int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
	      struct list_head *uf)
{
2478
	VMA_ITERATOR(vmi, mm, start);
2479

2480
	return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2481 2482
}

2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
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;
2496
	VMA_ITERATOR(vmi, mm, addr);
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513

	/* 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 */
2514
	if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
		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;
	}

2527 2528
	next = vma_next(&vmi);
	prev = vma_prev(&vmi);
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
	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 &&
2556
	    !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
		khugepaged_enter_vma(vma, vm_flags);
		goto expanded;
	}

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;
	}

2573
	vma_iter_set(&vmi, addr);
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
	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;

2592 2593 2594
		/*
		 * Expansion is handled above, merging is handled below.
		 * Drivers should not alter the address of the VMA.
2595
		 */
2596 2597
		error = -EINVAL;
		if (WARN_ON((addr != vma->vm_start)))
2598
			goto close_and_free_vma;
2599

2600
		vma_iter_set(&vmi, addr);
2601 2602 2603 2604 2605
		/*
		 * 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)) {
2606 2607 2608 2609
			merge = vma_merge(&vmi, mm, prev, vma->vm_start,
				    vma->vm_end, vma->vm_flags, NULL,
				    vma->vm_file, vma->vm_pgoff, NULL,
				    NULL_VM_UFFD_CTX, NULL);
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
			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. */
				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);
	}

2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
	if (map_deny_write_exec(vma, vma->vm_flags)) {
		error = -EACCES;
		if (file)
			goto close_and_free_vma;
		else if (vma->vm_file)
			goto unmap_and_free_vma;
		else
			goto free_vma;
	}

2646
	/* Allow architectures to sanity-check the vm_flags */
2647 2648 2649
	error = -EINVAL;
	if (!arch_validate_flags(vma->vm_flags))
		goto close_and_free_vma;
2650

2651 2652 2653
	error = -ENOMEM;
	if (vma_iter_prealloc(&vmi))
		goto close_and_free_vma;
2654 2655 2656 2657

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

2658
	vma_iter_store(&vmi, vma);
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
	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;

2711
close_and_free_vma:
2712
	if (file && vma->vm_ops && vma->vm_ops->close)
2713
		vma->vm_ops->close(vma);
2714 2715

	if (file || vma->vm_file) {
2716
unmap_and_free_vma:
2717 2718
		fput(vma->vm_file);
		vma->vm_file = NULL;
2719

2720 2721 2722 2723
		/* Undo any partial mapping done by a device driver. */
		unmap_region(mm, &mm->mm_mt, vma, prev, next, vma->vm_start,
			     vma->vm_end);
	}
2724
	if (file && (vm_flags & VM_SHARED))
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
		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;
}

2735
static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
Linus Torvalds's avatar
Linus Torvalds committed
2736 2737
{
	int ret;
Al Viro's avatar
Al Viro committed
2738
	struct mm_struct *mm = current->mm;
2739
	LIST_HEAD(uf);
2740
	VMA_ITERATOR(vmi, mm, start);
Linus Torvalds's avatar
Linus Torvalds committed
2741

2742
	if (mmap_write_lock_killable(mm))
Michal Hocko's avatar
Michal Hocko committed
2743 2744
		return -EINTR;

2745
	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, downgrade);
2746
	/*
2747
	 * Returning 1 indicates mmap_lock is downgraded.
2748 2749 2750 2751
	 * But 1 is not legal return value of vm_munmap() and munmap(), reset
	 * it to 0 before return.
	 */
	if (ret == 1) {
2752
		mmap_read_unlock(mm);
2753 2754
		ret = 0;
	} else
2755
		mmap_write_unlock(mm);
2756

2757
	userfaultfd_unmap_complete(mm, &uf);
Linus Torvalds's avatar
Linus Torvalds committed
2758 2759
	return ret;
}
2760 2761 2762 2763 2764

int vm_munmap(unsigned long start, size_t len)
{
	return __vm_munmap(start, len, false);
}
2765 2766 2767 2768
EXPORT_SYMBOL(vm_munmap);

SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
{
2769
	addr = untagged_addr(addr);
2770
	return __vm_munmap(addr, len, true);
2771
}
Linus Torvalds's avatar
Linus Torvalds committed
2772

2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786

/*
 * 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;

2787
	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
Joe Perches's avatar
Joe Perches committed
2788
		     current->comm, current->pid);
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801

	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;

2802
	if (mmap_write_lock_killable(mm))
2803 2804
		return -EINTR;

2805
	vma = vma_lookup(mm, start);
2806 2807 2808 2809

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

2810
	if (start + size > vma->vm_end) {
2811 2812
		VMA_ITERATOR(vmi, mm, vma->vm_end);
		struct vm_area_struct *next, *prev = vma;
2813

2814
		for_each_vma_range(vmi, next, start + size) {
2815
			/* hole between vmas ? */
2816
			if (next->vm_start != prev->vm_end)
2817 2818 2819 2820 2821 2822 2823 2824
				goto out;

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

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

2825 2826 2827
			if (start + size <= next->vm_end)
				break;

2828
			prev = next;
2829 2830 2831 2832
		}

		if (!next)
			goto out;
2833 2834 2835 2836 2837 2838 2839 2840
	}

	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;
2841
	if (vma->vm_flags & VM_LOCKED)
2842
		flags |= MAP_LOCKED;
2843

2844
	file = get_file(vma->vm_file);
2845
	ret = do_mmap(vma->vm_file, start, size,
2846
			prot, flags, pgoff, &populate, NULL);
2847 2848
	fput(file);
out:
2849
	mmap_write_unlock(mm);
2850 2851 2852 2853 2854 2855 2856
	if (populate)
		mm_populate(ret, populate);
	if (!IS_ERR_VALUE(ret))
		ret = 0;
	return ret;
}

Linus Torvalds's avatar
Linus Torvalds committed
2857
/*
2858 2859 2860 2861 2862
 * do_vma_munmap() - Unmap a full or partial vma.
 * @vmi: The vma iterator pointing at the vma
 * @vma: The first vma to be munmapped
 * @start: the start of the address to unmap
 * @end: The end of the address to unmap
2863
 * @uf: The userfaultfd list_head
2864
 * @downgrade: Attempt to downgrade or not
2865
 *
2866 2867 2868
 * Returns: 0 on success and not downgraded, 1 on success and downgraded.
 * unmaps a VMA mapping when the vma iterator is already in position.
 * Does not handle alignment.
Linus Torvalds's avatar
Linus Torvalds committed
2869
 */
2870 2871 2872
int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
		  unsigned long start, unsigned long end,
		  struct list_head *uf, bool downgrade)
Linus Torvalds's avatar
Linus Torvalds committed
2873
{
2874 2875
	struct mm_struct *mm = vma->vm_mm;
	int ret;
2876

2877 2878
	arch_unmap(mm, start, end);
	ret = do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
2879 2880 2881
	validate_mm_mt(mm);
	return ret;
}
Linus Torvalds's avatar
Linus Torvalds committed
2882

2883 2884
/*
 * do_brk_flags() - Increase the brk vma if the flags match.
2885
 * @vmi: The vma iterator
2886 2887 2888 2889 2890 2891 2892 2893 2894
 * @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.
 */
2895
static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
2896
		unsigned long addr, unsigned long len, unsigned long flags)
2897 2898
{
	struct mm_struct *mm = current->mm;
Linus Torvalds's avatar
Linus Torvalds committed
2899

2900 2901 2902 2903 2904 2905
	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;
2906
	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
Linus Torvalds's avatar
Linus Torvalds committed
2907 2908 2909 2910 2911
		return -ENOMEM;

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

2912
	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
Linus Torvalds's avatar
Linus Torvalds committed
2913 2914 2915
		return -ENOMEM;

	/*
2916 2917
	 * Expand the existing vma if possible; Note that singular lists do not
	 * occur after forking, so the expand will only happen on new VMAs.
Linus Torvalds's avatar
Linus Torvalds committed
2918
	 */
2919 2920 2921
	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)) {
2922
		if (vma_iter_prealloc(vmi))
2923
			goto unacct_fail;
2924 2925

		vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
2926 2927 2928 2929 2930 2931
		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;
2932
		vma_iter_store(vmi, vma);
2933 2934 2935 2936 2937 2938 2939

		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;
Linus Torvalds's avatar
Linus Torvalds committed
2940
	}
2941 2942 2943 2944

	/* create a vma struct for an anonymous mapping */
	vma = vm_area_alloc(mm);
	if (!vma)
2945
		goto unacct_fail;
Linus Torvalds's avatar
Linus Torvalds committed
2946

2947
	vma_set_anonymous(vma);
Linus Torvalds's avatar
Linus Torvalds committed
2948 2949
	vma->vm_start = addr;
	vma->vm_end = addr + len;
2950
	vma->vm_pgoff = addr >> PAGE_SHIFT;
Linus Torvalds's avatar
Linus Torvalds committed
2951
	vma->vm_flags = flags;
2952
	vma->vm_page_prot = vm_get_page_prot(flags);
2953
	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
2954
		goto mas_store_fail;
2955

2956
	mm->map_count++;
Linus Torvalds's avatar
Linus Torvalds committed
2957
out:
2958
	perf_event_mmap(vma);
Linus Torvalds's avatar
Linus Torvalds committed
2959
	mm->total_vm += len >> PAGE_SHIFT;
2960
	mm->data_vm += len >> PAGE_SHIFT;
2961 2962
	if (flags & VM_LOCKED)
		mm->locked_vm += (len >> PAGE_SHIFT);
2963
	vma->vm_flags |= VM_SOFTDIRTY;
2964
	validate_mm(mm);
2965
	return 0;
2966

2967
mas_store_fail:
2968
	vm_area_free(vma);
2969
unacct_fail:
2970 2971
	vm_unacct_memory(len >> PAGE_SHIFT);
	return -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
2972 2973
}

2974
int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
2975 2976
{
	struct mm_struct *mm = current->mm;
2977
	struct vm_area_struct *vma = NULL;
2978
	unsigned long len;
2979
	int ret;
2980
	bool populate;
2981
	LIST_HEAD(uf);
2982
	VMA_ITERATOR(vmi, mm, addr);
2983

2984 2985 2986 2987 2988 2989
	len = PAGE_ALIGN(request);
	if (len < request)
		return -ENOMEM;
	if (!len)
		return 0;

2990
	if (mmap_write_lock_killable(mm))
Michal Hocko's avatar
Michal Hocko committed
2991 2992
		return -EINTR;

2993 2994 2995 2996 2997 2998 2999 3000
	/* 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;

3001
	ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
3002 3003 3004
	if (ret)
		goto munmap_failed;

3005 3006
	vma = vma_prev(&vmi);
	ret = do_brk_flags(&vmi, vma, addr, len, flags);
3007
	populate = ((mm->def_flags & VM_LOCKED) != 0);
3008
	mmap_write_unlock(mm);
3009
	userfaultfd_unmap_complete(mm, &uf);
3010
	if (populate && !ret)
3011
		mm_populate(addr, len);
3012
	return ret;
3013 3014 3015 3016 3017

munmap_failed:
limits_failed:
	mmap_write_unlock(mm);
	return ret;
3018
}
3019 3020 3021 3022 3023 3024
EXPORT_SYMBOL(vm_brk_flags);

int vm_brk(unsigned long addr, unsigned long len)
{
	return vm_brk_flags(addr, len, 0);
}
3025
EXPORT_SYMBOL(vm_brk);
Linus Torvalds's avatar
Linus Torvalds committed
3026 3027 3028 3029

/* Release all mmaps. */
void exit_mmap(struct mm_struct *mm)
{
Peter Zijlstra's avatar
Peter Zijlstra committed
3030
	struct mmu_gather tlb;
3031
	struct vm_area_struct *vma;
Linus Torvalds's avatar
Linus Torvalds committed
3032
	unsigned long nr_accounted = 0;
3033 3034
	MA_STATE(mas, &mm->mm_mt, 0, 0);
	int count = 0;
Linus Torvalds's avatar
Linus Torvalds committed
3035

3036
	/* mm's last user has gone, and its about to be pulled down */
Andrea Arcangeli's avatar
Andrea Arcangeli committed
3037
	mmu_notifier_release(mm);
3038

3039
	mmap_read_lock(mm);
3040 3041
	arch_exit_mmap(mm);

3042
	vma = mas_find(&mas, ULONG_MAX);
3043 3044
	if (!vma) {
		/* Can happen if dup_mmap() received an OOM */
3045
		mmap_read_unlock(mm);
3046
		return;
3047
	}
3048

Linus Torvalds's avatar
Linus Torvalds committed
3049 3050
	lru_add_drain();
	flush_cache_mm(mm);
3051
	tlb_gather_mmu_fullmm(&tlb, mm);
3052
	/* update_hiwater_rss(mm) here? but nobody should be looking */
3053 3054
	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
	unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX);
3055 3056 3057 3058
	mmap_read_unlock(mm);

	/*
	 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3059
	 * because the memory has been already freed.
3060 3061 3062
	 */
	set_bit(MMF_OOM_SKIP, &mm->flags);
	mmap_write_lock(mm);
3063 3064
	free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
		      USER_PGTABLES_CEILING);
3065
	tlb_finish_mmu(&tlb);
Linus Torvalds's avatar
Linus Torvalds committed
3066

3067 3068 3069 3070 3071 3072
	/*
	 * Walk the list again, actually closing and freeing it, with preemption
	 * enabled, without holding any MM locks besides the unreachable
	 * mmap_write_lock.
	 */
	do {
3073 3074
		if (vma->vm_flags & VM_ACCOUNT)
			nr_accounted += vma_pages(vma);
3075 3076
		remove_vma(vma);
		count++;
3077
		cond_resched();
3078 3079 3080
	} while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);

	BUG_ON(count != mm->map_count);
3081 3082 3083

	trace_exit_mmap(mm);
	__mt_destroy(&mm->mm_mt);
3084
	mmap_write_unlock(mm);
3085
	vm_unacct_memory(nr_accounted);
Linus Torvalds's avatar
Linus Torvalds committed
3086 3087 3088 3089
}

/* Insert vm structure into process list sorted by address
 * and into the inode's i_mmap tree.  If vm_file is non-NULL
3090
 * then i_mmap_rwsem is taken here.
Linus Torvalds's avatar
Linus Torvalds committed
3091
 */
3092
int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
Linus Torvalds's avatar
Linus Torvalds committed
3093
{
3094
	unsigned long charged = vma_pages(vma);
Linus Torvalds's avatar
Linus Torvalds committed
3095

3096

3097
	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3098
		return -ENOMEM;
3099

3100
	if ((vma->vm_flags & VM_ACCOUNT) &&
3101
	     security_vm_enough_memory_mm(mm, charged))
3102 3103
		return -ENOMEM;

Linus Torvalds's avatar
Linus Torvalds committed
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113
	/*
	 * 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.
3114
	 * Similarly in do_mmap and in do_brk_flags.
Linus Torvalds's avatar
Linus Torvalds committed
3115
	 */
3116
	if (vma_is_anonymous(vma)) {
Linus Torvalds's avatar
Linus Torvalds committed
3117 3118 3119
		BUG_ON(vma->anon_vma);
		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
	}
3120

3121
	if (vma_link(mm, vma)) {
3122 3123 3124 3125
		vm_unacct_memory(charged);
		return -ENOMEM;
	}

Linus Torvalds's avatar
Linus Torvalds committed
3126 3127 3128 3129 3130 3131 3132 3133
	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,
3134 3135
	unsigned long addr, unsigned long len, pgoff_t pgoff,
	bool *need_rmap_locks)
Linus Torvalds's avatar
Linus Torvalds committed
3136 3137 3138 3139 3140
{
	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;
3141
	bool faulted_in_anon_vma = true;
3142
	VMA_ITERATOR(vmi, mm, addr);
Linus Torvalds's avatar
Linus Torvalds committed
3143

3144
	validate_mm_mt(mm);
Linus Torvalds's avatar
Linus Torvalds committed
3145 3146 3147 3148
	/*
	 * If anonymous vma has not yet been faulted, update new pgoff
	 * to match new location, to increase its chance of merging.
	 */
3149
	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
Linus Torvalds's avatar
Linus Torvalds committed
3150
		pgoff = addr >> PAGE_SHIFT;
3151 3152
		faulted_in_anon_vma = false;
	}
Linus Torvalds's avatar
Linus Torvalds committed
3153

3154 3155
	new_vma = find_vma_prev(mm, addr, &prev);
	if (new_vma && new_vma->vm_start < addr + len)
3156
		return NULL;	/* should never get here */
Liam R. Howlett's avatar
Liam R. Howlett committed
3157

3158
	new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
3159
			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3160
			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
Linus Torvalds's avatar
Linus Torvalds committed
3161 3162 3163 3164
	if (new_vma) {
		/*
		 * Source vma may have been merged into new_vma
		 */
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
		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.
			 */
3179
			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3180
			*vmap = vma = new_vma;
3181
		}
3182
		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
Linus Torvalds's avatar
Linus Torvalds committed
3183
	} else {
3184
		new_vma = vm_area_dup(vma);
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
		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);
3198
		if (vma_link(mm, new_vma))
Liam R. Howlett's avatar
Liam R. Howlett committed
3199
			goto out_vma_link;
3200
		*need_rmap_locks = false;
Linus Torvalds's avatar
Linus Torvalds committed
3201
	}
3202
	validate_mm_mt(mm);
Linus Torvalds's avatar
Linus Torvalds committed
3203
	return new_vma;
3204

Liam R. Howlett's avatar
Liam R. Howlett committed
3205 3206 3207
out_vma_link:
	if (new_vma->vm_ops && new_vma->vm_ops->close)
		new_vma->vm_ops->close(new_vma);
3208 3209 3210 3211 3212

	if (new_vma->vm_file)
		fput(new_vma->vm_file);

	unlink_anon_vmas(new_vma);
3213
out_free_mempol:
3214
	mpol_put(vma_policy(new_vma));
3215
out_free_vma:
3216
	vm_area_free(new_vma);
3217
out:
3218
	validate_mm_mt(mm);
3219
	return NULL;
Linus Torvalds's avatar
Linus Torvalds committed
3220
}
3221 3222 3223 3224 3225

/*
 * Return true if the calling process may expand its vm space by the passed
 * number of pages
 */
3226
bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3227
{
3228 3229
	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
		return false;
3230

3231 3232
	if (is_data_mapping(flags) &&
	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3233 3234 3235 3236
		/* Workaround for Valgrind */
		if (rlimit(RLIMIT_DATA) == 0 &&
		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
			return true;
3237 3238 3239 3240 3241 3242 3243 3244

		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)
3245 3246
			return false;
	}
3247

3248 3249 3250 3251 3252
	return true;
}

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

3255
	if (is_exec_mapping(flags))
3256
		mm->exec_vm += npages;
3257
	else if (is_stack_mapping(flags))
3258
		mm->stack_vm += npages;
3259
	else if (is_data_mapping(flags))
3260
		mm->data_vm += npages;
3261
}
3262

3263
static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276

/*
 * 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;
}

3277
static int special_mapping_mremap(struct vm_area_struct *new_vma)
3278 3279 3280
{
	struct vm_special_mapping *sm = new_vma->vm_private_data;

3281 3282 3283
	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
		return -EFAULT;

3284 3285
	if (sm->mremap)
		return sm->mremap(sm, new_vma);
3286

3287 3288 3289
	return 0;
}

3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
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;
}

3301 3302 3303
static const struct vm_operations_struct special_mapping_vmops = {
	.close = special_mapping_close,
	.fault = special_mapping_fault,
3304
	.mremap = special_mapping_mremap,
3305
	.name = special_mapping_name,
3306 3307
	/* vDSO code relies that VVAR can't be accessed remotely */
	.access = NULL,
3308
	.may_split = special_mapping_split,
3309 3310 3311 3312 3313 3314
};

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

3316
static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3317
{
3318
	struct vm_area_struct *vma = vmf->vma;
Nick Piggin's avatar
Nick Piggin committed
3319
	pgoff_t pgoff;
3320 3321
	struct page **pages;

3322
	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3323
		pages = vma->vm_private_data;
3324 3325 3326 3327
	} else {
		struct vm_special_mapping *sm = vma->vm_private_data;

		if (sm->fault)
3328
			return sm->fault(sm, vmf->vma, vmf);
3329 3330 3331

		pages = sm->pages;
	}
3332

3333
	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
Nick Piggin's avatar
Nick Piggin committed
3334
		pgoff--;
3335 3336 3337 3338

	if (*pages) {
		struct page *page = *pages;
		get_page(page);
Nick Piggin's avatar
Nick Piggin committed
3339 3340
		vmf->page = page;
		return 0;
3341 3342
	}

Nick Piggin's avatar
Nick Piggin committed
3343
	return VM_FAULT_SIGBUS;
3344 3345
}

3346 3347 3348
static struct vm_area_struct *__install_special_mapping(
	struct mm_struct *mm,
	unsigned long addr, unsigned long len,
3349 3350
	unsigned long vm_flags, void *priv,
	const struct vm_operations_struct *ops)
3351
{
3352
	int ret;
3353 3354
	struct vm_area_struct *vma;

3355
	validate_mm_mt(mm);
3356
	vma = vm_area_alloc(mm);
3357
	if (unlikely(vma == NULL))
3358
		return ERR_PTR(-ENOMEM);
3359 3360 3361 3362

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

3363
	vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3364
	vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3365
	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3366

3367 3368
	vma->vm_ops = ops;
	vma->vm_private_data = priv;
3369

3370 3371 3372
	ret = insert_vm_struct(mm, vma);
	if (ret)
		goto out;
3373

3374
	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3375

3376
	perf_event_mmap(vma);
3377

3378
	validate_mm_mt(mm);
3379
	return vma;
3380 3381

out:
3382
	vm_area_free(vma);
3383
	validate_mm_mt(mm);
3384 3385 3386
	return ERR_PTR(ret);
}

3387 3388 3389 3390 3391 3392 3393 3394
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);
}

3395
/*
3396
 * Called with mm->mmap_lock held for writing.
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
 * 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)
{
3409 3410
	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
					&special_mapping_vmops);
3411 3412
}

3413 3414 3415 3416
int install_special_mapping(struct mm_struct *mm,
			    unsigned long addr, unsigned long len,
			    unsigned long vm_flags, struct page **pages)
{
3417
	struct vm_area_struct *vma = __install_special_mapping(
3418 3419
		mm, addr, len, vm_flags, (void *)pages,
		&legacy_special_mapping_vmops);
3420

3421
	return PTR_ERR_OR_ZERO(vma);
3422
}
3423 3424 3425

static DEFINE_MUTEX(mm_all_locks_mutex);

3426
static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3427
{
3428
	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3429 3430 3431 3432
		/*
		 * The LSB of head.next can't change from under us
		 * because we hold the mm_all_locks_mutex.
		 */
3433
		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3434 3435
		/*
		 * We can safely modify head.next after taking the
3436
		 * anon_vma->root->rwsem. If some other vma in this mm shares
3437 3438 3439 3440
		 * 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
3441
		 * anon_vma->root->rwsem.
3442 3443
		 */
		if (__test_and_set_bit(0, (unsigned long *)
3444
				       &anon_vma->root->rb_root.rb_root.rb_node))
3445 3446 3447 3448
			BUG();
	}
}

3449
static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462
{
	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();
3463
		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3464 3465 3466 3467 3468 3469 3470 3471
	}
}

/*
 * 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.
 *
3472
 * The caller must take the mmap_lock in write mode before calling
3473
 * mm_take_all_locks(). The caller isn't allowed to release the
3474
 * mmap_lock until mm_drop_all_locks() returns.
3475
 *
3476
 * mmap_lock in write mode is required in order to block all operations
3477
 * that could modify pagetables and free pages without need of
3478
 * altering the vma layout. It's also needed in write mode to avoid new
3479 3480 3481 3482 3483
 * 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.
 *
3484
 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3485 3486 3487
 * 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.
 *
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
 * 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.
3498 3499 3500 3501 3502 3503 3504 3505 3506
 *
 * 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;
3507
	struct anon_vma_chain *avc;
3508
	MA_STATE(mas, &mm->mm_mt, 0, 0);
3509

3510
	mmap_assert_write_locked(mm);
3511 3512 3513

	mutex_lock(&mm_all_locks_mutex);

3514
	mas_for_each(&mas, vma, ULONG_MAX) {
3515 3516
		if (signal_pending(current))
			goto out_unlock;
3517 3518 3519 3520 3521
		if (vma->vm_file && vma->vm_file->f_mapping &&
				is_vm_hugetlb_page(vma))
			vm_lock_mapping(mm, vma->vm_file->f_mapping);
	}

3522 3523
	mas_set(&mas, 0);
	mas_for_each(&mas, vma, ULONG_MAX) {
3524 3525 3526 3527
		if (signal_pending(current))
			goto out_unlock;
		if (vma->vm_file && vma->vm_file->f_mapping &&
				!is_vm_hugetlb_page(vma))
3528
			vm_lock_mapping(mm, vma->vm_file->f_mapping);
3529
	}
3530

3531 3532
	mas_set(&mas, 0);
	mas_for_each(&mas, vma, ULONG_MAX) {
3533 3534 3535
		if (signal_pending(current))
			goto out_unlock;
		if (vma->anon_vma)
3536 3537
			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
				vm_lock_anon_vma(mm, avc->anon_vma);
3538
	}
3539

3540
	return 0;
3541 3542

out_unlock:
3543 3544
	mm_drop_all_locks(mm);
	return -EINTR;
3545 3546 3547 3548
}

static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
{
3549
	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3550 3551 3552 3553 3554
		/*
		 * 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
3555
		 * the vma so the users using the anon_vma->rb_root will
3556 3557 3558 3559
		 * never see our bitflag.
		 *
		 * No need of atomic instructions here, head.next
		 * can't change from under us until we release the
3560
		 * anon_vma->root->rwsem.
3561 3562
		 */
		if (!__test_and_clear_bit(0, (unsigned long *)
3563
					  &anon_vma->root->rb_root.rb_root.rb_node))
3564
			BUG();
3565
		anon_vma_unlock_write(anon_vma);
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
	}
}

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.
		 */
3576
		i_mmap_unlock_write(mapping);
3577 3578 3579 3580 3581 3582 3583
		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
					&mapping->flags))
			BUG();
	}
}

/*
3584
 * The mmap_lock cannot be released by the caller until
3585 3586 3587 3588 3589
 * mm_drop_all_locks() returns.
 */
void mm_drop_all_locks(struct mm_struct *mm)
{
	struct vm_area_struct *vma;
3590
	struct anon_vma_chain *avc;
3591
	MA_STATE(mas, &mm->mm_mt, 0, 0);
3592

3593
	mmap_assert_write_locked(mm);
3594 3595
	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));

3596
	mas_for_each(&mas, vma, ULONG_MAX) {
3597
		if (vma->anon_vma)
3598 3599
			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
				vm_unlock_anon_vma(avc->anon_vma);
3600 3601 3602 3603 3604 3605
		if (vma->vm_file && vma->vm_file->f_mapping)
			vm_unlock_mapping(vma->vm_file->f_mapping);
	}

	mutex_unlock(&mm_all_locks_mutex);
}
3606 3607

/*
3608
 * initialise the percpu counter for VM
3609 3610 3611
 */
void __init mmap_init(void)
{
3612 3613
	int ret;

3614
	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3615
	VM_BUG_ON(ret);
3616
}
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627

/*
 * 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.
 */
3628
static int init_user_reserve(void)
3629 3630 3631
{
	unsigned long free_kbytes;

3632
	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3633 3634 3635 3636

	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
	return 0;
}
3637
subsys_initcall(init_user_reserve);
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648

/*
 * 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.
 */
3649
static int init_admin_reserve(void)
3650 3651 3652
{
	unsigned long free_kbytes;

3653
	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3654 3655 3656 3657

	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
	return 0;
}
3658
subsys_initcall(init_admin_reserve);
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696

/*
 * 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:
3697
		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718

		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 int __meminit init_reserve_notifier(void)
{
3719
	if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3720
		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3721 3722 3723

	return 0;
}
3724
subsys_initcall(init_reserve_notifier);