xref: /linux/mm/mprotect.c (revision beace86e61e465dba204a268ab3f3377153a4973)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  mm/mprotect.c
4  *
5  *  (C) Copyright 1994 Linus Torvalds
6  *  (C) Copyright 2002 Christoph Hellwig
7  *
8  *  Address space accounting code	<alan@lxorguk.ukuu.org.uk>
9  *  (C) Copyright 2002 Red Hat Inc, All Rights Reserved
10  */
11 
12 #include <linux/pagewalk.h>
13 #include <linux/hugetlb.h>
14 #include <linux/shm.h>
15 #include <linux/mman.h>
16 #include <linux/fs.h>
17 #include <linux/highmem.h>
18 #include <linux/security.h>
19 #include <linux/mempolicy.h>
20 #include <linux/personality.h>
21 #include <linux/syscalls.h>
22 #include <linux/swap.h>
23 #include <linux/swapops.h>
24 #include <linux/mmu_notifier.h>
25 #include <linux/migrate.h>
26 #include <linux/perf_event.h>
27 #include <linux/pkeys.h>
28 #include <linux/ksm.h>
29 #include <linux/uaccess.h>
30 #include <linux/mm_inline.h>
31 #include <linux/pgtable.h>
32 #include <linux/sched/sysctl.h>
33 #include <linux/userfaultfd_k.h>
34 #include <linux/memory-tiers.h>
35 #include <uapi/linux/mman.h>
36 #include <asm/cacheflush.h>
37 #include <asm/mmu_context.h>
38 #include <asm/tlbflush.h>
39 #include <asm/tlb.h>
40 
41 #include "internal.h"
42 
43 static bool maybe_change_pte_writable(struct vm_area_struct *vma, pte_t pte)
44 {
45 	if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE)))
46 		return false;
47 
48 	/* Don't touch entries that are not even readable. */
49 	if (pte_protnone(pte))
50 		return false;
51 
52 	/* Do we need write faults for softdirty tracking? */
53 	if (pte_needs_soft_dirty_wp(vma, pte))
54 		return false;
55 
56 	/* Do we need write faults for uffd-wp tracking? */
57 	if (userfaultfd_pte_wp(vma, pte))
58 		return false;
59 
60 	return true;
61 }
62 
63 static bool can_change_private_pte_writable(struct vm_area_struct *vma,
64 					    unsigned long addr, pte_t pte)
65 {
66 	struct page *page;
67 
68 	if (!maybe_change_pte_writable(vma, pte))
69 		return false;
70 
71 	/*
72 	 * Writable MAP_PRIVATE mapping: We can only special-case on
73 	 * exclusive anonymous pages, because we know that our
74 	 * write-fault handler similarly would map them writable without
75 	 * any additional checks while holding the PT lock.
76 	 */
77 	page = vm_normal_page(vma, addr, pte);
78 	return page && PageAnon(page) && PageAnonExclusive(page);
79 }
80 
81 static bool can_change_shared_pte_writable(struct vm_area_struct *vma,
82 					   pte_t pte)
83 {
84 	if (!maybe_change_pte_writable(vma, pte))
85 		return false;
86 
87 	VM_WARN_ON_ONCE(is_zero_pfn(pte_pfn(pte)) && pte_dirty(pte));
88 
89 	/*
90 	 * Writable MAP_SHARED mapping: "clean" might indicate that the FS still
91 	 * needs a real write-fault for writenotify
92 	 * (see vma_wants_writenotify()). If "dirty", the assumption is that the
93 	 * FS was already notified and we can simply mark the PTE writable
94 	 * just like the write-fault handler would do.
95 	 */
96 	return pte_dirty(pte);
97 }
98 
99 bool can_change_pte_writable(struct vm_area_struct *vma, unsigned long addr,
100 			     pte_t pte)
101 {
102 	if (!(vma->vm_flags & VM_SHARED))
103 		return can_change_private_pte_writable(vma, addr, pte);
104 
105 	return can_change_shared_pte_writable(vma, pte);
106 }
107 
108 static int mprotect_folio_pte_batch(struct folio *folio, pte_t *ptep,
109 				    pte_t pte, int max_nr_ptes, fpb_t flags)
110 {
111 	/* No underlying folio, so cannot batch */
112 	if (!folio)
113 		return 1;
114 
115 	if (!folio_test_large(folio))
116 		return 1;
117 
118 	return folio_pte_batch_flags(folio, NULL, ptep, &pte, max_nr_ptes, flags);
119 }
120 
121 static bool prot_numa_skip(struct vm_area_struct *vma, unsigned long addr,
122 			   pte_t oldpte, pte_t *pte, int target_node,
123 			   struct folio **foliop)
124 {
125 	struct folio *folio = NULL;
126 	bool ret = true;
127 	bool toptier;
128 	int nid;
129 
130 	/* Avoid TLB flush if possible */
131 	if (pte_protnone(oldpte))
132 		goto skip;
133 
134 	folio = vm_normal_folio(vma, addr, oldpte);
135 	if (!folio)
136 		goto skip;
137 
138 	if (folio_is_zone_device(folio) || folio_test_ksm(folio))
139 		goto skip;
140 
141 	/* Also skip shared copy-on-write pages */
142 	if (is_cow_mapping(vma->vm_flags) &&
143 	    (folio_maybe_dma_pinned(folio) || folio_maybe_mapped_shared(folio)))
144 		goto skip;
145 
146 	/*
147 	 * While migration can move some dirty pages,
148 	 * it cannot move them all from MIGRATE_ASYNC
149 	 * context.
150 	 */
151 	if (folio_is_file_lru(folio) && folio_test_dirty(folio))
152 		goto skip;
153 
154 	/*
155 	 * Don't mess with PTEs if page is already on the node
156 	 * a single-threaded process is running on.
157 	 */
158 	nid = folio_nid(folio);
159 	if (target_node == nid)
160 		goto skip;
161 
162 	toptier = node_is_toptier(nid);
163 
164 	/*
165 	 * Skip scanning top tier node if normal numa
166 	 * balancing is disabled
167 	 */
168 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) && toptier)
169 		goto skip;
170 
171 	ret = false;
172 	if (folio_use_access_time(folio))
173 		folio_xchg_access_time(folio, jiffies_to_msecs(jiffies));
174 
175 skip:
176 	*foliop = folio;
177 	return ret;
178 }
179 
180 /* Set nr_ptes number of ptes, starting from idx */
181 static void prot_commit_flush_ptes(struct vm_area_struct *vma, unsigned long addr,
182 		pte_t *ptep, pte_t oldpte, pte_t ptent, int nr_ptes,
183 		int idx, bool set_write, struct mmu_gather *tlb)
184 {
185 	/*
186 	 * Advance the position in the batch by idx; note that if idx > 0,
187 	 * then the nr_ptes passed here is <= batch size - idx.
188 	 */
189 	addr += idx * PAGE_SIZE;
190 	ptep += idx;
191 	oldpte = pte_advance_pfn(oldpte, idx);
192 	ptent = pte_advance_pfn(ptent, idx);
193 
194 	if (set_write)
195 		ptent = pte_mkwrite(ptent, vma);
196 
197 	modify_prot_commit_ptes(vma, addr, ptep, oldpte, ptent, nr_ptes);
198 	if (pte_needs_flush(oldpte, ptent))
199 		tlb_flush_pte_range(tlb, addr, nr_ptes * PAGE_SIZE);
200 }
201 
202 /*
203  * Get max length of consecutive ptes pointing to PageAnonExclusive() pages or
204  * !PageAnonExclusive() pages, starting from start_idx. Caller must enforce
205  * that the ptes point to consecutive pages of the same anon large folio.
206  */
207 static int page_anon_exclusive_sub_batch(int start_idx, int max_len,
208 		struct page *first_page, bool expected_anon_exclusive)
209 {
210 	int idx;
211 
212 	for (idx = start_idx + 1; idx < start_idx + max_len; ++idx) {
213 		if (expected_anon_exclusive != PageAnonExclusive(first_page + idx))
214 			break;
215 	}
216 	return idx - start_idx;
217 }
218 
219 /*
220  * This function is a result of trying our very best to retain the
221  * "avoid the write-fault handler" optimization. In can_change_pte_writable(),
222  * if the vma is a private vma, and we cannot determine whether to change
223  * the pte to writable just from the vma and the pte, we then need to look
224  * at the actual page pointed to by the pte. Unfortunately, if we have a
225  * batch of ptes pointing to consecutive pages of the same anon large folio,
226  * the anon-exclusivity (or the negation) of the first page does not guarantee
227  * the anon-exclusivity (or the negation) of the other pages corresponding to
228  * the pte batch; hence in this case it is incorrect to decide to change or
229  * not change the ptes to writable just by using information from the first
230  * pte of the batch. Therefore, we must individually check all pages and
231  * retrieve sub-batches.
232  */
233 static void commit_anon_folio_batch(struct vm_area_struct *vma,
234 		struct folio *folio, unsigned long addr, pte_t *ptep,
235 		pte_t oldpte, pte_t ptent, int nr_ptes, struct mmu_gather *tlb)
236 {
237 	struct page *first_page = folio_page(folio, 0);
238 	bool expected_anon_exclusive;
239 	int sub_batch_idx = 0;
240 	int len;
241 
242 	while (nr_ptes) {
243 		expected_anon_exclusive = PageAnonExclusive(first_page + sub_batch_idx);
244 		len = page_anon_exclusive_sub_batch(sub_batch_idx, nr_ptes,
245 					first_page, expected_anon_exclusive);
246 		prot_commit_flush_ptes(vma, addr, ptep, oldpte, ptent, len,
247 				       sub_batch_idx, expected_anon_exclusive, tlb);
248 		sub_batch_idx += len;
249 		nr_ptes -= len;
250 	}
251 }
252 
253 static void set_write_prot_commit_flush_ptes(struct vm_area_struct *vma,
254 		struct folio *folio, unsigned long addr, pte_t *ptep,
255 		pte_t oldpte, pte_t ptent, int nr_ptes, struct mmu_gather *tlb)
256 {
257 	bool set_write;
258 
259 	if (vma->vm_flags & VM_SHARED) {
260 		set_write = can_change_shared_pte_writable(vma, ptent);
261 		prot_commit_flush_ptes(vma, addr, ptep, oldpte, ptent, nr_ptes,
262 				       /* idx = */ 0, set_write, tlb);
263 		return;
264 	}
265 
266 	set_write = maybe_change_pte_writable(vma, ptent) &&
267 		    (folio && folio_test_anon(folio));
268 	if (!set_write) {
269 		prot_commit_flush_ptes(vma, addr, ptep, oldpte, ptent, nr_ptes,
270 				       /* idx = */ 0, set_write, tlb);
271 		return;
272 	}
273 	commit_anon_folio_batch(vma, folio, addr, ptep, oldpte, ptent, nr_ptes, tlb);
274 }
275 
276 static long change_pte_range(struct mmu_gather *tlb,
277 		struct vm_area_struct *vma, pmd_t *pmd, unsigned long addr,
278 		unsigned long end, pgprot_t newprot, unsigned long cp_flags)
279 {
280 	pte_t *pte, oldpte;
281 	spinlock_t *ptl;
282 	long pages = 0;
283 	int target_node = NUMA_NO_NODE;
284 	bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
285 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
286 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
287 	int nr_ptes;
288 
289 	tlb_change_page_size(tlb, PAGE_SIZE);
290 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
291 	if (!pte)
292 		return -EAGAIN;
293 
294 	/* Get target node for single threaded private VMAs */
295 	if (prot_numa && !(vma->vm_flags & VM_SHARED) &&
296 	    atomic_read(&vma->vm_mm->mm_users) == 1)
297 		target_node = numa_node_id();
298 
299 	flush_tlb_batched_pending(vma->vm_mm);
300 	arch_enter_lazy_mmu_mode();
301 	do {
302 		nr_ptes = 1;
303 		oldpte = ptep_get(pte);
304 		if (pte_present(oldpte)) {
305 			const fpb_t flags = FPB_RESPECT_SOFT_DIRTY | FPB_RESPECT_WRITE;
306 			int max_nr_ptes = (end - addr) >> PAGE_SHIFT;
307 			struct folio *folio = NULL;
308 			pte_t ptent;
309 
310 			/*
311 			 * Avoid trapping faults against the zero or KSM
312 			 * pages. See similar comment in change_huge_pmd.
313 			 */
314 			if (prot_numa) {
315 				int ret = prot_numa_skip(vma, addr, oldpte, pte,
316 							 target_node, &folio);
317 				if (ret) {
318 
319 					/* determine batch to skip */
320 					nr_ptes = mprotect_folio_pte_batch(folio,
321 						  pte, oldpte, max_nr_ptes, /* flags = */ 0);
322 					continue;
323 				}
324 			}
325 
326 			if (!folio)
327 				folio = vm_normal_folio(vma, addr, oldpte);
328 
329 			nr_ptes = mprotect_folio_pte_batch(folio, pte, oldpte, max_nr_ptes, flags);
330 
331 			oldpte = modify_prot_start_ptes(vma, addr, pte, nr_ptes);
332 			ptent = pte_modify(oldpte, newprot);
333 
334 			if (uffd_wp)
335 				ptent = pte_mkuffd_wp(ptent);
336 			else if (uffd_wp_resolve)
337 				ptent = pte_clear_uffd_wp(ptent);
338 
339 			/*
340 			 * In some writable, shared mappings, we might want
341 			 * to catch actual write access -- see
342 			 * vma_wants_writenotify().
343 			 *
344 			 * In all writable, private mappings, we have to
345 			 * properly handle COW.
346 			 *
347 			 * In both cases, we can sometimes still change PTEs
348 			 * writable and avoid the write-fault handler, for
349 			 * example, if a PTE is already dirty and no other
350 			 * COW or special handling is required.
351 			 */
352 			if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) &&
353 			     !pte_write(ptent))
354 				set_write_prot_commit_flush_ptes(vma, folio,
355 				addr, pte, oldpte, ptent, nr_ptes, tlb);
356 			else
357 				prot_commit_flush_ptes(vma, addr, pte, oldpte, ptent,
358 					nr_ptes, /* idx = */ 0, /* set_write = */ false, tlb);
359 			pages += nr_ptes;
360 		} else if (is_swap_pte(oldpte)) {
361 			swp_entry_t entry = pte_to_swp_entry(oldpte);
362 			pte_t newpte;
363 
364 			if (is_writable_migration_entry(entry)) {
365 				struct folio *folio = pfn_swap_entry_folio(entry);
366 
367 				/*
368 				 * A protection check is difficult so
369 				 * just be safe and disable write
370 				 */
371 				if (folio_test_anon(folio))
372 					entry = make_readable_exclusive_migration_entry(
373 							     swp_offset(entry));
374 				else
375 					entry = make_readable_migration_entry(swp_offset(entry));
376 				newpte = swp_entry_to_pte(entry);
377 				if (pte_swp_soft_dirty(oldpte))
378 					newpte = pte_swp_mksoft_dirty(newpte);
379 			} else if (is_writable_device_private_entry(entry)) {
380 				/*
381 				 * We do not preserve soft-dirtiness. See
382 				 * copy_nonpresent_pte() for explanation.
383 				 */
384 				entry = make_readable_device_private_entry(
385 							swp_offset(entry));
386 				newpte = swp_entry_to_pte(entry);
387 				if (pte_swp_uffd_wp(oldpte))
388 					newpte = pte_swp_mkuffd_wp(newpte);
389 			} else if (is_pte_marker_entry(entry)) {
390 				/*
391 				 * Ignore error swap entries unconditionally,
392 				 * because any access should sigbus/sigsegv
393 				 * anyway.
394 				 */
395 				if (is_poisoned_swp_entry(entry) ||
396 				    is_guard_swp_entry(entry))
397 					continue;
398 				/*
399 				 * If this is uffd-wp pte marker and we'd like
400 				 * to unprotect it, drop it; the next page
401 				 * fault will trigger without uffd trapping.
402 				 */
403 				if (uffd_wp_resolve) {
404 					pte_clear(vma->vm_mm, addr, pte);
405 					pages++;
406 				}
407 				continue;
408 			} else {
409 				newpte = oldpte;
410 			}
411 
412 			if (uffd_wp)
413 				newpte = pte_swp_mkuffd_wp(newpte);
414 			else if (uffd_wp_resolve)
415 				newpte = pte_swp_clear_uffd_wp(newpte);
416 
417 			if (!pte_same(oldpte, newpte)) {
418 				set_pte_at(vma->vm_mm, addr, pte, newpte);
419 				pages++;
420 			}
421 		} else {
422 			/* It must be an none page, or what else?.. */
423 			WARN_ON_ONCE(!pte_none(oldpte));
424 
425 			/*
426 			 * Nobody plays with any none ptes besides
427 			 * userfaultfd when applying the protections.
428 			 */
429 			if (likely(!uffd_wp))
430 				continue;
431 
432 			if (userfaultfd_wp_use_markers(vma)) {
433 				/*
434 				 * For file-backed mem, we need to be able to
435 				 * wr-protect a none pte, because even if the
436 				 * pte is none, the page/swap cache could
437 				 * exist.  Doing that by install a marker.
438 				 */
439 				set_pte_at(vma->vm_mm, addr, pte,
440 					   make_pte_marker(PTE_MARKER_UFFD_WP));
441 				pages++;
442 			}
443 		}
444 	} while (pte += nr_ptes, addr += nr_ptes * PAGE_SIZE, addr != end);
445 	arch_leave_lazy_mmu_mode();
446 	pte_unmap_unlock(pte - 1, ptl);
447 
448 	return pages;
449 }
450 
451 /*
452  * Return true if we want to split THPs into PTE mappings in change
453  * protection procedure, false otherwise.
454  */
455 static inline bool
456 pgtable_split_needed(struct vm_area_struct *vma, unsigned long cp_flags)
457 {
458 	/*
459 	 * pte markers only resides in pte level, if we need pte markers,
460 	 * we need to split.  For example, we cannot wr-protect a file thp
461 	 * (e.g. 2M shmem) because file thp is handled differently when
462 	 * split by erasing the pmd so far.
463 	 */
464 	return (cp_flags & MM_CP_UFFD_WP) && !vma_is_anonymous(vma);
465 }
466 
467 /*
468  * Return true if we want to populate pgtables in change protection
469  * procedure, false otherwise
470  */
471 static inline bool
472 pgtable_populate_needed(struct vm_area_struct *vma, unsigned long cp_flags)
473 {
474 	/* If not within ioctl(UFFDIO_WRITEPROTECT), then don't bother */
475 	if (!(cp_flags & MM_CP_UFFD_WP))
476 		return false;
477 
478 	/* Populate if the userfaultfd mode requires pte markers */
479 	return userfaultfd_wp_use_markers(vma);
480 }
481 
482 /*
483  * Populate the pgtable underneath for whatever reason if requested.
484  * When {pte|pmd|...}_alloc() failed we treat it the same way as pgtable
485  * allocation failures during page faults by kicking OOM and returning
486  * error.
487  */
488 #define  change_pmd_prepare(vma, pmd, cp_flags)				\
489 	({								\
490 		long err = 0;						\
491 		if (unlikely(pgtable_populate_needed(vma, cp_flags))) {	\
492 			if (pte_alloc(vma->vm_mm, pmd))			\
493 				err = -ENOMEM;				\
494 		}							\
495 		err;							\
496 	})
497 
498 /*
499  * This is the general pud/p4d/pgd version of change_pmd_prepare(). We need to
500  * have separate change_pmd_prepare() because pte_alloc() returns 0 on success,
501  * while {pmd|pud|p4d}_alloc() returns the valid pointer on success.
502  */
503 #define  change_prepare(vma, high, low, addr, cp_flags)			\
504 	  ({								\
505 		long err = 0;						\
506 		if (unlikely(pgtable_populate_needed(vma, cp_flags))) {	\
507 			low##_t *p = low##_alloc(vma->vm_mm, high, addr); \
508 			if (p == NULL)					\
509 				err = -ENOMEM;				\
510 		}							\
511 		err;							\
512 	})
513 
514 static inline long change_pmd_range(struct mmu_gather *tlb,
515 		struct vm_area_struct *vma, pud_t *pud, unsigned long addr,
516 		unsigned long end, pgprot_t newprot, unsigned long cp_flags)
517 {
518 	pmd_t *pmd;
519 	unsigned long next;
520 	long pages = 0;
521 	unsigned long nr_huge_updates = 0;
522 
523 	pmd = pmd_offset(pud, addr);
524 	do {
525 		long ret;
526 		pmd_t _pmd;
527 again:
528 		next = pmd_addr_end(addr, end);
529 
530 		ret = change_pmd_prepare(vma, pmd, cp_flags);
531 		if (ret) {
532 			pages = ret;
533 			break;
534 		}
535 
536 		if (pmd_none(*pmd))
537 			goto next;
538 
539 		_pmd = pmdp_get_lockless(pmd);
540 		if (is_swap_pmd(_pmd) || pmd_trans_huge(_pmd)) {
541 			if ((next - addr != HPAGE_PMD_SIZE) ||
542 			    pgtable_split_needed(vma, cp_flags)) {
543 				__split_huge_pmd(vma, pmd, addr, false);
544 				/*
545 				 * For file-backed, the pmd could have been
546 				 * cleared; make sure pmd populated if
547 				 * necessary, then fall-through to pte level.
548 				 */
549 				ret = change_pmd_prepare(vma, pmd, cp_flags);
550 				if (ret) {
551 					pages = ret;
552 					break;
553 				}
554 			} else {
555 				ret = change_huge_pmd(tlb, vma, pmd,
556 						addr, newprot, cp_flags);
557 				if (ret) {
558 					if (ret == HPAGE_PMD_NR) {
559 						pages += HPAGE_PMD_NR;
560 						nr_huge_updates++;
561 					}
562 
563 					/* huge pmd was handled */
564 					goto next;
565 				}
566 			}
567 			/* fall through, the trans huge pmd just split */
568 		}
569 
570 		ret = change_pte_range(tlb, vma, pmd, addr, next, newprot,
571 				       cp_flags);
572 		if (ret < 0)
573 			goto again;
574 		pages += ret;
575 next:
576 		cond_resched();
577 	} while (pmd++, addr = next, addr != end);
578 
579 	if (nr_huge_updates)
580 		count_vm_numa_events(NUMA_HUGE_PTE_UPDATES, nr_huge_updates);
581 	return pages;
582 }
583 
584 static inline long change_pud_range(struct mmu_gather *tlb,
585 		struct vm_area_struct *vma, p4d_t *p4d, unsigned long addr,
586 		unsigned long end, pgprot_t newprot, unsigned long cp_flags)
587 {
588 	struct mmu_notifier_range range;
589 	pud_t *pudp, pud;
590 	unsigned long next;
591 	long pages = 0, ret;
592 
593 	range.start = 0;
594 
595 	pudp = pud_offset(p4d, addr);
596 	do {
597 again:
598 		next = pud_addr_end(addr, end);
599 		ret = change_prepare(vma, pudp, pmd, addr, cp_flags);
600 		if (ret) {
601 			pages = ret;
602 			break;
603 		}
604 
605 		pud = READ_ONCE(*pudp);
606 		if (pud_none(pud))
607 			continue;
608 
609 		if (!range.start) {
610 			mmu_notifier_range_init(&range,
611 						MMU_NOTIFY_PROTECTION_VMA, 0,
612 						vma->vm_mm, addr, end);
613 			mmu_notifier_invalidate_range_start(&range);
614 		}
615 
616 		if (pud_leaf(pud)) {
617 			if ((next - addr != PUD_SIZE) ||
618 			    pgtable_split_needed(vma, cp_flags)) {
619 				__split_huge_pud(vma, pudp, addr);
620 				goto again;
621 			} else {
622 				ret = change_huge_pud(tlb, vma, pudp,
623 						      addr, newprot, cp_flags);
624 				if (ret == 0)
625 					goto again;
626 				/* huge pud was handled */
627 				if (ret == HPAGE_PUD_NR)
628 					pages += HPAGE_PUD_NR;
629 				continue;
630 			}
631 		}
632 
633 		pages += change_pmd_range(tlb, vma, pudp, addr, next, newprot,
634 					  cp_flags);
635 	} while (pudp++, addr = next, addr != end);
636 
637 	if (range.start)
638 		mmu_notifier_invalidate_range_end(&range);
639 
640 	return pages;
641 }
642 
643 static inline long change_p4d_range(struct mmu_gather *tlb,
644 		struct vm_area_struct *vma, pgd_t *pgd, unsigned long addr,
645 		unsigned long end, pgprot_t newprot, unsigned long cp_flags)
646 {
647 	p4d_t *p4d;
648 	unsigned long next;
649 	long pages = 0, ret;
650 
651 	p4d = p4d_offset(pgd, addr);
652 	do {
653 		next = p4d_addr_end(addr, end);
654 		ret = change_prepare(vma, p4d, pud, addr, cp_flags);
655 		if (ret)
656 			return ret;
657 		if (p4d_none_or_clear_bad(p4d))
658 			continue;
659 		pages += change_pud_range(tlb, vma, p4d, addr, next, newprot,
660 					  cp_flags);
661 	} while (p4d++, addr = next, addr != end);
662 
663 	return pages;
664 }
665 
666 static long change_protection_range(struct mmu_gather *tlb,
667 		struct vm_area_struct *vma, unsigned long addr,
668 		unsigned long end, pgprot_t newprot, unsigned long cp_flags)
669 {
670 	struct mm_struct *mm = vma->vm_mm;
671 	pgd_t *pgd;
672 	unsigned long next;
673 	long pages = 0, ret;
674 
675 	BUG_ON(addr >= end);
676 	pgd = pgd_offset(mm, addr);
677 	tlb_start_vma(tlb, vma);
678 	do {
679 		next = pgd_addr_end(addr, end);
680 		ret = change_prepare(vma, pgd, p4d, addr, cp_flags);
681 		if (ret) {
682 			pages = ret;
683 			break;
684 		}
685 		if (pgd_none_or_clear_bad(pgd))
686 			continue;
687 		pages += change_p4d_range(tlb, vma, pgd, addr, next, newprot,
688 					  cp_flags);
689 	} while (pgd++, addr = next, addr != end);
690 
691 	tlb_end_vma(tlb, vma);
692 
693 	return pages;
694 }
695 
696 long change_protection(struct mmu_gather *tlb,
697 		       struct vm_area_struct *vma, unsigned long start,
698 		       unsigned long end, unsigned long cp_flags)
699 {
700 	pgprot_t newprot = vma->vm_page_prot;
701 	long pages;
702 
703 	BUG_ON((cp_flags & MM_CP_UFFD_WP_ALL) == MM_CP_UFFD_WP_ALL);
704 
705 #ifdef CONFIG_NUMA_BALANCING
706 	/*
707 	 * Ordinary protection updates (mprotect, uffd-wp, softdirty tracking)
708 	 * are expected to reflect their requirements via VMA flags such that
709 	 * vma_set_page_prot() will adjust vma->vm_page_prot accordingly.
710 	 */
711 	if (cp_flags & MM_CP_PROT_NUMA)
712 		newprot = PAGE_NONE;
713 #else
714 	WARN_ON_ONCE(cp_flags & MM_CP_PROT_NUMA);
715 #endif
716 
717 	if (is_vm_hugetlb_page(vma))
718 		pages = hugetlb_change_protection(vma, start, end, newprot,
719 						  cp_flags);
720 	else
721 		pages = change_protection_range(tlb, vma, start, end, newprot,
722 						cp_flags);
723 
724 	return pages;
725 }
726 
727 static int prot_none_pte_entry(pte_t *pte, unsigned long addr,
728 			       unsigned long next, struct mm_walk *walk)
729 {
730 	return pfn_modify_allowed(pte_pfn(ptep_get(pte)),
731 				  *(pgprot_t *)(walk->private)) ?
732 		0 : -EACCES;
733 }
734 
735 static int prot_none_hugetlb_entry(pte_t *pte, unsigned long hmask,
736 				   unsigned long addr, unsigned long next,
737 				   struct mm_walk *walk)
738 {
739 	return pfn_modify_allowed(pte_pfn(ptep_get(pte)),
740 				  *(pgprot_t *)(walk->private)) ?
741 		0 : -EACCES;
742 }
743 
744 static int prot_none_test(unsigned long addr, unsigned long next,
745 			  struct mm_walk *walk)
746 {
747 	return 0;
748 }
749 
750 static const struct mm_walk_ops prot_none_walk_ops = {
751 	.pte_entry		= prot_none_pte_entry,
752 	.hugetlb_entry		= prot_none_hugetlb_entry,
753 	.test_walk		= prot_none_test,
754 	.walk_lock		= PGWALK_WRLOCK,
755 };
756 
757 int
758 mprotect_fixup(struct vma_iterator *vmi, struct mmu_gather *tlb,
759 	       struct vm_area_struct *vma, struct vm_area_struct **pprev,
760 	       unsigned long start, unsigned long end, vm_flags_t newflags)
761 {
762 	struct mm_struct *mm = vma->vm_mm;
763 	vm_flags_t oldflags = READ_ONCE(vma->vm_flags);
764 	long nrpages = (end - start) >> PAGE_SHIFT;
765 	unsigned int mm_cp_flags = 0;
766 	unsigned long charged = 0;
767 	int error;
768 
769 	if (!can_modify_vma(vma))
770 		return -EPERM;
771 
772 	if (newflags == oldflags) {
773 		*pprev = vma;
774 		return 0;
775 	}
776 
777 	/*
778 	 * Do PROT_NONE PFN permission checks here when we can still
779 	 * bail out without undoing a lot of state. This is a rather
780 	 * uncommon case, so doesn't need to be very optimized.
781 	 */
782 	if (arch_has_pfn_modify_check() &&
783 	    (oldflags & (VM_PFNMAP|VM_MIXEDMAP)) &&
784 	    (newflags & VM_ACCESS_FLAGS) == 0) {
785 		pgprot_t new_pgprot = vm_get_page_prot(newflags);
786 
787 		error = walk_page_range(current->mm, start, end,
788 				&prot_none_walk_ops, &new_pgprot);
789 		if (error)
790 			return error;
791 	}
792 
793 	/*
794 	 * If we make a private mapping writable we increase our commit;
795 	 * but (without finer accounting) cannot reduce our commit if we
796 	 * make it unwritable again except in the anonymous case where no
797 	 * anon_vma has yet to be assigned.
798 	 *
799 	 * hugetlb mapping were accounted for even if read-only so there is
800 	 * no need to account for them here.
801 	 */
802 	if (newflags & VM_WRITE) {
803 		/* Check space limits when area turns into data. */
804 		if (!may_expand_vm(mm, newflags, nrpages) &&
805 				may_expand_vm(mm, oldflags, nrpages))
806 			return -ENOMEM;
807 		if (!(oldflags & (VM_ACCOUNT|VM_WRITE|VM_HUGETLB|
808 						VM_SHARED|VM_NORESERVE))) {
809 			charged = nrpages;
810 			if (security_vm_enough_memory_mm(mm, charged))
811 				return -ENOMEM;
812 			newflags |= VM_ACCOUNT;
813 		}
814 	} else if ((oldflags & VM_ACCOUNT) && vma_is_anonymous(vma) &&
815 		   !vma->anon_vma) {
816 		newflags &= ~VM_ACCOUNT;
817 	}
818 
819 	vma = vma_modify_flags(vmi, *pprev, vma, start, end, newflags);
820 	if (IS_ERR(vma)) {
821 		error = PTR_ERR(vma);
822 		goto fail;
823 	}
824 
825 	*pprev = vma;
826 
827 	/*
828 	 * vm_flags and vm_page_prot are protected by the mmap_lock
829 	 * held in write mode.
830 	 */
831 	vma_start_write(vma);
832 	vm_flags_reset_once(vma, newflags);
833 	if (vma_wants_manual_pte_write_upgrade(vma))
834 		mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE;
835 	vma_set_page_prot(vma);
836 
837 	change_protection(tlb, vma, start, end, mm_cp_flags);
838 
839 	if ((oldflags & VM_ACCOUNT) && !(newflags & VM_ACCOUNT))
840 		vm_unacct_memory(nrpages);
841 
842 	/*
843 	 * Private VM_LOCKED VMA becoming writable: trigger COW to avoid major
844 	 * fault on access.
845 	 */
846 	if ((oldflags & (VM_WRITE | VM_SHARED | VM_LOCKED)) == VM_LOCKED &&
847 			(newflags & VM_WRITE)) {
848 		populate_vma_page_range(vma, start, end, NULL);
849 	}
850 
851 	vm_stat_account(mm, oldflags, -nrpages);
852 	vm_stat_account(mm, newflags, nrpages);
853 	perf_event_mmap(vma);
854 	return 0;
855 
856 fail:
857 	vm_unacct_memory(charged);
858 	return error;
859 }
860 
861 /*
862  * pkey==-1 when doing a legacy mprotect()
863  */
864 static int do_mprotect_pkey(unsigned long start, size_t len,
865 		unsigned long prot, int pkey)
866 {
867 	unsigned long nstart, end, tmp, reqprot;
868 	struct vm_area_struct *vma, *prev;
869 	int error;
870 	const int grows = prot & (PROT_GROWSDOWN|PROT_GROWSUP);
871 	const bool rier = (current->personality & READ_IMPLIES_EXEC) &&
872 				(prot & PROT_READ);
873 	struct mmu_gather tlb;
874 	struct vma_iterator vmi;
875 
876 	start = untagged_addr(start);
877 
878 	prot &= ~(PROT_GROWSDOWN|PROT_GROWSUP);
879 	if (grows == (PROT_GROWSDOWN|PROT_GROWSUP)) /* can't be both */
880 		return -EINVAL;
881 
882 	if (start & ~PAGE_MASK)
883 		return -EINVAL;
884 	if (!len)
885 		return 0;
886 	len = PAGE_ALIGN(len);
887 	end = start + len;
888 	if (end <= start)
889 		return -ENOMEM;
890 	if (!arch_validate_prot(prot, start))
891 		return -EINVAL;
892 
893 	reqprot = prot;
894 
895 	if (mmap_write_lock_killable(current->mm))
896 		return -EINTR;
897 
898 	/*
899 	 * If userspace did not allocate the pkey, do not let
900 	 * them use it here.
901 	 */
902 	error = -EINVAL;
903 	if ((pkey != -1) && !mm_pkey_is_allocated(current->mm, pkey))
904 		goto out;
905 
906 	vma_iter_init(&vmi, current->mm, start);
907 	vma = vma_find(&vmi, end);
908 	error = -ENOMEM;
909 	if (!vma)
910 		goto out;
911 
912 	if (unlikely(grows & PROT_GROWSDOWN)) {
913 		if (vma->vm_start >= end)
914 			goto out;
915 		start = vma->vm_start;
916 		error = -EINVAL;
917 		if (!(vma->vm_flags & VM_GROWSDOWN))
918 			goto out;
919 	} else {
920 		if (vma->vm_start > start)
921 			goto out;
922 		if (unlikely(grows & PROT_GROWSUP)) {
923 			end = vma->vm_end;
924 			error = -EINVAL;
925 			if (!(vma->vm_flags & VM_GROWSUP))
926 				goto out;
927 		}
928 	}
929 
930 	prev = vma_prev(&vmi);
931 	if (start > vma->vm_start)
932 		prev = vma;
933 
934 	tlb_gather_mmu(&tlb, current->mm);
935 	nstart = start;
936 	tmp = vma->vm_start;
937 	for_each_vma_range(vmi, vma, end) {
938 		vm_flags_t mask_off_old_flags;
939 		vm_flags_t newflags;
940 		int new_vma_pkey;
941 
942 		if (vma->vm_start != tmp) {
943 			error = -ENOMEM;
944 			break;
945 		}
946 
947 		/* Does the application expect PROT_READ to imply PROT_EXEC */
948 		if (rier && (vma->vm_flags & VM_MAYEXEC))
949 			prot |= PROT_EXEC;
950 
951 		/*
952 		 * Each mprotect() call explicitly passes r/w/x permissions.
953 		 * If a permission is not passed to mprotect(), it must be
954 		 * cleared from the VMA.
955 		 */
956 		mask_off_old_flags = VM_ACCESS_FLAGS | VM_FLAGS_CLEAR;
957 
958 		new_vma_pkey = arch_override_mprotect_pkey(vma, prot, pkey);
959 		newflags = calc_vm_prot_bits(prot, new_vma_pkey);
960 		newflags |= (vma->vm_flags & ~mask_off_old_flags);
961 
962 		/* newflags >> 4 shift VM_MAY% in place of VM_% */
963 		if ((newflags & ~(newflags >> 4)) & VM_ACCESS_FLAGS) {
964 			error = -EACCES;
965 			break;
966 		}
967 
968 		if (map_deny_write_exec(vma->vm_flags, newflags)) {
969 			error = -EACCES;
970 			break;
971 		}
972 
973 		/* Allow architectures to sanity-check the new flags */
974 		if (!arch_validate_flags(newflags)) {
975 			error = -EINVAL;
976 			break;
977 		}
978 
979 		error = security_file_mprotect(vma, reqprot, prot);
980 		if (error)
981 			break;
982 
983 		tmp = vma->vm_end;
984 		if (tmp > end)
985 			tmp = end;
986 
987 		if (vma->vm_ops && vma->vm_ops->mprotect) {
988 			error = vma->vm_ops->mprotect(vma, nstart, tmp, newflags);
989 			if (error)
990 				break;
991 		}
992 
993 		error = mprotect_fixup(&vmi, &tlb, vma, &prev, nstart, tmp, newflags);
994 		if (error)
995 			break;
996 
997 		tmp = vma_iter_end(&vmi);
998 		nstart = tmp;
999 		prot = reqprot;
1000 	}
1001 	tlb_finish_mmu(&tlb);
1002 
1003 	if (!error && tmp < end)
1004 		error = -ENOMEM;
1005 
1006 out:
1007 	mmap_write_unlock(current->mm);
1008 	return error;
1009 }
1010 
1011 SYSCALL_DEFINE3(mprotect, unsigned long, start, size_t, len,
1012 		unsigned long, prot)
1013 {
1014 	return do_mprotect_pkey(start, len, prot, -1);
1015 }
1016 
1017 #ifdef CONFIG_ARCH_HAS_PKEYS
1018 
1019 SYSCALL_DEFINE4(pkey_mprotect, unsigned long, start, size_t, len,
1020 		unsigned long, prot, int, pkey)
1021 {
1022 	return do_mprotect_pkey(start, len, prot, pkey);
1023 }
1024 
1025 SYSCALL_DEFINE2(pkey_alloc, unsigned long, flags, unsigned long, init_val)
1026 {
1027 	int pkey;
1028 	int ret;
1029 
1030 	/* No flags supported yet. */
1031 	if (flags)
1032 		return -EINVAL;
1033 	/* check for unsupported init values */
1034 	if (init_val & ~PKEY_ACCESS_MASK)
1035 		return -EINVAL;
1036 
1037 	mmap_write_lock(current->mm);
1038 	pkey = mm_pkey_alloc(current->mm);
1039 
1040 	ret = -ENOSPC;
1041 	if (pkey == -1)
1042 		goto out;
1043 
1044 	ret = arch_set_user_pkey_access(current, pkey, init_val);
1045 	if (ret) {
1046 		mm_pkey_free(current->mm, pkey);
1047 		goto out;
1048 	}
1049 	ret = pkey;
1050 out:
1051 	mmap_write_unlock(current->mm);
1052 	return ret;
1053 }
1054 
1055 SYSCALL_DEFINE1(pkey_free, int, pkey)
1056 {
1057 	int ret;
1058 
1059 	mmap_write_lock(current->mm);
1060 	ret = mm_pkey_free(current->mm, pkey);
1061 	mmap_write_unlock(current->mm);
1062 
1063 	/*
1064 	 * We could provide warnings or errors if any VMA still
1065 	 * has the pkey set here.
1066 	 */
1067 	return ret;
1068 }
1069 
1070 #endif /* CONFIG_ARCH_HAS_PKEYS */
1071