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