Re: [PATCH] LoongArch: KVM: Fix memory leak in kvm_loongarch_env_init() error path
From: Huacai Chen
Date: Mon Aug 31 2026 - 16:56:44 EST
Hi, Bibo,
What do you think about this?
Huacai
On Mon, Aug 17, 2026 at 7:59 PM Chaithanya Lagisetty
<nagachaithanya9911@xxxxxxxxx> wrote:
>
> kvm_loongarch_env_init() allocates the per-CPU kvm_context (vmcs) and
> kvm_loongarch_ops, and registers the perf callbacks, before registering
> the IPI/EIOINTC/PCH-PIC/DMSINTC KVM devices. If any of those device
> registrations fails, the function returned the error directly without
> freeing vmcs and kvm_loongarch_ops or unregistering the perf callbacks.
> kvm_loongarch_init() propagates the error without calling
> kvm_loongarch_env_exit(), so these resources are leaked.
>
> Unwind the already-acquired resources on the error path, mirroring
> kvm_loongarch_env_exit().
>
> Fixes: c532de5a67a7 ("LoongArch: KVM: Add IPI device support")
> Signed-off-by: Chaithanya Lagisetty <nagachaithanya9911@xxxxxxxxx>
> ---
> arch/loongarch/kvm/main.c | 19 +++++++++++++++----
> 1 file changed, 15 insertions(+), 4 deletions(-)
>
> diff --git a/arch/loongarch/kvm/main.c b/arch/loongarch/kvm/main.c
> index 3e1005526f4b..685d334cf957 100644
> --- a/arch/loongarch/kvm/main.c
> +++ b/arch/loongarch/kvm/main.c
> @@ -385,22 +385,33 @@ static int kvm_loongarch_env_init(void)
> /* Register LoongArch IPI interrupt controller interface. */
> ret = kvm_loongarch_register_ipi_device();
> if (ret)
> - return ret;
> + goto err;
>
> /* Register LoongArch EIOINTC interrupt controller interface. */
> ret = kvm_loongarch_register_eiointc_device();
> if (ret)
> - return ret;
> + goto err;
>
> /* Register LoongArch PCH-PIC interrupt controller interface. */
> ret = kvm_loongarch_register_pch_pic_device();
> if (ret)
> - return ret;
> + goto err;
>
> /* Register LoongArch DMSINTC interrupt contrroller interface */
> - if (cpu_has_msgint)
> + if (cpu_has_msgint) {
> ret = kvm_loongarch_register_dmsintc_device();
> + if (ret)
> + goto err;
> + }
>
> + return 0;
> +
> +err:
> + kvm_unregister_perf_callbacks();
> + kfree(kvm_loongarch_ops);
> + kvm_loongarch_ops = NULL;
> + free_percpu(vmcs);
> + vmcs = NULL;
> return ret;
> }
>
> --
> 2.43.0
>