Skip to content

Commit 579dd91

Browse files
zhengbin13axboe
authored andcommitted
nbd: Fix memory leak in nbd_add_socket
When adding first socket to nbd, if nsock's allocation failed, the data structure member "config->socks" was reallocated, but the data structure member "config->num_connections" was not updated. A memory leak will occur then because the function "nbd_config_put" will free "config->socks" only when "config->num_connections" is not zero. Fixes: 03bf73c ("nbd: prevent memory leak") Reported-by: [email protected] Signed-off-by: Zheng Bin <[email protected]> Reviewed-by: Eric Biggers <[email protected]> Signed-off-by: Jens Axboe <[email protected]>
1 parent 05a4fed commit 579dd91

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

drivers/block/nbd.c

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,25 +1033,26 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
10331033
test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
10341034
dev_err(disk_to_dev(nbd->disk),
10351035
"Device being setup by another task");
1036-
sockfd_put(sock);
1037-
return -EBUSY;
1036+
err = -EBUSY;
1037+
goto put_socket;
1038+
}
1039+
1040+
nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1041+
if (!nsock) {
1042+
err = -ENOMEM;
1043+
goto put_socket;
10381044
}
10391045

10401046
socks = krealloc(config->socks, (config->num_connections + 1) *
10411047
sizeof(struct nbd_sock *), GFP_KERNEL);
10421048
if (!socks) {
1043-
sockfd_put(sock);
1044-
return -ENOMEM;
1049+
kfree(nsock);
1050+
err = -ENOMEM;
1051+
goto put_socket;
10451052
}
10461053

10471054
config->socks = socks;
10481055

1049-
nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
1050-
if (!nsock) {
1051-
sockfd_put(sock);
1052-
return -ENOMEM;
1053-
}
1054-
10551056
nsock->fallback_index = -1;
10561057
nsock->dead = false;
10571058
mutex_init(&nsock->tx_lock);
@@ -1063,6 +1064,10 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
10631064
atomic_inc(&config->live_connections);
10641065

10651066
return 0;
1067+
1068+
put_socket:
1069+
sockfd_put(sock);
1070+
return err;
10661071
}
10671072

10681073
static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)

0 commit comments

Comments
 (0)