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