Skip to contentSkip to conversation

sunrpc: Reduce lock contention for NFSD TCP sockets

RFC PATCH Superseded Chuck Lever 2 participants 11 messages Feb 5 – Mar 30

Subsystems (4)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Chuck Lever

author maintainer
#0 lore raw

cover sunrpc: Reduce lock contention for NFSD TCP sockets

From: Chuck Lever <[email protected]>

High-throughput NFSD workloads exhibit significant lock contention on TCP connections. Worker threads compete for the socket lock during receives and serialize on xpt_mutex during sends, limiting scalability.

This series addresses both paths:

- Receive: A dedicated kernel thread per TCP connection owns all sock_recvmsg() calls and queues complete RPC messages for workers via lock-free llist. This eliminates socket lock contention among workers.

- Transmit: Flat combining allows one thread to send on behalf of multiple waiters. Threads enqueue requests; the mutex holder ("combiner") processes the batch, amortizing lock acquisition and enabling TCP segment coalescing via MSG_MORE.

Supporting changes include a workqueue affinity fix for single-LLC systems, a page recycling pool for receive buffers, and explicit TCP buffer sizing for high bandwidth-delay product networks.

Base commit: v6.19-rc8

---

Chuck Lever (7):
workqueue: Automatic affinity scope fallback for single-pod topologies
sunrpc: split svc_data_ready into protocol-specific callbacks
sunrpc: add per-transport page recycling pool
sunrpc: add dedicated TCP receiver thread
sunrpc: implement flat combining for TCP socket sends
sunrpc: unify fore and backchannel server TCP send paths
SUNRPC: Set explicit TCP socket buffer sizes for NFSD

 include/linux/sunrpc/svc.h      |   1 +
 include/linux/sunrpc/svc_xprt.h |  32 ++
 include/linux/sunrpc/svcsock.h  |  40 ++
 include/linux/workqueue.h       |   8 +-
 kernel/workqueue.c              |  68 ++-
 net/sunrpc/svc.c                |  13 +
 net/sunrpc/svc_xprt.c           | 151 ++++++
 net/sunrpc/svcsock.c            | 797 +++++++++++++++++++++++++++++---
 net/sunrpc/xprtsock.c           |  60 +--
 9 files changed, 1044 insertions(+), 126 deletions(-)
Signature · 1 line
2.52.0
author maintainer
#1 lore raw

RFC PATCH 1/7 workqueue: Automatic affinity scope fallback for single-pod topologies

From: Chuck Lever <[email protected]>

The default affinity scope WQ_AFFN_CACHE assumes systems have multiple last-level caches. On systems where all CPUs share a single LLC (common with Intel monolithic dies), this scope degenerates to a single worker pool. All queue_work() calls then contend on that pool's single lock, causing severe performance degradation under high-throughput workloads.

For example, on a 12-core system with a single shared L3 cache running NFS over RDMA with 12 fio jobs, perf shows approximately 39% of CPU cycles spent in native_queued_spin_lock_slowpath, nearly all from __queue_work() contending on the single pool lock.

On such systems WQ_AFFN_CACHE, WQ_AFFN_SMT, and WQ_AFFN_NUMA scopes all collapse to a single pod.

Add wq_effective_affn_scope() to detect when a selected affinity scope provides only one pod despite having multiple CPUs, and automatically fall back to a finer-grained scope. This enables lock distribution to scale with CPU count without requiring manual configuration via the workqueue.default_affinity_scope parameter or per-workqueue sysfs tuning.

The fallback is conservative: it triggers only when a scope degenerates to exactly one pod, and respects explicitly configured (non-default) scopes.

Also update wq_affn_scope_show() to display the effective scope when fallback occurs, making the behavior transparent to administrators via sysfs (e.g., "default (cache -> smt)").

---
 include/linux/workqueue.h |  8 ++++-
 kernel/workqueue.c        | 68 +++++++++++++++++++++++++++++++++++----
 2 files changed, 69 insertions(+), 7 deletions(-)
include/linux/workqueue.h +7 -1
index dabc351cc127..1fca5791337d 100644
@@ -128,10 +128,16 @@ struct rcu_work {
 	struct workqueue_struct *wq;
 };
 
+/*
+ * Affinity scopes are ordered from finest to coarsest granularity. This
+ * ordering is used by the automatic fallback logic in wq_effective_affn_scope()
+ * which walks from coarse toward fine when a scope degenerates to a single pod.
+ */
 enum wq_affn_scope {
 	WQ_AFFN_DFL,			/* use system default */
 	WQ_AFFN_CPU,			/* one pod per CPU */
-	WQ_AFFN_SMT,			/* one pod poer SMT */
+	WQ_AFFN_SMT,			/* one pod per SMT */
+	WQ_AFFN_CLUSTER,		/* one pod per cluster */
 	WQ_AFFN_CACHE,			/* one pod per LLC */
 	WQ_AFFN_NUMA,			/* one pod per NUMA node */
 	WQ_AFFN_SYSTEM,			/* one pod across the whole system */
kernel/workqueue.c +62 -6

110 lines not on this page · raw message

Signature · 1 line
2.52.0
author maintainer
#3 lore raw

RFC PATCH 2/7 sunrpc: split svc_data_ready into protocol-specific callbacks

In reply to Chuck Lever

From: Chuck Lever <[email protected]>

Separate data-ready callbacks enable protocol-specific optimizations. UDP and TCP transports already have different
requirements: currently UDP sockets do not implement DTLS, so the XPT_HANDSHAKE check is unnecessary overhead for them.

Prepare the server-side socket infrastructure for additional changes to TCP's data_ready callback.

---
 net/sunrpc/svcsock.c | 37 ++++++++++++++++++++++++++++++++-----
 1 file changed, 32 insertions(+), 5 deletions(-)
net/sunrpc/svcsock.c +32 -5
index d61cd9b40491..3ec50812b110 100644
@@ -397,10 +397,37 @@ static void svc_sock_secure_port(struct svc_rqst *rqstp)
 		clear_bit(RQ_SECURE, &rqstp->rq_flags);
 }
 
-/*
- * INET callback when data has been received on the socket.
+/**
+ * svc_udp_data_ready - sk->sk_data_ready callback for UDP sockets
+ * @sk: socket whose receive buffer contains data
+ *
+ * This implementation does not yet support DTLS, so the
+ * XPT_HANDSHAKE check is not needed here.
  */
-static void svc_data_ready(struct sock *sk)
+static void svc_udp_data_ready(struct sock *sk)
+{
+	struct svc_sock	*svsk = (struct svc_sock *)sk->sk_user_data;
+
+	trace_sk_data_ready(sk);
+
+	if (svsk) {
+		/* Refer to svc_setup_socket() for details. */
+		rmb();
+		svsk->sk_odata(sk);
+		trace_svcsock_data_ready(&svsk->sk_xprt, 0);
+		if (!test_and_set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags))
+			svc_xprt_enqueue(&svsk->sk_xprt);
+	}
+}
+
+/**
+ * svc_tcp_data_ready - sk->sk_data_ready callback for TCP sockets
+ * @sk: socket whose receive buffer contains data
+ *
+ * Data ingest is skipped while a TLS handshake is in progress
+ * (XPT_HANDSHAKE).
+ */
+static void svc_tcp_data_ready(struct sock *sk)
 {
 	struct svc_sock	*svsk = (struct svc_sock *)sk->sk_user_data;
 
@@ -835,7 +862,7 @@ static void svc_udp_init(struct svc_sock *svsk, struct svc_serv *serv)
 	svc_xprt_init(sock_net(svsk->sk_sock->sk), &svc_udp_class,
 		      &svsk->sk_xprt, serv);
 	clear_bit(XPT_CACHE_AUTH, &svsk->sk_xprt.xpt_flags);
-	svsk->sk_sk->sk_data_ready = svc_data_ready;
+	svsk->sk_sk->sk_data_ready = svc_udp_data_ready;
 	svsk->sk_sk->sk_write_space = svc_write_space;
 
 	/* initialise setting must have enough space to
@@ -1368,7 +1395,7 @@ static void svc_tcp_init(struct svc_sock *svsk, struct svc_serv *serv)
 		set_bit(XPT_CONN, &svsk->sk_xprt.xpt_flags);
 	} else {
 		sk->sk_state_change = svc_tcp_state_change;
-		sk->sk_data_ready = svc_data_ready;
+		sk->sk_data_ready = svc_tcp_data_ready;
 		sk->sk_write_space = svc_write_space;
 
 		svsk->sk_marker = xdr_zero;
Signature · 1 line
2.52.0
author maintainer
#4 lore raw

RFC PATCH 3/7 sunrpc: add per-transport page recycling pool

In reply to Chuck Lever

From: Chuck Lever <[email protected]>

RPC server transports allocate pages for receiving incoming data on every request. Under high load, this repeated allocation and freeing creates unnecessary overhead in the page allocator hot path.

Introduce svc_page_pool, a lock-free page recycling mechanism that enables efficient page reuse between receive operations. A follow-up commit wires this into the TCP transport's receive path; svcrdma's RDMA Read path might also make use of this mechanism some day.

The pool uses llist for lock-free producer-consumer handoff: worker threads returning pages after RPC processing act as producers, while receiver threads allocating pages for incoming data act as consumers. Pages are linked via page->pcp_llist, which is safe because these pages are owned exclusively by the transport.

Each pool tracks its NUMA node affinity, allowing page allocations to target the same node as the transport's receiver thread. Provide svc_pool_node() to enable transports to determine the NUMA node associated with a service pool for NUMA-aware resource allocation.

---
 include/linux/sunrpc/svc.h      |   1 +
 include/linux/sunrpc/svc_xprt.h |  32 +++++++
 net/sunrpc/svc.c                |  13 +++
 net/sunrpc/svc_xprt.c           | 151 ++++++++++++++++++++++++++++++++
 4 files changed, 197 insertions(+)
include/linux/sunrpc/svc.h +1 -0
index 5506d20857c3..f4efe60f4dad 100644
@@ -457,6 +457,7 @@ void		   svc_wake_up(struct svc_serv *);
 void		   svc_reserve(struct svc_rqst *rqstp, int space);
 void		   svc_pool_wake_idle_thread(struct svc_pool *pool);
 struct svc_pool   *svc_pool_for_cpu(struct svc_serv *serv);
+int		   svc_pool_node(struct svc_pool *pool);
 char *		   svc_print_addr(struct svc_rqst *, char *, size_t);
 const char *	   svc_proc_name(const struct svc_rqst *rqstp);
 int		   svc_encode_result_payload(struct svc_rqst *rqstp,
include/linux/sunrpc/svc_xprt.h +32 -0
index da2a2531e110..e60c2936b1ce 100644
@@ -9,9 +9,33 @@
 #define SUNRPC_SVC_XPRT_H
 
 #include <linux/sunrpc/svc.h>
+#include <linux/llist.h>
 
 struct module;
 
+/**
+ * struct svc_page_pool - per-transport page recycling pool
+ * @pp_pages: lock-free list of recycled pages
+ * @pp_count: number of pages currently in pool
+ * @pp_numa_node: NUMA node for page allocations
+ * @pp_max: maximum pages to retain in pool
+ *
+ * Lock-free page recycling between producers (svc threads returning
+ * pages) and a single consumer (the thread allocating pages for
+ * receives). Uses llist for efficient producer-consumer handoff
+ * without spinlocks.
+ *
+ * Callers must serialize calls to svc_page_pool_get(); multiple
+ * concurrent consumers are not supported.
+ * Allocate with svc_page_pool_alloc(); free with svc_page_pool_free().
+ */
+struct svc_page_pool {
+	struct llist_head	pp_pages;
+	atomic_t		pp_count;
+	int			pp_numa_node;
+	unsigned int		pp_max;
+};
+
 struct svc_xprt_ops {
 	struct svc_xprt	*(*xpo_create)(struct svc_serv *,
 				       struct net *net,
@@ -187,6 +211,14 @@ void	svc_add_new_perm_xprt(struct svc_serv *serv, struct svc_xprt *xprt);
 void	svc_age_temp_xprts_now(struct svc_serv *, struct sockaddr *);
 void	svc_xprt_deferred_close(struct svc_xprt *xprt);
 
+/* Page pool helpers */
+struct svc_page_pool *svc_page_pool_alloc(int numa_node, unsigned int max);
+void	svc_page_pool_free(struct svc_page_pool *pool);
+void	svc_page_pool_put(struct svc_page_pool *pool, struct page *page);
+void	svc_page_pool_put_bulk(struct svc_page_pool *pool,
+			       struct page **pages, unsigned int count);
+struct page *svc_page_pool_get(struct svc_page_pool *pool);
+
 static inline void svc_xprt_get(struct svc_xprt *xprt)
 {
 	kref_get(&xprt->xpt_ref);
net/sunrpc/svc.c +13 -0
index 4704dce7284e..6b350cb7d539 100644
@@ -418,6 +418,19 @@ struct svc_pool *svc_pool_for_cpu(struct svc_serv *serv)
 	return &serv->sv_pools[pidx % serv->sv_nrpools];
 }
 
+/**
+ * svc_pool_node - Return the NUMA node affinity of a service pool
+ * @pool: the service pool
+ *
+ * Return value:
+ *   The NUMA node the pool is associated with, or the local node
+ *   if no explicit mapping exists
+ */
+int svc_pool_node(struct svc_pool *pool)
+{
+	return svc_pool_map_get_node(pool->sp_id);
+}
+
 static int svc_rpcb_setup(struct svc_serv *serv, struct net *net)
 {
 	int err;
net/sunrpc/svc_xprt.c +151 -0

155 lines not on this page · raw message

Signature · 1 line
2.52.0
author maintainer
#5 lore raw

RFC PATCH 4/7 sunrpc: add dedicated TCP receiver thread

In reply to Chuck Lever

From: Chuck Lever <[email protected]>

Eliminate receive-side socket lock contention for NFS server TCP connections by dedicating one kernel thread per TCP socket to handle all receives.

Current architecture has multiple nfsd worker threads competing for the same socket, serializing on socket lock inside sock_recvmsg(). The new design creates a single receiver thread per TCP connection that owns all sock_recvmsg() calls and queues complete RPC messages for workers to process.

Architecture:

Before:
Worker 1 --+ +-- sock_recvmsg() --+
Worker 2 --+-- compete for xprt--+-- sock_recvmsg() --+-- CONTENTION
Worker 3 --+ +-- sock_recvmsg() --+

After:
Receiver Thread -- sock_recvmsg() --+-- Worker 1 -- process -- send
(no contention) +-- Worker 2 -- process -- send
+-- Worker 3 -- process -- send

The receiver thread uses a lock-free llist queue to pass complete RPC messages to worker threads, avoiding spinlock overhead in the fast path. Flow control limits queue depth to SVC_TCP_MSG_QUEUE_MAX (64) messages per socket to bound memory usage.

This mirrors the architecture used by svcrdma, where RDMA completion handlers queue received messages for worker threads rather than having workers compete for hardware resources.

NUMA Affinity:

The receiver thread is created on the NUMA node associated with the service pool handling the accept, following the same NUMA placement strategy used for nfsd worker threads. Page allocations for receive buffers explicitly target this node via __alloc_pages_bulk(), providing memory locality for the receive path. This mirrors how svcrdma allocates resources on the RNIC's NUMA node.

svc_tcp_data_ready() now wakes the dedicated receiver thread instead of enqueueing the transport for worker threads. If receiver thread creation fails during connection accept, the connection is rejected; the client will retry.

---
 include/linux/sunrpc/svcsock.h |  36 +++
 net/sunrpc/svcsock.c           | 472 ++++++++++++++++++++++++++++++---
 2 files changed, 477 insertions(+), 31 deletions(-)
include/linux/sunrpc/svcsock.h +36 -0
index de37069aba90..391ce9c14f2d 100644
@@ -12,6 +12,32 @@
 
 #include <linux/sunrpc/svc.h>
 #include <linux/sunrpc/svc_xprt.h>
+#include <linux/cache.h>
+#include <linux/llist.h>
+#include <linux/wait.h>
+#include <linux/completion.h>
+#include <linux/ktime.h>
+
+/* Maximum queued messages per TCP socket before backpressure */
+#define SVC_TCP_MSG_QUEUE_MAX	64
+
+/**
+ * struct svc_tcp_msg - queued RPC message ready for processing
+ * @tm_node: lock-free queue linkage
+ * @tm_len: total message length
+ * @tm_npages: number of pages holding message data
+ * @tm_pages: flexible array of pages containing the message
+ *
+ * The receiver thread allocates these to queue complete RPC messages
+ * for worker threads to process. Page ownership transfers from the
+ * receiver's rqstp to this structure, then to the worker's rqstp.
+ */
+struct svc_tcp_msg {
+	struct llist_node	tm_node;
+	size_t			tm_len;
+	unsigned int		tm_npages;
+	struct page		*tm_pages[];
+};
 
 /*
  * RPC server socket.
@@ -43,6 +69,16 @@ struct svc_sock {
 
 	struct completion	sk_handshake_done;
 
+	/* Dedicated receiver thread (TCP only) */
+	struct task_struct	*sk_receiver;
+	struct llist_head	sk_msg_queue;
+	wait_queue_head_t	sk_receiver_wq;
+	struct completion	sk_receiver_exit;
+	struct svc_page_pool	*sk_page_pool;
+	ktime_t			sk_partial_record_time;
+
+	atomic_t		sk_msg_count ____cacheline_aligned_in_smp;
+
 	/* received data */
 	unsigned long		sk_maxpages;
 	struct page *		sk_pages[] __counted_by(sk_maxpages);
net/sunrpc/svcsock.c +441 -31

557 lines not on this page · raw message

Signature · 1 line
2.52.0
author maintainer
#6 lore raw

RFC PATCH 5/7 sunrpc: implement flat combining for TCP socket sends

In reply to Chuck Lever

From: Chuck Lever <[email protected]>

High contention on xpt_mutex during TCP reply transmission limits nfsd scalability. When multiple threads send replies on the same connection, mutex handoff triggers optimistic spinning that consumes substantial CPU time. Profiling on high-throughput workloads shows approximately 15% of cycles spent in the spin-wait path.

The flat combining pattern addresses this by allowing one thread to perform send operations on behalf of multiple waiting threads. Rather than each thread acquiring xpt_mutex independently, threads enqueue their send requests to a lock-free llist. The first thread to acquire the mutex becomes the combiner and processes all pending sends in a batch. Other threads wait on a per-request completion structure instead of spinning on the lock.

The combiner continues processing the queue until empty before releasing xpt_mutex, amortizing acquisition cost across multiple sends. Setting MSG_MORE on all but the final send in each batch hints TCP to coalesce segments, reducing protocol overhead when multiple replies transmit in quick succession.

---
 include/linux/sunrpc/svcsock.h |   2 +
 net/sunrpc/svcsock.c           | 190 ++++++++++++++++++++++++++++-----
 2 files changed, 165 insertions(+), 27 deletions(-)
include/linux/sunrpc/svcsock.h +2 -0
index 391ce9c14f2d..d085093769a1 100644
@@ -54,6 +54,8 @@ struct svc_sock {
 
 	/* For sends (protected by xpt_mutex) */
 	struct bio_vec		*sk_bvec;
+	struct llist_head	sk_send_queue;	/* pending sends for combining */
+	u64			sk_drain_avg_ns; /* EMA of combiner drain time */
 
 	/* private TCP part */
 	/* On-the-wire fragment header: */
net/sunrpc/svcsock.c +163 -27

223 lines not on this page · raw message

Signature · 1 line
2.52.0
author maintainer
#7 lore raw

RFC PATCH 6/7 sunrpc: unify fore and backchannel server TCP send paths

In reply to Chuck Lever

From: Chuck Lever <[email protected]>

High latency in callback processing for NFSv4.1+ sessions can occur when the fore channel sustains heavy request traffic. The backchannel implementation acquires xpt_mutex directly while the fore channel uses flat combining to batch socket operations. A thread in the combining loop processes queued sends continuously until the llist empties, which under load means backchannel threads block on xpt_mutex for extended periods waiting for a turn at the socket. Delegation recalls and other callback operations carry time constraints that make this starvation problematic.

Routing backchannel sends through the same flat combining infrastructure eliminates this starvation; a shared llist queue replaces direct mutex acquisition and separate code paths. The struct svc_pending_send now holds an xdr_buf pointer instead of svc_rqst, decoupling the queueing mechanism from RPC request structures. A new svc_tcp_send() function accepts an xprt, xdr_buf, and marker, then either enters the combining loop or enqueues for processing by an active combiner.

The fore channel path through svc_tcp_sendto() now calls svc_tcp_send() after preparing its xdr_buf. The backchannel bc_send_request() similarly calls svc_tcp_send() in place of its former mutex acquisition and direct bc_sendto() invocation. Both channels queue into the same llist, so backchannel operations receive fair treatment in the send ordering. When a backchannel send queues behind fore channel traffic, the combining loop processes both together with shared socket lock acquisition and MSG_MORE coalescing where applicable.

Maintenance burden decreases with a single code path for TCP sends. The backchannel gains batching benefits when concurrent with fore channel load, and starvation no longer occurs because queueing provides deterministic ordering independent of mutex contention timing.

---
 include/linux/sunrpc/svcsock.h |  2 +
 net/sunrpc/svcsock.c           | 76 +++++++++++++++++++++++++---------
 net/sunrpc/xprtsock.c          | 60 ++++++---------------------
 3 files changed, 71 insertions(+), 67 deletions(-)
include/linux/sunrpc/svcsock.h +2 -0
index d085093769a1..f7f0c5e47fc5 100644
@@ -101,6 +101,8 @@ static inline u32 svc_sock_final_rec(struct svc_sock *svsk)
  */
 void		svc_recv(struct svc_rqst *rqstp);
 void		svc_send(struct svc_rqst *rqstp);
+int		svc_tcp_send(struct svc_xprt *xprt, struct xdr_buf *xdr,
+			     rpc_fraghdr marker);
 int		svc_addsock(struct svc_serv *serv, struct net *net,
 			    const int fd, char *name_return, const size_t len,
 			    const struct cred *cred);
net/sunrpc/svcsock.c +56 -20

144 lines not on this page · raw message

net/sunrpc/xprtsock.c +13 -47

78 lines not on this page · raw message

Signature · 1 line
2.52.0
author maintainer
#8 lore raw

RFC PATCH 7/7 SUNRPC: Set explicit TCP socket buffer sizes for NFSD

In reply to Chuck Lever

From: Chuck Lever <[email protected]>

NFSD TCP sockets currently rely on system defaults with TCP auto-tuning. On networks with large bandwidth-delay products, the default maximum buffer sizes (6MB receive, 4MB send) can throttle throughput. Administrators must resort to system-wide sysctl adjustments (tcp_rmem/tcp_wmem), which affect all TCP connections rather than just NFS traffic.

This change sets explicit buffer sizes for NFSD TCP data sockets. The buffer size is set to 4 * sv_max_mesg, yielding approximately 16MB with default NFS payload sizes. On memory-constrained systems, the buffer size is capped at 1/1024 of physical RAM, with a hard ceiling of 16MB. SOCK_SNDBUF_LOCK and SOCK_RCVBUF_LOCK disable auto-tuning, providing predictable memory consumption.

The existing svc_sock_setbufsize() is renamed to svc_udp_setbufsize() to reflect its UDP-specific purpose, and a new svc_tcp_setbufsize() handles TCP data connections. Listener sockets remain unaffected, as listeners do not transfer data.

This approach improves throughput on high-speed networks without requiring system-wide configuration changes, while automatically scaling down buffer sizes on small systems.

---
 net/sunrpc/svcsock.c | 52 ++++++++++++++++++++++++++++++++++++++++----
 1 file changed, 48 insertions(+), 4 deletions(-)
net/sunrpc/svcsock.c +48 -4
index 8d7ac777dfe3..e019ae285d47 100644
@@ -50,6 +50,7 @@
 #include <net/handshake.h>
 #include <linux/uaccess.h>
 #include <linux/highmem.h>
+#include <linux/mm.h>
 #include <asm/ioctls.h>
 #include <linux/key.h>
 
@@ -377,9 +378,12 @@ static ssize_t svc_tcp_read_msg(struct svc_rqst *rqstp, size_t buflen,
 }
 
 /*
- * Set socket snd and rcv buffer lengths
+ * Set socket snd and rcv buffer lengths for UDP sockets.
+ *
+ * UDP sockets need large buffers because pending requests remain
+ * in the receive buffer until processed by a worker thread.
  */
-static void svc_sock_setbufsize(struct svc_sock *svsk, unsigned int nreqs)
+static void svc_udp_setbufsize(struct svc_sock *svsk, unsigned int nreqs)
 {
 	unsigned int max_mesg = svsk->sk_xprt.xpt_server->sv_max_mesg;
 	struct socket *sock = svsk->sk_sock;
@@ -393,6 +397,45 @@ static void svc_sock_setbufsize(struct svc_sock *svsk, unsigned int nreqs)
 	release_sock(sock->sk);
 }
 
+/* Accommodate high bandwidth-delay product connections */
+#define SVC_TCP_SNDBUF_MAX	(16 * 1024 * 1024)
+#define SVC_TCP_RCVBUF_MAX	(16 * 1024 * 1024)
+
+/*
+ * Set socket snd and rcv buffer lengths for TCP data sockets.
+ *
+ * Buffers are sized to accommodate high-bandwidth data transfers on
+ * high-latency networks (large bandwidth-delay product). Automatic
+ * buffer tuning is disabled to allow control of server memory
+ * consumption.
+ */
+static void svc_tcp_setbufsize(struct svc_sock *svsk)
+{
+	struct svc_serv *serv = svsk->sk_xprt.xpt_server;
+	struct socket *sock = svsk->sk_sock;
+	unsigned long mem_cap, ideal;
+	unsigned int sndbuf, rcvbuf;
+
+	/* Buffer multiple in-flight RPC messages */
+	ideal = serv->sv_max_mesg * 4;
+
+	/* Memory-based cap: 1/1024 of physical RAM */
+	mem_cap = (totalram_pages() >> 10) << PAGE_SHIFT;
+
+	sndbuf = clamp_t(unsigned long, ideal,
+			 serv->sv_max_mesg, min(mem_cap, SVC_TCP_SNDBUF_MAX));
+	rcvbuf = clamp_t(unsigned long, ideal,
+			 serv->sv_max_mesg, min(mem_cap, SVC_TCP_RCVBUF_MAX));
+
+	lock_sock(sock->sk);
+	sock->sk->sk_sndbuf = sndbuf;
+	sock->sk->sk_rcvbuf = rcvbuf;
+	sock->sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
+	sock->sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
+	sock->sk->sk_write_space(sock->sk);
+	release_sock(sock->sk);
+}
+
 static void svc_sock_secure_port(struct svc_rqst *rqstp)
 {
 	if (svc_port_is_privileged(svc_addr(rqstp)))
@@ -656,7 +699,7 @@ static int svc_udp_recvfrom(struct svc_rqst *rqstp)
 	     * provides an upper bound on the number of threads
 	     * which will access the socket.
 	     */
-	    svc_sock_setbufsize(svsk, serv->sv_nrthreads + 3);
+	    svc_udp_setbufsize(svsk, serv->sv_nrthreads + 3);
 
 	clear_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags);
 	err = kernel_recvmsg(svsk->sk_sock, &msg, NULL,
@@ -872,7 +915,7 @@ static void svc_udp_init(struct svc_sock *svsk, struct svc_serv *serv)
 	 * receive and respond to one request.
 	 * svc_udp_recvfrom will re-adjust if necessary
 	 */
-	svc_sock_setbufsize(svsk, 3);
+	svc_udp_setbufsize(svsk, 3);
 
 	/* data might have come in before data_ready set up */
 	set_bit(XPT_DATA, &svsk->sk_xprt.xpt_flags);
@@ -1986,6 +2029,7 @@ static void svc_tcp_init(struct svc_sock *svsk, struct svc_serv *serv)
 		       svsk->sk_maxpages * sizeof(struct page *));
 
 		tcp_sock_set_nodelay(sk);
+		svc_tcp_setbufsize(svsk);
 
 		switch (sk->sk_state) {
 		case TCP_SYN_RECV:
Signature · 1 line
2.52.0
author maintainer
#2 lore raw

Re: [RFC PATCH 1/7] workqueue: Automatic affinity scope fallback for single-pod topologies

In reply to Chuck Lever
Quoted 187 lines · Chuck Lever

From: Chuck Lever <[email protected]>

The default affinity scope WQ_AFFN_CACHE assumes systems have multiple last-level caches. On systems where all CPUs share a single LLC (common with Intel monolithic dies), this scope degenerates to a single worker pool. All queue_work() calls then contend on that pool's single lock, causing severe performance degradation under high-throughput workloads.

For example, on a 12-core system with a single shared L3 cache running NFS over RDMA with 12 fio jobs, perf shows approximately 39% of CPU cycles spent in native_queued_spin_lock_slowpath, nearly all from __queue_work() contending on the single pool lock.

On such systems WQ_AFFN_CACHE, WQ_AFFN_SMT, and WQ_AFFN_NUMA scopes all collapse to a single pod.

Add wq_effective_affn_scope() to detect when a selected affinity scope provides only one pod despite having multiple CPUs, and automatically fall back to a finer-grained scope. This enables lock distribution to scale with CPU count without requiring manual configuration via the workqueue.default_affinity_scope parameter or per-workqueue sysfs tuning.

The fallback is conservative: it triggers only when a scope degenerates to exactly one pod, and respects explicitly configured (non-default) scopes.

Also update wq_affn_scope_show() to display the effective scope when fallback occurs, making the behavior transparent to administrators via sysfs (e.g., "default (cache -> smt)").

---
 include/linux/workqueue.h |  8 ++++-
 kernel/workqueue.c        | 68 +++++++++++++++++++++++++++++++++++----
 2 files changed, 69 insertions(+), 7 deletions(-)
include/linux/workqueue.h +2 -0
index dabc351cc127..1fca5791337d 100644
@@ -128,10 +128,16 @@ struct rcu_work {
 	struct workqueue_struct *wq;
 };
 
+/*
+ * Affinity scopes are ordered from finest to coarsest granularity. 

This
+ * ordering is used by the automatic fallback logic in wq_effective_affn_scope()
+ * which walks from coarse toward fine when a scope degenerates to a single pod.
+ */
enum wq_affn_scope {

include/linux/workqueue.h +2 -1
 	WQ_AFFN_DFL,			/* use system default */
 	WQ_AFFN_CPU,			/* one pod per CPU */
-	WQ_AFFN_SMT,			/* one pod poer SMT */
+	WQ_AFFN_SMT,			/* one pod per SMT */
+	WQ_AFFN_CLUSTER,		/* one pod per cluster */
 	WQ_AFFN_CACHE,			/* one pod per LLC */
 	WQ_AFFN_NUMA,			/* one pod per NUMA node */
 	WQ_AFFN_SYSTEM,			/* one pod across the whole system */
kernel/workqueue.c +1 -0
index 253311af47c6..32598b9cd1c2 100644
@@ -405,6 +405,7 @@ static const char *wq_affn_names[WQ_AFFN_NR_TYPES] 
 = {
 	[WQ_AFFN_DFL]		= "default",
 	[WQ_AFFN_CPU]		= "cpu",
 	[WQ_AFFN_SMT]		= "smt",
+	[WQ_AFFN_CLUSTER]	= "cluster",
 	[WQ_AFFN_CACHE]		= "cache",
 	[WQ_AFFN_NUMA]		= "numa",
kernel/workqueue.c +33 -0
 	[WQ_AFFN_SYSTEM]	= "system",
@@ -4753,6 +4754,39 @@ static void wqattrs_actualize_cpumask(struct 
 workqueue_attrs *attrs,
 		cpumask_copy(attrs->cpumask, unbound_cpumask);
 }
 
+/*
+ * Determine the effective affinity scope. If the configured scope results
+ * in a single pod (e.g., WQ_AFFN_CACHE on a system with one shared LLC),
+ * fall back to a finer-grained scope to distribute pool lock contention.
+ *
+ * The search stops at WQ_AFFN_CPU, which always provides one pod per CPU
+ * and thus cannot degenerate further.
+ *
+ * Returns the scope to actually use, which may differ from the configured
+ * scope on systems where coarser scopes degenerate.
+ */
+static enum wq_affn_scope wq_effective_affn_scope(enum wq_affn_scope scope)
+{
+	struct wq_pod_type *pt;
+
+	/*
+	 * Walk from the requested scope toward finer granularity. Stop
+	 * when a scope provides more than one pod, or when CPU scope is
+	 * reached. CPU scope always provides nr_possible_cpus() pods.
+	 */
+	while (scope > WQ_AFFN_CPU) {
+		pt = &wq_pod_types[scope];
+
+		/* Multiple pods at this scope; no fallback needed */
+		if (pt->nr_pods > 1)
+			break;
+
+		scope--;
+	}
+
+	return scope;
+}
+
 /* find wq_pod_type to use for @attrs */
 static const struct wq_pod_type *

wqattrs_pod_type(const struct workqueue_attrs *attrs)

kernel/workqueue.c +28 -6
@@ -4763,8 +4797,13 @@ wqattrs_pod_type(const struct workqueue_attrs *attrs)
 	/* to synchronize access to wq_affn_dfl */
 	lockdep_assert_held(&wq_pool_mutex);
 
+	/*
+	 * For default scope, apply automatic fallback for degenerate
+	 * topologies. Explicit scope selection via sysfs or per-workqueue
+	 * attributes bypasses fallback, preserving administrator intent.
+	 */
 	if (attrs->affn_scope == WQ_AFFN_DFL)
-		scope = wq_affn_dfl;
+		scope = wq_effective_affn_scope(wq_affn_dfl);
 	else
 		scope = attrs->affn_scope;
 
@@ -7206,16 +7245,27 @@ static ssize_t wq_affn_scope_show(struct device *dev,
 				  struct device_attribute *attr, char *buf)
 {
 	struct workqueue_struct *wq = dev_to_wq(dev);
+	enum wq_affn_scope scope, effective;
 	int written;
 
 	mutex_lock(&wq->mutex);
-	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
-		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
-				    wq_affn_names[WQ_AFFN_DFL],
-				    wq_affn_names[wq_affn_dfl]);
-	else
+	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL) {
+		scope = wq_affn_dfl;
+		effective = wq_effective_affn_scope(scope);
+		if (wq_pod_types[effective].nr_pods >
+		    wq_pod_types[scope].nr_pods)
+			written = scnprintf(buf, PAGE_SIZE, "%s (%s -> %s)\n",
+					    wq_affn_names[WQ_AFFN_DFL],
+					    wq_affn_names[scope],
+					    wq_affn_names[effective]);
+		else
+			written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
+					    wq_affn_names[WQ_AFFN_DFL],
+					    wq_affn_names[scope]);
+	} else {
 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
 				    wq_affn_names[wq->unbound_attrs->affn_scope]);
+	}
 	mutex_unlock(&wq->mutex);
 
 	return written;
@@ -8023,6 +8073,11 @@ static bool __init cpus_share_smt(int cpu0, int cpu1)
 #endif
 }
 
+static bool __init cpus_share_cluster(int cpu0, int cpu1)
+{
+	return cpumask_test_cpu(cpu0, topology_cluster_cpumask(cpu1));
+}
+
 static bool __init cpus_share_numa(int cpu0, int cpu1)
 {
 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
@@ -8042,6 +8097,7 @@ void __init workqueue_init_topology(void)
 
 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
+	init_pod_type(&wq_pod_types[WQ_AFFN_CLUSTER], cpus_share_cluster);
 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
 
Signature · 1 line
2.52.0

Tejun has rejected this one. However I've worked up a patch that replaces svcrdma_wq with a kthread that does not have an issue with the workqueue pool spin lock, and that solves the same issue this one does (for NFSD).

Signature · 1 line
Chuck Lever
#9 lore raw
In reply to Chuck Lever

Hi Chuck,

Quoted 26 lines · Chuck Lever

From: Chuck Lever <[email protected]>

High-throughput NFSD workloads exhibit significant lock contention on TCP connections. Worker threads compete for the socket lock during receives and serialize on xpt_mutex during sends, limiting scalability.

This series addresses both paths:

- Receive: A dedicated kernel thread per TCP connection owns all sock_recvmsg() calls and queues complete RPC messages for workers via lock-free llist. This eliminates socket lock contention among workers.

- Transmit: Flat combining allows one thread to send on behalf of multiple waiters. Threads enqueue requests; the mutex holder ("combiner") processes the batch, amortizing lock acquisition and enabling TCP segment coalescing via MSG_MORE.

Supporting changes include a workqueue affinity fix for single-LLC systems, a page recycling pool for receive buffers, and explicit TCP buffer sizing for high bandwidth-delay product networks.

Base commit: v6.19-rc8

---

Quoted 8 lines

Chuck Lever (7):
workqueue: Automatic affinity scope fallback for single-pod topologies
sunrpc: split svc_data_ready into protocol-specific callbacks
sunrpc: add per-transport page recycling pool
sunrpc: add dedicated TCP receiver thread
sunrpc: implement flat combining for TCP socket sends
sunrpc: unify fore and backchannel server TCP send paths
SUNRPC: Set explicit TCP socket buffer sizes for NFSD

Curious to know your thinking on this patchset? Can you post v2 given your note about having adapted based on Tejun's feedback here?

https://lore.kernel.org/linux-nfs/[email protected]/

Thanks,
Mike

author maintainer
#10 lore raw
Quoted 38 lines · Mike Snitzer

Hi Chuck,

Quoted 26 lines · Chuck Lever

From: Chuck Lever <[email protected]>

High-throughput NFSD workloads exhibit significant lock contention on TCP connections. Worker threads compete for the socket lock during receives and serialize on xpt_mutex during sends, limiting scalability.

This series addresses both paths:

- Receive: A dedicated kernel thread per TCP connection owns all sock_recvmsg() calls and queues complete RPC messages for workers via lock-free llist. This eliminates socket lock contention among workers.

- Transmit: Flat combining allows one thread to send on behalf of multiple waiters. Threads enqueue requests; the mutex holder ("combiner") processes the batch, amortizing lock acquisition and enabling TCP segment coalescing via MSG_MORE.

Supporting changes include a workqueue affinity fix for single-LLC systems, a page recycling pool for receive buffers, and explicit TCP buffer sizing for high bandwidth-delay product networks.

Base commit: v6.19-rc8

---

Quoted 8 lines

Chuck Lever (7):
workqueue: Automatic affinity scope fallback for single-pod topologies
sunrpc: split svc_data_ready into protocol-specific callbacks
sunrpc: add per-transport page recycling pool
sunrpc: add dedicated TCP receiver thread
sunrpc: implement flat combining for TCP socket sends
sunrpc: unify fore and backchannel server TCP send paths
SUNRPC: Set explicit TCP socket buffer sizes for NFSD

Quoted 4 lines

Curious to know your thinking on this patchset? Can you post v2 given your note about having adapted based on Tejun's feedback here?

https://lore.kernel.org/linux-nfs/[email protected]/

The workqueue-related patch is not important for the server, it turns out, but I've adapted it for use on the client.

Regarding the series you listed above:

One reviewer balked at the idea of starting a kthread per connection on the server. I've reworked the receive side to use ->read_sock instead of ->recvmsg.

The flat combining changes on the send side are still good. One further optimization was to replace xpt_mutex with an llist queuing mechanism.

A number of other improvements are in the pipeline ahead of or behind these two.

Signature · 1 line
Chuck Lever