Call sk_set_memalloc() before acquiring nsock->tx_lock in nbd_genl_reconnect_sock_cb() instead of while holding nsock->tx_lock. sk_set_memalloc() increments the memalloc_socks_key static branch, which acquires cpu_hotplug_lock and jump_label_mutex. Calling it under nsock->tx_lock creates a nsock->tx_lock -> cpu_hotplug_lock lockdep dependency chain. Because nbd_genl_reconnect_sock_cb() is called with nbd->config_lock held and is the only place that transitions nsock->dead from true to false, nsock->dead cannot become false after the initial check, so sk_set_memalloc() can safely be called before acquiring nsock->tx_lock. Since other contexts may set nsock->dead concurrently, read it with READ_ONCE() and annotate the stores in nbd_mark_nsock_dead() and nbd_genl_reconnect_sock_cb() with WRITE_ONCE(). Fixes: b7aa3d39385d ("nbd: add a reconfigure netlink command") Reported-by: syzbot+72fceb8393e04ce876d9@syzkaller.appspotmail.com Closes: https://lore.kernel.org/lkml/6aece79e.382bd2ce.33e041.0001.GAE@google.com/ Signed-off-by: Bart Van Assche --- drivers/block/nbd.c | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c index 4d362e3cc395..fd0789849612 100644 --- a/drivers/block/nbd.c +++ b/drivers/block/nbd.c @@ -335,7 +335,7 @@ static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock, } } } - nsock->dead = true; + WRITE_ONCE(nsock->dead, true); nsock->pending = NULL; nsock->sent = 0; } @@ -1447,26 +1447,31 @@ static int nbd_genl_reconnect_sock_cb(struct nbd_device *nbd, unsigned long arg) return -ENOMEM; } + lockdep_assert_held(&nbd->config_lock); + for (i = 0; i < config->num_connections; i++) { struct nbd_sock *nsock = config->socks[i]; - if (!nsock->dead) + /* + * Only this function, with config_lock held, clears + * nsock->dead. Other contexts may set it concurrently; if that + * happens after this check, the socket is reconnected on a + * later reconfigure request. + */ + if (!READ_ONCE(nsock->dead)) continue; - mutex_lock(&nsock->tx_lock); - if (!nsock->dead) { - mutex_unlock(&nsock->tx_lock); - continue; - } sk_set_memalloc(sock->sk); if (nbd->tag_set.timeout) sock->sk->sk_sndtimeo = nbd->tag_set.timeout; atomic_inc(&config->recv_threads); refcount_inc(&nbd->config_refs); + + mutex_lock(&nsock->tx_lock); old = nsock->sock; nsock->fallback_index = -1; nsock->sock = sock; - nsock->dead = false; + WRITE_ONCE(nsock->dead, false); INIT_WORK(&args->work, recv_work); args->index = i; args->nbd = nbd;