xref: /linux/mm/madvise.c (revision 37104286f9390a3da330c299b01cabfb4c98af7c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *	linux/mm/madvise.c
4  *
5  * Copyright (C) 1999  Linus Torvalds
6  * Copyright (C) 2002  Christoph Hellwig
7  */
8 
9 #include <linux/mman.h>
10 #include <linux/pagemap.h>
11 #include <linux/syscalls.h>
12 #include <linux/mempolicy.h>
13 #include <linux/page-isolation.h>
14 #include <linux/page_idle.h>
15 #include <linux/userfaultfd_k.h>
16 #include <linux/hugetlb.h>
17 #include <linux/falloc.h>
18 #include <linux/fadvise.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
21 #include <linux/mm_inline.h>
22 #include <linux/mmu_context.h>
23 #include <linux/string.h>
24 #include <linux/uio.h>
25 #include <linux/ksm.h>
26 #include <linux/fs.h>
27 #include <linux/file.h>
28 #include <linux/blkdev.h>
29 #include <linux/backing-dev.h>
30 #include <linux/pagewalk.h>
31 #include <linux/swap.h>
32 #include <linux/swapops.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/mmu_notifier.h>
35 
36 #include <asm/tlb.h>
37 
38 #include "internal.h"
39 #include "swap.h"
40 
41 #define __MADV_SET_ANON_VMA_NAME (-1)
42 
43 /*
44  * Maximum number of attempts we make to install guard pages before we give up
45  * and return -ERESTARTNOINTR to have userspace try again.
46  */
47 #define MAX_MADVISE_GUARD_RETRIES 3
48 
49 struct madvise_walk_private {
50 	struct mmu_gather *tlb;
51 	bool pageout;
52 };
53 
54 enum madvise_lock_mode {
55 	MADVISE_NO_LOCK,
56 	MADVISE_MMAP_READ_LOCK,
57 	MADVISE_MMAP_WRITE_LOCK,
58 	MADVISE_VMA_READ_LOCK,
59 };
60 
61 struct madvise_behavior_range {
62 	unsigned long start;
63 	unsigned long end;
64 };
65 
66 struct madvise_behavior {
67 	struct mm_struct *mm;
68 	int behavior;
69 	struct mmu_gather *tlb;
70 	enum madvise_lock_mode lock_mode;
71 	struct anon_vma_name *anon_name;
72 
73 	/*
74 	 * The range over which the behaviour is currently being applied. If
75 	 * traversing multiple VMAs, this is updated for each.
76 	 */
77 	struct madvise_behavior_range range;
78 	/* The VMA and VMA preceding it (if applicable) currently targeted. */
79 	struct vm_area_struct *prev;
80 	struct vm_area_struct *vma;
81 	bool lock_dropped;
82 };
83 
84 #ifdef CONFIG_ANON_VMA_NAME
85 static int madvise_walk_vmas(struct madvise_behavior *madv_behavior);
86 
87 struct anon_vma_name *anon_vma_name_alloc(const char *name)
88 {
89 	struct anon_vma_name *anon_name;
90 	size_t count;
91 
92 	/* Add 1 for NUL terminator at the end of the anon_name->name */
93 	count = strlen(name) + 1;
94 	anon_name = kmalloc(struct_size(anon_name, name, count), GFP_KERNEL);
95 	if (anon_name) {
96 		kref_init(&anon_name->kref);
97 		memcpy(anon_name->name, name, count);
98 	}
99 
100 	return anon_name;
101 }
102 
103 void anon_vma_name_free(struct kref *kref)
104 {
105 	struct anon_vma_name *anon_name =
106 			container_of(kref, struct anon_vma_name, kref);
107 	kfree(anon_name);
108 }
109 
110 struct anon_vma_name *anon_vma_name(struct vm_area_struct *vma)
111 {
112 	if (!rwsem_is_locked(&vma->vm_mm->mmap_lock))
113 		vma_assert_locked(vma);
114 
115 	return vma->anon_name;
116 }
117 
118 /* mmap_lock should be write-locked */
119 static int replace_anon_vma_name(struct vm_area_struct *vma,
120 				 struct anon_vma_name *anon_name)
121 {
122 	struct anon_vma_name *orig_name = anon_vma_name(vma);
123 
124 	if (!anon_name) {
125 		vma->anon_name = NULL;
126 		anon_vma_name_put(orig_name);
127 		return 0;
128 	}
129 
130 	if (anon_vma_name_eq(orig_name, anon_name))
131 		return 0;
132 
133 	vma->anon_name = anon_vma_name_reuse(anon_name);
134 	anon_vma_name_put(orig_name);
135 
136 	return 0;
137 }
138 #else /* CONFIG_ANON_VMA_NAME */
139 static int replace_anon_vma_name(struct vm_area_struct *vma,
140 				 struct anon_vma_name *anon_name)
141 {
142 	if (anon_name)
143 		return -EINVAL;
144 
145 	return 0;
146 }
147 #endif /* CONFIG_ANON_VMA_NAME */
148 /*
149  * Update the vm_flags or anon_name on region of a vma, splitting it or merging
150  * it as necessary. Must be called with mmap_lock held for writing.
151  */
152 static int madvise_update_vma(vm_flags_t new_flags,
153 		struct madvise_behavior *madv_behavior)
154 {
155 	struct vm_area_struct *vma = madv_behavior->vma;
156 	struct madvise_behavior_range *range = &madv_behavior->range;
157 	struct anon_vma_name *anon_name = madv_behavior->anon_name;
158 	bool set_new_anon_name = madv_behavior->behavior == __MADV_SET_ANON_VMA_NAME;
159 	VMA_ITERATOR(vmi, madv_behavior->mm, range->start);
160 
161 	if (new_flags == vma->vm_flags && (!set_new_anon_name ||
162 			anon_vma_name_eq(anon_vma_name(vma), anon_name)))
163 		return 0;
164 
165 	if (set_new_anon_name)
166 		vma = vma_modify_name(&vmi, madv_behavior->prev, vma,
167 			range->start, range->end, anon_name);
168 	else
169 		vma = vma_modify_flags(&vmi, madv_behavior->prev, vma,
170 			range->start, range->end, &new_flags);
171 
172 	if (IS_ERR(vma))
173 		return PTR_ERR(vma);
174 
175 	madv_behavior->vma = vma;
176 
177 	/* vm_flags is protected by the mmap_lock held in write mode. */
178 	vma_start_write(vma);
179 	vm_flags_reset(vma, new_flags);
180 	if (set_new_anon_name)
181 		return replace_anon_vma_name(vma, anon_name);
182 
183 	return 0;
184 }
185 
186 #ifdef CONFIG_SWAP
187 static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
188 		unsigned long end, struct mm_walk *walk)
189 {
190 	struct vm_area_struct *vma = walk->private;
191 	struct swap_iocb *splug = NULL;
192 	pte_t *ptep = NULL;
193 	spinlock_t *ptl;
194 	unsigned long addr;
195 
196 	for (addr = start; addr < end; addr += PAGE_SIZE) {
197 		pte_t pte;
198 		swp_entry_t entry;
199 		struct folio *folio;
200 
201 		if (!ptep++) {
202 			ptep = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
203 			if (!ptep)
204 				break;
205 		}
206 
207 		pte = ptep_get(ptep);
208 		if (!is_swap_pte(pte))
209 			continue;
210 		entry = pte_to_swp_entry(pte);
211 		if (unlikely(non_swap_entry(entry)))
212 			continue;
213 
214 		pte_unmap_unlock(ptep, ptl);
215 		ptep = NULL;
216 
217 		folio = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE,
218 					     vma, addr, &splug);
219 		if (folio)
220 			folio_put(folio);
221 	}
222 
223 	if (ptep)
224 		pte_unmap_unlock(ptep, ptl);
225 	swap_read_unplug(splug);
226 	cond_resched();
227 
228 	return 0;
229 }
230 
231 static const struct mm_walk_ops swapin_walk_ops = {
232 	.pmd_entry		= swapin_walk_pmd_entry,
233 	.walk_lock		= PGWALK_RDLOCK,
234 };
235 
236 static void shmem_swapin_range(struct vm_area_struct *vma,
237 		unsigned long start, unsigned long end,
238 		struct address_space *mapping)
239 {
240 	XA_STATE(xas, &mapping->i_pages, linear_page_index(vma, start));
241 	pgoff_t end_index = linear_page_index(vma, end) - 1;
242 	struct folio *folio;
243 	struct swap_iocb *splug = NULL;
244 
245 	rcu_read_lock();
246 	xas_for_each(&xas, folio, end_index) {
247 		unsigned long addr;
248 		swp_entry_t entry;
249 
250 		if (!xa_is_value(folio))
251 			continue;
252 		entry = radix_to_swp_entry(folio);
253 		/* There might be swapin error entries in shmem mapping. */
254 		if (non_swap_entry(entry))
255 			continue;
256 
257 		addr = vma->vm_start +
258 			((xas.xa_index - vma->vm_pgoff) << PAGE_SHIFT);
259 		xas_pause(&xas);
260 		rcu_read_unlock();
261 
262 		folio = read_swap_cache_async(entry, mapping_gfp_mask(mapping),
263 					     vma, addr, &splug);
264 		if (folio)
265 			folio_put(folio);
266 
267 		rcu_read_lock();
268 	}
269 	rcu_read_unlock();
270 	swap_read_unplug(splug);
271 }
272 #endif		/* CONFIG_SWAP */
273 
274 static void mark_mmap_lock_dropped(struct madvise_behavior *madv_behavior)
275 {
276 	VM_WARN_ON_ONCE(madv_behavior->lock_mode == MADVISE_VMA_READ_LOCK);
277 	madv_behavior->lock_dropped = true;
278 }
279 
280 /*
281  * Schedule all required I/O operations.  Do not wait for completion.
282  */
283 static long madvise_willneed(struct madvise_behavior *madv_behavior)
284 {
285 	struct vm_area_struct *vma = madv_behavior->vma;
286 	struct mm_struct *mm = madv_behavior->mm;
287 	struct file *file = vma->vm_file;
288 	unsigned long start = madv_behavior->range.start;
289 	unsigned long end = madv_behavior->range.end;
290 	loff_t offset;
291 
292 #ifdef CONFIG_SWAP
293 	if (!file) {
294 		walk_page_range_vma(vma, start, end, &swapin_walk_ops, vma);
295 		lru_add_drain(); /* Push any new pages onto the LRU now */
296 		return 0;
297 	}
298 
299 	if (shmem_mapping(file->f_mapping)) {
300 		shmem_swapin_range(vma, start, end, file->f_mapping);
301 		lru_add_drain(); /* Push any new pages onto the LRU now */
302 		return 0;
303 	}
304 #else
305 	if (!file)
306 		return -EBADF;
307 #endif
308 
309 	if (IS_DAX(file_inode(file))) {
310 		/* no bad return value, but ignore advice */
311 		return 0;
312 	}
313 
314 	/*
315 	 * Filesystem's fadvise may need to take various locks.  We need to
316 	 * explicitly grab a reference because the vma (and hence the
317 	 * vma's reference to the file) can go away as soon as we drop
318 	 * mmap_lock.
319 	 */
320 	mark_mmap_lock_dropped(madv_behavior);
321 	get_file(file);
322 	offset = (loff_t)(start - vma->vm_start)
323 			+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
324 	mmap_read_unlock(mm);
325 	vfs_fadvise(file, offset, end - start, POSIX_FADV_WILLNEED);
326 	fput(file);
327 	mmap_read_lock(mm);
328 	return 0;
329 }
330 
331 static inline bool can_do_file_pageout(struct vm_area_struct *vma)
332 {
333 	if (!vma->vm_file)
334 		return false;
335 	/*
336 	 * paging out pagecache only for non-anonymous mappings that correspond
337 	 * to the files the calling process could (if tried) open for writing;
338 	 * otherwise we'd be including shared non-exclusive mappings, which
339 	 * opens a side channel.
340 	 */
341 	return inode_owner_or_capable(&nop_mnt_idmap,
342 				      file_inode(vma->vm_file)) ||
343 	       file_permission(vma->vm_file, MAY_WRITE) == 0;
344 }
345 
346 static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end,
347 					  struct folio *folio, pte_t *ptep,
348 					  pte_t *ptentp)
349 {
350 	int max_nr = (end - addr) / PAGE_SIZE;
351 
352 	return folio_pte_batch_flags(folio, NULL, ptep, ptentp, max_nr,
353 				     FPB_MERGE_YOUNG_DIRTY);
354 }
355 
356 static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
357 				unsigned long addr, unsigned long end,
358 				struct mm_walk *walk)
359 {
360 	struct madvise_walk_private *private = walk->private;
361 	struct mmu_gather *tlb = private->tlb;
362 	bool pageout = private->pageout;
363 	struct mm_struct *mm = tlb->mm;
364 	struct vm_area_struct *vma = walk->vma;
365 	pte_t *start_pte, *pte, ptent;
366 	spinlock_t *ptl;
367 	struct folio *folio = NULL;
368 	LIST_HEAD(folio_list);
369 	bool pageout_anon_only_filter;
370 	unsigned int batch_count = 0;
371 	int nr;
372 
373 	if (fatal_signal_pending(current))
374 		return -EINTR;
375 
376 	pageout_anon_only_filter = pageout && !vma_is_anonymous(vma) &&
377 					!can_do_file_pageout(vma);
378 
379 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
380 	if (pmd_trans_huge(*pmd)) {
381 		pmd_t orig_pmd;
382 		unsigned long next = pmd_addr_end(addr, end);
383 
384 		tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
385 		ptl = pmd_trans_huge_lock(pmd, vma);
386 		if (!ptl)
387 			return 0;
388 
389 		orig_pmd = *pmd;
390 		if (is_huge_zero_pmd(orig_pmd))
391 			goto huge_unlock;
392 
393 		if (unlikely(!pmd_present(orig_pmd))) {
394 			VM_BUG_ON(thp_migration_supported() &&
395 					!is_pmd_migration_entry(orig_pmd));
396 			goto huge_unlock;
397 		}
398 
399 		folio = pmd_folio(orig_pmd);
400 
401 		/* Do not interfere with other mappings of this folio */
402 		if (folio_maybe_mapped_shared(folio))
403 			goto huge_unlock;
404 
405 		if (pageout_anon_only_filter && !folio_test_anon(folio))
406 			goto huge_unlock;
407 
408 		if (next - addr != HPAGE_PMD_SIZE) {
409 			int err;
410 
411 			folio_get(folio);
412 			spin_unlock(ptl);
413 			folio_lock(folio);
414 			err = split_folio(folio);
415 			folio_unlock(folio);
416 			folio_put(folio);
417 			if (!err)
418 				goto regular_folio;
419 			return 0;
420 		}
421 
422 		if (!pageout && pmd_young(orig_pmd)) {
423 			pmdp_invalidate(vma, addr, pmd);
424 			orig_pmd = pmd_mkold(orig_pmd);
425 
426 			set_pmd_at(mm, addr, pmd, orig_pmd);
427 			tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
428 		}
429 
430 		folio_clear_referenced(folio);
431 		folio_test_clear_young(folio);
432 		if (folio_test_active(folio))
433 			folio_set_workingset(folio);
434 		if (pageout) {
435 			if (folio_isolate_lru(folio)) {
436 				if (folio_test_unevictable(folio))
437 					folio_putback_lru(folio);
438 				else
439 					list_add(&folio->lru, &folio_list);
440 			}
441 		} else
442 			folio_deactivate(folio);
443 huge_unlock:
444 		spin_unlock(ptl);
445 		if (pageout)
446 			reclaim_pages(&folio_list);
447 		return 0;
448 	}
449 
450 regular_folio:
451 #endif
452 	tlb_change_page_size(tlb, PAGE_SIZE);
453 restart:
454 	start_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
455 	if (!start_pte)
456 		return 0;
457 	flush_tlb_batched_pending(mm);
458 	arch_enter_lazy_mmu_mode();
459 	for (; addr < end; pte += nr, addr += nr * PAGE_SIZE) {
460 		nr = 1;
461 		ptent = ptep_get(pte);
462 
463 		if (++batch_count == SWAP_CLUSTER_MAX) {
464 			batch_count = 0;
465 			if (need_resched()) {
466 				arch_leave_lazy_mmu_mode();
467 				pte_unmap_unlock(start_pte, ptl);
468 				cond_resched();
469 				goto restart;
470 			}
471 		}
472 
473 		if (pte_none(ptent))
474 			continue;
475 
476 		if (!pte_present(ptent))
477 			continue;
478 
479 		folio = vm_normal_folio(vma, addr, ptent);
480 		if (!folio || folio_is_zone_device(folio))
481 			continue;
482 
483 		/*
484 		 * If we encounter a large folio, only split it if it is not
485 		 * fully mapped within the range we are operating on. Otherwise
486 		 * leave it as is so that it can be swapped out whole. If we
487 		 * fail to split a folio, leave it in place and advance to the
488 		 * next pte in the range.
489 		 */
490 		if (folio_test_large(folio)) {
491 			nr = madvise_folio_pte_batch(addr, end, folio, pte, &ptent);
492 			if (nr < folio_nr_pages(folio)) {
493 				int err;
494 
495 				if (folio_maybe_mapped_shared(folio))
496 					continue;
497 				if (pageout_anon_only_filter && !folio_test_anon(folio))
498 					continue;
499 				if (!folio_trylock(folio))
500 					continue;
501 				folio_get(folio);
502 				arch_leave_lazy_mmu_mode();
503 				pte_unmap_unlock(start_pte, ptl);
504 				start_pte = NULL;
505 				err = split_folio(folio);
506 				folio_unlock(folio);
507 				folio_put(folio);
508 				start_pte = pte =
509 					pte_offset_map_lock(mm, pmd, addr, &ptl);
510 				if (!start_pte)
511 					break;
512 				flush_tlb_batched_pending(mm);
513 				arch_enter_lazy_mmu_mode();
514 				if (!err)
515 					nr = 0;
516 				continue;
517 			}
518 		}
519 
520 		/*
521 		 * Do not interfere with other mappings of this folio and
522 		 * non-LRU folio. If we have a large folio at this point, we
523 		 * know it is fully mapped so if its mapcount is the same as its
524 		 * number of pages, it must be exclusive.
525 		 */
526 		if (!folio_test_lru(folio) ||
527 		    folio_mapcount(folio) != folio_nr_pages(folio))
528 			continue;
529 
530 		if (pageout_anon_only_filter && !folio_test_anon(folio))
531 			continue;
532 
533 		if (!pageout && pte_young(ptent)) {
534 			clear_young_dirty_ptes(vma, addr, pte, nr,
535 					       CYDP_CLEAR_YOUNG);
536 			tlb_remove_tlb_entries(tlb, pte, nr, addr);
537 		}
538 
539 		/*
540 		 * We are deactivating a folio for accelerating reclaiming.
541 		 * VM couldn't reclaim the folio unless we clear PG_young.
542 		 * As a side effect, it makes confuse idle-page tracking
543 		 * because they will miss recent referenced history.
544 		 */
545 		folio_clear_referenced(folio);
546 		folio_test_clear_young(folio);
547 		if (folio_test_active(folio))
548 			folio_set_workingset(folio);
549 		if (pageout) {
550 			if (folio_isolate_lru(folio)) {
551 				if (folio_test_unevictable(folio))
552 					folio_putback_lru(folio);
553 				else
554 					list_add(&folio->lru, &folio_list);
555 			}
556 		} else
557 			folio_deactivate(folio);
558 	}
559 
560 	if (start_pte) {
561 		arch_leave_lazy_mmu_mode();
562 		pte_unmap_unlock(start_pte, ptl);
563 	}
564 	if (pageout)
565 		reclaim_pages(&folio_list);
566 	cond_resched();
567 
568 	return 0;
569 }
570 
571 static const struct mm_walk_ops cold_walk_ops = {
572 	.pmd_entry = madvise_cold_or_pageout_pte_range,
573 	.walk_lock = PGWALK_RDLOCK,
574 };
575 
576 static void madvise_cold_page_range(struct mmu_gather *tlb,
577 		struct madvise_behavior *madv_behavior)
578 
579 {
580 	struct vm_area_struct *vma = madv_behavior->vma;
581 	struct madvise_behavior_range *range = &madv_behavior->range;
582 	struct madvise_walk_private walk_private = {
583 		.pageout = false,
584 		.tlb = tlb,
585 	};
586 
587 	tlb_start_vma(tlb, vma);
588 	walk_page_range_vma(vma, range->start, range->end, &cold_walk_ops,
589 			&walk_private);
590 	tlb_end_vma(tlb, vma);
591 }
592 
593 static inline bool can_madv_lru_vma(struct vm_area_struct *vma)
594 {
595 	return !(vma->vm_flags & (VM_LOCKED|VM_PFNMAP|VM_HUGETLB));
596 }
597 
598 static long madvise_cold(struct madvise_behavior *madv_behavior)
599 {
600 	struct vm_area_struct *vma = madv_behavior->vma;
601 	struct mmu_gather tlb;
602 
603 	if (!can_madv_lru_vma(vma))
604 		return -EINVAL;
605 
606 	lru_add_drain();
607 	tlb_gather_mmu(&tlb, madv_behavior->mm);
608 	madvise_cold_page_range(&tlb, madv_behavior);
609 	tlb_finish_mmu(&tlb);
610 
611 	return 0;
612 }
613 
614 static void madvise_pageout_page_range(struct mmu_gather *tlb,
615 		struct vm_area_struct *vma,
616 		struct madvise_behavior_range *range)
617 {
618 	struct madvise_walk_private walk_private = {
619 		.pageout = true,
620 		.tlb = tlb,
621 	};
622 
623 	tlb_start_vma(tlb, vma);
624 	walk_page_range_vma(vma, range->start, range->end, &cold_walk_ops,
625 			    &walk_private);
626 	tlb_end_vma(tlb, vma);
627 }
628 
629 static long madvise_pageout(struct madvise_behavior *madv_behavior)
630 {
631 	struct mmu_gather tlb;
632 	struct vm_area_struct *vma = madv_behavior->vma;
633 
634 	if (!can_madv_lru_vma(vma))
635 		return -EINVAL;
636 
637 	/*
638 	 * If the VMA belongs to a private file mapping, there can be private
639 	 * dirty pages which can be paged out if even this process is neither
640 	 * owner nor write capable of the file. We allow private file mappings
641 	 * further to pageout dirty anon pages.
642 	 */
643 	if (!vma_is_anonymous(vma) && (!can_do_file_pageout(vma) &&
644 				(vma->vm_flags & VM_MAYSHARE)))
645 		return 0;
646 
647 	lru_add_drain();
648 	tlb_gather_mmu(&tlb, madv_behavior->mm);
649 	madvise_pageout_page_range(&tlb, vma, &madv_behavior->range);
650 	tlb_finish_mmu(&tlb);
651 
652 	return 0;
653 }
654 
655 static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
656 				unsigned long end, struct mm_walk *walk)
657 
658 {
659 	const cydp_t cydp_flags = CYDP_CLEAR_YOUNG | CYDP_CLEAR_DIRTY;
660 	struct mmu_gather *tlb = walk->private;
661 	struct mm_struct *mm = tlb->mm;
662 	struct vm_area_struct *vma = walk->vma;
663 	spinlock_t *ptl;
664 	pte_t *start_pte, *pte, ptent;
665 	struct folio *folio;
666 	int nr_swap = 0;
667 	unsigned long next;
668 	int nr, max_nr;
669 
670 	next = pmd_addr_end(addr, end);
671 	if (pmd_trans_huge(*pmd))
672 		if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
673 			return 0;
674 
675 	tlb_change_page_size(tlb, PAGE_SIZE);
676 	start_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
677 	if (!start_pte)
678 		return 0;
679 	flush_tlb_batched_pending(mm);
680 	arch_enter_lazy_mmu_mode();
681 	for (; addr != end; pte += nr, addr += PAGE_SIZE * nr) {
682 		nr = 1;
683 		ptent = ptep_get(pte);
684 
685 		if (pte_none(ptent))
686 			continue;
687 		/*
688 		 * If the pte has swp_entry, just clear page table to
689 		 * prevent swap-in which is more expensive rather than
690 		 * (page allocation + zeroing).
691 		 */
692 		if (!pte_present(ptent)) {
693 			swp_entry_t entry;
694 
695 			entry = pte_to_swp_entry(ptent);
696 			if (!non_swap_entry(entry)) {
697 				max_nr = (end - addr) / PAGE_SIZE;
698 				nr = swap_pte_batch(pte, max_nr, ptent);
699 				nr_swap -= nr;
700 				free_swap_and_cache_nr(entry, nr);
701 				clear_not_present_full_ptes(mm, addr, pte, nr, tlb->fullmm);
702 			} else if (is_hwpoison_entry(entry) ||
703 				   is_poisoned_swp_entry(entry)) {
704 				pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
705 			}
706 			continue;
707 		}
708 
709 		folio = vm_normal_folio(vma, addr, ptent);
710 		if (!folio || folio_is_zone_device(folio))
711 			continue;
712 
713 		/*
714 		 * If we encounter a large folio, only split it if it is not
715 		 * fully mapped within the range we are operating on. Otherwise
716 		 * leave it as is so that it can be marked as lazyfree. If we
717 		 * fail to split a folio, leave it in place and advance to the
718 		 * next pte in the range.
719 		 */
720 		if (folio_test_large(folio)) {
721 			nr = madvise_folio_pte_batch(addr, end, folio, pte, &ptent);
722 			if (nr < folio_nr_pages(folio)) {
723 				int err;
724 
725 				if (folio_maybe_mapped_shared(folio))
726 					continue;
727 				if (!folio_trylock(folio))
728 					continue;
729 				folio_get(folio);
730 				arch_leave_lazy_mmu_mode();
731 				pte_unmap_unlock(start_pte, ptl);
732 				start_pte = NULL;
733 				err = split_folio(folio);
734 				folio_unlock(folio);
735 				folio_put(folio);
736 				pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
737 				start_pte = pte;
738 				if (!start_pte)
739 					break;
740 				flush_tlb_batched_pending(mm);
741 				arch_enter_lazy_mmu_mode();
742 				if (!err)
743 					nr = 0;
744 				continue;
745 			}
746 		}
747 
748 		if (folio_test_swapcache(folio) || folio_test_dirty(folio)) {
749 			if (!folio_trylock(folio))
750 				continue;
751 			/*
752 			 * If we have a large folio at this point, we know it is
753 			 * fully mapped so if its mapcount is the same as its
754 			 * number of pages, it must be exclusive.
755 			 */
756 			if (folio_mapcount(folio) != folio_nr_pages(folio)) {
757 				folio_unlock(folio);
758 				continue;
759 			}
760 
761 			if (folio_test_swapcache(folio) &&
762 			    !folio_free_swap(folio)) {
763 				folio_unlock(folio);
764 				continue;
765 			}
766 
767 			folio_clear_dirty(folio);
768 			folio_unlock(folio);
769 		}
770 
771 		if (pte_young(ptent) || pte_dirty(ptent)) {
772 			clear_young_dirty_ptes(vma, addr, pte, nr, cydp_flags);
773 			tlb_remove_tlb_entries(tlb, pte, nr, addr);
774 		}
775 		folio_mark_lazyfree(folio);
776 	}
777 
778 	if (nr_swap)
779 		add_mm_counter(mm, MM_SWAPENTS, nr_swap);
780 	if (start_pte) {
781 		arch_leave_lazy_mmu_mode();
782 		pte_unmap_unlock(start_pte, ptl);
783 	}
784 	cond_resched();
785 
786 	return 0;
787 }
788 
789 static inline enum page_walk_lock get_walk_lock(enum madvise_lock_mode mode)
790 {
791 	switch (mode) {
792 	case MADVISE_VMA_READ_LOCK:
793 		return PGWALK_VMA_RDLOCK_VERIFY;
794 	case MADVISE_MMAP_READ_LOCK:
795 		return PGWALK_RDLOCK;
796 	default:
797 		/* Other modes don't require fixing up the walk_lock */
798 		WARN_ON_ONCE(1);
799 		return PGWALK_RDLOCK;
800 	}
801 }
802 
803 static int madvise_free_single_vma(struct madvise_behavior *madv_behavior)
804 {
805 	struct mm_struct *mm = madv_behavior->mm;
806 	struct vm_area_struct *vma = madv_behavior->vma;
807 	unsigned long start_addr = madv_behavior->range.start;
808 	unsigned long end_addr = madv_behavior->range.end;
809 	struct mmu_notifier_range range;
810 	struct mmu_gather *tlb = madv_behavior->tlb;
811 	struct mm_walk_ops walk_ops = {
812 		.pmd_entry		= madvise_free_pte_range,
813 	};
814 
815 	/* MADV_FREE works for only anon vma at the moment */
816 	if (!vma_is_anonymous(vma))
817 		return -EINVAL;
818 
819 	range.start = max(vma->vm_start, start_addr);
820 	if (range.start >= vma->vm_end)
821 		return -EINVAL;
822 	range.end = min(vma->vm_end, end_addr);
823 	if (range.end <= vma->vm_start)
824 		return -EINVAL;
825 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
826 				range.start, range.end);
827 
828 	lru_add_drain();
829 	update_hiwater_rss(mm);
830 
831 	mmu_notifier_invalidate_range_start(&range);
832 	tlb_start_vma(tlb, vma);
833 	walk_ops.walk_lock = get_walk_lock(madv_behavior->lock_mode);
834 	walk_page_range_vma(vma, range.start, range.end,
835 			&walk_ops, tlb);
836 	tlb_end_vma(tlb, vma);
837 	mmu_notifier_invalidate_range_end(&range);
838 	return 0;
839 }
840 
841 /*
842  * Application no longer needs these pages.  If the pages are dirty,
843  * it's OK to just throw them away.  The app will be more careful about
844  * data it wants to keep.  Be sure to free swap resources too.  The
845  * zap_page_range_single call sets things up for shrink_active_list to actually
846  * free these pages later if no one else has touched them in the meantime,
847  * although we could add these pages to a global reuse list for
848  * shrink_active_list to pick up before reclaiming other pages.
849  *
850  * NB: This interface discards data rather than pushes it out to swap,
851  * as some implementations do.  This has performance implications for
852  * applications like large transactional databases which want to discard
853  * pages in anonymous maps after committing to backing store the data
854  * that was kept in them.  There is no reason to write this data out to
855  * the swap area if the application is discarding it.
856  *
857  * An interface that causes the system to free clean pages and flush
858  * dirty pages is already available as msync(MS_INVALIDATE).
859  */
860 static long madvise_dontneed_single_vma(struct madvise_behavior *madv_behavior)
861 
862 {
863 	struct madvise_behavior_range *range = &madv_behavior->range;
864 	struct zap_details details = {
865 		.reclaim_pt = true,
866 		.even_cows = true,
867 	};
868 
869 	zap_page_range_single_batched(
870 			madv_behavior->tlb, madv_behavior->vma, range->start,
871 			range->end - range->start, &details);
872 	return 0;
873 }
874 
875 static
876 bool madvise_dontneed_free_valid_vma(struct madvise_behavior *madv_behavior)
877 {
878 	struct vm_area_struct *vma = madv_behavior->vma;
879 	int behavior = madv_behavior->behavior;
880 	struct madvise_behavior_range *range = &madv_behavior->range;
881 
882 	if (!is_vm_hugetlb_page(vma)) {
883 		unsigned int forbidden = VM_PFNMAP;
884 
885 		if (behavior != MADV_DONTNEED_LOCKED)
886 			forbidden |= VM_LOCKED;
887 
888 		return !(vma->vm_flags & forbidden);
889 	}
890 
891 	if (behavior != MADV_DONTNEED && behavior != MADV_DONTNEED_LOCKED)
892 		return false;
893 	if (range->start & ~huge_page_mask(hstate_vma(vma)))
894 		return false;
895 
896 	/*
897 	 * Madvise callers expect the length to be rounded up to PAGE_SIZE
898 	 * boundaries, and may be unaware that this VMA uses huge pages.
899 	 * Avoid unexpected data loss by rounding down the number of
900 	 * huge pages freed.
901 	 */
902 	range->end = ALIGN_DOWN(range->end, huge_page_size(hstate_vma(vma)));
903 
904 	return true;
905 }
906 
907 static long madvise_dontneed_free(struct madvise_behavior *madv_behavior)
908 {
909 	struct mm_struct *mm = madv_behavior->mm;
910 	struct madvise_behavior_range *range = &madv_behavior->range;
911 	int behavior = madv_behavior->behavior;
912 
913 	if (!madvise_dontneed_free_valid_vma(madv_behavior))
914 		return -EINVAL;
915 
916 	if (range->start == range->end)
917 		return 0;
918 
919 	if (!userfaultfd_remove(madv_behavior->vma, range->start, range->end)) {
920 		struct vm_area_struct *vma;
921 
922 		mark_mmap_lock_dropped(madv_behavior);
923 		mmap_read_lock(mm);
924 		madv_behavior->vma = vma = vma_lookup(mm, range->start);
925 		if (!vma)
926 			return -ENOMEM;
927 		/*
928 		 * Potential end adjustment for hugetlb vma is OK as
929 		 * the check below keeps end within vma.
930 		 */
931 		if (!madvise_dontneed_free_valid_vma(madv_behavior))
932 			return -EINVAL;
933 		if (range->end > vma->vm_end) {
934 			/*
935 			 * Don't fail if end > vma->vm_end. If the old
936 			 * vma was split while the mmap_lock was
937 			 * released the effect of the concurrent
938 			 * operation may not cause madvise() to
939 			 * have an undefined result. There may be an
940 			 * adjacent next vma that we'll walk
941 			 * next. userfaultfd_remove() will generate an
942 			 * UFFD_EVENT_REMOVE repetition on the
943 			 * end-vma->vm_end range, but the manager can
944 			 * handle a repetition fine.
945 			 */
946 			range->end = vma->vm_end;
947 		}
948 		/*
949 		 * If the memory region between start and end was
950 		 * originally backed by 4kB pages and then remapped to
951 		 * be backed by hugepages while mmap_lock was dropped,
952 		 * the adjustment for hugetlb vma above may have rounded
953 		 * end down to the start address.
954 		 */
955 		if (range->start == range->end)
956 			return 0;
957 		VM_WARN_ON(range->start > range->end);
958 	}
959 
960 	if (behavior == MADV_DONTNEED || behavior == MADV_DONTNEED_LOCKED)
961 		return madvise_dontneed_single_vma(madv_behavior);
962 	else if (behavior == MADV_FREE)
963 		return madvise_free_single_vma(madv_behavior);
964 	else
965 		return -EINVAL;
966 }
967 
968 static long madvise_populate(struct madvise_behavior *madv_behavior)
969 {
970 	struct mm_struct *mm = madv_behavior->mm;
971 	const bool write = madv_behavior->behavior == MADV_POPULATE_WRITE;
972 	int locked = 1;
973 	unsigned long start = madv_behavior->range.start;
974 	unsigned long end = madv_behavior->range.end;
975 	long pages;
976 
977 	while (start < end) {
978 		/* Populate (prefault) page tables readable/writable. */
979 		pages = faultin_page_range(mm, start, end, write, &locked);
980 		if (!locked) {
981 			mmap_read_lock(mm);
982 			locked = 1;
983 		}
984 		if (pages < 0) {
985 			switch (pages) {
986 			case -EINTR:
987 				return -EINTR;
988 			case -EINVAL: /* Incompatible mappings / permissions. */
989 				return -EINVAL;
990 			case -EHWPOISON:
991 				return -EHWPOISON;
992 			case -EFAULT: /* VM_FAULT_SIGBUS or VM_FAULT_SIGSEGV */
993 				return -EFAULT;
994 			default:
995 				pr_warn_once("%s: unhandled return value: %ld\n",
996 					     __func__, pages);
997 				fallthrough;
998 			case -ENOMEM: /* No VMA or out of memory. */
999 				return -ENOMEM;
1000 			}
1001 		}
1002 		start += pages * PAGE_SIZE;
1003 	}
1004 	return 0;
1005 }
1006 
1007 /*
1008  * Application wants to free up the pages and associated backing store.
1009  * This is effectively punching a hole into the middle of a file.
1010  */
1011 static long madvise_remove(struct madvise_behavior *madv_behavior)
1012 {
1013 	loff_t offset;
1014 	int error;
1015 	struct file *f;
1016 	struct mm_struct *mm = madv_behavior->mm;
1017 	struct vm_area_struct *vma = madv_behavior->vma;
1018 	unsigned long start = madv_behavior->range.start;
1019 	unsigned long end = madv_behavior->range.end;
1020 
1021 	mark_mmap_lock_dropped(madv_behavior);
1022 
1023 	if (vma->vm_flags & VM_LOCKED)
1024 		return -EINVAL;
1025 
1026 	f = vma->vm_file;
1027 
1028 	if (!f || !f->f_mapping || !f->f_mapping->host) {
1029 			return -EINVAL;
1030 	}
1031 
1032 	if (!vma_is_shared_maywrite(vma))
1033 		return -EACCES;
1034 
1035 	offset = (loff_t)(start - vma->vm_start)
1036 			+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
1037 
1038 	/*
1039 	 * Filesystem's fallocate may need to take i_rwsem.  We need to
1040 	 * explicitly grab a reference because the vma (and hence the
1041 	 * vma's reference to the file) can go away as soon as we drop
1042 	 * mmap_lock.
1043 	 */
1044 	get_file(f);
1045 	if (userfaultfd_remove(vma, start, end)) {
1046 		/* mmap_lock was not released by userfaultfd_remove() */
1047 		mmap_read_unlock(mm);
1048 	}
1049 	error = vfs_fallocate(f,
1050 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1051 				offset, end - start);
1052 	fput(f);
1053 	mmap_read_lock(mm);
1054 	return error;
1055 }
1056 
1057 static bool is_valid_guard_vma(struct vm_area_struct *vma, bool allow_locked)
1058 {
1059 	vm_flags_t disallowed = VM_SPECIAL | VM_HUGETLB;
1060 
1061 	/*
1062 	 * A user could lock after setting a guard range but that's fine, as
1063 	 * they'd not be able to fault in. The issue arises when we try to zap
1064 	 * existing locked VMAs. We don't want to do that.
1065 	 */
1066 	if (!allow_locked)
1067 		disallowed |= VM_LOCKED;
1068 
1069 	return !(vma->vm_flags & disallowed);
1070 }
1071 
1072 static bool is_guard_pte_marker(pte_t ptent)
1073 {
1074 	return is_swap_pte(ptent) &&
1075 	       is_guard_swp_entry(pte_to_swp_entry(ptent));
1076 }
1077 
1078 static int guard_install_pud_entry(pud_t *pud, unsigned long addr,
1079 				   unsigned long next, struct mm_walk *walk)
1080 {
1081 	pud_t pudval = pudp_get(pud);
1082 
1083 	/* If huge return >0 so we abort the operation + zap. */
1084 	return pud_trans_huge(pudval);
1085 }
1086 
1087 static int guard_install_pmd_entry(pmd_t *pmd, unsigned long addr,
1088 				   unsigned long next, struct mm_walk *walk)
1089 {
1090 	pmd_t pmdval = pmdp_get(pmd);
1091 
1092 	/* If huge return >0 so we abort the operation + zap. */
1093 	return pmd_trans_huge(pmdval);
1094 }
1095 
1096 static int guard_install_pte_entry(pte_t *pte, unsigned long addr,
1097 				   unsigned long next, struct mm_walk *walk)
1098 {
1099 	pte_t pteval = ptep_get(pte);
1100 	unsigned long *nr_pages = (unsigned long *)walk->private;
1101 
1102 	/* If there is already a guard page marker, we have nothing to do. */
1103 	if (is_guard_pte_marker(pteval)) {
1104 		(*nr_pages)++;
1105 
1106 		return 0;
1107 	}
1108 
1109 	/* If populated return >0 so we abort the operation + zap. */
1110 	return 1;
1111 }
1112 
1113 static int guard_install_set_pte(unsigned long addr, unsigned long next,
1114 				 pte_t *ptep, struct mm_walk *walk)
1115 {
1116 	unsigned long *nr_pages = (unsigned long *)walk->private;
1117 
1118 	/* Simply install a PTE marker, this causes segfault on access. */
1119 	*ptep = make_pte_marker(PTE_MARKER_GUARD);
1120 	(*nr_pages)++;
1121 
1122 	return 0;
1123 }
1124 
1125 static long madvise_guard_install(struct madvise_behavior *madv_behavior)
1126 {
1127 	struct vm_area_struct *vma = madv_behavior->vma;
1128 	struct madvise_behavior_range *range = &madv_behavior->range;
1129 	struct mm_walk_ops walk_ops = {
1130 		.pud_entry	= guard_install_pud_entry,
1131 		.pmd_entry	= guard_install_pmd_entry,
1132 		.pte_entry	= guard_install_pte_entry,
1133 		.install_pte	= guard_install_set_pte,
1134 		.walk_lock	= get_walk_lock(madv_behavior->lock_mode),
1135 	};
1136 	long err;
1137 	int i;
1138 
1139 	if (!is_valid_guard_vma(vma, /* allow_locked = */false))
1140 		return -EINVAL;
1141 
1142 	/*
1143 	 * Set atomically under read lock. All pertinent readers will need to
1144 	 * acquire an mmap/VMA write lock to read it. All remaining readers may
1145 	 * or may not see the flag set, but we don't care.
1146 	 */
1147 	vma_flag_set_atomic(vma, VM_MAYBE_GUARD_BIT);
1148 
1149 	/*
1150 	 * If anonymous and we are establishing page tables the VMA ought to
1151 	 * have an anon_vma associated with it.
1152 	 *
1153 	 * We will hold an mmap read lock if this is necessary, this is checked
1154 	 * as part of the VMA lock logic.
1155 	 */
1156 	if (vma_is_anonymous(vma)) {
1157 		VM_WARN_ON_ONCE(!vma->anon_vma &&
1158 				madv_behavior->lock_mode != MADVISE_MMAP_READ_LOCK);
1159 
1160 		err = anon_vma_prepare(vma);
1161 		if (err)
1162 			return err;
1163 	}
1164 
1165 	/*
1166 	 * Optimistically try to install the guard marker pages first. If any
1167 	 * non-guard pages or THP huge pages are encountered, give up and zap
1168 	 * the range before trying again.
1169 	 *
1170 	 * We try a few times before giving up and releasing back to userland to
1171 	 * loop around, releasing locks in the process to avoid contention.
1172 	 *
1173 	 * This would only happen due to races with e.g. page faults or
1174 	 * khugepaged.
1175 	 *
1176 	 * In most cases we should simply install the guard markers immediately
1177 	 * with no zap or looping.
1178 	 */
1179 	for (i = 0; i < MAX_MADVISE_GUARD_RETRIES; i++) {
1180 		unsigned long nr_pages = 0;
1181 
1182 		/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */
1183 		if (madv_behavior->lock_mode == MADVISE_VMA_READ_LOCK)
1184 			err = walk_page_range_vma_unsafe(madv_behavior->vma,
1185 					range->start, range->end, &walk_ops,
1186 					&nr_pages);
1187 		else
1188 			err = walk_page_range_mm_unsafe(vma->vm_mm, range->start,
1189 					range->end, &walk_ops, &nr_pages);
1190 		if (err < 0)
1191 			return err;
1192 
1193 		if (err == 0) {
1194 			unsigned long nr_expected_pages =
1195 				PHYS_PFN(range->end - range->start);
1196 
1197 			VM_WARN_ON(nr_pages != nr_expected_pages);
1198 			return 0;
1199 		}
1200 
1201 		/*
1202 		 * OK some of the range have non-guard pages mapped, zap
1203 		 * them. This leaves existing guard pages in place.
1204 		 */
1205 		zap_page_range_single(vma, range->start,
1206 				range->end - range->start, NULL);
1207 	}
1208 
1209 	/*
1210 	 * We were unable to install the guard pages, return to userspace and
1211 	 * immediately retry, relieving lock contention.
1212 	 */
1213 	return restart_syscall();
1214 }
1215 
1216 static int guard_remove_pud_entry(pud_t *pud, unsigned long addr,
1217 				  unsigned long next, struct mm_walk *walk)
1218 {
1219 	pud_t pudval = pudp_get(pud);
1220 
1221 	/* If huge, cannot have guard pages present, so no-op - skip. */
1222 	if (pud_trans_huge(pudval))
1223 		walk->action = ACTION_CONTINUE;
1224 
1225 	return 0;
1226 }
1227 
1228 static int guard_remove_pmd_entry(pmd_t *pmd, unsigned long addr,
1229 				  unsigned long next, struct mm_walk *walk)
1230 {
1231 	pmd_t pmdval = pmdp_get(pmd);
1232 
1233 	/* If huge, cannot have guard pages present, so no-op - skip. */
1234 	if (pmd_trans_huge(pmdval))
1235 		walk->action = ACTION_CONTINUE;
1236 
1237 	return 0;
1238 }
1239 
1240 static int guard_remove_pte_entry(pte_t *pte, unsigned long addr,
1241 				  unsigned long next, struct mm_walk *walk)
1242 {
1243 	pte_t ptent = ptep_get(pte);
1244 
1245 	if (is_guard_pte_marker(ptent)) {
1246 		/* Simply clear the PTE marker. */
1247 		pte_clear_not_present_full(walk->mm, addr, pte, false);
1248 		update_mmu_cache(walk->vma, addr, pte);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
1254 static long madvise_guard_remove(struct madvise_behavior *madv_behavior)
1255 {
1256 	struct vm_area_struct *vma = madv_behavior->vma;
1257 	struct madvise_behavior_range *range = &madv_behavior->range;
1258 	struct mm_walk_ops wallk_ops = {
1259 		.pud_entry = guard_remove_pud_entry,
1260 		.pmd_entry = guard_remove_pmd_entry,
1261 		.pte_entry = guard_remove_pte_entry,
1262 		.walk_lock = get_walk_lock(madv_behavior->lock_mode),
1263 	};
1264 
1265 	/*
1266 	 * We're ok with removing guards in mlock()'d ranges, as this is a
1267 	 * non-destructive action.
1268 	 */
1269 	if (!is_valid_guard_vma(vma, /* allow_locked = */true))
1270 		return -EINVAL;
1271 
1272 	return walk_page_range_vma(vma, range->start, range->end,
1273 				   &wallk_ops, NULL);
1274 }
1275 
1276 #ifdef CONFIG_64BIT
1277 /* Does the madvise operation result in discarding of mapped data? */
1278 static bool is_discard(int behavior)
1279 {
1280 	switch (behavior) {
1281 	case MADV_FREE:
1282 	case MADV_DONTNEED:
1283 	case MADV_DONTNEED_LOCKED:
1284 	case MADV_REMOVE:
1285 	case MADV_DONTFORK:
1286 	case MADV_WIPEONFORK:
1287 	case MADV_GUARD_INSTALL:
1288 		return true;
1289 	}
1290 
1291 	return false;
1292 }
1293 
1294 /*
1295  * We are restricted from madvise()'ing mseal()'d VMAs only in very particular
1296  * circumstances - discarding of data from read-only anonymous SEALED mappings.
1297  *
1298  * This is because users cannot trivally discard data from these VMAs, and may
1299  * only do so via an appropriate madvise() call.
1300  */
1301 static bool can_madvise_modify(struct madvise_behavior *madv_behavior)
1302 {
1303 	struct vm_area_struct *vma = madv_behavior->vma;
1304 
1305 	/* If the VMA isn't sealed we're good. */
1306 	if (!vma_is_sealed(vma))
1307 		return true;
1308 
1309 	/* For a sealed VMA, we only care about discard operations. */
1310 	if (!is_discard(madv_behavior->behavior))
1311 		return true;
1312 
1313 	/*
1314 	 * We explicitly permit all file-backed mappings, whether MAP_SHARED or
1315 	 * MAP_PRIVATE.
1316 	 *
1317 	 * The latter causes some complications. Because now, one can mmap()
1318 	 * read/write a MAP_PRIVATE mapping, write to it, then mprotect()
1319 	 * read-only, mseal() and a discard will be permitted.
1320 	 *
1321 	 * However, in order to avoid issues with potential use of madvise(...,
1322 	 * MADV_DONTNEED) of mseal()'d .text mappings we, for the time being,
1323 	 * permit this.
1324 	 */
1325 	if (!vma_is_anonymous(vma))
1326 		return true;
1327 
1328 	/* If the user could write to the mapping anyway, then this is fine. */
1329 	if ((vma->vm_flags & VM_WRITE) &&
1330 	    arch_vma_access_permitted(vma, /* write= */ true,
1331 			/* execute= */ false, /* foreign= */ false))
1332 		return true;
1333 
1334 	/* Otherwise, we are not permitted to perform this operation. */
1335 	return false;
1336 }
1337 #else
1338 static bool can_madvise_modify(struct madvise_behavior *madv_behavior)
1339 {
1340 	return true;
1341 }
1342 #endif
1343 
1344 /*
1345  * Apply an madvise behavior to a region of a vma.  madvise_update_vma
1346  * will handle splitting a vm area into separate areas, each area with its own
1347  * behavior.
1348  */
1349 static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)
1350 {
1351 	int behavior = madv_behavior->behavior;
1352 	struct vm_area_struct *vma = madv_behavior->vma;
1353 	vm_flags_t new_flags = vma->vm_flags;
1354 	struct madvise_behavior_range *range = &madv_behavior->range;
1355 	int error;
1356 
1357 	if (unlikely(!can_madvise_modify(madv_behavior)))
1358 		return -EPERM;
1359 
1360 	switch (behavior) {
1361 	case MADV_REMOVE:
1362 		return madvise_remove(madv_behavior);
1363 	case MADV_WILLNEED:
1364 		return madvise_willneed(madv_behavior);
1365 	case MADV_COLD:
1366 		return madvise_cold(madv_behavior);
1367 	case MADV_PAGEOUT:
1368 		return madvise_pageout(madv_behavior);
1369 	case MADV_FREE:
1370 	case MADV_DONTNEED:
1371 	case MADV_DONTNEED_LOCKED:
1372 		return madvise_dontneed_free(madv_behavior);
1373 	case MADV_COLLAPSE:
1374 		return madvise_collapse(vma, range->start, range->end,
1375 			&madv_behavior->lock_dropped);
1376 	case MADV_GUARD_INSTALL:
1377 		return madvise_guard_install(madv_behavior);
1378 	case MADV_GUARD_REMOVE:
1379 		return madvise_guard_remove(madv_behavior);
1380 
1381 	/* The below behaviours update VMAs via madvise_update_vma(). */
1382 
1383 	case MADV_NORMAL:
1384 		new_flags = new_flags & ~VM_RAND_READ & ~VM_SEQ_READ;
1385 		break;
1386 	case MADV_SEQUENTIAL:
1387 		new_flags = (new_flags & ~VM_RAND_READ) | VM_SEQ_READ;
1388 		break;
1389 	case MADV_RANDOM:
1390 		new_flags = (new_flags & ~VM_SEQ_READ) | VM_RAND_READ;
1391 		break;
1392 	case MADV_DONTFORK:
1393 		new_flags |= VM_DONTCOPY;
1394 		break;
1395 	case MADV_DOFORK:
1396 		if (new_flags & VM_IO)
1397 			return -EINVAL;
1398 		new_flags &= ~VM_DONTCOPY;
1399 		break;
1400 	case MADV_WIPEONFORK:
1401 		/* MADV_WIPEONFORK is only supported on anonymous memory. */
1402 		if (vma->vm_file || new_flags & VM_SHARED)
1403 			return -EINVAL;
1404 		new_flags |= VM_WIPEONFORK;
1405 		break;
1406 	case MADV_KEEPONFORK:
1407 		if (new_flags & VM_DROPPABLE)
1408 			return -EINVAL;
1409 		new_flags &= ~VM_WIPEONFORK;
1410 		break;
1411 	case MADV_DONTDUMP:
1412 		new_flags |= VM_DONTDUMP;
1413 		break;
1414 	case MADV_DODUMP:
1415 		if ((!is_vm_hugetlb_page(vma) && (new_flags & VM_SPECIAL)) ||
1416 		    (new_flags & VM_DROPPABLE))
1417 			return -EINVAL;
1418 		new_flags &= ~VM_DONTDUMP;
1419 		break;
1420 	case MADV_MERGEABLE:
1421 	case MADV_UNMERGEABLE:
1422 		error = ksm_madvise(vma, range->start, range->end,
1423 				behavior, &new_flags);
1424 		if (error)
1425 			goto out;
1426 		break;
1427 	case MADV_HUGEPAGE:
1428 	case MADV_NOHUGEPAGE:
1429 		error = hugepage_madvise(vma, &new_flags, behavior);
1430 		if (error)
1431 			goto out;
1432 		break;
1433 	case __MADV_SET_ANON_VMA_NAME:
1434 		/* Only anonymous mappings can be named */
1435 		if (vma->vm_file && !vma_is_anon_shmem(vma))
1436 			return -EBADF;
1437 		break;
1438 	}
1439 
1440 	/* This is a write operation.*/
1441 	VM_WARN_ON_ONCE(madv_behavior->lock_mode != MADVISE_MMAP_WRITE_LOCK);
1442 
1443 	error = madvise_update_vma(new_flags, madv_behavior);
1444 out:
1445 	/*
1446 	 * madvise() returns EAGAIN if kernel resources, such as
1447 	 * slab, are temporarily unavailable.
1448 	 */
1449 	if (error == -ENOMEM)
1450 		error = -EAGAIN;
1451 	return error;
1452 }
1453 
1454 #ifdef CONFIG_MEMORY_FAILURE
1455 /*
1456  * Error injection support for memory error handling.
1457  */
1458 static int madvise_inject_error(struct madvise_behavior *madv_behavior)
1459 {
1460 	unsigned long size;
1461 	unsigned long start = madv_behavior->range.start;
1462 	unsigned long end = madv_behavior->range.end;
1463 
1464 	if (!capable(CAP_SYS_ADMIN))
1465 		return -EPERM;
1466 
1467 	for (; start < end; start += size) {
1468 		unsigned long pfn;
1469 		struct page *page;
1470 		int ret;
1471 
1472 		ret = get_user_pages_fast(start, 1, 0, &page);
1473 		if (ret != 1)
1474 			return ret;
1475 		pfn = page_to_pfn(page);
1476 
1477 		/*
1478 		 * When soft offlining hugepages, after migrating the page
1479 		 * we dissolve it, therefore in the second loop "page" will
1480 		 * no longer be a compound page.
1481 		 */
1482 		size = page_size(compound_head(page));
1483 
1484 		if (madv_behavior->behavior == MADV_SOFT_OFFLINE) {
1485 			pr_info("Soft offlining pfn %#lx at process virtual address %#lx\n",
1486 				 pfn, start);
1487 			ret = soft_offline_page(pfn, MF_COUNT_INCREASED);
1488 		} else {
1489 			pr_info("Injecting memory failure for pfn %#lx at process virtual address %#lx\n",
1490 				 pfn, start);
1491 			ret = memory_failure(pfn, MF_ACTION_REQUIRED | MF_COUNT_INCREASED | MF_SW_SIMULATED);
1492 			if (ret == -EOPNOTSUPP)
1493 				ret = 0;
1494 		}
1495 
1496 		if (ret)
1497 			return ret;
1498 	}
1499 
1500 	return 0;
1501 }
1502 
1503 static bool is_memory_failure(struct madvise_behavior *madv_behavior)
1504 {
1505 	switch (madv_behavior->behavior) {
1506 	case MADV_HWPOISON:
1507 	case MADV_SOFT_OFFLINE:
1508 		return true;
1509 	default:
1510 		return false;
1511 	}
1512 }
1513 
1514 #else
1515 
1516 static int madvise_inject_error(struct madvise_behavior *madv_behavior)
1517 {
1518 	return 0;
1519 }
1520 
1521 static bool is_memory_failure(struct madvise_behavior *madv_behavior)
1522 {
1523 	return false;
1524 }
1525 
1526 #endif	/* CONFIG_MEMORY_FAILURE */
1527 
1528 static bool
1529 madvise_behavior_valid(int behavior)
1530 {
1531 	switch (behavior) {
1532 	case MADV_DOFORK:
1533 	case MADV_DONTFORK:
1534 	case MADV_NORMAL:
1535 	case MADV_SEQUENTIAL:
1536 	case MADV_RANDOM:
1537 	case MADV_REMOVE:
1538 	case MADV_WILLNEED:
1539 	case MADV_DONTNEED:
1540 	case MADV_DONTNEED_LOCKED:
1541 	case MADV_FREE:
1542 	case MADV_COLD:
1543 	case MADV_PAGEOUT:
1544 	case MADV_POPULATE_READ:
1545 	case MADV_POPULATE_WRITE:
1546 #ifdef CONFIG_KSM
1547 	case MADV_MERGEABLE:
1548 	case MADV_UNMERGEABLE:
1549 #endif
1550 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1551 	case MADV_HUGEPAGE:
1552 	case MADV_NOHUGEPAGE:
1553 	case MADV_COLLAPSE:
1554 #endif
1555 	case MADV_DONTDUMP:
1556 	case MADV_DODUMP:
1557 	case MADV_WIPEONFORK:
1558 	case MADV_KEEPONFORK:
1559 	case MADV_GUARD_INSTALL:
1560 	case MADV_GUARD_REMOVE:
1561 #ifdef CONFIG_MEMORY_FAILURE
1562 	case MADV_SOFT_OFFLINE:
1563 	case MADV_HWPOISON:
1564 #endif
1565 		return true;
1566 
1567 	default:
1568 		return false;
1569 	}
1570 }
1571 
1572 /* Can we invoke process_madvise() on a remote mm for the specified behavior? */
1573 static bool process_madvise_remote_valid(int behavior)
1574 {
1575 	switch (behavior) {
1576 	case MADV_COLD:
1577 	case MADV_PAGEOUT:
1578 	case MADV_WILLNEED:
1579 	case MADV_COLLAPSE:
1580 		return true;
1581 	default:
1582 		return false;
1583 	}
1584 }
1585 
1586 /* Does this operation invoke anon_vma_prepare()? */
1587 static bool prepares_anon_vma(int behavior)
1588 {
1589 	switch (behavior) {
1590 	case MADV_GUARD_INSTALL:
1591 		return true;
1592 	default:
1593 		return false;
1594 	}
1595 }
1596 
1597 /*
1598  * We have acquired a VMA read lock, is the VMA valid to be madvise'd under VMA
1599  * read lock only now we have a VMA to examine?
1600  */
1601 static bool is_vma_lock_sufficient(struct vm_area_struct *vma,
1602 		struct madvise_behavior *madv_behavior)
1603 {
1604 	/* Must span only a single VMA.*/
1605 	if (madv_behavior->range.end > vma->vm_end)
1606 		return false;
1607 	/* Remote processes unsupported. */
1608 	if (current->mm != vma->vm_mm)
1609 		return false;
1610 	/* Userfaultfd unsupported. */
1611 	if (userfaultfd_armed(vma))
1612 		return false;
1613 	/*
1614 	 * anon_vma_prepare() explicitly requires an mmap lock for
1615 	 * serialisation, so we cannot use a VMA lock in this case.
1616 	 *
1617 	 * Note we might race with anon_vma being set, however this makes this
1618 	 * check overly paranoid which is safe.
1619 	 */
1620 	if (vma_is_anonymous(vma) &&
1621 	    prepares_anon_vma(madv_behavior->behavior) && !vma->anon_vma)
1622 		return false;
1623 
1624 	return true;
1625 }
1626 
1627 /*
1628  * Try to acquire a VMA read lock if possible.
1629  *
1630  * We only support this lock over a single VMA, which the input range must
1631  * span either partially or fully.
1632  *
1633  * This function always returns with an appropriate lock held. If a VMA read
1634  * lock could be acquired, we return true and set madv_behavior state
1635  * accordingly.
1636  *
1637  * If a VMA read lock could not be acquired, we return false and expect caller to
1638  * fallback to mmap lock behaviour.
1639  */
1640 static bool try_vma_read_lock(struct madvise_behavior *madv_behavior)
1641 {
1642 	struct mm_struct *mm = madv_behavior->mm;
1643 	struct vm_area_struct *vma;
1644 
1645 	vma = lock_vma_under_rcu(mm, madv_behavior->range.start);
1646 	if (!vma)
1647 		goto take_mmap_read_lock;
1648 
1649 	if (!is_vma_lock_sufficient(vma, madv_behavior)) {
1650 		vma_end_read(vma);
1651 		goto take_mmap_read_lock;
1652 	}
1653 
1654 	madv_behavior->vma = vma;
1655 	return true;
1656 
1657 take_mmap_read_lock:
1658 	mmap_read_lock(mm);
1659 	madv_behavior->lock_mode = MADVISE_MMAP_READ_LOCK;
1660 	return false;
1661 }
1662 
1663 /*
1664  * Walk the vmas in range [start,end), and call the madvise_vma_behavior
1665  * function on each one.  The function will get start and end parameters that
1666  * cover the overlap between the current vma and the original range.  Any
1667  * unmapped regions in the original range will result in this function returning
1668  * -ENOMEM while still calling the madvise_vma_behavior function on all of the
1669  * existing vmas in the range.  Must be called with the mmap_lock held for
1670  * reading or writing.
1671  */
1672 static
1673 int madvise_walk_vmas(struct madvise_behavior *madv_behavior)
1674 {
1675 	struct mm_struct *mm = madv_behavior->mm;
1676 	struct madvise_behavior_range *range = &madv_behavior->range;
1677 	/* range is updated to span each VMA, so store end of entire range. */
1678 	unsigned long last_end = range->end;
1679 	int unmapped_error = 0;
1680 	int error;
1681 	struct vm_area_struct *prev, *vma;
1682 
1683 	/*
1684 	 * If VMA read lock is supported, apply madvise to a single VMA
1685 	 * tentatively, avoiding walking VMAs.
1686 	 */
1687 	if (madv_behavior->lock_mode == MADVISE_VMA_READ_LOCK &&
1688 	    try_vma_read_lock(madv_behavior)) {
1689 		error = madvise_vma_behavior(madv_behavior);
1690 		vma_end_read(madv_behavior->vma);
1691 		return error;
1692 	}
1693 
1694 	vma = find_vma_prev(mm, range->start, &prev);
1695 	if (vma && range->start > vma->vm_start)
1696 		prev = vma;
1697 
1698 	for (;;) {
1699 		/* Still start < end. */
1700 		if (!vma)
1701 			return -ENOMEM;
1702 
1703 		/* Here start < (last_end|vma->vm_end). */
1704 		if (range->start < vma->vm_start) {
1705 			/*
1706 			 * This indicates a gap between VMAs in the input
1707 			 * range. This does not cause the operation to abort,
1708 			 * rather we simply return -ENOMEM to indicate that this
1709 			 * has happened, but carry on.
1710 			 */
1711 			unmapped_error = -ENOMEM;
1712 			range->start = vma->vm_start;
1713 			if (range->start >= last_end)
1714 				break;
1715 		}
1716 
1717 		/* Here vma->vm_start <= range->start < (last_end|vma->vm_end) */
1718 		range->end = min(vma->vm_end, last_end);
1719 
1720 		/* Here vma->vm_start <= range->start < range->end <= (last_end|vma->vm_end). */
1721 		madv_behavior->prev = prev;
1722 		madv_behavior->vma = vma;
1723 		error = madvise_vma_behavior(madv_behavior);
1724 		if (error)
1725 			return error;
1726 		if (madv_behavior->lock_dropped) {
1727 			/* We dropped the mmap lock, we can't ref the VMA. */
1728 			prev = NULL;
1729 			vma = NULL;
1730 			madv_behavior->lock_dropped = false;
1731 		} else {
1732 			vma = madv_behavior->vma;
1733 			prev = vma;
1734 		}
1735 
1736 		if (vma && range->end < vma->vm_end)
1737 			range->end = vma->vm_end;
1738 		if (range->end >= last_end)
1739 			break;
1740 
1741 		vma = find_vma(mm, vma ? vma->vm_end : range->end);
1742 		range->start = range->end;
1743 	}
1744 
1745 	return unmapped_error;
1746 }
1747 
1748 /*
1749  * Any behaviour which results in changes to the vma->vm_flags needs to
1750  * take mmap_lock for writing. Others, which simply traverse vmas, need
1751  * to only take it for reading.
1752  */
1753 static enum madvise_lock_mode get_lock_mode(struct madvise_behavior *madv_behavior)
1754 {
1755 	if (is_memory_failure(madv_behavior))
1756 		return MADVISE_NO_LOCK;
1757 
1758 	switch (madv_behavior->behavior) {
1759 	case MADV_REMOVE:
1760 	case MADV_WILLNEED:
1761 	case MADV_COLD:
1762 	case MADV_PAGEOUT:
1763 	case MADV_POPULATE_READ:
1764 	case MADV_POPULATE_WRITE:
1765 	case MADV_COLLAPSE:
1766 		return MADVISE_MMAP_READ_LOCK;
1767 	case MADV_GUARD_INSTALL:
1768 	case MADV_GUARD_REMOVE:
1769 	case MADV_DONTNEED:
1770 	case MADV_DONTNEED_LOCKED:
1771 	case MADV_FREE:
1772 		return MADVISE_VMA_READ_LOCK;
1773 	default:
1774 		return MADVISE_MMAP_WRITE_LOCK;
1775 	}
1776 }
1777 
1778 static int madvise_lock(struct madvise_behavior *madv_behavior)
1779 {
1780 	struct mm_struct *mm = madv_behavior->mm;
1781 	enum madvise_lock_mode lock_mode = get_lock_mode(madv_behavior);
1782 
1783 	switch (lock_mode) {
1784 	case MADVISE_NO_LOCK:
1785 		break;
1786 	case MADVISE_MMAP_WRITE_LOCK:
1787 		if (mmap_write_lock_killable(mm))
1788 			return -EINTR;
1789 		break;
1790 	case MADVISE_MMAP_READ_LOCK:
1791 		mmap_read_lock(mm);
1792 		break;
1793 	case MADVISE_VMA_READ_LOCK:
1794 		/* We will acquire the lock per-VMA in madvise_walk_vmas(). */
1795 		break;
1796 	}
1797 
1798 	madv_behavior->lock_mode = lock_mode;
1799 	return 0;
1800 }
1801 
1802 static void madvise_unlock(struct madvise_behavior *madv_behavior)
1803 {
1804 	struct mm_struct *mm = madv_behavior->mm;
1805 
1806 	switch (madv_behavior->lock_mode) {
1807 	case  MADVISE_NO_LOCK:
1808 		return;
1809 	case MADVISE_MMAP_WRITE_LOCK:
1810 		mmap_write_unlock(mm);
1811 		break;
1812 	case MADVISE_MMAP_READ_LOCK:
1813 		mmap_read_unlock(mm);
1814 		break;
1815 	case MADVISE_VMA_READ_LOCK:
1816 		/* We will drop the lock per-VMA in madvise_walk_vmas(). */
1817 		break;
1818 	}
1819 
1820 	madv_behavior->lock_mode = MADVISE_NO_LOCK;
1821 }
1822 
1823 static bool madvise_batch_tlb_flush(int behavior)
1824 {
1825 	switch (behavior) {
1826 	case MADV_DONTNEED:
1827 	case MADV_DONTNEED_LOCKED:
1828 	case MADV_FREE:
1829 		return true;
1830 	default:
1831 		return false;
1832 	}
1833 }
1834 
1835 static void madvise_init_tlb(struct madvise_behavior *madv_behavior)
1836 {
1837 	if (madvise_batch_tlb_flush(madv_behavior->behavior))
1838 		tlb_gather_mmu(madv_behavior->tlb, madv_behavior->mm);
1839 }
1840 
1841 static void madvise_finish_tlb(struct madvise_behavior *madv_behavior)
1842 {
1843 	if (madvise_batch_tlb_flush(madv_behavior->behavior))
1844 		tlb_finish_mmu(madv_behavior->tlb);
1845 }
1846 
1847 static bool is_valid_madvise(unsigned long start, size_t len_in, int behavior)
1848 {
1849 	size_t len;
1850 
1851 	if (!madvise_behavior_valid(behavior))
1852 		return false;
1853 
1854 	if (!PAGE_ALIGNED(start))
1855 		return false;
1856 	len = PAGE_ALIGN(len_in);
1857 
1858 	/* Check to see whether len was rounded up from small -ve to zero */
1859 	if (len_in && !len)
1860 		return false;
1861 
1862 	if (start + len < start)
1863 		return false;
1864 
1865 	return true;
1866 }
1867 
1868 /*
1869  * madvise_should_skip() - Return if the request is invalid or nothing.
1870  * @start:	Start address of madvise-requested address range.
1871  * @len_in:	Length of madvise-requested address range.
1872  * @behavior:	Requested madvise behavor.
1873  * @err:	Pointer to store an error code from the check.
1874  *
1875  * If the specified behaviour is invalid or nothing would occur, we skip the
1876  * operation.  This function returns true in the cases, otherwise false.  In
1877  * the former case we store an error on @err.
1878  */
1879 static bool madvise_should_skip(unsigned long start, size_t len_in,
1880 		int behavior, int *err)
1881 {
1882 	if (!is_valid_madvise(start, len_in, behavior)) {
1883 		*err = -EINVAL;
1884 		return true;
1885 	}
1886 	if (start + PAGE_ALIGN(len_in) == start) {
1887 		*err = 0;
1888 		return true;
1889 	}
1890 	return false;
1891 }
1892 
1893 static bool is_madvise_populate(struct madvise_behavior *madv_behavior)
1894 {
1895 	switch (madv_behavior->behavior) {
1896 	case MADV_POPULATE_READ:
1897 	case MADV_POPULATE_WRITE:
1898 		return true;
1899 	default:
1900 		return false;
1901 	}
1902 }
1903 
1904 /*
1905  * untagged_addr_remote() assumes mmap_lock is already held. On
1906  * architectures like x86 and RISC-V, tagging is tricky because each
1907  * mm may have a different tagging mask. However, we might only hold
1908  * the per-VMA lock (currently only local processes are supported),
1909  * so untagged_addr is used to avoid the mmap_lock assertion for
1910  * local processes.
1911  */
1912 static inline unsigned long get_untagged_addr(struct mm_struct *mm,
1913 		unsigned long start)
1914 {
1915 	return current->mm == mm ? untagged_addr(start) :
1916 				   untagged_addr_remote(mm, start);
1917 }
1918 
1919 static int madvise_do_behavior(unsigned long start, size_t len_in,
1920 		struct madvise_behavior *madv_behavior)
1921 {
1922 	struct blk_plug plug;
1923 	int error;
1924 	struct madvise_behavior_range *range = &madv_behavior->range;
1925 
1926 	if (is_memory_failure(madv_behavior)) {
1927 		range->start = start;
1928 		range->end = start + len_in;
1929 		return madvise_inject_error(madv_behavior);
1930 	}
1931 
1932 	range->start = get_untagged_addr(madv_behavior->mm, start);
1933 	range->end = range->start + PAGE_ALIGN(len_in);
1934 
1935 	blk_start_plug(&plug);
1936 	if (is_madvise_populate(madv_behavior))
1937 		error = madvise_populate(madv_behavior);
1938 	else
1939 		error = madvise_walk_vmas(madv_behavior);
1940 	blk_finish_plug(&plug);
1941 	return error;
1942 }
1943 
1944 /*
1945  * The madvise(2) system call.
1946  *
1947  * Applications can use madvise() to advise the kernel how it should
1948  * handle paging I/O in this VM area.  The idea is to help the kernel
1949  * use appropriate read-ahead and caching techniques.  The information
1950  * provided is advisory only, and can be safely disregarded by the
1951  * kernel without affecting the correct operation of the application.
1952  *
1953  * behavior values:
1954  *  MADV_NORMAL - the default behavior is to read clusters.  This
1955  *		results in some read-ahead and read-behind.
1956  *  MADV_RANDOM - the system should read the minimum amount of data
1957  *		on any access, since it is unlikely that the appli-
1958  *		cation will need more than what it asks for.
1959  *  MADV_SEQUENTIAL - pages in the given range will probably be accessed
1960  *		once, so they can be aggressively read ahead, and
1961  *		can be freed soon after they are accessed.
1962  *  MADV_WILLNEED - the application is notifying the system to read
1963  *		some pages ahead.
1964  *  MADV_DONTNEED - the application is finished with the given range,
1965  *		so the kernel can free resources associated with it.
1966  *  MADV_FREE - the application marks pages in the given range as lazy free,
1967  *		where actual purges are postponed until memory pressure happens.
1968  *  MADV_REMOVE - the application wants to free up the given range of
1969  *		pages and associated backing store.
1970  *  MADV_DONTFORK - omit this area from child's address space when forking:
1971  *		typically, to avoid COWing pages pinned by get_user_pages().
1972  *  MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
1973  *  MADV_WIPEONFORK - present the child process with zero-filled memory in this
1974  *              range after a fork.
1975  *  MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
1976  *  MADV_HWPOISON - trigger memory error handler as if the given memory range
1977  *		were corrupted by unrecoverable hardware memory failure.
1978  *  MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
1979  *  MADV_MERGEABLE - the application recommends that KSM try to merge pages in
1980  *		this area with pages of identical content from other such areas.
1981  *  MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
1982  *  MADV_HUGEPAGE - the application wants to back the given range by transparent
1983  *		huge pages in the future. Existing pages might be coalesced and
1984  *		new pages might be allocated as THP.
1985  *  MADV_NOHUGEPAGE - mark the given range as not worth being backed by
1986  *		transparent huge pages so the existing pages will not be
1987  *		coalesced into THP and new pages will not be allocated as THP.
1988  *  MADV_COLLAPSE - synchronously coalesce pages into new THP.
1989  *  MADV_DONTDUMP - the application wants to prevent pages in the given range
1990  *		from being included in its core dump.
1991  *  MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
1992  *  MADV_COLD - the application is not expected to use this memory soon,
1993  *		deactivate pages in this range so that they can be reclaimed
1994  *		easily if memory pressure happens.
1995  *  MADV_PAGEOUT - the application is not expected to use this memory soon,
1996  *		page out the pages in this range immediately.
1997  *  MADV_POPULATE_READ - populate (prefault) page tables readable by
1998  *		triggering read faults if required
1999  *  MADV_POPULATE_WRITE - populate (prefault) page tables writable by
2000  *		triggering write faults if required
2001  *
2002  * return values:
2003  *  zero    - success
2004  *  -EINVAL - start + len < 0, start is not page-aligned,
2005  *		"behavior" is not a valid value, or application
2006  *		is attempting to release locked or shared pages,
2007  *		or the specified address range includes file, Huge TLB,
2008  *		MAP_SHARED or VMPFNMAP range.
2009  *  -ENOMEM - addresses in the specified range are not currently
2010  *		mapped, or are outside the AS of the process.
2011  *  -EIO    - an I/O error occurred while paging in data.
2012  *  -EBADF  - map exists, but area maps something that isn't a file.
2013  *  -EAGAIN - a kernel resource was temporarily unavailable.
2014  *  -EPERM  - memory is sealed.
2015  */
2016 int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int behavior)
2017 {
2018 	int error;
2019 	struct mmu_gather tlb;
2020 	struct madvise_behavior madv_behavior = {
2021 		.mm = mm,
2022 		.behavior = behavior,
2023 		.tlb = &tlb,
2024 	};
2025 
2026 	if (madvise_should_skip(start, len_in, behavior, &error))
2027 		return error;
2028 	error = madvise_lock(&madv_behavior);
2029 	if (error)
2030 		return error;
2031 	madvise_init_tlb(&madv_behavior);
2032 	error = madvise_do_behavior(start, len_in, &madv_behavior);
2033 	madvise_finish_tlb(&madv_behavior);
2034 	madvise_unlock(&madv_behavior);
2035 
2036 	return error;
2037 }
2038 
2039 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
2040 {
2041 	return do_madvise(current->mm, start, len_in, behavior);
2042 }
2043 
2044 /* Perform an madvise operation over a vector of addresses and lengths. */
2045 static ssize_t vector_madvise(struct mm_struct *mm, struct iov_iter *iter,
2046 			      int behavior)
2047 {
2048 	ssize_t ret = 0;
2049 	size_t total_len;
2050 	struct mmu_gather tlb;
2051 	struct madvise_behavior madv_behavior = {
2052 		.mm = mm,
2053 		.behavior = behavior,
2054 		.tlb = &tlb,
2055 	};
2056 
2057 	total_len = iov_iter_count(iter);
2058 
2059 	ret = madvise_lock(&madv_behavior);
2060 	if (ret)
2061 		return ret;
2062 	madvise_init_tlb(&madv_behavior);
2063 
2064 	while (iov_iter_count(iter)) {
2065 		unsigned long start = (unsigned long)iter_iov_addr(iter);
2066 		size_t len_in = iter_iov_len(iter);
2067 		int error;
2068 
2069 		if (madvise_should_skip(start, len_in, behavior, &error))
2070 			ret = error;
2071 		else
2072 			ret = madvise_do_behavior(start, len_in, &madv_behavior);
2073 		/*
2074 		 * An madvise operation is attempting to restart the syscall,
2075 		 * but we cannot proceed as it would not be correct to repeat
2076 		 * the operation in aggregate, and would be surprising to the
2077 		 * user.
2078 		 *
2079 		 * We drop and reacquire locks so it is safe to just loop and
2080 		 * try again. We check for fatal signals in case we need exit
2081 		 * early anyway.
2082 		 */
2083 		if (ret == -ERESTARTNOINTR) {
2084 			if (fatal_signal_pending(current)) {
2085 				ret = -EINTR;
2086 				break;
2087 			}
2088 
2089 			/* Drop and reacquire lock to unwind race. */
2090 			madvise_finish_tlb(&madv_behavior);
2091 			madvise_unlock(&madv_behavior);
2092 			ret = madvise_lock(&madv_behavior);
2093 			if (ret)
2094 				goto out;
2095 			madvise_init_tlb(&madv_behavior);
2096 			continue;
2097 		}
2098 		if (ret < 0)
2099 			break;
2100 		iov_iter_advance(iter, iter_iov_len(iter));
2101 	}
2102 	madvise_finish_tlb(&madv_behavior);
2103 	madvise_unlock(&madv_behavior);
2104 
2105 out:
2106 	ret = (total_len - iov_iter_count(iter)) ? : ret;
2107 
2108 	return ret;
2109 }
2110 
2111 SYSCALL_DEFINE5(process_madvise, int, pidfd, const struct iovec __user *, vec,
2112 		size_t, vlen, int, behavior, unsigned int, flags)
2113 {
2114 	ssize_t ret;
2115 	struct iovec iovstack[UIO_FASTIOV];
2116 	struct iovec *iov = iovstack;
2117 	struct iov_iter iter;
2118 	struct task_struct *task;
2119 	struct mm_struct *mm;
2120 	unsigned int f_flags;
2121 
2122 	if (flags != 0) {
2123 		ret = -EINVAL;
2124 		goto out;
2125 	}
2126 
2127 	ret = import_iovec(ITER_DEST, vec, vlen, ARRAY_SIZE(iovstack), &iov, &iter);
2128 	if (ret < 0)
2129 		goto out;
2130 
2131 	task = pidfd_get_task(pidfd, &f_flags);
2132 	if (IS_ERR(task)) {
2133 		ret = PTR_ERR(task);
2134 		goto free_iov;
2135 	}
2136 
2137 	/* Require PTRACE_MODE_READ to avoid leaking ASLR metadata. */
2138 	mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
2139 	if (IS_ERR(mm)) {
2140 		ret = PTR_ERR(mm);
2141 		goto release_task;
2142 	}
2143 
2144 	/*
2145 	 * We need only perform this check if we are attempting to manipulate a
2146 	 * remote process's address space.
2147 	 */
2148 	if (mm != current->mm && !process_madvise_remote_valid(behavior)) {
2149 		ret = -EINVAL;
2150 		goto release_mm;
2151 	}
2152 
2153 	/*
2154 	 * Require CAP_SYS_NICE for influencing process performance. Note that
2155 	 * only non-destructive hints are currently supported for remote
2156 	 * processes.
2157 	 */
2158 	if (mm != current->mm && !capable(CAP_SYS_NICE)) {
2159 		ret = -EPERM;
2160 		goto release_mm;
2161 	}
2162 
2163 	ret = vector_madvise(mm, &iter, behavior);
2164 
2165 release_mm:
2166 	mmput(mm);
2167 release_task:
2168 	put_task_struct(task);
2169 free_iov:
2170 	kfree(iov);
2171 out:
2172 	return ret;
2173 }
2174 
2175 #ifdef CONFIG_ANON_VMA_NAME
2176 
2177 #define ANON_VMA_NAME_MAX_LEN		80
2178 #define ANON_VMA_NAME_INVALID_CHARS	"\\`$[]"
2179 
2180 static inline bool is_valid_name_char(char ch)
2181 {
2182 	/* printable ascii characters, excluding ANON_VMA_NAME_INVALID_CHARS */
2183 	return ch > 0x1f && ch < 0x7f &&
2184 		!strchr(ANON_VMA_NAME_INVALID_CHARS, ch);
2185 }
2186 
2187 static int madvise_set_anon_name(struct mm_struct *mm, unsigned long start,
2188 		unsigned long len_in, struct anon_vma_name *anon_name)
2189 {
2190 	unsigned long end;
2191 	unsigned long len;
2192 	int error;
2193 	struct madvise_behavior madv_behavior = {
2194 		.mm = mm,
2195 		.behavior = __MADV_SET_ANON_VMA_NAME,
2196 		.anon_name = anon_name,
2197 	};
2198 
2199 	if (start & ~PAGE_MASK)
2200 		return -EINVAL;
2201 	len = (len_in + ~PAGE_MASK) & PAGE_MASK;
2202 
2203 	/* Check to see whether len was rounded up from small -ve to zero */
2204 	if (len_in && !len)
2205 		return -EINVAL;
2206 
2207 	end = start + len;
2208 	if (end < start)
2209 		return -EINVAL;
2210 
2211 	if (end == start)
2212 		return 0;
2213 
2214 	madv_behavior.range.start = start;
2215 	madv_behavior.range.end = end;
2216 
2217 	error = madvise_lock(&madv_behavior);
2218 	if (error)
2219 		return error;
2220 	error = madvise_walk_vmas(&madv_behavior);
2221 	madvise_unlock(&madv_behavior);
2222 
2223 	return error;
2224 }
2225 
2226 int set_anon_vma_name(unsigned long addr, unsigned long size,
2227 		      const char __user *uname)
2228 {
2229 	struct anon_vma_name *anon_name = NULL;
2230 	struct mm_struct *mm = current->mm;
2231 	int error;
2232 
2233 	if (uname) {
2234 		char *name, *pch;
2235 
2236 		name = strndup_user(uname, ANON_VMA_NAME_MAX_LEN);
2237 		if (IS_ERR(name))
2238 			return PTR_ERR(name);
2239 
2240 		for (pch = name; *pch != '\0'; pch++) {
2241 			if (!is_valid_name_char(*pch)) {
2242 				kfree(name);
2243 				return -EINVAL;
2244 			}
2245 		}
2246 		/* anon_vma has its own copy */
2247 		anon_name = anon_vma_name_alloc(name);
2248 		kfree(name);
2249 		if (!anon_name)
2250 			return -ENOMEM;
2251 	}
2252 
2253 	error = madvise_set_anon_name(mm, addr, size, anon_name);
2254 	anon_vma_name_put(anon_name);
2255 
2256 	return error;
2257 }
2258 #endif
2259