AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/08 03:38 flow patch-triage
6m Args:
null

Results:
{
  "EnableConfigs": [
    "RDS",
    "RDS_TCP",
    "RDS_RDMA",
    "INFINIBAND",
    "INFINIBAND_ADDR_TRANS"
  ],
  "FocusSymbols": [
    "rds_conn_destroy",
    "rds_conn_put",
    "rds_conn_get",
    "rds_conn_create",
    "rds_conn_create_outgoing",
    "rds_sendmsg",
    "rds_release",
    "rds_ioctl",
    "rds_inc_put",
    "rds_recv_incoming",
    "rds_message_put",
    "rds_tcp_accept_one"
  ],
  "KMSANReasoning": "The patch addresses lifetime management, reference counting, and teardown synchronization for RDS connections (`struct rds_connection`) across the core RDS subsystem and its transport implementations (IB, TCP, and loopback). Specifically, it introduces refcounting via `kref` on `rds_connection`, handles deferred destruction once all holders (including sockets, queued messages, and incoming datagrams) release their references, synchronizes transport unload waiting for all connection instances to be freed, and uses `c_destroy_in_prog` to guard against queuing work on quiesced workqueues.\n\nFrom a memory sanitization perspective:\n1. **Uninitialized Memory \u0026 Info-leaks (KMSAN):**\n   - All newly added and modified struct fields (`c_refcount`, `c_destroy_in_prog`, `t_conn_count`, `i_ib_node_detached`, `shutting_down`, `t_tcp_node_detached`) reside in objects that are allocated via `kzalloc`, `kmem_cache_zalloc`, or `sk_alloc` (all zero-initialized), or in static BSS data (`struct rds_transport`).\n   - The user-copy site touched by the patch is `put_user(tos, ...)` in `rds_ioctl(SIOCRDSGETTOS)`, where `tos` is explicitly initialized (`tos = 0`) and read from zero-initialized socket state (`rs-\u003ers_tos`). No struct padding or kernel data leaks to userspace are introduced.\n   - The patch does not modify packet parsing, bounds checking, buffer length computations, or payload copying in any way that could expose uninitialized memory.\n\n2. **Memory Safety \u0026 Concurrency (KASAN / LOCKDEP):**\n   - The risks associated with these changes are use-after-free (e.g. incorrect refcounting or premature connection cleanup), double free, concurrency races, and locking deadlocks (e.g. `rs_lock`, `rds_conn_lock`, `cp_lock`).\n   - These classes of defects are already detected by KASAN, LOCKDEP, and standard debugging checks in the default KASAN fuzzing build.\n\nBecause there are no uninitialized memory reads or info-leak risks that would uniquely require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch overhauls connection lifecycle management and reference counting across the RDS (Reliable Datagram Sockets) subsystem and its transports (loopback, TCP, IB). It replaces immediate connection freeing with deferred kref-based destruction, updates lock handling and caching in rds_sendmsg, rds_release, and rds_ioctl, alters workqueue quiescing and message/incoming datagram reference ownership, and adjusts transport teardown paths. These changes affect fully reachable socket and networking code with concurrency, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/10/08 03:38 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 56430c88cd4670f2cd2c6b6dcee84004f34dda87\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Thu Oct 8 03:38:14 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/net/rds/af_rds.c b/net/rds/af_rds.c\nindex d5defe9172e36..99c44d88d2e7e 100644\n--- a/net/rds/af_rds.c\n+++ b/net/rds/af_rds.c\n@@ -80,6 +80,14 @@ static int rds_release(struct socket *sock)\n \trds_notify_queue_get(rs, NULL);\n \trds_notify_msg_zcopy_purge(\u0026rs-\u003ers_zcookie_queue);\n \n+\t/* drop the cached connection reference; no sendmsg can race\n+\t * with us here, the socket is going away\n+\t */\n+\tif (rs-\u003ers_conn) {\n+\t\trds_conn_put(rs-\u003ers_conn);\n+\t\trs-\u003ers_conn = NULL;\n+\t}\n+\n \tspin_lock_bh(\u0026rds_sock_lock);\n \tlist_del_init(\u0026rs-\u003ers_item);\n \tspin_unlock_bh(\u0026rds_sock_lock);\n@@ -255,6 +263,7 @@ static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)\n {\n \tstruct rds_sock *rs = rds_sk_to_rs(sock-\u003esk);\n \trds_tos_t utos, tos = 0;\n+\tunsigned long flags;\n \n \tswitch (cmd) {\n \tcase SIOCRDSSETTOS:\n@@ -267,18 +276,23 @@ static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)\n \t\telse\n \t\t\treturn -ENOIOCTLCMD;\n \n-\t\tspin_lock_bh(\u0026rds_sock_lock);\n+\t\t/* rs_conn is serialized by rs_lock (see rds_sendmsg());\n+\t\t * hold it across the \"no connection yet\" check and the\n+\t\t * rs_tos store so a racing sendmsg cannot cache a conn\n+\t\t * whose c_tos then disagrees with rs_tos.\n+\t\t */\n+\t\tspin_lock_irqsave(\u0026rs-\u003ers_lock, flags);\n \t\tif (rs-\u003ers_tos || rs-\u003ers_conn) {\n-\t\t\tspin_unlock_bh(\u0026rds_sock_lock);\n+\t\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n \t\t\treturn -EINVAL;\n \t\t}\n-\t\trs-\u003ers_tos = tos;\n-\t\tspin_unlock_bh(\u0026rds_sock_lock);\n+\t\tWRITE_ONCE(rs-\u003ers_tos, tos);\n+\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n \t\tbreak;\n \tcase SIOCRDSGETTOS:\n-\t\tspin_lock_bh(\u0026rds_sock_lock);\n+\t\tspin_lock_irqsave(\u0026rs-\u003ers_lock, flags);\n \t\ttos = rs-\u003ers_tos;\n-\t\tspin_unlock_bh(\u0026rds_sock_lock);\n+\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n \t\tif (put_user(tos, (rds_tos_t __user *)arg))\n \t\t\treturn -EFAULT;\n \t\tbreak;\ndiff --git a/net/rds/connection.c b/net/rds/connection.c\nindex c752a8623cfca..8c4df7d6b294d 100644\n--- a/net/rds/connection.c\n+++ b/net/rds/connection.c\n@@ -47,7 +47,8 @@\n \n /* converting this to RCU is a chore for another day.. */\n static DEFINE_SPINLOCK(rds_conn_lock);\n-static unsigned long rds_conn_count;\n+/* woken whenever a transport's t_conn_count drops to zero */\n+static DECLARE_WAIT_QUEUE_HEAD(rds_conn_freed_waitq);\n static struct hlist_head rds_conn_hash[RDS_CONNECTION_HASH_ENTRIES];\n static struct kmem_cache *rds_conn_slab;\n \n@@ -79,7 +80,10 @@ static struct hlist_head *rds_conn_bucket(const struct in6_addr *laddr,\n \t\tvar |= RDS_INFO_CONNECTION_FLAG_##suffix;\t\\\n } while (0)\n \n-/* rcu read lock must be held or the connection spinlock */\n+/* rcu read lock must be held or the connection spinlock.\n+ * On success a reference is taken on the returned connection; the\n+ * caller must drop it with rds_conn_put().\n+ */\n static struct rds_connection *rds_conn_lookup(struct net *net,\n \t\t\t\t\t      struct hlist_head *head,\n \t\t\t\t\t      const struct in6_addr *laddr,\n@@ -96,6 +100,17 @@ static struct rds_connection *rds_conn_lookup(struct net *net,\n \t\t    conn-\u003ec_tos == tos \u0026\u0026\n \t\t    net == rds_conn_net(conn) \u0026\u0026\n \t\t    conn-\u003ec_dev_if == dev_if) {\n+\t\t\t/* Only ever hand out a live reference.\n+\t\t\t * rds_conn_destroy() unhashes under\n+\t\t\t * rds_conn_lock and waits a grace period\n+\t\t\t * before dropping the initial reference, so\n+\t\t\t * an entry this traversal reaches still holds\n+\t\t\t * at least that one; the conditional get\n+\t\t\t * documents the contract rather than\n+\t\t\t * papering over a zero-refcount entry.\n+\t\t\t */\n+\t\t\tif (!kref_get_unless_zero(\u0026conn-\u003ec_refcount))\n+\t\t\t\tcontinue;\n \t\t\tret = conn;\n \t\t\tbreak;\n \t\t}\n@@ -161,6 +176,30 @@ static void __rds_conn_path_init(struct rds_connection *conn,\n \tcp-\u003ecp_flags = 0;\n }\n \n+/* c_passive is written under rds_conn_lock and read under RCU */\n+static struct rds_connection *\n+rds_conn_passive_locked(struct rds_connection *conn)\n+{\n+\treturn rcu_dereference_protected(conn-\u003ec_passive,\n+\t\t\t\t\t lockdep_is_held(\u0026rds_conn_lock));\n+}\n+\n+/* Undo trans-\u003econn_alloc(): it may have allocated transport data for\n+ * every path of a multipath connection, not just for path 0.\n+ */\n+static void rds_conn_free_transport_data(struct rds_connection *conn,\n+\t\t\t\t\t int npaths)\n+{\n+\tstruct rds_conn_path *cp;\n+\tint i;\n+\n+\tfor (i = 0; i \u003c npaths; i++) {\n+\t\tcp = \u0026conn-\u003ec_path[i];\n+\t\tif (cp-\u003ecp_transport_data)\n+\t\t\tconn-\u003ec_trans-\u003econn_free(cp-\u003ecp_transport_data);\n+\t}\n+}\n+\n /*\n  * There is only every one 'conn' for a given pair of addresses in the\n  * system at a time.  They contain messages to be retransmitted and so\n@@ -197,7 +236,20 @@ static struct rds_connection *__rds_conn_create(struct net *net,\n \t\t * We need a second connection object into which we\n \t\t * can stick the other QP. */\n \t\tparent = conn;\n-\t\tconn = parent-\u003ec_passive;\n+\t\t/* The c_passive pointer holds a reference which is only\n+\t\t * dropped one synchronize_rcu() after the pointer is\n+\t\t * cleared, so within this RCU section a fetched pointer\n+\t\t * is always safe to take a reference on.  A passive conn\n+\t\t * whose own destroy has begun is not handed out, though:\n+\t\t * it is quiesced and about to clear the parent's pointer\n+\t\t * itself, and reusing it would re-arm a connection that\n+\t\t * nothing will tear down again.\n+\t\t */\n+\t\tconn = rcu_dereference(parent-\u003ec_passive);\n+\t\tif (conn \u0026\u0026 rds_destroy_pending(conn))\n+\t\t\tconn = NULL;\n+\t\tif (conn)\n+\t\t\trds_conn_get(conn);\n \t}\n \trcu_read_unlock();\n \tif (conn)\n@@ -215,6 +267,7 @@ static struct rds_connection *__rds_conn_create(struct net *net,\n \t\tgoto out;\n \t}\n \n+\tkref_init(\u0026conn-\u003ec_refcount);\n \tINIT_HLIST_NODE(\u0026conn-\u003ec_hash_node);\n \tconn-\u003ec_laddr = *laddr;\n \tconn-\u003ec_isv6 = !ipv6_addr_v4mapped(laddr);\n@@ -284,12 +337,13 @@ static struct rds_connection *__rds_conn_create(struct net *net,\n \n \tinit_waitqueue_head(\u0026conn-\u003ec_hs_waitq);\n \tfor (i = 0; i \u003c npaths; i++) {\n+\t\tint seq = atomic_read(\u0026trans-\u003et_conn_count);\n+\n \t\t__rds_conn_path_init(conn, \u0026conn-\u003ec_path[i],\n \t\t\t\t     is_outgoing);\n \t\tconn-\u003ec_path[i].cp_index = i;\n \t\tconn-\u003ec_path[i].cp_wq =\n-\t\t\talloc_ordered_workqueue(\"krds_cp_wq#%lu/%d\", 0,\n-\t\t\t\t\t\trds_conn_count, i);\n+\t\t\talloc_ordered_workqueue(\"krds_cp_wq#%d/%d\", 0, seq, i);\n \t\tif (!conn-\u003ec_path[i].cp_wq)\n \t\t\tconn-\u003ec_path[i].cp_wq = rds_wq;\n \t}\n@@ -321,15 +375,44 @@ static struct rds_connection *__rds_conn_create(struct net *net,\n \tspin_lock_irqsave(\u0026rds_conn_lock, flags);\n \tif (parent) {\n \t\t/* Creating passive conn */\n-\t\tif (parent-\u003ec_passive) {\n-\t\t\ttrans-\u003econn_free(conn-\u003ec_path[0].cp_transport_data);\n+\t\tif (rds_destroy_pending(parent)) {\n+\t\t\t/* The parent's destroy has begun (it sets the\n+\t\t\t * flag and snatches c_passive under this\n+\t\t\t * lock); do not install a new passive conn\n+\t\t\t * that nothing would ever destroy.\n+\t\t\t */\n+\t\t\trds_conn_free_transport_data(conn, npaths);\n+\t\t\tfree_cp = conn-\u003ec_path;\n+\t\t\tkmem_cache_free(rds_conn_slab, conn);\n+\t\t\tconn = ERR_PTR(-ENETDOWN);\n+\t\t} else if (rcu_access_pointer(parent-\u003ec_passive)) {\n+\t\t\tstruct rds_connection *passive;\n+\n+\t\t\tpassive = rds_conn_passive_locked(parent);\n+\t\t\trds_conn_free_transport_data(conn, npaths);\n \t\t\tfree_cp = conn-\u003ec_path;\n \t\t\tkmem_cache_free(rds_conn_slab, conn);\n-\t\t\tconn = parent-\u003ec_passive;\n+\t\t\t/* A passive conn still installed here cannot have\n+\t\t\t * its own destroy begun: rds_conn_destroy() sets\n+\t\t\t * c_destroy_in_prog and clears the parent's pointer\n+\t\t\t * in one rds_conn_lock section, and the netns and\n+\t\t\t * unload cases were ruled out by the parent above.\n+\t\t\t */\n+\t\t\trds_conn_get(passive);\n+\t\t\tconn = passive;\n \t\t} else {\n-\t\t\tparent-\u003ec_passive = conn;\n+\t\t\t/* The initial reference belongs to whoever\n+\t\t\t * destroys the conn (the transport's conn\n+\t\t\t * lists, as for any other conn).  Take one\n+\t\t\t * for the c_passive pointer - dropped when\n+\t\t\t * the parent is destroyed - and one for our\n+\t\t\t * caller.\n+\t\t\t */\n+\t\t\trds_conn_get(conn);\t/* c_passive */\n+\t\t\trds_conn_get(conn);\t/* caller */\n+\t\t\trcu_assign_pointer(parent-\u003ec_passive, conn);\n \t\t\trds_cong_add_conn(conn);\n-\t\t\trds_conn_count++;\n+\t\t\tatomic_inc(\u0026conn-\u003ec_trans-\u003et_conn_count);\n \t\t}\n \t} else {\n \t\t/* Creating normal conn */\n@@ -338,33 +421,28 @@ static struct rds_connection *__rds_conn_create(struct net *net,\n \t\tfound = rds_conn_lookup(net, head, laddr, faddr, trans,\n \t\t\t\t\ttos, dev_if);\n \t\tif (found) {\n-\t\t\tstruct rds_conn_path *cp;\n-\t\t\tint i;\n-\n-\t\t\tfor (i = 0; i \u003c npaths; i++) {\n-\t\t\t\tcp = \u0026conn-\u003ec_path[i];\n-\t\t\t\t/* The -\u003econn_alloc invocation may have\n-\t\t\t\t * allocated resource for all paths, so all\n-\t\t\t\t * of them may have to be freed here.\n-\t\t\t\t */\n-\t\t\t\tif (cp-\u003ecp_transport_data)\n-\t\t\t\t\ttrans-\u003econn_free(cp-\u003ecp_transport_data);\n-\t\t\t}\n+\t\t\trds_conn_free_transport_data(conn, npaths);\n \t\t\tfree_cp = conn-\u003ec_path;\n \t\t\tkmem_cache_free(rds_conn_slab, conn);\n \t\t\tconn = found;\n \t\t} else {\n \t\t\tconn-\u003ec_my_gen_num = rds_gen_num;\n \t\t\tconn-\u003ec_peer_gen_num = 0;\n+\t\t\t/* the initial reference belongs to whoever\n+\t\t\t * destroys the conn; take one for our caller\n+\t\t\t */\n+\t\t\trds_conn_get(conn);\n \t\t\thlist_add_head_rcu(\u0026conn-\u003ec_hash_node, head);\n \t\t\trds_cong_add_conn(conn);\n-\t\t\trds_conn_count++;\n+\t\t\tatomic_inc(\u0026conn-\u003ec_trans-\u003et_conn_count);\n \t\t}\n \t}\n \tspin_unlock_irqrestore(\u0026rds_conn_lock, flags);\n \trcu_read_unlock();\n \n out:\n+\tif (parent)\n+\t\trds_conn_put(parent);\n \tif (free_cp) {\n \t\tfor (i = 0; i \u003c npaths; i++)\n \t\t\tif (free_cp[i].cp_wq != rds_wq)\n@@ -472,9 +550,10 @@ void rds_conn_shutdown(struct rds_conn_path *cp)\n \t\t\t * Quiesce the reconnect timer before bailing\n \t\t\t * out, though.  When a pending destroy did\n \t\t\t * suppress the queue, no later pass runs, and\n-\t\t\t * rds_conn_path_destroy() is about to flush\n-\t\t\t * cp_down_w and free the path: it must not\n-\t\t\t * find cp_conn_w still armed.  A successor\n+\t\t\t * rds_conn_path_quiesce() is about to flush\n+\t\t\t * cp_down_w, ahead of the path's deferred\n+\t\t\t * free: it must not find cp_conn_w still\n+\t\t\t * armed.  A successor\n \t\t\t * pass, when there is one, re-arms the\n \t\t\t * reconnect from its own tail.\n \t\t\t */\n@@ -521,12 +600,16 @@ void rds_conn_shutdown(struct rds_conn_path *cp)\n \t\tconn-\u003ec_trans-\u003econn_slots_available(conn, false);\n }\n \n-/* destroy a single rds_conn_path. rds_conn_destroy() iterates over\n- * all paths using rds_conn_path_destroy()\n+/* quiesce a single rds_conn_path: shut it down and tear down any\n+ * queued messages.  rds_conn_destroy() iterates over all paths using\n+ * rds_conn_path_quiesce(); the transport state and the workqueue are\n+ * freed later, from rds_conn_path_free().\n  */\n-static void rds_conn_path_destroy(struct rds_conn_path *cp)\n+static void rds_conn_path_quiesce(struct rds_conn_path *cp)\n {\n \tstruct rds_message *rm, *rtmp;\n+\tunsigned long flags;\n+\tLIST_HEAD(purge);\n \n \tif (!cp-\u003ecp_transport_data)\n \t\treturn;\n@@ -538,12 +621,29 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)\n \trds_conn_path_drop(cp, true);\n \tflush_work(\u0026cp-\u003ecp_down_w);\n \n-\t/* tear down queued messages */\n-\tlist_for_each_entry_safe(rm, rtmp,\n-\t\t\t\t \u0026cp-\u003ecp_send_queue,\n-\t\t\t\t m_conn_item) {\n+\t/* Tear down queued messages.  Every path that adds to\n+\t * cp_send_queue does so under cp_lock; take it here too.  No\n+\t * sender can still be running at any destroy trigger, so this is\n+\t * lock discipline rather than a race fix: nothing here tells a\n+\t * sender that the queue is closed.\n+\t */\n+\tspin_lock_irqsave(\u0026cp-\u003ecp_lock, flags);\n+\tlist_splice_init(\u0026cp-\u003ecp_send_queue, \u0026purge);\n+\t/* Give up the queue's claim on each message while still under\n+\t * the lock, so that rds_send_drop_to(), which decides ownership\n+\t * of the connection-queue reference by this bit, neither drops\n+\t * it a second time nor unlinks the message from our list.\n+\t */\n+\tlist_for_each_entry(rm, \u0026purge, m_conn_item)\n+\t\tclear_bit(RDS_MSG_ON_CONN, \u0026rm-\u003em_flags);\n+\tspin_unlock_irqrestore(\u0026cp-\u003ecp_lock, flags);\n+\tlist_for_each_entry_safe(rm, rtmp, \u0026purge, m_conn_item) {\n+\t\t/* No socket can still have messages queued on a connection\n+\t\t * at any destroy trigger; say so if one does, since the\n+\t\t * socket side then retires the message on its own.\n+\t\t */\n+\t\tWARN_ON_ONCE(!list_empty(\u0026rm-\u003em_sock_item));\n \t\tlist_del_init(\u0026rm-\u003em_conn_item);\n-\t\tBUG_ON(!list_empty(\u0026rm-\u003em_sock_item));\n \t\trds_message_put(rm);\n \t}\n \tif (cp-\u003ecp_xmit_rm)\n@@ -553,6 +653,16 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)\n \tWARN_ON(delayed_work_pending(\u0026cp-\u003ecp_recv_w));\n \tWARN_ON(delayed_work_pending(\u0026cp-\u003ecp_conn_w));\n \tWARN_ON(work_pending(\u0026cp-\u003ecp_down_w));\n+}\n+\n+/* free a quiesced rds_conn_path's transport state and workqueue; runs\n+ * from rds_conn_destroy_fini() once the last connection reference is\n+ * dropped.\n+ */\n+static void rds_conn_path_free(struct rds_conn_path *cp)\n+{\n+\tif (!cp-\u003ecp_transport_data)\n+\t\treturn;\n \n \tif (cp-\u003ecp_wq != rds_wq) {\n \t\tdestroy_workqueue(cp-\u003ecp_wq);\n@@ -562,17 +672,102 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)\n \tcp-\u003ecp_conn-\u003ec_trans-\u003econn_free(cp-\u003ecp_transport_data);\n }\n \n+/* Free a connection.  This runs from rds_conn_put() when the last\n+ * reference is dropped, after rds_conn_destroy() has quiesced the\n+ * connection and dropped the initial reference.\n+ */\n+static void rds_conn_destroy_fini(struct kref *kref)\n+{\n+\tstruct rds_connection *conn = container_of(kref, struct rds_connection,\n+\t\t\t\t\t\t   c_refcount);\n+\tint npaths = (conn-\u003ec_trans-\u003et_mp_capable ? RDS_MPATH_WORKERS : 1);\n+\tstruct rds_transport *trans = conn-\u003ec_trans;\n+\tint i;\n+\n+\tfor (i = 0; i \u003c npaths; i++)\n+\t\trds_conn_path_free(\u0026conn-\u003ec_path[i]);\n+\n+\tkfree(conn-\u003ec_path);\n+\tkmem_cache_free(rds_conn_slab, conn);\n+\n+\t/* only after everything the transport module owns has been\n+\t * freed above may its unload proceed\n+\t */\n+\tif (!atomic_dec_return(\u0026trans-\u003et_conn_count))\n+\t\twake_up_all(\u0026rds_conn_freed_waitq);\n+}\n+\n+/* Wait for all of @trans's connections to be freed; the free runs\n+ * asynchronously once rds_conn_destroy() has quiesced a connection.\n+ * Called on transport module unload after an initial sweep has\n+ * destroyed the transport's connections; @resweep, when given, is\n+ * called on every poll to destroy connections that were still\n+ * detaching from a device when the sweep ran (IB).  A connection\n+ * reference can be held for an application-controlled time - once\n+ * incs hold one, an unread datagram pins the inc that carries it, and\n+ * thus the connection - so the wait is unbounded: the frees that run\n+ * after unload call into this module's text (conn_free, inc_free) and\n+ * free into its slabs, so proceeding while any remain would be a\n+ * use-after-free, not a leak.  Warn periodically so a stuck count is\n+ * diagnosable, but never stop waiting.  This matches the historical\n+ * RDS contract that teardown does not discard queued data.\n+ */\n+void rds_conn_wait_conns_freed(struct rds_transport *trans,\n+\t\t\t       void (*resweep)(void))\n+{\n+\tunsigned long warn_interval =\n+\t\t\tmsecs_to_jiffies(RDS_CONN_FREE_WARN_INTERVAL_MS);\n+\tunsigned long warn_at = jiffies + warn_interval;\n+\n+\twhile (!wait_event_timeout(rds_conn_freed_waitq,\n+\t\t\t\t   !atomic_read(\u0026trans-\u003et_conn_count),\n+\t\t\t\t   msecs_to_jiffies(RDS_CONN_FREE_POLL_MS))) {\n+\t\t/* A transport whose teardown is asynchronous (IB moves a\n+\t\t * connection off its device from the shutdown work) gives\n+\t\t * us a resweep to destroy what has arrived since.\n+\t\t */\n+\t\tif (resweep)\n+\t\t\tresweep();\n+\t\tif (time_after_eq(jiffies, warn_at)) {\n+\t\t\tpr_warn(\"RDS/%s: still waiting for %d connection(s) to be freed before unload\\n\",\n+\t\t\t\ttrans-\u003et_name,\n+\t\t\t\tatomic_read(\u0026trans-\u003et_conn_count));\n+\t\t\twarn_at = jiffies + warn_interval;\n+\t\t}\n+\t}\n+}\n+EXPORT_SYMBOL_GPL(rds_conn_wait_conns_freed);\n+\n+void rds_conn_get(struct rds_connection *conn)\n+{\n+\tkref_get(\u0026conn-\u003ec_refcount);\n+}\n+EXPORT_SYMBOL_GPL(rds_conn_get);\n+\n+void rds_conn_put(struct rds_connection *conn)\n+{\n+\tkref_put(\u0026conn-\u003ec_refcount, rds_conn_destroy_fini);\n+}\n+EXPORT_SYMBOL_GPL(rds_conn_put);\n+\n /*\n  * Stop and free a connection.\n  *\n- * This can only be used in very limited circumstances.  It assumes that once\n- * the conn has been shutdown that no one else is referencing the connection.\n- * We can only ensure this in the rmmod path in the current code.\n+ * Quiesces the connection synchronously (workers cancelled, transport\n+ * connections shut down, queued messages dropped) and drops the\n+ * initial reference.  Only the first call for a connection does any\n+ * of that: a later one finds c_destroy_in_prog already set and\n+ * returns at once, without waiting for the first.  The memory -\n+ * including the transport's per-connection state and the path\n+ * workqueues - is freed once the last rds_conn_put() runs, which may\n+ * be after this returns.\n  */\n void rds_conn_destroy(struct rds_connection *conn)\n {\n-\tunsigned long flags;\n \tint i;\n+\tstruct rds_connection *passive, *parent;\n+\tstruct hlist_head *head;\n+\tbool was_passive = false;\n \tstruct rds_conn_path *cp;\n \tint npaths = (conn-\u003ec_trans-\u003et_mp_capable ? RDS_MPATH_WORKERS : 1);\n \n@@ -580,16 +775,68 @@ void rds_conn_destroy(struct rds_connection *conn)\n \t\t \"%pI4\\n\", conn, \u0026conn-\u003ec_laddr,\n \t\t \u0026conn-\u003ec_faddr);\n \n-\t/* Ensure conn will not be scheduled for reconnect */\n+\t/* Make rds_destroy_pending() true for this conn.  Together with\n+\t * the synchronize_rcu() below this stops the work-requeueing\n+\t * sites (which test rds_destroy_pending() under rcu_read_lock(),\n+\t * bar the exemptions noted at c_destroy_in_prog) from queueing\n+\t * new work on the path workqueues once we start cancelling and\n+\t * destroying them.\n+\t *\n+\t * Only the first caller proceeds.  No caller in this tree hands\n+\t * a connection to rds_conn_destroy() twice - every teardown\n+\t * sweep unlinks or claims its node before the destroy - so this\n+\t * documents the contract rather than closing a path: a second\n+\t * caller returns at once, without quiescing or waiting.  The\n+\t * unhash also happens under rds_conn_lock, so a looked-up conn\n+\t * can never be quiesced twice.\n+\t */\n \tspin_lock_irq(\u0026rds_conn_lock);\n+\tif (conn-\u003ec_destroy_in_prog) {\n+\t\tspin_unlock_irq(\u0026rds_conn_lock);\n+\t\treturn;\n+\t}\n+\tWRITE_ONCE(conn-\u003ec_destroy_in_prog, true);\n+\n+\t/* Ensure conn will not be scheduled for reconnect */\n \thlist_del_init_rcu(\u0026conn-\u003ec_hash_node);\n+\n+\t/* Snatch c_passive while holding the lock:\n+\t * __rds_conn_create() dereferences it under rcu_read_lock()\n+\t * (and refuses to install a new one once c_destroy_in_prog is\n+\t * set, which it checks under this lock).  After the\n+\t * synchronize_rcu() below no one can pick the pointer up any\n+\t * more and its reference can be dropped.\n+\t */\n+\tpassive = rds_conn_passive_locked(conn);\n+\tRCU_INIT_POINTER(conn-\u003ec_passive, NULL);\n+\n+\t/* If we are a parent's passive twin, invalidate its pointer to\n+\t * us as well, so that __rds_conn_create() cannot hand out a\n+\t * connection whose teardown has begun.  The parent is the\n+\t * hashed connection for our key (a passive conn is never\n+\t * hashed, and we unhashed ourselves above); it holds its\n+\t * initial reference for as long as it is hashed, so the lookup\n+\t * reference dropped below cannot be its last.\n+\t */\n+\thead = rds_conn_bucket(\u0026conn-\u003ec_laddr, \u0026conn-\u003ec_faddr);\n+\trcu_read_lock();\n+\tparent = rds_conn_lookup(rds_conn_net(conn), head, \u0026conn-\u003ec_laddr,\n+\t\t\t\t \u0026conn-\u003ec_faddr, conn-\u003ec_trans, conn-\u003ec_tos,\n+\t\t\t\t conn-\u003ec_dev_if);\n+\trcu_read_unlock();\n+\tif (parent \u0026\u0026 rds_conn_passive_locked(parent) == conn) {\n+\t\tRCU_INIT_POINTER(parent-\u003ec_passive, NULL);\n+\t\twas_passive = true;\n+\t}\n \tspin_unlock_irq(\u0026rds_conn_lock);\n+\tif (parent)\n+\t\trds_conn_put(parent);\n \tsynchronize_rcu();\n \n \t/* shut the connection down */\n \tfor (i = 0; i \u003c npaths; i++) {\n \t\tcp = \u0026conn-\u003ec_path[i];\n-\t\trds_conn_path_destroy(cp);\n+\t\trds_conn_path_quiesce(cp);\n \t\tBUG_ON(!list_empty(\u0026cp-\u003ecp_retrans));\n \t}\n \n@@ -600,12 +847,21 @@ void rds_conn_destroy(struct rds_connection *conn)\n \t */\n \trds_cong_remove_conn(conn);\n \n-\tkfree(conn-\u003ec_path);\n-\tkmem_cache_free(rds_conn_slab, conn);\n+\t/* Drop the reference our c_passive pointer held, if any, and\n+\t * the one a parent's c_passive pointer held on us.  Either may\n+\t * be the last one - the twin's own destroy may already have run\n+\t * - so these must stay here, in sleepable context with no lock\n+\t * held, where the free that follows the last put is allowed.\n+\t */\n+\tif (passive)\n+\t\trds_conn_put(passive);\n+\tif (was_passive)\n+\t\trds_conn_put(conn);\n \n-\tspin_lock_irqsave(\u0026rds_conn_lock, flags);\n-\trds_conn_count--;\n-\tspin_unlock_irqrestore(\u0026rds_conn_lock, flags);\n+\t/* drop the initial reference; the connection is freed from\n+\t * rds_conn_destroy_fini() once every holder has dropped theirs\n+\t */\n+\trds_conn_put(conn);\n }\n EXPORT_SYMBOL_GPL(rds_conn_destroy);\n \ndiff --git a/net/rds/ib.c b/net/rds/ib.c\nindex 4ea9838d090c3..7b1f611c0a3e5 100644\n--- a/net/rds/ib.c\n+++ b/net/rds/ib.c\n@@ -86,6 +86,11 @@ static void rds_ib_dev_shutdown(struct rds_ib_device *rds_ibdev)\n \tunsigned long flags;\n \n \tspin_lock_irqsave(\u0026rds_ibdev-\u003espinlock, flags);\n+\t/* Close the device to new connections under the same lock that\n+\t * rds_ib_add_conn() attaches them under, so that every\n+\t * connection is either dropped by the walk below or refused.\n+\t */\n+\trds_ibdev-\u003eshutting_down = true;\n \tlist_for_each_entry(ic, \u0026rds_ibdev-\u003econn_list, ib_node)\n \t\trds_conn_path_drop(\u0026ic-\u003econn-\u003ec_path[0], true);\n \tspin_unlock_irqrestore(\u0026rds_ibdev-\u003espinlock, flags);\n@@ -523,10 +528,7 @@ static void rds_ib_set_unloading(void)\n \n static bool rds_ib_is_unloading(struct rds_connection *conn)\n {\n-\tstruct rds_conn_path *cp = \u0026conn-\u003ec_path[0];\n-\n-\treturn (test_bit(RDS_DESTROY_PENDING, \u0026cp-\u003ecp_flags) ||\n-\t\tatomic_read(\u0026rds_ib_unloading) != 0);\n+\treturn atomic_read(\u0026rds_ib_unloading) != 0;\n }\n \n void rds_ib_exit(void)\n@@ -538,7 +540,24 @@ void rds_ib_exit(void)\n \trds_info_deregister_func(RDS6_INFO_IB_CONNECTIONS, rds6_ib_ic_info);\n #endif\n \trds_ib_unregister_client();\n+\n+\t/* rds_ib_dev_shutdown() only dropped the connections still\n+\t * attached to a device; each moves itself to ib_nodev_conns\n+\t * from its shutdown work.  Destroy what is there now and keep\n+\t * sweeping the list while the wait sees connections outstanding,\n+\t * so a late arrival is destroyed rather than waited on forever.\n+\t */\n \trds_ib_destroy_nodev_conns();\n+\trds_conn_wait_conns_freed(\u0026rds_ib_transport,\n+\t\t\t\t  rds_ib_destroy_nodev_conns);\n+\n+\t/* Tearing down the last connection may have dropped the final\n+\t * reference on a device, deferring rds_ib_dev_free() to rds_wq.\n+\t * Drain it before the module goes away; it queues nothing\n+\t * further on rds_wq.\n+\t */\n+\tflush_workqueue(rds_wq);\n+\n \trds_ib_sysctl_exit();\n \trds_ib_recv_exit();\n \trds_trans_unregister(\u0026rds_ib_transport);\ndiff --git a/net/rds/ib.h b/net/rds/ib.h\nindex 1901226368c98..07474fe7327b0 100644\n--- a/net/rds/ib.h\n+++ b/net/rds/ib.h\n@@ -143,6 +143,10 @@ struct rds_ib_device;\n struct rds_ib_connection {\n \n \tstruct list_head\tib_node;\n+\t/* set under ib_nodev_conns_lock once a transport teardown has\n+\t * claimed ib_node; from then on only the teardown touches it\n+\t */\n+\tbool\t\t\ti_ib_node_detached;\n \tstruct rds_ib_device\t*rds_ibdev;\n \tstruct rds_connection\t*conn;\n \n@@ -258,6 +262,10 @@ struct rds_ib_device {\n \tunsigned int\t\tmax_initiator_depth;\n \tunsigned int\t\tmax_responder_resources;\n \tspinlock_t\t\tspinlock;\t/* protect the above */\n+\t/* set under spinlock by rds_ib_dev_shutdown(): the device is\n+\t * going away and no connection may attach to it any more\n+\t */\n+\tbool\t\t\tshutting_down;\n \trefcount_t\t\trefcount;\n \tstruct work_struct\tfree_work;\n \tint\t\t\t*vector_load;\n@@ -384,7 +392,8 @@ void rds_ib_cm_connect_complete(struct rds_connection *conn,\n struct rds_ib_device *rds_ib_get_device(__be32 ipaddr);\n int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev,\n \t\t\t struct in6_addr *ipaddr);\n-void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn);\n+int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,\n+\t\t    struct rds_connection *conn);\n void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn);\n void rds_ib_destroy_nodev_conns(void);\n void rds_ib_mr_cqe_handler(struct rds_ib_connection *ic, struct ib_wc *wc);\ndiff --git a/net/rds/ib_cm.c b/net/rds/ib_cm.c\nindex 3ed03ad328129..38d95b016773c 100644\n--- a/net/rds/ib_cm.c\n+++ b/net/rds/ib_cm.c\n@@ -524,7 +524,9 @@ static int rds_ib_setup_qp(struct rds_connection *conn)\n \tfr_queue_space = RDS_IB_DEFAULT_FR_WR;\n \n \t/* add the conn now so that connection establishment has the dev */\n-\trds_ib_add_conn(rds_ibdev, conn);\n+\tret = rds_ib_add_conn(rds_ibdev, conn);\n+\tif (ret)\n+\t\tgoto out;\n \n \tmax_wrs = rds_ibdev-\u003emax_wrs \u003c rds_ib_sysctl_max_send_wr + 1 ?\n \t\trds_ibdev-\u003emax_wrs - 1 : rds_ib_sysctl_max_send_wr;\n@@ -874,6 +876,15 @@ int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,\n \t * see the comment above rds_queue_reconnect()\n \t */\n \tmutex_lock(\u0026conn-\u003ec_cm_lock);\n+\t/* Defensive: a destroy that has quiesced this conn also unhashed\n+\t * it, so rds_conn_create() cannot have returned it, and the\n+\t * listeners are stopped before any IB connection is destroyed at\n+\t * unload.  Should a request reach a conn in RDS_CONN_DOWN with\n+\t * its destroy begun all the same, do not install a new cm_id and\n+\t * QP that nothing would tear down.\n+\t */\n+\tif (rds_destroy_pending(conn))\n+\t\tgoto out;\n \tif (!rds_conn_transition(conn, RDS_CONN_DOWN, RDS_CONN_CONNECTING)) {\n \t\tif (rds_conn_state(conn) == RDS_CONN_UP) {\n \t\t\trdsdebug(\"incoming connect while connecting\\n\");\n@@ -924,8 +935,15 @@ int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,\n \t\trds_ib_conn_error(conn, \"rdma_accept failed\\n\");\n \n out:\n-\tif (conn)\n+\tif (conn) {\n \t\tmutex_unlock(\u0026conn-\u003ec_cm_lock);\n+\t\t/* Drop the reference rds_conn_create() handed us.  The\n+\t\t * conn stays reachable through cm_id-\u003econtext without a\n+\t\t * reference of its own; rds_rdma_cm_event_handler_cmn()\n+\t\t * takes one for the duration of each event it handles.\n+\t\t */\n+\t\trds_conn_put(conn);\n+\t}\n \tif (err)\n \t\trdma_reject(cm_id, \u0026err, sizeof(int),\n \t\t\t    IB_CM_REJ_CONSUMER_DEFINED);\n@@ -941,6 +959,18 @@ int rds_ib_cm_initiate_connect(struct rdma_cm_id *cm_id, bool isv6)\n \tunion rds_ib_conn_priv dp;\n \tint ret;\n \n+\t/* Defensive: a destroy that began while the address and route\n+\t * were being resolved either waits on c_cm_lock behind this\n+\t * handler, and its shutdown pass then tears down whatever is\n+\t * set up here, or has already destroyed the id this event\n+\t * arrived on, in which case the event never gets here.  Decline\n+\t * to set up a QP all the same, and return success: the id is\n+\t * still ic-\u003ei_cm_id, for that shutdown to destroy, and a\n+\t * non-zero return would have the rdma_cm destroy it instead.\n+\t */\n+\tif (rds_destroy_pending(conn))\n+\t\treturn 0;\n+\n \t/* If the peer doesn't do protocol negotiation, we must\n \t * default to RDSv3.0 */\n \trds_ib_set_protocol(conn, RDS_PROTOCOL_4_1);\n@@ -1284,19 +1314,29 @@ void rds_ib_conn_free(void *arg)\n {\n \tstruct rds_ib_connection *ic = arg;\n \tspinlock_t\t*lock_ptr;\n+\tunsigned long flags;\n \n \trdsdebug(\"ic %p\\n\", ic);\n \n \t/*\n-\t * Conn is either on a dev's list or on the nodev list.\n-\t * A race with shutdown() or connect() would cause problems\n-\t * (since rds_ibdev would change) but that should never happen.\n+\t * Conn is on a dev's list or on the nodev list - or, once a\n+\t * transport teardown has claimed it (i_ib_node_detached), on\n+\t * neither, in which case the lock chosen here only guards the\n+\t * test below.  A connect or shutdown still running for a\n+\t * claimed conn leaves the node alone, see rds_ib_add_conn() and\n+\t * rds_ib_remove_conn().\n+\t *\n+\t * Callers may hold rds_conn_lock with interrupts disabled\n+\t * (__rds_conn_create() undoing a lost creation race), so do not\n+\t * re-enable interrupts unconditionally here.\n \t */\n \tlock_ptr = ic-\u003erds_ibdev ? \u0026ic-\u003erds_ibdev-\u003espinlock : \u0026ib_nodev_conns_lock;\n \n-\tspin_lock_irq(lock_ptr);\n-\tlist_del(\u0026ic-\u003eib_node);\n-\tspin_unlock_irq(lock_ptr);\n+\tspin_lock_irqsave(lock_ptr, flags);\n+\t/* a transport teardown that gathered us first owns the node */\n+\tif (!ic-\u003ei_ib_node_detached)\n+\t\tlist_del(\u0026ic-\u003eib_node);\n+\tspin_unlock_irqrestore(lock_ptr, flags);\n \n \trds_ib_recv_free_caches(ic);\n \ndiff --git a/net/rds/ib_rdma.c b/net/rds/ib_rdma.c\nindex db7e92e7bd29f..f0e7d116b0844 100644\n--- a/net/rds/ib_rdma.c\n+++ b/net/rds/ib_rdma.c\n@@ -119,38 +119,62 @@ int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev,\n \treturn 0;\n }\n \n-void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)\n+int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,\n+\t\t    struct rds_connection *conn)\n {\n \tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\n+\tint ret = 0;\n \n-\t/* conn was previously on the nodev_conns_list */\n+\t/* conn was previously on the nodev_conns_list, unless a teardown\n+\t * sweep has claimed it ahead of destroying it: then it is on its\n+\t * way out, and its node belongs to the sweep.\n+\t */\n \tspin_lock_irq(\u0026ib_nodev_conns_lock);\n-\tBUG_ON(list_empty(\u0026ib_nodev_conns));\n-\tBUG_ON(list_empty(\u0026ic-\u003eib_node));\n-\tlist_del(\u0026ic-\u003eib_node);\n-\n \tspin_lock(\u0026rds_ibdev-\u003espinlock);\n-\tlist_add_tail(\u0026ic-\u003eib_node, \u0026rds_ibdev-\u003econn_list);\n+\t/* rds_ib_dev_shutdown() has walked conn_list, or is about to\n+\t * with this lock held: a connection attached now would never be\n+\t * dropped by it.  A node a teardown sweep has claimed belongs to\n+\t * a connection that sweep is destroying.  Refuse both, and leave\n+\t * the node where it is: on the nodev list for the exit sweep to\n+\t * find, or on the sweep's own list.\n+\t */\n+\tif (rds_ibdev-\u003eshutting_down || ic-\u003ei_ib_node_detached) {\n+\t\tret = -ENODEV;\n+\t} else {\n+\t\tlist_del(\u0026ic-\u003eib_node);\n+\t\tlist_add_tail(\u0026ic-\u003eib_node, \u0026rds_ibdev-\u003econn_list);\n+\t}\n \tspin_unlock(\u0026rds_ibdev-\u003espinlock);\n \tspin_unlock_irq(\u0026ib_nodev_conns_lock);\n+\tif (ret)\n+\t\treturn ret;\n \n \tic-\u003erds_ibdev = rds_ibdev;\n \trefcount_inc(\u0026rds_ibdev-\u003erefcount);\n+\n+\treturn 0;\n }\n \n void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)\n {\n \tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\n \n-\t/* place conn on nodev_conns_list */\n+\tbool detached;\n+\n+\t/* place conn on nodev_conns_list - unless a teardown sweep has\n+\t * claimed it ahead of destroying it, in which case its node\n+\t * belongs to the sweep\n+\t */\n \tspin_lock(\u0026ib_nodev_conns_lock);\n \n \tspin_lock_irq(\u0026rds_ibdev-\u003espinlock);\n-\tBUG_ON(list_empty(\u0026ic-\u003eib_node));\n-\tlist_del(\u0026ic-\u003eib_node);\n+\tdetached = ic-\u003ei_ib_node_detached;\n+\tif (!detached)\n+\t\tlist_del(\u0026ic-\u003eib_node);\n \tspin_unlock_irq(\u0026rds_ibdev-\u003espinlock);\n \n-\tlist_add_tail(\u0026ic-\u003eib_node, \u0026ib_nodev_conns);\n+\tif (!detached)\n+\t\tlist_add_tail(\u0026ic-\u003eib_node, \u0026ib_nodev_conns);\n \n \tspin_unlock(\u0026ib_nodev_conns_lock);\n \n@@ -163,13 +187,40 @@ void rds_ib_destroy_nodev_conns(void)\n \tstruct rds_ib_connection *ic, *_ic;\n \tLIST_HEAD(tmp_list);\n \n-\t/* avoid calling conn_destroy with irqs off */\n+\tstruct rds_connection *conn;\n+\n+\t/* Gather the connections and take a reference on each, so that\n+\t * none is freed under the walk below once the deferred frees\n+\t * introduced later in the series can drop a connection's last\n+\t * reference behind this sweep.  One whose free\n+\t * is already running gets no reference: its free unlinks the\n+\t * node itself, under this lock, once we drop it.  Marking the\n+\t * node detached claims it for this sweep: rds_ib_add_conn(),\n+\t * rds_ib_remove_conn() and rds_ib_conn_free() leave a claimed\n+\t * node alone, so the walk over tmp_list below needs no lock.\n+\t * Avoid calling conn_destroy with irqs off.\n+\t */\n \tspin_lock_irq(\u0026ib_nodev_conns_lock);\n-\tlist_splice(\u0026ib_nodev_conns, \u0026tmp_list);\n+\tlist_for_each_entry_safe(ic, _ic, \u0026ib_nodev_conns, ib_node) {\n+\t\tif (rds_conn_get_unless_zero(ic-\u003econn)) {\n+\t\t\tic-\u003ei_ib_node_detached = true;\n+\t\t\tlist_move_tail(\u0026ic-\u003eib_node, \u0026tmp_list);\n+\t\t}\n+\t}\n \tspin_unlock_irq(\u0026ib_nodev_conns_lock);\n \n-\tlist_for_each_entry_safe(ic, _ic, \u0026tmp_list, ib_node)\n-\t\trds_conn_destroy(ic-\u003econn);\n+\t/* rds_conn_destroy() can return before the connection is freed,\n+\t * and it is the free - rds_ib_conn_free() - that would unlink\n+\t * ib_node.  tmp_list lives on this stack frame, so take each node\n+\t * off it before its destroy; the free then leaves it alone.\n+\t */\n+\tlist_for_each_entry_safe(ic, _ic, \u0026tmp_list, ib_node) {\n+\t\tconn = ic-\u003econn;\n+\t\tlist_del_init(\u0026ic-\u003eib_node);\n+\n+\t\trds_conn_destroy(conn);\n+\t\trds_conn_put(conn);\n+\t}\n }\n \n void rds_ib_get_mr_info(struct rds_ib_device *rds_ibdev, struct rds_info_rdma_connection *iinfo)\ndiff --git a/net/rds/ib_recv.c b/net/rds/ib_recv.c\nindex bd6cb3ffaa571..7d45808544a0d 100644\n--- a/net/rds/ib_recv.c\n+++ b/net/rds/ib_recv.c\n@@ -458,7 +458,11 @@ void rds_ib_recv_refill(struct rds_connection *conn, int prefill, gfp_t gfp)\n \t    (must_wake ||\n \t    (can_wait \u0026\u0026 rds_ib_ring_low(\u0026ic-\u003ei_recv_ring)) ||\n \t    rds_ib_ring_empty(\u0026ic-\u003ei_recv_ring))) {\n-\t\tqueue_delayed_work(conn-\u003ec_path-\u003ecp_wq, \u0026conn-\u003ec_recv_w, 1);\n+\t\trcu_read_lock();\n+\t\tif (!rds_destroy_pending(conn))\n+\t\t\tqueue_delayed_work(conn-\u003ec_path-\u003ecp_wq,\n+\t\t\t\t\t   \u0026conn-\u003ec_recv_w, 1);\n+\t\trcu_read_unlock();\n \t}\n \tif (can_wait)\n \t\tcond_resched();\ndiff --git a/net/rds/ib_send.c b/net/rds/ib_send.c\nindex d6be95542119f..bc411e96ad12d 100644\n--- a/net/rds/ib_send.c\n+++ b/net/rds/ib_send.c\n@@ -298,8 +298,13 @@ void rds_ib_send_cqe_handler(struct rds_ib_connection *ic, struct ib_wc *wc)\n \trds_ib_sub_signaled(ic, nr_sig);\n \n \tif (test_and_clear_bit(RDS_LL_SEND_FULL, \u0026conn-\u003ec_flags) ||\n-\t    test_bit(0, \u0026conn-\u003ec_map_queued))\n-\t\tqueue_delayed_work(conn-\u003ec_path-\u003ecp_wq, \u0026conn-\u003ec_send_w, 0);\n+\t    test_bit(0, \u0026conn-\u003ec_map_queued)) {\n+\t\trcu_read_lock();\n+\t\tif (!rds_destroy_pending(conn))\n+\t\t\tqueue_delayed_work(conn-\u003ec_path-\u003ecp_wq,\n+\t\t\t\t\t   \u0026conn-\u003ec_send_w, 0);\n+\t\trcu_read_unlock();\n+\t}\n \n \t/* We expect errors as the qp is drained during shutdown */\n \tif (wc-\u003estatus != IB_WC_SUCCESS \u0026\u0026 rds_conn_up(conn)) {\n@@ -420,8 +425,13 @@ void rds_ib_send_add_credits(struct rds_connection *conn, unsigned int credits)\n \t\t\ttest_bit(RDS_LL_SEND_FULL, \u0026conn-\u003ec_flags) ? \", ll_send_full\" : \"\");\n \n \tatomic_add(IB_SET_SEND_CREDITS(credits), \u0026ic-\u003ei_credits);\n-\tif (test_and_clear_bit(RDS_LL_SEND_FULL, \u0026conn-\u003ec_flags))\n-\t\tqueue_delayed_work(conn-\u003ec_path-\u003ecp_wq, \u0026conn-\u003ec_send_w, 0);\n+\tif (test_and_clear_bit(RDS_LL_SEND_FULL, \u0026conn-\u003ec_flags)) {\n+\t\trcu_read_lock();\n+\t\tif (!rds_destroy_pending(conn))\n+\t\t\tqueue_delayed_work(conn-\u003ec_path-\u003ecp_wq,\n+\t\t\t\t\t   \u0026conn-\u003ec_send_w, 0);\n+\t\trcu_read_unlock();\n+\t}\n \n \tWARN_ON(IB_GET_SEND_CREDITS(credits) \u003e= 16384);\n \ndiff --git a/net/rds/loop.c b/net/rds/loop.c\nindex e6b0750bbedab..5bac858df87ef 100644\n--- a/net/rds/loop.c\n+++ b/net/rds/loop.c\n@@ -156,6 +156,45 @@ static int rds_loop_conn_alloc(struct rds_connection *conn, gfp_t gfp)\n \treturn 0;\n }\n \n+/* Destroy the connections whose nodes were gathered on @tmp_list.\n+ *\n+ * rds_conn_destroy() can return before the connection is freed, and\n+ * it is the free - rds_loop_conn_free() - that unlinks loop_node.\n+ * @tmp_list lives on the caller's stack, so unlink each node before\n+ * its destroy; the free then finds it empty and leaves it alone.\n+ */\n+static void rds_loop_destroy_gathered_conns(struct list_head *tmp_list)\n+{\n+\tstruct rds_loop_connection *lc, *_lc;\n+\tstruct rds_connection *conn;\n+\n+\tlist_for_each_entry_safe(lc, _lc, tmp_list, loop_node) {\n+\t\tconn = lc-\u003econn;\n+\t\tWARN_ON(rcu_access_pointer(conn-\u003ec_passive));\n+\n+\t\tspin_lock_irq(\u0026loop_conns_lock);\n+\t\tlist_del_init(\u0026lc-\u003eloop_node);\n+\t\tspin_unlock_irq(\u0026loop_conns_lock);\n+\n+\t\trds_conn_destroy(conn);\n+\t\trds_conn_put(conn);\n+\t}\n+}\n+\n+/* Gather @lc's connection for destruction: move the node to the\n+ * caller's @tmp_list and take a reference that keeps the connection,\n+ * and so the node, alive until rds_loop_destroy_gathered_conns() has\n+ * dealt with it.  Called with loop_conns_lock held.  A connection\n+ * whose free is already running gets no reference; its free unlinks\n+ * the node itself, under the same lock, once we drop it.\n+ */\n+static void rds_loop_gather_conn(struct rds_loop_connection *lc,\n+\t\t\t\t struct list_head *tmp_list)\n+{\n+\tif (rds_conn_get_unless_zero(lc-\u003econn))\n+\t\tlist_move_tail(\u0026lc-\u003eloop_node, tmp_list);\n+}\n+\n static void rds_loop_conn_free(void *arg)\n {\n \tstruct rds_loop_connection *lc = arg;\n@@ -163,7 +202,9 @@ static void rds_loop_conn_free(void *arg)\n \n \trdsdebug(\"lc %p\\n\", lc);\n \tspin_lock_irqsave(\u0026loop_conns_lock, flags);\n-\tlist_del(\u0026lc-\u003eloop_node);\n+\t/* already unlinked if a transport teardown gathered us first */\n+\tif (!list_empty(\u0026lc-\u003eloop_node))\n+\t\tlist_del(\u0026lc-\u003eloop_node);\n \tspin_unlock_irqrestore(\u0026loop_conns_lock, flags);\n \tkfree(lc);\n }\n@@ -187,14 +228,13 @@ void rds_loop_exit(void)\n \tsynchronize_rcu();\n \t/* avoid calling conn_destroy with irqs off */\n \tspin_lock_irq(\u0026loop_conns_lock);\n-\tlist_splice(\u0026loop_conns, \u0026tmp_list);\n-\tINIT_LIST_HEAD(\u0026loop_conns);\n+\tlist_for_each_entry_safe(lc, _lc, \u0026loop_conns, loop_node)\n+\t\trds_loop_gather_conn(lc, \u0026tmp_list);\n \tspin_unlock_irq(\u0026loop_conns_lock);\n \n-\tlist_for_each_entry_safe(lc, _lc, \u0026tmp_list, loop_node) {\n-\t\tWARN_ON(lc-\u003econn-\u003ec_passive);\n-\t\trds_conn_destroy(lc-\u003econn);\n-\t}\n+\trds_loop_destroy_gathered_conns(\u0026tmp_list);\n+\n+\trds_conn_wait_conns_freed(\u0026rds_loop_transport, NULL);\n }\n \n static void rds_loop_kill_conns(struct net *net)\n@@ -208,14 +248,11 @@ static void rds_loop_kill_conns(struct net *net)\n \n \t\tif (net != c_net)\n \t\t\tcontinue;\n-\t\tlist_move_tail(\u0026lc-\u003eloop_node, \u0026tmp_list);\n+\t\trds_loop_gather_conn(lc, \u0026tmp_list);\n \t}\n \tspin_unlock_irq(\u0026loop_conns_lock);\n \n-\tlist_for_each_entry_safe(lc, _lc, \u0026tmp_list, loop_node) {\n-\t\tWARN_ON(lc-\u003econn-\u003ec_passive);\n-\t\trds_conn_destroy(lc-\u003econn);\n-\t}\n+\trds_loop_destroy_gathered_conns(\u0026tmp_list);\n }\n \n static void __net_exit rds_loop_exit_net(struct net *net)\ndiff --git a/net/rds/message.c b/net/rds/message.c\nindex 47d5e9ab9b109..cea48ad745ca7 100644\n--- a/net/rds/message.c\n+++ b/net/rds/message.c\n@@ -182,6 +182,18 @@ static void rds_message_purge(struct rds_message *rm)\n \t\tkref_put(\u0026rm-\u003eatomic.op_rdma_mr-\u003er_kref, __rds_put_mr_final);\n }\n \n+static void rds_message_free(struct rds_message *rm)\n+{\n+\t/* get in rds_send_queue_rm(), rds_send_probe() or the congestion\n+\t * map path of rds_send_xmit().  Messages that were never queued on\n+\t * a connection have no reference to drop.\n+\t */\n+\tif (rm-\u003em_inc.i_conn)\n+\t\trds_conn_put(rm-\u003em_inc.i_conn);\n+\n+\tkfree(rm);\n+}\n+\n static void rds_message_unpin_worker(struct work_struct *work)\n {\n \tstruct rds_message *rm = container_of(work, struct rds_message,\n@@ -192,7 +204,7 @@ static void rds_message_unpin_worker(struct work_struct *work)\n \tif (rm-\u003eatomic.op_unpin_deferred)\n \t\trds_atomic_op_unpin_page(\u0026rm-\u003eatomic);\n \n-\tkfree(rm);\n+\trds_message_free(rm);\n }\n \n void rds_message_put(struct rds_message *rm)\n@@ -217,7 +229,7 @@ void rds_message_put(struct rds_message *rm)\n \t\t\treturn;\n \t\t}\n \n-\t\tkfree(rm);\n+\t\trds_message_free(rm);\n \t}\n }\n EXPORT_SYMBOL_GPL(rds_message_put);\ndiff --git a/net/rds/rdma_transport.c b/net/rds/rdma_transport.c\nindex 3f853004c4906..a789104725c9a 100644\n--- a/net/rds/rdma_transport.c\n+++ b/net/rds/rdma_transport.c\n@@ -63,6 +63,21 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,\n \tif (cm_id-\u003edevice-\u003enode_type == RDMA_NODE_IB_CA)\n \t\ttrans = \u0026rds_ib_transport;\n \n+\t/* cm_id-\u003econtext carries no reference of its own.  Pin the\n+\t * connection for the duration of the handler, since the mutex\n+\t * released at out: lives in the connection's path array.  None\n+\t * of the callbacks below drops a reference on this connection,\n+\t * and the shutdown destroys the cm_id - waiting for a running\n+\t * handler - before the last reference can go, so this is\n+\t * defensive.  A connection already at zero references gets no\n+\t * events handled.\n+\t */\n+\tif (conn \u0026\u0026 !rds_conn_get_unless_zero(conn)) {\n+\t\trdsdebug(\"conn %p id %p is being freed, ignoring event\\n\",\n+\t\t\t conn, cm_id);\n+\t\treturn 0;\n+\t}\n+\n \t/* Prevent shutdown from tearing down the connection\n \t * while we're executing. */\n \tif (conn) {\n@@ -171,8 +186,10 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,\n \t}\n \n out:\n-\tif (conn)\n+\tif (conn) {\n \t\tmutex_unlock(\u0026conn-\u003ec_cm_lock);\n+\t\trds_conn_put(conn);\n+\t}\n \n \trdsdebug(\"id %p event %u (%s) handling ret %d\\n\", cm_id, event-\u003eevent,\n \t\t rdma_event_msg(event-\u003eevent), ret);\ndiff --git a/net/rds/rds.h b/net/rds/rds.h\nindex 2db49573dacd5..4c63e5292dd11 100644\n--- a/net/rds/rds.h\n+++ b/net/rds/rds.h\n@@ -89,7 +89,6 @@ enum {\n #define RDS_RECONNECT_PENDING\t1\n #define RDS_IN_XMIT\t\t2\n #define RDS_RECV_REFILL\t\t3\n-#define\tRDS_DESTROY_PENDING\t4\n \n /* Max number of multipaths per RDS connection. Must be a power of 2 */\n #define\tRDS_MPATH_WORKERS\t8\n@@ -138,6 +137,12 @@ struct rds_conn_path {\n /* One rds_connection per RDS address pair */\n struct rds_connection {\n \tstruct hlist_node\tc_hash_node;\n+\t/* rds_conn_destroy() quiesces the connection synchronously;\n+\t * freeing it - the connection memory, the path workqueues and\n+\t * the transport's per-connection state - is deferred until the\n+\t * last reference is dropped via rds_conn_put().\n+\t */\n+\tstruct kref\t\tc_refcount;\n \tstruct in6_addr\t\tc_laddr;\n \tstruct in6_addr\t\tc_faddr;\n \tint\t\t\tc_dev_if; /* ifindex used for this conn */\n@@ -148,7 +153,25 @@ struct rds_connection {\n \t\t\t\tc_pad_to_32:29;\n \tint\t\t\tc_npaths;\n \tbool\t\t\tc_with_sport_idx;\n-\tstruct rds_connection\t*c_passive;\n+\t/* Set once, by rds_conn_destroy() under rds_conn_lock - a\n+\t * test-and-set, so a second destroy of the same connection\n+\t * returns at once - before it cancels the path works.  Read\n+\t * through rds_destroy_pending(), which also reports netns\n+\t * teardown and module unload; the c_passive handling in\n+\t * __rds_conn_create() uses the same predicate, since those rule\n+\t * a passive connection out just as well.  A site that arms\n+\t * a path work must test the predicate and queue the work inside\n+\t * one rcu_read_lock() section: the synchronize_rcu() that\n+\t * follows the store is what keeps a queue issued after the\n+\t * cancellation from landing on a destroyed workqueue.  Two kinds\n+\t * of site are exempt: the workers' own self-requeues, which the\n+\t * sync cancel in the destroy path rejects, and the destroy == true\n+\t * rds_conn_path_drop(): the destroy issues and flushes it itself,\n+\t * and IB device removal issues it ahead of the module exit, which\n+\t * destroys - and so flushes - that connection afterwards.\n+\t */\n+\tbool\t\t\tc_destroy_in_prog;\n+\tstruct rds_connection __rcu *c_passive;\n \tstruct rds_transport\t*c_trans;\n \n \tstruct rds_cong_map\t*c_lcong;\n@@ -544,6 +567,12 @@ struct rds_transport {\n \tunsigned int\t\tt_prefer_loopback:1,\n \t\t\t\tt_mp_capable:1;\n \tunsigned int\t\tt_type;\n+\t/* Connections of this transport not yet freed; freeing runs\n+\t * asynchronously once rds_conn_destroy() has quiesced a\n+\t * connection, so transport module unload has to wait for this\n+\t * to reach zero (rds_conn_wait_conns_freed()).\n+\t */\n+\tatomic_t\t\tt_conn_count;\n \n \tint (*laddr_check)(struct net *net, const struct in6_addr *addr,\n \t\t\t   __u32 scope_id);\n@@ -650,7 +679,12 @@ struct rds_sock {\n \n \t/*\n \t * rds_sendmsg caches the conn it used the last time around.\n-\t * This helps avoid costly lookups.\n+\t * This helps avoid costly lookups.  The cache owns a connection\n+\t * reference, dropped when it is replaced, when rds_sendmsg()\n+\t * evicts a connection whose destroy has begun, or when the\n+\t * socket is released, and is read and written under rs_lock -\n+\t * except by\n+\t * rds_release(), which runs once no one else can reach the socket.\n \t */\n \tstruct rds_connection\t*rs_conn;\n \n@@ -659,7 +693,11 @@ struct rds_sock {\n \t/* seen congestion (ENOBUFS) when sending? */\n \tint\t\t\trs_seen_congestion;\n \n-\t/* rs_lock protects all these adjacent members before the newline */\n+\t/* rs_lock protects all these adjacent members before the newline,\n+\t * as well as rs_conn above and rs_tos at the end of the struct -\n+\t * except that rds_sendmsg() samples rs_tos locklessly, with\n+\t * READ_ONCE(), for the create, and re-checks it under the lock.\n+\t */\n \tspinlock_t\t\trs_lock;\n \tstruct list_head\trs_send_queue;\n \tu32\t\t\trs_snd_bytes;\n@@ -819,6 +857,21 @@ struct rds_connection *rds_conn_create_outgoing(struct net *net,\n \t\t\t\t\t\tu8 tos, gfp_t gfp, int dev_if);\n void rds_conn_shutdown(struct rds_conn_path *cpath);\n void rds_conn_destroy(struct rds_connection *conn);\n+void rds_conn_get(struct rds_connection *conn);\n+void rds_conn_put(struct rds_connection *conn);\n+/* take a reference unless the connection is already being freed */\n+static inline bool rds_conn_get_unless_zero(struct rds_connection *conn)\n+{\n+\treturn kref_get_unless_zero(\u0026conn-\u003ec_refcount);\n+}\n+\n+/* transport unload waits for its connections to be freed, polling at\n+ * the first interval and warning at the second\n+ */\n+#define RDS_CONN_FREE_POLL_MS\t\t100\n+#define RDS_CONN_FREE_WARN_INTERVAL_MS\t10000\n+void rds_conn_wait_conns_freed(struct rds_transport *trans,\n+\t\t\t       void (*resweep)(void));\n void rds_conn_drop(struct rds_connection *conn);\n void rds_conn_path_drop(struct rds_conn_path *cpath, bool destroy);\n void rds_conn_connect_if_down(struct rds_connection *conn);\n@@ -994,7 +1047,8 @@ void __rds_put_mr_final(struct kref *kref);\n \n static inline bool rds_destroy_pending(struct rds_connection *conn)\n {\n-\treturn !check_net(rds_conn_net(conn)) ||\n+\treturn READ_ONCE(conn-\u003ec_destroy_in_prog) ||\n+\t       !check_net(rds_conn_net(conn)) ||\n \t       (conn-\u003ec_trans-\u003et_unloading \u0026\u0026 conn-\u003ec_trans-\u003et_unloading(conn));\n }\n \ndiff --git a/net/rds/recv.c b/net/rds/recv.c\nindex 6204e577a90ae..9e7e55ca7bd2b 100644\n--- a/net/rds/recv.c\n+++ b/net/rds/recv.c\n@@ -46,6 +46,7 @@ void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn,\n {\n \trefcount_set(\u0026inc-\u003ei_refcount, 1);\n \tINIT_LIST_HEAD(\u0026inc-\u003ei_item);\n+\trds_conn_get(conn);\t/* put in rds_inc_put() */\n \tinc-\u003ei_conn = conn;\n \tinc-\u003ei_conn_path = NULL;\n \tinc-\u003ei_saddr = *saddr;\n@@ -61,6 +62,7 @@ void rds_inc_path_init(struct rds_incoming *inc, struct rds_conn_path *cp,\n {\n \trefcount_set(\u0026inc-\u003ei_refcount, 1);\n \tINIT_LIST_HEAD(\u0026inc-\u003ei_item);\n+\trds_conn_get(cp-\u003ecp_conn);\t/* put in rds_inc_put() */\n \tinc-\u003ei_conn = cp-\u003ecp_conn;\n \tinc-\u003ei_conn_path = cp;\n \tinc-\u003ei_saddr = *saddr;\n@@ -81,9 +83,19 @@ void rds_inc_put(struct rds_incoming *inc)\n {\n \trdsdebug(\"put inc %p ref %d\\n\", inc, refcount_read(\u0026inc-\u003ei_refcount));\n \tif (refcount_dec_and_test(\u0026inc-\u003ei_refcount)) {\n+\t\tstruct rds_connection *conn = inc-\u003ei_conn;\n+\n \t\tBUG_ON(!list_empty(\u0026inc-\u003ei_item));\n \n-\t\tinc-\u003ei_conn-\u003ec_trans-\u003einc_free(inc);\n+\t\t/* inc_free() can free the memory @inc lives in, so the\n+\t\t * connection reference has to be dropped through the\n+\t\t * copy taken above.\n+\t\t */\n+\t\tconn-\u003ec_trans-\u003einc_free(inc);\n+\t\t/* get in rds_inc_init(), rds_inc_path_init() or\n+\t\t * rds_recv_incoming()\n+\t\t */\n+\t\trds_conn_put(conn);\n \t}\n }\n EXPORT_SYMBOL_GPL(rds_inc_put);\n@@ -325,6 +337,13 @@ void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,\n \tunsigned long flags;\n \tstruct rds_conn_path *cp;\n \n+\t/* every caller initialized @inc with rds_inc_init() or\n+\t * rds_inc_path_init() first, so i_conn already holds a reference.\n+\t * Take the new one before dropping the old, so that re-pointing an\n+\t * inc at the connection it already refers to cannot free it.\n+\t */\n+\trds_conn_get(conn);\n+\trds_conn_put(inc-\u003ei_conn);\n \tinc-\u003ei_conn = conn;\n \tinc-\u003ei_rx_jiffies = jiffies;\n \tif (conn-\u003ec_trans-\u003et_mp_capable)\n@@ -406,8 +425,9 @@ void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,\n \t * rds_find_bound() uses a global (netns-agnostic) hash table.\n \t * An RDS connection created in netns A can match a socket bound\n \t * in the init netns, delivering inc cross-netns with inc-\u003ei_conn\n-\t * pointing into netns A.  When cleanup_net() then frees that conn,\n-\t * any subsequent dereference of inc-\u003ei_conn is a use-after-free.\n+\t * pointing into netns A.  Cross-netns delivery is wrong on its\n+\t * own, and the inc's connection reference would keep a\n+\t * connection of a dead netns around, with a stale c_net.\n \t * Drop the inc if the receiving socket lives in a different netns.\n \t */\n \tif (!net_eq(sock_net(rds_rs_to_sk(rs)), rds_conn_net(conn))) {\n@@ -482,7 +502,6 @@ static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc,\n \tif (!list_empty(\u0026inc-\u003ei_item)) {\n \t\tret = 1;\n \t\tif (drop) {\n-\t\t\t/* XXX make sure this i_conn is reliable */\n \t\t\trds_recv_rcvbuf_delta(rs, sk, inc-\u003ei_conn-\u003ec_lcong,\n \t\t\t\t\t      -be32_to_cpu(inc-\u003ei_hdr.h_len),\n \t\t\t\t\t      inc-\u003ei_hdr.h_dport);\ndiff --git a/net/rds/send.c b/net/rds/send.c\nindex 1afa981e5c06d..4ec9931599c5d 100644\n--- a/net/rds/send.c\n+++ b/net/rds/send.c\n@@ -290,6 +290,8 @@ int rds_send_xmit(struct rds_conn_path *cp)\n \t\t\t}\n \t\t\trm-\u003edata.op_active = 1;\n \t\t\trm-\u003em_inc.i_conn_path = cp;\n+\t\t\t/* put in rds_message_put() */\n+\t\t\trds_conn_get(cp-\u003ecp_conn);\n \t\t\trm-\u003em_inc.i_conn = cp-\u003ecp_conn;\n \n \t\t\tcp-\u003ecp_xmit_rm = rm;\n@@ -947,6 +949,7 @@ static int rds_send_queue_rm(struct rds_sock *rs, struct rds_connection *conn,\n \t\t/* The code ordering is a little weird, but we're\n \t\t   trying to minimize the time we hold c_lock */\n \t\trds_message_populate_header(\u0026rm-\u003em_inc.i_hdr, sport, dport, 0);\n+\t\trds_conn_get(conn);\t/* put in rds_message_put() */\n \t\trm-\u003em_inc.i_conn = conn;\n \t\trm-\u003em_inc.i_conn_path = cp;\n \t\trds_message_addref(rm);\n@@ -1159,13 +1162,14 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \tDECLARE_SOCKADDR(struct sockaddr_in *, usin, msg-\u003emsg_name);\n \t__be16 dport;\n \tstruct rds_message *rm = NULL;\n-\tstruct rds_connection *conn;\n+\tstruct rds_connection *conn = NULL;\n \tint ret = 0;\n \tint queued = 0, allocated_mr = 0;\n \tint nonblock = msg-\u003emsg_flags \u0026 MSG_DONTWAIT;\n \tlong timeo = sock_sndtimeo(sk, nonblock);\n \tstruct rds_conn_path *cpath;\n \tstruct in6_addr daddr;\n+\tunsigned long flags;\n \t__u32 scope_id = 0;\n \tsize_t rdma_payload_len = 0;\n \tbool zcopy = ((msg-\u003emsg_flags \u0026 MSG_ZEROCOPY) \u0026\u0026\n@@ -1340,21 +1344,68 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \trm-\u003em_daddr = daddr;\n \n \t/* rds_conn_create has a spinlock that runs with IRQ off.\n-\t * Caching the conn in the socket helps a lot. */\n-\tif (rs-\u003ers_conn \u0026\u0026 ipv6_addr_equal(\u0026rs-\u003ers_conn-\u003ec_faddr, \u0026daddr) \u0026\u0026\n-\t    rs-\u003ers_tos == rs-\u003ers_conn-\u003ec_tos) {\n-\t\tconn = rs-\u003ers_conn;\n+\t * Caching the conn in the socket helps a lot.\n+\t *\n+\t * The cached rs_conn holds a connection reference; take one of\n+\t * our own for the duration of this call (dropped on both exit\n+\t * paths), so that neither a concurrent sender replacing the\n+\t * cache nor rds_conn_destroy() can free the connection under\n+\t * us.  A cached connection whose destruction has begun is not\n+\t * reused: it is evicted here, and this call goes on to look up\n+\t * or create a live one instead of returning -EAGAIN forever.\n+\t */\n+\tspin_lock_irqsave(\u0026rs-\u003ers_lock, flags);\n+\tconn = rs-\u003ers_conn;\n+\tif (conn \u0026\u0026 rds_destroy_pending(conn)) {\n+\t\t/* drop the cache's reference right here, or the socket\n+\t\t * would pin the quiesced connection until it is closed\n+\t\t */\n+\t\trs-\u003ers_conn = NULL;\n+\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n+\t\trds_conn_put(conn);\n+\t\tconn = NULL;\n \t} else {\n+\t\tif (conn \u0026\u0026 ipv6_addr_equal(\u0026conn-\u003ec_faddr, \u0026daddr) \u0026\u0026\n+\t\t    rs-\u003ers_tos == conn-\u003ec_tos)\n+\t\t\trds_conn_get(conn);\n+\t\telse\n+\t\t\tconn = NULL;\n+\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n+\t}\n+\n+\tif (!conn) {\n+\t\tstruct rds_connection *old;\n+\n \t\tconn = rds_conn_create_outgoing(sock_net(sock-\u003esk),\n \t\t\t\t\t\t\u0026rs-\u003ers_bound_addr, \u0026daddr,\n-\t\t\t\t\t\trs-\u003ers_transport, rs-\u003ers_tos,\n+\t\t\t\t\t\trs-\u003ers_transport,\n+\t\t\t\t\t\tREAD_ONCE(rs-\u003ers_tos),\n \t\t\t\t\t\tsock-\u003esk-\u003esk_allocation,\n \t\t\t\t\t\tscope_id);\n \t\tif (IS_ERR(conn)) {\n \t\t\tret = PTR_ERR(conn);\n+\t\t\tconn = NULL;\n \t\t\tgoto out;\n \t\t}\n+\t\t/* rs_tos was sampled without rs_lock for the create above,\n+\t\t * and SIOCRDSSETTOS only refuses a change once rs_conn is\n+\t\t * set, so it can have changed underneath us.  Do not\n+\t\t * install - or send on - a connection whose ToS no longer\n+\t\t * matches the socket's; the retry uses the new one.\n+\t\t */\n+\t\tspin_lock_irqsave(\u0026rs-\u003ers_lock, flags);\n+\t\tif (conn-\u003ec_tos != rs-\u003ers_tos) {\n+\t\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n+\t\t\tret = -EAGAIN;\n+\t\t\tgoto out;\n+\t\t}\n+\t\t/* hand the cache its own reference */\n+\t\trds_conn_get(conn);\n+\t\told = rs-\u003ers_conn;\n \t\trs-\u003ers_conn = conn;\n+\t\tspin_unlock_irqrestore(\u0026rs-\u003ers_lock, flags);\n+\t\tif (old)\n+\t\t\trds_conn_put(old);\n \t}\n \n \tif (conn-\u003ec_trans-\u003et_mp_capable) {\n@@ -1378,9 +1429,14 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \t\t * outstanding.\n \t\t */\n \t\tif (!test_and_set_bit(RDS_RECONNECT_PENDING,\n-\t\t\t\t      \u0026conn-\u003ec_path[0].cp_flags))\n-\t\t\tqueue_delayed_work(conn-\u003ec_path[0].cp_wq,\n-\t\t\t\t\t   \u0026conn-\u003ec_path[0].cp_conn_w, 0);\n+\t\t\t\t      \u0026conn-\u003ec_path[0].cp_flags)) {\n+\t\t\trcu_read_lock();\n+\t\t\tif (!rds_destroy_pending(conn))\n+\t\t\t\tqueue_delayed_work(conn-\u003ec_path[0].cp_wq,\n+\t\t\t\t\t\t   \u0026conn-\u003ec_path[0].cp_conn_w,\n+\t\t\t\t\t\t   0);\n+\t\t\trcu_read_unlock();\n+\t\t}\n \t\trds_send_ping(conn, 0);\n \t}\n \n@@ -1469,6 +1525,8 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \t\tkfree(vct.vec[ind].iov);\n \tkfree(vct.vec);\n \n+\trds_conn_put(conn);\n+\n \treturn payload_len;\n \n out:\n@@ -1476,6 +1534,9 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \t\tkfree(vct.vec[ind].iov);\n \tkfree(vct.vec);\n \n+\tif (conn)\n+\t\trds_conn_put(conn);\n+\n \t/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.\n \t * If the sendmsg goes through, we keep the MR. If it fails with EAGAIN\n \t * or in any other way, we need to destroy the MR again */\n@@ -1522,6 +1583,7 @@ rds_send_probe(struct rds_conn_path *cp, __be16 sport,\n \tlist_add_tail(\u0026rm-\u003em_conn_item, \u0026cp-\u003ecp_send_queue);\n \tset_bit(RDS_MSG_ON_CONN, \u0026rm-\u003em_flags);\n \trds_message_addref(rm);\n+\trds_conn_get(cp-\u003ecp_conn);\t/* put in rds_message_put() */\n \trm-\u003em_inc.i_conn = cp-\u003ecp_conn;\n \trm-\u003em_inc.i_conn_path = cp;\n \ndiff --git a/net/rds/tcp.c b/net/rds/tcp.c\nindex 774a71f88d375..552b32278e30d 100644\n--- a/net/rds/tcp.c\n+++ b/net/rds/tcp.c\n@@ -502,6 +502,48 @@ static bool rds_tcp_is_unloading(struct rds_connection *conn)\n \treturn atomic_read(\u0026rds_tcp_unloading) != 0;\n }\n \n+/* Gather @tc's connection for destruction: move the node to the\n+ * caller's @tmp_list and take a reference that keeps the connection,\n+ * and so the node, alive until rds_tcp_destroy_gathered_conns() has\n+ * dealt with it.  Called with rds_tcp_conn_lock held.  A connection\n+ * whose free is already running gets no reference; its free unlinks\n+ * the node itself, under the same lock, once we drop it.\n+ */\n+static void rds_tcp_gather_conn(struct rds_tcp_connection *tc,\n+\t\t\t\tstruct list_head *tmp_list)\n+{\n+\tif (rds_conn_get_unless_zero(tc-\u003et_cpath-\u003ecp_conn))\n+\t\tlist_move_tail(\u0026tc-\u003et_tcp_node, tmp_list);\n+}\n+\n+/* Destroy the connections whose nodes were gathered on @tmp_list.\n+ *\n+ * rds_conn_destroy() can return before the connection is freed, and\n+ * it is the free - rds_tcp_conn_free() - that unlinks t_tcp_node.\n+ * Since @tmp_list lives on the caller's stack, unlink each node here\n+ * and mark it detached before its destroy, so that a free that runs\n+ * after the caller has returned does not write into a dead frame.\n+ * Every entry holds a reference taken by rds_tcp_gather_conn(), so\n+ * none can be freed under the walk; each is dropped after its destroy.\n+ */\n+static void rds_tcp_destroy_gathered_conns(struct list_head *tmp_list)\n+{\n+\tstruct rds_tcp_connection *tc, *_tc;\n+\tstruct rds_connection *conn;\n+\n+\tlist_for_each_entry_safe(tc, _tc, tmp_list, t_tcp_node) {\n+\t\tconn = tc-\u003et_cpath-\u003ecp_conn;\n+\n+\t\tspin_lock_irq(\u0026rds_tcp_conn_lock);\n+\t\tlist_del_init(\u0026tc-\u003et_tcp_node);\n+\t\ttc-\u003et_tcp_node_detached = true;\n+\t\tspin_unlock_irq(\u0026rds_tcp_conn_lock);\n+\n+\t\trds_conn_destroy(conn);\n+\t\trds_conn_put(conn);\n+\t}\n+}\n+\n static void rds_tcp_destroy_conns(void)\n {\n \tstruct rds_tcp_connection *tc, *_tc;\n@@ -511,12 +553,11 @@ static void rds_tcp_destroy_conns(void)\n \tspin_lock_irq(\u0026rds_tcp_conn_lock);\n \tlist_for_each_entry_safe(tc, _tc, \u0026rds_tcp_conn_list, t_tcp_node) {\n \t\tif (!list_has_conn(\u0026tmp_list, tc-\u003et_cpath-\u003ecp_conn))\n-\t\t\tlist_move_tail(\u0026tc-\u003et_tcp_node, \u0026tmp_list);\n+\t\t\trds_tcp_gather_conn(tc, \u0026tmp_list);\n \t}\n \tspin_unlock_irq(\u0026rds_tcp_conn_lock);\n \n-\tlist_for_each_entry_safe(tc, _tc, \u0026tmp_list, t_tcp_node)\n-\t\trds_conn_destroy(tc-\u003et_cpath-\u003ecp_conn);\n+\trds_tcp_destroy_gathered_conns(\u0026tmp_list);\n }\n \n static void rds_tcp_exit(void);\n@@ -691,15 +732,14 @@ static void rds_tcp_kill_sock(struct net *net)\n \t\tif (net != c_net)\n \t\t\tcontinue;\n \t\tif (!list_has_conn(\u0026tmp_list, tc-\u003et_cpath-\u003ecp_conn)) {\n-\t\t\tlist_move_tail(\u0026tc-\u003et_tcp_node, \u0026tmp_list);\n+\t\t\trds_tcp_gather_conn(tc, \u0026tmp_list);\n \t\t} else {\n \t\t\tlist_del(\u0026tc-\u003et_tcp_node);\n \t\t\ttc-\u003et_tcp_node_detached = true;\n \t\t}\n \t}\n \tspin_unlock_irq(\u0026rds_tcp_conn_lock);\n-\tlist_for_each_entry_safe(tc, _tc, \u0026tmp_list, t_tcp_node)\n-\t\trds_conn_destroy(tc-\u003et_cpath-\u003ecp_conn);\n+\trds_tcp_destroy_gathered_conns(\u0026tmp_list);\n }\n \n static void __net_exit rds_tcp_exit_net(struct net *net)\n@@ -805,6 +845,7 @@ static void rds_tcp_exit(void)\n #endif\n \tunregister_pernet_device(\u0026rds_tcp_net_ops);\n \trds_tcp_destroy_conns();\n+\trds_conn_wait_conns_freed(\u0026rds_tcp_transport, NULL);\n \trds_trans_unregister(\u0026rds_tcp_transport);\n \trds_tcp_recv_exit();\n \tkmem_cache_destroy(rds_tcp_conn_slab);\ndiff --git a/net/rds/tcp_listen.c b/net/rds/tcp_listen.c\nindex 13fa60c1985bb..bb4f01c071693 100644\n--- a/net/rds/tcp_listen.c\n+++ b/net/rds/tcp_listen.c\n@@ -153,7 +153,7 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)\n {\n \tstruct socket *listen_sock = rtn-\u003erds_tcp_listen_sock;\n \tstruct socket *new_sock = NULL;\n-\tstruct rds_connection *conn;\n+\tstruct rds_connection *conn = NULL;\n \tint ret;\n \tstruct inet_sock *inet;\n \tstruct rds_tcp_connection *rs_tcp = NULL;\n@@ -229,6 +229,7 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)\n \n \tif (IS_ERR(conn)) {\n \t\tret = PTR_ERR(conn);\n+\t\tconn = NULL;\n \t\tgoto out;\n \t}\n \t/* An incoming SYN request came in, and TCP just accepted it.\n@@ -277,6 +278,13 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)\n \tcp = rs_tcp-\u003et_cpath;\n \tconn_state = rds_conn_path_state(cp);\n \tWARN_ON(conn_state == RDS_CONN_UP);\n+\t/* A connection whose destroy has begun cannot be found here:\n+\t * TCP connections are only destroyed on netns teardown and on\n+\t * module unload, and both go through rds_tcp_kill_sock() - which\n+\t * clears the listen socket that the top of this function tests\n+\t * and then flushes this work in rds_tcp_listen_stop() - before\n+\t * any connection is destroyed.\n+\t */\n \tif (conn_state != RDS_CONN_CONNECTING \u0026\u0026 conn_state != RDS_CONN_ERROR) {\n \t\trds_conn_path_drop(cp, 0);\n \t\tgoto rst_nsk;\n@@ -316,10 +324,14 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)\n \t */\n \tif (READ_ONCE(sk-\u003esk_state) == TCP_CLOSE_WAIT ||\n \t    READ_ONCE(sk-\u003esk_state) == TCP_LAST_ACK ||\n-\t    READ_ONCE(sk-\u003esk_state) == TCP_CLOSE)\n+\t    READ_ONCE(sk-\u003esk_state) == TCP_CLOSE) {\n \t\trds_conn_path_drop(cp, 0);\n-\telse\n-\t\tqueue_delayed_work(cp-\u003ecp_wq, \u0026cp-\u003ecp_recv_w, 0);\n+\t} else {\n+\t\trcu_read_lock();\n+\t\tif (!rds_destroy_pending(cp-\u003ecp_conn))\n+\t\t\tqueue_delayed_work(cp-\u003ecp_wq, \u0026cp-\u003ecp_recv_w, 0);\n+\t\trcu_read_unlock();\n+\t}\n \n \tsock_put(sk);\n \n@@ -343,6 +355,8 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)\n \t\tmutex_unlock(\u0026rs_tcp-\u003et_conn_path_lock);\n \tif (new_sock)\n \t\tsock_release(new_sock);\n+\tif (conn)\n+\t\trds_conn_put(conn);\n \n \tmutex_unlock(\u0026rtn-\u003erds_tcp_accept_lock);\n \n"
}

2/1 2026/10/08 03:38 agent patch-evaluator
3m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "RDS",
    "RDS_TCP",
    "RDS_RDMA",
    "INFINIBAND",
    "INFINIBAND_ADDR_TRANS"
  ],
  "FocusSymbols": [
    "rds_conn_destroy",
    "rds_conn_put",
    "rds_conn_get",
    "rds_conn_create",
    "rds_conn_create_outgoing",
    "rds_sendmsg",
    "rds_release",
    "rds_ioctl",
    "rds_inc_put",
    "rds_recv_incoming",
    "rds_message_put",
    "rds_tcp_accept_one"
  ],
  "Reasoning": "The patch overhauls connection lifecycle management and reference counting across the RDS (Reliable Datagram Sockets) subsystem and its transports (loopback, TCP, IB). It replaces immediate connection freeing with deferred kref-based destruction, updates lock handling and caching in rds_sendmsg, rds_release, and rds_ioctl, alters workqueue quiescing and message/incoming datagram reference ownership, and adjusts transport teardown paths. These changes affect fully reachable socket and networking code with concurrency, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 56430c88cd4670f2cd2c6b6dcee84004f34dda87
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 8 03:38:14 2026 +0000

    syz-cluster: applied patch under review

diff --git a/net/rds/af_rds.c b/net/rds/af_rds.c
index d5defe9172e36..99c44d88d2e7e 100644
--- a/net/rds/af_rds.c
+++ b/net/rds/af_rds.c
@@ -80,6 +80,14 @@ static int rds_release(struct socket *sock)
 	rds_notify_queue_get(rs, NULL);
 	rds_notify_msg_zcopy_purge(&rs->rs_zcookie_queue);
 
+	/* drop the cached connection reference; no sendmsg can race
+	 * with us here, the socket is going away
+	 */
+	if (rs->rs_conn) {
+		rds_conn_put(rs->rs_conn);
+		rs->rs_conn = NULL;
+	}
+
 	spin_lock_bh(&rds_sock_lock);
 	list_del_init(&rs->rs_item);
 	spin_unlock_bh(&rds_sock_lock);
@@ -255,6 +263,7 @@ static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
 {
 	struct rds_sock *rs = rds_sk_to_rs(sock->sk);
 	rds_tos_t utos, tos = 0;
+	unsigned long flags;
 
 	switch (cmd) {
 	case SIOCRDSSETTOS:
@@ -267,18 +276,23 @@ static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
 		else
 			return -ENOIOCTLCMD;
 
-		spin_lock_bh(&rds_sock_lock);
+		/* rs_conn is serialized by rs_lock (see rds_sendmsg());
+		 * hold it across the "no connection yet" check and the
+		 * rs_tos store so a racing sendmsg cannot cache a conn
+		 * whose c_tos then disagrees with rs_tos.
+		 */
+		spin_lock_irqsave(&rs->rs_lock, flags);
 		if (rs->rs_tos || rs->rs_conn) {
-			spin_unlock_bh(&rds_sock_lock);
+			spin_unlock_irqrestore(&rs->rs_lock, flags);
 			return -EINVAL;
 		}
-		rs->rs_tos = tos;
-		spin_unlock_bh(&rds_sock_lock);
+		WRITE_ONCE(rs->rs_tos, tos);
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
 		break;
 	case SIOCRDSGETTOS:
-		spin_lock_bh(&rds_sock_lock);
+		spin_lock_irqsave(&rs->rs_lock, flags);
 		tos = rs->rs_tos;
-		spin_unlock_bh(&rds_sock_lock);
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
 		if (put_user(tos, (rds_tos_t __user *)arg))
 			return -EFAULT;
 		break;
diff --git a/net/rds/connection.c b/net/rds/connection.c
index c752a8623cfca..8c4df7d6b294d 100644
--- a/net/rds/connection.c
+++ b/net/rds/connection.c
@@ -47,7 +47,8 @@
 
 /* converting this to RCU is a chore for another day.. */
 static DEFINE_SPINLOCK(rds_conn_lock);
-static unsigned long rds_conn_count;
+/* woken whenever a transport's t_conn_count drops to zero */
+static DECLARE_WAIT_QUEUE_HEAD(rds_conn_freed_waitq);
 static struct hlist_head rds_conn_hash[RDS_CONNECTION_HASH_ENTRIES];
 static struct kmem_cache *rds_conn_slab;
 
@@ -79,7 +80,10 @@ static struct hlist_head *rds_conn_bucket(const struct in6_addr *laddr,
 		var |= RDS_INFO_CONNECTION_FLAG_##suffix;	\
 } while (0)
 
-/* rcu read lock must be held or the connection spinlock */
+/* rcu read lock must be held or the connection spinlock.
+ * On success a reference is taken on the returned connection; the
+ * caller must drop it with rds_conn_put().
+ */
 static struct rds_connection *rds_conn_lookup(struct net *net,
 					      struct hlist_head *head,
 					      const struct in6_addr *laddr,
@@ -96,6 +100,17 @@ static struct rds_connection *rds_conn_lookup(struct net *net,
 		    conn->c_tos == tos &&
 		    net == rds_conn_net(conn) &&
 		    conn->c_dev_if == dev_if) {
+			/* Only ever hand out a live reference.
+			 * rds_conn_destroy() unhashes under
+			 * rds_conn_lock and waits a grace period
+			 * before dropping the initial reference, so
+			 * an entry this traversal reaches still holds
+			 * at least that one; the conditional get
+			 * documents the contract rather than
+			 * papering over a zero-refcount entry.
+			 */
+			if (!kref_get_unless_zero(&conn->c_refcount))
+				continue;
 			ret = conn;
 			break;
 		}
@@ -161,6 +176,30 @@ static void __rds_conn_path_init(struct rds_connection *conn,
 	cp->cp_flags = 0;
 }
 
+/* c_passive is written under rds_conn_lock and read under RCU */
+static struct rds_connection *
+rds_conn_passive_locked(struct rds_connection *conn)
+{
+	return rcu_dereference_protected(conn->c_passive,
+					 lockdep_is_held(&rds_conn_lock));
+}
+
+/* Undo trans->conn_alloc(): it may have allocated transport data for
+ * every path of a multipath connection, not just for path 0.
+ */
+static void rds_conn_free_transport_data(struct rds_connection *conn,
+					 int npaths)
+{
+	struct rds_conn_path *cp;
+	int i;
+
+	for (i = 0; i < npaths; i++) {
+		cp = &conn->c_path[i];
+		if (cp->cp_transport_data)
+			conn->c_trans->conn_free(cp->cp_transport_data);
+	}
+}
+
 /*
  * There is only every one 'conn' for a given pair of addresses in the
  * system at a time.  They contain messages to be retransmitted and so
@@ -197,7 +236,20 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 		 * We need a second connection object into which we
 		 * can stick the other QP. */
 		parent = conn;
-		conn = parent->c_passive;
+		/* The c_passive pointer holds a reference which is only
+		 * dropped one synchronize_rcu() after the pointer is
+		 * cleared, so within this RCU section a fetched pointer
+		 * is always safe to take a reference on.  A passive conn
+		 * whose own destroy has begun is not handed out, though:
+		 * it is quiesced and about to clear the parent's pointer
+		 * itself, and reusing it would re-arm a connection that
+		 * nothing will tear down again.
+		 */
+		conn = rcu_dereference(parent->c_passive);
+		if (conn && rds_destroy_pending(conn))
+			conn = NULL;
+		if (conn)
+			rds_conn_get(conn);
 	}
 	rcu_read_unlock();
 	if (conn)
@@ -215,6 +267,7 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 		goto out;
 	}
 
+	kref_init(&conn->c_refcount);
 	INIT_HLIST_NODE(&conn->c_hash_node);
 	conn->c_laddr = *laddr;
 	conn->c_isv6 = !ipv6_addr_v4mapped(laddr);
@@ -284,12 +337,13 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 
 	init_waitqueue_head(&conn->c_hs_waitq);
 	for (i = 0; i < npaths; i++) {
+		int seq = atomic_read(&trans->t_conn_count);
+
 		__rds_conn_path_init(conn, &conn->c_path[i],
 				     is_outgoing);
 		conn->c_path[i].cp_index = i;
 		conn->c_path[i].cp_wq =
-			alloc_ordered_workqueue("krds_cp_wq#%lu/%d", 0,
-						rds_conn_count, i);
+			alloc_ordered_workqueue("krds_cp_wq#%d/%d", 0, seq, i);
 		if (!conn->c_path[i].cp_wq)
 			conn->c_path[i].cp_wq = rds_wq;
 	}
@@ -321,15 +375,44 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 	spin_lock_irqsave(&rds_conn_lock, flags);
 	if (parent) {
 		/* Creating passive conn */
-		if (parent->c_passive) {
-			trans->conn_free(conn->c_path[0].cp_transport_data);
+		if (rds_destroy_pending(parent)) {
+			/* The parent's destroy has begun (it sets the
+			 * flag and snatches c_passive under this
+			 * lock); do not install a new passive conn
+			 * that nothing would ever destroy.
+			 */
+			rds_conn_free_transport_data(conn, npaths);
+			free_cp = conn->c_path;
+			kmem_cache_free(rds_conn_slab, conn);
+			conn = ERR_PTR(-ENETDOWN);
+		} else if (rcu_access_pointer(parent->c_passive)) {
+			struct rds_connection *passive;
+
+			passive = rds_conn_passive_locked(parent);
+			rds_conn_free_transport_data(conn, npaths);
 			free_cp = conn->c_path;
 			kmem_cache_free(rds_conn_slab, conn);
-			conn = parent->c_passive;
+			/* A passive conn still installed here cannot have
+			 * its own destroy begun: rds_conn_destroy() sets
+			 * c_destroy_in_prog and clears the parent's pointer
+			 * in one rds_conn_lock section, and the netns and
+			 * unload cases were ruled out by the parent above.
+			 */
+			rds_conn_get(passive);
+			conn = passive;
 		} else {
-			parent->c_passive = conn;
+			/* The initial reference belongs to whoever
+			 * destroys the conn (the transport's conn
+			 * lists, as for any other conn).  Take one
+			 * for the c_passive pointer - dropped when
+			 * the parent is destroyed - and one for our
+			 * caller.
+			 */
+			rds_conn_get(conn);	/* c_passive */
+			rds_conn_get(conn);	/* caller */
+			rcu_assign_pointer(parent->c_passive, conn);
 			rds_cong_add_conn(conn);
-			rds_conn_count++;
+			atomic_inc(&conn->c_trans->t_conn_count);
 		}
 	} else {
 		/* Creating normal conn */
@@ -338,33 +421,28 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 		found = rds_conn_lookup(net, head, laddr, faddr, trans,
 					tos, dev_if);
 		if (found) {
-			struct rds_conn_path *cp;
-			int i;
-
-			for (i = 0; i < npaths; i++) {
-				cp = &conn->c_path[i];
-				/* The ->conn_alloc invocation may have
-				 * allocated resource for all paths, so all
-				 * of them may have to be freed here.
-				 */
-				if (cp->cp_transport_data)
-					trans->conn_free(cp->cp_transport_data);
-			}
+			rds_conn_free_transport_data(conn, npaths);
 			free_cp = conn->c_path;
 			kmem_cache_free(rds_conn_slab, conn);
 			conn = found;
 		} else {
 			conn->c_my_gen_num = rds_gen_num;
 			conn->c_peer_gen_num = 0;
+			/* the initial reference belongs to whoever
+			 * destroys the conn; take one for our caller
+			 */
+			rds_conn_get(conn);
 			hlist_add_head_rcu(&conn->c_hash_node, head);
 			rds_cong_add_conn(conn);
-			rds_conn_count++;
+			atomic_inc(&conn->c_trans->t_conn_count);
 		}
 	}
 	spin_unlock_irqrestore(&rds_conn_lock, flags);
 	rcu_read_unlock();
 
 out:
+	if (parent)
+		rds_conn_put(parent);
 	if (free_cp) {
 		for (i = 0; i < npaths; i++)
 			if (free_cp[i].cp_wq != rds_wq)
@@ -472,9 +550,10 @@ void rds_conn_shutdown(struct rds_conn_path *cp)
 			 * Quiesce the reconnect timer before bailing
 			 * out, though.  When a pending destroy did
 			 * suppress the queue, no later pass runs, and
-			 * rds_conn_path_destroy() is about to flush
-			 * cp_down_w and free the path: it must not
-			 * find cp_conn_w still armed.  A successor
+			 * rds_conn_path_quiesce() is about to flush
+			 * cp_down_w, ahead of the path's deferred
+			 * free: it must not find cp_conn_w still
+			 * armed.  A successor
 			 * pass, when there is one, re-arms the
 			 * reconnect from its own tail.
 			 */
@@ -521,12 +600,16 @@ void rds_conn_shutdown(struct rds_conn_path *cp)
 		conn->c_trans->conn_slots_available(conn, false);
 }
 
-/* destroy a single rds_conn_path. rds_conn_destroy() iterates over
- * all paths using rds_conn_path_destroy()
+/* quiesce a single rds_conn_path: shut it down and tear down any
+ * queued messages.  rds_conn_destroy() iterates over all paths using
+ * rds_conn_path_quiesce(); the transport state and the workqueue are
+ * freed later, from rds_conn_path_free().
  */
-static void rds_conn_path_destroy(struct rds_conn_path *cp)
+static void rds_conn_path_quiesce(struct rds_conn_path *cp)
 {
 	struct rds_message *rm, *rtmp;
+	unsigned long flags;
+	LIST_HEAD(purge);
 
 	if (!cp->cp_transport_data)
 		return;
@@ -538,12 +621,29 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)
 	rds_conn_path_drop(cp, true);
 	flush_work(&cp->cp_down_w);
 
-	/* tear down queued messages */
-	list_for_each_entry_safe(rm, rtmp,
-				 &cp->cp_send_queue,
-				 m_conn_item) {
+	/* Tear down queued messages.  Every path that adds to
+	 * cp_send_queue does so under cp_lock; take it here too.  No
+	 * sender can still be running at any destroy trigger, so this is
+	 * lock discipline rather than a race fix: nothing here tells a
+	 * sender that the queue is closed.
+	 */
+	spin_lock_irqsave(&cp->cp_lock, flags);
+	list_splice_init(&cp->cp_send_queue, &purge);
+	/* Give up the queue's claim on each message while still under
+	 * the lock, so that rds_send_drop_to(), which decides ownership
+	 * of the connection-queue reference by this bit, neither drops
+	 * it a second time nor unlinks the message from our list.
+	 */
+	list_for_each_entry(rm, &purge, m_conn_item)
+		clear_bit(RDS_MSG_ON_CONN, &rm->m_flags);
+	spin_unlock_irqrestore(&cp->cp_lock, flags);
+	list_for_each_entry_safe(rm, rtmp, &purge, m_conn_item) {
+		/* No socket can still have messages queued on a connection
+		 * at any destroy trigger; say so if one does, since the
+		 * socket side then retires the message on its own.
+		 */
+		WARN_ON_ONCE(!list_empty(&rm->m_sock_item));
 		list_del_init(&rm->m_conn_item);
-		BUG_ON(!list_empty(&rm->m_sock_item));
 		rds_message_put(rm);
 	}
 	if (cp->cp_xmit_rm)
@@ -553,6 +653,16 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)
 	WARN_ON(delayed_work_pending(&cp->cp_recv_w));
 	WARN_ON(delayed_work_pending(&cp->cp_conn_w));
 	WARN_ON(work_pending(&cp->cp_down_w));
+}
+
+/* free a quiesced rds_conn_path's transport state and workqueue; runs
+ * from rds_conn_destroy_fini() once the last connection reference is
+ * dropped.
+ */
+static void rds_conn_path_free(struct rds_conn_path *cp)
+{
+	if (!cp->cp_transport_data)
+		return;
 
 	if (cp->cp_wq != rds_wq) {
 		destroy_workqueue(cp->cp_wq);
@@ -562,17 +672,102 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)
 	cp->cp_conn->c_trans->conn_free(cp->cp_transport_data);
 }
 
+/* Free a connection.  This runs from rds_conn_put() when the last
+ * reference is dropped, after rds_conn_destroy() has quiesced the
+ * connection and dropped the initial reference.
+ */
+static void rds_conn_destroy_fini(struct kref *kref)
+{
+	struct rds_connection *conn = container_of(kref, struct rds_connection,
+						   c_refcount);
+	int npaths = (conn->c_trans->t_mp_capable ? RDS_MPATH_WORKERS : 1);
+	struct rds_transport *trans = conn->c_trans;
+	int i;
+
+	for (i = 0; i < npaths; i++)
+		rds_conn_path_free(&conn->c_path[i]);
+
+	kfree(conn->c_path);
+	kmem_cache_free(rds_conn_slab, conn);
+
+	/* only after everything the transport module owns has been
+	 * freed above may its unload proceed
+	 */
+	if (!atomic_dec_return(&trans->t_conn_count))
+		wake_up_all(&rds_conn_freed_waitq);
+}
+
+/* Wait for all of @trans's connections to be freed; the free runs
+ * asynchronously once rds_conn_destroy() has quiesced a connection.
+ * Called on transport module unload after an initial sweep has
+ * destroyed the transport's connections; @resweep, when given, is
+ * called on every poll to destroy connections that were still
+ * detaching from a device when the sweep ran (IB).  A connection
+ * reference can be held for an application-controlled time - once
+ * incs hold one, an unread datagram pins the inc that carries it, and
+ * thus the connection - so the wait is unbounded: the frees that run
+ * after unload call into this module's text (conn_free, inc_free) and
+ * free into its slabs, so proceeding while any remain would be a
+ * use-after-free, not a leak.  Warn periodically so a stuck count is
+ * diagnosable, but never stop waiting.  This matches the historical
+ * RDS contract that teardown does not discard queued data.
+ */
+void rds_conn_wait_conns_freed(struct rds_transport *trans,
+			       void (*resweep)(void))
+{
+	unsigned long warn_interval =
+			msecs_to_jiffies(RDS_CONN_FREE_WARN_INTERVAL_MS);
+	unsigned long warn_at = jiffies + warn_interval;
+
+	while (!wait_event_timeout(rds_conn_freed_waitq,
+				   !atomic_read(&trans->t_conn_count),
+				   msecs_to_jiffies(RDS_CONN_FREE_POLL_MS))) {
+		/* A transport whose teardown is asynchronous (IB moves a
+		 * connection off its device from the shutdown work) gives
+		 * us a resweep to destroy what has arrived since.
+		 */
+		if (resweep)
+			resweep();
+		if (time_after_eq(jiffies, warn_at)) {
+			pr_warn("RDS/%s: still waiting for %d connection(s) to be freed before unload\n",
+				trans->t_name,
+				atomic_read(&trans->t_conn_count));
+			warn_at = jiffies + warn_interval;
+		}
+	}
+}
+EXPORT_SYMBOL_GPL(rds_conn_wait_conns_freed);
+
+void rds_conn_get(struct rds_connection *conn)
+{
+	kref_get(&conn->c_refcount);
+}
+EXPORT_SYMBOL_GPL(rds_conn_get);
+
+void rds_conn_put(struct rds_connection *conn)
+{
+	kref_put(&conn->c_refcount, rds_conn_destroy_fini);
+}
+EXPORT_SYMBOL_GPL(rds_conn_put);
+
 /*
  * Stop and free a connection.
  *
- * This can only be used in very limited circumstances.  It assumes that once
- * the conn has been shutdown that no one else is referencing the connection.
- * We can only ensure this in the rmmod path in the current code.
+ * Quiesces the connection synchronously (workers cancelled, transport
+ * connections shut down, queued messages dropped) and drops the
+ * initial reference.  Only the first call for a connection does any
+ * of that: a later one finds c_destroy_in_prog already set and
+ * returns at once, without waiting for the first.  The memory -
+ * including the transport's per-connection state and the path
+ * workqueues - is freed once the last rds_conn_put() runs, which may
+ * be after this returns.
  */
 void rds_conn_destroy(struct rds_connection *conn)
 {
-	unsigned long flags;
 	int i;
+	struct rds_connection *passive, *parent;
+	struct hlist_head *head;
+	bool was_passive = false;
 	struct rds_conn_path *cp;
 	int npaths = (conn->c_trans->t_mp_capable ? RDS_MPATH_WORKERS : 1);
 
@@ -580,16 +775,68 @@ void rds_conn_destroy(struct rds_connection *conn)
 		 "%pI4\n", conn, &conn->c_laddr,
 		 &conn->c_faddr);
 
-	/* Ensure conn will not be scheduled for reconnect */
+	/* Make rds_destroy_pending() true for this conn.  Together with
+	 * the synchronize_rcu() below this stops the work-requeueing
+	 * sites (which test rds_destroy_pending() under rcu_read_lock(),
+	 * bar the exemptions noted at c_destroy_in_prog) from queueing
+	 * new work on the path workqueues once we start cancelling and
+	 * destroying them.
+	 *
+	 * Only the first caller proceeds.  No caller in this tree hands
+	 * a connection to rds_conn_destroy() twice - every teardown
+	 * sweep unlinks or claims its node before the destroy - so this
+	 * documents the contract rather than closing a path: a second
+	 * caller returns at once, without quiescing or waiting.  The
+	 * unhash also happens under rds_conn_lock, so a looked-up conn
+	 * can never be quiesced twice.
+	 */
 	spin_lock_irq(&rds_conn_lock);
+	if (conn->c_destroy_in_prog) {
+		spin_unlock_irq(&rds_conn_lock);
+		return;
+	}
+	WRITE_ONCE(conn->c_destroy_in_prog, true);
+
+	/* Ensure conn will not be scheduled for reconnect */
 	hlist_del_init_rcu(&conn->c_hash_node);
+
+	/* Snatch c_passive while holding the lock:
+	 * __rds_conn_create() dereferences it under rcu_read_lock()
+	 * (and refuses to install a new one once c_destroy_in_prog is
+	 * set, which it checks under this lock).  After the
+	 * synchronize_rcu() below no one can pick the pointer up any
+	 * more and its reference can be dropped.
+	 */
+	passive = rds_conn_passive_locked(conn);
+	RCU_INIT_POINTER(conn->c_passive, NULL);
+
+	/* If we are a parent's passive twin, invalidate its pointer to
+	 * us as well, so that __rds_conn_create() cannot hand out a
+	 * connection whose teardown has begun.  The parent is the
+	 * hashed connection for our key (a passive conn is never
+	 * hashed, and we unhashed ourselves above); it holds its
+	 * initial reference for as long as it is hashed, so the lookup
+	 * reference dropped below cannot be its last.
+	 */
+	head = rds_conn_bucket(&conn->c_laddr, &conn->c_faddr);
+	rcu_read_lock();
+	parent = rds_conn_lookup(rds_conn_net(conn), head, &conn->c_laddr,
+				 &conn->c_faddr, conn->c_trans, conn->c_tos,
+				 conn->c_dev_if);
+	rcu_read_unlock();
+	if (parent && rds_conn_passive_locked(parent) == conn) {
+		RCU_INIT_POINTER(parent->c_passive, NULL);
+		was_passive = true;
+	}
 	spin_unlock_irq(&rds_conn_lock);
+	if (parent)
+		rds_conn_put(parent);
 	synchronize_rcu();
 
 	/* shut the connection down */
 	for (i = 0; i < npaths; i++) {
 		cp = &conn->c_path[i];
-		rds_conn_path_destroy(cp);
+		rds_conn_path_quiesce(cp);
 		BUG_ON(!list_empty(&cp->cp_retrans));
 	}
 
@@ -600,12 +847,21 @@ void rds_conn_destroy(struct rds_connection *conn)
 	 */
 	rds_cong_remove_conn(conn);
 
-	kfree(conn->c_path);
-	kmem_cache_free(rds_conn_slab, conn);
+	/* Drop the reference our c_passive pointer held, if any, and
+	 * the one a parent's c_passive pointer held on us.  Either may
+	 * be the last one - the twin's own destroy may already have run
+	 * - so these must stay here, in sleepable context with no lock
+	 * held, where the free that follows the last put is allowed.
+	 */
+	if (passive)
+		rds_conn_put(passive);
+	if (was_passive)
+		rds_conn_put(conn);
 
-	spin_lock_irqsave(&rds_conn_lock, flags);
-	rds_conn_count--;
-	spin_unlock_irqrestore(&rds_conn_lock, flags);
+	/* drop the initial reference; the connection is freed from
+	 * rds_conn_destroy_fini() once every holder has dropped theirs
+	 */
+	rds_conn_put(conn);
 }
 EXPORT_SYMBOL_GPL(rds_conn_destroy);
 
diff --git a/net/rds/ib.c b/net/rds/ib.c
index 4ea9838d090c3..7b1f611c0a3e5 100644
--- a/net/rds/ib.c
+++ b/net/rds/ib.c
@@ -86,6 +86,11 @@ static void rds_ib_dev_shutdown(struct rds_ib_device *rds_ibdev)
 	unsigned long flags;
 
 	spin_lock_irqsave(&rds_ibdev->spinlock, flags);
+	/* Close the device to new connections under the same lock that
+	 * rds_ib_add_conn() attaches them under, so that every
+	 * connection is either dropped by the walk below or refused.
+	 */
+	rds_ibdev->shutting_down = true;
 	list_for_each_entry(ic, &rds_ibdev->conn_list, ib_node)
 		rds_conn_path_drop(&ic->conn->c_path[0], true);
 	spin_unlock_irqrestore(&rds_ibdev->spinlock, flags);
@@ -523,10 +528,7 @@ static void rds_ib_set_unloading(void)
 
 static bool rds_ib_is_unloading(struct rds_connection *conn)
 {
-	struct rds_conn_path *cp = &conn->c_path[0];
-
-	return (test_bit(RDS_DESTROY_PENDING, &cp->cp_flags) ||
-		atomic_read(&rds_ib_unloading) != 0);
+	return atomic_read(&rds_ib_unloading) != 0;
 }
 
 void rds_ib_exit(void)
@@ -538,7 +540,24 @@ void rds_ib_exit(void)
 	rds_info_deregister_func(RDS6_INFO_IB_CONNECTIONS, rds6_ib_ic_info);
 #endif
 	rds_ib_unregister_client();
+
+	/* rds_ib_dev_shutdown() only dropped the connections still
+	 * attached to a device; each moves itself to ib_nodev_conns
+	 * from its shutdown work.  Destroy what is there now and keep
+	 * sweeping the list while the wait sees connections outstanding,
+	 * so a late arrival is destroyed rather than waited on forever.
+	 */
 	rds_ib_destroy_nodev_conns();
+	rds_conn_wait_conns_freed(&rds_ib_transport,
+				  rds_ib_destroy_nodev_conns);
+
+	/* Tearing down the last connection may have dropped the final
+	 * reference on a device, deferring rds_ib_dev_free() to rds_wq.
+	 * Drain it before the module goes away; it queues nothing
+	 * further on rds_wq.
+	 */
+	flush_workqueue(rds_wq);
+
 	rds_ib_sysctl_exit();
 	rds_ib_recv_exit();
 	rds_trans_unregister(&rds_ib_transport);
diff --git a/net/rds/ib.h b/net/rds/ib.h
index 1901226368c98..07474fe7327b0 100644
--- a/net/rds/ib.h
+++ b/net/rds/ib.h
@@ -143,6 +143,10 @@ struct rds_ib_device;
 struct rds_ib_connection {
 
 	struct list_head	ib_node;
+	/* set under ib_nodev_conns_lock once a transport teardown has
+	 * claimed ib_node; from then on only the teardown touches it
+	 */
+	bool			i_ib_node_detached;
 	struct rds_ib_device	*rds_ibdev;
 	struct rds_connection	*conn;
 
@@ -258,6 +262,10 @@ struct rds_ib_device {
 	unsigned int		max_initiator_depth;
 	unsigned int		max_responder_resources;
 	spinlock_t		spinlock;	/* protect the above */
+	/* set under spinlock by rds_ib_dev_shutdown(): the device is
+	 * going away and no connection may attach to it any more
+	 */
+	bool			shutting_down;
 	refcount_t		refcount;
 	struct work_struct	free_work;
 	int			*vector_load;
@@ -384,7 +392,8 @@ void rds_ib_cm_connect_complete(struct rds_connection *conn,
 struct rds_ib_device *rds_ib_get_device(__be32 ipaddr);
 int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev,
 			 struct in6_addr *ipaddr);
-void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn);
+int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,
+		    struct rds_connection *conn);
 void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn);
 void rds_ib_destroy_nodev_conns(void);
 void rds_ib_mr_cqe_handler(struct rds_ib_connection *ic, struct ib_wc *wc);
diff --git a/net/rds/ib_cm.c b/net/rds/ib_cm.c
index 3ed03ad328129..38d95b016773c 100644
--- a/net/rds/ib_cm.c
+++ b/net/rds/ib_cm.c
@@ -524,7 +524,9 @@ static int rds_ib_setup_qp(struct rds_connection *conn)
 	fr_queue_space = RDS_IB_DEFAULT_FR_WR;
 
 	/* add the conn now so that connection establishment has the dev */
-	rds_ib_add_conn(rds_ibdev, conn);
+	ret = rds_ib_add_conn(rds_ibdev, conn);
+	if (ret)
+		goto out;
 
 	max_wrs = rds_ibdev->max_wrs < rds_ib_sysctl_max_send_wr + 1 ?
 		rds_ibdev->max_wrs - 1 : rds_ib_sysctl_max_send_wr;
@@ -874,6 +876,15 @@ int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,
 	 * see the comment above rds_queue_reconnect()
 	 */
 	mutex_lock(&conn->c_cm_lock);
+	/* Defensive: a destroy that has quiesced this conn also unhashed
+	 * it, so rds_conn_create() cannot have returned it, and the
+	 * listeners are stopped before any IB connection is destroyed at
+	 * unload.  Should a request reach a conn in RDS_CONN_DOWN with
+	 * its destroy begun all the same, do not install a new cm_id and
+	 * QP that nothing would tear down.
+	 */
+	if (rds_destroy_pending(conn))
+		goto out;
 	if (!rds_conn_transition(conn, RDS_CONN_DOWN, RDS_CONN_CONNECTING)) {
 		if (rds_conn_state(conn) == RDS_CONN_UP) {
 			rdsdebug("incoming connect while connecting\n");
@@ -924,8 +935,15 @@ int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,
 		rds_ib_conn_error(conn, "rdma_accept failed\n");
 
 out:
-	if (conn)
+	if (conn) {
 		mutex_unlock(&conn->c_cm_lock);
+		/* Drop the reference rds_conn_create() handed us.  The
+		 * conn stays reachable through cm_id->context without a
+		 * reference of its own; rds_rdma_cm_event_handler_cmn()
+		 * takes one for the duration of each event it handles.
+		 */
+		rds_conn_put(conn);
+	}
 	if (err)
 		rdma_reject(cm_id, &err, sizeof(int),
 			    IB_CM_REJ_CONSUMER_DEFINED);
@@ -941,6 +959,18 @@ int rds_ib_cm_initiate_connect(struct rdma_cm_id *cm_id, bool isv6)
 	union rds_ib_conn_priv dp;
 	int ret;
 
+	/* Defensive: a destroy that began while the address and route
+	 * were being resolved either waits on c_cm_lock behind this
+	 * handler, and its shutdown pass then tears down whatever is
+	 * set up here, or has already destroyed the id this event
+	 * arrived on, in which case the event never gets here.  Decline
+	 * to set up a QP all the same, and return success: the id is
+	 * still ic->i_cm_id, for that shutdown to destroy, and a
+	 * non-zero return would have the rdma_cm destroy it instead.
+	 */
+	if (rds_destroy_pending(conn))
+		return 0;
+
 	/* If the peer doesn't do protocol negotiation, we must
 	 * default to RDSv3.0 */
 	rds_ib_set_protocol(conn, RDS_PROTOCOL_4_1);
@@ -1284,19 +1314,29 @@ void rds_ib_conn_free(void *arg)
 {
 	struct rds_ib_connection *ic = arg;
 	spinlock_t	*lock_ptr;
+	unsigned long flags;
 
 	rdsdebug("ic %p\n", ic);
 
 	/*
-	 * Conn is either on a dev's list or on the nodev list.
-	 * A race with shutdown() or connect() would cause problems
-	 * (since rds_ibdev would change) but that should never happen.
+	 * Conn is on a dev's list or on the nodev list - or, once a
+	 * transport teardown has claimed it (i_ib_node_detached), on
+	 * neither, in which case the lock chosen here only guards the
+	 * test below.  A connect or shutdown still running for a
+	 * claimed conn leaves the node alone, see rds_ib_add_conn() and
+	 * rds_ib_remove_conn().
+	 *
+	 * Callers may hold rds_conn_lock with interrupts disabled
+	 * (__rds_conn_create() undoing a lost creation race), so do not
+	 * re-enable interrupts unconditionally here.
 	 */
 	lock_ptr = ic->rds_ibdev ? &ic->rds_ibdev->spinlock : &ib_nodev_conns_lock;
 
-	spin_lock_irq(lock_ptr);
-	list_del(&ic->ib_node);
-	spin_unlock_irq(lock_ptr);
+	spin_lock_irqsave(lock_ptr, flags);
+	/* a transport teardown that gathered us first owns the node */
+	if (!ic->i_ib_node_detached)
+		list_del(&ic->ib_node);
+	spin_unlock_irqrestore(lock_ptr, flags);
 
 	rds_ib_recv_free_caches(ic);
 
diff --git a/net/rds/ib_rdma.c b/net/rds/ib_rdma.c
index db7e92e7bd29f..f0e7d116b0844 100644
--- a/net/rds/ib_rdma.c
+++ b/net/rds/ib_rdma.c
@@ -119,38 +119,62 @@ int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev,
 	return 0;
 }
 
-void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)
+int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,
+		    struct rds_connection *conn)
 {
 	struct rds_ib_connection *ic = conn->c_transport_data;
+	int ret = 0;
 
-	/* conn was previously on the nodev_conns_list */
+	/* conn was previously on the nodev_conns_list, unless a teardown
+	 * sweep has claimed it ahead of destroying it: then it is on its
+	 * way out, and its node belongs to the sweep.
+	 */
 	spin_lock_irq(&ib_nodev_conns_lock);
-	BUG_ON(list_empty(&ib_nodev_conns));
-	BUG_ON(list_empty(&ic->ib_node));
-	list_del(&ic->ib_node);
-
 	spin_lock(&rds_ibdev->spinlock);
-	list_add_tail(&ic->ib_node, &rds_ibdev->conn_list);
+	/* rds_ib_dev_shutdown() has walked conn_list, or is about to
+	 * with this lock held: a connection attached now would never be
+	 * dropped by it.  A node a teardown sweep has claimed belongs to
+	 * a connection that sweep is destroying.  Refuse both, and leave
+	 * the node where it is: on the nodev list for the exit sweep to
+	 * find, or on the sweep's own list.
+	 */
+	if (rds_ibdev->shutting_down || ic->i_ib_node_detached) {
+		ret = -ENODEV;
+	} else {
+		list_del(&ic->ib_node);
+		list_add_tail(&ic->ib_node, &rds_ibdev->conn_list);
+	}
 	spin_unlock(&rds_ibdev->spinlock);
 	spin_unlock_irq(&ib_nodev_conns_lock);
+	if (ret)
+		return ret;
 
 	ic->rds_ibdev = rds_ibdev;
 	refcount_inc(&rds_ibdev->refcount);
+
+	return 0;
 }
 
 void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)
 {
 	struct rds_ib_connection *ic = conn->c_transport_data;
 
-	/* place conn on nodev_conns_list */
+	bool detached;
+
+	/* place conn on nodev_conns_list - unless a teardown sweep has
+	 * claimed it ahead of destroying it, in which case its node
+	 * belongs to the sweep
+	 */
 	spin_lock(&ib_nodev_conns_lock);
 
 	spin_lock_irq(&rds_ibdev->spinlock);
-	BUG_ON(list_empty(&ic->ib_node));
-	list_del(&ic->ib_node);
+	detached = ic->i_ib_node_detached;
+	if (!detached)
+		list_del(&ic->ib_node);
 	spin_unlock_irq(&rds_ibdev->spinlock);
 
-	list_add_tail(&ic->ib_node, &ib_nodev_conns);
+	if (!detached)
+		list_add_tail(&ic->ib_node, &ib_nodev_conns);
 
 	spin_unlock(&ib_nodev_conns_lock);
 
@@ -163,13 +187,40 @@ void rds_ib_destroy_nodev_conns(void)
 	struct rds_ib_connection *ic, *_ic;
 	LIST_HEAD(tmp_list);
 
-	/* avoid calling conn_destroy with irqs off */
+	struct rds_connection *conn;
+
+	/* Gather the connections and take a reference on each, so that
+	 * none is freed under the walk below once the deferred frees
+	 * introduced later in the series can drop a connection's last
+	 * reference behind this sweep.  One whose free
+	 * is already running gets no reference: its free unlinks the
+	 * node itself, under this lock, once we drop it.  Marking the
+	 * node detached claims it for this sweep: rds_ib_add_conn(),
+	 * rds_ib_remove_conn() and rds_ib_conn_free() leave a claimed
+	 * node alone, so the walk over tmp_list below needs no lock.
+	 * Avoid calling conn_destroy with irqs off.
+	 */
 	spin_lock_irq(&ib_nodev_conns_lock);
-	list_splice(&ib_nodev_conns, &tmp_list);
+	list_for_each_entry_safe(ic, _ic, &ib_nodev_conns, ib_node) {
+		if (rds_conn_get_unless_zero(ic->conn)) {
+			ic->i_ib_node_detached = true;
+			list_move_tail(&ic->ib_node, &tmp_list);
+		}
+	}
 	spin_unlock_irq(&ib_nodev_conns_lock);
 
-	list_for_each_entry_safe(ic, _ic, &tmp_list, ib_node)
-		rds_conn_destroy(ic->conn);
+	/* rds_conn_destroy() can return before the connection is freed,
+	 * and it is the free - rds_ib_conn_free() - that would unlink
+	 * ib_node.  tmp_list lives on this stack frame, so take each node
+	 * off it before its destroy; the free then leaves it alone.
+	 */
+	list_for_each_entry_safe(ic, _ic, &tmp_list, ib_node) {
+		conn = ic->conn;
+		list_del_init(&ic->ib_node);
+
+		rds_conn_destroy(conn);
+		rds_conn_put(conn);
+	}
 }
 
 void rds_ib_get_mr_info(struct rds_ib_device *rds_ibdev, struct rds_info_rdma_connection *iinfo)
diff --git a/net/rds/ib_recv.c b/net/rds/ib_recv.c
index bd6cb3ffaa571..7d45808544a0d 100644
--- a/net/rds/ib_recv.c
+++ b/net/rds/ib_recv.c
@@ -458,7 +458,11 @@ void rds_ib_recv_refill(struct rds_connection *conn, int prefill, gfp_t gfp)
 	    (must_wake ||
 	    (can_wait && rds_ib_ring_low(&ic->i_recv_ring)) ||
 	    rds_ib_ring_empty(&ic->i_recv_ring))) {
-		queue_delayed_work(conn->c_path->cp_wq, &conn->c_recv_w, 1);
+		rcu_read_lock();
+		if (!rds_destroy_pending(conn))
+			queue_delayed_work(conn->c_path->cp_wq,
+					   &conn->c_recv_w, 1);
+		rcu_read_unlock();
 	}
 	if (can_wait)
 		cond_resched();
diff --git a/net/rds/ib_send.c b/net/rds/ib_send.c
index d6be95542119f..bc411e96ad12d 100644
--- a/net/rds/ib_send.c
+++ b/net/rds/ib_send.c
@@ -298,8 +298,13 @@ void rds_ib_send_cqe_handler(struct rds_ib_connection *ic, struct ib_wc *wc)
 	rds_ib_sub_signaled(ic, nr_sig);
 
 	if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags) ||
-	    test_bit(0, &conn->c_map_queued))
-		queue_delayed_work(conn->c_path->cp_wq, &conn->c_send_w, 0);
+	    test_bit(0, &conn->c_map_queued)) {
+		rcu_read_lock();
+		if (!rds_destroy_pending(conn))
+			queue_delayed_work(conn->c_path->cp_wq,
+					   &conn->c_send_w, 0);
+		rcu_read_unlock();
+	}
 
 	/* We expect errors as the qp is drained during shutdown */
 	if (wc->status != IB_WC_SUCCESS && rds_conn_up(conn)) {
@@ -420,8 +425,13 @@ void rds_ib_send_add_credits(struct rds_connection *conn, unsigned int credits)
 			test_bit(RDS_LL_SEND_FULL, &conn->c_flags) ? ", ll_send_full" : "");
 
 	atomic_add(IB_SET_SEND_CREDITS(credits), &ic->i_credits);
-	if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags))
-		queue_delayed_work(conn->c_path->cp_wq, &conn->c_send_w, 0);
+	if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags)) {
+		rcu_read_lock();
+		if (!rds_destroy_pending(conn))
+			queue_delayed_work(conn->c_path->cp_wq,
+					   &conn->c_send_w, 0);
+		rcu_read_unlock();
+	}
 
 	WARN_ON(IB_GET_SEND_CREDITS(credits) >= 16384);
 
diff --git a/net/rds/loop.c b/net/rds/loop.c
index e6b0750bbedab..5bac858df87ef 100644
--- a/net/rds/loop.c
+++ b/net/rds/loop.c
@@ -156,6 +156,45 @@ static int rds_loop_conn_alloc(struct rds_connection *conn, gfp_t gfp)
 	return 0;
 }
 
+/* Destroy the connections whose nodes were gathered on @tmp_list.
+ *
+ * rds_conn_destroy() can return before the connection is freed, and
+ * it is the free - rds_loop_conn_free() - that unlinks loop_node.
+ * @tmp_list lives on the caller's stack, so unlink each node before
+ * its destroy; the free then finds it empty and leaves it alone.
+ */
+static void rds_loop_destroy_gathered_conns(struct list_head *tmp_list)
+{
+	struct rds_loop_connection *lc, *_lc;
+	struct rds_connection *conn;
+
+	list_for_each_entry_safe(lc, _lc, tmp_list, loop_node) {
+		conn = lc->conn;
+		WARN_ON(rcu_access_pointer(conn->c_passive));
+
+		spin_lock_irq(&loop_conns_lock);
+		list_del_init(&lc->loop_node);
+		spin_unlock_irq(&loop_conns_lock);
+
+		rds_conn_destroy(conn);
+		rds_conn_put(conn);
+	}
+}
+
+/* Gather @lc's connection for destruction: move the node to the
+ * caller's @tmp_list and take a reference that keeps the connection,
+ * and so the node, alive until rds_loop_destroy_gathered_conns() has
+ * dealt with it.  Called with loop_conns_lock held.  A connection
+ * whose free is already running gets no reference; its free unlinks
+ * the node itself, under the same lock, once we drop it.
+ */
+static void rds_loop_gather_conn(struct rds_loop_connection *lc,
+				 struct list_head *tmp_list)
+{
+	if (rds_conn_get_unless_zero(lc->conn))
+		list_move_tail(&lc->loop_node, tmp_list);
+}
+
 static void rds_loop_conn_free(void *arg)
 {
 	struct rds_loop_connection *lc = arg;
@@ -163,7 +202,9 @@ static void rds_loop_conn_free(void *arg)
 
 	rdsdebug("lc %p\n", lc);
 	spin_lock_irqsave(&loop_conns_lock, flags);
-	list_del(&lc->loop_node);
+	/* already unlinked if a transport teardown gathered us first */
+	if (!list_empty(&lc->loop_node))
+		list_del(&lc->loop_node);
 	spin_unlock_irqrestore(&loop_conns_lock, flags);
 	kfree(lc);
 }
@@ -187,14 +228,13 @@ void rds_loop_exit(void)
 	synchronize_rcu();
 	/* avoid calling conn_destroy with irqs off */
 	spin_lock_irq(&loop_conns_lock);
-	list_splice(&loop_conns, &tmp_list);
-	INIT_LIST_HEAD(&loop_conns);
+	list_for_each_entry_safe(lc, _lc, &loop_conns, loop_node)
+		rds_loop_gather_conn(lc, &tmp_list);
 	spin_unlock_irq(&loop_conns_lock);
 
-	list_for_each_entry_safe(lc, _lc, &tmp_list, loop_node) {
-		WARN_ON(lc->conn->c_passive);
-		rds_conn_destroy(lc->conn);
-	}
+	rds_loop_destroy_gathered_conns(&tmp_list);
+
+	rds_conn_wait_conns_freed(&rds_loop_transport, NULL);
 }
 
 static void rds_loop_kill_conns(struct net *net)
@@ -208,14 +248,11 @@ static void rds_loop_kill_conns(struct net *net)
 
 		if (net != c_net)
 			continue;
-		list_move_tail(&lc->loop_node, &tmp_list);
+		rds_loop_gather_conn(lc, &tmp_list);
 	}
 	spin_unlock_irq(&loop_conns_lock);
 
-	list_for_each_entry_safe(lc, _lc, &tmp_list, loop_node) {
-		WARN_ON(lc->conn->c_passive);
-		rds_conn_destroy(lc->conn);
-	}
+	rds_loop_destroy_gathered_conns(&tmp_list);
 }
 
 static void __net_exit rds_loop_exit_net(struct net *net)
diff --git a/net/rds/message.c b/net/rds/message.c
index 47d5e9ab9b109..cea48ad745ca7 100644
--- a/net/rds/message.c
+++ b/net/rds/message.c
@@ -182,6 +182,18 @@ static void rds_message_purge(struct rds_message *rm)
 		kref_put(&rm->atomic.op_rdma_mr->r_kref, __rds_put_mr_final);
 }
 
+static void rds_message_free(struct rds_message *rm)
+{
+	/* get in rds_send_queue_rm(), rds_send_probe() or the congestion
+	 * map path of rds_send_xmit().  Messages that were never queued on
+	 * a connection have no reference to drop.
+	 */
+	if (rm->m_inc.i_conn)
+		rds_conn_put(rm->m_inc.i_conn);
+
+	kfree(rm);
+}
+
 static void rds_message_unpin_worker(struct work_struct *work)
 {
 	struct rds_message *rm = container_of(work, struct rds_message,
@@ -192,7 +204,7 @@ static void rds_message_unpin_worker(struct work_struct *work)
 	if (rm->atomic.op_unpin_deferred)
 		rds_atomic_op_unpin_page(&rm->atomic);
 
-	kfree(rm);
+	rds_message_free(rm);
 }
 
 void rds_message_put(struct rds_message *rm)
@@ -217,7 +229,7 @@ void rds_message_put(struct rds_message *rm)
 			return;
 		}
 
-		kfree(rm);
+		rds_message_free(rm);
 	}
 }
 EXPORT_SYMBOL_GPL(rds_message_put);
diff --git a/net/rds/rdma_transport.c b/net/rds/rdma_transport.c
index 3f853004c4906..a789104725c9a 100644
--- a/net/rds/rdma_transport.c
+++ b/net/rds/rdma_transport.c
@@ -63,6 +63,21 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
 	if (cm_id->device->node_type == RDMA_NODE_IB_CA)
 		trans = &rds_ib_transport;
 
+	/* cm_id->context carries no reference of its own.  Pin the
+	 * connection for the duration of the handler, since the mutex
+	 * released at out: lives in the connection's path array.  None
+	 * of the callbacks below drops a reference on this connection,
+	 * and the shutdown destroys the cm_id - waiting for a running
+	 * handler - before the last reference can go, so this is
+	 * defensive.  A connection already at zero references gets no
+	 * events handled.
+	 */
+	if (conn && !rds_conn_get_unless_zero(conn)) {
+		rdsdebug("conn %p id %p is being freed, ignoring event\n",
+			 conn, cm_id);
+		return 0;
+	}
+
 	/* Prevent shutdown from tearing down the connection
 	 * while we're executing. */
 	if (conn) {
@@ -171,8 +186,10 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
 	}
 
 out:
-	if (conn)
+	if (conn) {
 		mutex_unlock(&conn->c_cm_lock);
+		rds_conn_put(conn);
+	}
 
 	rdsdebug("id %p event %u (%s) handling ret %d\n", cm_id, event->event,
 		 rdma_event_msg(event->event), ret);
diff --git a/net/rds/rds.h b/net/rds/rds.h
index 2db49573dacd5..4c63e5292dd11 100644
--- a/net/rds/rds.h
+++ b/net/rds/rds.h
@@ -89,7 +89,6 @@ enum {
 #define RDS_RECONNECT_PENDING	1
 #define RDS_IN_XMIT		2
 #define RDS_RECV_REFILL		3
-#define	RDS_DESTROY_PENDING	4
 
 /* Max number of multipaths per RDS connection. Must be a power of 2 */
 #define	RDS_MPATH_WORKERS	8
@@ -138,6 +137,12 @@ struct rds_conn_path {
 /* One rds_connection per RDS address pair */
 struct rds_connection {
 	struct hlist_node	c_hash_node;
+	/* rds_conn_destroy() quiesces the connection synchronously;
+	 * freeing it - the connection memory, the path workqueues and
+	 * the transport's per-connection state - is deferred until the
+	 * last reference is dropped via rds_conn_put().
+	 */
+	struct kref		c_refcount;
 	struct in6_addr		c_laddr;
 	struct in6_addr		c_faddr;
 	int			c_dev_if; /* ifindex used for this conn */
@@ -148,7 +153,25 @@ struct rds_connection {
 				c_pad_to_32:29;
 	int			c_npaths;
 	bool			c_with_sport_idx;
-	struct rds_connection	*c_passive;
+	/* Set once, by rds_conn_destroy() under rds_conn_lock - a
+	 * test-and-set, so a second destroy of the same connection
+	 * returns at once - before it cancels the path works.  Read
+	 * through rds_destroy_pending(), which also reports netns
+	 * teardown and module unload; the c_passive handling in
+	 * __rds_conn_create() uses the same predicate, since those rule
+	 * a passive connection out just as well.  A site that arms
+	 * a path work must test the predicate and queue the work inside
+	 * one rcu_read_lock() section: the synchronize_rcu() that
+	 * follows the store is what keeps a queue issued after the
+	 * cancellation from landing on a destroyed workqueue.  Two kinds
+	 * of site are exempt: the workers' own self-requeues, which the
+	 * sync cancel in the destroy path rejects, and the destroy == true
+	 * rds_conn_path_drop(): the destroy issues and flushes it itself,
+	 * and IB device removal issues it ahead of the module exit, which
+	 * destroys - and so flushes - that connection afterwards.
+	 */
+	bool			c_destroy_in_prog;
+	struct rds_connection __rcu *c_passive;
 	struct rds_transport	*c_trans;
 
 	struct rds_cong_map	*c_lcong;
@@ -544,6 +567,12 @@ struct rds_transport {
 	unsigned int		t_prefer_loopback:1,
 				t_mp_capable:1;
 	unsigned int		t_type;
+	/* Connections of this transport not yet freed; freeing runs
+	 * asynchronously once rds_conn_destroy() has quiesced a
+	 * connection, so transport module unload has to wait for this
+	 * to reach zero (rds_conn_wait_conns_freed()).
+	 */
+	atomic_t		t_conn_count;
 
 	int (*laddr_check)(struct net *net, const struct in6_addr *addr,
 			   __u32 scope_id);
@@ -650,7 +679,12 @@ struct rds_sock {
 
 	/*
 	 * rds_sendmsg caches the conn it used the last time around.
-	 * This helps avoid costly lookups.
+	 * This helps avoid costly lookups.  The cache owns a connection
+	 * reference, dropped when it is replaced, when rds_sendmsg()
+	 * evicts a connection whose destroy has begun, or when the
+	 * socket is released, and is read and written under rs_lock -
+	 * except by
+	 * rds_release(), which runs once no one else can reach the socket.
 	 */
 	struct rds_connection	*rs_conn;
 
@@ -659,7 +693,11 @@ struct rds_sock {
 	/* seen congestion (ENOBUFS) when sending? */
 	int			rs_seen_congestion;
 
-	/* rs_lock protects all these adjacent members before the newline */
+	/* rs_lock protects all these adjacent members before the newline,
+	 * as well as rs_conn above and rs_tos at the end of the struct -
+	 * except that rds_sendmsg() samples rs_tos locklessly, with
+	 * READ_ONCE(), for the create, and re-checks it under the lock.
+	 */
 	spinlock_t		rs_lock;
 	struct list_head	rs_send_queue;
 	u32			rs_snd_bytes;
@@ -819,6 +857,21 @@ struct rds_connection *rds_conn_create_outgoing(struct net *net,
 						u8 tos, gfp_t gfp, int dev_if);
 void rds_conn_shutdown(struct rds_conn_path *cpath);
 void rds_conn_destroy(struct rds_connection *conn);
+void rds_conn_get(struct rds_connection *conn);
+void rds_conn_put(struct rds_connection *conn);
+/* take a reference unless the connection is already being freed */
+static inline bool rds_conn_get_unless_zero(struct rds_connection *conn)
+{
+	return kref_get_unless_zero(&conn->c_refcount);
+}
+
+/* transport unload waits for its connections to be freed, polling at
+ * the first interval and warning at the second
+ */
+#define RDS_CONN_FREE_POLL_MS		100
+#define RDS_CONN_FREE_WARN_INTERVAL_MS	10000
+void rds_conn_wait_conns_freed(struct rds_transport *trans,
+			       void (*resweep)(void));
 void rds_conn_drop(struct rds_connection *conn);
 void rds_conn_path_drop(struct rds_conn_path *cpath, bool destroy);
 void rds_conn_connect_if_down(struct rds_connection *conn);
@@ -994,7 +1047,8 @@ void __rds_put_mr_final(struct kref *kref);
 
 static inline bool rds_destroy_pending(struct rds_connection *conn)
 {
-	return !check_net(rds_conn_net(conn)) ||
+	return READ_ONCE(conn->c_destroy_in_prog) ||
+	       !check_net(rds_conn_net(conn)) ||
 	       (conn->c_trans->t_unloading && conn->c_trans->t_unloading(conn));
 }
 
diff --git a/net/rds/recv.c b/net/rds/recv.c
index 6204e577a90ae..9e7e55ca7bd2b 100644
--- a/net/rds/recv.c
+++ b/net/rds/recv.c
@@ -46,6 +46,7 @@ void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn,
 {
 	refcount_set(&inc->i_refcount, 1);
 	INIT_LIST_HEAD(&inc->i_item);
+	rds_conn_get(conn);	/* put in rds_inc_put() */
 	inc->i_conn = conn;
 	inc->i_conn_path = NULL;
 	inc->i_saddr = *saddr;
@@ -61,6 +62,7 @@ void rds_inc_path_init(struct rds_incoming *inc, struct rds_conn_path *cp,
 {
 	refcount_set(&inc->i_refcount, 1);
 	INIT_LIST_HEAD(&inc->i_item);
+	rds_conn_get(cp->cp_conn);	/* put in rds_inc_put() */
 	inc->i_conn = cp->cp_conn;
 	inc->i_conn_path = cp;
 	inc->i_saddr = *saddr;
@@ -81,9 +83,19 @@ void rds_inc_put(struct rds_incoming *inc)
 {
 	rdsdebug("put inc %p ref %d\n", inc, refcount_read(&inc->i_refcount));
 	if (refcount_dec_and_test(&inc->i_refcount)) {
+		struct rds_connection *conn = inc->i_conn;
+
 		BUG_ON(!list_empty(&inc->i_item));
 
-		inc->i_conn->c_trans->inc_free(inc);
+		/* inc_free() can free the memory @inc lives in, so the
+		 * connection reference has to be dropped through the
+		 * copy taken above.
+		 */
+		conn->c_trans->inc_free(inc);
+		/* get in rds_inc_init(), rds_inc_path_init() or
+		 * rds_recv_incoming()
+		 */
+		rds_conn_put(conn);
 	}
 }
 EXPORT_SYMBOL_GPL(rds_inc_put);
@@ -325,6 +337,13 @@ void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,
 	unsigned long flags;
 	struct rds_conn_path *cp;
 
+	/* every caller initialized @inc with rds_inc_init() or
+	 * rds_inc_path_init() first, so i_conn already holds a reference.
+	 * Take the new one before dropping the old, so that re-pointing an
+	 * inc at the connection it already refers to cannot free it.
+	 */
+	rds_conn_get(conn);
+	rds_conn_put(inc->i_conn);
 	inc->i_conn = conn;
 	inc->i_rx_jiffies = jiffies;
 	if (conn->c_trans->t_mp_capable)
@@ -406,8 +425,9 @@ void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,
 	 * rds_find_bound() uses a global (netns-agnostic) hash table.
 	 * An RDS connection created in netns A can match a socket bound
 	 * in the init netns, delivering inc cross-netns with inc->i_conn
-	 * pointing into netns A.  When cleanup_net() then frees that conn,
-	 * any subsequent dereference of inc->i_conn is a use-after-free.
+	 * pointing into netns A.  Cross-netns delivery is wrong on its
+	 * own, and the inc's connection reference would keep a
+	 * connection of a dead netns around, with a stale c_net.
 	 * Drop the inc if the receiving socket lives in a different netns.
 	 */
 	if (!net_eq(sock_net(rds_rs_to_sk(rs)), rds_conn_net(conn))) {
@@ -482,7 +502,6 @@ static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc,
 	if (!list_empty(&inc->i_item)) {
 		ret = 1;
 		if (drop) {
-			/* XXX make sure this i_conn is reliable */
 			rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
 					      -be32_to_cpu(inc->i_hdr.h_len),
 					      inc->i_hdr.h_dport);
diff --git a/net/rds/send.c b/net/rds/send.c
index 1afa981e5c06d..4ec9931599c5d 100644
--- a/net/rds/send.c
+++ b/net/rds/send.c
@@ -290,6 +290,8 @@ int rds_send_xmit(struct rds_conn_path *cp)
 			}
 			rm->data.op_active = 1;
 			rm->m_inc.i_conn_path = cp;
+			/* put in rds_message_put() */
+			rds_conn_get(cp->cp_conn);
 			rm->m_inc.i_conn = cp->cp_conn;
 
 			cp->cp_xmit_rm = rm;
@@ -947,6 +949,7 @@ static int rds_send_queue_rm(struct rds_sock *rs, struct rds_connection *conn,
 		/* The code ordering is a little weird, but we're
 		   trying to minimize the time we hold c_lock */
 		rds_message_populate_header(&rm->m_inc.i_hdr, sport, dport, 0);
+		rds_conn_get(conn);	/* put in rds_message_put() */
 		rm->m_inc.i_conn = conn;
 		rm->m_inc.i_conn_path = cp;
 		rds_message_addref(rm);
@@ -1159,13 +1162,14 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
 	__be16 dport;
 	struct rds_message *rm = NULL;
-	struct rds_connection *conn;
+	struct rds_connection *conn = NULL;
 	int ret = 0;
 	int queued = 0, allocated_mr = 0;
 	int nonblock = msg->msg_flags & MSG_DONTWAIT;
 	long timeo = sock_sndtimeo(sk, nonblock);
 	struct rds_conn_path *cpath;
 	struct in6_addr daddr;
+	unsigned long flags;
 	__u32 scope_id = 0;
 	size_t rdma_payload_len = 0;
 	bool zcopy = ((msg->msg_flags & MSG_ZEROCOPY) &&
@@ -1340,21 +1344,68 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 	rm->m_daddr = daddr;
 
 	/* rds_conn_create has a spinlock that runs with IRQ off.
-	 * Caching the conn in the socket helps a lot. */
-	if (rs->rs_conn && ipv6_addr_equal(&rs->rs_conn->c_faddr, &daddr) &&
-	    rs->rs_tos == rs->rs_conn->c_tos) {
-		conn = rs->rs_conn;
+	 * Caching the conn in the socket helps a lot.
+	 *
+	 * The cached rs_conn holds a connection reference; take one of
+	 * our own for the duration of this call (dropped on both exit
+	 * paths), so that neither a concurrent sender replacing the
+	 * cache nor rds_conn_destroy() can free the connection under
+	 * us.  A cached connection whose destruction has begun is not
+	 * reused: it is evicted here, and this call goes on to look up
+	 * or create a live one instead of returning -EAGAIN forever.
+	 */
+	spin_lock_irqsave(&rs->rs_lock, flags);
+	conn = rs->rs_conn;
+	if (conn && rds_destroy_pending(conn)) {
+		/* drop the cache's reference right here, or the socket
+		 * would pin the quiesced connection until it is closed
+		 */
+		rs->rs_conn = NULL;
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
+		rds_conn_put(conn);
+		conn = NULL;
 	} else {
+		if (conn && ipv6_addr_equal(&conn->c_faddr, &daddr) &&
+		    rs->rs_tos == conn->c_tos)
+			rds_conn_get(conn);
+		else
+			conn = NULL;
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
+	}
+
+	if (!conn) {
+		struct rds_connection *old;
+
 		conn = rds_conn_create_outgoing(sock_net(sock->sk),
 						&rs->rs_bound_addr, &daddr,
-						rs->rs_transport, rs->rs_tos,
+						rs->rs_transport,
+						READ_ONCE(rs->rs_tos),
 						sock->sk->sk_allocation,
 						scope_id);
 		if (IS_ERR(conn)) {
 			ret = PTR_ERR(conn);
+			conn = NULL;
 			goto out;
 		}
+		/* rs_tos was sampled without rs_lock for the create above,
+		 * and SIOCRDSSETTOS only refuses a change once rs_conn is
+		 * set, so it can have changed underneath us.  Do not
+		 * install - or send on - a connection whose ToS no longer
+		 * matches the socket's; the retry uses the new one.
+		 */
+		spin_lock_irqsave(&rs->rs_lock, flags);
+		if (conn->c_tos != rs->rs_tos) {
+			spin_unlock_irqrestore(&rs->rs_lock, flags);
+			ret = -EAGAIN;
+			goto out;
+		}
+		/* hand the cache its own reference */
+		rds_conn_get(conn);
+		old = rs->rs_conn;
 		rs->rs_conn = conn;
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
+		if (old)
+			rds_conn_put(old);
 	}
 
 	if (conn->c_trans->t_mp_capable) {
@@ -1378,9 +1429,14 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		 * outstanding.
 		 */
 		if (!test_and_set_bit(RDS_RECONNECT_PENDING,
-				      &conn->c_path[0].cp_flags))
-			queue_delayed_work(conn->c_path[0].cp_wq,
-					   &conn->c_path[0].cp_conn_w, 0);
+				      &conn->c_path[0].cp_flags)) {
+			rcu_read_lock();
+			if (!rds_destroy_pending(conn))
+				queue_delayed_work(conn->c_path[0].cp_wq,
+						   &conn->c_path[0].cp_conn_w,
+						   0);
+			rcu_read_unlock();
+		}
 		rds_send_ping(conn, 0);
 	}
 
@@ -1469,6 +1525,8 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		kfree(vct.vec[ind].iov);
 	kfree(vct.vec);
 
+	rds_conn_put(conn);
+
 	return payload_len;
 
 out:
@@ -1476,6 +1534,9 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		kfree(vct.vec[ind].iov);
 	kfree(vct.vec);
 
+	if (conn)
+		rds_conn_put(conn);
+
 	/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.
 	 * If the sendmsg goes through, we keep the MR. If it fails with EAGAIN
 	 * or in any other way, we need to destroy the MR again */
@@ -1522,6 +1583,7 @@ rds_send_probe(struct rds_conn_path *cp, __be16 sport,
 	list_add_tail(&rm->m_conn_item, &cp->cp_send_queue);
 	set_bit(RDS_MSG_ON_CONN, &rm->m_flags);
 	rds_message_addref(rm);
+	rds_conn_get(cp->cp_conn);	/* put in rds_message_put() */
 	rm->m_inc.i_conn = cp->cp_conn;
 	rm->m_inc.i_conn_path = cp;
 
diff --git a/net/rds/tcp.c b/net/rds/tcp.c
index 774a71f88d375..552b32278e30d 100644
--- a/net/rds/tcp.c
+++ b/net/rds/tcp.c
@@ -502,6 +502,48 @@ static bool rds_tcp_is_unloading(struct rds_connection *conn)
 	return atomic_read(&rds_tcp_unloading) != 0;
 }
 
+/* Gather @tc's connection for destruction: move the node to the
+ * caller's @tmp_list and take a reference that keeps the connection,
+ * and so the node, alive until rds_tcp_destroy_gathered_conns() has
+ * dealt with it.  Called with rds_tcp_conn_lock held.  A connection
+ * whose free is already running gets no reference; its free unlinks
+ * the node itself, under the same lock, once we drop it.
+ */
+static void rds_tcp_gather_conn(struct rds_tcp_connection *tc,
+				struct list_head *tmp_list)
+{
+	if (rds_conn_get_unless_zero(tc->t_cpath->cp_conn))
+		list_move_tail(&tc->t_tcp_node, tmp_list);
+}
+
+/* Destroy the connections whose nodes were gathered on @tmp_list.
+ *
+ * rds_conn_destroy() can return before the connection is freed, and
+ * it is the free - rds_tcp_conn_free() - that unlinks t_tcp_node.
+ * Since @tmp_list lives on the caller's stack, unlink each node here
+ * and mark it detached before its destroy, so that a free that runs
+ * after the caller has returned does not write into a dead frame.
+ * Every entry holds a reference taken by rds_tcp_gather_conn(), so
+ * none can be freed under the walk; each is dropped after its destroy.
+ */
+static void rds_tcp_destroy_gathered_conns(struct list_head *tmp_list)
+{
+	struct rds_tcp_connection *tc, *_tc;
+	struct rds_connection *conn;
+
+	list_for_each_entry_safe(tc, _tc, tmp_list, t_tcp_node) {
+		conn = tc->t_cpath->cp_conn;
+
+		spin_lock_irq(&rds_tcp_conn_lock);
+		list_del_init(&tc->t_tcp_node);
+		tc->t_tcp_node_detached = true;
+		spin_unlock_irq(&rds_tcp_conn_lock);
+
+		rds_conn_destroy(conn);
+		rds_conn_put(conn);
+	}
+}
+
 static void rds_tcp_destroy_conns(void)
 {
 	struct rds_tcp_connection *tc, *_tc;
@@ -511,12 +553,11 @@ static void rds_tcp_destroy_conns(void)
 	spin_lock_irq(&rds_tcp_conn_lock);
 	list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
 		if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn))
-			list_move_tail(&tc->t_tcp_node, &tmp_list);
+			rds_tcp_gather_conn(tc, &tmp_list);
 	}
 	spin_unlock_irq(&rds_tcp_conn_lock);
 
-	list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
-		rds_conn_destroy(tc->t_cpath->cp_conn);
+	rds_tcp_destroy_gathered_conns(&tmp_list);
 }
 
 static void rds_tcp_exit(void);
@@ -691,15 +732,14 @@ static void rds_tcp_kill_sock(struct net *net)
 		if (net != c_net)
 			continue;
 		if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
-			list_move_tail(&tc->t_tcp_node, &tmp_list);
+			rds_tcp_gather_conn(tc, &tmp_list);
 		} else {
 			list_del(&tc->t_tcp_node);
 			tc->t_tcp_node_detached = true;
 		}
 	}
 	spin_unlock_irq(&rds_tcp_conn_lock);
-	list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
-		rds_conn_destroy(tc->t_cpath->cp_conn);
+	rds_tcp_destroy_gathered_conns(&tmp_list);
 }
 
 static void __net_exit rds_tcp_exit_net(struct net *net)
@@ -805,6 +845,7 @@ static void rds_tcp_exit(void)
 #endif
 	unregister_pernet_device(&rds_tcp_net_ops);
 	rds_tcp_destroy_conns();
+	rds_conn_wait_conns_freed(&rds_tcp_transport, NULL);
 	rds_trans_unregister(&rds_tcp_transport);
 	rds_tcp_recv_exit();
 	kmem_cache_destroy(rds_tcp_conn_slab);
diff --git a/net/rds/tcp_listen.c b/net/rds/tcp_listen.c
index 13fa60c1985bb..bb4f01c071693 100644
--- a/net/rds/tcp_listen.c
+++ b/net/rds/tcp_listen.c
@@ -153,7 +153,7 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 {
 	struct socket *listen_sock = rtn->rds_tcp_listen_sock;
 	struct socket *new_sock = NULL;
-	struct rds_connection *conn;
+	struct rds_connection *conn = NULL;
 	int ret;
 	struct inet_sock *inet;
 	struct rds_tcp_connection *rs_tcp = NULL;
@@ -229,6 +229,7 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 
 	if (IS_ERR(conn)) {
 		ret = PTR_ERR(conn);
+		conn = NULL;
 		goto out;
 	}
 	/* An incoming SYN request came in, and TCP just accepted it.
@@ -277,6 +278,13 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 	cp = rs_tcp->t_cpath;
 	conn_state = rds_conn_path_state(cp);
 	WARN_ON(conn_state == RDS_CONN_UP);
+	/* A connection whose destroy has begun cannot be found here:
+	 * TCP connections are only destroyed on netns teardown and on
+	 * module unload, and both go through rds_tcp_kill_sock() - which
+	 * clears the listen socket that the top of this function tests
+	 * and then flushes this work in rds_tcp_listen_stop() - before
+	 * any connection is destroyed.
+	 */
 	if (conn_state != RDS_CONN_CONNECTING && conn_state != RDS_CONN_ERROR) {
 		rds_conn_path_drop(cp, 0);
 		goto rst_nsk;
@@ -316,10 +324,14 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 	 */
 	if (READ_ONCE(sk->sk_state) == TCP_CLOSE_WAIT ||
 	    READ_ONCE(sk->sk_state) == TCP_LAST_ACK ||
-	    READ_ONCE(sk->sk_state) == TCP_CLOSE)
+	    READ_ONCE(sk->sk_state) == TCP_CLOSE) {
 		rds_conn_path_drop(cp, 0);
-	else
-		queue_delayed_work(cp->cp_wq, &cp->cp_recv_w, 0);
+	} else {
+		rcu_read_lock();
+		if (!rds_destroy_pending(cp->cp_conn))
+			queue_delayed_work(cp->cp_wq, &cp->cp_recv_w, 0);
+		rcu_read_unlock();
+	}
 
 	sock_put(sk);
 
@@ -343,6 +355,8 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 		mutex_unlock(&rs_tcp->t_conn_path_lock);
 	if (new_sock)
 		sock_release(new_sock);
+	if (conn)
+		rds_conn_put(conn);
 
 	mutex_unlock(&rtn->rds_tcp_accept_lock);
 

3/2 2026/10/08 03:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25980
							output: 26
							thoughts: 399
						

Thoughts:
**Analyzing the RDS Patch for Fuzzing Potential**

Okay, let's dive into this patch and assess its fuzzing potential. My initial thought is to figure out whether it warrants a deep dive into fuzzing, and if so, understand the underlying configurations and pinpoint the critical symbols to focus on.

First, I see the patch touches a comprehensive set of files within the `net/rds/` directory. That's a strong indication this is a significant area: `af_rds.c`, `connection.c`, `ib.c`, `ib.h`, `ib_cm.c`, `ib_rdma.c`, `ib_recv.c`, `ib_send.c`, `loop.c`, `message.c`, `rdma_transport.c`, `rds.h`, `recv.c`, `send.c`, `tcp.c`, and `tcp_listen.c`. So, we're looking at core RDS functionality.

Now, a quick refresher on RDS – Reliable Datagram Sockets. From my experience, I know it's a Linux networking protocol (`AF_RDS` / `PF_RDS`) that's been heavily scrutinized by tools like syzkaller. I'm aware that it's accessible via standard socket syscalls, which immediately makes it a prime candidate for fuzzing. Given the prevalence of RDS in the fuzzing landscape, I'd expect that standard QEMU/syzkaller setups should be able to create sockets, use `sendmsg`, `recvmsg`, `setsockopt`, `ioctl`, etc. Loopback and TCP should work fine without any hardware requirements, which is a big win.

My next step is to nail down the Kconfig requirements for RDS. I'll either use `grepper` or check the `net/rds/Kconfig` file directly to confirm what's enabled. This is crucial for determining the build environment and potential dependencies. I'll need to know the specific configurations to ensure my fuzzing setup is correctly tailored.



4/2 2026/10/08 03:38 tool grepper
0m Args:
{
  "Expression": "config RDS",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/Kconfig-2-\nnet/rds/Kconfig:3:config RDS\nnet/rds/Kconfig-4-\ttristate \"The Reliable Datagram Sockets Protocol\"\n--\nnet/rds/Kconfig-9-\nnet/rds/Kconfig:10:config RDS_RDMA\nnet/rds/Kconfig-11-\ttristate \"RDS over Infiniband\"\n--\nnet/rds/Kconfig-16-\nnet/rds/Kconfig:17:config RDS_TCP\nnet/rds/Kconfig-18-\ttristate \"RDS over TCP\"\n--\nnet/rds/Kconfig-24-\nnet/rds/Kconfig:25:config RDS_DEBUG\nnet/rds/Kconfig-26-\tbool \"RDS debugging messages\"\n"
}

5/2 2026/10/08 03:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27034
							output: 32
							thoughts: 20
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into `net/rds/Kconfig`**

Okay, I need to get a handle on the configuration options for the Remote Direct Memory Access (RDMA) over Reliable Datagram Sockets (RDS) network protocol. Let's start by looking at `net/rds/Kconfig`, specifically lines 1 through 30. This should give me a high-level view of what's configurable, and how the various features and dependencies are structured within this module. Hopefully, it defines the core RDS options and any accompanying dependencies or relationships. I’m expecting to see things like whether the driver itself is included, and related settings around kernel features. Essentially, I need to understand what variables can be changed by the person that is configuring the kernel.



6/2 2026/10/08 03:38 tool read-file
0m Args:
{
  "File": "net/rds/Kconfig",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\t\n   3:\tconfig RDS\n   4:\t\ttristate \"The Reliable Datagram Sockets Protocol\"\n   5:\t\tdepends on INET\n   6:\t\thelp\n   7:\t\t  The RDS (Reliable Datagram Sockets) protocol provides reliable,\n   8:\t\t  sequenced delivery of datagrams over Infiniband or TCP.\n   9:\t\n  10:\tconfig RDS_RDMA\n  11:\t\ttristate \"RDS over Infiniband\"\n  12:\t\tdepends on RDS \u0026\u0026 INFINIBAND \u0026\u0026 INFINIBAND_ADDR_TRANS\n  13:\t\thelp\n  14:\t\t  Allow RDS to use Infiniband as a transport.\n  15:\t\t  This transport supports RDMA operations.\n  16:\t\n  17:\tconfig RDS_TCP\n  18:\t\ttristate \"RDS over TCP\"\n  19:\t\tdepends on RDS\n  20:\t\tdepends on IPV6 || !IPV6\n  21:\t\thelp\n  22:\t\t  Allow RDS to use TCP as a transport.\n  23:\t\t  This transport does not support RDMA operations.\n  24:\t\n  25:\tconfig RDS_DEBUG\n  26:\t\tbool \"RDS debugging messages\"\n  27:\t\tdepends on RDS\n  28:\t\tdefault n\n  29:\t\n  30:\tconfig GCOV_PROFILE_RDS\n  31:\t\tbool \"Enable GCOV profiling on RDS\"\n  32:\t\tdepends on GCOV_KERNEL\n  33:\t\thelp\n  34:\t\t  Enable GCOV profiling on RDS for checking which functions/lines\n  35:\t\t  are executed.\n  36:\t\n  37:\t\t  If unsure, say N.\n"
}

7/2 2026/10/08 03:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27709
							output: 31
							thoughts: 12
						

Thoughts:
Here's my analysis of the provided text, rendered as though I'm thinking it:

**Diving into the net/rds Makefile**

Alright, let's get down to brass tacks and dissect this `Makefile` within the `net/rds` directory. I want to understand the build process and dependencies for this particular network subsystem. My initial goal is to identify any potential areas for optimization, or maybe even spot some interesting new features that I might have missed in previous reviews. I'm especially keen to see how they handle module compilation, linking, and any custom build flags they are employing. I'm also going to check for any unusual or inefficient build steps; maybe I can suggest an improvement or two, or at least gain some insight into their design choices. I'm anticipating that I might discover interesting macros or configuration options that could provide valuable insight into the intricacies of this Remote Direct Memory Access (RDMA) over TCP/IP implementation.



8/2 2026/10/08 03:38 tool read-file
0m Args:
{
  "File": "net/rds/Makefile",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0\n   2:\tobj-$(CONFIG_RDS) += rds.o\n   3:\trds-y :=\taf_rds.o bind.o cong.o connection.o info.o message.o   \\\n   4:\t\t\t\trecv.o send.o stats.o sysctl.o threads.o transport.o \\\n   5:\t\t\t\tloop.o page.o rdma.o\n   6:\t\n   7:\tobj-$(CONFIG_RDS_RDMA) += rds_rdma.o\n   8:\trds_rdma-y :=\trdma_transport.o \\\n   9:\t\t\t\tib.o ib_cm.o ib_recv.o ib_ring.o ib_send.o ib_stats.o \\\n  10:\t\t\t\tib_sysctl.o ib_rdma.o ib_frmr.o\n  11:\t\n  12:\t\n  13:\tobj-$(CONFIG_RDS_TCP) += rds_tcp.o\n  14:\trds_tcp-y :=\t\ttcp.o tcp_connect.o tcp_listen.o tcp_recv.o \\\n  15:\t\t\t\ttcp_send.o tcp_stats.o\n  16:\t\n  17:\tccflags-$(CONFIG_RDS_DEBUG)\t:=\t-DRDS_DEBUG\n  18:\t\n  19:\t# for GCOV coverage profiling\n  20:\tifdef CONFIG_GCOV_PROFILE_RDS\n  21:\tGCOV_PROFILE := y\n  22:\tendif\n"
}

9/2 2026/10/08 03:38 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28342
							output: 31
							thoughts: 1504
						

Thoughts:
**Patch Analysis and Fuzzing Prioritization: RDS Connection Lifecycle Refactoring**

Alright, let's break this down. This patch is touching a *lot* of core RDS code: `af_rds.c`, `connection.c`, `loop.c`, `message.c`, `recv.c`, `send.c`. It's also getting into RDMA and TCP transport specifics with `ib.c`, `ib_cm.c`, `ib_rdma.c`, `ib_recv.c`, `ib_send.c`, `rdma_transport.c`, `tcp.c`, and `tcp_listen.c`. Crucially, these components are all built with `CONFIG_RDS`, and in the case of the RDMA and TCP elements `CONFIG_RDS_RDMA` and `CONFIG_RDS_TCP` respectively.

My initial thought is to make sure we understand the CONFIG dependencies. RDS depends on INET, which is usually not a problem. RDS_TCP depends on RDS, and RDS_RDMA needs RDS, INFINIBAND, and INFINIBAND_ADDR_TRANS. I'm noting that RDS and RDS_TCP are perfectly happy to run in a standard QEMU / syzkaller environment, that AF_RDS sockets can be opened without special permissions, and syzkaller *does* extensively fuzz RDS already, which means it's definitely reachable. RDMA, I can run with Soft-RoCE.

Now, looking at the patch itself, this is a *massive* overhaul of how RDS connections are managed. We're talking about a complete refactoring of the connection lifecycle: refcounting, deferred cleanup, and locking across various functions and data structures. It's touching `struct rds_connection` and related objects across the entire RDS codebase!

Specifically, it's adding refcounting with `kref_init`, `rds_conn_get`, and `rds_conn_put`. It's deferring memory cleanup with `rds_conn_destroy_fini`. There are updates to socket release, ioctl handling, `rds_conn_lookup()`, connection creation, path destruction, message freeing, receive, send, loop, and TCP connection management. Everything from refcounting and locking to workqueue handling and message lifecycles has been modified.

Given my experience, this immediately screams potential for race conditions. This is ripe with the possibility of use-after-free errors, memory leaks, assertion failures, and deadlocks. I'd be willing to bet this patch introduces tricky issues.

Okay, let's confirm the `WorthFuzzing=true` decision. This touches memory management, synchronization/locking, and core networking, and it is a substantial restructuring of data structures and algorithm flows. It definitely meets the criteria, especially the "restructuring of reachable data structures" component. This is absolutely `WorthFuzzing=true`.

Now, let's double-check those CONFIG dependencies. We have:
`config RDS`
`depends on INET`
`config RDS_TCP`
`depends on RDS`
`config RDS_RDMA`
`depends on RDS && INFINIBAND && INFINIBAND_ADDR_TRANS`

We need to make sure INET is enabled. Also, let's be sure to examine `INFINIBAND` and `INFINIBAND_ADDR_TRANS` to confirm their current implementations.



10/2 2026/10/08 03:40 tool grepper
0m Args:
{
  "Expression": "config INFINIBAND",
  "PathPrefixes": [
    "drivers/infiniband"
  ]
}

Results:
{
  "Output": "drivers/infiniband/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/Kconfig:2:menuconfig INFINIBAND\ndrivers/infiniband/Kconfig-3-\ttristate \"InfiniBand support\"\n--\ndrivers/infiniband/Kconfig=16=if INFINIBAND\ndrivers/infiniband/Kconfig-17-\ndrivers/infiniband/Kconfig:18:config INFINIBAND_USER_MAD\ndrivers/infiniband/Kconfig-19-\ttristate \"InfiniBand userspace MAD support\"\n--\ndrivers/infiniband/Kconfig-27-\ndrivers/infiniband/Kconfig:28:config INFINIBAND_USER_ACCESS\ndrivers/infiniband/Kconfig-29-\ttristate \"InfiniBand userspace access (verbs and CM)\"\n--\ndrivers/infiniband/Kconfig-39-\ndrivers/infiniband/Kconfig:40:config INFINIBAND_USER_ACCESS_CORE\ndrivers/infiniband/Kconfig-41-\tbool\n--\ndrivers/infiniband/Kconfig-43-\ndrivers/infiniband/Kconfig:44:config INFINIBAND_USER_MEM\ndrivers/infiniband/Kconfig-45-\tbool\n--\ndrivers/infiniband/Kconfig-50-\ndrivers/infiniband/Kconfig:51:config INFINIBAND_ON_DEMAND_PAGING\ndrivers/infiniband/Kconfig-52-\tbool \"InfiniBand on-demand paging support\"\n--\ndrivers/infiniband/Kconfig-63-\ndrivers/infiniband/Kconfig:64:config INFINIBAND_ADDR_TRANS\ndrivers/infiniband/Kconfig-65-\tbool \"RDMA/CM\"\n--\ndrivers/infiniband/Kconfig-71-\ndrivers/infiniband/Kconfig:72:config INFINIBAND_ADDR_TRANS_CONFIGFS\ndrivers/infiniband/Kconfig-73-\tbool\n--\ndrivers/infiniband/Kconfig-80-\ndrivers/infiniband/Kconfig:81:config INFINIBAND_VIRT_DMA\ndrivers/infiniband/Kconfig-82-\tdef_bool !HIGHMEM\n--\ndrivers/infiniband/hw/bng_re/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/bng_re/Kconfig:2:config INFINIBAND_BNG_RE\ndrivers/infiniband/hw/bng_re/Kconfig-3-\ttristate \"Broadcom Next generation RoCE HCA support\"\n--\ndrivers/infiniband/hw/bnxt_re/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/bnxt_re/Kconfig:2:config INFINIBAND_BNXT_RE\ndrivers/infiniband/hw/bnxt_re/Kconfig-3-\ttristate \"Broadcom Netxtreme HCA support\"\n--\ndrivers/infiniband/hw/cxgb4/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/cxgb4/Kconfig:2:config INFINIBAND_CXGB4\ndrivers/infiniband/hw/cxgb4/Kconfig-3-\ttristate \"Chelsio T4/T5 RDMA Driver\"\n--\ndrivers/infiniband/hw/efa/Kconfig-6-\ndrivers/infiniband/hw/efa/Kconfig:7:config INFINIBAND_EFA\ndrivers/infiniband/hw/efa/Kconfig-8-\ttristate \"Amazon Elastic Fabric Adapter (EFA) support\"\n--\ndrivers/infiniband/hw/erdma/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/erdma/Kconfig:2:config INFINIBAND_ERDMA\ndrivers/infiniband/hw/erdma/Kconfig-3-\ttristate \"Alibaba Elastic RDMA Adapter (ERDMA) support\"\n--\ndrivers/infiniband/hw/hfi1/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/hfi1/Kconfig:2:config INFINIBAND_HFI1\ndrivers/infiniband/hw/hfi1/Kconfig-3-\ttristate \"Cornelis OPX Gen1 support\"\n--\ndrivers/infiniband/hw/hns/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/hns/Kconfig:2:config INFINIBAND_HNS_HIP08\ndrivers/infiniband/hw/hns/Kconfig-3-\ttristate \"Hisilicon Hip08 Family RoCE support\"\n--\ndrivers/infiniband/hw/ionic/Kconfig-3-\ndrivers/infiniband/hw/ionic/Kconfig:4:config INFINIBAND_IONIC\ndrivers/infiniband/hw/ionic/Kconfig-5-\ttristate \"AMD Pensando DSC RDMA/RoCE Support\"\n--\ndrivers/infiniband/hw/irdma/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/irdma/Kconfig:2:config INFINIBAND_IRDMA\ndrivers/infiniband/hw/irdma/Kconfig-3-\ttristate \"Intel(R) Ethernet Protocol Driver for RDMA\"\n--\ndrivers/infiniband/hw/mthca/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/mthca/Kconfig:2:config INFINIBAND_MTHCA\ndrivers/infiniband/hw/mthca/Kconfig-3-\ttristate \"Mellanox HCA support\"\n--\ndrivers/infiniband/hw/mthca/Kconfig-9-\ndrivers/infiniband/hw/mthca/Kconfig:10:config INFINIBAND_MTHCA_DEBUG\ndrivers/infiniband/hw/mthca/Kconfig-11-\tbool \"Verbose debugging output\" if EXPERT\n--\ndrivers/infiniband/hw/ocrdma/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/ocrdma/Kconfig:2:config INFINIBAND_OCRDMA\ndrivers/infiniband/hw/ocrdma/Kconfig-3-\ttristate \"Emulex One Connect HCA support\"\n--\ndrivers/infiniband/hw/qedr/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/qedr/Kconfig:2:config INFINIBAND_QEDR\ndrivers/infiniband/hw/qedr/Kconfig-3-\ttristate \"QLogic RoCE driver\"\n--\ndrivers/infiniband/hw/usnic/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/usnic/Kconfig:2:config INFINIBAND_USNIC\ndrivers/infiniband/hw/usnic/Kconfig-3-\ttristate \"Verbs support for Cisco VIC\"\n--\ndrivers/infiniband/hw/vmw_pvrdma/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/hw/vmw_pvrdma/Kconfig:2:config INFINIBAND_VMWARE_PVRDMA\ndrivers/infiniband/hw/vmw_pvrdma/Kconfig-3-\ttristate \"VMware Paravirtualized RDMA Driver\"\n--\ndrivers/infiniband/sw/rdmavt/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/sw/rdmavt/Kconfig:2:config INFINIBAND_RDMAVT\ndrivers/infiniband/sw/rdmavt/Kconfig-3-\ttristate \"RDMA verbs transport library\"\n--\ndrivers/infiniband/ulp/ipoib/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/ulp/ipoib/Kconfig:2:config INFINIBAND_IPOIB\ndrivers/infiniband/ulp/ipoib/Kconfig-3-\ttristate \"IP-over-InfiniBand\"\n--\ndrivers/infiniband/ulp/ipoib/Kconfig-11-\ndrivers/infiniband/ulp/ipoib/Kconfig:12:config INFINIBAND_IPOIB_CM\ndrivers/infiniband/ulp/ipoib/Kconfig-13-\tbool \"IP-over-InfiniBand Connected Mode support\"\n--\ndrivers/infiniband/ulp/ipoib/Kconfig-26-\ndrivers/infiniband/ulp/ipoib/Kconfig:27:config INFINIBAND_IPOIB_DEBUG\ndrivers/infiniband/ulp/ipoib/Kconfig-28-\tbool \"IP-over-InfiniBand debugging\" if EXPERT\n--\ndrivers/infiniband/ulp/ipoib/Kconfig-41-\ndrivers/infiniband/ulp/ipoib/Kconfig:42:config INFINIBAND_IPOIB_DEBUG_DATA\ndrivers/infiniband/ulp/ipoib/Kconfig-43-\tbool \"IP-over-InfiniBand data path debugging\"\n--\ndrivers/infiniband/ulp/iser/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/ulp/iser/Kconfig:2:config INFINIBAND_ISER\ndrivers/infiniband/ulp/iser/Kconfig-3-\ttristate \"iSCSI Extensions for RDMA (iSER)\"\n--\ndrivers/infiniband/ulp/isert/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/ulp/isert/Kconfig:2:config INFINIBAND_ISERT\ndrivers/infiniband/ulp/isert/Kconfig-3-\ttristate \"iSCSI Extensions for RDMA (iSER) target support\"\n--\ndrivers/infiniband/ulp/rtrs/Kconfig-2-\ndrivers/infiniband/ulp/rtrs/Kconfig:3:config INFINIBAND_RTRS\ndrivers/infiniband/ulp/rtrs/Kconfig-4-\ttristate\n--\ndrivers/infiniband/ulp/rtrs/Kconfig-6-\ndrivers/infiniband/ulp/rtrs/Kconfig:7:config INFINIBAND_RTRS_CLIENT\ndrivers/infiniband/ulp/rtrs/Kconfig-8-\ttristate \"RTRS client module\"\n--\ndrivers/infiniband/ulp/rtrs/Kconfig-17-\ndrivers/infiniband/ulp/rtrs/Kconfig:18:config INFINIBAND_RTRS_SERVER\ndrivers/infiniband/ulp/rtrs/Kconfig-19-\ttristate \"RTRS server module\"\n--\ndrivers/infiniband/ulp/srp/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/ulp/srp/Kconfig:2:config INFINIBAND_SRP\ndrivers/infiniband/ulp/srp/Kconfig-3-\ttristate \"InfiniBand SCSI RDMA Protocol\"\n--\ndrivers/infiniband/ulp/srpt/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/infiniband/ulp/srpt/Kconfig:2:config INFINIBAND_SRPT\ndrivers/infiniband/ulp/srpt/Kconfig-3-\ttristate \"InfiniBand SCSI RDMA Protocol target support\"\n"
}

11/2 2026/10/08 03:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33557
							output: 27
							thoughts: 1663
						

Thoughts:
**Analyzing RDS/RDMA Patch for Fuzzing Focus**

Okay, here's the breakdown. I need to figure out the right configuration options and key functions to focus on for fuzzing this patch, specifically concerning RDS/RDMA. The starting configuration dependencies are clear: `RDS`, `RDS_TCP`, `RDS_RDMA`, and then if RDMA is enabled, `INFINIBAND` and `INFINIBAND_ADDR_TRANS` also come into play.

Now, the core of this assessment lies in identifying *which* functions the fuzzer should prioritize to understand and efficiently target this patch. I need to meticulously inspect the diff and categorize what's new, what's modified, and what warrants specific attention.  The goal is to provide a "FocusSymbols" list that's targeted and prevents dilution of the fuzzing effort. I have to avoid generic functions like allocators and deallocators. I have to find those functions that really matter to the *new* functionality.

Here's the initial list of functions I pulled from the diff:

*   `net/rds/af_rds.c`: `rds_release`, `rds_ioctl`
*   `net/rds/connection.c`: `rds_conn_lookup`, `rds_conn_passive_locked`, `rds_conn_free_transport_data`, `__rds_conn_create`, `rds_conn_shutdown`, `rds_conn_path_quiesce`, `rds_conn_path_free`, `rds_conn_destroy_fini`, `rds_conn_wait_conns_freed`, `rds_conn_get`, `rds_conn_put`, `rds_conn_destroy`
*   `net/rds/ib.c`: `rds_ib_dev_shutdown`, `rds_ib_is_unloading`, `rds_ib_exit`
*   `net/rds/ib_cm.c`: `rds_ib_setup_qp`, `rds_ib_cm_handle_connect`, `rds_ib_cm_initiate_connect`, `rds_ib_conn_free`
*   `net/rds/ib_rdma.c`: `rds_ib_add_conn`, `rds_ib_remove_conn`, `rds_ib_destroy_nodev_conns`
*   `net/rds/ib_recv.c`: `rds_ib_recv_refill`
*   `net/rds/ib_send.c`: `rds_ib_send_cqe_handler`, `rds_ib_send_add_credits`
*   `net/rds/loop.c`: `rds_loop_destroy_gathered_conns`, `rds_loop_gather_conn`, `rds_loop_conn_free`, `rds_loop_exit`, `rds_loop_kill_conns`
*   `net/rds/message.c`: `rds_message_free`, `rds_message_unpin_worker`, `rds_message_put`
*   `net/rds/rdma_transport.c`: `rds_rdma_cm_event_handler_cmn`
*   `net/rds/recv.c`: `rds_inc_init`, `rds_inc_path_init`, `rds_inc_put`, `rds_recv_incoming`
*   `net/rds/send.c`: `rds_send_xmit`, `rds_send_queue_rm`, `rds_sendmsg`, `rds_send_probe`
*   `net/rds/tcp.c`: `rds_tcp_gather_conn`, `rds_tcp_destroy_gathered_conns`, `rds_tcp_destroy_conns`, `rds_tcp_kill_sock`, `rds_tcp_exit`
*   `net/rds/tcp_listen.c`: `rds_tcp_accept_one`

Now the critical filtering starts.  I need to identify the *non-static, non-inline* functions that are *feature-specific*. I can't let the fuzzer get distracted by too many functions. I need to find the heart of the changes. Based on the guidelines, these jump out:

*   `rds_sendmsg` (direct socket sendmsg handler)
*   `rds_ioctl` (direct socket ioctl handler, modified ToS locking with rs_lock)
*   `rds_release` (direct socket release handler)
*   `rds_conn_destroy` (entrypoint for connection teardown)
*   `rds_conn_get`, `rds_conn_put` (the new refcounting functions)
*   `__rds_conn


12/2 2026/10/08 03:40 tool grepper
0m Args:
{
  "Expression": "rds_release",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/af_rds.c=48=DECLARE_WAIT_QUEUE_HEAD(rds_poll_waitq);\n--\nnet/rds/af_rds.c-58- */\nnet/rds/af_rds.c:59:static int rds_release(struct socket *sock)\nnet/rds/af_rds.c-60-{\n--\nnet/rds/af_rds.c-103-/*\nnet/rds/af_rds.c:104: * Careful not to race with rds_release -\u003e sock_orphan which clears sk_sleep.\nnet/rds/af_rds.c-105- * _bh() isn't OK here, we're called from interrupt handlers.  It's probably OK\n--\nnet/rds/af_rds.c=660=static const struct proto_ops rds_proto_ops = {\n--\nnet/rds/af_rds.c-662-\t.owner =\tTHIS_MODULE,\nnet/rds/af_rds.c:663:\t.release =\trds_release,\nnet/rds/af_rds.c-664-\t.bind =\t\trds_bind,\n--\nnet/rds/bind.c=56=static inline void __rds_create_bind_key(u8 *key, const struct in6_addr *addr,\n--\nnet/rds/bind.c-68- *\nnet/rds/bind.c:69: * The rx path can race with rds_release.  We notice if rds_release() has\nnet/rds/bind.c-70- * marked this socket and don't return a rs ref to the rx path.\n--\nnet/rds/rds.h=658=struct rds_sock {\n--\nnet/rds/rds.h-686-\t * except by\nnet/rds/rds.h:687:\t * rds_release(), which runs once no one else can reach the socket.\nnet/rds/rds.h-688-\t */\n--\nnet/rds/rds.h-718-\t * rs_recv_lock protects the receive queue, and is\nnet/rds/rds.h:719:\t * used to serialize with rds_release.\nnet/rds/rds.h-720-\t */\n--\nnet/rds/recv.c=331=void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,\n--\nnet/rds/recv.c-442-\nnet/rds/recv.c:443:\t/* We can be racing with rds_release() which marks the socket dead. */\nnet/rds/recv.c-444-\tsk = rds_rs_to_sk(rs);\nnet/rds/recv.c-445-\nnet/rds/recv.c:446:\t/* serialize with rds_release -\u003e sock_orphan */\nnet/rds/recv.c-447-\twrite_lock_irqsave(\u0026rs-\u003ers_recv_lock, flags);\n"
}

13/2 2026/10/08 03:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37024
							output: 29
							thoughts: 352
						

Thoughts:
**Analyzing Symbol Coverage for RDS Functions**

Okay, so `rds_release` is defined as `static int rds_release(struct socket *sock)`. My initial thought was to dismiss it because I was under the impression that static functions generally don't have symbols for coverage filters in vmlinux/kallsyms. But wait, that's not quite right. Static functions, unless inlined, DO have symbols! That's a key distinction. The guideline I have to remember is specifically about "STATIC INLINE FUNCTIONS IN HEADERS (.h)". It explicitly warns against those because the compiler often optimizes those and they don't have distinct addresses. This doesn't apply to *static* functions in .c files directly.

I'm thinking about the implications. Static functions that *might* get inlined by the compiler could still lack symbol entries, but that's not the case here, because `rds_release` has its address taken when assigned to a function pointer: `.release = rds_release`. This means the compiler *can't* inline it, and it *will* have a distinct symbol. The same logic holds for `rds_ioctl` with `.ioctl = rds_ioctl`.

Now, I need to check the scope of other functions. I'm thinking about exported/global symbols like `rds_conn_get`, `rds_conn_put`, `rds_conn_destroy`, `rds_conn_wait_conns_freed`, `rds_sendmsg`, `rds_recv_incoming`, `rds_inc_put`, `rds_message_put`, and `rds_tcp_accept_one`. These are obviously not static and should be fine. Finally, I'll need to confirm whether `rds_conn_create` or `__rds_conn_create` are global.



14/2 2026/10/08 03:40 tool grepper
0m Args:
{
  "Expression": "rds_conn_create",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/connection.c=190=static void rds_conn_free_transport_data(struct rds_connection *conn,\n--\nnet/rds/connection.c-210- */\nnet/rds/connection.c:211:static struct rds_connection *__rds_conn_create(struct net *net,\nnet/rds/connection.c-212-\t\t\t\t\t\tconst struct in6_addr *laddr,\n--\nnet/rds/connection.c-455-\nnet/rds/connection.c:456:struct rds_connection *rds_conn_create(struct net *net,\nnet/rds/connection.c-457-\t\t\t\t       const struct in6_addr *laddr,\n--\nnet/rds/connection.c-461-{\nnet/rds/connection.c:462:\treturn __rds_conn_create(net, laddr, faddr, trans, gfp, tos, 0, dev_if);\nnet/rds/connection.c-463-}\nnet/rds/connection.c:464:EXPORT_SYMBOL_GPL(rds_conn_create);\nnet/rds/connection.c-465-\nnet/rds/connection.c:466:struct rds_connection *rds_conn_create_outgoing(struct net *net,\nnet/rds/connection.c-467-\t\t\t\t\t\tconst struct in6_addr *laddr,\n--\nnet/rds/connection.c-471-{\nnet/rds/connection.c:472:\treturn __rds_conn_create(net, laddr, faddr, trans, gfp, tos, 1, dev_if);\nnet/rds/connection.c-473-}\nnet/rds/connection.c:474:EXPORT_SYMBOL_GPL(rds_conn_create_outgoing);\nnet/rds/connection.c-475-\n--\nnet/rds/connection.c=765=void rds_conn_destroy(struct rds_connection *conn)\n--\nnet/rds/connection.c-803-\t/* Snatch c_passive while holding the lock:\nnet/rds/connection.c:804:\t * __rds_conn_create() dereferences it under rcu_read_lock()\nnet/rds/connection.c-805-\t * (and refuses to install a new one once c_destroy_in_prog is\n--\nnet/rds/connection.c-813-\t/* If we are a parent's passive twin, invalidate its pointer to\nnet/rds/connection.c:814:\t * us as well, so that __rds_conn_create() cannot hand out a\nnet/rds/connection.c-815-\t * connection whose teardown has begun.  The parent is the\n--\nnet/rds/ib_cm.c=785=int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,\n--\nnet/rds/ib_cm.c-861-\t/* RDS/IB is not currently netns aware, thus init_net */\nnet/rds/ib_cm.c:862:\tconn = rds_conn_create(\u0026init_net, daddr6, saddr6,\nnet/rds/ib_cm.c-863-\t\t\t       \u0026rds_ib_transport, dp_cmn-\u003ericpc_dp_toss,\n--\nnet/rds/ib_cm.c-865-\tif (IS_ERR(conn)) {\nnet/rds/ib_cm.c:866:\t\trdsdebug(\"rds_conn_create failed (%ld)\\n\", PTR_ERR(conn));\nnet/rds/ib_cm.c-867-\t\tconn = NULL;\n--\nnet/rds/ib_cm.c-879-\t/* Defensive: a destroy that has quiesced this conn also unhashed\nnet/rds/ib_cm.c:880:\t * it, so rds_conn_create() cannot have returned it, and the\nnet/rds/ib_cm.c-881-\t * listeners are stopped before any IB connection is destroyed at\n--\nnet/rds/ib_cm.c-939-\t\tmutex_unlock(\u0026conn-\u003ec_cm_lock);\nnet/rds/ib_cm.c:940:\t\t/* Drop the reference rds_conn_create() handed us.  The\nnet/rds/ib_cm.c-941-\t\t * conn stays reachable through cm_id-\u003econtext without a\n--\nnet/rds/ib_cm.c=1313=void rds_ib_conn_free(void *arg)\n--\nnet/rds/ib_cm.c-1329-\t * Callers may hold rds_conn_lock with interrupts disabled\nnet/rds/ib_cm.c:1330:\t * (__rds_conn_create() undoing a lost creation race), so do not\nnet/rds/ib_cm.c-1331-\t * re-enable interrupts unconditionally here.\n--\nnet/rds/rds.h=138=struct rds_connection {\n--\nnet/rds/rds.h-160-\t * teardown and module unload; the c_passive handling in\nnet/rds/rds.h:161:\t * __rds_conn_create() uses the same predicate, since those rule\nnet/rds/rds.h-162-\t * a passive connection out just as well.  A site that arms\n--\nnet/rds/rds.h=846=void rds_conn_exit(void);\nnet/rds/rds.h:847:struct rds_connection *rds_conn_create(struct net *net,\nnet/rds/rds.h-848-\t\t\t\t       const struct in6_addr *laddr,\n--\nnet/rds/rds.h-852-\t\t\t\t       int dev_if);\nnet/rds/rds.h:853:struct rds_connection *rds_conn_create_outgoing(struct net *net,\nnet/rds/rds.h-854-\t\t\t\t\t\tconst struct in6_addr *laddr,\n--\nnet/rds/send.c=1157=int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n--\nnet/rds/send.c-1345-\nnet/rds/send.c:1346:\t/* rds_conn_create has a spinlock that runs with IRQ off.\nnet/rds/send.c-1347-\t * Caching the conn in the socket helps a lot.\n--\nnet/rds/send.c-1378-\nnet/rds/send.c:1379:\t\tconn = rds_conn_create_outgoing(sock_net(sock-\u003esk),\nnet/rds/send.c-1380-\t\t\t\t\t\t\u0026rs-\u003ers_bound_addr, \u0026daddr,\n--\nnet/rds/tcp_listen.c=152=int rds_tcp_accept_one(struct rds_tcp_net *rtn)\n--\nnet/rds/tcp_listen.c-225-\nnet/rds/tcp_listen.c:226:\tconn = rds_conn_create(sock_net(listen_sock-\u003esk),\nnet/rds/tcp_listen.c-227-\t\t\t       my_addr, peer_addr,\n"
}

15/2 2026/10/08 03:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39591
							output: 271
							thoughts: 939
						

Thoughts:
**Analysis of RDS Connection Lifecycle Refactoring for Fuzzing**

Okay, let's break this down. First, I'm noting that `rds_conn_create` and `rds_conn_create_outgoing` are wrappers around `__rds_conn_create`, which seems like a critical internal function. I also see that `rds_conn_destroy`, `rds_conn_get`, and `rds_conn_put` are exported symbols – important entry points. I then checked `rds_sendmsg`, which, as expected, is in `send.c` and hooked into `proto_ops`. From the `af_rds.c` and other source files, I've confirmed that `rds_sendmsg`, `rds_release`, and `rds_ioctl` are all part of `rds_proto_ops`. I've identified the associated functions within `recv.c`, `message.c`, `connection.c`, `loop.c` and `tcp.c` relevant to the overall connection lifecycle including the connection operations, accept calls and incoming datagrams.

Next, I verified that all requirements are met: `WorthFuzzing` is set to `true`, and all necessary configurations (`RDS`, `RDS_TCP`, `RDS_RDMA`, `INFINIBAND`, and `INFINIBAND_ADDR_TRANS`) are enabled. The `FocusSymbols` list is also exactly as anticipated.

Now, a crucial step: I meticulously checked whether any of the focus symbols are ubiquitous kernel functions. That is, functions that are used by many different parts of the kernel, such as allocators or lock primitives. I confirmed that each one – `rds_conn_destroy`, `rds_conn_put`, `rds_conn_get`, `rds_conn_create`, `rds_conn_create_outgoing`, `rds_sendmsg`, `rds_release`, `rds_ioctl`, `rds_inc_put`, `rds_recv_incoming`, `rds_message_put` and `rds_tcp_accept_one` – is specific to RDS, directly touching the core connection logic, sockets, incoming datagrams, and transports (including TCP). This indicates they are prime targets.

Finally, the reasoning is solid: The refactoring deeply impacts RDS connection management, introducing reference counting, deferred destruction, and changes in connection tracking across the socket operations, message queues, transports, and synchronization primitives. This refactoring clearly modifies the synchronization in `rds_ioctl`, and changes caching and state transitions in `rds_sendmsg`, workqueue scheduling, and message/incoming reference ownership (`rds_inc_put`, `rds_message_put`). This is reachable, network-socket-accessible code. The potential for race conditions, use-after-free errors, memory leaks, and assertion violations is therefore high. Given all this, I'm confident in the analysis. Time to finalize with `set-results`.



16/2 2026/10/08 03:41 tool set-results
0m Args:
{
  "EnableConfigs": [
    "RDS",
    "RDS_TCP",
    "RDS_RDMA",
    "INFINIBAND",
    "INFINIBAND_ADDR_TRANS"
  ],
  "FocusSymbols": [
    "rds_conn_destroy",
    "rds_conn_put",
    "rds_conn_get",
    "rds_conn_create",
    "rds_conn_create_outgoing",
    "rds_sendmsg",
    "rds_release",
    "rds_ioctl",
    "rds_inc_put",
    "rds_recv_incoming",
    "rds_message_put",
    "rds_tcp_accept_one"
  ],
  "Reasoning": "The patch overhauls connection lifecycle management and reference counting across the RDS (Reliable Datagram Sockets) subsystem and its transports (loopback, TCP, IB). It replaces immediate connection freeing with deferred kref-based destruction, updates lock handling and caching in rds_sendmsg, rds_release, and rds_ioctl, alters workqueue quiescing and message/incoming datagram reference ownership, and adjusts transport teardown paths. These changes affect fully reachable socket and networking code with concurrency, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "RDS",
    "RDS_TCP",
    "RDS_RDMA",
    "INFINIBAND",
    "INFINIBAND_ADDR_TRANS"
  ],
  "FocusSymbols": [
    "rds_conn_destroy",
    "rds_conn_put",
    "rds_conn_get",
    "rds_conn_create",
    "rds_conn_create_outgoing",
    "rds_sendmsg",
    "rds_release",
    "rds_ioctl",
    "rds_inc_put",
    "rds_recv_incoming",
    "rds_message_put",
    "rds_tcp_accept_one"
  ],
  "Reasoning": "The patch overhauls connection lifecycle management and reference counting across the RDS (Reliable Datagram Sockets) subsystem and its transports (loopback, TCP, IB). It replaces immediate connection freeing with deferred kref-based destruction, updates lock handling and caching in rds_sendmsg, rds_release, and rds_ioctl, alters workqueue quiescing and message/incoming datagram reference ownership, and adjusts transport teardown paths. These changes affect fully reachable socket and networking code with concurrency, making it a high-value target for fuzzing.",
  "WorthFuzzing": true
}

17/1 2026/10/08 03:41 action If
3m Args:
{
  "WorthFuzzing": true
}

Results:
null

18/2 2026/10/08 03:41 agent kmsan-evaluator
3m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch addresses lifetime management, reference counting, and teardown synchronization for RDS connections (`struct rds_connection`) across the core RDS subsystem and its transport implementations (IB, TCP, and loopback). Specifically, it introduces refcounting via `kref` on `rds_connection`, handles deferred destruction once all holders (including sockets, queued messages, and incoming datagrams) release their references, synchronizes transport unload waiting for all connection instances to be freed, and uses `c_destroy_in_prog` to guard against queuing work on quiesced workqueues.\n\nFrom a memory sanitization perspective:\n1. **Uninitialized Memory \u0026 Info-leaks (KMSAN):**\n   - All newly added and modified struct fields (`c_refcount`, `c_destroy_in_prog`, `t_conn_count`, `i_ib_node_detached`, `shutting_down`, `t_tcp_node_detached`) reside in objects that are allocated via `kzalloc`, `kmem_cache_zalloc`, or `sk_alloc` (all zero-initialized), or in static BSS data (`struct rds_transport`).\n   - The user-copy site touched by the patch is `put_user(tos, ...)` in `rds_ioctl(SIOCRDSGETTOS)`, where `tos` is explicitly initialized (`tos = 0`) and read from zero-initialized socket state (`rs-\u003ers_tos`). No struct padding or kernel data leaks to userspace are introduced.\n   - The patch does not modify packet parsing, bounds checking, buffer length computations, or payload copying in any way that could expose uninitialized memory.\n\n2. **Memory Safety \u0026 Concurrency (KASAN / LOCKDEP):**\n   - The risks associated with these changes are use-after-free (e.g. incorrect refcounting or premature connection cleanup), double free, concurrency races, and locking deadlocks (e.g. `rs_lock`, `rds_conn_lock`, `cp_lock`).\n   - These classes of defects are already detected by KASAN, LOCKDEP, and standard debugging checks in the default KASAN fuzzing build.\n\nBecause there are no uninitialized memory reads or info-leak risks that would uniquely require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 56430c88cd4670f2cd2c6b6dcee84004f34dda87
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 8 03:38:14 2026 +0000

    syz-cluster: applied patch under review

diff --git a/net/rds/af_rds.c b/net/rds/af_rds.c
index d5defe9172e36..99c44d88d2e7e 100644
--- a/net/rds/af_rds.c
+++ b/net/rds/af_rds.c
@@ -80,6 +80,14 @@ static int rds_release(struct socket *sock)
 	rds_notify_queue_get(rs, NULL);
 	rds_notify_msg_zcopy_purge(&rs->rs_zcookie_queue);
 
+	/* drop the cached connection reference; no sendmsg can race
+	 * with us here, the socket is going away
+	 */
+	if (rs->rs_conn) {
+		rds_conn_put(rs->rs_conn);
+		rs->rs_conn = NULL;
+	}
+
 	spin_lock_bh(&rds_sock_lock);
 	list_del_init(&rs->rs_item);
 	spin_unlock_bh(&rds_sock_lock);
@@ -255,6 +263,7 @@ static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
 {
 	struct rds_sock *rs = rds_sk_to_rs(sock->sk);
 	rds_tos_t utos, tos = 0;
+	unsigned long flags;
 
 	switch (cmd) {
 	case SIOCRDSSETTOS:
@@ -267,18 +276,23 @@ static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
 		else
 			return -ENOIOCTLCMD;
 
-		spin_lock_bh(&rds_sock_lock);
+		/* rs_conn is serialized by rs_lock (see rds_sendmsg());
+		 * hold it across the "no connection yet" check and the
+		 * rs_tos store so a racing sendmsg cannot cache a conn
+		 * whose c_tos then disagrees with rs_tos.
+		 */
+		spin_lock_irqsave(&rs->rs_lock, flags);
 		if (rs->rs_tos || rs->rs_conn) {
-			spin_unlock_bh(&rds_sock_lock);
+			spin_unlock_irqrestore(&rs->rs_lock, flags);
 			return -EINVAL;
 		}
-		rs->rs_tos = tos;
-		spin_unlock_bh(&rds_sock_lock);
+		WRITE_ONCE(rs->rs_tos, tos);
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
 		break;
 	case SIOCRDSGETTOS:
-		spin_lock_bh(&rds_sock_lock);
+		spin_lock_irqsave(&rs->rs_lock, flags);
 		tos = rs->rs_tos;
-		spin_unlock_bh(&rds_sock_lock);
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
 		if (put_user(tos, (rds_tos_t __user *)arg))
 			return -EFAULT;
 		break;
diff --git a/net/rds/connection.c b/net/rds/connection.c
index c752a8623cfca..8c4df7d6b294d 100644
--- a/net/rds/connection.c
+++ b/net/rds/connection.c
@@ -47,7 +47,8 @@
 
 /* converting this to RCU is a chore for another day.. */
 static DEFINE_SPINLOCK(rds_conn_lock);
-static unsigned long rds_conn_count;
+/* woken whenever a transport's t_conn_count drops to zero */
+static DECLARE_WAIT_QUEUE_HEAD(rds_conn_freed_waitq);
 static struct hlist_head rds_conn_hash[RDS_CONNECTION_HASH_ENTRIES];
 static struct kmem_cache *rds_conn_slab;
 
@@ -79,7 +80,10 @@ static struct hlist_head *rds_conn_bucket(const struct in6_addr *laddr,
 		var |= RDS_INFO_CONNECTION_FLAG_##suffix;	\
 } while (0)
 
-/* rcu read lock must be held or the connection spinlock */
+/* rcu read lock must be held or the connection spinlock.
+ * On success a reference is taken on the returned connection; the
+ * caller must drop it with rds_conn_put().
+ */
 static struct rds_connection *rds_conn_lookup(struct net *net,
 					      struct hlist_head *head,
 					      const struct in6_addr *laddr,
@@ -96,6 +100,17 @@ static struct rds_connection *rds_conn_lookup(struct net *net,
 		    conn->c_tos == tos &&
 		    net == rds_conn_net(conn) &&
 		    conn->c_dev_if == dev_if) {
+			/* Only ever hand out a live reference.
+			 * rds_conn_destroy() unhashes under
+			 * rds_conn_lock and waits a grace period
+			 * before dropping the initial reference, so
+			 * an entry this traversal reaches still holds
+			 * at least that one; the conditional get
+			 * documents the contract rather than
+			 * papering over a zero-refcount entry.
+			 */
+			if (!kref_get_unless_zero(&conn->c_refcount))
+				continue;
 			ret = conn;
 			break;
 		}
@@ -161,6 +176,30 @@ static void __rds_conn_path_init(struct rds_connection *conn,
 	cp->cp_flags = 0;
 }
 
+/* c_passive is written under rds_conn_lock and read under RCU */
+static struct rds_connection *
+rds_conn_passive_locked(struct rds_connection *conn)
+{
+	return rcu_dereference_protected(conn->c_passive,
+					 lockdep_is_held(&rds_conn_lock));
+}
+
+/* Undo trans->conn_alloc(): it may have allocated transport data for
+ * every path of a multipath connection, not just for path 0.
+ */
+static void rds_conn_free_transport_data(struct rds_connection *conn,
+					 int npaths)
+{
+	struct rds_conn_path *cp;
+	int i;
+
+	for (i = 0; i < npaths; i++) {
+		cp = &conn->c_path[i];
+		if (cp->cp_transport_data)
+			conn->c_trans->conn_free(cp->cp_transport_data);
+	}
+}
+
 /*
  * There is only every one 'conn' for a given pair of addresses in the
  * system at a time.  They contain messages to be retransmitted and so
@@ -197,7 +236,20 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 		 * We need a second connection object into which we
 		 * can stick the other QP. */
 		parent = conn;
-		conn = parent->c_passive;
+		/* The c_passive pointer holds a reference which is only
+		 * dropped one synchronize_rcu() after the pointer is
+		 * cleared, so within this RCU section a fetched pointer
+		 * is always safe to take a reference on.  A passive conn
+		 * whose own destroy has begun is not handed out, though:
+		 * it is quiesced and about to clear the parent's pointer
+		 * itself, and reusing it would re-arm a connection that
+		 * nothing will tear down again.
+		 */
+		conn = rcu_dereference(parent->c_passive);
+		if (conn && rds_destroy_pending(conn))
+			conn = NULL;
+		if (conn)
+			rds_conn_get(conn);
 	}
 	rcu_read_unlock();
 	if (conn)
@@ -215,6 +267,7 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 		goto out;
 	}
 
+	kref_init(&conn->c_refcount);
 	INIT_HLIST_NODE(&conn->c_hash_node);
 	conn->c_laddr = *laddr;
 	conn->c_isv6 = !ipv6_addr_v4mapped(laddr);
@@ -284,12 +337,13 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 
 	init_waitqueue_head(&conn->c_hs_waitq);
 	for (i = 0; i < npaths; i++) {
+		int seq = atomic_read(&trans->t_conn_count);
+
 		__rds_conn_path_init(conn, &conn->c_path[i],
 				     is_outgoing);
 		conn->c_path[i].cp_index = i;
 		conn->c_path[i].cp_wq =
-			alloc_ordered_workqueue("krds_cp_wq#%lu/%d", 0,
-						rds_conn_count, i);
+			alloc_ordered_workqueue("krds_cp_wq#%d/%d", 0, seq, i);
 		if (!conn->c_path[i].cp_wq)
 			conn->c_path[i].cp_wq = rds_wq;
 	}
@@ -321,15 +375,44 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 	spin_lock_irqsave(&rds_conn_lock, flags);
 	if (parent) {
 		/* Creating passive conn */
-		if (parent->c_passive) {
-			trans->conn_free(conn->c_path[0].cp_transport_data);
+		if (rds_destroy_pending(parent)) {
+			/* The parent's destroy has begun (it sets the
+			 * flag and snatches c_passive under this
+			 * lock); do not install a new passive conn
+			 * that nothing would ever destroy.
+			 */
+			rds_conn_free_transport_data(conn, npaths);
+			free_cp = conn->c_path;
+			kmem_cache_free(rds_conn_slab, conn);
+			conn = ERR_PTR(-ENETDOWN);
+		} else if (rcu_access_pointer(parent->c_passive)) {
+			struct rds_connection *passive;
+
+			passive = rds_conn_passive_locked(parent);
+			rds_conn_free_transport_data(conn, npaths);
 			free_cp = conn->c_path;
 			kmem_cache_free(rds_conn_slab, conn);
-			conn = parent->c_passive;
+			/* A passive conn still installed here cannot have
+			 * its own destroy begun: rds_conn_destroy() sets
+			 * c_destroy_in_prog and clears the parent's pointer
+			 * in one rds_conn_lock section, and the netns and
+			 * unload cases were ruled out by the parent above.
+			 */
+			rds_conn_get(passive);
+			conn = passive;
 		} else {
-			parent->c_passive = conn;
+			/* The initial reference belongs to whoever
+			 * destroys the conn (the transport's conn
+			 * lists, as for any other conn).  Take one
+			 * for the c_passive pointer - dropped when
+			 * the parent is destroyed - and one for our
+			 * caller.
+			 */
+			rds_conn_get(conn);	/* c_passive */
+			rds_conn_get(conn);	/* caller */
+			rcu_assign_pointer(parent->c_passive, conn);
 			rds_cong_add_conn(conn);
-			rds_conn_count++;
+			atomic_inc(&conn->c_trans->t_conn_count);
 		}
 	} else {
 		/* Creating normal conn */
@@ -338,33 +421,28 @@ static struct rds_connection *__rds_conn_create(struct net *net,
 		found = rds_conn_lookup(net, head, laddr, faddr, trans,
 					tos, dev_if);
 		if (found) {
-			struct rds_conn_path *cp;
-			int i;
-
-			for (i = 0; i < npaths; i++) {
-				cp = &conn->c_path[i];
-				/* The ->conn_alloc invocation may have
-				 * allocated resource for all paths, so all
-				 * of them may have to be freed here.
-				 */
-				if (cp->cp_transport_data)
-					trans->conn_free(cp->cp_transport_data);
-			}
+			rds_conn_free_transport_data(conn, npaths);
 			free_cp = conn->c_path;
 			kmem_cache_free(rds_conn_slab, conn);
 			conn = found;
 		} else {
 			conn->c_my_gen_num = rds_gen_num;
 			conn->c_peer_gen_num = 0;
+			/* the initial reference belongs to whoever
+			 * destroys the conn; take one for our caller
+			 */
+			rds_conn_get(conn);
 			hlist_add_head_rcu(&conn->c_hash_node, head);
 			rds_cong_add_conn(conn);
-			rds_conn_count++;
+			atomic_inc(&conn->c_trans->t_conn_count);
 		}
 	}
 	spin_unlock_irqrestore(&rds_conn_lock, flags);
 	rcu_read_unlock();
 
 out:
+	if (parent)
+		rds_conn_put(parent);
 	if (free_cp) {
 		for (i = 0; i < npaths; i++)
 			if (free_cp[i].cp_wq != rds_wq)
@@ -472,9 +550,10 @@ void rds_conn_shutdown(struct rds_conn_path *cp)
 			 * Quiesce the reconnect timer before bailing
 			 * out, though.  When a pending destroy did
 			 * suppress the queue, no later pass runs, and
-			 * rds_conn_path_destroy() is about to flush
-			 * cp_down_w and free the path: it must not
-			 * find cp_conn_w still armed.  A successor
+			 * rds_conn_path_quiesce() is about to flush
+			 * cp_down_w, ahead of the path's deferred
+			 * free: it must not find cp_conn_w still
+			 * armed.  A successor
 			 * pass, when there is one, re-arms the
 			 * reconnect from its own tail.
 			 */
@@ -521,12 +600,16 @@ void rds_conn_shutdown(struct rds_conn_path *cp)
 		conn->c_trans->conn_slots_available(conn, false);
 }
 
-/* destroy a single rds_conn_path. rds_conn_destroy() iterates over
- * all paths using rds_conn_path_destroy()
+/* quiesce a single rds_conn_path: shut it down and tear down any
+ * queued messages.  rds_conn_destroy() iterates over all paths using
+ * rds_conn_path_quiesce(); the transport state and the workqueue are
+ * freed later, from rds_conn_path_free().
  */
-static void rds_conn_path_destroy(struct rds_conn_path *cp)
+static void rds_conn_path_quiesce(struct rds_conn_path *cp)
 {
 	struct rds_message *rm, *rtmp;
+	unsigned long flags;
+	LIST_HEAD(purge);
 
 	if (!cp->cp_transport_data)
 		return;
@@ -538,12 +621,29 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)
 	rds_conn_path_drop(cp, true);
 	flush_work(&cp->cp_down_w);
 
-	/* tear down queued messages */
-	list_for_each_entry_safe(rm, rtmp,
-				 &cp->cp_send_queue,
-				 m_conn_item) {
+	/* Tear down queued messages.  Every path that adds to
+	 * cp_send_queue does so under cp_lock; take it here too.  No
+	 * sender can still be running at any destroy trigger, so this is
+	 * lock discipline rather than a race fix: nothing here tells a
+	 * sender that the queue is closed.
+	 */
+	spin_lock_irqsave(&cp->cp_lock, flags);
+	list_splice_init(&cp->cp_send_queue, &purge);
+	/* Give up the queue's claim on each message while still under
+	 * the lock, so that rds_send_drop_to(), which decides ownership
+	 * of the connection-queue reference by this bit, neither drops
+	 * it a second time nor unlinks the message from our list.
+	 */
+	list_for_each_entry(rm, &purge, m_conn_item)
+		clear_bit(RDS_MSG_ON_CONN, &rm->m_flags);
+	spin_unlock_irqrestore(&cp->cp_lock, flags);
+	list_for_each_entry_safe(rm, rtmp, &purge, m_conn_item) {
+		/* No socket can still have messages queued on a connection
+		 * at any destroy trigger; say so if one does, since the
+		 * socket side then retires the message on its own.
+		 */
+		WARN_ON_ONCE(!list_empty(&rm->m_sock_item));
 		list_del_init(&rm->m_conn_item);
-		BUG_ON(!list_empty(&rm->m_sock_item));
 		rds_message_put(rm);
 	}
 	if (cp->cp_xmit_rm)
@@ -553,6 +653,16 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)
 	WARN_ON(delayed_work_pending(&cp->cp_recv_w));
 	WARN_ON(delayed_work_pending(&cp->cp_conn_w));
 	WARN_ON(work_pending(&cp->cp_down_w));
+}
+
+/* free a quiesced rds_conn_path's transport state and workqueue; runs
+ * from rds_conn_destroy_fini() once the last connection reference is
+ * dropped.
+ */
+static void rds_conn_path_free(struct rds_conn_path *cp)
+{
+	if (!cp->cp_transport_data)
+		return;
 
 	if (cp->cp_wq != rds_wq) {
 		destroy_workqueue(cp->cp_wq);
@@ -562,17 +672,102 @@ static void rds_conn_path_destroy(struct rds_conn_path *cp)
 	cp->cp_conn->c_trans->conn_free(cp->cp_transport_data);
 }
 
+/* Free a connection.  This runs from rds_conn_put() when the last
+ * reference is dropped, after rds_conn_destroy() has quiesced the
+ * connection and dropped the initial reference.
+ */
+static void rds_conn_destroy_fini(struct kref *kref)
+{
+	struct rds_connection *conn = container_of(kref, struct rds_connection,
+						   c_refcount);
+	int npaths = (conn->c_trans->t_mp_capable ? RDS_MPATH_WORKERS : 1);
+	struct rds_transport *trans = conn->c_trans;
+	int i;
+
+	for (i = 0; i < npaths; i++)
+		rds_conn_path_free(&conn->c_path[i]);
+
+	kfree(conn->c_path);
+	kmem_cache_free(rds_conn_slab, conn);
+
+	/* only after everything the transport module owns has been
+	 * freed above may its unload proceed
+	 */
+	if (!atomic_dec_return(&trans->t_conn_count))
+		wake_up_all(&rds_conn_freed_waitq);
+}
+
+/* Wait for all of @trans's connections to be freed; the free runs
+ * asynchronously once rds_conn_destroy() has quiesced a connection.
+ * Called on transport module unload after an initial sweep has
+ * destroyed the transport's connections; @resweep, when given, is
+ * called on every poll to destroy connections that were still
+ * detaching from a device when the sweep ran (IB).  A connection
+ * reference can be held for an application-controlled time - once
+ * incs hold one, an unread datagram pins the inc that carries it, and
+ * thus the connection - so the wait is unbounded: the frees that run
+ * after unload call into this module's text (conn_free, inc_free) and
+ * free into its slabs, so proceeding while any remain would be a
+ * use-after-free, not a leak.  Warn periodically so a stuck count is
+ * diagnosable, but never stop waiting.  This matches the historical
+ * RDS contract that teardown does not discard queued data.
+ */
+void rds_conn_wait_conns_freed(struct rds_transport *trans,
+			       void (*resweep)(void))
+{
+	unsigned long warn_interval =
+			msecs_to_jiffies(RDS_CONN_FREE_WARN_INTERVAL_MS);
+	unsigned long warn_at = jiffies + warn_interval;
+
+	while (!wait_event_timeout(rds_conn_freed_waitq,
+				   !atomic_read(&trans->t_conn_count),
+				   msecs_to_jiffies(RDS_CONN_FREE_POLL_MS))) {
+		/* A transport whose teardown is asynchronous (IB moves a
+		 * connection off its device from the shutdown work) gives
+		 * us a resweep to destroy what has arrived since.
+		 */
+		if (resweep)
+			resweep();
+		if (time_after_eq(jiffies, warn_at)) {
+			pr_warn("RDS/%s: still waiting for %d connection(s) to be freed before unload\n",
+				trans->t_name,
+				atomic_read(&trans->t_conn_count));
+			warn_at = jiffies + warn_interval;
+		}
+	}
+}
+EXPORT_SYMBOL_GPL(rds_conn_wait_conns_freed);
+
+void rds_conn_get(struct rds_connection *conn)
+{
+	kref_get(&conn->c_refcount);
+}
+EXPORT_SYMBOL_GPL(rds_conn_get);
+
+void rds_conn_put(struct rds_connection *conn)
+{
+	kref_put(&conn->c_refcount, rds_conn_destroy_fini);
+}
+EXPORT_SYMBOL_GPL(rds_conn_put);
+
 /*
  * Stop and free a connection.
  *
- * This can only be used in very limited circumstances.  It assumes that once
- * the conn has been shutdown that no one else is referencing the connection.
- * We can only ensure this in the rmmod path in the current code.
+ * Quiesces the connection synchronously (workers cancelled, transport
+ * connections shut down, queued messages dropped) and drops the
+ * initial reference.  Only the first call for a connection does any
+ * of that: a later one finds c_destroy_in_prog already set and
+ * returns at once, without waiting for the first.  The memory -
+ * including the transport's per-connection state and the path
+ * workqueues - is freed once the last rds_conn_put() runs, which may
+ * be after this returns.
  */
 void rds_conn_destroy(struct rds_connection *conn)
 {
-	unsigned long flags;
 	int i;
+	struct rds_connection *passive, *parent;
+	struct hlist_head *head;
+	bool was_passive = false;
 	struct rds_conn_path *cp;
 	int npaths = (conn->c_trans->t_mp_capable ? RDS_MPATH_WORKERS : 1);
 
@@ -580,16 +775,68 @@ void rds_conn_destroy(struct rds_connection *conn)
 		 "%pI4\n", conn, &conn->c_laddr,
 		 &conn->c_faddr);
 
-	/* Ensure conn will not be scheduled for reconnect */
+	/* Make rds_destroy_pending() true for this conn.  Together with
+	 * the synchronize_rcu() below this stops the work-requeueing
+	 * sites (which test rds_destroy_pending() under rcu_read_lock(),
+	 * bar the exemptions noted at c_destroy_in_prog) from queueing
+	 * new work on the path workqueues once we start cancelling and
+	 * destroying them.
+	 *
+	 * Only the first caller proceeds.  No caller in this tree hands
+	 * a connection to rds_conn_destroy() twice - every teardown
+	 * sweep unlinks or claims its node before the destroy - so this
+	 * documents the contract rather than closing a path: a second
+	 * caller returns at once, without quiescing or waiting.  The
+	 * unhash also happens under rds_conn_lock, so a looked-up conn
+	 * can never be quiesced twice.
+	 */
 	spin_lock_irq(&rds_conn_lock);
+	if (conn->c_destroy_in_prog) {
+		spin_unlock_irq(&rds_conn_lock);
+		return;
+	}
+	WRITE_ONCE(conn->c_destroy_in_prog, true);
+
+	/* Ensure conn will not be scheduled for reconnect */
 	hlist_del_init_rcu(&conn->c_hash_node);
+
+	/* Snatch c_passive while holding the lock:
+	 * __rds_conn_create() dereferences it under rcu_read_lock()
+	 * (and refuses to install a new one once c_destroy_in_prog is
+	 * set, which it checks under this lock).  After the
+	 * synchronize_rcu() below no one can pick the pointer up any
+	 * more and its reference can be dropped.
+	 */
+	passive = rds_conn_passive_locked(conn);
+	RCU_INIT_POINTER(conn->c_passive, NULL);
+
+	/* If we are a parent's passive twin, invalidate its pointer to
+	 * us as well, so that __rds_conn_create() cannot hand out a
+	 * connection whose teardown has begun.  The parent is the
+	 * hashed connection for our key (a passive conn is never
+	 * hashed, and we unhashed ourselves above); it holds its
+	 * initial reference for as long as it is hashed, so the lookup
+	 * reference dropped below cannot be its last.
+	 */
+	head = rds_conn_bucket(&conn->c_laddr, &conn->c_faddr);
+	rcu_read_lock();
+	parent = rds_conn_lookup(rds_conn_net(conn), head, &conn->c_laddr,
+				 &conn->c_faddr, conn->c_trans, conn->c_tos,
+				 conn->c_dev_if);
+	rcu_read_unlock();
+	if (parent && rds_conn_passive_locked(parent) == conn) {
+		RCU_INIT_POINTER(parent->c_passive, NULL);
+		was_passive = true;
+	}
 	spin_unlock_irq(&rds_conn_lock);
+	if (parent)
+		rds_conn_put(parent);
 	synchronize_rcu();
 
 	/* shut the connection down */
 	for (i = 0; i < npaths; i++) {
 		cp = &conn->c_path[i];
-		rds_conn_path_destroy(cp);
+		rds_conn_path_quiesce(cp);
 		BUG_ON(!list_empty(&cp->cp_retrans));
 	}
 
@@ -600,12 +847,21 @@ void rds_conn_destroy(struct rds_connection *conn)
 	 */
 	rds_cong_remove_conn(conn);
 
-	kfree(conn->c_path);
-	kmem_cache_free(rds_conn_slab, conn);
+	/* Drop the reference our c_passive pointer held, if any, and
+	 * the one a parent's c_passive pointer held on us.  Either may
+	 * be the last one - the twin's own destroy may already have run
+	 * - so these must stay here, in sleepable context with no lock
+	 * held, where the free that follows the last put is allowed.
+	 */
+	if (passive)
+		rds_conn_put(passive);
+	if (was_passive)
+		rds_conn_put(conn);
 
-	spin_lock_irqsave(&rds_conn_lock, flags);
-	rds_conn_count--;
-	spin_unlock_irqrestore(&rds_conn_lock, flags);
+	/* drop the initial reference; the connection is freed from
+	 * rds_conn_destroy_fini() once every holder has dropped theirs
+	 */
+	rds_conn_put(conn);
 }
 EXPORT_SYMBOL_GPL(rds_conn_destroy);
 
diff --git a/net/rds/ib.c b/net/rds/ib.c
index 4ea9838d090c3..7b1f611c0a3e5 100644
--- a/net/rds/ib.c
+++ b/net/rds/ib.c
@@ -86,6 +86,11 @@ static void rds_ib_dev_shutdown(struct rds_ib_device *rds_ibdev)
 	unsigned long flags;
 
 	spin_lock_irqsave(&rds_ibdev->spinlock, flags);
+	/* Close the device to new connections under the same lock that
+	 * rds_ib_add_conn() attaches them under, so that every
+	 * connection is either dropped by the walk below or refused.
+	 */
+	rds_ibdev->shutting_down = true;
 	list_for_each_entry(ic, &rds_ibdev->conn_list, ib_node)
 		rds_conn_path_drop(&ic->conn->c_path[0], true);
 	spin_unlock_irqrestore(&rds_ibdev->spinlock, flags);
@@ -523,10 +528,7 @@ static void rds_ib_set_unloading(void)
 
 static bool rds_ib_is_unloading(struct rds_connection *conn)
 {
-	struct rds_conn_path *cp = &conn->c_path[0];
-
-	return (test_bit(RDS_DESTROY_PENDING, &cp->cp_flags) ||
-		atomic_read(&rds_ib_unloading) != 0);
+	return atomic_read(&rds_ib_unloading) != 0;
 }
 
 void rds_ib_exit(void)
@@ -538,7 +540,24 @@ void rds_ib_exit(void)
 	rds_info_deregister_func(RDS6_INFO_IB_CONNECTIONS, rds6_ib_ic_info);
 #endif
 	rds_ib_unregister_client();
+
+	/* rds_ib_dev_shutdown() only dropped the connections still
+	 * attached to a device; each moves itself to ib_nodev_conns
+	 * from its shutdown work.  Destroy what is there now and keep
+	 * sweeping the list while the wait sees connections outstanding,
+	 * so a late arrival is destroyed rather than waited on forever.
+	 */
 	rds_ib_destroy_nodev_conns();
+	rds_conn_wait_conns_freed(&rds_ib_transport,
+				  rds_ib_destroy_nodev_conns);
+
+	/* Tearing down the last connection may have dropped the final
+	 * reference on a device, deferring rds_ib_dev_free() to rds_wq.
+	 * Drain it before the module goes away; it queues nothing
+	 * further on rds_wq.
+	 */
+	flush_workqueue(rds_wq);
+
 	rds_ib_sysctl_exit();
 	rds_ib_recv_exit();
 	rds_trans_unregister(&rds_ib_transport);
diff --git a/net/rds/ib.h b/net/rds/ib.h
index 1901226368c98..07474fe7327b0 100644
--- a/net/rds/ib.h
+++ b/net/rds/ib.h
@@ -143,6 +143,10 @@ struct rds_ib_device;
 struct rds_ib_connection {
 
 	struct list_head	ib_node;
+	/* set under ib_nodev_conns_lock once a transport teardown has
+	 * claimed ib_node; from then on only the teardown touches it
+	 */
+	bool			i_ib_node_detached;
 	struct rds_ib_device	*rds_ibdev;
 	struct rds_connection	*conn;
 
@@ -258,6 +262,10 @@ struct rds_ib_device {
 	unsigned int		max_initiator_depth;
 	unsigned int		max_responder_resources;
 	spinlock_t		spinlock;	/* protect the above */
+	/* set under spinlock by rds_ib_dev_shutdown(): the device is
+	 * going away and no connection may attach to it any more
+	 */
+	bool			shutting_down;
 	refcount_t		refcount;
 	struct work_struct	free_work;
 	int			*vector_load;
@@ -384,7 +392,8 @@ void rds_ib_cm_connect_complete(struct rds_connection *conn,
 struct rds_ib_device *rds_ib_get_device(__be32 ipaddr);
 int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev,
 			 struct in6_addr *ipaddr);
-void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn);
+int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,
+		    struct rds_connection *conn);
 void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn);
 void rds_ib_destroy_nodev_conns(void);
 void rds_ib_mr_cqe_handler(struct rds_ib_connection *ic, struct ib_wc *wc);
diff --git a/net/rds/ib_cm.c b/net/rds/ib_cm.c
index 3ed03ad328129..38d95b016773c 100644
--- a/net/rds/ib_cm.c
+++ b/net/rds/ib_cm.c
@@ -524,7 +524,9 @@ static int rds_ib_setup_qp(struct rds_connection *conn)
 	fr_queue_space = RDS_IB_DEFAULT_FR_WR;
 
 	/* add the conn now so that connection establishment has the dev */
-	rds_ib_add_conn(rds_ibdev, conn);
+	ret = rds_ib_add_conn(rds_ibdev, conn);
+	if (ret)
+		goto out;
 
 	max_wrs = rds_ibdev->max_wrs < rds_ib_sysctl_max_send_wr + 1 ?
 		rds_ibdev->max_wrs - 1 : rds_ib_sysctl_max_send_wr;
@@ -874,6 +876,15 @@ int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,
 	 * see the comment above rds_queue_reconnect()
 	 */
 	mutex_lock(&conn->c_cm_lock);
+	/* Defensive: a destroy that has quiesced this conn also unhashed
+	 * it, so rds_conn_create() cannot have returned it, and the
+	 * listeners are stopped before any IB connection is destroyed at
+	 * unload.  Should a request reach a conn in RDS_CONN_DOWN with
+	 * its destroy begun all the same, do not install a new cm_id and
+	 * QP that nothing would tear down.
+	 */
+	if (rds_destroy_pending(conn))
+		goto out;
 	if (!rds_conn_transition(conn, RDS_CONN_DOWN, RDS_CONN_CONNECTING)) {
 		if (rds_conn_state(conn) == RDS_CONN_UP) {
 			rdsdebug("incoming connect while connecting\n");
@@ -924,8 +935,15 @@ int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,
 		rds_ib_conn_error(conn, "rdma_accept failed\n");
 
 out:
-	if (conn)
+	if (conn) {
 		mutex_unlock(&conn->c_cm_lock);
+		/* Drop the reference rds_conn_create() handed us.  The
+		 * conn stays reachable through cm_id->context without a
+		 * reference of its own; rds_rdma_cm_event_handler_cmn()
+		 * takes one for the duration of each event it handles.
+		 */
+		rds_conn_put(conn);
+	}
 	if (err)
 		rdma_reject(cm_id, &err, sizeof(int),
 			    IB_CM_REJ_CONSUMER_DEFINED);
@@ -941,6 +959,18 @@ int rds_ib_cm_initiate_connect(struct rdma_cm_id *cm_id, bool isv6)
 	union rds_ib_conn_priv dp;
 	int ret;
 
+	/* Defensive: a destroy that began while the address and route
+	 * were being resolved either waits on c_cm_lock behind this
+	 * handler, and its shutdown pass then tears down whatever is
+	 * set up here, or has already destroyed the id this event
+	 * arrived on, in which case the event never gets here.  Decline
+	 * to set up a QP all the same, and return success: the id is
+	 * still ic->i_cm_id, for that shutdown to destroy, and a
+	 * non-zero return would have the rdma_cm destroy it instead.
+	 */
+	if (rds_destroy_pending(conn))
+		return 0;
+
 	/* If the peer doesn't do protocol negotiation, we must
 	 * default to RDSv3.0 */
 	rds_ib_set_protocol(conn, RDS_PROTOCOL_4_1);
@@ -1284,19 +1314,29 @@ void rds_ib_conn_free(void *arg)
 {
 	struct rds_ib_connection *ic = arg;
 	spinlock_t	*lock_ptr;
+	unsigned long flags;
 
 	rdsdebug("ic %p\n", ic);
 
 	/*
-	 * Conn is either on a dev's list or on the nodev list.
-	 * A race with shutdown() or connect() would cause problems
-	 * (since rds_ibdev would change) but that should never happen.
+	 * Conn is on a dev's list or on the nodev list - or, once a
+	 * transport teardown has claimed it (i_ib_node_detached), on
+	 * neither, in which case the lock chosen here only guards the
+	 * test below.  A connect or shutdown still running for a
+	 * claimed conn leaves the node alone, see rds_ib_add_conn() and
+	 * rds_ib_remove_conn().
+	 *
+	 * Callers may hold rds_conn_lock with interrupts disabled
+	 * (__rds_conn_create() undoing a lost creation race), so do not
+	 * re-enable interrupts unconditionally here.
 	 */
 	lock_ptr = ic->rds_ibdev ? &ic->rds_ibdev->spinlock : &ib_nodev_conns_lock;
 
-	spin_lock_irq(lock_ptr);
-	list_del(&ic->ib_node);
-	spin_unlock_irq(lock_ptr);
+	spin_lock_irqsave(lock_ptr, flags);
+	/* a transport teardown that gathered us first owns the node */
+	if (!ic->i_ib_node_detached)
+		list_del(&ic->ib_node);
+	spin_unlock_irqrestore(lock_ptr, flags);
 
 	rds_ib_recv_free_caches(ic);
 
diff --git a/net/rds/ib_rdma.c b/net/rds/ib_rdma.c
index db7e92e7bd29f..f0e7d116b0844 100644
--- a/net/rds/ib_rdma.c
+++ b/net/rds/ib_rdma.c
@@ -119,38 +119,62 @@ int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev,
 	return 0;
 }
 
-void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)
+int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,
+		    struct rds_connection *conn)
 {
 	struct rds_ib_connection *ic = conn->c_transport_data;
+	int ret = 0;
 
-	/* conn was previously on the nodev_conns_list */
+	/* conn was previously on the nodev_conns_list, unless a teardown
+	 * sweep has claimed it ahead of destroying it: then it is on its
+	 * way out, and its node belongs to the sweep.
+	 */
 	spin_lock_irq(&ib_nodev_conns_lock);
-	BUG_ON(list_empty(&ib_nodev_conns));
-	BUG_ON(list_empty(&ic->ib_node));
-	list_del(&ic->ib_node);
-
 	spin_lock(&rds_ibdev->spinlock);
-	list_add_tail(&ic->ib_node, &rds_ibdev->conn_list);
+	/* rds_ib_dev_shutdown() has walked conn_list, or is about to
+	 * with this lock held: a connection attached now would never be
+	 * dropped by it.  A node a teardown sweep has claimed belongs to
+	 * a connection that sweep is destroying.  Refuse both, and leave
+	 * the node where it is: on the nodev list for the exit sweep to
+	 * find, or on the sweep's own list.
+	 */
+	if (rds_ibdev->shutting_down || ic->i_ib_node_detached) {
+		ret = -ENODEV;
+	} else {
+		list_del(&ic->ib_node);
+		list_add_tail(&ic->ib_node, &rds_ibdev->conn_list);
+	}
 	spin_unlock(&rds_ibdev->spinlock);
 	spin_unlock_irq(&ib_nodev_conns_lock);
+	if (ret)
+		return ret;
 
 	ic->rds_ibdev = rds_ibdev;
 	refcount_inc(&rds_ibdev->refcount);
+
+	return 0;
 }
 
 void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)
 {
 	struct rds_ib_connection *ic = conn->c_transport_data;
 
-	/* place conn on nodev_conns_list */
+	bool detached;
+
+	/* place conn on nodev_conns_list - unless a teardown sweep has
+	 * claimed it ahead of destroying it, in which case its node
+	 * belongs to the sweep
+	 */
 	spin_lock(&ib_nodev_conns_lock);
 
 	spin_lock_irq(&rds_ibdev->spinlock);
-	BUG_ON(list_empty(&ic->ib_node));
-	list_del(&ic->ib_node);
+	detached = ic->i_ib_node_detached;
+	if (!detached)
+		list_del(&ic->ib_node);
 	spin_unlock_irq(&rds_ibdev->spinlock);
 
-	list_add_tail(&ic->ib_node, &ib_nodev_conns);
+	if (!detached)
+		list_add_tail(&ic->ib_node, &ib_nodev_conns);
 
 	spin_unlock(&ib_nodev_conns_lock);
 
@@ -163,13 +187,40 @@ void rds_ib_destroy_nodev_conns(void)
 	struct rds_ib_connection *ic, *_ic;
 	LIST_HEAD(tmp_list);
 
-	/* avoid calling conn_destroy with irqs off */
+	struct rds_connection *conn;
+
+	/* Gather the connections and take a reference on each, so that
+	 * none is freed under the walk below once the deferred frees
+	 * introduced later in the series can drop a connection's last
+	 * reference behind this sweep.  One whose free
+	 * is already running gets no reference: its free unlinks the
+	 * node itself, under this lock, once we drop it.  Marking the
+	 * node detached claims it for this sweep: rds_ib_add_conn(),
+	 * rds_ib_remove_conn() and rds_ib_conn_free() leave a claimed
+	 * node alone, so the walk over tmp_list below needs no lock.
+	 * Avoid calling conn_destroy with irqs off.
+	 */
 	spin_lock_irq(&ib_nodev_conns_lock);
-	list_splice(&ib_nodev_conns, &tmp_list);
+	list_for_each_entry_safe(ic, _ic, &ib_nodev_conns, ib_node) {
+		if (rds_conn_get_unless_zero(ic->conn)) {
+			ic->i_ib_node_detached = true;
+			list_move_tail(&ic->ib_node, &tmp_list);
+		}
+	}
 	spin_unlock_irq(&ib_nodev_conns_lock);
 
-	list_for_each_entry_safe(ic, _ic, &tmp_list, ib_node)
-		rds_conn_destroy(ic->conn);
+	/* rds_conn_destroy() can return before the connection is freed,
+	 * and it is the free - rds_ib_conn_free() - that would unlink
+	 * ib_node.  tmp_list lives on this stack frame, so take each node
+	 * off it before its destroy; the free then leaves it alone.
+	 */
+	list_for_each_entry_safe(ic, _ic, &tmp_list, ib_node) {
+		conn = ic->conn;
+		list_del_init(&ic->ib_node);
+
+		rds_conn_destroy(conn);
+		rds_conn_put(conn);
+	}
 }
 
 void rds_ib_get_mr_info(struct rds_ib_device *rds_ibdev, struct rds_info_rdma_connection *iinfo)
diff --git a/net/rds/ib_recv.c b/net/rds/ib_recv.c
index bd6cb3ffaa571..7d45808544a0d 100644
--- a/net/rds/ib_recv.c
+++ b/net/rds/ib_recv.c
@@ -458,7 +458,11 @@ void rds_ib_recv_refill(struct rds_connection *conn, int prefill, gfp_t gfp)
 	    (must_wake ||
 	    (can_wait && rds_ib_ring_low(&ic->i_recv_ring)) ||
 	    rds_ib_ring_empty(&ic->i_recv_ring))) {
-		queue_delayed_work(conn->c_path->cp_wq, &conn->c_recv_w, 1);
+		rcu_read_lock();
+		if (!rds_destroy_pending(conn))
+			queue_delayed_work(conn->c_path->cp_wq,
+					   &conn->c_recv_w, 1);
+		rcu_read_unlock();
 	}
 	if (can_wait)
 		cond_resched();
diff --git a/net/rds/ib_send.c b/net/rds/ib_send.c
index d6be95542119f..bc411e96ad12d 100644
--- a/net/rds/ib_send.c
+++ b/net/rds/ib_send.c
@@ -298,8 +298,13 @@ void rds_ib_send_cqe_handler(struct rds_ib_connection *ic, struct ib_wc *wc)
 	rds_ib_sub_signaled(ic, nr_sig);
 
 	if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags) ||
-	    test_bit(0, &conn->c_map_queued))
-		queue_delayed_work(conn->c_path->cp_wq, &conn->c_send_w, 0);
+	    test_bit(0, &conn->c_map_queued)) {
+		rcu_read_lock();
+		if (!rds_destroy_pending(conn))
+			queue_delayed_work(conn->c_path->cp_wq,
+					   &conn->c_send_w, 0);
+		rcu_read_unlock();
+	}
 
 	/* We expect errors as the qp is drained during shutdown */
 	if (wc->status != IB_WC_SUCCESS && rds_conn_up(conn)) {
@@ -420,8 +425,13 @@ void rds_ib_send_add_credits(struct rds_connection *conn, unsigned int credits)
 			test_bit(RDS_LL_SEND_FULL, &conn->c_flags) ? ", ll_send_full" : "");
 
 	atomic_add(IB_SET_SEND_CREDITS(credits), &ic->i_credits);
-	if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags))
-		queue_delayed_work(conn->c_path->cp_wq, &conn->c_send_w, 0);
+	if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags)) {
+		rcu_read_lock();
+		if (!rds_destroy_pending(conn))
+			queue_delayed_work(conn->c_path->cp_wq,
+					   &conn->c_send_w, 0);
+		rcu_read_unlock();
+	}
 
 	WARN_ON(IB_GET_SEND_CREDITS(credits) >= 16384);
 
diff --git a/net/rds/loop.c b/net/rds/loop.c
index e6b0750bbedab..5bac858df87ef 100644
--- a/net/rds/loop.c
+++ b/net/rds/loop.c
@@ -156,6 +156,45 @@ static int rds_loop_conn_alloc(struct rds_connection *conn, gfp_t gfp)
 	return 0;
 }
 
+/* Destroy the connections whose nodes were gathered on @tmp_list.
+ *
+ * rds_conn_destroy() can return before the connection is freed, and
+ * it is the free - rds_loop_conn_free() - that unlinks loop_node.
+ * @tmp_list lives on the caller's stack, so unlink each node before
+ * its destroy; the free then finds it empty and leaves it alone.
+ */
+static void rds_loop_destroy_gathered_conns(struct list_head *tmp_list)
+{
+	struct rds_loop_connection *lc, *_lc;
+	struct rds_connection *conn;
+
+	list_for_each_entry_safe(lc, _lc, tmp_list, loop_node) {
+		conn = lc->conn;
+		WARN_ON(rcu_access_pointer(conn->c_passive));
+
+		spin_lock_irq(&loop_conns_lock);
+		list_del_init(&lc->loop_node);
+		spin_unlock_irq(&loop_conns_lock);
+
+		rds_conn_destroy(conn);
+		rds_conn_put(conn);
+	}
+}
+
+/* Gather @lc's connection for destruction: move the node to the
+ * caller's @tmp_list and take a reference that keeps the connection,
+ * and so the node, alive until rds_loop_destroy_gathered_conns() has
+ * dealt with it.  Called with loop_conns_lock held.  A connection
+ * whose free is already running gets no reference; its free unlinks
+ * the node itself, under the same lock, once we drop it.
+ */
+static void rds_loop_gather_conn(struct rds_loop_connection *lc,
+				 struct list_head *tmp_list)
+{
+	if (rds_conn_get_unless_zero(lc->conn))
+		list_move_tail(&lc->loop_node, tmp_list);
+}
+
 static void rds_loop_conn_free(void *arg)
 {
 	struct rds_loop_connection *lc = arg;
@@ -163,7 +202,9 @@ static void rds_loop_conn_free(void *arg)
 
 	rdsdebug("lc %p\n", lc);
 	spin_lock_irqsave(&loop_conns_lock, flags);
-	list_del(&lc->loop_node);
+	/* already unlinked if a transport teardown gathered us first */
+	if (!list_empty(&lc->loop_node))
+		list_del(&lc->loop_node);
 	spin_unlock_irqrestore(&loop_conns_lock, flags);
 	kfree(lc);
 }
@@ -187,14 +228,13 @@ void rds_loop_exit(void)
 	synchronize_rcu();
 	/* avoid calling conn_destroy with irqs off */
 	spin_lock_irq(&loop_conns_lock);
-	list_splice(&loop_conns, &tmp_list);
-	INIT_LIST_HEAD(&loop_conns);
+	list_for_each_entry_safe(lc, _lc, &loop_conns, loop_node)
+		rds_loop_gather_conn(lc, &tmp_list);
 	spin_unlock_irq(&loop_conns_lock);
 
-	list_for_each_entry_safe(lc, _lc, &tmp_list, loop_node) {
-		WARN_ON(lc->conn->c_passive);
-		rds_conn_destroy(lc->conn);
-	}
+	rds_loop_destroy_gathered_conns(&tmp_list);
+
+	rds_conn_wait_conns_freed(&rds_loop_transport, NULL);
 }
 
 static void rds_loop_kill_conns(struct net *net)
@@ -208,14 +248,11 @@ static void rds_loop_kill_conns(struct net *net)
 
 		if (net != c_net)
 			continue;
-		list_move_tail(&lc->loop_node, &tmp_list);
+		rds_loop_gather_conn(lc, &tmp_list);
 	}
 	spin_unlock_irq(&loop_conns_lock);
 
-	list_for_each_entry_safe(lc, _lc, &tmp_list, loop_node) {
-		WARN_ON(lc->conn->c_passive);
-		rds_conn_destroy(lc->conn);
-	}
+	rds_loop_destroy_gathered_conns(&tmp_list);
 }
 
 static void __net_exit rds_loop_exit_net(struct net *net)
diff --git a/net/rds/message.c b/net/rds/message.c
index 47d5e9ab9b109..cea48ad745ca7 100644
--- a/net/rds/message.c
+++ b/net/rds/message.c
@@ -182,6 +182,18 @@ static void rds_message_purge(struct rds_message *rm)
 		kref_put(&rm->atomic.op_rdma_mr->r_kref, __rds_put_mr_final);
 }
 
+static void rds_message_free(struct rds_message *rm)
+{
+	/* get in rds_send_queue_rm(), rds_send_probe() or the congestion
+	 * map path of rds_send_xmit().  Messages that were never queued on
+	 * a connection have no reference to drop.
+	 */
+	if (rm->m_inc.i_conn)
+		rds_conn_put(rm->m_inc.i_conn);
+
+	kfree(rm);
+}
+
 static void rds_message_unpin_worker(struct work_struct *work)
 {
 	struct rds_message *rm = container_of(work, struct rds_message,
@@ -192,7 +204,7 @@ static void rds_message_unpin_worker(struct work_struct *work)
 	if (rm->atomic.op_unpin_deferred)
 		rds_atomic_op_unpin_page(&rm->atomic);
 
-	kfree(rm);
+	rds_message_free(rm);
 }
 
 void rds_message_put(struct rds_message *rm)
@@ -217,7 +229,7 @@ void rds_message_put(struct rds_message *rm)
 			return;
 		}
 
-		kfree(rm);
+		rds_message_free(rm);
 	}
 }
 EXPORT_SYMBOL_GPL(rds_message_put);
diff --git a/net/rds/rdma_transport.c b/net/rds/rdma_transport.c
index 3f853004c4906..a789104725c9a 100644
--- a/net/rds/rdma_transport.c
+++ b/net/rds/rdma_transport.c
@@ -63,6 +63,21 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
 	if (cm_id->device->node_type == RDMA_NODE_IB_CA)
 		trans = &rds_ib_transport;
 
+	/* cm_id->context carries no reference of its own.  Pin the
+	 * connection for the duration of the handler, since the mutex
+	 * released at out: lives in the connection's path array.  None
+	 * of the callbacks below drops a reference on this connection,
+	 * and the shutdown destroys the cm_id - waiting for a running
+	 * handler - before the last reference can go, so this is
+	 * defensive.  A connection already at zero references gets no
+	 * events handled.
+	 */
+	if (conn && !rds_conn_get_unless_zero(conn)) {
+		rdsdebug("conn %p id %p is being freed, ignoring event\n",
+			 conn, cm_id);
+		return 0;
+	}
+
 	/* Prevent shutdown from tearing down the connection
 	 * while we're executing. */
 	if (conn) {
@@ -171,8 +186,10 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
 	}
 
 out:
-	if (conn)
+	if (conn) {
 		mutex_unlock(&conn->c_cm_lock);
+		rds_conn_put(conn);
+	}
 
 	rdsdebug("id %p event %u (%s) handling ret %d\n", cm_id, event->event,
 		 rdma_event_msg(event->event), ret);
diff --git a/net/rds/rds.h b/net/rds/rds.h
index 2db49573dacd5..4c63e5292dd11 100644
--- a/net/rds/rds.h
+++ b/net/rds/rds.h
@@ -89,7 +89,6 @@ enum {
 #define RDS_RECONNECT_PENDING	1
 #define RDS_IN_XMIT		2
 #define RDS_RECV_REFILL		3
-#define	RDS_DESTROY_PENDING	4
 
 /* Max number of multipaths per RDS connection. Must be a power of 2 */
 #define	RDS_MPATH_WORKERS	8
@@ -138,6 +137,12 @@ struct rds_conn_path {
 /* One rds_connection per RDS address pair */
 struct rds_connection {
 	struct hlist_node	c_hash_node;
+	/* rds_conn_destroy() quiesces the connection synchronously;
+	 * freeing it - the connection memory, the path workqueues and
+	 * the transport's per-connection state - is deferred until the
+	 * last reference is dropped via rds_conn_put().
+	 */
+	struct kref		c_refcount;
 	struct in6_addr		c_laddr;
 	struct in6_addr		c_faddr;
 	int			c_dev_if; /* ifindex used for this conn */
@@ -148,7 +153,25 @@ struct rds_connection {
 				c_pad_to_32:29;
 	int			c_npaths;
 	bool			c_with_sport_idx;
-	struct rds_connection	*c_passive;
+	/* Set once, by rds_conn_destroy() under rds_conn_lock - a
+	 * test-and-set, so a second destroy of the same connection
+	 * returns at once - before it cancels the path works.  Read
+	 * through rds_destroy_pending(), which also reports netns
+	 * teardown and module unload; the c_passive handling in
+	 * __rds_conn_create() uses the same predicate, since those rule
+	 * a passive connection out just as well.  A site that arms
+	 * a path work must test the predicate and queue the work inside
+	 * one rcu_read_lock() section: the synchronize_rcu() that
+	 * follows the store is what keeps a queue issued after the
+	 * cancellation from landing on a destroyed workqueue.  Two kinds
+	 * of site are exempt: the workers' own self-requeues, which the
+	 * sync cancel in the destroy path rejects, and the destroy == true
+	 * rds_conn_path_drop(): the destroy issues and flushes it itself,
+	 * and IB device removal issues it ahead of the module exit, which
+	 * destroys - and so flushes - that connection afterwards.
+	 */
+	bool			c_destroy_in_prog;
+	struct rds_connection __rcu *c_passive;
 	struct rds_transport	*c_trans;
 
 	struct rds_cong_map	*c_lcong;
@@ -544,6 +567,12 @@ struct rds_transport {
 	unsigned int		t_prefer_loopback:1,
 				t_mp_capable:1;
 	unsigned int		t_type;
+	/* Connections of this transport not yet freed; freeing runs
+	 * asynchronously once rds_conn_destroy() has quiesced a
+	 * connection, so transport module unload has to wait for this
+	 * to reach zero (rds_conn_wait_conns_freed()).
+	 */
+	atomic_t		t_conn_count;
 
 	int (*laddr_check)(struct net *net, const struct in6_addr *addr,
 			   __u32 scope_id);
@@ -650,7 +679,12 @@ struct rds_sock {
 
 	/*
 	 * rds_sendmsg caches the conn it used the last time around.
-	 * This helps avoid costly lookups.
+	 * This helps avoid costly lookups.  The cache owns a connection
+	 * reference, dropped when it is replaced, when rds_sendmsg()
+	 * evicts a connection whose destroy has begun, or when the
+	 * socket is released, and is read and written under rs_lock -
+	 * except by
+	 * rds_release(), which runs once no one else can reach the socket.
 	 */
 	struct rds_connection	*rs_conn;
 
@@ -659,7 +693,11 @@ struct rds_sock {
 	/* seen congestion (ENOBUFS) when sending? */
 	int			rs_seen_congestion;
 
-	/* rs_lock protects all these adjacent members before the newline */
+	/* rs_lock protects all these adjacent members before the newline,
+	 * as well as rs_conn above and rs_tos at the end of the struct -
+	 * except that rds_sendmsg() samples rs_tos locklessly, with
+	 * READ_ONCE(), for the create, and re-checks it under the lock.
+	 */
 	spinlock_t		rs_lock;
 	struct list_head	rs_send_queue;
 	u32			rs_snd_bytes;
@@ -819,6 +857,21 @@ struct rds_connection *rds_conn_create_outgoing(struct net *net,
 						u8 tos, gfp_t gfp, int dev_if);
 void rds_conn_shutdown(struct rds_conn_path *cpath);
 void rds_conn_destroy(struct rds_connection *conn);
+void rds_conn_get(struct rds_connection *conn);
+void rds_conn_put(struct rds_connection *conn);
+/* take a reference unless the connection is already being freed */
+static inline bool rds_conn_get_unless_zero(struct rds_connection *conn)
+{
+	return kref_get_unless_zero(&conn->c_refcount);
+}
+
+/* transport unload waits for its connections to be freed, polling at
+ * the first interval and warning at the second
+ */
+#define RDS_CONN_FREE_POLL_MS		100
+#define RDS_CONN_FREE_WARN_INTERVAL_MS	10000
+void rds_conn_wait_conns_freed(struct rds_transport *trans,
+			       void (*resweep)(void));
 void rds_conn_drop(struct rds_connection *conn);
 void rds_conn_path_drop(struct rds_conn_path *cpath, bool destroy);
 void rds_conn_connect_if_down(struct rds_connection *conn);
@@ -994,7 +1047,8 @@ void __rds_put_mr_final(struct kref *kref);
 
 static inline bool rds_destroy_pending(struct rds_connection *conn)
 {
-	return !check_net(rds_conn_net(conn)) ||
+	return READ_ONCE(conn->c_destroy_in_prog) ||
+	       !check_net(rds_conn_net(conn)) ||
 	       (conn->c_trans->t_unloading && conn->c_trans->t_unloading(conn));
 }
 
diff --git a/net/rds/recv.c b/net/rds/recv.c
index 6204e577a90ae..9e7e55ca7bd2b 100644
--- a/net/rds/recv.c
+++ b/net/rds/recv.c
@@ -46,6 +46,7 @@ void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn,
 {
 	refcount_set(&inc->i_refcount, 1);
 	INIT_LIST_HEAD(&inc->i_item);
+	rds_conn_get(conn);	/* put in rds_inc_put() */
 	inc->i_conn = conn;
 	inc->i_conn_path = NULL;
 	inc->i_saddr = *saddr;
@@ -61,6 +62,7 @@ void rds_inc_path_init(struct rds_incoming *inc, struct rds_conn_path *cp,
 {
 	refcount_set(&inc->i_refcount, 1);
 	INIT_LIST_HEAD(&inc->i_item);
+	rds_conn_get(cp->cp_conn);	/* put in rds_inc_put() */
 	inc->i_conn = cp->cp_conn;
 	inc->i_conn_path = cp;
 	inc->i_saddr = *saddr;
@@ -81,9 +83,19 @@ void rds_inc_put(struct rds_incoming *inc)
 {
 	rdsdebug("put inc %p ref %d\n", inc, refcount_read(&inc->i_refcount));
 	if (refcount_dec_and_test(&inc->i_refcount)) {
+		struct rds_connection *conn = inc->i_conn;
+
 		BUG_ON(!list_empty(&inc->i_item));
 
-		inc->i_conn->c_trans->inc_free(inc);
+		/* inc_free() can free the memory @inc lives in, so the
+		 * connection reference has to be dropped through the
+		 * copy taken above.
+		 */
+		conn->c_trans->inc_free(inc);
+		/* get in rds_inc_init(), rds_inc_path_init() or
+		 * rds_recv_incoming()
+		 */
+		rds_conn_put(conn);
 	}
 }
 EXPORT_SYMBOL_GPL(rds_inc_put);
@@ -325,6 +337,13 @@ void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,
 	unsigned long flags;
 	struct rds_conn_path *cp;
 
+	/* every caller initialized @inc with rds_inc_init() or
+	 * rds_inc_path_init() first, so i_conn already holds a reference.
+	 * Take the new one before dropping the old, so that re-pointing an
+	 * inc at the connection it already refers to cannot free it.
+	 */
+	rds_conn_get(conn);
+	rds_conn_put(inc->i_conn);
 	inc->i_conn = conn;
 	inc->i_rx_jiffies = jiffies;
 	if (conn->c_trans->t_mp_capable)
@@ -406,8 +425,9 @@ void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,
 	 * rds_find_bound() uses a global (netns-agnostic) hash table.
 	 * An RDS connection created in netns A can match a socket bound
 	 * in the init netns, delivering inc cross-netns with inc->i_conn
-	 * pointing into netns A.  When cleanup_net() then frees that conn,
-	 * any subsequent dereference of inc->i_conn is a use-after-free.
+	 * pointing into netns A.  Cross-netns delivery is wrong on its
+	 * own, and the inc's connection reference would keep a
+	 * connection of a dead netns around, with a stale c_net.
 	 * Drop the inc if the receiving socket lives in a different netns.
 	 */
 	if (!net_eq(sock_net(rds_rs_to_sk(rs)), rds_conn_net(conn))) {
@@ -482,7 +502,6 @@ static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc,
 	if (!list_empty(&inc->i_item)) {
 		ret = 1;
 		if (drop) {
-			/* XXX make sure this i_conn is reliable */
 			rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
 					      -be32_to_cpu(inc->i_hdr.h_len),
 					      inc->i_hdr.h_dport);
diff --git a/net/rds/send.c b/net/rds/send.c
index 1afa981e5c06d..4ec9931599c5d 100644
--- a/net/rds/send.c
+++ b/net/rds/send.c
@@ -290,6 +290,8 @@ int rds_send_xmit(struct rds_conn_path *cp)
 			}
 			rm->data.op_active = 1;
 			rm->m_inc.i_conn_path = cp;
+			/* put in rds_message_put() */
+			rds_conn_get(cp->cp_conn);
 			rm->m_inc.i_conn = cp->cp_conn;
 
 			cp->cp_xmit_rm = rm;
@@ -947,6 +949,7 @@ static int rds_send_queue_rm(struct rds_sock *rs, struct rds_connection *conn,
 		/* The code ordering is a little weird, but we're
 		   trying to minimize the time we hold c_lock */
 		rds_message_populate_header(&rm->m_inc.i_hdr, sport, dport, 0);
+		rds_conn_get(conn);	/* put in rds_message_put() */
 		rm->m_inc.i_conn = conn;
 		rm->m_inc.i_conn_path = cp;
 		rds_message_addref(rm);
@@ -1159,13 +1162,14 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
 	__be16 dport;
 	struct rds_message *rm = NULL;
-	struct rds_connection *conn;
+	struct rds_connection *conn = NULL;
 	int ret = 0;
 	int queued = 0, allocated_mr = 0;
 	int nonblock = msg->msg_flags & MSG_DONTWAIT;
 	long timeo = sock_sndtimeo(sk, nonblock);
 	struct rds_conn_path *cpath;
 	struct in6_addr daddr;
+	unsigned long flags;
 	__u32 scope_id = 0;
 	size_t rdma_payload_len = 0;
 	bool zcopy = ((msg->msg_flags & MSG_ZEROCOPY) &&
@@ -1340,21 +1344,68 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 	rm->m_daddr = daddr;
 
 	/* rds_conn_create has a spinlock that runs with IRQ off.
-	 * Caching the conn in the socket helps a lot. */
-	if (rs->rs_conn && ipv6_addr_equal(&rs->rs_conn->c_faddr, &daddr) &&
-	    rs->rs_tos == rs->rs_conn->c_tos) {
-		conn = rs->rs_conn;
+	 * Caching the conn in the socket helps a lot.
+	 *
+	 * The cached rs_conn holds a connection reference; take one of
+	 * our own for the duration of this call (dropped on both exit
+	 * paths), so that neither a concurrent sender replacing the
+	 * cache nor rds_conn_destroy() can free the connection under
+	 * us.  A cached connection whose destruction has begun is not
+	 * reused: it is evicted here, and this call goes on to look up
+	 * or create a live one instead of returning -EAGAIN forever.
+	 */
+	spin_lock_irqsave(&rs->rs_lock, flags);
+	conn = rs->rs_conn;
+	if (conn && rds_destroy_pending(conn)) {
+		/* drop the cache's reference right here, or the socket
+		 * would pin the quiesced connection until it is closed
+		 */
+		rs->rs_conn = NULL;
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
+		rds_conn_put(conn);
+		conn = NULL;
 	} else {
+		if (conn && ipv6_addr_equal(&conn->c_faddr, &daddr) &&
+		    rs->rs_tos == conn->c_tos)
+			rds_conn_get(conn);
+		else
+			conn = NULL;
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
+	}
+
+	if (!conn) {
+		struct rds_connection *old;
+
 		conn = rds_conn_create_outgoing(sock_net(sock->sk),
 						&rs->rs_bound_addr, &daddr,
-						rs->rs_transport, rs->rs_tos,
+						rs->rs_transport,
+						READ_ONCE(rs->rs_tos),
 						sock->sk->sk_allocation,
 						scope_id);
 		if (IS_ERR(conn)) {
 			ret = PTR_ERR(conn);
+			conn = NULL;
 			goto out;
 		}
+		/* rs_tos was sampled without rs_lock for the create above,
+		 * and SIOCRDSSETTOS only refuses a change once rs_conn is
+		 * set, so it can have changed underneath us.  Do not
+		 * install - or send on - a connection whose ToS no longer
+		 * matches the socket's; the retry uses the new one.
+		 */
+		spin_lock_irqsave(&rs->rs_lock, flags);
+		if (conn->c_tos != rs->rs_tos) {
+			spin_unlock_irqrestore(&rs->rs_lock, flags);
+			ret = -EAGAIN;
+			goto out;
+		}
+		/* hand the cache its own reference */
+		rds_conn_get(conn);
+		old = rs->rs_conn;
 		rs->rs_conn = conn;
+		spin_unlock_irqrestore(&rs->rs_lock, flags);
+		if (old)
+			rds_conn_put(old);
 	}
 
 	if (conn->c_trans->t_mp_capable) {
@@ -1378,9 +1429,14 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		 * outstanding.
 		 */
 		if (!test_and_set_bit(RDS_RECONNECT_PENDING,
-				      &conn->c_path[0].cp_flags))
-			queue_delayed_work(conn->c_path[0].cp_wq,
-					   &conn->c_path[0].cp_conn_w, 0);
+				      &conn->c_path[0].cp_flags)) {
+			rcu_read_lock();
+			if (!rds_destroy_pending(conn))
+				queue_delayed_work(conn->c_path[0].cp_wq,
+						   &conn->c_path[0].cp_conn_w,
+						   0);
+			rcu_read_unlock();
+		}
 		rds_send_ping(conn, 0);
 	}
 
@@ -1469,6 +1525,8 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		kfree(vct.vec[ind].iov);
 	kfree(vct.vec);
 
+	rds_conn_put(conn);
+
 	return payload_len;
 
 out:
@@ -1476,6 +1534,9 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		kfree(vct.vec[ind].iov);
 	kfree(vct.vec);
 
+	if (conn)
+		rds_conn_put(conn);
+
 	/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.
 	 * If the sendmsg goes through, we keep the MR. If it fails with EAGAIN
 	 * or in any other way, we need to destroy the MR again */
@@ -1522,6 +1583,7 @@ rds_send_probe(struct rds_conn_path *cp, __be16 sport,
 	list_add_tail(&rm->m_conn_item, &cp->cp_send_queue);
 	set_bit(RDS_MSG_ON_CONN, &rm->m_flags);
 	rds_message_addref(rm);
+	rds_conn_get(cp->cp_conn);	/* put in rds_message_put() */
 	rm->m_inc.i_conn = cp->cp_conn;
 	rm->m_inc.i_conn_path = cp;
 
diff --git a/net/rds/tcp.c b/net/rds/tcp.c
index 774a71f88d375..552b32278e30d 100644
--- a/net/rds/tcp.c
+++ b/net/rds/tcp.c
@@ -502,6 +502,48 @@ static bool rds_tcp_is_unloading(struct rds_connection *conn)
 	return atomic_read(&rds_tcp_unloading) != 0;
 }
 
+/* Gather @tc's connection for destruction: move the node to the
+ * caller's @tmp_list and take a reference that keeps the connection,
+ * and so the node, alive until rds_tcp_destroy_gathered_conns() has
+ * dealt with it.  Called with rds_tcp_conn_lock held.  A connection
+ * whose free is already running gets no reference; its free unlinks
+ * the node itself, under the same lock, once we drop it.
+ */
+static void rds_tcp_gather_conn(struct rds_tcp_connection *tc,
+				struct list_head *tmp_list)
+{
+	if (rds_conn_get_unless_zero(tc->t_cpath->cp_conn))
+		list_move_tail(&tc->t_tcp_node, tmp_list);
+}
+
+/* Destroy the connections whose nodes were gathered on @tmp_list.
+ *
+ * rds_conn_destroy() can return before the connection is freed, and
+ * it is the free - rds_tcp_conn_free() - that unlinks t_tcp_node.
+ * Since @tmp_list lives on the caller's stack, unlink each node here
+ * and mark it detached before its destroy, so that a free that runs
+ * after the caller has returned does not write into a dead frame.
+ * Every entry holds a reference taken by rds_tcp_gather_conn(), so
+ * none can be freed under the walk; each is dropped after its destroy.
+ */
+static void rds_tcp_destroy_gathered_conns(struct list_head *tmp_list)
+{
+	struct rds_tcp_connection *tc, *_tc;
+	struct rds_connection *conn;
+
+	list_for_each_entry_safe(tc, _tc, tmp_list, t_tcp_node) {
+		conn = tc->t_cpath->cp_conn;
+
+		spin_lock_irq(&rds_tcp_conn_lock);
+		list_del_init(&tc->t_tcp_node);
+		tc->t_tcp_node_detached = true;
+		spin_unlock_irq(&rds_tcp_conn_lock);
+
+		rds_conn_destroy(conn);
+		rds_conn_put(conn);
+	}
+}
+
 static void rds_tcp_destroy_conns(void)
 {
 	struct rds_tcp_connection *tc, *_tc;
@@ -511,12 +553,11 @@ static void rds_tcp_destroy_conns(void)
 	spin_lock_irq(&rds_tcp_conn_lock);
 	list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
 		if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn))
-			list_move_tail(&tc->t_tcp_node, &tmp_list);
+			rds_tcp_gather_conn(tc, &tmp_list);
 	}
 	spin_unlock_irq(&rds_tcp_conn_lock);
 
-	list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
-		rds_conn_destroy(tc->t_cpath->cp_conn);
+	rds_tcp_destroy_gathered_conns(&tmp_list);
 }
 
 static void rds_tcp_exit(void);
@@ -691,15 +732,14 @@ static void rds_tcp_kill_sock(struct net *net)
 		if (net != c_net)
 			continue;
 		if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
-			list_move_tail(&tc->t_tcp_node, &tmp_list);
+			rds_tcp_gather_conn(tc, &tmp_list);
 		} else {
 			list_del(&tc->t_tcp_node);
 			tc->t_tcp_node_detached = true;
 		}
 	}
 	spin_unlock_irq(&rds_tcp_conn_lock);
-	list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
-		rds_conn_destroy(tc->t_cpath->cp_conn);
+	rds_tcp_destroy_gathered_conns(&tmp_list);
 }
 
 static void __net_exit rds_tcp_exit_net(struct net *net)
@@ -805,6 +845,7 @@ static void rds_tcp_exit(void)
 #endif
 	unregister_pernet_device(&rds_tcp_net_ops);
 	rds_tcp_destroy_conns();
+	rds_conn_wait_conns_freed(&rds_tcp_transport, NULL);
 	rds_trans_unregister(&rds_tcp_transport);
 	rds_tcp_recv_exit();
 	kmem_cache_destroy(rds_tcp_conn_slab);
diff --git a/net/rds/tcp_listen.c b/net/rds/tcp_listen.c
index 13fa60c1985bb..bb4f01c071693 100644
--- a/net/rds/tcp_listen.c
+++ b/net/rds/tcp_listen.c
@@ -153,7 +153,7 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 {
 	struct socket *listen_sock = rtn->rds_tcp_listen_sock;
 	struct socket *new_sock = NULL;
-	struct rds_connection *conn;
+	struct rds_connection *conn = NULL;
 	int ret;
 	struct inet_sock *inet;
 	struct rds_tcp_connection *rs_tcp = NULL;
@@ -229,6 +229,7 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 
 	if (IS_ERR(conn)) {
 		ret = PTR_ERR(conn);
+		conn = NULL;
 		goto out;
 	}
 	/* An incoming SYN request came in, and TCP just accepted it.
@@ -277,6 +278,13 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 	cp = rs_tcp->t_cpath;
 	conn_state = rds_conn_path_state(cp);
 	WARN_ON(conn_state == RDS_CONN_UP);
+	/* A connection whose destroy has begun cannot be found here:
+	 * TCP connections are only destroyed on netns teardown and on
+	 * module unload, and both go through rds_tcp_kill_sock() - which
+	 * clears the listen socket that the top of this function tests
+	 * and then flushes this work in rds_tcp_listen_stop() - before
+	 * any connection is destroyed.
+	 */
 	if (conn_state != RDS_CONN_CONNECTING && conn_state != RDS_CONN_ERROR) {
 		rds_conn_path_drop(cp, 0);
 		goto rst_nsk;
@@ -316,10 +324,14 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 	 */
 	if (READ_ONCE(sk->sk_state) == TCP_CLOSE_WAIT ||
 	    READ_ONCE(sk->sk_state) == TCP_LAST_ACK ||
-	    READ_ONCE(sk->sk_state) == TCP_CLOSE)
+	    READ_ONCE(sk->sk_state) == TCP_CLOSE) {
 		rds_conn_path_drop(cp, 0);
-	else
-		queue_delayed_work(cp->cp_wq, &cp->cp_recv_w, 0);
+	} else {
+		rcu_read_lock();
+		if (!rds_destroy_pending(cp->cp_conn))
+			queue_delayed_work(cp->cp_wq, &cp->cp_recv_w, 0);
+		rcu_read_unlock();
+	}
 
 	sock_put(sk);
 
@@ -343,6 +355,8 @@ int rds_tcp_accept_one(struct rds_tcp_net *rtn)
 		mutex_unlock(&rs_tcp->t_conn_path_lock);
 	if (new_sock)
 		sock_release(new_sock);
+	if (conn)
+		rds_conn_put(conn);
 
 	mutex_unlock(&rtn->rds_tcp_accept_lock);
 

19/3 2026/10/08 03:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25192
							output: 31
							thoughts: 1658
						

Thoughts:
**KMSAN Evaluation for net/rds Patch**

Okay, let's break this down. My task is to determine if this patch to net/rds necessitates a dedicated KMSAN fuzzing session, or if KASAN and other standard bug detectors are sufficient. The guiding principle is clear: KMSAN is for catching *uninitialized memory reads*, specifically those missed by KASAN and other tools. Given the cost of a KMSAN session, I need to be sure.

First, I need to understand what this patch actually *does*. I've reviewed the commit diff, and it seems to revolve around several key changes: refcounting of `rds_connection` structs using `kref`, deferred freeing of these connections, more robust handling of transport connections, and some locking and RCU improvements. There are changes across a large number of files, touching connection management, IB, TCP, and message handling, indicating a potentially complex interaction.

The most critical area of concern, based on my expert knowledge, is where data is passed *to* user space, where conditional logic hinges on potentially uninitialized fields, where new structures are allocated, or where bounds checks might expose uninitialized memory. Let's analyze.

I've examined the `rds_ioctl` function, specifically the `SIOCRDSGETTOS` case. Here, a `tos` value is read from `rs->rs_tos` and copied to user space using `put_user`. Crucially, `tos` itself is explicitly initialized to 0. The key question is whether `rs->rs_tos` itself is initialized *before* being read. This warrants further investigation to understand how an `rds_sock` is allocated and initialized. I need to find the allocation and initialization path of the `rds_sock` and look into how the `rs->rs_tos` is set during allocation and/or initialization.

This is a good start, but my analysis isn't complete yet. I still need to go through *every single change* in the patch and identify any other instance of data being sent to user space, any conditional logic with potentially uninitialized dependencies, or any allocation/initialization of data structures where uninitialized fields could be read later. I'll need to pay particularly close attention to the new refcounting logic. I'm going to start by grepping the kernel sources to understand how `rds_sock` is allocated, initialized, and associated with `rs->rs_tos`. If this is safe, that should cover the first potential vector, which is data being copied from the kernel to the user.



20/3 2026/10/08 03:41 tool grepper
0m Args:
{
  "Expression": "rds_sk_to_rs",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/af_rds.c=59=static int rds_release(struct socket *sock)\n--\nnet/rds/af_rds.c-66-\nnet/rds/af_rds.c:67:\trs = rds_sk_to_rs(sk);\nnet/rds/af_rds.c-68-\n--\nnet/rds/af_rds.c=121=static int rds_getname(struct socket *sock, struct sockaddr *uaddr,\n--\nnet/rds/af_rds.c-123-{\nnet/rds/af_rds.c:124:\tstruct rds_sock *rs = rds_sk_to_rs(sock-\u003esk);\nnet/rds/af_rds.c-125-\tstruct sockaddr_in6 *sin6;\n--\nnet/rds/af_rds.c=219=static __poll_t rds_poll(struct file *file, struct socket *sock,\n--\nnet/rds/af_rds.c-222-\tstruct sock *sk = sock-\u003esk;\nnet/rds/af_rds.c:223:\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/af_rds.c-224-\t__poll_t mask = 0;\n--\nnet/rds/af_rds.c=262=static int rds_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)\nnet/rds/af_rds.c-263-{\nnet/rds/af_rds.c:264:\tstruct rds_sock *rs = rds_sk_to_rs(sock-\u003esk);\nnet/rds/af_rds.c-265-\trds_tos_t utos, tos = 0;\n--\nnet/rds/af_rds.c=450=static int rds_setsockopt(struct socket *sock, int level, int optname,\n--\nnet/rds/af_rds.c-452-{\nnet/rds/af_rds.c:453:\tstruct rds_sock *rs = rds_sk_to_rs(sock-\u003esk);\nnet/rds/af_rds.c-454-\tstruct net *net = sock_net(sock-\u003esk);\n--\nnet/rds/af_rds.c=502=static int rds_getsockopt(struct socket *sock, int level, int optname,\n--\nnet/rds/af_rds.c-504-{\nnet/rds/af_rds.c:505:\tstruct rds_sock *rs = rds_sk_to_rs(sock-\u003esk);\nnet/rds/af_rds.c-506-\tint ret = -ENOPROTOOPT, len;\n--\nnet/rds/af_rds.c=558=static int rds_connect(struct socket *sock, struct sockaddr_unsized *uaddr,\n--\nnet/rds/af_rds.c-562-\tstruct sockaddr_in *sin;\nnet/rds/af_rds.c:563:\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/af_rds.c-564-\tint ret = 0;\n--\nnet/rds/af_rds.c=680=static void rds_sock_destruct(struct sock *sk)\nnet/rds/af_rds.c-681-{\nnet/rds/af_rds.c:682:\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/af_rds.c-683-\n--\nnet/rds/af_rds.c=688=static int __rds_create(struct socket *sock, struct sock *sk, int protocol)\n--\nnet/rds/af_rds.c-696-\nnet/rds/af_rds.c:697:\trs = rds_sk_to_rs(sk);\nnet/rds/af_rds.c-698-\tspin_lock_init(\u0026rs-\u003ers_lock);\n--\nnet/rds/bind.c=163=int rds_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len)\n--\nnet/rds/bind.c-165-\tstruct sock *sk = sock-\u003esk;\nnet/rds/bind.c:166:\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/bind.c-167-\tstruct in6_addr v6addr, *binding_addr;\n--\nnet/rds/rds.h=658=struct rds_sock {\n--\nnet/rds/rds.h-742-\nnet/rds/rds.h:743:static inline struct rds_sock *rds_sk_to_rs(const struct sock *sk)\nnet/rds/rds.h-744-{\n--\nnet/rds/recv.c=708=int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,\n--\nnet/rds/recv.c-711-\tstruct sock *sk = sock-\u003esk;\nnet/rds/recv.c:712:\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/recv.c-713-\tlong timeo;\n--\nnet/rds/send.c=1157=int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n--\nnet/rds/send.c-1159-\tstruct sock *sk = sock-\u003esk;\nnet/rds/send.c:1160:\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/send.c-1161-\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\n"
}

21/3 2026/10/08 03:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28904
							output: 27
							thoughts: 17
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Analyzing `rds_create` and `struct sock` Allocation**

Okay, let's dive into how the `struct sock` is allocated within the `rds_create` function. I need to refresh my memory on the specifics of this allocation strategy. Is it a direct `kmalloc`? Does it involve any caching mechanisms, perhaps a per-CPU slab allocator for performance? Or maybe it's using some custom memory management scheme specific to the RDS implementation?

I'm particularly interested in any subtle nuances that might impact performance or resource utilization, things like alignment considerations, potential fragmentation issues, or interactions with NUMA nodes. I should also check if there are any specific flags used with the memory allocation – `GFP_KERNEL`, `GFP_ATOMIC`, and so on. Understanding these flags will be crucial for figuring out how the allocation behaves under different system load conditions. I also want to make sure no memory leaks are happening during creation and destruction of the object.



22/3 2026/10/08 03:41 tool grepper
0m Args:
{
  "Expression": "sk_alloc",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/af_rds.c=718=static int rds_create(struct net *net, struct socket *sock, int protocol,\n--\nnet/rds/af_rds.c-725-\nnet/rds/af_rds.c:726:\tsk = sk_alloc(net, AF_RDS, GFP_KERNEL, \u0026rds_proto, kern);\nnet/rds/af_rds.c-727-\tif (!sk)\n--\nnet/rds/send.c=1157=int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n--\nnet/rds/send.c-1382-\t\t\t\t\t\tREAD_ONCE(rs-\u003ers_tos),\nnet/rds/send.c:1383:\t\t\t\t\t\tsock-\u003esk-\u003esk_allocation,\nnet/rds/send.c-1384-\t\t\t\t\t\tscope_id);\n"
}

23/3 2026/10/08 03:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29401
							output: 35
							thoughts: 350
						

Thoughts:
**Analyzing RDS Socket and Connection Creation**

Okay, so `sk_alloc` is initializing the socket structure, using either `sk_prot_alloc` which seems to be wrapped around `kmem_cache_alloc` and `sk_prot_free`, or a simple `memset` to zero it out, specifically with `sk_init_common`. Makes sense, standard initialization.

Now, I'm looking at the `SIOCRDSGETTOS` and `SIOCRDSSETTOS` ioctls within `rds_ioctl`.  The key change here is moving from a global `rds_sock_lock` to the socket's individual lock, `rs->rs_lock`, which is a good, more granular locking strategy.  The data transfer to user space remains identical, using `put_user`.  That's a definite improvement; less contention.

Next, I need to understand the connection creation. I need to see where the `struct rds_connection` is being allocated. I'll need to check the `__rds_conn_create` function. I think it is within the `net/rds/connection.c` file, around lines 200-280. Time to get down into the code.



24/3 2026/10/08 03:42 tool read-file
0m Args:
{
  "File": "net/rds/connection.c",
  "FirstLine": 205,
  "LineCount": 50
}

Results:
{
  "Contents": " 205:\t * system at a time.  They contain messages to be retransmitted and so\n 206:\t * span the lifetime of the actual underlying transport connections.\n 207:\t *\n 208:\t * For now they are not garbage collected once they're created.  They\n 209:\t * are torn down as the module is removed, if ever.\n 210:\t */\n 211:\tstatic struct rds_connection *__rds_conn_create(struct net *net,\n 212:\t\t\t\t\t\t\tconst struct in6_addr *laddr,\n 213:\t\t\t\t\t\t\tconst struct in6_addr *faddr,\n 214:\t\t\t\t\t\t\tstruct rds_transport *trans,\n 215:\t\t\t\t\t\t\tgfp_t gfp, u8 tos,\n 216:\t\t\t\t\t\t\tint is_outgoing,\n 217:\t\t\t\t\t\t\tint dev_if)\n 218:\t{\n 219:\t\tstruct rds_connection *conn, *parent = NULL;\n 220:\t\tstruct hlist_head *head = rds_conn_bucket(laddr, faddr);\n 221:\t\tstruct rds_transport *loop_trans;\n 222:\t\tstruct rds_conn_path *free_cp = NULL;\n 223:\t\tunsigned long flags;\n 224:\t\tint ret, i;\n 225:\t\tint npaths = (trans-\u003et_mp_capable ? RDS_MPATH_WORKERS : 1);\n 226:\t\n 227:\t\trcu_read_lock();\n 228:\t\tconn = rds_conn_lookup(net, head, laddr, faddr, trans, tos, dev_if);\n 229:\t\tif (conn \u0026\u0026\n 230:\t\t    conn-\u003ec_loopback \u0026\u0026\n 231:\t\t    conn-\u003ec_trans != \u0026rds_loop_transport \u0026\u0026\n 232:\t\t    ipv6_addr_equal(laddr, faddr) \u0026\u0026\n 233:\t\t    !is_outgoing) {\n 234:\t\t\t/* This is a looped back IB connection, and we're\n 235:\t\t\t * called by the code handling the incoming connect.\n 236:\t\t\t * We need a second connection object into which we\n 237:\t\t\t * can stick the other QP. */\n 238:\t\t\tparent = conn;\n 239:\t\t\t/* The c_passive pointer holds a reference which is only\n 240:\t\t\t * dropped one synchronize_rcu() after the pointer is\n 241:\t\t\t * cleared, so within this RCU section a fetched pointer\n 242:\t\t\t * is always safe to take a reference on.  A passive conn\n 243:\t\t\t * whose own destroy has begun is not handed out, though:\n 244:\t\t\t * it is quiesced and about to clear the parent's pointer\n 245:\t\t\t * itself, and reusing it would re-arm a connection that\n 246:\t\t\t * nothing will tear down again.\n 247:\t\t\t */\n 248:\t\t\tconn = rcu_dereference(parent-\u003ec_passive);\n 249:\t\t\tif (conn \u0026\u0026 rds_destroy_pending(conn))\n 250:\t\t\t\tconn = NULL;\n 251:\t\t\tif (conn)\n 252:\t\t\t\trds_conn_get(conn);\n 253:\t\t}\n 254:\t\trcu_read_unlock();\n"
}

25/3 2026/10/08 03:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30909
							output: 35
							thoughts: 15
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Diving Deeper into Connection Creation**

Alright, so the clue is in `__rds_conn_create`. That's where it all begins, and where I need to focus my attention. It’s the obvious next step – I need to understand the connection initialization flow. There’s a good chance the root cause is hidden somewhere within that function's logic. Let's trace through it carefully. I'm going to start with a systematic examination of the code and variables in that section. Time to get down into the details of the connection management.



26/3 2026/10/08 03:43 tool read-file
0m Args:
{
  "File": "net/rds/connection.c",
  "FirstLine": 255,
  "LineCount": 60
}

Results:
{
  "Contents": " 255:\t\tif (conn)\n 256:\t\t\tgoto out;\n 257:\t\n 258:\t\tconn = kmem_cache_zalloc(rds_conn_slab, gfp);\n 259:\t\tif (!conn) {\n 260:\t\t\tconn = ERR_PTR(-ENOMEM);\n 261:\t\t\tgoto out;\n 262:\t\t}\n 263:\t\tconn-\u003ec_path = kzalloc_objs(struct rds_conn_path, npaths, gfp);\n 264:\t\tif (!conn-\u003ec_path) {\n 265:\t\t\tkmem_cache_free(rds_conn_slab, conn);\n 266:\t\t\tconn = ERR_PTR(-ENOMEM);\n 267:\t\t\tgoto out;\n 268:\t\t}\n 269:\t\n 270:\t\tkref_init(\u0026conn-\u003ec_refcount);\n 271:\t\tINIT_HLIST_NODE(\u0026conn-\u003ec_hash_node);\n 272:\t\tconn-\u003ec_laddr = *laddr;\n 273:\t\tconn-\u003ec_isv6 = !ipv6_addr_v4mapped(laddr);\n 274:\t\tconn-\u003ec_faddr = *faddr;\n 275:\t\tconn-\u003ec_dev_if = dev_if;\n 276:\t\tconn-\u003ec_tos = tos;\n 277:\t\n 278:\t#if IS_ENABLED(CONFIG_IPV6)\n 279:\t\t/* If the local address is link local, set c_bound_if to be the\n 280:\t\t * index used for this connection.  Otherwise, set it to 0 as\n 281:\t\t * the socket is not bound to an interface.  c_bound_if is used\n 282:\t\t * to look up a socket when a packet is received\n 283:\t\t */\n 284:\t\tif (ipv6_addr_type(laddr) \u0026 IPV6_ADDR_LINKLOCAL)\n 285:\t\t\tconn-\u003ec_bound_if = dev_if;\n 286:\t\telse\n 287:\t#endif\n 288:\t\t\tconn-\u003ec_bound_if = 0;\n 289:\t\n 290:\t\trds_conn_net_set(conn, net);\n 291:\t\n 292:\t\tret = rds_cong_get_maps(conn);\n 293:\t\tif (ret) {\n 294:\t\t\tkfree(conn-\u003ec_path);\n 295:\t\t\tkmem_cache_free(rds_conn_slab, conn);\n 296:\t\t\tconn = ERR_PTR(ret);\n 297:\t\t\tgoto out;\n 298:\t\t}\n 299:\t\n 300:\t\t/*\n 301:\t\t * This is where a connection becomes loopback.  If *any* RDS sockets\n 302:\t\t * can bind to the destination address then we'd rather the messages\n 303:\t\t * flow through loopback rather than either transport.\n 304:\t\t */\n 305:\t\tloop_trans = rds_trans_get_preferred(net, faddr, conn-\u003ec_dev_if);\n 306:\t\tif (loop_trans) {\n 307:\t\t\trds_trans_put(loop_trans);\n 308:\t\t\tconn-\u003ec_loopback = 1;\n 309:\t\t\tif (trans-\u003et_prefer_loopback) {\n 310:\t\t\t\tif (likely(is_outgoing)) {\n 311:\t\t\t\t\t/* \"outgoing\" connection to local address.\n 312:\t\t\t\t\t * Protocol says it wants the connection\n 313:\t\t\t\t\t * handled by the loopback transport.\n 314:\t\t\t\t\t * This is what TCP does.\n"
}

27/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32071
							output: 29
							thoughts: 173
						

Thoughts:
**Investigating Potential Data Corruption in RDS Connection Allocation**

Okay, so I'm seeing `kmem_cache_zalloc` and `kzalloc_objs` used, both zero-allocating functions, which is good. But it makes me wonder about the other `struct` allocations within the RDS connection code. Are there any potential uninitialized memory reads lurking? I need to make sure everything is properly zeroed out where it matters.

I should check if anything new was allocated or if any existing allocations have been modified. I'm focusing on `net/rds/connection.c` first. Ah, here's something: `alloc_ordered_workqueue`. The format string changed from `%lu/%d` to `%d/%d`. That's not the critical piece, though. The important thing is that `seq` is an `int`, read from an `atomic_t t_conn_count`. Hold on a second, is that `atomic_t` properly initialized within `struct rds_transport`? That's the key question. I need to go back and trace where `struct rds_transport` is defined and initialized. That's the next step; I need to follow the data.



28/3 2026/10/08 03:43 tool grepper
0m Args:
{
  "Expression": "rds_.*_transport",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 405 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (21 files in total):\nnet/rds/Makefile:1\nnet/rds/af_rds.c:3\nnet/rds/connection.c:7\nnet/rds/ib.c:8\nnet/rds/ib.h:1\nnet/rds/ib_cm.c:11\nnet/rds/ib_rdma.c:2\nnet/rds/ib_recv.c:5\nnet/rds/ib_send.c:6\nnet/rds/loop.c:3\nnet/rds/loop.h:1\nnet/rds/rdma_transport.c:1\nnet/rds/rdma_transport.h:1\nnet/rds/rds.h:5\nnet/rds/tcp.c:7\nnet/rds/tcp.h:1\nnet/rds/tcp_connect.c:3\nnet/rds/tcp_listen.c:1\nnet/rds/tcp_recv.c:3\nnet/rds/tcp_send.c:3\nnet/rds/transport.c:5\n\nnet/rds/Makefile=7=obj-$(CONFIG_RDS_RDMA) += rds_rdma.o\nnet/rds/Makefile:8:rds_rdma-y :=\trdma_transport.o \\\nnet/rds/Makefile-9-\t\t\tib.o ib_cm.o ib_recv.o ib_ring.o ib_send.o ib_stats.o \\\n--\nnet/rds/af_rds.c=59=static int rds_release(struct socket *sock)\n--\nnet/rds/af_rds.c-94-\nnet/rds/af_rds.c:95:\trds_trans_put(rs-\u003ers_transport);\nnet/rds/af_rds.c-96-\n--\nnet/rds/af_rds.c=356=static int rds_cong_monitor(struct rds_sock *rs, sockptr_t optval, int optlen)\n--\nnet/rds/af_rds.c-372-\nnet/rds/af_rds.c:373:static int rds_set_transport(struct net *net, struct rds_sock *rs,\nnet/rds/af_rds.c-374-\t\t\t     sockptr_t optval, int optlen)\n--\nnet/rds/af_rds.c=450=static int rds_setsockopt(struct socket *sock, int level, int optname,\n--\nnet/rds/af_rds.c-482-\t\tlock_sock(sock-\u003esk);\nnet/rds/af_rds.c:483:\t\tret = rds_set_transport(net, rs, optval, optlen);\nnet/rds/af_rds.c-484-\t\trelease_sock(sock-\u003esk);\n--\nnet/rds/connection.c=181=rds_conn_passive_locked(struct rds_connection *conn)\n--\nnet/rds/connection.c-189- */\nnet/rds/connection.c:190:static void rds_conn_free_transport_data(struct rds_connection *conn,\nnet/rds/connection.c-191-\t\t\t\t\t int npaths)\n--\nnet/rds/connection.c=211=static struct rds_connection *__rds_conn_create(struct net *net,\n--\nnet/rds/connection.c-230-\t    conn-\u003ec_loopback \u0026\u0026\nnet/rds/connection.c:231:\t    conn-\u003ec_trans != \u0026rds_loop_transport \u0026\u0026\nnet/rds/connection.c-232-\t    ipv6_addr_equal(laddr, faddr) \u0026\u0026\n--\nnet/rds/connection.c-315-\t\t\t\t */\nnet/rds/connection.c:316:\t\t\t\ttrans = \u0026rds_loop_transport;\nnet/rds/connection.c-317-\t\t\t} else {\n--\nnet/rds/connection.c-383-\t\t\t */\nnet/rds/connection.c:384:\t\t\trds_conn_free_transport_data(conn, npaths);\nnet/rds/connection.c-385-\t\t\tfree_cp = conn-\u003ec_path;\n--\nnet/rds/connection.c-391-\t\t\tpassive = rds_conn_passive_locked(parent);\nnet/rds/connection.c:392:\t\t\trds_conn_free_transport_data(conn, npaths);\nnet/rds/connection.c-393-\t\t\tfree_cp = conn-\u003ec_path;\n--\nnet/rds/connection.c-423-\t\tif (found) {\nnet/rds/connection.c:424:\t\t\trds_conn_free_transport_data(conn, npaths);\nnet/rds/connection.c-425-\t\t\tfree_cp = conn-\u003ec_path;\n--\nnet/rds/connection.c=679=static void rds_conn_destroy_fini(struct kref *kref)\n--\nnet/rds/connection.c-714- */\nnet/rds/connection.c:715:void rds_conn_wait_conns_freed(struct rds_transport *trans,\nnet/rds/connection.c-716-\t\t\t       void (*resweep)(void))\n--\nnet/rds/ib.c=297=static int rds_ib_conn_info_visitor(struct rds_connection *conn,\n--\nnet/rds/ib.c-300-\tstruct rds_info_rdma_connection *iinfo = buffer;\nnet/rds/ib.c:301:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib.c-302-\nnet/rds/ib.c-303-\t/* We will only ever look at IB transports */\nnet/rds/ib.c:304:\tif (conn-\u003ec_trans != \u0026rds_ib_transport)\nnet/rds/ib.c-305-\t\treturn 0;\n--\nnet/rds/ib.c=336=static int rds6_ib_conn_info_visitor(struct rds_connection *conn,\n--\nnet/rds/ib.c-339-\tstruct rds6_info_rdma_connection *iinfo6 = buffer;\nnet/rds/ib.c:340:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib.c-341-\nnet/rds/ib.c-342-\t/* We will only ever look at IB transports */\nnet/rds/ib.c:343:\tif (conn-\u003ec_trans != \u0026rds_ib_transport)\nnet/rds/ib.c-344-\t\treturn 0;\n--\nnet/rds/ib.c=534=void rds_ib_exit(void)\n--\nnet/rds/ib.c-550-\trds_ib_destroy_nodev_conns();\nnet/rds/ib.c:551:\trds_conn_wait_conns_freed(\u0026rds_ib_transport,\nnet/rds/ib.c-552-\t\t\t\t  rds_ib_destroy_nodev_conns);\n--\nnet/rds/ib.c-562-\trds_ib_recv_exit();\nnet/rds/ib.c:563:\trds_trans_unregister(\u0026rds_ib_transport);\nnet/rds/ib.c-564-\trds_ib_mr_exit();\n--\nnet/rds/ib.c=567=static u8 rds_ib_get_tos_map(u8 tos)\n--\nnet/rds/ib.c-575-\nnet/rds/ib.c:576:struct rds_transport rds_ib_transport = {\nnet/rds/ib.c-577-\t.laddr_check\t\t= rds_ib_laddr_check,\n--\nnet/rds/ib.c=605=int rds_ib_init(void)\n--\nnet/rds/ib.c-626-\nnet/rds/ib.c:627:\trds_trans_register(\u0026rds_ib_transport);\nnet/rds/ib.c-628-\n--\nnet/rds/ib.h=348=static inline void rds_ib_dma_sync_sg_for_device(struct ib_device *dev,\n--\nnet/rds/ib.h-364-/* ib.c */\nnet/rds/ib.h:365:extern struct rds_transport rds_ib_transport;\nnet/rds/ib.h-366-struct rds_ib_device *rds_ib_get_client_data(struct ib_device *device);\n--\nnet/rds/ib_cm.c=57=static void rds_ib_set_flow_control(struct rds_connection *conn, u32 credits)\nnet/rds/ib_cm.c-58-{\nnet/rds/ib_cm.c:59:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-60-\n--\nnet/rds/ib_cm.c=74=void rds_ib_cm_connect_complete(struct rds_connection *conn, struct rdma_cm_event *event)\nnet/rds/ib_cm.c-75-{\nnet/rds/ib_cm.c:76:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-77-\tconst union rds_ib_conn_priv *dp = NULL;\n--\nnet/rds/ib_cm.c=163=static void rds_ib_cm_fill_conn_param(struct rds_connection *conn,\n--\nnet/rds/ib_cm.c-170-{\nnet/rds/ib_cm.c:171:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-172-\tstruct rds_ib_device *rds_ibdev = ic-\u003erds_ibdev;\n--\nnet/rds/ib_cm.c=247=static void rds_ib_cq_comp_handler_recv(struct ib_cq *cq, void *context)\n--\nnet/rds/ib_cm.c-249-\tstruct rds_connection *conn = context;\nnet/rds/ib_cm.c:250:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-251-\n--\nnet/rds/ib_cm.c=354=static void rds_ib_qp_event_handler(struct ib_event *event, void *data)\n--\nnet/rds/ib_cm.c-356-\tstruct rds_connection *conn = data;\nnet/rds/ib_cm.c:357:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-358-\n--\nnet/rds/ib_cm.c=375=static void rds_ib_cq_comp_handler_send(struct ib_cq *cq, void *context)\n--\nnet/rds/ib_cm.c-377-\tstruct rds_connection *conn = context;\nnet/rds/ib_cm.c:378:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-379-\n--\nnet/rds/ib_cm.c=502=static int rds_ib_setup_qp(struct rds_connection *conn)\nnet/rds/ib_cm.c-503-{\nnet/rds/ib_cm.c:504:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-505-\tstruct ib_device *dev = ic-\u003ei_cm_id-\u003edevice;\n--\nnet/rds/ib_cm.c=785=int rds_ib_cm_handle_connect(struct rdma_cm_id *cm_id,\n--\nnet/rds/ib_cm.c-862-\tconn = rds_conn_create(\u0026init_net, daddr6, saddr6,\nnet/rds/ib_cm.c:863:\t\t\t       \u0026rds_ib_transport, dp_cmn-\u003ericpc_dp_toss,\nnet/rds/ib_cm.c-864-\t\t\t       GFP_KERNEL, ifindex);\n--\nnet/rds/ib_cm.c=954=int rds_ib_cm_initiate_connect(struct rdma_cm_id *cm_id, bool isv6)\n--\nnet/rds/ib_cm.c-956-\tstruct rds_connection *conn = cm_id-\u003econtext;\nnet/rds/ib_cm.c:957:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-958-\tstruct rdma_conn_param conn_param;\n--\nnet/rds/ib_cm.c=1088=static unsigned long rds_ib_conn_path_shutdown_check_wait(struct rds_conn_path *cp)\n--\nnet/rds/ib_cm.c-1090-\tstruct rds_connection *conn = cp-\u003ecp_conn;\nnet/rds/ib_cm.c:1091:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-1092-\n--\nnet/rds/ib_cm.c=1106=void rds_ib_conn_path_shutdown(struct rds_conn_path *cp)\n--\nnet/rds/ib_cm.c-1108-\tstruct rds_connection *conn = cp-\u003ecp_conn;\nnet/rds/ib_cm.c:1109:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_cm.c-1110-\tint err = 0;\n--\nnet/rds/ib_rdma.c=122=int rds_ib_add_conn(struct rds_ib_device *rds_ibdev,\n--\nnet/rds/ib_rdma.c-124-{\nnet/rds/ib_rdma.c:125:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_rdma.c-126-\tint ret = 0;\n--\nnet/rds/ib_rdma.c=158=void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)\nnet/rds/ib_rdma.c-159-{\nnet/rds/ib_rdma.c:160:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_rdma.c-161-\n--\nnet/rds/ib_recv.c=204=void rds_ib_inc_free(struct rds_incoming *inc)\n--\nnet/rds/ib_recv.c-208-\tstruct rds_page_frag *pos;\nnet/rds/ib_recv.c:209:\tstruct rds_ib_connection *ic = inc-\u003ei_conn-\u003ec_transport_data;\nnet/rds/ib_recv.c-210-\n--\nnet/rds/ib_recv.c=308=static int rds_ib_recv_refill_one(struct rds_connection *conn,\n--\nnet/rds/ib_recv.c-310-{\nnet/rds/ib_recv.c:311:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_recv.c-312-\tstruct ib_sge *sge;\n--\nnet/rds/ib_recv.c=382=void rds_ib_recv_refill(struct rds_connection *conn, int prefill, gfp_t gfp)\nnet/rds/ib_recv.c-383-{\nnet/rds/ib_recv.c:384:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_recv.c-385-\tstruct rds_ib_recv_work *recv;\n--\nnet/rds/ib_recv.c=854=static void rds_ib_process_recv(struct rds_connection *conn,\n--\nnet/rds/ib_recv.c-857-{\nnet/rds/ib_recv.c:858:\tstruct rds_ib_connection *ic = conn-\u003ec_transport_data;\nnet/rds/ib_recv.c-859-\tstruct rds_ib_incoming *ibinc = ic-\u003ei_ibinc;\n--\nnet/rds/ib_recv.c=1047=int rds_ib_recv_path(struct rds_conn_path *cp)\n\n"
}

29/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36834
							output: 31
							thoughts: 208
						

Thoughts:
Okay, here's my understanding, formatted as requested:

**Digging into RDS IB Transport Initialization and State**

Right, let me see... I'm looking at these `struct rds_transport` definitions, specifically how they are initialized. I remember these things, like `rds_ib_transport = { ... };` in `net/rds/ib.c`, are static global structs. Because they're static in C, they're allocated to the BSS segment, so initially, `t_conn_count` will be 0, of course. That's good to keep in mind.

Now, I need to understand the additions that were made to `struct rds_ib_connection` and `struct rds_ib_device`. So, in `net/rds/ib.h`, I see:

```c
struct rds_ib_connection {
...
	bool			i_ib_node_detached;
```

And:

```c
struct rds_ib_device {
...
	bool			shutting_down;
```

Interesting. I need to figure out how these structures, `rds_ib_connection` and `rds_ib_device`, are actually allocated. Are they dynamically allocated? Or maybe statically? Need to check. So, the next step is to search the code base for how these structures are allocated. That should give me a good handle on how these new boolean flags are managed throughout the lifecycle of the connections and devices.



30/3 2026/10/08 03:43 tool grepper
0m Args:
{
  "Expression": "kzalloc.*rds_ib_",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/ib.c=133=static int rds_ib_add_one(struct ib_device *device)\n--\nnet/rds/ib.c-145-\nnet/rds/ib.c:146:\trds_ibdev = kzalloc_node(sizeof(struct rds_ib_device), GFP_KERNEL,\nnet/rds/ib.c-147-\t\t\t\t ibdev_to_node(device));\n--\nnet/rds/ib_cm.c=1264=int rds_ib_conn_alloc(struct rds_connection *conn, gfp_t gfp)\n--\nnet/rds/ib_cm.c-1270-\t/* XXX too lazy? */\nnet/rds/ib_cm.c:1271:\tic = kzalloc_obj(struct rds_ib_connection, gfp);\nnet/rds/ib_cm.c-1272-\tif (!ic)\n"
}

31/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37635
							output: 31
							thoughts: 100
						

Thoughts:
Okay, here's my breakdown of this logic, as if I were thinking it through:

**Zero-Allocation Initialization Considerations**

Right, let's see, `kzalloc_node` and `kzalloc_obj` are both clearly zero-allocating functions. That means `i_ib_node_detached` and `shutting_down`, as initialized by those calls, should start at a value of 0. That much seems straightforward.

But hang on, there's a loose end. What about this `t_tcp_node_detached`? It's not immediately obvious how that is initialized. I recall seeing that variable used in the RDS TCP code...

Okay, a quick search... yep, there it is in `net/rds/tcp.c`: `tc->t_tcp_node_detached = true;`. So that variable is being explicitly set to `true`, not zero. Alright, now I need to trace back and determine how `rds_tcp_connection` is allocated, so I know where `t_tcp_node_detached` is being set.



32/3 2026/10/08 03:43 tool grepper
0m Args:
{
  "Expression": "rds_tcp_conn_alloc",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/tcp.c=427=static void rds_tcp_conn_free(void *arg)\n--\nnet/rds/tcp.c-441-\nnet/rds/tcp.c:442:static int rds_tcp_conn_alloc(struct rds_connection *conn, gfp_t gfp)\nnet/rds/tcp.c-443-{\n--\nnet/rds/tcp.c=571=struct rds_transport rds_tcp_transport = {\n--\nnet/rds/tcp.c-576-\t.recv_path\t\t= rds_tcp_recv_path,\nnet/rds/tcp.c:577:\t.conn_alloc\t\t= rds_tcp_conn_alloc,\nnet/rds/tcp.c-578-\t.conn_free\t\t= rds_tcp_conn_free,\n"
}

33/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38222
							output: 35
							thoughts: 23
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Diving into `rds_tcp_conn_alloc`**

Right, let's get down to brass tacks. I'm going to jump into `net/rds/tcp.c` and specifically focus on the `rds_tcp_conn_alloc` function. I know this is where the meat of RDS TCP connection allocation resides. I'm likely looking for the usual suspects: memory allocation, socket creation, initialization of the `rds_tcp_connection` structure, potential error handling, and the handoff to the lower TCP layers. I'm expecting to see calls to `kmalloc`, `sock_create`, `rds_conn_init` (or similar), and of course, a careful dance with the return values. I'll be particularly keen to see how they're handling potential resource exhaustion or errors during the setup phase – things like socket creation failures or memory allocation issues. I want to understand how robust this allocation process is and how it deals with contention if the system is under load. I'll also be watching out for any potential race conditions that might exist. I'm looking for thread-safety and how they ensure a clean connection setup. I'll probably be paying attention to any specific parameters passed in, such as flags or options, that might influence the behavior of the connection creation.



34/3 2026/10/08 03:43 tool read-file
0m Args:
{
  "File": "net/rds/tcp.c",
  "FirstLine": 442,
  "LineCount": 30
}

Results:
{
  "Contents": " 442:\tstatic int rds_tcp_conn_alloc(struct rds_connection *conn, gfp_t gfp)\n 443:\t{\n 444:\t\tstruct rds_tcp_connection *tc;\n 445:\t\tint i, j;\n 446:\t\tint ret = 0;\n 447:\t\n 448:\t\tfor (i = 0; i \u003c RDS_MPATH_WORKERS; i++) {\n 449:\t\t\ttc = kmem_cache_zalloc(rds_tcp_conn_slab, gfp);\n 450:\t\t\tif (!tc) {\n 451:\t\t\t\tret = -ENOMEM;\n 452:\t\t\t\tgoto fail;\n 453:\t\t\t}\n 454:\t\t\tmutex_init(\u0026tc-\u003et_conn_path_lock);\n 455:\t\t\ttc-\u003et_sock = NULL;\n 456:\t\t\ttc-\u003et_rtn = NULL;\n 457:\t\t\ttc-\u003et_tinc = NULL;\n 458:\t\t\ttc-\u003et_tinc_hdr_rem = sizeof(struct rds_header);\n 459:\t\t\ttc-\u003et_tinc_data_rem = 0;\n 460:\t\t\tinit_waitqueue_head(\u0026tc-\u003et_recv_done_waitq);\n 461:\t\n 462:\t\t\tconn-\u003ec_path[i].cp_transport_data = tc;\n 463:\t\t\ttc-\u003et_cpath = \u0026conn-\u003ec_path[i];\n 464:\t\t\ttc-\u003et_tcp_node_detached = true;\n 465:\t\n 466:\t\t\trdsdebug(\"rds_conn_path [%d] tc %p\\n\", i,\n 467:\t\t\t\t conn-\u003ec_path[i].cp_transport_data);\n 468:\t\t}\n 469:\t\tspin_lock_irq(\u0026rds_tcp_conn_lock);\n 470:\t\tfor (i = 0; i \u003c RDS_MPATH_WORKERS; i++) {\n 471:\t\t\ttc = conn-\u003ec_path[i].cp_transport_data;\n"
}

35/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39129
							output: 31
							thoughts: 48
						

Thoughts:
Okay, let's see, I'm looking at this `kmem_cache_zalloc` call with `rds_tcp_conn_slab` and a `gfp` flag. My mind immediately jumps to a potential parallel. Is this function call analogous to how we allocate and initialize `rds_loop_connection` structures? We need to verify how `rds_loop_conn_alloc` handles its memory. I want to make sure the memory allocation strategy and initialization are consistent across these connection types. Time to dive into the `rds_loop_conn_alloc` function. I need to understand if they use the same mechanism or if there are any subtle but important differences. Let's see...



36/3 2026/10/08 03:43 tool grepper
0m Args:
{
  "Expression": "rds_loop_conn_alloc",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/loop.c=128=struct rds_loop_connection {\n--\nnet/rds/loop.c-138- */\nnet/rds/loop.c:139:static int rds_loop_conn_alloc(struct rds_connection *conn, gfp_t gfp)\nnet/rds/loop.c-140-{\n--\nnet/rds/loop.c=283=struct rds_transport rds_loop_transport = {\n--\nnet/rds/loop.c-285-\t.recv_path\t\t= rds_loop_recv_path,\nnet/rds/loop.c:286:\t.conn_alloc\t\t= rds_loop_conn_alloc,\nnet/rds/loop.c-287-\t.conn_free\t\t= rds_loop_conn_free,\n"
}

37/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39574
							output: 35
							thoughts: 23
						

Thoughts:
Okay, let's dive into this. Here's my summary, taking the first-person perspective as requested:

**Diving into `rds_loop_conn_alloc`**

Right, time to get my hands dirty. I need to take a look at `rds_loop_conn_alloc`. My gut tells me it's probably in `net/rds/loop.c`. Let's confirm that and get to the code. I need to understand how these connections are being allocated within the RDS loopback mechanism. Given my expertise, I suspect this is where the core connection management for the loopback driver lives, so this is a good place to start my investigation. I'm expecting to find the connection setup details, resource allocation, and any associated initialization routines. This is where I'll get a clearer picture of how RDS handles loopback communication at the fundamental level.



38/3 2026/10/08 03:43 tool read-file
0m Args:
{
  "File": "net/rds/loop.c",
  "FirstLine": 139,
  "LineCount": 25
}

Results:
{
  "Contents": " 139:\tstatic int rds_loop_conn_alloc(struct rds_connection *conn, gfp_t gfp)\n 140:\t{\n 141:\t\tstruct rds_loop_connection *lc;\n 142:\t\tunsigned long flags;\n 143:\t\n 144:\t\tlc = kzalloc_obj(struct rds_loop_connection, gfp);\n 145:\t\tif (!lc)\n 146:\t\t\treturn -ENOMEM;\n 147:\t\n 148:\t\tINIT_LIST_HEAD(\u0026lc-\u003eloop_node);\n 149:\t\tlc-\u003econn = conn;\n 150:\t\tconn-\u003ec_transport_data = lc;\n 151:\t\n 152:\t\tspin_lock_irqsave(\u0026loop_conns_lock, flags);\n 153:\t\tlist_add_tail(\u0026lc-\u003eloop_node, \u0026loop_conns);\n 154:\t\tspin_unlock_irqrestore(\u0026loop_conns_lock, flags);\n 155:\t\n 156:\t\treturn 0;\n 157:\t}\n 158:\t\n 159:\t/* Destroy the connections whose nodes were gathered on @tmp_list.\n 160:\t *\n 161:\t * rds_conn_destroy() can return before the connection is freed, and\n 162:\t * it is the free - rds_loop_conn_free() - that unlinks loop_node.\n 163:\t * @tmp_list lives on the caller's stack, so unlink each node before\n"
}

39/3 2026/10/08 03:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40232
							output: 29
							thoughts: 1222
						

Thoughts:
**Analyzing a Concurrency Fix for rds_connection Lifetime**

Okay, so I'm looking at this patch for the RDS connection management, specifically dealing with potential lifetime issues.  My first thought is always to start with the fundamental building blocks.  Let's see: `kzalloc` is used, and the crucial structure is `rds_connection`. I need to review this structure's fields in `rds.h`.  I see `c_hash_node`, `c_refcount` (initialized with `kref_init`), `c_destroy_in_prog` (starts at false), and a potential passive connection.  The connection itself gets memory via `kmem_cache_zalloc`, meaning zeroed memory, which is good.  `c_destroy_in_prog` being false initially is exactly what I'd expect.

Now, what is this patch *actually* doing to address the problems?  It's flagged as a concurrency fix, dealing with use-after-free, double-free scenarios, workqueue synchronization, and module unloading.  The commit log indicates several key changes:  synchronous quiescing in `rds_conn_destroy` to prevent premature freeing, deferring the final free to `rds_conn_destroy_fini` when the reference count hits zero.  Critically, they've introduced explicit `kref_get` / `kref_put` operations (`rds_conn_get`, `rds_conn_put`) for reference counting, and are caching connections, which is a classic refcounting strategy to handle the socket lifetimes properly. They're also protecting the `rs_conn` and `rs_tos` with `rs->rs_lock`, which is a good design practice.  The patch seems to prevent queueing work on path workqueues after destroy began and is ensuring all connections are freed before transport unload.  These are textbook concurrency fixes – the sorts of things KASAN and LOCKDEP would usually catch.

The critical question now: Does this patch introduce a *NeedsKMSAN=true* condition?  I need to go through the four criteria *very* carefully.

1.  **Kernel structures to userspace with uninitialized fields?** Let's see. In `rds_ioctl`, the patch modifies a spinlock around accessing `rs->rs_tos` (which is a `u8`, an 8-bit unsigned integer). Looking at the code:  `tos` is initialized to 0, and `rs->rs_tos` is a `u8`.  The `rs` socket is also allocated using `sk_alloc`, which guarantees zeroed memory. Therefore, no uninitialized data is going to userspace.

2.  **Conditional logic based on uninitialized data?** Let's review the variables: `rs->rs_conn` and `rs->rs_tos` are initialized to 0; `conn->c_destroy_in_prog` is initialized to 0 by `kmem_cache_zalloc`; `trans->t_conn_count` is statically initialized to 0; and `rds_destroy_pending(conn)` is checking `c_destroy_in_prog`, the networking context, and the unloading flag. The other variables are either allocated with zeroed memory (kzalloc) or properly initialized. The important piece is `passive` which can be NULL or a valid connection pointer. We should check this again when we dive in to the code. We need to follow where it can be set. It seems all of the variables checked are initialized.

3.  **Allocation of complex data structures with uninitialized fields?** I need to check the allocation code, specifically `rds_message_alloc` to see what is initialized, though this seems unlikely given my review of the code.

4.  **Bounds checks exposing uninitialized memory?** This seems unlikely given the nature of the patch, focusing on reference counts and locks.

Therefore, *based on my analysis so far*, I don't see anything that triggers `NeedsKMSAN=true`. It's a clean concurrency fix without the introduction of uninitialized memory exposure to userspace. However, I want to confirm that `rds_message_alloc` is using zeroed memory as a final check. I need to track down how `rds_message_alloc` allocates memory to confirm that any fields in `rm` aren't read before initialization. I'll need to go back and check.



40/3 2026/10/08 03:44 tool grepper
0m Args:
{
  "Expression": "rds_message_alloc",
  "PathPrefixes": [
    "net/rds"
  ]
}

Results:
{
  "Output": "net/rds/message.c=365=EXPORT_SYMBOL_GPL(rds_message_add_rdma_dest_extension);\n--\nnet/rds/message.c-371- */\nnet/rds/message.c:372:struct rds_message *rds_message_alloc(unsigned int extra_len, gfp_t gfp)\nnet/rds/message.c-373-{\n--\nnet/rds/message.c-398- */\nnet/rds/message.c:399:struct scatterlist *rds_message_alloc_sgs(struct rds_message *rm, int nents)\nnet/rds/message.c-400-{\n--\nnet/rds/message.c=422=struct rds_message *rds_message_map_pages(unsigned long *page_addrs, unsigned int total_len)\n--\nnet/rds/message.c-428-\nnet/rds/message.c:429:\trm = rds_message_alloc(extra_bytes, GFP_NOWAIT);\nnet/rds/message.c-430-\tif (!rm)\n--\nnet/rds/message.c-435-\trm-\u003edata.op_nents = DIV_ROUND_UP(total_len, PAGE_SIZE);\nnet/rds/message.c:436:\trm-\u003edata.op_sg = rds_message_alloc_sgs(rm, num_sgs);\nnet/rds/message.c-437-\tif (IS_ERR(rm-\u003edata.op_sg)) {\n--\nnet/rds/rdma.c=637=int rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm,\n--\nnet/rds/rdma.c-697-\tWARN_ON(!nr_pages);\nnet/rds/rdma.c:698:\top-\u003eop_sg = rds_message_alloc_sgs(rm, nr_pages);\nnet/rds/rdma.c-699-\tif (IS_ERR(op-\u003eop_sg)) {\n--\nnet/rds/rdma.c=900=int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n--\nnet/rds/rdma.c-946-\trm-\u003eatomic.op_recverr = rs-\u003ers_recverr;\nnet/rds/rdma.c:947:\trm-\u003eatomic.op_sg = rds_message_alloc_sgs(rm, 1);\nnet/rds/rdma.c-948-\tif (IS_ERR(rm-\u003eatomic.op_sg)) {\n--\nnet/rds/rds.h=944=rds_conn_connecting(struct rds_connection *conn)\n--\nnet/rds/rds.h-950-/* message.c */\nnet/rds/rds.h:951:struct rds_message *rds_message_alloc(unsigned int nents, gfp_t gfp);\nnet/rds/rds.h:952:struct scatterlist *rds_message_alloc_sgs(struct rds_message *rm, int nents);\nnet/rds/rds.h-953-int rds_message_copy_from_user(struct rds_message *rm, struct iov_iter *from,\n--\nnet/rds/send.c=1157=int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n--\nnet/rds/send.c-1324-\nnet/rds/send.c:1325:\trm = rds_message_alloc(ret, GFP_KERNEL);\nnet/rds/send.c-1326-\tif (!rm) {\n--\nnet/rds/send.c-1332-\tif (payload_len) {\nnet/rds/send.c:1333:\t\trm-\u003edata.op_sg = rds_message_alloc_sgs(rm, num_sgs);\nnet/rds/send.c-1334-\t\tif (IS_ERR(rm-\u003edata.op_sg)) {\n--\nnet/rds/send.c=1560=rds_send_probe(struct rds_conn_path *cp, __be16 sport,\n--\nnet/rds/send.c-1566-\nnet/rds/send.c:1567:\trm = rds_message_alloc(0, GFP_ATOMIC);\nnet/rds/send.c-1568-\tif (!rm) {\n"
}

41/3 2026/10/08 03:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43573
							output: 35
							thoughts: 21
						

Thoughts:
Here's my summary, as if I were thinking these thoughts:

**Analyzing `rds_message_alloc` in `net/rds/message.c`**

Okay, time to dive into the core of how RDS messages are handled. I need to refresh my understanding of the allocation process. Let's start by looking at `rds_message_alloc` within `net/rds/message.c`. This function is fundamental to the RDS protocol, so getting a solid grasp of its workings is crucial for understanding message flow and potential bottlenecks. I'll focus on how it manages memory, handles different message types, and integrates with the overall RDS architecture. My aim is to spot any areas that might warrant further investigation or optimization, or to simply ensure my mental model of this part of the code is accurate.



42/3 2026/10/08 03:44 tool read-file
0m Args:
{
  "File": "net/rds/message.c",
  "FirstLine": 372,
  "LineCount": 25
}

Results:
{
  "Contents": " 372:\tstruct rds_message *rds_message_alloc(unsigned int extra_len, gfp_t gfp)\n 373:\t{\n 374:\t\tstruct rds_message *rm;\n 375:\t\n 376:\t\tif (extra_len \u003e KMALLOC_MAX_SIZE - sizeof(struct rds_message))\n 377:\t\t\treturn NULL;\n 378:\t\n 379:\t\trm = kzalloc(sizeof(struct rds_message) + extra_len, gfp);\n 380:\t\tif (!rm)\n 381:\t\t\tgoto out;\n 382:\t\n 383:\t\trm-\u003em_used_sgs = 0;\n 384:\t\trm-\u003em_total_sgs = extra_len / sizeof(struct scatterlist);\n 385:\t\n 386:\t\trefcount_set(\u0026rm-\u003em_refcount, 1);\n 387:\t\tINIT_LIST_HEAD(\u0026rm-\u003em_sock_item);\n 388:\t\tINIT_LIST_HEAD(\u0026rm-\u003em_conn_item);\n 389:\t\tspin_lock_init(\u0026rm-\u003em_rs_lock);\n 390:\t\tinit_waitqueue_head(\u0026rm-\u003em_flush_wait);\n 391:\t\n 392:\tout:\n 393:\t\treturn rm;\n 394:\t}\n 395:\t\n 396:\t/*\n"
}

43/3 2026/10/08 03:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44181
							output: 519
							thoughts: 1511
						

Thoughts:
**KMSAN Assessment: No Need for Dedicated Session**

Okay, let's break this down. My initial thought is that `rm` is allocated with `kzalloc`, so `rm->m_inc.i_conn` is, of course, initialized to NULL (zero). That's a good starting point. Now, to make a clear decision, I need to methodically check against the KMSAN guidance.

First, criterion 3, the one about allocation and initialization of complex data structures where uninitialized fields *could* be read. Right, so I'm looking at those data structures: `rds_connection`, `rds_conn_path`, `rds_message`, `rds_ib_connection`, `rds_ib_device`, `rds_tcp_connection`, `rds_loop_connection`, and `rds_sock`. They are all allocated with `kzalloc`, `kmem_cache_zalloc`, or `sk_alloc`. That immediately sets my mind at ease, as these functions inherently zero out the allocated memory. The patch *only* introduces or updates fields within these already zeroed structures. I verify this carefully: `c_refcount` is initialized with `kref_init`. `c_destroy_in_prog` is a bool, zeroed by `kzalloc` and only *written* once. `t_conn_count` is an atomic_t in a static global, initialized to zero. `i_ib_node_detached` and `shutting_down` are bools, zeroed, and `t_tcp_node_detached` is a bool initialized in `rds_tcp_conn_alloc` to `true`. So far, so good: no uninitialized data being created.

Next, I need to check criterion 4, looking for bounds checks, lengths, or logic that would allow access to uninitialized bytes of existing buffers. This is where I have to be particularly thorough. I methodically go through the changes in `connection.c`: the change to `alloc_ordered_workqueue` is just string formatting, no impact. Then I review `rds_conn_free_transport_data` - it's freeing `cp->cp_transport_data` for a range of `i`, completely safe. Then the important part: changes within `rds_ib_send_add_credits`, `rds_ib_send_cqe_handler`, `rds_ib_recv_refill`, `rds_sendmsg` and `rds_tcp_accept_one`. These look like added `rcu_read_lock()` checks around the workqueue queueing, with a `rds_destroy_pending(conn)` check. This is *critical* - it's dealing with races. But it doesn't change any bounds checks, length calculations, or indexing into buffers. It's solely to prevent work from being scheduled on a connection that is in the process of being destroyed.

Now, let's consider what bugs this patch series *does* target or could potentially introduce. This boils down to reference counting, handling use-after-free or double frees (memory management) on different data structures, deadlocks, and races during transport connection teardown or module unload. These are all concurrency and lifecycle issues that KASAN and LOCKDEP are designed to catch!

And here's the key point: *none* of these bug types are specifically uninitialized memory bugs or leaks of information to user space. KASAN/LOCKDEP are perfectly adequate for detecting the critical issues related to concurrency and memory management. No specific KMSAN analysis is needed here.

Looking back to the guidance again, it's clear: "NeedsKMSAN=false" is the correct choice. The code changes primarily address out-of-bounds, NULL pointer dereferences, locking deadlocks, and use-after-free bugs. It's all about concurrency and lifecycle management. All structures touched by the patch are fully zeroed or initialized, and there's no risk of uninitialized memory usage or info leaks. The KMSAN flag should be false.

Therefore, for the KMSANReasoning, I would lay it out like this for `set-results`:
1.  Explain patch changes: Refcounting `struct rds_connection`, synchronizing connection lifecycle during shutdown and module unload, workqueue scheduling, and adjustments to locking.
2.  Analyze uninitialized memory risks: New and modified fields checked, and allocated via `kzalloc`, `kmem_cache_zalloc`, `sk_alloc`, or are BSS objects. No user copies of uninitialized memory. No changes to buffer handling.
3.  Contrast with KASAN / LOCKDEP: KASAN, LOCKDEP, and standard tools handle the lifetime tracking, synchronization, and race condition fixes. KMSAN not needed.

Time to invoke the `set


44/3 2026/10/08 03:45 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch addresses lifetime management, reference counting, and teardown synchronization for RDS connections (`struct rds_connection`) across the core RDS subsystem and its transport implementations (IB, TCP, and loopback). Specifically, it introduces refcounting via `kref` on `rds_connection`, handles deferred destruction once all holders (including sockets, queued messages, and incoming datagrams) release their references, synchronizes transport unload waiting for all connection instances to be freed, and uses `c_destroy_in_prog` to guard against queuing work on quiesced workqueues.\n\nFrom a memory sanitization perspective:\n1. **Uninitialized Memory \u0026 Info-leaks (KMSAN):**\n   - All newly added and modified struct fields (`c_refcount`, `c_destroy_in_prog`, `t_conn_count`, `i_ib_node_detached`, `shutting_down`, `t_tcp_node_detached`) reside in objects that are allocated via `kzalloc`, `kmem_cache_zalloc`, or `sk_alloc` (all zero-initialized), or in static BSS data (`struct rds_transport`).\n   - The user-copy site touched by the patch is `put_user(tos, ...)` in `rds_ioctl(SIOCRDSGETTOS)`, where `tos` is explicitly initialized (`tos = 0`) and read from zero-initialized socket state (`rs-\u003ers_tos`). No struct padding or kernel data leaks to userspace are introduced.\n   - The patch does not modify packet parsing, bounds checking, buffer length computations, or payload copying in any way that could expose uninitialized memory.\n\n2. **Memory Safety \u0026 Concurrency (KASAN / LOCKDEP):**\n   - The risks associated with these changes are use-after-free (e.g. incorrect refcounting or premature connection cleanup), double free, concurrency races, and locking deadlocks (e.g. `rs_lock`, `rds_conn_lock`, `cp_lock`).\n   - These classes of defects are already detected by KASAN, LOCKDEP, and standard debugging checks in the default KASAN fuzzing build.\n\nBecause there are no uninitialized memory reads or info-leak risks that would uniquely require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch addresses lifetime management, reference counting, and teardown synchronization for RDS connections (`struct rds_connection`) across the core RDS subsystem and its transport implementations (IB, TCP, and loopback). Specifically, it introduces refcounting via `kref` on `rds_connection`, handles deferred destruction once all holders (including sockets, queued messages, and incoming datagrams) release their references, synchronizes transport unload waiting for all connection instances to be freed, and uses `c_destroy_in_prog` to guard against queuing work on quiesced workqueues.\n\nFrom a memory sanitization perspective:\n1. **Uninitialized Memory \u0026 Info-leaks (KMSAN):**\n   - All newly added and modified struct fields (`c_refcount`, `c_destroy_in_prog`, `t_conn_count`, `i_ib_node_detached`, `shutting_down`, `t_tcp_node_detached`) reside in objects that are allocated via `kzalloc`, `kmem_cache_zalloc`, or `sk_alloc` (all zero-initialized), or in static BSS data (`struct rds_transport`).\n   - The user-copy site touched by the patch is `put_user(tos, ...)` in `rds_ioctl(SIOCRDSGETTOS)`, where `tos` is explicitly initialized (`tos = 0`) and read from zero-initialized socket state (`rs-\u003ers_tos`). No struct padding or kernel data leaks to userspace are introduced.\n   - The patch does not modify packet parsing, bounds checking, buffer length computations, or payload copying in any way that could expose uninitialized memory.\n\n2. **Memory Safety \u0026 Concurrency (KASAN / LOCKDEP):**\n   - The risks associated with these changes are use-after-free (e.g. incorrect refcounting or premature connection cleanup), double free, concurrency races, and locking deadlocks (e.g. `rs_lock`, `rds_conn_lock`, `cp_lock`).\n   - These classes of defects are already detected by KASAN, LOCKDEP, and standard debugging checks in the default KASAN fuzzing build.\n\nBecause there are no uninitialized memory reads or info-leak risks that would uniquely require KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)