xref: /openbmc/linux/arch/arm64/mm/mmu.c (revision c832da79)
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 
28 #include <asm/barrier.h>
29 #include <asm/cputype.h>
30 #include <asm/fixmap.h>
31 #include <asm/kasan.h>
32 #include <asm/kernel-pgtable.h>
33 #include <asm/sections.h>
34 #include <asm/setup.h>
35 #include <linux/sizes.h>
36 #include <asm/tlb.h>
37 #include <asm/mmu_context.h>
38 #include <asm/ptdump.h>
39 #include <asm/tlbflush.h>
40 #include <asm/pgalloc.h>
41 
42 #define NO_BLOCK_MAPPINGS	BIT(0)
43 #define NO_CONT_MAPPINGS	BIT(1)
44 #define NO_EXEC_MAPPINGS	BIT(2)	/* assumes FEAT_HPDS is not used */
45 
46 int idmap_t0sz __ro_after_init;
47 
48 #if VA_BITS > 48
49 u64 vabits_actual __ro_after_init = VA_BITS_MIN;
50 EXPORT_SYMBOL(vabits_actual);
51 #endif
52 
53 u64 kimage_vaddr __ro_after_init = (u64)&_text;
54 EXPORT_SYMBOL(kimage_vaddr);
55 
56 u64 kimage_voffset __ro_after_init;
57 EXPORT_SYMBOL(kimage_voffset);
58 
59 u32 __boot_cpu_mode[] = { BOOT_CPU_MODE_EL2, BOOT_CPU_MODE_EL1 };
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 pte_t bm_pte[PTRS_PER_PTE] __page_aligned_bss;
75 static pmd_t bm_pmd[PTRS_PER_PMD] __page_aligned_bss __maybe_unused;
76 static pud_t bm_pud[PTRS_PER_PUD] __page_aligned_bss __maybe_unused;
77 
78 static DEFINE_SPINLOCK(swapper_pgdir_lock);
79 static DEFINE_MUTEX(fixmap_lock);
80 
81 void set_swapper_pgd(pgd_t *pgdp, pgd_t pgd)
82 {
83 	pgd_t *fixmap_pgdp;
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(int shift)
109 {
110 	phys_addr_t phys;
111 	void *ptr;
112 
113 	phys = memblock_phys_alloc_range(PAGE_SIZE, PAGE_SIZE, 0,
114 					 MEMBLOCK_ALLOC_NOLEAKTRACE);
115 	if (!phys)
116 		panic("Failed to allocate page table page\n");
117 
118 	/*
119 	 * The FIX_{PGD,PUD,PMD} slots may be in active use, but the FIX_PTE
120 	 * slot will be free, so we can (ab)use the FIX_PTE slot to initialise
121 	 * any level of table.
122 	 */
123 	ptr = pte_set_fixmap(phys);
124 
125 	memset(ptr, 0, PAGE_SIZE);
126 
127 	/*
128 	 * Implicit barriers also ensure the zeroed page is visible to the page
129 	 * table walker
130 	 */
131 	pte_clear_fixmap();
132 
133 	return phys;
134 }
135 
136 static bool pgattr_change_is_safe(u64 old, u64 new)
137 {
138 	/*
139 	 * The following mapping attributes may be updated in live
140 	 * kernel mappings without the need for break-before-make.
141 	 */
142 	pteval_t mask = PTE_PXN | PTE_RDONLY | PTE_WRITE | PTE_NG;
143 
144 	/* creating or taking down mappings is always safe */
145 	if (old == 0 || new == 0)
146 		return true;
147 
148 	/* live contiguous mappings may not be manipulated at all */
149 	if ((old | new) & PTE_CONT)
150 		return false;
151 
152 	/* Transitioning from Non-Global to Global is unsafe */
153 	if (old & ~new & PTE_NG)
154 		return false;
155 
156 	/*
157 	 * Changing the memory type between Normal and Normal-Tagged is safe
158 	 * since Tagged is considered a permission attribute from the
159 	 * mismatched attribute aliases perspective.
160 	 */
161 	if (((old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
162 	     (old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)) &&
163 	    ((new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
164 	     (new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)))
165 		mask |= PTE_ATTRINDX_MASK;
166 
167 	return ((old ^ new) & ~mask) == 0;
168 }
169 
170 static void init_pte(pmd_t *pmdp, unsigned long addr, unsigned long end,
171 		     phys_addr_t phys, pgprot_t prot)
172 {
173 	pte_t *ptep;
174 
175 	ptep = pte_set_fixmap_offset(pmdp, addr);
176 	do {
177 		pte_t old_pte = READ_ONCE(*ptep);
178 
179 		set_pte(ptep, pfn_pte(__phys_to_pfn(phys), prot));
180 
181 		/*
182 		 * After the PTE entry has been populated once, we
183 		 * only allow updates to the permission attributes.
184 		 */
185 		BUG_ON(!pgattr_change_is_safe(pte_val(old_pte),
186 					      READ_ONCE(pte_val(*ptep))));
187 
188 		phys += PAGE_SIZE;
189 	} while (ptep++, addr += PAGE_SIZE, addr != end);
190 
191 	pte_clear_fixmap();
192 }
193 
194 static void alloc_init_cont_pte(pmd_t *pmdp, unsigned long addr,
195 				unsigned long end, phys_addr_t phys,
196 				pgprot_t prot,
197 				phys_addr_t (*pgtable_alloc)(int),
198 				int flags)
199 {
200 	unsigned long next;
201 	pmd_t pmd = READ_ONCE(*pmdp);
202 
203 	BUG_ON(pmd_sect(pmd));
204 	if (pmd_none(pmd)) {
205 		pmdval_t pmdval = PMD_TYPE_TABLE | PMD_TABLE_UXN;
206 		phys_addr_t pte_phys;
207 
208 		if (flags & NO_EXEC_MAPPINGS)
209 			pmdval |= PMD_TABLE_PXN;
210 		BUG_ON(!pgtable_alloc);
211 		pte_phys = pgtable_alloc(PAGE_SHIFT);
212 		__pmd_populate(pmdp, pte_phys, pmdval);
213 		pmd = READ_ONCE(*pmdp);
214 	}
215 	BUG_ON(pmd_bad(pmd));
216 
217 	do {
218 		pgprot_t __prot = prot;
219 
220 		next = pte_cont_addr_end(addr, end);
221 
222 		/* use a contiguous mapping if the range is suitably aligned */
223 		if ((((addr | next | phys) & ~CONT_PTE_MASK) == 0) &&
224 		    (flags & NO_CONT_MAPPINGS) == 0)
225 			__prot = __pgprot(pgprot_val(prot) | PTE_CONT);
226 
227 		init_pte(pmdp, addr, next, phys, __prot);
228 
229 		phys += next - addr;
230 	} while (addr = next, addr != end);
231 }
232 
233 static void init_pmd(pud_t *pudp, unsigned long addr, unsigned long end,
234 		     phys_addr_t phys, pgprot_t prot,
235 		     phys_addr_t (*pgtable_alloc)(int), int flags)
236 {
237 	unsigned long next;
238 	pmd_t *pmdp;
239 
240 	pmdp = pmd_set_fixmap_offset(pudp, addr);
241 	do {
242 		pmd_t old_pmd = READ_ONCE(*pmdp);
243 
244 		next = pmd_addr_end(addr, end);
245 
246 		/* try section mapping first */
247 		if (((addr | next | phys) & ~PMD_MASK) == 0 &&
248 		    (flags & NO_BLOCK_MAPPINGS) == 0) {
249 			pmd_set_huge(pmdp, phys, prot);
250 
251 			/*
252 			 * After the PMD entry has been populated once, we
253 			 * only allow updates to the permission attributes.
254 			 */
255 			BUG_ON(!pgattr_change_is_safe(pmd_val(old_pmd),
256 						      READ_ONCE(pmd_val(*pmdp))));
257 		} else {
258 			alloc_init_cont_pte(pmdp, addr, next, phys, prot,
259 					    pgtable_alloc, flags);
260 
261 			BUG_ON(pmd_val(old_pmd) != 0 &&
262 			       pmd_val(old_pmd) != READ_ONCE(pmd_val(*pmdp)));
263 		}
264 		phys += next - addr;
265 	} while (pmdp++, addr = next, addr != end);
266 
267 	pmd_clear_fixmap();
268 }
269 
270 static void alloc_init_cont_pmd(pud_t *pudp, unsigned long addr,
271 				unsigned long end, phys_addr_t phys,
272 				pgprot_t prot,
273 				phys_addr_t (*pgtable_alloc)(int), int flags)
274 {
275 	unsigned long next;
276 	pud_t pud = READ_ONCE(*pudp);
277 
278 	/*
279 	 * Check for initial section mappings in the pgd/pud.
280 	 */
281 	BUG_ON(pud_sect(pud));
282 	if (pud_none(pud)) {
283 		pudval_t pudval = PUD_TYPE_TABLE | PUD_TABLE_UXN;
284 		phys_addr_t pmd_phys;
285 
286 		if (flags & NO_EXEC_MAPPINGS)
287 			pudval |= PUD_TABLE_PXN;
288 		BUG_ON(!pgtable_alloc);
289 		pmd_phys = pgtable_alloc(PMD_SHIFT);
290 		__pud_populate(pudp, pmd_phys, pudval);
291 		pud = READ_ONCE(*pudp);
292 	}
293 	BUG_ON(pud_bad(pud));
294 
295 	do {
296 		pgprot_t __prot = prot;
297 
298 		next = pmd_cont_addr_end(addr, end);
299 
300 		/* use a contiguous mapping if the range is suitably aligned */
301 		if ((((addr | next | phys) & ~CONT_PMD_MASK) == 0) &&
302 		    (flags & NO_CONT_MAPPINGS) == 0)
303 			__prot = __pgprot(pgprot_val(prot) | PTE_CONT);
304 
305 		init_pmd(pudp, addr, next, phys, __prot, pgtable_alloc, flags);
306 
307 		phys += next - addr;
308 	} while (addr = next, addr != end);
309 }
310 
311 static void alloc_init_pud(pgd_t *pgdp, unsigned long addr, unsigned long end,
312 			   phys_addr_t phys, pgprot_t prot,
313 			   phys_addr_t (*pgtable_alloc)(int),
314 			   int flags)
315 {
316 	unsigned long next;
317 	pud_t *pudp;
318 	p4d_t *p4dp = p4d_offset(pgdp, addr);
319 	p4d_t p4d = READ_ONCE(*p4dp);
320 
321 	if (p4d_none(p4d)) {
322 		p4dval_t p4dval = P4D_TYPE_TABLE | P4D_TABLE_UXN;
323 		phys_addr_t pud_phys;
324 
325 		if (flags & NO_EXEC_MAPPINGS)
326 			p4dval |= P4D_TABLE_PXN;
327 		BUG_ON(!pgtable_alloc);
328 		pud_phys = pgtable_alloc(PUD_SHIFT);
329 		__p4d_populate(p4dp, pud_phys, p4dval);
330 		p4d = READ_ONCE(*p4dp);
331 	}
332 	BUG_ON(p4d_bad(p4d));
333 
334 	/*
335 	 * No need for locking during early boot. And it doesn't work as
336 	 * expected with KASLR enabled.
337 	 */
338 	if (system_state != SYSTEM_BOOTING)
339 		mutex_lock(&fixmap_lock);
340 	pudp = pud_set_fixmap_offset(p4dp, addr);
341 	do {
342 		pud_t old_pud = READ_ONCE(*pudp);
343 
344 		next = pud_addr_end(addr, end);
345 
346 		/*
347 		 * For 4K granule only, attempt to put down a 1GB block
348 		 */
349 		if (pud_sect_supported() &&
350 		   ((addr | next | phys) & ~PUD_MASK) == 0 &&
351 		    (flags & NO_BLOCK_MAPPINGS) == 0) {
352 			pud_set_huge(pudp, phys, prot);
353 
354 			/*
355 			 * After the PUD entry has been populated once, we
356 			 * only allow updates to the permission attributes.
357 			 */
358 			BUG_ON(!pgattr_change_is_safe(pud_val(old_pud),
359 						      READ_ONCE(pud_val(*pudp))));
360 		} else {
361 			alloc_init_cont_pmd(pudp, addr, next, phys, prot,
362 					    pgtable_alloc, flags);
363 
364 			BUG_ON(pud_val(old_pud) != 0 &&
365 			       pud_val(old_pud) != READ_ONCE(pud_val(*pudp)));
366 		}
367 		phys += next - addr;
368 	} while (pudp++, addr = next, addr != end);
369 
370 	pud_clear_fixmap();
371 	if (system_state != SYSTEM_BOOTING)
372 		mutex_unlock(&fixmap_lock);
373 }
374 
375 static void __create_pgd_mapping(pgd_t *pgdir, phys_addr_t phys,
376 				 unsigned long virt, phys_addr_t size,
377 				 pgprot_t prot,
378 				 phys_addr_t (*pgtable_alloc)(int),
379 				 int flags)
380 {
381 	unsigned long addr, end, next;
382 	pgd_t *pgdp = pgd_offset_pgd(pgdir, virt);
383 
384 	/*
385 	 * If the virtual and physical address don't have the same offset
386 	 * within a page, we cannot map the region as the caller expects.
387 	 */
388 	if (WARN_ON((phys ^ virt) & ~PAGE_MASK))
389 		return;
390 
391 	phys &= PAGE_MASK;
392 	addr = virt & PAGE_MASK;
393 	end = PAGE_ALIGN(virt + size);
394 
395 	do {
396 		next = pgd_addr_end(addr, end);
397 		alloc_init_pud(pgdp, addr, next, phys, prot, pgtable_alloc,
398 			       flags);
399 		phys += next - addr;
400 	} while (pgdp++, addr = next, addr != end);
401 }
402 
403 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
404 extern __alias(__create_pgd_mapping)
405 void create_kpti_ng_temp_pgd(pgd_t *pgdir, phys_addr_t phys, unsigned long virt,
406 			     phys_addr_t size, pgprot_t prot,
407 			     phys_addr_t (*pgtable_alloc)(int), int flags);
408 #endif
409 
410 static phys_addr_t __pgd_pgtable_alloc(int shift)
411 {
412 	void *ptr = (void *)__get_free_page(GFP_PGTABLE_KERNEL);
413 	BUG_ON(!ptr);
414 
415 	/* Ensure the zeroed page is visible to the page table walker */
416 	dsb(ishst);
417 	return __pa(ptr);
418 }
419 
420 static phys_addr_t pgd_pgtable_alloc(int shift)
421 {
422 	phys_addr_t pa = __pgd_pgtable_alloc(shift);
423 
424 	/*
425 	 * Call proper page table ctor in case later we need to
426 	 * call core mm functions like apply_to_page_range() on
427 	 * this pre-allocated page table.
428 	 *
429 	 * We don't select ARCH_ENABLE_SPLIT_PMD_PTLOCK if pmd is
430 	 * folded, and if so pgtable_pmd_page_ctor() becomes nop.
431 	 */
432 	if (shift == PAGE_SHIFT)
433 		BUG_ON(!pgtable_pte_page_ctor(phys_to_page(pa)));
434 	else if (shift == PMD_SHIFT)
435 		BUG_ON(!pgtable_pmd_page_ctor(phys_to_page(pa)));
436 
437 	return pa;
438 }
439 
440 /*
441  * This function can only be used to modify existing table entries,
442  * without allocating new levels of table. Note that this permits the
443  * creation of new section or page entries.
444  */
445 static void __init create_mapping_noalloc(phys_addr_t phys, unsigned long virt,
446 				  phys_addr_t size, pgprot_t prot)
447 {
448 	if ((virt >= PAGE_END) && (virt < VMALLOC_START)) {
449 		pr_warn("BUG: not creating mapping for %pa at 0x%016lx - outside kernel range\n",
450 			&phys, virt);
451 		return;
452 	}
453 	__create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
454 			     NO_CONT_MAPPINGS);
455 }
456 
457 void __init create_pgd_mapping(struct mm_struct *mm, phys_addr_t phys,
458 			       unsigned long virt, phys_addr_t size,
459 			       pgprot_t prot, bool page_mappings_only)
460 {
461 	int flags = 0;
462 
463 	BUG_ON(mm == &init_mm);
464 
465 	if (page_mappings_only)
466 		flags = NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
467 
468 	__create_pgd_mapping(mm->pgd, phys, virt, size, prot,
469 			     pgd_pgtable_alloc, flags);
470 }
471 
472 static void update_mapping_prot(phys_addr_t phys, unsigned long virt,
473 				phys_addr_t size, pgprot_t prot)
474 {
475 	if ((virt >= PAGE_END) && (virt < VMALLOC_START)) {
476 		pr_warn("BUG: not updating mapping for %pa at 0x%016lx - outside kernel range\n",
477 			&phys, virt);
478 		return;
479 	}
480 
481 	__create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
482 			     NO_CONT_MAPPINGS);
483 
484 	/* flush the TLBs after updating live kernel mappings */
485 	flush_tlb_kernel_range(virt, virt + size);
486 }
487 
488 static void __init __map_memblock(pgd_t *pgdp, phys_addr_t start,
489 				  phys_addr_t end, pgprot_t prot, int flags)
490 {
491 	__create_pgd_mapping(pgdp, start, __phys_to_virt(start), end - start,
492 			     prot, early_pgtable_alloc, flags);
493 }
494 
495 void __init mark_linear_text_alias_ro(void)
496 {
497 	/*
498 	 * Remove the write permissions from the linear alias of .text/.rodata
499 	 */
500 	update_mapping_prot(__pa_symbol(_stext), (unsigned long)lm_alias(_stext),
501 			    (unsigned long)__init_begin - (unsigned long)_stext,
502 			    PAGE_KERNEL_RO);
503 }
504 
505 static bool crash_mem_map __initdata;
506 
507 static int __init enable_crash_mem_map(char *arg)
508 {
509 	/*
510 	 * Proper parameter parsing is done by reserve_crashkernel(). We only
511 	 * need to know if the linear map has to avoid block mappings so that
512 	 * the crashkernel reservations can be unmapped later.
513 	 */
514 	crash_mem_map = true;
515 
516 	return 0;
517 }
518 early_param("crashkernel", enable_crash_mem_map);
519 
520 static void __init map_mem(pgd_t *pgdp)
521 {
522 	static const u64 direct_map_end = _PAGE_END(VA_BITS_MIN);
523 	phys_addr_t kernel_start = __pa_symbol(_stext);
524 	phys_addr_t kernel_end = __pa_symbol(__init_begin);
525 	phys_addr_t start, end;
526 	int flags = NO_EXEC_MAPPINGS;
527 	u64 i;
528 
529 	/*
530 	 * Setting hierarchical PXNTable attributes on table entries covering
531 	 * the linear region is only possible if it is guaranteed that no table
532 	 * entries at any level are being shared between the linear region and
533 	 * the vmalloc region. Check whether this is true for the PGD level, in
534 	 * which case it is guaranteed to be true for all other levels as well.
535 	 */
536 	BUILD_BUG_ON(pgd_index(direct_map_end - 1) == pgd_index(direct_map_end));
537 
538 	if (can_set_direct_map() || IS_ENABLED(CONFIG_KFENCE))
539 		flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
540 
541 	/*
542 	 * Take care not to create a writable alias for the
543 	 * read-only text and rodata sections of the kernel image.
544 	 * So temporarily mark them as NOMAP to skip mappings in
545 	 * the following for-loop
546 	 */
547 	memblock_mark_nomap(kernel_start, kernel_end - kernel_start);
548 
549 #ifdef CONFIG_KEXEC_CORE
550 	if (crash_mem_map) {
551 		if (defer_reserve_crashkernel())
552 			flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
553 		else if (crashk_res.end)
554 			memblock_mark_nomap(crashk_res.start,
555 			    resource_size(&crashk_res));
556 	}
557 #endif
558 
559 	/* map all the memory banks */
560 	for_each_mem_range(i, &start, &end) {
561 		if (start >= end)
562 			break;
563 		/*
564 		 * The linear map must allow allocation tags reading/writing
565 		 * if MTE is present. Otherwise, it has the same attributes as
566 		 * PAGE_KERNEL.
567 		 */
568 		__map_memblock(pgdp, start, end, pgprot_tagged(PAGE_KERNEL),
569 			       flags);
570 	}
571 
572 	/*
573 	 * Map the linear alias of the [_stext, __init_begin) interval
574 	 * as non-executable now, and remove the write permission in
575 	 * mark_linear_text_alias_ro() below (which will be called after
576 	 * alternative patching has completed). This makes the contents
577 	 * of the region accessible to subsystems such as hibernate,
578 	 * but protects it from inadvertent modification or execution.
579 	 * Note that contiguous mappings cannot be remapped in this way,
580 	 * so we should avoid them here.
581 	 */
582 	__map_memblock(pgdp, kernel_start, kernel_end,
583 		       PAGE_KERNEL, NO_CONT_MAPPINGS);
584 	memblock_clear_nomap(kernel_start, kernel_end - kernel_start);
585 
586 	/*
587 	 * Use page-level mappings here so that we can shrink the region
588 	 * in page granularity and put back unused memory to buddy system
589 	 * through /sys/kernel/kexec_crash_size interface.
590 	 */
591 #ifdef CONFIG_KEXEC_CORE
592 	if (crash_mem_map && !defer_reserve_crashkernel()) {
593 		if (crashk_res.end) {
594 			__map_memblock(pgdp, crashk_res.start,
595 				       crashk_res.end + 1,
596 				       PAGE_KERNEL,
597 				       NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS);
598 			memblock_clear_nomap(crashk_res.start,
599 					     resource_size(&crashk_res));
600 		}
601 	}
602 #endif
603 }
604 
605 void mark_rodata_ro(void)
606 {
607 	unsigned long section_size;
608 
609 	/*
610 	 * mark .rodata as read only. Use __init_begin rather than __end_rodata
611 	 * to cover NOTES and EXCEPTION_TABLE.
612 	 */
613 	section_size = (unsigned long)__init_begin - (unsigned long)__start_rodata;
614 	update_mapping_prot(__pa_symbol(__start_rodata), (unsigned long)__start_rodata,
615 			    section_size, PAGE_KERNEL_RO);
616 
617 	debug_checkwx();
618 }
619 
620 static void __init map_kernel_segment(pgd_t *pgdp, void *va_start, void *va_end,
621 				      pgprot_t prot, struct vm_struct *vma,
622 				      int flags, unsigned long vm_flags)
623 {
624 	phys_addr_t pa_start = __pa_symbol(va_start);
625 	unsigned long size = va_end - va_start;
626 
627 	BUG_ON(!PAGE_ALIGNED(pa_start));
628 	BUG_ON(!PAGE_ALIGNED(size));
629 
630 	__create_pgd_mapping(pgdp, pa_start, (unsigned long)va_start, size, prot,
631 			     early_pgtable_alloc, flags);
632 
633 	if (!(vm_flags & VM_NO_GUARD))
634 		size += PAGE_SIZE;
635 
636 	vma->addr	= va_start;
637 	vma->phys_addr	= pa_start;
638 	vma->size	= size;
639 	vma->flags	= VM_MAP | vm_flags;
640 	vma->caller	= __builtin_return_address(0);
641 
642 	vm_area_add_early(vma);
643 }
644 
645 static int __init parse_rodata(char *arg)
646 {
647 	int ret = strtobool(arg, &rodata_enabled);
648 	if (!ret) {
649 		rodata_full = false;
650 		return 0;
651 	}
652 
653 	/* permit 'full' in addition to boolean options */
654 	if (strcmp(arg, "full"))
655 		return -EINVAL;
656 
657 	rodata_enabled = true;
658 	rodata_full = true;
659 	return 0;
660 }
661 early_param("rodata", parse_rodata);
662 
663 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
664 static int __init map_entry_trampoline(void)
665 {
666 	int i;
667 
668 	pgprot_t prot = rodata_enabled ? PAGE_KERNEL_ROX : PAGE_KERNEL_EXEC;
669 	phys_addr_t pa_start = __pa_symbol(__entry_tramp_text_start);
670 
671 	/* The trampoline is always mapped and can therefore be global */
672 	pgprot_val(prot) &= ~PTE_NG;
673 
674 	/* Map only the text into the trampoline page table */
675 	memset(tramp_pg_dir, 0, PGD_SIZE);
676 	__create_pgd_mapping(tramp_pg_dir, pa_start, TRAMP_VALIAS,
677 			     entry_tramp_text_size(), prot,
678 			     __pgd_pgtable_alloc, NO_BLOCK_MAPPINGS);
679 
680 	/* Map both the text and data into the kernel page table */
681 	for (i = 0; i < DIV_ROUND_UP(entry_tramp_text_size(), PAGE_SIZE); i++)
682 		__set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
683 			     pa_start + i * PAGE_SIZE, prot);
684 
685 	if (IS_ENABLED(CONFIG_RELOCATABLE))
686 		__set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
687 			     pa_start + i * PAGE_SIZE, PAGE_KERNEL_RO);
688 
689 	return 0;
690 }
691 core_initcall(map_entry_trampoline);
692 #endif
693 
694 /*
695  * Open coded check for BTI, only for use to determine configuration
696  * for early mappings for before the cpufeature code has run.
697  */
698 static bool arm64_early_this_cpu_has_bti(void)
699 {
700 	u64 pfr1;
701 
702 	if (!IS_ENABLED(CONFIG_ARM64_BTI_KERNEL))
703 		return false;
704 
705 	pfr1 = __read_sysreg_by_encoding(SYS_ID_AA64PFR1_EL1);
706 	return cpuid_feature_extract_unsigned_field(pfr1,
707 						    ID_AA64PFR1_BT_SHIFT);
708 }
709 
710 /*
711  * Create fine-grained mappings for the kernel.
712  */
713 static void __init map_kernel(pgd_t *pgdp)
714 {
715 	static struct vm_struct vmlinux_text, vmlinux_rodata, vmlinux_inittext,
716 				vmlinux_initdata, vmlinux_data;
717 
718 	/*
719 	 * External debuggers may need to write directly to the text
720 	 * mapping to install SW breakpoints. Allow this (only) when
721 	 * explicitly requested with rodata=off.
722 	 */
723 	pgprot_t text_prot = rodata_enabled ? PAGE_KERNEL_ROX : PAGE_KERNEL_EXEC;
724 
725 	/*
726 	 * If we have a CPU that supports BTI and a kernel built for
727 	 * BTI then mark the kernel executable text as guarded pages
728 	 * now so we don't have to rewrite the page tables later.
729 	 */
730 	if (arm64_early_this_cpu_has_bti())
731 		text_prot = __pgprot_modify(text_prot, PTE_GP, PTE_GP);
732 
733 	/*
734 	 * Only rodata will be remapped with different permissions later on,
735 	 * all other segments are allowed to use contiguous mappings.
736 	 */
737 	map_kernel_segment(pgdp, _stext, _etext, text_prot, &vmlinux_text, 0,
738 			   VM_NO_GUARD);
739 	map_kernel_segment(pgdp, __start_rodata, __inittext_begin, PAGE_KERNEL,
740 			   &vmlinux_rodata, NO_CONT_MAPPINGS, VM_NO_GUARD);
741 	map_kernel_segment(pgdp, __inittext_begin, __inittext_end, text_prot,
742 			   &vmlinux_inittext, 0, VM_NO_GUARD);
743 	map_kernel_segment(pgdp, __initdata_begin, __initdata_end, PAGE_KERNEL,
744 			   &vmlinux_initdata, 0, VM_NO_GUARD);
745 	map_kernel_segment(pgdp, _data, _end, PAGE_KERNEL, &vmlinux_data, 0, 0);
746 
747 	if (!READ_ONCE(pgd_val(*pgd_offset_pgd(pgdp, FIXADDR_START)))) {
748 		/*
749 		 * The fixmap falls in a separate pgd to the kernel, and doesn't
750 		 * live in the carveout for the swapper_pg_dir. We can simply
751 		 * re-use the existing dir for the fixmap.
752 		 */
753 		set_pgd(pgd_offset_pgd(pgdp, FIXADDR_START),
754 			READ_ONCE(*pgd_offset_k(FIXADDR_START)));
755 	} else if (CONFIG_PGTABLE_LEVELS > 3) {
756 		pgd_t *bm_pgdp;
757 		p4d_t *bm_p4dp;
758 		pud_t *bm_pudp;
759 		/*
760 		 * The fixmap shares its top level pgd entry with the kernel
761 		 * mapping. This can really only occur when we are running
762 		 * with 16k/4 levels, so we can simply reuse the pud level
763 		 * entry instead.
764 		 */
765 		BUG_ON(!IS_ENABLED(CONFIG_ARM64_16K_PAGES));
766 		bm_pgdp = pgd_offset_pgd(pgdp, FIXADDR_START);
767 		bm_p4dp = p4d_offset(bm_pgdp, FIXADDR_START);
768 		bm_pudp = pud_set_fixmap_offset(bm_p4dp, FIXADDR_START);
769 		pud_populate(&init_mm, bm_pudp, lm_alias(bm_pmd));
770 		pud_clear_fixmap();
771 	} else {
772 		BUG();
773 	}
774 
775 	kasan_copy_shadow(pgdp);
776 }
777 
778 static void __init create_idmap(void)
779 {
780 	u64 start = __pa_symbol(__idmap_text_start);
781 	u64 size = __pa_symbol(__idmap_text_end) - start;
782 	pgd_t *pgd = idmap_pg_dir;
783 	u64 pgd_phys;
784 
785 	/* check if we need an additional level of translation */
786 	if (VA_BITS < 48 && idmap_t0sz < (64 - VA_BITS_MIN)) {
787 		pgd_phys = early_pgtable_alloc(PAGE_SHIFT);
788 		set_pgd(&idmap_pg_dir[start >> VA_BITS],
789 			__pgd(pgd_phys | P4D_TYPE_TABLE));
790 		pgd = __va(pgd_phys);
791 	}
792 	__create_pgd_mapping(pgd, start, start, size, PAGE_KERNEL_ROX,
793 			     early_pgtable_alloc, 0);
794 
795 	if (IS_ENABLED(CONFIG_UNMAP_KERNEL_AT_EL0)) {
796 		extern u32 __idmap_kpti_flag;
797 		u64 pa = __pa_symbol(&__idmap_kpti_flag);
798 
799 		/*
800 		 * The KPTI G-to-nG conversion code needs a read-write mapping
801 		 * of its synchronization flag in the ID map.
802 		 */
803 		__create_pgd_mapping(pgd, pa, pa, sizeof(u32), PAGE_KERNEL,
804 				     early_pgtable_alloc, 0);
805 	}
806 }
807 
808 void __init paging_init(void)
809 {
810 	pgd_t *pgdp = pgd_set_fixmap(__pa_symbol(swapper_pg_dir));
811 	extern pgd_t init_idmap_pg_dir[];
812 
813 	idmap_t0sz = 63UL - __fls(__pa_symbol(_end) | GENMASK(VA_BITS_MIN - 1, 0));
814 
815 	map_kernel(pgdp);
816 	map_mem(pgdp);
817 
818 	pgd_clear_fixmap();
819 
820 	cpu_replace_ttbr1(lm_alias(swapper_pg_dir), init_idmap_pg_dir);
821 	init_mm.pgd = swapper_pg_dir;
822 
823 	memblock_phys_free(__pa_symbol(init_pg_dir),
824 			   __pa_symbol(init_pg_end) - __pa_symbol(init_pg_dir));
825 
826 	memblock_allow_resize();
827 
828 	create_idmap();
829 }
830 
831 /*
832  * Check whether a kernel address is valid (derived from arch/x86/).
833  */
834 int kern_addr_valid(unsigned long addr)
835 {
836 	pgd_t *pgdp;
837 	p4d_t *p4dp;
838 	pud_t *pudp, pud;
839 	pmd_t *pmdp, pmd;
840 	pte_t *ptep, pte;
841 
842 	addr = arch_kasan_reset_tag(addr);
843 	if ((((long)addr) >> VA_BITS) != -1UL)
844 		return 0;
845 
846 	pgdp = pgd_offset_k(addr);
847 	if (pgd_none(READ_ONCE(*pgdp)))
848 		return 0;
849 
850 	p4dp = p4d_offset(pgdp, addr);
851 	if (p4d_none(READ_ONCE(*p4dp)))
852 		return 0;
853 
854 	pudp = pud_offset(p4dp, addr);
855 	pud = READ_ONCE(*pudp);
856 	if (pud_none(pud))
857 		return 0;
858 
859 	if (pud_sect(pud))
860 		return pfn_valid(pud_pfn(pud));
861 
862 	pmdp = pmd_offset(pudp, addr);
863 	pmd = READ_ONCE(*pmdp);
864 	if (pmd_none(pmd))
865 		return 0;
866 
867 	if (pmd_sect(pmd))
868 		return pfn_valid(pmd_pfn(pmd));
869 
870 	ptep = pte_offset_kernel(pmdp, addr);
871 	pte = READ_ONCE(*ptep);
872 	if (pte_none(pte))
873 		return 0;
874 
875 	return pfn_valid(pte_pfn(pte));
876 }
877 
878 #ifdef CONFIG_MEMORY_HOTPLUG
879 static void free_hotplug_page_range(struct page *page, size_t size,
880 				    struct vmem_altmap *altmap)
881 {
882 	if (altmap) {
883 		vmem_altmap_free(altmap, size >> PAGE_SHIFT);
884 	} else {
885 		WARN_ON(PageReserved(page));
886 		free_pages((unsigned long)page_address(page), get_order(size));
887 	}
888 }
889 
890 static void free_hotplug_pgtable_page(struct page *page)
891 {
892 	free_hotplug_page_range(page, PAGE_SIZE, NULL);
893 }
894 
895 static bool pgtable_range_aligned(unsigned long start, unsigned long end,
896 				  unsigned long floor, unsigned long ceiling,
897 				  unsigned long mask)
898 {
899 	start &= mask;
900 	if (start < floor)
901 		return false;
902 
903 	if (ceiling) {
904 		ceiling &= mask;
905 		if (!ceiling)
906 			return false;
907 	}
908 
909 	if (end - 1 > ceiling - 1)
910 		return false;
911 	return true;
912 }
913 
914 static void unmap_hotplug_pte_range(pmd_t *pmdp, unsigned long addr,
915 				    unsigned long end, bool free_mapped,
916 				    struct vmem_altmap *altmap)
917 {
918 	pte_t *ptep, pte;
919 
920 	do {
921 		ptep = pte_offset_kernel(pmdp, addr);
922 		pte = READ_ONCE(*ptep);
923 		if (pte_none(pte))
924 			continue;
925 
926 		WARN_ON(!pte_present(pte));
927 		pte_clear(&init_mm, addr, ptep);
928 		flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
929 		if (free_mapped)
930 			free_hotplug_page_range(pte_page(pte),
931 						PAGE_SIZE, altmap);
932 	} while (addr += PAGE_SIZE, addr < end);
933 }
934 
935 static void unmap_hotplug_pmd_range(pud_t *pudp, unsigned long addr,
936 				    unsigned long end, bool free_mapped,
937 				    struct vmem_altmap *altmap)
938 {
939 	unsigned long next;
940 	pmd_t *pmdp, pmd;
941 
942 	do {
943 		next = pmd_addr_end(addr, end);
944 		pmdp = pmd_offset(pudp, addr);
945 		pmd = READ_ONCE(*pmdp);
946 		if (pmd_none(pmd))
947 			continue;
948 
949 		WARN_ON(!pmd_present(pmd));
950 		if (pmd_sect(pmd)) {
951 			pmd_clear(pmdp);
952 
953 			/*
954 			 * One TLBI should be sufficient here as the PMD_SIZE
955 			 * range is mapped with a single block entry.
956 			 */
957 			flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
958 			if (free_mapped)
959 				free_hotplug_page_range(pmd_page(pmd),
960 							PMD_SIZE, altmap);
961 			continue;
962 		}
963 		WARN_ON(!pmd_table(pmd));
964 		unmap_hotplug_pte_range(pmdp, addr, next, free_mapped, altmap);
965 	} while (addr = next, addr < end);
966 }
967 
968 static void unmap_hotplug_pud_range(p4d_t *p4dp, unsigned long addr,
969 				    unsigned long end, bool free_mapped,
970 				    struct vmem_altmap *altmap)
971 {
972 	unsigned long next;
973 	pud_t *pudp, pud;
974 
975 	do {
976 		next = pud_addr_end(addr, end);
977 		pudp = pud_offset(p4dp, addr);
978 		pud = READ_ONCE(*pudp);
979 		if (pud_none(pud))
980 			continue;
981 
982 		WARN_ON(!pud_present(pud));
983 		if (pud_sect(pud)) {
984 			pud_clear(pudp);
985 
986 			/*
987 			 * One TLBI should be sufficient here as the PUD_SIZE
988 			 * range is mapped with a single block entry.
989 			 */
990 			flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
991 			if (free_mapped)
992 				free_hotplug_page_range(pud_page(pud),
993 							PUD_SIZE, altmap);
994 			continue;
995 		}
996 		WARN_ON(!pud_table(pud));
997 		unmap_hotplug_pmd_range(pudp, addr, next, free_mapped, altmap);
998 	} while (addr = next, addr < end);
999 }
1000 
1001 static void unmap_hotplug_p4d_range(pgd_t *pgdp, unsigned long addr,
1002 				    unsigned long end, bool free_mapped,
1003 				    struct vmem_altmap *altmap)
1004 {
1005 	unsigned long next;
1006 	p4d_t *p4dp, p4d;
1007 
1008 	do {
1009 		next = p4d_addr_end(addr, end);
1010 		p4dp = p4d_offset(pgdp, addr);
1011 		p4d = READ_ONCE(*p4dp);
1012 		if (p4d_none(p4d))
1013 			continue;
1014 
1015 		WARN_ON(!p4d_present(p4d));
1016 		unmap_hotplug_pud_range(p4dp, addr, next, free_mapped, altmap);
1017 	} while (addr = next, addr < end);
1018 }
1019 
1020 static void unmap_hotplug_range(unsigned long addr, unsigned long end,
1021 				bool free_mapped, struct vmem_altmap *altmap)
1022 {
1023 	unsigned long next;
1024 	pgd_t *pgdp, pgd;
1025 
1026 	/*
1027 	 * altmap can only be used as vmemmap mapping backing memory.
1028 	 * In case the backing memory itself is not being freed, then
1029 	 * altmap is irrelevant. Warn about this inconsistency when
1030 	 * encountered.
1031 	 */
1032 	WARN_ON(!free_mapped && altmap);
1033 
1034 	do {
1035 		next = pgd_addr_end(addr, end);
1036 		pgdp = pgd_offset_k(addr);
1037 		pgd = READ_ONCE(*pgdp);
1038 		if (pgd_none(pgd))
1039 			continue;
1040 
1041 		WARN_ON(!pgd_present(pgd));
1042 		unmap_hotplug_p4d_range(pgdp, addr, next, free_mapped, altmap);
1043 	} while (addr = next, addr < end);
1044 }
1045 
1046 static void free_empty_pte_table(pmd_t *pmdp, unsigned long addr,
1047 				 unsigned long end, unsigned long floor,
1048 				 unsigned long ceiling)
1049 {
1050 	pte_t *ptep, pte;
1051 	unsigned long i, start = addr;
1052 
1053 	do {
1054 		ptep = pte_offset_kernel(pmdp, addr);
1055 		pte = READ_ONCE(*ptep);
1056 
1057 		/*
1058 		 * This is just a sanity check here which verifies that
1059 		 * pte clearing has been done by earlier unmap loops.
1060 		 */
1061 		WARN_ON(!pte_none(pte));
1062 	} while (addr += PAGE_SIZE, addr < end);
1063 
1064 	if (!pgtable_range_aligned(start, end, floor, ceiling, PMD_MASK))
1065 		return;
1066 
1067 	/*
1068 	 * Check whether we can free the pte page if the rest of the
1069 	 * entries are empty. Overlap with other regions have been
1070 	 * handled by the floor/ceiling check.
1071 	 */
1072 	ptep = pte_offset_kernel(pmdp, 0UL);
1073 	for (i = 0; i < PTRS_PER_PTE; i++) {
1074 		if (!pte_none(READ_ONCE(ptep[i])))
1075 			return;
1076 	}
1077 
1078 	pmd_clear(pmdp);
1079 	__flush_tlb_kernel_pgtable(start);
1080 	free_hotplug_pgtable_page(virt_to_page(ptep));
1081 }
1082 
1083 static void free_empty_pmd_table(pud_t *pudp, unsigned long addr,
1084 				 unsigned long end, unsigned long floor,
1085 				 unsigned long ceiling)
1086 {
1087 	pmd_t *pmdp, pmd;
1088 	unsigned long i, next, start = addr;
1089 
1090 	do {
1091 		next = pmd_addr_end(addr, end);
1092 		pmdp = pmd_offset(pudp, addr);
1093 		pmd = READ_ONCE(*pmdp);
1094 		if (pmd_none(pmd))
1095 			continue;
1096 
1097 		WARN_ON(!pmd_present(pmd) || !pmd_table(pmd) || pmd_sect(pmd));
1098 		free_empty_pte_table(pmdp, addr, next, floor, ceiling);
1099 	} while (addr = next, addr < end);
1100 
1101 	if (CONFIG_PGTABLE_LEVELS <= 2)
1102 		return;
1103 
1104 	if (!pgtable_range_aligned(start, end, floor, ceiling, PUD_MASK))
1105 		return;
1106 
1107 	/*
1108 	 * Check whether we can free the pmd page if the rest of the
1109 	 * entries are empty. Overlap with other regions have been
1110 	 * handled by the floor/ceiling check.
1111 	 */
1112 	pmdp = pmd_offset(pudp, 0UL);
1113 	for (i = 0; i < PTRS_PER_PMD; i++) {
1114 		if (!pmd_none(READ_ONCE(pmdp[i])))
1115 			return;
1116 	}
1117 
1118 	pud_clear(pudp);
1119 	__flush_tlb_kernel_pgtable(start);
1120 	free_hotplug_pgtable_page(virt_to_page(pmdp));
1121 }
1122 
1123 static void free_empty_pud_table(p4d_t *p4dp, unsigned long addr,
1124 				 unsigned long end, unsigned long floor,
1125 				 unsigned long ceiling)
1126 {
1127 	pud_t *pudp, pud;
1128 	unsigned long i, next, start = addr;
1129 
1130 	do {
1131 		next = pud_addr_end(addr, end);
1132 		pudp = pud_offset(p4dp, addr);
1133 		pud = READ_ONCE(*pudp);
1134 		if (pud_none(pud))
1135 			continue;
1136 
1137 		WARN_ON(!pud_present(pud) || !pud_table(pud) || pud_sect(pud));
1138 		free_empty_pmd_table(pudp, addr, next, floor, ceiling);
1139 	} while (addr = next, addr < end);
1140 
1141 	if (CONFIG_PGTABLE_LEVELS <= 3)
1142 		return;
1143 
1144 	if (!pgtable_range_aligned(start, end, floor, ceiling, PGDIR_MASK))
1145 		return;
1146 
1147 	/*
1148 	 * Check whether we can free the pud page if the rest of the
1149 	 * entries are empty. Overlap with other regions have been
1150 	 * handled by the floor/ceiling check.
1151 	 */
1152 	pudp = pud_offset(p4dp, 0UL);
1153 	for (i = 0; i < PTRS_PER_PUD; i++) {
1154 		if (!pud_none(READ_ONCE(pudp[i])))
1155 			return;
1156 	}
1157 
1158 	p4d_clear(p4dp);
1159 	__flush_tlb_kernel_pgtable(start);
1160 	free_hotplug_pgtable_page(virt_to_page(pudp));
1161 }
1162 
1163 static void free_empty_p4d_table(pgd_t *pgdp, unsigned long addr,
1164 				 unsigned long end, unsigned long floor,
1165 				 unsigned long ceiling)
1166 {
1167 	unsigned long next;
1168 	p4d_t *p4dp, p4d;
1169 
1170 	do {
1171 		next = p4d_addr_end(addr, end);
1172 		p4dp = p4d_offset(pgdp, addr);
1173 		p4d = READ_ONCE(*p4dp);
1174 		if (p4d_none(p4d))
1175 			continue;
1176 
1177 		WARN_ON(!p4d_present(p4d));
1178 		free_empty_pud_table(p4dp, addr, next, floor, ceiling);
1179 	} while (addr = next, addr < end);
1180 }
1181 
1182 static void free_empty_tables(unsigned long addr, unsigned long end,
1183 			      unsigned long floor, unsigned long ceiling)
1184 {
1185 	unsigned long next;
1186 	pgd_t *pgdp, pgd;
1187 
1188 	do {
1189 		next = pgd_addr_end(addr, end);
1190 		pgdp = pgd_offset_k(addr);
1191 		pgd = READ_ONCE(*pgdp);
1192 		if (pgd_none(pgd))
1193 			continue;
1194 
1195 		WARN_ON(!pgd_present(pgd));
1196 		free_empty_p4d_table(pgdp, addr, next, floor, ceiling);
1197 	} while (addr = next, addr < end);
1198 }
1199 #endif
1200 
1201 #if !ARM64_KERNEL_USES_PMD_MAPS
1202 int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
1203 		struct vmem_altmap *altmap)
1204 {
1205 	WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1206 	return vmemmap_populate_basepages(start, end, node, altmap);
1207 }
1208 #else	/* !ARM64_KERNEL_USES_PMD_MAPS */
1209 int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
1210 		struct vmem_altmap *altmap)
1211 {
1212 	unsigned long addr = start;
1213 	unsigned long next;
1214 	pgd_t *pgdp;
1215 	p4d_t *p4dp;
1216 	pud_t *pudp;
1217 	pmd_t *pmdp;
1218 
1219 	WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1220 	do {
1221 		next = pmd_addr_end(addr, end);
1222 
1223 		pgdp = vmemmap_pgd_populate(addr, node);
1224 		if (!pgdp)
1225 			return -ENOMEM;
1226 
1227 		p4dp = vmemmap_p4d_populate(pgdp, addr, node);
1228 		if (!p4dp)
1229 			return -ENOMEM;
1230 
1231 		pudp = vmemmap_pud_populate(p4dp, addr, node);
1232 		if (!pudp)
1233 			return -ENOMEM;
1234 
1235 		pmdp = pmd_offset(pudp, addr);
1236 		if (pmd_none(READ_ONCE(*pmdp))) {
1237 			void *p = NULL;
1238 
1239 			p = vmemmap_alloc_block_buf(PMD_SIZE, node, altmap);
1240 			if (!p) {
1241 				if (vmemmap_populate_basepages(addr, next, node, altmap))
1242 					return -ENOMEM;
1243 				continue;
1244 			}
1245 
1246 			pmd_set_huge(pmdp, __pa(p), __pgprot(PROT_SECT_NORMAL));
1247 		} else
1248 			vmemmap_verify((pte_t *)pmdp, node, addr, next);
1249 	} while (addr = next, addr != end);
1250 
1251 	return 0;
1252 }
1253 #endif	/* !ARM64_KERNEL_USES_PMD_MAPS */
1254 
1255 #ifdef CONFIG_MEMORY_HOTPLUG
1256 void vmemmap_free(unsigned long start, unsigned long end,
1257 		struct vmem_altmap *altmap)
1258 {
1259 	WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1260 
1261 	unmap_hotplug_range(start, end, true, altmap);
1262 	free_empty_tables(start, end, VMEMMAP_START, VMEMMAP_END);
1263 }
1264 #endif /* CONFIG_MEMORY_HOTPLUG */
1265 
1266 static inline pud_t *fixmap_pud(unsigned long addr)
1267 {
1268 	pgd_t *pgdp = pgd_offset_k(addr);
1269 	p4d_t *p4dp = p4d_offset(pgdp, addr);
1270 	p4d_t p4d = READ_ONCE(*p4dp);
1271 
1272 	BUG_ON(p4d_none(p4d) || p4d_bad(p4d));
1273 
1274 	return pud_offset_kimg(p4dp, addr);
1275 }
1276 
1277 static inline pmd_t *fixmap_pmd(unsigned long addr)
1278 {
1279 	pud_t *pudp = fixmap_pud(addr);
1280 	pud_t pud = READ_ONCE(*pudp);
1281 
1282 	BUG_ON(pud_none(pud) || pud_bad(pud));
1283 
1284 	return pmd_offset_kimg(pudp, addr);
1285 }
1286 
1287 static inline pte_t *fixmap_pte(unsigned long addr)
1288 {
1289 	return &bm_pte[pte_index(addr)];
1290 }
1291 
1292 /*
1293  * The p*d_populate functions call virt_to_phys implicitly so they can't be used
1294  * directly on kernel symbols (bm_p*d). This function is called too early to use
1295  * lm_alias so __p*d_populate functions must be used to populate with the
1296  * physical address from __pa_symbol.
1297  */
1298 void __init early_fixmap_init(void)
1299 {
1300 	pgd_t *pgdp;
1301 	p4d_t *p4dp, p4d;
1302 	pud_t *pudp;
1303 	pmd_t *pmdp;
1304 	unsigned long addr = FIXADDR_START;
1305 
1306 	pgdp = pgd_offset_k(addr);
1307 	p4dp = p4d_offset(pgdp, addr);
1308 	p4d = READ_ONCE(*p4dp);
1309 	if (CONFIG_PGTABLE_LEVELS > 3 &&
1310 	    !(p4d_none(p4d) || p4d_page_paddr(p4d) == __pa_symbol(bm_pud))) {
1311 		/*
1312 		 * We only end up here if the kernel mapping and the fixmap
1313 		 * share the top level pgd entry, which should only happen on
1314 		 * 16k/4 levels configurations.
1315 		 */
1316 		BUG_ON(!IS_ENABLED(CONFIG_ARM64_16K_PAGES));
1317 		pudp = pud_offset_kimg(p4dp, addr);
1318 	} else {
1319 		if (p4d_none(p4d))
1320 			__p4d_populate(p4dp, __pa_symbol(bm_pud), P4D_TYPE_TABLE);
1321 		pudp = fixmap_pud(addr);
1322 	}
1323 	if (pud_none(READ_ONCE(*pudp)))
1324 		__pud_populate(pudp, __pa_symbol(bm_pmd), PUD_TYPE_TABLE);
1325 	pmdp = fixmap_pmd(addr);
1326 	__pmd_populate(pmdp, __pa_symbol(bm_pte), PMD_TYPE_TABLE);
1327 
1328 	/*
1329 	 * The boot-ioremap range spans multiple pmds, for which
1330 	 * we are not prepared:
1331 	 */
1332 	BUILD_BUG_ON((__fix_to_virt(FIX_BTMAP_BEGIN) >> PMD_SHIFT)
1333 		     != (__fix_to_virt(FIX_BTMAP_END) >> PMD_SHIFT));
1334 
1335 	if ((pmdp != fixmap_pmd(fix_to_virt(FIX_BTMAP_BEGIN)))
1336 	     || pmdp != fixmap_pmd(fix_to_virt(FIX_BTMAP_END))) {
1337 		WARN_ON(1);
1338 		pr_warn("pmdp %p != %p, %p\n",
1339 			pmdp, fixmap_pmd(fix_to_virt(FIX_BTMAP_BEGIN)),
1340 			fixmap_pmd(fix_to_virt(FIX_BTMAP_END)));
1341 		pr_warn("fix_to_virt(FIX_BTMAP_BEGIN): %08lx\n",
1342 			fix_to_virt(FIX_BTMAP_BEGIN));
1343 		pr_warn("fix_to_virt(FIX_BTMAP_END):   %08lx\n",
1344 			fix_to_virt(FIX_BTMAP_END));
1345 
1346 		pr_warn("FIX_BTMAP_END:       %d\n", FIX_BTMAP_END);
1347 		pr_warn("FIX_BTMAP_BEGIN:     %d\n", FIX_BTMAP_BEGIN);
1348 	}
1349 }
1350 
1351 /*
1352  * Unusually, this is also called in IRQ context (ghes_iounmap_irq) so if we
1353  * ever need to use IPIs for TLB broadcasting, then we're in trouble here.
1354  */
1355 void __set_fixmap(enum fixed_addresses idx,
1356 			       phys_addr_t phys, pgprot_t flags)
1357 {
1358 	unsigned long addr = __fix_to_virt(idx);
1359 	pte_t *ptep;
1360 
1361 	BUG_ON(idx <= FIX_HOLE || idx >= __end_of_fixed_addresses);
1362 
1363 	ptep = fixmap_pte(addr);
1364 
1365 	if (pgprot_val(flags)) {
1366 		set_pte(ptep, pfn_pte(phys >> PAGE_SHIFT, flags));
1367 	} else {
1368 		pte_clear(&init_mm, addr, ptep);
1369 		flush_tlb_kernel_range(addr, addr+PAGE_SIZE);
1370 	}
1371 }
1372 
1373 void *__init fixmap_remap_fdt(phys_addr_t dt_phys, int *size, pgprot_t prot)
1374 {
1375 	const u64 dt_virt_base = __fix_to_virt(FIX_FDT);
1376 	int offset;
1377 	void *dt_virt;
1378 
1379 	/*
1380 	 * Check whether the physical FDT address is set and meets the minimum
1381 	 * alignment requirement. Since we are relying on MIN_FDT_ALIGN to be
1382 	 * at least 8 bytes so that we can always access the magic and size
1383 	 * fields of the FDT header after mapping the first chunk, double check
1384 	 * here if that is indeed the case.
1385 	 */
1386 	BUILD_BUG_ON(MIN_FDT_ALIGN < 8);
1387 	if (!dt_phys || dt_phys % MIN_FDT_ALIGN)
1388 		return NULL;
1389 
1390 	/*
1391 	 * Make sure that the FDT region can be mapped without the need to
1392 	 * allocate additional translation table pages, so that it is safe
1393 	 * to call create_mapping_noalloc() this early.
1394 	 *
1395 	 * On 64k pages, the FDT will be mapped using PTEs, so we need to
1396 	 * be in the same PMD as the rest of the fixmap.
1397 	 * On 4k pages, we'll use section mappings for the FDT so we only
1398 	 * have to be in the same PUD.
1399 	 */
1400 	BUILD_BUG_ON(dt_virt_base % SZ_2M);
1401 
1402 	BUILD_BUG_ON(__fix_to_virt(FIX_FDT_END) >> SWAPPER_TABLE_SHIFT !=
1403 		     __fix_to_virt(FIX_BTMAP_BEGIN) >> SWAPPER_TABLE_SHIFT);
1404 
1405 	offset = dt_phys % SWAPPER_BLOCK_SIZE;
1406 	dt_virt = (void *)dt_virt_base + offset;
1407 
1408 	/* map the first chunk so we can read the size from the header */
1409 	create_mapping_noalloc(round_down(dt_phys, SWAPPER_BLOCK_SIZE),
1410 			dt_virt_base, SWAPPER_BLOCK_SIZE, prot);
1411 
1412 	if (fdt_magic(dt_virt) != FDT_MAGIC)
1413 		return NULL;
1414 
1415 	*size = fdt_totalsize(dt_virt);
1416 	if (*size > MAX_FDT_SIZE)
1417 		return NULL;
1418 
1419 	if (offset + *size > SWAPPER_BLOCK_SIZE)
1420 		create_mapping_noalloc(round_down(dt_phys, SWAPPER_BLOCK_SIZE), dt_virt_base,
1421 			       round_up(offset + *size, SWAPPER_BLOCK_SIZE), prot);
1422 
1423 	return dt_virt;
1424 }
1425 
1426 int pud_set_huge(pud_t *pudp, phys_addr_t phys, pgprot_t prot)
1427 {
1428 	pud_t new_pud = pfn_pud(__phys_to_pfn(phys), mk_pud_sect_prot(prot));
1429 
1430 	/* Only allow permission changes for now */
1431 	if (!pgattr_change_is_safe(READ_ONCE(pud_val(*pudp)),
1432 				   pud_val(new_pud)))
1433 		return 0;
1434 
1435 	VM_BUG_ON(phys & ~PUD_MASK);
1436 	set_pud(pudp, new_pud);
1437 	return 1;
1438 }
1439 
1440 int pmd_set_huge(pmd_t *pmdp, phys_addr_t phys, pgprot_t prot)
1441 {
1442 	pmd_t new_pmd = pfn_pmd(__phys_to_pfn(phys), mk_pmd_sect_prot(prot));
1443 
1444 	/* Only allow permission changes for now */
1445 	if (!pgattr_change_is_safe(READ_ONCE(pmd_val(*pmdp)),
1446 				   pmd_val(new_pmd)))
1447 		return 0;
1448 
1449 	VM_BUG_ON(phys & ~PMD_MASK);
1450 	set_pmd(pmdp, new_pmd);
1451 	return 1;
1452 }
1453 
1454 int pud_clear_huge(pud_t *pudp)
1455 {
1456 	if (!pud_sect(READ_ONCE(*pudp)))
1457 		return 0;
1458 	pud_clear(pudp);
1459 	return 1;
1460 }
1461 
1462 int pmd_clear_huge(pmd_t *pmdp)
1463 {
1464 	if (!pmd_sect(READ_ONCE(*pmdp)))
1465 		return 0;
1466 	pmd_clear(pmdp);
1467 	return 1;
1468 }
1469 
1470 int pmd_free_pte_page(pmd_t *pmdp, unsigned long addr)
1471 {
1472 	pte_t *table;
1473 	pmd_t pmd;
1474 
1475 	pmd = READ_ONCE(*pmdp);
1476 
1477 	if (!pmd_table(pmd)) {
1478 		VM_WARN_ON(1);
1479 		return 1;
1480 	}
1481 
1482 	table = pte_offset_kernel(pmdp, addr);
1483 	pmd_clear(pmdp);
1484 	__flush_tlb_kernel_pgtable(addr);
1485 	pte_free_kernel(NULL, table);
1486 	return 1;
1487 }
1488 
1489 int pud_free_pmd_page(pud_t *pudp, unsigned long addr)
1490 {
1491 	pmd_t *table;
1492 	pmd_t *pmdp;
1493 	pud_t pud;
1494 	unsigned long next, end;
1495 
1496 	pud = READ_ONCE(*pudp);
1497 
1498 	if (!pud_table(pud)) {
1499 		VM_WARN_ON(1);
1500 		return 1;
1501 	}
1502 
1503 	table = pmd_offset(pudp, addr);
1504 	pmdp = table;
1505 	next = addr;
1506 	end = addr + PUD_SIZE;
1507 	do {
1508 		pmd_free_pte_page(pmdp, next);
1509 	} while (pmdp++, next += PMD_SIZE, next != end);
1510 
1511 	pud_clear(pudp);
1512 	__flush_tlb_kernel_pgtable(addr);
1513 	pmd_free(NULL, table);
1514 	return 1;
1515 }
1516 
1517 #ifdef CONFIG_MEMORY_HOTPLUG
1518 static void __remove_pgd_mapping(pgd_t *pgdir, unsigned long start, u64 size)
1519 {
1520 	unsigned long end = start + size;
1521 
1522 	WARN_ON(pgdir != init_mm.pgd);
1523 	WARN_ON((start < PAGE_OFFSET) || (end > PAGE_END));
1524 
1525 	unmap_hotplug_range(start, end, false, NULL);
1526 	free_empty_tables(start, end, PAGE_OFFSET, PAGE_END);
1527 }
1528 
1529 struct range arch_get_mappable_range(void)
1530 {
1531 	struct range mhp_range;
1532 	u64 start_linear_pa = __pa(_PAGE_OFFSET(vabits_actual));
1533 	u64 end_linear_pa = __pa(PAGE_END - 1);
1534 
1535 	if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) {
1536 		/*
1537 		 * Check for a wrap, it is possible because of randomized linear
1538 		 * mapping the start physical address is actually bigger than
1539 		 * the end physical address. In this case set start to zero
1540 		 * because [0, end_linear_pa] range must still be able to cover
1541 		 * all addressable physical addresses.
1542 		 */
1543 		if (start_linear_pa > end_linear_pa)
1544 			start_linear_pa = 0;
1545 	}
1546 
1547 	WARN_ON(start_linear_pa > end_linear_pa);
1548 
1549 	/*
1550 	 * Linear mapping region is the range [PAGE_OFFSET..(PAGE_END - 1)]
1551 	 * accommodating both its ends but excluding PAGE_END. Max physical
1552 	 * range which can be mapped inside this linear mapping range, must
1553 	 * also be derived from its end points.
1554 	 */
1555 	mhp_range.start = start_linear_pa;
1556 	mhp_range.end =  end_linear_pa;
1557 
1558 	return mhp_range;
1559 }
1560 
1561 int arch_add_memory(int nid, u64 start, u64 size,
1562 		    struct mhp_params *params)
1563 {
1564 	int ret, flags = NO_EXEC_MAPPINGS;
1565 
1566 	VM_BUG_ON(!mhp_range_allowed(start, size, true));
1567 
1568 	/*
1569 	 * KFENCE requires linear map to be mapped at page granularity, so that
1570 	 * it is possible to protect/unprotect single pages in the KFENCE pool.
1571 	 */
1572 	if (can_set_direct_map() || IS_ENABLED(CONFIG_KFENCE))
1573 		flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
1574 
1575 	__create_pgd_mapping(swapper_pg_dir, start, __phys_to_virt(start),
1576 			     size, params->pgprot, __pgd_pgtable_alloc,
1577 			     flags);
1578 
1579 	memblock_clear_nomap(start, size);
1580 
1581 	ret = __add_pages(nid, start >> PAGE_SHIFT, size >> PAGE_SHIFT,
1582 			   params);
1583 	if (ret)
1584 		__remove_pgd_mapping(swapper_pg_dir,
1585 				     __phys_to_virt(start), size);
1586 	else {
1587 		max_pfn = PFN_UP(start + size);
1588 		max_low_pfn = max_pfn;
1589 	}
1590 
1591 	return ret;
1592 }
1593 
1594 void arch_remove_memory(u64 start, u64 size, struct vmem_altmap *altmap)
1595 {
1596 	unsigned long start_pfn = start >> PAGE_SHIFT;
1597 	unsigned long nr_pages = size >> PAGE_SHIFT;
1598 
1599 	__remove_pages(start_pfn, nr_pages, altmap);
1600 	__remove_pgd_mapping(swapper_pg_dir, __phys_to_virt(start), size);
1601 }
1602 
1603 /*
1604  * This memory hotplug notifier helps prevent boot memory from being
1605  * inadvertently removed as it blocks pfn range offlining process in
1606  * __offline_pages(). Hence this prevents both offlining as well as
1607  * removal process for boot memory which is initially always online.
1608  * In future if and when boot memory could be removed, this notifier
1609  * should be dropped and free_hotplug_page_range() should handle any
1610  * reserved pages allocated during boot.
1611  */
1612 static int prevent_bootmem_remove_notifier(struct notifier_block *nb,
1613 					   unsigned long action, void *data)
1614 {
1615 	struct mem_section *ms;
1616 	struct memory_notify *arg = data;
1617 	unsigned long end_pfn = arg->start_pfn + arg->nr_pages;
1618 	unsigned long pfn = arg->start_pfn;
1619 
1620 	if ((action != MEM_GOING_OFFLINE) && (action != MEM_OFFLINE))
1621 		return NOTIFY_OK;
1622 
1623 	for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
1624 		unsigned long start = PFN_PHYS(pfn);
1625 		unsigned long end = start + (1UL << PA_SECTION_SHIFT);
1626 
1627 		ms = __pfn_to_section(pfn);
1628 		if (!early_section(ms))
1629 			continue;
1630 
1631 		if (action == MEM_GOING_OFFLINE) {
1632 			/*
1633 			 * Boot memory removal is not supported. Prevent
1634 			 * it via blocking any attempted offline request
1635 			 * for the boot memory and just report it.
1636 			 */
1637 			pr_warn("Boot memory [%lx %lx] offlining attempted\n", start, end);
1638 			return NOTIFY_BAD;
1639 		} else if (action == MEM_OFFLINE) {
1640 			/*
1641 			 * This should have never happened. Boot memory
1642 			 * offlining should have been prevented by this
1643 			 * very notifier. Probably some memory removal
1644 			 * procedure might have changed which would then
1645 			 * require further debug.
1646 			 */
1647 			pr_err("Boot memory [%lx %lx] offlined\n", start, end);
1648 
1649 			/*
1650 			 * Core memory hotplug does not process a return
1651 			 * code from the notifier for MEM_OFFLINE events.
1652 			 * The error condition has been reported. Return
1653 			 * from here as if ignored.
1654 			 */
1655 			return NOTIFY_DONE;
1656 		}
1657 	}
1658 	return NOTIFY_OK;
1659 }
1660 
1661 static struct notifier_block prevent_bootmem_remove_nb = {
1662 	.notifier_call = prevent_bootmem_remove_notifier,
1663 };
1664 
1665 /*
1666  * This ensures that boot memory sections on the platform are online
1667  * from early boot. Memory sections could not be prevented from being
1668  * offlined, unless for some reason they are not online to begin with.
1669  * This helps validate the basic assumption on which the above memory
1670  * event notifier works to prevent boot memory section offlining and
1671  * its possible removal.
1672  */
1673 static void validate_bootmem_online(void)
1674 {
1675 	phys_addr_t start, end, addr;
1676 	struct mem_section *ms;
1677 	u64 i;
1678 
1679 	/*
1680 	 * Scanning across all memblock might be expensive
1681 	 * on some big memory systems. Hence enable this
1682 	 * validation only with DEBUG_VM.
1683 	 */
1684 	if (!IS_ENABLED(CONFIG_DEBUG_VM))
1685 		return;
1686 
1687 	for_each_mem_range(i, &start, &end) {
1688 		for (addr = start; addr < end; addr += (1UL << PA_SECTION_SHIFT)) {
1689 			ms = __pfn_to_section(PHYS_PFN(addr));
1690 
1691 			/*
1692 			 * All memory ranges in the system at this point
1693 			 * should have been marked as early sections.
1694 			 */
1695 			WARN_ON(!early_section(ms));
1696 
1697 			/*
1698 			 * Memory notifier mechanism here to prevent boot
1699 			 * memory offlining depends on the fact that each
1700 			 * early section memory on the system is initially
1701 			 * online. Otherwise a given memory section which
1702 			 * is already offline will be overlooked and can
1703 			 * be removed completely. Call out such sections.
1704 			 */
1705 			if (!online_section(ms))
1706 				pr_err("Boot memory [%llx %llx] is offline, can be removed\n",
1707 					addr, addr + (1UL << PA_SECTION_SHIFT));
1708 		}
1709 	}
1710 }
1711 
1712 static int __init prevent_bootmem_remove_init(void)
1713 {
1714 	int ret = 0;
1715 
1716 	if (!IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
1717 		return ret;
1718 
1719 	validate_bootmem_online();
1720 	ret = register_memory_notifier(&prevent_bootmem_remove_nb);
1721 	if (ret)
1722 		pr_err("%s: Notifier registration failed %d\n", __func__, ret);
1723 
1724 	return ret;
1725 }
1726 early_initcall(prevent_bootmem_remove_init);
1727 #endif
1728