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