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