[PATCH] riscv/kvm: fix guest vector leak on host alloc failure

Yufan Chen yufan.chen at linux.dev
Sat Mar 28 02:21:57 PDT 2026


From: Yufan Chen <ericterminal at gmail.com>

When allocating vector context for a vCPU, guest_context.vector.datap is allocated before host_context.vector.datap. If the second allocation fails, the function returns -ENOMEM directly and leaks the guest buffer.

Switch the failure path to centralized cleanup. On host allocation failure, free guest_context.vector.datap, clear the pointer, and return -ENOMEM through a shared exit label.

Signed-off-by: Yufan Chen <ericterminal at gmail.com>
---
 arch/riscv/kvm/vcpu_vector.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/arch/riscv/kvm/vcpu_vector.c b/arch/riscv/kvm/vcpu_vector.c
index 05f3cc2d8..4c2f92dce 100644
--- a/arch/riscv/kvm/vcpu_vector.c
+++ b/arch/riscv/kvm/vcpu_vector.c
@@ -75,15 +75,23 @@ void kvm_riscv_vcpu_host_vector_restore(struct kvm_cpu_context *cntx)
 
 int kvm_riscv_vcpu_alloc_vector_context(struct kvm_vcpu *vcpu)
 {
+	int rc = -ENOMEM;
+
 	vcpu->arch.guest_context.vector.datap = kzalloc(riscv_v_vsize, GFP_KERNEL);
 	if (!vcpu->arch.guest_context.vector.datap)
-		return -ENOMEM;
+		goto out;
 
 	vcpu->arch.host_context.vector.datap = kzalloc(riscv_v_vsize, GFP_KERNEL);
 	if (!vcpu->arch.host_context.vector.datap)
-		return -ENOMEM;
+		goto free_guest_vector_datap;
 
 	return 0;
+
+free_guest_vector_datap:
+	kfree(vcpu->arch.guest_context.vector.datap);
+	vcpu->arch.guest_context.vector.datap = NULL;
+out:
+	return rc;
 }
 
 void kvm_riscv_vcpu_free_vector_context(struct kvm_vcpu *vcpu)
-- 
2.47.3




More information about the linux-riscv mailing list