xref: /linux/arch/arm64/mm/mmu.c (revision 971199ad2a0f1b2fbe14af13369704aff2999988)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Based on arch/arm/mm/mmu.c
4  *
5  * Copyright (C) 1995-2005 Russell King
6  * Copyright (C) 2012 ARM Ltd.
7  */
8 
9 #include <linux/cache.h>
10 #include <linux/export.h>
11 #include <linux/kernel.h>
12 #include <linux/errno.h>
13 #include <linux/init.h>
14 #include <linux/ioport.h>
15 #include <linux/kexec.h>
16 #include <linux/libfdt.h>
17 #include <linux/mman.h>
18 #include <linux/nodemask.h>
19 #include <linux/memblock.h>
20 #include <linux/memremap.h>
21 #include <linux/memory.h>
22 #include <linux/fs.h>
23 #include <linux/io.h>
24 #include <linux/mm.h>
25 #include <linux/vmalloc.h>
26 #include <linux/set_memory.h>
27 #include <linux/kfence.h>
28 #include <linux/pkeys.h>
29 #include <linux/mm_inline.h>
30 #include <linux/pagewalk.h>
31 #include <linux/stop_machine.h>
32 
33 #include <asm/barrier.h>
34 #include <asm/cputype.h>
35 #include <asm/fixmap.h>
36 #include <asm/kasan.h>
37 #include <asm/kernel-pgtable.h>
38 #include <asm/sections.h>
39 #include <asm/setup.h>
40 #include <linux/sizes.h>
41 #include <asm/tlb.h>
42 #include <asm/mmu_context.h>
43 #include <asm/ptdump.h>
44 #include <asm/tlbflush.h>
45 #include <asm/pgalloc.h>
46 #include <asm/kfence.h>
47 
48 #define NO_BLOCK_MAPPINGS	BIT(0)
49 #define NO_CONT_MAPPINGS	BIT(1)
50 #define NO_EXEC_MAPPINGS	BIT(2)	/* assumes FEAT_HPDS is not used */
51 
52 DEFINE_STATIC_KEY_FALSE(arm64_ptdump_lock_key);
53 
54 u64 kimage_voffset __ro_after_init;
55 EXPORT_SYMBOL(kimage_voffset);
56 
57 u32 __boot_cpu_mode[] = { BOOT_CPU_MODE_EL2, BOOT_CPU_MODE_EL1 };
58 
59 static bool rodata_is_rw __ro_after_init = true;
60 
61 /*
62  * The booting CPU updates the failed status @__early_cpu_boot_status,
63  * with MMU turned off.
64  */
65 long __section(".mmuoff.data.write") __early_cpu_boot_status;
66 
67 /*
68  * Empty_zero_page is a special page that is used for zero-initialized data
69  * and COW.
70  */
71 unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)] __page_aligned_bss;
72 EXPORT_SYMBOL(empty_zero_page);
73 
74 static DEFINE_SPINLOCK(swapper_pgdir_lock);
75 static DEFINE_MUTEX(fixmap_lock);
76 
set_swapper_pgd(pgd_t * pgdp,pgd_t pgd)77 void noinstr set_swapper_pgd(pgd_t *pgdp, pgd_t pgd)
78 {
79 	pgd_t *fixmap_pgdp;
80 
81 	/*
82 	 * Don't bother with the fixmap if swapper_pg_dir is still mapped
83 	 * writable in the kernel mapping.
84 	 */
85 	if (rodata_is_rw) {
86 		WRITE_ONCE(*pgdp, pgd);
87 		dsb(ishst);
88 		isb();
89 		return;
90 	}
91 
92 	spin_lock(&swapper_pgdir_lock);
93 	fixmap_pgdp = pgd_set_fixmap(__pa_symbol(pgdp));
94 	WRITE_ONCE(*fixmap_pgdp, pgd);
95 	/*
96 	 * We need dsb(ishst) here to ensure the page-table-walker sees
97 	 * our new entry before set_p?d() returns. The fixmap's
98 	 * flush_tlb_kernel_range() via clear_fixmap() does this for us.
99 	 */
100 	pgd_clear_fixmap();
101 	spin_unlock(&swapper_pgdir_lock);
102 }
103 
phys_mem_access_prot(struct file * file,unsigned long pfn,unsigned long size,pgprot_t vma_prot)104 pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
105 			      unsigned long size, pgprot_t vma_prot)
106 {
107 	if (!pfn_is_map_memory(pfn))
108 		return pgprot_noncached(vma_prot);
109 	else if (file->f_flags & O_SYNC)
110 		return pgprot_writecombine(vma_prot);
111 	return vma_prot;
112 }
113 EXPORT_SYMBOL(phys_mem_access_prot);
114 
early_pgtable_alloc(enum pgtable_type pgtable_type)115 static phys_addr_t __init early_pgtable_alloc(enum pgtable_type pgtable_type)
116 {
117 	phys_addr_t phys;
118 
119 	phys = memblock_phys_alloc_range(PAGE_SIZE, PAGE_SIZE, 0,
120 					 MEMBLOCK_ALLOC_NOLEAKTRACE);
121 	if (!phys)
122 		panic("Failed to allocate page table page\n");
123 
124 	return phys;
125 }
126 
pgattr_change_is_safe(pteval_t old,pteval_t new)127 bool pgattr_change_is_safe(pteval_t old, pteval_t new)
128 {
129 	/*
130 	 * The following mapping attributes may be updated in live
131 	 * kernel mappings without the need for break-before-make.
132 	 */
133 	pteval_t mask = PTE_PXN | PTE_RDONLY | PTE_WRITE | PTE_NG |
134 			PTE_SWBITS_MASK;
135 
136 	/* creating or taking down mappings is always safe */
137 	if (!pte_valid(__pte(old)) || !pte_valid(__pte(new)))
138 		return true;
139 
140 	/* A live entry's pfn should not change */
141 	if (pte_pfn(__pte(old)) != pte_pfn(__pte(new)))
142 		return false;
143 
144 	/* live contiguous mappings may not be manipulated at all */
145 	if ((old | new) & PTE_CONT)
146 		return false;
147 
148 	/* Transitioning from Non-Global to Global is unsafe */
149 	if (old & ~new & PTE_NG)
150 		return false;
151 
152 	/*
153 	 * Changing the memory type between Normal and Normal-Tagged is safe
154 	 * since Tagged is considered a permission attribute from the
155 	 * mismatched attribute aliases perspective.
156 	 */
157 	if (((old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
158 	     (old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)) &&
159 	    ((new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
160 	     (new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)))
161 		mask |= PTE_ATTRINDX_MASK;
162 
163 	return ((old ^ new) & ~mask) == 0;
164 }
165 
init_clear_pgtable(void * table)166 static void init_clear_pgtable(void *table)
167 {
168 	clear_page(table);
169 
170 	/* Ensure the zeroing is observed by page table walks. */
171 	dsb(ishst);
172 }
173 
init_pte(pte_t * ptep,unsigned long addr,unsigned long end,phys_addr_t phys,pgprot_t prot)174 static void init_pte(pte_t *ptep, unsigned long addr, unsigned long end,
175 		     phys_addr_t phys, pgprot_t prot)
176 {
177 	do {
178 		pte_t old_pte = __ptep_get(ptep);
179 
180 		/*
181 		 * Required barriers to make this visible to the table walker
182 		 * are deferred to the end of alloc_init_cont_pte().
183 		 */
184 		__set_pte_nosync(ptep, pfn_pte(__phys_to_pfn(phys), prot));
185 
186 		/*
187 		 * After the PTE entry has been populated once, we
188 		 * only allow updates to the permission attributes.
189 		 */
190 		BUG_ON(!pgattr_change_is_safe(pte_val(old_pte),
191 					      pte_val(__ptep_get(ptep))));
192 
193 		phys += PAGE_SIZE;
194 	} while (ptep++, addr += PAGE_SIZE, addr != end);
195 }
196 
alloc_init_cont_pte(pmd_t * pmdp,unsigned long addr,unsigned long end,phys_addr_t phys,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)197 static void alloc_init_cont_pte(pmd_t *pmdp, unsigned long addr,
198 				unsigned long end, phys_addr_t phys,
199 				pgprot_t prot,
200 				phys_addr_t (*pgtable_alloc)(enum pgtable_type),
201 				int flags)
202 {
203 	unsigned long next;
204 	pmd_t pmd = READ_ONCE(*pmdp);
205 	pte_t *ptep;
206 
207 	BUG_ON(pmd_sect(pmd));
208 	if (pmd_none(pmd)) {
209 		pmdval_t pmdval = PMD_TYPE_TABLE | PMD_TABLE_UXN | PMD_TABLE_AF;
210 		phys_addr_t pte_phys;
211 
212 		if (flags & NO_EXEC_MAPPINGS)
213 			pmdval |= PMD_TABLE_PXN;
214 		BUG_ON(!pgtable_alloc);
215 		pte_phys = pgtable_alloc(TABLE_PTE);
216 		ptep = pte_set_fixmap(pte_phys);
217 		init_clear_pgtable(ptep);
218 		ptep += pte_index(addr);
219 		__pmd_populate(pmdp, pte_phys, pmdval);
220 	} else {
221 		BUG_ON(pmd_bad(pmd));
222 		ptep = pte_set_fixmap_offset(pmdp, addr);
223 	}
224 
225 	do {
226 		pgprot_t __prot = prot;
227 
228 		next = pte_cont_addr_end(addr, end);
229 
230 		/* use a contiguous mapping if the range is suitably aligned */
231 		if ((((addr | next | phys) & ~CONT_PTE_MASK) == 0) &&
232 		    (flags & NO_CONT_MAPPINGS) == 0)
233 			__prot = __pgprot(pgprot_val(prot) | PTE_CONT);
234 
235 		init_pte(ptep, addr, next, phys, __prot);
236 
237 		ptep += pte_index(next) - pte_index(addr);
238 		phys += next - addr;
239 	} while (addr = next, addr != end);
240 
241 	/*
242 	 * Note: barriers and maintenance necessary to clear the fixmap slot
243 	 * ensure that all previous pgtable writes are visible to the table
244 	 * walker.
245 	 */
246 	pte_clear_fixmap();
247 }
248 
init_pmd(pmd_t * pmdp,unsigned long addr,unsigned long end,phys_addr_t phys,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)249 static void init_pmd(pmd_t *pmdp, unsigned long addr, unsigned long end,
250 		     phys_addr_t phys, pgprot_t prot,
251 		     phys_addr_t (*pgtable_alloc)(enum pgtable_type), int flags)
252 {
253 	unsigned long next;
254 
255 	do {
256 		pmd_t old_pmd = READ_ONCE(*pmdp);
257 
258 		next = pmd_addr_end(addr, end);
259 
260 		/* try section mapping first */
261 		if (((addr | next | phys) & ~PMD_MASK) == 0 &&
262 		    (flags & NO_BLOCK_MAPPINGS) == 0) {
263 			pmd_set_huge(pmdp, phys, prot);
264 
265 			/*
266 			 * After the PMD entry has been populated once, we
267 			 * only allow updates to the permission attributes.
268 			 */
269 			BUG_ON(!pgattr_change_is_safe(pmd_val(old_pmd),
270 						      READ_ONCE(pmd_val(*pmdp))));
271 		} else {
272 			alloc_init_cont_pte(pmdp, addr, next, phys, prot,
273 					    pgtable_alloc, flags);
274 
275 			BUG_ON(pmd_val(old_pmd) != 0 &&
276 			       pmd_val(old_pmd) != READ_ONCE(pmd_val(*pmdp)));
277 		}
278 		phys += next - addr;
279 	} while (pmdp++, addr = next, addr != end);
280 }
281 
alloc_init_cont_pmd(pud_t * pudp,unsigned long addr,unsigned long end,phys_addr_t phys,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)282 static void alloc_init_cont_pmd(pud_t *pudp, unsigned long addr,
283 				unsigned long end, phys_addr_t phys,
284 				pgprot_t prot,
285 				phys_addr_t (*pgtable_alloc)(enum pgtable_type),
286 				int flags)
287 {
288 	unsigned long next;
289 	pud_t pud = READ_ONCE(*pudp);
290 	pmd_t *pmdp;
291 
292 	/*
293 	 * Check for initial section mappings in the pgd/pud.
294 	 */
295 	BUG_ON(pud_sect(pud));
296 	if (pud_none(pud)) {
297 		pudval_t pudval = PUD_TYPE_TABLE | PUD_TABLE_UXN | PUD_TABLE_AF;
298 		phys_addr_t pmd_phys;
299 
300 		if (flags & NO_EXEC_MAPPINGS)
301 			pudval |= PUD_TABLE_PXN;
302 		BUG_ON(!pgtable_alloc);
303 		pmd_phys = pgtable_alloc(TABLE_PMD);
304 		pmdp = pmd_set_fixmap(pmd_phys);
305 		init_clear_pgtable(pmdp);
306 		pmdp += pmd_index(addr);
307 		__pud_populate(pudp, pmd_phys, pudval);
308 	} else {
309 		BUG_ON(pud_bad(pud));
310 		pmdp = pmd_set_fixmap_offset(pudp, addr);
311 	}
312 
313 	do {
314 		pgprot_t __prot = prot;
315 
316 		next = pmd_cont_addr_end(addr, end);
317 
318 		/* use a contiguous mapping if the range is suitably aligned */
319 		if ((((addr | next | phys) & ~CONT_PMD_MASK) == 0) &&
320 		    (flags & NO_CONT_MAPPINGS) == 0)
321 			__prot = __pgprot(pgprot_val(prot) | PTE_CONT);
322 
323 		init_pmd(pmdp, addr, next, phys, __prot, pgtable_alloc, flags);
324 
325 		pmdp += pmd_index(next) - pmd_index(addr);
326 		phys += next - addr;
327 	} while (addr = next, addr != end);
328 
329 	pmd_clear_fixmap();
330 }
331 
alloc_init_pud(p4d_t * p4dp,unsigned long addr,unsigned long end,phys_addr_t phys,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)332 static void alloc_init_pud(p4d_t *p4dp, unsigned long addr, unsigned long end,
333 			   phys_addr_t phys, pgprot_t prot,
334 			   phys_addr_t (*pgtable_alloc)(enum pgtable_type),
335 			   int flags)
336 {
337 	unsigned long next;
338 	p4d_t p4d = READ_ONCE(*p4dp);
339 	pud_t *pudp;
340 
341 	if (p4d_none(p4d)) {
342 		p4dval_t p4dval = P4D_TYPE_TABLE | P4D_TABLE_UXN | P4D_TABLE_AF;
343 		phys_addr_t pud_phys;
344 
345 		if (flags & NO_EXEC_MAPPINGS)
346 			p4dval |= P4D_TABLE_PXN;
347 		BUG_ON(!pgtable_alloc);
348 		pud_phys = pgtable_alloc(TABLE_PUD);
349 		pudp = pud_set_fixmap(pud_phys);
350 		init_clear_pgtable(pudp);
351 		pudp += pud_index(addr);
352 		__p4d_populate(p4dp, pud_phys, p4dval);
353 	} else {
354 		BUG_ON(p4d_bad(p4d));
355 		pudp = pud_set_fixmap_offset(p4dp, addr);
356 	}
357 
358 	do {
359 		pud_t old_pud = READ_ONCE(*pudp);
360 
361 		next = pud_addr_end(addr, end);
362 
363 		/*
364 		 * For 4K granule only, attempt to put down a 1GB block
365 		 */
366 		if (pud_sect_supported() &&
367 		   ((addr | next | phys) & ~PUD_MASK) == 0 &&
368 		    (flags & NO_BLOCK_MAPPINGS) == 0) {
369 			pud_set_huge(pudp, phys, prot);
370 
371 			/*
372 			 * After the PUD entry has been populated once, we
373 			 * only allow updates to the permission attributes.
374 			 */
375 			BUG_ON(!pgattr_change_is_safe(pud_val(old_pud),
376 						      READ_ONCE(pud_val(*pudp))));
377 		} else {
378 			alloc_init_cont_pmd(pudp, addr, next, phys, prot,
379 					    pgtable_alloc, flags);
380 
381 			BUG_ON(pud_val(old_pud) != 0 &&
382 			       pud_val(old_pud) != READ_ONCE(pud_val(*pudp)));
383 		}
384 		phys += next - addr;
385 	} while (pudp++, addr = next, addr != end);
386 
387 	pud_clear_fixmap();
388 }
389 
alloc_init_p4d(pgd_t * pgdp,unsigned long addr,unsigned long end,phys_addr_t phys,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)390 static void alloc_init_p4d(pgd_t *pgdp, unsigned long addr, unsigned long end,
391 			   phys_addr_t phys, pgprot_t prot,
392 			   phys_addr_t (*pgtable_alloc)(enum pgtable_type),
393 			   int flags)
394 {
395 	unsigned long next;
396 	pgd_t pgd = READ_ONCE(*pgdp);
397 	p4d_t *p4dp;
398 
399 	if (pgd_none(pgd)) {
400 		pgdval_t pgdval = PGD_TYPE_TABLE | PGD_TABLE_UXN | PGD_TABLE_AF;
401 		phys_addr_t p4d_phys;
402 
403 		if (flags & NO_EXEC_MAPPINGS)
404 			pgdval |= PGD_TABLE_PXN;
405 		BUG_ON(!pgtable_alloc);
406 		p4d_phys = pgtable_alloc(TABLE_P4D);
407 		p4dp = p4d_set_fixmap(p4d_phys);
408 		init_clear_pgtable(p4dp);
409 		p4dp += p4d_index(addr);
410 		__pgd_populate(pgdp, p4d_phys, pgdval);
411 	} else {
412 		BUG_ON(pgd_bad(pgd));
413 		p4dp = p4d_set_fixmap_offset(pgdp, addr);
414 	}
415 
416 	do {
417 		p4d_t old_p4d = READ_ONCE(*p4dp);
418 
419 		next = p4d_addr_end(addr, end);
420 
421 		alloc_init_pud(p4dp, addr, next, phys, prot,
422 			       pgtable_alloc, flags);
423 
424 		BUG_ON(p4d_val(old_p4d) != 0 &&
425 		       p4d_val(old_p4d) != READ_ONCE(p4d_val(*p4dp)));
426 
427 		phys += next - addr;
428 	} while (p4dp++, addr = next, addr != end);
429 
430 	p4d_clear_fixmap();
431 }
432 
__create_pgd_mapping_locked(pgd_t * pgdir,phys_addr_t phys,unsigned long virt,phys_addr_t size,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)433 static void __create_pgd_mapping_locked(pgd_t *pgdir, phys_addr_t phys,
434 					unsigned long virt, phys_addr_t size,
435 					pgprot_t prot,
436 					phys_addr_t (*pgtable_alloc)(enum pgtable_type),
437 					int flags)
438 {
439 	unsigned long addr, end, next;
440 	pgd_t *pgdp = pgd_offset_pgd(pgdir, virt);
441 
442 	/*
443 	 * If the virtual and physical address don't have the same offset
444 	 * within a page, we cannot map the region as the caller expects.
445 	 */
446 	if (WARN_ON((phys ^ virt) & ~PAGE_MASK))
447 		return;
448 
449 	phys &= PAGE_MASK;
450 	addr = virt & PAGE_MASK;
451 	end = PAGE_ALIGN(virt + size);
452 
453 	do {
454 		next = pgd_addr_end(addr, end);
455 		alloc_init_p4d(pgdp, addr, next, phys, prot, pgtable_alloc,
456 			       flags);
457 		phys += next - addr;
458 	} while (pgdp++, addr = next, addr != end);
459 }
460 
__create_pgd_mapping(pgd_t * pgdir,phys_addr_t phys,unsigned long virt,phys_addr_t size,pgprot_t prot,phys_addr_t (* pgtable_alloc)(enum pgtable_type),int flags)461 static void __create_pgd_mapping(pgd_t *pgdir, phys_addr_t phys,
462 				 unsigned long virt, phys_addr_t size,
463 				 pgprot_t prot,
464 				 phys_addr_t (*pgtable_alloc)(enum pgtable_type),
465 				 int flags)
466 {
467 	mutex_lock(&fixmap_lock);
468 	__create_pgd_mapping_locked(pgdir, phys, virt, size, prot,
469 				    pgtable_alloc, flags);
470 	mutex_unlock(&fixmap_lock);
471 }
472 
473 #define INVALID_PHYS_ADDR	(-1ULL)
474 
__pgd_pgtable_alloc(struct mm_struct * mm,gfp_t gfp,enum pgtable_type pgtable_type)475 static phys_addr_t __pgd_pgtable_alloc(struct mm_struct *mm, gfp_t gfp,
476 				       enum pgtable_type pgtable_type)
477 {
478 	/* Page is zeroed by init_clear_pgtable() so don't duplicate effort. */
479 	struct ptdesc *ptdesc = pagetable_alloc(gfp & ~__GFP_ZERO, 0);
480 	phys_addr_t pa;
481 
482 	if (!ptdesc)
483 		return INVALID_PHYS_ADDR;
484 
485 	pa = page_to_phys(ptdesc_page(ptdesc));
486 
487 	switch (pgtable_type) {
488 	case TABLE_PTE:
489 		BUG_ON(!pagetable_pte_ctor(mm, ptdesc));
490 		break;
491 	case TABLE_PMD:
492 		BUG_ON(!pagetable_pmd_ctor(mm, ptdesc));
493 		break;
494 	case TABLE_PUD:
495 		pagetable_pud_ctor(ptdesc);
496 		break;
497 	case TABLE_P4D:
498 		pagetable_p4d_ctor(ptdesc);
499 		break;
500 	}
501 
502 	return pa;
503 }
504 
505 static phys_addr_t
try_pgd_pgtable_alloc_init_mm(enum pgtable_type pgtable_type,gfp_t gfp)506 try_pgd_pgtable_alloc_init_mm(enum pgtable_type pgtable_type, gfp_t gfp)
507 {
508 	return __pgd_pgtable_alloc(&init_mm, gfp, pgtable_type);
509 }
510 
511 static phys_addr_t __maybe_unused
pgd_pgtable_alloc_init_mm(enum pgtable_type pgtable_type)512 pgd_pgtable_alloc_init_mm(enum pgtable_type pgtable_type)
513 {
514 	phys_addr_t pa;
515 
516 	pa = __pgd_pgtable_alloc(&init_mm, GFP_PGTABLE_KERNEL, pgtable_type);
517 	BUG_ON(pa == INVALID_PHYS_ADDR);
518 	return pa;
519 }
520 
521 static phys_addr_t
pgd_pgtable_alloc_special_mm(enum pgtable_type pgtable_type)522 pgd_pgtable_alloc_special_mm(enum pgtable_type pgtable_type)
523 {
524 	phys_addr_t pa;
525 
526 	pa = __pgd_pgtable_alloc(NULL, GFP_PGTABLE_KERNEL, pgtable_type);
527 	BUG_ON(pa == INVALID_PHYS_ADDR);
528 	return pa;
529 }
530 
split_contpte(pte_t * ptep)531 static void split_contpte(pte_t *ptep)
532 {
533 	int i;
534 
535 	ptep = PTR_ALIGN_DOWN(ptep, sizeof(*ptep) * CONT_PTES);
536 	for (i = 0; i < CONT_PTES; i++, ptep++)
537 		__set_pte(ptep, pte_mknoncont(__ptep_get(ptep)));
538 }
539 
split_pmd(pmd_t * pmdp,pmd_t pmd,gfp_t gfp,bool to_cont)540 static int split_pmd(pmd_t *pmdp, pmd_t pmd, gfp_t gfp, bool to_cont)
541 {
542 	pmdval_t tableprot = PMD_TYPE_TABLE | PMD_TABLE_UXN | PMD_TABLE_AF;
543 	unsigned long pfn = pmd_pfn(pmd);
544 	pgprot_t prot = pmd_pgprot(pmd);
545 	phys_addr_t pte_phys;
546 	pte_t *ptep;
547 	int i;
548 
549 	pte_phys = try_pgd_pgtable_alloc_init_mm(TABLE_PTE, gfp);
550 	if (pte_phys == INVALID_PHYS_ADDR)
551 		return -ENOMEM;
552 	ptep = (pte_t *)phys_to_virt(pte_phys);
553 
554 	if (pgprot_val(prot) & PMD_SECT_PXN)
555 		tableprot |= PMD_TABLE_PXN;
556 
557 	prot = __pgprot((pgprot_val(prot) & ~PTE_TYPE_MASK) | PTE_TYPE_PAGE);
558 	prot = __pgprot(pgprot_val(prot) & ~PTE_CONT);
559 	if (to_cont)
560 		prot = __pgprot(pgprot_val(prot) | PTE_CONT);
561 
562 	for (i = 0; i < PTRS_PER_PTE; i++, ptep++, pfn++)
563 		__set_pte(ptep, pfn_pte(pfn, prot));
564 
565 	/*
566 	 * Ensure the pte entries are visible to the table walker by the time
567 	 * the pmd entry that points to the ptes is visible.
568 	 */
569 	dsb(ishst);
570 	__pmd_populate(pmdp, pte_phys, tableprot);
571 
572 	return 0;
573 }
574 
split_contpmd(pmd_t * pmdp)575 static void split_contpmd(pmd_t *pmdp)
576 {
577 	int i;
578 
579 	pmdp = PTR_ALIGN_DOWN(pmdp, sizeof(*pmdp) * CONT_PMDS);
580 	for (i = 0; i < CONT_PMDS; i++, pmdp++)
581 		set_pmd(pmdp, pmd_mknoncont(pmdp_get(pmdp)));
582 }
583 
split_pud(pud_t * pudp,pud_t pud,gfp_t gfp,bool to_cont)584 static int split_pud(pud_t *pudp, pud_t pud, gfp_t gfp, bool to_cont)
585 {
586 	pudval_t tableprot = PUD_TYPE_TABLE | PUD_TABLE_UXN | PUD_TABLE_AF;
587 	unsigned int step = PMD_SIZE >> PAGE_SHIFT;
588 	unsigned long pfn = pud_pfn(pud);
589 	pgprot_t prot = pud_pgprot(pud);
590 	phys_addr_t pmd_phys;
591 	pmd_t *pmdp;
592 	int i;
593 
594 	pmd_phys = try_pgd_pgtable_alloc_init_mm(TABLE_PMD, gfp);
595 	if (pmd_phys == INVALID_PHYS_ADDR)
596 		return -ENOMEM;
597 	pmdp = (pmd_t *)phys_to_virt(pmd_phys);
598 
599 	if (pgprot_val(prot) & PMD_SECT_PXN)
600 		tableprot |= PUD_TABLE_PXN;
601 
602 	prot = __pgprot((pgprot_val(prot) & ~PMD_TYPE_MASK) | PMD_TYPE_SECT);
603 	prot = __pgprot(pgprot_val(prot) & ~PTE_CONT);
604 	if (to_cont)
605 		prot = __pgprot(pgprot_val(prot) | PTE_CONT);
606 
607 	for (i = 0; i < PTRS_PER_PMD; i++, pmdp++, pfn += step)
608 		set_pmd(pmdp, pfn_pmd(pfn, prot));
609 
610 	/*
611 	 * Ensure the pmd entries are visible to the table walker by the time
612 	 * the pud entry that points to the pmds is visible.
613 	 */
614 	dsb(ishst);
615 	__pud_populate(pudp, pmd_phys, tableprot);
616 
617 	return 0;
618 }
619 
split_kernel_leaf_mapping_locked(unsigned long addr)620 static int split_kernel_leaf_mapping_locked(unsigned long addr)
621 {
622 	pgd_t *pgdp, pgd;
623 	p4d_t *p4dp, p4d;
624 	pud_t *pudp, pud;
625 	pmd_t *pmdp, pmd;
626 	pte_t *ptep, pte;
627 	int ret = 0;
628 
629 	/*
630 	 * PGD: If addr is PGD aligned then addr already describes a leaf
631 	 * boundary. If not present then there is nothing to split.
632 	 */
633 	if (ALIGN_DOWN(addr, PGDIR_SIZE) == addr)
634 		goto out;
635 	pgdp = pgd_offset_k(addr);
636 	pgd = pgdp_get(pgdp);
637 	if (!pgd_present(pgd))
638 		goto out;
639 
640 	/*
641 	 * P4D: If addr is P4D aligned then addr already describes a leaf
642 	 * boundary. If not present then there is nothing to split.
643 	 */
644 	if (ALIGN_DOWN(addr, P4D_SIZE) == addr)
645 		goto out;
646 	p4dp = p4d_offset(pgdp, addr);
647 	p4d = p4dp_get(p4dp);
648 	if (!p4d_present(p4d))
649 		goto out;
650 
651 	/*
652 	 * PUD: If addr is PUD aligned then addr already describes a leaf
653 	 * boundary. If not present then there is nothing to split. Otherwise,
654 	 * if we have a pud leaf, split to contpmd.
655 	 */
656 	if (ALIGN_DOWN(addr, PUD_SIZE) == addr)
657 		goto out;
658 	pudp = pud_offset(p4dp, addr);
659 	pud = pudp_get(pudp);
660 	if (!pud_present(pud))
661 		goto out;
662 	if (pud_leaf(pud)) {
663 		ret = split_pud(pudp, pud, GFP_PGTABLE_KERNEL, true);
664 		if (ret)
665 			goto out;
666 	}
667 
668 	/*
669 	 * CONTPMD: If addr is CONTPMD aligned then addr already describes a
670 	 * leaf boundary. If not present then there is nothing to split.
671 	 * Otherwise, if we have a contpmd leaf, split to pmd.
672 	 */
673 	if (ALIGN_DOWN(addr, CONT_PMD_SIZE) == addr)
674 		goto out;
675 	pmdp = pmd_offset(pudp, addr);
676 	pmd = pmdp_get(pmdp);
677 	if (!pmd_present(pmd))
678 		goto out;
679 	if (pmd_leaf(pmd)) {
680 		if (pmd_cont(pmd))
681 			split_contpmd(pmdp);
682 		/*
683 		 * PMD: If addr is PMD aligned then addr already describes a
684 		 * leaf boundary. Otherwise, split to contpte.
685 		 */
686 		if (ALIGN_DOWN(addr, PMD_SIZE) == addr)
687 			goto out;
688 		ret = split_pmd(pmdp, pmd, GFP_PGTABLE_KERNEL, true);
689 		if (ret)
690 			goto out;
691 	}
692 
693 	/*
694 	 * CONTPTE: If addr is CONTPTE aligned then addr already describes a
695 	 * leaf boundary. If not present then there is nothing to split.
696 	 * Otherwise, if we have a contpte leaf, split to pte.
697 	 */
698 	if (ALIGN_DOWN(addr, CONT_PTE_SIZE) == addr)
699 		goto out;
700 	ptep = pte_offset_kernel(pmdp, addr);
701 	pte = __ptep_get(ptep);
702 	if (!pte_present(pte))
703 		goto out;
704 	if (pte_cont(pte))
705 		split_contpte(ptep);
706 
707 out:
708 	return ret;
709 }
710 
711 static DEFINE_MUTEX(pgtable_split_lock);
712 
split_kernel_leaf_mapping(unsigned long start,unsigned long end)713 int split_kernel_leaf_mapping(unsigned long start, unsigned long end)
714 {
715 	int ret;
716 
717 	/*
718 	 * !BBML2_NOABORT systems should not be trying to change permissions on
719 	 * anything that is not pte-mapped in the first place. Just return early
720 	 * and let the permission change code raise a warning if not already
721 	 * pte-mapped.
722 	 */
723 	if (!system_supports_bbml2_noabort())
724 		return 0;
725 
726 	/*
727 	 * Ensure start and end are at least page-aligned since this is the
728 	 * finest granularity we can split to.
729 	 */
730 	if (start != PAGE_ALIGN(start) || end != PAGE_ALIGN(end))
731 		return -EINVAL;
732 
733 	mutex_lock(&pgtable_split_lock);
734 	arch_enter_lazy_mmu_mode();
735 
736 	/*
737 	 * The split_kernel_leaf_mapping_locked() may sleep, it is not a
738 	 * problem for ARM64 since ARM64's lazy MMU implementation allows
739 	 * sleeping.
740 	 *
741 	 * Optimize for the common case of splitting out a single page from a
742 	 * larger mapping. Here we can just split on the "least aligned" of
743 	 * start and end and this will guarantee that there must also be a split
744 	 * on the more aligned address since the both addresses must be in the
745 	 * same contpte block and it must have been split to ptes.
746 	 */
747 	if (end - start == PAGE_SIZE) {
748 		start = __ffs(start) < __ffs(end) ? start : end;
749 		ret = split_kernel_leaf_mapping_locked(start);
750 	} else {
751 		ret = split_kernel_leaf_mapping_locked(start);
752 		if (!ret)
753 			ret = split_kernel_leaf_mapping_locked(end);
754 	}
755 
756 	arch_leave_lazy_mmu_mode();
757 	mutex_unlock(&pgtable_split_lock);
758 	return ret;
759 }
760 
split_to_ptes_pud_entry(pud_t * pudp,unsigned long addr,unsigned long next,struct mm_walk * walk)761 static int __init split_to_ptes_pud_entry(pud_t *pudp, unsigned long addr,
762 					  unsigned long next,
763 					  struct mm_walk *walk)
764 {
765 	pud_t pud = pudp_get(pudp);
766 	int ret = 0;
767 
768 	if (pud_leaf(pud))
769 		ret = split_pud(pudp, pud, GFP_ATOMIC, false);
770 
771 	return ret;
772 }
773 
split_to_ptes_pmd_entry(pmd_t * pmdp,unsigned long addr,unsigned long next,struct mm_walk * walk)774 static int __init split_to_ptes_pmd_entry(pmd_t *pmdp, unsigned long addr,
775 					  unsigned long next,
776 					  struct mm_walk *walk)
777 {
778 	pmd_t pmd = pmdp_get(pmdp);
779 	int ret = 0;
780 
781 	if (pmd_leaf(pmd)) {
782 		if (pmd_cont(pmd))
783 			split_contpmd(pmdp);
784 		ret = split_pmd(pmdp, pmd, GFP_ATOMIC, false);
785 
786 		/*
787 		 * We have split the pmd directly to ptes so there is no need to
788 		 * visit each pte to check if they are contpte.
789 		 */
790 		walk->action = ACTION_CONTINUE;
791 	}
792 
793 	return ret;
794 }
795 
split_to_ptes_pte_entry(pte_t * ptep,unsigned long addr,unsigned long next,struct mm_walk * walk)796 static int __init split_to_ptes_pte_entry(pte_t *ptep, unsigned long addr,
797 					  unsigned long next,
798 					  struct mm_walk *walk)
799 {
800 	pte_t pte = __ptep_get(ptep);
801 
802 	if (pte_cont(pte))
803 		split_contpte(ptep);
804 
805 	return 0;
806 }
807 
808 static const struct mm_walk_ops split_to_ptes_ops __initconst = {
809 	.pud_entry	= split_to_ptes_pud_entry,
810 	.pmd_entry	= split_to_ptes_pmd_entry,
811 	.pte_entry	= split_to_ptes_pte_entry,
812 };
813 
814 static bool linear_map_requires_bbml2 __initdata;
815 
816 u32 idmap_kpti_bbml2_flag;
817 
init_idmap_kpti_bbml2_flag(void)818 static void __init init_idmap_kpti_bbml2_flag(void)
819 {
820 	WRITE_ONCE(idmap_kpti_bbml2_flag, 1);
821 	/* Must be visible to other CPUs before stop_machine() is called. */
822 	smp_mb();
823 }
824 
linear_map_split_to_ptes(void * __unused)825 static int __init linear_map_split_to_ptes(void *__unused)
826 {
827 	/*
828 	 * Repainting the linear map must be done by CPU0 (the boot CPU) because
829 	 * that's the only CPU that we know supports BBML2. The other CPUs will
830 	 * be held in a waiting area with the idmap active.
831 	 */
832 	if (!smp_processor_id()) {
833 		unsigned long lstart = _PAGE_OFFSET(vabits_actual);
834 		unsigned long lend = PAGE_END;
835 		unsigned long kstart = (unsigned long)lm_alias(_stext);
836 		unsigned long kend = (unsigned long)lm_alias(__init_begin);
837 		int ret;
838 
839 		/*
840 		 * Wait for all secondary CPUs to be put into the waiting area.
841 		 */
842 		smp_cond_load_acquire(&idmap_kpti_bbml2_flag, VAL == num_online_cpus());
843 
844 		/*
845 		 * Walk all of the linear map [lstart, lend), except the kernel
846 		 * linear map alias [kstart, kend), and split all mappings to
847 		 * PTE. The kernel alias remains static throughout runtime so
848 		 * can continue to be safely mapped with large mappings.
849 		 */
850 		ret = walk_kernel_page_table_range_lockless(lstart, kstart,
851 						&split_to_ptes_ops, NULL, NULL);
852 		if (!ret)
853 			ret = walk_kernel_page_table_range_lockless(kend, lend,
854 						&split_to_ptes_ops, NULL, NULL);
855 		if (ret)
856 			panic("Failed to split linear map\n");
857 		flush_tlb_kernel_range(lstart, lend);
858 
859 		/*
860 		 * Relies on dsb in flush_tlb_kernel_range() to avoid reordering
861 		 * before any page table split operations.
862 		 */
863 		WRITE_ONCE(idmap_kpti_bbml2_flag, 0);
864 	} else {
865 		typedef void (wait_split_fn)(void);
866 		extern wait_split_fn wait_linear_map_split_to_ptes;
867 		wait_split_fn *wait_fn;
868 
869 		wait_fn = (void *)__pa_symbol(wait_linear_map_split_to_ptes);
870 
871 		/*
872 		 * At least one secondary CPU doesn't support BBML2 so cannot
873 		 * tolerate the size of the live mappings changing. So have the
874 		 * secondary CPUs wait for the boot CPU to make the changes
875 		 * with the idmap active and init_mm inactive.
876 		 */
877 		cpu_install_idmap();
878 		wait_fn();
879 		cpu_uninstall_idmap();
880 	}
881 
882 	return 0;
883 }
884 
linear_map_maybe_split_to_ptes(void)885 void __init linear_map_maybe_split_to_ptes(void)
886 {
887 	if (linear_map_requires_bbml2 && !system_supports_bbml2_noabort()) {
888 		init_idmap_kpti_bbml2_flag();
889 		stop_machine(linear_map_split_to_ptes, NULL, cpu_online_mask);
890 	}
891 }
892 
893 /*
894  * This function can only be used to modify existing table entries,
895  * without allocating new levels of table. Note that this permits the
896  * creation of new section or page entries.
897  */
create_mapping_noalloc(phys_addr_t phys,unsigned long virt,phys_addr_t size,pgprot_t prot)898 void __init create_mapping_noalloc(phys_addr_t phys, unsigned long virt,
899 				   phys_addr_t size, pgprot_t prot)
900 {
901 	if (virt < PAGE_OFFSET) {
902 		pr_warn("BUG: not creating mapping for %pa at 0x%016lx - outside kernel range\n",
903 			&phys, virt);
904 		return;
905 	}
906 	__create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
907 			     NO_CONT_MAPPINGS);
908 }
909 
create_pgd_mapping(struct mm_struct * mm,phys_addr_t phys,unsigned long virt,phys_addr_t size,pgprot_t prot,bool page_mappings_only)910 void __init create_pgd_mapping(struct mm_struct *mm, phys_addr_t phys,
911 			       unsigned long virt, phys_addr_t size,
912 			       pgprot_t prot, bool page_mappings_only)
913 {
914 	int flags = 0;
915 
916 	BUG_ON(mm == &init_mm);
917 
918 	if (page_mappings_only)
919 		flags = NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
920 
921 	__create_pgd_mapping(mm->pgd, phys, virt, size, prot,
922 			     pgd_pgtable_alloc_special_mm, flags);
923 }
924 
update_mapping_prot(phys_addr_t phys,unsigned long virt,phys_addr_t size,pgprot_t prot)925 static void update_mapping_prot(phys_addr_t phys, unsigned long virt,
926 				phys_addr_t size, pgprot_t prot)
927 {
928 	if (virt < PAGE_OFFSET) {
929 		pr_warn("BUG: not updating mapping for %pa at 0x%016lx - outside kernel range\n",
930 			&phys, virt);
931 		return;
932 	}
933 
934 	__create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
935 			     NO_CONT_MAPPINGS);
936 
937 	/* flush the TLBs after updating live kernel mappings */
938 	flush_tlb_kernel_range(virt, virt + size);
939 }
940 
__map_memblock(pgd_t * pgdp,phys_addr_t start,phys_addr_t end,pgprot_t prot,int flags)941 static void __init __map_memblock(pgd_t *pgdp, phys_addr_t start,
942 				  phys_addr_t end, pgprot_t prot, int flags)
943 {
944 	__create_pgd_mapping(pgdp, start, __phys_to_virt(start), end - start,
945 			     prot, early_pgtable_alloc, flags);
946 }
947 
mark_linear_text_alias_ro(void)948 void __init mark_linear_text_alias_ro(void)
949 {
950 	/*
951 	 * Remove the write permissions from the linear alias of .text/.rodata
952 	 */
953 	update_mapping_prot(__pa_symbol(_text), (unsigned long)lm_alias(_text),
954 			    (unsigned long)__init_begin - (unsigned long)_text,
955 			    PAGE_KERNEL_RO);
956 }
957 
958 #ifdef CONFIG_KFENCE
959 
960 bool __ro_after_init kfence_early_init = !!CONFIG_KFENCE_SAMPLE_INTERVAL;
961 
962 /* early_param() will be parsed before map_mem() below. */
parse_kfence_early_init(char * arg)963 static int __init parse_kfence_early_init(char *arg)
964 {
965 	int val;
966 
967 	if (get_option(&arg, &val))
968 		kfence_early_init = !!val;
969 	return 0;
970 }
971 early_param("kfence.sample_interval", parse_kfence_early_init);
972 
arm64_kfence_alloc_pool(void)973 static phys_addr_t __init arm64_kfence_alloc_pool(void)
974 {
975 	phys_addr_t kfence_pool;
976 
977 	if (!kfence_early_init)
978 		return 0;
979 
980 	kfence_pool = memblock_phys_alloc(KFENCE_POOL_SIZE, PAGE_SIZE);
981 	if (!kfence_pool) {
982 		pr_err("failed to allocate kfence pool\n");
983 		kfence_early_init = false;
984 		return 0;
985 	}
986 
987 	/* Temporarily mark as NOMAP. */
988 	memblock_mark_nomap(kfence_pool, KFENCE_POOL_SIZE);
989 
990 	return kfence_pool;
991 }
992 
arm64_kfence_map_pool(phys_addr_t kfence_pool,pgd_t * pgdp)993 static void __init arm64_kfence_map_pool(phys_addr_t kfence_pool, pgd_t *pgdp)
994 {
995 	if (!kfence_pool)
996 		return;
997 
998 	/* KFENCE pool needs page-level mapping. */
999 	__map_memblock(pgdp, kfence_pool, kfence_pool + KFENCE_POOL_SIZE,
1000 			pgprot_tagged(PAGE_KERNEL),
1001 			NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS);
1002 	memblock_clear_nomap(kfence_pool, KFENCE_POOL_SIZE);
1003 	__kfence_pool = phys_to_virt(kfence_pool);
1004 }
1005 #else /* CONFIG_KFENCE */
1006 
arm64_kfence_alloc_pool(void)1007 static inline phys_addr_t arm64_kfence_alloc_pool(void) { return 0; }
arm64_kfence_map_pool(phys_addr_t kfence_pool,pgd_t * pgdp)1008 static inline void arm64_kfence_map_pool(phys_addr_t kfence_pool, pgd_t *pgdp) { }
1009 
1010 #endif /* CONFIG_KFENCE */
1011 
force_pte_mapping(void)1012 static inline bool force_pte_mapping(void)
1013 {
1014 	bool bbml2 = system_capabilities_finalized() ?
1015 		system_supports_bbml2_noabort() : cpu_supports_bbml2_noabort();
1016 
1017 	return (!bbml2 && (rodata_full || arm64_kfence_can_set_direct_map() ||
1018 			   is_realm_world())) ||
1019 		debug_pagealloc_enabled();
1020 }
1021 
map_mem(pgd_t * pgdp)1022 static void __init map_mem(pgd_t *pgdp)
1023 {
1024 	static const u64 direct_map_end = _PAGE_END(VA_BITS_MIN);
1025 	phys_addr_t kernel_start = __pa_symbol(_text);
1026 	phys_addr_t kernel_end = __pa_symbol(__init_begin);
1027 	phys_addr_t start, end;
1028 	phys_addr_t early_kfence_pool;
1029 	int flags = NO_EXEC_MAPPINGS;
1030 	u64 i;
1031 
1032 	/*
1033 	 * Setting hierarchical PXNTable attributes on table entries covering
1034 	 * the linear region is only possible if it is guaranteed that no table
1035 	 * entries at any level are being shared between the linear region and
1036 	 * the vmalloc region. Check whether this is true for the PGD level, in
1037 	 * which case it is guaranteed to be true for all other levels as well.
1038 	 * (Unless we are running with support for LPA2, in which case the
1039 	 * entire reduced VA space is covered by a single pgd_t which will have
1040 	 * been populated without the PXNTable attribute by the time we get here.)
1041 	 */
1042 	BUILD_BUG_ON(pgd_index(direct_map_end - 1) == pgd_index(direct_map_end) &&
1043 		     pgd_index(_PAGE_OFFSET(VA_BITS_MIN)) != PTRS_PER_PGD - 1);
1044 
1045 	early_kfence_pool = arm64_kfence_alloc_pool();
1046 
1047 	linear_map_requires_bbml2 = !force_pte_mapping() && can_set_direct_map();
1048 
1049 	if (force_pte_mapping())
1050 		flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
1051 
1052 	/*
1053 	 * Take care not to create a writable alias for the
1054 	 * read-only text and rodata sections of the kernel image.
1055 	 * So temporarily mark them as NOMAP to skip mappings in
1056 	 * the following for-loop
1057 	 */
1058 	memblock_mark_nomap(kernel_start, kernel_end - kernel_start);
1059 
1060 	/* map all the memory banks */
1061 	for_each_mem_range(i, &start, &end) {
1062 		if (start >= end)
1063 			break;
1064 		/*
1065 		 * The linear map must allow allocation tags reading/writing
1066 		 * if MTE is present. Otherwise, it has the same attributes as
1067 		 * PAGE_KERNEL.
1068 		 */
1069 		__map_memblock(pgdp, start, end, pgprot_tagged(PAGE_KERNEL),
1070 			       flags);
1071 	}
1072 
1073 	/*
1074 	 * Map the linear alias of the [_text, __init_begin) interval
1075 	 * as non-executable now, and remove the write permission in
1076 	 * mark_linear_text_alias_ro() below (which will be called after
1077 	 * alternative patching has completed). This makes the contents
1078 	 * of the region accessible to subsystems such as hibernate,
1079 	 * but protects it from inadvertent modification or execution.
1080 	 * Note that contiguous mappings cannot be remapped in this way,
1081 	 * so we should avoid them here.
1082 	 */
1083 	__map_memblock(pgdp, kernel_start, kernel_end,
1084 		       PAGE_KERNEL, NO_CONT_MAPPINGS);
1085 	memblock_clear_nomap(kernel_start, kernel_end - kernel_start);
1086 	arm64_kfence_map_pool(early_kfence_pool, pgdp);
1087 }
1088 
mark_rodata_ro(void)1089 void mark_rodata_ro(void)
1090 {
1091 	unsigned long section_size;
1092 
1093 	/*
1094 	 * mark .rodata as read only. Use __init_begin rather than __end_rodata
1095 	 * to cover NOTES and EXCEPTION_TABLE.
1096 	 */
1097 	section_size = (unsigned long)__init_begin - (unsigned long)__start_rodata;
1098 	WRITE_ONCE(rodata_is_rw, false);
1099 	update_mapping_prot(__pa_symbol(__start_rodata), (unsigned long)__start_rodata,
1100 			    section_size, PAGE_KERNEL_RO);
1101 	/* mark the range between _text and _stext as read only. */
1102 	update_mapping_prot(__pa_symbol(_text), (unsigned long)_text,
1103 			    (unsigned long)_stext - (unsigned long)_text,
1104 			    PAGE_KERNEL_RO);
1105 }
1106 
declare_vma(struct vm_struct * vma,void * va_start,void * va_end,unsigned long vm_flags)1107 static void __init declare_vma(struct vm_struct *vma,
1108 			       void *va_start, void *va_end,
1109 			       unsigned long vm_flags)
1110 {
1111 	phys_addr_t pa_start = __pa_symbol(va_start);
1112 	unsigned long size = va_end - va_start;
1113 
1114 	BUG_ON(!PAGE_ALIGNED(pa_start));
1115 	BUG_ON(!PAGE_ALIGNED(size));
1116 
1117 	if (!(vm_flags & VM_NO_GUARD))
1118 		size += PAGE_SIZE;
1119 
1120 	vma->addr	= va_start;
1121 	vma->phys_addr	= pa_start;
1122 	vma->size	= size;
1123 	vma->flags	= VM_MAP | vm_flags;
1124 	vma->caller	= __builtin_return_address(0);
1125 
1126 	vm_area_add_early(vma);
1127 }
1128 
1129 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
1130 #define KPTI_NG_TEMP_VA		(-(1UL << PMD_SHIFT))
1131 
1132 static phys_addr_t kpti_ng_temp_alloc __initdata;
1133 
kpti_ng_pgd_alloc(enum pgtable_type type)1134 static phys_addr_t __init kpti_ng_pgd_alloc(enum pgtable_type type)
1135 {
1136 	kpti_ng_temp_alloc -= PAGE_SIZE;
1137 	return kpti_ng_temp_alloc;
1138 }
1139 
__kpti_install_ng_mappings(void * __unused)1140 static int __init __kpti_install_ng_mappings(void *__unused)
1141 {
1142 	typedef void (kpti_remap_fn)(int, int, phys_addr_t, unsigned long);
1143 	extern kpti_remap_fn idmap_kpti_install_ng_mappings;
1144 	kpti_remap_fn *remap_fn;
1145 
1146 	int cpu = smp_processor_id();
1147 	int levels = CONFIG_PGTABLE_LEVELS;
1148 	int order = order_base_2(levels);
1149 	u64 kpti_ng_temp_pgd_pa = 0;
1150 	pgd_t *kpti_ng_temp_pgd;
1151 	u64 alloc = 0;
1152 
1153 	if (levels == 5 && !pgtable_l5_enabled())
1154 		levels = 4;
1155 	else if (levels == 4 && !pgtable_l4_enabled())
1156 		levels = 3;
1157 
1158 	remap_fn = (void *)__pa_symbol(idmap_kpti_install_ng_mappings);
1159 
1160 	if (!cpu) {
1161 		alloc = __get_free_pages(GFP_ATOMIC | __GFP_ZERO, order);
1162 		kpti_ng_temp_pgd = (pgd_t *)(alloc + (levels - 1) * PAGE_SIZE);
1163 		kpti_ng_temp_alloc = kpti_ng_temp_pgd_pa = __pa(kpti_ng_temp_pgd);
1164 
1165 		//
1166 		// Create a minimal page table hierarchy that permits us to map
1167 		// the swapper page tables temporarily as we traverse them.
1168 		//
1169 		// The physical pages are laid out as follows:
1170 		//
1171 		// +--------+-/-------+-/------ +-/------ +-\\\--------+
1172 		// :  PTE[] : | PMD[] : | PUD[] : | P4D[] : ||| PGD[]  :
1173 		// +--------+-\-------+-\------ +-\------ +-///--------+
1174 		//      ^
1175 		// The first page is mapped into this hierarchy at a PMD_SHIFT
1176 		// aligned virtual address, so that we can manipulate the PTE
1177 		// level entries while the mapping is active. The first entry
1178 		// covers the PTE[] page itself, the remaining entries are free
1179 		// to be used as a ad-hoc fixmap.
1180 		//
1181 		__create_pgd_mapping_locked(kpti_ng_temp_pgd, __pa(alloc),
1182 					    KPTI_NG_TEMP_VA, PAGE_SIZE, PAGE_KERNEL,
1183 					    kpti_ng_pgd_alloc, 0);
1184 	}
1185 
1186 	cpu_install_idmap();
1187 	remap_fn(cpu, num_online_cpus(), kpti_ng_temp_pgd_pa, KPTI_NG_TEMP_VA);
1188 	cpu_uninstall_idmap();
1189 
1190 	if (!cpu) {
1191 		free_pages(alloc, order);
1192 		arm64_use_ng_mappings = true;
1193 	}
1194 
1195 	return 0;
1196 }
1197 
kpti_install_ng_mappings(void)1198 void __init kpti_install_ng_mappings(void)
1199 {
1200 	/* Check whether KPTI is going to be used */
1201 	if (!arm64_kernel_unmapped_at_el0())
1202 		return;
1203 
1204 	/*
1205 	 * We don't need to rewrite the page-tables if either we've done
1206 	 * it already or we have KASLR enabled and therefore have not
1207 	 * created any global mappings at all.
1208 	 */
1209 	if (arm64_use_ng_mappings)
1210 		return;
1211 
1212 	init_idmap_kpti_bbml2_flag();
1213 	stop_machine(__kpti_install_ng_mappings, NULL, cpu_online_mask);
1214 }
1215 
kernel_exec_prot(void)1216 static pgprot_t __init kernel_exec_prot(void)
1217 {
1218 	return rodata_enabled ? PAGE_KERNEL_ROX : PAGE_KERNEL_EXEC;
1219 }
1220 
map_entry_trampoline(void)1221 static int __init map_entry_trampoline(void)
1222 {
1223 	int i;
1224 
1225 	if (!arm64_kernel_unmapped_at_el0())
1226 		return 0;
1227 
1228 	pgprot_t prot = kernel_exec_prot();
1229 	phys_addr_t pa_start = __pa_symbol(__entry_tramp_text_start);
1230 
1231 	/* The trampoline is always mapped and can therefore be global */
1232 	pgprot_val(prot) &= ~PTE_NG;
1233 
1234 	/* Map only the text into the trampoline page table */
1235 	memset(tramp_pg_dir, 0, PGD_SIZE);
1236 	__create_pgd_mapping(tramp_pg_dir, pa_start, TRAMP_VALIAS,
1237 			     entry_tramp_text_size(), prot,
1238 			     pgd_pgtable_alloc_init_mm, NO_BLOCK_MAPPINGS);
1239 
1240 	/* Map both the text and data into the kernel page table */
1241 	for (i = 0; i < DIV_ROUND_UP(entry_tramp_text_size(), PAGE_SIZE); i++)
1242 		__set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
1243 			     pa_start + i * PAGE_SIZE, prot);
1244 
1245 	if (IS_ENABLED(CONFIG_RELOCATABLE))
1246 		__set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
1247 			     pa_start + i * PAGE_SIZE, PAGE_KERNEL_RO);
1248 
1249 	return 0;
1250 }
1251 core_initcall(map_entry_trampoline);
1252 #endif
1253 
1254 /*
1255  * Declare the VMA areas for the kernel
1256  */
declare_kernel_vmas(void)1257 static void __init declare_kernel_vmas(void)
1258 {
1259 	static struct vm_struct vmlinux_seg[KERNEL_SEGMENT_COUNT];
1260 
1261 	declare_vma(&vmlinux_seg[0], _text, _etext, VM_NO_GUARD);
1262 	declare_vma(&vmlinux_seg[1], __start_rodata, __inittext_begin, VM_NO_GUARD);
1263 	declare_vma(&vmlinux_seg[2], __inittext_begin, __inittext_end, VM_NO_GUARD);
1264 	declare_vma(&vmlinux_seg[3], __initdata_begin, __initdata_end, VM_NO_GUARD);
1265 	declare_vma(&vmlinux_seg[4], _data, _end, 0);
1266 }
1267 
1268 void __pi_map_range(phys_addr_t *pte, u64 start, u64 end, phys_addr_t pa,
1269 		    pgprot_t prot, int level, pte_t *tbl, bool may_use_cont,
1270 		    u64 va_offset);
1271 
1272 static u8 idmap_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init,
1273 	  kpti_bbml2_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init;
1274 
create_idmap(void)1275 static void __init create_idmap(void)
1276 {
1277 	phys_addr_t start = __pa_symbol(__idmap_text_start);
1278 	phys_addr_t end   = __pa_symbol(__idmap_text_end);
1279 	phys_addr_t ptep  = __pa_symbol(idmap_ptes);
1280 
1281 	__pi_map_range(&ptep, start, end, start, PAGE_KERNEL_ROX,
1282 		       IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
1283 		       __phys_to_virt(ptep) - ptep);
1284 
1285 	if (linear_map_requires_bbml2 ||
1286 	    (IS_ENABLED(CONFIG_UNMAP_KERNEL_AT_EL0) && !arm64_use_ng_mappings)) {
1287 		phys_addr_t pa = __pa_symbol(&idmap_kpti_bbml2_flag);
1288 
1289 		/*
1290 		 * The KPTI G-to-nG conversion code needs a read-write mapping
1291 		 * of its synchronization flag in the ID map. This is also used
1292 		 * when splitting the linear map to ptes if a secondary CPU
1293 		 * doesn't support bbml2.
1294 		 */
1295 		ptep = __pa_symbol(kpti_bbml2_ptes);
1296 		__pi_map_range(&ptep, pa, pa + sizeof(u32), pa, PAGE_KERNEL,
1297 			       IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
1298 			       __phys_to_virt(ptep) - ptep);
1299 	}
1300 }
1301 
paging_init(void)1302 void __init paging_init(void)
1303 {
1304 	map_mem(swapper_pg_dir);
1305 
1306 	memblock_allow_resize();
1307 
1308 	create_idmap();
1309 	declare_kernel_vmas();
1310 }
1311 
1312 #ifdef CONFIG_MEMORY_HOTPLUG
free_hotplug_page_range(struct page * page,size_t size,struct vmem_altmap * altmap)1313 static void free_hotplug_page_range(struct page *page, size_t size,
1314 				    struct vmem_altmap *altmap)
1315 {
1316 	if (altmap) {
1317 		vmem_altmap_free(altmap, size >> PAGE_SHIFT);
1318 	} else {
1319 		WARN_ON(PageReserved(page));
1320 		__free_pages(page, get_order(size));
1321 	}
1322 }
1323 
free_hotplug_pgtable_page(struct page * page)1324 static void free_hotplug_pgtable_page(struct page *page)
1325 {
1326 	free_hotplug_page_range(page, PAGE_SIZE, NULL);
1327 }
1328 
pgtable_range_aligned(unsigned long start,unsigned long end,unsigned long floor,unsigned long ceiling,unsigned long mask)1329 static bool pgtable_range_aligned(unsigned long start, unsigned long end,
1330 				  unsigned long floor, unsigned long ceiling,
1331 				  unsigned long mask)
1332 {
1333 	start &= mask;
1334 	if (start < floor)
1335 		return false;
1336 
1337 	if (ceiling) {
1338 		ceiling &= mask;
1339 		if (!ceiling)
1340 			return false;
1341 	}
1342 
1343 	if (end - 1 > ceiling - 1)
1344 		return false;
1345 	return true;
1346 }
1347 
unmap_hotplug_pte_range(pmd_t * pmdp,unsigned long addr,unsigned long end,bool free_mapped,struct vmem_altmap * altmap)1348 static void unmap_hotplug_pte_range(pmd_t *pmdp, unsigned long addr,
1349 				    unsigned long end, bool free_mapped,
1350 				    struct vmem_altmap *altmap)
1351 {
1352 	pte_t *ptep, pte;
1353 
1354 	do {
1355 		ptep = pte_offset_kernel(pmdp, addr);
1356 		pte = __ptep_get(ptep);
1357 		if (pte_none(pte))
1358 			continue;
1359 
1360 		WARN_ON(!pte_present(pte));
1361 		__pte_clear(&init_mm, addr, ptep);
1362 		flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
1363 		if (free_mapped)
1364 			free_hotplug_page_range(pte_page(pte),
1365 						PAGE_SIZE, altmap);
1366 	} while (addr += PAGE_SIZE, addr < end);
1367 }
1368 
unmap_hotplug_pmd_range(pud_t * pudp,unsigned long addr,unsigned long end,bool free_mapped,struct vmem_altmap * altmap)1369 static void unmap_hotplug_pmd_range(pud_t *pudp, unsigned long addr,
1370 				    unsigned long end, bool free_mapped,
1371 				    struct vmem_altmap *altmap)
1372 {
1373 	unsigned long next;
1374 	pmd_t *pmdp, pmd;
1375 
1376 	do {
1377 		next = pmd_addr_end(addr, end);
1378 		pmdp = pmd_offset(pudp, addr);
1379 		pmd = READ_ONCE(*pmdp);
1380 		if (pmd_none(pmd))
1381 			continue;
1382 
1383 		WARN_ON(!pmd_present(pmd));
1384 		if (pmd_sect(pmd)) {
1385 			pmd_clear(pmdp);
1386 
1387 			/*
1388 			 * One TLBI should be sufficient here as the PMD_SIZE
1389 			 * range is mapped with a single block entry.
1390 			 */
1391 			flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
1392 			if (free_mapped)
1393 				free_hotplug_page_range(pmd_page(pmd),
1394 							PMD_SIZE, altmap);
1395 			continue;
1396 		}
1397 		WARN_ON(!pmd_table(pmd));
1398 		unmap_hotplug_pte_range(pmdp, addr, next, free_mapped, altmap);
1399 	} while (addr = next, addr < end);
1400 }
1401 
unmap_hotplug_pud_range(p4d_t * p4dp,unsigned long addr,unsigned long end,bool free_mapped,struct vmem_altmap * altmap)1402 static void unmap_hotplug_pud_range(p4d_t *p4dp, unsigned long addr,
1403 				    unsigned long end, bool free_mapped,
1404 				    struct vmem_altmap *altmap)
1405 {
1406 	unsigned long next;
1407 	pud_t *pudp, pud;
1408 
1409 	do {
1410 		next = pud_addr_end(addr, end);
1411 		pudp = pud_offset(p4dp, addr);
1412 		pud = READ_ONCE(*pudp);
1413 		if (pud_none(pud))
1414 			continue;
1415 
1416 		WARN_ON(!pud_present(pud));
1417 		if (pud_sect(pud)) {
1418 			pud_clear(pudp);
1419 
1420 			/*
1421 			 * One TLBI should be sufficient here as the PUD_SIZE
1422 			 * range is mapped with a single block entry.
1423 			 */
1424 			flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
1425 			if (free_mapped)
1426 				free_hotplug_page_range(pud_page(pud),
1427 							PUD_SIZE, altmap);
1428 			continue;
1429 		}
1430 		WARN_ON(!pud_table(pud));
1431 		unmap_hotplug_pmd_range(pudp, addr, next, free_mapped, altmap);
1432 	} while (addr = next, addr < end);
1433 }
1434 
unmap_hotplug_p4d_range(pgd_t * pgdp,unsigned long addr,unsigned long end,bool free_mapped,struct vmem_altmap * altmap)1435 static void unmap_hotplug_p4d_range(pgd_t *pgdp, unsigned long addr,
1436 				    unsigned long end, bool free_mapped,
1437 				    struct vmem_altmap *altmap)
1438 {
1439 	unsigned long next;
1440 	p4d_t *p4dp, p4d;
1441 
1442 	do {
1443 		next = p4d_addr_end(addr, end);
1444 		p4dp = p4d_offset(pgdp, addr);
1445 		p4d = READ_ONCE(*p4dp);
1446 		if (p4d_none(p4d))
1447 			continue;
1448 
1449 		WARN_ON(!p4d_present(p4d));
1450 		unmap_hotplug_pud_range(p4dp, addr, next, free_mapped, altmap);
1451 	} while (addr = next, addr < end);
1452 }
1453 
unmap_hotplug_range(unsigned long addr,unsigned long end,bool free_mapped,struct vmem_altmap * altmap)1454 static void unmap_hotplug_range(unsigned long addr, unsigned long end,
1455 				bool free_mapped, struct vmem_altmap *altmap)
1456 {
1457 	unsigned long next;
1458 	pgd_t *pgdp, pgd;
1459 
1460 	/*
1461 	 * altmap can only be used as vmemmap mapping backing memory.
1462 	 * In case the backing memory itself is not being freed, then
1463 	 * altmap is irrelevant. Warn about this inconsistency when
1464 	 * encountered.
1465 	 */
1466 	WARN_ON(!free_mapped && altmap);
1467 
1468 	do {
1469 		next = pgd_addr_end(addr, end);
1470 		pgdp = pgd_offset_k(addr);
1471 		pgd = READ_ONCE(*pgdp);
1472 		if (pgd_none(pgd))
1473 			continue;
1474 
1475 		WARN_ON(!pgd_present(pgd));
1476 		unmap_hotplug_p4d_range(pgdp, addr, next, free_mapped, altmap);
1477 	} while (addr = next, addr < end);
1478 }
1479 
free_empty_pte_table(pmd_t * pmdp,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)1480 static void free_empty_pte_table(pmd_t *pmdp, unsigned long addr,
1481 				 unsigned long end, unsigned long floor,
1482 				 unsigned long ceiling)
1483 {
1484 	pte_t *ptep, pte;
1485 	unsigned long i, start = addr;
1486 
1487 	do {
1488 		ptep = pte_offset_kernel(pmdp, addr);
1489 		pte = __ptep_get(ptep);
1490 
1491 		/*
1492 		 * This is just a sanity check here which verifies that
1493 		 * pte clearing has been done by earlier unmap loops.
1494 		 */
1495 		WARN_ON(!pte_none(pte));
1496 	} while (addr += PAGE_SIZE, addr < end);
1497 
1498 	if (!pgtable_range_aligned(start, end, floor, ceiling, PMD_MASK))
1499 		return;
1500 
1501 	/*
1502 	 * Check whether we can free the pte page if the rest of the
1503 	 * entries are empty. Overlap with other regions have been
1504 	 * handled by the floor/ceiling check.
1505 	 */
1506 	ptep = pte_offset_kernel(pmdp, 0UL);
1507 	for (i = 0; i < PTRS_PER_PTE; i++) {
1508 		if (!pte_none(__ptep_get(&ptep[i])))
1509 			return;
1510 	}
1511 
1512 	pmd_clear(pmdp);
1513 	__flush_tlb_kernel_pgtable(start);
1514 	free_hotplug_pgtable_page(virt_to_page(ptep));
1515 }
1516 
free_empty_pmd_table(pud_t * pudp,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)1517 static void free_empty_pmd_table(pud_t *pudp, unsigned long addr,
1518 				 unsigned long end, unsigned long floor,
1519 				 unsigned long ceiling)
1520 {
1521 	pmd_t *pmdp, pmd;
1522 	unsigned long i, next, start = addr;
1523 
1524 	do {
1525 		next = pmd_addr_end(addr, end);
1526 		pmdp = pmd_offset(pudp, addr);
1527 		pmd = READ_ONCE(*pmdp);
1528 		if (pmd_none(pmd))
1529 			continue;
1530 
1531 		WARN_ON(!pmd_present(pmd) || !pmd_table(pmd) || pmd_sect(pmd));
1532 		free_empty_pte_table(pmdp, addr, next, floor, ceiling);
1533 	} while (addr = next, addr < end);
1534 
1535 	if (CONFIG_PGTABLE_LEVELS <= 2)
1536 		return;
1537 
1538 	if (!pgtable_range_aligned(start, end, floor, ceiling, PUD_MASK))
1539 		return;
1540 
1541 	/*
1542 	 * Check whether we can free the pmd page if the rest of the
1543 	 * entries are empty. Overlap with other regions have been
1544 	 * handled by the floor/ceiling check.
1545 	 */
1546 	pmdp = pmd_offset(pudp, 0UL);
1547 	for (i = 0; i < PTRS_PER_PMD; i++) {
1548 		if (!pmd_none(READ_ONCE(pmdp[i])))
1549 			return;
1550 	}
1551 
1552 	pud_clear(pudp);
1553 	__flush_tlb_kernel_pgtable(start);
1554 	free_hotplug_pgtable_page(virt_to_page(pmdp));
1555 }
1556 
free_empty_pud_table(p4d_t * p4dp,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)1557 static void free_empty_pud_table(p4d_t *p4dp, unsigned long addr,
1558 				 unsigned long end, unsigned long floor,
1559 				 unsigned long ceiling)
1560 {
1561 	pud_t *pudp, pud;
1562 	unsigned long i, next, start = addr;
1563 
1564 	do {
1565 		next = pud_addr_end(addr, end);
1566 		pudp = pud_offset(p4dp, addr);
1567 		pud = READ_ONCE(*pudp);
1568 		if (pud_none(pud))
1569 			continue;
1570 
1571 		WARN_ON(!pud_present(pud) || !pud_table(pud) || pud_sect(pud));
1572 		free_empty_pmd_table(pudp, addr, next, floor, ceiling);
1573 	} while (addr = next, addr < end);
1574 
1575 	if (!pgtable_l4_enabled())
1576 		return;
1577 
1578 	if (!pgtable_range_aligned(start, end, floor, ceiling, P4D_MASK))
1579 		return;
1580 
1581 	/*
1582 	 * Check whether we can free the pud page if the rest of the
1583 	 * entries are empty. Overlap with other regions have been
1584 	 * handled by the floor/ceiling check.
1585 	 */
1586 	pudp = pud_offset(p4dp, 0UL);
1587 	for (i = 0; i < PTRS_PER_PUD; i++) {
1588 		if (!pud_none(READ_ONCE(pudp[i])))
1589 			return;
1590 	}
1591 
1592 	p4d_clear(p4dp);
1593 	__flush_tlb_kernel_pgtable(start);
1594 	free_hotplug_pgtable_page(virt_to_page(pudp));
1595 }
1596 
free_empty_p4d_table(pgd_t * pgdp,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)1597 static void free_empty_p4d_table(pgd_t *pgdp, unsigned long addr,
1598 				 unsigned long end, unsigned long floor,
1599 				 unsigned long ceiling)
1600 {
1601 	p4d_t *p4dp, p4d;
1602 	unsigned long i, next, start = addr;
1603 
1604 	do {
1605 		next = p4d_addr_end(addr, end);
1606 		p4dp = p4d_offset(pgdp, addr);
1607 		p4d = READ_ONCE(*p4dp);
1608 		if (p4d_none(p4d))
1609 			continue;
1610 
1611 		WARN_ON(!p4d_present(p4d));
1612 		free_empty_pud_table(p4dp, addr, next, floor, ceiling);
1613 	} while (addr = next, addr < end);
1614 
1615 	if (!pgtable_l5_enabled())
1616 		return;
1617 
1618 	if (!pgtable_range_aligned(start, end, floor, ceiling, PGDIR_MASK))
1619 		return;
1620 
1621 	/*
1622 	 * Check whether we can free the p4d page if the rest of the
1623 	 * entries are empty. Overlap with other regions have been
1624 	 * handled by the floor/ceiling check.
1625 	 */
1626 	p4dp = p4d_offset(pgdp, 0UL);
1627 	for (i = 0; i < PTRS_PER_P4D; i++) {
1628 		if (!p4d_none(READ_ONCE(p4dp[i])))
1629 			return;
1630 	}
1631 
1632 	pgd_clear(pgdp);
1633 	__flush_tlb_kernel_pgtable(start);
1634 	free_hotplug_pgtable_page(virt_to_page(p4dp));
1635 }
1636 
free_empty_tables(unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)1637 static void free_empty_tables(unsigned long addr, unsigned long end,
1638 			      unsigned long floor, unsigned long ceiling)
1639 {
1640 	unsigned long next;
1641 	pgd_t *pgdp, pgd;
1642 
1643 	do {
1644 		next = pgd_addr_end(addr, end);
1645 		pgdp = pgd_offset_k(addr);
1646 		pgd = READ_ONCE(*pgdp);
1647 		if (pgd_none(pgd))
1648 			continue;
1649 
1650 		WARN_ON(!pgd_present(pgd));
1651 		free_empty_p4d_table(pgdp, addr, next, floor, ceiling);
1652 	} while (addr = next, addr < end);
1653 }
1654 #endif
1655 
vmemmap_set_pmd(pmd_t * pmdp,void * p,int node,unsigned long addr,unsigned long next)1656 void __meminit vmemmap_set_pmd(pmd_t *pmdp, void *p, int node,
1657 			       unsigned long addr, unsigned long next)
1658 {
1659 	pmd_set_huge(pmdp, __pa(p), __pgprot(PROT_SECT_NORMAL));
1660 }
1661 
vmemmap_check_pmd(pmd_t * pmdp,int node,unsigned long addr,unsigned long next)1662 int __meminit vmemmap_check_pmd(pmd_t *pmdp, int node,
1663 				unsigned long addr, unsigned long next)
1664 {
1665 	vmemmap_verify((pte_t *)pmdp, node, addr, next);
1666 
1667 	return pmd_sect(READ_ONCE(*pmdp));
1668 }
1669 
vmemmap_populate(unsigned long start,unsigned long end,int node,struct vmem_altmap * altmap)1670 int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
1671 		struct vmem_altmap *altmap)
1672 {
1673 	WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1674 	/* [start, end] should be within one section */
1675 	WARN_ON_ONCE(end - start > PAGES_PER_SECTION * sizeof(struct page));
1676 
1677 	if (!IS_ENABLED(CONFIG_ARM64_4K_PAGES) ||
1678 	    (end - start < PAGES_PER_SECTION * sizeof(struct page)))
1679 		return vmemmap_populate_basepages(start, end, node, altmap);
1680 	else
1681 		return vmemmap_populate_hugepages(start, end, node, altmap);
1682 }
1683 
1684 #ifdef CONFIG_MEMORY_HOTPLUG
vmemmap_free(unsigned long start,unsigned long end,struct vmem_altmap * altmap)1685 void vmemmap_free(unsigned long start, unsigned long end,
1686 		struct vmem_altmap *altmap)
1687 {
1688 	WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1689 
1690 	unmap_hotplug_range(start, end, true, altmap);
1691 	free_empty_tables(start, end, VMEMMAP_START, VMEMMAP_END);
1692 }
1693 #endif /* CONFIG_MEMORY_HOTPLUG */
1694 
pud_set_huge(pud_t * pudp,phys_addr_t phys,pgprot_t prot)1695 int pud_set_huge(pud_t *pudp, phys_addr_t phys, pgprot_t prot)
1696 {
1697 	pud_t new_pud = pfn_pud(__phys_to_pfn(phys), mk_pud_sect_prot(prot));
1698 
1699 	/* Only allow permission changes for now */
1700 	if (!pgattr_change_is_safe(READ_ONCE(pud_val(*pudp)),
1701 				   pud_val(new_pud)))
1702 		return 0;
1703 
1704 	VM_BUG_ON(phys & ~PUD_MASK);
1705 	set_pud(pudp, new_pud);
1706 	return 1;
1707 }
1708 
pmd_set_huge(pmd_t * pmdp,phys_addr_t phys,pgprot_t prot)1709 int pmd_set_huge(pmd_t *pmdp, phys_addr_t phys, pgprot_t prot)
1710 {
1711 	pmd_t new_pmd = pfn_pmd(__phys_to_pfn(phys), mk_pmd_sect_prot(prot));
1712 
1713 	/* Only allow permission changes for now */
1714 	if (!pgattr_change_is_safe(READ_ONCE(pmd_val(*pmdp)),
1715 				   pmd_val(new_pmd)))
1716 		return 0;
1717 
1718 	VM_BUG_ON(phys & ~PMD_MASK);
1719 	set_pmd(pmdp, new_pmd);
1720 	return 1;
1721 }
1722 
1723 #ifndef __PAGETABLE_P4D_FOLDED
p4d_clear_huge(p4d_t * p4dp)1724 void p4d_clear_huge(p4d_t *p4dp)
1725 {
1726 }
1727 #endif
1728 
pud_clear_huge(pud_t * pudp)1729 int pud_clear_huge(pud_t *pudp)
1730 {
1731 	if (!pud_sect(READ_ONCE(*pudp)))
1732 		return 0;
1733 	pud_clear(pudp);
1734 	return 1;
1735 }
1736 
pmd_clear_huge(pmd_t * pmdp)1737 int pmd_clear_huge(pmd_t *pmdp)
1738 {
1739 	if (!pmd_sect(READ_ONCE(*pmdp)))
1740 		return 0;
1741 	pmd_clear(pmdp);
1742 	return 1;
1743 }
1744 
__pmd_free_pte_page(pmd_t * pmdp,unsigned long addr,bool acquire_mmap_lock)1745 static int __pmd_free_pte_page(pmd_t *pmdp, unsigned long addr,
1746 			       bool acquire_mmap_lock)
1747 {
1748 	pte_t *table;
1749 	pmd_t pmd;
1750 
1751 	pmd = READ_ONCE(*pmdp);
1752 
1753 	if (!pmd_table(pmd)) {
1754 		VM_WARN_ON(1);
1755 		return 1;
1756 	}
1757 
1758 	/* See comment in pud_free_pmd_page for static key logic */
1759 	table = pte_offset_kernel(pmdp, addr);
1760 	pmd_clear(pmdp);
1761 	__flush_tlb_kernel_pgtable(addr);
1762 	if (static_branch_unlikely(&arm64_ptdump_lock_key) && acquire_mmap_lock) {
1763 		mmap_read_lock(&init_mm);
1764 		mmap_read_unlock(&init_mm);
1765 	}
1766 
1767 	pte_free_kernel(NULL, table);
1768 	return 1;
1769 }
1770 
pmd_free_pte_page(pmd_t * pmdp,unsigned long addr)1771 int pmd_free_pte_page(pmd_t *pmdp, unsigned long addr)
1772 {
1773 	/* If ptdump is walking the pagetables, acquire init_mm.mmap_lock */
1774 	return __pmd_free_pte_page(pmdp, addr, /* acquire_mmap_lock = */ true);
1775 }
1776 
pud_free_pmd_page(pud_t * pudp,unsigned long addr)1777 int pud_free_pmd_page(pud_t *pudp, unsigned long addr)
1778 {
1779 	pmd_t *table;
1780 	pmd_t *pmdp;
1781 	pud_t pud;
1782 	unsigned long next, end;
1783 
1784 	pud = READ_ONCE(*pudp);
1785 
1786 	if (!pud_table(pud)) {
1787 		VM_WARN_ON(1);
1788 		return 1;
1789 	}
1790 
1791 	table = pmd_offset(pudp, addr);
1792 
1793 	/*
1794 	 * Our objective is to prevent ptdump from reading a PMD table which has
1795 	 * been freed. In this race, if pud_free_pmd_page observes the key on
1796 	 * (which got flipped by ptdump) then the mmap lock sequence here will,
1797 	 * as a result of the mmap write lock/unlock sequence in ptdump, give
1798 	 * us the correct synchronization. If not, this means that ptdump has
1799 	 * yet not started walking the pagetables - the sequence of barriers
1800 	 * issued by __flush_tlb_kernel_pgtable() guarantees that ptdump will
1801 	 * observe an empty PUD.
1802 	 */
1803 	pud_clear(pudp);
1804 	__flush_tlb_kernel_pgtable(addr);
1805 	if (static_branch_unlikely(&arm64_ptdump_lock_key)) {
1806 		mmap_read_lock(&init_mm);
1807 		mmap_read_unlock(&init_mm);
1808 	}
1809 
1810 	pmdp = table;
1811 	next = addr;
1812 	end = addr + PUD_SIZE;
1813 	do {
1814 		if (pmd_present(pmdp_get(pmdp)))
1815 			/*
1816 			 * PMD has been isolated, so ptdump won't see it. No
1817 			 * need to acquire init_mm.mmap_lock.
1818 			 */
1819 			__pmd_free_pte_page(pmdp, next, /* acquire_mmap_lock = */ false);
1820 	} while (pmdp++, next += PMD_SIZE, next != end);
1821 
1822 	pmd_free(NULL, table);
1823 	return 1;
1824 }
1825 
1826 #ifdef CONFIG_MEMORY_HOTPLUG
__remove_pgd_mapping(pgd_t * pgdir,unsigned long start,u64 size)1827 static void __remove_pgd_mapping(pgd_t *pgdir, unsigned long start, u64 size)
1828 {
1829 	unsigned long end = start + size;
1830 
1831 	WARN_ON(pgdir != init_mm.pgd);
1832 	WARN_ON((start < PAGE_OFFSET) || (end > PAGE_END));
1833 
1834 	unmap_hotplug_range(start, end, false, NULL);
1835 	free_empty_tables(start, end, PAGE_OFFSET, PAGE_END);
1836 }
1837 
arch_get_mappable_range(void)1838 struct range arch_get_mappable_range(void)
1839 {
1840 	struct range mhp_range;
1841 	phys_addr_t start_linear_pa = __pa(_PAGE_OFFSET(vabits_actual));
1842 	phys_addr_t end_linear_pa = __pa(PAGE_END - 1);
1843 
1844 	if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) {
1845 		/*
1846 		 * Check for a wrap, it is possible because of randomized linear
1847 		 * mapping the start physical address is actually bigger than
1848 		 * the end physical address. In this case set start to zero
1849 		 * because [0, end_linear_pa] range must still be able to cover
1850 		 * all addressable physical addresses.
1851 		 */
1852 		if (start_linear_pa > end_linear_pa)
1853 			start_linear_pa = 0;
1854 	}
1855 
1856 	WARN_ON(start_linear_pa > end_linear_pa);
1857 
1858 	/*
1859 	 * Linear mapping region is the range [PAGE_OFFSET..(PAGE_END - 1)]
1860 	 * accommodating both its ends but excluding PAGE_END. Max physical
1861 	 * range which can be mapped inside this linear mapping range, must
1862 	 * also be derived from its end points.
1863 	 */
1864 	mhp_range.start = start_linear_pa;
1865 	mhp_range.end =  end_linear_pa;
1866 
1867 	return mhp_range;
1868 }
1869 
arch_add_memory(int nid,u64 start,u64 size,struct mhp_params * params)1870 int arch_add_memory(int nid, u64 start, u64 size,
1871 		    struct mhp_params *params)
1872 {
1873 	int ret, flags = NO_EXEC_MAPPINGS;
1874 
1875 	VM_BUG_ON(!mhp_range_allowed(start, size, true));
1876 
1877 	if (force_pte_mapping())
1878 		flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
1879 
1880 	__create_pgd_mapping(swapper_pg_dir, start, __phys_to_virt(start),
1881 			     size, params->pgprot, pgd_pgtable_alloc_init_mm,
1882 			     flags);
1883 
1884 	memblock_clear_nomap(start, size);
1885 
1886 	ret = __add_pages(nid, start >> PAGE_SHIFT, size >> PAGE_SHIFT,
1887 			   params);
1888 	if (ret)
1889 		__remove_pgd_mapping(swapper_pg_dir,
1890 				     __phys_to_virt(start), size);
1891 	else {
1892 		/* Address of hotplugged memory can be smaller */
1893 		max_pfn = max(max_pfn, PFN_UP(start + size));
1894 		max_low_pfn = max_pfn;
1895 	}
1896 
1897 	return ret;
1898 }
1899 
arch_remove_memory(u64 start,u64 size,struct vmem_altmap * altmap)1900 void arch_remove_memory(u64 start, u64 size, struct vmem_altmap *altmap)
1901 {
1902 	unsigned long start_pfn = start >> PAGE_SHIFT;
1903 	unsigned long nr_pages = size >> PAGE_SHIFT;
1904 
1905 	__remove_pages(start_pfn, nr_pages, altmap);
1906 	__remove_pgd_mapping(swapper_pg_dir, __phys_to_virt(start), size);
1907 }
1908 
1909 /*
1910  * This memory hotplug notifier helps prevent boot memory from being
1911  * inadvertently removed as it blocks pfn range offlining process in
1912  * __offline_pages(). Hence this prevents both offlining as well as
1913  * removal process for boot memory which is initially always online.
1914  * In future if and when boot memory could be removed, this notifier
1915  * should be dropped and free_hotplug_page_range() should handle any
1916  * reserved pages allocated during boot.
1917  */
prevent_bootmem_remove_notifier(struct notifier_block * nb,unsigned long action,void * data)1918 static int prevent_bootmem_remove_notifier(struct notifier_block *nb,
1919 					   unsigned long action, void *data)
1920 {
1921 	struct mem_section *ms;
1922 	struct memory_notify *arg = data;
1923 	unsigned long end_pfn = arg->start_pfn + arg->nr_pages;
1924 	unsigned long pfn = arg->start_pfn;
1925 
1926 	if ((action != MEM_GOING_OFFLINE) && (action != MEM_OFFLINE))
1927 		return NOTIFY_OK;
1928 
1929 	for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
1930 		unsigned long start = PFN_PHYS(pfn);
1931 		unsigned long end = start + (1UL << PA_SECTION_SHIFT);
1932 
1933 		ms = __pfn_to_section(pfn);
1934 		if (!early_section(ms))
1935 			continue;
1936 
1937 		if (action == MEM_GOING_OFFLINE) {
1938 			/*
1939 			 * Boot memory removal is not supported. Prevent
1940 			 * it via blocking any attempted offline request
1941 			 * for the boot memory and just report it.
1942 			 */
1943 			pr_warn("Boot memory [%lx %lx] offlining attempted\n", start, end);
1944 			return NOTIFY_BAD;
1945 		} else if (action == MEM_OFFLINE) {
1946 			/*
1947 			 * This should have never happened. Boot memory
1948 			 * offlining should have been prevented by this
1949 			 * very notifier. Probably some memory removal
1950 			 * procedure might have changed which would then
1951 			 * require further debug.
1952 			 */
1953 			pr_err("Boot memory [%lx %lx] offlined\n", start, end);
1954 
1955 			/*
1956 			 * Core memory hotplug does not process a return
1957 			 * code from the notifier for MEM_OFFLINE events.
1958 			 * The error condition has been reported. Return
1959 			 * from here as if ignored.
1960 			 */
1961 			return NOTIFY_DONE;
1962 		}
1963 	}
1964 	return NOTIFY_OK;
1965 }
1966 
1967 static struct notifier_block prevent_bootmem_remove_nb = {
1968 	.notifier_call = prevent_bootmem_remove_notifier,
1969 };
1970 
1971 /*
1972  * This ensures that boot memory sections on the platform are online
1973  * from early boot. Memory sections could not be prevented from being
1974  * offlined, unless for some reason they are not online to begin with.
1975  * This helps validate the basic assumption on which the above memory
1976  * event notifier works to prevent boot memory section offlining and
1977  * its possible removal.
1978  */
validate_bootmem_online(void)1979 static void validate_bootmem_online(void)
1980 {
1981 	phys_addr_t start, end, addr;
1982 	struct mem_section *ms;
1983 	u64 i;
1984 
1985 	/*
1986 	 * Scanning across all memblock might be expensive
1987 	 * on some big memory systems. Hence enable this
1988 	 * validation only with DEBUG_VM.
1989 	 */
1990 	if (!IS_ENABLED(CONFIG_DEBUG_VM))
1991 		return;
1992 
1993 	for_each_mem_range(i, &start, &end) {
1994 		for (addr = start; addr < end; addr += (1UL << PA_SECTION_SHIFT)) {
1995 			ms = __pfn_to_section(PHYS_PFN(addr));
1996 
1997 			/*
1998 			 * All memory ranges in the system at this point
1999 			 * should have been marked as early sections.
2000 			 */
2001 			WARN_ON(!early_section(ms));
2002 
2003 			/*
2004 			 * Memory notifier mechanism here to prevent boot
2005 			 * memory offlining depends on the fact that each
2006 			 * early section memory on the system is initially
2007 			 * online. Otherwise a given memory section which
2008 			 * is already offline will be overlooked and can
2009 			 * be removed completely. Call out such sections.
2010 			 */
2011 			if (!online_section(ms))
2012 				pr_err("Boot memory [%llx %llx] is offline, can be removed\n",
2013 					addr, addr + (1UL << PA_SECTION_SHIFT));
2014 		}
2015 	}
2016 }
2017 
prevent_bootmem_remove_init(void)2018 static int __init prevent_bootmem_remove_init(void)
2019 {
2020 	int ret = 0;
2021 
2022 	if (!IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
2023 		return ret;
2024 
2025 	validate_bootmem_online();
2026 	ret = register_memory_notifier(&prevent_bootmem_remove_nb);
2027 	if (ret)
2028 		pr_err("%s: Notifier registration failed %d\n", __func__, ret);
2029 
2030 	return ret;
2031 }
2032 early_initcall(prevent_bootmem_remove_init);
2033 #endif
2034 
modify_prot_start_ptes(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep,unsigned int nr)2035 pte_t modify_prot_start_ptes(struct vm_area_struct *vma, unsigned long addr,
2036 			     pte_t *ptep, unsigned int nr)
2037 {
2038 	pte_t pte = get_and_clear_ptes(vma->vm_mm, addr, ptep, nr);
2039 
2040 	if (alternative_has_cap_unlikely(ARM64_WORKAROUND_2645198)) {
2041 		/*
2042 		 * Break-before-make (BBM) is required for all user space mappings
2043 		 * when the permission changes from executable to non-executable
2044 		 * in cases where cpu is affected with errata #2645198.
2045 		 */
2046 		if (pte_accessible(vma->vm_mm, pte) && pte_user_exec(pte))
2047 			__flush_tlb_range(vma, addr, nr * PAGE_SIZE,
2048 					  PAGE_SIZE, true, 3);
2049 	}
2050 
2051 	return pte;
2052 }
2053 
ptep_modify_prot_start(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep)2054 pte_t ptep_modify_prot_start(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep)
2055 {
2056 	return modify_prot_start_ptes(vma, addr, ptep, 1);
2057 }
2058 
modify_prot_commit_ptes(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep,pte_t old_pte,pte_t pte,unsigned int nr)2059 void modify_prot_commit_ptes(struct vm_area_struct *vma, unsigned long addr,
2060 			     pte_t *ptep, pte_t old_pte, pte_t pte,
2061 			     unsigned int nr)
2062 {
2063 	set_ptes(vma->vm_mm, addr, ptep, pte, nr);
2064 }
2065 
ptep_modify_prot_commit(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep,pte_t old_pte,pte_t pte)2066 void ptep_modify_prot_commit(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep,
2067 			     pte_t old_pte, pte_t pte)
2068 {
2069 	modify_prot_commit_ptes(vma, addr, ptep, old_pte, pte, 1);
2070 }
2071 
2072 /*
2073  * Atomically replaces the active TTBR1_EL1 PGD with a new VA-compatible PGD,
2074  * avoiding the possibility of conflicting TLB entries being allocated.
2075  */
__cpu_replace_ttbr1(pgd_t * pgdp,bool cnp)2076 void __cpu_replace_ttbr1(pgd_t *pgdp, bool cnp)
2077 {
2078 	typedef void (ttbr_replace_func)(phys_addr_t);
2079 	extern ttbr_replace_func idmap_cpu_replace_ttbr1;
2080 	ttbr_replace_func *replace_phys;
2081 	unsigned long daif;
2082 
2083 	/* phys_to_ttbr() zeros lower 2 bits of ttbr with 52-bit PA */
2084 	phys_addr_t ttbr1 = phys_to_ttbr(virt_to_phys(pgdp));
2085 
2086 	if (cnp)
2087 		ttbr1 |= TTBR_CNP_BIT;
2088 
2089 	replace_phys = (void *)__pa_symbol(idmap_cpu_replace_ttbr1);
2090 
2091 	cpu_install_idmap();
2092 
2093 	/*
2094 	 * We really don't want to take *any* exceptions while TTBR1 is
2095 	 * in the process of being replaced so mask everything.
2096 	 */
2097 	daif = local_daif_save();
2098 	replace_phys(ttbr1);
2099 	local_daif_restore(daif);
2100 
2101 	cpu_uninstall_idmap();
2102 }
2103 
2104 #ifdef CONFIG_ARCH_HAS_PKEYS
arch_set_user_pkey_access(struct task_struct * tsk,int pkey,unsigned long init_val)2105 int arch_set_user_pkey_access(struct task_struct *tsk, int pkey, unsigned long init_val)
2106 {
2107 	u64 new_por;
2108 	u64 old_por;
2109 
2110 	if (!system_supports_poe())
2111 		return -ENOSPC;
2112 
2113 	/*
2114 	 * This code should only be called with valid 'pkey'
2115 	 * values originating from in-kernel users.  Complain
2116 	 * if a bad value is observed.
2117 	 */
2118 	if (WARN_ON_ONCE(pkey >= arch_max_pkey()))
2119 		return -EINVAL;
2120 
2121 	/* Set the bits we need in POR:  */
2122 	new_por = POE_RWX;
2123 	if (init_val & PKEY_DISABLE_WRITE)
2124 		new_por &= ~POE_W;
2125 	if (init_val & PKEY_DISABLE_ACCESS)
2126 		new_por &= ~POE_RW;
2127 	if (init_val & PKEY_DISABLE_READ)
2128 		new_por &= ~POE_R;
2129 	if (init_val & PKEY_DISABLE_EXECUTE)
2130 		new_por &= ~POE_X;
2131 
2132 	/* Shift the bits in to the correct place in POR for pkey: */
2133 	new_por = POR_ELx_PERM_PREP(pkey, new_por);
2134 
2135 	/* Get old POR and mask off any old bits in place: */
2136 	old_por = read_sysreg_s(SYS_POR_EL0);
2137 	old_por &= ~(POE_MASK << POR_ELx_PERM_SHIFT(pkey));
2138 
2139 	/* Write old part along with new part: */
2140 	write_sysreg_s(old_por | new_por, SYS_POR_EL0);
2141 
2142 	return 0;
2143 }
2144 #endif
2145