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