Mention branches and keyring.
[releases.git] / x86 / kernel / sev-shared.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * AMD Encrypted Register State Support
4  *
5  * Author: Joerg Roedel <jroedel@suse.de>
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 #ifndef __BOOT_COMPRESSED
13 #define error(v)        pr_err(v)
14 #define has_cpuflag(f)  boot_cpu_has(f)
15 #endif
16
17 /* I/O parameters for CPUID-related helpers */
18 struct cpuid_leaf {
19         u32 fn;
20         u32 subfn;
21         u32 eax;
22         u32 ebx;
23         u32 ecx;
24         u32 edx;
25 };
26
27 /*
28  * Individual entries of the SNP CPUID table, as defined by the SNP
29  * Firmware ABI, Revision 0.9, Section 7.1, Table 14.
30  */
31 struct snp_cpuid_fn {
32         u32 eax_in;
33         u32 ecx_in;
34         u64 xcr0_in;
35         u64 xss_in;
36         u32 eax;
37         u32 ebx;
38         u32 ecx;
39         u32 edx;
40         u64 __reserved;
41 } __packed;
42
43 /*
44  * SNP CPUID table, as defined by the SNP Firmware ABI, Revision 0.9,
45  * Section 8.14.2.6. Also noted there is the SNP firmware-enforced limit
46  * of 64 entries per CPUID table.
47  */
48 #define SNP_CPUID_COUNT_MAX 64
49
50 struct snp_cpuid_table {
51         u32 count;
52         u32 __reserved1;
53         u64 __reserved2;
54         struct snp_cpuid_fn fn[SNP_CPUID_COUNT_MAX];
55 } __packed;
56
57 /*
58  * Since feature negotiation related variables are set early in the boot
59  * process they must reside in the .data section so as not to be zeroed
60  * out when the .bss section is later cleared.
61  *
62  * GHCB protocol version negotiated with the hypervisor.
63  */
64 static u16 ghcb_version __ro_after_init;
65
66 /* Copy of the SNP firmware's CPUID page. */
67 static struct snp_cpuid_table cpuid_table_copy __ro_after_init;
68
69 /*
70  * These will be initialized based on CPUID table so that non-present
71  * all-zero leaves (for sparse tables) can be differentiated from
72  * invalid/out-of-range leaves. This is needed since all-zero leaves
73  * still need to be post-processed.
74  */
75 static u32 cpuid_std_range_max __ro_after_init;
76 static u32 cpuid_hyp_range_max __ro_after_init;
77 static u32 cpuid_ext_range_max __ro_after_init;
78
79 static bool __init sev_es_check_cpu_features(void)
80 {
81         if (!has_cpuflag(X86_FEATURE_RDRAND)) {
82                 error("RDRAND instruction not supported - no trusted source of randomness available\n");
83                 return false;
84         }
85
86         return true;
87 }
88
89 static void __head __noreturn
90 sev_es_terminate(unsigned int set, unsigned int reason)
91 {
92         u64 val = GHCB_MSR_TERM_REQ;
93
94         /* Tell the hypervisor what went wrong. */
95         val |= GHCB_SEV_TERM_REASON(set, reason);
96
97         /* Request Guest Termination from Hypvervisor */
98         sev_es_wr_ghcb_msr(val);
99         VMGEXIT();
100
101         while (true)
102                 asm volatile("hlt\n" : : : "memory");
103 }
104
105 /*
106  * The hypervisor features are available from GHCB version 2 onward.
107  */
108 static u64 get_hv_features(void)
109 {
110         u64 val;
111
112         if (ghcb_version < 2)
113                 return 0;
114
115         sev_es_wr_ghcb_msr(GHCB_MSR_HV_FT_REQ);
116         VMGEXIT();
117
118         val = sev_es_rd_ghcb_msr();
119         if (GHCB_RESP_CODE(val) != GHCB_MSR_HV_FT_RESP)
120                 return 0;
121
122         return GHCB_MSR_HV_FT_RESP_VAL(val);
123 }
124
125 static void snp_register_ghcb_early(unsigned long paddr)
126 {
127         unsigned long pfn = paddr >> PAGE_SHIFT;
128         u64 val;
129
130         sev_es_wr_ghcb_msr(GHCB_MSR_REG_GPA_REQ_VAL(pfn));
131         VMGEXIT();
132
133         val = sev_es_rd_ghcb_msr();
134
135         /* If the response GPA is not ours then abort the guest */
136         if ((GHCB_RESP_CODE(val) != GHCB_MSR_REG_GPA_RESP) ||
137             (GHCB_MSR_REG_GPA_RESP_VAL(val) != pfn))
138                 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_REGISTER);
139 }
140
141 static bool sev_es_negotiate_protocol(void)
142 {
143         u64 val;
144
145         /* Do the GHCB protocol version negotiation */
146         sev_es_wr_ghcb_msr(GHCB_MSR_SEV_INFO_REQ);
147         VMGEXIT();
148         val = sev_es_rd_ghcb_msr();
149
150         if (GHCB_MSR_INFO(val) != GHCB_MSR_SEV_INFO_RESP)
151                 return false;
152
153         if (GHCB_MSR_PROTO_MAX(val) < GHCB_PROTOCOL_MIN ||
154             GHCB_MSR_PROTO_MIN(val) > GHCB_PROTOCOL_MAX)
155                 return false;
156
157         ghcb_version = min_t(size_t, GHCB_MSR_PROTO_MAX(val), GHCB_PROTOCOL_MAX);
158
159         return true;
160 }
161
162 static __always_inline void vc_ghcb_invalidate(struct ghcb *ghcb)
163 {
164         ghcb->save.sw_exit_code = 0;
165         __builtin_memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
166 }
167
168 static bool vc_decoding_needed(unsigned long exit_code)
169 {
170         /* Exceptions don't require to decode the instruction */
171         return !(exit_code >= SVM_EXIT_EXCP_BASE &&
172                  exit_code <= SVM_EXIT_LAST_EXCP);
173 }
174
175 static enum es_result vc_init_em_ctxt(struct es_em_ctxt *ctxt,
176                                       struct pt_regs *regs,
177                                       unsigned long exit_code)
178 {
179         enum es_result ret = ES_OK;
180
181         memset(ctxt, 0, sizeof(*ctxt));
182         ctxt->regs = regs;
183
184         if (vc_decoding_needed(exit_code))
185                 ret = vc_decode_insn(ctxt);
186
187         return ret;
188 }
189
190 static void vc_finish_insn(struct es_em_ctxt *ctxt)
191 {
192         ctxt->regs->ip += ctxt->insn.length;
193 }
194
195 static enum es_result verify_exception_info(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
196 {
197         u32 ret;
198
199         ret = ghcb->save.sw_exit_info_1 & GENMASK_ULL(31, 0);
200         if (!ret)
201                 return ES_OK;
202
203         if (ret == 1) {
204                 u64 info = ghcb->save.sw_exit_info_2;
205                 unsigned long v = info & SVM_EVTINJ_VEC_MASK;
206
207                 /* Check if exception information from hypervisor is sane. */
208                 if ((info & SVM_EVTINJ_VALID) &&
209                     ((v == X86_TRAP_GP) || (v == X86_TRAP_UD)) &&
210                     ((info & SVM_EVTINJ_TYPE_MASK) == SVM_EVTINJ_TYPE_EXEPT)) {
211                         ctxt->fi.vector = v;
212
213                         if (info & SVM_EVTINJ_VALID_ERR)
214                                 ctxt->fi.error_code = info >> 32;
215
216                         return ES_EXCEPTION;
217                 }
218         }
219
220         return ES_VMM_ERROR;
221 }
222
223 static enum es_result sev_es_ghcb_hv_call(struct ghcb *ghcb,
224                                           struct es_em_ctxt *ctxt,
225                                           u64 exit_code, u64 exit_info_1,
226                                           u64 exit_info_2)
227 {
228         /* Fill in protocol and format specifiers */
229         ghcb->protocol_version = ghcb_version;
230         ghcb->ghcb_usage       = GHCB_DEFAULT_USAGE;
231
232         ghcb_set_sw_exit_code(ghcb, exit_code);
233         ghcb_set_sw_exit_info_1(ghcb, exit_info_1);
234         ghcb_set_sw_exit_info_2(ghcb, exit_info_2);
235
236         sev_es_wr_ghcb_msr(__pa(ghcb));
237         VMGEXIT();
238
239         return verify_exception_info(ghcb, ctxt);
240 }
241
242 static int __sev_cpuid_hv(u32 fn, int reg_idx, u32 *reg)
243 {
244         u64 val;
245
246         sev_es_wr_ghcb_msr(GHCB_CPUID_REQ(fn, reg_idx));
247         VMGEXIT();
248         val = sev_es_rd_ghcb_msr();
249         if (GHCB_RESP_CODE(val) != GHCB_MSR_CPUID_RESP)
250                 return -EIO;
251
252         *reg = (val >> 32);
253
254         return 0;
255 }
256
257 static int __sev_cpuid_hv_msr(struct cpuid_leaf *leaf)
258 {
259         int ret;
260
261         /*
262          * MSR protocol does not support fetching non-zero subfunctions, but is
263          * sufficient to handle current early-boot cases. Should that change,
264          * make sure to report an error rather than ignoring the index and
265          * grabbing random values. If this issue arises in the future, handling
266          * can be added here to use GHCB-page protocol for cases that occur late
267          * enough in boot that GHCB page is available.
268          */
269         if (cpuid_function_is_indexed(leaf->fn) && leaf->subfn)
270                 return -EINVAL;
271
272         ret =         __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EAX, &leaf->eax);
273         ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EBX, &leaf->ebx);
274         ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_ECX, &leaf->ecx);
275         ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EDX, &leaf->edx);
276
277         return ret;
278 }
279
280 static int __sev_cpuid_hv_ghcb(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
281 {
282         u32 cr4 = native_read_cr4();
283         int ret;
284
285         ghcb_set_rax(ghcb, leaf->fn);
286         ghcb_set_rcx(ghcb, leaf->subfn);
287
288         if (cr4 & X86_CR4_OSXSAVE)
289                 /* Safe to read xcr0 */
290                 ghcb_set_xcr0(ghcb, xgetbv(XCR_XFEATURE_ENABLED_MASK));
291         else
292                 /* xgetbv will cause #UD - use reset value for xcr0 */
293                 ghcb_set_xcr0(ghcb, 1);
294
295         ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_CPUID, 0, 0);
296         if (ret != ES_OK)
297                 return ret;
298
299         if (!(ghcb_rax_is_valid(ghcb) &&
300               ghcb_rbx_is_valid(ghcb) &&
301               ghcb_rcx_is_valid(ghcb) &&
302               ghcb_rdx_is_valid(ghcb)))
303                 return ES_VMM_ERROR;
304
305         leaf->eax = ghcb->save.rax;
306         leaf->ebx = ghcb->save.rbx;
307         leaf->ecx = ghcb->save.rcx;
308         leaf->edx = ghcb->save.rdx;
309
310         return ES_OK;
311 }
312
313 static int sev_cpuid_hv(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
314 {
315         return ghcb ? __sev_cpuid_hv_ghcb(ghcb, ctxt, leaf)
316                     : __sev_cpuid_hv_msr(leaf);
317 }
318
319 /*
320  * This may be called early while still running on the initial identity
321  * mapping. Use RIP-relative addressing to obtain the correct address
322  * while running with the initial identity mapping as well as the
323  * switch-over to kernel virtual addresses later.
324  */
325 static const struct snp_cpuid_table *snp_cpuid_get_table(void)
326 {
327         return &RIP_REL_REF(cpuid_table_copy);
328 }
329
330 /*
331  * The SNP Firmware ABI, Revision 0.9, Section 7.1, details the use of
332  * XCR0_IN and XSS_IN to encode multiple versions of 0xD subfunctions 0
333  * and 1 based on the corresponding features enabled by a particular
334  * combination of XCR0 and XSS registers so that a guest can look up the
335  * version corresponding to the features currently enabled in its XCR0/XSS
336  * registers. The only values that differ between these versions/table
337  * entries is the enabled XSAVE area size advertised via EBX.
338  *
339  * While hypervisors may choose to make use of this support, it is more
340  * robust/secure for a guest to simply find the entry corresponding to the
341  * base/legacy XSAVE area size (XCR0=1 or XCR0=3), and then calculate the
342  * XSAVE area size using subfunctions 2 through 64, as documented in APM
343  * Volume 3, Rev 3.31, Appendix E.3.8, which is what is done here.
344  *
345  * Since base/legacy XSAVE area size is documented as 0x240, use that value
346  * directly rather than relying on the base size in the CPUID table.
347  *
348  * Return: XSAVE area size on success, 0 otherwise.
349  */
350 static u32 snp_cpuid_calc_xsave_size(u64 xfeatures_en, bool compacted)
351 {
352         const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
353         u64 xfeatures_found = 0;
354         u32 xsave_size = 0x240;
355         int i;
356
357         for (i = 0; i < cpuid_table->count; i++) {
358                 const struct snp_cpuid_fn *e = &cpuid_table->fn[i];
359
360                 if (!(e->eax_in == 0xD && e->ecx_in > 1 && e->ecx_in < 64))
361                         continue;
362                 if (!(xfeatures_en & (BIT_ULL(e->ecx_in))))
363                         continue;
364                 if (xfeatures_found & (BIT_ULL(e->ecx_in)))
365                         continue;
366
367                 xfeatures_found |= (BIT_ULL(e->ecx_in));
368
369                 if (compacted)
370                         xsave_size += e->eax;
371                 else
372                         xsave_size = max(xsave_size, e->eax + e->ebx);
373         }
374
375         /*
376          * Either the guest set unsupported XCR0/XSS bits, or the corresponding
377          * entries in the CPUID table were not present. This is not a valid
378          * state to be in.
379          */
380         if (xfeatures_found != (xfeatures_en & GENMASK_ULL(63, 2)))
381                 return 0;
382
383         return xsave_size;
384 }
385
386 static bool __head
387 snp_cpuid_get_validated_func(struct cpuid_leaf *leaf)
388 {
389         const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
390         int i;
391
392         for (i = 0; i < cpuid_table->count; i++) {
393                 const struct snp_cpuid_fn *e = &cpuid_table->fn[i];
394
395                 if (e->eax_in != leaf->fn)
396                         continue;
397
398                 if (cpuid_function_is_indexed(leaf->fn) && e->ecx_in != leaf->subfn)
399                         continue;
400
401                 /*
402                  * For 0xD subfunctions 0 and 1, only use the entry corresponding
403                  * to the base/legacy XSAVE area size (XCR0=1 or XCR0=3, XSS=0).
404                  * See the comments above snp_cpuid_calc_xsave_size() for more
405                  * details.
406                  */
407                 if (e->eax_in == 0xD && (e->ecx_in == 0 || e->ecx_in == 1))
408                         if (!(e->xcr0_in == 1 || e->xcr0_in == 3) || e->xss_in)
409                                 continue;
410
411                 leaf->eax = e->eax;
412                 leaf->ebx = e->ebx;
413                 leaf->ecx = e->ecx;
414                 leaf->edx = e->edx;
415
416                 return true;
417         }
418
419         return false;
420 }
421
422 static void snp_cpuid_hv(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
423 {
424         if (sev_cpuid_hv(ghcb, ctxt, leaf))
425                 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID_HV);
426 }
427
428 static int snp_cpuid_postprocess(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
429                                  struct cpuid_leaf *leaf)
430 {
431         struct cpuid_leaf leaf_hv = *leaf;
432
433         switch (leaf->fn) {
434         case 0x1:
435                 snp_cpuid_hv(ghcb, ctxt, &leaf_hv);
436
437                 /* initial APIC ID */
438                 leaf->ebx = (leaf_hv.ebx & GENMASK(31, 24)) | (leaf->ebx & GENMASK(23, 0));
439                 /* APIC enabled bit */
440                 leaf->edx = (leaf_hv.edx & BIT(9)) | (leaf->edx & ~BIT(9));
441
442                 /* OSXSAVE enabled bit */
443                 if (native_read_cr4() & X86_CR4_OSXSAVE)
444                         leaf->ecx |= BIT(27);
445                 break;
446         case 0x7:
447                 /* OSPKE enabled bit */
448                 leaf->ecx &= ~BIT(4);
449                 if (native_read_cr4() & X86_CR4_PKE)
450                         leaf->ecx |= BIT(4);
451                 break;
452         case 0xB:
453                 leaf_hv.subfn = 0;
454                 snp_cpuid_hv(ghcb, ctxt, &leaf_hv);
455
456                 /* extended APIC ID */
457                 leaf->edx = leaf_hv.edx;
458                 break;
459         case 0xD: {
460                 bool compacted = false;
461                 u64 xcr0 = 1, xss = 0;
462                 u32 xsave_size;
463
464                 if (leaf->subfn != 0 && leaf->subfn != 1)
465                         return 0;
466
467                 if (native_read_cr4() & X86_CR4_OSXSAVE)
468                         xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
469                 if (leaf->subfn == 1) {
470                         /* Get XSS value if XSAVES is enabled. */
471                         if (leaf->eax & BIT(3)) {
472                                 unsigned long lo, hi;
473
474                                 asm volatile("rdmsr" : "=a" (lo), "=d" (hi)
475                                                      : "c" (MSR_IA32_XSS));
476                                 xss = (hi << 32) | lo;
477                         }
478
479                         /*
480                          * The PPR and APM aren't clear on what size should be
481                          * encoded in 0xD:0x1:EBX when compaction is not enabled
482                          * by either XSAVEC (feature bit 1) or XSAVES (feature
483                          * bit 3) since SNP-capable hardware has these feature
484                          * bits fixed as 1. KVM sets it to 0 in this case, but
485                          * to avoid this becoming an issue it's safer to simply
486                          * treat this as unsupported for SNP guests.
487                          */
488                         if (!(leaf->eax & (BIT(1) | BIT(3))))
489                                 return -EINVAL;
490
491                         compacted = true;
492                 }
493
494                 xsave_size = snp_cpuid_calc_xsave_size(xcr0 | xss, compacted);
495                 if (!xsave_size)
496                         return -EINVAL;
497
498                 leaf->ebx = xsave_size;
499                 }
500                 break;
501         case 0x8000001E:
502                 snp_cpuid_hv(ghcb, ctxt, &leaf_hv);
503
504                 /* extended APIC ID */
505                 leaf->eax = leaf_hv.eax;
506                 /* compute ID */
507                 leaf->ebx = (leaf->ebx & GENMASK(31, 8)) | (leaf_hv.ebx & GENMASK(7, 0));
508                 /* node ID */
509                 leaf->ecx = (leaf->ecx & GENMASK(31, 8)) | (leaf_hv.ecx & GENMASK(7, 0));
510                 break;
511         default:
512                 /* No fix-ups needed, use values as-is. */
513                 break;
514         }
515
516         return 0;
517 }
518
519 /*
520  * Returns -EOPNOTSUPP if feature not enabled. Any other non-zero return value
521  * should be treated as fatal by caller.
522  */
523 static int __head
524 snp_cpuid(struct ghcb *ghcb, struct es_em_ctxt *ctxt, struct cpuid_leaf *leaf)
525 {
526         const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
527
528         if (!cpuid_table->count)
529                 return -EOPNOTSUPP;
530
531         if (!snp_cpuid_get_validated_func(leaf)) {
532                 /*
533                  * Some hypervisors will avoid keeping track of CPUID entries
534                  * where all values are zero, since they can be handled the
535                  * same as out-of-range values (all-zero). This is useful here
536                  * as well as it allows virtually all guest configurations to
537                  * work using a single SNP CPUID table.
538                  *
539                  * To allow for this, there is a need to distinguish between
540                  * out-of-range entries and in-range zero entries, since the
541                  * CPUID table entries are only a template that may need to be
542                  * augmented with additional values for things like
543                  * CPU-specific information during post-processing. So if it's
544                  * not in the table, set the values to zero. Then, if they are
545                  * within a valid CPUID range, proceed with post-processing
546                  * using zeros as the initial values. Otherwise, skip
547                  * post-processing and just return zeros immediately.
548                  */
549                 leaf->eax = leaf->ebx = leaf->ecx = leaf->edx = 0;
550
551                 /* Skip post-processing for out-of-range zero leafs. */
552                 if (!(leaf->fn <= RIP_REL_REF(cpuid_std_range_max) ||
553                       (leaf->fn >= 0x40000000 && leaf->fn <= RIP_REL_REF(cpuid_hyp_range_max)) ||
554                       (leaf->fn >= 0x80000000 && leaf->fn <= RIP_REL_REF(cpuid_ext_range_max))))
555                         return 0;
556         }
557
558         return snp_cpuid_postprocess(ghcb, ctxt, leaf);
559 }
560
561 /*
562  * Boot VC Handler - This is the first VC handler during boot, there is no GHCB
563  * page yet, so it only supports the MSR based communication with the
564  * hypervisor and only the CPUID exit-code.
565  */
566 void __head do_vc_no_ghcb(struct pt_regs *regs, unsigned long exit_code)
567 {
568         unsigned int subfn = lower_bits(regs->cx, 32);
569         unsigned int fn = lower_bits(regs->ax, 32);
570         struct cpuid_leaf leaf;
571         int ret;
572
573         /* Only CPUID is supported via MSR protocol */
574         if (exit_code != SVM_EXIT_CPUID)
575                 goto fail;
576
577         leaf.fn = fn;
578         leaf.subfn = subfn;
579
580         ret = snp_cpuid(NULL, NULL, &leaf);
581         if (!ret)
582                 goto cpuid_done;
583
584         if (ret != -EOPNOTSUPP)
585                 goto fail;
586
587         if (__sev_cpuid_hv_msr(&leaf))
588                 goto fail;
589
590 cpuid_done:
591         regs->ax = leaf.eax;
592         regs->bx = leaf.ebx;
593         regs->cx = leaf.ecx;
594         regs->dx = leaf.edx;
595
596         /*
597          * This is a VC handler and the #VC is only raised when SEV-ES is
598          * active, which means SEV must be active too. Do sanity checks on the
599          * CPUID results to make sure the hypervisor does not trick the kernel
600          * into the no-sev path. This could map sensitive data unencrypted and
601          * make it accessible to the hypervisor.
602          *
603          * In particular, check for:
604          *      - Availability of CPUID leaf 0x8000001f
605          *      - SEV CPUID bit.
606          *
607          * The hypervisor might still report the wrong C-bit position, but this
608          * can't be checked here.
609          */
610
611         if (fn == 0x80000000 && (regs->ax < 0x8000001f))
612                 /* SEV leaf check */
613                 goto fail;
614         else if ((fn == 0x8000001f && !(regs->ax & BIT(1))))
615                 /* SEV bit */
616                 goto fail;
617
618         /* Skip over the CPUID two-byte opcode */
619         regs->ip += 2;
620
621         return;
622
623 fail:
624         /* Terminate the guest */
625         sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
626 }
627
628 static enum es_result vc_insn_string_check(struct es_em_ctxt *ctxt,
629                                            unsigned long address,
630                                            bool write)
631 {
632         if (user_mode(ctxt->regs) && fault_in_kernel_space(address)) {
633                 ctxt->fi.vector     = X86_TRAP_PF;
634                 ctxt->fi.error_code = X86_PF_USER;
635                 ctxt->fi.cr2        = address;
636                 if (write)
637                         ctxt->fi.error_code |= X86_PF_WRITE;
638
639                 return ES_EXCEPTION;
640         }
641
642         return ES_OK;
643 }
644
645 static enum es_result vc_insn_string_read(struct es_em_ctxt *ctxt,
646                                           void *src, char *buf,
647                                           unsigned int data_size,
648                                           unsigned int count,
649                                           bool backwards)
650 {
651         int i, b = backwards ? -1 : 1;
652         unsigned long address = (unsigned long)src;
653         enum es_result ret;
654
655         ret = vc_insn_string_check(ctxt, address, false);
656         if (ret != ES_OK)
657                 return ret;
658
659         for (i = 0; i < count; i++) {
660                 void *s = src + (i * data_size * b);
661                 char *d = buf + (i * data_size);
662
663                 ret = vc_read_mem(ctxt, s, d, data_size);
664                 if (ret != ES_OK)
665                         break;
666         }
667
668         return ret;
669 }
670
671 static enum es_result vc_insn_string_write(struct es_em_ctxt *ctxt,
672                                            void *dst, char *buf,
673                                            unsigned int data_size,
674                                            unsigned int count,
675                                            bool backwards)
676 {
677         int i, s = backwards ? -1 : 1;
678         unsigned long address = (unsigned long)dst;
679         enum es_result ret;
680
681         ret = vc_insn_string_check(ctxt, address, true);
682         if (ret != ES_OK)
683                 return ret;
684
685         for (i = 0; i < count; i++) {
686                 void *d = dst + (i * data_size * s);
687                 char *b = buf + (i * data_size);
688
689                 ret = vc_write_mem(ctxt, d, b, data_size);
690                 if (ret != ES_OK)
691                         break;
692         }
693
694         return ret;
695 }
696
697 #define IOIO_TYPE_STR  BIT(2)
698 #define IOIO_TYPE_IN   1
699 #define IOIO_TYPE_INS  (IOIO_TYPE_IN | IOIO_TYPE_STR)
700 #define IOIO_TYPE_OUT  0
701 #define IOIO_TYPE_OUTS (IOIO_TYPE_OUT | IOIO_TYPE_STR)
702
703 #define IOIO_REP       BIT(3)
704
705 #define IOIO_ADDR_64   BIT(9)
706 #define IOIO_ADDR_32   BIT(8)
707 #define IOIO_ADDR_16   BIT(7)
708
709 #define IOIO_DATA_32   BIT(6)
710 #define IOIO_DATA_16   BIT(5)
711 #define IOIO_DATA_8    BIT(4)
712
713 #define IOIO_SEG_ES    (0 << 10)
714 #define IOIO_SEG_DS    (3 << 10)
715
716 static enum es_result vc_ioio_exitinfo(struct es_em_ctxt *ctxt, u64 *exitinfo)
717 {
718         struct insn *insn = &ctxt->insn;
719         size_t size;
720         u64 port;
721
722         *exitinfo = 0;
723
724         switch (insn->opcode.bytes[0]) {
725         /* INS opcodes */
726         case 0x6c:
727         case 0x6d:
728                 *exitinfo |= IOIO_TYPE_INS;
729                 *exitinfo |= IOIO_SEG_ES;
730                 port       = ctxt->regs->dx & 0xffff;
731                 break;
732
733         /* OUTS opcodes */
734         case 0x6e:
735         case 0x6f:
736                 *exitinfo |= IOIO_TYPE_OUTS;
737                 *exitinfo |= IOIO_SEG_DS;
738                 port       = ctxt->regs->dx & 0xffff;
739                 break;
740
741         /* IN immediate opcodes */
742         case 0xe4:
743         case 0xe5:
744                 *exitinfo |= IOIO_TYPE_IN;
745                 port       = (u8)insn->immediate.value & 0xffff;
746                 break;
747
748         /* OUT immediate opcodes */
749         case 0xe6:
750         case 0xe7:
751                 *exitinfo |= IOIO_TYPE_OUT;
752                 port       = (u8)insn->immediate.value & 0xffff;
753                 break;
754
755         /* IN register opcodes */
756         case 0xec:
757         case 0xed:
758                 *exitinfo |= IOIO_TYPE_IN;
759                 port       = ctxt->regs->dx & 0xffff;
760                 break;
761
762         /* OUT register opcodes */
763         case 0xee:
764         case 0xef:
765                 *exitinfo |= IOIO_TYPE_OUT;
766                 port       = ctxt->regs->dx & 0xffff;
767                 break;
768
769         default:
770                 return ES_DECODE_FAILED;
771         }
772
773         *exitinfo |= port << 16;
774
775         switch (insn->opcode.bytes[0]) {
776         case 0x6c:
777         case 0x6e:
778         case 0xe4:
779         case 0xe6:
780         case 0xec:
781         case 0xee:
782                 /* Single byte opcodes */
783                 *exitinfo |= IOIO_DATA_8;
784                 size       = 1;
785                 break;
786         default:
787                 /* Length determined by instruction parsing */
788                 *exitinfo |= (insn->opnd_bytes == 2) ? IOIO_DATA_16
789                                                      : IOIO_DATA_32;
790                 size       = (insn->opnd_bytes == 2) ? 2 : 4;
791         }
792
793         switch (insn->addr_bytes) {
794         case 2:
795                 *exitinfo |= IOIO_ADDR_16;
796                 break;
797         case 4:
798                 *exitinfo |= IOIO_ADDR_32;
799                 break;
800         case 8:
801                 *exitinfo |= IOIO_ADDR_64;
802                 break;
803         }
804
805         if (insn_has_rep_prefix(insn))
806                 *exitinfo |= IOIO_REP;
807
808         return vc_ioio_check(ctxt, (u16)port, size);
809 }
810
811 static enum es_result vc_handle_ioio(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
812 {
813         struct pt_regs *regs = ctxt->regs;
814         u64 exit_info_1, exit_info_2;
815         enum es_result ret;
816
817         ret = vc_ioio_exitinfo(ctxt, &exit_info_1);
818         if (ret != ES_OK)
819                 return ret;
820
821         if (exit_info_1 & IOIO_TYPE_STR) {
822
823                 /* (REP) INS/OUTS */
824
825                 bool df = ((regs->flags & X86_EFLAGS_DF) == X86_EFLAGS_DF);
826                 unsigned int io_bytes, exit_bytes;
827                 unsigned int ghcb_count, op_count;
828                 unsigned long es_base;
829                 u64 sw_scratch;
830
831                 /*
832                  * For the string variants with rep prefix the amount of in/out
833                  * operations per #VC exception is limited so that the kernel
834                  * has a chance to take interrupts and re-schedule while the
835                  * instruction is emulated.
836                  */
837                 io_bytes   = (exit_info_1 >> 4) & 0x7;
838                 ghcb_count = sizeof(ghcb->shared_buffer) / io_bytes;
839
840                 op_count    = (exit_info_1 & IOIO_REP) ? regs->cx : 1;
841                 exit_info_2 = min(op_count, ghcb_count);
842                 exit_bytes  = exit_info_2 * io_bytes;
843
844                 es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
845
846                 /* Read bytes of OUTS into the shared buffer */
847                 if (!(exit_info_1 & IOIO_TYPE_IN)) {
848                         ret = vc_insn_string_read(ctxt,
849                                                (void *)(es_base + regs->si),
850                                                ghcb->shared_buffer, io_bytes,
851                                                exit_info_2, df);
852                         if (ret)
853                                 return ret;
854                 }
855
856                 /*
857                  * Issue an VMGEXIT to the HV to consume the bytes from the
858                  * shared buffer or to have it write them into the shared buffer
859                  * depending on the instruction: OUTS or INS.
860                  */
861                 sw_scratch = __pa(ghcb) + offsetof(struct ghcb, shared_buffer);
862                 ghcb_set_sw_scratch(ghcb, sw_scratch);
863                 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_IOIO,
864                                           exit_info_1, exit_info_2);
865                 if (ret != ES_OK)
866                         return ret;
867
868                 /* Read bytes from shared buffer into the guest's destination. */
869                 if (exit_info_1 & IOIO_TYPE_IN) {
870                         ret = vc_insn_string_write(ctxt,
871                                                    (void *)(es_base + regs->di),
872                                                    ghcb->shared_buffer, io_bytes,
873                                                    exit_info_2, df);
874                         if (ret)
875                                 return ret;
876
877                         if (df)
878                                 regs->di -= exit_bytes;
879                         else
880                                 regs->di += exit_bytes;
881                 } else {
882                         if (df)
883                                 regs->si -= exit_bytes;
884                         else
885                                 regs->si += exit_bytes;
886                 }
887
888                 if (exit_info_1 & IOIO_REP)
889                         regs->cx -= exit_info_2;
890
891                 ret = regs->cx ? ES_RETRY : ES_OK;
892
893         } else {
894
895                 /* IN/OUT into/from rAX */
896
897                 int bits = (exit_info_1 & 0x70) >> 1;
898                 u64 rax = 0;
899
900                 if (!(exit_info_1 & IOIO_TYPE_IN))
901                         rax = lower_bits(regs->ax, bits);
902
903                 ghcb_set_rax(ghcb, rax);
904
905                 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_IOIO, exit_info_1, 0);
906                 if (ret != ES_OK)
907                         return ret;
908
909                 if (exit_info_1 & IOIO_TYPE_IN) {
910                         if (!ghcb_rax_is_valid(ghcb))
911                                 return ES_VMM_ERROR;
912                         regs->ax = lower_bits(ghcb->save.rax, bits);
913                 }
914         }
915
916         return ret;
917 }
918
919 static int vc_handle_cpuid_snp(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
920 {
921         struct pt_regs *regs = ctxt->regs;
922         struct cpuid_leaf leaf;
923         int ret;
924
925         leaf.fn = regs->ax;
926         leaf.subfn = regs->cx;
927         ret = snp_cpuid(ghcb, ctxt, &leaf);
928         if (!ret) {
929                 regs->ax = leaf.eax;
930                 regs->bx = leaf.ebx;
931                 regs->cx = leaf.ecx;
932                 regs->dx = leaf.edx;
933         }
934
935         return ret;
936 }
937
938 static enum es_result vc_handle_cpuid(struct ghcb *ghcb,
939                                       struct es_em_ctxt *ctxt)
940 {
941         struct pt_regs *regs = ctxt->regs;
942         u32 cr4 = native_read_cr4();
943         enum es_result ret;
944         int snp_cpuid_ret;
945
946         snp_cpuid_ret = vc_handle_cpuid_snp(ghcb, ctxt);
947         if (!snp_cpuid_ret)
948                 return ES_OK;
949         if (snp_cpuid_ret != -EOPNOTSUPP)
950                 return ES_VMM_ERROR;
951
952         ghcb_set_rax(ghcb, regs->ax);
953         ghcb_set_rcx(ghcb, regs->cx);
954
955         if (cr4 & X86_CR4_OSXSAVE)
956                 /* Safe to read xcr0 */
957                 ghcb_set_xcr0(ghcb, xgetbv(XCR_XFEATURE_ENABLED_MASK));
958         else
959                 /* xgetbv will cause #GP - use reset value for xcr0 */
960                 ghcb_set_xcr0(ghcb, 1);
961
962         ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_CPUID, 0, 0);
963         if (ret != ES_OK)
964                 return ret;
965
966         if (!(ghcb_rax_is_valid(ghcb) &&
967               ghcb_rbx_is_valid(ghcb) &&
968               ghcb_rcx_is_valid(ghcb) &&
969               ghcb_rdx_is_valid(ghcb)))
970                 return ES_VMM_ERROR;
971
972         regs->ax = ghcb->save.rax;
973         regs->bx = ghcb->save.rbx;
974         regs->cx = ghcb->save.rcx;
975         regs->dx = ghcb->save.rdx;
976
977         return ES_OK;
978 }
979
980 static enum es_result vc_handle_rdtsc(struct ghcb *ghcb,
981                                       struct es_em_ctxt *ctxt,
982                                       unsigned long exit_code)
983 {
984         bool rdtscp = (exit_code == SVM_EXIT_RDTSCP);
985         enum es_result ret;
986
987         ret = sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, 0, 0);
988         if (ret != ES_OK)
989                 return ret;
990
991         if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb) &&
992              (!rdtscp || ghcb_rcx_is_valid(ghcb))))
993                 return ES_VMM_ERROR;
994
995         ctxt->regs->ax = ghcb->save.rax;
996         ctxt->regs->dx = ghcb->save.rdx;
997         if (rdtscp)
998                 ctxt->regs->cx = ghcb->save.rcx;
999
1000         return ES_OK;
1001 }
1002
1003 struct cc_setup_data {
1004         struct setup_data header;
1005         u32 cc_blob_address;
1006 };
1007
1008 /*
1009  * Search for a Confidential Computing blob passed in as a setup_data entry
1010  * via the Linux Boot Protocol.
1011  */
1012 static __head
1013 struct cc_blob_sev_info *find_cc_blob_setup_data(struct boot_params *bp)
1014 {
1015         struct cc_setup_data *sd = NULL;
1016         struct setup_data *hdr;
1017
1018         hdr = (struct setup_data *)bp->hdr.setup_data;
1019
1020         while (hdr) {
1021                 if (hdr->type == SETUP_CC_BLOB) {
1022                         sd = (struct cc_setup_data *)hdr;
1023                         return (struct cc_blob_sev_info *)(unsigned long)sd->cc_blob_address;
1024                 }
1025                 hdr = (struct setup_data *)hdr->next;
1026         }
1027
1028         return NULL;
1029 }
1030
1031 /*
1032  * Initialize the kernel's copy of the SNP CPUID table, and set up the
1033  * pointer that will be used to access it.
1034  *
1035  * Maintaining a direct mapping of the SNP CPUID table used by firmware would
1036  * be possible as an alternative, but the approach is brittle since the
1037  * mapping needs to be updated in sync with all the changes to virtual memory
1038  * layout and related mapping facilities throughout the boot process.
1039  */
1040 static void __head setup_cpuid_table(const struct cc_blob_sev_info *cc_info)
1041 {
1042         const struct snp_cpuid_table *cpuid_table_fw, *cpuid_table;
1043         int i;
1044
1045         if (!cc_info || !cc_info->cpuid_phys || cc_info->cpuid_len < PAGE_SIZE)
1046                 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID);
1047
1048         cpuid_table_fw = (const struct snp_cpuid_table *)cc_info->cpuid_phys;
1049         if (!cpuid_table_fw->count || cpuid_table_fw->count > SNP_CPUID_COUNT_MAX)
1050                 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID);
1051
1052         cpuid_table = snp_cpuid_get_table();
1053         memcpy((void *)cpuid_table, cpuid_table_fw, sizeof(*cpuid_table));
1054
1055         /* Initialize CPUID ranges for range-checking. */
1056         for (i = 0; i < cpuid_table->count; i++) {
1057                 const struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
1058
1059                 if (fn->eax_in == 0x0)
1060                         RIP_REL_REF(cpuid_std_range_max) = fn->eax;
1061                 else if (fn->eax_in == 0x40000000)
1062                         RIP_REL_REF(cpuid_hyp_range_max) = fn->eax;
1063                 else if (fn->eax_in == 0x80000000)
1064                         RIP_REL_REF(cpuid_ext_range_max) = fn->eax;
1065         }
1066 }