xref: /linux/arch/x86/kernel/head64.c (revision 6a4aee277740d04ac0fd54cfa17cc28261932ddc)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  prepare to run common code
4  *
5  *  Copyright (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
6  */
7 
8 #define DISABLE_BRANCH_PROFILING
9 
10 /* cpu_feature_enabled() cannot be used this early */
11 #define USE_EARLY_PGTABLE_L5
12 
13 #include <linux/init.h>
14 #include <linux/linkage.h>
15 #include <linux/types.h>
16 #include <linux/kernel.h>
17 #include <linux/string.h>
18 #include <linux/percpu.h>
19 #include <linux/start_kernel.h>
20 #include <linux/io.h>
21 #include <linux/memblock.h>
22 #include <linux/cc_platform.h>
23 #include <linux/pgtable.h>
24 
25 #include <asm/asm.h>
26 #include <asm/page_64.h>
27 #include <asm/processor.h>
28 #include <asm/proto.h>
29 #include <asm/smp.h>
30 #include <asm/setup.h>
31 #include <asm/desc.h>
32 #include <asm/tlbflush.h>
33 #include <asm/sections.h>
34 #include <asm/kdebug.h>
35 #include <asm/e820/api.h>
36 #include <asm/bios_ebda.h>
37 #include <asm/bootparam_utils.h>
38 #include <asm/microcode.h>
39 #include <asm/kasan.h>
40 #include <asm/fixmap.h>
41 #include <asm/realmode.h>
42 #include <asm/extable.h>
43 #include <asm/trapnr.h>
44 #include <asm/sev.h>
45 #include <asm/tdx.h>
46 #include <asm/init.h>
47 
48 /*
49  * Manage page tables very early on.
50  */
51 extern pmd_t early_dynamic_pgts[EARLY_DYNAMIC_PAGE_TABLES][PTRS_PER_PMD];
52 static unsigned int __initdata next_early_pgt;
53 pmdval_t early_pmd_flags = __PAGE_KERNEL_LARGE & ~(_PAGE_GLOBAL | _PAGE_NX);
54 
55 #ifdef CONFIG_X86_5LEVEL
56 unsigned int __pgtable_l5_enabled __ro_after_init;
57 unsigned int pgdir_shift __ro_after_init = 39;
58 EXPORT_SYMBOL(pgdir_shift);
59 unsigned int ptrs_per_p4d __ro_after_init = 1;
60 EXPORT_SYMBOL(ptrs_per_p4d);
61 #endif
62 
63 #ifdef CONFIG_DYNAMIC_MEMORY_LAYOUT
64 unsigned long page_offset_base __ro_after_init = __PAGE_OFFSET_BASE_L4;
65 EXPORT_SYMBOL(page_offset_base);
66 unsigned long vmalloc_base __ro_after_init = __VMALLOC_BASE_L4;
67 EXPORT_SYMBOL(vmalloc_base);
68 unsigned long vmemmap_base __ro_after_init = __VMEMMAP_BASE_L4;
69 EXPORT_SYMBOL(vmemmap_base);
70 #endif
71 
72 static inline bool check_la57_support(void)
73 {
74 	if (!IS_ENABLED(CONFIG_X86_5LEVEL))
75 		return false;
76 
77 	/*
78 	 * 5-level paging is detected and enabled at kernel decompression
79 	 * stage. Only check if it has been enabled there.
80 	 */
81 	if (!(native_read_cr4() & X86_CR4_LA57))
82 		return false;
83 
84 	return true;
85 }
86 
87 static unsigned long __head sme_postprocess_startup(struct boot_params *bp, pmdval_t *pmd)
88 {
89 	unsigned long vaddr, vaddr_end;
90 	int i;
91 
92 	/* Encrypt the kernel and related (if SME is active) */
93 	sme_encrypt_kernel(bp);
94 
95 	/*
96 	 * Clear the memory encryption mask from the .bss..decrypted section.
97 	 * The bss section will be memset to zero later in the initialization so
98 	 * there is no need to zero it after changing the memory encryption
99 	 * attribute.
100 	 */
101 	if (sme_get_me_mask()) {
102 		vaddr = (unsigned long)__start_bss_decrypted;
103 		vaddr_end = (unsigned long)__end_bss_decrypted;
104 
105 		for (; vaddr < vaddr_end; vaddr += PMD_SIZE) {
106 			/*
107 			 * On SNP, transition the page to shared in the RMP table so that
108 			 * it is consistent with the page table attribute change.
109 			 *
110 			 * __start_bss_decrypted has a virtual address in the high range
111 			 * mapping (kernel .text). PVALIDATE, by way of
112 			 * early_snp_set_memory_shared(), requires a valid virtual
113 			 * address but the kernel is currently running off of the identity
114 			 * mapping so use __pa() to get a *currently* valid virtual address.
115 			 */
116 			early_snp_set_memory_shared(__pa(vaddr), __pa(vaddr), PTRS_PER_PMD);
117 
118 			i = pmd_index(vaddr);
119 			pmd[i] -= sme_get_me_mask();
120 		}
121 	}
122 
123 	/*
124 	 * Return the SME encryption mask (if SME is active) to be used as a
125 	 * modifier for the initial pgdir entry programmed into CR3.
126 	 */
127 	return sme_get_me_mask();
128 }
129 
130 /* Code in __startup_64() can be relocated during execution, but the compiler
131  * doesn't have to generate PC-relative relocations when accessing globals from
132  * that function. Clang actually does not generate them, which leads to
133  * boot-time crashes. To work around this problem, every global pointer must
134  * be accessed using RIP_REL_REF().
135  */
136 unsigned long __head __startup_64(unsigned long physaddr,
137 				  struct boot_params *bp)
138 {
139 	pmd_t (*early_pgts)[PTRS_PER_PMD] = RIP_REL_REF(early_dynamic_pgts);
140 	unsigned long pgtable_flags;
141 	unsigned long load_delta;
142 	pgdval_t *pgd;
143 	p4dval_t *p4d;
144 	pudval_t *pud;
145 	pmdval_t *pmd, pmd_entry;
146 	bool la57;
147 	int i;
148 
149 	la57 = check_la57_support();
150 
151 	/* Is the address too large? */
152 	if (physaddr >> MAX_PHYSMEM_BITS)
153 		for (;;);
154 
155 	/*
156 	 * Compute the delta between the address I am compiled to run at
157 	 * and the address I am actually running at.
158 	 */
159 	load_delta = physaddr - (unsigned long)(_text - __START_KERNEL_map);
160 	RIP_REL_REF(phys_base) = load_delta;
161 
162 	/* Is the address not 2M aligned? */
163 	if (load_delta & ~PMD_MASK)
164 		for (;;);
165 
166 	/* Include the SME encryption mask in the fixup value */
167 	load_delta += sme_get_me_mask();
168 
169 	/* Fixup the physical addresses in the page table */
170 
171 	pgd = &RIP_REL_REF(early_top_pgt)->pgd;
172 	pgd[pgd_index(__START_KERNEL_map)] += load_delta;
173 
174 	if (la57) {
175 		p4d = (p4dval_t *)&RIP_REL_REF(level4_kernel_pgt);
176 		p4d[MAX_PTRS_PER_P4D - 1] += load_delta;
177 
178 		pgd[pgd_index(__START_KERNEL_map)] = (pgdval_t)p4d | _PAGE_TABLE_NOENC;
179 	}
180 
181 	RIP_REL_REF(level3_kernel_pgt)[PTRS_PER_PUD - 2].pud += load_delta;
182 	RIP_REL_REF(level3_kernel_pgt)[PTRS_PER_PUD - 1].pud += load_delta;
183 
184 	for (i = FIXMAP_PMD_TOP; i > FIXMAP_PMD_TOP - FIXMAP_PMD_NUM; i--)
185 		RIP_REL_REF(level2_fixmap_pgt)[i].pmd += load_delta;
186 
187 	/*
188 	 * Set up the identity mapping for the switchover.  These
189 	 * entries should *NOT* have the global bit set!  This also
190 	 * creates a bunch of nonsense entries but that is fine --
191 	 * it avoids problems around wraparound.
192 	 */
193 
194 	pud = &early_pgts[0]->pmd;
195 	pmd = &early_pgts[1]->pmd;
196 	RIP_REL_REF(next_early_pgt) = 2;
197 
198 	pgtable_flags = _KERNPG_TABLE_NOENC + sme_get_me_mask();
199 
200 	if (la57) {
201 		p4d = &early_pgts[RIP_REL_REF(next_early_pgt)++]->pmd;
202 
203 		i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD;
204 		pgd[i + 0] = (pgdval_t)p4d + pgtable_flags;
205 		pgd[i + 1] = (pgdval_t)p4d + pgtable_flags;
206 
207 		i = physaddr >> P4D_SHIFT;
208 		p4d[(i + 0) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags;
209 		p4d[(i + 1) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags;
210 	} else {
211 		i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD;
212 		pgd[i + 0] = (pgdval_t)pud + pgtable_flags;
213 		pgd[i + 1] = (pgdval_t)pud + pgtable_flags;
214 	}
215 
216 	i = physaddr >> PUD_SHIFT;
217 	pud[(i + 0) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags;
218 	pud[(i + 1) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags;
219 
220 	pmd_entry = __PAGE_KERNEL_LARGE_EXEC & ~_PAGE_GLOBAL;
221 	/* Filter out unsupported __PAGE_KERNEL_* bits: */
222 	pmd_entry &= RIP_REL_REF(__supported_pte_mask);
223 	pmd_entry += sme_get_me_mask();
224 	pmd_entry +=  physaddr;
225 
226 	for (i = 0; i < DIV_ROUND_UP(_end - _text, PMD_SIZE); i++) {
227 		int idx = i + (physaddr >> PMD_SHIFT);
228 
229 		pmd[idx % PTRS_PER_PMD] = pmd_entry + i * PMD_SIZE;
230 	}
231 
232 	/*
233 	 * Fixup the kernel text+data virtual addresses. Note that
234 	 * we might write invalid pmds, when the kernel is relocated
235 	 * cleanup_highmap() fixes this up along with the mappings
236 	 * beyond _end.
237 	 *
238 	 * Only the region occupied by the kernel image has so far
239 	 * been checked against the table of usable memory regions
240 	 * provided by the firmware, so invalidate pages outside that
241 	 * region. A page table entry that maps to a reserved area of
242 	 * memory would allow processor speculation into that area,
243 	 * and on some hardware (particularly the UV platform) even
244 	 * speculative access to some reserved areas is caught as an
245 	 * error, causing the BIOS to halt the system.
246 	 */
247 
248 	pmd = &RIP_REL_REF(level2_kernel_pgt)->pmd;
249 
250 	/* invalidate pages before the kernel image */
251 	for (i = 0; i < pmd_index((unsigned long)_text); i++)
252 		pmd[i] &= ~_PAGE_PRESENT;
253 
254 	/* fixup pages that are part of the kernel image */
255 	for (; i <= pmd_index((unsigned long)_end); i++)
256 		if (pmd[i] & _PAGE_PRESENT)
257 			pmd[i] += load_delta;
258 
259 	/* invalidate pages after the kernel image */
260 	for (; i < PTRS_PER_PMD; i++)
261 		pmd[i] &= ~_PAGE_PRESENT;
262 
263 	return sme_postprocess_startup(bp, pmd);
264 }
265 
266 /* Wipe all early page tables except for the kernel symbol map */
267 static void __init reset_early_page_tables(void)
268 {
269 	memset(early_top_pgt, 0, sizeof(pgd_t)*(PTRS_PER_PGD-1));
270 	next_early_pgt = 0;
271 	write_cr3(__sme_pa_nodebug(early_top_pgt));
272 }
273 
274 /* Create a new PMD entry */
275 bool __init __early_make_pgtable(unsigned long address, pmdval_t pmd)
276 {
277 	unsigned long physaddr = address - __PAGE_OFFSET;
278 	pgdval_t pgd, *pgd_p;
279 	p4dval_t p4d, *p4d_p;
280 	pudval_t pud, *pud_p;
281 	pmdval_t *pmd_p;
282 
283 	/* Invalid address or early pgt is done ?  */
284 	if (physaddr >= MAXMEM || read_cr3_pa() != __pa_nodebug(early_top_pgt))
285 		return false;
286 
287 again:
288 	pgd_p = &early_top_pgt[pgd_index(address)].pgd;
289 	pgd = *pgd_p;
290 
291 	/*
292 	 * The use of __START_KERNEL_map rather than __PAGE_OFFSET here is
293 	 * critical -- __PAGE_OFFSET would point us back into the dynamic
294 	 * range and we might end up looping forever...
295 	 */
296 	if (!pgtable_l5_enabled())
297 		p4d_p = pgd_p;
298 	else if (pgd)
299 		p4d_p = (p4dval_t *)((pgd & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);
300 	else {
301 		if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {
302 			reset_early_page_tables();
303 			goto again;
304 		}
305 
306 		p4d_p = (p4dval_t *)early_dynamic_pgts[next_early_pgt++];
307 		memset(p4d_p, 0, sizeof(*p4d_p) * PTRS_PER_P4D);
308 		*pgd_p = (pgdval_t)p4d_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;
309 	}
310 	p4d_p += p4d_index(address);
311 	p4d = *p4d_p;
312 
313 	if (p4d)
314 		pud_p = (pudval_t *)((p4d & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);
315 	else {
316 		if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {
317 			reset_early_page_tables();
318 			goto again;
319 		}
320 
321 		pud_p = (pudval_t *)early_dynamic_pgts[next_early_pgt++];
322 		memset(pud_p, 0, sizeof(*pud_p) * PTRS_PER_PUD);
323 		*p4d_p = (p4dval_t)pud_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;
324 	}
325 	pud_p += pud_index(address);
326 	pud = *pud_p;
327 
328 	if (pud)
329 		pmd_p = (pmdval_t *)((pud & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);
330 	else {
331 		if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {
332 			reset_early_page_tables();
333 			goto again;
334 		}
335 
336 		pmd_p = (pmdval_t *)early_dynamic_pgts[next_early_pgt++];
337 		memset(pmd_p, 0, sizeof(*pmd_p) * PTRS_PER_PMD);
338 		*pud_p = (pudval_t)pmd_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;
339 	}
340 	pmd_p[pmd_index(address)] = pmd;
341 
342 	return true;
343 }
344 
345 static bool __init early_make_pgtable(unsigned long address)
346 {
347 	unsigned long physaddr = address - __PAGE_OFFSET;
348 	pmdval_t pmd;
349 
350 	pmd = (physaddr & PMD_MASK) + early_pmd_flags;
351 
352 	return __early_make_pgtable(address, pmd);
353 }
354 
355 void __init do_early_exception(struct pt_regs *regs, int trapnr)
356 {
357 	if (trapnr == X86_TRAP_PF &&
358 	    early_make_pgtable(native_read_cr2()))
359 		return;
360 
361 	if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT) &&
362 	    trapnr == X86_TRAP_VC && handle_vc_boot_ghcb(regs))
363 		return;
364 
365 	if (trapnr == X86_TRAP_VE && tdx_early_handle_ve(regs))
366 		return;
367 
368 	early_fixup_exception(regs, trapnr);
369 }
370 
371 /* Don't add a printk in there. printk relies on the PDA which is not initialized
372    yet. */
373 void __init clear_bss(void)
374 {
375 	memset(__bss_start, 0,
376 	       (unsigned long) __bss_stop - (unsigned long) __bss_start);
377 	memset(__brk_base, 0,
378 	       (unsigned long) __brk_limit - (unsigned long) __brk_base);
379 }
380 
381 static unsigned long get_cmd_line_ptr(void)
382 {
383 	unsigned long cmd_line_ptr = boot_params.hdr.cmd_line_ptr;
384 
385 	cmd_line_ptr |= (u64)boot_params.ext_cmd_line_ptr << 32;
386 
387 	return cmd_line_ptr;
388 }
389 
390 static void __init copy_bootdata(char *real_mode_data)
391 {
392 	char * command_line;
393 	unsigned long cmd_line_ptr;
394 
395 	/*
396 	 * If SME is active, this will create decrypted mappings of the
397 	 * boot data in advance of the copy operations.
398 	 */
399 	sme_map_bootdata(real_mode_data);
400 
401 	memcpy(&boot_params, real_mode_data, sizeof(boot_params));
402 	sanitize_boot_params(&boot_params);
403 	cmd_line_ptr = get_cmd_line_ptr();
404 	if (cmd_line_ptr) {
405 		command_line = __va(cmd_line_ptr);
406 		memcpy(boot_command_line, command_line, COMMAND_LINE_SIZE);
407 	}
408 
409 	/*
410 	 * The old boot data is no longer needed and won't be reserved,
411 	 * freeing up that memory for use by the system. If SME is active,
412 	 * we need to remove the mappings that were created so that the
413 	 * memory doesn't remain mapped as decrypted.
414 	 */
415 	sme_unmap_bootdata(real_mode_data);
416 }
417 
418 asmlinkage __visible void __init __noreturn x86_64_start_kernel(char * real_mode_data)
419 {
420 	/*
421 	 * Build-time sanity checks on the kernel image and module
422 	 * area mappings. (these are purely build-time and produce no code)
423 	 */
424 	BUILD_BUG_ON(MODULES_VADDR < __START_KERNEL_map);
425 	BUILD_BUG_ON(MODULES_VADDR - __START_KERNEL_map < KERNEL_IMAGE_SIZE);
426 	BUILD_BUG_ON(MODULES_LEN + KERNEL_IMAGE_SIZE > 2*PUD_SIZE);
427 	BUILD_BUG_ON((__START_KERNEL_map & ~PMD_MASK) != 0);
428 	BUILD_BUG_ON((MODULES_VADDR & ~PMD_MASK) != 0);
429 	BUILD_BUG_ON(!(MODULES_VADDR > __START_KERNEL));
430 	MAYBE_BUILD_BUG_ON(!(((MODULES_END - 1) & PGDIR_MASK) ==
431 				(__START_KERNEL & PGDIR_MASK)));
432 	BUILD_BUG_ON(__fix_to_virt(__end_of_fixed_addresses) <= MODULES_END);
433 
434 	if (check_la57_support()) {
435 		__pgtable_l5_enabled	= 1;
436 		pgdir_shift		= 48;
437 		ptrs_per_p4d		= 512;
438 		page_offset_base	= __PAGE_OFFSET_BASE_L5;
439 		vmalloc_base		= __VMALLOC_BASE_L5;
440 		vmemmap_base		= __VMEMMAP_BASE_L5;
441 	}
442 
443 	cr4_init_shadow();
444 
445 	/* Kill off the identity-map trampoline */
446 	reset_early_page_tables();
447 
448 	clear_bss();
449 
450 	/*
451 	 * This needs to happen *before* kasan_early_init() because latter maps stuff
452 	 * into that page.
453 	 */
454 	clear_page(init_top_pgt);
455 
456 	/*
457 	 * SME support may update early_pmd_flags to include the memory
458 	 * encryption mask, so it needs to be called before anything
459 	 * that may generate a page fault.
460 	 */
461 	sme_early_init();
462 
463 	kasan_early_init();
464 
465 	/*
466 	 * Flush global TLB entries which could be left over from the trampoline page
467 	 * table.
468 	 *
469 	 * This needs to happen *after* kasan_early_init() as KASAN-enabled .configs
470 	 * instrument native_write_cr4() so KASAN must be initialized for that
471 	 * instrumentation to work.
472 	 */
473 	__native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4));
474 
475 	idt_setup_early_handler();
476 
477 	/* Needed before cc_platform_has() can be used for TDX */
478 	tdx_early_init();
479 
480 	copy_bootdata(__va(real_mode_data));
481 
482 	/*
483 	 * Load microcode early on BSP.
484 	 */
485 	load_ucode_bsp();
486 
487 	/* set init_top_pgt kernel high mapping*/
488 	init_top_pgt[511] = early_top_pgt[511];
489 
490 	x86_64_start_reservations(real_mode_data);
491 }
492 
493 void __init __noreturn x86_64_start_reservations(char *real_mode_data)
494 {
495 	/* version is always not zero if it is copied */
496 	if (!boot_params.hdr.version)
497 		copy_bootdata(__va(real_mode_data));
498 
499 	x86_early_init_platform_quirks();
500 
501 	switch (boot_params.hdr.hardware_subarch) {
502 	case X86_SUBARCH_INTEL_MID:
503 		x86_intel_mid_early_setup();
504 		break;
505 	default:
506 		break;
507 	}
508 
509 	start_kernel();
510 }
511 
512 /*
513  * Data structures and code used for IDT setup in head_64.S. The bringup-IDT is
514  * used until the idt_table takes over. On the boot CPU this happens in
515  * x86_64_start_kernel(), on secondary CPUs in start_secondary(). In both cases
516  * this happens in the functions called from head_64.S.
517  *
518  * The idt_table can't be used that early because all the code modifying it is
519  * in idt.c and can be instrumented by tracing or KASAN, which both don't work
520  * during early CPU bringup. Also the idt_table has the runtime vectors
521  * configured which require certain CPU state to be setup already (like TSS),
522  * which also hasn't happened yet in early CPU bringup.
523  */
524 static gate_desc bringup_idt_table[NUM_EXCEPTION_VECTORS] __page_aligned_data;
525 
526 /* This may run while still in the direct mapping */
527 static void __head startup_64_load_idt(void *vc_handler)
528 {
529 	struct desc_ptr desc = {
530 		.address = (unsigned long)&RIP_REL_REF(bringup_idt_table),
531 		.size    = sizeof(bringup_idt_table) - 1,
532 	};
533 	struct idt_data data;
534 	gate_desc idt_desc;
535 
536 	/* @vc_handler is set only for a VMM Communication Exception */
537 	if (vc_handler) {
538 		init_idt_data(&data, X86_TRAP_VC, vc_handler);
539 		idt_init_desc(&idt_desc, &data);
540 		native_write_idt_entry((gate_desc *)desc.address, X86_TRAP_VC, &idt_desc);
541 	}
542 
543 	native_load_idt(&desc);
544 }
545 
546 /* This is used when running on kernel addresses */
547 void early_setup_idt(void)
548 {
549 	void *handler = NULL;
550 
551 	if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) {
552 		setup_ghcb();
553 		handler = vc_boot_ghcb;
554 	}
555 
556 	startup_64_load_idt(handler);
557 }
558 
559 /*
560  * Setup boot CPU state needed before kernel switches to virtual addresses.
561  */
562 void __head startup_64_setup_gdt_idt(void)
563 {
564 	void *handler = NULL;
565 
566 	struct desc_ptr startup_gdt_descr = {
567 		.address = (unsigned long)&RIP_REL_REF(init_per_cpu_var(gdt_page.gdt)),
568 		.size    = GDT_SIZE - 1,
569 	};
570 
571 	/* Load GDT */
572 	native_load_gdt(&startup_gdt_descr);
573 
574 	/* New GDT is live - reload data segment registers */
575 	asm volatile("movl %%eax, %%ds\n"
576 		     "movl %%eax, %%ss\n"
577 		     "movl %%eax, %%es\n" : : "a"(__KERNEL_DS) : "memory");
578 
579 	if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT))
580 		handler = &RIP_REL_REF(vc_no_ghcb);
581 
582 	startup_64_load_idt(handler);
583 }
584