Skip to contentSkip to conversation

nfsd: reduce the scope of the nfsd_mutex

PATCH In review Jeff Layton 2 participants 10 messages Sep 22

Subsystems (3)
lore
Share & tools
lore

Jeff Layton

author maintainer
#0 lore raw

v2 cover nfsd: reduce the scope of the nfsd_mutex

This version fixes a couple of minor issues that Sashiko flagged, and also implements a suggestion by Neil to use guard() with the new filecache mutex.

Original cover letter follows:

-------------------8<--------------------

Currently much of nfsd's administration is serialized under the global nfsd_mutex, even though most of the objects managed under it are segregated by net namespace.

This patchset does a couple of small cleanups and then adds a new per-net mutex and moves all of the appropriate per-net data structures to be protected by it instead of the global mutex. The filecache is given its own mutex, and the global mutex is renamed and left for managing just the few remaning global objects.

I also had an LLM cook up some selftests so we can hopefully keep all of this working properly in the future.

Please consider for v7.4.

Thanks,
Jeff

---
Changes in v2:
- Fix potential deadlock in cross-namespace isolation selftest
- Drop binaries from selftest patches
- Use guard() in nfsd_file_cache_init()
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Jeff Layton (8):
nfsd: clear NFSD_NET_UP before dropping the generic resource reference
nfsd: make max_blksize a per-namespace setting
nfsd: move the control plane to a per-namespace mutex
nfsd: rename nfsd_mutex to nfsd_global_mutex
nfsd: give the open file cache its own mutex selftests/nfsd: factor the netlink plumbing into a shared header selftests/nfsd: add cross-namespace isolation tests selftests/nfsd: add a cross-namespace control-plane soak

 fs/nfsd/export.c                                   |  22 +-
 fs/nfsd/filecache.c                                |  26 +-
 fs/nfsd/netns.h                                    |  16 +
 fs/nfsd/nfs4proc.c                                 |   4 +-
 fs/nfsd/nfs4state.c                                |   8 +-
 fs/nfsd/nfsctl.c                                   | 129 ++---
 fs/nfsd/nfsd.h                                     |   4 +-
 fs/nfsd/nfssvc.c                                   | 146 ++++--
 tools/testing/selftests/nfsd/.gitignore            |   2 +
 tools/testing/selftests/nfsd/Makefile              |   2 +
 tools/testing/selftests/nfsd/config                |   6 +
 tools/testing/selftests/nfsd/nfsd_netlink.h        | 319 ++++++++++++
 .../testing/selftests/nfsd/nfsd_netlink_listener.c | 301 +----------
 .../testing/selftests/nfsd/nfsd_netns_isolation.c  | 468 +++++++++++++++++
 tools/testing/selftests/nfsd/nfsd_netns_stress.c   | 572 +++++++++++++++++++++
 tools/testing/selftests/nfsd/settings              |   2 +-
 16 files changed, 1592 insertions(+), 435 deletions(-)

---
base-commit: aeaddc6a3711283c09a9183068897d4fe1fb464f
change-id: 20260918-nfsd-per-net-mutex-8655764940ac

Best regards,

Signature · 1 line
Jeff Layton <[email protected]>
author maintainer
#1 lore raw

PATCH v2 1/8 nfsd: clear NFSD_NET_UP before dropping the generic resource reference

nfsd_shutdown_net() leaves NFSD_NET_UP set across nfsd_shutdown_generic(), so during that window the bit claims the host-wide file cache and NFSv4 tables are up when the last namespace may already have torn them down. Nothing observes it today only because one global mutex covers both.

Fold the test and clear into test_and_clear_bit() so the invariant "NFSD_NET_UP implies the generic resources are up" holds on its own. No functional change.

Assisted-by LLM
---
 fs/nfsd/nfssvc.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
fs/nfsd/nfssvc.c +6 -2
index cbc989238710..d75fe1523436 100644
@@ -433,9 +433,13 @@ static void nfsd_shutdown_net(struct net *net)
 
 	percpu_ref_exit(&nn->nfsd_net_ref);
 
-	if (test_bit(NFSD_NET_UP, &nn->flags))
+	/*
+	 * Clear NFSD_NET_UP before dropping this namespace's reference on
+	 * the generic (host-wide) resources, so that the bit never claims
+	 * they are available once they may already be gone.
+	 */
+	if (test_and_clear_bit(NFSD_NET_UP, &nn->flags))
 		nfsd_shutdown_generic();
-	clear_bit(NFSD_NET_UP, &nn->flags);
 }
 
 static DEFINE_SPINLOCK(nfsd_notifier_lock);
Signature · 1 line
2.55.0
author maintainer
#2 lore raw

PATCH v2 2/8 nfsd: make max_blksize a per-namespace setting

In reply to Jeff Layton

nfsd_max_blksize is module-scope, but /proc/fs/nfsd/max_block_size is a per-netns file. A container writing it therefore changes the payload size that every other namespace's next server start will use.

Move it into struct nfsd_net as ->max_blksize. The lazy nfsd_get_default_max_blksize() fill-in now happens per namespace on first nfsd_create_serv().

User-visible change: max_block_size no longer leaks across namespaces.

Fixes 11f779421a39 ("nfsd: containerize NFSd filesystem")
Assisted-by LLM
---
 fs/nfsd/netns.h  | 6 ++++++
 fs/nfsd/nfsctl.c | 8 +++-----
 fs/nfsd/nfsd.h   | 2 --
 fs/nfsd/nfssvc.c | 6 +++---
 4 files changed, 12 insertions(+), 10 deletions(-)
fs/nfsd/netns.h +6 -0
index 0ce7da20aba3..374ce83e2ba0 100644
@@ -154,6 +154,12 @@ struct nfsd_net {
 	 */
 	unsigned int min_threads;
 
+	/*
+	 * Maximum size of an NFS READ or WRITE payload.  Zero until the
+	 * first server start in this namespace picks a default.
+	 */
+	unsigned int max_blksize;
+
 	u32 clientid_base;
 	u32 clientid_counter;
 	u32 clverifier_counter;
fs/nfsd/nfsctl.c +3 -5
index f32311f2d7cf..330d0f12e199 100644
@@ -885,8 +885,6 @@ static ssize_t write_ports(struct file *file, char *buf, size_t size)
 }
 
 
-int nfsd_max_blksize;
-
 /*
  * write_maxblksize - Set or report the current NFS blksize
  *
@@ -931,12 +929,12 @@ static ssize_t write_maxblksize(struct file *file, char *buf, size_t size)
 			mutex_unlock(&nfsd_mutex);
 			return -EBUSY;
 		}
-		nfsd_max_blksize = bsize;
+		nn->max_blksize = bsize;
 		mutex_unlock(&nfsd_mutex);
 	}
 
-	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n",
-							nfsd_max_blksize);
+	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%u\n",
+							nn->max_blksize);
 }
 
 #ifdef CONFIG_NFSD_V4
fs/nfsd/nfsd.h +0 -2
index d1e413d21e76..0864d6d564e2 100644
@@ -143,8 +143,6 @@ enum {
 extern u64 nfsd_io_cache_read __read_mostly;
 extern u64 nfsd_io_cache_write __read_mostly;
 
-extern int nfsd_max_blksize;
-
 bool nfsd_v4client(struct svc_rqst *rqstp);
 
 /*
fs/nfsd/nfssvc.c +3 -3
index d75fe1523436..77e1e6ba686d 100644
@@ -630,12 +630,12 @@ int nfsd_create_serv(struct net *net, bool no_rpcbind)
 	init_completion(&nn->nfsd_net_free_done);
 	init_completion(&nn->nfsd_net_confirm_done);
 
-	if (nfsd_max_blksize == 0)
-		nfsd_max_blksize = nfsd_get_default_max_blksize();
+	if (nn->max_blksize == 0)
+		nn->max_blksize = nfsd_get_default_max_blksize();
 	nfsd_reset_versions(nn);
 	serv = svc_create_pooled(nfsd_programs, ARRAY_SIZE(nfsd_programs),
 				 &nn->nfsd_svcstats,
-				 nfsd_max_blksize, nfsd);
+				 nn->max_blksize, nfsd);
 	if (serv == NULL) {
 		percpu_ref_exit(&nn->nfsd_net_ref);
 		return -ENOMEM;
Signature · 1 line
2.55.0
author maintainer
#3 lore raw

PATCH v2 3/8 nfsd: move the control plane to a per-namespace mutex

In reply to Jeff Layton

nfsd_mutex serializes the entire NFSD control plane across every network namespace. The nfsd genl family sets .parallel_ops, so it is the only serialization there: one container starting nfsd, or one long RPC_STATUS_GET dump, stalls every other namespace's admin operations. The nfsd threads suffer too -- the dynamic-thread autoscaler trylocks the same mutex on every -ETIMEDOUT and -EBUSY, and a failed trylock skips the spawn/reap entirely.

Almost none of what the mutex covers is actually shared. Add nn->nfsd_mutex for the per-namespace control plane:

- nn->nfsd_serv and the svc_serv members hanging off it (->sv_permsocks,

    ->sv_temp_socks, per-pool thread counts)
  - NFSD_NET_UP / NFSD_NET_LOCKD_UP
  - the settables that may only change while the server is down
    (->nfsd_versions, ->nfsd4_lease, ->nfsd4_grace, ->max_blksize, ...)

- nn->svc_export_cache / nn->svc_expkey_cache liveness
- nn->conf_id_hashtbl liveness, for the state-revoke walks

The global nfsd_mutex keeps only what is genuinely host-wide: the nfsd_users refcount and the resources it brings up (open file cache, NFSv4 global tables), and the address-notifier registration. nfsd_startup_generic()/nfsd_shutdown_generic() and the notifier register/unregister now take it internally, so per-net callers never see it. nfsd_file_cache_purge() likewise takes it itself, which lets expkey_flush() drop its hand-rolled lock.

write_recoverydir() still takes the global mutex, but that now serializes writers only. The startup readers of user_recovery_dirname -- nfsd4_init_recdir() and check_for_legacy_methods() -- run under nn->nfsd_mutex alone, so a write from one namespace can tear the string under another namespace's startup. Worst case is a bogus path and a spurious startup error; the buffer is always NUL-terminated in bounds, so there is nothing to overrun. Left alone deliberately: that global already had lock-free readers in nfsd4_cltrack_legacy_{topdir,recdir}(), and legacy client tracking is deprecated and effectively init-netns-only -- its usermodehelper upcall always runs in the init mount namespace, so the stored path can only ever name an init-ns path.

Lock ordering is nn->nfsd_mutex outside the global nfsd_mutex; nothing takes two namespaces' nfsd_mutexes. struct svc_info already indirects through a mutex pointer, so pool_stats needs only to be pointed at the new lock.

The notifier refcount becomes a plain int now that it is genuinely mutex-guarded -- an atomic was never enough to serialize the register/unregister against the count. nfsd_create_serv() now takes that reference before publishing nn->nfsd_serv: namespaces are no longer serialized against each other here, so ordering it the other way would let the count dip to zero while another namespace's serv is already visible.

Note: the RPC thread pool needs no global lock here. svc_pool_map has its own svc_pool_map_mutex and per-pool thread counts live in the per-net svc_serv.

Assisted-by LLM
---
 fs/nfsd/export.c                                   |  22 ++--
 fs/nfsd/filecache.c                                |   5 +-
 fs/nfsd/netns.h                                    |  10 ++
 fs/nfsd/nfs4proc.c                                 |   4 +-
 fs/nfsd/nfs4state.c                                |   8 +-
 fs/nfsd/nfsctl.c                                   | 117 ++++++++++---------
 fs/nfsd/nfssvc.c                                   | 129 ++++++++++++++-------
 .../testing/selftests/nfsd/nfsd_netlink_listener.c |   6 +-
 8 files changed, 180 insertions(+), 121 deletions(-)
fs/nfsd/export.c +8 -14
index e5a0f1ababe6..265ea8fd31c6 100644
@@ -248,13 +248,7 @@ static struct cache_head *expkey_alloc(void)
 
 static void expkey_flush(void)
 {
-	/*
-	 * Take the nfsd_mutex here to ensure that the file cache is not
-	 * destroyed while we're in the middle of flushing.
-	 */
-	mutex_lock(&nfsd_mutex);
 	nfsd_file_cache_purge(current->nsproxy->net_ns);
-	mutex_unlock(&nfsd_mutex);
 }
 
 static int expkey_notify(struct cache_detail *cd, struct cache_head *h)
@@ -346,7 +340,7 @@ int nfsd_nl_expkey_get_reqs_dumpit(struct sk_buff *skb,
 
 	nn = net_generic(sock_net(skb->sk), nfsd_net_id);
 
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nn->nfsd_mutex);
 
 	cd = nn->svc_expkey_cache;
 	if (!cd) {
@@ -425,7 +419,7 @@ int nfsd_nl_expkey_get_reqs_dumpit(struct sk_buff *skb,
 	kfree(seqnos);
 	kfree(items);
 out_unlock:
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nn->nfsd_mutex);
 	return ret;
 }
 
@@ -560,7 +554,7 @@ int nfsd_nl_expkey_set_reqs_doit(struct sk_buff *skb,
 
 	nn = net_generic(genl_info_net(info), nfsd_net_id);
 
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nn->nfsd_mutex);
 
 	cd = nn->svc_expkey_cache;
 	if (!cd) {
@@ -576,7 +570,7 @@ int nfsd_nl_expkey_set_reqs_doit(struct sk_buff *skb,
 	}
 
 out_unlock:
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nn->nfsd_mutex);
 	return ret;
 }
 
@@ -673,7 +667,7 @@ int nfsd_nl_svc_export_get_reqs_dumpit(struct sk_buff *skb,
 
 	nn = net_generic(sock_net(skb->sk), nfsd_net_id);
 
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nn->nfsd_mutex);
 
 	cd = nn->svc_export_cache;
 	if (!cd) {
@@ -757,7 +751,7 @@ int nfsd_nl_svc_export_get_reqs_dumpit(struct sk_buff *skb,
 	kfree(seqnos);
 	kfree(items);
 out_unlock:
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nn->nfsd_mutex);
 	return ret;
 }
 
@@ -1056,7 +1050,7 @@ int nfsd_nl_svc_export_set_reqs_doit(struct sk_buff *skb,
 
 	nn = net_generic(genl_info_net(info), nfsd_net_id);
 
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nn->nfsd_mutex);
 
 	cd = nn->svc_export_cache;
 	if (!cd) {
@@ -1072,7 +1066,7 @@ int nfsd_nl_svc_export_set_reqs_doit(struct sk_buff *skb,
 	}
 
 out_unlock:
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nn->nfsd_mutex);
 	return ret;
 }
 
fs/nfsd/filecache.c +4 -1
index 17a94e6fcb15..79b9e8c92e70 100644
@@ -1011,13 +1011,16 @@ nfsd_file_cache_start_net(struct net *net)
  * nfsd_file_cache_purge - Remove all cache items associated with @net
  * @net: target net namespace
  *
+ * Takes nfsd_mutex so the cache cannot be torn down underneath the
+ * walk.  Callers must not already hold it.
  */
 void
 nfsd_file_cache_purge(struct net *net)
 {
-	lockdep_assert_held(&nfsd_mutex);
+	mutex_lock(&nfsd_mutex);
 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
 		__nfsd_file_cache_purge(net);
+	mutex_unlock(&nfsd_mutex);
 }
 
 void
fs/nfsd/netns.h +10 -0
index 374ce83e2ba0..35199c17f8d1 100644
@@ -164,6 +164,16 @@ struct nfsd_net {
 	u32 clientid_counter;
 	u32 clverifier_counter;
 
+	/*
+	 * Serializes this namespace's control plane: ->nfsd_serv and the
+	 * svc_serv members that hang off it (->sv_permsocks,
+	 * ->sv_temp_socks, thread counts), the NFSD_NET_* flags, and the
+	 * settables above that may only change while the server is down.
+	 *
+	 * Nests outside the global nfsd_mutex.
+	 */
+	struct mutex nfsd_mutex;
+
 	struct svc_info nfsd_info;
 #define nfsd_serv nfsd_info.serv
 
fs/nfsd/nfs4proc.c +2 -2
index 3a82af381a8d..7df60abfbff1 100644
@@ -1703,7 +1703,7 @@ static bool nfsd4_copy_on_sb(const struct nfsd4_copy *copy,
  * @net: net namespace containing the copy operations
  * @sb: targeted superblock
  *
- * Context: Caller must hold nfsd_mutex with NFSD_NET_UP set.  Outside
+ * Context: Caller must hold nn->nfsd_mutex with NFSD_NET_UP set.  Outside
  *          that window nn->conf_id_hashtbl is unallocated or freed,
  *          so the walk would dereference a NULL or dangling pointer.
  */
@@ -1715,7 +1715,7 @@ void nfsd4_cancel_copy_by_sb(struct net *net, struct super_block *sb)
 	unsigned int idhashval;
 	LIST_HEAD(to_cancel);
 
-	lockdep_assert_held(&nfsd_mutex);
+	lockdep_assert_held(&nn->nfsd_mutex);
 	spin_lock(&nn->client_lock);
 	for (idhashval = 0; idhashval < CLIENT_HASH_SIZE; idhashval++) {
 		struct list_head *head = &nn->conf_id_hashtbl[idhashval];
fs/nfsd/nfs4state.c +4 -4
index 1de6c6d757c3..0f9340eb281e 100644
@@ -2102,7 +2102,7 @@ static void revoke_one_stid(struct nfsd_net *nn, struct nfs4_client *clp,
  * The clients which own the states will subsequently be notified that the
  * states have been "admin-revoked".
  *
- * Context: Caller must hold nfsd_mutex with NFSD_NET_UP set.  Outside
+ * Context: Caller must hold nn->nfsd_mutex with NFSD_NET_UP set.  Outside
  *          that window nn->conf_id_hashtbl is unallocated or freed,
  *          so the walk would dereference a NULL or dangling pointer.
  */
@@ -2111,7 +2111,7 @@ void nfsd4_revoke_states(struct nfsd_net *nn, struct super_block *sb)
 	unsigned int idhashval;
 	unsigned int sc_types;
 
-	lockdep_assert_held(&nfsd_mutex);
+	lockdep_assert_held(&nn->nfsd_mutex);
 
 	sc_types = SC_TYPE_OPEN | SC_TYPE_LOCK | SC_TYPE_DELEG | SC_TYPE_LAYOUT;
 
@@ -2190,7 +2190,7 @@ static struct nfs4_stid *find_one_export_stid(struct nfs4_client *clp,
  * Userspace (exportfs -u) sends this after removing the last client
  * for a path, enabling the underlying filesystem to be unmounted.
  *
- * Context: Caller must hold nfsd_mutex with NFSD_NET_UP set.  Outside
+ * Context: Caller must hold nn->nfsd_mutex with NFSD_NET_UP set.  Outside
  *          that window nn->conf_id_hashtbl is unallocated or freed,
  *          so the walk would dereference a NULL or dangling pointer.
  */
@@ -2199,7 +2199,7 @@ void nfsd4_revoke_export_states(struct nfsd_net *nn, const struct path *path)
 	unsigned int idhashval;
 	unsigned int sc_types;
 
-	lockdep_assert_held(&nfsd_mutex);
+	lockdep_assert_held(&nn->nfsd_mutex);
 
 	sc_types = SC_TYPE_OPEN | SC_TYPE_LOCK | SC_TYPE_DELEG | SC_TYPE_LAYOUT;
 
fs/nfsd/nfsctl.c +65 -52

408 lines not on this page · raw message

fs/nfsd/nfssvc.c +84 -45

249 lines not on this page · raw message

tools/testing/selftests/nfsd/nfsd_netlink_listener.c +3 -3
index bef7e8b1ee71..1294057b6f62 100644
@@ -5,7 +5,7 @@
  *
  * Three groups:
  *   validation  - malformed/abusive LISTENER_SET requests are rejected by
- *                 nfsd_nl_validate_listeners(), before nfsd_mutex is taken.
+ *                 nfsd_nl_validate_listeners(), before nn->nfsd_mutex is taken.
  *   functional  - create/add/remove listeners and verify LISTENER_GET
  *                 reflects the set (round-trip of transport + addr:port).
  *   semantics   - once threads are running (THREADS_SET) a listener change
@@ -949,8 +949,8 @@ TEST_F(nfsd_listener, val_missing_transport)
 }
 
 /*
- * A name matching no transport class must be refused before nfsd_mutex is
- * taken, so it never reaches svc_xprt_create_from_sa() and its
+ * A name matching no transport class must be refused before nn->nfsd_mutex
+ * is taken, so it never reaches svc_xprt_create_from_sa() and its
  * request_module("svc%s", name) upcall.
  *
  * The errno cannot show that -- svc_xprt_create_from_sa() returns
Signature · 1 line
2.55.0
author maintainer
#4 lore raw

PATCH v2 4/8 nfsd: rename nfsd_mutex to nfsd_global_mutex

In reply to Jeff Layton

With nn->nfsd_mutex now carrying the per-namespace control plane, give the remaining module-wide mutex a name that says which one a call site means. Mechanical; no functional change.

Assisted-by LLM
---
 fs/nfsd/filecache.c | 14 +++++++-------
 fs/nfsd/netns.h     |  2 +-
 fs/nfsd/nfsctl.c    |  4 ++--
 fs/nfsd/nfsd.h      |  2 +-
 fs/nfsd/nfssvc.c    | 34 +++++++++++++++++-----------------
 5 files changed, 28 insertions(+), 28 deletions(-)
fs/nfsd/filecache.c +7 -7
index 79b9e8c92e70..501772bc8f8d 100644
@@ -869,7 +869,7 @@ nfsd_file_cache_init(void)
 {
 	int ret;
 
-	lockdep_assert_held(&nfsd_mutex);
+	lockdep_assert_held(&nfsd_global_mutex);
 	if (test_and_set_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
 		return 0;
 
@@ -1011,16 +1011,16 @@ nfsd_file_cache_start_net(struct net *net)
  * nfsd_file_cache_purge - Remove all cache items associated with @net
  * @net: target net namespace
  *
- * Takes nfsd_mutex so the cache cannot be torn down underneath the
+ * Takes nfsd_global_mutex so the cache cannot be torn down underneath the
  * walk.  Callers must not already hold it.
  */
 void
 nfsd_file_cache_purge(struct net *net)
 {
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
 		__nfsd_file_cache_purge(net);
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 }
 
 void
@@ -1045,7 +1045,7 @@ nfsd_file_cache_shutdown(void)
 {
 	int i;
 
-	lockdep_assert_held(&nfsd_mutex);
+	lockdep_assert_held(&nfsd_global_mutex);
 	if (test_and_clear_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 0)
 		return;
 
@@ -1477,7 +1477,7 @@ int nfsd_file_cache_stats_show(struct seq_file *m, void *v)
 	unsigned long lru = 0, total_age = 0;
 
 	/* Serialize with server shutdown */
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1) {
 		struct bucket_table *tbl;
 		struct rhashtable *ht;
@@ -1491,7 +1491,7 @@ int nfsd_file_cache_stats_show(struct seq_file *m, void *v)
 		buckets = tbl->size;
 		rcu_read_unlock();
 	}
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 
 	for_each_possible_cpu(i) {
 		hits += per_cpu(nfsd_file_cache_hits, i);
fs/nfsd/netns.h +1 -1
index 35199c17f8d1..866d5f64641f 100644
@@ -170,7 +170,7 @@ struct nfsd_net {
 	 * ->sv_temp_socks, thread counts), the NFSD_NET_* flags, and the
 	 * settables above that may only change while the server is down.
 	 *
-	 * Nests outside the global nfsd_mutex.
+	 * Nests outside nfsd_global_mutex.
 	 */
 	struct mutex nfsd_mutex;
 
fs/nfsd/nfsctl.c +2 -2
index 5ae33c21cf71..e2455a549e25 100644
@@ -1092,9 +1092,9 @@ static ssize_t write_recoverydir(struct file *file, char *buf, size_t size)
 	 * dirname itself is still shared between namespaces.
 	 */
 	mutex_lock(&nn->nfsd_mutex);
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	rv = __write_recoverydir(file, buf, size, nn);
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 	mutex_unlock(&nn->nfsd_mutex);
 	return rv;
 }
fs/nfsd/nfsd.h +1 -1
index 0864d6d564e2..d824d2c39029 100644
@@ -46,7 +46,7 @@ enum {
 
 extern struct svc_program	nfsd_programs[];
 extern const struct svc_version	nfsd_version2, nfsd_version3, nfsd_version4;
-extern struct mutex		nfsd_mutex;
+extern struct mutex		nfsd_global_mutex;
 extern atomic_t			nfsd_th_cnt;		/* number of available threads */
 
 extern const struct seq_operations nfs_exports_op;
fs/nfsd/nfssvc.c +17 -17
index 3d47e5c86bd5..5cb92c3829f9 100644
@@ -64,15 +64,15 @@ static __be32			nfsd_init_request(struct svc_rqst *,
  * that namespace's server is down (->nfsd_versions, ->nfsd4_lease,
  * ->nfsd4_grace, ->max_blksize, ...).
  *
- * The global nfsd_mutex covers only what is genuinely shared between
+ * nfsd_global_mutex covers only what is genuinely shared between
  * namespaces: the nfsd_users refcount and the host-wide resources it
  * brings up and tears down (the open file cache and the NFSv4 global
  * tables), the address-notifier registration, and user_recovery_dirname.
  *
- * Lock ordering is nn->nfsd_mutex outside the global nfsd_mutex.  Nothing
- * takes two namespaces' nfsd_mutexes.
+ * Lock ordering is nn->nfsd_mutex outside nfsd_global_mutex.  Nothing takes
+ * two namespaces' nfsd_mutexes.
  */
-DEFINE_MUTEX(nfsd_mutex);
+DEFINE_MUTEX(nfsd_global_mutex);
 
 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
 static const struct svc_version *localio_versions[] = {
@@ -272,7 +272,7 @@ static int __nfsd_startup_generic(void)
 {
 	int ret;
 
-	lockdep_assert_held(&nfsd_mutex);
+	lockdep_assert_held(&nfsd_global_mutex);
 
 	if (nfsd_users++)
 		return 0;
@@ -297,20 +297,20 @@ static int nfsd_startup_generic(void)
 {
 	int ret;
 
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	ret = __nfsd_startup_generic();
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 	return ret;
 }
 
 static void nfsd_shutdown_generic(void)
 {
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	if (!--nfsd_users) {
 		nfs4_state_shutdown();
 		nfsd_file_cache_shutdown();
 	}
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 }
 
 static bool nfsd_needs_lockd(struct nfsd_net *nn)
@@ -525,31 +525,31 @@ static struct notifier_block nfsd_inet6addr_notifier = {
 };
 #endif
 
-/* Number of namespaces with a serv, guarded by nfsd_mutex */
+/* Number of namespaces with a serv, guarded by nfsd_global_mutex */
 static int nfsd_notifier_users;
 
 static void nfsd_register_notifiers(void)
 {
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	if (!nfsd_notifier_users++) {
 		register_inetaddr_notifier(&nfsd_inetaddr_notifier);
 #if IS_ENABLED(CONFIG_IPV6)
 		register_inet6addr_notifier(&nfsd_inet6addr_notifier);
 #endif
 	}
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 }
 
 static void nfsd_unregister_notifiers(void)
 {
-	mutex_lock(&nfsd_mutex);
+	mutex_lock(&nfsd_global_mutex);
 	if (!--nfsd_notifier_users) {
 		unregister_inetaddr_notifier(&nfsd_inetaddr_notifier);
 #if IS_ENABLED(CONFIG_IPV6)
 		unregister_inet6addr_notifier(&nfsd_inet6addr_notifier);
 #endif
 	}
-	mutex_unlock(&nfsd_mutex);
+	mutex_unlock(&nfsd_global_mutex);
 }
 
 /**
@@ -690,9 +690,9 @@ int nfsd_create_serv(struct net *net, bool no_rpcbind)
 	}
 	/*
 	 * Register before publishing nn->nfsd_serv.  Namespaces are only
-	 * serialized against each other by nfsd_mutex here, so
-	 * taking the reference first is what guarantees a visible
-	 * nn->nfsd_serv never coincides with an unregistered notifier.
+	 * serialized against each other by nfsd_global_mutex here, so taking
+	 * the reference first is what guarantees a visible nn->nfsd_serv
+	 * never coincides with an unregistered notifier.
 	 */
 	nfsd_register_notifiers();
 
Signature · 1 line
2.55.0
author maintainer
#5 lore raw

PATCH v2 5/8 nfsd: give the open file cache its own mutex

In reply to Jeff Layton

nfsd_global_mutex still serializes file cache flushes against server start/stop in unrelated namespaces. nfsd_file_cache_purge() is reached from expkey_flush() on every "exportfs -f", which makes it the only frequent taker of the global lock -- and it has nothing to do with nfsd_users or the NFSv4 global tables it would be waiting on.

Move NFSD_FILE_CACHE_UP and the objects it covers (rhltable, LRU, slabs, shrinker, fsnotify groups) onto a nfsd_file_cache_mutex private to filecache.c. nfsd_file_cache_init() and nfsd_file_cache_shutdown() take it themselves rather than asserting the caller holds the global one, so nfssvc.c no longer needs to know how the cache locks itself.

nfsd_global_mutex is left holding only nfsd_users, the notifier count and user_recovery_dirname, all of which are touched solely on server start/stop.

Ordering is nn->nfsd_mutex outside nfsd_global_mutex outside nfsd_file_cache_mutex. The cache mutex is reached three ways, all consistent with that: from nfsd_startup_generic()/nfsd_shutdown_generic() under the global mutex, from nfsd_shutdown_net() under nn->nfsd_mutex, and bare from expkey_flush() and the filecache stats file. Nothing called with the cache mutex held takes either of the others.

Assisted-by LLM
---
 fs/nfsd/filecache.c | 29 ++++++++++++++++++++---------
 fs/nfsd/nfssvc.c    |  9 +++++----
 2 files changed, 25 insertions(+), 13 deletions(-)
fs/nfsd/filecache.c +20 -9
index 501772bc8f8d..42bd8c7859cf 100644
@@ -67,6 +67,17 @@
  */
 static DEFINE_SPINLOCK(nfsd_gc_lock);
 
+/*
+ * Guards NFSD_FILE_CACHE_UP and the host-wide objects it covers: the
+ * rhltable, the LRU, the slabs, the shrinker and the fsnotify groups.
+ * Held across cache bring-up and teardown, and by readers and walkers
+ * that need the cache to stay up for the duration (->cache_purge, the
+ * stats file).
+ *
+ * Nests inside nfsd_global_mutex and inside nn->nfsd_mutex.
+ */
+static DEFINE_MUTEX(nfsd_file_cache_mutex);
+
 static DEFINE_PER_CPU(unsigned long, nfsd_file_cache_hits);
 static DEFINE_PER_CPU(unsigned long, nfsd_file_acquisitions);
 static DEFINE_PER_CPU(unsigned long, nfsd_file_allocations);
@@ -869,7 +880,7 @@ nfsd_file_cache_init(void)
 {
 	int ret;
 
-	lockdep_assert_held(&nfsd_global_mutex);
+	guard(mutex)(&nfsd_file_cache_mutex);
 	if (test_and_set_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
 		return 0;
 
@@ -1011,16 +1022,16 @@ nfsd_file_cache_start_net(struct net *net)
  * nfsd_file_cache_purge - Remove all cache items associated with @net
  * @net: target net namespace
  *
- * Takes nfsd_global_mutex so the cache cannot be torn down underneath the
- * walk.  Callers must not already hold it.
+ * Takes nfsd_file_cache_mutex so the cache cannot be torn down underneath
+ * the walk.  Callers must not already hold it.
  */
 void
 nfsd_file_cache_purge(struct net *net)
 {
-	mutex_lock(&nfsd_global_mutex);
+	mutex_lock(&nfsd_file_cache_mutex);
 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1)
 		__nfsd_file_cache_purge(net);
-	mutex_unlock(&nfsd_global_mutex);
+	mutex_unlock(&nfsd_file_cache_mutex);
 }
 
 void
@@ -1045,7 +1056,7 @@ nfsd_file_cache_shutdown(void)
 {
 	int i;
 
-	lockdep_assert_held(&nfsd_global_mutex);
+	guard(mutex)(&nfsd_file_cache_mutex);
 	if (test_and_clear_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 0)
 		return;
 
@@ -1476,8 +1487,8 @@ int nfsd_file_cache_stats_show(struct seq_file *m, void *v)
 	unsigned int i, count = 0, buckets = 0;
 	unsigned long lru = 0, total_age = 0;
 
-	/* Serialize with server shutdown */
-	mutex_lock(&nfsd_global_mutex);
+	/* Serialize with cache teardown */
+	mutex_lock(&nfsd_file_cache_mutex);
 	if (test_bit(NFSD_FILE_CACHE_UP, &nfsd_file_flags) == 1) {
 		struct bucket_table *tbl;
 		struct rhashtable *ht;
@@ -1491,7 +1502,7 @@ int nfsd_file_cache_stats_show(struct seq_file *m, void *v)
 		buckets = tbl->size;
 		rcu_read_unlock();
 	}
-	mutex_unlock(&nfsd_global_mutex);
+	mutex_unlock(&nfsd_file_cache_mutex);
 
 	for_each_possible_cpu(i) {
 		hits += per_cpu(nfsd_file_cache_hits, i);
fs/nfsd/nfssvc.c +5 -4
index 5cb92c3829f9..b2c215775e08 100644
@@ -66,11 +66,12 @@ static __be32			nfsd_init_request(struct svc_rqst *,
  *
  * nfsd_global_mutex covers only what is genuinely shared between
  * namespaces: the nfsd_users refcount and the host-wide resources it
- * brings up and tears down (the open file cache and the NFSv4 global
- * tables), the address-notifier registration, and user_recovery_dirname.
+ * brings up and tears down (the NFSv4 global tables, and the open file
+ * cache -- which guards its own internals with nfsd_file_cache_mutex),
+ * the address-notifier registration, and user_recovery_dirname.
  *
- * Lock ordering is nn->nfsd_mutex outside nfsd_global_mutex.  Nothing takes
- * two namespaces' nfsd_mutexes.
+ * Lock ordering is nn->nfsd_mutex outside nfsd_global_mutex outside
+ * nfsd_file_cache_mutex.  Nothing takes two namespaces' nfsd_mutexes.
  */
 DEFINE_MUTEX(nfsd_global_mutex);
 
Signature · 1 line
2.55.0
author maintainer
#6 lore raw

PATCH v2 6/8 selftests/nfsd: factor the netlink plumbing into a shared header

In reply to Jeff Layton

nfsd_netlink_listener.c carries a small generic-netlink client -- socket setup, attribute packing, extack parsing, family resolution -- plus the LISTENER_SET/THREADS_SET/VERSION_SET wrappers. Other nfsd tests want the same thing.

Move it to nfsd_netlink.h as static inline helpers, so each test binary gets its own copy and there is nothing to link. Code is unchanged; only the three continuation lines that the static inline prefix pushed out of alignment were reflowed.

Assisted-by LLM
---
 tools/testing/selftests/nfsd/nfsd_netlink.h        | 319 +++++++++++++++++++++
 .../testing/selftests/nfsd/nfsd_netlink_listener.c | 295 +------------------
 2 files changed, 322 insertions(+), 292 deletions(-)
tools/testing/selftests/nfsd/nfsd_netlink.h new file +319 -0
new file mode 100644
index 000000000000..c66a980bfc01
@@ -0,0 +1,319 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Shared generic-netlink plumbing for the NFSD selftests.
+ *
+ * Header-only: every helper is static inline, so each test binary gets its
+ * own copy and there is nothing extra to link. nfsd_family must be set by
+ * calling genl_resolve_nfsd() before any of the request helpers are used.
+ */
+#ifndef __SELFTESTS_NFSD_NETLINK_H__
+#define __SELFTESTS_NFSD_NETLINK_H__
+
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <linux/netlink.h>
+#include <linux/genetlink.h>
+#include <linux/nfsd_netlink.h>
+
+#define NLA_ALIGN4(len)			(((len) + 3) & ~3)
+#define RECV_TIMEO_SEC			30
+
+static int nfsd_family = -1;		/* set per-test in FIXTURE_SETUP */
+
+/* Extack message from the last genl_request(); empty if there was none. */
+static char last_extack[128];
+
+static inline void die(const char *msg)
+{
+	perror(msg);
+	exit(1);
+}
+
+/* ------------------- minimal generic-netlink plumbing ------------------- */
+
+static inline int genl_open(void)
+{
+	struct sockaddr_nl sa = { .nl_family = AF_NETLINK };
+	struct timeval tv = { .tv_sec = RECV_TIMEO_SEC };
+	int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
+	int on = 1;
+
+	if (fd < 0)
+		die("socket(NETLINK_GENERIC)");
+	if (bind(fd, (void *)&sa, sizeof(sa)) < 0)
+		die("bind(netlink)");
+	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	/*
+	 * Ask for extack, and cap the ack so the request is not echoed back:
+	 * the TLVs then always follow the fixed part of the error message.
+	 */
+	setsockopt(fd, SOL_NETLINK, NETLINK_EXT_ACK, &on, sizeof(on));
+	setsockopt(fd, SOL_NETLINK, NETLINK_CAP_ACK, &on, sizeof(on));
+	return fd;
+}
+
+/* Stash the extack message of an ack, if it carries one. */
+static inline void parse_extack(const char *rbuf)
+{
+	const struct nlmsghdr *nlh = (const void *)rbuf;
+	const struct nlattr *na;
+	int off, left;
+
+	last_extack[0] = '\0';
+	if (nlh->nlmsg_type != NLMSG_ERROR ||
+	    !(nlh->nlmsg_flags & NLM_F_ACK_TLVS))
+		return;
+
+	off = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(struct nlmsgerr));
+	left = nlh->nlmsg_len - off;
+	na = (const void *)(rbuf + off);
+
+	while (left >= (int)NLA_HDRLEN) {
+		if ((na->nla_type & NLA_TYPE_MASK) == NLMSGERR_ATTR_MSG) {
+			strncpy(last_extack, (const char *)na + NLA_HDRLEN,
+				sizeof(last_extack) - 1);
+			last_extack[sizeof(last_extack) - 1] = '\0';
+			return;
+		}
+		left -= NLA_ALIGN4(na->nla_len);
+		na = (const void *)((const char *)na + NLA_ALIGN4(na->nla_len));
+	}
+}
+
+/* Append an attribute at @off; return the new (aligned) offset. */
+static inline int put_attr(char *buf, int off, uint16_t type,
+			   const void *data, int len)
+{
+	struct nlattr *na = (void *)(buf + off);
+
+	na->nla_type = type;
+	na->nla_len = NLA_HDRLEN + len;
+	if (len)
+		memcpy(buf + off + NLA_HDRLEN, data, len);
+	return off + NLA_ALIGN4(NLA_HDRLEN + len);
+}
+
+/* Build a genl message header into @buf; return the offset past it. */
+static inline int genl_hdr(char *buf, uint16_t type, uint16_t flags, uint8_t cmd)
+{
+	struct nlmsghdr *nlh = (void *)buf;
+	struct genlmsghdr *gnl = (void *)(buf + NLMSG_HDRLEN);
+
+	memset(buf, 0, NLMSG_HDRLEN + GENL_HDRLEN);
+	nlh->nlmsg_type = type;
+	nlh->nlmsg_flags = flags;
+	nlh->nlmsg_seq = 1;
+	gnl->cmd = cmd;
+	gnl->version = 1;
+	return NLMSG_HDRLEN + GENL_HDRLEN;
+}
+
+/* Send an nfsd command with an ACK; return the ACK errno (<= 0). */
+static inline int genl_request(uint8_t cmd, const char *attrs, int attrs_len)
+{
+	char buf[1 << 20], rbuf[4096];
+	struct nlmsghdr *nlh = (void *)buf;
+	int fd = genl_open();
+	int off, n, ret;
+
+	off = genl_hdr(buf, nfsd_family, NLM_F_REQUEST | NLM_F_ACK, cmd);
+	if (attrs_len) {
+		memcpy(buf + off, attrs, attrs_len);
+		off += attrs_len;
+	}
+	nlh->nlmsg_len = off;
+
+	if (send(fd, buf, off, 0) < 0)
+		die("send(genl)");
+
+	last_extack[0] = '\0';
+	n = recv(fd, rbuf, sizeof(rbuf), 0);
+	if (n < 0) {
+		ret = (errno == EAGAIN || errno == EWOULDBLOCK) ? -ETIMEDOUT : -errno;
+	} else if (((struct nlmsghdr *)rbuf)->nlmsg_type == NLMSG_ERROR) {
+		ret = ((struct nlmsgerr *)NLMSG_DATA(rbuf))->error;
+		parse_extack(rbuf);
+	} else {
+		ret = 0;
+	}
+	close(fd);
+	return ret;
+}
+
+/*
+ * Send a command with attributes and return the full reply message; -errno
+ * on failure. NLM_F_ACK is left off: the kernel reports an error either way,
+ * so the first message back is the reply whenever there is one.
+ */
+static inline int genl_request_reply_attrs(uint8_t cmd, const char *attrs,
+					   int attrs_len, char *rbuf,
+					   size_t rlen)
+{
+	char buf[1 << 20];
+	struct nlmsghdr *nlh = (void *)buf;
+	int fd = genl_open();
+	int off, n, ret;
+
+	off = genl_hdr(buf, nfsd_family, NLM_F_REQUEST, cmd);
+	if (attrs_len) {
+		memcpy(buf + off, attrs, attrs_len);
+		off += attrs_len;
+	}
+	nlh->nlmsg_len = off;
+
+	if (send(fd, buf, off, 0) < 0)
+		die("send(genl reply)");
+
+	n = recv(fd, rbuf, rlen, 0);
+	if (n < 0)
+		ret = (errno == EAGAIN || errno == EWOULDBLOCK) ? -ETIMEDOUT : -errno;
+	else if (((struct nlmsghdr *)rbuf)->nlmsg_type == NLMSG_ERROR)
+		ret = ((struct nlmsgerr *)NLMSG_DATA(rbuf))->error;
+	else
+		ret = n;
+	close(fd);
+	return ret;
+}
+
+static inline int genl_request_reply(uint8_t cmd, char *rbuf, size_t rlen)
+{
+	return genl_request_reply_attrs(cmd, NULL, 0, rbuf, rlen);
+}
+
+/* Resolve the "nfsd" genl family id; -1 if not registered. */
+static inline int genl_resolve_nfsd(void)
+{
+	char buf[1024], rbuf[4096];
+	struct nlmsghdr *nlh = (void *)buf;
+	struct nlmsghdr *rh = (void *)rbuf;
+	struct nlattr *na;
+	int fd, off, left, id = -1;
+
+	fd = genl_open();
+	off = genl_hdr(buf, GENL_ID_CTRL, NLM_F_REQUEST, CTRL_CMD_GETFAMILY);
+	off = put_attr(buf, off, CTRL_ATTR_FAMILY_NAME,
+		       NFSD_FAMILY_NAME, sizeof(NFSD_FAMILY_NAME));
+	nlh->nlmsg_len = off;
+
+	if (send(fd, buf, off, 0) < 0)
+		die("send(GETFAMILY)");
+	if (recv(fd, rbuf, sizeof(rbuf), 0) < 0)
+		die("recv(GETFAMILY)");
+	close(fd);
+
+	if (rh->nlmsg_type == NLMSG_ERROR)
+		return -1;
+
+	na = (void *)((char *)NLMSG_DATA(rh) + GENL_HDRLEN);
+	left = rh->nlmsg_len - NLMSG_HDRLEN - GENL_HDRLEN;
+	while (left >= (int)NLA_HDRLEN) {
+		if (na->nla_type == CTRL_ATTR_FAMILY_ID) {
+			id = *(uint16_t *)((char *)na + NLA_HDRLEN);
+			break;
+		}
+		left -= NLA_ALIGN4(na->nla_len);
+		na = (void *)((char *)na + NLA_ALIGN4(na->nla_len));
+	}
+	return id;
+}
+
+/* ------------------- listener request builders ------------------- */
+
+/* Fine-grained control for negative tests: any field can be omitted/malformed. */
+struct raw_listener {
+	const char *xprt;	/* NULL -> omit NFSD_A_SOCK_TRANSPORT_NAME */
+	int emit_addr;		/* 0 -> omit NFSD_A_SOCK_ADDR */
+	const void *addr;
+	int addr_len;		/* bytes to emit for NFSD_A_SOCK_ADDR */
+};
+
+static inline int put_raw_listener(char *buf, int off, const struct raw_listener *r)
+{
+	struct nlattr *nest = (void *)(buf + off);
+	int inner = off + NLA_HDRLEN;
+
+	if (r->emit_addr)
+		inner = put_attr(buf, inner, NFSD_A_SOCK_ADDR, r->addr, r->addr_len);
+	if (r->xprt)
+		inner = put_attr(buf, inner, NFSD_A_SOCK_TRANSPORT_NAME,
+				 r->xprt, strlen(r->xprt) + 1);
+	nest->nla_type = NFSD_A_SERVER_SOCK_ADDR | NLA_F_NESTED;
+	nest->nla_len = inner - off;
+	return off + NLA_ALIGN4(nest->nla_len);
+}
+
+/* Well-formed loopback listener for @family (AF_INET or AF_INET6). */
+static inline int put_listener_af(char *buf, int off, const char *xprt,
+				  int family, uint16_t port)
+{
+	struct sockaddr_storage ss = {0};
+	struct raw_listener r = { .xprt = xprt, .emit_addr = 1, .addr = &ss };
+
+	if (family == AF_INET6) {
+		struct sockaddr_in6 *s6 = (void *)&ss;
+
+		s6->sin6_family = AF_INET6;
+		s6->sin6_port = htons(port);
+		s6->sin6_addr = in6addr_loopback;
+		r.addr_len = sizeof(*s6);
+	} else {
+		struct sockaddr_in *s4 = (void *)&ss;
+
+		s4->sin_family = AF_INET;
+		s4->sin_port = htons(port);
+		s4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+		r.addr_len = sizeof(*s4);
+	}
+	return put_raw_listener(buf, off, &r);
+}
+
+static inline int put_listener(char *buf, int off, const char *xprt, uint16_t port)
+{
+	return put_listener_af(buf, off, xprt, AF_INET, port);
+}
+
+static inline int listener_set(const char *attrs, int len)
+{
+	return genl_request(NFSD_CMD_LISTENER_SET, attrs, len);
+}
+
+/*
+ * Enable exactly one NFS version in this netns. NFSD_CMD_VERSION_SET clears
+ * every version first, so one nest is enough to leave the server v4-only.
+ * It refuses once a serv exists, so call it before any listener.
+ */
+static inline int version_set_only(uint32_t major, uint32_t minor)
+{
+	char attrs[64];
+	struct nlattr *nest = (void *)attrs;
+	int inner = NLA_HDRLEN;
+
+	inner = put_attr(attrs, inner, NFSD_A_VERSION_MAJOR,
+			 &major, sizeof(major));
+	inner = put_attr(attrs, inner, NFSD_A_VERSION_MINOR,
+			 &minor, sizeof(minor));
+	inner = put_attr(attrs, inner, NFSD_A_VERSION_ENABLED, NULL, 0);
+	nest->nla_type = NFSD_A_SERVER_PROTO_VERSION | NLA_F_NESTED;
+	nest->nla_len = inner;
+
+	return genl_request(NFSD_CMD_VERSION_SET, attrs, NLA_ALIGN4(inner));
+}
+
+/* Start (@n > 0) or stop (@n == 0) nfsd threads in this netns. */
+static inline int threads_set(int n)
+{
+	char attrs[64];
+	uint32_t v = n;
+	int off = put_attr(attrs, 0, NFSD_A_SERVER_THREADS, &v, sizeof(v));
+
+	return genl_request(NFSD_CMD_THREADS_SET, attrs, off);
+}
+
+#endif /* __SELFTESTS_NFSD_NETLINK_H__ */
tools/testing/selftests/nfsd/nfsd_netlink_listener.c +3 -292

317 lines not on this page · raw message

Signature · 1 line
2.55.0
author maintainer
#7 lore raw

PATCH v2 7/8 selftests/nfsd: add cross-namespace isolation tests

In reply to Jeff Layton

Check that one namespace's NFSD settings and running server stay out of another's, now that the control plane is serialized per namespace.

max_blksize_is_per_netns
max_block_size is reachable only through a per-netns nfsd filesystem but used to live in a module-wide variable. Read it in a throwaway namespace, change it in a second, read it again in a third; the two reads must agree. No value is hardcoded -- the default is derived from the size of memory, so the test picks a target that differs from whatever this machine reports.

*_busy_is_per_netns, pool_stats_readable_with_foreign_server, listener_get_does_not_show_foreign_listeners
max_block_size, VERSION_SET and nfsv4leasetime all refuse with -EBUSY once that namespace has a serv. A peer namespace holds a server up while the test pokes its own, which must not be affected. LISTENER_GET must not report the peer's listener.

expkey_flush_with_foreign_server
writing /proc/net/rpc/nfsd.fh/flush is the one userspace path that reaches nfsd_file_cache_purge(), and so the one that takes the file cache lock with nothing else held.

Servers are created with NFSD_A_SERVER_SOCK_USERSPACE_RPCBIND so nothing calls out to rpcbind, and restricted to NFSv4.1 so nfsd_needs_lockd() stays false. Each namespace mounts its own nfsd filesystem on a private tmpfs; the module creates /proc/fs/nfs, not /proc/fs/nfsd, so there is no mountpoint to borrow.

Assisted-by LLM
---
 tools/testing/selftests/nfsd/.gitignore            |   1 +
 tools/testing/selftests/nfsd/Makefile              |   1 +
 .../testing/selftests/nfsd/nfsd_netns_isolation.c  | 468 +++++++++++++++++++++
 tools/testing/selftests/nfsd/settings              |   2 +-
 4 files changed, 471 insertions(+), 1 deletion(-)
tools/testing/selftests/nfsd/.gitignore +1 -0
index 19e6dec04d8e..0304b80eb844 100644
@@ -1 +1,2 @@
 nfsd_netlink_listener
+nfsd_netns_isolation
tools/testing/selftests/nfsd/Makefile +1 -0
index 15ac65549d25..2b7c44c3fb00 100644
@@ -2,5 +2,6 @@
 CFLAGS += $(KHDR_INCLUDES) -Wall
 
 TEST_GEN_PROGS := nfsd_netlink_listener
+TEST_GEN_PROGS += nfsd_netns_isolation
 
 include ../lib.mk
tools/testing/selftests/nfsd/nfsd_netns_isolation.c new file +468 -0

468 lines not on this page · raw message

tools/testing/selftests/nfsd/settings +1 -1
index 6091b45d226b..694d70710ff0 100644
@@ -1 +1 @@
-timeout=120
+timeout=300
Signature · 1 line
2.55.0
author maintainer
#8 lore raw

PATCH v2 8/8 selftests/nfsd: add a cross-namespace control-plane soak

In reply to Jeff Layton

Drive the NFSD control plane from many namespaces at once, to exercise every edge of the lock nesting:

	nn->nfsd_mutex -> nfsd_global_mutex -> nfsd_file_cache_mutex

Each worker owns a namespace and churns between "no serv" and "serv with threads", mixing in the operations that cross into the host-wide locks:

start/stop a server nn -> global (nfsd_users 0->1->0, notifiers)

			   -> cache (cache init/shutdown)
  empty LISTENER_SET	creates and destroys a serv in one call, so the
			   host-wide refcount goes 0->1->0 on its own

nfsd.fh/flush the cache lock with nothing else held
read filecache likewise
read pool_stats nn, reached through svc_info.mutex

Random churn alone is a weak race finder, so the run ends with synchronized rounds where every namespace attempts the host-wide 0->1 transition at the same instant. That window only opened up once the per-namespace lock stopped serializing namespaces against each other.

The test asserts little by itself; the result that matters is that the kernel did not warn. The taint word is sampled before and after and a newly set TAINT_WARN fails the run, which catches lockdep splats, WARN_ON()s and refcount saturation alike. Add PROVE_LOCKING and friends to the config, and log a note if lockdep looks absent.

Two things can silently gut the coverage, so both are reported rather than left to look like a pass:

- without lockdep there is very little for the kernel to complain

    about;

- a server already running outside these namespaces pins the host-wide refcount above zero for the whole run, so the 0->1 transition the synchronized rounds are built around never happens.

Each worker leaves only NFSv4.1 enabled. A fresh namespace has v3 on, which makes nfsd_needs_lockd() true, and the lockd that comes up then waits out an RPC timeout against an rpcbind that is not there on every single server start.

Every namespace binds the same port; they are isolated, so that must work, and a bind failure is a louder signal than a silent pass. Sized from nproc, capped at 8 namespaces and 5s of churn by default, and tunable with NFSD_STRESS_WORKERS and NFSD_STRESS_SECS. The barrier waits with a deadline so a worker that dies cannot wedge the run, and the test carries an explicit timeout because the harness otherwise caps it at TEST_TIMEOUT_DEFAULT.

Assisted-by LLM
---
 tools/testing/selftests/nfsd/.gitignore          |   1 +
 tools/testing/selftests/nfsd/Makefile            |   1 +
 tools/testing/selftests/nfsd/config              |   6 +
 tools/testing/selftests/nfsd/nfsd_netns_stress.c | 572 +++++++++++++++++++++++
 tools/testing/selftests/nfsd/settings            |   2 +-
 5 files changed, 581 insertions(+), 1 deletion(-)
tools/testing/selftests/nfsd/.gitignore +1 -0
index 0304b80eb844..2347491c634d 100644
@@ -1,2 +1,3 @@
 nfsd_netlink_listener
 nfsd_netns_isolation
+nfsd_netns_stress
tools/testing/selftests/nfsd/Makefile +1 -0
index 2b7c44c3fb00..b29bf642c0ad 100644
@@ -3,5 +3,6 @@ CFLAGS += $(KHDR_INCLUDES) -Wall
 
 TEST_GEN_PROGS := nfsd_netlink_listener
 TEST_GEN_PROGS += nfsd_netns_isolation
+TEST_GEN_PROGS += nfsd_netns_stress
 
 include ../lib.mk
tools/testing/selftests/nfsd/config +6 -0
index 0eef03af3503..c6407806b58b 100644
@@ -12,3 +12,9 @@ CONFIG_INOTIFY_USER=y
 CONFIG_SUNRPC=y
 CONFIG_NFSD=y
 CONFIG_NFSD_V4=y
+
+# nfsd_netns_stress leans on lockdep to find anything; without these the
+# soak still runs but proves very little.
+CONFIG_PROVE_LOCKING=y
+CONFIG_DEBUG_MUTEXES=y
+CONFIG_DEBUG_ATOMIC_SLEEP=y
tools/testing/selftests/nfsd/nfsd_netns_stress.c new file +572 -0

572 lines not on this page · raw message

tools/testing/selftests/nfsd/settings +1 -1
index 694d70710ff0..a62d2fa1275c 100644
@@ -1 +1 @@
-timeout=300
+timeout=600
Signature · 1 line
2.55.0
maintainer
#9 lore raw
In reply to Jeff Layton
Quoted 11 lines · Jeff Layton

Currently much of nfsd's administration is serialized under the global nfsd_mutex, even though most of the objects managed under it are segregated by net namespace.

This patchset does a couple of small cleanups and then adds a new per-net mutex and moves all of the appropriate per-net data structures to be protected by it instead of the global mutex. The filecache is given its own mutex, and the global mutex is renamed and left for managing just the few remaning global objects.

[...]

Applied to nfsd-testing, thanks!

[1/8] nfsd: clear NFSD_NET_UP before dropping the generic resource reference

      commit: 77881893d52fc4ac737bd55727eca54cb95d6002
[2/8] nfsd: make max_blksize a per-namespace setting
      commit: 4a29b69535eb2778255634b795ad9c026269a95f
[3/8] nfsd: move the control plane to a per-namespace mutex
      commit: 88815584b68611c3eeb6f536b8dc1f4a2274c129
[4/8] nfsd: rename nfsd_mutex to nfsd_global_mutex
      commit: 828e48566b8145969f93df212628349e4d2849d0
[5/8] nfsd: give the open file cache its own mutex
      commit: 4ad8170fd7287fbf7adc493c785a284fe213065f
[6/8] selftests/nfsd: factor the netlink plumbing into a shared header
      commit: e99f6a7157acd18cda500c2bcbb17761ecfede3f
[7/8] selftests/nfsd: add cross-namespace isolation tests
      commit: 20801469b68a678a06b51592a1f90cb018983cf9
[8/8] selftests/nfsd: add a cross-namespace control-plane soak
      commit: a55e35036b7e984e601264565c767a23582c2175

--
Chuck Lever