/
tdx.c
3188 lines (2726 loc) · 82.9 KB
/
tdx.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-2.0
#include <linux/cpu.h>
#include <linux/mmu_context.h>
#include <asm/fpu/xcr.h>
#include <asm/tdx.h>
#include "capabilities.h"
#include "x86_ops.h"
#include "common.h"
#include "mmu.h"
#include "tdx.h"
#include "vmx.h"
#include "x86.h"
#include <trace/events/kvm.h>
#include "trace.h"
#undef pr_fmt
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define TDX_MAX_NR_CPUID_CONFIGS \
((TDSYSINFO_STRUCT_SIZE - \
offsetof(struct tdsysinfo_struct, cpuid_configs)) \
/ sizeof(struct tdx_cpuid_config))
int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
{
int r;
switch (cap->cap) {
case KVM_CAP_MAX_VCPUS: {
if (cap->flags || cap->args[0] == 0)
return -EINVAL;
if (cap->args[0] > KVM_MAX_VCPUS)
return -E2BIG;
if (cap->args[0] > TDX_MAX_VCPUS)
return -E2BIG;
mutex_lock(&kvm->lock);
if (kvm->created_vcpus)
r = -EBUSY;
else {
kvm->max_vcpus = cap->args[0];
r = 0;
}
mutex_unlock(&kvm->lock);
break;
}
default:
r = -EINVAL;
break;
}
return r;
}
struct tdx_info {
u64 no_rbp_mod;
u8 nr_tdcs_pages;
u8 nr_tdvpx_pages;
};
/* Info about the TDX module. */
static struct tdx_info tdx_info __ro_after_init;
/*
* Some TDX SEAMCALLs (TDH.MNG.CREATE, TDH.PHYMEM.CACHE.WB,
* TDH.MNG.KEY.RECLAIMID, TDH.MNG.KEY.FREEID etc) tries to acquire a global lock
* internally in TDX module. If failed, TDX_OPERAND_BUSY is returned without
* spinning or waiting due to a constraint on execution time. It's caller's
* responsibility to avoid race (or retry on TDX_OPERAND_BUSY). Use this mutex
* to avoid race in TDX module because the kernel knows better about scheduling.
*/
static DEFINE_MUTEX(tdx_lock);
static struct mutex *tdx_mng_key_config_lock;
static atomic_t nr_configured_hkid;
/*
* A per-CPU list of TD vCPUs associated with a given CPU. Used when a CPU
* is brought down to invoke TDH_VP_FLUSH on the approapriate TD vCPUS.
* Protected by interrupt mask. This list is manipulated in process context
* of vcpu and IPI callback. See tdx_flush_vp_on_cpu().
*/
static DEFINE_PER_CPU(struct list_head, associated_tdvcpus);
static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
{
return pa | ((hpa_t)hkid << boot_cpu_data.x86_phys_bits);
}
static __always_inline unsigned long tdexit_exit_qual(struct kvm_vcpu *vcpu)
{
return kvm_rcx_read(vcpu);
}
static __always_inline unsigned long tdexit_ext_exit_qual(struct kvm_vcpu *vcpu)
{
return kvm_rdx_read(vcpu);
}
static __always_inline unsigned long tdexit_gpa(struct kvm_vcpu *vcpu)
{
return kvm_r8_read(vcpu);
}
static __always_inline unsigned long tdexit_intr_info(struct kvm_vcpu *vcpu)
{
return kvm_r9_read(vcpu);
}
#define BUILD_TDVMCALL_ACCESSORS(param, gpr) \
static __always_inline \
unsigned long tdvmcall_##param##_read(struct kvm_vcpu *vcpu) \
{ \
return kvm_##gpr##_read(vcpu); \
} \
static __always_inline void tdvmcall_##param##_write(struct kvm_vcpu *vcpu, \
unsigned long val) \
{ \
kvm_##gpr##_write(vcpu, val); \
}
BUILD_TDVMCALL_ACCESSORS(a0, r12);
BUILD_TDVMCALL_ACCESSORS(a1, r13);
BUILD_TDVMCALL_ACCESSORS(a2, r14);
BUILD_TDVMCALL_ACCESSORS(a3, r15);
static __always_inline unsigned long tdvmcall_exit_type(struct kvm_vcpu *vcpu)
{
return kvm_r10_read(vcpu);
}
static __always_inline unsigned long tdvmcall_leaf(struct kvm_vcpu *vcpu)
{
return kvm_r11_read(vcpu);
}
static __always_inline void tdvmcall_set_return_code(struct kvm_vcpu *vcpu,
long val)
{
kvm_r10_write(vcpu, val);
}
static __always_inline void tdvmcall_set_return_val(struct kvm_vcpu *vcpu,
unsigned long val)
{
kvm_r11_write(vcpu, val);
}
static inline bool is_td_vcpu_created(struct vcpu_tdx *tdx)
{
return tdx->tdvpr_pa;
}
static inline bool is_td_created(struct kvm_tdx *kvm_tdx)
{
return kvm_tdx->tdr_pa;
}
static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
{
tdx_guest_keyid_free(kvm_tdx->hkid);
kvm_tdx->hkid = 0;
}
static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)
{
return kvm_tdx->hkid > 0;
}
static inline bool is_td_finalized(struct kvm_tdx *kvm_tdx)
{
return kvm_tdx->finalized;
}
static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
{
lockdep_assert_irqs_disabled();
list_del(&to_tdx(vcpu)->cpu_list);
/*
* Ensure tdx->cpu_list is updated is before setting vcpu->cpu to -1,
* otherwise, a different CPU can see vcpu->cpu = -1 and add the vCPU
* to its list before its deleted from this CPUs list.
*/
smp_wmb();
vcpu->cpu = -1;
}
static void tdx_disassociate_vp_arg(void *vcpu)
{
tdx_disassociate_vp(vcpu);
}
static void tdx_disassociate_vp_on_cpu(struct kvm_vcpu *vcpu)
{
int cpu = vcpu->cpu;
if (unlikely(cpu == -1))
return;
smp_call_function_single(cpu, tdx_disassociate_vp_arg, vcpu, 1);
}
static void tdx_clear_page(unsigned long page_pa)
{
const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
void *page = __va(page_pa);
unsigned long i;
/*
* When re-assign one page from old keyid to a new keyid, MOVDIR64B is
* required to clear/write the page with new keyid to prevent integrity
* error when read on the page with new keyid.
*
* clflush doesn't flush cache with HKID set. The cache line could be
* poisoned (even without MKTME-i), clear the poison bit.
*/
for (i = 0; i < PAGE_SIZE; i += 64)
movdir64b(page + i, zero_page);
/*
* MOVDIR64B store uses WC buffer. Prevent following memory reads
* from seeing potentially poisoned cache.
*/
__mb();
}
static int tdx_reclaim_page(hpa_t pa, bool do_wb, u16 hkid)
{
struct tdx_module_args out;
u64 err;
do {
err = tdh_phymem_page_reclaim(pa, &out);
/*
* TDH.PHYMEM.PAGE.RECLAIM is allowed only when TD is shutdown.
* state. i.e. destructing TD.
* TDH.PHYMEM.PAGE.RECLAIM requires TDR and target page.
* Because we're destructing TD, it's rare to contend with TDR.
*/
} while (unlikely(err == (TDX_OPERAND_BUSY | TDX_OPERAND_ID_RCX)));
if (WARN_ON_ONCE(err)) {
pr_tdx_error(TDH_PHYMEM_PAGE_RECLAIM, err, &out);
return -EIO;
}
if (do_wb) {
/*
* Only TDR page gets into this path. No contention is expected
* because of the last page of TD.
*/
err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(pa, hkid));
if (WARN_ON_ONCE(err)) {
pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
return -EIO;
}
}
tdx_clear_page(pa);
return 0;
}
static void tdx_reclaim_td_page(unsigned long td_page_pa)
{
WARN_ON_ONCE(!td_page_pa);
/*
* TDCX are being reclaimed. TDX module maps TDCX with HKID
* assigned to the TD. Here the cache associated to the TD
* was already flushed by TDH.PHYMEM.CACHE.WB before here, So
* cache doesn't need to be flushed again.
*/
if (tdx_reclaim_page(td_page_pa, false, 0))
/*
* Leak the page on failure:
* tdx_reclaim_page() returns an error if and only if there's an
* unexpected, fatal error, e.g. a SEAMCALL with bad params,
* incorrect concurrency in KVM, a TDX Module bug, etc.
* Retrying at a later point is highly unlikely to be
* successful.
* No log here as tdx_reclaim_page() already did.
*/
return;
free_page((unsigned long)__va(td_page_pa));
}
struct tdx_flush_vp_arg {
struct kvm_vcpu *vcpu;
u64 err;
};
static void tdx_flush_vp(void *arg_)
{
struct tdx_flush_vp_arg *arg = arg_;
struct kvm_vcpu *vcpu = arg->vcpu;
u64 err;
arg->err = 0;
lockdep_assert_irqs_disabled();
/* Task migration can race with CPU offlining. */
if (unlikely(vcpu->cpu != raw_smp_processor_id()))
return;
/*
* No need to do TDH_VP_FLUSH if the vCPU hasn't been initialized. The
* list tracking still needs to be updated so that it's correct if/when
* the vCPU does get initialized.
*/
if (is_td_vcpu_created(to_tdx(vcpu))) {
/*
* No need to retry. TDX Resources needed for TDH.VP.FLUSH are,
* TDVPR as exclusive, TDR as shared, and TDCS as shared. This
* vp flush function is called when destructing vcpu/TD or vcpu
* migration. No other thread uses TDVPR in those cases.
*/
err = tdh_vp_flush(to_tdx(vcpu)->tdvpr_pa);
if (unlikely(err && err != TDX_VCPU_NOT_ASSOCIATED)) {
/*
* This function is called in IPI context. Do not use
* printk to avoid console semaphore.
* The caller prints out the error message, instead.
*/
if (err)
arg->err = err;
}
}
tdx_disassociate_vp(vcpu);
}
static void tdx_flush_vp_on_cpu(struct kvm_vcpu *vcpu)
{
struct tdx_flush_vp_arg arg = {
.vcpu = vcpu,
};
int cpu = vcpu->cpu;
if (unlikely(cpu == -1))
return;
smp_call_function_single(cpu, tdx_flush_vp, &arg, 1);
if (WARN_ON_ONCE(arg.err)) {
pr_err("cpu: %d ", cpu);
pr_tdx_error(TDH_VP_FLUSH, arg.err, NULL);
}
}
void tdx_hardware_disable(void)
{
int cpu = raw_smp_processor_id();
struct list_head *tdvcpus = &per_cpu(associated_tdvcpus, cpu);
struct tdx_flush_vp_arg arg;
struct vcpu_tdx *tdx, *tmp;
unsigned long flags;
lockdep_assert_preemption_disabled();
local_irq_save(flags);
/* Safe variant needed as tdx_disassociate_vp() deletes the entry. */
list_for_each_entry_safe(tdx, tmp, tdvcpus, cpu_list) {
arg.vcpu = &tdx->vcpu;
tdx_flush_vp(&arg);
}
local_irq_restore(flags);
}
static int tdx_do_tdh_phymem_cache_wb(void *param)
{
u64 err = 0;
do {
err = tdh_phymem_cache_wb(!!err);
} while (err == TDX_INTERRUPTED_RESUMABLE);
/* Other thread may have done for us. */
if (err == TDX_NO_HKID_READY_TO_WBCACHE)
err = TDX_SUCCESS;
if (WARN_ON_ONCE(err)) {
pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
return -EIO;
}
return 0;
}
void tdx_mmu_release_hkid(struct kvm *kvm)
{
struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
cpumask_var_t packages;
bool cpumask_allocated;
struct kvm_vcpu *vcpu;
unsigned long j;
u64 err;
int ret;
int i;
if (!is_hkid_assigned(kvm_tdx))
return;
if (!is_td_created(kvm_tdx))
goto free_hkid;
kvm_for_each_vcpu(j, vcpu, kvm)
tdx_flush_vp_on_cpu(vcpu);
mutex_lock(&tdx_lock);
err = tdh_mng_vpflushdone(kvm_tdx->tdr_pa);
mutex_unlock(&tdx_lock);
if (WARN_ON_ONCE(err)) {
pr_tdx_error(TDH_MNG_VPFLUSHDONE, err, NULL);
pr_err("tdh_mng_vpflushdone failed. HKID %d is leaked.\n",
kvm_tdx->hkid);
return;
}
cpumask_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
cpus_read_lock();
for_each_online_cpu(i) {
if (cpumask_allocated &&
cpumask_test_and_set_cpu(topology_physical_package_id(i),
packages))
continue;
/*
* We can destroy multiple the guest TDs simultaneously.
* Prevent tdh_phymem_cache_wb from returning TDX_BUSY by
* serialization.
*/
mutex_lock(&tdx_lock);
ret = smp_call_on_cpu(i, tdx_do_tdh_phymem_cache_wb, NULL, 1);
mutex_unlock(&tdx_lock);
if (ret)
break;
}
cpus_read_unlock();
free_cpumask_var(packages);
mutex_lock(&tdx_lock);
err = tdh_mng_key_freeid(kvm_tdx->tdr_pa);
mutex_unlock(&tdx_lock);
if (WARN_ON_ONCE(err)) {
pr_tdx_error(TDH_MNG_KEY_FREEID, err, NULL);
pr_err("tdh_mng_key_freeid failed. HKID %d is leaked.\n",
kvm_tdx->hkid);
return;
} else
atomic_dec(&nr_configured_hkid);
free_hkid:
tdx_hkid_free(kvm_tdx);
}
void tdx_vm_free(struct kvm *kvm)
{
struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
int i;
/*
* tdx_mmu_release_hkid() failed to reclaim HKID. Something went wrong
* heavily with TDX module. Give up freeing TD pages. As the function
* already warned, don't warn it again.
*/
if (is_hkid_assigned(kvm_tdx))
return;
if (kvm_tdx->tdcs_pa) {
for (i = 0; i < tdx_info.nr_tdcs_pages; i++) {
if (kvm_tdx->tdcs_pa[i])
tdx_reclaim_td_page(kvm_tdx->tdcs_pa[i]);
}
kfree(kvm_tdx->tdcs_pa);
kvm_tdx->tdcs_pa = NULL;
}
if (!kvm_tdx->tdr_pa)
return;
/*
* TDX module maps TDR with TDX global HKID. TDX module may access TDR
* while operating on TD (Especially reclaiming TDCS). Cache flush with
* TDX global HKID is needed.
*/
if (tdx_reclaim_page(kvm_tdx->tdr_pa, true, tdx_global_keyid))
return;
free_page((unsigned long)__va(kvm_tdx->tdr_pa));
kvm_tdx->tdr_pa = 0;
kfree(kvm_tdx->cpuid);
kvm_tdx->cpuid = NULL;
}
static int tdx_do_tdh_mng_key_config(void *param)
{
hpa_t *tdr_p = param;
u64 err;
do {
err = tdh_mng_key_config(*tdr_p);
/*
* If it failed to generate a random key, retry it because this
* is typically caused by an entropy error of the CPU's random
* number generator.
*/
} while (err == TDX_KEY_GENERATION_FAILED);
if (WARN_ON_ONCE(err)) {
pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
return -EIO;
}
return 0;
}
int tdx_vm_init(struct kvm *kvm)
{
/*
* Because guest TD is protected, VMM can't parse the instruction in TD.
* Instead, guest uses MMIO hypercall. For unmodified device driver,
* #VE needs to be injected for MMIO and #VE handler in TD converts MMIO
* instruction into MMIO hypercall.
*
* SPTE value for MMIO needs to be setup so that #VE is injected into
* TD instead of triggering EPT MISCONFIG.
* - RWX=0 so that EPT violation is triggered.
* - suppress #VE bit is cleared to inject #VE.
*/
kvm_mmu_set_mmio_spte_value(kvm, 0);
/* TODO: Enable 2mb and 1gb large page support. */
kvm->arch.tdp_max_page_level = PG_LEVEL_4K;
/*
* This function initializes only KVM software construct. It doesn't
* initialize TDX stuff, e.g. TDCS, TDR, TDCX, HKID etc.
* It is handled by KVM_TDX_INIT_VM, __tdx_td_init().
*/
/*
* TDX has its own limit of the number of vcpus in addition to
* KVM_MAX_VCPUS.
*/
kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
return 0;
}
u8 tdx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
{
if (is_mmio)
return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
/* TDX enforces CR0.CD = 0 and KVM MTRR emulation enforces writeback. */
return MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT;
}
int tdx_vcpu_create(struct kvm_vcpu *vcpu)
{
struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
struct vcpu_tdx *tdx = to_tdx(vcpu);
/*
* On cpu creation, cpuid entry is blank. Forcibly enable
* X2APIC feature to allow X2APIC.
* Because vcpu_reset() can't return error, allocation is done here.
*/
WARN_ON_ONCE(vcpu->arch.cpuid_entries);
WARN_ON_ONCE(vcpu->arch.cpuid_nent);
/* TDX only supports x2APIC, which requires an in-kernel local APIC. */
if (!vcpu->arch.apic)
return -EINVAL;
fpstate_set_confidential(&vcpu->arch.guest_fpu);
vcpu->arch.apic->guest_apic_protected = true;
INIT_LIST_HEAD(&tdx->pi_wakeup_list);
vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
vcpu->arch.switch_db_regs = KVM_DEBUGREG_AUTO_SWITCH;
vcpu->arch.cr0_guest_owned_bits = -1ul;
vcpu->arch.cr4_guest_owned_bits = -1ul;
vcpu->arch.tsc_offset = to_kvm_tdx(vcpu->kvm)->tsc_offset;
vcpu->arch.l1_tsc_offset = vcpu->arch.tsc_offset;
/*
* TODO: support off-TD debug. If TD DEBUG is enabled, guest state
* can be accessed. guest_state_protected = false. and kvm ioctl to
* access CPU states should be usable for user space VMM (e.g. qemu).
*
* vcpu->arch.guest_state_protected =
* !(to_kvm_tdx(vcpu->kvm)->attributes & TDX_TD_ATTRIBUTE_DEBUG);
*/
vcpu->arch.guest_state_protected = true;
if ((kvm_tdx->xfam & XFEATURE_MASK_XTILE) == XFEATURE_MASK_XTILE)
vcpu->arch.xfd_no_write_intercept = true;
tdx->host_state_need_save = true;
tdx->host_state_need_restore = false;
tdx->pi_desc.nv = POSTED_INTR_VECTOR;
tdx->pi_desc.sn = 1;
return 0;
}
int tdx_vcpu_check_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2, int nent)
{
struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
const struct tdsysinfo_struct *tdsysinfo;
int i;
tdsysinfo = tdx_get_sysinfo();
if (!tdsysinfo)
return -EOPNOTSUPP;
/*
* Simple check that new cpuid is consistent with created one.
* For simplicity, only trivial check. Don't try comprehensive checks
* with the cpuid virtualization table in the TDX module spec.
*/
for (i = 0; i < tdsysinfo->num_cpuid_config; i++) {
const struct tdx_cpuid_config *config = &tdsysinfo->cpuid_configs[i];
u32 index = config->sub_leaf == TDX_CPUID_NO_SUBLEAF ? 0 : config->sub_leaf;
const struct kvm_cpuid_entry2 *old =
kvm_find_cpuid_entry2(kvm_tdx->cpuid, kvm_tdx->cpuid_nent,
config->leaf, index);
const struct kvm_cpuid_entry2 *new = kvm_find_cpuid_entry2(e2, nent,
config->leaf, index);
if (!!old != !!new)
return -EINVAL;
if (!old && !new)
continue;
if ((old->eax ^ new->eax) & config->eax ||
(old->ebx ^ new->ebx) & config->ebx ||
(old->ecx ^ new->ecx) & config->ecx ||
(old->edx ^ new->edx) & config->edx)
return -EINVAL;
}
return 0;
}
void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
struct vcpu_tdx *tdx = to_tdx(vcpu);
vmx_vcpu_pi_load(vcpu, cpu);
if (vcpu->cpu == cpu)
return;
tdx_flush_vp_on_cpu(vcpu);
local_irq_disable();
/*
* Pairs with the smp_wmb() in tdx_disassociate_vp() to ensure
* vcpu->cpu is read before tdx->cpu_list.
*/
smp_rmb();
list_add(&tdx->cpu_list, &per_cpu(associated_tdvcpus, cpu));
local_irq_enable();
}
bool tdx_protected_apic_has_interrupt(struct kvm_vcpu *vcpu)
{
bool ret = pi_has_pending_interrupt(vcpu);
struct vcpu_tdx *tdx = to_tdx(vcpu);
if (ret || vcpu->arch.mp_state != KVM_MP_STATE_HALTED)
return true;
if (tdx->interrupt_disabled_hlt)
return false;
/*
* This is for the case where the virtual interrupt is recognized,
* i.e. set in vmcs.RVI, between the STI and "HLT". KVM doesn't have
* access to RVI and the interrupt is no longer in the PID (because it
* was "recognized". It doesn't get delivered in the guest because the
* TDCALL completes before interrupts are enabled.
*
* TDX modules sets RVI while in an STI interrupt shadow.
* - TDExit(typically TDG.VP.VMCALL<HLT>) from the guest to TDX module.
* The interrupt shadow at this point is gone.
* - It knows that there is an interrupt that can be delivered
* (RVI > PPR && EFLAGS.IF=1, the other conditions of 29.2.2 don't
* matter)
* - It forwards the TDExit nevertheless, to a clueless hypervisor that
* has no way to glean either RVI or PPR.
*/
return !!xchg(&tdx->buggy_hlt_workaround, 0);
}
void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
{
struct vcpu_tdx *tdx = to_tdx(vcpu);
if (!tdx->host_state_need_save)
return;
if (likely(is_64bit_mm(current->mm)))
tdx->msr_host_kernel_gs_base = current->thread.gsbase;
else
tdx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
tdx->host_state_need_save = false;
}
static void tdx_prepare_switch_to_host(struct kvm_vcpu *vcpu)
{
struct vcpu_tdx *tdx = to_tdx(vcpu);
tdx->host_state_need_save = true;
if (!tdx->host_state_need_restore)
return;
++vcpu->stat.host_state_reload;
wrmsrl(MSR_KERNEL_GS_BASE, tdx->msr_host_kernel_gs_base);
tdx->host_state_need_restore = false;
}
void tdx_vcpu_put(struct kvm_vcpu *vcpu)
{
vmx_vcpu_pi_put(vcpu);
tdx_prepare_switch_to_host(vcpu);
}
void tdx_vcpu_free(struct kvm_vcpu *vcpu)
{
struct vcpu_tdx *tdx = to_tdx(vcpu);
int i;
/*
* When destroying VM, kvm_unload_vcpu_mmu() calls vcpu_load() for every
* vcpu after they already disassociated from the per cpu list by
* tdx_mmu_release_hkid(). So we need to disassociate them again,
* otherwise the freed vcpu data will be accessed when do
* list_{del,add}() on associated_tdvcpus list later.
*/
tdx_disassociate_vp_on_cpu(vcpu);
WARN_ON_ONCE(vcpu->cpu != -1);
/*
* This methods can be called when vcpu allocation/initialization
* failed. So it's possible that hkid, tdvpx and tdvpr are not assigned
* yet.
*/
if (is_hkid_assigned(to_kvm_tdx(vcpu->kvm))) {
WARN_ON_ONCE(tdx->tdvpx_pa);
WARN_ON_ONCE(tdx->tdvpr_pa);
return;
}
if (tdx->tdvpx_pa) {
for (i = 0; i < tdx_info.nr_tdvpx_pages; i++) {
if (tdx->tdvpx_pa[i])
tdx_reclaim_td_page(tdx->tdvpx_pa[i]);
}
kfree(tdx->tdvpx_pa);
tdx->tdvpx_pa = NULL;
}
if (tdx->tdvpr_pa) {
tdx_reclaim_td_page(tdx->tdvpr_pa);
tdx->tdvpr_pa = 0;
}
}
void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
{
/* vcpu_deliver_init method silently discards INIT event. */
if (KVM_BUG_ON(init_event, vcpu->kvm))
return;
if (KVM_BUG_ON(is_td_vcpu_created(to_tdx(vcpu)), vcpu->kvm))
return;
/*
* Don't update mp_state to runnable because more initialization
* is needed by TDX_VCPU_INIT.
*/
}
static void tdx_complete_interrupts(struct kvm_vcpu *vcpu)
{
/* Avoid costly SEAMCALL if no nmi was injected */
if (vcpu->arch.nmi_injected)
vcpu->arch.nmi_injected = td_management_read8(to_tdx(vcpu),
TD_VCPU_PEND_NMI);
}
struct tdx_uret_msr {
u32 msr;
unsigned int slot;
u64 defval;
};
static struct tdx_uret_msr tdx_uret_msrs[] = {
{.msr = MSR_SYSCALL_MASK, .defval = 0x20200 },
{.msr = MSR_STAR,},
{.msr = MSR_LSTAR,},
{.msr = MSR_TSC_AUX,},
};
static unsigned int tdx_uret_tsx_ctrl_slot;
static void tdx_user_return_update_cache(struct kvm_vcpu *vcpu)
{
int i;
for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++)
kvm_user_return_update_cache(tdx_uret_msrs[i].slot,
tdx_uret_msrs[i].defval);
/*
* TSX_CTRL is reset to 0 if guest TSX is supported. Otherwise
* preserved.
*/
if (to_kvm_tdx(vcpu->kvm)->tsx_supported && tdx_uret_tsx_ctrl_slot != -1)
kvm_user_return_update_cache(tdx_uret_tsx_ctrl_slot, 0);
}
static void tdx_restore_host_xsave_state(struct kvm_vcpu *vcpu)
{
struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
if (static_cpu_has(X86_FEATURE_XSAVE) &&
host_xcr0 != (kvm_tdx->xfam & kvm_caps.supported_xcr0))
xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
if (static_cpu_has(X86_FEATURE_XSAVES) &&
/* PT can be exposed to TD guest regardless of KVM's XSS support */
host_xss != (kvm_tdx->xfam &
(kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET)))
wrmsrl(MSR_IA32_XSS, host_xss);
if (static_cpu_has(X86_FEATURE_PKU) &&
(kvm_tdx->xfam & XFEATURE_MASK_PKRU))
write_pkru(vcpu->arch.host_pkru);
}
static noinstr void tdx_vcpu_enter_exit(struct vcpu_tdx *tdx)
{
/*
* Avoid section mismatch with to_tdx() with KVM_VM_BUG(). The caller
* should call to_tdx().
*/
struct kvm_vcpu *vcpu = &tdx->vcpu;
guest_state_enter_irqoff();
/*
* struct tdx_module_args and struct kvm_vcpu_arch::args must be same
* layout to use __seamcall_saved_ret().
*/
#define WORD_SIZE (BITS_PER_LONG / 8)
#define BUG_ON_ARG_OFFSET(arg_reg, vcpu_reg) \
BUILD_BUG_ON(offsetof(struct tdx_module_args, arg_reg) != \
VCPU_REGS_ ## vcpu_reg * WORD_SIZE);
BUG_ON_ARG_OFFSET(rax_unused, RAX);
BUG_ON_ARG_OFFSET(rcx, RCX);
BUG_ON_ARG_OFFSET(rdx, RDX);
BUG_ON_ARG_OFFSET(rbx, RBX);
BUG_ON_ARG_OFFSET(rsp_unused, RSP);
BUG_ON_ARG_OFFSET(rbp_unused, RBP);
BUG_ON_ARG_OFFSET(rsi, RSI);
BUG_ON_ARG_OFFSET(rdi, RDI);
BUG_ON_ARG_OFFSET(r8, R8);
BUG_ON_ARG_OFFSET(r9, R9);
BUG_ON_ARG_OFFSET(r10, R10);
BUG_ON_ARG_OFFSET(r11, R11);
BUG_ON_ARG_OFFSET(r12, R12);
BUG_ON_ARG_OFFSET(r13, R13);
BUG_ON_ARG_OFFSET(r14, R14);
BUG_ON_ARG_OFFSET(r15, R15);
#undef BUG_ON_ARG_OFFSET
#undef WORD_SIZE
/*
* TODO: micro optimization:
* copyin/copyout registers only if (tdx->tdvmvall.regs_mask != 0)
* which means TDG.VP.VMCALL.
*/
vcpu->arch.regs[VCPU_REGS_RCX] = tdx->tdvpr_pa;
tdx->exit_reason.full = __seamcall_saved_ret(TDH_VP_ENTER,
(struct tdx_module_args*)vcpu->arch.regs);
WARN_ON_ONCE(!kvm_rebooting &&
(tdx->exit_reason.full & TDX_SW_ERROR) == TDX_SW_ERROR);
if ((u16)tdx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI &&
is_nmi(tdexit_intr_info(vcpu))) {
kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
vmx_do_nmi_irqoff();
kvm_after_interrupt(vcpu);
}
guest_state_exit_irqoff();
}
fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu)
{
struct vcpu_tdx *tdx = to_tdx(vcpu);
if (unlikely(!tdx->initialized))
return -EINVAL;
if (unlikely(vcpu->kvm->vm_bugged)) {
tdx->exit_reason.full = TDX_NON_RECOVERABLE_VCPU;
return EXIT_FASTPATH_NONE;
}
trace_kvm_entry(vcpu);
if (pi_test_on(&tdx->pi_desc)) {
apic->send_IPI_self(POSTED_INTR_VECTOR);
kvm_wait_lapic_expire(vcpu);
}
tdx_vcpu_enter_exit(tdx);
tdx_user_return_update_cache(vcpu);
perf_restore_debug_store();
tdx_restore_host_xsave_state(vcpu);
tdx->host_state_need_restore = true;
vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
trace_kvm_exit(vcpu, KVM_ISA_VMX);
tdx_complete_interrupts(vcpu);
if (tdx->exit_reason.basic == EXIT_REASON_TDCALL)
tdx->tdvmcall.rcx = vcpu->arch.regs[VCPU_REGS_RCX];
else
tdx->tdvmcall.rcx = 0;
return EXIT_FASTPATH_NONE;
}
void tdx_inject_nmi(struct kvm_vcpu *vcpu)
{
++vcpu->stat.nmi_injections;
td_management_write8(to_tdx(vcpu), TD_VCPU_PEND_NMI, 1);
}
void tdx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
{
struct vcpu_tdx *tdx = to_tdx(vcpu);
u16 exit_reason = tdx->exit_reason.basic;
if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
vmx_handle_external_interrupt_irqoff(vcpu,
tdexit_intr_info(vcpu));
else if (exit_reason == EXIT_REASON_EXCEPTION_NMI)
vmx_handle_exception_irqoff(vcpu, tdexit_intr_info(vcpu));
else if (unlikely(tdx->exit_reason.non_recoverable ||
tdx->exit_reason.error)) {
/*
* The only reason it gets EXIT_REASON_OTHER_SMI is there is an
* #MSMI(Machine Check System Management Interrupt) with
* exit_qualification bit 0 set in TD guest.
* The #MSMI is delivered right after SEAMCALL returns,
* and an #MC is delivered to host kernel after SMI handler
* returns.
*
* The #MC right after SEAMCALL is fixed up and skipped in #MC
* handler because it's an #MC happens in TD guest we cannot
* handle it with host's context.
*
* Call KVM's machine check handler explicitly here.
*/
if (tdx->exit_reason.basic == EXIT_REASON_OTHER_SMI) {
unsigned long exit_qual;
exit_qual = tdexit_exit_qual(vcpu);
if (exit_qual & TD_EXIT_OTHER_SMI_IS_MSMI)
kvm_machine_check();
}
}
}
static int tdx_handle_exception(struct kvm_vcpu *vcpu)
{
u32 intr_info = tdexit_intr_info(vcpu);
if (is_nmi(intr_info) || is_machine_check(intr_info))
return 1;
kvm_pr_unimpl("unexpected exception 0x%x(exit_reason 0x%llx qual 0x%lx)\n",
intr_info,
to_tdx(vcpu)->exit_reason.full, tdexit_exit_qual(vcpu));
return -EFAULT;
}
static int tdx_handle_external_interrupt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.irq_exits;
return 1;
}