]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
KVM: TDX: Use struct_size to simplify tdx_get_capabilities()
authorSean Christopherson <seanjc@google.com>
Mon, 10 Nov 2025 21:24:53 +0000 (13:24 -0800)
committerSean Christopherson <seanjc@google.com>
Thu, 13 Nov 2025 16:30:07 +0000 (08:30 -0800)
Use struct_size() instead of manually calculating the number of bytes to
allocate for 'caps', including the nested flexible array, and copy all of
'caps' to user space with a single copy_to_user() call (thanks to the full
size being provided by struct_size()).

Signed-off-by: Thorsten Blum <thorsten.blum@linux.dev>
Tested-by: Rick Edgecombe <rick.p.edgecombe@intel.com>
Link: https://patch.msgid.link/20251017213914.167301-1-thorsten.blum@linux.dev
[sean: separate from swap of get_user() vs. kzalloc() ordering]
Signed-off-by: Sean Christopherson <seanjc@google.com>
arch/x86/kvm/vmx/tdx.c

index cc751c088476679890a4e51a66ee2fa747e1cc46..a940a54ca5933f2c5d791d783973faf4d815765d 100644 (file)
@@ -2231,9 +2231,8 @@ static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
        if (nr_user_entries < td_conf->num_cpuid_config)
                return -E2BIG;
 
-       caps = kzalloc(sizeof(*caps) +
-                      sizeof(struct kvm_cpuid_entry2) * td_conf->num_cpuid_config,
-                      GFP_KERNEL);
+       caps = kzalloc(struct_size(caps, cpuid.entries,
+                                  td_conf->num_cpuid_config), GFP_KERNEL);
        if (!caps)
                return -ENOMEM;
 
@@ -2241,16 +2240,12 @@ static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
        if (ret)
                goto out;
 
-       if (copy_to_user(user_caps, caps, sizeof(*caps))) {
+       if (copy_to_user(user_caps, caps, struct_size(caps, cpuid.entries,
+                                                     caps->cpuid.nent))) {
                ret = -EFAULT;
                goto out;
        }
 
-       if (copy_to_user(user_caps->cpuid.entries, caps->cpuid.entries,
-                        caps->cpuid.nent *
-                        sizeof(caps->cpuid.entries[0])))
-               ret = -EFAULT;
-
 out:
        /* kfree() accepts NULL. */
        kfree(caps);