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