This is an automated email from the ASF dual-hosted git repository.

xiaoxiang781216 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit a375789b2159bbeea013747dae10d96c57696c51
Author: Marco Casaroli <[email protected]>
AuthorDate: Wed Nov 18 02:01:42 2026 +0100

    net/tcp: Look at the state of a closed connection under its locks.
    
    tcp_close_eventhandler() queues tcp_close_work() on LPWORK and returns
    its flags.  For a reset (TCP_ABORT: unread data at the close, or a
    close with SO_LINGER 0) tcp_appsend() sets TCP_CLOSED only after the
    handler returned, and the poll holds the device and connection locks
    until then.  tcp_close_work() read the state without these locks: on
    SMP it could run on another CPU at once, see the old state, clear
    TCP_CLOSE_ARRANGED and free nothing.  No one freed the connection
    later: it stayed in the active list as TCP_CLOSED with no reference.
    With dynamic connections (CONFIG_NET_TCP_ALLOC_CONNS > 0) tcp_alloc()
    never takes it back, and the heap grows with each such close.
    
    Now tcp_close_work() takes the device and connection locks before it
    looks at the state.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Marco Casaroli <[email protected]>
---
 net/tcp/tcp_close.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/net/tcp/tcp_close.c b/net/tcp/tcp_close.c
index c74911a5f67..c435ee84fda 100644
--- a/net/tcp/tcp_close.c
+++ b/net/tcp/tcp_close.c
@@ -54,16 +54,26 @@ static void tcp_close_work(FAR void *param)
 {
   FAR struct tcp_conn_s *conn = (FAR struct tcp_conn_s *)param;
 
+  /* The close event handler queues this work before tcp_appsend() acts on
+   * its result: a TCP_ABORT sets TCP_CLOSED only after the handler
+   * returns.  Look at the state under the same locks, or the work, run
+   * on another CPU at once, would see the old state, free nothing, and
+   * no one would free the connection later.
+   */
+
+  conn_dev_lock(&conn->sconn, conn->dev);
   conn->flags &= ~TCP_CLOSE_ARRANGED;
   if (conn->crefs == 0 && conn->tcpstateflags == TCP_CLOSED)
     {
       /* Stop the network monitor for all sockets */
 
-      conn_dev_lock(&conn->sconn, conn->dev);
       tcp_stop_monitor(conn, TCP_TXCLOSE);
       conn_dev_unlock(&conn->sconn, conn->dev);
       tcp_free(conn);
+      return;
     }
+
+  conn_dev_unlock(&conn->sconn, conn->dev);
 }
 
 /****************************************************************************

Reply via email to