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