Re: [PATCH v18 030/121] KVM: TDX: Do TDX specific vcpu initialization

From: Isaku Yamahata
Date: Mon Feb 26 2024 - 14:01:29 EST


On Thu, Jan 25, 2024 at 03:56:53PM +0800,
Binbin Wu <binbin.wu@xxxxxxxxxxxxxxx> wrote:

> > diff --git a/arch/x86/kvm/vmx/tdx.c b/arch/x86/kvm/vmx/tdx.c
> > index 8330f448ab8e..245be29721b4 100644
> > --- a/arch/x86/kvm/vmx/tdx.c
> > +++ b/arch/x86/kvm/vmx/tdx.c
..
> > @@ -951,15 +992,147 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
> > return r;
> > }
> > +/* VMM can pass one 64bit auxiliary data to vcpu via RCX for guest BIOS. */
> > +static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
> > +{
> > + struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
> > + struct vcpu_tdx *tdx = to_tdx(vcpu);
> > + unsigned long *tdvpx_pa = NULL;
> > + unsigned long tdvpr_pa;
> > + unsigned long va;
> > + int ret, i;
> > + u64 err;
> > +
> > + if (is_td_vcpu_created(tdx))
> > + return -EINVAL;
> > +
> > + /*
> > + * vcpu_free method frees allocated pages. Avoid partial setup so
> > + * that the method can't handle it.
> > + */
> > + va = __get_free_page(GFP_KERNEL_ACCOUNT);
> > + if (!va)
> > + return -ENOMEM;
> > + tdvpr_pa = __pa(va);
> > +
> > + tdvpx_pa = kcalloc(tdx_info->nr_tdvpx_pages, sizeof(*tdx->tdvpx_pa),
> > + GFP_KERNEL_ACCOUNT);
> > + if (!tdvpx_pa) {
> > + ret = -ENOMEM;
> > + goto free_tdvpr;
> > + }
> > + for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
> > + va = __get_free_page(GFP_KERNEL_ACCOUNT);
> > + if (!va) {
> > + ret = -ENOMEM;
> > + goto free_tdvpx;
> > + }
> > + tdvpx_pa[i] = __pa(va);
> > + }
> > +
> > + err = tdh_vp_create(kvm_tdx->tdr_pa, tdvpr_pa);
> > + if (KVM_BUG_ON(err, vcpu->kvm)) {
> > + ret = -EIO;
> > + pr_tdx_error(TDH_VP_CREATE, err, NULL);
> > + goto free_tdvpx;
> > + }
> > + tdx->tdvpr_pa = tdvpr_pa;
> > +
> > + tdx->tdvpx_pa = tdvpx_pa;
> > + for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
> > + err = tdh_vp_addcx(tdx->tdvpr_pa, tdvpx_pa[i]);
> > + if (KVM_BUG_ON(err, vcpu->kvm)) {
> > + pr_tdx_error(TDH_VP_ADDCX, err, NULL);
> > + for (; i < tdx_info->nr_tdvpx_pages; i++) {
> > + free_page((unsigned long)__va(tdvpx_pa[i]));
> > + tdvpx_pa[i] = 0;
> > + }
> > + /* vcpu_free method frees TDVPX and TDR donated to TDX */
> vcpu_free() interface is called by two sites.
> One is the error handling path of kvm_vm_ioctl_create_vcpu() when vcpu
> creation.
> The other is during kvm_destroy_vm().
>
> What about the error occurs in KVM_TDX_INIT_VCPU?
> Let's assume TDR and some of tdvpx pages are donated to TDX, and the next
> call of tdh_vp_addcx() failed. The comment says "vcpu_free method frees
> TDVPX
> and TDR donated to TDX", but if it happens, it seems that vcpu_free() would
> not be called? Memory leakage?

vcpu_free() is called because we already created vcpu with KVM_VCPU_CREATE
irrelevant of the result of TDX_VCPU_INIT.
tdx_vcpu_free() handles error case of TDX_VCPU_INIT. So no leakage.
--
Isaku Yamahata <isaku.yamahata@xxxxxxxxxxxxxxx>