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