[PATCH net] net/mlx5: HV VHCA: Fix the agent registration race

From: Ginger Li

Date: Tue Sep 22 2026 - 03:50:54 EST


mlx5_hv_vhca_agent_create() drops agents_lock between checking whether an
agent is already registered for the type and publishing the new agent, so two
concurrent create calls for the same type can both pass the check. The second
one then silently replaces the first one in hv_vhca->agents[], and the agent
allocated by the first call is leaked.

Hold agents_lock for the whole registration. While at it, read
hv_vhca->agents[MLX5_HV_VHCA_AGENT_CONTROL] under the lock in
mlx5_hv_vhca_cleanup() as well, since that slot is written under the lock.

Fixes: 87175120defd ("net/mlx5: Add HV VHCA infrastructure")
Signed-off-by: Ginger Li <ginger.jzllee@xxxxxxxxx>
---
drivers/net/ethernet/mellanox/mlx5/core/lib/hv_vhca.c | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/hv_vhca.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/hv_vhca.c
--- a/drivers/net/ethernet/mellanox/mlx5/core/lib/hv_vhca.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/hv_vhca.c
@@ -228,7 +228,10 @@ void mlx5_hv_vhca_cleanup(struct mlx5_hv_vhca *hv_vhca
if (!hv_vhca)
return;

+ mutex_lock(&hv_vhca->agents_lock);
agent = hv_vhca->agents[MLX5_HV_VHCA_AGENT_CONTROL];
+ mutex_unlock(&hv_vhca->agents_lock);
+
if (agent)
mlx5_hv_vhca_control_agent_destroy(agent);

@@ -270,11 +273,12 @@ mlx5_hv_vhca_agent_create(struct mlx5_hv_vhca *hv_vhca
mutex_unlock(&hv_vhca->agents_lock);
return ERR_PTR(-EINVAL);
}
- mutex_unlock(&hv_vhca->agents_lock);

agent = kzalloc_obj(*agent);
- if (!agent)
+ if (!agent) {
+ mutex_unlock(&hv_vhca->agents_lock);
return ERR_PTR(-ENOMEM);
+ }

agent->type = type;
agent->hv_vhca = hv_vhca;
@@ -286,7 +290,6 @@ mlx5_hv_vhca_agent_create(struct mlx5_hv_vhca *hv_vhca
if (ctx_update)
WRITE_ONCE(*ctx_update, agent);

- mutex_lock(&hv_vhca->agents_lock);
hv_vhca->agents[type] = agent;
mutex_unlock(&hv_vhca->agents_lock);

--
2.43.0