Skip to contentSkip to conversation

vsock: only undo SS_CONNECTING when connect() fails

PATCH In review Bobby Eshleman 7 participants 14 messages Nov 18 – Nov 26

Subsystems (4)
lore
Share & tools
lore

Bobby Eshleman

author reviewer
#0 lore raw

PATCH v2 1/1 vsock: only undo SS_CONNECTING when connect() fails

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

---
Changes in v2:
- Only reset sk_state if it is still TCP_SYN_SENT, so a concurrent
connect() caller that times out late doesn't overwrite TCP_LISTEN
(Sashiko).
- Drop Michal's Reviewed-by since the code changed.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
 net/vmw_vsock/af_vsock.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
net/vmw_vsock/af_vsock.c +16 -6
index 1d7d53542724..ce958b48295b 100644
@@ -1704,6 +1704,19 @@ static void vsock_connect_timeout(struct work_struct *work)
 	sock_put(sk);
 }
 
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}
+
 static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 			 int addr_len, int flags)
 {
@@ -1862,8 +1875,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 			 * sk_state == TCP_SYN_SENT, which hereby we break.
 			 * In such case VIRTIO_VSOCK_OP_RST will follow.
 			 */
-			sk->sk_state = TCP_CLOSE;
-			sock->state = SS_UNCONNECTED;
+			vsock_connect_close(sock);
 
 			/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
 			 * transport->connect().
@@ -1877,10 +1889,8 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 	}
 
 	err = sock_error(sk);
-	if (err) {
-		sk->sk_state = TCP_CLOSE;
-		sock->state = SS_UNCONNECTED;
-	}
+	if (err)
+		vsock_connect_close(sock);
 
 out_wait:
 	finish_wait(sk_sleep(sk), &wait);

---
base-commit: 533ec433efdc11196f438da90d683053a57257ff
change-id: 20261116-vsock-connect-close-1beb7cb51e7a

Best regards,

Signature · 1 line
Bobby Eshleman <[email protected]>
#1 lore raw
This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

Hi!

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

- How the issue was discovered, e.g. hit in production, hit during development, syzbot report, manual code inspection, LLM or static analysis tool scan.

- Whether the issue was actually triggered, or is only theoretical (e.g. found by LLM and not proven at runtime). If it was triggered please include the symptoms, like the stack trace or kernel messages.

Please do not repost the series just to address the above. Instead, reply to this email with the missing information, so that reviewers can take it into account.

*IMPORTANT*: If you do repost (for other reasons) - please include the relevant info in the cover letter or commit messages.

Signature · 2 lines
The evaluation is done by an LLM so it may be wrong, if you think
that is the case please reply and explain.
#2 lore raw
In reply to Bobby Eshleman
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] vsock: incomplete handling of post-handshake reset in vsock_connect() - [Medium] vsock: concurrent…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] vsock: incomplete handling of post-handshake reset in vsock_connect()
- [Medium] vsock: concurrent vsock_connect() waiter stays in loop and clobbers retry
--

commit 82a88284866b93cccb5d48f9bd76a86ebb091f06
Author: Bobby Eshleman <[email protected]>

vsock: only undo SS_CONNECTING when connect() fails

This commit adds vsock_connect_close() so vsock_connect() only resets sk->sk_state to TCP_CLOSE when it is still TCP_SYN_SENT and sock->state to SS_UNCONNECTED when it is still SS_CONNECTING.

Quoted 10 lines
net/vmw_vsock/af_vsock.c +2 -0
index 1d7d53542724f..ce958b48295b9 100644
@@ -1704,6 +1704,19 @@ static void vsock_connect_timeout(struct work_struct *work)
 	sock_put(sk);
 }
 
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 10 lines
net/vmw_vsock/af_vsock.c +10 -0
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

[Severity: Medium]
Can a second thread blocked in vsock_connect() stay in the wait loop after the first attempt fails, and later clobber a retry connect() on the same socket?

CPU0 CPU1
vsock_connect()
sk->sk_state = TCP_SYN_SENT
sock->state = SS_CONNECTING
release_sock(sk)

                                  vsock_connect()
                                    /* sees SS_CONNECTING */
                                    release_sock(sk)
  /* timeout or peer RST */
  lock_sock(sk)
  sock_error(sk) /* clears sk_err */
  vsock_connect_close(sock)
    sk->sk_state = TCP_CLOSE
    sock->state = SS_UNCONNECTED
  release_sock(sk)
                                  lock_sock(sk)
                                  /* sk_state == TCP_CLOSE && sk_err == 0,
                                   * so while loop continues
                                   */
                                  release_sock(sk)
  vsock_connect() /* retry */
    sk->sk_state = TCP_SYN_SENT
    sock->state = SS_CONNECTING
    release_sock(sk)
                                  /* timeout or signal */
                                  lock_sock(sk)
                                  vsock_connect_close(sock)
                                    /* resets retry's TCP_SYN_SENT and
                                     * SS_CONNECTING
                                     */
                                  vsock_transport_cancel_pkt(vsk)

Because the wait loop only exits on TCP_ESTABLISHED, TCP_CLOSING or sk->sk_err != 0, CPU1 does not see that the socket left TCP_SYN_SENT once CPU0 clears sk->sk_err (or times out with sk->sk_err == 0). When CPU1 later times out or gets a signal, vsock_connect_close() sees TCP_SYN_SENT and SS_CONNECTING from the new connect() attempt, resets them to TCP_CLOSE and SS_UNCONNECTED while CPU0 sleeps, and cancels the new attempt's packets. Even if userspace called listen() instead of retrying connect(), CPU1 still calls vsock_transport_cancel_pkt() on timeout.

Also, if another thread consumes sk->sk_err via getsockopt(SO_ERROR) or recvmsg(MSG_ERRQUEUE) before vsock_connect() calls sock_error(sk), err is 0, so vsock_connect() skips vsock_connect_close() and returns 0 while leaving sock->state as SS_CONNECTING with sk->sk_state == TCP_CLOSE.

Quoted 13 lines
net/vmw_vsock/af_vsock.c +1 -2
@@ -1862,8 +1875,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 			 * sk_state == TCP_SYN_SENT, which hereby we break.
 			 * In such case VIRTIO_VSOCK_OP_RST will follow.
 			 */
-			sk->sk_state = TCP_CLOSE;
-			sock->state = SS_UNCONNECTED;
+			vsock_connect_close(sock);
 
 			/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
 			 * transport->connect().
@@ -1877,10 +1889,8 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 	}
 

net/vmw_vsock/af_vsock.c static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr, · line 1896

Quoted 10 lines
net/vmw_vsock/af_vsock.c +2 -4
 	err = sock_error(sk);
-	if (err) {
-		sk->sk_state = TCP_CLOSE;
-		sock->state = SS_UNCONNECTED;
-	}
+	if (err)
+		vsock_connect_close(sock);
 
 out_wait:
 	finish_wait(sk_sleep(sk), &wait);

[Severity: Medium]
When the transport completes the handshake (setting sock->state to SS_CONNECTED and sk->sk_state to TCP_ESTABLISHED) and then resets the socket to TCP_CLOSE while vsock_connect() is sleeping, does vsock_connect() still mishandle the post-handshake reset in the wait loop and error path?

First, in vmci_transport_handle_detach(), a detach after the socket has already reached TCP_ESTABLISHED sets sk->sk_state = TCP_CLOSE without setting sk->sk_err:

net/vmw_vsock/vmci_transport.c:vmci_transport_handle_detach() {
    ...
			if (sk->sk_state == TCP_SYN_SENT) {
				sk->sk_state = TCP_CLOSE;
				sk->sk_err = ECONNRESET;
				sk_error_report(sk);
				return;
			}
			sk->sk_state = TCP_CLOSE;
    ...
}

When vsock_connect() wakes up, sk->sk_state is neither TCP_ESTABLISHED nor TCP_CLOSING and sk->sk_err is 0, so it re-enters schedule_timeout() and blocks until connect_timeout expires.

Second, if a timeout or signal coincides with a post-handshake reset to TCP_CLOSE, vsock_connect() enters the signal/timeout branch and calls vsock_transport_cancel_pkt(vsk) on a socket whose sock->state is already SS_CONNECTED. If another thread called sendmsg() once sock->state became SS_CONNECTED, virtio_transport_cancel_pkt() purges queued VIRTIO_VSOCK_OP_RW packets without decrementing vvs->bytes_unsent, leaving unsent-byte accounting for SIOCOUTQ and vsock_linger() out of sync.

Third, when virtio_vsock_reset_sock() or vhost_vsock_reset_orphans() sets sk->sk_err = ECONNRESET after the handshake completed, vsock_connect() exits the loop, consumes sk->sk_err via sock_error(sk), and returns -ECONNRESET from connect() while leaving sock->state as SS_CONNECTED.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw
In reply to Bobby Eshleman
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] A connect() waiter that times out late can still abort a newer connect attempt on the same socket.
- [Low] The commit message names the wrong trigger paths.
- [Low] If another thread calls shutdown() while a blocking connect() is sleeping, a failed connect now leaves the socket in SS_DISCONNECTING…

--

vsock: only undo SS_CONNECTING when connect() fails

This patch adds a vsock_connect_close() helper. On a failed connect(), it moves sk_state to TCP_CLOSE only if it is still TCP_SYN_SENT, and moves sock->state to SS_UNCONNECTED only if it is still SS_CONNECTING. The goal is to stop a socket that got connected and was then reset from going back to SS_UNCONNECTED, and to stop a late waiter from overwriting TCP_LISTEN.

Quoted 6 lines

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED.

[Severity: Low]
Does this description hold for all three examples?

virtio_vsock_reset_sock() fits it: it sets sk_state = TCP_CLOSE and sk_err = ECONNRESET.

vhost_vsock_reset_orphans() in drivers/vhost/vsock.c writes a socket_state constant into sk_state:

    sk->sk_state = SS_UNCONNECTED;
    sk->sk_err = ECONNRESET;

SS_UNCONNECTED has the same value (1) as TCP_ESTABLISHED. This function also only runs on sockets in vsock_connected_table, which are already established. So a vsock_connect() that gets the lock back takes the early exit:

    if (sk->sk_state == TCP_ESTABLISHED ||
        sk->sk_state == TCP_CLOSING) {
        err = 0;
        goto out_wait;
    }

It returns 0 and never reaches the code this patch changes.

vmci_transport_handle_detach() sets sk_err only in the TCP_SYN_SENT branch. For an established socket it only does this, and sk_err stays 0:

    sk->sk_state = TCP_CLOSE;

connect() then goes back to sleep and reaches the reset through the timeout/signal branch, not through the sock_error() branch.

The code change covers both reset sites, so only the description is affected. Could the commit message say which transports actually reach this, and by which path?

Quoted 9 lines
net/vmw_vsock/af_vsock.c +1 -0
index 1d7d53542724f..ce958b48295b9 100644
@@ -1704,6 +1704,19 @@ static void vsock_connect_timeout(struct work_struct *work)
 	sock_put(sk);
 }
 
+/* Avoid breaking the socket when another thread has changed its state while

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1717

Quoted 10 lines
net/vmw_vsock/af_vsock.c +10 -0
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;

[Severity: Low]
What happens if another thread calls shutdown() while a blocking connect() is asleep?

vsock_shutdown() moves any socket that is not SS_UNCONNECTED to SS_DISCONNECTING, including one that is still SS_CONNECTING:

    } else {
        sock->state = SS_DISCONNECTING;
        err = 0;
    }

Later the sleeping connect() times out, gets a signal, or sees sk_err. vsock_connect_close() then moves sk_state from TCP_SYN_SENT to TCP_CLOSE, but sock->state stays SS_DISCONNECTING. After that, every connect() takes this path:

    case SS_DISCONNECTING:
        err = -EINVAL;
        goto out;

listen() also fails its sock->state != SS_UNCONNECTED check. So a socket that never connected can no longer be reused. Before this patch it went back to SS_UNCONNECTED.

The non-blocking path in vsock_connect_timeout() still resets sock->state without checking it:

    if (sk->sk_state == TCP_SYN_SENT &&
        (sk->sk_shutdown != SHUTDOWN_MASK)) {
        sk->sk_state = TCP_CLOSE;
        sk->sk_socket->state = SS_UNCONNECTED;

So the same shutdown-during-connect race now ends differently depending on O_NONBLOCK.

SS_DISCONNECTING does need to stay when the connection was established before shutdown() and the reset. Otherwise SS_CONNECTED -> SS_DISCONNECTING -> reset brings the original problem back. Could the helper tell the never-established case apart, for example by looking at sk_state, instead of either always keeping or always clearing SS_DISCONNECTING?

Quoted 2 lines
net/vmw_vsock/af_vsock.c +2 -0
+}
+

[ ... ]

net/vmw_vsock/af_vsock.c static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr, · line 1881

Quoted 10 lines
net/vmw_vsock/af_vsock.c +1 -2
@@ -1862,8 +1875,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 			 * sk_state == TCP_SYN_SENT, which hereby we break.
 			 * In such case VIRTIO_VSOCK_OP_RST will follow.
 			 */
-			sk->sk_state = TCP_CLOSE;
-			sock->state = SS_UNCONNECTED;
+			vsock_connect_close(sock);
 
 			/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
 			 * transport->connect().

[Severity: Medium]
Can a connect() waiter that times out late still abort a newer connect attempt on the same socket?

vsock_connect_close() only checks whether the socket looks like it is connecting right now. It cannot tell whether TCP_SYN_SENT / SS_CONNECTING belongs to this waiter's attempt or to a later connect() call.

Here is a possible sequence in vsock_connect():

Thread A
blocking connect(), sets TCP_SYN_SENT / SS_CONNECTING, sleeps

Thread B
connect() on the same socket, takes the SS_CONNECTING case (-EALREADY), sleeps with a full connect_timeout

The peer rejects the handshake:

  virtio_transport_recv_connecting()
      sk->sk_state = TCP_CLOSE;
      sk->sk_err = skerr;
      sk_error_report(sk);

Thread A
wakes first, sock_error() clears sk_err to 0,
vsock_connect_close() sets SS_UNCONNECTED

Thread B
wakes, sees TCP_CLOSE with sk_err == 0, sleeps for the rest of its timeout

Thread C
connect() takes the default branch, sets TCP_SYN_SENT, sends a REQUEST, sets SS_CONNECTING

Thread B
timeout expires:
vsock_connect_close(sock); <- sees C's state, resets it
vsock_transport_cancel_pkt(vsk); <- cancels C's REQUEST

C is not woken and gets no error. It sleeps until its own timeout and returns -ETIMEDOUT. A peer RESPONSE that arrives while the socket is in TCP_CLOSE gets an RST.

This looks like the same stale-waiter problem that v2 fixes for TCP_LISTEN. The new helper's comment says "Avoid breaking the socket when another thread has changed its state while we were asleep". Should this case be covered as well?

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261117-vsock-connect-close-v2-1-db5388323770%40meta.com
#4 lore raw
In reply to Bobby Eshleman
Quoted 10 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Quoted 8 lines

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Ohh, this took me a while.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 12 lines
net/vmw_vsock/af_vsock.c +12 -0
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

I was wondering why not

	if (sk->sk_state == TCP_SYN_SENT) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}

and I think the only reasons we can't say "SYN_SENT iff CONNECTING" is because shutdown() can flip SYN_SENT/CONNECTING to SYN_SENT/DISCONNECTING. On connect's failure, the blocking path kinda-ignores such shutdown() and resets the socket to UNCONNECTED anyway, while the non-blocking (i.e. vsock_connect_timeout()) also consults sk_shutdown != SHUTDOWN_MASK.

So how about being consistent:

static void vsock_connect_close(struct socket *sock)

{
	struct sock *sk = sock->sk;

	// we follow vsock_connect_timeout():
	// TCP_SYN_SENT implies SS_{DIS,}CONNECTING;
	// and we do check sk_shutdown
	//
	// or am I missing something?

	if (sk->sk_state == TCP_SYN_SENT &&
	    sk->sk_shutdown != SHUTDOWN_MASK) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}
}

What do you think?

I guess this approach also addresses "[Severity: Low] What happens if another thread calls shutdown() while a blocking connect() is asleep?". As for "[Severity: Medium] Can a connect() waiter that times out late still abort a newer connect attempt on the same socket?", isn't this the current situation?

thanks,
Michal

author reviewer
#5 lore raw
Quoted 67 lines · Michal Luczaj
Quoted 10 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Quoted 8 lines

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Ohh, this took me a while.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 12 lines
net/vmw_vsock/af_vsock.c +12 -0
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

I was wondering why not

	if (sk->sk_state == TCP_SYN_SENT) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}

and I think the only reasons we can't say "SYN_SENT iff CONNECTING" is because shutdown() can flip SYN_SENT/CONNECTING to SYN_SENT/DISCONNECTING. On connect's failure, the blocking path kinda-ignores such shutdown() and resets the socket to UNCONNECTED anyway, while the non-blocking (i.e. vsock_connect_timeout()) also consults sk_shutdown != SHUTDOWN_MASK.

So how about being consistent:

static void vsock_connect_close(struct socket *sock)

{
	struct sock *sk = sock->sk;

	// we follow vsock_connect_timeout():
	// TCP_SYN_SENT implies SS_{DIS,}CONNECTING;
	// and we do check sk_shutdown
	//
	// or am I missing something?

	if (sk->sk_state == TCP_SYN_SENT &&
	    sk->sk_shutdown != SHUTDOWN_MASK) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}
}
Quoted 1 line

What do you think?

I think we could say TCP_SYN_SENT implies SS_{DIS,}CONNECTING, but probably not the reverse... without a peer on the other end our connect request gets an RST reply, switching to TCP_CLOSE but leaving untouched SS_CONNECTING. Using only TCP_SYN_SENT then skips resetting SS_CONNECTING to SS_UNCONNECTED, and future connect() retries hit -EALREADY forever.

It seems to work for vsock_connect_timeout() because that function only needs to test if the attempt to connect is still pending (if yes, then close everything up), but vsock_connect_close() needs to know more precisely if the socket still holds the state that this current connect attempt changed... so it separately checks "Did we set TCP_SYN_SENT? if so, set to TCP_CLOSE. Did we set SS_CONNECTING? If so, set to SS_UNCONNECTED."

I think it might even make more sense to consolidate in the other direction and make vsock_connect_timeout() a caller of the new vsock_connect_close(), since it appears there is a similar edge case there...

connect(), O_NONBLOCK
transport->connect() /* OP_REQUEST */
mod_delayed_work(connect_work)

shutdown(SHUT_RDWR)
sock->state = SS_DISCONNECTING
sk_shutdown = SHUTDOWN_MASK

vsock_connect_timeout()
skips the socket because of SHUTDOWN_MASK
/* still TCP_SYN_SENT / SS_DISCONNECTING */

late OP_RESPONSE, virtio_transport_recv_connecting()
sk_state = TCP_ESTABLISHED
sock->state = SS_CONNECTED vsock_insert_connected()

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Or am I off track / missing something?

Quoted 9 lines

I guess this approach also addresses "[Severity: Low] What happens if another thread calls shutdown() while a blocking connect() is asleep?". As for "[Severity: Medium] Can a connect() waiter that times out late still abort a newer connect attempt on the same socket?", isn't this the current situation?

thanks,
Michal

Yeah, Sashiko is worried that a racing shutdown() breaks reusing the socket, but AFAIK vsock doesn't support reuse after shutdown anyway. Before this patch a second connect() could succeed, but the shutdown flags are never cleared, so sendmsg() still returns -EPIPE and recvmsg() returns 0. With this patch the socket stays SS_DISCONNECTING, so connect() fails with -EINVAL instead.

And agreed about the medium issue, the late connect() waiter race is no different than before this patch.

Thanks,
Bobby

maintainer
#6 lore raw
Quoted 107 lines · Bobby Eshleman
Quoted 67 lines · Michal Luczaj
Quoted 10 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Quoted 8 lines

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Ohh, this took me a while.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 12 lines
net/vmw_vsock/af_vsock.c +12 -0
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

I was wondering why not

	if (sk->sk_state == TCP_SYN_SENT) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}

and I think the only reasons we can't say "SYN_SENT iff CONNECTING" is because shutdown() can flip SYN_SENT/CONNECTING to SYN_SENT/DISCONNECTING. On connect's failure, the blocking path kinda-ignores such shutdown() and resets the socket to UNCONNECTED anyway, while the non-blocking (i.e. vsock_connect_timeout()) also consults sk_shutdown != SHUTDOWN_MASK.

So how about being consistent:

static void vsock_connect_close(struct socket *sock)

{
	struct sock *sk = sock->sk;

	// we follow vsock_connect_timeout():
	// TCP_SYN_SENT implies SS_{DIS,}CONNECTING;
	// and we do check sk_shutdown
	//
	// or am I missing something?

	if (sk->sk_state == TCP_SYN_SENT &&
	    sk->sk_shutdown != SHUTDOWN_MASK) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}
}
Quoted 1 line

What do you think?

I think we could say TCP_SYN_SENT implies SS_{DIS,}CONNECTING, but probably not the reverse... without a peer on the other end our connect request gets an RST reply, switching to TCP_CLOSE but leaving untouched SS_CONNECTING. Using only TCP_SYN_SENT then skips resetting SS_CONNECTING to SS_UNCONNECTED, and future connect() retries hit -EALREADY forever.

It seems to work for vsock_connect_timeout() because that function only needs to test if the attempt to connect is still pending (if yes, then close everything up), but vsock_connect_close() needs to know more precisely if the socket still holds the state that this current connect attempt changed... so it separately checks "Did we set TCP_SYN_SENT? if so, set to TCP_CLOSE. Did we set SS_CONNECTING? If so, set to SS_UNCONNECTED."

I think it might even make more sense to consolidate in the other direction and make vsock_connect_timeout() a caller of the new vsock_connect_close(), since it appears there is a similar edge case there...

connect(), O_NONBLOCK
transport->connect() /* OP_REQUEST */
mod_delayed_work(connect_work)

shutdown(SHUT_RDWR)
sock->state = SS_DISCONNECTING
sk_shutdown = SHUTDOWN_MASK

vsock_connect_timeout()
skips the socket because of SHUTDOWN_MASK
/* still TCP_SYN_SENT / SS_DISCONNECTING */

late OP_RESPONSE, virtio_transport_recv_connecting()
sk_state = TCP_ESTABLISHED
sock->state = SS_CONNECTED vsock_insert_connected()

Quoted 6 lines

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Or am I off track / missing something?

I have slightly different question: is the 'multiple threads connecting/disconnecting the same socket concurrently' a relevant scenario? Otherwise if final state is self-consistent (i.e. _NOT_ TCP_SYN_SENT + SS_DISCONNECTING) I think there is nothing to fix here.

/P

author reviewer
#7 lore raw
Quoted 113 lines · Paolo Abeni
Quoted 112 lines · Bobby Eshleman
Quoted 67 lines · Michal Luczaj
Quoted 10 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Quoted 8 lines

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Ohh, this took me a while.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 12 lines
net/vmw_vsock/af_vsock.c +12 -0
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

I was wondering why not

	if (sk->sk_state == TCP_SYN_SENT) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}

and I think the only reasons we can't say "SYN_SENT iff CONNECTING" is because shutdown() can flip SYN_SENT/CONNECTING to SYN_SENT/DISCONNECTING. On connect's failure, the blocking path kinda-ignores such shutdown() and resets the socket to UNCONNECTED anyway, while the non-blocking (i.e. vsock_connect_timeout()) also consults sk_shutdown != SHUTDOWN_MASK.

So how about being consistent:

static void vsock_connect_close(struct socket *sock)

{
	struct sock *sk = sock->sk;

	// we follow vsock_connect_timeout():
	// TCP_SYN_SENT implies SS_{DIS,}CONNECTING;
	// and we do check sk_shutdown
	//
	// or am I missing something?

	if (sk->sk_state == TCP_SYN_SENT &&
	    sk->sk_shutdown != SHUTDOWN_MASK) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}
}
Quoted 1 line

What do you think?

I think we could say TCP_SYN_SENT implies SS_{DIS,}CONNECTING, but probably not the reverse... without a peer on the other end our connect request gets an RST reply, switching to TCP_CLOSE but leaving untouched SS_CONNECTING. Using only TCP_SYN_SENT then skips resetting SS_CONNECTING to SS_UNCONNECTED, and future connect() retries hit -EALREADY forever.

It seems to work for vsock_connect_timeout() because that function only needs to test if the attempt to connect is still pending (if yes, then close everything up), but vsock_connect_close() needs to know more precisely if the socket still holds the state that this current connect attempt changed... so it separately checks "Did we set TCP_SYN_SENT? if so, set to TCP_CLOSE. Did we set SS_CONNECTING? If so, set to SS_UNCONNECTED."

I think it might even make more sense to consolidate in the other direction and make vsock_connect_timeout() a caller of the new vsock_connect_close(), since it appears there is a similar edge case there...

connect(), O_NONBLOCK
transport->connect() /* OP_REQUEST */
mod_delayed_work(connect_work)

shutdown(SHUT_RDWR)
sock->state = SS_DISCONNECTING
sk_shutdown = SHUTDOWN_MASK

vsock_connect_timeout()
skips the socket because of SHUTDOWN_MASK
/* still TCP_SYN_SENT / SS_DISCONNECTING */

late OP_RESPONSE, virtio_transport_recv_connecting()
sk_state = TCP_ESTABLISHED
sock->state = SS_CONNECTED vsock_insert_connected()

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Quoted 8 lines
Quoted 1 line

Or am I off track / missing something?

I have slightly different question: is the 'multiple threads connecting/disconnecting the same socket concurrently' a relevant scenario? Otherwise if final state is self-consistent (i.e. _NOT_ TCP_SYN_SENT + SS_DISCONNECTING) I think there is nothing to fix here.

/P

To your point, the only user-facing issue I can see with vsock_connect_timeout() would be seen in pretty rare cases.... Since it skips the socket when sk_shutdown == SHUTDOWN_MASK, if the peer never responds with RST the connect attempt never times out, the socket sits in TCP_SYN_SENT + SS_DISCONNECTING (connect() returning -EINVAL) until close(). But I'm pretty sure this could only happen on the vhost side if the guest was unresponsive/crashed or on the virtio side if maybe vhost's RST dropped during VM migration when vhost's send queue is purged. IMHO this should probably be fixed, but I don't think its worth turning the code upside down for.

Looking at this connect()/shutdown() sequence again today... with O_NONBLOCK, there is some inconsistent behavior that although is not caused by vsock_connect_timeout(), I'd like to mention here since its come up. It exists even for a single thread making both calls. Playing w/ vsock_loopback and bpftrace, it does end up with SS_DISCONNECTING + TCP_SYN_SENT, but I think the most unexpected thing from the user's perspective is that it temporarily flips to SS_CONNECTED even after shutdown() and a number of syscalls present the socket as connected:

  repro    connect()     -> -EINPROGRESS  SS_CONNECTING     TCP_SYN_SENT
  repro    shutdown()    -> 0             SS_DISCONNECTING  TCP_SYN_SENT
  repro    getpeername() -> -ENOTCONN     SS_DISCONNECTING  TCP_SYN_SENT
  repro    connect()     -> -EINVAL       SS_DISCONNECTING  TCP_SYN_SENT
  repro    recv()        -> -ENOTCONN     SS_DISCONNECTING  TCP_SYN_SENT
  repro    SO_ERROR      =  0
  repro    poll()        -> IN|HUP|RDHUP  SS_DISCONNECTING  TCP_SYN_SENT
  kworker  recv_pkt(OP_RESPONSE)          SS_CONNECTED      TCP_ESTABLISHED

^ the switch to connected is here

  repro    getpeername() -> 0             SS_CONNECTED      TCP_ESTABLISHED
  repro    connect()     -> -EISCONN      SS_CONNECTED      TCP_ESTABLISHED
  repro    recv()        -> 0             SS_CONNECTED      TCP_ESTABLISHED
  repro    SO_ERROR      =  0

^ the socket starts partially acting like it's connected/established

  repro    poll()        -> IN|HUP|RDHUP  SS_CONNECTED      TCP_ESTABLISHED
  kworker  recv_pkt(OP_RST)               SS_CONNECTED      TCP_CLOSING

^ eventually RST shows up and shuts things down

TCP handles this better... shutdown() on SYN_SENT socket aborts the connect attempt w/ tcp_disconnect() resulting in TCP_CLOSE, SS_UNCONNECTED, sk_err = ECONNRESET, and the late SYN-ACK doesn't push it into established, and users see POLLERR/SO_ERROR.

I think the TCP approach also fixes that edge case with vsock_connect_timeout(), since the user would at least see the errors.

Best,
Bobby

maintainer
#8 lore raw
Quoted 163 lines · Bobby Eshleman
Quoted 113 lines · Paolo Abeni
Quoted 112 lines · Bobby Eshleman
Quoted 67 lines · Michal Luczaj
Quoted 10 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Quoted 8 lines

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Ohh, this took me a while.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 12 lines
net/vmw_vsock/af_vsock.c +12 -0
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

I was wondering why not

	if (sk->sk_state == TCP_SYN_SENT) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}

and I think the only reasons we can't say "SYN_SENT iff CONNECTING" is because shutdown() can flip SYN_SENT/CONNECTING to SYN_SENT/DISCONNECTING. On connect's failure, the blocking path kinda-ignores such shutdown() and resets the socket to UNCONNECTED anyway, while the non-blocking (i.e. vsock_connect_timeout()) also consults sk_shutdown != SHUTDOWN_MASK.

So how about being consistent:

static void vsock_connect_close(struct socket *sock)

{
	struct sock *sk = sock->sk;

	// we follow vsock_connect_timeout():
	// TCP_SYN_SENT implies SS_{DIS,}CONNECTING;
	// and we do check sk_shutdown
	//
	// or am I missing something?

	if (sk->sk_state == TCP_SYN_SENT &&
	    sk->sk_shutdown != SHUTDOWN_MASK) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}
}
Quoted 1 line

What do you think?

I think we could say TCP_SYN_SENT implies SS_{DIS,}CONNECTING, but probably not the reverse... without a peer on the other end our connect request gets an RST reply, switching to TCP_CLOSE but leaving untouched SS_CONNECTING. Using only TCP_SYN_SENT then skips resetting SS_CONNECTING to SS_UNCONNECTED, and future connect() retries hit -EALREADY forever.

It seems to work for vsock_connect_timeout() because that function only needs to test if the attempt to connect is still pending (if yes, then close everything up), but vsock_connect_close() needs to know more precisely if the socket still holds the state that this current connect attempt changed... so it separately checks "Did we set TCP_SYN_SENT? if so, set to TCP_CLOSE. Did we set SS_CONNECTING? If so, set to SS_UNCONNECTED."

I think it might even make more sense to consolidate in the other direction and make vsock_connect_timeout() a caller of the new vsock_connect_close(), since it appears there is a similar edge case there...

connect(), O_NONBLOCK

    transport->connect()  /* OP_REQUEST */
    mod_delayed_work(connect_work)

shutdown(SHUT_RDWR)
sock->state = SS_DISCONNECTING
sk_shutdown = SHUTDOWN_MASK

vsock_connect_timeout()
skips the socket because of SHUTDOWN_MASK
/* still TCP_SYN_SENT / SS_DISCONNECTING */

late OP_RESPONSE, virtio_transport_recv_connecting()
sk_state = TCP_ESTABLISHED
sock->state = SS_CONNECTED vsock_insert_connected()

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Quoted 8 lines
Quoted 1 line

Or am I off track / missing something?

I have slightly different question: is the 'multiple threads connecting/disconnecting the same socket concurrently' a relevant scenario? Otherwise if final state is self-consistent (i.e. _NOT_ TCP_SYN_SENT + SS_DISCONNECTING) I think there is nothing to fix here.

/P

To your point, the only user-facing issue I can see with vsock_connect_timeout() would be seen in pretty rare cases.... Since it skips the socket when sk_shutdown == SHUTDOWN_MASK, if the peer never responds with RST the connect attempt never times out, the socket sits in TCP_SYN_SENT + SS_DISCONNECTING (connect() returning -EINVAL) until close(). But I'm pretty sure this could only happen on the vhost side if the guest was unresponsive/crashed or on the virtio side if maybe vhost's RST dropped during VM migration when vhost's send queue is purged. IMHO this should probably be fixed, but I don't think its worth turning the code upside down for.

Looking at this connect()/shutdown() sequence again today... with O_NONBLOCK, there is some inconsistent behavior that although is not caused by vsock_connect_timeout(), I'd like to mention here since its come up. It exists even for a single thread making both calls. Playing w/ vsock_loopback and bpftrace, it does end up with SS_DISCONNECTING + TCP_SYN_SENT, but I think the most unexpected thing from the user's perspective is that it temporarily flips to SS_CONNECTED even after shutdown() and a number of syscalls present the socket as connected:

   repro    connect()     -> -EINPROGRESS  SS_CONNECTING     TCP_SYN_SENT
   repro    shutdown()    -> 0             SS_DISCONNECTING  TCP_SYN_SENT
   repro    getpeername() -> -ENOTCONN     SS_DISCONNECTING  TCP_SYN_SENT
   repro    connect()     -> -EINVAL       SS_DISCONNECTING  TCP_SYN_SENT
   repro    recv()        -> -ENOTCONN     SS_DISCONNECTING  TCP_SYN_SENT
   repro    SO_ERROR      =  0
   repro    poll()        -> IN|HUP|RDHUP  SS_DISCONNECTING  TCP_SYN_SENT
   kworker  recv_pkt(OP_RESPONSE)          SS_CONNECTED      TCP_ESTABLISHED

^ the switch to connected is here

   repro    getpeername() -> 0             SS_CONNECTED      TCP_ESTABLISHED
   repro    connect()     -> -EISCONN      SS_CONNECTED      TCP_ESTABLISHED
   repro    recv()        -> 0             SS_CONNECTED      TCP_ESTABLISHED
   repro    SO_ERROR      =  0

^ the socket starts partially acting like it's connected/established

   repro    poll()        -> IN|HUP|RDHUP  SS_CONNECTED      TCP_ESTABLISHED
   kworker  recv_pkt(OP_RST)               SS_CONNECTED      TCP_CLOSING

^ eventually RST shows up and shuts things down

Quoted 7 lines

TCP handles this better... shutdown() on SYN_SENT socket aborts the connect attempt w/ tcp_disconnect() resulting in TCP_CLOSE, SS_UNCONNECTED, sk_err = ECONNRESET, and the late SYN-ACK doesn't push it into established, and users see POLLERR/SO_ERROR.

I think the TCP approach also fixes that edge case with vsock_connect_timeout(), since the user would at least see the errors.

Ok, it looks worth addressing. But possibly for net-next? since 'broken from the beginning', not critical and possibly some functional change implied.

/P

#9 lore raw
In reply to Bobby Eshleman
Quoted 68 lines · Bobby Eshleman
Quoted 67 lines · Michal Luczaj
Quoted 10 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Quoted 8 lines

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Ohh, this took me a while.

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1718

Quoted 12 lines
net/vmw_vsock/af_vsock.c +12 -0
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}

I was wondering why not

	if (sk->sk_state == TCP_SYN_SENT) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}

and I think the only reasons we can't say "SYN_SENT iff CONNECTING" is because shutdown() can flip SYN_SENT/CONNECTING to SYN_SENT/DISCONNECTING. On connect's failure, the blocking path kinda-ignores such shutdown() and resets the socket to UNCONNECTED anyway, while the non-blocking (i.e. vsock_connect_timeout()) also consults sk_shutdown != SHUTDOWN_MASK.

So how about being consistent:

static void vsock_connect_close(struct socket *sock)

{
	struct sock *sk = sock->sk;

	// we follow vsock_connect_timeout():
	// TCP_SYN_SENT implies SS_{DIS,}CONNECTING;
	// and we do check sk_shutdown
	//
	// or am I missing something?

	if (sk->sk_state == TCP_SYN_SENT &&
	    sk->sk_shutdown != SHUTDOWN_MASK) {
		sk->sk_state = TCP_CLOSE;
		sock->state = SS_UNCONNECTED;
	}
}
Quoted 8 lines
Quoted 1 line

What do you think?

I think we could say TCP_SYN_SENT implies SS_{DIS,}CONNECTING, but probably not the reverse... without a peer on the other end our connect request gets an RST reply, switching to TCP_CLOSE but leaving untouched SS_CONNECTING. Using only TCP_SYN_SENT then skips resetting SS_CONNECTING to SS_UNCONNECTED, and future connect() retries hit -EALREADY forever.

Ugh, true. And your double-if approach has it covered.

Quoted 7 lines

It seems to work for vsock_connect_timeout() because that function only needs to test if the attempt to connect is still pending (if yes, then close everything up), but vsock_connect_close() needs to know more precisely if the socket still holds the state that this current connect attempt changed... so it separately checks "Did we set TCP_SYN_SENT? if so, set to TCP_CLOSE. Did we set SS_CONNECTING? If so, set to SS_UNCONNECTED."

Right, got it.

Quoted 22 lines

I think it might even make more sense to consolidate in the other direction and make vsock_connect_timeout() a caller of the new vsock_connect_close(), since it appears there is a similar edge case there...

connect(), O_NONBLOCK
transport->connect() /* OP_REQUEST */
mod_delayed_work(connect_work)

shutdown(SHUT_RDWR)
sock->state = SS_DISCONNECTING
sk_shutdown = SHUTDOWN_MASK

vsock_connect_timeout()
skips the socket because of SHUTDOWN_MASK
/* still TCP_SYN_SENT / SS_DISCONNECTING */

late OP_RESPONSE, virtio_transport_recv_connecting()
sk_state = TCP_ESTABLISHED
sock->state = SS_CONNECTED vsock_insert_connected()

Quoted 4 lines

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Great, I'm all in favour of consolidation. So in the scenario above, invoking vsock_connect_close() on vsock_connect_timeout() (with sk_shutdown check dropped) would result in CLOSE/DISCONNECTING, and no more late virtio_transport_recv_connecting(), right?

Quoted 6 lines
Quoted 6 lines

I guess this approach also addresses "[Severity: Low] What happens if another thread calls shutdown() while a blocking connect() is asleep?". As for "[Severity: Medium] Can a connect() waiter that times out late still abort a newer connect attempt on the same socket?", isn't this the current situation?

Quoted 6 lines

Yeah, Sashiko is worried that a racing shutdown() breaks reusing the socket, but AFAIK vsock doesn't support reuse after shutdown anyway. Before this patch a second connect() could succeed, but the shutdown flags are never cleared, so sendmsg() still returns -EPIPE and recvmsg() returns 0. With this patch the socket stays SS_DISCONNECTING, so connect() fails with -EINVAL instead.

One more detail: currently a sock that went through a failed connect() can still become a listener. A transport-bearing listener, which I don't think is good. So, except for the connect+shutdown case, this does not change with your patch, right?

Quoted 2 lines

And agreed about the medium issue, the late connect() waiter race is no different than before this patch.

Paolo, is this the "multiple threads connecting/disconnecting the same socket concurrently" you were referring to? Yeah, I think there's an agreement it's not an issue.

thanks,
Michal

author reviewer
#10 lore raw
Quoted 2 lines · Michal Luczaj
Quoted 1 line · Bobby Eshleman

On Sat, Nov 21, 2026 at 07:32:15PM +0100, Michal Luczaj wrote:

[...]

Quoted 9 lines
Quoted 4 lines

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Great, I'm all in favour of consolidation. So in the scenario above, invoking vsock_connect_close() on vsock_connect_timeout() (with sk_shutdown check dropped) would result in CLOSE/DISCONNECTING, and no more late virtio_transport_recv_connecting(), right?

Right, that late response will fall through and get an RST back. I'm not 100% sure yet about how to rework the sk_shutdown check yet though. I mention TCP's approach to shutdowns in my reply to Paolo and I'm thinking thats probably the right way to go about it, but not 100% sure yet...

Do we agree that touching vsock_connect_timeout() should not happen in this patch? Is there anything pending on this one from your perspective Michal?

[...]

Quoted 4 lines

One more detail: currently a sock that went through a failed connect() can still become a listener. A transport-bearing listener, which I don't think is good. So, except for the connect+shutdown case, this does not change with your patch, right?

Yeah I don't think this changes here.

Best,
Bobby

Reviewed-by
#11 lore raw
Quoted 22 lines · Bobby Eshleman
Quoted 2 lines · Michal Luczaj
Quoted 1 line · Bobby Eshleman

On Sat, Nov 21, 2026 at 07:32:15PM +0100, Michal Luczaj wrote:

[...]

Quoted 9 lines
Quoted 4 lines

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Great, I'm all in favour of consolidation. So in the scenario above, invoking vsock_connect_close() on vsock_connect_timeout() (with sk_shutdown check dropped) would result in CLOSE/DISCONNECTING, and no more late virtio_transport_recv_connecting(), right?

Right, that late response will fall through and get an RST back. I'm not 100% sure yet about how to rework the sk_shutdown check yet though. I mention TCP's approach to shutdowns in my reply to Paolo and I'm thinking thats probably the right way to go about it, but not 100% sure yet...

Quoted 3 lines

Do we agree that touching vsock_connect_timeout() should not happen in this patch? Is there anything pending on this one from your perspective Michal?

I think we're good. Patch fixes what started the discussion.

And if I get this right, the only unintended side-effect is that shutdown/connect inconsistency, but the sibling thread concludes shutdown handling needs rework anyway.

thanks,
Michal

#12 lore raw
In reply to Bobby Eshleman
Quoted 16 lines · Bobby Eshleman
Quoted 2 lines · Michal Luczaj
Quoted 1 line · Bobby Eshleman

On Sat, Nov 21, 2026 at 07:32:15PM +0100, Michal Luczaj wrote:

[...]

Quoted 9 lines
Quoted 4 lines

So the attempt never times out, and a late OP_RESPONSE connects a socket the user already shut down, overwriting SS_DISCONNECTING with SS_CONNECTED. I think that's a separate bug for a separate patch, though.

Great, I'm all in favour of consolidation. So in the scenario above, invoking vsock_connect_close() on vsock_connect_timeout() (with sk_shutdown check dropped) would result in CLOSE/DISCONNECTING, and no more late virtio_transport_recv_connecting(), right?

Quoted 5 lines

Right, that late response will fall through and get an RST back. I'm not 100% sure yet about how to rework the sk_shutdown check yet though. I mention TCP's approach to shutdowns in my reply to Paolo and I'm thinking thats probably the right way to go about it, but not 100% sure yet...

I just wanted to admit that simply dropping the sk_shutdown check was a bad
idea: vsock_connect_timeout() may outlive vsock_release(), and that check guards against bad things happening.

#13 lore raw
In reply to Bobby Eshleman
Quoted 41 lines · Bobby Eshleman

vsock_connect() sleeps with the socket unlocked. Meanwhile the transport can complete the handshake, setting sock->state to SS_CONNECTED, and then reset the connection, e.g. in vhost_vsock_reset_orphans(), virtio_vsock_reset_sock() or vmci_transport_handle_detach(). When connect() gets the lock back, it finds sk_err set and moves the socket back to SS_UNCONNECTED. Userspace can then connect() the socket again, and a connect() to a CID on another transport makes vsock_assign_transport() release the transport the socket was connected on.

Only move the socket back to SS_UNCONNECTED if it is still SS_CONNECTING. A socket that got connected stays SS_CONNECTED, and another connect() fails with -EISCONN.

Likewise, only move sk_state to TCP_CLOSE if it is still TCP_SYN_SENT. Otherwise a second thread blocked in connect() on the same socket can time out after the first one failed and called listen(), and overwrite TCP_LISTEN.

Fixes d021c344051a ("VSOCK: Introduce VM Sockets")

Link:
https://lore.kernel.org/netdev/[email protected]/

---
Changes in v2:
- Only reset sk_state if it is still TCP_SYN_SENT, so a concurrent
connect() caller that times out late doesn't overwrite TCP_LISTEN
(Sashiko).
- Drop Michal's Reviewed-by since the code changed.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
 net/vmw_vsock/af_vsock.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
net/vmw_vsock/af_vsock.c +0 -0
index 1d7d53542724..ce958b48295b 100644

net/vmw_vsock/af_vsock.c static void vsock_connect_timeout(struct work_struct *work) · line 1709

Quoted 6 lines
net/vmw_vsock/af_vsock.c +3 -0
@@ -1704,6 +1704,19 @@ static void vsock_connect_timeout(struct work_struct *work)
 	sock_put(sk);
 }
 
+/* Avoid breaking the socket when another thread has changed its state while
+ * we were asleep.
+ */

Should we make this comment a bit more clear to explain why we are doing this?

Something like this (IIUC, please check and correct it)

/* Undo only the state this connect() attempt set. While we slept, the
* transport may have connected and then reset the socket (it is still in
* vsock_connected_table, so it must not go back to SS_UNCONNECTED), or
* another thread may have turned it into a listener.
*/

The rest LGTM!

Thanks,
Stefano

Quoted 45 lines
net/vmw_vsock/af_vsock.c +13 -7
+static void vsock_connect_close(struct socket *sock)
+{
+	struct sock *sk = sock->sk;
+
+	if (sk->sk_state == TCP_SYN_SENT)
+		sk->sk_state = TCP_CLOSE;
+	if (sock->state == SS_CONNECTING)
+		sock->state = SS_UNCONNECTED;
+}
+
 static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 			 int addr_len, int flags)
 {
@@ -1862,8 +1875,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 			 * sk_state == TCP_SYN_SENT, which hereby we break.
 			 * In such case VIRTIO_VSOCK_OP_RST will follow.
 			 */
-			sk->sk_state = TCP_CLOSE;
-			sock->state = SS_UNCONNECTED;
+			vsock_connect_close(sock);
 
 			/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
 			 * transport->connect().
@@ -1877,10 +1889,8 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
 	}
 
 	err = sock_error(sk);
-	if (err) {
-		sk->sk_state = TCP_CLOSE;
-		sock->state = SS_UNCONNECTED;
-	}
+	if (err)
+		vsock_connect_close(sock);
 
 out_wait:
 	finish_wait(sk_sleep(sk), &wait);
 
---

base-commit: 533ec433efdc11196f438da90d683053a57257ff
change-id: 20261116-vsock-connect-close-1beb7cb51e7a

Best regards,

Signature · 1 line
Bobby Eshleman <[email protected]>