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