Re: [PATCH v16 03/20] KVM: selftests: Initialize the TDX VM
From: Ackerley Tng
Date: Tue Nov 10 2026 - 17:51:52 EST
Sean Christopherson <seanjc@xxxxxxxxxx> writes:
> On Mon, Nov 09, 2026, Ackerley Tng wrote:
>> Lisa Wang <wyihan@xxxxxxxxxx> writes:
>> > +static const struct kvm_tdx_capabilities *tdx_read_capabilities(struct kvm_vm *vm)
>> > +{
>> > + static struct kvm_tdx_capabilities *tdx_cap;
>> > + int nr_cpuid_configs = 4;
>> > + int rc = -1;
>> > + int i;
>> > +
>> > + if (tdx_cap)
>> > + return tdx_cap;
>> > +
>> > + do {
>> > + nr_cpuid_configs *= 2;
>> > +
>> > + tdx_cap = realloc(tdx_cap, sizeof(*tdx_cap) +
>> > + (sizeof(struct kvm_cpuid_entry2) * nr_cpuid_configs));
>>
>> Would be nice if struct_size() could be used here instead of manual
>> calculation of the size. Same below.
>
> ...
>
>> > +void tdx_init_vm(struct kvm_vm *vm)
>> > +{
>> > + struct kvm_tdx_init_vm *init_vm;
>> > + const struct kvm_cpuid2 *tmp;
>> > +
>> > + tmp = kvm_get_supported_cpuid();
>> > +
>> > + init_vm = calloc(1, sizeof(*init_vm) +
>> > + sizeof(init_vm->cpuid.entries[0]) * tmp->nent);
>>
>> Would it be possible to use struct_size() here?
>> Or perhaps kvm_cpuid2_size(tmp->nent)?
>>
>> > + TEST_ASSERT(init_vm, "init_vm allocation failed");
>> > +
>> > + memcpy(&init_vm->cpuid, tmp, kvm_cpuid2_size(tmp->nent));
>> > + init_vm->cpuid.padding = 0;
>> > + tdx_filter_cpuid(vm, &init_vm->cpuid);
>>
>> How about something like this?
>>
>> 1. Query TDX capabilities first to get tdx_cap->cpuid.nent (let's say N).
>> 2. Allocate init_vm sized for at most N entries, since the filtered
>> result can never exceed TDX's supported CPUID set.
>> 3. Iterate over the TDX CPUID capabilities, look each one up in
>> kvm_get_supported_cpuid(), and append matching, masked entries
>> directly into init_vm->cpuid.entries.
>>
>> This would avoid the memcpy and all the memmoves, though this works
>> as-is. Just an optimization/different perspective.
>
> At this point, I'll do minimial fixup when applying, e.g. if switching to
> struct_size() Just Works. But I don't want to do anything more invasive at this
> point so that we can get TDX selftests landed asap. To be clear, I'm not opposed
> to more cleanups, I just want to do them on top.
Good to know that this series is ready for Sean's apply + small
fixes. Don't worry about my suggestions on refactoring.
Sean, for this series, is the next step to wait for the merge to
kvm-x86/coco? Do you need anything else from us?