If we add first socket to nbd, config->socks is malloced but num_connections does not update(nsock's allocation fail), the memory is leaked. Cause in later nbd_config_put(), will only free config->socks when num_connections is not 0. Let nsock's allocation first to avoid this. Fixes: 03bf73c315ed ("nbd: prevent memory leak") Signed-off-by: Zheng Bin <zhengbin13@xxxxxxxxxx> --- v1->v2: modify comments drivers/block/nbd.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c index 43cff01a5a67..3e7709317b17 100644 --- a/drivers/block/nbd.c +++ b/drivers/block/nbd.c @@ -1037,21 +1037,22 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg, return -EBUSY; } + nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL); + if (!nsock) { + sockfd_put(sock); + return -ENOMEM; + } + socks = krealloc(config->socks, (config->num_connections + 1) * sizeof(struct nbd_sock *), GFP_KERNEL); if (!socks) { sockfd_put(sock); + kfree(nsock); return -ENOMEM; } config->socks = socks; - nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL); - if (!nsock) { - sockfd_put(sock); - return -ENOMEM; - } - nsock->fallback_index = -1; nsock->dead = false; mutex_init(&nsock->tx_lock); -- 2.26.0.106.g9fadedd