1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * AMD Encrypted Register State Support
4 *
5 * Author: Joerg Roedel <[email protected]>
6 *
7 * This file is not compiled stand-alone. It contains code shared
8 * between the pre-decompression boot code and the running Linux kernel
9 * and is included directly into both code-bases.
10 */
11
12 #include <asm/setup_data.h>
13
14 #ifndef __BOOT_COMPRESSED
15 #define error(v) pr_err(v)
16 #define has_cpuflag(f) boot_cpu_has(f)
17 #define sev_printk(fmt, ...) printk(fmt, ##__VA_ARGS__)
18 #define sev_printk_rtl(fmt, ...) printk_ratelimited(fmt, ##__VA_ARGS__)
19 #else
20 #undef WARN
21 #define WARN(condition, format...) (!!(condition))
22 #define sev_printk(fmt, ...)
23 #define sev_printk_rtl(fmt, ...)
24 #undef vc_forward_exception
25 #define vc_forward_exception(c) panic("SNP: Hypervisor requested exception\n")
26 #endif
27
28 /*
29 * SVSM related information:
30 * When running under an SVSM, the VMPL that Linux is executing at must be
31 * non-zero. The VMPL is therefore used to indicate the presence of an SVSM.
32 *
33 * During boot, the page tables are set up as identity mapped and later
34 * changed to use kernel virtual addresses. Maintain separate virtual and
35 * physical addresses for the CAA to allow SVSM functions to be used during
36 * early boot, both with identity mapped virtual addresses and proper kernel
37 * virtual addresses.
38 */
39 u8 snp_vmpl __ro_after_init;
40 EXPORT_SYMBOL_GPL(snp_vmpl);
41 static struct svsm_ca *boot_svsm_caa __ro_after_init;
42 static u64 boot_svsm_caa_pa __ro_after_init;
43
44 static struct svsm_ca *svsm_get_caa(void);
45 static u64 svsm_get_caa_pa(void);
46 static int svsm_perform_call_protocol(struct svsm_call *call);
47
48 /* I/O parameters for CPUID-related helpers */
49 struct cpuid_leaf {
50 u32 fn;
51 u32 subfn;
52 u32 eax;
53 u32 ebx;
54 u32 ecx;
55 u32 edx;
56 };
57
58 /*
59 * Individual entries of the SNP CPUID table, as defined by the SNP
60 * Firmware ABI, Revision 0.9, Section 7.1, Table 14.
61 */
62 struct snp_cpuid_fn {
63 u32 eax_in;
64 u32 ecx_in;
65 u64 xcr0_in;
66 u64 xss_in;
67 u32 eax;
68 u32 ebx;
69 u32 ecx;
70 u32 edx;
71 u64 __reserved;
72 } __packed;
73
74 /*
75 * SNP CPUID table, as defined by the SNP Firmware ABI, Revision 0.9,
76 * Section 8.14.2.6. Also noted there is the SNP firmware-enforced limit
77 * of 64 entries per CPUID table.
78 */
79 #define SNP_CPUID_COUNT_MAX 64
80
81 struct snp_cpuid_table {
82 u32 count;
83 u32 __reserved1;
84 u64 __reserved2;
85 struct snp_cpuid_fn fn[SNP_CPUID_COUNT_MAX];
86 } __packed;
87
88 /*
89 * Since feature negotiation related variables are set early in the boot
90 * process they must reside in the .data section so as not to be zeroed
91 * out when the .bss section is later cleared.
92 *
93 * GHCB protocol version negotiated with the hypervisor.
94 */
95 static u16 ghcb_version __ro_after_init;
96
97 /* Copy of the SNP firmware's CPUID page. */
98 static struct snp_cpuid_table cpuid_table_copy __ro_after_init;
99
100 /*
101 * These will be initialized based on CPUID table so that non-present
102 * all-zero leaves (for sparse tables) can be differentiated from
103 * invalid/out-of-range leaves. This is needed since all-zero leaves
104 * still need to be post-processed.
105 */
106 static u32 cpuid_std_range_max __ro_after_init;
107 static u32 cpuid_hyp_range_max __ro_after_init;
108 static u32 cpuid_ext_range_max __ro_after_init;
109
sev_es_check_cpu_features(void)110 static bool __init sev_es_check_cpu_features(void)
111 {
112 if (!has_cpuflag(X86_FEATURE_RDRAND)) {
113 error("RDRAND instruction not supported - no trusted source of randomness available\n");
114 return false;
115 }
116
117 return true;
118 }
119
120 static void __head __noreturn
sev_es_terminate(unsigned int set,unsigned int reason)121 sev_es_terminate(unsigned int set, unsigned int reason)
122 {
123 u64 val = GHCB_MSR_TERM_REQ;
124
125 /* Tell the hypervisor what went wrong. */
126 val |= GHCB_SEV_TERM_REASON(set, reason);
127
128 /* Request Guest Termination from Hypervisor */
129 sev_es_wr_ghcb_msr(val);
130 VMGEXIT();
131
132 while (true)
133 asm volatile("hlt\n" : : : "memory");
134 }
135
136 /*
137 * The hypervisor features are available from GHCB version 2 onward.
138 */
get_hv_features(void)139 static u64 get_hv_features(void)
140 {
141 u64 val;
142
143 if (ghcb_version < 2)
144 return 0;
145
146 sev_es_wr_ghcb_msr(GHCB_MSR_HV_FT_REQ);
147 VMGEXIT();
148
149 val = sev_es_rd_ghcb_msr();
150 if (GHCB_RESP_CODE(val) != GHCB_MSR_HV_FT_RESP)
151 return 0;
152
153 return GHCB_MSR_HV_FT_RESP_VAL(val);
154 }
155
snp_register_ghcb_early(unsigned long paddr)156 static void snp_register_ghcb_early(unsigned long paddr)
157 {
158 unsigned long pfn = paddr >> PAGE_SHIFT;
159 u64 val;
160
161 sev_es_wr_ghcb_msr(GHCB_MSR_REG_GPA_REQ_VAL(pfn));
162 VMGEXIT();
163
164 val = sev_es_rd_ghcb_msr();
165
166 /* If the response GPA is not ours then abort the guest */
167 if ((GHCB_RESP_CODE(val) != GHCB_MSR_REG_GPA_RESP) ||
168 (GHCB_MSR_REG_GPA_RESP_VAL(val) != pfn))
169 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_REGISTER);
170 }
171
sev_es_negotiate_protocol(void)172 static bool sev_es_negotiate_protocol(void)
173 {
174 u64 val;
175
176 /* Do the GHCB protocol version negotiation */
177 sev_es_wr_ghcb_msr(GHCB_MSR_SEV_INFO_REQ);
178 VMGEXIT();
179 val = sev_es_rd_ghcb_msr();
180
181 if (GHCB_MSR_INFO(val) != GHCB_MSR_SEV_INFO_RESP)
182 return false;
183
184 if (GHCB_MSR_PROTO_MAX(val) < GHCB_PROTOCOL_MIN ||
185 GHCB_MSR_PROTO_MIN(val) > GHCB_PROTOCOL_MAX)
186 return false;
187
188 ghcb_version = min_t(size_t, GHCB_MSR_PROTO_MAX(val), GHCB_PROTOCOL_MAX);
189
190 return true;
191 }
192
vc_ghcb_invalidate(struct ghcb * ghcb)193 static __always_inline void vc_ghcb_invalidate(struct ghcb *ghcb)
194 {
195 ghcb->save.sw_exit_code = 0;
196 __builtin_memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
197 }
198
vc_decoding_needed(unsigned long exit_code)199 static bool vc_decoding_needed(unsigned long exit_code)
200 {
201 /* Exceptions don't require to decode the instruction */
202 return !(exit_code >= SVM_EXIT_EXCP_BASE &&
203 exit_code <= SVM_EXIT_LAST_EXCP);
204 }
205
vc_init_em_ctxt(struct es_em_ctxt * ctxt,struct pt_regs * regs,unsigned long exit_code)206 static enum es_result vc_init_em_ctxt(struct es_em_ctxt *ctxt,
207 struct pt_regs *regs,
208 unsigned long exit_code)
209 {
210 enum es_result ret = ES_OK;
211
212 memset(ctxt, 0, sizeof(*ctxt));
213 ctxt->regs = regs;
214
215 if (vc_decoding_needed(exit_code))
216 ret = vc_decode_insn(ctxt);
217
218 return ret;
219 }
220
vc_finish_insn(struct es_em_ctxt * ctxt)221 static void vc_finish_insn(struct es_em_ctxt *ctxt)
222 {
223 ctxt->regs->ip += ctxt->insn.length;
224 }
225
verify_exception_info(struct ghcb * ghcb,struct es_em_ctxt * ctxt)226 static enum es_result verify_exception_info(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
227 {
228 u32 ret;
229
230 ret = ghcb->save.sw_exit_info_1 & GENMASK_ULL(31, 0);
231 if (!ret)
232 return ES_OK;
233
234 if (ret == 1) {
235 u64 info = ghcb->save.sw_exit_info_2;
236 unsigned long v = info & SVM_EVTINJ_VEC_MASK;
237
238 /* Check if exception information from hypervisor is sane. */
239 if ((info & SVM_EVTINJ_VALID) &&
240 ((v == X86_TRAP_GP) || (v == X86_TRAP_UD)) &&
241 ((info & SVM_EVTINJ_TYPE_MASK) == SVM_EVTINJ_TYPE_EXEPT)) {
242 ctxt->fi.vector = v;
243
244 if (info & SVM_EVTINJ_VALID_ERR)
245 ctxt->fi.error_code = info >> 32;
246
247 return ES_EXCEPTION;
248 }
249 }
250
251 return ES_VMM_ERROR;
252 }
253
svsm_process_result_codes(struct svsm_call * call)254 static inline int svsm_process_result_codes(struct svsm_call *call)
255 {
256 switch (call->rax_out) {
257 case SVSM_SUCCESS:
258 return 0;
259 case SVSM_ERR_INCOMPLETE:
260 case SVSM_ERR_BUSY:
261 return -EAGAIN;
262 default:
263 return -EINVAL;
264 }
265 }
266
267 /*
268 * Issue a VMGEXIT to call the SVSM:
269 * - Load the SVSM register state (RAX, RCX, RDX, R8 and R9)
270 * - Set the CA call pending field to 1
271 * - Issue VMGEXIT
272 * - Save the SVSM return register state (RAX, RCX, RDX, R8 and R9)
273 * - Perform atomic exchange of the CA call pending field
274 *
275 * - See the "Secure VM Service Module for SEV-SNP Guests" specification for
276 * details on the calling convention.
277 * - The calling convention loosely follows the Microsoft X64 calling
278 * convention by putting arguments in RCX, RDX, R8 and R9.
279 * - RAX specifies the SVSM protocol/callid as input and the return code
280 * as output.
281 */
svsm_issue_call(struct svsm_call * call,u8 * pending)282 static __always_inline void svsm_issue_call(struct svsm_call *call, u8 *pending)
283 {
284 register unsigned long rax asm("rax") = call->rax;
285 register unsigned long rcx asm("rcx") = call->rcx;
286 register unsigned long rdx asm("rdx") = call->rdx;
287 register unsigned long r8 asm("r8") = call->r8;
288 register unsigned long r9 asm("r9") = call->r9;
289
290 call->caa->call_pending = 1;
291
292 asm volatile("rep; vmmcall\n\t"
293 : "+r" (rax), "+r" (rcx), "+r" (rdx), "+r" (r8), "+r" (r9)
294 : : "memory");
295
296 *pending = xchg(&call->caa->call_pending, *pending);
297
298 call->rax_out = rax;
299 call->rcx_out = rcx;
300 call->rdx_out = rdx;
301 call->r8_out = r8;
302 call->r9_out = r9;
303 }
304
svsm_perform_msr_protocol(struct svsm_call * call)305 static int svsm_perform_msr_protocol(struct svsm_call *call)
306 {
307 u8 pending = 0;
308 u64 val, resp;
309
310 /*
311 * When using the MSR protocol, be sure to save and restore
312 * the current MSR value.
313 */
314 val = sev_es_rd_ghcb_msr();
315
316 sev_es_wr_ghcb_msr(GHCB_MSR_VMPL_REQ_LEVEL(0));
317
318 svsm_issue_call(call, &pending);
319
320 resp = sev_es_rd_ghcb_msr();
321
322 sev_es_wr_ghcb_msr(val);
323
324 if (pending)
325 return -EINVAL;
326
327 if (GHCB_RESP_CODE(resp) != GHCB_MSR_VMPL_RESP)
328 return -EINVAL;
329
330 if (GHCB_MSR_VMPL_RESP_VAL(resp))
331 return -EINVAL;
332
333 return svsm_process_result_codes(call);
334 }
335
svsm_perform_ghcb_protocol(struct ghcb * ghcb,struct svsm_call * call)336 static int svsm_perform_ghcb_protocol(struct ghcb *ghcb, struct svsm_call *call)
337 {
338 struct es_em_ctxt ctxt;
339 u8 pending = 0;
340
341 vc_ghcb_invalidate(ghcb);
342
343 /*
344 * Fill in protocol and format specifiers. This can be called very early
345 * in the boot, so use rip-relative references as needed.
346 */
347 ghcb->protocol_version = RIP_REL_REF(ghcb_version);
348 ghcb->ghcb_usage = GHCB_DEFAULT_USAGE;
349
350 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_SNP_RUN_VMPL);
351 ghcb_set_sw_exit_info_1(ghcb, 0);
352 ghcb_set_sw_exit_info_2(ghcb, 0);
353
354 sev_es_wr_ghcb_msr(__pa(ghcb));
355
356 svsm_issue_call(call, &pending);
357
358 if (pending)
359 return -EINVAL;
360
361 switch (verify_exception_info(ghcb, &ctxt)) {
362 case ES_OK:
363 break;
364 case ES_EXCEPTION:
365 vc_forward_exception(&ctxt);
366 fallthrough;
367 default:
368 return -EINVAL;
369 }
370
371 return svsm_process_result_codes(call);
372 }
373
sev_es_ghcb_hv_call(struct ghcb * ghcb,struct es_em_ctxt * ctxt,u64 exit_code,u64 exit_info_1,u64 exit_info_2)374 static enum es_result sev_es_ghcb_hv_call(struct ghcb *ghcb,
375 struct es_em_ctxt *ctxt,
376 u64 exit_code, u64 exit_info_1,
377 u64 exit_info_2)
378 {
379 /* Fill in protocol and format specifiers */
380 ghcb->protocol_version = ghcb_version;
381 ghcb->ghcb_usage = GHCB_DEFAULT_USAGE;
382
383 ghcb_set_sw_exit_code(ghcb, exit_code);
384 ghcb_set_sw_exit_info_1(ghcb, exit_info_1);
385 ghcb_set_sw_exit_info_2(ghcb, exit_info_2);
386
387 sev_es_wr_ghcb_msr(__pa(ghcb));
388 VMGEXIT();
389
390 return verify_exception_info(ghcb, ctxt);
391 }
392
__sev_cpuid_hv(u32 fn,int reg_idx,u32 * reg)393 static int __sev_cpuid_hv(u32 fn, int reg_idx, u32 *reg)
394 {
395 u64 val;
396
397 sev_es_wr_ghcb_msr(GHCB_CPUID_REQ(fn, reg_idx));
398 VMGEXIT();
399 val = sev_es_rd_ghcb_msr();
400 if (GHCB_RESP_CODE(val) != GHCB_MSR_CPUID_RESP)
401 return -EIO;
402
403 *reg = (val >> 32);
404
405 return 0;
406 }
407
__sev_cpuid_hv_msr(struct cpuid_leaf * leaf)408 static int __sev_cpuid_hv_msr(struct cpuid_leaf *leaf)
409 {
410 int ret;
411
412 /*
413 * MSR protocol does not support fetching non-zero subfunctions, but is
414 * sufficient to handle current early-boot cases. Should that change,
415 * make sure to report an error rather than ignoring the index and
416 * grabbing random values. If this issue arises in the future, handling
417 * can be added here to use GHCB-page protocol for cases that occur late
418 * enough in boot that GHCB page is available.
419 */
420 if (cpuid_function_is_indexed(leaf->fn) && leaf->subfn)
421 return -EINVAL;
422
423 ret = __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EAX, &leaf->eax);
424 ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EBX, &leaf->ebx);
425 ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_ECX, &leaf->ecx);
426 ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EDX, &leaf->edx);
427
428 return ret;
429 }
430
__sev_cpuid_hv_ghcb(struct ghcb * ghcb,struct es_em_ctxt * ctxt,struct cpuid_leaf * leaf)431 static int __sev_cpuid_hv_ghcb(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
432 {
433 u32 cr4 = native_read_cr4();
434 int ret;
435
436 ghcb_set_rax(ghcb, leaf->fn);
437 ghcb_set_rcx(ghcb, leaf->subfn);
438
439 if (cr4 & X86_CR4_OSXSAVE)
440 /* Safe to read xcr0 */
441 ghcb_set_xcr0(ghcb, xgetbv(XCR_XFEATURE_ENABLED_MASK));
442 else
443 /* xgetbv will cause #UD - use reset value for xcr0 */
444 ghcb_set_xcr0(ghcb, 1);
445
446 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_CPUID, 0, 0);
447 if (ret != ES_OK)
448 return ret;
449
450 if (!(ghcb_rax_is_valid(ghcb) &&
451 ghcb_rbx_is_valid(ghcb) &&
452 ghcb_rcx_is_valid(ghcb) &&
453 ghcb_rdx_is_valid(ghcb)))
454 return ES_VMM_ERROR;
455
456 leaf->eax = ghcb->save.rax;
457 leaf->ebx = ghcb->save.rbx;
458 leaf->ecx = ghcb->save.rcx;
459 leaf->edx = ghcb->save.rdx;
460
461 return ES_OK;
462 }
463
sev_cpuid_hv(struct ghcb * ghcb,struct es_em_ctxt * ctxt,struct cpuid_leaf * leaf)464 static int sev_cpuid_hv(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
465 {
466 return ghcb ? __sev_cpuid_hv_ghcb(ghcb, ctxt, leaf)
467 : __sev_cpuid_hv_msr(leaf);
468 }
469
470 /*
471 * This may be called early while still running on the initial identity
472 * mapping. Use RIP-relative addressing to obtain the correct address
473 * while running with the initial identity mapping as well as the
474 * switch-over to kernel virtual addresses later.
475 */
snp_cpuid_get_table(void)476 static const struct snp_cpuid_table *snp_cpuid_get_table(void)
477 {
478 return &RIP_REL_REF(cpuid_table_copy);
479 }
480
481 /*
482 * The SNP Firmware ABI, Revision 0.9, Section 7.1, details the use of
483 * XCR0_IN and XSS_IN to encode multiple versions of 0xD subfunctions 0
484 * and 1 based on the corresponding features enabled by a particular
485 * combination of XCR0 and XSS registers so that a guest can look up the
486 * version corresponding to the features currently enabled in its XCR0/XSS
487 * registers. The only values that differ between these versions/table
488 * entries is the enabled XSAVE area size advertised via EBX.
489 *
490 * While hypervisors may choose to make use of this support, it is more
491 * robust/secure for a guest to simply find the entry corresponding to the
492 * base/legacy XSAVE area size (XCR0=1 or XCR0=3), and then calculate the
493 * XSAVE area size using subfunctions 2 through 64, as documented in APM
494 * Volume 3, Rev 3.31, Appendix E.3.8, which is what is done here.
495 *
496 * Since base/legacy XSAVE area size is documented as 0x240, use that value
497 * directly rather than relying on the base size in the CPUID table.
498 *
499 * Return: XSAVE area size on success, 0 otherwise.
500 */
snp_cpuid_calc_xsave_size(u64 xfeatures_en,bool compacted)501 static u32 __head snp_cpuid_calc_xsave_size(u64 xfeatures_en, bool compacted)
502 {
503 const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
504 u64 xfeatures_found = 0;
505 u32 xsave_size = 0x240;
506 int i;
507
508 for (i = 0; i < cpuid_table->count; i++) {
509 const struct snp_cpuid_fn *e = &cpuid_table->fn[i];
510
511 if (!(e->eax_in == 0xD && e->ecx_in > 1 && e->ecx_in < 64))
512 continue;
513 if (!(xfeatures_en & (BIT_ULL(e->ecx_in))))
514 continue;
515 if (xfeatures_found & (BIT_ULL(e->ecx_in)))
516 continue;
517
518 xfeatures_found |= (BIT_ULL(e->ecx_in));
519
520 if (compacted)
521 xsave_size += e->eax;
522 else
523 xsave_size = max(xsave_size, e->eax + e->ebx);
524 }
525
526 /*
527 * Either the guest set unsupported XCR0/XSS bits, or the corresponding
528 * entries in the CPUID table were not present. This is not a valid
529 * state to be in.
530 */
531 if (xfeatures_found != (xfeatures_en & GENMASK_ULL(63, 2)))
532 return 0;
533
534 return xsave_size;
535 }
536
537 static bool __head
snp_cpuid_get_validated_func(struct cpuid_leaf * leaf)538 snp_cpuid_get_validated_func(struct cpuid_leaf *leaf)
539 {
540 const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
541 int i;
542
543 for (i = 0; i < cpuid_table->count; i++) {
544 const struct snp_cpuid_fn *e = &cpuid_table->fn[i];
545
546 if (e->eax_in != leaf->fn)
547 continue;
548
549 if (cpuid_function_is_indexed(leaf->fn) && e->ecx_in != leaf->subfn)
550 continue;
551
552 /*
553 * For 0xD subfunctions 0 and 1, only use the entry corresponding
554 * to the base/legacy XSAVE area size (XCR0=1 or XCR0=3, XSS=0).
555 * See the comments above snp_cpuid_calc_xsave_size() for more
556 * details.
557 */
558 if (e->eax_in == 0xD && (e->ecx_in == 0 || e->ecx_in == 1))
559 if (!(e->xcr0_in == 1 || e->xcr0_in == 3) || e->xss_in)
560 continue;
561
562 leaf->eax = e->eax;
563 leaf->ebx = e->ebx;
564 leaf->ecx = e->ecx;
565 leaf->edx = e->edx;
566
567 return true;
568 }
569
570 return false;
571 }
572
snp_cpuid_hv(struct ghcb * ghcb,struct es_em_ctxt * ctxt,struct cpuid_leaf * leaf)573 static void snp_cpuid_hv(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
574 {
575 if (sev_cpuid_hv(ghcb, ctxt, leaf))
576 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID_HV);
577 }
578
579 static int __head
snp_cpuid_postprocess(struct ghcb * ghcb,struct es_em_ctxt * ctxt,struct cpuid_leaf * leaf)580 snp_cpuid_postprocess(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
581 struct cpuid_leaf *leaf)
582 {
583 struct cpuid_leaf leaf_hv = *leaf;
584
585 switch (leaf->fn) {
586 case 0x1:
587 snp_cpuid_hv(ghcb, ctxt, &leaf_hv);
588
589 /* initial APIC ID */
590 leaf->ebx = (leaf_hv.ebx & GENMASK(31, 24)) | (leaf->ebx & GENMASK(23, 0));
591 /* APIC enabled bit */
592 leaf->edx = (leaf_hv.edx & BIT(9)) | (leaf->edx & ~BIT(9));
593
594 /* OSXSAVE enabled bit */
595 if (native_read_cr4() & X86_CR4_OSXSAVE)
596 leaf->ecx |= BIT(27);
597 break;
598 case 0x7:
599 /* OSPKE enabled bit */
600 leaf->ecx &= ~BIT(4);
601 if (native_read_cr4() & X86_CR4_PKE)
602 leaf->ecx |= BIT(4);
603 break;
604 case 0xB:
605 leaf_hv.subfn = 0;
606 snp_cpuid_hv(ghcb, ctxt, &leaf_hv);
607
608 /* extended APIC ID */
609 leaf->edx = leaf_hv.edx;
610 break;
611 case 0xD: {
612 bool compacted = false;
613 u64 xcr0 = 1, xss = 0;
614 u32 xsave_size;
615
616 if (leaf->subfn != 0 && leaf->subfn != 1)
617 return 0;
618
619 if (native_read_cr4() & X86_CR4_OSXSAVE)
620 xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
621 if (leaf->subfn == 1) {
622 /* Get XSS value if XSAVES is enabled. */
623 if (leaf->eax & BIT(3)) {
624 unsigned long lo, hi;
625
626 asm volatile("rdmsr" : "=a" (lo), "=d" (hi)
627 : "c" (MSR_IA32_XSS));
628 xss = (hi << 32) | lo;
629 }
630
631 /*
632 * The PPR and APM aren't clear on what size should be
633 * encoded in 0xD:0x1:EBX when compaction is not enabled
634 * by either XSAVEC (feature bit 1) or XSAVES (feature
635 * bit 3) since SNP-capable hardware has these feature
636 * bits fixed as 1. KVM sets it to 0 in this case, but
637 * to avoid this becoming an issue it's safer to simply
638 * treat this as unsupported for SNP guests.
639 */
640 if (!(leaf->eax & (BIT(1) | BIT(3))))
641 return -EINVAL;
642
643 compacted = true;
644 }
645
646 xsave_size = snp_cpuid_calc_xsave_size(xcr0 | xss, compacted);
647 if (!xsave_size)
648 return -EINVAL;
649
650 leaf->ebx = xsave_size;
651 }
652 break;
653 case 0x8000001E:
654 snp_cpuid_hv(ghcb, ctxt, &leaf_hv);
655
656 /* extended APIC ID */
657 leaf->eax = leaf_hv.eax;
658 /* compute ID */
659 leaf->ebx = (leaf->ebx & GENMASK(31, 8)) | (leaf_hv.ebx & GENMASK(7, 0));
660 /* node ID */
661 leaf->ecx = (leaf->ecx & GENMASK(31, 8)) | (leaf_hv.ecx & GENMASK(7, 0));
662 break;
663 default:
664 /* No fix-ups needed, use values as-is. */
665 break;
666 }
667
668 return 0;
669 }
670
671 /*
672 * Returns -EOPNOTSUPP if feature not enabled. Any other non-zero return value
673 * should be treated as fatal by caller.
674 */
675 static int __head
snp_cpuid(struct ghcb * ghcb,struct es_em_ctxt * ctxt,struct cpuid_leaf * leaf)676 snp_cpuid(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
677 {
678 const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
679
680 if (!cpuid_table->count)
681 return -EOPNOTSUPP;
682
683 if (!snp_cpuid_get_validated_func(leaf)) {
684 /*
685 * Some hypervisors will avoid keeping track of CPUID entries
686 * where all values are zero, since they can be handled the
687 * same as out-of-range values (all-zero). This is useful here
688 * as well as it allows virtually all guest configurations to
689 * work using a single SNP CPUID table.
690 *
691 * To allow for this, there is a need to distinguish between
692 * out-of-range entries and in-range zero entries, since the
693 * CPUID table entries are only a template that may need to be
694 * augmented with additional values for things like
695 * CPU-specific information during post-processing. So if it's
696 * not in the table, set the values to zero. Then, if they are
697 * within a valid CPUID range, proceed with post-processing
698 * using zeros as the initial values. Otherwise, skip
699 * post-processing and just return zeros immediately.
700 */
701 leaf->eax = leaf->ebx = leaf->ecx = leaf->edx = 0;
702
703 /* Skip post-processing for out-of-range zero leafs. */
704 if (!(leaf->fn <= RIP_REL_REF(cpuid_std_range_max) ||
705 (leaf->fn >= 0x40000000 && leaf->fn <= RIP_REL_REF(cpuid_hyp_range_max)) ||
706 (leaf->fn >= 0x80000000 && leaf->fn <= RIP_REL_REF(cpuid_ext_range_max))))
707 return 0;
708 }
709
710 return snp_cpuid_postprocess(ghcb, ctxt, leaf);
711 }
712
713 /*
714 * Boot VC Handler - This is the first VC handler during boot, there is no GHCB
715 * page yet, so it only supports the MSR based communication with the
716 * hypervisor and only the CPUID exit-code.
717 */
do_vc_no_ghcb(struct pt_regs * regs,unsigned long exit_code)718 void __head do_vc_no_ghcb(struct pt_regs *regs, unsigned long exit_code)
719 {
720 unsigned int subfn = lower_bits(regs->cx, 32);
721 unsigned int fn = lower_bits(regs->ax, 32);
722 u16 opcode = *(unsigned short *)regs->ip;
723 struct cpuid_leaf leaf;
724 int ret;
725
726 /* Only CPUID is supported via MSR protocol */
727 if (exit_code != SVM_EXIT_CPUID)
728 goto fail;
729
730 /* Is it really a CPUID insn? */
731 if (opcode != 0xa20f)
732 goto fail;
733
734 leaf.fn = fn;
735 leaf.subfn = subfn;
736
737 ret = snp_cpuid(NULL, NULL, &leaf);
738 if (!ret)
739 goto cpuid_done;
740
741 if (ret != -EOPNOTSUPP)
742 goto fail;
743
744 if (__sev_cpuid_hv_msr(&leaf))
745 goto fail;
746
747 cpuid_done:
748 regs->ax = leaf.eax;
749 regs->bx = leaf.ebx;
750 regs->cx = leaf.ecx;
751 regs->dx = leaf.edx;
752
753 /*
754 * This is a VC handler and the #VC is only raised when SEV-ES is
755 * active, which means SEV must be active too. Do sanity checks on the
756 * CPUID results to make sure the hypervisor does not trick the kernel
757 * into the no-sev path. This could map sensitive data unencrypted and
758 * make it accessible to the hypervisor.
759 *
760 * In particular, check for:
761 * - Availability of CPUID leaf 0x8000001f
762 * - SEV CPUID bit.
763 *
764 * The hypervisor might still report the wrong C-bit position, but this
765 * can't be checked here.
766 */
767
768 if (fn == 0x80000000 && (regs->ax < 0x8000001f))
769 /* SEV leaf check */
770 goto fail;
771 else if ((fn == 0x8000001f && !(regs->ax & BIT(1))))
772 /* SEV bit */
773 goto fail;
774
775 /* Skip over the CPUID two-byte opcode */
776 regs->ip += 2;
777
778 return;
779
780 fail:
781 /* Terminate the guest */
782 sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
783 }
784
vc_insn_string_check(struct es_em_ctxt * ctxt,unsigned long address,bool write)785 static enum es_result vc_insn_string_check(struct es_em_ctxt *ctxt,
786 unsigned long address,
787 bool write)
788 {
789 if (user_mode(ctxt->regs) && fault_in_kernel_space(address)) {
790 ctxt->fi.vector = X86_TRAP_PF;
791 ctxt->fi.error_code = X86_PF_USER;
792 ctxt->fi.cr2 = address;
793 if (write)
794 ctxt->fi.error_code |= X86_PF_WRITE;
795
796 return ES_EXCEPTION;
797 }
798
799 return ES_OK;
800 }
801
vc_insn_string_read(struct es_em_ctxt * ctxt,void * src,char * buf,unsigned int data_size,unsigned int count,bool backwards)802 static enum es_result vc_insn_string_read(struct es_em_ctxt *ctxt,
803 void *src, char *buf,
804 unsigned int data_size,
805 unsigned int count,
806 bool backwards)
807 {
808 int i, b = backwards ? -1 : 1;
809 unsigned long address = (unsigned long)src;
810 enum es_result ret;
811
812 ret = vc_insn_string_check(ctxt, address, false);
813 if (ret != ES_OK)
814 return ret;
815
816 for (i = 0; i < count; i++) {
817 void *s = src + (i * data_size * b);
818 char *d = buf + (i * data_size);
819
820 ret = vc_read_mem(ctxt, s, d, data_size);
821 if (ret != ES_OK)
822 break;
823 }
824
825 return ret;
826 }
827
vc_insn_string_write(struct es_em_ctxt * ctxt,void * dst,char * buf,unsigned int data_size,unsigned int count,bool backwards)828 static enum es_result vc_insn_string_write(struct es_em_ctxt *ctxt,
829 void *dst, char *buf,
830 unsigned int data_size,
831 unsigned int count,
832 bool backwards)
833 {
834 int i, s = backwards ? -1 : 1;
835 unsigned long address = (unsigned long)dst;
836 enum es_result ret;
837
838 ret = vc_insn_string_check(ctxt, address, true);
839 if (ret != ES_OK)
840 return ret;
841
842 for (i = 0; i < count; i++) {
843 void *d = dst + (i * data_size * s);
844 char *b = buf + (i * data_size);
845
846 ret = vc_write_mem(ctxt, d, b, data_size);
847 if (ret != ES_OK)
848 break;
849 }
850
851 return ret;
852 }
853
854 #define IOIO_TYPE_STR BIT(2)
855 #define IOIO_TYPE_IN 1
856 #define IOIO_TYPE_INS (IOIO_TYPE_IN | IOIO_TYPE_STR)
857 #define IOIO_TYPE_OUT 0
858 #define IOIO_TYPE_OUTS (IOIO_TYPE_OUT | IOIO_TYPE_STR)
859
860 #define IOIO_REP BIT(3)
861
862 #define IOIO_ADDR_64 BIT(9)
863 #define IOIO_ADDR_32 BIT(8)
864 #define IOIO_ADDR_16 BIT(7)
865
866 #define IOIO_DATA_32 BIT(6)
867 #define IOIO_DATA_16 BIT(5)
868 #define IOIO_DATA_8 BIT(4)
869
870 #define IOIO_SEG_ES (0 << 10)
871 #define IOIO_SEG_DS (3 << 10)
872
vc_ioio_exitinfo(struct es_em_ctxt * ctxt,u64 * exitinfo)873 static enum es_result vc_ioio_exitinfo(struct es_em_ctxt *ctxt, u64 *exitinfo)
874 {
875 struct insn *insn = &ctxt->insn;
876 size_t size;
877 u64 port;
878
879 *exitinfo = 0;
880
881 switch (insn->opcode.bytes[0]) {
882 /* INS opcodes */
883 case 0x6c:
884 case 0x6d:
885 *exitinfo |= IOIO_TYPE_INS;
886 *exitinfo |= IOIO_SEG_ES;
887 port = ctxt->regs->dx & 0xffff;
888 break;
889
890 /* OUTS opcodes */
891 case 0x6e:
892 case 0x6f:
893 *exitinfo |= IOIO_TYPE_OUTS;
894 *exitinfo |= IOIO_SEG_DS;
895 port = ctxt->regs->dx & 0xffff;
896 break;
897
898 /* IN immediate opcodes */
899 case 0xe4:
900 case 0xe5:
901 *exitinfo |= IOIO_TYPE_IN;
902 port = (u8)insn->immediate.value & 0xffff;
903 break;
904
905 /* OUT immediate opcodes */
906 case 0xe6:
907 case 0xe7:
908 *exitinfo |= IOIO_TYPE_OUT;
909 port = (u8)insn->immediate.value & 0xffff;
910 break;
911
912 /* IN register opcodes */
913 case 0xec:
914 case 0xed:
915 *exitinfo |= IOIO_TYPE_IN;
916 port = ctxt->regs->dx & 0xffff;
917 break;
918
919 /* OUT register opcodes */
920 case 0xee:
921 case 0xef:
922 *exitinfo |= IOIO_TYPE_OUT;
923 port = ctxt->regs->dx & 0xffff;
924 break;
925
926 default:
927 return ES_DECODE_FAILED;
928 }
929
930 *exitinfo |= port << 16;
931
932 switch (insn->opcode.bytes[0]) {
933 case 0x6c:
934 case 0x6e:
935 case 0xe4:
936 case 0xe6:
937 case 0xec:
938 case 0xee:
939 /* Single byte opcodes */
940 *exitinfo |= IOIO_DATA_8;
941 size = 1;
942 break;
943 default:
944 /* Length determined by instruction parsing */
945 *exitinfo |= (insn->opnd_bytes == 2) ? IOIO_DATA_16
946 : IOIO_DATA_32;
947 size = (insn->opnd_bytes == 2) ? 2 : 4;
948 }
949
950 switch (insn->addr_bytes) {
951 case 2:
952 *exitinfo |= IOIO_ADDR_16;
953 break;
954 case 4:
955 *exitinfo |= IOIO_ADDR_32;
956 break;
957 case 8:
958 *exitinfo |= IOIO_ADDR_64;
959 break;
960 }
961
962 if (insn_has_rep_prefix(insn))
963 *exitinfo |= IOIO_REP;
964
965 return vc_ioio_check(ctxt, (u16)port, size);
966 }
967
vc_handle_ioio(struct ghcb * ghcb,struct es_em_ctxt * ctxt)968 static enum es_result vc_handle_ioio(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
969 {
970 struct pt_regs *regs = ctxt->regs;
971 u64 exit_info_1, exit_info_2;
972 enum es_result ret;
973
974 ret = vc_ioio_exitinfo(ctxt, &exit_info_1);
975 if (ret != ES_OK)
976 return ret;
977
978 if (exit_info_1 & IOIO_TYPE_STR) {
979
980 /* (REP) INS/OUTS */
981
982 bool df = ((regs->flags & X86_EFLAGS_DF) == X86_EFLAGS_DF);
983 unsigned int io_bytes, exit_bytes;
984 unsigned int ghcb_count, op_count;
985 unsigned long es_base;
986 u64 sw_scratch;
987
988 /*
989 * For the string variants with rep prefix the amount of in/out
990 * operations per #VC exception is limited so that the kernel
991 * has a chance to take interrupts and re-schedule while the
992 * instruction is emulated.
993 */
994 io_bytes = (exit_info_1 >> 4) & 0x7;
995 ghcb_count = sizeof(ghcb->shared_buffer) / io_bytes;
996
997 op_count = (exit_info_1 & IOIO_REP) ? regs->cx : 1;
998 exit_info_2 = min(op_count, ghcb_count);
999 exit_bytes = exit_info_2 * io_bytes;
1000
1001 es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
1002
1003 /* Read bytes of OUTS into the shared buffer */
1004 if (!(exit_info_1 & IOIO_TYPE_IN)) {
1005 ret = vc_insn_string_read(ctxt,
1006 (void *)(es_base + regs->si),
1007 ghcb->shared_buffer, io_bytes,
1008 exit_info_2, df);
1009 if (ret)
1010 return ret;
1011 }
1012
1013 /*
1014 * Issue an VMGEXIT to the HV to consume the bytes from the
1015 * shared buffer or to have it write them into the shared buffer
1016 * depending on the instruction: OUTS or INS.
1017 */
1018 sw_scratch = __pa(ghcb) + offsetof(struct ghcb, shared_buffer);
1019 ghcb_set_sw_scratch(ghcb, sw_scratch);
1020 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_IOIO,
1021 exit_info_1, exit_info_2);
1022 if (ret != ES_OK)
1023 return ret;
1024
1025 /* Read bytes from shared buffer into the guest's destination. */
1026 if (exit_info_1 & IOIO_TYPE_IN) {
1027 ret = vc_insn_string_write(ctxt,
1028 (void *)(es_base + regs->di),
1029 ghcb->shared_buffer, io_bytes,
1030 exit_info_2, df);
1031 if (ret)
1032 return ret;
1033
1034 if (df)
1035 regs->di -= exit_bytes;
1036 else
1037 regs->di += exit_bytes;
1038 } else {
1039 if (df)
1040 regs->si -= exit_bytes;
1041 else
1042 regs->si += exit_bytes;
1043 }
1044
1045 if (exit_info_1 & IOIO_REP)
1046 regs->cx -= exit_info_2;
1047
1048 ret = regs->cx ? ES_RETRY : ES_OK;
1049
1050 } else {
1051
1052 /* IN/OUT into/from rAX */
1053
1054 int bits = (exit_info_1 & 0x70) >> 1;
1055 u64 rax = 0;
1056
1057 if (!(exit_info_1 & IOIO_TYPE_IN))
1058 rax = lower_bits(regs->ax, bits);
1059
1060 ghcb_set_rax(ghcb, rax);
1061
1062 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_IOIO, exit_info_1, 0);
1063 if (ret != ES_OK)
1064 return ret;
1065
1066 if (exit_info_1 & IOIO_TYPE_IN) {
1067 if (!ghcb_rax_is_valid(ghcb))
1068 return ES_VMM_ERROR;
1069 regs->ax = lower_bits(ghcb->save.rax, bits);
1070 }
1071 }
1072
1073 return ret;
1074 }
1075
vc_handle_cpuid_snp(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1076 static int vc_handle_cpuid_snp(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1077 {
1078 struct pt_regs *regs = ctxt->regs;
1079 struct cpuid_leaf leaf;
1080 int ret;
1081
1082 leaf.fn = regs->ax;
1083 leaf.subfn = regs->cx;
1084 ret = snp_cpuid(ghcb, ctxt, &leaf);
1085 if (!ret) {
1086 regs->ax = leaf.eax;
1087 regs->bx = leaf.ebx;
1088 regs->cx = leaf.ecx;
1089 regs->dx = leaf.edx;
1090 }
1091
1092 return ret;
1093 }
1094
vc_handle_cpuid(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1095 static enum es_result vc_handle_cpuid(struct ghcb *ghcb,
1096 struct es_em_ctxt *ctxt)
1097 {
1098 struct pt_regs *regs = ctxt->regs;
1099 u32 cr4 = native_read_cr4();
1100 enum es_result ret;
1101 int snp_cpuid_ret;
1102
1103 snp_cpuid_ret = vc_handle_cpuid_snp(ghcb, ctxt);
1104 if (!snp_cpuid_ret)
1105 return ES_OK;
1106 if (snp_cpuid_ret != -EOPNOTSUPP)
1107 return ES_VMM_ERROR;
1108
1109 ghcb_set_rax(ghcb, regs->ax);
1110 ghcb_set_rcx(ghcb, regs->cx);
1111
1112 if (cr4 & X86_CR4_OSXSAVE)
1113 /* Safe to read xcr0 */
1114 ghcb_set_xcr0(ghcb, xgetbv(XCR_XFEATURE_ENABLED_MASK));
1115 else
1116 /* xgetbv will cause #GP - use reset value for xcr0 */
1117 ghcb_set_xcr0(ghcb, 1);
1118
1119 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_CPUID, 0, 0);
1120 if (ret != ES_OK)
1121 return ret;
1122
1123 if (!(ghcb_rax_is_valid(ghcb) &&
1124 ghcb_rbx_is_valid(ghcb) &&
1125 ghcb_rcx_is_valid(ghcb) &&
1126 ghcb_rdx_is_valid(ghcb)))
1127 return ES_VMM_ERROR;
1128
1129 regs->ax = ghcb->save.rax;
1130 regs->bx = ghcb->save.rbx;
1131 regs->cx = ghcb->save.rcx;
1132 regs->dx = ghcb->save.rdx;
1133
1134 return ES_OK;
1135 }
1136
vc_handle_rdtsc(struct ghcb * ghcb,struct es_em_ctxt * ctxt,unsigned long exit_code)1137 static enum es_result vc_handle_rdtsc(struct ghcb *ghcb,
1138 struct es_em_ctxt *ctxt,
1139 unsigned long exit_code)
1140 {
1141 bool rdtscp = (exit_code == SVM_EXIT_RDTSCP);
1142 enum es_result ret;
1143
1144 /*
1145 * The hypervisor should not be intercepting RDTSC/RDTSCP when Secure
1146 * TSC is enabled. A #VC exception will be generated if the RDTSC/RDTSCP
1147 * instructions are being intercepted. If this should occur and Secure
1148 * TSC is enabled, guest execution should be terminated as the guest
1149 * cannot rely on the TSC value provided by the hypervisor.
1150 */
1151 if (sev_status & MSR_AMD64_SNP_SECURE_TSC)
1152 return ES_VMM_ERROR;
1153
1154 ret = sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, 0, 0);
1155 if (ret != ES_OK)
1156 return ret;
1157
1158 if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb) &&
1159 (!rdtscp || ghcb_rcx_is_valid(ghcb))))
1160 return ES_VMM_ERROR;
1161
1162 ctxt->regs->ax = ghcb->save.rax;
1163 ctxt->regs->dx = ghcb->save.rdx;
1164 if (rdtscp)
1165 ctxt->regs->cx = ghcb->save.rcx;
1166
1167 return ES_OK;
1168 }
1169
1170 struct cc_setup_data {
1171 struct setup_data header;
1172 u32 cc_blob_address;
1173 };
1174
1175 /*
1176 * Search for a Confidential Computing blob passed in as a setup_data entry
1177 * via the Linux Boot Protocol.
1178 */
1179 static __head
find_cc_blob_setup_data(struct boot_params * bp)1180 struct cc_blob_sev_info *find_cc_blob_setup_data(struct boot_params *bp)
1181 {
1182 struct cc_setup_data *sd = NULL;
1183 struct setup_data *hdr;
1184
1185 hdr = (struct setup_data *)bp->hdr.setup_data;
1186
1187 while (hdr) {
1188 if (hdr->type == SETUP_CC_BLOB) {
1189 sd = (struct cc_setup_data *)hdr;
1190 return (struct cc_blob_sev_info *)(unsigned long)sd->cc_blob_address;
1191 }
1192 hdr = (struct setup_data *)hdr->next;
1193 }
1194
1195 return NULL;
1196 }
1197
1198 /*
1199 * Initialize the kernel's copy of the SNP CPUID table, and set up the
1200 * pointer that will be used to access it.
1201 *
1202 * Maintaining a direct mapping of the SNP CPUID table used by firmware would
1203 * be possible as an alternative, but the approach is brittle since the
1204 * mapping needs to be updated in sync with all the changes to virtual memory
1205 * layout and related mapping facilities throughout the boot process.
1206 */
setup_cpuid_table(const struct cc_blob_sev_info * cc_info)1207 static void __head setup_cpuid_table(const struct cc_blob_sev_info *cc_info)
1208 {
1209 const struct snp_cpuid_table *cpuid_table_fw, *cpuid_table;
1210 int i;
1211
1212 if (!cc_info || !cc_info->cpuid_phys || cc_info->cpuid_len < PAGE_SIZE)
1213 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID);
1214
1215 cpuid_table_fw = (const struct snp_cpuid_table *)cc_info->cpuid_phys;
1216 if (!cpuid_table_fw->count || cpuid_table_fw->count > SNP_CPUID_COUNT_MAX)
1217 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID);
1218
1219 cpuid_table = snp_cpuid_get_table();
1220 memcpy((void *)cpuid_table, cpuid_table_fw, sizeof(*cpuid_table));
1221
1222 /* Initialize CPUID ranges for range-checking. */
1223 for (i = 0; i < cpuid_table->count; i++) {
1224 const struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
1225
1226 if (fn->eax_in == 0x0)
1227 RIP_REL_REF(cpuid_std_range_max) = fn->eax;
1228 else if (fn->eax_in == 0x40000000)
1229 RIP_REL_REF(cpuid_hyp_range_max) = fn->eax;
1230 else if (fn->eax_in == 0x80000000)
1231 RIP_REL_REF(cpuid_ext_range_max) = fn->eax;
1232 }
1233 }
1234
__pval_terminate(u64 pfn,bool action,unsigned int page_size,int ret,u64 svsm_ret)1235 static inline void __pval_terminate(u64 pfn, bool action, unsigned int page_size,
1236 int ret, u64 svsm_ret)
1237 {
1238 WARN(1, "PVALIDATE failure: pfn: 0x%llx, action: %u, size: %u, ret: %d, svsm_ret: 0x%llx\n",
1239 pfn, action, page_size, ret, svsm_ret);
1240
1241 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
1242 }
1243
svsm_pval_terminate(struct svsm_pvalidate_call * pc,int ret,u64 svsm_ret)1244 static void svsm_pval_terminate(struct svsm_pvalidate_call *pc, int ret, u64 svsm_ret)
1245 {
1246 unsigned int page_size;
1247 bool action;
1248 u64 pfn;
1249
1250 pfn = pc->entry[pc->cur_index].pfn;
1251 action = pc->entry[pc->cur_index].action;
1252 page_size = pc->entry[pc->cur_index].page_size;
1253
1254 __pval_terminate(pfn, action, page_size, ret, svsm_ret);
1255 }
1256
svsm_pval_4k_page(unsigned long paddr,bool validate)1257 static void __head svsm_pval_4k_page(unsigned long paddr, bool validate)
1258 {
1259 struct svsm_pvalidate_call *pc;
1260 struct svsm_call call = {};
1261 unsigned long flags;
1262 u64 pc_pa;
1263 int ret;
1264
1265 /*
1266 * This can be called very early in the boot, use native functions in
1267 * order to avoid paravirt issues.
1268 */
1269 flags = native_local_irq_save();
1270
1271 call.caa = svsm_get_caa();
1272
1273 pc = (struct svsm_pvalidate_call *)call.caa->svsm_buffer;
1274 pc_pa = svsm_get_caa_pa() + offsetof(struct svsm_ca, svsm_buffer);
1275
1276 pc->num_entries = 1;
1277 pc->cur_index = 0;
1278 pc->entry[0].page_size = RMP_PG_SIZE_4K;
1279 pc->entry[0].action = validate;
1280 pc->entry[0].ignore_cf = 0;
1281 pc->entry[0].pfn = paddr >> PAGE_SHIFT;
1282
1283 /* Protocol 0, Call ID 1 */
1284 call.rax = SVSM_CORE_CALL(SVSM_CORE_PVALIDATE);
1285 call.rcx = pc_pa;
1286
1287 ret = svsm_perform_call_protocol(&call);
1288 if (ret)
1289 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
1290
1291 native_local_irq_restore(flags);
1292 }
1293
pvalidate_4k_page(unsigned long vaddr,unsigned long paddr,bool validate)1294 static void __head pvalidate_4k_page(unsigned long vaddr, unsigned long paddr,
1295 bool validate)
1296 {
1297 int ret;
1298
1299 /*
1300 * This can be called very early during boot, so use rIP-relative
1301 * references as needed.
1302 */
1303 if (RIP_REL_REF(snp_vmpl)) {
1304 svsm_pval_4k_page(paddr, validate);
1305 } else {
1306 ret = pvalidate(vaddr, RMP_PG_SIZE_4K, validate);
1307 if (ret)
1308 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
1309 }
1310 }
1311
pval_pages(struct snp_psc_desc * desc)1312 static void pval_pages(struct snp_psc_desc *desc)
1313 {
1314 struct psc_entry *e;
1315 unsigned long vaddr;
1316 unsigned int size;
1317 unsigned int i;
1318 bool validate;
1319 u64 pfn;
1320 int rc;
1321
1322 for (i = 0; i <= desc->hdr.end_entry; i++) {
1323 e = &desc->entries[i];
1324
1325 pfn = e->gfn;
1326 vaddr = (unsigned long)pfn_to_kaddr(pfn);
1327 size = e->pagesize ? RMP_PG_SIZE_2M : RMP_PG_SIZE_4K;
1328 validate = e->operation == SNP_PAGE_STATE_PRIVATE;
1329
1330 rc = pvalidate(vaddr, size, validate);
1331 if (!rc)
1332 continue;
1333
1334 if (rc == PVALIDATE_FAIL_SIZEMISMATCH && size == RMP_PG_SIZE_2M) {
1335 unsigned long vaddr_end = vaddr + PMD_SIZE;
1336
1337 for (; vaddr < vaddr_end; vaddr += PAGE_SIZE, pfn++) {
1338 rc = pvalidate(vaddr, RMP_PG_SIZE_4K, validate);
1339 if (rc)
1340 __pval_terminate(pfn, validate, RMP_PG_SIZE_4K, rc, 0);
1341 }
1342 } else {
1343 __pval_terminate(pfn, validate, size, rc, 0);
1344 }
1345 }
1346 }
1347
svsm_build_ca_from_pfn_range(u64 pfn,u64 pfn_end,bool action,struct svsm_pvalidate_call * pc)1348 static u64 svsm_build_ca_from_pfn_range(u64 pfn, u64 pfn_end, bool action,
1349 struct svsm_pvalidate_call *pc)
1350 {
1351 struct svsm_pvalidate_entry *pe;
1352
1353 /* Nothing in the CA yet */
1354 pc->num_entries = 0;
1355 pc->cur_index = 0;
1356
1357 pe = &pc->entry[0];
1358
1359 while (pfn < pfn_end) {
1360 pe->page_size = RMP_PG_SIZE_4K;
1361 pe->action = action;
1362 pe->ignore_cf = 0;
1363 pe->pfn = pfn;
1364
1365 pe++;
1366 pfn++;
1367
1368 pc->num_entries++;
1369 if (pc->num_entries == SVSM_PVALIDATE_MAX_COUNT)
1370 break;
1371 }
1372
1373 return pfn;
1374 }
1375
svsm_build_ca_from_psc_desc(struct snp_psc_desc * desc,unsigned int desc_entry,struct svsm_pvalidate_call * pc)1376 static int svsm_build_ca_from_psc_desc(struct snp_psc_desc *desc, unsigned int desc_entry,
1377 struct svsm_pvalidate_call *pc)
1378 {
1379 struct svsm_pvalidate_entry *pe;
1380 struct psc_entry *e;
1381
1382 /* Nothing in the CA yet */
1383 pc->num_entries = 0;
1384 pc->cur_index = 0;
1385
1386 pe = &pc->entry[0];
1387 e = &desc->entries[desc_entry];
1388
1389 while (desc_entry <= desc->hdr.end_entry) {
1390 pe->page_size = e->pagesize ? RMP_PG_SIZE_2M : RMP_PG_SIZE_4K;
1391 pe->action = e->operation == SNP_PAGE_STATE_PRIVATE;
1392 pe->ignore_cf = 0;
1393 pe->pfn = e->gfn;
1394
1395 pe++;
1396 e++;
1397
1398 desc_entry++;
1399 pc->num_entries++;
1400 if (pc->num_entries == SVSM_PVALIDATE_MAX_COUNT)
1401 break;
1402 }
1403
1404 return desc_entry;
1405 }
1406
svsm_pval_pages(struct snp_psc_desc * desc)1407 static void svsm_pval_pages(struct snp_psc_desc *desc)
1408 {
1409 struct svsm_pvalidate_entry pv_4k[VMGEXIT_PSC_MAX_ENTRY];
1410 unsigned int i, pv_4k_count = 0;
1411 struct svsm_pvalidate_call *pc;
1412 struct svsm_call call = {};
1413 unsigned long flags;
1414 bool action;
1415 u64 pc_pa;
1416 int ret;
1417
1418 /*
1419 * This can be called very early in the boot, use native functions in
1420 * order to avoid paravirt issues.
1421 */
1422 flags = native_local_irq_save();
1423
1424 /*
1425 * The SVSM calling area (CA) can support processing 510 entries at a
1426 * time. Loop through the Page State Change descriptor until the CA is
1427 * full or the last entry in the descriptor is reached, at which time
1428 * the SVSM is invoked. This repeats until all entries in the descriptor
1429 * are processed.
1430 */
1431 call.caa = svsm_get_caa();
1432
1433 pc = (struct svsm_pvalidate_call *)call.caa->svsm_buffer;
1434 pc_pa = svsm_get_caa_pa() + offsetof(struct svsm_ca, svsm_buffer);
1435
1436 /* Protocol 0, Call ID 1 */
1437 call.rax = SVSM_CORE_CALL(SVSM_CORE_PVALIDATE);
1438 call.rcx = pc_pa;
1439
1440 for (i = 0; i <= desc->hdr.end_entry;) {
1441 i = svsm_build_ca_from_psc_desc(desc, i, pc);
1442
1443 do {
1444 ret = svsm_perform_call_protocol(&call);
1445 if (!ret)
1446 continue;
1447
1448 /*
1449 * Check if the entry failed because of an RMP mismatch (a
1450 * PVALIDATE at 2M was requested, but the page is mapped in
1451 * the RMP as 4K).
1452 */
1453
1454 if (call.rax_out == SVSM_PVALIDATE_FAIL_SIZEMISMATCH &&
1455 pc->entry[pc->cur_index].page_size == RMP_PG_SIZE_2M) {
1456 /* Save this entry for post-processing at 4K */
1457 pv_4k[pv_4k_count++] = pc->entry[pc->cur_index];
1458
1459 /* Skip to the next one unless at the end of the list */
1460 pc->cur_index++;
1461 if (pc->cur_index < pc->num_entries)
1462 ret = -EAGAIN;
1463 else
1464 ret = 0;
1465 }
1466 } while (ret == -EAGAIN);
1467
1468 if (ret)
1469 svsm_pval_terminate(pc, ret, call.rax_out);
1470 }
1471
1472 /* Process any entries that failed to be validated at 2M and validate them at 4K */
1473 for (i = 0; i < pv_4k_count; i++) {
1474 u64 pfn, pfn_end;
1475
1476 action = pv_4k[i].action;
1477 pfn = pv_4k[i].pfn;
1478 pfn_end = pfn + 512;
1479
1480 while (pfn < pfn_end) {
1481 pfn = svsm_build_ca_from_pfn_range(pfn, pfn_end, action, pc);
1482
1483 ret = svsm_perform_call_protocol(&call);
1484 if (ret)
1485 svsm_pval_terminate(pc, ret, call.rax_out);
1486 }
1487 }
1488
1489 native_local_irq_restore(flags);
1490 }
1491
pvalidate_pages(struct snp_psc_desc * desc)1492 static void pvalidate_pages(struct snp_psc_desc *desc)
1493 {
1494 if (snp_vmpl)
1495 svsm_pval_pages(desc);
1496 else
1497 pval_pages(desc);
1498 }
1499
vmgexit_psc(struct ghcb * ghcb,struct snp_psc_desc * desc)1500 static int vmgexit_psc(struct ghcb *ghcb, struct snp_psc_desc *desc)
1501 {
1502 int cur_entry, end_entry, ret = 0;
1503 struct snp_psc_desc *data;
1504 struct es_em_ctxt ctxt;
1505
1506 vc_ghcb_invalidate(ghcb);
1507
1508 /* Copy the input desc into GHCB shared buffer */
1509 data = (struct snp_psc_desc *)ghcb->shared_buffer;
1510 memcpy(ghcb->shared_buffer, desc, min_t(int, GHCB_SHARED_BUF_SIZE, sizeof(*desc)));
1511
1512 /*
1513 * As per the GHCB specification, the hypervisor can resume the guest
1514 * before processing all the entries. Check whether all the entries
1515 * are processed. If not, then keep retrying. Note, the hypervisor
1516 * will update the data memory directly to indicate the status, so
1517 * reference the data->hdr everywhere.
1518 *
1519 * The strategy here is to wait for the hypervisor to change the page
1520 * state in the RMP table before guest accesses the memory pages. If the
1521 * page state change was not successful, then later memory access will
1522 * result in a crash.
1523 */
1524 cur_entry = data->hdr.cur_entry;
1525 end_entry = data->hdr.end_entry;
1526
1527 while (data->hdr.cur_entry <= data->hdr.end_entry) {
1528 ghcb_set_sw_scratch(ghcb, (u64)__pa(data));
1529
1530 /* This will advance the shared buffer data points to. */
1531 ret = sev_es_ghcb_hv_call(ghcb, &ctxt, SVM_VMGEXIT_PSC, 0, 0);
1532
1533 /*
1534 * Page State Change VMGEXIT can pass error code through
1535 * exit_info_2.
1536 */
1537 if (WARN(ret || ghcb->save.sw_exit_info_2,
1538 "SNP: PSC failed ret=%d exit_info_2=%llx\n",
1539 ret, ghcb->save.sw_exit_info_2)) {
1540 ret = 1;
1541 goto out;
1542 }
1543
1544 /* Verify that reserved bit is not set */
1545 if (WARN(data->hdr.reserved, "Reserved bit is set in the PSC header\n")) {
1546 ret = 1;
1547 goto out;
1548 }
1549
1550 /*
1551 * Sanity check that entry processing is not going backwards.
1552 * This will happen only if hypervisor is tricking us.
1553 */
1554 if (WARN(data->hdr.end_entry > end_entry || cur_entry > data->hdr.cur_entry,
1555 "SNP: PSC processing going backward, end_entry %d (got %d) cur_entry %d (got %d)\n",
1556 end_entry, data->hdr.end_entry, cur_entry, data->hdr.cur_entry)) {
1557 ret = 1;
1558 goto out;
1559 }
1560 }
1561
1562 out:
1563 return ret;
1564 }
1565
vc_check_opcode_bytes(struct es_em_ctxt * ctxt,unsigned long exit_code)1566 static enum es_result vc_check_opcode_bytes(struct es_em_ctxt *ctxt,
1567 unsigned long exit_code)
1568 {
1569 unsigned int opcode = (unsigned int)ctxt->insn.opcode.value;
1570 u8 modrm = ctxt->insn.modrm.value;
1571
1572 switch (exit_code) {
1573
1574 case SVM_EXIT_IOIO:
1575 case SVM_EXIT_NPF:
1576 /* handled separately */
1577 return ES_OK;
1578
1579 case SVM_EXIT_CPUID:
1580 if (opcode == 0xa20f)
1581 return ES_OK;
1582 break;
1583
1584 case SVM_EXIT_INVD:
1585 if (opcode == 0x080f)
1586 return ES_OK;
1587 break;
1588
1589 case SVM_EXIT_MONITOR:
1590 /* MONITOR and MONITORX instructions generate the same error code */
1591 if (opcode == 0x010f && (modrm == 0xc8 || modrm == 0xfa))
1592 return ES_OK;
1593 break;
1594
1595 case SVM_EXIT_MWAIT:
1596 /* MWAIT and MWAITX instructions generate the same error code */
1597 if (opcode == 0x010f && (modrm == 0xc9 || modrm == 0xfb))
1598 return ES_OK;
1599 break;
1600
1601 case SVM_EXIT_MSR:
1602 /* RDMSR */
1603 if (opcode == 0x320f ||
1604 /* WRMSR */
1605 opcode == 0x300f)
1606 return ES_OK;
1607 break;
1608
1609 case SVM_EXIT_RDPMC:
1610 if (opcode == 0x330f)
1611 return ES_OK;
1612 break;
1613
1614 case SVM_EXIT_RDTSC:
1615 if (opcode == 0x310f)
1616 return ES_OK;
1617 break;
1618
1619 case SVM_EXIT_RDTSCP:
1620 if (opcode == 0x010f && modrm == 0xf9)
1621 return ES_OK;
1622 break;
1623
1624 case SVM_EXIT_READ_DR7:
1625 if (opcode == 0x210f &&
1626 X86_MODRM_REG(ctxt->insn.modrm.value) == 7)
1627 return ES_OK;
1628 break;
1629
1630 case SVM_EXIT_VMMCALL:
1631 if (opcode == 0x010f && modrm == 0xd9)
1632 return ES_OK;
1633
1634 break;
1635
1636 case SVM_EXIT_WRITE_DR7:
1637 if (opcode == 0x230f &&
1638 X86_MODRM_REG(ctxt->insn.modrm.value) == 7)
1639 return ES_OK;
1640 break;
1641
1642 case SVM_EXIT_WBINVD:
1643 if (opcode == 0x90f)
1644 return ES_OK;
1645 break;
1646
1647 default:
1648 break;
1649 }
1650
1651 sev_printk(KERN_ERR "Wrong/unhandled opcode bytes: 0x%x, exit_code: 0x%lx, rIP: 0x%lx\n",
1652 opcode, exit_code, ctxt->regs->ip);
1653
1654 return ES_UNSUPPORTED;
1655 }
1656
1657 /*
1658 * Maintain the GPA of the SVSM Calling Area (CA) in order to utilize the SVSM
1659 * services needed when not running in VMPL0.
1660 */
svsm_setup_ca(const struct cc_blob_sev_info * cc_info)1661 static bool __head svsm_setup_ca(const struct cc_blob_sev_info *cc_info)
1662 {
1663 struct snp_secrets_page *secrets_page;
1664 struct snp_cpuid_table *cpuid_table;
1665 unsigned int i;
1666 u64 caa;
1667
1668 BUILD_BUG_ON(sizeof(*secrets_page) != PAGE_SIZE);
1669
1670 /*
1671 * Check if running at VMPL0.
1672 *
1673 * Use RMPADJUST (see the rmpadjust() function for a description of what
1674 * the instruction does) to update the VMPL1 permissions of a page. If
1675 * the guest is running at VMPL0, this will succeed and implies there is
1676 * no SVSM. If the guest is running at any other VMPL, this will fail.
1677 * Linux SNP guests only ever run at a single VMPL level so permission mask
1678 * changes of a lesser-privileged VMPL are a don't-care.
1679 *
1680 * Use a rip-relative reference to obtain the proper address, since this
1681 * routine is running identity mapped when called, both by the decompressor
1682 * code and the early kernel code.
1683 */
1684 if (!rmpadjust((unsigned long)&RIP_REL_REF(boot_ghcb_page), RMP_PG_SIZE_4K, 1))
1685 return false;
1686
1687 /*
1688 * Not running at VMPL0, ensure everything has been properly supplied
1689 * for running under an SVSM.
1690 */
1691 if (!cc_info || !cc_info->secrets_phys || cc_info->secrets_len != PAGE_SIZE)
1692 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SECRETS_PAGE);
1693
1694 secrets_page = (struct snp_secrets_page *)cc_info->secrets_phys;
1695 if (!secrets_page->svsm_size)
1696 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_NO_SVSM);
1697
1698 if (!secrets_page->svsm_guest_vmpl)
1699 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SVSM_VMPL0);
1700
1701 RIP_REL_REF(snp_vmpl) = secrets_page->svsm_guest_vmpl;
1702
1703 caa = secrets_page->svsm_caa;
1704
1705 /*
1706 * An open-coded PAGE_ALIGNED() in order to avoid including
1707 * kernel-proper headers into the decompressor.
1708 */
1709 if (caa & (PAGE_SIZE - 1))
1710 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SVSM_CAA);
1711
1712 /*
1713 * The CA is identity mapped when this routine is called, both by the
1714 * decompressor code and the early kernel code.
1715 */
1716 RIP_REL_REF(boot_svsm_caa) = (struct svsm_ca *)caa;
1717 RIP_REL_REF(boot_svsm_caa_pa) = caa;
1718
1719 /* Advertise the SVSM presence via CPUID. */
1720 cpuid_table = (struct snp_cpuid_table *)snp_cpuid_get_table();
1721 for (i = 0; i < cpuid_table->count; i++) {
1722 struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
1723
1724 if (fn->eax_in == 0x8000001f)
1725 fn->eax |= BIT(28);
1726 }
1727
1728 return true;
1729 }
1730