xref: /openbmc/linux/arch/x86/boot/compressed/sev.c (revision 2a598d0b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * AMD Encrypted Register State Support
4  *
5  * Author: Joerg Roedel <jroedel@suse.de>
6  */
7 
8 /*
9  * misc.h needs to be first because it knows how to include the other kernel
10  * headers in the pre-decompression code in a way that does not break
11  * compilation.
12  */
13 #include "misc.h"
14 
15 #include <asm/pgtable_types.h>
16 #include <asm/sev.h>
17 #include <asm/trapnr.h>
18 #include <asm/trap_pf.h>
19 #include <asm/msr-index.h>
20 #include <asm/fpu/xcr.h>
21 #include <asm/ptrace.h>
22 #include <asm/svm.h>
23 #include <asm/cpuid.h>
24 
25 #include "error.h"
26 #include "../msr.h"
27 
28 struct ghcb boot_ghcb_page __aligned(PAGE_SIZE);
29 struct ghcb *boot_ghcb;
30 
31 /*
32  * Copy a version of this function here - insn-eval.c can't be used in
33  * pre-decompression code.
34  */
35 static bool insn_has_rep_prefix(struct insn *insn)
36 {
37 	insn_byte_t p;
38 	int i;
39 
40 	insn_get_prefixes(insn);
41 
42 	for_each_insn_prefix(insn, i, p) {
43 		if (p == 0xf2 || p == 0xf3)
44 			return true;
45 	}
46 
47 	return false;
48 }
49 
50 /*
51  * Only a dummy for insn_get_seg_base() - Early boot-code is 64bit only and
52  * doesn't use segments.
53  */
54 static unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx)
55 {
56 	return 0UL;
57 }
58 
59 static inline u64 sev_es_rd_ghcb_msr(void)
60 {
61 	struct msr m;
62 
63 	boot_rdmsr(MSR_AMD64_SEV_ES_GHCB, &m);
64 
65 	return m.q;
66 }
67 
68 static inline void sev_es_wr_ghcb_msr(u64 val)
69 {
70 	struct msr m;
71 
72 	m.q = val;
73 	boot_wrmsr(MSR_AMD64_SEV_ES_GHCB, &m);
74 }
75 
76 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
77 {
78 	char buffer[MAX_INSN_SIZE];
79 	int ret;
80 
81 	memcpy(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
82 
83 	ret = insn_decode(&ctxt->insn, buffer, MAX_INSN_SIZE, INSN_MODE_64);
84 	if (ret < 0)
85 		return ES_DECODE_FAILED;
86 
87 	return ES_OK;
88 }
89 
90 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
91 				   void *dst, char *buf, size_t size)
92 {
93 	memcpy(dst, buf, size);
94 
95 	return ES_OK;
96 }
97 
98 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
99 				  void *src, char *buf, size_t size)
100 {
101 	memcpy(buf, src, size);
102 
103 	return ES_OK;
104 }
105 
106 #undef __init
107 #define __init
108 
109 #define __BOOT_COMPRESSED
110 
111 /* Basic instruction decoding support needed */
112 #include "../../lib/inat.c"
113 #include "../../lib/insn.c"
114 
115 /* Include code for early handlers */
116 #include "../../kernel/sev-shared.c"
117 
118 bool sev_snp_enabled(void)
119 {
120 	return sev_status & MSR_AMD64_SEV_SNP_ENABLED;
121 }
122 
123 static void __page_state_change(unsigned long paddr, enum psc_op op)
124 {
125 	u64 val;
126 
127 	if (!sev_snp_enabled())
128 		return;
129 
130 	/*
131 	 * If private -> shared then invalidate the page before requesting the
132 	 * state change in the RMP table.
133 	 */
134 	if (op == SNP_PAGE_STATE_SHARED && pvalidate(paddr, RMP_PG_SIZE_4K, 0))
135 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
136 
137 	/* Issue VMGEXIT to change the page state in RMP table. */
138 	sev_es_wr_ghcb_msr(GHCB_MSR_PSC_REQ_GFN(paddr >> PAGE_SHIFT, op));
139 	VMGEXIT();
140 
141 	/* Read the response of the VMGEXIT. */
142 	val = sev_es_rd_ghcb_msr();
143 	if ((GHCB_RESP_CODE(val) != GHCB_MSR_PSC_RESP) || GHCB_MSR_PSC_RESP_VAL(val))
144 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
145 
146 	/*
147 	 * Now that page state is changed in the RMP table, validate it so that it is
148 	 * consistent with the RMP entry.
149 	 */
150 	if (op == SNP_PAGE_STATE_PRIVATE && pvalidate(paddr, RMP_PG_SIZE_4K, 1))
151 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
152 }
153 
154 void snp_set_page_private(unsigned long paddr)
155 {
156 	__page_state_change(paddr, SNP_PAGE_STATE_PRIVATE);
157 }
158 
159 void snp_set_page_shared(unsigned long paddr)
160 {
161 	__page_state_change(paddr, SNP_PAGE_STATE_SHARED);
162 }
163 
164 static bool early_setup_ghcb(void)
165 {
166 	if (set_page_decrypted((unsigned long)&boot_ghcb_page))
167 		return false;
168 
169 	/* Page is now mapped decrypted, clear it */
170 	memset(&boot_ghcb_page, 0, sizeof(boot_ghcb_page));
171 
172 	boot_ghcb = &boot_ghcb_page;
173 
174 	/* Initialize lookup tables for the instruction decoder */
175 	inat_init_tables();
176 
177 	/* SNP guest requires the GHCB GPA must be registered */
178 	if (sev_snp_enabled())
179 		snp_register_ghcb_early(__pa(&boot_ghcb_page));
180 
181 	return true;
182 }
183 
184 static phys_addr_t __snp_accept_memory(struct snp_psc_desc *desc,
185 				       phys_addr_t pa, phys_addr_t pa_end)
186 {
187 	struct psc_hdr *hdr;
188 	struct psc_entry *e;
189 	unsigned int i;
190 
191 	hdr = &desc->hdr;
192 	memset(hdr, 0, sizeof(*hdr));
193 
194 	e = desc->entries;
195 
196 	i = 0;
197 	while (pa < pa_end && i < VMGEXIT_PSC_MAX_ENTRY) {
198 		hdr->end_entry = i;
199 
200 		e->gfn = pa >> PAGE_SHIFT;
201 		e->operation = SNP_PAGE_STATE_PRIVATE;
202 		if (IS_ALIGNED(pa, PMD_SIZE) && (pa_end - pa) >= PMD_SIZE) {
203 			e->pagesize = RMP_PG_SIZE_2M;
204 			pa += PMD_SIZE;
205 		} else {
206 			e->pagesize = RMP_PG_SIZE_4K;
207 			pa += PAGE_SIZE;
208 		}
209 
210 		e++;
211 		i++;
212 	}
213 
214 	if (vmgexit_psc(boot_ghcb, desc))
215 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
216 
217 	pvalidate_pages(desc);
218 
219 	return pa;
220 }
221 
222 void snp_accept_memory(phys_addr_t start, phys_addr_t end)
223 {
224 	struct snp_psc_desc desc = {};
225 	unsigned int i;
226 	phys_addr_t pa;
227 
228 	if (!boot_ghcb && !early_setup_ghcb())
229 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
230 
231 	pa = start;
232 	while (pa < end)
233 		pa = __snp_accept_memory(&desc, pa, end);
234 }
235 
236 void sev_es_shutdown_ghcb(void)
237 {
238 	if (!boot_ghcb)
239 		return;
240 
241 	if (!sev_es_check_cpu_features())
242 		error("SEV-ES CPU Features missing.");
243 
244 	/*
245 	 * GHCB Page must be flushed from the cache and mapped encrypted again.
246 	 * Otherwise the running kernel will see strange cache effects when
247 	 * trying to use that page.
248 	 */
249 	if (set_page_encrypted((unsigned long)&boot_ghcb_page))
250 		error("Can't map GHCB page encrypted");
251 
252 	/*
253 	 * GHCB page is mapped encrypted again and flushed from the cache.
254 	 * Mark it non-present now to catch bugs when #VC exceptions trigger
255 	 * after this point.
256 	 */
257 	if (set_page_non_present((unsigned long)&boot_ghcb_page))
258 		error("Can't unmap GHCB page");
259 }
260 
261 static void __noreturn sev_es_ghcb_terminate(struct ghcb *ghcb, unsigned int set,
262 					     unsigned int reason, u64 exit_info_2)
263 {
264 	u64 exit_info_1 = SVM_VMGEXIT_TERM_REASON(set, reason);
265 
266 	vc_ghcb_invalidate(ghcb);
267 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_TERM_REQUEST);
268 	ghcb_set_sw_exit_info_1(ghcb, exit_info_1);
269 	ghcb_set_sw_exit_info_2(ghcb, exit_info_2);
270 
271 	sev_es_wr_ghcb_msr(__pa(ghcb));
272 	VMGEXIT();
273 
274 	while (true)
275 		asm volatile("hlt\n" : : : "memory");
276 }
277 
278 bool sev_es_check_ghcb_fault(unsigned long address)
279 {
280 	/* Check whether the fault was on the GHCB page */
281 	return ((address & PAGE_MASK) == (unsigned long)&boot_ghcb_page);
282 }
283 
284 void do_boot_stage2_vc(struct pt_regs *regs, unsigned long exit_code)
285 {
286 	struct es_em_ctxt ctxt;
287 	enum es_result result;
288 
289 	if (!boot_ghcb && !early_setup_ghcb())
290 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
291 
292 	vc_ghcb_invalidate(boot_ghcb);
293 	result = vc_init_em_ctxt(&ctxt, regs, exit_code);
294 	if (result != ES_OK)
295 		goto finish;
296 
297 	switch (exit_code) {
298 	case SVM_EXIT_RDTSC:
299 	case SVM_EXIT_RDTSCP:
300 		result = vc_handle_rdtsc(boot_ghcb, &ctxt, exit_code);
301 		break;
302 	case SVM_EXIT_IOIO:
303 		result = vc_handle_ioio(boot_ghcb, &ctxt);
304 		break;
305 	case SVM_EXIT_CPUID:
306 		result = vc_handle_cpuid(boot_ghcb, &ctxt);
307 		break;
308 	default:
309 		result = ES_UNSUPPORTED;
310 		break;
311 	}
312 
313 finish:
314 	if (result == ES_OK)
315 		vc_finish_insn(&ctxt);
316 	else if (result != ES_RETRY)
317 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
318 }
319 
320 static void enforce_vmpl0(void)
321 {
322 	u64 attrs;
323 	int err;
324 
325 	/*
326 	 * RMPADJUST modifies RMP permissions of a lesser-privileged (numerically
327 	 * higher) privilege level. Here, clear the VMPL1 permission mask of the
328 	 * GHCB page. If the guest is not running at VMPL0, this will fail.
329 	 *
330 	 * If the guest is running at VMPL0, it will succeed. Even if that operation
331 	 * modifies permission bits, it is still ok to do so currently because Linux
332 	 * SNP guests are supported only on VMPL0 so VMPL1 or higher permission masks
333 	 * changing is a don't-care.
334 	 */
335 	attrs = 1;
336 	if (rmpadjust((unsigned long)&boot_ghcb_page, RMP_PG_SIZE_4K, attrs))
337 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_NOT_VMPL0);
338 }
339 
340 /*
341  * SNP_FEATURES_IMPL_REQ is the mask of SNP features that will need
342  * guest side implementation for proper functioning of the guest. If any
343  * of these features are enabled in the hypervisor but are lacking guest
344  * side implementation, the behavior of the guest will be undefined. The
345  * guest could fail in non-obvious way making it difficult to debug.
346  *
347  * As the behavior of reserved feature bits is unknown to be on the
348  * safe side add them to the required features mask.
349  */
350 #define SNP_FEATURES_IMPL_REQ	(MSR_AMD64_SNP_VTOM |			\
351 				 MSR_AMD64_SNP_REFLECT_VC |		\
352 				 MSR_AMD64_SNP_RESTRICTED_INJ |		\
353 				 MSR_AMD64_SNP_ALT_INJ |		\
354 				 MSR_AMD64_SNP_DEBUG_SWAP |		\
355 				 MSR_AMD64_SNP_VMPL_SSS |		\
356 				 MSR_AMD64_SNP_SECURE_TSC |		\
357 				 MSR_AMD64_SNP_VMGEXIT_PARAM |		\
358 				 MSR_AMD64_SNP_VMSA_REG_PROTECTION |	\
359 				 MSR_AMD64_SNP_RESERVED_BIT13 |		\
360 				 MSR_AMD64_SNP_RESERVED_BIT15 |		\
361 				 MSR_AMD64_SNP_RESERVED_MASK)
362 
363 /*
364  * SNP_FEATURES_PRESENT is the mask of SNP features that are implemented
365  * by the guest kernel. As and when a new feature is implemented in the
366  * guest kernel, a corresponding bit should be added to the mask.
367  */
368 #define SNP_FEATURES_PRESENT (0)
369 
370 void snp_check_features(void)
371 {
372 	u64 unsupported;
373 
374 	if (!(sev_status & MSR_AMD64_SEV_SNP_ENABLED))
375 		return;
376 
377 	/*
378 	 * Terminate the boot if hypervisor has enabled any feature lacking
379 	 * guest side implementation. Pass on the unsupported features mask through
380 	 * EXIT_INFO_2 of the GHCB protocol so that those features can be reported
381 	 * as part of the guest boot failure.
382 	 */
383 	unsupported = sev_status & SNP_FEATURES_IMPL_REQ & ~SNP_FEATURES_PRESENT;
384 	if (unsupported) {
385 		if (ghcb_version < 2 || (!boot_ghcb && !early_setup_ghcb()))
386 			sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
387 
388 		sev_es_ghcb_terminate(boot_ghcb, SEV_TERM_SET_GEN,
389 				      GHCB_SNP_UNSUPPORTED, unsupported);
390 	}
391 }
392 
393 void sev_enable(struct boot_params *bp)
394 {
395 	unsigned int eax, ebx, ecx, edx;
396 	struct msr m;
397 	bool snp;
398 
399 	/*
400 	 * bp->cc_blob_address should only be set by boot/compressed kernel.
401 	 * Initialize it to 0 to ensure that uninitialized values from
402 	 * buggy bootloaders aren't propagated.
403 	 */
404 	if (bp)
405 		bp->cc_blob_address = 0;
406 
407 	/*
408 	 * Setup/preliminary detection of SNP. This will be sanity-checked
409 	 * against CPUID/MSR values later.
410 	 */
411 	snp = snp_init(bp);
412 
413 	/* Check for the SME/SEV support leaf */
414 	eax = 0x80000000;
415 	ecx = 0;
416 	native_cpuid(&eax, &ebx, &ecx, &edx);
417 	if (eax < 0x8000001f)
418 		return;
419 
420 	/*
421 	 * Check for the SME/SEV feature:
422 	 *   CPUID Fn8000_001F[EAX]
423 	 *   - Bit 0 - Secure Memory Encryption support
424 	 *   - Bit 1 - Secure Encrypted Virtualization support
425 	 *   CPUID Fn8000_001F[EBX]
426 	 *   - Bits 5:0 - Pagetable bit position used to indicate encryption
427 	 */
428 	eax = 0x8000001f;
429 	ecx = 0;
430 	native_cpuid(&eax, &ebx, &ecx, &edx);
431 	/* Check whether SEV is supported */
432 	if (!(eax & BIT(1))) {
433 		if (snp)
434 			error("SEV-SNP support indicated by CC blob, but not CPUID.");
435 		return;
436 	}
437 
438 	/* Set the SME mask if this is an SEV guest. */
439 	boot_rdmsr(MSR_AMD64_SEV, &m);
440 	sev_status = m.q;
441 	if (!(sev_status & MSR_AMD64_SEV_ENABLED))
442 		return;
443 
444 	/* Negotiate the GHCB protocol version. */
445 	if (sev_status & MSR_AMD64_SEV_ES_ENABLED) {
446 		if (!sev_es_negotiate_protocol())
447 			sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_PROT_UNSUPPORTED);
448 	}
449 
450 	/*
451 	 * SNP is supported in v2 of the GHCB spec which mandates support for HV
452 	 * features.
453 	 */
454 	if (sev_status & MSR_AMD64_SEV_SNP_ENABLED) {
455 		if (!(get_hv_features() & GHCB_HV_FT_SNP))
456 			sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
457 
458 		enforce_vmpl0();
459 	}
460 
461 	if (snp && !(sev_status & MSR_AMD64_SEV_SNP_ENABLED))
462 		error("SEV-SNP supported indicated by CC blob, but not SEV status MSR.");
463 
464 	sme_me_mask = BIT_ULL(ebx & 0x3f);
465 }
466 
467 /* Search for Confidential Computing blob in the EFI config table. */
468 static struct cc_blob_sev_info *find_cc_blob_efi(struct boot_params *bp)
469 {
470 	unsigned long cfg_table_pa;
471 	unsigned int cfg_table_len;
472 	int ret;
473 
474 	ret = efi_get_conf_table(bp, &cfg_table_pa, &cfg_table_len);
475 	if (ret)
476 		return NULL;
477 
478 	return (struct cc_blob_sev_info *)efi_find_vendor_table(bp, cfg_table_pa,
479 								cfg_table_len,
480 								EFI_CC_BLOB_GUID);
481 }
482 
483 /*
484  * Initial set up of SNP relies on information provided by the
485  * Confidential Computing blob, which can be passed to the boot kernel
486  * by firmware/bootloader in the following ways:
487  *
488  * - via an entry in the EFI config table
489  * - via a setup_data structure, as defined by the Linux Boot Protocol
490  *
491  * Scan for the blob in that order.
492  */
493 static struct cc_blob_sev_info *find_cc_blob(struct boot_params *bp)
494 {
495 	struct cc_blob_sev_info *cc_info;
496 
497 	cc_info = find_cc_blob_efi(bp);
498 	if (cc_info)
499 		goto found_cc_info;
500 
501 	cc_info = find_cc_blob_setup_data(bp);
502 	if (!cc_info)
503 		return NULL;
504 
505 found_cc_info:
506 	if (cc_info->magic != CC_BLOB_SEV_HDR_MAGIC)
507 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
508 
509 	return cc_info;
510 }
511 
512 /*
513  * Indicate SNP based on presence of SNP-specific CC blob. Subsequent checks
514  * will verify the SNP CPUID/MSR bits.
515  */
516 bool snp_init(struct boot_params *bp)
517 {
518 	struct cc_blob_sev_info *cc_info;
519 
520 	if (!bp)
521 		return false;
522 
523 	cc_info = find_cc_blob(bp);
524 	if (!cc_info)
525 		return false;
526 
527 	/*
528 	 * If a SNP-specific Confidential Computing blob is present, then
529 	 * firmware/bootloader have indicated SNP support. Verifying this
530 	 * involves CPUID checks which will be more reliable if the SNP
531 	 * CPUID table is used. See comments over snp_setup_cpuid_table() for
532 	 * more details.
533 	 */
534 	setup_cpuid_table(cc_info);
535 
536 	/*
537 	 * Pass run-time kernel a pointer to CC info via boot_params so EFI
538 	 * config table doesn't need to be searched again during early startup
539 	 * phase.
540 	 */
541 	bp->cc_blob_address = (u32)(unsigned long)cc_info;
542 
543 	return true;
544 }
545 
546 void sev_prep_identity_maps(unsigned long top_level_pgt)
547 {
548 	/*
549 	 * The Confidential Computing blob is used very early in uncompressed
550 	 * kernel to find the in-memory CPUID table to handle CPUID
551 	 * instructions. Make sure an identity-mapping exists so it can be
552 	 * accessed after switchover.
553 	 */
554 	if (sev_snp_enabled()) {
555 		unsigned long cc_info_pa = boot_params->cc_blob_address;
556 		struct cc_blob_sev_info *cc_info;
557 
558 		kernel_add_identity_map(cc_info_pa, cc_info_pa + sizeof(*cc_info));
559 
560 		cc_info = (struct cc_blob_sev_info *)cc_info_pa;
561 		kernel_add_identity_map(cc_info->cpuid_phys, cc_info->cpuid_phys + cc_info->cpuid_len);
562 	}
563 
564 	sev_verify_cbit(top_level_pgt);
565 }
566