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