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